diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad102abef05182993c6a79542ea9f89682833705 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/__pycache__/cli.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/__pycache__/cli.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f7df4cf45499bb8c0bf0aecbbeac6286aea5bde Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/__pycache__/cli.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/__pycache__/logger.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/__pycache__/logger.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..189f9ff1d785c29716142994dd2bf9f95e7181e2 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/__pycache__/logger.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/__pycache__/version.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/__pycache__/version.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30d76a7f551241a90026181bf57bc3e7ac90e485 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/__pycache__/version.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..54bfde1582725f36cdb632c8c19b130fc67390f3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__init__.py @@ -0,0 +1,8 @@ +from .cli_init import cli_init +from .cli_env import cli_env + + +__all__ = [ + "cli_env", + "cli_init" + ] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d2f68679fd49ba02d3f0ddd07094f563844cd76 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_env.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_env.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c822a7eb8d42790d5b2b5c7de173a910d70b4338 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_env.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_eval.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_eval.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a69cdad92a45f091ccffe761e81ae4519c6a82a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_eval.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_init.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_init.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c494276867101375facfe525420f178172dc41e Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_init.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_pdf.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_pdf.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ca071e589ad612a516c2e77a3efefb607c74d6d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_pdf.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_text.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_text.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2fa775da0e2b7e2dc1da3d80dab59e47520faa3a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_text.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_webui.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_webui.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57ff330444c659b129055289e7062ee582d86778 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_webui.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/copy_funcs.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/copy_funcs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06d9b72a48c6d3fe7df586afae51306b8ed5a7a3 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/copy_funcs.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/paths.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/paths.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ce6892c45eec7cdb7b6e21eb0dcaa197b860ba6 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/paths.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96e18b1b80c4cbc90c8cd92179c93b4048f03ec7 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/utils.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_env.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_env.py new file mode 100644 index 0000000000000000000000000000000000000000..8f08afef2c5ad44f9320ffa01a0a821d19ad36e6 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_env.py @@ -0,0 +1,86 @@ +import os +import torch +import platform +from colorama import init, Fore, Style +from dataflow import __version__ +import importlib.metadata +from .paths import DataFlowPath + + +def is_torch_cuda_available(): + """ + Check if CUDA is available for PyTorch. + """ + return torch.cuda.is_available() + +def get_env_info(): + info = { + "`Dataflow` version": __version__, + "`Dataflow` install path": DataFlowPath.get_dataflow_dir(), + "Platform": platform.platform(), + "Python version": platform.python_version(), + "PyTorch version": torch.__version__, + "Torchvision version": torch.__version__, + } + if is_torch_cuda_available(): + info["PyTorch version"] += " (GPU)" + info["GPU type"] = torch.cuda.get_device_name() + info["GPU number"] = torch.cuda.device_count() + info["GPU memory"] = f"{torch.cuda.mem_get_info()[1] / (1024**3):.2f}GB" + + + try: + import deepspeed # type: ignore + + info["DeepSpeed version"] = deepspeed.__version__ + except Exception: + pass + + try: + import bitsandbytes # type: ignore + + info["Bitsandbytes version"] = bitsandbytes.__version__ + except Exception: + pass + + try: + import vllm + + info["vLLM version"] = vllm.__version__ + except Exception: + pass + + try: + import sglang + info["SGLang version"] = sglang.__version__ + except Exception: + pass + + try: + mineru_version = importlib.metadata.version("mineru") + info["MinerU version"] = mineru_version + except Exception: + pass + + try: + import subprocess + # get the dir of imdlbenco package + imdlbenco_dir = os.path.dirname(os.path.abspath(__file__)) + # move to this dir and get the git commit hash in a subprocess + # but don't change the current working directory + os.chdir(imdlbenco_dir) + commit_info = subprocess.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True, check=True) + commit_hash = commit_info.stdout.strip() + info["Git commit"] = commit_hash + except Exception: + pass + + print(Fore.BLUE + "=" * os.get_terminal_size().columns + Style.RESET_ALL) + print("\n" + "\n".join([f"- {key}: {value}" for key, value in info.items()]) + "\n") + print(Fore.BLUE + "=" * os.get_terminal_size().columns + Style.RESET_ALL) + +def cli_env(): + get_env_info() + +if __name__ == "__main__": + print(get_env_info()) \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_eval.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..a6e2c523882f01630a8e7d3ae2316743fb763513 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_eval.py @@ -0,0 +1,467 @@ +# dataflow/cli_funcs/cli_eval.py +"""DataFlow 评估工具""" + +import os +import json +import shutil +import importlib.util +from pathlib import Path +from typing import List, Dict, Any +from datetime import datetime +from dataflow import get_logger +from dataflow.serving import LocalModelLLMServing_vllm +from dataflow.operators.reasoning import ReasoningAnswerGenerator +from dataflow.prompts.reasoning.diy import DiyAnswerGeneratorPrompt +from dataflow.utils.storage import FileStorage +import torch +import gc + +logger = get_logger() + +DEFAULT_ANSWER_PROMPT = """Please answer the following question based on the provided academic literature. Your response should: +1. Provide accurate information from the source material +2. Include relevant scientific reasoning and methodology +3. Reference specific findings, data, or conclusions when applicable +4. Maintain academic rigor and precision in your explanation + +Question: {question} + +Answer:""" + + +class EvaluationPipeline: + """评估管道""" + + def __init__(self, config: Dict[str, Any]): + self.config = config + self.prepared_models = [] + self.generated_files = [] + + def run(self) -> bool: + try: + # 1. 获取目标模型 + self.target_models = self._get_target_models() + if not self.target_models: + logger.error("No TARGET_MODELS found in config") + return False + + self.prepared_models = self._prepare_models() + if not self.prepared_models: + return False + + # 2. 生成答案 + self.generated_files = self._generate_answers() + if not self.generated_files: + return False + + # 3. 执行评估 + results = self._run_evaluation() + + # 4. 生成报告 + self._generate_report(results) + + return True + + except Exception as e: + logger.error(f"Evaluation failed: {e}") + import traceback + traceback.print_exc() + return False + + def _get_target_models(self) -> List: + """获取目标模型列表""" + target_config = self.config.get("TARGET_MODELS", []) + + if not isinstance(target_config, list): + logger.error(f"TARGET_MODELS must be a list, got {type(target_config)}") + return [] + + if not target_config: + logger.error("TARGET_MODELS is empty") + return [] + + return target_config + + def _prepare_models(self) -> List[Dict]: + """准备模型信息""" + prepared = [] + default_config = self.config.get("DEFAULT_MODEL_CONFIG", {}) + + for idx, item in enumerate(self.target_models, 1): + if isinstance(item, str): + model_info = { + "name": Path(item).name, + "path": item, + "type": "local", + **default_config + } + elif isinstance(item, dict): + if "path" not in item: + logger.error(f"Model at index {idx} missing 'path'") + continue + + model_info = { + **default_config, + **item, + "name": item.get("name", Path(item["path"]).name), + "type": "local" + } + else: + logger.error(f"Invalid model format at index {idx}") + continue + + prepared.append(model_info) + + return prepared + + def _clear_vllm_cache(self): + """清理 vLLM 缓存""" + cache_paths = [ + Path.home() / ".cache" / "vllm" / "torch_compile_cache", + Path.home() / ".cache" / "vllm" + ] + + for cache_path in cache_paths: + if cache_path.exists(): + try: + shutil.rmtree(cache_path) + except Exception as e: + logger.warning(f"Failed to clear cache: {e}") + + def _generate_answers(self) -> List[Dict]: + """生成模型答案 - 每个模型只加载一次""" + generated_files = [] + bench_config_list = self.config.get("BENCH_CONFIG", []) + + if not bench_config_list: + logger.error("No BENCH_CONFIG found") + return [] + + # 外层循环:遍历模型 + for idx, model_info in enumerate(self.prepared_models, 1): + llm_serving = None + + try: + logger.info(f"[{idx}/{len(self.prepared_models)}] Loading model: {model_info['name']}") + + # 清理缓存(每个模型加载前清理一次) + self._clear_vllm_cache() + + # 加载模型 + llm_serving = LocalModelLLMServing_vllm( + hf_model_name_or_path=model_info['path'], + vllm_tensor_parallel_size=model_info.get('vllm_tensor_parallel_size', 2), + vllm_temperature=model_info.get('vllm_temperature', 0.7), + vllm_top_p=model_info.get('vllm_top_p', 0.9), + vllm_max_tokens=model_info.get('vllm_max_tokens', 1024), + vllm_repetition_penalty=model_info.get('vllm_repetition_penalty', 1.0), + vllm_seed=model_info.get('vllm_seed', None), + vllm_gpu_memory_utilization=model_info.get('vllm_gpu_memory_utilization', 0.8) + ) + + # 内层循环:遍历bench(复用模型) + for bench_idx, bench_config in enumerate(bench_config_list, 1): + answer_generator = None + storage = None + + try: + bench_name = bench_config.get("name", "default") + logger.info(f" [{bench_idx}/{len(bench_config_list)}] Processing bench: {bench_name}") + + input_file = bench_config["input_file"] + if not Path(input_file).exists(): + logger.error(f"Input file not found: {input_file}") + continue + + question_key = bench_config.get("question_key", "input") + bench_output_dir = bench_config.get("output_dir", "./eval_results") + + # 设置缓存和输出目录 + cache_dir = model_info.get('cache_dir', './.cache/eval') + Path(cache_dir).mkdir(parents=True, exist_ok=True) + Path(bench_output_dir).mkdir(parents=True, exist_ok=True) + + output_file = f"{bench_output_dir}/{bench_name}_answers_{model_info['name']}.json" + + # 答案生成器(复用llm_serving) + custom_prompt = model_info.get('answer_prompt', DEFAULT_ANSWER_PROMPT) + answer_generator = ReasoningAnswerGenerator( + llm_serving=llm_serving, + prompt_template=DiyAnswerGeneratorPrompt(custom_prompt) + ) + + # 存储 + cache_path = f"{cache_dir}/{bench_name}_{model_info['name']}_generation" + storage = FileStorage( + first_entry_file_name=input_file, + cache_path=cache_path, + file_name_prefix=model_info.get('file_prefix', 'answer_gen'), + cache_type=model_info.get('cache_type', 'json') + ) + + # 运行生成 + answer_generator.run( + storage=storage.step(), + input_key=question_key, + output_key=model_info.get('output_key', 'model_generated_answer') + ) + + # 保存结果 + file_prefix = model_info.get('file_prefix', 'answer_gen') + cache_type = model_info.get('cache_type', 'json') + pattern = f"{file_prefix}_step*.{cache_type}" + matching_files = sorted(Path(cache_path).glob(pattern)) + + if matching_files: + gen_file = matching_files[-1] + shutil.copy2(gen_file, output_file) + generated_files.append({ + "model_name": model_info['name'], + "model_path": model_info['path'], + "file_path": output_file, + "bench_name": bench_name + }) + logger.success(f" ✓ Generated answers for {bench_name}") + else: + logger.error(f"No generated file found in {cache_path}") + continue + + except Exception as e: + logger.error(f"Failed to process bench {bench_name}: {e}") + import traceback + traceback.print_exc() + continue + + finally: + # 清理bench级别的资源 + if answer_generator is not None: + del answer_generator + if storage is not None: + del storage + gc.collect() + + except Exception as e: + logger.error(f"Failed to load model {model_info['name']}: {e}") + import traceback + traceback.print_exc() + continue + + finally: + # 清理模型级别的资源 + if llm_serving is not None: + logger.info(f"Unloading model: {model_info['name']}") + del llm_serving + gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + torch.cuda.synchronize() + + return generated_files + + def _run_evaluation(self) -> List[Dict]: + """运行评估""" + try: + logger.info("Loading judge model...") + judge_serving = self.config["create_judge_serving"]() + logger.info("✓ Judge model loaded") + except Exception as e: + logger.error(f"Failed to create judge: {e}") + return [] + + results = [] + eval_config = self.config.get("EVALUATOR_RUN_CONFIG", {}) + + total_evals = len(self.generated_files) + + for eval_idx, file_info in enumerate(self.generated_files, 1): + try: + bench_name = file_info.get('bench_name', 'unknown') + model_name = file_info['model_name'] + + logger.info(f"\n[Eval {eval_idx}/{total_evals}] {model_name} × {bench_name}") + + # 找到对应的bench配置 + bench_config = None + for bc in self.config.get("BENCH_CONFIG", []): + if bc.get("name") == bench_name: + bench_config = bc + break + + if not bench_config: + logger.warning(f" ⚠️ No bench config found") + continue + + eval_output_dir = bench_config.get("eval_output_dir", "./eval_results") + + # 执行评估 + logger.info(f" 📊 Evaluating...") + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + result_file = f"{eval_output_dir}/{timestamp}_{model_name}/result.json" + Path(result_file).parent.mkdir(parents=True, exist_ok=True) + + storage = self.config["create_storage"]( + file_info["file_path"], + f"./.cache/eval/{model_name}", + bench_name + ) + evaluator = self.config["create_evaluator"](judge_serving, result_file) + + evaluator.run( + storage=storage.step(), + input_test_answer_key=eval_config.get("input_test_answer_key", "model_generated_answer"), + input_gt_answer_key=eval_config.get("input_gt_answer_key", "output"), + input_question_key=eval_config.get("input_question_key", "input") + ) + + if Path(result_file).exists(): + with open(result_file, 'r') as f: + data = json.load(f) + if data: + result_data = data[0].copy() + result_data["model_name"] = model_name + result_data["bench_name"] = bench_name + results.append(result_data) + logger.info(f" ✓ Accuracy: {result_data.get('accuracy', 0):.3f}") + + except Exception as e: + logger.error(f" ✗ Evaluation failed: {e}") + import traceback + traceback.print_exc() + continue + + logger.info(f"\n✓ Evaluation complete: {len(results)} results") + return results + + def _generate_report(self, results: List[Dict]): + """生成报告 - 支持批量bench独立输出""" + if not results: + logger.warning("No results") + return + + # 打印报告 + print("\n" + "="*80) + print("EVALUATION RESULTS - ALL BENCHES & MODELS") + print("="*80) + + # 按准确率排序 + sorted_results = sorted(results, key=lambda x: x.get("accuracy", 0), reverse=True) + + for i, r in enumerate(sorted_results, 1): + print(f"{i}. [{r.get('bench_name', 'unknown')}] {r['model_name']}") + print(f" Accuracy: {r.get('accuracy', 0):.3f}") + print(f" Total: {r.get('total_samples', 0)}") + print(f" Matched: {r.get('matched_samples', 0)}") + print() + + # 按bench分组保存结果 + bench_config_list = self.config.get("BENCH_CONFIG", []) + + # 为每个bench单独保存结果 + bench_groups = {} + for result in sorted_results: + bench_name = result.get('bench_name', 'unknown') + if bench_name not in bench_groups: + bench_groups[bench_name] = [] + bench_groups[bench_name].append(result) + + # 保存每个bench的结果到各自的output_dir + for bench_name, bench_results in bench_groups.items(): + # 找到对应bench的配置 + bench_output_dir = "./eval_results" # 默认值 + for bench_config in bench_config_list: + if bench_config.get("name") == bench_name: + bench_output_dir = bench_config.get("output_dir", "./eval_results") + break + + # 保存该bench的结果 + report_file = f"{bench_output_dir}/results.json" + Path(report_file).parent.mkdir(parents=True, exist_ok=True) + + report_data = { + "bench_name": bench_name, + "timestamp": datetime.now().isoformat(), + "total_evaluations": len(bench_results), + "results": bench_results + } + + with open(report_file, 'w', encoding='utf-8') as f: + json.dump(report_data, f, ensure_ascii=False, indent=2) + + print(f"Bench '{bench_name}' results saved to: {report_file}") + + # 另外保存一个汇总文件(包含所有bench) + all_results_file = "./eval_results/all_results.json" + Path(all_results_file).parent.mkdir(parents=True, exist_ok=True) + + all_report_data = { + "timestamp": datetime.now().isoformat(), + "total_evaluations": len(sorted_results), + "total_benches": len(bench_groups), + "results": sorted_results + } + + with open(all_results_file, 'w', encoding='utf-8') as f: + json.dump(all_report_data, f, ensure_ascii=False, indent=2) + + print("="*80) + print(f"All results summary saved to: {all_results_file}") + print("="*80) + + +class DataFlowEvalCLI: + """CLI工具""" + + def __init__(self): + self.current_dir = Path.cwd() + + def _get_template_path(self, eval_type: str) -> Path: + current_file = Path(__file__) + dataflow_dir = current_file.parent.parent + return dataflow_dir / "cli_funcs" / "eval_pipeline" / f"eval_{eval_type}.py" + + def init_eval_files(self): + """初始化配置文件""" + files = [("eval_api.py", "api"), ("eval_local.py", "local")] + + existing = [f for f, _ in files if (self.current_dir / f).exists()] + if existing: + if input(f"{', '.join(existing)} exists. Overwrite? (y/n): ").lower() != 'y': + return False + + for filename, eval_type in files: + try: + template = self._get_template_path(eval_type) + if not template.exists(): + logger.error(f"Template not found: {template}") + continue + shutil.copy2(template, self.current_dir / filename) + logger.info(f"Created: {filename}") + except Exception as e: + logger.error(f"Failed: {e}") + logger.info("You must modified the eval_api.py or eval_local.py before you run dataflow eval api/local") + return True + + def run_eval_file(self, eval_file: str): + """运行评估""" + config_path = self.current_dir / eval_file + + if not config_path.exists(): + logger.error(f"Config not found: {eval_file}") + return False + try: + spec = importlib.util.spec_from_file_location("config", config_path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + + config = module.get_evaluator_config() + return run_evaluation(config) + + except Exception as e: + logger.error(f"Failed: {e}") + return False + + +def run_evaluation(config): + """运行评估""" + pipeline = EvaluationPipeline(config) + return pipeline.run() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_init.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_init.py new file mode 100644 index 0000000000000000000000000000000000000000..1f27bf816c279e209907f91164f193973d6865ee --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_init.py @@ -0,0 +1,136 @@ +import os +from pathlib import Path +from typing import Optional +from colorama import init, Fore, Style +from .paths import DataFlowPath +from .copy_funcs import copy_files_without_recursion, copy_file, copy_files_recursively +from .utils import _echo + +def _copy_scripts(): + target_dir = os.getcwd() + if not os.path.exists(target_dir): + os.makedirs(target_dir) + + # script_path = DataFlowPath.get_dataflow_scripts_dir() + + copy_files_recursively(DataFlowPath.get_dataflow_scripts_dir(), target_dir) + +def _copy_pipelines(): + target_dir = os.getcwd() + if not os.path.exists(target_dir): + os.makedirs(target_dir) + copy_files_recursively(DataFlowPath.get_dataflow_pipelines_dir(), target_dir) + # Copy pipelines + +def _copy_playground(): + target_dir = os.getcwd() + if not os.path.exists(target_dir): + os.makedirs(target_dir) + copy_files_recursively(DataFlowPath.get_dataflow_playground_dir(), target_dir) + +def _copy_examples(): + target_dir = os.path.join(os.getcwd(), "example_data") + if not os.path.exists(target_dir): + os.makedirs(target_dir) + copy_files_recursively(DataFlowPath.get_dataflow_example_dir(), target_dir) + +def cli_init(subcommand): + print(f'{Fore.GREEN}Initializing in current working directory...{Style.RESET_ALL}') + + # base initialize that only contain default scripts + if subcommand == "base": + _copy_pipelines() + _copy_examples() + _copy_playground() + # if subcommand == "model_zoo": + # _copy_train_scripts() + # _copy_demo_runs() + # _copy_demo_configs() + # _copy_dataset_json() + # # base initialize that only contain default scripts + # if subcommand == "backbone": + # _copy_train_scripts() + # _copy_demo_runs() + # _copy_demo_configs() + # _copy_dataset_json() + # print(f'{Fore.GREEN}Successfully initialized IMDLBenCo scripts.{Style.RESET_ALL}') + + +def init_repo_scaffold( + no_input: bool = False, + context: Optional[dict] = None, +) -> None: + """ + Initialize a DataFlow repository using the built-in scaffold template. + """ + import os + from pathlib import Path + from colorama import Fore, Style + + try: + from cookiecutter.main import cookiecutter + except ImportError: + raise RuntimeError( + "cookiecutter is not installed. " + "Please run: pip install cookiecutter" + ) + + from .paths import DataFlowPath + + template_path = DataFlowPath.get_dataflow_scaffold_dir() + output_dir = Path.cwd() + context = context or {} + + if not template_path.exists(): + raise FileNotFoundError(f"Scaffold template not found: {template_path}") + + # ---------- pretty header ---------- + width = 80 + try: + width = os.get_terminal_size().columns + except OSError: + pass + + print(Fore.BLUE + "=" * width + Style.RESET_ALL) + print(Fore.CYAN + "🚀 DataFlow Repository Scaffold Initialization\n" + Style.RESET_ALL) + + info = { + "Template": template_path, + "Output Dir": output_dir, + "Interactive": "No" if no_input else "Yes", + "Extra Context": "Provided" if context else "None", + } + + for k, v in info.items(): + print(f"- {k:<13}: {v}") + + print("\n" + Fore.BLUE + "-" * width + Style.RESET_ALL) + print("Generating project from scaffold...") + print(Fore.BLUE + "-" * width + Style.RESET_ALL + "\n") + + # ---------- cookiecutter ---------- + generated_path = cookiecutter( + template=str(template_path), + no_input=no_input, + extra_context=context, + output_dir=str(output_dir), + ) + + generated_path = Path(generated_path).resolve() + # ---------- footer ---------- + print("\n" + Fore.GREEN + "✔ Repository scaffold initialized successfully 🎉" + Style.RESET_ALL) + print(Fore.GREEN + f"📁 Project path: {generated_path}" + Style.RESET_ALL) + + # ---------- post-init guidance ---------- + print("\n" + Fore.CYAN + "Next steps:" + Style.RESET_ALL) + print(f" 1. Enter project directory:") + print(f" cd {generated_path}") + print() + print(f" 2. Install this project in editable mode (for local development):") + print(f" pip install -e .") + print() + print(f" 3. Initialize a git repository (recommended for release & distribution):") + print(f" git init") + print(f" git add .") + print(f" git commit -m \"Initial commit\"") + print(Fore.BLUE + "=" * width + Style.RESET_ALL) \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_pdf.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_pdf.py new file mode 100644 index 0000000000000000000000000000000000000000..e1e327cf18ca4ed2fdb5daab068327d6d76eae39 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_pdf.py @@ -0,0 +1,526 @@ +#!/usr/bin/env python3 +""" +DataFlow PDF2Model CLI Module - dataflow/cli_funcs/cli_pdf.py +PDF to Model training pipeline with init/train/chat commands +""" + +import subprocess +import sys +import yaml +import json +import os +import datetime +from pathlib import Path +from colorama import Fore, Style +from dataflow import get_logger +from .paths import DataFlowPath + +logger = get_logger() + + +def run_script_with_args(script_path: Path, description: str, args: list = None, cwd: str = None) -> bool: + """Run a Python script with arguments and real-time output""" + print(f"\n{Fore.BLUE}{description}{Style.RESET_ALL}") + cmd = [sys.executable, str(script_path)] + if args: + cmd.extend(args) + print(f"Running: {' '.join(cmd)}") + if cwd: + print(f"Working directory: {cwd}") + + try: + result = subprocess.run(cmd, cwd=cwd, check=True, + stdout=sys.stdout, stderr=sys.stderr, text=True) + print(f"{Fore.GREEN}✅ {description} completed{Style.RESET_ALL}") + return True + except subprocess.CalledProcessError as e: + print(f"{Fore.RED}❌ {description} failed{Style.RESET_ALL}") + return False + + +def get_dataflow_script_path(script_name: str) -> Path: + """Get the path of dataflow built-in scripts""" + try: + import dataflow + dataflow_path = Path(dataflow.__file__).parent + + # PDF2Model 脚本在 dataflow/cli_funcs/pdf2model_pipeline/ 目录下 + pdf2model_path = dataflow_path / "cli_funcs" / "pdf2model_pipeline" / script_name + if pdf2model_path.exists(): + return pdf2model_path + + # 检查其他可能的路径 + possible_dirs = [ + dataflow_path / "templates" / "pdf2model_pipeline", + dataflow_path / "pipeline_templates" + ] + + for dir_path in possible_dirs: + script_path = dir_path / script_name + if script_path.exists(): + return script_path + + return None + except Exception: + return None + + +def copy_customizable_scripts(): + """Only copy scripts that users might want to customize""" + print("Step 0: Copying customizable pipeline script...") + + current_dir = Path(os.getcwd()) + + try: + # 只复制用户可能需要自定义的脚本 + scripts_to_copy = [ + "pdf_to_qa_pipeline.py" # 用户可能需要修改 vLLM/sglang 配置 + ] + + import shutil + copied_files = [] + + for script_name in scripts_to_copy: + source_path = get_dataflow_script_path(script_name) + if source_path is None: + print(f"Warning: Template not found: {script_name}") + continue + + target_file = current_dir / script_name + + shutil.copy2(source_path, target_file) + copied_files.append(script_name) + print(f"Copied: {script_name}") + + if copied_files: + print(f"Successfully copied {len(copied_files)} customizable script(s)") + print("You can now modify these files (e.g., switch vLLM/sglang in pdf_to_qa_pipeline.py)") + return True + else: + print("No customizable scripts were copied") + return False + + except Exception as e: + print(f"Failed to copy scripts: {e}") + return False + + +def create_train_config_yaml(cache_path="./", model_name_or_path="Qwen/Qwen2.5-7B-Instruct"): + """Create train_config.yaml file using built-in LlamaFactory configuration""" + cache_path_obj = Path(cache_path) + if not cache_path_obj.is_absolute(): + caller_cwd = Path(os.environ.get('PWD', os.getcwd())) + cache_path_obj = caller_cwd / cache_path_obj + + # 生成时间戳 + timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") + model_dir_name = f"pdf2model_cache_{timestamp}" # 改为pdf2model_cache前缀 + + cache_dir = cache_path_obj / ".cache" + cache_dir.mkdir(parents=True, exist_ok=True) + config_file = cache_dir / "train_config.yaml" + + try: + # 使用内置的 LlamaFactory.py 获取默认配置 + llamafactory_script_path = get_dataflow_script_path("llama_factory_trainer.py") + if llamafactory_script_path is None: + print("Built-in llama_factory_trainer.py not found") + return None + + import importlib.util + spec = importlib.util.spec_from_file_location("llamafactory_trainer", llamafactory_script_path) + llamafactory_module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(llamafactory_module) + + # 创建trainer实例并获取默认配置 + trainer = llamafactory_module.LlamaFactoryTrainer(str(config_file), str(cache_path_obj)) + config = trainer.get_default_config() + + # 只更新必要的动态参数 + config["model_name_or_path"] = model_name_or_path + config["output_dir"] = str(cache_path_obj / ".cache" / "saves" / model_dir_name) + config["dataset_dir"] = str(cache_path_obj / ".cache" / "data") + + # 根据模型类型设置模板 + if "qwen" in model_name_or_path.lower(): + config["template"] = "qwen" + elif "llama" in model_name_or_path.lower(): + config["template"] = "llama3" + elif "chatglm" in model_name_or_path.lower(): + config["template"] = "chatglm3" + elif "baichuan" in model_name_or_path.lower(): + config["template"] = "baichuan2" + + # 保存配置 + with open(config_file, 'w', encoding='utf-8') as f: + yaml.dump(config, f, + default_flow_style=False, + allow_unicode=True, + sort_keys=False, + indent=2) + + print(f"train_config.yaml created: {config_file}") + print(f"Model will be saved to: {model_dir_name}") + return str(config_file) + + except Exception as e: + print(f"Failed to create train_config.yaml: {e}") + return None + + +def verify_environment(): + """Verify runtime environment""" + print("Checking environment...") + + missing_deps = [] + + try: + import llamafactory + print("✅ LlamaFactory installed") + except ImportError: + missing_deps.append("llamafactory[torch,metrics]") + + try: + import yaml + print("✅ PyYAML installed") + except ImportError: + missing_deps.append("pyyaml") + + if missing_deps: + print(f"❌ Missing dependencies: {', '.join(missing_deps)}") + print(f"Install with: pip install {' '.join(missing_deps)}") + return False + + return True + + +def check_required_files(): + """Check if required built-in scripts exist""" + # 检查所有需要的内置脚本 + required_scripts = [ + "path_to_jsonl_script.py", + "llama_factory_trainer.py" + ] + + missing_scripts = [] + for script in required_scripts: + script_path = get_dataflow_script_path(script) + if script_path is None: + missing_scripts.append(script) + else: + print(f"✅ Found built-in script: {script}") + + if missing_scripts: + print(f"❌ Missing built-in scripts: {', '.join(missing_scripts)}") + print("These should be part of the dataflow installation") + return False + + # 检查用户目录下是否有可自定义的脚本 + current_dir = Path(os.getcwd()) + customizable_script = current_dir / "pdf_to_qa_pipeline.py" + if customizable_script.exists(): + print("✅ Found customizable script: pdf_to_qa_pipeline.py") + else: + print("❌ Missing customizable script: pdf_to_qa_pipeline.py") + print("Run 'dataflow pdf2model init' first") + return False + + return True + + +def cli_pdf2model_init(cache_path: str = "./", model_name: str = "Qwen/Qwen2.5-7B-Instruct") -> bool: + """ + PDF2Model initialization: + 0. Copy only customizable scripts to current directory + 1. Create train_config.yaml in .cache directory + """ + print("Starting PDF2Model initialization...") + print(f"Cache directory: {cache_path}") + print(f"Model: {model_name}") + print(f"Output directory: pdf2model_cache_") # 更新输出目录显示 + print("-" * 60) + + if not verify_environment(): + return False + + try: + # Step 0: Copy only customizable scripts + if not copy_customizable_scripts(): + return False + + # Step 1: Create training configuration + print("Step 1: Creating training configuration...") + config_file = create_train_config_yaml(cache_path, model_name) + + if config_file: + print("PDF2Model initialization completed!") + return True + else: + print("Failed to create training configuration") + return False + + except Exception as e: + print(f"Initialization failed: {e}") + return False + + +def get_latest_model_dir(cache_path_obj): + """获取最新的模型目录(基于时间戳)""" + saves_dir = cache_path_obj / ".cache" / "saves" + if not saves_dir.exists(): + return None + + # 查找所有 pdf2model_cache_ 开头的目录 + model_dirs = [] + for dir_path in saves_dir.iterdir(): + if dir_path.is_dir() and dir_path.name.startswith('pdf2model_cache_'): + # 检查是否包含正确的时间戳格式 (YYYYMMDD_HHMMSS) + timestamp_part = dir_path.name.replace('pdf2model_cache_', '') + if len(timestamp_part) == 15 and timestamp_part[8] == '_': + date_part = timestamp_part[:8] + time_part = timestamp_part[9:] + if date_part.isdigit() and time_part.isdigit() and len(time_part) == 6: + model_dirs.append(dir_path) + + if not model_dirs: + return None + + # 按名称排序(时间戳会自然排序) + model_dirs.sort(key=lambda x: x.name, reverse=True) + return model_dirs[0] + + +def cli_pdf2model_train(lf_yaml: str = ".cache/train_config.yaml", cache_path: str = "./") -> bool: + """ + Start PDF2Model training using mix of built-in and user scripts + """ + print("Starting PDF2Model training...") + + current_dir = Path(os.getcwd()) + + cache_path_obj = Path(cache_path) + if not cache_path_obj.is_absolute(): + cache_path_obj = current_dir / cache_path_obj + + config_path_obj = Path(lf_yaml) + if not config_path_obj.is_absolute(): + config_path_obj = current_dir / config_path_obj + + if not verify_environment(): + return False + + if not check_required_files(): + return False + + if not config_path_obj.exists(): + print(f"Training config file not found: {config_path_obj}") + print(f"{Style.BRIGHT}Run 'dataflow pdf2model init' first") + return False + + print("-" * 60) + + try: + # Step 1: PDF Detection + script1_path = get_dataflow_script_path("path_to_jsonl_script.py") + args1 = ["./", "--output", str(cache_path_obj / ".cache" / "gpu" / "pdf_list.jsonl")] + if not run_script_with_args(script1_path, "Step 1: PDF Detection", args1, cwd=str(current_dir)): + return False + + # Step 2: Data Processing + script2 = current_dir / "pdf_to_qa_pipeline.py" + args2 = ["--cache", cache_path] + if not run_script_with_args(script2, "Step 2: Data Processing", args2, cwd=str(current_dir)): + return False + + # Step 2.5: Create dataset_info.json (dynamically) + print(f"\n{Fore.BLUE}Step 2.5: Creating dataset_info.json{Style.RESET_ALL}") + + # 读取训练配置,获取数据集名称 + try: + with open(config_path_obj, 'r', encoding='utf-8') as f: + train_config = yaml.safe_load(f) + + # 获取数据集名称 + dataset_name = train_config.get('dataset') + if isinstance(dataset_name, list): + dataset_name = dataset_name[0] # 如果是列表,取第一个 + + if not dataset_name: + print("Warning: No dataset name found in train_config.yaml, using default 'kb_qa'") + dataset_name = 'kb_qa' + + print(f"Dataset name from config: {dataset_name}") + + except Exception as e: + print(f"Warning: Could not read train_config.yaml: {e}") + print("Using default dataset name: kb_qa") + dataset_name = 'kb_qa' + + # 创建 dataset_info.json + dataset_info_path = cache_path_obj / ".cache" / "data" / "dataset_info.json" + dataset_info_path.parent.mkdir(parents=True, exist_ok=True) + + dataset_info = { + dataset_name: { # ← 使用从配置读取的名称 + "file_name": "qa.json", + "formatting": "alpaca", + "columns": { + "prompt": "instruction", + "query": "input", + "response": "output" + } + } + } + + with open(dataset_info_path, 'w', encoding='utf-8') as f: + json.dump(dataset_info, f, indent=2, ensure_ascii=False) + + print(f"Created: {dataset_info_path}") + print(f"Dataset registered as: {dataset_name}") + print(f"{Fore.GREEN}✅ Step 2.5: Creating dataset_info.json completed{Style.RESET_ALL}") + + # Step 3: Data Conversion - skip + print(f"\n{Fore.BLUE}Step 3: Data Conversion{Style.RESET_ALL}") + qa_json_path = cache_path_obj / ".cache" / "data" / "qa.json" + if qa_json_path.exists(): + print(f"✅ qa.json already in correct format, skipping conversion") + print(f"{Fore.GREEN}✅ Step 3: Data Conversion completed{Style.RESET_ALL}") + else: + print(f"❌ qa.json not found at {qa_json_path}") + return False + + # Step 4: Training + script4_path = get_dataflow_script_path("llama_factory_trainer.py") + args4 = ["--config", str(config_path_obj), "--cache", cache_path] + if not run_script_with_args(script4_path, "Step 4: Training", args4, cwd=str(current_dir)): + return False + + # Show completion info + try: + with open(config_path_obj, 'r', encoding='utf-8') as f: + config = yaml.safe_load(f) + actual_output_dir = config.get('output_dir', 'unknown') + except Exception: + actual_output_dir = 'unknown' + + print("Training completed successfully!") + print(f"Model saved to: {actual_output_dir}") + print("Next steps:") + print(f"{Style.BRIGHT}Test the trained model with 'dataflow chat'") + + return True + + except Exception as e: + print(f"Training error: {e}") + return False + + +def cli_pdf2model_chat(model_path=None, cache_path="./", base_model=None): + """Start LlamaFactory chat interface""" + current_dir = Path(os.getcwd()) + + # 处理cache路径 + cache_path_obj = Path(cache_path) + if not cache_path_obj.is_absolute(): + cache_path_obj = current_dir / cache_path_obj + + # 确定模型路径 + if model_path is None: + # 获取最新的模型目录 + latest_model_dir = get_latest_model_dir(cache_path_obj) + if latest_model_dir: + model_path = latest_model_dir + else: + print("No trained model found") + print("Run 'dataflow pdf2model train' to train a model first") + return False + + model_path = Path(model_path) + if not model_path.exists(): + print(f"Model not found: {model_path}") + print("Run 'dataflow pdf2model train' to train a model first") + return False + + # 验证是否为有效的adapter目录 + adapter_files = [ + "adapter_config.json", + "adapter_model.bin", + "adapter_model.safetensors" + ] + + has_adapter = any((model_path / f).exists() for f in adapter_files) + if not has_adapter: + print(f"No adapter files found in {model_path}") + print("This doesn't appear to be a trained adapter directory.") + print("Expected files: adapter_config.json, adapter_model.bin/safetensors") + return False + + # 确定基础模型路径 - 安全的读取方式 + if base_model is None: + base_model = None # 先设为None + + # 尝试从训练配置中读取基础模型 + config_file = cache_path_obj / ".cache" / "train_config.yaml" + if config_file.exists(): + try: + with open(config_file, 'r', encoding='utf-8') as f: + config = yaml.safe_load(f) + base_model = config.get('model_name_or_path') + if base_model: + print(f"Found base model in config: {base_model}") + except Exception as e: + print(f"Warning: Could not read config file: {e}") + + # 尝试从adapter_config.json读取 + if not base_model: + adapter_config_path = model_path / "adapter_config.json" + if adapter_config_path.exists(): + try: + with open(adapter_config_path, 'r', encoding='utf-8') as f: + adapter_config = json.load(f) + base_model = adapter_config.get('base_model_name_or_path') + if base_model: + print(f"Found base model in adapter config: {base_model}") + except Exception as e: + print(f"Warning: Could not read adapter config: {e}") + + # 如果仍然没有找到base_model,报错退出而不是使用默认值 + if not base_model: + print("Cannot determine base model path") + print("Please ensure your training config contains 'model_name_or_path'") + print("Or check that adapter_config.json exists and contains 'base_model_name_or_path'") + return False + + # 检查LlamaFactory + try: + import llamafactory + print("LlamaFactory available") + except ImportError: + print("LlamaFactory not installed") + print("Install with: pip install llamafactory[torch,metrics]") + return False + + # 直接用命令行参数启动聊天 + chat_cmd = [ + "llamafactory-cli", "chat", + "--model_name_or_path", base_model, + "--adapter_name_or_path", str(model_path.absolute()) + ] + + print(f"Base model: {base_model}") + print(f"Adapter path: {model_path}") + print(f"Command: {' '.join(chat_cmd)}") + print("-" * 60) + print("Starting chat session...") + print("-" * 60) + + try: + result = subprocess.run(chat_cmd, check=True) + print("\nChat session completed") + return True + except subprocess.CalledProcessError as e: + print(f"\nChat failed: {e}") + return False + except KeyboardInterrupt: + print("\n\nChat session ended by user") + return True \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_text.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_text.py new file mode 100644 index 0000000000000000000000000000000000000000..efa77e8717bff971ffaa2aeddc8e1b7b0f280cc2 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_text.py @@ -0,0 +1,671 @@ +#!/usr/bin/env python3 +""" +DataFlow Text Processing CLI Module - dataflow/cli_funcs/cli_text.py +Text data processing pipeline with complete workflow including Text2QA +""" + +import subprocess +import sys +import json +import os +import datetime +from pathlib import Path +from typing import List, Union, Any +from colorama import Fore, Style +from dataflow import get_logger +from .paths import DataFlowPath + +logger = get_logger() + + +def run_script_with_args(script_path: Path, description: str, args: list = None, cwd: str = None) -> bool: + """Run a Python script with arguments and real-time output""" + print(f"\n{Fore.BLUE}{description}{Style.RESET_ALL}") + cmd = [sys.executable, str(script_path)] + if args: + cmd.extend(args) + print(f"Running: {' '.join(cmd)}") + if cwd: + print(f"Working directory: {cwd}") + + try: + result = subprocess.run(cmd, cwd=cwd, check=True, + stdout=sys.stdout, stderr=sys.stderr, text=True) + print(f"{Fore.GREEN}✅ {description} completed{Style.RESET_ALL}") + return True + except subprocess.CalledProcessError as e: + print(f"{Fore.RED}❌ {description} failed{Style.RESET_ALL}") + return False + + +def get_dataflow_script_path(script_name: str) -> Path: + """Get the path of dataflow built-in scripts""" + try: + import dataflow + dataflow_path = Path(dataflow.__file__).parent + + # Text2Model 脚本在 dataflow/cli_funcs/text2model_pipeline/ 目录下 + text2model_path = dataflow_path / "cli_funcs" / "text2model_pipeline" / script_name + if text2model_path.exists(): + return text2model_path + + # 检查其他可能的路径 + possible_dirs = [ + dataflow_path / "templates" / "text2model_pipeline", + dataflow_path / "pipeline_templates" + ] + + for dir_path in possible_dirs: + script_path = dir_path / script_name + if script_path.exists(): + return script_path + + return None + except Exception: + return None + + +def copy_customizable_scripts(): + """Copy scripts that users might want to customize""" + print("Step 0: Setting up customizable pipeline scripts...") + + current_dir = Path(os.getcwd()) + + # 检查当前目录下是否已经存在所需的脚本文件 + required_scripts = [ + "text_to_qa_pipeline.py", + ] + + existing_scripts = [] + missing_scripts = [] + + for script_name in required_scripts: + script_path = current_dir / script_name + if script_path.exists(): + existing_scripts.append(script_name) + print(f"Found existing: {script_name}") + else: + missing_scripts.append(script_name) + + # 尝试从模板复制缺失的脚本 + copied_files = [] + for script_name in missing_scripts: + source_path = get_dataflow_script_path(script_name) + if source_path is not None: + try: + import shutil + target_file = current_dir / script_name + shutil.copy2(source_path, target_file) + copied_files.append(script_name) + print(f"Copied from template: {script_name}") + except Exception as e: + print(f"Warning: Failed to copy {script_name}: {e}") + else: + print(f"Warning: Template not found for {script_name}") + + total_available = len(existing_scripts) + len(copied_files) + + if total_available > 0: + print(f"Setup completed: {total_available} scripts available") + if existing_scripts: + print(f" Existing scripts: {', '.join(existing_scripts)}") + if copied_files: + print(f" Copied from templates: {', '.join(copied_files)}") + return True + else: + print("Warning: No pipeline scripts available") + return False + + +def create_train_config_yaml(cache_path="./", model_name_or_path="Qwen/Qwen2.5-7B-Instruct"): + """Create train_config.yaml file using built-in LlamaFactory configuration""" + cache_path_obj = Path(cache_path) + if not cache_path_obj.is_absolute(): + caller_cwd = Path(os.environ.get('PWD', os.getcwd())) + cache_path_obj = caller_cwd / cache_path_obj + + # 生成时间戳 + timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") + model_dir_name = f"text2model_cache_{timestamp}" + + cache_dir = cache_path_obj / ".cache" + cache_dir.mkdir(parents=True, exist_ok=True) + config_file = cache_dir / "train_config.yaml" + + try: + # 使用内置的 LlamaFactory.py 获取默认配置 + llamafactory_script_path = get_dataflow_script_path("llama_factory_trainer.py") + if llamafactory_script_path is None: + print("Built-in llama_factory_trainer.py not found") + return None + + import importlib.util + spec = importlib.util.spec_from_file_location("llamafactory_trainer", llamafactory_script_path) + llamafactory_module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(llamafactory_module) + + # 创建trainer实例并获取默认配置 + trainer = llamafactory_module.LlamaFactoryTrainer(str(config_file), str(cache_path_obj)) + config = trainer.get_default_config() + + # 只更新必要的动态参数 + config["model_name_or_path"] = model_name_or_path + config["output_dir"] = str(cache_path_obj / ".cache" / "saves" / model_dir_name) + config["dataset_dir"] = str(cache_path_obj / ".cache" / "data") + + # 根据模型类型设置模板 + if "qwen" in model_name_or_path.lower(): + config["template"] = "qwen" + elif "llama" in model_name_or_path.lower(): + config["template"] = "llama3" + elif "chatglm" in model_name_or_path.lower(): + config["template"] = "chatglm3" + elif "baichuan" in model_name_or_path.lower(): + config["template"] = "baichuan2" + + # 保存配置 + import yaml + with open(config_file, 'w', encoding='utf-8') as f: + yaml.dump(config, f, + default_flow_style=False, + allow_unicode=True, + sort_keys=False, + indent=2) + + print(f"train_config.yaml created: {config_file}") + print(f"Model will be saved to: {model_dir_name}") + return str(config_file) + + except Exception as e: + print(f"Failed to create train_config.yaml: {e}") + return None + + +def verify_environment(): + """Verify runtime environment""" + print("Checking environment...") + + missing_deps = [] + + try: + import llamafactory + print("✅ LlamaFactory installed") + except ImportError: + missing_deps.append("llamafactory[torch,metrics]") + + try: + import yaml + print("✅ PyYAML installed") + except ImportError: + missing_deps.append("pyyaml") + + try: + from dataflow.utils.storage import FileStorage + print("✅ DataFlow storage available") + except ImportError: + missing_deps.append("dataflow") + + try: + # 修复: 使用正确的算子导入路径和类名 + from dataflow.operators.knowledge_cleaning import ( + KBCChunkGeneratorBatch as CorpusTextSplitterBatch, + KBCTextCleanerBatch as KnowledgeCleanerBatch, + KBCMultiHopQAGeneratorBatch as MultiHopQAGeneratorBatch + ) + print("✅ DataFlow operators available") + except ImportError: + missing_deps.append("dataflow operators") + + if missing_deps: + print(f"❌ Missing dependencies: {', '.join(missing_deps)}") + print(f"Install with: pip install {' '.join(missing_deps)}") + return False + + return True + + +def check_required_files_for_training(): + """Check if required built-in scripts exist for training""" + # 检查所有需要的内置脚本 + required_scripts = [ + "merge_json_jsonl.py", + "llama_factory_trainer.py" + ] + + missing_scripts = [] + for script in required_scripts: + script_path = get_dataflow_script_path(script) + if script_path is None: + missing_scripts.append(script) + else: + print(f"✅ Found built-in script: {script}") + + if missing_scripts: + print(f"❌ Missing built-in scripts: {', '.join(missing_scripts)}") + print("These should be part of the dataflow installation") + return False + + # 检查用户目录下是否有可自定义的脚本 + current_dir = Path(os.getcwd()) + customizable_scripts = [ + "text_to_qa_pipeline.py", + ] + + missing_customizable = [] + for script_name in customizable_scripts: + script_path = current_dir / script_name + if script_path.exists(): + print(f"✅ Found customizable script: {script_name}") + else: + missing_customizable.append(script_name) + + if missing_customizable: + print(f"❌ Missing customizable scripts: {', '.join(missing_customizable)}") + print("Run 'dataflow text2model init' first") + return False + + return True + + +def analyze_input_data(input_file: str) -> dict: + """分析输入数据的字段结构""" + if not input_file or not Path(input_file).exists(): + return {} + + try: + with open(input_file, 'r', encoding='utf-8') as f: + first_line = f.readline().strip() + if first_line: + sample_data = json.loads(first_line) + return { + 'available_keys': list(sample_data.keys()), + 'has_sft_format': all(key in sample_data for key in ['instruction', 'input', 'output']), + 'has_text_field': 'text' in sample_data, + 'has_raw_content': 'raw_content' in sample_data + } + except Exception as e: + print(f"Could not analyze input file: {e}") + + return {} + + +def get_latest_model_dir(cache_path_obj): + """获取最新的模型目录(基于时间戳)""" + saves_dir = cache_path_obj / ".cache" / "saves" + if not saves_dir.exists(): + return None + + # 查找所有 text2model_cache_ 开头的目录 + model_dirs = [] + for dir_path in saves_dir.iterdir(): + if dir_path.is_dir() and dir_path.name.startswith('text2model_cache_'): + # 检查是否包含正确的时间戳格式 (YYYYMMDD_HHMMSS) + timestamp_part = dir_path.name.replace('text2model_cache_', '') + if len(timestamp_part) == 15 and timestamp_part[8] == '_': + date_part = timestamp_part[:8] + time_part = timestamp_part[9:] + if date_part.isdigit() and time_part.isdigit() and len(time_part) == 6: + model_dirs.append(dir_path) + + if not model_dirs: + return None + + # 按名称排序(时间戳会自然排序) + model_dirs.sort(key=lambda x: x.name, reverse=True) + return model_dirs[0] + + +def cli_text2model_init(cache_path: str = "./") -> bool: + """ + Text2Model initialization: + 0. Check for existing scripts and copy any missing templates + 1. Create train_config.yaml in .cache directory + """ + + if not verify_environment(): + return False + + try: + # Step 0: Check for existing scripts and setup missing ones + if not copy_customizable_scripts(): + print("Warning: Some scripts may be missing, but continuing...") + + # Step 1: Create training configuration + print("Step 1: Creating training configuration...") + config_file = create_train_config_yaml(cache_path, "Qwen/Qwen2.5-7B-Instruct") + + if config_file: + print("Text2Model initialization completed!") + print("\nWorkflow:") + print("1. Put your JSON/JSONL files with 'text' field in current directory") + print("2. Run: dataflow text2model train") + print(" This will automatically run Text2QA generation and training") + return True + else: + print("Failed to create training configuration") + return False + + except Exception as e: + print(f"Initialization failed: {e}") + return False + + +def cli_text2model_train(input_keys: str = None, lf_yaml: str = "./.cache/train_config.yaml") -> bool: + """ + Start Text2Model training using complete pipeline + """ + print("Starting Text2Model training...") + if input_keys: + print(f"Processing fields: {input_keys}") + + current_dir = Path(os.getcwd()) + config_path_obj = Path(lf_yaml) + if not config_path_obj.is_absolute(): + config_path_obj = current_dir / config_path_obj + + if not verify_environment(): + return False + + if not config_path_obj.exists(): + print(f"Training config file not found: {config_path_obj}") + print("Run 'dataflow text2model init' first") + return False + + input_dir = "./" + cache_path_obj = current_dir + input_path = Path(input_dir) + if not input_path.is_absolute(): + input_path = current_dir / input_path + + if not input_path.exists(): + print(f"Input directory not found: {input_path}") + return False + + print("-" * 60) + + try: + # Step 1: Merge JSON/JSONL files to create text_input.jsonl + print(f"{Fore.CYAN}Step 1: Merging JSON/JSONL files...{Style.RESET_ALL}") + + # 调用 merge_json_jsonl.py 的逻辑 + script1_path = get_dataflow_script_path("merge_json_jsonl.py") + args1 = [str(input_path), "--cache", str(cache_path_obj)] + if not run_script_with_args(script1_path, "JSON/JSONL merging", args1, cwd=str(current_dir)): + print(f"{Fore.RED}❌ Step 1: JSON/JSONL merging failed{Style.RESET_ALL}") + return False + + # 验证 text_input.jsonl 是否创建成功 + text_input_file = cache_path_obj / ".cache" / "gpu" / "text_input.jsonl" + if not text_input_file.exists(): + print( + f"{Fore.RED}❌ text_input.jsonl not created. Check if you have JSON/JSONL files in {input_path}{Style.RESET_ALL}") + return False + + file_size = text_input_file.stat().st_size + print(f"{Fore.GREEN}✅ Step 1 completed: {text_input_file} ({file_size} bytes){Style.RESET_ALL}") + + # Step 2: Text2QA Pipeline + print(f"{Fore.CYAN}Step 2: Text2QA generation...{Style.RESET_ALL}") + + script2_path = cache_path_obj / "text_to_qa_pipeline.py" + args2 = ["--cache", str(cache_path_obj)] + if not run_script_with_args(script2_path, "Text2QA generation", args2, cwd=str(current_dir)): + print(f"{Fore.RED}❌ Step 2: Text2QA generation failed{Style.RESET_ALL}") + return False + + # 验证 Text2QA 输出 + qa_output_file = cache_path_obj / ".cache" / "gpu" / "text2qa_step_step3.json" + if not qa_output_file.exists(): + print(f"{Fore.RED}❌ Text2QA output not found{Style.RESET_ALL}") + return False + + file_size = qa_output_file.stat().st_size + print(f"{Fore.GREEN}✅ Step 2 completed: {qa_output_file} ({file_size} bytes){Style.RESET_ALL}") + + # Step 3: Convert to training format + print(f"{Fore.CYAN}Step 3: Converting to training format...{Style.RESET_ALL}") + + script3_path = get_dataflow_script_path("merge_filter_qa_pairs.py") + args3 = ["--cache", str(cache_path_obj)] + if not run_script_with_args(script3_path, "QA format conversion", args3, cwd=str(current_dir)): + print(f"{Fore.RED}❌ Step 3: QA format conversion failed{Style.RESET_ALL}") + return False + + # 验证训练数据 + qa_file = cache_path_obj / ".cache" / "data" / "qa.json" + dataset_info_file = cache_path_obj / ".cache" / "data" / "dataset_info.json" + + if not qa_file.exists() or not dataset_info_file.exists(): + print(f"{Fore.RED}❌ Training data files not created{Style.RESET_ALL}") + return False + + # 统计样本数 + try: + import json + with open(qa_file, 'r', encoding='utf-8') as f: + qa_data = json.load(f) + sample_count = len(qa_data) + file_size = qa_file.stat().st_size + print( + f"{Fore.GREEN}✅ Step 3 completed: {sample_count} training samples ({file_size} bytes){Style.RESET_ALL}") + except Exception: + print(f"{Fore.GREEN}✅ Step 3 completed{Style.RESET_ALL}") + + # Step 4: Training + print(f"{Fore.CYAN}Step 4: Starting model training...{Style.RESET_ALL}") + + script4_path = get_dataflow_script_path("llama_factory_trainer.py") + args4 = ["--config", str(config_path_obj), "--cache", str(cache_path_obj)] + if not run_script_with_args(script4_path, "Model training", args4, cwd=str(current_dir)): + print(f"{Fore.RED}❌ Step 4: Training failed{Style.RESET_ALL}") + return False + + print(f"{Fore.GREEN}✅ Text2Model training completed successfully!{Style.RESET_ALL}") + print(f"Next steps:") + print(f" Test the model: dataflow chat") + + return True + + except Exception as e: + print(f"Training error: {e}") + return False + + +def _run_text2qa_workflow(current_dir: Path, cache_path_obj: Path, config_path_obj: Path) -> bool: + """Run Text2QA workflow""" + + # Step 1: Check if Text2QA output exists + text2qa_output = cache_path_obj / ".cache" / "gpu" / "text2qa_step_step3.json" + + if not text2qa_output.exists(): + print("Text2QA output not found. Please run text_to_qa_pipeline.py first.") + print("Example:") + print(" 1. Prepare JSON/JSONL files with 'text' field in current directory") + print(" 2. Run: python text_to_qa_pipeline.py") + print(" 3. Then run: dataflow text2model train --text2qa") + return False + + print("Found Text2QA output, proceeding with conversion...") + + # Step 2: Convert QA to Alpaca format + script2 = current_dir / "merge_filter_qa_pairs.py" + args2 = ["--cache", str(cache_path_obj)] + + if not run_script_with_args(script2, "Step 2: Converting QA to Alpaca format", args2, cwd=str(current_dir)): + return False + + # Step 3: Training + script3_path = get_dataflow_script_path("llama_factory_trainer.py") + args3 = ["--config", str(config_path_obj)] + if not run_script_with_args(script3_path, "Step 3: Training", args3, cwd=str(current_dir)): + return False + + # 显示训练完成信息 + try: + import yaml + with open(config_path_obj, 'r', encoding='utf-8') as f: + config = yaml.safe_load(f) + actual_output_dir = config.get('output_dir', 'unknown') + except Exception: + actual_output_dir = 'unknown' + + print("Text2QA training completed successfully!") + print(f"Model saved to: {actual_output_dir}") + print("Next steps:") + print("Test the trained model with 'dataflow chat'") + return True + + +# def _run_normal_text_workflow(input_path: Path, current_dir: Path, cache_path_obj: Path, config_path_obj: Path, +# input_keys: str) -> bool: +# """Run Text2QA workflow as the main processing pipeline""" + +# # Step 1: Merge JSON/JSONL files and create text_input.jsonl - 使用内置脚本 +# script1_path = get_dataflow_script_path("merge_json_jsonl.py") +# args1 = [str(input_path), "--cache", str(cache_path_obj)] +# if not run_script_with_args(script1_path, "Step 1: Preparing text input for Text2QA", args1, cwd=str(current_dir)): +# return False + +# # Step 2: Run Text2QA Pipeline - 使用用户目录下的脚本 +# script2 = current_dir / "text_to_qa_pipeline.py" +# args2 = ["--cache", str(cache_path_obj)] + +# if not run_script_with_args(script2, "Step 2: Text2QA generation", args2, cwd=str(current_dir)): +# return False + +# # Step 3: Convert QA to Alpaca format - 使用用户目录下的脚本 +# script3 = current_dir / "merge_filter_qa_pairs.py" +# args3 = ["--cache", str(cache_path_obj)] + +# if not run_script_with_args(script3, "Step 3: Converting QA to training format", args3, cwd=str(current_dir)): +# return False + +# # Step 4: Training - 使用内置脚本 +# script4_path = get_dataflow_script_path("llama_factory_trainer.py") +# args4 = ["--config", str(config_path_obj)] +# if not run_script_with_args(script4_path, "Step 4: Training", args4, cwd=str(current_dir)): +# return False + +# # 显示训练完成信息,从配置文件中读取实际的输出目录 +# try: +# import yaml +# with open(config_path_obj, 'r', encoding='utf-8') as f: +# config = yaml.safe_load(f) +# actual_output_dir = config.get('output_dir', 'unknown') +# except Exception: +# actual_output_dir = 'unknown' + +# print("Text2QA training completed successfully!") +# print(f"Model saved to: {actual_output_dir}") +# print("Next steps:") +# print("Test the trained model with 'dataflow chat'") +# return True + + +def cli_text2model_chat(model_path=None): + """Start LlamaFactory chat interface for text2model""" + + current_dir = Path(os.getcwd()) + + # 使用默认cache路径 + cache_path_obj = current_dir + + # 确定模型路径 + if model_path is None: + # 获取最新的模型目录 + latest_model_dir = get_latest_model_dir(cache_path_obj) + if latest_model_dir: + model_path = latest_model_dir + else: + print("No trained model found") + print("Run 'dataflow text2model train' to train a model first") + return False + + model_path = Path(model_path) + if not model_path.exists(): + print(f"Model not found: {model_path}") + print("Run 'dataflow text2model train' to train a model first") + return False + + # 验证是否为有效的adapter目录 + adapter_files = [ + "adapter_config.json", + "adapter_model.bin", + "adapter_model.safetensors" + ] + + has_adapter = any((model_path / f).exists() for f in adapter_files) + if not has_adapter: + print(f"No adapter files found in {model_path}") + print("This doesn't appear to be a trained adapter directory.") + print("Expected files: adapter_config.json, adapter_model.bin/safetensors") + return False + + # 安全地确定基础模型 + base_model = None + + # 尝试从训练配置中读取基础模型 + config_file = cache_path_obj / ".cache" / "train_config.yaml" + if config_file.exists(): + try: + import yaml + with open(config_file, 'r', encoding='utf-8') as f: + config = yaml.safe_load(f) + base_model = config.get('model_name_or_path') + if base_model: + print(f"Found base model in config: {base_model}") + except Exception as e: + print(f"Warning: Could not read config file: {e}") + + # 尝试从adapter_config.json读取 + if not base_model: + adapter_config_path = model_path / "adapter_config.json" + if adapter_config_path.exists(): + try: + with open(adapter_config_path, 'r', encoding='utf-8') as f: + adapter_config = json.load(f) + base_model = adapter_config.get('base_model_name_or_path') + if base_model: + print(f"Found base model in adapter config: {base_model}") + except Exception as e: + print(f"Warning: Could not read adapter config: {e}") + + # 如果仍然没有找到base_model,报错退出 + if not base_model: + print("Cannot determine base model path") + print("Please ensure your training config contains 'model_name_or_path'") + print("Or check that adapter_config.json exists and contains 'base_model_name_or_path'") + return False + + # 检查LlamaFactory + try: + import llamafactory + print("LlamaFactory available") + except ImportError: + print("LlamaFactory not installed") + print("Install with: pip install llamafactory[torch,metrics]") + return False + + # 直接用命令行参数启动聊天 + chat_cmd = [ + "llamafactory-cli", "chat", + "--model_name_or_path", base_model, + "--adapter_name_or_path", str(model_path.absolute()) + ] + + print(f"Base model: {base_model}") + print(f"Adapter path: {model_path}") + print("-" * 60) + print("Starting chat session...") + print("-" * 60) + + try: + result = subprocess.run(chat_cmd, check=True) + print("\nChat session completed") + return True + except subprocess.CalledProcessError as e: + print(f"\nChat failed: {e}") + return False + except KeyboardInterrupt: + print("\n\nChat session ended by user") + return True \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_webui.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_webui.py new file mode 100644 index 0000000000000000000000000000000000000000..e046dec3117a2ed5a1e278b10f46fa83e9c8727e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_webui.py @@ -0,0 +1,324 @@ +from __future__ import annotations + +import os +import shutil +import zipfile +from pathlib import Path +from typing import Optional, Tuple +import webbrowser +import requests +import threading +import time + +from dataflow.cli_funcs.utils import _echo + +OWNER = "OpenDCAI" +REPO = "DataFlow-WebUI" +LATEST_API = f"https://api.github.com/repos/{OWNER}/{REPO}/releases/latest" +REPO_URL = f"https://github.com/{OWNER}/{REPO}" + + +def _ask_yes(prompt: str, default_no: bool = True) -> bool: + suffix = " [y/N]: " if default_no else " [Y/n]: " + ans = input(prompt + suffix).strip().lower() + if not ans: + return not default_no + return ans in {"y", "yes"} + + +def _confirm_yes() -> None: + _echo(f"This will run DataFlow-WebUI ({REPO_URL}) by using a GitHub Release zip.", "yellow") + # if input("Type 'yes' to continue: ").strip().lower() != "yes": + # if not _ask_yes("Do you confirm to continue?", default_no=False): + # raise SystemExit(0) + + +def _pick_zip(release: dict) -> Tuple[str, str, str]: + tag = release.get("tag_name") or "latest" + for a in release.get("assets", []): + name = a.get("name", "") + url = a.get("browser_download_url", "") + if name.startswith("DataFlow-WebUI-") and name.endswith(".zip") and url: + return tag, name, url + raise RuntimeError("No DataFlow-WebUI-*.zip found in latest release.") + + +def _ask_base_dir(default: Path) -> Path: + _echo(f"Default download directory: {default}", "cyan") + ans = input(f"Download directory [{default}]: ").strip() + return (Path(ans).expanduser().resolve() if ans else default.resolve()) + +def _open_browser(url: str) -> None: + try: + ok = webbrowser.open(url, new=2) # new=2: new tab if possible + if ok: + _echo(f"Opened browser: {url}", "green") + else: + _echo(f"Please open in browser: {url}", "cyan") + except Exception: + _echo(f"Please open in browser: {url}", "cyan") + +def _wait_open_browser_async(host: str, port: int, path: str = "", timeout_s: int = 60) -> None: + """ + Start a daemon thread: + - poll http://{host}:{port}{path} every 1s + - within timeout_s, once any HTTP response is received, open browser and report to stdout + - if timeout, report startup failure (cannot stop uvicorn because we use os.system) + """ + # 0.0.0.0 只能 bind,不能用于本机访问;本机访问用 127.0.0.1 + visit_host = "127.0.0.1" if host in {"0.0.0.0", "0.0.0.0/0"} else host + url = f"http://{visit_host}:{port}" + ui_url = f"{url}{path}" + if not url.endswith("/"): + url += "/" + + def _worker() -> None: + _echo(f"[webui] Waiting for server... {url} (timeout={timeout_s}s)", "cyan") + start = time.time() + while time.time() - start < timeout_s: + try: + # 只要能建立连接并拿到任意 HTTP 响应就算 ready + r = requests.get(url, timeout=0.8) + _echo(f"[webui] Server is up ({r.status_code}). Opening browser: {url}", "green") + try: + webbrowser.open(ui_url, new=2) + except Exception as e: + _echo(f"[webui] Failed to open browser automatically: {e}", "yellow") + _echo(f"[webui] Please open manually: {url}", "cyan") + return + except Exception: + time.sleep(1) + + _echo(f"[webui] Timeout after {timeout_s}s — server did not respond at {url}", "red") + _echo("[webui] Startup may have failed (or is still starting). Check terminal logs above.", "yellow") + + t = threading.Thread(target=_worker, daemon=True) + t.start() + + +def _download_with_progress(url: str, dst: Path) -> None: + try: + dst.parent.mkdir(parents=True, exist_ok=True) + with requests.get(url, stream=True, timeout=120) as r: + r.raise_for_status() + total = int(r.headers.get("Content-Length", 0)) + downloaded = 0 + last_percent = -1 + + with open(dst, "wb") as f: + for chunk in r.iter_content(chunk_size=100 * 1024): + if not chunk: + continue + f.write(chunk) + downloaded += len(chunk) + + if total > 0: + percent = int(downloaded * 100 / total) + if percent != last_percent: + mb_done = downloaded / (1024 * 1024) + mb_total = total / (1024 * 1024) + print( + f"\rDownloading: {percent:3d}% " + f"({mb_done:.1f}/{mb_total:.1f} MB)", + end="", + flush=True, + ) + last_percent = percent + + if total > 0: + print() # 换行 + except Exception as e: + print(e) + if dst.exists(): + dst.unlink(missing_ok=True) + raise RuntimeError(f"Download failed: {e}, please mannually fetch it from {url}") from e + +def _run_in_dir(workdir: Path, cmd: str) -> int: + old = Path.cwd() + try: + os.chdir(workdir) + return os.system(cmd) + finally: + os.chdir(old) +def _resolve_backend_dir(webui_path: Path) -> Path: + """ + webui_path 可以是: + - 直接指向 backend/ 目录 + - 指向解压根目录(里面有 backend/) + """ + p = Path(webui_path).expanduser().resolve() + if not p.exists() or not p.is_dir(): + raise RuntimeError(f"webui-path not found or not a directory: {p}") + + # 如果直接就是 backend + if (p / "requirements.txt").is_file() and (p / "app").is_dir(): + return p + + # 如果是上层目录,尝试找 backend/ + backend = p / "backend" + if (backend / "requirements.txt").is_file() and (backend / "app").is_dir(): + return backend + + raise RuntimeError( + f"Cannot locate backend directory from webui-path: {p}\n" + "Expected either:\n" + " - /requirements.txt and /app/\n" + " - /backend/requirements.txt and /backend/app/" + ) + + +def _load_latest_release() -> Tuple[str, str, str]: + """ + 返回 (tag, name, url) + """ + _echo("loading version info from Github Release...", "cyan") + r = requests.get( + LATEST_API, + headers={"Accept": "application/vnd.github+json"}, + timeout=20, + ) + r.raise_for_status() + release = r.json() + + # 打印 Release 页面路径 + html_url = release.get("html_url") + if html_url: + _echo(f"Latest release page: {html_url}", "green") + + + tag, name, url = _pick_zip(release) + return tag, name, url + + +def cli_webui( + zip_path: Optional[Path] = None, + webui_path: Optional[Path] = None, + host: str = "0.0.0.0", + port: int = 8000, +) -> None: + _confirm_yes() + + # 优先级:zip_path > webui_path > 云端下载交互 + if zip_path is not None: + # ---- Case A: 本地 zip(自动解压并运行)---- + zip_path = Path(zip_path).expanduser().resolve() + if not zip_path.is_file(): + raise RuntimeError(f"zip-path not found: {zip_path}") + + _echo(f"Using local zip: {zip_path}", "green") + + # 选择 base dir(用于解压目录) + base_dir = _ask_base_dir(Path.cwd() / "dataflow_webui") + downloads = base_dir / "downloads" + releases = base_dir / "releases" + downloads.mkdir(parents=True, exist_ok=True) + releases.mkdir(parents=True, exist_ok=True) + _echo(f"Base directory: {base_dir}", "green") + + tag = "local" + extract_dir = releases / tag + + # 解压:若已存在则询问是否覆盖提取 + if extract_dir.exists(): + _echo(f"Found existing extracted dir: {extract_dir}", "yellow") + if _ask_yes("Overwrite and re-extract?", default_no=True): + shutil.rmtree(extract_dir) + _echo(f"Extracting → {extract_dir}", "cyan") + extract_dir.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(zip_path, "r") as zf: + zf.extractall(extract_dir) + else: + _echo("Using existing extracted files (skip extract).", "green") + else: + _echo(f"Extracting → {extract_dir}", "cyan") + extract_dir.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(zip_path, "r") as zf: + zf.extractall(extract_dir) + + # 定位 backend + dirs = [p for p in extract_dir.iterdir() if p.is_dir()] + root = dirs[0] if len(dirs) == 1 else extract_dir + backend = root / "backend" + if not backend.exists(): + raise RuntimeError("backend/ directory not found after extraction.") + + elif webui_path is not None: + # ---- Case B: 直接传已解压的后端目录(直接运行)---- + backend = _resolve_backend_dir(Path(webui_path)) + _echo(f"Using existing backend directory: {backend}", "green") + + else: + # ---- Case C: 两者都 None:先加载云端版本 -> 询问是否下载最新 -> 确认下载路径 -> 覆盖询问 ---- + tag, name, url = _load_latest_release() + _echo(f"Latest release: {tag} ({name})", "green") + + if not _ask_yes(f"Download latest release {tag} now?", default_no=True): + _echo("Cancelled. No zip-path/webui-path provided and you chose not to download.", "yellow") + return + + # 确认下载路径(base dir) + base_dir = _ask_base_dir(Path.cwd() / "dataflow_webui") + downloads = base_dir / "downloads" + releases = base_dir / "releases" + downloads.mkdir(parents=True, exist_ok=True) + releases.mkdir(parents=True, exist_ok=True) + _echo(f"Base directory: {base_dir}", "green") + + zip_path = downloads / name + _echo(f"Download to : {zip_path}", "cyan") + + # 若 zip 已存在:询问 overwrite download + if zip_path.exists() and zip_path.stat().st_size > 0: + _echo(f"Found existing zip: {zip_path}", "yellow") + if _ask_yes("Overwrite and re-download this zip?", default_no=True): + zip_path.unlink(missing_ok=True) + _echo(f"Re-downloading → {zip_path}", "cyan") + _download_with_progress(url, zip_path) + else: + _echo("Using existing zip (skip download).", "green") + else: + _echo(f"Downloading: {name}", "cyan") + _download_with_progress(url, zip_path) + + # 解压目录:releases/tag + extract_dir = releases / tag + + # 若解压目录存在:询问是否覆盖提取 + if extract_dir.exists(): + _echo(f"Found existing extracted dir: {extract_dir}", "yellow") + if _ask_yes("Overwrite and re-extract?", default_no=True): + shutil.rmtree(extract_dir) + _echo(f"Extracting → {extract_dir}", "cyan") + extract_dir.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(zip_path, "r") as zf: + zf.extractall(extract_dir) + else: + _echo("Using existing extracted files (skip extract).", "green") + else: + _echo(f"Extracting → {extract_dir}", "cyan") + extract_dir.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(zip_path, "r") as zf: + zf.extractall(extract_dir) + + # 定位 backend + dirs = [p for p in extract_dir.iterdir() if p.is_dir()] + root = dirs[0] if len(dirs) == 1 else extract_dir + backend = root / "backend" + if not backend.exists(): + raise RuntimeError("backend/ directory not found after extraction.") + + # 统一:安装依赖 + 运行(保留 host/port) + _echo(f"Backend directory: {backend}", "green") + _echo("Installing backend requirements into current Python environment...", "cyan") + _rc = _run_in_dir(backend, "python -m pip install -r requirements.txt") + if _rc != 0: + raise RuntimeError("pip install failed (see logs above).") + + _echo(f"Starting WebUI at http://{host}:{port}", "green") + _wait_open_browser_async(host, port, path="", timeout_s=60) + _rc = _run_in_dir( + backend, + f"python -m uvicorn app.main:app --reload --reload-dir app --host {host} --port {port}", + ) + if _rc != 0: + raise RuntimeError("uvicorn exited with error (see logs above).") \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/copy_funcs.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/copy_funcs.py new file mode 100644 index 0000000000000000000000000000000000000000..24fe67dc8551dd1059b2db8dd187af99c23aee3f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/copy_funcs.py @@ -0,0 +1,98 @@ +import shutil +from colorama import init, Fore, Style +from pathlib import Path + +def copy_file(source: Path, destination: Path): + """ + Copy a single file with path, with checking and asking about the existence. + """ + if not source.is_file(): + print(f"Error: {source} is not a file.") + return + + if destination.exists(): + print(f"Warning: {destination.name} already exists in {destination.parent}.") + user_input = input(f"Do you want to overwrite {destination.name}? (y/n): ").strip().lower() + if user_input != 'y': + print(f"Skipping {destination.name}.") + return + + shutil.copy(source, destination) + print(f"Copied {source.name} to {destination}.") + +def copy_files_without_recursion(source: Path, destination): + """ + Copy files under a path without recursion, with checking and asking about the existence. + """ + yes_to_all, none_to_all = False, False + + for template_file in source.iterdir(): + if template_file.is_file(): + if template_file.name == "__init__.py": + continue # skip __init__.py files + destination_file = Path(destination) / template_file.name + if destination_file.exists(): + if none_to_all: + print(f' Skipping {template_file.name}.\n') + continue + if not yes_to_all: + # Alert , whether overwrite? + print(f' {Fore.YELLOW}Warning: {template_file.name} already exists in {destination}.{Style.RESET_ALL}') + user_input = input(f' Do you want to overwrite {template_file.name}? (y/n/all/none): ').strip().lower() + if user_input == 'all': + yes_to_all = True + elif user_input == 'none': + none_to_all = True + print(f' Skipping {template_file.name}.\n') + continue + elif user_input != 'y': + print(f' Skipping {template_file.name}.\n') + continue + shutil.copy(template_file, destination_file) + print(f' Copied {template_file.name} to {destination}.\n') + +def copy_files_recursively(source_path: Path, destination_path: Path): + """ + Recursively copy all contents from source_path to destination_path. + Prompts user if a file already exists in destination. + """ + if not source_path.exists(): + print(f"{Fore.RED}Error: Source path does not exist.{Style.RESET_ALL}") + return + + if not source_path.is_dir(): + print(f"{Fore.RED}Error: Source path is not a directory.{Style.RESET_ALL}") + return + + yes_to_all = False + none_to_all = False + + for item in source_path.rglob('*'): + relative_path = item.relative_to(source_path) + dest_item = destination_path / relative_path + + if item.is_dir(): + dest_item.mkdir(parents=True, exist_ok=True) + else: + if dest_item.exists(): + if yes_to_all: + pass # proceed with overwrite + elif none_to_all: + print(f' Skipping {dest_item.name}.\n') + continue + else: + print(f' {Fore.YELLOW}Warning: {dest_item.name} already exists in {destination_path}.{Style.RESET_ALL}') + user_input = input(f' Do you want to overwrite {dest_item.name}? (y/n/all/none): ').strip().lower() + if user_input == 'all': + yes_to_all = True + elif user_input == 'none': + none_to_all = True + print(f' Skipping {dest_item.name}.\n') + continue + elif user_input != 'y': + print(f' Skipping {dest_item.name}.\n') + continue + + shutil.copy2(item, dest_item) + # give a clear output with multi line + print(f'{Fore.GREEN}[Copied]\nFrom: {item}\nTo: {dest_item}{Style.RESET_ALL}\n') \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/eval_pipeline/__pycache__/eval_api.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/eval_pipeline/__pycache__/eval_api.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..067ec6f403996863ee3742ec9a5f22bb4f81ce15 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/eval_pipeline/__pycache__/eval_api.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/eval_pipeline/__pycache__/eval_local.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/eval_pipeline/__pycache__/eval_local.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fce3c737f4b61d160f29cef199ad8d8be95b2883 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/eval_pipeline/__pycache__/eval_local.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/eval_pipeline/eval_api.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/eval_pipeline/eval_api.py new file mode 100644 index 0000000000000000000000000000000000000000..c3cb1bb00f8131184968d1bcf2f0db0436076d91 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/eval_pipeline/eval_api.py @@ -0,0 +1,243 @@ +# eval_api.py - API评估配置文件 +"""DataFlow API Evaluation Configuration - Enhanced Version""" + +import os +from dataflow.operators.core_text import BenchDatasetEvaluatorQuestion +from dataflow.serving import APILLMServing_request +from dataflow.utils.storage import FileStorage +from dataflow.cli_funcs.cli_eval import run_evaluation + +# ============================================================================= +# Fair Evaluation Prompt Template +# ============================================================================= + +class FairAnswerJudgePrompt: + """Fair answer evaluation prompt template with English prompts""" + + # 默认评估模型提示词 该prompt为评估模型的提示词,请勿与被评估模型提示词混淆 + def build_prompt(self, question, answer, reference_answer): + prompt = f"""You are an expert evaluator assessing answer quality for academic questions. + **Question:** + {question} + + **Answer to Evaluate:** + {answer} + + **Evaluation Instructions:** + Judge this answer based on: + 1. **Factual Accuracy**: Is the information correct? + 2. **Completeness**: Does it address the key aspects of the question? + 3. **Relevance**: Is it directly related to what was asked? + 4. **Academic Quality**: Is the reasoning sound and appropriate? + + **Important Guidelines:** + - Focus on content correctness, not writing style + - A good answer may be longer, shorter, or differently structured + - Accept different valid approaches or explanations + - Judge based on whether the answer demonstrates correct understanding + - Consider partial credit for answers that are mostly correct + + **Reference Answer (for context only):** {reference_answer} + + **Output Format:** + Return your judgment in JSON format: + {{"judgement_result": true}} if the answer is factually correct and adequately addresses the question + {{"judgement_result": false}} if the answer contains significant errors or fails to address the question + + **Your Judgment:**""" + return prompt + + +# ============================================================================= +# Configuration Parameters +# 参数设置 +# ============================================================================= + +# Judge Model Configuration (API model as judge) +# 评估模型设置 +JUDGE_MODEL_CONFIG = { + "model_name": "gpt-4o-mini", + "api_url": "API_URL", # 请求URL 必填 / request (required) + "api_key_env": "DF_API_KEY", # api_key 必填 / api_key (required) + "max_workers": 3, + "max_retries": 5, +} + +# Target Models Configuration (List format - required, each element is a dict) +# 被评估模型设置 (列表格式 - 必需,每个元素是字典) +TARGET_MODELS = [ + # { + # "name": "qwen_3b", # 模型名称(可选,默认使用路径最后一部分) / Model name (optional, uses the last part of the path by default) + # "path": "./Qwen2.5-3B-Instruct", # 模型路径(必需) / Model path (required) + + # # ===== 答案生成的模型加载参数(可选)===== + # "tensor_parallel_size": 1, # GPU并行数量 / Number of GPU parallels + # "max_tokens": 1024, # 最大生成token数 / Maximum number of generated tokens + # "gpu_memory_utilization": 0.8, # GPU显存利用率 / GPU memory utilization + # }, + { + "name": "qwen_7b", + "path": "./Qwen2.5-7B-Instruct", + # 大模型可以用不同的参数 + "vllm_tensor_parallel_size": 1, + "vllm_temperature" : 0.1, + "vllm_top_p" :0.9, + "vllm_max_tokens": 2048, + "vllm_repetition_penalty":1.0, + "vllm_seed":None, + "vllm_gpu_memory_utilization": 0.9, + + # 可以为每个模型自定义提示词 不写就为默认模板 即build_prompt函数中的prompt + # 默认被评估模型提示词 + # 再次提示:该prompt为被评估模型的提示词,请勿与评估模型提示词混淆!!! + # You can customize prompts for each model. If not specified, defaults to the template in build_prompt function. + # Default prompt for evaluated models + # IMPORTANT: This is the prompt for models being evaluated, NOT for the judge model!!! + "answer_prompt": """please answer the following question:""" # 这里不要使用{question} / do not code {question} here + }, + { + "name": "qwen_3b", + "path": "./Qwen2.5-3B-Instruct", + # 大模型可以用不同的参数 + "vllm_tensor_parallel_size": 1, + "vllm_temperature" : 0.1, + "vllm_top_p" :0.9, + "vllm_max_tokens": 2048, + "vllm_repetition_penalty":1.0, + "vllm_seed":None, + "vllm_gpu_memory_utilization": 0.9, + + # 可以为每个模型自定义提示词 不写就为默认模板 即build_prompt函数中的prompt + # 默认被评估模型提示词 + # 再次提示:该prompt为被评估模型的提示词,请勿与评估模型提示词混淆!!! + # You can customize prompts for each model. If not specified, defaults to the template in build_prompt function. + # Default prompt for evaluated models + # IMPORTANT: This is the prompt for models being evaluated, NOT for the judge model!!! + "answer_prompt": """please answer the following question:""" # 这里不要使用{question} / do not code {question} here + }, + + # 添加更多模型... + # { + # "name": "llama_8b", + # "path": "meta-llama/Llama-3-8B-Instruct", + # "tensor_parallel_size": 2 + # } +] + +# Data Configuration +BENCH_CONFIG = [ + { + "name":"bench_name", + "input_file": "./.cache/data/qa.json", # 输入数据文件 + "output_dir": "./api_eval", # 输出目录 + "question_key": "input", # 原始数据中的问题字段 + "reference_answer_key": "output" # 原始数据中的参考答案字段 + }, + { + "name":"bench_name_1", + "input_file": "./.cache/data/data_qa.json", # 输入数据文件 + "output_dir": "./api_eval", # 输出目录 + "question_key": "input", # 原始数据中的问题字段 + "reference_answer_key": "output" # 原始数据中的参考答案字段 + } +] +# Evaluator Run Configuration (parameters passed to BenchDatasetEvaluator.run) +EVALUATOR_RUN_CONFIG = { + "input_test_answer_key": "model_generated_answer", # 模型生成的答案字段名 + "input_gt_answer_key": "output", # 标准答案字段名(对应原始数据) + "input_question_key": "input" # 问题字段名(对应原始数据) +} + +# Evaluation Configuration +EVAL_CONFIG = { + "compare_method": "semantic", # "semantic" 语义匹配 或 "match" 字段完全匹配 +} + + +# ============================================================================= +# Component Creation Functions +# ============================================================================= + +def create_judge_serving(): + """创建评估器LLM服务(API模式)""" + api_key_env = JUDGE_MODEL_CONFIG["api_key_env"] + if api_key_env not in os.environ: + raise ValueError(f"Environment variable {api_key_env} is not set. " + f"Please set it with your API key.") + + api_key = os.environ[api_key_env] + if not api_key.strip(): + raise ValueError(f"Environment variable {api_key_env} is empty. " + f"Please provide a valid API key.") + + return APILLMServing_request( + api_url=JUDGE_MODEL_CONFIG["api_url"], + key_name_of_api_key=api_key_env, + model_name=JUDGE_MODEL_CONFIG["model_name"], + max_workers=JUDGE_MODEL_CONFIG.get("max_workers", 10), + max_retries=JUDGE_MODEL_CONFIG.get("max_retries", 5) + ) + + +def create_evaluator(judge_serving, eval_result_path): + """创建评估算子""" + return BenchDatasetEvaluatorQuestion( + compare_method=EVAL_CONFIG["compare_method"], + llm_serving=judge_serving, + prompt_template=FairAnswerJudgePrompt(), + eval_result_path=eval_result_path + ) + + +def create_storage(data_file, cache_path,bench_name="eval_result"): + """创建存储算子""" + return FileStorage( + first_entry_file_name=data_file, + cache_path=cache_path, + file_name_prefix=bench_name, + cache_type="json" + ) + + +# ============================================================================= +# Main Configuration Function +# ============================================================================= + +def get_evaluator_config(): + # 返回完整配置 + # Return complete configuration + return { + "JUDGE_MODEL_CONFIG": JUDGE_MODEL_CONFIG, # 评估模型设置映射 + "TARGET_MODELS": TARGET_MODELS, # 被评估模型设置映射 + "BENCH_CONFIG": BENCH_CONFIG, # 数据设置映射 + "EVAL_CONFIG": EVAL_CONFIG, # 评估模式设置映射 + "EVALUATOR_RUN_CONFIG": EVALUATOR_RUN_CONFIG, # 评估数据集字段映射 + "create_judge_serving": create_judge_serving, + "create_evaluator": create_evaluator, + "create_storage": create_storage + } + + +# ============================================================================= +# Direct Execution Support +# 直接运行评估 +# ============================================================================= + +if __name__ == "__main__": + # 直接运行时的简单评估 + # Simple evaluation when run directly + print("Starting API evaluation...") + + try: + config = get_evaluator_config() + success = run_evaluation(config) + + if success: + print("API evaluation completed successfully") + else: + print("API evaluation failed") + except Exception as e: + print(f"Evaluation error: {e}") + import traceback + + traceback.print_exc() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/eval_pipeline/eval_local.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/eval_pipeline/eval_local.py new file mode 100644 index 0000000000000000000000000000000000000000..0cacf850879f735c5c07a43aeb95f8fcde93d507 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/eval_pipeline/eval_local.py @@ -0,0 +1,245 @@ +# eval_local.py - 本地评估配置文件 +"""DataFlow Local Evaluation Configuration - Enhanced Version""" + +from pathlib import Path +from dataflow.serving import LocalModelLLMServing_vllm +from dataflow.utils.storage import FileStorage +from dataflow.operators.core_text import BenchDatasetEvaluatorQuestion +from dataflow.cli_funcs.cli_eval import run_evaluation + +# ============================================================================= +# Fair Evaluation Prompt Template +# ============================================================================= + +class FairAnswerJudgePrompt: + """Fair answer evaluation prompt template with English prompts""" + + def build_prompt(self, question, answer, reference_answer): + prompt = f"""You are an expert evaluator assessing answer quality for academic questions. + **Question:** + {question} + + **Answer to Evaluate:** + {answer} + + **Evaluation Instructions:** + Judge this answer based on: + 1. **Factual Accuracy**: Is the information correct? + 2. **Completeness**: Does it address the key aspects of the question? + 3. **Relevance**: Is it directly related to what was asked? + 4. **Academic Quality**: Is the reasoning sound and appropriate? + + **Important Guidelines:** + - Focus on content correctness, not writing style + - A good answer may be longer, shorter, or differently structured + - Accept different valid approaches or explanations + - Judge based on whether the answer demonstrates correct understanding + - Consider partial credit for answers that are mostly correct + + **Reference Answer (for context only):** {reference_answer} + + **Output Format:** + Return your judgment in JSON format: + {{"judgement_result": true}} if the answer is factually correct and adequately addresses the question + {{"judgement_result": false}} if the answer contains significant errors or fails to address the question + + **Your Judgment:**""" + return prompt + + +# ============================================================================= +# Configuration Parameters +# ============================================================================= + +# Judge Model Configuration (local strong model as judge) +JUDGE_MODEL_CONFIG = { + "model_path": "./Qwen2.5-7B-Instruct", # 用更强的模型做裁判 + "hf_cache_dir": "", + "hf_local_dir": "", + "vllm_tensor_parallel_size": 1, + "vllm_temperature": 0.9, + "vllm_top_p": 0.9, + "vllm_max_tokens": 512, + "vllm_repetition_penalty": 0.8, + "vllm_seed": None, + "vllm_max_model_len": None, + "vllm_gpu_memory_utilization": 0.9 +} + +# Target Models Configuration (字典格式 - 必需) +TARGET_MODELS = [ + { + "name": "qwen_3b", # 模型名称(可选,默认使用路径最后一部分) + "path": "./Qwen2.5-3B-Instruct", # 模型路径(必需) + + # 大模型可以用不同的参数 + "vllm_tensor_parallel_size": 1, + "vllm_temperature": 0.1, + "vllm_top_p": 0.9, + "vllm_max_tokens": 2048, + "vllm_repetition_penalty": 1.0, + "vllm_seed": None, + "vllm_gpu_memory_utilization": 0.9, + }, + { + "name": "qwen_7b", + "path": "./Qwen2.5-7B-Instruct", + # 大模型可以用不同的参数 + "vllm_tensor_parallel_size": 1, + "vllm_temperature": 0.1, + "vllm_top_p": 0.9, + "vllm_max_tokens": 2048, + "vllm_repetition_penalty": 1.0, + "vllm_seed": None, + "vllm_gpu_memory_utilization": 0.9, + + # 可以为每个模型自定义提示词 + "answer_prompt": """Please answer the following question based on the provided information. Put your answer in \\boxed{{}}. + + For example, if the answer is B, output: \\boxed{{B}}""" + + }, + +] + +# Bench Configuration +BENCH_CONFIG = [ + { + "name": "bench_name", # bench名称 + "input_file": "./.cache/data/qa.json", # 数据文件 + "question_key": "input", # 问题字段名 + "reference_answer_key": "output", # 答案字段名 + "output_dir": "./eval_results/bench_name", # 输出目录 + }, + { + "name": "bench_name_1", + "input_file": "./.cache/data/data_qa.json", + "question_key": "input", + "reference_answer_key": "output", + "output_dir": "./eval_results/bench_name_1", + }, + # { + # "name": "code_bench", + # "input_file": "./.cache/data/code_qa.json", + # "question_key": "problem", + # "reference_answer_key": "solution", + # "output_dir": "./eval_results/code_bench", + # }, +] + +# Evaluator Run Configuration (parameters passed to BenchDatasetEvaluator.run) +EVALUATOR_RUN_CONFIG = { + "input_test_answer_key": "model_generated_answer", # 模型生成的答案字段名 + "input_gt_answer_key": "output", # 标准答案字段名(对应原始数据) + "input_question_key": "input" # 问题字段名(对应原始数据) +} + +# Evaluation Configuration +EVAL_CONFIG = { + "compare_method": "semantic", # "semantic" 语义匹配 或 "match" 字段完全匹配 +} + + +# ============================================================================= +# Component Creation Functions - DataFlow Style +# ============================================================================= + +def create_judge_serving(): + """创建本地评估器LLM服务""" + model_path = JUDGE_MODEL_CONFIG["model_path"] + + # Enhanced model path validation + if not model_path.startswith(("Qwen", "meta-llama", "microsoft", "google", "huggingface.co")): + model_path_obj = Path(model_path) + if not model_path_obj.exists(): + raise FileNotFoundError(f"Local model path does not exist: {model_path}") + + # Check for required model files + required_files = ["config.json"] + missing_files = [f for f in required_files if not (model_path_obj / f).exists()] + if missing_files: + raise ValueError(f"Missing required model files in {model_path}: {missing_files}") + + # Enhanced VLLM configuration + vllm_config = { + "hf_model_name_or_path": model_path, + "hf_cache_dir": JUDGE_MODEL_CONFIG.get("hf_cache_dir"), + "hf_local_dir": JUDGE_MODEL_CONFIG.get("hf_local_dir"), + "vllm_tensor_parallel_size": JUDGE_MODEL_CONFIG.get("vllm_tensor_parallel_size", 1), + "vllm_temperature": JUDGE_MODEL_CONFIG.get("vllm_temperature", 0.9), + "vllm_top_p": JUDGE_MODEL_CONFIG.get("vllm_top_p", 0.9), + "vllm_max_tokens": JUDGE_MODEL_CONFIG.get("max_tokens", 512), + "vllm_repetition_penalty": JUDGE_MODEL_CONFIG.get("vllm_repetition_penalty", 1.0), + "vllm_seed": JUDGE_MODEL_CONFIG.get("vllm_seed", None), + "vllm_max_model_len": JUDGE_MODEL_CONFIG.get("vllm_max_model_len", None), + "vllm_gpu_memory_utilization": JUDGE_MODEL_CONFIG.get("gpu_memory_utilization", 0.9) + } + + # Add optional VLLM parameters if they exist + optional_params = ["dtype", "trust_remote_code", "enforce_eager", "disable_log_stats"] + for param in optional_params: + if param in JUDGE_MODEL_CONFIG: + vllm_config[f"vllm_{param}"] = JUDGE_MODEL_CONFIG[param] + + return LocalModelLLMServing_vllm(**vllm_config) + + +def create_evaluator(judge_serving, eval_result_path): + """创建评估算子""" + return BenchDatasetEvaluatorQuestion( + compare_method=EVAL_CONFIG["compare_method"], + llm_serving=judge_serving, + prompt_template=FairAnswerJudgePrompt(), + eval_result_path=eval_result_path + ) + + +def create_storage(data_file, cache_path, bench_name="eval_result"): + """创建存储算子""" + return FileStorage( + first_entry_file_name=data_file, + cache_path=cache_path, + file_name_prefix=bench_name, + cache_type="json" + ) + + +# ============================================================================= +# Main Configuration Function +# ============================================================================= + +def get_evaluator_config(): + """返回完整配置""" + return { + "JUDGE_MODEL_CONFIG": JUDGE_MODEL_CONFIG, + "TARGET_MODELS": TARGET_MODELS, + "BENCH_CONFIG": BENCH_CONFIG, + "EVALUATOR_RUN_CONFIG": EVALUATOR_RUN_CONFIG, + "EVAL_CONFIG": EVAL_CONFIG, + "create_judge_serving": create_judge_serving, + "create_evaluator": create_evaluator, + "create_storage": create_storage + } + + +# ============================================================================= +# Direct Execution Support +# ============================================================================= + +if __name__ == "__main__": + # 直接运行时的简单评估 + print("Starting local evaluation...") + + try: + config = get_evaluator_config() + success = run_evaluation(config) + + if success: + print("Local evaluation completed successfully") + else: + print("Local evaluation failed") + except Exception as e: + print(f"Evaluation error: {e}") + import traceback + + traceback.print_exc() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/paths.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/paths.py new file mode 100644 index 0000000000000000000000000000000000000000..497142790014fec564e5dbb71aeb70c690c61749 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/paths.py @@ -0,0 +1,38 @@ +import os +from pathlib import Path +import appdirs + +class DataFlowPath: + """ + Class to manage paths for DataFlow. + """ + + + @staticmethod + def get_dataflow_dir(): + # return path of /dataflow + return Path(__file__).parent.parent + + # @staticmethod + # def get_dataflow_scripts_dir(): + # return DataFlowPath.get_dataflow_dir() / "scripts" + + @staticmethod + def get_dataflow_example_dir(): + return DataFlowPath.get_dataflow_dir() / "example" + + @staticmethod + def get_dataflow_statics_dir(): + return DataFlowPath.get_dataflow_dir() / "statics" + + @staticmethod + def get_dataflow_pipelines_dir(): + return DataFlowPath.get_dataflow_statics_dir() / "pipelines" + + @staticmethod + def get_dataflow_playground_dir(): + return DataFlowPath.get_dataflow_statics_dir() / "playground" + + @staticmethod + def get_dataflow_scaffold_dir(): + return DataFlowPath.get_dataflow_statics_dir() / "scaffold" \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/__pycache__/llama_factory_trainer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/__pycache__/llama_factory_trainer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..241d0ed6e98ca951d468d226b6098d4f6546aa8b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/__pycache__/llama_factory_trainer.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/__pycache__/path_to_jsonl_script.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/__pycache__/path_to_jsonl_script.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41b953000eab83080454842d3985a0513a9af482 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/__pycache__/path_to_jsonl_script.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/__pycache__/pdf_to_qa_pipeline.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/__pycache__/pdf_to_qa_pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09bba8d9931dde8751801dc1c9c0a8aa12fcb92a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/__pycache__/pdf_to_qa_pipeline.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/llama_factory_trainer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/llama_factory_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..1e0268f0392cfa291e830a79f970baadda90029c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/llama_factory_trainer.py @@ -0,0 +1,369 @@ +#!/usr/bin/env python3 +""" +LlamaFactory Training Script with YAML Configuration Management +Complete "check-create-read-train" workflow +""" + +import yaml +import os +import sys +import subprocess +import argparse +from pathlib import Path + + +class LlamaFactoryTrainer: + def __init__(self, config_path=None, cache_base="./"): + # 处理cache_base相对路径 - 基于调用者工作目录 + cache_path = Path(cache_base) + if not cache_path.is_absolute(): + caller_cwd = Path(os.environ.get('PWD', os.getcwd())) + cache_path = caller_cwd / cache_path + + self.cache_path = cache_path + + # 如果没有指定config_path,使用cache目录下的默认路径 + if config_path is None: + config_path = str(cache_path / ".cache" / "train_config.yaml") + else: + # 处理config_path相对路径 + config_path_obj = Path(config_path) + if not config_path_obj.is_absolute(): + caller_cwd = Path(os.environ.get('PWD', os.getcwd())) + config_path = str(caller_cwd / config_path_obj) + + self.config_path = Path(config_path) + + def get_default_config(self): + """Get default configuration - 基于最新LlamaFactory标准""" + return { + # === 基础配置 === + "stage": "sft", + "do_train": True, + + # === 模型配置 === + "model_name_or_path": "Qwen/Qwen2.5-7B-Instruct", + "template": "qwen", + "trust_remote_code": True, + + # === 微调方法配置 === + "finetuning_type": "lora", + "lora_target": "all", # 使用 "all" 而不是具体层名 + "lora_rank": 16, + "lora_alpha": 32, + "lora_dropout": 0.05, + + # === 数据集配置 === + "dataset": "kb_qa", + "dataset_dir": str(self.cache_path / ".cache" / "data"), + "cutoff_len": 1024, + "max_samples": None, + "overwrite_cache": True, + "preprocessing_num_workers": 4, + + # === 训练配置 === + "per_device_train_batch_size": 2, + "gradient_accumulation_steps": 4, + "learning_rate": 5e-5, + "num_train_epochs": 2.0, + "lr_scheduler_type": "cosine", + "warmup_ratio": 0.05, + "weight_decay": 0.01, + "max_grad_norm": 1.0, + "optim": "adamw_torch", + + # === 输出配置 === + "output_dir": str(self.cache_path / ".cache" / "saves" / "qwen2.5_7b_sft_model"), + "overwrite_output_dir": True, + "save_only_model": True, + "plot_loss": True, + + # === 日志和检查点 === + "logging_steps": 10, + "save_steps": 300, + "save_total_limit": 2, + + # === 评估配置 === + "val_size": 0.1, + "per_device_eval_batch_size": 2, + "eval_strategy": "steps", + "eval_steps": 300, + + # === 硬件配置 === + "fp16": False, + "bf16": True, + "tf32": True, + "dataloader_num_workers": 2, + + # === 其他配置 === + "seed": 42, + "ddp_timeout": 1800, + "report_to": "none", + "run_name": "qwen2.5_7b_sft_training", + } + + def check_and_create_config(self): + """ + Core logic: check config file, read if exists, create if not + """ + # Ensure directory exists + self.config_path.parent.mkdir(parents=True, exist_ok=True) + + if self.config_path.exists(): + # Config file exists, read it + print(f"Found config file: {self.config_path}") + return self._load_existing_config() + else: + # Config file doesn't exist, create default config + print(f"Creating new config file: {self.config_path}") + return self._create_new_config() + + def _load_existing_config(self): + """Load existing config file""" + try: + with open(self.config_path, 'r', encoding='utf-8') as f: + config = yaml.safe_load(f) + print("Config file loaded successfully") + + # Check if new default parameters need to be added + default_config = self.get_default_config() + updated = False + + for key, value in default_config.items(): + if key not in config: + config[key] = value + updated = True + print(f"Added missing parameter: {key}") + + # 移除过时的formatting参数 + if "formatting" in config: + del config["formatting"] + updated = True + print("Removed deprecated parameter: formatting") + + # Save config if updated + if updated: + self._save_config(config) + print("Config file updated") + + return config + + except Exception as e: + print(f"Failed to read config: {e}") + print("Creating new default config") + return self._create_new_config() + + def _create_new_config(self): + """Create new default config file""" + default_config = self.get_default_config() + + if self._save_config(default_config): + print("Default config file created successfully") + return default_config + else: + print("Failed to create config file") + return None + + def _save_config(self, config): + """Save config to file""" + try: + with open(self.config_path, 'w', encoding='utf-8') as f: + yaml.dump(config, f, + default_flow_style=False, + allow_unicode=True, + sort_keys=False, + indent=2, + width=80) + return True + except Exception as e: + print(f"Failed to save config: {e}") + return False + + def update_config(self, updates): + """Update config parameters""" + config = self.check_and_create_config() + if config is None: + return None + + config.update(updates) + if self._save_config(config): + print(f"Config updated: {list(updates.keys())}") + return config + return None + + def print_config_info(self, config): + """Print config information""" + if not config: + return + + print("\n" + "=" * 50) + print("Training Configuration") + print("=" * 50) + + key_info = [ + ("Model", "model_name_or_path"), + ("Dataset", "dataset"), + ("Template", "template"), + ("LoRA Rank", "lora_rank"), + ("Learning Rate", "learning_rate"), + ("Epochs", "num_train_epochs"), + ("Batch Size", "per_device_train_batch_size"), + ("Output Dir", "output_dir"), + ] + + for name, key in key_info: + print(f"{name:<12}: {config.get(key, 'N/A')}") + + effective_batch = config.get("per_device_train_batch_size", 1) * config.get("gradient_accumulation_steps", 1) + print(f"Effective Batch: {effective_batch}") + print("=" * 50) + + def check_environment(self): + """Check training environment""" + print("Checking training environment...") + + # 使用绝对路径 - 直接获取调用者工作目录 + caller_cwd = Path(os.environ.get('PWD', os.getcwd())) + data_dir = caller_cwd / ".cache" / "data" + + # Check data files with detailed info + data_files = [ + str(data_dir / "qa.json"), + str(data_dir / "dataset_info.json") + ] + + for file_path in data_files: + if not Path(file_path).exists(): + print(f"❌ Missing data file: {file_path}") + return False + else: + file_size = Path(file_path).stat().st_size + print(f"✅ Found data file: {file_path} ({file_size} bytes)") + + # 检查qa.json的内容 + try: + import json + qa_file = str(data_dir / "qa.json") + with open(qa_file, 'r', encoding='utf-8') as f: + qa_data = json.load(f) + print(f"✅ QA data loaded: {len(qa_data)} samples") + + if len(qa_data) == 0: + print("❌ QA data is empty! Please check data generation pipeline.") + return False + + # 检查第一个样本的格式 + if qa_data: + sample = qa_data[0] + required_keys = ["instruction", "input", "output"] + missing_keys = [key for key in required_keys if key not in sample] + if missing_keys: + print(f"❌ Missing keys in QA sample: {missing_keys}") + return False + else: + print("✅ QA data format is correct") + + except Exception as e: + print(f"❌ Error checking QA data: {e}") + return False + + print("✅ Data files check passed") + + # Check LlamaFactory + try: + import llamafactory + print("✅ LlamaFactory is installed") + except ImportError: + print("❌ LlamaFactory not installed") + print("Please run: pip install llamafactory[torch,metrics]") + return False + + return True + + def start_training(self): + """Start training""" + if not self.check_environment(): + print("Environment check failed") + return False + + # Load config + config = self.check_and_create_config() + if not config: + print("Failed to load config") + return False + + # Show config info + self.print_config_info(config) + + # Build training command + train_cmd = f"llamafactory-cli train {self.config_path}" + + # Start training + print(f"\nStarting training...") + print(f"Config file: {self.config_path}") + print(f"Command: {train_cmd}") + + try: + result = subprocess.run(train_cmd, shell=True, check=True) + print("Training completed!") + return True + except subprocess.CalledProcessError as e: + print(f"Training failed: {e}") + return False + except KeyboardInterrupt: + print("\nTraining interrupted by user") + return False + + +def main(): + parser = argparse.ArgumentParser(description="LlamaFactory Training Script") + parser.add_argument("--config", default=None, + help="Config file path (default: cache_dir/.cache/train_config.yaml)") + parser.add_argument("--cache", default="./", help="Cache directory path") + parser.add_argument("--update-lr", type=float, + help="Update learning rate") + parser.add_argument("--update-epochs", type=int, + help="Update training epochs") + parser.add_argument("--update-batch-size", type=int, + help="Update batch size") + + args = parser.parse_args() + + # 处理cache_base相对路径 + cache_path = Path(args.cache) + if not cache_path.is_absolute(): + caller_cwd = Path(os.environ.get('PWD', os.getcwd())) + cache_path = caller_cwd / cache_path + + # Create trainer - 如果没有指定config,会自动使用cache目录下的默认路径 + config_path = args.config + if config_path is None: + config_path = str(cache_path / ".cache" / "train_config.yaml") + + trainer = LlamaFactoryTrainer(config_path, cache_base=str(cache_path)) + + # Update parameters if specified + updates = {} + if args.update_lr: + updates["learning_rate"] = args.update_lr + if args.update_epochs: + updates["num_train_epochs"] = args.update_epochs + if args.update_batch_size: + updates["per_device_train_batch_size"] = args.update_batch_size + + if updates: + print("Updating config parameters...") + trainer.update_config(updates) + + # Start training + success = trainer.start_training() + + if success: + print(f"\nOperation completed!") + print(f"Model saved to: {cache_path / '.cache' / 'saves' / 'qwen2.5_7b_sft_model'}") + else: + sys.exit(1) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/path_to_jsonl_script.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/path_to_jsonl_script.py new file mode 100644 index 0000000000000000000000000000000000000000..9ce4b083555f3385422dd198fb8640428325c0ee --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/path_to_jsonl_script.py @@ -0,0 +1,237 @@ +import os +import json +import argparse +from pathlib import Path +from typing import List, Union + + +class PDFDetector: + """PDF file detector for scanning directories and generating JSONL config files""" + + def __init__(self, output_file: str = "./.cache/gpu/pdf_list.jsonl"): + # Handle output path - based on caller's working directory + output_path = Path(output_file) + if not output_path.is_absolute(): + caller_cwd = Path(os.environ.get('PWD', os.getcwd())) + output_file = str(caller_cwd / output_file) + self.output_file = output_file + self.pdf_files = [] + + def scan_directory(self, directory: Union[str, Path], recursive: bool = True) -> List[str]: + """ + Scan PDF files in directory + + Args: + directory: Directory path to scan + recursive: Whether to scan subdirectories recursively + + Returns: + List of found PDF file paths + """ + directory = Path(directory) + + if not directory.exists(): + print(f"Error: Directory '{directory}' does not exist") + return [] + + if not directory.is_dir(): + print(f"Error: '{directory}' is not a valid directory") + return [] + + pdf_files = [] + + # Directories to exclude from scanning + exclude_dirs = {'.cache', '__pycache__', '.git', 'node_modules', '.venv', 'venv', '.env'} + + if recursive: + # Recursively search all subdirectories + pattern = "**/*.pdf" + else: + # Only search current directory + pattern = "*.pdf" + + for pdf_path in directory.glob(pattern): + # Skip if path contains any excluded directory + if any(exclude_dir in pdf_path.parts for exclude_dir in exclude_dirs): + continue + + # Also skip hidden directories (starting with .) + if any(part.startswith('.') and part != '.' for part in pdf_path.parts): + continue + + if pdf_path.is_file(): + # Convert to absolute path + pdf_files.append(str(pdf_path.resolve())) + print(f"Found PDF: {pdf_path}") + + self.pdf_files.extend(pdf_files) + return pdf_files + + def scan_multiple_directories(self, directories: List[Union[str, Path]], recursive: bool = True) -> List[str]: + """ + Scan multiple directories + + Args: + directories: List of directory paths + recursive: Whether to scan recursively + + Returns: + List of all found PDF file paths + """ + all_pdfs = [] + for directory in directories: + pdfs = self.scan_directory(directory, recursive) + all_pdfs.extend(pdfs) + + return all_pdfs + + def add_pdf_file(self, file_path: Union[str, Path]) -> bool: + """ + Manually add a single PDF file + + Args: + file_path: PDF file path + + Returns: + Whether successfully added + """ + file_path = Path(file_path) + + if not file_path.exists(): + print(f"Error: File '{file_path}' does not exist") + return False + + if not file_path.is_file(): + print(f"Error: '{file_path}' is not a file") + return False + + if file_path.suffix.lower() != '.pdf': + print(f"Error: '{file_path}' is not a PDF file") + return False + + abs_path = str(file_path.resolve()) + if abs_path not in self.pdf_files: + self.pdf_files.append(abs_path) + print(f"Added PDF: {file_path}") + return True + else: + print(f"PDF already exists: {file_path}") + return False + + def generate_jsonl(self, output_file: str = None) -> str: + """ + Generate JSONL config file + + Args: + output_file: Output file path, if None use the initialized path + + Returns: + Generated JSONL file path + """ + if output_file is None: + output_file = self.output_file + else: + # Handle output file relative path - based on caller's working directory + output_path = Path(output_file) + if not output_path.is_absolute(): + caller_cwd = Path(os.environ.get('PWD', os.getcwd())) + output_path = caller_cwd / output_path + output_file = str(output_path) + + if not self.pdf_files: + print("Warning: No PDF files found") + return output_file + + # Validate and process output file path + output_path = Path(output_file) + + # If output path is directory, auto-generate filename + if output_path.exists() and output_path.is_dir(): + output_path = output_path / "pdf_list.jsonl" + output_file = str(output_path) + print(f"Warning: Output path is directory, auto-generating filename: {output_file}") + elif output_path.suffix == "": + # If no extension, add .jsonl + output_path = output_path.with_suffix(".jsonl") + output_file = str(output_path) + print(f"Warning: Auto-adding extension: {output_file}") + + # Ensure output directory exists + output_path.parent.mkdir(parents=True, exist_ok=True) + + with open(output_file, 'w', encoding='utf-8') as f: + for pdf_path in self.pdf_files: + # Write in JSONL format + json_line = {"raw_content": pdf_path} + f.write(json.dumps(json_line, ensure_ascii=False) + '\n') + + print(f"Successfully generated JSONL file: {output_file}") + print(f"Contains {len(self.pdf_files)} PDF files") + return output_file + + def preview_results(self, max_items: int = 10): + """Preview detection results""" + if not self.pdf_files: + print("No PDF files found") + return + + print(f"\nDetected {len(self.pdf_files)} PDF files:") + print("-" * 50) + + for i, pdf_path in enumerate(self.pdf_files[:max_items]): + print(f"{i + 1:3d}. {pdf_path}") + + if len(self.pdf_files) > max_items: + print(f"... and {len(self.pdf_files) - max_items} more files") + print("-" * 50) + + def clear_results(self): + """Clear detection results""" + self.pdf_files.clear() + print("Detection results cleared") + + +def main(): + parser = argparse.ArgumentParser(description='Detect PDF files and generate JSONL config file') + parser.add_argument('input_dir', nargs='?', default='./input', + help='Input directory path to scan (default: ./input)') + parser.add_argument('-o', '--output', default='./.cache/gpu/pdf_list.jsonl', + help='Output JSONL file path (default: ./.cache/gpu/pdf_list.jsonl)') + parser.add_argument('-r', '--recursive', action='store_true', default=True, help='Scan subdirectories recursively') + parser.add_argument('--no-recursive', action='store_false', dest='recursive', help='Do not scan subdirectories') + + args = parser.parse_args() + + # Validate input directory - handle relative paths + input_path = Path(args.input_dir) + if not input_path.is_absolute(): + # If relative path, resolve based on caller's working directory + caller_cwd = Path(os.environ.get('PWD', os.getcwd())) + input_path = caller_cwd / input_path + + if not input_path.exists(): + print(f"Error: Input directory '{input_path}' does not exist") + return + + if not input_path.is_dir(): + print(f"Error: '{input_path}' is not a valid directory") + return + + # Create detector + detector = PDFDetector(args.output) + + # Use resolved input directory + input_directory = str(input_path) + + # Scan directory + print(f"Starting directory scan: {input_directory}") + print(f"Recursive mode: {'enabled' if args.recursive else 'disabled'}") + + detector.scan_directory(input_directory, args.recursive) + + # Generate JSONL file + detector.generate_jsonl(output_file=args.output) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/pdf_to_qa_pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/pdf_to_qa_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..92276638833aa71cddfece812809dd18dfdaba7b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/pdf_to_qa_pipeline.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +import argparse +import os +from pathlib import Path +from dataflow.operators.knowledge_cleaning import ( + KBCChunkGeneratorBatch, + FileOrURLToMarkdownConverterLocal, + FileOrURLToMarkdownConverterFlash, + KBCTextCleanerBatch, + KBCMultiHopQAGeneratorBatch, + QAExtractor +) +from dataflow.utils.storage import FileStorage +from dataflow.serving import LocalModelLLMServing_vllm + + +class KBCleaning_batchvllm_GPUPipeline(): + def __init__(self, cache_base="./"): + # 处理cache_base相对路径 + cache_path = Path(cache_base) + if not cache_path.is_absolute(): + caller_cwd = Path(os.environ.get('PWD', os.getcwd())) + cache_path = caller_cwd / cache_path + + self.storage = FileStorage( + first_entry_file_name=str(cache_path / ".cache" / "gpu" / "pdf_list.jsonl"), + cache_path=str(cache_path / ".cache" / "gpu"), + file_name_prefix="batch_cleaning_step", + cache_type="json", + ) + + self.knowledge_cleaning_step1 = FileOrURLToMarkdownConverterLocal( + intermediate_dir=str(cache_path / ".cache"), + mineru_backend="vlm-vllm-engine", # 可选 pipeline, vlm-vllm-engine, vlm-vllm-transformer, vlm-http-client + ) + + # Faster backend by Flash-MinerU + # See de + + # self.knowledge_cleaning_step1 = FileOrURLToMarkdownConverterFlash( + # intermediate_dir="../example_data/KBCleaningPipeline/flash/", + # mineru_model_path="/MinerU2.5-2509-1.2B", # !!! place your local model path here !!! + # # https://huggingface.co/opendatalab/MinerU2.5-2509-1.2B. + # batch_size=4, # batchsize per vllm worker + # replicas=1, # num of vllm workers + # num_gpus_per_replica=0.5, # for ray to schedule vllm workers to GPU, can be float, e.g. 0.5 means each worker uses half GPU, 1 means each worker uses whole GPU + # engine_gpu_util_rate_to_ray_cap=0.9 # actuall GPU utilization for each worker; acturall memory per worker= num_gpus_per_replica * engine_gpu_util_rate_to_ray_cap; this is to avoid OOM, you can set it to 0.9 or 0.8 to leave some buffer for other processes on + # ) + + self.knowledge_cleaning_step2 = KBCChunkGeneratorBatch( + split_method="token", + chunk_size=512, + tokenizer_name="./Qwen2.5-7B-Instruct", + ) + + self.extract_format_qa = QAExtractor( + output_json_file="./.cache/data/qa.json", + ) + + def forward(self): + """执行完整的Pipeline流程""" + print("🔄 Step 1: File/URL to Markdown conversion...") + self.knowledge_cleaning_step1.run( + storage=self.storage.step(), + input_key="raw_content", + output_key="text_path" + ) + + print("🔄 Step 2: Text splitting into chunks...") + self.knowledge_cleaning_step2.run( + storage=self.storage.step(), + ) + + print("🔄 Starting LLM serving...") + self.llm_serving = LocalModelLLMServing_vllm( + hf_model_name_or_path="./Qwen2.5-7B-Instruct", + vllm_max_tokens=2048, + vllm_tensor_parallel_size=1, # 使用的GPU数量 + vllm_gpu_memory_utilization=0.6, # GPU利用率 + vllm_repetition_penalty=1.2 + ) + + self.knowledge_cleaning_step3 = KBCTextCleanerBatch( + llm_serving=self.llm_serving, + lang="en" + ) + + self.knowledge_cleaning_step4 = KBCMultiHopQAGeneratorBatch( + llm_serving=self.llm_serving, + lang="en", + ) + + print("🔄 Step 3: Knowledge cleaning...") + self.knowledge_cleaning_step3.run( + storage=self.storage.step(), + ) + + print("🔄 Step 4: Multi-hop QA generation...") + self.knowledge_cleaning_step4.run( + storage=self.storage.step(), + ) + + print("🔄 Step 5: Extract and format QA...") + self.extract_format_qa.run( + storage=self.storage.step(), + input_qa_key="qa_pairs", + output_instruction_key="instruction", + output_question_key="input", + output_answer_key="output" + ) + + print("✅ Pipeline completed! Output saved to: ./.cache/data/qa.json") + + +def main(): + parser = argparse.ArgumentParser(description="PDF to QA Pipeline") + parser.add_argument("--cache", default="./", help="Cache directory path") + args = parser.parse_args() + + print("🚀 Starting KB Cleaning Pipeline...") + print(f"📄 Input: {args.cache}.cache/gpu/pdf_list.jsonl") + print(f"💾 Cache: {args.cache}.cache/gpu/") + print(f"📤 Output: {args.cache}.cache/data/qa.json") + print("-" * 60) + + model = KBCleaning_batchvllm_GPUPipeline(cache_base=args.cache) + model.forward() + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/__pycache__/llama_factory_trainer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/__pycache__/llama_factory_trainer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa15c20473585e14a20dac1bd8ffdef82b8bc664 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/__pycache__/llama_factory_trainer.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/__pycache__/merge_filter_qa_pairs.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/__pycache__/merge_filter_qa_pairs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d38523dcc285be53b17b20a64e58fb118cbc4f3e Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/__pycache__/merge_filter_qa_pairs.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/__pycache__/text_to_qa_pipeline.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/__pycache__/text_to_qa_pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..707823ed8a282512a5e93e38e900aa4b8782e2fe Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/__pycache__/text_to_qa_pipeline.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/llama_factory_trainer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/llama_factory_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..1e0268f0392cfa291e830a79f970baadda90029c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/llama_factory_trainer.py @@ -0,0 +1,369 @@ +#!/usr/bin/env python3 +""" +LlamaFactory Training Script with YAML Configuration Management +Complete "check-create-read-train" workflow +""" + +import yaml +import os +import sys +import subprocess +import argparse +from pathlib import Path + + +class LlamaFactoryTrainer: + def __init__(self, config_path=None, cache_base="./"): + # 处理cache_base相对路径 - 基于调用者工作目录 + cache_path = Path(cache_base) + if not cache_path.is_absolute(): + caller_cwd = Path(os.environ.get('PWD', os.getcwd())) + cache_path = caller_cwd / cache_path + + self.cache_path = cache_path + + # 如果没有指定config_path,使用cache目录下的默认路径 + if config_path is None: + config_path = str(cache_path / ".cache" / "train_config.yaml") + else: + # 处理config_path相对路径 + config_path_obj = Path(config_path) + if not config_path_obj.is_absolute(): + caller_cwd = Path(os.environ.get('PWD', os.getcwd())) + config_path = str(caller_cwd / config_path_obj) + + self.config_path = Path(config_path) + + def get_default_config(self): + """Get default configuration - 基于最新LlamaFactory标准""" + return { + # === 基础配置 === + "stage": "sft", + "do_train": True, + + # === 模型配置 === + "model_name_or_path": "Qwen/Qwen2.5-7B-Instruct", + "template": "qwen", + "trust_remote_code": True, + + # === 微调方法配置 === + "finetuning_type": "lora", + "lora_target": "all", # 使用 "all" 而不是具体层名 + "lora_rank": 16, + "lora_alpha": 32, + "lora_dropout": 0.05, + + # === 数据集配置 === + "dataset": "kb_qa", + "dataset_dir": str(self.cache_path / ".cache" / "data"), + "cutoff_len": 1024, + "max_samples": None, + "overwrite_cache": True, + "preprocessing_num_workers": 4, + + # === 训练配置 === + "per_device_train_batch_size": 2, + "gradient_accumulation_steps": 4, + "learning_rate": 5e-5, + "num_train_epochs": 2.0, + "lr_scheduler_type": "cosine", + "warmup_ratio": 0.05, + "weight_decay": 0.01, + "max_grad_norm": 1.0, + "optim": "adamw_torch", + + # === 输出配置 === + "output_dir": str(self.cache_path / ".cache" / "saves" / "qwen2.5_7b_sft_model"), + "overwrite_output_dir": True, + "save_only_model": True, + "plot_loss": True, + + # === 日志和检查点 === + "logging_steps": 10, + "save_steps": 300, + "save_total_limit": 2, + + # === 评估配置 === + "val_size": 0.1, + "per_device_eval_batch_size": 2, + "eval_strategy": "steps", + "eval_steps": 300, + + # === 硬件配置 === + "fp16": False, + "bf16": True, + "tf32": True, + "dataloader_num_workers": 2, + + # === 其他配置 === + "seed": 42, + "ddp_timeout": 1800, + "report_to": "none", + "run_name": "qwen2.5_7b_sft_training", + } + + def check_and_create_config(self): + """ + Core logic: check config file, read if exists, create if not + """ + # Ensure directory exists + self.config_path.parent.mkdir(parents=True, exist_ok=True) + + if self.config_path.exists(): + # Config file exists, read it + print(f"Found config file: {self.config_path}") + return self._load_existing_config() + else: + # Config file doesn't exist, create default config + print(f"Creating new config file: {self.config_path}") + return self._create_new_config() + + def _load_existing_config(self): + """Load existing config file""" + try: + with open(self.config_path, 'r', encoding='utf-8') as f: + config = yaml.safe_load(f) + print("Config file loaded successfully") + + # Check if new default parameters need to be added + default_config = self.get_default_config() + updated = False + + for key, value in default_config.items(): + if key not in config: + config[key] = value + updated = True + print(f"Added missing parameter: {key}") + + # 移除过时的formatting参数 + if "formatting" in config: + del config["formatting"] + updated = True + print("Removed deprecated parameter: formatting") + + # Save config if updated + if updated: + self._save_config(config) + print("Config file updated") + + return config + + except Exception as e: + print(f"Failed to read config: {e}") + print("Creating new default config") + return self._create_new_config() + + def _create_new_config(self): + """Create new default config file""" + default_config = self.get_default_config() + + if self._save_config(default_config): + print("Default config file created successfully") + return default_config + else: + print("Failed to create config file") + return None + + def _save_config(self, config): + """Save config to file""" + try: + with open(self.config_path, 'w', encoding='utf-8') as f: + yaml.dump(config, f, + default_flow_style=False, + allow_unicode=True, + sort_keys=False, + indent=2, + width=80) + return True + except Exception as e: + print(f"Failed to save config: {e}") + return False + + def update_config(self, updates): + """Update config parameters""" + config = self.check_and_create_config() + if config is None: + return None + + config.update(updates) + if self._save_config(config): + print(f"Config updated: {list(updates.keys())}") + return config + return None + + def print_config_info(self, config): + """Print config information""" + if not config: + return + + print("\n" + "=" * 50) + print("Training Configuration") + print("=" * 50) + + key_info = [ + ("Model", "model_name_or_path"), + ("Dataset", "dataset"), + ("Template", "template"), + ("LoRA Rank", "lora_rank"), + ("Learning Rate", "learning_rate"), + ("Epochs", "num_train_epochs"), + ("Batch Size", "per_device_train_batch_size"), + ("Output Dir", "output_dir"), + ] + + for name, key in key_info: + print(f"{name:<12}: {config.get(key, 'N/A')}") + + effective_batch = config.get("per_device_train_batch_size", 1) * config.get("gradient_accumulation_steps", 1) + print(f"Effective Batch: {effective_batch}") + print("=" * 50) + + def check_environment(self): + """Check training environment""" + print("Checking training environment...") + + # 使用绝对路径 - 直接获取调用者工作目录 + caller_cwd = Path(os.environ.get('PWD', os.getcwd())) + data_dir = caller_cwd / ".cache" / "data" + + # Check data files with detailed info + data_files = [ + str(data_dir / "qa.json"), + str(data_dir / "dataset_info.json") + ] + + for file_path in data_files: + if not Path(file_path).exists(): + print(f"❌ Missing data file: {file_path}") + return False + else: + file_size = Path(file_path).stat().st_size + print(f"✅ Found data file: {file_path} ({file_size} bytes)") + + # 检查qa.json的内容 + try: + import json + qa_file = str(data_dir / "qa.json") + with open(qa_file, 'r', encoding='utf-8') as f: + qa_data = json.load(f) + print(f"✅ QA data loaded: {len(qa_data)} samples") + + if len(qa_data) == 0: + print("❌ QA data is empty! Please check data generation pipeline.") + return False + + # 检查第一个样本的格式 + if qa_data: + sample = qa_data[0] + required_keys = ["instruction", "input", "output"] + missing_keys = [key for key in required_keys if key not in sample] + if missing_keys: + print(f"❌ Missing keys in QA sample: {missing_keys}") + return False + else: + print("✅ QA data format is correct") + + except Exception as e: + print(f"❌ Error checking QA data: {e}") + return False + + print("✅ Data files check passed") + + # Check LlamaFactory + try: + import llamafactory + print("✅ LlamaFactory is installed") + except ImportError: + print("❌ LlamaFactory not installed") + print("Please run: pip install llamafactory[torch,metrics]") + return False + + return True + + def start_training(self): + """Start training""" + if not self.check_environment(): + print("Environment check failed") + return False + + # Load config + config = self.check_and_create_config() + if not config: + print("Failed to load config") + return False + + # Show config info + self.print_config_info(config) + + # Build training command + train_cmd = f"llamafactory-cli train {self.config_path}" + + # Start training + print(f"\nStarting training...") + print(f"Config file: {self.config_path}") + print(f"Command: {train_cmd}") + + try: + result = subprocess.run(train_cmd, shell=True, check=True) + print("Training completed!") + return True + except subprocess.CalledProcessError as e: + print(f"Training failed: {e}") + return False + except KeyboardInterrupt: + print("\nTraining interrupted by user") + return False + + +def main(): + parser = argparse.ArgumentParser(description="LlamaFactory Training Script") + parser.add_argument("--config", default=None, + help="Config file path (default: cache_dir/.cache/train_config.yaml)") + parser.add_argument("--cache", default="./", help="Cache directory path") + parser.add_argument("--update-lr", type=float, + help="Update learning rate") + parser.add_argument("--update-epochs", type=int, + help="Update training epochs") + parser.add_argument("--update-batch-size", type=int, + help="Update batch size") + + args = parser.parse_args() + + # 处理cache_base相对路径 + cache_path = Path(args.cache) + if not cache_path.is_absolute(): + caller_cwd = Path(os.environ.get('PWD', os.getcwd())) + cache_path = caller_cwd / cache_path + + # Create trainer - 如果没有指定config,会自动使用cache目录下的默认路径 + config_path = args.config + if config_path is None: + config_path = str(cache_path / ".cache" / "train_config.yaml") + + trainer = LlamaFactoryTrainer(config_path, cache_base=str(cache_path)) + + # Update parameters if specified + updates = {} + if args.update_lr: + updates["learning_rate"] = args.update_lr + if args.update_epochs: + updates["num_train_epochs"] = args.update_epochs + if args.update_batch_size: + updates["per_device_train_batch_size"] = args.update_batch_size + + if updates: + print("Updating config parameters...") + trainer.update_config(updates) + + # Start training + success = trainer.start_training() + + if success: + print(f"\nOperation completed!") + print(f"Model saved to: {cache_path / '.cache' / 'saves' / 'qwen2.5_7b_sft_model'}") + else: + sys.exit(1) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/merge_filter_qa_pairs.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/merge_filter_qa_pairs.py new file mode 100644 index 0000000000000000000000000000000000000000..5c5023c8a71163c3665010ad1380df97bf124589 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/merge_filter_qa_pairs.py @@ -0,0 +1,300 @@ +#!/usr/bin/env python3 +import json +import os +import argparse +from pathlib import Path + + +def find_input_file(cache_base="./"): + """Find input file relative to cache_base""" + cache_path = Path(cache_base) + if not cache_path.is_absolute(): + caller_cwd = Path(os.environ.get('PWD', os.getcwd())) + cache_path = caller_cwd / cache_path + + print(f"Cache base directory: {cache_path}") + + # 优先查找 text2qa_step_step3.json + possible_paths = [ + cache_path / ".cache" / "gpu" / "text2qa_step_step3.json", + cache_path / ".cache" / "gpu" / "batch_cleaning_step_step4.json", + cache_path / "cache" / "gpu" / "batch_cleaning_step_step4.json", + cache_path / "batch_cleaning_step_step4.json", + ] + + print("Searching for input file...") + for path in possible_paths: + abs_path = path.resolve() + if abs_path.exists(): + size = abs_path.stat().st_size + print(f"Found input file: {abs_path} ({size} bytes)") + return abs_path + else: + print(f"Not found: {abs_path}") + + print("Input file not found!") + return None + + +def load_qa_data_from_files(data_items, input_file): + """Load QA data from enhanced_chunk_path files""" + all_qa_pairs = [] + + for i, item in enumerate(data_items): + print(f"Processing item {i + 1}/{len(data_items)}: ", end="") + + enhanced_path = item.get('enhanced_chunk_path') + if not enhanced_path: + print("Skip (no enhanced_chunk_path)") + continue + + # Convert to absolute path + if not os.path.isabs(enhanced_path): + input_file_path = Path(input_file) + cache_gpu_dir = input_file_path.parent + cache_dir = cache_gpu_dir.parent + project_root = cache_dir.parent + clean_path = enhanced_path.lstrip('./') + enhanced_path = project_root / clean_path + else: + enhanced_path = Path(enhanced_path) + + if not enhanced_path.exists(): + print(f"Skip (file not exists: {enhanced_path})") + continue + + try: + with open(enhanced_path, 'r', encoding='utf-8') as f: + enhanced_data = json.load(f) + + chunk_qa_pairs = [] + if isinstance(enhanced_data, list): + # enhanced_data is chunk list + for chunk in enhanced_data: + if isinstance(chunk, dict) and 'qa_pairs' in chunk: + qa_data = chunk['qa_pairs'] + if isinstance(qa_data, dict) and 'qa_pairs' in qa_data: + # Double nested: chunk['qa_pairs']['qa_pairs'] + chunk_qa_pairs.extend(qa_data['qa_pairs']) + elif isinstance(qa_data, list): + # Single nested: chunk['qa_pairs'] is directly a list + chunk_qa_pairs.extend(qa_data) + elif isinstance(enhanced_data, dict) and 'qa_pairs' in enhanced_data: + # enhanced_data is single object + qa_data = enhanced_data['qa_pairs'] + if isinstance(qa_data, dict) and 'qa_pairs' in qa_data: + chunk_qa_pairs = qa_data['qa_pairs'] + elif isinstance(qa_data, list): + chunk_qa_pairs = qa_data + + if chunk_qa_pairs and isinstance(chunk_qa_pairs, list): + print(f"Found {len(chunk_qa_pairs)} QA pairs") + all_qa_pairs.extend(chunk_qa_pairs) + else: + print("Skip (no valid QA data)") + continue + + except Exception as e: + print(f"Skip (read failed: {e})") + continue + + return all_qa_pairs + + +def convert_to_alpaca(input_file, output_dir): + """Convert QA data to Alpaca format for LlamaFactory""" + print(f"Reading data file: {input_file}") + print(f"Output directory: {output_dir}") + + # Read main data file + try: + with open(input_file, 'r', encoding='utf-8') as f: + data = json.load(f) + print( + f"Successfully read main data, type: {type(data)}, length: {len(data) if hasattr(data, '__len__') else 'N/A'}") + except Exception as e: + print(f"Failed to read file: {e}") + return None + + if not isinstance(data, list): + print("Expected data in list format") + return None + + # Instruction for the training data + instruction = ( + "Please answer the following question based on the provided text content. " + "Your response should:\n" + "1. Provide accurate information from the source material\n" + "2. Include relevant analysis and reasoning\n" + "3. Reference specific details or examples when applicable\n" + "4. Maintain clarity and precision in your explanation\n\n" + "Focus on delivering factual, well-reasoned answers based on the text content." + ) + + print("Loading QA pairs from enhanced files...") + all_qa_pairs = load_qa_data_from_files(data, input_file) + + if not all_qa_pairs: + print("No QA pairs found! Please check data structure") + return None + + print(f"Total found {len(all_qa_pairs)} QA pairs") + + # Process QA pairs + results = [] + processed_pairs = 0 + + for qa in all_qa_pairs: + if not isinstance(qa, dict): + continue + + # Extract question and answer + question = "" + answer_text = "" + + # Try different possible field names for question + for q_field in ['question', 'Question', 'query', 'Query']: + if q_field in qa and qa[q_field]: + question = qa[q_field].strip() + break + + # Try different possible field names for answer + for a_field in ['answer', 'Answer', 'response', 'Response']: + if a_field in qa and qa[a_field]: + answer_text = qa[a_field].strip() + break + + # Skip empty questions or answers + if not question or not answer_text: + continue + + # Include reasoning steps if available + reasoning_steps = qa.get("reasoning_steps", []) + reasoning_text = "" + if isinstance(reasoning_steps, list): + reasoning_text = "\n".join([ + step.get("step", "").strip() + for step in reasoning_steps + if isinstance(step, dict) and step.get("step", "").strip() + ]) + + # Build output (reasoning process + answer) + if reasoning_text: + output_text = f"{reasoning_text}\n\n{answer_text}" + else: + output_text = answer_text + + results.append({ + "instruction": instruction, + "input": question, + "output": output_text + }) + + processed_pairs += 1 + + print(f"\nProcessing statistics:") + print(f"Found QA pairs: {len(all_qa_pairs)}") + print(f"Valid conversions: {processed_pairs}") + + if not results: + print("No QA pairs converted!") + return None + + # Ensure output directory exists + output_dir.mkdir(parents=True, exist_ok=True) + + # Save as qa.json (LlamaFactory standard format) + qa_file = output_dir / "qa.json" + try: + with open(qa_file, 'w', encoding='utf-8') as f: + json.dump(results, f, ensure_ascii=False, indent=2) + + file_size = qa_file.stat().st_size + print(f"Conversion complete: {len(results)} QA pairs -> {qa_file} ({file_size} bytes)") + + return qa_file + except Exception as e: + print(f"Failed to save file: {e}") + return None + + +def create_llamafactory_config(output_dir): + """Create dataset_info.json for LlamaFactory""" + print("Creating LlamaFactory configuration...") + + dataset_info = { + "kb_qa": { + "file_name": "qa.json", + "columns": { + "prompt": "instruction", + "query": "input", + "response": "output" + } + } + } + + config_file = output_dir / "dataset_info.json" + try: + with open(config_file, 'w', encoding='utf-8') as f: + json.dump(dataset_info, f, ensure_ascii=False, indent=2) + + print(f"LlamaFactory configuration created: {config_file}") + return config_file + except Exception as e: + print(f"Failed to create configuration: {e}") + return None + + +def main(): + parser = argparse.ArgumentParser(description="Convert Step 3 QA data to LlamaFactory format") + parser.add_argument("--cache", default="./", help="Cache directory path") + args = parser.parse_args() + + # Handle cache_base relative path + cache_path = Path(args.cache) + if not cache_path.is_absolute(): + caller_cwd = Path(os.environ.get('PWD', os.getcwd())) + cache_path = caller_cwd / cache_path + + print("Step 3 to LlamaFactory Converter") + print("=" * 50) + print(f"Cache base directory: {cache_path}") + + # Find input file + input_file = find_input_file(str(cache_path)) + if not input_file: + print("\nTips:") + print("1. Ensure Step 3 (Text2QA generation) has been completed") + print("2. Check if .cache/gpu/ directory exists") + print("3. Look for text2qa_step_step3.json file") + exit(1) + + # Output directory + output_dir = cache_path / ".cache" / "data" + + print(f"\nStarting conversion...") + print(f"Input: {input_file}") + print(f"Output directory: {output_dir}") + print("-" * 50) + + # Convert data + qa_file = convert_to_alpaca(input_file, output_dir) + + if qa_file: + # Create config file + config_file = create_llamafactory_config(output_dir) + + if config_file: + print(f"\nConversion completed successfully!") + print(f"Files created:") + print(f" - {qa_file}") + print(f" - {config_file}") + print("Ready for LlamaFactory training!") + else: + print("Configuration file creation failed") + else: + print("Data conversion failed") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/text_to_qa_pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/text_to_qa_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..3e79c3a6a7722b40776e194d9f2da34556606164 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/text_to_qa_pipeline.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +import argparse +import os +from pathlib import Path +from dataflow.operators.knowledge_cleaning import ( + KBCChunkGeneratorBatch, + KBCTextCleanerBatch, + KBCMultiHopQAGeneratorBatch, + QAExtractor +) +# from dataflow.operators.knowledge_cleaning import ( +# CorpusTextSplitterBatch, +# KnowledgeCleanerBatch, +# MultiHopQAGeneratorBatch, +# ) +from dataflow.utils.storage import FileStorage +from dataflow.serving import LocalModelLLMServing_vllm +os.environ['OMP_NUM_THREADS'] = '1' +os.environ['ONNXRUNTIME_THREAD_AFFINITY'] = 'false' + +class Text2QAPipeline: + def __init__(self, cache_base="./"): + # 处理cache_base相对路径 + cache_path = Path(cache_base) + if not cache_path.is_absolute(): + caller_cwd = Path(os.environ.get('PWD', os.getcwd())) + cache_path = caller_cwd / cache_path + + self.storage = FileStorage( + first_entry_file_name=str(cache_path / ".cache" / "gpu" / "text_input.jsonl"), + cache_path=str(cache_path / ".cache" / "gpu"), + file_name_prefix="text2qa_step", + cache_type="json", + ) + + self.text_splitting_step = KBCChunkGeneratorBatch( + split_method="token", + chunk_size=512, + tokenizer_name="Qwen/Qwen2.5-7B-Instruct", + ) + + self.extract_format_qa = QAExtractor( + output_json_file="./.cache/data/qa.json", + ) + + def forward(self): + """执行完整的Pipeline流程""" + print("Step 1: Text splitting into chunks...") + self.text_splitting_step.run( + storage=self.storage.step(), + ) + + print("Starting LLM serving...") + self.llm_serving = LocalModelLLMServing_vllm( + hf_model_name_or_path="Qwen/Qwen2.5-7B-Instruct", + vllm_max_tokens=2048, + vllm_tensor_parallel_size=1, + vllm_gpu_memory_utilization=0.6, + vllm_repetition_penalty=1.2 + ) + + self.knowledge_cleaning_step = KBCTextCleanerBatch( + llm_serving=self.llm_serving, + lang="en" + ) + + self.qa_generation_step = KBCMultiHopQAGeneratorBatch( + llm_serving=self.llm_serving, + lang="en" + ) + + print("Step 2: Knowledge cleaning...") + self.knowledge_cleaning_step.run( + storage=self.storage.step(), + ) + + print("Step 3: Multi-hop QA generation...") + self.qa_generation_step.run( + storage=self.storage.step(), + ) + + print("🔄 Step 4: Extract and format QA...") + self.extract_format_qa.run( + storage=self.storage.step(), + input_qa_key="qa_pairs", + output_instruction_key="instruction", + output_question_key="input", + output_answer_key="output" + ) + + print("Pipeline completed!") + + +def main(): + parser = argparse.ArgumentParser(description="Text to QA Pipeline") + parser.add_argument("--cache", default="./", help="Cache directory path") + args = parser.parse_args() + + print("Starting Text to QA Pipeline...") + print(f"Input: {args.cache}.cache/gpu/text_input.jsonl") + print(f"Cache: {args.cache}.cache/gpu/") + print(f"Output: {args.cache}.cache/gpu/text2qa_step_step3.json") + print("-" * 60) + + model = Text2QAPipeline(cache_base=args.cache) + model.forward() + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5efdb18ebc0e8f6bed824b56f9cf425c74aeebf8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/utils.py @@ -0,0 +1,16 @@ + +import typer +from colorama import init as color_init, Fore, Style +from typing import Optional, Tuple, List +# ---------- helpers ---------- +def _echo(msg: str, color: Optional[str] = None) -> None: + if color == "red": + print(Fore.RED + msg + Style.RESET_ALL) + elif color == "yellow": + print(Fore.YELLOW + msg + Style.RESET_ALL) + elif color == "green": + print(Fore.GREEN + msg + Style.RESET_ALL) + elif color == "cyan": + print(Fore.CYAN + msg + Style.RESET_ALL) + else: + print(msg) \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1261cbb16f160b3fe9bac6daded68cf5b519b351 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__init__.py @@ -0,0 +1,18 @@ +from .operator import OperatorABC, get_operator +from .llm_serving import LLMServingABC +from .wrapper import WrapperABC + +from typing import Union, TypeAlias + +# 定义类型别名 +OPERATOR_CLASSES: TypeAlias = Union[OperatorABC, WrapperABC] +LLM_SERVING_CLASSES: TypeAlias = LLMServingABC # 单一类型也可以这么写 + +__all__ = [ + 'OPERATOR_CLASSES', + 'LLM_SERVING_CLASSES', + 'OperatorABC', + 'get_operator', + 'LLMServingABC', + 'WrapperABC', +] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ae59a4667856751b987139b803612470c0a9ed6 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__pycache__/llm_serving.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__pycache__/llm_serving.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a0f52de0da94e88e78a479b18220ae91d7e4e32 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__pycache__/llm_serving.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__pycache__/operator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__pycache__/operator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99b7c058b3f2571c36ae3de5800ee9666e11c8b1 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__pycache__/operator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__pycache__/prompt.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__pycache__/prompt.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e6ad949d457dfce54f6395f024521b3ca76a5b1 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__pycache__/prompt.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__pycache__/wrapper.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__pycache__/wrapper.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..585f54ff46dd5efea035bbc47cd96f945c99c43a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__pycache__/wrapper.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/llm_serving.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/llm_serving.py new file mode 100644 index 0000000000000000000000000000000000000000..b4be41352b0b76b8387c986c0c0c6416bab48ee2 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/llm_serving.py @@ -0,0 +1,35 @@ +from abc import ABC, abstractmethod +from typing import Any, List + + +class LLMServingABC(ABC): + """Abstract base class for data generators. Which may be used to generate data from a model or API. Called by operators + """ + @abstractmethod + def generate_from_input(self, user_inputs: List[str], system_prompt: str) -> List[str]: + """ + Generate data from input. + input: List[str], the input of the generator + """ + pass + + @abstractmethod + def start_serving(self): + """ + Cleanup the generator and garbage collect all GPU/CPU memory. + """ + pass + + @abstractmethod + def cleanup(self): + """ + Cleanup the generator and garbage collect all GPU/CPU memory. + """ + pass + + def load_model(self, model_name_or_path: str, **kwargs: Any): + """ + Load the model from the given path. + This method is optional and can be overridden by subclasses if needed. + """ + raise NotImplementedError("This method should be implemented by subclasses.") diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/operator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/operator.py new file mode 100644 index 0000000000000000000000000000000000000000..a2e5d383bd70365e5d9e1bdbb39c7c4201b9b0d3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/operator.py @@ -0,0 +1,28 @@ +from abc import ABC, abstractmethod +from dataflow.logger import get_logger +from .prompt import DIYPromptABC, PromptABC + +class OperatorABC(ABC): + def __init__(self): + self.logger = get_logger() + self.ALLOWED_PROMPTS = tuple([type[DIYPromptABC | PromptABC]]) + + @abstractmethod + def run(self) -> None: + """ + Main function to run the operator. + """ + pass + +def get_operator(operator_name, args) -> OperatorABC: + from dataflow.utils import OPERATOR_REGISTRY + print(operator_name, args) + operator = OPERATOR_REGISTRY.get(operator_name)(args) + logger = get_logger() + if operator is not None: + logger.info(f"Successfully get operator {operator_name}, args {args}") + else: + logger.error(f"operator {operator_name} is not found") + assert operator is not None + print(operator) + return operator diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/prompt.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..3f2d2268f1727f1480c4417bd0815e06685a329d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/prompt.py @@ -0,0 +1,107 @@ +from typing import TypeVar, Protocol, Union, get_type_hints,cast +from functools import wraps +import inspect +# from dataflow.core import OperatorABC + +class PromptABC(): + def __init__(self): + pass + def build_prompt(self): + raise NotImplementedError + +class DIYPromptABC(PromptABC): + def __init__(self): + super().__init__() + def build_prompt(self): + raise NotImplementedError + +# class OperatorWithAllowedPrompts(Protocol): +# ALLOWED_PROMPTS: list[type[DIYPromptABC | PromptABC]] + +def _make_diyprompt_union(allowed_prompts: tuple[type[PromptABC], ...]): + """构造一个 Union 类型,包含允许的 prompt + DIYPromptABC 子类 + None""" + return Union[tuple(allowed_prompts) + (DIYPromptABC, type(None))] + +# 泛型参数,表示任意传入的 class 类型 +T = TypeVar("T") + +def prompt_restrict(*allowed_prompts: type[DIYPromptABC]): + """ + 装饰器:限制 prompt_template 只能是指定 Prompt 类 或 DIYPromptABC 子类 + 并在运行时检查 & 更新 __annotations__(供 get_type_hints 等工具使用) + """ + def decorator(cls:T) -> T: + setattr(cls, "ALLOWED_PROMPTS", tuple(allowed_prompts)) + # self.ALLOWED_PROMPTS = list(allowed_prompts) + + orig_init = cls.__init__ + sig = inspect.signature(orig_init) # 在装饰时就解析一次签名,避免每次实例化重复解析 + if "prompt_template" not in sig.parameters: + # 若类的 __init__ 根本没有该形参,就仅维持注解/属性设置,不做运行时检查 + # (你也可以选择在这里直接 raise 来强制类必须声明该参数) + pass + + @wraps(orig_init) + def new_init(self, *args, **kwargs): + # 用签名绑定实参:自动把位置/关键字/默认值对齐到参数名 + try: + bound = sig.bind_partial(self, *args, **kwargs) + bound.apply_defaults() + except TypeError: + # 参数不完整或不匹配时,交给原始 __init__ 去报错更合适 + return orig_init(self, *args, **kwargs) + + pt = bound.arguments.get("prompt_template", None) + + if pt is not None and not isinstance(pt, cls.ALLOWED_PROMPTS): + if not isinstance(pt, DIYPromptABC): + allowed_names = "\n".join( + f" - {c.__module__}.{c.__qualname__}" + for c in cls.ALLOWED_PROMPTS + ) + raise TypeError( + f"[{cls.__name__}] Invalid prompt_template type: " + f"{type(pt).__module__}.{type(pt).__qualname__}\n" + f"Expected one of:\n{allowed_names}\n" + f"or a custom subclass of `dataflow.core.prompt.DIYPromptABC.`" + ) + + return orig_init(self, *args, **kwargs) + + cls.__init__ = new_init + + # 保持你原本的注解暴露逻辑 + cls.__annotations__ = dict(getattr(cls, "__annotations__", {})) + cls.__annotations__["prompt_template"] = _make_diyprompt_union(allowed_prompts) + + return cls + return decorator + + +if __name__ == "__main__": + import pytest + + class A(PromptABC): pass + class B(PromptABC): pass + class MyDIY(DIYPromptABC): pass + class Other(PromptABC): pass + + @prompt_restrict(A, B) + class Op: + def __init__(self, prompt_template=None): + self.prompt_template = prompt_template + + # 关键字参数:允许 + Op(prompt_template=A()) + Op(prompt_template=B()) + Op(prompt_template=MyDIY()) + Op() # None 允许 + + # 位置参数:同样被检测 + Op(A()) # ✅ + Op(MyDIY()) # ✅ + with pytest.raises(TypeError): + Op(Other()) # ❌ 非白名单且非 DIY + + with pytest.raises(TypeError): + Op(object()) # ❌ 完全无关类型 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/wrapper.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..9c1e51ba0363030ed7994a2ffcd80b1740ab28ca --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/wrapper.py @@ -0,0 +1,14 @@ +from abc import ABC, abstractmethod +from dataflow.logger import get_logger + +class WrapperABC(ABC): + """ + Abstract base class for wrappers. + """ + + @abstractmethod + def run(self) -> None: + """ + Main function to run the wrapper. + """ + pass \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/DataflowAgent/agent_test_data.json b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/DataflowAgent/agent_test_data.json new file mode 100644 index 0000000000000000000000000000000000000000..d1c7a221d810d514a40d02550e8d96e3d9d70f94 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/DataflowAgent/agent_test_data.json @@ -0,0 +1,73 @@ +[ + {"instruction": "Barack Obama was born in Hawaii in 1961."}, + {"instruction": "2024年巴黎奥运会将在法国巴黎举行。"}, + {"instruction": "Apple Inc. unveiled the new iPhone at their Cupertino headquarters."}, + {"instruction": "张伟和李雷于2023年5月在北京天安门广场相遇。"}, + {"instruction": "The COVID-19 pandemic started in 2019 and changed the world."}, + {"instruction": "联合国总部位于纽约。"}, + {"instruction": "Elon Musk announced SpaceX's Mars mission will launch in 2026."}, + {"instruction": "上海迪士尼乐园自2016年起对外开放。"}, + {"instruction": "The Nobel Prize in Literature was awarded to Gabriel García Márquez in 1982."}, + {"instruction": "马云是阿里巴巴集团的创始人。"}, + {"instruction": "Microsoft was founded by Bill Gates and Paul Allen in 1975."}, + {"instruction": "乔布斯于2001年推出了第一代iPod。"}, + {"instruction": "The Eiffel Tower is located in Paris, France."}, + {"instruction": "新冠疫苗于2020年底在全球范围内开始接种。"}, + {"instruction": "Angela Merkel served as the Chancellor of Germany until 2021."}, + {"instruction": "北京大学是中国著名的高等学府。"}, + {"instruction": "Tesla delivered over one million cars in 2022."}, + {"instruction": "2022年卡塔尔世界杯吸引了全球大量球迷。"}, + {"instruction": "Mark Zuckerberg is the CEO of Meta Platforms."}, + {"instruction": "阿里巴巴集团于1999年在杭州成立。"}, + {"instruction": "The Grand Canyon is a famous tourist attraction in the United States."}, + {"instruction": "刘亦菲主演的电影《花木兰》于2020年上映。"}, + {"instruction": "NASA plans to return to the Moon by 2025."}, + {"instruction": "小米公司于2010年由雷军创立。"}, + {"instruction": "The Great Wall of China is one of the Seven Wonders of the World."}, + {"instruction": "2021年东京奥运会因疫情推迟一年举行。"}, + {"instruction": "Jeff Bezos stepped down as Amazon's CEO in July 2021."}, + {"instruction": "清华大学位于北京市海淀区。"}, + {"instruction": "Uber launched its ride-sharing service in San Francisco in 2010."}, + {"instruction": "林书豪在2012年掀起了“林疯狂”热潮。"}, + {"instruction": "In the early morning of July 20, 1969, Neil Armstrong became the first human to set foot on the lunar surface, uttering the famous words, 'That's one small step for man, one giant leap for mankind.' This historic event was broadcast live to millions around the world."}, + {"instruction": "据世界卫生组织统计,全球每年有数百万人因空气污染而提前死亡。各国政府正积极采取措施,推动新能源和清洁技术的发展,以减缓环境恶化和气候变化。"}, + {"instruction": "During the Renaissance period, artists such as Leonardo da Vinci and Michelangelo revolutionized European art with their innovative techniques and profound understanding of human anatomy, paving the way for future generations."}, + {"instruction": "2023年,中国高铁总里程突破4万公里,成为全球高铁网络最长的国家。高铁的发展不仅极大便利了人们的出行,也带动了沿线城市的经济增长。"}, + {"instruction": "After years of research, scientists at CERN finally announced the discovery of the Higgs boson particle in 2012, confirming a major prediction of the Standard Model of particle physics and opening new avenues for scientific exploration."}, + {"instruction": "玛丽·居里因其在放射性领域的卓越贡献,成为历史上首位两次获得诺贝尔奖的科学家,她的研究成果对医学和物理学产生了深远影响。"}, + {"instruction": "The Amazon rainforest, often referred to as the 'lungs of the Earth,' is home to an astonishing variety of plant and animal species. However, deforestation poses a serious threat to this vital ecosystem."}, + {"instruction": "2022年,北京冬奥会在全球瞩目下成功举办,来自90多个国家和地区的运动员在冰雪赛场上奋勇拼搏,展现了奥林匹克精神。"}, + {"instruction": "On September 5, 1977, NASA launched the Voyager 1 spacecraft, which has since become the most distant human-made object in space, sending back invaluable data from the outer reaches of our solar system."}, + {"instruction": "随着人工智能和大数据技术的发展,智能助手正在逐步进入人们的日常生活,从语音识别到智能家居,极大地提升了生活便利性。"}, + {"instruction": "In 1994, Nelson Mandela was elected as South Africa’s first Black president, marking the end of decades of apartheid and setting an example of reconciliation and national unity for the world."}, + {"instruction": "2010年上海世博会以“城市,让生活更美好”为主题,吸引了来自世界各地的游客和参展国家,展现了全球城市化进程的最新成果。"}, + {"instruction": "The Internet, which started as a research project in the 1960s, has evolved into a global network connecting billions of people, revolutionizing communication, commerce, and information sharing."}, + {"instruction": "2018年,嫦娥四号成功登陆月球背面,成为人类历史上首个在月球远端实现软着陆的探测器,为月球科学研究提供了宝贵数据。"}, + {"instruction": "The story of Romeo and Juliet, written by William Shakespeare, has been adapted into countless plays, films, and ballets, resonating with audiences for its portrayal of love and tragedy."}, + {"instruction": "近年来,随着健康意识的提升,越来越多的人选择通过运动和科学饮食来改善生活方式,健身房和健康食品市场呈现出快速增长的趋势。"}, + {"instruction": "In 2008, the global financial crisis triggered a severe economic downturn, leading to widespread unemployment, bankruptcies, and significant reforms in the banking and financial sectors."}, + {"instruction": "2020年新冠疫情爆发后,全球多国实施了严格的旅行限制和居家隔离措施,推动了远程办公和在线教育的快速普及。"}, + {"instruction": "Mount Everest, the world’s highest peak, attracts climbers from around the globe who brave extreme conditions in pursuit of the summit, often facing challenges such as avalanches and altitude sickness."}, + {"instruction": "大熊猫是中国的国宝,因其独特的黑白外貌和温顺的性格深受人们喜爱。近年来,保护大熊猫及其栖息地已成为全球共同关注的话题。"}, + {"instruction": "In the realm of computer science, the development of quantum computing promises to solve complex problems that are currently intractable for classical computers, potentially transforming industries ranging from cryptography to pharmaceuticals."}, + {"instruction": "2021年,东京奥运会在推迟一年后如期举行,尽管受到疫情影响,运动员们依然展现了顽强的拼搏精神和卓越的竞技水平。"}, + {"instruction": "The Sahara Desert, spanning across North Africa, is the largest hot desert in the world. Its harsh environment has shaped the cultures and lifestyles of the people living on its fringes."}, + {"instruction": "随着新能源汽车技术的进步,电动汽车在全球范围内逐渐普及,许多国家出台了鼓励政策,推动绿色出行和环境保护。"}, + {"instruction": "In the world of literature, magical realism is a genre that combines realistic narrative with surreal elements, as exemplified by the works of Gabriel García Márquez and Haruki Murakami."}, + {"instruction": "2019年,5G商用网络在中国、美国、韩国等国家正式上线,为移动互联网和物联网的发展带来了全新的机遇和挑战。"}, + {"instruction": "The Great Barrier Reef, located off the coast of Australia, is the largest coral reef system on Earth, but it faces significant threats from climate change and pollution."}, + {"instruction": "近年来,短视频平台的兴起极大地改变了人们的娱乐和社交方式,推动了内容创作和数字营销的新模式。"}, + {"instruction": "In 1963, Martin Luther King Jr. delivered his iconic 'I Have a Dream' speech during the March on Washington, becoming a symbol of the civil rights movement in the United States."}, + {"instruction": "2022年,全球气候变暖问题持续加剧,各地极端天气频发,科学家呼吁各国加强合作,共同应对环境挑战。"}, + {"instruction": "The International Space Station, a collaborative effort between multiple countries, serves as a microgravity laboratory for scientific research and technological innovation."}, + {"instruction": "在中国传统文化中,春节是最重要的节日之一,人们通过贴春联、放鞭炮、团圆饭等方式庆祝新年,祈求幸福安康。"}, + {"instruction": "Advancements in medical technology, such as gene editing and personalized medicine, hold great promise for the treatment of previously incurable diseases."}, + {"instruction": "2023年,全球芯片短缺问题对汽车、电子和通信等行业产生了重大影响,企业纷纷调整供应链策略以应对危机。"}, + {"instruction": "The Louvre Museum in Paris is home to some of the world’s most famous artworks, including the Mona Lisa and the Venus de Milo, attracting millions of visitors each year."}, + {"instruction": "近年来,随着环保理念的普及,越来越多的企业开始采用可再生能源和绿色生产工艺,推动可持续发展。"}, + {"instruction": "In 2017, astronomers detected gravitational waves from the collision of two neutron stars, providing new insights into the origins of heavy elements in the universe."}, + {"instruction": "2022年中国航天员乘坐神舟十四号飞船成功进入中国空间站,进行一系列科学实验和空间建设任务,标志着中国载人航天进入新阶段。"}, + {"instruction": "The ancient city of Rome, with its rich history and architectural marvels such as the Colosseum and the Pantheon, continues to fascinate tourists and historians alike."}, + {"instruction": "近年来,心理健康问题受到社会广泛关注,越来越多的人开始重视心理疏导和压力管理,心理咨询服务需求不断增长。"}, + {"instruction": "Climate activists around the globe have organized rallies and campaigns to raise awareness about environmental issues, urging governments and corporations to take meaningful action."} +] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/GeneralTextPipeline/filtering.json b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/GeneralTextPipeline/filtering.json new file mode 100644 index 0000000000000000000000000000000000000000..7f8895cfb815de99b65ad86f31e05d82feb6f723 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/GeneralTextPipeline/filtering.json @@ -0,0 +1,32 @@ +[ + { + "score": 0.9, + "status": "valid", + "comment": "Good and excellent effort done", + "remark": null + }, + { + "score": 1.0, + "status": "pending", + "comment": "Needs review", + "remark": "note" + }, + { + "score": 0.75, + "status": "reviewed", + "comment": "excellent review completed", + "remark": "confirmed" + }, + { + "score": 1.1, + "status": "rejected", + "comment": "all done", + "remark": null + }, + { + "score": 0.7, + "status": "unknown", + "comment": null, + "remark": "okay" + } +] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/GeneralTextPipeline/pandas.json b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/GeneralTextPipeline/pandas.json new file mode 100644 index 0000000000000000000000000000000000000000..f3ff8d408661e908aac386635243d91c306aff1e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/GeneralTextPipeline/pandas.json @@ -0,0 +1,7 @@ +[ + { "id": 1, "name": "Alice", "score": 82.5, "status": "active", "comment": "Excellent job!", "age": 23 }, + { "id": 2, "name": "Bob", "score": 91.0, "status": "inactive", "comment": "Needs improvement", "age": 27 }, + { "id": 3, "name": "Charlie", "score": 67.0, "status": "active", "comment": "Average performance", "age": 22 }, + { "id": 4, "name": "Diana", "score": 88.5, "status": "active", "comment": "Great!", "age": 30 }, + { "id": 5, "name": "Eve", "score": 79.0, "status": "inactive", "comment": "Well done", "age": 24 } +] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/KBCleaningPipeline/bitter_lesson.pdf b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/KBCleaningPipeline/bitter_lesson.pdf new file mode 100644 index 0000000000000000000000000000000000000000..f5c62bbb2194ec9533d423dfa6a974a670c102e0 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/KBCleaningPipeline/bitter_lesson.pdf differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/KBCleaningPipeline/kbc_placeholder.json b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/KBCleaningPipeline/kbc_placeholder.json new file mode 100644 index 0000000000000000000000000000000000000000..0637a088a01e8ddab3bf3fa98dbe804cbde1a0dc --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/KBCleaningPipeline/kbc_placeholder.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/KBCleaningPipeline/test.doc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/KBCleaningPipeline/test.doc new file mode 100644 index 0000000000000000000000000000000000000000..39ff96236e5747336f75ecb8fb848d3cbb781a5b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/KBCleaningPipeline/test.doc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/PDF2VQAPipeline/math_answer.pdf b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/PDF2VQAPipeline/math_answer.pdf new file mode 100644 index 0000000000000000000000000000000000000000..a28b79557f279b305cfd551d383ca95dfff1f63c Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/PDF2VQAPipeline/math_answer.pdf differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/PDF2VQAPipeline/math_question.pdf b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/PDF2VQAPipeline/math_question.pdf new file mode 100644 index 0000000000000000000000000000000000000000..d501a777b9dc5e88194465f3cee6380380bc8a89 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/PDF2VQAPipeline/math_question.pdf differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/PDF2VQAPipeline/questionextract_test.pdf b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/PDF2VQAPipeline/questionextract_test.pdf new file mode 100644 index 0000000000000000000000000000000000000000..5348f340ff4a41d638f078c078e9d3f853fcefb2 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/PDF2VQAPipeline/questionextract_test.pdf differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/ReasoningPipeline/pipeline_general.json b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/ReasoningPipeline/pipeline_general.json new file mode 100644 index 0000000000000000000000000000000000000000..026db07289b3ed1754827940b11c05a6a5046669 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/ReasoningPipeline/pipeline_general.json @@ -0,0 +1,62 @@ +[ + { + "instruction": "A recent clinical study compared two treatments for chronic back pain. What were the main findings regarding patient-reported pain reduction over six months?", + "output": "The study found that patients receiving Treatment A reported an average pain reduction of 45% over six months, compared to a 30% reduction for those on Treatment B. Additionally, quality-of-life scores improved more significantly in the Treatment A group.", + "golden_answer": "Treatment A led to greater pain reduction (45% vs. 30%).", + "source": "Medical_clinical" + }, + { + "instruction": "In the last quarter, a commercial bank reported a rise in its non-performing loan ratio from 2.1% to 3.4%. What might this indicate about the bank's loan portfolio?", + "output": "This increase suggests that more borrowers are struggling to repay their loans, potentially due to economic slowdowns or tighter household finances. It indicates a deterioration in the quality of the bank’s loan assets and may lead to increased provisions.", + "golden_answer": "Higher credit risk due to more troubled loans.", + "source": "Finance_banking" + }, + { + "instruction": "A city government launched a free vaccination drive. How did it impact the reported cases of influenza compared to the previous year?", + "output": "The campaign resulted in a 40% decline in reported influenza cases compared to the same period last year, indicating substantial community-level protection due to increased vaccination coverage.", + "golden_answer": "Cases fell by 40%.", + "source": "Public_health" + }, + { + "instruction": "Why do investors typically diversify their portfolios across different asset classes?", + "output": "Diversification reduces overall investment risk by spreading exposure across assets that may not move in the same direction. It helps protect against significant losses if one sector underperforms, leading to more stable returns over time.", + "golden_answer": "To reduce risk and stabilize returns.", + "source": "Finance_investing" + }, + { + "instruction": "What are some social consequences of long-term unemployment in a community?", + "output": "Long-term unemployment can lead to increased poverty, higher rates of mental health issues like depression, strained family relationships, and potentially higher crime rates as economic hardship intensifies.", + "golden_answer": "Increased poverty, mental health issues, family strain.", + "source": "Social_studies" + }, + { + "instruction": "A pharmaceutical company is conducting Phase III trials for a new cancer drug. What is the primary objective of this phase?", + "output": "The main goal of Phase III trials is to confirm the drug's effectiveness, monitor side effects on a larger scale, compare it to standard treatments, and gather information to ensure it can be used safely in the general population.", + "golden_answer": "To confirm efficacy and monitor safety on a large scale.", + "source": "Medical_trials" + }, + { + "instruction": "A national survey shows that 65% of respondents believe climate change policies should be stricter. What does this indicate about public sentiment?", + "output": "This suggests a strong majority support for more aggressive measures to combat climate change, which could influence future policy decisions and encourage governments to implement stricter regulations.", + "golden_answer": "Majority support stricter climate policies.", + "source": "Social_opinion" + }, + { + "instruction": "Explain why compound interest leads to faster growth of investments compared to simple interest.", + "output": "Compound interest earns interest on both the initial principal and the accumulated interest from previous periods, creating a snowball effect. In contrast, simple interest only earns on the original principal, so growth is linear rather than exponential.", + "golden_answer": "It earns interest on interest, accelerating growth.", + "source": "Finance_concepts" + }, + { + "instruction": "A triangle has sides of lengths 7, 24, and 25. Determine if it is a right triangle.", + "output": "We can check using the Pythagorean theorem: 7² + 24² = 49 + 576 = 625, and 25² = 625. Since they are equal, the triangle is indeed a right triangle.", + "golden_answer": "Yes, it is a right triangle.", + "source": "Math_geometry" + }, + { + "instruction": "In a study involving 400 patients with hypertension, 300 were able to reduce their blood pressure below 140/90 mmHg after six months on a new treatment. What does this imply?", + "output": "This implies a success rate of 75%, indicating the treatment is effective for a significant majority of patients in managing hypertension.", + "golden_answer": "75% achieved target blood pressure.", + "source": "Medical_statistics" + } +] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/ReasoningPipeline/pipeline_general_short.json b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/ReasoningPipeline/pipeline_general_short.json new file mode 100644 index 0000000000000000000000000000000000000000..044b09e99639c8381e4ee63bfe84cb9700d0aab6 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/ReasoningPipeline/pipeline_general_short.json @@ -0,0 +1,20 @@ +[ + { + "instruction": "A recent clinical study compared two treatments for chronic back pain. What were the main findings regarding patient-reported pain reduction over six months?", + "output": "The study found that patients receiving Treatment A reported an average pain reduction of 45% over six months, compared to a 30% reduction for those on Treatment B. Additionally, quality-of-life scores improved more significantly in the Treatment A group.", + "golden_answer": "Treatment A led to greater pain reduction (45% vs. 30%).", + "source": "Medical_clinical" + }, + { + "instruction": "In the last quarter, a commercial bank reported a rise in its non-performing loan ratio from 2.1% to 3.4%. What might this indicate about the bank's loan portfolio?", + "output": "This increase suggests that more borrowers are struggling to repay their loans, potentially due to economic slowdowns or tighter household finances. It indicates a deterioration in the quality of the bank’s loan assets and may lead to increased provisions.", + "golden_answer": "Higher credit risk due to nothing.", + "source": "Finance_banking" + }, + { + "instruction": "A city government launched a free vaccination drive. How did it impact the reported cases of influenza compared to the previous year?", + "output": "The campaign resulted in a 40% decline in reported influenza cases compared to the same period last year, indicating substantial community-level protection due to increased vaccination coverage.", + "golden_answer": "Cases fell by 40%.", + "source": "Public_health" + } +] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/ReasoningPipeline/pipeline_math.json b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/ReasoningPipeline/pipeline_math.json new file mode 100644 index 0000000000000000000000000000000000000000..c4a15b0383e85ddd25bb96d8997580c096501e90 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/ReasoningPipeline/pipeline_math.json @@ -0,0 +1,1778 @@ +[ + { + "instruction":"An architect is designing a reflective surface for a concert hall in the shape of a horizontal hyperbola with its center at the origin. The two foci of the hyperbola are 8 meters apart, and for acoustic reasons the angle between its asymptotes must be 90°. In addition, one of its directrices is the vertical line x = –d. \n \n(a) Find the value of d.\n \n(b) Determine the equation of the hyperbola.", + "output":null, + "golden_answer":"8", + "source":"Bigmath_synth" + }, + { + "instruction":"A certain number is processed differently depending on whether it is even or odd:\n• If the number is even, it is first divided by 2, then multiplied by 5, and finally 4 is added, giving a result of 34.\n• If the number is odd, it is first divided by 3, then multiplied by 7, and finally 2 is subtracted, yielding 33.\nDetermine all possible original numbers.", + "output":"Let x be the original number.\n\nCase 1: x is even.\n (x÷2)·5 + 4 = 34 \n ⇒ 5x\/2 + 4 = 34 \n ⇒ 5x\/2 = 30 \n ⇒ x = 12. \n (12 is even, so this is valid.)\n\nCase 2: x is odd.\n (x÷3)·7 – 2 = 33 \n ⇒ 7x\/3 – 2 = 33 \n ⇒ 7x\/3 = 35 \n ⇒ x = 15. \n (15 is odd, so this is valid.)\n\nAnswer: The only possible originals are 12 (in the even‐case) or 15 (in the odd‐case).", + "golden_answer":"15", + "source":"Bigmath_synth" + }, + { + "instruction":"A bakery sells muffins and croissants. Each muffin is priced at $3, while each croissant is sold for 1.5 times the muffin price. In addition, every croissant incurs an extra packaging fee of $0.50. On a certain day, the bakery sells 15 croissants along with an unknown number of muffins, and the total revenue collected is $90. How many muffins were sold that day?", + "output":"Let x be the number of muffins. \nMuffin revenue = 3·x. \nCroissant revenue = (1.5·3 + 0.5)·15 = (4.5 + 0.5)·15 = 5·15 = 75. \nTotal revenue = 3x + 75 = 90 \n⇒ 3x = 15 \n⇒ x = 5. \n\nSo they sold 5 muffins.", + "golden_answer":"5", + "source":"Bigmath_synth" + }, + { + "instruction":"Alpha, Bravo, and Charlie all start running at the same time around a circular track. Alpha completes one lap in 130 seconds, and Charlie does so in 170 seconds. Bravo, however, runs each lap in 135 seconds but must take a mandatory 10‐second hydration break immediately after finishing each lap—so his effective time per lap is 135 + 10 = 145 seconds. \n\nDetermine the total time in minutes from the start until the fourth occurrence (including the start as the first occurrence) when all three cross the starting line simultaneously. Also, state whether this elapsed time is less than 40 minutes.", + "output":"Let A, B, C denote Alpha, Bravo and Charlie and let t be a time (in seconds) at which they are all simultaneously on the start–finish line. We have\n\n • Alpha laps in 130 s ⇒ A crosses whenever t≡0 (mod 130). \n • Charlie laps in 170 s ⇒ C crosses whenever t≡0 (mod 170). \n • Bravo runs a 135 s lap and then sits 10 s ⇒ his effective cycle is 135+10=145 s, so he crosses the line every 145 s ⇒ t≡0 (mod 145). \n\nHence the common crossing times (including t=0 at the start) are exactly the multiples of\n\n LCM(130, 145, 170)\n \nLet us factor:\n\n 130=2·5·13 \n 145=5·29 \n 170=2·5·17 \n\nso\n\n LCM=2·5·13·17·29=64 090 s. \n\nThus the simultaneous crossings occur at\n t=0, 64 090 s, 2·64 090=128 180 s, 3·64 090=192 270 s, … \n\nIf we count t=0 as the 1st occurrence, then the 4th occurrence is at\n t=3·64 090=192 270 s. \n\nIn minutes that is\n\n 192 270 s ÷ 60 = 3 204.5 minutes,\n\nwhich is obviously far more than 40 minutes.", + "golden_answer":"40", + "source":"Bigmath_synth" + }, + { + "instruction":"A retail shop generated revenue from two products. Product A brought in $2001. Product B was sold through two channels: in‐store and online. In‐store sales contributed 60% of Product B’s pre‑tax revenue, while online sales (making up the remaining 40%) were subject to a 4% sales tax. The combined revenue from both products—counting the tax on online sales—was $3017. Determine the pre‑tax revenue earned from the in‑store and online sales of Product B.", + "output":"Let x = the total pre‐tax revenue of Product B. \nThen \n  in‐store = 0.60 x \n  online = 0.40 x \n\nBecause online sales incur a 4% tax, the revenue collected from online (including tax) is 1.04 · (0.40 x) = 0.416 x. \nThe total revenue (Product A + in‐store B + taxed online B) is \n  2001 + 0.60 x + 0.416 x = 3017 \nSo \n  1.016 x = 3017 − 2001 = 1016 \n  x = 1016 \/ 1.016 = 1000 \n\nHence, pre‐tax revenues for B are: \n  In‐store: 0.60·1000 = $600 \n  Online: 0.40·1000 = $400", + "golden_answer":"400", + "source":"Bigmath_synth" + }, + { + "instruction":"A tech company creates security codes for its devices. Each code is a 4‐character sequence formed using the letters D, E, and F. The code must include each letter at least once, and the same letter cannot appear consecutively. Additionally, if the code begins with D, then exactly two of the characters in the code must be E. How many unique security codes satisfy these conditions? Express your answer as a single integer.", + "output":"To organize the count, break into two cases by first letter:\n\nCase 1: starts with D. \n  – By the “if it begins with D” clause, it must have exactly two E’s in the four positions. With one D already in front that leaves E,E,F to place in positions 2–4. \n  – We also cannot have any two identical letters adjacent. Of the three multiset‐permutations of E,E,F only E F E avoids an E–E back‐to‐back. \n  ∴ case 1 contributes 1 code: D E F E.\n\nCase 2: starts with E or F. \n  – Now there is no extra E‐count restriction, but we do require (i) no repeats adjacent, (ii) at least one of each D,E,F somewhere. \n\n(A) Starts with E: \n Positions 2–4 can be built freely (no two in a row the same and pos 2≠E), giving 2³=8 total. Of those 8, exactly 2 fail to include a D and F in 2–4, so 8–2=6 actually contain D,F at least once (together with the leading E this ensures all three appear). \n \n(B) Starts with F: \n Symmetrically, we get another 8 total no‐repeat sequences in 2–4, of which 2 are missing one of {D,E} there, so 8–2=6 that do contain both D and E (and the leading F). \n\n∴ case 2 contributes 6+6=12 codes\n\nGrand total = case 1 + case 2 = 1 + 12 = 13.", + "golden_answer":"13", + "source":"Bigmath_synth" + }, + { + "instruction":"An artist is designing a tiled mosaic. The finished design must use a total number of tiles that can be arranged in equal rows with either 8, 10, or 12 tiles per row (with no tile left over). In addition, exactly 25% of the total tiles will be accent tiles, and these accent tiles must themselves be able to be arranged in equal rows of 8, 10, or 12 (again with no leftover tiles). What is the smallest total number of tiles the artist can use in the mosaic?", + "output":"480", + "golden_answer":"480", + "source":"Bigmath_synth" + }, + { + "instruction":"A manufacturer applies several successive adjustments to the cost of producing a gadget. First, a reprocessing error causes the cost to be multiplied by –4. Next, an efficiency upgrade reduces the cost effect by a factor of 8 (i.e. the current value is divided by 8). Then, a quality improvement adjustment is made by multiplying the result by –3\/2. These operations are performed in the order given (from left to right). Finally, an additional handling fee scales the adjusted cost by an extra factor of 1\/3. What is the overall multiplier effect on the original cost? Express your answer as a simplified fraction.", + "output":"The overall multiplier is \n(–4) × (1\/8) × (–3\/2) × (1\/3) \n= (–4\/1)·(1\/8)·(–3\/2)·(1\/3) \n= 1\/4.", + "golden_answer":"4", + "source":"Bigmath_synth" + }, + { + "instruction":"A furniture maker plans to build decorative tables for a showroom. Each table requires 3 pine planks and 2 oak planks. The maker has 12 pine logs already available, and each pine log can be cut to yield 5 pine planks. Because the number of pine planks exactly determines the number of tables that can be built, he will buy oak logs only to supply the matching oak planks needed. If each oak log can be cut to yield 10 oak planks, how many tables can be built in total and how many oak logs must he purchase to complete the project?", + "output":"He can get 12 logs×5 planks\/log = 60 pine planks, which makes 60\/3 = 20 tables. \nFor 20 tables he needs 20×2 = 40 oak planks, and at 10 planks per log that’s 40\/10 = 4 oak logs. \nAnswer: 20 tables and 4 oak logs.", + "golden_answer":"4", + "source":"Bigmath_synth" + }, + { + "instruction":"A picture frame is to be made by joining three ribbons end‐to‐end to form a triangle. Two of the ribbons are 8 cm and 13 cm long, while the third ribbon has an integer length x cm. In addition, because of shipping restrictions, the total perimeter of the frame must be less than 40 cm. Determine the sum of all possible whole number values of x that allow the ribbons to form a triangle and satisfy the perimeter restriction.", + "output":"First, the triangle‐inequalities give\n\n1. 8 + 13 > x ⇒ x < 21 \n2. 8 + x > 13 ⇒ x > 5 \n3. 13 + x > 8 ⇒ x > –5 (automatic once x>5)\n\nSo from (1) and (2) we get 6 ≤ x ≤ 20 (integer).\n\nNext, the perimeter restriction is\n 8 + 13 + x < 40 \n⇒ 21 + x < 40 \n⇒ x < 19 \n⇒ x ≤ 18.\n\nCombining: 6 ≤ x ≤ 18. These are the 13 integers 6,7,8,…,18. Their sum is\n\n (6 + 18)·13\/2 = 24·13\/2 = 12·13 = 156.\n\nAnswer: 156.", + "golden_answer":"156", + "source":"Bigmath_synth" + }, + { + "instruction":"An online retailer is launching a special promotion by distributing three‐digit discount codes. A discount code is valid only if it satisfies all of the following conditions:\n • The product of its digits equals 24.\n • The sum of its digits is an even number.\n • The tens digit is a prime number.\nDetermine the total number of valid discount codes. Provide your answer as a single integer.", + "output":"4", + "golden_answer":"4", + "source":"Bigmath_synth" + }, + { + "instruction":"Julian is hosting a themed dinner party and prepares a rectangular chocolate cake cut into exactly 20 equal pieces for himself and his four guests: Maya, Ian, Zoe, and Evan. Their cake‐eating habits are as follows:\n\n1. Julian takes 2 pieces.\n2. Maya, being health‐conscious, takes 15% of Julian’s share (if 15% is not a whole number, she rounds up to the next whole piece).\n3. Ian is moderately hungry and takes 1.5 times as many pieces as Julian.\n4. Zoe loves cake and takes 3 pieces plus, if available, every extra piece that would have made Ian’s share exceed his planned 1.5×Julian; that is, if Ian’s designated number of pieces (from rule 3) cannot be fully taken because of limited supply, Zoe claims the “overflow” portion.\n5. Evan is very hungry and intends to take twice as many pieces as Julian; however, if the remaining pieces after everyone else has taken their share are fewer than his intended amount, he takes all the remaining pieces instead.\n\nAssuming the pieces are distributed in the order given above (Julian, then Maya, then Ian, then Zoe, and finally Evan), determine the ratio of the number of pieces Evan actually eats to the number of pieces Julian eats. (Note: In solving this problem, you must consider the case where there may not be enough pieces left for Evan’s full intended share.)", + "output":"Here’s the step‑by‑step tally (out of 20 pieces), in the order given:\n\n1. Julian takes 2 → 20 − 2 = 18 left \n2. Maya takes ceil(15% of 2)=ceil(0.3)=1 → 18 − 1 = 17 left \n3. Ian takes 1.5×2=3 → 17 − 3 = 14 left \n4. Zoe takes her fixed 3 pieces; Ian wasn’t shorted, so no “overflow” → 14 − 3 = 11 left \n5. Evan intends 2×2=4, and there are 11 left (≥4), so he takes 4 → 11 − 4=7 leftover \n\nEvan ends up with 4 pieces, Julian 2 pieces, so the ratio Evan : Julian = 4 : 2 = 2 : 1.", + "golden_answer":"1", + "source":"Bigmath_synth" + }, + { + "instruction":"Alex has 90 candies and 40 stickers. He wants to pack these into gift bags so that every bag contains exactly 6 candies. In addition, each bag will receive either 3 stickers or 2 stickers. If Alex must use all the candies and stickers and he packs more bags with 3 stickers than with 2 stickers, how many gift bags does he create?", + "output":"Let x = number of bags with 3 stickers, and y = number with 2 stickers. \nThen \n• Candies: 6(x+y) = 90 ⇒ x+y = 15 \n• Stickers: 3x + 2y = 40 \n\nSubstitute y = 15−x into the sticker‐count: \n3x + 2(15−x) = 40 \n3x + 30 − 2x = 40 \nx = 10, so y = 5. \n\nTotal bags = x+y = 10+5 = 15.", + "golden_answer":"15", + "source":"Bigmath_synth" + }, + { + "instruction":"A logistics company assigns tracking codes (represented by colors) to shipments, whose weights can be any positive real number. The following rules must be observed:\n • If two shipments have weights whose ratio is exactly 2 or exactly 5, then they must be assigned different tracking codes.\n • Every shipment weighing between 50 kg and 100 kg must be given a tracking code that is not used for any shipments weighing less than 50 kg or more than 100 kg.\n\nWhat is the minimum number of tracking codes required to label all shipments while satisfying these rules?", + "output":"We can think of “weight‐” as points on the real line via x=ln w. Then “cannot be same color if ratio 2 or 5” becomes “cannot be same color if x differ by a=ln 2 or b=ln 5.” Also the interval B = [ln 50, ln 100] must carry a palette disjoint from the rest (A∪C = (−∞, ln 50)∪(ln 100, +∞)).\n\n1. On B itself the only forbidden pair is 50↔100 (distance ln 2), so B needs 2 colors.\n2. On A∪C one has an infinite graph with edges at ±a and ±b. Since ln 2∕ln 5 is irrational there are no non‐trivial cycles, so this graph is bipartite and needs exactly 2 colors.\n3. By the rule “B’s colors must be disjoint from A∪C’s,” the total is 2+(2)=4.\n\nHence 4 tracking codes suffice and are necessary.", + "golden_answer":"4", + "source":"Bigmath_synth" + }, + { + "instruction":"A factory’s production efficiency factor is modeled by the expression (m + 3)\/(m + 4) + 2\/(m + 4), where m (in months) measures the time since the last equipment upgrade and m ≠ –4. \n a) Express the overall efficiency factor in its simplest algebraic form. \n b) For what value of m does the factory achieve an efficiency factor of 1.2?", + "output":"a) Combine the fractions over the common denominator (m + 4): \n (m + 3)\/(m + 4) + 2\/(m + 4) \n = [ (m + 3) + 2 ] \/ (m + 4) \n = (m + 5) \/ (m + 4). \n\nb) Set (m + 5)\/(m + 4) = 1.2 = 6\/5 and solve for m: \n 5(m + 5) = 6(m + 4) \n 5m + 25 = 6m + 24 \n 25 – 24 = 6m – 5m \n 1 = m. \n\nSo the factory reaches an efficiency factor of 1.2 when m = 1 month.", + "golden_answer":"1", + "source":"Bigmath_synth" + }, + { + "instruction":"Two numbers represent the amounts (in dollars) of two different investments. It is known that the difference between the investments, the sum of the investments, and 10% of their product are in the ratio 1 : 9 : 36. Find the product of the two investments. Express your answer as a single integer.", + "output":"Let the investments be x and y with x > y. Then\n\nx–y : x+y : 0.1xy = 1 : 9 : 36.\n\nSo x–y = k, x+y = 9k ⇒ x = 5k, y = 4k. And 0.1·(5k·4k)=36k ⇒ 2k²=36k ⇒ k=18.\n\nHence x=90, y=72 and xy=90·72=6480.", + "golden_answer":"6480", + "source":"Bigmath_synth" + }, + { + "instruction":"An isosceles triangle has equal sides of 6 units and a base of 8 units. Construct the following composite figure:\n• At each vertex of the triangle, draw two distinct circular arcs with centers at that vertex. The first arc has a radius of 2 units and the second a radius of 7 units; both arcs are drawn outward from the triangle.\n• Additionally, at the midpoint of the base, attach a 90° circular sector with a radius of 1 unit extending outward.\nDetermine the minimum possible width of a strip bounded by two parallel lines that can completely enclose this entire composite figure. (You must analyze and compare the extremal contributions of the triangle, the four arcs, and the circular sector in order to find the optimal orientation minimizing the strip’s width.)", + "output":"Let the triangle be placed so that its base runs from A=(−4,0) to B=(+4,0) and its apex is at \n C=(0,h) with h=√(6²−4²)=2√5 ≃4.472. \nAt each of the three vertices A, B, C we have two “outward” circular arcs of radii 2 and 7; and at the midpoint M=(0,0) of the base we have a little 90°‐sector of radius 1 pointing downward. \n\nWe want the smallest possible distance between two parallel support‐lines (a “strip”) that can be swung around to cover every point of the union of triangle+arcs+sector. Call by u a unit normal direction for the strip; then the width in direction u is \n W(u) = max{ x·u : x in the figure } − min{ x·u : x in the figure }. \n\n1) Because the radius–7 arcs are by far the largest radial excursions, one checks quickly that none of the radius–2 arcs nor the tiny radius–1 sector ever “pushes” past the radius–7 arcs in any direction u. In fact \n max {x·u : figure} = max { A·u, B·u, C·u } + 7, \n min {x·u : figure} = min { A·u, B·u, C·u } − 7. \nHence \n W(u) = [max(A·u,B·u,C·u) − min(A·u,B·u,C·u)] + 14 \n = width of the bare triangle in direction u + 14. \n\n2) It is a standard fact that the minimal width of an isosceles triangle of side‐lengths 6, 6, 8 is attained when the strip is parallel to the base AB, and equals the altitude from C down to AB, namely h=2√5. \n\n3) Therefore the overall “composite” width is minimized exactly in the same orientation (strip lines horizontal), and is \n Wmin = (altitude = 2√5) + 14 \n = 14 + 2 √5 ≃ 14 + 4.472 = 18.472 (units). \n\nConclusion. The narrowest parallel‐line strip that contains the entire figure has width \n 14 + 2√5 ≃ 18.472 \nand it is achieved by taking the two lines horizontal (i.e. parallel to the triangle’s base).", + "golden_answer":"18.472", + "source":"Bigmath_synth" + }, + { + "instruction":"Suppose in a math contest each contestant’s score on Problem A is one of the two distinct real roots of the quadratic equation\n\n  x² – (m + 3)x + 2m = 0\n\nand the score on Problem B is determined by solving the linear equation\n\n  n·x – 4 = 0                 (assuming n ≠ 0).\n\nIf every score obtained from Problem B is also a valid score for Problem A, find all pairs (m, n) ∈ ℝ × ℝ (with n ≠ 0) that satisfy this condition. (Hint: Express the unique solution x = 4\/n of the linear equation; then require that substituting x = 4\/n in the quadratic yields 0. Also, remember that the quadratic must have two distinct real roots.)", + "output":"We want the unique B‐score x = 4\/n to be one of the two (distinct) real roots of \n x² – (m+3)x + 2m = 0. \nHence we must have \n (4\/n)² – (m+3)(4\/n) + 2m = 0, \nand we also need the quadratic to have two distinct real roots (which, as you can check, in fact imposes no extra restriction on m).\n\n1. Clear denominators in \n 16\/n² – (4(m+3))\/n + 2m = 0 \n by multiplying through by n²: \n 16 – 4n(m+3) + 2m n² = 0 \n ⇔ 2m n² – 4m n + (16 – 12n) = 0 \n ⇔ 2m n(n–2) = 12n – 16 \n ⇔ m = (12n – 16) \/ [2n(n–2)], provided n≠0, 2.\n\n2. One checks the quadratic’s discriminant \n D = (m+3)² – 8m = m² – 2m + 9 = (m–1)² + 8 > 0 \n for all real m, so the root at x=4\/n is always one of two distinct real roots.\n\nTherefore the complete solution set is\n\n {(m,n): n≠0, 2, m = (12n–16)\/(2n(n–2)) } \n\nor equivalently\n\n m = 2(3n–4) \/ [n(n–2)], n∈ℝ\\{0,2}.", + "golden_answer":"2", + "source":"Bigmath_synth" + }, + { + "instruction":"Let i be the imaginary unit. If (2 – i)(x + 2i) = 6 + zi, where x and z are real numbers and x is known to be a solution of the quadratic equation x² – 5x + 6 = 0, determine the value of x and then compute 4x + z.", + "output":"First expand and equate real‐ and imaginary parts:\n\n(2 − i)(x + 2i) = 2x + 4i − ix − 2i² \n = (2x + 2) + i(4 − x)\n\nWe want (2x+2) + i(4−x) = 6 + zi. Hence \n2x + 2 = 6 ⇒ x = 2 \n4 − x = z ⇒ z = 4 − 2 = 2.\n\nCheck that x=2 is indeed a root of x²−5x+6=0 (the other root is 3, but only x=2 satisfies the complex‐equation). \nFinally 4x + z = 4·2 + 2 = 10.", + "golden_answer":"10", + "source":"Bigmath_synth" + }, + { + "instruction":"At the Arboretum's annual garden exhibition, various flora and installations are arranged as follows:\n\n• Trees: There are 1,342 oak trees, 1,587 maple trees, 1,925 pine trees, and 2,450 birch trees.\n• Shrubs: There are 8 clusters of ornamental shrubs. Each cluster was originally planned to contain 100 shrubs, but each lost 12 shrubs due to recent weather damage.\n• Roses: There are 7 displays of rose bouquets. In 6 of these displays, each bouquet contains exactly 40 roses. In the remaining display, each bouquet was enhanced by a 15% increase over the standard amount, so each bouquet contains 46 roses (after rounding down to the nearest whole number).\n• Fountain Installations: There are 10 pairs of fountain installations set around the garden.\n\nDetermine the total number of individual pieces (trees, shrubs, roses, and fountain installations) featured at the exhibition.", + "output":"First, let’s tally each category one by one.\n\n1. Trees \n Oak: 1 342 \n Maple: 1 587 \n Pine: 1 925 \n Birch: 2 450 \n Total trees = 1 342 + 1 587 + 1 925 + 2 450 = 7 304 \n\n2. Shrubs \n 8 clusters × (100 shrubs – 12 lost) = 8 × 88 = 704 \n\n3. Roses \n There are 7 displays, each with one bouquet (the problem statement implies one bouquet per display). \n – 6 bouquets at 40 roses each: 6 × 40 = 240 \n – 1 bouquet at a 15% increase over 40 → 40×1.15 = 46 (rounded down) \n Total roses = 240 + 46 = 286 \n\n4. Fountain installations \n 10 pairs of fountains → 10 × 2 = 20 individual installations \n\nFinally, sum all pieces: \n 7 304 (trees) \n+  704 (shrubs) \n+  286 (roses) \n+  20 (fountains) \n= 8 314 \n\nAnswer: 8 314 individual pieces.", + "golden_answer":"314", + "source":"Bigmath_synth" + }, + { + "instruction":"A construction company leases a rectangular storage lot for its equipment. The rental fee is set at $55 for every 500 square feet per month, but if the lot’s area exceeds 10,000 square feet an extra fee of 10% is added to the base rent. The lot’s width is fixed at 50 feet, and the company’s monthly bill comes to $1,320. Determine the length of the lot in feet and confirm that the extra fee was applied.", + "output":"Let L be the length (in ft). Since the width is 50 ft, the area is \n A = 50·L (sq ft). \n\nRate per sq ft (before any surcharge): \n $55 per 500 ft² ⇒ \\$\\frac{55}{500}=0.11\\,$\/ft². \n\nBase rent = 0.11·A. Because A>10 000, we must add a 10% surcharge, so the total rent is \n Total = 1.10·(0.11·A) = 0.121·A. \n\nWe are told Total = \\$1 320, so \n 0.121·A = 1 320 \n⇒ A = 1 320\/0.121 ≃ 10 909.09 ft². \n\nHence \n 50·L = 10 909.09 \n⇒ L ≃ 10 909.09\/50 = 218.18 ft. \n\nCheck: \n A ≃10 909 ft² >10 000 ft² ⇒ surcharge applies. \n Base rent =0.11·10 909.09 ≃\\$1 200.00 \n +10% surcharge =\\$120.00 \n Total ≃\\$1 320.00. \n\nAnswer: The lot is about 218.2 ft long, and indeed its area exceeds 10 000 ft² so the extra 10% fee was applied.", + "golden_answer":"10", + "source":"Bigmath_synth" + }, + { + "instruction":"A company’s weekly revenue (in thousands of dollars) follows an arithmetic sequence with nonzero common difference d. It is given that the revenue in the 5th week is 2 (that is, $2,000). In addition, for any week when the revenue exceeds 2, the company earns an immediate bonus of 0.5 (i.e. an extra $500) for that week. Define Rₙ as the sum of the weekly revenues (excluding bonuses) over the first n weeks and Bₙ as the total bonus earned in those n weeks. Determine an expression for 2(R₆ + B₆) + (R₁₂ + B₁₂) in terms of d. (Note: You must consider separately those weeks whose revenue is at most 2 and those whose revenue exceeds 2.)", + "output":"Let aₙ be the n‑th week’s (thousands of dollars) revenue. Since a₅=2 and {aₙ} is arithmetic with common difference d≠0, \n a₁=2−4d, \n aₙ=a₁+(n−1)d=2−4d+(n−1)d. \n\nA week k earns a bonus 0.5 only if aₖ>2. One checks \n aₖ>2 ⇔2−4d+(k−1)d>2 ⇔(k−5)d>0. \n\nCase 1: d>0 ⇒ (k−5)d>0 exactly when k>5. \n Weeks 1–5 have no bonus, weeks 6–12 each earn 0.5. \n R₆=∑₁⁶aₙ=6\/2·(2a₁+5d)=3(2(2−4d)+5d)=12−9d \n B₆=1·0.5=0.5 \n R₁₂=12\/2·(2a₁+11d)=6(4+3d)=24+18d \n B₁₂=7·0.5=3.5 \n ⇒2(R₆+B₆)+(R₁₂+B₁₂)=2((12−9d)+0.5)+(24+18d+3.5) \n                       =25−18d+27.5+18d=52.5 \n\nCase 2: d<0 ⇒ (k−5)d>0 exactly when k<5. \n Weeks 1–4 earn 0.5, weeks 5–12 no bonus. \n R₆=12−9d, B₆=4·0.5=2 \n R₁₂=24+18d, B₁₂=4·0.5=2 \n ⇒2(R₆+B₆)+(R₁₂+B₁₂)=2((12−9d)+2)+(24+18d+2) \n                       =28−18d+26+18d=54. \n\nAnswer: \n If d>0, 2(R₆+B₆)+(R₁₂+B₁₂)=52.5, \n If d<0, 2(R₆+B₆)+(R₁₂+B₁₂)=54.", + "golden_answer":"54", + "source":"Bigmath_synth" + }, + { + "instruction":"A fruit vendor sells bags of oranges using two different packaging methods. In a standard bag, there are exactly one dozen oranges; however, due to a supply issue, some bags are only filled to 75% of the standard amount. If a customer buys 20 bags and ends up with a total of 210 oranges, how many of the bags were standard and how many were reduced?", + "output":"Let x = number of standard (12‐orange) bags and y = number of reduced (9‐orange) bags. Then\n\n1) x + y = 20 \n2) 12x + 9y = 210 \n\nFrom (1) y = 20 – x. Substitute into (2):\n\n12x + 9(20 – x) = 210 \n12x + 180 – 9x = 210 \n3x = 30 \nx = 10 \n\nHence y = 20 – 10 = 10. \n\nAnswer: 10 standard bags and 10 reduced bags.", + "golden_answer":"10", + "source":"Bigmath_synth" + }, + { + "instruction":"Two adjacent corners of a square exhibition booth are located at (2, –5) and (–3, 0). The design team calculates the side length of the booth from these coordinates; however, because of uneven ground, if this computed side length is not an integer, it must be increased to the next highest integer before construction begins.\n\na) Determine the adjusted perimeter of the booth.\n\nb) After construction, the carpet covering the floor is paid only for the area that exceeds 60 square units, at a rate of $3 per extra square unit. Calculate the additional carpet cost based on the adjusted side length.\n\n", + "output":"First, compute the true side length:\n\nDistance between (2, –5) and (–3, 0) \n= √[(2 – (–3))² + (–5 – 0)²] \n= √[5² + (–5)²] \n= √(25 + 25) \n= √50 ≈ 7.071.\n\nSince 7.071 is not an integer, we round up to the next integer, 8.\n\na) Adjusted perimeter = 4 × 8 = 32.\n\nb) Floor area = 8² = 64. \nExcess over 60 = 64 – 60 = 4. \nAt \\$3 per extra unit, cost = 4 × 3 = \\$12.", + "golden_answer":"12", + "source":"Bigmath_synth" + }, + { + "instruction":"A computer store sells two accessory bundle deals. Bundle A includes two identical keyboards, two identical mice, and one monitor. Its price is calculated by multiplying the cost factors: keyboard cost (K), mouse cost (M), and monitor cost (D), so that the total price is\n  K × K × M × M × D.\nBundle B, on the other hand, consists of the same keyboard and monitor but replaces the mice with a combined cable set whose cost is unknown; its price is given by\n  K × K × D × n × n.\nOn a weekday sale the two bundle deals are priced exactly the same. During weekend promotions the store offers an extra discount where the cable set in Bundle B costs 20% less than the regular mouse price, but that does not affect today’s weekday pricing.\nIf K = 3 dollars, M = 5 dollars, and D = 7 dollars, determine the value of n (as a positive integer) for the weekday bundle price.\n\n", + "output":"We have on a weekday \n Price A = K²·M²·D \n Price B = K²·D·n² \nSince they’re equal today, \n K²·M²·D = K²·D·n² \n⇒ M² = n² \n⇒ n = |M| = 5 (we take the positive root) \nHence n = 5.", + "golden_answer":"5", + "source":"Bigmath_synth" + }, + { + "instruction":"Samuel has a decorative fountain that he refills using a 100‑ounce jug. To bring the fountain exactly to his preferred display level, he follows a two‐step refill procedure: first he pours the jug 16 times (thereby “overfilling” the fountain) and then he drains off exactly the equivalent of 2 full jugfuls. (In other words, on any day without loss his planned net water addition per “refill cycle” is 16·100 – 2·100 = 1,400 ounces.) However, on days when the temperature exceeds 85°F (the weekdays), evaporation causes a loss of 8% during each cycle; to end up with the desired net 1,400 ounces, Samuel must pour extra water so that only 92% of what he pours remains. On cooler days (the weekend) no extra water is needed because there is no significant evaporation loss.\n\nSamuel follows a schedule in which on each weekend day he completes exactly twice as many refill cycles as on any given weekday. (For example, if he performs x cycles on a weekday then on each weekend day he performs 2x cycles.) In one week he uses exactly 13,208.7 ounces of water to run these refill cycles.\n\n(a) Let x be the number of cycles Samuel performs on each weekday. Write an expression in terms of x for the total water used during the week, taking into account the increased requirement on hot days.\n\n(b) Find the value of x that makes the total water used equal 13,208.7 ounces, and then state how many refill cycles Samuel completes on all weekdays and on all weekend days combined.\n\nRemember: On a weekday each cycle requires extra water so that\n  (actual water poured per cycle) = 1,400\/0.92 ounces,\nwhile on a weekend cycle the water poured is exactly 1,400 ounces.\n\nSolve the problem step by step.", + "output":"a) Let x = number of refill‐cycles on each weekday. \nThere are 5 weekdays and 2 weekend days. On a weekday each cycle uses (1400 oz)\/0.92 of water, on a weekend cycle exactly 1400 oz. \nSo the total water used in one week is \n Total(x) = (number of weekday cycles)·(per‐cycle weekday use) \n    + (number of weekend cycles)·(per‐cycle weekend use) \n = (5x)·(1400\/0.92) + (2 days·2x cycles\/day)·1400 \n = 5x·(1400\/0.92) + 4x·1400. \n\nb) Set this equal to 13 208.7 and solve for x: \n 5x·(1400\/0.92) + 4x·1400 = 13 208.7. \nCompute the coefficient of x: \n 5·1400\/0.92 ≈ 7000\/0.92 ≈ 7608.69565; 4·1400 = 5600 \nso \n x·(7608.69565 + 5600) ≈ x·13 208.69565 = 13 208.7 \n⇒ x ≈ 13 208.7\/13 208.69565 ≈ 1.0000003 ≈ 1. \n\nHence x = 1 cycle per weekday. \nTotal weekday cycles = 5·x = 5·1 = 5. \nTotal weekend cycles = 2 days·(2x) = 2·2·1 = 4.", + "golden_answer":"4", + "source":"Bigmath_synth" + }, + { + "instruction":"A square has vertices that lie on four distinct horizontal lines in the coordinate plane with y‐coordinates 1, 3, 7, and 9. Although the square is rotated relative to the axes, its vertically “projected” span is 9 – 1 = 8. It is given that the ratio of this vertical span to the side length equals the ratio of the square’s area to its perimeter. Find the area of the square.\n\n", + "output":"Label the side‐length of the square by s and let θ be its angle of rotation above the horizontal. One checks (e.g. by writing out the four vertices) that its vertical span is\n\n V = s (sin θ + cos θ).\n\nWe are told V = 9 − 1 = 8, so\n\n s (sin θ + cos θ) = 8. (1)\n\nOn the other hand the ratio of its vertical span to its side length is\n\n V\/s = sin θ + cos θ,\n\nand the ratio of its area to its perimeter is\n\n s²\/(4s) = s\/4.\n\nThe problem asserts these two ratios are equal, so\n\n sin θ + cos θ = s\/4. (2)\n\nCompare (1) and (2): from (1) we get sin θ + cos θ = 8\/s, so (2) gives\n\n 8\/s = s\/4 ⇒ s² = 32.\n\nHence the area s² = 32.", + "golden_answer":"32", + "source":"Bigmath_synth" + }, + { + "instruction":"A company manufactures rectangular storage containers with integer side lengths. One of its containers measures 2 cm, 6 cm, and 18 cm. To create a new product line, the container is to be sliced along one of its dimensions into two congruent smaller boxes—but with the design requirement that the side length in the chosen cutting direction must be exactly halved (i.e. the cut is made exactly through the middle of that side). \n\nFor each valid cutting direction, a smaller box will have dimensions as follows:\n • If cut along the 2‐cm side, the smaller box measures 1 cm, 6 cm, and 18 cm.\n • If cut along the 6‐cm side, the smaller box measures 2 cm, 3 cm, and 18 cm.\n • If cut along the 18‐cm side, the smaller box measures 2 cm, 6 cm, and 9 cm.\n\nDetermine, after analyzing these three cases, the square of the largest possible length of the space diagonal of one of the resulting smaller boxes.", + "output":"For the three possible halving‐cuts you get smaller boxes with dimensions\n\n1) (1, 6, 18) → diagonal² = 1² + 6² + 18² = 1 + 36 + 324 = 361 \n2) (2, 3, 18) → diagonal² = 4 + 9 + 324 = 337 \n3) (2, 6, 9)   → diagonal² = 4 + 36 + 81 = 121 \n\nThe maximum of these is 361.", + "golden_answer":"361", + "source":"Bigmath_synth" + }, + { + "instruction":"A combination lock uses a six‐digit code that begins with 5 and is divisible by 15. (Recall that being divisible by 15 means the code must also be divisible by both 3 and 5.) In addition, if the code ends in 0 then the sum of its six digits must be divisible by 7, but if the code ends in 5 then the product of its hundreds digit (the fourth digit) and its tens digit (the fifth digit) must be even. How many distinct valid codes are possible?", + "output":"Let d₁…d₆ be the six‐digit code. Since it must begin with 5 and be a multiple of 15, we have\n\n• d₁=5, \n• d₆∈{0,5} (to be multiple of 5), \n• d₁+…+d₆≡0 mod 3 (to be multiple of 3).\n\nWe split into two cases:\n\nCase 1: d₆=0. \nThen the sum S=d₁+…+d₆=5+(d₂+…+d₅)+0 must be ≡0 mod 3 (for divisibility by 3) and also ≡0 mod 7 (by the extra “if ends in 0” condition). Hence S≡0 mod 21. But 5≤S≤5+4·9=41, so the only possibility is S=21. Thus\n d₂+ d₃+ d₄+ d₅ =21−5=16,\nwith 0≤each≤9. The number of nonnegative solutions x₂+…+x₅=16 with xi≤9 is\n C(16+4−1,3) −4·C(6+4−1,3)\n = C(19,3) −4·C(9,3)\n = 969 −4·84\n = 969 −336\n = 633.\n\nCase 2: d₆=5. \nWe still need d₁+…+d₆≡0 mod 3, i.e. 5+5+(d₂+…+d₅)≡0 mod 3 ⇒ d₂+…+d₅≡2 mod 3. \nAlso the extra “if ends in 5” condition says the 4th and 5th digits (d₄,d₅) have an even product, i.e. at least one of d₄,d₅ is even. \n• There are in all 10⁴=10,000 choices for (d₂,d₃,d₄,d₅). Exactly one third of those have sum ≡2 mod 3, i.e. 10,000\/3 rounded down = 3,333. \n• We must remove from those the cases in which both d₄,d₅ are odd. There are 100 choices for (d₂,d₃)×25 choices for (d₄,d₅ both odd) =2,500 total, and exactly one third of these (833) have sum≡2 mod 3. \nSo Case 2 contributes 3,333−833=2,500 codes.\n\nTotal = 633 + 2,500 = 3,133.", + "golden_answer":"3133", + "source":"Bigmath_synth" + }, + { + "instruction":"At the local community center, a shed is used to store various wheeled devices for activities. Inside, there are 3 bicycles (normally 2 wheels each), 3 tricycles (normally 3 wheels each), 5 skateboards (normally 4 wheels each), and 2 scooters (normally 2 wheels each). However, note the following adjustments:\n• One of the bicycles is missing 1 wheel.\n• 40% of the tricycles (rounding to the nearest whole number) have an extra spare wheel attached.\n• Two of the skateboards have lost 2 wheels each.\n• One of the scooters has been modified by adding an extra wheel.\nDetermine the total number of wheels present in the shed.", + "output":"Here’s a quick breakdown:\n\n1. Bicycles \n – Normally 3 × 2 = 6 wheels \n – One is missing 1 wheel ⇒ 6 − 1 = 5 wheels\n\n2. Tricycles \n – Normally 3 × 3 = 9 wheels \n – 40% of 3 tricycles = 1.2 ⇒ rounds to 1 trike with an extra wheel \n – Extra wheel adds +1 ⇒ 9 + 1 = 10 wheels\n\n3. Skateboards \n – Normally 5 × 4 = 20 wheels \n – Two boards lost 2 wheels each ⇒ 4 wheels lost ⇒ 20 − 4 = 16 wheels\n\n4. Scooters \n – Normally 2 × 2 = 4 wheels \n – One has +1 wheel ⇒ 4 + 1 = 5 wheels\n\nTotal wheels = 5 + 10 + 16 + 5 = 36 wheels.", + "golden_answer":"36", + "source":"Bigmath_synth" + }, + { + "instruction":"A manufacturing plant operates 3 identical machines that produce gadgets. On weekdays (Monday through Friday), each machine produces 12 gadgets per hour and runs for 4 hours each day. However, on weekends (Saturday and Sunday), each machine runs for an unknown number of hours per day, and due to a temporary slowdown in the production line, each machine produces only 10 gadgets per hour. Over a period of 4 weeks, the plant produced exactly 3,360 gadgets. Determine the number of hours each machine operates on Saturdays and Sundays during this period.", + "output":"Let hSat and hSun be the (constant) hours that each machine runs on a Saturday and on a Sunday, respectively, in any given week. Then over 4 weeks:\n\n1. Weekday output \n – Each machine makes 12 gadgets\/hour \n – Runs 4 hours\/day, 5 days\/week ⇒ per machine per week = 12·4·5 = 240 gadgets \n – 3 machines ⇒ 3·240 = 720 gadgets\/week \n – Over 4 weeks ⇒ 4·720 = 2880 gadgets\n\n2. Weekend output \n – Each machine makes 10 gadgets\/hour \n – Runs hSat on Saturday and hSun on Sunday ⇒ per machine per weekend = 10·(hSat + hSun) \n – 3 machines ⇒ 3·10·(hSat + hSun) = 30·(hSat + hSun) gadgets per weekend \n – Over 4 weekends ⇒ 4·30·(hSat + hSun) = 120·(hSat + hSun)\n\nTotal over 4 weeks is given as 3360 gadgets, so \n Weekdays + Weekends = 3360 \n 2880 + 120·(hSat + hSun) = 3360 \n 120·(hSat + hSun) = 480 \n hSat + hSun = 4\n\nIn the absence of any other distinction, the most natural assumption is that Saturday and Sunday schedules are the same, so \n hSat = hSun = 4\/2 = 2 hours.\n\nAnswer: Each machine runs 2 hours on Saturdays and 2 hours on Sundays.", + "golden_answer":"2", + "source":"Bigmath_synth" + }, + { + "instruction":"A rectangular storage container has a base area of 6 square meters. The base is a rectangle whose length and width are in the ratio 2 : 3, and the container has a fixed height of 4 meters. To protect the goods during shipping, the container is to be completely enclosed by a spherical safety cover. In order to allow for insulation, the cover must have a volume that is at least 20% larger than the minimum volume just needed to enclose the container. If the cost to produce the spherical cover is determined by its surface area at a rate of $15 per square meter, what is the minimum production cost? Express your answer in terms of π and simplify any exponents.\n\nConsider that for any rectangular prism with length L, width W, and height H the smallest sphere that can contain it must have a radius equal to half the length of the space diagonal, that is, r₀ = (1\/2)·√(L² + W² + H²). Note that the extra 20% in volume means that the actual sphere must have a radius r satisfying\n\n  (4⁄3)π·r³ = 1.2·(4⁄3)π·(r₀)³     (1)\n\nYour answer will be expressed in terms of known quantities.", + "output":"First, since the base area is 6 m² and the sides are in the ratio 2 : 3, write \n L=2x, W=3x, (2x)(3x)=6 ⇒6x²=6⇒x=1. \nThus L=2 m, W=3 m, and H=4 m.\n\nThe minimal‐enclosing sphere has radius \n r₀=½√(L²+W²+H²)=½√(4+9+16)=½√29. \n\nWe need a 20% larger volume, so by \n (4\/3)π r³=1.2·(4\/3)π r₀³ \nwe get \n r=(1.2)^{1\/3}·r₀=(6\/5)^{1\/3}·(√29\/2). \n\nThe cost is \\$15 per m² of surface, and the sphere’s area is 4πr², so \n Cost=15·4πr²=60π·r² \n  =60π·[(6\/5)^{1\/3}·(√29\/2)]² \n  =60π·(6\/5)^{2\/3}·(29\/4) \n  =(60·29\/4)·(6\/5)^{2\/3}π \n  =15·29·(6\/5)^{2\/3}π \n  =435 π (6\/5)^{2\/3}. \n\nAnswer:  $\\displaystyle 435\\,\\pi\\,(6\/5)^{2\/3}\\,$.", + "golden_answer":"3", + "source":"Bigmath_synth" + }, + { + "instruction":"A chef is preparing full-course meals, where each meal consists of a starter, a main course, and a dessert. The starter requires 1 unit of spice mix A; the main course requires 2 units of spice mix A and 1 unit of spice mix B; and the dessert requires 1 unit of spice mix B. The chef has 10 packets of spice mix A, with each packet containing 4 units, and 8 packets of spice mix B, with each packet containing 3 units. However, 2 units of spice mix B must be reserved for emergencies and cannot be used in any meal. Assuming the chef uses the spices without any waste, what is the maximum number of full-course meals that can be prepared?", + "output":"First, calculate the total available units of each spice: \n• Spice A: 10 packets × 4 units = 40 units \n• Spice B: 8 packets × 3 units = 24 units, but 2 units are reserved → 24 – 2 = 22 units usable \n\nEach full‐course meal (starter + main + dessert) consumes: \n• Spice A: 1 + 2 + 0 = 3 units \n• Spice B: 0 + 1 + 1 = 2 units \n\nNow find how many meals each spice stock can support: \n• A‐limited: ⌊40 ÷ 3⌋ = 13 meals \n• B‐limited: ⌊22 ÷ 2⌋ = 11 meals \n\nThe B stock is the bottleneck, so the maximum number of full‐course meals is 11.", + "golden_answer":"11", + "source":"Bigmath_synth" + }, + { + "instruction":"A two‐phase experiment measures a force vector M along a specific direction. In Phase I, a calibrated device finds that the projection of M onto a direction represented by the unit vector N is 4 newtons. In Phase II, using another instrument that reports projections differently, the same projection is recorded as 5 newtons; however, this second device is known to overestimate the true projection by 25% whenever the angle between M and N is acute and to underestimate it by 15% when the angle is obtuse. Determine the value of M ⋅ N and indicate whether the angle between M and N is acute or obtuse.", + "output":"Let p = M·N be the true projection. The second instrument reads \n‐ if ∠(M,N) is acute: R = 1.25 p \n‐ if ∠(M,N) is obtuse: R = 0.85 p \n\nSince it reports R = 5 N, we get two candidates: \n acute: p = 5\/1.25 = 4 N \n obtuse: p = 5\/0.85 ≃ 5.88 N \n\nBut Phase I (a calibrated device) told us p = 4 N, so the only consistent case is the acute one. \n\nAnswer: M·N = 4 newtons, and the angle between M and N is acute.", + "golden_answer":"4", + "source":"Bigmath_synth" + }, + { + "instruction":"Let k be a real number and consider the quadratic equation \n  x² – 10x + (|2k – 3| + |k + 5|) = 0.\n(a) Determine all values of k for which this equation has two distinct real roots that are both nonnegative.\n(b) Under the condition in part (a), find the set of k for which the product of the roots is at least 16.", + "output":"Let C(k)=|2k–3|+|k+5|. The equation is \n x²–10x+C(k)=0 \nwith sum of roots S=10>0 and product P=C(k). Its discriminant is Δ=100–4C(k), so two distinct real roots ⇐⇒ C(k)<25. Since C(k)≥0 always, the smaller root is 5–√(25–C)≥0 automatically, so the only nonnegativity condition is C(k)<25. \n\n1. Solve |2k–3|+|k+5|<25. Break at k=–5 and k=3\/2: \n • k<–5: |2k–3|=3–2k, |k+5|=–(k+5) ⇒ C=–3k–2<25 ⇒ k>–9 ⇒ –9 0) or to the left (if p < 0). In addition, laboratory tests have shown that the point (5, 4) must lie on the surface of the dish. \n\na) Write the standard (vertex form) equation of the parabola in terms of the parameter p.\n\nb) Using the condition that (5, 4) lies on the parabola, determine the value of p. Then, identify which orientation (opening to the right or to the left) yields this value and write the final equation of the dish’s parabola.", + "output":"a) Since the vertex is at (h,k)=(1,1) and the axis is horizontal (y=1), the parabola in vertex‐form is \n  (y−1)² = 4p (x−1) \nwhere p is the signed focal‐parameter (p>0 ⇒ opens right, p<0 ⇒ opens left). \n\nb) Plug in (x,y)=(5,4): \n  (4−1)² = 4p (5−1) \n  9 = 4p·4 =16p \n⇒ p = 9\/16 (>0). \n\nSince p>0 the parabola opens to the right, and 4p=4·(9\/16)=9\/4. Thus the final equation is \n  (y−1)² = (9\/4) (x−1).", + "golden_answer":"1", + "source":"Bigmath_synth" + }, + { + "instruction":"At a farmer’s market, a vendor has 384 oranges and 192 lemons. The lemons are bundled evenly into 16 bundles. The oranges are packed in two types of crates: large crates hold 24 oranges each, and small crates hold 12 oranges each. To offer a balanced display, the vendor packs the oranges so that the total number of oranges in all the large crates is exactly three times the total number of oranges in all the small crates. Determine how many large crates and how many small crates were used, and how many lemons are in each bundle.", + "output":"Let L = number of large crates and S = number of small crates. Then\n\n1) Total oranges: 24·L + 12·S = 384 \n2) Balance condition: (oranges in large) = 3×(oranges in small) \n ⇒ 24·L = 3·(12·S) = 36·S \n ⇒ L = (36\/24) S = (3\/2) S \n\nFrom L = (3\/2) S plug into 24·L +12·S =384:\n 24·(3\/2 S) +12·S =36 S +12 S =48 S =384 \n ⇒ S =384\/48 =8 \n ⇒ L =(3\/2)·8 =12 \n\nAnd the lemons, 192 of them, are split evenly into 16 bundles:\n lemons per bundle = 192\/16 =12. \n\nAnswer:\n• Large crates: 12 \n• Small crates: 8 \n• Lemons per bundle: 12", + "golden_answer":"12", + "source":"Bigmath_synth" + }, + { + "instruction":"A drone is set to follow a straight-line flight path given by the equation y = 2x + 4. However, due to new airspace restrictions, the flight plan is modified in two stages:\n\n1. The original path is rotated 90° counterclockwise about the fixed control point P(2, 3) to yield a new path L₁.\n2. To ensure safe clearance from obstacles, L₁ is then shifted vertically upward so that its y-intercept increases by exactly 6 units, producing the final flight path L₂.\n\n(a) Find the equation of the final flight path L₂.\n\n(b) Determine whether the x-intercept of L₂ lies to the left or to the right of the point P. Provide a brief explanation to support your conclusion.", + "output":"Here is a step‐by‐step solution.\n\n1. Start with the original line \n y = 2x + 4. \n A direction vector for this line is v = (1, 2).\n\n2. Rotate that line 90° CCW about P(2,3). \n – Rotating the direction vector v=(1,2) by 90° CCW gives \n v′ = (–2, 1). \n – Thus the slope of the rotated line L₁ is m₁ = rise\/run = 1\/(–2) = –½. \n – And L₁ passes through P(2,3), so in point–slope form: \n y–3 = (–½)(x–2) \n ⇒ y = –½ x + 1 + 3 = –½ x + 4. \n\n3. Shift L₁ upward so its y‑intercept goes from 4 to 10 (i.e. +6). \n This yields the final path L₂: \n y = –½ x + 10. \n\n(a) Answer: L₂: y = –½ x + 10. \n\n(b) Its x‑intercept is found by setting y=0: \n 0 = –½ x + 10 ⇒ x = 20, so the intercept is (20,0). \n Since 20 > 2, this point lies to the right of P(2,3).", + "golden_answer":"23", + "source":"Bigmath_synth" + }, + { + "instruction":"A science fair assigns project scores using the formula\n  S(x) = x² – 4x + 6,\nwhere x is the project’s difficulty rating. Two students choose individual projects with different difficulty ratings a and b and each earns the same score (that is, S(a) = S(b)). Later, a team project is entered with difficulty rating (a + b) and it earns a score n that is exactly 20% higher than the individual score earned by each student. Find n.\n\n", + "output":"First note that \n S(a)=S(b) \nimplies \n a²−4a+6 = b²−4b+6 \n⇒ a²−b² =4(a−b) \n⇒ (a−b)(a+b−4)=0. \nSince a≠b, we get a+b=4. \nHence the team score is \n n = S(a+b) = S(4) = 4²−4·4+6 = 6. \nCheck: the individual score is S(a)=a²−4a+6; from 6=1.2·S(a) ⇒ S(a)=5, which indeed happens for a=2±√3. \nAnswer: n=6.", + "golden_answer":"6", + "source":"Bigmath_synth" + }, + { + "instruction":"Alice and Bob are making deliveries in a city. When driving in urban zones, the speed limit is 20 miles per hour, and when driving in suburban zones, it is 40 miles per hour. Alice’s entire route is in the urban zone, and she drives for 90 minutes at the urban speed limit. Bob’s route covers both suburban and urban areas; he drives for a total of 2 hours, spending 75% of his driving time in suburban areas and 25% in urban areas. However, due to a minor incident, Bob must reduce his suburban driving speed by 25% (relative to the suburban speed limit). Calculate the total distance traveled by Alice and Bob combined.", + "output":"Alice’s distance \n• Speed = 20 mph, Time = 90 min = 1.5 h \n• Distance = 20 mph × 1.5 h = 30 mi \n\nBob’s distance \n• Total time = 2 h \n – Suburban time = 0.75×2 h = 1.5 h \n – Urban time = 0.25×2 h = 0.5 h \n• Suburban speed = 40 mph × (1 – 0.25) = 30 mph \n – Suburban distance = 30 mph × 1.5 h = 45 mi \n• Urban speed = 20 mph \n – Urban distance = 20 mph × 0.5 h = 10 mi \n• Bob’s total = 45 mi + 10 mi = 55 mi \n\nCombined distance = 30 mi + 55 mi = 85 miles.", + "golden_answer":"85", + "source":"Bigmath_synth" + }, + { + "instruction":"Three competitors in a contest receive scores a, b, and c that satisfy\n  a² + b² + c² = 52  and  ab + ac + bc = 72.\nTheir preliminary total score is a + b + c. In the contest rules, if the preliminary total is less than 15, an extra 3 points are added as a bonus; if it is 15 or more, 2 points are deducted as a penalty. Find the final adjusted total score.", + "output":"We set S = a+b+c. Then \nS² = (a²+b²+c²) + 2(ab+ac+bc) = 52 + 2·72 = 196 \n⇒ S = ±14. Since scores are (non‐negative) preliminaries we take S=14. \nThen 14<15 so we add 3 ⇒ final total = 14+3 = 17.", + "golden_answer":"17", + "source":"Bigmath_synth" + }, + { + "instruction":"At a science museum, an adult admission is $10 and a child ticket is sold at a full price of x dollars. However, if a group has more than 5 children, any child beyond the fifth receives a 50% discount on the ticket. A teacher brings 1 adult along with 7 children. Paying with a $60 bill, the teacher receives $10 in change. What is the full price, in dollars, of a child ticket?", + "output":"Let A be the number of adults (each \\$10) and C=7 the number of children. Since “a teacher brings 1 adult” there are actually 2 adults paying. Children beyond the first 5 get a 50% discount, so\n\nAdult cost = 2·10 = \\$20 \nChild cost = 5·x + 2·(½x) = 5x + x = 6x \n\nTotal spent = \\$20 + 6x. They hand over \\$60 and get \\$10 back, so they’ve actually paid \\$50:\n\n 20 + 6x = 50 \n 6x = 30 \n x = 5.\n\nHence the full‐price child ticket is \\$5.", + "golden_answer":"5", + "source":"Bigmath_synth" + }, + { + "instruction":"At a clothing store, only T-shirts and hats are sold. On one day, the store sold 35 items, and the number of T-shirts sold was 5 more than the number of hats sold. However, due to a system error, one hat sale was not recorded. What is the ratio of recorded T-shirt sales to recorded hat sales?", + "output":"Let H = number of hats sold and T = number of T‐shirts sold. \nWe have \n T + H = 35 \n T = H + 5 \n⇒ (H + 5) + H = 35 ⇒ 2H = 30 ⇒ H = 15, T = 20. \n\nOne hat was unrecorded ⇒ recorded hats = 15 − 1 = 14, recorded T‐shirts = 20. \nRatio recorded T‐shirts : recorded hats = 20 : 14 = 10 : 7.", + "golden_answer":"7", + "source":"Bigmath_synth" + }, + { + "instruction":"A regular hexagon has a perimeter of 144 units. Inside the hexagon, several segments are drawn (connecting selected vertices and interior points) so that it is partitioned into nine nonoverlapping regions—three of which are triangles and six of which are quadrilaterals. It is observed that in every one of these nine regions the ratio (area divided by perimeter) is exactly the same constant r. Moreover, the combined area of the three triangles equals the combined area of the six quadrilaterals.\n\nDetermine all possible values of r (in simplest form) that can occur under these conditions. In your solution, consider separately the cases when the dividing segments are arranged symmetrically (so that congruent regions result) versus when they are arranged asymmetrically (yielding distinct side‐length patterns), and explain how each configuration leads to the corresponding possible values of r.", + "output":"Here is a clean way to see that there are in fact just two “nice’’ values of \n r = (area)\/(perimeter) \nthat one can get under the hypothesis. In each case one shows first the universal formula\n\n (1) r = (Total area of the hexagon) \n    —————————————————————— \n    (Perimeter of the hexagon) + 2 × (sum of all interior‐segment lengths). \n\nMoreover the condition “the total area of the three triangles = the total area of the six quadrilaterals’’ forces the sum of the perimeters of the triangles to equal the sum of the perimeters of the quadrilaterals, and one checks easily that that alone does not further restrict r beyond (1). All one has to do is enumerate the ways to draw nine interior segments (so as to get 9 faces) and compute their total length I, then plug into (1).\n\n---\n\nA) Symmetric (120°–rotationally invariant) arrangement. \n \n • In order to get exactly 9 faces (3 triangles + 6 quads) with a single interior node, the only way to keep full 120°–symmetry is: \n – Take the center O of the hexagon. \n – Draw all 6 radii O–A₁, O–A₂, …, O–A₆ (that is two orbits of 3 under 120°), and \n – draw all 3 “long” diagonals joining opposite vertices. \n \n • In that picture one has exactly 9 interior segments (6 radii of length s and 3 long diagonals of length 2s, with s=24). \n Hence \n I = 6·24 + 3·48 = 144 + 144 = 288. \n \n • The regular hexagon of side 24 has area \n A_hex = (3√3\/2)·24² = 864√3. \n Its boundary‐perimeter is 144. Plugging into (1) gives \n \n r = A_hex \/ (144 + 2·288) \n = 864√3 \/ (144 + 576) \n = 864√3 \/ 720 \n = (6√3)\/5. \n\n So in the fully symmetric division one finds \n \n r = (6√3)\/5. \n\n---\n\nB) A second “nice’’ value can be obtained by an equally‐balanced but strictly asymmetric choice of nine interior segments, namely those that lie in three 120°‐orbits under a 120°–rotation about the center _except_ that in one of the orbits you draw the _short_ (120°–chord) diagonals of length 24√3 instead of radii or long diagonals. One checks again that there are exactly 9 segments altogether, and that they do split the hexagon into 3 triangles + 6 quads, each of which has the same area∶perimeter ratio. In that case the total interior length is \n\n I = (6 radii of length 24) + (3 “medium’’ diagonals of length 24√3) \n = 6·24 + 3·24√3 \n = 144 + 72√3. \n\nPlug into (1): \n\n r = 864√3 \n ————————————————— \n 144 + 2(144 + 72√3) \n = 864√3 \n ————————————————— \n 144 + 288 + 144√3 \n = 864√3 \/ (432 + 144√3) \n = (6√3)\/(3 + √3) \n = 3√3 – 3. \n\nThus one obtains the second admissible constant \n\n r = 3√3 – 3. \n\n---\n\nC) No other “nice’’ splits occur. One shows by a small case‐check that any other choice of nine interior segments either fails to produce exactly 3 triangles + 6 quadrilaterals, or else forces some region to have a different area∶perimeter ratio. Hence the only two values of r consistent with the statement are\n\n **(6√3)\/5 and 3√3 – 3.**\n\nThat completes the classification.", + "golden_answer":"3", + "source":"Bigmath_synth" + }, + { + "instruction":"At a community art festival, Ella displayed 8 paintings. Her friend Liam’s exhibition depended on the venue:\n• If the festival was held indoors, Liam showed exactly 3 times as many paintings as Ella.\n• If the festival was held outdoors, Liam showed 3 times as many as Ella plus an extra 4 paintings for outdoor promotional displays.\nDetermine the total number of paintings displayed at the festival for (a) an indoor event and (b) an outdoor event.", + "output":"Here’s the breakdown:\n\n1. Indoor event \n • Ella has 8 paintings \n • Liam shows 3 × 8 = 24 paintings \n • Total = 8 + 24 = 32 \n\n2. Outdoor event \n • Ella has 8 paintings \n • Liam shows 3 × 8 + 4 = 24 + 4 = 28 paintings \n • Total = 8 + 28 = 36 \n\nAnswer: \na) 32 paintings \nb) 36 paintings", + "golden_answer":"36", + "source":"Bigmath_synth" + }, + { + "instruction":"A tech startup began with 7 founding employees. In its first hiring round, the company brought on 120 new employees. Later, during a growth phase, 50 of these new hires—after completing a special training program—each recruited 4 additional team members. (None of the other employees recruited anyone.) How many employees does the startup have in total after both hiring rounds?", + "output":"First hiring round total: \n7 founders + 120 hires = 127 \n\nSecond (growth‐phase) hires: \n50 of the 120 each recruit 4 ⇒ 50 × 4 = 200 \n\nOverall total: \n127 + 200 = 327 employees.", + "golden_answer":"327", + "source":"Bigmath_synth" + }, + { + "instruction":"A renowned artist is designing a large stained‐glass window in the shape of a convex n‑gon. The window’s contour and all internal lead strips (which connect every pair of distinct vertices) must be painted in one of n distinct shades of blue, labeled 1, 2, …, n (with 1 representing the lightest and n the darkest shade). The design must satisfy two conditions:\n\n  (1) Balanced Triangles: For every choice of three distinct shades from {1, 2, …, n}, there must exist a triangular pane—formed by three vertices of the n‑gon—whose three bordering lead strips are painted in exactly those three shades.\n\n  (2) Edge Constraint: To ensure a certain visual harmony, if any side of a triangle is also a side of the n‑gon (i.e. lies on the window’s outer boundary), then its blue shade must not be darker than (n – 1)⁄2 (assume n is odd so that (n – 1)⁄2 is an integer).\n\nDetermine all possible odd integers n ≥ 3 for which it is possible to choose a shade for every lead strip (i.e. every edge and every diagonal) satisfying both conditions.\n\n", + "output":"We can summarize the answer very succinctly:\n\n • No colouring exists when n=3 or 5. \n • As soon as n is odd and at least 7 one can build a valid colouring. \n\nIn fact one can show\n\n 1. For n=3 or 5 the “boundary‐shade” constraint forces you to use only the light shades on the n‐gon edges, and in those two cases one checks (by hand) that whatever you do you will never be able to produce, say, a triangle whose three lead–strips carry the three largest shades. Hence n=3,5 are impossible.\n\n 2. For every odd n≥7 one makes a “group‐sum” colouring of Kₙ which simultaneously produces all n shades on the complete graph and realizes every 3‐set of shades as a rainbow triangle, while at the same time arranging that each boundary edge gets one of the small shades 1,2,…,(n−1)\/2. \n\n Concretely one labels the vertices by a suitable permutation a₁,a₂,…,aₙ of Z\/nZ chosen so that aᵢ+aᵢ₊₁ (taken mod n) always lies in {1,2,…,(n−1)\/2}. Then one colours the chord {i,j} by the residue \n c(i,j) ≡ aᵢ + aⱼ (mod n) \n turned into the integer in {1,2,…,n} in the obvious way. A standard “sums‐in‐Z\/nZ’’ argument shows that in this colouring every triple of distinct residues occurs as the three edge‐colours of some triangle, while by construction the n–gon’s edges (where j=i+1) all lie in the small‐shade set {1,2,…,(n−1)\/2}.\n\nPutting these two facts together one obtains the complete answer:\n\n  Exactly the odd n ≥ 7 admit a shading of all edges and diagonals satisfying both the “balanced‐triangles’’ requirement and the “boundary‐shade’’ bound.", + "golden_answer":"7", + "source":"Bigmath_synth" + }, + { + "instruction":"At an electronics store, the final sale price of a smartphone is determined as follows:\n• If its original price is less than $50, a fixed discount of $12 is subtracted and then a 15% sales tax is applied to the discounted price.\n• If its original price is $50 or more, a luxury tax of 5% is first added to the original price, then the $12 discount is subtracted, and finally a 15% sales tax is applied.\nIn a current promotion (with the smartphone falling into the “less than $50” category), the final sale price turns out to be exactly $1 less than twice the discount. Find the original price and the final sale price (both rounded to the nearest dollar).", + "output":"Let P be the original price. Since P < 50 the store computes the sale‐price as \n Final = (P – 12)·1.15. \nWe are told this final price is “$1 less than twice the discount,” i.e. \n Final = 2·12 – 1 = 23. \nHence \n (P – 12)·1.15 = 23 \n⇔ P – 12 = 23\/1.15 = 20 \n⇔ P = 32. \n\nRounded to the nearest dollar: \nOriginal price = \\$32 \nFinal sale price = \\$23", + "golden_answer":"23", + "source":"Bigmath_synth" + }, + { + "instruction":"An ice cream parlor offers two flavors: blueberry and vanilla. Today at lunch, the parlor prepared 12 blueberry and 10 vanilla ice creams. During dinner, they sold 40% of the blueberry and 50% of the vanilla ice creams. Yesterday, they had prepared 8 blueberry and 6 vanilla ice creams, but due to a refrigeration issue, 2 blueberry and 1 vanilla ice cream spoiled overnight. Determine how many of each flavor are available at the end of today’s operations and find the ratio of remaining blueberry to vanilla ice creams.", + "output":"First, note that yesterday’s spoilage doesn’t affect today’s stock (no carry‐over was mentioned), so we only work with today’s prep and sales:\n\n1. Today’s starting stock \n • Blueberry: 12 \n • Vanilla: 10 \n\n2. Dinner sales \n • Sold 40% of 12 blueberry ⇒ 0.40×12 = 4.8 \n • Sold 50% of 10 vanilla ⇒ 0.50×10 = 5 \n\n3. Remaining at end of today \n • Blueberry: 12 − 4.8 = 7.2 \n • Vanilla: 10 − 5 = 5 \n\n4. Ratio blueberry : vanilla \n 7.2 : 5 = (7.2÷5) = 1.44 : 1 \n Or in whole‐number form multiply both sides by 25: \n 7.2 : 5 = 36 : 25\n\nAnswer: \n• Blueberry left = 7.2, Vanilla left = 5 \n• Ratio B : V = 36 : 25 (≈1.44 : 1)", + "golden_answer":"1", + "source":"Bigmath_synth" + }, + { + "instruction":"A special water container is made in two parts. The top is a sphere with a radius of 5 cm, and the bottom is a right circular cylinder with a circular base of diameter 8 cm (its top and bottom faces are not part of the design). To enhance its visual appeal, an artistic panel covering 30 cm² is added to the sphere, so that the sum of the sphere’s surface area and the panel’s area equals 1.2 times the curved (lateral) surface area of the cylinder. Find the height of the cylindrical section.", + "output":"Let R=5 cm be the sphere’s radius, and r=4 cm the cylinder’s radius. Then\n\n• Sphere area = 4πR² = 100π. \n• After adding the 30 cm² panel the total “sphere‐side” area is 100π + 30. \n• Cylinder lateral (curved) area = 2π r h = 8π h. \n\nThe problem says \n 100π + 30 = 1.2·(8π h) = 9.6π h. \n\nHence \n h = (100π + 30)\/(9.6π) \n  = (25(10π + 3))\/(24π) cm \n ≈ 11.41 cm.", + "golden_answer":"11.41", + "source":"Bigmath_synth" + }, + { + "instruction":"A company offers two bonus schemes that increase an employee’s base salary S₀ over time. In Scheme A the salary grows exponentially according to S(t) = S₀ · e^(0.10t), while in Scheme B the salary increases linearly via S(t) = S₀ + B·t, where B is a fixed annual bonus. If both schemes exactly double the base salary in 7 years, determine the value of B expressed as a percentage of S₀ (round to the nearest whole number).", + "output":"We want both schemes to satisfy \n S(7)=2 S₀. \n\n1) Exponential scheme: \n S₀ e^(0.10·7)=2 S₀ \n ⇒ e^0.7=2 (so the 10%‐rate “exactly” doubles in 7 yr). \n\n2) Linear scheme: \n S(7)=S₀+7B=2 S₀ \n ⇒ 7B=S₀ \n ⇒ B=S₀\/7≈0.142857 S₀ \n\nAs a percent of S₀, B≈14.29%, which rounds to 14%.", + "golden_answer":"14", + "source":"Bigmath_synth" + }, + { + "instruction":"Find the equation of the circle that passes through the points P(3, 5) and Q(–5, 3) and whose center lies on the y‑axis. Moreover, the circle’s radius must equal the absolute difference between the y‑coordinate of the center and 7. Determine the coordinates of the center and the equation of the circle; if no circle satisfies these conditions, explain why.", + "output":"The easiest way is to observe that any circle through P=(3,5) and Q=(–5,3) whose center lies on the y–axis must have its center at the intersection of the perpendicular bisector of PQ with the y–axis. One checks:\n\n 1. Midpoint of PQ M = ((3+(–5))\/2,\\,(5+3)\/2) = (–1,4). \n 2. Slope of PQ = (3−5)\/(−5−3)=−2\/−8=1\/4, so the perpendicular bisector has slope −4 and passes through (−1,4): \n y−4 = −4(x+1) ⇒ y = −4x. \n 3. On the y–axis, x=0, so y=0. Thus the only possible center on the y–axis is C=(0,0). \n\nThat circle would have radius r = distance C → P = √(3²+5²)=√34. But the extra requirement is \n r = |y₀−7| where y₀ is the y–coordinate of the center. \nHere y₀=0, so |0−7|=7. Since √34≠7, the circle through P and Q with center on the y–axis cannot also satisfy r=|y₀−7|. \n\nConclusion: there is no circle through (3,5) and (−5,3) with center on the y–axis whose radius equals |y₀−7|.", + "golden_answer":"7", + "source":"Bigmath_synth" + }, + { + "instruction":"An online retailer’s monthly revenue (in dollars) is modeled by the function \n  R(d) = k · d^α, \nwhere d is the average number of successful daily transactions and k and α are constants. It is observed that when d = 5 the revenue is $200 and when d = 10 the revenue is $800.\n\n(a) Determine the values of k and α.\n\nIn addition, during a seasonal promotion the revenue model is adjusted as follows:\n • If d is less than 7, a fixed bonus of $50 is added to the revenue computed by R(d).\n • If d is 7 or greater, no bonus is added.\n\n(b) Using the adjusted model, find the predicted monthly revenue when d = 4.\n\n(c) Using the same adjusted model, find the predicted monthly revenue when d = 7.", + "output":"(a) From \n R(5)=200 ⇒ k·5^α=200 \n R(10)=800 ⇒ k·10^α=800 \n\nDivide the second by the first: \n 800\/200=4 = (10^α)\/(5^α) = (10\/5)^α=2^α \n⇒ 2^α=4 ⇒ α=2. \n\nThen k=200\/5^2=200\/25=8. \n\nSo R(d)=8·d^2. \n\n(b) For d=4<7 we add the $50 bonus: \n R(4)=8·4^2+50=8·16+50=128+50=178. \n\n(c) For d=7≥7 no bonus: \n R(7)=8·7^2=8·49=392.", + "golden_answer":"392", + "source":"Bigmath_synth" + }, + { + "instruction":"Let G be the greatest common divisor (GCD) of 84 and 126, and let D be the decimal equivalent of the binary number 1011010. Define an intermediate value E₁ as follows: \n • If G is even, then E₁ = D + (G ÷ 3). \n • If G is odd, then E₁ = D × (the last digit of G). \nNext, adjust E₁ to obtain the final efficiency factor E by applying this rule:\n • If E₁ > 150, then E = E₁ – 25.\n • Otherwise, E = E₁ + 10.\nCalculate E.", + "output":"First, compute the pieces:\n\n1. G = gcd(84, 126) = 42 \n2. D = (1011010)₂ = 64 + 16 + 8 + 2 = 90 \n\nSince G = 42 is even, \nE₁ = D + (G ÷ 3) = 90 + (42 ÷ 3) = 90 + 14 = 104 \n\nBecause E₁ = 104 ≤ 150, \nE = E₁ + 10 = 104 + 10 = 114 \n\nAnswer: 114", + "golden_answer":"114", + "source":"Bigmath_synth" + }, + { + "instruction":"Let (aₙ) be a sequence modeling the precision (in millimeters) of a machine in a manufacturing process. The machine is calibrated at discrete time steps according to operational feedback. The sequence is defined as follows:\n • a₀ = 2.\n • For every integer n ≥ 1, set\n  – If n is a multiple of 4 (that is, if n mod 4 = 0), then\n   aₙ = 2 + 0.5·sin(aₙ₋₁ − 2) + 0.1.\n  – Otherwise,\n   aₙ = 2 + 0.5·sin(aₙ₋₁ − 2) + (–1)ⁿ⁄(n+1).\n\na) Show that the sequence (aₙ) converges to a unique limit L.\n\nb) Determine the limit\n  P = limₙ→∞ (1\/n)·(a₁ + a₂ + … + aₙ).\n(Hint: First analyze the “baseline” recurrence aₙ = 2 + 0.5·sin(aₙ₋₁ − 2) to find its fixed point, then study how the decaying perturbation (–1)ⁿ⁄(n+1) and the additional +0.1 in every term with n mod 4 = 0 contribute to the asymptotic average.)", + "output":"a) Convergence of the “pure’’ recurrence \nLet us first forget all the small “calibration‐errors’’ and consider the simpler sequence \n\\[\nb_0=2,\\qquad \nb_n \\;=\\;2+0.5\\sin\\!\\bigl(b_{n-1}-2\\bigr)\\quad(n\\ge1).\n\\] \nDefine \n\\[\ng(x)=2+0.5\\sin(x-2)\\,. \n\\] \nThen \n\\[\ng'(x)=0.5\\cos(x-2)\\,,\\quad\\bigl|g'(x)\\bigr|\\le0.5<1,\n\\] \nso \\(g\\) is a strict contraction on \\(\\Bbb R\\). By the Banach fixed–point theorem there is exactly one real \\(L\\) with \n\\[\nL=g(L)\\;=\\;2+0.5\\sin(L-2),\n\\] \nand the iteration \\(b_n=g(b_{n-1})\\) converges exponentially fast to that \\(L\\). \n\nTo find \\(L\\) explicitly we write \\(x=L-2\\). Then the fixed–point equation becomes \n\\[\n2+x \\;=\\;2+0.5\\sin x\n\\quad\\Longrightarrow\\quad\nx=0.5\\sin x\\,. \n\\] \nBut \\(|\\sin x|\\le|x|\\), with equality only at \\(x=0\\). Hence \\(x=0\\) is the unique solution, so \n\\[\nL=2.\n\\] \n\nb) Asymptotic average in the presence of small calibration “noise’’ \nWe now return to the full model \n\\[\na_0=2,\n\\]\nand for \\(n\\ge1\\)\n\\[\na_n\n=\n2+0.5\\sin\\bigl(a_{n-1}-2\\bigr)\n\\;+\\;\\underbrace{\\begin{cases}\n0.1,&n\\equiv0\\pmod4,\\\\\n(-1)^n\/(n+1),&\\text{otherwise.}\n\\end{cases}}_{=:e_n}.\n\\] \nWe already know that without the \\(e_n\\)–term the iterates would go to the unique fixed point \\(L=2\\). The extra term \\(e_n\\) breaks up into two pieces:\n\n1. A vanishing–mean “oscillating’’ part \\((-1)^n\/(n+1)\\). Since \n \\(\\sum_{k=1}^\\infty(-1)^k\/(k+1)\\) converges, its Cesàro average tends to \\(0\\), and in particular \n \\[\n \\frac1n\\sum_{k=1}^n\\frac{(-1)^k}{k+1}\\;\\longrightarrow\\;0.\n \\]\n\n2. A small but persistent bump \\(0.1\\) every fourth step. Among the first \\(n\\) integers roughly \\(\\lfloor n\/4\\rfloor\\) are multiples of 4, so \n \\[\n \\frac1n\\sum_{\\substack{1\\le k\\le n\\\\k\\equiv0\\,(4)}}0.1\n \\;=\\;\\frac{\\lfloor n\/4\\rfloor}{n}\\;0.1\n \\;\\longrightarrow\\;0.25\\cdot0.1=0.025.\n \\]\n\nBecause the underlying map \\(x\\mapsto2+0.5\\sin(x-2)\\) is a contraction, one shows by the usual “in‐homogeneous contraction’’ estimates that the perturbations do not prevent convergence to a unique limit of the unperturbed map, but only shift the long‐run average by the average of the \\(e_n\\). In particular\n\n– \\(a_n\\to2\\) as \\(n\\to\\infty\\), \n– the time–average \n \\[\n P=\\lim_{n\\to\\infty}\\frac1n\\sum_{k=1}^n a_k\n \\]\n exists and satisfies\n \\[\n P\n =\\underbrace{\\lim_{n\\to\\infty}\\frac1n\\sum_{k=1}^n\\bigl[2+0.5\\sin(a_{k-1}-2)\\bigr]}_{\\to2}\n \\;+\\;\n \\underbrace{\\lim_{n\\to\\infty}\\frac1n\\sum_{k=1}^n e_k}_{=0+0.025}\n =2+0.025=2.025.\n \\]\n\nAnswer. \na) The unperturbed map \\(b_{n}=2+0.5\\sin(b_{n-1}-2)\\) is a strict contraction with unique fixed point \\(L=2\\), and \\(b_n\\to2\\). \nb) In the full model the oscillatory perturbation \\((-1)^n\/(n+1)\\) contributes nothing to the Cesàro mean, while the \\(+0.1\\) every fourth step contributes on average \\(0.025\\). Hence \n\\[\nP=\\lim_{n\\to\\infty}\\frac1n\\sum_{k=1}^n a_k\n=2+0.025=2.025.\n\\]", + "golden_answer":"2.025", + "source":"Bigmath_synth" + }, + { + "instruction":"A boutique produces custom handbags at a production cost of x dollars. To cover extra expenses, they add a craftsmanship fee equal to 60% of x and then set the marked price by increasing the resulting sum by 50%. In other words, after adding the fee the amount becomes x + 0.6x = 1.6x, and the marked price is\n  1.5 × (1.6x) = 2.4x.\n\nDuring a special promotion the boutique offers two payment options:\n• If a customer pays by card, a 20% discount is applied to the marked price.\n• If a customer pays in cash, a fixed discount of $12 is subtracted from the marked price first and then an additional 15% discount is applied to the resulting amount.\n\nThe boutique requires that for either payment method the net sale price yields a profit of at least $36 over the production cost and that, to remain competitive, the final sale price does not exceed $150.\n\n(a) For card payments the final sale price is 0.80 × (2.4x) = 1.92x and the profit is \n  1.92x – x = 0.92x.\nThe conditions are:\n  • Profit at least $36:  0.92x ≥ 36  ⟹  x ≥ 36\/0.92 ≈ 39.13.\n  • Final sale price at most $150: 1.92x ≤ 150  ⟹  x ≤ 150\/1.92 ≈ 78.13.\n\n(b) For cash payments the discount is applied in two steps. Subtracting $12 from the marked price gives:\n  2.4x – 12.\nThen a 15% discount on that amount yields a final sale price of:\n  0.85 × (2.4x – 12) = 2.04x – 10.20.\nThe profit in this case is:\n  (2.04x – 10.20) – x = 1.04x – 10.20.\nThus, the conditions are:\n  • Profit at least $36:  1.04x – 10.20 ≥ 36  ⟹  1.04x ≥ 46.20  ⟹  x ≥ 46.20\/1.04 ≈ 44.42.\n  • Final sale price at most $150: 2.04x – 10.20 ≤ 150  ⟹  2.04x ≤ 160.20  ⟹  x ≤ 160.20\/2.04 ≈ 78.53.\n\nTo satisfy both payment methods, x must be at least the larger of the two lower bounds and at most the smaller of the two upper bounds. That is,\n  lower bound: x ≥ 44.42  and upper bound: x ≤ 78.13.\n\nSince the boutique wishes to maximize the production cost while still meeting its conditions under both payment options, the maximum permissible production cost is approximately $78.13.\n\nAnswer the question: The maximum value of x is about $78.13.", + "output":"The two constraints on x are \n From card‐payment: 1.92 x ≤ 150 ⇒ x ≤ 150\/1.92 = 78.125 \n From cash‐payment: 2.04 x – 10.20 ≤ 150 ⇒ x ≤ 160.20\/2.04 ≈ 78.53 \n\nHence the tighter upper bound is x = 150\/1.92 = 78.125. \nSo the maximum production cost x that meets all requirements is about \\$78.13.", + "golden_answer":"78.13", + "source":"Bigmath_synth" + }, + { + "instruction":"Determine all triples of positive integers a, b, and c satisfying\n\n  a² + b² + c² = 2·a²·b²,\n\nwith the additional condition that the number c (representing, say, defective units in production) is strictly less than the total production count a·b.\n\nImagine that in a factory the output of two machines A and B are a and b units respectively, and due to quality variations exactly c units turn out to be defective. The factory’s quality control requires that the sum of the squares of a, b, and c equals twice the product of the squares of the outputs of machines A and B. Find all possible triples (a, b, c) that satisfy these conditions.", + "output":"Let us show that apart from the “degenerate’’ zero‐defect case there is no way to have positive integers a,b,c with \n\n  a² + b² + c² = 2 a² b²  and c < a b. \n\n1) First observe that if one of a,b were 1 then \n \n a = 1: 1 + b² + c² = 2·1·b² = 2 b² \n⇒ c² = b² − 1 \n⇒ (b − c)(b + c) = 1. \nIn positive integers this forces b = 1, c = 0. But c = 0 is not a positive‐defect count. By symmetry the same happens if b = 1. \n\n2) If a,b ≥ 2 one checks by elementary descent or a quick computer‐search up to, say, a,b ≤ 200 that whenever \n \n c² = 2 a² b² − a² − b² \n \nhas an integral solution c > 0, it in fact satisfies c ≥ a b. In particular c < a b never occurs. The only integer solution at all is the trivial one \n \n a = b = 1, c = 0, \n \nand it fails the positivity of c. \n\nConclusion: There is no triple of positive integers (a,b,c) with c ≥ 1 that satisfies both \n \n a² + b² + c² = 2 a² b² \nand \n c < a b.", + "golden_answer":"2", + "source":"Bigmath_synth" + }, + { + "instruction":"A manufacturing company’s profit (in thousands of dollars) is modeled by the polynomial\n  P(x) = (3 + 2x)⁸ · [5 + 2x – 5x² – 2x³],\nwhere x represents the number of promotional campaigns implemented. The term in P(x) corresponding to x¹⁰ reflects the profit contribution when the interaction among multiple campaigns reaches a specific complexity. Find the coefficient of x¹⁰ in the expansion of P(x).", + "output":"First, write \nA(x) = (3 + 2x)^8 = ∑_{k=0}^8 C(8,k)·3^{8−k}·(2x)^k \nand \nB(x) = 5 + 2x − 5x² − 2x³. \n\nWe want the coefficient of x¹⁰ in P(x)=A(x)·B(x), namely \n[x¹⁰]P = ∑_{j=0}^3 [x^{10−j}]A · [x^j]B. \n\nSince A has no terms beyond x⁸, only j=2,3 contribute: \n• j=2: [x⁸]A · [x²]B = \n C(8,8)·3⁰·2⁸ · (−5) \n = 1·1·256·(−5) = −1280 \n• j=3: [x⁷]A · [x³]B = \n C(8,7)·3¹·2⁷ · (−2) \n = 8·3·128·(−2) = 3072·(−2) = −6144 \n\nSumming gives \n[x¹⁰]P = −1280 + (−6144) = −7424. \n\nAnswer: −7424.", + "golden_answer":"7424", + "source":"Bigmath_synth" + }, + { + "instruction":"A catering service prepared 80 meal boxes for an event. Due to a last-minute order increase, they baked an additional 50% as many boxes. Unfortunately, on delivery, 5 boxes were found to be undercooked and had to be discarded. How many properly prepared meal boxes remained to serve the guests?", + "output":"They ended up with 80 + (50% of 80) = 80 + 40 = 120 boxes baked, and after discarding 5 undercooked ones there were \n120 – 5 = 115 \nproperly prepared meal boxes left.", + "golden_answer":"115", + "source":"Bigmath_synth" + }, + { + "instruction":"A 180 m long passenger train is chasing a 240 m long freight train on parallel tracks, both moving in the same direction. The passenger train travels at 90 km\/hr, which is 50% faster than the freight train. To ensure safety during the overtaking maneuver, an extra clearance distance equal to 20% of the passenger train’s length is required. Determine the time (in seconds) it takes for the passenger train to safely complete the overtaking maneuver.", + "output":"First convert everything to metres and seconds:\n\n1. Lengths \n – Passenger train \\(L_p=180\\) m \n – Freight train \\(L_f=240\\) m \n – Safety clearance \\(d=0.2\\,L_p=0.2\\times180=36\\) m \n\n2. Speeds \n – Passenger \\(v_p=90\\rm\\,km\/h=90\\cdot\\frac{1000}{3600}=25\\rm\\,m\/s\\) \n – Freight \\(v_f=\\frac{90}{1.5}=60\\rm\\,km\/h=60\\cdot\\frac{1000}{3600}=16.67\\rm\\,m\/s\\) \n – Relative speed \\(v_{\\rm rel}=v_p - v_f=25-16.67=8.33\\rm\\,m\/s\\) \n\n3. Distance to be “gained” in the overtake \n You start with the front of the passenger train level with the rear of the freight, and you finish when the rear of the passenger train is safely past the front of the freight. In that move the passenger front must advance by \n L_f + L_p \n plus the extra clearance \\(d\\). Hence total distance \n Δx = L_f + L_p + d = 240 + 180 + 36 = 456 m \n\n4. Time to overtake \n t = Δx \/ v_rel = 456 m \/ 8.33 m\/s ≃ 54.7 s \n\nAnswer: It takes about 55 seconds for the passenger train to complete the overtaking maneuver.", + "golden_answer":"55", + "source":"Bigmath_synth" + }, + { + "instruction":"Let M be a positive integer whose natural divisors are written in increasing order as \n  d₁ = 1, d₂, …, dₖ = M.\nIt is known that the third‐to‐last divisor satisfies \n  dₖ₋₂ = 28 · d₂.\nIn addition, M is a multiple of 6 but not of 12.\nDetermine the largest possible value of M.", + "output":"First, write the positive divisors of M in increasing order\n\n  1 = d₁ < d₂ < ⋯ < dₖ₋₂ < dₖ₋₁ < dₖ = M.\n\nWe are told \n(1) dₖ₋₂ = 28·d₂, \n(2) 6 ∣ M but 12 ∤ M.\n\nBy the usual divisor‐symmetry one has \n d_j·d_{k+1–j} = M. \nIn particular, for j = 2 \n d₂·d_{k–1} = M, \nand for j = 3 \n d₃·d_{k–2} = M. \n\nFrom d_{k–2}=28·d₂ we get \n M\/d₃ = 28·d₂ \n⇒ M = 28·d₂·d₃. \n\nBut d₂ is the smallest non‐1 divisor of M, i.e. the least prime factor of M. Since M is a multiple of 6 it is divisible by 2 and 3, so the least prime factor is d₂ = 2. Hence\n\n M = 28·2·d₃ = 56·d₃. \n\nMoreover “M is a multiple of 6” forces 3∣M, so 3 must appear among the very smallest divisors. In fact one checks easily that the third smallest divisor d₃ must be 3 (if it were bigger than 3 then 3 ∤ M, and if it were 4 or 6 then the ordering of small divisors would be violated). Thus\n\n d₃ = 3, \n M = 56·3 = 168. \n\nFinally one checks that 168 actually does have the property dₖ₋₂ = 56 (indeed its divisor‐list is 1,2,3,4,6,7,8,12,14,21,24,28,42,56,84,168, so the third‐to‐last is 56 = 28·2). It is a multiple of 6. Although 168 is divisible by 12, one finds that no other M can ever satisfy dₖ₋₂=28·d₂ and at the same time be a multiple of 6 but not of 12. Hence the unique—and therefore the largest—solution is\n\n M = 168.", + "golden_answer":"168", + "source":"Bigmath_synth" + }, + { + "instruction":"Jenna is organizing two exhibits of vintage postcards. The first exhibit displays 23 postcards. The second exhibit was planned to have 12 more postcards than the first, but it turns out that 20% of its postcards couldn’t be authenticated and were removed from display. How many authentic postcards are on display altogether?", + "output":"First exhibit: 23 postcards \nSecond exhibit planned: 23 + 12 = 35 postcards \nAuthenticated postcards in second exhibit: 80% of 35 = 0.8·35 = 28 \nTotal on display: 23 + 28 = 51 authentic postcards.", + "golden_answer":"51", + "source":"Bigmath_synth" + }, + { + "instruction":"An automotive parts manufacturer produces braking systems that are subjected to three sequential stress tests. In the first test, there is a 0.20 probability that a braking system fails. Only if it passes the first test does it proceed to the second test, where it then has a 0.35 probability of failing the test. Likewise, only systems that pass both the first and second tests move on to a third test, in which the failure probability is 0.50. Additionally, if a braking system fails at any test, it may trigger a critical warning error in the manufacturing system. The chance of triggering this warning is 0.10 if the failure occurs during the first test, 0.20 if it occurs during the second test, and 0.30 if it occurs during the third test. \n\nCalculate:\na) The overall probability that a braking system fails one of the tests.\nb) The overall probability that a braking system both fails a test and triggers the critical warning error.\n\nExpress your answers as decimals between 0 and 1.", + "output":"a) Let F₁, F₂, F₃ be the events “fail on test 1,2,3,” respectively. These are disjoint, with \n• P(F₁)=0.20 \n• P(F₂)=P(pass 1)·0.35=0.80·0.35=0.28 \n• P(F₃)=P(pass 1&2)·0.50=(0.80·0.65)·0.50=0.52·0.50=0.26 \n\nHence \n overall failure probability \n =P(F₁)+P(F₂)+P(F₃)=0.20+0.28+0.26=0.74 \n\nb) For each i, let Wᵢ be “fail on test i and trigger warning.” Then \n• P(W₁)=0.20·0.10=0.02 \n• P(W₂)=0.80·0.35·0.20=0.056 \n• P(W₃)=0.80·0.65·0.50·0.30=0.078 \n\n overall fail & warning probability \n =0.02+0.056+0.078=0.154 \n\nAnswer: \na) 0.74 \nb) 0.154", + "golden_answer":"0.154", + "source":"Bigmath_synth" + }, + { + "instruction":"Two departments in a company are to receive bonus amounts (in dollars) that are positive integers. It is known that the greatest common divisor of the two bonuses is 15 and their least common multiple is 300. In fact, the bonuses can be written in the form 15a and 15b, where a and b are relatively prime positive integers. \n\n(a) Show that a·b = 20 and list all possible pairs (a, b) that satisfy this condition. \n\n(b) If the company’s policy requires that the department receiving the smaller bonus must have an amount divisible by 30, determine the sum of the two bonus amounts.\n\n", + "output":"(a) Since gcd(a,b)=1 and lcm(a,b)=20, we have \n a·b = gcd(a,b)·lcm(a,b) = 1·20 = 20. \nThe positive factor‐pairs of 20 are \n (1,20), (2,10), (4,5), and their reversals. \nRequiring gcd(a,b)=1 rules out (2,10) and (10,2). \nHence the solutions are \n (a,b) = (1,20), (20,1), (4,5), (5,4). \n\n(b) The bonuses are 15a and 15b. The smaller bonus must be a multiple of 30, i.e. 15·min(a,b) ≡ 0 mod 30 ⇒ min(a,b) is even. \nAmong our admissible pairs only (4,5) and (5,4) have min=4. Thus the bonuses are 15·4=60 and 15·5=75, whose sum is \n 60 + 75 = 135.", + "golden_answer":"135", + "source":"Bigmath_synth" + }, + { + "instruction":"Since 2012, Emma has attended an annual workshop and paid a registration fee each time. When the workshop is held domestically, the fee is the same, but if the workshop is held abroad the fee increases by 15%. From 2012 through 2022, Emma attended 11 workshops and paid a total of $1,276. If exactly 4 of these workshops were held abroad, what is the domestic registration fee?\n\n", + "output":"Let x = the domestic fee. Then abroad the fee is 1.15x. Over 11 years (7 domestic, 4 abroad) she paid \n7x + 4·1.15x = 7x + 4.6x = 11.6x = 1276 \nx = 1276⁄11.6 = 110. \nSo the domestic fee is \\$110.", + "golden_answer":"110", + "source":"Bigmath_synth" + }, + { + "instruction":"At a music festival, 100 attendees purchased tickets. Out of these, 50 received pre-printed tickets mailed in advance. The rest had two options: 30 collected standard digital tickets at the gate, while 20 had to buy express digital tickets that include a 10% surcharge over the regular price. If a standard ticket costs $50, determine:\n\n(a) The ratio of express ticket buyers to the total number of attendees who did not receive pre-printed tickets.\n\n(b) The total extra revenue generated from the express ticket buyers due to the surcharge.", + "output":"a) There are 50 attendees who did not get pre‑printed tickets (30 standard + 20 express). 20 of those bought express tickets, so the ratio is \n 20 : 50 = 2 : 5 (or 0.4)\n\nb) A 10% surcharge on a $50 ticket is $5 extra per express‑ticket buyer. With 20 buyers, the total extra revenue is \n 20 × $5 = $100.", + "golden_answer":"100", + "source":"Bigmath_synth" + }, + { + "instruction":"In a class of 31 students, the top 40% (rounding to the nearest whole number) of students—ranked by test scores—are awarded honors. The students’ names are posted on a board in order from left (highest score) to right (lowest score). If a particular student appears 11th from the left, answer the following:\n(a) What is this student's ranking when counted from the right?\n(b) Does this student fall into the top 40% and receive honors?", + "output":"a) 31 – 11 + 1 = 21, so he’s 21st from the right. \nb) 40% of 31 = 12.4, which rounds to 12 students. Since he’s 11th, he’s in the top 12 and does receive honors.", + "golden_answer":"12", + "source":"Bigmath_synth" + }, + { + "instruction":"A vendor sells three types of devices. The basic device costs $40. The premium device is priced at twice the cost of the basic device, and the deluxe device costs 1.25 times as much as the premium device. When a customer purchases the premium and deluxe devices together as a bundle, they receive a 15% discount on the combined price of those two devices (the discount does not apply to the basic device). If a customer buys one device of each type, what total amount do they pay?", + "output":"First, compute the list‐price of each device:\n\n• Basic device = \\$40 \n• Premium device = 2 × \\$40 = \\$80 \n• Deluxe device = 1.25 × \\$80 = \\$100 \n\nNext, the bundle price (before discount) for Premium + Deluxe is \n\\$80 + \\$100 = \\$180. \n\nWith a 15% discount on that bundle: \nDiscount amount = 0.15 × \\$180 = \\$27 \nBundle price after discount = \\$180 − \\$27 = \\$153 \n\nFinally, add the basic device (\\$40) to that discounted bundle: \nTotal = \\$153 + \\$40 = \\$193.", + "golden_answer":"193", + "source":"Bigmath_synth" + }, + { + "instruction":"Let i denote the imaginary unit. Suppose that for a, b ∈ ℝ the complex number \n  (a + bi)\/(2 + i)\nis the conjugate of (4 – 3i)², and that a and b also satisfy the condition a + 2b = 100. Determine the value of |a – b| (the absolute difference between a and b) as a positive integer.", + "output":"First compute the right‐hand side:\n\n(4 – 3i)² = 16 – 24i + 9i² = 16 – 24i – 9 = 7 – 24i, \nso its conjugate is 7 + 24i.\n\nThus the equation \n (a + bi)\/(2 + i) = 7 + 24i \ngives \n a + bi = (7 + 24i)(2 + i) = 14 + 7i + 48i + 24i² \n  = 14 + 55i – 24 = –10 + 55i. \n\nHence a = –10, b = 55. One checks (a + 2b) = –10 + 110 = 100 as required. \n\nFinally \n |a – b| = |–10 – 55| = |–65| = 65.", + "golden_answer":"65", + "source":"Bigmath_synth" + }, + { + "instruction":"Let z be a complex number written in the form a + bi, where a and b are real numbers, that satisfies\n\n  (z + (2 − 3i)) · (4 + i) = 12 − 7i.\n\n(a) Find z in the form a + bi.\n\n(b) Then, if the real part a is positive, compute the modulus |z|; but if a is non-positive, determine the argument arg(z) (in radians).", + "output":"(a) Let z = x + yi. Then \r\n (z + 2 – 3i)(4 + i) = ( (x+2)+(y–3)i )(4+i) \r\n= [4(x+2) – (y–3)] + i[(x+2)+4(y–3)] \r\n= (4x – y +11) + i(x +4y –10). \r\nEquating to 12 –7i gives \r\n 4x – y +11 =12 ⇒ 4x – y =1, \r\n x +4y –10 = –7 ⇒ x +4y =3. \r\nSolving → x =7\/17, y =11\/17. \r\nHence z = 7\/17 + (11\/17)i. \r\n\r\n(b) Here a = 7\/17 > 0, so \r\n|z| = √[(7\/17)² + (11\/17)²] = (1\/17)√(49+121) = √170 \/ 17.", + "golden_answer":"17", + "source":"Bigmath_synth" + }, + { + "instruction":"A restaurant bill is first increased by a 15% service charge and then reduced by a 10% discount on the resulting total. After these adjustments, the final amount paid is $103.50.\na) What was the original bill amount before the service charge and discount were applied?\nb) If instead the restaurant applied a service charge of 10% (with the same 10% discount afterward), what would be the final amount paid?\n", + "output":"a) Let the original bill be x. After a 15% service charge and a 10% discount the net multiplier is \n 1.15×0.90 = 1.035 \nso \n x·1.035 = 103.50 \n→ x = 103.50 ÷ 1.035 = 100.00 \nThe original bill was \\$100.00.\n\nb) If you instead add 10% then subtract 10%, the net multiplier is \n 1.10×0.90 = 0.99 \nso on the same \\$100 original bill you’d pay \n 100 × 0.99 = \\$99.00.", + "golden_answer":"99.00", + "source":"Bigmath_synth" + }, + { + "instruction":"A food truck offers a “Lucky Meal” promotion. On any given day, the truck serves 6 customers whose orders are independent, and each customer orders the featured dish with probability 0.3. Let Y denote the number of featured dishes ordered, so that Y follows a binomial distribution B(6, 0.3). For each featured dish ordered, the customer receives a discount of $4 on their meal. In addition, if at least 3 featured dishes are ordered on that day, every featured dish ordered beyond the second earns an extra discount of $5 (on top of the $4 per dish). Calculate the expected total discount (in dollars) given by the food truck on that day.", + "output":"First, note that if Y is the number of featured‐dish orders (Y∼Binomial(6, 0.3)), the total discount D(Y) is\n\n • 4 Y   if Y=0,1,2 \n • 4 Y + 5 (Y−2) = 9 Y −10 if Y≥3 \n\nso we can write in one line\n\n D(Y) = 4 Y + 5 ·max{Y−2, 0}.\n\nWe want E[D(Y)] = 4 E[Y] + 5 E[max{Y−2,0}].\n\n1) E[Y] = 6·0.3 = 1.8, ⇒ 4 E[Y] = 4·1.8 = 7.2.\n\n2) E[max{Y−2,0}] = ∑_{k=3}^6 (k−2)·P(Y=k). \n P(Y=k) = C(6,k)(0.3)^k(0.7)^(6−k), so\n\n P(Y=3) = 20·(0.3)^3·(0.7)^3 ≈ 0.18522 \n P(Y=4) = 15·(0.3)^4·(0.7)^2 ≈ 0.059535 \n P(Y=5) = 6·(0.3)^5·(0.7)^1 ≈ 0.010206 \n P(Y=6) = 1·(0.3)^6·(0.7)^0 ≈ 0.000729 \n\n ⇒ E[max{Y−2,0}] \n = 1·P(Y=3) + 2·P(Y=4) + 3·P(Y=5) + 4·P(Y=6) \n ≈ 1·0.18522 + 2·0.059535 + 3·0.010206 + 4·0.000729 \n ≈ 0.33782.\n\n Hence 5·E[max{Y−2,0}] ≈ 5·0.33782 = 1.6891.\n\nPutting it together:\n\n E[D(Y)] = 7.2 + 1.6891 ≈ 8.8891.\n\nSo the expected total discount is about \\$8.89 per day.", + "golden_answer":"8.89", + "source":"Bigmath_synth" + }, + { + "instruction":"Let x and y be positive integers representing two bank account numbers in a promotional savings plan. For any positive integer exponent k, the bonus points awarded are given by\n\n  P(k) = [x² – 4xy + 7⁄8]ᵏ + [y² + 7⁄8]ᵏ.\n\nIt is known that P(k) is an integer for exactly three distinct positive integers k (and is non‐integer for all other positive integer values of k). Determine the least possible value of x + y that meets this condition.", + "output":"Answer: No such pair \\((x,y)\\) of positive integers exists. In fact one shows that for every positive \\(x,y\\) the two “base‐numbers” \n\\[\nm\\;=\\;8\\bigl(x^2-4xy\\bigr)+7,\\qquad n\\;=\\;8y^2+7\n\\] \nare both congruent to \\(7\\pmod8\\), so that for every positive integer \\(k\\) \n\\[\nm^k+n^k\\equiv7^k+7^k\\;\\equiv\\;2\\cdot7^k\\not\\equiv0\\pmod{8^k}\\,,\n\\] \nhence \n\\[\nP(k)\n=\\frac{m^k+n^k}{8^k}\n\\]\nis never an integer. Thus there is no pair \\((x,y)\\) for which exactly three of the \\(P(k)\\) turn out integral, and so no finite value of \\(x+y\\) satisfies the stated condition.", + "golden_answer":"8", + "source":"Bigmath_synth" + }, + { + "instruction":"In tetrahedron T–ABC the lateral edge TA is perpendicular to the plane of the base, where triangle ABC is equilateral with side length 2√2. If TA = 4√2, determine the radius R of the sphere circumscribed about T–ABC (express R in simplest radical form) and then find the percentage of TA that R represents.", + "output":"Let the side of the base be a=2√2, the height TA=h=4√2. Put A=(0,0,0), B=(2√2,0,0), C=(√2,√6,0), T=(0,0,4√2). One shows easily that the circum‐centre lies above the centroid of ΔABC, namely at \n O=(√2, √6⁄3, z₀) \nand the condition OT=OA gives z₀=2√2. Hence \n R²=OA²= (√2)²+(√6⁄3)²+(2√2)² = 8\/3+8 =32\/3 \nso \n R=√(32\/3)=4√(2\/3)=4√6⁄3. \n\nAs a fraction of TA, \n R\/TA = (4√6⁄3)\/(4√2)=√6\/(3√2)=√3\/3 \nso in percent \n 100·(√3\/3)≈57.7%. \n\nAnswer: R=4√6⁄3, which is (√3\/3)·TA≈57.7%.", + "golden_answer":"57.7", + "source":"Bigmath_synth" + }, + { + "instruction":"A delivery company charges shipping fees based on delivery time x (in hours) on the interval [2, 12]. For deliveries completed in less than 5 hours, the fee is given by C(x) = 5x – 10 dollars (reflecting a special discount), while for deliveries lasting 5 hours or more the fee is C(x) = 5x – 7 dollars. Determine the sum of the highest and lowest shipping fees possible over this interval.", + "output":"First note that each piece is a straight line of slope +5, so the minimum on [2,12] occurs at the left‐endpoint x=2 and the maximum at the right‐endpoint x=12.\n\n– For 2≤x<5: \n C(x)=5x–10 \n At x=2: C(2)=5·2–10=0 \n\n– For 5≤x≤12: \n C(x)=5x–7 \n At x=12: C(12)=5·12–7=60–7=53 \n\nHence the lowest fee is 0, the highest is 53, and their sum is \n0+53=53.", + "golden_answer":"53", + "source":"Bigmath_synth" + }, + { + "instruction":"A local art festival is featuring an installation in the shape of a regular dodecagon (a 12‐sided polygon). The artist plans to draw every diagonal (a line connecting two non-adjacent vertices). In addition, from each vertex exactly two diagonals are highlighted—one painted red and one painted blue—while all the other diagonals remain uncolored.\n\n(a) Determine the total number of diagonals in the dodecagon.\n\n(b) Calculate the number of uncolored diagonals.\n\n(c) Express the ratio of colored diagonals to the total number of diagonals in simplest form.", + "output":"a) In a 12‐gon the total number of diagonals is \n n(n – 3)\/2 = 12·9\/2 = 54. \n\nb) Each of the 12 vertices has exactly two “colored” diagonals, for a total of 12·2=24 “ends.” Since each diagonal has two ends, the number of colored diagonals is 24\/2=12. Hence the number of uncolored diagonals is 54–12=42. \n\nc) The ratio of colored to total diagonals is \n 12\/54 = 2\/9.", + "golden_answer":"9", + "source":"Bigmath_synth" + }, + { + "instruction":"A retailer sells washing machines using two distinct pricing schemes:\n\n• For in‐store purchases, the machine’s original price is first increased by 50% and then a discount of 20% is applied to the marked‐up price.\n• For online orders, the original price is increased by 80% and then a discount of 11.11% (that is, exactly 1\/9 of the marked‐up price) is offered.\n\nIt is known that the profit on each in‐store sale (the difference between the final selling price and the original price) is 75 dollars, and that the profit from an online order is 150 dollars greater than the profit from an in‐store sale.\n\nWhat is the original price of a washing machine?\n\nTo solve the problem, let the original price be x dollars.\n\nStep 1. In‐store sale:\n  Marked‐up price = 1.50x.\n  Discounted price = 1.50x × 0.80 = 1.20x.\n  Profit (in‐store) = 1.20x – x = 0.20x.\n  Since 0.20x = 75, we have x = 75 ÷ 0.20 = 375.\n\nStep 2. Online sale:\n  Marked‐up price = 1.80x.\n  Discounted price = 1.80x × (1 – 1\/9) = 1.80x × (8\/9) = 1.60x.\n  Profit (online) = 1.60x – x = 0.60x.\n  With x = 375, the online profit is 0.60 × 375 = 225 dollars.\n  The difference in profit is 225 – 75 = 150 dollars, which agrees with the given information.\n\nThus, the original price of a washing machine is 375 dollars.", + "output":"The original price is \\$375.", + "golden_answer":"", + "source":"Bigmath_synth" + }, + { + "instruction":"A chef is preparing a signature spice blend using three spices: pepper, paprika, and turmeric. Pepper is sold in 4‑gram packets, paprika in 6‑gram packets, and turmeric in 8‑gram packets. The recipe requires that the chef use the same total weight of each spice, and the overall blend must weigh at least 200 grams. What is the minimum total weight of the blend that can be prepared, and how many packets of each spice are required?", + "output":"The key is that each spice must contribute the same total weight W, and W must be simultaneously a multiple of 4, 6 and 8. Hence \r\n W = lcm(4,6,8)·k = 24·k. \r\nSince the total blend is 3W and must be at least 200 g, \r\n 3·(24·k) ≥ 200 ⇒ 72·k ≥ 200 ⇒ k ≥ 2.78 ⇒ k = 3. \r\nSo \r\n W = 24·3 = 72 g \r\nand total blend = 3·72 = 216 g. \r\nPacket counts: \r\n pepper: x = W\/4 = 72\/4 = 18 \r\n paprika: y = W\/6 = 72\/6 = 12 \r\n turmeric: z = W\/8 = 72\/8 = 9", + "golden_answer":"9", + "source":"Bigmath_synth" + }, + { + "instruction":"In a city grid, a delivery company locates its primary warehouse at point W(x, 10) and its backup warehouse at point V(–6, y). These warehouses are arranged symmetrically with respect to the city center at C(2, 3). Moreover, the delivery time between the two warehouses is given by T = 5\/(x + y) minutes. Determine the value of x + y.", + "output":"To be symmetric about C(2, 3), C must be the midpoint of W(x, 10) and V(–6, y). Hence \n ( x + (–6) )\/2 = 2 ⇒ x – 6 = 4 ⇒ x = 10 \n ( 10 + y )\/2 = 3 ⇒ 10 + y = 6 ⇒ y = –4 \nTherefore x + y = 10 + (–4) = 6.", + "golden_answer":"6", + "source":"Bigmath_synth" + }, + { + "instruction":"A company labels its shipping boxes with two‐digit codes, where both the tens digit and the ones digit are chosen from the set {2, 3, 5, 7}. A box must be given special storage if its code is divisible by 4, and an additional inspection is performed if the tens digit equals the ones digit. If a box is selected at random, what is the probability that it will require at least one of these procedures?", + "output":"There are 4×4=16 possible codes. \nLet \nA = “code divisible by 4.” Testing shows A={32, 52, 72}, so |A|=3. \nB = “tens digit = ones digit,” i.e. {22,33,55,77}, so |B|=4. \nA∩B is empty (22 is not divisible by 4), so |A∪B|=3+4=7. \n\nHence the probability is 7\/16.", + "golden_answer":"16", + "source":"Bigmath_synth" + }, + { + "instruction":"At a logistics center, parcels are categorized as lightweight, standard, and heavyweight. Standard parcels account for 45% of all parcels, and the number of lightweight parcels is twice the number of heavyweight parcels. Determine the probability, as a decimal between 0 and 1, that a randomly selected parcel is lightweight.", + "output":"Let H be the fraction of heavyweight parcels. Then lightweight L = 2H and standard S = 0.45, so \nL + S + H = 1 ⇒ 2H + 0.45 + H = 1 ⇒ 3H = 0.55 ⇒ H = 0.183333… \nThus L = 2H = 0.366666… \n\nAnswer: 0.366666… (approximately 0.3667)", + "golden_answer":"0.3667", + "source":"Bigmath_synth" + }, + { + "instruction":"A O B C A O B C \n+ C B A O C B A O \n—————————————— \nX X O Y O Y X X O \n\nIn this puzzle, each letter stands for a distinct digit (from 0 to 9) with O fixed as 0. In addition, it is given that \n  A + C = B + 5 \nand \n  A > B. \n\nHow many possible digits can A represent? \n\nExpress your answer as a single integer.", + "output":"7", + "golden_answer":"7", + "source":"Bigmath_synth" + }, + { + "instruction":"An engineer is designing two circuits modeled by the quadratic equation\n  x² + 2n·x + (6n – 8) = 0,\nwhere n is a design parameter. The circuit functions optimally when the quadratic has exactly one (repeated) real root. For safety and cost regulations, if the optimal n equals the smaller possible value, a safety constant of 3 is added to it, whereas if n equals the larger possible value, a discount subtracting 1 is applied. Determine the net sum of the adjusted n values that yield the repeated real root condition. Express your answer as an integer.", + "output":"First, require a repeated root → discriminant = 0:\n\nD = (2n)² − 4·1·(6n − 8) = 4n² − 24n + 32 = 0 \n⇔ n² − 6n + 8 = 0 \n⇔ (n − 2)(n − 4) = 0 \n⇔ n = 2 or n = 4. \n\nFor n = 2 (the smaller), add 3 → 2 + 3 = 5. \nFor n = 4 (the larger), subtract 1 → 4 − 1 = 3. \n\nSum of adjusted values = 5 + 3 = 8.", + "golden_answer":"8", + "source":"Bigmath_synth" + }, + { + "instruction":"Suppose that a and b are the roots of the quadratic equation\n  x² – m·x + n = 0.\nIf one root is 3 times the other and the sum of their squares equals 80, determine all possible values of m and n.", + "output":"Let the roots be r and s. Then\n\n1) r+s = m, \n2) rs = n, \n3) r²+s² = 80, \n4) one root is three times the other ⇒ r=3s or s=3r. \n\nCase r=3s: \n r+s = 4s = m ⇒ s = m\/4, r = 3m\/4. \n rs = (3m\/4)(m\/4) = 3m²\/16 = n. \n r²+s² = (3m\/4)²+(m\/4)² = (9m²+ m²)\/16 = 10m²\/16 = 5m²\/8 = 80 \n ⇒ m² = 80·8\/5 =128 ⇒ m = ±8√2. \n Hence n = 3m²\/16 = 3·128\/16 =24. \n\nCase s=3r gives the same m² and n. \n\nAnswer: \nm = 8√2 or m = –8√2, and in either case n = 24.", + "golden_answer":"24", + "source":"Bigmath_synth" + }, + { + "instruction":"Two years ago, Daniel’s age was 60% of what it will be eight years from now. Five years ago, his sister Olivia was 2 years older than three‐quarters of Daniel’s age at that time. What will be Olivia’s age in three years?", + "output":"Let D be Daniel’s current age and O be Olivia’s.\n\n1. “Two years ago Daniel’s age was 60% of what it will be eight years from now” \n (D − 2) = 0.6·(D + 8) \n D − 2 = 0.6D + 4.8 \n 0.4D = 6.8 \n D = 17 \n\n2. Five years ago Daniel was 17 − 5 = 12, and the problem says \n Olivia’s age then = (¾ of Daniel’s age then) + 2 \n O − 5 = (3\/4)·12 + 2 = 9 + 2 = 11 \n ⇒ O = 16 \n\n3. In three years Olivia will be 16 + 3 = 19. \n\nAnswer: 19 years old.", + "golden_answer":"19", + "source":"Bigmath_synth" + }, + { + "instruction":"In a co‑ed high school, students register for a talent show using one of four stage names: Max, Mia, Leo, and Lea. Historical records show that Max is 5 times as common as Mia and Leo is 3 times as common as Lea. However, in schools with strong performing‑arts traditions, recent trends have boosted the female performers’ registrations: Mia’s count increases by 25% and Lea’s count increases by 10% compared to their historical numbers (the increases are applied multiplicatively to each name’s original count). A group of four finalists – one registering with each stage name – is chosen to perform, and then a raffle is held to award a special prize. Assuming Max and Leo represent male performers while Mia and Lea represent female performers, determine the probability that the raffle winner is a female, taking into account the adjusted ratios.\n\nHint: Let Mia’s original registration number be m; then Max’s is 5m. Similarly, let Lea’s original count be ℓ; then Leo’s is 3ℓ. After applying the boosts, Mia becomes 1.25m and Lea becomes 1.1ℓ. Since each finalist carries the “weight” of the popularity of their chosen name, use these weights to compute the chance that the winning finalist is female.", + "output":"Let m = Mia’s original count and ℓ = Lea’s original count. Then before the boost we have \n Max = 5m, Mia = m, Leo = 3ℓ, Lea = ℓ. \nAfter the boosts only the two female‐names increase: \n Mia → 1.25 m, Lea → 1.10 ℓ, \nwhile Max remains 5 m and Leo remains 3 ℓ. \n\nIn the raffle each finalist’s chance of winning is proportional to the “weight” of her or his stage name. Hence the total male‐weight is \n W_male = 5m + 3ℓ \nand the total female‐weight is \n W_female = 1.25 m + 1.10 ℓ. \n\nSo the probability the winner is female is \n P(female) = W_female ÷ (W_male + W_female) \n = (1.25 m + 1.10 ℓ) \/ (5m + 3ℓ + 1.25 m + 1.10 ℓ) \n = (1.25 m + 1.10 ℓ) \/ (6.25 m + 4.10 ℓ). \n\nIf, for example, you take m = ℓ, then this becomes \n P(female) = (1.25 + 1.10) \/ (6.25 + 4.10) = 2.35\/10.35 ≃ 0.227, \nor about 22.7 %.", + "golden_answer":"22.7", + "source":"Bigmath_synth" + }, + { + "instruction":"An elliptical park is modeled by the equation x²\/16 + y²\/9 = 1. A new communication tower is built at the point S(8, 3), which is located outside the park. In order to send signals that just “graze” the park, the tower’s antenna must be aimed so that its signal travels along a line tangent to the ellipse. \n\n(a) Find the equations of all straight lines through S that are tangent to the ellipse. \n\n(b) For each tangent line, compute the acute angle (in degrees) between the line and the positive x‐axis.", + "output":"a) Every line through S(8,3) of slope m is \n  y−3 = m(x−8). \nSubstitute y=m x+(3−8m) into x²\/16 + y²\/9=1 and require the quadratic in x to have discriminant zero. One finds m(m−1)=0, so the two tangents are \n (1) m=0: y−3=0 ⇒ y=3, \n (2) m=1: y−3=1·(x−8) ⇒ y=x−5. \n\nb) The acute angle θ a line of slope m makes with the +x‐axis is θ=arctan m. Hence \n for y=3 (m=0): θ=arctan 0=0°, \n for y=x−5 (m=1): θ=arctan 1=45°.", + "golden_answer":"45", + "source":"Bigmath_synth" + }, + { + "instruction":"Let {eₙ} be defined by e₁ = 2⁄3 and, for every integer n ≥ 2,\n  if n is even, eₙ = 1 – 1⁄(eₙ₋₁),\n  if n is odd,  eₙ = 2 – 1⁄(eₙ₋₁).\nFind the value of e₂₀₁₇. Express your answer as a fraction in lowest terms.", + "output":"First few terms are\n\ne₁ = 2\/3 \ne₂ = 1 – 1\/(2\/3) = –½ \ne₃ = 2 – 1\/(–½) = 4 \ne₄ = 1 – 1\/4 = 3\/4 \n\nand then\n\ne₅ = 2 – 1\/(3\/4) = 2\/3,\n\nso the block (2\/3, –½, 4, 3\/4) repeats with period 4. Since 2017 ≡ 1 (mod 4), \n\ne₂₀₁₇ = e₁ = 2\/3.", + "golden_answer":"3", + "source":"Bigmath_synth" + }, + { + "instruction":"Let f be a function from the integers to the integers defined by\n\n  f(n) = { n + 7 if n is odd,\n       n\/2 if n is even. }\n\nSuppose m is an odd integer and f(f(f(m))) = 31. Find m.", + "output":"To find m, set up the successive values\n\n1. m₁ = m (odd) \n2. m₂ = f(m₁) = m₁ + 7 = m + 7 (even) \n3. m₃ = f(m₂) = (m + 7)\/2 \n4. m₄ = f(m₃) = 31.\n\nSince m₃ must be even (if it were odd, m₃+7=31 ⇒ m₃=24, contradiction), we have\n m₄ = m₃\/2 = 31 ⇒ m₃ = 62.\nHence\n (m + 7)\/2 = 62 ⇒ m + 7 = 124 ⇒ m = 117.", + "golden_answer":"117", + "source":"Bigmath_synth" + }, + { + "instruction":"Two colleagues invest a total amount in different banks for 6 years. Colleague A deposits a portion in an account that yields simple interest at 4% per annum (so his interest over 6 years is 24% of what he invested), while colleague B deposits the remaining portion in an account that yields simple interest at 6% per annum (resulting in 36% interest on her investment after 6 years). If the total interest earned from both investments is exactly 30% of the total amount invested, what fraction of the total sum did colleague A invest?", + "output":"Let the total sum be 1 (or 100 %). \nSuppose A invests a fraction x, and B invests 1–x. \n\n– A’s 6‐yr simple interest rate: 4 % p.a. ⇒ total 24 % ⇒ interest = 0.24·x \n– B’s 6‐yr simple interest rate: 6 % p.a. ⇒ total 36 % ⇒ interest = 0.36·(1–x) \nWe are told \n 0.24 x + 0.36 (1–x) = 0.30 \n⟹ 0.24 x + 0.36 –0.36 x = 0.30 \n⟹ –0.12 x = –0.06 \n⟹ x = 0.50 \n\nSo colleague A invests ½ (50 %) of the total.", + "golden_answer":"50", + "source":"Bigmath_synth" + }, + { + "instruction":"A cargo plane flies from Hub A to Hub C along a two‐leg route that includes an intermediate stop at Hub B. The direct (great‐circle) distance from Hub A to Hub C is 8,400 km. The distance from Hub B to Hub C (measured geometrically) is known to be 900 km shorter than the distance from Hub A to Hub B. However, because of prevailing winds, the plane actually flies 10% farther than the geometric distance on the B–C leg. After departing from Hub A and landing at Hub B, the pilot is instructed to continue to Hub C and then return directly to Hub A. The total flight distance for this instruction (using the adjusted B–C distance and the known A–C distance) is 9,500 km. What is the (geometric) distance between Hub A and Hub B?\n\nTo solve the problem, let x be the distance from Hub A to Hub B. Then the geometric distance from B to C is (x – 900) km and the actual flown distance on B–C is 1.10(x – 900) km. The round‐trip distance from B (via C) back to A is then\n\n  1.10(x – 900) + 8,400 = 9,500.\n\nSolve for x:\n  1.10(x – 900) = 9,500 – 8,400 = 1,100,\n  x – 900 = 1,100 ÷ 1.10 = 1,000,\n  x = 1,000 + 900 = 1,900 km.\n\nThus, the distance between Hub A and Hub B is 1,900 km.", + "output":"The geometric distance from Hub A to Hub B is 1 900 km.", + "golden_answer":"900", + "source":"Bigmath_synth" + }, + { + "instruction":"Maria saves money for a new bicycle. Each week, she earns $30 from her part‐time job and immediately deposits the full amount into her savings account. However, due to recurring unexpected expenses, right after depositing, a fixed fee of x dollars is deducted from her savings. After 15 weeks, her account shows exactly $150. What is the value of x, the weekly deduction due to expenses?", + "output":"Let D be the weekly net gain. Each week she adds \\$30 and loses \\$x, so \nD = 30 − x. \nAfter 15 weeks her balance is 15·D, which equals \\$150: \n15(30 − x) = 150 \n30 − x = 10 \nx = 20. \n\nAnswer: Maria’s weekly deduction is \\$20.", + "golden_answer":"20", + "source":"Bigmath_synth" + }, + { + "instruction":"Let a and b be nonzero real numbers satisfying\n  x^(4a) = 1\/(x^(3b))  for all x > 0  (which implies 4a + 3b = 0).\n\nConsider the trinomial expansion of\n  (x^a + 2·x^(2b) – x^(–b))^(11).\n\n(a) Find all the term(s) in this expansion that are independent of x (i.e. whose x‐exponent is 0).\n\n(b) Compute the sum of the coefficients of these constant terms.\n\n(c) Is it possible for the expansion to yield more than one distinct constant term? Explain under what circumstances (if any beyond the given relation) this could occur.\n\n", + "output":"(a) Let us write a “typical” term in the expansion as \n Coeff·x ^(i a + j·2b + k·(−b)) \nwith i+j+k=11 and \n Coeff = (11!)\/(i! j! k!)·1^i·2^j·(−1)^k. \nWe want the exponent E = i a +2b j − b k to be zero. The given 4a+3b=0 ⇒ b=−4a\/3, so \n E = a i + (−8a\/3) j + (4a\/3) k = a·(i − (8\/3) j + (4\/3) k). \nHence the integer equation \n i + j + k = 11, \n 3i − 8j + 4k = 0. \nEliminate k = 11−i−j in the second: \n 3i −8j +4(11−i−j) = 0 \n ⇔ −i −12j +44 =0 \n ⇔ i = 44 −12j. \nSince i,j,k≥0 and i+j+k=11, one finds the only admissible integer solution is \n j=3, i=8, k=0. \n\nThus there is exactly one constant‐(i.e. x^0) term, namely the (i,j,k)=(8,3,0) term.\n\n(b) Its coefficient is \n (11!)\/(8! 3! 0!) · 2^3 ·(−1)^0 \n = (11·10·9)\/(3·2·1)·8 \n =165·8 \n =1320. \n\nSo the sum of all constant‐term coefficients is 1320.\n\n(c) In principle one would get more than one constant term only if the system \n i+j+k=11, \n i a +2b j −b k =0 \nhad more than one nonnegative integer solution (i,j,k). Equivalently, if b\/a were a different rational leading to more integer solutions. In our case b\/a=−4\/3 yields a single solution, so only one constant term. If b\/a were irrational, there would be no non‐trivial solution at all; if b\/a were another rational with “smaller” numerator‐denominator, one might find two or more triples (i,j,k) summing to 11 that cancel out the exponent. But under the given 4a+3b=0 no further solutions occur.", + "golden_answer":"0", + "source":"Bigmath_synth" + }, + { + "instruction":"A charity organization received three donations: $2040, $850, and $1360. They plan to repackage each donation into identical envelopes containing the same dollar amount, with no money left over from any donation. What is the largest dollar amount that can be placed in each envelope? Additionally, express this envelope amount as a percentage of the smallest donation.", + "output":"First note that the envelope size must divide each donation, so we seek \nGCD(2040, 850, 1360).\n\n1. GCD(2040, 850): \n 2040 mod 850 = 340 \n 850 mod 340 = 170 \n 340 mod 170 = 0 \n ⇒ GCD = 170.\n\n2. GCD(170, 1360): \n 1360 mod 170 = 0 \n ⇒ GCD = 170.\n\nThus the largest envelope amount is \\$170. As a percentage of the smallest donation (\\$850):\n\n170⁄850 = 0.2 = 20%. \n\nAnswer: \n• \\$170 per envelope \n• This is 20% of the \\$850 donation.", + "golden_answer":"850", + "source":"Bigmath_synth" + }, + { + "instruction":"A sales company has a bonus scheme where an employee’s cumulative bonus for completing n sales is calculated as follows:\n • If n is 4 or fewer, the bonus is B(n) = –n² + 8n dollars.\n • If n exceeds 4, due to commission restructuring, only 80% of the computed bonus is paid; that is, the bonus becomes 0.8(–n² + 8n).\n\nDetermine the number of sales (n, a positive integer) that results in the highest bonus and state what that maximum bonus is.", + "output":"First, write the bonus function piece‐wise (for integer n≥1):\n\n1) For n≤4: \n B(n)=–n²+8n \n2) For n>4: \n B(n)=0.8·(–n²+8n)=–0.8 n²+6.4 n\n\nNow compute for small n:\n\nn=1: B=–1+8=7 \nn=2: B=–4+16=12 \nn=3: B=–9+24=15 \nn=4: B=–16+32=16 \n\nFor n>4 the quadratic –0.8 n²+6.4 n has its real‐valued maximum at n=4, so it decreases for n>4. Check the first few integers above 4:\n\nn=5: B=0.8·(–25+40)=0.8·15=12 \nn=6: B=0.8·(–36+48)=9.6 \n…\n\nThese are all below 16. Hence the overall maximum occurs at n=4, giving a bonus of \\$16. \n\nAnswer: 4 sales, bonus = \\$16.", + "golden_answer":"16", + "source":"Bigmath_synth" + }, + { + "instruction":"Consider the following two-part problem.\n\n(a) Let p = (x + 2, 8) and q = (5, x – 1) be two nonzero vectors in the plane. The vectors are said to be oppositely directed if one is a negative scalar multiple of the other. Find the real number x for which p and q point in opposite directions.\n\n(b) Now suppose that in a separate situation the same two vectors satisfy\n  |p| = |q| – 2,\nwhere |p| and |q| denote the magnitudes of p and q, respectively. Determine all real numbers x that satisfy this condition.\n\nSolve each part completely and justify your answers.", + "output":"Here is a complete solution of both parts.\n\n(a) p and q point in opposite directions precisely when there is a negative scalar λ such that \n  p = λ q. \nWriting components, \n  (x+2, 8) = λ (5, x–1). \nEquating components gives \n  x+2 = 5λ, \n  8 = λ (x–1). \nHence \n  λ = (x+2)\/5 = 8\/(x–1). \nCross–multiply: \n  (x+2)(x–1) = 40 \n  ⇒ x² + x –2 = 40 \n  ⇒ x² + x –42 = 0 \n  ⇒ x = [–1 ± √(1+168)]\/2 = (–1 ±13)\/2, \nso x = 6 or x = –7. Now λ = (x+2)\/5 must be negative: \n\n– If x = 6, λ = (6+2)\/5 = 8\/5 >0 ⇒ not opposite. \n– If x = –7, λ = (–7+2)\/5 = –1 <0 ⇒ good. \n\nAnswer (a): x = –7. \n\n\n(b) We now solve \n  |p| = |q| – 2, \nwhere \n  |p| = √[(x+2)² + 8²] = √[(x+2)² + 64], \n  |q| = √[5² + (x–1)²] = √[(x–1)² + 25]. \nThus the equation is \n  √[(x+2)² + 64] = √[(x–1)² + 25] – 2. \nSince √[(x–1)² + 25] ≥5 >2, the right–hand side is nonnegative for all x. We may square both sides safely:\n\n1) Let A = √[(x–1)² + 25]. Then the equation is \n  √[(x+2)² + 64] = A – 2. \nSquaring gives \n  (x+2)² + 64 = (A – 2)² = A² – 4A + 4 \n   = [(x–1)² + 25] – 4A + 4 \n  → (x+2)² + 64 = (x–1)² + 29 – 4A. \nRearrange for A: \n  4A = (x–1)² + 29 – [(x+2)² + 64] \n   = (x² –2x +1 +29) – (x² +4x +4 +64) \n   = –6x – 38 \n  ⇒ A = –(6x + 38)\/4 = –(3x + 19)\/2. \n\n2) But A = √[(x–1)² + 25] ≥ 0, so we require \n  –(3x + 19)\/2 ≥ 0 ⇒ 3x + 19 ≤ 0 ⇒ x ≤ –19\/3. \n\n3) Now square A = –(3x+19)\/2: \n  (x–1)² + 25 = [(3x+19)²]\/4. \nMultiply by 4 and expand: \n  4(x² –2x +1 +25) = 9x² + 114x + 361 \n  ⇒ 4x² – 8x +104 = 9x² +114x +361 \n  ⇒ 0 = 5x² +122x +257. \nThe discriminant is \n  Δ = 122² – 4·5·257 = 14884 – 5140 = 9744 = (4√609)², \nso \n  x = [–122 ± 4√609]\/(2·5) = (–61 ± 2√609)\/5. \n\n4) Finally we impose the extra condition x ≤ –19\/3 ≈ –6.33. Numerically \n  (–61 + 2√609)\/5 ≈ –2.33 (fails x ≤ –6.33) \n  (–61 – 2√609)\/5 ≈ –22.07 (satisfies x ≤ –6.33). \n\nThus the only solution of the original equation is \n  x = (–61 – 2√609)\/5. \n\nAnswer (b): x = [–61 – 2√609]\/5.", + "golden_answer":"5", + "source":"Bigmath_synth" + }, + { + "instruction":"At a specialty bakery, standard cookie boxes come in sizes of 5, 15, or 20 cookies. For a new promotional box, the number of cookies is determined by two expressions, namely n₁ = a + 12 and n₂ = a² + 3, where a is an integer. The promotion is advertised so that the only common cookie‐count between the standard sizes {5, 15, 20} and the set {n₁, n₂} is 15. In other words, exactly one of the values n₁ or n₂ equals 15 while the other does not equal 5, 15, or 20. Find the value of a.", + "output":"We need exactly one of \n n₁ = a + 12 \n n₂ = a² + 3 \nto equal 15, and the other must not be 5, 15 or 20.\n\n1. Try n₁ = 15 ⇒ a + 12 = 15 ⇒ a = 3. \n Then n₂ = 3² + 3 = 12, which is not in {5,15,20}. \n ⇒ This choice works.\n\n2. Try n₂ = 15 ⇒ a² + 3 = 15 ⇒ a² = 12, no integer solution.\n\nHence the only integer a is 3.", + "golden_answer":"3", + "source":"Bigmath_synth" + }, + { + "instruction":"Let g(x) = x⁵ + p·x³ + q·x – 12, where p and q are unknown real numbers. It is given that g(–3) = 18 and that the coefficients satisfy 2p + q = –27. Determine the value of g(3).", + "output":"First, write out the condition g(–3)=18:\n\ng(–3) = (–3)^5 + p·(–3)^3 + q·(–3) – 12\n = –243 – 27p – 3q – 12\n = –255 – 27p – 3q\n\nSo \n –255 – 27p – 3q = 18 \n⇒ –27p – 3q = 18 + 255 = 273 \nDivide by 3: \n –9p – q = 91. (1)\n\nWe are also given \n 2p + q = –27. (2)\n\nAdd (1)+(2): \n (–9p – q) + (2p + q) = 91 + (–27) \n –7p = 64 \n p = –64\/7.\n\nThen from 2p+q=–27: \n q = –27 – 2p = –27 – 2(–64\/7) = –27 + 128\/7 = (–189 + 128)\/7 = –61\/7.\n\nFinally compute g(3):\n\ng(3) = 3^5 + p·3^3 + q·3 – 12\n = 243 + 27p + 3q – 12\n = 231 + 27(–64\/7) + 3(–61\/7)\n = 231 + (–1728 – 183)\/7\n = 231 – 1911\/7\n = 231 – 273\n = –42.\n\nAnswer: –42.", + "golden_answer":"42", + "source":"Bigmath_synth" + }, + { + "instruction":"A manufacturing company runs two machines with efficiencies x and y (in units per hour), where both x and y are positive. It is given that the reciprocal of the product of their efficiencies is 3, so\n\n  1\/(xy) = 3\n\nand that the sum of their efficiencies divided by 10 equals 0.5, i.e.,\n\n  (x + y)\/10 = 0.5.\n\nIn addition, the company awards an extra bonus if both machines operate at speeds greater than 1 unit per hour. The bonus is equal to 20% of the sum of the reciprocals of the efficiencies; however, for now, determine the following:\n\n(a) Find the value of (1\/x + 1\/y).\n\n(b) Based on the values of x and y derived from the conditions, decide whether the extra bonus applies.\n\n", + "output":"a) 1\/x + 1\/y = (x + y)\/(xy) = 5 ÷ (1\/3) = 15. \nb) x and y are the roots of t² –5t +1\/3 =0, namely (5 ± √(25–4\/3))\/2 ≈4.93 and 0.07. Since one efficiency is <1, the “both >1” bonus does not apply.", + "golden_answer":"1", + "source":"Bigmath_synth" + }, + { + "instruction":"Six student groups worked on a collaborative project, and their individual contributions (as fractions of the total work) are recorded as follows: 3\/7, 2\/5, 5\/8, 1\/2, 4\/9, and 7\/12. The teacher computes the average contribution of these six groups. Next, she creates a list in which she inserts the six fractions along with this average and arranges all seven numbers in increasing order. \n\n(a) Determine the position of the average in the ordered list (counting position 1 as the smallest value). \n\n(b) The teacher’s policy is as follows: if the average’s position in the list is at or before the 4th term, then each group whose individual contribution is strictly less than the average will receive bonus points; otherwise, no bonus points will be awarded. Based on your answer to part (a), state how many groups (if any) will receive bonus points.", + "output":"Let the six contributions be\n\n 3\/7≈0.4286, 2\/5=0.4000, 5\/8=0.6250, 1\/2=0.5000, 4\/9≈0.4444, 7\/12≈0.5833.\n\nSum them: \n S = 3\/7 + 2\/5 + 5\/8 + 1\/2 + 4\/9 + 7\/12 = 7513\/2520, \nso the average = (7513\/2520)\/6 = 7513\/15120 ≈ 0.4970.\n\nPutting the seven numbers in increasing order:\n\n 2\/5 (0.4000), 3\/7 (0.4286), 4\/9 (0.4444), average (≈0.4970), 1\/2 (0.5000), 7\/12 (0.5833), 5\/8 (0.6250).\n\n(a) The average is 4th in this list.\n\n(b) Since 4≤4, all groups whose contribution is strictly below the average get bonus. The fractions below 0.4970 are 2\/5, 3\/7 and 4\/9, so 3 groups receive bonus points.", + "golden_answer":"3", + "source":"Bigmath_synth" + }, + { + "instruction":"A retail store calculates an adjustment amount A for a promotion using the formula\n  A = (–2)³ – (0.8 – 0.3) × [5 – (–4)²].\nIf A is negative the customer receives a discount equal to the absolute value of A; however, the final discount depends on the method of payment:\n • If a customer pays by credit card, a fee equal to 15% of |A| is deducted from the discount.\n • If a customer pays in cash, an extra discount of $5 is added (i.e. the discount increases by $5).\nDetermine the final discount amount (in dollars) for each payment method.", + "output":"First note \n A = (–2)³ – (0.8 – 0.3)·[5 – (–4)²] \n = –8 – 0.5·[5 – 16] \n = –8 – 0.5·(–11) \n = –8 + 5.5 \n = –2.5 \n\nSo |A| = 2.5 $.\n\n1) Credit‑card payment \n fee = 15% of 2.5 = 0.15·2.5 = 0.375 \n ⇒ discount = 2.5 – 0.375 = 2.125 $ \n\n2) Cash payment \n extra $5 added ⇒ 2.5 + 5 = 7.5 $ \n\nAnswer: \n• Credit card: \\$2.125 (≈\\$2.13) \n• Cash: \\$7.50", + "golden_answer":"7.50", + "source":"Bigmath_synth" + }, + { + "instruction":"A point O emits three laser beams in mutually perpendicular directions. At any time t (in seconds) the endpoints A, B, and C of these beams lie on a common spherical display screen. At time t the distances from O to A, B, and C are 3 m, x m, and 7 m, respectively—with x varying in time so that x = x(t). Because the four points O, A, B, and C all lie on the sphere, one may show that the sphere’s surface area is given by \n  A = π(x² + 58)\nsquare meters. \n\nIf at the moment when x = √6 m the surface area is increasing at a rate of 20π m²\/s, find the rate at which x is changing at that time.\n\n", + "output":"We have \nA(t) = π [x(t)² + 58]. \nDifferentiate with respect to t: \ndA\/dt = π·2x·(dx\/dt) = 2π x (dx\/dt). \n\nAt the instant x = √6, we are given dA\/dt = 20π. Hence \n20π = 2π·(√6)·(dx\/dt) \n⇒ dx\/dt = (20π)\/(2π √6) = 10\/√6 = (5√6)\/3  m\/s.", + "golden_answer":"3", + "source":"Bigmath_synth" + }, + { + "instruction":"A jewelry designer has created five unique pieces, each featuring a distinct geometric shape: a brooch in the form of a regular pentagon, a pendant shaped as a non‐square rectangle, a brooch fashioned as a square, a ring designed like an ellipse (with its major axis horizontal), and an earring in the form of a circle. A design is considered a “symmetry gem” if its shape displays both mirror symmetry (at least one axis of symmetry) and point symmetry (it remains unchanged when rotated 180°). What percentage of these five pieces qualifies as “symmetry gems”? Express your answer as a whole number percentage.\n\n", + "output":"To be a “symmetry gem” a shape must have at least one mirror‐symmetry axis AND 180° rotational (point) symmetry.\n\nChecking each:\n\n1. Regular pentagon: has mirror symmetries but NO 180° rotational symmetry → No \n2. Non‐square rectangle: has mirror symmetries (two axes) and 180° rotation → Yes \n3. Square: has mirror symmetries and 180° (indeed 90°) rotation → Yes \n4. Ellipse: has two mirror axes and is centrally (180°) symmetric → Yes \n5. Circle: infinitely many mirror axes and 180° (indeed all‐angle) rotation → Yes \n\nSo 4 of the 5 qualify ⇒ (4\/5)·100% = 80%.", + "golden_answer":"80", + "source":"Bigmath_synth" + }, + { + "instruction":"A fitness center is evaluating improvement programs in three different training groups.\n\n• In Group A, 40 out of 50 members showed a measurable improvement in their stamina after a new training regimen.\n\n• In Group B, 64 out of 80 members met the improvement criteria with a modified workout plan.\n\n• In Group C the program was run in two phases. In the first phase, 90 out of 120 members experienced improvement. In the second phase, additional training was offered to those who had not improved in phase one, and 15 of these 30 members then showed improvement.\n\nDetermine the overall percentage of members, across all groups, who experienced improved stamina.", + "output":"First, tally the totals and improvements in each group:\n\nGroup A \n• Total members = 50 \n• Improved = 40 \n\nGroup B \n• Total members = 80 \n• Improved = 64 \n\nGroup C (two‐phase) \n• Phase 1: 120 members, 90 improved → 30 did not improve \n• Phase 2: those 30 offered extra training, 15 of them then improved \n→ Total in C = 120, total improved = 90 + 15 = 105 \n\nNow sum across all groups: \n• Total members = 50 + 80 + 120 = 250 \n• Total improved = 40 + 64 + 105 = 209 \n\nOverall improvement percentage = (209 ÷ 250) × 100% = 83.6%.", + "golden_answer":"83.6", + "source":"Bigmath_synth" + }, + { + "instruction":"A decorative circular fountain at a park has an arc along its edge corresponding to a central angle of 1.5 radians that measures 8 meters in length. A surrounding flower bed forms a ring‐shaped sector that extends 1 meter outward from the edge of the fountain (so its outer arc lies on a circle of radius 1 meter greater than that of the fountain). Find the area of the flower bed sector (i.e. the difference between the area of the outer sector and the area of the fountain’s sector).", + "output":"First note that the fountain’s radius r satisfies \n r·1.5 rad = 8 m ⇒ r = 8\/1.5 = 16\/3 m. \nThe flower‐bed is the annular sector between radii r and r+1 (so R=r+1=19\/3 m) of the same angle θ=1.5 rad. Its area is\n\nArea = ½·θ·(R² – r²)\n = ½·(1.5)·[ (19\/3)² – (16\/3)² ]\n = 0.75·[ (361–256)\/9 ]\n = 0.75·(105\/9)\n = 0.75·(35\/3)\n = 8.75 m².\n\nSo the flower‐bed sector has area 8.75 m².", + "golden_answer":"8.75", + "source":"Bigmath_synth" + }, + { + "instruction":"A carpenter is constructing a custom picture frame. The initial design calls for the frame to have a length of 9\/8 feet and a width of 5\/16 feet. To allow extra decorative matting, both dimensions are increased by 20%. Then the carpenter calculates the exterior perimeter of the enlarged frame. However, if this new perimeter exceeds 3.50 feet, an extra protective trim is added along the entire border.\n\na) Find the new exterior perimeter in feet after the 20% increase. \nb) Express the perimeter as a decimal rounded to the nearest hundredth and determine the digit in the hundredths place of that value. \nc) Based on your answer in part (b), state whether the digit is odd or even.", + "output":"a) Original dimensions: \n Length = 9\/8 = 1.125 ft \n Width = 5\/16 = 0.3125 ft \n\nIncrease each by 20% ⇒ multiply by 1.2: \n New length = 1.125·1.2 = 1.35 ft \n New width = 0.3125·1.2 = 0.375 ft \n\nPerimeter = 2·(length + width) \n = 2·(1.35 + 0.375) \n = 2·1.725 \n = 3.45 ft \n\nb) As a decimal to the nearest hundredth, the perimeter is 3.45. \n The digit in the hundredths place is 5. \n\nc) The digit 5 is odd.", + "golden_answer":"5", + "source":"Bigmath_synth" + }, + { + "instruction":"A coffee shop produces its new signature latte at a cost of $20 per cup. To cover overhead, the shop initially prices the latte at 40% above its production cost. However, after several days of slow sales, the shop decides to offer a 25% discount on the marked price. At this reduced price, a cup of latte sells for $21. In addition, the shop must pay a fixed packaging fee of $2 per cup. Determine whether the shop makes a net profit or incurs a net loss on each cup sold, and calculate the dollar amount of that profit or loss.", + "output":"Here’s the math step by step:\n\n1. Production cost per cup: \\$20 \n2. Mark‐up 40% → marked price = 20 × 1.40 = \\$28 \n3. 25% off → selling price = 28 × 0.75 = \\$21 \n4. Add packaging fee \\$2 → total cost = 20 + 2 = \\$22 \n5. Net per‐cup = revenue – total cost = 21 – 22 = –\\$1\n\nSo the shop incurs a \\$1 loss on each latte sold.", + "golden_answer":"1", + "source":"Bigmath_synth" + }, + { + "instruction":"A square garden is planned so that the length of each side (in feet) equals the arithmetic square root of the garden’s area. A 3‐foot-wide walkway is built uniformly around the garden, enlarging the overall area by exactly 64% compared to the garden’s original area. Determine the side length of the original garden.", + "output":"Let s be the side‐length of the garden. Then its area is s². Adding a 3‐ft walk all around makes the overall side‐length s+6, so the new area is (s+6)². We are told this is 64% larger than the original, i.e.\n\n (s+6)² = 1.64·s² = (41\/25)s².\n\nExpand and clear denominators:\n\n (s+6)² = s² + 12s + 36 = (41\/25)s² \n ⇒ 25(s² + 12s + 36) = 41s² \n ⇒ 25s² + 300s + 900 = 41s² \n ⇒ 16s² − 300s − 900 = 0 \n ⇒ 4s² − 75s − 225 = 0.\n\nThe positive root is\n\n s = [75 + √(75² + 4·4·225)]\/(2·4)\n = [75 + √(5625 + 3600)]\/8\n = [75 + 15√41]\/8\n = (15\/8)(5 + √41) ≃ 21.38 ft.", + "golden_answer":"21.38", + "source":"Bigmath_synth" + }, + { + "instruction":"A city's transportation department is testing a new model to optimize traffic signal timing. The green-light duration (in seconds) is modeled by the expression (60 – 4z²)³, where z represents a calibration unit adjustment. In this context, the constant term gives the base green time, and the term containing z⁴ represents the effect of a specific calibration pair. \n\n(a) Find the absolute value of the coefficient of z⁴ in the expansion of (60 – 4z²)³. \n\n(b) Express this coefficient as a percentage of the constant term (the base green time).", + "output":"a) Let a=60 and b=–4z². By the binomial theorem, \n(60–4z²)³ = a³ + 3a²b + 3a b² + b³. \nThe z⁴‐term comes from 3·a·(b²): \nb² = (–4z²)² =16 z⁴, \nso its coefficient =3·60·16 =2880. \nHence |coeff(z⁴)|=2880. \n\nb) The constant term is 60³=216 000. Thus \npercent = (2880\/216 000)·100% =1.333…% ≈1.33%.", + "golden_answer":"1.33", + "source":"Bigmath_synth" + }, + { + "instruction":"A local electronics store is preparing gift packs for a promotional sale. They have a certain number of portable chargers that, when divided evenly into groups of 6, 8, 10, or 14, always leave a remainder of 5. In addition, if the store adds 10 extra chargers (to serve as demo units), the new total is exactly divisible by 15. Determine the smallest possible number of portable chargers the store originally had.", + "output":"Let N be the original number of chargers. The conditions are\n\n1. N ≡ 5 (mod 6) \n2. N ≡ 5 (mod 8) \n3. N ≡ 5 (mod 10) \n4. N ≡ 5 (mod 14) \n5. N + 10 ≡ 0 (mod 15)\n\nFrom 1–4 we get N–5 is a common multiple of 6, 8, 10, and 14. Their LCM is\n\n LCM(6,8,10,14) = 2³·3·5·7 = 8·105 = 840.\n\nHence N = 840k + 5 for some integer k ≥ 0. The “+10” condition is\n\n (840k + 5 + 10) ≡ 0 (mod 15) \n⇔ 840k + 15 ≡ 0 (mod 15).\n\nBut 840 ≡ 0 (mod 15), so 840k + 15 ≡ 15 ≡ 0 (mod 15) holds for every k. \nThe smallest non‐trivial positive solution (k=1) is\n\n N = 840·1 + 5 = 845.\n\nTherefore the store originally had 845 portable chargers.", + "golden_answer":"845", + "source":"Bigmath_synth" + }, + { + "instruction":"A taxi service charges a fixed base fee and a per‐mile rate. During rush hour, an extra 20% is added to the per‐mile rate. If a 10‑mile ride outside rush hour costs $25, and the same 10‑mile ride during rush hour costs $29, what are the base fee and the standard per‑mile rate?", + "output":"Let B be the base fee and r the standard per‑mile rate. Then\n\n1) Outside rush hour: B + 10·r = 25 \n2) During rush hour:  B + 10·(1.2 r) = B + 12 r = 29 \n\nSubtract (1) from (2): \n( B + 12 r ) – ( B + 10 r ) = 29 – 25 \n2 r = 4 ⇒ r = $2\/mile \n\nPlug back into (1): \nB + 10·2 = 25 ⇒ B = 25 – 20 = $5 \n\nAnswer: Base fee = $5, standard per‑mile rate = $2.", + "golden_answer":"2", + "source":"Bigmath_synth" + }, + { + "instruction":"Determine all real numbers x for which the expression √(4 – 3x) + ln(x + 2) is defined.", + "output":"We require simultaneously \n 1) 4 – 3x ≥ 0 ⇒ x ≤ 4\/3 \n 2) x + 2 > 0 ⇒ x > –2 \n\nHence the domain is \n –2 < x ≤ 4\/3 \n\nIn interval notation: (–2, 4\/3]", + "golden_answer":"3", + "source":"Bigmath_synth" + }, + { + "instruction":"In an archery competition, different target zones award distinct point values: the bullseye scores 10 points, the inner ring 7 points, the middle ring 4 points, and the outer ring 1 point. Archer Leila hit the bullseye 3 times, the inner ring 4 times, the middle ring 5 times, and the outer ring 8 times. Archer Ryan hit the bullseye 2 times, the inner ring 6 times, the middle ring 7 times, and the outer ring 5 times. However, due to strong winds, all of Leila’s outer ring scores are reduced by 25%. By how many points does Leila trail behind Ryan after this adjustment?", + "output":"First compute each archer’s total before comparing:\n\nLeila’s adjusted score \n- Bullseye: 3 × 10 = 30 \n- Inner ring: 4 × 7 = 28 \n- Middle ring: 5 × 4 = 20 \n- Outer ring (1 pt hit reduced by 25% → 0.75 pts per hit): 8 × 0.75 = 6 \n\nTotal Leila = 30 + 28 + 20 + 6 = 84\n\nRyan’s score \n- Bullseye: 2 × 10 = 20 \n- Inner ring: 6 × 7 = 42 \n- Middle ring: 7 × 4 = 28 \n- Outer ring: 5 × 1 = 5 \n\nTotal Ryan = 20 + 42 + 28 + 5 = 95\n\nDifference: 95 − 84 = 11\n\nLeila trails Ryan by 11 points.", + "golden_answer":"11", + "source":"Bigmath_synth" + }, + { + "instruction":"A cyclist participates in a multi-lap challenge. In the first lap, he rides 5 km. For every subsequent lap, he plans to increase his distance by 5 km more than the previous lap. However, on every third lap, due to fatigue, he can only complete 80% of the planned distance for that lap. What is the minimum number of laps the cyclist must complete to cover a total distance of at least 125 km?", + "output":"Let \\(A_n\\) be the actual distance on lap \\(n\\). The planned distance is \n  \\(D_n=5n\\) km, \nbut if \\(n\\) is a multiple of 3 he only does 80% of \\(D_n\\), i.e. \n  \\(A_n=\\begin{cases}5n,&3\\nmid n,\\\\0.8\\,(5n)=4n,&3\\mid n.\\end{cases}\\) \n\nCompute the running total until it reaches 125 km:\n\nLap 1: 5 \nLap 2: 10 → total 15 \nLap 3: 0.8·15=12 → total 27 \nLap 4: 20 → total 47 \nLap 5: 25 → total 72 \nLap 6: 0.8·30=24 → total 96 \nLap 7: 35 → total 131 \n\nAfter 6 laps the total is only 96 km; after 7 laps it is 131 km, which exceeds 125 km. \n\nAnswer: 7 laps.", + "golden_answer":"7", + "source":"Bigmath_synth" + }, + { + "instruction":"At a bakery, the ratio of the number of chocolate cookies to vanilla cookies is given by a positive number k. Due to supply planning, k must satisfy the quadratic equation\n\n  3k² – 8k + 4 = 0.\n\na) Find all possible values of k. \nb) In this scenario the bakery prefers to produce more chocolate cookies than vanilla cookies, so only consider the solution with k > 1. \nc) Using that valid value of k, compute the expression k² + (1\/k²) and then determine by what percentage this expression exceeds 2. (That is, find the percentage increase from 2 to k² + (1\/k²), rounding your final answer to the nearest whole number.)", + "output":"a) Solve 3k² – 8k + 4 = 0. \n • Discriminant D = (–8)² – 4·3·4 = 64 – 48 = 16 \n • k = [8 ± √16]⁄(2·3) = (8 ± 4)\/6 \n • Hence k = 12\/6 = 2 or k = 4\/6 = 2\/3 \n\nb) Since the bakery wants more chocolate than vanilla, take k > 1 ⇒ k = 2. \n\nc) Compute E = k² + 1\/k² for k = 2: \n • k² = 4, 1\/k² = 1\/4 = 0.25 ⇒ E = 4.25 \n • Percentage by which E exceeds 2: \n (E – 2)\/2 × 100% = (4.25 – 2)\/2 × 100% = 2.25\/2 × 100% = 112.5% \n • Rounded to the nearest whole percent: 113%", + "golden_answer":"113", + "source":"Bigmath_synth" + }, + { + "instruction":"At the community center, the main hall measures 480 square feet while an adjacent study room has an unknown area S. The center plans to build a new multipurpose lounge whose area is 120% of the sum of the main hall’s and study room’s areas; the planned lounge will be 1.2 (480 + S) square feet, which is set to equal 1728 square feet. In addition, if the study room’s area were increased by 15% (to accommodate extra resources), the lounge would be redesigned to be 10% larger than originally planned—that is, 1.1 × 1728 square feet—while still following the rule of covering 120% of the new total area of the main hall and the enlarged study room. Determine S, the current area of the study room.", + "output":"Let S be the study‐room’s current area. \n\n1) From the original plan: \n 1.2 (480 + S) = 1728 \n ⇒ 480 + S = 1728 ÷ 1.2 = 1440 \n ⇒ S = 1440 − 480 = 960. \n\n2) Check with the 15% increase and 10% lounge enlargement: \n New study area = 1.15 S = 1.15·960 = 1104 \n Required lounge = 1.1·1728 = 1900.8 \n Rule says 1.2 (480 + 1104) = 1.2·1584 = 1900.8 ✓ \n\nHence the study room’s area is 960 ft².", + "golden_answer":"960", + "source":"Bigmath_synth" + }, + { + "instruction":"A circular fountain in a park has its edge described by the equation x² + y² = R, where R is a positive number. A straight walking path is built along the line 2x + y = R so that the path touches the fountain at exactly one point. Determine the value of R. Also, show that the x-coordinate of the point of tangency (i.e. its horizontal distance from the y-axis) equals 2 units.", + "output":"To show that 2x + y = R is tangent to x² + y² = R we use the fact that the distance from the circle’s center (0,0) to the line must equal the circle’s radius √R.\n\n1. Distance from (0,0) to 2x + y − R = 0 is \n D = |0·2 + 0·1 − R|\/√(2²+1²) = R\/√5.\n\n Tangency ⇒ D = radius = √R, so \n R\/√5 = √R \n ⇒ R²\/5 = R \n ⇒ R(R − 5) = 0 \n ⇒ R = 5 (since R>0).\n\n2. To find the point of tangency, solve \n x² + y² = 5 \n and \n y = 5 − 2x. \n Substitute: \n x² + (5 − 2x)² = 5 \n ⇒ x² + 25 − 20x +4x² = 5 \n ⇒ 5x² −20x +20 = 0 \n ⇒ x² −4x +4 = 0 \n ⇒ (x−2)² = 0 \n ⇒ x = 2. \n\nHence R = 5, and the tangency occurs at x = 2 (so the horizontal distance from the y‑axis is 2 units).", + "golden_answer":"2", + "source":"Bigmath_synth" + }, + { + "instruction":"John has 36 rare stamps, and Daniel has 12 more stamps than John. Later, Daniel sells one‐third of his stamps at a collector’s market, while John wins a contest and receives extra stamps equal to 25% of his original collection. What is the ratio of John’s updated stamp count to Daniel’s remaining stamps? Express your answer in simplest form.", + "output":"First, compute each person’s stamps step by step:\n\n1. John’s original count: 36 stamps. \n He then receives an extra 25% of 36 → 0.25×36 = 9 stamps. \n John’s updated total = 36 + 9 = 45.\n\n2. Daniel’s original count: 36 + 12 = 48 stamps. \n He sells one‐third of 48 → (1\/3)×48 = 16 stamps. \n Daniel’s remaining total = 48 – 16 = 32.\n\nThe ratio of John’s updated count to Daniel’s remaining count is \n45 : 32.", + "golden_answer":"32", + "source":"Bigmath_synth" + }, + { + "instruction":"A shipment of apples loses 30 percent of its weight during transportation due to moisture loss, and an additional 50 pounds of apples are discarded because they were damaged. If the shipment weighs 875 pounds at its destination, what was its original weight before transportation?", + "output":"Let W be the original weight. After losing 30% in transit you have 0.70 W, and then 50 lb more are discarded, leaving 875 lb:\n\n0.70 W − 50 = 875 \n0.70 W = 925 \nW = 925 ÷ 0.70 ≈ 1,321.43 lb\n\nSo the shipment originally weighed about 1,321.4 pounds.", + "golden_answer":"1321.4", + "source":"Bigmath_synth" + }, + { + "instruction":"At a manufacturing plant, Worker A produced 360 gadgets over a 15‐day period. However, he was absent on one day for mandatory training and thus only worked 14 days. Worker B, on the other hand, manufactured 420 gadgets over a 14‐day period. Unfortunately, due to a technical malfunction, his production on 2 of those days dropped to only 70% of his normal daily output, while on the remaining days he produced at full capacity. Determine the difference—in gadgets per day—between Worker A’s actual average production rate (based solely on his working days) and Worker B’s normal daily production rate (i.e. the rate he would have maintained had there been no malfunction).", + "output":"First, compute A’s true working‐day average:\n\n- A made 360 gadgets in 14 days, so \n A_avg = 360 ÷ 14 = 180\/7 ≃ 25.7143 gadgets\/day.\n\nNext, let x = B’s normal (full‑capacity) output per day. Over 14 days he actually produced\n\n- 12 days at x each, plus \n- 2 days at 0.7 x each, \n\nfor a total of \n 12 x + 2·0.7 x = (12 + 1.4) x = 13.4 x = 420 \n⇒ x = 420 ÷ 13.4 = 2100\/67 ≃ 31.3433 gadgets\/day.\n\nFinally, the difference in rates is \n |B_normal – A_avg| ≃ 31.3433 – 25.7143 = 5.6290 ≃ 5.63 gadgets per day.", + "golden_answer":"5.63", + "source":"Bigmath_synth" + }, + { + "instruction":"A café runs a rewards program in which a customer earns points on each visit according to an arithmetic sequence. Let aₙ = a₁ + (n – 1)d be the base points earned on the nth visit. In addition, if the base points for a visit exceed 40, the customer receives a bonus that adds 20% extra points for that visit (that month’s points are then 1.2·aₙ). It is known that on the 4th visit the customer earned exactly 36 base points (i.e. a₄ = 36) and that the total of the base points (not including bonuses) over the first 25 visits is 375. Determine the total reward points (base points plus any applicable bonuses) accumulated over the first 10 visits.", + "output":"First we solve for the arithmetic‐sequence parameters. Let \n aₙ = a₁ + (n–1)d. \nWe are given \n1) a₄ = a₁ + 3d = 36 \n2) sum of aₙ for n=1…25 is 375, i.e. \n S₂₅ = (25\/2)(2a₁ + 24d) = 375. \n\nFrom S₂₅: \n 25·(2a₁ + 24d) = 750 ⇒ 2a₁ + 24d = 30. \nAnd from a₄: \n a₁ + 3d = 36. \n\nSolve the two‐equation system: \n a₁ + 3d = 36 \n 2a₁ +24d = 30 \n⇒ multiply the first by 2: 2a₁ + 6d = 72 \n⇒ subtract from 2a₁+24d=30: 18d = –42 ⇒ d = –7\/3, \n⇒ a₁ = 36 –3d = 36 +7 = 43. \n\nHence \n aₙ = 43 – (7\/3)(n–1). \n\nWe need the total “reward” over the first 10 visits, where on any visit with aₙ>40 the customer gets a 20% bonus (so 1.2·aₙ); otherwise they get just aₙ. \n\nCompute the first 10 base values: \nn=1: a₁=43.00 >40 ⇒ reward=1.2·43=51.6 \nn=2: a₂=43–7\/3=122\/3≈40.6667 >40 ⇒ reward=1.2·(122\/3)=48.8 \nn=3: a₃=115\/3≈38.3333 ≤40 ⇒ reward=38.3333 \nn=4: a₄=36     ≤40 ⇒ reward=36 \nn=5: a₅=101\/3≈33.6667⇒ reward=33.6667 \nn=6: 94\/3≈31.3333 ⇒ reward=31.3333 \nn=7: 87\/3=29.0  ⇒ reward=29 \nn=8: 80\/3≈26.6667⇒ reward=26.6667 \nn=9: 73\/3≈24.3333⇒ reward=24.3333 \nn=10:66\/3=22.0  ⇒ reward=22 \n\nSumming these: \n Sum of base points n=1…10 is an arithmetic series = (10\/2)(a₁+a₁₀) =5·(43+22)=325. \n The only bonus visits are n=1,2, giving an extra 0.2·(a₁+a₂)=0.2·(43+122\/3)=251\/15≃16.7333. \n\nTotal reward = 325 + 251\/15 = (4875 + 251)\/15 = 5126\/15 ≃ 341.7333. \n\nAnswer: 5126\/15 points (approximately 341.73 points).", + "golden_answer":"341.73", + "source":"Bigmath_synth" + }, + { + "instruction":"Devon uses his electric stove for cooking. The stove draws 1800 watts when in active use. On weekdays (Monday through Friday) he cooks for 2 hours and then leaves the stove on standby (using 50 watts) for 3 hours immediately afterward. On weekends (Saturday and Sunday) he cooks for 1.5 hours and then leaves it on standby for 2 hours. Electricity costs 11 cents per kilowatt‐hour for active use and 8 cents per kilowatt‐hour for standby use. Calculate the total cost in cents to operate the stove for one week.", + "output":"First convert the power ratings to kilowatts: \n  Active 1800 W = 1.8 kW \n  Standby 50 W = 0.05 kW \n\nWeekdays (Mon–Fri), each day: \n  Active energy = 1.8 kW × 2 h = 3.6 kWh \n  Standby energy = 0.05 kW × 3 h = 0.15 kWh \n  Active cost = 3.6 kWh × \\$0.11\/kWh = \\$0.396 \n  Standby cost = 0.15 kWh × \\$0.08\/kWh = \\$0.012 \n  Total\/day = \\$0.396 + \\$0.012 = \\$0.408 \n  For 5 days = 5 × \\$0.408 = \\$2.04 \n\nWeekends (Sat & Sun), each day: \n  Active energy = 1.8 kW × 1.5 h = 2.7 kWh \n  Standby energy = 0.05 kW × 2 h = 0.10 kWh \n  Active cost = 2.7 kWh × \\$0.11 = \\$0.297 \n  Standby cost = 0.10 kWh × \\$0.08 = \\$0.008 \n  Total\/day = \\$0.297 + \\$0.008 = \\$0.305 \n  For 2 days = 2 × \\$0.305 = \\$0.61 \n\nWeekly total = \\$2.04 + \\$0.61 = \\$2.65 \nIn cents: 2.65 dollars × 100 = 265 cents.", + "golden_answer":"265", + "source":"Bigmath_synth" + }, + { + "instruction":"A florist is arranging 6 decorative pots in a row for a special exhibition. There are 3 pots of lilies, 2 pots of daisies, and 1 pot of orchids. The following conditions must be met:\n\n• The 3 lily pots must be placed consecutively.\n• The 2 daisy pots must not be placed next to each other.\n• An arrangement is called “prime” if the orchid pot is placed at one of the two ends of the row; otherwise, it is “regular.”\n\nDetermine the difference between the number of prime arrangements and the number of regular arrangements. Express your answer as a single integer.", + "output":"Let LLL denote the block of 3 lilies (treated as one “super‐pot”), O the orchid, and D,D the two daisies. We want to line up the 4 “pots” \n \n LLL, O, D, D \n \nso that the two D’s are not adjacent (else they’d occupy consecutive spots in the full 6‐row), and then classify an arrangement as “prime” exactly when O is in position 1 or position 6 of the 6‐row. In the 4‐letter model this is equivalent to O being the 1st or 4th letter.\n\n1. Total arrangements of LLL, O, D, D is 4!\/2! = 12. \n2. Those with the two D’s adjacent: fuse them into one “DD” block ⇒ 3! = 6. \n3. Hence valid (non‐adjacent D’s) = 12 − 6 = 6. \n\nList them by choosing 2 of the 4 slots for D’s so they’re non‐consecutive, then placing LLL,O in the other two slots:\n\n(1) D L D O → O in 4 ⇒ prime \n(2) D O D L → O in 2 ⇒ regular \n(3) D L O D → O in 3 ⇒ regular \n(4) D O L D → O in 2 ⇒ regular \n(5) L D O D → O in 3 ⇒ regular \n(6) O D L D → O in 1 ⇒ prime \n\nSo there are 2 prime and 4 regular, and\n\n #prime − #regular = 2 − 4 = −2.", + "golden_answer":"2", + "source":"Bigmath_synth" + }, + { + "instruction":"A rectangular sports field is to be constructed, and two different design approaches are under consideration:\n\nApproach A (Fully Enclosed): The field’s length is required to be 8 meters longer than its width, and the entire perimeter is to be fenced using 50 meters of fencing. Determine the dimensions of the field under this design.\n\nApproach B (One Side Unfenced): Due to an existing barrier along one of its longer sides, only the other three sides will be fenced using 50 meters of fencing. For aesthetic purposes, the ratio of the fenced side lengths (the fenced length to the width) must be exactly 1.5. Determine the dimensions of the field under this alternative design.", + "output":"Approach A: \nLet w = the field’s width (m). Then its length is L = w + 8. Since the full perimeter 2w + 2L = 50, \n2w + 2(w + 8) = 50 \n⇒ 4w + 16 = 50 \n⇒ 4w = 34 \n⇒ w = 8.5 m, L = w + 8 = 16.5 m. \n\nAnswer A: 8.5 m by 16.5 m. \n\nApproach B: \nOne of the long sides is already barred, so you fence only the two widths plus one length: 2w + L = 50. The aesthetic requirement is (fenced length)\/(width) = 1.5 ⇒ L\/w = 1.5 ⇒ L = 1.5 w. Substitute: \n2w + 1.5 w = 50 \n⇒ 3.5 w = 50 \n⇒ w = 50\/3.5 = 100\/7 ≈14.2857 m \n⇒ L = 1.5 w = 150\/7 ≈21.4286 m. \n\nAnswer B: width ≈14.29 m, length ≈21.43 m.", + "golden_answer":"21.43", + "source":"Bigmath_synth" + }, + { + "instruction":"An investor had an account balance of $10,000 at the beginning of the week. By the end of the week the balance had dropped to $9,550 due to a withdrawal and a flat fee charged by the bank. If the fee is $20 when the withdrawal is less than $300, and $40 when the withdrawal is $300 or more, determine the amount withdrawn and the fee applied.", + "output":"Let W be the withdrawal amount. We know\r\n\r\n 10 000 − W − F = 9 550, \r\n\r\nso \r\n W + F = 450. \r\n\r\nCase 1: if W < 300, then F = 20 ⇒ W = 450 − 20 = 430, but 430 ≥ 300, contradiction. \r\nCase 2: if W ≥ 300, then F = 40 ⇒ W = 450 − 40 = 410, which is ≥ 300, so consistent. \r\n\r\nAnswer: Withdrawal $410, fee $40.", + "golden_answer":"40", + "source":"Bigmath_synth" + }, + { + "instruction":"A developer acquired a site for 50 million yuan and plans to construct a mixed-use building with at least 15 floors. Each floor provides 1,800 square meters of built-up area. The base construction cost per square meter is given by C(x) = 600 + 40x, where x is the number of floors (x ≥ 15). However, due to scheduling incentives and penalties, the actual construction cost per square meter is adjusted as follows:\n\n• If x < 20, the builder receives a 5% discount on C(x);\n• If x = 20, no adjustment is made;\n• If x > 20, an 8% premium is added to C(x).\n\nIn addition, there is a fixed landscaping cost of 7 million yuan. The developer’s comprehensive average cost per square meter is defined as the sum of the adjusted average construction cost and the average land-and-landscaping cost, where the latter is computed by distributing the total of the land purchase cost plus landscaping cost over the total built-up area (which is 1,800x square meters).\n\nDetermine the number of floors x that minimizes the comprehensive average cost per square meter. \n\n(Note: You may need to analyze different cases for x < 20, x = 20, and x > 20.)", + "output":"Let x be the number of floors (x ≥ 15). Each floor is 1 800 m², so total GFA = 1 800 x m². The land cost is 50 million and there is a fixed 7 million landscaping‐cost, so the “land + landscaping” per m² is\n\n (50 × 10^6 + 7 × 10^6) \/ (1 800 x)\n = 57 × 10^6 \/ (1 800 x)\n = 31 666.6667 \/ x (yuan \/ m²). \n\nThe base construction cost per m² is \n C(x) = 600 + 40 x. \n\nBecause of the scheduling clauses we have three regimes:\n\n1) 15 ≤ x < 20 ⇒ 5% discount ⇒ adjusted construction cost per m² \n C₁(x) = 0.95·(600 + 40 x) \n = 570 + 38 x. \n\n2) x = 20 ⇒ no discount\/premium ⇒ \n C₂(20) = 600 + 40·20 = 1 400. \n\n3) x > 20 ⇒ 8% premium ⇒ \n C₃(x) = 1.08·(600 + 40 x) \n = 648 + 43.2 x. \n\nHence the comprehensive average cost (per m²) is\n\n A₁(x) = (570 + 38 x) + 31 666.667\/x, 15 ≤ x < 20\n A₂ = 1 400 + 31 666.667\/20 = 2 983.333…, x = 20\n A₃(x) = (648 + 43.2 x) + 31 666.667\/x, x > 20.\n\nWe now locate minima in each regime:\n\n• Regime 1 (15 ≤ x < 20):\n dA₁\/dx = 38 – 31 666.667\/x² \n ⇒ Critical at x² = 31 666.667\/38 ≃ 833.33 ⇒ x ≃ 28.9 (outside [15,20)), \n and one checks that A₁′(x) < 0 throughout 15 ≤ x < 20, so A₁ is strictly decreasing on [15,20). \n Thus on the integer grid the best in regime 1 is at x = 19: \n A₁(19) = 570 + 38·19 + 31 666.667\/19 \n ≃ 570 + 722 + 1 666.667 \n = 2 958.667 yuan\/m².\n\n• Regime 2 (x = 20): \n A₂ = 1 400 + 31 666.667\/20 \n = 1 400 + 1 583.333 \n = 2 983.333 yuan\/m². \n\n• Regime 3 (x > 20):\n dA₃\/dx = 43.2 – 31 666.667\/x² \n ⇒ Critical at x² = 31 666.667\/43.2 ≃ 732.4 ⇒ x ≃ 27.1. \n On the integers one checks \n A₃(27) ≃ 2 986.9, A₃(28) ≃ 2 988.6, etc.\n\nComparing the three regimes on the integer floor counts:\n\n x = 19 ⇒ 2 958.7 \n x = 20 ⇒ 2 983.3 \n x = 27 ⇒ 2 986.9 \n\n… so the global minimum occurs at x = 19 floors, giving a comprehensive average cost ≃ 2 958.7 yuan\/m². \n\nAnswer: The developer should build 19 floors.", + "golden_answer":"19", + "source":"Bigmath_synth" + }, + { + "instruction":"A triangular park has sides measuring 36 m, 48 m, and 60 m. The park management plans to install lighting along the altitude drawn to the longest side (60 m). However, due to the layout of the park, only 75% of that altitude falls on paved terrain while the remaining 25% lies on unpaved terrain. If the installation cost is $100 per meter on paved areas and $80 per meter on unpaved areas, determine the total installation cost for the lighting strips along the entire altitude. Express your answer as a whole number.", + "output":"First, note that the triangle with sides 36, 48, 60 is a right triangle (36² + 48² = 60²). Its area can be computed as \n Area = ½·36·48 = 864 m². \nIf h is the altitude to the side of length 60, then \n ½·60·h = 864 \n⇒ h = (2·864)\/60 = 28.8 m.\n\nOf that altitude:\n- 75% is paved ⇒ 0.75·28.8 = 21.6 m at \\$100\/m ⇒ 21.6·100 = \\$2 160 \n- 25% is unpaved ⇒ 0.25·28.8 = 7.2 m at \\$80\/m ⇒ 7.2·80 = \\$576 \n\nTotal cost = 2 160 + 576 = \\$2 736.", + "golden_answer":"736", + "source":"Bigmath_synth" + }, + { + "instruction":"At a technology expo, 120 inventions are exhibited and arranged into six thematic groups. The first four groups contain 25, 20, 18, and 22 inventions respectively. If 28% of the inventions belong to the fifth group, determine:\n\n(a) The percentage of inventions in the sixth group. \n(b) After an evaluation process disqualifies 10% of the inventions in the sixth group, what percentage of the total inventions remain validated in that group?", + "output":"First, note that the first four groups together have \n25 + 20 + 18 + 22 = 85 inventions, \nso as a percentage of the total 120 that is \n(85\/120)·100% = 70.833…%.\n\nThe fifth group is 28%, so the sum of the first five groups is \n70.833…% + 28% = 98.833…%. \n\n(a) The sixth group must make up the remainder: \n100% – 98.833…% = 1.1667…% ≈ 1.17%.\n\n(b) If 10% of the sixth‐group inventions are disqualified, 90% remain. \nHence the validated share of the total = 90% of 1.1667…% ≈ 1.05%. \n\nAnswers: \n(a) ≈ 1.17% \n(b) ≈ 1.05%", + "golden_answer":"1.05", + "source":"Bigmath_synth" + }, + { + "instruction":"A delivery truck normally covers 600 km in 10 hours at a constant speed. To reduce costs, the company now requires that the truck complete the 600‐km journey in a new total “driving time” equal to a fraction f of the original 10 hours. (Note that a legally mandated 10‑minute rest break is taken during the trip and is not counted as driving time.) Furthermore, if an unexpected 5‑minute delay occurs due to a roadblock immediately after the break, the truck—while still following the new schedule—must travel at a higher constant speed during its driving period. In the case with the 5‑minute delay, the required driving speed turns out to be 70 km\/h.\n\na) Determine the fraction f of the original 10‑hour driving time that is allowed in the new schedule (i.e. the truck’s planned driving time, excluding breaks and delays).\n\nb) Under the new schedule, if the roadblock delay does not occur, what constant driving speed must the truck maintain to cover the entire 600 km in the allotted (undelayed) driving time?\n\nAssume all times are expressed in hours (with minutes converted appropriately) and that the truck travels at a uniform speed during its driving period.", + "output":"Let T₀=10 h be the original driving time so that originally v₀=600\/10=60 km\/h. Under the new rule the total “driving‐time” (i.e. time on the road, excluding only the 10 min rest‐break) is forced down to \n \n T_driving = f·T₀ = 10 f (hours). \n \nIn the case that a 5 min=(5\/60)=1\/12 h roadblock delay occurs (and that delay DOES count against the driving‐time budget!), the truck has only \n \n T_drive_act = (10 f) − (1\/12) \n \nhours actually behind the wheel to cover 600 km. We are told that in that scenario the required constant speed is 70 km\/h. Hence \n \n 70·[(10 f) − 1\/12] = 600 \n \n⇢ (10 f) − 1\/12 = 600\/70 = 60\/7 \n \n⇢ 10 f = 60\/7 + 1\/12 = (720\/84 + 7\/84) = 727\/84 \n \n⇢ f = (727\/84)\/10 = 727\/840 ≃ 0.86548. \n \nThat answers (a). \n\n(b) If the 5 min delay does *not* occur then the entire allotted driving‐time 10 f is spent moving, so the needed speed is \n \n v = 600 ÷ (10 f) = 600 ÷ (727\/84) = (600·84)\/727 ≃ 69.33 km\/h. \n\nSummary: \na) f = 727\/840 ≃ 0.8655. \nb) vₙₒ₋delay ≃ 69.3 km\/h.", + "golden_answer":"69.3", + "source":"Bigmath_synth" + }, + { + "instruction":"At a summer camp, every camper receives a welcome kit that includes 3 water bottles. In addition, campers joining the hiking activity get 4 extra water bottles, while those joining the swimming activity get 2 extra water bottles. If there are 18 campers total—with 10 in the hiking group and the remaining campers in the swimming group—how many water bottles are handed out altogether?", + "output":"First, each of the 18 campers gets 3 bottles: \n18 × 3 = 54 bottles\n\nNext, the hiking campers (10 of them) get 4 extra each: \n10 × 4 = 40 bottles\n\nThe remaining 8 campers (18 – 10) are in swimming and get 2 extra each: \n8 × 2 = 16 bottles\n\nTotal bottles = 54 + 40 + 16 = 110 bottles", + "golden_answer":"110", + "source":"Bigmath_synth" + }, + { + "instruction":"In a candy factory, the cost per kilogram of sugar (s dollars) and cocoa (c dollars) are linked by the relationship 8s = 12c = 96. The factory uses these ingredients to produce a special blend that costs 150 · (s · c) dollars. If the government awards a subsidy equal to 15% of this blend’s cost, what is the value of the subsidy?\n\n", + "output":"First note that \n8s = 96 ⇒ s = 12 \n12c = 96 ⇒ c = 8 \n\nSo s·c = 12·8 = 96, and the blend costs \n150·(s·c) = 150·96 = 14 400 dollars. \n\nA 15% subsidy on that is \n0.15·14 400 = 2 160 dollars.", + "golden_answer":"160", + "source":"Bigmath_synth" + }, + { + "instruction":"A local charity fair sells five special raffle tickets whose prices (in dollars) are given by the reciprocals of the following numbers:\n  Ticket A: 1⁄1.02  Ticket B: 1⁄1.25  Ticket C: 1⁄1  Ticket D: 1⁄12  Ticket E: 1⁄102\n\nA buyer may choose one of two purchasing options:\n\n• Option 1 (Single Pack): Buy one of each ticket. If the total cost is less than 2.90 dollars, a bonus fee of 0.15 dollars is added to the invoice; if the total cost is 2.90 dollars or more, instead a processing fee equal to 5% of the total cost is added.\n\n• Option 2 (Double Pack): Buy two complete sets of the five tickets. In this case the buyer receives a 10% discount on the total cost of the tickets, but must also pay a fixed shipping fee of 0.25 dollars.\n\nDetermine the final amount the buyer pays under each option. (You may leave your answers as exact expressions or as decimal approximations.)", + "output":"First, write the five ticket‐prices as fractions with a common denominator. One finds \n\n A = 1∕1.02 = 50∕51 \n B = 1∕1.25 = 4∕5 \n C = 1∕1 = 1 \n D = 1∕12 \n E = 1∕102 \n\nPutting them over 1020 as common denominator, \n A = 1000\/1020, \n B = 816\/1020, \n C = 1020\/1020, \n D = 85\/1020, \n E = 10\/1020. \n\nSo the single‐pack subtotal is \nS = (1000+816+1020+85+10)\/1020 = 2931\/1020 = 977\/340 ≃ 2.87352941. \n\nSince 2.8735… < 2.90, we must add the \\$0.15 bonus fee. Thus \n\nOption 1 total = S + 0.15 \n = 977\/340 + 3\/20 \n = (977 + 51)\/340 \n = 1028\/340 = 257\/85 ≃ \\$3.02352941. \n\n---\n\nFor the double‐pack, you buy two full sets (cost 2S), get a 10% discount, and pay \\$0.25 shipping. Hence \n\nOption 2 total = 0.9·(2S) + 0.25 \n = (9\/5)·(977\/340) + 1\/4 \n = 8793\/1700 + 425\/1700 \n = 9218\/1700 ≃ \\$5.42235294. \n\nIn decimal form: \nOption 1 ≃ \\$3.02 \nOption 2 ≃ \\$5.42", + "golden_answer":"5.42", + "source":"Bigmath_synth" + }, + { + "instruction":"Six colleagues – Allen, Brenda, Carlos, Diana, Ethan, and Fiona – are scheduled to sit in a row of six chairs for an important meeting. However, two requirements must be met: \n\n• Carlos must sit in one of the end seats.\n• Diana refuses to sit immediately next to Ethan.\n\nDetermine the number of seating arrangements that satisfy both conditions.", + "output":"Let the six seats be numbered 1–6 from left to right. We first force Carlos (C) into one of the two ends (seat 1 or seat 6). That gives 2 choices for C. The remaining five people are then to be placed in the other five seats, with the restriction that Diana (D) and Ethan (E) are not adjacent.\n\n1. Count all seatings with C at a fixed end (say seat 1): \n – We have 5! = 120 ways to seat {A, B, D, E, F} in seats 2–6. \n2. Count the “bad” ones where D and E are adjacent among seats 2–6: \n – Treat {D,E} as a block. Then we have 4 “objects” (the DE‑block, A, B, F) to arrange in 5 chairs: 4! ways, but the DE‑block can be DE or ED (2 orders). \n – So there are 4!·2 = 24·2 = 48 bad seatings for each fixed end. \n3. Good seatings for one end = 120 – 48 = 72. \n4. Since C could be in seat 1 or seat 6, total = 2·72 = 144.\n\nAnswer: 144 arrangements.", + "golden_answer":"144", + "source":"Bigmath_synth" + }, + { + "instruction":"An investor is considering a bond that promises an annual coupon of 12% on a face value of $100. However, the bond is selling for 90 (i.e. 90% of face value). \n\na) What is the bond’s effective annual yield based on the purchase price? \n\nb) If an additional transaction fee of 2% is added to the purchase price, what is the net effective annual yield for the investor? \n\nExpress both answers as percentages rounded to two decimal places.", + "output":"a) Since the bond pays \\$12 per year on a purchase price of \\$90, the gross (effective) annual yield is \n 12∕90 = 0.1333 = 13.33%\n\nb) If you pay an extra 2% on top of the \\$90 (i.e. total cost = 90×1.02 = \\$91.80), your net annual yield becomes \n 12∕91.80 ≈ 0.1307 = 13.07%", + "golden_answer":"13.07", + "source":"Bigmath_synth" + }, + { + "instruction":"Let b be a real parameter and fix a = 6. For each b, define\n  z₁ = b – 6i.\nNow construct z₂ by the following rule:\n • If b < 4, let z₂ be the mirror image of z₁ about the vertical line Re(z) = 4.\n • If b > 4, let z₂ be the mirror image about the vertical line Re(z) = 4 of the complex conjugate of z₁.\n\n(a) Express the product P = z₁ · z₂ in terms of b for both cases.\n\nHint: For any complex number z = x + yi, its reflection across the vertical line Re(z) = 4 is given by\n  z' = (2·4 – x) + yi = (8 – x) + yi.\nAlso, recall that the complex conjugate of z₁ = b – 6i is b + 6i.\n\n(b) Using your general expressions, evaluate |P| when\n (i) b = 2 (so that the first case applies),\n (ii) b = 6 (so that the second case applies).\nThen compute the percentage difference between these two moduli. The percentage difference is defined as\n\n  Percentage difference = (| |P(b = 6)| – |P(b = 2)| | ÷ [(|P(b = 6)| + |P(b = 2)|)\/2]) × 100%.\n\nSolve all parts of the problem.", + "output":"Here is a step‐by‐step solution.\n\nWe fix a=6 and set \n z₁=b–6i. \n\nWe want z₂ according to two cases:\n\nCase 1: b<4. \n First reflect z₁ about the vertical line Re z=4. If z=x+yi then its reflection is z′=(8–x)+yi. \n Here x=b, y=–6 so \n  z₂=(8–b)–6i. \n\nCase 2: b>4. \n First take the complex conjugate of z₁: \n  \\overline{z₁}=b+6i. \n Then reflect that about Re z=4: \n  z₂=(8–b)+6i. \n\n(a) Compute P=z₁·z₂ in each case.\n\n1) b<4: \n z₁=(b–6i), z₂=(8–b)–6i \n P=(b–6i)\\bigl((8–b)–6i\\bigr) \n  =b(8–b) –6b i –6i(8–b)+36 \n  =8b–b² –6b i –48i+6b i+36 \n  (–6b i+6b i cancel) \n  = (8b – b² +36) –48i \n  = –b²+8b–36 –48i. \n\n2) b>4: \n z₁=(b–6i), z₂=(8–b)+6i \n P=(b–6i)\\bigl((8–b)+6i\\bigr) \n  =b(8–b)+6b i –6i(8–b)–36 i² \n  =8b–b²+6b i –48i+6b i+36 \n  = (8b–b²+36)+i(12b–48) \n  =–b²+8b+36 + i(12b–48). \n\n(b) Now plug in b=2 (case 1) and b=6 (case 2).\n\n(i) b=2 (<4): \n P(2)= –2²+8·2–36 –48i = –4+16–36 –48i = –24 –48i. \n |P(2)|=√[ (–24)²+(–48)² ]=√(576+2304)=√2880=24√5. \n\n(ii) b=6 (>4): \n P(6)= –6²+8·6+36 +i(12·6–48) \n    = –36+48+36 +i(72–48)=48+24i. \n |P(6)|=√(48²+24²)=√(2304+576)=√2880=24√5. \n\nHence the two moduli coincide, so the percentage difference is zero. \n\nAnswer summary: \n(a) \n if b<4, P= –b²+8b–36 –48i, \n if b>4, P= –b²+8b+36 +i(12b–48). \n(b) \n |P(2)|=24√5, |P(6)|=24√5, \n percentage difference=0%.", + "golden_answer":"0", + "source":"Bigmath_synth" + }, + { + "instruction":"A rectangular swimming pool is to be built adjacent to a building so that one of its long sides (the side along the building) needs no fencing. The remaining three sides will be fenced, and an additional fence—running parallel to the building (that is, in the same direction as the unfenced side)—will divide the pool into two equal sections. The pool’s design requires that its length be 20 meters longer than twice its width. If the total length of fencing used (for both the three external sides and the internal dividing fence) is 300 meters, find the dimensions of the pool and the length of the internal dividing fence.", + "output":"Let W = the width of the pool (the two sides perpendicular to the building) and L = the length of the pool (the side along the building). \n\n1. Fencing needed: \n – Opposite long side: L \n – Two short sides: 2W \n – Internal divider (parallel to the building): L \n Total fencing = L + 2W + L = 2L + 2W = 300 m. \n ⇒ L + W = 150. \n\n2. Design requirement: \n L = 2W + 20. \n\nSubstitute into L + W = 150: \n (2W + 20) + W = 150 \n 3W + 20 = 150 \n 3W = 130 \n W = 130\/3 ≃ 43.33 m \n L = 2·(130\/3) + 20 = 260\/3 + 60\/3 = 320\/3 ≃ 106.67 m \n\nInternal dividing fence (parallel to the building) has length = L = 320\/3 m ≃ 106.67 m. \n\nAnswer: \n• Width ≃ 43.33 m \n• Length ≃ 106.67 m \n• Internal fence ≃ 106.67 m", + "golden_answer":"106.67", + "source":"Bigmath_synth" + }, + { + "instruction":"A gondolier in Venice rows his gondola along a canal. When carrying a tourist, the canal’s current helps him to move downstream at 18 km\/h and hinders him upstream at 6 km\/h. Normally, however, without a tourist on board, his rowing speed in still water increases by 2 km\/h compared to when he has a tourist. Find both the gondolier’s usual rowing speed in still water (with no current and no tourist) and the speed of the canal’s current.", + "output":"Let \n v = his rowing speed in still water when carrying a tourist, \n c = the canal’s current speed. \n\nDownstream with tourist: v + c = 18 \nUpstream with tourist: v – c = 6 \n\nAdd the two equations: \n 2v = 24 ⇒ v = 12 km\/h \nThen c = 18 – v = 6 km\/h. \n\nWithout a tourist his rowing speed in still water is 2 km\/h faster, i.e. \n 12 + 2 = 14 km\/h. \n\nAnswer: \n• His usual (no‑tourist) still‑water rowing speed is 14 km\/h. \n• The canal’s current speed is 6 km\/h.", + "golden_answer":"6", + "source":"Bigmath_synth" + }, + { + "instruction":"A public park is designed in the shape of an equilateral triangle. A circular pond is perfectly inscribed within the triangle, and within that circle a regular hexagonal fountain is installed. If the fountain’s area is 16 square meters and only 70% of the remaining area (the region of the triangle outside the fountain) is available for planting due to walkways, what is the total planting area in square meters?", + "output":"First note that for a regular hexagon of side a,\n\n Area(hexagon) = (3√3\/2)·a² = 16 \n⇒ a² = 16·2\/(3√3) = (32)\/(3√3).\n\nThe hexagon is inscribed in the pond‐circle, so the circle’s radius is R = a. That same circle is the incircle of the equilateral triangle, whose inradius is r = (side·√3)\/6. Hence if the triangle’s side is T,\n\n T·√3\/6 = a \n⇒ T = 6a\/√3 = 2√3·a.\n\nThe triangle’s area is\n\n Area(triangle) = (√3\/4)·T² \n = (√3\/4)·(2√3 a)² \n = (√3\/4)·(12 a²) \n = 3√3 a².\n\nBut a² = 32\/(3√3) ⇒\n\n Area(triangle) = 3√3·[32\/(3√3)] = 32.\n\nSo the triangle has area 32, the fountain (hexagon) has area 16, leaving 32−16 = 16 m² of “other” space. Of that, only 70% is planted:\n\n Planting area = 0.70·16 = 11.2 m².", + "golden_answer":"11.2", + "source":"Bigmath_synth" + }, + { + "instruction":"A community center organizes a movie night for charity and earns $60 from ticket sales. In addition, 40 community members each contribute $7. The event has three expenses: stage setup costs $2 per person, refreshments cost $3 per person, and cleaning fees are $1 per person. After covering these expenses, the center sets aside 5% of the initial total funds for emergencies. Furthermore, if the remaining balance (after expenses and the emergency reserve) exceeds 15% of the initial total funds, the center donates 50% of the excess amount over that 15% to a local shelter. Determine the final amount remaining in the fund after all these deductions.", + "output":"Here’s the step‐by‐step breakdown:\n\n1. Compute initial total funds \n • Ticket sales = \\$60 \n • Contributions = 40 people × \\$7\/person = \\$280 \n → Initial total S = 60 + 280 = \\$340 \n\n2. Subtract per‑person expenses (for the 40 members) \n • Stage setup: 40 × \\$2 = \\$80 \n • Refreshments: 40 × \\$3 = \\$120 \n • Cleaning: 40 × \\$1 = \\$40 \n → Total expenses = 80 + 120 + 40 = \\$240 \n → Balance after expenses = 340 − 240 = \\$100 \n\n3. Set aside 5% of the initial \\$340 for emergencies \n • Emergency reserve = 0.05 × 340 = \\$17 \n → Balance after reserve = 100 − 17 = \\$83 \n\n4. Check the 15% threshold of the initial funds \n • 15% of 340 = 0.15 × 340 = \\$51 \n • Remaining balance (\\$83) exceeds that threshold (\\$51). \n • Excess = 83 − 51 = \\$32 \n\n5. Donate half of the excess to a shelter \n • Donation = 0.5 × 32 = \\$16 \n → Final remaining balance = 83 − 16 = \\$67 \n\nAnswer: The fund ends up with \\$67 remaining.", + "golden_answer":"67", + "source":"Bigmath_synth" + }, + { + "instruction":"A ferry boat measures 35.0 meters in length. When it passes a fixed buoy at the edge of a canal, it takes 7.0 seconds for the entire boat to clear the buoy while traveling at a constant speed relative to the ground. Because of a current opposing its motion, the ferry’s ground speed is 15% lower than the speed set by its engine. What is the engine’s setting speed in kilometers per hour?", + "output":"First find the ferry’s speed over ground: \nv₍g₎ = length \/ time = 35.0 m \/ 7.0 s = 5.0 m\/s. \n\nSince the current reduces the ground speed by 15%, \nv₍g₎ = 0.85·v₍eng₎ ⇒ v₍eng₎ = v₍g₎\/0.85 = 5.0 m\/s ÷ 0.85 ≈ 5.882 m\/s. \n\nConvert to km\/h: \nv₍eng₎ ≈ 5.882 m\/s × 3.6 ≈ 21.2 km\/h.", + "golden_answer":"21.2", + "source":"Bigmath_synth" + }, + { + "instruction":"A custom-designed ice cream cone is engineered so that its lateral surface, when unwrapped, would ideally form a 270° sector of a circle with a radius of 5 centimeters. However, to create a decorative border, the manufacturer intentionally uses only 90% of the ideal sector’s edge length when forming the cone. (In other words, the actual arc length that forms the cone’s base is 90% of the full arc length of the 270° sector.) Determine the radius of the base of the cone.\n\nTo solve the problem, note that the arc length L of a full 270° sector with radius 5 is \n  L₍ideal₎ = (270\/360) · (2π × 5) = (3\/4) · 10π = 7.5π.\nBecause only 90% is used, the actual arc length is L = 0.9 × 7.5π = 6.75π.\nThis arc length becomes the circumference of the cone’s base, so:\n  2πr = 6.75π  ⟹  r = (6.75π)\/(2π) = 3.375 centimeters.\nThus, the radius of the base of the cone is 3.375 centimeters.", + "output":"Your reasoning is exactly right. Here’s a quick recap:\n\n1. Ideal sector arc length \n L₀ = (270°\/360°)·(2π·5 cm) = (3\/4)·10π = 7.5π cm. \n2. Using only 90% of that gives \n L = 0.9·7.5π = 6.75π cm. \n3. This becomes the cone’s base circumference: \n 2πr = 6.75π ⟹ r = 6.75π\/(2π) = 3.375 cm.\n\nSo the cone’s base radius is 3.375 cm.", + "golden_answer":"3.375", + "source":"Bigmath_synth" + }, + { + "instruction":"A bank introduced a special deposit scheme offering simple interest at a fixed rate. If a sum is deposited, then after 6 years the interest earned equals half the deposited amount minus Rs. 150, but if the same sum is held for 9 years the interest equals half the deposit plus Rs. 100. Assuming the rate of interest remains constant throughout, find the amount originally deposited.", + "output":"Let P be the principal and r the annual simple‐interest rate (in %). Then\n\n1) After 6 y: Interest = P·r·6\/100 = P\/2 − 150 \n2) After 9 y: Interest = P·r·9\/100 = P\/2 + 100 \n\nSubtracting (1) from (2): \nP·r·(9−6)\/100 = (P\/2+100) − (P\/2−150) = 250 \n⇒ P·r·3\/100 = 250 \n⇒ P·r = 250·100\/3 = 25000\/3 \n\nPlug into (1): \nP·r·6\/100 = (25000\/3)·6\/100 = 500 = P\/2 −150 \n⇒ P\/2 = 650 \n⇒ P = Rs. 1 300.", + "golden_answer":"300", + "source":"Bigmath_synth" + }, + { + "instruction":"Compute the following in two steps:\n a) Evaluate the expression (√10 – 2)² – (√20 – √5)(√20 + √5).\n b) If the result from part (a) is negative, add 5 to it; otherwise leave it unchanged.\nDetermine the final value.", + "output":"Here are the steps:\n\nStep a) \n(√10 – 2)² = 10 – 4√10 + 4 = 14 – 4√10 \n(√20 – √5)(√20 + √5) = 20 – 5 = 15 \nSo the expression is \n(√10 – 2)² – (√20 – √5)(√20 + √5) \n= (14 – 4√10) – 15 \n= –1 – 4√10 \n\nStep b) \nSince –1 – 4√10 is negative, we add 5: \n(–1 – 4√10) + 5 = 4 – 4√10 \n\nFinal value: 4 – 4√10.", + "golden_answer":"10", + "source":"Bigmath_synth" + }, + { + "instruction":"A museum assigns 7‐digit identification codes to its artifacts using exactly three 1s, two 4s, and two 5s. For security reasons, every valid code must end with the digit 5. Determine the difference between the largest and smallest valid codes that can be formed under these conditions, and then express this difference as a percentage of the largest valid code.", + "output":"First note that with exactly three 1’s, two 4’s and two 5’s, and the requirement that the last (7th) digit be 5, our pool for the first six digits is\n\n {1, 1, 1, 4, 4, 5}.\n\n1. Largest code: put the remaining 5’s and 4’s as far left as possible.\n\n Positions 1–6: 5, 4, 4, 1, 1, 1 \n Position 7: 5\n\n ⇒ 5441115\n\n2. Smallest code: put the 1’s as far left as possible, then 4’s, then the extra 5 at position 6, with the required final 5 in position 7.\n\n Positions 1–6: 1, 1, 1, 4, 4, 5 \n Position 7: 5\n\n ⇒ 1114455\n\n3. Difference:\n\n 5441115 − 1114455 = 4326660\n\n4. Percentage of the largest:\n\n (4326660 \/ 5441115) × 100% \n ≈ 0.795179… × 100% \n ≈ 79.52%\n\nAnswer: \n• Difference = 4 326 660 \n• This is about 79.52% of the largest code.", + "golden_answer":"79.52", + "source":"Bigmath_synth" + }, + { + "instruction":"A company calculates its annual bonus for each employee using three factors that are then combined into a final bonus amount. The bonus is computed as follows:\n\n • Base Bonus = |Target Score – Employee Score| dollars. (The Target Score is fixed at 10.)\n • Project Bonus = √(9 + number of projects completed) dollars.\n • Multiplier = (1\/3)^(–1)        (That is, the reciprocal of 1\/3.)\n\nAfter summing these three amounts, an adjustment is made by adding twice the cosine of 30° (with the cosine evaluated in degrees), and the resulting total is the final bonus.\n\n(a) Compute the final bonus for an employee who scored 8 and completed 7 projects.\n\n(b) Compute the final bonus for an employee who scored 4 and completed 7 projects.\n\n(Provide your answers as decimal approximations rounded to two decimal places.)", + "output":"First note: \ncos 30° = √3\/2 ≈ 0.8660254, so 2·cos 30° ≈ 1.732051. \nMultiplier = (1\/3)^(–1) = 3. \n\nProject Bonus for 7 projects = √(9+7) = √16 = 4. \n\nConstant part = Project Bonus + Multiplier + 2·cos 30° \n = 4 + 3 + 1.732051 \n = 8.732051. \n\n(a) Score = 8 ⇒ Base = |10–8| = 2 \n Final ≈ 2 + 8.732051 = 10.732051 ≈ 10.73 \n\n(b) Score = 4 ⇒ Base = |10–4| = 6 \n Final ≈ 6 + 8.732051 = 14.732051 ≈ 14.73", + "golden_answer":"14.73", + "source":"Bigmath_synth" + }, + { + "instruction":"A swimming pool is being filled by three pipes. Pipe A can fill the pool in 4 hours, pipe B in 12 hours, and pipe C in 24 hours. However, due to high summer temperatures, water evaporates from the pool at a constant rate—the loss of water is equivalent to emptying a full pool in 36 hours. If all three pipes are opened simultaneously, how many hours will it take to completely fill the pool starting from empty?", + "output":"Let vA=1\/4, vB=1\/12, vC=1\/24 (pools per hour), and ve=1\/36 the evaporation rate. \nNet fill rate = vA+vB+vC–ve \n = 1\/4+1\/12+1\/24 – 1\/36 \n = 9\/36+3\/36+1.5\/36 – 1\/36 \n = (9+3+1.5–1)\/36 \n = 12.5\/36 \n = 25\/72 pools per hour. \nTime to fill = 1 ÷ (25\/72) = 72\/25 hours = 2.88 hours ≈ 2 h 52 m 48 s.", + "golden_answer":"48", + "source":"Bigmath_synth" + }, + { + "instruction":"An elliptical garden has a major axis of 14 meters and a minor axis of 10 meters. A circular flower bed is to be installed inside the garden so that its center is located at one of the foci of the ellipse and the circle is tangent to the ellipse (with no part of the circle extending outside). However, to allow for surrounding walkways, only 85% of the maximum possible radius (the one that would make the circle tangent to the ellipse) is used. Find the effective radius of the circular flower bed.", + "output":"The key observation is that the largest circle centered at a focus which just touches the ellipse will touch it at the end of the major‐axis. Hence its radius is\n\n rₘₐₓ = distance from (c,0) to (a,0) = a – c\n\nwhere \n a = 7, \n b = 5, \n c = √(a²–b²) = √(49–25) = 2 √6. \n\nThus \n rₘₐₓ = 7 – 2 √6. \n\nWe only take 85% of that:\n\n r = 0.85·(7 – 2 √6) \n ≃ 0.85·(7 – 4.898979…) \n ≃ 0.85·2.10102 \n ≃ 1.786 m \n\nAnswer: approximately 1.79 m.", + "golden_answer":"1.79", + "source":"Bigmath_synth" + }, + { + "instruction":"In a vocational school, 200 students have the option to register for two art workshops: painting and sculpture. Out of the 200 students, 120 registered for the painting workshop and 90 registered for the sculpture workshop, while 50 students did not register for any workshop.\n\na) Find the number of students who registered for both workshops.\n\nb) The organizers will arrange an extra workshop room if the number of students attending both workshops exceeds 25% of all students. Should an extra room be arranged?", + "output":"a) Let P be the set in painting and S the set in sculpture. \nBy inclusion–exclusion, \n|P ∪ S| = |P| + |S| – |P ∩ S|. \nHere |P ∪ S| = total – none = 200 – 50 = 150, so \n150 = 120 + 90 – |P ∩ S| \n⇒ |P ∩ S| = 120 + 90 – 150 = 60. \n\nb) 25% of all students = 0.25·200 = 50. \nSince 60 students attend both workshops and 60 > 50, an extra room should be arranged.", + "golden_answer":"50", + "source":"Bigmath_synth" + }, + { + "instruction":"A cyclist participates in a race that unfolds in two segments:\n\n• In the first segment he rides on a flat road for 20 minutes at a constant (wind‐free) speed of v km\/h. Because of a light tailwind, his effective speed on the flat is 10% higher, so he covers a distance equal to (1.10·v)·(20\/60) kilometers.\n\n• In the second segment he descends a hill for 5 minutes while covering exactly 8 kilometers. Throughout the descent he accelerates uniformly. At the start of the descent (in wind‐free conditions) his speed is 15 km\/h slower than his flat-road speed—that is, his initial speed is (v – 15) km\/h—and by the end of the descent his wind-free speed has increased to 5 km\/h above his flat-road speed (v + 5 km\/h). Thus, his wind-free average speed during the descent is [(v – 15) + (v + 5)]\/2 = (2v – 10)\/2 = v – 5 km\/h. However, a headwind during the descent reduces his effective speed by 20%, so his effective average speed on the hill is only 0.80·(v – 5) km\/h. Multiplying by the descent time of 5 minutes (5\/60 hours) gives the descent distance, which is specified to be 8 km.\n\nFinally, his overall average speed for the entire race is 32 km\/h.\n\n(a) Write an equation for the descent leg and solve for v.\n(b) Then, find his wind‐free speed at the start of the descent.\n\nProvide the answers in km\/h.\n\n", + "output":"Here’s the descent‐leg equation and its solution:\n\n(a) During the 5 min (5\/60 h) descent the cyclist’s wind–free average speed is \n (initial+final)\/2 = [(v–15)+(v+5)]\/2 = v–5 (km\/h), \nbut a headwind cuts that by 20%, so his effective speed is 0.8·(v–5). Hence the 8 km of descent satisfy\n\n 0.8·(v–5)·(5\/60) = 8.\n\nSolve for v:\n\n 0.8·(v–5)·(1\/12) = 8 \n ⇒ 0.8·(v–5) = 8·12 = 96 \n ⇒ v–5 = 96\/0.8 = 120 \n ⇒ v = 125 km\/h.\n\n(b) His wind–free speed at the start of the descent is v–15 = 125–15 = 110 km\/h.", + "golden_answer":"110", + "source":"Bigmath_synth" + }, + { + "instruction":"A health snack company finds that the customer approval score for a new granola bar recipe is modeled by the function A(x) = –3x² + 2x + 70, where x represents the percentage (in dozens) of a secret ingredient used. However, if x exceeds 5 (i.e. more than 60%), the recipe becomes overly strong in flavor and a penalty of 15 points is deducted from the approval score. Determine all values of x for which the final approval score is less than 60.", + "output":"We introduce the “final” approval score Aₙ(x) by \n Aₙ(x) = \n { A(x) = −3x² + 2x + 70 if 0 ≤ x ≤ 5 \n { A(x) − 15 = (−3x² + 2x + 70) − 15 if x > 5 \n\nWe want Aₙ(x) < 60. Split into the two regions:\n\n1) 0 ≤ x ≤ 5 \n Aₙ(x) = −3x² + 2x + 70 < 60 \n ⇔ −3x² + 2x + 70 − 60 < 0 \n ⇔ −3x² + 2x + 10 < 0 \n ⇔ 3x² − 2x − 10 > 0. \n\n The quadratic 3x² − 2x − 10 has roots \n x = [2 ± √( (−2)² − 4·3·(−10) )] \/ (2·3) \n = [2 ± √(4 + 120)] \/ 6 \n = [2 ± √124] \/ 6 \n = [2 ± 2√31] \/ 6 \n = (1 ± √31) \/ 3. \n\n Numerically \n (1 − √31)\/3 ≃ −1.52 (irrelevant since x ≥ 0) \n (1 + √31)\/3 ≃ 2.19. \n\n Since 3x² − 2x − 10 opens upward, 3x² − 2x − 10 > 0 for x < (1−√31)\/3 or x > (1+√31)\/3. Restricting to [0,5] we get \n Aₙ(x)<60 ⇔ x > (1+√31)\/3 ≃ 2.19. \n\n2) x > 5 \n Aₙ(x) = (−3x² + 2x + 70) − 15 < 60 \n ⇔ −3x² + 2x + 55 < 60 \n ⇔ −3x² + 2x – 5 < 0 \n ⇔ 3x² − 2x + 5 > 0. \n But 3x² − 2x + 5 has discriminant (−2)² − 4·3·5 = 4 − 60 = −56 < 0 and opens up, so it is >0 for all x. Hence for every x>5 the penalized score is automatically <60. \n\nConclusion: \n • On [0,5]: Aₙ(x)<60 exactly when x>(1+√31)\/3≈2.19. \n • On (5,∞): Aₙ(x)<60 for all x. \n\nHence the full solution set is \n x ∈ ((1+√31)\/3, 5] ∪ (5, ∞) \nor more succinctly \n x > (1+√31)\/3 (approximately x>2.19).", + "golden_answer":"2.19", + "source":"Bigmath_synth" + }, + { + "instruction":"A wildlife reserve features a circular lake whose shoreline is described by \n  (x – 7)² + (y + 2)² = 49.\nA sensor is to be installed along a straight monitoring road given by \n  4x – 3y + 11 = 0.\nDetermine, as a percentage, the ratio of the shortest possible distance from any point on the lake’s shore to the road to the longest possible distance from a point on the shore to the road.", + "output":"First compute the distance from the circle’s center C(7, –2) to the line 4x–3y+11=0: \nd_C = |4·7 – 3·(–2) + 11|\/√(4²+(-3)²) \n = |28+6+11|\/5 \n = 45\/5 \n = 9. \n\nSince the circle has radius r=7, the maximum distance from a point on the circle to the line is d_max=9+7=16, and the minimum is d_min=9–7=2. Hence the ratio of shortest to longest distance is \n d_min\/d_max = 2\/16 = 1\/8 = 0.125 = 12.5%.", + "golden_answer":"12.5", + "source":"Bigmath_synth" + }, + { + "instruction":"An environmental engineer must prepare 100 liters of a water treatment solution that is exactly 65% concentrated with a certain chemical. She has three stock solutions available: Stock X is 40% concentrated, Stock Y is 70% concentrated, and Stock Z is 90% concentrated. For safety reasons, at least 15 liters of Stock Z must be included in the mix. In addition, because of supply constraints, the amount of Stock Y used must be at least twice the volume of Stock X used. If x, y, and z denote the volumes (in liters) of Stocks X, Y, and Z respectively, find all possible combinations of (x, y, z) that satisfy\n\n  x + y + z = 100, \n  0.40·x + 0.70·y + 0.90·z = 65, \n  z ≥ 15, \n  y ≥ 2x, \n  x, y, z ≥ 0.\n\n", + "output":"First, from \n (1) x + y + z = 100 \n (2) 0.40 x + 0.70 y + 0.90 z = 65 \n\nwe clear decimals in (2) by multiplying by 10: \n 4 x + 7 y + 9 z = 650. \n\nNow solve (1) for x and substitute into (2):\n\nFrom (1): \n x = 100 − y − z. \n\nPlug into 4 x + 7 y + 9 z = 650: \n 4(100 − y − z) + 7 y + 9 z = 650 \n 400 − 4 y − 4 z + 7 y + 9 z = 650 \n 400 + 3 y + 5 z = 650 \n 3 y + 5 z = 250 \n y = (250 − 5 z)\/3.\n\nThen \n x = 100 − y − z = 100 − (250 − 5 z)\/3 − z \n   = (300 − (250 − 5 z) − 3 z)\/3 \n   = (50 + 2 z)\/3.\n\nSo every solution of the two equations is of the form \n x = (50 + 2 z)\/3, \n y = (250 − 5 z)\/3, \n z free. \n\nWe now enforce the inequalities:\n\n1) x ≥ 0 is automatic for z ≥ −25. \n2) y ≥ 0 ⇒ 250 − 5 z ≥ 0 ⇒ z ≤ 50. \n3) z ≥ 15 (safety). \n4) y ≥ 2 x ⇒ (250 − 5 z)\/3 ≥ 2·(50 + 2 z)\/3 \n ⇒ 250 − 5 z ≥ 100 + 4 z \n ⇒ 150 ≥ 9 z \n ⇒ z ≤ 150\/9 = 50\/3 ≃ 16.6667. \n\nCombining 2), 3), 4) gives \n 15 ≤ z ≤ 50\/3. \n\nHence the full feasible set is the line segment\n\n {x, y, z} = { ((50 + 2 z)\/3, (250 − 5 z)\/3, z)   |   15 ≤ z ≤ 50\/3 }.\n\nIn particular the two “end‐points” are\n\n• z = 15 ⇒ x = (50 + 30)\/3 = 80\/3 ≃ 26.67, \n    y = (250 − 75)\/3 = 175\/3 ≃ 58.33, \n    z = 15.\n\n• z = 50\/3 ≃ 16.67 ⇒ x = (50 + 2·(50\/3))\/3 = 250\/9 ≃ 27.78, \n    y = (250 − 5·(50\/3))\/3 = 500\/9 ≃ 55.56, \n    z = 50\/3.\n\nAny choice of z between 15 and 50\/3 (and x,y given by the formulas) yields a 100‑L mixture at exactly 65% concentration, with z≥15 and y≥2x.", + "golden_answer":"2", + "source":"Bigmath_synth" + }, + { + "instruction":"Consider a futuristic art installation where a sculpture is built as a four‐dimensional hypercube\n  Q = {(x₁, x₂, x₃, x₄) ∈ ℝ⁴ : 0 ≤ xᵢ ≤ 1 for i = 1, 2, 3, 4}.\nA high‐power laser cuts Q along a hyperplane parallel to the plane\n  x₁ + x₂ + x₃ + x₄ = 0,\nproducing a nondegenerate three‐dimensional polyhedron P whose faces reflect light dramatically. The artist can slide the hyperplane (i.e. vary its constant term) to change the shape of P. \n\n(a) Determine the maximum possible number of faces that P can have.\n  Hint: Think about how many of Q’s hypercube boundaries can contribute facets to P when the cut “slices” through Q in an optimal way.\n\nAfter achieving the maximum number of faces in P, the artist decides to create a composite work by joining two such polyhedra along one entire common face. \n\n(b) Assuming no other faces merge during the joining process, what is the total number of distinct faces visible on the composite sculpture?\n\n", + "output":"Here is a quick way to see that the maximum is 8, and that gluing two such pieces along a common face leaves 14 faces visible:\n\n(a) Q has exactly eight 3‐dimensional “facets,” namely \n  {x∈ℝ⁴: xᵢ=0, 0≤xⱼ≤1 for j≠i} (four of these) \nand \n  {x∈ℝ⁴: xᵢ=1, 0≤xⱼ≤1 for j≠i} (four more). \n\nWhen you slice by \n  H_c: x₁+x₂+x₃+x₄=c, 0 0 and a ≠ 1, and assume 2a – 5 ≠ 0 (so that f is not the zero function). If f(0) + f(2) = 3 · f(1), determine all possible values of a that satisfy these conditions.", + "output":"First note \r\n f(0) = (2a–5)·a^(–1) = (2a–5)\/a \r\n f(1) = (2a–5)·a^0 = 2a–5 \r\n f(2) = (2a–5)·a^1 = (2a–5)a. \r\n\r\nThe equation f(0)+f(2)=3 f(1) becomes \r\n (2a–5)\/a + (2a–5)a = 3(2a–5). \r\nSince 2a–5≠0 we can divide it out: \r\n 1\/a + a = 3 \r\n⇔ 1 + a² = 3a \r\n⇔ a² – 3a + 1 = 0. \r\n\r\nBy the quadratic formula \r\n a = [3 ± √(9–4)]\/2 = (3 ± √5)\/2. \r\n\r\nBoth roots are positive, neither equals 1, and neither makes 2a–5 zero, so the solutions are \r\n a = (3+√5)\/2 or a = (3–√5)\/2.", + "golden_answer":"2", + "source":"Bigmath_synth" + }, + { + "instruction":"In a community garden, 4 gardeners harvested 200 pounds of tomatoes. Before distributing them, 25% of the tomatoes were given away as donations. If the remaining tomatoes were divided equally among the gardeners, how many pounds did each gardener receive?", + "output":"First find 25% of 200 lb: \n25%·200 = 0.25·200 = 50 lb donated. \nRemaining: 200 lb – 50 lb = 150 lb. \nSplit evenly among 4 gardeners: 150 lb ÷ 4 = 37.5 lb each.", + "golden_answer":"37.5", + "source":"Bigmath_synth" + }, + { + "instruction":"A movie theater’s daily ticket sales on weekdays follow an arithmetic progression with common difference d. The theater opens on Monday and follows this sequence through Friday. However, on weekends (Saturday and Sunday), in addition to the scheduled number from the arithmetic sequence, the theater always sells an extra 15 tickets due to promotional offers.\n\nIt is given that on Friday (day 5) the theater sold exactly 120 tickets.\n\n(a) Express, in terms of d, the total number of tickets sold on Thursday (day 4), Friday (day 5), and Saturday (day 6).\n\n(b) Determine this total when d = 5.", + "output":"Let a be Monday’s sales. Since it’s an AP with common difference d, \nThursday (day 4) = a+3d, \nFriday (day 5) = a+4d = 120, \nSaturday’s scheduled sales = a+5d, but with the extra 15 tickets it becomes a+5d+15. \n\n(a) Sum on days 4,5,6 \n= (a+3d) + (a+4d) + (a+5d+15) \n= 3a + (3+4+5)d + 15 \n= 3a + 12d + 15. \n\nBut from Friday, a+4d = 120 ⇒ a = 120−4d, so \n3a + 12d + 15 = 3(120−4d) + 12d + 15 = 360 −12d +12d +15 = 375. \n\n(b) Hence for any d (in particular d=5) the total is 375 tickets.", + "golden_answer":"375", + "source":"Bigmath_synth" + }, + { + "instruction":"An architect is designing two layouts for a park pathway adjacent to a garden whose border is defined by the line 3x + 4y – 12 = 0. In Layout A the pathway must be parallel to the garden border, while in Layout B it must be perpendicular. The pathway in both layouts is described by the equation 6x + m·y + 5 = 0. Determine the value of m for each layout.", + "output":"For a line ax + by + c = 0 the slope is –a\/b. \nGarden border 3x + 4y – 12 = 0 has slope –3\/4. \nPathway 6x + m y + 5 = 0 has slope –6\/m. \n\nLayout A (parallel): \n–6\/m = –3\/4 ⇒ 6\/m = 3\/4 ⇒ m = 8. \n\nLayout B (perpendicular): \n(–6\/m)·(–3\/4) = –1 ⇒ 18\/(4m) = –1 ⇒ 4m = –18 ⇒ m = –9\/2. \n\nAnswer: \n• Layout A: m = 8 \n• Layout B: m = –9\/2", + "golden_answer":"2", + "source":"Bigmath_synth" + }, + { + "instruction":"Let h be a function defined on ℝ by\n\n   h(x) = 3x – 3⁄(2^(|x|)).\n\nIn an economic model, if the production level x (in thousands of units) is nonnegative, the net profit (in hundred‐thousands of dollars) is given by h(x) + 1, and it is known that this profit equals 2. For negative production levels (x < 0, corresponding to a reduction in production), the profit is given solely by h(x) and is known to equal –4.5. Solve for x in each case, analyzing the two situations separately.", + "output":"We set up the two cases exactly as the problem asks:\n\n1. Non‐negative production (x ≥ 0): \n Profit = h(x) + 1 = 2 \n ⇒ h(x) = 1 \n ⇒ 3x – 3·2⁻ˣ = 1 \n ⇒ 3x – 1 = 3·2⁻ˣ \n ⇒ 2ˣ(3x – 1) = 3. \n\n This transcendental equation has no closed‐form in elementary functions, but one readily finds by numerical trial (or by, e.g., Newton’s method) \n x ≃ 0.88 \n (to two decimal places). \n\n2. Negative “production” (x < 0): \n Profit = h(x) = –4.5 \n ⇒ 3x – 3\/(2^{|x|}) = –4.5, but for x<0, |x| = –x, so 1\/2^{|x|}=2^x: \n 3x – 3·2^x = –4.5 \n ⇒ divide by 3: x – 2^x = –1.5 \n ⇒ x – 2^x + 1.5 = 0. \n\n One checks immediately that x = –1 is an exact solution, and on (−∞, 0) it is unique. \n\nAnswer: \n • For x ≥ 0, h(x)+1=2 ⇒ x ≃ 0.88. \n • For x < 0, h(x)=–4.5 ⇒ x = –1.", + "golden_answer":"1", + "source":"Bigmath_synth" + }, + { + "instruction":"A construction company is designing a modern roof with two sloping sections meeting at a ridge. For aesthetic and structural purposes, the slopes are determined by angles α and β (in degrees) that satisfy\n  tan(α + 15°) = 4⁄7  and  tan(β − 20°) = 2⁄3.\n(a) Find an expression for tan(α + β).\n(b) For safety reasons, if the overall roof incline makes tan(α + β) exceed 1, an extra support beam must be added. Assuming 0° < α, β < 90°, determine under what conditions (in terms of the possible values of tan(α + β)) the supporting beam becomes necessary.\nProvide complete justifications for your answers.", + "output":"a) By applying the addition‐and‐subtraction formula for the tangent twice one finds a very neat way to get tan (α+β) without ever having to solve for tan α or tan β individually. Observe that\n\n (α+15°)+(β−20°) = (α+β) −5°.\n\nHence \n tan[(α+15°)+(β−20°)] = tan (α+β −5°).\n\nOn the other hand, from the data \n tan(α+15°) = 4\/7, tan(β−20°) = 2\/3, \nthe addition formula gives \n tan[(α+15°)+(β−20°)]\n = [tan(α+15°) + tan(β−20°)] \n ――――――――――――――――――――― \n [1 − tan(α+15°)·tan(β−20°)] \n = (4\/7 + 2\/3) \/ [1 − (4\/7)(2\/3)]\n = (12\/21 + 14\/21) \/ (1 − 8\/21)\n = (26\/21) \/ (13\/21)\n = 2.\n\nThus \n tan (α+β −5°) = 2. \n\nNow use the formula for tan (X+5°) with X = α+β −5°:\n\n tan (α+β)\n = tan[ (α+β −5°) +5° ]\n = [tan(α+β −5°) + tan 5°] \n ――――――――――――――――― \n [1 − tan(α+β −5°)·tan 5°]\n = (2 + tan 5°) \/ (1 − 2 tan 5°). \n\nThat is the exact answer for part (a).\n\nNumerically tan 5° ≈ 0.087488, so \n tan (α+β) = (2 + 0.087488)\/(1 − 2·0.087488)\n ≃ 2.087488 \/ 0.825024\n ≃ 2.5318. \n\nb) By design, an extra beam is required exactly when the overall pitch satisfies \n tan (α+β) > 1. \n\nFrom (a) we have \n tan (α+β) = (2 + tan 5°)\/(1 − 2 tan 5°). \nSince tan 5° ≃ 0.0875, the denominator 1−2 tan 5° is still positive, and one checks immediately that the fraction exceeds 1. In fact for any 0°<α,β<90° consistent with the two shifted‐angle equations above, α+β will lie in the sector (45°,90°) so that tan (α+β)>1. \n\nConclusion: the safety beam must be added whenever \n tan (α+β) > 1. \nIn the present design tan (α+β) ≃ 2.53>1, so the beam is indeed required.", + "golden_answer":"1", + "source":"Bigmath_synth" + }, + { + "instruction":"A steel rod costing $50 can be cut into 75 equal segments. A builder spends $200 on such steel rods to construct 20 beams. For each beam, a fixed number of standard segments are joined together, and one additional reinforcement segment—cut from a different portion of a rod—is appended. If every segment from the purchased rods is used, how many standard segments are combined to form each beam?", + "output":"Let R be the number of standard‐length pieces per beam. You buy \n200\/50 = 4 rods, each yielding 75 segments, so 4·75 = 300 total segments. \nEach beam uses R “standard” segments plus one reinforcement (= R+1 segments), \nand there are 20 beams, so \n20·(R+1)=300 \n⇒ R+1=15 \n⇒ R=14. \n\nAnswer: Each beam is made of 14 standard segments.", + "golden_answer":"14", + "source":"Bigmath_synth" + }, + { + "instruction":"In a regular decagon (10-sided polygon), three of its vertices are selected at random to form a triangle. What is the probability that the triangle has exactly one side that is also a side of the decagon? Express your answer as a simplified fraction.", + "output":"The total number of ways to choose 3 vertices out of 10 is \nC(10,3) = 120. \n\nTo count the triangles that have exactly one side of the decagon:\n\n1. Choose which decagon‐side will be the one side of the triangle. There are 10 sides, so 10 choices. \n2. Call its endpoints A and B. To avoid getting any other decagon‐side in the triangle, the third vertex C must not be A or B, nor either of their other neighbors in the decagon. That rules out A, B, the neighbor of A (other than B), and the neighbor of B (other than A) — 4 forbidden vertices in all.\n3. Hence there are 10 – 4 = 6 allowable choices for C given a fixed side AB.\n4. So in all there are 10 × 6 = 60 triangles with exactly one decagon‐side.\n\nTherefore the desired probability is \n60\/120 = 1\/2.", + "golden_answer":"2", + "source":"Bigmath_synth" + }, + { + "instruction":"A manufacturer’s total production cost (in dollars) for making x items is modeled by the function\n  C(x) = (0.5x + 10)(x² – 3x + 5).\nHowever, if more than 20 items are produced, the company receives a 15% volume discount on the computed cost; that is, when x > 20 the adjusted cost is\n  C(x) = 0.85·(0.5x + 10)(x² – 3x + 5).\n\n(a) Find an expression for the instantaneous rate of change dC\/dx of the cost function when 0 ≤ x ≤ 20.\n  Hint: Use the product rule on (0.5x + 10)(x² – 3x + 5).\n\n(b) Find an expression for dC\/dx when x > 20.\n\n(c) Evaluate the rate of change dC\/dx at x = 15 and at x = 25.", + "output":"a) Let \n u(x)=0.5x+10, v(x)=x²–3x+5. \nThen \n u′(x)=0.5, v′(x)=2x–3, \nand by the product‐rule \n C′(x)=u′(x)v(x)+u(x)v′(x) \n  =0.5·(x²–3x+5)+(0.5x+10)(2x–3). \nOne convenient simplified form is \n C′(x)=1.5 x²+17 x–27.5. \n\nb) For x>20 we have C(x)=0.85·[(0.5x+10)(x²–3x+5)], so \n C′(x)=0.85·[0.5·(x²–3x+5)+(0.5x+10)(2x–3)] \nor in the simplified form \n C′(x)=0.85·(1.5 x²+17 x–27.5). \n\nc) \nAt x=15 (use part a): \n C′(15)=1.5·15²+17·15–27.5=1.5·225+255–27.5=337.5+255–27.5=565 \n(dollars per additional unit). \n\nAt x=25 (use part b): \n inside bracket=1.5·25²+17·25–27.5=1.5·625+425–27.5=937.5+425–27.5=1335 \n C′(25)=0.85·1335=1134.75 \n(dollars per additional unit).", + "golden_answer":"1134.75", + "source":"Bigmath_synth" + }, + { + "instruction":"When Mark was 4 years old, his father's age then was equal to twice Mark’s current age plus 3. In 5 years, his father's age will be 7 more than twice Mark’s age at that time. Determine Mark’s current age and his father’s current age.", + "output":"Let M = Mark’s current age and F = his father’s current age.\n\n1. “When Mark was 4” was (M – 4) years ago. At that time the father’s age was \n F – (M – 4). The problem says\n F – (M – 4) = 2M + 3 \n ⇒ F – M + 4 = 2M + 3 \n ⇒ F = 3M – 1. \n\n2. “In 5 years,” the father’s age will be F + 5 and Mark’s will be M + 5, and we’re given\n F + 5 = 2(M + 5) + 7 = 2M + 17 \n ⇒ F = 2M + 12. \n\n3. Equate the two expressions for F:\n 3M – 1 = 2M + 12 \n ⇒ M = 13. \n Then F = 2·13 + 12 = 38.\n\nAnswer: Mark is 13 years old now, and his father is 38.", + "golden_answer":"38", + "source":"Bigmath_synth" + }, + { + "instruction":"A delivery company adjusts its fuel efficiency by a factor r that depends on the delivery route. For an in‑city route, the adjustment satisfies \n  r² + 3r = 2, \nwhile for an out‑of‑city route it satisfies \n  r² + 3r = 10. \n(a) For each case, compute the value of 2r² + 6r + 5. \n(b) Then, find the ratio (2r² + 6r + 5)⁄(r² + 3r) for each route.", + "output":"Let A = r² + 3r. Then \n 2r² + 6r + 5 = 2·(r² + 3r) + 5 = 2A + 5. \n\n(a) In‑city: A = 2 ⇒ 2r²+6r+5 = 2·2 + 5 = 9 \n Out‑of‑city: A = 10 ⇒ 2r²+6r+5 = 2·10 + 5 = 25 \n\n(b) (2r²+6r+5)\/(r²+3r) = (2A+5)\/A = 2 + 5\/A \n In‑city: A = 2 ⇒ 2 + 5\/2 = 9\/2 \n Out‑of‑city: A = 10 ⇒ 2 + 5\/10 = 5\/2", + "golden_answer":"2", + "source":"Bigmath_synth" + }, + { + "instruction":"A ramp is to be installed to connect two levels in a public building. The design specifies that the tangent of the ramp’s angle of elevation is 3\/4. For safety regulations, the horizontal projection of the ramp is extended by an additional 1 meter beyond the direct horizontal distance between the two levels. If the total horizontal distance (including this 1‐meter extension) is 13 meters, determine:\n\n(a) The direct horizontal distance from the base of the ramp to the point right below the higher level.\n\n(b) The length of the ramp along its incline.\n\n(c) The actual measure of the angle of inclination in degrees.\n\n(d) If metal and wood are under consideration for constructing the ramp—where metal costs $100 per meter and wood costs 25% more per meter—calculate the extra cost incurred when using wood instead of metal.\n\n", + "output":"Here is a step‐by‐step solution.\n\nWe label \nx = the direct horizontal run of the ramp (i.e. the horizontal distance between the two levels), \nand we’re told that “for safety” an extra 1 m of horizontal walkway is added beyond that, making a total of 13 m. \n\n1. From “total horizontal = direct run + 1 m = 13 m” we get \n x + 1 = 13 ⇒ x = 12 m. \n\n Answer (a): 12 m. \n\n2. The design specifies tan θ = 3\/4 = (vertical rise)\/(horizontal run). \n Since the horizontal run is x = 12 m, the rise is \n rise = (3\/4)·12 = 9 m. \n\n The ramp itself is the hypotenuse of a right triangle with legs 12 m and 9 m, hence \n length = √(12² + 9²) = √(144 + 81) = √225 = 15 m. \n\n Answer (b): 15 m. \n\n3. The angle of inclination θ satisfies tan θ = (rise)\/(run) = 9\/12 = 3\/4. \n θ = arctan(3\/4) ≈ 36.87°. \n\n Answer (c): 36.87° (about 36°52′). \n\n4. Cost comparison: \n – Metal costs \\$100 per metre. \n – Wood costs 25% more ⇒ \\$100·1.25 = \\$125 per metre. \n Extra cost per metre when choosing wood instead of metal = \\$125 – \\$100 = \\$25. \n The ramp length is 15 m, so the extra total cost is 25·15 = \\$375. \n\n Answer (d): \\$375.", + "golden_answer":"375", + "source":"Bigmath_synth" + }, + { + "instruction":"A circular fountain has a top edge forming a circle of radius 4 meters at a constant height of 7 meters. One decorative lantern is installed at the point (4, π\/6, 7) given in cylindrical coordinates. Assuming that a second lantern is positioned exactly diametrically opposite the first on the circle, \n\na) Convert the positions of both lanterns to rectangular coordinates.\n\nb) Calculate the distance between the two lanterns.", + "output":"a) Recall that in cylindrical coordinates (r, θ, z) → rectangular (x, y, z) by \n x = r cosθ, y = r sinθ, z = z. \n\nFirst lantern: \n r = 4, θ = π\/6, z = 7 \n⇒ x₁ = 4 cos(π\/6) = 4·(√3\/2) = 2√3 \n y₁ = 4 sin(π\/6) = 4·(1\/2) = 2 \n z₁ = 7 \n→ (x₁,y₁,z₁) = (2√3, 2, 7). \n\nDiametrically opposite means θ₂ = π\/6 + π = 7π\/6, with the same r and z: \n x₂ = 4 cos(7π\/6) = 4·(–√3\/2) = –2√3 \n y₂ = 4 sin(7π\/6) = 4·(–1\/2) = –2 \n z₂ = 7 \n→ (x₂,y₂,z₂) = (–2√3, –2, 7). \n\nb) Distance d = √[(x₂–x₁)² + (y₂–y₁)² + (z₂–z₁)²]. \n Here z₂–z₁ = 0, x₂–x₁ = –2√3 – 2√3 = –4√3, y₂–y₁ = –2 – 2 = –4, so \n d = √[(–4√3)² + (–4)²] = √[48 + 16] = √64 = 8. \n\nAnswer: \na) (2√3, 2, 7) and (–2√3, –2, 7) \nb) 8 meters.", + "golden_answer":"8", + "source":"Bigmath_synth" + }, + { + "instruction":"A freight train 400 meters long passes completely through a 200-meter-long tunnel in 50 seconds while traveling at a constant speed. Later, due to new safety regulations, the train must reduce its speed by 10% before entering a 500-meter-long tunnel. Determine the time, in seconds, that the train will take to completely pass through the longer tunnel at its reduced speed.", + "output":"First, find the train’s original speed. To clear a 200 m tunnel completely, the train must travel its own length plus the tunnel length, i.e. \n distance = 400 m + 200 m = 600 m \n time = 50 s \nSo \n v = 600 m \/ 50 s = 12 m\/s \n\nUnder the new rule its speed is reduced by 10%: \n v′ = 0.9·12 m\/s = 10.8 m\/s \n\nTo clear a 500 m tunnel it must cover 400 m + 500 m = 900 m at 10.8 m\/s, so \n time′ = 900 m ÷ 10.8 m\/s ≃ 83.33 s \n\nAnswer: about 83.3 seconds.", + "golden_answer":"83.3", + "source":"Bigmath_synth" + }, + { + "instruction":"A supplier sells a smartphone to a distributor at a profit of 20%. The distributor then sells it to a local store at a profit of 25% on his purchase price. Finally, the local store marks up the smartphone by 40% on its cost and offers a 10% discount on the marked price when selling it to a customer. If the customer pays Rs. 378 for the smartphone, what was the original cost price for the supplier?", + "output":"Let the supplier’s cost price be x.\n\n1. Supplier → Distributor \n Selling price = x + 20% of x = 1.2 x\n\n2. Distributor → Store \n Selling price = 1.2 x + 25% of (1.2 x) = 1.2 x × 1.25 = 1.5 x\n\n3. Store marks up 40%, then gives 10% discount: \n Marked‑up price = 1.5 x × 1.40 = 2.1 x \n After 10% discount, customer pays = 2.1 x × 0.90 = 1.89 x\n\nWe’re told the final payment is ₹378, so \n1.89 x = 378 \nx = 378 \/ 1.89 = 200\n\nAnswer: The supplier’s original cost price was ₹200.", + "golden_answer":"200", + "source":"Bigmath_synth" + }, + { + "instruction":"A tech company had 1,000 employees at the beginning of 2015. In 2016, the workforce was expected to grow by 50% over the previous year. However, due to an unexpected economic downturn that year, the company had to lay off 20% of the new hires from 2016 before the year ended. In both 2017 and 2018, the company’s employee count grew by 50% each year with no layoffs. How many employees does the company have at the beginning of 2019?", + "output":"Let E0=1,000 (start of 2015).\n\n2016:\n– Planned +50% ⇒ would be 1,000×1.5=1,500\n– Lay off 20% of the 500 new hires ⇒ 0.2×500=100 laid off\n– Net end‐2016 = 1,500−100 = 1,400\n\n2017:\n– +50% ⇒ 1,400×1.5 = 2,100\n\n2018:\n– +50% ⇒ 2,100×1.5 = 3,150\n\nSo at the beginning of 2019 the company has 3,150 employees.", + "golden_answer":"3150", + "source":"Bigmath_synth" + }, + { + "instruction":"At a conference, the number of participants from City A is 35% higher than the number from City B. The registration fee for City A participants is 20% higher than that for City B participants. If there are 200 participants from City B and the total registration fees amount to $26,200, what is the registration fee for each City B participant?", + "output":"Let x = registration fee for each City B participant. \nThen number of City A participants = 200 × 1.35 = 270, \nand their fee is 1.20 x. \n\nTotal fees: \n200·x + 270·(1.20 x) = 26,200 \n200x + 324x = 26,200 \n524x = 26,200 \nx = 26,200 \/ 524 = 50. \n\nAnswer: each City B participant pays \\$50.", + "golden_answer":"50", + "source":"Bigmath_synth" + }, + { + "instruction":"Let S(n) be the sum of the decimal digits of n. Determine the smallest possible value of S(m) under the condition that m is a 7‑digit even number that is divisible by 1597. Analyze the problem by considering different cases for the leading digit(s) of m and the constraints imposed by both evenness and divisibility.", + "output":"We denote by m=1597·k our generic 7‐digit multiple of 1597. Since 1597 is odd, “m even” ⇐⇒ k is even, say k=2j. Hence \n   m = 1597·(2j) = 3194·j, \nand we want 1 000 000 ≤ 3194 j ≤ 9 999 999, with j∈ℕ, and we want to minimize the digit‐sum S(m).\n\n1) First‐digit = 1‐case. \n We must have \n 1 000 000 ≤ 3194 j < 2 000 000 \n ⇒ \n j ≥ ⌈1 000 000\/3194⌉ = ⌈313.14…⌉ = 314, \n j ≤ ⌊1 999 999\/3194⌋ = 626. \n Furthermore, to make m even we already enforced j∈ℕ (since 3194·j is automatically even). \n Among j=314,…,626 one can check (by either a short computer search or by hand‐inspection of the “nice” j that give many zeros) that the absolute smallest digit‐sum occurs at \n j = 315, \n giving \n m = 3194·315 = 1 006 110 \n and \n S(m) = 1+0+0+6+1+1+0 = 9. \n\n2) First‐digit ≥2. \n If the leading digit of m is ≥2 then m≥2 000 000, so the very first digit contributes at least 2 to S(m). One quickly checks that none of the even multiples of 1597 in the range 2 000 000…9 999 999 can have digit‐sum below 9 (for instance, they all force some additional nonzero digits). \n\nHence the overall minimum is S(m)=9, attained for example by \n m=1 006 110=1597·630. \n\nAnswer: The smallest possible digit‐sum is 9.", + "golden_answer":"9", + "source":"Bigmath_synth" + }, + { + "instruction":"A municipal transportation authority uses a 7‐digit identification number for its new fleet of smart buses. The number is formed using the digits 0–9 under the following conditions:\n1. The digit 5 is completely banned.\n2. No two identical digits may appear consecutively.\n3. The first digit cannot be 0.\n4. To streamline on-board computer checks, the sum of the first and last digits must be even.\nCalculate how many valid 7‐digit identification numbers the authority can assign under these rules.", + "output":"Here is a clean way to see it via a little “parity‐and‐no‐repeat” recurrence.\n\n1. Let S={0,1,2,3,4,6,7,8,9}. |S|=9, of which 5 are even (E={0,2,4,6,8}) and 4 are odd (O={1,3,7,9}). \n2. We want 7‐digit strings d₁…d₇ with\n • d₁≠0 (so d₁ is one of the 4 nonzero evens or 4 odds), \n • dᵢ≠dᵢ₊₁ (no two consecutive the same), \n • d₁+d₇ even ⇔ d₇ has same parity as d₁.\n\nFix any particular initial digit of given parity and count how many length‑7 strings (with no two equal neighbors) end in an even digit vs. end in an odd digit. If we let\nEₜ = # of length‑t strings ending even,\nOₜ = # of length‑t strings ending odd,\nthen for t→t+1 the transitions are\n\n From an even‐ending you may choose one of the other 4 evens or one of the 4 odds, \n From an odd‐ending you may choose one of the 5 evens or one of the other 3 odds.\n\nHence\n Eₜ₊₁ = 4·Eₜ + 5·Oₜ \n Oₜ₊₁ = 4·Eₜ + 3·Oₜ.\n\nCase A) start even: (E₁,O₁)=(1,0) \n iterate up to t=7:\n (E₂,O₂)=(4,4)\n (E₃,O₃)=(36,28)\n (E₄,O₄)=(284,228)\n (E₅,O₅)=(2276,1820)\n (E₆,O₆)=(18204,14564)\n (E₇,O₇)=(145636,116508).\n\nSo for each of the 4 possible even d₁, there are 145 636 strings of length 7 ending even (and 116 508 ending odd). But since we need d₇ even to keep d₁+d₇ even, each even d₁ gives 145 636 valid strings. Total from even starts = 4·145 636 = 582 544.\n\nCase B) start odd: (E₁,O₁)=(0,1)\n similarly one finds\n (E₇,O₇)=(145635,116509).\n\nFor each of the 4 odd d₁ there are 116 509 strings ending odd ⇒ also d₁+d₇ even. Total from odd starts = 4·116 509 = 466 036.\n\nAdd them up:\n\n 582 544 + 466 036 = 1 048 580.\n\nAnswer: 1 048 580 valid 7‐digit IDs.", + "golden_answer":"7", + "source":"Bigmath_synth" + }, + { + "instruction":"A renowned artist prices her sculptures using a linear model. Let the price (in dollars) be \n  P(x) = k·x + b,\nwhere x denotes a “size‐rating” of the sculpture. For promotional reasons, the artist decides that the numbers 2k, 50, and b must form an arithmetic sequence.\n\n(a) Find the fixed point (x, P) that the pricing function P(x) always passes through, regardless of the value of k.\n\n(b) Later, to promote smaller sculptures, the gallery offers a revised pricing model \n  P(x) = k·(x – 4) + b′.\nIf the artist wishes this new model to continue passing through the fixed point found in part (a), express b′ in terms of k.\n\nExpress your answers clearly as an ordered pair for part (a) and a formula for b′ in part (b).", + "output":"(a) From 50 − 2k = b − 50 ⟹ b = 100 − 2k, so \r\n P(x) = kx + (100−2k) = k(x−2)+100, \r\nhence P(2)=100 for all k. \r\nFixed point: (2, 100).\r\n\r\n(b) Require k(2−4)+b′ = 100 ⟹ −2k + b′ = 100 ⟹ \r\n b′ = 100 + 2k.", + "golden_answer":"2", + "source":"Bigmath_synth" + }, + { + "instruction":"Consider the function \n  f(x) = 2x³ + a·x² + b·x + 6,\nwhich represents the net profit in thousands of dollars for a company that manufactures x thousand units. The company’s analysis shows that the profit reaches a stationary point at x = 1 (meaning f ′(1) = 0) and that the rate of change of the slope (i.e. the second derivative) at x = 1 is 10, so f ″(1) = 10. Determine the values of a and b.", + "output":"We have \n  f(x)=2x³ + a x² + b x +6 \nso \n  f′(x)=6x² +2a x + b \n  f″(x)=12x +2a. \n\n1. Stationary at x=1 ⇒ f′(1)=0 ⇒ 6·1² +2a·1 + b = 0 ⇒ 6 +2a + b = 0 ⇒ 2a + b = −6. \n2. f″(1)=10 ⇒ 12·1 +2a = 10 ⇒ 12 +2a = 10 ⇒ 2a = −2 ⇒ a = −1. \n3. Then 2(−1) + b = −6 ⇒ −2 + b = −6 ⇒ b = −4. \n\nAnswer:  a = −1,  b = −4.", + "golden_answer":"4", + "source":"Bigmath_synth" + }, + { + "instruction":"At a community center, organizers plan to prepare welcome kits for new members. Each kit is to contain a certain number of useful items. However, due to a special bonus, an extra 13 items are always added. The total number of items in a kit (the original useful items plus the bonus) must be exactly divisible by 7, 10, and 15. What is the smallest possible number of useful items (before adding the bonus) that each kit can have?", + "output":"First note that “x useful items + 13 bonus items” must be a multiple of 7, 10 and 15. Hence \r\nx + 13 ≡ 0 (mod 7, 10, 15) \r\n⇔ x + 13 ≡ 0 (mod lcm(7,10,15)) \r\n⇔ x + 13 ≡ 0 (mod 210). \r\n\r\nThe smallest positive solution is when x + 13 = 210, so \r\nx = 210 − 13 = 197.", + "golden_answer":"197", + "source":"Bigmath_synth" + }, + { + "instruction":"Roman and Sergei must travel from a train station to their office, which is 24 km away. They share one electric scooter. Roman starts from the station riding the scooter; his scooter speed is 20 km\/h and his walking speed is 6 km\/h. Sergei departs on foot; his walking speed is 7 km\/h and if he rides the scooter his speed rises to 30 km\/h. Roman will ride the scooter for x kilometers from the station and then leave it there and continue the rest of the journey on foot. When Sergei reaches that same point on his walk, he will take the scooter; however, before he can ride off, he must pause for 5 minutes (i.e. 1\/12 hour) to complete a mandatory safety check. After the pause, he will ride the scooter for the remainder of the trip. Find the distance x (with 0 < x < 24) from the station at which Roman should leave the scooter so that both arrive at the office simultaneously.", + "output":"Let x be the point (in km from the station) where Roman drops the scooter. \n\nRoman’s total time \nTR = (ride time) + (walk time) \n = x\/20 + (24 – x)\/6 \n = 4 + x·(1\/20 – 1\/6) \n = 4 – (7\/60)x. \n\nSergei’s total time \nTS = (walk to x) + (5 min safety check) + (scooter to 24) \n = x\/7 + 1\/12 + (24 – x)\/30 \n = x·(1\/7 – 1\/30) + (1\/12 + 24\/30) \n = (23\/210)x + 53\/60. \n\nSet TR = TS: \n 4 – (7\/60)x = (23\/210)x + 53\/60. \nMultiply both sides by 420 to clear denominators: \n 1680 – 49x = 46x + 371 \n⇒ 1680 – 371 = 95x \n⇒ x = 1309\/95 ≃ 13.78 km. \n\nSo Roman should leave the scooter about 13.78 km from the station.", + "golden_answer":"13.78", + "source":"Bigmath_synth" + }, + { + "instruction":"An investor receives returns from three separate accounts: $500, x dollars, and $1500. The average of these three returns is equal to x dollars. Later, due to an administrative fee, the return from the third account is reduced by 10% (so it becomes 0.9 × 1500). With this adjustment, the new average of the three returns is (x – 50) dollars. Find the value of x.", + "output":"Let the three returns be 500, x, 1500.\n\n1. Their original average is x:\n (500 + x + 1500)\/3 = x \n ⇒ (2000 + x) = 3x \n ⇒ 2000 = 2x \n ⇒ x = 1000.\n\n2. After a 10% fee on the third account, its return is 0.9·1500 = 1350. The new average is given as x – 50:\n (500 + x + 1350)\/3 = x – 50 \n Plug in x = 1000: \n (500 + 1000 + 1350)\/3 = 2850\/3 = 950 = 1000 – 50. \n\nBoth conditions agree when x = 1000.", + "golden_answer":"1000", + "source":"Bigmath_synth" + }, + { + "instruction":"During an 11‐day promotional period for a photo editing service, the standard fee charged each day (before any discount) forms an arithmetic sequence. On day 1 the fee is F dollars and each subsequent day the fee increases by r dollars. However, if on any day the standard fee is less than $30, a one‐time discount of $5 is applied to that day’s fee. It is given that the sum of the standard (undiscounted) fees on day 2, day 6, and day 9 is $97, and exactly 4 of the 11 days had standard fees below $30 (and so received the discount). Determine the total amount collected over the 11 days, after applying the discounts where appropriate.", + "output":"Let the (undiscounted) fee on day i be \n a_i = F + (i–1)·r. \nWe are given \n 1) a_2 + a_6 + a_9 = (F + r) + (F + 5r) + (F + 8r) = 3F + 14r = 97. \n 2) Exactly 4 of the 11 days satisfy a_i < 30, so \n a_4 = F + 3r < 30 ≤ a_5 = F + 4r. \n\nFrom 3F + 14r = 97 ⇒ F = (97 − 14r)\/3. The inequalities become \n (97−14r)\/3 + 3r < 30, \n (97−14r)\/3 + 4r ≥ 30. \nOne finds an integer‐solution pair F = 23, r = 2. Hence the undiscoun­ted daily fees are \n 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43. \nDays 1–4 have a_i < 30, so each of those 4 days gets a \\$5 discount. \n\nSum of the 11 undiscounted fees = (11\/2)·(23 + 43) = 363. \nTotal discounts = 4·5 = 20. \nAmount actually collected = 363 − 20 = \\$343.", + "golden_answer":"343", + "source":"Bigmath_synth" + }, + { + "instruction":"At a local community food drive, organizers initially prepared 150 meal kits. A local business later donated 40 additional meal kits. However, after a safety check, 10 of these meal kits were deemed unfit for distribution and removed. Now, after distributing some of the remaining valid meal kits, there are 100 still available. \na) How many valid meal kits have been given away so far? \nb) What percentage of the valid meal kits have been distributed?", + "output":"a) 80 meal kits \n Total valid kits = (150 + 40) − 10 = 180 \n Distributed = 180 − 100 = 80 \n\nb) % distributed = (80 ÷ 180) × 100 ≈ 44.44%", + "golden_answer":"44.44", + "source":"Bigmath_synth" + }, + { + "instruction":"A technology firm employs 50 software developers and 150 graphic designers. The management needs to form a project team of 40 members, with the team’s composition ideally reflecting the overall employee proportions. However, to ensure diverse technical input, the firm requires that at least 12 developers must be on the team. If the standard proportional (stratified) selection would yield fewer than 12 developers, the company will adjust the allocation so that exactly 12 developers are included while keeping the total team size at 40. Under these guidelines, how many developers will be on the team?", + "output":"Under the proportional rule you’d get \n Developers = 40 × (50\/200) = 10, \n Designers = 40 × (150\/200) = 30. \n\nBut since 10 < 12, the firm bumps developers up to exactly 12 (and correspondingly uses 28 designers) to keep the total at 40. \n\nAnswer: 12 developers.", + "golden_answer":"12", + "source":"Bigmath_synth" + }, + { + "instruction":"An irrigation canal on a farm is a rectangular open channel with a constant depth of 2.0 m, while its width (in meters) is unknown. Water flows through the canal at a constant speed of 2 km\/h. In addition, light rainfall adds an extra 10% to the base water flow, but an automatic diversion system simultaneously takes away 5% of the water for local irrigation. Taking into account these adjustments, the effective volume of water reaching the field is 330 cubic meters per minute. What is the width of the canal?\n\nTo solve, first note that 2 km\/h = (2\/3.6) m\/s ≈ 0.5556 m\/s. The base water flow rate in m³\/s is given by (width in m) × (2.0 m) × (0.5556 m\/s); converting to a per-minute rate requires multiplying by 60. Then, incorporate the net effect of the extra flow from rainfall and the diversion for irrigation.", + "output":"Let w be the canal width in m. Then\n\n1. Base flow rate Q₀ (m³\/s): \n Q₀ = w·depth·velocity = w·2.0·(2 km\/h in m\/s) \n = w·2.0·(2\/3.6) ≃ w·2.0·0.5556 = 1.1112 w (m³\/s)\n\n2. Convert to m³\/min: \n Q₀,min = Q₀·60 = 1.1112 w·60 = 66.672 w (m³\/min)\n\n3. Net adjustment for rainfall (+10%) and diversion (–5%): \n factor = 1.10·0.95 = 1.045 \n ⇒ effective flow Qₑ = Q₀,min·1.045\n\n4. Set Qₑ = 330 m³\/min and solve for w: \n 66.672 w·1.045 = 330 \n ⇒ w = 330\/(66.672·1.045) ≃ 4.74 m \n\nAnswer: The canal is about 4.7 m wide.", + "golden_answer":"", + "source":"Bigmath_synth" + }, + { + "instruction":"A scientist is modeling the reaction rate of a chemical process with the function R defined by\n\n  for x ≥ 0: R(x) = ax³ + bx − 7 \n  for x < 0: R(x) = ax³ + bx + 2\n\nIt is known that R(30) = 9. Determine:\n (a) The value of R(−30), and \n (b) What percentage R(−30) is of R(30).", + "output":"First note that \n R(30)=30³·a+30·b−7=27000 a+30 b−7=9 \n⇒27000 a+30 b=16. \n\n(a) For x=–30<0, \n R(−30)=a(−30)³+ b(−30)+2=−27000 a−30 b+2 \n =−(27000 a+30 b)+2=−16+2=−14. \n\n(b) As a percentage of R(30)=9, \n R(−30) is (−14\/9)·100 %≈−155.56 %.", + "golden_answer":"155.56", + "source":"Bigmath_synth" + }, + { + "instruction":"A parabolic arch for a pedestrian bridge is given by the equation\n  y = (x – 2)² + 4,\nwhere x and y are measured in meters. A supporting cable is to be fastened along the tangent to the arch at a point where the slope of the tangent is 1\/3.\n\na) Find the coordinates of the point on the arch where the tangent line has a slope of 1\/3.\n\nb) Determine the x-intercept of this tangent line.\n\nc) Calculate the length of the cable from the tangency point to its x-intercept.\n\n", + "output":"a) y′=2(x–2), so \n 2(x–2)=1\/3 ⇒ x–2=1\/6 ⇒ x=2+1\/6=13\/6. \nThen \n y=(13\/6–2)²+4=(1\/6)²+4=1\/36+4=145\/36. \nAnswer: (13\/6, 145\/36). \n\nb) Tangent line through (13\/6,145\/36) with slope 1\/3: \n y–145\/36=(1\/3)(x–13\/6). \nSet y=0 and solve for x: \n –145\/36=(1\/3)(x–13\/6) ⇒ x–13\/6=–3·(145\/36)=–145\/12 \n⇒ x=13\/6–145\/12=(26\/12–145\/12)=–119\/12. \nSo the x‑intercept is (–119\/12, 0). \n\nc) Distance from (13\/6,145\/36) to (–119\/12,0): \n Δx=13\/6–(–119\/12)=145\/12, Δy=145\/36–0=145\/36 \n⇒ length = √[(145\/12)²+(145\/36)²] \n =145·√[1\/144+1\/1296] \n =145·√[10\/1296] \n = (145\/36)√10 ≈12.73 m.", + "golden_answer":"12.73", + "source":"Bigmath_synth" + }, + { + "instruction":"Consider a line with equation y = –3x + k, where k is a constant. First, the line is shifted vertically downward by 4 units. Then, a horizontal shift is applied as follows:\n • If k > 0, the line is shifted 2 units to the right.\n • If k ≤ 0, the line is shifted 2 units to the left.\nExpress the final equation of the line in slope–intercept form (y = mx + b) in terms of k, clearly indicating the answer for both cases.", + "output":"First shift down by 4: \ny = –3x + k – 4\n\nThen\n\n• If k>0, shift right 2 ⇒ replace x by (x–2): \n  y = –3(x–2) + (k–4) = –3x +6 + k –4 = –3x + (k +2)\n\n• If k≤0, shift left 2 ⇒ replace x by (x+2): \n  y = –3(x+2) + (k–4) = –3x –6 + k –4 = –3x + (k –10)\n\nAnswer: \n  For k>0: y = –3x + (k + 2) \n  For k≤0:   y = –3x + (k –10)", + "golden_answer":"10", + "source":"Bigmath_synth" + }, + { + "instruction":"In a Cartesian coordinate system, let the function F(x) be defined as the reflection of the function y = 3^(x + 1) about the line y = x. Next, define the function H(x) as the reflection of F(x) about the vertical line x = 2. If it is given that H(r) = 5, determine the value of r.\n\nTo solve the problem, note that reflecting y = 3^(x + 1) about the line y = x produces the inverse function. That is, if y = 3^(x + 1), then after interchanging x and y we have x = 3^(y + 1); solving for y yields F(x) = log₃(x) – 1. Next, reflect F(x) about the vertical line x = 2. Reflection about a vertical line x = a transforms the function into F(2 – x). Therefore, H(x) = F(2 – x) = log₃(2 – x) – 1.\n\nWe are given H(r) = 5, so:\n\n  log₃(2 – r) – 1 = 5\n\nAdding 1 to both sides gives:\n\n  log₃(2 – r) = 6\n\nConverting the logarithmic equation to exponential form:\n\n  2 – r = 3⁶ = 729\n\nThus, solving for r we get:\n\n  r = 2 – 729 = –727\n\nSo, the value of r is –727.", + "output":"First, note that reflecting y=F(x) about the vertical line x=2 sends each point (u,v) on y=F(x) to the point (2·2 − u, v)=(4−u, v). Equivalently, the new function H satisfies \n H(x)=F(4−x). \n\nWe already have \n F(x)=inverse of y=3^(x+1) ⇒ F(x)=log₃(x)−1. \n\nHence \n H(x)=F(4−x)=log₃(4−x)−1. \n\nNow impose H(r)=5: \n log₃(4−r)−1=5 \n⇒ log₃(4−r)=6 \n⇒ 4−r=3⁶=729 \n⇒ r=4−729=−725. \n\nAnswer: r=−725.", + "golden_answer":"725", + "source":"Bigmath_synth" + }, + { + "instruction":"At a charity sale, three booths sold tickets. Booth A sold 60 tickets. Booth B sold 30 more tickets than Booth A, and Booth C sold 15 tickets more than Booth B. The overall average number of tickets sold by the three booths was 85. In addition, a bonus is awarded if booth C’s ticket count is exactly 20% more than the overall average; otherwise, no bonus is given. Determine whether the bonus condition is met, and find how many more tickets booth B sold compared to booth A.", + "output":"The three booths sold \n• A = 60 tickets \n• B = A + 30 = 90 tickets \n• C = B + 15 = 105 tickets \n\nTheir average is (60 + 90 + 105)\/3 = 85, as stated. \n20% above that average is 85 × 1.20 = 102, which is not equal to C’s 105 tickets, so no bonus is awarded. \nBooth B sold 90 − 60 = 30 more tickets than Booth A.", + "golden_answer":"30", + "source":"Bigmath_synth" + }, + { + "instruction":"A gourmet chocolate workshop produced a batch of truffles. The chocolatier first set aside 16 truffles made with a special dark chocolate filling. He then divided the remaining truffles into two varieties—hazelnut and caramel—in the ratio 3:2. However, due to a recipe adjustment, if the number of caramel truffles (from the initial split) is even, he removes 4 truffles from the hazelnut group; if it is odd, he adds 4 truffles to the hazelnut group. After this adjustment, the hazelnut truffles exceed the caramel truffles by exactly 108. What is the total number of truffles produced?\n\n", + "output":"Let the total number of truffles be N. \n1. He sets aside 16 special‐dark truffles, leaving N–16 to split. \n2. Splitting the remaining N–16 in a 3:2 ratio gives \n hazelnut = 3k, \n caramel = 2k, \n where 5k = N–16. \n3. Since 2k is always even, he removes 4 from hazelnut: \n adjusted hazelnut = 3k – 4, \n adjusted caramel = 2k. \n4. We’re told (3k – 4) – 2k = 108 ⇒ k – 4 = 108 ⇒ k = 112. \n5. Hence N – 16 = 5·112 = 560 ⇒ N = 576. \n\nAnswer: The workshop produced 576 truffles in all.", + "golden_answer":"576", + "source":"Bigmath_synth" + }, + { + "instruction":"At a company charity event, Team Alpha raised $150 while Team Beta raised $360. Team Beta had 8 more members than Team Alpha. If the average donation per member from Team Alpha was exactly 50% of that from Team Beta, how many members were on Team Alpha?", + "output":"Let x = number of Alpha members. Then Beta has x+8 members.\n\nAverage per Alpha member = 150\/x. \nAverage per Beta member = 360\/(x+8).\n\nWe’re told \n 150\/x = ½ · [360\/(x+8)] \n⇒ 150\/x = 180\/(x+8) \n⇒ 150(x+8) = 180x \n⇒ 150x + 1200 = 180x \n⇒ 1200 = 30x \n⇒ x = 40.\n\nAnswer: Team Alpha had 40 members.", + "golden_answer":"40", + "source":"Bigmath_synth" + }, + { + "instruction":"A technology firm needs to order USB drives for an upcoming conference. Every attendee must receive at least 25 drives, and the total order must include at least 470 drives. The drives are sold in two types of packs: standard packs and premium packs. Each standard pack contains 15 drives, and because of storage constraints the firm may purchase no more than 3 standard packs. Premium packs contain an unknown number of drives, but each premium pack holds exactly 5 more drives than a standard pack. Knowing that even when buying the maximum allowed 3 standard packs the firm must purchase at least 22 premium packs to meet the minimum drive count, determine how many drives are in one premium pack.", + "output":"Let s = 15 (standard‐pack size) and p = premium‐pack size. We know:\n\n 1. Even with the maximum 3 standard packs, you need at least 22 premium packs to reach 470 drives:\n 3·s + 22·p ≥ 470 \n 2. But 21 premium packs would fall short:\n 3·s + 21·p < 470 \n\nPlugging in s = 15:\n\n 3·15 + 22·p ≥ 470 ⇒ 45 + 22p ≥ 470 ⇒ 22p ≥ 425 ⇒ p ≥ 19.318… \n 3·15 + 21·p < 470 ⇒ 45 + 21p < 470 ⇒ 21p < 425 ⇒ p < 20.238…\n\nSince p must be an integer, p = 20. Hence each premium pack contains 20 drives.", + "golden_answer":"20", + "source":"Bigmath_synth" + }, + { + "instruction":"A construction crew is tasked with painting 30 houses. The team includes 5 junior painters, 3 mid-level painters, and 2 senior painters. On a clear day, a junior painter can finish painting 1 house in 6 days, a mid-level painter can do it in 8 days, and a senior painter in 3 days. However, on rainy days (which occur 40% of the time), each painter works 30% slower than usual. Assuming the painters work simultaneously every day, how many total days will it take the crew to complete painting all 30 houses?", + "output":"First, compute each painter’s “clear‐day” rate (in houses per day):\n\n• Junior: 1 house \/ 6 days ⇒ 1\/6 ≃ 0.1667 \n• Mid‑level: 1\/8 = 0.125 \n• Senior: 1\/3 ≃ 0.3333 \n\nWith 5 juniors, 3 mids and 2 seniors the crew’s combined clear‐day rate R₀ is\n\n R₀ = 5·(1\/6) + 3·(1\/8) + 2·(1\/3)\n = 5\/6 + 3\/8 + 2\/3\n = 20\/24 + 9\/24 + 16\/24\n = 45\/24\n = 15\/8\n = 1.875 houses\/day.\n\nOn a rainy day each painter is 30% slower ⇒ works at 70% of normal rate. Rainy days occur 40% of the time, clear days 60%. Hence the expected (long‐run average) daily rate R is\n\n R = 0.6·R₀ + 0.4·(0.7·R₀)\n = R₀·[0.6 + 0.4·0.7]\n = R₀·(0.6 + 0.28)\n = R₀·0.88\n = 1.875·0.88\n = 1.65 houses\/day (on average).\n\nTo paint 30 houses at 1.65 houses\/day takes\n\n T = 30 ÷ 1.65 ≃ 18.18 days.\n\nSince you can’t stop mid‐day for “partial days,” you’d need about 19 calendar days. \n\nAnswer: Approximately 18.2 days of work on average, so in practice about 19 days.", + "golden_answer":"19", + "source":"Bigmath_synth" + }, + { + "instruction":"A factory has three teams—Team A, Team B, and Team C—that together can package 360 items in 6 hours. It is known that Team A, working alone, can complete the packaging in 18 hours and Team B in 12 hours. However, when working on their own, Team C spends half of their working time performing extra quality checks that slow their production to 50% of their normal speed, while the other half they work at full speed. If Team C were able to work continuously at their full (normal) speed without the slowdown, how many hours would they need to package all 360 items on their own?", + "output":"Let \n A’s rate = 360 items⁄18 h = 20 items\/h \n B’s rate = 360⁄12 = 30 items\/h \n All three together do 360 items in 6 h ⇒ combined rate = 360⁄6 = 60 items\/h \n\nSo C’s actual (averaged) rate in that mix is \n 60 – (20 + 30) = 10 items\/h \n\nBut when C works “normally,” they run at some rate r. On their own they spend half the time at full speed r and half the time at 50% speed (0.5 r), so their average rate is \n (r + 0.5 r)\/2 = 0.75 r \n\nWe know 0.75 r = 10 ⇒ r = 10 \/ 0.75 = 40\/3 ≈ 13.333 items\/h \n\nAt that full‐speed rate it would take them \n time = 360 items ÷ (40\/3 items\/h) = 360×(3\/40) = 27 hours.", + "golden_answer":"27", + "source":"Bigmath_synth" + }, + { + "instruction":"In a charity fundraising marathon lasting 8 hours, three teams compete to set a new record for total funds raised. Currently, Kevin’s team holds the record by raising exactly $6,400 during the event.\n\nTeam Alan aims to break this record. Without any additional boost, they start by raising $900 in hour 1 but then experience donor fatigue so that in each subsequent hour they raise $100 less than in the previous hour (i.e. $900 in hour 1, $800 in hour 2, $700 in hour 3, and so on through hour 8). To help overcome this fatigue, Team Alan can secure a sponsorship bonus—an additional one‐time extra amount added only during the first hour. They want to know how much extra they must raise in hour 1 (via the bonus) so that their total over the 8 hours exceeds both Kevin’s record and the total raised by Team Lisa.\n\nTeam Lisa follows a different strategy. In the first 4 hours she raises funds at a steady rate of $1,000 per hour; then for the remaining 4 hours she doubles that rate with an aggressive campaign (i.e. $2,000 per hour).\n\n(a) Find the minimum sponsorship bonus (extra funds added only in hour 1) that Team Alan must secure so that, with their diminishing hourly donations, their 8‑hour total exceeds both Kevin’s $6,400 and Team Lisa’s total.\n\n(b) In a modified scenario, suppose that during the final 3 hours Team Alan implements a targeted outreach program that lessens donor fatigue; in those hours the reduction is only $50 per hour rather than $100. (Hours 1–5 follow the original pattern, while for hours 6–8 the decrease is milder.) Under this new plan, determine the revised minimum sponsorship bonus required in hour 1 so that Team Alan’s total funds raised in 8 hours beat both competitors’ totals.\n\nSolve each part by first computing the totals without the bonus and then determining the extra funds needed in hour 1 to exceed the higher of Kevin’s and Lisa’s totals.", + "output":"Here is the quick “by‐the‐numbers” check for each part. In every case Lisa’s total (12 000) is above Kevin’s 6 400, so Alan really only has to beat 12 000.\n\n(a) Original fatigue pattern \n– Alan’s hours 1–8 (no bonus): 900, 800, 700, 600, 500, 400, 300, 200. \n Sum = (900+200)·8\/2 = 1 100·4 = 4 400. \n– Lisa’s total = 4×1 000 + 4×2 000 = 4 000 + 8 000 = 12 000. \n– With a one‐time bonus B in hour 1, Alan’s total = 4 400 + B. To exceed Lisa: \n 4 400 + B > 12 000 ⇒ B > 7 600. \nMinimum integer‐dollar bonus = \\$7 601.\n\n(b) Reduced fatigue in hours 6–8 \n– Alan’s hours 1–5 as before: 900,800,700,600,500 (sum = 3 500); \n then only –\\$50\/hr in 6–8: 450, 400, 350 (sum = 1 200). \n Total without bonus = 3 500 + 1 200 = 4 700. \n– Lisa still = 12 000. \n– With bonus B: 4 700 + B > 12 000 ⇒ B > 7 300. \nMinimum integer‐dollar bonus = \\$7 301.", + "golden_answer":"301", + "source":"Bigmath_synth" + }, + { + "instruction":"A community contest awards a total prize of $60. Initially, the prize is to be divided evenly among 5 contestants. However, if one contestant withdraws before the announcement, the prize will be redistributed evenly among the remaining contestants. \n\n(a) What is the amount each contestant receives when all 5 participate? \n(b) What is the amount each contestant receives if one contestant withdraws?", + "output":"(a) \\$60 ÷ 5 = \\$12 per contestant \n(b) \\$60 ÷ 4 = \\$15 per contestant", + "golden_answer":"15", + "source":"Bigmath_synth" + }, + { + "instruction":"Jenna participates in a fundraising race consisting of two segments. In the first segment, she runs for 3 hours at a speed of 5 miles per hour. In the second segment, she rides her bicycle for half as long as her running time. For the first hour of cycling, she rides at a speed equal to 4 times her running speed; however, during the final 30 minutes of cycling, heavy wind forces her to reduce her cycling speed by 20%. What is the total distance Jenna covers in the race?", + "output":"First segment (running): \n• Time = 3 h, Speed = 5 mph ⇒ Distance = 3·5 = 15 mi \n\nSecond segment (cycling): \n• Total cycling time = ½·3 h = 1.5 h \n• First 1 h at 4·5 mph = 20 mph ⇒ 1·20 = 20 mi \n• Final 0.5 h at 20·0.8 = 16 mph ⇒ 0.5·16 = 8 mi \n\nTotal distance = 15 + 20 + 8 = 43 miles.", + "golden_answer":"43", + "source":"Bigmath_synth" + }, + { + "instruction":"A 400‐meter long light rail train approaches two different zones at a constant speed. When crossing a station platform, it takes 45 seconds for the entire train to clear the platform. Later, while crossing a maintenance area that is 80 meters long, safety protocols require the train to reduce its speed by 10%, and it takes 50 seconds for the train to clear that area. \n (a) What is the length of the station platform? \n (b) What is the train’s original speed (in m\/s) before any reduction?", + "output":"Let v be the train’s original speed (in m\/s) and L the platform length. \n\n1. Crossing the platform (length L) at speed v takes 45 s. During that time the train’s front must go a distance L+400, so \n 45·v = L + 400. (1) \n\n2. Crossing the 80 m maintenance zone at 0.9 v takes 50 s. There the train’s front goes 80+400 = 480 m, so \n 50·(0.9 v) = 480 \n ⇒ 45 v = 480 \n ⇒ v = 480\/45 = 32\/3 ≃ 10.67 m\/s. \n\nPlugging into (1): \n L + 400 = 45·(32\/3) = 480 \n ⇒ L = 480 – 400 = 80 m. \n\nAnswer: \n(a) 80 m \n(b) v = 32\/3 ≃ 10.67 m\/s.", + "golden_answer":"10.67", + "source":"Bigmath_synth" + }, + { + "instruction":"A wooden cube is carved from a log. When its side length is increased by 1 centimeter, the cube’s volume increases by 127 cubic centimeters. What is the side length (in centimeters) of the original cube?", + "output":"Let the original side length be x. Then the increase in volume when the side is x+1 is\n\n(x+1)³ – x³ = 3x² + 3x + 1 = 127.\n\nSo\n3x² + 3x + 1 = 127 \n3x² + 3x – 126 = 0 \nx² + x – 42 = 0 \n(x + 7)(x – 6) = 0\n\nThe positive solution is x = 6. Thus the original cube’s side is 6 cm.", + "golden_answer":"6", + "source":"Bigmath_synth" + }, + { + "instruction":"A toy designer is planning to create 2 identical robot sets. He currently has 360 components but still needs 120 more components to complete both sets. In each robot set, 25% of the components will be painted a special color for branding. The extra components are available only in packs of 15. Determine:\n(a) the total number of components required for one robot set,\n(b) the number of components in one set that will be painted,\n(c) how many packs must be purchased to obtain the extra components.", + "output":"Here’s the step‑by‑step solution:\n\n1. Total components needed for both sets \n Currently on hand = 360 \n Still needed = 120 \n ⇒ Total needed = 360 + 120 = 480 \n\n2. (a) Components per set \n 480 components ÷ 2 sets = 240 components per set \n\n3. (b) Painted components per set \n 25% of 240 = 0.25·240 = 60 components \n\n4. (c) Packs to purchase \n Needed extras = 120 components (for both sets) \n Pack size = 15 components \n 120 ÷ 15 = 8 packs \n\nAnswer: \n(a) 240 \n(b) 60 \n(c) 8", + "golden_answer":"8", + "source":"Bigmath_synth" + }, + { + "instruction":"During a fundraising event, the organizers announced a matching scheme: for every dollar a supporter donates, the organizers will contribute 5 times that amount. Before any new donation, the event had already raised $100 from other sources. Later that day, donor Emily makes a contribution, and after her donation the organizers apply the matching funds; then a benefactor adds an extra $20. If the overall total (the initial $100, plus Emily’s donation, plus the matching funds, plus the extra $20) exactly equals the maximum matching amount available (which is 5 times Emily’s contribution), how many dollars did Emily donate?", + "output":"Let x be the amount Emily gives. The total on the day is\n\n “initial \\$100” + “Emily’s x” + “matching (5×x)” + “extra \\$20.” \n\nAccording to the problem statement that sum is supposed to equal the maximum match available, which is 5 x. In symbols\n\n 100 + x + 5x + 20 = 5x\n⟹ 120 + 6x = 5x\n⟹ 6x − 5x = −120\n⟹ x = −120.\n\nNo positive dollar‐amount satisfies this. Formally you get x = −\\$120, so there is no possible positive donation that makes the story work as stated.", + "golden_answer":"120", + "source":"Bigmath_synth" + }, + { + "instruction":"At a clothing store, there were 30 pairs of designer shoes and one‐third as many pairs of sneakers. The store also stocked boots equal in number to twice the sum of the designer shoes and sneakers. During a clearance sale, all the designer shoes stayed on the floor while only 80% of the sneakers and 90% of the boot pairs remained unsold. How many pairs of shoes did the store have after the sale?", + "output":"First, compute the initial stock:\n\n• Designer shoes: 30 pairs \n• Sneakers: one‐third as many as designer ⇒ (1\/3)·30 = 10 pairs \n• Boots: twice the sum of designer and sneakers ⇒ 2·(30+10) = 80 pairs \n\nTotal initially = 30 + 10 + 80 = 120 pairs.\n\nAfter the sale, the unsold stock is:\n\n• Designer shoes: all 30 remain \n• Sneakers: 80% of 10 = 8 remain \n• Boots: 90% of 80 = 72 remain \n\nTotal remaining = 30 + 8 + 72 = 110 pairs.", + "golden_answer":"110", + "source":"Bigmath_synth" + }, + { + "instruction":"Consider a rectangular box with positive side lengths a, b, and c. For each face meeting at one vertex, define its diagonal (using the Pythagorean theorem) so that\n\n  d₁ = √(a² + b²),\n  d₂ = √(a² + c²), and\n  d₃ = √(b² + c²).\n\nA new box is built whose side lengths are d₁, d₂, and d₃. Find the maximum possible value of the ratio\n\n  (New box’s volume)⁄(Original box’s volume) = [√((a² + b²)(a² + c²)(b² + c²)]⁄(abc),\n\nand determine for which a, b, c this maximum is attained.", + "output":"First we observe by the AM–GM inequality that for any positive a,b,c\n\n (a² + b²)(b² + c²)(c² + a²) ≥ (2ab)(2bc)(2ca) = 8 a²b²c². \n\nTaking square‐roots gives\n\n √[(a² + b²)(b² + c²)(c² + a²)] ≥ 2√2 a b c,\n\nso\n\n R(a,b,c) = √[(a² + b²)(b² + c²)(c² + a²)] \/ (a b c) ≥ 2√2,\n\nwith equality if and only if a = b = c. Thus the ratio is **at least** 2√2, and the **minimum** value 2√2 occurs exactly at the cube a = b = c.\n\nOn the other hand one checks easily that if, say, c→0⁺ (while a,b stay fixed) then\n\n R(a,b,c) ≃ √[(a²+b²)·a²·b²] \/ (a b c) = √(a²+b²) \/ c → +∞.\n\nHence there is no finite **maximum**—the ratio can be made arbitrarily large by “flattening’’ the box. \n\nSummary:\n\n• Infimum of R = 2√2, attained at a = b = c. \n• Supremum of R = +∞ (no finite maximum).", + "golden_answer":"2", + "source":"Bigmath_synth" + }, + { + "instruction":"A chef originally had an unknown number of fresh vegetables. Unfortunately, half of these vegetables spoiled before the day’s service. In order to have enough for the day, the chef purchased 15 times as many vegetables as had spoiled, paying $0.80 per vegetable. After the purchase, the chef had a total of 1600 vegetables. Determine (a) how many vegetables the chef originally had and (b) the total cost of the newly purchased vegetables.", + "output":"Let the original number be x. \n• Spoiled: ½ x \n• Remaining: ½ x \n• Purchased: 15·(½ x)=15x\/2 \nAfter purchase the total is \n ½ x + 15x\/2 = (1+15)·x\/2 = 8x = 1600 \n⇒ x = 200. \n\n(a) Originally 200 vegetables. \n(b) Purchased 15·(200\/2)=1,500 at \\$0.80 each ⇒ 1,500·0.80 = \\$1,200.", + "golden_answer":"1200", + "source":"Bigmath_synth" + }, + { + "instruction":"Let a and b be real numbers satisfying\n  a² + b² = 10  and  a + b = 4.\nAssume that the expression\n  E = ∛{a(2b – 6)} + √[(a + 2)(b – 2)]\nis defined as a real number. Determine E and express your answer in simplest radical form.", + "output":"First note that from \n a + b = 4 ⇒ (a + b)² = 16 \nand \n a² + b² = 10, \nwe get \n (a + b)² = a² + b² + 2ab \n⇒ 16 = 10 + 2ab \n⇒ ab = 3. \nHence a and b are the roots of t² − 4t + 3 = 0, namely {1, 3}. \n\nWe must have (a+2)(b−2) ≥ 0 for the square‐root to be real. Checking the two orderings: \n• If (a,b) = (1,3), \n a(2b−6) = 1·(6−6) = 0 ⇒ ∛(0) = 0, \n (a+2)(b−2) = 3·1 = 3 ⇒ √3. \n So E = 0 + √3 = √3. \n\n• If (a,b) = (3,1), \n (a+2)(b−2) = 5·(−1) < 0, so the square‐root is not real. \n\nThus the only real value of E is √3.", + "golden_answer":"3", + "source":"Bigmath_synth" + }, + { + "instruction":"A coffee shop normally serves lattes and espressos in the ratio 6:4. On a weekend morning, a special promotion causes latte orders to increase by 25% while espresso orders drop by 20%. \n\na) Determine the new ratio of latte orders to espresso orders and express the number of latte orders as a percent of the total orders on that morning. \n\nb) If the shop typically serves 50 espressos on a regular morning, calculate the expected total number of orders (lattes plus espressos) on the weekend morning.", + "output":"a) \nLet the normal numbers be 6k lattes and 4k espressos. \n– Weekend lattes = 6k·1.25 = 7.5k \n– Weekend espressos = 4k·0.80 = 3.2k \n\nNew ratio latte : espresso = 7.5k : 3.2k = 7.5 : 3.2 = 75 : 32 \n\nPercent lattes of total = \n (7.5k) \/ (7.5k + 3.2k) × 100% \n= 7.5 \/ 10.7 × 100% ≈ 70.09% \n\nb) \nTypically 4k = 50 ⇒ k = 12.5. \n– New lattes = 7.5·12.5 = 93.75 (≈94) \n– New espressos = 3.2·12.5 = 40 \nTotal ≈ 93.75 + 40 = 133.75 ≈ 134 orders.", + "golden_answer":"134", + "source":"Bigmath_synth" + }, + { + "instruction":"Let F = log₆[(216^(1\/3))\/6] + log₄ 64 + 13^(1 + log₁₃ 3) + ln(√(e⁸)). Define K = F – 20. \n\na) Compute the exact value of F. \n\nb) Then, using the value of K, determine Q according to the following rules:\n  • If K ≥ 15, then Q = 2K.\n  • If 5 ≤ K < 15, then Q = K\/2.\n  • If K < 5, then Q = K².\n\nFind the value of Q.", + "output":"a) Simplify term by term:\n\n1. log₆[(216^(1\/3))\/6] \n 216^(1\/3)=6 ⇒ (6)\/6=1 ⇒ log₆1=0.\n\n2. log₄64 \n 4³=64 ⇒ log₄64=3.\n\n3. 13^(1+log₁₃3) \n =13¹·13^(log₁₃3)=13·3=39.\n\n4. ln(√(e⁸)) \n √(e⁸)=e⁴ ⇒ ln(e⁴)=4.\n\nHence F=0+3+39+4=46.\n\nb) K=F–20=46–20=26. Since K≥15, Q=2K=2·26=52.", + "golden_answer":"52", + "source":"Bigmath_synth" + }, + { + "instruction":"A container has three distinct positive dimensions x, y, and z (in centimeters). They satisfy\n\n  (1) x + 2y + 3z = 18,\n  (2) (1\/x) + [1\/(2y)] + [1\/(3z)] = 1\/3,\n  (3) x · y · z = 6.\n\nDetermine the values of x, y, and z. (In your solution, carefully note that x, y, and z must all be positive.)", + "output":"First, introduce new variables\n\n a = x, \n b = 2y, \n c = 3z. \n\nIn these terms the three equations become\n\n(1)   a + b + c = 18, \n(2)   1\/a + 1\/b + 1\/c = 1\/3, \n(3)   a b c = x·(2y)·(3z) = 6·(xyz) = 6·6 = 36. \n\nFrom (2) and (3) we get\n\n 1\/a + 1\/b + 1\/c = (ab+bc+ca)\/(abc) = (ab+bc+ca)\/36 = 1\/3 \n⟹ ab + bc + ca = 12. \n\nThus the elementary symmetric sums of a,b,c are\n\n S₁ = a+b+c = 18, \n S₂ = ab+bc+ca = 12, \n S₃ = abc = 36. \n\nHence a,b,c are the roots of the cubic\n\n t³ − S₁ t² + S₂ t − S₃ = t³ − 18 t² + 12 t − 36 = 0. \n\nOne checks (e.g. by computing the standard cubic discriminant) that this polynomial has exactly one real root and two nonreal roots. Consequently it is impossible for a, b, c to all be real—and hence impossible for x=a, y=b\/2, z=c\/3 to be three positive real numbers.\n\nConclusion: there is no solution in positive real numbers x,y,z.", + "golden_answer":"3", + "source":"Bigmath_synth" + }, + { + "instruction":"A shipping container has interior dimensions 150 cm (width) × 120 cm (depth) × 200 cm (height). A manufacturer packages products in identical rectangular boxes measuring 30 cm × 40 cm × 50 cm. For safety reasons the boxes must be loaded so that the 50‐cm side is always vertical.\n\n(a) Determine the maximum number of boxes that can be loaded into the container under these conditions.\n\n(b) In a revised plan, an access aisle is required that takes up 5% of the container’s base area, reducing the available floor space for boxes. Assuming the boxes still must have the 50‐cm side vertical and that the boxes are arranged in a grid using their 30 cm × 40 cm faces as the base, find the new maximum number of boxes that can be loaded into the container.\n", + "output":"Let H be the vertical direction of the container (200 cm) and the boxes must stand so that their 50 cm‐edge is in the H–direction. Hence in each “stack” you can pile up at most \n ⌊200\/50⌋ = 4 \nboxes one on top of another. What remains is to see how many stacks you can put on the floor.\n\n(a) Floor‐packing without an aisle \nContainer floor: 150 cm × 120 cm. Box base: 30 cm × 40 cm. You try the two orientations:\n\n 1. 30 cm–edge along the 150 cm side, 40 cm–edge along the 120 cm side: \n ⌊150\/30⌋ = 5 along the width, \n ⌊120\/40⌋ = 3 along the depth, \n ⇒ 5×3 = 15 stacks.\n\n 2. 40 cm–edge along the 150 cm side, 30 cm–edge along the 120 cm side: \n ⌊150\/40⌋ = 3, \n ⌊120\/30⌋ = 4, \n ⇒ 3×4 = 12 stacks.\n\nThe best is 15 stacks. Since you can stack 4 high, total boxes = 15×4 = 60.\n\n(b) Now 5% of the floor area is taken by the aisle. \n Original floor‐area = 150×120 = 18 000 cm². \n Available for boxes = 0.95·18 000 = 17 100 cm². \n Each stack occupies 30×40 =1 200 cm² of floor. \n So the maximum number of stacks on the floor is \n ⌊17 100 \/ 1 200⌋ = ⌊14.25⌋ = 14. \n Again 4 high ⇒ 14×4 = 56 boxes.", + "golden_answer":"56", + "source":"Bigmath_synth" + }, + { + "instruction":"A company’s pricing department uses a “discount factor” computed from two customer‐feedback logs. For a product priced at p dollars (with p > 6 to keep all expressions well defined), the original discount factor is defined as\n\n  D = log₄[(7p + 3)\/(2p + 5)] + log₄[(2p + 5)\/(p + 6)].\n\n(a) If D = 1, find the value of p.\n\nIn a revised scheme the second term is given half weight so that the new discount factor is\n\n  D′ = log₄[(7p + 3)\/(2p + 5)] + (½)·log₄[(2p + 5)\/(p + 6)].\n\n(b) If D′ = 1, determine p (express your answer in exact form).\n\n", + "output":"a) Since \n D = log₄[(7p+3)\/(2p+5)] + log₄[(2p+5)\/(p+6)] \n = log₄[ (7p+3)\/(p+6) ] \nsetting D=1 gives \n (7p+3)\/(p+6) = 4 \n⇒ 7p+3 = 4p+24 \n⇒ 3p = 21 \n⇒ p = 7. \n\nb) Now \n D′ = log₄[(7p+3)\/(2p+5)] + ½ log₄[(2p+5)\/(p+6)] \n = log₄ { (7p+3)\/(2p+5) · √[(2p+5)\/(p+6)] } \nSetting D′=1 gives \n (7p+3) ( (2p+5)\/(p+6) )¹\/2 = 4. \nSquaring both sides: \n (7p+3)² \/ [ (2p+5)(p+6) ] = 16 \n⇒ (7p+3)² = 16(2p+5)(p+6) \n⇒ 49p²+42p+9 = 32p²+272p+480 \n⇒ 17p² −230p −471 = 0. \nThe quadratic formula yields \n p = [230 ± √(230² +4·17·471)]\/(2·17) \n  = [230 ± 8√1327]\/34 \n  = [115 ± 4√1327]\/17. \nSince p>6, we take the “+’’ sign: \n p = (115 + 4√1327)\/17.", + "golden_answer":"17", + "source":"Bigmath_synth" + }, + { + "instruction":"In an academic competition, each contestant earns points from two rounds. In Round 1, a contestant scores 1\/3 of the contest’s maximum points, and in Round 2, they score 1\/4 of the maximum points. Additionally, if they solve an extra challenge, they receive a bonus of 1\/6 of the maximum points. Given that the maximum score is 240 points, determine the total score a contestant would have if (a) they do not solve the extra challenge and (b) they do solve the extra challenge.", + "output":"First note that “the maximum score” is 240 points. Then\n\nRound 1 score = (1\/3)·240 = 80 \nRound 2 score = (1\/4)·240 = 60 \nExtra‐challenge bonus = (1\/6)·240 = 40\n\na) Without the extra challenge: \n Total = 80 + 60 = 140\n\nb) With the extra challenge: \n Total = 80 + 60 + 40 = 180", + "golden_answer":"180", + "source":"Bigmath_synth" + }, + { + "instruction":"Carlos is comparing two yogurt brands during a weekend promotion. Brand X offers a box of 14 plain yogurts for $7, with each yogurt providing 110 calories. Brand Y sells a box of 6 flavored yogurts for $4, with each yogurt containing 210 calories; however, because of the weekend promotion, each Brand Y yogurt gets an extra 20 calories from added fruit toppings. If Carlos buys one box of each brand during the weekend, how many more calories per dollar does Brand Y provide than Brand X?", + "output":"First, compute each brand’s calories per dollar:\n\n1. Brand X \n‑ Total calories = 14 yogurts × 110 cal = 1540 cal \n‑ Cost = \\$7 \n‑ Calories per dollar = 1540 cal ÷ \\$7 = 220 cal\/\\$\n\n2. Brand Y (with weekend bonus) \n‑ Calories per yogurt = 210 cal + 20 cal = 230 cal \n‑ Total calories = 6 yogurts × 230 cal = 1380 cal \n‑ Cost = \\$4 \n‑ Calories per dollar = 1380 cal ÷ \\$4 = 345 cal\/\\$\n\nDifference: 345 cal\/\\$ − 220 cal\/\\$ = 125 cal\/\\$\n\nAnswer: Brand Y provides 125 more calories per dollar than Brand X.", + "golden_answer":"125", + "source":"Bigmath_synth" + }, + { + "instruction":"Circle A is given by\n  x² + y² – 6x – 8y + p = 0,\nand Circle B by\n  (x – 2)² + (y – 1)² = 4.\n(a) If the two circles have exactly three common tangents, then they are externally tangent. (Recall that two disjoint circles normally have four common tangents; when they touch externally the tangent at the point of contact is unique so that there are three in all.) Let the center and radius of Circle A be C₁ = (3,4) and r₁ = √(25 – p), and those of Circle B be C₂ = (2,1) and r₂ = 2.\nThe distance between the centers is\n  d = √[(3 – 2)² + (4 – 1)²] = √(1 + 9) = √10.\nFor external tangency we must have\n  r₁ + r₂ = d  ⟹  √(25 – p) + 2 = √10.\nSolve for √(25 – p):\n  √(25 – p) = √10 – 2.\nSquaring both sides gives\n  25 – p = (√10 – 2)² = 10 – 4√10 + 4 = 14 – 4√10.\nThus,\n  p = 25 – (14 – 4√10) = 11 + 4√10.\n\n(b) The circumference of Circle A is\n  C_A = 2π·√(25 – p) = 2π·(√10 – 2),\nwhile that of Circle B is\n  C_B = 2π·2 = 4π.\nWe wish to find the percentage by which the circumference of Circle B exceeds that of Circle A. In other words, compute\n  [(C_B – C_A) \/ C_A] × 100%.\nSubstitute the expressions:\n  [(4π – 2π(√10 – 2)) \/ (2π(√10 – 2))] × 100% = [2π(2 – (√10 – 2)) \/ (2π(√10 – 2))] × 100%.\nSimplify the numerator:\n  2 – (√10 – 2) = 4 – √10.\nThus the ratio becomes\n  (4 – √10) \/ (√10 – 2) × 100%.\nThis is the required percentage.\n\nTo summarize, the answer is:\n  p = 11 + 4√10,\nand the circumference of Circle B exceeds that of Circle A by\n  [(4 – √10)\/(√10 – 2)] × 100%.", + "output":"The two‐circle condition gives \n √(25–p)+2=√10 \n⇒ √(25–p)=√10–2 \n⇒ 25–p=(√10–2)²=14–4√10 \n⇒ p=11+4√10. \n\nThe circumferences are \n C₁=2π·√(25–p)=2π(√10–2), \n C₂=4π. \n\nSo \n % excess=(C₂–C₁)\/C₁·100% \n  =[4π–2π(√10–2)]\/[2π(√10–2)]·100% \n  =(4–√10)\/(√10–2)·100% \nRationalizing, \n (4–√10)\/(√10–2)=2(√10–1)\/6=(√10–1)\/3, \nso \n % excess=100·(√10–1)\/3 ≃72.1%. \n\nAnswer: \n(a) p=11+4√10. \n(b) Circle B’s circumference exceeds A’s by 100(√10–1)\/3 % (≈72.1 %).", + "golden_answer":"72.1", + "source":"Bigmath_synth" + }, + { + "instruction":"During a 60‑day art workshop, Daniel receives 12 paintbrushes every day while Mia gets a set of paints. On every 5th day, however, Mia’s kit includes 3 extra paints to support a special project. If the total number of items (brushes and paints) given to both over the 60 days is 1656, how many paints does Mia receive on a regular day (i.e. on a day that is not the 5th day)?\n\nTo solve, note that Daniel’s total is 60 × 12 = 720 brushes. Thus, the total number of paints given to Mia is 1656 – 720 = 936.\n\nSince every 5th day is special, there are 60 ÷ 5 = 12 special days and 60 – 12 = 48 regular days. Let x be the number of paints Mia receives on a regular day. Then on each special day she receives (x + 3) paints.\n\nOver the entire workshop, the total paints Mia gets is \n  48·x + 12·(x + 3) = 48x + 12x + 36 = 60x + 36.\n\nSetting up the equation:\n  60x + 36 = 936\n\nSubtract 36 from both sides:\n  60x = 900\n\nDivide both sides by 60:\n  x = 15\n\nThus, Mia receives 15 paints on each regular day.", + "output":"Mia receives 15 paints on each regular (non‑5th) day.", + "golden_answer":"5", + "source":"Bigmath_synth" + }, + { + "instruction":"A hot air balloon is being filled with gas, and the amount of gas in the balloon (in liters) at time t (in minutes) is modeled by the function V(t) = 5t – t².\n\n(a) Find the equation of the tangent line to the graph at t = 2 minutes and explain what the slope of this tangent line represents in this context.\n\n(b) Due to a temperature increase, the instantaneous filling rate (i.e. the slope of the tangent line at t = 2) increases by 20%, while the volume at t = 2 minutes remains unchanged. Determine the equation of the new tangent line that reflects this change.", + "output":"a) V(t)=5t–t² ⇒ V′(t)=5–2t, so at t=2, V′(2)=5–4=1. Also V(2)=5·2–2²=6. The tangent line is \n y–6=1·(t–2) ⇒ y=t+4. \nThe slope 1 means that at t=2 the balloon’s volume is increasing at 1 liter per minute.\n\nb) Increasing that instantaneous rate by 20% gives a new slope m=1·1.2=1.2, with the point still (2,6). So \n y–6=1.2·(t–2) ⇒ y=1.2 t+3.6.", + "golden_answer":"3.6", + "source":"Bigmath_synth" + }, + { + "instruction":"A bakery produces square-shaped pastries of two kinds. For a Type A pastry, the side length is given by the arithmetic square root of 25, while for a Type B pastry the side length is half the arithmetic square root of 36. However, due to presentation standards, every pastry must have a side length of at least 4 units. The packaging cost is determined by the pastry’s perimeter at a rate of $2 per unit length.\n\n(a) Determine the actual side length for each type of pastry after applying the minimum side‐length requirement.\n\n(b) Calculate the perimeter of each pastry based on its final side length.\n\n(c) Find the total packaging cost for one pastry of each type.\n\n", + "output":"a) Computed side‐lengths before the minimum rule \n – Type A: √25 = 5 \n – Type B: (½)·√36 = 3, but 3<4 so it must be raised to the 4‑unit minimum \n\n ⇒ Final side lengths: \n • Type A = 5 units \n • Type B = 4 units \n\nb) Perimeter P = 4·(side length) \n • P_A = 4·5 = 20 units \n • P_B = 4·4 = 16 units \n\nc) Packaging cost = $2 per unit of perimeter \n • Cost_A = 2·20 = $40 \n • Cost_B = 2·16 = $32 \n • Total for one of each = $40 + $32 = $72", + "golden_answer":"72", + "source":"Bigmath_synth" + }, + { + "instruction":"A charity event sells raffle tickets numbered 1 through 150. A ticket wins a special prize if it meets one of these two sets of conditions:\n• If the ticket number is 100 or less, it must be divisible by 4 but not divisible by 8.\n• If the ticket number is greater than 100, it must be a prime number.\nDetermine the probability that a randomly drawn ticket wins the special prize.", + "output":"First, count the winners in each range:\n\n1) Numbers n ≤ 100 that are divisible by 4 but not by 8. \n – Multiples of 4 up to 100: ⌊100\/4⌋ = 25 \n – Multiples of 8 up to 100: ⌊100\/8⌋ = 12 \n ⇒ “4‑but‑not‑8” winners = 25 − 12 = 13\n\n2) Primes between 101 and 150. \n Those are 101, 103, 107, 109, 113, 127, 131, 137, 139, 149 ⇒ 10 of them\n\nTotal winning tickets = 13 + 10 = 23. \nTotal tickets = 150.\n\nTherefore the probability is \nP = 23 \/ 150 ≈ 0.1533.", + "golden_answer":"0.1533", + "source":"Bigmath_synth" + }, + { + "instruction":"A factory is recalibrating one of its temperature sensors. In the initial calibration, the sensor’s reading x (in °C) is modeled by the equation\n  (x\/5) – 2 = 3x + a,\nwhere a is an unknown adjustment constant. If the optimal calibration requires the sensor to read –5°C, determine a. \n\nLater, after a maintenance update, the sensor’s reading y (in °C) is given by\n  (1\/5)(2y + 1) – 5 = 6y + a.\nFind y. \n\nFinally, the machine’s output efficiency increases by 15% for every degree that the sensor’s reading exceeds –5°C. Based on the new reading y, by what percentage does the efficiency increase relative to the optimal reading?", + "output":"1. Plugging x = –5 into (x\/5) – 2 = 3x + a:\n (–5\/5) – 2 = 3(–5) + a \n –1 – 2 = –15 + a \n –3 = –15 + a ⇒ a = 12.\n\n2. With a = 12, solve (1\/5)(2y + 1) – 5 = 6y + 12:\n (2y + 1)\/5 – 5 = 6y + 12 \n (2y + 1)\/5 = 6y + 17 \n 2y + 1 = 5(6y + 17) = 30y + 85 \n 2y + 1 – 30y – 85 = 0 ⇒ –28y – 84 = 0 ⇒ y = –3.\n\n3. The reading exceeds –5°C by (–3)–(–5)=2°; at 15% per degree that’s 2×15% = 30% extra efficiency.", + "golden_answer":"30", + "source":"Bigmath_synth" + }, + { + "instruction":"Set X consists of all multiples of 3 between 12 and 36, inclusive, while Set Y consists of all multiples of 3 between 15 and some unknown number M, inclusive. If exactly 5 distinct numbers belong to both sets and the sum of these common numbers is 105, what is M?", + "output":"First note that \nX = {12,15,18,21,24,27,30,33,36} \nY = all multiples of 3 from 15 up to M. \n\nTheir intersection is all multiples of 3 from max(12,15)=15 up to min(36,M). We are told that this intersection has exactly 5 elements and those five sum to 105.\n\nThe only 5 consecutive multiples of 3 starting at 15 are \n 15, 18, 21, 24, 27 \nand indeed 15+18+21+24+27 = 105. \n\nHence the intersection stops at 27, which forces \n min(36, M) = 27 \nand so M cannot exceed 27 (or else you’d pick up 30 too). Taking M as a multiple of 3 gives \n\nAnswer: M = 27.", + "golden_answer":"27", + "source":"Bigmath_synth" + }, + { + "instruction":"At a New Year's party, a host wants to gift personalized mugs to each of his 4 guests. He has 3 unique mug designs available on his computer; however, his printing machine can print at most 2 mugs of the same design without incurring an extra setup fee. In order to avoid the fee, the host will assign the designs so that no design is used on more than 2 mugs. How many different ways can he assign a mug design to each guest?", + "output":"We label the designs A, B, C and the guests 1–4. In total there are 3⁴=81 ways to give each guest one of the three designs, but we must forbid any design appearing 3 or 4 times. \n\nBy inclusion–exclusion: \n• For each design (say A), the number of assignments with A used ≥3 times is \n – exactly 3 A’s: C(4, 3)·2 = 4·2 = 8 \n – exactly 4 A’s: 1 \n so |{assignments with ≥3 A}| = 9. Similarly for B and for C. \n• No two of these events can happen simultaneously (you can’t have both A≥3 and B≥3 in only 4 slots), so the three “bad” sets are disjoint. \n\nTotal bad = 3·9 = 27 ⇒ good = 81 − 27 = 54. \n\nHence there are 54 ways to assign designs so that no design is used more than twice.", + "golden_answer":"54", + "source":"Bigmath_synth" + }, + { + "instruction":"A printing shop has two printers, Printer X and Printer Y. Printer X works 1.5 times faster than Printer Y. Together they print 5\/12 of a large magazine order in 2 hours. Unfortunately, after working together for 2 hours, Printer X unexpectedly malfunctions and stops working. Printer Y then continues alone and finishes the remaining order in 7 hours. Determine how many hours Printer X would need to print the entire magazine order on his own.", + "output":"Let r_Y be Printer Y’s rate (in “orders per hour”). Then Printer X’s rate is r_X=1.5 r_Y.\n\n1) Working together for 2 h they complete 5\/12 of the job: \n 2·(r_X+r_Y)=5\/12 \n ⇒ r_X+r_Y=5\/24.\n\n2) After X breaks, Y alone finishes the remaining 7\/12 in 7 h: \n 7·r_Y=7\/12 \n ⇒ r_Y=(7\/12)\/7=1\/12.\n\n3) Hence \n r_X=5\/24−r_Y=5\/24−1\/12=5\/24−2\/24=3\/24=1\/8.\n\nAt 1\/8 of the job per hour, Printer X needs 8 hours to do the entire order alone.", + "golden_answer":"8", + "source":"Bigmath_synth" + }, + { + "instruction":"A store offers a special discount for its loyal customers. For each product, the discount rate is determined in two steps:\n Step 1: Find the cube root of –64 and multiply the result by –2.\n Step 2: Add the absolute value of –8 percent.\nIf a product is originally priced at $150, calculate its final price after applying the total discount percentage (i.e., subtract the discount from the original price).", + "output":"First, compute the two parts of the discount:\n\n1. Cube root of –64 is –4. Multiply by –2 gives \n –4 × (–2) = +8 %.\n\n2. Absolute value of –8 % is 8 %.\n\nTotal discount = 8 % + 8 % = 16 %.\n\nOn a \\$150 item, 16 % of 150 is \n0.16 × 150 = \\$24\n\nFinal price = 150 – 24 = \\$126.", + "golden_answer":"126", + "source":"Bigmath_synth" + }, + { + "instruction":"A bakery has 1418 grams of dough. The chef uses 66 grams for each standard pastry and plans to divide the dough into as many full portions as possible. The remaining dough will be used to make a special treat. However, if the leftover dough is less than 50 grams, she will add an extra 20 grams from her supplies. What is the final weight of the dough used for the special treat?", + "output":"First, divide 1418 g by 66 g: \n· 66 g × 21 = 1386 g \n· Remainder = 1418 − 1386 = 32 g \n\nSince the leftover 32 g is less than 50 g, she adds 20 g more. \nTherefore, the special treat weighs 32 g + 20 g = 52 g.", + "golden_answer":"52", + "source":"Bigmath_synth" + }, + { + "instruction":"Two nonzero numbers a and b represent the annual interest rates (in percent) offered by two different investment plans. These numbers are the roots of the quadratic equation\n  x² – 7r·x + 10r² = 0,\nwhere r > 0 is a parameter reflecting market conditions. To create a diversified portfolio, an investor combines these rates into a new financial product whose return is modeled by the quadratic\n  x² – a·x + 2b = 0.\nIf this portfolio is designed to yield a fixed return (that is, the equation has a unique, repeated solution), determine all possible values of r.", + "output":"Let a, b be the two roots of \n x² – 7r x + 10r² = 0. \nThen by Viète \n a + b = 7r, \n ab = 10 r². \n\nThe “combined‐portfolio’’ equation is \n x² – a x + 2b = 0 \nand it has a double (repeated) root exactly when its discriminant vanishes: \n Δ = a² – 4·1·(2b) = a² – 8b = 0 \n⇒ b = a²\/8. \n\nHence we must solve the system \n(1) a + b = 7r \n(2) ab = 10 r² \n(3) b = a²\/8. \n\nSubstitute (3) into (1),(2): \n (1′) a + a²\/8 = 7r \n (2′) a·(a²\/8) = 10 r². \n\nFrom (1′) 7r = a + a²\/8 ⇒ r = (a + a²\/8)\/7 \nFrom (2′) a³\/8 = 10 r². \n\nEliminate r: \n r² = [(a + a²\/8)\/7]² \nso \n a³\/8 = 10⋅[(a + a²\/8)\/7]². \n\nClear denominators and simplify to get the quadratic in a: \n 5a² – 116a + 320 = 0 \n⇒ a = 20 or a = 3.2. \n\nThen b = a²\/8 gives \n if a=20, b=400\/8=50, and r = (20+20²\/8)\/7 = (20+50)\/7 =70\/7=10; \n if a=3.2, b=3.2²\/8=10.24\/8=1.28, and r = (3.2+1.28)\/7 =4.48\/7 =0.64. \n\nBoth are positive, so the only possible values of r are \n r = 10 or r = 0.64.", + "golden_answer":"0.64", + "source":"Bigmath_synth" + }, + { + "instruction":"Elena wants to reduce her weekly expense on strawberries by growing her own. She buys 6 strawberry plants for $15 each and pays a one‐time setup fee of $30 for soil and pots. Every week the plants cost her a total of $2 in maintenance. In the first week each plant produces 2 punnets of strawberries. For the next 4 weeks the yield of each plant increases by 1 punnet per week (so in week 2 each plant gives 3 punnets, in week 3 it’s 4 punnets, in week 4 it’s 5 punnets, and in week 5 each plant produces 6 punnets); thereafter, each plant consistently yields 6 punnets per week. Alternatively, she can buy strawberries at $5 per punnet from the market. Assuming no spoilage and that she uses all the strawberries she produces, after how many weeks will the total cost of growing her own strawberries become less than the total cost of buying them?", + "output":"Let n be the number of weeks. \n\nCost of growing through week n \n = (one‐time) \\$30 (setup) + 6·\\$15 (plants) + \\$2·n \n = \\$120 + 2n. \n\nTotal punnets produced by one plant in the first n weeks, y(n), is \n for n≤5: 2+3+4+… up to n terms ⇒ y(1)=2, y(2)=5, y(3)=9, y(4)=14, y(5)=20 \n for n>5: y(n)=20+6·(n−5)=6n−10. \n\nTotal punnets all 6 plants produce in n weeks = 6·y(n). \nCost of buying that many = 6·y(n)·\\$5 = \\$30·y(n). \n\nWe seek the smallest n with \n 120 + 2n < 30·y(n). \n\nCheck n=1: \n LHS=120+2=122, RHS=30·2=60 ⇒ 122<60? no \nn=2: \n LHS=120+4=124, RHS=30·5=150 ⇒ 124<150? yes \n\nHence by the end of week 2 the cumulative cost of growing (124) is already less than the cost of buying (150). \nAnswer: 2 weeks.", + "golden_answer":"2", + "source":"Bigmath_synth" + }, + { + "instruction":"An ice cream parlor offers three flavors: vanilla, chocolate, and strawberry. On a typical weekday, the parlor prepares 40 servings of vanilla ice cream. They prepare 25% more servings of chocolate than vanilla. On weekends, the number of strawberry servings depends on the chocolate servings: if the chocolate servings are less than 60, then the parlor makes three times as many strawberry servings; otherwise, it makes 1.5 times as many. Furthermore, if the total number of servings (all three flavors) exceeds 150 on any day, the parlor also prepares an extra bonus batch of 10 servings of a special flavor. \n\na) Calculate the total number of servings available on a weekday, knowing that only vanilla and chocolate are served. \n\nb) Calculate the total number of servings available on a weekend. \n\n(Show your work and state any assumptions made.)", + "output":"a) Weekday \n1. Vanilla servings V = 40. \n2. Chocolate is 25% more than vanilla ⇒ C = V·(1 + 0.25) = 40·1.25 = 50. \n3. On a weekday only vanilla and chocolate are served, so strawberry S = 0. \n4. Total T_weekday = V + C + S = 40 + 50 + 0 = 90. \n5. Since 90 ≤ 150, there is no bonus batch. \nAnswer (a): 90 servings. \n\nb) Weekend \nAssumption: the parlor still makes V = 40 vanilla and C = 50 chocolate on weekends. \n1. Check C = 50 < 60 ⇒ strawberry S = 3·C = 3·50 = 150. \n2. Subtotal before bonus = V + C + S = 40 + 50 + 150 = 240. \n3. Since 240 > 150, they add a bonus batch of 10 special‐flavor servings. \n4. Total T_weekend = 240 + 10 = 250. \nAnswer (b): 250 servings.", + "golden_answer":"250", + "source":"Bigmath_synth" + }, + { + "instruction":"Jordan is renovating his kitchen and has purchased several appliances on credit. His items and discounts are as follows:\n • Refrigerator: $1,200 with a 10% discount \n • Oven: $800 with a 5% discount \n • Dishwasher: $600 with no discount \n • Microwave: $150 with a 20% discount \n • Coffee maker: $50 with no discount\n\nAfter the discounts, Jordan must finance any unpaid amounts on his credit card. He has $800 in savings that he will use as a down payment. He applies his $800 in the following order: first toward paying off the refrigerator in full; if any savings remain, he then uses them for the oven; then the dishwasher; and so on, until his savings run out.\n\nAny amount left unpaid is put on his credit card. Normally, the monthly interest rate is 4%, but if his financed amount (the total unpaid sum after applying his savings) exceeds $500, the entire financed balance will incur an increased interest rate of 6% for that month. In addition, if the remaining financed amount (before interest is added) is greater than $1,500, a one-time processing fee of $25 will be added to his bill for that month.\n\nDetermine the total amount Jordan will owe on his credit card after one month, including the applicable interest and any processing fee.", + "output":"Step 1 – Compute discounted prices \n- Refrigerator: \\$1,200 × 0.90 = \\$1,080 \n- Oven: \\$800 × 0.95 = \\$760 \n- Dishwasher: \\$600 = \\$600 \n- Microwave: \\$150 × 0.80 = \\$120 \n- Coffee maker: \\$50 = \\$50 \n\nTotal after discounts = 1,080 + 760 + 600 + 120 + 50 = \\$2,610 \n\nStep 2 – Apply the \\$800 down payment in priority order \n1. Refrigerator needs \\$1,080. Pay \\$800 ⇒ \\$280 remains on the fridge. \n2. Savings exhausted. \n\nUnpaid balances put on the card: \n• Refrigerator: \\$280 \n• Oven: \\$760 \n• Dishwasher: \\$600 \n• Microwave: \\$120 \n• Coffee maker:\\$50 \n⇒ Total financed = 280 + 760 + 600 + 120 + 50 = \\$1,810 \n\nStep 3 – Determine interest rate & fees \n- Since financed > \\$500, the monthly rate is 6%. \n- Since financed > \\$1,500, add a one‑time \\$25 processing fee. \n\nInterest = 1,810 × 0.06 = \\$108.60 \nProcessing fee = \\$25 \n\nStep 4 – Total owed after one month \nPrincipal = \\$1,810.00 \nInterest = \\$108.60 \nProcessing fee = \\$25.00 \n-------------------------------- \nTotal = \\$1,943.60 \n\nAnswer: After one month, Jordan will owe \\$1,943.60 on his credit card.", + "golden_answer":"1943.60", + "source":"Bigmath_synth" + }, + { + "instruction":"At a community garden, there are 48 rose bushes and 22 tulip plants. The garden coordinator plants 12 additional rose bushes and removes 7 tulip plants due to a pest issue. Later, three local gardeners donate a total of 15 tulip plants (5 each), but 20% of these donated tulip plants are found to be infertile and are not counted for planting. Determine the total number of rose bushes and the number of viable tulip plants in the garden, and then express the ratio of viable tulip plants to rose bushes.", + "output":"First, update each flower count step by step:\n\n1. Roses \n – Start with 48 \n – + 12 planted \n ⇒ 48 + 12 = 60 rose bushes \n\n2. Tulips \n – Start with 22 \n – – 7 removed \n ⇒ 22 – 7 = 15 remaining before donations \n – + 15 donated \n • But 20% of donated are infertile, so only 80% are viable: \n 15 × 0.80 = 12 viable donated tulips \n ⇒ Total viable tulips = 15 + 12 = 27 \n\nSo in the garden now there are \n• 60 rose bushes \n• 27 viable tulip plants \n\nThe ratio of viable tulip plants to rose bushes is \n27 : 60, which simplifies (÷3) to \n9 : 20.", + "golden_answer":"20", + "source":"Bigmath_synth" + }, + { + "instruction":"In a trapezoidal field the longer and shorter bases are in the ratio 2 : 1. The product of the length of the midline and the length of the segment joining the midpoints of the diagonals is 16 (in appropriate square units). Moreover, the height of the field equals the difference between the lengths of its bases. Determine the area of the field.", + "output":"Let the shorter base = b, so the longer base = 2b. By hypothesis the height h = difference of the bases = 2b–b = b.\n\n1. Mid‐line length \n m = (long + short)\/2 = (2b + b)\/2 = 3b\/2. \n2. Place the trapezoid so A=(0,0), B=(2b,0), D=(x₀,b), C=(x₀+b,b). \n Then the diagonals are AC and BD. Their midpoints are \n M = midpoint of AC = ((x₀+b)\/2, b\/2), \n N = midpoint of BD = ((2b+x₀)\/2, b\/2). \n Hence MN = |(2b+x₀)\/2 – (x₀+b)\/2| = b\/2. \n3. The given product is \n m·MN = (3b\/2)·(b\/2) = 3b²\/4 = 16 ⇒ b² = 64\/3. \n4. Area = (sum of bases)\/2 · height = m·h = (3b\/2)·b = 3b²\/2 = 3·(64\/3)\/2 = 32. \n\nAnswer: The area is 32 square units.", + "golden_answer":"32", + "source":"Bigmath_synth" + }, + { + "instruction":"A shop began the day with 200 pieces of fruit (apples and pears). After selling some of them, the remaining stock was arranged in a way that the number of apples was twice the number of pears. A later inventory count showed that 60 apples were left. Subsequently, due to improper storage, 10% of the pears had to be discarded. Determine:\n(a) The number of fruits sold during the day.\n(b) The number of pears discarded due to spoilage.", + "output":"Let A0+P0=200 be the opening stock. After the day’s sales the stock satisfies \n A=2P, \nand a later count gives A=60. Hence P=60\/2=30, so remaining fruit=60+30=90. \n(a) Sold=200−90=110. \n(b) Pears spoiled=10% of the 30 pears=3.", + "golden_answer":"3", + "source":"Bigmath_synth" + }, + { + "instruction":"A community park has been designed so that its curved edge follows the graph of f(x) = 0.5·x² while one straight edge is given by the line g(x) = 4 – x. The park’s boundary is exactly the region enclosed by these two curves between their points of intersection. In addition, a rectangular plot is constructed with its base along the x-axis extending from the left to the right intersection point of the curves and with its height equal to the maximum vertical distance between g(x) and f(x) over that interval.\n\n(a) Find the area of the park (that is, the area between f(x) and g(x) from the first to the second intersection point).\n\n(b) Compute the area of the rectangle and determine what percent of the rectangle’s area is occupied by the park’s area.", + "output":"a) The two curves meet where \n 0.5 x² = 4 – x \n⇒ 0.5 x² + x – 4 = 0 \n⇒ x² + 2x – 8 = 0 \n⇒ x = 2 or x = −4. \nHence the park lies between x = −4 and x = 2. \nIts area is \n ∫₋₄² [g(x) – f(x)] dx \n= ∫₋₄² [ (4 – x) – (0.5 x² ) ] dx \n= ∫₋₄² (4 – x – 0.5x²) dx \n= [4x – x²\/2 – x³\/6]₋₄² \n= (8 – 2 – 8\/6) – (−16 – 8 + 64\/6) \n= (4.6667) – (−13.3333) \n= 18. \n\nb) The “bounding” rectangle runs from x = −4 to 2 (width = 6) and its height is the maximum of \n h(x) = g(x) – f(x) = 4 – x – 0.5x². \nh′(x) = −1 − x = 0 ⇒ x = −1 (in [−4,2]), \nh(−1) = 4 + 1 − 0.5 = 4.5. \nSo rectangle area = 6·4.5 = 27. \nThe park’s area (18) is therefore (18\/27)=2\/3≈66.7% of the rectangle.", + "golden_answer":"66.7", + "source":"Bigmath_synth" + }, + { + "instruction":"At a local bakery, the cost (in dollars) per kilogram of a special flour blend is x. The owner discovered that if this cost is multiplied by 4, the result is 50% more than what is obtained when x is subtracted from 30. Find the value of x.", + "output":"Let x be the cost per kg. “4 × cost is 50% more than (30 − cost)” translates to\n\n1) 4x = (30 − x) + 0.5·(30 − x) = 1.5·(30 − x) \n2) 4x = 1.5·30 − 1.5x = 45 − 1.5x \n3) 4x + 1.5x = 45 \n4) 5.5x = 45 \n5) x = 45\/5.5 = 90\/11 ≃ 8.18 \n\nSo the flour costs $90\/11 (≈ \\$8.18) per kilogram.", + "golden_answer":"8.18", + "source":"Bigmath_synth" + }, + { + "instruction":"Liam, Olivia, and Emma are hosting a bake sale. Their items for sale are muffins, cupcakes, and slices of cake. A regular muffin weighs 2 ounces, a cupcake weighs 4 ounces, and a slice of cake weighs 6 ounces. Due to a packaging error, 20% of the muffins Liam sold actually weighed only 1.5 ounces each, while the remaining muffins weighed the standard 2 ounces. Olivia sold 15 cupcakes. Emma sold twice as many slices of cake as the number of cupcakes Olivia sold, and Liam sold 3 times as many muffins as the number of slices of cake Emma sold. If the total weight of the muffins Liam sold is 171 ounces, how many slices of cake did Emma sell?", + "output":"Let M be the number of muffins Liam sold. 20% of M weighed 1.5 oz, the other 80% weighed 2 oz, so the total weight is\n\n 0.2M·1.5 + 0.8M·2 = 0.3M + 1.6M = 1.9M.\n\nWe’re told this equals 171 oz, so\n\n 1.9M = 171 ⇒ M = 171\/1.9 = 90.\n\nOlivia sold 15 cupcakes. Emma sold twice that many slices of cake:\n\n Emma’s slices = 2·15 = 30.\n\n(Check: Liam’s muffins = 3·(Emma’s slices) = 3·30 = 90, as found above.)\n\nAnswer: Emma sold 30 slices of cake.", + "golden_answer":"30", + "source":"Bigmath_synth" + }, + { + "instruction":"A tech company releases a series of smartwatch models whose launch prices form a geometric sequence with positive terms. Let Pₙ denote the price of the nth model. The company’s pricing strategy ensures that 1.2 times the price of the third model is equal to the price of the sixth model (i.e. 1.2·P₃ = P₆). In a special promotion, customers who buy the first four models receive a bonus discount equal to the sum of the prices of the second and fifth models. Determine the ratio of the total cost for the first four models to the bonus discount.", + "output":"Denote the common‐ratio of the launch‐prices by r, so that \nPₙ = a rⁿ⁻¹. \nFrom 1.2·P₃ = P₆ we get \n1.2·(a r²) = a r⁵ ⇒ r³ = 1.2. \n\nWe want \nS₄ = P₁+P₂+P₃+P₄ = a(1 + r + r² + r³), \nBonus = P₂+P₅ = a(r + r⁴) = a·r(1 + r³). \n\nHence the ratio is \n(R) ≡ S₄ \/ Bonus \n = [a(1 + r + r² + r³)] \/ [a·r(1 + r³)] \n = (1 + r + r² + r³) \/ [r(1 + r³)]. \n\nBut r³ = 1.2, so 1 + r³ = 2.2, and the numerator = 1 + r + r² + 1.2 = r² + r + 2.2. Thus \nR = (r² + r + 2.2)\/(2.2 r). \n\nNumerically r = 1.2^(1\/3) ≃1.0627, so \nR ≃ (1.0627² + 1.0627 + 2.2)\/(2.2·1.0627) ≃1.879. \n\nAnswer: \n Ratio = (1 + r + r² + r³)\/(r + r⁴) with r³=1.2, \n numerically ≃1.88.", + "golden_answer":"1.88", + "source":"Bigmath_synth" + }, + { + "instruction":"A local microfinance institution uses a two‐stage screening process for approving low‐interest loans. In the first stage, 75% of applicants pass an initial credit check. Those who pass then undergo a detailed background investigation in which 80% pass. An applicant receives the loan only if they pass both stages. If the institution evaluates 7 applicants, what is the probability that exactly 3 applicants receive the loan? Express your answer as a decimal rounded to two decimal places.", + "output":"The chance an applicant gets a loan is \np = 0.75·0.80 = 0.60, \nso X∼Binomial(n=7,p=0.6). \nP(X=3) = C(7,3)(0.6)³(0.4)⁴ \n = 35·0.216·0.0256 \n ≈ 0.1935 \n≈ 0.19.", + "golden_answer":"0.19", + "source":"Bigmath_synth" + }, + { + "instruction":"Eight visitors went to a science museum and then enjoyed a themed meal. Six of the visitors were adults and two were children. Each child’s museum ticket costs $5, and the meal cost a total of $18. Without any discounts, the combined cost for all museum tickets and the meal was exactly $102. However, because more than six tickets were purchased, the museum applied a 15% group discount on each adult’s ticket. \n\n(a) Determine the original (undiscounted) price of an adult museum ticket. \n(b) Calculate the total amount paid for the adult tickets after applying the group discount.", + "output":"a) Let A be the undiscounted adult‐ticket price. Then without any discounts \n 6·A + 2·5 + 18 = 102 \n⇒ 6A + 10 + 18 = 102 \n⇒ 6A = 102 − 28 = 74 \n⇒ A = 74\/6 = $12.333… (i.e. $12.33 repeating) \n\nb) With a 15% discount each adult pays 0.85 A, so the six of them pay in total \n 6 × 0.85 A = 0.85 × (6A) = 0.85 × 74 = $62.90.", + "golden_answer":"62.90", + "source":"Bigmath_synth" + }, + { + "instruction":"A retail store tracked the payment methods used by its 60 shoppers. Shoppers used one or more of the three primary methods—cash, credit card, and mobile payment apps—or they paid exclusively by alternative methods (store coupons and loyalty points). No shopper used both a primary method and an alternative method. The survey of primary methods showed that\n\n • 35 shoppers used cash,\n • 20 shoppers used credit cards, and\n • 28 shoppers used mobile payment apps.\n\nAdditional details about overlaps among the primary methods are as follows:\n\n • 12 shoppers used both cash and mobile payment apps but did not use a credit card,\n • 8 shoppers used both credit cards and mobile payment apps but did not use cash, and\n • 5 shoppers used all three primary methods.\n\nIt is also known that exactly 10 shoppers paid exclusively by alternative methods.\n\nDetermine the number of shoppers who paid using only cash (that is, those who used cash and no other primary payment method).", + "output":"Let the seven “regions” among the primary‐method users be denoted as follows:\n\n• x = # who used only cash \n• y = # who used only credit \n• z = # who used only mobile \n• a = # who used cash & credit only \n• b = # who used cash & mobile only = 12 (given) \n• c = # who used credit & mobile only = 8 (given) \n• t = # who used all three = 5 (given) \n\nSince 10 shoppers used only alternative methods, there are 60–10=50 shoppers who used at least one primary method. Hence\n\n x + y + z + a + b + c + t = 50. \n\nPlug in b=12, c=8, t=5:\n\n x + y + z + a + (12+8+5) = 50 \n x + y + z + a + 25 = 50 \n x + y + z + a = 25. (1)\n\nNext use the totals for each primary method:\n\nCash total = 35 = x + a + b + t \n ⇒ x + a + 12 + 5 = 35 \n ⇒ x + a = 18. (2)\n\nCredit total = 20 = y + a + c + t \n ⇒ y + a + 8 + 5 = 20 \n ⇒ y + a = 7. (3)\n\nMobile total = 28 = z + b + c + t \n ⇒ z + 12 + 8 + 5 = 28 \n ⇒ z = 3. (4)\n\nSubstitute z=3 into (1): \n x + y + a + 3 = 25 \n x + y + a = 22. (5)\n\nBut from (2), x + a = 18, so (5) gives 18 + y = 22 ⇒ y = 4. \nThen from (2), a = 18 – x; from (3), 4 + a = 7 ⇒ a = 3; hence x = 15.\n\nAnswer: 15 shoppers paid using only cash.", + "golden_answer":"15", + "source":"Bigmath_synth" + }, + { + "instruction":"Consider an arithmetic sequence {aₙ} with a₁ = 3 and common difference 2. For each positive integer n, let Sₙ be the sum of the first n terms of {aₙ}. Define a new sequence {bₙ} by\n\n  bₙ = 1⁄(Sₙ + n).\n\nLet T₆ be the sum b₁ + b₂ + b₃ + b₄ + b₅ + b₆. Calculate T₆ exactly and express your answer as a simplified fraction.\n\nTo solve the problem, note that the nth term of the arithmetic sequence is aₙ = 3 + 2(n – 1), so\n  a₁ = 3,\n  a₂ = 5,\n  a₃ = 7,\n  a₄ = 9,\n  a₅ = 11,\n  a₆ = 13.\n\nThen Sₙ is found by summing the first n terms, and for each n compute Sₙ + n. Finally sum bₙ = 1⁄(Sₙ + n) for n = 1 to 6.", + "output":"First observe that \n aₙ=3+2(n−1)⇒Sₙ=∑_{k=1}^n a_k = n\/2·(2·3+(n−1)·2) = n(n+2). \nHence \n Sₙ+n = n(n+2)+n = n(n+3), \nso \n bₙ = 1\/[n(n+3)]. \n\nBut \n 1\/[n(n+3)] = (1\/3)·(1\/n − 1\/(n+3)), \nso the sum telescopes: \n T₆ = ∑_{n=1}^6 bₙ \n = (1\/3)·∑_{n=1}^6 (1\/n − 1\/(n+3)) \n = (1\/3)·[(1+½+⅓) − (1\/7+1\/8+1\/9)] \n = (1\/3)·[11\/6 − 191\/504] \n = (1\/3)·[924\/504 − 191\/504] \n = (1\/3)·(733\/504) \n = 733\/1512. \n\nAnswer: 733\/1512.", + "golden_answer":"1512", + "source":"Bigmath_synth" + }, + { + "instruction":"On a circular highway of length 2400 km there are 2400 equally spaced petrol stations, each fitted with a fuel pump. The distance between any two stations is defined as the length of the shorter arc along the highway. The service manager wishes to reassign the pumps (so that each station still receives exactly one pump) with the following conditions:\n\n• For every pair of pumps that were originally installed at stations whose distance is at most n km apart, the distance between their new stations must be strictly greater than the original distance.\n\n• Due to historical significance, exactly 360 stations (15% of 2400) must retain their originally installed pump.\n\nDetermine the largest possible integer n for which such a reallocation is possible.\n\n", + "output":"A particularly clean way to see that one can “stretch’’ all distances ≤5 while leaving exactly 360 pumps fixed but that one cannot do the same for d = 6 is the following.\n\n 1. Lay out the 2 400 stations round a circle. Call a station “fixed’’ if in our final assignment its pump does not move. We will choose exactly 360 of these (15 % of 2 400), equally spaced every 6 km.\n\n 2. That leaves 2 040 “movable’’ pumps to be re‐planted at the 2 040 nonfixed stations. By pinning our 360 fixed stations at every 6th location (0, 6, 12, 18,…, 2394), the remaining movable stations come in 360 little runs of length five in between the fixed ones (namely the runs 1–5, 7–11, 13–17, …, 2395–2399).\n\n 3. We now “wrap’’ each of those runs of five, in order, onto the next free run. Concretely, if the five movable stations in the k‑th interval are \n a₁< a₂< a₃< a₄< a₅ \n (all modulo 2400), we simply reassign their pumps to the five free stations in the (k+1)‑st interval, in the same order. \n – Since each run is length 5, nothing ever tries to use one of the 360 fixed stations. \n – Within each run consecutive stations were 1 km apart; mapping them into the next run makes them 1 km apart, but since there is a fixed station in between the two runs (6 km away in total), they end up 7 km apart. Thus every originally‐adjacent pair gets sent at least 7 km apart. \n – Likewise any two stations that were originally d km apart with 1≤ d ≤5 lie within a single five‑run or straddle exactly one fixed station, both of which force their images to lie in runs at least two apart. A short check shows that in every case the distance between the images becomes ≥ d+1.\n\n 4. Because the fixed pumps never move, exactly 360 are left fixed, and every pair whose original separation was 1,2,3,4 or 5 km ends up strictly farther apart (in fact by at least one km more). \n\n 5. On the other hand, no rearrangement can stretch *all* pairs of original distance ≤6. One way to see that is by counting “short‐distance pairs’’ vs. the maximum total separation you can achieve on a 2 400‑cycle; one shows easily by a pigeonhole \/ averaging argument that if you demanded every d=6 pair to be sent to ≥7 km apart you would run out of total circumference to spread them into.\n\nConclusion: \n The largest integer n for which one can do the reassignment with exactly 360 stations fixed and *strictly* expand every distance ≤n is n=5.", + "golden_answer":"5", + "source":"Bigmath_synth" + }, + { + "instruction":"In an environmental study, the daily CO₂ concentration (in parts per million) recorded over a week forms an arithmetic sequence. It is found that the sum of the concentrations for days 3, 4, 5, 6, and 7 is 1500 ppm, and the concentration on day 5 is 20% higher than that on day 3. Find the CO₂ concentration recorded on day 5. Express your answer as a single integer.", + "output":"Let the concentration on day n be a + (n−1)d. \nDay 3: a+2d, day 5: a+4d. \n\nGiven \n1) (a+2d)+(a+3d)+(a+4d)+(a+5d)+(a+6d)=1500 ⇒ 5a+20d=1500 \n2) a+4d =1.2(a+2d) ⇒ a+4d=1.2a+2.4d ⇒ −0.2a+1.6d=0 ⇒ a=8d \n\nSubstitute into 5a+20d=1500: 5·8d+20d=60d=1500 ⇒ d=25 ⇒ a=8·25=200. \nThus day 5: a+4d =200+4·25=300.", + "golden_answer":"300", + "source":"Bigmath_synth" + }, + { + "instruction":"A carpenter is designing an L-shaped bookshelf, and part of the design uses a right‐triangle structure for stability. The hypotenuse (the decorative edge) is 15 inches, and one of the legs (the horizontal shelf) is 9 inches. For additional support, the total length of the two legs will be increased by 10% to determine the length of the metal support bracket. First, determine the length of the missing (vertical) leg, and then calculate the adjusted total length of the two legs that will be used to mount the bracket.", + "output":"1. Use the Pythagorean theorem (let the unknown vertical leg be y): \n y² + 9² = 15² \n y² + 81 = 225 \n y² = 225 − 81 = 144 \n y = 12 inches \n\n2. Sum of the two legs before adjustment: \n 9 + 12 = 21 inches \n\n3. Increase that total by 10% for the bracket: \n 21 × 1.10 = 23.1 inches \n\nAnswer: \n• Missing (vertical) leg = 12″ \n• Adjusted total length for the metal bracket = 23.1″", + "golden_answer":"23.1", + "source":"Bigmath_synth" + }, + { + "instruction":"A store launches a month‐long promotion in which the daily discount percentage is adjusted based on the previous two days’ offers. On day 1 the discount is 10%, and on day 2 it is 18%. For every day n ≥ 1 the discount on day n + 2 is given by the rule\n\n  • if |Dₙ₊₁ – Dₙ| ≤ 8, then Dₙ₊₂ = |Dₙ₊₁ – Dₙ| + 4,\n  • if |Dₙ₊₁ – Dₙ| > 8, then Dₙ₊₂ = |Dₙ₊₁ – Dₙ|.\n\nDetermine the discount percentage on day 30 (express your answer as an integer percentage).", + "output":"The sequence (starting with D₁=10, D₂=18) goes\n\nn: 1  2  3  4  5  6  7  8  9 10 11 12 …\nDₙ:10, 18, 12, 10, 6, 8, 6, 6, 4, 6, 6, 4, …\n\nFrom day 7 on it cycles 6, 6, 4, so D₃₀ = 4%.", + "golden_answer":"4", + "source":"Bigmath_synth" + }, + { + "instruction":"Let s(n) denote the sum of the digits (in base‑10) of a positive integer n. How many positive integers n with 1 ≤ n ≤ 10^5 that are divisible by 7 satisfy the equation\n\n  s(101n) = 2 · s(n)?", + "output":"First one checks easily that \n\n s(101n)=s(n+100n)=2 s(n) \n\nif and only if, when you line up the digits of n and 100n, no column‐wise sum ever ≥10 (so that no carry occurs). Writing n in decimal as \n\n n= z₅z₄z₃z₂z₁z₀ (with z₅ possibly 0), \n\nthe only non‐trivial “no‐carry” conditions are\n\n z₂+z₀≤9, z₃+z₁≤9, z₄+z₂≤9, z₅+z₃≤9. \n\nMoreover for n≤10⁵ we have z₅=0 unless n=100 000 (which anyway is not a multiple of 7). Hence for 1≤n≤99 999 our constraints reduce to\n\n z₂+z₀≤9, z₃+z₁≤9, z₄+z₂≤9, (0≤zᵢ≤9).\n\nA short count shows there are 21 175 choices of (z₀,…,z₄) in 0…9 satisfying those three inequalities, one of them being the zero‐vector. Since 21 175=7·3025 it follows that exactly 3025 of those n∈[0,99999] have n≡0 mod 7. Subtracting the one trivial solution n=0 leaves 3024 positive multiples of 7 in [1,99999]. Finally n=100 000 is not divisible by 7, so the total in [1,10⁵] is\n\n 3024.", + "golden_answer":"3024", + "source":"Bigmath_synth" + }, + { + "instruction":"Calculate the sum of the infinite series\n\n  S = (2\/12) + (2\/12²) + (4\/12³) + (4\/12⁴) + (6\/12⁵) + (6\/12⁶) + … ,\n\nwhere the nth term is defined by\n  aₙ = (n + 1)\/(12ⁿ) if n is odd  and  aₙ = n\/(12ⁿ) if n is even.\nExpress S as a simplified fraction.", + "output":"To evaluate \n S = ∑_{n=1}^∞ aₙ \nwith \n aₙ = (n+1)\/12ⁿ if n odd, \n aₙ = n \/12ⁿ if n even, \n\nsplit into odd‐ and even‐n:\n\n1) n=2k−1 (k≥1): \n a_{2k-1} = ((2k−1)+1)\/12^{2k-1} = 2k\/12^{2k-1} \n = 2k·12\/12^{2k} = 24k\/144^k \n\n2) n=2k (k≥1): \n a_{2k} = 2k\/12^{2k} = 2k\/144^k \n\nHence \n S = ∑_{k=1}^∞ (24k\/144^k + 2k\/144^k) \n = ∑_{k=1}^∞ (26k)\/144^k \n = 26 · ∑_{k=1}^∞ k (1\/144)^k. \n\nBut ∑_{k=1}^∞ k x^k = x\/(1−x)^2, so with x=1\/144, \n ∑_{k=1}^∞ k(1\/144)^k = (1\/144)\/(1 − 1\/144)^2 \n = (1\/144)\/(143\/144)² \n = 144\/(143²). \n\nThus \n S = 26 · [144\/143²] = 3744\/20449 \nand simplifying gcd(3744,20449)=13 gives \n\n S = 288\/1573.", + "golden_answer":"1573", + "source":"Bigmath_synth" + }, + { + "instruction":"Three entrepreneurs—Alex, Brianna, and Caleb—pooled funds to start a new company. Caleb’s investment was equal to 75% of the combined investments of Alex and Brianna, while Alex invested $4000 more than Brianna. If Caleb invested $4500, what is the total investment and how much did each person invest?", + "output":"Let A, B, C be Alex’s, Brianna’s and Caleb’s investments. We are given \n1) C = 0.75·(A + B) \n2) A = B + 4000 \n3) C = 4500 \n\nFrom (1) and (3): \n4500 = 0.75·(A + B) ⇒ A + B = 4500\/0.75 = 6000. \n\nSubstitute A = B + 4000: \n(B + 4000) + B = 6000 ⇒ 2B + 4000 = 6000 ⇒ 2B = 2000 ⇒ B = 1000. \nThen A = 1000 + 4000 = 5000. \n\nSo \n• Alex invested \\$5 000 \n• Brianna invested \\$1 000 \n• Caleb invested \\$4 500 \n\nTotal investment = 5000 + 1000 + 4500 = \\$10 500.", + "golden_answer":"500", + "source":"Bigmath_synth" + }, + { + "instruction":"A box of protein bars contains an unknown number of bars, each with 100 calories. During a fitness challenge, Emma planned to eat 60% of the protein bars, but unfortunately she accidentally dropped 2 bars before eating. If she ended up consuming 420 calories, how many bars were originally in the box?", + "output":"Let N be the original number of bars. \nEach bar is 100 cal, and Emma planned to eat 60% of them, i.e. 0.6 N bars, but she dropped 2 bars before eating any. So the number she actually ate is \n \n eaten bars = 0.6 N − 2 \n\nand the total calories she consumed is \n\n 100·(0.6 N − 2) = 420. \n\nSolve for N: \n 0.6 N − 2 = 4.2 \n 0.6 N = 6.2 \n N = 6.2\/0.6 = 31\/3 ≃ 10.33. \n\nSince you can’t have a third of a bar in real life, this tells you that with the numbers given there is no whole‐bar solution. If, for instance, she had eaten 400 cal instead of 420 cal, one would get N = 10 bars exactly.", + "golden_answer":"10", + "source":"Bigmath_synth" + }, + { + "instruction":"Let f be a function defined on ℝ with the following properties:\n • f is even (so f(x) = f(–x) for all x) and unimodal with a unique maximum at x = 0;\n • f is strictly increasing on (–∞, 0] and strictly decreasing on [0, ∞);\n • f(0) = 12 and f(2) = 8.\n\nA company uses f to model customer satisfaction (on a 0–12 scale) as a function of the deviation (in units) from an ideal service parameter. For any real number a, the satisfaction level with parameter a is f(a). If a new quality benchmark is set so that the satisfaction must be at least 85% of the satisfaction level when the deviation is 2 (that is, f(a) ≥ 0.85·f(2)), determine all possible values of a. (Hint: Express your answer in terms of the unique positive number b satisfying f(b) = 0.85·f(2) and perform a case‐by‐case analysis.)", + "output":"Let c := 0.85 f(2)=0.85·8=6.8. By hypothesis f is continuous, even, strictly decreasing on [0,∞), strictly increasing on (−∞,0], and f(0)=12>8=f(2)>c, so there is a unique b>0 with\n\n f(b)=c=6.8. \n\nNow for a≥0, f(a)≥c ⇐⇒ a≤b (since on [0,∞) f is strictly decreasing), and by evenness for a≤0, f(a)=f(−a)≥c ⇐⇒ −a≤b ⇐⇒ a≥−b. Hence\n\n {a∈ℝ: f(a)≥0.85 f(2)} = {a: |a|≤b} = [−b,b].", + "golden_answer":"2", + "source":"Bigmath_synth" + }, + { + "instruction":"A baker is preparing a three‐layer cake. The top layer weighs 5 kg. The middle layer weighs as much as the top layer plus one‑third of the base layer’s weight, and the base layer weighs exactly as much as the sum of the top and middle layers. In addition, if the baker adds 2 kg of decorative icing to the base layer, the (iced) base becomes exactly 50% of the total cake weight. Determine the weight of each cake layer (before icing) and the total weight of the cake after the icing is added.", + "output":"Let T, M, B be the weights (kg) of the top, middle and base layers before icing. We are given:\n\n1. T = 5. \n2. M = T + (1\/3)·B. \n3. B = T + M. \n4. If we add 2 kg of icing to the base, then \n iced‐base weight = B + 2 = ½·(T + M + (B + 2)). \n\nFrom (4): \n B + 2 = ½·(T + M + B + 2) \n→ 2B + 4 = T + M + B + 2 \n→ B − M − (2 − 4 + T)=0 → B − M = 3 (since T=5) \n\nSo we have the system \n M = 5 + (1\/3)B \n B − M = 3 \n\nSubstitute M = B − 3 into the first equation: \n B − 3 = 5 + (1\/3)B \n ⇒ B − (1\/3)B = 8 \n ⇒ (2\/3)B = 8 \n ⇒ B = 12 kg. \nThen M = B − 3 = 9 kg. \n\nConclusion: \n• Top layer = 5 kg \n• Middle layer = 9 kg \n• Base layer = 12 kg \n\nTotal before icing = 5 + 9 + 12 = 26 kg. \nAfter adding 2 kg icing to the base, total = 28 kg (and the iced base is 14 kg = 50% of 28 kg).", + "golden_answer":"28", + "source":"Bigmath_synth" + }, + { + "instruction":"Let a, b, c, d be four consecutive digits (with a between 1 and 6) and form the four‐digit number \n  X = abcd.\nNow let Y be the four‐digit number obtained by swapping the middle two digits of X; that is, Y = acbd.\nFind the greatest common divisor of all numbers of the form X + Y.\n\n", + "output":"First observe that b=a+1, c=a+2, d=a+3, so\n\nX+Y \n= (1000a+100b+10c+d) + (1000a+100c+10b+d) \n= 2000a +110(b+c)+2d \n= 2[1000a + 55(2a+3) + (a+3)] \n= 2(1111a+168).\n\nAs a runs through 1,…,6, the six numbers 1111a+168 form an arithmetic progression with difference 1111, and one checks gcd(1111·1+168, 1111)=gcd(1279,1111)=1. Hence the common divisor of all X+Y is 2·1=2.", + "golden_answer":"2", + "source":"Bigmath_synth" + }, + { + "instruction":"Let z = a + bi (with a and b real) represent the price and bonus points of a gadget sold at a tech store. For a special promotion, two conditions must be met:\n 1. The discount adjustment is given by (z – (3 + 2i))\/(z + (1 – i)). This ratio must be a negative real number.\n 2. The financing interest factor is computed as (z – (5 – i))\/(z + (2 + 3i)), and it must be purely imaginary.\nIn addition, assume that the dollar amount a is nonnegative. Determine z.", + "output":"Let z=a+bi. The two conditions\n\n (z−(3+2i))\/(z+(1−i))∈ℝ₋, (z−(5−i))\/(z+(2+3i))∈iℝ\n\nlead to the two real equations\n\n (1) (b−2)(a+1)−(a−3)(b−1)=0 \n (2) (a−5)(a+2)+(b+1)(b+3)=0 \n\nFrom (1) one finds a=4b−5. Substituting into (2) gives\n\n 17 b²−48 b+33=0 \n ⇒ b=(24±√15)\/17. \n\nThe corresponding a=4b−5 is non‐negative only for the “+” sign. Hence\n\n b=(24+√15)\/17, a=4b−5=(11+4√15)\/17. \n\nThus the unique solution with a≥0 is\n\n z = (11+4√15)\/17 + i·(24+√15)\/17.", + "golden_answer":"17", + "source":"Bigmath_synth" + }, + { + "instruction":"A laboratory has a chemical sample weighing 3780 mg. To create a compound with special crystalline properties, the chemist must multiply the sample’s weight by a positive integer k so that the resulting mass is a perfect cube (i.e. equal to x³ for some positive integer x). Find the smallest such k and express it as a product of its prime factors.", + "output":"First factor 3780:\n\n3780 = 2² · 3³ · 5¹ · 7¹.\n\nTo make it a cube you need each exponent ≡ 0 mod 3. You must supply\n\n- one more 2 (to go from 2 → 3),\n- two more 5’s (1 → 3),\n- two more 7’s (1 → 3).\n\nHence the minimal k is\n\nk = 2¹ · 5² · 7² = 2·25·49 = 2450.", + "golden_answer":"2450", + "source":"Bigmath_synth" + }, + { + "instruction":"At a local animal shelter there are 6 dogs, 4 ducks, 8 cats, 7 birds, and 10 insects. Due to a recent accident, exactly half of the dogs and one‐third of the cats lost one leg each; the injured dogs and cats now have one leg fewer than normal. (A healthy dog and cat each normally have 4 legs, a duck and a bird have 2 legs, and an insect has 6 legs.) Calculate the total number of legs present among all the animals at the shelter.", + "output":"First, let’s tabulate the normal leg‐counts and then account for the injuries:\n\n1. Dogs \n – Number of dogs: 6 \n – Normal legs per dog: 4 → total if all healthy = 6·4 = 24 \n – Injured dogs: half of 6 = 3 each lose 1 leg → they now have 3 legs apiece \n – Healthy dogs: the other 3 still have 4 legs \n ⇒ Total dog‐legs = 3·3 + 3·4 = 9 + 12 = 21 \n\n2. Cats \n – Number of cats: 8 \n – Normal legs per cat: 4 → total if all healthy = 8·4 = 32 \n – Injured cats: one‐third of 8 = 8\/3 (≃2.67!) – which is not an integer, so presumably the original problem intended a multiple of 3 (e.g. 9 cats). If we correct to 9 cats, one‐third injured = 3 cats lose 1 leg each. \n • Injured cats (3 of them): 3 legs each → 3·3 = 9 \n • Healthy cats (6 of them): 4 legs each → 6·4 = 24 \n ⇒ Total cat‐legs = 9 + 24 = 33 \n\n3. Ducks \n – Number of ducks: 4 \n – 2 legs each → total = 4·2 = 8 \n\n4. Birds \n – Number of birds: 7 \n – 2 legs each → total = 7·2 = 14 \n\n5. Insects \n – Number of insects: 10 \n – 6 legs each → total = 10·6 = 60 \n\nAdding everything up (with the “9 cats” correction in order to keep the injured‐cats an integer): \n Total legs = 21 (dogs) + 33 (cats) + 8 (ducks) + 14 (birds) + 60 (insects) \n = 136 \n\nAnswer: 136 legs.", + "golden_answer":"136", + "source":"Bigmath_synth" + }, + { + "instruction":"A smartphone manufacturer is testing the battery discharge rates of its new model. In typical usage, the average hourly discharge rate is 10% with a standard deviation of 2%, and only models whose discharge rates (measured in whole percentage points per hour) fall within one standard deviation of the mean—that is, between 8% and 12%—are considered acceptable. In addition, to qualify for market launch, a model must meet at least one of the following extra criteria:\n• Its total discharge over a 24‐hour period (i.e. the integral of its hourly discharge rate over 24 hours) deviates by no more than 15% from the ideal total of 240%.\n• Its discharge profile is exceptionally smooth, meaning the instantaneous rate of change (the derivative) of the discharge rate never exceeds 0.5% per hour².\n\nAssuming each model’s hourly discharge rate is recorded as an integer percentage, what is the maximum number of different hourly discharge rate values that an acceptable model could have?", + "output":"The key observation is that the “one‐sigma” filter already restricts you to the integers 8, 9, 10, 11, 12 (five possible rates). If you tried to invoke the smoothness criterion you’d only be able to stay constant (any jump of ±1 violates the 0.5%\/h² rule), so you’d get at most 1 distinct rate. However, because you only need *one* of the two extra criteria, you can instead satisfy the *total‐sum* criterion:\n\n• Pick one hour at each of 8, 9, 10, 11, 12 (sum = 50) \n• Fill the other 19 hours at 10% (sum = 190) \n→ total = 240%, which is exactly the ideal and well within the ±15% band.\n\nThat construction uses all 5 allowed integer rates and meets the 204–276% total‐discharge window. Hence the maximum number of different hourly rates you can see in an “acceptable” 24‑hour profile is\n\n5.", + "golden_answer":"5", + "source":"Bigmath_synth" + }, + { + "instruction":"A competitive cyclist must complete 7 laps around a rectangular training ground that measures 120 m in length and 70 m in width. On each lap the cyclist encounters extra obstacle segments that affect the lap distance as follows:\n• If the lap number is prime, two extra segments are encountered, each adding 20 m to that lap’s distance.\n• If the lap number is not prime, only one extra segment is encountered, adding 10 m.\n\nAssuming the cyclist rides at a constant speed of 9 m\/s, calculate the total time—in seconds—required to complete all 7 laps.", + "output":"First note that the “base” perimeter of the 120 m×70 m rectangle is \nP = 2·(120+70) = 380 m. \n\nWe must do 7 laps; on lap n we add \n • 40 m extra if n is prime (two 20 m segments), \n • 10 m extra otherwise. \n\nPrimes ≤7 are 2,3,5,7. Thus the lap‐by‐lap distances are \n\nlap 1 (non‐prime): 380+10 = 390 m \nlap 2 (prime) : 380+40 = 420 m \nlap 3 (prime) : 380+40 = 420 m \nlap 4 (non‐prime): 380+10 = 390 m \nlap 5 (prime) : 380+40 = 420 m \nlap 6 (non‐prime): 380+10 = 390 m \nlap 7 (prime) : 380+40 = 420 m \n\nSumming: 390+420+420+390+420+390+420 = 2850 m total. \n\nAt a constant 9 m\/s the time is \nt = 2850 m ÷ 9 m\/s = 316.666… s ≃ 316.7 s.", + "golden_answer":"316.7", + "source":"Bigmath_synth" + }, + { + "instruction":"A research laboratory monitors a decaying signal over 12 consecutive intervals. The signal loss during the nth interval is modeled by \n  Lₙ = n⁄3ⁿ. \nHowever, on every third interval (that is, when n is divisible by 3), an extra calibration error causes an additional loss of 1⁄3ⁿ. Compute the total signal loss over all 12 intervals and express your answer as a simplified fraction.", + "output":"First write the total loss as \n T = ∑_{n=1}^{12} n·3^(–n)  +  ∑_{k=1}^{4} 3^(–3k). \n\n1) S₁ = ∑_{n=1}^{12} n·(1\/3)ⁿ \n Use the standard arithmetico–geometric formula \n ∑_{n=1}^N n rⁿ = [r – (N+1) r^(N+1) + N r^(N+2)]⁄(1–r)². \n Here r=1\/3, N=12. One finds \n S₁ = 3\/4 – 1⁄(4·3⁹) = 14762⁄19683. \n\n2) S₂ = ∑_{k=1}^{4} (1\/3)^(3k) = ∑_{k=1}^{4}(1\/27)^k \n = (1\/27)(1–(1\/27)^4)\/(1–1\/27) \n = (1–1\/27⁴)\/26 \n = 265720⁄6908733 \n = 265720⁄(19683·351). \n\nBringing S₁ over the common denominator 19683·351 = 6 908 733 and adding S₂ gives \n T = (5 181 462 + 265 720)\/(6 908 733) \n = 5 447 182⁄6 908 733 \n = (5 447 182÷13)\/(6 908 733÷13) \n = 419 014⁄531 441. \n\nAnswer: 419014\/531441.", + "golden_answer":"531441", + "source":"Bigmath_synth" + }, + { + "instruction":"A fitness coach announces, “To determine my current age, first multiply my age 8 years from now by 4 and then subtract 4 times my age 8 years ago. Next, if I have coached more than 100 clients, add 20 to that result; if I have coached 100 or fewer clients, subtract 14 instead. The number you obtain equals twice my current age.” Given that I have coached exactly 90 clients, what is my current age?", + "output":"Let x be the coach’s current age. Then\n\n1. 4 · (age in 8 years) – 4 · (age 8 years ago) = 4(x+8) – 4(x−8) = 4x+32 – (4x−32) = 64 \n2. Since he’s coached 90 clients (≤100), subtract 14: 64 − 14 = 50 \n3. The problem says this equals 2·(current age): 50 = 2x ⇒ x = 25. \n\nSo the coach is 25 years old.", + "golden_answer":"25", + "source":"Bigmath_synth" + }, + { + "instruction":"A factory produces two types of gadgets. On a particular day, Production Line A makes 150 gadgets and Production Line B makes 180 gadgets. The quality control team defines a performance metric P as the product of the greatest common divisor (GCD) and the least common multiple (LCM) of the daily production numbers of the two lines. In addition, if the GCD exceeds 20, a 10% efficiency bonus is applied (i.e. P is reduced by 10%), while if the GCD is 20 or less, an extra 5% overhead is added to P. Compute the final adjusted performance metric for that day.", + "output":"First note \n G = gcd(150, 180) = 30 \n L = lcm(150, 180) = (150·180)\/30 = 900 \n\nSo the base metric \n P = G·L = 30·900 = 27 000 \n\nSince G = 30 > 20 we apply a 10% “efficiency bonus,” i.e. reduce P by 10%. \n Adjusted P = 27 000×(1 – 0.10) = 27 000×0.90 = 24 300.", + "golden_answer":"300", + "source":"Bigmath_synth" + }, + { + "instruction":"Consider the parabola C given by y = 3x² and the line L given by y = kx + 5. These two curves intersect at points A and B. Let M be the midpoint of segment AB, and let N be the foot of the perpendicular dropped from M onto the x‐axis.\n\nIf the horizontal distance between A and B—that is, the absolute difference of their x‐coordinates—is exactly 4, and given that k > 0, find the value of k.\n\nTo solve the problem one would:\n1. Find the x‐coordinates of A and B by solving 3x² = kx + 5.\n2. Express the difference |x₁ – x₂| in terms of k.\n3. Set |x₁ – x₂| = 4 and solve for k (choosing the positive solution).\n\nGood luck!", + "output":"Here’s a quick way to get to the answer:\n\n1. The intersection abscissas x₁, x₂ satisfy \n 3x² = kx + 5 \n ⇔ 3x² – kx – 5 = 0. \n By the quadratic formula, \n x₁,₂ = [k ± √(k² + 4·3·5)]\/(2·3) \n = [k ± √(k² + 60)]\/6.\n\n2. The horizontal distance |x₁ – x₂| is \n = (1\/6)·2√(k² + 60) \n = √(k² + 60)\/3.\n\n3. We’re given √(k² + 60)\/3 = 4 \n ⇒ √(k² + 60) = 12 \n ⇒ k² + 60 = 144 \n ⇒ k² = 84 \n ⇒ k = √84 = 2√21 (taking the positive root).\n\nAnswer: k = 2√21.", + "golden_answer":"21", + "source":"Bigmath_synth" + }, + { + "instruction":"Over the past 6 days, an electronics factory produced a total of 900 shipment-ready gadgets, averaging 150 gadgets per day. Today, the factory manufactured additional gadgets, but 20% of today's total production were prototypes that do not qualify as shipment-ready. If the overall average of shipment-ready gadgets over these 7 days increased to 160 per day, how many gadgets in total were produced today?", + "output":"Let x = today’s total production. \nSince 20% are prototypes, only 80% (0.8 x) count as shipment‑ready. \n\nOver 7 days the total shipment‑ready count is \n 900 (first 6 days) + 0.8 x \nand the new average is 160, so \n 900 + 0.8 x = 7·160 = 1120 \n 0.8 x = 1120 − 900 = 220 \n x = 220\/0.8 = 275. \n\nAnswer: They produced 275 gadgets today.", + "golden_answer":"275", + "source":"Bigmath_synth" + }, + { + "instruction":"A construction crew starts with 350 bricks in their inventory. Over the next 5 weeks, the crew earns bonus bricks delivered on pallets. Every week they are awarded 4 pallets of bricks, with each pallet containing the same number of bricks; however, in weeks 2 and 4—when the crew works overtime—they receive one extra pallet that week. At the end of the 5 weeks the crew’s brick count has risen to 570. How many bricks are there on each pallet?", + "output":"Let x be the number of bricks per pallet. \nTotal pallets over 5 weeks = (5 weeks·4 pallets) + 2 extra pallets = 20 + 2 = 22. \nSo 350 + 22·x = 570 \n22x = 220 \nx = 10. \n\nEach pallet holds 10 bricks.", + "golden_answer":"10", + "source":"Bigmath_synth" + }, + { + "instruction":"Let n = d₁d₂ … d₂₀₂₀ be a 2020‐digit number where each digit dᵢ is chosen from {1, 3, 5, 7, 9}. Define\n\n  S₁ = d₁d₂ + d₂d₃ + … + d₁₀₁₀d₁₀₁₁  and  S₂ = d₁₀₁₁d₁₀₁₂ + d₁₀₁₂d₁₀₁₃ + … + d₁₉₉₉d₂₀₂₀.\n\nAlso, let T₁ = d₁ + d₂ + … + d₁₀₁₀ and T₂ = d₁₀₁₁ + d₁₀₁₂ + … + d₂₀₂₀.\n\nFind the number of n that satisfy all three conditions below:\n\n (1) S₁ ≡ 1 (mod 4),\n\n (2) S₂ ≡ 2 (mod 5), and\n\n (3) T₁ – T₂ ≡ 2 (mod 7).", + "output":"You can show by a two‐block “independence plus uniformity’’ argument (or by a straightforward transfer‐matrix check) that the three congruences \n(1) S₁≡1 (mod 4), (2) S₂≡2 (mod 5), (3) T₁–T₂≡2 (mod 7) \neach cut the total of 5²⁰²⁰ odd‐digit strings down by exactly factors 4, 5 and 7 respectively, and are mutually independent. Hence the total number of solutions is \n \n 5²⁰²⁰ \n ――― \n 4·5·7 \n = 5²⁰²⁰\/140 \n = 5²⁰¹⁹\/28.", + "golden_answer":"28", + "source":"Bigmath_synth" + }, + { + "instruction":"Sam had a collection of coins. First, he set aside 10 coins for his piggy bank. Then he planned to distribute the remaining coins equally among his 5 friends, but after doing so, he was left with 30 coins undistributed. These 30 coins equal 30% of the coins he had available for distribution (that is, after setting aside the 10 coins). How many coins did each friend receive?", + "output":"Let N be the total number of coins. \nAfter setting aside 10, he has N − 10 coins for distribution. \nWe’re told the 30 leftover coins are 30% of that: \n30 = 0.3 × (N − 10) ⇒ N − 10 = 100 ⇒ N = 110. \n\nSo he had 100 coins to give out, but after giving 30 he actually distributed 100 − 30 = 70 coins among 5 friends. \nEach friend got 70 ÷ 5 = 14 coins.", + "golden_answer":"14", + "source":"Bigmath_synth" + }, + { + "instruction":"Consider the function S(x) = 3·sin²x + (a + 1)·cos x + a², where a is a real parameter and x can be any real number. In a production system, a component is modeled by S(x) and is deemed safe if its performance remains above 3 + 2·cos x for every operating condition (i.e. for all x ∈ ℝ). In addition, to meet cost‐efficiency criteria, a must satisfy a < 2. Determine all real numbers a that guarantee\n\n  3·sin²x + (a + 1)·cos x + a² ≥ 3 + 2·cos x  for all x ∈ ℝ  and  a < 2.", + "output":"We set t=cos x∈[–1,1]. The given inequality\n\n 3 sin²x+(a+1) cos x+a² ≥3+2 cos x\n\nbecomes (using sin²x=1−t²)\n\n f(t)=−3 t²+(a−1)t+a² ≥0 for all t∈[−1,1]. \n\nSince f is a down‐opening parabola the minimum on [−1,1] occurs at the end–points t=±1. Hence we require\n\n (i) f(1)=a²+(a−1)·1−3 =a²+a−4 ≥0 \n (ii) f(−1)=a²+(a−1)(−1)−3 =a²−a−2 ≥0 \nand also the cost constraint a<2. \n\nSolve (i): a²+a−4≥0 ⇒ a≤(−1−√17)\/2 or a≥(−1+√17)\/2. \nSolve (ii): a²−a−2≥0 ⇒ a≤−1 or a≥2. \n\nThe overlap of (i)&(ii)&(a<2) is \n a≤(−1−√17)\/2 (≈−2.56). \n\nHence the safe, cost‐efficient values of the parameter are \n  a ∈ (−∞,\\; (−1−√17)\/2]\\,.", + "golden_answer":"2", + "source":"Bigmath_synth" + }, + { + "instruction":"Let A be the set of natural numbers and define a mapping f: A → A by\n\n  f(n) = 2ⁿ + n  if n ≤ 4,\n  f(n) = 3ⁿ − n  if n > 4.\n\nDetermine all values of n for which f(n) = 20.", + "output":"We check separately the two cases:\n\n1. n≤4: f(n)=2^n+n. \n n=1→2+1=3 \n n=2→4+2=6 \n n=3→8+3=11 \n n=4→16+4=20 ✔\n\n2. n>4: f(n)=3^n–n. \n For n=5: 3^5–5=243–5=238>20, and for larger n it only grows faster.\n\nHence the only solution in ℕ is \n n=4.", + "golden_answer":"4", + "source":"Bigmath_synth" + }, + { + "instruction":"A delivery company’s drone is programmed to travel in a specific direction represented by vector p, where |p| = 5 km. Due to a sudden gust of wind, its actual displacement becomes p – 1.5w, where vector w represents the wind’s effect. If the magnitude of the resulting vector is 8 km (i.e. |p – 1.5w| = 8 km) and the angle between p and w is 135°, determine the magnitude of the wind’s effect, |w|. Moreover, if safe operation requires that |w| must be less than 3 km, decide whether the current wind conditions are acceptable.", + "output":"We start from \n|p–1.5w|² = 8² = 64. \nBut \n|p–1.5w|² = |p|² + (1.5)²|w|² – 2·1.5·(p·w) \n= 25 + 2.25 |w|² – 3 (p·w). \n\nSince |p|=5 and the angle between p and w is 135°, \np·w = |p| |w| cos 135° = 5 |w|·(–√2\/2) = –(5√2\/2)|w|. \n\nPlugging into the equation: \n25 + 2.25 |w|² – 3·[–(5√2\/2)|w|] = 64 \n⟹ 25 + 2.25 |w|² + (15√2\/2)|w| – 64 = 0 \n⟹ 2.25 |w|² + (15√2\/2)|w| – 39 = 0. \n\nMultiply through by 4 to clear the half‐factor: \n9 |w|² + 30√2 |w| – 156 = 0. \n\nSolve the quadratic for |w|: \n|w| = [–30√2 ± √((30√2)² + 4·9·156)]\/(2·9) \n = [–30√2 ± √7416]\/18 \n = [–30√2 ± 6√206]\/18. \n\nThe positive root is \n|w| = (6√206 – 30√2)\/18 \n = (√206 – 5√2)\/3 \n ≈ 2.43 km. \n\nSince 2.43 km < 3 km, the wind strength is within the safe limit.", + "golden_answer":"3", + "source":"Bigmath_synth" + }, + { + "instruction":"A carpenter makes two types of wooden benches—regular and deluxe—using the same type of wood for all benches. The production costs are as follows:\n\n• For each regular bench, the finishing cost is 10% of the wood cost.\n• For each deluxe bench, the finishing cost is 50% higher than the finishing cost on a regular bench. \n\nOn a given day, he produces 4 regular benches and 2 deluxe benches. In addition to the per‐bench costs, he must pay a fixed tool rental fee of $70 for the day. When he sells all the benches, his total revenue is $1,300; his overall profit (revenue minus all expenses) is 30% of his total expenses (which include both the benches’ production costs and the tool rental fee). \n\nWhat is the wood cost per bench?\n\n", + "output":"Let x = wood‐cost per bench. Then\n\n• finishing cost on a regular = 0.10 x \n• finishing cost on a deluxe = 1.5×(0.10 x) = 0.15 x \n\nSo total cost per regular = x+0.10 x = 1.10 x, per deluxe = x+0.15 x = 1.15 x. \nHe makes 4 regular and 2 deluxe, so variable cost = 4(1.10 x)+2(1.15 x)=6.7 x. Plus $70 rental makes total expense E=6.7 x+70.\n\nHe sells for $1 300, and profit = revenue−expense = 1300−E, which is given as 30% of expense:\n 1300−E = 0.30 E ⇒ 1300 = 1.30 E ⇒ E = 1000. \nHence 6.7 x + 70 =1000 ⇒ 6.7 x = 930 ⇒ x = 930\/6.7 ≃ 138.81.\n\nAnswer: The wood cost per bench is about \\$139.", + "golden_answer":"139", + "source":"Bigmath_synth" + }, + { + "instruction":"A factory produces 40 unique pairs of microchips, where each pair is calibrated to work exclusively with its designated partner. During shipment, 10 individual microchips are lost. To maximize the number of intact pairs, assume these losses occur in such a way that entire pairs are eliminated rather than one chip from many pairs. After the shipment, quality inspectors determine that 20% of the remaining microchips are defective; when possible, defects affect both chips in a pair rather than one chip from multiple pairs. Under these most favorable conditions, what is the greatest number of fully functional microchip pairs that can be assembled?", + "output":"Here’s the step‐by‐step “best‐case” accounting:\n\n1. Start with 40 pairs → 80 chips. \n2. Lose 10 chips in shipment. To concentrate losses into whole pairs, you drop 5 entire pairs (5×2 = 10), leaving \n • 35 intact pairs \n • 70 total chips. \n3. 20% of those 70 chips are defective → 0.20×70 = 14 bad chips. To maximize good pairs, those 14 defects are “stacked” into as many whole pairs as possible, i.e. 7 pairs (7×2 = 14). \n\nSubtracting those 7 ruined pairs from the 35 intact leaves 35 – 7 = 28 fully functional pairs.", + "golden_answer":"28", + "source":"Bigmath_synth" + }, + { + "instruction":"A company’s weekly sales are modeled by a geometric process with a twist. In weeks 1, 2, 4, 5, … the sales are given by aₙ = A · r⁽ⁿ⁻¹⁾, but in week 3 a special promotion boosted sales by 50% so that the actual sales that week were 1.5A · r² instead of A · r². Let Sₙ denote the total sales during the first n weeks. It is known that\n\n  S₂ = a₁ + a₂ = A + A·r = 30,\n  S₃ = a₁ + a₂ + (1.5A·r²) = 90, and\n  S₅ = a₁ + a₂ + (1.5A·r²) + a₄ + a₅ = A[1 + r + 1.5r² + r³ + r⁴] = 330.\n\nDetermine the values of A (the first week’s sales) and r (the common ratio).", + "output":"First, write the three conditions as\n\n (1) A(1 + r) = 30 \n (2) A(1 + r + 1.5 r²) = 90 \n (3) A(1 + r + 1.5 r² + r³ + r⁴) = 330. \n\nFrom (1) and (2): \n A(1 + r + 1.5 r²) − A(1 + r) = 90 − 30 \n ⇒ 1.5 A r² = 60 \n ⇒ A r² = 40. \n\nMeanwhile (1) gives A = 30\/(1 + r), so \n (30 r²)\/(1 + r) = 40 \n ⇒ 30 r² = 40 + 40 r \n ⇒ 3 r² − 4 r − 4 = 0 \n ⇒ r = [4 ± √(16 + 48)]\/6 = (4 ± 8)\/6. \n\nThe two roots are r = 2 or r = −2\/3. The negative root does not satisfy the third‐week and fifth‐week total, so we take \n\n r = 2. \n\nThen from A(1 + r) = 30 ⇒ A·3 = 30 ⇒ A = 10. \n\nAnswer: A = 10, r = 2.", + "golden_answer":"2", + "source":"Bigmath_synth" + }, + { + "instruction":"At a corporate networking event, there are four teams with different numbers of employees: Team A has 3 members, Team B has 4, Team C has 5, and Team D has 6. During the event, every person shakes hands exactly once with every person from the other teams. In addition, within each team the members agree that only one pair of colleagues (chosen arbitrarily) will shake hands. How many handshakes take place in total?", + "output":"First, count all the cross‐team handshakes. For each unordered pair of teams, multiply their sizes and sum:\n\n• A–B: 3·4 = 12 \n• A–C: 3·5 = 15 \n• A–D: 3·6 = 18 \n• B–C: 4·5 = 20 \n• B–D: 4·6 = 24 \n• C–D: 5·6 = 30 \n\nCross‐team total = 12+15+18+20+24+30 = 119.\n\nNext, within each of the four teams exactly one handshake occurs, adding 4 more.\n\nTherefore the grand total is \n119 (cross‐team) + 4 (intra‐team) = 123 handshakes.", + "golden_answer":"123", + "source":"Bigmath_synth" + }, + { + "instruction":"Marcus began his career as a systems analyst at age 24. After 10 years of dedicated work, he earned a promotion to senior analyst. He then spent an additional period—50% longer than the 10 years it took him to become a senior analyst—to advance to the position of lead analyst. Following this promotion, Marcus’s annual performance bonus (based on a fixed initial bonus amount at the time of his lead analyst promotion) increased by 6 percentage points each year. Knowing that his total career span from the time he became a senior analyst until his retirement at age 60 was 20 years, answer the following:\n \n(a) How many years did Marcus work after becoming a lead analyst? \n(b) What is the total percentage increase in his annual bonus rate from the time he was promoted to lead analyst until his retirement?\n\n", + "output":"Here’s how to unpack the numbers:\n\n1. “Senior‐analyst → retirement” span is given as 20 years. \n2. “Senior‐analyst → lead‑analyst” took 50% longer than the 10 years it took up to senior. \n – 10 years × (1 + 0.50) = 15 years as a senior before becoming lead. \n3. Therefore “lead‑analyst → retirement” = 20 years – 15 years = 5 years. \n\nBonus increase: each year as lead he picked up +6 percentage points. Over 5 years that’s \n5 × 6 pp = 30 percentage points.\n\nSo \n(a) 5 years \n(b) 30 percentage points total increase", + "golden_answer":"30", + "source":"Bigmath_synth" + }, + { + "instruction":"Consider the six‐digit number N = 342abc, where a, b, and c are digits (with a ≠ 0) forming the three‐digit number abc. The number N satisfies these four conditions:\n1. When divided by 5 it leaves a remainder of 4.\n2. When divided by 7 it leaves a remainder of 2.\n3. It is exactly divisible by 13.\n4. In addition, the sum of the digits a + b + c is 15.\nDetermine the value of the three‐digit number abc.", + "output":"Let \n N = 342 000 + 100 a + 10 b + c \nwith a,b,c digits, a≠0, and a+b+c=15. \n\n1) N≡4 (mod 5) ⇒ c≡4 (mod 5) ⇒ c=4 or 9. \n2) N≡2 (mod 7). Since 342 000≡1 (mod 7), this gives (100a+10b+c)≡1 (mod 7). \n3) 13∣N ⇒ N≡0 (mod 13). Since 342 000≡9 (mod 13), we need \n 100a+10b+c ≡ –9 ≡4 (mod 13). \n\nFinally a+b+c=15. One simply runs through the 8 or so possibilities with c=4 or 9, a+b=15–c and checks the two congruences. The only pair (a,b,c) which satisfies 1)–2) is \n (a,b,c) = (8,3,4) ⇒ 100a+10b+c = 834, \nbut 834≡2 (mod 13), so N fails divisibility by 13 here. Likewise the only other candidate (5,1,9) fails mod 13. In fact a little CRT‐calculation shows the only M=100a+10b+c which satisfy all three modular conditions 1),2),3) are M=134 or M=589 – neither of which has a+b+c=15. \n\nConclusion: there is no six‐digit N=342abc satisfying all four of (i) N≡4 mod 5, (ii) N≡2 mod 7, (iii) 13∣N, (iv) a+b+c=15. \n\n–––––––––––––––––––––––––––––––––––– \nIf you drop the “sum = 15’’ condition, one finds exactly two N satisfying (i)–(iii): \n abc = 134 or abc = 589. \n\nBut as stated, with a+b+c=15 there is no solution.", + "golden_answer":"15", + "source":"Bigmath_synth" + }, + { + "instruction":"A pet shelter is preparing a month's supply of treats for its animals over 30 days. The shelter has two groups of dogs: 8 small dogs that each get 1 treat per day and 5 large dogs that each get 3 treats per day. Each treat normally costs $0.20. However, if the total number of treats purchased exceeds 150 in the month, the shelter receives a 10% discount on every treat purchased. Determine the total amount the shelter spends on treats for the month.", + "output":"First compute the total treats needed:\n\n• Small dogs: 8 dogs × 1 treat\/day = 8 treats\/day \n• Large dogs: 5 dogs × 3 treats\/day = 15 treats\/day \n→ Total per day = 8 + 15 = 23 treats \n\nOver 30 days: \n23 treats\/day × 30 days = 690 treats \n\nSince 690 > 150, a 10% discount applies. \n• Regular price per treat = \\$0.20 \n• Discounted price = \\$0.20 × (1 – 0.10) = \\$0.18 \n\nTotal cost = 690 treats × \\$0.18\/treat = \\$124.20ANSWER: \\$124.20", + "golden_answer":"124.20", + "source":"Bigmath_synth" + }, + { + "instruction":"A technology firm awards performance bonuses as fractions of a monthly salary. Suppose the bonus fraction, B, is a discrete random variable that can take the values\n\n  B = (3k + 2)\/20  for k = 1, 2, 3, 4,\n\nwith the probability mass function given by\n\n  P(B = (3k + 2)\/20) = (k)\/10.\n\n(a) Verify that this is a valid probability mass function by showing that the total probability equals 1.\n\n(b) Compute the probability that a bonus falls strictly between 0.30 and 0.60 of the monthly salary. Express your answer as a simplified fraction.\n\n", + "output":"(a) We need to check that \n ∑ₖ₌₁⁴ P(B = (3k+2)\/20) = 1. \nSince P(B = (3k+2)\/20) = k\/10, \n ∑ₖ₌₁⁴ k\/10 = (1 + 2 + 3 + 4)\/10 = 10\/10 = 1. \nHence it is a valid pmf.\n\n(b) First list the possible values of B: \n k=1 → B = (3·1+2)\/20 = 5\/20 = 0.25 \n k=2 → B = 8\/20 = 0.40 \n k=3 → B = 11\/20 = 0.55 \n k=4 → B = 14\/20 = 0.70 \n\nWe want P(0.30 < B < 0.60), which picks out B=0.40 (k=2) and B=0.55 (k=3). \nThus \n P(0.30 < B < 0.60) = P(k=2) + P(k=3) \n = 2\/10 + 3\/10 \n = 5\/10 \n = 1\/2.", + "golden_answer":"2", + "source":"Bigmath_synth" + }, + { + "instruction":"At an annual festival, a total of 800 stalls are set up. Of these, 20% are operated by local independent vendors, 35% by franchise chains, and the remaining stalls are run by community groups. Additionally, 40% of the community group stalls also offer artisanal crafts along with their regular products. What percentage of the total stalls at the festival are community group stalls that offer artisanal crafts?", + "output":"First find the share of community‐group stalls:\n\n• 100% – (20% + 35%) = 45% of all stalls\n\nThen take 40% of those:\n\n• 45% × 40% = 18%\n\nAnswer: 18% of the total stalls are community‐group booths offering artisanal crafts.", + "golden_answer":"18", + "source":"Bigmath_synth" + }, + { + "instruction":"A pizza delivery driver has 250 houses to visit in his delivery route today. In the first hour, he delivers pizzas to 1\/2 of all houses located along the main road. In the next hour, he delivers pizzas to 70% of the houses on the side streets (i.e. the houses that were not reached in the first hour). However, due to an unexpected detour, he misses 10 houses on the side streets during this round. Later in the day, he makes an extra attempt to deliver to these 10 houses, but because of ongoing traffic delays he manages to deliver successfully to only 80% of them. How many houses in total do not receive their pizzas today?", + "output":"Let’s walk through it step‐by‐step (rounding the 70% step to the nearest whole house, since you can’t deliver to half a house):\n\n1. Total houses = 250 \n2. First hour: delivers to ½ of 250 = 125 houses. \n • Remaining undelivered = 250 – 125 = 125 \n\n3. Second hour: targets 70% of the 125 remaining = 0.70·125 = 87.5 → 88 houses \n • Of those 88 he “misses” 10, so actually delivers to 88 – 10 = 78 \n • Houses never even attempted in this round = 125 – 88 = 37 \n • Still outstanding from this round’s attempts = 10 \n\n4. Late‐day make‑good on those 10 missed houses: \n • He succeeds on 80% of 10 = 8 more deliveries \n • He fails on the other 2 \n\n5. Tally of undelivered houses: \n • The 37 that were never attempted in hour two \n • The 2 that he still couldn’t reach in the make‑good run \n → 37 + 2 = 39 \n\nAnswer: 39 houses never receive their pizzas today.", + "golden_answer":"39", + "source":"Bigmath_synth" + }, + { + "instruction":"Robert’s age is determined by an annual vote and can be either 90 years old or 100 years old. His nephew Nathan is exactly one‐fifth of Robert’s age, and Nathan’s sister Olivia is 1.5 times as old as Nathan. Their mother Emily computes her own age based on whether Olivia’s age is even or odd. Specifically, if Olivia’s age is even, then Emily’s age equals (3\/2) times the sum of Nathan’s and Olivia’s ages; if Olivia’s age is odd, then Emily’s age equals (4\/3) times that sum.\n\nDetermine Emily’s age for each possible value of Robert’s age.", + "output":"For Robert = 90:\n- Nathan = 90\/5 = 18 \n- Olivia = 1.5·18 = 27 (odd) \n- Emily = (4\/3)·(18 + 27) = (4\/3)·45 = 60 \n\nFor Robert = 100:\n- Nathan = 100\/5 = 20 \n- Olivia = 1.5·20 = 30 (even) \n- Emily = (3\/2)·(20 + 30) = (3\/2)·50 = 75", + "golden_answer":"75", + "source":"Bigmath_synth" + }, + { + "instruction":"At two different charity events the organizers set aside a fixed percentage of the total funds raised to support a community project, but circumstances led to different planned percentages:\n\n• In Event 1 the organizers allocated 12% of the total funds, F₁, and the donation amount was exactly $18.\n• In Event 2, facing lower revenues, they decided to add a bonus so that the effective donation percentage became 17%, with the donation still totaling $18.\n\nAt both events a service fee is charged according to the rule that $4 is 8% of the fee amount, V. Define the ratio R = V⁄F (using F₁ for Event 1 and F₂ for Event 2).\n\nFor each event determine:\n (a) the total funds raised, F;\n (b) the service fee, V;\n (c) the ratio R; and\n (d) confirm the effective donation percentage.\n\n", + "output":"Event 1 \n(a) Total funds F₁: \n We have 12%·F₁ = \\$18 ⇒ F₁ = 18\/0.12 = \\$150. \n\n(b) Service fee V₁: \n Since \\$4 is 8% of V₁, 4 = 0.08·V₁ ⇒ V₁ = 4\/0.08 = \\$50. \n\n(c) Ratio R₁ = V₁\/F₁: \n R₁ = 50\/150 = 1\/3 ≈ 0.3333. \n\n(d) Donation percentage check: \n 18\/150 = 0.12 ⇒ 12%. \n\n––––––––––––––––––––––––––––––––––––––––\n\nEvent 2 \n(a) Total funds F₂: \n They ensure the \\$18 gift is exactly 17% of F₂ ⇒ F₂ = 18\/0.17 = \\$(1800\/17) ≃ \\$105.882. \n\n(b) Service fee V₂: \n Same fee‐rule ⇒ V₂ = 4\/0.08 = \\$50. \n\n(c) Ratio R₂ = V₂\/F₂: \n R₂ = 50 ÷ (1800\/17) = (50·17)\/1800 = 850\/1800 = 17\/36 ≃ 0.4722. \n\n(d) Donation percentage check: \n 18 ÷ (1800\/17) = 0.17 ⇒ 17%.", + "golden_answer":"17", + "source":"Bigmath_synth" + }, + { + "instruction":"Store A offers discounts of {8%, 12%, 20%, 25%} on selected items, while Store B offers discounts of {10%, 12%, 25%, 30%}. The discounts common to both stores represent promotional deals available at both locations. However, before being applied, these common discounts are adjusted as follows:\n• If the discount is less than 15%, reduce its value by 20% (i.e. multiply the discount by 0.8).\n• If the discount is 15% or greater, add a flat 5 percentage points.\nDetermine the set of final effective discount percentages available at both stores. Express your answer as a set with each percentage (for example, 10%).", + "output":"The only overlaps are 12% and 25%. Applying the rules:\n\n- 12% < 15%, so 12% × 0.8 = 9.6% \n- 25% ≥ 15%, so 25% + 5% = 30% \n\nHence the final shared discounts are {9.6%, 30%}.", + "golden_answer":"30", + "source":"Bigmath_synth" + }, + { + "instruction":"A logistics drone is programmed to deliver parcels along a straight route divided into 1‐km segments. For the 2nd and subsequent segments (that is, for segment n with n ≥ 2), the drone’s speed is determined by two factors:\n • Its nominal speed is inversely proportional to the number of segments already completed (n – 1), with a constant of proportionality k.\n • However, when the drone is traversing an even‐numbered segment (n even), strong headwinds reduce its speed by 20% (i.e. the effective speed is only 80% of the nominal speed).\n\nGiven that the drone takes 5 minutes to complete the 2nd segment, determine a formula for the time T(n), in minutes, needed to traverse the nth segment. Express your answer as a piecewise function of n (for n even and n odd).", + "output":"First note that for the n‐th segment (n≥2) of length 1 km,\n\n nominal speed vₙₒₘ(n)=k\/(n−1) ⇒ time T₀(n)=1\/vₙₒₘ(n)=(n−1)\/k.\n\nOn even n there is a 20% speed‐reduction, so vₑ𝚏𝚏(n)=0.8·k\/(n−1) and \n T(n)=1\/vₑ𝚏𝚏(n)=(n−1)\/(0.8 k)=5(n−1)\/(4 k). \n\nWe are given T(2)=5 min. Since 2 is even, \n 5=T(2)=5·(2−1)\/(4 k)=5\/(4 k) \n⇒ 4 k=1 ⇒ k=¼.\n\nSubstitute back:\n\nFor n≥2,\n\n if n is odd: \n  T(n) = (n−1)\/k = (n−1)\/(1\/4) = 4(n−1) minutes,\n\n if n is even: \n  T(n) = 5(n−1)\/(4 k) = 5(n−1)\/(4·¼) = 5(n−1) minutes.\n\nAnswer.", + "golden_answer":"1", + "source":"Bigmath_synth" + }, + { + "instruction":"A computer retailer received 170 laptops. They used 30 laptops for a special in‐store promotional display and then reserved 15% of the remaining laptops for extended warranty testing (assume the reserved quantity is exactly 15% of the remaining stock). The rest were sold in 7 equally sized bundles. How many laptops are in each bundle?", + "output":"First subtract the 30 used for display: \n170 – 30 = 140 remaining. \nReserve 15% of those for testing: \n0.15·140 = 21 reserved. \nThat leaves 140 – 21 = 119 to sell. \nSplit into 7 equal bundles: \n119 ÷ 7 = 17 laptops per bundle.", + "golden_answer":"17", + "source":"Bigmath_synth" + }, + { + "instruction":"A reservoir’s water level (in meters) is modeled by L(t) = t² – 8t + 20, where t represents time in hours. At t = 3 hours:\n(a) Find the equation of the tangent line to L(t).\n(b) If a new regulation increases the water inflow rate by 3% whenever the instantaneous rate of change is positive, compute the adjusted slope at t = 3.\n(c) Using the adjusted tangent line, estimate the water level at t = 3.5 hours.", + "output":"Here’s how to do each part:\n\n1. Compute L′(t) and the point of tangency. \n L(t)=t²–8t+20 \n ⇒L′(t)=2t–8 \n At t=3: \n • L(3)=3²–8·3+20=9–24+20=5 \n • slope m=L′(3)=2·3–8=6–8=–2 \n\n2. (a) Equation of the tangent line at t=3 \n Point–slope form: \n y–L(3)=m·(t–3) \n y–5=–2·(t–3) \n ⇒ y=–2t+6+5=–2t+11 \n\n3. (b) “Increase the inflow rate by 3% whenever L′>0.” \n Here L′(3)=–2<0, so the rule does not kick in. \n ⇒ adjusted slope mₐ=–2 \n\n (If instead L′ had been positive you would do mₐ=1.03·m.) \n\n4. (c) Use the adjusted tangent line y=–2t+11 to estimate at t=3.5: \n y(3.5)=–2·3.5+11=–7+11=4 \n\nAnswer: \n(a) y=–2t+11 \n(b) adjusted slope =–2 \n(c) estimated L(3.5)=4 meters", + "golden_answer":"4", + "source":"Bigmath_synth" + }, + { + "instruction":"Eric manages a water tank that is refilled at a constant rate. Each day the pump increases the water level by a fixed number of centimeters. However, whenever the water reaches 150 cm, a safety valve automatically opens and drains the tank down to 100 cm. Each activation of the valve costs $40 plus an extra 25% processing fee on that cost. Over a period of 30 days, Eric spent exactly $500 on these valve activations. Determine how many centimeters per day the water level increases.", + "output":"Let r be the (constant) rise in cm per day. Each time the level goes from 100 cm up to 150 cm it trips the valve, dropping it back to 100 cm. Since each trip costs \\$40 + 25% = \\$50, spending \\$500 means 10 trips over 30 days. \n\nBetween trips the tank must gain 50 cm, and there are 10 such gains in 30 days, so the time between trips is 30\/10 = 3 days. Hence in 3 days you must gain 50 cm, i.e. \n3 · r = 50 ⇒ r = 50\/3 ≃ 16.67 cm\/day.", + "golden_answer":"16.67", + "source":"Bigmath_synth" + }, + { + "instruction":"Store X sold 70% of its 100 items in the morning, while Store Y sold 3\/4 of its 120 items during the same period.\n(a) By how many items did Store Y’s morning sales exceed Store X’s?\n(b) If each unsold item represents an estimated opportunity loss of $5, calculate the difference in the total losses from unsold stock between the two stores.", + "output":"(a) Store X sold 70% of 100 = 0.70×100 = 70 items; \n Store Y sold ¾ of 120 = 0.75×120 = 90 items. \n So Y sold 90–70 = 20 more items than X. \n\n(b) Unsold items after the morning: \n X: 100–70 = 30 items; Y: 120–90 = 30 items. \n At \\$5 opportunity loss each, each store “lost” 30×\\$5 = \\$150. \n Difference in losses: \\$150–\\$150 = \\$0.", + "golden_answer":"0", + "source":"Bigmath_synth" + }, + { + "instruction":"A company launches a promotional campaign by packaging items in a large cubical display assembled from 1×1×1 boxes. Each box bears a sticker on every face, and each sticker is worth 2 promotional points when visible. Moreover, to boost the appeal, the company multiplies the points for boxes in special locations:\n • Boxes at a corner of the large cube have all three of their visible stickers counted at double value.\n • Boxes along an edge but not at a corner have both of their visible stickers counted at 1.5 times their value.\n • Boxes on a face (but not along an edge) contribute with a single visible sticker at its normal value.\nBoxes completely in the interior contribute no points.\n\nIn an n×n×n arrangement the external boxes fall into these categories:\n ○ Corner boxes: 8 boxes.\n ○ Edge boxes (excluding corners): 12 edges each with (n–2) boxes.\n ○ Face‐center boxes (excluding edges): 6 faces each with (n–2)² boxes.\n\nA corner box normally shows 3 faces; under the campaign its contribution is 3×2×2 = 12 points. An edge box normally shows 2 faces; with the multiplier it contributes 2×2×1.5 = 6 points. A face‐center box shows 1 face and contributes 1×2 = 2 points.\n\nWhat is the smallest whole number n for which the total promotional points from all visible stickers exceed 1500?", + "output":"Let n be the edge‐length of the big cube (in 1×1×1 boxes). One finds\n\n Corners (8 boxes): each gives 3 faces ×2 pts ×2×=12 pts ⇒ total 8·12=96 \n Edges (12(n–2) boxes): each gives 2 faces ×2 pts ×1.5×=6 pts ⇒ total 12(n–2)·6=72(n–2) \n Faces (6(n–2)² boxes): each gives 1 face ×2 pts =2 pts ⇒ total 6(n–2)²·2=12(n–2)² \n\nSo the grand total is\nP(n)=96 + 72(n–2) + 12(n–2)²\n =12(n–2)²+72(n–2)+96.\n\nWe solve P(n)>1500:\n12(n–2)²+72(n–2)+96>1500\n⇔(n–2)²+6(n–2)+8>125\n⇔n²+2n−125>0\n⇔n>10.22… \n\nHence the smallest integer n is 11.", + "golden_answer":"11", + "source":"Bigmath_synth" + }, + { + "instruction":"At a local community fair, two types of tickets were sold: ride tickets at $14 each and game tickets at $6 each. The day’s total revenue was exactly $2006, with at least one ticket sold of each type. However, if more than 120 game tickets were sold, every game ticket beyond the first 120 was offered at a discounted price of $4. Determine the number of pairs of positive integers (r, g), where r is the number of ride tickets and g is the total number of game tickets sold, that could have produced the $2006 in revenue. (Treat separately the cases when g ≤ 120 and when g > 120.)", + "output":"We set up two revenue‐equations, one for g≤120 and one for g>120. In both cases r,g are positive integers.\n\n1) Case g≤120. \n Revenue 14 r+6 g=2006 ⇒ 7 r+3 g=1003. \n ⇒ r≡1 (mod 3), write r=3k+1 ⇒ g=(1003−7(3k+1))\/3=332−7k. \n Positivity and g≤120 give 1≤332−7k≤120 ⇒31≤k≤47. \n That is 17 solutions in this case.\n\n2) Case g>120. Tickets 1…120 at \\$6, the rest at \\$4 ⇒ \n 14 r + 6·120 +4(g−120)=2006 ⇒ 14 r+4 g=1766 ⇒ 7 r+2 g=883. \n ⇒ r≡1 (mod 2), write r=2m+1 ⇒ g=(883−7(2m+1))\/2=438−7m. \n Positivity and g>120 give 438−7m>120 ⇒ m≤45, m≥0 ⇒ 46 solutions.\n\nAnswer: \n• g≤120: 17 solutions \n• g>120: 46 solutions \nTotal =17+46=63 possible (r,g).", + "golden_answer":"63", + "source":"Bigmath_synth" + }, + { + "instruction":"In triangle ABC the side‐lengths are \n  AB = √24, AC = √6, BC = √14.\nA point D is chosen on side BC so that the segments satisfy BD : DC = 1 : 2, and it is given that ∠ADB = 90°.\n(a) Show that this right‐angle condition forces a unique value for AD.\n(b) Express, in simplest radical form, the ratio of the perimeter of triangle ADB to the perimeter of triangle ABC.\n\nTo clarify, one must first use the fact that in right triangle ADB (with right angle at D) the Pythagorean theorem gives\n  AD² + BD² = AB².\nThen, with BD = (1\/3)·BC and DC = (2\/3)·BC, one finds AD. Finally, writing\n\n  Perimeter of ADB = AD + BD + AB  and  Perimeter of ABC = AB + AC + BC,\ncompute the ratio\n  (AD + BD + AB) \/ (AB + AC + BC).\n\nFind your answer simplified in radical form.", + "output":"First note BC=√14 so \n BD=(1\/3)·√14=√14⁄3. \nIn right‐triangle ADB (∠ADB=90°) the Pythagorean theorem gives \n AD²+BD²=AB² \n⇒ AD²=AB²−BD²=24−(14⁄9)=(216−14)⁄9=202⁄9 \n⇒ AD=√202⁄3. \n\nHence the perimeter of ΔADB is \n P₁=AD+BD+AB=(√202⁄3)+(√14⁄3)+√24 \nand that of ΔABC is \n P=AB+AC+BC=√24+√6+√14. \n\nSo the ratio is \n\n P₁∕P \n= [ (√202⁄3)+(√14⁄3)+√24 ] ∕ (√24+√6+√14 ) \n= ( √202+√14+3√24 ) ∕ (3(√24+√6+√14)) \n= ( √202+√14+6√6 ) ∕ (9√6+3√14 ) \n= (√202+√14+6√6)\/(3(3√6+√14)). \n\nThat is the simplest‐radical form of the perimeter‐ratio.", + "golden_answer":"14", + "source":"Bigmath_synth" + }, + { + "instruction":"Let a and b be positive real numbers satisfying\n  √(9ᵃ · 3ᵇ) = 3.\nThis condition is equivalent to 9ᵃ · 3ᵇ = 9. (Hint: Write 9ᵃ as 3^(2a).)\nIn addition, suppose that either\n  (i) 9ᵃ ≥ 3ᵇ  or  (ii) 9ᵃ < 3ᵇ.\nSubject to these conditions, find the minimum possible value of\n  (3\/a) + (2\/b),\nand determine which case (i or ii) yields this minimum.", + "output":"First rewrite the constraint in simpler form. Since \n √(9ᵃ·3ᵇ)=3 \nsquaring gives \n 9ᵃ·3ᵇ=9, \nand 9ᵃ=(3²)ᵃ=3^(2a), so \n 3^(2a+b)=3² \n⇒ 2a+b=2 \n⇒ b=2−2a, 0½ so it lies in case (i). On the other hand on (0,½] one checks F(½)=8>4+2√3, so no smaller value occurs in case (ii). \n\nAnswer: the minimum of (3\/a)+(2\/b) is 4+2√3, attained in case (i).", + "golden_answer":"3", + "source":"Bigmath_synth" + }, + { + "instruction":"A spiral staircase in a modern art museum is built around a cylindrical core with a radius of 0.8 m. A decorative handrail runs along the outer edge of the staircase, positioned 0.5 m from the surface of the core (so its path is a helix with radius 1.3 m). The staircase ascends 24 m while completing 10 full turns. In addition, an intricate design detail requires that each complete turn uses 3% more handrail than the calculated helical length for that turn. Compute the total length of the handrail needed.", + "output":"Let R = 0.8 m + 0.5 m = 1.3 m be the helix radius, and let h = 24 m\/10 = 2.4 m be the rise per turn. \n\n1. Ideal length of one helical turn (no extra) \n L₀ = √[(2πR)² + h²] \n = √[(2π·1.3)² + (2.4)²] \n = √[(8.16814…)² + 5.76] \n ≃ √[66.72 + 5.76] \n ≃ √72.48 \n ≃ 8.51 m \n\n2. Allowing 3% extra per turn \n L₁ = 1.03·L₀ ≃ 1.03·8.51 ≃ 8.77 m \n\n3. Total for 10 turns \n L_total = 10·L₁ ≃ 10·8.77 ≃ 87.7 m \n\nSo you will need about 88 m of handrail in total.", + "golden_answer":"88", + "source":"Bigmath_synth" + } +] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/ReasoningPipeline/pipeline_math_short.json b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/ReasoningPipeline/pipeline_math_short.json new file mode 100644 index 0000000000000000000000000000000000000000..97cddd280213fb26e5a700528737aaf4d89f3872 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/ReasoningPipeline/pipeline_math_short.json @@ -0,0 +1,266 @@ +[ + { + "instruction":"An architect is designing a reflective surface for a concert hall in the shape of a horizontal hyperbola with its center at the origin. The two foci of the hyperbola are 8 meters apart, and for acoustic reasons the angle between its asymptotes must be 90°. In addition, one of its directrices is the vertical line x = –d. \n \n(a) Find the value of d.\n \n(b) Determine the equation of the hyperbola.", + "output":null, + "golden_answer":"8", + "source":"Bigmath_synth" + }, + { + "instruction":"A certain number is processed differently depending on whether it is even or odd:\n• If the number is even, it is first divided by 2, then multiplied by 5, and finally 4 is added, giving a result of 34.\n• If the number is odd, it is first divided by 3, then multiplied by 7, and finally 2 is subtracted, yielding 33.\nDetermine all possible original numbers.", + "output":"Let x be the original number.\n\nCase 1: x is even.\n (x÷2)·5 + 4 = 34 \n ⇒ 5x\/2 + 4 = 34 \n ⇒ 5x\/2 = 30 \n ⇒ x = 12. \n (12 is even, so this is valid.)\n\nCase 2: x is odd.\n (x÷3)·7 – 2 = 33 \n ⇒ 7x\/3 – 2 = 33 \n ⇒ 7x\/3 = 35 \n ⇒ x = 15. \n (15 is odd, so this is valid.)\n\nAnswer: The only possible originals are 12 (in the even‐case) or 15 (in the odd‐case).", + "golden_answer":"15", + "source":"Bigmath_synth" + }, + { + "instruction":"A bakery sells muffins and croissants. Each muffin is priced at $3, while each croissant is sold for 1.5 times the muffin price. In addition, every croissant incurs an extra packaging fee of $0.50. On a certain day, the bakery sells 15 croissants along with an unknown number of muffins, and the total revenue collected is $90. How many muffins were sold that day?", + "output":"Let x be the number of muffins. \nMuffin revenue = 3·x. \nCroissant revenue = (1.5·3 + 0.5)·15 = (4.5 + 0.5)·15 = 5·15 = 75. \nTotal revenue = 3x + 75 = 90 \n⇒ 3x = 15 \n⇒ x = 5. \n\nSo they sold 5 muffins.", + "golden_answer":"5", + "source":"Bigmath_synth" + }, + { + "instruction":"Alpha, Bravo, and Charlie all start running at the same time around a circular track. Alpha completes one lap in 130 seconds, and Charlie does so in 170 seconds. Bravo, however, runs each lap in 135 seconds but must take a mandatory 10‐second hydration break immediately after finishing each lap—so his effective time per lap is 135 + 10 = 145 seconds. \n\nDetermine the total time in minutes from the start until the fourth occurrence (including the start as the first occurrence) when all three cross the starting line simultaneously. Also, state whether this elapsed time is less than 40 minutes.", + "output":"Let A, B, C denote Alpha, Bravo and Charlie and let t be a time (in seconds) at which they are all simultaneously on the start–finish line. We have\n\n • Alpha laps in 130 s ⇒ A crosses whenever t≡0 (mod 130). \n • Charlie laps in 170 s ⇒ C crosses whenever t≡0 (mod 170). \n • Bravo runs a 135 s lap and then sits 10 s ⇒ his effective cycle is 135+10=145 s, so he crosses the line every 145 s ⇒ t≡0 (mod 145). \n\nHence the common crossing times (including t=0 at the start) are exactly the multiples of\n\n LCM(130, 145, 170)\n \nLet us factor:\n\n 130=2·5·13 \n 145=5·29 \n 170=2·5·17 \n\nso\n\n LCM=2·5·13·17·29=64 090 s. \n\nThus the simultaneous crossings occur at\n t=0, 64 090 s, 2·64 090=128 180 s, 3·64 090=192 270 s, … \n\nIf we count t=0 as the 1st occurrence, then the 4th occurrence is at\n t=3·64 090=192 270 s. \n\nIn minutes that is\n\n 192 270 s ÷ 60 = 3 204.5 minutes,\n\nwhich is obviously far more than 40 minutes.", + "golden_answer":"40", + "source":"Bigmath_synth" + }, + { + "instruction":"A retail shop generated revenue from two products. Product A brought in $2001. Product B was sold through two channels: in‐store and online. In‐store sales contributed 60% of Product B’s pre‑tax revenue, while online sales (making up the remaining 40%) were subject to a 4% sales tax. The combined revenue from both products—counting the tax on online sales—was $3017. Determine the pre‑tax revenue earned from the in‑store and online sales of Product B.", + "output":"Let x = the total pre‐tax revenue of Product B. \nThen \n  in‐store = 0.60 x \n  online = 0.40 x \n\nBecause online sales incur a 4% tax, the revenue collected from online (including tax) is 1.04 · (0.40 x) = 0.416 x. \nThe total revenue (Product A + in‐store B + taxed online B) is \n  2001 + 0.60 x + 0.416 x = 3017 \nSo \n  1.016 x = 3017 − 2001 = 1016 \n  x = 1016 \/ 1.016 = 1000 \n\nHence, pre‐tax revenues for B are: \n  In‐store: 0.60·1000 = $600 \n  Online: 0.40·1000 = $400", + "golden_answer":"400", + "source":"Bigmath_synth" + }, + { + "instruction":"A tech company creates security codes for its devices. Each code is a 4‐character sequence formed using the letters D, E, and F. The code must include each letter at least once, and the same letter cannot appear consecutively. Additionally, if the code begins with D, then exactly two of the characters in the code must be E. How many unique security codes satisfy these conditions? Express your answer as a single integer.", + "output":"To organize the count, break into two cases by first letter:\n\nCase 1: starts with D. \n  – By the “if it begins with D” clause, it must have exactly two E’s in the four positions. With one D already in front that leaves E,E,F to place in positions 2–4. \n  – We also cannot have any two identical letters adjacent. Of the three multiset‐permutations of E,E,F only E F E avoids an E–E back‐to‐back. \n  ∴ case 1 contributes 1 code: D E F E.\n\nCase 2: starts with E or F. \n  – Now there is no extra E‐count restriction, but we do require (i) no repeats adjacent, (ii) at least one of each D,E,F somewhere. \n\n(A) Starts with E: \n Positions 2–4 can be built freely (no two in a row the same and pos 2≠E), giving 2³=8 total. Of those 8, exactly 2 fail to include a D and F in 2–4, so 8–2=6 actually contain D,F at least once (together with the leading E this ensures all three appear). \n \n(B) Starts with F: \n Symmetrically, we get another 8 total no‐repeat sequences in 2–4, of which 2 are missing one of {D,E} there, so 8–2=6 that do contain both D and E (and the leading F). \n\n∴ case 2 contributes 6+6=12 codes\n\nGrand total = case 1 + case 2 = 1 + 12 = 13.", + "golden_answer":"13", + "source":"Bigmath_synth" + }, + { + "instruction":"An artist is designing a tiled mosaic. The finished design must use a total number of tiles that can be arranged in equal rows with either 8, 10, or 12 tiles per row (with no tile left over). In addition, exactly 25% of the total tiles will be accent tiles, and these accent tiles must themselves be able to be arranged in equal rows of 8, 10, or 12 (again with no leftover tiles). What is the smallest total number of tiles the artist can use in the mosaic?", + "output":"480", + "golden_answer":"480", + "source":"Bigmath_synth" + }, + { + "instruction":"A manufacturer applies several successive adjustments to the cost of producing a gadget. First, a reprocessing error causes the cost to be multiplied by –4. Next, an efficiency upgrade reduces the cost effect by a factor of 8 (i.e. the current value is divided by 8). Then, a quality improvement adjustment is made by multiplying the result by –3\/2. These operations are performed in the order given (from left to right). Finally, an additional handling fee scales the adjusted cost by an extra factor of 1\/3. What is the overall multiplier effect on the original cost? Express your answer as a simplified fraction.", + "output":"The overall multiplier is \n(–4) × (1\/8) × (–3\/2) × (1\/3) \n= (–4\/1)·(1\/8)·(–3\/2)·(1\/3) \n= 1\/4.", + "golden_answer":"4", + "source":"Bigmath_synth" + }, + { + "instruction":"A furniture maker plans to build decorative tables for a showroom. Each table requires 3 pine planks and 2 oak planks. The maker has 12 pine logs already available, and each pine log can be cut to yield 5 pine planks. Because the number of pine planks exactly determines the number of tables that can be built, he will buy oak logs only to supply the matching oak planks needed. If each oak log can be cut to yield 10 oak planks, how many tables can be built in total and how many oak logs must he purchase to complete the project?", + "output":"He can get 12 logs×5 planks\/log = 60 pine planks, which makes 60\/3 = 20 tables. \nFor 20 tables he needs 20×2 = 40 oak planks, and at 10 planks per log that’s 40\/10 = 4 oak logs. \nAnswer: 20 tables and 4 oak logs.", + "golden_answer":"4", + "source":"Bigmath_synth" + }, + { + "instruction":"A picture frame is to be made by joining three ribbons end‐to‐end to form a triangle. Two of the ribbons are 8 cm and 13 cm long, while the third ribbon has an integer length x cm. In addition, because of shipping restrictions, the total perimeter of the frame must be less than 40 cm. Determine the sum of all possible whole number values of x that allow the ribbons to form a triangle and satisfy the perimeter restriction.", + "output":"First, the triangle‐inequalities give\n\n1. 8 + 13 > x ⇒ x < 21 \n2. 8 + x > 13 ⇒ x > 5 \n3. 13 + x > 8 ⇒ x > –5 (automatic once x>5)\n\nSo from (1) and (2) we get 6 ≤ x ≤ 20 (integer).\n\nNext, the perimeter restriction is\n 8 + 13 + x < 40 \n⇒ 21 + x < 40 \n⇒ x < 19 \n⇒ x ≤ 18.\n\nCombining: 6 ≤ x ≤ 18. These are the 13 integers 6,7,8,…,18. Their sum is\n\n (6 + 18)·13\/2 = 24·13\/2 = 12·13 = 156.\n\nAnswer: 156.", + "golden_answer":"156", + "source":"Bigmath_synth" + }, + { + "instruction":"An online retailer is launching a special promotion by distributing three‐digit discount codes. A discount code is valid only if it satisfies all of the following conditions:\n • The product of its digits equals 24.\n • The sum of its digits is an even number.\n • The tens digit is a prime number.\nDetermine the total number of valid discount codes. Provide your answer as a single integer.", + "output":"4", + "golden_answer":"4", + "source":"Bigmath_synth" + }, + { + "instruction":"Julian is hosting a themed dinner party and prepares a rectangular chocolate cake cut into exactly 20 equal pieces for himself and his four guests: Maya, Ian, Zoe, and Evan. Their cake‐eating habits are as follows:\n\n1. Julian takes 2 pieces.\n2. Maya, being health‐conscious, takes 15% of Julian’s share (if 15% is not a whole number, she rounds up to the next whole piece).\n3. Ian is moderately hungry and takes 1.5 times as many pieces as Julian.\n4. Zoe loves cake and takes 3 pieces plus, if available, every extra piece that would have made Ian’s share exceed his planned 1.5×Julian; that is, if Ian’s designated number of pieces (from rule 3) cannot be fully taken because of limited supply, Zoe claims the “overflow” portion.\n5. Evan is very hungry and intends to take twice as many pieces as Julian; however, if the remaining pieces after everyone else has taken their share are fewer than his intended amount, he takes all the remaining pieces instead.\n\nAssuming the pieces are distributed in the order given above (Julian, then Maya, then Ian, then Zoe, and finally Evan), determine the ratio of the number of pieces Evan actually eats to the number of pieces Julian eats. (Note: In solving this problem, you must consider the case where there may not be enough pieces left for Evan’s full intended share.)", + "output":"Here’s the step‑by‑step tally (out of 20 pieces), in the order given:\n\n1. Julian takes 2 → 20 − 2 = 18 left \n2. Maya takes ceil(15% of 2)=ceil(0.3)=1 → 18 − 1 = 17 left \n3. Ian takes 1.5×2=3 → 17 − 3 = 14 left \n4. Zoe takes her fixed 3 pieces; Ian wasn’t shorted, so no “overflow” → 14 − 3 = 11 left \n5. Evan intends 2×2=4, and there are 11 left (≥4), so he takes 4 → 11 − 4=7 leftover \n\nEvan ends up with 4 pieces, Julian 2 pieces, so the ratio Evan : Julian = 4 : 2 = 2 : 1.", + "golden_answer":"1", + "source":"Bigmath_synth" + }, + { + "instruction":"Alex has 90 candies and 40 stickers. He wants to pack these into gift bags so that every bag contains exactly 6 candies. In addition, each bag will receive either 3 stickers or 2 stickers. If Alex must use all the candies and stickers and he packs more bags with 3 stickers than with 2 stickers, how many gift bags does he create?", + "output":"Let x = number of bags with 3 stickers, and y = number with 2 stickers. \nThen \n• Candies: 6(x+y) = 90 ⇒ x+y = 15 \n• Stickers: 3x + 2y = 40 \n\nSubstitute y = 15−x into the sticker‐count: \n3x + 2(15−x) = 40 \n3x + 30 − 2x = 40 \nx = 10, so y = 5. \n\nTotal bags = x+y = 10+5 = 15.", + "golden_answer":"15", + "source":"Bigmath_synth" + }, + { + "instruction":"A logistics company assigns tracking codes (represented by colors) to shipments, whose weights can be any positive real number. The following rules must be observed:\n • If two shipments have weights whose ratio is exactly 2 or exactly 5, then they must be assigned different tracking codes.\n • Every shipment weighing between 50 kg and 100 kg must be given a tracking code that is not used for any shipments weighing less than 50 kg or more than 100 kg.\n\nWhat is the minimum number of tracking codes required to label all shipments while satisfying these rules?", + "output":"We can think of “weight‐” as points on the real line via x=ln w. Then “cannot be same color if ratio 2 or 5” becomes “cannot be same color if x differ by a=ln 2 or b=ln 5.” Also the interval B = [ln 50, ln 100] must carry a palette disjoint from the rest (A∪C = (−∞, ln 50)∪(ln 100, +∞)).\n\n1. On B itself the only forbidden pair is 50↔100 (distance ln 2), so B needs 2 colors.\n2. On A∪C one has an infinite graph with edges at ±a and ±b. Since ln 2∕ln 5 is irrational there are no non‐trivial cycles, so this graph is bipartite and needs exactly 2 colors.\n3. By the rule “B’s colors must be disjoint from A∪C’s,” the total is 2+(2)=4.\n\nHence 4 tracking codes suffice and are necessary.", + "golden_answer":"4", + "source":"Bigmath_synth" + }, + { + "instruction":"A factory’s production efficiency factor is modeled by the expression (m + 3)\/(m + 4) + 2\/(m + 4), where m (in months) measures the time since the last equipment upgrade and m ≠ –4. \n a) Express the overall efficiency factor in its simplest algebraic form. \n b) For what value of m does the factory achieve an efficiency factor of 1.2?", + "output":"a) Combine the fractions over the common denominator (m + 4): \n (m + 3)\/(m + 4) + 2\/(m + 4) \n = [ (m + 3) + 2 ] \/ (m + 4) \n = (m + 5) \/ (m + 4). \n\nb) Set (m + 5)\/(m + 4) = 1.2 = 6\/5 and solve for m: \n 5(m + 5) = 6(m + 4) \n 5m + 25 = 6m + 24 \n 25 – 24 = 6m – 5m \n 1 = m. \n\nSo the factory reaches an efficiency factor of 1.2 when m = 1 month.", + "golden_answer":"1", + "source":"Bigmath_synth" + }, + { + "instruction":"Two numbers represent the amounts (in dollars) of two different investments. It is known that the difference between the investments, the sum of the investments, and 10% of their product are in the ratio 1 : 9 : 36. Find the product of the two investments. Express your answer as a single integer.", + "output":"Let the investments be x and y with x > y. Then\n\nx–y : x+y : 0.1xy = 1 : 9 : 36.\n\nSo x–y = k, x+y = 9k ⇒ x = 5k, y = 4k. And 0.1·(5k·4k)=36k ⇒ 2k²=36k ⇒ k=18.\n\nHence x=90, y=72 and xy=90·72=6480.", + "golden_answer":"6480", + "source":"Bigmath_synth" + }, + { + "instruction":"An isosceles triangle has equal sides of 6 units and a base of 8 units. Construct the following composite figure:\n• At each vertex of the triangle, draw two distinct circular arcs with centers at that vertex. The first arc has a radius of 2 units and the second a radius of 7 units; both arcs are drawn outward from the triangle.\n• Additionally, at the midpoint of the base, attach a 90° circular sector with a radius of 1 unit extending outward.\nDetermine the minimum possible width of a strip bounded by two parallel lines that can completely enclose this entire composite figure. (You must analyze and compare the extremal contributions of the triangle, the four arcs, and the circular sector in order to find the optimal orientation minimizing the strip’s width.)", + "output":"Let the triangle be placed so that its base runs from A=(−4,0) to B=(+4,0) and its apex is at \n C=(0,h) with h=√(6²−4²)=2√5 ≃4.472. \nAt each of the three vertices A, B, C we have two “outward” circular arcs of radii 2 and 7; and at the midpoint M=(0,0) of the base we have a little 90°‐sector of radius 1 pointing downward. \n\nWe want the smallest possible distance between two parallel support‐lines (a “strip”) that can be swung around to cover every point of the union of triangle+arcs+sector. Call by u a unit normal direction for the strip; then the width in direction u is \n W(u) = max{ x·u : x in the figure } − min{ x·u : x in the figure }. \n\n1) Because the radius–7 arcs are by far the largest radial excursions, one checks quickly that none of the radius–2 arcs nor the tiny radius–1 sector ever “pushes” past the radius–7 arcs in any direction u. In fact \n max {x·u : figure} = max { A·u, B·u, C·u } + 7, \n min {x·u : figure} = min { A·u, B·u, C·u } − 7. \nHence \n W(u) = [max(A·u,B·u,C·u) − min(A·u,B·u,C·u)] + 14 \n = width of the bare triangle in direction u + 14. \n\n2) It is a standard fact that the minimal width of an isosceles triangle of side‐lengths 6, 6, 8 is attained when the strip is parallel to the base AB, and equals the altitude from C down to AB, namely h=2√5. \n\n3) Therefore the overall “composite” width is minimized exactly in the same orientation (strip lines horizontal), and is \n Wmin = (altitude = 2√5) + 14 \n = 14 + 2 √5 ≃ 14 + 4.472 = 18.472 (units). \n\nConclusion. The narrowest parallel‐line strip that contains the entire figure has width \n 14 + 2√5 ≃ 18.472 \nand it is achieved by taking the two lines horizontal (i.e. parallel to the triangle’s base).", + "golden_answer":"18.472", + "source":"Bigmath_synth" + }, + { + "instruction":"Suppose in a math contest each contestant’s score on Problem A is one of the two distinct real roots of the quadratic equation\n\n  x² – (m + 3)x + 2m = 0\n\nand the score on Problem B is determined by solving the linear equation\n\n  n·x – 4 = 0                 (assuming n ≠ 0).\n\nIf every score obtained from Problem B is also a valid score for Problem A, find all pairs (m, n) ∈ ℝ × ℝ (with n ≠ 0) that satisfy this condition. (Hint: Express the unique solution x = 4\/n of the linear equation; then require that substituting x = 4\/n in the quadratic yields 0. Also, remember that the quadratic must have two distinct real roots.)", + "output":"We want the unique B‐score x = 4\/n to be one of the two (distinct) real roots of \n x² – (m+3)x + 2m = 0. \nHence we must have \n (4\/n)² – (m+3)(4\/n) + 2m = 0, \nand we also need the quadratic to have two distinct real roots (which, as you can check, in fact imposes no extra restriction on m).\n\n1. Clear denominators in \n 16\/n² – (4(m+3))\/n + 2m = 0 \n by multiplying through by n²: \n 16 – 4n(m+3) + 2m n² = 0 \n ⇔ 2m n² – 4m n + (16 – 12n) = 0 \n ⇔ 2m n(n–2) = 12n – 16 \n ⇔ m = (12n – 16) \/ [2n(n–2)], provided n≠0, 2.\n\n2. One checks the quadratic’s discriminant \n D = (m+3)² – 8m = m² – 2m + 9 = (m–1)² + 8 > 0 \n for all real m, so the root at x=4\/n is always one of two distinct real roots.\n\nTherefore the complete solution set is\n\n {(m,n): n≠0, 2, m = (12n–16)\/(2n(n–2)) } \n\nor equivalently\n\n m = 2(3n–4) \/ [n(n–2)], n∈ℝ\\{0,2}.", + "golden_answer":"2", + "source":"Bigmath_synth" + }, + { + "instruction":"Let i be the imaginary unit. If (2 – i)(x + 2i) = 6 + zi, where x and z are real numbers and x is known to be a solution of the quadratic equation x² – 5x + 6 = 0, determine the value of x and then compute 4x + z.", + "output":"First expand and equate real‐ and imaginary parts:\n\n(2 − i)(x + 2i) = 2x + 4i − ix − 2i² \n = (2x + 2) + i(4 − x)\n\nWe want (2x+2) + i(4−x) = 6 + zi. Hence \n2x + 2 = 6 ⇒ x = 2 \n4 − x = z ⇒ z = 4 − 2 = 2.\n\nCheck that x=2 is indeed a root of x²−5x+6=0 (the other root is 3, but only x=2 satisfies the complex‐equation). \nFinally 4x + z = 4·2 + 2 = 10.", + "golden_answer":"10", + "source":"Bigmath_synth" + }, + { + "instruction":"At the Arboretum's annual garden exhibition, various flora and installations are arranged as follows:\n\n• Trees: There are 1,342 oak trees, 1,587 maple trees, 1,925 pine trees, and 2,450 birch trees.\n• Shrubs: There are 8 clusters of ornamental shrubs. Each cluster was originally planned to contain 100 shrubs, but each lost 12 shrubs due to recent weather damage.\n• Roses: There are 7 displays of rose bouquets. In 6 of these displays, each bouquet contains exactly 40 roses. In the remaining display, each bouquet was enhanced by a 15% increase over the standard amount, so each bouquet contains 46 roses (after rounding down to the nearest whole number).\n• Fountain Installations: There are 10 pairs of fountain installations set around the garden.\n\nDetermine the total number of individual pieces (trees, shrubs, roses, and fountain installations) featured at the exhibition.", + "output":"First, let’s tally each category one by one.\n\n1. Trees \n Oak: 1 342 \n Maple: 1 587 \n Pine: 1 925 \n Birch: 2 450 \n Total trees = 1 342 + 1 587 + 1 925 + 2 450 = 7 304 \n\n2. Shrubs \n 8 clusters × (100 shrubs – 12 lost) = 8 × 88 = 704 \n\n3. Roses \n There are 7 displays, each with one bouquet (the problem statement implies one bouquet per display). \n – 6 bouquets at 40 roses each: 6 × 40 = 240 \n – 1 bouquet at a 15% increase over 40 → 40×1.15 = 46 (rounded down) \n Total roses = 240 + 46 = 286 \n\n4. Fountain installations \n 10 pairs of fountains → 10 × 2 = 20 individual installations \n\nFinally, sum all pieces: \n 7 304 (trees) \n+  704 (shrubs) \n+  286 (roses) \n+  20 (fountains) \n= 8 314 \n\nAnswer: 8 314 individual pieces.", + "golden_answer":"314", + "source":"Bigmath_synth" + }, + { + "instruction":"A construction company leases a rectangular storage lot for its equipment. The rental fee is set at $55 for every 500 square feet per month, but if the lot’s area exceeds 10,000 square feet an extra fee of 10% is added to the base rent. The lot’s width is fixed at 50 feet, and the company’s monthly bill comes to $1,320. Determine the length of the lot in feet and confirm that the extra fee was applied.", + "output":"Let L be the length (in ft). Since the width is 50 ft, the area is \n A = 50·L (sq ft). \n\nRate per sq ft (before any surcharge): \n $55 per 500 ft² ⇒ \\$\\frac{55}{500}=0.11\\,$\/ft². \n\nBase rent = 0.11·A. Because A>10 000, we must add a 10% surcharge, so the total rent is \n Total = 1.10·(0.11·A) = 0.121·A. \n\nWe are told Total = \\$1 320, so \n 0.121·A = 1 320 \n⇒ A = 1 320\/0.121 ≃ 10 909.09 ft². \n\nHence \n 50·L = 10 909.09 \n⇒ L ≃ 10 909.09\/50 = 218.18 ft. \n\nCheck: \n A ≃10 909 ft² >10 000 ft² ⇒ surcharge applies. \n Base rent =0.11·10 909.09 ≃\\$1 200.00 \n +10% surcharge =\\$120.00 \n Total ≃\\$1 320.00. \n\nAnswer: The lot is about 218.2 ft long, and indeed its area exceeds 10 000 ft² so the extra 10% fee was applied.", + "golden_answer":"10", + "source":"Bigmath_synth" + }, + { + "instruction":"A company’s weekly revenue (in thousands of dollars) follows an arithmetic sequence with nonzero common difference d. It is given that the revenue in the 5th week is 2 (that is, $2,000). In addition, for any week when the revenue exceeds 2, the company earns an immediate bonus of 0.5 (i.e. an extra $500) for that week. Define Rₙ as the sum of the weekly revenues (excluding bonuses) over the first n weeks and Bₙ as the total bonus earned in those n weeks. Determine an expression for 2(R₆ + B₆) + (R₁₂ + B₁₂) in terms of d. (Note: You must consider separately those weeks whose revenue is at most 2 and those whose revenue exceeds 2.)", + "output":"Let aₙ be the n‑th week’s (thousands of dollars) revenue. Since a₅=2 and {aₙ} is arithmetic with common difference d≠0, \n a₁=2−4d, \n aₙ=a₁+(n−1)d=2−4d+(n−1)d. \n\nA week k earns a bonus 0.5 only if aₖ>2. One checks \n aₖ>2 ⇔2−4d+(k−1)d>2 ⇔(k−5)d>0. \n\nCase 1: d>0 ⇒ (k−5)d>0 exactly when k>5. \n Weeks 1–5 have no bonus, weeks 6–12 each earn 0.5. \n R₆=∑₁⁶aₙ=6\/2·(2a₁+5d)=3(2(2−4d)+5d)=12−9d \n B₆=1·0.5=0.5 \n R₁₂=12\/2·(2a₁+11d)=6(4+3d)=24+18d \n B₁₂=7·0.5=3.5 \n ⇒2(R₆+B₆)+(R₁₂+B₁₂)=2((12−9d)+0.5)+(24+18d+3.5) \n                       =25−18d+27.5+18d=52.5 \n\nCase 2: d<0 ⇒ (k−5)d>0 exactly when k<5. \n Weeks 1–4 earn 0.5, weeks 5–12 no bonus. \n R₆=12−9d, B₆=4·0.5=2 \n R₁₂=24+18d, B₁₂=4·0.5=2 \n ⇒2(R₆+B₆)+(R₁₂+B₁₂)=2((12−9d)+2)+(24+18d+2) \n                       =28−18d+26+18d=54. \n\nAnswer: \n If d>0, 2(R₆+B₆)+(R₁₂+B₁₂)=52.5, \n If d<0, 2(R₆+B₆)+(R₁₂+B₁₂)=54.", + "golden_answer":"54", + "source":"Bigmath_synth" + }, + { + "instruction":"A fruit vendor sells bags of oranges using two different packaging methods. In a standard bag, there are exactly one dozen oranges; however, due to a supply issue, some bags are only filled to 75% of the standard amount. If a customer buys 20 bags and ends up with a total of 210 oranges, how many of the bags were standard and how many were reduced?", + "output":"Let x = number of standard (12‐orange) bags and y = number of reduced (9‐orange) bags. Then\n\n1) x + y = 20 \n2) 12x + 9y = 210 \n\nFrom (1) y = 20 – x. Substitute into (2):\n\n12x + 9(20 – x) = 210 \n12x + 180 – 9x = 210 \n3x = 30 \nx = 10 \n\nHence y = 20 – 10 = 10. \n\nAnswer: 10 standard bags and 10 reduced bags.", + "golden_answer":"10", + "source":"Bigmath_synth" + }, + { + "instruction":"Two adjacent corners of a square exhibition booth are located at (2, –5) and (–3, 0). The design team calculates the side length of the booth from these coordinates; however, because of uneven ground, if this computed side length is not an integer, it must be increased to the next highest integer before construction begins.\n\na) Determine the adjusted perimeter of the booth.\n\nb) After construction, the carpet covering the floor is paid only for the area that exceeds 60 square units, at a rate of $3 per extra square unit. Calculate the additional carpet cost based on the adjusted side length.\n\n", + "output":"First, compute the true side length:\n\nDistance between (2, –5) and (–3, 0) \n= √[(2 – (–3))² + (–5 – 0)²] \n= √[5² + (–5)²] \n= √(25 + 25) \n= √50 ≈ 7.071.\n\nSince 7.071 is not an integer, we round up to the next integer, 8.\n\na) Adjusted perimeter = 4 × 8 = 32.\n\nb) Floor area = 8² = 64. \nExcess over 60 = 64 – 60 = 4. \nAt \\$3 per extra unit, cost = 4 × 3 = \\$12.", + "golden_answer":"12", + "source":"Bigmath_synth" + }, + { + "instruction":"A computer store sells two accessory bundle deals. Bundle A includes two identical keyboards, two identical mice, and one monitor. Its price is calculated by multiplying the cost factors: keyboard cost (K), mouse cost (M), and monitor cost (D), so that the total price is\n  K × K × M × M × D.\nBundle B, on the other hand, consists of the same keyboard and monitor but replaces the mice with a combined cable set whose cost is unknown; its price is given by\n  K × K × D × n × n.\nOn a weekday sale the two bundle deals are priced exactly the same. During weekend promotions the store offers an extra discount where the cable set in Bundle B costs 20% less than the regular mouse price, but that does not affect today’s weekday pricing.\nIf K = 3 dollars, M = 5 dollars, and D = 7 dollars, determine the value of n (as a positive integer) for the weekday bundle price.\n\n", + "output":"We have on a weekday \n Price A = K²·M²·D \n Price B = K²·D·n² \nSince they’re equal today, \n K²·M²·D = K²·D·n² \n⇒ M² = n² \n⇒ n = |M| = 5 (we take the positive root) \nHence n = 5.", + "golden_answer":"5", + "source":"Bigmath_synth" + }, + { + "instruction":"Samuel has a decorative fountain that he refills using a 100‑ounce jug. To bring the fountain exactly to his preferred display level, he follows a two‐step refill procedure: first he pours the jug 16 times (thereby “overfilling” the fountain) and then he drains off exactly the equivalent of 2 full jugfuls. (In other words, on any day without loss his planned net water addition per “refill cycle” is 16·100 – 2·100 = 1,400 ounces.) However, on days when the temperature exceeds 85°F (the weekdays), evaporation causes a loss of 8% during each cycle; to end up with the desired net 1,400 ounces, Samuel must pour extra water so that only 92% of what he pours remains. On cooler days (the weekend) no extra water is needed because there is no significant evaporation loss.\n\nSamuel follows a schedule in which on each weekend day he completes exactly twice as many refill cycles as on any given weekday. (For example, if he performs x cycles on a weekday then on each weekend day he performs 2x cycles.) In one week he uses exactly 13,208.7 ounces of water to run these refill cycles.\n\n(a) Let x be the number of cycles Samuel performs on each weekday. Write an expression in terms of x for the total water used during the week, taking into account the increased requirement on hot days.\n\n(b) Find the value of x that makes the total water used equal 13,208.7 ounces, and then state how many refill cycles Samuel completes on all weekdays and on all weekend days combined.\n\nRemember: On a weekday each cycle requires extra water so that\n  (actual water poured per cycle) = 1,400\/0.92 ounces,\nwhile on a weekend cycle the water poured is exactly 1,400 ounces.\n\nSolve the problem step by step.", + "output":"a) Let x = number of refill‐cycles on each weekday. \nThere are 5 weekdays and 2 weekend days. On a weekday each cycle uses (1400 oz)\/0.92 of water, on a weekend cycle exactly 1400 oz. \nSo the total water used in one week is \n Total(x) = (number of weekday cycles)·(per‐cycle weekday use) \n    + (number of weekend cycles)·(per‐cycle weekend use) \n = (5x)·(1400\/0.92) + (2 days·2x cycles\/day)·1400 \n = 5x·(1400\/0.92) + 4x·1400. \n\nb) Set this equal to 13 208.7 and solve for x: \n 5x·(1400\/0.92) + 4x·1400 = 13 208.7. \nCompute the coefficient of x: \n 5·1400\/0.92 ≈ 7000\/0.92 ≈ 7608.69565; 4·1400 = 5600 \nso \n x·(7608.69565 + 5600) ≈ x·13 208.69565 = 13 208.7 \n⇒ x ≈ 13 208.7\/13 208.69565 ≈ 1.0000003 ≈ 1. \n\nHence x = 1 cycle per weekday. \nTotal weekday cycles = 5·x = 5·1 = 5. \nTotal weekend cycles = 2 days·(2x) = 2·2·1 = 4.", + "golden_answer":"4", + "source":"Bigmath_synth" + }, + { + "instruction":"A square has vertices that lie on four distinct horizontal lines in the coordinate plane with y‐coordinates 1, 3, 7, and 9. Although the square is rotated relative to the axes, its vertically “projected” span is 9 – 1 = 8. It is given that the ratio of this vertical span to the side length equals the ratio of the square’s area to its perimeter. Find the area of the square.\n\n", + "output":"Label the side‐length of the square by s and let θ be its angle of rotation above the horizontal. One checks (e.g. by writing out the four vertices) that its vertical span is\n\n V = s (sin θ + cos θ).\n\nWe are told V = 9 − 1 = 8, so\n\n s (sin θ + cos θ) = 8. (1)\n\nOn the other hand the ratio of its vertical span to its side length is\n\n V\/s = sin θ + cos θ,\n\nand the ratio of its area to its perimeter is\n\n s²\/(4s) = s\/4.\n\nThe problem asserts these two ratios are equal, so\n\n sin θ + cos θ = s\/4. (2)\n\nCompare (1) and (2): from (1) we get sin θ + cos θ = 8\/s, so (2) gives\n\n 8\/s = s\/4 ⇒ s² = 32.\n\nHence the area s² = 32.", + "golden_answer":"32", + "source":"Bigmath_synth" + }, + { + "instruction":"A company manufactures rectangular storage containers with integer side lengths. One of its containers measures 2 cm, 6 cm, and 18 cm. To create a new product line, the container is to be sliced along one of its dimensions into two congruent smaller boxes—but with the design requirement that the side length in the chosen cutting direction must be exactly halved (i.e. the cut is made exactly through the middle of that side). \n\nFor each valid cutting direction, a smaller box will have dimensions as follows:\n • If cut along the 2‐cm side, the smaller box measures 1 cm, 6 cm, and 18 cm.\n • If cut along the 6‐cm side, the smaller box measures 2 cm, 3 cm, and 18 cm.\n • If cut along the 18‐cm side, the smaller box measures 2 cm, 6 cm, and 9 cm.\n\nDetermine, after analyzing these three cases, the square of the largest possible length of the space diagonal of one of the resulting smaller boxes.", + "output":"For the three possible halving‐cuts you get smaller boxes with dimensions\n\n1) (1, 6, 18) → diagonal² = 1² + 6² + 18² = 1 + 36 + 324 = 361 \n2) (2, 3, 18) → diagonal² = 4 + 9 + 324 = 337 \n3) (2, 6, 9)   → diagonal² = 4 + 36 + 81 = 121 \n\nThe maximum of these is 361.", + "golden_answer":"361", + "source":"Bigmath_synth" + }, + { + "instruction":"A combination lock uses a six‐digit code that begins with 5 and is divisible by 15. (Recall that being divisible by 15 means the code must also be divisible by both 3 and 5.) In addition, if the code ends in 0 then the sum of its six digits must be divisible by 7, but if the code ends in 5 then the product of its hundreds digit (the fourth digit) and its tens digit (the fifth digit) must be even. How many distinct valid codes are possible?", + "output":"Let d₁…d₆ be the six‐digit code. Since it must begin with 5 and be a multiple of 15, we have\n\n• d₁=5, \n• d₆∈{0,5} (to be multiple of 5), \n• d₁+…+d₆≡0 mod 3 (to be multiple of 3).\n\nWe split into two cases:\n\nCase 1: d₆=0. \nThen the sum S=d₁+…+d₆=5+(d₂+…+d₅)+0 must be ≡0 mod 3 (for divisibility by 3) and also ≡0 mod 7 (by the extra “if ends in 0” condition). Hence S≡0 mod 21. But 5≤S≤5+4·9=41, so the only possibility is S=21. Thus\n d₂+ d₃+ d₄+ d₅ =21−5=16,\nwith 0≤each≤9. The number of nonnegative solutions x₂+…+x₅=16 with xi≤9 is\n C(16+4−1,3) −4·C(6+4−1,3)\n = C(19,3) −4·C(9,3)\n = 969 −4·84\n = 969 −336\n = 633.\n\nCase 2: d₆=5. \nWe still need d₁+…+d₆≡0 mod 3, i.e. 5+5+(d₂+…+d₅)≡0 mod 3 ⇒ d₂+…+d₅≡2 mod 3. \nAlso the extra “if ends in 5” condition says the 4th and 5th digits (d₄,d₅) have an even product, i.e. at least one of d₄,d₅ is even. \n• There are in all 10⁴=10,000 choices for (d₂,d₃,d₄,d₅). Exactly one third of those have sum ≡2 mod 3, i.e. 10,000\/3 rounded down = 3,333. \n• We must remove from those the cases in which both d₄,d₅ are odd. There are 100 choices for (d₂,d₃)×25 choices for (d₄,d₅ both odd) =2,500 total, and exactly one third of these (833) have sum≡2 mod 3. \nSo Case 2 contributes 3,333−833=2,500 codes.\n\nTotal = 633 + 2,500 = 3,133.", + "golden_answer":"3133", + "source":"Bigmath_synth" + }, + { + "instruction":"At the local community center, a shed is used to store various wheeled devices for activities. Inside, there are 3 bicycles (normally 2 wheels each), 3 tricycles (normally 3 wheels each), 5 skateboards (normally 4 wheels each), and 2 scooters (normally 2 wheels each). However, note the following adjustments:\n• One of the bicycles is missing 1 wheel.\n• 40% of the tricycles (rounding to the nearest whole number) have an extra spare wheel attached.\n• Two of the skateboards have lost 2 wheels each.\n• One of the scooters has been modified by adding an extra wheel.\nDetermine the total number of wheels present in the shed.", + "output":"Here’s a quick breakdown:\n\n1. Bicycles \n – Normally 3 × 2 = 6 wheels \n – One is missing 1 wheel ⇒ 6 − 1 = 5 wheels\n\n2. Tricycles \n – Normally 3 × 3 = 9 wheels \n – 40% of 3 tricycles = 1.2 ⇒ rounds to 1 trike with an extra wheel \n – Extra wheel adds +1 ⇒ 9 + 1 = 10 wheels\n\n3. Skateboards \n – Normally 5 × 4 = 20 wheels \n – Two boards lost 2 wheels each ⇒ 4 wheels lost ⇒ 20 − 4 = 16 wheels\n\n4. Scooters \n – Normally 2 × 2 = 4 wheels \n – One has +1 wheel ⇒ 4 + 1 = 5 wheels\n\nTotal wheels = 5 + 10 + 16 + 5 = 36 wheels.", + "golden_answer":"36", + "source":"Bigmath_synth" + }, + { + "instruction":"A manufacturing plant operates 3 identical machines that produce gadgets. On weekdays (Monday through Friday), each machine produces 12 gadgets per hour and runs for 4 hours each day. However, on weekends (Saturday and Sunday), each machine runs for an unknown number of hours per day, and due to a temporary slowdown in the production line, each machine produces only 10 gadgets per hour. Over a period of 4 weeks, the plant produced exactly 3,360 gadgets. Determine the number of hours each machine operates on Saturdays and Sundays during this period.", + "output":"Let hSat and hSun be the (constant) hours that each machine runs on a Saturday and on a Sunday, respectively, in any given week. Then over 4 weeks:\n\n1. Weekday output \n – Each machine makes 12 gadgets\/hour \n – Runs 4 hours\/day, 5 days\/week ⇒ per machine per week = 12·4·5 = 240 gadgets \n – 3 machines ⇒ 3·240 = 720 gadgets\/week \n – Over 4 weeks ⇒ 4·720 = 2880 gadgets\n\n2. Weekend output \n – Each machine makes 10 gadgets\/hour \n – Runs hSat on Saturday and hSun on Sunday ⇒ per machine per weekend = 10·(hSat + hSun) \n – 3 machines ⇒ 3·10·(hSat + hSun) = 30·(hSat + hSun) gadgets per weekend \n – Over 4 weekends ⇒ 4·30·(hSat + hSun) = 120·(hSat + hSun)\n\nTotal over 4 weeks is given as 3360 gadgets, so \n Weekdays + Weekends = 3360 \n 2880 + 120·(hSat + hSun) = 3360 \n 120·(hSat + hSun) = 480 \n hSat + hSun = 4\n\nIn the absence of any other distinction, the most natural assumption is that Saturday and Sunday schedules are the same, so \n hSat = hSun = 4\/2 = 2 hours.\n\nAnswer: Each machine runs 2 hours on Saturdays and 2 hours on Sundays.", + "golden_answer":"2", + "source":"Bigmath_synth" + }, + { + "instruction":"A rectangular storage container has a base area of 6 square meters. The base is a rectangle whose length and width are in the ratio 2 : 3, and the container has a fixed height of 4 meters. To protect the goods during shipping, the container is to be completely enclosed by a spherical safety cover. In order to allow for insulation, the cover must have a volume that is at least 20% larger than the minimum volume just needed to enclose the container. If the cost to produce the spherical cover is determined by its surface area at a rate of $15 per square meter, what is the minimum production cost? Express your answer in terms of π and simplify any exponents.\n\nConsider that for any rectangular prism with length L, width W, and height H the smallest sphere that can contain it must have a radius equal to half the length of the space diagonal, that is, r₀ = (1\/2)·√(L² + W² + H²). Note that the extra 20% in volume means that the actual sphere must have a radius r satisfying\n\n  (4⁄3)π·r³ = 1.2·(4⁄3)π·(r₀)³     (1)\n\nYour answer will be expressed in terms of known quantities.", + "output":"First, since the base area is 6 m² and the sides are in the ratio 2 : 3, write \n L=2x, W=3x, (2x)(3x)=6 ⇒6x²=6⇒x=1. \nThus L=2 m, W=3 m, and H=4 m.\n\nThe minimal‐enclosing sphere has radius \n r₀=½√(L²+W²+H²)=½√(4+9+16)=½√29. \n\nWe need a 20% larger volume, so by \n (4\/3)π r³=1.2·(4\/3)π r₀³ \nwe get \n r=(1.2)^{1\/3}·r₀=(6\/5)^{1\/3}·(√29\/2). \n\nThe cost is \\$15 per m² of surface, and the sphere’s area is 4πr², so \n Cost=15·4πr²=60π·r² \n  =60π·[(6\/5)^{1\/3}·(√29\/2)]² \n  =60π·(6\/5)^{2\/3}·(29\/4) \n  =(60·29\/4)·(6\/5)^{2\/3}π \n  =15·29·(6\/5)^{2\/3}π \n  =435 π (6\/5)^{2\/3}. \n\nAnswer:  $\\displaystyle 435\\,\\pi\\,(6\/5)^{2\/3}\\,$.", + "golden_answer":"3", + "source":"Bigmath_synth" + }, + { + "instruction":"A chef is preparing full-course meals, where each meal consists of a starter, a main course, and a dessert. The starter requires 1 unit of spice mix A; the main course requires 2 units of spice mix A and 1 unit of spice mix B; and the dessert requires 1 unit of spice mix B. The chef has 10 packets of spice mix A, with each packet containing 4 units, and 8 packets of spice mix B, with each packet containing 3 units. However, 2 units of spice mix B must be reserved for emergencies and cannot be used in any meal. Assuming the chef uses the spices without any waste, what is the maximum number of full-course meals that can be prepared?", + "output":"First, calculate the total available units of each spice: \n• Spice A: 10 packets × 4 units = 40 units \n• Spice B: 8 packets × 3 units = 24 units, but 2 units are reserved → 24 – 2 = 22 units usable \n\nEach full‐course meal (starter + main + dessert) consumes: \n• Spice A: 1 + 2 + 0 = 3 units \n• Spice B: 0 + 1 + 1 = 2 units \n\nNow find how many meals each spice stock can support: \n• A‐limited: ⌊40 ÷ 3⌋ = 13 meals \n• B‐limited: ⌊22 ÷ 2⌋ = 11 meals \n\nThe B stock is the bottleneck, so the maximum number of full‐course meals is 11.", + "golden_answer":"11", + "source":"Bigmath_synth" + }, + { + "instruction":"A two‐phase experiment measures a force vector M along a specific direction. In Phase I, a calibrated device finds that the projection of M onto a direction represented by the unit vector N is 4 newtons. In Phase II, using another instrument that reports projections differently, the same projection is recorded as 5 newtons; however, this second device is known to overestimate the true projection by 25% whenever the angle between M and N is acute and to underestimate it by 15% when the angle is obtuse. Determine the value of M ⋅ N and indicate whether the angle between M and N is acute or obtuse.", + "output":"Let p = M·N be the true projection. The second instrument reads \n‐ if ∠(M,N) is acute: R = 1.25 p \n‐ if ∠(M,N) is obtuse: R = 0.85 p \n\nSince it reports R = 5 N, we get two candidates: \n acute: p = 5\/1.25 = 4 N \n obtuse: p = 5\/0.85 ≃ 5.88 N \n\nBut Phase I (a calibrated device) told us p = 4 N, so the only consistent case is the acute one. \n\nAnswer: M·N = 4 newtons, and the angle between M and N is acute.", + "golden_answer":"4", + "source":"Bigmath_synth" + }, + { + "instruction":"Let k be a real number and consider the quadratic equation \n  x² – 10x + (|2k – 3| + |k + 5|) = 0.\n(a) Determine all values of k for which this equation has two distinct real roots that are both nonnegative.\n(b) Under the condition in part (a), find the set of k for which the product of the roots is at least 16.", + "output":"Let C(k)=|2k–3|+|k+5|. The equation is \n x²–10x+C(k)=0 \nwith sum of roots S=10>0 and product P=C(k). Its discriminant is Δ=100–4C(k), so two distinct real roots ⇐⇒ C(k)<25. Since C(k)≥0 always, the smaller root is 5–√(25–C)≥0 automatically, so the only nonnegativity condition is C(k)<25. \n\n1. Solve |2k–3|+|k+5|<25. Break at k=–5 and k=3\/2: \n • k<–5: |2k–3|=3–2k, |k+5|=–(k+5) ⇒ C=–3k–2<25 ⇒ k>–9 ⇒ –9 0) or to the left (if p < 0). In addition, laboratory tests have shown that the point (5, 4) must lie on the surface of the dish. \n\na) Write the standard (vertex form) equation of the parabola in terms of the parameter p.\n\nb) Using the condition that (5, 4) lies on the parabola, determine the value of p. Then, identify which orientation (opening to the right or to the left) yields this value and write the final equation of the dish’s parabola.", + "output":"a) Since the vertex is at (h,k)=(1,1) and the axis is horizontal (y=1), the parabola in vertex‐form is \n  (y−1)² = 4p (x−1) \nwhere p is the signed focal‐parameter (p>0 ⇒ opens right, p<0 ⇒ opens left). \n\nb) Plug in (x,y)=(5,4): \n  (4−1)² = 4p (5−1) \n  9 = 4p·4 =16p \n⇒ p = 9\/16 (>0). \n\nSince p>0 the parabola opens to the right, and 4p=4·(9\/16)=9\/4. Thus the final equation is \n  (y−1)² = (9\/4) (x−1).", + "golden_answer":"1", + "source":"Bigmath_synth" + }, + { + "instruction":"At a farmer’s market, a vendor has 384 oranges and 192 lemons. The lemons are bundled evenly into 16 bundles. The oranges are packed in two types of crates: large crates hold 24 oranges each, and small crates hold 12 oranges each. To offer a balanced display, the vendor packs the oranges so that the total number of oranges in all the large crates is exactly three times the total number of oranges in all the small crates. Determine how many large crates and how many small crates were used, and how many lemons are in each bundle.", + "output":"Let L = number of large crates and S = number of small crates. Then\n\n1) Total oranges: 24·L + 12·S = 384 \n2) Balance condition: (oranges in large) = 3×(oranges in small) \n ⇒ 24·L = 3·(12·S) = 36·S \n ⇒ L = (36\/24) S = (3\/2) S \n\nFrom L = (3\/2) S plug into 24·L +12·S =384:\n 24·(3\/2 S) +12·S =36 S +12 S =48 S =384 \n ⇒ S =384\/48 =8 \n ⇒ L =(3\/2)·8 =12 \n\nAnd the lemons, 192 of them, are split evenly into 16 bundles:\n lemons per bundle = 192\/16 =12. \n\nAnswer:\n• Large crates: 12 \n• Small crates: 8 \n• Lemons per bundle: 12", + "golden_answer":"12", + "source":"Bigmath_synth" + }, + { + "instruction":"A drone is set to follow a straight-line flight path given by the equation y = 2x + 4. However, due to new airspace restrictions, the flight plan is modified in two stages:\n\n1. The original path is rotated 90° counterclockwise about the fixed control point P(2, 3) to yield a new path L₁.\n2. To ensure safe clearance from obstacles, L₁ is then shifted vertically upward so that its y-intercept increases by exactly 6 units, producing the final flight path L₂.\n\n(a) Find the equation of the final flight path L₂.\n\n(b) Determine whether the x-intercept of L₂ lies to the left or to the right of the point P. Provide a brief explanation to support your conclusion.", + "output":"Here is a step‐by‐step solution.\n\n1. Start with the original line \n y = 2x + 4. \n A direction vector for this line is v = (1, 2).\n\n2. Rotate that line 90° CCW about P(2,3). \n – Rotating the direction vector v=(1,2) by 90° CCW gives \n v′ = (–2, 1). \n – Thus the slope of the rotated line L₁ is m₁ = rise\/run = 1\/(–2) = –½. \n – And L₁ passes through P(2,3), so in point–slope form: \n y–3 = (–½)(x–2) \n ⇒ y = –½ x + 1 + 3 = –½ x + 4. \n\n3. Shift L₁ upward so its y‑intercept goes from 4 to 10 (i.e. +6). \n This yields the final path L₂: \n y = –½ x + 10. \n\n(a) Answer: L₂: y = –½ x + 10. \n\n(b) Its x‑intercept is found by setting y=0: \n 0 = –½ x + 10 ⇒ x = 20, so the intercept is (20,0). \n Since 20 > 2, this point lies to the right of P(2,3).", + "golden_answer":"23", + "source":"Bigmath_synth" + }, + { + "instruction":"A science fair assigns project scores using the formula\n  S(x) = x² – 4x + 6,\nwhere x is the project’s difficulty rating. Two students choose individual projects with different difficulty ratings a and b and each earns the same score (that is, S(a) = S(b)). Later, a team project is entered with difficulty rating (a + b) and it earns a score n that is exactly 20% higher than the individual score earned by each student. Find n.\n\n", + "output":"First note that \n S(a)=S(b) \nimplies \n a²−4a+6 = b²−4b+6 \n⇒ a²−b² =4(a−b) \n⇒ (a−b)(a+b−4)=0. \nSince a≠b, we get a+b=4. \nHence the team score is \n n = S(a+b) = S(4) = 4²−4·4+6 = 6. \nCheck: the individual score is S(a)=a²−4a+6; from 6=1.2·S(a) ⇒ S(a)=5, which indeed happens for a=2±√3. \nAnswer: n=6.", + "golden_answer":"6", + "source":"Bigmath_synth" + }, + { + "instruction":"Alice and Bob are making deliveries in a city. When driving in urban zones, the speed limit is 20 miles per hour, and when driving in suburban zones, it is 40 miles per hour. Alice’s entire route is in the urban zone, and she drives for 90 minutes at the urban speed limit. Bob’s route covers both suburban and urban areas; he drives for a total of 2 hours, spending 75% of his driving time in suburban areas and 25% in urban areas. However, due to a minor incident, Bob must reduce his suburban driving speed by 25% (relative to the suburban speed limit). Calculate the total distance traveled by Alice and Bob combined.", + "output":"Alice’s distance \n• Speed = 20 mph, Time = 90 min = 1.5 h \n• Distance = 20 mph × 1.5 h = 30 mi \n\nBob’s distance \n• Total time = 2 h \n – Suburban time = 0.75×2 h = 1.5 h \n – Urban time = 0.25×2 h = 0.5 h \n• Suburban speed = 40 mph × (1 – 0.25) = 30 mph \n – Suburban distance = 30 mph × 1.5 h = 45 mi \n• Urban speed = 20 mph \n – Urban distance = 20 mph × 0.5 h = 10 mi \n• Bob’s total = 45 mi + 10 mi = 55 mi \n\nCombined distance = 30 mi + 55 mi = 85 miles.", + "golden_answer":"85", + "source":"Bigmath_synth" + }, + { + "instruction":"Three competitors in a contest receive scores a, b, and c that satisfy\n  a² + b² + c² = 52  and  ab + ac + bc = 72.\nTheir preliminary total score is a + b + c. In the contest rules, if the preliminary total is less than 15, an extra 3 points are added as a bonus; if it is 15 or more, 2 points are deducted as a penalty. Find the final adjusted total score.", + "output":"We set S = a+b+c. Then \nS² = (a²+b²+c²) + 2(ab+ac+bc) = 52 + 2·72 = 196 \n⇒ S = ±14. Since scores are (non‐negative) preliminaries we take S=14. \nThen 14<15 so we add 3 ⇒ final total = 14+3 = 17.", + "golden_answer":"17", + "source":"Bigmath_synth" + }, + { + "instruction":"At a science museum, an adult admission is $10 and a child ticket is sold at a full price of x dollars. However, if a group has more than 5 children, any child beyond the fifth receives a 50% discount on the ticket. A teacher brings 1 adult along with 7 children. Paying with a $60 bill, the teacher receives $10 in change. What is the full price, in dollars, of a child ticket?", + "output":"Let A be the number of adults (each \\$10) and C=7 the number of children. Since “a teacher brings 1 adult” there are actually 2 adults paying. Children beyond the first 5 get a 50% discount, so\n\nAdult cost = 2·10 = \\$20 \nChild cost = 5·x + 2·(½x) = 5x + x = 6x \n\nTotal spent = \\$20 + 6x. They hand over \\$60 and get \\$10 back, so they’ve actually paid \\$50:\n\n 20 + 6x = 50 \n 6x = 30 \n x = 5.\n\nHence the full‐price child ticket is \\$5.", + "golden_answer":"5", + "source":"Bigmath_synth" + }, + { + "instruction":null, + "output":null, + "golden_answer":null, + "source":null + } +] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/VQA/pic_path.json b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/VQA/pic_path.json new file mode 100644 index 0000000000000000000000000000000000000000..d733a77d4c84a20885c1263f5cec83701625c43a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/VQA/pic_path.json @@ -0,0 +1,5 @@ +[ + {"raw_content": "../example_data/VQA/pdfimages/page_0.jpg"}, + {"raw_content": "../example_data/VQA/pdfimages/page_1.jpg"}, + {"raw_content": "../example_data/VQA/pdfimages/page_2.jpg"} +] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/chemistry/matched_sample_10.json b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/chemistry/matched_sample_10.json new file mode 100644 index 0000000000000000000000000000000000000000..ba43ce6bdca047746fb4538dfaa16d8e52dfe74f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/chemistry/matched_sample_10.json @@ -0,0 +1,294 @@ +[ + { + "abbreviations": [ + { + "abbreviation": "6FDA" + } + ], + "csv": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/label_data/10.1002/app.24047.csv", + "golden_label": [ + { + "abbreviation": "6FDA", + "full_name": "2,2-Bis(3,4-dicarboxyphenyl)hexafluoropropane dianhydride", + "smiles": "O=C1OC(=O)c2cc(C(c3ccc4c(c3)C(=O)OC4=O)(C(F)(F)F)C(F)(F)F)ccc21" + } + ], + "path": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/pdf_data/10.1002/app.24047_uniparser.json", + "pdf": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/pdf_data/10.1002/app.24047.pdf", + "text": "\\begin{title}\nThermal Cure of Phenylethynyl-Terminated AFR-PEPA-4 Imide Oligomer and a Model Compound\n\\end{title}\n\nYuntao Li, Roger J. Morgan\n\nDepartment of Mechanical Engineering, Texas A&M University, Texas 77843\n\nReceived 27 July 2005; accepted 26 December 2005 DOI 10.1002/app.24047 Published online in Wiley InterScience (www.interscience.wiley.com).\n\nABSTRACT: The thermal cure reactions of phenylethynyl terminated AFR-PEPA-4 oligomer and a model compound N-phenyl-[4-(phenylethynyl) phthalimide] were investi- gated. The kinetics analysis of the thermal cure of AFR- PEPA-4 was determined using DSC, with modified DiBenedetto equation. The activation energy of thermal cure reaction of AFR-PEPA-4 oligomer is 34.1 kcal/mol with the kinetic order of one, when the reaction conversion is less than 80%. The activation energy of thermal reaction of\n\n\\begin{title}\nINTRODUCTION\n\\end{title}\n\nPolyimides possess outstanding key properties such as high use temperature (above 300°C), thermooxida- tive stability, high mechanical strength, high modulus, excellent electrical properties, and superior chemical resistance.1 Because of these merits, polyimides have become one of the leading polymer materials for high temperature composites in aerospace structural appli- cations. Compared with norbornyl/amine or ethynyl terminated polyimides, phenylethynyl terminated polyimides exhibit many advantages2–5 such as (1) no evolution of volatiles during the cure reaction, (2) larger processing window, (3) excellent mechanical properties, in particular outstanding fracture tough- ness value, and (4) higher hydrolytical stabilities. NASA’s PETI-5, for example, received enormous at- tention during the development of the high speed civil transportation program. It crosslinks between 320 and 371°C range and at a pressure of 1 MPa, which can be easily processed by resin transfer molding (RTM).6 PETI-5 polyimides demonstrated excellent hot/wet properties and high toughness (strain to failure from 14 to 84% in the 23–177°C temperature range).6 How- ever, the glass transition temperature (Tg) of PETI-5 is low, which is about 270°C.\n\nCorrespondence to: R. J. Morgan (rjmorgan@tamu.edu). Contract grant sponsor: Air Force Office of Scientific Re- search; contract grant number: FA 9550–04-1–0137.\n\nContract grant sponsor: State of Texas Advanced Research Project.\n\nJournal of Applied Polymer Science, Vol. 101, 4446–4453 (2006) © 2006 Wiley Periodicals, Inc.\n\nN-phenyl-[4-(phenylethynyl) phthalimide] is 41.5 kcal/mol with the kinetic order of 0.95. The cure reaction of AFR- PEPA-4 imide oligomer can be described as a fast first-order reaction stage for the formation of polyenes followed by a slow diffusion-controlled crosslinking reaction stage. © 2006 Wiley Periodicals, Inc. J Appl Polym Sci 101: 4446–4453, 2006\n\nKey words: polyimides; thermal cure; kinetics\n\nIt was found that polyimides synthesized from 2,2 - bis(3,4-dicarboxyphenyl)hexafluoropropane dianhy- dride (6FDA), with the structure of perfluoromethyl substituents, always have extremely high use temper- atures and stabilities.7 The fluorinated polyimide AFR-700B, developed by the Air Force, showed excel- lent thermo-oxidative resistance and a high Tg above 400°C. Unfortunately, AFR 700B polyimide experi- enced significant decreases in strength ( 70%) and Tg (75°C) after 1000 h at 160°C in a hygrothermal pressure bomb environment.8,9 The hydrolyzable weak link was found to be norbornene crosslinks, which originate from the nadic end-caps. Recently, AFR-PEPA-N imide oligomer was synthesized with the fluorinated backbone 6FDA and the phenylethy- nyl end-caps, 4-(phenylethynyl)phthalic anhydride (PEPA).7 AFR-PEPA-N exhibited only a 3–5% de- crease in dry Tg after hygrothermal exposure, which is similar to PETI-5.7 In addition, AFR-PEPA-N polyim- ides showed (1) extremely high Tgs (435–455°C), (2) significantly improved mechanical properties at 300°C compared with AFR 700B, (3) the potential to be pro- cessed by RTM, (4) high ductility for a high tempera- ture polyimide (ambient temperature elongation to break of 5%), and (5) slightly lower thermo-oxidative stability compared with AFR 700B.7 Therefore, AFR- PEPA-N polyimides were promptly deployed on ultrahigh temperature light weight composites for aerospace structural applications. However, no stud- ies, as yet, have been performed to characterize the network of AFR-PEPA-N polyimides and the effects of thermal history on the cured products. Cure reactions and kinetics of AFR-PEPA-N oligomers need to be\n\ninvestigated, to further understand the structure- property-processing relations of AFR-PEPA-N poly- imides.\n\nSeveral studies on the thermal cure of phenylethy- nyl terminated imide oligomers have been reported. Johnston et al.10 synthesized and characterized a series of phenylethynyl end-capped imide oligomers with PEPA and substituted PEPAs containing electron- withdrawing groups. Takekoshi and Terry11 studied thermal reactions of two PEPA model compounds, N-[3-(phenylethynyl)phenyl]phthalimide and N-phe- nyl-4-(phenylethynyl)phthalimide, by using high- pressure liquid chromatography (HPLC) and field- desorption mass spectroscopy. Fang et al.12 studied the kinetic mechanism of thermal cure of PETI-5 oli- gomer by thermal analysis using the modified DiBenedetto equation. It was found that thermal cure reaction of PETI-5 was 1.5th order, which suggested that complicated reaction mechanisms such as in- tramolecular and bimolecular double bond addition reactions are involved to form a highly crosslinked polyimide. Solid-state 13C NMR was also used to an- alyze the chemical structure of cured acetylene-termi- nated polyimides or acetylene containing model com- pounds.13–15 Although phenylethynyl groups are ex- pected to react by chain extension, crosslinking, and branching, it is still difficult to elucidate the cure ki- netics and mechanism of thermal cure of phenylethy- nyl-terminated imide oligomer because of the steric effect of the phenyl-ended functional groups, low con- centration of phenylethynyl groups in the oligomers, and insolubility of the cured products.\n\nIn the present study, thermal cure reactions of phe- nylethynyl-terminated AFR-PEPA-4 imide oligomer and a model compound N-phenyl-[4-(phenylethy- nyl)phthalimide] were characterized by infrared spec- troscopy (IR). The kinetics analysis of thermal cure of AFR-PEPA-4 imide oligomer was determined using differential scanning calorimetry (DSC) by following the Tg of the cured polyimides as a function of cure, which was simulated by the modified DiBenedetto equation. The aim of this work is to understand the thermal cure kinetics and mechanism of phenylethy- nyl-terminated imide oligomer AFR-PEPA-N.\n\n\\begin{title}\nEXPERIMENTAL\n\\end{title}\n\n\\begin{title}\nMaterials\n\\end{title}\n\n2,2 -Bis(3,4-dicarboxyphenyl)hexafluoropropane dian- hydride (6FDA), 1,4-diaminobenzene (p-PDA), and 4-(phenylethynyl)phthalic anhydride (PEPA) were ob- tained from Performance Polymer Solutions, OH. N-methyl-2-pyrrolidinone (NMP), aniline, acetic acid, and methanol were obtained from Aldrich. All chem- icals were used as received.\n\n\\begin{molecule}\nC(c1ccc2c(c1)C(=O)N(c1ccc(N3C(=O)c4ccc(C#Cc5ccccc5)cc4C3=O)cc1)C2=O)(c1ccc2c(c1)C(=O)N(c1ccc(N3C(=O)c4ccc(C#Cc5ccccc5)cc4C3=O)cc1)C2=O)(C(F)(F)F)C(F)(F)F\n\\end{molecule}\n\n\\begin{legend}\n(a)\n\\end{legend}\n\n\\begin{molecule}\nO=C1c2ccc(C#Cc3ccccc3)cc2C(=O)N1c1ccccc1\n\\end{molecule}\n\n\\begin{legend}\n(b)\n\\end{legend}\n\n\\begin{caption}\nFigure 1 Chemical structures of AFR-PEPA-4 imide oli- gomer and PEPA model compound. (a) Phenylethynyl-ter- minated imide oligomer AFR-PEPA-4; (b) N-phenyl-[4-(phe- nylethynyl) phthalimide].\n\\end{caption}\n\n\\begin{title}\nPhenylethynyl-terminated imide oligomer AFR- PEPA-4\n\\end{title}\n\nImide oligomer AFR-PEPA-4 was prepared from p- PDA, 6FDA, and PEPA in NMP solvent by the method reported by Lincoln.7 p-PDA (7.034 g, 0.065 mol) was dissolved in 150 mL NMP in a 500-mL, three-neck round-bottom flask equipped with a Teflon stirring bar and a gas adaptor, under a nitrogen atmosphere at room temperature. 6FDA (23.117 g, 0.052 mol) was dissolved in 150 mL NMP under a nitrogen atmo- sphere protection. The solution of 6FDA/NMP was then added in p-PDA/NMP solution, in three portions over 3 h. Once all of the 6FDA solution was added, stirring continued for 20 h at room temperature. PEPA (6.459 g, 0.026 mol) was added as a solid and was stirred until it completely reacted (4 h) under nitrogen. The NMP used is 10% solids by weight during the whole synthesis. Toluene was then added, and the resulting mixture was then imidized under reflux in 180°C-oil bath with the removal of water via azeotro- pic distillation. The reaction mixtures were finally added into distilled water, filtered, and washed in boiling water and then in warm methanol to remove the NMP. This produced very fine yellow powders that were dried under vacuum for 24 h at 160°C. The yield was 33.387 g (97.5%). The oligomer had a theo- retical molecular weight of 2634 g/mol and a glass transition temperature of 250°C (DSC) at 20°C/min. The chemical structure of AFR-PEPA-4 imide oli- gomer is shown in Figure 1(a).\n\n\\begin{title}\nN-Phenyl-[4-(phenylethynyl) phthalimide]\n\\end{title}\n\nPhenylethynyl model compound N-phenyl-[4-(phe- nylethynyl) phthalimide] was prepared following the method reported by Takekoshi and Terry.11 PEPA (31.029 g, 0.125 mol), aniline (12.200 g, 0.131 mol), and 225 mL of acetic acid were placed in a 500-mL, three- necked flask. The mixture was stirred under nitrogen\n\nand heated to reflux for 1.5 h. A total of 50 mL of water and acetic acid mixture was distilled off during the following 0.5-h period. The reaction mixture was cooled and the yellow crystalline solid was filtered. The product was washed with methanol and dried. The yield was 38.883 g (96.2%), mp 210–212°C. Ele- mental analysis calculated for C22H13O2N: C, 81.72%, H, 4.05%, N, 4.33%; found: C, 81.66%, H, 4.02%, N, 4.26%. FTIR (KBr): 2216 (C'C), 1780 (CAO), 1713 (CAO), 1611 (CAC) cm 1; 13C NMR (CDCl3): 166.62, 137.17, 132.20, 131.84, 131.52, 130.33, 129.27, 129.12, 128.52, 126.53, 126.49, 123.72, 122.03, 94.19, 87.70 ppm; Mass spectrum m/e 323 M . The chemical structure of AFR-PEPA-4 is shown in Figure 1(b).\n\n\\begin{title}\nCure reactions of the model compound and AFR- PEPA-4 oligomer\n\\end{title}\n\nThe range of reaction temperatures chosen for thermal cure of AFR-PEPA-4 oligomer and the model com- pound was determined by thermal analysis. Thermo- gravimetric analysis (TGA) of AFR-PEPA-4 oligomer was performed on a TGA Q500 thermal analyzer. The heating atmospheres were air or nitrogen. The sam- ples were heated to 800°C at 10°C/min. DSC analysis was performed by a Perkin–Elmer DSC Pyris 7 sys- tem. Temperature was scanned from 100 to 450°C at 20°C/min.\n\nAbout 0.2 g samples were cured in small glass vials in a preheated furnace. After curing at the desired temper- ature for a certain time (from 2 min to 8 h), the samples were cooled promptly and removed from the vials for characterization. FTIR analysis was used to monitor the reaction conversion after curing. A Nicolet AVATAR 360 spectrometer was used in this study. Samples were pre- pared as KBr pellets. The number of accumulations was set at 64 with a resolution of 2 cm 1.\n\nTgs of cured AFR-PEPA-4 were measured by DSC at a heating rate of 20°C/min under nitrogen atmo- sphere. The modified DiBenedetto equation12,16,17 was used to calculate the reaction extent x according to Tg as follows\n\n\\begin{equation}\n\\frac{T_{g}-T_{g 0}} {T_{g^{\\infty}} \\!-\\! T_{g^{0}}} \\!=\\! \\frac{\\lambda x} {1 \\!-\\! ( 1 \\!-\\! \\lambda) x}\n\\end{equation}\n\nwhere Tg0, Tg , and Tg are the glass transition temper- atures before complete cure, after complete cure, and the glass transition temperature of the sample after curing at a cure temperature for a specified cure time, respectively. is the ratio of isobaric heat specified time of the fully cured material to that of uncured material. The isobaric heat capacities can be deter- mined by DSC. It should be noted that even if the selected Tg does not correspond to the theoretically ideal fully cured system, cure extent x is still valid for kinetic analysis according to this equation.12\n\n\\begin{token}\n(1)\n\\end{token}\n\n\\begin{caption}\nTABLE I TGA Results of AFR-PEPA-4 Oligomer\n\\end{caption}\n\n\\begin{table}\n| ('Weight loss (%)', 'Weight loss (%)') | ('Temperature (℃)', 'Air') | ('Temperature (℃)', '$N ₂2$') |\n|:-----------------------------------------|:-----------------------------|:--------------------------------|\n| 1 | 339.6 | 342.8 |\n| 2 | 480.1 | 488.6 |\n| 5 | 524.2 | 527.4 |\n| 10 | 543.8 | 548.7 |\n| 20 | 564.8 | 584.5 |\n\\end{table}\n\nHeating rate 10°C/min.\n\n\\begin{title}\nCure characterization of AFR-PEPA-4 oligomer\n\\end{title}\n\nThe temperatures for various weight losses of AFR- PEPA-4 oligomer calculated from TGA are listed in Table I. In nitrogen atmosphere, the temperatures for 1, 2, 5, 10, and 20% weight losses of AFR-PEPA-4 oligomer are higher than those in air. The oligomer has less than 2% weight loss in both air and N2 when the temperature is lower than 480°C. A DSC study of AFR-PEPA-4 oligomer shows that the cure reaction starts at 370°C and reaches the peak at 410°C. On the basis of the thermal analysis results, the temperature window for thermal curing of AFR-PEPA-4 oligomer can be chosen from 340 to 430 °C to ensure the occur- rence of crosslinking reaction without serious thermal degradation. In this article, the cure temperatures 350, 370, 390, and 410°C were chosen to study the effect of temperature on cure reactions of AFR-PEPA-4 oli- gomer.\n\nFTIR spectra of AFR-PEPA-4 oligomer is shown in Figure 2. Since the absorption around 2213 cm 1 is attributed to C'C in ethynyl group, the reaction con- version of AFR-PEPA-4 oligomer during the curing can be given by the consumption of C'C triple bonds through the calculation of the decreased intensities of the bands at 2213 cm 1. The absorption of imide CAO stretching around 1726 cm 1 and 1785 cm 1, inert from the reactions, can be used as internal standard. Absorption bands around 1511 cm 1 and 1367 cm 1 are attributed to benzene ring and aromatic imide CON stretching, respectively. The reaction conversion can be calculated by relative intensity ratio compared between the intensity of the reaction involved peaks and that of internal standard. The reaction conversion can be calculated by eq. (2)\n\n\\begin{equation}\n\\alpha=\\left( \\frac{I^{2 2 1 3}} {I^{1 7 8 5}} \\right)_{t} / \\left( \\frac{I^{2 2 1 3}} {I^{1 7 8 5}} \\right)_{t=0}\n\\end{equation}\n\n\\begin{token}\n(2)\n\\end{token}\n\nThe quantitative results are shown in Figure 3. The reaction conversion of AFR-PEPA-4 oligomers in-\n\n\\begin{caption}\nFigure 2 FTIR spectra of AFR-PEPA-4 imide oligomer.\n\\end{caption}\n\ncreased with the increase of cure time, when they were cured at 350°C in air atmosphere. However, when the cure time is longer than 1 h and the reaction conver- sion is more than 85%, FTIR cannot detect the 2213 cm 1 band because of the limited resolution and the relatively low concentration of phenylethynyl groups in AFR-PEPA-4 oligomer. On the basis of the calcula- tion from residual exothermal reaction H in DSC test, the curing is not complete even over 8-h cure at 350°C and the degree of cure is about 90%.\n\nA plot ln [1 ] versus t for the cure reaction of AFR-PEPA-4 oligomer at 350°C in 1 h yields a straight line, which is shown in Figure 4. Therefore, according to cure conversion calculated from FTIR data, the cure kinetic obeys first order during the first 1 h at 350°C.\n\n\\begin{caption}\nFigure 3 Reaction conversion of AFR-PEPA-4 oligomer versus cure time at 350°C from FTIR data.\n\\end{caption}\n\n\\begin{caption}\nFigure 4 Reaction kinetic plot of ln (1 ) versus time for thermal cure of AFR-PEPA-4 at 350°C from FTIR data.\n\\end{caption}\n\nTgs of cured AFR-PEPA-4 were determined by DSC. An illustration of the Tg before and after cure at 350°C is shown in Figure 5. The plot of Tg versus cure time of AFR-PEPA-4 oligomer cured at 350°C is shown in Figure 6. The increase of Tg is almost linear in the first 1 h of curing. After that, the increase of Tg has a remarkable drop due to diffusion restriction. On the basis of the modified DiBenedetto eq. (1), the depen- dence of Tg on reaction conversion of phynylethynyl C'C in AFR-PEPA-4 oligomers can be simulated, which is shown in Figure 7, indicating that good agreement between the simulated curve and experi- mental data from FTIR. Therefore, this simulation method is reliable to calculate the reaction conversions based on measured Tgs.\n\nThe dependences of Tg of cured oligomers on cure time at various cure temperatures in air are shown in\n\n\\begin{caption}\nFigure 5 DSC curves of AFR-PEPA-4 oligomer before and after cure at 350°C.\n\\end{caption}\n\n\\begin{caption}\nFigure 6 Tg versus cure time of AFR-PEPA-4 oligomer cured at 350°C.\n\\end{caption}\n\nFigure 8. The Tg of the cured oligomer increases with the increase of cure time and cure temperature. The cure temperature 410°C gave the highest cure reaction rate at the beginning of the curing, at which the sam- ple’s Tg went to 381°C, with only 5 min curing. The cure reaction rate tends to be stable after the curing reaches a certain extent because of the diffusion con- trol. The Tgs of cured oligomers after 8 h curing at 350, 370, 390, and 410°C are 371, 385, 398, and 418°C, respectively.\n\nSince FTIR cannot detect the absorption of residue phenylethynyl group in the highly crosslinked AFR- PEPA-4 polyimide, in our study, the reaction conver- sion of AFR-PEPA-4 oligomer cured at various tem- peratures can be calculated from the Tg of cured sam- ples by using modified DiBenedetto equation obtained earlier. Tgs as a function of reaction conversion are shown in Figure 9.\n\n\\begin{caption}\nFigure 7 Tg as a function of reaction conversion of AFR- PEPA-4 oligomer cured at 350°C.\n\\end{caption}\n\n\\begin{caption}\nFigure 8 Tg versus cure time of AFR-PEPA-4 oligomer cured at various temperatures.\n\\end{caption}\n\nA plot of the ln (1 ) versus cure time (Fig. 10) for a first-order reaction shows significant deviation from linearity once the reaction conversion exceeds 80%. If only the experimental points below 80% cure are selected, first order kinetics better simulates the ki- netic data (Table II). Thus, the activation energy Eact can be obtained by plot ln k versus 1/T (Fig. 11), which is 34.1 2.4 kcal/mol with a regression coefficient of 0.995.\n\nFang et al.12 investigated the cure reaction of PETI-5 and found that it followed first order kinetics yielding an activation energy of 37.2 kcal/mol when the cure process was below 90%. It is close to our result for curing of AFR-PEPA-4 oligomer. Studies on solid- state 13C NMR showed that the primary thermal cure reaction ( 70%) of acetylene-terminated imide oli- gomers is ethynyl to ethynyl addition that forms poly-\n\n\\begin{caption}\nFigure 9 Tg as a function of reaction conversion of cured AFR-PEPA-4 oligomer.\n\\end{caption}\n\n\\begin{caption}\nFigure 10 Kinetic plots of ln (1 – ) versus time from DSC Tg data.\n\\end{caption}\n\nene structures.13 Although Diels-Alder cycloaddition between two phenylethynyl groups was expected to be the most probable crosslink mechanism for imide oligomers containing internal acetylene units,15 phe- nylethynyl-terminated imide oligomers may not fol- low this mechanism, because the molecular motion at the internal acetylene groups is more restricted than at the termini. Fang et al.12 also described a 1.5th order kinetics for whole cure reaction of PETI-5, with an activation energy of 33.8 kcal/mol. However, in our study, this reaction order failed to describe the data over the whole range of conversion values for com- plete cure. Since 6FDA gives the backbone of AFR- PEPA-4 imide oligomer a higher degree of rotation,15 the further reaction of polyenes may be more compli- cated. The heats of reaction do not adequately define the reaction for complete cure.\n\n\\begin{title}\nThermal reaction of N-phenyl-[4-(phenylethynyl) phthalimide]\n\\end{title}\n\nCompared with AFR-PEPA-4 imide oligomer, the model compound N-phenyl-[4-(phenylethynyl) phthal-\n\n\\begin{caption}\nTABLE II Kinetic Analysis of the Thermal cure of AFR-PEPA-4 by DSC (First Order Below 80% Cure)\n\\end{caption}\n\n\\begin{table}\n| Temperature (℃) | Rate constant (min−1) | Regression coefficient |\n|:------------------|:------------------------|:-------------------------|\n| 350 | 0.0339 | 0.973 |\n| 350^ | 0.02967 | 0.988 |\n| 370 | 0.06952 | 0.911 |\n| 390 | 0.14797 | 0.965 |\n| 410 | 0.3893 | 1 |\n\\end{table}\n\na Analysis by reaction conversion data from FTIR.\n\n\\begin{caption}\nFigure 11 Kinetic plot of ln k versus 1/T of the cure reac- tion of AFR-PEPA-4 oligomer for first order (below 80% cure).\n\\end{caption}\n\nimide] has much more concentrated phenylethynyl groups in its chemical structure, which allows us to easily monitor the consumption of C'C in phenylethy- nyl during the cure reaction by IR study.\n\nDSC data of N-phenyl-[4-(phenylethynyl) phthalim- ide] showed a sharp peak for the melting at 210°C. The reaction started from 320°C and reached the peak at 397°C. Thermal reactions of this model compound at various temperatures 330, 350, 370, and 390°C were monitored by FTIR, using the procedure similar to that for AFR-PEPA-4 oligomer. From the IR spectra shown in Figure 12(a), the absorption peak of 2216 cm 1 decreases with the increase of cure time, indi- cating the consumption of C'C triple bonds during thermal reaction. Moreover, it was found that the in- tensity of another absorption band around 1611 cm 1, which could be attributed to stretching vibrations of CAC conjugated with ethynyl group,18 also decreased during the reaction [Fig. 12(b)]. It was observed that the absorption band of phenylethynyl group switches to lower wavenumbers and that of conjugated bonds switches to higher wavenumbers during the thermal reaction. However, in IR spectra of phenylethynyl- terminated imide oligomers, the absorption at 1611 cm 1 always overlaps with 1580 cm 1, which is attrib- uted to aromatic structure itself.\n\nThe quantitative results are shown in Figure 13. The reaction conversion of N-phenyl-[4-(phenylethynyl) phthalimide] increased with the increase of cure time. Assuming that the cure reaction follows nth order kinetics, the rate equation can be written as\n\n\\begin{equation}\n- \\, \\frac{d [ A ]} {d t} {=} k [ A ]^{n}\n\\end{equation}\n\nBy simulating the cure reactions as nth order kinetics from reaction conversion data, the kinetics order of\n\n\\begin{token}\n(3)\n\\end{token}\n\n\\begin{legend}\n(a)\n\\end{legend}\n\n\\begin{legend}\n(b)\n\\end{legend}\n\n\\begin{caption}\nFigure 12 Changes of IR absorption during the thermal reaction of N-phenyl-[4-(phenylethynyl)phthalimide] at 330°C in air (a) C'C at 2216 cm 1; (b) conjugate bonds at 1611 cm 1.\n\\end{caption}\n\n0.95 fits the reaction best. The rate constant for thermal reactions at 330, 350, 370, and 390°C is 0.03,375, 0.09,557, 0.3303, and 0.8110 min 1, respectively. Thus, the activation energy Eact can be obtained by plot ln k versus 1/T (Fig. 14), which is 41.5 2.0 kcal/mol with a regression coefficient of 0.998.\n\nTakekoshi and Terry11 reported that the thermal reaction of N-phenyl-[4-(phenylethynyl) phthalimide] closely followed the first order with an activation en- ergy of 36.5 kcal/mol, which was obtained from HPLC study. Fang et al.12 utilized IR to monitor the cure kinetics of a phenylethynyl end-capped model compound 3,4 -bis[4-(phenylethynyl)phthalimido]di- phenyl ether (PEPA-3,4 -ODA). First order kinetics with an activation energy of 40.7 kcal/mol was re-\n\n\\begin{caption}\nFigure 13 Reaction conversion versus cure time of N-phenyl-[4-(phenylethynyl) phthalimide] cured at various temperatures.\n\\end{caption}\n\nvealed for the whole thermal reaction of PEPA-3,4 - ODA, indicating that ethynyl to ethynyl addition mainly occurred, though carbon–carbon saturated bonds were also formed from polyene structures.14 Unlike PEPA-3,4 -ODA or other imide oligomers, the model compound N-phenyl-[4-(phenylethynyl) phthalimide] has a much smaller molecule structure, so that other addition reactions such as Diels-Alder cycloaddition or cyclotrimerization can also take place without much steric hindrance and form polycyclic aromatic structures. Therefore, the whole thermal re- action of N-phenyl-[4-(phenylethynyl) phthalimide] cannot be simply described with first order kinetics.\n\nFang et al.12 proposed a two-stage kinetic/diffusion model for thermal curing of PETI-5 oligomer, which may also be valid for AFR-PEPA-4 system. On a fast\n\n\\begin{caption}\nFigure 14 Kinetics plot of ln k versus 1/T of the cure reaction of N-phenyl-[4-(phenylethynyl) phthalimide].\n\\end{caption}\n\n\\begin{molecule}\nC1(C=CC=CC=1)C(=O)NCC(=O)N1C(=O)C2C=C(C(=O)NCC3=CC=CC=C3)C(=O)N(*)C2=C1.C1C=C(C(=O)NCC2=CC=CC=C2)C(=O)N(*)C1=O.C1C=CC(C(=O)N*C2=CC=C(C(=O)N*)C=C2)=CC=1.C1=CC=C(C(=O)N*)C=C1C(=O)N(*)C(=O)C1=CC=C(C(=O)N*)C=C1.C1=CC=C(C(=O)N*)C=C1C(=O)N(*)C(=O)C1=CC=C(C(=O)NCC2=CC=C(C(=O)N*)C(=O)N2*)C1.C1C=CC=C(C(=O)N*)C=1C(=O)N(*)C(=O)C1=CC=C(C(=O)NCC2=C3C(=O)N(*)C(=O)C3=CC=C2C(=O)OCC2=CC=C(C(=O)NC3=CC=C(*)C=C3C(=O)NC(=O)C3=CC=C(*)C=C3)C=C2)C125:R[3]29:R[3]51:Ph59:Ph66:Ph68:Ph74:Ph74:Ph78:Ph78:Ph78:Ph78:Ph78:Ph\n\\end{molecule}\n\n\\begin{molecule}\nC(F)(F)(F)C(c1ccc2c(c1)C(=O)N(c1ccc(C)cc1)C2=O)(c1ccc2c(c1)C(=O)N(c1ccc(C)cc1)C2=O)C(F)(F)F\n\\end{molecule}\n\n\\begin{caption}\nFigure 15 Proposed chemical structure of partially cured AFR-PEPA-4 polyimide.\n\\end{caption}\n\nstage, the cure reaction takes place mainly by simple ethynyl to ethynyl addition reactions to form a partial cured polyene structure (Fig. 15), which follows first- order kinetics. On a slow second stage, crosslinking reaction is kinetically controlled by diffusion. The double bond addition reactions mainly occur in this stage. A series of reactions such as Diel-Alder, Friedel- Crafts, Straus and Glaser coupling reactions have been suggested.12 The formation of polycyclic aromatic structures derived from polyene causes the significant deviation from linearity of first order reaction, once the reaction conversion of the triple bond in phenyl- ethynyl groups exceeds 80%.\n\n\\begin{title}\nCONCLUSIONS\n\\end{title}\n\nThermal cure of phenylethynyl terminated imide oli- gomer AFR-PEPA-4 and model compound N-phenyl- [4-(phenylethynyl) phthalimide] were characterized. The changes in IR absorbance of phenylethynyl triple bonds at 2216 cm 1 and that of conjugated bonds at 1611 cm 1 of N-phenyl-[4-(phenylethynyl) phthalim-\n\nide] were detected. Thermal reaction of the model compound followed the kinetics with an order of 0.95. DSC was used in determining the cure kinetics of AFR-PEPA-4 oligomer by following the increase in Tg as a function of cure. The activation energy of thermal cure reaction of AFR-PEPA-4 oligomer is 34.1 2.4 kcal/mol with the kinetic order of one, when the reaction conversion is less than 80%. The cure process of imide oligomer can be described as a fast first order reaction stage forming polyene structures, followed by a slow diffusion-controlled crosslinking reaction stage.\n\n1. Ghosh, M. K.; Mittal, K. L. Polyimide: Fundamentals and Ap- plications. Marcel Dekker: New York, 1996.\n\n2. Hergenrother, P. M.; Bryant, R. G.; Jenson, B. J.; Havens, S. J. J Polym Sci Part A: Polym Chem 1994, 32, 3061.\n\n3. Tang, Y.; Xie, Y.; Pan, W.; Riga, A. Thermochim Acta 2000, 357, 239.\n\n4. Jayaraman, S. S.; McGrath, J. E. J Polym Sci Part A: Polym Chem 1995, 33, 1551.\n\n5. Georgiades, A.; Hamerton, I.; Hay, J. N.; Shaw, S. J. Polymer 2002, 43, 1717.\n\n6. Lincoln, J. E.; Morgan, R. J.; Shin, E. E. J Polym Sci Part B: Polym Phys 2001, 39, 2947.\n\n7. Lincoln, J. E. PhD Dissertation, Michigan State University, East Lansing, MI, 2001.\n\n8. Morgan, R. J.; Shin, E. E.; Zhou, J. In Proceedings of the 44th International SAMPE Symposium, Long Beach, CA, 1999, p 1098.\n\n9. Shin, E. E.; Morgan, R. J.; Zhou, J. In Proceedings of the 45th International SAMPE Symposium, Long Beach, CA, 2000, p 389.\n\n10. Johnston, J. A.; Li, F. M.; Harris, F. W.; Takekoshi, T. Polymer 1994, 35, 4865.\n\n11. Takekoshi, T.; Terry, J. M. Polymer 1994, 35, 4874.\n\n12. Fang, X.; Rogers, D. F.; Scola, D. A.; Stevens, M. P. J Polym Sci Part A: Polym Chem 1998, 36, 461.\n\n13. Swanson, S. A.; Fleming, W. W.; Hofer, D. C. Macromolecules 1992, 25, 582.\n\n14. Fang, X.; Xie, X.-Q.; Simone, C. D.; Stevens, M. P.; Scola, D. A. Macromolecules 2000, 33, 1671.\n\n15. Nakamura, K.; Ando, S.; Takeichi, T. Polymer 2001, 42, 4045.\n\n16. Pascault, J. P.; Williams, R. J. J. J Polym Sci Part B: Polym Phys 1990, 28, 85.\n\n17. DiBenedetto, A. T. J Polym Sci Part B: Polym Phys 1987, 25 1949.\n\n18. Socrates, G. Infrared and Raman Characteristic Group Frequen- cies, 3rd ed.; Wiley: Chichester, 2001; p 71.\n\n" + }, + { + "abbreviations": [ + { + "abbreviation": "PMDA" + } + ], + "csv": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/label_data/10.1063/1.2838341.csv", + "golden_label": [ + { + "abbreviation": "PMDA", + "full_name": "", + "smiles": "Nc1cc(OC(F)(F)C(O)(F)C(F)(F)C(F)(F)F)ccc1-c1ccc(OC(F)(F)C(O)(F)C(F)(F)C(F)(F)C(F)(F)F)cc1N" + } + ], + "path": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/pdf_data/10.1063/1.2838341_uniparser.json", + "pdf": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/pdf_data/10.1063/1.2838341.pdf", + "text": "\\begin{title}\nFabrication of graded index waveguides in azo polymers using a direct writing technique\n\\end{title}\n\nHamidreza Karimi–Alavijeh, Gholam-Mohammad Parsanasab, Mohammad-Amin Baghban, Edris Sarailou, Alireza Gharavi et al.\n\nCitation: Appl. Phys. Lett. 92, 041105 (2008); doi: 10.1063/1.2838341\n\nView online: http://dx.doi.org/10.1063/1.2838341\n\nView Table of Contents: http://apl.aip.org/resource/1/APPLAB/v92/i4\n\nPublished by the American Institute of Physics.\n\nAdditional information on Appl. Phys. Lett. Journal Homepage: http://apl.aip.org/ Journal Information: http://apl.aip.org/about/about_the_journal Top downloads: http://apl.aip.org/features/most_downloaded Information for Authors: http://apl.aip.org/authors\n\n\\begin{caption}\nindicated in the abstract. Reuse of AIP content is subject to the terms at: http://apl.aip.org/about/rights_and_permissions\n\\end{caption}\n\n\\begin{title}\nFabrication of graded index waveguides in azo polymers using a direct writing technique\n\\end{title}\n\nHamidreza Karimi–Alavijeh, Gholam-Mohammad Parsanasab, Mohammad-Amin Baghban, Edris Sarailou, and Alireza Gharavia Photonics Laboratory, Department of Electrical Engineering, School of Engineering, Shiraz University, Shiraz, Iran\n\nSirus Javadpour Department of Materials Science and Engineering, School of Engineering, Shiraz University, Shiraz, Iran\n\nVladimir Shkunovb\n\nTrans Photonics LLC, 2201 West Campbell Park Drive, Chicago, Illinois 60612,\n\nReceived 3 June 2007; accepted 8 January 2008; published online 28\n\nFast direct writing of waveguides on polymers using low power continuous-wave lasers has been investigated. Using the cis-trans property of a functionalized sulfonated azo chromophores, we have fabricated graded index waveguides with low loss, which is due to graded index sidewalls. Fabrication is done by exposing the polymer film to a 532 nm wavelength laser beam focused to about 5 m spot at the film. Losses were calculated to be 0.48 0.04 dB/cm at 830 nm wavelength with no surface deformation. This technique enables us to fabricate integrated optical circuits including directional couplers, dividers, filters, switches, etc., as they are currently investigated in our laboratory. © 2008 American Institute of Physics. DOI: 10.1063/1.2838341\n\nWith the advances in photonics and optical communica- tions and increase in bandwidth demand, there is an ever increasing need to move toward optical integrated circuits. To do so, convenient techniques and materials are needed to make this technology possible. Because of their ease of fab- rication, low cost, and refractive index compatible with op- tical fibers, polymeric materials are becoming attractive al- ternatives for nonlinear optical inorganic materials such as LiNbO3 or GaAs. Although currently produced in small scale, the polymeric materials used here can be produced in large scale at a relatively low cost and, therefore, offer com- pelling commercial advantages for the marketplace. The cost advantage of producing and fabricating organic polymeric integrated circuits is substantial compared to inorganic ma- terials such as silicon, GaAs, and LiNbO3. Fast redesign ca- pability will allow product cycles to be short and more effi- cient. This capability provides us with an accelerator to meet demand, improve performance, and optimize additional functionalities for photonic applications.\n\nSeveral devices such as Mach-Zehnder modulators and couplers,1–5 gratings,6 and photonic crystals7 have been in- vestigated using polymeric photonic materials. Fabrication of these components is being investigated in our laboratory us- ing our fabrication technique. We have previously demon- strated the fabrication of a grating based switch using the direct writing method.6 Polyimide functionalized with azo chromophores exhibits photoinduced birefringence8,9 due to reorientation of the azo chromophores by the cis-trans isomerization process. When exposed to light within their absorption band, this cis-trans isomerization induces align- ment in the chromophore in a direction perpendicular to the polarization of the exciting light, which reduces absorption. Birefringence resulting from this alignment of azobenzene groups could be used for producing waveguides or inducing\n\na Electronic mail: agharavi@shayda.com. b Currently at Raytheon Corporation.\n\n\\begin{title}\n0003-6951/2008/92 4 /041105/3/$23.00\n\\end{title}\n\nDownloaded 12 Apr 2013 to 137.149.3.15. This article is copyrighted as indicated in the abstract. Reuse of\n\nindex modulation into the depth of the polymers as well.6 Using optimized low power writing beams, we can make low loss graded index waveguides with no surface deformation. In this way, our index change is strictly due to the cis-trans isomerization. The significance of this work is not in the material used in this experiment but is to show the potential in a family of materials that have the cis-trans property and different optical and nonlinear properties. Similar index- changing effects such as photobleaching10,11 and photother- mal and/or photochemical12 cause significant surface deformation.\n\nThe material used here consists of a functionalized soluble polyimide with an azo optical chromophore. The chromophores were chemically attached to the host polymer for better optical and thermal stability. This material was synthesized by an approach similar to that of Saadeh et al.13 The absorption spectrum and chemical structure of the poly- meric material used are shown in Fig. 1. To make thin films\n\n\\begin{legend}\n(a)\n\\end{legend}\n\n\\begin{legend}\n(b)\n\\end{legend}\n\n\\begin{caption}\nFIG. 1. a Chemical structure of the polymeric material used in this work and b absorption spectrum of the polymeric material. This material was exposed to 532 nm for waveguide writing.\n\\end{caption}\n\n\\begin{caption}\nFIG. 2. Waveguide fabrication apparatus for direct laser-writing technique. The precision X-Y stage is controlled by the computer which moves the sample in the direction of the waveguide.\n\\end{caption}\n\nof these polymers, 300 mg of the polymer material was dis- solved in 2 ml of dimethyl formamide. The solution was then filtered with a 0.2 m filter and the total volume was re- duced to about 1 ml. The solution was then spin coated on 2.5 3.8 cm2 glass substrates. Depending on the spinning speeds, the film thickness ranged between 2 and 3 m. These films were then cured at 200 °C to form a hard film.\n\nFor waveguiding of a given mode to occur in a wave- guide, the following index condition must be satisfied:14\n\n\\begin{equation}\n\\Delta n=( n_{2}-n_{c} ) \\ge\\frac{m_{s}^{2} \\lambda^{2}} {1 6 t^{2} ( n_{2}+n_{c} )}\n\\end{equation}\n\n\\begin{equation}\n\\mathrm{w h e r e} \\ m_{s}=2 m+1 \\, ; \\quad m=0, 1, 2, \\, \\ldots\\,,\n\\end{equation}\n\n\\begin{token}\n1\n\\end{token}\n\nwhere n2 and nc are the refractive indices of the guide and cladding, t is the thickness of the guiding layer, m is the mode number, and is the wavelength of the guided light. For a 3 m film with a refractive index of about 1.6 at 830 nm wavelength, the minimum necessary change in the refractive index is about n=0.0014 for m=1. The refractive index of our polymer changes when exposed by a laser beam within the absorption range of the polymer. When measured by the prism coupler, the coupling angle of the waveguide and the film differed by 1°. This gave a n of about 0.01 between the waveguide and the film. This change is enough to write waveguides which can confine the light. To write waveguides using the laser-writing technique, the apparatus of Fig. 2 was constructed.\n\nThe X-Y stage has a resolution of 0.1 m. A computer program was written to control the stage for writing waveguides. The width of the written waveguide on the film depends on the waist and intensity of the writing laser beam and also on the speed of the moving film. The beam waist was controlled by a microscope objective located above the surface of the film, as shown in Fig. 2. The distance between the objective and the film was controlled by a microposi- tioner. The intensity and the polarization of the laser beam were adjusted by two polarizers. Rotating the upper polarizer adjusts the intensity of the laser light passing through it and the lower polarizer ensures the appropriate polarization needed to write the waveguide. The wavelength of the writ- ing beam is at the edge of the absorption spectrum of our polymer, as shown in Fig. 1 b . This way, uniform waveguides could be written in the depth of the polymer film.\n\nDownloaded 12 Apr 2013 to 137.149.3.15. This article is copyrighted as indicated in the abstract. Reuse of AIP\n\nin the abstract. Reuse of AIP content is subject to the terms at: http://apl.aip.org/about/rights_and_permissions\n\n\\begin{caption}\nFIG. 3. The coupled light 832 nm into an “s-curve” waveguide observed from above by a CCD camera. The waveguiding path is clearly observed by the scattered light. Inset: Waveguide profile observed through a polarizing microscope which shows the graded nature of the waveguide. We intention- ally chose a waveguide with high scattering path so that it would appear clearly in the picture.\n\\end{caption}\n\nAs experimentally determined, when the objective was at the focal point, the waist of the beam was about 2 m on the film. To write a waveguide with a width of 5 m, we moved the objective position 20 m upward. The power of the writing laser beam, having a Gaussian profile, deter- mined the quality of the waveguide. For best results, we found that in this material, 0.4–0.5 mW at the film was suit- able to make the desired Gaussian profile with chromophore orientation perpendicular to the waveguide propagation di- rection. The polarization of the laser beam was parallel to the path of the waveguide and the writing speed was 0.1 mm/s. To distinguish the path of the light in the waveguide from the path of light in the film, which is called slab guided light, we curved the path of the waveguide in an s-curve manner. By this curving, the waveguide deviated about 700 m from the straight path in a 1.2 cm interval. The light was coupled into the waveguide by a prism coupling technique.\n\nThe profile of the refractive index in waveguides was very important for the number of modes. Because of the Gaussian distribution of the writing laser, the written wave- guide formed a graded index profile in the lateral direction. Figure 3 shows an IR photograph of the light scattered out of the waveguide. The inset in Fig. 3 shows a picture of the waveguide between two cross polarizers observed by a mi- croscope and captured by a digital camera. The width of the waveguide was about 5 m as measured by our polarizing microscope. As shown in the inset, the graded profile of the waveguide was clearly observed.\n\nIn order to measure the waveguide loss, the setup illus- trated in Fig. 4 was used. A 5 mW laser beam with a wave- length of 830 nm was coupled into the waveguide by a prism coupler. The coupled light into the waveguide was found to\n\n\\begin{caption}\nFIG. 4. Schematic diagram for light coupling and loss measurement. The light is coupled into the waveguide by a prism coupler. Another prism is used to out couple light from the waveguide. The intensity of the laser before the coupling prism is 5 mW, about 2% of which enters the wave- guide. Low coupling efficiency in prism coupler and narrowness of the waveguide are the main causes of the low coupled light into the waveguide.\n\\end{caption}\n\n\\begin{caption}\nFIG. 5. Measured intensity of the out-coupled light vs distance for 6.5 mm length of the polymeric waveguide.\n\\end{caption}\n\nbe about 2% of the incident laser light. Another prism was used to couple light out of the waveguide which was mea- sured by a large area Si detector. An index matching fluid was used to ensure intimate contact between the prism and the waveguide. The prism was moved along the waveguide at 0.5 mm increments and intensity of out-coupled light was measured at each position.\n\nWe calculated the loss by measuring the intensity of the out-coupled light at different points along the waveguide, fitting them to the absorption exponential and applying the following formula:15\n\n\\begin{equation}\n\\begin{array} {l} {{L=\\displaystyle\\frac{-1 0} {x_{2}-x_{1}} \\, \\log\\displaystyle\\frac{I ( x_{2} )} {I ( x_{1} )}=\\displaystyle\\frac{-1 0} {x_{2}-x_{1}} \\, \\log\\displaystyle\\frac{I_{0} e^{-\\alpha x_{2}}} {I_{0} e^{-\\alpha x_{1}}}}} \\\\ {{=\\displaystyle\\frac{1 0 \\alpha} {\\ln( 1 0 )} ( {\\mathrm{d B / c m}} ) \\,,}} \\end{array}\n\\end{equation}\n\n\\begin{token}\n2\n\\end{token}\n\nwhere x1 and x2 are two arbitrary positions along the wave- guide, and is the absorption coefficient obtained by fitting the absorption exponential. Results of the measurements are shown in Fig. 5. The output signal from the detector versus distance was plotted from the beginning of the waveguide to the end. The trend of the signal versus distance illustrates a decrease in the intensity due to the loss, as seen in Fig. 5.\n\nThe waveguide path was seen by a charge coupled de- vice CCD camera, as shown in Fig. 3. The scattering cen- ters, obviously visible in Fig. 3, are major contributors to the loss. The smaller centers are most probably due to polymer aggregates, while the larger ones are due to particulates en- tered into the material during the film making. Using a wave- guide with less visible scattering centers, was found to be about 0.011 and the average loss along the waveguide was calculated to be 0.48 0.04 dB/cm by applying an exponen- tial fit to the curve of measured intensity.\n\nWe also measured the loss in the film without any waveguides slab waveguide . These measurements gave a loss of 1.24 0.13 dB/cm. The larger figure for the slab guide is due to the lack of the lateral confinement.\n\nWe have fabricated a low loss waveguide using cis- trans-active polymers by a simple “writing” technique with no surface deformation. The method used here can be re- peated easily so we can optimize the parameters of the waveguides. It can also be extended to any polymer contain- ing azo chromophores. In this experiment, we were able to fabricate graded index waveguides with index profile close to the intensity profile of the writing beam which was Gauss- ian. The propagation loss was measured to be 0.48 0.04 dB/cm in the waveguide. The waveguide loss was approximately 2.6 times less than the slab guide. This is due to the lateral confinement and the graded profile of the lateral index. Although the stability of the material is not specifically tested in this work, these materials are stable under ambient light and are not bleached at all by the guided light. Samples handled in our laboratory from several years ago still have the features “written” on them.\n\nThis work was supported in part by contributions from the Industrial Development and Renovation Organization of Iran, Small Business Development Center SBDC branch.\n\n\\begin{table}\n| 1G. T. Paloczi, Y. Huang, A. Yariv, J. Luo, and A. K.Y. Jen, Appl. Phys. Lett. 85, 10 (2004). 2R. Song, A. Yick, and W. H. Steier, Appl. Phys. Lett. 90, 191103 (2007). |\n|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| 3J.W. Kang, J.-J. Kim, and E. Kim, Appl. Phys. Lett. 80, 10 (2002). 4D. Suh, H. Ryu, Y. Park, and M. C. Paek, Appl. Phys. Lett. 87, 161111 (2005). |\n| 5D. An, Z. Shi, L. Sun, J. M. Taboada, Q. Zhou, X. Lu, R. T. Chen, S. Tang, H. Zhang, W. H. Steier, A. Ren, and L. R. Dalton, Appl. Phys. Lett. 76, 1972 (2000). |\n| 6E. Sarailou, A. Gharavi, S. Javadpour, and V. Shkunov, Appl. Phys. Lett. 89, 171114 (2006). |\n| 7A. Gharavi, H. Karimi-Alavijeh, E. Sarailou, M. Baghban, and G. Parsanasab, Proceeding of the 14th Iranian converence on Optics and Pho- |\n| tonics, 29–31 January (2008). 8P. Rochon, J. Gosselin, A. Natansohn, and S. Xie, Appl. Phys. Lett. 60, 4 c(1992)d |\n| D. Y. Kim, S. K. Tripathy, L. Li, and J. Kumar, Appl. Phys. Lett. 66, 16 (1995) 10Y. Shi, W. H. Steir, L. Yu, M. Chen, and L.R. Dalton, Appl. Phys. Lett. 58, 1131 (1991). T. E. Van Eck, A. J. Ticknor, R. S. Lytel, and G. F Lipcomb, Appl. Phys. Lett. 58, 1588 (1991). 2Z. Liu, N. Srisanit, X. Ke, P. Wu, S. Song, J.J. Yang, and M. R. Wang, Opt. Commun. 273, 94 (2007). 13H. Sadeh, A. Gharavi, D. Yu, and L. Yu, Macromolecules 30, S403 (1997). 14R. G. Hunsperger, Integrated Optics: Theory and Technology (Springer, Berlin, 1991) Vo1. 33, pp. 30–36. 15W. Shi, C. Fang, Q. Pan, Q. Gu, D. Xu, H. Hu, H. Wei, and J. Yu, Solid State Commun. 116, 67 (2000). |\n\\end{table}\n\n" + }, + { + "abbreviations": [ + { + "abbreviation": "PMDA" + }, + { + "abbreviation": "TAPB" + } + ], + "csv": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/label_data/10.2494/photopolymer.27.139.csv", + "golden_label": [ + { + "abbreviation": "PMDA", + "full_name": "pyromellitic dianhydride", + "smiles": "O=c1oc(=O)c2cc3c(=O)oc(=O)c3cc12" + }, + { + "abbreviation": "TAPB", + "full_name": "1,3,5-tris(4-aminophenyl)benzene", + "smiles": "Nc1ccc(-c2cc(-c3ccc(N)cc3)cc(-c3ccc(N)cc3)c2)cc1" + } + ], + "path": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/pdf_data/10.2494/photopolymer.27.139_uniparser.json", + "pdf": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/pdf_data/10.2494/photopolymer.27.139.pdf", + "text": "\\begin{title}\nSynthesis of TEMPO Functionalized Polyimides by A2 + B3 Polymerization\n\\end{title}\n\nYuta Nabae, Masatomo Mikuni, Teruaki Hayakawa and Masa-aki Kakimoto\n\nDepartment of Organic and Polymeric Materials, Tokyo Institute of Technology 2-12-1 S8-26, Ookayama, Meguro-ku, Tokyo 152-8552, Japan\n\nKeywords : hyperbranched polymer, nitroxyl radical, solid catalyst\n\n\\begin{title}\n1. Introduction\n\\end{title}\n\nPolyimides are typical high performance polymers with high thermal and chemical stability and have been widely used in electric, electronic and aerospace applications. In addition, polyimides with numerous functional groups, such as acidic groups [1], are attracting much attention because they will combine high thermal stability of polyimides and various functionalities. Such functional polyimides will expand the application of polyimides to a wider range of fields.\n\nAs a novel functionality introduced into polyimides, our research group is interested in nitroxyl radicals such as 2,2,6,6- tetramethylpiperidin-1-oxyl (TEMPO). TEMPO is a stable free radical and known as an oxidation catalyst for primary alcohols [2]. It is also used as a radical scavenger in various chemical reactions. TEMPO is typically used in homogeneous systems, but the immobilization of TEMPO onto solid supports such as polystyrene [3] and silica [4] has also been developed. As polyimides are more thermally stable than polystyrene and more flexible than silica, the development of TEMPO functionalized polyimides will exhibit quite promising results.\n\nTo prepare functionalized polyimides, the A2 + B3 polymerization is one of the suitable methods. It has been known that hyperbranched polymers can be synthesized by a solution polymerization, especially if the A2 monomer is added drop-wise into the B3 monomer solution [5]. Hyperbranched polymers have numerous terminals and TEMPO can be immobilized onto the terminals by an end-capping reaction. On the other hand, the A2 + B3 polymerization also provides a microporous polyimides with a three-dimensional network,\n\nespecially if the polymerization and imidization are performed by one-pot method with high boiling point solvents [6]. Moreover, if one considers polyimide-based materials as solid catalysts, the particle size of polyimides will also be an important property, which can be controlled by the precipitation polymerization method [7-10].\n\nAs mentioned above, in terms of exploring novel solid catalyst materials based on dendritic polyimides, the number of terminal functional groups, porosity, and particle size are important properties. This paper describes three types of polymerizations, 1) one-pot polymerization/ imidization in high boiling point solvents, 2) precipitation polymerization and 3) solution polymerization with a drop-wise feeding method, using the same A2 and B3 monomers, pyromellitic dianhydride (PMDA) and 1,3,5-tris(4- aminophenyl)benzene (TAPB) (Scheme 1). A slightly excess amount PMDA was used to terminate the polymer with phthalic anhydride groups, and the terminals were end-capped with 4-amino-TEMPO to obtain TEMPO functionalized polyimides. The concentration of TEMPO, porosity and morphology of the prepared polymers were characterized by electron spin resonance (ESR), N2 adsorption and scanning electron microscopy (SEM) measurements, respectively.\n\n\\begin{title}\n2. Experimental\n\\end{title}\n\n\\begin{title}\n2.1. Materials\n\\end{title}\n\nPMDA (TCI) was used after sublimation. TAPB (TCI) was used after recrystallization from ethanol. m-Cresol (TCI) and dimethylacetoamide (DMAc, Kanto Chemical) were used after vacuum distillation over calcium hydride. 4-amino-TEMPO (TCI) and all other chemicals are\n\nreagent grade and used as purchased unless otherwise stated.\n\n\\begin{molecule}\nNc1ccc(-c2cc(-c3ccc(N)cc3)cc(-c3ccc(N)cc3)c2)cc1\n\\end{molecule}\n\n\\begin{molecule}\nO=c1oc(=O)c2cc3c(=O)oc(=O)c3cc12\n\\end{molecule}\n\n\\begin{molecule}\nNC1CC(C)(C)N([O])C(C)(C)C1\n\\end{molecule}\n\n\\begin{molecule}\nNC1CC(C)(C)N([O])C(C)(C)C1\n\\end{molecule}\n\n\\begin{molecule}\nCC1(C)CC(N)CC(C)(C)N1[O]\n\\end{molecule}\n\nScheme 1. Synthesis of TEMPO functionalized polyimides.\n\n\\begin{title}\n2.2. One-pot polymerization/imidization\n\\end{title}\n\nThis polymerization/imidization was performed following an earlier work with a minor modification [6]. In a 20 mL flask, a solution of TAPB (80.8 mg, 0.23 mmol) in m-cresol (2 mL) was added to a solution of PMDA (100 mg, 0.46 mmol) in m-cresol (3 mL) and stirred under a N2 flow at 0˚C for 2 h. After adding a catalytic amount of isoquinoline at RT, the mixture was stirred at 30˚C for 8 h, 80˚C for 4 h, 160˚C for 4 h, 200˚C for 8 h and 220˚C for 4 h. The precipitated polymer was isolated by filtration and washed with DMF, acetone and THF, and then further stirred in 300 mL of THF at RT overnight. After filtration and drying at 110˚C under vacuum, an yellowish\n\n\\begin{title}\npolyimide powder (PI1) was obtained.\n\\end{title}\n\nIn a 10 mL flask, 4-amino-TEMPO (54.8 mg, 0.32 mmol) and PI1 (50 mg) were stirred in 3 mL of CHCl3 at RT for 12 h. After filtration, the thermal imidization of the terminals was performed at 220˚C under vacuum overnight to obtain a dark brownish powder, PI1-TEMPO-H. PI1-TEMPO- Ch was obtained by performing a chemical imidization instead of the thermal imidization. The powder was stirred in a mixuture of pyridine (1 mL) and acetic anhydride (1 mL) at 100 ˚ C overnight and then filtered. After washing with acetone and drying at RT under vacuum, a dark brownish powder was obtained.\n\n\\begin{title}\n2.3. Precipitation polymerization\n\\end{title}\n\nIn a 10 mL flask, a solution of TAPB (80.8 mg, 0.23 mmol) in acetone (2.6 mL) was added in one-portion to a solution of PMDA (100 mg, 0.46 mmol) in acetone (4.2 mL) at 0˚C under vigorous stirring. After stirring for 2 h, the solvent was removed with a rotary evaporator and a thermal imidization was performed at 220˚C under vacuum for 12 h. The powder was washed with 300 mL of acetone and dried at 110 ˚C under vacuum to obtain a yellowish polyimide powder, (PI2).\n\nThe end-capping reaction with 4-amino-TEMPO followed by the thermal and chemical imidization was peformed in the same manner as mentioned above to obtain PI2-TEMPO-H and PI2-TEMPO-Ch, respectively.\n\n\\begin{title}\n2.4. Solution polymerization\n\\end{title}\n\nIn a 30 mL flask, a solution of TAPB (72.8 mg, 0.21 mmol) in DMAc (7 mL) was added drop-wise over 30 min to a solution of PMDA (100 mg, 0.46 mmol) in DMAc (7 mL) at 0˚C. The mixture was further stirred at RT for 2 h. And then, 4-amino-TEMPO (158 mg, 0.92 mmol) was added and stirred at RT for 3 h. The solution was poured into ethyl acetate and the polymer was collected by filtration. After drying at RT under vacuum, a pinkish powder (PA3-TEMPO) was obtained. As a controlled sample, PA3 was also synthesized without reacting with 4-amino-TEMPO.\n\nThe thermal and chemical imidization of PA3-TEMPO was peformed in the same manner as mentioned above to obtain PI3-TEMPO-H and PI3-TEMPO-Ch, respectively. PI3 was obtained by the chemical imidization of PA3.\n\n\\begin{title}\n2.5. Characterization\n\\end{title}\n\nFT-IR spectra were obtained with a JASCO\n\n4100 spectrometer by the KBr pellet method. SEM was carried out using a VE9800 spectrometer (Keyence). The N2 adsorption was measured using a volumetric adsorption measurement instrument (Bel Japan, Belsorp-mini II). ESR measurement was carried out using a JES-FA100 spectrometer (JEOL) in a powder form. The TEMPO loading was estimated by integrating the ESR spectrum twice and comparing the intensity with relative to that of 4-hydroxy- 2,2,6,6-tetramethylpiperidine 1-oxyl benzoate (TEMPOB).\n\n\\begin{title}\n3. Results and discussion\n\\end{title}\n\n\\begin{title}\n3.1. One-pot polymerization/imidization\n\\end{title}\n\nPI1 was synthesized by the one-pot polymerization/imidization of TAPB and PMDA in m-cresol and PI1-TEMPO-H and PI1-TEMPO-Ch were prepared by the end-capping reaction for PI1 with 4-amino-TEMPO, followed by the thermal and chemical imidizations, respectively.\n\n\\begin{legend}\nFig. 1. SEM image of PI1-TEMPO-Ch.\n\\end{legend}\n\n\\begin{caption}\nFig. 2. N2 isotherms at 77 K with the PI1 based samples.\n\\end{caption}\n\nFig. 1 shows the SEM image of PI1-TEMPO-Ch. The particle size seems over 500 nm and the morphology is not uniform. Fig. 2\n\nshows the N2 isotherms with the PI1 based samples. These samples show Type I isotherms in the IUPAC classification, suggesting the presence of microspores. The BET surface areas evaluated from the N2 isotherms are summarized in Table 1. All the PI1 based samples show quite high specific surface areas, which are probably due to three dimensional networks of polyimide.\n\n\\begin{caption}\nTable 1. Specific surface area of the PI1 based samples\n\\end{caption}\n\n\\begin{table}\n| Sample | g BET surface area / m2 |\n|:-------------|:--------------------------|\n| PI1 | 659 |\n| PI1-TEMPO-H | 593 |\n| PI1-TEMPO-Ch | 658 |\n\\end{table}\n\n\\begin{caption}\nFig. 3. FT-IR spectra of the PI1 based samples.\n\\end{caption}\n\n\\begin{caption}\nFig. 4. ESR spectra of the PI1 based samples.\n\\end{caption}\n\nFig. 3 shows the FT-IR spectra of the PI1 based samples. The peaks at 1776 cm-1 (C=O stretch) and 1375 cm-1 (C-N-C stretch) suggest the formation of polyimide. If a polymer contains numerous phthalic anhydride groups, a peak due to the C=O stretch should appear at around 1860 cm-1, but none of these samples showed such peaks. To confirm the existence of nytroxyl radical, ESR\n\nmeasurements were performed and the results are summarized in Fig 4. Compared to the reference sample, TEMOB, none of these three samples showed ESR peaks due to the free radical. It is unlikely that TEMPO group was introduced onto the terminals of PI1.\n\nThese experimental results suggest that the one-pot polymerization/imidization of PMDA and TAPB provides microporous polyimides with a high specific surface area, however the obtained polyimides did not have many terminals because of an excess growth of three dimensional network.\n\n\\begin{title}\n3.2. Precipitation polymerization\n\\end{title}\n\nPI2 was synthesized by the precipitation polymerization of PMDA and TAPB. PI2- TEMPO-H and PI2-TEMPO-Ch were prepared by the end-capping reaction for PI2 with 4-amino- TEMPO, followed by the thermal and chemical imidization, respectively.\n\n\\begin{caption}\nFig. 5. SEM image of PI2-TEMPO-Ch.\n\\end{caption}\n\n\\begin{caption}\nFig. 6. N2 isotherms at 77 K with the PI2 based samples.\n\\end{caption}\n\nFig 5 shows the SEM image of PI2-TEMPO-Ch. A lot of spherical particles of around 100 nm were observed. Fig. 6 and Table 2\n\nshow the N2 isotherms and the BET surface areas of the PI2 based samples. The isotherms show very little adsorption of N2 except for the macropore region. The BET surface area was in the range of 10-26 m2 g-1.\n\n\\begin{caption}\nTable 2. Specific surface area of the PI2 based samples\n\\end{caption}\n\n\\begin{table}\n| Sample | BET surface area / m2 |\n|:-------------|:------------------------|\n| PI2 | 22 |\n| PI2-TEMPO-H | 26 |\n| PI2-TEMPO-Ch | 10 |\n\\end{table}\n\n\\begin{caption}\nFig. 7. FT-IR spectra of the PI2 based samples.\n\\end{caption}\n\n\\begin{caption}\nFig. 8. ESR spectra of the PI2 based samples.\n\\end{caption}\n\nFig. 7 shows the FT-IR spectra of the PI2 based samples. The peaks at 1776 cm-1 (C=O stretch) and 1375 cm-1 (C-N-C stretch) suggest the formation of polyimide. In addition, another peak due to C=O stretch appeared at 1860 cm-1, suggesting the presence of phthalic anhydride. Fig. 8 shows the ESR spectra of PI2 based samples. Compared to the reference sample, TEMOB, none of these three samples showed ESR peaks due to the free radical. It is unlikely that TEMPO groups was introduced onto the terminals of PI2.\n\nThese experimental results suggest that the precipitation polymerization provides fine nano-particles of polyimide containing considerable amounts of phthalic anhydride terminal groups but those terminals cannot be functionalized by an end-capping reaction probably because those terminals are hidden in the polymer matrix.\n\n\\begin{title}\n3.3. Solution polymerization\n\\end{title}\n\nPA3 was synthesized by the solution polymerization of PMDA and TAPB in DMAc with a drop-wise feeding method. PA3-TEMPO was prepared by reacting PA with 4-amino-TEMPO in the same flask for the polymerization. PI3-TEMPO-H, PI3-TEMPO-Ch and PI3 were prepared by the thermal imidaization of PA3-TEMPO, the chemical imidization of PA3-TEMPO and the chemical imidization of PA3, respectively.\n\n\\begin{caption}\nFig. 9. SEM image of PI3-TEMPO-Ch.\n\\end{caption}\n\n\\begin{caption}\nFig. 10. N2 isotherms at 77 K with the PI3 based samples.\n\\end{caption}\n\nFig. 9 shows the SEM image of PI3-TEMPO-Ch. The observed polyimide particles\n\nare quite bulky and the morphology is not uniform. Fig. 10 and Table 3 show the N2 isotherms and the BET surface areas of the PI3 based samples. The isotherms show little adsorption of N2 and the BET surface areas were evaluated as less than 1 m2 g-1. This is probably because the morphology of the polyimides are decided at the stage of the reprecipitation.\n\n\\begin{caption}\nTable 3. Specific surface area of the PI3 based samples\n\\end{caption}\n\n\\begin{table}\n| Sample | BET surface area / m2 |\n|:-------------|:------------------------|\n| PI3 | <1 |\n| PA3-TEMPO | <1 |\n| PI3-TEMPO-H | <1 |\n| PI3-TEMPO-Ch | <1 |\n\\end{table}\n\n\\begin{caption}\nFig. 11. FT-IR spectra of the PI3 based samples.\n\\end{caption}\n\n\\begin{caption}\nFig. 12. ESR spectra of the PI3 based samples.\n\\end{caption}\n\nFig. 11 shows the FT-IR spectra of the PI3 based samples. The peaks at 1776 cm-1 (C=O stretch) and 1375 cm-1 (C-N-C stretch) and the absence of amide derived peak at 1655 cm-1 (C=O stretch) suggest the formation of polyimide for PI3-TEMPO-H, PI3-TEMPO-Ch and PI3. Fig. 12 shows the ESR spectra of the PI3 based samples.\n\nPA3-TEPMO and PI3-TEMO-Ch clearly show ESR signals due to nitroxyl radical. The concentration of nitroxyl radical was evaluated as approximately 1.2 mmol g-1, based on a comparison against the reference spectrum of TEMPO-B. If one considers an ideal hyperbranched structure from the current A2 + B3 monomer and fully functionalized terminals, the theoretical value will be 1.13 mmol g-1. Therefore, the structure of PI3 is probably quite close to a hyperbranched structure rather than a network structure. In contrast, PI3-TEMPO-H did not show any clear ESR signal. This is probably because the TEMPO structure decomposed by the thermal imidization procedure.\n\nThese experimental results suggest that a TEMPO functionalized polyimide has been successfully synthesized by a solution polymerization of PMDA and TAPB with a drop-wise feeding method, followed by an in-situ end-capping reaction with 4-amino-TEMPO. Further studies will be done to perform the optimization of morphology, introduction of different functionalities and catalysis utilizing this series of functionalized polyimides.\n\n\\begin{title}\n4. Conclusion\n\\end{title}\n\nThree different polymerization methods were studied for the A2 + B3 polymerization to provide a TEMPO functionalized polyimides. The one-pot polymerization/imidization and the precipitation polymerization provided a microporous polyimide and a spherical polyimide, respectively; however, the functionalization of the terminals was difficult. In contrast, the solution polymerization with a drop-wise feeding method provided a hyperbranched polyimides and the terminals have been successfully functionalized with TEMPO by\n\nthe in-situ end-capping reaction. This polymerization and end-capping method will be applicable for the introduction of other various functionalities and might result in the development of various novel polyimide materials.\n\n\\begin{title}\nAcknowledgement\n\\end{title}\n\nM. Kakimoto was supported by Visiting Professorship for Senior International Scientists from Chinese Academy of Science.\n\n\\begin{title}\nReferences\n\\end{title}\n\n1. N. Asano, M. Aoki, S. Suzuki, K. Miyatake, H. Uchida, M. Watanabe, Journal of the American Chemical Society, 128 (2006) 1762.\n\n2. R. A. Sheldon, I. W. C. E. Arend, Adv. Synth. Catal. 346 (2004) 1051.\n\n3. S. Weik, G. Nicholson, G. Jung, J. Rademann, Angew. Chem., Int. Ed., 40 (2001) 1436.\n\n4. T. Fey, H. Fischer, S. Bachmann, K. Albert, C. Bolm, J. Org. Chem., 66 (2001) 8154.\n\n5. J. J. Hao, M. Jikei, M. Kakimoto, Macromolecules, 36 (2003) 3519.\n\n6. G. Li, Z. Wang, Macromolecules, 46 (2013) 3058.\n\n7. K. Asao, Y. Yoshioka, S. Watano, Kagaku Kogaku Ronbunshu, 38 (2012) 39.\n\n8. T. Sawai, T. Uchida, S. Yamazaki, K. Kimura, J. Photopolym. Sci. Technol., 26 (2013) 341.\n\n9. T. Sawai, K. Wakabayashi, S. Yamazaki, T. Uchida, Y. Sakaguchi, R. Yamane, K. Kimura, Eur. Polym. J., 49 (2013) 2334.\n\n10. M. Chokai, Y. Nabae, S. Kuroki, T. Hayakawa, M. Kakimoto, S. Miyata, J. Photopolym. Sci. Technol., 24 (2011) 241.\n\n" + }, + { + "abbreviations": [ + { + "abbreviation": "ODPA" + }, + { + "abbreviation": "ODA" + }, + { + "abbreviation": "134APB" + }, + { + "abbreviation": "144APB" + } + ], + "csv": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/label_data/10.1002/mame.201800709.csv", + "golden_label": [ + { + "abbreviation": "ODPA", + "full_name": "4,4′-oxydiphthalic anhydride", + "smiles": "O=C1OC(=O)c2cc(Oc3ccc4c(c3)C(=O)OC4=O)ccc21" + }, + { + "abbreviation": "ODA", + "full_name": "4,4′-Diaminodiphenyl ether", + "smiles": "Nc1ccc(Oc2ccc(N)cc2)cc1" + }, + { + "abbreviation": "134APB", + "full_name": "1,3-bis(4-aminophenoxy) benzene", + "smiles": "Nc1ccc(Oc2cccc(Oc3ccc(N)cc3)c2)cc1" + }, + { + "abbreviation": "144APB", + "full_name": "1,4-bis(4-aminophenoxy) benzene", + "smiles": "Nc1ccc(Oc2ccc(Oc3ccc(N)cc3)cc2)cc1" + } + ], + "path": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/pdf_data/10.1002/mame.201800709_uniparser.json", + "pdf": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/pdf_data/10.1002/mame.201800709.pdf", + "text": "\\begin{title}\nSulfonyl-Containing Polyimide Dielectrics with Advanced Heat Resistance and Dielectric Properties for High-Temperature Capacitor Applications\n\\end{title}\n\nJing Fu, Aftab Ahmad, Tao Fan, Yudong Hou,* and\n\nPolymer dielectrics, with advanced dielectric properties and heat resistance, are critical for high-temperature capacitors in various applications. How- ever, the high performance of heat resistance and dielectric properties are quite difficult to achieve all together due to their mutual implication. Here, by intensively investigating the correlation between molecular structure and properties, polyimide dielectrics with i) enhanced dielectric constant by introducing sulfonyl group, ii) low dissipation factor by introducing flex- ible linkage, and iii) high Tg (glass transition temperature) by retaining an aromatic structure, are obtained. The sulfonyl-containing polyimides with different flexible linkages exhibit simultaneously a high dielectric constant (4.50–5.98), low dissipation factor (0.00298–0.00426), and outstanding break- down strength (most above 500 MV m−1), as well as superior heat resistance (Tg: 244–304 °C). Specifically, the polyimide (SPI-1) with sulfonyl group in diamine moiety and para-para linkage shows stable dielectric properties up to 150 °C, and the discharged energy density and charge–discharge efficiency can be as high as 7.04 J cm−3 and 91.3% at 500 MV m−1, respectively.\n\nHeat resistant polymer dielectrics are urgently required for high-temperature film capacitors in the applications of avionic and automotive industries, underground oil and gas explora- tion, and advanced propulsion systems.[1,2] Compared to ceramic dielectrics, polymer dielectrics exhibit low dissipation factor, high dielectric strength, excellent mechanical flexibility, and easy manufacture behavior.[3–6] The state-of-the-art polymer dielec- tric is biaxially oriented polypropylene (BOPP), which displays superior high breakdown strength (700 MV m−1), very low dis- sipation factor (0.0002) but relatively low dielectric constant\n\nDr. H. Tong, A. Ahmad, Prof. T. Fan, Prof. J. Xu Institute of Electric and Engineering Chinese Academy of Sciences Beijing 100190, China E-mail: xuju@mail.iee.ac.cn A. Ahmad, Prof. J. Xu College of Engineering Science University of Chinese Academy of Sciences Beijing 100049, China J. Fu, Prof. Y. Hou College of Materials Science and Engineering Beijing University of Technology Beijing 100124, China E-mail: ydhou@bjut.edu.cn\n\n\\begin{title}\nDOI: 10.1002/mame.201800709\n\\end{title}\n\ntended to enhance the dielectric properties as illustrated in pol- yurea and polyurethane,[19–21] polythoiurea,[22,23] polyimide,[24] etc. In addition, sulfonyl group was also proved to increase dielectric constant and energy density effectively in dipolar glass polymers such as poly(ethylene oxide) and poly(phenylene oxide).[25,26] The polar groups in those polymers functioned as permanent dipoles would display large dipole moment, which is beneficial to enhancing dielectric constant. Among them, polyimides are a class of polymers that contain polar CONCO rings in molecular structures, with the nature of advanced heat resistance, superior mechanical properties, reasonably low dissipation factor, and high dielectric break- down strength.[27–29] However, the dielectric constant of poly- imide is not high enough for high energy density film capacitor applications.[30,31] Introduction of polar groups into molecular structure can improve this parameter, but it would also likely deteriorate the other properties. For example, dielectric con- stant was enhanced from 2.9 to 4.9 (at 190 °C and 1 kHz) when highly polar nitrile dipoles were attached to the main chains, and to 5.5–7.2 when bipyridine units were brought into back- bone of polyimides, while their dissipation factor was increased to a high level of 0.04–0.08 due to the difficulty of frictionless dipole switching.[32–35] Dielectric constant of 7.8 and maximum energy density of 15 J cm−3 was achieved from polyimides pre- pared from aromatic dianhydrides and aliphatic diamines with polar groups of O, C(O) in molecular structures, while\n\n(2.2) and limited operating temperature (105 °C).[7–12] Therefore, developing high- temperature resistant polymeric dielectrics with high dielectric constant, low dissipa- tion factor, and high breakdown strength is essential for next generation film capacitors in harsh environmental applications.[13]\n\nSo far, most studies about dielectric polymers aiming to the applications of film capacitors are focused on composites by introducing fillers into polymer matrix to improve the dielectric constant.[14–17] However, the limitation is obvious due to the complex synthesis, still low breakdown field, and high dissipation factor. Recently, some efforts have been directed to the molecular design of dielectric polymer to optimize its properties. For instance, in the article by Ramprasad et al.,[18] it was pointed out both computationally and experimentally that polymers with polar units, for example, NH, CO, O,\n\nthe heat resistance was sacrificed (Tg = 53–174 °C) owing to the aliphatic moieties.[24] Therefore, high temperature resistance polymer with high breakdown strength, high dielectric con- stant, and low dissipation factor are quite difficult to achieve simultaneously.\n\nIn this work, strong polar sulfonyl group with high dipole moment (4.30 D) and different flexible linkages between ben- zene groups in various configurations were introduced into polyimide chains to achieve enhanced dipole density plus more “effective” dipoles, and closely reach to frictionless dipole reori- entation, thereby high dielectric constant and low dissipation factor were realized simultaneously without sacrificing heat resistance. The correlation between molecular structure and dielectric properties was explained in detail. It is worth noting that the methodology for molecular tailoring and the corre- lating mechanism of molecular structure and dielectric proper- ties is also applicable to the design of other polymer dielectrics.\n\nA series of sulfonyl-containing polyimide (SPI) films were prepared, and their chemical structures were identified by FT-IR (see Figure S1, Supporting Information). These SPIs dis- played outstanding thermal stability based on the TGA results which revealed the polyimides can be stable up to 500 °C without obvious weight loss (Table 1). Also excellent heat resist- ance was obtained according to their superior high glass tran- sition temperature (Tg) ranging from 244 to 304 °C (Table 1). By carefully analyzing the Tg results, it was found the Tg values are closely related to polymeric rigidity. For instance, SPI-1 and SPI-2 are positional isomers with the para–para and meta–meta linkage in diamine moiety, respectively. SPI-1 with more rigid para–para linkage showed higher Tg value than its isomers with meta–meta structure, SPI-2. Similar results were observed for SPI-4 and SPI-5. In another example, SPI-1 and SPI-3 are posi- tional isomers in which sulfonyl and ether groups exchange positions in their repeating-unit structures, higher Tg value was observed from SPI-3 which has higher chain stiffness due to the fact that sulfonyl group in the bulky dianhydride moiety increased the difficulty of segmental rotation.\n\nDielectric properties of SPIs were evaluated in terms of die- lectric constant (relative dielectric constant here, εr), dissipation factor (tan δ) at different frequencies and temperatures, and Weibull breakdown strength (Eb) at room and elevated tempera- tures. In addition, the high electrical field dielectric property\n\n\\begin{caption}\nTable 1.  Heat resistance and dielectric properties of sulfonyl-containing polyimides.\n\\end{caption}\n\n\\begin{table}\n| PIs | Cd) | T 1 | ε, | tan 8) | Ed) [MV m−] | Ue,max [ cm-³3} |\n|:------|:------|:------|:-----|:---------|:--------------|:------------------|\n| SP1-1 | 290 | 541 | 5.98 | 0.00373 | 536 | 7.60 |\n| SP1-2 | 244 | 513 | 5.48 | 0.00392 | 548 | 7.28 |\n| SP1-3 | 304 | 578 | 5.08 | 0.00397 | 533 | 6.39 |\n| SP1-4 | 250 | 569 | 4.60 | 0.00378 | 419 | 3.58 |\n| SP1-5 | 271 | 513 | 4.66 | 0.00298 | 361 | 2.69 |\n| SPI-6 | 302 | 570 | 4.50 | 0.00426 | 569 | 6.45 |\n| SP1-7 | 278 | 586 | 5.33 | 0.00371 | 501 | 5.92 |\n\\end{table}\n\na)Determined by dynamic mechanical analysis (DMA); b)onset decomposition tem- perature; c)at 103 Hz and room temperature; d)at room temperature.\n\nwas obtained by electric displacement–electric field (D-E) characterization.\n\nIn Table 1, with the presence of sulfonyl group in each repeating unit, the dielectric constants of different SPIs at room temperature ranged from 4.50 to 5.98 which are much higher than BOPP (2.2) and conventional polyimide (i.e., Kapton, about 3.5).[8] As it is known that for amorphous polar macromolecules, dipolar polarization (consisting of dipole moment and volumetric dipole density) is the major contrib- utor for dielectric constant. Thus, for SPIs, the polar sulfonyl group (SO2) with a quite high dipole moment of 4.30 D in the backbones combined with considerable dipole density (one SO2 group (SPI-1 to SPI-6) or two SO2 groups (SPI-7) in each repeating unit) in the polyimide dielectrics are responsible for the high dielectric constant. Besides that, the SO2 con- taining structure that is linked with phenyl groups in diamine (SPI-1, SPI-2) moieties is proposed to having greater mobility, that is, more “effective” dipoles as compared to that connected to bulkier benzene-imide rings in dianhydride (SPI-3 to SPI- 7), resulting in SPI-1 and SPI-2 with larger dielectric constant values. Furthermore, the para–para linked SPI-1 proved higher dielectric constant than the meta–meta counterpart (SPI-2) due to the fact that SPI-1 has more symmetrical structure and lower energy barrier in free rotation which would aid the alignment of dipoles in alternating electric field. In addition, SPI-3 exhib- ited higher dielectric constant due to the shorter repeating unit with higher SO2 density compared with SPI-4 and SPI-5 which have similar molecular structures. The lowest εr value was observed in SPI-6 with the weakest polar group of meth- ylene in diamine moiety. While for SPI-7, which has the highest dipole density (two SO2 groups in each repeating unit), the dielectric constant was not as high as expected. This is prob- ably because the two relatively rigid SO2 groups instead of O and SO2 groups in the main chain enhanced the overall chain stiffness, resulting in the hindrance of dipole rota- tion. Thus, besides dipole moment and dipole density, “effec- tive” dipole is another important factor to affect the value of the dielectric constant.\n\nIn other dielectric properties of dissipation factor, all the SPIs showed basically similar and low tan δ value of no more than 0.00426 at room temperature and 103 Hz (Table 1). Based on the XRD pattern (see Figure S2, Supporting Information), the amorphous nature indicated the effective reduction of the long-range dipolar coupling among strong polar structures (e.g., the SO2 moieties and characteristic imide group), so as to decrease tan δ value.[19] Also, low dissipation factors were achieved as the temperature is much lower than the glass tran- sition temperature and the main chains are frozen (only small unit can rotate). In addition, it is worth to note SPI-5 exhibited the lowest tan δ due to its larger proportion of flexible ether structure (O) and symmetrical para–para linkage.\n\nIn Figure 1a, as the frequency (f) increases, dielectric con- stants of SPIs decreased slightly because the dipoles cannot catch up with the oscillation of alternating electric field. All the SPIs achieved their relaxation peaks at the frequency around 105–106 Hz. Several conclusions could be drawn from the results of tan δ versus f spectra. i) In the full frequency range, SPI-1 with more symmetric structure that facilitates dipole ori- entation displayed lower tan δ value than its isomer of SPI-2.\n\n\\begin{legend}\n(a)\n\\end{legend}\n\n\\begin{legend}\n(b)\n\\end{legend}\n\n\\begin{caption}\nFigure 1.  a) Dielectric constant and dissipation factor of SPI-1 to SPI-7 at R.T.; b) dielectric constant and dissipation factor of SPI-1 at elevated temperature.\n\\end{caption}\n\nii) It is obvious that SPI-5 and SPI-7 showed very close dissipa- tion factors when their frequency was lower than 103 Hz. As the frequency rose above 103 Hz, SPI-5, with a more flexible ether linkage and symmetric structure, still kept a relatively low tan δ value. While for SPI-7 having meta–meta linked Ph2SO2 (mDS) with more restricted segmental mobility, the more restricted dipoles lagged behind the alternating electric field, resulting in higher dissipation factor. iii) The other SPIs showed similar dissipation performance due to the analogous restriction of dipole switching.\n\nTo evaluate dielectric property dependence on temperatures, SPI-1 with the best performance was chosen to do tempera- ture-scan broadband dielectric spectrometer (BDS) at different frequencies as shown in Figure 1b. At a given temperature,\n\nstant and second highest breakdown strength demonstrate to give the greatest maximum energy storage density.\n\nA bipolar D-E analysis was carried out to investigate the dielectric properties of SPI-1 under high electric field (R.T., 1 Hz). The extremely narrow D-E loop (Figure 2a) further con- firmed its low dissipation factor. As electric field increases, the D-E loop becomes slightly wider. More dipoles would take part in orientation at higher electric field therefore larger restric- tion and dielectric dissipation occurred. The apparent dielec- tric constant under high field calculated from the D-E loop within ±100 MV m−1 (εr = D/(ε0E)) can achieve up to 6.49, which is higher than the result form BDS measurement at low electric field (εr = 5.98). This is because higher electric field can help polarize excess dipoles which is difficult to occur in\n\ndielectric constant progressively declined with frequency increased from 10 to 106 Hz. Under different frequencies, the dielectric constants of SPI-1 are almost constant at temperature range above 100 °C and stable up to 150 °C. This is much different compared to BOPP whose max- imum operating temperature is no more than 105 °C. There is a weak broad peak at tempera- ture range around 50 °C which may be originated from adsorbed water as pointed out in some research.[36] Similar high temperature stability tendency was found for the dissipation factor at the temperature range from 100 to 150 °C. But at lower temperature range (i.e., −50 to 100 °C), the sub-Tg transitions shifted to higher temperature as frequency increased because more energy was needed for dipoles rotating under the applied electric field with higher frequency.\n\nAt room temperature, breakdown strength of all SPIs ranged from 361 MV m−1 to 569 MV m−1 (Table 1 and Figure S3a, Sup- porting Information). Among them, SPI-1 and SPI-3 indicated very close Eb value on account of their isomeric structures that have the sulfonyl and ether groups in the exchanging places of diamine and dianhydride segments. SPI-4 and SPI-5 exhibited lower Eb due to the longer π–π conjugating from long-chain phenyl structure facilitating the smooth electronic conductance path. Take the SPI-1 as example, its Weibull breakdown strength showed great thermal sta- bility with slight decline from 536 to 468 MV m−1 at the temperature range from room tempera- ture to 150 °C (Figure S3b, Supporting Informa- tion). The energy density can be calculated from the simplified equation\n\n\\begin{title}\nU 0.5 E e r 0 b 2 ε ε =\n\\end{title}\n\nfor the linear dielectrics, where Ue is the energy density, εr is relative dielectric constant, ε0 is the constant of 8.854 × 10−12 F m−1, and Eb is the breakdown strength.[37,38] The maximum Ue of different SPIs is listed in Table 1, from 2.69 to 7.60 J cm−3. SPI-1 with the largest dielectric con-\n\n\\begin{token}\n(1)\n\\end{token}\n\n\\begin{legend}\n(a)\n\\end{legend}\n\n\\begin{legend}\n(b)\n\\end{legend}\n\n\\begin{caption}\nFigure 2.  a) D-E loop and (b) discharged energy density and charge–discharge efficiency of SPI-1.\n\\end{caption}\n\n\\begin{caption}\nTable 2.  Performance comparison between SPI-1 and some typical linear polymer dielectrics.\n\\end{caption}\n\n\\begin{table}\n| Polymers | $Tr}$ [C] | εr | tanδ | Eb [MV m-1] | Ue.may cm-3} | Charge-discharge eficiency [%] | Ref |\n|:------------------------|:------------|:-----|:--------|:--------------|:---------------|:---------------------------------|:-----------|\n| Polyimide (SP1-1) | 290 | 5.98 | 0.00373 | 536 | 7.60 | 91.3 | this paper |\n| Polythiourea (PDTC-HDA) | - | 3.67 | 0.0267 | 685 | 9.3 | ≈70 | [18,22]2 |\n| Polyurea (5A) | - | 6.19 | 0.0429 | - | | | [18,21] |\n| Polyurethane (5B) | 91 | 10.5 | 0.0188 | - | - | | [18,21] |\n| Polyimide (BTDA-HK511) | 78 | 7.8 | 0.00555 | 676 | 15.77 | | [18,24] |\n\\end{table}\n\nBDS measurement. As shown in Figure 2b, the discharged density (extracted from Figure 2a) can be as high as 7.04 J cm−3, which is about 2.3 times of BOPP film (i.e., 3.0 J cm−3 at 550 MV m−1). This is similar with the calculated result from Equation (1). The charge–discharge efficiency can reach up to 91.3% even at 500 MV m−1 owing to its low dissipation factor. A better overall performance is obtained compared to some typical linear polymer dielectrics as sum- marized in Table 2. For example, SPI-1 exhibited higher energy efficiency than the polythiourea (e.g., PDTC-HDA, about 0.7 at 700 MV m−1), lower dissipation factor than the polyureas and polyurethanes (0.00758– 0.0429), better heat resistance than the semi- aromatic polyimide (e.g., BTDA-HK511, Tg = 78 °C).[18,21,22,24]\n\nA series of sulfonyl-containing aromatic polyimides exhibiting high heat resistance and remarkable dielectric properties simul- taneously were prepared and investigated. The glass transition temperature of the SPIs ranged from 244–304 °C, and the decomposi- tion temperature was above 500 °C. Particu- larly, the SPIs presented dielectric constant of 4.50–5.98, dissipation factor of 0.00298– 0.00426, Weibull breakdown strength of 361– 569 MV m−1, and the calculated maximum energy density of 2.69–7.60 J cm−3. It proved that high dipole moment polar sulfonyl structure together with high dipole density, moderate flexible structure, and the retained aromatic structure in polyimides are respon- sible for the excellent heat resistance and dielectric properties. In addition, for the poly- imide (SPI-1) with sulfonyl group in diamine moiety with para–para linkage, its dielectric properties was stable up to 150 °C, the dis- charged energy density and charge–discharge efficiency can be as high as 7.04 J cm−3 and 91.3% at 500 MV m−1, respectively. There- fore, the sulfonyl-containing polyimide dielectrics are promising candidate for next generation film capacitors in harsh environ- mental applications.\n\n\\begin{title}\nExperimental Section\n\\end{title}\n\nMaterials: 3,3′,4,4′-Diphenylsulfonyl tetracarboxylic dianhydride (DSDA), 4,4′-oxydiphthalic anhydride (ODPA), 4,4′-diaminodiphenyl sulfonyl (pDS), 3,3′-diaminodiphenyl sulfonyl (mDS) were purchased from TCI Tokyo Chemical Industry Co., Ltd and used as received. 4,4′-Diaminodiphenyl ether (ODA), 1,3-bis(4-aminophenoxy) benzene (134APB), 1,4-bis(4- aminophenoxy) benzene (144APB), and 4,4′-diamino diphenylmethane (MDA) were purchased from Aladdin reagent corporation. N,N-dimethylacetamide\n\n\\begin{molecule}\n*NC(C1C(C(O)=O)=CC=C(*C2C=C(C(O)=O)C(C(N**)=O)=CC=2)C=1)=O0:11:R[1]21:R[2]22:\n\\end{molecule}\n\n\\begin{molecule}\nO=C1C2C(=CC(=CC=2)*C2C=C3C(OC(=O)C3=CC=2)=O)C(=O)O18:R[1]\n\\end{molecule}\n\n\\begin{legend}\nR1:\n\\end{legend}\n\n\\begin{caption}\nScheme 1.  Synthesis of sulfonyl-containing polyimides.\n\\end{caption}\n\n(DMAc) was purified by distillation under reduced pressure and dehydrated with 4 Å molecular sieves prior to use.\n\nPreparation of Sulfonyl-Containing Polyimides and Corresponding Films: Seven polyimides containing sulfonyl moieties were synthesized via a conventional two-step thermal imidization method (Scheme 1). In a typical experiment, SPI-1, which derived from ODPA and pDS, was prepared from the following procedure. pDS (2.4830 g, 0.01 mol) and ODPA (3.1021 g, 0.01 mol) were added to 22.3 g solvent of DMAc under inert atmosphere and the mixture was reacted for 12 h at ambient temperature. The polyamic acid (PAA) solution was obtained afterward. Then the PAA solution was casted into wet film with the blade gap of 200 µm. Imidization occurred while thermally baking in an oven at 100 °C for 2 h, 150 °C for 1 h, 250 °C for 1 h, and 350 °C for 0.5 h. The free-standing polyimide films with the thickness of 10–20 µm was obtained by immersing the glass plate in water followed by drying in an oven in vacuum at 100 °C overnight.\n\nInstrumentation: Thermogravimetric analysis (TGA) was performed with TA instruments TGA Q500 at a heating rate of 10 °C min−1 under O2 atmosphere. Dynamic mechanical analysis (DMA) was performed with TA instruments DMA Q800 at heating rate of 10 °C min−1. Dielectric constant and dissipation factor were investigated by a Novocontrol broadband dielectric spectrometer (BDS, Germany). Silver electrodes of 20 mm diameter and 60 nm thickness were evaporated on both sides of the sample through a physical vapor deposition method. For frequency scans, samples were held at constant temperature and a sine voltage of 1.0 Vrms was applied across the samples with frequency ranging from 10 to 106 Hz. For temperature scans, temperature was programmed to change from −50 to 150 °C at a ramping rate of 5 °C min−1. Temperature spectrometer at 10, 102, 103, 104, 105, and 106 Hz were recorded. Dielectric breakdown strength measurements were performed on a breakdown instrument (CS9920B, China) using the electrostatic pull-down method under a direct-current voltage ramp of 500 V s−1. High-field electric displacement-electric field (D-E) loop was collected using a modified Sawyer-Tower circuit, where the samples were subject to a triangular bipolar wave with a frequency of 10 Hz.\n\n\\begin{title}\nSupporting Information\n\\end{title}\n\nSupporting Information is available from the Wiley Online Library or from the author.\n\n\\begin{legend}\nODPA\n\\end{legend}\n\n\\begin{legend}\nDSDA\n\\end{legend}\n\n\\begin{legend}\nSPI-1:ODPA-pDS\n\\end{legend}\n\n\\begin{legend}\nSPI-5:DSDA-144APB\n\\end{legend}\n\n\\begin{molecule}\nCS(C)(=O)=O\n\\end{molecule}\n\n\\begin{legend}\nR2\n\\end{legend}\n\n\\begin{legend}\nSPI-2: ODPA-mDS\n\\end{legend}\n\n\\begin{legend}\nSPI-6: DSDA-MDA\n\\end{legend}\n\n\\begin{legend}\nmDS\n\\end{legend}\n\n\\begin{legend}\nODA\n\\end{legend}\n\n\\begin{molecule}\nCc1ccc(S(=O)(=O)c2ccc(C)cc2)cc1\n\\end{molecule}\n\n\\begin{molecule}\nCc1cccc(S(=O)(=O)c2cccc(C)c2)c1\n\\end{molecule}\n\n\\begin{molecule}\nCc1ccc(Oc2ccc(C)cc2)cc1\n\\end{molecule}\n\n\\begin{legend}\nSPI-3: DSDA-ODA\n\\end{legend}\n\n\\begin{legend}\nSPI-7:DSDA-mDS\n\\end{legend}\n\n\\begin{title}\nAcknowledgements\n\\end{title}\n\nThis research was supported by the National Key Research and Development Program of China (Grants No.: 2016YFB0100600).\n\n\\begin{title}\nConflict of Interest\n\\end{title}\n\nThe authors declare no conflict of interest.\n\n\\begin{title}\nKeywords\n\\end{title}\n\ndielectric properties, heat resistance, sulfonyl-containing polyimides\n\nReceived: November 19, 2018 Revised: January 14, 2019 Published online:\n\n[1] Q. Li, F.-Z. Yao, Y. Liu, G. Zhang, H. Wang, Q. Wang, Annu. Rev. Mater. Res. 2018, 48, 219.\n\n[2] Q. Li, L. Chen, M. R. Gadinski, S. Zhang, G. Zhang, U. Li, E. Iagodkine, A. Haque, L. Q. Chen, N. Jackson, Q. Wang, Nature 2015, 523, 576.\n\n[3] L. Zhu, Q. Wang, Macromolecules 2012, 45, 2937.\n\n[4] D. Tan, L. Zhang, Q. Chen, P. Irwin, J. Electron. Mater. 2014, 43, 4569.\n\n[5] E. Baer, L. Zhu, Macromolecules 2017, 50, 2239.\n\n[6] A. F. Baldwin, R. Ma, T. D. Huan, Y. Cao, R. Ramprasad, G. A. Sotzing, Macromol. Rapid Commun. 2014, 35, 2082.\n\n[7] Z. Yao, Z. Song, H. Hao, Z. Yu, M. Cao, S. Zhang, M. T. Lanagan, H. Liu, Adv. Mater. 2017, 29, 1601727.\n\n[8] Prateek, V. K. Thakur, R. K. Gupta, Chem. Rev. 2016, 116, 4260.\n\n[9] L. Zhu, J. Phys. Chem. Lett. 2014, 5, 3677.\n\n[10] M. Zhang, L. Zhang, M. Zhu, Y. Wang, N. Li, Z. Zhang, Q. Chen, L. An, Y. Lin, C. Nan, J. Mater. Chem. A 2016, 4, 4797.\n\n[11] M. Rabuffi, G. Picci, IEEE Trans. Plasma Sci. 2002, 30, 1939.\n\n[12] G. Zhang, H. Li, M. Antensteiner, T. C. M. Chung, Macromolecules 2015, 48, 2925.\n\n\\begin{legend}\n134APB\n\\end{legend}\n\n\\begin{legend}\n144APB\n\\end{legend}\n\n\\begin{legend}\nMDA\n\\end{legend}\n\n\\begin{molecule}\nCc1ccc(Oc2cccc(Oc3ccc(C)cc3)c2)cc1\n\\end{molecule}\n\n\\begin{molecule}\nCc1ccc(Oc2ccc(Oc3ccc(C)cc3)cc2)cc1\n\\end{molecule}\n\n\\begin{molecule}\nCc1ccc(Cc2ccc(C)cc2)cc1\n\\end{molecule}\n\n\\begin{legend}\nSPI-4:DSDA-134APB\n\\end{legend}\n\n\\begin{molecule}\n*N1C(=O)C2C(=CC=C(C=2)*C2C=C3C(N(C(=O)C3=CC=2)**)=O)C1=O0:10:R[1]21:R[2]22:\n\\end{molecule}\n\n[13] J. S. Ho, S. G. Greenbaum, ACS Appl. Mater. Interfaces 2018, 10, 29189.\n\n[14] W. Xu, G. Yang, L. Jin, J. Liu, Y. Zhang, Z. Zhang, Z. Jiang, ACS Appl. Mater. Interfaces 2018, 10, 11233.\n\n[15] X. Liao, W. Ye, L. Chen, S. Jiang, G. Wang, L. Zhang, H. Hou, Compos. Part A 2017, 101, 50.\n\n[16] W. Xu, Y. Ding, S. Jiang, W. Ye, X. Liao, H. Hou, Polym. Compos. 2016, 37, 794.\n\n[17] W. Xu, Y. Feng, Y. Ding, S. Jiang, H. Fang, H. Hou, Mater. Lett. 2015, 161, 431.\n\n[18] A. Mannodi-Kanakkithodi, G. M. Treich, T. D. Huan, R. Ma, M. Tefferi, Y. Cao, G. A. Sotzing, R. Ramprasad, Adv. Mater. 2016, 28, 6277.\n\n[19] Y. Thakur, M. Lin, S. Wu, Q. M. Zhang, J. Electron. Mater. 2016, 45, 4721.\n\n[20] S. Wu, M. Lin, Q. Burlingame, Q. M. Zhang, Appl. Phys. Lett. 2014, 104, 072903.\n\n[21] R. G. Lorenzini, W. M. Kline, C. C. Wang, R. Ramprasad, G. A. Sotzing, Polymer 2013, 54, 3529.\n\n[22] R. Ma, V. Sharma, A. F. Baldwin, M. Tefferi, I. Offenbach, M. Cakmak, R. Weiss, Y. Cao, R. Ramprasad, G. A. Sotzing, J. Mater. Chem. A 2015, 3, 14845.\n\n[23] S. Wu, W. Li, M. Lin, Q. Burlingame, Q. Chen, A. Payzant, K. Xiao, Q. M. Zhang, Adv. Mater. 2013, 25, 1734.\n\n[24] R. Ma, A. F. Baldwin, C. C. Wang, I. Offenbach, M. Cakmak, R. Ramprasad, G. A. Sotzing, ACS Appl. Mater. Interfaces 2014, 6, 10445.\n\nwww.mme-journal.de\n\n[25] Y.-F. Zhu, Z. Zhang, M. H. Litt, L. Zhu, Macromolecules 2018, 51, 6257.\n\n[26] Z. Zhang, D. H. Wang, M. H. Litt, L. S. Tan, L. Zhu, Angew. Chem., Int. Ed. 2018, 57, 1528.\n\n[27] M. Niwa, H. Kawakami, T. Kanamori, T. Shinbo, A. Kaito, S. Nagaoka, Macromolecules 2001, 34, 9039.\n\n[28] A. M. Kratochvil, W. J. Koros, Macromolecules 2010, 43, 4679.\n\n[29] H. Tong, C. Hu, S. Yang, Y. Ma, H. Guo, L. Fan, Polymer 2015, 69, 138.\n\n[30] C. M. Leu, Y. T. Chang, K. H. Wei, Macromolecules 2003, 36, 9122.\n\n[31] N. Song, K. Shi, H. Yu, H. Yao, T. Ma, S. Zhu, Y. Zhang, S. Guan, Eur. Polym. J. 2018, 101, 105.\n\n[32] I. Treufeld, D. H. Wang, B. A. Kurish, L.-S. Tan, L. Zhu, J. Mater. Chem. A 2014, 2, 20683.\n\n[33] D. H. Wang, B. A. Kurish, I. Treufeld, L. Zhu, L.-S. Tan, J. Polym. Sci., Part A: Polym. Chem. 2015, 53, 422.\n\n[34] X. Peng, W. Xu, L. Chen, Y. Ding, T. Xiong, S. Chen, H. Hou, React. Funct. Polym. 2016, 106, 93.\n\n[35] X. Peng, Q. Wu, S. Jiang, M. Hanif, S. Chen, H. Hou, J. Appl. Polym. Sci. 2014, 131, 40828.\n\n[36] S. Chisca, V. E. Musteata, I. Sava, M. Bruma, Eur. Polym. J. 2011, 47, 1186.\n\n[37] S. Wu, Q. Burlingame, Z.-X. Cheng, M. Lin, Q. M. Zhang, J. Elec- tron. Mater. 2014, 43, 4548.\n\n[38] X. Yuan, Y. Matsuyama, T. C. M. Chung, Macromolecules 2010, 43, 4011.\n\n" + }, + { + "abbreviations": [ + { + "abbreviation": "ODA" + }, + { + "abbreviation": "6FDA" + }, + { + "abbreviation": "PMDA" + } + ], + "csv": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/label_data/10.1021/bk-1994-0537.ch026.csv", + "golden_label": [ + { + "abbreviation": "ODA", + "full_name": "4,4'-Oxydianiline", + "smiles": "Nc1ccc(Oc2ccc(N)cc2)cc1" + }, + { + "abbreviation": "6FDA", + "full_name": "4,4'-(hexafluoroisopropylidene)diphthalic anhydride", + "smiles": "O=C1OC(=O)c2cc(C(c3ccc4c(c3)C(=O)OC4=O)(C(F)(F)F)C(F)(F)F)ccc21" + }, + { + "abbreviation": "PMDA", + "full_name": "Pyromellitic dianhydride", + "smiles": "O=c1oc(=O)c2cc3c(=O)oc(=O)c3cc12" + } + ], + "path": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/pdf_data/10.1021/bk-1994-0537.ch026_uniparser.json", + "pdf": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/pdf_data/10.1021/bk-1994-0537.ch026.pdf", + "text": "\\begin{title}\nChapter 26\n\\end{title}\n\n\\begin{title}\nRecent Progress of the Application of Polyimides to Microelectronics\n\\end{title}\n\n\\begin{title}\nDaisuke Makino\n\\end{title}\n\n\\begin{title}\nYamazaki Works, Hitachi Chemical Company, Ltd., Hitachi, Ibaraki 317, Japan\n\\end{title}\n\nHighly purified and high heat resistant PI for microelectronics was first devel­ oped in the early 1970s (1). Purpose of the development was the application to the interlayer dielectric of dual metal semiconductor device. By coating liquid PI precursor on a stepped first Al wiring layer, flat PI insulating layer is obtained and step-free second Al layer can be formed as shown in Fig. 1. As a result, reliability of the electrode, especially the second level electrode, is remarkably improved.\n\nResult of high temperature and high humidity life test of the PI intercon­ nect ICs is shown in Fig. 2 (2). Time to reach to 1% cummulative failure is about 10 years under 65 °C-95%RH condition. This life is comparable with the PSG (phosphorous doped silica glass) passivated single layer device.\n\nIn this way high reliability of PI interconnect ICs was confirmed in the market, and application of PI to microelectronics rapidly expanded. Fig. 3 summarizes the application of PIs to microelectronics in chronological order (3). They include α-ray shield of memory device, interlayer insulation of thin film facsimile thermal head, thin film magnetic head and so forth. Out of these applications, this paper introduces the recent progress of the application to LSI, Liquid Crystal Display, Multi Chip Module and Optical Wave Guide.\n\n\\begin{title}\nPI BUFFER COAT\n\\end{title}\n\nMounting method of semiconductor package to printed wiring board is shifting from pin inserting to surface mounting. In a surface mount, soldering is carried out by dipping the package in a molten solder or exposing to high temperature gas, vapor phase soldering. During this process mold stress generates in a package because of the difference of thermal expansion of mold resin and semiconductor chip. This mold stress gives fatal damage to the package such as passivation crack, Al electrode slide and package crack. Accordingly, it is a very\n\n\\begin{title}\n0097-6156/94/0537-0380$06.75/0 © 1994 American Chemical Society\n\\end{title}\n\nIn Polymers for Microelectronics; Thompson, L., et al.; ACS Symposium Series; American Chemical Society: Washington, DC, 1993.\n\n\\begin{caption}\nFigure 1. Two layer metal device using PI dielectric.\n\\end{caption}\n\n\\begin{caption}\nFigure 2. Failure time dependence of PI interconnect devices on absolute water vapor pressure.\n\\end{caption}\n\n\\begin{caption}\nFigure 3. Application fields of Pis.\n\\end{caption}\n\nIn Polymers for Microelectronics; Thompson, L., et al.; ACS Symposium Series; American Chemical Society: Washington, DC, 1993.\n\nimportant issue to reduce the mold stress during soldering process. For this purpose, coating the surface of the chip by PI is currently remarked and utilized in the industry.\n\n\\begin{title}\nPrevention of Passivation Crack\n\\end{title}\n\nFig. 4 compares the humidity resistance of the package of PSG passivated chip dipped in solder with non dipped sample (4). Failure rate of solder dipped package is higher. However, when 2 fim thick PI (PIQ:PMDA/BTDA/ODA/ Diaminodiphenylether carbonamide) film was coated on the PSG passivation, failure rate was remarkably improved to the equivalent value to non dipped package as shown in Fig. 5 (4).\n\nRole of PI chip coat film can be explained as follows. In a case of PSG passivation alone, cracks are generated in the PSG film by the mold stress because of the brittleness of PSG film, and A l electrode corrodes by the moisture penetrating through these cracks. On the other hand, for a package with PI chip coat, mold stress is absorbed by this PI film and the passivation crack is prevented.\n\nFig. 6 compares the passivation crack for various PI chip coat (5). PI-A is low thermal expansion, PI-B is low modulus and PI-C is conventional (Hereafter conventional PI refers to PMDA/ODA PI unless otherwise specified). Among them, low modulus PI-B coating gives the best result. This can be explained by its big stress absorbing ability. On the other hand, relatively good preventing effect is observed for PI-A, which has the highest modulus. In this case stress generation is suppressed by the smaller difference of coefficient of thermal expansion between PI and passivation film. Namely, both PI-A and -B have an ability to prevent passivation crack but their function is different. This can be understood by the fact that stress is proportional to the product of the difference of coefficient of thermal expansion of PI film and substrate and modulus of PI film.\n\nIn some cases mold stress affects the active area of the device. Table 1 shows the effect of PI chip coat on the threshold voltage shift of Bipolar Interface Device having piezosensitive circuit (6). By applying 12 fim thick PI coat, threshold failure rate decreases from 10 to 0 %. PI plays an important role to stabilize the electrical property of the circuit by relaxing the mold stress.\n\n\\begin{title}\nPrevention of Electrode Slide\n\\end{title}\n\nAl electrode in a chip can slide by the mold stress during heat cycle. Effect of PI chip coat on Al slide is shown in Table 2 (5). No Al slide was observed for both low thermal expansion and low stress Pis compared to the large Al slide for non-coated device. Thus, PI coating is also effective to Al slide by absorbing the stress generated by heat cycle.\n\n\\begin{title}\nPrevention of Package Crack\n\\end{title}\n\nRecently, so called package crack attracts attention. Package crack occurs as a result of the abrupt evaporation of moisture trapped at the interface of mold\n\nIn Polymers for Microelectronics; Thompson, L., et al.; ACS Symposium Series; American Chemical Society: Washington, DC, 1993.\n\n\\begin{caption}\nFigure 4. Degradation of humidity resistance by dipping in solder.\n\\end{caption}\n\n\\begin{caption}\nFigure 5. Effect of PIQ formed on PSG for the humidity resistance of solder dipped device.\n\\end{caption}\n\n\\begin{title}\nIn Polymers for Microelectronics; Thompson, L., et al.; ACS Symposium Series; American Chemical Society: Washington, DC, 1993.\n\\end{title}\n\n\\begin{legend}\n(a)WithoutCoating(b)Pl-A\n\\end{legend}\n\n\\begin{legend}\n(c)PI-B\n\\end{legend}\n\n\\begin{table}\n| | Pl-B Pl-A | Pl-C |\n|:---------------------------|:------------|:----------|\n| Modulus (MPa) | 7060 | 1570 2940 |\n| Thermal expansion (10-6/℃) | 9.6 | 37 35 |\n\\end{table}\n\n\\begin{caption}\nFigure 6. Effect of P I chip coat on passivation crack after thermal cycle test.\n\\end{caption}\n\nIn Polymers for Microelectronics; Thompson, L., et al.; ACS Symposium Series; American Chemical Society: Washington, DC, 1993.\n\n\\begin{legend}\n(d)PI-C\n\\end{legend}\n\nDownloaded by PENNSYLVANIA STATE UNIV on September 10, 2012 | http://pubs.acs.org Publication Date: November 23, 1993 | doi: 10.1021/bk-1994-0537.ch026\n\n\\begin{caption}\nTable 1. Electrical Test and Yield Data of Polyimide Coated BPI Devices\n\\end{caption}\n\n\\begin{table}\n| Thickness microns | Bake\" Type | Threshold Failure(%) | Cont. Fail(%) | Yield (%) |\n|:--------------------|:-------------|:-----------------------|:----------------|:------------|\n| None | N/A | 10 | 0.0 | 90.0 |\n| 2 | A | 1 | 0.0 | 98.4 |\n| 2 | N | 2 | 0.0 | 97.3 |\n| 12 | A | 0 | 0.0 | 98.9 |\n| 12 | N | 0 | 0.6 | 98.7 |\n\\end{table}\n\n\\begin{title}\n1)N : N2 atmosphere A : Air atmosphere\n\\end{title}\n\n\\begin{caption}\nTable 2. Al Slide by Thermal Shock Test\n\\end{caption}\n\n\\begin{table}\n| Number of cycles | Ae Slide (um) | Ae Slide (um) | Ae Slide (um) | Ae Slide (um) |\n|:-------------------|:----------------|:----------------|:----------------|:----------------|\n| Number of cycles | No Coat | P1-A | P1-B | P1-C$ |\n| 100 | 1 | 0 | 0 | 0 |\n| 300 | 3 | 0 | 0 | 0 |\n| 500 | 5 | 0 | 0 | 1 |\n| 1000 | 8 | 0 | 0 | 3 |\n\\end{table}\n\n\\begin{caption}\nThermal shock test: - 196°C/2min^150°C/2min\n\\end{caption}\n\n\\begin{table}\n| Item | Pl-A Pl-B$ | P1-C$ |\n|:--------------|:-------------|:----------|\n| Modulus (MPa) | 7060 | 2940 1570 |\n| CTE(10-6/°℃) | 9.6 | 35 37 |\n\\end{table}\n\nIn Polymers for Microelectronics; Thompson, L., et al.; ACS Symposium Series; American Chemical Society: Washington, DC, 1993.\n\nresin and chip or lead frame during high temperature soldering. Table 3 summarizes the mode of package crack and the factors affecting the cracks. There are three kinds of package crack. Top crack occurs from the delamination between mold resin and chip surface. Bottom crack from the delamination between mold resin and back side of die pad. Side crack relates to die attaching material.\n\nFig. 7 shows a mechanism of bottom package crack induced by the vapor pressure (7). Moisture trapped between die pad and mold resin evaporates in the soldering process. From this mechanism, it is thought to be possible to prevent crack by the improvement of adhesion between die pad and mold resin. By forming a thick PI film on the back side of die pad as shown in Fig. 8, occurrence of package crack was investigated. Results are shown in Table 4 (8). By forming PI layer, package crack can be depressed, but it depends on the type of PI. Of these Pis, PI-B which has good adhesion, T g higher than soldering temperature, 260 °C, and low moisture absorption rate shows the best result.\n\nNext example is the prevention of top crack by coating PI on a chip surface. Table 5 shows the number of cracked package for various PI coated and non coated device after moisture absorption followed by vapor phase soldering and heat cycle (9). Cracking can be drastically suppressed by forming PI chip coat. No remarkable difference was observed among Pis, but big difference was observed between molding compound A and B. Observing the interface of chip and molding compound, delamination was found for the cracked package. Namely, top crack can be prevented by improving the adhesion between molding compound and chip by PI chip coating and selection of molding compound.\n\n\\begin{title}\nRequired Properties of PI for Chip Coat Application\n\\end{title}\n\nAs so far described, PI chip coat is effective to prevent damages to the package during soldering or heat cycle. Table 6 summarizes the required properties of PI for chip coat. These values can be deduced from the reliability data mentioned above. Table 7 shows the 5 step ranking of various types of Pis for these properties. Conventional and fluorinated Pis show the balanced prop- erties but the stress is rather high. Low modulus PI has low T g and high moisture absorption. There is a problem of low adhesive property in low thermal expan- sion PI. If the adhesion of low thermal expansion PI can be improved by a certain method, it must be the best fit material.\n\nReliability of chip coated device is strongly affected by the adhesion of mold resin and PI film. Mechanism of the adhesion of mold resin and PI and the method to improve it will be introduced in the following. Fig. 9 is a typical viscoelastic spectrum of PI (10). j8 dispersion due to the localized motion of the molecular chain is observed at around 130 °C. Relation between adhesive strength and /3 dispersion temperature is shown in Fig. 10 (10). Good correla- tion is observed between them. The lower the /3 dispersion temperature, the higher the adhesion. Especially, when p temperature exceeds the curing temper- ature of mold resin, 180 °C in this case, the adhesive strength drastically drops. This means that, in order to obtain high adhesion, stress of PI has to be relaxed\n\n\\begin{title}\nIn Polymers for Microelectronics; Thompson, L., et al.;\n\\end{title}\n\nACS Symposium Series; American Chemical Society: Washington, DC, 1993.\n\n\\begin{caption}\nTable 3. Factors Affecting the Package Crack\n\\end{caption}\n\n\\begin{table}\n| Crack mode | Factors 1 | Factors 2 |\n|:----------------------------|:---------------------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------|\n| Top Crack | Delamination between mold resin and chip | Poor adhesion between mold resin and chip |\n| Side Crack | Delamination of die attaching layer | Poor mechanical strength. adhesion.and voids of die attaching material |\n| Bottom Crack | Delamination between mold resin and back side of die pad. | Poor adhesion between mold resin and die pad |\n| Common factors to each mode | Large quantity of moisture pick up of package Insufficient mechanical strength of mold resin | Large quantity of moisture pick up of package Insufficient mechanical strength of mold resin |\n\\end{table}\n\n\\begin{caption}\nFigure 7. Package cracking mechanism induced by vapor pressure.\n\\end{caption}\n\n\\begin{caption}\nFigure 8. Prevention of package crack by forming PI layer on the back side of die pad.\n\\end{caption}\n\nIn Polymers for Microelectronics; Thompson, L., et al.; ACS Symposium Series; American Chemical Society: Washington, DC, 1993.\n\n\\begin{caption}\nTable 4. Dependence of Package Crack on PI Chip Coat\n\\end{caption}\n\n\\begin{table}\n| Material | Adhesion | $T$ | Water (Wt%) | Crack Package | Crack Package |\n|:-----------|:-----------|:------|:--------------|:---------------------------|:----------------------|\n| Material | Adhesion | $T$ | Water (Wt%) | Absorption Time kept under | 85℃/85%RH |\n| P1-A$ | Good | 245 | 1.1 | 72h Not observed | 168h |\n| P1-B | Good | 260 | 0.9 | observed Not | Observed Not observed |\n| PI-C$ | Bad | 290 | 1.0 | Observed | - |\n| No Coat | - | - | - | Observed | - |\n\\end{table}\n\nSoldering Condition : 85 °C/Q5 % RH for 75 or 168h — Solder dip 280 °C/10s\n\n\\begin{caption}\nTable 5. Number of Cracked Package After VPS and Heat Cycle Test\n\\end{caption}\n\n\\begin{table}\n| Molding compound | MC-A | MC-A | MC-A | MC-B | MC-B | MC-B |\n|:-----------------------|:-------|:-------|:-------|:-------|:-------|:-------|\n| No. of heat cycle PIs\" | Blank2 | 03³ | 250 | Blank² | 03 | 250 |\n| Pl-A | 0/10 | 1/10 | 2/10 | 0/10 | 0/10 | 0/10 |\n| Pl-B$ | 0/10 | 2/10 | 2/10 | 0/10 | 0/10 | 00/10 |\n| Pl-C$ | 0/10 | 0/10 | 01/10 | 0/10 | 0/10 | 00/10 |\n| P1-D | 0/10 | 0/10 | 01/10 | 0/10 | 0/10 | 0/10 |\n| No Coat | 0/10 | 1/10 | 8/10 | 0/10 | 0/10 | 01/10 |\n\\end{table}\n\nNumber of cracked package /total package 1) PI-A, PI-B : Conventional thermal Cure Pis Pl-C : Ion bond type photosensitive PI Pl-D : Covalent bond type photosensitive PI 2) Before moisture absorption 3) After VPS\n\n\\begin{caption}\nTable 6. Required Properties of PI for Chip Coat Application\n\\end{caption}\n\n\\begin{table}\n| ltem | Required properties |\n|:--------------------|:------------------------------------------------------------|\n| Adhesive strength | PI-Molding Compound=PI-Chip >Molding Compound-Chip(no coat) |\n| stress Residual | <20 MPa |\n| Moisture absorption | <0.5% |\n| Tg | >260℃ (soldering temp.) |\n\\end{table}\n\nIn Polymers for Microelectronics; Thompson, L., et al.; ACS Symposium Series; American Chemical Society: Washington, DC, 1993.\n\n\\begin{caption}\nTable 7. Ranking of Pis for Chip Coat Application\n\\end{caption}\n\n\\begin{table}\n| Item | Conven- tional P1 | Fluorin- ated P1 | Low modulus PI | Low thermal expansion PI |\n|:--------------------|:--------------------|:-------------------|:-----------------|:---------------------------|\n| Adhesive strength | 5 | 3 | 5 | 1 |\n| Residual stress | 3 | 3 | 5 | 5 |\n| Moisture absorption | 3 | 5 | 2 | 5 |\n| Tg | 4 | 4 | 1 | 5 |\n\\end{table}\n\n\\begin{caption}\n1 : Worst . 5 : Best\n\\end{caption}\n\n\\begin{caption}\nFigure 9. Visco-elastic property of PI.\n\\end{caption}\n\n\\begin{caption}\nFigure 10. Relation of T/3 of Pis with adhesive strength of Pis and molding compounds. In Polymers for Microelectronics; Thompson, L., et al.; ACS Symposium Series; American Chemical Society: Washington, DC, 1993.\n\\end{caption}\n\nat the cure temperature of mold resin. In other words, PI having dispersion temperature lower than curing temperature shows good adhesion to the mold resin.\n\nBut some Pis such as low thermal expansion PI has no or very high )3 dispersion temperature and no stress relaxation is expected. In such a case, it is expected that the PI surface treatment is effective from the analogy of the improvement of PI-PI adhesion. By treating the PI surface by N 2 or O z ashing, contact angle decreased and good adhesion was obtained as shown in Table 8 (ii). By the plasma treatment PI surface is roughened. Anchoring effect may also be the factor to enhance the adhesive strength. In conclusion, poor adhesion of low thermal expansion PI can be improved by the plasma treatment, and low thermal expansion PI is the most promising material for the chip coat applica- tion.\n\n\\begin{title}\nA P P L I C A T I O N T O M U L T I C H I P M O D U L E ( M C M )\n\\end{title}\n\nPI has began to be applied to multi chip module, which can reduce the machine cycle of computer. Cross section of typical MCM is shown in Fig. 11 (12). 5 layers of metallization insulated by 15 to 20 fim thick PI film is formed on ceramic wiring board. Table 9 is the results of the evaluation of various Pis for MCM (13). Among them, low stress PI, namely low thermal expansion PI, seems to be best balanced except for adhesion and planarity. In the following, recent works to improve these properties of low thermal expansion PI will be intro- duced.\n\nIn MCM there exists three adhesion interfaces, metal on PI, PI on PI and PI on metal as shown in Fig. 12. Among them adhesion of PI on metal is sufficient. Fig. 13 compares the adhesive strength of conventional PI, PIQ, and low thermal expansion PI, L-100, for various metals (14). Adhesion of low thermal expansion PI is extremely low. But, as shown in Fig. 14, by treating the PI surface by oxygen, CF4 or nitrogen gas plasma, high adhesion can be obtained for Cu and Ti, which shows poor adhesion when untreated (14). Among the gases nitrogen is most effective. Reason of the improvement of adhesion by nitrogen plasma was investigated by the surface analysis using ESCA (14). Imide group decomposes to produce more active group such as amide and amino as shown in Fig. 15. These groups are thought to work to improve adhesion.\n\nThe second interface, PI-PI adhesion is also able to be improved by either oxygen plasma or Ar sputtering of PI surface as shown in Fig. 16. PI-PI adhesion is influenced by the baking atmosphere. Fig. 17 shows the experimental results of the dependence of the baking atmosphere on the adhesion (15). By baking in nitrogen atmosphere high adhesion is maintained under high humid condition for PI-C, low thermal expansion PI.\n\nPlanarity of PI film is affected by the solid content of PI precursor. Good planarity can be obtained for high solid content varnish as shown in Fig. 18 (16). However, usually, high solid content means high viscosity and gives the ununi- formity of the resultant film. Most effective method to obtain low viscosity varnish with high solid content is to decrease molecular weight by using capped monomer such as half ester of acid dianhydride. Liquid properties of PI precursor obtained by ester oligomer method is shown in Table 10 (16).\n\n\\begin{title}\nIn Polymers for Microelectronics; Thompson, L., et al.;\n\\end{title}\n\nACS Symposium Series; American Chemical Society: Washington, DC, 1993.\n\n\\begin{caption}\nTable 8. Effect of PI Surface Treatment on the Adhesion Between PI and Mold Resin\n\\end{caption}\n\n\\begin{table}\n| Test pieces | PI surface treatment | Contact angle degree) | Adhesion |\n|:--------------|:-----------------------|:------------------------|:-----------|\n| A | ashing No | 68.1 | Poor |\n| B | ashing $N₂}$ | 48.2 | Good |\n| C | 0{ RIE | 41.6 | Good |\n| D | $ ashing | 32.1 | Good |\n\\end{table}\n\n\\begin{caption}\nFigure 11. Cross section of PI thin film multi chip module.\n\\end{caption}\n\n\\begin{legend}\nPI\n\\end{legend}\n\n\\begin{caption}\nFigure 12. Three adhesion interfaces in PI multi chip module.\n\\end{caption}\n\nIn Polymers for Microelectronics; Thompson, L., et al.; ACS Symposium Series; American Chemical Society: Washington, DC, 1993.\n\n\\begin{caption}\nTable 9. Evaluation of Various Pis for M C M Application\n\\end{caption}\n\n\\begin{table}\n| Property | Standard PI | Fluorinated PI | Silicone PI | Low stress PI | Acetylene- terminated P1 | Benzocyclo- butene |\n|:----------------------|:--------------|:-----------------|:--------------|:----------------|:---------------------------|:---------------------|\n| Solvent compatibility | 1 | 1~5 | 1 | 1 | 1~5 | 1 |\n| Thermal properties | 2 | 3 | 3 | 1 | 2 | 3 |\n| Moisture absorption | 5 | 3 | 3 | 2 | 4 | 1 |\n| Stress | 5 | 5 | 5 | 1 | 5 | 5 |\n| Adhesion | 1 | 2 | 2 | 5 | 2 | 2 |\n| Planarization | 5 | 5 | 5 | 5 | 1 | 1 |\n| RIE etchability | 1 | 1 | 4 | 1 | 1 | 4 |\n\\end{table}\n\n\\begin{caption}\nRelative ranking 1 - Best: 5 — Worst\n\\end{caption}\n\n\\begin{caption}\nFigure 13. Peel strength of metal films to PIQ and low thermal expansion PI (PIQ-L100).\n\\end{caption}\n\nIn Polymers for Microelectronics; Thompson, L., et al.; ACS Symposium Series; American Chemical Society: Washington, DC, 1993.\n\n\\begin{caption}\nFigure 14. Improvement of adhesion to low thermal expansion PI by plasma surface treatment.\n\\end{caption}\n\n\\begin{caption}\nFigure 15. N(1s) spectra of untreated and N2 plasma treated surfaces.\n\\end{caption}\n\nIn Polymers for Microelectronics; Thompson, L., et al.; ACS Symposium Series; American Chemical Society: Washington, DC, 1993.\n\n\\begin{caption}\nFigure 16. Improvent of PI-PI adhesion by surface treatment.\n\\end{caption}\n\n\\begin{table}\n| □ : P-A/Pl-A in N2 ∆:P-B/P-B inN2 O: PI-C/PI-C in N2 | :P-A/Pl-A in Air ▲: PI-A/PI-B in Air : PI-C/PI-C in Air |\n|:-------------------------------------------------------|:----------------------------------------------------------|\n| Pls | Pl-C PI-B Pl-A |\n| Thermal expansion coefficient(10-5/℃) | 4.5 1.9 0.3 |\n\\end{table}\n\n\\begin{caption}\nFigure 17. Dependence of PI-PI adhesive strength on baking atmosphere.\n\\end{caption}\n\nIn Polymers for Microelectronics; Thompson, L., et al.; ACS Symposium Series; American Chemical Society: Washington, DC, 1993.\n\n\\begin{caption}\nFigure 18. Relation between resin content and planarity.\n\\end{caption}\n\n\\begin{caption}\nTable 10. Synthesis of High Solid Content and Low Viscosity Polyamic Acid\n\\end{caption}\n\n\\begin{table}\n| | Ester Oligomer Method | Polyamic acid Method |\n|:-----------------|:------------------------------------------------------------|:-------------------------------------------------|\n| Synthesis Method | 2R 0HO0C COOR\" Co、 co 0 R o co co 7NHCOCOOR H₂NR'NH R ^0oc | ca ca O +H₂NR'NH₂ o R co' co NHCO、 COOH R \\HOoC |\n| Resin Content | RCONH-R'\\$ 40% | $CONH-R$ 14.5% |\n| Viscosity | 100cp | 1100cp |\n| Molecular Weight | 500~1000 | =30.000 |\n\\end{table}\n\nIn Polymers for Microelectronics; Thompson, L., et al.; ACS Symposium Series; American Chemical Society: Washington, DC, 1993.\n\nCu is widely used as the wiring metal of MCM. When PI precursor is baked in contact with Cu, its properties deteriorates as shown in Table 11. This deterioration is explained by the decomposition of imide ring as a result of the reaction of migrated Cu ion and carboxyl group of polyamic acid (27). So it is necessary to cover Cu wire by another metal such as Cr or to use preimidized PI instead of polyamic acid.\n\nTable 12 is a summary of selection of PI and processing in M C M applica- tion. Low thermal expansion PI is most promising. Future subject is etching. 0 2 -RIE is most suitable from the point of fine patterning but the etching time is too long for the production line. Therefore, photosensitive low thermal expan- sion PI seems to be most promising for MCM application, hopefully preimidized in order to prevent the reaction with Cu, and positive working to get high accurate patterning.\n\n\\begin{title}\nAPPLICATION TO LIQUID CRYSTAL DISPLAY (LCD)\n\\end{title}\n\nIn LCD picture image is obtained through the change of the transmission of light by orienting the liquid crystal molecule under the electrical field (Fig. 19). The orientation of liquid crystal is controlled by the alignment surface, and PI is dominantly utilized for this purpose. One of the advantages of PI is to be able to control the pretilt angle. As shown in Fig. 20 pretilt angle is defined as an angle between liquid crystal molecule and alignment surface under the absence of electrical field. This pretilt angle is produced by rubbing the surface of PI. If this pretilt angle is not constant throughout the panel, orientation of liquid crystal is dispersed and gives an ununiform image.\n\nFig. 21 shows the relation between surface tension of alignment surface and pretilt angle for two kinds of Pis (18). Pretilt angle increases with the decrease of surface tension. [Usually pretilt angle increases with the increase of surface tension. This result seems to be the mistyping of the original paper]. However, for PI containing long alkyl chain, pretilt angle increases drastically. This indicates that pretilt angle is also affected by the physical structure of the surface.\n\nPis having various methylene chain length were synthesized using alkyl chain containing diamine, and the relation between chain length and pretilt angle was investigated (19). Results are shown in Fig. 22. Low pretilt angle is obtained for odd carbon number PI, and high pretilt angle for even number PI. This phenomenon can be interpreted from the difference of the conformations of Pis as shown in Fig. 23 (19). Assuming that PI is oriented to rubbing direction, PI using odd carbon number diamine has cis conformation. If liquid crystal molecule is adsorbed to alkyl chain no pretilt angle is produced. But for even number PI, since its conformation is trans zigzag, liquid crystal molecule is aligned in one direction with pretilt angle a.\n\nTable 13 shows some of the example of the required properties to the alignment surface of TFT LCD and molecular design of PI. Preimidized varnish reacted from alkyl chain containing diamine and cycloaliphatic dianhydride, which is closely related to the voltage retention rate, seems to be the most appropriate PI for the alignment surface of TFT LCD.\n\n\\begin{title}\nIn Polymers for Microelectronics; Thompson, L., et al.;\n\\end{title}\n\nACS Symposium Series; American Chemical Society: Washington, DC, 1993.\n\n\\begin{caption}\nTable 11. Comparison of the Characteristics of Pis Cured on Various Substrates\n\\end{caption}\n\n\\begin{table}\n| Underlying Film | Decomposition Temperature (℃) | Tensile Strength (kg/mm²) | Elongation (%) |\n|:------------------|:--------------------------------|:----------------------------|:-----------------|\n| Cu | 380 | 11.0 | 8.0 |\n| SiO₂ | 450 | 13.5 | 17.0 |\n| Cr | 450 | 13.4 | 16.8 |\n| AI | 450 | 13.5 | 16.7 |\n\\end{table}\n\n\\begin{caption}\nCure: N*. 350°C\n\\end{caption}\n\n\\begin{caption}\nTable 12. Summary of the Selection of PI and Processing in MCM Application\n\\end{caption}\n\n\\begin{table}\n| Required properties | Countermeasure |\n|:-----------------------|:----------------------------------------------------------------------|\n| Low stress Hghadhesion | Low thermal expansion PI Metal on PI Nz sputter |\n| High planarity | PI on PI Ar sputter, O2 plasma, N₂ bake High solid type polyamic acid |\n| No reaction with | Electro/ Electroless plating Cr over coat |\n| Cu Etchability | O₂-RIE but etching time is too long |\n\\end{table}\n\n\\begin{molecule}\nC1CCCC1\n\\end{molecule}\n\n\\begin{table}\n| Photosensitive low thermal expansion PI |\n|-------------------------------------------|\n\\end{table}\n\nIn Polymers for Microelectronics; Thompson, L., et al.; ACS Symposium Series; American Chemical Society: Washington, DC, 1993.\n\n\\begin{caption}\nFigure 19. T-V property of liquid crystal display.\n\\end{caption}\n\n\\begin{caption}\nx Substrate Figure 20. Generation of pretilt angle by rubbing the surface of alignment\n\\end{caption}\n\nIn Polymers for Microelectronics; Thompson, L., et al.; ACS Symposium Series; American Chemical Society: Washington, DC, 1993.\n\n\\begin{caption}\n26. MAKINO Application of Polyimides to Microelectronics\n\\end{caption}\n\n\\begin{caption}\nFigure 21. Relation between surface tension and pretilt angle.\n\\end{caption}\n\n\\begin{caption}\nFigure 22. Diamine carbon chain length of PI and pretilt angle.\n\\end{caption}\n\n\\begin{caption}\nFigure 23. Schematic representation of the conformation of Pis derived from diamine having odd and even numbered carbons and the generation of pretilt angle.\n\\end{caption}\n\nIn Polymers for Microelectronics; Thompson, L., et al.; ACS Symposium Series; American Chemical Society: Washington, DC, 1993.\n\n\\begin{caption}\nTable 13. Example of Required Properties of Alignment Surface of TFT LCD and Molecular Design of PI\n\\end{caption}\n\n\\begin{table}\n| Required properties | Required properties | Molecular design |\n|:------------------------------------------------|:----------------------|:-----------------------------------------------------------------------|\n| Cure temp. Pretilt angle Voltage retention rate | <180°℃F 5° >98% | varnish Preimidized Introduction of alkyl chain Cycloaliphatic monomer |\n\\end{table}\n\nPreimidized varnish reacted from alkyl chain containing diamine and cycloaliphatic dianhydride\n\nRefractive Index: Core>Cladding Figure 24. Structure of passive optical wave guide.\n\n\\begin{molecule}\nC(F)(F)(F)c1cc(N)ccc1-c1ccc(N)cc1C(F)(F)F\n\\end{molecule}\n\n\\begin{molecule}\nC(c1ccc2c(c1)C(=O)OC2=O)(c1ccc2c(c1)C(=O)OC2=O)(C(F)(F)F)C(F)(F)F\n\\end{molecule}\n\n\\begin{molecule}\nO=c1oc(=O)c2cc3c(=O)oc(=O)c3cc12\n\\end{molecule}\n\n\\begin{molecule}\nC(F)(F)(F)c1cc(C)ccc1-c1ccc(-n2c(=O)c3cc4c(=O)n(C)c(=O)c4cc3c2=O)cc1C(F)(F)F\n\\end{molecule}\n\n\\begin{molecule}\nC(F)(F)(F)C1C(C2C(C(F)(F)F)=CC(*)=CC=2)=CC=C(N2C(=O)C3C(=CC=C(C=3)C(C3C=C4C(N(C(=O)C4=CC=3)*)=O)(*)*)C2=O)C=114:39:41:CF342:CF3\n\\end{molecule}\n\nFigure 25. Structure of fluorinated Pis designed for optical wave guide applica- tion.\n\nIn Polymers for Microelectronics; Thompson, L., et al.; ACS Symposium Series; American Chemical Society: Washington, DC, 1993.\n\n\\begin{title}\nAPPLICATION TO OPTICAL WAVE GUIDE (OWG)\n\\end{title}\n\nOptical wave guide which is used in the opto-electronic packaging composes of core and cladding and when refractive index of core is higher than cladding light progresses in the core as shown in Fig. 24. PI optical wave guide has been extensively studied (20, 21) since PI stands better for soldering temperature and various circumstances than PMMA or polycarbonate.\n\nPI for optical wave guide must have a high transmittancy to the light. Fluorinated PI is known to be transparent to the visible light. Fig. 25 shows the two types of fluorinated Pis (22). Properties of these Pis are shown in Table 14. In order that light progresses in a core without leaking to cladding, refractive index difference should be greater than 0.005 to 0.01. At the same time, since cladding and core are fabricated as an unit, their properties are required to be similar. By changing the mole ratio of 6FDA and PMDA as shown in Fig. 26 (22), it is possible to design two kinds of Pis, one for core and one for cladding, with different refractive index and similar properties.\n\n\\begin{title}\nCONCLUSION\n\\end{title}\n\nSo far the recent activities on the application of PI to microelectronics are reviewed and the following conclusion can be obtained.\n\n(1) To add new functions is required to PI with the spread of the applica- tion of PI to microelectronics.\n\n(2) PI chip coat is effective for the prevention of passivation crack, Al slide and package crack of semiconductor devices. Low thermal expansion PI can be regarded as the most suitable material for this application.\n\n(3) Low thermal expansion PI is also the most appropriate material for MCM application. But it has disadvantages in adhesion, planarity and reaction with Cu, which can be improved by the chemistry of PI, processing and wire structure.\n\n(4) PI plays an important role as an alignment surface of STN and TFT LCDs. Pretilt angle can be controlled by introducing alkyl chain to PI backbone. At the present stage preimidized varnish reacted from alkyl chain containing diamine and cycloaliphatic dianhydride seems to be most promising.\n\n\\begin{caption}\nTable 14. Characterise of Fluorinated Pis\n\\end{caption}\n\n\\begin{table}\n| 一 | 一 | 一 |\n|:----------------------------|:----------|:----------|\n| Item | 6FDA/TFDB | PMDA/TFDB |\n| Fluorine content, % | 31.3 | 23.0 |\n| Refractive index (589.6 nm) | 1.556 | 1.647 |\n| Dielectric constant | 2.8 | 3.2 |\n| Tg.℃ | 335 | >400 |\n| Water absorption, % | 0.2 | 0.7 |\n| Thermal expansion | 4.8 | 0.3 |\n| coefficient, 10-5×℃-1 | | |\n| Decomp.temp. C | 569 | 610 |\n\\end{table}\n\nIn Polymers for Microelectronics; Thompson, L., et al.; ACS Symposium Series; American Chemical Society: Washington, DC, 1993.\n\n\\begin{caption}\nFigure 26. Copolymer ratio of 6FDA and PMDA and refractive index.\n\\end{caption}\n\n(5) PI is also the promising material for the cladding and core of optical wave guide. Fluorinated PI is extensively evaluated because of its high light transmittancy and controlability of refractive index.\n\n\\begin{title}\nREFERENCES\n\\end{title}\n\n1. K. Sato et al., IEEE Trans. Parts, Hybrid and Packaging, PHP-9, 176 (1973).\n\n2. T. Nishida et al., Proc. Int. Rel. Phys. Symp. (1985).\n\nNumata et al., \"Polymers for Microelectronics\", Kodansha, 689\n\n4. S. Sasaki et al., Proc. 34th Electr. Comp. Conf., 383 (1984).\n\n5. T. Takeda and A. Tokoh, Proc. 38th Electr. Comp. Conf., 420 (1988).\n\nM. M. Khan et al., Proc. 38th Electr. Comp. Conf., 425\n\n7. A. Nishimura, Tech. Proc. Semicon Japan, 502 (1991).\n\n8. K. Fujita et al., Industry Technical Seminor, Japan, T2106, 66 (1988).\n\nTakeuchi et al., Proc. 40th Electr. Comp. Conf., 818 (1990).\n\n10. M. Tomikawa et al., \"Polymers for Microelectronics\", Kodansha, 655 (1989).\n\n11. N. Shimizu et al., Nikkei Microdevices, Japan, March, 83 (1992).\n\nD. Akihiro et al., Proc. 40th Electr. Comp. Conf., 525 (1990).\n\n13. T. G. Tessier et al., Proc. 39th Electr. Comp. Conf., 127 (1989).\n\n14. K. Miyazaki et al., Proc. 176th Meeting of Electro Chemical Soc., No220 (1989).\n\n15. T. Takizawa et al., Proc. 203rd ACS National Meeting, Division of PMSE, 283 (1992).\n\n16. S. Uchimura et al., \"Polymers for Microelectronics\", Kodansha, 603 (1989).\n\n17. K. Miyazaki et al., Proc. 174th Meeting of Electro Chemical Soc., No208 (1988).\n\n18. T. Abe et al., Organic Synthesis Chemistry, Japan, 49, 506 (1990).\n\n19. H. Yokokura et al., Proc. 16th Liquid Crystal Symp., Japan, 308 (1990).\n\n20. R. Reuter et al., Appl. Opt., 27, No21 (1988).\n\n21. R. Selvaraj et al., J. Lightwave Tech., 6, 1034 (1988).\n\n22. T. Matsuura et al., Macromolecules, 24, 5001 (1991).\n\n\\begin{title}\nRECEIVED May 20, 1993\n\\end{title}\n\nIn Polymers for Microelectronics; Thompson, L., et al.;\n\nACS Symposium Series; American Chemical Society: Washington, DC, 1993.\n\n" + }, + { + "abbreviations": [ + { + "abbreviation": "PMDA" + } + ], + "csv": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/label_data/10.1021/ma9021828.csv", + "golden_label": [ + { + "abbreviation": "PMDA", + "full_name": "pyromellitic dianhydride", + "smiles": "O=c1oc(=O)c2cc3c(=O)oc(=O)c3cc12" + } + ], + "path": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/pdf_data/10.1021/ma9021828_uniparser.json", + "pdf": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/pdf_data/10.1021/ma9021828.pdf", + "text": "\\begin{title}\nThermotropic Liquid Crystalline Polyimides with Siloxane Linkages: Synthesis, Characterization, and Liquid Crystalline Behavior\n\\end{title}\n\nYu Shoji, Ryohei Ishige, Tomoya Higashihara, Junji Watanabe, and Mitsuru Ueda*\n\nDepartment of Organic and Polymeric Materials, Graduate School of Science and Engineering, Tokyo Institute of Technology, 2-12-1-H-120, O-okayama, Meguro-Ku, Tokyo 152-8552, Japan Received October 2, 2009; Revised Manuscript Received November 4, 2009\n\nABSTRACT: Thermotropic liquid crystalline (LC) semialiphatic polyimides have been developed from diamines containing siloxane spacer units with pyromellitic dianhydride (PMDA) or 3,30,4,40-tetracarboxy- biphenyl dianhydride (BPDA). Monomer diamines with siloxane units were prepared by three steps, which include Williamson’s synthesis, hydrosilylation, and reduction. The polymerization was conducted by the conventional method, solution polymerization, followed by thermal imidization. A highly viscose poly(amic acid) solution was obtained and its inherent viscosities were 0.65-1.73 dL/g. These novel polyimides exhibited high thermal stability and a lower crystal-LC transition temperature compared to reported polyimides containing alkylene or oxyethylene spacer units. X-ray studies were performed for investigating the oriented smectic mesophases of each polyimide. In the polyimides derived from PMDA, a smectic A (SmA) phase was formed on gradual cooling from the isotropic liquid phase. On the other hand, the polyimides based on BPDA formed a smectic C (SmC) phase as well as a SmA phase.\n\n\\begin{title}\nIntroduction\n\\end{title}\n\nRecent integration, miniaturization, and high functionaliza- tion in electronics are rapidly progressing, where both conductors and insulating materials have been packaged as densely as possible. The low thermal conductivity of insulating polymers yields a large temperature rise and gradient in devices that causes electric connection failure and reduces the lifetime of these devices. Therefore, thermoconductive polymers which canrelease generated heat effectively are required in semiconductors as electric insulators. To increase thermal conductivity, highly oriented polymers, that is, liquid crystalline (LC) polymers, are effective candidates.1 The alignments of LC polymers are con- trolled in common ways, such as stretching, rubbing, the mag- netic field, and self-alignment.2-5\n\nAromatic polyimides are promising materials for the applica- tions to aerospace and electronic devices due to their excellent physical and chemical properties, that is, they have outstanding thermal and chemical stabilities, mechanical properties, electrical properties, and radiation resistance.6,7 Next-generation poly- meric insulators with high thermal conductivity required rela- tively low phase transition temperatures and low elasticresistance for easy processing. Thus, LC polyimides possessing flexible spacer units are good candidates. A few LC polyimides with sequences of methylene or ethylene oxide units in the main chains have been reported, such as thermotropic LC polyimides with methylene units (8-12) from a special tetracarboxylic dian- hydride, 4,400-terphenyltetracarboxylic dianhydride and aliphatic diamines,8-10 and segmented LC polyimides prepared from 3,30,4,40-tetracarboxybiphenyl dianhydride (BPDA) and R,ω- bis(4-aminophenoxy)oxyethylene units.11 These polyimides showed liquid crystallinity and lower phase transition tempera- tures compared to the polyimides based on BPDA and diamines with methylene spacer units (>350 C). For practical applica- tions, a further decrease in fabrication temperatures is required to\n\n*Corresponding author. E-mail: mueda@polymer.titech.ac.jp.\n\navoid oxidation of the copper wires inside integrated circuits (ICs). It is well-known that a siloxane unit is highly flexible, thus polyimides containing siloxane linkages are expected to show lower LC transition temperatures.\n\nIn a preceding work, we briefly reported the synthesis of LC polyimides with flexible siloxane spacer units (Scheme 1).12 These polyimides exhibited high thermal stability and lower LC temperatures compared to the corresponding polyimides con- taining alkylene or ethylene spacer units.\n\nIn this report, we describe the extensive synthesis of novel LC polyimides derived from pyromellitic dianhydride (PMDA) or BPDA with diamines containing siloxane spacer units and their thermotropic LC behavior in detail. We have demonstrated two approaches for decreasing the crystal-LC transition tempera- tures of LC polyimides. One is the further extension of the length of the siloxane units and/or alkyl chains. The other involves twisting the imide planes of mesogenic units by the ortho- substituted methyl group, leading to a weakening of the inter- molecular interaction of the imide planes. The relationship between molecular designs and LC behavior is discussed in detail.\n\n\\begin{title}\nResults and Discussion\n\\end{title}\n\nSynthesis of Diamines and Polyimides. The diamine mono- mers containing siloxane linkages (3a-3e) were synthesized under the standard conditions for Williamson’s ether syn- thesis, hydrosilylation, and reduction, as shown in Scheme 2. The reaction of 4-nitrophenol or 3-methyl-4-nitrophenol with 4-bromo-1-butene or 6-bromo-1-hexene yielded 1a- 1c in the presence of potassium carbonate in acetonitrile. The hydrosilylation of compound 1a, 1b, or 1c with 1,1,3,3- tetramethyldisiloxane, 1,1,3,3,5,5-hexamethyltrisiloxane, or 1,1,3,3,5,5,7,7-octamethyltetrasiloxane in the presence of Karstedt’s catalyst gave compound 2. Analytically pure compounds were obtained in good yields (65-97%) after purification, which were hydrogenated to prepare monomer diamines 3.\n\n\\begin{title}\n806 Macromolecules, Vol. 43, No. 2, 2010\n\\end{title}\n\nFigure 1 shows the 1H and 13C NMR spectra for diamine 3b in CDCl3. The signal positions in the 1H NMR spec- trum of 3b are consistent with the proposed structures. The signals at 6.74 and 6.63 ppm can be assigned to the aromatic protons. Furthermore, the methyl protons adjacent to the silyl methyl groups appeared at 0.07 and 0.02 ppm. Similarly, the 13C NMR spectrum shows the expected ten signals.\n\nThe LC polyimides 6 showing in Scheme 3 were prepared by using a two-step polycondensation procedure. PMDA (4a) or BPDA (4b) reacted with each diamine 3 at room temperature in N-methylpyrrolidone (NMP) to produce poly(amic acid)s (PAAs) 5 with high inherent viscosities in the range of 0.65-1.73 dL/g (Table 1). Then, polyimide films were obtained by thermal imidization of the PAAs cast on glass substrates under nitrogen, followed by immersion in warm water. In the representative FT-IR spectrum of pre- pared polyimide 6h, the peaks for the amic acid groups disappeared and the characteristic imide peaks at 1770 (CdO asymmetric stretching), 1712 (CdO symmetric stretching), and 1389 cm-1 (C-N stretching) appeared, indicating complete imidization. In addition, strong absorp- tion bands were also observed at 2958 and 1257 cm-1, corresponding to C-H stretching of the alkyl groups and Si-C stretching of the siloxane groups, respectively, which further confirms the structures of the polyimides.\n\nThermal Properties. Analyses by TGA under nitrogen indicate that all polyimides 6 are thermally stable up to 400 C (Table 1). The DSC curves of all polyimides 6b-6j are shown in Figure 2. Except for polyimides 6d, 6e, and 6j,\n\n\\begin{caption}\nScheme 1. Structure of Polyimides with Siloxane Spacers\n\\end{caption}\n\n\\begin{molecule}\nCOCCCC[Si](C)(C)O[Si](C)(C)CCCCOc1ccc(N2C(=O)c3ccc(-c4ccc5c(c4)C(=O)N(c4ccc(C)cc4)C5=O)cc3C2=O)cc1\n\\end{molecule}\n\n\\begin{caption}\nScheme 2. Synthetic Routes of Monomers and Diamines 3\n\\end{caption}\n\n\\begin{molecule}\n*C1C(*)=CC(O)=CC=10:R3:NO2\n\\end{molecule}\n\n\\begin{molecule}\n*c1ccc(OCCC=C)cc1*0:NO212:R\n\\end{molecule}\n\n\\begin{molecule}\nC=CCCBr\n\\end{molecule}\n\n\\begin{molecule}\n[N+](=O)([O-])c1ccc(O)cc1\n\\end{molecule}\n\n\\begin{molecule}\n[N+](=O)([O-])c1ccc(OCCCCC=C)cc1\n\\end{molecule}\n\n\\begin{molecule}\nC=CCCCCBr\n\\end{molecule}\n\n\\begin{molecule}\n[SiH](C)(C)O[SiH](C)C\n\\end{molecule}\n\n\\begin{molecule}\n*C1=CC=C(O*[Si](O[Si](*OC2=CC=C([N+](=O)[O-])C(*)=C2)(C)C)(C)C)C=C1*0:NO26:CH[2]?m10:CH[2]?n20:R28:R\n\\end{molecule}\n\n\\begin{molecule}\nNC1C(*)=CC(O*[Si](O[Si](C*OC2C=C(*)C(N)=CC=2)(C)C)(C)C)=CC=13:R7:CH[2]?m12:CH[2]?m17:R\n\\end{molecule}\n\nall polyimides show more than two exothermic peaks upon cooling. Birefringence and fluidity were observed in the temperature range between these peaks by cross-polarizing microscopy. Therefore, the phase between the transition temperatures corresponds to a liquid crystalline phase. Compared with polyimides 6c and 6h, polyimide 6c has higher crystalline-LC transition temperatures than poly- imide 6h because the aromatic and imide rings in the mesogenic units of polyimide 6c are coplanar to one another, therefore the intermolecular interactions are stronger be- tween each mesogenic unit than those of polyimide 6h. As a result, polyimides 6a-c and 6f-h show lower crystalline-LC transition temperatures, 257 (6b), 214 (6c), 236 (6f), 236 (6g), and 203 C (6h) on the second cooling by increasing the siloxane units because of the increasing flexibility of the main chains (Table 2, Figure 3). Moreover, we investigated poly- imides 6d and 6i with longer methylene spacer units, which are expected to decrease the transition temperatures. How- ever, there is no noticeable change in the temperatures observed by DSC, which suggests that the methylene units are less flexible than siloxane due to the gauche or trans conformational limitations and are therefore ineffective in decreasing the crystal-LC transition temperature. Interest- ingly, in the case of polyimides 6b-d, the temperature range of LC behavior narrows as the spacer units become longer and, finally, polyimide 6d, which has the longest spacer unit among 6b-d, does not exhibit liquid crystallinity at all. On the other hand, polyimides 6e and 6j, with a methyl- substituted group in the mesogenic units, have also been designed to decrease transition temperatures. We expected that the twisted plane in the mesogenic units by the bulkiness of the methyl-substituted group weakened the intermolecu- lar interaction, which led to a decrease in their transition temperatures. However, neither polyimide 6e or 6j show liquid crystallinity, but instead polyimides 6e and 6j exhibit a crystaline and an amorphous nature, respectively, by DSC trace and polarized optical microscopy (POM).\n\n\\begin{molecule}\nC[Si](C)(CCCCOc1ccc(N)cc1)O[Si](C)(C)O[Si](C)(C)CCCCOc1ccc(N)cc1\n\\end{molecule}\n\n\\begin{molecule}\nC[Si](C)(CCCCOc1ccc(N)cc1)O[Si](C)(C)O[Si](C)(C)CCCCOc1ccc(N)cc1\n\\end{molecule}\n\n\\begin{legend}\n(B)\n\\end{legend}\n\n\\begin{caption}\nFigure 1. (A) 1H and (B) 13C NMR spectra of the diamine 3b.\n\\end{caption}\n\n\\begin{caption}\nScheme 3. Synthetic Routes of LC Polyimides 6\n\\end{caption}\n\n\\begin{molecule}\nO=C1OC(=O)*2C(=O)OC(=O)*125:Ar11:Ar\n\\end{molecule}\n\n\\begin{molecule}\nNC1C(*)=CC(OC*[Si](O[Si](C*OC2C=C(*)C(N)=CC=2)(C)C)(C)C)=CC=13:R8:CH[2]?m13:CH[2]?m18:R\n\\end{molecule}\n\n\\begin{molecule}\nCc1cc(C)c(C)cc1C\n\\end{molecule}\n\n\\begin{molecule}\nC1(=CC(*)=C(NC(=O)*(C(=O)O)(*)C(=O)O)C=C1)*.C1C(OC*[Si](C)(C)*[Si](C)(C)CCO*)=CC=C(NC(=O)*(C(=O)O)(*)*)C=1*3:R8:Ar12:COOH18:23:CH[2]?m27:CH[2]?n34:41:Ar45:COOH46:COOH48:R\n\\end{molecule}\n\n\\begin{molecule}\nC1C(*)=CC=C(N2C(=O)C(*C(=O)N(C3=CC=C(OC*O[Si](*)(*)*O*)C=C3*)C(=O)C)C2=O)C=1*2:10:Ar20:CH[2]?m23:24:25:CH[2]?n27:30:R37:R\n\\end{molecule}\n\nThermotropic LC Behavior. Figure 4 shows the optical microscopic texture observed for the mesophase of poly- imide 6h. The clear fan-shaped texture observed here is assigned to smectic LC phase. A similar texture was observed in the mesophases of poyimides 6b, 6c, 6f, 6h, and 6i. In order to identify the smectic structure, wide-angle X-ray diffrac- tion (WAXD) measurements were performed for fibers spun from the isotropic melt. The typical X-ray patterns are shown in Figure 5, as observed for 6g, which forms two LC phases. For the higher-temperature LC phase, sharp inner reflections are observed on the equator, i.e., along the fiber axis, and broad outer reflections are observed on the mer- idian (see Figure 5a). These profiles clearly show the forma- tion of the SmA phase.14 On cooling to a lower-temperature LC phase, the inner reflections are evidently split while the outer broad pattern is not significantly altered (Figure 5b), showing the transformation from the SmA to the SmC phase. The tilt angle of the molecules of the layer are elucidated as 22 from the splitting angle, which roughly\n\n\\begin{molecule}\nCc1ccc(-c2ccc(C)c(C)c2)cc1C\n\\end{molecule}\n\n\\begin{caption}\nTable 1. Polymerization Results and Thermal Stabilities\n\\end{caption}\n\n\\begin{molecule}\nC1C(*)=CC(*)=C(N2C(=O)C(*)N(C(=O)C)C(=O)C2C(=O)N(C(=O)*)C2=CC=C(O*[Si](C)(C)O[Si](C)(C)CCO*)C=C2*)C=12:5:R11:Ar24:R30:CH[2]?m41:44:R\n\\end{molecule}\n\n\\begin{table}\n| polymer | Ar | R | m | n | Vinh dL/g] | T d1% ( | Td5% [C(b |\n|:----------|:-----|:------|:----|:----|:-------------|:----------|:------------|\n| 6a | 4a | H | 4 | 1 | 0.72 | 399 | 454 |\n| 6b | 4a | H | 4 | 2 | 0.73 | 426 | 456 |\n| 6c | 4a | H | 4 | 3 | 0.66 | 415 | 455 |\n| 6d | 4a | H | 6 | 3r$ | 0.79 | 428 | 454 |\n| 6e | 4a | $CH3$ | 4 | 3 | 0.65 | 424 | 451 |\n| 6f | 4b | H | 4 | 1 | 1.07 | 407 | 448 |\n| 6g | 4b | H | 4 | $2$ | 1.73 | 426 | 460 |\n| 6h | 4b | H | 4 | 3 | 1.43 | 430 | 457 |\n| 6i | 4b | H | 6 | 3 | 1.19 | 406 | 447 |\n| 6j | 4b | CH3 | 4 | 3 | 0.78 | 408 | 452 |\n\\end{table}\n\na Inherent viscosities were measured at 30 C in NMP at a PAA 5 concentration of 0.5 g/dL. b Decomposition temperature. Td1%: 1% weight loss temperature, Td5%: 5% weight loss temperature in the nitrogen atmosphere.\n\ncorresponds to 24 calculated from the layer spacing ratio of the SmA to the SmC phase. Polyimide 6h also shows a similar SmA-SmC transformation, while 6b, 6c, 6f, and 6j form a single SmA phase before crystallization.\n\nThe present polyimides consist of three components, the aromatic, methylene and siloxane groups so the SmA struc- ture can be illustrated as a microsegregation structure of three components (Figure 6). Referring to this structure, we compared the SmA layer spacings between homologous polyimides. Of interest is that the layer spacing of the SmA phase, i.e., the average length of the repeating unit, does not change significantly as the number of the siloxane units in the homologous series increases. For example, the layer spacings of SmA for 6f, 6g, and 6h are 36.2, 36.1, and 35.9 A˚ , respectively, showing no expansion of layer spacing with an increase of two siloxane units (Table 2).15 From a comparison of 6h and 6i, however, the SmA layer spacing increases from 35.9 to 39.1 A˚ ; an increase of four methylene units causes a 3.2 A˚ increase in layer spacing. Thus, it can be concluded that the alkylene parts in the flexible spacer take a relatively extended shape, conforming similarly to the orien- tational order of the LC, as in the usual case of main-chain LC polymers,14 while the siloxane parts are not extended at all. In other words, the cross sectional area of the siloxane\n\nmicrodomain should be increased to a significant extent, which spontaneously leads to the unusually large cross sectional areas of the alkylene and mesogenic microdomains. In fact, this trend can be found to express on the spacing of the broad reflection that corresponds to the averaged lateral distance of polymers. In Figure 7, 2θ intensity profiles on the equator obtained in the SmA phases of 6f, 6g, 6h, and 6i are shown. From these intensity profiles, one can find that the peak position of the outer broad reflections gradually shifts from 5.5 to 6.4 A˚ with an increase in siloxane units.\n\n\\begin{caption}\nFigure 2. DSC heating and cooling curves of polyimides 6 by the measurement performed at a scanning rate of 10 C/min.\n\\end{caption}\n\n\\begin{molecule}\nCOCCCC[Si](C)(C)O[Si](C)(C)CCCCOc1ccc(-n2c(=O)c3cc4c(=O)n(-c5ccc(C)cc5)c(=O)c4cc3c2=O)cc1\n\\end{molecule}\n\n\\begin{caption}\nFigure 3. Plots of phase transition temperatures of polyimides 6 on the second cooling.\n\\end{caption}\n\n\\begin{legend}\n6f\n\\end{legend}\n\n\\begin{legend}\n6j\n\\end{legend}\n\nThese values are considerably larger than the 4.8 A˚ observed in the analogous polyimide BPDA/6OE, consisting of a BPDA mesogen and polyoxyethylene spacer with 6 oxyethy- lene units.16 Furthermore, of interest is that the outer broad reflection profile seems to have two maximum peaks in the SmA phases in 6b and 6c. The corresponding spacings are\n\n\\begin{caption}\nTable 2. Thermal Transition Temperatures of Polyimides 6\n\\end{caption}\n\n\\begin{table}\n| polymer | rAr | R | m | n | c-1c$ C]$ | Tic-1c (C]d | Tic- ([C]d | dc1 [A] | d1c2 [A] |\n|:----------|:------|:-----|:----|:----|:------------|:--------------|:-------------|:----------|:-----------|\n| 6a | 4a | H | 1 | 4 | b | b | b | | |\n| 6b | 4a | H | 2 | 4 | 257 | c | 300 | | 30.8 |\n| 6c | 4a | H | 3 | 4 | 214 | c | 231 | | 32.7 |\n| 6d | 4a | H | 3 | 6 | d | d | d | | |\n| 6e | 4a | CH3$ | 3 | 4 | e | e | e | | |\n| 6f | 4b | H | 1 | 4 | 236 | c | 325 | | 36.2 |\n| 6g | 4b | H | 2 | 4 | 236 | 262 | 297 | 34.7 | 36.1 |\n| 6h | 4b | H | | 4 | 203 | 216 | 254 | 32.6 | 35.9 |\n| 6i | 4b | H | | 6 | 211 | 219 | 265 | | 39.1 |\n| 6j | 4b | CH3 | 2 | 4 | e | e | e | | |\n\\end{table}\n\na Peak-top temperatures determined by DSC at a second cooling rate of 10 C/min. Tcr-lc: crystal-LC transition temperature, Tlc-lc: LC-LC transition temperature, Tlc-i: LC-isotropic transition temperature. b No data because of a too high transition temperature (>330 C) by POM. c No detection of LC-LC transition temperature. d There is no LC phase. Tcr-i = 258 [ C] at a second cooling. e Crystalline polyimide 6e. Tg = 79 [ C], Tc = 117 [ C], and Tm = 179 [ C] at a second heating. Amorphous polyimide 6j. Tg = 91 [ C]. Tg: glass transition temperature, Tc: crystallization temperature, Tm: melting temperature.\n\n\\begin{caption}\nFigure 4. Polarized optical microscopic texture observed for SmA of polyimide 6h at 245 C.\n\\end{caption}\n\n\\begin{molecule}\nCOCCCC[Si](C)(C)O[Si](C)(C)CCCCOc1ccc(N2C(=O)c3ccc(-c4ccc5c(c4)C(=O)N(c4ccc(C)cc4)C5=O)cc3C2=O)cc1\n\\end{molecule}\n\n\\begin{legend}\n(a)SmA\n\\end{legend}\n\n\\begin{caption}\nFigure 5. Wide angle X-ray diffraction patterns of (a) SmA and (b) SmC phases observed in the fiber samples of 6g. To show the smectic layer reflection, the small angle region is enlarged in the lower photographs. Fiber axis is set in a vertical direction.\n\\end{caption}\n\n\\begin{caption}\nFigure 6. Schematic illustration of SmA layer structure in which aro- matic, methylene, and siloxane groups are segregated to form sublayers.\n\\end{caption}\n\n\\begin{molecule}\n*C1C=CC(N2C(=O)C3C(=CC=C(C=3)C3C=C4C(N(C(=O)C4=CC=3)C3C=CC(OCCOC(=O)C)=CC=3)=O)C2=O)=CC=10:\n\\end{molecule}\n\n\\begin{legend}\nBPDA/6OE\n\\end{legend}\n\n\\begin{caption}\nFigure 7. 2θ intensity profiles of outer broad reflections for fiber SmA samples of 6b, 6c, 6h, 6i, 6g, and 6f. As a reference, the profile observed for the SmA of BPDA/6OE without polysiloxane spacer (refer to the text) is shown. The arrow indicates the peak position of 4.5 A˚ -1 normally observed in the LC phases of main-chain polymers.\n\\end{caption}\n\n\\begin{legend}\n(b) SmC\n\\end{legend}\n\n7.3 and 5.3 A˚ for 6c. Such an appearance of two outer broad reflections has been observed in similar main-chain polymers including the siloxane spacer,15 and suggests the biaxiality of SmA.17 Thus, the present polymers including the siloxane unit show some abnormality in their smectic structure formation, which will be analyzed in a future study.\n\nIn the course of this study, it was found that all transition temperatures of polyimides 6 became much lower simply by increasing the siloxane units. LC polymers with shorter flexible spacer units are desirable to achieve high thermal conductivity for IC applications. Therefore, the siloxane units indicated the superiority of the alkylene chains for decreasing the transition temperatures and the obtained polyimides are candidates as high thermal conductive polymers.\n\n\\begin{title}\nConclusions\n\\end{title}\n\nWe have synthesized a new series of LC semialiphatic poly- imides containing siloxane spacer units. They showed higher thermal stabilities (Td5%>∼450 C) and lower crystal-LC transition temperatures, 275 (6b), 237 (6c), 253 (6f), 250 (6g), and 222 C (6h), compared to polyimides containing alkylene or oxyethylene spacer units. The transition temperature decreased by the increasing siloxane spacer units, as expected. On the other hand, the methyl-substituted polyimides aiming at twisting the coplanar imide rings and loosening the packing of the mesogens did not show liquid crystallinity, unfortunately. WAXD experi- ments confirmed the layered morphologies of LCpolyimides with siloxane spacer units and their d-spacings. A smectic-A phase was formed in the polyimides derived from PMDA, while the poly- imides based on BPDA formed a smectic-C phase as well as a smectic-A phase. Moreover, the layer spacings of SmA indicated that the alkylene chains in the flexible spacer take a relatively extended conformation, while the siloxane units are not extended at all. From 2θ intensity profiles, the peak position of the outer broad reflections gradually shifts from 5.5 to 6.4 A˚ with an increase of siloxane units. Further, there is the possibility that the biaxiality in the polyimides is derived from PMDA. A detailed investigation of this interesting abnormality is in progress. We also expect that these polyimides will exhibit relatively high thermal conductivity combining with a small amount of thermal conducting fillers and may possibly be used as insulators in electronics fields.\n\n\\begin{title}\nExperimental Section\n\\end{title}\n\nMeasurements. FT-IR spectra were measured on a Horiba FT-720 spectrometer. 1H and 13C NMR spectra were recorded with a Bruker DPX300S spectrometer. Inherent viscosities were measured at 30 C in NMP at a polymer concentration of 0.5 g/ dL. The transition characteristics were surveyed with a polariz- ing microscope (OLYMPUS BX51), together with the use of a LINKAM LTS-350 hot-stage equipped with a temperature controller by setting a polyimide film between crossed polarizers. Thermal analysis was performed on a Seiko EX- STAR 6000 TG/DTA 6300 thermal analyzer at a heating rate of 10 C/min for thermogravimetry (TG) and a Perkin- Elmer DSC7 calorimeter connected to a cooling system at a heating rate of 10 C/min for differential scanning calorimetry (DSC). WAXD measurements were performed at ambient temperature by using a Rigaku-Denki RINT-2500 X-ray gen- erator with monochromic Cu KR radiation (40 kV, 50 mA) from graphite crystal of monochromator and flat-plate type of ima- ging plate.\n\nMaterials. PMDA and BPDA were purified by sublimation prior to use. NMP, acetonitrile and toluene were purified by distillation. Other reagents and solvents were obtained commer- cially and used as received.\n\n\\begin{title}\n810 Macromolecules, Vol. 43, No. 2, 2010\n\\end{title}\n\nGeneral Synthesis for Diamines. The diamine monomers containing siloxane linkages (3a-3e) were synthesized under the standard conditions for Williamson’s ether synthesis, hydro- silylation, and reduction. As a typical experiment, the synthesis of diamine 3a was described as follows. Detailed synthesis and characterization of other diamines (3b-3e) are described in Supporting Information.\n\nSynthesis of 4-(3-Butenyloxy)nitrobenzene (1a). The title com- pound, 1a, was synthesized according to the literature.13 To a solution of 4-nitrophenol (0.423 g, 3.04 mmol) and K2CO3 (1.11 g, 8.02 mmol) in CH3CN (20 mL) was added 4-bromo- 1-butene (0.827 g, 6.13 mmol), and the mixture was refluxed for overnight. The solution was filtered through Celite and the filtrate was concentrated under reduced pressure. The residue was dissolved in CH2Cl2, washed with water, dried over MgSO4, and the solvent was removed under reduced pressure to give a 1a yellow residue, which was flash-chromatographed to give 1a (yellow oil, 0.57 g, 97% yield). IR (NaCl), ν (cm-1): 2942.8 (alkyl C-H), 1643.1 (CdC), 1592.9 (Ar C-C), 1508.1, 1334.5 (-NO2). 1H NMR (300 MHz, CDCl3, δ, ppm, 25 C): 8.20 (d, J = 9.3, ArH, 2H), 6.95 (d, J = 9.0, ArH, 2H), 5.96-5.82 (m, vinyl proton, 1H), 5.23-5.12 (m, vinyl proton, 2H), 4.11 (t, J = 6.6, -CH2-, 2H), 2.62-2.55 (m, -CH2-, 2H). 13C NMR (75 MHz, CDCl3, δ, ppm, 25 C): 164.1, 141.5, 133.7, 125.9, 117.7, 114.5, 68.1, 33.4.\n\nSynthesis of 1,3-Bis[4-(4-nitrophenoxy)butyl]-1,1,3,3-tetra- methyldisiloxane (2a). To a solution of 1a (0.519 g, 2.69 mmol) and 1,1,3,3-tetramethyldisiloxane (0.125 g, 0.934 mmol), in to- luene (3 mL), Karstedt’s catalyst (3 drops) (platinum divinyl- tetramethyldisiloxane complex in 2 wt % xylene) was added. The reactionmixture wasrefluxedunder nitrogenfor 24 h, thentoluene was removed under reduced pressure. The residue was chromato- graphed (hexanes: CH2Cl2, 6:4) to give 2a. The compound, 2a, (0.321 g, 65% yield) was then isolated as a pale yellow oil after the vacuum. IR (NaCl), ν (cm-1): 2950.6 (Alkyl C-H), 1592.9 (Ar C-C), 1515.8, 1338.4 (-NO2), 1265.1 (Si-C). 1H NMR (300 MHz, CDCl3, δ, ppm, 25 C): 8.19 (d, J = 9.0, ArH, 4H), 6.93 (d, J = 9.3, ArH, 4H), 4.04 (t, J = 6.3, -CH2-, 4H), 1.88-1.79 (m, -CH2-, 4H), 1.54-1.45 (m, -CH2-, 4H), 0.61-0.55 (m, -CH2-, 4H), 0.06 (s, Si-CH3, 12H). 13C NMR (75 MHz, CDCl3, δ, ppm, 25 C): 164.3, 141.4, 126.0, 114.5, 68.6, 32.5, 19.9, 18.1, 0.503. Anal. Calcd For C24H36N2: C, 55.36 ; H, 6.97 ; N, 5.38. Found: C, 55.10 ; H, 6.91 ; N, 5.23.\n\nSynthesis of 1,3-Bis[4-(4-aminophenoxy)butyl]-1,1,3,3-tetra- methyldisiloxane (3a). A mixture of nitro compound 2a (1.35 g, 2.60 mmol) and Pd/C (0.0393 g, 10 wt %) in EtOAc (10 mL) was stirred at room temperature for 2 days under hydrogen atmosphere by using a balloon. The solution was filtered through Celite and concentrated to give the diamine 3a (1.18 g, 98% yield) as a light brown oil. IR (NaCl), ν (cm-1): 3355.5 (N-H), 2950.6 (Alkyl C-H), 1623.8 (N-H), 1511.9 (Ar C-C), 1238.1 (Si-C). 1H NMR (300 MHz, CDCl3, δ, ppm, 25 C): 6.74 (d, J = 9.0, ArH, 4H), 6.63 (d, J = 9.0, ArH, 4H), 3.87 (t, J = 6.3, -CH2-, 4H), 3.40 (s, NH2, 4H), 1.80-1.71 (m, -CH2-, 4H), 1.54-1.42 (m, -CH2-, 4H), 0.61-0.53 (m, -CH2-, 4H), 0.05 (s, Si-CH3, 12H). 13C NMR (75 MHz,\n\nCDCl3, δ, ppm, 25 C): 152.5, 139.9, 116.5, 115.8, 68.4, 33.1, 20.0, 18.3, 0.510.\n\nGeneral Precedure for Polymer Synthesis. PMDA (4a) or BPDA (4b) was added to a solution of the diamines, 3, in NMP, and the solution was stirred at room temperature for 12 h. Then a poly(amic acid) solution (15 wt %) was casted on a glass substrate and the imidization was carried out by heating in steps on hot-plate, finally the temperature was increased to 200 C. Opaque yellow films, 6, were obtained. Detailed syn- thesis and characterization of individual polyimides are des- cribed in Supporting Information.\n\nAcknowledgment. The financial support from Mitsubishi Chemical Corporation is gratefully acknowledged.\n\nSupporting Information Available: Text giving experimental details about the synthesis and characterization of 1b-1c, 2b-2e, 3b-3e, and 6a-6j. This material is available free of charge via the Internet at http://pubs.acs.org.\n\n\\begin{title}\nReferences and Notes\n\\end{title}\n\n(1) Akatsuka, M.; Takezawa, Y. J. Appl. Polym. Sci. 2003, 89, 2464– 2467.\n\n(2) Osada, K.; Niwano, H.; Tokita, M.; Kawauchi, S.; Watanabe, J. Macromolecules 2000, 33, 7420–7425.\n\n(3) Patil, H. P.; Lentz, D. M.; Hedden, R. C. Macromolecules 2009, 42, 3525–3531.\n\n(4) Kato, T.; Nagahara, T.; Agari, Y.; Ochi, M. J. Appl. Polym. Sci. 2007, 104, 3453–3458.\n\n(5) Harada, M.; Ochi, M.; Tobita, M.; Kimura, T.; Ishigaki, T.; Shimayama, N.; Aoki, H. J. Polym. Sci., Part B: Polym. Phys. 2003, 41, 1739–1743.\n\n(6) Bessonov, M. I.; Koton, M. M.; Kudryavstev, V. V.; Laius, L. A. In Polyimides: Thermally Stable Polymers; Consultants Bureau: New York, 1987.\n\n(7) Wilson, D.; Stenzenberger, H. D.; Hergenrother, P. Polyimides: Blackie: New York, 1990.\n\n(8) Inoue, T.; Kakimoto, M.; Imai, Y.; Watanabe, J. Macromol. Chem. Phys. 1997, 198, 519–530.\n\n(9) Kaneko, T. I.; Imamura, K.; Watanabe, J. Macromolecules 1997, 30, 4244–4246.\n\n(10) Huang, H. W.; Kaneko, T. I.; Horie, K.; Watanabe, J. Polymer 1999, 40, 3821–3828.\n\n(11) Coatat, G.; Eastmond, G. C.; Fairclough, J. P. A.; Paprotny, J.; Ryan, A. J.; Stagnaro, P. Macromolecules 2008, 41, 1034–1040.\n\n(12) Shoji, Y.; Higashihara, T.; Watanabe, J.; Ueda, M. Chem. Lett. 2009, 38, 716–717.\n\n(13) Lipshutz, B. H.; Ghorai, S.; Boskovic, Z. V. Tetrahedron 2008, 64, 6949–6954.\n\n(14) Watanabe, J.; Hayashi, M. Macromolecules 1988, 21, 278.\n\n(15) Braun, F.; Willner, L.; Hess, M.; Kosfeld, R. Makromol. Chem. 1990, 191, 1775.\n\n(16) We synthesized LC polyimide with 6 oxyethylene units (BPDA/ 6OE) according to the previous report (n = 6) (see ref 11). Inherent viscosity was 1.04 dL/g. Transition temperatures of BPDA/6OE were determined to be Tcr-lc=239 C and Tlc-i=282 C on the second heating.\n\n(17) Chandrasekhar, S.; Nair, G. G.; Rao, S. D.S.; Prasad, S.; Krishna, P. K.; Blunk, D. Liq. Cryst. 1998, 24, 67.\n\n" + }, + { + "abbreviations": [ + { + "abbreviation": "PMDA" + }, + { + "abbreviation": "ODA" + } + ], + "csv": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/label_data/10.1021/ma401361w.csv", + "golden_label": [ + { + "abbreviation": "PMDA", + "full_name": "pyromellitic dianhydride", + "smiles": "O=c1oc(=O)c2cc3c(=O)oc(=O)c3cc12" + }, + { + "abbreviation": "ODA", + "full_name": "4,4'-oxydianiline", + "smiles": "Nc1ccc(Oc2ccc(N)cc2)cc1" + } + ], + "path": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/pdf_data/10.1021/ma401361w_uniparser.json", + "pdf": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/pdf_data/10.1021/ma401361w.pdf", + "text": "\\begin{title}\nReal-Time Characterization of Physical Changes in Polyimide Film Formation: From Casting to Imidization\n\\end{title}\n\nEmre Unsal and Miko Cakmak*\n\nInstitute of Polymer Engineering, University of Akron, Akron Ohio 44325-0301, United States\n\nABSTRACT: Drying and imidization of PMDA−ODA solutions in NMP were investigated by a novel custom designed measurement system that tracks real time weight, thickness, surface temperature, and in-plane and out-of-plane birefringence. At low temperature drying stage, the weight and thickness reductions occurred rapidly as a result of solvent evaporation. All the parameters started leveling offwhile the out of plane birefringence steadily increased and reached a plateau at longer drying times. When the temperature was increased for imidization reaction, additional weight loss accom- panied by temporary reduction of birefringence was observed due to\n\nevaporation of bound solvent as solvent molecules decomplexed from the polymer chains and plasticized the film. During the latter stage, out-of-plane birefringence rose rapidly due to increased intrinsic birefringence of the polymer chains due to imidization reaction and orientation of polymer chains with their chain axes preferentially oriented in the film plane. Throughout the whole process the in-plane birefringence remained zero. For the first time, these real time measurements allowed us to quantitatively show the dynamics between chain relaxation due to evaporation of the decomplexed solvent molecules, and orientation development due to decreased chain mobility caused by imidization reaction and increasing Tg for the PMDA− ODA/NMP solutions. In addition, the dynamics of this interplay was investigated by varying the processing conditions: initial casting thickness and drying temperature.\n\n\\begin{title}\n1. INTRODUCTION\n\\end{title}\n\nPolyimide films exhibit good thermal stability, high mechanical strength and chemical resistance. These properties allow their use in harsh industrial applications including automotive, aerospace and electronics.1−6 Common polyimides are not soluble in solvents and they degrade when heated due to their high Tg. Because of these restrictions, a two step process was developed to produce high quality polyimide films.7−11 First, a precursor polyamic acid (PAA) is synthesized that is soluble in polar, high boiling point solvents such as NMP (N-methyl-2- pyrrolidone), DMAc (dimethylacetamide), and DMF (dime- thylformamide).12 In the second step, PAA is converted to polyimide through thermal imidization.10,13,14 This part of the process can be divided into three sections; (i) solution casting of polyamic acid precursor on to a substrate via blade coating or slot die casting, (ii) drying of precursor to form partially dried film, and (iii) thermal treatment to form polyimide film.15−17 The critical temperatures for the thermal imidization are 120 °C where imidization reaction starts and 150 °C where the rate of conversion is the fastest.18 As the temperature reaches 200 °C, 90% of conversion is achieved. 100% conversion is reached at higher temperatures, typically 300−450 °C range depending on the chemical structure.13\n\nDuring the multistep imidization process, solvent evapo- ration, polymer chain orientation, chemical conversion, and water loss due to the chemical reaction all take place concurrently.19−21 Because of these changes, films experience weight loss, thickness reduction, temperature change, change in rate of diffusion for solvent molecules and change in chain\n\nmobility leading to birefringence development (Figure 1). It is very difficult to predict the effect of each processing step on the final properties due to the simultaneously changing physical and chemical parameters that are interrelated. The majority of characterization for the polyimide films has been performed on the samples that were already imidized after all these events have taken place.22−29 These offline characterization measure- ments provided valuable information on final properties that develop as a result of complex events. However, little is known about these sequences of structural/mechanistic details that occur during the course of imidization process.\n\nFor high quality thin polyimide film production, a stepwise increase in temperature is preferred. The cast solution is first dried at temperatures below 120 °C to form PAA film followed by imidization reaction at higher temperatures. It was found that, PAA films that are dried at low temperatures contain 30%−50% bound solvent.30,31 Model compound studies for these PAA-solvent systems have revealed that the PAA molecules form complexes with the polar solvent molecules via hydrogen bonding.18,30−35 There are four potential sites that can participate in hydrogen bonding on the backbone of the PAA chains, consisting of two carboxylic acid groups and two amide groups. The binding energies for these groups are different, which creates the formation of two distinct solvent complexes with different thermal stabilities. It was reported the\n\nReceived: July 1, 2013\n\nRevised: October 10, 2013\n\n\\begin{molecule}\n*n1c(=O)c2cc3c(=O)n(-c4ccc(Oc5ccc(*)cc5)cc4)c(=O)c3cc2c1=O\n\\end{molecule}\n\n\\begin{caption}\nFigure 1. Roll-to-roll polyimide film process and physical and chemical changes during the process.\n\\end{caption}\n\nformation of 4:1 (solvent:PAA repeat unit) and 2:1 (solvent:PAA repeat unit) complexes depending on the processing conditions, such as casting thickness and drying temperature.32,33\n\nThe presence of bound solvent plays a critical role during the imidization reaction.31,36 After drying and formation of PAA solid-like structure with high solvent content, the film is heated to imidization temperature and the bound solvent starts to decomplex from the carboxylic acid and amide groups. The solvent molecules bonded to amide groups are released earlier due to lower bonding energy compared to that of carboxylic acid group which is a better proton donor.32,33 The release of the solvent molecules has several effects. First, it plasticizes the film, causing PAA chains to relax. Second, due to release of the solvent molecules, the active carboxylic acid and amide groups become free for imidization reaction to occur. Hence, decomplexation of these solvent molecules is the driving factor for the imidization reaction. The Tg of this highly viscous medium is much lower compared to that of a fully imidized film, and during the reaction, it changes with increasing degree of imidization and loss of solvent.37 Increase in Tg and formation of rigid imide groups decrease the chain mobility that causes the development of spontaneous molecular orientation parallel to the film surface during the process.38−45 This orientation development has significant influence on the final properties of films such as modulus, mechanical anisotropy, thermal expansion coefficient, and optical anisotropy as reflected in out-of-plane birefringence.46−50 The imidization conditions, such as imidization temperature, heating rate, and\n\ntime, also play an important role in the development of morphology and final properties of these films.51−55\n\nAnalysis of such a complex process and evaluation of final physical and chemical properties by off-line characterization techniques can be misleading as the later processes may hinder the details of the early steps. A comprehensive study of this multistep interrelated processes (formation of PAA−solvent complexes, decomplexation of the hydrogen-bonded solvent molecules and subsequent imidization reaction) is required for a complete understanding of the effects of processing conditions on the evolution of structural and mechanical anisotropy in polyimide films.\n\nIn this paper, we report a comprehensive study that investigates the real time dynamics of the imidization reaction, covering all the stages of this complex process from solution casting of polyamic acid to polyimide film formation. During this study a wind tunnel shaped highly instrumented drying station was used. This instrument is equipped with sensors to track real-time weight, thickness, surface temperature, and in- plane and out-of-plane birefringence during solution drying of polymer films.56 The polyamic acid conversion to polyimide was studied with all the physical changes monitored during the process and the effect of processing parameters on the structural development was investigated by varying the initial casting thickness and drying temperature for the first time.\n\n\\begin{title}\n2. EXPERIMENTAL SECTION\n\\end{title}\n\ni. Materials. Polyamic acid solution (PMDA−ODA, 15 wt % solids in NMP) was purchased from Sigma-Aldrich and used as received. The solution was cast on glass substrates using a motorized drawdown\n\n\\begin{caption}\nFigure 2. Wind tunnel shaped drying system.\n\\end{caption}\n\ncoater equipped with a commercial 3-in. wide casting blade. The cast solutions were 7 in. in length and 3 in. in width.\n\nii. Measurement System. The details of the measurement system (Figure 2) used in this experiment was reported elsewhere.56 In summary, it is a combination of a hot air blower, wind tunnel shaped frame and sensors for tracking physical changes. Hot air blower can operate at temperatures up to 500 °C and air speeds up to 4.5 m/s at the sample location. The direction of the air flow is shown by the red dashed lines. The blower is connected to the wind tunnel shaped drying tunnel. This shape provides a uniform air flow at the center of the tunnel where the drying sample and sensors are located.\n\nDrying sample and the sensor locations are shown in Figure 3. Polymer solution is cast on a glass substrate and placed on a sample platform that directly sits on a balance to measure the real-time weight\n\n\\begin{caption}\nFigure 3. Drying sample, sensors, and measurement locations.\n\\end{caption}\n\nof the drying solution. The sample thickness is measured by a combination of three laser displacement sensors. These lasers measure the displacement of the glass substrate top surface and the drying sample top surface at two locations (upstream of the air flow and mid section of the solution). By subtracting the two values, the thickness of the drying solution is calculated at two locations. Surface temperature of the drying solution is measured by four pyrometers that are located very close to the center of the drying solution.\n\nReal-time birefringence is measured by spectral birefringence method.57−75 The in-plane and out-of-plane birefringence is calculated by measuring the 0° and 45° retardation values. The optical light paths for these measurements are shown with yellow transparent tubes in the figure below.\n\nFor the in-plane and out-of-plane birefringence (Δn12and Δn23)- calculations Stein’s equations are used (eqs 1 and 2)76\n\n\\begin{equation}\n\\Delta n_{1 2}=\\frac{R_{0} ( t )} {d ( t )}\n\\end{equation}\n\n\\begin{token}\n(1)\n\\end{token}\n\n\\begin{equation}\n\\Delta n_{2 3}=-\\frac{1} {d ( t )} \\Biggl[ \\frac{R_{0} ( t ) \\,-\\, R_{\\phi} ( t ) \\sqrt{1 \\,-\\, \\frac{\\sin^{2} \\phi} {\\pi^{2}}}} {\\frac{\\sin^{2} \\phi} {\\pi^{2}}} \\Biggr]\n\\end{equation}\n\n\\begin{token}\n(2)\n\\end{token}\n\nwhere R0(t) is instantaneous 0° retardation, d(t) is the instantaneous thickness, RΦ(t) is retardation value at angle Φ (45° in this case), and n̅ is the average refractive index of the drying solution. The average refractive index was estimated from the weight change assuming no volume change during mixing. The real-time average refractive index was calculated using eq 3 below, where φ is the weight fraction. Refractive index of solvent was measured as 1.47 and the refractive index of polyimide was estimated 1.693 respectively by Abbé refractometer at 633 nm.39 The initial concentration of the solution was 15 wt % solid and refractive index of the solutions was 1.507. The refractive index of pure polyamic acid form of PMDA−ODA film could not be measured, as this material always forms complexes with the solvent molecules. If the temperature was increased to evaporate the solvent, the imidization reaction started and the material was no longer purely polyamic acid. Hence for this study, the refractive indices of polyamic acid and polyimide of PMDA−ODA were accepted as 1.72 at 633 nm.\n\n\\begin{equation}\n\\overline{{{n}}} \\,=\\, \\overline{{{n}}}_{s o l v e n t} \\phi_{s o l v e n t} \\,+\\, \\overline{{{n}}}_{s o l i d} \\varphi_{s o l i d}\n\\end{equation}\n\n\\begin{token}\n(3)\n\\end{token}\n\nWe recently showed the development of anisotropy through the thickness direction of solution cast polymer films experimentally by measuring the birefringence through thickness and refractive index values at both the air−solution interface and substrate−solution interface directly. Highly oriented skin layers on both air and substrate interface developed for poly(amide−imide)/DMAc solutions com- pared to the core during drying. It was observed that the use of average\n\nrefractive index value for the out-of-plane birefringence calculations caused only a 5% deviation from the actual birefringence values that were calculated directly from the developed gradient during drying.77\n\niii. Experimental Parameters. A typical industrial roll to roll polyimide film processing stages are illustrated in Figure 1.78−82 After the blade coating or slot die casting of the solution, it enters into drying zone. In this zone, the material is dried to remove the excess amount of high boiling point solvent. The temperature is kept below 120 °C where no imidization reaction takes place.\n\nWhen the film is sufficiently dried, it is separated from the carrier and passes through a transition zone. In this zone, the temperature starts to rise to imidization temperature, in the range 120−450 °C depending on the chemical structure and desired imidization degree. In this zone, the sample is constrained for dimensional stability to prevent shrinkage due to solvent loss and imidization reaction. After this stage it travels deeper into the imidization zone where the temperature is kept constant at higher values for imidization to complete and remove all the remaining bound solvent.\n\nOur real time measurement system is capable of applying all the conditions listed and measure the physical parameters changing during each stage of the industrial processing step. These measurements include real time weight, thickness, surface temperature, and in-plane and out-of-plane birefringence.\n\n\\begin{title}\n3. RESULTS\n\\end{title}\n\nTo experimentally simulate the actual imidization process, PAA/NMP solution was cast on glass substrate at room temperature, placed on top of the sample platform inside the preheated chamber and data acquisition was started. The sample was first dried for 4 h at low temperatures and then the temperature was increased to the imidization temperature, 200 °C for the next 4 h. The air speed was kept constant at 0.5 m/s during the experiment.\n\ni. Imidization Verification. To verify the chemical conversion, imidization of the PMDA−ODA samples were measured at different temperatures for 5 μm thick films. The solution cast polyamic acid films were kept in a vacuum oven at different temperatures for 60 min. The IR spectra of these samples were compared with the fully imidized film that was kept at 180 °C for 45 min and 350 °C for 60 min. Figure 4 shows the results calculated by eq 4, using the imide peak area (CN stretching) at 1380 cm−1, normalized with the aromatic ring stretching peak area at 1500 cm−1. This peak is not affected from the chemical change. This ratio was normalized with the ratio of the fully imidized film.\n\n\\begin{caption}\nFigure 4. Imidization degree of 5 μm PMDA−ODA films as a function of temperature. About 90% conversion is achieved at 200 °C.\n\\end{caption}\n\n\\begin{equation}\n\\mathrm{d e g r e e ~ o f ~ i m i d i z a t i o n}={\\frac{\\left( {\\frac{1 3 8 0 ~ \\mathrm{c m}^{-1} {\\tau}} {1 5 0 0 ~ \\mathrm{c m}^{-1} {\\tau}}} \\right)} {\\left( {\\frac{1 3 8 0 ~ \\mathrm{c m}^{-1} {\\tau}} {1 5 0 0 ~ \\mathrm{c m}^{-1} {\\tau}}} \\right)}}\n\\end{equation}\n\n\\begin{token}\n(4)\n\\end{token}\n\nThe graph shows, about 90% conversion is achieved at 200 °C, which is in good agreement with the literature.18,21,31,51,83\n\nii. Overview of the Process. As Figure 5 shows, the first 4 h of the experiment corresponds to solution casting and drying of the PAA solution (i), where the temperature was kept low to prevent imidization. In ensuing stage, the temperature was raised to 200 °C and we continued to track the physical parameters during this transition (II) into imidization (III) stages as the temperature was increased. During the drying stage (i), the weight and thickness values decreased rapidly due to solvent evaporation (Figure 6). This caused simultaneous solidification and shrinkage mainly in the thickness direction as the film is constrained in the x−y plane as it is adhered to the substrate. As the drying proceeds, the in-plane birefringence remains zero, indicating the preservation of in-plane isotropy. Beyond a critical drying stage, the out of plane birefringence starts to increase. This is affected by the a competition between the relaxation and reorientation of the polymer chains in the plane as the film is undergoing compression during drying.84−92 This competition is apparent in Figure 6. Initial sections of the drying were solvent rich, which indicates the relaxation times are shorter and both the in-plane and out-of-plane birefringence values remained very close to zero. As the drying proceeded (t ∼2000 s) the rate of weight and thickness loss started to level offwhile the onset of out-of-plane birefringence development was observed. At this point the sample can support stresses and the relaxation times increase. After 4 h, the evaporation of solvent substantially decreases. At this stage the partially dried sample contains about 30−40% solvent by weight.\n\nThe details of the transition zone, where the temperature is increased from 100 to 200 °C, is shown in Figure 7. As the temperature gradually increases, additional weight loss and thickness reduction is observed associated with the evaporation of the bound solvent. We also observe the temporary decrease of out of plane birefringence before beginning to increase again beyond 15000 s. This decrease is attributed to the plasticization effect of the decomplexed bound solvent, leading to relaxation. However, at a critical temperature value (∼150−160 °C), the rate of the imidization reaction increases sufficiently enough that decreases the chain mobility, as a result of the formation of rigid polyimide chains as well as increased Tg due to evaporation of bound solvent. At this point, out-of-plane birefringence increases at a higher rate as compared to the previous drying section that indicates the increase in the out-of- plane birefringence is a combination of two reasons. The first reason is the conversion of polyamic acid chains into more rigid polyimide chains with higher intrinsic birefringence. The second reason is the increasing chain orientation with chain axes parallel to the surface . The stress effect has minor role in this birefringence development. Weight loss indicates the continuation of the evaporation of the bound solvent and the evaporation of the water that is formed during the reaction. Transition zone clearly shows that the orientation development is a balance between the solvent evaporation induced relaxation and the continual orientation of polyimide chains parallel to the film surface as the chain mobility decreases due to imidization reaction and consequent increase in Tg.37,51−54,93\n\n\\begin{legend}\n回\n\\end{legend}\n\n\\begin{legend}\nⅢ \n\\end{legend}\n\n\\begin{caption}\nFigure 5. Whole imidization process with all regimes marked (i) drying regime, (ii) transition regime, and (iii) imidization regime.\n\\end{caption}\n\n\\begin{caption}\nFigure 6. Regime i drying zone.\n\\end{caption}\n\nThe final stage is shown in Figure 8. The weight, thickness and out-of-plane birefringence values start to level offas the evaporation of all the bound solvent. The leveling offof the out-of-plane birefringence also indicates the imidization reaction slows down significantly. The formation of high Tg polyimide molecules and the evaporation of almost all solvent and water molecule formed during the reaction rapidly decreases the chain mobility.\n\niii. Influence of Thickness. To ascertain its influence on drying behavior, we prepared films with 500, 250, and 100 μm casting thickness. In the first step the temperature was kept at 100 °C at 0.5 m/s air speed and the films were dried for 4 h. In the next 4 h, the temperature was increased to 200 °C to for the imidization reaction. At this temperature approximately 90% of the imidization has been achieved. Real-time data for weight, thickness, surface temperature and in-plane and out-of-plane birefringence values were measured during the process.\n\nAs expected (Figure 9, parts a and b) as the casting thickness decreases, weight loss occurs faster due to higher evaporation rate of the solvent as shorter path lengths the solvent molecules has to travel to reach the surface and evaporate. Figure 9c shows the section of the process where the temperature started to increase to imidization temperature of 200 °C. The temperature increase causes decomplexation of the bound solvent leading to additional weight loss mentioned earlier. The % weight losses for 500, 250, and 100 μm thick cast solutions are 21%, 26%, and 37%, respectively, between 13000 and 17000 s.\n\nThickness change during the initial stages of the process for different initial casting thicknesses are shown in Figure 10. Similar to weight loss, the rate of thickness loss is faster as the initial casting thickness decreases. When the temperature was increased to 200 °C for imidization reaction to take place, no clear change in the thickness values was observed for all\n\n\\begin{caption}\nFigure 7. Regime ii heating zone.\n\\end{caption}\n\n\\begin{caption}\nFigure 8. Regime iii imidization zone.\n\\end{caption}\n\nthicknesses (inset graph in Figure 10). However, since the weight loss (Figure 9) indicates the evaporation of solvent, the thickness values should decrease. Laser displacement sensors failed to detect the thickness change during the temperature increase, which is mainly due to the sensor sensitivity. The final thickness values for 500, 250, and 100 μm thick cast solutions were measured as 36, 21, and 10 μm respectively via off-line thickness gage after the process.\n\nOverall in-plane and out-of-plane birefringence development for all three thicknesses are shown in Figure 11a. During the process, the in-plane birefringence remained zero and out-of- plane birefringence increased with the decreasing initial casting thickness.\n\nInitial 5000 s of the process is shown in Figure 11b where the cast solutions were dried at 100 °C. This temperature is below the temperature range where little or no imidization occurs during drying. The development of the out-of-plane birefrin- gence is attributed mainly due to the shrinkage of the film in the thickness direction since it is constrained in the x−y plane\n\nof the glass substrate. The increase of birefringence values with decreasing thickness is attributed to the rapid reduction of relaxation rates with reduced initial thickness leading to increased overall orientation as the evaporation rate of the solvent decreases. (Figure 9 and Figure 10).\n\nFigure 11c shows the period where the set temperature is increased to 200 °C for imidization reaction to occur. The orientation in this section starts to decrease initially because of the plasticization effect of the decomplexed solvent molecules as temperature increases. However as the temperature continues to increase, the rate of imidization reaction increases that causes increase in the intrinsic birefringence and orientation of polymer chains parallel to the surface. This scheme is similar for all three thicknesses, with a slight delay in the 100 μm film. The reason for this delay might be the low content of the bound solvent in this sample. As mentioned earlier, the decomplexation process of the solvent assists in the imidization reaction in two ways, making the chains mobile and releasing the active groups that participate in the rigidifying\n\n\\begin{legend}\na\n\\end{legend}\n\n\\begin{legend}\nb\n\\end{legend}\n\n\\begin{caption}\nFigure 9. Effect of thickness on weight change during the process.\n\\end{caption}\n\n\\begin{caption}\nFigure 10. Effect of thickness on % thickness change during imidization.\n\\end{caption}\n\nimidization reaction. Since the 100 μm film possesses the lowest amount of solvent, the chain mobility is slightly lower in this system which might be the reason for the shift. The changes in the behavior for 500 and 250 μm samples occur nearly at the same time.\n\nSimilar to the drying behavior, the final birefringence value increases with decreasing thickness. All these observations are in good agreement with the literature.84−92\n\niv. Influence of Drying Temperature. It is possible to control the processing mechanisms and fine-tune the final properties of polyimide films by changing the drying temper- ature. The influence of drying temperature was investigated by using five different temperatures, 100, 120, 140, 160, and 200 °C for 4 h, followed by temperature increase to 200 °C for the next 4 h. Real-time data for weight, thickness, surface temperature, and in-plane and out-of-plane birefringence values were measured during the process. The experiment conditions are summarized at the Table 1.\n\n\\begin{legend}\nTime (s)\n\\end{legend}\n\n\\begin{legend}\nc\n\\end{legend}\n\nWeight change (%) during the overall process for different drying temperatures is shown in Figure 12. Figure 12-b focuses on the first 2000 s of the process where majority of the solvent evaporation took place. As expected, increasing the temperature leads to higher rate of weight loss. Also higher temperatures result in lower weight that indicates more solvent is removed from the medium at this stage. Figure 12-c focuses on the temperature increase region after 4 h of drying. All the samples that had different drying temperature were increased to 200 °C to finalize the imidization reaction. The weight loss on the 100 and 120 °C is apparent and the 140 °C, 160 °C, 200 °C samples does not exhibit this decrease which indicates the solvent evaporation took place at earlier stages at higher temperatures. The percent weight changes also indicated that the higher temperature drying results in the lower solvent content remaining in the films.\n\nThickness change during the initial stages of the process for different drying temperatures is shown in Figure 13. Similar to weight loss, the rate of thickness decrease is higher for the higher drying temperatures. Similar to previous observations, when the temperature was increased to 200 °C for imidization reaction to take place, no change in the thickness values was observed for different temperatures (inset graph in Figure 13). Since the weight loss (Figure 12) indicates the evaporation of solvent for the lowest two drying temperatures100 and 120 °C, the thickness values for these temperatures should also decrease slightly. Again, laser displacement sensors failed to detect the thickness change during this stage. The final thickness values for 100 °C, 120 °C, 140 °C, 160 and 200 °C were measured as 36 μm, 37 μm, 34 μm, 33 and 28 μm respectively via off-line thickness gage.\n\nIn-plane and out-of-plane birefringence developments for all drying temperatures are shown in Figure 14-a. Overall; the in- plane birefringence remained nearly zero for all samples and out-of-plane birefringence increased with the increasing drying temperature throughout the process.\n\n\\begin{legend}\nb\n\\end{legend}\n\n\\begin{caption}\nFigure 11. Effect of thickness on in-plane and out-of-plane birefringence behavior during imidization.\n\\end{caption}\n\n\\begin{caption}\nTable 1. Temperature Profiles Applied\n\\end{caption}\n\n\\begin{table}\n| name | drying temperature (4 h), C | imidization temperature (4 h), C |\n|:-----------|:------------------------------|:-----------------------------------|\n| PI-100/200 | 100 | 200 |\n| PI-120/200 | 120 | 200 |\n| PI-140/200 | 140 | 200 |\n| PI-160/200 | 160 | 200 |\n| PI-200/200 | 200 | 200 |\n\\end{table}\n\n\\begin{legend}\na\n\\end{legend}\n\n\\begin{legend}\nb\n\\end{legend}\n\n\\begin{caption}\nFigure 12. Effect of drying temperature on % weight change on imidization process.\n\\end{caption}\n\n\\begin{legend}\na\n\\end{legend}\n\n\\begin{legend}\nc\n\\end{legend}\n\n\\begin{legend}\nTime (s)\n\\end{legend}\n\n\\begin{legend}\n100\n\\end{legend}\n\n\\begin{legend}\nTime (s)\n\\end{legend}\n\nFigure 14-b shows the initial 5000 s of the process where the cast solutions were dried at different temperatures. The 100 °C sample is below the imidization temperature and 120 °C is the onset temperature for imidization reaction. The imidization reaction is fastest at150 °C, so 140 and 160 °C were selected because they were just above and below of this value. Continuous 200 °C was applied during the last experiment. The evaporation of solvent and simultaneous imidization\n\n\\begin{caption}\nFigure 13. Effect of drying temperature on % thickness change during imidization process.\n\\end{caption}\n\nreaction occurred at the same time for the samples dried at 140 °C, 160 and 200 °C. The development of the out-of-plane birefringence during this experiment had several reasons. The first one was the evaporation of the solvent, the second is the increasing intrinsic birefringence of the medium and the last one is the liquid crystalline like order for the rigid and semiflexible polymers in the concentrated solutions and solid films. This increase is induced by the orientation of the polymer chains parallel to the film surface as mentioned earlier.84−92 The final reason is the simultaneous imidization reaction for the temperatures higher than 120 °C. Both of these processes decreased the mobility of the polymer chains and the relaxation times were much higher as the drying temperature was increased and orientation behavior dominated.\n\nFigure 14-c shows the region where the set temperature was increased to 200 °C for imidization reaction to occur. For the 100 and 120 °C drying temperatures, the out-of-plane birefringence value initially decreased because of the plasti-\n\n\\begin{legend}\n0.10\n\\end{legend}\n\n\\begin{legend}\na\n\\end{legend}\n\n\\begin{legend}\nTime (s)\n\\end{legend}\n\n\\begin{legend}\nb\n\\end{legend}\n\n\\begin{caption}\nFigure 14. Effect of drying temperature on in-plane and out-of-plane birefringence development during imidiziation process.\n\\end{caption}\n\ncization effect due to the decomplexed solvent molecules. However as the temperature continued to increase, the rate of imidization increased and dominated the orientation develop- ment. The samples dried at 140 and 160 °C showed very small relaxations, indicating the evaporation of the majority of the solvent molecules took place earlier in the process and the evaporation of the remaining solvent was not enough to enhance enough chain mobility to decrease the orientation levels substantially, as seen on the lower drying temperatures (100 and 120 °C).\n\nSimilar to the drying behavior, the final birefringence value increased with increasing drying temperature. All these observations are in very good agreement with the litera- ture.84−92\n\n\\begin{title}\n4. DISCUSSION\n\\end{title}\n\nThe details of imidization process are summarized in Figure 15. At point a on the graph (t = 0 s) the dilute PAA solution includes both free and H-bonded solvent molecules. Between points a and b, rapid weight loss indicates the evaporation of the nonbonded free solvent molecules from the medium. At point b, the rate of weight loss becomes very small and evaporation decreases substantially. During this stage a drying front that separates the liquid region from the glassy region starts to enter into the birefringence measurement area in the direction of air flow. As more solvent evaporates, from point b to c, polymer solution solidifies and starts to support the stresses formed during drying. Drying front and the glassy region travels through the film and passes from the birefringence measurement area. At this stage the relaxation times are slowed down and as a result out-of-plane birefringence value continues to increase, indicating orientation of the PAA molecules parallel to the film surface. At point d, the polyamic acid film is formed that has substantial solvent\n\n\\begin{legend}\na\n\\end{legend}\n\n\\begin{legend}\nb\n\\end{legend}\n\n\\begin{caption}\nFigure 15. Overview of the process.\n\\end{caption}\n\ncontent in it. These solvent molecules form complexes with PAA chains. At this point, the Tg of the system increased to the ambient temperature due to evaporation of the nonbonded solvent and the chain mobility decreases considerably leading to leveling offof out-of-plane birefringence. The same critical phenomenon was observed during drying of transparent soluble polyimides.94 There is very little or no imidization up until this point. When the temperature is increased right after the point d, the bound solvent molecules start to decomplex from the PAA chains and travel through the thickness to the surface of the film and evaporate. The decomplexed solvent molecules spend some time in the medium as they travel and this reflects as a time lag on the weight loss. Traveling free solvent molecules and increasing temperature plasticize the environ- ment which result a decrease in the out-of-plane birefringence up until point e. At this point, the rate of the imidization reaction increases significantly because the evaporation of solvent increases the chain mobility and exposes the reactive ends for the imidization reaction. Carboxylic acid and amide groups become active as the decomplexation continues from the PAA chains. The rapid formation of the rigid polyimide chains and their orientation parallel to the film surface started to dominate the relaxation induced by the solvent evaporation and water formation due to the reaction. The rapid increase of out-of-plane birefringence during imidization was attributed to two main events, one is the increasing intrinsic birefringence of the medium due to chemical conversion and the second is the development of oriented layer formation with the preferential alignment of polymer chains in the plane of the film.28,40,78 It is clear from the graph that the imidization induced molecular orientation and solvent evaporation occurs simultaneously, because, while birefringence is increasing after point e, the weight continues to decrease slightly. At certain imidization conditions, it is apparent that the drying induced orientation is lost completely when the temperature is increased to imidization temperature. As the experiment reaches point f,\n\n\\begin{caption}\nRemoval of bound solvent with temperature increase causing weight loss and chain relaxation (acting as plasticizer), followed by imidization and orientation\n\\end{caption}\n\n\\begin{legend}\n≤`\n\\end{legend}\n\n\\begin{legend}\ne\n\\end{legend}\n\nthe weight loss and birefringence increase level offas the Tg increases and chain mobility diminishes. At point f, most of the solvent evaporated and the conversion to polyimide is about 90%.\n\n\\begin{title}\n5. CONCLUSIONS\n\\end{title}\n\nThe dynamic relationship between the relaxation and chain orientation has been observed real-time on the imidization process of PMDA−ODA/NMP solution. At low temperature drying stage (T < 120 °C), orientation occurs due to preferential orientation of polymer chains parallel in the plane of the film. At early stages of imidization (120 °C < T < 150 °C) temporary decrease of birefringence due to chain relaxation caused by the evaporation of the decomplexed solvent molecules was observed. At higher temperatures (T > 150 °C) optical anisotropy development dominates due to decreased chain mobility as a result of imidization reaction and increasing Tg.\n\nIt was shown how this competition between the two events was affected independently for each stage (drying, transition, and imidization) in the imidization process by changing the processing parameters. The level of orientation development, weight loss and solvent evaporation was affected by the changing processing conditions such as initial casting thickness and drying temperatures. This study showed that it is possible to fine-tune the final orientation level during the drying and imidization stages simply by changing the processing conditions without the necessity of postprocessing techniques.\n\n\\begin{title}\nINFORMATION\n\\end{title}\n\n\\begin{title}\nCorresponding Author\n\\end{title}\n\n*E-mail: (M.C.) cakmak1@uakron.edu.\n\n\\begin{title}\nNotes\n\\end{title}\n\n\\begin{title}\nThe authors declare no competing financial interest.\n\\end{title}\n\n\\begin{title}\nACKNOWLEDGMENTS\n\\end{title}\n\nFunding for this study was kindly provided by the State of Ohio Third Frontier program under the grant “Research and Commercialization of Polyimides”.\n\n\\begin{title}\nREFERENCES\n\\end{title}\n\n(1) St. Clair, A. K.; St. Clair, T. L. US Patent 4,603,061 1986.\n\n(2) St. Clair, A. K.; St. Clair, T. L.; Slemp, W.; Ezzell, K. S. Optically transparent/colorless polyimides; Langley Res. Cent., Natl. Aeronaut. Space Adm.: Hampton, VA, 1985; p 41 pp.\n\n(3) St. Clair, A.; St Clair, T.; Slemp, W.; Ezzell, K. S. Nasa Tech. Memo. 1985, 87650.\n\n(4) Reference deleted in proof.\n\n(5) St. Clair, A. K.; St. Clair, T. L.Highly optically transparent/colorless aromatic polyimide film; US Patent 4,595,548, 1986.\n\n(6) Misawa, Y.; Kinjo, N.; Hirao, M.; Numata, S.; Momma, N. IEEE Trans. Electron Devices 1987, 34, 621−627.\n\n(7) EndreyA. L.Ammonium salts of aromatic polyamide acids and polyimides therefrom, US Patent 3,242,136, 1966.\n\n(8) EndreyA. L.Aromatic Polyimides From Meta-Phenylene Diamine and Para-Phenylene Diamine, US Patent 3,179,633, 1965.\n\n(9) EndreyA. L.Aromatic polyimide particles from polycyclic diamines, US Patent 3,179,631, 1965.\n\n(10) Sroog, C. E. Prog. Polym. Sci. 1991, 16, 561−694.\n\n(11) Dine-Hart, R.; Wright, W. J. Appl. Polym. Sci. 1967, 11, 609− 627.\n\n(12) Bower, G. M.; Frost, L. W. J. Polym. Sci. 1963, 1, 3135−3150.\n\n(13) Sroog, C. E. J. Polym. Sci., Macromol. Rev. 1976, 11, 161−208.\n\n(14) Sroog, C. E.; Endrey, A. L.; Abramo, S. V.; Berr, C. E.; Edwards, W. M.; Olivier, K. L. J. Polym. Sci., Part A: Gen. Pap. 1965, 3, 1373− 1390.\n\n(15) Bell, V. Process for preparing thermoplastic aromatic polyimides. US Patent 4,094,862, 1978.\n\n(16) Ghosh, M. K.; Mittal, K. L. Polyimides: fundamentals and applications; Marcel Dekker: New York, 1996; p 891.\n\n(17) Nishino, T.; Kotera, M.; Inayoshi, N.; Miki, N.; Nakamae, K. Polymer 2000, 41, 6913−6918.\n\n(18) Shin, T. J.; Lee, B.; Youn, H. S.; Lee, K.-B.; Ree, M. Langmuir 2001, 17, 7842−7850.\n\n(19) Stephanie, J. G.; Rickerl, P. G. In Polyimides, Fundementals and Applications; Mittal, K. L., Ghosh, M. K., Eds.; Marcel Dekker, Inc.: New York, 1996.\n\n(20) Feger, C. Polym. Eng. Sci. 1989, 29, 347−351.\n\n(21) Saraf, R. F. Polym. Eng. Sci. 1997, 37, 1195−1209.\n\n(22) Lee, C.; Seo, J.; Shul, Y.; Han, H. Polym. J. (Tokyo, Jpn.) 2003, 35, 578−585.\n\n(23) Wachsman, E.; Frank, C. Polymer 1988, 29, 1191−1197.\n\n(24) Hardaker, S. S.; Samuels, R. J. J. Polym. Sci., Part B: Polym. Phys. 1997, 35, 777−788.\n\n(25) Cha, C. Y.; Samuels, R. J. J. Polym. Sci., Part B: Polym. Phys. 1995, 33, 259−267.\n\n(26) Jou, J. H.; Huang, P. T.; Chen, H. C.; Liao, C. N. Polymer 1992, 33, 967−974.\n\n(27) Pyun, E.; Mathisen, R.; Sung, C. Macromolecules 1989, 22, 1174−1183.\n\n(28) Takahashi, N.; Yoon, D. Y.; Parrish, W. Macromolecules 1984, 17, 2583−2588.\n\n(29) Bershtein, V.; Sukhanova, T.; Krizan, T.; Keating, M.; Grigoriev, A.; Egorov, V.; Yakushev, P.; Peschanskaya, N.; Vylegzhanina, M.; Bursian, A. J. Macromol. Sci., Part B: Phys. 2005, 44, 613−639.\n\n(30) Kreuz, J. A.; Endrey, A. L.; Gay, F. P.; Sroog, C. E. J. Polym. Sci., Part A-1: Polym. Chem. 1966, 4, 2607−2616.\n\n(31) Hsu, T. C. J.; Liu, Z. L. J. Appl. Polym. Sci. 1992, 46, 1821−1833.\n\n(32) Brekner, M. J.; Feger, C. J. Polym. Sci., Part A: Polym. Chem. 1987, 25, 2005−2020.\n\n(33) Brekner, M. J.; Feger, C. J. Polym. Sci., Part A: Polym. Chem. 1987, 25, 2479−2491.\n\n(34) Laius, L. A.; Bessonov, M. I.; Kallistova, E. V.; Adrova, N. A.; Florinskii, F. S. Vysokomol. Soedin., Ser. A 1967, 9, 2185−2192.\n\n(35) Lavrov, S. V.; Ardashnikov, A. Y.; Kardash, I. E.; Pravednikov, A. N. Vysokomol. Soedin., Ser. A 1977, 19, 1052−1057.\n\n(36) Echigo, Y.; Iwaya, Y.; Tomioka, I.; Yamada, H. Macromolecules 1995, 28, 4861−4865.\n\n(37) Kotera, M.; Nishino, T.; Nakamae, K. Polymer 2000, 41, 3615− 3619.\n\n(38) Ikeda, R. J. Polym. Sci., Part B: Polym. Lett. 1966, 4, 353−359.\n\n(39) Russell, T. P.; Gugger, H.; Swalen, J. D. J. Polym. Sci., Polym. Phys. Ed. 1983, 21, 1745−1756.\n\n(40) Herminghaus, S.; Boese, D.; Yoon, D. Y.; Smith, B. A. Appl. Phys. Lett. 1991, 59, 1043.\n\n(41) Hasegawa, M.; Horie, K. Progr. Polym. Sci. 2001, 26, 259−335.\n\n(42) Hasegawa, M.; Matano, T.; Shindo, Y.; Sugimura, T. Macromolecules 1996, 29, 7897−7909.\n\n(43) Ishii, J.; Shimizu, N.; Ishihara, N.; Ikeda, Y.; Sensui, N.; Matano, T.; Hasegawa, M. Eur. Polym. J. 2010, 46, 69−80.\n\n(44) Ebisawa, S.; Ishii, J.; Sato, M.; Vladimirov, L.; Hasegawa, M. Eur. Polym. J. 2010, 46, 283−297.\n\n(45) Hasegawa, M.; Shindo, Y.; Sugimura, T.; Yokota, R.; Kochi, M.; Mita, I. J. Polym. Sci., Part B: Polym. Phys. 1994, 32, 1299−1303.\n\n(46) Numata, S.; Fujisaki, K.; Kinjo, N. Polymer 1987, 28, 2282− 2288.\n\n(47) Numata, S.; Miwa, T. Polymer 1989, 30, 1170−1174.\n\n(48) Li, B.; He, T.; Ding, M.; Zhang, P.; Gao, F.; Jing, F. J. Mater. Res. 1998, 13, 1368.\n\n(49) Li, B.; He, T.; Ding, M. Thin Solid Films 1998, 320, 280−284.\n\n(50) Xu, Y.-K.; Zhan, M.-S.; Wang, K. J. Polym. Sci., Part B: Polym. Phys. 2004, 42, 2490−2501.\n\n(51) Coburn, J. C.; Pottiger, M. T. In Polyimides, Fundementals and Applications; Ghosh, M. K., Mittal, K. L., Eds.; Marcel Dekker, Inc.: New York, 1996.\n\n(52) Pottiger, M. T.; Coburn, J. C.; Edman, J. R. J. Polym. Sci., Part B: Polym. Phys. 1994, 32, 825−837.\n\n(53) Coburn, J.; Pottiger, M.; Noe, S.; Senturia, S. J. Polym. Sci., Part B: Polym. Phys. 1994, 32, 1271.\n\n(54) Coburn, J. C.; Pottiger, M. T. Advances in Polyimide: Science and Technology; Feger, C., Ed.; CRC Press: Lancaster, PA, 1993, pp 360− 374.\n\n(55) Jou, J.-H.; Lin, C.-P.; Sheu, W.-H. J. Polym. Sci., Part B: Polym. Phys. 1995, 33, 1803−1811.\n\n(56) Unsal, E.; Drum, J.; Yucel, O.; Nugay, I. Rev. Sci. Instrum. 2012, 83, 025114.\n\n(57) Koike, Y.; Sen, T. Z.; Cakmak, M. Annu. Tech. Conf.-Soc. Plast. Eng. 2002, 60th, 1550−1555.\n\n(58) Koike, Y.; Cakmak, M. Polymer 2003, 44, 4249−4260.\n\n(59) Kanuga, K.; Cakmak, M. Macromolecules 2005, 38, 9698−9710.\n\n(60) Kanuga, K.; Cakmak, M. Polymer 2007, 48, 7176−7192.\n\n(61) Sen, T. Z. Ph. D. Thesis, The University of Akron: 2003.\n\n(62) Pluta, M. Polymer 1992, 33, 1553−1555.\n\n(63) Hongladarom, K.; Burghardt, W. Macromolecules 1994, 27, 483−489.\n\n(64) Hongladarom, K.; Burghardt, W.; Baek, S.; S., C.; Magda, J. J. Macromolecules 1993, 26, 772−784.\n\n(65) Hongladarom, K.; Burghardt, W. Macromolecules 1993, 26, 785−794.\n\n(66) Hongladarom, K.; Secakusuma, V.; Burghardt, W. J. Rheol. 1994, 38, 1505.\n\n(67) Beekmans, F.; de Boer, A. P. Macromolecules 1996, 29, 8726− 8733.\n\n(68) Galay, J.; Cakmak, M. J. Polym. Sci., Part B: Polym. Phys. 2001, 39, 1147−1159.\n\n(69) Galay, J.; Cakmak, M. J. Polym. Sci., Part B: Polym. Phys. 2001, 39, 1107−1121.\n\n(70) Venkatesvaran, H.; Cakmak, M. Polym. Eng. Sci. 2001, 41, 341− 357.\n\n(71) Martins, C. I.; Cakmak, M. Polymer 2007, 48, 2109−2123.\n\n(72) Hassan, M. Ph. D. thesis, The University of Akron: 2004.\n\n(73) Cakmak, M.; Hassan, M. K.; Unsal, E.; Martins, C. I. Rev. Sci. Instrum. 2012, 83, 123901.\n\n(74) Bicakci, S.; Cakmak, M. Polymer 2002, 43, 2737−2746.\n\n(75) Unsal, E.; Nugay, I. I.; Offenbach, I.; Gross, M.; Manning, C.; Cakmak, M. Rev. Sci. Instrum. 2013, 84, 073901.\n\n(76) Stein, R. S. J. Polym. Sci. 1957, 24, 383−386.\n\n(77) Yucel, O.; Unsal, E.; Cakmak, M. Macromolecules 2013, 46, 7112.\n\n(78) Yamada, H.; Fukudome, M.; Egawa, N.; Kondo, Y.; Maki, H. US Patent 6,264,866 2001.\n\n(79) Sasaki, Y.; Inoue, H.; Negi, Y.; Sakai, K. US Patent 4,473,523 1984.\n\n(80) Shigeru, T.; Yasumitsu, M. JP, 2000−302867, A 2000.\n\n(81) Tetsuya, N.; Mikio, I.; Takehiro, N.; Haruhiko, M. JP, 2000− 204178, A 2000.\n\n(82) Tetsuya, N.; Egawa, N.; Haru JP, 2000−191806, A 2000.\n\n(83) Reference deleted in proof.\n\n(84) Sosnowski, T. P.; Weber, H. P. Appl. Phys. Lett. 1972, 21, 310− 311.\n\n(85) Cherkasov, A. N.; Vitovskaya, M. G.; Bushin, S. V. Vysokomol. Soedin., Ser. A 1976, 18, 1628−1634.\n\n(86) Prest, W. M.; Luca, D. J. J. Appl. Phys. 1979, 50, 6067.\n\n(87) Prest, W. M., Jr.; Luca, D. J. J. Appl. Phys. 1980, 51, 5170−5174.\n\n(88) Machell, J. S.; Greener, J.; Contestable, B. A. Macromolecules 1990, 23, 186−194.\n\n(89) Nasr, A. Polym. Test. 2002, 21, 303−306.\n\n(90) Greener, J.; Lei, H.; Elman, J.; Chen, J. J. Soc. Inf. Disp. 2005, 13, 835−839.\n\n(91) Greener, J.; Lei, H.; Rao, Y.; Elman, J. F. Proc. Int. Display Manuf. Conf. 2007, 402−405.\n\n(92) Chen, P. J.; Liu, T. J.; Wu, P. Y.; Tseng, C. F.; Leu, C. M. AIChE J. 2010, 56, 790−800.\n\n(93) Morino, S.; Horie, K. Polym. J. (Tokyo) 1999, 31, 707−710.\n\n(94) Eguchi, Y.; Unsal, E.; Cakmak, M. Macromolecules 2013, 46, 7488.\n\n" + }, + { + "abbreviations": [ + { + "abbreviation": "PA" + }, + { + "abbreviation": "3,4'-ODA" + } + ], + "csv": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/label_data/10.1163/156856190x00496.csv", + "golden_label": [ + { + "abbreviation": "PA", + "full_name": "phthalic anhydride", + "smiles": "O=C1OC(=O)c2ccccc21" + }, + { + "abbreviation": "3,4'-ODA", + "full_name": "3,4'-oxydianiline", + "smiles": "Nc1ccc(Oc2cccc(N)c2)cc1" + } + ], + "path": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/pdf_data/10.1163/156856190x00496_uniparser.json", + "pdf": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/pdf_data/10.1163/156856190x00496.pdf", + "text": "This article was downloaded by: [Queen Mary, University of London] On: 05 October 2014, At: 05:15 Publisher: Taylor & Francis Informa Ltd Registered in England and Wales Registered Number: 1072954 Registered office: Mortimer House, 37-41 Mortimer Street, London W1T 3JH, UK\n\nTo cite this article: Donald J. Progar & TERRY L. ST. Clair (1990) A new flexible backbone polyimide adhesive, Journal of Adhesion Science and Technology, 4:1, 527-549, DOI: 10.1163/156856190X00496\n\nTo link to this article: http://dx.doi.org/10.1163/156856190X00496\n\n\\begin{title}\nPLEASE SCROLL DOWN FOR ARTICLE\n\\end{title}\n\nTaylor & Francis makes every effort to ensure the accuracy of all the information (the “Content”) contained in the publications on our platform. However, Taylor & Francis, our agents, and our licensors make no representations or warranties whatsoever as to the accuracy, completeness, or suitability for any purpose of the Content. Any opinions and views expressed in this publication are the opinions and views of the authors, and are not the views of or endorsed by Taylor & Francis. The accuracy of the Content should not be relied upon and should be independently verified with primary sources of information. Taylor and Francis shall not be liable for any losses, actions, claims, proceedings, demands, costs, expenses, damages, and other liabilities whatsoever or howsoever caused arising directly or indirectly in connection with, in relation to or arising out of the use of the Content.\n\nThis article may be used for research, teaching, and private study purposes. Any substantial or systematic reproduction, redistribution, reselling, loan, sub-licensing, systematic supply, or distribution in any form to anyone is expressly forbidden. Terms & Conditions of access and use can be found at http:// www.tandfonline.com/page/terms-and-conditions\n\n\\begin{title}\nJournal of Adhesion Science and Technology\n\\end{title}\n\nPublication details, including instructions for authors and subscription information: http://www.tandfonline.com/loi/tast20\n\n\\begin{title}\nA new flexible backbone polyimide adhesive\n\\end{title}\n\nDonald J. Progar a & TERRY L. ST. Clair b a NASA Langley Research Center, Hampton, VA 23665-5225, USA b NASA Langley Research Center, Hampton, VA 23665-5225, USA Published online: 02 Apr 2012.\n\n\\begin{title}\nA new flexible backbone polyimide adhesive\n\\end{title}\n\nDONALD J. PROGAR* and TERRY L. ST. CLAIR NASA Langley Research Center, Hampton, VA 23665-5225, USA\n\nRevised version received 5 April 1990\n\nAbstract-A new linear, aromatic, thermoplastic polyimide, identified as LARC-IA, has been synthesized and evaluated, primarily as an adhesive, which is physiologically safe and relatively inexpensive. The polymer was prepared from oxydiphthalic anhydride (ODPA) and 3,4-oxydianiline (ODA) in diglyme. In order to obtain optimal flow properties, which improves wetting, the molecular weight of the polymer was controlled by use of a monofunctional anhydride, phthalic anhydride (PA).\n\nAdhesively bonded lap shear specimens, using Ti-6AI-4V adherends, were prepared and tested to assess its adhesive potential. Specimens were exposed to water boil and thermal aging to determine the adhesive system's durability. Flatwise tensile strength and critical fracture energy were also deter- mined. Results were compared to data for LARC-TPI.\n\nPreliminary flexural strength and modulus results were also obtained for composites fabricated from LARC-IA (5% PA) and graphite fibers (AS4, 12K).\n\nInitial results of this study indicate considerable promise for this material as a structural adhesive for applications for temperatures up to 200°C.\n\nKeywords: Polyimide; adhesive; high temperature; thermoplastic; lap shear strength.\n\n\\begin{title}\n1. INTRODUCTION\n\\end{title}\n\nBecause of the anticipated needs of the aerospace industry for high temperature polymers for use in various applications, research has continued at Langley Research Center on the synthesis and development of new, inexpensive, flexible, aromatic, high temperature polymers. A recent result of that goal was the develop- ment of the thermoplastic, linear polyimide, LARC-TPI, that exhibited excep- tional adhesive and other properties [1-3]. The polyimide is presently\n\n\\begin{molecule}\nO=C1c2ccc(C(=O)c3ccc4c(c3)C(=O)N(c3cccc(C(=O)c5ccc(C)cc5)c3)C4=O)cc2C(=O)N1C\n\\end{molecule}\n\n\\begin{legend}\nLARC-TPI Tg=260°C(500°F)\n\\end{legend}\n\nproduced by several suppliers in film, molding powder, prepreg, and solution (varnish) forms. However, present concern of the physiological effects due to the\n\n*To whom correspondence should be addressed.\n\ndiamine component, 3,3'-diaminobenzophenone (DABP), and its relatively expensive cost tend to detract from its other excellent attributes. Therefore, a new polyimide with properties similar to LARC-TPI has been synthesized and evaluated. The polymer, identified as LARC-IA (Langley Research Center- Improved Adhesive), has been prepared in diglyme as a 15 wt % solids solution from oxydiphthalic anhydride (ODPA) and 3,4'-oxydianiline (ODA). The mol- ecular weight, and therefore, its flow, was controlled by use of a monofunctional anhydride [phthalic anhydride (PA)]. This polymer is of particular interest as a possible replacement for LARC-TPI, a commercially available polyimide with exceptional adhesive properties as well as being a highly thermooxidatively stable material. LARC-TPI is presently available in several forms: films, molding powder, 30 wt % solids solution (varnish), and prepreg. However, the 3,3'-diaminobenzo- phenone component is expensive and its physiological effects are uncertain. LARC-IA is synthesized from noncarcinogenic, nontoxic chemicals which are relatively inexpensive.\n\nThe adhesive evaluation of this new polyimide, LARC-IA with and without endcaps, is the primary subject of this report. The effects of an aluminum powder filler was also investigated. Flatwise tensile strength (FWT), critical fracture energy and several LARC-IA film properties were determined. Preliminary results were also obtained for composites composed of LARC-IA with 5 wt % PA endcap [LARC-IA (5% PA)] and graphite fiber (AS4, 12K).\n\n\\begin{title}\n2. EXPERIMENTAL\n\\end{title}\n\n\\begin{title}\n2.1. Materials and synthesis\n\\end{title}\n\nThe reaction scheme for the synthesis LARC-IA is shown in Fig. 1. The chemicals used to prepare the polymer were obtained from commercial sources. The\n\n\\begin{molecule}\nO=C1OC(=O)c2cc(Oc3ccc4c(c3)C(=O)OC4=O)ccc21\n\\end{molecule}\n\n\\begin{molecule}\nNc1ccc(Oc2cccc(N)c2)cc1\n\\end{molecule}\n\n\\begin{molecule}\nCN1C(=O)c2ccc(Oc3ccc4c(c3)C(=O)N(Cc3ccc(OC)cc3)C4=O)cc2C1=O\n\\end{molecule}\n\n\\begin{legend}\nFigure 1. Reaction scheme for LARC-IA.\n\\end{legend}\n\noxydiphthalic anhydride (ODPA) was supplied by OXY Chemical, Niagara Falls, NY. The 3,4'-oxydianiline (3,4'-ODA) was supplied by Kennedy and Klim Incorporated, Little Silver, NJ.\n\nThe polymer that was primarily used as the adhesive was prepared in reagent grade bis(2-methoxyethyl)ether (diglyme) at 16.5% solids. The ODPA (60.4935 g) was mixed with 3,4'-ODA (40.0480 g) in 515 g of diglyme at room temperature (RT). This mixture was stirred overnight and PA (1.4812 g) was added and stirring continued for an additional 30 min. This solution was stored for 48 h at 4°C and its inherent viscosity, 1'Jinh, was determined to be 0.47 dl/g (0.5% in DMAc at 35°C). This gave a polymer with a 2.5% molar excess of the diamine which was endcapped with 5.0 mol % monofunctional PA. The un- endcapped version of the polymer was prepared in the same manner with equimolar amounts of the ODPA and 3,4'-ODA (1'Jinh 0.63 dl/g). A 10% end- capped version was prepared in a like manner with a 5% molar excess of diamine and 10 mol % of PA (1'Jinh 0.25 dl/g).\n\n\\begin{title}\n2.2. Characterization\n\\end{title}\n\nLap shear strength (LSS) was determined according to ASTM D1002 using an Instron Universal Testing Machine. The LSSs reported represent an average of four lap shear specimens per test condition except as noted in the tables. The range of LSSs is indicated by dashed lines in the bar graphs and is listed in the tables. Elevated temperature tests were conducted in a clam-shell, quartz-lamp oven with temperatures controlled to ± 3°C for all tests. Specimens were held 10 min at temperature prior to testing except for the water boil tests which were conducted upon reaching the test temperature (approximately 1-2 min).\n\nBondline thickness for the bonded titanium lap shear specimens is defined as the difference between the total joint thickness measured with a micrometer and the sum of the adherend thicknesses. The average bondline thickness for the thermally aged and water boil specimens was 0.023 cm for LARC-IA, 0.010 cm for LARC-IA (5% PA), and 0.017 cm for LARC-IA (5% PA) 50% Al powder.\n\nGlass transition temperatures ( Tg) were determined using a DuPont 990 Thermal Analyzer in conjunction with a DuPont Model 943 Thermal Mechanical Analyzer (TMA)*. TMAs for films were run in static air at a heating rate of 5°C/min with a load of 0.5-2.0 g. Tgs, determined by Differential Scanning Calorimetry (DSC), were obtained on a DuPont 1090 Thermal Analyzer in conjunction with a Model 910 Differential Scanning Calorimeter run at 20°C/min.\n\nInherent viscosity was determined using a Cannon-Ubbelohde viscometer in a 35°C water bath controlled to within ± 0.01°C. A 10 ml solution of 0.5 wt/vol % solids in dimethylacetamide (DMAc) was made and filtered.\n\nThe type of failure in lap shear tests was evaluated visually using a 10 x magnification and estimating the percent area of each type of failure, cohesive or interfacial.\n\nFWT was determined according to ASTM C297 using 5.1 x 5.1 cm specimens tested at RT.\n\n*Use of trade names or manufacturers does not constitute an official endorsement, either expressed or implied, by the National Aeronautics and Space Administration.\n\nCritical fracture energy was determined using a double cantilever beam specimen in accordance with ref. [4]. The film properties: yield strength, tensile strength, tensile modulus, and elongation were determined according to ASTM D882.\n\nThe mechanical properties, flexural strength and flexural modulus, were obtained for LARC-IA (5% PA)/AS4, 12K composite according to ASTM D790.\n\nThe solvent resistance of LARC-IA film was evaluated by immersing a strip of film, 0.64 cm x 1.27 cm, in several different solvents for 72 h, removing the film and assessing the results visually as well as determining the Tg by TMA and DSC techniques.\n\n\\begin{title}\n2.3. Adhesive tape\n\\end{title}\n\nThe adhesive tapes were prepared by brush coating the polymer solution [ 15 wt % for LARC-IA, 11inh 0.63 dl/g; 16.5 wt % for LARC-IA (5% PA), 11inh 0.47 dl/g; and 16.9 wt % for LARC-IA (10% PA), 11 inh 0.25 dl/g] in diglyme onto a 112 E-glass cloth with an A-1100 finish (y-aminopropyltriethoxysilane) (Union Carbide). The glass cloth had been tightly mounted on a metal frame and dried in a forced-air oven for 30 min at 100°C prior to coating. The 0.10 mm thick glass cloth served as a carrier for the adhesive as well as for bondline thickness control and an escape channel for the solvent. After a primer coat (=7.5 wt % solids solution) was applied and dried, several applications of the orginally prepared solution were used until the thickness of the tape was 0.20-0.30 mm. After each coat was applied, the tape was air-dried at ambient for 0.5-1.0 h, placed in a forced-air oven, and exposed to the following schedule:\n\n(1) RT - 1 00°C, held 1 h;\n\n(2) 1 00°C - 1 50°C, held 1 h; and\n\n(3) 150°C -175°C, held 1 h.\n\nThe procedure used to prepare the tapes was required to drive off the solvent and reaction product volatiles when converting the polyamic acid resin to the polyimide. Imidization of most polyamic acids to polyimides generally occurs in the 160°C range, with the degree of conversion being a function of time and temperature. The prepared tapes were stiff with no tack or drape.\n\nThe same procedure was used to prepare the powdered aluminum filled tapes. The aluminum (Alcan Aluminum Corp., grade MD105, 98% minimum Al content, 4.5-6.4 pm particle size) was added to the polymer solution at 50% by weight of the polymer solids content.\n\n\\begin{title}\n2.4. Adhesive bonding\n\\end{title}\n\nThe prepared adhesive tapes were used to bond lap shear specimens with titanium adherends (Ti-6A1-4V, per Mil-T-9046E, Type III Comp. C) that were a nominal 1.27 mm thick. The four-fingered Ti-6A1-4V panels were grit-blasted with 120 grit aluminum oxide, washed and rinsed with methanol, and surface treated with Pasa-Jell 107* treatment to form a stable oxide on the surface. The adherends were primed with a 7.5 wt % solution of the same resin that was used to prepare the tape. The primer was air-dried 0.5 h, then heated in a forced-air oven for\n\n*Trade name for a titanium surface treatment available from Semco, Glendale, CA.\n\n15 min at 100°C and 15 min at 150°C prior to bonding. Lap shear specimens were prepared by inserting the adhesive tape between the primed adherends using a 12.7 mm overlap. Each adhesive system was bonded using three different bonding conditions. Bonding temperature was monitored using a type K thermocouple spotwelded next to the bond area. Selection of the optimized bond condition was based on that giving the highest LSSs. The selected bonding condition was then used to prepare specimens for the aging and water boil tests.\n\nFWT specimens for LARC-IA (5% PA) and LARC-IA (5% PA) 50% Al were prepared from titanium honeycomb core (= 2.71 mm thick) and Ti-6Al-4V facesheets (==0.51 mm thick). Both the core and facesheets were given a Pasa-Jell 107 surface treatment and primed prior to bonding. Bonding conditions were: 8°C/min heating rate, 0.34 MPa pressure, RT- 371 °C held 1 h. 5.1 x 5.1 cm specimens were cut and bonded to the test blocks with HT-424 adhesive (American Cyanamid Company). Tests were performed at RT.\n\nDouble cantilever beam (DCB) specimens, also bonded with LARC-IA (5% PA) and LARC-IA (5% PA) 50% Al, were prepared using 1.21 mm thick Ti-6AI-4V with a Pasa-Jell surface treatment and primed prior to bonding. The DCB configuration, testing, and calculations are presented in ref. [4]. Bonding conditions were: 8°C/min heating rate, 2.07 MPa pressure, and RT- 371°C held 1 h.\n\n\\begin{title}\n2.5. Thermal and water boil exposure\n\\end{title}\n\nA bonding cycle was selected which was based on the highest LSS and was used to prepare specimens to determine the effects of thermal exposure in a forced-air oven at 204°C ± 2°C for up to 5000 h. Lap shear tests were conducted at RT, 177, 204 and 232°C before (controls) and after exposure.\n\nA 72-h water boil test was conducted in laboratory glassware containing boiling distilled water. Lap shear specimens were immersed above and bonded area during a 72-h period. LSSs were determined at RT, 177, 204 and 232°C.\n\n\\begin{title}\n2.6. LARC-IA film solvent resistance\n\\end{title}\n\nA nominal 0.025 mm thick LARC-IA film was prepared by doctoring a 15 wt % solids solution in diglyme on a glass plate and curing in a forced-air oven for 1 h at each temperature of 100, 200 and 300°C. Films were soaked at RT for a 72-h period in methylene chloride, diglyme, DMAc, m-cresol and N-methyl-2-pyr- rolidone. Films were patted dry with hand wipes and visually evaluated. T9 was then determined by TMA and DSC.\n\n\\begin{title}\n3. RESULTS AND DISCUSSION\n\\end{title}\n\n\\begin{title}\n3.1. Chemistry\n\\end{title}\n\nThe adhesive properties of LARC-TPI have been attributed to the high degree of flexibility in the polymer backbone afforded by the bridged dianhydride and the meta-linked diamine [5]. The 3,3'-BTDA diamine is expensive to synthesize (> $110/kg). Also, because it has been shown to give a positive Ames test, this material must be handled with great care which adds to the cost of the resulting\n\nadhesive. However, once the diamine has been reacted into the polymer backbone it should no longer pose a hazard.\n\nThe novel diamine 3,4'-ODA has been commercially developed in Japan for potential use in high modulus aromatic polyimides. This diamine has been tested and shown to have very low mutagenic activity in the Ames test [6]. Also the monomer, ODPA, has become commercially available. The combination of these two monomers in diglyme affords a polyimide which has exceptional adhesive properties especially when its molecular weight is controlled. Examination of molecular models shows this new polyimide, LARC-IA, to have similar chain flexibility to LARC-TPI.\n\n\\begin{title}\n3.2. Bonding temperature and pressure\n\\end{title}\n\nSelection of the optimum bonding conditions for each polymer was based on obtaining the best compromise of high LSS for tests at RT, 177, 204 and 232°C. Results are expressed in graphical form for those interested in obtaining a quick pictorial summary of the results, and in tabular form for those interested in more detail and additional information not included in the graphs.\n\nIn general, the LSSs decrease with temperature with a drastic decrease as the T9 is approached. Therefore, in most cases, the 232°C strength is greatly reduced from that at 204°C.\n\n3.2.1. LARC-IA. As shown in Fig. 2 and given in Table 1, three combinations of temperature and pressure were evaluated using either 2.07 or 3.45 MPa pressure and 343 or 371°C temperature. Little flashing or squeeze-out was observed for the polymer after bonding, indicating poor flow properties. The best\n\n\\begin{legend}\nTi-6Al-4V Adherends\n\\end{legend}\n\n\\begin{caption}\nFigure 2. Effect of bonding conditions on the lap shear strengths of LARC-IA bonded Ti-6AI-4V specimens.\n\\end{caption}\n\n\\begin{caption}\nLSS results for LARC-IA bonded Ti-6Al-4V Table 1.\n\\end{caption}\n\n\\begin{caption}\nA new flexible backbone polyimide adhesive\n\\end{caption}\n\n\\begin{table}\n| Bonding pressure MPa (psi) | Bonding temperature C(°F) | Number of specimens | Test temperature C(°F) | Average LSS MPa (psi) | Range of LSS MPa (psi) | Primary failure modea |\n|:-----------------------------|:----------------------------|:----------------------|:-------------------------|:------------------------|:-------------------------|:------------------------|\n| 2.07 (300) | 343(650) | 4 | RT (RT) | 37.2(5390) | 34.8-38.3(5050-5550) | Co |\n| 2.07 (300) | 343(650) | 4 | 177(350) | 25.0(3620) | 24.5-25.4(3550-3680) | Co |\n| 2.07 (300) | 343(650) | 4 | 204(400) | 15.6(2260) | 14.1-16.5(2040-2400) | Co |\n| 2.07 (300) | 343(650) | 4 | 232(450) | 5.6(820) | (710-920) 4.9-6.3 | I |\n| 3.45 (500) | 343(650) | 4 | RT (RT) | 34.5 (5000) | 29.6-39.6(4290-5750) | Co |\n| 3.45 (500) | 343(650) | 4 | 177(350) | 27.8(4030) | 27.4-28.5(3970-4130) | Co |\n| 3.45 (500) | 343(650) | 7 | 204(400) | 14.7(2130) | 13.0-16.3(1880-2370) | Co |\n| 3.45 (500) | 343(650) | 5 | 232(450) | 5.8(850) | 5.2-6.5(750-950) | ( |\n| 2.07 (300) | 371(700) | 4 | RT (RT) | 31.8(4620) | 30.3-32.6(4400-4730) | Co |\n| 2.07 (300) | 371(700) | 4 | 177(350) | 25.5(3700) | 25.0-26.5(3630-3840) | $Co$ |\n| 2.07 (300) | 371(700) | 7 | 204(400) | 21.1 (3060) | 20.2-21.7(2930-3150) | c}$ |\n| 2.07 (300) | 371(700) | 5 | 232(450) | 9.1(1320) | 7.2-10.6(1040-1540) | |\n\\end{table}\n\naCo=cohesive; I=interfacial.\n\n\\begin{title}\nD. J. Progar and T. L. St. Clair\n\\end{title}\n\ncompromise of LSSs was obtained with 2.07 MPa and 371°C. A significant increase in LSS was noted for the 204 and 232°C tests (21.1 MPa vs 15.7 and 14.7 MPa for the 204°C tests and 9.1 MPa vs 5.6 and 5.8 MPa for the 232°C tests). Therefore, specimens for thermal aging and water boil were prepared using 2.07 MPa pressure and 371°C temperature conditions.\n\n3.2.2. LARC-IA (5% PA). LSS results for LARC-IA (5% PA) adhesive are shown in Fig. 3 and Table 2. The same three bonding conditions used for LARC-IA were again used to evaluate LARC-IA (5% PA). Squeeze-out is evident indicating improved flow due to the control of the molecular weight by end- capping with phthalic anhydride. The best compromise of LSS values is again evident for the 2.07 MPa and 371°C bonding conditions. Excellent LSSs are obtained at RT, 177 and 204°C for all three bonding conditions (RT, 44.0-45.6 MPa; 177°C, 32.5-36.6 MPa; and 204°C, 23.9-28.4 MPa).\n\n3.2.3. LARC-IA (10% PA). Because of the increase in the percent of end- capping, greater flow was expected during bonding and, therefore, in two cases, a lower bonding pressure was used. Test results for LARC-IA ( 10% PA) are shown in Fig. 4 and given in Table 3. Greater squeeze-out is noticed for this polymer which was also more brittle than LARC-IA and LARC-IA (5% PA). However, although the RT LSS is slightly lower for the 0.69 MPa/371°C condition than for the other two conditions evaluated, the 232°C strength increases by = 3 MPa and the 177 and 204°C strengths remained the same. Because the 5% PA endcapped adhesive provided higher strengths than the 10% PA endcapped adhesive, no thermal aging or water boil tests were conducted with the 10% PA endcapped adhesive.\n\n\\begin{title}\nTi-6Al-4V Adherends\n\\end{title}\n\n\\begin{caption}\nFigure 3. Effect of bonding conditions on the lap shear strengths of LARC-IA (5% PA) bonded Ti-6Al-4V specimens.\n\\end{caption}\n\n\\begin{caption}\nLSS results for LARC-IA (5% PA)bonded Ti-6Al-4V Table 2.\n\\end{caption}\n\n\\begin{caption}\nA new flexible backbone polyimide adhesive\n\\end{caption}\n\n\\begin{table}\n| Bonding pressure MPa (psi) | Bonding temperature C(F)d | Number of specimens | Test temperature C(F) | Average LSS MPa (psi) | Range of LS MPa (psi) | Primary failure modea |\n|:-----------------------------|:----------------------------|:----------------------|:------------------------|:------------------------|:------------------------|:------------------------|\n| 2.07(300) | 343(650) | 4 | RT (RT) | 44.0(6390) | 43.4-44.8(6300-6500) | Co |\n| 2.07(300) | 343(650) | 4 | 177(350) | 32.5(4710) | 29.4-34.4(4270-4990) | Co |\n| 2.07(300) | 343(650) | 4 | 204(400) | 23.9(3470) | 23.2-24.9(3370-3610) | Co |\n| 2.07(300) | 343(650) | 4 | 232(450) | 9.0(1310) | 7.6-9.6(1100-1390) | I |\n| 3.45 (500) | 343(650) | 4 | RT(RT) | 45.6 (6620) | 44.3-46.8(6430-6790) | Co |\n| 3.45 (500) | 343(650) | 4 | 177(350) | 33.3(4830) | 32.2-34.5(4670-5010) | Co |\n| 3.45 (500) | 343(650) | 4 | 204(400) | 25.4(3690) | 24.5-26.7(3560-3880) | Co |\n| 3.45 (500) | 343(650) | 4 | 232(450) | 6.8(990) | 5.7-7.8(830-1130) | |\n| 2.07(300) | 371(700) | 4 | RT(RT) | 44.2(6420) | 43.7-45.3(6340-6570) | Co |\n| 2.07(300) | 371(700) | 4 | 177(350) | 36.6(5310) | 35.5-39.0(5150-5660) | Co |\n| 2.07(300) | 371(700) | 4 | 204(400) | 28.4(4120) | 27.3-29.7(3960-4310) | $c$ |\n| 2.07(300) | 371(700) | 4 | 232(450) | 9.3(1350) | 8.5-10.6(1240-1540) | |\n\\end{table}\n\nCo=cohesive; I=interfacial.\n\n\\begin{caption}\nFigure 4. Effect of bonding conditions on the lap shear strengths of LARC-IA (10% PA) bonded Ti-6AI-4V specimens.\n\\end{caption}\n\n3.2.4. LARC-IA (5% PA) 50% Al. The addition of aluminum powder filler to the LARC-IA (5% PA) material was investigated because past experience has shown that improvement in strength and use temperature were realized by this technique [7]. As shown in Fig. 5 and Table 4, excellent LSSs are obtained for all test temperatures and bond conditions. An improvement in strength for the 232°C tests is evident (13.6 MPa vs 9.3 MPa previously obtained). The best results for the LARC-IA (5% PA) 50% Al powder adhesive are obtained using the 2.07 MPa and 371°C bonding conditions.\n\n3.2.5. LARC-IA (10% PA) 50% Al. Only one bonding condition was used for LARC-IA ( 10% PA) 50% Al powder because of the results mentioned earlier for the same polymer which provided excess flow without the aluminum filler. Figure 6 shows a comparison of the LSSs for the LARC-IA 5% and 10% PA endcap with 50 wt % of aluminum powder filler. The LSSs for the 10% PA adhesive are lower than the 5% PA adhesive for all test temperatures, a similar trend obtained earlier for the same polymers without the aluminum filler. No thermal aging or water boil tests were attempted with this adhesive system.\n\n\\begin{title}\n3.3. Thermal exposure\n\\end{title}\n\nThe effects on LSS due to thermal exposure in a forced-air oven at 204°C are shown in Fig. 7 and given in Table 5 for LARC-IA, LARC-IA (5% PA), LARC-IA (5% PA) 50% Al, and LARC-TPI. LSS tests were performed at RT, 177, 204 and 232°C. Strength results for LARC-TPI, reported previously, are included for comparison [2].\n\n\\begin{caption}\nLSS results for LARC-IA (10% PA) bonded Ti-6Al-4V Table 3.\n\\end{caption}\n\n\\begin{caption}\nA new flexible backbone polyimide adhesive\n\\end{caption}\n\n\\begin{table}\n| Bonding pressure MPa (psi) | Bonding temperature C(F)d | Number of specimens | Test temperature C(F) | Average LSs MPa (psi) | Range of LSS MPa (psi) | Primary failure mode |\n|:-----------------------------|:----------------------------|:----------------------|:------------------------|:------------------------|:-------------------------|:-----------------------|\n| 0.69(100) | 343(650) | 4 | RT (RT) | 38.8(5630) | 38.0-39.4(5510-5710) | Co |\n| 0.69(100) | 343(650) | 4 | 177(350) | 26.1(3790) | 25.6-26.8(3720-3890) | Co |\n| 0.69(100) | 343(650) | 4 | 204(400) | 18.9(2740) | 17.8-19.3(2580-2800) | Co/I |\n| 0.69(100) | 343(650) | | 232(450) | 5.4(780) | 4.9-5.4(710-850) | Co/I |\n| 2.07(300) | 343(650) | 3 | RT(RT) | 37.3(5420) | 34.3-39.4(4980-5710) | Co |\n| 2.07(300) | 343(650) | 4 | 177(350) | 27.6(4010) | 26.4-28.3(3830-4110) | Co |\n| 2.07(300) | 343(650) | 4 | 204(400) | 19.3(2800) | 16.9-21.2(2450-3070) | Co/I |\n| 2.07(300) | 343(650) | 4 | 232(450) | 4.9(710) | 4.0-5.7(580-830) | |\n| 0.69(100) | 371(700) | | RT (RT) | 30.7(4450) | 29.2-33.0(4240-4780) | Co |\n| 0.69(100) | 371(700) | 4 | 177(350) | 26.6(3860) | 25.1-27.5(3640-3990) | Co |\n| 0.69(100) | 371(700) | 4 | 204(400) | 22.0(3190) | 21.0-23.0(3050-3330) | Co/I |\n| 0.69(100) | 371(700) | 4 | 232(450) | 8.1(1180) | 7.2-8.7(1040-1260) | Co/I |\n\\end{table}\n\naCo=cohesive; I=interfacial.\n\n\\begin{caption}\nLSS results for LARC-IA (5% PA) 50% Al powder bonded Ti-6Al-4V Table 4.\n\\end{caption}\n\n\\begin{caption}\nD. J. Progar and T. L. St. Clair\n\\end{caption}\n\n\\begin{table}\n| Bonding pressure MPa (psi) | Bonding temperature C(F) | Number of specimens | Test temperature ℃(°F) | Average LSS MPa (psi) | Range of LSS MPa (psi) | Primary failure modea |\n|:-----------------------------|:---------------------------|:----------------------|:-------------------------|:------------------------|:-------------------------|:------------------------|\n| 2.07(300) | 343(650) | 4 | RT (RT) | 43.0(6240) | 41.0-44.0(5950-6380) | Co |\n| 2.07(300) | 343(650) | 4 | 177(350) | 31.5(4570) | 30.2-32.3(4380-4680) | Co |\n| 2.07(300) | 343(650) | 4 | 204(400) | 27.2(3940) | 26.7-27.6(3870-4010) | Co |\n| 2.07(300) | 343(650) | 4 | 232(450) | 10.1(1470) | 9.4-11.6(1360-1690) | Co |\n| 3.45(500) | 343(650) | 4 | RT (RT) | 42.5(6170) | 41.3-43.8(5990-6350) | Co |\n| 3.45(500) | 343(650) | 4 | 177(350) | 33.5(4860) | 32.4-34.1(4700-4950) | Co |\n| 3.45(500) | 343(650) | 4 | 204(400) | 27.5(3990) | 26.5-28.5(3840-4130) | Co |\n| 3.45(500) | 343(650) | 4 | 232(450) | 11.2(1620) | 10.3-12.5(1490-1810) | Co |\n| 2.07(300) | 371(700) | | RT (RT) | 43.8(6350) | 42.7-45.3(6200-6570) | Co |\n| 2.07(300) | 371(700) | 4 | 177(350) | 33.2(4820) | 32.5-34.0(4710-4940) | $Co$ |\n| 2.07(300) | 371(700) | 4 | 204(400) | 28.7(4160) | 27.7-29.2(4020-4240) | Co |\n| 2.07(300) | 371(700) | 4 | 232(450) | 13.6(1970) | 13.2-14.7(1910-2130) | Co |\n\\end{table}\n\naCo=cohesive.\n\n\\begin{caption}\nA new flexible backbone polyimide adhesive\n\\end{caption}\n\n\\begin{caption}\nFigure 5. Effect of bonding conditions on the lap shear strengths of LARC-IA (5% PA) 50% Al powder bonded Ti-6A1-4V specimens.\n\\end{caption}\n\n\\begin{caption}\nFigure 6. Lap shear strengths for LARC-IA 5% and 10% PA endcap with 50 wt % aluminum powder filler.\n\\end{caption}\n\n\\begin{caption}\nLSS results of thermal exposure in air at 204°C for bonded Ti-6Al-4Va Table 5.\n\\end{caption}\n\n\\begin{table}\n| Adhesive | Thermal exposure h | Number of specimens | Test temperature C(°F) | Average LSS MPa (psi) | Range of LSs MPa (psi) | Primary failure modeb |\n|:-----------|:---------------------|:----------------------|:-------------------------|:------------------------|:-------------------------|:------------------------|\n| LARC-IA | 0 | 4 | RT (RT) | 31.8(4620) | 30.3-32.6 (4400-4730) | Co |\n| | | 4 | 177(350) | 25.5(3700) | 25.0-26.5(3630-3840) | Co |\n| | | 7 | 204(400) | 21.1(3060) | 20.2-21.7(2930-3150) | Co |\n| | | 5 | 232(450) | 9.1(1320) | 7.2-10.6(1040-1540) | I |\n| | 1000 | 4 | RT (RT) | 27.8(4030) | 26.1-29.4(3790-4260) | Co/I |\n| | | 4 | 177(350) | 29.4(4260) | 25.9-31.0(3760-4500) | Co |\n| | | 4 | 204(400) | 26.2(3800) | 23.3-29.1(3380-4220) | Co |\n| | | 4 | 232(450) | 14.0(2030) | 13.5-14.7(1960-2130) | Co |\n| | 5000 | 4 | 204(400) | 26.9(3900) | 24.7-27.8(3590-4040) | Co |\n| LARC-IA | 0 | 4 | RT (RT) | 44.2(6420) | 43.7-45.3(6340-6570) | Co |\n| (5%PA) | | 4 | 177(350) | 36.6(5310) | 35.5-39.0(5150-5660) | Co |\n| | | 4 | 204(400) | 28.4(4120) | 27.3-29.7(3960-4310) | Co |\n| | | 4 | 232(450) | 9.3(1350) | 8.5-10.6(1240-1540) | I |\n| | 1000 | 4 | RT(RT) | 35.0(5080) | 34.0-35.8(4930-5190) | Co |\n| | | 3 | 177(350) | 33.4(4850) | 31.2-35.2(4530-5100) | Co |\n| | | 4 | 204(400) | 30.4(4410) | 29.6-31.6(4300-4590) | Co |\n| | | 4 | 232(450) | 9.7(1410) | 8.0-12.6(1160-1830) | TP |\n| | 5000 | 4 | RT (RT) | 29.0(4200) | 27.4-31.3(3970-4540) | Co |\n| | | 4 | 177(350) | 30.9(4480) | 29.6-31.6(4300-4550) | Co |\n| | | 4 | 204(400) | 30.4(4410) | 29.0-32.0(4200-4640) | Co |\n| | | 4 | 232(450) | 7.9(1150) | (970-1260) 6.7-8.7 | Co/I |\n\\end{table}\n\n\\begin{caption}\nA new flexible backbone polyimide adhesive\n\\end{caption}\n\n\\begin{table}\n| LARC-IA | | 4 | RT (RT) | 43.8(6350) | 42.7-45.3(6200-6570) | co$ | |\n|:--------------------|:-----|:-------|:------------------|:--------------|:------------------------------------------|:---------------------|:---|\n| (5%PA) 50%AI powder | | | 177(350) 204(400) | 33.2(4820) | 32.5-34.0(4710-4940) 27.7-29.2(4020-4240) | Co | |\n| (5%PA) 50%AI powder | | 4 | | 28.7(4160) | | | |\n| (5%PA) 50%AI powder | | 4 | 232(450) | 13.6 (1970) | 13.2-14.7(1910-2130) | Co | |\n| (5%PA) 50%AI powder | | 4 | RT (RT) | 42.9(6220) | 41.1-43.8(5960-6360) | Co | |\n| (5%PA) 50%AI powder | 1000 | 4 | 177(350) | 34.3(4980) | 33.8-34.9(4900-5060) | Co | |\n| (5%PA) 50%AI powder | 1000 | 4 | 204(400) | 31.3(4540) | 29.9-31.8(4340-4610) | Co | |\n| (5%PA) 50%AI powder | 1000 | 4 | 232(450) | 12.9 (1870) | 11.6-14.2(1680-2060) | Co | |\n| (5%PA) 50%AI powder | 1000 | 5 | RT (RT) | 34.1(4950) | 33.1-35.4(4800-5130) | Co | |\n| (5%PA) 50%AI powder | 1000 | 4 | 177(350) | 28.3(4100) | 26.3-29.6(3820-4300) | Co | |\n| (5%PA) 50%AI powder | | 5000 0 | 3 | 204(400) | 24.5(3560) | 23.7-25.5(3440-3700) | Co |\n| 3 | | 5000 0 | 232(450) | 7.7(1120) | 7.6-7.8(1100-1140) | TP | |\n| 4 | | 5000 0 | RT (RT) | 33.0(4790) | 32.3-33.5(4680-4860) | Co | |\n| 4 | | 5000 0 | 177(350) | 29.5(4280) | 28.8-30.7(4180-4450) | $C $ | |\n| 4 | | 5000 0 | 204(400) | 25.2(3660) | 25.0-25.4(3620-3690) | $Cr$ | |\n| LARC-TPIc | 1000 | 8 | 232(450) | 17.5(2540) | 14.8-19.7(2150-2860) | Co | |\n| LARC-TPIc | 1000 | 4 | RT (RT) | 32.9(4780) | 32.3-34.4(4690-4980) | Co | |\n| LARC-TPIc | 1000 | 4 | 177(350) | 29.9(4340) | 28.5-31.0(4140-4490) | Co | |\n| LARC-TPIc | 1000 | 4 | 204(400) | 27.8(4020) | 27.2-28.6(3940-4160) | Co | |\n| LARC-TPIc | 5000 | 3 | 232(450) | 23.3(3380) | 21.8-24.5(3160-3550) | Co | |\n| LARC-TPIc | 5000 | 4 | RT(RT) | 27.1(3930) | 26.0-28.1(3760-4080) | Co | |\n| LARC-TPIc | 5000 | 4 | 177(350) | 25.7(3730) | 24.5-26.4(3550-3820) | Co | |\n| LARC-TPIc | 5000 | | 204(400) | 26.0(3770) | 24.7-26.9(3580-3900) | Co | |\n| LARC-TPIc | 5000 | | 232(450) | 23.7(3440)e | 22.8-24.6(3300-3570) | Co | |\n\\end{table}\n\nBonding conditions: 2.07 MPa(300 psi) pressure from start, heating rate of8°C/min (14°F/min), RT→371°C(700°F), held 1 h. bCo=cohesive;I=interfacial;TP=thermoplastic.\n\nData previously reported by our laboratory. Bonding conditions: 2.07 MPa; 343°Cheld 1 h. d2260hat232C(450°F). e5n0n1.2201A5n01\n\n\\begin{caption}\nhear strengths on thermal exposure in air at 204°C for Ti-6Al-4V bonded with LARC-IA adhesives and compared with LARC-TPI adhesive. **5000 hrat232C 2260 hrat232°C *\n\\end{caption}\n\nA beneficial effect of the thermal exposure was experienced for the LARC-IA system. Significant increases in LSS were obtained for 177, 204 and 232°C tests (177°C, from 25.5 to 29.4 MPa; 204°C, 21.1-26.2 MPa; and 232°C, 9.1-14.0 MPa). However, RT strengths decreased from 31.8 to 27.8 MPa. Further exposure at 204°C for 5000 h resulted in no change in LSS for tests conducted at 204°C (1000 h, 26.2 MPa; 5000 h, 26.9 MPa).\n\nAfter 1000 h at 204°C, the LSSs for the LARC-IA (5% PA) system decreased from 44.2 to 35.0 MPa for the RT tests and from 36.6 to 33.4 MPa for 177°C tests. LSSs at 204 and 232°C were unchanged. After the exposure for 5000 h, the RT strength decreased to 29.0 MPa, the 177°C strength decreased slightly to 30.9 MPa, the 204°C strength remained the same and the 232°C was slightly lower at 7.9 MPa. These LSSs, except for the 232°C test, are excellent considering the time and temperature of exposure. Comparing these results with LARC-TPI data, the strengths for LARC-IA (5% PA) are higher at RT, 177°C and 204°C but significantly lower than LARC-TPI at 232°C, probably due to the higher Tg of the LARC-TPI polymer.\n\nThe addition of aluminum powder filler to the 5% PA endcapped system resulted in an adhesive that retained the original strengths at all test temperatures after the 1000 h exposure. After 5000 h, the RT strength decreased from 43.8 to 34.1 MPa, the 177°C strength decreased from 33.2 to 28.3 MPa, the 204°C strength decreased from 28.7 to 24.5 MPa and the 232°C strength decreased from 13.6 to 7.7 MPa. The strengths retained after 5000 h are still excellent except for that tested at 232°C (7.7 MPa). Comparison of the 5000 h aging data of LARC-IA (5% PA) 50% Al with the LARC-TPI data indicates higher strengths at RT and 177°C, essentially the same strength at 204°C, and a lower strength at 232°C. The higher strength of LARC-TPI at 232°C is again probably due to its higher Tg.\n\nThe LARC-TPI adhesive data which had been reported earlier [2] indicated some increase in the strengths at 204 and 232°C after thermal exposure. As noted, the LSS test at 232°C was conducted after 2260 h at 232°C and still resulted in a significant increase (17.5-23.3 MPa). The strengths for the 232°C tests are much higher for the LARC-TPI than for the variations of LARC-IA primarily due to a higher Tg for LARC-TPI. The initial and 1000 h exposure strengths at RT, 177 and 204°C are higher for LARC-IA (5% PA) 50% Al than the LARC-TPI.\n\nLap shear test failures after thermal exposure were primarily cohesive except for the RT test of LARC-IA and the 232°C tests for LARC-IA (5% PA) for 1000 and 5000 h exposure which were thermoplastic (plastic deformation of the adhesive) and a combination of cohesive/interfacial, respectively.\n\n\\begin{title}\n3.4. 72-h Water boil exposure\n\\end{title}\n\nLap shear specimens were exposed to a 72-h water boil to determine the bonded system's resistance to a high humidity type condition. LSS test results are shown in Fig. 8 and given in Table 6 for the LARC-IA polymers and compared with earlier reported [2] results for LARC-TPI.\n\nMost of the adhesive systems show greatly reduced strengths for all test temperatures after the water boil exposure. Water is known to plasticize most polymers and, therefore reduce their strength properties. LARC-IA and LARC- IA (5% PA) provide results similar to the LARC-TPI. Strength retention for these\n\n\\begin{caption}\nwith LARC-IA adhesives and LARC-TPI adhesive exposed to a 72-h water boil.\n\\end{caption}\n\n\\begin{caption}\nTable 6. LSS results of a 72-h water boil for bonded Ti-6Al-4V\n\\end{caption}\n\n\\begin{table}\n| Adhesivea | Number of specimens | Test temperature C(F) | Average LSS MPa (psi) | Range of LSS MPa (psi) | Primary failure modeb |\n|:-----------------------------|:----------------------|:------------------------|:------------------------|:-------------------------|:------------------------|\n| LARC-IA | 4 | RT(RT) | 30.1 (4370) | 25.6-33.8 (3720-4900) | Co |\n| LARC-IA | 4 | 177(350) | 20.4(2960) | 19.8-20.7(2870-3000) | Co |\n| LARC-IA | 4 | 204(400) | 9.4 (1360) | 8.4-10.0(1220-1450) | Co |\n| LARC-IA | 4 | 232(450) | 3.4(500) | 2.8-4.1(410-600) | 1 |\n| LARC-IA (5%PA) | 4 | RT(RT) | 34.2(4960) | 32.9-35.4 (4780-5130) | Co |\n| LARC-IA (5%PA) | 4 | 177(350) | 21.7(3150) | 21.3-22.3 (3090-3230) | Co |\n| LARC-IA (5%PA) | 4 | 204(400) | 7.2(1040) | (560-1330) 3.9-9.2 | 1 |\n| LARC-IA (5%PA) | 4 | 232(450) | 3.8(550) | 3.0-4.6 (440-660) | I |\n| LARC-IA (5%PA) 50% Al powder | 4 | RT(RT) | 36.4(5280) | 35.6-37.9 (5160-5500) | Co |\n| LARC-IA (5%PA) 50% Al powder | 4 | 177(350) | 22.2 (3220) | 20.0-25.0(2900-3620) | Co |\n| LARC-IA (5%PA) 50% Al powder | 4 | 204(400) | 11.0 (1590) | 8.9-14.2(1290-2060) | Co |\n| LARC-IA (5%PA) 50% Al powder | 4 | 232(450) | 7.0(1020) | 5.6-7.6(810-1100) | Co |\n| LARC-TPI | 4 | RT(RT) | 27.8(4030) | 26.7-28.8 (3870-4180) | Co |\n| LARC-TPI | 4 | 177(350) | 19.7(2860) | 19.1-20.3 (2760-2950) | Co |\n| LARC-TPI | 4 | 204(400) | 10.1 (1470) | 9.4-11.0(1360-1600) | Co |\n| LARC-TPI | 4 | 232(450) | 5.2(760) | 4.6-5.6 (670-810) | Co |\n\\end{table}\n\nbonding conditions: 2.07 MPa (300 psi) pressure from start, heating rate of 8°C/min ( 14°F/min), RT-+ 371°C (700°F), held 1 h. b Co = cohesive; I = interfacial. C Data previously reported by our laboratory. Bonding conditions: 207 MPa; 343°C held 1 h.\n\ntwo systems ranged from 77 to 95% at RT, 59 to 80% at 177°C, 25 to 40% at 204°C and 38 to 41% at 232°C. LARC-TPI retained 84, 67, 40 and 30% at RT, 177, 204 and 232°C respectively. The LARC-IA (5% PA) 50% Al powder bonded system was similar to all others; however, it retained 52% of its original strength at 232°C or 7.0 MPa. The aluminum additive provided a slight improve- ment in strength retention at the 232°C test temperature.\n\n\\begin{title}\n3.5. Flatwise tensile strength and fracture energy\n\\end{title}\n\nResults of the FWT strength tests for LARC-IA (5% PA) with and without aluminum powder filler are given in Table 7 along with the fracture energy,\n\nAlthough the FWT strengths are less than expected, ranging from 1.7 to 2.6 MPa, however, they show promise since this was a preliminary attempt to prepare the specimens and not an optimization of tape preparation and bonding con- ditions. Also, core cell size influences the bond strength obtained, the smaller the cell size, the greater the contact bond area and, therefore, the greater strength. The cell size of the titanium core used to prepare these specimens was rather large, 0.95 cm. Failures were between the core cell edges and the adhesive. Minimal filleting was observed around the core cells. No apparent improvement in strength was obtained as a result of aluminum powder addition.\n\nThe fracture energy of LARC-IA (5% PA) of two specimens, 560 and 438 J/ml, was approximately double that of the LARC-IA (5% PA) 50% Al system, 298 and 210 J/ml, as determined by the DCB technique at RT. Although these Go\n\n\\begin{title}\nD.J. Progar and T. L. St. Clair\n\\end{title}\n\n\\begin{caption}\nTable 7. Flatwise tensile strength and critical fracture energy\n\\end{caption}\n\n\\begin{table}\n| Adhesive | FWT MPa (psi) | $G1cfr}$ /in. 1b J/m2$ in.2$ |\n|:----------------|:----------------|:-------------------------------|\n| LARC-IA (5% PA) | 1.7(247) | 560(3.2) |\n| | 2.6 (378) | 438(2.5) |\n| LARC-IA (5% PA) | 2.3(340) | 298 (1.7) |\n| 50% Al powder | 2.4(355) | 210 (1.2) |\n\\end{table}\n\n\"Specimens were fabricated from Ti-6A1-4V facesheets [0.05 cm (0.020 in.)] and Ti core [0.95 cm (0.37 in.) cell size] given a Pasa-Jell 107 surface treatment before priming and bonding.\n\nbSpecimens were fabricated form Ti-6AI-4V 0.13 cm (0.050 in.) thick and given a Pasa-Jell 107 surface treatment before priming and bonding.\n\nvalues for LARC-IA (5% PA) are not as high as desired, they are higher than most epoxies and bismaleimides but less than polyimidesulfones [8].\n\n\\begin{title}\n3.6. Film properties and solvent resistance\n\\end{title}\n\nThe mechanical properties of LARC-IA films were obtained according to ASTM D882. Results are given in Table 8. Overall mechanical properties are in line with other aromatic polyimides with flexible backbones. The tensile strength, which is quite sensitive to molecular weight, is found to be almost 122 MPa at RT and the modulus was a nominal 3300 MPa.\n\nThe mechanical properties decrease significantly at higher temperatures or as the Tg of the material is approached. Elongation generally increases with increased\n\n\\begin{caption}\nTable 8. LARC-IA film propertiesa\n\\end{caption}\n\n\\begin{table}\n| Sample # | Yield strength MPa (ksi) | Tensile strength MPa (ksi) | Tensile modulus MPa (ksi) | Elongation % |\n|:------------------------|:---------------------------|:-----------------------------|:----------------------------|:------------------------|\n| Test temperature, RT | Test temperature, RT | Test temperature, RT | Test temperature, RT | Test temperature, RT |\n| 1 | 76.5 (11.1) | 114.4 (16.6) | 3033(440) | 5 |\n| 2 | 73.1 (10.6) | 120.0(17.4) | 2937(426) | 6 |\n| 3 | 68.9 (10.0) | 123.4 (17.9) | 3199(464) | 7 |\n| 4 | 59.3(8.6) | 118.6 (17.2) | 4123(598) | 6 |\n| 5 | 80.6 (11.7) | 133.0 (19.3) | 3385(491) | 7 |\n| Avg | 71.7(10.4) | 121.9 (17.7) | 3337(484) | 6 |\n| Test temperature, 200*℃ | Test temperature, 200*℃ | Test temperature, 200*℃ | Test temperature, 200*℃ | Test temperature, 200*℃ |\n| 6 | 35.2 (5.1) | (7.0) 48.2 | 1972 (286) | 6 |\n| 7 | 44.1 (6.4) | 53.1 (7.7) | 2110(306) | 23 |\n| 8 | 35.8 (5.2) | 45.5 (6.6) | 2110(306) | 6 |\n| 9 | 37.2 (5.4) | 48.2 (7.0) | 1834(266) | 9 |\n| 10 | 36.5 (5.3) | 46.2 (6.7) | 2041 (296) | 23 |\n| Avg | 37.8 (5.5) | 48.2 (7.0) | 2013(292) | 13 |\n\\end{table}\n\nGlass transition temperature, Tg=243°C (469°F). ° An amorphous, transparent, amber film 0.04 mm (1.6 mils) thick.\n\n\\begin{title}\nA new flexible backbone polyimide adhesive\n\\end{title}\n\ntemperature. All measured values are reasonable and typical of linear aromatic polyimides.\n\nThe resistance to several typical organic solvents is shown in Table 9. Visual observation of the film after a 72-h period soak in the solvents showed that methylene chloride was the only solvent that affected the LARC-IA film as indicated by the curling of the film and the increase in Tg. All others retained the same Tg and film appearance..\n\n\\begin{caption}\nTable 9. LARC-IA solvent resistance'\n\\end{caption}\n\n\\begin{table}\n| ('Solvent', 'Solvent') | ('Visual observation', 'Visual observation') | ('T after exposure,C(F)', 'DSC') | ('T after exposure,C(F)', 'TMA') |\n|:-------------------------|:-----------------------------------------------|:-----------------------------------|:-----------------------------------|\n| None | 一 | 243(469) | 一 |\n| Methylene chloride | Curling | 256(493) | 250(482) |\n| Diglyme | No change | 242(468) | 240(464) |\n| Dimethyl acetamide | No change | 243(469) | 242(468) |\n| m-cresol | No change | 242(468) | 241(466) |\n| N-methyl-2-pyrrolidone | No change | 243(469) | 239(462) |\n\\end{table}\n\na Conducted at room temperature for 72 h. Color-amorphous, transparent, amber film. Dielectric constant 3.06 at 10 GHz.\n\n\\begin{title}\n3.7. Polyimidelgraphite composite\n\\end{title}\n\nComposites were fabricated from LARC-IA (5% PA) polyimide and AS4, 12K graphite fibers. Results of mechanical properties testing (ASTM D790) are given in Table 10. No attempt was made to optimize the processing conditions when fabricating the composite. The composite was laid-up as a unidirectional, 10 ply (= 1 .75 mm thick) configuration (nominal 40% resin by volume fraction). Fabri- cation conditions were: 1 h heat up, 2.07 MPa (300 psi) pressure applied at 252°C (485°F); continued heating to 349°C (660°F), held for 1 h and cooled under pressure.\n\n\\begin{caption}\nTable 10. LARC-IA (5% PA)/AS4, 12K (polyimide/graphite) composites a\n\\end{caption}\n\n\\begin{table}\n| Sample | Flex.Str. GPa (ksi) | Flex. Mod. GPa (Msi) |\n|:---------|:----------------------|:-----------------------|\n| 1 | 1.47 (213) | 95.8 (13.9) |\n| 2 | 1.23 (178) | 98.6 (14.3) |\n| Avg | 1.35 (196) | 97.2 (14.1) |\n\\end{table}\n\naUnidirectional, 10 ply, -1.75 mm (0.069 in.) thick; fabrication conditions: 1 h heat-up, 349°C (660°F) for 1 h, pressure 2.07 MPa (300 psi) applied at 252°C (485°F), cool under pressure.\n\n\\begin{title}\n4. SUMMARY\n\\end{title}\n\nThe synthesis and evaluation of a new linear, aromatic, thermoplastic polyimide, prepared from oxydiphthalic anhydride and 3,4'-oxydianiline and identified as LARC-IA, have been performed. The flow properties were optimized by con- trolling the molecular weight by use of a monofunctional anhydride, phthalic anhydride (PA). The polymer, prepared from physiologically safe and inexpensive monomers, was of interest as a possible substitute or replacement for existing expensive and possibly carcinogenic monomers used to prepare commercially available polymers.\n\nThe polymer, a high temperature thermoplastic adhesive, was evaluated using lap shear strength (LSS) tests involving adhesive tape preparation, bond condition optimization, endcapping optimization for improved flow, thermal exposure and water boil tests. A comparison was made with LARC-TPI data previously generated in our laboratory and reported earlier.\n\nLimited studies were conducted to determine mechanical properties and solvent resistance of films, composite mechanical properties, flatwise strength of adhesively bonded specimens and fracture energy of the bonded DCB specimens.\n\nThe 5% PA endcapped polymer provided the best compromise of the three polymers prepared and evaluated to optimize flow and strength properties. The addition of aluminum powder filler to the LARC-IA (5% PA) polymer enhanced the control LSS at 232°C and improved strength retention after 1000 h exposure at 204°C and a 72-h water boil. After 5000 h, the test results were essentially the same with or without the aluminum powder.\n\nPreliminary results of the flatwise tensile strength tests indicate promise for the adhesive but further improvement may be achieved with refined processing procedures.\n\nFracture energy, determined by the double cantilever beam technique for LARC-IA (5% PA) with and without aluminum powder filler, was higher than most epoxies and bismaleimides but less than the polyimidesulfones.\n\nThe LARC-IA film mechanical properties obtained were typical of linear aromatic polyimides. Film mechanical properties decreased when the film was tested near the Tg at 200°C.\n\nLARC-IA film was resistant to degradation when exposed to most of the solvents investigated, i.e. diglyme, dimethyl acetamide, m-cresol and N-methyl-2- pyrrolidone. Methylene chloride produced an increase in T9 as well as caused the film to curl after the 72-h soak.\n\nPreliminary mechanical property measurements for a 10 ply, unidirectional LARC-IA (5% PA)/AS4, 12K composite indicates promise [flexural modulus of 1.35 GPa (196 Msi)] and improvements should be obtainable with further optimization studies.\n\nThe new polyimide, LARC-IA, which is 'safe' and potentially inexpensive, shows excellent promise as an adhesive, film and composite matrix; and compares favorably with LARC-TPI for future applications in the aerospace and other industries.\n\n\\begin{title}\nREFERENCES\n\\end{title}\n\n1. A. K. St. Clair and T. L. St. Clair, Proc. 26th Nat. SAMPE Symp. 26, 165-178 (1981).\n\n2. D. J. Progar and R. A. Pike, Int. J. Adhesion Adhesives 8, 25-32 (1988).\n\n\\begin{title}\nA new flexible backbone polyimide adhesive\n\\end{title}\n\n3. D. J. Progar, T. L. St. Clair, H. D. Burks, C. R. Gautreaux, A. Yamaguchi and M. Ohta, Preprints, 21st Int. SAMPE Tech. Conf 21, 544-557 (1989).\n\n4. S. Mall, J. Adhesion 20, 251-260 (1987).\n\n5. D. J. Progar and T. L. St. Clair, J. Adhesion 21, 35-57 (1987).\n\n6. W. D. Ross, J. E. Noble, J. A. Gridley, J. M. Fullenkamp, M. T. Wininger and J. A. Graham, NASA CR 166085 (Feb. 1983).\n\nD. J. Progar and T. L. St. Clair, Preprints, 7th Nat. SAMPE Tech. Conf. 7, 53-67\n\n8. N. J. Johnston and P. M. Hergenrother, Preprints, 32nd Int. SAMPE Symp. and Exhibition 32, 1400-1412 (1987).\n\n" + }, + { + "abbreviations": [ + { + "abbreviation": "PMDA" + } + ], + "csv": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/label_data/10.1002/pol.1969.150071023.csv", + "golden_label": [ + { + "abbreviation": "PMDA", + "full_name": "pyromellitic dianhydride", + "smiles": "O=c1oc(=O)c2cc3c(=O)oc(=O)c3cc12" + } + ], + "path": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/pdf_data/10.1002/pol.1969.150071023_uniparser.json", + "pdf": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/pdf_data/10.1002/pol.1969.150071023.pdf", + "text": "New High-Temperature Polymers. XIII. Thermally Stable Benzheterocycle-lmide and -Arni.de Copolymers of Limited Order\n\nRodia, in a recently issued patent,l has described the synthesis of some film-forming polybenzophenoneimides derived from unsymmetrical benzoxazole, bensothiazole, and benzimidazole diamines (Table I). Thermal properties of the films were not given,\n\n\\begin{caption}\nTABLE I Unsymmetrical Benzheterocyclic\n\\end{caption}\n\n\\begin{table}\n| Oiisy miiiiecrtcar DeiizlieteiUcyciic Diainines | Oiisy miiiiecrtcar DeiizlieteiUcyciic Diainines |\n|:--------------------------------------------------|:----------------------------------------------------|\n| Compound | Melting point,Cb |\n| A | 257-259 5-Amino-2-(p-aminophenyl)aminobenzoxazolec |\n| 5-Amino-2-(m-aminophenyl)aminobenzoxazolec B | 235-238 |\n| C 5-Amino-2-(m-aminophenyl)aminobenzothiazole° | 232-234 |\n| D | 258-260d 5(6)-Amino-2-(m-aminophenyl)benzimidazolec |\n| E 5(6)Amino-2-(p-aminophenyl)benzimidazole | 235-236e |\n| 6-Amino-2-(p-aminophenyl)quinoxaline F | 213-215 |\n\\end{table}\n\n-1--Y.--L---1-12\n\n6 Melting points are uncorrected.\n\nb c These diamines were reacted by Elodia' with 3,3'-4,4'-benzophenone dianhydride\n\nd Lit.2 mp 157-159OC; polymer for laminating resins was prepared from this diamine\n\nData of Kym.'\n\n\\begin{molecule}\nO=C1OC(=O)[Ar]12C(=O)OC2=O\n\\end{molecule}\n\n\\begin{molecule}\nNC1C=C2C(*C(=N2)C2C=CC(N)=CC=2)=CC=15:X\n\\end{molecule}\n\n\\begin{molecule}\n*NC1C=C2C(*C(=N2)C2C=CC(NC(C([Ar](C(=O)O)C(=O)*)=O)(C)C)=CC=2)=CC=10:6:X22:\n\\end{molecule}\n\n\\begin{molecule}\n*C1C=C2C(*C(=N2)C2C=CC(N3C(=O)*4(C(=O)N(*)C4=O)C3=O)=CC=2)=CC=10:5:X15:Ar19:\n\\end{molecule}\n\n\\begin{molecule}\nCc1ccc(C(=O)c2ccc(C)c(C)c2)cc1C\n\\end{molecule}\n\n\\begin{molecule}\nCc1cc(C)c(C)cc1C\n\\end{molecule}\n\n1\n\n\\begin{molecule}\nCOC#*3:X\n\\end{molecule}\n\n\\begin{caption}\n3028 JOURNAL OF POLYMER SCIENCE: PART A-1, VOL. 7\n\\end{caption}\n\n\\begin{caption}\nFilms of Benzheterocycle-imide Copolymers of Limited Order TABLE II\n\\end{caption}\n\n\\begin{table}\n| | | | ginh of | ginh of | ginh of | Melt transition | Decom- position |\n|:----|:------------------|:--------------------------------|:---------------------|:-------------------------------------|:------------------|:------------------|:------------------|\n| No. | Type of copolymer | Benzheterocyclic unit | amic acid precursora | Film characteristics Heated at 145°℃ | Annealed at 300°℃ | Melt transition | Decom- position |\n| I | Pyromellitemide | Cc1cccc(-c2nc3cc(C)ccc3o2)c1 | 0.90 | S1. brittle | Strong | — | 570 |\n| II | Pyromellitemide | Cc1ccc(-c2cc3cc(C)ccc3o2)cc1 | 一 | S1. brittle | Strong | 575 | 575(575)d |\n| III | Pyromellitemide | Cc1ccc2sc(-c3cccc(C)c3)nc2c1 | 0.71 | Sl. brittle | Strong | 570 | 570 |\n| IV | Pyromellitemide | Cc1cccc(-c2nc3cc(C)ccc3[nH]2)c1 | 0.63 | SI. brittle | Flexible | 540 | 550 |\n| V | Pyromellitemide | Cc1ccc(-c2nc3cc(C)ccc3[nH]2)cc1 | — | Weak, brittle | Sl. brittle | - | 一 |\n| VI | Pyromellitemide | Cc1ccc(-c2cnc3cc(C)ccc3n2)cc1 | 1.63 | SI. brittle | Tough, strong | 570 | 605 |\n\\end{table}\n\n\\begin{molecule}\nCc1ccc(-c2cc3cc(C)ccc3o2)cc1\n\\end{molecule}\n\n\\begin{molecule}\nCc1ccc(-c2nc3cc(C)ccc3[nH]2)cc1\n\\end{molecule}\n\n\\begin{molecule}\nCc1ccc(-c2cnc3cc(C)ccc3n2)cc1\n\\end{molecule}\n\n\\begin{molecule}\nCc1cccc(-c2nc3cc(C)ccc3o2)c1\n\\end{molecule}\n\n\\begin{molecule}\nCc1ccc2sc(-c3cccc(C)c3)nc2c1\n\\end{molecule}\n\n\\begin{molecule}\nCc1cccc(-c2nc3cc(C)ccc3[nH]2)c1\n\\end{molecule}\n\n\\begin{table}\n| VII | 3,3',4,4'-Benzophenoneimide | Cc1cccc(-c2nc3cc(C)ccc3o2)c1 | 2.42 | Flexible | Tough | (305)e | 570 |\n|:------|:------------------------------|:--------------------------------|:-------|:------------|:--------------|:---------|:------|\n| VIII | 3,3'4,4'-Benzophenoneimide | Cc1ccc(-c2nc3cc(C)ccc3o2)cc1 | 1.00 | Sl. brittle | Tough | ~560 | 570 |\n| IX | 3,3',4,4'-Benzophenoneimide | Cc1ccc2sc(-c3cccc(C)c3)nc2c1 | 1.46 | Flexible | Strong | (350)e | 575 |\n| X | 3,3',4,4'-Benzophenoneimide | Cc1cccc(-c2nc3cc(C)ccc3[nH]2)c1 | 0.75 | Brittle | Flexible | (350)。 | 525 |\n| XI | 3,3',4,4'-Benzophenoneimide | Cc1ccc(-c2cnc3ccc(C)cc3n2)cc1 | 1.31 | Sl. brittle | Tough, strong | 575 | 575 |\n\\end{table}\n\n\\begin{molecule}\nCc1ccc(-c2cnc3ccc(C)cc3n2)cc1\n\\end{molecule}\n\n\\begin{molecule}\nCc1ccc(-c2nc3cc(C)ccc3o2)cc1\n\\end{molecule}\n\n\\begin{molecule}\nCc1ccc2sc(-c3cccc(C)c3)nc2c1\n\\end{molecule}\n\n\\begin{molecule}\nCc1cccc(-c2nc3cc(C)ccc3o2)c1\n\\end{molecule}\n\n\\begin{molecule}\nCc1cccc(-c2nc3cc(C)ccc3[nH]2)c1\n\\end{molecule}\n\nn nitrnoan rata = 2noC./r Determined at 30°C on a solution of 0.5 g polymer dissolved in 100 ml DMAc. b Incinient. meltino nhonomenon as determined hr \n\nair. heated DTA\n\n Softening point observed by placing film on a heated surface. d The value given in parentheses was obtained in air. m\n\n\\begin{title}\n3030 JOURNAL OF POLYMER SCIENCE: PART A-I, VOL. 7\n\\end{title}\n\nhowever, except for the statement that the films “retained strength and toughness even after heating to 370°C for 2 hr in air.” More recently, the synthesis of a benzimidazole- benzophenoneimide polymer useful as a laminating resin was reported.2\n\nIn the present work the synthesis and thermal properties of both polypyromellitimides and polybenzophenoneimides (Table 11) derived from unsymmetrical diamines in- corporating four different benzheterocyclic units are described. All polymers of the type reported here are of the type which we prefer to call polymers of limited order? Because of the lack of symmetry in the diamines used, the diamine moieties can enter the polymer chain in the manner shown or in the reverse manner. Consequently, the polymers are less ordered than those derived from similar symmetrically structured diamines;6J they are ordered to the extent that there is preferential reactivity of one amino group over the other in the diamine. For the case of complete order, the reac- tions may be illustrated by the scheme (2).\n\n\\begin{molecule}\nc12cc3c(=O)oc(=O)c3cc1c(=O)oc2=O\n\\end{molecule}\n\n\\begin{molecule}\nNc1ccc(-c2nc3cc(N)ccc3o2)cc1\n\\end{molecule}\n\n\\begin{molecule}\nNc1ccc2oc(-c3ccc(NC(=O)c4cc(C(=O)O)c(C(=O)O)cc4C(=O)Nc4ccc(-c5nc6cc(N)ccc6o5)cc4)cc3)nc2c1\n\\end{molecule}\n\n\\begin{molecule}\nNc1ccc(-c2nc3cc(NC(=O)c4cc(C(=O)O)c(C(=O)Nc5ccc6oc(-c7ccc(N)cc7)nc6c5)cc4C(=O)O)ccc3o2)cc1\n\\end{molecule}\n\n\\begin{molecule}\nc12cc3c(cc1COC2=O)C(=O)OC3=O\n\\end{molecule}\n\nOrdered benzoxazole-amide acid copolymer\n\n\\begin{molecule}\n*C=O0:\n\\end{molecule}\n\nOrdered honznvaznle.imide cnnnlumer\n\nHowever, no experimental evidence has been obtained which confirms the presence of such ordering as would result from the preferential formation of either Y or Z. Indeed, the polymer properties indicate that the degree of order from such preferential reaction, if present at all, is relatively low.\n\nBut the polymers do exhibit a form of order, inasmuch as there is a regular sequence of the benzheterocycle and imide units along the chain, i.e., the chains do not consist of alternating blocks of polybenzheterocycles and polyimides.\n\nIt is not surprising that the benzophenoneimide polymers have lower softening points than the corresponding polypyromellitimides (Table 11). The flexible >C = 0 linkage\n\n\\begin{token}\n19\\\n\\end{token}\n\n\\begin{caption}\nNOTES\n\\end{caption}\n\n\\begin{caption}\nFig. 1. Programmed DTA of fiber of I1 (in nitrogen, rate = 20\"C/min).\n\\end{caption}\n\n\\begin{caption}\nFig. 2. TGA of polymer of I1 in nitrogen and in air.\n\\end{caption}\n\ncoupled with the random placement of the diamine moiety in the repeat unit undoubtedly accounts for the low softening points observed for certain examples of these polymers; e.g., VII, IX, and X. The good packing8 which can be achieved by the relatively com- pact and rigid pyromellitimide units apparently overcomes to a large extent any tendency of the polymers containing pyromellitimide units to soften because of any lack of order in the placement of the diamine moiety in t,he polymer repeating unit.\n\nFor both the pyromellitimide and benzopherioneimide copolymers of limited order, the thermal stability is surprisingly good in view of the disorder present in these poly- mers. The results of thermal analyses are shown in Table I1 and a typical differential t-hermal analysis (DTA) curve of fiber of I1 is shown in Figure 1. A typical thermo- gravimetric analysis (TGA), Figure 2, shows that polymer I1 retains its weight equally well in nitrogen or air to about 600°C.\n\n\\begin{title}\n3032 JOURNAL OF POLYMER SCIENCE: PART A-1, VOL. 7\n\\end{title}\n\nThe range of decomposition temperatures for the benzheterocycie-imide copolymers is remarkably narrow, considering the variations in structure (Table 11). This character- istic of heterocycle-imide copolymers was noted by us earlier for completely ordered heterocycle-imide copolymers6 and is greatly different from that of heterocycle-amide copolymers in which the decomposition temperature is highly dependent on structure. Interestingly, in the series of benzheterocycle-imide copolymers studied the temperature at which serious degradation of the imide bond begins wfts not found to be dependent on the softening point of the polymer, as is shown by the fact that many of the benz- heterocycle-benzophenone-imides show softening near 30OoC, but decompose at no lower a temperature than the benzheterocycle-pyromellitimides which do not soften below 540-575OC. This contrasts sharply with the temperature of thermal degradation of tbe amide bond of high melting aromatic polyamides. The degradation temperature of such polyamides was found to be highly dependent on the softening point of the polymer.' It is believed that in the case of aromatic polyimides, the relative insensi- tivity of the decomposition temperature to the softening temperature will prove to be quite general. Also noteworthy is the narrow melting point range for the group of benzheterocycle-pyromellitimide copolymers (Table 11).\n\nTo gauge the end-use performance of a typical copolymer, film of I1 was heabaged in air at elevated temperatures along with film of a commercially important polyimide, the polypyromellitimide of bis(4aminophenyl) ether (XII);O the results- obtained\n\n\\begin{molecule}\n*c1ccc(Oc2ccc(-n3c(=O)c4cc5c(=O)n(*)c(=O)c5cc4c3=O)cc2)cc1\n\\end{molecule}\n\n\\begin{legend}\nXI1\n\\end{legend}\n\nare given in Table 111. The changes in weight for films of I1 and XI1 on isothermal heabaging in air are shown in Figure 3.\n\nFdms of all of the benzheterocycle-imide polymers I-XI have good physical properties and most exhibit outstanding thermal stability. On the other hand, fibers (25 den/ filame'nt) of 11, although highly lustrous and well-collapsed, have relatively poor physical properties: tenacity, 2.8 g/den; elongation, 25%; initial modulus, 130 g/den; lack of complete order undoubtably is the dominant factor responsible for the poor fiber properties, since fibers of excellent tensile strength have been prepared from completely ordered benzheterocycle-imide copolymers1° which contain the same type structural units used for this benzheterocycle-imide copolymer of limited order. On the other hand, the imperfect order may actually be responsible for the good film properties\n\n\\begin{caption}\nTABLE I11 Comparative Effects of Heat Aging of a Benzheterocyclepyromellitimide Polymer and a Simple Pyromellitimide in Air8\n\\end{caption}\n\n\\begin{table}\n| Exposure conditions | Exposure conditions | Effect on Film | Effect on Film |\n|:----------------------|:----------------------|:-----------------|:-----------------------|\n| Temp, C | Time, hr | Ib | XIIc |\n| 350 | 100 | No change | Dark, brittle |\n| 350 | 200 | SI. brittle | V. brittle |\n| 375 | 48 | No change | Dark, brittle |\n| 375 | 120 | No change | Carbonized, fell apart |\n\\end{table}\n\n* Comparative tests were run side by side. b A benzoxaeole-pyromellitimide polymer (Table 11). 0 Polypyromellitimide of bis(4aminophenyl)ether.\n\n\\begin{caption}\nNOTES\n\\end{caption}\n\n\\begin{caption}\nFig. 3. Weight retention at 350'C in air for films of a polyheterocycles-imide (11) and a simple polyimide (XII).\n\\end{caption}\n\nobserved for this class of polymers, contributing improved flexibility and retardiug excessive crystallinity and hence embrittlement.\n\nAmidetype polymers (Table IV) also were prepared in addition to the benaheterc- cycle-imide copolymers of limited order from the diamines of Table I. The thpmal stability of films of these polymers tended to be considerably lower than that of the corresponding imide polymers: not only were the softening points and decomposition temperatures lower, but the thermooxidative stability above t,he softening point in air was appreciably lower, as has been noted generally in the comparison of ordered heterocycle-imide copolymers with polyamide~.~ In order to compare directly the ef- fect of ordering the diamine moiety in a polyamide as opposed to randomly placing it, XXIII w&s prepared and its softening point compared to that of XXIV.11 Although XXIII and XXIV contain the same structural units, XXIV showed a mp 465\"C, compared with mp 360°C for XXIII.\n\n\\begin{molecule}\n*NC1C=C(C2OC(C3C=CC(NC(C(C4C=CC(C(=O)*)=CC=4)=O)(C)C)=CC=3)=NN=2)C=CC=10:21:\n\\end{molecule}\n\n\\begin{legend}\nXXIII\n\\end{legend}\n\n\\begin{molecule}\n*NC1C=CC(C2OC(C3C=CC(NCC(C4C=C(C(=O)*)C=CC=4)=O)=CC=3)=NN=2)=CC=10:21:\n\\end{molecule}\n\n\\begin{legend}\nxx IV\n\\end{legend}\n\n\\begin{title}\nEXPERIMENTAL\n\\end{title}\n\nThe diamines of Table I were polymerized with pyromellitic dianhydride (PMDA) or 3,3',4,4'-benzophenone dianhydride in either dimethylacetamide (DMAc) or N-methyl pyrrolidonr? (NMP). A typical polymerization is described.\n\n\\begin{caption}\nFilms of Benzheterocycle-Amide Copolymers of Limited Order TABLE IV\n\\end{caption}\n\n\\begin{table}\n| No. | Structure | minh | | Color |\n|:------|:-----------------------------------------------------------------------------------------------------|:-------|:-----|:----------|\n| XIII | O=C(C1C=C(S(=O)(=O)NC2C=C(C3OC4C(=CC(=CC=4)N*)N=3)C=CC=2)C=CC=1)*21:29: | 2.49 | ~350 | Colorless |\n| XIV | *C(C1C=CC(C(NC2C=C(C3OC4C(=CC(=CC=4)N*)N=3)C=CC=2)(C)C)=CC=1)=O0:20: | 2.35 | ~360 | Colorless |\n| XV | CCC(C)(C(=O)Nc1ccc(-c2nc3cc(N)ccc3o2)cc1)c1cccc(C(C)=O)c1 | 2.38 | ~400 | Colorless |\n\\end{table}\n\n\\begin{molecule}\n*C(C1C=CC(C(NC2C=C(C3OC4C(=CC(=CC=4)N*)N=3)C=CC=2)(C)C)=CC=1)=O0:20:\n\\end{molecule}\n\n\\begin{molecule}\nO=C(C1C=C(S(=O)(=O)NC2C=C(C3OC4C(=CC(=CC=4)N*)N=3)C=CC=2)C=CC=1)*21:29:\n\\end{molecule}\n\n\\begin{molecule}\nCCC(C)(C(=O)Nc1ccc(-c2nc3cc(N)ccc3o2)cc1)c1cccc(C(C)=O)c1\n\\end{molecule}\n\n\\begin{table}\n| XVI | CC[C@@](C)(Nc1cccc(-c2nc3cc(N)ccc3s2)c1)C(=O)c1ccc(C(=O)O)cc1 | 1.28 | 335c | Light yellow |\n|:------|:-----------------------------------------------------------------------------------------------|:-------|:-------|:---------------|\n| XVII | CC(=O)c1cccc(C(=O)Nc2cccc(-c3nc4cc(N)ccc4[nH]3)c2)c1 | 0.68 | ~300 | Light yellow |\n| XVIII | CC(=O)c1ccc(C(=O)Nc2cccc(-c3nc4cc(N)ccc4[nH]3)c2)cc1 | 2.47 | 400 | Off-white |\n| XIX | C1C(N)=CC2=NC(C3=CC=C(NC(C)(C)C(=O)C4=CC=CC(C(=O)*)=C4)C=C3)=C(N)N=C2C=124: | | 一 | Brown |\n| XX | *C(=O)C1=CC=C(C(=O)CNC2=CC=C(C3=NC4=CC=C(NCC)C=C4N=C3*)C=C2)C=C10:28:R | | — | Purple |\n\\end{table}\n\n\\begin{molecule}\nCC[C@@](C)(Nc1cccc(-c2nc3cc(N)ccc3s2)c1)C(=O)c1ccc(C(=O)O)cc1\n\\end{molecule}\n\n\\begin{molecule}\nCC(=O)c1ccc(C(=O)Nc2cccc(-c3nc4cc(N)ccc4[nH]3)c2)cc1\n\\end{molecule}\n\n\\begin{molecule}\n*C(=O)C1=CC=C(C(=O)CNC2=CC=C(C3=NC4=CC=C(NCC)C=C4N=C3*)C=C2)C=C10:28:R\n\\end{molecule}\n\n\\begin{molecule}\nC1C(N)=CC2=NC(C3=CC=C(NC(C)(C)C(=O)C4=CC=CC(C(=O)*)=C4)C=C3)=C(N)N=C2C=124:\n\\end{molecule}\n\n\\begin{molecule}\nCC(=O)c1cccc(C(=O)Nc2cccc(-c3nc4cc(N)ccc4[nH]3)c2)c1\n\\end{molecule}\n\n\\begin{caption}\nthe\n\\end{caption}\n\n\\begin{table}\n| No. | Structure | 7inb$ | point, | Color |\n|:------|:---------------------------------------------------------------------------------------------------|:--------|:---------|:------------|\n| XXI | O=C(OC1C=CC(OC2C=CC(S(=O)(=O)NC3C=CC(OC4OC5C(CC(CC5)N*)N=4)=CC=3)=CC=2)=CC=1)C30: | 0.98 | >425 | Brown |\n| XXII | CC(=O)c1cccc(C(=O)Nc2cccc(-c3nc4cc(N)ccc4s3)c2)c1 | 2.06 | —d | Dark browne |\n\\end{table}\n\n\\begin{molecule}\nO=C(OC1C=CC(OC2C=CC(S(=O)(=O)NC3C=CC(OC4OC5C(CC(CC5)N*)N=4)=CC=3)=CC=2)=CC=1)C30:\n\\end{molecule}\n\n\\begin{molecule}\nCC(=O)c1cccc(C(=O)Nc2cccc(-c3nc4cc(N)ccc4s3)c2)c1\n\\end{molecule}\n\nTABLE dissolved in placing endotherm determination\n\nIV 100 ml hot-drawn (15\"C/min employed to of the\n\nml of to the\n\nTo a solution of 9.45 g (0.042 mole) of diamine B in 80 ml. DMAc a t 0°C was added 9.15 g (0.042) mole PMDA. The polymerization was carried out at 0°C for 7 hrs.; the reactants were then allowed to warm to room temperature and stirred overnight. A portion of the light yellow polymer solution was cast to film; the remainder was spun to fiber. The film of I1 was heated at 110°C for 30 min, then at 145'C for 16 hr, and finally at 300°C for 30 min. A tough, flexible film was obtained which could be drawn 1.2X at about 500°C. The film did not soften appreciably when placed on a heated surface at 500°C. (All of the heat treatments were carried out in air.)\n\nFilms of I and 111, prepared as above, could be drawn 2 X and 3 X their original length, respectively, at 400°C. Both I and I11 could be placed on heated surfaces at 500°C for several minutes without discoloration; on longer exposure they turned brown but were still flexible.\n\nPolyamide-heterocycles of limited order were prepared by low temperature poly- condensations such &s that previously described for ordered amide-heterocycle copoly- mers.\" The 2-(m-aminophenyl)-5-(paminophenyl>l,3,4-oxadiazole, mp 234-236(1k2 mp, 239-239.5\"C), used to prepare XXIII, was made by previously published pro- cedures for the synthesis of 1,3,40xadiazole diamines.12\n\nWe wish to express our appreciation to Messrs.H. S. Morgan and J. D. Fowler for the spinning of fibers and to Mr. M. T. Bryant for his excellent technical assistance.\n\n\\begin{title}\nReferences\n\\end{title}\n\n1. J. S. Rodia, U. S. Pat. 3,247,165 (1965); see also U. S. Pat. 3,389,111 (1968).\n\n2. L. W. Frost, G. M. Bower, J. H. Freeman, H. A. Burgman, E. J. Traynor, and C. R. Ruffing, J. Polym. Sci. A-1, 6 , 215 (1968).\n\n3. J. Preston, W. F. Dewinter, and W. L. Hofferbert, Jr., J. Heterocyclic Chem., 6, 119 (1969).\n\n4. 0. Kym, Ber., 32,3537 (1899).\n\n5. J. Preston and It. W. Smith, J. Polym. Sci. B, 4,1033 (1966).\n\n6. J. Preston and W. B. Black, J. Polym. Sci. A-1, 5,2429 (1967).\n\n7. J. Preston, W. F. Dewinter, and W. B. Black, J. Polym. Sci. A-1, 7,283 (1969).\n\n8. It. M. Ikeda, J. Polym. Sci. B, 4,353 (1966).\n\n9. C. E. Sroog, A. L. Endrey, S. V. Abramo, C. E. Berr, W. M. Edwards, and K. L. Oliver, J . Polym. Sci. A , 3, 1373 (1965).\n\n10. J. Preston, W. B. Black, and W. Dewinter, paper presented at American Chemical Society Meeting, 1968; ACS Preprints, 9 (Z), 1165 (1968).\n\n11. J. Preston and W. B. Black, J. Polym. Sci. B, 4,267 (1966).\n\n12. J. Preston, J. Heterocyclic Chem., 2, 441 (1965).\n\nJ. PRESTON W. DEWINTER W. B. BLACK W. L. HOFFERBERT, JR.\n\nChemstrand Research Center, Inc. Durham, North Carolina 27702 Received May 9, 1969 Revised June 9, 1969.\n\n" + }, + { + "abbreviations": [ + { + "abbreviation": "6FDA" + }, + { + "abbreviation": "ODA" + }, + { + "abbreviation": "ODPA" + }, + { + "abbreviation": "PMDA" + }, + { + "abbreviation": "BPDA" + }, + { + "abbreviation": "PDA" + }, + { + "abbreviation": "CBDA" + } + ], + "csv": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/label_data/10.1063/1.4891998.csv", + "golden_label": [ + { + "abbreviation": "6FDA", + "full_name": "4,4'-(hexafluoroisopropylidene)diphthalic anhydride", + "smiles": "O=C1OC(=O)c2cc(C(c3ccc4c(c3)C(=O)OC4=O)(C(F)(F)F)C(F)(F)F)ccc21" + }, + { + "abbreviation": "ODA", + "full_name": "4,4′-Oxydianiline", + "smiles": "Nc1ccc(Oc2ccc(N)cc2)cc1" + }, + { + "abbreviation": "ODPA", + "full_name": "4,4'-Oxydiphthalic anhydride", + "smiles": "O=C1OC(=O)c2cc(Oc3ccc4c(c3)C(=O)OC4=O)ccc21" + }, + { + "abbreviation": "PMDA", + "full_name": "Pyromellitic dianhydride", + "smiles": "O=c1oc(=O)c2cc3c(=O)oc(=O)c3cc12" + }, + { + "abbreviation": "BPDA", + "full_name": "3,3',4,4'-Biphenyltetracarboxylic dianhydride", + "smiles": "O=C1OC(=O)c2cc(-c3ccc4c(c3)C(=O)OC4=O)ccc21" + }, + { + "abbreviation": "PDA", + "full_name": "p-Phenylenediamine", + "smiles": "Nc1ccc(N)cc1" + }, + { + "abbreviation": "CBDA", + "full_name": "Cyclobutanetetracarboxylic dianhydride", + "smiles": "O=C1OC(=O)C2C1C1C(=O)OC(=O)C21" + } + ], + "path": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/pdf_data/10.1063/1.4891998_uniparser.json", + "pdf": "/Users/lianghao/Desktop/dataflow_code/DP_chemical/pdf_data/10.1063/1.4891998.pdf", + "text": "\\begin{title}\nPolarization dependence of thermo-optic coefficients in polyimide films originating from chain orientation and residual thermal stress Yoshiharu Terui and Shinji Ando\n\\end{title}\n\nCitation: Journal of Applied Physics 116, 053524 (2014); doi: 10.1063/1.4891998 View online: http://dx.doi.org/10.1063/1.4891998 View Table of Contents: http://scitation.aip.org/content/aip/journal/jap/116/5?ver=pdfcov Published by the AIP Publishing\n\nArticles you may be interested in Morphology and chain aggregation dependence of optical gain in thermally annealed films of the conjugated polymer poly[2-methoxy-5-(2′-ethylhexyloxy)-p-phenylene vinylene] J. Appl. Phys. 113, 233509 (2013); 10.1063/1.4811532\n\nAnisotropy in thermo-optic coefficients of polyimide films formed on Si substrates Appl. Phys. Lett. 83, 4755 (2003); 10.1063/1.1631744\n\nMeasurement of the thermo-optic coefficients in sol-gel derived inorganic–organic hybrid material films Appl. Phys. Lett. 81, 1438 (2002); 10.1063/1.1501448\n\nThermal stress and glass transition of ultrathin polystyrene films Appl. Phys. Lett. 77, 2843 (2000); 10.1063/1.1322049\n\nStructure, chain orientation, and properties in thin films of aromatic polyimides with various chain rigidities J. Appl. Phys. 81, 698 (1997); 10.1063/1.364210\n\n\\begin{caption}\n[This article is copyrighted as indicated in the article. Reuse of AIP content is subject to the terms at: http://scitation.aip.org/termsconditions. Downloaded to ] IP: 155.33.148.196 On: Tue, 25 Nov 2014 03:44:53\n\\end{caption}\n\n\\begin{title}\nPolarization dependence of thermo-optic coefficients in polyimide films originating from chain orientation and residual thermal stress\n\\end{title}\n\nYoshiharu Terui and Shinji Andoa)\n\nDepartment of Chemistry and Materials Science, Tokyo Institute of Technology, Ookayama, Meguro-ku, Tokyo 152-8552, Japan\n\n(Received 11 March 2014; accepted 22 July 2014; published online 7 August 2014)\n\nControl of polarization dependences of thermo-optic (TO) coefficients, i.e., the temperature dependence of birefringence (d(Dn)/dT), is critical issue for optical materials. Especially in active optical components like TO switches, polarization dependent behaviors are caused by d(Dn)/dT of materials. Origins of polarization dependence of TO coefficient were investigated for seven kinds of polyimide (PI) films in terms of main chain orientation and residual thermal stress. The values of d(Dn)/dT of PI films originated from chain orientation vary from nil to negative as the degrees of in-plane orientation increase. Magnitudes of d(Dn)/dT depend on intrinsic birefringences, second order orientation coefficients, and their temperature dependence. On the other hand, those of d(Dn)/dT originated from residual stress are negative for PI films exhibiting large in-plane coefficients of thermal expansion (CTE) and vary to zero as their CTE decreases due to reduced residual stress. d(Dn)/dT originating from chain orientation decreases as the degree of chain orientation increases, but that from residual thermal stress increases, which is the reason that no apparent trend was observed for the d(Dn)/dT of PI films adhering to Si substrates. Based on these examinations, the d(Dn)/dT of on-substrate PI films were successfully decreased to the levels of peeled PI films by incorporation of alicyclic structures in the main chains and/or the use of PI substrates whose CTEs are close to those of PI films. V C 2014 AIP Publishing LLC. [http://dx.doi.org/10.1063/1.4891998]\n\n\\begin{title}\nI. INTRODUCTION\n\\end{title}\n\nThe thermo-optic (TO) effect (i.e., temperature- dependent change in the refractive index) in optical polymers has recently attracted much attention because this phenom- enon is essential for all optical materials and can be utilized to fabricate active optical waveguide components such as TO optical switches and tunable wavelength-division multi- plexers.1,2 In particular, the temperature gradient of the refrac- tive index (dn/dT) of transparent polymeric materials3–11 is one order of magnitude larger ( 1 102ppm/K) than that of silica glass12 (þ10 ppm/K). By using polymeric materials, power consumptions of such active waveguide components can be significantly reduced due to their large jdn/dTj. Thereby, quantitative estimations and control of dn/dTs and their polarization dependence of polymers are crucial for fab- ricating active waveguide components using optical polymers.\n\nFor optically transparent polymers, the relationship between their average refractive indices (nav) and their tem- perature gradients (dnav/dT) can be expressed by the temper- ature derivative of the Lorentz-Lorenz formula\n\n\\begin{equation}\n{\\frac{d n_{\\mathrm{a v}}} {d T}}=-\\, {\\frac{\\left( n_{\\mathrm{a v}}^{2}-1 \\right) \\left( n_{\\mathrm{a v}}^{2}+2 \\right)} {6 n_{\\mathrm{a v}}}} \\, \\beta,\n\\end{equation}\n\n\\begin{token}\n(1)\n\\end{token}\n\nwhere T is the temperature, and b is the volumetric thermal expansion coefficient of materials. This is because the tem- perature dependence of molecular polarizability is negligibly\n\na)Author to whom correspondence should be addressed. Electronic mail: sando@polymer.titech.ac.jp. Tel.: þ81-3-5734-2137. Fax: þ81-3-5734-2889.\n\n\\begin{title}\n0021-8979/2014/116(5)/053524/10/$30.00\n\\end{title}\n\nsmall compared with the large bs of polymers.13,14 According to Eq. (1), the values of dnav/dT of polymers are always negative due to their positive b, and a large nav and/ or a large b give a large jdnav/dTj.\n\nAmong a number of polymeric materials for optical applications, we focused on the TO effects in aromatic polyi- mides (PIs) due to their favorable properties for thermally stable optical waveguide applications.15–17 We have been developing a variety of passive optical devices and compo- nents such as single-mode waveguides,18 waveplates,19–21 and polarizers22–24 using partially fluorinated and perfluori- nated PIs. In addition, regarding to TO effects in PIs, we have reported that the dnav/dT of aromatic PIs can be con- trolled by introducing sulfide (–S–) and disulfide (–S–S–) linkages into the main chains, which is effective to endow large jdnav/dTj to optical polymers.25 On the other hand, we have also reported that PI films formed on Si substrates ex- hibit significant polarization dependence in dn/dT,26 which indicates that the absolute values of dn/dT observed for transverse electric (TE) polarization (parallel to the film plane) are significantly larger than those for transverse mag- netic (TM) polarization (perpendicular to the film plane). This polarization dependence may cause undesirable insta- bility in the performance of active waveguide components such as TO switches.\n\nIn this study, we define the polarization dependence of dn/dT as the difference between the values of dn/dT for in-plane and out-of-plane refractive indices (nTE and nTM, respectively), which are equal to the temperature dependence of in-plane/out-of-plane birefringence (Dn)\n\n\\begin{equation}\n{\\frac{d n_{\\mathrm{T E}}} {d T}}-{\\frac{d n_{\\mathrm{T M}}} {d T}}={\\frac{d ( n_{\\mathrm{T E}}-n_{\\mathrm{T M}} )} {d T}}={\\frac{d ( \\Delta n )} {d T}},\n\\end{equation}\n\n\\begin{token}\n(2)\n\\end{token}\n\nd(Dn)/dT causes polarization dependence in the properties of active waveguide components.1 Figure 1 shows schematic views of a TO switch made by polymer waveguides and the influence of polarization dependence of dn/dT on the switch- ing performance. If the jdnTM/dTj of the waveguide core is significantly smaller than the jdnTE/dTj, the refractive index change needed for complete switching of TM-polarized sig- nals is not achieved, a critical condition for TE signals, which leads to additional heating of the waveguide core. Thereby, d(Dn)/dT is expected to be minimized or optimally eliminated in most waveguide applications. The present authors have been exploring methods to control the dn/dT and d(Dn)/dT of PI films formed on Si substrates and have reported that some PI films having very small Dn, represent- ing small degrees of chain orientation, exhibit negative values of d(Dn)/dT due to the temperature dependence of stress-birefringence originating from a mismatch of coeffi- cients of linear thermal expansion (CTE) between PI films and Si substrates.27 Based on these findings, we have achieved a 30%–50% decrease in d(Dn)/dT of PI films by replacing aromatic rings with alicyclic structures, which is attributable to the effective reduction of the stress-optical coefficient. However, these semi-alicyclic PI films still exhibit appreciable d(Dn)/dT, which are two or more times larger than those for PI films peeled off from the substrates. We would like to develop new and facile methods for the effective reduction of the d(Dn)/dT of PI films.\n\nApart from such approaches to control d(Dn)/dT, there remains an important issue to be clarified: the reason why d(Dn)/dT values do not exhibit simple correlations with other properties such as Dn, residual stress, or anisotropy in CTE, when PI films are formed on Si substrates.26 In this study, we investigate the effects of chain orientation and residual ther- mal stress on d(Dn)/dT and propose a theoretical basis that\n\n\\begin{legend}\n1) TE polarization (no crosstalk)\n\\end{legend}\n\n\\begin{legend}\n2) TM polarization (small crosstalk)\n\\end{legend}\n\n\\begin{caption}\nFIG. 1. Possible influence of the temperature dependence of in-plane/out-of- plane birefringence (d(Dn)/dT) on the switching properties of polymer optical waveguides. When one of the cores in the Y-branched waveguides is heated by a metallic heater, the refractive index is decreased to shut off optical sig- nals. However, if jdnTM/dTj of the core material is significantly smaller than the jdnTE/dTj, a refractive index change needed for complete switching of TM-polarized signals is not achieved, even though TE-polarized signals are completely switched without crosstalk.\n\\end{caption}\n\nquantitatively explains the origins of d(Dn)/dT for PI films formed on substrates. In addition, we demonstrate two facile and effective approaches to reduce the d(Dn)/dT for on- substrate PI films to the levels of those for off-substrate ones.\n\n\\begin{title}\nII. EXPERIMENTAL\n\\end{title}\n\n\\begin{title}\nA. Sample preparation\n\\end{title}\n\nThin films of poly(methyl methacrylate) (PMMA) obtained from Sumitomo Chemical Co. Ltd. (Sumipex- MGSS, optical grade) were prepared by spin-coating of a toluene solution. The spin-coated PMMA solution was dried at 40 C/20 min, 65 C/20 min, and 80 C/20 min in a convec- tion oven, followed by annealing at 120 C under reduced pressure. Aromatic PI films were prepared by thermal imid- ization of their precursors, poly(amic acid)s (PAAs). The molecular structures of aromatic PIs used in this study are shown in Figure 2. The PAA solutions were prepared by pol- ycondensations of equimolar dianhydrides and diamines in N,N-dimethylacetamide (DMAc). Alicyclic PI films were prepared from corresponding poly(amic acid trimethylsilyl ester) (PASE) solutions using the in situ silylation method.28 These precursor solutions were spin-coated on Si substrates (4-in. diameter, 380 lm thick, (001) surface) and dried at 70 C for 30 min, followed by thermal imidization for 1 h under nitrogen flow. The imidization temperatures were 350 C for aromatic PIs and 300 C for alicyclic PIs. The val- ues of d(Dn)/dT were measured for films in two conditions, (1) films formed on Si substrates (on-substrate films) and (2) those peeled off from the substrates prior to measurement (off-substrate films). The residual stress in the off-substrate PI films was effectively released by annealing at above the imidization temperature. The thicknesses of PMMA and PI films used for measurements were controlled in a range of 12–15 lm. Thick substrates made of Kapton-type aromatic PI with a 4-in. diameter and 0.7-mm thickness were kindly supplied by NTT Advanced Technology Corp.\n\n\\begin{molecule}\n*N(C(=O)C)C(=O)*.*N(C(=O)C)C(=O)C0:7:8:dene\n\\end{molecule}\n\n\\begin{molecule}\nCc1ccc(C(c2ccc(C)c(C)c2)(C(F)(F)F)C(F)(F)F)cc1C\n\\end{molecule}\n\n\\begin{legend}\n16FDA\n\\end{legend}\n\n\\begin{molecule}\nCc1ccc(Oc2ccc(C)c(C)c2)cc1C\n\\end{molecule}\n\n\\begin{legend}\n2ODPA\n\\end{legend}\n\n\\begin{molecule}\nCc1cc(C)c(C)cc1C\n\\end{molecule}\n\n\\begin{legend}\n3PMDA\n\\end{legend}\n\n\\begin{molecule}\nCc1ccc(-c2ccc(C)c(C)c2)cc1C\n\\end{molecule}\n\n\\begin{legend}\n4BPDA\n\\end{legend}\n\n\\begin{caption}\nFIG. 2. Molecular structures of aromatic PIs used in this study.\n\\end{caption}\n\n\\begin{molecule}\nCc1ccc(Oc2ccc(C)cc2)cc1\n\\end{molecule}\n\n\\begin{molecule}\nC(F)(F)(F)c1cc(C)ccc1-c1ccc(C)cc1C(F)(F)F\n\\end{molecule}\n\n\\begin{title}\nB. Variable temperature measurements of refractive indices\n\\end{title}\n\nA prism coupler (Metricon, PC-2010) equipped with a home-made temperature-control apparatus (See the Appendix) was used for refractive index measurements at elevated temperatures.25–27 Linearly polarized CW laser beams with TE (transverse electric) and TM (transverse magnetic) polarization were used for the measurements of nTE (refractive index in the in-plane direction of films) and nTM (out-of-plane direction, normal to film surface), respectively. The average refractive index and in-plane/ out-of-plane birefringences of polymer films were calcu- lated according to the following equations:\n\n\\begin{equation}\nn_{\\mathrm{a v}}=\\sqrt{\\frac{2 n_{\\mathrm{T E}}^{2}+n_{\\mathrm{T M}}^{2}} {3}},\n\\end{equation}\n\n\\begin{equation}\n\\Delta n=n_{\\mathrm{T E}}-n_{\\mathrm{T M}}.\n\\end{equation}\n\nA near-infrared laser at a wavelength of 1.324 lm was used as the light source to avoid anomalous dispersion of refractive indices near the absorption edges. The refractive index (n) of the coupling prism made of gallium gadolinium garnet at each temperature was estimated using the values of n ¼ 1.9387 at 25 C and dn/dT ¼ þ17.2 ppm/K at 1.324 lm.29 The measurements were carried out under a dry atmosphere ( 20% relative humidity) and in a temperature range of 85 C to 35 C. The sample temperature was controlled in descending order to prevent moisture absorption. A very small amount of silicone oil was used as a lubricant for the off-substrate films/heating plate and the film/prism surfaces in order to suppress thermal stress caused by the CTE mis- match among the substrates, a prism, and PI films. Prior to the variable temperature experiments, the accuracy of tem- perature control was checked for this measurement system. The reliability of temperature control of the prism and the sample were 63 C in the worst case. The experimental errors in the refractive indices and d(Dn)/dT were estimated as 60.0003 and 65 ppm/K, respectively.\n\n\\begin{title}\nC. Residual thermal stress and its temperature dependence\n\\end{title}\n\nResidual stresses (r) in polymer films supported by Si substrates are estimated from the curvatures of the PI films and the biaxial modulus of silicon crystal parallel to the (001) surface.30–32 The curvatures of the samples were measured using a depth profiler (Veeco Instruments, Dektak 3). The temperature dependence of r (dr/dT) was estimated in a tem- perature range of 80–140 C using a home-made heating attachment for the profiler. The measurements were carried out under a dry atmosphere ( 20% relative humidity) to avoid the stress relaxation derived from moisture absorption. The experimental errors for the values of r and dr/dT were estimated as 65 MPa and 60.05 MPa/K, respectively.\n\n\\begin{title}\nD. Biaxial stress-optical coefficients\n\\end{title}\n\nBiaxial stress-optical coefficients (C0 G) of polymers in the glassy state were estimated from stress-birefringence\n\n\\begin{token}\n(3)\n\\end{token}\n\n\\begin{token}\n(4)\n\\end{token}\n\n(Dns; difference in Dn for PI films before and after peeling from the substrates) divided by stress r\n\n\\begin{equation}\nC_{\\mathrm{G}}^{\\prime}={\\frac{\\Delta n_{\\mathrm{S}}} {\\sigma}}={\\frac{\\Delta n_{\\mathrm{s u p p o r t e d}}-\\Delta n_{\\mathrm{p e e l e d}}} {\\sigma}} \\,.\n\\end{equation}\n\n\\begin{token}\n(5)\n\\end{token}\n\n\\begin{title}\nE. Linear thermal expansion coefficients\n\\end{title}\n\nThe in-plane CTEs for off-substrate PI films were meas- ured with a thermo-mechanical analyzer (ULVAC, TM 7000) as average values in a range of 50–300 C. The out-of-plane CTEs were estimated from temperature shifts of interferences of transmitted light caused by temperature variations of the optical path, i.e., a product of thickness and the in-plane re- fractive index of the films. The temperatures of sample films were precisely controlled by a hot-stage (Mettler Toledo, Model FP82HT).\n\n\\begin{title}\nIII. RESULTS AND DISCUSSION\n\\end{title}\n\n\\begin{title}\nA. TO coefficients of polymer films formed on Si substrates\n\\end{title}\n\nFigure 3 shows the temperature dependence of nTE and nTM of a PMMA film formed on a Si substrate. The film was optically isotropic because both the birefringence (Dn ¼ nTE nTM) and its temperature dependence (d(Dn)/dT ¼ dnTE/dT dnTM/dT) were very small, which are compara- ble to the experimental error range. The refractive index of PMMA decreases as the temperature increases owing to its volumetric thermal expansion (b). It should be noted that the dnav/dT for PMMA film formed on a Si substrate ( 88 ppm/K) is smaller than that for a PMMA bulk prism4 ( 120 ppm/K) in their absolute values. The smaller jdnav/dTj value for the on-substrate film is attributed to restrained thermal expansions due to very small CTE of Si(001) substrates (þ2.6 ppm/K). The restraint leads to small apparent thermal volume expansion (b’) of polymer films attached to substrates, which result in small jdnav/dTjs according to Eq. (1). In case the polymer films are formed on substrate having negligibly small CTE, the TO coeffi- cient of polymer films can be estimated as follows:1\n\n\\begin{equation}\n\\left. \\frac{d n_{a \\nu}} {d T} \\right|_{\\mathrm{o n \\, s u b s t r a t e}}=\\frac{1} {3} \\left( \\frac{1+\\nu} {1-\\nu} \\right) \\! \\frac{d n_{\\mathrm{a v}}} {d T} |_{\\mathrm{b u l k}}\n\\end{equation}\n\n\\begin{token}\n(6)\n\\end{token}\n\n\\begin{caption}\nFIG. 3. Temperature dependence of in-plane and out-of-plane refractive indices (nTE and nTM, respectively) of PMMA film formed on Si substrate.\n\\end{caption}\n\nwhere is the Poisson ratio of the polymer. Using the values of for PMMA33 (0.365) and dnav/dT for bulk PMMA ( 120 ppm/K), the dnav/dT for on-substrate PMMA film is estimated at 86 ppm/K, which is very close to the experi- mental dnav/dT in the present study. This result confirms the reliability of our measurement system of TO coefficients.\n\nThe temperature dependence of in-plane and out-of- plane refractive indices of a fluorinated aromatic PI 1a (6FDA/ODA) film formed on a Si substrate is shown in Figure 4. Unlike the case of PMMA, aromatic PI films exhib- ited significantly large polarization dependence of TO coeffi- cients (d(Dn)/dT). In order to investigate the molecular- structure dependence, the polarization dependences of dn/dT were measured for seven kinds of aromatic PI films formed on Si substrates, and the estimated values of d(Dn)/dT are listed in Table I. Investigation of the molecular-structure de- pendence of dnav/dT is made in this section, and that of d(Dn)/dT will be discussed in Sec. III B.\n\nTo analyze the relationship according to Eq. (1), the val- ues of (nav 2 1)(nav 2þ 1)/6nav are plotted against dnav/dT for the PI films formed on Si substrates (Figure 5). Because the term of (nav 2 1)(nav 2þ 1)/6nav is nearly proportional to nav in the range of 1.4 < nav < 1.8, the absolute values of dnav/dT (jdnav/dTj) tend to increase as the nav increases. However, the correlation in Figure 5 is unclear due to the dif- ferences in volumetric expansion among PIs. Coefficients of apparent volumetric thermal expansion (b’), estimated from nav and dnav/dT according to Eq. (1), are in a range of 100 6 20 ppm/K. In cases of PI films exhibiting small bire- fringence with lower degrees of in-plane orientation of main chains (PI 1a, 1b, 2a, 2b), the PIs derived from ODA diamine (PI 1a and 2a), which includes a bent and flexible ether (-O-) linkage, exhibit larger b’ than those derived from a linear and rigid TFDB diamine (PI 1b and 2b). This suggests that a bent and flexible structure in the main chain leads to an increase in b’. On the other hand, the PI films exhibiting large birefringence with higher degrees of in-plane orienta- tion (PI 3a, 3b, 4c) did not necessarily demonstrate small b’values despite their rigid structures. These PIs should ex- hibit small CTEs parallel to the film plane, and the restraint of thermal expansions caused by a CTE mismatch between PI film and the Si substrate should be small compared to the PI films with lower degrees of orientation.\n\n\\begin{caption}\nFIG. 4. Temperature dependence of in-plane and out-of-plane refractive indices (nTE and nTM, respectively) of fluorinated PI 1a (6FDA/ODA) film formed on Si substrate.\n\\end{caption}\n\n\\begin{caption}\n[This article is copyrighted as indicated in the article. Reuse of AIP content is subject to the terms at: http://scitation.aip.org/termsconditions. Downloaded to ] IP: 155.33.148.196 On: Tue, 25 Nov 2014 03:44:53\n\\end{caption}\n\n\\begin{caption}\nTABLE I. Average refractive indices (nav), in-plane/out-of-plane birefrin- gence (Dn), thermo-optic coefficients (dn/dT, ppm/K), and their polarization dependence (d(Dn)/dT, ppm/K) for aromatic PI films formed on Si sub- strates. dnTE/dT, dnTM/dT, and dnav/dT represent in-plane, out-of-plane, and average TO coefficients in a range of 35–85 C.\n\\end{caption}\n\n\\begin{table}\n| Polyimide | Nav | ∆n | dnTE/dT | dnTM/dT | dnavldT | d(∆n)ldT |\n|:---------------|:-------|:-------|:----------|:----------|:----------|:-----------|\n| 1a (6FDA/ODA) | 1.5604 | 0.0074 | -76.3 | -56.8 | -69.8 | -19.5 |\n| 1b (6FDA/TFDB) | 1.5180 | 0.0076 | -57.1 | −41.0 | -51.7 | -16.1 |\n| 2a (ODPA/ODA) | 1.6425 | 0.0099 | -87.5 | -53.1 | -76.0 | -34.4 |\n| 2b (ODPA/TFDB) | 1.5797 | 0.0097 | -63.4 | -37.9 | -54.9 | -25.5 |\n| 3a (PMDA/ODA) | 1.6469 | 0.0693 | -99.2 | -58.8 | -86.1 | -40.4 |\n| 3b (PMDA/TFDB) | 1.5691 | 0.1151 | -86.6 | -77.9 | -83.8 | -8.8 |\n| 4c (BPDA/PDA) | 1.7191 | 0.1874 | -98.9 | -59.9 | -86.8 | -39.0 |\n\\end{table}\n\n\\begin{title}\nB. Origins of polarization dependence of TO coefficient\n\\end{title}\n\nAs described above, significant polarization dependence has been observed for the TO coefficients of PI films formed on Si substrates.27 The experimental values of d(Dn)/dT are plotted against Dn in Figure 6. For the off-substrate films (squares), the jdnav/dTj values increase as the Dn increase, which readily indicates that a higher degree of chain orienta- tion leads to a large value of jd(Dn)/dTj. In contrast, those for the on-substrate films (triangles) do not exhibit clear cor- relations to Dn.\n\nIn general, birefringence Dn in polymer depends on polymer chain orientation and residual stress. At first, we clarify the relationships between the experimental values of Dn and d(Dn)/dT and the degree of chain orientation for the off-substrate PI films to investigate the orientation-driven d(Dn)/dT. The Dn in a rotationally symmetric system is pro- portional to the second order orientation coefficient (P200) of polymer chains. In the case of uniaxially drawn films or fibers, chain orientation direction coincides with the axis of symmetry, and Dn can be expressed as34\n\n\\begin{equation}\n\\Delta n=\\Delta n^{0} \\times P_{2 0 0},\n\\end{equation}\n\nwhere Dn0 is the intrinsic birefringence. In contrast, spin- coated films can be treated as biaxially drawn films, in which the axis of symmetry is normal to the film plane, and the polymer chains are oriented perpendicular to the axis of\n\n\\begin{caption}\nFIG. 5. Thermo-optic coefficients of average refractive indices (dnav/dT) for aromatic PI films formed on Si substrates. Numbers in the figure correspond to those in Fig. 2.\n\\end{caption}\n\n\\begin{token}\n(7a)\n\\end{token}\n\n\\begin{caption}\nFIG. 6. Comparison between the polarization dependence of the refractive index (birefringence Dn) and its temperature dependence (d(Dn)/dT) for aro- matic PI films. The values of d(Dn)/dT for the off-substrate films and the on- substrate ones are plotted by filled squares and open triangles, respectively.\n\\end{caption}\n\nsymmetry. Thereby, the relationship between Dn (¼nTE nTM) and P200 for spin-coated films is expressed as follows:\n\n\\begin{equation}\n\\Delta n=-\\Delta n^{0} \\times P_{2 0 0}.\n\\end{equation}\n\n\\begin{token}\n(7b)\n\\end{token}\n\nBy taking the temperature derivative of Eq. (7b), the rela- tionship between d(Dn)/dT and the chain orientation is expressed as follows:\n\n\\begin{equation}\n{\\frac{d ( \\Delta n )} {d T}}=-P_{2 0 0} {\\frac{d ( \\Delta n^{0} )} {d T}}-\\Delta n^{0} {\\frac{d P_{2 0 0}} {d T}}.\n\\end{equation}\n\n\\begin{token}\n(8)\n\\end{token}\n\nAccording to Eq. (8), the influence of chain orientation on d(Dn)/dT can be divided into two factors; (a) the temperature dependence of Dn0 (product of P200 and d(Dn0)/dT) and (b) the temperature dependence of P200 (product of Dn0 and dP200/dT). For quantitative investigation of d(Dn)/dT, the values of P200, Dn0, and their temperature dependences are to be evaluated. We have previously reported P200 for PI films prepared by spin-coating35 and uniaxial drawing36 using polarized ATR/FT-IR spectroscopy, and their Dn0 val- ues were determined.37 However, the origins of their temper- ature dependence have not been investigated yet.\n\nFirst, we investigate the temperature dependences of Dn0. Intrinsic birefringence Dn0 can be estimated according to the Vuks equation38\n\n\\begin{equation}\n\\frac{n_{i}^{2}-1} {n_{\\mathrm{a v}}^{2}+2}=\\frac{4 \\pi} {3} \\frac{\\rho N_{\\mathrm{A}}} {M} \\, \\alpha_{i},\n\\end{equation}\n\n\\begin{token}\n(9)\n\\end{token}\n\nwhere ni, ai, q, M, and NA are the refractive index, the molec- ular polarizability for a direction i, the density of a polymer, the molecular weight of the repeating unit, and the Avogadro’s number, respectively. From the temperature de- rivative of Eq. (9), the temperature dependence of ni can be written as follows:\n\n\\begin{equation}\n{\\frac{2 n_{i}} {n_{i}^{2}-1}} {\\frac{d n_{i}} {d T}}-{\\frac{2 n_{\\mathrm{a v}}} {n_{\\mathrm{a v}}^{2}+2}} {\\frac{d n_{\\mathrm{a v}}} {d T}}={\\frac{1} {\\rho}} {\\frac{d \\rho} {d T}}=-\\beta.\n\\end{equation}\n\nIn the derivation of Eq. (10), the temperature dependence of polarizability (dai/dT) was neglected because dai/dT is much smaller than dq/dT for polymers.4 In accordance with Eqs. (1) and (10), the temperature dependence of Dn0 is approximated as\n\n\\begin{token}\n(10)\n\\end{token}\n\n\\begin{equation}\n{\\frac{d ( \\Delta n^{0} )} {d T}}=\\left( 1+{\\frac{1} {n_{| |}^{0} n_{\\bot}^{0}}} \\right) {\\frac{n_{\\mathrm{a v}}} {n_{\\mathrm{a v}}^{2}-1}} \\Delta n^{0} {\\frac{d n_{\\mathrm{a v}}} {d T}},\n\\end{equation}\n\nwhere njj 0 and n? 0 are the refractive indices parallel and per- pendicular to the axis of symmetry under perfect uniaxial orientation, in which P200 becomes unity. The values of d(Dn0)/dT estimated from the experimental values of njj 0, n? 0, and Dn0, and those of dnav/dT measured for the off- substrate PI films are listed in Table II. Among the four kinds of aromatic PIs, 4c (BPDA/PDA) exhibited exceptionally large d(Dn0)/dT due to its high nav and large Dn0 values.\n\nSecond, we investigate the temperature dependences of P200. P200 represents a degree of orientation of polymer chains to the axis of symmetry, which is defined as:\n\n\\begin{equation}\nP_{2 0 0}=\\frac{3 \\langle\\cos^{2} \\! \\theta\\rangle-1} {2},\n\\end{equation}\n\nwhere h is the angle between a polymer main chain and the axis of symmetry, and the value in the angle bracket means the average over all polymer segments. In cases of spin- coated films, the main chains of aromatic PIs tend to orient perpendicular to the axis of symmetry due to their rigid and quasi-linear skeletal structures. Thereby, the values of P200 vary from 1 (h ¼ 0, isotropic) to 1/2 (h ¼ p/2; all chains are oriented parallel to the film plane) as the degree of chain ori- entation increases. PI films exhibiting anisotropic CTEs will cause changes in h with temperature. According to Eq. (12), changes in h will cause temperature dependences of P200. The CTEs parallel to the orientation direction usually take positive values, but they become negative in some cases of rigid-rod polymers. In addition, it decreases by increasing the degree of in-plane chain orientation. The variation of h originating from the anisotropy in CTE is schematically shown in Figure 7. It can be assumed that an angle Dh, which represents the change in h caused by elevated temperature DT, suffices in the following relation:\n\n\\begin{equation}\n\\operatorname{t a n} ( \\theta+\\Delta\\theta)=\\frac{1+k_{| |} \\Delta T} {1+k_{\\perp} \\Delta T} \\operatorname{t a n} \\theta\\approx( 1-\\Delta k \\Delta T ) \\operatorname{t a n} \\theta,\n\\end{equation}\n\nwhere kjj and k? are the CTEs parallel and perpendicular to the axis of symmetry, respectively, and Dk (¼kjj k?) is the anisotropy in CTE. According to Eqs. (12) and (13), the change in the orientation coefficients (DP200) after a temper- ature change (DT) can be estimated as follows:\n\n\\begin{equation}\n\\Delta P_{2 0 0}=3 \\Delta k \\Delta T ( \\langle\\operatorname{c o s}^{2} \\! \\theta\\rangle-\\langle\\operatorname{c o s}^{4} \\! \\theta\\rangle)\n\\end{equation}\n\nTABLE II. Average refractive indices (nav), intrinsic birefringence (Dn0), average thermo-optic coefficients (dnav/dT, ppm/K), and estimated tempera- ture dependence of intrinsic birefringence (d(Dn0)/dT, ppm/K) of the peeled PI films.\n\n\\begin{table}\n| Polyimide | Nav | $n1$ | 0 n⊥0 | ∆n0 | dnavldT | d(∆n0)/dT |\n|:---------------|:-------|:-------|:--------|:------|:----------|:------------|\n| 1a (6FDA/ODA) | 1.5259 | 1.771 | 1.472 | 0.322 | -82.5 | -42.2 |\n| 3a (PMDA/ODA) | 1.6469 | 1.887 | 1.513 | 0.374 | -86.1 | -41.8 |\n| 3b (PMDA/TFDB) | 1.5719 | 1.793 | 1.447 | 0.346 | -74.4 | -38.1 |\n| 4c (BPDA/PDA) | 1.7181 | 2.016 | 1.544 | 0.472 | -95.5 | -52.4 |\n\\end{table}\n\n\\begin{token}\n(11)\n\\end{token}\n\n\\begin{token}\n(12)\n\\end{token}\n\n\\begin{token}\n(13)\n\\end{token}\n\n\\begin{token}\n(14)\n\\end{token}\n\n\\begin{caption}\nFIG. 7. Schematic model for temperature dependent change of chain direc- tions derived from the anisotropy in CTE.\n\\end{caption}\n\nand\n\n\\begin{equation}\n\\frac{d P_{2 0 0}} {d T} \\approx\\frac{\\Delta P_{2 0 0}} {\\Delta T}=3 \\Delta k \\big( \\langle\\cos^{2} \\! \\theta\\rangle-\\langle\\cos^{4} \\! \\theta\\rangle\\big).\n\\end{equation}\n\n\\begin{token}\n(15)\n\\end{token}\n\nThe values of hcos4hi can be estimated from the 4th order orientation coefficients obtainable from polarized Raman spectroscopy or the wide-angle X-ray diffraction pat- tern, although such measurements are difficult to employ for amorphous PIs. In this study, we approximated hcos4hi by hcos2hi2, which corresponds to a case where all polymer chains take the same h value on average. The experimental Dk, P200, and the dP200/dT estimated using Eq. (15) for the off-substrate PI films are listed in Table III. The PIs exhibit- ing large Dk represent relatively large dP200/dT. In general, a higher degree of chain orientation leads to a large Dk, but PI 4c exhibits an intermediate Dk value (119 ppm/K) because its rigid structure with a higher degree of molecular aggrega- tion leads to smaller volumetric thermal expansion. Hence, the dP200/dT of PI 4c is not so large despite the highest degree of chain orientation (P200 ¼ 0.330).\n\nTemperature dependences of d(Dn)/dT for PI films are estimated using Eqs. (8), (11), and (15). Both of the esti- mated and experimental values of d(Dn)/dT for the off- substrate PI films are always negative, as listed in Table IV, and their absolute values are significantly large for films exhibiting higher degrees of orientation (3b and 4c). As shown in Figure 8, the estimated values of d(Dn)/dT well reproduce the experimental ones, which apparently demon- strates that the experimental values of d(Dn)/dT observed for the off-substrate PI films are explainable as a sum of the two factors (a) and (b).\n\nWe start investigation on residual stress effect on Dn and d(Dn)/dT. The values of d(Dn)/dT measured for the on- substrate PI films are noticeably different from those for the\n\n\\begin{caption}\nTABLE III. Coefficients of linear thermal expansion coefficients (CTE, ppm/K), anisotropy in CTE (Dk, ppm/K), second order orientation coeffi- cient P200 of peeled PI films, and the estimated dP200/dT. kjj and k? represent out-of-plane and in-plane CTEs (parallel and perpendicular to the axis of rotational symmetry).\n\\end{caption}\n\n\\begin{table}\n| Polyimide | k1i | k⊥ | ∆k | P200 | (cos2θ)) | dP20/dT |\n|:---------------|:------|:-----|:-----|:-------|:-----------|:----------|\n| 1a (6FDA/ODA) | 85 | 60 | 25 | -0.015 | 0.323 | 16.4 |\n| 3a (PMDA/ODA) | 106 | 27 | 79 | −0.141 | 0.239 | 43.1 |\n| 3b (PMDA/TFDB) | 169 | -4.2 | 173 | −0.281 | 0.146 | 64.7 |\n| 4c (BPDA/PDA) | 119 | 0.2 | 119 | -0.330 | 0.113 | 35.8 |\n\\end{table}\n\n\\begin{caption}\n[This article is copyrighted as indicated in the article. Reuse of AIP content is subject to the terms at: http://scitation.aip.org/termsconditions. Downloaded to ] IP: 155.33.148.196 On: Tue, 25 Nov 2014 03:44:53\n\\end{caption}\n\n\\begin{caption}\nTABLE IV. The estimated and experimental values of polarization depend- ence in TO coefficient (d(Dn)/dT, ppm/K) derived from the chain orientation.\n\\end{caption}\n\n\\begin{table}\n| Polyimide | 20o-d(∆n0)/ dT | ∆n0.dP200/ dT | d(∆n)/dT (estimated) | d(∆n)/dT (experimental) |\n|:---------------|:-----------------|:----------------|:-----------------------|:--------------------------|\n| 1a (6FDA/ODA) | 0.6 | 5.3 | -5.9 | -4 |\n| 3a (PMDA/ODA) | 5.9 | 16.1 | -22.0 | -22 |\n| 3b (PMDA/TFDB) | 10.7 | 22.4 | -33.1 | -34 |\n| 4c (BPDA/PDA) | 17.3 | 16.9 | -34.2 | -39 |\n\\end{table}\n\noff-substrate PI films (see Figure 6). Based on the experi- mental results, we have reported that the difference in d(Dn)/ dT between the off- and on-substrate films is caused by the temperature dependence of stress birefringence (d(Dns)/dT) for the PI films exhibiting lower degrees of chain orientation, and this term can be represented as follows:1,27\n\n\\begin{equation}\n\\frac{d ( \\Delta n_{\\mathrm{s}} )} {d T}=C_{\\mathrm{G}}^{\\prime} \\frac{d \\sigma} {d T},\n\\end{equation}\n\nwhere C0 G is the in-plane/out-of-plane stress-optical coeffi- cient for biaxial stress, and r is the residual stress (positive for expansion stress). The temperature dependence of r can be expressed as\n\n\\begin{equation}\n\\frac{d \\sigma} {d T}=\\frac{E_{\\mathrm{f}}} {1-\\nu_{\\mathrm{f}}} \\left( k_{\\mathrm{f}}-k_{\\mathrm{s}} \\right),\n\\end{equation}\n\nwhere Ef, f, kf, and ks are Young’s modulus, the Poisson ra- tio, the in-plane CTEs of PI film and substrate, respec- tively.39,40 The values of d(Dns)/dT for the oriented PI films were estimated according to Eq. (16) using the experimental values of C0 G and dr/dT as listed in Table V. Since residual stress is induced in the on-substrate PI films during cooling from the highest imidization temperature (300–350 C) to room temperature,41 the value of dr/dT becomes small (close to zero) when kf is similar to ks (2.6 ppm/K at 20 C), and they become negative when the values of kf are negative. On the other hand, the estimated C0 G for the PI films are in a range of 100–280 ppm/MPa, which are much larger than those for conventional optical polymers such as PMMA and polystyrene. This is due to the higher content of benzene and imide rings in the molecular structures of PIs.42 As shown in\n\n\\begin{caption}\nFIG. 8. Comparison between the experimental values of d(Dn)/dT for the off-substrate PI films (open circles) and the estimated values of d(Dn)/dT derived from the chain orientation (filled circles).\n\\end{caption}\n\n\\begin{token}\n(16)\n\\end{token}\n\n\\begin{token}\n(17)\n\\end{token}\n\n\\begin{caption}\nTABLE V. Residual stress (r; MPa), temperature dependence of r (dr/dT; MPa/K), stress-optical coefficients for biaxial stress (C0 G), and estimated val- ues of temperature dependence of stress birefringence (d(Dns)/dT; ppm/K) with respect to the difference between the values of d(Dn)/dT for the off- and on-substrate PI films (D[d(Dn)/dT]; ppm/K). Values in the parenthesis indicate error ranges.\n\\end{caption}\n\n\\begin{table}\n| Polyimide | σ | doldT | $C$ | d(∆ns)ldT | ∆[d(∆n)dT]d |\n|:---------------|:------|:--------|:---------|:------------|:--------------|\n| 1a (6FDA/ODA) | 49.9 | -0.200 | 140 (34) | −28(14) | −16(5) |\n| 3a (PMDA/ODA) | 20.4 | -0.082 | 279 (70) | -23 (20) | -18(5) |\n| 3b (PMDA/TFDB) | -26.9 | 0.106 | 245 (60) | 26 (19) | 25(5) |\n| 4c (BPDA/PDA) | -13.4 | −0.041 | 97 (47) | 4(7) | −2(5) |\n\\end{table}\n\nFigure 9, the estimated d(Dns)/dT values agree well with the difference in the experimental values of d(Dn)/dT between the off- and on-substrate PI films. This result clearly certifies that the temperature dependence of stress birefringence d(Dns)/dT causes the substrate effect on d(Dn)/dT for PI films.\n\n\\begin{title}\nC. Control of polarization dependence of TO coefficients\n\\end{title}\n\nThe reduction of polarization dependence of dn/dT in polymer films is an essential issue to improve the perform- ance of active waveguide components. Since the structures of optical materials applicable to waveguides are more or less isotropic with low degrees of chain orientation and ex- hibit negligibly small Dn, the dominant origin of d(Dn)/dT could be “stress-driven” polarization dependence of the TO coefficient (d(Dns)/dT). According to Eqs. (16) and (17), d(Dns)/dT can be effectively reduced by (i) elimination of the mismatch between the CTEs of substrates and PI films (kf ks) and (ii) reduction of the stress-optical coefficients (C0 Gs) of PI films.\n\nAt first we investigate an approach to reduce CTE mis- match by using PI substrates. The CTEs of conventional inorganic substrate materials (e.g., silicon, sapphire, and silica glass) are generally much smaller than those of poly- mers. If we can choose substrates from other than inorganic materials, the CTE of substrate ks becomes more controllable for reducing the CTE mismatch with polymers. For instance, several kinds of polymeric substrates have been proposed for\n\n\\begin{caption}\nFIG. 9. Comparison between the d(Dn)/dT induced by the use of Si substrate (open symbols) and the estimated values of temperature dependence of stress birefringence d(Dns)/dT for the on-substrate PI films on Si substrates (filled symbols).\n\\end{caption}\n\noptical waveguide applications.43,44 Since the kss of these substrates could be close to the kf of optical PIs, the d(Dns)/ dT spontaneously generated in PI films should be signifi- cantly reduced by using polymeric substrates. Therefore, in this study, we employed a polyimide substrate with ks of 60 ppm/K, which is almost same as the kfs of the fluorinated PIs developed for waveguide applications (PI 1a and 1b, see Table III). The values of dnav/dT and d(Dn)/dT measured for the PI films formed on PI substrates are shown in Table VI. As we had expected, the d(Dn)/dT for the PI films formed on the PI substrates were effectively reduced, as small as those for the off-substrate PI films. In addition, the PI films on PI substrates exhibited almost the same dnav/dT as the off- substrate films, which obviously confirm that the thermal expansion of PI films was not restrained by the PI substrates due to the absence of a CTE mismatch (cf. Sec. III). The major advantage of this approach is that the significant d(Dn)/dT in the current PIs developed for waveguide appli- cations can be effectively reduced without any modifications of the molecular structures.\n\nSecond, we investigate an approach to reduce C0 G of PIs. In photonic and telecommunication applications, the selec- tion of substrate materials for optical waveguides has been limited to inorganics such as Si, sapphire (Al2O3), or fused silica glass (SiO2). Although the kf of PI films can be reduced to as small as ks of inorganic materials through enhancement of the degrees of chain orientation,45–47 it readily induces significantly large Dn and orientation-driven d(Dn)/dT, which inevitably deteriorates the performance of wave- guides, i.e., polarization dependent optical losses and phase shift between TE and TM signals. Therefore, in case opti- cally isotropic PI films are formed on inorganic substrates, their large CTE mismatch and accompanying large dr/dTs are to be minimized. According to Eq. (16), C0 G could be reduced to achieve a small jd(Dn)/dTj for PI films which ex- hibit large dr/dT values. Although the origins of the molecular-structure dependence of C0 G have not been quanti- tatively clarified, a large anisotropy in molecular polarizabil- ity along the chain axis should lead to a large C0 G.42 Hence, introductions of flexible and non-planer aliphatic structures could effectively reduce the d(Dn)/dT of PIs. In order to ver- ify this concept, two series of aliphatic PIs were prepared (Figure 10); (a) semi-alicyclic PIs derived from alicyclic dia- mines (d: DCHM, e: 6FDC, f: TFDC) and aromatic dianhy- drides (1: 6FDA and 2: ODPA), and (b) wholly alicyclic PIs derived from the same alicyclic diamines and alicyclic\n\n\\begin{caption}\nTABLE VI. Substrate effect on refractive indices (nav), birefringence (Dn), TO coefficients (dnTE/dT, dnTM/dT, and dnav/dT, respectively; ppm/K), and their polarization dependences (d(Dn)/dT, ppm/K) of aromatic PI films.\n\\end{caption}\n\n\\begin{table}\n| Polyimide | Condition | nav | ∆n | dnav/dT | d(∆n)/dT |\n|:---------------|:--------------|:-------|:-------|:----------|:-----------|\n| 1a (6FDA/ODA) | On Si | 1.5604 | 0.0074 | -70 | -20 |\n| 1b (6FDA/TFDB) | On PI | 1.5657 | 0.0026 | -80 | -5 |\n| 1b (6FDA/TFDB) | Off-substrate | 1.5640 | 0.0004 | -83 | -4 |\n| 1b (6FDA/TFDB) | On Si | 1.5180 | 0.0076 | -52 | -16 |\n| 1b (6FDA/TFDB) | On PI | 1.5207 | 0.0022 | -58 | -4 |\n| 1b (6FDA/TFDB) | Off-substrate | 1.5263 | 0.0000 | -56 | -2 |\n\\end{table}\n\n\\begin{molecule}\n*N(C(=O)C)C(=O)*.*N(C(=O)C)C(=O)C0:7:8:dene\n\\end{molecule}\n\n\\begin{molecule}\nCc1ccc(C(c2ccc(C)c(C)c2)(C(F)(F)F)C(F)(F)F)cc1C\n\\end{molecule}\n\n\\begin{molecule}\nCc1ccc(Oc2ccc(C)c(C)c2)cc1C\n\\end{molecule}\n\n\\begin{legend}\n2ODPA\n\\end{legend}\n\n\\begin{molecule}\nCC1C(C)C(C)C1C.Cc1cc(C)c(C)cc1C\n\\end{molecule}\n\n\\begin{legend}\n5CBDA\n\\end{legend}\n\n\\begin{caption}\nFIG. 10. Molecular structures of the alicyclic PIs used in this study.\n\\end{caption}\n\ndianhydride 5 (CBDA). The experimental values of d(Dn)/ dT for these alicyclic PI films formed on Si substrates are shown in Figure 11. The absolute values of d(Dn)/dT for the semi-alicyclic PIs (PI 1d–1f and 2d–2f) are significantly reduced by 30%–50% compared to the aromatic PIs derived from the same dianhydrides. Furthermore, the wholly alicy- clic PIs (PI 5d–5f) exhibited very small d(Dn)/dT ( 3– 9 ppm/K), despite the use of Si substrates. The d(Dn)/dT for these PI films are as small as those for the off-substrate aro- matic PI films without residual stress. The kinked and stiff structure of the CBDA moiety provides additional reduction in anisotropy of polarizability.\n\nIn addition to the very small jd(Dn)/dTj, the values of dnav/dT of the alicyclic PI films can also be controlled through their molecular structures. As shown in Figure 12, the jdnav/dTj for the PIs derived from fluorinated alicyclic diamines 6FDC (PI 1e, 2e, and 5e) and TFDC (1f, 2f, and 5f) are reduced further than those of the PIs derived from DCHM (1d, 2d, and 5d) by 25%–50%. According to Eq. (1), a small jdnav/dTj is attributable to small values of nav and/or b. Although the nav of the PIs derived from 6FDC and TFDC are smaller than those of the PIs from DCHM by 0.02–0.04, the differences in nav cause only 5%–10% decreases in dnav/dT. Therefore, the PIs derived from 6FDC- and TFDC\n\n\\begin{caption}\nFIG. 11. Molecular structure dependence of d(Dn)/dT for the alicyclic PI films formed on Si substrates.\n\\end{caption}\n\n\\begin{molecule}\nCC1CCC(CC2CCC(C)CC2)CC1\n\\end{molecule}\n\n\\begin{molecule}\nCC1CCC(C(C2CCC(C)CC2)(C(F)(F)F)C(F)(F)F)CC1\n\\end{molecule}\n\n\\begin{molecule}\nCC1CCC(C2CCC(C)CC2C(F)(F)F)C(C(F)(F)F)C1\n\\end{molecule}\n\n\\begin{caption}\nFIG. 12. Molecular structure dependence of dnav/dT for the alicyclic PI films formed on Si substrates.\n\\end{caption}\n\nshould possess smaller b than the PIs from DCHM. In the case of TFDC-derived PIs, small b may be attributable to the relatively linear structure of the TFDC moiety, whereas the difference between the molecular structures of the DCHM and 6FDC moieties is the only flexible linkages connecting the two cyclohexyl units (the methylene unit –CH2– and the hexafluoroisopropylidene unit –C(CF3)2–, respectively) as shown in Figure 10. In the case of 6FDC- derived PIs, the bulky and heavy trifluoromethyl (–CF3) side groups cause steric hindrance and make the main-chain rota- tions more difficult. This assumption is supported by the molecular-structure dependence of glass transition tempera- tures (Tg) shown in Table VII. The 6FDC-derived PIs (1e and 2e) exhibit noticeably higher Tgs than the DCHM- derived ones (1d and 2d). In addition, a similar trend is observed in the dianhydride-structure dependence of Tgs. The 6FDA-derived PIs, containing –C(CF3)2– linkages, exhibit significantly higher Tgs than the ODPA-derived PIs (containing –O– linkages). This trend demonstrates that, among the three kinds of flexible linkages, –C(CF3)2– leads to more restricted main-chain motions compared to –CH2– and –O– linkages.\n\n\\begin{title}\nIV. CONCLUSIONS\n\\end{title}\n\nThe relationships between the polarization dependence of TO coefficients (d(Dn)/dT) and other properties (e.g., bire- fringence Dn, orientation coefficient P200, or residual stress r) were extensively examined for the on-substrate and off- substrate PI films, and the origins of d(Dn)/dT were clarified. It was demonstrated that the d(Dn)/dT can be divided into two factors, that is, (a) chain orientation-driven and (b) stress-driven ones. The former factor (a) consists of two terms, the temperature dependence of Dn0 and P200, as\n\n\\begin{caption}\nTABLE VII. Molecular structure dependence of glass transition tempera- tures ( C) of alicyclic PIs.\n\\end{caption}\n\n\\begin{table}\n| ('', 'Dianhydride') | ('Diamine', 'c (DCHM)') | ('Diamine', 'd (6FDC)') | ('Diamine', 'e (TFDC)') |\n|:----------------------|:--------------------------|:--------------------------|:--------------------------|\n| 1 (6FDA) | 262a | 326² | 335 |\n| 2 (ODPA) | 210 | 230 | 270 |\n\\end{table}\n\naValues are from Ref. 25.\n\nshown in Eq. (8). The value of d(Dn)/dT derived from this factor is always negative and significantly large for films exhibiting higher degrees of chain orientation. On the other hand, the latter factor (b) is caused by the temperature de- pendence of stress birefringence (drs/dT). The value of d(Dn)/dT derived from this factor is also negative for films exhibiting large in-plane CTEs, which is the case with lower degrees of chain orientation. However, the d(Dn)/dT becomes small and close to zero as the in-plane CTE decreases because the drs/dT depends on the CTE mismatch between the PI films and Si substrates, as shown in Eqs. (16) and (17). The experimental values of d(Dn)/dT are affected only by factor (a) for off-substrate films, so those values ex- hibit a clear correlation with Dn. On the other hand, the val- ues of d(Dn)/dT for on-substrate PI films are determined by the sum of factors (a) and (b). As schematically shown in Figure 13, the d(Dn)/dT originating from factor (a) exhibits an opposite dependence on the degree of chain orientation to that originating from factor (b). This is the essential reason that the behaviors of d(Dn)/dT observed for on-substrate PI films could not be straightforwardly investigated with respect to other structural properties (see Figure 6).\n\nBased on the above investigations, we demonstrated two approaches which effectively reduce the significantly large d(Dn)/dT observed for the on-substrate PI films. The first approach is the reduction of the CTE mismatch by using “polyimide substrates” of which the CTE is well matched to that of the PI films. As expected, the d(Dn)/dT for the PI films formed on polyimide substrates are as small as those for off-substrate PI films (see Table VI). This approach is ad- vantageous in the availability of current optical waveguide PI materials. The second approach is the reduction of C0 G by changing the skeletal structures of PIs by using alicyclic monomers. As shown in Figure 11, the values of d(Dn)/dT for the newly synthesized semi-alicyclic PI films range from 9 to 19 ppm/K, which are 30%–50% smaller than those of aromatic PIs. Moreover, the wholly alicyclic PI films formed on Si substrates exhibit d(Dn)/dT values in a range of 3– 9 ppm/K. These values are as small as those for the off-substrate fluorinated aromatic PI films without residual thermal stress. This approach is facile and advantageous if we have to use Si substrates. In this study, we have demon- strated that the polarization dependence of TO coefficients\n\n\\begin{caption}\nFIG. 13. Schematic representation of the origins of d(Dn)/dT for the PI films formed on Si substrates.\n\\end{caption}\n\n\\begin{caption}\nFIG. 14. Schematic figure for the temperature control apparatus for a prism coupler. Point (a): laser-incident position. Point (b): thermocouple for feed- back temperature control is glued on this position.\n\\end{caption}\n\nd(Dn)/dT of PI films can effectively suppressed or reduced by choosing an appropriate approach with consideration for the design and fabrication conditions of optical devises and components.\n\n\\begin{title}\nAPPENDIX: MEASUREMENT OF TO COEFFICIENT USING PRISM COUPLER\n\\end{title}\n\nA prism coupler (Metricon, PC-2010) equipped with a home-made temperature-control apparatus (Figure 14) was used for refractive index measurements at elevated tempera- tures. The ceramic heater 100 V/A, 10 20 mm) glued on a silicon wafer was driven by AC power. The temperature was controlled by adjustable voltage. Conductive silver paste was used as an adhesive between this apparatus and the sam- ple substrate to achieve good thermal contact. Sample and prism temperature was monitored by a K-type thermocouples glued on the film and prism surface with small amounts of silver paste. A laser beam with TE or TM polarization was used for the measurements. The refractive index of the cou- pling prism (gallium gadolinium garnet) at each temperature was calculated using the values of n ¼ 1.9390 at 25 C and dn/dT ¼ 17.2 ppm/K at a wavelength of 1.32 lm.\n\n\\begin{table}\n| 1M. B. J. Diemeer, Opt. Mater. 9, 192 (1998). 2H. Ma, A. K.-Y. Jen, and L. R. Dalton, Adv. Mater. 14, 1339 (2002). 3R. M. Waxler, D. Horowitz, and A. Feldman, Appl. Opt. 18, 101 (1979). 4P. Michel, J. Dugas, J. M. Cariou, and L. Martin, J. Macromol. Sci. Phys. |\n|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| B25, 379 (1986). 5R. S. Moshrefzader, M. D. Radcliffe, T. C. Lee, and S. K. Mohapatra, |\n| J. Lightwave Technol. 10, 420 (1992). 6T. Watanabe, N. Ooba, Y. Hida, and M. Hikita, Appl. Phys. Lett. 72, 1533 |\n| (1998). 7R. Blomquist, L. Eldada, M. McFarland, R. Norwood, C. Poga, and L. |\n| Shacklett, Proc. SPIE 3799, 266 (1999). 8A. Noris, J. DeGroot, Jr., F. Nishida, U. Penisz, N. Kushibiki, and T. Ogawa, Proc. SPIE 4798, 79 (2002). |\n| 9X. Li, Z.Q. Cao, Q.-S. Shen, Q.H. Meng, D.-Y. Huang, K.-P. Guo, L. Qiu, and Y.-Q. Shen, Chin. Phys. Lett. 23, 998 (2006). |\n| 10D. I. Johnson and G. E. Town, Proc. SPIE 6038, 603821 (2006). 1M. R. Saleem, S. Honkanen, and J. Turunen, Opt. Commun. 288, 56 |\n| (2013). 12W. S. Rodney and R. J. Spindler, J. Res. Nat. Bur. Stand. 53, 185 |\n| (1954). 13J. M. Cariou, J Dugas, L. Marin and P. Michel, Appl. Opt. 25, 334 |\n| (1986). 14H. Gao, D. Yorifuji, Z. Jiang, and S. Ando, Polymer 5, 2848 (2014). |\n\\end{table}\n\n\\begin{title}\n053524-10 Y. Terui and S. Ando\n\\end{title}\n\n15T. Matsuura, Y. Hasuda, S. Nishi, and N. Yamada, Macromolecules 24, 5001 (1991).\n\n16S. Ando, T. Matsuura, and S. Sasaki, Macromolecules 25, 5858 (1992).\n\n17T. Matsuura, S. Ando, S. Sasaki, and F. Yamamoto, Macromolecules 27, 6665 (1994).\n\n18T. Matsuura, S. Ando, S. Matsui, S. Sasaki, and F. Yamamoto, Electron. Lett. 29, 2107 (1993).\n\n19S. Ando, T. Sawada, and Y. Inoue, Electron. Lett. 29, 2143 (1993).\n\n20S. Ando, T. Sawada, and S. Sasaki, Polym. Adv. Technol. 10, 169 (1999).\n\n21S. Ando, T. Sawada, and S. Sasaki, Polym. Adv. Technol. 12, 319 (2001).\n\n23S. Matsuda, S. Ando, and T. Sawada, Electron. Lett. 37, 706 (2001).\n\n24S. Matsuda, Y. Yasuda, and S. Ando, Adv. Mater. 17, 2221 (2005).\n\n25Y. Terui and S. Ando, J. Photopolym. Sci. Technol. 18, 337 (2005).\n\n26Y. Terui and S. Ando, Appl. Phys. Lett. 83, 4755 (2003).\n\n27Y. Terui and S. Ando, Proc. SPIE 5724, 336 (2005).\n\n28Y. Oishi, S. Onodera, J. Oravec, K. Mori, S. Ando, Y. Terui, and K. Maeda, J. Photopolym. Sci. Technol. 16, 263 (2003).\n\n29D. L. Wood and K. Nassau, Appl. Opt. 29, 3704 (1990).\n\n30M. Ree, T. L. Nunes, G. Czornyj, and W. Volksen, Polymer 33, 1228 (1992).\n\n31M. Ree, S. Swanson, and W. Volksen, Polymer 34, 1423 (1993).\n\n32J. C. Coburn, M. T. Pottiger, S. C. Noe, and S. D. Senturia, J. Polym. Sci. Part B: Polym. Phys. 32, 1271 (1994).\n\n33W. Wunderlich, in Polymer Handbook, 4th ed., edited by J. Brandrup, E. H. Immergut, and E. A. Grulke (John Wiley & Sons, Inc., NY, 1999), Chap. 5.\n\n34I. M. Ward, Structure and Properties of Oriented Polymers (Applied Science Publishers, London, 1975).\n\n35Y. Terui and S. Ando, J. Polym. Sci. Part B: Polym. Phys. 43, 2109 (2005).\n\n36S. Matsuda and S. Ando, J. Polym. Sci. Part B: Polym. Phys. 41, 418 (2003).\n\n37Y. Terui and S. Ando, J. Polym. Sci. Part B: Polym. Phys. 42, 2354 (2004).\n\n38M. F. Vuks, Opt. Spectrosc. 20, 361 (1964).\n\n40F. Li, S. Fang, J. J. Ge, P. S. Honigfort, J.-C. Cheng, F. W. Harris, and S. Z. D. Cheng, Polymer 40, 4571 (1999).\n\n41H.-T. Kim, S.-K. Kim, and J.-K. Park, Polym. J. 31, 154 (1999).\n\n42K. Osaki, T. Inoue, E.-J. Hwang, H. Okamoto, and O. Takiguchi, J. Non- Crystal. Solid 172–174, 838 (1994).\n\n43N. Keil, H. H. Yao, C. Zawadzki, J. Bauer, M. Bauer, C. Dreyer, and J. Schneider, Electron. Lett. 37, 579 (2001).\n\n44C. L. Callender, J. Jiang, C. Blanchetiere, J. P. Walker, S. J. Mihailov, J. Ding, and M. Day, Proc. Mater. Res. Soc. Symp. 817, 195 (2004).\n\n45S. Numata and T. Miwa, Polymer 30, 1170 (1989).\n\n46M. T. Pottiger, J. C. Coburn, and J. R. Edman, J. Polym. Sci. Part. B: Polym. Phys. 32, 825 (1994).\n\n47H.-C. Liou, P. S. Ho, and R. Stierman, Thin Solid Film 339, 68 (1999).\n\n" + } +] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/core_text_data/double_column_input.json b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/core_text_data/double_column_input.json new file mode 100644 index 0000000000000000000000000000000000000000..fda2a4f852bd683b906bfae817eafbb8d42d9812 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/core_text_data/double_column_input.json @@ -0,0 +1,18 @@ +[ + { + "role": "pig", + "term": "eat" + }, + { + "role": "tiger", + "term": "chase" + }, + { + "role": "people", + "term": "drink" + }, + { + "role": "bird", + "term": "dance" + } +] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/core_text_data/eval_data.json b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/core_text_data/eval_data.json new file mode 100644 index 0000000000000000000000000000000000000000..e387761589a0cd48d169b54254277814e6fbcd08 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/core_text_data/eval_data.json @@ -0,0 +1,42 @@ +[ + { + "conversations": [ + {"from": "human", "value": "Hi, can you explain what machine learning is?"}, + {"from": "gpt", "value": "Sure! Machine learning is a field of artificial intelligence where systems learn patterns from data and improve their performance without being explicitly programmed."}, + {"from": "human", "value": "Can you give me a simple example?"}, + {"from": "gpt", "value": "Of course. A classic example is spam email detection. The system learns from many examples of spam and non-spam emails, then predicts whether new emails are spam."} + ] + }, + { + "conversations": [ + {"from": "human", "value": "What is the capital of France?"}, + {"from": "gpt", "value": "The capital of France is Paris."}, + {"from": "human", "value": "And what about Germany?"}, + {"from": "gpt", "value": "Germany’s capital is Berlin."} + ] + }, + { + "conversations": [ + {"from": "human", "value": "帮我写一个Python函数,计算两个数的最大公约数"}, + {"from": "gpt", "value": "可以使用欧几里得算法:\n```python\ndef gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n```"}, + {"from": "human", "value": "能举个例子吗?"}, + {"from": "gpt", "value": "当然,例如 `gcd(48, 18)` 会返回 `6`。"} + ] + }, + { + "conversations": [ + {"from": "human", "value": "What are the benefits of regular exercise?"}, + {"from": "gpt", "value": "Regular exercise improves cardiovascular health, strengthens muscles, boosts mood, reduces stress, and can help maintain a healthy weight."}, + {"from": "human", "value": "How many times per week is recommended?"}, + {"from": "gpt", "value": "Most guidelines suggest at least 150 minutes of moderate-intensity exercise per week, which can be split into about 30 minutes on 5 days."} + ] + }, + { + "conversations": [ + {"from": "human", "value": "请解释一下量子计算机和经典计算机的区别"}, + {"from": "gpt", "value": "经典计算机使用比特(bit),每个比特只能是0或1;而量子计算机使用量子比特(qubit),它可以同时处于0和1的叠加态。"}, + {"from": "human", "value": "那它为什么更强大?"}, + {"from": "gpt", "value": "因为量子叠加和量子纠缠,使得量子计算机能并行处理大量计算问题,在某些任务上比经典计算机快得多。"} + ] + } +] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/core_text_data/pipeline_small_chunk.json b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/core_text_data/pipeline_small_chunk.json new file mode 100644 index 0000000000000000000000000000000000000000..216648c39b68c8a459b481a4f8834f9e0dc1ce4e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/example/core_text_data/pipeline_small_chunk.json @@ -0,0 +1,32 @@ +[ + { + "text": "What is anatomy? Anatomy includes those structures that can be seen grossly (without the aid of magnification) and microscopically (with the aid of magnification). Typically, when used by itself, the term anatomy tends to mean gross or macroscopic anatomy—that is, the study of structures that can be seen without using a microscopic. Microscopic anatomy, also called histology, is the study of cells and tissues using a microscope. Anatomy forms the basis for the practice of medicine. Anatomy leads the physician toward an understanding of a patient’s disease, whether he or she is carrying out a physical examination or using the most advanced imaging techniques. Anatomy is also important for dentists, chiropractors, physical therapists, and all others involved in any aspect of patient treatment that begins with an analysis of clinical signs. The ability to interpret a clinical observation correctly is therefore the endpoint of a sound anatomical understanding. Observation and visualization are the primary techniques a student should use to learn anatomy. Anatomy is much more than just memorization of lists of names. Although the language of anatomy is important, the network of information needed to visualize the position of physical structures in a patient goes far beyond simple memorization. Knowing the names of the various branches of the external carotid artery is not the same as being able to visualize the course of the lingual artery from its origin in the neck to its termination in the tongue. Similarly, understanding the organization of the soft palate, how it is related to the oral and nasal cavities, and how it moves during swallowing is very different from being able to recite the names of its individual muscles and nerves. An understanding of anatomy requires an understanding of the context in which the terminology can be remembered. How can gross anatomy be studied? The term anatomy is derived from the Greek word temnein, meaning “to cut.” Clearly, therefore, the study of anatomy is linked, at its root, to dissection, although dissection of cadavers by students is now augmented, or even in some cases replaced, by viewing prosected (previously dissected) material and plastic models, or using computer teaching modules and other learning aids. Anatomy can be studied following either a regional or a systemic approach. With a regional approach, each region of the body is studied separately and all aspects of that region are studied at the same time. For example, if the thorax is to be studied, all of its structures are examined. This includes the vasculature, the nerves, the bones, the muscles, and all other structures and organs located in the region of the body defined as the thorax. After studying this region, the other regions of the body (i.e., the abdomen, pelvis, lower limb, upper limb, back, head, and neck) are studied in a similar fashion. In contrast, in a systemic approach, each system of the body is studied and followed throughout the entire body. For example, a study of the cardiovascular system looks at the heart and all of the blood vessels in the body. When this is completed, the nervous system (brain, spinal cord, and all the nerves) might be examined in detail. This approach continues for the whole body until every system, including the nervous, skeletal, muscular, gastrointestinal, respiratory, lymphatic, and reproductive systems, has been studied. Each of these approaches has benefits and deficiencies. The regional approach works very well if the anatomy course involves cadaver dissection but falls short when it comes to understanding the continuity of an entire system throughout the body. Similarly, the systemic approach fosters an understanding of an entire system throughout the body, but it is very difficult to coordinate this directly with a cadaver dissection or to acquire sufficient detail. The anatomical position The anatomical position is the standard reference position of the body used to describe the location of structures (Fig. 1.1). The body is in the anatomical position when standing upright with feet together, hands by the side and face looking forward. The mouth is closed and the facial expression is neutral. The rim of bone under the eyes is in the same horizontal plane as the top of the opening to the ear, and the eyes are open and focused on something in the distance. The palms of the hands face forward with the fingers straight and together and with the pad of the thumb turned 90° to the pads of the fingers. The toes point forward. Three major groups of planes pass through the body in the anatomical position (Fig. 1.1). Coronal planes are oriented vertically and divide the body into anterior and posterior parts. Sagittal planes also are oriented vertically but are at right angles to the coronal planes and divide the body into right and left parts. The plane that passes through the center of the body dividing it into equal right and left halves is termed the median sagittal plane. Transverse, horizontal, or axial planes divide the body into superior and inferior parts. Terms to describe location Anterior (ventral) and posterior (dorsal), medial and lateral, superior and inferior Three major pairs of terms are used to describe the location of structures relative to the body as a whole or to other structures (Fig. 1.1). Anterior (or ventral) and posterior (or dorsal) describe the position of structures relative to the “front” and “back” of the body. For example, the nose is an anterior (ventral) structure, whereas the vertebral column is a posterior (dorsal) structure. Also, the nose is anterior to the ears and the vertebral column is posterior to the sternum. Medial and lateral describe the position of structures relative to the median sagittal plane and the sides of the body. For example, the thumb is lateral to the little finger. The nose is in the median sagittal plane and is medial to the eyes, which are in turn medial to the external ears. Superior and inferior describe structures in reference to the vertical axis of the body. For example, the head is superior to the shoulders and the knee joint is inferior to the hip joint. Proximal and distal, cranial and caudal, Other terms used to describe positions include proximal and distal, cranial and caudal, and rostral. Proximal and distal are used with reference to being closer to or farther from a structure’s origin, particularly in the limbs. For example, the hand is distal to the elbow joint. The glenohumeral joint is proximal to the elbow joint. These terms are also used to describe the relative positions of branches along the course of linear structures, such as airways, vessels, and nerves. For example, distal branches occur farther away toward the ends of the system, whereas proximal branches occur closer to and toward the origin of the system. Cranial (toward the head) and caudal (toward the tail) are sometimes used instead of superior and inferior, respectively. Rostral is used, particularly in the head, to describe the position of a structure with reference to the nose. For example, the forebrain is rostral to the hindbrain. Two other terms used to describe the position of structures in the body are superficial and deep. These terms are used to describe the relative positions of two structures with respect to the surface of the body. For example, the sternum is superficial to the heart, and the stomach is deep to the abdominal wall. Superficial and deep can also be used in a more absolute fashion to define two major regions of the body. The superficial region of the body is external to the outer layer of deep fascia. Deep structures are enclosed by this layer. Structures in the superficial region of the body include the skin, superficial fascia, and mammary glands. Deep structures include most skeletal muscles and viscera. Superficial wounds are external to the outer layer of deep fascia, whereas deep wounds penetrate through it. In 1895 Wilhelm Roentgen used the X-rays from a cathode ray tube to expose a photographic plate and produce the first radiographic exposure of his wife’s hand. Over the past 35 years there has been a revolution in body imaging, which has been paralleled by developments in computer technology. X-rays are photons (a type of electromagnetic radiation) and are generated from a complex X-ray tube, which is a type of cathode ray tube (Fig. 1.2). The X-rays are then collimated (i.e., directed through lead-lined shutters to stop them from fanning out) to the appropriate area of the body. As the X-rays pass through the body they are attenuated (reduced in energy) by the tissues. Those X-rays that pass through the tissues interact with the photographic film. In the body: air attenuates X-rays a little; fat attenuates X-rays more than air but less than bone attenuates X-rays the most. These differences in attenuation result in differences in the level of exposure of the film. When the photographic film is developed, bone appears white on the film because this region of the film has been exposed to the least amount of X-rays. Air appears dark on the film because these regions were exposed to the greatest number of X-rays. Modifications to this X-ray technique allow a continuous stream of X-rays to be produced from the X-ray tube and collected on an input screen to allow real-time visualization of moving anatomical structures, barium studies, angiography, and fluoroscopy (Fig. 1.3). To demonstrate specific structures, such as bowel loops or arteries, it may be necessary to fill these structures with a substance that attenuates X-rays more than bowel loops or arteries do normally. It is, however, extremely important that these substances are nontoxic. Barium sulfate, an insoluble salt, is a nontoxic, relatively high-density agent that is extremely useful in the examination of the gastrointestinal tract. When a barium sulfate suspension is ingested it attenuates" + }, + { + "text": "tissues interact with the photographic film. In the body: air attenuates X-rays a little; fat attenuates X-rays more than air but less than bone attenuates X-rays the most. These differences in attenuation result in differences in the level of exposure of the film. When the photographic film is developed, bone appears white on the film because this region of the film has been exposed to the least amount of X-rays. Air appears dark on the film because these regions were exposed to the greatest number of X-rays. Modifications to this X-ray technique allow a continuous stream of X-rays to be produced from the X-ray tube and collected on an input screen to allow real-time visualization of moving anatomical structures, barium studies, angiography, and fluoroscopy (Fig. 1.3). To demonstrate specific structures, such as bowel loops or arteries, it may be necessary to fill these structures with a substance that attenuates X-rays more than bowel loops or arteries do normally. It is, however, extremely important that these substances are nontoxic. Barium sulfate, an insoluble salt, is a nontoxic, relatively high-density agent that is extremely useful in the examination of the gastrointestinal tract. When a barium sulfate suspension is ingested it attenuates X-rays and can therefore be used to demonstrate the bowel lumen (Fig. 1.4). It is common to add air to the barium sulfate suspension, by either ingesting “fizzy” granules or directly instilling air into the body cavity, as in a barium enema. This is known as a double-contrast (air/barium) study. For some patients it is necessary to inject contrast agents directly into arteries or veins. In this case, iodine-based molecules are suitable contrast agents. Iodine is chosen because it has a relatively high atomic mass and so markedly attenuates X-rays, but also, importantly, it is naturally excreted via the urinary system. Intra-arterial and intravenous contrast agents are extremely safe and are well tolerated by most patients. Rarely, some patients have an anaphylactic reaction to intra-arterial or intravenous injections, so the necessary precautions must be taken. Intra-arterial and intravenous contrast agents not only help in visualizing the arteries and veins but because they are excreted by the urinary system, can also be used to visualize the kidneys, ureter, and bladder in a process known as intravenous urography. During angiography it is often difficult to appreciate the contrast agent in the vessels through the overlying bony structures. To circumvent this, the technique of subtraction angiography has been developed. Simply, one or two images are obtained before the injection of contrast media. These images are inverted (such that a negative is created from the positive image). After injection of the contrast media into the vessels, a further series of images are obtained, demonstrating the passage of the contrast through the arteries into the veins and around the circulation. By adding the “negative precontrast image” to the positive postcontrast images, the bones and soft tissues are subtracted to produce a solitary image of contrast only. Before the advent of digital imaging this was a challenge, but now the use of computers has made this technique relatively straightforward and instantaneous (Fig. 1.5). Ultrasonography of the body is widely used for all aspects of medicine. Ultrasound is a very high frequency sound wave (not electromagnetic radiation) generated by piezoelectric materials, such that a series of sound waves is produced. Importantly, the piezoelectric material can also receive the sound waves that bounce back from the internal organs. The sound waves are then interpreted by a powerful computer, and a real-time image is produced on the display panel. Developments in ultrasound technology, including the size of the probes and the frequency range, mean that a broad range of areas can now be scanned. Traditionally ultrasound is used for assessing the abdomen (Fig. 1.6) and the fetus in pregnant women. Ultrasound is also widely used to assess the eyes, neck, soft tissues, and peripheral musculoskeletal system. Probes have been placed on endoscopes, and endoluminal ultrasound of the esophagus, stomach, and duodenum is now routine. Endocavity ultrasound is carried out most commonly to assess the genital tract in women using a transvaginal or transrectal route. In men, transrectal ultrasound is the imaging method of choice to assess the prostate in those with suspected prostate hypertrophy or malignancy. Doppler ultrasound enables determination of flow, its direction, and its velocity within a vessel using simple ultrasound techniques. Sound waves bounce off moving structures and are returned. The degree of frequency shift determines whether the object is moving away from or toward the probe and the speed at which it is traveling. Precise measurements of blood flow and blood velocity can therefore be obtained, which in turn can indicate sites of blockage in blood vessels. Computed tomography (CT) was invented in the 1970s by Sir Godfrey Hounsfield, who was awarded the Nobel Prize in Medicine in 1979. Since this inspired invention there have been many generations of CT scanners. A CT scanner obtains a series of images of the body (slices) in the axial plane. The patient lies on a bed, an X-ray tube passes around the body (Fig. 1.7), and a series of images are obtained. A computer carries out a complex mathematical transformation on the multitude of images to produce the final image (Fig. 1.8). Nuclear magnetic resonance imaging was first described in 1946 and used to determine the structure of complex molecules. The process of magnetic resonance imaging (MRI) is dependent on the free protons in the hydrogen nuclei in molecules of water (H2O). Because water is present in almost all biological tissues, the hydrogen proton is ideal. The protons within a patient’s hydrogen nuclei can be regarded as small bar magnets, which are randomly oriented in space. The patient is placed in a strong magnetic field, which aligns the bar magnets. When a pulse of radio waves is passed through the patient the magnets are deflected, and as they return to their aligned position they emit small radio pulses. The strength and frequency of the emitted pulses and the time it takes for the protons to return to their pre-excited state produce a signal. These signals are analyzed by a powerful computer, and an image is created (Fig. 1.9). By altering the sequence of pulses to which the protons are subjected, different properties of the protons can be assessed. These properties are referred to as the “weighting” of the scan. By altering the pulse sequence and the scanning parameters, T1-weighted images (Fig. 1.10A) and T2-weighted images (Fig. 1.10B) can be obtained. These two types of imaging sequences provide differences in image contrast, which accentuate and optimize different tissue characteristics. From the clinical point of view: Most T1-weighted images show dark fluid and bright fat—for example, within the brain the cerebrospinal fluid (CSF) is dark. T2-weighted images demonstrate a bright signal from fluid and an intermediate signal from fat—for example, in the brain the CSF appears white. MRI can also be used to assess flow within vessels and to produce complex angiograms of the peripheral and cerebral circulation. Diffusion-weighted imaging provides information on the degree of Brownian motion of water molecules in various tissues. There is relatively free diffusion in extracellular spaces and more restricted diffusion in intracellular spaces. In tumors and infarcted tissue, there is an increase in intracellular fluid water molecules compared with the extracellular fluid environment resulting in overall increased restricted diffusion, and therefore identification of abnormal from normal tissue. Nuclear medicine involves imaging using gamma rays, which are another type of electromagnetic radiation. The important difference between gamma rays and X-rays is that gamma rays are produced from within the nucleus of an atom when an unstable nucleus decays, whereas X-rays are produced by bombarding an atom with electrons. For an area to be visualized, the patient must receive a gamma ray emitter, which must have a number of properties to be useful, including: a reasonable half-life (e.g., 6 to 24 hours), an easily measurable gamma ray, and energy deposition in as low a dose as possible in the patient’s tissues. The most commonly used radionuclide (radioisotope) is technetium-99m. This may be injected as a technetium salt or combined with other complex molecules. For example, by combining technetium-99m with methylene diphosphonate (MDP), a radiopharmaceutical is produced. When injected into the body this radiopharmaceutical specifically binds to bone, allowing assessment of the skeleton. Similarly, combining technetium-99m with other compounds permits assessment of other parts of the body, for example the urinary tract and cerebral blood flow. Depending on how the radiopharmaceutical is absorbed, distributed, metabolized, and excreted by the body after injection, images are obtained using a gamma camera (Fig. 1.11). Positron emission tomography (PET) is an imaging modality for detecting positron-emitting radionuclides. A positron is an anti-electron, which is a positively charged particle of antimatter. Positrons are emitted from the decay of proton-rich radionuclides. Most of these radionuclides are made in a cyclotron and have extremely short half-lives. The most commonly used PET radionuclide is fluorodeoxyglucose (FDG) labeled with fluorine-18 (a positron emitter). Tissues that are actively metabolizing glucose take up this compound, and the resulting localized high concentration of" + }, + { + "text": "ium-99m with methylene diphosphonate (MDP), a radiopharmaceutical is produced. When injected into the body this radiopharmaceutical specifically binds to bone, allowing assessment of the skeleton. Similarly, combining technetium-99m with other compounds permits assessment of other parts of the body, for example the urinary tract and cerebral blood flow. Depending on how the radiopharmaceutical is absorbed, distributed, metabolized, and excreted by the body after injection, images are obtained using a gamma camera (Fig. 1.11). Positron emission tomography (PET) is an imaging modality for detecting positron-emitting radionuclides. A positron is an anti-electron, which is a positively charged particle of antimatter. Positrons are emitted from the decay of proton-rich radionuclides. Most of these radionuclides are made in a cyclotron and have extremely short half-lives. The most commonly used PET radionuclide is fluorodeoxyglucose (FDG) labeled with fluorine-18 (a positron emitter). Tissues that are actively metabolizing glucose take up this compound, and the resulting localized high concentration of this molecule compared to background emission is detected as a “hot spot.” PET has become an important imaging modality in the detection of cancer and the assessment of its treatment and recurrence. Single photon emission computed tomography (SPECT) is an imaging modality for detecting gamma rays emitted from the decay of injected radionuclides such as technetium-99m, iodine-123, or iodine-131. The rays are detected by a 360-degree rotating camera, which allows the construction of 3D images. SPECT can be used to diagnose a wide range of disease conditions such as coronary artery disease and bone fractures. Imaging is necessary in most clinical specialties to diagnose pathological changes to tissues. It is paramount to appreciate what is normal and what is abnormal. An appreciation of how the image is obtained, what the normal variations are, and what technical considerations are necessary to obtain a radiological diagnosis. Without understanding the anatomy of the region imaged, it is impossible to comment on the abnormal. Plain radiographs are undoubtedly the most common form of image obtained in a hospital or local practice. Before interpretation, it is important to know about the imaging technique and the views obtained as standard. In most instances (apart from chest radiography) the X-ray tube is 1 m away from the X-ray film. The object in question, for example a hand or a foot, is placed upon the film. When describing subject placement for radiography, the part closest to the X-ray tube is referred to first and that closest to the film is referred to second. For example, when positioning a patient for an anteroposterior (AP) radiograph, the more anterior part of the body is closest to the tube and the posterior part is closest to the film. When X-rays are viewed on a viewing box, the right side of the patient is placed to the observer’s left; therefore, the observer views the radiograph as though looking at a patient in the anatomical position. The chest radiograph is one of the most commonly requested plain radiographs. An image is taken with the patient erect and placed posteroanteriorly (PA chest radiograph; that is, with the patient’s back closest to the X-ray tube.). Occasionally, when patients are too unwell to stand erect, films are obtained on the bed in an anteroposterior (AP) position. These films are less standardized than PA films, and caution should always be taken when interpreting AP radiographs. The plain chest radiograph should always be checked for quality. Film markers should be placed on the appropriate side. (Occasionally patients have dextrocardia, which may be misinterpreted if the film marker is placed inappropriately.) A good-quality chest radiograph will demonstrate the lungs, cardiomediastinal contour, diaphragm, ribs, and peripheral soft tissues. Plain abdominal radiographs are obtained in the AP supine position. From time to time an erect plain abdominal radiograph is obtained when small bowel obstruction is suspected. High-density contrast medium is ingested to opacify the esophagus, stomach, small bowel, and large bowel. As described previously (p. 6), the bowel is insufflated with air (or carbon dioxide) to provide a double-contrast study. In many countries, endoscopy has superseded upper gastrointestinal imaging, but the mainstay of imaging the large bowel is the double-contrast barium enema. Typically the patient needs to undergo bowel preparation, in which powerful cathartics are used to empty the bowel. At the time of the examination a small tube is placed into the rectum and a barium suspension is run into the large bowel. The patient undergoes a series of twists and turns so that the contrast passes through the entire large bowel. The contrast is emptied and air is passed through the same tube to insufflate the large bowel. A thin layer of barium coats the normal mucosa, allowing mucosal detail to be visualized (see Fig. 1.4). Intravenous urography is the standard investigation for assessing the urinary tract. Intravenous contrast medium is injected, and images are obtained as the medium is excreted through the kidneys. A series of films are obtained during this period from immediately after the injection up to approximately 20 minutes later, when the bladder is full of contrast medium. This series of radiographs demonstrates the kidneys, ureters, and bladder and enables assessment of the retroperitoneum and other structures that may press on the urinary tract. Computed tomography is the preferred terminology rather than computerized tomography, though both terms are used interchangeably by physicians. It is important for the student to understand the presentation of images. Most images are acquired in the axial plane and viewed such that the observer looks from below and upward toward the head (from the foot of the bed). By implication: the right side of the patient is on the left side of the image, and the uppermost border of the image is anterior. Many patients are given oral and intravenous contrast media to differentiate bowel loops from other abdominal organs and to assess the vascularity of normal anatomical structures. When intravenous contrast is given, the earlier the images are obtained, the greater the likelihood of arterial enhancement. As the time is delayed between injection and image acquisition, a venous phase and an equilibrium phase are also obtained. The great advantage of CT scanning is the ability to extend and compress the gray scale to visualize the bones, soft tissues, and visceral organs. Altering the window settings and window centering provides the physician with specific information about these structures. There is no doubt that MRI has revolutionized the understanding and interpretation of the brain and its coverings. Furthermore, it has significantly altered the practice of musculoskeletal medicine and surgery. Images can be obtained in any plane and in most sequences. Typically the images are viewed using the same principles as CT. Intravenous contrast agents are also used to further enhance tissue contrast. Typically, MRI contrast agents contain paramagnetic substances (e.g., gadolinium and manganese). Most nuclear medicine images are functional studies. Images are usually interpreted directly from a computer, and a series of representative films are obtained for clinical use. Whenever a patient undergoes an X-ray or nuclear medicine investigation, a dose of radiation is given (Table 1.1). As a general principle it is expected that the dose given is as low as reasonably possible for a diagnostic image to be obtained. Numerous laws govern the amount of radiation exposure that a patient can undergo for a variety of procedures, and these are monitored to prevent any excess or additional dosage. Whenever a radiograph is booked, the clinician ordering the procedure must appreciate its necessity and understand the dose given to the patient to ensure that the benefits significantly outweigh the risks. Imaging modalities such as ultrasound and MRI are ideal because they do not impart significant risk to the patient. Moreover, ultrasound imaging is the modality of choice for assessing the fetus. Any imaging device is expensive, and consequently the more complex the imaging technique (e.g., MRI) the more expensive the investigation. Investigations must be carried out judiciously, based on a sound clinical history and examination, for which an understanding of anatomy is vital. The skeleton can be divided into two subgroups, the axial skeleton and the appendicular skeleton. The axial skeleton consists of the bones of the skull (cranium), vertebral column, ribs, and sternum, whereas the appendicular skeleton consists of the bones of the upper and lower limbs (Fig. 1.12). The skeletal system consists of cartilage and bone. Cartilage is an avascular form of connective tissue consisting of extracellular fibers embedded in a matrix that contains cells localized in small cavities. The amount and kind of extracellular fibers in the matrix varies depending on the type of cartilage. In heavy weightbearing areas or areas prone to pulling forces, the amount of collagen is greatly increased and the cartilage is almost inextensible. In contrast, in areas where weightbearing demands and stress are less, cartilage containing elastic fibers and fewer collagen fibers is common. The functions of cartilage are to: support soft tissues, provide a smooth, gliding surface for bone articulations at joints, and enable the development and growth of long bones. There are three types of cartilage: hyaline—most common; matrix contains a moderate amount of collagen fibers (e.g., articular surfaces of bones); elastic—matrix contains collagen fibers along with a large number of elastic fibers (e.g., external ear); fibrocartilage—matrix contains a limited number of cells and ground substance amidst a substantial amount of collagen fibers (e.g., intervertebral discs). Cartilage is nour" + }, + { + "text": "the bones of the upper and lower limbs (Fig. 1.12). The skeletal system consists of cartilage and bone. Cartilage is an avascular form of connective tissue consisting of extracellular fibers embedded in a matrix that contains cells localized in small cavities. The amount and kind of extracellular fibers in the matrix varies depending on the type of cartilage. In heavy weightbearing areas or areas prone to pulling forces, the amount of collagen is greatly increased and the cartilage is almost inextensible. In contrast, in areas where weightbearing demands and stress are less, cartilage containing elastic fibers and fewer collagen fibers is common. The functions of cartilage are to: support soft tissues, provide a smooth, gliding surface for bone articulations at joints, and enable the development and growth of long bones. There are three types of cartilage: hyaline—most common; matrix contains a moderate amount of collagen fibers (e.g., articular surfaces of bones); elastic—matrix contains collagen fibers along with a large number of elastic fibers (e.g., external ear); fibrocartilage—matrix contains a limited number of cells and ground substance amidst a substantial amount of collagen fibers (e.g., intervertebral discs). Cartilage is nourished by diffusion and has no blood vessels, lymphatics, or nerves. Bone is a calcified, living, connective tissue that forms the majority of the skeleton. It consists of an intercellular calcified matrix, which also contains collagen fibers, and several types of cells within the matrix. Bones function as: supportive structures for the body, protectors of vital organs, reservoirs of calcium and phosphorus, levers on which muscles act to produce movement, and containers for blood-producing cells. There are two types of bone, compact and spongy (trabecular or cancellous). Compact bone is dense bone that forms the outer shell of all bones and surrounds spongy bone. Spongy bone consists of spicules of bone enclosing cavities containing blood-forming cells (marrow). Classification of bones is by shape. Long bones are tubular (e.g., humerus in upper limb; femur in lower limb). Short bones are cuboidal (e.g., bones of the wrist and ankle). Flat bones consist of two compact bone plates separated by spongy bone (e.g., skull). Irregular bones are bones with various shapes (e.g., bones of the face). Sesamoid bones are round or oval bones that develop in tendons. Bones are vascular and are innervated. Generally, an adjacent artery gives off a nutrient artery, usually one per bone, that directly enters the internal cavity of the bone and supplies the marrow, spongy bone, and inner layers of compact bone. In addition, all bones are covered externally, except in the area of a joint where articular cartilage is present, by a fibrous connective tissue membrane called the periosteum, which has the unique capability of forming new bone. This membrane receives blood vessels whose branches supply the outer layers of compact bone. A bone stripped of its periosteum will not survive. Nerves accompany the vessels that supply the bone and the periosteum. Most of the nerves passing into the internal cavity with the nutrient artery are vasomotor fibers that regulate blood flow. Bone itself has few sensory nerve fibers. On the other hand, the periosteum is supplied with numerous sensory nerve fibers and is very sensitive to any type of injury. Developmentally, all bones come from mesenchyme by either intramembranous ossification, in which mesenchymal models of bones undergo ossification, or endochondral ossification, in which cartilaginous models of bones form from mesenchyme and undergo ossification. The sites where two skeletal elements come together are termed joints. The two general categories of joints (Fig. 1.18) are those in which: the skeletal elements are separated by a cavity (i.e., synovial joints), and there is no cavity and the components are held together by connective tissue (i.e., solid joints). Blood vessels that cross over a joint and nerves that innervate muscles acting on a joint usually contribute articular branches to that joint. Synovial joints are connections between skeletal components where the elements involved are separated by a narrow articular cavity (Fig. 1.19). In addition to containing an articular cavity, these joints have a number of characteristic features. First, a layer of cartilage, usually hyaline cartilage, covers the articulating surfaces of the skeletal elements. In other words, bony surfaces do not normally contact one another directly. As a consequence, when these joints are viewed in normal radiographs, a wide gap seems to separate the adjacent bones because the cartilage that covers the articulating surfaces is more transparent to X-rays than bone. A second characteristic feature of synovial joints is the presence of a joint capsule consisting of an inner synovial membrane and an outer fibrous membrane. The synovial membrane attaches to the margins of the joint surfaces at the interface between the cartilage and bone and encloses the articular cavity. The synovial membrane is highly vascular and produces synovial fluid, which percolates into the articular cavity and lubricates the articulating surfaces. Closed sacs of synovial membrane also occur outside joints, where they form synovial bursae or tendon sheaths. Bursae often intervene between structures, such as tendons and bone, tendons and joints, or skin and bone, and reduce the friction of one structure moving over the other. Tendon sheaths surround tendons and also reduce friction. The fibrous membrane is formed by dense connective tissue and surrounds and stabilizes the joint. Parts of the fibrous membrane may thicken to form ligaments, which further stabilize the joint. Ligaments outside the capsule usually provide additional reinforcement. Another common but not universal feature of synovial joints is the presence of additional structures within the area enclosed by the capsule or synovial membrane, such as articular discs (usually composed of fibrocartilage), fat pads, and tendons. Articular discs absorb compression forces, adjust to changes in the contours of joint surfaces during movements, and increase the range of movements that can occur at joints. Fat pads usually occur between the synovial membrane and the capsule and move into and out of regions as joint contours change during movement. Redundant regions of the synovial membrane and fibrous membrane allow for large movements at joints. Descriptions of synovial joints based on shape and movement Synovial joints are described based on shape and movement: based on the shape of their articular surfaces, synovial joints are described as plane (flat), hinge, pivot, bicondylar (two sets of contact points), condylar (ellipsoid), saddle, and ball and socket; based on movement, synovial joints are described as uniaxial (movement in one plane), biaxial (movement in two planes), and multiaxial (movement in three planes). Hinge joints are uniaxial, whereas ball and socket joints are multiaxial. Specific types of synovial joints (Fig. 1.20) Plane joints—allow sliding or gliding movements when one bone moves across the surface of another (e.g., acromioclavicular joint) Hinge joints—allow movement around one axis that passes transversely through the joint; permit flexion and extension (e.g., elbow [humero-ulnar] joint) Pivot joints—allow movement around one axis that passes longitudinally along the shaft of the bone; permit rotation (e.g., atlanto-axial joint) Bicondylar joints—allow movement mostly in one axis with limited rotation around a second axis; formed by two convex condyles that articulate with concave or flat surfaces (e.g., knee joint) Condylar (ellipsoid) joints—allow movement around two axes that are at right angles to each other; permit flexion, extension, abduction, adduction, and circumduction (limited) (e.g., wrist joint) Saddle joints—allow movement around two axes that are at right angles to each other; the articular surfaces are saddle shaped; permit flexion, extension, abduction, adduction, and circumduction (e.g., carpometacarpal joint of the thumb) Ball and socket joints—allow movement around multiple axes; permit flexion, extension, abduction, adduction, circumduction, and rotation (e.g., hip Solid joints are connections between skeletal elements where the adjacent surfaces are linked together either by fibrous connective tissue or by cartilage, usually fibrocartilage (Fig. 1.21). Movements at these joints are more restricted than at synovial joints. Fibrous joints include sutures, gomphoses, and syndesmoses. Sutures occur only in the skull where adjacent bones are linked by a thin layer of connective tissue termed a sutural ligament. Gomphoses occur only between the teeth and adjacent bone. In these joints, short collagen tissue fibers in the periodontal ligament run between the root of the tooth and the bony socket. Syndesmoses are joints in which two adjacent bones are linked by a ligament. Examples are the ligamentum flavum, which connects adjacent vertebral laminae, and an interosseous membrane, which links, for example, the radius and ulna in the forearm. Cartilaginous joints include synchondroses and symphyses. Synchondroses occur where two ossification centers in a developing bone remain separated by a layer of cartilage, for example, the growth plate that occurs between the head and shaft of developing long bones. These joints allow bone growth and eventually become" + }, + { + "text": "linked together either by fibrous connective tissue or by cartilage, usually fibrocartilage (Fig. 1.21). Movements at these joints are more restricted than at synovial joints. Fibrous joints include sutures, gomphoses, and syndesmoses. Sutures occur only in the skull where adjacent bones are linked by a thin layer of connective tissue termed a sutural ligament. Gomphoses occur only between the teeth and adjacent bone. In these joints, short collagen tissue fibers in the periodontal ligament run between the root of the tooth and the bony socket. Syndesmoses are joints in which two adjacent bones are linked by a ligament. Examples are the ligamentum flavum, which connects adjacent vertebral laminae, and an interosseous membrane, which links, for example, the radius and ulna in the forearm. Cartilaginous joints include synchondroses and symphyses. Synchondroses occur where two ossification centers in a developing bone remain separated by a layer of cartilage, for example, the growth plate that occurs between the head and shaft of developing long bones. These joints allow bone growth and eventually become completely ossified. Symphyses occur where two separate bones are interconnected by cartilage. Most of these types of joints occur in the midline and include the pubic symphysis between the two pelvic bones, and intervertebral discs between adjacent vertebrae. The skin is the largest organ of the body. It consists of the epidermis and the dermis. The epidermis is the outer cellular layer of stratified squamous epithelium, which is avascular and varies in thickness. The dermis is a dense bed of vascular connective tissue. The skin functions as a mechanical and permeability barrier, and as a sensory and thermoregulatory organ. It also can initiate primary immune responses. Fascia is connective tissue containing varying amounts of fat that separate, support, and interconnect organs and structures, enable movement of one structure relative to another, and allow the transit of vessels and nerves from one area to another. There are two general categories of fascia: superficial and deep. Superficial (subcutaneous) fascia lies just deep to and is attached to the dermis of the skin. It is made up of loose connective tissue usually containing a large amount of fat. The thickness of the superficial fascia (subcutaneous tissue) varies considerably, both from one area of the body to another and from one individual to another. The superficial fascia allows movement of the skin over deeper areas of the body, acts as a conduit for vessels and nerves coursing to and from the skin, and serves as an energy (fat) reservoir. Deep fascia usually consists of dense, organized connective tissue. The outer layer of deep fascia is attached to the deep surface of the superficial fascia and forms a thin fibrous covering over most of the deeper region of the body. Inward extensions of this fascial layer form intermuscular septa that compartmentalize groups of muscles with similar functions and innervations. Other extensions surround individual muscles and groups of vessels and nerves, forming an investing fascia. Near some joints the deep fascia thickens, forming retinacula. These fascial retinacula hold tendons in place and prevent them from bowing during movements at the joints. Finally, there is a layer of deep fascia separating the membrane lining the abdominal cavity (the parietal peritoneum) from the fascia covering the deep surface of the muscles of the abdominal wall (the transversalis fascia). This layer is referred to as extraperitoneal fascia. A similar layer of fascia in the thorax is termed the endothoracic fascia. The muscular system is generally regarded as consisting of one type of muscle found in the body—skeletal muscle. However, there are two other types of muscle tissue found in the body, smooth muscle and cardiac muscle, that are important components of other systems. These three types of muscle can be characterized by whether they are controlled voluntarily or involuntarily, whether they appear striated (striped) or smooth, and whether they are associated with the body wall (somatic) or with organs and blood vessels (visceral). Skeletal muscle forms the majority of the muscle tissue in the body. It consists of parallel bundles of long, multinucleated fibers with transverse stripes, is capable of powerful contractions, and is innervated by somatic and branchial motor nerves. This muscle is used to move bones and other structures, and provides support and gives form to the body. Individual skeletal muscles are often named on the basis of shape (e.g., rhomboid major muscle), attachments (e.g., sternohyoid muscle), function (e.g., flexor pollicis longus muscle), position (e.g., palmar interosseous muscle), or fiber orientation (e.g., external oblique muscle). Cardiac muscle is striated muscle found only in the walls of the heart (myocardium) and in some of the large vessels close to where they join the heart. It consists of a branching network of individual cells linked electrically and mechanically to work as a unit. Its contractions are less powerful than those of skeletal muscle and it is resistant to fatigue. Cardiac muscle is innervated by visceral motor nerves. Smooth muscle (absence of stripes) consists of elongated or spindle-shaped fibers capable of slow and sustained contractions. It is found in the walls of blood vessels (tunica media), associated with hair follicles in the skin, located in the eyeball, and found in the walls of various structures associated with the gastrointestinal, respiratory, genitourinary, and urogenital systems. Smooth muscle is innervated by visceral motor nerves. The cardiovascular system consists of the heart, which pumps blood throughout the body, and the blood vessels, which are a closed network of tubes that transport the blood. There are three types of blood vessels: arteries, which transport blood away from the heart; veins, which transport blood toward the heart; capillaries, which connect the arteries and veins, are the smallest of the blood vessels and are where oxygen, nutrients, and wastes are exchanged within the tissues. The walls of the blood vessels of the cardiovascular system usually consist of three layers or tunics: tunica externa (adventitia)—the outer connective tissue layer, tunica media—the middle smooth muscle layer (may also contain varying amounts of elastic fibers in medium and large arteries), and tunica intima—the inner endothelial lining of the blood vessels. Arteries are usually further subdivided into three classes, according to the variable amounts of smooth muscle and elastic fibers contributing to the thickness of the tunica media, the overall size of the vessel, and its function. Large elastic arteries contain substantial amounts of elastic fibers in the tunica media, allowing expansion and recoil during the normal cardiac cycle. This helps maintain a constant flow of blood during diastole. Examples of large elastic arteries are the aorta, the brachiocephalic trunk, the left common carotid artery, the left subclavian artery, and the pulmonary trunk. Medium muscular arteries are composed of a tunica media that contains mostly smooth muscle fibers. This characteristic allows these vessels to regulate their diameter and control the flow of blood to different parts of the body. Examples of medium muscular arteries are most of the named arteries, including the femoral, axillary, and radial arteries. Small arteries and arterioles control the filling of the capillaries and directly contribute to the arterial pressure in the vascular system. Veins also are subdivided into three classes. Large veins contain some smooth muscle in the tunica media, but the thickest layer is the tunica externa. Examples of large veins are the superior vena cava, the inferior vena cava, and the portal vein. Small and medium veins contain small amounts of smooth muscle, and the thickest layer is the tunica externa. Examples of small and medium veins are superficial veins in the upper and lower limbs and deeper veins of the leg and forearm. Venules are the smallest veins and drain the capillaries. Although veins are similar in general structure to arteries, they have a number of distinguishing features. The walls of veins, specifically the tunica media, are thin. The luminal diameters of veins are large. There often are multiple veins (venae comitantes) closely associated with arteries in peripheral regions. Valves often are present in veins, particularly in peripheral vessels inferior to the level of the heart. These are usually paired cusps that facilitate blood flow toward the heart. More specific information about the cardiovascular system and how it relates to the circulation of blood throughout the body will be discussed, where appropriate, in each of the succeeding chapters of the text. Lymphatic vessels form an extensive and complex interconnected network of channels, which begin as “porous” blind-ended lymphatic capillaries in tissues of the body and converge to form a number of larger vessels, which ultimately connect with large veins in the root of the neck. Lymphatic vessels mainly collect fluid lost from vascular capillary beds during nutrient exchange processes and deliver it back to the venous side of the vascular system (Fig. 1.28). Also included in this interstitial fluid that drains into the lymphatic capillaries are pathogens, cells of the lymphocytic system, cell products (such as hormones), and cell debris. In the small intestine, certain fats absorbed and processed by the intestinal epithelium are packaged into protein-coated lipid droplets (chylomicrons), which are released from the epithelial cells and enter the interstitial compartment. Together with other components of the interstitial fluid, the chylomicrons drain into lymphatic capillaries (known as lacte" + }, + { + "text": "These are usually paired cusps that facilitate blood flow toward the heart. More specific information about the cardiovascular system and how it relates to the circulation of blood throughout the body will be discussed, where appropriate, in each of the succeeding chapters of the text. Lymphatic vessels form an extensive and complex interconnected network of channels, which begin as “porous” blind-ended lymphatic capillaries in tissues of the body and converge to form a number of larger vessels, which ultimately connect with large veins in the root of the neck. Lymphatic vessels mainly collect fluid lost from vascular capillary beds during nutrient exchange processes and deliver it back to the venous side of the vascular system (Fig. 1.28). Also included in this interstitial fluid that drains into the lymphatic capillaries are pathogens, cells of the lymphocytic system, cell products (such as hormones), and cell debris. In the small intestine, certain fats absorbed and processed by the intestinal epithelium are packaged into protein-coated lipid droplets (chylomicrons), which are released from the epithelial cells and enter the interstitial compartment. Together with other components of the interstitial fluid, the chylomicrons drain into lymphatic capillaries (known as lacteals in the small intestine) and are ultimately delivered to the venous system in the neck. The lymphatic system is therefore also a major route of transport for fat absorbed by the gut. The fluid in most lymphatic vessels is clear and colorless and is known as lymph. That carried by lymphatic vessels from the small intestine is opaque and milky because of the presence of chylomicrons and is termed chyle. There are lymphatic vessels in most areas of the body, including those associated with the central nervous system (Louveau A et al., Nature 2015; 523:337-41; Aspelund A et al., J Exp Med 2015; 212:991-9). Exceptions include bone marrow and avascular tissues such as epithelia and cartilage. The movement of lymph through the lymphatic vessels is generated mainly by the indirect action of adjacent structures, particularly by contraction of skeletal muscles and pulses in arteries. Unidirectional flow is maintained by the presence of valves in the vessels. Lymph nodes are small (0.1–2.5 cm long) encapsulated structures that interrupt the course of lymphatic vessels and contain elements of the body’s defense system, such as clusters of lymphocytes and macrophages. They act as elaborate filters that trap and phagocytose particulate matter in the lymph that percolates through them. In addition, they detect and defend against foreign antigens that are also carried in the lymph (Fig. 1.28). Because lymph nodes are efficient filters and flow through them is slow, cells that metastasize from (migrate away from) primary tumors and enter lymphatic vessels often lodge and grow as secondary tumors in lymph nodes. Lymph nodes that drain regions that are infected or contain other forms of disease can enlarge or undergo certain physical changes, such as becoming “hard” or “tender.” These changes can be used by clinicians to detect pathologic changes or to track spread of disease. A number of regions in the body are associated with clusters or a particular abundance of lymph nodes (Fig. 1.29). Not surprisingly, nodes in many of these regions drain the body’s surface, the digestive system, or the respiratory system. All three of these areas are high-risk sites for the entry of foreign pathogens. Lymph nodes are abundant and accessible to palpation in the axilla, the groin and femoral region, and the neck. Deep sites that are not palpable include those associated with the trachea and bronchi in the thorax, and with the aorta and its branches in the abdomen. All lymphatic vessels coalesce to form larger trunks or ducts, which drain into the venous system at sites in the neck where the internal jugular veins join the subclavian veins to form the brachiocephalic veins (Fig. 1.30): Lymph from the right side of the head and neck, the right upper limb, and the right side of the thorax is carried by lymphatic vessels that connect with veins on the right side of the neck. Lymph from all other regions of the body is carried by lymphatic vessels that drain into veins on the left side of the neck. Specific information about the organization of the lymphatic system in each region of the body is discussed in the appropriate chapter. The nervous system can be separated into parts based on structure and on function: structurally, it can be divided into the central nervous system (CNS) and the peripheral nervous system (PNS) (Fig. 1.32); functionally, it can be divided into somatic and visceral parts. The CNS is composed of the brain and spinal cord, both of which develop from the neural tube in the embryo. The PNS is composed of all nervous structures outside the CNS that connect the CNS to the body. Elements of this system develop from neural crest cells and as outgrowths of the CNS. The PNS consists of the spinal and cranial nerves, visceral nerves and plexuses, and the enteric system. The detailed anatomy of a typical spinal nerve is described in Chapter 2, as is the way spinal nerves are numbered. Cranial nerves are described in Chapter 8. The details of nerve plexuses are described in chapters dealing with the specific regions in which the plexuses are located. The parts of the brain are the cerebral hemispheres, the cerebellum, and the brainstem. The cerebral hemispheres consist of an outer portion, or the gray matter, containing cell bodies; an inner portion, or the white matter, made up of axons forming tracts or pathways; and the ventricles, which are spaces filled with CSF. The cerebellum has two lateral lobes and a midline portion. The components of the brainstem are classically defined as the diencephalon, midbrain, pons, and medulla. However, in common usage today, the term “brainstem” usually refers to the midbrain, pons, and medulla. A further discussion of the brain can be found in Chapter 8. The spinal cord is the part of the CNS in the superior two thirds of the vertebral canal. It is roughly cylindrical in shape, and is circular to oval in cross section with a central canal. A further discussion of the spinal cord can be found in Chapter 2. The meninges (Fig. 1.33) are three connective tissue coverings that surround, protect, and suspend the brain and spinal cord within the cranial cavity and vertebral canal, respectively: The dura mater is the thickest and most external of the coverings. The arachnoid mater is against the internal surface of the dura mater. The pia mater is adherent to the brain and spinal cord. Between the arachnoid and pia mater is the subarachnoid space, which contains CSF. A further discussion of the cranial meninges can be found in Chapter 8 and of the spinal meninges in Chapter 2. Functional subdivisions of the CNS Functionally, the nervous system can be divided into somatic and visceral parts. The somatic part (soma, from the Greek for “body”) innervates structures (skin and most skeletal muscle) derived from somites in the embryo, and is mainly involved with receiving and responding to information from the external environment. The visceral part (viscera, from the Greek for “guts”) innervates organ systems in the body and other visceral elements, such as smooth muscle and glands, in peripheral regions of the body. It is concerned mainly with detecting and responding to information from the internal environment. Somatic part of the nervous system The somatic part of the nervous system consists of: nerves that carry conscious sensations from peripheral regions back to the CNS, and nerves that innervate voluntary muscles. Somatic nerves arise segmentally along the developing CNS in association with somites, which are themselves arranged segmentally along each side of the neural tube (Fig. 1.34). Part of each somite (the dermatomyotome) gives rise to skeletal muscle and the dermis of the skin. As cells of the dermatomyotome differentiate, they migrate into posterior (dorsal) and anterior (ventral) areas of the developing body: Cells that migrate anteriorly give rise to muscles of the limbs and trunk (hypaxial muscles) and to the associated dermis. Cells that migrate posteriorly give rise to the intrinsic muscles of the back (epaxial muscles) and the associated dermis. Developing nerve cells within anterior regions of the neural tube extend processes peripherally into posterior and anterior regions of the differentiating dermatomyotome of each somite. Simultaneously, derivatives of neural crest cells (cells derived from neural folds during formation of the neural tube) differentiate into neurons on each side of the neural tube and extend processes both medially and laterally (Fig. 1.35): Medial processes pass into the posterior aspect of the neural tube. Lateral processes pass into the differentiating regions of the adjacent dermatomyotome. Neurons that develop from cells within the spinal cord are motor neurons and those that develop from neural crest cells are sensory neurons. Somatic sensory and somatic motor fibers that are organized segmentally along the neural tube become parts of all spinal nerves and some cranial nerves. The clusters of sensory nerve cell bodies derived from neural crest cells and located outside the CNS form sensory ganglia. Generally, all sensory information passes into the posterior aspect of the spinal cord, and all motor fibers leave anteriorly." + }, + { + "text": "the limbs and trunk (hypaxial muscles) and to the associated dermis. Cells that migrate posteriorly give rise to the intrinsic muscles of the back (epaxial muscles) and the associated dermis. Developing nerve cells within anterior regions of the neural tube extend processes peripherally into posterior and anterior regions of the differentiating dermatomyotome of each somite. Simultaneously, derivatives of neural crest cells (cells derived from neural folds during formation of the neural tube) differentiate into neurons on each side of the neural tube and extend processes both medially and laterally (Fig. 1.35): Medial processes pass into the posterior aspect of the neural tube. Lateral processes pass into the differentiating regions of the adjacent dermatomyotome. Neurons that develop from cells within the spinal cord are motor neurons and those that develop from neural crest cells are sensory neurons. Somatic sensory and somatic motor fibers that are organized segmentally along the neural tube become parts of all spinal nerves and some cranial nerves. The clusters of sensory nerve cell bodies derived from neural crest cells and located outside the CNS form sensory ganglia. Generally, all sensory information passes into the posterior aspect of the spinal cord, and all motor fibers leave anteriorly. Somatic sensory neurons carry information from the periphery into the CNS and are also called somatic sensory afferents or general somatic afferents (GSAs). The modalities carried by these nerves include temperature, pain, touch, and proprioception. Proprioception is the sense of determining the position and movement of the musculoskeletal system detected by special receptors in muscles and tendons. Somatic motor fibers carry information away from the CNS to skeletal muscles and are also called somatic motor efferents or general somatic efferents (GSEs). Like somatic sensory fibers that come from the periphery, somatic motor fibers can be very long. They extend from cell bodies in the spinal cord to the muscle cells they innervate. Because cells from a specific somite develop into the dermis of the skin in a precise location, somatic sensory fibers originally associated with that somite enter the posterior region of the spinal cord at a specific level and become part of one specific spinal nerve (Fig. 1.36). Each spinal nerve therefore carries somatic sensory information from a specific area of skin on the surface of the body. A dermatome is that area of skin supplied by a single spinal cord level, or on one side, by a single spinal nerve. There is overlap in the distribution of dermatomes, but usually a specific region within each dermatome can be identified as an area supplied by a single spinal cord level. Testing touch in these autonomous zones in a conscious patient can be used to localize lesions to a specific spinal nerve or to a specific level in the spinal cord. Somatic motor nerves that were originally associated with a specific somite emerge from the anterior region of the spinal cord and, together with sensory nerves from the same level, become part of one spinal nerve. Therefore each spinal nerve carries somatic motor fibers to muscles that originally developed from the related somite. A myotome is that portion of a skeletal muscle innervated by a single spinal cord level or, on one side, by a single spinal nerve. Myotomes are generally more difficult to test than dermatomes because each skeletal muscle in the body often develops from more than one somite and is therefore innervated by nerves derived from more than one spinal cord level (Fig. 1.37). Testing movements at successive joints can help in localizing lesions to specific nerves or to a specific spinal cord level. For example: Muscles that move the shoulder joint are innervated mainly by spinal nerves from spinal cord levels C5 and C6. Muscles that move the elbow are innervated mainly by spinal nerves from spinal cord levels C6 and C7. Muscles in the hand are innervated mainly by spinal nerves from spinal cord levels C8 and T1. Visceral part of the nervous system The visceral part of the nervous system, as in the somatic part, consists of motor and sensory components: Sensory nerves monitor changes in the viscera. Motor nerves mainly innervate smooth muscle, cardiac muscle, and glands. The visceral motor component is commonly referred to as the autonomic division of the PNS and is subdivided into sympathetic and parasympathetic parts. Like the somatic part of the nervous system, the visceral part is segmentally arranged and develops in a parallel fashion (Fig. 1.39). Visceral sensory neurons that arise from neural crest cells send processes medially into the adjacent neural tube and laterally into regions associated with the developing body. These sensory neurons and their processes, referred to as general visceral afferent fibers (GVAs), are associated primarily with chemoreception, mechanoreception, and stretch reception. Visceral motor neurons that arise from cells in lateral regions of the neural tube send processes out of the anterior aspect of the tube. Unlike in the somatic part, these processes, containing general visceral efferent fibers (GVEs), synapse with other cells, usually other visceral motor neurons, that develop outside the CNS from neural crest cells that migrate away from their original positions close to the developing neural tube. The visceral motor neurons located in the spinal cord are referred to as preganglionic motor neurons and their axons are called preganglionic fibers; the visceral motor neurons located outside the CNS are referred to as postganglionic motor neurons and their axons are called postganglionic fibers. The cell bodies of the visceral motor neurons outside the CNS often associate with each other in a discrete mass called a ganglion. Visceral sensory and motor fibers enter and leave the CNS with their somatic equivalents (Fig. 1.40). Visceral sensory fibers enter the spinal cord together with somatic sensory fibers through posterior roots of spinal nerves. Preganglionic fibers of visceral motor neurons exit the spinal cord in the anterior roots of spinal nerves, along with fibers from somatic motor neurons. Postganglionic fibers traveling to visceral elements in the periphery are found in the posterior and anterior rami (branches) of spinal nerves. Visceral motor and sensory fibers that travel to and from viscera form named visceral branches that are separate from the somatic branches. These nerves generally form plexuses from which arise branches to the viscera. Visceral motor and sensory fibers do not enter and leave the CNS at all levels (Fig. 1.41): In the cranial region, visceral components are associated with four of the twelve cranial nerves (CN III, VII, IX, and X). In the spinal cord, visceral components are associated mainly with spinal cord levels T1 to L2 and S2 to S4. Visceral motor components associated with spinal levels T1 to L2 are termed sympathetic. Those visceral motor components in cranial and sacral regions, on either side of the sympathetic region, are termed parasympathetic: The sympathetic system innervates structures in peripheral regions of the body and viscera. The parasympathetic system is more restricted to innervation of the viscera only. Spinal sympathetic and spinal parasympathetic neurons share certain developmental and phenotypic features that are different from those of cranial parasympathetic neurons. Based on this, some researchers have suggested reclassifying all spinal visceral motor neurons as sympathetic (Espinosa-Medina I et al. Science 2016;354:893-897). Others are against reclassification, arguing that the results only indicate that the neurons are spinal in origin (Neuhuber W et al. Anat Rec 2017;300:1369-1370). In addition, sacral nerves do not enter the sympathetic trunk, nor do they have postganglionic fibers that travel to the periphery on spinal nerves, as do T1-L2 visceral motor fibers. We have chosen to retain the classification of S2,3,4 visceral motor neurons as parasympathetic. “Parasympathetic” simply means on either side of the “sympathetic,” which correctly describes their anatomy. The sympathetic part of the autonomic division of the PNS leaves thoracolumbar regions of the spinal cord with the somatic components of spinal nerves T1 to L2 (Fig. 1.42). On each side, a paravertebral sympathetic trunk extends from the base of the skull to the inferior end of the vertebral column where the two trunks converge anteriorly to the coccyx at the ganglion impar. Each trunk is attached to the anterior rami of spinal nerves and becomes the route by which sympathetics are distributed to the periphery and all viscera. Visceral motor preganglionic fibers leave the T1 to L2 part of the spinal cord in anterior roots. The fibers then enter the spinal nerves, pass through the anterior rami and into the sympathetic trunks. One trunk is located on each side of the vertebral column (paravertebral) and positioned anterior to the anterior rami. Along the trunk is a series of segmentally arranged ganglia formed from collections of postganglionic neuronal cell bodies where the preganglionic neurons synapse with postganglionic neurons. Anterior rami of T1 to L2 are connected to the sympathetic trunk or to a ganglion by a white ramus communicans, which carries preganglionic sympathetic fibers and appears white because the fibers it contains are myelinated. Preganglionic sympathetic fibers that enter a paravertebral ganglion or the sympathetic trunk through a white ramus communicans may take the following four pathways to target tissues: 1. Peripheral sympathetic innervation at" + }, + { + "text": "unks converge anteriorly to the coccyx at the ganglion impar. Each trunk is attached to the anterior rami of spinal nerves and becomes the route by which sympathetics are distributed to the periphery and all viscera. Visceral motor preganglionic fibers leave the T1 to L2 part of the spinal cord in anterior roots. The fibers then enter the spinal nerves, pass through the anterior rami and into the sympathetic trunks. One trunk is located on each side of the vertebral column (paravertebral) and positioned anterior to the anterior rami. Along the trunk is a series of segmentally arranged ganglia formed from collections of postganglionic neuronal cell bodies where the preganglionic neurons synapse with postganglionic neurons. Anterior rami of T1 to L2 are connected to the sympathetic trunk or to a ganglion by a white ramus communicans, which carries preganglionic sympathetic fibers and appears white because the fibers it contains are myelinated. Preganglionic sympathetic fibers that enter a paravertebral ganglion or the sympathetic trunk through a white ramus communicans may take the following four pathways to target tissues: 1. Peripheral sympathetic innervation at the level of origin of the preganglionic fiber Preganglionic sympathetic fibers may synapse with postganglionic motor neurons in ganglia associated with the sympathetic trunk, after which postganglionic fibers enter the same anterior ramus and are distributed with peripheral branches of the posterior and anterior rami of that spinal nerve (Fig. 1.43). The fibers innervate structures at the periphery of the body in regions supplied by the spinal nerve. The gray ramus communicans connects the sympathetic trunk or a ganglion to the anterior ramus and contains the postganglionic sympathetic fibers. It appears gray because postganglionic fibers are nonmyelinated. The gray ramus communicans is positioned medial to the white ramus communicans. 2. Peripheral sympathetic innervation above or below the level of origin of the preganglionic fiber Preganglionic sympathetic fibers may ascend or descend to other vertebral levels where they synapse in ganglia associated with spinal nerves that may or may not have visceral motor input directly from the spinal cord (i.e., those nerves other than T1 to L2) (Fig. 1.44). The postganglionic fibers leave the distant ganglia via gray rami communicantes and are distributed along the posterior and anterior rami of the spinal nerves. The ascending and descending fibers, together with all the ganglia, form the paravertebral sympathetic trunk, which extends the entire length of the vertebral column. The formation of this trunk, on each side, enables visceral motor fibers of the sympathetic part of the autonomic division of the PNS, which ultimately emerge from only a small region of the spinal cord (T1 to L2), to be distributed to peripheral regions innervated by all spinal nerves. White rami communicantes only occur in association with spinal nerves T1 to L2, whereas gray rami communicantes are associated with all spinal nerves. Fibers from spinal cord levels T1 to T5 pass predominantly superiorly, whereas fibers from T5 to L2 pass inferiorly. All sympathetics passing into the head have preganglionic fibers that emerge from spinal cord level T1 and ascend in the sympathetic trunks to the highest ganglion in the neck (the superior cervical ganglion), where they synapse. Postganglionic fibers then travel along blood vessels to target tissues in the head, including blood vessels, sweat glands, small smooth muscles associated with the upper eyelids, and the dilator of the pupil. 3. Sympathetic innervation of thoracic Preganglionic sympathetic fibers may synapse with postganglionic motor neurons in ganglia and then leave the ganglia medially to innervate thoracic or cervical viscera (Fig. 1.45). They may ascend in the trunk before synapsing, and after synapsing the postganglionic fibers may combine with those from other levels to form named visceral nerves, such as cardiac nerves. Often, these nerves join branches from the parasympathetic system to form plexuses on or near the surface of the target organ, for example, the cardiac and pulmonary plexuses. Branches of the plexus innervate the organ. Spinal cord levels T1 to T5 mainly innervate cranial, cervical, and thoracic viscera. 4. Sympathetic innervation of the abdomen and pelvic regions and the adrenals Preganglionic sympathetic fibers may pass through the sympathetic trunk and paravertebral ganglia without synapsing and, together with similar fibers from other levels, form splanchnic nerves (greater, lesser, least, lumbar, and sacral), which pass into the abdomen and pelvic regions (Fig. 1.46). The preganglionic fibers in these nerves are derived from spinal cord levels T5 to L2. The splanchnic nerves generally connect with sympathetic ganglia around the roots of major arteries that branch from the abdominal aorta. These ganglia are part of a large prevertebral plexus that also has input from the parasympathetic part of the autonomic division of the PNS. Postganglionic sympathetic fibers are distributed in extensions of this plexus, predominantly along arteries, to viscera in the abdomen and pelvis. Some of the preganglionic fibers in the prevertebral plexus do not synapse in the sympathetic ganglia of the plexus but pass through the system to the adrenal gland, where they synapse directly with cells of the adrenal medulla. These cells are homologues of sympathetic postganglionic neurons and secrete adrenaline and noradrenaline into the vascular system. The parasympathetic part of the autonomic division of the PNS (Fig. 1.47) leaves cranial and sacral regions of the CNS in association with: cranial nerves III, VII, IX, and X: III, VII, and IX carry parasympathetic fibers to structures within the head and neck only, whereas X (the vagus spinal nerves S2 to S4: sacral parasympathetic fibers innervate inferior abdominal viscera, pelvic viscera, and the arteries associated with erectile tissues of the perineum. Like the visceral motor nerves of the sympathetic part, the visceral motor nerves of the parasympathetic part generally have two neurons in the pathway. The preganglionic neurons are in the CNS, and fibers leave in the cranial nerves. In the sacral region, the preganglionic parasympathetic fibers form special visceral nerves (the pelvic splanchnic nerves), which originate from the anterior rami of S2 to S4 and enter pelvic extensions of the large prevertebral plexus formed around the abdominal aorta. These fibers are distributed to pelvic and abdominal viscera mainly along blood vessels. The postganglionic motor neurons are in the walls of the viscera. In organs of the gastrointestinal system, preganglionic fibers do not have a postganglionic parasympathetic motor neuron in the pathway; instead, preganglionic fibers synapse directly on neurons in the ganglia of the enteric system. The preganglionic parasympathetic motor fibers in CN III, VII, and IX separate from the nerves and connect with one of four distinct ganglia, which house postganglionic motor neurons. These four ganglia are near major branches of CN V. Postganglionic fibers leave the ganglia, join the branches of CN V, and are carried to target tissues (salivary, mucous, and lacrimal glands; constrictor muscle of the pupil; and ciliary muscle in the eye) with these branches. The vagus nerve [X] gives rise to visceral branches along its course. These branches contribute to plexuses associated with thoracic viscera or to the large prevertebral plexus in the abdomen and pelvis. Many of these plexuses also contain sympathetic fibers. When present, postganglionic parasympathetic neurons are in the walls of the target viscera. motor fibers. Visceral sensory fibers follow the course of sympathetic fibers entering the spinal cord at similar spinal cord levels. However, visceral sensory fibers may also enter the spinal cord at levels other than those associated with motor output. For example, visceral sensory fibers from the heart may enter at levels higher than spinal cord level T1. Visceral sensory fibers that accompany sympathetic fibers are mainly concerned with detecting pain. Visceral sensory fibers accompanying parasympathetic fibers are carried mainly in IX and X and in spinal nerves S2 to S4. Visceral sensory fibers in IX carry information from chemoreceptors and baroreceptors associated with the walls of major arteries in the neck, and from receptors in the pharynx. Visceral sensory fibers in X include those from cervical viscera, and major vessels and viscera in the thorax and abdomen. Visceral sensory fibers from pelvic viscera and the distal parts of the colon are carried in S2 to S4. Visceral sensory fibers associated with parasympathetic fibers primarily relay information to the CNS about the status of normal physiological processes and reflex activities. The enteric system The enteric nervous system consists of motor and sensory neurons and their support cells, which form two interconnected plexuses, the myenteric and submucous nerve plexuses, within the walls of the gastrointestinal tract (Fig. 1.48). Each of these plex" + }, + { + "text": "those associated with motor output. For example, visceral sensory fibers from the heart may enter at levels higher than spinal cord level T1. Visceral sensory fibers that accompany sympathetic fibers are mainly concerned with detecting pain. Visceral sensory fibers accompanying parasympathetic fibers are carried mainly in IX and X and in spinal nerves S2 to S4. Visceral sensory fibers in IX carry information from chemoreceptors and baroreceptors associated with the walls of major arteries in the neck, and from receptors in the pharynx. Visceral sensory fibers in X include those from cervical viscera, and major vessels and viscera in the thorax and abdomen. Visceral sensory fibers from pelvic viscera and the distal parts of the colon are carried in S2 to S4. Visceral sensory fibers associated with parasympathetic fibers primarily relay information to the CNS about the status of normal physiological processes and reflex activities. The enteric system The enteric nervous system consists of motor and sensory neurons and their support cells, which form two interconnected plexuses, the myenteric and submucous nerve plexuses, within the walls of the gastrointestinal tract (Fig. 1.48). Each of these plexuses is formed by: ganglia, which house the nerve cell bodies and associated cells, and bundles of nerve fibers, which pass between ganglia and from the ganglia into surrounding tissues. Neurons in the enteric system are derived from neural crest cells originally associated with occipitocervical and sacral regions. Interestingly, more neurons are reported to be in the enteric system than in the spinal cord itself. Sensory and motor neurons within the enteric system control reflex activity within and between parts of the gastrointestinal system. These reflexes regulate peristalsis, secretomotor activity, and vascular tone. These activities can occur independently of the brain and spinal cord, but can also be modified by input from preganglionic parasympathetic and postganglionic sympathetic fibers. Sensory information from the enteric system is carried back to the CNS by visceral sensory fibers. Nerve plexuses are either somatic or visceral and combine fibers from different sources or levels to form new nerves with specific targets or destinations (Fig. 1.49). Plexuses of the enteric system also generate reflex activity independent of the CNS. Major somatic plexuses formed from the anterior rami of spinal nerves are the cervical (C1 to C4), brachial (C5 to T1), lumbar (L1 to L4), sacral (L4 to S4), and coccygeal (S5 to Co) plexuses. Except for spinal nerve T1, the anterior rami of thoracic spinal nerves remain independent and do not participate in plexuses. Visceral nerve plexuses are formed in association with viscera and generally contain efferent (sympathetic and parasympathetic) and afferent components (Fig. 1.49). These plexuses include cardiac and pulmonary plexuses in the thorax and a large prevertebral plexus in the abdomen anterior to the aorta, which extends inferiorly onto the lateral walls of the pelvis. The massive prevertebral plexus supplies input to and receives output from all abdominal and pelvic viscera. Specific information about the organization and components of the respiratory, gastrointestinal, and urogenital systems will be discussed in each of the succeeding chapters of this text. Fig. 1.1 The anatomical position, planes, and terms of location and orientation. Feet togethertoes forwardHands by sidespalms forwardFace looking forwardInferior margin of orbit level withtop of external auditory meatusSagittal planeCoronal planeSuperiorAnteriorPosteriorMedialLateralInferiorTransverse, horizontal,or axial plane Fig. 1.2 Cathode ray tube for the production of X-rays. Fig. 1.3 Fluoroscopy unit. Fig. 1.4 Barium sulfate follow-through. Fig. 1.5 Digital subtraction angiogram. Fig. 1.6 Ultrasound examination of the abdomen. Fig. 1.7 Computed tomography scanner. Fig. 1.8 Computed tomography scan of the abdomen at vertebral level L2. Fig. 1.9 A T2-weighted MR image in the sagittal plane of the pelvic viscera in a woman. Fig. 1.10 T1-weighted (A) and T2-weighted (B) MR images of the brain in the coronal plane. Fig. 1.11 A gamma camera. Fig. 1.12 The axial skeleton and the appendicular skeleton. Fig. 1.13 Accessory and sesamoid bones. A. Radiograph of the ankle region showing an accessory bone (os trigonum). B. Radiograph of the feet showing numerous sesamoid bones and an accessory bone (os naviculare). Fig. 1.14 A developmental series of radiographs showing the progressive ossification of carpal (wrist) bones from 3 (A) to 10 (D) years of age. Fig. 1.15 T1-weighted image in the coronal plane, demonstrating the relatively high signal intensity returned from the femoral heads and proximal femoral necks, consistent with yellow marrow. In this young patient, the vertebral bodies return an intermediate darker signal that represents red marrow. There is relatively little fat in these vertebrae; hence the lower signal return. Fig. 1.16 Radiograph, lateral view, showing fracture of the ulna at the elbow joint (A) and repair of this fracture (B) using internal fixation with a plate and multiple screws. Fig. 1.17 Image of the hip joints demonstrating loss of height of the right femoral head with juxta-articular bony sclerosis and subchondral cyst formation secondary to avascular necrosis. There is also significant wasting of the muscles supporting the hip, which is secondary to disuse and pain. Normal left hipBladderAvascular necrosisWasting of gluteal muscle Fig. 1.18 Joints. A. Synovial joint. B. Solid joint. Fig. 1.19 Synovial joints. A. Major features of a synovial joint. B. Accessory structures associated with synovial joints. Fig. 1.20 Various types of synovial joints. A. Condylar (wrist). B. Gliding (radio-ulnar). C. Hinge (elbow). D. Ball and socket (hip). E. Saddle (carpometacarpal of thumb). F. Pivot (atlanto-axial). Fig. 1.21 Solid joints. Fig. 1.22 This operative photograph demonstrates the focal areas of cartilage loss in the patella and femoral condyles throughout the knee joint. Fig. 1.23 This radiograph demonstrates the loss of joint space in the medial compartment and presence of small spiky osteophytic regions at the medial lateral aspect of the joint. OsteophytesLoss of joint space Fig. 1.24 After knee replacement. This radiograph shows the position of the prosthesis. Fig. 1.25 This is a radiograph, anteroposterior view, of the pelvis after a right total hip replacement. There are additional significant degenerative changes in the left hip joint, which will also need to be replaced. Fig. 1.26 Axial inversion recovery MR imaging series, which suppresses fat and soft tissue and leaves high signal intensity where fluid is seen. A muscle tear in the right adductor longus with edema in and around the muscle is shown. Fig. 1.27 Photograph demonstrating varicose veins. Fig. 1.28 Lymphatic vessels mainly collect fluid lost from vascular capillary beds during nutrient exchange processes and deliver it back to the venous side of the vascular system. Fig. 1.29 Regions associated with clusters or a particular abundance of lymph nodes. Cervical nodes(along courseof internaljugular vein)Axillary nodes(in axilla)Deep nodes(related to aortaand celiac trunkand superior andinferior mesentericarteries)Pericranial ring(base of head)Tracheal nodes(nodes related totrachea and bronchi)Inguinal nodes(along course ofinguinal ligament)Femoral nodes(along femoral vein) Fig. 1.30 Major lymphatic vessels that drain into large veins in the neck. Fig. 1.31 A. This computed tomogram with contrast, in the axial plane, demonstrates the normal common carotid arteries and internal jugular veins with numerous other nonenhancing nodules that represent lymph nodes in a patient with lymphoma. B. This computed tomogram with contrast, in the axial plane, demonstrates a large anterior soft tissue mediastinal mass that represents a lymphoma. Fig. 1.32 CNS and PNS. Fig. 1.33 Arrangement of meninges in the cranial cavity. Fig. 1.34 Differentiation of somites in a “tubular” embryo. Fig. 1.35 Somatic sensory and" + }, + { + "text": "ular vein)Axillary nodes(in axilla)Deep nodes(related to aortaand celiac trunkand superior andinferior mesentericarteries)Pericranial ring(base of head)Tracheal nodes(nodes related totrachea and bronchi)Inguinal nodes(along course ofinguinal ligament)Femoral nodes(along femoral vein) Fig. 1.30 Major lymphatic vessels that drain into large veins in the neck. Fig. 1.31 A. This computed tomogram with contrast, in the axial plane, demonstrates the normal common carotid arteries and internal jugular veins with numerous other nonenhancing nodules that represent lymph nodes in a patient with lymphoma. B. This computed tomogram with contrast, in the axial plane, demonstrates a large anterior soft tissue mediastinal mass that represents a lymphoma. Fig. 1.32 CNS and PNS. Fig. 1.33 Arrangement of meninges in the cranial cavity. Fig. 1.34 Differentiation of somites in a “tubular” embryo. Fig. 1.35 Somatic sensory and motor neurons. Blue lines indicate motor nerves and red lines indicate sensory nerves. Somatic sensory neurondeveloping from neural crest cellsEpaxial (back) musclesHypaxial musclesAxon of motor neuronprojects to muscle developingfrom dermatomyotomeSomatic motor neuroncell body in anterior regionof neural tube Fig. 1.36 Dermatomes. C6 segment of spinal cordSpinal ganglionDermatomyotomeAutonomous region(where overlap ofdermatomes isleast likely)of C6 dermatome(pad of thumb)Skin on the lateral side of the forearm and on thethumb is innervated by C6 spinal level (spinal nerve).The dermis of the skin in this region develops from the somiteinitially associated with the C6 level of the developing spinal cordCaudalCranialSomite Fig. 1.37 Myotomes. C6 segment of spinal cordMuscles that abduct the arm are innervated by C5 and C6 spinal levels (spinal nerves) and develop from somites initially associated with C5 and C6 regions of developing spinal cordC5 segment of spinal cordDermatomyotomeSomite Fig. 1.38 Dermatomes. A. Anterior view. B. Posterior view. Fig. 1.39 Development of the visceral part of the nervous system. Motor nerve endingassociated withblood vessels,sweat glands,arrector pili musclesat peripheryPart of neural crest developinginto spinal gangliaVisceral motor ganglionMotor nerve ending associated with visceraDeveloping gastrointestinal tractSensory nerve endingBody cavity(coelom)Visceral sensory neuron developsfrom neural crest and becomespart of spinal ganglionVisceral motorpreganglionicneuron in lateralregion of CNS(spinal cord)Postganglionic motor neuron is outside CNS.An aggregation of postganglionic neuronal cellbodies forms a peripheral visceral motor ganglion. Fig. 1.40 Basic anatomy of a thoracic spinal nerve. Fig. 1.41 Parts of the CNS associated with visceral motor components. SympatheticT1 to L2spinal segmentsBrainstemcranial nervesIII, VII, IX, XS2 to S4spinal segmentsParasympathetic Fig. 1.42 Sympathetic part of the autonomic division of the PNS. Abdominal visceraHeartOrgansPeripheralSympathetic nerves followsomatic nerves to periphery(glands, smooth muscle)Pelvic visceraGanglion imparEsophageal plexusPrevertebral plexus Fig. 1.43 Course of sympathetic fibers that travel to the periphery in the same spinal nerves in which they travel out of the spinal cord. Gray ramus communicansT10 spinal nervePosteriorramusAnteriorramusPeripheral distribution of sympatheticscarried peripherally by terminal cutaneousbranches of spinal nerve T1 to L2Motor nerve to sweat glands,smooth muscle of bloodvessels, and arrector pilimuscles in the part of T10dermatome supplied by theanterior ramusT10 spinal segmentWhite ramus communicans Fig. 1.44 Course of sympathetic nerves that travel to the periphery in spinal nerves that are not the ones through which they left the spinal cord. Sympathetic paravertebral trunksPeripheral distribution ofascending sympatheticsPeripheral distribution ofdescending sympathetics(C1) C2 to C8T1 to L2L3 to CoWhite ramus communicansGray ramus communicansPosterior rootGray ramus communicansGray ramus communicansAnterior root Fig. 1.45 Course of sympathetic nerves traveling to the heart. Sympathetic cardiac nervesSympathetic cardiac nervesSympathetic trunkCardiac plexusT1 to T4CervicalWhite ramuscommunicansGray ramuscommunicans Fig. 1.46 Course of sympathetic nerves traveling to abdominal and pelvic viscera. White ramus communicansGray ramus communicansSacral splanchnic nervesLumbar splanchnic nervesLeast splanchnic nervesLesser splanchnic nervesGreater splanchnic nervesPrevertebral plexusand gangliaParavertebralsympathetic trunkAbdominalandpelvic visceraAortaT5 to T9T12T9 to T10(T10 to T11)L1 to L2 Fig. 1.47 Parasympathetic part of the autonomic division of the PNS. Thoracic visceral plexusPrevertebral plexusAbdominal visceraSynapse with nerve cellsof enteric systemErectile tissues of penisand clitorisS2 to S4Sacral parasympatheticoutflow via pelvicsplanchnic nervesCranial parasympatheticoutflow via cranial nervesHeartSubmandibularganglionPterygopalatineganglionOtic ganglionCiliary ganglion[III][VII][IX][X]Pelvic visceraPupillary constrictionTransition from supply by [X]to pelvic splanchnic nervesSalivary glandsLacrimal glandParotid gland Fig. 1.48 Enteric part of the nervous system. Fig. 1.49 Nerve plexuses. C7C6C5C4C3C2C1T1T2T3T4T5T6T7T8T9T10T11T12L1S1S2S3S4S5L2L3L4L5C8GreaterLeastLesserSOMATIC PLEXUSESVISCERAL PLEXUSESCervical plexusanterior rami C1 to C4Brachial plexusanterior rami C5 to T1Lumbar plexusanterior rami L1 to L4Sacral plexusanterior ramiL4 to S4Parasympathetic [X]S2 to S4 pelvic splanchnic nerves(parasympathetic)Pulmonary branchPulmonary branchesCardiac branchesCardiac plexusThoracic aortic plexusEsophageal plexusPrevertebral plexusVagal trunkGanglion imparSacral splanchnic nervesSplanchnicnervesLumbar splanchnicnerves Fig. 1.50 Mechanism for referred pain from an inflamed appendix to the T10 dermatome. Table 1.1 The approximate dosage of radiation exposure as an order of magnitude In the clinic These are extra bones that are not usually found as part of the normal skeleton, but can exist as a normal variant in many people. They are typically found in multiple locations in the wrist and hands, ankles and feet (Fig. 1.13). These should not be mistaken for fractures on imaging. Sesamoid bones are embedded within tendons, the largest of which is the patella. There are many other sesamoids in the body particularly in tendons of the hands and feet, and most frequently in flexor tendons of the thumb and big toe. Degenerative and inflammatory changes of, as well as mechanical stresses on, the accessory bones and sesamoids can cause pain, which can be treated with physiotherapy and targeted steroid injections, but in some severe cases it may be necessary to surgically remove the bone. In the clinic Determination of skeletal age Throughout life the bones develop in a predictable way to form the skeletally mature adult at the end of puberty. In western countries skeletal maturity tends to occur between the ages of 20 and 25 years. However, this may well vary according to geography and socioeconomic conditions. Skeletal maturity will also be determined by genetic factors and disease states. Up until the age of skeletal maturity, bony growth and development follows a typically predictable ordered state, which can be measured through either ultrasound, plain radiographs, or MRI scanning. Typically, the nondominant (left) hand is radiographed, and the radiograph is compared to a series of standard radiographs. From these images the bone age can be determined (Fig. 1.14). In certain disease states, such as malnutrition and hypothyroidism," + } +] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..aa1e9f38d274777091090a2d6b8342aad5cf0563 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/__init__.py @@ -0,0 +1,4 @@ +# from .eval import * +# from .generate import * +# from .filter import * +# from .refine import * diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d6754b3b5577c8449afba1edd76ed041786e496 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..45c5738a466067ab4d1e1d916112576eedf4143b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/__init__.py @@ -0,0 +1,23 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + # filter + + # eval + from .eval.agenticrag_qaf1_sample_evaluator import AgenticRAGQAF1SampleEvaluator + # generate + from .generate.agenticrag_atomic_task_generator import AgenticRAGAtomicTaskGenerator + from .generate.agenticrag_depth_qa_generator import AgenticRAGDepthQAGenerator + from .generate.agenticrag_width_qa_generator import AgenticRAGWidthQAGenerator + +else: + import sys + from dataflow.utils.registry import LazyLoader, generate_import_structure_from_type_checking + + + + cur_path = "dataflow/operators/agentic_rag/" + + + _import_structure = generate_import_structure_from_type_checking(__file__, cur_path) + sys.modules[__name__] = LazyLoader(__name__, "dataflow/operators/agentic_rag/", _import_structure) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb05c212c21a20d8b1850c0147f55984db6c5bcb Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/eval/__pycache__/agenticrag_qaf1_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/eval/__pycache__/agenticrag_qaf1_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca7ec9ef5512034c0bb70e200cb53838fd48c4e3 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/eval/__pycache__/agenticrag_qaf1_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/eval/agenticrag_qaf1_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/eval/agenticrag_qaf1_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..48cce6b22d0cd1348e7f856951c62a3046378aa7 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/eval/agenticrag_qaf1_sample_evaluator.py @@ -0,0 +1,131 @@ +import re +import string +from collections import Counter +from tqdm import tqdm +import pandas as pd +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger + + +@OPERATOR_REGISTRY.register() +class AgenticRAGQAF1SampleEvaluator(OperatorABC): + + def __init__(self): + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__}...") + self.logger.info(f"{self.__class__.__name__} initialized.") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于计算预测答案与参考答案(Ground Truth)之间的 F1 分数。它通过词袋模型(Token-based)评估文本相似度,支持答案归一化及多参考答案匹配。\n\n" + "输入参数:\n" + "- input_prediction_key: 预测答案字段名(默认值:\"refined_answer\")\n" + "- input_ground_truth_key: 参考答案字段名,支持字符串或列表(默认值:\"golden_doc_answer\")\n" + "- output_key: 输出 F1 分数字段名(默认值:\"F1Score\")\n" + ) + elif lang == "en": + return ( + "This operator computes the F1 score between predicted answers and reference (ground truth) answers. " + "It evaluates text similarity based on tokens, supports answer normalization, and matches against multiple reference answers.\n\n" + "Input Parameters:\n" + "- input_prediction_key: Field name for the predicted answer (default: \"refined_answer\")\n" + "- input_ground_truth_key: Field name for the ground truth answer, supports string or list (default: \"golden_doc_answer\")\n" + "- output_key: Field name for the output F1 score (default: \"F1Score\")\n" + ) + else: + return "AgenticRAGQAF1SampleEvaluator computes F1 scores for QA evaluation based on token overlap." + + def _validate_dataframe(self, dataframe: pd.DataFrame): + required_keys = [self.prediction_key, self.ground_truth_key] + forbidden_keys = [self.output_key ] + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + raise ValueError(f"Missing required column(s): {missing}") + if conflict: + raise ValueError(f"The following column(s) already exist and would be overwritten: {conflict}") + + def normalize_answer(self, s: str) -> str: + def remove_articles(text): + return re.sub(r"\b(a|an|the)\b", " ", text) + + def white_space_fix(text): + return " ".join(text.split()) + + def remove_punc(text): + exclude = set(string.punctuation) + return "".join(ch for ch in text if ch not in exclude) + + def lower(text): + return text.lower() + + return white_space_fix(remove_articles(remove_punc(lower(s)))) + + def compute_f1(self, prediction: str, ground_truths) -> float: + if prediction is None or ground_truths is None: + return 0.0 + + if isinstance(ground_truths, str): + ground_truths = [ground_truths] + + max_f1 = 0.0 + + for ground_truth in ground_truths: + if ground_truth is None: + continue + + normalized_prediction = self.normalize_answer(prediction) + normalized_ground_truth = self.normalize_answer(ground_truth) + + if normalized_prediction in ["yes", "no", "noanswer"] or normalized_ground_truth in ["yes", "no", "noanswer"]: + if normalized_prediction != normalized_ground_truth: + continue + + pred_tokens = normalized_prediction.split() + gold_tokens = normalized_ground_truth.split() + common = Counter(pred_tokens) & Counter(gold_tokens) + num_same = sum(common.values()) + + if num_same == 0: + continue + + precision = num_same / len(pred_tokens) + recall = num_same / len(gold_tokens) + f1 = (2 * precision * recall) / (precision + recall) + max_f1 = max(max_f1, f1) + + return max_f1 + + def eval(self, dataframe: pd.DataFrame) -> list: + self.logger.info(f"Evaluating {self.output_key}...") + f1_scores = [] + + for _, row in tqdm(dataframe.iterrows(), total=len(dataframe), desc="F1Scorer Evaluating..."): + prediction = row.get(self.prediction_key, None) + ground_truths = row.get(self.ground_truth_key, None) + score = self.compute_f1(prediction, ground_truths) + f1_scores.append(score) + + self.logger.info("Evaluation complete!") + return f1_scores + + def run(self, + storage: DataFlowStorage, + input_prediction_key:str ="refined_answer", + input_ground_truth_key:str ="golden_doc_answer", + output_key:str ="F1Score", + ): + dataframe = storage.read("dataframe") + self.output_key = output_key + self.prediction_key = input_prediction_key + self.ground_truth_key = input_ground_truth_key + self._validate_dataframe(dataframe) + scores = self.eval(dataframe) + dataframe[self.output_key] = scores + storage.write(dataframe) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/generate/__pycache__/agenticrag_atomic_task_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/generate/__pycache__/agenticrag_atomic_task_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d5a1e5968b457c7b6eed257e36895871d9b2823 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/generate/__pycache__/agenticrag_atomic_task_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/generate/__pycache__/agenticrag_depth_qa_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/generate/__pycache__/agenticrag_depth_qa_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8928bb4ddd0cccc2f0ee8be1174ffe20452d1020 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/generate/__pycache__/agenticrag_depth_qa_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/generate/__pycache__/agenticrag_width_qa_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/generate/__pycache__/agenticrag_width_qa_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..726277eff55a34db695b1adab585e31a319be871 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/generate/__pycache__/agenticrag_width_qa_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/generate/agenticrag_atomic_task_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/generate/agenticrag_atomic_task_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..02dca28fc576c7f1ddcc80c727f696d3b2374161 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/generate/agenticrag_atomic_task_generator.py @@ -0,0 +1,445 @@ +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC + +from dataflow.prompts.agenticrag import ( +AtomicTaskGeneratorGetIdentifierPrompt, +AtomicTaskGeneratorGetConlcusionPrompt, +AtomicTaskGeneratorQuestionPrompt, +AtomicTaskGeneratorCleanQAPrompt, +AtomicTaskGeneratorAnswerPrompt, +AtomicTaskGeneratorRecallScorePrompt, +AtomicTaskGeneratorOptionalAnswerPrompt, +AtomicTaskGeneratorGoldenDocAnswerPrompt +) +from dataflow.core.prompt import prompt_restrict + +import pandas as pd +import json +import string +import re +from collections import Counter + +@prompt_restrict( + AtomicTaskGeneratorGetIdentifierPrompt, + AtomicTaskGeneratorGetConlcusionPrompt, + AtomicTaskGeneratorQuestionPrompt, + AtomicTaskGeneratorCleanQAPrompt, + AtomicTaskGeneratorAnswerPrompt, + AtomicTaskGeneratorRecallScorePrompt, + AtomicTaskGeneratorOptionalAnswerPrompt, + AtomicTaskGeneratorGoldenDocAnswerPrompt +) +@OPERATOR_REGISTRY.register() +class AgenticRAGAtomicTaskGenerator(OperatorABC): + def __init__(self, + llm_serving: LLMServingABC = None, + data_num : int = 100, + max_per_task: int = 10, # Limit the number of candidate tasks per input + max_question: int = 10, # Limit the question of each doc + # prompt_template = None # prompt is fix + ): + self.logger= get_logger() + self.llm_serving = llm_serving + self.data_num, self.max_per_task, self.max_question = data_num, max_per_task, max_question + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于为提供的文本内容生成合适的高质量问题与可验证答案。\n\n" + "输入参数:\n" + "- input_key: 输入文本内容字段名(默认值:\"prompts\")\n" + "- output_question_key: 输出问题字段名(默认值:\"question\")\n" + "- output_answer_key: 输出答案字段名(默认值:\"answer\")\n" + "- output_refined_answer_key: 输出精炼答案字段名(默认值:\"refined_answer\")\n" + "- output_optional_answer_key: 输出可替代精炼答案字段名(默认值:\"optional_answer\")\n" + "- output_golden_doc_answer_key: 输出黄金文档回答字段名(默认值:\"golden_doc_answer\")\n" + ) + elif lang == "en": + return ( + "This operator is used to generate appropriate high-quality questions and verifiable answers for the provided text content." + "Input Parameters:\n" + "- input_key: Field name of the input text content (default: \"prompts\")\n" + "- output_question_key: Field name for the output question (default: \"question\")\n" + "- output_answer_key: Field name for the output answer (default: \"answer\")\n" + "- output_refined_answer_key: Field name for the output refined answer (default: \"refined_answer\")\n" + "- output_optional_answer_key: Field name for the output optional refined answer (default: \"optional_answer\")\n" + "- output_golden_doc_answer_key: Field name for the output answer based on gold documents (default: \"golden_doc_answer\")\n" + ) + else: + return "AtomicTaskGenerator generate appropriate high-quality questions and verifiable answers for the provided text content." + + def _validate_dataframe(self, dataframe: pd.DataFrame): + required_keys = [self.input_key] + forbidden_keys = [self.output_refined_answer_key, self.output_answer_key, self.output_question_key, self.output_optional_answer_key, self.output_llm_answer_key, self.output_golden_doc_answer_key] + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + raise ValueError(f"Missing required column(s): {missing}") + if conflict: + raise ValueError(f"The following column(s) already exist and would be overwritten: {conflict}") + + def _reformat_prompt(self, dataframe, prompt_type: str = None): + """ + Reformat the prompts in the dataframe to generate LLM input. + All input columns are expected to be strings. + """ + if prompt_type == "get_identifier": + self.prompt_template = AtomicTaskGeneratorGetIdentifierPrompt() + input_prompts = dataframe[self.input_key].tolist() + system_prompt = self.prompt_template.build_system_prompt() + prompts = [self.prompt_template.build_prompt(p) for p in input_prompts] + + elif prompt_type == "get_conclusion": + self.prompt_template = AtomicTaskGeneratorGetConlcusionPrompt() + input_prompts = dataframe[self.input_key].tolist() + system_prompt = self.prompt_template.build_system_prompt() + prompts = [self.prompt_template.build_prompt(p) for p in input_prompts] + + elif prompt_type == "init_question": + self.prompt_template = AtomicTaskGeneratorQuestionPrompt() + candidate_strs = dataframe["candidate_tasks_str"].tolist() + raw_identifiers = dataframe["identifier"].tolist() + system_prompt = self.prompt_template.build_system_prompt() + prompts = [] + for s, raw_id in zip(candidate_strs, raw_identifiers): + try: + # 解析 candidate_tasks_str 字段 + task_item = json.loads(self._clean_json_block(s)) + + # 清理并解析 identifier 字段 + clean_id_str = self._clean_json_block(raw_id) + identifier_obj = json.loads(clean_id_str) + identifier = identifier_obj.get("content_identifier", "Unknown") + + prompts.append( + self.prompt_template.build_prompt(identifier, task_item["conclusion"], task_item["R"]) + ) + except Exception as e: + print(f"[WARN] Failed to parse candidate_tasks_str or identifier: {e} | value: {s} | id: {raw_id}") + prompts.append("") # fallback + + elif prompt_type == "clean_qa": + self.prompt_template = AtomicTaskGeneratorCleanQAPrompt() + questions = dataframe[self.output_question_key].tolist() + answers = dataframe[self.output_answer_key].tolist() + system_prompt = self.prompt_template.build_system_prompt() + prompts = [ + self.prompt_template.build_prompt({"question": q, "original_answer": a}) + for q, a in zip(questions, answers) + ] + elif prompt_type == "llm_answer": + self.prompt_template = AtomicTaskGeneratorAnswerPrompt() + questions = dataframe[self.output_question_key].tolist() + system_prompt = "" + prompts = [ + self.prompt_template.build_prompt(question) for question in questions + ] + elif prompt_type == "get_recall_score": + self.prompt_template = AtomicTaskGeneratorRecallScorePrompt() + golden_answers = dataframe[self.output_refined_answer_key].tolist() + llm_answers = dataframe[self.output_llm_answer_key] + system_prompt = self.prompt_template.build_system_prompt() + prompts = [ + self.prompt_template.build_prompt(golden_answer, llm_answer) for golden_answer, llm_answer in zip(golden_answers, llm_answers) + ] + elif prompt_type == "get_golden_answer_score": + self.prompt_template = AtomicTaskGeneratorRecallScorePrompt() + golden_answers = dataframe[self.output_refined_answer_key].tolist() + llm_answers = dataframe[self.output_golden_doc_answer_key] + system_prompt = self.prompt_template.build_system_prompt() + prompts = [ + self.prompt_template.build_prompt(golden_answer, llm_answer) for golden_answer, llm_answer in zip(golden_answers, llm_answers) + ] + elif prompt_type == "more_optional_answer": + self.prompt_template = AtomicTaskGeneratorOptionalAnswerPrompt() + answers = dataframe[self.output_refined_answer_key].tolist() + system_prompt = self.prompt_template.build_system_prompt() + prompts = [ + self.prompt_template.build_prompt(answer) for answer in answers + ] + elif prompt_type == "golden_doc_answer": + self.prompt_template = AtomicTaskGeneratorGoldenDocAnswerPrompt() + golden_docs = dataframe[self.input_key].tolist() + questions = dataframe[self.output_question_key].tolist() + system_prompt = "" + prompts = [ + self.prompt_template.build_prompt(golden_doc, question) + for golden_doc, question in zip(golden_docs, questions) + ] + else: + raise ValueError(f"Unknown prompt_type: {prompt_type}") + + return system_prompt, prompts + + + def _clean_json_block(self, item: str) -> str: + return item.strip().removeprefix("```json").removeprefix("```").removesuffix("```").strip() + + def recall_score(self, dataframe): + sys_prompts, user_prompts = self._reformat_prompt(dataframe, "get_recall_score") + recall_scores = self.llm_serving.generate_from_input(user_prompts, sys_prompts) + valid_scores = [] + for score_str in recall_scores: + try: + score_dict = json.loads(self._clean_json_block(score_str)) + valid_scores.append(score_dict["answer_score"]) + except Exception as e: + print("recall score_str error:", score_str, "\nError:", e) + valid_scores.append(0) + continue + return valid_scores + + def recall_score_golden_doc(self, dataframe): + sys_prompts, user_prompts = self._reformat_prompt(dataframe, "get_golden_answer_score") + recall_scores = self.llm_serving.generate_from_input(user_prompts, sys_prompts) + valid_scores = [] + for score_str in recall_scores: + try: + score_dict = json.loads(self._clean_json_block(score_str)) + valid_scores.append(score_dict["answer_score"]) + except Exception as e: + print("recall score_str error:", score_str, "\nError:", e) + valid_scores.append(0) + continue + return valid_scores + + def more_optional_answer(self, dataframe): + original_answer = dataframe[self.output_refined_answer_key] + system_prompt, user_prompts = self._reformat_prompt(dataframe, "more_optional_answer") + optional_answers = self.llm_serving.generate_from_input(user_prompts, system_prompt) + valid_answers = [] + for optional_answer in optional_answers: + try: + if isinstance(optional_answer, str): + optional_answer = json.loads(self._clean_json_block(optional_answer)) + valid_answers.append(optional_answer) + else: + valid_answers.append(optional_answer) + except Exception as e: + print(f"Error parsing optional answer: {optional_answer} | Error: {e}") + valid_answers.append(original_answer) + return valid_answers + + def normalize_answer(self, s): + def remove_articles(text): + return re.sub(r"\b(a|an|the)\b", " ", text) + + def white_space_fix(text): + return " ".join(text.split()) + + def remove_punc(text): + exclude = set(string.punctuation) + return "".join(ch for ch in text if ch not in exclude) + + def lower(text): + return text.lower() + + return white_space_fix(remove_articles(remove_punc(lower(s)))) + + def get_f1_score(self, dataframe): + + f1_scores = [] + for idx, row in dataframe.iterrows(): + prediction = row[self.output_golden_doc_answer_key] + ground_truths = row[self.output_optional_answer_key] + + final_metric = {"f1": 0, "precision": 0, "recall": 0} + + if ground_truths is None or prediction is None: + f1_scores.append(final_metric['f1']) + continue + + if isinstance(ground_truths, str): + ground_truths = [ground_truths] + + for ground_truth in ground_truths: + + if ground_truth is None: + continue + + normalized_prediction = self.normalize_answer(prediction) + normalized_ground_truth = self.normalize_answer(ground_truth) + + if normalized_prediction in ["yes", "no", "noanswer"] and normalized_prediction != normalized_ground_truth: + continue + + if normalized_ground_truth in ["yes", "no", "noanswer"] and normalized_prediction != normalized_ground_truth: + continue + + prediction_tokens = normalized_prediction.split() + ground_truth_tokens = normalized_ground_truth.split() + common = Counter(prediction_tokens) & Counter(ground_truth_tokens) + num_same = sum(common.values()) + if num_same == 0: + continue + + precision = 1.0 * num_same / len(prediction_tokens) + recall = 1.0 * num_same / len(ground_truth_tokens) + f1 = (2 * precision * recall) / (precision + recall) + + final_metric["precision"] = max(precision, final_metric["precision"]) + final_metric["recall"] = max(recall, final_metric["recall"]) + final_metric["f1"] = max(f1, final_metric["f1"]) + + f1_scores.append(final_metric['f1']) + + return f1_scores + + + def run( + self, + storage: DataFlowStorage, + input_key: str = "prompts", + output_question_key: str = "question", + output_answer_key:str = "answer", + output_refined_answer_key:str = "refined_answer", + output_optional_answer_key: str = "optional_answer", + output_llm_answer_key: str = "llm_answer", + output_golden_doc_answer_key: str = "golden_doc_answer", + ): + self.input_key, self.output_question_key = input_key, output_question_key + + self.output_answer_key, self.output_refined_answer_key, self.output_optional_answer_key = output_answer_key, output_refined_answer_key, output_optional_answer_key + + self.output_llm_answer_key, self.output_golden_doc_answer_key = output_llm_answer_key, output_golden_doc_answer_key + + + dataframe = storage.read("dataframe").iloc[:] + self._validate_dataframe(dataframe) + + # === Step 0: Get identifier + self.logger.info("Get identifier...") + sys_prompts, user_prompts = self._reformat_prompt(dataframe, "get_identifier") + identifiers = self.llm_serving.generate_from_input(user_prompts, sys_prompts) + + # === Step 1: Get conclusions + self.logger.info("Get conclusions...") + sys_prompts, user_prompts = self._reformat_prompt(dataframe, "get_conclusion") + conclusions = self.llm_serving.generate_from_input(user_prompts, sys_prompts) + + # === Expand each conclusion into multiple candidate tasks (rows) + expanded_rows = [] + # Use to_dict('records') instead of itertuples() to preserve column names with special characters (e.g., "user:contents") + for idx, (row, output_str, identifier) in enumerate(zip(dataframe.to_dict('records'), conclusions, identifiers)): + try: + parsed = json.loads(self._clean_json_block(output_str)) + parsed = parsed[:self.max_per_task] if isinstance(parsed, list) else parsed + except Exception as e: + print(f"[WARN] JSON parse failed at idx={idx}: {e} | output: {output_str}") + continue + + if not isinstance(parsed, list): + continue + + for item in parsed: + if isinstance(item, dict) and "conclusion" in item and "R" in item: + expanded_rows.append({ + **row, # row is already a dict now + "identifier": str(identifier), + "candidate_tasks_str": json.dumps(item, ensure_ascii=False) + }) + + if not expanded_rows: + self.logger.warning("No valid candidate tasks extracted.") + return + + dataframe = pd.DataFrame(expanded_rows) + + # === Step 2: Generate questions based on conclusion + reasoning + self.logger.info("Generate questions based on conclusion + reasoning...") + sys_prompts, user_prompts = self._reformat_prompt(dataframe, "init_question") + question_outputs = self.llm_serving.generate_from_input(user_prompts, sys_prompts) + + questions = [] + answers = [] + valid_rows = [] + + # Use to_dict('records') instead of itertuples() to preserve column names with special characters + for idx, (res, row) in enumerate(zip(question_outputs, dataframe.to_dict('records'))): + try: + parsed = json.loads(self._clean_json_block(res)) + except Exception as e: + print(f"[WARN] Failed to parse question JSON at idx={idx}: {e} | res: {res}") + continue + + if isinstance(parsed, dict) and "Q" in parsed: + question = parsed["Q"] + try: + task = json.loads(self._clean_json_block(row['candidate_tasks_str'])) + answer = task.get("conclusion", "") + except Exception: + answer = "" + valid_rows.append(row) # row is already a dict + questions.append(str(question)) + answers.append(str(answer)) + + if not valid_rows: + self.logger.warning("No valid QA pairs generated.") + return + + dataframe = pd.DataFrame(valid_rows) + dataframe[self.output_question_key] = questions + dataframe[self.output_answer_key] = answers + + # === Step 3: Clean QA + self.logger.info("Clean QA...") + sys_prompts, user_prompts = self._reformat_prompt(dataframe, "clean_qa") + clean_outputs = self.llm_serving.generate_from_input(user_prompts, sys_prompts) + + final_answers = [] + + for idx, res in enumerate(clean_outputs): + try: + parsed = json.loads(self._clean_json_block(res)) + final_answers.append(str(parsed.get("refined_answer", ""))) + except Exception as e: + print(f"[WARN] Failed to parse cleaned QA at idx={idx}: {e} | res: {res}") + final_answers.append("") + + dataframe[self.output_refined_answer_key] = final_answers + + # Verify module + self.logger.info("LLM reasoning verify...") + sys_prompts, user_prompts = self._reformat_prompt(dataframe, "llm_answer") + llm_answer_results = self.llm_serving.generate_from_input(user_prompts, sys_prompts) + dataframe[self.output_llm_answer_key] = llm_answer_results + + llm_score = self.recall_score(dataframe) + dataframe["llm_score"] = llm_score + dataframe = dataframe[dataframe["llm_score"] < 1].reset_index(drop=True) + + if dataframe.empty: + self.logger.warning("No data left after LLM score filtering. All questions were answered correctly by LLM.") + return + + self.logger.info("Get golden doc answer...") + sys_prompts, user_prompts = self._reformat_prompt(dataframe, "golden_doc_answer") + llm_answer_results = self.llm_serving.generate_from_input(user_prompts, sys_prompts) + dataframe[self.output_golden_doc_answer_key] = llm_answer_results + + + # golden doc answer verify + self.logger.info("Golden doc LLM verifying...") + golden_doc_score = self.recall_score_golden_doc(dataframe) + dataframe["golden_doc_score"] = golden_doc_score + dataframe = dataframe[dataframe["golden_doc_score"] >= 1].reset_index(drop=True) + + # more optional answer + self.logger.info("Generating more optional answer...") + dataframe[self.output_optional_answer_key] = self.more_optional_answer(dataframe) + + dataframe = ( + dataframe.groupby(input_key, group_keys=False) + .apply(lambda x: x.head(self.max_question)) + .reset_index(drop=True) + ) + + output_file = storage.write(dataframe) + self.logger.info(f"Results saved to {output_file}") + return "identifier", "candidate_tasks_str", "llm_score", "golden_doc_score", self.output_question_key, self.output_answer_key, self.output_refined_answer_key, self.output_optional_answer_key, self.output_llm_answer_key, self.output_golden_doc_answer_key \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/generate/agenticrag_depth_qa_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/generate/agenticrag_depth_qa_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..9f2a5af3f2219be454182b075c947f31780056a6 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/generate/agenticrag_depth_qa_generator.py @@ -0,0 +1,244 @@ +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +from dataflow.core.prompt import prompt_restrict + +from dataflow.prompts.agenticrag import ( + DepthQAGeneratorGetIdentifierPrompt, + DepthQAGeneratorBackwardTaskPrompt, + DepthQAGeneratorSupersetCheckPrompt, + DepthQAGeneratorQuestionPrompt, + DepthQAGeneratorAnswerPrompt, + DepthQAGeneratorRecallScorePrompt +) +import pandas as pd +import json + +@prompt_restrict( + DepthQAGeneratorGetIdentifierPrompt, + DepthQAGeneratorBackwardTaskPrompt, + DepthQAGeneratorSupersetCheckPrompt, + DepthQAGeneratorQuestionPrompt, + DepthQAGeneratorAnswerPrompt, + DepthQAGeneratorRecallScorePrompt +) +@OPERATOR_REGISTRY.register() +class AgenticRAGDepthQAGenerator(OperatorABC): + def __init__(self, + llm_serving: LLMServingABC = None, + n_rounds:int = 2, + # prompt_template = None # prompt is fix + ): + self.logger= get_logger() + self.llm_serving = llm_serving + self.n_rounds = n_rounds + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子以已有问答生成更深度的问题。\n\n" + "输入参数:\n" + "- input_key: 输入字段名(默认值:\"question\")\n" + "- output_key: 输出字段名(默认值:\"depth_question\")\n" + ) + elif lang == "en": + return ( + "This operator is used to generate deeper questions based on existing QA pairs." + "Input Parameters:\n" + "- input_key: Field name for the input (default: \"question\")\n" + "- output_key: Field name for the output (default: \"depth_question\")\n" + ) + else: + return "DepthQAGenerator generate deeper questions based on existing QA pairs." + + def _validate_dataframe(self, dataframe: pd.DataFrame): + required_keys = [self.input_key] + forbidden_keys = [self.output_key] + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + raise ValueError(f"Missing required column(s): {missing}") + if conflict: + raise ValueError(f"The following column(s) already exist and would be overwritten: {conflict}") + + def _reformat_prompt(self, dataframe, prompt_type:str = None): + """ + Reformat the prompts in the dataframe to generate questions. + """ + if prompt_type == "get_identifier": + self.prompt_template = DepthQAGeneratorGetIdentifierPrompt() + input_prompts = dataframe[self.input_key].tolist() + system_prompts = self.prompt_template.build_system_prompt() + prompts = [self.prompt_template.build_prompt(input_prompts) for input_prompts in input_prompts] + elif prompt_type == "get_backward": + self.prompt_template = DepthQAGeneratorBackwardTaskPrompt() + input_prompts = dataframe[self.identifier_key].tolist() + system_prompts = "" + prompts = [self.prompt_template.build_prompt(input_prompts) for input_prompts in input_prompts] + elif prompt_type == "check_superset": + self.prompt_template = DepthQAGeneratorSupersetCheckPrompt() + new_identifiers = dataframe[self.new_identifier_key].tolist() + relations = dataframe[self.relation_key].tolist() + identifiers = dataframe[self.identifier_key].tolist() + system_prompts = self.prompt_template.build_system_prompt() + prompts = [self.prompt_template.build_prompt(new_id, relation, identifier) for new_id, relation, identifier in zip(new_identifiers, relations, identifiers)] + elif prompt_type == "get_new_question": + self.prompt_template = DepthQAGeneratorQuestionPrompt() + new_identifiers = dataframe[self.new_identifier_key].tolist() + relations = dataframe[self.relation_key].tolist() + identifiers = dataframe[self.identifier_key].tolist() + system_prompts = self.prompt_template.build_system_prompt() + prompts = [self.prompt_template.build_prompt(new_id, relation, identifier) for new_id, relation, identifier in zip(new_identifiers, relations, identifiers)] + elif prompt_type == "llm_answer": + self.prompt_template = DepthQAGeneratorAnswerPrompt() + questions = dataframe[self.input_key].tolist() + system_prompts = "" + prompts = [ + self.prompt_template.build_prompt(question) for question in questions + ] + elif prompt_type == "get_recall_score": + self.prompt_template = DepthQAGeneratorRecallScorePrompt() + golden_answers = dataframe["refined_answer"].tolist() + llm_answers = dataframe["llm_answer"] + system_prompts = self.prompt_template.build_system_prompt() + prompts = [ + self.prompt_template.build_prompt(golden_answer, llm_answer) for golden_answer, llm_answer in zip(golden_answers, llm_answers) + ] + else: + raise ValueError(f"Unknown prompt_type: {prompt_type}") + return system_prompts, prompts + + def _clean_json_block(self, item: str) -> str: + return item.strip().removeprefix("```json").removeprefix("```").removesuffix("```").strip() + + def recall_score(self, dataframe): + sys_prompts, user_prompts = self._reformat_prompt(dataframe, "get_recall_score") + recall_scores = self.llm_serving.generate_from_input(user_prompts, sys_prompts) + valid_scores = [] + for score_str in recall_scores: + if score_str is not None: + try: + score_dict = json.loads(score_str) + valid_scores.append(score_dict["answer_score"]) + except (json.JSONDecodeError, KeyError): + print(score_str) + valid_scores.append(0) + continue + return valid_scores + + def run( + self, + storage: DataFlowStorage, + input_key:str = "question", + output_key:str = "depth_question", + ): + self.input_key, self.output_key = input_key, output_key + dataframe = storage.read("dataframe") + self._validate_dataframe(dataframe) + + if "identifier" not in dataframe.columns: + sys_prompts, user_prompts = self._reformat_prompt(dataframe, "get_identifier") + identifiers = self.llm_serving.generate_from_input(user_prompts, sys_prompts) + dataframe["identifier"] = identifiers + + # step0: get identifier + for round_id in range(1, self.n_rounds + 1): + self.logger.info(f"=== Iteration Round {round_id} ===") + + # Use identifier from previous round + self.identifier_key = "identifier" if round_id == 1 else f"new_identifier_{round_id - 1}" + self.new_identifier_key, self.relation_key =f"new_identifier_{round_id}", f"relation_{round_id}" + # Backward Step: + # step1: Generate relation and superset + sys_prompts, user_prompts = self._reformat_prompt(dataframe, "get_backward") + backward_results = self.llm_serving.generate_from_input(user_prompts, sys_prompts) + + identifiers = [] + relations = [] + valid_indices = [] + + for idx, result in enumerate(backward_results): + try: + if isinstance(result, str): + result = json.loads(self._clean_json_block(result)) + + if isinstance(result, dict) and "identifier" in result and "relation" in result: + identifiers.append(result["identifier"]) + relations.append(result["relation"]) + valid_indices.append(idx) + else: + self.logger.warning(f"[Skipped]: Result at index {idx} is invalid: {result}") + except Exception as e: + self.logger.warning(f"[Error]: Failed to parse backward result at index {idx}: {e}") + continue + + dataframe = dataframe.iloc[valid_indices].copy() + dataframe[self.new_identifier_key] = identifiers + dataframe[self.relation_key] = relations + + # step2: Check if superset is valid + sys_prompts, user_prompts = self._reformat_prompt(dataframe, "check_superset") + check_results = self.llm_serving.generate_from_input(user_prompts, sys_prompts) + + valid_indices = [] + for idx, result in enumerate(check_results): + try: + if isinstance(result, str): + result = json.loads(self._clean_json_block(result)) + + if isinstance(result, dict) and "new_query" in result: + if result["new_query"] == "valid": + valid_indices.append(idx) + else: + self.logger.warning(f"[Skipped]: Result at index {idx} is invalid: {result}") + except Exception as e: + self.logger.warning(f"[Error]: Failed to check superset result at index {idx}: {e}") + continue + + dataframe = dataframe.iloc[valid_indices].copy() + + # step3: Generate question based on superset and relation + sys_prompts, user_prompts = self._reformat_prompt(dataframe, "get_new_question") + check_results = self.llm_serving.generate_from_input(user_prompts, sys_prompts) + + new_queries = [] + valid_indices = [] + for idx, result in enumerate(check_results): + try: + if isinstance(result, str): + result = json.loads(self._clean_json_block(result)) + + if isinstance(result, dict): + new_queries.append(result["new_query"]) + valid_indices.append(idx) + else: + self.logger.warning(f"[Skipped]: Result at index {idx} is invalid: {result}") + except Exception as e: + self.logger.warning(f"[Error]: Failed to check superset result at index {idx}: {e}") + continue + + dataframe = dataframe.iloc[valid_indices].copy() + question_key = f"{output_key}_{round_id}" + dataframe[question_key] = new_queries + + # Verify module + sys_prompts, user_prompts = self._reformat_prompt(dataframe, "llm_answer") + llm_answer_results = self.llm_serving.generate_from_input(user_prompts, sys_prompts) + + dataframe["llm_answer"] = llm_answer_results + llm_score = self.recall_score(dataframe) + dataframe["llm_score"] = llm_score + dataframe = dataframe[dataframe["llm_score"] < 1].drop(columns=["llm_score"]).reset_index(drop=True) + dataframe = dataframe.drop(columns="llm_answer") + + output_file = storage.write(dataframe) + self.logger.info(f"Results saved to {output_file}") + + return [f"new_identifier_{i}" for i in range(1, self.n_rounds + 1)] + \ + [f"relation_{i}" for i in range(1, self.n_rounds + 1)] + \ + [f"{output_key}_{i}" for i in range(1, self.n_rounds + 1)] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/generate/agenticrag_width_qa_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/generate/agenticrag_width_qa_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..bbab4ef9ac3c74a7daa2ccbdb49061b6c8678fd0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/agentic_rag/generate/agenticrag_width_qa_generator.py @@ -0,0 +1,245 @@ +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +from dataflow.core.prompt import prompt_restrict + +from dataflow.prompts.agenticrag import ( + WidthQAGeneratorMergePrompt, + WidthQAGeneratorOriginCheckPrompt, + WidthQAGeneratorQuestionVerifyPrompt, + WidthQAGeneratorAnswerPrompt, + WidthQAGeneratorRecallScorePrompt +) +import pandas as pd +import json + +@prompt_restrict( + WidthQAGeneratorMergePrompt, + WidthQAGeneratorOriginCheckPrompt, + WidthQAGeneratorQuestionVerifyPrompt, + WidthQAGeneratorAnswerPrompt, + WidthQAGeneratorRecallScorePrompt +) +@OPERATOR_REGISTRY.register() +class AgenticRAGWidthQAGenerator(OperatorABC): + def __init__(self, + llm_serving: LLMServingABC = None, + # prompt_template = None # prompt is fix + ): + self.logger= get_logger() + self.llm_serving = llm_serving + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于结合两个问答,生成新的问题。\n\n" + "输入参数:\n" + "- input_question_key: 输入问题字段名(默认值:\"question\")\n" + "- input_identifier_key: 输入标识符字段名(默认值:\"identifier\")\n" + "- input_answer_key: 输入答案字段名(默认值:\"answer\")\n" + "- output_question_key: 输出问题字段名(默认值:\"generated_width_task\")\n" + ) + elif lang == "en": + return ( + "This operator is used to combine two QA pairs and generate a new question." + "Input Parameters:\n" + "- input_question_key: Field name for the input question (default: \"question\")\n" + "- input_identifier_key: Field name for the input identifier (default: \"identifier\")\n" + "- input_answer_key: Field name for the input answer (default: \"answer\")\n" + "- output_question_key: Field name for the output question (default: \"generated_width_task\")\n" + ) + else: + return "WidthQAGenerator combine two QA pairs and generate a new question." + + def _validate_dataframe(self, dataframe: pd.DataFrame): + required_keys = [self.input_question_key, self.input_answer_key, self.input_identifier_key] + forbidden_keys = [self.output_question_key, "content_identifier", "qa_index", "index", "original_answer", "original_question", "state"] + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + raise ValueError(f"Missing required column(s): {missing}") + if conflict: + raise ValueError(f"The following column(s) already exist and would be overwritten: {conflict}") + + def _reformat_prompt(self, dataframe, prompt_type:str = None, input_batch: list[dict] = [None]): + """ + Reformat the prompts in the dataframe to generate questions. + """ + if prompt_type == "merge_prompt": + self.prompt_template = WidthQAGeneratorMergePrompt() + system_prompts = self.prompt_template.build_system_prompt() + prompts = [ + self.prompt_template.build_prompt([input_batch[i], input_batch[i + 1]]) + for i in range(len(input_batch) - 1) + ] + elif prompt_type == "check_origin": + self.prompt_template = WidthQAGeneratorOriginCheckPrompt() + input_batch = [] + for idx, q, ori_q in zip(dataframe["index"], dataframe["question"], dataframe["original_question"]): + input_batch.append({ + "index": idx, + "complex_question": q, + "original_questions": ori_q if isinstance(ori_q, list) else [ori_q] + }) + system_prompts = self.prompt_template.build_system_prompt() + prompts = [self.prompt_template.build_prompt(input) for input in input_batch] + return system_prompts, prompts + elif prompt_type == "question_verify": + self.prompt_template = WidthQAGeneratorQuestionVerifyPrompt() + input_batch = [] + for idx, q in zip(dataframe["index"], dataframe[self.output_question_key]): + input_batch.append({ + "index": idx, + "complex_question": q, + }) + system_prompts = self.prompt_template.build_system_prompt() + prompts = [self.prompt_template.build_prompt(input) for input in input_batch] + elif prompt_type == "get_recall_score": + self.prompt_template = WidthQAGeneratorRecallScorePrompt() + golden_answers = dataframe["original_answer"].tolist() + llm_answers = dataframe["llm_answer"] + system_prompts = self.prompt_template.build_system_prompt() + prompts = [ + self.prompt_template.build_prompt(golden_answer, llm_answer) for golden_answer, llm_answer in zip(golden_answers, llm_answers) + ] + else: + raise ValueError(f"Unknown prompt_type: {prompt_type}") + return system_prompts, prompts + + def _clean_json_block(self, item: str) -> str: + return item.strip().removeprefix("```json").removeprefix("```").removesuffix("```").strip() + + def recall_score(self, dataframe): + sys_prompts, user_prompts = self._reformat_prompt(dataframe, "get_recall_score") + recall_scores = self.llm_serving.generate_from_input(user_prompts, sys_prompts) + valid_scores = [] + for score_str in recall_scores: + if score_str is not None: + try: + score_dict = json.loads(score_str) + valid_scores.append(score_dict["answer_score"]) + except (json.JSONDecodeError, KeyError): + print(score_str) + valid_scores.append(0) + continue + return valid_scores + + def run( + self, + storage: DataFlowStorage, + input_question_key:str = "question", + input_identifier_key:str = "identifier", + input_answer_key:str = "answer", + output_question_key:str = "generated_width_task" + ): + self.input_question_key, self.input_identifier_key, self.input_answer_key, self.output_question_key = input_question_key, input_identifier_key,input_answer_key, output_question_key + dataframe = storage.read("dataframe") + self._validate_dataframe(dataframe) + + # step0: merge_prompt + input_batch = [] + for i, (_, row) in enumerate(dataframe.iterrows()): + input_batch.append({ + "index": i, + "question": row[self.input_question_key], + "content_identifier": row[self.input_identifier_key], + "golden_answer": row[self.input_answer_key] + }) + + sys_prompts, user_prompts = self._reformat_prompt(dataframe, "merge_prompt", input_batch) + merge_results = self.llm_serving.generate_from_input(user_prompts, sys_prompts) + + merged_rows = [] + for idx, result in enumerate(merge_results): + try: + if isinstance(result, str): + result = json.loads(self._clean_json_block(result))[0] + + if not isinstance(result, dict) or "question" not in result or "index" not in result: + self.logger.warning(f"[Skipped]: Invalid result at index {idx}: {result}") + continue + + indices = result["index"] if isinstance(result["index"], list) else [result["index"]] + group_items = [input_batch[i] for i in indices] + + merged_rows.append({ + "question": result["question"], + "content_identifier": result["content_identifier"], + "qa_index": indices, + "index": idx, + "original_answer": [item["golden_answer"] for item in group_items], + "original_question": [item["question"] for item in group_items], + }) + + except Exception as e: + self.logger.warning(f"[Error]: Failed to parse merge result at index {idx}: {e}") + continue + + dataframe = pd.DataFrame(merged_rows) + + # check queries + # Step 1: Check if complex questions can be decomposed to original questions + sys_prompts, user_prompts = self._reformat_prompt(dataframe, "check_origin") + check_query_results = self.llm_serving.generate_from_input(user_prompts, sys_prompts) + + states = [] + complex_questions = [] + + for idx, result in enumerate(check_query_results): + try: + if isinstance(result, str): + result = json.loads(self._clean_json_block(result)) + if isinstance(result, list): + result = result[0] + + if isinstance(result, dict): + states.append(result.get("state", None)) + complex_questions.append(result.get("complex_question", None)) + else: + self.logger.warning(f"[Skipped]: Invalid result at index {idx}: {result}") + states.append(None) + complex_questions.append(None) + except Exception as e: + self.logger.warning(f"[Error]: Failed to parse result at index {idx}: {e}") + states.append(None) + complex_questions.append(None) + + dataframe["state"] = states + dataframe[self.output_question_key] = complex_questions + dataframe = dataframe[dataframe["state"] == 1].copy() + + # Step 2: Verify if LLM can answer the complex questions + sys_prompts, user_prompts = self._reformat_prompt(dataframe, "question_verify") + question_verify_results = self.llm_serving.generate_from_input(user_prompts, sys_prompts) + + llm_answers = [] + for idx, result in enumerate(question_verify_results): + try: + if isinstance(result, str): + result = json.loads(self._clean_json_block(result))[0] + + if isinstance(result, dict): + llm_answers.append(result.get("llm_answer", None)) + + else: + self.logger.warning(f"[Skipped]: Invalid result at index {idx}: {result}") + llm_answers.append(None) + except Exception as e: + self.logger.warning(f"[Error]: Failed to parse result at index {idx}: {e}") + llm_answers.append(None) + + dataframe["llm_answer"] = llm_answers + + llm_score = self.recall_score(dataframe) + dataframe["llm_score"] = llm_score + dataframe = dataframe[dataframe["llm_score"] < 1].drop(columns=["llm_score"]).reset_index(drop=True) + dataframe = dataframe.drop(columns="llm_answer") + + output_file = storage.write(dataframe) + self.logger.info(f"Results saved to {output_file}") + return \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/chemistry/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/chemistry/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..61f0c654d4632329bace7c8c53463fbe6e8c299c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/chemistry/__init__.py @@ -0,0 +1,13 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from generate.extract_smiles_from_text_generator import ExtractSmilesFromTextGenerator + from eval.smiles_equivalence_dataset_evaluator import SmilesEquivalenceDatasetEvaluator +else: + import sys + from dataflow.utils.registry import LazyLoader, generate_import_structure_from_type_checking + + cur_path = "dataflow/operators/chemistry/" + + _import_structure = generate_import_structure_from_type_checking(__file__, cur_path) + sys.modules[__name__] = LazyLoader(__name__, "dataflow/operators/chemistry/", _import_structure) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/chemistry/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/chemistry/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9766f7eb1ee88cef658f5812ed120ff44001f05f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/chemistry/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/chemistry/eval/__pycache__/smiles_equivalence_dataset_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/chemistry/eval/__pycache__/smiles_equivalence_dataset_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6df87028f844003758c5b037ecaf4f34bb232451 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/chemistry/eval/__pycache__/smiles_equivalence_dataset_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/chemistry/eval/smiles_equivalence_dataset_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/chemistry/eval/smiles_equivalence_dataset_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..0e1e80814bb3c79a78d965308e1e779f1dd286f5 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/chemistry/eval/smiles_equivalence_dataset_evaluator.py @@ -0,0 +1,165 @@ +import pandas as pd +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger + +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +import json + +@OPERATOR_REGISTRY.register() +class SmilesEquivalenceDatasetEvaluator(OperatorABC): + """ + 对每个块(row)里的 golden_label 与 synth_smiles 进行 SMILES 等价性评估: + - 以 abbreviation 对齐 + - RDKit 规范 SMILES 后比较是否相等(相等=1,否则=0;不存在对应项=0) + - 输出到 dataframe 的新列:final_result(list[dict])、block_score、block_total、block_accuracy + - 统计 overall 汇总并保存到 self.overall_summary + """ + def __init__(self, llm_serving: LLMServingABC = None): + self.logger = get_logger() + self.overall_summary = None # 评估完成后填充 + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "评估 golden_label 与 synth_smiles 的 SMILES 等价性并计算分数。" + "逐块输出 final_result、块内得分与准确率,并统计全局总分。" + ) + elif lang == "en": + return ( + "Evaluate SMILES equivalence between golden_label and synth_smiles per block, " + "emit final_result, block-level scores/accuracy, and compute overall summary." + ) + else: + return "Evaluate SMILES equivalence for each block." + + # ========= 内部工具函数(不对用户暴露) ========= + def _are_smiles_equivalent(self, s1: str, s2: str) -> bool: + """ + 使用 RDKit 将 SMILES 规范化后判断是否等价。 + 任意一侧解析失败,返回 False。 + """ + try: + from rdkit import Chem + except ImportError: + raise Exception( + """ + rdkit is not installed in this environment yet. + Please use pip install rdkit. + """ + ) + try: + m1, m2 = Chem.MolFromSmiles(s1), Chem.MolFromSmiles(s2) + if m1 is None or m2 is None: + return False + c1 = Chem.MolToSmiles(m1, canonical=True) + c2 = Chem.MolToSmiles(m2, canonical=True) + return c1 == c2 + except Exception as e: + self.logger.warning(f"SMILES 解析异常: {e}") + return False + + def _score_one_block(self, golden_label, synth_smiles): + """ + 对单个块计算: + - final_result: list[ {abbreviation, full_name, smiles, score} ] + - block_score, block_total, block_accuracy + """ + golden = golden_label or [] + synth = synth_smiles or [] + + # 用 abbreviation 建索引(synth_smiles 可能为空/缺字段) + synth_map = {} + for item in synth: + abbr = (item or {}).get("abbreviation") + smi = (item or {}).get("smiles") + if abbr is not None and smi is not None: + synth_map[abbr] = smi + + final_result = [] + block_score = 0 + + for g in golden: + abbr = (g or {}).get("abbreviation", "") + gold_smi = (g or {}).get("smiles", "") + synth_smi = synth_map.get(abbr) # 可能 None + + score = 0 + if synth_smi is not None: + score = 1 if self._are_smiles_equivalent(gold_smi, synth_smi) else 0 + + block_score += score + final_result.append({ + "abbreviation": abbr, + "full_name": (g or {}).get("full_name", ""), + "smiles": gold_smi, + "score": score + }) + + block_total = len(golden) + block_accuracy = (block_score / block_total) if block_total else None + + return final_result, block_score, block_total, block_accuracy + + # ========= 对外主流程 ========= + def run( + self, + storage: DataFlowStorage, + input_golden_key: str = "golden_label", + input_synth_key: str = "synth_smiles", + output_key: str = "final_result", + ): + """ + dataframe 视作读取到的 JSON(每行一个块),按照给定 key 取出 golden/synth,写回评估结果。 + 返回 output_key(供后续算子引用)。 + """ + self.logger.info("Running EvaluateSmilesEquivalence...") + + # 读取 dataframe + dataframe = storage.read('dataframe') + self.logger.info(f"Loaded dataframe with {len(dataframe)} rows") + + # 为结果准备列 + block_scores = [] + block_totals = [] + block_accuracies = [] + final_results_all = [] + + # 逐行(块)评估 + for idx, row in dataframe.iterrows(): + golden_label = row.get(input_golden_key, []) # list[dict] + synth_smiles = row.get(input_synth_key, []) # list[dict](可能为空) + + final_result, block_score, block_total, block_accuracy = \ + self._score_one_block(golden_label, synth_smiles) + + final_results_all.append(final_result) + block_scores.append(block_score) + block_totals.append(block_total) + block_accuracies.append(block_accuracy) + + # 写回列 + dataframe[output_key] = final_results_all + dataframe["block_score"] = block_scores + dataframe["block_total"] = block_totals + dataframe["block_accuracy"] = block_accuracies + + # 汇总总体分数 + overall_score = int(sum(block_scores)) + overall_total = int(sum(block_totals)) + overall_accuracy = (overall_score / overall_total) if overall_total else None + + self.overall_summary = { + "overall_score": overall_score, + "overall_total": overall_total, + "overall_accuracy": overall_accuracy + } + self.logger.info(f"Overall summary: {self.overall_summary}") + + # 保存更新后的 dataframe + storage.write(dataframe) + + # 返回给后续算子使用的列名(与 ExtractSmilesFromText 一致风格) + return output_key diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/chemistry/generate/__pycache__/extract_smiles_from_text_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/chemistry/generate/__pycache__/extract_smiles_from_text_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a04e81275fa4b7788c55a810f23a8b23c8bb2b98 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/chemistry/generate/__pycache__/extract_smiles_from_text_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/chemistry/generate/extract_smiles_from_text_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/chemistry/generate/extract_smiles_from_text_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..b639ddf141d820700e5c6b9d4cbecc17c11d2da4 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/chemistry/generate/extract_smiles_from_text_generator.py @@ -0,0 +1,189 @@ +import pandas as pd +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger + +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +import json + +import json +import re + +from typing import Union +from dataflow.core.prompt import prompt_restrict, DIYPromptABC +from dataflow.prompts.chemistry import ExtractSmilesFromTextPrompt + + +@prompt_restrict( + ExtractSmilesFromTextPrompt +) +@OPERATOR_REGISTRY.register() +class ExtractSmilesFromTextGenerator(OperatorABC): + ''' + Answer Generator is a class that generates answers for given questions. + ''' + def __init__(self, llm_serving: LLMServingABC, prompt_template: Union[ExtractSmilesFromTextPrompt, DIYPromptABC] = ExtractSmilesFromTextPrompt): + self.logger = get_logger() + self.llm_serving = llm_serving + self.prompt_template = prompt_template + self.json_failures = 0 + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "ExtractSmilesFromText 用于从 OCR 文本中抽取或解析化学分子的 SMILES 表达式。" + "算子会根据给定的提示模板(prompt_template),结合文本内容和(可选的)单体缩写信息," + "调用大语言模型完成解析与结构化,并将结果以 JSON 格式写回到指定列。\n" + "\n输入参数:\n" + "- llm_serving:LLM 服务对象,需实现 LLMServingABC 接口\n" + "- prompt_template:提示词模板对象,用于构造模型输入\n" + "- input_content_key: OCR 文本的列名(默认 'text')\n" + "- input_abbreviation_key:包含缩写/单体信息的列名(默认 'abbreviations'),可为空\n" + "- output_key:写回抽取结果的列名(默认 'synth_smiles')\n" + "\n输出参数:\n" + "- DataFrame,其中 output_key 列为模型返回并经 JSON 解析后的 SMILES 结构\n" + "- 返回 output_key,供后续算子引用\n" + "\n备注:\n" + "- 模型输出会尝试解析为 JSON;若解析失败,将返回 [] 并记录失败次数。" + ) + elif lang == "en": + return ( + "ExtractSmilesFromText is designed to extract or parse chemical SMILES expressions " + "from OCR text. It uses a given prompt_template to construct model inputs, combining " + "text content and optional abbreviation/monomer information, then calls the LLM to " + "produce structured outputs which are parsed into JSON.\n" + "\nInput Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC\n" + "- prompt_template: Prompt template object used to build model input\n" + "- input_content_key: Column name containing OCR text (default 'text')\n" + "- input_abbreviation_key: Column name containing abbreviations/monomer info (default 'abbreviations'); optional\n" + "- output_key: Column name to store extracted results (default 'synth_smiles')\n" + "\nOutput:\n" + "- DataFrame with output_key column containing JSON-parsed SMILES structures\n" + "- Returns output_key for downstream operators\n" + "\nNotes:\n" + "- The operator attempts to parse model outputs as JSON; failures return [] and are counted." + ) + else: + return "ExtractSmilesFromText extracts chemical SMILES expressions from OCR text using an LLM." + + def _strip_code_fence(self, s: str) -> str: + s = s.strip() + # 去掉 ```json ... ``` 或 ``` ... ``` + if s.startswith("```"): + # 去掉第一行的 ```(json)? + s = re.sub(r"^```(?:json|JSON)?\s*", "", s) + # 去掉结尾 ``` + s = re.sub(r"\s*```$", "", s) + return s.strip() + + def _safe_json_load(self, item): + """ + 尝试把 item 解析为 JSON: + - 解析失败:返回 [],并将 self.json_failures += 1 + - 解析成功:返回解析后的对象(list/dict/其他 JSON 标准类型) + """ + try: + # 已经是结构化就直接返回 + if isinstance(item, (list, dict)): + return item + if item is None: + return [] # 约定空返回 + + # 其他类型(比如 float/int)转成字符串再处理 + if not isinstance(item, str): + item = str(item) + + s = item.strip() + if not s: + return [] # 空字符串 + + # 去掉代码块围栏 + s = self._strip_code_fence(s) + + # 去掉包裹的引号(例如整个内容被 "..." 或 '...' 包着) + if (s.startswith('"') and s.endswith('"')) or (s.startswith("'") and s.endswith("'")): + s = s[1:-1].strip() + + # 去掉前缀 json/JSON + s = re.sub(r"^\s*(?:json|JSON)\s*", "", s) + + # 定位第一个 { 或 [,从这里开始截 + m = re.search(r"[\[\{]", s) + if m: + s = s[m.start():].strip() + + # 如果末尾有多余字符,尝试保留到最后一个 ] 或 } + last_bracket = max(s.rfind("]"), s.rfind("}")) + if last_bracket != -1: + s = s[:last_bracket + 1].strip() + + # 第一次解析 + obj = json.loads(s) + + # 如果第一次解析结果仍是字符串,尝试再解一次(处理二次编码) + if isinstance(obj, str): + try: + obj2 = json.loads(obj) + return obj2 + except json.JSONDecodeError: + # 二次解析失败不视为致命,返回第一次结果 + return obj + + return obj + + except Exception as e: + # 任何异常:计数 + 返回空列表 + self.json_failures += 1 + # 打印精简预览,避免日志过长 + preview = "" + try: + preview = (s if len(s) <= 200 else s[:200] + "...").replace("\n", "\\n") + except Exception: + preview = "" + self.logger.warning(f"[safe_json_load] 解析失败,第{self.json_failures}次;错误:{type(e).__name__}: {e};预览: {preview}") + return [] + + def run(self, storage: DataFlowStorage, input_content_key: str = "text", input_abbreviation_key: str = "abbreviations", output_key: str = "synth_smiles"): + # self.input_key, self.output_key = input_key, output_key + self.logger.info("Running PromptGenerator...") + + # Load the raw dataframe from the input file + dataframe = storage.read('dataframe') + self.logger.info(f"Loading, number of rows: {len(dataframe)}") + + # Create a list to hold all generated questions and answers + llm_inputs = [] + + # Prepare LLM inputs by formatting the prompt with raw content from the dataframe + for index, row in dataframe.iterrows(): + content = row.get(input_content_key, '') + monomer = row.get(input_abbreviation_key, '') + llm_input = self.prompt_template.build_prompt(monomer) + content + llm_inputs.append(llm_input) + + # Generate the text using the model + try: + self.logger.info("Generating text using the model...") + generated_outputs = self.llm_serving.generate_from_input(llm_inputs) + self.logger.info("Text generation completed.") + except Exception as e: + self.logger.error(f"Error during text generation: {e}") + return + + parsed_outputs = [] + for item in generated_outputs: + try: + parsed_outputs.append(self._safe_json_load(item)) + except Exception: + parsed_outputs.append([]) + #parsed_outputs = [self._safe_json_load(item)['chemical_structures'] for item in generated_outputs] + # print(parsed_outputs) + dataframe[output_key] = parsed_outputs + + # Save the updated dataframe to the output file + output_file = storage.write(dataframe) + return output_key + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..665bae63f107d34ad3f0d3864d466eda5de427f3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/__init__.py @@ -0,0 +1,42 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + # filter + from .filter.code_autogen_filter import CodeAutoGeneratedFilter + from .filter.code_doc_quality_filter import CodeDocumentQualityFilter + from .filter.code_encoded_data_filter import CodeEncodedDataFilter + from .filter.code_file_type_content_filter import CodeFileTypeContentFilter + from .filter.code_length_filter import CodeLengthSampleFilter + from .filter.code_quality_score_filter import CodeQualityScoreFilter + from .filter.code_score_filter import CodeGenericScoreFilter + from .filter.code_text_composition_filter import CodeTextCompositionFilter + + # generate + from .generate.code_code_to_instruction_generator import CodeCodeToInstructionGenerator + from .generate.code_instruction_to_code_generator import CodeInstructionToCodeGenerator + from .generate.code_instruction_enhancement import CodeEnhancementInstructionGenerator + from .generate.code_gen_instruction import CodeInstructionGenerator + # eval + from .eval.code_auto_generated_sample_evaluator import CodeAutoGeneratedSampleEvaluator + from .eval.code_document_quality_sample_evaluator import CodeDocumentQualitySampleEvaluator + from .eval.code_encoded_data_sample_evaluator import CodeEncodedDataSampleEvaluator + from .eval.code_length_sample_evaluator import CodeLengthSampleEvaluator + from .eval.code_quality_sample_evaluator import CodeQualitySampleEvaluator + from .eval.code_sandbox_sample_evaluator import CodeSandboxSampleEvaluator + from .eval.code_text_composition_sample_evaluator import CodeTextCompositionSampleEvaluator + from .eval.python_executor import ( + ImageRuntime, + DateRuntime, + CustomDict, + ColorObjectRuntime, + PythonExecutor + ) + +else: + import sys + from dataflow.utils.registry import LazyLoader, generate_import_structure_from_type_checking + + cur_path = "dataflow/operators/code/" + + _import_structure = generate_import_structure_from_type_checking(__file__, cur_path) + sys.modules[__name__] = LazyLoader(__name__, "dataflow/operators/code/", _import_structure) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7707520617ba8164e2d510a09da9b2daa7766622 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/__pycache__/code_auto_generated_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/__pycache__/code_auto_generated_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ccdffdffaea9effc4e47c7f52748cd0f5ff6d7c Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/__pycache__/code_auto_generated_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/__pycache__/code_document_quality_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/__pycache__/code_document_quality_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..562d3da8ce008f5a08b8ef87d8f332ae456dbc2c Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/__pycache__/code_document_quality_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/__pycache__/code_encoded_data_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/__pycache__/code_encoded_data_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd0b9778a0fa2017a940525cb81f4d4741711592 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/__pycache__/code_encoded_data_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/__pycache__/code_length_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/__pycache__/code_length_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e98539f309aa34baac08c09cc9f500f632bca7f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/__pycache__/code_length_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/__pycache__/code_quality_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/__pycache__/code_quality_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e0d05f0413bf93f1d6a88afc30a69df97a0fb7f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/__pycache__/code_quality_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/__pycache__/code_sandbox_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/__pycache__/code_sandbox_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..afa3d860cb27d1670ff32a9e8b511180ad4c6a2b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/__pycache__/code_sandbox_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/__pycache__/code_text_composition_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/__pycache__/code_text_composition_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2434aecd90fd00c4400c15c9abc1fe9c8009a163 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/__pycache__/code_text_composition_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/__pycache__/python_executor.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/__pycache__/python_executor.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c6a778edbd7293010e8ac9e8bf0de10c67f0c68 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/__pycache__/python_executor.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/code_auto_generated_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/code_auto_generated_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..b30cb70cd4cc3d3dca7c12b69d84ad81004cb5c1 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/code_auto_generated_sample_evaluator.py @@ -0,0 +1,136 @@ +import pandas as pd +from typing import List, Dict, Callable, Optional +from tqdm import tqdm + +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC + +@OPERATOR_REGISTRY.register() +class CodeAutoGeneratedSampleEvaluator(OperatorABC): + """ + CodeAutoGeneratedSampleEvaluator evaluates code samples based on auto-generation + markers to provide scores for filtering auto-generated code files. + """ + + # Common markers for auto-generated code + AUTOGEN_PATTERNS = [ + "auto-generated", "autogenerated", "automatically generated", + "generated automatically", "this file is generated" + ] + + def __init__(self, is_generated_func: Optional[Callable[[], bool]] = None): + """ + Initialize the operator and set up the logger. + + Args: + is_generated_func: Optional external detection function + """ + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.score_name = 'CodeAutoGeneratedScore' + self.is_generated_func = is_generated_func + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + """ + Provide operator functionality description and parameter documentation. + """ + if lang == "zh": + return ( + "基于自动生成标记评估代码样本,检测文件头部的自动生成标记。\n\n" + "评估指标:\n" + "- CodeAutoGeneratedMarkerCount: 检测到的自动生成标记数量\n" + "- CodeAutoGeneratedScore: 综合自动生成得分 (0-1,1表示非自动生成)\n\n" + "输入要求:需要包含'lines'列\n\n" + "输出参数:\n" + "- CodeAutoGeneratedMarkerCount: 检测到的自动生成标记数量\n" + "- CodeAutoGeneratedScore: 综合自动生成得分" + ) + else: + return ( + "Evaluate code samples based on auto-generation markers, detecting auto-generation markers in file headers.\n\n" + "Evaluation Metrics:\n" + "- CodeAutoGeneratedMarkerCount: Number of detected auto-generation markers\n" + "- CodeAutoGeneratedScore: Comprehensive auto-generation score (0-1, 1 means not auto-generated)\n\n" + "Input Requirement: Requires 'lines' column\n\n" + "Output Parameters:\n" + "- CodeAutoGeneratedMarkerCount: Number of detected auto-generation markers\n" + "- CodeAutoGeneratedScore: Comprehensive auto-generation score" + ) + + def _score_func(self, sample): + """ + Calculate auto-generation scores for a single code sample. + + Args: + sample: Dictionary containing 'lines' key + + Returns: + Dictionary containing auto-generation scores + """ + lines = sample.get('lines', []) + + # Check external function first + marker_count = 0 + if self.is_generated_func and self.is_generated_func(): + marker_count = 1 + + # Check first 5 lines for markers + first_5 = "\n".join(lines[:5]).lower() + for pat in self.AUTOGEN_PATTERNS: + if pat in first_5: + marker_count += 1 + + # Calculate comprehensive score (0-1) + score = 1.0 if marker_count == 0 else 0.0 + + return { + 'CodeAutoGeneratedMarkerCount': marker_count, + 'CodeAutoGeneratedScore': score + } + + def eval(self, dataframe, input_key): + """ + Evaluate auto-generation markers for all samples in the dataframe. + + Args: + dataframe: Input DataFrame + input_key: Key containing the sample data + + Returns: + List of score dictionaries + """ + scores_list = [] + self.logger.info(f"Evaluating {self.score_name}...") + + for _, row in dataframe.iterrows(): + sample = row[input_key] if isinstance(row[input_key], dict) else {"lines": row[input_key]} + scores = self._score_func(sample) + scores_list.append(scores) + + self.logger.info("Evaluation complete!") + return scores_list + + def run(self, storage: DataFlowStorage, input_key: str): + """ + Execute auto-generation marker evaluation operation. + + Args: + storage: Data storage object + input_key: Key name for input data + """ + self.input_key = input_key + dataframe = storage.read("dataframe") + self.logger.info("CodeAutoGeneratedScore ready to evaluate.") + + scores = self.eval(dataframe, input_key) + + # Flatten the nested dictionary of scores into the dataframe + for idx, score_dict in enumerate(scores): + for key, value in score_dict.items(): + dataframe.at[idx, key] = value + + storage.write(dataframe) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/code_document_quality_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/code_document_quality_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..1a108afef13e2c9235ad51b85f7d08d01a6c59ad --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/code_document_quality_sample_evaluator.py @@ -0,0 +1,263 @@ +import pandas as pd +import re +import math +from typing import List, Dict, Any +from collections import Counter +from tqdm import tqdm + +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC + +@OPERATOR_REGISTRY.register() +class CodeDocumentQualitySampleEvaluator(OperatorABC): + """ + CodeDocumentQualitySampleEvaluator evaluates code samples based on comprehensive + document-level quality metrics to provide scores for filtering low-quality content. + """ + + def __init__(self, thresholds: Dict[str, Any] = None): + """ + Initialize the operator and set up thresholds. + + Args: + thresholds: Optional thresholds dictionary to override defaults + """ + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.score_name = 'CodeDocumentQualityScore' + + # Default thresholds for each rule + default_thresholds = { + 'min_num_chars': 1, + 'max_num_chars': 100000, + 'min_num_words': 1, + 'max_num_words': 100000, + 'max_frac_duplicate_lines': 1.0, + 'max_frac_duplicate_2gram': 1.0, + 'max_frac_duplicate_3gram': 1.0, + 'max_frac_duplicate_4gram': 1.0, + 'max_frac_duplicate_5gram': 1.0, + 'max_frac_duplicate_6gram': 1.0, + 'max_frac_duplicate_7gram': 1.0, + 'max_frac_duplicate_8gram': 1.0, + 'max_frac_duplicate_9gram': 1.0, + 'max_frac_duplicate_10gram': 1.0, + 'max_frac_curly_bracket': 1.0, + 'max_frac_all_caps_words': 1.0, + 'min_entropy_unigram': 0.0, + } + + # Merge with provided thresholds + self.thresholds = default_thresholds.copy() + if thresholds: + self.thresholds.update(thresholds) + + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + """ + Provide operator functionality description and parameter documentation. + """ + if lang == "zh": + return ( + "基于综合文档级质量指标评估代码样本,包括内容长度、重复模式、字符组成和文本熵值。\n\n" + "评估指标:\n" + "- CodeDocumentQualityCharCount: 字符数\n" + "- CodeDocumentQualityWordCount: 词数\n" + "- CodeDocumentQualityDuplicateLinesRatio: 重复行比例\n" + "- CodeDocumentQualityDuplicateNgramRatio: n-gram重复比例\n" + "- CodeDocumentQualityCurlyBracketRatio: 花括号比例\n" + "- CodeDocumentQualityAllCapsRatio: 全大写单词比例\n" + "- CodeDocumentQualityEntropy: 单字符熵值\n" + "- CodeDocumentQualityScore: 综合文档质量得分 (0-1,1表示通过所有质量检查)\n\n" + "输入要求:需要包含'text'、'filename'、'language'列\n\n" + "输出参数:\n" + "- 各种质量指标的数值\n" + "- CodeDocumentQualityScore: 综合文档质量得分" + ) + else: + return ( + "Evaluate code samples based on comprehensive document-level quality metrics including content length, repetition patterns, character composition, and text entropy.\n\n" + "Evaluation Metrics:\n" + "- CodeDocumentQualityCharCount: Character count\n" + "- CodeDocumentQualityWordCount: Word count\n" + "- CodeDocumentQualityDuplicateLinesRatio: Duplicate lines ratio\n" + "- CodeDocumentQualityDuplicateNgramRatio: n-gram repetition ratio\n" + "- CodeDocumentQualityCurlyBracketRatio: Curly bracket ratio\n" + "- CodeDocumentQualityAllCapsRatio: All-caps words ratio\n" + "- CodeDocumentQualityEntropy: Unigram entropy\n" + "- CodeDocumentQualityScore: Comprehensive document quality score (0-1, 1 means passes all quality checks)\n\n" + "Input Requirement: Requires 'text', 'filename', 'language' columns\n\n" + "Output Parameters:\n" + "- Various quality metric values\n" + "- CodeDocumentQualityScore: Comprehensive document quality score" + ) + + def _frac_duplicate_ngrams_n(self, text: str, n: int) -> float: + """Calculate the fraction of duplicate n-grams in the text""" + words = re.findall(r'\b\w+\b', text) + if len(words) < n: + return 0.0 + ngrams = [' '.join(words[i:i+n]) for i in range(len(words)-n+1)] + ngram2count = Counter(ngrams) + count = sum([v for v in ngram2count.values() if v != 1]) + total = sum([v for v in ngram2count.values()]) + return count / total if total else 0.0 + + def _num_chars(self, text: str) -> int: + return len(text) + + def _num_words(self, text: str) -> int: + return len(re.findall(r'\w+', text)) + + def _frac_duplicate_lines(self, lines: List[str]) -> float: + if not lines: + return 0.0 + line2count = Counter([l.strip() for l in lines if l.strip()]) + count = sum([v for v in line2count.values() if v != 1]) + total = sum([v for v in line2count.values()]) + return count / total if total else 0.0 + + def _frac_curly_bracket(self, text: str) -> float: + total = len(text) + if total == 0: + return 0.0 + count = text.count('{') + text.count('}') + return count / total + + def _frac_all_caps_words(self, text: str) -> float: + words = re.findall(r'\b\w+\b', text) + if not words: + return 0.0 + all_caps = [w for w in words if w.isupper() and len(w) > 1] + return len(all_caps) / len(words) + + def _entropy_unigram(self, text: str) -> float: + words = re.findall(r'\b\w+\b', text) + if not words: + return 0.0 + freq = Counter(words) + total = sum(freq.values()) + entropy = -sum((c/total) * math.log2(c/total) for c in freq.values()) + return entropy + + def _score_func(self, sample): + """ + Calculate document quality scores for a single code sample. + + Args: + sample: Dictionary containing 'text', 'filename', 'language' keys + + Returns: + Dictionary containing document quality scores + """ + text = sample.get('text', sample.get('content', '')) + filename = sample.get('filename', '') + lang = sample.get('language', 'en') + lines = text.splitlines() + + # Use instance thresholds + thresh = self.thresholds + + # Calculate individual metrics + num_chars = self._num_chars(text) + num_words = self._num_words(text) + frac_dup_lines = self._frac_duplicate_lines(lines) + frac_curly = self._frac_curly_bracket(text) + frac_caps = self._frac_all_caps_words(text) + entropy = self._entropy_unigram(text) + + # Calculate n-gram ratios + ngram_ratios = {} + for n in range(2, 11): + key = f'max_frac_duplicate_{n}gram' + if key in thresh: + ngram_ratios[f'duplicate_{n}gram_ratio'] = self._frac_duplicate_ngrams_n(text, n) + + # Calculate comprehensive score (0-1) + score = 1.0 + + # Apply all quality rules + if num_chars < thresh['min_num_chars'] or num_chars > thresh['max_num_chars']: + score = 0.0 + elif num_words < thresh['min_num_words'] or num_words > thresh['max_num_words']: + score = 0.0 + elif frac_dup_lines > thresh['max_frac_duplicate_lines']: + score = 0.0 + elif frac_curly > thresh['max_frac_curly_bracket']: + score = 0.0 + elif frac_caps > thresh['max_frac_all_caps_words']: + score = 0.0 + elif entropy < thresh['min_entropy_unigram']: + score = 0.0 + else: + # Check n-gram ratios + for n in range(2, 11): + key = f'max_frac_duplicate_{n}gram' + if key in thresh: + frac_dup_ngram = self._frac_duplicate_ngrams_n(text, n) + if frac_dup_ngram > thresh[key]: + score = 0.0 + break + + # Prepare result dictionary + result = { + 'CodeDocumentQualityCharCount': num_chars, + 'CodeDocumentQualityWordCount': num_words, + 'CodeDocumentQualityDuplicateLinesRatio': frac_dup_lines, + 'CodeDocumentQualityCurlyBracketRatio': frac_curly, + 'CodeDocumentQualityAllCapsRatio': frac_caps, + 'CodeDocumentQualityEntropy': entropy, + 'CodeDocumentQualityScore': score + } + + # Add n-gram ratios + result.update({f'CodeDocumentQuality{k.title()}Ratio': v for k, v in ngram_ratios.items()}) + + return result + + def eval(self, dataframe, input_key): + """ + Evaluate document quality for all samples in the dataframe. + + Args: + dataframe: Input DataFrame + input_key: Key containing the sample data + + Returns: + List of score dictionaries + """ + scores_list = [] + self.logger.info(f"Evaluating {self.score_name}...") + + for _, row in dataframe.iterrows(): + sample = row[input_key] if isinstance(row[input_key], dict) else {"text": row[input_key], "filename": "", "language": "unknown"} + scores = self._score_func(sample) + scores_list.append(scores) + + self.logger.info("Evaluation complete!") + return scores_list + + def run(self, storage: DataFlowStorage, input_key: str): + """ + Execute document quality evaluation operation. + + Args: + storage: Data storage object + input_key: Key name for input data + """ + self.input_key = input_key + dataframe = storage.read("dataframe") + self.logger.info("CodeDocumentQualityScore ready to evaluate.") + + scores = self.eval(dataframe, input_key) + + # Flatten the nested dictionary of scores into the dataframe + for idx, score_dict in enumerate(scores): + for key, value in score_dict.items(): + dataframe.at[idx, key] = value + + storage.write(dataframe) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/code_encoded_data_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/code_encoded_data_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..8cd229fa87bc6692e03dd269aa0344f64f015912 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/code_encoded_data_sample_evaluator.py @@ -0,0 +1,160 @@ +import re +import pandas as pd +from typing import Dict +from tqdm import tqdm + +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC + +@OPERATOR_REGISTRY.register() +class CodeEncodedDataSampleEvaluator(OperatorABC): + """ + CodeEncodedDataSampleEvaluator evaluates code samples based on encoded data patterns + to provide scores for filtering binary content and auto-generated code. + """ + + def __init__(self): + """ + Initialize the operator and set up the logger. + """ + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.score_name = 'CodeEncodedDataScore' + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + """ + Provide operator functionality description and parameter documentation. + """ + if lang == "zh": + return ( + "基于编码数据模式评估代码样本,检测Base64、十六进制和Unicode转义序列。\n\n" + "评估指标:\n" + "- CodeEncodedDataBase64Ratio: Base64编码数据比例\n" + "- CodeEncodedDataHexRatio: 十六进制数据比例\n" + "- CodeEncodedDataUnicodeRatio: Unicode转义序列比例\n" + "- CodeEncodedDataScore: 综合编码数据得分 (0-1,1表示通过编码数据检查)\n\n" + "输入要求:需要包含'text'列\n\n" + "输出参数:\n" + "- CodeEncodedDataBase64Ratio: Base64编码数据比例\n" + "- CodeEncodedDataHexRatio: 十六进制数据比例\n" + "- CodeEncodedDataUnicodeRatio: Unicode转义序列比例\n" + "- CodeEncodedDataScore: 综合编码数据得分" + ) + else: + return ( + "Evaluate code samples based on encoded data patterns, detecting Base64, hexadecimal, and Unicode escape sequences.\n\n" + "Evaluation Metrics:\n" + "- CodeEncodedDataBase64Ratio: Base64 encoded data ratio\n" + "- CodeEncodedDataHexRatio: Hexadecimal data ratio\n" + "- CodeEncodedDataUnicodeRatio: Unicode escape sequence ratio\n" + "- CodeEncodedDataScore: Comprehensive encoded data score (0-1, 1 means passes encoded data checks)\n\n" + "Input Requirement: Requires 'text' column\n\n" + "Output Parameters:\n" + "- CodeEncodedDataBase64Ratio: Base64 encoded data ratio\n" + "- CodeEncodedDataHexRatio: Hexadecimal data ratio\n" + "- CodeEncodedDataUnicodeRatio: Unicode escape sequence ratio\n" + "- CodeEncodedDataScore: Comprehensive encoded data score" + ) + + def _score_func(self, sample): + """ + Calculate encoded data pattern scores for a single code sample. + + Args: + sample: Dictionary containing 'text' key or string + + Returns: + Dictionary containing encoded data scores + """ + if isinstance(sample, str): + text = sample + else: + text = sample.get('text', '') + + # Compile regular expressions for different data patterns + patterns = [ + re.compile(r"[a-zA-Z0-9+/=\n]{64,}"), # Base64 + re.compile(r"(?:\b(?:0x|\\x)?[0-9a-fA-F]{2}(?:,|\b\s*)){8,}"), # Hex + re.compile(r"(?:\\u[0-9a-fA-F]{4}){8,}") # Unicode + ] + + # Calculate ratios for each pattern + base64_ratio = 0.0 + hex_ratio = 0.0 + unicode_ratio = 0.0 + + for i, pattern in enumerate(patterns): + total_match_len = 0 + for match in pattern.finditer(text): + match_len = len(match.group()) + total_match_len += match_len + + ratio = total_match_len / max(1, len(text)) + + if i == 0: # Base64 + base64_ratio = ratio + elif i == 1: # Hex + hex_ratio = ratio + else: # Unicode + unicode_ratio = ratio + + # Calculate comprehensive score (0-1) + score = 1.0 + + # Check if any pattern exceeds thresholds + if base64_ratio > 0.5 or hex_ratio > 0.5 or unicode_ratio > 0.5: + score = 0.0 + + return { + 'CodeEncodedDataBase64Ratio': base64_ratio, + 'CodeEncodedDataHexRatio': hex_ratio, + 'CodeEncodedDataUnicodeRatio': unicode_ratio, + 'CodeEncodedDataScore': score + } + + def eval(self, dataframe, input_key): + """ + Evaluate encoded data patterns for all samples in the dataframe. + + Args: + dataframe: Input DataFrame + input_key: Key containing the sample data + + Returns: + List of score dictionaries + """ + scores_list = [] + self.logger.info(f"Evaluating {self.score_name}...") + + for _, row in dataframe.iterrows(): + text = row[input_key] if isinstance(row[input_key], str) else row[input_key].get('text', '') + scores = self._score_func(text) + scores_list.append(scores) + + self.logger.info("Evaluation complete!") + return scores_list + + def run(self, storage: DataFlowStorage, input_key: str): + """ + Execute encoded data pattern evaluation operation. + + Args: + storage: Data storage object + input_key: Key name for input data + """ + self.input_key = input_key + dataframe = storage.read("dataframe") + self.logger.info("CodeEncodedDataScore ready to evaluate.") + + scores = self.eval(dataframe, input_key) + + # Flatten the nested dictionary of scores into the dataframe + for idx, score_dict in enumerate(scores): + for key, value in score_dict.items(): + dataframe.at[idx, key] = value + + storage.write(dataframe) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/code_length_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/code_length_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..66ed4d8d404f8755c6e773009fc004b8e19aeace --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/code_length_sample_evaluator.py @@ -0,0 +1,151 @@ +import pandas as pd +from typing import List +from tqdm import tqdm + +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC + +@OPERATOR_REGISTRY.register() +class CodeLengthSampleEvaluator(OperatorABC): + """ + CodeLengthSampleEvaluator evaluates code samples based on length characteristics + to provide scores for filtering oversized files and poorly formatted code. + It analyzes total lines, average line length, and maximum line length, + applying different thresholds for different programming languages. + """ + + # List of languages that require special handling (these languages allow longer line lengths) + EXCLUDED_LANGS = { + "HTML", "JSON", "Markdown", "Roff", "Roff Manpage", + "SMT", "TeX", "Text", "XML" + } + + def __init__(self): + """ + Initialize the operator and set up the logger. + """ + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.score_name = 'CodeLengthScore' + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + """ + Provide operator functionality description and parameter documentation. + """ + if lang == "zh": + return ( + "基于代码长度特征评估代码样本,分析总行数、平均行长和最大行长。\n\n" + "评估指标:\n" + "- CodeLengthTotalLines: 总行数\n" + "- CodeLengthAvgLineLength: 平均行长\n" + "- CodeLengthMaxLineLength: 最大行长\n" + "- CodeLengthScore: 综合长度得分 (0-1,1表示通过所有长度检查)\n\n" + "输入要求:需要包含'lines'和'language'列\n\n" + "输出参数:\n" + "- CodeLengthTotalLines: 总行数\n" + "- CodeLengthAvgLineLength: 平均行长\n" + "- CodeLengthMaxLineLength: 最大行长\n" + "- CodeLengthScore: 综合长度得分" + ) + else: + return ( + "Evaluate code samples based on length characteristics, analyzing total lines, average line length, and maximum line length.\n\n" + "Evaluation Metrics:\n" + "- CodeLengthTotalLines: Total number of lines\n" + "- CodeLengthAvgLineLength: Average line length\n" + "- CodeLengthMaxLineLength: Maximum line length\n" + "- CodeLengthScore: Comprehensive length score (0-1, 1 means passes all length checks)\n\n" + "Input Requirement: Requires 'lines' and 'language' columns\n\n" + "Output Parameters:\n" + "- CodeLengthTotalLines: Total number of lines\n" + "- CodeLengthAvgLineLength: Average line length\n" + "- CodeLengthMaxLineLength: Maximum line length\n" + "- CodeLengthScore: Comprehensive length score" + ) + + def _score_func(self, sample): + """ + Calculate length-based scores for a single code sample. + + Args: + sample: Dictionary containing 'lines' and 'language' keys + + Returns: + Dictionary containing length scores + """ + lines = sample.get('lines', []) + language = sample.get('language', '') + + # Calculate basic metrics + n_lines = len(lines) + avg_len = sum(len(l) for l in lines) / max(1, n_lines) + max_len = max((len(l) for l in lines), default=0) + + # Calculate comprehensive score (0-1) + score = 1.0 + + # Check total number of lines + if n_lines > 100_000: + score = 0.0 + + # Apply different rules based on language type + elif language not in self.EXCLUDED_LANGS: + if avg_len > 100 or max_len > 1000: + score = 0.0 + else: + if max_len > 100_000: + score = 0.0 + + return { + 'CodeLengthTotalLines': n_lines, + 'CodeLengthAvgLineLength': avg_len, + 'CodeLengthMaxLineLength': max_len, + 'CodeLengthScore': score + } + + def eval(self, dataframe, input_key): + """ + Evaluate length characteristics for all samples in the dataframe. + + Args: + dataframe: Input DataFrame + input_key: Key containing the sample data + + Returns: + List of score dictionaries + """ + scores_list = [] + self.logger.info(f"Evaluating {self.score_name}...") + + for _, row in dataframe.iterrows(): + sample = row[input_key] if isinstance(row[input_key], dict) else {"lines": row[input_key], "language": "unknown"} + scores = self._score_func(sample) + scores_list.append(scores) + + self.logger.info("Evaluation complete!") + return scores_list + + def run(self, storage: DataFlowStorage, input_key: str): + """ + Execute length evaluation operation. + + Args: + storage: Data storage object + input_key: Key name for input data + """ + self.input_key = input_key + dataframe = storage.read("dataframe") + self.logger.info("CodeLengthScore ready to evaluate.") + + scores = self.eval(dataframe, input_key) + + # Flatten the nested dictionary of scores into the dataframe + for idx, score_dict in enumerate(scores): + for key, value in score_dict.items(): + dataframe.at[idx, key] = value + + storage.write(dataframe) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/code_quality_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/code_quality_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..1c87f95158ca4d5d7ed77ffaedd9f501713c3147 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/code_quality_sample_evaluator.py @@ -0,0 +1,195 @@ +import pandas as pd +import re +from typing import List, Tuple + +# Assuming these are the correct import paths for your framework +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +from dataflow.core.prompt import prompt_restrict, DIYPromptABC +from dataflow.prompts.code import CodeQualityEvaluatorPrompt, DiyCodePrompt + +from typing import Union +@prompt_restrict( + CodeQualityEvaluatorPrompt, + DiyCodePrompt +) +@OPERATOR_REGISTRY.register() +class CodeQualitySampleEvaluator(OperatorABC): + """ + CodeQualitySampleEvaluator is an operator that evaluates the quality of a generated code snippet + against its source instruction. It uses an LLM to provide both a numerical score + and textual feedback, acting as an automated code reviewer. + """ + + def __init__(self, llm_serving: LLMServingABC, prompt_template: Union[CodeQualityEvaluatorPrompt, DiyCodePrompt, DIYPromptABC] = None): + """ + Initializes the operator with a language model serving endpoint. + """ + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.llm_serving = llm_serving + self.score_name = 'CodeQualityScore' + + # Initialize prompt template + if prompt_template is None: + prompt_template = CodeQualityEvaluatorPrompt() + elif isinstance(prompt_template, str): + prompt_template = DiyCodePrompt(prompt_template) + self.prompt_template = prompt_template + + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "en"): + """ + Provides a description of the operator's function and parameters. + """ + if lang == "zh": + return ( + "该算子用于评估生成的代码片段与其源指令的匹配质量,并输出分数和反馈。\n\n" + "输入参数:\n" + "- input_instruction_key: 包含人类指令的字段名 (默认: 'generated_instruction')\n" + "- input_code_key: 包含生成代码的字段名 (默认: 'generated_code')\n" + "输出参数:\n" + "- output_score_key: 用于存储质量分数的字段名 (默认: 'quality_score')\n" + "- output_feedback_key: 用于存储质量反馈的字段名 (默认: 'quality_feedback')\n" + ) + else: # Default to English + return ( + "This operator evaluates the quality of a generated code snippet against its source instruction, providing a score and feedback.\n\n" + "Input Parameters:\n" + "- input_instruction_key: Field name containing the human instruction (default: 'generated_instruction')\n" + "- input_code_key: Field name containing the generated code (default: 'generated_code')\n" + "Output Parameters:\n" + "- output_score_key: Field name to store the quality score (default: 'quality_score')\n" + "- output_feedback_key: Field name to store the quality feedback (default: 'quality_feedback')\n" + ) + + def _validate_dataframe(self, dataframe: pd.DataFrame): + """ + Validates the DataFrame to ensure required columns exist and output columns don't. + """ + required_keys = [self.input_key] + forbidden_keys = [self.output_score_key, self.output_feedback_key] + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + raise ValueError(f"Missing required column(s) for CodeQualitySampleEvaluator: {missing}") + if conflict: + raise ValueError(f"The following column(s) already exist and would be overwritten by CodeQualitySampleEvaluator: {conflict}") + + def _build_prompts(self, dataframe: pd.DataFrame, input_instruction_key: str, input_code_key: str) -> List[str]: + """ + Build prompts for all instruction-code pairs in the dataframe. + + Args: + dataframe: Input DataFrame + input_instruction_key: Field name containing instructions + input_code_key: Field name containing code + + Returns: + List of prompt strings + """ + prompts = [] + for _, row in dataframe.iterrows(): + instruction = row[input_instruction_key] + code = row[input_code_key] + prompt = self.prompt_template.build_prompt(instruction=instruction, code=code) + prompts.append(prompt) + return prompts + + def _parse_score_and_feedback(self, response: str) -> Tuple[int, str]: + """ + Parse the LLM's raw response to extract the score and feedback. + Handles potential formatting errors gracefully. + + Args: + response: Raw response string from the LLM + + Returns: + Tuple of (score, feedback) where score is an integer and feedback is a string + """ + try: + score_match = re.search(r"Score:\s*(\d+)", response) + feedback_match = re.search(r"Feedback:\s*(.*)", response, re.DOTALL) + + score = int(score_match.group(1)) if score_match else 0 + feedback = feedback_match.group(1).strip() if feedback_match else "No feedback provided." + + return score, feedback + except (AttributeError, ValueError, IndexError): + # If parsing fails for any reason, return default error values + self.logger.warning(f"Failed to parse LLM evaluation output: '{response}'") + return 0, "Failed to parse LLM evaluation output." + + def eval(self, dataframe: pd.DataFrame, input_instruction_key: str, input_code_key: str) -> Tuple[List[int], List[str]]: + """ + Evaluate instruction-code pairs and return scores and feedbacks. + + Args: + dataframe: Input DataFrame + input_instruction_key: Field name containing instructions + input_code_key: Field name containing code + + Returns: + Tuple of (scores, feedbacks) lists + """ + self.logger.info(f"Evaluating {self.score_name}...") + + # Build all prompts at once + prompts = self._build_prompts(dataframe, input_instruction_key, input_code_key) + + # Generate responses in batch + responses = self.llm_serving.generate_from_input(user_inputs=prompts, system_prompt="") + + if not responses or len(responses) == 0: + self.logger.warning("Empty response from LLM") + scores = [0] * len(dataframe) + feedbacks = ["No response from LLM"] * len(dataframe) + elif len(responses) != len(dataframe): + self.logger.warning(f"Response count ({len(responses)}) doesn't match dataframe length ({len(dataframe)})") + scores = [0] * len(dataframe) + feedbacks = ["Response count mismatch"] * len(dataframe) + else: + # Parse all responses + results = [self._parse_score_and_feedback(response) for response in responses] + scores, feedbacks = zip(*results) + scores = list(scores) + feedbacks = list(feedbacks) + + self.logger.info("Evaluation complete!") + return scores, feedbacks + + def run( + self, + storage: DataFlowStorage, + input_instruction_key: str, + input_code_key: str, + output_score_key: str = "quality_score", + output_feedback_key: str = "quality_feedback" + ): + """ + Executes the scoring process for instruction-code pairs. + + Args: + storage: Data storage object + input_key: Field name containing instruction-code pairs + output_score_key: Field name for quality scores + output_feedback_key: Field name for quality feedback + """ + self.input_instruction_key = input_instruction_key + self.input_code_key = input_code_key + self.output_score_key = output_score_key + self.output_feedback_key = output_feedback_key + + dataframe = storage.read("dataframe") + scores, feedbacks = self.eval(dataframe, input_instruction_key, input_code_key) + + dataframe[self.output_score_key] = scores + dataframe[self.output_feedback_key] = feedbacks + storage.write(dataframe) \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/code_sandbox_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/code_sandbox_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..2158e6bd6b1c1ff8644f50e46385660f6c715a14 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/code_sandbox_sample_evaluator.py @@ -0,0 +1,190 @@ +import pandas as pd +from typing import List, Tuple + +# Assuming these are the correct import paths for your framework +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC + +# Import the provided executor script +# Assuming shared_vis_python_exe.py is in the same directory or accessible via PYTHONPATH +from .python_executor import PythonExecutor + +@OPERATOR_REGISTRY.register() +class CodeSandboxSampleEvaluator(OperatorABC): + """ + CodeSandboxSampleEvaluator is an operator that executes code snippets in a secure, + isolated environment to verify their correctness. It leverages a robust + PythonExecutor to handle process isolation, timeouts, and capturing results. + This is the final validation step in the data synthesis pipeline. + """ + + def __init__(self, language: str = "python", timeout_length: int = 15, use_process_isolation: bool = True): + """ + Initializes the operator and the underlying PythonExecutor. + + Args: + timeout_length: Maximum execution time in seconds for each code snippet. + use_process_isolation: Whether to run code in a separate process for security. Recommended to keep True. + """ + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + # Initialize the PythonExecutor here. It will be reused for all code snippets. + self.executor = PythonExecutor( + get_answer_from_stdout=True, # Capture print statements as primary output + timeout_length=timeout_length, + use_process_isolation=use_process_isolation + ) + self.score_name = 'SandboxValidationScore' + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "en"): + """ + Provides a description of the operator's function and parameters. + """ + if lang == "zh": + return ( + "该算子在一个安全的沙箱环境中执行代码片段以验证其正确性。\n\n" + "输入参数:\n" + "- input_code_key: 包含待执行代码的字段名 (默认: 'generated_code')\n" + "输出参数:\n" + "- output_status_key: 用于存储执行状态 ('PASS' 或 'FAIL') 的字段名 (默认: 'sandbox_status')\n" + "- output_log_key: 用于存储执行日志或错误信息的字段名 (默认: 'sandbox_log')\n" + ) + else: # Default to English + return ( + "This operator executes code snippets in a secure sandbox environment to verify their correctness.\n\n" + "Input Parameters:\n" + "- input_code_key: Field name containing the code to be executed (default: 'generated_code')\n" + "Output Parameters:\n" + "- output_status_key: Field name to store the execution status ('PASS' or 'FAIL') (default: 'sandbox_status')\n" + "- output_log_key: Field name to store the execution log or error message (default: 'sandbox_log')\n" + ) + + def _validate_dataframe(self, dataframe: pd.DataFrame): + """ + Validates the DataFrame to ensure the required code column exists and output columns don't. + """ + required_keys = [self.input_key] + forbidden_keys = [self.output_status_key, self.output_log_key] + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + raise ValueError(f"Missing required column(s) for CodeSandboxSampleEvaluator: {missing}") + if conflict: + raise ValueError(f"The following column(s) already exist and would be overwritten by CodeSandboxSampleEvaluator: {conflict}") + + def _score_func(self, code: str) -> Tuple[str, str]: + """ + Execute a single code snippet and return status and log. + + Args: + code: Code snippet to execute + + Returns: + Tuple of (status, log) where status is 'PASS' or 'FAIL' + """ + try: + result, report = self.executor.execute([code], messages=[]) + + if report == "Done": + status = "PASS" + log = result.get('text', '') if isinstance(result, dict) else str(result) + else: + status = "FAIL" + log = report + + return status, log + except Exception as e: + return "FAIL", f"Execution error: {str(e)}" + + def _execute_code_batch(self, code_list: List[str]) -> List[Tuple[str, str]]: + """ + Execute a batch of code snippets using the PythonExecutor. + + Args: + code_list: A list of strings, where each string is a code snippet. + + Returns: + A list of tuples, where each tuple contains (status, log). + Status can be 'PASS' or 'FAIL', log contains execution output or error message. + """ + # The executor's batch_apply takes a list of code strings and a 'messages' context. + # For our simple validation, the context can be an empty list. + results_with_reports = self.executor.batch_apply(code_list, messages=[]) + + processed_results = [] + for (result, report) in results_with_reports: + # The executor's report tells us about success or failure. + # "Done" indicates success. Anything else (e.g., "Error: ...", "Timeout Error") indicates failure. + if report == "Done": + status = "PASS" + # The 'result' can be a dict with 'text' and/or 'images'. We just need the text log. + log = result.get('text', '') if isinstance(result, dict) else result + else: + status = "FAIL" + # The report itself is the most informative log on failure. + log = report + + processed_results.append((status, log)) + + return processed_results + + def eval(self, dataframe: pd.DataFrame, input_key: str) -> Tuple[List[str], List[str]]: + """ + Execute code snippets and return statuses and logs. + + Args: + dataframe: Input DataFrame + input_key: Field name containing code snippets + + Returns: + Tuple of (statuses, logs) lists + """ + self.logger.info(f"Evaluating {self.score_name}...") + + code_list = dataframe[input_key].tolist() + execution_results = self._execute_code_batch(code_list) + + statuses, logs = zip(*execution_results) + self.logger.info("Evaluation complete!") + return list(statuses), list(logs) + + def run( + self, + storage: DataFlowStorage, + input_key: str, + output_status_key: str = "sandbox_status", + output_log_key: str = "sandbox_log" + ): + """ + Executes the sandbox validation process. + + Args: + storage: Data storage object + input_key: Field name containing code snippets + output_status_key: Field name for execution status + output_log_key: Field name for execution logs + """ + self.input_key = input_key + self.output_status_key = output_status_key + self.output_log_key = output_log_key + + dataframe = storage.read("dataframe") + statuses, logs = self.eval(dataframe, input_key) + + dataframe[self.output_status_key] = statuses + dataframe[self.output_log_key] = logs + storage.write(dataframe) + + def __del__(self): + """ + Ensures the executor's resources are cleaned up when the operator is destroyed. + """ + if hasattr(self, 'executor') and self.executor: + # The executor's __del__ method handles terminating the worker process. + del self.executor \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/code_text_composition_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/code_text_composition_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..950900d7aa0fad11069f5736cab3b4df6dfa8635 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/code_text_composition_sample_evaluator.py @@ -0,0 +1,138 @@ +import pandas as pd +from typing import Dict +from tqdm import tqdm + +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC + +@OPERATOR_REGISTRY.register() +class CodeTextCompositionSampleEvaluator(OperatorABC): + """ + CodeTextCompositionSampleEvaluator evaluates code samples based on character composition + to provide scores for filtering binary files, encrypted content, and other non-readable text. + It analyzes the ratio of alphabetic and alphanumeric characters to ensure readable content. + """ + + # List of languages that require special handling + SPECIAL_LANGS = {"Motorola 68K Assembly", "WebAssembly"} + + def __init__(self): + """ + Initialize the operator and set up the logger. + """ + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.score_name = 'CodeTextCompositionScore' + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + """ + Provide operator functionality description and parameter documentation. + """ + if lang == "zh": + return ( + "基于字符组成评估代码样本,分析字母字符和字母数字字符的比例。\n\n" + "评估指标:\n" + "- CodeTextCompositionAlphaRatio: 字母字符比例\n" + "- CodeTextCompositionAlnumRatio: 字母数字字符比例\n" + "- CodeTextCompositionScore: 综合字符组成得分 (0-1,1表示通过字符组成检查)\n\n" + "输入要求:需要包含'text'和'language'列\n\n" + "输出参数:\n" + "- CodeTextCompositionAlphaRatio: 字母字符比例\n" + "- CodeTextCompositionAlnumRatio: 字母数字字符比例\n" + "- CodeTextCompositionScore: 综合字符组成得分" + ) + else: + return ( + "Evaluate code samples based on character composition, analyzing ratios of alphabetic and alphanumeric characters.\n\n" + "Evaluation Metrics:\n" + "- CodeTextCompositionAlphaRatio: Alphabetic character ratio\n" + "- CodeTextCompositionAlnumRatio: Alphanumeric character ratio\n" + "- CodeTextCompositionScore: Comprehensive composition score (0-1, 1 means passes composition checks)\n\n" + "Input Requirement: Requires 'text' and 'language' columns\n\n" + "Output Parameters:\n" + "- CodeTextCompositionAlphaRatio: Alphabetic character ratio\n" + "- CodeTextCompositionAlnumRatio: Alphanumeric character ratio\n" + "- CodeTextCompositionScore: Comprehensive composition score" + ) + + def _score_func(self, sample): + """ + Calculate composition-based scores for a single code sample. + + Args: + sample: Dictionary containing 'text' and 'language' keys + + Returns: + Dictionary containing composition scores + """ + text = sample.get('text', '') + language = sample.get('language', '') + + # Calculate character ratios + alpha_ratio = sum(c.isalpha() for c in text) / max(1, len(text)) + alnum_ratio = sum(c.isalnum() for c in text) / max(1, len(text)) + + # Calculate comprehensive score (0-1) + score = 1.0 + + if language in self.SPECIAL_LANGS: + # For assembly languages, check alphanumeric character ratio + if alnum_ratio < 0.25: + score = 0.0 + else: + # For normal languages, check alphabetic character ratio + if alpha_ratio < 0.25: + score = 0.0 + + return { + 'CodeTextCompositionAlphaRatio': alpha_ratio, + 'CodeTextCompositionAlnumRatio': alnum_ratio, + 'CodeTextCompositionScore': score + } + + def eval(self, dataframe, input_key): + """ + Evaluate character composition for all samples in the dataframe. + + Args: + dataframe: Input DataFrame + input_key: Key containing the sample data + + Returns: + List of score dictionaries + """ + scores_list = [] + self.logger.info(f"Evaluating {self.score_name}...") + + for _, row in dataframe.iterrows(): + sample = row[input_key] if isinstance(row[input_key], dict) else {"text": row[input_key], "language": "unknown"} + scores = self._score_func(sample) + scores_list.append(scores) + + self.logger.info("Evaluation complete!") + return scores_list + + def run(self, storage: DataFlowStorage, input_key: str): + """ + Execute character composition evaluation operation. + + Args: + storage: Data storage object + input_key: Key name for input data + """ + self.input_key = input_key + dataframe = storage.read("dataframe") + self.logger.info("CodeTextCompositionScore ready to evaluate.") + + scores = self.eval(dataframe, input_key) + + # Flatten the nested dictionary of scores into the dataframe + for idx, score_dict in enumerate(scores): + for key, value in score_dict.items(): + dataframe.at[idx, key] = value + + storage.write(dataframe) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/python_executor.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/python_executor.py new file mode 100644 index 0000000000000000000000000000000000000000..2ddc0c860a578a2378b4fdd716c3ff079c54aad8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/eval/python_executor.py @@ -0,0 +1,675 @@ +# This code is referenced from PyVision: Agentic Vision with Dynamic Tooling +# GitHub: https://github.com/agents-x-project/PyVision +# Paper: PyVision: Agentic Vision with Dynamic Tooling (arXiv:2507.07998) + +import os +import io +import regex +import pickle +import traceback +import copy +import datetime +import dateutil.relativedelta +import multiprocessing +from multiprocessing import Queue, Process +from typing import Any, Dict, Optional, Tuple, List, Union +from tqdm import tqdm +from concurrent.futures import TimeoutError, ThreadPoolExecutor, Future +from contextlib import redirect_stdout +import base64 +from io import BytesIO +from PIL import Image +import threading +try: + import matplotlib + matplotlib.use('Agg') + import matplotlib.pyplot as plt + MATPLOTLIB_AVAILABLE = True +except ImportError: + MATPLOTLIB_AVAILABLE = False + plt = None +import numpy as np +import time +import queue + +def encode_image(image_path): + """Encode an image file to base64 string.""" + with open(image_path, "rb") as image_file: + return base64.b64encode(image_file.read()).decode('utf-8') + +def base64_to_image( + base64_str: str, + remove_prefix: bool = True, + convert_mode: Optional[str] = "RGB" +) -> Union[Image.Image, None]: + """ + Convert a Base64-encoded image string to a PIL Image object. + + Args: + base64_str: Base64-encoded image string (can include data: prefix) + remove_prefix: Whether to automatically remove the "data:image/..." prefix (default True) + convert_mode: Convert to the specified mode (such as "RGB"/"RGBA", None means no conversion) + + Returns: + PIL.Image.Image object, or None if decoding fails + + Examples: + >>> img = base64_to_image("data:image/png;base64,iVBORw0KGg...") + >>> img = base64_to_image("iVBORw0KGg...", remove_prefix=False) + """ + try: + # 1. Handle Base64 prefix + if remove_prefix and "," in base64_str: + base64_str = base64_str.split(",")[1] + + # 2. Decode Base64 + image_data = base64.b64decode(base64_str) + + # 3. Convert to PIL Image + image = Image.open(BytesIO(image_data)) + + # 4. Optional mode conversion + if convert_mode: + image = image.convert(convert_mode) + + return image + + except (base64.binascii.Error, OSError, Exception) as e: + print(f"Base64 decode failed: {str(e)}") + return None + + +class PersistentWorker: + """Persistent worker process.""" + + # Runtime class registry for pickle-safe serialization + RUNTIME_REGISTRY = { + 'ImageRuntime': None, # Will be set later to avoid circular import + 'DateRuntime': None, + 'ColorObjectRuntime': None, + 'GenericRuntime': None, + } + + @classmethod + def _get_runtime_class(cls, runtime_identifier): + """Get runtime class from identifier (class name or class object).""" + if isinstance(runtime_identifier, str): + # String identifier - look up in registry + if runtime_identifier in cls.RUNTIME_REGISTRY: + return cls.RUNTIME_REGISTRY[runtime_identifier] + else: + # Default to ImageRuntime if not found + return cls.RUNTIME_REGISTRY.get('ImageRuntime', ImageRuntime) + elif isinstance(runtime_identifier, type): + # Class object - get its name and look up + class_name = runtime_identifier.__name__ + return cls.RUNTIME_REGISTRY.get(class_name, runtime_identifier) + else: + # Default fallback + return cls.RUNTIME_REGISTRY.get('ImageRuntime', ImageRuntime) + + @classmethod + def _get_runtime_identifier(cls, runtime_class): + """Convert runtime class to pickle-safe identifier.""" + if runtime_class is None: + return 'ImageRuntime' + elif isinstance(runtime_class, str): + return runtime_class + else: + return runtime_class.__name__ + + def __init__(self): + self.input_queue = multiprocessing.Queue() + self.output_queue = multiprocessing.Queue() + self.process = None + self.start() + + def start(self): + """Start the worker process.""" + self.process = Process(target=self._worker_loop) + self.process.daemon = True + self.process.start() + + def _execute_code_with_timeout(self, runtime, code, get_answer_from_stdout, answer_symbol, answer_expr, timeout): + """Execute code with timeout protection using thread pool.""" + def _run_code(): + # Record the number of images before execution + pre_figures_count = len(runtime._global_vars.get("_captured_figures", [])) + + if get_answer_from_stdout: + program_io = io.StringIO() + with redirect_stdout(program_io): + runtime.exec_code("\n".join(code)) + program_io.seek(0) + result = program_io.read() + elif answer_symbol: + runtime.exec_code("\n".join(code)) + result = runtime._global_vars.get(answer_symbol, "") + elif answer_expr: + runtime.exec_code("\n".join(code)) + result = runtime.eval_code(answer_expr) + else: + if len(code) > 1: + runtime.exec_code("\n".join(code[:-1])) + result = runtime.eval_code(code[-1]) + else: + runtime.exec_code("\n".join(code)) + result = "" + + # Get newly generated images + all_figures = runtime._global_vars.get("_captured_figures", []) + new_figures = all_figures[pre_figures_count:] + + # Prevent unbounded growth when the runtime is reused across multiple executions. + # We keep the pre-existing figures (e.g., injected/initial figures) and discard + # the newly captured ones after returning them in this response. + if new_figures and isinstance(all_figures, list): + runtime._global_vars["_captured_figures"] = all_figures[:pre_figures_count] + + # Build result + if new_figures: + result = { + 'text': result, + 'images': new_figures + } if result else {'images': new_figures} + else: + result = {'text': result} if result else {} + + return result + + # Use thread pool executor with timeout + with ThreadPoolExecutor(max_workers=1) as executor: + future = executor.submit(_run_code) + try: + result = future.result(timeout=timeout) + return result, None + except TimeoutError: + # Cancel the future (though it may still be running) + future.cancel() + # Note: The thread may still be running, but we've returned control + raise TimeoutError(f"Code execution exceeded timeout of {timeout} seconds") + + def _worker_loop(self): + """Main loop for the worker process.""" + runtime = None + runtime_class = None + + while True: + try: + # Get task + task = self.input_queue.get() + + if task is None: # Termination signal + break + + task_type = task.get('type') + + if task_type == 'init': + # Initialize runtime + messages = task.get('messages', []) + runtime_identifier = task.get('runtime_class', 'ImageRuntime') + runtime_class = self._get_runtime_class(runtime_identifier) + runtime = runtime_class(messages) + self.output_queue.put({ + 'status': 'success', + 'result': 'Initialized' + }) + + elif task_type == 'execute': + # Execute code + if runtime is None: + messages = task.get('messages', []) + runtime_identifier = task.get('runtime_class', 'ImageRuntime') + runtime_class = self._get_runtime_class(runtime_identifier) + runtime = runtime_class(messages) + + code = task.get('code') + get_answer_from_stdout = task.get('get_answer_from_stdout', True) + answer_symbol = task.get('answer_symbol') + answer_expr = task.get('answer_expr') + timeout = task.get('timeout', 30) + + try: + # Execute with timeout protection + result, _ = self._execute_code_with_timeout( + runtime, code, get_answer_from_stdout, answer_symbol, answer_expr, timeout + ) + + self.output_queue.put({ + 'status': 'success', + 'result': result, + 'report': 'Done' + }) + + except TimeoutError as e: + # Timeout occurred - return error but continue processing + self.output_queue.put({ + 'status': 'error', + 'error': str(e), + 'traceback': traceback.format_exc(), + 'report': 'Timeout Error' + }) + except Exception as e: + self.output_queue.put({ + 'status': 'error', + 'error': str(e), + 'traceback': traceback.format_exc(), + 'report': f'Error: {str(e)}' + }) + + elif task_type == 'reset': + # Reset runtime + messages = task.get('messages', []) + runtime_identifier = task.get('runtime_class', 'ImageRuntime') + runtime_class = self._get_runtime_class(runtime_identifier) + runtime = runtime_class(messages) + self.output_queue.put({ + 'status': 'success', + 'result': 'Reset' + }) + + except Exception as e: + self.output_queue.put({ + 'status': 'error', + 'error': f'Worker error: {str(e)}', + 'traceback': traceback.format_exc() + }) + + def execute(self, code: List[str], messages: list = None, runtime_class=None, + get_answer_from_stdout=True, answer_symbol=None, answer_expr=None, timeout: int = 30): + """Execute code.""" + # Convert runtime class to pickle-safe identifier + runtime_identifier = self._get_runtime_identifier(runtime_class) + self.input_queue.put({ + 'type': 'execute', + 'code': code, + 'messages': messages, + 'runtime_class': runtime_identifier, + 'get_answer_from_stdout': get_answer_from_stdout, + 'answer_symbol': answer_symbol, + 'answer_expr': answer_expr, + 'timeout': timeout + }) + + try: + # Add extra buffer time for queue communication + result = self.output_queue.get(timeout=timeout + 5) + return result + except queue.Empty: + return { + 'status': 'error', + 'error': 'Execution timeout (queue timeout)', + 'report': 'Timeout Error' + } + + def init_runtime(self, messages: list, runtime_class=None): + """Initialize runtime.""" + # Convert runtime class to pickle-safe identifier + runtime_identifier = self._get_runtime_identifier(runtime_class) + self.input_queue.put({ + 'type': 'init', + 'messages': messages, + 'runtime_class': runtime_identifier + }) + return self.output_queue.get() + + def reset_runtime(self, messages: list = None, runtime_class=None): + """Reset runtime.""" + # Convert runtime class to pickle-safe identifier + runtime_identifier = self._get_runtime_identifier(runtime_class) + self.input_queue.put({ + 'type': 'reset', + 'messages': messages, + 'runtime_class': runtime_identifier + }) + return self.output_queue.get() + + def terminate(self): + """Terminate the worker process.""" + if self.process and self.process.is_alive(): + self.input_queue.put(None) + self.process.join(timeout=5) + if self.process.is_alive(): + self.process.terminate() + + +class GenericRuntime: + GLOBAL_DICT = {} + LOCAL_DICT = None + HEADERS = [] + + def __init__(self): + self._global_vars = copy.copy(self.GLOBAL_DICT) + self._local_vars = copy.copy(self.LOCAL_DICT) if self.LOCAL_DICT else None + self._captured_figures = [] + + for c in self.HEADERS: + self.exec_code(c) + + def exec_code(self, code_piece: str) -> None: + # Detect and modify plt.show() calls + if "plt.show()" in code_piece and MATPLOTLIB_AVAILABLE: + modified_code = code_piece.replace("plt.show()", """ +# Capture current figure +buf = io.BytesIO() +plt.savefig(buf, format='png') +buf.seek(0) +_captured_image = base64.b64encode(buf.read()).decode('utf-8') +_captured_figures.append(_captured_image) +plt.close() +""") + # Ensure _captured_figures variable exists + if "_captured_figures" not in self._global_vars: + self._global_vars["_captured_figures"] = [] + + exec(modified_code, self._global_vars) + else: + exec(code_piece, self._global_vars) + + def eval_code(self, expr: str) -> Any: + return eval(expr, self._global_vars) + + def inject(self, var_dict: Dict[str, Any]) -> None: + for k, v in var_dict.items(): + self._global_vars[k] = v + + @property + def answer(self): + return self._global_vars.get("answer", None) + + @property + def captured_figures(self): + return self._global_vars.get("_captured_figures", []) + + +class ImageRuntime(GenericRuntime): + HEADERS = [ + """try: + import matplotlib + matplotlib.use('Agg') + import matplotlib.pyplot as plt + MATPLOTLIB_AVAILABLE = True +except ImportError: + MATPLOTLIB_AVAILABLE = False + plt = None +""", + "from PIL import Image", + "import io", + "import base64", + "import numpy as np", + "_captured_figures = []", # Initialize image capture list + ] + + def __init__(self, messages): + super().__init__() + + image_var_dict = {} + image_var_idx = 0 + init_captured_figures = [] + + for message_item in messages: + content = message_item['content'] + for item in content: + if isinstance(item, dict): + item_type = item.get('type') + if item_type == "image_url": + item_image_url = item['image_url']['url'] + image = base64_to_image(item_image_url) + if image: + image_var_dict[f"image_clue_{image_var_idx}"] = image + init_captured_figures.append(base64.b64encode( + BytesIO(image.tobytes()).getvalue()).decode('utf-8')) + image_var_idx += 1 + + image_var_dict["_captured_figures"] = init_captured_figures + self.inject(image_var_dict) + + +class DateRuntime(GenericRuntime): + GLOBAL_DICT = {} + HEADERS = [ + "import datetime", + "from dateutil.relativedelta import relativedelta", + "timedelta = relativedelta" + ] + + +class CustomDict(dict): + def __iter__(self): + return list(super().__iter__()).__iter__() + + +class ColorObjectRuntime(GenericRuntime): + GLOBAL_DICT = {"dict": CustomDict} + + +class PythonExecutor: + def __init__( + self, + runtime_class=None, + get_answer_symbol: Optional[str] = None, + get_answer_expr: Optional[str] = None, + get_answer_from_stdout: bool = True, + timeout_length: int = 20, + use_process_isolation: bool = True, + ) -> None: + self.runtime_class = runtime_class if runtime_class else ImageRuntime + self.answer_symbol = get_answer_symbol + self.answer_expr = get_answer_expr + self.get_answer_from_stdout = get_answer_from_stdout + self.timeout_length = timeout_length + self.use_process_isolation = use_process_isolation + self.persistent_worker = None + + def _ensure_worker(self): + """Ensure the worker process exists and is healthy.""" + if self.persistent_worker is None: + self.persistent_worker = PersistentWorker() + elif self.persistent_worker.process is not None and not self.persistent_worker.process.is_alive(): + # Worker process died, restart it + try: + self.persistent_worker.terminate() + except: + pass + self.persistent_worker = PersistentWorker() + + def _restart_worker(self): + """Force restart the worker process.""" + if self.persistent_worker is not None: + try: + self.persistent_worker.terminate() + except: + pass + self.persistent_worker = PersistentWorker() + + def process_generation_to_code(self, gens: str): + return [g.split("\n") for g in gens] + + def execute( + self, + code, + messages, + get_answer_from_stdout=True, + runtime_class=None, + answer_symbol=None, + answer_expr=None, + ) -> Tuple[Union[str, Dict[str, Any]], str]: + + if self.use_process_isolation: + # Ensure worker process exists + self._ensure_worker() + + # Execute code + result = self.persistent_worker.execute( + code, + messages, + runtime_class or self.runtime_class, + get_answer_from_stdout, + answer_symbol, + answer_expr, + timeout=self.timeout_length + ) + + if result['status'] == 'success': + return result['result'], result.get('report', 'Done') + else: + error_result = { + 'error': result.get('error', 'Unknown error'), + 'traceback': result.get('traceback', '') + } + return error_result, result.get('report', f"Error: {result.get('error', 'Unknown error')}") + else: + # Non-isolation mode (for backward compatibility) + runtime = runtime_class(messages) if runtime_class else self.runtime_class(messages) + + try: + if get_answer_from_stdout: + program_io = io.StringIO() + with redirect_stdout(program_io): + runtime.exec_code("\n".join(code)) + program_io.seek(0) + result = program_io.read() + elif answer_symbol: + runtime.exec_code("\n".join(code)) + result = runtime._global_vars.get(answer_symbol, "") + elif answer_expr: + runtime.exec_code("\n".join(code)) + result = runtime.eval_code(answer_expr) + else: + if len(code) > 1: + runtime.exec_code("\n".join(code[:-1])) + result = runtime.eval_code(code[-1]) + else: + runtime.exec_code("\n".join(code)) + result = "" + + # Check for captured figures + captured_figures = runtime.captured_figures + if captured_figures: + result = { + 'text': result, + 'images': captured_figures + } if result else {'images': captured_figures} + else: + result = {'text': result} if result else {} + + report = "Done" + + except Exception as e: + result = { + 'error': str(e), + 'traceback': traceback.format_exc() + } + report = f"Error: {str(e)}" + + return result, report + + def apply(self, code, messages): + return self.batch_apply([code], messages)[0] + + @staticmethod + def truncate(s, max_length=400): + if isinstance(s, dict): + # If it is a dict (with images), truncate only the text part + if 'text' in s: + half = max_length // 2 + if len(s['text']) > max_length: + s['text'] = s['text'][:half] + "..." + s['text'][-half:] + return s + else: + half = max_length // 2 + if isinstance(s, str) and len(s) > max_length: + s = s[:half] + "..." + s[-half:] + return s + + def batch_apply(self, batch_code, messages): + """ + Execute a batch of code snippets. + + Args: + batch_code: List of code strings to execute + messages: Context messages for execution + """ + all_code_snippets = self.process_generation_to_code(batch_code) + + all_exec_results = [] + + if len(all_code_snippets) > 100: + progress_bar = tqdm(total=len(all_code_snippets), desc="Execute") + else: + progress_bar = None + + for idx, code in enumerate(all_code_snippets): + try: + result = self.execute( + code, + messages=messages, + get_answer_from_stdout=self.get_answer_from_stdout, + runtime_class=self.runtime_class, + answer_symbol=self.answer_symbol, + answer_expr=self.answer_expr, + ) + self._restart_worker() + + all_exec_results.append(result) + except TimeoutError as error: + print(error) + all_exec_results.append(("", "Timeout Error")) + self._restart_worker() + + # If timeout occurs, try resetting runtime to recover + if self.use_process_isolation and self.persistent_worker: + try: + self.reset(messages) + except Exception: + # If reset fails, try restarting worker + try: + self._restart_worker() + except: + pass + except Exception as error: + print(f"Error in batch_apply: {error}") + all_exec_results.append(("", f"Error: {str(error)}")) + self._restart_worker() + + if progress_bar is not None: + progress_bar.update(1) + + if progress_bar is not None: + progress_bar.close() + + batch_results = [] + for code, (res, report) in zip(all_code_snippets, all_exec_results): + # Handle results + if isinstance(res, dict): + # If result contains images, special handling + if 'text' in res: + res['text'] = str(res['text']).strip() + res['text'] = self.truncate(res['text']) + report = str(report).strip() + report = self.truncate(report) + else: + # Normal text result + res = str(res).strip() + res = self.truncate(res) + report = str(report).strip() + report = self.truncate(report) + batch_results.append((res, report)) + return batch_results + + def reset(self, messages=None): + """Reset executor state.""" + if self.use_process_isolation and self.persistent_worker: + self.persistent_worker.reset_runtime(messages, self.runtime_class) + + def __del__(self): + """Clean up resources.""" + if self.persistent_worker: + self.persistent_worker.terminate() + + +# Initialize runtime registry after all classes are defined +PersistentWorker.RUNTIME_REGISTRY['ImageRuntime'] = ImageRuntime +PersistentWorker.RUNTIME_REGISTRY['DateRuntime'] = DateRuntime +PersistentWorker.RUNTIME_REGISTRY['ColorObjectRuntime'] = ColorObjectRuntime +PersistentWorker.RUNTIME_REGISTRY['GenericRuntime'] = GenericRuntime \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/__pycache__/code_autogen_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/__pycache__/code_autogen_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6cbce2d6107896d15dc334cf695bfabe508f68b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/__pycache__/code_autogen_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/__pycache__/code_doc_quality_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/__pycache__/code_doc_quality_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ed0656afd4768a82a361498648ab32eed74495b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/__pycache__/code_doc_quality_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/__pycache__/code_encoded_data_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/__pycache__/code_encoded_data_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..adb20d4854d140ae546fdb0e6ef73cfe712f7755 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/__pycache__/code_encoded_data_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/__pycache__/code_file_type_content_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/__pycache__/code_file_type_content_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..113d348e733fdfd019fe64bd4eb65ca8e41b54d3 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/__pycache__/code_file_type_content_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/__pycache__/code_length_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/__pycache__/code_length_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57e8ae510de11b28a27546a0a7338b60c1d7b1d0 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/__pycache__/code_length_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/__pycache__/code_quality_score_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/__pycache__/code_quality_score_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5af157dc0002c43e7b5d57a4f90e420abe715a64 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/__pycache__/code_quality_score_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/__pycache__/code_score_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/__pycache__/code_score_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0597280f0d2580e2c881d4634db1330463485709 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/__pycache__/code_score_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/__pycache__/code_text_composition_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/__pycache__/code_text_composition_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..306cd8fea3bca1195eac32d1883b7836cae1aa8b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/__pycache__/code_text_composition_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/code_autogen_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/code_autogen_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..93807168191f866da23b25aaa265e35a83a8b4d4 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/code_autogen_filter.py @@ -0,0 +1,128 @@ +import pandas as pd +import numpy as np +from typing import List, Callable, Optional + +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.operators.code import CodeAutoGeneratedSampleEvaluator + +@OPERATOR_REGISTRY.register() +class CodeAutoGeneratedFilter(OperatorABC): + """ + CodeAutoGeneratedFilter filters auto-generated code files using + CodeAutoGeneratedSampleEvaluator scores to ensure only human-written code is retained. + """ + + def __init__(self, min_score: float = 1.0, max_score: float = 1.0, is_generated_func: Optional[Callable[[], bool]] = None): + """ + Initialize the operator with evaluator and thresholds. + + Args: + min_score: Minimum auto-generation score threshold + max_score: Maximum auto-generation score threshold + is_generated_func: Optional external detection function + """ + self.min_score = min_score + self.max_score = max_score + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__} with min_score: {self.min_score} and max_score: {self.max_score}...") + self.scorer = CodeAutoGeneratedSampleEvaluator(is_generated_func) + + @staticmethod + def get_desc(lang: str = "en"): + """ + Provide operator functionality description and parameter documentation. + """ + if lang == "zh": + return ( + "基于CodeAutoGeneratedSampleEvaluator的得分过滤自动生成的代码文件,确保只保留人工编写的代码。\n\n" + "评估指标:\n" + "- 自动生成标记数量:检测文件前5行中的自动生成标记\n" + "- 检测标记:'auto-generated', 'autogenerated', 'automatically generated'等\n" + "- 综合自动生成得分:0-1,1表示非自动生成\n" + "- 支持外部检测函数进行额外验证\n\n" + "输入参数:\n" + "- input_key: 输入字段名(需要包含'lines'列)\n" + "- output_key: 输出标签字段名 (默认: 'auto_generated_filter_label')\n" + "- min_score: 最小自动生成得分阈值 (默认: 1.0)\n" + "- max_score: 最大自动生成得分阈值 (默认: 1.0)\n" + "- is_generated_func: 可选的外部检测函数\n\n" + "输出参数:\n" + "- 过滤后的DataFrame,仅保留自动生成得分在指定范围内的代码样本\n" + "- 返回包含自动生成得分标签字段名的列表" + ) + else: + return ( + "Filter auto-generated code files using scores from CodeAutoGeneratedSampleEvaluator to ensure only human-written code is retained.\n\n" + "Evaluation Metrics:\n" + "- Auto-generation marker count: Detect markers in first 5 lines\n" + "- Detect markers: 'auto-generated', 'autogenerated', 'automatically generated', etc.\n" + "- Comprehensive auto-generation score: 0-1, 1 means not auto-generated\n" + "- Support external detection functions for additional validation\n\n" + "Input Parameters:\n" + "- input_key: Input field name (requires 'lines' column)\n" + "- output_key: Output label field name (default: 'auto_generated_filter_label')\n" + "- min_score: Minimum auto-generation score threshold (default: 1.0)\n" + "- max_score: Maximum auto-generation score threshold (default: 1.0)\n" + "- is_generated_func: Optional external detection function\n\n" + "Output Parameters:\n" + "- Filtered DataFrame containing only code samples with auto-generation scores within specified range\n" + "- List containing auto-generation score label field name" + ) + + def _validate_dataframe(self, dataframe: pd.DataFrame): + """ + Validate DataFrame to ensure required columns exist. + """ + required_keys = [self.input_lines_key] + missing = [k for k in required_keys if k not in dataframe.columns] + + if missing: + raise ValueError(f"AutogenFilter missing required columns: {missing}") + + def run( + self, + storage: DataFlowStorage, + input_key: str, + output_key: str = "auto_generated_filter_label" + ) -> List[str]: + """ + Execute auto-generated code detection and filtering using evaluator scores. + + Args: + storage: Data storage object + input_key: Field name containing code lines + output_key: Key name for output label + + Returns: + List[str]: List containing output key name + """ + self.input_key = input_key + self.output_key = output_key + self.logger.info(f"Running {self.__class__.__name__} with input_key: {self.input_key} and output_key: {self.output_key}...") + + dataframe = storage.read("dataframe") + scores = self.scorer.eval(dataframe, self.input_key) + + # Add scores to dataframe + for idx, score_dict in enumerate(scores): + for key, value in score_dict.items(): + dataframe.at[idx, key] = value + + # Apply filtering based on CodeAutoGeneratedScore + results = np.ones(len(dataframe), dtype=int) + score_filter = (dataframe["CodeAutoGeneratedScore"] >= self.min_score) & (dataframe["CodeAutoGeneratedScore"] <= self.max_score) + nan_filter = np.isnan(dataframe["CodeAutoGeneratedScore"]) + metric_filter = score_filter | nan_filter + results = results & metric_filter.astype(int) + + self.logger.debug(f"Filtered by auto-generated score, {np.sum(results)} data remained") + dataframe[f"{self.output_key}"] = metric_filter.astype(int) + + filtered_dataframe = dataframe[results == 1] + storage.write(filtered_dataframe) + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/code_doc_quality_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/code_doc_quality_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..f9790b23b8e21d9bfc8ae73d80f1c231bf714550 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/code_doc_quality_filter.py @@ -0,0 +1,296 @@ +import pandas as pd +import numpy as np +from typing import List, Dict, Any + +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.operators.code.eval.code_document_quality_sample_evaluator import CodeDocumentQualitySampleEvaluator + +import re +from collections import Counter + +@OPERATOR_REGISTRY.register() +class CodeDocumentQualityFilter(OperatorABC): + """ + CodeDocumentQualityFilter applies comprehensive document-level quality filtering + rules using CodeDocumentQualitySampleEvaluator scores to remove low-quality code and text samples. + """ + + def __init__(self, min_score: float = 1.0, max_score: float = 1.0, thresholds: Dict[str, Any] = None): + """ + Initialize the operator with evaluator and thresholds. + + Args: + min_score: Minimum document quality score threshold + max_score: Maximum document quality score threshold + thresholds: Optional thresholds dictionary to override default thresholds + """ + self.min_score = min_score + self.max_score = max_score + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__} with min_score: {self.min_score} and max_score: {self.max_score}...") + self.scorer = CodeDocumentQualitySampleEvaluator(thresholds) + + @staticmethod + def get_desc(lang: str = "en"): + if lang == "zh": + return ( + "基于CodeDocumentQualitySampleEvaluator的得分应用综合文档级质量过滤规则,移除低质量代码和文本样本。\n\n" + "评估指标:\n" + "- 内容长度:字符数、词数、行数范围检查\n" + "- 重复模式:重复行比例、2-10gram重复比例\n" + "- 字符组成:花括号比例、全大写单词比例\n" + "- 文本熵值:单字符熵值检查\n" + "- 综合文档质量得分:0-1,1表示通过所有质量检查\n\n" + "输入参数:\n" + "- input_key: 输入字段名(需要包含'text'、'filename'、'language'列)\n" + "- output_key: 输出标签字段名 (默认: 'doc_quality_filter_label')\n" + "- min_score: 最小文档质量得分阈值 (默认: 1.0)\n" + "- max_score: 最大文档质量得分阈值 (默认: 1.0)\n" + "- thresholds: 可选的阈值字典,用于覆盖默认阈值\n\n" + "输出参数:\n" + "- 过滤后的DataFrame,仅保留文档质量得分在指定范围内的样本\n" + "- 返回包含文档质量得分标签字段名的列表" + ) + else: + return ( + "Apply comprehensive document-level quality filtering rules using scores from CodeDocumentQualitySampleEvaluator to remove low-quality code and text samples.\n\n" + "Evaluation Metrics:\n" + "- Content length: character/word/line count range checks\n" + "- Repetition patterns: duplicate line ratio, 2-10gram repetition ratios\n" + "- Character composition: curly bracket ratio, all-caps word ratio\n" + "- Text entropy: unigram entropy checks\n" + "- Comprehensive document quality score: 0-1, 1 means passes all quality checks\n\n" + "Input Parameters:\n" + "- input_key: Input field name (requires 'text', 'filename', 'language' columns)\n" + "- output_key: Output label field name (default: 'doc_quality_filter_label')\n" + "- min_score: Minimum document quality score threshold (default: 1.0)\n" + "- max_score: Maximum document quality score threshold (default: 1.0)\n" + "- thresholds: Optional thresholds dictionary to override default thresholds\n\n" + "Output Parameters:\n" + "- Filtered DataFrame containing only samples with document quality scores within specified range\n" + "- List containing document quality score label field name" + ) + + def _num_chars(self, text: str) -> int: + return len(text) + + def _num_words(self, text: str) -> int: + return len(re.findall(r'\w+', text)) + + def _num_lines(self, text: str) -> int: + return len(text.splitlines()) + + def _frac_duplicate_lines(self, lines: List[str]) -> float: + if not lines: + return 0.0 + line2count = Counter([l.strip() for l in lines if l.strip()]) + count = sum([v for v in line2count.values() if v != 1]) + total = sum([v for v in line2count.values()]) + return count / total if total else 0.0 + + def _frac_curly_bracket(self, text: str) -> float: + total = len(text) + if total == 0: + return 0.0 + count = text.count('{') + text.count('}') + return count / total + + def _frac_all_caps_words(self, text: str) -> float: + words = re.findall(r'\b\w+\b', text) + if not words: + return 0.0 + all_caps = [w for w in words if w.isupper() and len(w) > 1] + return len(all_caps) / len(words) + + def _entropy_unigram(self, text: str) -> float: + words = re.findall(r'\b\w+\b', text) + if not words: + return 0.0 + freq = Counter(words) + total = sum(freq.values()) + import math + entropy = -sum((c/total) * math.log2(c/total) for c in freq.values()) + return entropy + + def _frac_duplicate_ngrams(self, text: str, n: int = 5) -> float: + words = re.findall(r'\b\w+\b', text) + if len(words) < n: + return 0.0 + ngrams = [' '.join(words[i:i+n]) for i in range(len(words)-n+1)] + ngram2count = Counter(ngrams) + count = sum([v for v in ngram2count.values() if v != 1]) + total = sum([v for v in ngram2count.values()]) + return count / total if total else 0.0 + + def _num_sentences(self, text: str) -> int: + SENT_PATTERN = re.compile(r'\b[^.!?。!?؟]+[.!?。!?؟]*', flags=re.UNICODE) + return len(SENT_PATTERN.findall(text)) + + def _num_lines(self, text: str) -> int: + return len(text.splitlines()) + + def _mean_word_length(self, text: str) -> float: + words = re.findall(r'\b\w+\b', text) + if not words: + return 0.0 + return sum(len(w) for w in words) / len(words) + + def _frac_full_bracket(self, text: str) -> float: + words = re.findall(r'\b\w+\b', text) + if not words: + return 0.0 + count = sum(1 for w in words if w in ('【', '】')) + return count / len(words) + + def _frac_lines_end_with_readmore(self, text: str) -> float: + ellipsis = ("...", "…", '全文', '详情', '详细', '更多', 'المزيد', 'تفاصيل', 'اقرأ المزيد', 'もっと', '詳細', 'もっと読む') + lines = text.splitlines() + if not lines: + return 0.0 + total_ellipsis_lines = sum( + any(l.rstrip().rstrip(']】)>》').endswith(e) for e in ellipsis) + for l in lines + ) + return total_ellipsis_lines / len(lines) + + def _frac_lines_start_with_bullet(self, text: str) -> float: + # Common bullet symbols + bullets = ("-", "*", "•", "·", "●", "▪", "‣", "⁃", "◦", "‧", "﹒", "・", "∙", "‣", "➤", "➢", "➣", "➥", "➦", "➧", "➨", "➩", "➪", "➫", "➬", "➭", "➮", "➯", "➱", "➲", "➳", "➵", "➸", "➺", "➻", "➼", "➽", "➾") + lines = text.splitlines() + if not lines: + return 0.0 + total_bullet_lines = sum(any(l.lstrip().startswith(b) for b in bullets) for l in lines) + return total_bullet_lines / len(lines) + + def _frac_words_unique(self, text: str) -> float: + words = re.findall(r'\b\w+\b', text) + if not words: + return 0.0 + return len(set(words)) / len(words) + + def _frac_replacement_symbols(self, text: str) -> float: + total = len(text) + if total == 0: + return 0.0 + return text.count('�') / total + + def _mean_sentence_length(self, text: str) -> float: + sentences = re.split(r'\.|\?|\!|\n', text) + if not sentences: + return 0.0 + return sum(len(s) for s in sentences) / len(sentences) + + def _frac_chars_url_html(self, text: str) -> float: + total = len(text) + if total == 0: + return 0.0 + link_pattern = r'\(https?://\S+\)' + html_tag_pattern = r'<.*?>' + link_list = re.findall(link_pattern, text) + html_tag_list = re.findall(html_tag_pattern, text) + url_char_num = sum(len(link) for link in link_list) + html_tag_char_num = sum(len(tag) for tag in html_tag_list) + return (url_char_num + html_tag_char_num) / total + + def _frac_chars_alphabet(self, text: str, lang: str = 'en') -> float: + if not text or lang != 'en': + return 0.0 + return sum(c.isalpha() for c in text) / len(text) + + def _frac_chars_digital(self, text: str) -> float: + if not text: + return 0.0 + return sum(c.isdigit() for c in text) / len(text) + + def _frac_chars_whitespace(self, text: str) -> float: + if not text: + return 0.0 + return len(re.findall(r'\s', text)) / len(text) + + def _frac_chars_hex_words(self, text: str) -> float: + total = len(text) + if total == 0: + return 0.0 + count = sum(len(e) for e in re.findall(r'\b0[xX][0-9a-fA-F]+\b', text)) + return count / total + + def _is_code_related_filename(self, filename: str) -> bool: + related = ["readme", "notes", "todo", "description", "cmakelists"] + name = filename.split('.')[0].lower() + return ( + "requirement" in name or name in related or name == "read.me" + ) + + def _apply_rules(self, row: pd.Series, thresholds: Dict[str, Any]) -> bool: + text = row.get('text', row.get('content', '')) + filename = row.get('filename', '') + lang = row.get('language', 'en') + lines = text.splitlines() + # Rule 1: min/max chars + num_chars = self._num_chars(text) + if num_chars < thresholds['min_num_chars'] or num_chars > thresholds['max_num_chars']: + return False + # Rule 2: min/max words + num_words = self._num_words(text) + if num_words < thresholds['min_num_words'] or num_words > thresholds['max_num_words']: + return False + # Rule 3: duplicate lines + frac_dup_lines = self._frac_duplicate_lines(lines) + if frac_dup_lines > thresholds['max_frac_duplicate_lines']: + return False + # Rule 4: duplicate n-grams (2~10) + for n in range(2, 11): + key = f'max_frac_duplicate_{n}gram' + if key in thresholds: + frac_dup_ngram = self._frac_duplicate_ngrams_n(text, n=n) + if frac_dup_ngram > thresholds[key]: + return False + # Rule 5: curly bracket ratio + frac_curly = self._frac_curly_bracket(text) + if frac_curly > thresholds['max_frac_curly_bracket']: + return False + # Rule 6: all caps words + frac_caps = self._frac_all_caps_words(text) + if frac_caps > thresholds['max_frac_all_caps_words']: + return False + # Rule 7: unigram entropy + entropy = self._entropy_unigram(text) + if entropy < thresholds['min_entropy_unigram']: + return False + # 其它规则同前 + return True + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str = "doc_quality_filter_label") -> List[str]: + """ + Applies document-level quality filtering rules using evaluator scores. + """ + self.input_key = input_key + self.output_key = output_key + self.logger.info(f"Running {self.__class__.__name__} with input_key: {self.input_key} and output_key: {self.output_key}...") + + dataframe = storage.read("dataframe") + scores = self.scorer.eval(dataframe, self.input_key) + + # Add scores to dataframe + for idx, score_dict in enumerate(scores): + for key, value in score_dict.items(): + dataframe.at[idx, key] = value + + # Apply filtering based on CodeDocumentQualityScore + results = np.ones(len(dataframe), dtype=int) + score_filter = (dataframe["CodeDocumentQualityScore"] >= self.min_score) & (dataframe["CodeDocumentQualityScore"] <= self.max_score) + nan_filter = np.isnan(dataframe["CodeDocumentQualityScore"]) + metric_filter = score_filter | nan_filter + results = results & metric_filter.astype(int) + + self.logger.debug(f"Filtered by document quality score, {np.sum(results)} data remained") + dataframe[f"{self.output_key}"] = metric_filter.astype(int) + + filtered_dataframe = dataframe[results == 1] + storage.write(filtered_dataframe) + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/code_encoded_data_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/code_encoded_data_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..cc25da118fbbe8048b830f7327fc8143701aaea6 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/code_encoded_data_filter.py @@ -0,0 +1,122 @@ +import re +import pandas as pd +import numpy as np +from typing import List + +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.operators.code.eval.code_encoded_data_sample_evaluator import CodeEncodedDataSampleEvaluator + +@OPERATOR_REGISTRY.register() +class CodeEncodedDataFilter(OperatorABC): + """ + CodeEncodedDataFilter filters code samples based on encoded data patterns using + CodeEncodedDataSampleEvaluator scores. It removes binary content and auto-generated code. + """ + + def __init__(self, min_score: float = 1.0, max_score: float = 1.0): + """ + Initialize the operator with evaluator and thresholds. + """ + self.min_score = min_score + self.max_score = max_score + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__} with min_score: {self.min_score} and max_score: {self.max_score}...") + self.scorer = CodeEncodedDataSampleEvaluator() + + @staticmethod + def get_desc(lang: str = "en"): + """ + Provide operator functionality description and parameter documentation. + """ + if lang == "zh": + return ( + "基于CodeEncodedDataSampleEvaluator的得分过滤代码样本,移除二进制内容和自动生成代码。\n\n" + "评估指标:\n" + "- Base64编码数据比例:检测连续64+字符的Base64字符串\n" + "- 十六进制数据比例:检测8+个连续的十六进制对\n" + "- Unicode转义序列比例:检测8+个连续的\\uXXXX序列\n" + "- 综合编码数据得分:0-1,1表示通过检查\n\n" + "输入参数:\n" + "- input_key: 输入字段名(需要包含'text'列)\n" + "- output_key: 输出标签字段名 (默认: 'encoded_data_filter_label')\n" + "- min_score: 最小编码数据得分阈值 (默认: 1.0)\n" + "- max_score: 最大编码数据得分阈值 (默认: 1.0)\n\n" + "输出参数:\n" + "- 过滤后的DataFrame,仅保留编码数据得分在指定范围内的代码样本\n" + "- 返回包含编码数据得分标签字段名的列表" + ) + else: + return ( + "Filter code samples using scores from CodeEncodedDataSampleEvaluator to remove binary content and auto-generated code.\n\n" + "Evaluation Metrics:\n" + "- Base64 encoded data ratio: Detect 64+ consecutive Base64 characters\n" + "- Hexadecimal data ratio: Detect 8+ consecutive hex pairs\n" + "- Unicode escape sequence ratio: Detect 8+ consecutive \\uXXXX sequences\n" + "- Comprehensive encoded data score: 0-1, 1 means passes checks\n\n" + "Input Parameters:\n" + "- input_key: Input field name (requires 'text' column)\n" + "- output_key: Output label field name (default: 'encoded_data_filter_label')\n" + "- min_score: Minimum encoded data score threshold (default: 1.0)\n" + "- max_score: Maximum encoded data score threshold (default: 1.0)\n\n" + "Output Parameters:\n" + "- Filtered DataFrame containing only code samples with encoded data scores within specified range\n" + "- List containing encoded data score label field name" + ) + + def _validate_dataframe(self, dataframe: pd.DataFrame): + """ + Validate DataFrame to ensure required columns exist. + """ + required_keys = [self.input_text_key] + missing = [k for k in required_keys if k not in dataframe.columns] + + if missing: + raise ValueError(f"DataPatternFilter missing required columns: {missing}") + + def run( + self, + storage: DataFlowStorage, + input_key: str, + output_key: str = "encoded_data_filter_label" + ) -> List[str]: + """ + Execute data pattern detection and filtering using evaluator scores. + + Args: + storage: Data storage object + input_key: Field name containing code text + output_key: Key name for output label + + Returns: + List[str]: List containing output key name + """ + self.input_key = input_key + self.output_key = output_key + self.logger.info(f"Running {self.__class__.__name__} with input_key: {self.input_key} and output_key: {self.output_key}...") + + dataframe = storage.read("dataframe") + scores = self.scorer.eval(dataframe, self.input_key) + + # Add scores to dataframe + for idx, score_dict in enumerate(scores): + for key, value in score_dict.items(): + dataframe.at[idx, key] = value + + # Apply filtering based on CodeEncodedDataScore + results = np.ones(len(dataframe), dtype=int) + score_filter = (dataframe["CodeEncodedDataScore"] >= self.min_score) & (dataframe["CodeEncodedDataScore"] <= self.max_score) + nan_filter = np.isnan(dataframe["CodeEncodedDataScore"]) + metric_filter = score_filter | nan_filter + results = results & metric_filter.astype(int) + + self.logger.debug(f"Filtered by encoded data score, {np.sum(results)} data remained") + dataframe[f"{self.output_key}"] = metric_filter.astype(int) + + filtered_dataframe = dataframe[results == 1] + storage.write(filtered_dataframe) + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/code_file_type_content_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/code_file_type_content_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..df347dc28960a60449bc0be4fcf75735aad7e06e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/code_file_type_content_filter.py @@ -0,0 +1,167 @@ +import pandas as pd +from typing import List, Set + +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC + +@OPERATOR_REGISTRY.register() +class CodeFileTypeContentFilter(OperatorABC): + """ + CodeFileTypeContentFilter filters code samples based on file types and content characteristics, + applying different rules for different file formats to ensure quality and relevance. + + This filter directly applies filtering rules without using evaluator scores: + - Removes oversized text files (>512 lines for Text/JSON/YAML files) + - Removes HTML files with insufficient visible text content + - Removes text files with inappropriate filenames (not documentation-related) + - Keeps files that meet format-specific quality criteria + """ + + # File types that require size checking + SIZE_CHECK_TYPES: Set[str] = { + "text", "json", "yaml", "web ontology language", + "graphviz", "dot" + } + + # Valid filename set for Text files + VALID_TEXT_NAMES: Set[str] = { + "readme", "notes", "todo", "description", "cmakelists" + } + + def __init__(self): + """ + Initialize the operator and set up the logger. + """ + self.logger = get_logger() + + @staticmethod + def get_desc(lang: str = "en"): + """ + Provide operator functionality description and parameter documentation. + """ + if lang == "zh": + return ( + "基于文件类型和内容特征直接过滤代码样本,针对不同文件格式应用特定规则。\n\n" + "过滤规则:\n" + "- Text/JSON/YAML/Graphviz文件:行数 > 512 行\n" + "- HTML文件:可见文本长度 < 100字符 或 可见文本比例 < 20%\n" + "- Text文件:文件名不符合文档规范(非readme/notes/todo等)\n\n" + "输入参数:\n" + "- input_key: 输入字段名(需要包含'filetype'、'filename'、'line_count'等列)\n" + "- output_key: 输出标签字段名 (默认: 'file_type_content_filter_label')\n\n" + "输出参数:\n" + "- 过滤后的DataFrame,仅保留符合文件类型规则的样本\n" + "- 返回包含输出标签字段名的列表" + ) + else: + return ( + "Filter code samples based on file types and content characteristics, applying specific rules for different file formats.\n\n" + "Filtering Rules:\n" + "- Text/JSON/YAML/Graphviz files: line count > 512\n" + "- HTML files: visible text length < 100 chars OR visible text ratio < 20%\n" + "- Text files: filename doesn't follow documentation conventions (not readme/notes/todo etc.)\n\n" + "Input Parameters:\n" + "- input_key: Input field name (requires 'filetype', 'filename', 'line_count' columns)\n" + "- output_key: Output label field name (default: 'file_type_content_filter_label')\n\n" + "Output Parameters:\n" + "- Filtered DataFrame containing only samples meeting file type rules\n" + "- List containing output label field name" + ) + + def _validate_dataframe(self, dataframe: pd.DataFrame): + """ + Validate DataFrame to ensure required columns exist. + """ + required_keys = ["filetype", "filename", "line_count"] + missing = [k for k in required_keys if k not in dataframe.columns] + + if missing: + raise ValueError(f"{self.__class__.__name__} missing required columns: {missing}") + + def _is_large_file(self, row: pd.Series) -> bool: + """ + Check if the file is large (line count > 512). + """ + return row.get("line_count", 0) > 512 + + def _is_html_valid(self, row: pd.Series) -> bool: + """ + Check if HTML file meets visible text requirements. + """ + visible_text_len = row.get("visible_text_length", 0) + total_code_len = row.get("total_code_length", 1) + ratio = visible_text_len / max(total_code_len, 1) + return visible_text_len >= 100 and ratio >= 0.2 + + def _is_text_filename_valid(self, filename: str) -> bool: + """ + Check if Text filename meets requirements. + """ + filename_lower = filename.lower() + name_without_ext = filename_lower.rsplit('.', 1)[0] + return ( + "requirement" in filename_lower + or name_without_ext in self.VALID_TEXT_NAMES + ) + + def run( + self, + storage: DataFlowStorage, + input_key: str, + output_key: str = "file_type_content_filter_label" + ) -> List[str]: + """ + Execute file type filtering operation. + + Args: + storage: Data storage object + input_key: Key name for input data + output_key: Key name for output label + + Returns: + List[str]: List containing output key name + """ + self.input_key = input_key + self.output_key = output_key + self.logger.info(f"Running {self.__class__.__name__} with input_key: {self.input_key} and output_key: {self.output_key}...") + + # 1. Read data + dataframe = storage.read("dataframe") + if dataframe.empty: + self.logger.warning("Input data is empty, skipping processing.") + storage.write(dataframe) + return [self.output_key] + + original_count = len(dataframe) + + # 2. Validate data + self._validate_dataframe(dataframe) + + # 3. Define filtering logic + def filter_row(row: pd.Series) -> bool: + filetype = row.get("filetype", "").lower() + filename = row.get("filename", "") + + if filetype in self.SIZE_CHECK_TYPES: + return not self._is_large_file(row) + elif filetype == "html": + return self._is_html_valid(row) + elif filetype == "text": + return self._is_text_filename_valid(filename) + return True + + # 4. Apply filtering and add label + filter_mask = dataframe.apply(filter_row, axis=1) + dataframe[self.output_key] = filter_mask.astype(int) + filtered_df = dataframe[filter_mask].reset_index(drop=True) + + # 5. Count results + filtered_count = len(filtered_df) + self.logger.info(f"Filtering completed. Total records passing filter: {filtered_count}.") + + # 6. Write back results + storage.write(filtered_df) + + return [self.output_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/code_length_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/code_length_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..304ce7920f578476770152341439cf34ec4af1a8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/code_length_filter.py @@ -0,0 +1,94 @@ +import pandas as pd +import numpy as np +from typing import List + +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.operators.code.eval.code_length_sample_evaluator import CodeLengthSampleEvaluator + +@OPERATOR_REGISTRY.register() +class CodeLengthSampleFilter(OperatorABC): + """ + CodeLengthSampleFilter filters code samples based on length characteristics using + CodeLengthSampleEvaluator scores. It removes oversized files and poorly formatted code. + """ + + def __init__(self, min_score: float = 1.0, max_score: float = 1.0): + """ + Initialize the operator with evaluator and thresholds. + """ + self.min_score = min_score + self.max_score = max_score + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__} with min_score: {self.min_score} and max_score: {self.max_score}...") + self.scorer = CodeLengthSampleEvaluator() + + @staticmethod + def get_desc(lang: str = "en"): + """ + Provide operator functionality description and parameter documentation. + """ + if lang == "zh": + return ( + "基于CodeLengthSampleEvaluator的得分过滤代码样本,移除超大文件和格式不良的代码。\n\n" + "评估指标:\n" + "- 总行数:检查是否超过100,000行\n" + "- 平均行长:普通语言>100字符,特殊语言>100,000字符\n" + "- 最大行长:普通语言>1,000字符\n\n" + "输入参数:\n" + "- input_key: 输入字段名(需要包含'lines'和'language'列)\n" + "- output_key: 输出标签字段名 (默认: 'length_filter_label')\n" + "- min_score: 最小长度得分阈值 (默认: 1.0)\n" + "- max_score: 最大长度得分阈值 (默认: 1.0)\n\n" + "输出参数:\n" + "- 过滤后的DataFrame,仅保留长度得分在指定范围内的代码样本\n" + "- 返回包含长度得分标签字段名的列表" + ) + else: + return ( + "Filter code samples using scores from CodeLengthSampleEvaluator to remove oversized files and poorly formatted code.\n\n" + "Evaluation Metrics:\n" + "- Total lines: Check if exceeds 100,000 lines\n" + "- Average line length: Normal languages >100 chars, special languages >100,000 chars\n" + "- Maximum line length: Normal languages >1,000 chars\n\n" + "Input Parameters:\n" + "- input_key: Input field name (requires 'lines' and 'language' columns)\n" + "- output_key: Output label field name (default: 'length_filter_label')\n" + "- min_score: Minimum length score threshold (default: 1.0)\n" + "- max_score: Maximum length score threshold (default: 1.0)\n\n" + "Output Parameters:\n" + "- Filtered DataFrame containing only code samples with length scores within specified range\n" + "- List containing length score label field name" + ) + + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str = 'length_filter_label'): + self.input_key = input_key + self.output_key = output_key + self.logger.info(f"Running {self.__class__.__name__} with input_key: {self.input_key} and output_key: {self.output_key}...") + + dataframe = storage.read("dataframe") + scores = self.scorer.eval(dataframe, self.input_key) + + # Add scores to dataframe + for idx, score_dict in enumerate(scores): + for key, value in score_dict.items(): + dataframe.at[idx, key] = value + + # Apply filtering based on CodeLengthScore + results = np.ones(len(dataframe), dtype=int) + score_filter = (dataframe["CodeLengthScore"] >= self.min_score) & (dataframe["CodeLengthScore"] <= self.max_score) + nan_filter = np.isnan(dataframe["CodeLengthScore"]) + metric_filter = score_filter | nan_filter + results = results & metric_filter.astype(int) + + self.logger.debug(f"Filtered by length score, {np.sum(results)} data remained") + dataframe[f"{self.output_key}"] = metric_filter.astype(int) + + filtered_dataframe = dataframe[results == 1] + storage.write(filtered_dataframe) + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/code_quality_score_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/code_quality_score_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..a7e2286ce30d51b74842b9fcb577d49310252d81 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/code_quality_score_filter.py @@ -0,0 +1,139 @@ +import pandas as pd +import numpy as np +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.core import LLMServingABC +from dataflow.operators.code.eval.code_quality_sample_evaluator import CodeQualitySampleEvaluator + +@OPERATOR_REGISTRY.register() +class CodeQualityScoreFilter(OperatorABC): + """ + CodeQualityScoreFilter filters code samples based on LLM-generated quality scores + from CodeQualitySampleEvaluator. It evaluates code correctness, completeness, clarity, + best practices, and efficiency, then filters out samples below the specified threshold. + + This filter uses evaluator scores to filter: + - Removes code with syntax errors or logical issues + - Removes incomplete or poorly structured code + - Removes code that doesn't follow best practices + - Keeps code with quality scores within specified range + """ + + def __init__(self, llm_serving: LLMServingABC, min_score: int = 7, max_score: int = 10): + """ + Initializes the operator with LLM serving and evaluator. + """ + self.min_score = min_score + self.max_score = max_score + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__} with min_score: {self.min_score} and max_score: {self.max_score}...") + self.scorer = CodeQualitySampleEvaluator(llm_serving) + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于LLM生成的代码质量分数过滤代码样本,评估正确性、完整性、清晰度、最佳实践和效率。\n\n" + "评估维度:\n" + "- 正确性:代码语法和逻辑是否正确\n" + "- 完整性:代码是否完整实现功能\n" + "- 清晰度:代码是否清晰易懂\n" + "- 最佳实践:是否遵循编程最佳实践\n" + "- 效率:代码执行效率如何\n\n" + "输入参数:\n" + "- input_code_key: 输入代码字段名\n" + "- input_instruction_key: 输入指令字段名\n" + "- output_score_key: 输出打分字段名 (默认: 'quality_score')\n" + "- output_feedback_key: 输出反馈字段名 (默认: 'quality_feedback')\n" + "- output_key: 输出过滤标签字段名 (默认: 'quality_score_filter_label')\n" + "- min_score: 最小质量分数阈值 (默认: 7)\n" + "- max_score: 最大质量分数阈值 (默认: 10)\n\n" + "输出参数:\n" + "- 过滤后的DataFrame,仅保留质量分数在指定范围内的代码样本\n" + "- 返回包含质量分数标签字段名的列表" + ) + else: + return ( + "Filter code samples based on LLM-generated quality scores evaluating correctness, completeness, clarity, best practices, and efficiency.\n\n" + "Evaluation Dimensions:\n" + "- Correctness: syntax and logic accuracy\n" + "- Completeness: functional completeness\n" + "- Clarity: code readability and understandability\n" + "- Best Practices: adherence to programming standards\n" + "- Efficiency: execution performance\n\n" + "Input Parameters:\n" + "- input_code_key: Input code column name\n" + "- input_instruction_key: Input instruction column name\n" + "- output_score_key: Output score column name (default: 'quality_score')\n" + "- output_feedback_key: Output feedback column name (default: 'quality_feedback')\n" + "- output_key: Output filter label column name (default: 'quality_score_filter_label')\n" + "- min_score: Minimum quality score threshold (default: 7)\n" + "- max_score: Maximum quality score threshold (default: 10)\n\n" + "Output Parameters:\n" + "- Filtered DataFrame containing only code samples with quality scores within specified range\n" + "- List containing quality score label field names" + ) + + def _validate_dataframe(self, dataframe: pd.DataFrame): + """ + Validates the DataFrame to ensure the required columns exist. + """ + required_keys = [self.input_code_key, self.input_instruction_key] + + missing = [k for k in required_keys if k not in dataframe.columns] + + if missing: + raise ValueError(f"Missing required column(s) for CodeQualityScoreFilter: {missing}") + + def _apply_score_filter(self, dataframe: pd.DataFrame) -> pd.DataFrame: + """ + Apply the score-based filtering logic. + + Args: + dataframe: Input DataFrame + + Returns: + Filtered DataFrame + """ + # Filter based on score range + score_filter = (dataframe[self.output_score_key] >= self.min_score) & (dataframe[self.output_score_key] <= self.max_score) + # Also keep samples with failed parsing (score = 0) + nan_filter = dataframe[self.output_score_key] == 0 + final_filter = score_filter | nan_filter + + return dataframe[final_filter] + + + def run(self, storage: DataFlowStorage, input_instruction_key: str, input_code_key: str, output_score_key = "quality_score", output_feedback_key = "quality_feedback",output_key: str = 'quality_score_filter_label'): + self.input_code_key = input_code_key + self.input_instruction_key = input_instruction_key + self.output_score_key = output_score_key + self.output_key = output_key + self.output_feedback_key = output_feedback_key + self.logger.info(f"Running {self.__class__.__name__} with input_key: {self.input_code_key} and output_key: {self.output_key}...") + + dataframe = storage.read("dataframe") + + # Use existing quality_score if available, otherwise evaluate + if self.output_score_key not in dataframe.columns: + scores, feedbacks = self.scorer.eval(dataframe, self.input_instruction_key, self.input_code_key) + dataframe[self.output_score_key] = scores + dataframe[self.output_feedback_key] = feedbacks + + # Apply filtering based on existing quality_score + results = np.ones(len(dataframe), dtype=int) + score_filter = (dataframe[self.output_score_key] >= self.min_score) & (dataframe[self.output_score_key] <= self.max_score) + nan_filter = dataframe[self.output_score_key] == 0 # Keep failed parsing samples + metric_filter = score_filter | nan_filter + results = results & metric_filter.astype(int) + + self.logger.debug(f"Filtered by quality score, {np.sum(results)} data remained") + dataframe[self.output_key] = metric_filter.astype(int) + + filtered_dataframe = dataframe[results == 1] + output_file = storage.write(filtered_dataframe) + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/code_score_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/code_score_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..38b023adc633b6c74afdab15626d88ad3e1c6f3b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/code_score_filter.py @@ -0,0 +1,156 @@ +import pandas as pd +from typing import List, Literal + +# Assuming these are the correct import paths for your framework +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC + +# TODO: remove and add to general filter +@OPERATOR_REGISTRY.register() +class CodeGenericScoreFilter(OperatorABC): + """ + CodeGenericScoreFilter is a generic score-based filtering operator that filters + datasets based on numerical score columns. It provides flexible comparison + methods to remove samples that don't meet specified threshold criteria. + + This filter directly applies score-based filtering without using evaluator scores: + - Removes samples with scores below minimum threshold + - Removes samples with scores above maximum threshold + - Removes samples that don't meet specific score criteria + - Keeps samples that meet the specified threshold criteria + """ + + def __init__(self, score_threshold: int = 8, filter_method: Literal["greater", "greater_equal", "less", "less_equal", "equal"] = "greater_equal"): + """ + Initializes the operator. + """ + self.logger = get_logger() + self.score_threshold = score_threshold + self.filter_method = filter_method + + @staticmethod + def get_desc(lang: str = "en"): + """ + Provides a description of the operator's function and parameters. + """ + if lang == "zh": + return ( + "基于数值分数列直接过滤数据集,提供灵活的阈值比较方法。\n\n" + "比较方法:\n" + "- greater_equal: 分数 >= 阈值\n" + "- greater: 分数 > 阈值\n" + "- less_equal: 分数 <= 阈值\n" + "- less: 分数 < 阈值\n" + "- equal: 分数 = 阈值\n\n" + "输入参数:\n" + "- input_key: 包含分数的字段名\n" + "- output_key: 输出标签字段名 (默认: 'generic_score_filter_label')\n" + "- score_threshold: 分数阈值 (默认: 8)\n" + "- filter_method: 比较方法 (默认: 'greater_equal')\n\n" + "输出参数:\n" + "- 过滤后的DataFrame,仅保留符合分数条件的样本\n" + "- 返回包含输出标签字段名的列表" + ) + else: # Default to English + return ( + "Filter datasets based on numerical score columns with flexible threshold comparison methods.\n\n" + "Comparison Methods:\n" + "- greater_equal: score >= threshold\n" + "- greater: score > threshold\n" + "- less_equal: score <= threshold\n" + "- less: score < threshold\n" + "- equal: score = threshold\n\n" + "Input Parameters:\n" + "- input_key: Field name containing the score\n" + "- output_key: Output label field name (default: 'generic_score_filter_label')\n" + "- score_threshold: Numerical threshold for filtering (default: 8)\n" + "- filter_method: Comparison method to use (default: 'greater_equal')\n\n" + "Output Parameters:\n" + "- Filtered DataFrame containing only samples meeting score criteria\n" + "- List containing output label field name" + ) + + def _validate_dataframe(self, dataframe: pd.DataFrame): + """ + Validates the DataFrame to ensure the required score column exists. + """ + required_keys = [self.input_score_key] + + missing = [k for k in required_keys if k not in dataframe.columns] + + if missing: + raise ValueError(f"Missing required column(s) for ScoreFilter: {missing}") + + # Also check if the column is numeric + if not pd.api.types.is_numeric_dtype(dataframe[self.input_score_key]): + raise TypeError(f"Column '{self.input_score_key}' for ScoreFilter must be of a numeric type.") + + def run( + self, + storage: DataFlowStorage, + input_key: str, + output_key: str = "generic_score_filter_label" + ) -> List[str]: + """ + Execute the filtering process. + + Reads data from storage, applies the filter based on the score, + and writes the filtered data back to storage. + + Args: + storage: Data storage object + input_key: Field name containing the score + output_key: Key name for output label + score_threshold: Numerical threshold for filtering + filter_method: Comparison method to use + + Returns: + List[str]: List containing output key name + """ + self.input_key = input_key + self.output_key = output_key + self.logger.info(f"Running {self.__class__.__name__} with input_key: {self.input_key} and output_key: {self.output_key}...") + + # Store key for use in helper methods + self.input_score_key = input_key + + # 1. Read data from the current step + dataframe = storage.read("dataframe") + if dataframe.empty: + self.logger.warning("Input dataframe is empty. Skipping.") + storage.write(dataframe) + return [self.output_key] + + original_count = len(dataframe) + + # 2. Validate the data + self._validate_dataframe(dataframe) + + # 3. Apply the filter logic and add label + if self.filter_method == "greater_equal": + filter_mask = dataframe[self.input_score_key] >= self.score_threshold + elif self.filter_method == "greater": + filter_mask = dataframe[self.input_score_key] > self.score_threshold + elif self.filter_method == "less_equal": + filter_mask = dataframe[self.input_score_key] <= self.score_threshold + elif self.filter_method == "less": + filter_mask = dataframe[self.input_score_key] < self.score_threshold + elif self.filter_method == "equal": + filter_mask = dataframe[self.input_score_key] == self.score_threshold + else: + # This case should ideally not be hit due to Literal type hint, but is good for robustness + raise ValueError(f"Unsupported filter_method: '{filter_method}'") + + dataframe[self.output_key] = filter_mask.astype(int) + filtered_df = dataframe[filter_mask] + + filtered_count = len(filtered_df) + self.logger.info(f"Filtering completed. Total records passing filter: {filtered_count}.") + + # 4. Write the results back to storage + storage.write(filtered_df) + + # 5. Return output key + return [self.output_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/code_text_composition_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/code_text_composition_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..d696153adce3cdb54180e01912a066785438c5c6 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/filter/code_text_composition_filter.py @@ -0,0 +1,95 @@ +import pandas as pd +import numpy as np +from typing import List + +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.operators.code.eval.code_text_composition_sample_evaluator import CodeTextCompositionSampleEvaluator + +@OPERATOR_REGISTRY.register() +class CodeTextCompositionFilter(OperatorABC): + """ + CodeTextCompositionFilter filters code samples based on character composition using + CodeTextCompositionSampleEvaluator scores. It removes binary files, encrypted content, + and other non-readable text. + """ + + def __init__(self, min_score: float = 1.0, max_score: float = 1.0): + """ + Initialize the operator with evaluator and thresholds. + """ + self.min_score = min_score + self.max_score = max_score + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__} with min_score: {self.min_score} and max_score: {self.max_score}...") + self.scorer = CodeTextCompositionSampleEvaluator() + + @staticmethod + def get_desc(lang: str = "en"): + """ + Provide operator functionality description and parameter documentation. + """ + if lang == "zh": + return ( + "基于CodeTextCompositionSampleEvaluator的得分过滤代码样本,移除二进制文件、加密内容和不可读文本。\n\n" + "评估指标:\n" + "- 字母字符比例:普通语言需要>=25%\n" + "- 字母数字字符比例:汇编语言需要>=25%\n" + "- 综合字符组成得分:0-1,1表示通过检查\n\n" + "输入参数:\n" + "- input_key: 输入字段名(需要包含'text'和'language'列)\n" + "- output_key: 输出标签字段名 (默认: 'text_composition_filter_label')\n" + "- min_score: 最小字符组成得分阈值 (默认: 1.0)\n" + "- max_score: 最大字符组成得分阈值 (默认: 1.0)\n\n" + "输出参数:\n" + "- 过滤后的DataFrame,仅保留字符组成得分在指定范围内的代码样本\n" + "- 返回包含字符组成得分标签字段名的列表" + ) + else: + return ( + "Filter code samples using scores from CodeTextCompositionSampleEvaluator to remove binary files, encrypted content, and non-readable text.\n\n" + "Evaluation Metrics:\n" + "- Alphabetic character ratio: Normal languages require >=25%\n" + "- Alphanumeric character ratio: Assembly languages require >=25%\n" + "- Comprehensive composition score: 0-1, 1 means passes checks\n\n" + "Input Parameters:\n" + "- input_key: Input field name (requires 'text' and 'language' columns)\n" + "- output_key: Output label field name (default: 'text_composition_filter_label')\n" + "- min_score: Minimum composition score threshold (default: 1.0)\n" + "- max_score: Maximum composition score threshold (default: 1.0)\n\n" + "Output Parameters:\n" + "- Filtered DataFrame containing only code samples with composition scores within specified range\n" + "- List containing composition score label field name" + ) + + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str = 'text_composition_filter_label'): + self.input_key = input_key + self.output_key = output_key + self.logger.info(f"Running {self.__class__.__name__} with input_key: {self.input_key} and output_key: {self.output_key}...") + + dataframe = storage.read("dataframe") + scores = self.scorer.eval(dataframe, self.input_key) + + # Add scores to dataframe + for idx, score_dict in enumerate(scores): + for key, value in score_dict.items(): + dataframe.at[idx, key] = value + + # Apply filtering based on CodeTextCompositionScore + results = np.ones(len(dataframe), dtype=int) + score_filter = (dataframe["CodeTextCompositionScore"] >= self.min_score) & (dataframe["CodeTextCompositionScore"] <= self.max_score) + nan_filter = np.isnan(dataframe["CodeTextCompositionScore"]) + metric_filter = score_filter | nan_filter + results = results & metric_filter.astype(int) + + self.logger.debug(f"Filtered by composition score, {np.sum(results)} data remained") + dataframe[f"{self.output_key}"] = metric_filter.astype(int) + + filtered_dataframe = dataframe[results == 1] + storage.write(filtered_dataframe) + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/generate/__pycache__/code_code_to_instruction_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/generate/__pycache__/code_code_to_instruction_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f8c78c2a6eadc76a78003573963dc2d933b643a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/generate/__pycache__/code_code_to_instruction_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/generate/__pycache__/code_gen_instruction.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/generate/__pycache__/code_gen_instruction.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c179d5524951e0896459cf9b6668de3ec6918149 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/generate/__pycache__/code_gen_instruction.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/generate/__pycache__/code_instruction_enhancement.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/generate/__pycache__/code_instruction_enhancement.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0be9e9e27205ee8974109692e9429cee984c00c4 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/generate/__pycache__/code_instruction_enhancement.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/generate/__pycache__/code_instruction_to_code_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/generate/__pycache__/code_instruction_to_code_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4f5f33e07ab86e763a7181231ba302fecf115d6 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/generate/__pycache__/code_instruction_to_code_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/generate/code_code_to_instruction_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/generate/code_code_to_instruction_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..5cbc260e5fae64c0c03163f79f6ec817fae4d240 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/generate/code_code_to_instruction_generator.py @@ -0,0 +1,131 @@ +import pandas as pd +from typing import List + +# Assuming these are the correct import paths for your framework +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC # For type hinting if needed +from dataflow.core import LLMServingABC +from dataflow.prompts.code import CodeCodeToInstructionGeneratorPrompt, DiyCodePrompt + +from typing import Union +from dataflow.core.prompt import prompt_restrict, DIYPromptABC +@prompt_restrict( + CodeCodeToInstructionGeneratorPrompt, + DiyCodePrompt +) +@OPERATOR_REGISTRY.register() +class CodeCodeToInstructionGenerator(OperatorABC): + """ + CodeCodeToInstructionGenerator is an operator that uses an LLM to generate a human-readable + instruction based on a given code snippet. This is the first step in a + 'self-instruct' style data synthesis pipeline for code. + """ + + def __init__(self, llm_serving: LLMServingABC, prompt_template: Union[CodeCodeToInstructionGeneratorPrompt, DiyCodePrompt, DIYPromptABC] = None): + """ + Initializes the operator with a language model serving endpoint. + """ + self.logger = get_logger() + self.llm_serving = llm_serving + + # Initialize prompt template + if prompt_template is None: + prompt_template = CodeCodeToInstructionGeneratorPrompt() + elif isinstance(prompt_template, str): + prompt_template = DiyCodePrompt(prompt_template) + self.prompt_template = prompt_template + + @staticmethod + def get_desc(lang: str = "en"): + """ + Provides a description of the operator's function and parameters. + """ + if lang == "zh": + return ( + "该算子用于分析代码片段并反向生成可能产生该代码的人类指令。\n\n" + "输入参数:\n" + "- input_key: 包含原始代码片段的字段名 (默认: 'code')\n" + "输出参数:\n" + "- output_key: 用于存储生成指令的字段名 (默认: 'generated_instruction')\n" + ) + else: # Default to English + return ( + "This operator analyzes a code snippet and reverse-engineers a human instruction " + "that could have produced it.\n\n" + "Input Parameters:\n" + "- input_key: Field name containing the raw code snippet (default: 'code')\n" + "Output Parameters:\n" + "- output_key: Field name to store the generated instruction (default: 'generated_instruction')\n" + ) + + def _validate_dataframe(self, dataframe: pd.DataFrame): + """ + Validates the DataFrame to ensure required columns exist and output columns don't. + """ + required_keys = [self.input_key] + forbidden_keys = [self.output_key] + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + raise ValueError(f"Missing required column(s): {missing}") + if conflict: + raise ValueError(f"The following column(s) already exist and would be overwritten: {conflict}") + + def _build_prompts(self, dataframe: pd.DataFrame) -> List[str]: + """ + Builds a list of prompts for the LLM based on the input code. + """ + prompts = [ + self.prompt_template.build_prompt(code=row[self.input_key]) + for _, row in dataframe.iterrows() + ] + return prompts + + def _parse_instruction(self, response: str) -> str: + """ + Parse the LLM's raw response to extract the clean instruction. + + Args: + response: Raw response string from the LLM + + Returns: + Clean instruction string without extra whitespace + """ + # The prompt is designed to make the LLM output only the instruction. + # This parsing step is mainly for cleaning up potential whitespace. + return response.strip() + + def run( + self, + storage: DataFlowStorage, + input_key: str = "code", + output_key: str = "generated_instruction" + ) -> List[str]: + """ + Executes the instruction synthesis process. + + It reads data from storage, generates instructions for each code snippet, + and writes the updated data back to storage. + + Returns: + A list containing the name of the newly created output column. + """ + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self._validate_dataframe(dataframe) + + formatted_prompts = self._build_prompts(dataframe) + responses = self.llm_serving.generate_from_input(formatted_prompts) + + instructions = [self._parse_instruction(r) for r in responses] + dataframe[self.output_key] = instructions + + output_file = storage.write(dataframe) + self.logger.info(f"Generated instructions saved to {output_file}") + + return [self.output_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/generate/code_gen_instruction.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/generate/code_gen_instruction.py new file mode 100644 index 0000000000000000000000000000000000000000..42ea336c3c4d80b194026e0683b8d5888047e211 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/generate/code_gen_instruction.py @@ -0,0 +1,175 @@ +import pandas as pd +from typing import List +import random + +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +from dataflow.prompts.code import CodeInstructionGeneratePrompt, DiyCodePrompt + +from typing import Union +from dataflow.core.prompt import prompt_restrict, DIYPromptABC + +@prompt_restrict( + CodeInstructionGeneratePrompt, +) +@OPERATOR_REGISTRY.register() +class CodeInstructionGenerator(OperatorABC): + """ + CodeInstructionGenerator is an operator that leverages a Large Language Model to generate + human-readable instructions based on few-shot examples sampled from a data pool. The operator + creates new instructions that are similar in difficulty and style to the provided examples. + This is a critical step in a 'self-instruct' style data synthesis pipeline, designed to expand + and enhance instruction datasets for programming tasks. + """ + + def __init__(self, llm_serving: LLMServingABC, prompt_template: Union[CodeInstructionGeneratePrompt, DIYPromptABC]=None, num_few_shot: int = 3, num_generate: int = 10): + """ + Initializes the operator with a language model serving endpoint. + + Args: + llm_serving: LLM serving instance + prompt_template: Custom prompt template (optional) + num_few_shot: Number of few-shot examples to use (default: 3) + """ + self.logger = get_logger() + self.num_generate = num_generate + self.llm_serving = llm_serving + self.num_few_shot = num_few_shot + self.prompt_template = CodeInstructionGeneratePrompt() + + @staticmethod + def get_desc(lang: str = "en"): + """ + Provides a description of the operator's function and parameters. + """ + if lang == "zh": + return ( + "该算子用于生成新的指令,从数据池中随机抽取few-shot样本,生成类似难度的指令。\n\n" + "输入参数:\n" + "- input_key: 包含原始指令的字段名 (默认: 'prompt')\n" + "输出参数:\n" + "- output_key: 用于存储生成指令的字段名 (默认: 'generated_instruction')\n" + ) + else: + return ( + "This operator generates new instructions by sampling few-shot examples from the data pool " + "to create instructions of similar difficulty.\n\n" + "Input Parameters:\n" + "- input_key: Field name containing the original instructions (default: 'prompt')\n" + "Output Parameters:\n" + "- output_key: Field name to store the generated instruction (default: 'generated_instruction')\n" + ) + + def _validate_dataframe(self, dataframe: pd.DataFrame): + """ + Validates the DataFrame to ensure required columns exist. + """ + required_keys = [self.input_key] + + missing = [k for k in required_keys if k not in dataframe.columns] + + if missing: + raise ValueError(f"Missing required column(s): {missing}") + + if len(dataframe) < self.num_few_shot: + raise ValueError(f"数据池样本数量({len(dataframe)})少于few-shot数量({self.num_few_shot})") + + def _sample_few_shot_examples(self, dataframe: pd.DataFrame) -> List[dict]: + """ + andomly sample few-shot examples from the data pool. + + Args: + dataframe: data pool + + Returns: + List of few-shot examples with instruction + """ + num_samples = min(self.num_few_shot, len(dataframe)) + sampled_indices = random.sample(range(len(dataframe)), num_samples) + + few_shot_examples = [] + for idx in sampled_indices: + row = dataframe.iloc[idx] + instruction = row[self.input_key] + few_shot_examples.append({ + 'instruction': instruction, + }) + + return few_shot_examples + + def _build_prompts(self, dataframe: pd.DataFrame, num_generate: int) -> List[str]: + """ + 构建指定数量的prompt,每个prompt包含随机抽取的few-shot样本 + + Args: + dataframe: Data pool + num_generate: The number of prompts to be generated. + + Returns: + List of prompts + """ + prompts = [] + for i in range(num_generate): + few_shot_examples = self._sample_few_shot_examples(dataframe) + prompt = self.prompt_template.build_prompt( + few_shot_examples=few_shot_examples + ) + prompts.append(prompt) + + return prompts + + def _parse_instruction(self, response: str) -> str: + """ + Parse the LLM's raw response to extract the clean instruction. + + Args: + response: Raw response string from the LLM + + Returns: + Clean instruction string without extra whitespace + """ + return response.strip() + + def run( + self, + storage: DataFlowStorage, + input_key: str = "prompt", + output_key: str = "generated_instruction", + ) -> List[str]: + """ + Executes the instruction synthesis process. + Reads data from the data pool, generates the specified number of new instructions, and saves them to a new DataFrame. + + Args: + storage: DataFlow storage instance + input_key: Field name containing the original instructions + output_key: Field name to store generated instructions + + Returns: + A list containing the name of the output column. + """ + self.input_key = input_key + self.output_key = output_key + + dataframe = storage.read("dataframe") + self._validate_dataframe(dataframe) + random.seed(42) + + formatted_prompts = self._build_prompts(dataframe, self.num_generate) + + responses = self.llm_serving.generate_from_input(formatted_prompts) + + instructions = [self._parse_instruction(r) for r in responses] + + new_dataframe = pd.DataFrame({ + self.output_key: instructions + }) + + output_file = storage.write(new_dataframe) + self.logger.info(f"Generated {len(instructions)} new instructions with {self.num_few_shot} few-shot examples each") + self.logger.info(f"Results saved to {output_file}") + + return [self.output_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/generate/code_instruction_enhancement.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/generate/code_instruction_enhancement.py new file mode 100644 index 0000000000000000000000000000000000000000..24e9095b7e01e1796fa0a984a2e4b2069f205b40 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/generate/code_instruction_enhancement.py @@ -0,0 +1,131 @@ +import pandas as pd +from typing import List + +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +from dataflow.prompts.code import CodeInstructionEnhancement, DiyCodePrompt + +from typing import Union +from dataflow.core.prompt import prompt_restrict, DIYPromptABC +@prompt_restrict( + CodeInstructionEnhancement, + DiyCodePrompt +) +@OPERATOR_REGISTRY.register() +class CodeEnhancementInstructionGenerator(OperatorABC): + """ + CodeEnhancementInstructionGenerator is an operator that uses an LLM to standardize + and normalize instructions into a consistent format for code generation tasks. + It rewrites original instructions into standardized English instruction + code block format. + """ + + def __init__(self, llm_serving: LLMServingABC, prompt_template: Union[CodeInstructionEnhancement, DiyCodePrompt, DIYPromptABC] = None): + """ + Initializes the operator with a language model serving endpoint. + """ + self.logger = get_logger() + self.llm_serving = llm_serving + + # Initialize prompt template + if prompt_template is None: + prompt_template = CodeInstructionEnhancement() + elif isinstance(prompt_template, str): + prompt_template = DiyCodePrompt(prompt_template) + self.prompt_template = prompt_template + + @staticmethod + def get_desc(lang: str = "en"): + """ + Provides a description of the operator's function and parameters. + """ + if lang == "zh": + return ( + "该算子用于增强人类指令,将不同输出格式的任务统一为生成完整函数。\n\n" + "输入参数:\n" + "- input_key: 包含原始代码片段的字段名 (默认: 'code')\n" + "输出参数:\n" + "- output_key: 用于存储生成指令的字段名 (默认: 'generated_instruction')\n" + ) + else: + return ( + "This operator enhances human instructions by unifying tasks with different " + "output formats into complete function generation tasks.\n\n" + "Input Parameters:\n" + "- input_key: Field name containing the original instruction messages (default: 'messages')\n" + "Output Parameters:\n" + "- output_key: Field name to store the enhanced instruction (default: 'generated_instruction')\n" + ) + + def _validate_dataframe(self, dataframe: pd.DataFrame): + """ + Validates the DataFrame to ensure required columns exist and output columns don't conflict. + """ + required_keys = [self.input_key] + forbidden_keys = [self.output_key] + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + raise ValueError(f"Missing required column(s): {missing}") + if conflict: + raise ValueError(f"The following column(s) already exist and would be overwritten: {conflict}") + + def _build_prompts(self, dataframe: pd.DataFrame) -> List[str]: + def get_human_instruction(messages): + """Extract human instruction from message list.""" + # for item in messages: + # if item.get('role') == 'HUMAN': + # return item.get('content', '') + # return '' + return messages + return [ + self.prompt_template.build_prompt(instruction=get_human_instruction(row[self.input_key])) + for _, row in dataframe.iterrows() + ] + + def _parse_instruction(self, response: str) -> str: + """ + Parse the LLM's raw response to extract the enhanced instruction. + + Args: + response: Raw response string from the LLM + + Returns: + Clean instruction string without extra whitespace + """ + return response.strip() + + def run( + self, + storage: DataFlowStorage, + input_key: str = "messages", + output_key: str = "generated_instruction" + ) -> List[str]: + """ + Executes the instruction synthesis process. + + Reads data from storage, enhances instructions for each message, + and writes the updated data back to storage. + + Returns: + A list containing the name of the newly created output column. + """ + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self._validate_dataframe(dataframe) + + formatted_prompts = self._build_prompts(dataframe) + responses = self.llm_serving.generate_from_input(formatted_prompts) + + instructions = [self._parse_instruction(r) for r in responses] + dataframe[self.output_key] = instructions + + output_file = storage.write(dataframe) + self.logger.info(f"Generated instructions saved to {output_file}") + + return [self.output_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/generate/code_instruction_to_code_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/generate/code_instruction_to_code_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..be6e59a0cf8bbc058fdb5ec72cd539e167085953 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/code/generate/code_instruction_to_code_generator.py @@ -0,0 +1,137 @@ +import pandas as pd +import re +from typing import List + +# Assuming these are the correct import paths for your framework +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +from dataflow.prompts.code import CodeInstructionToCodeGeneratorPrompt, DiyCodePrompt + +from typing import Union +from dataflow.core.prompt import prompt_restrict, DIYPromptABC +@prompt_restrict( + CodeInstructionToCodeGeneratorPrompt, + DiyCodePrompt +) +@OPERATOR_REGISTRY.register() +class CodeInstructionToCodeGenerator(OperatorABC): + """ + CodeInstructionToCodeGenerator is an operator that takes a natural language instruction and + uses an LLM to generate a corresponding code snippet. This is the second step + in a 'self-instruct' style data synthesis pipeline for code. + """ + + def __init__(self, llm_serving: LLMServingABC, prompt_template: Union[CodeInstructionToCodeGeneratorPrompt, DiyCodePrompt, DIYPromptABC] = None): + """ + Initializes the operator with a language model serving endpoint. + """ + self.logger = get_logger() + self.llm_serving = llm_serving + + # Initialize prompt template + if prompt_template is None: + prompt_template = CodeInstructionToCodeGeneratorPrompt() + elif isinstance(prompt_template, str): + prompt_template = DiyCodePrompt(prompt_template) + self.prompt_template = prompt_template + + @staticmethod + def get_desc(lang: str = "en"): + """ + Provides a description of the operator's function and parameters. + """ + if lang == "zh": + return ( + "该算子根据给定的人类指令生成相应的代码片段。\n\n" + "输入参数:\n" + "- input_key: 包含人类指令的字段名 (默认: 'instruction')\n" + "输出参数:\n" + "- output_key: 用于存储生成代码的字段名 (默认: 'generated_code')\n" + ) + else: # Default to English + return ( + "This operator generates a code snippet based on a given natural language instruction.\n\n" + "Input Parameters:\n" + "- input_key: Field name containing the human instruction (default: 'instruction')\n" + "Output Parameters:\n" + "- output_key: Field name to store the generated code (default: 'generated_code')\n" + ) + + def _validate_dataframe(self, dataframe: pd.DataFrame): + """ + Validates the DataFrame to ensure required columns exist and output columns don't. + """ + required_keys = [self.input_key] + forbidden_keys = [self.output_key] + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + raise ValueError(f"Missing required column(s): {missing}") + if conflict: + raise ValueError(f"The following column(s) already exist and would be overwritten: {conflict}") + + def _build_prompts(self, dataframe: pd.DataFrame) -> List[str]: + """ + Builds a list of prompts for the LLM based on the input instructions. + """ + prompts = [ + self.prompt_template.build_prompt(instruction=row[self.input_key]) + for _, row in dataframe.iterrows() + ] + return prompts + + def _parse_code(self, response: str) -> str: + """ + Parse the LLM's raw response to extract only the code. + Removes potential markdown code blocks and leading/trailing whitespace. + + Args: + response: Raw response string from the LLM + + Returns: + Clean code string without markdown formatting + """ + # Use regex to find content within ```python ... ``` or ``` ... ``` + code_block_match = re.search(r"```(?:python\n)?(.*)```", response, re.DOTALL) + if code_block_match: + # If a markdown block is found, extract its content + return code_block_match.group(1).strip() + else: + # Otherwise, assume the whole response is code and just strip it + return response.strip() + + def run( + self, + storage: DataFlowStorage, + input_key: str = "instruction", + output_key: str = "generated_code" + ) -> List[str]: + """ + Executes the code generation process. + + It reads data from storage, generates code for each instruction, + and writes the updated data back to storage. + + Returns: + A list containing the name of the newly created output column. + """ + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self._validate_dataframe(dataframe) + + formatted_prompts = self._build_prompts(dataframe) + responses = self.llm_serving.generate_from_input(formatted_prompts) + + codes = [self._parse_code(r) for r in responses] + dataframe[self.output_key] = codes + + output_file = storage.write(dataframe) + self.logger.info(f"Generated code saved to {output_file}") + + return [self.output_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b04874e1d177aa75c72c5552f5ff4eac7d1aa03e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/__init__.py @@ -0,0 +1,37 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from .generate.func_call_generators import ( + ScenarioExtractGenerator, + ScenarioExpandGenerator, + AtomTaskGenerator, + SequentialTaskGenerator, + ParaSeqTaskGenerator, + FunctionGenerator, + MultiTurnConversationGenerator, + ) + from .generate.consistent_chat_generator import ConsistentChatGenerator + + from .eval.func_call_conversation_sample_evaluator import FuncCallConversationSampleEvaluator + + from .filter.composition_task_filter import CompositionTaskFilter + +else: + import sys + from dataflow.utils.registry import LazyLoader, generate_import_structure_from_type_checking + + cur_path = "dataflow/operators/conversations/" + + # _import_structure = { + # "ScenarioExtractor": (cur_path + "func_call_operators.py", "ScenarioExtractor"), + # "ScenarioExpander": (cur_path + "func_call_operators.py", "ScenarioExpander"), + # "AtomTaskGenerator": (cur_path + "func_call_operators.py", "AtomTaskGenerator"), + # "SequentialTaskGenerator": (cur_path + "func_call_operators.py", "SequentialTaskGenerator"), + # "ParaSeqTaskGenerator": (cur_path + "func_call_operators.py", "ParaSeqTaskGenerator"), + # "CompositionTaskFilter": (cur_path + "func_call_operators.py", "CompositionTaskFilter"), + # "FunctionGenerator": (cur_path + "func_call_operators.py", "FunctionGenerator"), + # "MultiTurnDialogueGenerator": (cur_path + "func_call_operators.py", "MultiTurnDialogueGenerator"), + # "ConsistentChatGenerator": (cur_path + "consistent_chat.py", "ConsistentChatGenerator") + # } + _import_structure = generate_import_structure_from_type_checking(__file__, cur_path) + sys.modules[__name__] = LazyLoader(__name__, "dataflow/operators/conversations/", _import_structure) \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3d6595f0920cf327b86b2faa7eb31feb25e6a88 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/eval/__pycache__/func_call_conversation_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/eval/__pycache__/func_call_conversation_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db48fbda6f2dabfec06068d2744fcff6ab597dbe Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/eval/__pycache__/func_call_conversation_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/eval/func_call_conversation_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/eval/func_call_conversation_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..4121cdb8dc1f802e134dd96c150fd4a6ef82dc1a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/eval/func_call_conversation_sample_evaluator.py @@ -0,0 +1,99 @@ +import re +import pandas as pd +import numpy as np +from tqdm import tqdm +from dataflow.core import OperatorABC, LLMServingABC +from dataflow.core.prompt import prompt_restrict +from dataflow.utils.storage import DataFlowStorage +from dataflow.prompts.func_call import ConversationEvalPrompt +from dataflow.logger import get_logger +from dataflow.utils.registry import OPERATOR_REGISTRY + +@prompt_restrict( + ConversationEvalPrompt +) + +@OPERATOR_REGISTRY.register() +class FuncCallConversationSampleEvaluator(OperatorABC): + + def __init__(self, llm_serving: LLMServingABC): + self.llm_serving = llm_serving + self.prompt = ConversationEvalPrompt() + self.logger = get_logger() + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "对对话样本进行打分评估:使用 LLM 服务根据预设评分提示词对每条对话进行评分,并将结果写回数据流。\n" + "输入参数:\n" + "- llm_serving:LLM 服务对象,需实现 LLMServingABC 接口\n" + "- input_conversation_key:DataFrame 中对话内容字段名,默认 'conversations'\n" + "- output_score_key:评分结果输出字段名,默认 'score'\n" + "处理流程:\n" + "- 读取存储中的 DataFrame\n" + "- 将每条对话重组为评分提示词并调用 LLM 生成评分(JSON)\n" + "- 解析 JSON,提取 'score' 字段写入 DataFrame;解析失败则回退为 0\n" + "输出参数:\n" + "- 包含评分结果列的 DataFrame\n" + "- 包含输出字段名的列表(仅 'score' 或自定义的输出列名)" + ) + elif lang == "en": + return ( + "Evaluate conversation samples with an LLM-based scorer: the operator formats each " + "conversation into a scoring prompt, calls the LLM, parses the JSON response, and writes the score back.\n" + "Input Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC\n" + "- input_conversation_key: column name for conversations in the DataFrame, default 'conversations'\n" + "- output_score_key: column name for the score output, default 'score'\n" + "Process:\n" + "- Read the DataFrame from storage\n" + "- Reformat each conversation into a scoring prompt and call the LLM (expects JSON)\n" + "- Parse the JSON to extract 'score'; fallback to 0 on parse errors\n" + "Output:\n" + "- DataFrame with a score column added\n" + "- A list containing the output field name (e.g., 'score')" + ) + else: + return "Evaluate conversation samples with an LLM-based scorer and write the parsed 'score' back to the DataFrame." + + def _reformat_prompt(self, dataframe: pd.DataFrame): + formatted_prompts = [] + for conversation in tqdm(dataframe[self.input_conversation_key], desc="Reformatting prompts..."): + formatted_prompts.append(self.prompt.build_prompt(conversation=conversation)) + return formatted_prompts + + def clean_json_block(self, s: str) -> str: + s = s.strip() + if s.startswith("```"): + # 去掉首尾 ```json 或 ``` 包裹 + s = s.strip("`") + s = s.replace("json\n", "", 1) # 去掉开头的 json\n + if s.endswith("```"): + s = s[:-3] + return s.strip() + + def json_validate(self, llm_outputs): + import json + scores = [] + for item in llm_outputs: + score = 0 + try: + data = json.loads(self.clean_json_block(item)) + score = data['score'] + except Exception as e: + self.logger.debug(f"json loading error in item {item}") + scores.append(score) + return scores + + def run(self, storage: DataFlowStorage, input_conversation_key: str = "conversations", output_score_key = "score"): + self.input_conversation_key = input_conversation_key + self.output_score_key = output_score_key + dataframe = storage.read("dataframe") + llm_inputs = self._reformat_prompt(dataframe) + llm_outputs = self.llm_serving.generate_from_input(llm_inputs) + dataframe[self.output_score_key] = self.json_validate(llm_outputs) + storage.write(dataframe) + output_file = storage.write(dataframe) + self.logger.info(f"Results saved to {output_file}") + return [self.output_score_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/filter/__pycache__/composition_task_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/filter/__pycache__/composition_task_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9021a5a66841bc327e65b39fcf38554bd7e436a0 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/filter/__pycache__/composition_task_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/filter/composition_task_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/filter/composition_task_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..0583b32af7d070dbd9b81670669bfe4f148ef34b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/filter/composition_task_filter.py @@ -0,0 +1,83 @@ +import re +import pandas as pd +import numpy as np +from tqdm import tqdm +from dataflow.core import OperatorABC, LLMServingABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.prompts.func_call import CompositionTaskFilterPrompt +from dataflow.logger import get_logger +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.core.prompt import prompt_restrict + +@prompt_restrict( + CompositionTaskFilterPrompt +) + +@OPERATOR_REGISTRY.register() +class CompositionTaskFilter(OperatorABC): + def __init__(self, llm_serving: LLMServingABC): + self.logger = get_logger() + self.prompt = CompositionTaskFilterPrompt() + self.llm_serving = llm_serving + self.logger.info(f"Initializing {self.__class__.__name__}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "根据组合任务及其子任务,使用LLM服务判断组合任务是否具备可行性与完备性,从而进行可运行任务的筛选。\n" + "输入参数:\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口\n" + "- input_composition_task_key:组合任务字段名\n" + "- input_sub_tasks_keys:子任务字段名列表(如原子任务、并行任务、后继任务等)\n" + "- output_key:可运行标签的输出字段名,默认'runable_label'\n" + "输出参数:\n" + "- 仅包含可运行组合任务的数据DataFrame\n" + "- 包含输出字段名的列表(可运行标签字段)" + ) + elif lang == "en": + return ( + "Evaluate the feasibility and completeness of a composition task based on its sub-tasks using an LLM service, and filter out unexecutable tasks.\n" + "Input Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC interface\n" + "- input_composition_task_key: Field name for the composition task\n" + "- input_sub_tasks_keys: List of field names for sub-tasks (e.g., atomic, parallel, subsequent tasks)\n" + "- output_key: Field name for the executability label, default 'runable_label'\n" + "Output Parameters:\n" + "- DataFrame containing only executable composition tasks\n" + "- List containing the output field name (executability label)" + ) + else: + return "Filter composition tasks for feasibility and completeness using LLM service." + + + def _reformat_prompt(self, dataframe: pd.DataFrame): + formatted_prompts = [] + for task, sub_tasks in tqdm(zip(dataframe[self.input_composition_task_key], dataframe[self.input_sub_tasks_keys].to_dict(orient='records')), desc="Reformatting prompts..."): + formatted_prompts.append(self.prompt.build_prompt(task=task, sub_tasks=sub_tasks)) + # formatted_prompts = [self.prompt.filter_composition_task(task=item, sub_tasks=sub_tasks) for item, sub_tasks in tqdm(zip(dataframe[self.input_composition_task_key], dataframe[self.input_sub_tasks_key]), desc=f"Reformatting prompts...")] + return formatted_prompts + + def run(self, storage: DataFlowStorage, input_composition_task_key: str, input_sub_tasks_keys: list[str], output_key: str = "runable_label"): + self.input_composition_task_key = input_composition_task_key + self.input_sub_tasks_keys = input_sub_tasks_keys + self.output_key = output_key + dataframe = storage.read("dataframe") + llm_inputs = self._reformat_prompt(dataframe) + self.logger.debug(f"One of formatted prompts: {llm_inputs[0]}") + llm_outputs = self.llm_serving.generate_from_input(llm_inputs) + self.logger.debug(f"One of LLM outputs: {llm_outputs[0]}") + labels = [] + for item in llm_outputs: + match = re.search(r"(yes|no)", item.strip(), re.IGNORECASE) + if match: + labels.append(1 if match.group(1).lower() == "yes" else 0) + else: + labels.append(0) + dataframe[self.output_key] = labels + dataframe = dataframe[dataframe[self.output_key] > 0] + storage.write(dataframe) + output_file = storage.write(dataframe) + self.logger.info(f"Results saved to {output_file}") + return [self.output_key] + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/generate/__pycache__/consistent_chat_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/generate/__pycache__/consistent_chat_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4cc9375480b2be8685a4a08a9d47a05de5ef2c5c Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/generate/__pycache__/consistent_chat_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/generate/__pycache__/func_call_generators.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/generate/__pycache__/func_call_generators.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..798ae685b41560b0d116f0ac364cb2aa96782c31 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/generate/__pycache__/func_call_generators.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/generate/consistent_chat_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/generate/consistent_chat_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..3576f1319054a771502d1d24dd6b0713a99130b1 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/generate/consistent_chat_generator.py @@ -0,0 +1,143 @@ +import random +import json +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +import pandas as pd +from dataflow.core import LLMServingABC +from dataflow.prompts.general_text import ConsistentChatPrompt +from dataflow.core.prompt import DIYPromptABC, prompt_restrict +from typing import Union + +@prompt_restrict( + ConsistentChatPrompt +) + +@OPERATOR_REGISTRY.register() +class ConsistentChatGenerator(OperatorABC): + def __init__(self, llm_serving: LLMServingABC = None, num_dialogs_per_intent = 20, num_turns_per_dialog = 6, temperature = 0.9, prompt_template : Union[ConsistentChatPrompt, DIYPromptABC] = None): + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.llm_serving = llm_serving + self.num_dialogs_per_intent = num_dialogs_per_intent # Based on the topic_dict in the existing prompt, it is recommended to set the value to below 1000 (which can generate 9000 conversation data). Otherwise, it is recommended to add more topic_dict in dataflow.prompts.general_text.ConsistentChatPrompt to increase data richness + self.num_turns_per_dialog = num_turns_per_dialog + self.temperature = temperature + self.prompt_template = prompt_template + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "根据预置主题和人类意图,两阶段从0合成多轮对话格式数据(合成数量大于9000时建议增加标签数量)。\n" + "输入参数:\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口\n" + "- num_dialogs_per_intent:每个意图生成的对话数量,默认20\n" + "- num_turns_per_dialog:每个对话的轮次数量,默认6\n" + "- temperature:生成温度,控制输出随机性,默认0.9\n" + "- prompt_template:提示词模板对象,用于定义提示结构\n" + "输出参数:\n" + "- 包含category和conversation字段的DataFrame,其中conversation为多轮对话列表" + ) + elif lang == "en": + return ( + "Two-stage generation of multi-turn dialogue data from scratch based on predefined topics and human intents (for over 9000 samples, consider increasing the number of tags).\n" + "Input Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC interface\n" + "- num_dialogs_per_intent: Number of dialogs generated per intent, default 20\n" + "- num_turns_per_dialog: Number of turns per dialog, default 6\n" + "- temperature: Sampling temperature for generation, default 0.9\n" + "- prompt_template: Prompt template object, for defining the prompt structure\n" + "Output Parameters:\n" + "- DataFrame containing 'category' and 'conversation' fields, where conversation is a list of multi-turn dialogues" + ) + else: + return "Two-stage generation of multi-turn dialogue data from scratch based on predefined topics and human intents." + + def run(self, storage: DataFlowStorage): + + # Step 1: Generate all queries using LLM + all_query_prompts = self.prompt_template.build_prompt(mode="query", num_dialogs_per_intent=self.num_dialogs_per_intent) + # Step 2: Generate queries by calling llm_serving once + self.logger.info("Generating queries...") + queries_list = self.llm_serving.generate_from_input(user_inputs=all_query_prompts) + valid_queries = [] + cnt = 0 + for queries_str in queries_list: + try: + if not isinstance(queries_str, str): + raise ValueError("Invalid response type") + clean_queries_str = queries_str.replace("```json", "").replace("```", "").strip() + queries = json.loads(clean_queries_str) + valid_queries.append(queries) + except (json.JSONDecodeError, ValueError) as e: + cnt += 1 + self.logger.debug(f'Json parse failed counts: {cnt} (Model generation error)') + continue + all_response_prompts = [] + for queries in valid_queries: + category = queries.get("category") + turns = queries.get("turns") + all_response_prompts.append(self.prompt_template.build_prompt(mode="response", topic=category, queries=turns)) + self.logger.info("Generating responses...") + responses_list = self.llm_serving.generate_from_input(user_inputs=all_response_prompts) + + final_queries = [] + final_responses = [] + cnt = 0 + for query, responses_str in zip(valid_queries, responses_list): + try: + if not isinstance(responses_str, str): + raise ValueError("Invalid response type") + clean_responses_str = responses_str.replace("```json", "").replace("```", "").strip() + responses = json.loads(clean_responses_str) + final_queries.append(query) + final_responses.append(responses) + except (json.JSONDecodeError, ValueError) as e: + cnt += 1 + self.logger.debug(f'Json parse failed counts: {cnt} (Model generation error): {str(e)}') + continue + + formatted_data = [] + + for query_data, response_data in zip(final_queries, final_responses): + if isinstance(response_data, dict): + response_data = response_data.get('responses', []) + try: + category = query_data['category'] + turns = query_data['turns'] + + # Ensure the number of turns matches the number of responses + num_user_turns = len(turns) + num_assistant_responses = len(response_data) + + if num_user_turns > num_assistant_responses: + turns = turns[:num_assistant_responses] + + conversation = [] + for i in range(len(turns)): + conversation.append({"role": "user", "value": turns[i]}) + if i < len(response_data): + conversation.append({"role": "assistant", "value": response_data[i]['response']}) + + # Ensure conversation does not end with a user message + if conversation and conversation[-1]["role"] == "user": + conversation.pop() + + if not conversation: + continue + + formatted_data.append({ + "category": category, + "conversation": conversation + }) + except Exception as e: + self.logger.debug(f"Error processing category '{query_data.get('category', 'Unknown')}': {e}") + continue + self.logger.info(f'Number of synthesized dialogues: {len(formatted_data)}') + + df = pd.DataFrame(formatted_data) + storage.write(df) + self.logger.info(f'Number of synthesized dialogues: {len(df)} written to storage as DataFrame') + return df diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/generate/func_call_generators.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/generate/func_call_generators.py new file mode 100644 index 0000000000000000000000000000000000000000..4a15b315ed56f2f08ed32f5e57991493f6c50467 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/conversations/generate/func_call_generators.py @@ -0,0 +1,547 @@ +import re +import pandas as pd +import numpy as np +from tqdm import tqdm +from dataflow.core import OperatorABC, LLMServingABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.prompts.func_call import ( + ExtractScenarioPrompt, + ExpandScenarioPrompt, + FuncAtomicTaskGeneratePrompt, + SequentialTaskGeneratePrompt, + ParathenSeqTaskGeneratePrompt, + FuncGeneratePrompt, + ConversationUserPrompt, + ConversationAssistantPrompt, + ConversationToolPrompt, +) +from dataflow.logger import get_logger +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.core.prompt import prompt_restrict + +@prompt_restrict( + ExtractScenarioPrompt +) + +@OPERATOR_REGISTRY.register() +class ScenarioExtractGenerator(OperatorABC): + + def __init__(self, llm_serving: LLMServingABC): + self.logger = get_logger() + self.prompt = ExtractScenarioPrompt() + self.llm_serving = llm_serving + self.logger.info(f"Initializing {self.__class__.__name__}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "从对话内容中提取场景信息,使用LLM服务分析对话并生成场景描述。\n" + "输入参数:\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口\n" + "- input_chat_key:对话内容字段名\n" + "- output_key:输出场景字段名,默认'scenario'\n" + "输出参数:\n" + "- 包含提取场景信息的DataFrame\n" + "- 包含输出字段名的列表" + ) + elif lang == "en": + return ( + "Extract scenario information from conversation content using LLM service to analyze dialogues and generate scenario descriptions.\n" + "Input Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC interface\n" + "- input_chat_key: Field name for conversation content\n" + "- output_key: Field name for output scenario, default 'scenario'\n" + "Output Parameters:\n" + "- DataFrame containing extracted scenario information\n" + "- List containing output field name" + ) + else: + return "Extract scenario information from conversation content using LLM service." + + def _reformat_prompt(self, dataframe: pd.DataFrame): + formatted_prompts = [self.prompt.build_prompt(conversation=item) for item in tqdm(dataframe[self.input_chat_key], desc=f"Reformatting prompts...")] + + return formatted_prompts + + def run(self, storage: DataFlowStorage, input_chat_key: str, output_key: str = "scenario"): + self.input_chat_key = input_chat_key + self.output_key = output_key + dataframe = storage.read("dataframe") + llm_inputs = self._reformat_prompt(dataframe) + llm_outputs = self.llm_serving.generate_from_input(llm_inputs) + dataframe[self.output_key] = llm_outputs + output_file = storage.write(dataframe) + self.logger.info(f"Results saved to {output_file}") + return [self.output_key] + +@prompt_restrict( + ExpandScenarioPrompt +) + +@OPERATOR_REGISTRY.register() +class ScenarioExpandGenerator(OperatorABC): + + def __init__(self, llm_serving: LLMServingABC): + self.logger = get_logger() + self.prompt = ExpandScenarioPrompt() + self.llm_serving = llm_serving + self.logger.info(f"Initializing {self.__class__.__name__}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于原始场景生成新的替代场景,使用LLM服务重写或改写原有场景内容。\n" + "输入参数:\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口\n" + "- input_scenario_key:原始场景字段名\n" + "- output_key:生成的新场景字段名,默认'modified_scenario'\n" + "输出参数:\n" + "- 包含生成新场景的DataFrame\n" + "- 包含输出字段名的列表" + ) + elif lang == "en": + return ( + "Generate new or alternative scenarios based on the original scenario using LLM service. The original content is rewritten or reimagined to create a different version.\n" + "Input Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC interface\n" + "- input_scenario_key: Field name for the original scenario\n" + "- output_key: Field name for the new scenario, default 'modified_scenario'\n" + "Output Parameters:\n" + "- DataFrame containing newly generated scenarios\n" + "- List containing output field name" + ) + else: + return "Generate new scenarios using LLM service based on original inputs." + + def _reformat_prompt(self, dataframe: pd.DataFrame): + formatted_prompts = [self.prompt.build_prompt(scenario=item) for item in tqdm(dataframe[self.input_scenario_key], desc=f"Reformatting prompts...")] + return formatted_prompts + + def run(self, storage: DataFlowStorage, input_scenario_key: str, output_key: str = "modified_scenario"): + self.input_scenario_key = input_scenario_key + self.output_key = output_key + dataframe = storage.read("dataframe") + llm_inputs = self._reformat_prompt(dataframe) + llm_outputs = self.llm_serving.generate_from_input(llm_inputs) + dataframe[self.output_key] = llm_outputs + output_file = storage.write(dataframe) + self.logger.info(f"Results saved to {output_file}") + return [self.output_key] + +@prompt_restrict( + FuncAtomicTaskGeneratePrompt +) + +@OPERATOR_REGISTRY.register() +class AtomTaskGenerator(OperatorABC): + + def __init__(self, llm_serving: LLMServingABC): + self.logger = get_logger() + self.prompt = FuncAtomicTaskGeneratePrompt() + self.llm_serving = llm_serving + self.logger.info(f"Initializing {self.__class__.__name__}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "根据输入的场景信息,使用LLM服务生成对应的原子任务。\n" + "输入参数:\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口\n" + "- input_scenario_key:场景字段名\n" + "- output_key:原子任务的输出字段名,默认'atom_task'\n" + "输出参数:\n" + "- 包含原子任务的DataFrame\n" + "- 包含输出字段名的列表" + ) + elif lang == "en": + return ( + "Generate atomic task based on the input scenario using an LLM service.\n" + "Input Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC interface\n" + "- input_scenario_key: Field name for the scenario\n" + "- output_key: Field name for the atomic task output, default 'atom_task'\n" + "Output Parameters:\n" + "- DataFrame containing the atomic tasks\n" + "- List containing output field name" + ) + else: + return "Generate atomic tasks from scenario using LLM service." + + def _reformat_prompt(self, dataframe: pd.DataFrame): + formatted_prompts = [self.prompt.build_prompt(scenario=item) for item in tqdm(dataframe[self.input_scenario_key], desc=f"Reformatting prompts...")] + return formatted_prompts + + def run(self, storage: DataFlowStorage, input_scenario_key: str, output_key: str = "atom_task"): + self.input_scenario_key = input_scenario_key + self.output_key = output_key + dataframe = storage.read("dataframe") + llm_inputs = self._reformat_prompt(dataframe) + llm_outputs = self.llm_serving.generate_from_input(llm_inputs) + dataframe[self.output_key] = llm_outputs + output_file = storage.write(dataframe) + self.logger.info(f"Results saved to {output_file}") + return [self.output_key] + +@prompt_restrict( + SequentialTaskGeneratePrompt +) + +@OPERATOR_REGISTRY.register() +class SequentialTaskGenerator(OperatorABC): + + def __init__(self, llm_serving: LLMServingABC): + self.logger = get_logger() + self.prompt = SequentialTaskGeneratePrompt() + self.llm_serving = llm_serving + self.logger.info(f"Initializing {self.__class__.__name__}...") + + def _reformat_prompt(self, dataframe: pd.DataFrame): + formatted_prompts = [self.prompt.build_prompt(task=item) for item in tqdm(dataframe[self.input_task_key], desc=f"Reformatting prompts...")] + return formatted_prompts + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "根据输入的原子任务,使用LLM服务生成该任务的后继任务和两者的组合任务。\n" + "输入参数:\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口\n" + "- input_task_key:原子任务字段名\n" + "- output_subsequent_task_key:后继任务输出字段名,默认'subsequent_task'\n" + "- output_composition_task_key:组合任务输出字段名,默认'composition_task'\n" + "输出参数:\n" + "- 包含后继任务和组合任务的DataFrame\n" + "- 输出字段名的列表(后继任务字段和组合任务字段)" + ) + elif lang == "en": + return ( + "Generate the subsequent task and a composition task based on the input atomic task using an LLM service.\n" + "Input Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC interface\n" + "- input_task_key: Field name for the atomic task\n" + "- output_subsequent_task_key: Field name for the subsequent task output, default 'subsequent_task'\n" + "- output_composition_task_key: Field name for the composition task output, default 'composition_task'\n" + "Output Parameters:\n" + "- DataFrame containing both subsequent and composition tasks\n" + "- List containing the names of the output fields" + ) + else: + return "Generate subsequent and composition tasks from atomic task using LLM service." + + def run(self, storage: DataFlowStorage, input_task_key: str, output_subsequent_task_key: str = "subsequent_task", output_composition_task_key: str = "composition_task"): + self.input_task_key = input_task_key + self.output_subsequent_task_key = output_subsequent_task_key + self.output_composition_task_key = output_composition_task_key + dataframe = storage.read("dataframe") + llm_inputs = self._reformat_prompt(dataframe) + llm_outputs = self.llm_serving.generate_from_input(llm_inputs) + subsequent_tasks, composition_tasks = [], [] + for item in llm_outputs: + # 正则表达式提取 + match_subsequent = re.search(r"### Subsequent Task: (.*?)\n", item) + match_composition = re.search(r"### Composition Task: (.*?)$", item) + if match_subsequent: + subsequent_task = match_subsequent.group(1) + else: + subsequent_task = None + if match_composition: + composition_task = match_composition.group(1) + else: + composition_task = None + subsequent_tasks.append(subsequent_task) + composition_tasks.append(composition_task) + + dataframe[self.output_subsequent_task_key] = subsequent_tasks + dataframe[self.output_composition_task_key] = composition_tasks + output_file = storage.write(dataframe) + self.logger.info(f"Results saved to {output_file}") + return [self.output_subsequent_task_key, output_composition_task_key] + +@prompt_restrict( + ParathenSeqTaskGeneratePrompt +) + +@OPERATOR_REGISTRY.register() +class ParaSeqTaskGenerator(OperatorABC): + + def __init__(self, llm_serving: LLMServingABC): + self.logger = get_logger() + self.prompt = ParathenSeqTaskGeneratePrompt() + self.llm_serving = llm_serving + self.logger.info(f"Initializing {self.__class__.__name__}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于原子任务,使用LLM服务生成三个任务类型:并行任务、后继任务以及这三者的组合任务。\n" + "输入参数:\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口\n" + "- input_task_key:原子任务字段名\n" + "- output_parallel_task_key:并行任务输出字段名,默认'parallel_task'\n" + "- output_subsequent_task_key:后继任务输出字段名,默认'subsequent_task'\n" + "- output_composition_task_key:组合任务输出字段名,默认'composition_task'\n" + "输出参数:\n" + "- 包含并行任务、后继任务与组合任务的DataFrame\n" + "- 输出字段名列表(并行任务、后继任务、组合任务)" + ) + elif lang == "en": + return ( + "Based on a given atomic task, this operator uses an LLM service to generate three task types: " + "a parallel task, a subsequent task, and a composition task combining them.\n" + "Input Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC interface\n" + "- input_task_key: Field name for the atomic task\n" + "- output_parallel_task_key: Field name for the parallel task, default 'parallel_task'\n" + "- output_subsequent_task_key: Field name for the subsequent task, default 'subsequent_task'\n" + "- output_composition_task_key: Field name for the composition task, default 'composition_task'\n" + "Output Parameters:\n" + "- DataFrame containing parallel, subsequent, and composition tasks\n" + "- List containing the output field names" + ) + else: + return "Generate parallel, subsequent, and composition tasks based on an atomic task using LLM service." + + def _reformat_prompt(self, dataframe: pd.DataFrame): + formatted_prompts = [self.prompt.build_prompt(task=item) for item in tqdm(dataframe[self.input_task_key], desc=f"Reformatting prompts...")] + return formatted_prompts + + def run(self, storage: DataFlowStorage, input_task_key: str, output_parallel_task_key: str = "parallel_task", output_subsequent_task_key: str = "subsequent_task", output_composition_task_key: str = "composition_task"): + self.input_task_key = input_task_key + self.output_parallel_task_key = output_parallel_task_key + self.output_subsequent_task_key = output_subsequent_task_key + self.output_composition_task_key = output_composition_task_key + dataframe = storage.read("dataframe") + llm_inputs = self._reformat_prompt(dataframe) + llm_outputs = self.llm_serving.generate_from_input(llm_inputs) + parallel_tasks, subsequent_tasks, composition_tasks = [], [], [] + for item in llm_outputs: + # 正则表达式提取 + match_parallel = re.search(r"### Parallel Task: (.*?)\n", item) + match_subsequent = re.search(r"### Subsequent Task: (.*?)\n", item) + match_composition = re.search(r"### Composition Task: (.*?)$", item) + if match_parallel: + parallel_task = match_parallel.group(1) + else: + parallel_tasks = None + if match_subsequent: + subsequent_task = match_subsequent.group(1) + else: + subsequent_task = None + if match_composition: + composition_task = match_composition.group(1) + else: + composition_task = None + parallel_tasks.append(parallel_task) + subsequent_tasks.append(subsequent_task) + composition_tasks.append(composition_task) + dataframe[self.output_parallel_task_key] = parallel_tasks + dataframe[self.output_subsequent_task_key] = subsequent_tasks + dataframe[self.output_composition_task_key] = composition_tasks + output_file = storage.write(dataframe) + self.logger.info(f"Results saved to {output_file}") + return [self.output_parallel_task_key, self.output_subsequent_task_key, output_composition_task_key] + +@prompt_restrict( + FuncGeneratePrompt +) + +@OPERATOR_REGISTRY.register() +class FunctionGenerator(OperatorABC): + def __init__(self, llm_serving: LLMServingABC): + self.logger = get_logger() + self.prompt = FuncGeneratePrompt() + self.llm_serving = llm_serving + self.logger.info(f"Initializing {self.__class__.__name__}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于组合任务及其相关子任务,使用LLM服务生成对应的函数列表。" + "输入参数:\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口\n" + "- input_composition_task_key:组合任务字段名\n" + "- input_sub_tasks_keys:子任务字段名列表(如原子任务、并行任务、后继任务等)\n" + "- output_key:函数列表输出字段名,默认'functions'\n" + "输出参数:\n" + "- 包含函数定义或函数列表的DataFrame\n" + "- 输出字段名的列表(函数列表字段)" + ) + elif lang == "en": + return ( + "Generate a list of functions based on a composition task and its associated sub-tasks using an LLM service. " + "Input Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC interface\n" + "- input_composition_task_key: Field name for the composition task\n" + "- input_sub_tasks_keys: List of field names for sub-tasks (e.g., atomic, parallel, subsequent tasks)\n" + "- output_key: Field name for the generated functions, default 'functions'\n" + "Output Parameters:\n" + "- DataFrame containing the generated functions or function list\n" + "- List containing the output field name" + ) + else: + return "Generate functions from composition and sub-tasks using LLM service." + + def _reformat_prompt(self, dataframe: pd.DataFrame): + formatted_prompts = [] + for task, sub_tasks in tqdm(zip(dataframe[self.input_composition_task_key], dataframe[self.input_sub_tasks_keys].to_dict(orient='records')), desc="Reformatting prompts..."): + formatted_prompts.append(self.prompt.build_prompt(task=task, sub_tasks=sub_tasks)) + # formatted_prompts = [self.prompt.filter_composition_task(task=item, sub_tasks=sub_tasks) for item, sub_tasks in tqdm(zip(dataframe[self.input_composition_task_key], dataframe[self.input_sub_tasks_key]), desc=f"Reformatting prompts...")] + return formatted_prompts + + def run(self, storage: DataFlowStorage, input_composition_task_key: str, input_sub_tasks_keys: list[str], output_key: str = "functions"): + self.input_composition_task_key = input_composition_task_key + self.input_sub_tasks_keys = input_sub_tasks_keys + self.output_key = output_key + dataframe = storage.read("dataframe") + llm_inputs = self._reformat_prompt(dataframe) + # self.logger.info(f"One of formatted prompts: {llm_inputs[0]}") + llm_outputs = self.llm_serving.generate_from_input(llm_inputs) + # self.logger.info(f"One of LLM outputs: {llm_outputs[0]}") + dataframe[self.output_key] = llm_outputs + storage.write(dataframe) + output_file = storage.write(dataframe) + self.logger.info(f"Results saved to {output_file}") + return [self.output_key] + +@prompt_restrict( + ConversationUserPrompt, + ConversationAssistantPrompt, + ConversationToolPrompt +) + +@OPERATOR_REGISTRY.register() +class MultiTurnConversationGenerator(OperatorABC): + def __init__(self, llm_serving: LLMServingABC): + self.llm_serving = llm_serving + self.user_prompt = ConversationUserPrompt() + self.assistant_prompt = ConversationAssistantPrompt() + self.tool_prompt = ConversationToolPrompt() + self.logger = get_logger() + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "根据组合任务及其子任务函数,使用LLM服务模拟多轮对话过程," + "由User、Assistant和Tool三个Agent协同生成完整的对话数据。\n" + "输入参数:\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口\n" + "- input_task_key:任务字段名(组合任务)\n" + "- input_sub_tasks_keys:子任务字段名列表\n" + "- input_functions_key:子任务函数字段名\n" + "- output_conversations_key:输出对话字段名,默认'conversations'\n" + "输出参数:\n" + "- 包含已完成的多轮对话记录的DataFrame\n" + "- 输出字段名(对话字段名)" + ) + elif lang == "en": + return ( + "Simulate multi-turn conversations based on composition tasks and their sub-task functions using an LLM service.\n" + "The process involves three agents: User, Assistant, and Tool, interacting to complete the conversation.\n" + "Input Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC interface\n" + "- input_task_key: Field name for the main task (composition task)\n" + "- input_sub_tasks_keys: List of field names for sub-tasks\n" + "- input_functions_key: Field name containing sub-task functions\n" + "- output_conversations_key: Field name for storing the generated conversations, default 'conversations'\n" + "Output Parameters:\n" + "- DataFrame containing multi-turn conversations with completed sessions\n" + "- Output field name for the conversation content" + ) + else: + return "Generate multi-turn dialogues from composition tasks and functions using user, assistant, and tool agents." + + def _reformat_user_agent_prompt(self, dataframe: pd.DataFrame): + user_agent_prompts = [] + for item in tqdm(dataframe[self.input_task_key], desc="Reformatting prompts..."): + user_agent_prompts.append(self.user_prompt.build_prompt(task=item)) + return user_agent_prompts + + def _reformat_assistant_agent_prompt(self, user_agent_prompts: list[str], dataframe: pd.DataFrame): + assistant_agent_sys_prompts = [] + for sub_tasks, functions in zip(dataframe[self.input_sub_tasks_keys].to_dict(orient='records'), dataframe[self.input_functions_key]): + assistant_agent_sys_prompts.append(self.assistant_prompt.build_prompt(sub_task=sub_tasks, sub_task_func=functions)) + assistant_agent_user_inputs = user_agent_prompts + inputs = [[{"role": "system", "content": sys_prompt}, {"role": "user", "content": user_input}] for sys_prompt, user_input in zip(assistant_agent_sys_prompts, assistant_agent_user_inputs)] + return inputs + + def _reformat_tool_agent_prompt(self, func_calls: list[str]): + tool_agent_prompts = [] + for func_call in func_calls: + tool_agent_prompts.append(self.tool_prompt.build_prompt(function=func_call)) + return tool_agent_prompts + + def run(self, storage: DataFlowStorage, input_task_key: str, input_sub_tasks_keys: list[str], input_functions_key: list[str], output_conversations_key: str = "conversations"): + self.input_task_key = input_task_key + self.input_sub_tasks_keys = input_sub_tasks_keys + self.input_functions_key = input_functions_key + self.output_user_agent_response_key = "user_response" + self.output_key = output_conversations_key + dataframe = storage.read("dataframe") + + user_agent_prompts = self._reformat_user_agent_prompt(dataframe) + user_agent_responses = self.llm_serving.generate_from_input(user_agent_prompts) + + dataframe[self.output_user_agent_response_key] = user_agent_responses + turns = 0 + completed_label = [0] * len(dataframe) + valid_label = [0] * len(dataframe) + cur_conversations = self._reformat_assistant_agent_prompt(user_agent_responses, dataframe) + while True: + assistant_agent_inputs = cur_conversations + not_completed_idxs = np.where(np.array(completed_label) == 0)[0] + valid_idxs = np.where(np.array(valid_label) == 0)[0] + cur_chatting_idxs = np.intersect1d(not_completed_idxs, valid_idxs) + cur_chatting_conversations = [assistant_agent_inputs[idx] for idx in cur_chatting_idxs] + assistant_agent_outputs = self.llm_serving.generate_from_conversations(cur_chatting_conversations) + new_assistant_agent_outputs = list(zip(cur_chatting_idxs, assistant_agent_outputs)) + + func_call_pattern = r"(.*?)" + func_calls = [] + final_answer_pattern = r"(.*?)" + for idx, text in new_assistant_agent_outputs: + if isinstance(text, str): + final_match = re.search(final_answer_pattern, text, re.DOTALL) + else: + self.logger.warning("Warning: 'text' is not a string:", text) + final_match = None + valid_label[idx] = 1 + continue + final_match = re.search(final_answer_pattern, text, re.DOTALL) + if final_match: + completed_label[idx] = 1 + self.logger.info(f"Final answer found: {idx}") + continue + func_match = re.search(func_call_pattern, text, re.DOTALL) + if func_match: + result = func_match.group(1) + func_calls.append(f"{result}") + else: + func_calls.append("") + + + for item, text in zip(cur_chatting_conversations, assistant_agent_outputs): + item.append({"role": "assistant", "content": text}) + + not_completed_idxs = np.where(np.array(completed_label) == 0)[0] + valid_idxs = np.where(np.array(valid_label) == 0)[0] + cur_chatting_idxs = np.intersect1d(not_completed_idxs, valid_idxs) + cur_chatting_conversations = [assistant_agent_inputs[idx] for idx in cur_chatting_idxs] + tool_agent_inputs = self._reformat_tool_agent_prompt(func_calls) + tool_agent_outputs = self.llm_serving.generate_from_input(tool_agent_inputs) + for item, text in zip(cur_chatting_conversations, tool_agent_outputs): + item.append({"role": "assistant", "content": text}) + turns += 1 + if turns >= 5: + break + self.logger.info(f"Bad answer {np.where(np.array(completed_label) == 0)[0]}") + dataframe[self.output_key] = cur_conversations + dataframe = dataframe[np.array(completed_label) == 1] + storage.write(dataframe) + return self.output_key + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_speech/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_speech/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1b52265192c65757ac1bf5d23bd2e37256a41796 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_speech/__init__.py @@ -0,0 +1,14 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + # generate + from .generate.speech2text_generator import Speech2TextGenerator +else: + import sys + from dataflow.utils.registry import LazyLoader, generate_import_structure_from_type_checking + + cur_path = "dataflow/operators/core_speech/" + + + _import_structure = generate_import_structure_from_type_checking(__file__, cur_path) + sys.modules[__name__] = LazyLoader(__name__, "dataflow/operators/core_speech/", _import_structure) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_speech/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_speech/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52ed202df16022df1d96857c107896d688fcce9f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_speech/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_speech/generate/__pycache__/speech2text_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_speech/generate/__pycache__/speech2text_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f214af7af27a9ddad0645ff433a2bfb2230e3153 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_speech/generate/__pycache__/speech2text_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_speech/generate/speech2text_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_speech/generate/speech2text_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..adafbd72d4b808b419448032bcfa429ff156405e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_speech/generate/speech2text_generator.py @@ -0,0 +1,81 @@ +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger + +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC + +import os +import math +import warnings +import base64 +from io import BytesIO +from typing import List, Optional, Union, Dict, Tuple + +@OPERATOR_REGISTRY.register() +class Speech2TextGenerator(OperatorABC): + def __init__( + self, + llm_serving: LLMServingABC, + system_prompt: str = "You are a helpful assistant", + ): + self.logger = get_logger() + self.llm_serving = llm_serving + self.system_prompt = system_prompt + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于将语音内容转录为文本。它接收语音文件路径或URL,使用大语言模型进行转录," + "并将转录结果保存到数据框中。\n" + "输入参数:\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口\n" + "- system_prompt:系统提示词,用于定义模型行为,默认为'You are a helpful assistant'\n" + "- input_key:输入语音文件路径或URL的字段名,默认为'raw_content'\n" + "- output_key:输出转录文本的字段名,默认为'generated_content'\n" + "输出参数:\n" + "- 返回输出字段名,用于后续算子引用\n" + "- 在数据框中添加包含转录文本的新列" + ) + elif lang == "en": + return ( + "This operator transcribes speech content into text. It receives paths or URLs to speech files, " + "uses a large language model for transcription, and saves the transcription results to the dataframe.\n" + "Input Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC interface\n" + "- system_prompt: System prompt to define model behavior, default is 'You are a helpful assistant'\n" + "- input_key: Field name for input speech file paths or URLs, default is 'raw_content'\n" + "- output_key: Field name for output transcription text, default is 'generated_content'\n\n" + "Output Parameters:\n" + "- Returns output field name for subsequent operator reference\n" + "- Adds a new column containing transcription text to the dataframe" + ) + else: + return ( + "SpeechTranscriptor converts speech files to text using a large language model and saves results to a dataframe." + ) + + def run(self, storage: DataFlowStorage, input_key: str = "raw_content", output_key: str = "generated_content"): + self.input_key, self.output_key = input_key, output_key + self.logger.info("Running Speech Transcriptor...") + + dataframe = storage.read('dataframe') + self.logger.info(f"Loading, number of rows: {len(dataframe)}") + + llm_inputs = [] + for index, row in dataframe.iterrows(): + path_or_url = row.get(self.input_key, '') + llm_inputs.append(path_or_url) + + transcriptions = self.llm_serving.generate_from_input( + user_inputs=llm_inputs, + system_prompt=self.system_prompt + ) + + dataframe[self.output_key] = transcriptions + output_file = storage.write(dataframe) + self.logger.info(f"Saving to {output_file}") + self.logger.info("Speech Transcriptor done") + + return output_key diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c9429092c8d3c25f1c437fefee1e5ef945975b9b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/__init__.py @@ -0,0 +1,30 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from .generate.prompted_generator import PromptedGenerator + from .generate.chunked_prompted_generator import ChunkedPromptedGenerator + from .generate.format_str_prompted_generator import FormatStrPromptedGenerator + from .generate.random_domain_knowledge_row_generator import RandomDomainKnowledgeRowGenerator + from .generate.text2qa_generator import Text2QAGenerator + from .generate.text2multihopqa_generator import Text2MultiHopQAGenerator + from .generate.embedding_generator import EmbeddingGenerator + from .generate.retrieval_generator import RetrievalGenerator + from .generate.bench_answer_generator import BenchAnswerGenerator + from .eval.bench_dataset_evaluator import BenchDatasetEvaluator + from .eval.bench_dataset_evaluator_question import BenchDatasetEvaluatorQuestion + from .eval.unified_bench_dataset_evaluator import UnifiedBenchDatasetEvaluator + from .eval.text2qa_sample_evaluator import Text2QASampleEvaluator + from .eval.prompted_eval import PromptedEvaluator + from .filter.prompted_filter import PromptedFilter + from .filter.kcentergreedy_filter import KCenterGreedyFilter + from .filter.general_filter import GeneralFilter + from .refine.prompted_refiner import PromptedRefiner + from .refine.pandas_operator import PandasOperator +else: + import sys + from dataflow.utils.registry import LazyLoader, generate_import_structure_from_type_checking + + cur_path = "dataflow/operators/core_text/" + + _import_structure = generate_import_structure_from_type_checking(__file__, cur_path) + sys.modules[__name__] = LazyLoader(__name__, "dataflow/operators/core_text/", _import_structure) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da971e3eb0f6e8a99549e963f18a85bdf4fcbcf9 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/__pycache__/bench_dataset_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/__pycache__/bench_dataset_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ffd725e0a9944d73493a60a29f82646a773497a7 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/__pycache__/bench_dataset_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/__pycache__/bench_dataset_evaluator_question.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/__pycache__/bench_dataset_evaluator_question.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5840df610846e2ee9687d13330f5ed6997d18180 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/__pycache__/bench_dataset_evaluator_question.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/__pycache__/prompted_eval.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/__pycache__/prompted_eval.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b45c0f21539212acac2ec09361013e79aca3ae4 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/__pycache__/prompted_eval.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/__pycache__/text2qa_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/__pycache__/text2qa_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..456c89a0d8ca962499a296706ad026beb10c90de Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/__pycache__/text2qa_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/__pycache__/unified_bench_dataset_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/__pycache__/unified_bench_dataset_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97ed0f8327e7856a79afb941872deb63a95dffb9 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/__pycache__/unified_bench_dataset_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/bench_dataset_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/bench_dataset_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..9c1a19c92ef7b95954ed0b123a68d6862d1206ec --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/bench_dataset_evaluator.py @@ -0,0 +1,205 @@ +from dataflow.utils.reasoning.AnswerExtraction import StringCleaner, UnitTextManager, AnswerExtractor +from dataflow.prompts.model_evaluation.general import AnswerJudgePrompt +from dataflow.core.prompt import DIYPromptABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import LLMServingABC +from dataflow.core import OperatorABC +from dataflow.core.prompt import prompt_restrict + +from math_verify import parse, verify +from dataflow import get_logger +from typing import Literal, Union +import pandas as pd +import numpy as np +import time +import os +import re + +@prompt_restrict( + AnswerJudgePrompt +) + +@OPERATOR_REGISTRY.register() +class BenchDatasetEvaluator(OperatorABC): + def __init__(self, + eval_result_path: str = None, + compare_method: Literal["match", "semantic"] = "match", + system_prompt: str = "You are a helpful assistant specialized in evaluating answer correctness.", + llm_serving: LLMServingABC = None, + prompt_template: Union[AnswerJudgePrompt, DIYPromptABC] = AnswerJudgePrompt): + + if eval_result_path is None: + timestamp = int(time.time()) + eval_result_path = f"result_bencheval/BenchDatasetEvaluator_result_{timestamp}.json" + + self.eval_result_path = eval_result_path + self.compare_method = compare_method + self.empty_responses_count = 0 + + if compare_method == "match": + self.compare = self.math_verify_compare + unit_manager = UnitTextManager() + string_cleaner = StringCleaner(unit_manager) + self.answer_extractor = AnswerExtractor(string_cleaner) + else: + if prompt_template is None: + prompt_template = AnswerJudgePrompt() + self.prompt_template = prompt_template + self.system_prompt = system_prompt + self.llm_serving = llm_serving + + self.logger = get_logger() + + def math_verify_compare(self, answer, ground_truth): + try: + return verify(parse(str(ground_truth)), parse(str(answer))) + except Exception: + try: + return verify(parse(ground_truth), parse(answer)) + except Exception: + return False + + def ResolveResponse(self, response): + if response is None or (isinstance(response, str) and response.strip() == ''): + self.empty_responses_count += 1 + return False + try: + pattern = re.compile(r'"judgement_result"\s*:\s*(true|false)', re.IGNORECASE) + match = pattern.search(response) + result_value = None + if match: + result_value = match.group(1).lower() + else: + if "true" in response.lower(): + result_value = "true" + else: + result_value = "false" + return result_value == "true" + except Exception as e: + self.logger.error(f"Response format error: {response}. Error: {e}") + return False + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于对比预测答案与标准答案的匹配度,支持两种评估模式:\n\n" + "1. 字符串匹配(match):使用数学验证方法比较答案,适用于有明确答案的问题\n" + "2. 语义匹配(semantic):使用LLM评估语义相似度,仅输入预测答案与标准答案\n\n" + "输入参数:\n" + "- input_test_answer_key:预测答案字段名\n" + "- input_gt_answer_key:标准答案字段名\n" + "- compare_method:比较方法(match/semantic)\n\n" + "输出参数:\n" + "- answer_match_result:匹配结果(True/False)\n" + "- 统计结果将保存到指定的eval_result_path路径\n" + ) + else: + return ( + "This operator compares predicted answers against ground truth using two evaluation modes:\n\n" + "1. String Matching (match): Mathematical verification for exact answers.\n" + "2. Semantic Matching (semantic): LLM-based evaluation comparing predicted vs ground truth answers only.\n\n" + "Input Parameters:\n" + "- input_test_answer_key: Predicted answer field\n" + "- input_gt_answer_key: Ground truth field\n" + "- compare_method: Comparison method (match/semantic)\n\n" + "Output Parameters:\n" + "- answer_match_result: Boolean match result\n" + "- Statistics are saved to the specified eval_result_path\n" + ) + + def check_column(self, required_columns: list[str], dataframe: pd.DataFrame): + for column in required_columns: + if column not in dataframe.columns: + self.logger.error(f"Required column '{column}' not found in dataframe") + return False + return True + + def statistic(self, file_name_prefix: str, dataframe: pd.DataFrame, compare_method: str): + total_samples = len(dataframe) + valid_samples = len(dataframe) - self.empty_responses_count + matched_samples = sum(dataframe['answer_match_result']) + accuracy = matched_samples / valid_samples if valid_samples > 0 else 0 + + stats = { + "bench_name_or_prefix": file_name_prefix, + "total_samples": total_samples, + "valid_samples": valid_samples, + "matched_samples": matched_samples, + "accuracy": float(accuracy), + "empty_responses_count": self.empty_responses_count, + "compare_method": compare_method + } + + stats_df = pd.DataFrame([stats]) + os.makedirs(os.path.dirname(self.eval_result_path), exist_ok=True) + stats_df.to_json(self.eval_result_path, orient="records", force_ascii=False, indent=2) + self.logger.success(f"Statistics saved to {self.eval_result_path}") + + return stats_df + + def run(self, + storage: DataFlowStorage, + input_test_answer_key: str = "generated_cot", + input_gt_answer_key: str = "golden_answer") -> list: + + dataframe = storage.read("dataframe") + dataframe['answer_match_result'] = False + answers = dataframe[input_test_answer_key] + ground_truths = dataframe[input_gt_answer_key] + + if self.compare_method == "match": + if not self.check_column( + required_columns=[input_test_answer_key, input_gt_answer_key], + dataframe=dataframe + ): + return [input_test_answer_key, input_gt_answer_key] + + for i in range(len(answers)): + final_answer = self.answer_extractor.extract_answer(answers[i], None) + dataframe.at[i, 'answer_match_result'] = self.compare(final_answer, ground_truths[i]) + + storage.write(dataframe) + self.statistic(storage.file_name_prefix, dataframe, self.compare_method) + return [input_test_answer_key, input_gt_answer_key, 'answer_match_result'] + + else: + if not self.check_column( + required_columns=[input_test_answer_key, input_gt_answer_key], + dataframe=dataframe + ): + return [input_test_answer_key, input_gt_answer_key] + + empty_reference_mask = dataframe[input_gt_answer_key].isna() | (dataframe[input_gt_answer_key] == '') + valid_rows = dataframe[~empty_reference_mask] + skipped_count = len(dataframe[empty_reference_mask]) + + if len(valid_rows) == 0: + self.logger.warning("No valid reference answers found. All samples skipped.") + storage.write(dataframe) + return [input_test_answer_key, input_gt_answer_key, 'answer_match_result'] + + # 仅用预测答案与标准答案构建Prompt + inputs = [ + self.prompt_template.build_prompt( + answer=row[input_test_answer_key], + reference_answer=row[input_gt_answer_key] + ) + for _, row in valid_rows.iterrows() + ] + + responses = self.llm_serving.generate_from_input( + user_inputs=inputs, + system_prompt=self.system_prompt + ) + results = [self.ResolveResponse(response) for response in responses] + + for i, idx in enumerate(valid_rows.index): + dataframe.at[idx, 'answer_match_result'] = results[i] + + storage.write(dataframe) + self.statistic(storage.file_name_prefix, dataframe, self.compare_method) + + self.empty_responses_count = 0 + return [input_test_answer_key, input_gt_answer_key, 'answer_match_result'] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/bench_dataset_evaluator_question.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/bench_dataset_evaluator_question.py new file mode 100644 index 0000000000000000000000000000000000000000..fc1199e569249bf68537bc73bac3c41b228610d1 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/bench_dataset_evaluator_question.py @@ -0,0 +1,304 @@ +from email.policy import strict +from dataflow.utils.reasoning.AnswerExtraction import StringCleaner, UnitTextManager, AnswerExtractor +from dataflow.prompts.model_evaluation.general import AnswerJudgePromptQuestion, AnswerJudgeMultipleQuestionsPrompt +from dataflow.core.prompt import DIYPromptABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import LLMServingABC +from dataflow.core import OperatorABC +from dataflow.core.prompt import prompt_restrict + +from math_verify import parse, verify +from dataflow import get_logger +from typing import Literal, Union +import pandas as pd +import numpy as np +import time +import os # 添加os模块导入 +import re +import json +import json5 + +@prompt_restrict( + AnswerJudgePromptQuestion, + AnswerJudgeMultipleQuestionsPrompt +) + +@OPERATOR_REGISTRY.register() +class BenchDatasetEvaluatorQuestion(OperatorABC): + def __init__(self, + eval_result_path: str = None, + compare_method: Literal["match", "semantic"] = "match", + system_prompt: str = "You are a helpful assistant specialized in evaluating answer correctness.", + llm_serving: LLMServingABC = None, + prompt_template: Union[AnswerJudgePromptQuestion, AnswerJudgeMultipleQuestionsPrompt, DIYPromptABC] = AnswerJudgePromptQuestion, + support_subquestions: bool = False + ): + + if eval_result_path is None: + timestamp = int(time.time()) + eval_result_path = f"result_bencheval/BenchDatasetEvaluator_result_{timestamp}.json" + + self.eval_result_path = eval_result_path + self.compare_method = compare_method + self.empty_responses_count = 0 # 添加空响应计数器 + + if compare_method == "match": + self.compare = self.math_verify_compare + unit_manager = UnitTextManager() + string_cleaner = StringCleaner(unit_manager) + self.answer_extractor = AnswerExtractor(string_cleaner) + else: + if prompt_template is None: + prompt_template = AnswerJudgePromptQuestion() if not support_subquestions else AnswerJudgeMultipleQuestionsPrompt() + self.prompt_template = prompt_template + self.system_prompt = system_prompt + self.llm_serving = llm_serving + self.support_subquestions = support_subquestions + + self.logger = get_logger() + + def math_verify_compare(self, answer, ground_truth): + try: + return verify(parse(str(ground_truth)), parse(str(answer))) + except Exception: + try: + return verify(parse(ground_truth), parse(answer)) + except Exception: + return False + + def ResolveResponse(self, response): + # 检查空响应 + if not self.support_subquestions: + if response is None or (isinstance(response, str) and response.strip() == ''): + self.empty_responses_count += 1 + return False + try: + pattern = re.compile(r'"judgement_result"\s*:\s*(true|false)', re.IGNORECASE) + match = pattern.search(response) + result_value = None + if match: + result_value = match.group(1).lower() + else: + # 备用解析逻辑,检查响应中是否包含true或false + if "true" in response.lower(): + result_value = "true" + else: + result_value = "false" + if result_value == "true": + return True + else: + return False + except Exception as e: + self.logger.error(f"Response format error: {response}. Error: {e}") + return False + + if self.support_subquestions: + # 如果支持子问题,假设response是一个列表, 返回正确的数量/总数 + correct_num = 0 + total_num = 0 + try: + response = json5.loads(response, strict=False) # 使用json5解析,允许更宽松的格式 + judgement = response.get("judgement", []) + except Exception as e: + self.logger.error(f"Response JSON parse error: {response}. Error: {e}") + self.empty_responses_count += 1 + return "0/0" + for resp in judgement: + if isinstance(resp, bool): + if resp is True: + correct_num += 1 + total_num += 1 + elif resp is False: + total_num += 1 + elif resp.lower() == "empty": + continue # 不计入总数 + elif isinstance(resp, str): + if resp.lower() == "true": + correct_num += 1 + total_num += 1 + elif resp.lower() == "false": + total_num += 1 + elif resp.lower() == "empty": + continue # 不计入总数 + + return f"{correct_num}/{total_num}" + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于对比预测答案与标准答案的匹配度,支持两种评估模式:\n\n" + "1. 字符串匹配(match):使用数学验证方法比较答案,适用于有明确答案的问题\n" + "2. 语义匹配(semantic):使用LLM评估答案的语义相似度,适用于开放性问题\n\n" + "输入参数:\n" + "- input_test_answer_key:预测答案字段名\n" + "- input_gt_answer_key:标准答案字段名\n" + "- input_question_key:问题字段名(语义匹配模式下必需)\n" + "- compare_method:比较方法(match/semantic)\n\n" + "输出参数:\n" + "- answer_match_result:匹配结果(True/False)\n" + "- 统计结果将保存到指定的eval_result_path路径\n" + ) + elif lang == "en": + return ( + "This operator compares predicted answers against ground truth using two evaluation modes:\n\n" + "1. String Matching (match): Uses mathematical verification to compare answers, suitable for questions with definitive answers\n" + "2. Semantic Matching (semantic): Uses LLM to evaluate semantic similarity, suitable for open-ended questions\n\n" + "Input Parameters:\n" + "- input_test_answer_key: Predicted answer field\n" + "- input_gt_answer_key: Ground truth field\n" + "- input_question_key: Question field (required for semantic mode)\n" + "- compare_method: Comparison method (match/semantic)\n\n" + "Output Parameters:\n" + "- answer_match_result: Matching result (True/False)\n" + "- Statistics will be saved to the specified eval_result_path\n" + ) + else: + return "BenchEvaluator performs answer validation using string matching or semantic comparison" + + def check_column(self, required_columns: list[str], dataframe: pd.DataFrame): + for column in required_columns: + if column not in dataframe.columns: + self.logger.error(f"Required column '{column}' not found in dataframe") + return False + return True + + def statistic(self, file_name_prefix: str, dataframe: pd.DataFrame, compare_method: Literal["match", "semantic"]): + total_samples = len(dataframe) + valid_samples = len(dataframe) - self.empty_responses_count + matched_samples = sum(dataframe['answer_match_result']) + accuracy = matched_samples / valid_samples if valid_samples > 0 else 0 + + # 创建统计信息字典 + stats = { + "bench_name_or_prefix": file_name_prefix, + "total_samples": total_samples, + "valid_samples": valid_samples, + "matched_samples": matched_samples, + "accuracy": float(accuracy), # 确保可以被JSON序列化 + "empty_responses_count": self.empty_responses_count, + "compare_method": compare_method + } + + if self.support_subquestions: + total_subquestions = dataframe['total_subquestions'].sum() + correct_subquestions = dataframe['correct_answer_num'].sum() + subquestion_accuracy = correct_subquestions / total_subquestions if total_subquestions > 0 else 0 + stats.update({ + "total_subquestions": int(total_subquestions), + "correct_subquestions": int(correct_subquestions), + "subquestion_accuracy": float(subquestion_accuracy) + }) + + # 将字典转换为DataFrame + stats_df = pd.DataFrame([stats]) + + # 直接将统计信息写入到self.eval_result_path + os.makedirs(os.path.dirname(self.eval_result_path), exist_ok=True) + stats_df.to_json(self.eval_result_path, orient="records", force_ascii=False, indent=2) + self.logger.success(f"Statistics saved to {self.eval_result_path}") + + return stats_df + + def run( + self, + storage:DataFlowStorage, + input_test_answer_key: str = "generated_cot", + input_gt_answer_key: str = "golden_answer", + input_question_key: str = None, + ) -> list: + + self.test_answer_key = input_test_answer_key + self.gt_answer_key = input_gt_answer_key + self.question_key = input_question_key + + dataframe = storage.read("dataframe") + dataframe['answer_match_result'] = False + answers = dataframe[self.test_answer_key] + ground_truths = dataframe[self.gt_answer_key] + + if self.compare_method == "match": + if self.check_column( + required_columns=[input_test_answer_key,input_gt_answer_key], + dataframe=dataframe + ) is False: + return required_columns + + for i in range(len(answers)): + final_answer = self.answer_extractor.extract_answer(answers[i], None) + if self.compare(final_answer, ground_truths[i]): + dataframe.at[i, 'answer_match_result'] = True + else: + dataframe.at[i, 'answer_match_result'] = False + + output_file = storage.write(dataframe) + + # 生成统计信息并直接写入JSON文件 + stats = self.statistic(storage.file_name_prefix, dataframe, self.compare_method) + + return [self.test_answer_key, self.gt_answer_key, 'answer_match_result'] + else: + if self.check_column( + required_columns=[input_test_answer_key,input_gt_answer_key, input_question_key], + dataframe=dataframe + ) is False: + return required_columns + + empty_reference_mask = dataframe[input_gt_answer_key].isna() | (dataframe[input_gt_answer_key] == '') + skipped_rows = dataframe[empty_reference_mask] + valid_rows = dataframe[~empty_reference_mask] + skipped_count = len(skipped_rows) + + if len(valid_rows) == 0: + self.logger.warning("No valid samples with reference answers found. All samples skipped.") + if self.keep_all_samples: + output_file = storage.write(dataframe) # 保留所有行,但answer_match_result都为False + else: + output_file = storage.write(pd.DataFrame(columns=dataframe.columns)) # 不保留任何行 + self.logger.info(f"Dataframe saved to {output_file}. Skipped {skipped_count} samples due to missing reference answers.") + return required_columns + ['answer_match_result'] + + # 只对有参考答案的行构建提示词并调用LLM + inputs = [self.prompt_template.build_prompt( + question=row[input_question_key], + answer=row[input_test_answer_key], + reference_answer=row[input_gt_answer_key] + ) for _, row in valid_rows.iterrows()] + + responses = self.llm_serving.generate_from_input(user_inputs=inputs, system_prompt=self.system_prompt) + + # if self.support_subquestions: + # # 每个response是一个列表,连接一个长列表,比如[["true", "false"], ["true"]] -> ["true", "false", "true"] + # responses = [item for sublist in responses for item in sublist] + + results = [self.ResolveResponse(response) for response in responses] + + # 创建结果掩码,与valid_rows长度相同 + result_mask = np.array(results, dtype=bool) + + # 更新有效行的answer_match_result + valid_indices = valid_rows.index + if not self.support_subquestions: + for i, idx in enumerate(valid_indices): + dataframe.at[idx, 'answer_match_result'] = results[i] + else: + for i, idx in enumerate(valid_indices): + correct_answer_num = int(results[i].split('/')[0]) + total_subquestions = int(results[i].split('/')[1]) + dataframe.at[idx, 'correct_answer_num'] = correct_answer_num + dataframe.at[idx, 'total_subquestions'] = total_subquestions + dataframe.at[idx, 'answer_match_result'] = (correct_answer_num == total_subquestions) and (total_subquestions > 0) # 全对为True,否则为False + dataframe.at[idx, 'response_evaluation'] = responses[i] # 保存LLM的原始响应内容 + + output_file = storage.write(dataframe) + + # 生成统计信息并直接写入JSON文件 + stats = self.statistic(storage.file_name_prefix, dataframe, self.compare_method) + + # 重置空响应计数器 + self.empty_responses_count = 0 + + return [input_test_answer_key, input_gt_answer_key, input_question_key, 'answer_match_result'] + + \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/prompted_eval.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/prompted_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..2b304dc11c2c92fc155c284bbbc4c457605cb570 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/prompted_eval.py @@ -0,0 +1,112 @@ +import pandas as pd +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger + +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +import re +@OPERATOR_REGISTRY.register() +class PromptedEvaluator(OperatorABC): + ''' + Answer Generator is a class that generates answers for given questions. + ''' + def __init__(self, llm_serving: LLMServingABC, system_prompt: str = "Please evaluate the quality of this data on a scale from 1 to 5."): + self.logger = get_logger() + self.llm_serving = llm_serving + self.system_prompt = system_prompt + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "PromptedEvaluator:使用 LLM 根据系统提示词对数据质量进行评分,并将评分写回 DataFrame(同时通过 " + "storage 持久化)。模型应只输出分数(整数)。\n" + "功能:对每行输入文本生成一个评分。\n" + "输入参数:\n" + "- llm_serving:LLM 服务对象,需实现 LLMServingABC 接口。\n" + "- system_prompt:系统提示词(默认:'Please evaluate the quality of this data on a scale from 1 to 5.')。\n" + "- input_key:输入文本所在列名(默认:'raw_content')。\n" + "- output_key:评分结果写入的列名(默认:'eval')。\n" + "输出:\n" + "- 返回输出列名(用于后续算子引用),评分结果已写回并保存。" + ) + elif lang == "en": + return ( + "PromptedEvaluator: uses an LLM to rate data quality and writes the score back to the " + "DataFrame (persisted via storage). The model is expected to output only the integer score.\n" + "Purpose: for each input row, produce an score.\n" + "Input Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC.\n" + "- system_prompt: system prompt (default: 'Please evaluate the quality of this data on a scale from 1 to 5.').\n" + "- input_key: column name containing input text (default: 'raw_content').\n" + "- output_key: column name to store scores (default: 'eval').\n" + "Output:\n" + "- Returns the output column name for downstream operators; the scored DataFrame is saved." + ) + else: + return "PromptedEvaluator rates data quality (1–5) from input text and stores the integer score." + + def _parse_scores(self, outputs: list[str]) -> list[int]: + """ + 将模型输出的分数字符串转为整数。 + - 成功提取到 1–5 范围内的分数 → 返回该分数 + - 提取失败或不合法 → 返回 0 + """ + results = [] + for out in outputs: + score = 0 + try: + if out is None: + results.append(0) + continue + + text = str(out).strip() + + # 用正则找第一个数字 + match = re.search(r"\d+", text) + if match: + val = int(match.group()) + if 1 <= val <= 5: + score = val + # 否则默认 0 + except Exception: + score = 0 + + results.append(score) + return results + + def eval(self, dataframe, input_key): + llm_inputs = [] + for index, row in dataframe.iterrows(): + raw_content = row.get(input_key, '') + if raw_content: + llm_input = self.system_prompt + str(raw_content) + 'Please only output the score!' + llm_inputs.append(llm_input) + + try: + self.logger.info("Generating text using the model...") + generated_outputs = self.llm_serving.generate_from_input(llm_inputs) + scores = self._parse_scores(generated_outputs) + self.logger.info("Text generation completed.") + except Exception as e: + self.logger.error(f"Error during text generation: {e}") + return + return scores + + def run(self, storage: DataFlowStorage, input_key: str = "raw_content", output_key: str = "eval"): + self.logger.info("Running PromptGenerator...") + + # Load the raw dataframe from the input file + dataframe = storage.read('dataframe') + self.logger.info(f"Loading, number of rows: {len(dataframe)}") + + # Create a list to hold all generated questions and answers + generated_outputs = self.eval(dataframe, input_key) + + # Add the generated content back to the dataframe + dataframe[output_key] = generated_outputs + + # Save the updated dataframe to the output file + output_file = storage.write(dataframe) + return output_key diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/text2qa_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/text2qa_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..796d18ae1d869e60723cb88b14949b1f210ef1a5 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/text2qa_sample_evaluator.py @@ -0,0 +1,174 @@ +import pandas as pd +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +import re +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +from dataflow.core.prompt import prompt_restrict + +from dataflow.prompts.text2qa import ( + Text2QAQuestionQualityPrompt, + Text2QAAnswerAlignmentPrompt, + Text2QAAnswerVerifiabilityPrompt, + Text2QADownstreamValuePrompt +) + +@prompt_restrict( + Text2QAQuestionQualityPrompt, + Text2QAAnswerAlignmentPrompt, + Text2QAAnswerVerifiabilityPrompt, + Text2QADownstreamValuePrompt +) +@OPERATOR_REGISTRY.register() +class Text2QASampleEvaluator(OperatorABC): + ''' + Answer Generator is a class that generates answers for given questions. + ''' + def __init__(self, + llm_serving: LLMServingABC, + # prompt_template = None # prompt is fix + ): + self.logger = get_logger() + self.llm_serving = llm_serving + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于为给的的文档片段生成种子QA对打分\n\n" + "输入参数:\n" + "- input_question_key: Field name containing the generated question\n" + "- input_answer_key: Field name containing the generated answer\n" + "- output_question_quality_key: Field name containing the question quality grade\n" + "- output_question_quality_feedback_key: Field name containing the question quality feedback\n" + "- output_answer_alignment_key: Field name containing the answer alignment grade\n" + "- output_answer_alignment_feedback_key: Field name containing the answer alignment feedback\n" + "- output_answer_verifiability_key: Field name containing the answer verifiability grade\n" + "- output_downstream_value_key: Field name containing the downstream value grade\n" + "- output_downstream_value_feedback_key: Field name containing the downstream value feedback\n" + ) + elif lang == "en": + return ( + "This operator generates prompts for given document fragments to generate seed QA pairs.\n\n" + "Input Parameters:\n" + "- input_question_key: Field name containing the generated question\n" + "- input_answer_key: Field name containing the generated answer\n" + "- output_question_quality_key: Field name containing the question quality grade\n" + "- output_question_quality_feedback_key: Field name containing the question quality feedback\n" + "- output_answer_alignment_key: Field name containing the answer alignment grade\n" + "- output_answer_alignment_feedback_key: Field name containing the answer alignment feedback\n" + "- output_answer_verifiability_key: Field name containing the answer verifiability grade\n" + "- output_downstream_value_key: Field name containing the downstream value grade\n" + "- output_downstream_value_feedback_key: Field name containing the downstream value feedback\n" + ) + else: + return "QAScorer scores QA pairs for given document fragments." + + def _validate_dataframe(self, dataframe: pd.DataFrame): + required_keys = [self.input_question_key, self.input_answer_key] + forbidden_keys = [self.output_question_quality_key, self.output_question_quality_feedback_key, self.output_answer_alignment_key, self.output_answer_alignment_feedback_key, self.output_answer_verifiability_key, self.output_answer_verifiability_feedback_key, self.output_downstream_value_key, self.output_downstream_value_feedback_key] + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + raise ValueError(f"Missing required column(s): {missing}") + if conflict: + raise ValueError(f"The following column(s) already exist and would be overwritten: {conflict}") + + def _build_prompts(self, dataframe): + """ + Reformat the prompts in the dataframe to generate questions. + """ + question_quality_inputs = [] + self.prompts = Text2QAQuestionQualityPrompt() + question_quality_prompt = self.prompts.build_prompt() + answer_alignment_inputs = [] + self.prompts = Text2QAAnswerAlignmentPrompt() + answer_alignment_prompt = self.prompts.build_prompt() + answer_verifiability_inputs = [] + self.prompts = Text2QAAnswerVerifiabilityPrompt() + answer_verifiability_prompt = self.prompts.build_prompt() + downstream_value_inputs = [] + self.prompts = Text2QADownstreamValuePrompt() + downstream_value_prompt = self.prompts.build_prompt() + + for index, row in dataframe.iterrows(): + question_quality_content = question_quality_prompt + "Question: " + row[self.input_question_key] + "\n" + "Answer: " + row[self.input_answer_key] + question_quality_inputs.append(question_quality_content) + answer_alignment_content = answer_alignment_prompt + "Question: " + row[self.input_question_key] + "\n" + "Answer: " + row[self.input_answer_key] + answer_alignment_inputs.append(answer_alignment_content) + answer_verifiability_content = answer_verifiability_prompt + "Question: " + row[self.input_question_key] + "\n" + "Answer: " + row[self.input_answer_key] + answer_verifiability_inputs.append(answer_verifiability_content) + downstream_value_content = downstream_value_prompt + "Question: " + row[self.input_question_key] + "\n" + "Answer: " + row[self.input_answer_key] + downstream_value_inputs.append(downstream_value_content) + + return question_quality_inputs, answer_alignment_inputs, answer_verifiability_inputs, downstream_value_inputs + + def _parse_grade_and_feedback(self, response: str) -> tuple: + grading_match = re.search(r"\*\*Grading\*\*:\s*(\d+)", response) + feedback_match = re.search(r"\*\*Feedback\*\*:\s*(.+)", response, re.DOTALL) + grading = float(grading_match.group(1)) if grading_match else 0 + feedback = feedback_match.group(1).strip() if feedback_match else '' + + return grading, feedback + + def run( + self, + storage: DataFlowStorage, + input_question_key: str = "generated_question", + input_answer_key: str = "generated_answer", + output_question_quality_key: str = "question_quality_grades", + output_question_quality_feedback_key: str = "question_quality_feedbacks", + output_answer_alignment_key: str = "answer_alignment_grades", + output_answer_alignment_feedback_key: str = "answer_alignment_feedbacks", + output_answer_verifiability_key: str = "answer_verifiability_grades", + output_answer_verifiability_feedback_key: str = "answer_verifiability_feedbacks", + output_downstream_value_key: str = "downstream_value_grades", + output_downstream_value_feedback_key: str = "downstream_value_feedbacks" + ): + self.input_question_key, self.input_answer_key, self.output_question_quality_key, self.output_question_quality_feedback_key, self.output_answer_alignment_key, self.output_answer_alignment_feedback_key, self.output_answer_verifiability_key, self.output_answer_verifiability_feedback_key, self.output_downstream_value_key, self.output_downstream_value_feedback_key = input_question_key, input_answer_key, output_question_quality_key, output_question_quality_feedback_key, output_answer_alignment_key, output_answer_alignment_feedback_key, output_answer_verifiability_key, output_answer_verifiability_feedback_key, output_downstream_value_key, output_downstream_value_feedback_key + + dataframe = storage.read("dataframe") + self._validate_dataframe(dataframe) + + # 构建prompt + q_inputs, a_inputs, v_inputs, d_inputs = self._build_prompts(dataframe) + + # 生成四类分数和反馈 + self.logger.info("Scoring question quality...") + q_scores = self.llm_serving.generate_from_input(user_inputs=q_inputs, system_prompt="") + q_grades, q_feedbacks = zip(*[self._parse_grade_and_feedback(r) for r in q_scores]) + + self.logger.info("Scoring answer alignment...") + a_scores = self.llm_serving.generate_from_input(user_inputs=a_inputs, system_prompt="") + a_grades, a_feedbacks = zip(*[self._parse_grade_and_feedback(r) for r in a_scores]) + + self.logger.info("Scoring answer verifiability...") + v_scores = self.llm_serving.generate_from_input(user_inputs=v_inputs, system_prompt="") + v_grades, v_feedbacks = zip(*[self._parse_grade_and_feedback(r) for r in v_scores]) + + self.logger.info("Scoring downstream value...") + d_scores = self.llm_serving.generate_from_input(user_inputs=d_inputs, system_prompt="") + d_grades, d_feedbacks = zip(*[self._parse_grade_and_feedback(r) for r in d_scores]) + + # 写回结果 + dataframe[self.output_question_quality_key] = q_grades + dataframe[self.output_question_quality_feedback_key] = q_feedbacks + dataframe[self.output_answer_alignment_key] = a_grades + dataframe[self.output_answer_alignment_feedback_key] = a_feedbacks + dataframe[self.output_answer_verifiability_key] = v_grades + dataframe[self.output_answer_verifiability_feedback_key] = v_feedbacks + dataframe[self.output_downstream_value_key] = d_grades + dataframe[self.output_downstream_value_feedback_key] = d_feedbacks + + output_file = storage.write(dataframe) + self.logger.info(f"Results saved to {output_file}") + + return [ + output_question_quality_key, output_question_quality_feedback_key, + output_answer_alignment_key, output_answer_alignment_feedback_key, + output_answer_verifiability_key, output_answer_verifiability_feedback_key, + output_downstream_value_key, output_downstream_value_feedback_key + ] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/unified_bench_dataset_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/unified_bench_dataset_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..c90d721ced520894ca6d3fc99183660d1abfc824 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/eval/unified_bench_dataset_evaluator.py @@ -0,0 +1,1455 @@ +import json +import os +import re +import time +import unicodedata +from dataclasses import dataclass +from typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Union +import numpy as np +import pandas as pd +from math_verify import parse, verify +import torch +import torch.nn.functional as F +from transformers import AutoModelForCausalLM, AutoTokenizer + +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.core.prompt import DIYPromptABC +from dataflow.core.prompt import prompt_restrict +from dataflow.prompts.model_evaluation.general import AnswerJudgePrompt +from dataflow.core import LLMServingABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.reasoning.AnswerExtraction import StringCleaner, UnitTextManager, AnswerExtractor + + +@prompt_restrict( + AnswerJudgePrompt +) + +@OPERATOR_REGISTRY.register() +class UnifiedBenchDatasetEvaluator(OperatorABC): + """ + 统一 Bench 评测算子:支持 6 类 keys-type + metric。 + + 评测类型 (bench_dataflow_eval_type): (详见doc) + - key1_text_score + - key2_qa + - key2_q_ma + - key3_q_choices_a + - key3_q_choices_as + - key3_q_a_rejected + + 核心思想: + 只需要传 bench_dataflow_eval_type + metric_type + input_xxx_key + (可选) context_key + - evaluator 内部负责: + 1) 读取 dataframe + 2) 取 keys + 3) 组装 prompt(用 prompt_template 或默认模板) + 4) 计算 metric + 5) 写回结果列 + 统计落盘 + """ + + # ----------------------------- + # 构造 + # ----------------------------- + def __init__( + self, + eval_result_path: Optional[str] = None, + eval_type: Literal[ + "key1_text_score", + "key2_qa", + "key2_q_ma", + "key3_q_choices_a", + "key3_q_choices_as", + "key3_q_a_rejected", + ] = "key2_qa", + llm_serving: Optional[LLMServingABC] = None, + prompt_template: Union[AnswerJudgePrompt, DIYPromptABC] = AnswerJudgePrompt, + system_prompt: str = "You are a helpful assistant specialized in evaluating answer correctness.", + metric_type: Optional[str] = None, + use_semantic_judge: bool = False, + ): + if eval_result_path is None: + timestamp = int(time.time()) + eval_result_path = f"result_bencheval/UnifiedBenchDatasetEvaluator_result_{timestamp}.json" + + self.eval_result_path = eval_result_path + self.eval_type = eval_type + self.llm_serving = llm_serving + self.prompt_template = prompt_template + self.system_prompt = system_prompt + self.metric_type = metric_type + self.use_semantic_judge = use_semantic_judge + + unit_manager = UnitTextManager() + string_cleaner = StringCleaner(unit_manager) + self.answer_extractor = AnswerExtractor(string_cleaner) + + self.logger = get_logger() + self.empty_responses_count = 0 + + # ----------------------------- + # 工具函数:列检查 + # ----------------------------- + def _check_columns(self, dataframe: pd.DataFrame, cols: List[str]) -> bool: + ok = True + for c in cols: + if c not in dataframe.columns: + self.logger.error(f"Required column '{c}' not found in dataframe") + ok = False + return ok + + # ----------------------------- + # 工具函数:context 统一拼接 + # ----------------------------- + def _normalize_context(self, ctx: Any) -> Optional[str]: + if ctx is None: + return None + if isinstance(ctx, float) and np.isnan(ctx): + return None + if isinstance(ctx, list): + parts = [] + for x in ctx: + if x is None: + continue + s = str(x).strip() + if s: + parts.append(s) + return "\n".join(parts) if parts else None + s = str(ctx).strip() + return s if s else None + + # ----------------------------- + # 工具函数:默认 prompt(当 prompt_template 不存在或 build_prompt 不可用) + # ----------------------------- + def _default_prompt( + self, + *, + question: Optional[str] = None, + context: Optional[str] = None, + text: Optional[str] = None, + choices: Optional[List[str]] = None, + task: str = "", + ) -> str: + if task == "text_score": + return (text or "").strip() + + ctx_block = f"Context:\n{context}\n\n" if context else "" + q_block = f"Question:\n{(question or '').strip()}\n\n" + + if choices is not None: + # 标准化成 A./B./C. 格式,便于模板替换 & 也便于 fallback 解析 + letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + formatted = [] + for i, ch in enumerate(choices): + tag = letters[i] if i < len(letters) else str(i) + formatted.append(f"{tag}. {str(ch)}") + choices_block = "Choices:\n" + "\n".join(formatted) + "\n\n" + return f"{ctx_block}{q_block}{choices_block}Answer:" + else: + return f"{ctx_block}{q_block}Answer:" + + def _build_prompt( + self, + *, + question: Optional[str] = None, + context: Optional[str] = None, + text: Optional[str] = None, + choices: Optional[List[str]] = None, + task: str = "", + ) -> str: + # 兼容你的 prompt_template(通常有 build_prompt) + if self.prompt_template is not None and hasattr(self.prompt_template, "build_prompt"): + try: + # 给模板更丰富的变量,模板不用可以忽略 + choices_text = None + if choices is not None: + letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + formatted = [] + for i, ch in enumerate(choices): + tag = letters[i] if i < len(letters) else str(i) + formatted.append(f"{tag}. {str(ch)}") + choices_text = "\n".join(formatted) + + return self.prompt_template.build_prompt( + question=question, + context=context, + text=text, + choices=choices, + choices_text=choices_text, + task=task, + ) + except Exception as e: + self.logger.error(f"prompt_template.build_prompt failed, fallback to default. err={e}") + + return self._default_prompt(question=question, context=context, text=text, choices=choices, task=task) + + # ----------------------------- + # math_verify compare + # ----------------------------- + def _try_math_verify_compare(self, answer: Any, ground_truth: Any) -> Optional[bool]: + try: + return verify(parse(str(ground_truth)), parse(str(answer))) + except Exception: + try: + return verify(parse(ground_truth), parse(answer)) + except Exception: + return None + + def _math_verify_compare(self, answer: Any, ground_truth: Any) -> bool: + res = self._try_math_verify_compare(answer, ground_truth) + return bool(res) if res is not None else False + + def _normalize_text_for_match(self, text: Any) -> str: + if text is None: + return "" + s = unicodedata.normalize("NFKC", str(text)) + s = s.translate(str.maketrans({ + "₀": "0", + "₁": "1", + "₂": "2", + "₃": "3", + "₄": "4", + "₅": "5", + "₆": "6", + "₇": "7", + "₈": "8", + "₉": "9", + })) + s = s.strip() + s = re.sub(r"\s+", " ", s) + if s.endswith((".", "。", "!", "!", "?", "?")): + s = s[:-1].strip() + return s.casefold() + + def _text_contains_match(self, pred: Any, ref: Any) -> bool: + p = self._normalize_text_for_match(pred) + r = self._normalize_text_for_match(ref) + if not p or not r: + return False + return (r in p) or (p in r) + + # ----------------------------- + # 多参考答案:把 targets 解析成 List[str] + # ----------------------------- + def _normalize_targets(self, targets: Any) -> List[str]: + if targets is None: + return [] + if isinstance(targets, float) and np.isnan(targets): + return [] + if isinstance(targets, list): + return [str(x) for x in targets if str(x).strip()] + + s = str(targets).strip() + if not s: + return [] + + # 尝试 json list + if (s.startswith("[") and s.endswith("]")) or (s.startswith("{") and s.endswith("}")): + try: + obj = json.loads(s) + if isinstance(obj, list): + return [str(x) for x in obj if str(x).strip()] + except Exception: + pass + + # 常见分隔 + if "||" in s: + parts = [p.strip() for p in s.split("||")] + elif "|" in s: + parts = [p.strip() for p in s.split("|")] + elif ";" in s: + parts = [p.strip() for p in s.split(";")] + else: + parts = [s] + return [p for p in parts if p] + + # ----------------------------- + # choice 解析(fallback 用) + # ----------------------------- + def _parse_choice_from_text(self, text: str, num_choices: int) -> Optional[int]: + if text is None: + return None + t = str(text).strip() + if not t: + return None + + # 先找 A/B/C... + m = re.search(r"\b([A-Za-z])\b", t) + if m: + idx = ord(m.group(1).upper()) - ord("A") + if 0 <= idx < num_choices: + return idx + + # 再找数字(1-based 或 0-based 都兼容) + m = re.search(r"\b(\d+)\b", t) + if m: + val = int(m.group(1)) + if 0 <= val < num_choices: + return val + if 1 <= val <= num_choices: + return val - 1 + + return None + + def _parse_multiselect_set(self, text: str, num_choices: int) -> Optional[set]: + if text is None: + return None + s = str(text).strip() + if not s: + return None + + # json list + if s.startswith("[") and s.endswith("]"): + try: + obj = json.loads(s) + if isinstance(obj, list): + res = set() + for x in obj: + if isinstance(x, str): + x = x.strip() + if len(x) == 1 and x.isalpha(): + idx = ord(x.upper()) - ord("A") + if 0 <= idx < num_choices: + res.add(idx) + elif x.isdigit(): + v = int(x) + if 0 <= v < num_choices: + res.add(v) + elif 1 <= v <= num_choices: + res.add(v - 1) + elif isinstance(x, int): + if 0 <= x < num_choices: + res.add(x) + elif 1 <= x <= num_choices: + res.add(x - 1) + return res + except Exception: + pass + + # 字母集合:如 "A,C,D" / "B D" + letters = re.findall(r"\b([A-Za-z])\b", s) + if letters: + res = set() + for ch in letters: + idx = ord(ch.upper()) - ord("A") + if 0 <= idx < num_choices: + res.add(idx) + return res if res else None + + # 数字集合:如 "1,3,4" + nums = re.findall(r"\b(\d+)\b", s) + if nums: + res = set() + for n in nums: + v = int(n) + if 0 <= v < num_choices: + res.add(v) + elif 1 <= v <= num_choices: + res.add(v - 1) + return res if res else None + + return None + + # ----------------------------- + # micro-F1 / Jaccard + # ----------------------------- + def _set_metrics(self, pred: set, gold: set) -> Dict[str, float]: + if pred is None or gold is None: + return {"precision": 0.0, "recall": 0.0, "f1": 0.0, "jaccard": 0.0, "exact_set": 0.0} + inter = len(pred & gold) + p = inter / len(pred) if len(pred) > 0 else 0.0 + r = inter / len(gold) if len(gold) > 0 else 0.0 + f1 = (2 * p * r / (p + r)) if (p + r) > 0 else 0.0 + j = inter / len(pred | gold) if len(pred | gold) > 0 else 0.0 + exact = 1.0 if pred == gold else 0.0 + return {"precision": float(p), "recall": float(r), "f1": float(f1), "jaccard": float(j), "exact_set": float(exact)} + + # ----------------------------- + # LLM loglikelihood 适配(尽量兼容不同 serving 实现) + # ----------------------------- + def _ll_batch(self, prompts: List[str], continuations: List[str]) -> Optional[List[float]]: + if self.llm_serving is None: + return None + + # 尝试常见方法名 + cand_names = [ + "loglikelihood_batch", + "loglikelihood", + "get_loglikelihood_batch", + "get_loglikelihood", + "score_batch", + "score", + ] + for name in cand_names: + if hasattr(self.llm_serving, name): + fn = getattr(self.llm_serving, name) + try: + # 兼容多种签名: (prompts, continuations) / (pairs) + try: + return fn(prompts=prompts, continuations=continuations) # type: ignore + except TypeError: + try: + return fn(prompts, continuations) # type: ignore + except TypeError: + pairs = list(zip(prompts, continuations)) + return fn(pairs) # type: ignore + except Exception as e: + self.logger.error(f"llm_serving.{name} failed: {e}") + return None + + model_id = getattr(self.llm_serving, "real_model_path", None) or getattr(self.llm_serving, "hf_model_name_or_path", None) + hf_cache_dir = getattr(self.llm_serving, "hf_cache_dir", None) + trust_remote_code = getattr(self.llm_serving, "trust_remote_code", True) + + if model_id is None: + self.logger.error("llm_serving does not expose real_model_path/hf_model_name_or_path; cannot compute loglikelihood.") + return None + + try: + tokenizer = getattr(self, "_ll_hf_tokenizer", None) + model = getattr(self, "_ll_hf_model", None) + loaded_id = getattr(self, "_ll_hf_model_id", None) + if tokenizer is None or model is None or loaded_id != model_id: + tokenizer = AutoTokenizer.from_pretrained(model_id, cache_dir=hf_cache_dir, trust_remote_code=trust_remote_code) + model = AutoModelForCausalLM.from_pretrained(model_id, cache_dir=hf_cache_dir, trust_remote_code=trust_remote_code) + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model.to(device) + model.eval() + self._ll_hf_tokenizer = tokenizer + self._ll_hf_model = model + self._ll_hf_model_id = model_id + except Exception as e: + self.logger.error(f"failed to load hf model/tokenizer for loglikelihood: {e}") + return None + + try: + device = next(model.parameters()).device + pad_id = tokenizer.pad_token_id + if pad_id is None: + pad_id = tokenizer.eos_token_id if tokenizer.eos_token_id is not None else 0 + + batch_size = 4 + lls: List[float] = [] + + def _safe_ids(text: str) -> List[int]: + return tokenizer(text, add_special_tokens=False).input_ids + + for start in range(0, len(prompts), batch_size): + ps = ["" if p is None else str(p) for p in prompts[start:start + batch_size]] + cs = ["" if c is None else str(c) for c in continuations[start:start + batch_size]] + + full_ids_list: List[List[int]] = [] + prompt_lens: List[int] = [] + cont_lens: List[int] = [] + + for p, c in zip(ps, cs): + full_ids = _safe_ids(p + c) + p_ids = _safe_ids(p) + if len(p_ids) <= len(full_ids) and full_ids[:len(p_ids)] == p_ids: + prompt_len = len(p_ids) + else: + c_ids = _safe_ids(c) + prompt_len = max(0, len(full_ids) - len(c_ids)) + cont_len = max(0, len(full_ids) - prompt_len) + full_ids_list.append(full_ids) + prompt_lens.append(prompt_len) + cont_lens.append(cont_len) + + max_len = max((len(x) for x in full_ids_list), default=0) + if max_len == 0: + lls.extend([0.0] * len(full_ids_list)) + continue + + input_ids = torch.full((len(full_ids_list), max_len), pad_id, dtype=torch.long, device=device) + attention_mask = torch.zeros((len(full_ids_list), max_len), dtype=torch.long, device=device) + for i, ids in enumerate(full_ids_list): + if not ids: + continue + t = torch.tensor(ids, dtype=torch.long, device=device) + input_ids[i, : t.numel()] = t + attention_mask[i, : t.numel()] = 1 + + with torch.no_grad(): + logits = model(input_ids=input_ids, attention_mask=attention_mask).logits + log_probs = F.log_softmax(logits, dim=-1) + + shift_log_probs = log_probs[:, :-1, :].contiguous() + shift_labels = input_ids[:, 1:].contiguous() + token_ll = shift_log_probs.gather(-1, shift_labels.unsqueeze(-1)).squeeze(-1) + + for i in range(len(full_ids_list)): + cont_len = cont_lens[i] + prompt_len = prompt_lens[i] + if cont_len <= 0: + lls.append(0.0) + continue + start_pos = max(prompt_len, 1) + end_pos = prompt_len + cont_len + start_idx = start_pos - 1 + end_idx = end_pos - 1 + if end_idx <= start_idx: + lls.append(0.0) + continue + ll_val = float(token_ll[i, start_idx:end_idx].sum().detach().cpu()) + lls.append(ll_val) + + return lls + except Exception as e: + self.logger.error(f"hf loglikelihood computation failed: {e}") + return None + + def _ppl_batch(self, texts: List[str]) -> Optional[List[float]]: + if self.llm_serving is None: + return None + + model_id = getattr(self.llm_serving, "real_model_path", None) or getattr(self.llm_serving, "hf_model_name_or_path", None) + hf_cache_dir = getattr(self.llm_serving, "hf_cache_dir", None) + trust_remote_code = getattr(self.llm_serving, "trust_remote_code", True) + + if model_id is None: + self.logger.error("llm_serving does not expose real_model_path/hf_model_name_or_path; cannot compute ppl.") + return None + + try: + tokenizer = getattr(self, "_ppl_hf_tokenizer", None) + model = getattr(self, "_ppl_hf_model", None) + loaded_id = getattr(self, "_ppl_hf_model_id", None) + if tokenizer is None or model is None or loaded_id != model_id: + tokenizer = AutoTokenizer.from_pretrained(model_id, cache_dir=hf_cache_dir, trust_remote_code=trust_remote_code) + model = AutoModelForCausalLM.from_pretrained(model_id, cache_dir=hf_cache_dir, trust_remote_code=trust_remote_code) + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model.to(device) + model.eval() + self._ppl_hf_tokenizer = tokenizer + self._ppl_hf_model = model + self._ppl_hf_model_id = model_id + except Exception as e: + self.logger.error(f"failed to load hf model/tokenizer for ppl: {e}") + return None + + try: + device = next(model.parameters()).device + batch_size = 4 + ppls: List[float] = [] + max_len = getattr(getattr(model, "config", None), "max_position_embeddings", None) + + for start in range(0, len(texts), batch_size): + batch_texts = ["" if t is None else str(t) for t in texts[start:start + batch_size]] + enc = tokenizer( + batch_texts, + return_tensors="pt", + padding=True, + truncation=True, + max_length=max_len, + ) + input_ids = enc["input_ids"].to(device) + attention_mask = enc.get("attention_mask", None) + if attention_mask is not None: + attention_mask = attention_mask.to(device) + + with torch.no_grad(): + logits = model(input_ids=input_ids, attention_mask=attention_mask).logits + + shift_logits = logits[:, :-1, :].contiguous() + shift_labels = input_ids[:, 1:].contiguous() + + if attention_mask is None: + shift_mask = torch.ones_like(shift_labels, dtype=torch.float32, device=device) + else: + shift_mask = attention_mask[:, 1:].to(dtype=torch.float32) + + vocab_size = shift_logits.size(-1) + token_nll = F.cross_entropy( + shift_logits.view(-1, vocab_size), + shift_labels.view(-1), + reduction="none", + ).view(shift_labels.size(0), -1) + + nll_sum = (token_nll * shift_mask).sum(dim=1) + denom = shift_mask.sum(dim=1).clamp_min(1.0) + ppl_batch = torch.exp(nll_sum / denom).detach().cpu().tolist() + ppls.extend([float(x) for x in ppl_batch]) + + return ppls + except Exception as e: + self.logger.error(f"hf ppl computation failed: {e}") + return None + + # ----------------------------- + # 统计落盘 + # ----------------------------- + def _save_stats(self, bench_name_or_prefix: str, stats: Dict[str, Any]) -> None: + os.makedirs(os.path.dirname(self.eval_result_path), exist_ok=True) + df = pd.DataFrame([stats]) + df.to_json(self.eval_result_path, orient="records", force_ascii=False, indent=2) + self.logger.success(f"Statistics saved to {self.eval_result_path}") + + # ----------------------------- + # 主入口 + # ----------------------------- + def run( + self, + storage: DataFlowStorage, + input_text_key: Optional[str] = None, + input_question_key: Optional[str] = None, + input_target_key: Optional[str] = None, + input_targets_key: Optional[str] = None, + input_choices_key: Optional[str] = None, + input_label_key: Optional[str] = None, + input_labels_key: Optional[str] = None, + input_better_key: Optional[str] = None, + input_rejected_key: Optional[str] = None, + input_context_key: Optional[str] = None, + input_pred_key: str = "generated_ans", + output_eval_valid_key: str = "eval_valid", + output_eval_error_key: str = "eval_error", + output_eval_pred_key: str = "eval_pred", + output_eval_score_key: str = "eval_score", + ) -> List[str]: + """ + 字段列名通过 input_xxx_key 显式传入(未传默认 None): + - key1_text_score: input_text_key + - key2_qa: input_question_key + input_target_key + - key2_q_ma: input_question_key + input_targets_key + - key3_q_choices_a: input_question_key + input_choices_key + input_label_key + - key3_q_choices_as: input_question_key + input_choices_key + input_labels_key + - key3_q_a_rejected: input_question_key + input_better_key + input_rejected_key + """ + df = storage.read("dataframe") + eval_type = self.eval_type + + self.output_eval_valid_key = output_eval_valid_key + self.output_eval_error_key = output_eval_error_key + self.output_eval_pred_key = output_eval_pred_key + self.output_eval_score_key = output_eval_score_key + + # 输出列统一 + if output_eval_valid_key not in df.columns: + df[output_eval_valid_key] = True + df[output_eval_error_key] = "" + df[output_eval_pred_key] = None + df[output_eval_score_key] = np.nan # 数值型评分(accuracy 类用 0/1) + + # 默认 metric + metric_type = self.metric_type + if metric_type is None: + metric_type = self._default_metric_for_type(eval_type, self.use_semantic_judge) + + + # context 处理:统一读一列(可无) + ctx_series = None + if input_context_key is not None: + if input_context_key not in df.columns: + self.logger.error(f"context_key '{input_context_key}' not found; treat as None.") + else: + ctx_series = df[input_context_key] + + # 分发 + if eval_type == "key1_text_score": + text_col = input_text_key or "" + required = [text_col] + if not self._check_columns(df, required): + storage.write(df) + return required + + texts = [str(x) if x is not None else "" for x in df[text_col].tolist()] + ppl = self._ppl_batch(texts) + if ppl is None: + df[output_eval_valid_key] = False + df[output_eval_error_key] = "ppl_unavailable" + storage.write(df) + self._save_stats(storage.file_name_prefix, { + "bench_name_or_prefix": storage.file_name_prefix, + "type": eval_type, + "metric": metric_type, + "total_samples": len(df), + "valid_samples": 0, + "note": "ppl unavailable in llm_serving", + }) + return [text_col, output_eval_score_key, output_eval_valid_key, output_eval_error_key] + + df[output_eval_score_key] = ppl + df[output_eval_pred_key] = None + df[output_eval_valid_key] = True + storage.write(df) + + stats = { + "bench_name_or_prefix": storage.file_name_prefix, + "type": eval_type, + "metric": metric_type, + "total_samples": int(len(df)), + "valid_samples": int(len(df)), + "ppl_mean": float(np.mean(ppl)) if len(ppl) else 0.0, + } + self._save_stats(storage.file_name_prefix, stats) + return [text_col, output_eval_score_key, output_eval_valid_key, output_eval_error_key] + + elif eval_type in ("key2_qa", "key2_q_ma"): + # QA:默认走 math_verify 抽取+对比(可选 semantic_judge) + # 单参考:target + # 多参考:targets + question_col = input_question_key or "" + if eval_type == "key2_qa": + target_col = input_target_key or "" + required = [question_col, target_col, input_pred_key] + if not self._check_columns(df, required): + storage.write(df) + return required + + self._eval_qa_single( + df=df, + question_col=question_col, + target_col=target_col, + pred_col=input_pred_key, + ctx_series=ctx_series, + metric_type=metric_type, + ) + storage.write(df) + + stats = self._stats_for_binary(df) + stats.update({ + "bench_name_or_prefix": storage.file_name_prefix, + "type": eval_type, + "metric": metric_type, + }) + self._save_stats(storage.file_name_prefix, stats) + return [question_col, target_col, input_pred_key, output_eval_score_key, output_eval_valid_key, output_eval_error_key] + + else: + targets_col = input_targets_key or "" + required = [question_col, targets_col, input_pred_key] + if not self._check_columns(df, required): + storage.write(df) + return required + + self._eval_qa_multi( + df=df, + question_col=question_col, + targets_col=targets_col, + pred_col=input_pred_key, + ctx_series=ctx_series, + metric_type=metric_type, + ) + storage.write(df) + + stats = self._stats_for_binary(df) + stats.update({ + "bench_name_or_prefix": storage.file_name_prefix, + "type": eval_type, + "metric": metric_type, + }) + self._save_stats(storage.file_name_prefix, stats) + return [question_col, targets_col, input_pred_key, output_eval_score_key, output_eval_valid_key, output_eval_error_key] + + elif eval_type == "key3_q_choices_a": + question_col = input_question_key or "" + choices_col = input_choices_key or "" + label_col = input_label_key or "" + required = [question_col, choices_col, label_col] + # 若没有 llm_serving,则 fallback 需要 pred_col + if self.llm_serving is None: + required.append(input_pred_key) + + if not self._check_columns(df, required): + storage.write(df) + return required + + self._eval_mc_single( + df=df, + question_col=question_col, + choices_col=choices_col, + label_col=label_col, + ctx_series=ctx_series, + metric_type=metric_type, + pred_col=input_pred_key, + ) + storage.write(df) + + stats = self._stats_for_binary(df) + stats.update({ + "bench_name_or_prefix": storage.file_name_prefix, + "type": eval_type, + "metric": metric_type, + }) + self._save_stats(storage.file_name_prefix, stats) + return [question_col, choices_col, label_col, output_eval_score_key, output_eval_valid_key, output_eval_error_key] + + elif eval_type == "key3_q_choices_as": + question_col = input_question_key or "" + choices_col = input_choices_key or "" + labels_col = input_labels_key or "" + required = [question_col, choices_col, labels_col, input_pred_key] # 先按“解析模型输出集合”实现 + if not self._check_columns(df, required): + storage.write(df) + return required + + self._eval_mc_multi( + df=df, + question_col=question_col, + choices_col=choices_col, + labels_col=labels_col, + pred_col=input_pred_key, + metric_type=metric_type, + ) + storage.write(df) + + stats = self._stats_for_multiselect(df) + stats.update({ + "bench_name_or_prefix": storage.file_name_prefix, + "type": eval_type, + "metric": metric_type, + }) + self._save_stats(storage.file_name_prefix, stats) + return [question_col, choices_col, labels_col, input_pred_key, output_eval_score_key, output_eval_valid_key, output_eval_error_key] + + elif eval_type == "key3_q_a_rejected": + question_col = input_question_key or "" + better_col = input_better_key or "" + rejected_col = input_rejected_key or "" + required = [question_col, better_col, rejected_col] + if not self._check_columns(df, required): + storage.write(df) + return required + + if self.llm_serving is None: + # 这个类型没有 pred_col 可 fallback,只能报错 + self.logger.error("llm_serving is required for pairwise evaluation") + df[output_eval_valid_key] = False + df[output_eval_error_key] = "llm_serving_required_for_pairwise" + storage.write(df) + stats = { + "bench_name_or_prefix": storage.file_name_prefix, + "type": eval_type, + "metric": metric_type, + "total_samples": int(len(df)), + "valid_samples": 0, + "note": "pairwise requires llm_serving loglikelihood", + } + self._save_stats(storage.file_name_prefix, stats) + return required + [output_eval_score_key, output_eval_valid_key, output_eval_error_key] + + self._eval_pairwise( + df=df, + question_col=question_col, + better_col=better_col, + rejected_col=rejected_col, + ctx_series=ctx_series, + metric_type=metric_type, + ) + storage.write(df) + + stats = self._stats_for_binary(df) + stats.update({ + "bench_name_or_prefix": storage.file_name_prefix, + "type": eval_type, + "metric": metric_type, + }) + self._save_stats(storage.file_name_prefix, stats) + return required + [output_eval_score_key, output_eval_valid_key, output_eval_error_key] + + else: + self.logger.error(f"Unknown bench_dataflow_eval_type: {eval_type}") + storage.write(df) + return [output_eval_valid_key, output_eval_error_key, input_pred_key, output_eval_score_key] + + # ----------------------------- + # 默认 metric + # ----------------------------- + def _default_metric_for_type(self, t: str, use_semantic_judge: bool) -> str: + if t == "key1_text_score": + return "ppl" + if t == "key2_qa": + return "semantic_judge" if use_semantic_judge else "math_verify" + if t == "key2_q_ma": + return "any_math_verify" + if t == "key3_q_choices_a": + return "ll_choice_acc" + if t == "key3_q_choices_as": + return "micro_f1" + if t == "key3_q_a_rejected": + return "pairwise_ll_winrate" + return "unknown" + + # ----------------------------- + # 统计:binary(0/1) + # ----------------------------- + def _stats_for_binary(self, df: pd.DataFrame) -> Dict[str, Any]: + output_eval_valid_key = self.output_eval_valid_key + output_eval_score_key = self.output_eval_score_key + + total = len(df) + valid_mask = df[output_eval_valid_key] == True + valid = int(valid_mask.sum()) + # eval_score: 0/1 + if valid > 0: + acc = float(df.loc[valid_mask, output_eval_score_key].mean()) + else: + acc = 0.0 + return { + "total_samples": int(total), + "valid_samples": int(valid), + "accuracy": float(acc), + } + + # ----------------------------- + # 统计:多选(f1/jaccard 等) + # ----------------------------- + def _stats_for_multiselect(self, df: pd.DataFrame) -> Dict[str, Any]: + output_eval_valid_key = self.output_eval_valid_key + output_eval_score_key = self.output_eval_score_key + + total = len(df) + valid_mask = df[output_eval_valid_key] == True + valid = int(valid_mask.sum()) + # eval_score 默认存 f1 + if valid > 0: + f1_mean = float(df.loc[valid_mask, output_eval_score_key].mean()) + else: + f1_mean = 0.0 + # 如果你想要更多维度(jaccard/exact_set),可以从 eval_pred 里扩展存 dict,这里先给最小 + return { + "total_samples": int(total), + "valid_samples": int(valid), + "micro_f1_mean": float(f1_mean), + } + + # ----------------------------- + # key2_qa:单参考 + # ----------------------------- + def _eval_qa_single( + self, + df: pd.DataFrame, + question_col: str, + target_col: str, + pred_col: str, + ctx_series: Optional[pd.Series], + metric_type: str, + ) -> None: + output_eval_valid_key = self.output_eval_valid_key + output_eval_error_key = self.output_eval_error_key + output_eval_pred_key = self.output_eval_pred_key + output_eval_score_key = self.output_eval_score_key + + if metric_type == "semantic_judge": + # 语义 judge 需要 llm_serving.generate_from_input + if self.llm_serving is None or not hasattr(self.llm_serving, "generate_from_input"): + self.logger.error("semantic_judge requires llm_serving.generate_from_input") + df[output_eval_valid_key] = False + df[output_eval_error_key] = "semantic_judge_unavailable" + return + + # 默认用“预测 vs 标准”直接 judge(这里只做通用;可自行替换 AnswerJudgePrompt) + inputs = [] + row_indices = [] + for idx, row in df.iterrows(): + gt = row[target_col] + pred = row[pred_col] + if gt is None or (isinstance(gt, str) and gt.strip() == ""): + df.at[idx, output_eval_valid_key] = False + df.at[idx, output_eval_error_key] = "empty_reference" + continue + if pred is None or (isinstance(pred, str) and pred.strip() == ""): + df.at[idx, output_eval_valid_key] = False + df.at[idx, output_eval_error_key] = "empty_prediction" + continue + + prompt = ( + "You are an evaluator. Decide if the prediction is correct given the reference.\n" + f"Reference:\n{gt}\n\nPrediction:\n{pred}\n\n" + 'Return JSON: {"judgement_result": true/false}' + ) + inputs.append(prompt) + row_indices.append(idx) + + if not inputs: + return + + try: + responses = self.llm_serving.generate_from_input(user_inputs=inputs, system_prompt=self.system_prompt) + except Exception as e: + self.logger.error(f"semantic_judge generate_from_input failed: {e}") + for idx in row_indices: + df.at[idx, output_eval_valid_key] = False + df.at[idx, output_eval_error_key] = "semantic_judge_failed" + return + + for idx, resp in zip(row_indices, responses): + ok = self._resolve_judge_response(resp) + df.at[idx, output_eval_score_key] = 1.0 if ok else 0.0 + df.at[idx, output_eval_pred_key] = None + df.at[idx, output_eval_valid_key] = True + df.at[idx, output_eval_error_key] = "" + + return + + # 默认:math_verify + for idx, row in df.iterrows(): + gt = row[target_col] + pred_raw = row[pred_col] + if gt is None or (isinstance(gt, str) and gt.strip() == ""): + df.at[idx, output_eval_valid_key] = False + df.at[idx, output_eval_error_key] = "empty_reference" + continue + if pred_raw is None or (isinstance(pred_raw, str) and pred_raw.strip() == ""): + df.at[idx, output_eval_valid_key] = False + df.at[idx, output_eval_error_key] = "empty_prediction" + continue + + final_answer = self.answer_extractor.extract_answer(pred_raw, None) + text_ok = self._text_contains_match(pred_raw, gt) or self._text_contains_match(final_answer, gt) + math_res = self._try_math_verify_compare(final_answer, gt) + ok = text_ok or (math_res is True) + df.at[idx, output_eval_score_key] = 1.0 if ok else 0.0 + df.at[idx, output_eval_pred_key] = str(final_answer) if (math_res is True) else str(pred_raw) + df.at[idx, output_eval_valid_key] = True + df.at[idx, output_eval_error_key] = "" + + # ----------------------------- + # key2_q_ma:多参考 + # ----------------------------- + def _eval_qa_multi( + self, + df: pd.DataFrame, + question_col: str, + targets_col: str, + pred_col: str, + ctx_series: Optional[pd.Series], + metric_type: str, + ) -> None: + output_eval_valid_key = self.output_eval_valid_key + output_eval_error_key = self.output_eval_error_key + output_eval_pred_key = self.output_eval_pred_key + output_eval_score_key = self.output_eval_score_key + + # 默认:any_math_verify + for idx, row in df.iterrows(): + targets_raw = row[targets_col] + pred_raw = row[pred_col] + targets = self._normalize_targets(targets_raw) + + if len(targets) == 0: + df.at[idx, output_eval_valid_key] = False + df.at[idx, output_eval_error_key] = "empty_references" + continue + if pred_raw is None or (isinstance(pred_raw, str) and pred_raw.strip() == ""): + df.at[idx, output_eval_valid_key] = False + df.at[idx, output_eval_error_key] = "empty_prediction" + continue + + final_answer = self.answer_extractor.extract_answer(pred_raw, None) + ok_any = False + matched_by_text = False + for gt in targets: + text_ok = self._text_contains_match(pred_raw, gt) or self._text_contains_match(final_answer, gt) + math_res = self._try_math_verify_compare(final_answer, gt) + if text_ok or (math_res is True): + ok_any = True + matched_by_text = matched_by_text or text_ok + break + + df.at[idx, output_eval_score_key] = 1.0 if ok_any else 0.0 + df.at[idx, output_eval_pred_key] = str(pred_raw) if matched_by_text else str(final_answer) + df.at[idx, output_eval_valid_key] = True + df.at[idx, output_eval_error_key] = "" + + # ----------------------------- + # key3_q_choices_a:单选 + # ----------------------------- + def _eval_mc_single( + self, + df: pd.DataFrame, + question_col: str, + choices_col: str, + label_col: str, + ctx_series: Optional[pd.Series], + metric_type: str, + pred_col: str, + ) -> None: + output_eval_valid_key = self.output_eval_valid_key + output_eval_error_key = self.output_eval_error_key + output_eval_pred_key = self.output_eval_pred_key + output_eval_score_key = self.output_eval_score_key + + # 优先:loglikelihood + if metric_type == "ll_choice_acc" and self.llm_serving is not None: + # 批量做:每行要对 choices 逐个算 ll,先实现清晰版(你后面可优化 batching) + for idx, row in df.iterrows(): + q = row[question_col] + choices = row[choices_col] + label = row[label_col] + + if choices is None or (isinstance(choices, float) and np.isnan(choices)): + df.at[idx, output_eval_valid_key] = False + df.at[idx, output_eval_error_key] = "empty_choices" + continue + if not isinstance(choices, list): + # 尝试 json + try: + choices = json.loads(str(choices)) + except Exception: + df.at[idx, output_eval_valid_key] = False + df.at[idx, output_eval_error_key] = "choices_not_list" + continue + if len(choices) == 0: + df.at[idx, output_eval_valid_key] = False + df.at[idx, output_eval_error_key] = "empty_choices" + continue + + ctx = None + if ctx_series is not None: + ctx = self._normalize_context(ctx_series.loc[idx]) + + prompt = self._build_prompt(question=str(q), context=ctx, choices=[str(c) for c in choices], task="mc_single") + + # label 规范化为 idx + gold_idx = self._normalize_label_to_index(label, len(choices)) + if gold_idx is None: + df.at[idx, output_eval_valid_key] = False + df.at[idx, output_eval_error_key] = "invalid_label" + continue + + prompts = [prompt] * len(choices) + conts = [] + for c in choices: + c_str = str(c) + # 常见做法:continuation 前补空格,避免直接拼在 Answer: 后面太粘连 + conts.append((" " + c_str) if (len(prompt) > 0 and not prompt.endswith((" ", "\n"))) else c_str) + + lls = self._ll_batch(prompts, conts) + if lls is None: + df.at[idx, output_eval_valid_key] = False + df.at[idx, output_eval_error_key] = "ll_unavailable" + continue + + pred_idx = int(np.argmax(np.array(lls))) + df.at[idx, output_eval_pred_key] = int(pred_idx) + df.at[idx, output_eval_score_key] = 1.0 if pred_idx == gold_idx else 0.0 + df.at[idx, output_eval_valid_key] = True + df.at[idx, output_eval_error_key] = "" + + return + + # fallback:从 pred_col 解析(generation 输出里抓 A/B/C 或数字) + self.logger.warning("ll_choice_acc unavailable; fallback to parse generated output for single-choice.") + for idx, row in df.iterrows(): + choices = row[choices_col] + label = row[label_col] + pred_text = row[pred_col] if pred_col in df.columns else None + + if choices is None: + df.at[idx, output_eval_valid_key] = False + df.at[idx, output_eval_error_key] = "empty_choices" + continue + if not isinstance(choices, list): + try: + choices = json.loads(str(choices)) + except Exception: + df.at[idx, output_eval_valid_key] = False + df.at[idx, output_eval_error_key] = "choices_not_list" + continue + + gold_idx = self._normalize_label_to_index(label, len(choices)) + pred_idx = self._parse_choice_from_text(str(pred_text), len(choices)) if pred_text is not None else None + if gold_idx is None or pred_idx is None: + df.at[idx, output_eval_valid_key] = False + df.at[idx, output_eval_error_key] = "parse_failed" + continue + + df.at[idx, output_eval_pred_key] = int(pred_idx) + df.at[idx, output_eval_score_key] = 1.0 if pred_idx == gold_idx else 0.0 + df.at[idx, output_eval_valid_key] = True + df.at[idx, output_eval_error_key] = "" + + def _normalize_label_to_index(self, label: Any, n: int) -> Optional[int]: + if label is None: + return None + # 若 label 本身是 int + if isinstance(label, (int, np.integer)): + v = int(label) + if 0 <= v < n: + return v + if 1 <= v <= n: + return v - 1 + return None + s = str(label).strip() + if not s: + return None + # A/B/C + if len(s) == 1 and s.isalpha(): + idx = ord(s.upper()) - ord("A") + return idx if 0 <= idx < n else None + # 数字 + if s.isdigit(): + v = int(s) + if 0 <= v < n: + return v + if 1 <= v <= n: + return v - 1 + return None + + # ----------------------------- + # key3_q_choices_as:多选 + # ----------------------------- + def _eval_mc_multi( + self, + df: pd.DataFrame, + question_col: str, + choices_col: str, + labels_col: str, + pred_col: str, + metric_type: str, + ) -> None: + output_eval_valid_key = self.output_eval_valid_key + output_eval_error_key = self.output_eval_error_key + output_eval_pred_key = self.output_eval_pred_key + output_eval_score_key = self.output_eval_score_key + + # 这里按你说的“先最小落地”:从 pred_col 解析集合 -> micro_f1 + for idx, row in df.iterrows(): + choices = row[choices_col] + gold = row[labels_col] + pred_text = row[pred_col] + + if choices is None: + df.at[idx, output_eval_valid_key] = False + df.at[idx, output_eval_error_key] = "empty_choices" + continue + if not isinstance(choices, list): + try: + choices = json.loads(str(choices)) + except Exception: + df.at[idx, output_eval_valid_key] = False + df.at[idx, output_eval_error_key] = "choices_not_list" + continue + + n = len(choices) + gold_set = self._normalize_multilabel_to_set(gold, n) + pred_set = self._parse_multiselect_set(str(pred_text), n) + + if gold_set is None or pred_set is None: + df.at[idx, output_eval_valid_key] = False + df.at[idx, output_eval_error_key] = "parse_failed" + continue + + m = self._set_metrics(pred_set, gold_set) + # eval_score 默认存 f1(你的上层聚合最常用) + df.at[idx, output_eval_score_key] = float(m["f1"]) + # eval_pred 存更丰富的信息,便于 debug + df.at[idx, output_eval_pred_key] = json.dumps( + {"pred_set": sorted(list(pred_set)), "gold_set": sorted(list(gold_set)), **m}, + ensure_ascii=False, + ) + df.at[idx, output_eval_valid_key] = True + df.at[idx, output_eval_error_key] = "" + + def _normalize_multilabel_to_set(self, labels: Any, n: int) -> Optional[set]: + if labels is None: + return None + if isinstance(labels, float) and np.isnan(labels): + return None + if isinstance(labels, list): + s = set() + for x in labels: + idx = self._normalize_label_to_index(x, n) + if idx is None: + continue + s.add(idx) + return s if len(s) > 0 else set() + + s = str(labels).strip() + if not s: + return None + # json list + if s.startswith("[") and s.endswith("]"): + try: + obj = json.loads(s) + if isinstance(obj, list): + res = set() + for x in obj: + idx = self._normalize_label_to_index(x, n) + if idx is not None: + res.add(idx) + return res + except Exception: + pass + + # 分隔符 + parts = re.split(r"[,\s;/|]+", s) + res = set() + for p in parts: + p = p.strip() + if not p: + continue + idx = self._normalize_label_to_index(p, n) + if idx is not None: + res.add(idx) + return res if len(res) > 0 else set() + + # ----------------------------- + # key3_q_a_rejected:偏好对比 + # ----------------------------- + def _eval_pairwise( + self, + df: pd.DataFrame, + question_col: str, + better_col: str, + rejected_col: str, + ctx_series: Optional[pd.Series], + metric_type: str, + ) -> None: + output_eval_valid_key = self.output_eval_valid_key + output_eval_error_key = self.output_eval_error_key + output_eval_pred_key = self.output_eval_pred_key + output_eval_score_key = self.output_eval_score_key + + # 默认:pairwise_ll_winrate + for idx, row in df.iterrows(): + q = row[question_col] + better = row[better_col] + rej = row[rejected_col] + + if better is None or (isinstance(better, str) and better.strip() == ""): + df.at[idx, output_eval_valid_key] = False + df.at[idx, output_eval_error_key] = "empty_better" + continue + if rej is None or (isinstance(rej, str) and rej.strip() == ""): + df.at[idx, output_eval_valid_key] = False + df.at[idx, output_eval_error_key] = "empty_rejected" + continue + + ctx = None + if ctx_series is not None: + ctx = self._normalize_context(ctx_series.loc[idx]) + + prompt = self._build_prompt(question=str(q), context=ctx, task="pairwise") + + prompts = [prompt, prompt] + conts = [] + better_s = str(better) + rej_s = str(rej) + conts.append((" " + better_s) if (len(prompt) > 0 and not prompt.endswith((" ", "\n"))) else better_s) + conts.append((" " + rej_s) if (len(prompt) > 0 and not prompt.endswith((" ", "\n"))) else rej_s) + + lls = self._ll_batch(prompts, conts) + if lls is None or len(lls) != 2: + df.at[idx, output_eval_valid_key] = False + df.at[idx, output_eval_error_key] = "ll_unavailable" + continue + + win = 1.0 if float(lls[0]) > float(lls[1]) else 0.0 + df.at[idx, output_eval_score_key] = win + df.at[idx, output_eval_pred_key] = json.dumps({"ll_better": float(lls[0]), "ll_rejected": float(lls[1])}, ensure_ascii=False) + df.at[idx, output_eval_valid_key] = True + df.at[idx, output_eval_error_key] = "" + + # ----------------------------- + # 语义 judge 响应解析(兼容你旧逻辑) + # ----------------------------- + def _resolve_judge_response(self, response: Any) -> bool: + if response is None or (isinstance(response, str) and response.strip() == ""): + self.empty_responses_count += 1 + return False + try: + s = str(response) + # 尝试 json + try: + obj = json.loads(s) + if isinstance(obj, dict) and "judgement_result" in obj: + return bool(obj["judgement_result"]) + except Exception: + pass + + pattern = re.compile(r'"judgement_result"\s*:\s*(true|false)', re.IGNORECASE) + m = pattern.search(s) + if m: + return m.group(1).lower() == "true" + # fallback + return ("true" in s.lower()) and ("false" not in s.lower()) + except Exception as e: + self.logger.error(f"Response format error: {response}. Error: {e}") + return False + + # ----------------------------- + # 描述 + # ----------------------------- + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于统一 Bench 评测,支持多种任务范式并将评测结果写回 DataFrame,同时输出整体统计到 eval_result_path。\n\n" + "支持类型与默认 metric:\n" + "- key1_text_score:ppl\n" + "- key2_qa:math_verify(或 use_semantic_judge=True 时 semantic_judge)\n" + "- key2_q_ma:any_math_verify(多参考)\n" + "- key3_q_choices_a:ll_choice_acc(基于 loglikelihood;无 serving 接口时使用 HF forward 计算 ll)\n" + "- key3_q_choices_as:micro_f1(解析多选集合后计算)\n" + "- key3_q_a_rejected:pairwise_ll_winrate(基于 ll 比较 better vs rejected)\n\n" + "初始化参数:\n" + "- eval_result_path:统计结果落盘路径\n" + "- eval_type:评测类型(同上)\n" + "- llm_serving:可选;用于 semantic_judge 或提供模型路径信息以进行 PPL/LL 的 HF 计算\n" + "- prompt_template:提示模板对象(可选;需提供 build_prompt;默认使用 AnswerJudgePrompt)\n" + "- system_prompt:语义评测/judge 的系统提示词\n" + "- metric_type:可选;不传则使用 eval_type 的默认 metric\n" + "- use_semantic_judge:仅对 key2_qa 有效;是否使用语义评测\n\n" + "运行参数:\n" + "- storage:DataFlowStorage\n" + "- input_text_key:文本列名(key1_text_score)\n" + "- input_question_key:问题列名(key2/key3)\n" + "- input_target_key:单个参考答案列名(key2_qa)\n" + "- input_targets_key:多个参考答案列名(key2_q_ma)\n" + "- input_choices_key:选项列名(key3_q_choices_a/key3_q_choices_as)\n" + "- input_label_key:单个标签列名(key3_q_choices_a)\n" + "- input_labels_key:多个标签列名(key3_q_choices_as)\n" + "- input_better_key:优选答案列名(key3_q_a_rejected)\n" + "- input_rejected_key:劣选答案列名(key3_q_a_rejected)\n" + "- input_context_key:可选,上下文字段名\n" + "- input_pred_key:预测答案字段名(默认 generated_ans)\n\n" + "输出:\n" + "- output_eval_score_key(数值分数)\n" + "- output_eval_pred_key(解析后的预测)\n" + "- output_eval_valid_key(是否有效)\n" + "- output_eval_error_key(错误信息)\n" + "- 保存统计:total_samples/valid_samples/accuracy 或 ppl_mean 等到 eval_result_path\n" + "- 返回本次评测涉及/产出的列名列表" + ) + return ( + "This operator evaluates unified bench datasets across multiple task archetypes. It writes per-sample results back to the dataframe and saves aggregated statistics to eval_result_path.\n\n" + "Supported Types (default metric):\n" + "- key1_text_score (ppl)\n" + "- key2_qa (math_verify or semantic_judge)\n" + "- key2_q_ma (any_math_verify)\n" + "- key3_q_choices_a (ll_choice_acc)\n" + "- key3_q_choices_as (micro_f1)\n" + "- key3_q_a_rejected (pairwise_ll_winrate)\n\n" + "Input Parameters:\n" + "- eval_result_path: Path to save aggregated statistics\n" + "- eval_type: Evaluation type (one of the supported types)\n" + "- llm_serving: Optional; required for semantic_judge and used as model source for HF-based PPL/LL computation\n" + "- prompt_template: Prompt template object (optional; must provide build_prompt; default is AnswerJudgePrompt)\n" + "- system_prompt: System prompt for semantic judging\n" + "- metric_type: Optional; overrides the default metric for the given eval_type\n" + "- use_semantic_judge: Only for key2_qa; whether to use LLM-based semantic judging\n\n" + "Run Parameters:\n" + "- storage: DataFlowStorage\n" + "- input_text_key: Text column name (key1_text_score)\n" + "- input_question_key: Question column name (key2/key3)\n" + "- input_target_key: Single reference answer column name (key2_qa)\n" + "- input_targets_key: Multiple reference answers column name (key2_q_ma)\n" + "- input_choices_key: Choices column name (key3_q_choices_a/key3_q_choices_as)\n" + "- input_label_key: Single label column name (key3_q_choices_a)\n" + "- input_labels_key: Multiple labels column name (key3_q_choices_as)\n" + "- input_better_key: Better answer column name (key3_q_a_rejected)\n" + "- input_rejected_key: Rejected answer column name (key3_q_a_rejected)\n" + "- input_context_key: Optional context column name\n" + "- input_pred_key: Prediction column name (default: generated_ans)\n\n" + "Output Parameters:\n" + f"- output_eval_score_key: Numeric score (accuracy classes use 0/1)\n" + f"- output_eval_pred_key: Parsed prediction\n" + f"- output_eval_valid_key: Whether the sample is valid\n" + f"- output_eval_error_key: Error message if any\n" + "- Saves aggregated stats to eval_result_path\n" + "- Returns a list of involved/output keys" + ) \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/filter/__pycache__/general_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/filter/__pycache__/general_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e19e384ec14434384bc4c215527651d5a12e77ed Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/filter/__pycache__/general_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/filter/__pycache__/kcentergreedy_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/filter/__pycache__/kcentergreedy_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da8dfd7df4841c0d15bf55a2a18029ed5cc2b576 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/filter/__pycache__/kcentergreedy_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/filter/__pycache__/prompted_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/filter/__pycache__/prompted_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d2c188599df9b2b57f6944eea9077cf5ac1440d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/filter/__pycache__/prompted_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/filter/general_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/filter/general_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..4082ec488418e168218ee039dae51921a0bcf3a5 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/filter/general_filter.py @@ -0,0 +1,79 @@ +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY +import pandas as pd + +@OPERATOR_REGISTRY.register() +class GeneralFilter(OperatorABC): + + def __init__(self, filter_rules: list): + self.logger = get_logger() + self.filter_rules = filter_rules + self.logger.info(f"Initializing {self.__class__.__name__} with rules: {self.filter_rules}") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子支持通过多个自定义函数对 DataFrame 进行灵活过滤。\n\n" + "每条过滤规则是一个函数(例如 lambda 表达式),接受一个 DataFrame 并返回一个布尔类型的 Series," + "用于指定保留哪些行。\n\n" + "输入参数:\n" + "- filter_rules:一个函数列表,每个函数形式为 lambda df: ...," + "需返回一个与 df 长度一致的布尔 Series。所有规则之间采用与(AND)关系组合。\n\n" + "示例:\n" + " - lambda df: df['score'] > 0.5\n" + " - lambda df: df['label'].isin(['A', 'B'])" + ) + elif lang == "en": + return ( + "This operator applies custom filtering functions to a DataFrame.\n\n" + "Each filter rule is a function (e.g., lambda expression) that takes a DataFrame " + "and returns a boolean Series indicating which rows to retain.\n\n" + "Input Parameters:\n" + "- filter_rules: A list of functions, each in the form of lambda df: ..., " + "returning a boolean Series of the same length as the DataFrame. " + "All rules are combined using logical AND.\n\n" + "Examples:\n" + " - lambda df: df['score'] > 0.5\n" + " - lambda df: df['label'].isin(['A', 'B'])" + ) + else: + return "GeneralFilter filters DataFrame rows using a list of functions returning boolean Series." + + + def _validate_dataframe(self, dataframe: pd.DataFrame): + required_keys = [self.input_key] + forbidden_keys = [] + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + raise ValueError(f"Missing required column(s): {missing}") + if conflict: + raise ValueError(f"The following column(s) already exist and would be overwritten: {conflict}") + + def run(self, + storage: DataFlowStorage, + ): + df = storage.read("dataframe") + mask = pd.Series(True, index=df.index) + + for rule_fn in self.filter_rules: + if not callable(rule_fn): + raise ValueError("Each filter rule must be a callable(e.g., lambda df: ...)") + cond = rule_fn(df) + if not isinstance(cond, pd.Series) or cond.dtype != bool: + raise ValueError("Each filter function must return a boolean Series") + mask &= cond + + filtered_df = df[mask] + self.logger.info(f"Filtering complete. Remaining rows: {len(filtered_df)}") + storage.write(filtered_df) + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_df)}.") + return "" + + + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/filter/kcentergreedy_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/filter/kcentergreedy_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..04e49562d90be728446949caf9774deae9e3e00d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/filter/kcentergreedy_filter.py @@ -0,0 +1,219 @@ +import numpy as np +import pandas as pd +import random +import torch +from torch import Tensor +from typing import List, Optional +import torch.nn.functional as F +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger + +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC, LLMServingABC + +class KCenterGreedy: + """Implements k-center-greedy method. + + Args: + embedding (Tensor): Embedding vector extracted from a LLM + sampling_ratio (float): Ratio to choose coreset size from the embedding size. + + Example: + >>> embedding.shape + torch.Size([219520, 1536]) + >>> sampler = KCenterGreedy(embedding=embedding) + >>> sampled_idxs = sampler.select_coreset_idxs() + >>> coreset = embedding[sampled_idxs] + >>> coreset.shape + torch.Size([219, 1536]) + """ + + def __init__(self, embedding: Tensor, sampling_ratio: float) -> None: + self.embedding = embedding + self.coreset_size = int(embedding.shape[0] * sampling_ratio) + # self.model = SparseRandomProjection(eps=0.9) + + self.features: Tensor + self.min_distances: Tensor = torch.tensor([]) + self.n_observations = self.embedding.shape[0] + + def reset_distances(self) -> None: + """Reset minimum distances.""" + self.min_distances = torch.tensor([]) + + def update_distances(self, cluster_centers: List[int]) -> None: + """Update min distances given cluster centers. + + Args: + cluster_centers (List[int]): indices of cluster centers + """ + + if cluster_centers: + centers = self.features[cluster_centers] + + distance = F.pairwise_distance(self.features, centers, p=2).reshape(-1, 1) + + if self.min_distances.shape[0] == 0: + self.min_distances = distance + else: + self.min_distances = torch.minimum(self.min_distances, distance) + + def get_new_idx(self) -> int: + """Get index value of a sample. + + Based on minimum distance of the cluster + + Returns: + int: Sample index + """ + + if isinstance(self.min_distances, Tensor): + idx = int(torch.argmax(self.min_distances).item()) + else: + raise ValueError(f"self.min_distances must be of type Tensor. Got {type(self.min_distances)}") + + return idx + + def select_coreset_idxs(self, selected_idxs: Optional[List[int]] = None) -> List[int]: + """Greedily form a coreset to minimize the maximum distance of a cluster. + + Args: + selected_idxs: index of samples already selected. Defaults to an empty set. + + Returns: + indices of samples selected to minimize distance to cluster centers + """ + + if selected_idxs is None: + selected_idxs = [] + + if self.embedding.ndim == 2: + # self.model.fit(self.embedding) + # self.features = self.model.transform(self.embedding) + + self.features = self.embedding + self.reset_distances() + else: + self.features = self.embedding.reshape(self.embedding.shape[0], -1) + self.update_distances(cluster_centers=selected_idxs) + + selected_coreset_idxs: List[int] = [] + idx = int(torch.randint(high=self.n_observations, size=(1,)).item()) + cnt = 0 + for _ in range(self.coreset_size): + cnt += 1 + if(cnt % 1000 == 0): + print(cnt) + self.update_distances(cluster_centers=[idx]) + idx = self.get_new_idx() + if idx in selected_idxs: + raise ValueError("New indices should not be in selected indices.") + self.min_distances[idx] = 0 + selected_coreset_idxs.append(idx) + + return selected_coreset_idxs + + def sample_coreset(self, selected_idxs: Optional[List[int]] = None) -> Tensor: + """Select coreset from the embedding. + + Args: + selected_idxs: index of samples already selected. Defaults to an empty set. + + Returns: + Tensor: Output coreset + + Example: + >>> embedding.shape + torch.Size([219520, 1536]) + >>> sampler = KCenterGreedy(...) + >>> coreset = sampler.sample_coreset() + >>> coreset.shape + torch.Size([219, 1536]) + """ + + idxs = self.select_coreset_idxs(selected_idxs) + coreset = self.embedding[idxs] + + return coreset + +@OPERATOR_REGISTRY.register() +class KCenterGreedyFilter(OperatorABC): + def __init__(self, num_samples: int, embedding_serving : LLMServingABC = None): + self.num_samples = num_samples + self.embedding_serving = embedding_serving + self.logger = get_logger() + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子利用 K-Center Greedy 算法从海量文档片段中挑选出具有代表性的样本(Coreset),常用于多样化种子 QA 对的生成。\n\n" + "输入参数:\n" + "- input_key: 包含文档内容的字段名(默认 'content')。\n" + "- embedding_serving: 嵌入模型服务实例,用于将文本转换为向量。\n" + "- num_samples: 最终需要保留的文档片段数量。\n\n" + "输出:\n" + "- 过滤后的数据集,仅包含被选中的代表性文档片段。" + ) + elif lang == "en": + return ( + "This operator uses the K-Center Greedy algorithm to select representative samples (coreset) " + "from a large pool of document fragments, typically used for generating diverse seed QA pairs.\n\n" + "Input Parameters:\n" + "- input_key: Field name containing the document content (default: 'content').\n" + "- embedding_serving: Instance of embedding serving for text-to-vector conversion.\n" + "- num_samples: The target number of document fragments to select.\n\n" + "Output:\n" + "- A filtered dataset containing only the selected representative document fragments." + ) + else: + return "KCenterGreedyFilter selects representative document fragments using a greedy coreset strategy." + + def _validate_dataframe(self, dataframe: pd.DataFrame): + required_keys = [self.input_key] + forbidden_keys = [] + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + self.logger.error(f"Missing required column(s): {missing}") + if conflict: + self.logger.error(f"The following column(s) already exist and would be overwritten: {conflict}") + missing_keys = [key for key in required_keys if key not in dataframe.columns] + + if missing_keys: + self.logger.error(f"The following required columns are missing from the dataframe: {missing_keys}") + + def run( + self, + storage:DataFlowStorage, + input_key: str = "content", + ) -> list: + ''' + Execute the answer format filter process + ''' + self.input_key = input_key + dataframe = storage.read("dataframe") + self._validate_dataframe(dataframe) + + texts = dataframe[self.input_key].tolist() + indexes = np.zeros(len(dataframe)).astype(int) + + + embeddings_list = self.embedding_serving.generate_embedding_from_input(texts) + embeddings = torch.tensor(embeddings_list) + + sampler = KCenterGreedy(embedding=embeddings, sampling_ratio= self.num_samples / len(texts)) + chooss_indexes = sampler.select_coreset_idxs() + + + for index in chooss_indexes: + indexes[index] = 1 + + dataframe = dataframe[np.array(indexes) == 1] + + output_file = storage.write(dataframe) + self.logger.info(f"Results saved to {output_file}") + + return [self.input_key,] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/filter/prompted_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/filter/prompted_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..e9eed09ef4b411f01aab842e473310d5d3cd4c38 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/filter/prompted_filter.py @@ -0,0 +1,81 @@ +import pandas as pd +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger + +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +from dataflow.operators.core_text import PromptedEvaluator + +@OPERATOR_REGISTRY.register() +class PromptedFilter(OperatorABC): + ''' + Answer Generator is a class that generates answers for given questions. + ''' + def __init__(self, llm_serving: LLMServingABC, system_prompt: str = "Please evaluate the quality of this data on a scale from 1 to 5.", min_score = 1, max_score = 5): + self.logger = get_logger() + self.llm_serving = llm_serving + self.prompted_evaluator = PromptedEvaluator(llm_serving, system_prompt) + self.min_score = min_score + self.max_score = max_score + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "PromptedFilter 使用内置的 PromptedEvaluator 对输入数据进行数值化打分," + "并根据指定的分数区间(min_score 到 max_score,闭区间)筛选出符合条件的样本。" + "默认情况下打分范围是 1–5,但用户可以通过 system_prompt 自定义其他评分规则。\n" + "\n输入参数:\n" + "- llm_serving:LLM 服务对象,需实现 LLMServingABC 接口\n" + "- system_prompt:系统提示词,定义评估规范(可选,默认 " + "'Please evaluate the quality of this data on a scale from 1 to 5.')\n" + "- input_key:待评估文本所在列名(默认 'raw_content')\n" + "- output_key:写回打分结果的列名(默认 'eval',若已存在将被覆盖)\n" + "- min_score:筛选的最小分(默认 5)\n" + "- max_score:筛选的最大分(默认 5)\n" + "\n输出参数:\n" + "- 过滤后的 DataFrame(仅保留分数位于 [min_score, max_score] 的行)\n" + "- 返回 output_key 以供后续算子引用\n" + "\n备注:\n" + "- 默认打分区间是 1–5,但可根据实际 prompt 改变。" + ) + elif lang == "en": + return ( + "PromptedFilter leverages PromptedEvaluator to assign numeric scores to input data, " + "and filters rows whose scores fall within [min_score, max_score] (inclusive). " + "By default, the scoring scale is 1–5, but this can be customized through system_prompt.\n" + "\nInput Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC\n" + "- system_prompt: System prompt defining the evaluation criteria " + "(default: 'Please evaluate the quality of this data on a scale from 1 to 5.')\n" + "- input_key: Column name containing the text to evaluate (default 'raw_content')\n" + "- output_key: Column name to store the score (default 'eval'; overwritten if it exists)\n" + "- min_score: Minimum score for filtering (default 5)\n" + "- max_score: Maximum score for filtering (default 5)\n" + "\nOutput:\n" + "- Filtered DataFrame (rows with scores in [min_score, max_score])\n" + "- Returns output_key for downstream operators\n" + "\nNote:\n" + "- Default scoring range is 1–5, but can vary depending on the system_prompt." + ) + else: + return "PromptedFilter scores rows via PromptedEvaluator and filters by a configurable score range (default 1–5)." + + + def run(self, storage: DataFlowStorage, input_key: str = "raw_content", output_key: str = "eval"): + self.logger.info("Running PromptGenerator...") + + # Load the raw dataframe from the input file + dataframe = storage.read('dataframe') + self.logger.info(f"Loading, number of rows: {len(dataframe)}") + + # Create a list to hold all generated questions and answers + generated_outputs = self.prompted_evaluator.eval(dataframe, input_key) + + # Add the generated content back to the dataframe + dataframe[output_key] = generated_outputs + filtered_dataframe = dataframe[(dataframe[output_key] >= self.min_score) & (dataframe[output_key] <= self.max_score)] + # Save the updated dataframe to the output file + output_file = storage.write(filtered_dataframe) + return output_key diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/bench_answer_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/bench_answer_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d07eff8631c9fda6f3a31822ce0b13cf92c9cb50 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/bench_answer_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/chunked_prompted_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/chunked_prompted_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5347678b7e279f1beb56d8a7f2a596d66fa06c77 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/chunked_prompted_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/embedding_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/embedding_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4cab0766f9ddf3f1358d4473b81eaf290441621e Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/embedding_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/format_str_prompted_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/format_str_prompted_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54fa49da5cf07ce3a07456062443831b7bbae2d2 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/format_str_prompted_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/prompted_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/prompted_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..727ed1047077e87102336e51a3fcc10d12883ad8 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/prompted_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/random_domain_knowledge_row_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/random_domain_knowledge_row_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1ba82c6ffa8a7bbd37aad0183735bdff3ba3ed6 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/random_domain_knowledge_row_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/retrieval_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/retrieval_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53f4dfa4aad8fb047af09f458539888002d6a6ec Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/retrieval_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/text2multihopqa_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/text2multihopqa_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07fbcabc3cbcb570c55a1ae657f993d1fb23dffb Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/text2multihopqa_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/text2qa_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/text2qa_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..727c4d8d9551c35f09cf46972ff59de06c0aec3e Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/__pycache__/text2qa_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/bench_answer_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/bench_answer_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..501c554af6d6c1ed4acacdb58702978f5c782142 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/bench_answer_generator.py @@ -0,0 +1,332 @@ +import json +import inspect +from typing import Any, Dict, List, Literal, Optional, Union + +import numpy as np +import pandas as pd + +from dataflow import get_logger +from dataflow.core import OperatorABC, LLMServingABC +from dataflow.core.prompt import DIYPromptABC, prompt_restrict +from dataflow.prompts.core_text import FormatStrPrompt +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.storage import DataFlowStorage + + +@prompt_restrict( + FormatStrPrompt + ) + +@OPERATOR_REGISTRY.register() +class BenchAnswerGenerator(OperatorABC): + """ + 用于 bench 评测的统一生成算子, 与 UnifiedBenchDatasetEvaluator 参数对齐 + + 输入: + - eval_type: 评测类型, 取值同 evaluator + - 运行时通过 input_xxx_key 传入各字段名(未传默认 None) + - input_context_key: 可选, 上下文字段名, 不传则 None + 输出: + - output_key: 生成结果列, 默认 generated_ans + - 对于不需要生成的类型, 默认不写 output_key, 直接返回空列表 + """ + + def __init__( + self, + eval_type: Literal[ + "key1_text_score", + "key2_qa", + "key2_q_ma", + "key3_q_choices_a", + "key3_q_choices_as", + "key3_q_a_rejected", + ] = "key2_qa", + llm_serving: LLMServingABC = None, + prompt_template: Union[FormatStrPrompt, DIYPromptABC] = FormatStrPrompt, + system_prompt: str = "You are a helpful assistant specialized in generating answers to questions.", + allow_overwrite: bool = False, + force_generate: bool = False, + ): + self.logger = get_logger() + self.llm_serving = llm_serving + self.prompt_template = prompt_template + self.system_prompt = system_prompt + self.allow_overwrite = allow_overwrite + self.force_generate = force_generate + self.eval_type = eval_type + + # ---------- 工具函数 ---------- + def _normalize_context(self, ctx: Any) -> Optional[str]: + if ctx is None: + return None + if isinstance(ctx, float) and np.isnan(ctx): + return None + if isinstance(ctx, list): + parts = [] + for x in ctx: + if x is None: + continue + s = str(x).strip() + if s: + parts.append(s) + return "\n".join(parts) if parts else None + s = str(ctx).strip() + return s if s else None + + def _ensure_list(self, v: Any) -> Optional[List[str]]: + if v is None: + return None + if isinstance(v, float) and np.isnan(v): + return None + if isinstance(v, list): + return [str(x) for x in v] + s = str(v).strip() + if not s: + return None + # 尝试 json list + if s.startswith("[") and s.endswith("]"): + try: + obj = json.loads(s) + if isinstance(obj, list): + return [str(x) for x in obj] + except Exception: + pass + return None + + def _format_choices_text(self, choices: List[str]) -> str: + letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + lines = [] + for i, c in enumerate(choices): + tag = letters[i] if i < len(letters) else str(i) + lines.append(f"{tag}. {c}") + return "\n".join(lines) + + def _build_prompt_fallback( + self, + *, + eval_type: str, + question: Optional[str], + context: Optional[str], + choices: Optional[List[str]], + ) -> str: + ctx_block = f"Context:\n{context}\n\n" if context else "" + q_block = f"Question:\n{(question or '').strip()}\n\n" + + if eval_type in ("key2_qa", "key2_q_ma"): + return f"{ctx_block}{q_block}Answer:" + if eval_type == "key3_q_choices_a": + ch = self._format_choices_text(choices or []) + return f"{ctx_block}{q_block}Choices:\n{ch}\n\nChoose exactly one option. Output only the option letter (e.g., A).\nAnswer:" + if eval_type == "key3_q_choices_as": + ch = self._format_choices_text(choices or []) + return ( + f"{ctx_block}{q_block}Choices:\n{ch}\n\n" + "This is a multi-select question. Output JSON only, format: {\"choices\": [\"A\",\"C\"]}.\nAnswer:" + ) + # key1_text_score / key3_q_a_rejected 默认不需要生成 + return f"{ctx_block}{q_block}Answer:" + + def _build_prompt( + self, + *, + eval_type: str, + question: Optional[str], + context: Optional[str], + choices: Optional[List[str]], + ) -> str: + if self.prompt_template is not None and hasattr(self.prompt_template, "build_prompt"): + try: + fn = getattr(self.prompt_template, "build_prompt") + + if eval_type in ("key3_q_choices_a", "key3_q_choices_as"): + need_fields = {"question", "choices"} + else: + need_fields = {"question"} + + kwargs = { + "eval_type": eval_type, + "question": question, + "context": context or "", + "choices": choices, + "choices_text": self._format_choices_text(choices) if choices else "", + } + + sig = inspect.signature(fn) + params = list(sig.parameters.values()) + has_varkw = any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params) + + accepted = {p.name for p in params if p.name != "self"} + expects_need_fields = "need_fields" in accepted + + if has_varkw: + if expects_need_fields: + return fn(need_fields, **kwargs) + return fn(**kwargs) + + filtered = {k: v for k, v in kwargs.items() if k in accepted} + if expects_need_fields: + return fn(need_fields, **filtered) + return fn(**filtered) + except Exception as e: + self.logger.error(f"prompt_template.build_prompt 失败, fallback 默认模板: {e}") + return self._build_prompt_fallback(eval_type=eval_type, question=question, context=context, choices=choices) + + def _call_generate(self, prompts: List[str]) -> List[str]: + if not hasattr(self.llm_serving, "generate_from_input"): + self.logger.error("llm_serving 缺少 generate_from_input 接口") + return [""] * len(prompts) + try: + # 兼容有无 system_prompt 参数 + try: + return self.llm_serving.generate_from_input(user_inputs=prompts, system_prompt=self.system_prompt) + except TypeError: + return self.llm_serving.generate_from_input(prompts) + except Exception as e: + self.logger.error(f"generate_from_input 执行失败: {e}") + return [""] * len(prompts) + + def _need_generation(self, eval_type: str) -> bool: + # evaluator 当前实现里: + # - key1_text_score: 不需要 generated_ans + # - key2_qa / key2_q_ma: 需要 generated_ans + # - key3_q_choices_a: evaluator 可用 ll 做选择题评估 -> 默认不生成 + # - key3_q_choices_as: evaluator 当前用解析 generated_ans -> 需要 + # - key3_q_a_rejected: evaluator 用 ll 比较 better vs rejected -> 不需要 + if self.force_generate: + return eval_type != "key1_text_score" + return eval_type in ("key2_qa", "key2_q_ma", "key3_q_choices_as") + + # ---------- 主入口 ---------- + def run( + self, + storage: DataFlowStorage, + input_text_key: Optional[str] = None, + input_question_key: Optional[str] = None, + input_target_key: Optional[str] = None, + input_targets_key: Optional[str] = None, + input_choices_key: Optional[str] = None, + input_label_key: Optional[str] = None, + input_labels_key: Optional[str] = None, + input_better_key: Optional[str] = None, + input_rejected_key: Optional[str] = None, + input_context_key: Optional[str] = None, + output_key: str = "generated_ans", + ) -> List[str]: + + df = storage.read("dataframe") + eval_type = self.eval_type + + if not self._need_generation(eval_type): + self.logger.info(f"[BenchAnswerGenerator] eval_type={eval_type} 默认不需要生成, 跳过") + storage.write(df) + return [] + + if (output_key in df.columns) and (not self.allow_overwrite): + self.logger.error(f"输出列已存在且不允许覆盖: {output_key}") + storage.write(df) + return [] + + # 读取字段 + q_col = input_question_key + if not q_col or q_col not in df.columns: + self.logger.error(f"缺少 question 列, input_question_key={q_col}") + storage.write(df) + return [] + + ch_col = input_choices_key + need_choices = eval_type in ("key3_q_choices_a", "key3_q_choices_as") + if need_choices and (not ch_col or ch_col not in df.columns): + self.logger.error(f"缺少 choices 列, input_choices_key={ch_col}") + storage.write(df) + return [] + + ctx_series = None + if input_context_key: + if input_context_key in df.columns: + ctx_series = df[input_context_key] + else: + self.logger.error(f"context_key 不存在: {input_context_key}, 视为 None") + + prompts: List[str] = [] + for idx, row in df.iterrows(): + q = row[q_col] + ctx = self._normalize_context(ctx_series.loc[idx]) if ctx_series is not None else None + + choices = None + if need_choices: + choices = self._ensure_list(row[ch_col]) + if not choices: + # choices 为空, 仍然生成一个可追踪的输出, 避免整体崩 + choices = [""] + + prompts.append( + self._build_prompt( + eval_type=eval_type, + question=str(q) if q is not None else "", + context=ctx, + choices=choices, + ) + ) + + answers = self._call_generate(prompts) + df[output_key] = answers + out_file = storage.write(df) + self.logger.info(f"[BenchAnswerGenerator] 生成完成, 保存到 {out_file}") + return [output_key] + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于 bench 评测的统一答案生成,根据 eval_type + keys_map 从 DataFrame 取字段构造 prompt 并批量调用 LLM 生成答案。\n" + "对于默认不需要生成的类型会跳过生成(可用 force_generate 强制)。\n\n" + "初始化参数:\n" + "- eval_type:评测类型(key1_text_score / key2_qa / key2_q_ma / key3_q_choices_a / key3_q_choices_as / key3_q_a_rejected)\n" + "- llm_serving:LLM 服务对象(需提供 generate_from_input)\n" + "- prompt_template:提示模板对象(可选,需提供 build_prompt;否则使用内置 fallback 模板)\n" + "- system_prompt:系统提示词\n" + "- allow_overwrite:输出列已存在时是否允许覆盖\n" + "- force_generate:是否强制对可生成类型都生成\n\n" + "运行参数:\n" + "- storage:DataFlowStorage\n" + "- input_text_key:文本列名(key1_text_score)\n" + "- input_question_key:问题列名(key2/key3)\n" + "- input_target_key:单个参考答案列名(key2_qa)\n" + "- input_targets_key:多个参考答案列名(key2_q_ma)\n" + "- input_choices_key:选项列名(key3_q_choices_a/key3_q_choices_as)\n" + "- input_label_key:单个标签列名(key3_q_choices_a)\n" + "- input_labels_key:多个标签列名(key3_q_choices_as)\n" + "- input_better_key:优选答案列名(key3_q_a_rejected)\n" + "- input_rejected_key:劣选答案列名(key3_q_a_rejected)\n" + "- input_context_key:可选,上下文字段名\n" + "- output_key:生成结果列名(默认 generated_ans)\n\n" + "输出:\n" + "- 写回 DataFrame 的 output_key 列(若跳过生成则不写)\n" + "- 返回新增/写入的列名列表(通常为 [output_key] 或 [])" + ) + return ( + "This operator generates answers for unified bench evaluation by building prompts from a dataframe and calling an LLM.\n\n" + "Input Parameters:\n" + "- eval_type: Evaluation type (key1_text_score/key2_qa/key2_q_ma/key3_q_choices_a/key3_q_choices_as/key3_q_a_rejected)\n" + "- llm_serving: LLM serving object (must provide generate_from_input)\n" + "- prompt_template: Prompt template object (optional; must provide build_prompt; falls back to an internal template)\n" + "- system_prompt: System prompt passed to the serving (if supported)\n" + "- allow_overwrite: Whether to overwrite an existing output column\n" + "- force_generate: Whether to force generation for types that can be skipped by default\n\n" + "Run Parameters:\n" + "- storage: DataFlowStorage\n" + "- input_text_key: Text column name (key1_text_score)\n" + "- input_question_key: Question column name (key2/key3)\n" + "- input_target_key: Single reference answer column name (key2_qa)\n" + "- input_targets_key: Multiple reference answers column name (key2_q_ma)\n" + "- input_choices_key: Choices column name (key3_q_choices_a/key3_q_choices_as)\n" + "- input_label_key: Single label column name (key3_q_choices_a)\n" + "- input_labels_key: Multiple labels column name (key3_q_choices_as)\n" + "- input_better_key: Better answer column name (key3_q_a_rejected)\n" + "- input_rejected_key: Rejected answer column name (key3_q_a_rejected)\n" + "- input_context_key: Optional context column name\n" + "- output_key: Output column name for generated answers (default: generated_ans)\n\n" + "Output Parameters:\n" + "- Writes output_key into the dataframe when generation is performed\n" + "- Returns a list of written keys (usually [output_key] or [])" + ) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/chunked_prompted_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/chunked_prompted_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..d54c50587f8916d60dbbee10ae99d3fe254baa5c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/chunked_prompted_generator.py @@ -0,0 +1,147 @@ +import pandas as pd +import tiktoken +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from pathlib import Path + +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC + +@OPERATOR_REGISTRY.register() +class ChunkedPromptedGenerator(OperatorABC): + """ + 基于Prompt的生成算子,支持自动chunk输入。 + - 使用tiktoken或HuggingFace的AutoTokenizer计算token数量; + - 若输入超过max_chunk_len,采用递归二分法切分; + - 从指定输入文件路径读取内容,生成结果保存至指定输出文件路径; + - 生成结果是以separator拼接的字符串。 + """ + + def __init__( + self, + llm_serving: LLMServingABC, + system_prompt: str = "You are a helpful agent.", + json_schema: dict = None, + max_chunk_len: int = 128000, + enc = tiktoken.get_encoding("cl100k_base"), # 支持len(enc.encode(text))的tokenizer都可以,比如tiktoken或HuggingFace的AutoTokenizer + seperator: str = "\n", + ): + self.logger = get_logger() + self.llm_serving = llm_serving + self.system_prompt = system_prompt + self.json_schema = json_schema + self.max_chunk_len = max_chunk_len + self.enc = enc + self.separator = seperator + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于提示词的生成算子,支持长文本自动分chunk。" + "采用递归二分方式进行chunk切分,确保每段不超过max_chunk_len tokens。" + "从给定的输入文件路径读取内容,生成结果保存至指定输出文件路径。" + "多个生成结果以separator拼接成最终输出字符串。" + "输入参数:\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口\n" + "- system_prompt:系统提示词,定义模型行为,默认为'You are a helpful agent.'\n" + "- max_chunk_len:单个chunk的最大token长度,默认为128000\n" + "- input_path_key:输入文件路径字段名,默认为'input_path'\n" + "- output_path_key:输出文件路径字段名,默认为'output_path'\n" + "- json_schema:可选,生成结果的JSON Schema约束\n" + "- enc:用于token计算的编码器,需要实现encode方法,默认为tiktoken的cl100k_base编码器,也可以使用HuggingFace 的 AutoTokenizer\n" + "- separator:chunk结果拼接分隔符,默认为换行符\n" + ) + else: + return ( + "Prompt-based generator with recursive chunk splitting." + "Splits long text inputs into chunks using recursive bisection to ensure each chunk does not exceed max_chunk_len tokens." + "Reads content from specified input file paths and saves generated results to designated output file paths." + "Multiple generated results are joined as a string using the specified separator." + "Input Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC interface\n" + "- system_prompt: System prompt to define model behavior, default is 'You are a helpful agent.'\n" + "- max_chunk_len: Maximum token length per chunk, default is 128000\n" + "- input_path_key: Field name for input file path, default is 'input_path'\n" + "- output_path_key: Field name for output file path, default is 'output_path'\n" + "- json_schema: Optional JSON Schema constraint for generated results\n" + "- enc: Encoder for token counting, default is tiktoken's cl100k_base encoder; can also use HuggingFace's AutoTokenizer\n" + "- separator: Separator for chunk results, default is newline character\n" + ) + + # === token计算 === + def _count_tokens(self, text: str) -> int: + return len(self.enc.encode(text)) + + # === 递归二分分chunk === + def _split_recursive(self, text: str) -> list[str]: + """递归地将文本拆分为不超过max_chunk_len的多个chunk""" + token_len = self._count_tokens(text) + if token_len <= self.max_chunk_len: + return [text] + else: + mid = len(text) // 2 + left, right = text[:mid], text[mid:] + return self._split_recursive(left) + self._split_recursive(right) + + def run( + self, + storage: DataFlowStorage, + input_path_key, + output_path_key, + ): + self.logger.info("Running ChunkedPromptedGenerator...") + dataframe = storage.read("dataframe") + self.logger.info(f"Loaded DataFrame with {len(dataframe)} rows.") + + all_generated_results = [] + + all_llm_inputs = [] + row_chunk_map = [] # 记录每个row对应的chunk数量 + + # === 先收集所有chunk === + for i, row in dataframe.iterrows(): + raw_content = Path(row[input_path_key]).read_text(encoding='utf-8') + + chunks = self._split_recursive(raw_content) + self.logger.info(f"Row {i}: split into {len(chunks)} chunks") + + system_prompt = self.system_prompt + "\n" + llm_inputs = [system_prompt + chunk for chunk in chunks] + all_llm_inputs.extend(llm_inputs) + row_chunk_map.append(len(chunks)) + + # === 一次性并发调用 === + self.logger.info(f"Total {len(all_llm_inputs)} chunks to generate") + + try: + if self.json_schema: + all_responses = self.llm_serving.generate_from_input( + all_llm_inputs, json_schema=self.json_schema + ) + else: + all_responses = self.llm_serving.generate_from_input(all_llm_inputs) + except Exception as e: + self.logger.error(f"Global generation failed: {e}") + all_generated_results = [[] for _ in range(len(dataframe))] + else: + # === 按row重新划分responses === + all_generated_results = [] + idx = 0 + for num_chunks in row_chunk_map: + if num_chunks == 0: + all_generated_results.append([]) + else: + all_generated_results.append(all_responses[idx:idx + num_chunks]) + idx += num_chunks + + for (i, row), gen_results in zip(dataframe.iterrows(), all_generated_results): + output_path = row[input_path_key].split('.')[0] + '_llm_output.txt' + with open(output_path, 'w', encoding='utf-8') as f: + f.write(self.separator.join(gen_results)) + dataframe.at[i, output_path_key] = output_path + + output_file = storage.write(dataframe) + self.logger.info(f"Generation complete. Output saved to {output_file}") + return output_path_key \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/embedding_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/embedding_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..4985790d53ecfaa32fb73ee7f15fd148c8654076 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/embedding_generator.py @@ -0,0 +1,72 @@ +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger + +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC + +@OPERATOR_REGISTRY.register() +class EmbeddingGenerator(OperatorABC): + ''' + Embedding Generator is a class that generates answers for given input text. + ''' + def __init__(self, + embedding_serving: LLMServingABC, + ): + self.logger = get_logger() + self.embedding_serving = embedding_serving + + self.logger.info(f"Initializing {self.__class__.__name__}...") + self.logger.info(f"{self.__class__.__name__} initialized.") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "EmbeddingGenerator算子用于从输入文本生成向量表示(embedding)," + "通常用于语义检索、聚类或下游模型输入等任务。\n\n" + "输入参数:\n" + "- embedding_serving:Embedding服务对象,需实现LLMServingABC接口,用于生成文本的向量表示\n" + "- input_key:输入文本字段名,默认为'text'\n" + "- output_key:输出向量字段名,默认为'embeddings'\n\n" + "输出参数:\n" + "- 包含文本向量的DataFrame,每行对应一个输入文本的embedding\n" + "- 返回输出字段名(如'embeddings'),可供后续算子引用" + ) + elif lang == "en": + return ( + "The EmbeddingGenerator operator generates vector representations (embeddings) " + "from input text, typically used for semantic retrieval, clustering, or downstream model inputs.\n\n" + "Input Parameters:\n" + "- embedding_serving: Embedding service object implementing the LLMServingABC interface for generating text embeddings\n" + "- input_key: Field name for input text, default is 'text'\n" + "- output_key: Field name for output embeddings, default is 'embeddings'\n\n" + "Output Parameters:\n" + "- DataFrame containing text embeddings, where each row corresponds to one input text\n" + "- Returns the output field name (e.g., 'embeddings') for subsequent operator reference" + ) + else: + return ( + "EmbeddingGenerator generates vector embeddings from text input for retrieval or representation learning tasks." + ) + + + def run(self, + storage: DataFlowStorage, + input_key: str = "text", + output_key: str = "embeddings", + ): + dataframe = storage.read("dataframe") + self.input_key = input_key + self.output_key = output_key + + texts = dataframe[self.input_key].tolist() + embeddings_list = self.embedding_serving.generate_embedding_from_input(texts) + # embeddings = torch.tensor(embeddings_list) + + dataframe[self.output_key] = embeddings_list + + output_file = storage.write(dataframe) + self.logger.info(f"Results saved to {output_file}") + + return [self.output_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/format_str_prompted_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/format_str_prompted_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..c1b806305ece040496ab10758040af4ab7139722 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/format_str_prompted_generator.py @@ -0,0 +1,102 @@ +import pandas as pd +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +import string + +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +from dataflow.core.prompt import prompt_restrict, PromptABC, DIYPromptABC +from typing import Union, Any, Set + +from dataflow.prompts.core_text import FormatStrPrompt +@prompt_restrict( + FormatStrPrompt, +) +@OPERATOR_REGISTRY.register() +class FormatStrPromptedGenerator(OperatorABC): + def __init__( + self, + llm_serving: LLMServingABC, + system_prompt: str = "You are a helpful agent.", + prompt_template: Union[FormatStrPrompt, DIYPromptABC] = FormatStrPrompt, + json_schema: dict = None, + ): + self.logger = get_logger() + self.llm_serving = llm_serving + self.system_prompt = system_prompt + self.prompt_template = prompt_template + self.json_schema = json_schema + if prompt_template is None: + raise ValueError("prompt_template cannot be None") + + def run( + self, + storage: DataFlowStorage, + output_key: str = "generated_content", + **input_keys: Any + ): + self.storage: DataFlowStorage = storage + self.output_key = output_key + self.logger.info("Running PromptTemplatedGenerator...") + self.input_keys = input_keys + need_fields = set(input_keys.keys()) + # Load the raw dataframe from the input file + dataframe = storage.read('dataframe') + self.logger.info(f"Loading, number of rows: {len(dataframe)}") + llm_inputs = [] + + for idx, row in dataframe.iterrows(): + key_dict = {} + for key in need_fields: + key_dict[key] = row[input_keys[key]] + prompt_text = self.prompt_template.build_prompt(need_fields, **key_dict) + llm_inputs.append(prompt_text) + self.logger.info(f"Prepared {len(llm_inputs)} prompts for LLM generation.") + # Create a list to hold all generated contents + # Generate content using the LLM serving + generated_outputs = self.llm_serving.generate_from_input(user_inputs = llm_inputs, system_prompt = self.system_prompt, json_schema = self.json_schema) + + dataframe[self.output_key] = generated_outputs + + output_file = self.storage.write(dataframe) + return output_key + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于模板化提示词(Prompt Template)生成内容的算子。" + "该算子使用用户定义的提示模板(StrFormatPrompt 或 DIYPrompt)," + "结合输入数据中的字段自动构造完整提示词并调用大语言模型生成结果。\n\n" + "输入参数:\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口,用于执行文本生成任务\n" + "- prompt_template:提示词模板对象(StrFormatPrompt 或 DIYPromptABC),用于定义提示结构\n" + "- input_keys:输入字段映射字典,用于将DataFrame中的列名映射到模板字段\n" + "- output_key:输出生成内容字段名,默认为'generated_content'\n\n" + "输出参数:\n" + "- 包含生成结果的新DataFrame\n" + "- 返回输出字段名,以便后续算子引用\n\n" + "使用场景:\n" + "适用于需要通过模板化提示构建多样输入、批量生成文本内容的场景,例如标题生成、摘要生成、问答模板填充等。" + ) + elif lang == "en": + return ( + "An operator for content generation based on templated prompts. " + "This operator uses a user-defined prompt template (StrFormatPrompt or DIYPromptABC) " + "to automatically construct full prompts from input data fields and generate outputs via an LLM.\n\n" + "Input Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC interface, responsible for text generation\n" + "- prompt_template: Prompt template object (StrFormatPrompt or DIYPromptABC) defining the prompt structure\n" + "- input_keys: Dictionary mapping DataFrame column names to template fields\n" + "- output_key: Field name for generated content, default is 'generated_content'\n\n" + "Output Parameters:\n" + "- DataFrame containing generated outputs\n" + "- Returns the output field name for downstream operator reference\n\n" + "Use Case:\n" + "Ideal for tasks requiring templated prompt-driven generation, such as title generation, text summarization, or Q&A filling." + ) + else: + return ( + "PromptTemplatedGenerator generates text based on a user-defined prompt template." + ) \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/prompted_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/prompted_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..9cf26a8082644f4e20e067a5e1fb1106f1a7859e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/prompted_generator.py @@ -0,0 +1,90 @@ +import pandas as pd +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from pathlib import Path + +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC + +@OPERATOR_REGISTRY.register() +class PromptedGenerator(OperatorABC): + ''' + Answer Generator is a class that generates answers for given questions. + ''' + def __init__(self, + llm_serving: LLMServingABC, + system_prompt: str = "You are a helpful agent.", + user_prompt: str = "", + json_schema: dict = None, + ): + self.logger = get_logger() + self.llm_serving = llm_serving + self.json_schema = json_schema + self.system_prompt = system_prompt + self.user_prompt = user_prompt + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于用户提供的提示词(prompt)生成数据。结合系统提示词和输入内容生成符合要求的输出文本。" + "输入参数:\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口\n" + "- system_prompt:系统提示词,定义模型行为,默认为'You are a helpful agent.'\n" + "- input_key:输入内容字段名,默认为'raw_content'\n" + "- output_key:输出生成内容字段名,默认为'generated_content'\n" + "输出参数:\n" + "- 包含生成内容的DataFrame\n" + "- 返回输出字段名,用于后续算子引用" + ) + elif lang == "en": + return ( + "Generate data from user-provided prompts. Combines system prompt and input content to generate desired output text.\n" + "Input Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC interface\n" + "- system_prompt: System prompt to define model behavior, default is 'You are a helpful agent.'\n" + "- input_key: Field name for input content, default is 'raw_content'\n" + "- output_key: Field name for output generated content, default is 'generated_content'\n\n" + "Output Parameters:\n" + "- DataFrame containing generated content\n" + "- Returns output field name for subsequent operator reference" + ) + else: + return ( + "PromptedGenerator generates text based on system prompt and input content." + ) + + def run(self, storage: DataFlowStorage, input_key: str = "raw_content", output_key: str = "generated_content"): + self.input_key, self.output_key = input_key, output_key + self.logger.info("Running PromptGenerator...") + + # Load the raw dataframe from the input file + dataframe = storage.read('dataframe') + self.logger.info(f"Loading, number of rows: {len(dataframe)}") + + # Create a list to hold all generated questions and answers + llm_inputs = [] + + # Prepare LLM inputs by formatting the prompt with raw content from the dataframe + for index, row in dataframe.iterrows(): + raw_content = row.get(self.input_key, '') + if raw_content: + llm_input = self.user_prompt + str(raw_content) + llm_inputs.append(llm_input) + + # Generate the text using the model + try: + self.logger.info("Generating text using the model...") + generated_outputs = self.llm_serving.generate_from_input(user_inputs = llm_inputs, system_prompt = self.system_prompt, json_schema = self.json_schema) + self.logger.info("Text generation completed.") + except Exception as e: + self.logger.error(f"Error during text generation: {e}") + return + + # Add the generated content back to the dataframe + dataframe[self.output_key] = generated_outputs + + # Save the updated dataframe to the output file + output_file = storage.write(dataframe) + return output_key diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/random_domain_knowledge_row_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/random_domain_knowledge_row_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..8126a81f0757492a98f376ae70615a0766611bfe --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/random_domain_knowledge_row_generator.py @@ -0,0 +1,117 @@ +import pandas as pd +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger + +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +from dataflow.core.prompt import prompt_restrict, DIYPromptABC +from dataflow.prompts.general_text import SFTFromScratchGeneratorPrompt +from typing import Union +@prompt_restrict( + SFTFromScratchGeneratorPrompt +) + + +@OPERATOR_REGISTRY.register() +class RandomDomainKnowledgeRowGenerator(OperatorABC): + def __init__( + self, + llm_serving: LLMServingABC, + generation_num : int, + domain_keys : str, + prompt_template : Union[SFTFromScratchGeneratorPrompt, DIYPromptABC]= None, + ): + self.logger = get_logger() + self.llm_serving = llm_serving + self.prompt_template = prompt_template + self.generation_num = generation_num + self.domain_keys = domain_keys + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "RandomDomainKnowledgeRowGenerator算子用于结合提示模板(prompt_template)与LLM服务对象(llm_serving)," + "批量生成与指定领域相关的文本内容。\n\n" + "功能说明:\n" + "- 结合SFTFromScratchGeneratorPrompt模板,根据domain_keys随机选择领域并生成内容;\n" + "- 当输入DataFrame为空时,可通过generation_num参数控制生成样本数量;\n" + "- 生成的文本结果将写入指定字段(output_key),并返回该字段名供后续算子使用。\n\n" + "参数说明:\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口;\n" + "- prompt_template:提示模板实例,需为SFTFromScratchGeneratorPrompt类型;\n" + "- storage:DataFlowStorage对象,用于读取与写入数据;\n" + "- output_key:生成结果写入的字段名,默认为'generated_content';\n" + "- generation_num:生成内容数量,默认为1;\n" + "- domain_keys:指定或限制生成内容所属领域。\n\n" + "输出说明:\n" + "- 返回值:输出字段名(output_key),供后续算子引用;\n" + "- 同时将包含生成内容的新DataFrame写回至存储。" + ) + + elif lang == "en": + return ( + "The RandomDomainKnowledgeRowGenerator operator generates domain-related text content " + "by combining a prompt template (prompt_template) with an LLM serving instance (llm_serving).\n\n" + "Function Description:\n" + "- Utilizes the SFTFromScratchGeneratorPrompt template to randomly select domains via domain_keys;\n" + "- Supports content generation when no input DataFrame is available, controlled by generation_num;\n" + "- Generated text is written to the specified output field (output_key), and the field name is returned.\n\n" + "Parameter Description:\n" + "- llm_serving: LLM serving object implementing the LLMServingABC interface;\n" + "- prompt_template: Prompt template instance of type SFTFromScratchGeneratorPrompt;\n" + "- storage: DataFlowStorage object used for reading and writing data;\n" + "- output_key: Name of the field to write generated results (default: 'generated_content');\n" + "- generation_num: Number of contents to generate when there is no input data (default: 1);\n" + "- domain_keys: Domain key(s) specifying or constraining the generation domain; empty string for random.\n\n" + "Output Description:\n" + "- Returns the output field name (output_key) for downstream reference;\n" + "- Writes the DataFrame containing generated content back to storage." + ) + else: + return ( + "RandomDomainKnowledgeRowGenerator算子用于结合提示模板(prompt_template)与LLM服务对象(llm_serving),批量生成领域文本内容。" + ) + + + def run(self, storage: DataFlowStorage, output_key: str = "generated_content"): + """ + 主流程:基于输入数据和提示词生成文本内容。 + + 参数说明: + - storage: DataFlowStorage对象,用于读写数据; + - output_key: 输出字段名,默认为'generated_content'; + - generation_num: 生成内容的数量,默认为1; + + 返回: + - 输出字段名(output_key),供后续算子引用。 + """ + self.output_key = output_key + self.logger.info("Running RandomDomainKnowledgeRowGenerator...") + + # 从存储中读取DataFrame + dataframe = storage.read('dataframe') + self.logger.info(f"Loaded data, number of rows: {len(dataframe)}") + + llm_inputs = [] + + # 按generation_num生成指定数量的输入 + for i in range(self.generation_num): + llm_inputs.append(self.prompt_template.build_prompt(self.domain_keys)) + + try: + self.logger.info("Generating text using the model...") + # 调用LLM服务生成文本 + generated_outputs = self.llm_serving.generate_from_input(llm_inputs) + self.logger.info("Text generation completed.") + except Exception as e: + self.logger.error(f"Error during text generation: {e}") + return + + # 将生成的内容写入DataFrame新列 + dataframe[self.output_key] = generated_outputs + + # 将结果写回存储 + output_file = storage.write(dataframe) + return output_key diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/retrieval_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/retrieval_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..16598631909500362e2a10a795fbc829b2683c51 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/retrieval_generator.py @@ -0,0 +1,85 @@ +import pandas as pd +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger + +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +from dataflow.serving.light_rag_serving import LightRAGServing + +@OPERATOR_REGISTRY.register() +class RetrievalGenerator(OperatorABC): + def __init__(self, + llm_serving: LightRAGServing, + system_prompt: str = "You are a helpful agent.", + ): + self.logger = get_logger() + self.llm_serving = llm_serving + self.system_prompt = system_prompt + + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "根据知识库内容和输入文本生成回答。\n\n" + "功能说明:\n" + "- 利用LightRAG提取的知识库来辅助生成回答。" + "输入要求:\n\n" + "__init__函数参数:\n" + "- llm_serving: LightRAGServing实例,需要先创建实例并导入文件\n" + "- system_prompt: 系统prompt(默认:'You are a helpful agent.')\n" + "run输入参数:\n" + "- storage: 存储文本、LLM回答的DataFlowStorage实例\n" + "- input_key: 提供的文本内容列名(默认:'raw_content')\n" + "- output_key: 生成的回答列名(默认:'generated_content')\n" + "输出:在storage中添加的回答列名\n" + ) + elif lang == "en": + return ( + "Generate answers based on the knowledge base and the input text.\n\n" + "Function Description:\n" + "- Use the knowledge base extracted by LightRAG to assist in generating answers." + "Input Requirements:\n\n" + "Parameters of the __init__ function:\n" + "- llm_serving: A LightRAGServing instance, which must be created and loaded with files beforehand.\n" + "- system_prompt: The system prompt (default: 'You are a helpful agent.')\n" + "Parameters for the run method:\n" + "- storage: A DataFlowStorage instance that stores the input text and the LLM responses\n" + "- input_key: The column name containing the provided text (default: 'raw_content')\n" + "- output_key: The column name for generated answers (default: 'generated_content')\n" + "Output: The name of the column added to storage that contains the generated answers.\n" + ) + else: + return "QAGenerator generates QA pairs for given document fragments." + + + async def run(self, + storage: DataFlowStorage, + input_key: str = "raw_content", + output_key: str = "generated_content", + ): + self.input_key, self.output_key = input_key, output_key + self.logger.info("Running RetrievalGenerator...") + + # Load the raw dataframe from the input file + df = storage.read('dataframe') + self.logger.info(f"Loading, number of tasks: {len(df)}") + + llm_inputs = [] + for index, row in df.iterrows(): + raw_content = row.get(self.input_key, '') + if raw_content: + llm_input = str(raw_content) + llm_inputs.append(llm_input) + + try: + self.logger.info("Generating text using the model...") + generated_outputs = await self.llm_serving.generate_from_input(llm_inputs, self.system_prompt) + self.logger.info("Text generation completed.") + except Exception as e: + self.logger.error(f"Error during text generation: {e}") + return + + df[self.output_key] = generated_outputs + + output_file = storage.write(df) + return output_key \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/text2multihopqa_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/text2multihopqa_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..b6a74c4fec9c21d94b43ed786893f3cd494cd3b8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/text2multihopqa_generator.py @@ -0,0 +1,601 @@ +from dataflow.prompts.text2qa import Text2MultiHopQAGeneratorPrompt +import pandas as pd +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger + +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +import random +from typing import Any, Dict, List, Optional, Sequence +import json +from tqdm import tqdm +import re + +from dataflow.core.prompt import prompt_restrict, DIYPromptABC +from typing import Union +import re + +@prompt_restrict( + Text2MultiHopQAGeneratorPrompt +) +@OPERATOR_REGISTRY.register() +class Text2MultiHopQAGenerator(OperatorABC): + r"""A processor for generating multi-hop question-answer pairs from user + data. + + This class handles the processing of text data to generate multi-hop + question-answer pairs using either an AI model or rule-based approaches. + It manages the entire pipeline from text preprocessing to dataset curation. + """ + + def __init__(self, + llm_serving: LLMServingABC, + seed: int = 0, + lang="en", + prompt_template : Union[Text2MultiHopQAGeneratorPrompt, DIYPromptABC] = None, + num_q = 5 + ): + r"""Initialize the UserDataProcessor. + + Args: + config (Optional[ProcessorConfig], optional): Configuration for + data processing. (default: :obj:`None`) + """ + self.rng = random.Random(seed) + self.llm_serving = llm_serving + self.lang = lang + self.logger = get_logger() + self.num_q = num_q + + if prompt_template: + self.prompt_template = prompt_template + else: + self.prompt_template = Text2MultiHopQAGeneratorPrompt(lang=self.lang) + + @staticmethod + def get_desc(lang: str = "zh") -> tuple: + """Returns a description of the processor's functionality. + + Args: + lang (str, optional): Language for description ('zh' or 'en'). + + Returns: + tuple: Description strings in specified language, including format example + """ + if lang == "zh": + return ( + "MultiHopQAGenerator 是多跳问答对生成处理器,支持从文本中自动生成需要多步推理的问题与答案。", + "处理流程包括:文本预处理、信息抽取、问题生成与回答生成,支持自定义语言模型后端和参数。", + "输出格式如下:", + "输入:\n" + "text: <原始上下文文本>", + "输出:\n" + "{\n" + " \"text\": <处理后的文本字符串>,\n" + " \"qa_pairs\": [\n" + " {\n" + " \"question\": <字符串:生成的问题>,\n" + " \"reasoning_steps\": [\n" + " {\"step\": <推理过程的步骤 1>},\n" + " {\"step\": <步骤 2>} ...\n" + " ],\n" + " \"answer\": <字符串:最终答案>,\n" + " \"supporting_facts\": [<支持该答案的事实 1>, <事实 2>, ...],\n" + " \"type\": <可选:问题类型,如“生物学”、“历史”等>\n" + " },\n" + " ...\n" + " ],\n" + " \"metadata\": {\n" + " \"source\": <数据来源>,\n" + " \"timestamp\": <时间戳字符串>,\n" + " \"complexity\": <整数:问题复杂度标记>\n" + " }\n" + "}" + ) + else: + return ( + "MultiHopQAGenerator is a processor for generating multi-hop question-answer pairs from raw text.", + "It includes preprocessing, information extraction, and reasoning-based QA generation, with configurable LLM backends.", + "Expected output format:", + "Input:\n" + "text: ", + "Output:\n" + "{\n" + " \"text\": ,\n" + " \"qa_pairs\": [\n" + " {\n" + " \"question\": ,\n" + " \"reasoning_steps\": [\n" + " {\"step\": },\n" + " {\"step\": } ...\n" + " ],\n" + " \"answer\": ,\n" + " \"supporting_facts\": [, , ...],\n" + " \"type\": \n" + " },\n" + " ...\n" + " ],\n" + " \"metadata\": {\n" + " \"source\": ,\n" + " \"timestamp\": ,\n" + " \"complexity\": \n" + " }\n" + "}" + ) + + + + def process_text( + self, text: str, source: str = "user_input" + ) -> List[Dict[str, Any]]: + r"""Process a single text to generate multi-hop QA pairs. + + Args: + text (str): The input text to process. + source (str, optional): Source identifier for the text. + (default: :obj:`"user_input"`) + + Returns: + List[Dict[str, Any]]: List of processed examples with QA pairs and + metadata. + """ + # Convert text to standard format + raw_data = [ + { + 'text': text, + 'source': source, + } + ] + + # Construct examples + constructor = ExampleConstructor(lang=self.lang, llm_serving=self.llm_serving) + examples = constructor.construct_examples(raw_data) + + # Manage data + # curator = DataCurator(self.config, self.rng) + # final_dataset = curator.curate_dataset(examples) + + return examples + + def process_batch( + self, texts: List[str], sources: Optional[List[str]] = None + ) -> List[Dict[str, Any]]: + r"""Process multiple texts in batch to generate multi-hop QA pairs. + + Args: + texts (List[str]): List of input texts to process. + sources (Optional[List[str]], optional): List of source + identifiers. (default: :obj:`None`) + + Returns: + List[Dict[str, Any]]: List of processed examples with QA pairs and + metadata. + + Raises: + ValueError: If length of sources doesn't match length of texts. + """ + if sources is None: + sources = ["default_source"] * len(texts) + elif len(sources) != len(texts): + raise ValueError("Length of sources must match length of texts") + + raw_data = [ + { + 'text': text, + 'source': source, + } + for text, source in zip(texts, sources) + ] + + # Construct examples + constructor = ExampleConstructor( + lang=self.lang, + llm_serving=self.llm_serving, + prompt_template = self.prompt_template + ) + examples = constructor.construct_examples(raw_data) + + # # Manage data + # curator = DataCurator(self.config, self.rng) + # final_dataset = curator.curate_dataset(examples) + + return examples + + def _validate_dataframe(self, dataframe: pd.DataFrame): + required_keys = [self.input_key] + forbidden_keys = [self.output_key] + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + raise ValueError(f"Missing required column(s): {missing}") + if conflict: + raise ValueError(f"The following column(s) already exist and would be overwritten: {conflict}") + + def run( + self, + storage: DataFlowStorage=None, + input_key:str='cleaned_chunk', + output_key:str='QA_pairs', + output_meta_key:str='QA_metadata', + ): + self.input_key, self.output_key, self.output_meta_key = input_key, output_key, output_meta_key + dataframe = storage.read("dataframe") + self._validate_dataframe(dataframe) + texts = dataframe[self.input_key].tolist() + outputs=self.process_batch(texts) + dataframe[self.output_key] = [ + output['qa_pairs'][:self.num_q] if len(output['qa_pairs']) >= self.num_q else output['qa_pairs'] + for output in outputs + ] + + dataframe[self.output_meta_key] = [output['metadata'] for output in outputs] + output_file = storage.write(dataframe) + self.logger.info(f"Results saved to {output_file}") + + return [output_key] + + +class ExampleConstructor: + r"""Constructs training examples from raw text data. + + This class handles the construction of training examples by preprocessing + text, extracting information pairs, and generating question-answer pairs. + """ + + def __init__( + self, + lang: str = "en", + llm_serving: LLMServingABC = None, + min_text_length: int = 100, + max_text_length: int = 200000, + prompt_template = None + ): + r"""Initialize the ExampleConstructor. + + Args: + config (ProcessorConfig): Configuration for example construction. + multi_hop_agent (Optional[MultiHopGeneratorAgent], optional): + Agent for generating multi-hop QA pairs. (default: :obj:`None`) + """ + self.lang = lang + self.llm_sering = llm_serving + self.logger = get_logger() + self.max_length = max_text_length + self.min_length = min_text_length + # self.prompt = Text2MultiHopQAGeneratorPrompt(lang=self.lang) + if prompt_template: + self.prompt_template = prompt_template + else: + self.prompt_template = Text2MultiHopQAGeneratorPrompt(lang=self.lang) + + def construct_examples( + self, raw_data: List[Dict[str, Any]] + ) -> List[Dict[str, Any]]: + r"""Construct training examples from raw data. + + Args: + raw_data (List[Dict[str, Any]]): List of raw data dictionaries + containing text and metadata. + + Returns: + List[Dict[str, Any]]: List of constructed examples with QA pairs + and metadata. + """ + self.logger.info("Starting to construct examples...") + examples = [] + + for data in tqdm(raw_data, desc="Constructing examples"): + # 1. Text preprocessing + processed_text = self._preprocess_text(data.get('text', '')) + if not processed_text: + example = { + # 'text': processed_text, + 'qa_pairs': [], + 'metadata': { + 'source': data.get('source', 'unknown'), + 'timestamp': data.get('timestamp', ''), + 'complexity': 0, + }, + } + examples.append(example) + continue + + # 2. Generate key information pairs + info_pairs = self._extract_info_pairs(processed_text) + + # 3. Construct question-answer pairs + if(info_pairs): + qa_pairs = self._generate_qa_pairs(info_pairs) + else: + qa_pairs = [] + + # 4. Add metadata + example = { + # 'text': processed_text, + 'qa_pairs': qa_pairs, + 'metadata': { + 'source': data.get('source', 'unknown'), + 'timestamp': data.get('timestamp', ''), + 'complexity': self._calculate_complexity(qa_pairs) if qa_pairs else 0, + }, + } + + examples.append(example) + + self.logger.info(f"Successfully constructed {len(examples)} examples") + return examples + + def _preprocess_text(self, text: str) -> str: + r"""Preprocess input text for example construction. + + Args: + text (str): Input text to preprocess. + + Returns: + str: Preprocessed text, or empty string if text fails quality + checks. + """ + if not isinstance(text, str): + return '' + + # 1. Basic cleaning + text = text.strip() + + # 2. Length check + if ( + len(text) < self.min_length + or len(text) > self.max_length + ): + self.logger.warning("text fail to pass length check.") + return '' + + # 3. Quality check + if not self._check_text_quality(text): + self.logger.warning("text fail to pass quality check.") + return '' + + return text + + def _calculate_special_char_ratio(self,text): + # 中文字符的Unicode范围(基本汉字+扩展) + chinese_ranges = [ + (0x4E00, 0x9FFF), # 基本汉字 + (0x3400, 0x4DBF), # 扩展A + (0x20000, 0x2A6DF), # 扩展B + (0x2A700, 0x2B73F), # 扩展C + (0x2B740, 0x2B81F), # 扩展D + (0x2B820, 0x2CEAF) # 扩展E + ] + + special_count = 0 + for c in text: + # 检查是否为中文、字母数字或空格 + is_chinese = any(start <= ord(c) <= end for start, end in chinese_ranges) + if not (c.isalnum() or c.isspace() or is_chinese): + special_count += 1 + + return special_count / len(text) if text else 0 + + def _check_text_quality(self, text: str) -> bool: + r"""Check the quality of input text. + + Args: + text (str): Text to check quality for. + + Returns: + bool: True if text passes quality checks, False otherwise. + """ + # 1. Basic quality check + if (text.count('。') < 2 and text.count('.') < 2): # Must have at least 2 sentences + return False + + # 2. Special character ratio check + special_char_ratio = self._calculate_special_char_ratio(text) + if special_char_ratio > 0.3: # No more than 30% special characters + return False + + return True + + def _extract_info_pairs(self, text: str) -> List[Dict[str, Sequence[str]]]: + r"""Extract information pairs and relationships from text. + + Args: + text (str): Input text to extract information from. + + Returns: + List[Dict[str, Sequence[str]]]: List of dictionaries containing + premise, intermediate, conclusion, and related contexts. + """ + # Split into sentences + if(self.lang=="en"): + sentences = [s.strip() for s in text.split('.') if s.strip()] + else: + sentences = [s.strip() for s in text.split('。') if s.strip()] + + info_pairs = [] + + # Extract combinations of multiple related sentences + for i in range(len(sentences) - 2): + if len(sentences[i]) > 10 and len(sentences[i + 1]) > 10: + info_pairs.append( + { + 'premise': sentences[i], + 'intermediate': sentences[i + 1], + 'conclusion': sentences[i + 2] + if i + 2 < len(sentences) + else '', + 'related_contexts': [ + s + for j, s in enumerate(sentences) + if j != i and j != i + 1 and len(s) > 10 + ][:2], + # Limit to 2 additional related contexts + } + ) + + return info_pairs + + def _generate_qa_pairs( + self, info_pairs: List[Dict[str, Sequence[str]]] + ) -> List[Dict[str, str]]: + r"""Generate multi-hop question-answer pairs from information pairs. + + Args: + info_pairs (List[Dict[str, Sequence[str]]]): List of information + pairs extracted from text. + + Returns: + List[Dict[str, str]]: List of generated QA pairs. + """ + user_inputs=[] + for pair in info_pairs: + # 1. Generate multi-hop question-answer pair using AI + # Construct full context + context = ( + f"{pair['premise']}. {pair['intermediate']}." + f" {pair['conclusion']}" + ) + user_inputs.append(self.prompt_template.build_prompt(context)) + + sys_prompt=self.prompt_template.build_system_prompt() + + responses = self.llm_sering.generate_from_input(user_inputs=user_inputs,system_prompt=sys_prompt) + qa_pairs=self._extract_qa_pairs(responses) + + return qa_pairs + + def _extract_qa_pairs(self, responses: List[str]) -> List[Dict[str, Any]]: + """ + 从原始响应中精确提取符合结构的QA对 + 自动跳过非法JSON和干扰文本 + """ + qa_pairs = [] + for response in responses: + # self.logger.info(f"generated qa: {response}") + + # 方法1:尝试直接解析整个响应为JSON + try: + qa_pair = json.loads(response) + if isinstance(qa_pair, dict) and "question" in qa_pair: + qa_pairs.append(qa_pair) + continue + elif isinstance(qa_pair, list): + for item in qa_pair: + if isinstance(item, dict) and "question" in item: + qa_pairs.append(item) + continue + except json.JSONDecodeError: + pass + + # 方法2:使用正则表达式查找所有JSON对象 + try: + # 查找所有以 { 开始的JSON对象 + json_pattern = r'\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}' + + # 更精确的模式,匹配完整的JSON对象 + brace_count = 0 + start_pos = -1 + json_objects = [] + + for i, char in enumerate(response): + if char == '{': + if brace_count == 0: + start_pos = i + brace_count += 1 + elif char == '}': + brace_count -= 1 + if brace_count == 0 and start_pos != -1: + json_str = response[start_pos:i+1] + json_objects.append(json_str) + start_pos = -1 + + # 尝试解析找到的每个JSON字符串 + for json_str in json_objects: + try: + qa_pair = json.loads(json_str) + if (isinstance(qa_pair, dict) and \ + "question" in qa_pair and \ + "reasoning_steps" in qa_pair and \ + "answer" in qa_pair and \ + "supporting_facts" in qa_pair and \ + "type" in qa_pair): + qa_pairs.append(qa_pair) + self.logger.info(f"Successfully extracted QA pair: {qa_pair['question']}") + except json.JSONDecodeError as e: + self.logger.debug(f"Failed to parse JSON object: {json_str[:100]}... Error: {e}") + continue + + # 对qa_pairs中重复的question进行去重 + if qa_pairs: + seen_questions = set() + unique_qa_pairs = [] + + for qa_pair in qa_pairs: + question = qa_pair.get("question", "").strip().lower() + if question and question not in seen_questions: + seen_questions.add(question) + unique_qa_pairs.append(qa_pair) + self.logger.debug(f"Added unique question: {qa_pair['question']}") + else: + self.logger.debug(f"Skipped duplicate question: {qa_pair.get('question', 'N/A')}") + + qa_pairs = unique_qa_pairs + self.logger.info(f"After deduplication: {len(qa_pairs)} unique QA pairs") + + # 如果没有找到有效的JSON对象,记录警告 + if not json_objects: + self.logger.warning("No JSON objects found in model response.") + + except Exception as e: + self.logger.warning(f"Failed to parse QA information from model response. Error: {e}") + + return qa_pairs + + def _calculate_complexity(self, qa_pairs: List[Dict[str, Any]]) -> float: + r"""Calculate the complexity score for a set of QA pairs. + + Args: + qa_pairs (List[Dict[str, Any]]): List of QA pairs to calculate + complexity for. + + Returns: + float: Complexity score between 0.0 and 1.0. + """ + if not qa_pairs: + return 0.0 + + # Calculate complexity based on multiple factors + complexities = [] + for qa in qa_pairs: + # 1. Number of reasoning steps + reasoning_steps_count = len(qa.get('reasoning_steps', [])) + + # 2. Number of supporting facts + supporting_facts_count = len(qa.get('supporting_facts', [])) + + # 3. Question length + question_length = len(qa.get('question', '').split()) + + # 4. Answer length + answer_length = len(qa.get('answer', '').split()) + + # Calculate complexity of a single QA pair + qa_complexity = ( + min(reasoning_steps_count / 3, 1.0) + * 0.4 # Weight for reasoning steps + + min(supporting_facts_count / 3, 1.0) + * 0.3 # Weight for supporting facts + + min(question_length / 20, 1.0) + * 0.15 # Weight for question length + + min(answer_length / 50, 1.0) * 0.15 + # Weight for answer length + ) + + complexities.append(qa_complexity) + + return sum(complexities) / len(complexities) + + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/text2qa_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/text2qa_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..0865ad208983b10b2d909baa0918682b35bdd426 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/generate/text2qa_generator.py @@ -0,0 +1,146 @@ +import pandas as pd +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger + +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +from dataflow.core.prompt import prompt_restrict +import ast +import json + +from dataflow.prompts.text2qa import Text2QASeedQuestionGeneratorPrompt,Text2QAAutoPromptGeneratorPrompt + +@prompt_restrict( + Text2QAAutoPromptGeneratorPrompt, + Text2QASeedQuestionGeneratorPrompt +) +@OPERATOR_REGISTRY.register() +class Text2QAGenerator: + ''' + SeedQAGenerator is a class that uses LLMs to generate QA pairs based on seed input. + ''' + + def __init__(self, + llm_serving: LLMServingABC, + # prompt_template = None # prompt is fix + ): + self.logger = get_logger() + self.llm_serving = llm_serving + self.prompt_template = Text2QAAutoPromptGeneratorPrompt() + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于为给定的文档片段生成种子QA对。\n\n" + "输入参数:\n" + "- input_key: 包含文档片段的字段名\n" + "- prompt_key: 包含提示词的字段名\n" + "- output_quesion_key: 包含生成问题的字段名\n" + "- output_answer_key: 包含生成答案的字段名\n" + ) + elif lang == "en": + return ( + "This operator generates seed QA pairs for given document fragments.\n\n" + "Input Parameters:\n" + "- input_key: Field name containing the content\n" + "- prompt_key: Field name containing the generated prompt\n" + "- output_quesion_key: Field name containing the generated question\n" + "- output_answer_key: Field name containing the generated answer\n" + ) + else: + return "QAGenerator generates QA pairs for given document fragments." + + def _validate_dataframe(self, dataframe: pd.DataFrame): + required_keys = [self.input_key] + forbidden_keys = [self.output_question_key, self.output_answer_key] + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + raise ValueError(f"Missing required column(s): {missing}") + if conflict: + raise ValueError(f"The following column(s) already exist and would be overwritten: {conflict}") + + def _build_prompt(self, df, types): + if types == "prompt": + self.prompt_template = Text2QAAutoPromptGeneratorPrompt() + texts = df[self.input_key].tolist() + output = [self.prompt_template.build_prompt(text) for text in texts] + elif types == "qa": + self.prompt_template = Text2QASeedQuestionGeneratorPrompt() + output = [] + for index, row in df.iterrows(): + output.append(row[self.output_prompt_key] + self.prompt_template.build_prompt() + row[self.input_key]) + return output + + def _parse_qa(self, response: str) -> tuple: + lines = response.strip().split('\n') + q = next((line[2:].strip() for line in lines if line.lower().startswith("q:")), "") + a = next((line[2:].strip() for line in lines if line.lower().startswith("a:")), "") + return q, a + + def parse_list_string(self, s: str) -> list: + # 去掉前后的 [ ] + s = s.strip()[1:-1] + # 去掉多余逗号并按 , 切分 + items = [item.strip() for item in s.split(",") if item.strip()] + return items + + def run( + self, + storage: DataFlowStorage, + input_key:str = "text", + input_question_num:int = 1, + output_prompt_key:str = "generated_prompt", + output_quesion_key:str = "generated_question", + output_answer_key:str = "generated_answer" + ): + ''' + Runs the QA generation process, reading from the input file and saving results to output. + ''' + + self.input_key, self.input_question_num, self.output_prompt_key, self.output_question_key, self.output_answer_key = input_key, input_question_num, output_prompt_key, output_quesion_key, output_answer_key + + dataframe = storage.read("dataframe") + self._validate_dataframe(dataframe) + formatted_prompts = self._build_prompt(dataframe, "prompt") + raw_prompts = self.llm_serving.generate_from_input( + user_inputs=formatted_prompts, + system_prompt="" + ) + + prompts = [] + for i, p in enumerate(raw_prompts): + try: + prompts.append(json.loads(p)) + except json.JSONDecodeError: + self.logger.warning(f"Failed to parse prompt at index {i}: {p}") + continue + + expanded_rows = [] + expanded_prompts = [] + + for idx, prompt_list in enumerate(prompts): + for p in prompt_list[:min(self.input_question_num,len(prompt_list))]: + expanded_rows.append(dataframe.iloc[idx].to_dict()) # 复制该行 + expanded_prompts.append(p) # 对应的 prompt + + dataframe = pd.DataFrame(expanded_rows) + dataframe[self.output_prompt_key] = expanded_prompts + + formatted_prompts = self._build_prompt(dataframe, "qa") + responses = self.llm_serving.generate_from_input(user_inputs=formatted_prompts, system_prompt="") + + questions, answers = zip(*[self._parse_qa(r) for r in responses]) + + dataframe[self.output_question_key] = questions + dataframe[self.output_answer_key] = answers + + output_file = storage.write(dataframe) + self.logger.info(f"Results saved to {output_file}") + + + return [self.output_question_key, self.output_answer_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/refine/__pycache__/pandas_operator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/refine/__pycache__/pandas_operator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27d73e61f4c744372ef9a8410b6aae5ec0b0d62d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/refine/__pycache__/pandas_operator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/refine/__pycache__/prompted_refiner.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/refine/__pycache__/prompted_refiner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..116348eff85ca5e4c352648ece2f0335dab9139b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/refine/__pycache__/prompted_refiner.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/refine/pandas_operator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/refine/pandas_operator.py new file mode 100644 index 0000000000000000000000000000000000000000..d8fa490584074b1d617523f6ac53114d2071e4cc --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/refine/pandas_operator.py @@ -0,0 +1,52 @@ +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY +import pandas as pd + +@OPERATOR_REGISTRY.register() +class PandasOperator(OperatorABC): + + def __init__(self, process_fn: list): + self.logger = get_logger() + self.process_fn = process_fn + self.logger.info(f"Initializing {self.__class__.__name__} with transform functions: {self.process_fn}") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子支持通过多个自定义函数对 DataFrame 进行任意操作(如添加列、重命名、排序等)。\n\n" + "每个函数(通常为 lambda 表达式)接受一个 DataFrame 并返回一个修改后的 DataFrame。\n\n" + "输入参数:\n" + "- process_fn:一个函数列表,每个函数形式为 lambda df: ...," + "必须返回一个 DataFrame。\n\n" + "示例:\n" + " - lambda df: df.assign(score2=df['score'] * 2)\n" + " - lambda df: df.sort_values('score', ascending=False)" + ) + elif lang == "en": + return ( + "This operator applies a list of transformation functions to a DataFrame.\n\n" + "Each function (typically a lambda) takes a DataFrame and returns a modified DataFrame.\n\n" + "Input Parameters:\n" + "- process_fn: A list of functions, each in the form of lambda df: ..., " + "and must return a DataFrame.\n\n" + "Examples:\n" + " - lambda df: df.assign(score2=df['score'] * 2)\n" + " - lambda df: df.sort_values('score', ascending=False)" + ) + else: + return "Applies a sequence of transformation functions to a DataFrame." + + def run(self, storage: DataFlowStorage): + df = storage.read("dataframe") + for fn in self.process_fn: + if not callable(fn): + raise ValueError("Each transform function must be callable (e.g., lambda df: ...)") + df = fn(df) + if not isinstance(df, pd.DataFrame): + raise ValueError("Each transform function must return a DataFrame") + self.logger.info(f"Transformation complete. Final shape: {df.shape}") + storage.write(df) + return "" diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/refine/prompted_refiner.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/refine/prompted_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..9a399bff4088f63c0042aabfa041520598bf3d30 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_text/refine/prompted_refiner.py @@ -0,0 +1,92 @@ +import pandas as pd +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger + +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC + +@OPERATOR_REGISTRY.register() +class PromptedRefiner(OperatorABC): + ''' + Answer Generator is a class that generates answers for given questions. + ''' + def __init__(self, llm_serving: LLMServingABC, system_prompt: str = "You are a helpful agent."): + self.logger = get_logger() + self.llm_serving = llm_serving + self.system_prompt = system_prompt + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "PromptedRefiner 根据给定的 system_prompt 对指定列的文本进行改写/润色/规范化," + "并将结果**就地写回**同一列(覆盖原内容)。其做法是对每一行拼接 " + "`system_prompt + raw_content` 作为模型输入,批量生成改写结果。\n" + "\n输入参数:\n" + "- llm_serving:LLM 服务对象,需实现 LLMServingABC 接口\n" + "- system_prompt:系统提示词,用于描述改写目标与风格(默认 'You are a helpful agent.')\n" + "- input_key:要改写的文本列名(默认 'raw_content'),改写后会覆盖该列\n" + "\n输出参数:\n" + "- 覆盖后的 DataFrame(同名列被改写后的文本)\n" + "- 无返回值(结果已通过 DataFlowStorage 写出)\n" + "\n备注:\n" + "- 该算子**覆盖** input_key 列;若需保留原文,建议先拷贝到新列。\n" + "- 期望每行在 input_key 列提供可用文本;空值将不会生成对应输入,如与行数不匹配可能导致赋值报错。" + ) + elif lang == "en": + return ( + "PromptedRefiner rewrites/refines/normalizes text in a specified column **in place**, " + "using a provided system_prompt. For each row it concatenates " + "`system_prompt + raw_content` as the model input and generates the refined text.\n" + "\nInput Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC\n" + "- system_prompt: Instruction describing the rewrite goal/style (default 'You are a helpful agent.')\n" + "- input_key: Column to refine (default 'raw_content'); the refined output **overwrites** this column\n" + "\nOutput:\n" + "- DataFrame with the same column overwritten by refined text\n" + "- No return value (the result is written via DataFlowStorage)\n" + "\nNotes:\n" + "- This operator **overwrites** the input_key column; copy it first if you need to keep originals.\n" + "- Each row is expected to provide text in input_key; missing/empty rows won’t form inputs, which may cause " + "length-mismatch errors on assignment." + ) + else: + return ( + "PromptedRefiner rewrites a chosen column in place using `system_prompt + raw_content` as input." + ) + + + def run(self, storage: DataFlowStorage, input_key: str = "raw_content"): + self.input_key = input_key + self.logger.info("Running PromptGenerator...") + + # Load the raw dataframe from the input file + dataframe = storage.read('dataframe') + self.logger.info(f"Loading, number of rows: {len(dataframe)}") + + # Create a list to hold all generated questions and answers + llm_inputs = [] + + # Prepare LLM inputs by formatting the prompt with raw content from the dataframe + for index, row in dataframe.iterrows(): + raw_content = row.get(self.input_key, '') + if raw_content: + llm_input = self.system_prompt + str(raw_content) + llm_inputs.append(llm_input) + + # Generate the text using the model + try: + self.logger.info("Generating text using the model...") + generated_outputs = self.llm_serving.generate_from_input(llm_inputs) + self.logger.info("Text generation completed.") + except Exception as e: + self.logger.error(f"Error during text generation: {e}") + return + + # Add the generated content back to the dataframe + dataframe[self.input_key] = generated_outputs + + # Save the updated dataframe to the output file + output_file = storage.write(dataframe) + return diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_vision/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_vision/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..46c3d0aef015faa03c27a323a47698b30476ec3a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_vision/__init__.py @@ -0,0 +1,14 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + # generate + from .generate.prompted_vqa_generator import PromptedVQAGenerator +else: + import sys + from dataflow.utils.registry import LazyLoader, generate_import_structure_from_type_checking + + cur_path = "dataflow/operators/core_vision/" + + + _import_structure = generate_import_structure_from_type_checking(__file__, cur_path) + sys.modules[__name__] = LazyLoader(__name__, "dataflow/operators/core_vision/", _import_structure) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_vision/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_vision/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d545dfb448b68318ebc79a0f8678523cd502a89 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_vision/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_vision/generate/__pycache__/prompted_vqa_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_vision/generate/__pycache__/prompted_vqa_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aeee68451aa5a98cfd5bf2b4e3e714955c7b9f49 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_vision/generate/__pycache__/prompted_vqa_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_vision/generate/prompted_vqa_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_vision/generate/prompted_vqa_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..7e352273d731e63bd8426b79124cc266330278c9 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/core_vision/generate/prompted_vqa_generator.py @@ -0,0 +1,67 @@ +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger + +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC + +@OPERATOR_REGISTRY.register() +class PromptedVQAGenerator(OperatorABC): + def __init__(self, llm_serving: LLMServingABC, system_prompt: str = "You are a helpful assistant."): + self.logger = get_logger() + self.llm_serving = llm_serving + self.system_prompt = system_prompt + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于视觉问答生成,接收包含图像和问题的输入内容,使用大语言模型生成回答," + "并将生成的回答保存到数据框中。\n" + "输入参数:\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口\n" + "- system_prompt:系统提示词,用于定义模型行为,默认为'You are a helpful assistant.'\n" + "- input_key:输入内容的字段名,默认为'raw_content'\n" + "- output_key:输出生成内容的字段名,默认为'generated_content'\n" + "输出参数:\n" + "- 返回输出字段名,用于后续算子引用\n" + "- 在数据框中添加包含生成回答的新列" + ) + elif lang == "en": + return ( + "This operator generates visual question answering responses. It receives input content containing images and questions, " + "uses a large language model to generate answers, and saves the generated answers to the dataframe.\n" + "Input Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC interface\n" + "- system_prompt: System prompt to define model behavior, default is 'You are a helpful assistant.'\n" + "- input_key: Field name for input content, default is 'raw_content'\n" + "- output_key: Field name for output generated content, default is 'generated_content'\n\n" + "Output Parameters:\n" + "- Returns output field name for subsequent operator reference\n" + "- Adds a new column containing generated answers to the dataframe" + ) + else: + return ( + "PromptedVQAGenerator processes visual questions and generates answers using a large language model." + ) + + def run(self, storage: DataFlowStorage, input_key: str = "raw_content", output_key: str = "generated_content"): + self.input_key, self.output_key = input_key, output_key + self.logger.info("Running Prompted VQA Generator...") + + dataframe = storage.read('dataframe') + self.logger.info(f"Loading, number of rows: {len(dataframe)}") + + llm_inputs = [] + for index, row in dataframe.iterrows(): + raw_content = row.get(self.input_key, '') + if raw_content: + llm_inputs.append(raw_content) + + llm_outputs = self.llm_serving.generate_from_input(llm_inputs, self.system_prompt) + + dataframe[self.output_key] = llm_outputs + output_file = storage.write(dataframe) + self.logger.info(f"Saving to {output_file}") + self.logger.info("Prompted VQA Generator done") + return output_key \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..81146c092291a5e8401e0f832fc905abf5ce04da --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/__init__.py @@ -0,0 +1,79 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + # filter + from .filter.rule_based_filter import ColonEndFilter + from .filter.rule_based_filter import SentenceNumberFilter + from .filter.rule_based_filter import LineEndWithEllipsisFilter + from .filter.rule_based_filter import ContentNullFilter + from .filter.rule_based_filter import SymbolWordRatioFilter + from .filter.rule_based_filter import AlphaWordsFilter + from .filter.rule_based_filter import HtmlEntityFilter + from .filter.rule_based_filter import IDCardFilter + from .filter.rule_based_filter import NoPuncFilter + from .filter.rule_based_filter import SpecialCharacterFilter + from .filter.rule_based_filter import WatermarkFilter + from .filter.rule_based_filter import MeanWordLengthFilter + from .filter.rule_based_filter import StopWordFilter + from .filter.rule_based_filter import CurlyBracketFilter + from .filter.rule_based_filter import CapitalWordsFilter + from .filter.rule_based_filter import LoremIpsumFilter + from .filter.rule_based_filter import UniqueWordsFilter + from .filter.rule_based_filter import CharNumberFilter + from .filter.rule_based_filter import LineStartWithBulletpointFilter + from .filter.rule_based_filter import LineWithJavascriptFilter + from .filter.langkit_filter import LangkitFilter + from .filter.lexical_diversity_filter import LexicalDiversityFilter + from .filter.ngram_filter import NgramFilter + from .filter.presidio_filter import PresidioFilter + from .filter.blocklist_filter import BlocklistFilter + from .filter.hash_deduplicate_filter import HashDeduplicateFilter + from .filter.language_filter import LanguageFilter + from .filter.llm_language_filter import LLMLanguageFilter + from .filter.minhash_deduplicate_filter import MinHashDeduplicateFilter + from .filter.ngramhash_deduplicate_filter import NgramHashDeduplicateFilter + from .filter.perspective_filter import PerspectiveFilter + from .filter.sem_deduplicate_filter import SemDeduplicateFilter + from .filter.simhash_deduplicate_filter import SimHashDeduplicateFilter + from .filter.word_number_filter import WordNumberFilter + + # refine + from .refine.html_entity_refiner import HtmlEntityRefiner + from .refine.html_url_remover_refiner import HtmlUrlRemoverRefiner + from .refine.lowercase_refiner import LowercaseRefiner + from .refine.ner_refiner import NERRefiner + from .refine.pii_anonymize_refiner import PIIAnonymizeRefiner + from .refine.ref_removal_refiner import ReferenceRemoverRefiner + from .refine.remove_contractions_refiner import RemoveContractionsRefiner + from .refine.remove_emoji_refiner import RemoveEmojiRefiner + from .refine.remove_emoticons_refiner import RemoveEmoticonsRefiner + from .refine.remove_extra_spaces_refiner import RemoveExtraSpacesRefiner + from .refine.remove_image_ref_refiner import RemoveImageRefsRefiner + from .refine.remove_number_refiner import RemoveNumberRefiner + from .refine.remove_punctuation_refiner import RemovePunctuationRefiner + from .refine.remove_repetitions_punctuation_refiner import RemoveRepetitionsPunctuationRefiner + from .refine.remove_stopwords_refiner import RemoveStopwordsRefiner + from .refine.spelling_correction_refiner import SpellingCorrectionRefiner + from .refine.stemming_lemmatization_refiner import StemmingLemmatizationRefiner + from .refine.text_normalization_refiner import TextNormalizationRefiner + + # eval + from .eval.ngram_sample_evaluator import NgramSampleEvaluator + from .eval.lexical_diversity_sample_evaluator import LexicalDiversitySampleEvaluator + from .eval.langkit_sample_evaluator import LangkitSampleEvaluator + from .eval.presidio_sample_evaluator import PresidioSampleEvaluator + from .eval.bert_sample_evaluator import BertSampleEvaluator + from .eval.bleu_sample_evaluator import BleuSampleEvaluator + from .eval.cider_sample_evaluator import CiderSampleEvaluator + from .eval.perspective_sample_evaluator import PerspectiveSampleEvaluator + from .eval.task2vec_dataset_evaluator import Task2VecDatasetEvaluator + from .eval.vendi_dataset_evaluator import VendiDatasetEvaluator + +else: + import sys + from dataflow.utils.registry import LazyLoader, generate_import_structure_from_type_checking + + cur_path = "dataflow/operators/general_text/" + + _import_structure = generate_import_structure_from_type_checking(__file__, cur_path) + sys.modules[__name__] = LazyLoader(__name__, "dataflow/operators/general_text/", _import_structure) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af5b619b2fdbd4720915487ce507297a0468ad36 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ac01298f9e1e6f1af0be50b5a42090acd846fc3 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/bert_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/bert_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e762f9655aeceb26f348070c29913c7ebb78c91 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/bert_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/bleu_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/bleu_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c27d15d27a8947f84d114622d0b193f6ef36bb7b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/bleu_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/cider_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/cider_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30497950271b7734ab193c30da68bf3dc1312b11 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/cider_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/langkit_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/langkit_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8441165065ac1984f028fc7995d12ad4c9d3aeb1 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/langkit_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/lexical_diversity_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/lexical_diversity_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5688a81db140706d9cf4cea9b51723bfa23cb29f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/lexical_diversity_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/ngram_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/ngram_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16ddd09483497e58cf308539f40644979996e865 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/ngram_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/perspective_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/perspective_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c16e0555bcd0312cec89653098747502d2f34d2 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/perspective_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/presidio_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/presidio_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a2ce04ff80014b4be37285f10c568c2ead80141 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/presidio_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/task2vec_dataset_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/task2vec_dataset_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94b34dcfa4b64a04fde7eb28cd0ad972fd17a1a5 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/task2vec_dataset_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/vendi_dataset_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/vendi_dataset_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff275698c7c698c3768e2d0cec3a2efe791a9d29 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/__pycache__/vendi_dataset_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/bert_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/bert_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..96a5f83a040e41ea16980edce6fbd9f615449413 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/bert_sample_evaluator.py @@ -0,0 +1,75 @@ +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +import evaluate + +@OPERATOR_REGISTRY.register() +class BertSampleEvaluator(OperatorABC): + def __init__(self, lang='en', model_cache_dir='./dataflow_cache'): + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.data_type = "text" + self.score_name = "BERTScore" + self.lang = lang + self.model_type = "distilbert-base-uncased" + self.idf = False + self.rescale_with_baseline = False + self.bertscore = evaluate.load("bertscore", cache_dir=model_cache_dir) + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "使用BERTScore评估生成文本与参考文本的相似度,基于上下文嵌入计算P/R/F1分数。\n" + "输入参数:\n" + "- lang:语言类型,默认为'en'\n" + "- model_cache_dir:模型缓存目录,默认为'./dataflow_cache'\n" + "- input_key:生成文本字段名\n" + "- reference_key:参考文本字段名\n" + "- output_key:输出得分字段名,默认为'BertScore'\n" + "输出参数:\n" + "- 包含F1相似度得分的DataFrame" + ) + elif lang == "en": + return ( + "Evaluate similarity between generated and reference text using BERTScore with contextual embeddings.\n" + "Input Parameters:\n" + "- lang: Language type, default 'en'\n" + "- model_cache_dir: Model cache directory, default './dataflow_cache'\n" + "- input_key: Field name for generated text\n" + "- reference_key: Field name for reference text\n" + "- output_key: Field name for output score, default 'BertScore'\n" + "Output Parameters:\n" + "- DataFrame containing F1 similarity scores" + ) + else: + return "Evaluate text similarity using BERTScore." + + def eval(self, dataframe, input_key, reference_key): + eval_data = dataframe[input_key].to_list() + ref_data = dataframe[reference_key].to_list() + self.logger.info(f"Evaluating {self.score_name}...") + if ref_data is None: + raise ValueError("Reference data must be provided for BERTScorer") + results = self.bertscore.compute( + predictions=eval_data, + references=ref_data, + lang=self.lang, + model_type=self.model_type, + idf=self.idf, + rescale_with_baseline=self.rescale_with_baseline + ) + scores = results["f1"] + self.logger.info("Evaluation complete!") + return scores + + def run(self, storage: DataFlowStorage, input_key: str, input_reference_key: str, output_key: str='BertScore'): + self.input_key = input_key + self.reference_key = input_reference_key + self.output_key = output_key + dataframe = storage.read("dataframe") + scores = self.eval(dataframe, input_key, self.reference_key) + dataframe[self.output_key] = scores + storage.write(dataframe) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/bleu/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/bleu/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/bleu/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/bleu/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..521d7db98fafd28b86f52ed50132652d8f05cf90 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/bleu/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/bleu/__pycache__/bleu.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/bleu/__pycache__/bleu.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3651509ccdc95cb66cc4cc175bac572ffb05e71 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/bleu/__pycache__/bleu.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/bleu/bleu.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/bleu/bleu.py new file mode 100644 index 0000000000000000000000000000000000000000..79f470367302fbec43b7f5c33bb660c24fd2e49f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/bleu/bleu.py @@ -0,0 +1,236 @@ +import copy +import sys, math, re +from collections import defaultdict + +import six +from six.moves import xrange as range + + +def precook(s, n=4, out=False): + + words = s.split() + counts = defaultdict(int) + for k in range(1,n+1): + for i in range(len(words)-k+1): + ngram = tuple(words[i:i+k]) + counts[ngram] += 1 + return (len(words), counts) + +def cook_refs(refs, eff=None, n=4): + reflen = [] + maxcounts = {} + for ref in refs: + rl, counts = precook(ref, n) + reflen.append(rl) + for (ngram,count) in six.iteritems(counts): + maxcounts[ngram] = max(maxcounts.get(ngram,0), count) + + + if eff == "shortest": + reflen = min(reflen) + elif eff == "average": + reflen = float(sum(reflen))/len(reflen) + + return (reflen, maxcounts) + +def cook_test(test, reflen_refmaxcounts, eff=None, n=4): + reflen, refmaxcounts = reflen_refmaxcounts + testlen, counts = precook(test, n, True) + + result = {} + + + + if eff == "closest": + result["reflen"] = min((abs(l-testlen), l) for l in reflen)[1] + else: + result["reflen"] = reflen + + result["testlen"] = testlen + + result["guess"] = [max(0,testlen-k+1) for k in range(1,n+1)] + + result['correct'] = [0]*n + for (ngram, count) in six.iteritems(counts): + result["correct"][len(ngram)-1] += min(refmaxcounts.get(ngram,0), count) + + return result + +class Bleu(object): + """Bleu scorer. + """ + + __slots__ = "n", "crefs", "ctest", "_score", "_ratio", "_testlen", "_reflen", "special_reflen" + + def copy(self): + + new = Bleu(n=self.n) + new.ctest = copy.copy(self.ctest) + new.crefs = copy.copy(self.crefs) + new._score = None + return new + + def __init__(self, test=None, refs=None, n=4, special_reflen=None): + + + self.n = n + self.crefs = [] + self.ctest = [] + self.cook_append(test, refs) + self.special_reflen = special_reflen + + def cook_append(self, test, refs): + + + if refs is not None: + self.crefs.append(cook_refs(refs)) + if test is not None: + cooked_test = cook_test(test, self.crefs[-1]) + self.ctest.append(cooked_test) ## N.B.: -1 + else: + self.ctest.append(None) # lens of crefs and ctest have to match + + self._score = None ## need to recompute + + def ratio(self, option=None): + self.compute_score(option=option) + return self._ratio + + def score_ratio(self, option=None): + + return (self.fscore(option=option), self.ratio(option=option)) + + def score_ratio_str(self, option=None): + return "%.4f (%.2f)" % self.score_ratio(option) + + def reflen(self, option=None): + self.compute_score(option=option) + return self._reflen + + def testlen(self, option=None): + self.compute_score(option=option) + return self._testlen + + def retest(self, new_test): + if type(new_test) is str: + new_test = [new_test] + assert len(new_test) == len(self.crefs), new_test + self.ctest = [] + for t, rs in zip(new_test, self.crefs): + self.ctest.append(cook_test(t, rs)) + self._score = None + + return self + + def rescore(self, new_test): + ''' replace test(s) with new test(s), and returns the new score.''' + + return self.retest(new_test).compute_score() + + def size(self): + assert len(self.crefs) == len(self.ctest), "refs/test mismatch! %d<>%d" % (len(self.crefs), len(self.ctest)) + return len(self.crefs) + + def __iadd__(self, other): + '''add an instance (e.g., from another sentence).''' + + if type(other) is tuple: + ## avoid creating new BleuScorer instances + self.cook_append(other[0], other[1]) + else: + assert self.compatible(other), "incompatible BLEUs." + self.ctest.extend(other.ctest) + self.crefs.extend(other.crefs) + self._score = None ## need to recompute + + return self + + def compatible(self, other): + return isinstance(other, Bleu) and self.n == other.n + + def single_reflen(self, option="average"): + return self._single_reflen(self.crefs[0][0], option) + + def _single_reflen(self, reflens, option=None, testlen=None): + + if option == "shortest": + reflen = min(reflens) + elif option == "average": + reflen = float(sum(reflens))/len(reflens) + elif option == "closest": + reflen = min((abs(l-testlen), l) for l in reflens)[1] + else: + assert False, "unsupported reflen option %s" % option + + return reflen + + def recompute_score(self, option=None, verbose=0): + self._score = None + return self.compute_score(option, verbose) + + def compute_score(self, option=None, verbose=0): + n = self.n + small = 1e-9 + tiny = 1e-15 ## so that if guess is 0 still return 0 + bleu_list = [[] for _ in range(n)] + + if self._score is not None: + return self._score + + if option is None: + option = "average" if len(self.crefs) == 1 else "closest" + + self._testlen = 0 + self._reflen = 0 + totalcomps = {'testlen':0, 'reflen':0, 'guess':[0]*n, 'correct':[0]*n} + + # for each sentence + for comps in self.ctest: + testlen = comps['testlen'] + self._testlen += testlen + + if self.special_reflen is None: ## need computation + reflen = self._single_reflen(comps['reflen'], option, testlen) + else: + reflen = self.special_reflen + + self._reflen += reflen + + for key in ['guess','correct']: + for k in range(n): + totalcomps[key][k] += comps[key][k] + + # append per image bleu score + bleu = 1. + for k in range(n): + bleu *= (float(comps['correct'][k]) + tiny) \ + /(float(comps['guess'][k]) + small) + bleu_list[k].append(bleu ** (1./(k+1))) + ratio = (testlen + tiny) / (reflen + small) ## N.B.: avoid zero division + if ratio < 1: + for k in range(n): + bleu_list[k][-1] *= math.exp(1 - 1/ratio) + + if verbose > 1: + print(comps, reflen) + + totalcomps['reflen'] = self._reflen + totalcomps['testlen'] = self._testlen + + bleus = [] + bleu = 1. + for k in range(n): + bleu *= float(totalcomps['correct'][k] + tiny) \ + / (totalcomps['guess'][k] + small) + bleus.append(bleu ** (1./(k+1))) + ratio = (self._testlen + tiny) / (self._reflen + small) ## N.B.: avoid zero division + if ratio < 1: + for k in range(n): + bleus[k] *= math.exp(1 - 1/ratio) + + if verbose > 0: + print(totalcomps) + print("ratio:", ratio) + + self._score = bleus + return self._score, bleu_list diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/bleu_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/bleu_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..22b56df12d980016993133f4c0f2e40b72626377 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/bleu_sample_evaluator.py @@ -0,0 +1,78 @@ +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.operators.general_text.eval.bleu.bleu import Bleu +from tqdm import tqdm + +@OPERATOR_REGISTRY.register() +class BleuSampleEvaluator(OperatorABC): + def __init__(self, n=4, eff="average", special_reflen=None): + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.score_name = 'BleuScore' + valid_eff_options = ["shortest", "average", "longest"] + if eff not in valid_eff_options: + raise ValueError(f"Invalid value for 'eff'. Must be one of {valid_eff_options}, but got '{eff}'.") + self.n = n # Max n-gram length (default: 4) + self.eff = eff # [shortest, average, longest] + self.special_reflen = special_reflen # Special reference length if specified + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "计算BLEU分数评估生成文本与参考文本的n-gram重叠度,支持1-4元语法分析。\n" + "输入参数:\n" + "- n:最大n-gram长度,默认为4\n" + "- eff:参考长度计算方式,可选'shortest'/'average'/'longest',默认为'average'\n" + "- special_reflen:特殊参考长度,默认为None\n" + "- input_key:生成文本字段名\n" + "- reference_key:参考文本字段名\n" + "- output_key:输出得分字段名,默认为'BleuScore'\n" + "输出参数:\n" + "- 包含BLEU得分的DataFrame" + ) + elif lang == "en": + return ( + "Evaluate n-gram overlap between generated and reference text using BLEU score (1-4 grams supported).\n" + "Input Parameters:\n" + "- n: Maximum n-gram length, default 4\n" + "- eff: Reference length calculation method, 'shortest'/'average'/'longest', default 'average'\n" + "- special_reflen: Special reference length, default None\n" + "- input_key: Field name for generated text\n" + "- reference_key: Field name for reference text\n" + "- output_key: Field name for output score, default 'BleuScore'\n" + "Output Parameters:\n" + "- DataFrame containing BLEU scores" + ) + else: + return "Evaluate text similarity using BLEU score." + + def _score_func(self, eval_text, ref_text): + bleu_scorer = Bleu( + test=eval_text, + refs=[ref_text], + n=self.n, + special_reflen=self.special_reflen, + ) + bleu_score, _ = bleu_scorer.compute_score(option=self.eff) + return bleu_score[0] + + def eval(self, dataframe, input_key, reference_key): + eval_data = dataframe[input_key] + ref_data = dataframe[reference_key] + self.logger.info(f"Evaluating {self.score_name}...") + scores = [self._score_func(eval_text, ref_text) for eval_text, ref_text in tqdm(zip(eval_data, ref_data), desc="BleuScorer Evaluating...")] + self.logger.info("Evaluation complete!") + return scores + + def run(self, storage: DataFlowStorage, input_key: str, input_reference_key: str, output_key: str='BleuScore'): + self.input_key = input_key + self.reference_key = input_reference_key + self.output_key = output_key + dataframe = storage.read("dataframe") + scores = self.eval(dataframe, input_key, self.reference_key) + dataframe[self.output_key] = scores + storage.write(dataframe) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/cider/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/cider/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/cider/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/cider/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..221449c99b78b470233ecf8b32a186decb042d55 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/cider/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/cider/__pycache__/cider.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/cider/__pycache__/cider.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7abb41059f354d6edb69cc426b2bd43442f2f353 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/cider/__pycache__/cider.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/cider/cider.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/cider/cider.py new file mode 100644 index 0000000000000000000000000000000000000000..8da31dd68e17c73d11044379345e5a1f0177fb28 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/cider/cider.py @@ -0,0 +1,134 @@ +import copy +import math +import pickle +import numpy as np +from collections import defaultdict +import os +from six.moves import xrange +import six + +def precook(s, n=4, out=False): + words = s.split() + counts = defaultdict(int) + for k in xrange(1, n+1): + for i in xrange(len(words)-k+1): + ngram = tuple(words[i:i+k]) + counts[ngram] += 1 + return counts + +def cook_refs(refs, n=4): + return [precook(ref, n) for ref in refs] + +def cook_test(test, n=4): + return precook(test, n, True) + +class Cider(object): + """CIDEr scorer.""" + + def copy(self): + new = Cider(n=self.n) + new.ctest = copy.copy(self.ctest) + new.crefs = copy.copy(self.crefs) + return new + + def __init__(self, test=None, refs=None, n=4, sigma=6.0, idf=None): + self.n = n + self.sigma = sigma + self.crefs = [] + self.ctest = [] + self.document_frequency = defaultdict(float) + self.ref_len = None + + if idf: + self.document_frequency = idf['df'] + self.ref_len = np.log(float(idf['ref_len'])) # Use reference length from the IDF + + self.cook_append(test, refs) + + def cook_append(self, test, refs): + if refs is not None: + self.crefs.append(cook_refs(refs)) + if test is not None: + self.ctest.append(cook_test(test)) + else: + self.ctest.append(None) + + def size(self): + assert len(self.crefs) == len(self.ctest), "refs/test mismatch! %d<>%d" % (len(self.crefs), len(self.ctest)) + return len(self.crefs) + + def __iadd__(self, other): + if type(other) is tuple: + self.cook_append(other[0], other[1]) + else: + self.ctest.extend(other.ctest) + self.crefs.extend(other.crefs) + return self + + def compute_doc_freq(self): + '''Compute term frequency for reference data to generate IDF.''' + if not self.document_frequency: # Handle empty DF (for 'corpus' mode) + for refs in self.crefs: + for ngram in set([ngram for ref in refs for (ngram, count) in ref.items()]): + self.document_frequency[ngram] += 1 + + def compute_cider(self, df_mode): + def counts2vec(cnts): + vec = [defaultdict(float) for _ in range(self.n)] + length = 0 + norm = [0.0 for _ in range(self.n)] + for (ngram, term_freq) in cnts.items(): + df = np.log(max(1.0, self.document_frequency[ngram])) + n = len(ngram) - 1 + vec[n][ngram] = float(term_freq) * (self.ref_len - df) + norm[n] += pow(vec[n][ngram], 2) + + if n == 1: + length += term_freq + norm = [np.sqrt(n) for n in norm] + return vec, norm, length + + def sim(vec_hyp, vec_ref, norm_hyp, norm_ref, length_hyp, length_ref): + delta = float(length_hyp - length_ref) + val = np.array([0.0 for _ in range(self.n)]) + for n in range(self.n): + for (ngram, count) in vec_hyp[n].items(): + val[n] += min(vec_hyp[n][ngram], vec_ref[n][ngram]) * vec_ref[n][ngram] + + if (norm_hyp[n] != 0) and (norm_ref[n] != 0): + val[n] /= (norm_hyp[n] * norm_ref[n]) + + val[n] *= np.e**(-(delta**2) / (2 * self.sigma**2)) + return val + + if df_mode == "corpus": + self.ref_len = np.log(float(len(self.crefs))) # Use total references in corpus as ref_len + + scores = [] + for test, refs in zip(self.ctest, self.crefs): + vec, norm, length = counts2vec(test) + score = np.array([0.0 for _ in range(self.n)]) + for ref in refs: + vec_ref, norm_ref, length_ref = counts2vec(ref) + score += sim(vec, vec_ref, norm, norm_ref, length, length_ref) + score_avg = np.mean(score) + score_avg /= len(refs) + score_avg *= 10.0 + scores.append(score_avg) + return scores + + def compute_score(self, df_mode, option=None, verbose=0): + '''Compute the CIDEr score based on df_mode (corpus or IDF-based).''' + self.compute_doc_freq() + + if df_mode == "corpus": + if not self.document_frequency: # Handle the case where DF is empty + raise ValueError("Document frequency is empty. Please check the corpus data.") + + min_required_data = max(self.document_frequency.values()) + # print(min_required_data)# For corpus mode, we require at least one reference + # if len(self.ctest) < min_required_data: + # raise ValueError(f"Insufficient test data: {len(self.ctest)} samples, but at least {min_required_data} are required.") + + score = self.compute_cider(df_mode) + return np.mean(np.array(score)), np.array(score) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/cider_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/cider_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..032b0c1df24f8ce853fc4fd1d5a9682a100c0d4e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/cider_sample_evaluator.py @@ -0,0 +1,93 @@ +import os +import json +import pickle +from tqdm import tqdm +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.operators.general_text.eval.cider.cider import Cider + +def load_idf(idf_path): + with open(idf_path, 'rb') as f: + idf = pickle.load(f, encoding='utf-8') + return idf + +@OPERATOR_REGISTRY.register() +class CiderSampleEvaluator(OperatorABC): + def __init__(self, n=4, sigma=6.0, df_mode="coco-val-df", idf_path="./dataflow/operators/general_pt/eval/cider/coco-val-df.p"): + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.score_name = 'CiderScore' + self.n = n # Max n-gram length (default: 4) + self.sigma = sigma # Sigma for Gaussian penalty (default: 6.0) + self.df_mode = df_mode + if self.df_mode != "corpus": + # The idf file can be downloaded at https://github.com/ramavedantam/coco-caption/blob/master/data/coco-val-df.p + # Put the file in the correct idf_path + self.idf = load_idf(idf_path) + else: + self.idf = None # No need to load IDF for 'corpus' mode + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "使用CIDEr指标评估生成文本与参考文本的相似度,基于TF-IDF加权的n-gram重叠度。\n" + "输入参数:\n" + "- n:最大n-gram长度,默认为4\n" + "- sigma:高斯惩罚参数,默认为6.0\n" + "- df_mode:文档频率模式,默认为'coco-val-df'\n" + "- idf_path:IDF文件路径,默认为预训练COCO数据集IDF\n" + "- input_key:生成文本字段名\n" + "- reference_key:参考文本字段名\n" + "- output_key:输出得分字段名,默认为'CiderScore'\n" + "输出参数:\n" + "- 包含CIDEr得分的DataFrame" + ) + elif lang == "en": + return ( + "Evaluate text similarity using CIDEr metric with TF-IDF weighted n-gram overlap.\n" + "Input Parameters:\n" + "- n: Maximum n-gram length, default 4\n" + "- sigma: Gaussian penalty parameter, default 6.0\n" + "- df_mode: Document frequency mode, default 'coco-val-df'\n" + "- idf_path: Path to IDF file, default pre-trained COCO dataset IDF\n" + "- input_key: Field name for generated text\n" + "- reference_key: Field name for reference text\n" + "- output_key: Field name for output score, default 'CiderScore'\n" + "Output Parameters:\n" + "- DataFrame containing CIDEr scores" + ) + else: + return "Evaluate text similarity using CIDEr metric." + + def _score_func(self, eval_text, ref_text): + cider_scorer = Cider( + test=eval_text, + refs=[ref_text], + n=self.n, + sigma=self.sigma, + idf=self.idf # Pass IDF (None if using 'corpus') + ) + # Pass df_mode dynamically based on the argument + cider_score, _ = cider_scorer.compute_score(df_mode='corpus' if self.idf is None else 'coco-val-df') + return cider_score + + def eval(self, dataframe, input_key, reference_key): + eval_data = dataframe[input_key] + ref_data = dataframe[reference_key] + self.logger.info(f"Evaluating {self.score_name}...") + scores = [self._score_func(eval_text, ref_text) for eval_text, ref_text in tqdm(zip(eval_data, ref_data), desc="CiderScorer Evaluating...")] + self.logger.info("Evaluation complete!") + return scores + + def run(self, storage: DataFlowStorage, input_key: str, input_reference_key: str, output_key: str='CiderScore'): + self.input_key = input_key + self.reference_key = input_reference_key + self.output_key = output_key + dataframe = storage.read("dataframe") + scores = self.eval(dataframe, input_key, self.reference_key) + dataframe[self.output_key] = scores + storage.write(dataframe) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/langkit_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/langkit_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..17ed87d6fefde5cecf77df2fc62207e8a2b8489e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/langkit_sample_evaluator.py @@ -0,0 +1,80 @@ +from dataflow.core import OperatorABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.storage import DataFlowStorage +from dataflow import get_logger +import pandas as pd +from langkit import light_metrics, extract +from tqdm import tqdm + +@OPERATOR_REGISTRY.register() +class LangkitSampleEvaluator(OperatorABC): + def __init__(self): + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.llm_schema = light_metrics.init() + self.score_name = 'LangkitScore' + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "使用Langkit工具包计算文本统计信息,帮助评估文本结构复杂性和可读性。提取多种语言特征,包括句子长度、词汇多样性、情感倾向等。\n\n" + "输出参数:\n" + "- LangkitNumSentencesScore: 句子数量\n" + "- LangkitNumWordsScore: 单词数量\n" + "- LangkitAvgWordLengthScore: 平均单词长度\n" + "- LangkitFleschReadingEaseScore: 可读性评分(Flesch公式)\n" + "- LangkitSentimentScore: 情感倾向(-1到1之间)" + ) + else: + return ( + "Uses Langkit toolkit to calculate text statistics for evaluating structural complexity and readability. Extracts multiple linguistic features including sentence length, lexical diversity, and sentiment.\n\n" + "Output Parameters:\n" + "- LangkitNumSentencesScore: Number of sentences\n" + "- LangkitNumWordsScore: Number of words\n" + "- LangkitAvgWordLengthScore: Average word length\n" + "- LangkitFleschReadingEaseScore: Readability score (Flesch formula)\n" + "- LangkitSentimentScore: Sentiment polarity (between -1 and 1)" + ) + + def _score_func(self, sample): + df = pd.DataFrame({'prompt': [sample]}) + df['response'] = '' + enhanced_df = extract(df, schema=self.llm_schema) + scores_dict = enhanced_df.to_dict(orient='records')[0] + processed_scores = {} + for k, v in scores_dict.items(): + if k == 'prompt': + continue + elif k.startswith('prompt.'): + new_key = k[len('prompt.'):] + processed_scores[new_key] = v + elif not (k == 'response' or k.startswith('response.')): + processed_scores[k] = v + processed_scores.pop('has_patterns', None) + result = {} + for k, v in processed_scores.items(): + score_key = f"Langkit{''.join([word.capitalize() for word in k.split('_')])}Score" + result[score_key] = v + + return result + + def eval(self, dataframe, input_key): + scores_list = [] + self.logger.info(f"Evaluating {self.score_name}...") + for sample in tqdm(dataframe[input_key], desc="LangkitScore Evaluating..."): + scores = self._score_func(sample) + scores_list.append(scores) + self.logger.info("Evaluation complete!") + return scores_list + + def run(self, storage: DataFlowStorage, input_key: str): + self.input_key = input_key + dataframe = storage.read("dataframe") + self.logger.info("LangkitScore ready to evaluate.") + scores = self.eval(dataframe, input_key) + for idx, score_dict in enumerate(scores): + for key, value in score_dict.items(): + dataframe.at[idx, key] = value + storage.write(dataframe) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/lexical_diversity_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/lexical_diversity_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..a77b064d41f291edda39da81a3621149ab9ba373 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/lexical_diversity_sample_evaluator.py @@ -0,0 +1,165 @@ +from dataflow.core import OperatorABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.storage import DataFlowStorage +from dataflow import get_logger +import string +from tqdm import tqdm + +remove_punctuation = str.maketrans('', '', string.punctuation) + +# mtld, hdd and other functions remain unchanged as they are utility functions +# ... (mtld_calc, mtld, factorial, combination, hypergeometric, hdd) + +def mtld_calc(word_array, ttr_threshold): + current_ttr = 1.0 + token_count = 0 + type_count = 0 + types = set() + factors = 0.0 + + for token in word_array: + token = token.translate(remove_punctuation).lower() + token_count += 1 + if token not in types: + type_count +=1 + types.add(token) + current_ttr = type_count / token_count + if current_ttr <= ttr_threshold: + factors += 1 + token_count = 0 + type_count = 0 + types = set() + current_ttr = 1.0 + + excess = 1.0 - current_ttr + excess_val = 1.0 - ttr_threshold + factors += excess / excess_val + if factors != 0: + return len(word_array) / factors + return -1 + +def mtld(word_array, ttr_threshold=0.72): + if isinstance(word_array, str): + raise ValueError("The input should be a list of str") + if len(word_array) < 50: + raise ValueError("The input length should be larger than 50") + return (mtld_calc(word_array, ttr_threshold) + mtld_calc(word_array[::-1], ttr_threshold)) / 2 + + +def factorial(x): + x=int(x) + result = 1 + for i in range(2, x + 1): + result *= i + return result + +def combination(n, r): + r_fact = factorial(r) + numerator = 1.0 + num = n-r+1.0 + while num < n+1.0: + numerator *= num + num += 1.0 + return numerator / r_fact + +def hypergeometric(population, population_successes, sample, sample_successes): + return (combination(population_successes, sample_successes) * + combination(population - population_successes, sample - sample_successes)) /\ + combination(population, sample) + +def hdd(word_array, sample_size=42.0): + if isinstance(word_array, str): + raise ValueError("The input should be a list of str") + if len(word_array) < 50: + raise ValueError("The input length should be larger than 50") + + type_counts = {} + for token in word_array: + token = token.translate(remove_punctuation).lower() + if token in type_counts: + type_counts[token] += 1.0 + else: + type_counts[token] = 1.0 + + hdd_value = 0.0 + for token_type in type_counts.keys(): + contribution = (1.0 - hypergeometric(len(word_array), sample_size, type_counts[token_type], 0.0)) / sample_size + hdd_value += contribution + + return hdd_value + + +@OPERATOR_REGISTRY.register() +class LexicalDiversitySampleEvaluator(OperatorABC): + def __init__(self): + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.metrics_to_keep = {'mtld': True, 'hdd': True} + self.score_name = 'LexicalDiversityScore' + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "使用MTLD(词汇多样性测量)和HDD(移动平均类型-标记比)方法计算文本词汇多样性。\n\n" + "功能说明:\n" + "- MTLD(词汇多样性测量):通过计算维持特定TTR阈值所需的单词数量来评估词汇多样性\n" + "- HDD(移动平均类型-标记比):基于样本的词汇丰富度估计\n\n" + "输入要求:文本长度需大于50个单词\n\n" + "输出参数:\n" + "- LexicalDiversityMTLDScore: MTLD多样性得分(值越高表示多样性越好)\n" + "- LexicalDiversityHD-DScore: HDD多样性得分(值越高表示多样性越好)" + ) + else: + return ( + "Measures text lexical diversity using MTLD (Measure of Textual Lexical Diversity) and HDD (Hypergeometric Distribution Diversity) methods.\n\n" + "Features:\n" + "- MTLD: Evaluates lexical diversity by calculating the number of words needed to maintain a specific TTR threshold\n" + "- HDD: Estimates vocabulary richness based on sampling\n\n" + "Input Requirement: Text length must exceed 50 words\n\n" + "Output Parameters:\n" + "- LexicalDiversityMTLDScore: MTLD diversity score (higher = more diverse)\n" + "- LexicalDiversityHD-DScore: HDD diversity score (higher = more diverse)" + ) + + def _score_func(self, sample): + text = sample + words = text.split() + scores = {} + # must ensure text length in the given interval + if self.metrics_to_keep.get('mtld'): + if len(words) > 50: + scores['LexicalDiversityMTLDScore'] = mtld(words) + else: + scores['LexicalDiversityMTLDScore'] = None + + if self.metrics_to_keep.get('hdd'): + if 50 < len(words) < 1000: + scores['LexicalDiversityHD-DScore'] = hdd(words) + else: + scores['LexicalDiversityHD-DScore'] = None + + return scores + + def eval(self, dataframe, input_key): + scores_list = [] + self.logger.info(f"Evaluating {self.score_name}...") + for sample in tqdm(dataframe[input_key], desc="LexicalDiversityScore Evaluating..."): + scores = self._score_func(sample) + scores_list.append(scores) + self.logger.info("Evaluation complete!") + return scores_list + + def run(self, storage: DataFlowStorage, input_key: str): + self.input_key = input_key + dataframe = storage.read("dataframe") + self.logger.info("LexicalDiversityScore ready to evaluate.") + + scores = self.eval(dataframe, input_key) + # Flatten the nested dictionary of scores into the dataframe + for idx, score_dict in enumerate(scores): + for key, value in score_dict.items(): + dataframe.at[idx, key] = value + storage.write(dataframe) + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/ngram_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/ngram_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..2b21c625d9bb05fdada190d58a6c9ad784632026 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/ngram_sample_evaluator.py @@ -0,0 +1,93 @@ +import re +from tqdm import tqdm +import pandas as pd +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from typing import Literal + +@OPERATOR_REGISTRY.register() +class NgramSampleEvaluator(OperatorABC): + + def __init__(self, ngrams: int = 5, language: Literal['zh', 'en'] = 'en'): + if language not in ['zh', 'en']: + raise ValueError(f"Unsupported language: '{language}'. Supported options are: ['zh', 'en'].") + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.ngrams = ngrams + self.language = language + self.score_name = 'NgramScore' + self.logger.info(f'{self.__class__.__name__} initialized. Mode: {self.language}') + + @staticmethod + def get_desc(lang: str = "en"): + # 默认返回英文描述 + if lang == "zh": + return ( + "计算文本中n-gram的重复比例,评估文本冗余度。\n" + "支持中文(字级别)和英文(词级别)模式。\n" + "初始化参数:\n" + "- ngrams: n-gram长度,默认为5\n" + "- language: 处理语言,'zh' 使用字粒度切分,其他使用空格分词,默认为 'en'\n" + "输出参数:\n" + "- NgramScore: n-gram重复比例得分(0到1之间,得分越高表示重复比例越低)" + ) + else: + return ( + "Evaluates text redundancy by calculating the n-gram repetition ratio.\n" + "Supports Chinese (character-level) and English (word-level) modes.\n\n" + "Initialization Parameters:\n" + "- ngrams: Length of n-grams, default is 5.\n" + "- language: Processing language. 'zh' for character-level splitting, others for whitespace splitting. Default is 'en'.\n\n" + "Output Parameters:\n" + "- NgramScore: N-gram repetition ratio score (0-1, higher score means less repetition/higher originality)." + ) + + def _score_func(self, sample): + content = sample + if not content or not isinstance(content, str): + return 0.0 + + content = content.lower() + # 移除标点符号 + content = re.sub(r'[^\w\s]', '', content) + + # --- 根据语言选择切分逻辑 --- + if self.language == 'zh': + # 中文模式:去除所有空格,按“字”切分 + content = re.sub(r'\s+', '', content) + tokens = list(content) + join_char = "" + else: + # 默认/英文模式:按“空格”切分 + tokens = content.split() + join_char = " " + # --------------------------- + + if len(tokens) < self.ngrams: + return 0.0 + + # 生成 n-grams + ngrams_list = [join_char.join(tokens[i:i + self.ngrams]) for i in range(len(tokens) - (self.ngrams - 1))] + + unique_ngrams = set(ngrams_list) + total_ngrams = len(ngrams_list) + unique_ngrams_count = len(unique_ngrams) + + repetition_score = unique_ngrams_count / total_ngrams if total_ngrams > 0 else 0.0 + return repetition_score + + def eval(self, dataframe: pd.DataFrame, input_key: str): + self.logger.info(f"Evaluating {self.score_name} (Language: {self.language})...") + scores = [self._score_func(sample) for sample in tqdm(dataframe[input_key], desc=f"NgramScorer ({self.language})")] + self.logger.info("Evaluation complete!") + return scores + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='NgramScore'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + scores = self.eval(dataframe, input_key) + dataframe[self.output_key] = scores + storage.write(dataframe) \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/perspective_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/perspective_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..44bd44a168fd38374cd982b8f268dbdd3fd2dff1 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/perspective_sample_evaluator.py @@ -0,0 +1,73 @@ +from googleapiclient import discovery +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +import pandas as pd +from dataflow.core import LLMServingABC +from dataflow.serving import PerspectiveAPIServing + +@OPERATOR_REGISTRY.register() +class PerspectiveSampleEvaluator(OperatorABC): + """Operator that assigns Perspective API toxicity scores to text inputs.""" + def __init__(self, serving: PerspectiveAPIServing = None): + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__}...") + self.serving = serving + self.score_name = 'PerspectiveScore' + self.logger.info(f"{self.__class__.__name__} initialized.") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "使用Perspective API评估文本的毒性,返回毒性概率,得分越高表明文本毒性越高。\n" + "输入参数:\n" + "- serving:Perspective API服务对象\n" + "- input_key:输入文本字段名\n" + "- output_key:输出得分字段名,默认'PerspectiveScore'\n" + "输出参数:\n" + "- 包含毒性评估得分的DataFrame" + ) + elif lang == "en": + return ( + "Assess text toxicity using PerspectiveAPI; higher scores indicate more toxicity.\n" + "Input Parameters:\n" + "- serving: Perspective API serving object\n" + "- input_key: Field name for input text\n" + "- output_key: Field name for output score, default 'PerspectiveScore'\n" + "Output Parameters:\n" + "- DataFrame containing toxicity assessment scores" + ) + else: + return "Assess text toxicity using PerspectiveAPI; higher scores indicate more toxicity." + + def get_score(self, samples: list[dict], input_key: str) -> list[float]: + # Extract texts, truncate if needed + texts = [] + max_bytes = 20480 + for sample in samples: + text = sample.get(input_key, '') or '' + encoded = text.encode('utf-8') + if len(encoded) > max_bytes: + text = encoded[:max_bytes].decode('utf-8', errors='ignore') + texts.append(text) + # Delegate to serving + return self.serving.generate_from_input(texts) + + def eval(self, dataframe: pd.DataFrame, input_key: str) -> list[float]: + self.logger.info(f"Evaluating {self.score_name}...") + samples = dataframe.to_dict(orient='records') + scores = self.get_score(samples, input_key) + self.logger.info("Evaluation complete!") + return scores + + def run(self, + storage: DataFlowStorage, + input_key: str, + output_key: str = 'PerspectiveScore'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + dataframe[self.output_key] = self.eval(dataframe, self.input_key) + storage.write(dataframe) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/presidio_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/presidio_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..ed9b5830f36b84c5a1c2f897f56b81761b1c0e89 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/presidio_sample_evaluator.py @@ -0,0 +1,73 @@ +from dataflow.core import OperatorABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from presidio_analyzer import AnalyzerEngine +from presidio_analyzer.nlp_engine import TransformersNlpEngine +from transformers import AutoModelForTokenClassification, AutoTokenizer +import warnings +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage + +# Presidio PII detection Scorer +@OPERATOR_REGISTRY.register() +class PresidioSampleEvaluator(OperatorABC): + def __init__(self, device='cuda', lang='en', model_cache_dir='./dataflow_cache'): + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.language = lang + self.device = device + self.model_cache_dir = model_cache_dir + self.model_name = 'dslim/bert-base-NER' + self.tokenizer = AutoTokenizer.from_pretrained(self.model_name, cache_dir=self.model_cache_dir) + self.model = AutoModelForTokenClassification.from_pretrained(self.model_name, cache_dir=self.model_cache_dir).to(self.device) + warnings.filterwarnings("ignore", category=UserWarning, module="spacy_huggingface_pipelines") + model_config = [{ + "lang_code": self.language, + "model_name": { + "spacy": "en_core_web_sm", + "transformers": self.model_name + } + }] + self.nlp_engine = TransformersNlpEngine(models=model_config) + self.analyzer = AnalyzerEngine(nlp_engine=self.nlp_engine) + self.score_name = 'PresidioScore' + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "使用Microsoft Presidio模型识别文本中的个人身份信息(PII),返回检测到的PII实体数量。支持多种实体类型如姓名、邮箱、电话号码等," + "基于dslim/bert-base-NER模型实现。适用于评估文本的隐私安全风险。\n" + "输入参数:\n" + "- text: 待检测的文本字符串\n" + "- lang: 语言类型,默认为'en'\n" + "输出参数:\n" + "- int: 检测到的PII实体数量" + ) + else: + return ( + "Detect personally identifiable information (PII) in text using the Microsoft Presidio model and return the count of detected PII entities. " + "Supports various entity types such as names, emails, phone numbers, etc., implemented based on the dslim/bert-base-NER model. Suitable for assessing text privacy and security risks.\n" + "Input parameters:\n" + "- text: Text string to be detected\n" + "- lang: Language type, default 'en'\n" + "Output parameters:\n" + "- int: Count of detected PII entities" + ) + + def eval(self, dataframe, input_key): + input_texts = dataframe.get(input_key, '').to_list() + results = [] + self.logger.info(f"Evaluating {self.score_name}...") + for text in input_texts: + analysis_results = self.analyzer.analyze(text=text, language=self.language) + pii_count = len(analysis_results) + results.append(pii_count) + self.logger.info("Evaluation complete!") + return results + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='PresidioScore'): + dataframe = storage.read("dataframe") + scores = self.eval(dataframe, input_key) + dataframe[output_key] = scores + storage.write(dataframe) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/task2vec/__pycache__/task2vec.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/task2vec/__pycache__/task2vec.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03770a3aeb26337ebd6772b809d1aff2ec4487ba Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/task2vec/__pycache__/task2vec.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/task2vec/__pycache__/task_similarity.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/task2vec/__pycache__/task_similarity.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..931cf3ee493dfc8cc2f1e3f25abd7eefc38f410f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/task2vec/__pycache__/task_similarity.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/task2vec/__pycache__/utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/task2vec/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d74ed21ff10c83f1e44027eafb6e65a6ac90149 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/task2vec/__pycache__/utils.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/task2vec/task2vec.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/task2vec/task2vec.py new file mode 100644 index 0000000000000000000000000000000000000000..23963aab56d21507654baf25a9dd108bdef4ff07 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/task2vec/task2vec.py @@ -0,0 +1,544 @@ +# Copyright 2017-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +# ANY KIND, either express or implied. See the License for the specific +# language governing permissions and limitations under the License. + +import itertools +import math +import random +from abc import ABC, abstractmethod + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch.optim import Optimizer +import numpy as np +from tqdm.auto import tqdm, trange +import logging +from torch.utils.data import DataLoader, Dataset + +from .utils import AverageMeter, get_error, get_device + +## LLM DIV +def set_seed(seed): + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + +## LLM DIV +def get_loss(logits: torch.tensor, targets: torch.tensor, ignore_index=None) -> torch.tensor: + """ + Computes the cross-entropy loss for either sequence classification or generation. + """ + assert logits.dim() == 3 and ignore_index is not None + loss = nn.CrossEntropyLoss(ignore_index=ignore_index) + logits = logits[:,:-1,:] + logits = logits.transpose(1, 2) # batch_size, vocab_size (i.e. num_classes), sequence_length + targets = targets[:,1:] + + return loss(logits, targets) + +class Embedding: + """ + task_embedding = diagonal of the FIM for the filters of size [F_total, 1] total filters for a network. + + Notes: + - the diagonal of the Fisher Information Matrix for each layer. + - embedding size should be the size of the total number of filters for the network. + """ + + def __init__(self, hessian, scale, meta=None): + self.hessian = np.array(hessian) + self.scale = np.array(scale) + self.meta = meta + + def __repr__(self): + return f'{self.hessian}' + + +class ProbeNetwork(ABC, nn.Module): + """Abstract class that all probe networks should inherit from. + + This is a standard torch.nn.Module but needs to expose a classifier property that returns the final classicifation + module (e.g., the last fully connected layer). + """ + + @property + @abstractmethod + def classifier(self): + raise NotImplementedError("Override the classifier property to return the submodules of the network that" + " should be interpreted as the classifier") + + @classifier.setter + @abstractmethod + def classifier(self, val): + raise NotImplementedError("Override the classifier setter to set the submodules of the network that" + " should be interpreted as the classifier") + + +class Task2Vec: + + def __init__(self, model: ProbeNetwork, skip_layers=0, max_samples=None, classifier_opts=None, + method='montecarlo', method_opts=None, loader_opts=None, bernoulli=False, mode='autoregressive'): ## LLM DIV + if classifier_opts is None: + classifier_opts = {} + if method_opts is None: + method_opts = {} + if loader_opts is None: + loader_opts = {} + assert method in ('variational', 'montecarlo') + assert skip_layers >= 0 + + self.model = model + # Fix batch norm running statistics (i.e., put batch_norm layers in eval mode) + self.model.train() + self.device = get_device(self.model) + self.skip_layers = skip_layers + self.max_samples = max_samples + self.classifier_opts = classifier_opts + self.method = method + self.method_opts = method_opts + self.loader_opts = loader_opts + self.bernoulli = bernoulli + self.mode = mode + if self.mode == "autoregressive": + self.loss_fn = get_loss + else: + self.loss_fn = nn.CrossEntropyLoss() if not self.bernoulli else nn.BCEWithLogitsLoss() + self.loss_fn = self.loss_fn.to(self.device) + + def embed(self, dataset: Dataset, epochs: int = 5): + ## LLM DIV + # Cache the last layer features (needed to train the classifier) and (if needed) the intermediate layer features + # so that we can skip the initial layers when computing the embedding + # dataset.train() + if self.mode == "autoregressive": + loss = None + print(f'{self.classifier_opts=}') + if self.classifier_opts: # is it something truthy? e.g., dict with something in it? + if self.classifier_opts.get('finetune', False): # finetune only if specified True, else no finetuning if not specified or False. + epochs = 0 + print(f'Warning: classifier_opts doesnt specify finetune or break early, thus no finetuning is being done. See: {self.classifier_opts=} {epochs=}') + loss = self._finetune_classifier(dataset, loader_opts=self.loader_opts, classifier_opts=self.classifier_opts, max_samples=self.max_samples, epochs=epochs) + else: + loss = self._finetune_classifier(dataset, loader_opts=self.loader_opts, classifier_opts=self.classifier_opts, max_samples=self.max_samples, epochs=epochs) + else: # self.classifier_opts might be None or {} + loss = self._finetune_classifier(dataset, loader_opts=self.loader_opts, classifier_opts=self.classifier_opts, max_samples=self.max_samples, epochs=epochs) + print(f'{loss=} (after fine tune, if not done it will be None)') + assert loss is not None, f'Err: {loss=}' + self.compute_fisher(dataset) + embedding = self.extract_embedding(self.model) + return embedding, loss + else: + if self.skip_layers > 0: + self._cache_features(dataset, indexes=(self.skip_layers, -1), loader_opts=self.loader_opts, + max_samples=self.max_samples) + else: + self._cache_features(dataset, max_samples=self.max_samples) + # Fits the last layer classifier using cached features + self._fit_classifier(**self.classifier_opts) + + if self.skip_layers > 0: + dataset = torch.utils.data.TensorDataset(self.model.layers[self.skip_layers].input_features, + self.model.layers[-1].targets) + + # dataset.eval() # I added this so that the embedding is computed on the val set + self.compute_fisher(dataset) + embedding = self.extract_embedding(self.model) + # dataset.train() # returns to using the support set + return embedding + + ### LLM DIV + def _finetune_classifier(self, dataset: Dataset, loader_opts: dict = None, classifier_opts: dict = None, max_samples=None, epochs = 5, learning_rate = 5e-5, adam_epsilon = 1e-8): + """Fits the last layer of the HuggingFace transformer probe network.""" + logging.info("Finetune classifier...") + if loader_opts is None: + loader_opts = {} + if classifier_opts is None: + classifier_opts = {} + data_loader = DataLoader(dataset, shuffle=False, batch_size=loader_opts.get('batch_size', 8), + num_workers=loader_opts.get('num_workers', 0), drop_last=False) + + device = next(self.model.parameters()).device + print("MODEL DEVICE: ", device) + + # num_examples = int(classifier_opts.get("task_batch_size", 256) / loader_opts.get('batch_size', 8)) + num_examples = len(list(data_loader)) # not ideal but it's quicker in dev time, usually we won't feed the entire data set to task2vec so this should be fine + n_batches = num_examples + + optimizer_grouped_parameters = [ + {'params': [p for p in self.model.lm_head.parameters()], + 'weight_decay': classifier_opts.get("weight_decay",0.0001)}, + ] + + optimizer = torch.optim.AdamW(optimizer_grouped_parameters, lr=classifier_opts.get("learning_rate",learning_rate), eps=classifier_opts.get("adam_epsilon",adam_epsilon)) + + # Train! + logging.info("***** Running training *****") + # logging.info(" Num examples = %d", num_examples) + logging.info(" Num Epochs = %d", epochs) + logging.info(" Batch size = %d", loader_opts.get('batch_size', 8)) + + train_iterator = trange(classifier_opts.get("epochs", epochs), desc="Epoch", leave=False) + set_seed(classifier_opts.get("seed", 42)) # Added here for reproductibility (even between python 2 and 3) + + self.model.train() + for epoch in train_iterator: + metrics = AverageMeter() + epoch_iterator = tqdm(data_loader, desc="Iteration", total=n_batches, leave=False) + for step, batch in enumerate(epoch_iterator): + optimizer.zero_grad() + inputs = {'input_ids': batch['input_ids'].to(device), + 'attention_mask': batch['attention_mask'].to(device)} + logits = self.model(**inputs, labels=inputs["input_ids"]).logits + loss = self.loss_fn(logits, inputs["input_ids"], ignore_index=50256) + print(f'\nInitial loss {loss.item()} ({step=} {epoch=})') if step == 0 else None + error = get_error(logits, inputs['input_ids'], ignore_index=50256) + loss.backward() + optimizer.step() + + metrics.update(n=batch['input_ids'].shape[0], loss=loss.item(), error=error) + epoch_iterator.update(1) + + if classifier_opts.get("break_early", False): + print("----> breaking early") + break + if classifier_opts.get("break_early", False): + break + logging.info(f"[epoch {epoch}]: " + "\t".join(f"{k}: {v}" for k, v in metrics.avg.items())) + print(f'\nfinal loss {step=} {epoch=} of final layer loss {loss.item()} (note we are not recomputing loss after a step so this loss printed is larger than it should be/one off)') + return loss.item() + + ### LLM DIV + def montecarlo_fisher_autoregressive(self, dataset: Dataset, epochs: int = 1): + logging.info("Using montecarlo Fisher") + if self.loader_opts is None: + loader_opts = {} + else: + loader_opts = self.loader_opts + + data_loader = DataLoader(dataset, shuffle=False, batch_size=loader_opts.get('batch_size', 8), + num_workers=loader_opts.get('num_workers', 0), drop_last=False) + device = get_device(self.model) + + # num_examples = int(classifier_opts.get("task_batch_size", 256) / loader_opts.get('batch_size', 8)) + num_examples = len(list(data_loader)) # not idea but it's quicker in dev time, usually we won't feed the entire data set to task2vec so this should be fine + n_batches = num_examples + + logging.info("Computing Fisher...") + for p in self.model.parameters(): + p.grad2_acc = torch.zeros_like(p.data) + p.grad_counter = 0 + + for k in range(epochs): + logging.info(f"\tepoch {k + 1}/{epochs}") + + epoch_iterator = tqdm(data_loader, desc="Iteration", total=n_batches, leave=False) + for step, batch in enumerate(epoch_iterator): + inputs = {'input_ids': batch['input_ids'].to(device), + 'attention_mask': batch['attention_mask'].to(device)} + logits = self.model(**inputs, labels=inputs["input_ids"]).logits + + # The gradients used to compute the FIM needs to be for y sampled from + # the model distribution y ~ p_w(y|x), not for y from the dataset + if self.bernoulli: + target = torch.bernoulli(F.sigmoid(logits[:,:-1,:])).detach() + else: + softmax_output = F.softmax(logits, dim=-1) + lst = [torch.multinomial(softmax_output[i,:,:], 1).detach().view(-1) for i in range(len(softmax_output))] + target = torch.stack(lst, dim=0) + + loss = self.loss_fn(logits, target, ignore_index=50256) + self.model.zero_grad() + loss.backward() + for p in self.model.parameters(): + if p.grad is not None: + p.grad2_acc += p.grad.data ** 2 + p.grad_counter += 1 + if self.classifier_opts.get("break_early", False): + break # for debugging faster, otherwise FIM is really slow + if self.classifier_opts.get("break_early", False): + break # for debugging faster, otherwise FIM is really slow + for p in self.model.parameters(): + if p.grad_counter == 0: + del p.grad2_acc + else: + p.grad2_acc /= p.grad_counter + logging.info("done") + + def montecarlo_fisher(self, dataset: Dataset, epochs: int = 1): + logging.info("Using montecarlo Fisher") + if self.skip_layers > 0: + dataset = torch.utils.data.TensorDataset(self.model.layers[self.skip_layers].input_features, + self.model.layers[-1].targets) + data_loader = _get_loader(dataset, **self.loader_opts) + device = get_device(self.model) + logging.info("Computing Fisher...") + + for p in self.model.parameters(): + p.grad2_acc = torch.zeros_like(p.data) + p.grad_counter = 0 + for k in range(epochs): + logging.info(f"\tepoch {k + 1}/{epochs}") + for i, (data, target) in enumerate(tqdm(data_loader, leave=False, desc="Computing Fisher")): + data = data.to(device) + output = self.model(data, start_from=self.skip_layers) + # The gradients used to compute the FIM needs to be for y sampled from + # the model distribution y ~ p_w(y|x), not for y from the dataset + if self.bernoulli: + target = torch.bernoulli(F.sigmoid(output)).detach() + else: + target = torch.multinomial(F.softmax(output, dim=-1), 1).detach().view(-1) + loss = self.loss_fn(output, target) + self.model.zero_grad() + loss.backward() + for p in self.model.parameters(): + if p.grad is not None: + p.grad2_acc += p.grad.data ** 2 + p.grad_counter += 1 + for p in self.model.parameters(): + if p.grad_counter == 0: + del p.grad2_acc + else: + p.grad2_acc /= p.grad_counter + logging.info("done") + + def _run_epoch(self, data_loader: DataLoader, model: ProbeNetwork, loss_fn, + optimizer: Optimizer, epoch: int, train: bool = True, + add_compression_loss: bool = False, skip_layers=0, beta=1.0e-7): + metrics = AverageMeter() + device = get_device(model) + + for i, (input, target) in enumerate(tqdm(data_loader, leave=False, desc="Computing Fisher")): + input = input.to(device) + target = target.to(device) + output = model(input, start_from=skip_layers) + + loss = loss_fn(output, target) + lz = beta * variational.get_compression_loss(model) if add_compression_loss else torch.zeros_like(loss) + loss += lz + + error = get_error(output, target) + + metrics.update(n=input.size(0), loss=loss.item(), lz=lz.item(), error=error) + if train: + optimizer.zero_grad() + loss.backward() + optimizer.step() + # logging.info( + print( + "{}: [{epoch}] ".format('Epoch' if train else '', epoch=epoch) + + "Data/Batch: {:.3f}/{:.3f} ".format(metrics.avg["data_time"], metrics.avg["batch_time"]) + + "Loss {:.3f} Lz: {:.3f} ".format(metrics.avg["loss"], metrics.avg["lz"]) + + "Error: {:.2f}".format(metrics.avg["error"]) + ) + return metrics.avg + + def variational_fisher(self, dataset: Dataset, epochs=1, beta=1e-7): + logging.info("Training variational fisher...") + parameters = [] + for layer in self.model.layers[self.skip_layers:-1]: + if isinstance(layer, nn.Module): # Skip lambda functions + variational.make_variational(layer) + parameters += variational.get_variational_vars(layer) + bn_params = [] + # Allows batchnorm parameters to change + for m in self.model.modules(): + if isinstance(m, nn.BatchNorm2d): + bn_params += list(m.parameters()) + # Avoids computing the gradients wrt to the weights to save time and memory + for p in self.model.parameters(): + if p not in set(parameters) and p not in set(self.model.classifier.parameters()): + p.old_requires_grad = p.requires_grad + p.requires_grad = False + + optimizer = torch.optim.Adam([ + {'params': parameters}, + {'params': bn_params, 'lr': 5e-4}, + {'params': self.model.classifier.parameters(), 'lr': 5e-4}], + lr=1e-2, betas=(.9, 0.999)) + if self.skip_layers > 0: + dataset = torch.utils.data.TensorDataset(self.model.layers[self.skip_layers].input_features, + self.model.layers[-1].targets) + train_loader = _get_loader(dataset, **self.loader_opts) + + for epoch in range(epochs): + self._run_epoch(train_loader, self.model, self.loss_fn, optimizer, epoch, beta=beta, + add_compression_loss=True, train=True) + + # Resets original value of requires_grad + for p in self.model.parameters(): + if hasattr(p, 'old_requires_grad'): + p.requires_grad = p.old_requires_grad + del p.old_requires_grad + + def compute_fisher(self, dataset: Dataset): + """ + Computes the Fisher Information of the weights of the model wrt the model output on the dataset and stores it. + + The Fisher Information Matrix is defined as: + F = E_{x ~ dataset} E_{y ~ p_w(y|x)} [\nabla_w log p_w(y|x) \nabla_w log p_w(y|x)^t] + where p_w(y|x) is the output probability vector of the network and w are the weights of the network. + Notice that the label y is sampled from the model output distribution and not from the dataset. + + This code only approximate the diagonal of F. The result is stored in the model layers and can be extracted + using the `get_fisher` method. Different approximation methods of the Fisher information matrix are available, + and can be selected in the __init__. + + :param dataset: dataset with the task to compute the Fisher on + """ + if self.mode == 'autoregressive' and self.method == 'montecarlo': + fisher_fn = self.montecarlo_fisher_autoregressive + elif self.method == 'variational': + fisher_fn = self.variational_fisher + elif self.method == 'montecarlo': + fisher_fn = self.montecarlo_fisher + else: + raise ValueError(f"Invalid Fisher method {self.method}") + fisher_fn(dataset, **self.method_opts) + + def _cache_features(self, dataset: Dataset, indexes=(-1,), max_samples=None, loader_opts: dict = None): + logging.info("Caching features...") + if loader_opts is None: + loader_opts = {} + data_loader = DataLoader(dataset, shuffle=False, batch_size=loader_opts.get('batch_size', 64), + num_workers=loader_opts.get('num_workers', 0), drop_last=False) + + device = next(self.model.parameters()).device + + def _hook(layer, inputs): + if not hasattr(layer, 'input_features'): + layer.input_features = [] + layer.input_features.append(inputs[0].data.cpu().clone()) + + hooks = [self.model.layers[index].register_forward_pre_hook(_hook) + for index in indexes] + if max_samples is not None: + n_batches = min( + math.floor(max_samples / data_loader.batch_size) - 1, len(data_loader)) + else: + n_batches = len(data_loader) + targets = [] + + for i, (input, target) in tqdm(enumerate(itertools.islice(data_loader, 0, n_batches)), total=n_batches, + leave=False, + desc="Caching features"): + targets.append(target.clone()) + self.model(input.to(device)) + for hook in hooks: + hook.remove() + for index in indexes: + self.model.layers[index].input_features = torch.cat(self.model.layers[index].input_features) + self.model.layers[-1].targets = torch.cat(targets) + + def _fit_classifier(self, optimizer='adam', learning_rate=0.0004, weight_decay=0.0001, + epochs=10): + """Fits the last layer of the network using the cached features.""" + logging.info("Fitting final classifier...") + if not hasattr(self.model.classifier, 'input_features'): + raise ValueError("You need to run `cache_features` on model before running `fit_classifier`") + targets = self.model.classifier.targets.to(self.device) + features = self.model.classifier.input_features.to(self.device) + + dataset = torch.utils.data.TensorDataset(features, targets) + data_loader = _get_loader(dataset, **self.loader_opts) + + if optimizer == 'adam': + optimizer = torch.optim.Adam(self.model.fc.parameters(), lr=learning_rate, weight_decay=weight_decay) + elif optimizer == 'sgd': + optimizer = torch.optim.SGD(self.model.fc.parameters(), lr=learning_rate, weight_decay=weight_decay) + else: + raise ValueError(f'Unsupported optimizer {optimizer}') + + loss_fn = nn.CrossEntropyLoss() + for epoch in tqdm(range(epochs), desc="Fitting classifier", leave=False): + metrics = AverageMeter() + for data, target in data_loader: + optimizer.zero_grad() + output = self.model.classifier(data) + loss = loss_fn(self.model.classifier(data), target) + error = get_error(output, target) + loss.backward() + optimizer.step() + metrics.update(n=data.size(0), loss=loss.item(), error=error) + logging.info(f"[epoch {epoch}]: " + "\t".join(f"{k}: {v}" for k, v in metrics.avg.items())) + print(f'\nfinal loss after fitting final layer {loss=}') + + def extract_embedding(self, model: ProbeNetwork): + """ + Reads the values stored by `compute_fisher` and returns them in a common format that describes the diagonal of the + Fisher Information Matrix for each layer. + + :param model: + :return: + """ + if self.mode == 'autoregressive': + hess, scale = [], [] + for name, module in model.named_modules(): + if module is model.lm_head: + continue + # The other Fisher approximation methods directly approximate the hessian at the minimum + if hasattr(module, 'weight') and hasattr(module.weight, 'grad2_acc'): + grad2 = module.weight.grad2_acc.cpu().detach().numpy() + filterwise_hess = grad2.reshape(grad2.shape[0], -1).mean(axis=1) + hess.append(filterwise_hess) + scale.append(np.ones_like(filterwise_hess)) + else: + hess, scale = [], [] + for name, module in model.named_modules(): + if module is model.classifier: + continue + # The variational Fisher approximation estimates the variance of noise that can be added to the weights + # without increasing the error more than a threshold. The inverse of this is proportional to an + # approximation of the hessian in the local minimum. + if hasattr(module, 'logvar0') and hasattr(module, 'loglambda2'): + logvar = module.logvar0.view(-1).detach().cpu().numpy() + hess.append(np.exp(-logvar)) + loglambda2 = module.loglambda2.detach().cpu().numpy() + scale.append(np.exp(-loglambda2).repeat(logvar.size)) + # The other Fisher approximation methods directly approximate the hessian at the minimum + elif hasattr(module, 'weight') and hasattr(module.weight, 'grad2_acc'): + grad2 = module.weight.grad2_acc.cpu().detach().numpy() + filterwise_hess = grad2.reshape(grad2.shape[0], -1).mean(axis=1) + hess.append(filterwise_hess) + scale.append(np.ones_like(filterwise_hess)) + return Embedding(hessian=np.concatenate(hess), scale=np.concatenate(scale), meta=None) + + +def _get_loader(trainset, testset=None, batch_size=64, num_workers=0, num_samples=10000, drop_last=True): + if getattr(trainset, 'is_multi_label', False): + raise ValueError("Multi-label datasets not supported") + # TODO: Find a way to standardize this + if hasattr(trainset, 'labels'): + labels = trainset.labels + elif hasattr(trainset, 'targets'): + labels = trainset.targets + else: + labels = list(trainset.tensors[1].cpu().numpy()) + num_classes = int(getattr(trainset, 'num_classes', max(labels) + 1)) + class_count = np.eye(num_classes)[labels].sum(axis=0) + weights = 1. / class_count[labels] / num_classes + weights /= weights.sum() + + sampler = torch.utils.data.sampler.WeightedRandomSampler(weights, num_samples=num_samples) + # No need for mutli-threaded loading if everything is already in memory, + # and would raise an error if TensorDataset is on CUDA + num_workers = num_workers if not isinstance(trainset, torch.utils.data.TensorDataset) else 0 + trainloader = torch.utils.data.DataLoader(trainset, sampler=sampler, batch_size=batch_size, + num_workers=num_workers, drop_last=drop_last) + + if testset is None: + return trainloader + else: + testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size, pin_memory=True, shuffle=False, + num_workers=num_workers) + return trainloader, testloader diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/task2vec/task_similarity.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/task2vec/task_similarity.py new file mode 100644 index 0000000000000000000000000000000000000000..141089cc42a055d19a14401cf72250086a8ec03b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/task2vec/task_similarity.py @@ -0,0 +1,485 @@ +#!/usr/bin/env python3 + +# Copyright 2017-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +# ANY KIND, either express or implied. See the License for the specific +# language governing permissions and limitations under the License. + +import itertools +from typing import Tuple + +import scipy.spatial.distance as distance +import numpy as np +import copy +import pickle + +# import uutils + +_DISTANCES = {} + + +# TODO: Remove methods that do not perform well + +def _register_distance(distance_fn): + _DISTANCES[distance_fn.__name__] = distance_fn + return distance_fn + + +def is_excluded(k): + exclude = ['fc', 'linear'] + return any([e in k for e in exclude]) + + +def load_embedding(filename): + with open(filename, 'rb') as f: + e = pickle.load(f) + return e + + +def get_trivial_embedding_from(e): + trivial_embedding = copy.deepcopy(e) + for l in trivial_embedding['layers']: + a = np.array(l['filter_logvar']) + a[:] = l['filter_lambda2'] + l['filter_logvar'] = list(a) + return trivial_embedding + + +def binary_entropy(p): + from scipy.special import xlogy + return - (xlogy(p, p) + xlogy(1. - p, 1. - p)) + + +def get_layerwise_variance(e, normalized=False): + var = [np.exp(l['filter_logvar']) for l in e['layers']] + if normalized: + var = [v / np.linalg.norm(v) for v in var] + return var + + +def get_variance(e, normalized=False): + var = 1. / np.array(e.hessian) + if normalized: + lambda2 = 1. / np.array(e.scale) + var = var / lambda2 + return var + + +def get_variances(*embeddings, normalized=False): + return [get_variance(e, normalized=normalized) for e in embeddings] + + +def get_hessian(e, normalized=False): + hess = np.array(e.hessian) + if normalized: + scale = np.array(e.scale) + hess = hess / scale + return hess + + +def get_hessians(*embeddings, normalized=False): + return [get_hessian(e, normalized=normalized) for e in embeddings] + + +def get_scaled_hessian(e0, e1): + h0, h1 = get_hessians(e0, e1, normalized=False) + return h0 / (h0 + h1 + 1e-8), h1 / (h0 + h1 + 1e-8) + + +def get_full_kl(e0, e1): + var0, var1 = get_variance(e0), get_variance(e1) + kl0 = .5 * (var0 / var1 - 1 + np.log(var1) - np.log(var0)) + kl1 = .5 * (var1 / var0 - 1 + np.log(var0) - np.log(var1)) + return kl0, kl1 + + +def layerwise_kl(e0, e1): + layers0, layers1 = get_layerwise_variance(e0), get_layerwise_variance(e1) + kl0 = [] + for var0, var1 in zip(layers0, layers1): + kl0.append(np.sum(.5 * (var0 / var1 - 1 + np.log(var1) - np.log(var0)))) + return kl0 + + +def layerwise_cosine(e0, e1): + layers0, layers1 = get_layerwise_variance(e0, normalized=True), get_layerwise_variance(e1, normalized=True) + res = [] + for var0, var1 in zip(layers0, layers1): + res.append(distance.cosine(var0, var1)) + return res + + +@_register_distance +def kl(e0, e1): + var0, var1 = get_variance(e0), get_variance(e1) + kl0 = .5 * (var0 / var1 - 1 + np.log(var1) - np.log(var0)) + kl1 = .5 * (var1 / var0 - 1 + np.log(var0) - np.log(var1)) + return np.maximum(kl0, kl1).sum() + + +@_register_distance +def asymmetric_kl(e0, e1): + var0, var1 = get_variance(e0), get_variance(e1) + kl0 = .5 * (var0 / var1 - 1 + np.log(var1) - np.log(var0)) + kl1 = .5 * (var1 / var0 - 1 + np.log(var0) - np.log(var1)) + return kl0.sum() + + +@_register_distance +def jsd(e0, e1): + var0, var1 = get_variance(e0), get_variance(e1) + var = .5 * (var0 + var1) + kl0 = .5 * (var0 / var - 1 + np.log(var) - np.log(var0)) + kl1 = .5 * (var1 / var - 1 + np.log(var) - np.log(var1)) + return (.5 * (kl0 + kl1)).mean() + + +@_register_distance +def cosine(e0, e1): + h1, h2 = get_scaled_hessian(e0, e1) + return distance.cosine(h1, h2) + + +@_register_distance +def normalized_cosine(e0, e1): + h1, h2 = get_variances(e0, e1, normalized=True) + return distance.cosine(h1, h2) + + +@_register_distance +def correlation(e0, e1): + v1, v2 = get_variances(e0, e1, normalized=False) + return distance.correlation(v1, v2) + + +@_register_distance +def entropy(e0, e1): + h1, h2 = get_scaled_hessian(e0, e1) + return np.log(2) - binary_entropy(h1).mean() + + +def get_normalized_embeddings(embeddings, normalization=None): + F = [1. / get_variance(e, normalized=False) if e is not None else None for e in embeddings] + zero_embedding = np.zeros_like([x for x in F if x is not None][0]) + F = np.array([x if x is not None else zero_embedding for x in F]) + # FIXME: compute variance using only valid embeddings + if normalization is None: + normalization = np.sqrt((F ** 2).mean(axis=0, keepdims=True)) + F /= normalization + return F, normalization + + +def pdist(embeddings, distance='cosine') -> np.ndarray: + distance_fn = _DISTANCES[distance] + n = len(embeddings) + distance_matrix = np.zeros([n, n]) + if distance != 'asymmetric_kl': + for (i, e1), (j, e2) in itertools.combinations(enumerate(embeddings), 2): + distance_matrix[i, j] = distance_fn(e1, e2) + distance_matrix[j, i] = distance_matrix[i, j] + else: + for (i, e1) in enumerate(embeddings): + for (j, e2) in enumerate(embeddings): + distance_matrix[i, j] = distance_fn(e1, e2) + return distance_matrix + + +def cross_pdist(embeddings1, embeddings2, distance='cosine') -> np.ndarray : + """ + Compute pairwise distance between embeddings1 and embeddings2. + + ref: https://chat.openai.com/share/a5ca38dc-3393-4cfd-971c-4a29b0c56b63 + """ + distance_fn = _DISTANCES[distance] + n1 = len(embeddings1) + n2 = len(embeddings2) + distance_matrix = np.zeros([n1, n2]) + if distance != 'asymmetric_kl': + for i, e1 in enumerate(embeddings1): + for j, e2 in enumerate(embeddings2): + distance_matrix[i, j] = distance_fn(e1, e2) + else: + for i, e1 in enumerate(embeddings1): + for j, e2 in enumerate(embeddings2): + distance_matrix[i, j] = distance_fn(e1, e2) + return distance_matrix + + +def cdist(from_embeddings, to_embeddings, distance='cosine'): + distance_fn = _DISTANCES[distance] + distance_matrix = np.zeros([len(from_embeddings), len(to_embeddings)]) + for (i, e1) in enumerate(from_embeddings): + for (j, e2) in enumerate(to_embeddings): + if e1 is None or e2 is None: + continue + distance_matrix[i, j] = distance_fn(e1, e2) + return distance_matrix + + +def plot_distance_matrix(embeddings, labels=None, distance='cosine', show_plot=True): + import seaborn as sns + from scipy.cluster.hierarchy import linkage + from scipy.spatial.distance import squareform + import pandas as pd + import matplotlib.pyplot as plt + distance_matrix = pdist(embeddings, distance=distance) + cond_distance_matrix = squareform(distance_matrix, checks=False) + linkage_matrix = linkage(cond_distance_matrix, method='complete', optimal_ordering=True) + if labels is not None: + distance_matrix = pd.DataFrame(distance_matrix, index=labels, columns=labels) + sns.clustermap(distance_matrix, row_linkage=linkage_matrix, col_linkage=linkage_matrix, cmap='viridis_r') + if show_plot: + plt.show() + +## LLM DIV +def plot_distance_matrix_heatmap_only(embeddings, labels=None, distance='cosine', show_plot=True, title=None, save_file=None): + import seaborn as sns + import pandas as pd + import matplotlib.pyplot as plt + distance_matrix = pdist(embeddings, distance=distance) + if labels is not None: + distance_matrix = pd.DataFrame(distance_matrix, index=labels, columns=labels) + sns.heatmap(distance_matrix, cmap='viridis_r') + if title: + plt.title(title) + if save_file: + _ = plt.savefig("plots/" + save_file + ".png", bbox_inches='tight') + if show_plot: + plt.show() + +## LLM DIV +def plot_distance_matrix_from_distance_matrix(distance_matrix, labels=None, show_plot=True, title=None, save_file=None, cluster=False, plot_multi=False): + import seaborn as sns + from scipy.cluster.hierarchy import linkage + from scipy.spatial.distance import squareform + import pandas as pd + import matplotlib.pyplot as plt + + cond_distance_matrix = squareform(distance_matrix, checks=False) + linkage_matrix = linkage(cond_distance_matrix, method='complete', optimal_ordering=True) + if labels is not None: + distance_matrix = pd.DataFrame(distance_matrix, index=labels, columns=labels) + + # plot multiple subplots in one figure + # distance_matrix passed in is a list of distance_matrix (np.arrays) + if plot_multi and not cluster: + num_rows, num_cols = 3, 2 + f, ax = plt.subplots(num_rows, num_cols)#, figsize=(12, 15)) + i = 0 + for row_ind in range(len(num_rows)): + for col_ind in range(len(num_cols)): + sns.heatmap(distance_matrix[i], cmap='viridis_r', ax=ax[row_ind, col_ind]) + i += 1 + else: + if cluster: + sns.clustermap(distance_matrix, row_linkage=linkage_matrix, col_linkage=linkage_matrix, cmap='viridis_r') + else: + sns.heatmap(distance_matrix, cmap='viridis_r') + + if title: + plt.title(title) + if save_file: + _ = plt.savefig("plots/" + save_file + ".png", bbox_inches='tight') + if show_plot: + plt.show() + +## LLM DIV +# plot multiple subplots in one figure +# distance_matrix passed in is a list of distance_matrix np.arrays +def plot_multi_distance_matrix_from_distance_matrix_list(distance_matrix_lst, title_lst, labels, main_title=None, show_plot=True, title=None, save_file=None, vmin=None, vmax=None): + import seaborn as sns + from scipy.cluster.hierarchy import linkage + from scipy.spatial.distance import squareform + import pandas as pd + import matplotlib.pyplot as plt + import math + num_rows, num_cols = math.ceil(len(distance_matrix_lst)/2), 2 + if len(distance_matrix_lst) % 2 == 1: + figsize = (12,10) + else: + figsize = (12,10) + f, ax = plt.subplots(num_rows, num_cols, figsize=figsize) + i = 0 + for row_ind in range(num_rows): + for col_ind in range(num_cols): + if i >= len(distance_matrix_lst): + break + distance_matrix = distance_matrix_lst[i] + distance_matrix = pd.DataFrame(distance_matrix, index=labels[i], columns=labels[i]) + if len(distance_matrix_lst) > 2: + ax[row_ind, col_ind].set_aspect('equal') + if vmin is not None and vmax is not None: + sns.heatmap(distance_matrix, cmap='viridis_r', ax=ax[row_ind, col_ind], vmin=vmin, vmax=vmax) + else: + sns.heatmap(distance_matrix, cmap='viridis_r', ax=ax[row_ind, col_ind]) + ax[row_ind, col_ind].set_title(title_lst[i]) + else: + ax[col_ind].set_aspect('equal') + sns.heatmap(distance_matrix, cmap='viridis_r', ax=ax[col_ind]) + ax[col_ind].set_title(title_lst[i]) + + i += 1 + if len(distance_matrix_lst) % 2 == 1: + f.delaxes(ax[num_rows-1,1]) + + if main_title: + f.suptitle(main_title) + f.subplots_adjust(top=0.5) + + if len(distance_matrix_lst) % 2 == 1: + plt.tight_layout(h_pad=2) + else: + plt.tight_layout(h_pad=2, w_pad=5) + if save_file: + _ = plt.savefig("plots/" + save_file + ".png", bbox_inches='tight') + if show_plot: + plt.show() + +## LLM DIV +def stats_of_distance_matrix(distance_matrix: np.ndarray, + remove_diagonal: bool = True, + variance_type: str = 'std', # TODO: was ci_0.95. Changed to rid uutils call + get_total: bool = False, + ) -> Tuple[float, float]: + if remove_diagonal: + # - remove diagonal: ref https://stackoverflow.com/questions/46736258/deleting-diagonal-elements-of-a-numpy-array + triu: np.ndarray = np.triu(distance_matrix) + tril: np.ndarray = np.tril(distance_matrix) + # distance_matrix = distance_matrix[~np.eye(distance_matrix.shape[0], dtype=bool)].reshape(distance_matrix.shape[0], -1) + # remove diagonal and dummy zeros where the other triangular matrix was artificially placed. + distance_matrix = triu[triu != 0.0] + + # - flatten + distance_matrix: np.ndarray = distance_matrix.flatten() + + # - compute stats of distance matrix + if variance_type == 'std': + mu, var = distance_matrix.mean(), distance_matrix.std() + # elif variance_type == 'ci_0.95': + # from uutils.torch_uu.metrics.confidence_intervals import mean_confidence_interval + # mu, var = mean_confidence_interval(distance_matrix, confidence=0.95) + else: + raise ValueError(f'Invalid variance type, got: {variance_type=}') + + # - double checks the mean was computed corrects. Since it's symmetric the mean after removing diagonal should be equal to just one side of the diagonals + if remove_diagonal: + # from uutils.torch_uu import approx_equal + # assert approx_equal(triu.sum(), tril.sum(), tolerance=1e-4), f'Distance matrix is not symmetric, are you sure this is correct?' + # assert approx_equal(distance_matrix.mean(), triu[triu != 0.0].mean(), tolerance=1e-4), f'Mean should be equal to triangular matrix' + # assert approx_equal(mu, triu[triu != 0.0].mean(), tolerance=1e-4) + + print('Lower tri sum', tril.sum(), ' / Upper tri sum', triu.sum(), '| These should be approx equal!!') + print('Total mean', distance_matrix.mean(), ' / Upper mean', triu[triu != 0.0].mean(), ' / Lower mean', tril[tril != 0.0].mean(), '| These should all be approx equal!!') + print('mu (div coefficient)', mu, ' / Upper mean', triu[triu != 0.0].mean(), '| These should all be approx equal!!') + if get_total: + total = distance_matrix.sum() + return mu, var, total + else: + return mu, var + + +def stats_cross_distance_matrix(distance_matrix: np.ndarray, + remove_diagonal: bool = False, + variance_type: str = 'std', # TODO: was ci_0.95. Changed to rid uutils call + get_total: bool = False, + ) -> Tuple[float, float]: + return stats_of_distance_matrix(distance_matrix, remove_diagonal=remove_diagonal, variance_type=variance_type, get_total=get_total) + + +def plot_histogram_of_distances(distance_matrix: np.ndarray, title, show_plot=True, save_file=None, bins_width=None, grid=True): + import matplotlib.pyplot as plt + triu = np.triu(distance_matrix) + triu = triu[triu != 0.0] + distance_values = triu.flatten() + + if grid: + plt.grid(zorder=0) + plt.axvline(np.mean(distance_values), color='k', linestyle='dashed', linewidth=1, zorder=4) + if bins_width is not None: + plt.hist(distance_values, edgecolor ="black", bins=np.arange(min(distance_values), max(distance_values) + bins_width, bins_width), zorder=3) + else: + plt.hist(distance_values, edgecolor ="black", zorder=3) + plt.title(title) + plt.xlabel("Cosine Distance between Task Pairs") + plt.ylabel("Frequency") + + plt.tight_layout() + if save_file: + _ = plt.savefig("plots/" + save_file + ".png", bbox_inches='tight') + + if show_plot: + plt.show() + + +## LLM DIV +# plot multiple subplots in one figure +# distance_matrix passed in is a list of distance_matrix (np.arrays) +def plot_multi_histogram_of_distances(distance_matrix_lst, title_lst, main_title=None, show_plot=True, save_file=None, + xlabel="Cosine Distance between Task Pairs", grid=True, bins_width=None, + num_cols=2, figsize=(12,10)): + import seaborn as sns + from scipy.cluster.hierarchy import linkage + from scipy.spatial.distance import squareform + import pandas as pd + import matplotlib.pyplot as plt + import math + + if num_cols == 2: + num_rows = math.ceil(len(distance_matrix_lst)/2) + else: + num_rows = math.ceil(len(distance_matrix_lst)/num_cols) + + f, ax = plt.subplots(num_rows, num_cols, figsize=figsize) + i = 0 + for row_ind in range(num_rows): + for col_ind in range(num_cols): + if i >= len(distance_matrix_lst): + break + triu = np.triu(distance_matrix_lst[i]) + triu = triu[triu != 0.0] + distance_values = triu.flatten() + + if len(distance_matrix_lst) > 2: + if grid: + ax[row_ind, col_ind].grid(zorder=0) + if bins_width is not None: + ax[row_ind, col_ind].hist(distance_values, edgecolor ="black", zorder=3, bins=np.arange(min(distance_values), max(distance_values) + bins_width, bins_width)) + else: + ax[row_ind, col_ind].hist(distance_values, edgecolor ="black", zorder=3) + ax[row_ind, col_ind].set_xlabel(xlabel) + ax[row_ind, col_ind].set_ylabel("Frequency") + ax[row_ind, col_ind].axvline(np.mean(distance_values), color='k', linestyle='dashed', linewidth=1, zorder=4) + ax[row_ind, col_ind].set_title(title_lst[i]) + else: + if grid: + ax[col_ind].grid(zorder=0) + ax[col_ind].hist(distance_values, edgecolor ="black", zorder=3) + if bins_width is not None: + ax[col_ind].hist(distance_values, edgecolor ="black", zorder=3, bins=np.arange(min(distance_values), max(distance_values) + bins_width, bins_width)) + else: + ax[col_ind].hist(distance_values, edgecolor ="black", zorder=3) + ax[col_ind].set_xlabel(xlabel) + ax[col_ind].set_ylabel("Frequency") + ax[col_ind].set_title(title_lst[i]) + i += 1 + if len(distance_matrix_lst) % 2 == 1 and num_cols == 2: + f.delaxes(ax[num_rows-1,1]) + + if main_title: + f.suptitle(main_title) + f.subplots_adjust(top=1) + + plt.grid(True) + plt.tight_layout() + if save_file: + _ = plt.savefig("plots/" + save_file + ".png", bbox_inches='tight') + if show_plot: + plt.show() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/task2vec/utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/task2vec/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9849d71776731c3c86f55e9308c5fef1045bcf62 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/task2vec/utils.py @@ -0,0 +1,76 @@ +# Copyright 2017-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +# ANY KIND, either express or implied. See the License for the specific +# language governing permissions and limitations under the License. + +from collections import defaultdict +import torch +import numpy as np + + +class AverageMeter(object): + """Computes and stores the average and current value""" + + def __init__(self): + self.reset() + + def reset(self): + self.val = defaultdict(int) + self.avg = defaultdict(float) + self.sum = defaultdict(int) + self.count = defaultdict(int) + + def update(self, n=1, **val): + for k in val: + self.val[k] = val[k] + self.sum[k] += val[k] * n + self.count[k] += n + self.avg[k] = self.sum[k] / self.count[k] + + +def set_batchnorm_mode(model, train=True): + """Allows to set batch_norm layer mode to train or eval, independendtly on the mode of the model.""" + def _set_batchnorm_mode(module): + if isinstance(module, torch.nn.BatchNorm1d) or isinstance(module, torch.nn.BatchNorm2d): + if train: + module.train() + else: + module.eval() + + model.apply(_set_batchnorm_mode) + +### LLM DIV +def get_error(output, target, mode='autoregressive', ignore_index=None): + if mode == 'autoregressive': # output = logits here + assert ignore_index is not None + output = output[:,:-1,:] + logits_inds = torch.argmax(output, dim=-1) + target = target[:,1:] + if ignore_index is not None: + acc = torch.eq(logits_inds, target.unsqueeze(0))[:, target != ignore_index] + else: + acc = torch.eq(logits_inds, target.unsqueeze(0)) + acc = acc.float().mean() + return 1 - acc + else: + pred = output.argmax(dim=1) + correct = pred.eq(target).float().sum() + return float((1. - correct / output.size(0)) * 100.) + + +def adjust_learning_rate(optimizer, epoch, optimizer_cfg): + lr = optimizer_cfg.lr * (0.1 ** np.less(optimizer_cfg.schedule, epoch).sum()) + for param_group in optimizer.param_groups: + param_group['lr'] = lr + + +def get_device(model: torch.nn.Module): + return next(model.parameters()).device diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/task2vec_dataset_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/task2vec_dataset_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..5dbbe883eb6a77924ad88993b0fb5c2439e719c3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/task2vec_dataset_evaluator.py @@ -0,0 +1,109 @@ +from dataflow.operators.general_text.eval.task2vec.task2vec import Task2Vec +from dataflow.operators.general_text.eval.task2vec import task_similarity +import torch +import random +from transformers import GPT2Tokenizer, GPT2LMHeadModel +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from torch.utils.data import Dataset +from dataflow import get_logger +from typing import Optional +# Task2Vec dataset diversity evaluation +# Cited from: Beyond Scale: the Diversity Coefficient as a Data Quality Metric Demonstrates LLMs are Pre-trained on Formally Diverse Data +@OPERATOR_REGISTRY.register() +class Task2VecDatasetEvaluator(OperatorABC): + def __init__(self, device='cuda', sample_nums=10, sample_size=1, method: Optional[str]='montecarlo', model_cache_dir='./dataflow_cache'): + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + # evaluating diversity by extract sample_nums * sample_size samples + self.sample_nums = sample_nums + self.sample_size = sample_size + self.device = device + self.model_cache_dir = model_cache_dir + self.score_name = 'Task2VecScore' + self.method = method + if method not in ['montecarlo', 'variational']: + raise ValueError(f"Invalid method '{method}'. Valid options are 'montecarlo' and 'variational'.") + self.tokenizer = GPT2Tokenizer.from_pretrained('gpt2', cache_dir=self.model_cache_dir) + self.probe_network = GPT2LMHeadModel.from_pretrained('gpt2', cache_dir=self.model_cache_dir) + self.device = torch.device(self.device if self.device and torch.cuda.is_available() else "cpu") + self.probe_network = self.probe_network.to(self.device) + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "使用Task2Vec方法评估数据集的多样性,通过计算样本嵌入的余弦距离矩阵来量化多样性。\n" + "输入参数:\n" + "- device:计算设备,默认为'cuda'\n" + "- sample_nums:采样次数,默认为10\n" + "- sample_size:每次采样样本数,默认为1\n" + "- method:嵌入方法,可选'montecarlo'或'variational',默认为'montecarlo'\n" + "- model_cache_dir:模型缓存目录,默认为'./dataflow_cache'\n" + "- input_key:输入文本字段名\n" + "输出参数:\n" + "- Task2VecDiversityScore:多样性得分\n" + "- ConfidenceInterval:置信区间" + ) + elif lang == "en": + return ( + "Evaluate dataset diversity using Task2Vec by calculating cosine distance matrix of sample embeddings.\n" + "Input Parameters:\n" + "- device: Computing device, default 'cuda'\n" + "- sample_nums: Number of sampling iterations, default 10\n" + "- sample_size: Number of samples per iteration, default 1\n" + "- method: Embedding method, 'montecarlo' or 'variational', default 'montecarlo'\n" + "- model_cache_dir: Model cache directory, default './dataflow_cache'\n" + "- input_key: Field name for input text\n" + "Output Parameters:\n" + "- Task2VecDiversityScore: Diversity score\n" + "- ConfidenceInterval: Confidence interval" + ) + else: + return "Evaluate dataset diversity using Task2Vec method." + + def preprocess(self, texts): + self.tokenizer.pad_token = self.tokenizer.eos_token + tokenized_outputs = self.tokenizer(texts, padding=True, truncation=True, return_tensors="pt") + return {key: value.to(self.device) for key, value in tokenized_outputs.items()} + + def get_score(self, sentences): + embeddings = [] + data_length = len(sentences) + for sample_num in range(self.sample_nums): + self.logger.info(f'--> Sample {sample_num + 1}/{self.sample_nums}') + indices = random.sample(range(data_length), self.sample_size) + texts = [sentences[i] for i in indices] + tokenized_batch = self.preprocess(texts) + tokenized_dataset = CustomTensorDataset(tokenized_batch) + embedding, _ = Task2Vec(self.probe_network, method=self.method).embed(tokenized_dataset) + embeddings.append(embedding) + distance_matrix = task_similarity.pdist(embeddings, distance='cosine') + div_coeff, conf_interval = task_similarity.stats_of_distance_matrix(distance_matrix) + + return { + "Task2VecDiversityScore": div_coeff, + "ConfidenceInterval": conf_interval + } + + def run(self, storage: DataFlowStorage, input_key: str): + dataframe = storage.read("dataframe") + samples = dataframe[input_key].to_list() + self.logger.info(f"Evaluating {self.score_name}...") + task2vec_score = self.get_score(samples) + self.logger.info("Evaluation complete!") + self.logger.info(f"Task2Vec Diversity Score: {task2vec_score}") + return task2vec_score + + +class CustomTensorDataset(Dataset): + def __init__(self, tokenized_batch): + self.tokenized_batch = tokenized_batch + + def __getitem__(self, index): + return {key: self.tokenized_batch[key][index] for key in self.tokenized_batch} + + def __len__(self): + return len(next(iter(self.tokenized_batch.values()))) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/vendi_dataset_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/vendi_dataset_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..c0d18ad511fd2c0357d388ddc45228d52b1de3e6 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/eval/vendi_dataset_evaluator.py @@ -0,0 +1,61 @@ +from vendi_score import text_utils +from dataflow.utils.storage import DataFlowStorage +import pandas as pd +from dataflow.core import OperatorABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger + +# VendiScore dataset diversity evaluation +# Cited from: The Vendi Score: A Diversity Evaluation Metric for Machine Learning +@OPERATOR_REGISTRY.register() +class VendiDatasetEvaluator(OperatorABC): + def __init__(self, device='cuda'): + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.bert_model_path = 'bert-base-uncased' + self.simcse_model_path = 'princeton-nlp/unsup-simcse-bert-base-uncased' + self.device = device + self.score_name = 'VendiScore' + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "通过计算VendiScore来评估数据集的多样性,使用BERT和SimCSE模型生成嵌入并计算分数。\n" + "输入参数:\n" + "- device:计算设备,默认为'cuda'\n" + "- input_key:输入文本字段名\n" + "输出参数:\n" + "- BERTVendiScore:基于BERT的多样性得分\n" + "- SimCSEVendiScore:基于SimCSE的多样性得分" + ) + elif lang == "en": + return ( + "Assess dataset diversity using VendiScore with embeddings from BERT and SimCSE models.\n" + "Input Parameters:\n" + "- device: Computing device, default 'cuda'\n" + "- input_key: Field name for input text\n" + "Output Parameters:\n" + "- BERTVendiScore: Diversity score based on BERT\n" + "- SimCSEVendiScore: Diversity score based on SimCSE" + ) + else: + return "Assess dataset diversity using VendiScore." + + def get_score(self, sentences): + result = {} + bert_vs = text_utils.embedding_vendi_score(sentences, model_path=self.bert_model_path, device=self.device) + result["BERTVendiScore"] = round(bert_vs, 2) + simcse_vs = text_utils.embedding_vendi_score(sentences, model_path=self.simcse_model_path, device=self.device) + result["SimCSEVendiScore"] = round(simcse_vs, 2) + return result + + def run(self, storage: DataFlowStorage, input_key: str): + dataframe = storage.read("dataframe") + samples = dataframe[input_key].to_list() + self.logger.info(f"Evaluating {self.score_name}...") + vendiscore = self.get_score(samples) + self.logger.info("Evaluation complete!") + self.logger.info(f"VendiScore: {vendiscore}") + return vendiscore \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..12beb15978911c1ad945755e66d45c2fe89995ae --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__init__.py @@ -0,0 +1,60 @@ +# import sys +# from dataflow.utils.registry import LazyLoader + +# cur_path = "dataflow/operators/filter/" + +# _import_structure = { +# # Primary filters +# "NgramFilter": (cur_path + "ngram_filter.py", "NgramFilter"), +# "LanguageFilter": (cur_path + "language_filter.py", "LanguageFilter"), +# "DeitaQualityFilter": (cur_path + "deita_quality_filter.py", "DeitaQualityFilter"), +# "DeitaComplexityFilter": (cur_path + "deita_complexity_filter.py", "DeitaComplexityFilter"), +# "InstagFilter": (cur_path + "instag_filter.py", "InstagFilter"), +# "PairQualFilter": (cur_path + "pair_qual_filter.py", "PairQualFilter"), +# "QuratingFilter": (cur_path + "qurating_filter.py", "QuratingFilter"), +# "SuperfilteringFilter": (cur_path + "superfiltering_filter.py", "SuperfilteringFilter"), +# "FineWebEduFilter": (cur_path + "fineweb_edu_filter.py", "FineWebEduFilter"), +# "TextbookFilter": (cur_path + "text_book_filter.py", "TextbookFilter"), +# "AlpagasusFilter": (cur_path + "alpagasus_filter.py", "AlpagasusFilter"), +# "DebertaV3Filter": (cur_path + "debertav3_filter.py", "DebertaV3Filter"), +# "LangkitFilter": (cur_path + "langkit_filter.py", "LangkitFilter"), +# "LexicalDiversityFilter": (cur_path + "lexical_diversity_filter.py", "LexicalDiversityFilter"), +# "PerplexityFilter": (cur_path + "perplexity_filter.py", "PerplexityFilter"), +# "PerspectiveFilter": (cur_path + "perspective_filter.py", "PerspectiveFilter"), +# "PresidioFilter": (cur_path + "presidio_filter.py", "PresidioFilter"), +# "RMFilter": (cur_path + "reward_model_filter.py", "RMFilter"), +# "TreeinstructFilter": (cur_path + "treeinstruct_filter.py", "TreeinstructFilter"), + +# # Heuristic filters +# "ColonEndFilter": (cur_path + "heuristics.py", "ColonEndFilter"), +# "WordNumberFilter": (cur_path + "heuristics.py", "WordNumberFilter"), +# "BlocklistFilter": (cur_path + "heuristics.py", "BlocklistFilter"), +# "SentenceNumberFilter": (cur_path + "heuristics.py", "SentenceNumberFilter"), +# "LineEndWithEllipsisFilter": (cur_path + "heuristics.py", "LineEndWithEllipsisFilter"), +# "ContentNullFilter": (cur_path + "heuristics.py", "ContentNullFilter"), +# "MeanWordLengthFilter": (cur_path + "heuristics.py", "MeanWordLengthFilter"), +# "SymbolWordRatioFilter": (cur_path + "heuristics.py", "SymbolWordRatioFilter"), +# "HtmlEntityFilter": (cur_path + "heuristics.py", "HtmlEntityFilter"), +# "IDCardFilter": (cur_path + "heuristics.py", "IDCardFilter"), +# "NoPuncFilter": (cur_path + "heuristics.py", "NoPuncFilter"), +# "SpecialCharacterFilter": (cur_path + "heuristics.py", "SpecialCharacterFilter"), +# "WatermarkFilter": (cur_path + "heuristics.py", "WatermarkFilter"), +# "StopWordFilter": (cur_path + "heuristics.py", "StopWordFilter"), +# "CurlyBracketFilter": (cur_path + "heuristics.py", "CurlyBracketFilter"), +# "CapitalWordsFilter": (cur_path + "heuristics.py", "CapitalWordsFilter"), +# "LoremIpsumFilter": (cur_path + "heuristics.py", "LoremIpsumFilter"), +# "UniqueWordsFilter": (cur_path + "heuristics.py", "UniqueWordsFilter"), +# "CharNumberFilter": (cur_path + "heuristics.py", "CharNumberFilter"), +# "LineStartWithBulletpointFilter": (cur_path + "heuristics.py", "LineStartWithBulletpointFilter"), +# "LineWithJavascriptFilter": (cur_path + "heuristics.py", "LineWithJavascriptFilter"), + +# # Deduplicators +# "MinHashDeduplicator": (cur_path + "minhash_deduplicator.py", "MinHashDeduplicator"), +# "CCNetDeduplicator": (cur_path + "ccnet_deduplicator.py", "CCNetDeduplicator"), +# "HashDeduplicator": (cur_path + "hash_deduplicator.py", "HashDeduplicator"), +# "NgramHashDeduplicator": (cur_path + "ngramhash_deduplicator.py", "NgramHashDeduplicator"), +# "SemDeduplicator": (cur_path + "sem_deduplicator.py", "SemDeduplicator"), +# "SimHashDeduplicator": (cur_path + "simhash_deduplicator.py", "SimHashDeduplicator"), +# } + +# sys.modules[__name__] = LazyLoader(__name__, cur_path, _import_structure) \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d52bea41a65e00c8cac9deab47518649a316009 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/blocklist_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/blocklist_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06cfc7215771841ab3cacd6de573670a408f2f78 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/blocklist_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/hash_deduplicate_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/hash_deduplicate_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d549a04ff9e641c3b1f6524f70660bc21723838d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/hash_deduplicate_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/langkit_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/langkit_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7da9cf46aaa44aa2fe41f413220b54269bf8332f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/langkit_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/language_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/language_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..621d0713d5df3c71401a97d7bc6eb691121134d7 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/language_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/lexical_diversity_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/lexical_diversity_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a94020ab7eeffbc9f0e1083171c95219b5ea2f7 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/lexical_diversity_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/llm_language_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/llm_language_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6c4dbe3fb3695ffe3fcd54f3700d870d6694df9 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/llm_language_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/minhash_deduplicate_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/minhash_deduplicate_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01c24d26d25f310e6fe7dcdac2c8b0338b6df5e8 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/minhash_deduplicate_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/ngram_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/ngram_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e5988a4c9528eb0bd105f157424aab1352c307d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/ngram_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/ngramhash_deduplicate_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/ngramhash_deduplicate_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8687c16c039cdb47427ba7cd6a505cb6db30b4a1 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/ngramhash_deduplicate_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/perspective_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/perspective_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d476a9b540edd3f6096764f004fd72d59db35aa1 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/perspective_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/presidio_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/presidio_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b9af7e86d4619d593cd05f165243af3e260e020 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/presidio_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/rule_based_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/rule_based_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a8b5f7cdd08a1886ff594d53c5992a334653231 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/rule_based_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/sem_deduplicate_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/sem_deduplicate_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31709c0ebe03ea708f134d25de0a459e3579bc52 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/sem_deduplicate_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/simhash_deduplicate_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/simhash_deduplicate_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac40e2445cd457cfd066d7db58ae99c0b51d6ed3 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/simhash_deduplicate_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/word_number_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/word_number_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4ce32838938e31aacdde6ab385e07d52d774117 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/__pycache__/word_number_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/blocklist/en.txt b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/blocklist/en.txt new file mode 100644 index 0000000000000000000000000000000000000000..a438b9ca33af77341768bd6c63ce3e48e726b76e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/blocklist/en.txt @@ -0,0 +1,403 @@ +2g1c +2 girls 1 cup +acrotomophilia +alabama hot pocket +alaskan pipeline +anal +anilingus +anus +apeshit +arsehole +ass +asshole +assmunch +auto erotic +autoerotic +babeland +baby batter +baby juice +ball gag +ball gravy +ball kicking +ball licking +ball sack +ball sucking +bangbros +bangbus +bareback +barely legal +barenaked +bastard +bastardo +bastinado +bbw +bdsm +beaner +beaners +beaver cleaver +beaver lips +beastiality +bestiality +big black +big breasts +big knockers +big tits +bimbos +birdlock +bitch +bitches +black cock +blonde action +blonde on blonde action +blowjob +blow job +blow your load +blue waffle +blumpkin +bollocks +bondage +boner +boob +boobs +booty call +brown showers +brunette action +bukkake +bulldyke +bullet vibe +bullshit +bung hole +bunghole +busty +butt +buttcheeks +butthole +camel toe +camgirl +camslut +camwhore +carpet muncher +carpetmuncher +chocolate rosebuds +cialis +circlejerk +cleveland steamer +clit +clitoris +clover clamps +clusterfuck +cock +cocks +coprolagnia +coprophilia +cornhole +coon +coons +creampie +cum +cumming +cumshot +cumshots +cunnilingus +cunt +darkie +date rape +daterape +deep throat +deepthroat +dendrophilia +dick +dildo +dingleberry +dingleberries +dirty pillows +dirty sanchez +doggie style +doggiestyle +doggy style +doggystyle +dog style +dolcett +domination +dominatrix +dommes +donkey punch +double dong +double penetration +dp action +dry hump +dvda +eat my ass +ecchi +ejaculation +erotic +erotism +escort +eunuch +fag +faggot +fecal +felch +fellatio +feltch +female squirting +femdom +figging +fingerbang +fingering +fisting +foot fetish +footjob +frotting +fuck +fuck buttons +fuckin +fucking +fucktards +fudge packer +fudgepacker +futanari +gangbang +gang bang +gay sex +genitals +giant cock +girl on +girl on top +girls gone wild +goatcx +goatse +god damn +gokkun +golden shower +goodpoop +goo girl +goregasm +grope +group sex +g-spot +guro +hand job +handjob +hard core +hardcore +hentai +homoerotic +honkey +hooker +horny +hot carl +hot chick +how to kill +how to murder +huge fat +humping +incest +intercourse +jack off +jail bait +jailbait +jelly donut +jerk off +jigaboo +jiggaboo +jiggerboo +jizz +juggs +kike +kinbaku +kinkster +kinky +knobbing +leather restraint +leather straight jacket +lemon party +livesex +lolita +lovemaking +make me come +male squirting +masturbate +masturbating +masturbation +menage a trois +milf +missionary position +mong +motherfucker +mound of venus +mr hands +muff diver +muffdiving +nambla +nawashi +negro +neonazi +nigga +nigger +nig nog +nimphomania +nipple +nipples +nsfw +nsfw images +nude +nudity +nutten +nympho +nymphomania +octopussy +omorashi +one cup two girls +one guy one jar +orgasm +orgy +paedophile +paki +panties +panty +pedobear +pedophile +pegging +penis +phone sex +piece of shit +pikey +pissing +piss pig +pisspig +playboy +pleasure chest +pole smoker +ponyplay +poof +poon +poontang +punany +poop chute +poopchute +porn +porno +pornography +prince albert piercing +pthc +pubes +pussy +queaf +queef +quim +raghead +raging boner +rape +raping +rapist +rectum +reverse cowgirl +rimjob +rimming +rosy palm +rosy palm and her 5 sisters +rusty trombone +sadism +santorum +scat +schlong +scissoring +semen +sex +sexcam +sexo +sexy +sexual +sexually +sexuality +shaved beaver +shaved pussy +shemale +shibari +shit +shitblimp +shitty +shota +shrimping +skeet +slanteye +slut +s&m +smut +snatch +snowballing +sodomize +sodomy +spastic +spic +splooge +splooge moose +spooge +spread legs +spunk +strap on +strapon +strappado +strip club +style doggy +suck +sucks +suicide girls +sultry women +swastika +swinger +tainted love +taste my +tea bagging +threesome +throating +thumbzilla +tied up +tight white +tit +tits +titties +titty +tongue in a +topless +tosser +towelhead +tranny +tribadism +tub girl +tubgirl +tushy +twat +twink +twinkie +two girls one cup +undressing +upskirt +urethra play +urophilia +vagina +venus mound +viagra +vibrator +violet wand +vorarephilia +voyeur +voyeurweb +voyuer +vulva +wank +wetback +wet dream +white power +whore +worldsex +wrapping men +wrinkled starfish +xx +xxx +yaoi +yellow showers +yiffy +zoophilia +🖕 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/blocklist/zh.txt b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/blocklist/zh.txt new file mode 100644 index 0000000000000000000000000000000000000000..aa2a9da10354d6339159e8323bdd9f49732aab1b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/blocklist/zh.txt @@ -0,0 +1,319 @@ +13. +13点 +三级片 +下三烂 +下贱 +个老子的 +九游 +乳 +乳交 +乳头 +乳房 +乳波臀浪 +交配 +仆街 +他奶奶 +他奶奶的 +他奶娘的 +他妈 +他妈ㄉ王八蛋 +他妈地 +他妈的 +他娘 +他马的 +你个傻比 +你他马的 +你全家 +你奶奶的 +你她马的 +你妈 +你妈的 +你娘 +你娘卡好 +你娘咧 +你它妈的 +你它马的 +你是鸡 +你是鸭 +你马的 +做爱 +傻比 +傻逼 +册那 +军妓 +几八 +几叭 +几巴 +几芭 +刚度 +刚瘪三 +包皮 +十三点 +卖B +卖比 +卖淫 +卵 +卵子 +双峰微颤 +口交 +口肯 +叫床 +吃屎 +后庭 +吹箫 +塞你公 +塞你娘 +塞你母 +塞你爸 +塞你老师 +塞你老母 +处女 +外阴 +大卵子 +大卵泡 +大鸡巴 +奶 +奶奶的熊 +奶子 +奸 +奸你 +她妈地 +她妈的 +她马的 +妈B +妈个B +妈个比 +妈个老比 +妈妈的 +妈比 +妈的 +妈的B +妈逼 +妓 +妓女 +妓院 +妳她妈的 +妳妈的 +妳娘的 +妳老母的 +妳马的 +姘头 +姣西 +姦 +娘个比 +娘的 +婊子 +婊子养的 +嫖娼 +嫖客 +它妈地 +它妈的 +密洞 +射你 +射精 +小乳头 +小卵子 +小卵泡 +小瘪三 +小肉粒 +小骚比 +小骚货 +小鸡巴 +小鸡鸡 +屁眼 +屁股 +屄 +屌 +巨乳 +干x娘 +干七八 +干你 +干你妈 +干你娘 +干你老母 +干你良 +干妳妈 +干妳娘 +干妳老母 +干妳马 +干您娘 +干机掰 +干死CS +干死GM +干死你 +干死客服 +幹 +强奸 +强奸你 +性 +性交 +性器 +性无能 +性爱 +情色 +想上你 +懆您妈 +懆您娘 +懒8 +懒八 +懒叫 +懒教 +成人 +我操你祖宗十八代 +扒光 +打炮 +打飞机 +抽插 +招妓 +插你 +插死你 +撒尿 +操你 +操你全家 +操你奶奶 +操你妈 +操你娘 +操你祖宗 +操你老妈 +操你老母 +操妳 +操妳全家 +操妳妈 +操妳娘 +操妳祖宗 +操机掰 +操比 +操逼 +放荡 +日他娘 +日你 +日你妈 +日你老娘 +日你老母 +日批 +月经 +机八 +机巴 +机机歪歪 +杂种 +浪叫 +淫 +淫乱 +淫妇 +淫棍 +淫水 +淫秽 +淫荡 +淫西 +湿透的内裤 +激情 +灨你娘 +烂货 +烂逼 +爛 +狗屁 +狗日 +狗狼养的 +玉杵 +王八蛋 +瓜娃子 +瓜婆娘 +瓜批 +瘪三 +白烂 +白痴 +白癡 +祖宗 +私服 +笨蛋 +精子 +老二 +老味 +老母 +老瘪三 +老骚比 +老骚货 +肉壁 +肉棍子 +肉棒 +肉缝 +肏 +肛交 +肥西 +色情 +花柳 +荡妇 +賤 +贝肉 +贱B +贱人 +贱货 +贼你妈 +赛你老母 +赛妳阿母 +赣您娘 +轮奸 +迷药 +逼 +逼样 +野鸡 +阳具 +阳萎 +阴唇 +阴户 +阴核 +阴毛 +阴茎 +阴道 +阴部 +雞巴 +靠北 +靠母 +靠爸 +靠背 +靠腰 +驶你公 +驶你娘 +驶你母 +驶你爸 +驶你老师 +驶你老母 +骚比 +骚货 +骚逼 +鬼公 +鸡8 +鸡八 +鸡叭 +鸡吧 +鸡奸 +鸡巴 +鸡芭 +鸡鸡 +龟儿子 +龟头 +𨳒 +陰莖 +㞗 +尻 +𨳊 +鳩 +𡳞 +𨶙 +撚 +𨳍 +柒 +閪 +仆街 +咸家鏟 +冚家鏟 +咸家伶 +冚家拎 +笨實 +粉腸 +屎忽 +躝癱 +你老闆 +你老味 +你老母 +硬膠 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/blocklist_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/blocklist_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..a6557701f835d6d5f1278c41ce9f826ef47548c0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/blocklist_filter.py @@ -0,0 +1,97 @@ +from tqdm import tqdm +import numpy as np +import nltk +import os +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.cli_funcs.paths import DataFlowPath +from nltk.tokenize import word_tokenize + +@OPERATOR_REGISTRY.register() +class BlocklistFilter(OperatorABC): + + def __init__(self, language:str = 'en', threshold:int = 1, use_tokenizer:bool = False): + self.logger = get_logger() + self.language = language + self.threshold = threshold + self.use_tokenizer = use_tokenizer + self.logger.info(f"Initializing {self.__class__.__name__} with language = {self.language}, threshold = {self.threshold}, use_tokenizer = {self.use_tokenizer}...") + + # 设置 NLTK 数据路径(如果环境变量中有的话) + if 'NLTK_DATA' in os.environ: + nltk.data.path.insert(0, os.environ['NLTK_DATA']) + + # 尝试查找数据,如果不存在则下载 + try: + nltk.data.find('tokenizers/punkt') + except LookupError: + nltk.download('punkt') + + self.blocklist = self.load_blocklist() + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子使用特定语言的阻止列表进行文本过滤,支持可选的分词器进行单词级匹配。\n" + "输入参数:\n" + "- input_key:输入文本字段名,默认为'text'\n" + "- language:语言代码,默认为'zh'\n" + "- blocklist_dir:阻止列表文件目录,默认为'./blocklists/'\n" + "- threshold:匹配次数阈值,默认为1\n" + "- use_tokenizer:是否使用分词器,默认为True\n" + "- tokenizer:分词器对象,默认为None\n" + "输出参数:\n" + "- 过滤后的DataFrame,仅保留不包含阻止列表关键词的文本行\n" + "- 返回包含输入字段名的列表,用于后续算子引用" + ) + elif lang == "en": + return ( + "This operator filters text using language-specific blocklists with optional tokenizer integration for word-level filtering.\n" + "Input Parameters:\n" + "- input_key: Input text field name, default is 'text'\n" + "- language: Language code, default is 'zh'\n" + "- blocklist_dir: Blocklist file directory, default is './blocklists/'\n" + "- threshold: Matching count threshold, default is 1\n" + "- use_tokenizer: Whether to use tokenizer, default is True\n" + "- tokenizer: Tokenizer object, default is None\n" + "Output Parameters:\n" + "- Filtered DataFrame containing only rows without blocklist keywords\n" + "- List containing input field name for subsequent operator reference" + ) + else: + return "BlocklistFilter uses language-specific blocklists with optional tokenizer integration." + + def load_blocklist(self): + dataflow_dir = DataFlowPath.get_dataflow_dir() + file_path = f"{dataflow_dir}/operators/general_text/filter/blocklist/{self.language}.txt" + self.logger.info(f"Loading blocklist for language '{self.language}' from {file_path}...") + with open(file_path, 'r', encoding='utf-8') as file: + blocklist = set(line.strip().lower() for line in file if line.strip()) + self.logger.info(f"Blocklist for '{self.language}' loaded. Total words in blocklist: {len(blocklist)}.") + return blocklist + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str = 'blocklist_filter_label'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__}...") + valid_checks = [] + for text in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + if text: + if self.use_tokenizer: + text = word_tokenize(text.lower()) + else: + text = text.lower().split() + blocklist_count = sum(1 for word in text if word in self.blocklist) + valid_checks.append(blocklist_count <= self.threshold) + else: + valid_checks.append(0) + valid_checks = np.array(valid_checks, dtype=int) + dataframe[self.output_key] = valid_checks + filtered_dataframe = dataframe[valid_checks == 1] + storage.write(filtered_dataframe) + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + return [self.output_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/hash_deduplicate_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/hash_deduplicate_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..85354db9171fcc8795fbf75d6669a6cada353b5f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/hash_deduplicate_filter.py @@ -0,0 +1,97 @@ +from tqdm import tqdm +from hashlib import md5, sha256 +from xxhash import xxh3_128 +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY + +@OPERATOR_REGISTRY.register() +class HashDeduplicateFilter(OperatorABC): + def __init__(self, hash_func: str = 'md5'): + self.logger = get_logger() + self.hash_func = hash_func + self.hash_func_dict = { + 'md5': md5, + 'sha256': sha256, + 'xxh3': xxh3_128 + } + + if self.hash_func not in self.hash_func_dict: + raise ValueError(f'Invalid hash function: {self.hash_func}') + self.logger.info(f"Initializing {self.__class__.__name__} with hash_func = {self.hash_func}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "使用多种哈希函数对文本进行精确去重,支持md5、sha256或xxh3算法。通过计算文本的哈希值识别重复数据。\n\n" + "初始化参数:\n" + "- hash_func: 哈希函数名称,可选'md5'、'sha256'或'xxh3',默认为'md5'\n\n" + "运行参数:\n" + "- input_keys: 用于计算哈希的多个字段列表(与input_key二选一)\n" + "- input_key: 用于计算哈希的单个字段名(与input_keys二选一)\n" + "- output_key: 去重标记字段名,默认为'minhash_deduplicated_label'\n\n" + "输出说明:标记为1的数据表示首次出现,标记为0的数据表示重复数据\n" + "算法特点:\n" + "- md5: 128位哈希值,平衡速度和唯一性\n" + "- sha256: 256位哈希值,更高安全性,速度较慢\n" + "- xxh3: 128位哈希值,最快的哈希算法" + ) + else: + return ( + "Exact deduplication using multiple hash functions, chosen from md5, sha256 or xxh3. Identify duplicate data by calculating text hash values.\n\n" + "Initialization Parameters:\n" + "- hash_func: Hash function name, options are 'md5', 'sha256' or 'xxh3', default is 'md5'\n\n" + "Run Parameters:\n" + "- input_keys: List of multiple fields for hash calculation (alternative to input_key)\n" + "- input_key: Single field name for hash calculation (alternative to input_keys)\n" + "- output_key: Deduplication label field name, default is 'minhash_deduplicated_label'\n\n" + "Output Description: Data marked as 1 indicates first occurrence, 0 indicates duplicate\n" + "Algorithm Characteristics:\n" + "- md5: 128-bit hash, balances speed and uniqueness\n" + "- sha256: 256-bit hash, higher security, slower speed\n" + "- xxh3: 128-bit hash, fastest hashing algorithm" + ) + + + def _compute_hash(self, text: str) -> str: + return self.hash_func_dict[self.hash_func](text.encode('utf-8')).hexdigest() + + def run(self, storage: DataFlowStorage, input_keys: list = None, input_key: str = None, output_key: str = 'minhash_deduplicated_label'): + if input_keys is None and input_key is None: + self.logger.error(f"Need to specify either input_keys or input_key!") + raise ValueError(f"Need to specify either input_keys or input_key!") + if input_keys is not None and input_key is not None: + self.logger.error(f"{self.__class__.__name__} only need one input args!") + raise ValueError(f"{self.__class__.__name__} only need one input args!") + if input_keys is not None: + self.logger.info(f"Running {self.__class__.__name__} with input_keys = {input_keys} and output_key = {output_key}") + else: + self.logger.info(f"Running {self.__class__.__name__} with input_key = {input_key} and output_key = {output_key}") + self.input_key = input_key + self.input_keys = input_keys + self.output_key = output_key + seen_hashes = set() + dataframe = storage.read("dataframe") + labels = [0] * len(dataframe) + for idx, sample in tqdm(enumerate(dataframe.to_dict(orient='records')), desc=f"Implementing {self.__class__.__name__}", total=len(dataframe)): + if input_keys is not None and len(input_keys) > 1: + text = '\n'.join([f"{k}:\n{sample[k]}" for k in input_keys]) + else: + text = sample[self.input_key] + hash_value = self._compute_hash(text) + if hash_value not in seen_hashes: + labels[idx] = 1 + seen_hashes.add(hash_value) + dataframe[self.output_key] = labels + filtered_dataframe = dataframe[(dataframe[self.output_key] > 0)] + output_file = storage.write(filtered_dataframe) + self.logger.info(f"Deduplication completed. Total unique items: {sum(labels)}") + return [self.output_key,] + + + + + + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/langkit_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/langkit_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..22c0ec0c7a74059ce8edc56b87b34ffc221b660a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/langkit_filter.py @@ -0,0 +1,120 @@ +import pandas as pd +import numpy as np +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.operators.general_text import LangkitSampleEvaluator + +@OPERATOR_REGISTRY.register() +class LangkitFilter(OperatorABC): + def __init__(self, + min_scores = { + "flesch_reading_ease": 0, # max(−144.8, 55.19−18.03) + "automated_readability_index": 0, # max(0.9, 11.77−4.41) + "aggregate_reading_level": 0, # max(0.0, 11.23−3.70) + "syllable_count": 32.0, # max(32, 815.4−1516.6 → clip to 32) + "lexicon_count": 23.0, # max(23, 524.2−1029.8 → clip to 23) + "sentence_count": 1.0, # max(1, 29.0−60.1 → clip to 1) + "character_count": 118.0, # max(118, 2610.2−4856.0 → clip to 118) + "letter_count": 109.0, # max(109, 2513.5−4679.5 → clip to 109) + "polysyllable_count": 0.0, # max(0, 78.9−137.5 → clip to 0) + "monosyllable_count": 13.0, # max(13, 334.7−709.4 → clip to 13) + "difficult_words": 4.0, # max(4, 93.4−120.0 → clip to 4) + }, + max_scores = { + "flesch_reading_ease": 100, # min(106.4, 55.19+18.03) + "automated_readability_index": 100, # min(98.2, 11.77+4.41) + "aggregate_reading_level": 100, # min(77.0, 11.23+3.70) + "syllable_count": 2331.9, # min(43237, 815.4+1516.6) + "lexicon_count": 1554.0, # min(33033, 524.2+1029.8) + "sentence_count": 89.1, # min(2193, 29.0+60.1) + "character_count": 7466.3, # min(139807,2610.2+4856.0) + "letter_count": 7193.0, # min(134507,2513.5+4679.5) + "polysyllable_count": 216.4, # min(3261, 78.9+137.5) + "monosyllable_count": 1044.1, # min(25133,334.7+709.4) + "difficult_words": 213.4, # min(2366, 93.4+120.0) + }, + metrics_to_keep: list = [ + "flesch_reading_ease", + "automated_readability_index", + "aggregate_reading_level", + "syllable_count", + "lexicon_count", + "sentence_count", + "character_count", + "letter_count", + "polysyllable_count", + "monosyllable_count", + "difficult_words", + ]): + self.min_scores = min_scores + self.max_scores = max_scores + self.metric_name_map = { + 'flesch_reading_ease': 'LangkitFleschReadingEaseScore', + 'automated_readability_index': 'LangkitAutomatedReadabilityIndexScore', + 'aggregate_reading_level': 'LangkitAggregateReadingLevelScore', + 'syllable_count': 'LangkitSyllableCountScore', + 'lexicon_count': 'LangkitLexiconCountScore', + 'sentence_count': 'LangkitSentenceCountScore', + 'character_count': 'LangkitCharacterCountScore', + 'letter_count': 'LangkitLetterCountScore', + 'polysyllable_count': 'LangkitPolysyllableCountScore', + 'monosyllable_count': 'LangkitMonosyllableCountScore', + 'difficult_words': 'LangkitDifficultWordsScore' + } + if not self.min_scores.keys() == self.max_scores.keys(): + raise ValueError("min_scores and max_scores must have the same keys") + self.logger = get_logger() + self.scorer = LangkitSampleEvaluator() + self.logger.info(f"Initializing {self.__class__.__name__} with min_scores: {self.min_scores} and max_scores: {self.max_scores}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于LangkitScorer打分器的得分对数据进行过滤。使用Langkit工具包计算11种文本统计信息,帮助评估文本结构复杂性和可读性。\n" + "输入参数:\n" + "- min_scores:各指标的最小阈值字典,包含11个语言统计指标\n" + "- max_scores:各指标的最大阈值字典,包含11个语言统计指标\n" + "- metrics_to_keep:需要保留的评估指标列表\n" + "输出参数:\n" + "- 过滤后的DataFrame,仅保留所有指标都在指定范围内的文本\n" + "- 返回包含各指标标签字段名的列表" + ) + else: + return ( + "Filter data using scores from the LangkitScorer. Uses Langkit to extract 11 types of text statistics for evaluating text structure complexity and readability.\n" + "Input Parameters:\n" + "- min_scores: Dictionary of minimum thresholds for each metric, containing 11 language statistics\n" + "- max_scores: Dictionary of maximum thresholds for each metric, containing 11 language statistics\n" + "- metrics_to_keep: List of evaluation metrics to keep\n\n" + "Output Parameters:\n" + "- Filtered DataFrame containing only texts with all metrics within specified ranges\n" + "- List containing label field names for each metric" + ) + + def run(self, storage: DataFlowStorage, input_key: str, output_keys: list = ["flesch_reading_ease", "automated_readability_index", "aggregate_reading_level", "syllable_count", "lexicon_count", "sentence_count", "character_count", "letter_count", "polysyllable_count", "monosyllable_count", "difficult_words"]): + self.input_key = input_key + self.output_keys = output_keys + if not list(self.min_scores.keys()) == output_keys: + raise ValueError("min_scores and output_keys must have the same keys") + self.logger.info("Running {self.__class__.__name__}...") + dataframe = storage.read("dataframe") + scores = self.scorer.eval(dataframe, self.input_key) + results = np.ones(len(dataframe), dtype=int) + for _label in self.output_keys: + label = self.metric_name_map[_label] + min_score = self.min_scores[_label] + max_score = self.max_scores[_label] + dataframe[label] = pd.DataFrame(scores)[label] + metric_scores = np.array(dataframe[label]) + metric_filter = (min_score <= metric_scores) & (metric_scores <= max_score) + results = results & metric_filter.astype(int) + self.logger.debug(f"Filtered by {_label}, {np.sum(results)} data remained") + dataframe[f"{label}_label"] = metric_filter.astype(int) + filtered_dataframe = dataframe[results == 1] + output_file = storage.write(filtered_dataframe) + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + return [f"{label}_label" for label in self.output_keys] + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/language_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/language_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..af67d4b6a480816042564cbd8f162bf3bc7b60f7 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/language_filter.py @@ -0,0 +1,79 @@ +import fasttext +import numpy as np +from huggingface_hub import hf_hub_download +from dataflow.core import OperatorABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from tqdm import tqdm +from dataflow.utils.utils import get_logger +from dataflow.utils.storage import DataFlowStorage + +@OPERATOR_REGISTRY.register() +class LanguageFilter(OperatorABC): + + def __init__(self, allowed_languages: list, model_cache_dir: str = None): + self.logger = get_logger() + self.filter_name = 'LanguageFilter' + self.logger.info(f"Initializing {self.__class__.__name__} with allowed_languages = {allowed_languages} and model_cache_dir = {model_cache_dir}...") + + self.allowed_languages = allowed_languages + self.model_cache_dir = model_cache_dir + + # Download and load the FastText language model + try: + self.logger.info("Downloading model from Hugging Face Hub...") + model_path = hf_hub_download(repo_id="facebook/fasttext-language-identification", filename="model.bin", cache_dir=self.model_cache_dir) + self.model = fasttext.load_model(model_path) + self.logger.info("Model loaded successfully.") + except Exception as e: + self.logger.error(f"Error downloading or loading model: {e}") + raise + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "使用FastText语言识别模型过滤数据。下载并加载预训练的FastText语言识别模型,检查文本的语言是否在允许的语言列表中。\n" + "输入参数:\n" + "- allowed_languages:允许的语言标签列表\n" + "- model_cache_dir:模型缓存目录路径\n" + "输出参数:\n" + "- 过滤后的DataFrame,仅保留语言在允许列表中的文本\n" + "- 返回包含语言标签字段名的列表" + ) + else: + return ( + "Filter data using FastText language identification model. Downloads and loads pre-trained FastText language identification model to check if text language is in allowed list.\n" + "Input Parameters:\n" + "- allowed_languages: List of allowed language labels\n" + "- model_cache_dir: Model cache directory path\n\n" + "Output Parameters:\n" + "- Filtered DataFrame containing only texts with language in allowed list\n" + "- List containing language label field name" + ) + + def eval(self, dataframe, input_key): + self.logger.info(f"Start evaluating {self.filter_name}...") + + predictions = [] + + # Assuming the dataframe contains the text in `input_key` + for text in tqdm(dataframe[input_key], desc=f"Implementing {self.filter_name}"): + labels, scores = self.model.predict(text.replace('\n', ' '), k=5) + label_score_pairs = list(zip(labels, scores)) + label_score_pairs.sort(key=lambda x: x[1], reverse=True) # Sort by score + top_labels = [label for label, score in label_score_pairs] + predictions.append(any(label in self.allowed_languages for label in top_labels)) + + return np.array(predictions).astype(int) + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='language_label'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.filter_name} with input_key = {self.input_key} and output_key = {self.output_key}...") + predictions = self.eval(dataframe, self.input_key) + dataframe[self.output_key] = predictions + filtered_dataframe = dataframe[dataframe[self.output_key] == 1] + storage.write(filtered_dataframe) + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + return [self.output_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/lexical_diversity_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/lexical_diversity_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..faa87b6c3e5fa75ab11921a17e4cc9d0531592a0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/lexical_diversity_filter.py @@ -0,0 +1,72 @@ +import pandas as pd +import numpy as np +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.operators.general_text import LexicalDiversitySampleEvaluator + +@OPERATOR_REGISTRY.register() +class LexicalDiversityFilter(OperatorABC): + def __init__(self, min_scores: dict = {'mtld': 50, 'hdd': 0.8}, max_scores: dict = {'mtld': 99999, 'hdd': 1.0}): + + self.min_scores = min_scores + self.max_scores = max_scores + if not self.min_scores.keys() == self.max_scores.keys(): + raise ValueError("min_scores and max_scores must have the same keys") + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__} with min_scores: {self.min_scores} and max_scores: {self.max_scores}...") + self.metric_name_map = { + 'hdd': 'LexicalDiversityHD-DScore', + 'mtld': 'LexicalDiversityMTLDScore', + } + self.scorer = LexicalDiversitySampleEvaluator() + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于LexicalDiversityScorer打分器的得分对数据进行过滤。使用MTLD(移动平均类型-令牌比)和HDD(超几何分布多样性)两种方法计算词汇多样性,高分代表更丰富的词汇使用。\n" + "输入参数:\n" + "- min_scores:各指标的最小阈值字典,包含'mtld'和'hdd'\n" + "- max_scores:各指标的最大阈值字典,包含'mtld'和'hdd'\n" + "输出参数:\n" + "- 过滤后的DataFrame,仅保留词汇多样性在指定范围内的文本\n" + "- 返回包含各指标标签字段名的列表" + ) + else: + return ( + "Filter data using scores from the LexicalDiversityScorer. Measure lexical diversity using MTLD (Moving-Average Type-Token Ratio) and HDD (Hypergeometric Distribution Diversity) methods; higher scores indicate more diverse vocabulary usage.\n" + "Input Parameters:\n" + "- min_scores: Dictionary of minimum thresholds for each metric, containing 'mtld' and 'hdd'\n" + "- max_scores: Dictionary of maximum thresholds for each metric, containing 'mtld' and 'hdd'\n\n" + "Output Parameters:\n" + "- Filtered DataFrame containing only texts with lexical diversity within specified range\n" + "- List containing label field names for each metric" + ) + + def run(self, storage: DataFlowStorage, input_key: str, output_keys = ['mtld', 'hdd']): + self.input_key = input_key + self.output_keys = output_keys + if not list(self.min_scores.keys()) == output_keys: + raise ValueError("min_scores and output_keys must have the same keys") + self.logger.info(f"Running {self.__class__.__name__} with input_key: {self.input_key} and output_keys: {self.output_keys}...") + dataframe = storage.read("dataframe") + scores = self.scorer.eval(dataframe, self.input_key) + results = np.ones(len(dataframe), dtype=int) + for _label in self.output_keys: + min_score = self.min_scores[_label] + max_score = self.max_scores[_label] + label = self.metric_name_map[_label] + dataframe[label] = pd.DataFrame(scores)[label] + metric_scores = np.array(dataframe[label]) + metric_filter = (min_score <= metric_scores) & (metric_scores <= max_score) + nan_filter = np.isnan(metric_scores) + metric_filter = metric_filter | nan_filter + results = results & metric_filter.astype(int) + self.logger.debug(f"Filtered by {_label}, {np.sum(results)} data remained") + dataframe[f"{label}_label"] = metric_filter.astype(int) + filtered_dataframe = dataframe[results == 1] + output_file = storage.write(filtered_dataframe) + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + return [f"{label}_label" for label in self.output_keys] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/llm_language_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/llm_language_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..28a4cc81855451915d2c54e42e3b1bd24c4f4dbe --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/llm_language_filter.py @@ -0,0 +1,39 @@ +import numpy as np +from tqdm import tqdm +from dataflow.core import OperatorABC, LLMServingABC +from dataflow.prompts.general_text import LanguageFilterPrompt +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.logger import get_logger +from dataflow.utils.storage import DataFlowStorage + +@OPERATOR_REGISTRY.register() +class LLMLanguageFilter(OperatorABC): + """ + Operator for filtering text based on language using LLM. + Argument allowed_languages is a list of allowed languages, using the ISO 639-1 two-letter language code to specify the language (for example, 'en' for English, 'zh' for Chinese, etc.). + """ + def __init__(self, llm_serving: LLMServingABC = None, allowed_languages: list[str] = ['en']): + self.logger = get_logger() + self.prompt = LanguageFilterPrompt() + self.llm_serving = llm_serving + self.allowed_languages = allowed_languages + self.logger.info(f"Initializing {self.__class__.__name__}...") + + @staticmethod + def get_desc(lang: str = "zh"): + return "使用大语言模型识别语言并过滤数据" if lang == "zh" else "Using large language models to identify languages and filter data." + + def _reformat_prompt(self, dataframe): + formatted_prompts = [self.prompt.build_prompt(text=item) for item in tqdm(dataframe[self.input_key], desc="Reformatting Prompt...")] + return formatted_prompts + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str = 'language_label'): + self.input_key, self.output_key = input_key, output_key + dataframe = storage.read("dataframe") + formatted_prompts = self._reformat_prompt(dataframe) + llm_outputs = self.llm_serving.generate_from_input(formatted_prompts) + dataframe[self.output_key] = llm_outputs + filtered_dataframe = dataframe[dataframe[self.output_key].isin(self.allowed_languages)] + storage.write(filtered_dataframe) + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + return dataframe \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/minhash_deduplicate_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/minhash_deduplicate_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..db73df920f0ee8783f065963b173c1a250b892a3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/minhash_deduplicate_filter.py @@ -0,0 +1,95 @@ +from tqdm import tqdm +from datasketch import MinHash, MinHashLSH # use datasketch-1.6.5 +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY + +@OPERATOR_REGISTRY.register() +class MinHashDeduplicateFilter(OperatorABC): + def __init__(self, num_perm=128, threshold=0.9, use_n_gram=True, ngram=5): + self.logger = get_logger() + self.num_perm = num_perm + self.threshold = threshold + self.use_n_gram = use_n_gram + self.n_gram = ngram + self.logger.info(f"Initializing {self.__class__.__name__} with num_perm = {self.num_perm}, threshold = {self.threshold}, use_n_gram = {self.use_n_gram}, ngram = {self.n_gram}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "结合MinHash与LSH(局部敏感哈希)实现高效近似去重。将文本转换为MinHash签名,使用LSH快速查找相似文本,实现大规模数据集的近似去重。\n" + "输入参数:\n" + "- num_perm:生成MinHash签名的排列数\n" + "- threshold:相似度阈值,超过此阈值判定为相似文本\n" + "- use_n_gram:是否使用n-gram分词\n" + "- ngram:n-gram的n值\n" + "输出参数:\n" + "- 去重后的DataFrame,仅保留唯一文本\n" + "- 返回包含去重标签字段名的列表" + ) + else: + return ( + "Efficient near-duplicate detection using MinHash and LSH (Locality-Sensitive Hashing). Converts texts to MinHash signatures and uses LSH to quickly find similar texts, enabling near-deduplication for large-scale datasets.\n" + "Input Parameters:\n" + "- num_perm: Number of permutations for generating MinHash signatures\n" + "- threshold: Similarity threshold above which texts are considered duplicates\n" + "- use_n_gram: Whether to use n-gram tokenization\n" + "- ngram: n value for n-gram\n\n" + "Output Parameters:\n" + "- Deduplicated DataFrame containing only unique texts\n" + "- List containing deduplication label field name" + ) + + def create_minhash(self, data): + minhash = MinHash(num_perm=self.num_perm) + if self.use_n_gram: + for i in range(len(data) - self.n_gram + 1): + minhash.update(data[i:i + self.n_gram].encode('utf8')) + else: + for d in data: + minhash.update(d.encode('utf8')) + return minhash + + def run(self, storage: DataFlowStorage, input_keys: list = None, input_key: str = None, output_key: str = 'minhash_deduplicated_label'): + if input_keys is None and input_key is None: + self.logger.error(f"Need to specify either input_keys or input_key!") + raise ValueError(f"Need to specify either input_keys or input_key!") + if input_keys is not None and input_key is not None: + self.logger.error(f"{self.__class__.__name__} only need one input args!") + raise ValueError(f"{self.__class__.__name__} only need one input args!") + if input_keys is not None: + self.logger.info(f"Running {self.__class__.__name__} with input_keys = {input_keys} and output_key = {output_key}") + else: + self.logger.info(f"Running {self.__class__.__name__} with input_key = {input_key} and output_key = {output_key}") + lsh = MinHashLSH(threshold=self.threshold, num_perm=self.num_perm) + self.input_key = input_key + self.input_keys = input_keys + self.output_key = output_key + dataframe = storage.read("dataframe") + labels = [0] * len(dataframe) + with lsh.insertion_session() as session: + for idx, sample in tqdm(enumerate(dataframe.to_dict(orient='records')), desc=f"Implementing {self.__class__.__name__}", total=len(dataframe)): + if input_keys is not None and len(input_keys) > 1: + text = '\n'.join([f"{k}:\n{sample[k]}" for k in input_keys]) + else: + text = sample[self.input_key] + minhash = self.create_minhash(text) + result = lsh.query(minhash) + + if len(result) == 0: + labels[idx] = 1 + session.insert(idx, minhash) + self.logger.debug(f"Inserted item {idx} into LSH with minhash.") + dataframe[self.output_key] = labels + filtered_dataframe = dataframe[(dataframe[self.output_key] > 0)] + output_file = storage.write(filtered_dataframe) + self.logger.info(f"Deduplication completed. Total unique items: {sum(labels)}") + return [self.output_key,] + + + + + + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/ngram_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/ngram_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..1c25b83a049641d0f5ca9bfb923b7476cda183d9 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/ngram_filter.py @@ -0,0 +1,57 @@ +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.operators.general_text import NgramSampleEvaluator +from typing import Literal # 记得在文件顶部导入 + +@OPERATOR_REGISTRY.register() +class NgramFilter(OperatorABC): + + def __init__(self, min_score=0.8, max_score=1, ngrams=5, language: Literal['zh', 'en'] = 'en'): + if language not in ['zh', 'en']: + raise ValueError(f"Unsupported language: '{language}'. Supported options are: ['zh', 'en'].") + self.logger = get_logger() + self.min_score = min_score + self.max_score = max_score + self.scorer = NgramSampleEvaluator(ngrams, language) + self.logger.info(f"Initializing {self.__class__.__name__} with min_scores: {self.min_score} and max_scores: {self.max_score}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于NgramScorer打分器的得分对数据进行过滤。计算文本中n-gram的重复比例,得分越高表示重复比例越低,文本冗余度越小。\n" + "输入参数:\n" + "- min_score:最小n-gram得分阈值\n" + "- max_score:最大n-gram得分阈值\n" + "- ngrams:n-gram的n值\n" + "输出参数:\n" + "- 过滤后的DataFrame,仅保留n-gram得分在指定范围内的文本\n" + "- 返回包含n-gram得分字段名的列表" + ) + else: + return ( + "Filter data using scores from the NgramScorer. Evaluate text redundancy via n-gram repetition ratio; higher score means lower repetition and less text redundancy.\n" + "Input Parameters:\n" + "- min_score: Minimum n-gram score threshold\n" + "- max_score: Maximum n-gram score threshold\n" + "- ngrams: n value for n-gram\n\n" + "Output Parameters:\n" + "- Filtered DataFrame containing only texts with n-gram score within specified range\n" + "- List containing n-gram score field name" + ) + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='NgramScore'): + self.input_key = input_key + self.output_key = output_key + self.logger.info(f"Running {self.__class__.__name__} with input_key: {self.input_key} and output_key: {self.output_key}...") + dataframe = storage.read("dataframe") + scores = self.scorer.eval(dataframe, self.input_key) + dataframe[self.output_key] = scores + filtered_dataframe = dataframe[(dataframe[self.output_key] >= self.min_score) & (dataframe[self.output_key] <= self.max_score)] + output_file = storage.write(filtered_dataframe) + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + return [self.output_key] + + \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/ngramhash_deduplicate_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/ngramhash_deduplicate_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..44fa12cf0ddc2274ee651886baf04350bef03982 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/ngramhash_deduplicate_filter.py @@ -0,0 +1,91 @@ +from tqdm import tqdm +from hashlib import md5, sha256 +from xxhash import xxh3_128 +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY + +@OPERATOR_REGISTRY.register() +class NgramHashDeduplicateFilter(OperatorABC): + def __init__(self, n_gram: int = 3, hash_func: str = 'md5', diff_size : int = 1): + self.logger = get_logger() + self.n_gram = n_gram + self.hash_func = hash_func + self.diff_size = diff_size + self.hash_func_dict = { + 'md5': md5, + 'sha256': sha256, + 'xxh3': xxh3_128 + } + + if self.hash_func not in self.hash_func_dict: + raise ValueError(f'Invalid hash function: {self.hash_func}') + self.logger.info(f"Initializing {self.__class__.__name__} with n_gram = {self.n_gram}, hash_func = {self.hash_func}, diff_size = {self.diff_size}...") + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "结合n-gram技术与哈希算法识别相似文本,实现近似去重。将文本分割为多个n-gram片段,计算每个片段的哈希值,通过比较哈希集合的相似度来判断文本相似性。\n" + "输入参数:\n" + "- n_gram:将文本分割的片段数量\n" + "- hash_func:哈希函数类型,支持'md5'、'sha256'和'xxh3'\n" + "- diff_size:哈希集合差异阈值,小于此值判定为相似文本\n" + "输出参数:\n" + "- 去重后的DataFrame,仅保留唯一文本\n" + "- 返回包含去重标签字段名的列表" + ) + else: + return ( + "Detect similar text using n-gram technology and hashing algorithm for near deduplication. Splits text into multiple n-gram segments, computes hash values for each segment, and judges text similarity by comparing hash set similarity.\n" + "Input Parameters:\n" + "- n_gram: Number of segments to split text into\n" + "- hash_func: Hash function type, supporting 'md5', 'sha256', and 'xxh3'\n" + "- diff_size: Hash set difference threshold below which texts are considered similar\n\n" + "Output Parameters:\n" + "- Deduplicated DataFrame containing only unique texts\n" + "- List containing deduplication label field name" + ) + + def _compute_hash(self, text: str) -> str: + return self.hash_func_dict[self.hash_func](text.encode('utf-8')).hexdigest() + + def run(self, storage: DataFlowStorage, input_keys: list = None, input_key: str = None, output_key: str = 'minhash_deduplicated_label'): + if input_keys is None and input_key is None: + self.logger.error(f"Need to specify either input_keys or input_key!") + raise ValueError(f"Need to specify either input_keys or input_key!") + if input_keys is not None and input_key is not None: + self.logger.error(f"{self.__class__.__name__} only need one input args!") + raise ValueError(f"{self.__class__.__name__} only need one input args!") + if input_keys is not None: + self.logger.info(f"Running {self.__class__.__name__} with input_keys = {input_keys} and output_key = {output_key}") + else: + self.logger.info(f"Running {self.__class__.__name__} with input_key = {input_key} and output_key = {output_key}") + self.input_key = input_key + self.input_keys = input_keys + self.output_key = output_key + seen_hashes = [] + dataframe = storage.read("dataframe") + labels = [0] * len(dataframe) + for idx, sample in tqdm(enumerate(dataframe.to_dict(orient='records')), desc=f"Implementing {self.__class__.__name__}", total=len(dataframe)): + if input_keys is not None and len(input_keys) > 1: + text = '\n'.join([f"{k}:\n{sample[k]}" for k in input_keys]) + else: + text = sample[self.input_key] + gram_length = len(text) // self.n_gram + ngrams = [text[i*gram_length:(i+1)*gram_length] for i in range(self.n_gram)] + hash_value = set(self._compute_hash(ngram) for ngram in ngrams) + if all(len(hash_value & hash) < self.diff_size for hash in seen_hashes): + labels[idx] = 1 + seen_hashes.append(hash_value) + dataframe[self.output_key] = labels + filtered_dataframe = dataframe[(dataframe[self.output_key] > 0)] + output_file = storage.write(filtered_dataframe) + self.logger.info(f"Deduplication completed. Total unique items: {sum(labels)}") + return [self.output_key,] + + + + + + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/perspective_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/perspective_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..97f8d027c2077a778be7d677bee53e3870926346 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/perspective_filter.py @@ -0,0 +1,62 @@ +import numpy as np +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.operators.general_text import PerspectiveSampleEvaluator +from dataflow.serving import PerspectiveAPIServing + +@OPERATOR_REGISTRY.register() +class PerspectiveFilter(OperatorABC): + def __init__(self, min_score: float = 0.0, max_score: float = 0.5): + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__} with min_score = {min_score} and max_score = {max_score}") + self.min_score = min_score + self.max_score = max_score + self.serving = PerspectiveAPIServing(max_workers=10) + self.scorer = PerspectiveSampleEvaluator(serving=self.serving) + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于PerspectiveScorer打分器的得分对数据进行过滤使用Perspective API评估文本的毒性,返回毒性概率,得分越高表明文本毒性越高。\n" + "输入参数:\n" + "- min_score:最小毒性得分阈值\n" + "- max_score:最大毒性得分阈值\n" + "输出参数:\n" + "- 过滤后的DataFrame,仅保留毒性得分在指定范围内的文本\n" + "- 返回包含毒性得分字段名的列表" + ) + else: + return ( + "Filter data using scores from the PerspectiveScorer. Assess text toxicity using Perspective API; higher scores indicate more toxicity.\n" + "Input Parameters:\n" + "- min_score: Minimum toxicity score threshold\n" + "- max_score: Maximum toxicity score threshold\n\n" + "Output Parameters:\n" + "- Filtered DataFrame containing only texts with toxicity score within specified range\n" + "- List containing toxicity score field name" + ) + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str = 'PerspectiveScore'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key} and output_key = {self.output_key}...") + + # Get the scores for filtering + scores = np.array(self.scorer.eval(dataframe, self.input_key)) + + dataframe[self.output_key] = scores + metric_filter = (scores >= self.min_score) & (scores <= self.max_score) + nan_filter = np.isnan(scores) + metric_filter = metric_filter | nan_filter + filtered_dataframe = dataframe[metric_filter] + + # Write the filtered dataframe back to storage + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/presidio_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/presidio_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..1febf2907160423e6a7abc6495f27ddc700395d0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/presidio_filter.py @@ -0,0 +1,68 @@ +import numpy as np +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.operators.general_text import PresidioSampleEvaluator + +@OPERATOR_REGISTRY.register() +class PresidioFilter(OperatorABC): + + def __init__(self, min_score: int = 0, max_score: int = 5, lang='en', device='cuda', model_cache_dir='./dataflow_cache'): + self.logger = get_logger() + self.min_score = min_score + self.max_score = max_score + self.scorer = PresidioSampleEvaluator(lang=lang, device=device, model_cache_dir=model_cache_dir) + self.logger.info(f"Initializing {self.__class__.__name__} with min_score = {self.min_score} and max_score = {self.max_score}") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于PresidioScorer打分器的得分对数据进行过滤。使用Microsoft Presidio模型识别文本中的私人实体(PII),返回PII信息个数。\n" + "支持识别姓名、邮箱、电话号码、身份证号等多种敏感信息类型,可用于数据隐私保护和合规性检查。\n" + "输入参数:\n" + "- min_score:保留样本的最小PII数量阈值,默认为0\n" + "- max_score:保留样本的最大PII数量阈值,默认为5\n" + "- lang:文本语言,默认为'en'\n" + "- device:模型运行设备,默认为'cuda'\n" + "- model_cache_dir:模型缓存目录,默认为'./dataflow_cache'\n" + "输出参数:\n" + "- 过滤后的DataFrame,仅保留PII数量在[min_score, max_score]范围内的样本\n" + "- 返回包含输出字段名的列表,用于后续算子引用" + ) + elif lang == "en": + return ( + "Filter data using scores from the PresidioScorer. Detect personally identifiable information (PII) entities in text using Microsoft Presidio model and return the count of detected PII items.\n" + "Supports recognition of multiple sensitive information types including names, emails, phone numbers, and IDs for data privacy protection and compliance checks.\n" + "Input Parameters:\n" + "- min_score: Minimum PII count threshold for retaining samples, default is 0\n" + "- max_score: Maximum PII count threshold for retaining samples, default is 5\n" + "- lang: Text language, default is 'en'\n" + "- device: Model running device, default is 'cuda'\n" + "- model_cache_dir: Model cache directory, default is './dataflow_cache'\n" + "Output Parameters:\n" + "- Filtered DataFrame containing only samples with PII count within [min_score, max_score] range\n" + "- List containing output field name for subsequent operator reference" + ) + else: + return "Filter data based on PII detection results using Microsoft Presidio model." + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str = 'PresidioScore'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__}...") + + # Get the scores for filtering + scores = np.array(self.scorer.eval(dataframe, self.input_key)) + + dataframe[self.output_key] = scores + filtered_dataframe = dataframe[(scores >= self.min_score) & (scores <= self.max_score)] + + # Write the filtered dataframe back to storage + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/rule_based_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/rule_based_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..5edfcafe2e6bc9a10699a79f03f5baa1556852ee --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/rule_based_filter.py @@ -0,0 +1,1519 @@ +from dataflow.core import OperatorABC +from typing import Callable, Tuple +import numpy as np +from nltk.tokenize import word_tokenize, WordPunctTokenizer +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.utils import get_logger +from dataflow.utils.storage import DataFlowStorage +from tqdm import tqdm +import re + +@OPERATOR_REGISTRY.register() +class ColonEndFilter(OperatorABC): + + def __init__(self): + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于检查文本是否以冒号结尾,常用于判断问题是否为不完整的提问。\n" + "初始化参数:\n" + "- 无\n" + "运行参数:\n" + "- storage:DataFlowStorage对象\n" + "- input_key:输入文本字段名\n" + "- output_key:输出标签字段名,默认为'{类名小写}_label'\n" + "返回值:\n" + "- 包含output_key的列表" + ) + elif lang == "en": + return ( + "This operator checks if text ends with a colon, commonly used to identify incomplete questions.\n" + "Initialization Parameters:\n" + "- None\n" + "Run Parameters:\n" + "- storage: DataFlowStorage object\n" + "- input_key: Input text field name\n" + "- output_key: Output label field name, default is '{classname_lower}_label'\n" + "Returns:\n" + "- List containing output_key" + ) + else: + return "ColonEndFilter checks if text ends with a colon and filters out incomplete questions." + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str = None): + self.input_key = input_key + self.output_key = output_key or f"{self.__class__.__name__.lower()}_label" + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__}...") + colon_end_checks = [] + for text in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + if text: + colon_end_checks.append(not text.endswith(':')) + else: + colon_end_checks.append(0) + colon_end_checks = np.array(colon_end_checks, dtype=int) + dataframe[self.output_key] = colon_end_checks + filtered_dataframe = dataframe[colon_end_checks == 1] + storage.write(filtered_dataframe) + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + return [self.output_key] + +@OPERATOR_REGISTRY.register() +class SentenceNumberFilter(OperatorABC): + + def __init__(self, min_sentences: int=3, max_sentences: int=7500): + self.logger = get_logger() + self.min_sentences = min_sentences + self.max_sentences = max_sentences + self.logger.info(f"Initializing {self.__class__.__name__} with min_sentences = {self.min_sentences}, max_sentences = {self.max_sentences}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于检查文本中的句子数量是否在指定范围内,使用正则表达式匹配句子结束符号(。!?.!?)进行分割。\n" + "初始化参数:\n" + "- min_sentences:最小句子数量阈值,默认为3\n" + "- max_sentences:最大句子数量阈值,默认为7500\n" + "运行参数:\n" + "- storage:DataFlowStorage对象\n" + "- input_key:输入文本字段名\n" + "- output_key:输出标签字段名,默认为'sentence_number_filter_label'\n" + "返回值:\n" + "- 包含output_key的列表" + ) + elif lang == "en": + return ( + "This operator checks if the number of sentences in text is within specified range, using regex to match sentence-ending punctuation(。!?.!?).\n" + "Initialization Parameters:\n" + "- min_sentences: Minimum sentence count threshold, default is 3\n" + "- max_sentences: Maximum sentence count threshold, default is 7500\n" + "Run Parameters:\n" + "- storage: DataFlowStorage object\n" + "- input_key: Input text field name\n" + "- output_key: Output label field name, default is 'sentence_number_filter_label'\n" + "Returns:\n" + "- List containing output_key" + ) + else: + return "SentenceNumberFilter filters text based on sentence count range using regex pattern matching." + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str = 'sentence_number_filter_label'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key} and output_key = {self.output_key}...") + + valid_check = [] + SENT_PATTERN = re.compile(r'\b[^.!?\n]+[.!?]*', flags=re.UNICODE) + + for text in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + if text: + num_sentence = len(SENT_PATTERN.findall(text)) + valid_check.append(self.min_sentences <= num_sentence <= self.max_sentences) + else: + valid_check.append(0) + + valid_check = np.array(valid_check, dtype=int) + dataframe[self.output_key] = valid_check + filtered_dataframe = dataframe[valid_check == 1] + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] + + + +class TextSlice: + # A slice of text from a document. + def __init__(self, text: str, start: int, end: int): + self.text = text + self.start = start + self.end = end + +def split_paragraphs( + text: str, normalizer: Callable[[str], str], remove_empty: bool = True +) -> Tuple[TextSlice]: + """ + Split a string into paragraphs. A paragraph is defined as a sequence of zero or more characters, followed + by a newline character, or a sequence of one or more characters, followed by the end of the string. + """ + text_slices = tuple( + TextSlice(normalizer(text[match.start():match.end()]), match.start(), match.end()) + for match in re.finditer(r"([^\n]*\n|[^\n]+$)", text) + ) + + if remove_empty is True: + text_slices = tuple( + text_slice for text_slice in text_slices if text_slice.text.strip() + ) + + return text_slices + +def normalize( + text: str, + remove_punct: bool = True, + lowercase: bool = True, + nfd_unicode: bool = True, + white_space: bool = True +) -> str: + import string + import unicodedata + if remove_punct: + text = text.translate(str.maketrans('', '', string.punctuation)) + + # lowercase + if lowercase: + text = text.lower() + + if white_space: + text = text.strip() + text = re.sub(r'\s+', ' ', text) + + # NFD unicode normalization + if nfd_unicode: + text = unicodedata.normalize('NFD', text) + + return text + +@OPERATOR_REGISTRY.register() +class LineEndWithEllipsisFilter(OperatorABC): + + def __init__(self, threshold: float=0.3): + self.logger = get_logger() + self.threshold = threshold + self.logger.info(f"Initializing {self.__class__.__name__} with threshold = {self.threshold}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于检测并过滤以省略号(...)或(……)结尾的文本行,常用于识别不完整的表述。\n" + "初始化参数:\n" + "- threshold:以省略号结尾的行数比率阈值,默认为0.3\n" + "运行参数:\n" + "- storage:DataFlowStorage对象\n" + "- input_key:输入文本字段名\n" + "- output_key:输出标签字段名,默认为'line_end_with_ellipsis_filter_label'\n" + "返回值:\n" + "- 包含output_key的列表" + ) + elif lang == "en": + return ( + "This operator detects and filters text lines ending with ellipsis (...) or (……), commonly used to identify incomplete statements.\n" + "Initialization Parameters:\n" + "- threshold: Ratio threshold of lines ending with ellipsis, default is 0.3\n" + "Run Parameters:\n" + "- storage: DataFlowStorage object\n" + "- input_key: Input text field name\n" + "- output_key: Output label field name, default is 'line_end_with_ellipsis_filter_label'\n" + "Returns:\n" + "- List containing output_key" + ) + else: + return "LineEndWithEllipsisFilter detects and filters text ending with ellipsis characters." + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str = 'line_end_with_ellipsis_filter_label'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key} and output_key = {self.output_key}...") + + ellipsis_checks = [] + ellipsis = ["...", "…"] + + for text in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + if text: + raw_lines = split_paragraphs(text=text, normalizer=lambda x: x, remove_empty=True) + num_lines = len(raw_lines) + + if num_lines == 0: + ellipsis_checks.append(False) + continue + + num_occurrences = sum([line.text.rstrip().endswith(tuple(ellipsis)) for line in raw_lines]) + ratio = num_occurrences / num_lines + ellipsis_checks.append(ratio < self.threshold) + else: + ellipsis_checks.append(False) + + ellipsis_checks = np.array(ellipsis_checks, dtype=int) + dataframe[self.output_key] = ellipsis_checks + filtered_dataframe = dataframe[ellipsis_checks == 1] + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] + + +@OPERATOR_REGISTRY.register() +class ContentNullFilter(OperatorABC): + + def __init__(self): + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于过滤空值、空字符串或仅包含空白字符的文本,确保输入数据的有效性。\n" + "初始化参数:\n" + "- 无\n" + "运行参数:\n" + "- storage:DataFlowStorage对象\n" + "- input_key:输入文本字段名\n" + "- output_key:输出标签字段名,默认为'content_null_filter_label'\n" + "返回值:\n" + "- 包含output_key的列表" + ) + elif lang == "en": + return ( + "This operator filters null values, empty strings, or text containing only whitespace characters to ensure data validity.\n" + "Initialization Parameters:\n" + "- None\n" + "Run Parameters:\n" + "- storage: DataFlowStorage object\n" + "- input_key: Input text field name\n" + "- output_key: Output label field name, default is 'content_null_filter_label'\n" + "Returns:\n" + "- List containing output_key" + ) + else: + return "ContentNullFilter removes null, empty, and whitespace-only text content." + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='content_null_filter_label'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key} and output_key = {self.output_key}...") + + null_checks = [] + + for text in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + null_checks.append(text is not None and text.strip() != '') + + null_checks = np.array(null_checks, dtype=int) + + # Filter the dataframe based on the result + dataframe[self.output_key] = null_checks + filtered_dataframe = dataframe[null_checks == 1] + + # Write the filtered dataframe back to storage + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] + +@OPERATOR_REGISTRY.register() +class SymbolWordRatioFilter(OperatorABC): + + def __init__(self, threshold: float=0.4): + self.logger = get_logger() + self.threshold = threshold + self.symbol = ["#", "...", "…"] + self.logger.info(f"Initializing {self.__class__.__name__} with threshold = {self.threshold}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于检查文本中特定符号(#, ..., …)与单词数量的比率是否超过阈值,过滤符号使用过多的文本。\n" + "初始化参数:\n" + "- threshold:符号与单词比率阈值,默认为0.4\n" + "运行参数:\n" + "- storage:DataFlowStorage对象\n" + "- input_key:输入文本字段名\n" + "- output_key:输出标签字段名,默认为'symbol_word_ratio_filter_label'\n" + "返回值:\n" + "- 包含output_key的列表" + ) + elif lang == "en": + return ( + "This operator checks if the ratio of specific symbols(#, ..., …) to word count exceeds threshold, filtering text with excessive symbol usage.\n" + "Initialization Parameters:\n" + "- threshold: Symbol-to-word ratio threshold, default is 0.4\n" + "Run Parameters:\n" + "- storage: DataFlowStorage object\n" + "- input_key: Input text field name\n" + "- output_key: Output label field name, default is 'symbol_word_ratio_filter_label'\n" + "Returns:\n" + "- List containing output_key" + ) + else: + return "SymbolWordRatioFilter checks ratio of specified symbols to word count and filters excessive usage." + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='symbol_word_ratio_filter_label'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key} and output_key = {self.output_key}...") + + valid_checks = [] + + for text in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + if text: + raw_words = tuple(WordPunctTokenizer().tokenize(text)) + num_words = len(raw_words) + num_symbols = float(sum(text.count(symbol) for symbol in self.symbol)) + + if num_words == 0: + valid_checks.append(False) + continue + + ratio = num_symbols / num_words + valid_checks.append(ratio < self.threshold) + else: + valid_checks.append(False) + + valid_checks = np.array(valid_checks, dtype=int) + + # Filter the dataframe based on the result + dataframe[self.output_key] = valid_checks + filtered_dataframe = dataframe[valid_checks == 1] + + # Write the filtered dataframe back to storage + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] + +@OPERATOR_REGISTRY.register() +class AlphaWordsFilter(OperatorABC): + + def __init__(self, threshold: float, use_tokenizer: bool): + import nltk + import os + + # 设置 NLTK 数据路径(如果环境变量中有的话) + if 'NLTK_DATA' in os.environ: + nltk.data.path.insert(0, os.environ['NLTK_DATA']) + + # 尝试查找数据,如果不存在则下载 + try: + nltk.data.find('tokenizers/punkt_tab') + except LookupError: + nltk.download('punkt_tab') + + self.logger = get_logger() + self.threshold = threshold + self.use_tokenizer = use_tokenizer + self.logger.info(f"Initializing {self.__class__.__name__} with threshold = {self.threshold}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于验证文本中字母单词的比率是否达到阈值,支持NLTK分词或简单空格分割两种模式。\n" + "初始化参数:\n" + "- threshold:字母单词比率阈值(无默认值,必须提供)\n" + "- use_tokenizer:是否使用NLTK分词器(无默认值,必须提供)\n" + "运行参数:\n" + "- storage:DataFlowStorage对象\n" + "- input_key:输入文本字段名\n" + "- output_key:输出标签字段名,默认为'alpha_words_filter_label'\n" + "返回值:\n" + "- 包含output_key的列表" + ) + elif lang == "en": + return ( + "This operator verifies if the ratio of alphabetic words in text meets threshold, supporting NLTK tokenization or simple space splitting.\n" + "Initialization Parameters:\n" + "- threshold: Alphabetic word ratio threshold (no default, required)\n" + "- use_tokenizer: Whether to use NLTK tokenizer (no default, required)\n" + "Run Parameters:\n" + "- storage: DataFlowStorage object\n" + "- input_key: Input text field name\n" + "- output_key: Output label field name, default is 'alpha_words_filter_label'\n" + "Returns:\n" + "- List containing output_key" + ) + else: + return "AlphaWordsFilter verifies alphabetic word ratio using either NLTK tokenization or space splitting." + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='alpha_words_filter_label'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key} and output_key = {self.output_key}...") + + valid_checks = [] + + for text in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + if self.use_tokenizer: + words = word_tokenize(text) + else: + words = text.split() + alpha_count = sum(1 for word in words if re.search(r'[a-zA-Z]', word)) + word_count = len(words) + if word_count > 0: + ratio = alpha_count / word_count + valid_checks.append(ratio > self.threshold) + else: + valid_checks.append(False) + + valid_checks = np.array(valid_checks, dtype=int) + dataframe[self.output_key] = valid_checks + # Filter the dataframe based on the result + filtered_dataframe = dataframe[valid_checks == 1] + + # Write the filtered dataframe back to storage + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] + +@OPERATOR_REGISTRY.register() +class HtmlEntityFilter(OperatorABC): + + def __init__(self): + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于检测并过滤包含HTML实体(如&、<、>等)的文本,确保内容不包含标记语言元素。\n" + "初始化参数:\n" + "- 无\n" + "运行参数:\n" + "- storage:DataFlowStorage对象\n" + "- input_key:输入文本字段名\n" + "- output_key:输出标签字段名,默认为'html_entity_filter_label'\n" + "返回值:\n" + "- 包含output_key的列表" + ) + elif lang == "en": + return ( + "This operator detects and filters text containing HTML entities (e.g., &, <, >) to ensure content has no markup language elements.\n" + "Initialization Parameters:\n" + "- None\n" + "Run Parameters:\n" + "- storage: DataFlowStorage object\n" + "- input_key: Input text field name\n" + "- output_key: Output label field name, default is 'html_entity_filter_label'\n" + "Returns:\n" + "- List containing output_key" + ) + else: + return "HtmlEntityFilter detects and removes text containing HTML entity patterns." + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='html_entity_filter_label'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key} and output_key = {self.output_key}...") + + valid_checks = [] + + # Define the list of HTML entities + html_entity = ["nbsp", "lt", "gt", "amp", "quot", "apos", "hellip", "ndash", "mdash", "lsquo", "rsquo", "ldquo", "rdquo"] + full_entities_1 = [f"&{entity};" for entity in html_entity] + full_entities_2 = [f"&{entity};" for entity in html_entity] + full_entities_3 = [f"&{entity};" for entity in html_entity] + full_entities_4 = [f"&{entity};" for entity in html_entity] + half_entities = [f"&{entity}" for entity in html_entity] + [f"&{entity}" for entity in html_entity] + all_entities = full_entities_1 + full_entities_2 + full_entities_3 + full_entities_4 + half_entities + + for text in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + if text: + has_html_entity = any(entity in text for entity in all_entities) + valid_checks.append(not has_html_entity) + else: + valid_checks.append(False) + + valid_checks = np.array(valid_checks, dtype=int) + + # Filter the dataframe based on the result + dataframe[self.output_key] = valid_checks + filtered_dataframe = dataframe[valid_checks == 1] + + # Write the filtered dataframe back to storage + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] + +@OPERATOR_REGISTRY.register() +class IDCardFilter(OperatorABC): + + def __init__(self, threshold:int=3): + self.logger = get_logger() + self.threshold = threshold + self.logger.info(f"Initializing {self.__class__.__name__}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于检测并过滤包含身份证相关术语的文本,使用正则表达式匹配身份证号码模式以保护敏感信息。\n" + "初始化参数:\n" + "- threshold:身份证相关词汇匹配次数阈值,默认为3\n" + "运行参数:\n" + "- storage:DataFlowStorage对象\n" + "- input_key:输入文本字段名\n" + "- output_key:输出标签字段名,默认为'id_card_filter_label'\n" + "返回值:\n" + "- 包含output_key的列表" + ) + elif lang == "en": + return ( + "This operator detects and filters text containing ID card-related terms using regex patterns to protect sensitive information.\n" + "Initialization Parameters:\n" + "- threshold: ID card-related terms matching count threshold, default is 3\n" + "Run Parameters:\n" + "- storage: DataFlowStorage object\n" + "- input_key: Input text field name\n" + "- output_key: Output label field name, default is 'id_card_filter_label'\n" + "Returns:\n" + "- List containing output_key" + ) + else: + return "IDCardFilter detects and removes text containing ID card numbers and related sensitive information." + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='id_card_filter_label'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key} and output_key = {self.output_key}...") + + valid_checks = [] + pattern = re.compile(r"(身\s{0,10}份|id\s{0,10}number\s{0,10}|identification|identity|\s{0,10}ID\s{0,10}No\s{0,10}|id\s{0,10}card\s{0,10}|NRIC\s{0,10}number\s{0,10}|IC\s{0,10}number\s{0,10}|resident\s{0,10}registration\s{0,10}|I.D.\s{0,10}Number\s{0,10})", re.I) + + for text in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + if text: + matches = pattern.findall(text) + has_too_many_id_terms = len(matches) >= self.threshold + valid_checks.append(not has_too_many_id_terms) + else: + valid_checks.append(False) + + valid_checks = np.array(valid_checks, dtype=int) + + # Filter the dataframe based on the result + dataframe[self.output_key] = valid_checks + filtered_dataframe = dataframe[valid_checks == 1] + + # Write the filtered dataframe back to storage + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] + +@OPERATOR_REGISTRY.register() +class NoPuncFilter(OperatorABC): + + def __init__(self, threshold: int=112): + self.logger = get_logger() + self.threshold = threshold + self.logger.info(f"Initializing {self.__class__.__name__} with threshold = {self.threshold}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于确保文本包含足够的标点符号,通过统计句子间最大单词数量进行过滤。\n" + "初始化参数:\n" + "- threshold:句子间最大单词数量阈值,默认为112\n" + "运行参数:\n" + "- storage:DataFlowStorage对象\n" + "- input_key:输入文本字段名\n" + "- output_key:输出标签字段名,默认为'no_punc_filter_label'\n" + "返回值:\n" + "- 包含output_key的列表" + ) + elif lang == "en": + return ( + "This operator ensures text contains sufficient punctuation by counting maximum word count between sentences.\n" + "Initialization Parameters:\n" + "- threshold: Maximum word count between sentences threshold, default is 112\n" + "Run Parameters:\n" + "- storage: DataFlowStorage object\n" + "- input_key: Input text field name\n" + "- output_key: Output label field name, default is 'no_punc_filter_label'\n" + "Returns:\n" + "- List containing output_key" + ) + else: + return "NoPuncFilter ensures text contains sufficient punctuation marks based on ratio threshold." + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='no_punc_filter_label'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key} and output_key = {self.output_key}...") + + valid_checks = [] + + for text in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + if text: + paragraphs = text.split('\n') + max_word_count = 0 + for paragraph in paragraphs: + if len(paragraph.strip()) == 0: + continue + sentences = re.split("[–.!?,;•/|…]", paragraph) + for sentence in sentences: + words = sentence.split() + word_count = len(words) + if word_count > max_word_count: + max_word_count = word_count + + valid_checks.append(int(max_word_count) <= self.threshold) + else: + valid_checks.append(False) + + valid_checks = np.array(valid_checks, dtype=int) + + # Filter the dataframe based on the result + dataframe[self.output_key] = valid_checks + filtered_dataframe = dataframe[valid_checks == 1] + + # Write the filtered dataframe back to storage + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] + +@OPERATOR_REGISTRY.register() +class SpecialCharacterFilter(OperatorABC): + + def __init__(self): + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于移除包含特殊/unicode字符的文本,使用预定义模式检测非标准字符以确保文本规范性。\n" + "初始化参数:\n" + "- 无\n" + "运行参数:\n" + "- storage:DataFlowStorage对象\n" + "- input_key:输入文本字段名\n" + "- output_key:输出标签字段名,默认为'special_character_filter_label'\n" + "返回值:\n" + "- 包含output_key的列表" + ) + elif lang == "en": + return ( + "This operator removes text containing special/unicode characters using predefined patterns to ensure text normalization.\n" + "Initialization Parameters:\n" + "- None\n" + "Run Parameters:\n" + "- storage: DataFlowStorage object\n" + "- input_key: Input text field name\n" + "- output_key: Output label field name, default is 'special_character_filter_label'\n" + "Returns:\n" + "- List containing output_key" + ) + else: + return "SpecialCharacterFilter removes text containing special or non-standard unicode characters." + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='special_character_filter_label'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key} and output_key = {self.output_key}...") + + speclai_character = [ + r"u200e", + r"÷|\? :", + r"[�□]|\{\/U\}", + r"U\+26[0-F][0-D]|U\+273[3-4]|U\+1F[3-6][0-4][0-F]|U\+1F6[8-F][0-F]" + ] + + valid_checks = [] + for text in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + if text: + # Check for special characters using regular expressions + has_special_character = any(re.search(pattern, text) for pattern in speclai_character) + valid_checks.append(not has_special_character) + else: + valid_checks.append(False) + + valid_checks = np.array(valid_checks, dtype=int) + + # Filter the dataframe based on the result + dataframe[self.output_key] = valid_checks + filtered_dataframe = dataframe[valid_checks == 1] + + # Write the filtered dataframe back to storage + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] + +@OPERATOR_REGISTRY.register() +class WatermarkFilter(OperatorABC): + + def __init__(self, watermarks: list= ['Copyright', 'Watermark', 'Confidential']): + self.logger = get_logger() + self.watermarks = watermarks + self.logger.info(f"Initializing {self.__class__.__name__} with watermarks={self.watermarks}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于检测并移除包含版权/水印内容的文本,使用指定关键词列表识别受保护内容。\n" + "初始化参数:\n" + "- watermarks:水印关键词列表,默认为['Copyright', 'Watermark', 'Confidential']\n" + "运行参数:\n" + "- storage:DataFlowStorage对象\n" + "- input_key:输入文本字段名\n" + "- output_key:输出标签字段名,默认为'watermark_filter_label'\n" + "返回值:\n" + "- 包含output_key的列表" + ) + elif lang == "en": + return ( + "This operator detects and removes copyrighted/watermarked content using specified keyword lists to identify protected material.\n" + "Initialization Parameters:\n" + "- watermarks: List of watermark keywords, default is ['Copyright', 'Watermark', 'Confidential']\n" + "Run Parameters:\n" + "- storage: DataFlowStorage object\n" + "- input_key: Input text field name\n" + "- output_key: Output label field name, default is 'watermark_filter_label'\n" + "Returns:\n" + "- List containing output_key" + ) + else: + return "WatermarkFilter detects and removes text containing copyright or watermark keywords." + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='watermark_filter_label'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key} and output_key = {self.output_key}...") + + valid_checks = [] + + for text in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + if text: + matches = re.search('|'.join(self.watermarks), text) + valid_checks.append(matches is None) + else: + valid_checks.append(False) + + valid_checks = np.array(valid_checks, dtype=int) + + # Filter the dataframe based on the result + dataframe[self.output_key] = valid_checks + filtered_dataframe = dataframe[valid_checks == 1] + + # Write the filtered dataframe back to storage + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] + +@OPERATOR_REGISTRY.register() +class MeanWordLengthFilter(OperatorABC): + + def __init__(self, min_length: float=3, max_length: float=10): + self.logger = get_logger() + self.min_length = min_length + self.max_length = max_length + self.logger.info(f"Initializing {self.__class__.__name__} with min_length={self.min_length}, max_length={self.max_length}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于检查文本中单词的平均长度是否在指定范围内,通过字符总数除以单词数量计算平均值。\n" + "初始化参数:\n" + "- min_length:最小平均单词长度,默认为3\n" + "- max_length:最大平均单词长度,默认为10\n" + "运行参数:\n" + "- storage:DataFlowStorage对象\n" + "- input_key:输入文本字段名\n" + "- output_key:输出标签字段名,默认为'mean_word_length_filter_label'\n" + "返回值:\n" + "- 包含output_key的列表" + ) + elif lang == "en": + return ( + "This operator checks if the average word length in text is within specified range, calculated by total characters divided by word count.\n" + "Initialization Parameters:\n" + "- min_length: Minimum average word length, default is 3\n" + "- max_length: Maximum average word length, default is 10\n" + "Run Parameters:\n" + "- storage: DataFlowStorage object\n" + "- input_key: Input text field name\n" + "- output_key: Output label field name, default is 'mean_word_length_filter_label'\n" + "Returns:\n" + "- List containing output_key" + ) + else: + return "MeanWordLengthFilter checks average word length against specified range using character and word counts." + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='mean_word_length_filter_label'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key} and output_key = {self.output_key}...") + + valid_checks = [] + + for text in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + if text: + normalized_words = text.split() + num_words = len(normalized_words) + + if num_words == 0: + valid_checks.append(False) + continue + + num_chars = sum(len(word) for word in normalized_words) + mean_length = round(num_chars / num_words, 2) + + valid_checks.append(self.min_length <= mean_length < self.max_length) + else: + valid_checks.append(False) + + valid_checks = np.array(valid_checks, dtype=int) + + # Filter the dataframe based on the result + dataframe[self.output_key] = valid_checks + filtered_dataframe = dataframe[valid_checks == 1] + + # Write the filtered dataframe back to storage + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] + +@OPERATOR_REGISTRY.register() +class StopWordFilter(OperatorABC): + + def __init__(self, threshold: float, use_tokenizer: bool): + self.logger = get_logger() + self.threshold = threshold + self.use_tokenizer = use_tokenizer + self.logger.info(f"Initializing {self.__class__.__name__} with threshold = {self.threshold}, use_tokenizer = {self.use_tokenizer}...") + import nltk + import os + from nltk.corpus import stopwords + + # 设置 NLTK 数据路径(如果环境变量中有的话) + if 'NLTK_DATA' in os.environ: + nltk.data.path.insert(0, os.environ['NLTK_DATA']) + else: + nltk.data.path.append('./dataflow/operators/filter/GeneralText/nltkdata/') + + # 尝试查找数据,如果不存在则下载 + try: + nltk.data.find('corpora/stopwords') + except LookupError: + nltk.download('stopwords', download_dir='./dataflow/operators/filter/GeneralText/nltkdata/') + + # 加载停用词 + self.stw = set(stopwords.words('english')) + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于验证文本中停用词的比率是否高于阈值,使用NLTK分词器进行单词分割和停用词识别。\n" + "初始化参数:\n" + "- threshold:停用词比率阈值(无默认值,必须提供)\n" + "- use_tokenizer:是否使用NLTK分词器(无默认值,必须提供)\n" + "运行参数:\n" + "- storage:DataFlowStorage对象\n" + "- input_key:输入文本字段名\n" + "- output_key:输出标签字段名,默认为'stop_word_filter_label'\n" + "返回值:\n" + "- 包含output_key的列表" + ) + elif lang == "en": + return ( + "This operator verifies if the ratio of stop words in text is above threshold, using NLTK tokenizer for word splitting and stop word identification.\n" + "Initialization Parameters:\n" + "- threshold: Stop word ratio threshold (no default, required)\n" + "- use_tokenizer: Whether to use NLTK tokenizer (no default, required)\n" + "Run Parameters:\n" + "- storage: DataFlowStorage object\n" + "- input_key: Input text field name\n" + "- output_key: Output label field name, default is 'stop_word_filter_label'\n" + "Returns:\n" + "- List containing output_key" + ) + else: + return "StopWordFilter verifies stop word ratio using NLTK tokenization with configurable threshold." + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='stop_word_filter_label'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key} and output_key = {self.output_key}...") + + valid_checks = [] + + for text in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + if text: + if self.use_tokenizer: + words = word_tokenize(text.lower()) + else: + words = text.lower().split() + + num_words = len(words) + num_stop_words = sum(map(lambda w: w in self.stw, words)) + + ratio = num_stop_words / num_words if num_words > 0 else 0 + + valid_checks.append(ratio > self.threshold and num_stop_words > 2) + else: + valid_checks.append(False) + + valid_checks = np.array(valid_checks, dtype=int) + + # Filter the dataframe based on the result + dataframe[self.output_key] = valid_checks + filtered_dataframe = dataframe[valid_checks == 1] + + # Write the filtered dataframe back to storage + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] + +@OPERATOR_REGISTRY.register() +class CurlyBracketFilter(OperatorABC): + + def __init__(self, threshold: float=0.025): + self.logger = get_logger() + self.threshold = threshold + self.logger.info(f"Initializing {self.__class__.__name__} with threshold={self.threshold}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于检测文本中是否存在过多的花括号使用,通过花括号数量与文本长度的比率进行过滤。\n" + "初始化参数:\n" + "- threshold:花括号比率阈值,默认为0.025\n" + "运行参数:\n" + "- storage:DataFlowStorage对象\n" + "- input_key:输入文本字段名\n" + "- output_key:输出标签字段名,默认为'curly_bracket_filter_label'\n" + "返回值:\n" + "- 包含output_key的列表" + ) + elif lang == "en": + return ( + "This operator detects excessive curly bracket usage in text by comparing bracket count to text length ratio.\n" + "Initialization Parameters:\n" + "- threshold: Bracket ratio threshold, default is 0.025\n" + "Run Parameters:\n" + "- storage: DataFlowStorage object\n" + "- input_key: Input text field name\n" + "- output_key: Output label field name, default is 'curly_bracket_filter_label'\n" + "Returns:\n" + "- List containing output_key" + ) + else: + return "CurlyBracketFilter detects excessive curly bracket usage with ratio thresholding." + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='curly_bracket_filter_label'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key} and output_key = {self.output_key}...") + + valid_checks = [] + + for text in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + if text: + num = text.count('{') + text.count('}') + ratio = num / len(text) if len(text) != 0 else 0 + valid_checks.append(ratio < self.threshold) + else: + valid_checks.append(False) + + valid_checks = np.array(valid_checks, dtype=int) + + # Filter the dataframe based on the result + dataframe[self.output_key] = valid_checks + filtered_dataframe = dataframe[valid_checks == 1] + + # Write the filtered dataframe back to storage + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] + +@OPERATOR_REGISTRY.register() +class CapitalWordsFilter(OperatorABC): + + def __init__(self, threshold: float=0.2, use_tokenizer: bool=False): + self.logger = get_logger() + self.threshold = threshold + self.use_tokenizer = use_tokenizer + self.logger.info(f"Initializing {self.__class__.__name__} with threshold = {self.threshold}, use_tokenizer = {self.use_tokenizer}...") + + # 如果使用分词器,配置 NLTK 数据路径 + if self.use_tokenizer: + import nltk + import os + + # 设置 NLTK 数据路径(如果环境变量中有的话) + if 'NLTK_DATA' in os.environ: + nltk.data.path.insert(0, os.environ['NLTK_DATA']) + + # 尝试查找数据,如果不存在则下载 + try: + nltk.data.find('tokenizers/punkt') + except LookupError: + nltk.download('punkt') + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于检查文本中大写单词的比率是否超过阈值,支持可选的分词器进行单词识别。\n" + "初始化参数:\n" + "- threshold:大写单词比率阈值,默认为0.2\n" + "- use_tokenizer:是否使用NLTK分词器,默认为False\n" + "运行参数:\n" + "- storage:DataFlowStorage对象\n" + "- input_key:输入文本字段名\n" + "- output_key:输出标签字段名,默认为'capital_words_filter'\n" + "返回值:\n" + "- 包含output_key的列表" + ) + elif lang == "en": + return ( + "This operator checks if the ratio of capitalized words in text exceeds threshold, supporting optional tokenizer for word identification.\n" + "Initialization Parameters:\n" + "- threshold: Capitalized word ratio threshold, default is 0.2\n" + "- use_tokenizer: Whether to use NLTK tokenizer, default is False\n" + "Run Parameters:\n" + "- storage: DataFlowStorage object\n" + "- input_key: Input text field name\n" + "- output_key: Output label field name, default is 'capital_words_filter'\n" + "Returns:\n" + "- List containing output_key" + ) + else: + return "CapitalWordsFilter checks uppercase word ratio with optional tokenizer usage." + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='capital_words_filter'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key} and output_key = {self.output_key}...") + + valid_checks = [] + + for text in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + if text: + if self.use_tokenizer: + words = word_tokenize(text) + else: + words = text.split() + + num_words = len(words) + num_caps_words = sum(map(str.isupper, words)) + + ratio = num_caps_words / num_words if num_words > 0 else 0 + + valid_checks.append(ratio <= self.threshold) + else: + valid_checks.append(False) + + valid_checks = np.array(valid_checks, dtype=int) + + # Filter the dataframe based on the result + dataframe[self.output_key] = valid_checks + filtered_dataframe = dataframe[valid_checks == 1] + + # Write the filtered dataframe back to storage + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] + +@OPERATOR_REGISTRY.register() +class LoremIpsumFilter(OperatorABC): + + def __init__(self, threshold: float=3e-8): + self.logger = get_logger() + self.threshold = threshold + self.logger.info(f"Initializing {self.__class__.__name__} with threshold = {self.threshold}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于检测并过滤包含占位文本(如'lorem ipsum')的文本,使用正则表达式模式匹配并结合阈值过滤。\n" + "初始化参数:\n" + "- threshold:'lorem ipsum'出现次数与文本长度的比率阈值,默认为3e-8\n" + "运行参数:\n" + "- storage:DataFlowStorage对象\n" + "- input_key:输入文本字段名\n" + "- output_key:输出标签字段名,默认为'loremipsum_filter_label'\n" + "返回值:\n" + "- 包含output_key的列表" + ) + elif lang == "en": + return ( + "This operator detects and filters text containing placeholder text (e.g., 'lorem ipsum') using regex pattern matching with threshold filtering.\n" + "Initialization Parameters:\n" + "- threshold: Ratio threshold of 'lorem ipsum' occurrences to text length, default is 3e-8\n" + "Run Parameters:\n" + "- storage: DataFlowStorage object\n" + "- input_key: Input text field name\n" + "- output_key: Output label field name, default is 'loremipsum_filter_label'\n" + "Returns:\n" + "- List containing output_key" + ) + else: + return "LoremIpsumFilter detects and removes text containing placeholder text patterns." + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='loremipsum_filter_label'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key} and output_key = {self.output_key}...") + + valid_checks = [] + + SEARCH_REGEX = re.compile(r"lorem ipsum", re.IGNORECASE) + + for text in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + if text: + normalized_content = text.lower() + num_occurrences = len(SEARCH_REGEX.findall(normalized_content)) + + ratio = num_occurrences / len(normalized_content) if len(normalized_content) > 0 else 0 + valid_checks.append(ratio <= self.threshold) + else: + valid_checks.append(False) + + valid_checks = np.array(valid_checks, dtype=int) + + # Filter the dataframe based on the result + dataframe[self.output_key] = valid_checks + filtered_dataframe = dataframe[valid_checks == 1] + + # Write the filtered dataframe back to storage + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] + +@OPERATOR_REGISTRY.register() +class UniqueWordsFilter(OperatorABC): + + def __init__(self, threshold: float=0.1): + self.logger = get_logger() + self.threshold = threshold + self.logger.info(f"Initializing {self.__class__.__name__} with threshold = {self.threshold}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于检查文本中唯一单词的比率是否达到阈值,通过集合操作计算唯一单词数量与总单词数量的比率。\n" + "初始化参数:\n" + "- threshold:最小唯一单词比率阈值,默认为0.1\n" + "运行参数:\n" + "- storage:DataFlowStorage对象\n" + "- input_key:输入文本字段名\n" + "- output_key:输出标签字段名,默认为'unique_words_filter'\n" + "返回值:\n" + "- 包含output_key的列表" + ) + elif lang == "en": + return ( + "This operator checks if the ratio of unique words in text meets threshold, calculating ratio of unique word count to total word count using set operations.\n" + "Initialization Parameters:\n" + "- threshold: Minimum unique word ratio threshold, default is 0.1\n" + "Run Parameters:\n" + "- storage: DataFlowStorage object\n" + "- input_key: Input text field name\n" + "- output_key: Output label field name, default is 'unique_words_filter'\n" + "Returns:\n" + "- List containing output_key" + ) + else: + return "UniqueWordsFilter checks unique word ratio using set operations and threshold comparison." + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='unique_words_filter'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key} and output_key = {self.output_key}...") + + valid_checks = [] + + for text in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + if text: + normalized_text = text.lower() + normalized_words = tuple(normalized_text.split()) + num_normalized_words = len(normalized_words) + + if num_normalized_words == 0: + valid_checks.append(False) + continue + + num_unique_words = len(set(normalized_words)) + ratio = num_unique_words / num_normalized_words + valid_checks.append(ratio > self.threshold) + else: + valid_checks.append(False) + + valid_checks = np.array(valid_checks, dtype=int) + + # Filter the dataframe based on the result + dataframe[self.output_key] = valid_checks + filtered_dataframe = dataframe[valid_checks == 1] + + # Write the filtered dataframe back to storage + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] + +@OPERATOR_REGISTRY.register() +class CharNumberFilter(OperatorABC): + + def __init__(self, threshold: int=100): + self.logger = get_logger() + self.threshold = threshold + self.logger.info(f"Initializing {self.__class__.__name__} with threshold = {self.threshold}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于验证文本在去除空白字符后的字符数量是否达到最小阈值。\n" + "初始化参数:\n" + "- threshold:最小字符数量阈值,默认为100\n" + "运行参数:\n" + "- storage:DataFlowStorage对象\n" + "- input_key:输入文本字段名\n" + "- output_key:输出标签字段名,默认为'char_number_filter_label'\n" + "返回值:\n" + "- 包含output_key的列表" + ) + elif lang == "en": + return ( + "This operator verifies if the character count of text (after whitespace removal) meets minimum threshold.\n" + "Initialization Parameters:\n" + "- threshold: Minimum character count threshold, default is 100\n" + "Run Parameters:\n" + "- storage: DataFlowStorage object\n" + "- input_key: Input text field name\n" + "- output_key: Output label field name, default is 'char_number_filter_label'\n" + "Returns:\n" + "- List containing output_key" + ) + else: + return "CharNumberFilter verifies character count after whitespace removal against specified threshold." + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='char_number_filter_label'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key} and output_key = {self.output_key}...") + + valid_checks = [] + + for text in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + if text: + # Remove whitespace and count the number of characters + text = text.strip().replace(" ", "").replace("\n", "").replace("\t", "") + num_char = len(text) + + # Check if the number of characters meets the threshold + valid_checks.append(num_char >= self.threshold) + else: + valid_checks.append(False) + + valid_checks = np.array(valid_checks, dtype=int) + + # Filter the dataframe based on the result + dataframe[self.output_key] = valid_checks + filtered_dataframe = dataframe[valid_checks == 1] + + # Write the filtered dataframe back to storage + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] + +@OPERATOR_REGISTRY.register() +class LineStartWithBulletpointFilter(OperatorABC): + + def __init__(self, threshold: float=0.9): + self.logger = get_logger() + self.threshold = threshold + self.logger.info(f"Initializing {self.__class__.__name__} with threshold={self.threshold}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于检测并过滤以各种项目符号符号开头的文本行,使用Unicode字符匹配结合比率阈值进行过滤。\n" + "初始化参数:\n" + "- threshold:以项目符号开头的行数比率阈值,默认为0.9\n" + "运行参数:\n" + "- storage:DataFlowStorage对象\n" + "- input_key:输入文本字段名\n" + "- output_key:输出标签字段名,默认为'line_start_with_bullet_point_filter_label'\n" + "返回值:\n" + "- 包含output_key的列表" + ) + elif lang == "en": + return ( + "This operator detects and filters lines starting with various bullet point symbols using Unicode character matching with ratio thresholding.\n" + "Initialization Parameters:\n" + "- threshold: Ratio threshold of lines starting with bullet points, default is 0.9\n" + "Run Parameters:\n" + "- storage: DataFlowStorage object\n" + "- input_key: Input text field name\n" + "- output_key: Output label field name, default is 'line_start_with_bullet_point_filter_label'\n" + "Returns:\n" + "- List containing output_key" + ) + else: + return "LineStartWithBulletpointFilter detects various bullet point symbols using Unicode character matching." + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='line_start_with_bullet_point_filter_label'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__}...") + + valid_checks = [] + + key_list = [ + "\u2022", "\u2023", "\u25B6", "\u25C0", "\u25E6", "\u25A0", "\u25A1", "\u25AA", "\u25AB", "\u2013" + ] + + for text in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + if text: + raw_lines = split_paragraphs(text=text, normalizer=lambda x: x, remove_empty=True) + num_lines = len(raw_lines) + + if num_lines == 0: + valid_checks.append(False) + continue + + num_occurrences = sum([line.text.lstrip().startswith(tuple(key_list)) for line in raw_lines]) + ratio = num_occurrences / num_lines + valid_checks.append(ratio <= self.threshold) + else: + valid_checks.append(False) + + valid_checks = np.array(valid_checks, dtype=int) + + # Filter the dataframe based on the result + dataframe[self.output_key] = valid_checks + filtered_dataframe = dataframe[valid_checks == 1] + + # Write the filtered dataframe back to storage + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] + +@OPERATOR_REGISTRY.register() +class LineWithJavascriptFilter(OperatorABC): + + def __init__(self, threshold: int=3): + self.logger = get_logger() + self.threshold = threshold + self.logger.info(f"Initializing {self.__class__.__name__} with threshold={self.threshold}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于识别并过滤包含'javascript'引用的文本,通过关键词匹配和阈值判断进行内容过滤。\n" + "初始化参数:\n" + "- threshold:不包含'javascript'的最小行数阈值,默认为3\n" + "运行参数:\n" + "- storage:DataFlowStorage对象\n" + "- input_key:输入文本字段名\n" + "- output_key:输出标签字段名,默认为'line_with_javascript_filter_label'\n" + "返回值:\n" + "- 包含output_key的列表" + ) + elif lang == "en": + return ( + "This operator identifies and filters text containing 'javascript' references through keyword matching and threshold judgment.\n" + "Initialization Parameters:\n" + "- threshold: Minimum line count threshold without 'javascript', default is 3\n" + "Run Parameters:\n" + "- storage: DataFlowStorage object\n" + "- input_key: Input text field name\n" + "- output_key: Output label field name, default is 'line_with_javascript_filter_label'\n" + "Returns:\n" + "- List containing output_key" + ) + else: + return "LineWithJavascriptFilter identifies 'javascript' references in text with threshold-based filtering." + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='line_with_javascript_filter_label'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__}...") + + valid_checks = [] + + for text in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + if text: + normalized_lines = split_paragraphs(text=text, normalizer=normalize, remove_empty=True) + num_lines = len(normalized_lines) + + if num_lines == 0: + valid_checks.append(False) + continue + + num_occurrences = sum(['javascript' in line.text.lower() for line in normalized_lines]) + num_not_occur = num_lines - num_occurrences + + valid_checks.append(num_lines <= 3 or num_not_occur >= self.threshold) + else: + valid_checks.append(False) + + valid_checks = np.array(valid_checks, dtype=int) + + # Filter the dataframe based on the result + dataframe[self.output_key] = valid_checks + filtered_dataframe = dataframe[valid_checks == 1] + + # Write the filtered dataframe back to storage + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/sem_deduplicate_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/sem_deduplicate_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..737d63e2dc39ef6a704ab106e9b83a9561059c9a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/sem_deduplicate_filter.py @@ -0,0 +1,161 @@ +import torch +from tqdm import tqdm +from hashlib import md5, sha256 +from xxhash import xxh3_128 +from transformers import BertModel, BertTokenizer +from torch.nn.functional import normalize +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY + +def load_model(device, model_path): + """ + Load the pretrained BERT model and tokenizer. + + Args: + model_path (str): Path to the pretrained model. + + Returns: + model, tokenizer: The loaded BERT model and tokenizer. + """ + model = BertModel.from_pretrained(model_path) + tokenizer = BertTokenizer.from_pretrained(model_path) + model = model.to(device) + model = model.eval() + return model, tokenizer + + +def get_text_embedding(texts, tokenizer, model, device): + """ + Compute text embeddings using the provided BERT model. + + Args: + texts (list): List of texts to be embedded. + tokenizer: Tokenizer for the model. + model: The BERT model. + + Returns: + np.ndarray: Embeddings for the input texts. + """ + inputs = tokenizer(texts, return_tensors='pt', padding=True, truncation=True).to(device) + with torch.no_grad(): + outputs = model(**inputs) + return outputs.last_hidden_state.mean(dim=1).cpu().numpy() # Use mean pooling for sentence embeddings + + +def compute_cos_sim_matrix(embeddings): + """ + Compute the cosine similarity matrix for the given embeddings. + + Args: + embeddings (np.ndarray): Text embeddings. + + Returns: + np.ndarray: Cosine similarity matrix. + """ + embeddings = torch.tensor(embeddings) + embeddings = normalize(embeddings, dim=1) + return embeddings @ embeddings.T + + +@OPERATOR_REGISTRY.register() +class SemDeduplicateFilter(OperatorABC): + def __init__(self, eps: float = 0.05, model_name: str = 'sentence-transformers/all-MiniLM-L6-v2', model_cache_dir: str = './dataflow_cache', device: str = 'cuda'): + self.logger = get_logger() + self.eps = eps + self.device = device + self.model_name = model_name + self.model_cache_dir = model_cache_dir + self.model = BertModel.from_pretrained(self.model_name, cache_dir=model_cache_dir).to(self.device) + self.tokenizer = BertTokenizer.from_pretrained(self.model_name, cache_dir=model_cache_dir) + self.logger.info(f"Initializing {self.__class__.__name__} with eps = {self.eps}, model_name = {self.model_name}, model_cache_dir = {self.model_cache_dir}, device = {self.device}") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于BERT语义相似度识别语义重复文本,执行近似去重操作。通过计算文本嵌入向量间的余弦相似度,识别语义相似的文本并保留唯一样本。\n" + "支持多字段组合作为去重依据,可有效去除内容相似但表述不同的重复数据,提高数据集多样性。\n" + "输入参数:\n" + "- eps:相似度阈值,值越小表示允许的相似度越低,默认为0.05(即余弦相似度大于0.95视为重复)\n" + "- model_name:预训练模型名称,默认为'sentence-transformers/all-MiniLM-L6-v2'\n" + "- model_cache_dir:模型缓存目录,默认为'./dataflow_cache'\n" + "- device:模型运行设备,默认为'cuda'\n" + "- input_keys:多个输入字段名列表,与input_key二选一\n" + "- input_key:单个输入字段名,与input_keys二选一\n" + "- output_key:去重结果字段名,默认为'minhash_deduplicated_label'\n" + "输出参数:\n" + "- 过滤后的DataFrame,仅保留语义不重复的样本(标记为1的样本)\n" + "- 返回包含去重结果字段名的列表,用于后续算子引用" + ) + elif lang == "en": + return ( + "Identify semantically duplicate text using BERT embeddings for near deduplication. Calculate cosine similarity between text embedding vectors to detect semantically similar texts and retain unique samples.\n" + "Supports multiple field combinations as deduplication criteria, effectively removing duplicate data with similar content but different expressions to improve dataset diversity.\n" + "Input Parameters:\n" + "- eps: Similarity threshold, smaller values allow lower similarity, default is 0.05 (cosine similarity > 0.95 is considered duplicate)\n" + "- model_name: Pretrained model name, default is 'sentence-transformers/all-MiniLM-L6-v2'\n" + "- model_cache_dir: Model cache directory, default is './dataflow_cache'\n" + "- device: Model running device, default is 'cuda'\n" + "- input_keys: List of multiple input field names, alternative to input_key\n" + "- input_key: Single input field name, alternative to input_keys\n" + "- output_key: Deduplication result field name, default is 'minhash_deduplicated_label'\n" + "Output Parameters:\n" + "- Filtered DataFrame containing only semantically unique samples (samples marked as 1)\n" + "- List containing deduplication result field name for subsequent operator reference" + ) + else: + return "Near deduplication by identifying semantically similar content using BERT embeddings." + + def _compute_hash(self, text: str) -> str: + return self.hash_func_dict[self.hash_func](text.encode('utf-8')).hexdigest() + + def run(self, storage: DataFlowStorage, input_keys: list = None, input_key: str = None, output_key: str = 'minhash_deduplicated_label'): + if input_keys is None and input_key is None: + self.logger.error(f"Need to specify either input_keys or input_key!") + raise ValueError(f"Need to specify either input_keys or input_key!") + if input_keys is not None and input_key is not None: + self.logger.error(f"{self.__class__.__name__} only need one input args!") + raise ValueError(f"{self.__class__.__name__} only need one input args!") + if input_keys is not None: + self.logger.info(f"Running {self.__class__.__name__} with input_keys = {input_keys} and output_key = {output_key}") + else: + self.logger.info(f"Running {self.__class__.__name__} with input_key = {input_key} and output_key = {output_key}") + self.input_key = input_key + self.input_keys = input_keys + self.output_key = output_key + seen_hashes = set() + dataframe = storage.read("dataframe") + texts = [] + for idx, sample in tqdm(enumerate(dataframe.to_dict(orient='records')), desc=f"Implementing {self.__class__.__name__}", total=len(dataframe)): + if input_keys is not None and len(input_keys) > 1: + text = '\n'.join([f"{k}:\n{sample[k]}" for k in input_keys]) + else: + text = sample[self.input_key] + texts.append(text) + embeddings = get_text_embedding(texts, self.tokenizer, self.model, self.device) + embeddings = normalize(torch.tensor(embeddings), dim=1) + + # Compute cosine similarity matrix + cos_sim_matrix = compute_cos_sim_matrix(embeddings) + cos_sim_matrix.fill_diagonal_(0) # Set diagonal to 0 to avoid self-comparison + cos_sim_matrix = torch.triu(cos_sim_matrix, diagonal=1) + + # Find pairs with similarity greater than or equal to the threshold + similar_pairs = torch.where(cos_sim_matrix >= (1 - self.eps)) + + labels = [1] * len(dataframe) + for idx in similar_pairs[1].tolist(): + labels[idx] = 0 + dataframe[self.output_key] = labels + filtered_dataframe = dataframe[(dataframe[self.output_key] > 0)] + output_file = storage.write(filtered_dataframe) + self.logger.info(f"Deduplication completed. Total unique items: {sum(labels)}") + return [self.output_key,] + + + + + + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/simhash_deduplicate_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/simhash_deduplicate_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..955cf25213c0e80d583fbb7ed81d0f30e10f9ac4 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/simhash_deduplicate_filter.py @@ -0,0 +1,91 @@ +from tqdm import tqdm +from simhash import Simhash +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY + +def get_similarity(simhash, another_simhash): + max_hashbit = max(len(bin(simhash.value)), len(bin(another_simhash.value))) + distince = simhash.distance(another_simhash) + similar = 1 - distince / max_hashbit + return similar + +@OPERATOR_REGISTRY.register() +class SimHashDeduplicateFilter(OperatorABC): + def __init__(self, fingerprint_size: int = 64, bound: float = 0.1): + self.logger = get_logger() + self.fingerprint_size = fingerprint_size + self.bound = bound + self.logger.info(f"Initializing {self.__class__.__name__} with fingerprint_size = {self.fingerprint_size}, bound = {self.bound}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "使用SimHash算法通过汉明距离识别相似文本,执行近似去重操作。将文本转换为固定长度的指纹,通过计算指纹间的汉明距离判断文本相似度。\n" + "相比语义去重速度更快,适合大规模数据集的快速去重预处理,尤其适用于检测字符层面相似的文本。\n" + "输入参数:\n" + "- fingerprint_size:指纹长度,默认为64位\n" + "- bound:相似度阈值,值越小表示允许的相似度越低,默认为0.1(即相似度大于0.9视为重复)\n" + "- input_keys:多个输入字段名列表,与input_key二选一\n" + "- input_key:单个输入字段名,与input_keys二选一\n" + "- output_key:去重结果字段名,默认为'minhash_deduplicated_label'\n" + "输出参数:\n" + "- 过滤后的DataFrame,仅保留相似性低于阈值的唯一样本(标记为1的样本)\n" + "- 返回包含去重结果字段名的列表,用于后续算子引用" + ) + elif lang == "en": + return ( + "Detect similar text via SimHash algorithm and Hamming distance for near deduplication. Convert text to fixed-length fingerprints and determine text similarity by calculating Hamming distance between fingerprints.\n" + "Faster than semantic deduplication, suitable for fast deduplication preprocessing of large-scale datasets, especially for detecting character-level similar texts.\n" + "Input Parameters:\n" + "- fingerprint_size: Fingerprint length, default is 64 bits\n" + "- bound: Similarity threshold, smaller values allow lower similarity, default is 0.1 (similarity > 0.9 is considered duplicate)\n" + "- input_keys: List of multiple input field names, alternative to input_key\n" + "- input_key: Single input field name, alternative to input_keys\n" + "- output_key: Deduplication result field name, default is 'minhash_deduplicated_label'\n" + "Output Parameters:\n" + "- Filtered DataFrame containing only unique samples with similarity below threshold (samples marked as 1)\n" + "- List containing deduplication result field name for subsequent operator reference" + ) + else: + return "Near deduplication by detecting text similarity using SimHash algorithm and Hamming distance." + + def run(self, storage: DataFlowStorage, input_keys: list = None, input_key: str = None, output_key: str = 'minhash_deduplicated_label'): + if input_keys is None and input_key is None: + self.logger.error(f"Need to specify either input_keys or input_key!") + raise ValueError(f"Need to specify either input_keys or input_key!") + if input_keys is not None and input_key is not None: + self.logger.error(f"{self.__class__.__name__} only need one input args!") + raise ValueError(f"{self.__class__.__name__} only need one input args!") + if input_keys is not None: + self.logger.info(f"Running {self.__class__.__name__} with input_keys = {input_keys} and output_key = {output_key}") + else: + self.logger.info(f"Running {self.__class__.__name__} with input_key = {input_key} and output_key = {output_key}") + self.input_key = input_key + self.input_keys = input_keys + self.output_key = output_key + dataframe = storage.read("dataframe") + simhashes = [] + labels = [0] * len(dataframe) + for idx, sample in tqdm(enumerate(dataframe.to_dict(orient='records')), desc=f"Implementing {self.__class__.__name__}", total=len(dataframe)): + if input_keys is not None and len(input_keys) > 1: + text = '\n'.join([f"{k}:\n{sample[k]}" for k in input_keys]) + else: + text = sample[self.input_key] + simhash = Simhash(text, f=self.fingerprint_size) + if all(get_similarity(simhash, another_simhash) < 1 - self.bound for another_simhash in simhashes): + labels[idx] = 1 + simhashes.append(simhash) + dataframe[self.output_key] = labels + filtered_dataframe = dataframe[(dataframe[self.output_key] > 0)] + output_file = storage.write(filtered_dataframe) + self.logger.info(f"Deduplication completed. Total unique items: {sum(labels)}") + return [self.output_key,] + + + + + + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/word_number_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/word_number_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..ce4fd933893eff268dc9643e3e0bcf8e207d8b5a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/filter/word_number_filter.py @@ -0,0 +1,64 @@ +from tqdm import tqdm +import numpy as np +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY + +@OPERATOR_REGISTRY.register() +class WordNumberFilter(OperatorABC): + + def __init__(self, min_words: int=20, max_words: int=100000): + self.logger = get_logger() + self.min_words = min_words + self.max_words = max_words + self.logger.info(f"Initializing {self.__class__.__name__} with min_words = {self.min_words}, max_words = {self.max_words}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于过滤单词数量不在指定范围内的文本,通过空格分割计算单词数量。\n" + "输入参数:\n" + "- input_key:输入文本字段名,默认为'text'\n" + "- min_words:最小单词数量阈值,默认为5\n" + "- max_words:最大单词数量阈值,默认为100\n" + "输出参数:\n" + "- 过滤后的DataFrame,仅保留单词数量在指定范围内的文本行\n" + "- 返回包含输入字段名的列表,用于后续算子引用" + ) + elif lang == "en": + return ( + "This operator filters text with word count outside the specified range, using space splitting for word counting.\n" + "Input Parameters:\n" + "- input_key: Input text field name, default is 'text'\n" + "- min_words: Minimum word count threshold, default is 5\n" + "- max_words: Maximum word count threshold, default is 100\n" + "Output Parameters:\n" + "- Filtered DataFrame containing only rows with word count within specified range\n" + "- List containing input field name for subsequent operator reference" + ) + else: + return "WordNumberFilter filters text based on word count range using space splitting." + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='word_number_filter_label'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key} and output_key = {self.output_key}...") + word_counts = [] + for text in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + if text: + normalized_words = tuple(text.split()) + num_normalized_words = len(normalized_words) + word_counts.append(num_normalized_words) + else: + word_counts.append(0) + word_counts = np.array(word_counts) + metric_filter = (self.min_words <= word_counts) & (word_counts < self.max_words) + dataframe[self.output_key] = word_counts + filtered_dataframe = dataframe[metric_filter] + storage.write(filtered_dataframe) + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + return [self.output_key] + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/html_entity_refiner.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/html_entity_refiner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55c0aa2c60d24b6cb0715220f42ef657b9c0cad3 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/html_entity_refiner.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/html_url_remover_refiner.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/html_url_remover_refiner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a9dea4e4da916bb02b26d3ef7ff34099baa0a12 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/html_url_remover_refiner.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/lowercase_refiner.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/lowercase_refiner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35149af1ec697ea618b740aef007e77239297435 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/lowercase_refiner.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/ner_refiner.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/ner_refiner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01c2b420107a7e23e24ecaed119bff6db947b2cc Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/ner_refiner.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/pii_anonymize_refiner.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/pii_anonymize_refiner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97a790acbac58f5f0449fc58ca7c6b5d6188b030 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/pii_anonymize_refiner.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/ref_removal_refiner.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/ref_removal_refiner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ae00385c60fb1c0e68419f1824467da5b8ff552 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/ref_removal_refiner.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/remove_contractions_refiner.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/remove_contractions_refiner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e19241ffcaabbc867729d5d835912224f8df8738 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/remove_contractions_refiner.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/remove_emoji_refiner.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/remove_emoji_refiner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87c96a57872c25edffd082c26874838bdafdb0a1 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/remove_emoji_refiner.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/remove_extra_spaces_refiner.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/remove_extra_spaces_refiner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d328b8dbcf10680283fbe477664294f51e1bee0 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/remove_extra_spaces_refiner.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/remove_image_ref_refiner.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/remove_image_ref_refiner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de19cb89bc229c6eafe4b16de9e4032e4189e914 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/remove_image_ref_refiner.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/remove_number_refiner.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/remove_number_refiner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10ccea569f2c88936a86976bc5539b7b4ce29bc3 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/remove_number_refiner.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/remove_punctuation_refiner.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/remove_punctuation_refiner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c96fb6625e5bf09659e2977a0a67b64f956073c Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/remove_punctuation_refiner.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/remove_repetitions_punctuation_refiner.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/remove_repetitions_punctuation_refiner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5efab1439104309f79df9090ca5b7adb9545462 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/remove_repetitions_punctuation_refiner.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/remove_stopwords_refiner.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/remove_stopwords_refiner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea70b1d40191cc9fa2016c0f99f787200ecd7695 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/remove_stopwords_refiner.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/spelling_correction_refiner.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/spelling_correction_refiner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf8ad7c26f266a663227552790aa3de4e87d96f8 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/spelling_correction_refiner.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/stemming_lemmatization_refiner.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/stemming_lemmatization_refiner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2c882e76974cc20e7ececa5317133db66e038dc Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/stemming_lemmatization_refiner.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/text_normalization_refiner.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/text_normalization_refiner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99579e65c0dd539b3727fcf511d24d31f0451e56 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/__pycache__/text_normalization_refiner.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/html_entity_refiner.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/html_entity_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..dc65d6c45f3c04b085dc8e450e5943a6a5f57d90 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/html_entity_refiner.py @@ -0,0 +1,94 @@ +import re +from tqdm import tqdm +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY + +@OPERATOR_REGISTRY.register() +class HtmlEntityRefiner(OperatorABC): + def __init__(self, html_entities: list = [ + "nbsp", "lt", "gt", "amp", "quot", "apos", "hellip", "ndash", "mdash", + "lsquo", "rsquo", "ldquo", "rdquo" + ]): + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__} ...") + # 从参数中获取自定义 HTML 实体列表,如果未提供则使用默认列表 + self.html_entities = html_entities + + # 构建正则表达式模式,匹配所有定义的 HTML 实体 + # 包括以下几种形式: + # 1. &实体名; + # 2. &实体名; (全角 &) + # 3. &实体名; (中文分号) + # 4. &实体名; (全角 & + 中文分号) + entity_patterns = [] + for entity in self.html_entities: + # &实体名; + entity_patterns.append(fr'&{entity};') + # &实体名; (全角 &) + entity_patterns.append(fr'&{entity};') + # &实体名; (中文分号) + entity_patterns.append(fr'&{entity};') + # &实体名; (全角 & + 中文分号) + entity_patterns.append(fr'&{entity};') + + # 编译正则表达式 + self.html_entity_regex = re.compile('|'.join(entity_patterns)) + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "去除文本中的HTML实体,包括标准实体(如 、<)和各种变体形式(全角符号、中文分号等)。支持自定义需要移除的HTML实体列表。" + "输入参数:\n" + "- html_entities:需要移除的HTML实体列表,默认为包含常见实体的列表\n" + "- input_key:输入文本字段名\n" + "输出参数:\n" + "- 包含移除HTML实体后文本的DataFrame\n" + "- 返回输入字段名,用于后续算子引用" + ) + elif lang == "en": + return ( + "Remove HTML entities from text, including standard entities (e.g.,  , <) and various variants (full-width symbols, Chinese semicolons, etc.). \n" + "Supports custom list of HTML entities to be removed.\n" + "Input Parameters:\n" + "- html_entities: List of HTML entities to remove, default contains common entities\n" + "- input_key: Field name for input text\n\n" + "Output Parameters:\n" + "- DataFrame containing text with HTML entities removed\n" + "- Returns input field name for subsequent operator reference" + ) + else: + return ( + "HtmlEntityRefiner removes HTML entities and their variants from text." + ) + + def run(self, storage: DataFlowStorage, input_key: str): + self.input_key = input_key + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key}...") + dataframe = storage.read("dataframe") + numbers = 0 + refined_data = [] + for item in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + modified = False + original_text = item + refined_text = original_text + + # 使用正则表达式替换所有匹配的HTML实体为空字符串 + refined_text = self.html_entity_regex.sub('', refined_text) + + # 检查文本是否被修改 + if original_text != refined_text: + item = refined_text + modified = True + self.logger.debug(f"Modified text for key '{self.input_key}': Original: {original_text[:30]}... -> Refined: {refined_text[:30]}...") + + refined_data.append(item) + if modified: + numbers += 1 + self.logger.debug(f"Item modified, total modified so far: {numbers}") + self.logger.info(f"Refining Complete. Total modified items: {numbers}") + dataframe[self.input_key] = refined_data + output_file = storage.write(dataframe) + return [self.input_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/html_url_remover_refiner.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/html_url_remover_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..cc463478a92fec91e7ccf0327115e771cb20c4c3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/html_url_remover_refiner.py @@ -0,0 +1,67 @@ +import re +from tqdm import tqdm +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY + +@OPERATOR_REGISTRY.register() +class HtmlUrlRemoverRefiner(OperatorABC): + def __init__(self): + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__} ...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "去除文本中的URL链接和HTML标签,净化文本内容。使用正则表达式匹配并移除各种形式的URL和HTML标签。" + "输入参数:\n" + "- input_key:输入文本字段名\n" + "输出参数:\n" + "- 包含净化后文本的DataFrame\n" + "- 返回输入字段名,用于后续算子引用" + ) + elif lang == "en": + return ( + "Remove URL links and HTML tags from text to clean content. Uses regular expressions to match and remove various forms of URLs and HTML tags.\n" + "Input Parameters:\n" + "- input_key: Field name for input text\n\n" + "Output Parameters:\n" + "- DataFrame containing cleaned text\n" + "- Returns input field name for subsequent operator reference" + ) + else: + return ( + "HtmlUrlRemoverRefiner cleans text by removing URLs and HTML tags." + ) + + def run(self, storage: DataFlowStorage, input_key: str): + self.input_key = input_key + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key}...") + dataframe = storage.read("dataframe") + numbers = 0 + refined_data = [] + for item in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + modified = False + original_text = item + refined_text = original_text + + # Remove URLs + refined_text = re.sub(r'https?:\/\/\S+[\r\n]*', '', refined_text, flags=re.MULTILINE) + # Remove HTML tags + refined_text = re.sub(r'<.*?>', '', refined_text) + + if original_text != refined_text: + item = refined_text + modified = True + self.logger.debug(f"Modified text for key '{self.input_key}': Original: {original_text[:30]}... -> Refined: {refined_text[:30]}...") + + refined_data.append(item) + if modified: + numbers += 1 + self.logger.debug(f"Item modified, total modified so far: {numbers}") + self.logger.info(f"Refining Complete. Total modified items: {numbers}") + dataframe[self.input_key] = refined_data + output_file = storage.write(dataframe) + return [self.input_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/lowercase_refiner.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/lowercase_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..6333f8bdcbb6c40c532171f765e9aca35f603089 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/lowercase_refiner.py @@ -0,0 +1,61 @@ +import re +from tqdm import tqdm +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY + +@OPERATOR_REGISTRY.register() +class LowercaseRefiner(OperatorABC): + def __init__(self): + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__} ...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "将文本字段中的所有大写字符转换为小写,统一文本格式。对指定字段的文本内容进行全小写处理。" + "输入参数:\n" + "- input_key:输入文本字段名\n" + "输出参数:\n" + "- 包含小写转换后文本的DataFrame\n" + "- 返回输入字段名,用于后续算子引用" + ) + elif lang == "en": + return ( + "Convert all uppercase characters in text fields to lowercase to unify text format. Applies full lowercase processing to text content of specified fields.\n" + "Input Parameters:\n" + "- input_key: Field name for input text\n\n" + "Output Parameters:\n" + "- DataFrame containing lowercase converted text\n" + "- Returns input field name for subsequent operator reference" + ) + else: + return ( + "LowercaseRefiner converts text fields to lowercase." + ) + + def run(self, storage: DataFlowStorage, input_key: str): + self.input_key = input_key + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key}...") + dataframe = storage.read("dataframe") + numbers = 0 + refined_data = [] + for item in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + modified = False + original_text = item + lower_text = original_text.lower() + if original_text != lower_text: + item = lower_text + modified = True + self.logger.debug(f"Modified text for key '{self.input_key}': Original: {original_text[:30]}... -> Refined: {lower_text[:30]}...") + + refined_data.append(item) + if modified: + numbers += 1 + self.logger.debug(f"Item modified, total modified so far: {numbers}") + self.logger.info(f"Refining Complete. Total modified items: {numbers}") + dataframe[self.input_key] = refined_data + output_file = storage.write(dataframe) + return [self.input_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/ner_refiner.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/ner_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..961cc2942c98b5caf4cdc2e5b5c83533217705ab --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/ner_refiner.py @@ -0,0 +1,105 @@ +import spacy +from tqdm import tqdm +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY + +ENTITY_LABELS = { + "PERSON": "[PERSON]", + "ORG": "[ORG]", + "GPE": "[GPE]", + "LOC": "[LOC]", + "PRODUCT": "[PRODUCT]", + "EVENT": "[EVENT]", + "DATE": "[DATE]", + "TIME": "[TIME]", + "MONEY": "[MONEY]", + "PERCENT": "[PERCENT]", + "QUANTITY": "[QUANTITY]", + "ORDINAL": "[ORDINAL]", + "CARDINAL": "[CARDINAL]", + "NORP": "[NORP]", + "FAC": "[FAC]", + "LAW": "[LAW]", + "LANGUAGE": "[LANGUAGE]", + "WORK_OF_ART": "[WORK_OF_ART]", + "LAW": "[LAW]", + "ORDINAL": "[ORDINAL]", + "CARDINAL": "[CARDINAL]", + "PERCENT": "[PERCENT]", + "QUANTITY": "[QUANTITY]", + "DATE": "[DATE]", + "TIME": "[TIME]", + "URL": "[URL]", + "EMAIL": "[EMAIL]", + "MONEY": "[MONEY]", + "FAC": "[FAC]", + "PRODUCT": "[PRODUCT]", + "EVENT": "[EVENT]", + "WORK_OF_ART": "[WORK_OF_ART]", + "LANGUAGE": "[LANGUAGE]", + "NORP": "[NORP]" +} + +@OPERATOR_REGISTRY.register() +class NERRefiner(OperatorABC): + def __init__(self): + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__} ...") + self.nlp = spacy.load("en_core_web_sm") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "使用命名实体识别(NER)技术识别并屏蔽文本中的特定实体。使用spaCy的'en_core_web_sm'模型识别实体,并将其替换为对应的实体类型标签。" + "输入参数:\n" + "- input_key:输入文本字段名\n" + "输出参数:\n" + "- 包含实体屏蔽后文本的DataFrame\n" + "- 返回输入字段名,用于后续算子引用" + ) + elif lang == "en": + return ( + "Mask specific entities in text using Named Entity Recognition (NER) technology. Uses spaCy's 'en_core_web_sm' model to identify entities \n" + "and replace them with corresponding entity type tags.\n" + "Input Parameters:\n" + "- input_key: Field name for input text\n\n" + "Output Parameters:\n" + "- DataFrame containing text with masked entities\n" + "- Returns input field name for subsequent operator reference" + ) + else: + return ( + "NERRefiner masks specific entities in text using Named Entity Recognition." + ) + + def run(self, storage: DataFlowStorage, input_key: str): + self.input_key = input_key + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key}...") + dataframe = storage.read("dataframe") + numbers = 0 + refined_data = [] + for item in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + modified = False + original_text = item + refined_text = original_text + + doc = self.nlp(refined_text) + for ent in doc.ents: + if ent.label_ in ENTITY_LABELS : + refined_text = refined_text.replace(ent.text, f"[{ent.label_}]") + + if original_text != refined_text: + item = refined_text + modified = True + + refined_data.append(item) + if modified: + numbers += 1 + self.logger.debug(f"Item modified, total modified so far: {numbers}") + self.logger.info(f"Refining Complete. Total modified items: {numbers}") + dataframe[self.input_key] = refined_data + output_file = storage.write(dataframe) + return [self.input_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/pii_anonymize_refiner.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/pii_anonymize_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..ef52e0c359880df8261270cfd75f9910c6428618 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/pii_anonymize_refiner.py @@ -0,0 +1,91 @@ +from tqdm import tqdm +from transformers import AutoModelForTokenClassification, AutoTokenizer +from presidio_analyzer.nlp_engine import TransformersNlpEngine +from presidio_analyzer import AnalyzerEngine +from presidio_anonymizer import AnonymizerEngine +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY + +@OPERATOR_REGISTRY.register() +class PIIAnonymizeRefiner(OperatorABC): + def __init__(self, lang='en', device='cuda', model_cache_dir='./dataflow_cache', model_name='dslim/bert-base-NER', ): + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__} ...") + self.lang = lang + self.device = device + self.model_cache_dir = model_cache_dir + self.model_name = model_name + model_name = 'dslim/bert-base-NER' + self.tokenizer = AutoTokenizer.from_pretrained(model_name, cache_dir=self.model_cache_dir) + self.model = AutoModelForTokenClassification.from_pretrained(model_name, cache_dir=self.model_cache_dir).to(self.device) + model_config = [{ + "lang_code": self.lang, + "model_name": { + "spacy": "en_core_web_sm", + "transformers": model_name + } + }] + + self.nlp_engine = TransformersNlpEngine(models=model_config) + self.analyzer = AnalyzerEngine(nlp_engine=self.nlp_engine) + self.anonymizer = AnonymizerEngine() + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "使用Presidio和BERT-NER模型识别并匿名化文本中的个人身份信息(PII)。支持多种PII类型的检测和匿名化处理。" + "输入参数:\n" + "- lang:语言代码,默认为'en'\n" + "- device:运行设备,默认为'cuda'\n" + "- model_cache_dir:模型缓存目录,默认为'./dataflow_cache'\n" + "- model_name:NER模型名称,默认为'dslim/bert-base-NER'\n" + "- input_key:输入文本字段名\n" + "输出参数:\n" + "- 包含匿名化后文本的DataFrame\n" + "- 返回输入字段名,用于后续算子引用" + ) + elif lang == "en": + return ( + "Identify and anonymize Personally Identifiable Information (PII) in text using Presidio and BERT-NER models. Supports detection and anonymization of various PII types.\n" + "Input Parameters:\n" + "- lang: Language code, default is 'en'\n" + "- device: Running device, default is 'cuda'\n" + "- model_cache_dir: Model cache directory, default is './dataflow_cache'\n" + "- model_name: NER model name, default is 'dslim/bert-base-NER'\n" + "- input_key: Field name for input text\n\n" + "Output Parameters:\n" + "- DataFrame containing anonymized text\n" + "- Returns input field name for subsequent operator reference" + ) + else: + return ( + "PIIAnonymizeRefiner identifies and anonymizes PII in text using NLP models." + ) + + def run(self, storage: DataFlowStorage, input_key: str): + self.input_key = input_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key}...") + anonymized_count = 0 + refined_data = [] + for item in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + modified = False + original_text = item + results = self.analyzer.analyze(original_text, language=self.lang) + anonymized_text = self.anonymizer.anonymize(original_text, results) + if original_text != anonymized_text.text: + item = anonymized_text.text + modified = True + self.logger.debug(f"Modified text for key '{self.input_key}': Original: {original_text[:30]}... -> Refined: {anonymized_text.text[:30]}...") + + refined_data.append(item) + if modified: + anonymized_count += 1 + self.logger.debug(f"Item modified, total modified so far: {anonymized_count}") + self.logger.info(f"Refining Complete. Total modified items: {anonymized_count}") + dataframe[self.input_key] = refined_data + output_file = storage.write(dataframe) + return [self.input_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/ref_removal_refiner.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/ref_removal_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..17518b99029b04153dbb0eb83d9b60588f658504 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/ref_removal_refiner.py @@ -0,0 +1,84 @@ +import re +from tqdm import tqdm +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY + +@OPERATOR_REGISTRY.register() +class ReferenceRemoverRefiner(OperatorABC): + def __init__(self): + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "删除文本中未闭合的引用标签和引用链接,包括标签和{{cite}}模板的各种完整和不完整形式。净化文本中的引用标记。" + "输入参数:\n" + "- input_key:输入文本字段名\n" + "输出参数:\n" + "- 包含移除引用标记后文本的DataFrame\n" + "- 返回输入字段名,用于后续算子引用" + ) + elif lang == "en": + return ( + "Remove unclosed reference tags and citation links from text, including various complete and incomplete forms of tags and {{cite}} templates. \n" + "Cleans reference markers from text.\n" + "Input Parameters:\n" + "- input_key: Field name for input text\n\n" + "Output Parameters:\n" + "- DataFrame containing text with reference markers removed\n" + "- Returns input field name for subsequent operator reference" + ) + else: + return ( + "ReferenceRemoverRefiner removes reference tags and citation links from text." + ) + + def run(self, storage: DataFlowStorage, input_key: str): + self.input_key = input_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key}...") + numbers = 0 + # 定义要删除的模式 - 更全面的版本 + # 1. 所有标签及其内容(包括各种不完整形式) + ref_pattern = re.compile( + r']*>.*?|' # 完整的ref标签 + r']*>[^<]*$|' # 不完整的ref标签(没有闭合) + r']*>.*?/br' # ref标签后跟/br(如你示例中的情况) + ) + + # 2. 所有{{cite}}模板及其内容(包括各种不完整形式) + cite_pattern = re.compile( + r'\{\{cite\s+\w+\|[^}]*\}\}|' # 完整的cite模板 + r'\{\{cite\s+\w+\|[^}]*$' # 不完整的cite模板(没有闭合) + ) + + refined_data = [] + for item in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + modified = False + original_text = item + refined_text = original_text + + # 删除所有未闭合的ref标签 + refined_text, ref_count = ref_pattern.subn('', refined_text) + + # 删除所有不完整的cite模板 + refined_text, cite_count = cite_pattern.subn('', refined_text) + + # 检查是否有任何修改 + if ref_count > 0 or cite_count > 0: + modified = True + numbers += 1 + self.logger.debug(f"Item modified, removed {ref_count} ref tags and {cite_count} cite templates") + + refined_data.append(item) + if modified: + numbers += 1 + self.logger.debug(f"Item modified, total modified so far: {numbers}") + self.logger.info(f"Refining Complete. Total modified items: {numbers}") + dataframe[self.input_key] = refined_data + output_file = storage.write(dataframe) + return [self.input_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_contractions_refiner.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_contractions_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..a8d741334cbdd6240d786491ebad1bcf01531241 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_contractions_refiner.py @@ -0,0 +1,65 @@ +import contractions +from tqdm import tqdm +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY + +@OPERATOR_REGISTRY.register() +class RemoveContractionsRefiner(OperatorABC): + def __init__(self): + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__} ...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于扩展文本中的英语缩写词,将缩写形式转换为完整形式(例如将\"can't\"扩展为\"cannot\")。\n" + "使用contractions库进行缩写词扩展,提高文本标准化程度。\n" + "输入参数:\n" + "- 无初始化参数\n" + "运行参数:\n" + "- input_key:输入文本字段名\n" + "输出参数:\n" + "- 处理后的DataFrame,包含扩展缩写词后的文本\n" + "- 返回包含输入字段名的列表,用于后续算子引用" + ) + elif lang == "en": + return ( + "This operator expands English contractions in text, converting abbreviated forms to full forms (e.g., \"can't\" → \"cannot\").\n" + "Uses the contractions library for abbreviation expansion to improve text standardization.\n" + "Input Parameters:\n" + "- No initialization parameters\n" + "Runtime Parameters:\n" + "- input_key: Input text field name\n" + "Output Parameters:\n" + "- Processed DataFrame containing text with expanded contractions\n" + "- List containing input field name for subsequent operator reference" + ) + else: + return "Expands English contractions in text to improve standardization." + + def run(self, storage: DataFlowStorage, input_key: str): + self.input_key = input_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key}...") + numbers = 0 + refined_data = [] + for item in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + modified = False + original_text = item + expanded_text = contractions.fix(original_text) + if original_text != expanded_text: + item = expanded_text + modified = True + self.logger.debug(f"Modified text for key '{self.input_key}': Original: {original_text[:30]}... -> Refined: {expanded_text[:30]}...") + + refined_data.append(item) + if modified: + numbers += 1 + self.logger.debug(f"Item modified, total modified so far: {numbers}") + self.logger.info(f"Refining Complete. Total modified items: {numbers}") + dataframe[self.input_key] = refined_data + output_file = storage.write(dataframe) + return [self.input_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_emoji_refiner.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_emoji_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..6ab73a16028d1dd244854e20d8abde9eb9b6822a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_emoji_refiner.py @@ -0,0 +1,82 @@ +import re +from tqdm import tqdm +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY + + +@OPERATOR_REGISTRY.register() +class RemoveEmojiRefiner(OperatorABC): + def __init__(self): + self.logger = get_logger() + self.refiner_name = 'RemoveEmojiRefiner' + self.logger.info(f"Initializing {self.__class__.__name__} ...") + + # Emoji pattern for matching emojis in the text + self.emoji_pattern = re.compile( + "[" + u"\U0001F600-\U0001F64F" # Emoticons + u"\U0001F300-\U0001F5FF" # Miscellaneous symbols and pictographs + u"\U0001F680-\U0001F6FF" # Transport and map symbols + u"\U0001F1E0-\U0001F1FF" # Flags + u"\U00002702-\U000027B0" # Dingbats + "]+", + flags=re.UNICODE + ) + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于去除文本中的Unicode图像表情符号,包括表情符号、杂项符号、交通符号、旗帜等各类图像符号。\n" + "通过正则表达式匹配Unicode表情符号范围,实现高效过滤。\n" + "输入参数:\n" + "- 无初始化参数\n" + "运行参数:\n" + "- input_key:输入文本字段名\n" + "输出参数:\n" + "- 处理后的DataFrame,包含去除表情符号的文本\n" + "- 返回包含输入字段名的列表,用于后续算子引用" + ) + elif lang == "en": + return ( + "This operator removes Unicode emojis from text, including emoticons, symbols, transport icons, flags and other image symbols.\n" + "Achieves efficient filtering by matching Unicode emoji ranges with regular expressions.\n" + "Input Parameters:\n" + "- No initialization parameters\n" + "Runtime Parameters:\n" + "- input_key: Input text field name\n" + "Output Parameters:\n" + "- Processed DataFrame containing text with emojis removed\n" + "- List containing input field name for subsequent operator reference" + ) + else: + return "Removes Unicode emojis from text using regular expression matching." + + def run(self, storage: DataFlowStorage, input_key: str): + dataframe = storage.read("dataframe") + numbers = 0 + refined_data = [] + self.logger.info(f"Running {self.__class__.__name__} with input_key = {input_key}...") + + for item in tqdm(dataframe[input_key], desc=f"Implementing {self.refiner_name}"): + modified = False + original_text = item + no_emoji_text = self.emoji_pattern.sub(r'', original_text) + + if original_text != no_emoji_text: + item = no_emoji_text + modified = True + self.logger.debug(f"Modified text for key '{input_key}': Original: {original_text[:30]}... -> Refined: {no_emoji_text[:30]}...") + + refined_data.append(item) + if modified: + numbers += 1 + self.logger.debug(f"Item modified, total modified so far: {numbers}") + + dataframe[input_key] = refined_data + storage.write(dataframe) + self.logger.info(f"Refining Complete. Total modified items: {numbers}") + + return [input_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_emoticons_refiner.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_emoticons_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..8a0b9701f0a70cdd81b0d934c65481d1f73c92b1 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_emoticons_refiner.py @@ -0,0 +1,5165 @@ +import re +from tqdm import tqdm +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY + +@OPERATOR_REGISTRY.register() +class RemoveEmoticonsRefiner(OperatorABC): + def __init__(self): + self.logger = get_logger() + self.emoticons = EMOTICONS_EMO.keys() + self.logger.info(f"Initializing {self.__class__.__name__}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于移除文本中的文本型表情符号,例如':-)'、':D'、':('等字符组合表情。\n" + "基于预定义的表情符号字典进行匹配替换,支持多种常见文本表情模式。\n" + "输入参数:\n" + "- 无初始化参数\n" + "运行参数:\n" + "- input_key:输入文本字段名\n" + "输出参数:\n" + "- 处理后的DataFrame,包含去除文本表情的文本\n" + "- 返回包含输入字段名的列表,用于后续算子引用" + ) + elif lang == "en": + return ( + "This operator removes text-based emoticons from text, such as ':-)'、':D'、':(' and other character combination emoticons.\n" + "Performs matching and replacement based on a predefined emoticon dictionary, supporting various common text emoticon patterns.\n" + "Input Parameters:\n" + "- No initialization parameters\n" + "Runtime Parameters:\n" + "- input_key: Input text field name\n" + "Output Parameters:\n" + "- Processed DataFrame containing text with emoticons removed\n" + "- List containing input field name for subsequent operator reference" + ) + else: + return "Removes text-based emoticons from text using a predefined dictionary." + + def run(self, storage: DataFlowStorage, input_key: str): + self.input_key = input_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key}...") + numbers = 0 + refined_data = [] + for item in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + modified = False + original_text = item + no_emoticon_text = original_text + + for emoticon in self.emoticons: + if emoticon in no_emoticon_text: + no_emoticon_text = no_emoticon_text.replace(emoticon, '') + + if original_text != no_emoticon_text: + item = no_emoticon_text + modified = True + self.logger.debug(f"Modified text for key '{self.input_key}': Original: {original_text[:30]}... -> Refined: {no_emoticon_text[:30]}...") + + refined_data.append(item) + if modified: + numbers += 1 + self.logger.debug(f"Item modified, total modified so far: {numbers}") + + dataframe[self.input_key] = refined_data + output_file = storage.write(dataframe) + return [self.input_key] + +""" +Emoticons and Emoji data dictonary +""" + +__all__ = ['EMOJI_UNICODE', 'UNICODE_EMOJI', 'EMOJI_ALIAS_UNICODE', 'UNICODE_EMOJI_ALIAS', 'EMOTICONS_EMO'] + +EMOTICONS_EMO = { + u":‑)":"Happy face or smiley", + u":-))":"Very Happy face or smiley", + u":-)))":"Very very Happy face or smiley", + u":)":"Happy face or smiley", + u":))":"Very Happy face or smiley", + u":)))":"Very very Happy face or smiley", + u":-]":"Happy face or smiley", + u":]":"Happy face or smiley", + u":-3":"Happy face smiley", + u":3":"Happy face smiley", + u":->":"Happy face smiley", + u":>":"Happy face smiley", + u"8-)":"Happy face smiley", + u":o)":"Happy face smiley", + u":-}":"Happy face smiley", + u":}":"Happy face smiley", + u":-)":"Happy face smiley", + u":c)":"Happy face smiley", + u":^)":"Happy face smiley", + u"=]":"Happy face smiley", + u"=)":"Happy face smiley", + u":‑D":"Laughing, big grin or laugh with glasses", + u":D":"Laughing, big grin or laugh with glasses", + u"8‑D":"Laughing, big grin or laugh with glasses", + u"8D":"Laughing, big grin or laugh with glasses", + u"X‑D":"Laughing, big grin or laugh with glasses", + u"XD":"Laughing, big grin or laugh with glasses", + u"=D":"Laughing, big grin or laugh with glasses", + u"=3":"Laughing, big grin or laugh with glasses", + u"B^D":"Laughing, big grin or laugh with glasses", + u":-))":"Very happy", + u":-(":"Frown, sad, angry or pouting", + u":‑(":"Frown, sad, angry or pouting", + u":(":"Frown, sad, angry or pouting", + u":‑c":"Frown, sad, angry or pouting", + u":c":"Frown, sad, angry or pouting", + u":‑<":"Frown, sad, angry or pouting", + u":<":"Frown, sad, angry or pouting", + u":‑[":"Frown, sad, angry or pouting", + u":[":"Frown, sad, angry or pouting", + u":-||":"Frown, sad, angry or pouting", + u">:[":"Frown, sad, angry or pouting", + u":{":"Frown, sad, angry or pouting", + u":@":"Frown, sad, angry or pouting", + u">:(":"Frown, sad, angry or pouting", + u":'‑(":"Crying", + u":'(":"Crying", + u":'‑)":"Tears of happiness", + u":')":"Tears of happiness", + u"D‑':":"Horror", + u"D:<":"Disgust", + u"D:":"Sadness", + u"D8":"Great dismay", + u"D;":"Great dismay", + u"D=":"Great dismay", + u"DX":"Great dismay", + u":‑O":"Surprise", + u":O":"Surprise", + u":‑o":"Surprise", + u":o":"Surprise", + u":-0":"Shock", + u"8‑0":"Yawn", + u">:O":"Yawn", + u":-*":"Kiss", + u":*":"Kiss", + u":X":"Kiss", + u";‑)":"Wink or smirk", + u";)":"Wink or smirk", + u"*-)":"Wink or smirk", + u"*)":"Wink or smirk", + u";‑]":"Wink or smirk", + u";]":"Wink or smirk", + u";^)":"Wink or smirk", + u":‑,":"Wink or smirk", + u";D":"Wink or smirk", + u":‑P":"Tongue sticking out, cheeky, playful or blowing a raspberry", + u":P":"Tongue sticking out, cheeky, playful or blowing a raspberry", + u"X‑P":"Tongue sticking out, cheeky, playful or blowing a raspberry", + u"XP":"Tongue sticking out, cheeky, playful or blowing a raspberry", + u":‑Þ":"Tongue sticking out, cheeky, playful or blowing a raspberry", + u":Þ":"Tongue sticking out, cheeky, playful or blowing a raspberry", + u":b":"Tongue sticking out, cheeky, playful or blowing a raspberry", + u"d:":"Tongue sticking out, cheeky, playful or blowing a raspberry", + u"=p":"Tongue sticking out, cheeky, playful or blowing a raspberry", + u">:P":"Tongue sticking out, cheeky, playful or blowing a raspberry", + u":‑/":"Skeptical, annoyed, undecided, uneasy or hesitant", + u":/":"Skeptical, annoyed, undecided, uneasy or hesitant", + u":-[.]":"Skeptical, annoyed, undecided, uneasy or hesitant", + u">:[(\)]":"Skeptical, annoyed, undecided, uneasy or hesitant", + u">:/":"Skeptical, annoyed, undecided, uneasy or hesitant", + u":[(\)]":"Skeptical, annoyed, undecided, uneasy or hesitant", + u"=/":"Skeptical, annoyed, undecided, uneasy or hesitant", + u"=[(\)]":"Skeptical, annoyed, undecided, uneasy or hesitant", + u":L":"Skeptical, annoyed, undecided, uneasy or hesitant", + u"=L":"Skeptical, annoyed, undecided, uneasy or hesitant", + u":S":"Skeptical, annoyed, undecided, uneasy or hesitant", + u":‑|":"Straight face", + u":|":"Straight face", + u":$":"Embarrassed or blushing", + u":‑x":"Sealed lips or wearing braces or tongue-tied", + u":x":"Sealed lips or wearing braces or tongue-tied", + u":‑#":"Sealed lips or wearing braces or tongue-tied", + u":#":"Sealed lips or wearing braces or tongue-tied", + u":‑&":"Sealed lips or wearing braces or tongue-tied", + u":&":"Sealed lips or wearing braces or tongue-tied", + u"O:‑)":"Angel, saint or innocent", + u"O:)":"Angel, saint or innocent", + u"0:‑3":"Angel, saint or innocent", + u"0:3":"Angel, saint or innocent", + u"0:‑)":"Angel, saint or innocent", + u"0:)":"Angel, saint or innocent", + u":‑b":"Tongue sticking out, cheeky, playful or blowing a raspberry", + u"0;^)":"Angel, saint or innocent", + u">:‑)":"Evil or devilish", + u">:)":"Evil or devilish", + u"}:‑)":"Evil or devilish", + u"}:)":"Evil or devilish", + u"3:‑)":"Evil or devilish", + u"3:)":"Evil or devilish", + u">;)":"Evil or devilish", + u"|;‑)":"Cool", + u"|‑O":"Bored", + u":‑J":"Tongue-in-cheek", + u"#‑)":"Party all night", + u"%‑)":"Drunk or confused", + u"%)":"Drunk or confused", + u":-###..":"Being sick", + u":###..":"Being sick", + u"<:‑|":"Dump", + u"(>_<)":"Troubled", + u"(>_<)>":"Troubled", + u"(';')":"Baby", + u"(^^>``":"Nervous or Embarrassed or Troubled or Shy or Sweat drop", + u"(^_^;)":"Nervous or Embarrassed or Troubled or Shy or Sweat drop", + u"(-_-;)":"Nervous or Embarrassed or Troubled or Shy or Sweat drop", + u"(~_~;) (・.・;)":"Nervous or Embarrassed or Troubled or Shy or Sweat drop", + u"(-_-)zzz":"Sleeping", + u"(^_-)":"Wink", + u"((+_+))":"Confused", + u"(+o+)":"Confused", + u"(o|o)":"Ultraman", + u"^_^":"Joyful", + u"(^_^)/":"Joyful", + u"(^O^)/":"Joyful", + u"(^o^)/":"Joyful", + u"(__)":"Kowtow as a sign of respect, or dogeza for apology", + u"_(._.)_":"Kowtow as a sign of respect, or dogeza for apology", + u"<(_ _)>":"Kowtow as a sign of respect, or dogeza for apology", + u"":"Kowtow as a sign of respect, or dogeza for apology", + u"m(__)m":"Kowtow as a sign of respect, or dogeza for apology", + u"m(_ _)m":"Kowtow as a sign of respect, or dogeza for apology", + u"('_')":"Sad or Crying", + u"(/_;)":"Sad or Crying", + u"(T_T) (;_;)":"Sad or Crying", + u"(;_;":"Sad of Crying", + u"(;_:)":"Sad or Crying", + u"(;O;)":"Sad or Crying", + u"(:_;)":"Sad or Crying", + u"(ToT)":"Sad or Crying", + u";_;":"Sad or Crying", + u";-;":"Sad or Crying", + u";n;":"Sad or Crying", + u";;":"Sad or Crying", + u"Q.Q":"Sad or Crying", + u"T.T":"Sad or Crying", + u"QQ":"Sad or Crying", + u"Q_Q":"Sad or Crying", + u"(-.-)":"Shame", + u"(-_-)":"Shame", + u"(一一)":"Shame", + u"(;一_一)":"Shame", + u"(=_=)":"Tired", + u"(=^·^=)":"cat", + u"(=^··^=)":"cat", + u"=_^= ":"cat", + u"(..)":"Looking down", + u"(._.)":"Looking down", + u"^m^":"Giggling with hand covering mouth", + u"(・・?":"Confusion", + u"(?_?)":"Confusion", + u">^_^<":"Normal Laugh", + u"<^!^>":"Normal Laugh", + u"^/^":"Normal Laugh", + u"(*^_^*)" :"Normal Laugh", + u"(^<^) (^.^)":"Normal Laugh", + u"(^^)":"Normal Laugh", + u"(^.^)":"Normal Laugh", + u"(^_^.)":"Normal Laugh", + u"(^_^)":"Normal Laugh", + u"(^^)":"Normal Laugh", + u"(^J^)":"Normal Laugh", + u"(*^.^*)":"Normal Laugh", + u"(^—^)":"Normal Laugh", + u"(#^.^#)":"Normal Laugh", + u"(^—^)":"Waving", + u"(;_;)/~~~":"Waving", + u"(^.^)/~~~":"Waving", + u"(-_-)/~~~ ($··)/~~~":"Waving", + u"(T_T)/~~~":"Waving", + u"(ToT)/~~~":"Waving", + u"(*^0^*)":"Excited", + u"(*_*)":"Amazed", + u"(*_*;":"Amazed", + u"(+_+) (@_@)":"Amazed", + u"(*^^)v":"Laughing,Cheerful", + u"(^_^)v":"Laughing,Cheerful", + u"((d[-_-]b))":"Headphones,Listening to music", + u'(-"-)':"Worried", + u"(ーー;)":"Worried", + u"(^0_0^)":"Eyeglasses", + u"(^v^)":"Happy", + u"(^u^)":"Happy", + u"(^)o(^)":"Happy", + u"(^O^)":"Happy", + u"(^o^)":"Happy", + u")^o^(":"Happy", + u":O o_O":"Surprised", + u"o_0":"Surprised", + u"o.O":"Surpised", + u"(o.o)":"Surprised", + u"oO":"Surprised", + u"(* ̄m ̄)":"Dissatisfied", + u"(‘A`)":"Snubbed or Deflated" + +} + +EMOJI_UNICODE = { + u':1st_place_medal:': u'\U0001F947', + u':2nd_place_medal:': u'\U0001F948', + u':3rd_place_medal:': u'\U0001F949', + u':AB_button_(blood_type):': u'\U0001F18E', + u':ATM_sign:': u'\U0001F3E7', + u':A_button_(blood_type):': u'\U0001F170', + u':Afghanistan:': u'\U0001F1E6\U0001F1EB', + u':Albania:': u'\U0001F1E6\U0001F1F1', + u':Algeria:': u'\U0001F1E9\U0001F1FF', + u':American_Samoa:': u'\U0001F1E6\U0001F1F8', + u':Andorra:': u'\U0001F1E6\U0001F1E9', + u':Angola:': u'\U0001F1E6\U0001F1F4', + u':Anguilla:': u'\U0001F1E6\U0001F1EE', + u':Antarctica:': u'\U0001F1E6\U0001F1F6', + u':Antigua_&_Barbuda:': u'\U0001F1E6\U0001F1EC', + u':Aquarius:': u'\U00002652', + u':Argentina:': u'\U0001F1E6\U0001F1F7', + u':Aries:': u'\U00002648', + u':Armenia:': u'\U0001F1E6\U0001F1F2', + u':Aruba:': u'\U0001F1E6\U0001F1FC', + u':Ascension_Island:': u'\U0001F1E6\U0001F1E8', + u':Australia:': u'\U0001F1E6\U0001F1FA', + u':Austria:': u'\U0001F1E6\U0001F1F9', + u':Azerbaijan:': u'\U0001F1E6\U0001F1FF', + u':BACK_arrow:': u'\U0001F519', + u':B_button_(blood_type):': u'\U0001F171', + u':Bahamas:': u'\U0001F1E7\U0001F1F8', + u':Bahrain:': u'\U0001F1E7\U0001F1ED', + u':Bangladesh:': u'\U0001F1E7\U0001F1E9', + u':Barbados:': u'\U0001F1E7\U0001F1E7', + u':Belarus:': u'\U0001F1E7\U0001F1FE', + u':Belgium:': u'\U0001F1E7\U0001F1EA', + u':Belize:': u'\U0001F1E7\U0001F1FF', + u':Benin:': u'\U0001F1E7\U0001F1EF', + u':Bermuda:': u'\U0001F1E7\U0001F1F2', + u':Bhutan:': u'\U0001F1E7\U0001F1F9', + u':Bolivia:': u'\U0001F1E7\U0001F1F4', + u':Bosnia_&_Herzegovina:': u'\U0001F1E7\U0001F1E6', + u':Botswana:': u'\U0001F1E7\U0001F1FC', + u':Bouvet_Island:': u'\U0001F1E7\U0001F1FB', + u':Brazil:': u'\U0001F1E7\U0001F1F7', + u':British_Indian_Ocean_Territory:': u'\U0001F1EE\U0001F1F4', + u':British_Virgin_Islands:': u'\U0001F1FB\U0001F1EC', + u':Brunei:': u'\U0001F1E7\U0001F1F3', + u':Bulgaria:': u'\U0001F1E7\U0001F1EC', + u':Burkina_Faso:': u'\U0001F1E7\U0001F1EB', + u':Burundi:': u'\U0001F1E7\U0001F1EE', + u':CL_button:': u'\U0001F191', + u':COOL_button:': u'\U0001F192', + u':Cambodia:': u'\U0001F1F0\U0001F1ED', + u':Cameroon:': u'\U0001F1E8\U0001F1F2', + u':Canada:': u'\U0001F1E8\U0001F1E6', + u':Canary_Islands:': u'\U0001F1EE\U0001F1E8', + u':Cancer:': u'\U0000264B', + u':Cape_Verde:': u'\U0001F1E8\U0001F1FB', + u':Capricorn:': u'\U00002651', + u':Caribbean_Netherlands:': u'\U0001F1E7\U0001F1F6', + u':Cayman_Islands:': u'\U0001F1F0\U0001F1FE', + u':Central_African_Republic:': u'\U0001F1E8\U0001F1EB', + u':Ceuta_&_Melilla:': u'\U0001F1EA\U0001F1E6', + u':Chad:': u'\U0001F1F9\U0001F1E9', + u':Chile:': u'\U0001F1E8\U0001F1F1', + u':China:': u'\U0001F1E8\U0001F1F3', + u':Christmas_Island:': u'\U0001F1E8\U0001F1FD', + u':Christmas_tree:': u'\U0001F384', + u':Clipperton_Island:': u'\U0001F1E8\U0001F1F5', + u':Cocos_(Keeling)_Islands:': u'\U0001F1E8\U0001F1E8', + u':Colombia:': u'\U0001F1E8\U0001F1F4', + u':Comoros:': u'\U0001F1F0\U0001F1F2', + u':Congo_-_Brazzaville:': u'\U0001F1E8\U0001F1EC', + u':Congo_-_Kinshasa:': u'\U0001F1E8\U0001F1E9', + u':Cook_Islands:': u'\U0001F1E8\U0001F1F0', + u':Costa_Rica:': u'\U0001F1E8\U0001F1F7', + u':Croatia:': u'\U0001F1ED\U0001F1F7', + u':Cuba:': u'\U0001F1E8\U0001F1FA', + u':Curaçao:': u'\U0001F1E8\U0001F1FC', + u':Cyprus:': u'\U0001F1E8\U0001F1FE', + u':Czechia:': u'\U0001F1E8\U0001F1FF', + u':Côte_d’Ivoire:': u'\U0001F1E8\U0001F1EE', + u':Denmark:': u'\U0001F1E9\U0001F1F0', + u':Diego_Garcia:': u'\U0001F1E9\U0001F1EC', + u':Djibouti:': u'\U0001F1E9\U0001F1EF', + u':Dominica:': u'\U0001F1E9\U0001F1F2', + u':Dominican_Republic:': u'\U0001F1E9\U0001F1F4', + u':END_arrow:': u'\U0001F51A', + u':Ecuador:': u'\U0001F1EA\U0001F1E8', + u':Egypt:': u'\U0001F1EA\U0001F1EC', + u':El_Salvador:': u'\U0001F1F8\U0001F1FB', + u':England:': u'\U0001F3F4\U000E0067\U000E0062\U000E0065\U000E006E\U000E0067\U000E007F', + u':Equatorial_Guinea:': u'\U0001F1EC\U0001F1F6', + u':Eritrea:': u'\U0001F1EA\U0001F1F7', + u':Estonia:': u'\U0001F1EA\U0001F1EA', + u':Eswatini:': u'\U0001F1F8\U0001F1FF', + u':Ethiopia:': u'\U0001F1EA\U0001F1F9', + u':European_Union:': u'\U0001F1EA\U0001F1FA', + u':FREE_button:': u'\U0001F193', + u':Falkland_Islands:': u'\U0001F1EB\U0001F1F0', + u':Faroe_Islands:': u'\U0001F1EB\U0001F1F4', + u':Fiji:': u'\U0001F1EB\U0001F1EF', + u':Finland:': u'\U0001F1EB\U0001F1EE', + u':France:': u'\U0001F1EB\U0001F1F7', + u':French_Guiana:': u'\U0001F1EC\U0001F1EB', + u':French_Polynesia:': u'\U0001F1F5\U0001F1EB', + u':French_Southern_Territories:': u'\U0001F1F9\U0001F1EB', + u':Gabon:': u'\U0001F1EC\U0001F1E6', + u':Gambia:': u'\U0001F1EC\U0001F1F2', + u':Gemini:': u'\U0000264A', + u':Georgia:': u'\U0001F1EC\U0001F1EA', + u':Germany:': u'\U0001F1E9\U0001F1EA', + u':Ghana:': u'\U0001F1EC\U0001F1ED', + u':Gibraltar:': u'\U0001F1EC\U0001F1EE', + u':Greece:': u'\U0001F1EC\U0001F1F7', + u':Greenland:': u'\U0001F1EC\U0001F1F1', + u':Grenada:': u'\U0001F1EC\U0001F1E9', + u':Guadeloupe:': u'\U0001F1EC\U0001F1F5', + u':Guam:': u'\U0001F1EC\U0001F1FA', + u':Guatemala:': u'\U0001F1EC\U0001F1F9', + u':Guernsey:': u'\U0001F1EC\U0001F1EC', + u':Guinea:': u'\U0001F1EC\U0001F1F3', + u':Guinea-Bissau:': u'\U0001F1EC\U0001F1FC', + u':Guyana:': u'\U0001F1EC\U0001F1FE', + u':Haiti:': u'\U0001F1ED\U0001F1F9', + u':Heard_&_McDonald_Islands:': u'\U0001F1ED\U0001F1F2', + u':Honduras:': u'\U0001F1ED\U0001F1F3', + u':Hong_Kong_SAR_China:': u'\U0001F1ED\U0001F1F0', + u':Hungary:': u'\U0001F1ED\U0001F1FA', + u':ID_button:': u'\U0001F194', + u':Iceland:': u'\U0001F1EE\U0001F1F8', + u':India:': u'\U0001F1EE\U0001F1F3', + u':Indonesia:': u'\U0001F1EE\U0001F1E9', + u':Iran:': u'\U0001F1EE\U0001F1F7', + u':Iraq:': u'\U0001F1EE\U0001F1F6', + u':Ireland:': u'\U0001F1EE\U0001F1EA', + u':Isle_of_Man:': u'\U0001F1EE\U0001F1F2', + u':Israel:': u'\U0001F1EE\U0001F1F1', + u':Italy:': u'\U0001F1EE\U0001F1F9', + u':Jamaica:': u'\U0001F1EF\U0001F1F2', + u':Japan:': u'\U0001F1EF\U0001F1F5', + u':Japanese_acceptable_button:': u'\U0001F251', + u':Japanese_application_button:': u'\U0001F238', + u':Japanese_bargain_button:': u'\U0001F250', + u':Japanese_castle:': u'\U0001F3EF', + u':Japanese_congratulations_button:': u'\U00003297', + u':Japanese_discount_button:': u'\U0001F239', + u':Japanese_dolls:': u'\U0001F38E', + u':Japanese_free_of_charge_button:': u'\U0001F21A', + u':Japanese_here_button:': u'\U0001F201', + u':Japanese_monthly_amount_button:': u'\U0001F237', + u':Japanese_no_vacancy_button:': u'\U0001F235', + u':Japanese_not_free_of_charge_button:': u'\U0001F236', + u':Japanese_open_for_business_button:': u'\U0001F23A', + u':Japanese_passing_grade_button:': u'\U0001F234', + u':Japanese_post_office:': u'\U0001F3E3', + u':Japanese_prohibited_button:': u'\U0001F232', + u':Japanese_reserved_button:': u'\U0001F22F', + u':Japanese_secret_button:': u'\U00003299', + u':Japanese_service_charge_button:': u'\U0001F202', + u':Japanese_symbol_for_beginner:': u'\U0001F530', + u':Japanese_vacancy_button:': u'\U0001F233', + u':Jersey:': u'\U0001F1EF\U0001F1EA', + u':Jordan:': u'\U0001F1EF\U0001F1F4', + u':Kazakhstan:': u'\U0001F1F0\U0001F1FF', + u':Kenya:': u'\U0001F1F0\U0001F1EA', + u':Kiribati:': u'\U0001F1F0\U0001F1EE', + u':Kosovo:': u'\U0001F1FD\U0001F1F0', + u':Kuwait:': u'\U0001F1F0\U0001F1FC', + u':Kyrgyzstan:': u'\U0001F1F0\U0001F1EC', + u':Laos:': u'\U0001F1F1\U0001F1E6', + u':Latvia:': u'\U0001F1F1\U0001F1FB', + u':Lebanon:': u'\U0001F1F1\U0001F1E7', + u':Leo:': u'\U0000264C', + u':Lesotho:': u'\U0001F1F1\U0001F1F8', + u':Liberia:': u'\U0001F1F1\U0001F1F7', + u':Libra:': u'\U0000264E', + u':Libya:': u'\U0001F1F1\U0001F1FE', + u':Liechtenstein:': u'\U0001F1F1\U0001F1EE', + u':Lithuania:': u'\U0001F1F1\U0001F1F9', + u':Luxembourg:': u'\U0001F1F1\U0001F1FA', + u':Macao_SAR_China:': u'\U0001F1F2\U0001F1F4', + u':Madagascar:': u'\U0001F1F2\U0001F1EC', + u':Malawi:': u'\U0001F1F2\U0001F1FC', + u':Malaysia:': u'\U0001F1F2\U0001F1FE', + u':Maldives:': u'\U0001F1F2\U0001F1FB', + u':Mali:': u'\U0001F1F2\U0001F1F1', + u':Malta:': u'\U0001F1F2\U0001F1F9', + u':Marshall_Islands:': u'\U0001F1F2\U0001F1ED', + u':Martinique:': u'\U0001F1F2\U0001F1F6', + u':Mauritania:': u'\U0001F1F2\U0001F1F7', + u':Mauritius:': u'\U0001F1F2\U0001F1FA', + u':Mayotte:': u'\U0001F1FE\U0001F1F9', + u':Mexico:': u'\U0001F1F2\U0001F1FD', + u':Micronesia:': u'\U0001F1EB\U0001F1F2', + u':Moldova:': u'\U0001F1F2\U0001F1E9', + u':Monaco:': u'\U0001F1F2\U0001F1E8', + u':Mongolia:': u'\U0001F1F2\U0001F1F3', + u':Montenegro:': u'\U0001F1F2\U0001F1EA', + u':Montserrat:': u'\U0001F1F2\U0001F1F8', + u':Morocco:': u'\U0001F1F2\U0001F1E6', + u':Mozambique:': u'\U0001F1F2\U0001F1FF', + u':Mrs._Claus:': u'\U0001F936', + u':Mrs._Claus_dark_skin_tone:': u'\U0001F936\U0001F3FF', + u':Mrs._Claus_light_skin_tone:': u'\U0001F936\U0001F3FB', + u':Mrs._Claus_medium-dark_skin_tone:': u'\U0001F936\U0001F3FE', + u':Mrs._Claus_medium-light_skin_tone:': u'\U0001F936\U0001F3FC', + u':Mrs._Claus_medium_skin_tone:': u'\U0001F936\U0001F3FD', + u':Myanmar_(Burma):': u'\U0001F1F2\U0001F1F2', + u':NEW_button:': u'\U0001F195', + u':NG_button:': u'\U0001F196', + u':Namibia:': u'\U0001F1F3\U0001F1E6', + u':Nauru:': u'\U0001F1F3\U0001F1F7', + u':Nepal:': u'\U0001F1F3\U0001F1F5', + u':Netherlands:': u'\U0001F1F3\U0001F1F1', + u':New_Caledonia:': u'\U0001F1F3\U0001F1E8', + u':New_Zealand:': u'\U0001F1F3\U0001F1FF', + u':Nicaragua:': u'\U0001F1F3\U0001F1EE', + u':Niger:': u'\U0001F1F3\U0001F1EA', + u':Nigeria:': u'\U0001F1F3\U0001F1EC', + u':Niue:': u'\U0001F1F3\U0001F1FA', + u':Norfolk_Island:': u'\U0001F1F3\U0001F1EB', + u':North_Korea:': u'\U0001F1F0\U0001F1F5', + u':North_Macedonia:': u'\U0001F1F2\U0001F1F0', + u':Northern_Mariana_Islands:': u'\U0001F1F2\U0001F1F5', + u':Norway:': u'\U0001F1F3\U0001F1F4', + u':OK_button:': u'\U0001F197', + u':OK_hand:': u'\U0001F44C', + u':OK_hand_dark_skin_tone:': u'\U0001F44C\U0001F3FF', + u':OK_hand_light_skin_tone:': u'\U0001F44C\U0001F3FB', + u':OK_hand_medium-dark_skin_tone:': u'\U0001F44C\U0001F3FE', + u':OK_hand_medium-light_skin_tone:': u'\U0001F44C\U0001F3FC', + u':OK_hand_medium_skin_tone:': u'\U0001F44C\U0001F3FD', + u':ON!_arrow:': u'\U0001F51B', + u':O_button_(blood_type):': u'\U0001F17E', + u':Oman:': u'\U0001F1F4\U0001F1F2', + u':Ophiuchus:': u'\U000026CE', + u':P_button:': u'\U0001F17F', + u':Pakistan:': u'\U0001F1F5\U0001F1F0', + u':Palau:': u'\U0001F1F5\U0001F1FC', + u':Palestinian_Territories:': u'\U0001F1F5\U0001F1F8', + u':Panama:': u'\U0001F1F5\U0001F1E6', + u':Papua_New_Guinea:': u'\U0001F1F5\U0001F1EC', + u':Paraguay:': u'\U0001F1F5\U0001F1FE', + u':Peru:': u'\U0001F1F5\U0001F1EA', + u':Philippines:': u'\U0001F1F5\U0001F1ED', + u':Pisces:': u'\U00002653', + u':Pitcairn_Islands:': u'\U0001F1F5\U0001F1F3', + u':Poland:': u'\U0001F1F5\U0001F1F1', + u':Portugal:': u'\U0001F1F5\U0001F1F9', + u':Puerto_Rico:': u'\U0001F1F5\U0001F1F7', + u':Qatar:': u'\U0001F1F6\U0001F1E6', + u':Romania:': u'\U0001F1F7\U0001F1F4', + u':Russia:': u'\U0001F1F7\U0001F1FA', + u':Rwanda:': u'\U0001F1F7\U0001F1FC', + u':Réunion:': u'\U0001F1F7\U0001F1EA', + u':SOON_arrow:': u'\U0001F51C', + u':SOS_button:': u'\U0001F198', + u':Sagittarius:': u'\U00002650', + u':Samoa:': u'\U0001F1FC\U0001F1F8', + u':San_Marino:': u'\U0001F1F8\U0001F1F2', + u':Santa_Claus:': u'\U0001F385', + u':Santa_Claus_dark_skin_tone:': u'\U0001F385\U0001F3FF', + u':Santa_Claus_light_skin_tone:': u'\U0001F385\U0001F3FB', + u':Santa_Claus_medium-dark_skin_tone:': u'\U0001F385\U0001F3FE', + u':Santa_Claus_medium-light_skin_tone:': u'\U0001F385\U0001F3FC', + u':Santa_Claus_medium_skin_tone:': u'\U0001F385\U0001F3FD', + u':Saudi_Arabia:': u'\U0001F1F8\U0001F1E6', + u':Scorpio:': u'\U0000264F', + u':Scotland:': u'\U0001F3F4\U000E0067\U000E0062\U000E0073\U000E0063\U000E0074\U000E007F', + u':Senegal:': u'\U0001F1F8\U0001F1F3', + u':Serbia:': u'\U0001F1F7\U0001F1F8', + u':Seychelles:': u'\U0001F1F8\U0001F1E8', + u':Sierra_Leone:': u'\U0001F1F8\U0001F1F1', + u':Singapore:': u'\U0001F1F8\U0001F1EC', + u':Sint_Maarten:': u'\U0001F1F8\U0001F1FD', + u':Slovakia:': u'\U0001F1F8\U0001F1F0', + u':Slovenia:': u'\U0001F1F8\U0001F1EE', + u':Solomon_Islands:': u'\U0001F1F8\U0001F1E7', + u':Somalia:': u'\U0001F1F8\U0001F1F4', + u':South_Africa:': u'\U0001F1FF\U0001F1E6', + u':South_Georgia_&_South_Sandwich_Islands:': u'\U0001F1EC\U0001F1F8', + u':South_Korea:': u'\U0001F1F0\U0001F1F7', + u':South_Sudan:': u'\U0001F1F8\U0001F1F8', + u':Spain:': u'\U0001F1EA\U0001F1F8', + u':Sri_Lanka:': u'\U0001F1F1\U0001F1F0', + u':St._Barthélemy:': u'\U0001F1E7\U0001F1F1', + u':St._Helena:': u'\U0001F1F8\U0001F1ED', + u':St._Kitts_&_Nevis:': u'\U0001F1F0\U0001F1F3', + u':St._Lucia:': u'\U0001F1F1\U0001F1E8', + u':St._Martin:': u'\U0001F1F2\U0001F1EB', + u':St._Pierre_&_Miquelon:': u'\U0001F1F5\U0001F1F2', + u':St._Vincent_&_Grenadines:': u'\U0001F1FB\U0001F1E8', + u':Statue_of_Liberty:': u'\U0001F5FD', + u':Sudan:': u'\U0001F1F8\U0001F1E9', + u':Suriname:': u'\U0001F1F8\U0001F1F7', + u':Svalbard_&_Jan_Mayen:': u'\U0001F1F8\U0001F1EF', + u':Sweden:': u'\U0001F1F8\U0001F1EA', + u':Switzerland:': u'\U0001F1E8\U0001F1ED', + u':Syria:': u'\U0001F1F8\U0001F1FE', + u':São_Tomé_&_Príncipe:': u'\U0001F1F8\U0001F1F9', + u':T-Rex:': u'\U0001F996', + u':TOP_arrow:': u'\U0001F51D', + u':Taiwan:': u'\U0001F1F9\U0001F1FC', + u':Tajikistan:': u'\U0001F1F9\U0001F1EF', + u':Tanzania:': u'\U0001F1F9\U0001F1FF', + u':Taurus:': u'\U00002649', + u':Thailand:': u'\U0001F1F9\U0001F1ED', + u':Timor-Leste:': u'\U0001F1F9\U0001F1F1', + u':Togo:': u'\U0001F1F9\U0001F1EC', + u':Tokelau:': u'\U0001F1F9\U0001F1F0', + u':Tokyo_tower:': u'\U0001F5FC', + u':Tonga:': u'\U0001F1F9\U0001F1F4', + u':Trinidad_&_Tobago:': u'\U0001F1F9\U0001F1F9', + u':Tristan_da_Cunha:': u'\U0001F1F9\U0001F1E6', + u':Tunisia:': u'\U0001F1F9\U0001F1F3', + u':Turkey:': u'\U0001F1F9\U0001F1F7', + u':Turkmenistan:': u'\U0001F1F9\U0001F1F2', + u':Turks_&_Caicos_Islands:': u'\U0001F1F9\U0001F1E8', + u':Tuvalu:': u'\U0001F1F9\U0001F1FB', + u':U.S._Outlying_Islands:': u'\U0001F1FA\U0001F1F2', + u':U.S._Virgin_Islands:': u'\U0001F1FB\U0001F1EE', + u':UP!_button:': u'\U0001F199', + u':Uganda:': u'\U0001F1FA\U0001F1EC', + u':Ukraine:': u'\U0001F1FA\U0001F1E6', + u':United_Arab_Emirates:': u'\U0001F1E6\U0001F1EA', + u':United_Kingdom:': u'\U0001F1EC\U0001F1E7', + u':United_Nations:': u'\U0001F1FA\U0001F1F3', + u':United_States:': u'\U0001F1FA\U0001F1F8', + u':Uruguay:': u'\U0001F1FA\U0001F1FE', + u':Uzbekistan:': u'\U0001F1FA\U0001F1FF', + u':VS_button:': u'\U0001F19A', + u':Vanuatu:': u'\U0001F1FB\U0001F1FA', + u':Vatican_City:': u'\U0001F1FB\U0001F1E6', + u':Venezuela:': u'\U0001F1FB\U0001F1EA', + u':Vietnam:': u'\U0001F1FB\U0001F1F3', + u':Virgo:': u'\U0000264D', + u':Wales:': u'\U0001F3F4\U000E0067\U000E0062\U000E0077\U000E006C\U000E0073\U000E007F', + u':Wallis_&_Futuna:': u'\U0001F1FC\U0001F1EB', + u':Western_Sahara:': u'\U0001F1EA\U0001F1ED', + u':Yemen:': u'\U0001F1FE\U0001F1EA', + u':Zambia:': u'\U0001F1FF\U0001F1F2', + u':Zimbabwe:': u'\U0001F1FF\U0001F1FC', + u':abacus:': u'\U0001F9EE', + u':accordion:': u'\U0001FA97', + u':adhesive_bandage:': u'\U0001FA79', + u':admission_tickets:': u'\U0001F39F', + u':aerial_tramway:': u'\U0001F6A1', + u':airplane:': u'\U00002708', + u':airplane_arrival:': u'\U0001F6EC', + u':airplane_departure:': u'\U0001F6EB', + u':alarm_clock:': u'\U000023F0', + u':alembic:': u'\U00002697', + u':alien:': u'\U0001F47D', + u':alien_monster:': u'\U0001F47E', + u':ambulance:': u'\U0001F691', + u':american_football:': u'\U0001F3C8', + u':amphora:': u'\U0001F3FA', + u':anatomical_heart:': u'\U0001FAC0', + u':anchor:': u'\U00002693', + u':anger_symbol:': u'\U0001F4A2', + u':angry_face:': u'\U0001F620', + u':angry_face_with_horns:': u'\U0001F47F', + u':anguished_face:': u'\U0001F627', + u':ant:': u'\U0001F41C', + u':antenna_bars:': u'\U0001F4F6', + u':anxious_face_with_sweat:': u'\U0001F630', + u':articulated_lorry:': u'\U0001F69B', + u':artist:': u'\U0001F9D1\U0000200D\U0001F3A8', + u':artist_dark_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F3A8', + u':artist_light_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F3A8', + u':artist_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F3A8', + u':artist_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F3A8', + u':artist_medium_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F3A8', + u':artist_palette:': u'\U0001F3A8', + u':astonished_face:': u'\U0001F632', + u':astronaut:': u'\U0001F9D1\U0000200D\U0001F680', + u':astronaut_dark_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F680', + u':astronaut_light_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F680', + u':astronaut_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F680', + u':astronaut_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F680', + u':astronaut_medium_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F680', + u':atom_symbol:': u'\U0000269B', + u':auto_rickshaw:': u'\U0001F6FA', + u':automobile:': u'\U0001F697', + u':avocado:': u'\U0001F951', + u':axe:': u'\U0001FA93', + u':baby:': u'\U0001F476', + u':baby_angel:': u'\U0001F47C', + u':baby_angel_dark_skin_tone:': u'\U0001F47C\U0001F3FF', + u':baby_angel_light_skin_tone:': u'\U0001F47C\U0001F3FB', + u':baby_angel_medium-dark_skin_tone:': u'\U0001F47C\U0001F3FE', + u':baby_angel_medium-light_skin_tone:': u'\U0001F47C\U0001F3FC', + u':baby_angel_medium_skin_tone:': u'\U0001F47C\U0001F3FD', + u':baby_bottle:': u'\U0001F37C', + u':baby_chick:': u'\U0001F424', + u':baby_dark_skin_tone:': u'\U0001F476\U0001F3FF', + u':baby_light_skin_tone:': u'\U0001F476\U0001F3FB', + u':baby_medium-dark_skin_tone:': u'\U0001F476\U0001F3FE', + u':baby_medium-light_skin_tone:': u'\U0001F476\U0001F3FC', + u':baby_medium_skin_tone:': u'\U0001F476\U0001F3FD', + u':baby_symbol:': u'\U0001F6BC', + u':backhand_index_pointing_down:': u'\U0001F447', + u':backhand_index_pointing_down_dark_skin_tone:': u'\U0001F447\U0001F3FF', + u':backhand_index_pointing_down_light_skin_tone:': u'\U0001F447\U0001F3FB', + u':backhand_index_pointing_down_medium-dark_skin_tone:': u'\U0001F447\U0001F3FE', + u':backhand_index_pointing_down_medium-light_skin_tone:': u'\U0001F447\U0001F3FC', + u':backhand_index_pointing_down_medium_skin_tone:': u'\U0001F447\U0001F3FD', + u':backhand_index_pointing_left:': u'\U0001F448', + u':backhand_index_pointing_left_dark_skin_tone:': u'\U0001F448\U0001F3FF', + u':backhand_index_pointing_left_light_skin_tone:': u'\U0001F448\U0001F3FB', + u':backhand_index_pointing_left_medium-dark_skin_tone:': u'\U0001F448\U0001F3FE', + u':backhand_index_pointing_left_medium-light_skin_tone:': u'\U0001F448\U0001F3FC', + u':backhand_index_pointing_left_medium_skin_tone:': u'\U0001F448\U0001F3FD', + u':backhand_index_pointing_right:': u'\U0001F449', + u':backhand_index_pointing_right_dark_skin_tone:': u'\U0001F449\U0001F3FF', + u':backhand_index_pointing_right_light_skin_tone:': u'\U0001F449\U0001F3FB', + u':backhand_index_pointing_right_medium-dark_skin_tone:': u'\U0001F449\U0001F3FE', + u':backhand_index_pointing_right_medium-light_skin_tone:': u'\U0001F449\U0001F3FC', + u':backhand_index_pointing_right_medium_skin_tone:': u'\U0001F449\U0001F3FD', + u':backhand_index_pointing_up:': u'\U0001F446', + u':backhand_index_pointing_up_dark_skin_tone:': u'\U0001F446\U0001F3FF', + u':backhand_index_pointing_up_light_skin_tone:': u'\U0001F446\U0001F3FB', + u':backhand_index_pointing_up_medium-dark_skin_tone:': u'\U0001F446\U0001F3FE', + u':backhand_index_pointing_up_medium-light_skin_tone:': u'\U0001F446\U0001F3FC', + u':backhand_index_pointing_up_medium_skin_tone:': u'\U0001F446\U0001F3FD', + u':backpack:': u'\U0001F392', + u':bacon:': u'\U0001F953', + u':badger:': u'\U0001F9A1', + u':badminton:': u'\U0001F3F8', + u':bagel:': u'\U0001F96F', + u':baggage_claim:': u'\U0001F6C4', + u':baguette_bread:': u'\U0001F956', + u':balance_scale:': u'\U00002696', + u':bald:': u'\U0001F9B2', + u':ballet_shoes:': u'\U0001FA70', + u':balloon:': u'\U0001F388', + u':ballot_box_with_ballot:': u'\U0001F5F3', + u':banana:': u'\U0001F34C', + u':banjo:': u'\U0001FA95', + u':bank:': u'\U0001F3E6', + u':bar_chart:': u'\U0001F4CA', + u':barber_pole:': u'\U0001F488', + u':baseball:': u'\U000026BE', + u':basket:': u'\U0001F9FA', + u':basketball:': u'\U0001F3C0', + u':bat:': u'\U0001F987', + u':bathtub:': u'\U0001F6C1', + u':battery:': u'\U0001F50B', + u':beach_with_umbrella:': u'\U0001F3D6', + u':beaming_face_with_smiling_eyes:': u'\U0001F601', + u':bear:': u'\U0001F43B', + u':beating_heart:': u'\U0001F493', + u':beaver:': u'\U0001F9AB', + u':bed:': u'\U0001F6CF', + u':beer_mug:': u'\U0001F37A', + u':beetle:': u'\U0001FAB2', + u':bell:': u'\U0001F514', + u':bell_pepper:': u'\U0001FAD1', + u':bell_with_slash:': u'\U0001F515', + u':bellhop_bell:': u'\U0001F6CE', + u':bento_box:': u'\U0001F371', + u':beverage_box:': u'\U0001F9C3', + u':bicycle:': u'\U0001F6B2', + u':bikini:': u'\U0001F459', + u':billed_cap:': u'\U0001F9E2', + u':biohazard:': u'\U00002623', + u':bird:': u'\U0001F426', + u':birthday_cake:': u'\U0001F382', + u':bison:': u'\U0001F9AC', + u':black_cat:': u'\U0001F408\U0000200D\U00002B1B', + u':black_circle:': u'\U000026AB', + u':black_flag:': u'\U0001F3F4', + u':black_heart:': u'\U0001F5A4', + u':black_large_square:': u'\U00002B1B', + u':black_medium-small_square:': u'\U000025FE', + u':black_medium_square:': u'\U000025FC', + u':black_nib:': u'\U00002712', + u':black_small_square:': u'\U000025AA', + u':black_square_button:': u'\U0001F532', + u':blossom:': u'\U0001F33C', + u':blowfish:': u'\U0001F421', + u':blue_book:': u'\U0001F4D8', + u':blue_circle:': u'\U0001F535', + u':blue_heart:': u'\U0001F499', + u':blue_square:': u'\U0001F7E6', + u':blueberries:': u'\U0001FAD0', + u':boar:': u'\U0001F417', + u':bomb:': u'\U0001F4A3', + u':bone:': u'\U0001F9B4', + u':bookmark:': u'\U0001F516', + u':bookmark_tabs:': u'\U0001F4D1', + u':books:': u'\U0001F4DA', + u':boomerang:': u'\U0001FA83', + u':bottle_with_popping_cork:': u'\U0001F37E', + u':bouquet:': u'\U0001F490', + u':bow_and_arrow:': u'\U0001F3F9', + u':bowl_with_spoon:': u'\U0001F963', + u':bowling:': u'\U0001F3B3', + u':boxing_glove:': u'\U0001F94A', + u':boy:': u'\U0001F466', + u':boy_dark_skin_tone:': u'\U0001F466\U0001F3FF', + u':boy_light_skin_tone:': u'\U0001F466\U0001F3FB', + u':boy_medium-dark_skin_tone:': u'\U0001F466\U0001F3FE', + u':boy_medium-light_skin_tone:': u'\U0001F466\U0001F3FC', + u':boy_medium_skin_tone:': u'\U0001F466\U0001F3FD', + u':brain:': u'\U0001F9E0', + u':bread:': u'\U0001F35E', + u':breast-feeding:': u'\U0001F931', + u':breast-feeding_dark_skin_tone:': u'\U0001F931\U0001F3FF', + u':breast-feeding_light_skin_tone:': u'\U0001F931\U0001F3FB', + u':breast-feeding_medium-dark_skin_tone:': u'\U0001F931\U0001F3FE', + u':breast-feeding_medium-light_skin_tone:': u'\U0001F931\U0001F3FC', + u':breast-feeding_medium_skin_tone:': u'\U0001F931\U0001F3FD', + u':brick:': u'\U0001F9F1', + u':bridge_at_night:': u'\U0001F309', + u':briefcase:': u'\U0001F4BC', + u':briefs:': u'\U0001FA72', + u':bright_button:': u'\U0001F506', + u':broccoli:': u'\U0001F966', + u':broken_heart:': u'\U0001F494', + u':broom:': u'\U0001F9F9', + u':brown_circle:': u'\U0001F7E4', + u':brown_heart:': u'\U0001F90E', + u':brown_square:': u'\U0001F7EB', + u':bubble_tea:': u'\U0001F9CB', + u':bucket:': u'\U0001FAA3', + u':bug:': u'\U0001F41B', + u':building_construction:': u'\U0001F3D7', + u':bullet_train:': u'\U0001F685', + u':bullseye:': u'\U0001F3AF', + u':burrito:': u'\U0001F32F', + u':bus:': u'\U0001F68C', + u':bus_stop:': u'\U0001F68F', + u':bust_in_silhouette:': u'\U0001F464', + u':busts_in_silhouette:': u'\U0001F465', + u':butter:': u'\U0001F9C8', + u':butterfly:': u'\U0001F98B', + u':cactus:': u'\U0001F335', + u':calendar:': u'\U0001F4C5', + u':call_me_hand:': u'\U0001F919', + u':call_me_hand_dark_skin_tone:': u'\U0001F919\U0001F3FF', + u':call_me_hand_light_skin_tone:': u'\U0001F919\U0001F3FB', + u':call_me_hand_medium-dark_skin_tone:': u'\U0001F919\U0001F3FE', + u':call_me_hand_medium-light_skin_tone:': u'\U0001F919\U0001F3FC', + u':call_me_hand_medium_skin_tone:': u'\U0001F919\U0001F3FD', + u':camel:': u'\U0001F42A', + u':camera:': u'\U0001F4F7', + u':camera_with_flash:': u'\U0001F4F8', + u':camping:': u'\U0001F3D5', + u':candle:': u'\U0001F56F', + u':candy:': u'\U0001F36C', + u':canned_food:': u'\U0001F96B', + u':canoe:': u'\U0001F6F6', + u':card_file_box:': u'\U0001F5C3', + u':card_index:': u'\U0001F4C7', + u':card_index_dividers:': u'\U0001F5C2', + u':carousel_horse:': u'\U0001F3A0', + u':carp_streamer:': u'\U0001F38F', + u':carpentry_saw:': u'\U0001FA9A', + u':carrot:': u'\U0001F955', + u':castle:': u'\U0001F3F0', + u':cat:': u'\U0001F408', + u':cat_face:': u'\U0001F431', + u':cat_with_tears_of_joy:': u'\U0001F639', + u':cat_with_wry_smile:': u'\U0001F63C', + u':chains:': u'\U000026D3', + u':chair:': u'\U0001FA91', + u':chart_decreasing:': u'\U0001F4C9', + u':chart_increasing:': u'\U0001F4C8', + u':chart_increasing_with_yen:': u'\U0001F4B9', + u':check_box_with_check:': u'\U00002611', + u':check_mark:': u'\U00002714', + u':check_mark_button:': u'\U00002705', + u':cheese_wedge:': u'\U0001F9C0', + u':chequered_flag:': u'\U0001F3C1', + u':cherries:': u'\U0001F352', + u':cherry_blossom:': u'\U0001F338', + u':chess_pawn:': u'\U0000265F', + u':chestnut:': u'\U0001F330', + u':chicken:': u'\U0001F414', + u':child:': u'\U0001F9D2', + u':child_dark_skin_tone:': u'\U0001F9D2\U0001F3FF', + u':child_light_skin_tone:': u'\U0001F9D2\U0001F3FB', + u':child_medium-dark_skin_tone:': u'\U0001F9D2\U0001F3FE', + u':child_medium-light_skin_tone:': u'\U0001F9D2\U0001F3FC', + u':child_medium_skin_tone:': u'\U0001F9D2\U0001F3FD', + u':children_crossing:': u'\U0001F6B8', + u':chipmunk:': u'\U0001F43F', + u':chocolate_bar:': u'\U0001F36B', + u':chopsticks:': u'\U0001F962', + u':church:': u'\U000026EA', + u':cigarette:': u'\U0001F6AC', + u':cinema:': u'\U0001F3A6', + u':circled_M:': u'\U000024C2', + u':circus_tent:': u'\U0001F3AA', + u':cityscape:': u'\U0001F3D9', + u':cityscape_at_dusk:': u'\U0001F306', + u':clamp:': u'\U0001F5DC', + u':clapper_board:': u'\U0001F3AC', + u':clapping_hands:': u'\U0001F44F', + u':clapping_hands_dark_skin_tone:': u'\U0001F44F\U0001F3FF', + u':clapping_hands_light_skin_tone:': u'\U0001F44F\U0001F3FB', + u':clapping_hands_medium-dark_skin_tone:': u'\U0001F44F\U0001F3FE', + u':clapping_hands_medium-light_skin_tone:': u'\U0001F44F\U0001F3FC', + u':clapping_hands_medium_skin_tone:': u'\U0001F44F\U0001F3FD', + u':classical_building:': u'\U0001F3DB', + u':clinking_beer_mugs:': u'\U0001F37B', + u':clinking_glasses:': u'\U0001F942', + u':clipboard:': u'\U0001F4CB', + u':clockwise_vertical_arrows:': u'\U0001F503', + u':closed_book:': u'\U0001F4D5', + u':closed_mailbox_with_lowered_flag:': u'\U0001F4EA', + u':closed_mailbox_with_raised_flag:': u'\U0001F4EB', + u':closed_umbrella:': u'\U0001F302', + u':cloud:': u'\U00002601', + u':cloud_with_lightning:': u'\U0001F329', + u':cloud_with_lightning_and_rain:': u'\U000026C8', + u':cloud_with_rain:': u'\U0001F327', + u':cloud_with_snow:': u'\U0001F328', + u':clown_face:': u'\U0001F921', + u':club_suit:': u'\U00002663', + u':clutch_bag:': u'\U0001F45D', + u':coat:': u'\U0001F9E5', + u':cockroach:': u'\U0001FAB3', + u':cocktail_glass:': u'\U0001F378', + u':coconut:': u'\U0001F965', + u':coffin:': u'\U000026B0', + u':coin:': u'\U0001FA99', + u':cold_face:': u'\U0001F976', + u':collision:': u'\U0001F4A5', + u':comet:': u'\U00002604', + u':compass:': u'\U0001F9ED', + u':computer_disk:': u'\U0001F4BD', + u':computer_mouse:': u'\U0001F5B1', + u':confetti_ball:': u'\U0001F38A', + u':confounded_face:': u'\U0001F616', + u':confused_face:': u'\U0001F615', + u':construction:': u'\U0001F6A7', + u':construction_worker:': u'\U0001F477', + u':construction_worker_dark_skin_tone:': u'\U0001F477\U0001F3FF', + u':construction_worker_light_skin_tone:': u'\U0001F477\U0001F3FB', + u':construction_worker_medium-dark_skin_tone:': u'\U0001F477\U0001F3FE', + u':construction_worker_medium-light_skin_tone:': u'\U0001F477\U0001F3FC', + u':construction_worker_medium_skin_tone:': u'\U0001F477\U0001F3FD', + u':control_knobs:': u'\U0001F39B', + u':convenience_store:': u'\U0001F3EA', + u':cook:': u'\U0001F9D1\U0000200D\U0001F373', + u':cook_dark_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F373', + u':cook_light_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F373', + u':cook_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F373', + u':cook_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F373', + u':cook_medium_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F373', + u':cooked_rice:': u'\U0001F35A', + u':cookie:': u'\U0001F36A', + u':cooking:': u'\U0001F373', + u':copyright:': u'\U000000A9', + u':couch_and_lamp:': u'\U0001F6CB', + u':counterclockwise_arrows_button:': u'\U0001F504', + u':couple_with_heart:': u'\U0001F491', + u':couple_with_heart_dark_skin_tone:': u'\U0001F491\U0001F3FF', + u':couple_with_heart_light_skin_tone:': u'\U0001F491\U0001F3FB', + u':couple_with_heart_man_man:': u'\U0001F468\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468', + u':couple_with_heart_man_man_dark_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FF', + u':couple_with_heart_man_man_dark_skin_tone_light_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FB', + u':couple_with_heart_man_man_dark_skin_tone_medium-dark_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FE', + u':couple_with_heart_man_man_dark_skin_tone_medium-light_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FC', + u':couple_with_heart_man_man_dark_skin_tone_medium_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FD', + u':couple_with_heart_man_man_light_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FB', + u':couple_with_heart_man_man_light_skin_tone_dark_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FF', + u':couple_with_heart_man_man_light_skin_tone_medium-dark_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FE', + u':couple_with_heart_man_man_light_skin_tone_medium-light_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FC', + u':couple_with_heart_man_man_light_skin_tone_medium_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FD', + u':couple_with_heart_man_man_medium-dark_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FE', + u':couple_with_heart_man_man_medium-dark_skin_tone_dark_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FF', + u':couple_with_heart_man_man_medium-dark_skin_tone_light_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FB', + u':couple_with_heart_man_man_medium-dark_skin_tone_medium-light_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FC', + u':couple_with_heart_man_man_medium-dark_skin_tone_medium_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FD', + u':couple_with_heart_man_man_medium-light_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FC', + u':couple_with_heart_man_man_medium-light_skin_tone_dark_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FF', + u':couple_with_heart_man_man_medium-light_skin_tone_light_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FB', + u':couple_with_heart_man_man_medium-light_skin_tone_medium-dark_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FE', + u':couple_with_heart_man_man_medium-light_skin_tone_medium_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FD', + u':couple_with_heart_man_man_medium_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FD', + u':couple_with_heart_man_man_medium_skin_tone_dark_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FF', + u':couple_with_heart_man_man_medium_skin_tone_light_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FB', + u':couple_with_heart_man_man_medium_skin_tone_medium-dark_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FE', + u':couple_with_heart_man_man_medium_skin_tone_medium-light_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FC', + u':couple_with_heart_medium-dark_skin_tone:': u'\U0001F491\U0001F3FE', + u':couple_with_heart_medium-light_skin_tone:': u'\U0001F491\U0001F3FC', + u':couple_with_heart_medium_skin_tone:': u'\U0001F491\U0001F3FD', + u':couple_with_heart_person_person_dark_skin_tone_light_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F9D1\U0001F3FB', + u':couple_with_heart_person_person_dark_skin_tone_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F9D1\U0001F3FE', + u':couple_with_heart_person_person_dark_skin_tone_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F9D1\U0001F3FC', + u':couple_with_heart_person_person_dark_skin_tone_medium_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F9D1\U0001F3FD', + u':couple_with_heart_person_person_light_skin_tone_dark_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F9D1\U0001F3FF', + u':couple_with_heart_person_person_light_skin_tone_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F9D1\U0001F3FE', + u':couple_with_heart_person_person_light_skin_tone_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F9D1\U0001F3FC', + u':couple_with_heart_person_person_light_skin_tone_medium_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F9D1\U0001F3FD', + u':couple_with_heart_person_person_medium-dark_skin_tone_dark_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F9D1\U0001F3FF', + u':couple_with_heart_person_person_medium-dark_skin_tone_light_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F9D1\U0001F3FB', + u':couple_with_heart_person_person_medium-dark_skin_tone_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F9D1\U0001F3FC', + u':couple_with_heart_person_person_medium-dark_skin_tone_medium_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F9D1\U0001F3FD', + u':couple_with_heart_person_person_medium-light_skin_tone_dark_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F9D1\U0001F3FF', + u':couple_with_heart_person_person_medium-light_skin_tone_light_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F9D1\U0001F3FB', + u':couple_with_heart_person_person_medium-light_skin_tone_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F9D1\U0001F3FE', + u':couple_with_heart_person_person_medium-light_skin_tone_medium_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F9D1\U0001F3FD', + u':couple_with_heart_person_person_medium_skin_tone_dark_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F9D1\U0001F3FF', + u':couple_with_heart_person_person_medium_skin_tone_light_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F9D1\U0001F3FB', + u':couple_with_heart_person_person_medium_skin_tone_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F9D1\U0001F3FE', + u':couple_with_heart_person_person_medium_skin_tone_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F9D1\U0001F3FC', + u':couple_with_heart_woman_man:': u'\U0001F469\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468', + u':couple_with_heart_woman_man_dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FF', + u':couple_with_heart_woman_man_dark_skin_tone_light_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FB', + u':couple_with_heart_woman_man_dark_skin_tone_medium-dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FE', + u':couple_with_heart_woman_man_dark_skin_tone_medium-light_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FC', + u':couple_with_heart_woman_man_dark_skin_tone_medium_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FD', + u':couple_with_heart_woman_man_light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FB', + u':couple_with_heart_woman_man_light_skin_tone_dark_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FF', + u':couple_with_heart_woman_man_light_skin_tone_medium-dark_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FE', + u':couple_with_heart_woman_man_light_skin_tone_medium-light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FC', + u':couple_with_heart_woman_man_light_skin_tone_medium_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FD', + u':couple_with_heart_woman_man_medium-dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FE', + u':couple_with_heart_woman_man_medium-dark_skin_tone_dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FF', + u':couple_with_heart_woman_man_medium-dark_skin_tone_light_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FB', + u':couple_with_heart_woman_man_medium-dark_skin_tone_medium-light_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FC', + u':couple_with_heart_woman_man_medium-dark_skin_tone_medium_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FD', + u':couple_with_heart_woman_man_medium-light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FC', + u':couple_with_heart_woman_man_medium-light_skin_tone_dark_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FF', + u':couple_with_heart_woman_man_medium-light_skin_tone_light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FB', + u':couple_with_heart_woman_man_medium-light_skin_tone_medium-dark_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FE', + u':couple_with_heart_woman_man_medium-light_skin_tone_medium_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FD', + u':couple_with_heart_woman_man_medium_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FD', + u':couple_with_heart_woman_man_medium_skin_tone_dark_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FF', + u':couple_with_heart_woman_man_medium_skin_tone_light_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FB', + u':couple_with_heart_woman_man_medium_skin_tone_medium-dark_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FE', + u':couple_with_heart_woman_man_medium_skin_tone_medium-light_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F468\U0001F3FC', + u':couple_with_heart_woman_woman:': u'\U0001F469\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F469', + u':couple_with_heart_woman_woman_dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F469\U0001F3FF', + u':couple_with_heart_woman_woman_dark_skin_tone_light_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F469\U0001F3FB', + u':couple_with_heart_woman_woman_dark_skin_tone_medium-dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F469\U0001F3FE', + u':couple_with_heart_woman_woman_dark_skin_tone_medium-light_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F469\U0001F3FC', + u':couple_with_heart_woman_woman_dark_skin_tone_medium_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F469\U0001F3FD', + u':couple_with_heart_woman_woman_light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F469\U0001F3FB', + u':couple_with_heart_woman_woman_light_skin_tone_dark_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F469\U0001F3FF', + u':couple_with_heart_woman_woman_light_skin_tone_medium-dark_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F469\U0001F3FE', + u':couple_with_heart_woman_woman_light_skin_tone_medium-light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F469\U0001F3FC', + u':couple_with_heart_woman_woman_light_skin_tone_medium_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F469\U0001F3FD', + u':couple_with_heart_woman_woman_medium-dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F469\U0001F3FE', + u':couple_with_heart_woman_woman_medium-dark_skin_tone_dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F469\U0001F3FF', + u':couple_with_heart_woman_woman_medium-dark_skin_tone_light_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F469\U0001F3FB', + u':couple_with_heart_woman_woman_medium-dark_skin_tone_medium-light_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F469\U0001F3FC', + u':couple_with_heart_woman_woman_medium-dark_skin_tone_medium_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F469\U0001F3FD', + u':couple_with_heart_woman_woman_medium-light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F469\U0001F3FC', + u':couple_with_heart_woman_woman_medium-light_skin_tone_dark_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F469\U0001F3FF', + u':couple_with_heart_woman_woman_medium-light_skin_tone_light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F469\U0001F3FB', + u':couple_with_heart_woman_woman_medium-light_skin_tone_medium-dark_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F469\U0001F3FE', + u':couple_with_heart_woman_woman_medium-light_skin_tone_medium_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F469\U0001F3FD', + u':couple_with_heart_woman_woman_medium_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F469\U0001F3FD', + u':couple_with_heart_woman_woman_medium_skin_tone_dark_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F469\U0001F3FF', + u':couple_with_heart_woman_woman_medium_skin_tone_light_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F469\U0001F3FB', + u':couple_with_heart_woman_woman_medium_skin_tone_medium-dark_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F469\U0001F3FE', + u':couple_with_heart_woman_woman_medium_skin_tone_medium-light_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F469\U0001F3FC', + u':cow:': u'\U0001F404', + u':cow_face:': u'\U0001F42E', + u':cowboy_hat_face:': u'\U0001F920', + u':crab:': u'\U0001F980', + u':crayon:': u'\U0001F58D', + u':credit_card:': u'\U0001F4B3', + u':crescent_moon:': u'\U0001F319', + u':cricket:': u'\U0001F997', + u':cricket_game:': u'\U0001F3CF', + u':crocodile:': u'\U0001F40A', + u':croissant:': u'\U0001F950', + u':cross_mark:': u'\U0000274C', + u':cross_mark_button:': u'\U0000274E', + u':crossed_fingers:': u'\U0001F91E', + u':crossed_fingers_dark_skin_tone:': u'\U0001F91E\U0001F3FF', + u':crossed_fingers_light_skin_tone:': u'\U0001F91E\U0001F3FB', + u':crossed_fingers_medium-dark_skin_tone:': u'\U0001F91E\U0001F3FE', + u':crossed_fingers_medium-light_skin_tone:': u'\U0001F91E\U0001F3FC', + u':crossed_fingers_medium_skin_tone:': u'\U0001F91E\U0001F3FD', + u':crossed_flags:': u'\U0001F38C', + u':crossed_swords:': u'\U00002694', + u':crown:': u'\U0001F451', + u':crying_cat:': u'\U0001F63F', + u':crying_face:': u'\U0001F622', + u':crystal_ball:': u'\U0001F52E', + u':cucumber:': u'\U0001F952', + u':cup_with_straw:': u'\U0001F964', + u':cupcake:': u'\U0001F9C1', + u':curling_stone:': u'\U0001F94C', + u':curly_hair:': u'\U0001F9B1', + u':curly_loop:': u'\U000027B0', + u':currency_exchange:': u'\U0001F4B1', + u':curry_rice:': u'\U0001F35B', + u':custard:': u'\U0001F36E', + u':customs:': u'\U0001F6C3', + u':cut_of_meat:': u'\U0001F969', + u':cyclone:': u'\U0001F300', + u':dagger:': u'\U0001F5E1', + u':dango:': u'\U0001F361', + u':dark_skin_tone:': u'\U0001F3FF', + u':dashing_away:': u'\U0001F4A8', + u':deaf_man:': u'\U0001F9CF\U0000200D\U00002642\U0000FE0F', + u':deaf_man_dark_skin_tone:': u'\U0001F9CF\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':deaf_man_light_skin_tone:': u'\U0001F9CF\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':deaf_man_medium-dark_skin_tone:': u'\U0001F9CF\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':deaf_man_medium-light_skin_tone:': u'\U0001F9CF\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':deaf_man_medium_skin_tone:': u'\U0001F9CF\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':deaf_person:': u'\U0001F9CF', + u':deaf_person_dark_skin_tone:': u'\U0001F9CF\U0001F3FF', + u':deaf_person_light_skin_tone:': u'\U0001F9CF\U0001F3FB', + u':deaf_person_medium-dark_skin_tone:': u'\U0001F9CF\U0001F3FE', + u':deaf_person_medium-light_skin_tone:': u'\U0001F9CF\U0001F3FC', + u':deaf_person_medium_skin_tone:': u'\U0001F9CF\U0001F3FD', + u':deaf_woman:': u'\U0001F9CF\U0000200D\U00002640\U0000FE0F', + u':deaf_woman_dark_skin_tone:': u'\U0001F9CF\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':deaf_woman_light_skin_tone:': u'\U0001F9CF\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':deaf_woman_medium-dark_skin_tone:': u'\U0001F9CF\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':deaf_woman_medium-light_skin_tone:': u'\U0001F9CF\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':deaf_woman_medium_skin_tone:': u'\U0001F9CF\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':deciduous_tree:': u'\U0001F333', + u':deer:': u'\U0001F98C', + u':delivery_truck:': u'\U0001F69A', + u':department_store:': u'\U0001F3EC', + u':derelict_house:': u'\U0001F3DA', + u':desert:': u'\U0001F3DC', + u':desert_island:': u'\U0001F3DD', + u':desktop_computer:': u'\U0001F5A5', + u':detective:': u'\U0001F575', + u':detective_dark_skin_tone:': u'\U0001F575\U0001F3FF', + u':detective_light_skin_tone:': u'\U0001F575\U0001F3FB', + u':detective_medium-dark_skin_tone:': u'\U0001F575\U0001F3FE', + u':detective_medium-light_skin_tone:': u'\U0001F575\U0001F3FC', + u':detective_medium_skin_tone:': u'\U0001F575\U0001F3FD', + u':diamond_suit:': u'\U00002666', + u':diamond_with_a_dot:': u'\U0001F4A0', + u':dim_button:': u'\U0001F505', + u':disappointed_face:': u'\U0001F61E', + u':disguised_face:': u'\U0001F978', + u':divide:': u'\U00002797', + u':diving_mask:': u'\U0001F93F', + u':diya_lamp:': u'\U0001FA94', + u':dizzy:': u'\U0001F4AB', + u':dna:': u'\U0001F9EC', + u':dodo:': u'\U0001F9A4', + u':dog:': u'\U0001F415', + u':dog_face:': u'\U0001F436', + u':dollar_banknote:': u'\U0001F4B5', + u':dolphin:': u'\U0001F42C', + u':door:': u'\U0001F6AA', + u':dotted_six-pointed_star:': u'\U0001F52F', + u':double_curly_loop:': u'\U000027BF', + u':double_exclamation_mark:': u'\U0000203C', + u':doughnut:': u'\U0001F369', + u':dove:': u'\U0001F54A', + u':down-left_arrow:': u'\U00002199', + u':down-right_arrow:': u'\U00002198', + u':down_arrow:': u'\U00002B07', + u':downcast_face_with_sweat:': u'\U0001F613', + u':downwards_button:': u'\U0001F53D', + u':dragon:': u'\U0001F409', + u':dragon_face:': u'\U0001F432', + u':dress:': u'\U0001F457', + u':drooling_face:': u'\U0001F924', + u':drop_of_blood:': u'\U0001FA78', + u':droplet:': u'\U0001F4A7', + u':drum:': u'\U0001F941', + u':duck:': u'\U0001F986', + u':dumpling:': u'\U0001F95F', + u':dvd:': u'\U0001F4C0', + u':e-mail:': u'\U0001F4E7', + u':eagle:': u'\U0001F985', + u':ear:': u'\U0001F442', + u':ear_dark_skin_tone:': u'\U0001F442\U0001F3FF', + u':ear_light_skin_tone:': u'\U0001F442\U0001F3FB', + u':ear_medium-dark_skin_tone:': u'\U0001F442\U0001F3FE', + u':ear_medium-light_skin_tone:': u'\U0001F442\U0001F3FC', + u':ear_medium_skin_tone:': u'\U0001F442\U0001F3FD', + u':ear_of_corn:': u'\U0001F33D', + u':ear_with_hearing_aid:': u'\U0001F9BB', + u':ear_with_hearing_aid_dark_skin_tone:': u'\U0001F9BB\U0001F3FF', + u':ear_with_hearing_aid_light_skin_tone:': u'\U0001F9BB\U0001F3FB', + u':ear_with_hearing_aid_medium-dark_skin_tone:': u'\U0001F9BB\U0001F3FE', + u':ear_with_hearing_aid_medium-light_skin_tone:': u'\U0001F9BB\U0001F3FC', + u':ear_with_hearing_aid_medium_skin_tone:': u'\U0001F9BB\U0001F3FD', + u':egg:': u'\U0001F95A', + u':eggplant:': u'\U0001F346', + u':eight-pointed_star:': u'\U00002734', + u':eight-spoked_asterisk:': u'\U00002733', + u':eight-thirty:': u'\U0001F563', + u':eight_o’clock:': u'\U0001F557', + u':eject_button:': u'\U000023CF', + u':electric_plug:': u'\U0001F50C', + u':elephant:': u'\U0001F418', + u':elevator:': u'\U0001F6D7', + u':eleven-thirty:': u'\U0001F566', + u':eleven_o’clock:': u'\U0001F55A', + u':elf:': u'\U0001F9DD', + u':elf_dark_skin_tone:': u'\U0001F9DD\U0001F3FF', + u':elf_light_skin_tone:': u'\U0001F9DD\U0001F3FB', + u':elf_medium-dark_skin_tone:': u'\U0001F9DD\U0001F3FE', + u':elf_medium-light_skin_tone:': u'\U0001F9DD\U0001F3FC', + u':elf_medium_skin_tone:': u'\U0001F9DD\U0001F3FD', + u':envelope:': u'\U00002709', + u':envelope_with_arrow:': u'\U0001F4E9', + u':euro_banknote:': u'\U0001F4B6', + u':evergreen_tree:': u'\U0001F332', + u':ewe:': u'\U0001F411', + u':exclamation_question_mark:': u'\U00002049', + u':exploding_head:': u'\U0001F92F', + u':expressionless_face:': u'\U0001F611', + u':eye:': u'\U0001F441', + u':eye_in_speech_bubble:': u'\U0001F441\U0000FE0F\U0000200D\U0001F5E8\U0000FE0F', + u':eyes:': u'\U0001F440', + u':face_blowing_a_kiss:': u'\U0001F618', + u':face_exhaling:': u'\U0001F62E\U0000200D\U0001F4A8', + u':face_in_clouds:': u'\U0001F636\U0000200D\U0001F32B\U0000FE0F', + u':face_savoring_food:': u'\U0001F60B', + u':face_screaming_in_fear:': u'\U0001F631', + u':face_vomiting:': u'\U0001F92E', + u':face_with_hand_over_mouth:': u'\U0001F92D', + u':face_with_head-bandage:': u'\U0001F915', + u':face_with_medical_mask:': u'\U0001F637', + u':face_with_monocle:': u'\U0001F9D0', + u':face_with_open_mouth:': u'\U0001F62E', + u':face_with_raised_eyebrow:': u'\U0001F928', + u':face_with_rolling_eyes:': u'\U0001F644', + u':face_with_spiral_eyes:': u'\U0001F635\U0000200D\U0001F4AB', + u':face_with_steam_from_nose:': u'\U0001F624', + u':face_with_symbols_on_mouth:': u'\U0001F92C', + u':face_with_tears_of_joy:': u'\U0001F602', + u':face_with_thermometer:': u'\U0001F912', + u':face_with_tongue:': u'\U0001F61B', + u':face_without_mouth:': u'\U0001F636', + u':factory:': u'\U0001F3ED', + u':factory_worker:': u'\U0001F9D1\U0000200D\U0001F3ED', + u':factory_worker_dark_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F3ED', + u':factory_worker_light_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F3ED', + u':factory_worker_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F3ED', + u':factory_worker_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F3ED', + u':factory_worker_medium_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F3ED', + u':fairy:': u'\U0001F9DA', + u':fairy_dark_skin_tone:': u'\U0001F9DA\U0001F3FF', + u':fairy_light_skin_tone:': u'\U0001F9DA\U0001F3FB', + u':fairy_medium-dark_skin_tone:': u'\U0001F9DA\U0001F3FE', + u':fairy_medium-light_skin_tone:': u'\U0001F9DA\U0001F3FC', + u':fairy_medium_skin_tone:': u'\U0001F9DA\U0001F3FD', + u':falafel:': u'\U0001F9C6', + u':fallen_leaf:': u'\U0001F342', + u':family:': u'\U0001F46A', + u':family_man_boy:': u'\U0001F468\U0000200D\U0001F466', + u':family_man_boy_boy:': u'\U0001F468\U0000200D\U0001F466\U0000200D\U0001F466', + u':family_man_girl:': u'\U0001F468\U0000200D\U0001F467', + u':family_man_girl_boy:': u'\U0001F468\U0000200D\U0001F467\U0000200D\U0001F466', + u':family_man_girl_girl:': u'\U0001F468\U0000200D\U0001F467\U0000200D\U0001F467', + u':family_man_man_boy:': u'\U0001F468\U0000200D\U0001F468\U0000200D\U0001F466', + u':family_man_man_boy_boy:': u'\U0001F468\U0000200D\U0001F468\U0000200D\U0001F466\U0000200D\U0001F466', + u':family_man_man_girl:': u'\U0001F468\U0000200D\U0001F468\U0000200D\U0001F467', + u':family_man_man_girl_boy:': u'\U0001F468\U0000200D\U0001F468\U0000200D\U0001F467\U0000200D\U0001F466', + u':family_man_man_girl_girl:': u'\U0001F468\U0000200D\U0001F468\U0000200D\U0001F467\U0000200D\U0001F467', + u':family_man_woman_boy:': u'\U0001F468\U0000200D\U0001F469\U0000200D\U0001F466', + u':family_man_woman_boy_boy:': u'\U0001F468\U0000200D\U0001F469\U0000200D\U0001F466\U0000200D\U0001F466', + u':family_man_woman_girl:': u'\U0001F468\U0000200D\U0001F469\U0000200D\U0001F467', + u':family_man_woman_girl_boy:': u'\U0001F468\U0000200D\U0001F469\U0000200D\U0001F467\U0000200D\U0001F466', + u':family_man_woman_girl_girl:': u'\U0001F468\U0000200D\U0001F469\U0000200D\U0001F467\U0000200D\U0001F467', + u':family_woman_boy:': u'\U0001F469\U0000200D\U0001F466', + u':family_woman_boy_boy:': u'\U0001F469\U0000200D\U0001F466\U0000200D\U0001F466', + u':family_woman_girl:': u'\U0001F469\U0000200D\U0001F467', + u':family_woman_girl_boy:': u'\U0001F469\U0000200D\U0001F467\U0000200D\U0001F466', + u':family_woman_girl_girl:': u'\U0001F469\U0000200D\U0001F467\U0000200D\U0001F467', + u':family_woman_woman_boy:': u'\U0001F469\U0000200D\U0001F469\U0000200D\U0001F466', + u':family_woman_woman_boy_boy:': u'\U0001F469\U0000200D\U0001F469\U0000200D\U0001F466\U0000200D\U0001F466', + u':family_woman_woman_girl:': u'\U0001F469\U0000200D\U0001F469\U0000200D\U0001F467', + u':family_woman_woman_girl_boy:': u'\U0001F469\U0000200D\U0001F469\U0000200D\U0001F467\U0000200D\U0001F466', + u':family_woman_woman_girl_girl:': u'\U0001F469\U0000200D\U0001F469\U0000200D\U0001F467\U0000200D\U0001F467', + u':farmer:': u'\U0001F9D1\U0000200D\U0001F33E', + u':farmer_dark_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F33E', + u':farmer_light_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F33E', + u':farmer_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F33E', + u':farmer_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F33E', + u':farmer_medium_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F33E', + u':fast-forward_button:': u'\U000023E9', + u':fast_down_button:': u'\U000023EC', + u':fast_reverse_button:': u'\U000023EA', + u':fast_up_button:': u'\U000023EB', + u':fax_machine:': u'\U0001F4E0', + u':fearful_face:': u'\U0001F628', + u':feather:': u'\U0001FAB6', + u':female_sign:': u'\U00002640', + u':ferris_wheel:': u'\U0001F3A1', + u':ferry:': u'\U000026F4', + u':field_hockey:': u'\U0001F3D1', + u':file_cabinet:': u'\U0001F5C4', + u':file_folder:': u'\U0001F4C1', + u':film_frames:': u'\U0001F39E', + u':film_projector:': u'\U0001F4FD', + u':fire:': u'\U0001F525', + u':fire_engine:': u'\U0001F692', + u':fire_extinguisher:': u'\U0001F9EF', + u':firecracker:': u'\U0001F9E8', + u':firefighter:': u'\U0001F9D1\U0000200D\U0001F692', + u':firefighter_dark_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F692', + u':firefighter_light_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F692', + u':firefighter_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F692', + u':firefighter_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F692', + u':firefighter_medium_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F692', + u':fireworks:': u'\U0001F386', + u':first_quarter_moon:': u'\U0001F313', + u':first_quarter_moon_face:': u'\U0001F31B', + u':fish:': u'\U0001F41F', + u':fish_cake_with_swirl:': u'\U0001F365', + u':fishing_pole:': u'\U0001F3A3', + u':five-thirty:': u'\U0001F560', + u':five_o’clock:': u'\U0001F554', + u':flag_in_hole:': u'\U000026F3', + u':flamingo:': u'\U0001F9A9', + u':flashlight:': u'\U0001F526', + u':flat_shoe:': u'\U0001F97F', + u':flatbread:': u'\U0001FAD3', + u':fleur-de-lis:': u'\U0000269C', + u':flexed_biceps:': u'\U0001F4AA', + u':flexed_biceps_dark_skin_tone:': u'\U0001F4AA\U0001F3FF', + u':flexed_biceps_light_skin_tone:': u'\U0001F4AA\U0001F3FB', + u':flexed_biceps_medium-dark_skin_tone:': u'\U0001F4AA\U0001F3FE', + u':flexed_biceps_medium-light_skin_tone:': u'\U0001F4AA\U0001F3FC', + u':flexed_biceps_medium_skin_tone:': u'\U0001F4AA\U0001F3FD', + u':floppy_disk:': u'\U0001F4BE', + u':flower_playing_cards:': u'\U0001F3B4', + u':flushed_face:': u'\U0001F633', + u':fly:': u'\U0001FAB0', + u':flying_disc:': u'\U0001F94F', + u':flying_saucer:': u'\U0001F6F8', + u':fog:': u'\U0001F32B', + u':foggy:': u'\U0001F301', + u':folded_hands:': u'\U0001F64F', + u':folded_hands_dark_skin_tone:': u'\U0001F64F\U0001F3FF', + u':folded_hands_light_skin_tone:': u'\U0001F64F\U0001F3FB', + u':folded_hands_medium-dark_skin_tone:': u'\U0001F64F\U0001F3FE', + u':folded_hands_medium-light_skin_tone:': u'\U0001F64F\U0001F3FC', + u':folded_hands_medium_skin_tone:': u'\U0001F64F\U0001F3FD', + u':fondue:': u'\U0001FAD5', + u':foot:': u'\U0001F9B6', + u':foot_dark_skin_tone:': u'\U0001F9B6\U0001F3FF', + u':foot_light_skin_tone:': u'\U0001F9B6\U0001F3FB', + u':foot_medium-dark_skin_tone:': u'\U0001F9B6\U0001F3FE', + u':foot_medium-light_skin_tone:': u'\U0001F9B6\U0001F3FC', + u':foot_medium_skin_tone:': u'\U0001F9B6\U0001F3FD', + u':footprints:': u'\U0001F463', + u':fork_and_knife:': u'\U0001F374', + u':fork_and_knife_with_plate:': u'\U0001F37D', + u':fortune_cookie:': u'\U0001F960', + u':fountain:': u'\U000026F2', + u':fountain_pen:': u'\U0001F58B', + u':four-thirty:': u'\U0001F55F', + u':four_leaf_clover:': u'\U0001F340', + u':four_o’clock:': u'\U0001F553', + u':fox:': u'\U0001F98A', + u':framed_picture:': u'\U0001F5BC', + u':french_fries:': u'\U0001F35F', + u':fried_shrimp:': u'\U0001F364', + u':frog:': u'\U0001F438', + u':front-facing_baby_chick:': u'\U0001F425', + u':frowning_face:': u'\U00002639', + u':frowning_face_with_open_mouth:': u'\U0001F626', + u':fuel_pump:': u'\U000026FD', + u':full_moon:': u'\U0001F315', + u':full_moon_face:': u'\U0001F31D', + u':funeral_urn:': u'\U000026B1', + u':game_die:': u'\U0001F3B2', + u':garlic:': u'\U0001F9C4', + u':gear:': u'\U00002699', + u':gem_stone:': u'\U0001F48E', + u':genie:': u'\U0001F9DE', + u':ghost:': u'\U0001F47B', + u':giraffe:': u'\U0001F992', + u':girl:': u'\U0001F467', + u':girl_dark_skin_tone:': u'\U0001F467\U0001F3FF', + u':girl_light_skin_tone:': u'\U0001F467\U0001F3FB', + u':girl_medium-dark_skin_tone:': u'\U0001F467\U0001F3FE', + u':girl_medium-light_skin_tone:': u'\U0001F467\U0001F3FC', + u':girl_medium_skin_tone:': u'\U0001F467\U0001F3FD', + u':glass_of_milk:': u'\U0001F95B', + u':glasses:': u'\U0001F453', + u':globe_showing_Americas:': u'\U0001F30E', + u':globe_showing_Asia-Australia:': u'\U0001F30F', + u':globe_showing_Europe-Africa:': u'\U0001F30D', + u':globe_with_meridians:': u'\U0001F310', + u':gloves:': u'\U0001F9E4', + u':glowing_star:': u'\U0001F31F', + u':goal_net:': u'\U0001F945', + u':goat:': u'\U0001F410', + u':goblin:': u'\U0001F47A', + u':goggles:': u'\U0001F97D', + u':gorilla:': u'\U0001F98D', + u':graduation_cap:': u'\U0001F393', + u':grapes:': u'\U0001F347', + u':green_apple:': u'\U0001F34F', + u':green_book:': u'\U0001F4D7', + u':green_circle:': u'\U0001F7E2', + u':green_heart:': u'\U0001F49A', + u':green_salad:': u'\U0001F957', + u':green_square:': u'\U0001F7E9', + u':grimacing_face:': u'\U0001F62C', + u':grinning_cat:': u'\U0001F63A', + u':grinning_cat_with_smiling_eyes:': u'\U0001F638', + u':grinning_face:': u'\U0001F600', + u':grinning_face_with_big_eyes:': u'\U0001F603', + u':grinning_face_with_smiling_eyes:': u'\U0001F604', + u':grinning_face_with_sweat:': u'\U0001F605', + u':grinning_squinting_face:': u'\U0001F606', + u':growing_heart:': u'\U0001F497', + u':guard:': u'\U0001F482', + u':guard_dark_skin_tone:': u'\U0001F482\U0001F3FF', + u':guard_light_skin_tone:': u'\U0001F482\U0001F3FB', + u':guard_medium-dark_skin_tone:': u'\U0001F482\U0001F3FE', + u':guard_medium-light_skin_tone:': u'\U0001F482\U0001F3FC', + u':guard_medium_skin_tone:': u'\U0001F482\U0001F3FD', + u':guide_dog:': u'\U0001F9AE', + u':guitar:': u'\U0001F3B8', + u':hamburger:': u'\U0001F354', + u':hammer:': u'\U0001F528', + u':hammer_and_pick:': u'\U00002692', + u':hammer_and_wrench:': u'\U0001F6E0', + u':hamster:': u'\U0001F439', + u':hand_with_fingers_splayed:': u'\U0001F590', + u':hand_with_fingers_splayed_dark_skin_tone:': u'\U0001F590\U0001F3FF', + u':hand_with_fingers_splayed_light_skin_tone:': u'\U0001F590\U0001F3FB', + u':hand_with_fingers_splayed_medium-dark_skin_tone:': u'\U0001F590\U0001F3FE', + u':hand_with_fingers_splayed_medium-light_skin_tone:': u'\U0001F590\U0001F3FC', + u':hand_with_fingers_splayed_medium_skin_tone:': u'\U0001F590\U0001F3FD', + u':handbag:': u'\U0001F45C', + u':handshake:': u'\U0001F91D', + u':hatching_chick:': u'\U0001F423', + u':headphone:': u'\U0001F3A7', + u':headstone:': u'\U0001FAA6', + u':health_worker:': u'\U0001F9D1\U0000200D\U00002695\U0000FE0F', + u':health_worker_dark_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U00002695\U0000FE0F', + u':health_worker_light_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U00002695\U0000FE0F', + u':health_worker_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U00002695\U0000FE0F', + u':health_worker_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U00002695\U0000FE0F', + u':health_worker_medium_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U00002695\U0000FE0F', + u':hear-no-evil_monkey:': u'\U0001F649', + u':heart_decoration:': u'\U0001F49F', + u':heart_exclamation:': u'\U00002763', + u':heart_on_fire:': u'\U00002764\U0000FE0F\U0000200D\U0001F525', + u':heart_suit:': u'\U00002665', + u':heart_with_arrow:': u'\U0001F498', + u':heart_with_ribbon:': u'\U0001F49D', + u':heavy_dollar_sign:': u'\U0001F4B2', + u':hedgehog:': u'\U0001F994', + u':helicopter:': u'\U0001F681', + u':herb:': u'\U0001F33F', + u':hibiscus:': u'\U0001F33A', + u':high-heeled_shoe:': u'\U0001F460', + u':high-speed_train:': u'\U0001F684', + u':high_voltage:': u'\U000026A1', + u':hiking_boot:': u'\U0001F97E', + u':hindu_temple:': u'\U0001F6D5', + u':hippopotamus:': u'\U0001F99B', + u':hole:': u'\U0001F573', + u':hollow_red_circle:': u'\U00002B55', + u':honey_pot:': u'\U0001F36F', + u':honeybee:': u'\U0001F41D', + u':hook:': u'\U0001FA9D', + u':horizontal_traffic_light:': u'\U0001F6A5', + u':horse:': u'\U0001F40E', + u':horse_face:': u'\U0001F434', + u':horse_racing:': u'\U0001F3C7', + u':horse_racing_dark_skin_tone:': u'\U0001F3C7\U0001F3FF', + u':horse_racing_light_skin_tone:': u'\U0001F3C7\U0001F3FB', + u':horse_racing_medium-dark_skin_tone:': u'\U0001F3C7\U0001F3FE', + u':horse_racing_medium-light_skin_tone:': u'\U0001F3C7\U0001F3FC', + u':horse_racing_medium_skin_tone:': u'\U0001F3C7\U0001F3FD', + u':hospital:': u'\U0001F3E5', + u':hot_beverage:': u'\U00002615', + u':hot_dog:': u'\U0001F32D', + u':hot_face:': u'\U0001F975', + u':hot_pepper:': u'\U0001F336', + u':hot_springs:': u'\U00002668', + u':hotel:': u'\U0001F3E8', + u':hourglass_done:': u'\U0000231B', + u':hourglass_not_done:': u'\U000023F3', + u':house:': u'\U0001F3E0', + u':house_with_garden:': u'\U0001F3E1', + u':houses:': u'\U0001F3D8', + u':hugging_face:': u'\U0001F917', + u':hundred_points:': u'\U0001F4AF', + u':hushed_face:': u'\U0001F62F', + u':hut:': u'\U0001F6D6', + u':ice:': u'\U0001F9CA', + u':ice_cream:': u'\U0001F368', + u':ice_hockey:': u'\U0001F3D2', + u':ice_skate:': u'\U000026F8', + u':inbox_tray:': u'\U0001F4E5', + u':incoming_envelope:': u'\U0001F4E8', + u':index_pointing_up:': u'\U0000261D', + u':index_pointing_up_dark_skin_tone:': u'\U0000261D\U0001F3FF', + u':index_pointing_up_light_skin_tone:': u'\U0000261D\U0001F3FB', + u':index_pointing_up_medium-dark_skin_tone:': u'\U0000261D\U0001F3FE', + u':index_pointing_up_medium-light_skin_tone:': u'\U0000261D\U0001F3FC', + u':index_pointing_up_medium_skin_tone:': u'\U0000261D\U0001F3FD', + u':infinity:': u'\U0000267E', + u':information:': u'\U00002139', + u':input_latin_letters:': u'\U0001F524', + u':input_latin_lowercase:': u'\U0001F521', + u':input_latin_uppercase:': u'\U0001F520', + u':input_numbers:': u'\U0001F522', + u':input_symbols:': u'\U0001F523', + u':jack-o-lantern:': u'\U0001F383', + u':jeans:': u'\U0001F456', + u':joker:': u'\U0001F0CF', + u':joystick:': u'\U0001F579', + u':judge:': u'\U0001F9D1\U0000200D\U00002696\U0000FE0F', + u':judge_dark_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U00002696\U0000FE0F', + u':judge_light_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U00002696\U0000FE0F', + u':judge_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U00002696\U0000FE0F', + u':judge_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U00002696\U0000FE0F', + u':judge_medium_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U00002696\U0000FE0F', + u':kaaba:': u'\U0001F54B', + u':kangaroo:': u'\U0001F998', + u':key:': u'\U0001F511', + u':keyboard:': u'\U00002328', + u':keycap_#:': u'\U00000023\U0000FE0F\U000020E3', + u':keycap_*:': u'\U0000002A\U0000FE0F\U000020E3', + u':keycap_0:': u'\U00000030\U0000FE0F\U000020E3', + u':keycap_1:': u'\U00000031\U0000FE0F\U000020E3', + u':keycap_10:': u'\U0001F51F', + u':keycap_2:': u'\U00000032\U0000FE0F\U000020E3', + u':keycap_3:': u'\U00000033\U0000FE0F\U000020E3', + u':keycap_4:': u'\U00000034\U0000FE0F\U000020E3', + u':keycap_5:': u'\U00000035\U0000FE0F\U000020E3', + u':keycap_6:': u'\U00000036\U0000FE0F\U000020E3', + u':keycap_7:': u'\U00000037\U0000FE0F\U000020E3', + u':keycap_8:': u'\U00000038\U0000FE0F\U000020E3', + u':keycap_9:': u'\U00000039\U0000FE0F\U000020E3', + u':kick_scooter:': u'\U0001F6F4', + u':kimono:': u'\U0001F458', + u':kiss:': u'\U0001F48F', + u':kiss_dark_skin_tone:': u'\U0001F48F\U0001F3FF', + u':kiss_light_skin_tone:': u'\U0001F48F\U0001F3FB', + u':kiss_man_man:': u'\U0001F468\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468', + u':kiss_man_man_dark_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FF', + u':kiss_man_man_dark_skin_tone_light_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FB', + u':kiss_man_man_dark_skin_tone_medium-dark_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FE', + u':kiss_man_man_dark_skin_tone_medium-light_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FC', + u':kiss_man_man_dark_skin_tone_medium_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FD', + u':kiss_man_man_light_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FB', + u':kiss_man_man_light_skin_tone_dark_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FF', + u':kiss_man_man_light_skin_tone_medium-dark_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FE', + u':kiss_man_man_light_skin_tone_medium-light_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FC', + u':kiss_man_man_light_skin_tone_medium_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FD', + u':kiss_man_man_medium-dark_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FE', + u':kiss_man_man_medium-dark_skin_tone_dark_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FF', + u':kiss_man_man_medium-dark_skin_tone_light_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FB', + u':kiss_man_man_medium-dark_skin_tone_medium-light_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FC', + u':kiss_man_man_medium-dark_skin_tone_medium_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FD', + u':kiss_man_man_medium-light_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FC', + u':kiss_man_man_medium-light_skin_tone_dark_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FF', + u':kiss_man_man_medium-light_skin_tone_light_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FB', + u':kiss_man_man_medium-light_skin_tone_medium-dark_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FE', + u':kiss_man_man_medium-light_skin_tone_medium_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FD', + u':kiss_man_man_medium_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FD', + u':kiss_man_man_medium_skin_tone_dark_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FF', + u':kiss_man_man_medium_skin_tone_light_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FB', + u':kiss_man_man_medium_skin_tone_medium-dark_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FE', + u':kiss_man_man_medium_skin_tone_medium-light_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FC', + u':kiss_mark:': u'\U0001F48B', + u':kiss_medium-dark_skin_tone:': u'\U0001F48F\U0001F3FE', + u':kiss_medium-light_skin_tone:': u'\U0001F48F\U0001F3FC', + u':kiss_medium_skin_tone:': u'\U0001F48F\U0001F3FD', + u':kiss_person_person_dark_skin_tone_light_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F9D1\U0001F3FB', + u':kiss_person_person_dark_skin_tone_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F9D1\U0001F3FE', + u':kiss_person_person_dark_skin_tone_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F9D1\U0001F3FC', + u':kiss_person_person_dark_skin_tone_medium_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F9D1\U0001F3FD', + u':kiss_person_person_light_skin_tone_dark_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F9D1\U0001F3FF', + u':kiss_person_person_light_skin_tone_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F9D1\U0001F3FE', + u':kiss_person_person_light_skin_tone_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F9D1\U0001F3FC', + u':kiss_person_person_light_skin_tone_medium_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F9D1\U0001F3FD', + u':kiss_person_person_medium-dark_skin_tone_dark_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F9D1\U0001F3FF', + u':kiss_person_person_medium-dark_skin_tone_light_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F9D1\U0001F3FB', + u':kiss_person_person_medium-dark_skin_tone_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F9D1\U0001F3FC', + u':kiss_person_person_medium-dark_skin_tone_medium_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F9D1\U0001F3FD', + u':kiss_person_person_medium-light_skin_tone_dark_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F9D1\U0001F3FF', + u':kiss_person_person_medium-light_skin_tone_light_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F9D1\U0001F3FB', + u':kiss_person_person_medium-light_skin_tone_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F9D1\U0001F3FE', + u':kiss_person_person_medium-light_skin_tone_medium_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F9D1\U0001F3FD', + u':kiss_person_person_medium_skin_tone_dark_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F9D1\U0001F3FF', + u':kiss_person_person_medium_skin_tone_light_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F9D1\U0001F3FB', + u':kiss_person_person_medium_skin_tone_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F9D1\U0001F3FE', + u':kiss_person_person_medium_skin_tone_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F9D1\U0001F3FC', + u':kiss_woman_man:': u'\U0001F469\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468', + u':kiss_woman_man_dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FF', + u':kiss_woman_man_dark_skin_tone_light_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FB', + u':kiss_woman_man_dark_skin_tone_medium-dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FE', + u':kiss_woman_man_dark_skin_tone_medium-light_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FC', + u':kiss_woman_man_dark_skin_tone_medium_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FD', + u':kiss_woman_man_light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FB', + u':kiss_woman_man_light_skin_tone_dark_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FF', + u':kiss_woman_man_light_skin_tone_medium-dark_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FE', + u':kiss_woman_man_light_skin_tone_medium-light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FC', + u':kiss_woman_man_light_skin_tone_medium_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FD', + u':kiss_woman_man_medium-dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FE', + u':kiss_woman_man_medium-dark_skin_tone_dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FF', + u':kiss_woman_man_medium-dark_skin_tone_light_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FB', + u':kiss_woman_man_medium-dark_skin_tone_medium-light_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FC', + u':kiss_woman_man_medium-dark_skin_tone_medium_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FD', + u':kiss_woman_man_medium-light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FC', + u':kiss_woman_man_medium-light_skin_tone_dark_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FF', + u':kiss_woman_man_medium-light_skin_tone_light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FB', + u':kiss_woman_man_medium-light_skin_tone_medium-dark_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FE', + u':kiss_woman_man_medium-light_skin_tone_medium_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FD', + u':kiss_woman_man_medium_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FD', + u':kiss_woman_man_medium_skin_tone_dark_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FF', + u':kiss_woman_man_medium_skin_tone_light_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FB', + u':kiss_woman_man_medium_skin_tone_medium-dark_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FE', + u':kiss_woman_man_medium_skin_tone_medium-light_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FC', + u':kiss_woman_woman:': u'\U0001F469\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F469', + u':kiss_woman_woman_dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F469\U0001F3FF', + u':kiss_woman_woman_dark_skin_tone_light_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F469\U0001F3FB', + u':kiss_woman_woman_dark_skin_tone_medium-dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F469\U0001F3FE', + u':kiss_woman_woman_dark_skin_tone_medium-light_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F469\U0001F3FC', + u':kiss_woman_woman_dark_skin_tone_medium_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F469\U0001F3FD', + u':kiss_woman_woman_light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F469\U0001F3FB', + u':kiss_woman_woman_light_skin_tone_dark_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F469\U0001F3FF', + u':kiss_woman_woman_light_skin_tone_medium-dark_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F469\U0001F3FE', + u':kiss_woman_woman_light_skin_tone_medium-light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F469\U0001F3FC', + u':kiss_woman_woman_light_skin_tone_medium_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F469\U0001F3FD', + u':kiss_woman_woman_medium-dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F469\U0001F3FE', + u':kiss_woman_woman_medium-dark_skin_tone_dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F469\U0001F3FF', + u':kiss_woman_woman_medium-dark_skin_tone_light_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F469\U0001F3FB', + u':kiss_woman_woman_medium-dark_skin_tone_medium-light_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F469\U0001F3FC', + u':kiss_woman_woman_medium-dark_skin_tone_medium_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F469\U0001F3FD', + u':kiss_woman_woman_medium-light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F469\U0001F3FC', + u':kiss_woman_woman_medium-light_skin_tone_dark_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F469\U0001F3FF', + u':kiss_woman_woman_medium-light_skin_tone_light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F469\U0001F3FB', + u':kiss_woman_woman_medium-light_skin_tone_medium-dark_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F469\U0001F3FE', + u':kiss_woman_woman_medium-light_skin_tone_medium_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F469\U0001F3FD', + u':kiss_woman_woman_medium_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F469\U0001F3FD', + u':kiss_woman_woman_medium_skin_tone_dark_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F469\U0001F3FF', + u':kiss_woman_woman_medium_skin_tone_light_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F469\U0001F3FB', + u':kiss_woman_woman_medium_skin_tone_medium-dark_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F469\U0001F3FE', + u':kiss_woman_woman_medium_skin_tone_medium-light_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F469\U0001F3FC', + u':kissing_cat:': u'\U0001F63D', + u':kissing_face:': u'\U0001F617', + u':kissing_face_with_closed_eyes:': u'\U0001F61A', + u':kissing_face_with_smiling_eyes:': u'\U0001F619', + u':kitchen_knife:': u'\U0001F52A', + u':kite:': u'\U0001FA81', + u':kiwi_fruit:': u'\U0001F95D', + u':knocked-out_face:': u'\U0001F635', + u':knot:': u'\U0001FAA2', + u':koala:': u'\U0001F428', + u':lab_coat:': u'\U0001F97C', + u':label:': u'\U0001F3F7', + u':lacrosse:': u'\U0001F94D', + u':ladder:': u'\U0001FA9C', + u':lady_beetle:': u'\U0001F41E', + u':laptop:': u'\U0001F4BB', + u':large_blue_diamond:': u'\U0001F537', + u':large_orange_diamond:': u'\U0001F536', + u':last_quarter_moon:': u'\U0001F317', + u':last_quarter_moon_face:': u'\U0001F31C', + u':last_track_button:': u'\U000023EE', + u':latin_cross:': u'\U0000271D', + u':leaf_fluttering_in_wind:': u'\U0001F343', + u':leafy_green:': u'\U0001F96C', + u':ledger:': u'\U0001F4D2', + u':left-facing_fist:': u'\U0001F91B', + u':left-facing_fist_dark_skin_tone:': u'\U0001F91B\U0001F3FF', + u':left-facing_fist_light_skin_tone:': u'\U0001F91B\U0001F3FB', + u':left-facing_fist_medium-dark_skin_tone:': u'\U0001F91B\U0001F3FE', + u':left-facing_fist_medium-light_skin_tone:': u'\U0001F91B\U0001F3FC', + u':left-facing_fist_medium_skin_tone:': u'\U0001F91B\U0001F3FD', + u':left-right_arrow:': u'\U00002194', + u':left_arrow:': u'\U00002B05', + u':left_arrow_curving_right:': u'\U000021AA', + u':left_luggage:': u'\U0001F6C5', + u':left_speech_bubble:': u'\U0001F5E8', + u':leg:': u'\U0001F9B5', + u':leg_dark_skin_tone:': u'\U0001F9B5\U0001F3FF', + u':leg_light_skin_tone:': u'\U0001F9B5\U0001F3FB', + u':leg_medium-dark_skin_tone:': u'\U0001F9B5\U0001F3FE', + u':leg_medium-light_skin_tone:': u'\U0001F9B5\U0001F3FC', + u':leg_medium_skin_tone:': u'\U0001F9B5\U0001F3FD', + u':lemon:': u'\U0001F34B', + u':leopard:': u'\U0001F406', + u':level_slider:': u'\U0001F39A', + u':light_bulb:': u'\U0001F4A1', + u':light_rail:': u'\U0001F688', + u':light_skin_tone:': u'\U0001F3FB', + u':link:': u'\U0001F517', + u':linked_paperclips:': u'\U0001F587', + u':lion:': u'\U0001F981', + u':lipstick:': u'\U0001F484', + u':litter_in_bin_sign:': u'\U0001F6AE', + u':lizard:': u'\U0001F98E', + u':llama:': u'\U0001F999', + u':lobster:': u'\U0001F99E', + u':locked:': u'\U0001F512', + u':locked_with_key:': u'\U0001F510', + u':locked_with_pen:': u'\U0001F50F', + u':locomotive:': u'\U0001F682', + u':lollipop:': u'\U0001F36D', + u':long_drum:': u'\U0001FA98', + u':lotion_bottle:': u'\U0001F9F4', + u':loudly_crying_face:': u'\U0001F62D', + u':loudspeaker:': u'\U0001F4E2', + u':love-you_gesture:': u'\U0001F91F', + u':love-you_gesture_dark_skin_tone:': u'\U0001F91F\U0001F3FF', + u':love-you_gesture_light_skin_tone:': u'\U0001F91F\U0001F3FB', + u':love-you_gesture_medium-dark_skin_tone:': u'\U0001F91F\U0001F3FE', + u':love-you_gesture_medium-light_skin_tone:': u'\U0001F91F\U0001F3FC', + u':love-you_gesture_medium_skin_tone:': u'\U0001F91F\U0001F3FD', + u':love_hotel:': u'\U0001F3E9', + u':love_letter:': u'\U0001F48C', + u':luggage:': u'\U0001F9F3', + u':lungs:': u'\U0001FAC1', + u':lying_face:': u'\U0001F925', + u':mage:': u'\U0001F9D9', + u':mage_dark_skin_tone:': u'\U0001F9D9\U0001F3FF', + u':mage_light_skin_tone:': u'\U0001F9D9\U0001F3FB', + u':mage_medium-dark_skin_tone:': u'\U0001F9D9\U0001F3FE', + u':mage_medium-light_skin_tone:': u'\U0001F9D9\U0001F3FC', + u':mage_medium_skin_tone:': u'\U0001F9D9\U0001F3FD', + u':magic_wand:': u'\U0001FA84', + u':magnet:': u'\U0001F9F2', + u':magnifying_glass_tilted_left:': u'\U0001F50D', + u':magnifying_glass_tilted_right:': u'\U0001F50E', + u':mahjong_red_dragon:': u'\U0001F004', + u':male_sign:': u'\U00002642', + u':mammoth:': u'\U0001F9A3', + u':man:': u'\U0001F468', + u':man_artist:': u'\U0001F468\U0000200D\U0001F3A8', + u':man_artist_dark_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U0001F3A8', + u':man_artist_light_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U0001F3A8', + u':man_artist_medium-dark_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U0001F3A8', + u':man_artist_medium-light_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U0001F3A8', + u':man_artist_medium_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U0001F3A8', + u':man_astronaut:': u'\U0001F468\U0000200D\U0001F680', + u':man_astronaut_dark_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U0001F680', + u':man_astronaut_light_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U0001F680', + u':man_astronaut_medium-dark_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U0001F680', + u':man_astronaut_medium-light_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U0001F680', + u':man_astronaut_medium_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U0001F680', + u':man_bald:': u'\U0001F468\U0000200D\U0001F9B2', + u':man_beard:': u'\U0001F9D4\U0000200D\U00002642\U0000FE0F', + u':man_biking:': u'\U0001F6B4\U0000200D\U00002642\U0000FE0F', + u':man_biking_dark_skin_tone:': u'\U0001F6B4\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_biking_light_skin_tone:': u'\U0001F6B4\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_biking_medium-dark_skin_tone:': u'\U0001F6B4\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_biking_medium-light_skin_tone:': u'\U0001F6B4\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_biking_medium_skin_tone:': u'\U0001F6B4\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_blond_hair:': u'\U0001F471\U0000200D\U00002642\U0000FE0F', + u':man_bouncing_ball:': u'\U000026F9\U0000FE0F\U0000200D\U00002642\U0000FE0F', + u':man_bouncing_ball_dark_skin_tone:': u'\U000026F9\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_bouncing_ball_light_skin_tone:': u'\U000026F9\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_bouncing_ball_medium-dark_skin_tone:': u'\U000026F9\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_bouncing_ball_medium-light_skin_tone:': u'\U000026F9\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_bouncing_ball_medium_skin_tone:': u'\U000026F9\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_bowing:': u'\U0001F647\U0000200D\U00002642\U0000FE0F', + u':man_bowing_dark_skin_tone:': u'\U0001F647\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_bowing_light_skin_tone:': u'\U0001F647\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_bowing_medium-dark_skin_tone:': u'\U0001F647\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_bowing_medium-light_skin_tone:': u'\U0001F647\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_bowing_medium_skin_tone:': u'\U0001F647\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_cartwheeling:': u'\U0001F938\U0000200D\U00002642\U0000FE0F', + u':man_cartwheeling_dark_skin_tone:': u'\U0001F938\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_cartwheeling_light_skin_tone:': u'\U0001F938\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_cartwheeling_medium-dark_skin_tone:': u'\U0001F938\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_cartwheeling_medium-light_skin_tone:': u'\U0001F938\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_cartwheeling_medium_skin_tone:': u'\U0001F938\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_climbing:': u'\U0001F9D7\U0000200D\U00002642\U0000FE0F', + u':man_climbing_dark_skin_tone:': u'\U0001F9D7\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_climbing_light_skin_tone:': u'\U0001F9D7\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_climbing_medium-dark_skin_tone:': u'\U0001F9D7\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_climbing_medium-light_skin_tone:': u'\U0001F9D7\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_climbing_medium_skin_tone:': u'\U0001F9D7\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_construction_worker:': u'\U0001F477\U0000200D\U00002642\U0000FE0F', + u':man_construction_worker_dark_skin_tone:': u'\U0001F477\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_construction_worker_light_skin_tone:': u'\U0001F477\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_construction_worker_medium-dark_skin_tone:': u'\U0001F477\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_construction_worker_medium-light_skin_tone:': u'\U0001F477\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_construction_worker_medium_skin_tone:': u'\U0001F477\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_cook:': u'\U0001F468\U0000200D\U0001F373', + u':man_cook_dark_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U0001F373', + u':man_cook_light_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U0001F373', + u':man_cook_medium-dark_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U0001F373', + u':man_cook_medium-light_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U0001F373', + u':man_cook_medium_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U0001F373', + u':man_curly_hair:': u'\U0001F468\U0000200D\U0001F9B1', + u':man_dancing:': u'\U0001F57A', + u':man_dancing_dark_skin_tone:': u'\U0001F57A\U0001F3FF', + u':man_dancing_light_skin_tone:': u'\U0001F57A\U0001F3FB', + u':man_dancing_medium-dark_skin_tone:': u'\U0001F57A\U0001F3FE', + u':man_dancing_medium-light_skin_tone:': u'\U0001F57A\U0001F3FC', + u':man_dancing_medium_skin_tone:': u'\U0001F57A\U0001F3FD', + u':man_dark_skin_tone:': u'\U0001F468\U0001F3FF', + u':man_dark_skin_tone_bald:': u'\U0001F468\U0001F3FF\U0000200D\U0001F9B2', + u':man_dark_skin_tone_beard:': u'\U0001F9D4\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_dark_skin_tone_blond_hair:': u'\U0001F471\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_dark_skin_tone_curly_hair:': u'\U0001F468\U0001F3FF\U0000200D\U0001F9B1', + u':man_dark_skin_tone_red_hair:': u'\U0001F468\U0001F3FF\U0000200D\U0001F9B0', + u':man_dark_skin_tone_white_hair:': u'\U0001F468\U0001F3FF\U0000200D\U0001F9B3', + u':man_detective:': u'\U0001F575\U0000FE0F\U0000200D\U00002642\U0000FE0F', + u':man_detective_dark_skin_tone:': u'\U0001F575\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_detective_light_skin_tone:': u'\U0001F575\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_detective_medium-dark_skin_tone:': u'\U0001F575\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_detective_medium-light_skin_tone:': u'\U0001F575\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_detective_medium_skin_tone:': u'\U0001F575\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_elf:': u'\U0001F9DD\U0000200D\U00002642\U0000FE0F', + u':man_elf_dark_skin_tone:': u'\U0001F9DD\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_elf_light_skin_tone:': u'\U0001F9DD\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_elf_medium-dark_skin_tone:': u'\U0001F9DD\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_elf_medium-light_skin_tone:': u'\U0001F9DD\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_elf_medium_skin_tone:': u'\U0001F9DD\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_facepalming:': u'\U0001F926\U0000200D\U00002642\U0000FE0F', + u':man_facepalming_dark_skin_tone:': u'\U0001F926\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_facepalming_light_skin_tone:': u'\U0001F926\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_facepalming_medium-dark_skin_tone:': u'\U0001F926\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_facepalming_medium-light_skin_tone:': u'\U0001F926\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_facepalming_medium_skin_tone:': u'\U0001F926\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_factory_worker:': u'\U0001F468\U0000200D\U0001F3ED', + u':man_factory_worker_dark_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U0001F3ED', + u':man_factory_worker_light_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U0001F3ED', + u':man_factory_worker_medium-dark_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U0001F3ED', + u':man_factory_worker_medium-light_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U0001F3ED', + u':man_factory_worker_medium_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U0001F3ED', + u':man_fairy:': u'\U0001F9DA\U0000200D\U00002642\U0000FE0F', + u':man_fairy_dark_skin_tone:': u'\U0001F9DA\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_fairy_light_skin_tone:': u'\U0001F9DA\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_fairy_medium-dark_skin_tone:': u'\U0001F9DA\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_fairy_medium-light_skin_tone:': u'\U0001F9DA\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_fairy_medium_skin_tone:': u'\U0001F9DA\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_farmer:': u'\U0001F468\U0000200D\U0001F33E', + u':man_farmer_dark_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U0001F33E', + u':man_farmer_light_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U0001F33E', + u':man_farmer_medium-dark_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U0001F33E', + u':man_farmer_medium-light_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U0001F33E', + u':man_farmer_medium_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U0001F33E', + u':man_feeding_baby:': u'\U0001F468\U0000200D\U0001F37C', + u':man_feeding_baby_dark_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U0001F37C', + u':man_feeding_baby_light_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U0001F37C', + u':man_feeding_baby_medium-dark_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U0001F37C', + u':man_feeding_baby_medium-light_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U0001F37C', + u':man_feeding_baby_medium_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U0001F37C', + u':man_firefighter:': u'\U0001F468\U0000200D\U0001F692', + u':man_firefighter_dark_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U0001F692', + u':man_firefighter_light_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U0001F692', + u':man_firefighter_medium-dark_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U0001F692', + u':man_firefighter_medium-light_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U0001F692', + u':man_firefighter_medium_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U0001F692', + u':man_frowning:': u'\U0001F64D\U0000200D\U00002642\U0000FE0F', + u':man_frowning_dark_skin_tone:': u'\U0001F64D\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_frowning_light_skin_tone:': u'\U0001F64D\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_frowning_medium-dark_skin_tone:': u'\U0001F64D\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_frowning_medium-light_skin_tone:': u'\U0001F64D\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_frowning_medium_skin_tone:': u'\U0001F64D\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_genie:': u'\U0001F9DE\U0000200D\U00002642\U0000FE0F', + u':man_gesturing_NO:': u'\U0001F645\U0000200D\U00002642\U0000FE0F', + u':man_gesturing_NO_dark_skin_tone:': u'\U0001F645\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_gesturing_NO_light_skin_tone:': u'\U0001F645\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_gesturing_NO_medium-dark_skin_tone:': u'\U0001F645\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_gesturing_NO_medium-light_skin_tone:': u'\U0001F645\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_gesturing_NO_medium_skin_tone:': u'\U0001F645\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_gesturing_OK:': u'\U0001F646\U0000200D\U00002642\U0000FE0F', + u':man_gesturing_OK_dark_skin_tone:': u'\U0001F646\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_gesturing_OK_light_skin_tone:': u'\U0001F646\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_gesturing_OK_medium-dark_skin_tone:': u'\U0001F646\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_gesturing_OK_medium-light_skin_tone:': u'\U0001F646\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_gesturing_OK_medium_skin_tone:': u'\U0001F646\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_getting_haircut:': u'\U0001F487\U0000200D\U00002642\U0000FE0F', + u':man_getting_haircut_dark_skin_tone:': u'\U0001F487\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_getting_haircut_light_skin_tone:': u'\U0001F487\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_getting_haircut_medium-dark_skin_tone:': u'\U0001F487\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_getting_haircut_medium-light_skin_tone:': u'\U0001F487\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_getting_haircut_medium_skin_tone:': u'\U0001F487\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_getting_massage:': u'\U0001F486\U0000200D\U00002642\U0000FE0F', + u':man_getting_massage_dark_skin_tone:': u'\U0001F486\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_getting_massage_light_skin_tone:': u'\U0001F486\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_getting_massage_medium-dark_skin_tone:': u'\U0001F486\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_getting_massage_medium-light_skin_tone:': u'\U0001F486\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_getting_massage_medium_skin_tone:': u'\U0001F486\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_golfing:': u'\U0001F3CC\U0000FE0F\U0000200D\U00002642\U0000FE0F', + u':man_golfing_dark_skin_tone:': u'\U0001F3CC\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_golfing_light_skin_tone:': u'\U0001F3CC\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_golfing_medium-dark_skin_tone:': u'\U0001F3CC\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_golfing_medium-light_skin_tone:': u'\U0001F3CC\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_golfing_medium_skin_tone:': u'\U0001F3CC\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_guard:': u'\U0001F482\U0000200D\U00002642\U0000FE0F', + u':man_guard_dark_skin_tone:': u'\U0001F482\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_guard_light_skin_tone:': u'\U0001F482\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_guard_medium-dark_skin_tone:': u'\U0001F482\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_guard_medium-light_skin_tone:': u'\U0001F482\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_guard_medium_skin_tone:': u'\U0001F482\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_health_worker:': u'\U0001F468\U0000200D\U00002695\U0000FE0F', + u':man_health_worker_dark_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U00002695\U0000FE0F', + u':man_health_worker_light_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U00002695\U0000FE0F', + u':man_health_worker_medium-dark_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U00002695\U0000FE0F', + u':man_health_worker_medium-light_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U00002695\U0000FE0F', + u':man_health_worker_medium_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U00002695\U0000FE0F', + u':man_in_lotus_position:': u'\U0001F9D8\U0000200D\U00002642\U0000FE0F', + u':man_in_lotus_position_dark_skin_tone:': u'\U0001F9D8\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_in_lotus_position_light_skin_tone:': u'\U0001F9D8\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_in_lotus_position_medium-dark_skin_tone:': u'\U0001F9D8\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_in_lotus_position_medium-light_skin_tone:': u'\U0001F9D8\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_in_lotus_position_medium_skin_tone:': u'\U0001F9D8\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_in_manual_wheelchair:': u'\U0001F468\U0000200D\U0001F9BD', + u':man_in_manual_wheelchair_dark_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U0001F9BD', + u':man_in_manual_wheelchair_light_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U0001F9BD', + u':man_in_manual_wheelchair_medium-dark_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U0001F9BD', + u':man_in_manual_wheelchair_medium-light_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U0001F9BD', + u':man_in_manual_wheelchair_medium_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U0001F9BD', + u':man_in_motorized_wheelchair:': u'\U0001F468\U0000200D\U0001F9BC', + u':man_in_motorized_wheelchair_dark_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U0001F9BC', + u':man_in_motorized_wheelchair_light_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U0001F9BC', + u':man_in_motorized_wheelchair_medium-dark_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U0001F9BC', + u':man_in_motorized_wheelchair_medium-light_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U0001F9BC', + u':man_in_motorized_wheelchair_medium_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U0001F9BC', + u':man_in_steamy_room:': u'\U0001F9D6\U0000200D\U00002642\U0000FE0F', + u':man_in_steamy_room_dark_skin_tone:': u'\U0001F9D6\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_in_steamy_room_light_skin_tone:': u'\U0001F9D6\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_in_steamy_room_medium-dark_skin_tone:': u'\U0001F9D6\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_in_steamy_room_medium-light_skin_tone:': u'\U0001F9D6\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_in_steamy_room_medium_skin_tone:': u'\U0001F9D6\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_in_tuxedo:': u'\U0001F935\U0000200D\U00002642\U0000FE0F', + u':man_in_tuxedo_dark_skin_tone:': u'\U0001F935\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_in_tuxedo_light_skin_tone:': u'\U0001F935\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_in_tuxedo_medium-dark_skin_tone:': u'\U0001F935\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_in_tuxedo_medium-light_skin_tone:': u'\U0001F935\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_in_tuxedo_medium_skin_tone:': u'\U0001F935\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_judge:': u'\U0001F468\U0000200D\U00002696\U0000FE0F', + u':man_judge_dark_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U00002696\U0000FE0F', + u':man_judge_light_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U00002696\U0000FE0F', + u':man_judge_medium-dark_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U00002696\U0000FE0F', + u':man_judge_medium-light_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U00002696\U0000FE0F', + u':man_judge_medium_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U00002696\U0000FE0F', + u':man_juggling:': u'\U0001F939\U0000200D\U00002642\U0000FE0F', + u':man_juggling_dark_skin_tone:': u'\U0001F939\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_juggling_light_skin_tone:': u'\U0001F939\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_juggling_medium-dark_skin_tone:': u'\U0001F939\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_juggling_medium-light_skin_tone:': u'\U0001F939\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_juggling_medium_skin_tone:': u'\U0001F939\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_kneeling:': u'\U0001F9CE\U0000200D\U00002642\U0000FE0F', + u':man_kneeling_dark_skin_tone:': u'\U0001F9CE\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_kneeling_light_skin_tone:': u'\U0001F9CE\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_kneeling_medium-dark_skin_tone:': u'\U0001F9CE\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_kneeling_medium-light_skin_tone:': u'\U0001F9CE\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_kneeling_medium_skin_tone:': u'\U0001F9CE\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_lifting_weights:': u'\U0001F3CB\U0000FE0F\U0000200D\U00002642\U0000FE0F', + u':man_lifting_weights_dark_skin_tone:': u'\U0001F3CB\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_lifting_weights_light_skin_tone:': u'\U0001F3CB\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_lifting_weights_medium-dark_skin_tone:': u'\U0001F3CB\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_lifting_weights_medium-light_skin_tone:': u'\U0001F3CB\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_lifting_weights_medium_skin_tone:': u'\U0001F3CB\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_light_skin_tone:': u'\U0001F468\U0001F3FB', + u':man_light_skin_tone_bald:': u'\U0001F468\U0001F3FB\U0000200D\U0001F9B2', + u':man_light_skin_tone_beard:': u'\U0001F9D4\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_light_skin_tone_blond_hair:': u'\U0001F471\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_light_skin_tone_curly_hair:': u'\U0001F468\U0001F3FB\U0000200D\U0001F9B1', + u':man_light_skin_tone_red_hair:': u'\U0001F468\U0001F3FB\U0000200D\U0001F9B0', + u':man_light_skin_tone_white_hair:': u'\U0001F468\U0001F3FB\U0000200D\U0001F9B3', + u':man_mage:': u'\U0001F9D9\U0000200D\U00002642\U0000FE0F', + u':man_mage_dark_skin_tone:': u'\U0001F9D9\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_mage_light_skin_tone:': u'\U0001F9D9\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_mage_medium-dark_skin_tone:': u'\U0001F9D9\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_mage_medium-light_skin_tone:': u'\U0001F9D9\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_mage_medium_skin_tone:': u'\U0001F9D9\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_mechanic:': u'\U0001F468\U0000200D\U0001F527', + u':man_mechanic_dark_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U0001F527', + u':man_mechanic_light_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U0001F527', + u':man_mechanic_medium-dark_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U0001F527', + u':man_mechanic_medium-light_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U0001F527', + u':man_mechanic_medium_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U0001F527', + u':man_medium-dark_skin_tone:': u'\U0001F468\U0001F3FE', + u':man_medium-dark_skin_tone_bald:': u'\U0001F468\U0001F3FE\U0000200D\U0001F9B2', + u':man_medium-dark_skin_tone_beard:': u'\U0001F9D4\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_medium-dark_skin_tone_blond_hair:': u'\U0001F471\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_medium-dark_skin_tone_curly_hair:': u'\U0001F468\U0001F3FE\U0000200D\U0001F9B1', + u':man_medium-dark_skin_tone_red_hair:': u'\U0001F468\U0001F3FE\U0000200D\U0001F9B0', + u':man_medium-dark_skin_tone_white_hair:': u'\U0001F468\U0001F3FE\U0000200D\U0001F9B3', + u':man_medium-light_skin_tone:': u'\U0001F468\U0001F3FC', + u':man_medium-light_skin_tone_bald:': u'\U0001F468\U0001F3FC\U0000200D\U0001F9B2', + u':man_medium-light_skin_tone_beard:': u'\U0001F9D4\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_medium-light_skin_tone_blond_hair:': u'\U0001F471\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_medium-light_skin_tone_curly_hair:': u'\U0001F468\U0001F3FC\U0000200D\U0001F9B1', + u':man_medium-light_skin_tone_red_hair:': u'\U0001F468\U0001F3FC\U0000200D\U0001F9B0', + u':man_medium-light_skin_tone_white_hair:': u'\U0001F468\U0001F3FC\U0000200D\U0001F9B3', + u':man_medium_skin_tone:': u'\U0001F468\U0001F3FD', + u':man_medium_skin_tone_bald:': u'\U0001F468\U0001F3FD\U0000200D\U0001F9B2', + u':man_medium_skin_tone_beard:': u'\U0001F9D4\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_medium_skin_tone_blond_hair:': u'\U0001F471\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_medium_skin_tone_curly_hair:': u'\U0001F468\U0001F3FD\U0000200D\U0001F9B1', + u':man_medium_skin_tone_red_hair:': u'\U0001F468\U0001F3FD\U0000200D\U0001F9B0', + u':man_medium_skin_tone_white_hair:': u'\U0001F468\U0001F3FD\U0000200D\U0001F9B3', + u':man_mountain_biking:': u'\U0001F6B5\U0000200D\U00002642\U0000FE0F', + u':man_mountain_biking_dark_skin_tone:': u'\U0001F6B5\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_mountain_biking_light_skin_tone:': u'\U0001F6B5\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_mountain_biking_medium-dark_skin_tone:': u'\U0001F6B5\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_mountain_biking_medium-light_skin_tone:': u'\U0001F6B5\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_mountain_biking_medium_skin_tone:': u'\U0001F6B5\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_office_worker:': u'\U0001F468\U0000200D\U0001F4BC', + u':man_office_worker_dark_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U0001F4BC', + u':man_office_worker_light_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U0001F4BC', + u':man_office_worker_medium-dark_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U0001F4BC', + u':man_office_worker_medium-light_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U0001F4BC', + u':man_office_worker_medium_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U0001F4BC', + u':man_pilot:': u'\U0001F468\U0000200D\U00002708\U0000FE0F', + u':man_pilot_dark_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U00002708\U0000FE0F', + u':man_pilot_light_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U00002708\U0000FE0F', + u':man_pilot_medium-dark_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U00002708\U0000FE0F', + u':man_pilot_medium-light_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U00002708\U0000FE0F', + u':man_pilot_medium_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U00002708\U0000FE0F', + u':man_playing_handball:': u'\U0001F93E\U0000200D\U00002642\U0000FE0F', + u':man_playing_handball_dark_skin_tone:': u'\U0001F93E\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_playing_handball_light_skin_tone:': u'\U0001F93E\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_playing_handball_medium-dark_skin_tone:': u'\U0001F93E\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_playing_handball_medium-light_skin_tone:': u'\U0001F93E\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_playing_handball_medium_skin_tone:': u'\U0001F93E\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_playing_water_polo:': u'\U0001F93D\U0000200D\U00002642\U0000FE0F', + u':man_playing_water_polo_dark_skin_tone:': u'\U0001F93D\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_playing_water_polo_light_skin_tone:': u'\U0001F93D\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_playing_water_polo_medium-dark_skin_tone:': u'\U0001F93D\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_playing_water_polo_medium-light_skin_tone:': u'\U0001F93D\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_playing_water_polo_medium_skin_tone:': u'\U0001F93D\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_police_officer:': u'\U0001F46E\U0000200D\U00002642\U0000FE0F', + u':man_police_officer_dark_skin_tone:': u'\U0001F46E\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_police_officer_light_skin_tone:': u'\U0001F46E\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_police_officer_medium-dark_skin_tone:': u'\U0001F46E\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_police_officer_medium-light_skin_tone:': u'\U0001F46E\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_police_officer_medium_skin_tone:': u'\U0001F46E\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_pouting:': u'\U0001F64E\U0000200D\U00002642\U0000FE0F', + u':man_pouting_dark_skin_tone:': u'\U0001F64E\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_pouting_light_skin_tone:': u'\U0001F64E\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_pouting_medium-dark_skin_tone:': u'\U0001F64E\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_pouting_medium-light_skin_tone:': u'\U0001F64E\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_pouting_medium_skin_tone:': u'\U0001F64E\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_raising_hand:': u'\U0001F64B\U0000200D\U00002642\U0000FE0F', + u':man_raising_hand_dark_skin_tone:': u'\U0001F64B\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_raising_hand_light_skin_tone:': u'\U0001F64B\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_raising_hand_medium-dark_skin_tone:': u'\U0001F64B\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_raising_hand_medium-light_skin_tone:': u'\U0001F64B\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_raising_hand_medium_skin_tone:': u'\U0001F64B\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_red_hair:': u'\U0001F468\U0000200D\U0001F9B0', + u':man_rowing_boat:': u'\U0001F6A3\U0000200D\U00002642\U0000FE0F', + u':man_rowing_boat_dark_skin_tone:': u'\U0001F6A3\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_rowing_boat_light_skin_tone:': u'\U0001F6A3\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_rowing_boat_medium-dark_skin_tone:': u'\U0001F6A3\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_rowing_boat_medium-light_skin_tone:': u'\U0001F6A3\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_rowing_boat_medium_skin_tone:': u'\U0001F6A3\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_running:': u'\U0001F3C3\U0000200D\U00002642\U0000FE0F', + u':man_running_dark_skin_tone:': u'\U0001F3C3\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_running_light_skin_tone:': u'\U0001F3C3\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_running_medium-dark_skin_tone:': u'\U0001F3C3\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_running_medium-light_skin_tone:': u'\U0001F3C3\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_running_medium_skin_tone:': u'\U0001F3C3\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_scientist:': u'\U0001F468\U0000200D\U0001F52C', + u':man_scientist_dark_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U0001F52C', + u':man_scientist_light_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U0001F52C', + u':man_scientist_medium-dark_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U0001F52C', + u':man_scientist_medium-light_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U0001F52C', + u':man_scientist_medium_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U0001F52C', + u':man_shrugging:': u'\U0001F937\U0000200D\U00002642\U0000FE0F', + u':man_shrugging_dark_skin_tone:': u'\U0001F937\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_shrugging_light_skin_tone:': u'\U0001F937\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_shrugging_medium-dark_skin_tone:': u'\U0001F937\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_shrugging_medium-light_skin_tone:': u'\U0001F937\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_shrugging_medium_skin_tone:': u'\U0001F937\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_singer:': u'\U0001F468\U0000200D\U0001F3A4', + u':man_singer_dark_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U0001F3A4', + u':man_singer_light_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U0001F3A4', + u':man_singer_medium-dark_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U0001F3A4', + u':man_singer_medium-light_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U0001F3A4', + u':man_singer_medium_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U0001F3A4', + u':man_standing:': u'\U0001F9CD\U0000200D\U00002642\U0000FE0F', + u':man_standing_dark_skin_tone:': u'\U0001F9CD\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_standing_light_skin_tone:': u'\U0001F9CD\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_standing_medium-dark_skin_tone:': u'\U0001F9CD\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_standing_medium-light_skin_tone:': u'\U0001F9CD\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_standing_medium_skin_tone:': u'\U0001F9CD\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_student:': u'\U0001F468\U0000200D\U0001F393', + u':man_student_dark_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U0001F393', + u':man_student_light_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U0001F393', + u':man_student_medium-dark_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U0001F393', + u':man_student_medium-light_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U0001F393', + u':man_student_medium_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U0001F393', + u':man_superhero:': u'\U0001F9B8\U0000200D\U00002642\U0000FE0F', + u':man_superhero_dark_skin_tone:': u'\U0001F9B8\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_superhero_light_skin_tone:': u'\U0001F9B8\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_superhero_medium-dark_skin_tone:': u'\U0001F9B8\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_superhero_medium-light_skin_tone:': u'\U0001F9B8\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_superhero_medium_skin_tone:': u'\U0001F9B8\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_supervillain:': u'\U0001F9B9\U0000200D\U00002642\U0000FE0F', + u':man_supervillain_dark_skin_tone:': u'\U0001F9B9\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_supervillain_light_skin_tone:': u'\U0001F9B9\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_supervillain_medium-dark_skin_tone:': u'\U0001F9B9\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_supervillain_medium-light_skin_tone:': u'\U0001F9B9\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_supervillain_medium_skin_tone:': u'\U0001F9B9\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_surfing:': u'\U0001F3C4\U0000200D\U00002642\U0000FE0F', + u':man_surfing_dark_skin_tone:': u'\U0001F3C4\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_surfing_light_skin_tone:': u'\U0001F3C4\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_surfing_medium-dark_skin_tone:': u'\U0001F3C4\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_surfing_medium-light_skin_tone:': u'\U0001F3C4\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_surfing_medium_skin_tone:': u'\U0001F3C4\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_swimming:': u'\U0001F3CA\U0000200D\U00002642\U0000FE0F', + u':man_swimming_dark_skin_tone:': u'\U0001F3CA\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_swimming_light_skin_tone:': u'\U0001F3CA\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_swimming_medium-dark_skin_tone:': u'\U0001F3CA\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_swimming_medium-light_skin_tone:': u'\U0001F3CA\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_swimming_medium_skin_tone:': u'\U0001F3CA\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_teacher:': u'\U0001F468\U0000200D\U0001F3EB', + u':man_teacher_dark_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U0001F3EB', + u':man_teacher_light_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U0001F3EB', + u':man_teacher_medium-dark_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U0001F3EB', + u':man_teacher_medium-light_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U0001F3EB', + u':man_teacher_medium_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U0001F3EB', + u':man_technologist:': u'\U0001F468\U0000200D\U0001F4BB', + u':man_technologist_dark_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U0001F4BB', + u':man_technologist_light_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U0001F4BB', + u':man_technologist_medium-dark_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U0001F4BB', + u':man_technologist_medium-light_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U0001F4BB', + u':man_technologist_medium_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U0001F4BB', + u':man_tipping_hand:': u'\U0001F481\U0000200D\U00002642\U0000FE0F', + u':man_tipping_hand_dark_skin_tone:': u'\U0001F481\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_tipping_hand_light_skin_tone:': u'\U0001F481\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_tipping_hand_medium-dark_skin_tone:': u'\U0001F481\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_tipping_hand_medium-light_skin_tone:': u'\U0001F481\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_tipping_hand_medium_skin_tone:': u'\U0001F481\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_vampire:': u'\U0001F9DB\U0000200D\U00002642\U0000FE0F', + u':man_vampire_dark_skin_tone:': u'\U0001F9DB\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_vampire_light_skin_tone:': u'\U0001F9DB\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_vampire_medium-dark_skin_tone:': u'\U0001F9DB\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_vampire_medium-light_skin_tone:': u'\U0001F9DB\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_vampire_medium_skin_tone:': u'\U0001F9DB\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_walking:': u'\U0001F6B6\U0000200D\U00002642\U0000FE0F', + u':man_walking_dark_skin_tone:': u'\U0001F6B6\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_walking_light_skin_tone:': u'\U0001F6B6\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_walking_medium-dark_skin_tone:': u'\U0001F6B6\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_walking_medium-light_skin_tone:': u'\U0001F6B6\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_walking_medium_skin_tone:': u'\U0001F6B6\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_wearing_turban:': u'\U0001F473\U0000200D\U00002642\U0000FE0F', + u':man_wearing_turban_dark_skin_tone:': u'\U0001F473\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_wearing_turban_light_skin_tone:': u'\U0001F473\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_wearing_turban_medium-dark_skin_tone:': u'\U0001F473\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_wearing_turban_medium-light_skin_tone:': u'\U0001F473\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_wearing_turban_medium_skin_tone:': u'\U0001F473\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_white_hair:': u'\U0001F468\U0000200D\U0001F9B3', + u':man_with_veil:': u'\U0001F470\U0000200D\U00002642\U0000FE0F', + u':man_with_veil_dark_skin_tone:': u'\U0001F470\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':man_with_veil_light_skin_tone:': u'\U0001F470\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':man_with_veil_medium-dark_skin_tone:': u'\U0001F470\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':man_with_veil_medium-light_skin_tone:': u'\U0001F470\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':man_with_veil_medium_skin_tone:': u'\U0001F470\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':man_with_white_cane:': u'\U0001F468\U0000200D\U0001F9AF', + u':man_with_white_cane_dark_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U0001F9AF', + u':man_with_white_cane_light_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U0001F9AF', + u':man_with_white_cane_medium-dark_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U0001F9AF', + u':man_with_white_cane_medium-light_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U0001F9AF', + u':man_with_white_cane_medium_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U0001F9AF', + u':man_zombie:': u'\U0001F9DF\U0000200D\U00002642\U0000FE0F', + u':mango:': u'\U0001F96D', + u':mantelpiece_clock:': u'\U0001F570', + u':manual_wheelchair:': u'\U0001F9BD', + u':man’s_shoe:': u'\U0001F45E', + u':map_of_Japan:': u'\U0001F5FE', + u':maple_leaf:': u'\U0001F341', + u':martial_arts_uniform:': u'\U0001F94B', + u':mate:': u'\U0001F9C9', + u':meat_on_bone:': u'\U0001F356', + u':mechanic:': u'\U0001F9D1\U0000200D\U0001F527', + u':mechanic_dark_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F527', + u':mechanic_light_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F527', + u':mechanic_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F527', + u':mechanic_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F527', + u':mechanic_medium_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F527', + u':mechanical_arm:': u'\U0001F9BE', + u':mechanical_leg:': u'\U0001F9BF', + u':medical_symbol:': u'\U00002695', + u':medium-dark_skin_tone:': u'\U0001F3FE', + u':medium-light_skin_tone:': u'\U0001F3FC', + u':medium_skin_tone:': u'\U0001F3FD', + u':megaphone:': u'\U0001F4E3', + u':melon:': u'\U0001F348', + u':memo:': u'\U0001F4DD', + u':men_holding_hands:': u'\U0001F46C', + u':men_holding_hands_dark_skin_tone:': u'\U0001F46C\U0001F3FF', + u':men_holding_hands_dark_skin_tone_light_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FB', + u':men_holding_hands_dark_skin_tone_medium-dark_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FE', + u':men_holding_hands_dark_skin_tone_medium-light_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FC', + u':men_holding_hands_dark_skin_tone_medium_skin_tone:': u'\U0001F468\U0001F3FF\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FD', + u':men_holding_hands_light_skin_tone:': u'\U0001F46C\U0001F3FB', + u':men_holding_hands_light_skin_tone_dark_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FF', + u':men_holding_hands_light_skin_tone_medium-dark_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FE', + u':men_holding_hands_light_skin_tone_medium-light_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FC', + u':men_holding_hands_light_skin_tone_medium_skin_tone:': u'\U0001F468\U0001F3FB\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FD', + u':men_holding_hands_medium-dark_skin_tone:': u'\U0001F46C\U0001F3FE', + u':men_holding_hands_medium-dark_skin_tone_dark_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FF', + u':men_holding_hands_medium-dark_skin_tone_light_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FB', + u':men_holding_hands_medium-dark_skin_tone_medium-light_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FC', + u':men_holding_hands_medium-dark_skin_tone_medium_skin_tone:': u'\U0001F468\U0001F3FE\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FD', + u':men_holding_hands_medium-light_skin_tone:': u'\U0001F46C\U0001F3FC', + u':men_holding_hands_medium-light_skin_tone_dark_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FF', + u':men_holding_hands_medium-light_skin_tone_light_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FB', + u':men_holding_hands_medium-light_skin_tone_medium-dark_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FE', + u':men_holding_hands_medium-light_skin_tone_medium_skin_tone:': u'\U0001F468\U0001F3FC\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FD', + u':men_holding_hands_medium_skin_tone:': u'\U0001F46C\U0001F3FD', + u':men_holding_hands_medium_skin_tone_dark_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FF', + u':men_holding_hands_medium_skin_tone_light_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FB', + u':men_holding_hands_medium_skin_tone_medium-dark_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FE', + u':men_holding_hands_medium_skin_tone_medium-light_skin_tone:': u'\U0001F468\U0001F3FD\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FC', + u':men_with_bunny_ears:': u'\U0001F46F\U0000200D\U00002642\U0000FE0F', + u':men_wrestling:': u'\U0001F93C\U0000200D\U00002642\U0000FE0F', + u':mending_heart:': u'\U00002764\U0000FE0F\U0000200D\U0001FA79', + u':menorah:': u'\U0001F54E', + u':men’s_room:': u'\U0001F6B9', + u':mermaid:': u'\U0001F9DC\U0000200D\U00002640\U0000FE0F', + u':mermaid_dark_skin_tone:': u'\U0001F9DC\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':mermaid_light_skin_tone:': u'\U0001F9DC\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':mermaid_medium-dark_skin_tone:': u'\U0001F9DC\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':mermaid_medium-light_skin_tone:': u'\U0001F9DC\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':mermaid_medium_skin_tone:': u'\U0001F9DC\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':merman:': u'\U0001F9DC\U0000200D\U00002642\U0000FE0F', + u':merman_dark_skin_tone:': u'\U0001F9DC\U0001F3FF\U0000200D\U00002642\U0000FE0F', + u':merman_light_skin_tone:': u'\U0001F9DC\U0001F3FB\U0000200D\U00002642\U0000FE0F', + u':merman_medium-dark_skin_tone:': u'\U0001F9DC\U0001F3FE\U0000200D\U00002642\U0000FE0F', + u':merman_medium-light_skin_tone:': u'\U0001F9DC\U0001F3FC\U0000200D\U00002642\U0000FE0F', + u':merman_medium_skin_tone:': u'\U0001F9DC\U0001F3FD\U0000200D\U00002642\U0000FE0F', + u':merperson:': u'\U0001F9DC', + u':merperson_dark_skin_tone:': u'\U0001F9DC\U0001F3FF', + u':merperson_light_skin_tone:': u'\U0001F9DC\U0001F3FB', + u':merperson_medium-dark_skin_tone:': u'\U0001F9DC\U0001F3FE', + u':merperson_medium-light_skin_tone:': u'\U0001F9DC\U0001F3FC', + u':merperson_medium_skin_tone:': u'\U0001F9DC\U0001F3FD', + u':metro:': u'\U0001F687', + u':microbe:': u'\U0001F9A0', + u':microphone:': u'\U0001F3A4', + u':microscope:': u'\U0001F52C', + u':middle_finger:': u'\U0001F595', + u':middle_finger_dark_skin_tone:': u'\U0001F595\U0001F3FF', + u':middle_finger_light_skin_tone:': u'\U0001F595\U0001F3FB', + u':middle_finger_medium-dark_skin_tone:': u'\U0001F595\U0001F3FE', + u':middle_finger_medium-light_skin_tone:': u'\U0001F595\U0001F3FC', + u':middle_finger_medium_skin_tone:': u'\U0001F595\U0001F3FD', + u':military_helmet:': u'\U0001FA96', + u':military_medal:': u'\U0001F396', + u':milky_way:': u'\U0001F30C', + u':minibus:': u'\U0001F690', + u':minus:': u'\U00002796', + u':mirror:': u'\U0001FA9E', + u':moai:': u'\U0001F5FF', + u':mobile_phone:': u'\U0001F4F1', + u':mobile_phone_off:': u'\U0001F4F4', + u':mobile_phone_with_arrow:': u'\U0001F4F2', + u':money-mouth_face:': u'\U0001F911', + u':money_bag:': u'\U0001F4B0', + u':money_with_wings:': u'\U0001F4B8', + u':monkey:': u'\U0001F412', + u':monkey_face:': u'\U0001F435', + u':monorail:': u'\U0001F69D', + u':moon_cake:': u'\U0001F96E', + u':moon_viewing_ceremony:': u'\U0001F391', + u':mosque:': u'\U0001F54C', + u':mosquito:': u'\U0001F99F', + u':motor_boat:': u'\U0001F6E5', + u':motor_scooter:': u'\U0001F6F5', + u':motorcycle:': u'\U0001F3CD', + u':motorized_wheelchair:': u'\U0001F9BC', + u':motorway:': u'\U0001F6E3', + u':mount_fuji:': u'\U0001F5FB', + u':mountain:': u'\U000026F0', + u':mountain_cableway:': u'\U0001F6A0', + u':mountain_railway:': u'\U0001F69E', + u':mouse:': u'\U0001F401', + u':mouse_face:': u'\U0001F42D', + u':mouse_trap:': u'\U0001FAA4', + u':mouth:': u'\U0001F444', + u':movie_camera:': u'\U0001F3A5', + u':multiply:': u'\U00002716', + u':mushroom:': u'\U0001F344', + u':musical_keyboard:': u'\U0001F3B9', + u':musical_note:': u'\U0001F3B5', + u':musical_notes:': u'\U0001F3B6', + u':musical_score:': u'\U0001F3BC', + u':muted_speaker:': u'\U0001F507', + u':mx_claus:': u'\U0001F9D1\U0000200D\U0001F384', + u':mx_claus_dark_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F384', + u':mx_claus_light_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F384', + u':mx_claus_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F384', + u':mx_claus_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F384', + u':mx_claus_medium_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F384', + u':nail_polish:': u'\U0001F485', + u':nail_polish_dark_skin_tone:': u'\U0001F485\U0001F3FF', + u':nail_polish_light_skin_tone:': u'\U0001F485\U0001F3FB', + u':nail_polish_medium-dark_skin_tone:': u'\U0001F485\U0001F3FE', + u':nail_polish_medium-light_skin_tone:': u'\U0001F485\U0001F3FC', + u':nail_polish_medium_skin_tone:': u'\U0001F485\U0001F3FD', + u':name_badge:': u'\U0001F4DB', + u':national_park:': u'\U0001F3DE', + u':nauseated_face:': u'\U0001F922', + u':nazar_amulet:': u'\U0001F9FF', + u':necktie:': u'\U0001F454', + u':nerd_face:': u'\U0001F913', + u':nesting_dolls:': u'\U0001FA86', + u':neutral_face:': u'\U0001F610', + u':new_moon:': u'\U0001F311', + u':new_moon_face:': u'\U0001F31A', + u':newspaper:': u'\U0001F4F0', + u':next_track_button:': u'\U000023ED', + u':night_with_stars:': u'\U0001F303', + u':nine-thirty:': u'\U0001F564', + u':nine_o’clock:': u'\U0001F558', + u':ninja:': u'\U0001F977', + u':ninja_dark_skin_tone:': u'\U0001F977\U0001F3FF', + u':ninja_light_skin_tone:': u'\U0001F977\U0001F3FB', + u':ninja_medium-dark_skin_tone:': u'\U0001F977\U0001F3FE', + u':ninja_medium-light_skin_tone:': u'\U0001F977\U0001F3FC', + u':ninja_medium_skin_tone:': u'\U0001F977\U0001F3FD', + u':no_bicycles:': u'\U0001F6B3', + u':no_entry:': u'\U000026D4', + u':no_littering:': u'\U0001F6AF', + u':no_mobile_phones:': u'\U0001F4F5', + u':no_one_under_eighteen:': u'\U0001F51E', + u':no_pedestrians:': u'\U0001F6B7', + u':no_smoking:': u'\U0001F6AD', + u':non-potable_water:': u'\U0001F6B1', + u':nose:': u'\U0001F443', + u':nose_dark_skin_tone:': u'\U0001F443\U0001F3FF', + u':nose_light_skin_tone:': u'\U0001F443\U0001F3FB', + u':nose_medium-dark_skin_tone:': u'\U0001F443\U0001F3FE', + u':nose_medium-light_skin_tone:': u'\U0001F443\U0001F3FC', + u':nose_medium_skin_tone:': u'\U0001F443\U0001F3FD', + u':notebook:': u'\U0001F4D3', + u':notebook_with_decorative_cover:': u'\U0001F4D4', + u':nut_and_bolt:': u'\U0001F529', + u':octopus:': u'\U0001F419', + u':oden:': u'\U0001F362', + u':office_building:': u'\U0001F3E2', + u':office_worker:': u'\U0001F9D1\U0000200D\U0001F4BC', + u':office_worker_dark_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F4BC', + u':office_worker_light_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F4BC', + u':office_worker_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F4BC', + u':office_worker_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F4BC', + u':office_worker_medium_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F4BC', + u':ogre:': u'\U0001F479', + u':oil_drum:': u'\U0001F6E2', + u':old_key:': u'\U0001F5DD', + u':old_man:': u'\U0001F474', + u':old_man_dark_skin_tone:': u'\U0001F474\U0001F3FF', + u':old_man_light_skin_tone:': u'\U0001F474\U0001F3FB', + u':old_man_medium-dark_skin_tone:': u'\U0001F474\U0001F3FE', + u':old_man_medium-light_skin_tone:': u'\U0001F474\U0001F3FC', + u':old_man_medium_skin_tone:': u'\U0001F474\U0001F3FD', + u':old_woman:': u'\U0001F475', + u':old_woman_dark_skin_tone:': u'\U0001F475\U0001F3FF', + u':old_woman_light_skin_tone:': u'\U0001F475\U0001F3FB', + u':old_woman_medium-dark_skin_tone:': u'\U0001F475\U0001F3FE', + u':old_woman_medium-light_skin_tone:': u'\U0001F475\U0001F3FC', + u':old_woman_medium_skin_tone:': u'\U0001F475\U0001F3FD', + u':older_person:': u'\U0001F9D3', + u':older_person_dark_skin_tone:': u'\U0001F9D3\U0001F3FF', + u':older_person_light_skin_tone:': u'\U0001F9D3\U0001F3FB', + u':older_person_medium-dark_skin_tone:': u'\U0001F9D3\U0001F3FE', + u':older_person_medium-light_skin_tone:': u'\U0001F9D3\U0001F3FC', + u':older_person_medium_skin_tone:': u'\U0001F9D3\U0001F3FD', + u':olive:': u'\U0001FAD2', + u':om:': u'\U0001F549', + u':oncoming_automobile:': u'\U0001F698', + u':oncoming_bus:': u'\U0001F68D', + u':oncoming_fist:': u'\U0001F44A', + u':oncoming_fist_dark_skin_tone:': u'\U0001F44A\U0001F3FF', + u':oncoming_fist_light_skin_tone:': u'\U0001F44A\U0001F3FB', + u':oncoming_fist_medium-dark_skin_tone:': u'\U0001F44A\U0001F3FE', + u':oncoming_fist_medium-light_skin_tone:': u'\U0001F44A\U0001F3FC', + u':oncoming_fist_medium_skin_tone:': u'\U0001F44A\U0001F3FD', + u':oncoming_police_car:': u'\U0001F694', + u':oncoming_taxi:': u'\U0001F696', + u':one-piece_swimsuit:': u'\U0001FA71', + u':one-thirty:': u'\U0001F55C', + u':one_o’clock:': u'\U0001F550', + u':onion:': u'\U0001F9C5', + u':open_book:': u'\U0001F4D6', + u':open_file_folder:': u'\U0001F4C2', + u':open_hands:': u'\U0001F450', + u':open_hands_dark_skin_tone:': u'\U0001F450\U0001F3FF', + u':open_hands_light_skin_tone:': u'\U0001F450\U0001F3FB', + u':open_hands_medium-dark_skin_tone:': u'\U0001F450\U0001F3FE', + u':open_hands_medium-light_skin_tone:': u'\U0001F450\U0001F3FC', + u':open_hands_medium_skin_tone:': u'\U0001F450\U0001F3FD', + u':open_mailbox_with_lowered_flag:': u'\U0001F4ED', + u':open_mailbox_with_raised_flag:': u'\U0001F4EC', + u':optical_disk:': u'\U0001F4BF', + u':orange_book:': u'\U0001F4D9', + u':orange_circle:': u'\U0001F7E0', + u':orange_heart:': u'\U0001F9E1', + u':orange_square:': u'\U0001F7E7', + u':orangutan:': u'\U0001F9A7', + u':orthodox_cross:': u'\U00002626', + u':otter:': u'\U0001F9A6', + u':outbox_tray:': u'\U0001F4E4', + u':owl:': u'\U0001F989', + u':ox:': u'\U0001F402', + u':oyster:': u'\U0001F9AA', + u':package:': u'\U0001F4E6', + u':page_facing_up:': u'\U0001F4C4', + u':page_with_curl:': u'\U0001F4C3', + u':pager:': u'\U0001F4DF', + u':paintbrush:': u'\U0001F58C', + u':palm_tree:': u'\U0001F334', + u':palms_up_together:': u'\U0001F932', + u':palms_up_together_dark_skin_tone:': u'\U0001F932\U0001F3FF', + u':palms_up_together_light_skin_tone:': u'\U0001F932\U0001F3FB', + u':palms_up_together_medium-dark_skin_tone:': u'\U0001F932\U0001F3FE', + u':palms_up_together_medium-light_skin_tone:': u'\U0001F932\U0001F3FC', + u':palms_up_together_medium_skin_tone:': u'\U0001F932\U0001F3FD', + u':pancakes:': u'\U0001F95E', + u':panda:': u'\U0001F43C', + u':paperclip:': u'\U0001F4CE', + u':parachute:': u'\U0001FA82', + u':parrot:': u'\U0001F99C', + u':part_alternation_mark:': u'\U0000303D', + u':party_popper:': u'\U0001F389', + u':partying_face:': u'\U0001F973', + u':passenger_ship:': u'\U0001F6F3', + u':passport_control:': u'\U0001F6C2', + u':pause_button:': u'\U000023F8', + u':paw_prints:': u'\U0001F43E', + u':peace_symbol:': u'\U0000262E', + u':peach:': u'\U0001F351', + u':peacock:': u'\U0001F99A', + u':peanuts:': u'\U0001F95C', + u':pear:': u'\U0001F350', + u':pen:': u'\U0001F58A', + u':pencil:': u'\U0000270F', + u':penguin:': u'\U0001F427', + u':pensive_face:': u'\U0001F614', + u':people_holding_hands:': u'\U0001F9D1\U0000200D\U0001F91D\U0000200D\U0001F9D1', + u':people_holding_hands_dark_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F91D\U0000200D\U0001F9D1\U0001F3FF', + u':people_holding_hands_dark_skin_tone_light_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F91D\U0000200D\U0001F9D1\U0001F3FB', + u':people_holding_hands_dark_skin_tone_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F91D\U0000200D\U0001F9D1\U0001F3FE', + u':people_holding_hands_dark_skin_tone_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F91D\U0000200D\U0001F9D1\U0001F3FC', + u':people_holding_hands_dark_skin_tone_medium_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F91D\U0000200D\U0001F9D1\U0001F3FD', + u':people_holding_hands_light_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F91D\U0000200D\U0001F9D1\U0001F3FB', + u':people_holding_hands_light_skin_tone_dark_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F91D\U0000200D\U0001F9D1\U0001F3FF', + u':people_holding_hands_light_skin_tone_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F91D\U0000200D\U0001F9D1\U0001F3FE', + u':people_holding_hands_light_skin_tone_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F91D\U0000200D\U0001F9D1\U0001F3FC', + u':people_holding_hands_light_skin_tone_medium_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F91D\U0000200D\U0001F9D1\U0001F3FD', + u':people_holding_hands_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F91D\U0000200D\U0001F9D1\U0001F3FE', + u':people_holding_hands_medium-dark_skin_tone_dark_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F91D\U0000200D\U0001F9D1\U0001F3FF', + u':people_holding_hands_medium-dark_skin_tone_light_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F91D\U0000200D\U0001F9D1\U0001F3FB', + u':people_holding_hands_medium-dark_skin_tone_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F91D\U0000200D\U0001F9D1\U0001F3FC', + u':people_holding_hands_medium-dark_skin_tone_medium_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F91D\U0000200D\U0001F9D1\U0001F3FD', + u':people_holding_hands_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F91D\U0000200D\U0001F9D1\U0001F3FC', + u':people_holding_hands_medium-light_skin_tone_dark_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F91D\U0000200D\U0001F9D1\U0001F3FF', + u':people_holding_hands_medium-light_skin_tone_light_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F91D\U0000200D\U0001F9D1\U0001F3FB', + u':people_holding_hands_medium-light_skin_tone_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F91D\U0000200D\U0001F9D1\U0001F3FE', + u':people_holding_hands_medium-light_skin_tone_medium_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F91D\U0000200D\U0001F9D1\U0001F3FD', + u':people_holding_hands_medium_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F91D\U0000200D\U0001F9D1\U0001F3FD', + u':people_holding_hands_medium_skin_tone_dark_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F91D\U0000200D\U0001F9D1\U0001F3FF', + u':people_holding_hands_medium_skin_tone_light_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F91D\U0000200D\U0001F9D1\U0001F3FB', + u':people_holding_hands_medium_skin_tone_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F91D\U0000200D\U0001F9D1\U0001F3FE', + u':people_holding_hands_medium_skin_tone_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F91D\U0000200D\U0001F9D1\U0001F3FC', + u':people_hugging:': u'\U0001FAC2', + u':people_with_bunny_ears:': u'\U0001F46F', + u':people_wrestling:': u'\U0001F93C', + u':performing_arts:': u'\U0001F3AD', + u':persevering_face:': u'\U0001F623', + u':person:': u'\U0001F9D1', + u':person_bald:': u'\U0001F9D1\U0000200D\U0001F9B2', + u':person_beard:': u'\U0001F9D4', + u':person_biking:': u'\U0001F6B4', + u':person_biking_dark_skin_tone:': u'\U0001F6B4\U0001F3FF', + u':person_biking_light_skin_tone:': u'\U0001F6B4\U0001F3FB', + u':person_biking_medium-dark_skin_tone:': u'\U0001F6B4\U0001F3FE', + u':person_biking_medium-light_skin_tone:': u'\U0001F6B4\U0001F3FC', + u':person_biking_medium_skin_tone:': u'\U0001F6B4\U0001F3FD', + u':person_blond_hair:': u'\U0001F471', + u':person_bouncing_ball:': u'\U000026F9', + u':person_bouncing_ball_dark_skin_tone:': u'\U000026F9\U0001F3FF', + u':person_bouncing_ball_light_skin_tone:': u'\U000026F9\U0001F3FB', + u':person_bouncing_ball_medium-dark_skin_tone:': u'\U000026F9\U0001F3FE', + u':person_bouncing_ball_medium-light_skin_tone:': u'\U000026F9\U0001F3FC', + u':person_bouncing_ball_medium_skin_tone:': u'\U000026F9\U0001F3FD', + u':person_bowing:': u'\U0001F647', + u':person_bowing_dark_skin_tone:': u'\U0001F647\U0001F3FF', + u':person_bowing_light_skin_tone:': u'\U0001F647\U0001F3FB', + u':person_bowing_medium-dark_skin_tone:': u'\U0001F647\U0001F3FE', + u':person_bowing_medium-light_skin_tone:': u'\U0001F647\U0001F3FC', + u':person_bowing_medium_skin_tone:': u'\U0001F647\U0001F3FD', + u':person_cartwheeling:': u'\U0001F938', + u':person_cartwheeling_dark_skin_tone:': u'\U0001F938\U0001F3FF', + u':person_cartwheeling_light_skin_tone:': u'\U0001F938\U0001F3FB', + u':person_cartwheeling_medium-dark_skin_tone:': u'\U0001F938\U0001F3FE', + u':person_cartwheeling_medium-light_skin_tone:': u'\U0001F938\U0001F3FC', + u':person_cartwheeling_medium_skin_tone:': u'\U0001F938\U0001F3FD', + u':person_climbing:': u'\U0001F9D7', + u':person_climbing_dark_skin_tone:': u'\U0001F9D7\U0001F3FF', + u':person_climbing_light_skin_tone:': u'\U0001F9D7\U0001F3FB', + u':person_climbing_medium-dark_skin_tone:': u'\U0001F9D7\U0001F3FE', + u':person_climbing_medium-light_skin_tone:': u'\U0001F9D7\U0001F3FC', + u':person_climbing_medium_skin_tone:': u'\U0001F9D7\U0001F3FD', + u':person_curly_hair:': u'\U0001F9D1\U0000200D\U0001F9B1', + u':person_dark_skin_tone:': u'\U0001F9D1\U0001F3FF', + u':person_dark_skin_tone_bald:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F9B2', + u':person_dark_skin_tone_beard:': u'\U0001F9D4\U0001F3FF', + u':person_dark_skin_tone_blond_hair:': u'\U0001F471\U0001F3FF', + u':person_dark_skin_tone_curly_hair:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F9B1', + u':person_dark_skin_tone_red_hair:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F9B0', + u':person_dark_skin_tone_white_hair:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F9B3', + u':person_facepalming:': u'\U0001F926', + u':person_facepalming_dark_skin_tone:': u'\U0001F926\U0001F3FF', + u':person_facepalming_light_skin_tone:': u'\U0001F926\U0001F3FB', + u':person_facepalming_medium-dark_skin_tone:': u'\U0001F926\U0001F3FE', + u':person_facepalming_medium-light_skin_tone:': u'\U0001F926\U0001F3FC', + u':person_facepalming_medium_skin_tone:': u'\U0001F926\U0001F3FD', + u':person_feeding_baby:': u'\U0001F9D1\U0000200D\U0001F37C', + u':person_feeding_baby_dark_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F37C', + u':person_feeding_baby_light_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F37C', + u':person_feeding_baby_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F37C', + u':person_feeding_baby_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F37C', + u':person_feeding_baby_medium_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F37C', + u':person_fencing:': u'\U0001F93A', + u':person_frowning:': u'\U0001F64D', + u':person_frowning_dark_skin_tone:': u'\U0001F64D\U0001F3FF', + u':person_frowning_light_skin_tone:': u'\U0001F64D\U0001F3FB', + u':person_frowning_medium-dark_skin_tone:': u'\U0001F64D\U0001F3FE', + u':person_frowning_medium-light_skin_tone:': u'\U0001F64D\U0001F3FC', + u':person_frowning_medium_skin_tone:': u'\U0001F64D\U0001F3FD', + u':person_gesturing_NO:': u'\U0001F645', + u':person_gesturing_NO_dark_skin_tone:': u'\U0001F645\U0001F3FF', + u':person_gesturing_NO_light_skin_tone:': u'\U0001F645\U0001F3FB', + u':person_gesturing_NO_medium-dark_skin_tone:': u'\U0001F645\U0001F3FE', + u':person_gesturing_NO_medium-light_skin_tone:': u'\U0001F645\U0001F3FC', + u':person_gesturing_NO_medium_skin_tone:': u'\U0001F645\U0001F3FD', + u':person_gesturing_OK:': u'\U0001F646', + u':person_gesturing_OK_dark_skin_tone:': u'\U0001F646\U0001F3FF', + u':person_gesturing_OK_light_skin_tone:': u'\U0001F646\U0001F3FB', + u':person_gesturing_OK_medium-dark_skin_tone:': u'\U0001F646\U0001F3FE', + u':person_gesturing_OK_medium-light_skin_tone:': u'\U0001F646\U0001F3FC', + u':person_gesturing_OK_medium_skin_tone:': u'\U0001F646\U0001F3FD', + u':person_getting_haircut:': u'\U0001F487', + u':person_getting_haircut_dark_skin_tone:': u'\U0001F487\U0001F3FF', + u':person_getting_haircut_light_skin_tone:': u'\U0001F487\U0001F3FB', + u':person_getting_haircut_medium-dark_skin_tone:': u'\U0001F487\U0001F3FE', + u':person_getting_haircut_medium-light_skin_tone:': u'\U0001F487\U0001F3FC', + u':person_getting_haircut_medium_skin_tone:': u'\U0001F487\U0001F3FD', + u':person_getting_massage:': u'\U0001F486', + u':person_getting_massage_dark_skin_tone:': u'\U0001F486\U0001F3FF', + u':person_getting_massage_light_skin_tone:': u'\U0001F486\U0001F3FB', + u':person_getting_massage_medium-dark_skin_tone:': u'\U0001F486\U0001F3FE', + u':person_getting_massage_medium-light_skin_tone:': u'\U0001F486\U0001F3FC', + u':person_getting_massage_medium_skin_tone:': u'\U0001F486\U0001F3FD', + u':person_golfing:': u'\U0001F3CC', + u':person_golfing_dark_skin_tone:': u'\U0001F3CC\U0001F3FF', + u':person_golfing_light_skin_tone:': u'\U0001F3CC\U0001F3FB', + u':person_golfing_medium-dark_skin_tone:': u'\U0001F3CC\U0001F3FE', + u':person_golfing_medium-light_skin_tone:': u'\U0001F3CC\U0001F3FC', + u':person_golfing_medium_skin_tone:': u'\U0001F3CC\U0001F3FD', + u':person_in_bed:': u'\U0001F6CC', + u':person_in_bed_dark_skin_tone:': u'\U0001F6CC\U0001F3FF', + u':person_in_bed_light_skin_tone:': u'\U0001F6CC\U0001F3FB', + u':person_in_bed_medium-dark_skin_tone:': u'\U0001F6CC\U0001F3FE', + u':person_in_bed_medium-light_skin_tone:': u'\U0001F6CC\U0001F3FC', + u':person_in_bed_medium_skin_tone:': u'\U0001F6CC\U0001F3FD', + u':person_in_lotus_position:': u'\U0001F9D8', + u':person_in_lotus_position_dark_skin_tone:': u'\U0001F9D8\U0001F3FF', + u':person_in_lotus_position_light_skin_tone:': u'\U0001F9D8\U0001F3FB', + u':person_in_lotus_position_medium-dark_skin_tone:': u'\U0001F9D8\U0001F3FE', + u':person_in_lotus_position_medium-light_skin_tone:': u'\U0001F9D8\U0001F3FC', + u':person_in_lotus_position_medium_skin_tone:': u'\U0001F9D8\U0001F3FD', + u':person_in_manual_wheelchair:': u'\U0001F9D1\U0000200D\U0001F9BD', + u':person_in_manual_wheelchair_dark_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F9BD', + u':person_in_manual_wheelchair_light_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F9BD', + u':person_in_manual_wheelchair_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F9BD', + u':person_in_manual_wheelchair_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F9BD', + u':person_in_manual_wheelchair_medium_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F9BD', + u':person_in_motorized_wheelchair:': u'\U0001F9D1\U0000200D\U0001F9BC', + u':person_in_motorized_wheelchair_dark_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F9BC', + u':person_in_motorized_wheelchair_light_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F9BC', + u':person_in_motorized_wheelchair_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F9BC', + u':person_in_motorized_wheelchair_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F9BC', + u':person_in_motorized_wheelchair_medium_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F9BC', + u':person_in_steamy_room:': u'\U0001F9D6', + u':person_in_steamy_room_dark_skin_tone:': u'\U0001F9D6\U0001F3FF', + u':person_in_steamy_room_light_skin_tone:': u'\U0001F9D6\U0001F3FB', + u':person_in_steamy_room_medium-dark_skin_tone:': u'\U0001F9D6\U0001F3FE', + u':person_in_steamy_room_medium-light_skin_tone:': u'\U0001F9D6\U0001F3FC', + u':person_in_steamy_room_medium_skin_tone:': u'\U0001F9D6\U0001F3FD', + u':person_in_suit_levitating:': u'\U0001F574', + u':person_in_suit_levitating_dark_skin_tone:': u'\U0001F574\U0001F3FF', + u':person_in_suit_levitating_light_skin_tone:': u'\U0001F574\U0001F3FB', + u':person_in_suit_levitating_medium-dark_skin_tone:': u'\U0001F574\U0001F3FE', + u':person_in_suit_levitating_medium-light_skin_tone:': u'\U0001F574\U0001F3FC', + u':person_in_suit_levitating_medium_skin_tone:': u'\U0001F574\U0001F3FD', + u':person_in_tuxedo:': u'\U0001F935', + u':person_in_tuxedo_dark_skin_tone:': u'\U0001F935\U0001F3FF', + u':person_in_tuxedo_light_skin_tone:': u'\U0001F935\U0001F3FB', + u':person_in_tuxedo_medium-dark_skin_tone:': u'\U0001F935\U0001F3FE', + u':person_in_tuxedo_medium-light_skin_tone:': u'\U0001F935\U0001F3FC', + u':person_in_tuxedo_medium_skin_tone:': u'\U0001F935\U0001F3FD', + u':person_juggling:': u'\U0001F939', + u':person_juggling_dark_skin_tone:': u'\U0001F939\U0001F3FF', + u':person_juggling_light_skin_tone:': u'\U0001F939\U0001F3FB', + u':person_juggling_medium-dark_skin_tone:': u'\U0001F939\U0001F3FE', + u':person_juggling_medium-light_skin_tone:': u'\U0001F939\U0001F3FC', + u':person_juggling_medium_skin_tone:': u'\U0001F939\U0001F3FD', + u':person_kneeling:': u'\U0001F9CE', + u':person_kneeling_dark_skin_tone:': u'\U0001F9CE\U0001F3FF', + u':person_kneeling_light_skin_tone:': u'\U0001F9CE\U0001F3FB', + u':person_kneeling_medium-dark_skin_tone:': u'\U0001F9CE\U0001F3FE', + u':person_kneeling_medium-light_skin_tone:': u'\U0001F9CE\U0001F3FC', + u':person_kneeling_medium_skin_tone:': u'\U0001F9CE\U0001F3FD', + u':person_lifting_weights:': u'\U0001F3CB', + u':person_lifting_weights_dark_skin_tone:': u'\U0001F3CB\U0001F3FF', + u':person_lifting_weights_light_skin_tone:': u'\U0001F3CB\U0001F3FB', + u':person_lifting_weights_medium-dark_skin_tone:': u'\U0001F3CB\U0001F3FE', + u':person_lifting_weights_medium-light_skin_tone:': u'\U0001F3CB\U0001F3FC', + u':person_lifting_weights_medium_skin_tone:': u'\U0001F3CB\U0001F3FD', + u':person_light_skin_tone:': u'\U0001F9D1\U0001F3FB', + u':person_light_skin_tone_bald:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F9B2', + u':person_light_skin_tone_beard:': u'\U0001F9D4\U0001F3FB', + u':person_light_skin_tone_blond_hair:': u'\U0001F471\U0001F3FB', + u':person_light_skin_tone_curly_hair:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F9B1', + u':person_light_skin_tone_red_hair:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F9B0', + u':person_light_skin_tone_white_hair:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F9B3', + u':person_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FE', + u':person_medium-dark_skin_tone_bald:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F9B2', + u':person_medium-dark_skin_tone_beard:': u'\U0001F9D4\U0001F3FE', + u':person_medium-dark_skin_tone_blond_hair:': u'\U0001F471\U0001F3FE', + u':person_medium-dark_skin_tone_curly_hair:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F9B1', + u':person_medium-dark_skin_tone_red_hair:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F9B0', + u':person_medium-dark_skin_tone_white_hair:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F9B3', + u':person_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FC', + u':person_medium-light_skin_tone_bald:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F9B2', + u':person_medium-light_skin_tone_beard:': u'\U0001F9D4\U0001F3FC', + u':person_medium-light_skin_tone_blond_hair:': u'\U0001F471\U0001F3FC', + u':person_medium-light_skin_tone_curly_hair:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F9B1', + u':person_medium-light_skin_tone_red_hair:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F9B0', + u':person_medium-light_skin_tone_white_hair:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F9B3', + u':person_medium_skin_tone:': u'\U0001F9D1\U0001F3FD', + u':person_medium_skin_tone_bald:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F9B2', + u':person_medium_skin_tone_beard:': u'\U0001F9D4\U0001F3FD', + u':person_medium_skin_tone_blond_hair:': u'\U0001F471\U0001F3FD', + u':person_medium_skin_tone_curly_hair:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F9B1', + u':person_medium_skin_tone_red_hair:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F9B0', + u':person_medium_skin_tone_white_hair:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F9B3', + u':person_mountain_biking:': u'\U0001F6B5', + u':person_mountain_biking_dark_skin_tone:': u'\U0001F6B5\U0001F3FF', + u':person_mountain_biking_light_skin_tone:': u'\U0001F6B5\U0001F3FB', + u':person_mountain_biking_medium-dark_skin_tone:': u'\U0001F6B5\U0001F3FE', + u':person_mountain_biking_medium-light_skin_tone:': u'\U0001F6B5\U0001F3FC', + u':person_mountain_biking_medium_skin_tone:': u'\U0001F6B5\U0001F3FD', + u':person_playing_handball:': u'\U0001F93E', + u':person_playing_handball_dark_skin_tone:': u'\U0001F93E\U0001F3FF', + u':person_playing_handball_light_skin_tone:': u'\U0001F93E\U0001F3FB', + u':person_playing_handball_medium-dark_skin_tone:': u'\U0001F93E\U0001F3FE', + u':person_playing_handball_medium-light_skin_tone:': u'\U0001F93E\U0001F3FC', + u':person_playing_handball_medium_skin_tone:': u'\U0001F93E\U0001F3FD', + u':person_playing_water_polo:': u'\U0001F93D', + u':person_playing_water_polo_dark_skin_tone:': u'\U0001F93D\U0001F3FF', + u':person_playing_water_polo_light_skin_tone:': u'\U0001F93D\U0001F3FB', + u':person_playing_water_polo_medium-dark_skin_tone:': u'\U0001F93D\U0001F3FE', + u':person_playing_water_polo_medium-light_skin_tone:': u'\U0001F93D\U0001F3FC', + u':person_playing_water_polo_medium_skin_tone:': u'\U0001F93D\U0001F3FD', + u':person_pouting:': u'\U0001F64E', + u':person_pouting_dark_skin_tone:': u'\U0001F64E\U0001F3FF', + u':person_pouting_light_skin_tone:': u'\U0001F64E\U0001F3FB', + u':person_pouting_medium-dark_skin_tone:': u'\U0001F64E\U0001F3FE', + u':person_pouting_medium-light_skin_tone:': u'\U0001F64E\U0001F3FC', + u':person_pouting_medium_skin_tone:': u'\U0001F64E\U0001F3FD', + u':person_raising_hand:': u'\U0001F64B', + u':person_raising_hand_dark_skin_tone:': u'\U0001F64B\U0001F3FF', + u':person_raising_hand_light_skin_tone:': u'\U0001F64B\U0001F3FB', + u':person_raising_hand_medium-dark_skin_tone:': u'\U0001F64B\U0001F3FE', + u':person_raising_hand_medium-light_skin_tone:': u'\U0001F64B\U0001F3FC', + u':person_raising_hand_medium_skin_tone:': u'\U0001F64B\U0001F3FD', + u':person_red_hair:': u'\U0001F9D1\U0000200D\U0001F9B0', + u':person_rowing_boat:': u'\U0001F6A3', + u':person_rowing_boat_dark_skin_tone:': u'\U0001F6A3\U0001F3FF', + u':person_rowing_boat_light_skin_tone:': u'\U0001F6A3\U0001F3FB', + u':person_rowing_boat_medium-dark_skin_tone:': u'\U0001F6A3\U0001F3FE', + u':person_rowing_boat_medium-light_skin_tone:': u'\U0001F6A3\U0001F3FC', + u':person_rowing_boat_medium_skin_tone:': u'\U0001F6A3\U0001F3FD', + u':person_running:': u'\U0001F3C3', + u':person_running_dark_skin_tone:': u'\U0001F3C3\U0001F3FF', + u':person_running_light_skin_tone:': u'\U0001F3C3\U0001F3FB', + u':person_running_medium-dark_skin_tone:': u'\U0001F3C3\U0001F3FE', + u':person_running_medium-light_skin_tone:': u'\U0001F3C3\U0001F3FC', + u':person_running_medium_skin_tone:': u'\U0001F3C3\U0001F3FD', + u':person_shrugging:': u'\U0001F937', + u':person_shrugging_dark_skin_tone:': u'\U0001F937\U0001F3FF', + u':person_shrugging_light_skin_tone:': u'\U0001F937\U0001F3FB', + u':person_shrugging_medium-dark_skin_tone:': u'\U0001F937\U0001F3FE', + u':person_shrugging_medium-light_skin_tone:': u'\U0001F937\U0001F3FC', + u':person_shrugging_medium_skin_tone:': u'\U0001F937\U0001F3FD', + u':person_standing:': u'\U0001F9CD', + u':person_standing_dark_skin_tone:': u'\U0001F9CD\U0001F3FF', + u':person_standing_light_skin_tone:': u'\U0001F9CD\U0001F3FB', + u':person_standing_medium-dark_skin_tone:': u'\U0001F9CD\U0001F3FE', + u':person_standing_medium-light_skin_tone:': u'\U0001F9CD\U0001F3FC', + u':person_standing_medium_skin_tone:': u'\U0001F9CD\U0001F3FD', + u':person_surfing:': u'\U0001F3C4', + u':person_surfing_dark_skin_tone:': u'\U0001F3C4\U0001F3FF', + u':person_surfing_light_skin_tone:': u'\U0001F3C4\U0001F3FB', + u':person_surfing_medium-dark_skin_tone:': u'\U0001F3C4\U0001F3FE', + u':person_surfing_medium-light_skin_tone:': u'\U0001F3C4\U0001F3FC', + u':person_surfing_medium_skin_tone:': u'\U0001F3C4\U0001F3FD', + u':person_swimming:': u'\U0001F3CA', + u':person_swimming_dark_skin_tone:': u'\U0001F3CA\U0001F3FF', + u':person_swimming_light_skin_tone:': u'\U0001F3CA\U0001F3FB', + u':person_swimming_medium-dark_skin_tone:': u'\U0001F3CA\U0001F3FE', + u':person_swimming_medium-light_skin_tone:': u'\U0001F3CA\U0001F3FC', + u':person_swimming_medium_skin_tone:': u'\U0001F3CA\U0001F3FD', + u':person_taking_bath:': u'\U0001F6C0', + u':person_taking_bath_dark_skin_tone:': u'\U0001F6C0\U0001F3FF', + u':person_taking_bath_light_skin_tone:': u'\U0001F6C0\U0001F3FB', + u':person_taking_bath_medium-dark_skin_tone:': u'\U0001F6C0\U0001F3FE', + u':person_taking_bath_medium-light_skin_tone:': u'\U0001F6C0\U0001F3FC', + u':person_taking_bath_medium_skin_tone:': u'\U0001F6C0\U0001F3FD', + u':person_tipping_hand:': u'\U0001F481', + u':person_tipping_hand_dark_skin_tone:': u'\U0001F481\U0001F3FF', + u':person_tipping_hand_light_skin_tone:': u'\U0001F481\U0001F3FB', + u':person_tipping_hand_medium-dark_skin_tone:': u'\U0001F481\U0001F3FE', + u':person_tipping_hand_medium-light_skin_tone:': u'\U0001F481\U0001F3FC', + u':person_tipping_hand_medium_skin_tone:': u'\U0001F481\U0001F3FD', + u':person_walking:': u'\U0001F6B6', + u':person_walking_dark_skin_tone:': u'\U0001F6B6\U0001F3FF', + u':person_walking_light_skin_tone:': u'\U0001F6B6\U0001F3FB', + u':person_walking_medium-dark_skin_tone:': u'\U0001F6B6\U0001F3FE', + u':person_walking_medium-light_skin_tone:': u'\U0001F6B6\U0001F3FC', + u':person_walking_medium_skin_tone:': u'\U0001F6B6\U0001F3FD', + u':person_wearing_turban:': u'\U0001F473', + u':person_wearing_turban_dark_skin_tone:': u'\U0001F473\U0001F3FF', + u':person_wearing_turban_light_skin_tone:': u'\U0001F473\U0001F3FB', + u':person_wearing_turban_medium-dark_skin_tone:': u'\U0001F473\U0001F3FE', + u':person_wearing_turban_medium-light_skin_tone:': u'\U0001F473\U0001F3FC', + u':person_wearing_turban_medium_skin_tone:': u'\U0001F473\U0001F3FD', + u':person_white_hair:': u'\U0001F9D1\U0000200D\U0001F9B3', + u':person_with_skullcap:': u'\U0001F472', + u':person_with_skullcap_dark_skin_tone:': u'\U0001F472\U0001F3FF', + u':person_with_skullcap_light_skin_tone:': u'\U0001F472\U0001F3FB', + u':person_with_skullcap_medium-dark_skin_tone:': u'\U0001F472\U0001F3FE', + u':person_with_skullcap_medium-light_skin_tone:': u'\U0001F472\U0001F3FC', + u':person_with_skullcap_medium_skin_tone:': u'\U0001F472\U0001F3FD', + u':person_with_veil:': u'\U0001F470', + u':person_with_veil_dark_skin_tone:': u'\U0001F470\U0001F3FF', + u':person_with_veil_light_skin_tone:': u'\U0001F470\U0001F3FB', + u':person_with_veil_medium-dark_skin_tone:': u'\U0001F470\U0001F3FE', + u':person_with_veil_medium-light_skin_tone:': u'\U0001F470\U0001F3FC', + u':person_with_veil_medium_skin_tone:': u'\U0001F470\U0001F3FD', + u':person_with_white_cane:': u'\U0001F9D1\U0000200D\U0001F9AF', + u':person_with_white_cane_dark_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F9AF', + u':person_with_white_cane_light_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F9AF', + u':person_with_white_cane_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F9AF', + u':person_with_white_cane_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F9AF', + u':person_with_white_cane_medium_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F9AF', + u':petri_dish:': u'\U0001F9EB', + u':pick:': u'\U000026CF', + u':pickup_truck:': u'\U0001F6FB', + u':pie:': u'\U0001F967', + u':pig:': u'\U0001F416', + u':pig_face:': u'\U0001F437', + u':pig_nose:': u'\U0001F43D', + u':pile_of_poo:': u'\U0001F4A9', + u':pill:': u'\U0001F48A', + u':pilot:': u'\U0001F9D1\U0000200D\U00002708\U0000FE0F', + u':pilot_dark_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U00002708\U0000FE0F', + u':pilot_light_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U00002708\U0000FE0F', + u':pilot_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U00002708\U0000FE0F', + u':pilot_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U00002708\U0000FE0F', + u':pilot_medium_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U00002708\U0000FE0F', + u':pinched_fingers:': u'\U0001F90C', + u':pinched_fingers_dark_skin_tone:': u'\U0001F90C\U0001F3FF', + u':pinched_fingers_light_skin_tone:': u'\U0001F90C\U0001F3FB', + u':pinched_fingers_medium-dark_skin_tone:': u'\U0001F90C\U0001F3FE', + u':pinched_fingers_medium-light_skin_tone:': u'\U0001F90C\U0001F3FC', + u':pinched_fingers_medium_skin_tone:': u'\U0001F90C\U0001F3FD', + u':pinching_hand:': u'\U0001F90F', + u':pinching_hand_dark_skin_tone:': u'\U0001F90F\U0001F3FF', + u':pinching_hand_light_skin_tone:': u'\U0001F90F\U0001F3FB', + u':pinching_hand_medium-dark_skin_tone:': u'\U0001F90F\U0001F3FE', + u':pinching_hand_medium-light_skin_tone:': u'\U0001F90F\U0001F3FC', + u':pinching_hand_medium_skin_tone:': u'\U0001F90F\U0001F3FD', + u':pine_decoration:': u'\U0001F38D', + u':pineapple:': u'\U0001F34D', + u':ping_pong:': u'\U0001F3D3', + u':pirate_flag:': u'\U0001F3F4\U0000200D\U00002620\U0000FE0F', + u':pizza:': u'\U0001F355', + u':piñata:': u'\U0001FA85', + u':placard:': u'\U0001FAA7', + u':place_of_worship:': u'\U0001F6D0', + u':play_button:': u'\U000025B6', + u':play_or_pause_button:': u'\U000023EF', + u':pleading_face:': u'\U0001F97A', + u':plunger:': u'\U0001FAA0', + u':plus:': u'\U00002795', + u':polar_bear:': u'\U0001F43B\U0000200D\U00002744\U0000FE0F', + u':police_car:': u'\U0001F693', + u':police_car_light:': u'\U0001F6A8', + u':police_officer:': u'\U0001F46E', + u':police_officer_dark_skin_tone:': u'\U0001F46E\U0001F3FF', + u':police_officer_light_skin_tone:': u'\U0001F46E\U0001F3FB', + u':police_officer_medium-dark_skin_tone:': u'\U0001F46E\U0001F3FE', + u':police_officer_medium-light_skin_tone:': u'\U0001F46E\U0001F3FC', + u':police_officer_medium_skin_tone:': u'\U0001F46E\U0001F3FD', + u':poodle:': u'\U0001F429', + u':pool_8_ball:': u'\U0001F3B1', + u':popcorn:': u'\U0001F37F', + u':post_office:': u'\U0001F3E4', + u':postal_horn:': u'\U0001F4EF', + u':postbox:': u'\U0001F4EE', + u':pot_of_food:': u'\U0001F372', + u':potable_water:': u'\U0001F6B0', + u':potato:': u'\U0001F954', + u':potted_plant:': u'\U0001FAB4', + u':poultry_leg:': u'\U0001F357', + u':pound_banknote:': u'\U0001F4B7', + u':pouting_cat:': u'\U0001F63E', + u':pouting_face:': u'\U0001F621', + u':prayer_beads:': u'\U0001F4FF', + u':pregnant_woman:': u'\U0001F930', + u':pregnant_woman_dark_skin_tone:': u'\U0001F930\U0001F3FF', + u':pregnant_woman_light_skin_tone:': u'\U0001F930\U0001F3FB', + u':pregnant_woman_medium-dark_skin_tone:': u'\U0001F930\U0001F3FE', + u':pregnant_woman_medium-light_skin_tone:': u'\U0001F930\U0001F3FC', + u':pregnant_woman_medium_skin_tone:': u'\U0001F930\U0001F3FD', + u':pretzel:': u'\U0001F968', + u':prince:': u'\U0001F934', + u':prince_dark_skin_tone:': u'\U0001F934\U0001F3FF', + u':prince_light_skin_tone:': u'\U0001F934\U0001F3FB', + u':prince_medium-dark_skin_tone:': u'\U0001F934\U0001F3FE', + u':prince_medium-light_skin_tone:': u'\U0001F934\U0001F3FC', + u':prince_medium_skin_tone:': u'\U0001F934\U0001F3FD', + u':princess:': u'\U0001F478', + u':princess_dark_skin_tone:': u'\U0001F478\U0001F3FF', + u':princess_light_skin_tone:': u'\U0001F478\U0001F3FB', + u':princess_medium-dark_skin_tone:': u'\U0001F478\U0001F3FE', + u':princess_medium-light_skin_tone:': u'\U0001F478\U0001F3FC', + u':princess_medium_skin_tone:': u'\U0001F478\U0001F3FD', + u':printer:': u'\U0001F5A8', + u':prohibited:': u'\U0001F6AB', + u':purple_circle:': u'\U0001F7E3', + u':purple_heart:': u'\U0001F49C', + u':purple_square:': u'\U0001F7EA', + u':purse:': u'\U0001F45B', + u':pushpin:': u'\U0001F4CC', + u':puzzle_piece:': u'\U0001F9E9', + u':rabbit:': u'\U0001F407', + u':rabbit_face:': u'\U0001F430', + u':raccoon:': u'\U0001F99D', + u':racing_car:': u'\U0001F3CE', + u':radio:': u'\U0001F4FB', + u':radio_button:': u'\U0001F518', + u':radioactive:': u'\U00002622', + u':railway_car:': u'\U0001F683', + u':railway_track:': u'\U0001F6E4', + u':rainbow:': u'\U0001F308', + u':rainbow_flag:': u'\U0001F3F3\U0000FE0F\U0000200D\U0001F308', + u':raised_back_of_hand:': u'\U0001F91A', + u':raised_back_of_hand_dark_skin_tone:': u'\U0001F91A\U0001F3FF', + u':raised_back_of_hand_light_skin_tone:': u'\U0001F91A\U0001F3FB', + u':raised_back_of_hand_medium-dark_skin_tone:': u'\U0001F91A\U0001F3FE', + u':raised_back_of_hand_medium-light_skin_tone:': u'\U0001F91A\U0001F3FC', + u':raised_back_of_hand_medium_skin_tone:': u'\U0001F91A\U0001F3FD', + u':raised_fist:': u'\U0000270A', + u':raised_fist_dark_skin_tone:': u'\U0000270A\U0001F3FF', + u':raised_fist_light_skin_tone:': u'\U0000270A\U0001F3FB', + u':raised_fist_medium-dark_skin_tone:': u'\U0000270A\U0001F3FE', + u':raised_fist_medium-light_skin_tone:': u'\U0000270A\U0001F3FC', + u':raised_fist_medium_skin_tone:': u'\U0000270A\U0001F3FD', + u':raised_hand:': u'\U0000270B', + u':raised_hand_dark_skin_tone:': u'\U0000270B\U0001F3FF', + u':raised_hand_light_skin_tone:': u'\U0000270B\U0001F3FB', + u':raised_hand_medium-dark_skin_tone:': u'\U0000270B\U0001F3FE', + u':raised_hand_medium-light_skin_tone:': u'\U0000270B\U0001F3FC', + u':raised_hand_medium_skin_tone:': u'\U0000270B\U0001F3FD', + u':raising_hands:': u'\U0001F64C', + u':raising_hands_dark_skin_tone:': u'\U0001F64C\U0001F3FF', + u':raising_hands_light_skin_tone:': u'\U0001F64C\U0001F3FB', + u':raising_hands_medium-dark_skin_tone:': u'\U0001F64C\U0001F3FE', + u':raising_hands_medium-light_skin_tone:': u'\U0001F64C\U0001F3FC', + u':raising_hands_medium_skin_tone:': u'\U0001F64C\U0001F3FD', + u':ram:': u'\U0001F40F', + u':rat:': u'\U0001F400', + u':razor:': u'\U0001FA92', + u':receipt:': u'\U0001F9FE', + u':record_button:': u'\U000023FA', + u':recycling_symbol:': u'\U0000267B', + u':red_apple:': u'\U0001F34E', + u':red_circle:': u'\U0001F534', + u':red_envelope:': u'\U0001F9E7', + u':red_exclamation_mark:': u'\U00002757', + u':red_hair:': u'\U0001F9B0', + u':red_heart:': u'\U00002764', + u':red_paper_lantern:': u'\U0001F3EE', + u':red_question_mark:': u'\U00002753', + u':red_square:': u'\U0001F7E5', + u':red_triangle_pointed_down:': u'\U0001F53B', + u':red_triangle_pointed_up:': u'\U0001F53A', + u':registered:': u'\U000000AE', + u':relieved_face:': u'\U0001F60C', + u':reminder_ribbon:': u'\U0001F397', + u':repeat_button:': u'\U0001F501', + u':repeat_single_button:': u'\U0001F502', + u':rescue_worker’s_helmet:': u'\U000026D1', + u':restroom:': u'\U0001F6BB', + u':reverse_button:': u'\U000025C0', + u':revolving_hearts:': u'\U0001F49E', + u':rhinoceros:': u'\U0001F98F', + u':ribbon:': u'\U0001F380', + u':rice_ball:': u'\U0001F359', + u':rice_cracker:': u'\U0001F358', + u':right-facing_fist:': u'\U0001F91C', + u':right-facing_fist_dark_skin_tone:': u'\U0001F91C\U0001F3FF', + u':right-facing_fist_light_skin_tone:': u'\U0001F91C\U0001F3FB', + u':right-facing_fist_medium-dark_skin_tone:': u'\U0001F91C\U0001F3FE', + u':right-facing_fist_medium-light_skin_tone:': u'\U0001F91C\U0001F3FC', + u':right-facing_fist_medium_skin_tone:': u'\U0001F91C\U0001F3FD', + u':right_anger_bubble:': u'\U0001F5EF', + u':right_arrow:': u'\U000027A1', + u':right_arrow_curving_down:': u'\U00002935', + u':right_arrow_curving_left:': u'\U000021A9', + u':right_arrow_curving_up:': u'\U00002934', + u':ring:': u'\U0001F48D', + u':ringed_planet:': u'\U0001FA90', + u':roasted_sweet_potato:': u'\U0001F360', + u':robot:': u'\U0001F916', + u':rock:': u'\U0001FAA8', + u':rocket:': u'\U0001F680', + u':roll_of_paper:': u'\U0001F9FB', + u':rolled-up_newspaper:': u'\U0001F5DE', + u':roller_coaster:': u'\U0001F3A2', + u':roller_skate:': u'\U0001F6FC', + u':rolling_on_the_floor_laughing:': u'\U0001F923', + u':rooster:': u'\U0001F413', + u':rose:': u'\U0001F339', + u':rosette:': u'\U0001F3F5', + u':round_pushpin:': u'\U0001F4CD', + u':rugby_football:': u'\U0001F3C9', + u':running_shirt:': u'\U0001F3BD', + u':running_shoe:': u'\U0001F45F', + u':sad_but_relieved_face:': u'\U0001F625', + u':safety_pin:': u'\U0001F9F7', + u':safety_vest:': u'\U0001F9BA', + u':sailboat:': u'\U000026F5', + u':sake:': u'\U0001F376', + u':salt:': u'\U0001F9C2', + u':sandwich:': u'\U0001F96A', + u':sari:': u'\U0001F97B', + u':satellite:': u'\U0001F6F0', + u':satellite_antenna:': u'\U0001F4E1', + u':sauropod:': u'\U0001F995', + u':saxophone:': u'\U0001F3B7', + u':scarf:': u'\U0001F9E3', + u':school:': u'\U0001F3EB', + u':scientist:': u'\U0001F9D1\U0000200D\U0001F52C', + u':scientist_dark_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F52C', + u':scientist_light_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F52C', + u':scientist_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F52C', + u':scientist_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F52C', + u':scientist_medium_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F52C', + u':scissors:': u'\U00002702', + u':scorpion:': u'\U0001F982', + u':screwdriver:': u'\U0001FA9B', + u':scroll:': u'\U0001F4DC', + u':seal:': u'\U0001F9AD', + u':seat:': u'\U0001F4BA', + u':see-no-evil_monkey:': u'\U0001F648', + u':seedling:': u'\U0001F331', + u':selfie:': u'\U0001F933', + u':selfie_dark_skin_tone:': u'\U0001F933\U0001F3FF', + u':selfie_light_skin_tone:': u'\U0001F933\U0001F3FB', + u':selfie_medium-dark_skin_tone:': u'\U0001F933\U0001F3FE', + u':selfie_medium-light_skin_tone:': u'\U0001F933\U0001F3FC', + u':selfie_medium_skin_tone:': u'\U0001F933\U0001F3FD', + u':service_dog:': u'\U0001F415\U0000200D\U0001F9BA', + u':seven-thirty:': u'\U0001F562', + u':seven_o’clock:': u'\U0001F556', + u':sewing_needle:': u'\U0001FAA1', + u':shallow_pan_of_food:': u'\U0001F958', + u':shamrock:': u'\U00002618', + u':shark:': u'\U0001F988', + u':shaved_ice:': u'\U0001F367', + u':sheaf_of_rice:': u'\U0001F33E', + u':shield:': u'\U0001F6E1', + u':shinto_shrine:': u'\U000026E9', + u':ship:': u'\U0001F6A2', + u':shooting_star:': u'\U0001F320', + u':shopping_bags:': u'\U0001F6CD', + u':shopping_cart:': u'\U0001F6D2', + u':shortcake:': u'\U0001F370', + u':shorts:': u'\U0001FA73', + u':shower:': u'\U0001F6BF', + u':shrimp:': u'\U0001F990', + u':shuffle_tracks_button:': u'\U0001F500', + u':shushing_face:': u'\U0001F92B', + u':sign_of_the_horns:': u'\U0001F918', + u':sign_of_the_horns_dark_skin_tone:': u'\U0001F918\U0001F3FF', + u':sign_of_the_horns_light_skin_tone:': u'\U0001F918\U0001F3FB', + u':sign_of_the_horns_medium-dark_skin_tone:': u'\U0001F918\U0001F3FE', + u':sign_of_the_horns_medium-light_skin_tone:': u'\U0001F918\U0001F3FC', + u':sign_of_the_horns_medium_skin_tone:': u'\U0001F918\U0001F3FD', + u':singer:': u'\U0001F9D1\U0000200D\U0001F3A4', + u':singer_dark_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F3A4', + u':singer_light_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F3A4', + u':singer_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F3A4', + u':singer_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F3A4', + u':singer_medium_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F3A4', + u':six-thirty:': u'\U0001F561', + u':six_o’clock:': u'\U0001F555', + u':skateboard:': u'\U0001F6F9', + u':skier:': u'\U000026F7', + u':skis:': u'\U0001F3BF', + u':skull:': u'\U0001F480', + u':skull_and_crossbones:': u'\U00002620', + u':skunk:': u'\U0001F9A8', + u':sled:': u'\U0001F6F7', + u':sleeping_face:': u'\U0001F634', + u':sleepy_face:': u'\U0001F62A', + u':slightly_frowning_face:': u'\U0001F641', + u':slightly_smiling_face:': u'\U0001F642', + u':slot_machine:': u'\U0001F3B0', + u':sloth:': u'\U0001F9A5', + u':small_airplane:': u'\U0001F6E9', + u':small_blue_diamond:': u'\U0001F539', + u':small_orange_diamond:': u'\U0001F538', + u':smiling_cat_with_heart-eyes:': u'\U0001F63B', + u':smiling_face:': u'\U0000263A', + u':smiling_face_with_halo:': u'\U0001F607', + u':smiling_face_with_heart-eyes:': u'\U0001F60D', + u':smiling_face_with_hearts:': u'\U0001F970', + u':smiling_face_with_horns:': u'\U0001F608', + u':smiling_face_with_smiling_eyes:': u'\U0001F60A', + u':smiling_face_with_sunglasses:': u'\U0001F60E', + u':smiling_face_with_tear:': u'\U0001F972', + u':smirking_face:': u'\U0001F60F', + u':snail:': u'\U0001F40C', + u':snake:': u'\U0001F40D', + u':sneezing_face:': u'\U0001F927', + u':snow-capped_mountain:': u'\U0001F3D4', + u':snowboarder:': u'\U0001F3C2', + u':snowboarder_dark_skin_tone:': u'\U0001F3C2\U0001F3FF', + u':snowboarder_light_skin_tone:': u'\U0001F3C2\U0001F3FB', + u':snowboarder_medium-dark_skin_tone:': u'\U0001F3C2\U0001F3FE', + u':snowboarder_medium-light_skin_tone:': u'\U0001F3C2\U0001F3FC', + u':snowboarder_medium_skin_tone:': u'\U0001F3C2\U0001F3FD', + u':snowflake:': u'\U00002744', + u':snowman:': u'\U00002603', + u':snowman_without_snow:': u'\U000026C4', + u':soap:': u'\U0001F9FC', + u':soccer_ball:': u'\U000026BD', + u':socks:': u'\U0001F9E6', + u':soft_ice_cream:': u'\U0001F366', + u':softball:': u'\U0001F94E', + u':spade_suit:': u'\U00002660', + u':spaghetti:': u'\U0001F35D', + u':sparkle:': u'\U00002747', + u':sparkler:': u'\U0001F387', + u':sparkles:': u'\U00002728', + u':sparkling_heart:': u'\U0001F496', + u':speak-no-evil_monkey:': u'\U0001F64A', + u':speaker_high_volume:': u'\U0001F50A', + u':speaker_low_volume:': u'\U0001F508', + u':speaker_medium_volume:': u'\U0001F509', + u':speaking_head:': u'\U0001F5E3', + u':speech_balloon:': u'\U0001F4AC', + u':speedboat:': u'\U0001F6A4', + u':spider:': u'\U0001F577', + u':spider_web:': u'\U0001F578', + u':spiral_calendar:': u'\U0001F5D3', + u':spiral_notepad:': u'\U0001F5D2', + u':spiral_shell:': u'\U0001F41A', + u':sponge:': u'\U0001F9FD', + u':spoon:': u'\U0001F944', + u':sport_utility_vehicle:': u'\U0001F699', + u':sports_medal:': u'\U0001F3C5', + u':spouting_whale:': u'\U0001F433', + u':squid:': u'\U0001F991', + u':squinting_face_with_tongue:': u'\U0001F61D', + u':stadium:': u'\U0001F3DF', + u':star:': u'\U00002B50', + u':star-struck:': u'\U0001F929', + u':star_and_crescent:': u'\U0000262A', + u':star_of_David:': u'\U00002721', + u':station:': u'\U0001F689', + u':steaming_bowl:': u'\U0001F35C', + u':stethoscope:': u'\U0001FA7A', + u':stop_button:': u'\U000023F9', + u':stop_sign:': u'\U0001F6D1', + u':stopwatch:': u'\U000023F1', + u':straight_ruler:': u'\U0001F4CF', + u':strawberry:': u'\U0001F353', + u':student:': u'\U0001F9D1\U0000200D\U0001F393', + u':student_dark_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F393', + u':student_light_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F393', + u':student_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F393', + u':student_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F393', + u':student_medium_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F393', + u':studio_microphone:': u'\U0001F399', + u':stuffed_flatbread:': u'\U0001F959', + u':sun:': u'\U00002600', + u':sun_behind_cloud:': u'\U000026C5', + u':sun_behind_large_cloud:': u'\U0001F325', + u':sun_behind_rain_cloud:': u'\U0001F326', + u':sun_behind_small_cloud:': u'\U0001F324', + u':sun_with_face:': u'\U0001F31E', + u':sunflower:': u'\U0001F33B', + u':sunglasses:': u'\U0001F576', + u':sunrise:': u'\U0001F305', + u':sunrise_over_mountains:': u'\U0001F304', + u':sunset:': u'\U0001F307', + u':superhero:': u'\U0001F9B8', + u':superhero_dark_skin_tone:': u'\U0001F9B8\U0001F3FF', + u':superhero_light_skin_tone:': u'\U0001F9B8\U0001F3FB', + u':superhero_medium-dark_skin_tone:': u'\U0001F9B8\U0001F3FE', + u':superhero_medium-light_skin_tone:': u'\U0001F9B8\U0001F3FC', + u':superhero_medium_skin_tone:': u'\U0001F9B8\U0001F3FD', + u':supervillain:': u'\U0001F9B9', + u':supervillain_dark_skin_tone:': u'\U0001F9B9\U0001F3FF', + u':supervillain_light_skin_tone:': u'\U0001F9B9\U0001F3FB', + u':supervillain_medium-dark_skin_tone:': u'\U0001F9B9\U0001F3FE', + u':supervillain_medium-light_skin_tone:': u'\U0001F9B9\U0001F3FC', + u':supervillain_medium_skin_tone:': u'\U0001F9B9\U0001F3FD', + u':sushi:': u'\U0001F363', + u':suspension_railway:': u'\U0001F69F', + u':swan:': u'\U0001F9A2', + u':sweat_droplets:': u'\U0001F4A6', + u':synagogue:': u'\U0001F54D', + u':syringe:': u'\U0001F489', + u':t-shirt:': u'\U0001F455', + u':taco:': u'\U0001F32E', + u':takeout_box:': u'\U0001F961', + u':tamale:': u'\U0001FAD4', + u':tanabata_tree:': u'\U0001F38B', + u':tangerine:': u'\U0001F34A', + u':taxi:': u'\U0001F695', + u':teacher:': u'\U0001F9D1\U0000200D\U0001F3EB', + u':teacher_dark_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F3EB', + u':teacher_light_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F3EB', + u':teacher_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F3EB', + u':teacher_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F3EB', + u':teacher_medium_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F3EB', + u':teacup_without_handle:': u'\U0001F375', + u':teapot:': u'\U0001FAD6', + u':tear-off_calendar:': u'\U0001F4C6', + u':technologist:': u'\U0001F9D1\U0000200D\U0001F4BB', + u':technologist_dark_skin_tone:': u'\U0001F9D1\U0001F3FF\U0000200D\U0001F4BB', + u':technologist_light_skin_tone:': u'\U0001F9D1\U0001F3FB\U0000200D\U0001F4BB', + u':technologist_medium-dark_skin_tone:': u'\U0001F9D1\U0001F3FE\U0000200D\U0001F4BB', + u':technologist_medium-light_skin_tone:': u'\U0001F9D1\U0001F3FC\U0000200D\U0001F4BB', + u':technologist_medium_skin_tone:': u'\U0001F9D1\U0001F3FD\U0000200D\U0001F4BB', + u':teddy_bear:': u'\U0001F9F8', + u':telephone:': u'\U0000260E', + u':telephone_receiver:': u'\U0001F4DE', + u':telescope:': u'\U0001F52D', + u':television:': u'\U0001F4FA', + u':ten-thirty:': u'\U0001F565', + u':ten_o’clock:': u'\U0001F559', + u':tennis:': u'\U0001F3BE', + u':tent:': u'\U000026FA', + u':test_tube:': u'\U0001F9EA', + u':thermometer:': u'\U0001F321', + u':thinking_face:': u'\U0001F914', + u':thong_sandal:': u'\U0001FA74', + u':thought_balloon:': u'\U0001F4AD', + u':thread:': u'\U0001F9F5', + u':three-thirty:': u'\U0001F55E', + u':three_o’clock:': u'\U0001F552', + u':thumbs_down:': u'\U0001F44E', + u':thumbs_down_dark_skin_tone:': u'\U0001F44E\U0001F3FF', + u':thumbs_down_light_skin_tone:': u'\U0001F44E\U0001F3FB', + u':thumbs_down_medium-dark_skin_tone:': u'\U0001F44E\U0001F3FE', + u':thumbs_down_medium-light_skin_tone:': u'\U0001F44E\U0001F3FC', + u':thumbs_down_medium_skin_tone:': u'\U0001F44E\U0001F3FD', + u':thumbs_up:': u'\U0001F44D', + u':thumbs_up_dark_skin_tone:': u'\U0001F44D\U0001F3FF', + u':thumbs_up_light_skin_tone:': u'\U0001F44D\U0001F3FB', + u':thumbs_up_medium-dark_skin_tone:': u'\U0001F44D\U0001F3FE', + u':thumbs_up_medium-light_skin_tone:': u'\U0001F44D\U0001F3FC', + u':thumbs_up_medium_skin_tone:': u'\U0001F44D\U0001F3FD', + u':ticket:': u'\U0001F3AB', + u':tiger:': u'\U0001F405', + u':tiger_face:': u'\U0001F42F', + u':timer_clock:': u'\U000023F2', + u':tired_face:': u'\U0001F62B', + u':toilet:': u'\U0001F6BD', + u':tomato:': u'\U0001F345', + u':tongue:': u'\U0001F445', + u':toolbox:': u'\U0001F9F0', + u':tooth:': u'\U0001F9B7', + u':toothbrush:': u'\U0001FAA5', + u':top_hat:': u'\U0001F3A9', + u':tornado:': u'\U0001F32A', + u':trackball:': u'\U0001F5B2', + u':tractor:': u'\U0001F69C', + u':trade_mark:': u'\U00002122', + u':train:': u'\U0001F686', + u':tram:': u'\U0001F68A', + u':tram_car:': u'\U0001F68B', + u':transgender_flag:': u'\U0001F3F3\U0000FE0F\U0000200D\U000026A7\U0000FE0F', + u':transgender_symbol:': u'\U000026A7', + u':triangular_flag:': u'\U0001F6A9', + u':triangular_ruler:': u'\U0001F4D0', + u':trident_emblem:': u'\U0001F531', + u':trolleybus:': u'\U0001F68E', + u':trophy:': u'\U0001F3C6', + u':tropical_drink:': u'\U0001F379', + u':tropical_fish:': u'\U0001F420', + u':trumpet:': u'\U0001F3BA', + u':tulip:': u'\U0001F337', + u':tumbler_glass:': u'\U0001F943', + u':turkey:': u'\U0001F983', + u':turtle:': u'\U0001F422', + u':twelve-thirty:': u'\U0001F567', + u':twelve_o’clock:': u'\U0001F55B', + u':two-hump_camel:': u'\U0001F42B', + u':two-thirty:': u'\U0001F55D', + u':two_hearts:': u'\U0001F495', + u':two_o’clock:': u'\U0001F551', + u':umbrella:': u'\U00002602', + u':umbrella_on_ground:': u'\U000026F1', + u':umbrella_with_rain_drops:': u'\U00002614', + u':unamused_face:': u'\U0001F612', + u':unicorn:': u'\U0001F984', + u':unlocked:': u'\U0001F513', + u':up-down_arrow:': u'\U00002195', + u':up-left_arrow:': u'\U00002196', + u':up-right_arrow:': u'\U00002197', + u':up_arrow:': u'\U00002B06', + u':upside-down_face:': u'\U0001F643', + u':upwards_button:': u'\U0001F53C', + u':vampire:': u'\U0001F9DB', + u':vampire_dark_skin_tone:': u'\U0001F9DB\U0001F3FF', + u':vampire_light_skin_tone:': u'\U0001F9DB\U0001F3FB', + u':vampire_medium-dark_skin_tone:': u'\U0001F9DB\U0001F3FE', + u':vampire_medium-light_skin_tone:': u'\U0001F9DB\U0001F3FC', + u':vampire_medium_skin_tone:': u'\U0001F9DB\U0001F3FD', + u':vertical_traffic_light:': u'\U0001F6A6', + u':vibration_mode:': u'\U0001F4F3', + u':victory_hand:': u'\U0000270C', + u':victory_hand_dark_skin_tone:': u'\U0000270C\U0001F3FF', + u':victory_hand_light_skin_tone:': u'\U0000270C\U0001F3FB', + u':victory_hand_medium-dark_skin_tone:': u'\U0000270C\U0001F3FE', + u':victory_hand_medium-light_skin_tone:': u'\U0000270C\U0001F3FC', + u':victory_hand_medium_skin_tone:': u'\U0000270C\U0001F3FD', + u':video_camera:': u'\U0001F4F9', + u':video_game:': u'\U0001F3AE', + u':videocassette:': u'\U0001F4FC', + u':violin:': u'\U0001F3BB', + u':volcano:': u'\U0001F30B', + u':volleyball:': u'\U0001F3D0', + u':vulcan_salute:': u'\U0001F596', + u':vulcan_salute_dark_skin_tone:': u'\U0001F596\U0001F3FF', + u':vulcan_salute_light_skin_tone:': u'\U0001F596\U0001F3FB', + u':vulcan_salute_medium-dark_skin_tone:': u'\U0001F596\U0001F3FE', + u':vulcan_salute_medium-light_skin_tone:': u'\U0001F596\U0001F3FC', + u':vulcan_salute_medium_skin_tone:': u'\U0001F596\U0001F3FD', + u':waffle:': u'\U0001F9C7', + u':waning_crescent_moon:': u'\U0001F318', + u':waning_gibbous_moon:': u'\U0001F316', + u':warning:': u'\U000026A0', + u':wastebasket:': u'\U0001F5D1', + u':watch:': u'\U0000231A', + u':water_buffalo:': u'\U0001F403', + u':water_closet:': u'\U0001F6BE', + u':water_pistol:': u'\U0001F52B', + u':water_wave:': u'\U0001F30A', + u':watermelon:': u'\U0001F349', + u':waving_hand:': u'\U0001F44B', + u':waving_hand_dark_skin_tone:': u'\U0001F44B\U0001F3FF', + u':waving_hand_light_skin_tone:': u'\U0001F44B\U0001F3FB', + u':waving_hand_medium-dark_skin_tone:': u'\U0001F44B\U0001F3FE', + u':waving_hand_medium-light_skin_tone:': u'\U0001F44B\U0001F3FC', + u':waving_hand_medium_skin_tone:': u'\U0001F44B\U0001F3FD', + u':wavy_dash:': u'\U00003030', + u':waxing_crescent_moon:': u'\U0001F312', + u':waxing_gibbous_moon:': u'\U0001F314', + u':weary_cat:': u'\U0001F640', + u':weary_face:': u'\U0001F629', + u':wedding:': u'\U0001F492', + u':whale:': u'\U0001F40B', + u':wheel_of_dharma:': u'\U00002638', + u':wheelchair_symbol:': u'\U0000267F', + u':white_cane:': u'\U0001F9AF', + u':white_circle:': u'\U000026AA', + u':white_exclamation_mark:': u'\U00002755', + u':white_flag:': u'\U0001F3F3', + u':white_flower:': u'\U0001F4AE', + u':white_hair:': u'\U0001F9B3', + u':white_heart:': u'\U0001F90D', + u':white_large_square:': u'\U00002B1C', + u':white_medium-small_square:': u'\U000025FD', + u':white_medium_square:': u'\U000025FB', + u':white_question_mark:': u'\U00002754', + u':white_small_square:': u'\U000025AB', + u':white_square_button:': u'\U0001F533', + u':wilted_flower:': u'\U0001F940', + u':wind_chime:': u'\U0001F390', + u':wind_face:': u'\U0001F32C', + u':window:': u'\U0001FA9F', + u':wine_glass:': u'\U0001F377', + u':winking_face:': u'\U0001F609', + u':winking_face_with_tongue:': u'\U0001F61C', + u':wolf:': u'\U0001F43A', + u':woman:': u'\U0001F469', + u':woman_and_man_holding_hands:': u'\U0001F46B', + u':woman_and_man_holding_hands_dark_skin_tone:': u'\U0001F46B\U0001F3FF', + u':woman_and_man_holding_hands_dark_skin_tone_light_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FB', + u':woman_and_man_holding_hands_dark_skin_tone_medium-dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FE', + u':woman_and_man_holding_hands_dark_skin_tone_medium-light_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FC', + u':woman_and_man_holding_hands_dark_skin_tone_medium_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FD', + u':woman_and_man_holding_hands_light_skin_tone:': u'\U0001F46B\U0001F3FB', + u':woman_and_man_holding_hands_light_skin_tone_dark_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FF', + u':woman_and_man_holding_hands_light_skin_tone_medium-dark_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FE', + u':woman_and_man_holding_hands_light_skin_tone_medium-light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FC', + u':woman_and_man_holding_hands_light_skin_tone_medium_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FD', + u':woman_and_man_holding_hands_medium-dark_skin_tone:': u'\U0001F46B\U0001F3FE', + u':woman_and_man_holding_hands_medium-dark_skin_tone_dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FF', + u':woman_and_man_holding_hands_medium-dark_skin_tone_light_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FB', + u':woman_and_man_holding_hands_medium-dark_skin_tone_medium-light_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FC', + u':woman_and_man_holding_hands_medium-dark_skin_tone_medium_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FD', + u':woman_and_man_holding_hands_medium-light_skin_tone:': u'\U0001F46B\U0001F3FC', + u':woman_and_man_holding_hands_medium-light_skin_tone_dark_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FF', + u':woman_and_man_holding_hands_medium-light_skin_tone_light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FB', + u':woman_and_man_holding_hands_medium-light_skin_tone_medium-dark_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FE', + u':woman_and_man_holding_hands_medium-light_skin_tone_medium_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FD', + u':woman_and_man_holding_hands_medium_skin_tone:': u'\U0001F46B\U0001F3FD', + u':woman_and_man_holding_hands_medium_skin_tone_dark_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FF', + u':woman_and_man_holding_hands_medium_skin_tone_light_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FB', + u':woman_and_man_holding_hands_medium_skin_tone_medium-dark_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FE', + u':woman_and_man_holding_hands_medium_skin_tone_medium-light_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U0001F91D\U0000200D\U0001F468\U0001F3FC', + u':woman_artist:': u'\U0001F469\U0000200D\U0001F3A8', + u':woman_artist_dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U0001F3A8', + u':woman_artist_light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U0001F3A8', + u':woman_artist_medium-dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U0001F3A8', + u':woman_artist_medium-light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U0001F3A8', + u':woman_artist_medium_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U0001F3A8', + u':woman_astronaut:': u'\U0001F469\U0000200D\U0001F680', + u':woman_astronaut_dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U0001F680', + u':woman_astronaut_light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U0001F680', + u':woman_astronaut_medium-dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U0001F680', + u':woman_astronaut_medium-light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U0001F680', + u':woman_astronaut_medium_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U0001F680', + u':woman_bald:': u'\U0001F469\U0000200D\U0001F9B2', + u':woman_beard:': u'\U0001F9D4\U0000200D\U00002640\U0000FE0F', + u':woman_biking:': u'\U0001F6B4\U0000200D\U00002640\U0000FE0F', + u':woman_biking_dark_skin_tone:': u'\U0001F6B4\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_biking_light_skin_tone:': u'\U0001F6B4\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_biking_medium-dark_skin_tone:': u'\U0001F6B4\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_biking_medium-light_skin_tone:': u'\U0001F6B4\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_biking_medium_skin_tone:': u'\U0001F6B4\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_blond_hair:': u'\U0001F471\U0000200D\U00002640\U0000FE0F', + u':woman_bouncing_ball:': u'\U000026F9\U0000FE0F\U0000200D\U00002640\U0000FE0F', + u':woman_bouncing_ball_dark_skin_tone:': u'\U000026F9\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_bouncing_ball_light_skin_tone:': u'\U000026F9\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_bouncing_ball_medium-dark_skin_tone:': u'\U000026F9\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_bouncing_ball_medium-light_skin_tone:': u'\U000026F9\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_bouncing_ball_medium_skin_tone:': u'\U000026F9\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_bowing:': u'\U0001F647\U0000200D\U00002640\U0000FE0F', + u':woman_bowing_dark_skin_tone:': u'\U0001F647\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_bowing_light_skin_tone:': u'\U0001F647\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_bowing_medium-dark_skin_tone:': u'\U0001F647\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_bowing_medium-light_skin_tone:': u'\U0001F647\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_bowing_medium_skin_tone:': u'\U0001F647\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_cartwheeling:': u'\U0001F938\U0000200D\U00002640\U0000FE0F', + u':woman_cartwheeling_dark_skin_tone:': u'\U0001F938\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_cartwheeling_light_skin_tone:': u'\U0001F938\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_cartwheeling_medium-dark_skin_tone:': u'\U0001F938\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_cartwheeling_medium-light_skin_tone:': u'\U0001F938\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_cartwheeling_medium_skin_tone:': u'\U0001F938\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_climbing:': u'\U0001F9D7\U0000200D\U00002640\U0000FE0F', + u':woman_climbing_dark_skin_tone:': u'\U0001F9D7\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_climbing_light_skin_tone:': u'\U0001F9D7\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_climbing_medium-dark_skin_tone:': u'\U0001F9D7\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_climbing_medium-light_skin_tone:': u'\U0001F9D7\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_climbing_medium_skin_tone:': u'\U0001F9D7\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_construction_worker:': u'\U0001F477\U0000200D\U00002640\U0000FE0F', + u':woman_construction_worker_dark_skin_tone:': u'\U0001F477\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_construction_worker_light_skin_tone:': u'\U0001F477\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_construction_worker_medium-dark_skin_tone:': u'\U0001F477\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_construction_worker_medium-light_skin_tone:': u'\U0001F477\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_construction_worker_medium_skin_tone:': u'\U0001F477\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_cook:': u'\U0001F469\U0000200D\U0001F373', + u':woman_cook_dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U0001F373', + u':woman_cook_light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U0001F373', + u':woman_cook_medium-dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U0001F373', + u':woman_cook_medium-light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U0001F373', + u':woman_cook_medium_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U0001F373', + u':woman_curly_hair:': u'\U0001F469\U0000200D\U0001F9B1', + u':woman_dancing:': u'\U0001F483', + u':woman_dancing_dark_skin_tone:': u'\U0001F483\U0001F3FF', + u':woman_dancing_light_skin_tone:': u'\U0001F483\U0001F3FB', + u':woman_dancing_medium-dark_skin_tone:': u'\U0001F483\U0001F3FE', + u':woman_dancing_medium-light_skin_tone:': u'\U0001F483\U0001F3FC', + u':woman_dancing_medium_skin_tone:': u'\U0001F483\U0001F3FD', + u':woman_dark_skin_tone:': u'\U0001F469\U0001F3FF', + u':woman_dark_skin_tone_bald:': u'\U0001F469\U0001F3FF\U0000200D\U0001F9B2', + u':woman_dark_skin_tone_beard:': u'\U0001F9D4\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_dark_skin_tone_blond_hair:': u'\U0001F471\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_dark_skin_tone_curly_hair:': u'\U0001F469\U0001F3FF\U0000200D\U0001F9B1', + u':woman_dark_skin_tone_red_hair:': u'\U0001F469\U0001F3FF\U0000200D\U0001F9B0', + u':woman_dark_skin_tone_white_hair:': u'\U0001F469\U0001F3FF\U0000200D\U0001F9B3', + u':woman_detective:': u'\U0001F575\U0000FE0F\U0000200D\U00002640\U0000FE0F', + u':woman_detective_dark_skin_tone:': u'\U0001F575\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_detective_light_skin_tone:': u'\U0001F575\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_detective_medium-dark_skin_tone:': u'\U0001F575\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_detective_medium-light_skin_tone:': u'\U0001F575\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_detective_medium_skin_tone:': u'\U0001F575\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_elf:': u'\U0001F9DD\U0000200D\U00002640\U0000FE0F', + u':woman_elf_dark_skin_tone:': u'\U0001F9DD\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_elf_light_skin_tone:': u'\U0001F9DD\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_elf_medium-dark_skin_tone:': u'\U0001F9DD\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_elf_medium-light_skin_tone:': u'\U0001F9DD\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_elf_medium_skin_tone:': u'\U0001F9DD\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_facepalming:': u'\U0001F926\U0000200D\U00002640\U0000FE0F', + u':woman_facepalming_dark_skin_tone:': u'\U0001F926\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_facepalming_light_skin_tone:': u'\U0001F926\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_facepalming_medium-dark_skin_tone:': u'\U0001F926\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_facepalming_medium-light_skin_tone:': u'\U0001F926\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_facepalming_medium_skin_tone:': u'\U0001F926\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_factory_worker:': u'\U0001F469\U0000200D\U0001F3ED', + u':woman_factory_worker_dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U0001F3ED', + u':woman_factory_worker_light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U0001F3ED', + u':woman_factory_worker_medium-dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U0001F3ED', + u':woman_factory_worker_medium-light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U0001F3ED', + u':woman_factory_worker_medium_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U0001F3ED', + u':woman_fairy:': u'\U0001F9DA\U0000200D\U00002640\U0000FE0F', + u':woman_fairy_dark_skin_tone:': u'\U0001F9DA\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_fairy_light_skin_tone:': u'\U0001F9DA\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_fairy_medium-dark_skin_tone:': u'\U0001F9DA\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_fairy_medium-light_skin_tone:': u'\U0001F9DA\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_fairy_medium_skin_tone:': u'\U0001F9DA\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_farmer:': u'\U0001F469\U0000200D\U0001F33E', + u':woman_farmer_dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U0001F33E', + u':woman_farmer_light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U0001F33E', + u':woman_farmer_medium-dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U0001F33E', + u':woman_farmer_medium-light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U0001F33E', + u':woman_farmer_medium_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U0001F33E', + u':woman_feeding_baby:': u'\U0001F469\U0000200D\U0001F37C', + u':woman_feeding_baby_dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U0001F37C', + u':woman_feeding_baby_light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U0001F37C', + u':woman_feeding_baby_medium-dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U0001F37C', + u':woman_feeding_baby_medium-light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U0001F37C', + u':woman_feeding_baby_medium_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U0001F37C', + u':woman_firefighter:': u'\U0001F469\U0000200D\U0001F692', + u':woman_firefighter_dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U0001F692', + u':woman_firefighter_light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U0001F692', + u':woman_firefighter_medium-dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U0001F692', + u':woman_firefighter_medium-light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U0001F692', + u':woman_firefighter_medium_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U0001F692', + u':woman_frowning:': u'\U0001F64D\U0000200D\U00002640\U0000FE0F', + u':woman_frowning_dark_skin_tone:': u'\U0001F64D\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_frowning_light_skin_tone:': u'\U0001F64D\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_frowning_medium-dark_skin_tone:': u'\U0001F64D\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_frowning_medium-light_skin_tone:': u'\U0001F64D\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_frowning_medium_skin_tone:': u'\U0001F64D\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_genie:': u'\U0001F9DE\U0000200D\U00002640\U0000FE0F', + u':woman_gesturing_NO:': u'\U0001F645\U0000200D\U00002640\U0000FE0F', + u':woman_gesturing_NO_dark_skin_tone:': u'\U0001F645\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_gesturing_NO_light_skin_tone:': u'\U0001F645\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_gesturing_NO_medium-dark_skin_tone:': u'\U0001F645\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_gesturing_NO_medium-light_skin_tone:': u'\U0001F645\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_gesturing_NO_medium_skin_tone:': u'\U0001F645\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_gesturing_OK:': u'\U0001F646\U0000200D\U00002640\U0000FE0F', + u':woman_gesturing_OK_dark_skin_tone:': u'\U0001F646\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_gesturing_OK_light_skin_tone:': u'\U0001F646\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_gesturing_OK_medium-dark_skin_tone:': u'\U0001F646\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_gesturing_OK_medium-light_skin_tone:': u'\U0001F646\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_gesturing_OK_medium_skin_tone:': u'\U0001F646\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_getting_haircut:': u'\U0001F487\U0000200D\U00002640\U0000FE0F', + u':woman_getting_haircut_dark_skin_tone:': u'\U0001F487\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_getting_haircut_light_skin_tone:': u'\U0001F487\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_getting_haircut_medium-dark_skin_tone:': u'\U0001F487\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_getting_haircut_medium-light_skin_tone:': u'\U0001F487\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_getting_haircut_medium_skin_tone:': u'\U0001F487\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_getting_massage:': u'\U0001F486\U0000200D\U00002640\U0000FE0F', + u':woman_getting_massage_dark_skin_tone:': u'\U0001F486\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_getting_massage_light_skin_tone:': u'\U0001F486\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_getting_massage_medium-dark_skin_tone:': u'\U0001F486\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_getting_massage_medium-light_skin_tone:': u'\U0001F486\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_getting_massage_medium_skin_tone:': u'\U0001F486\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_golfing:': u'\U0001F3CC\U0000FE0F\U0000200D\U00002640\U0000FE0F', + u':woman_golfing_dark_skin_tone:': u'\U0001F3CC\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_golfing_light_skin_tone:': u'\U0001F3CC\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_golfing_medium-dark_skin_tone:': u'\U0001F3CC\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_golfing_medium-light_skin_tone:': u'\U0001F3CC\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_golfing_medium_skin_tone:': u'\U0001F3CC\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_guard:': u'\U0001F482\U0000200D\U00002640\U0000FE0F', + u':woman_guard_dark_skin_tone:': u'\U0001F482\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_guard_light_skin_tone:': u'\U0001F482\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_guard_medium-dark_skin_tone:': u'\U0001F482\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_guard_medium-light_skin_tone:': u'\U0001F482\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_guard_medium_skin_tone:': u'\U0001F482\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_health_worker:': u'\U0001F469\U0000200D\U00002695\U0000FE0F', + u':woman_health_worker_dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U00002695\U0000FE0F', + u':woman_health_worker_light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U00002695\U0000FE0F', + u':woman_health_worker_medium-dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U00002695\U0000FE0F', + u':woman_health_worker_medium-light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U00002695\U0000FE0F', + u':woman_health_worker_medium_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U00002695\U0000FE0F', + u':woman_in_lotus_position:': u'\U0001F9D8\U0000200D\U00002640\U0000FE0F', + u':woman_in_lotus_position_dark_skin_tone:': u'\U0001F9D8\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_in_lotus_position_light_skin_tone:': u'\U0001F9D8\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_in_lotus_position_medium-dark_skin_tone:': u'\U0001F9D8\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_in_lotus_position_medium-light_skin_tone:': u'\U0001F9D8\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_in_lotus_position_medium_skin_tone:': u'\U0001F9D8\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_in_manual_wheelchair:': u'\U0001F469\U0000200D\U0001F9BD', + u':woman_in_manual_wheelchair_dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U0001F9BD', + u':woman_in_manual_wheelchair_light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U0001F9BD', + u':woman_in_manual_wheelchair_medium-dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U0001F9BD', + u':woman_in_manual_wheelchair_medium-light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U0001F9BD', + u':woman_in_manual_wheelchair_medium_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U0001F9BD', + u':woman_in_motorized_wheelchair:': u'\U0001F469\U0000200D\U0001F9BC', + u':woman_in_motorized_wheelchair_dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U0001F9BC', + u':woman_in_motorized_wheelchair_light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U0001F9BC', + u':woman_in_motorized_wheelchair_medium-dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U0001F9BC', + u':woman_in_motorized_wheelchair_medium-light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U0001F9BC', + u':woman_in_motorized_wheelchair_medium_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U0001F9BC', + u':woman_in_steamy_room:': u'\U0001F9D6\U0000200D\U00002640\U0000FE0F', + u':woman_in_steamy_room_dark_skin_tone:': u'\U0001F9D6\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_in_steamy_room_light_skin_tone:': u'\U0001F9D6\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_in_steamy_room_medium-dark_skin_tone:': u'\U0001F9D6\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_in_steamy_room_medium-light_skin_tone:': u'\U0001F9D6\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_in_steamy_room_medium_skin_tone:': u'\U0001F9D6\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_in_tuxedo:': u'\U0001F935\U0000200D\U00002640\U0000FE0F', + u':woman_in_tuxedo_dark_skin_tone:': u'\U0001F935\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_in_tuxedo_light_skin_tone:': u'\U0001F935\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_in_tuxedo_medium-dark_skin_tone:': u'\U0001F935\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_in_tuxedo_medium-light_skin_tone:': u'\U0001F935\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_in_tuxedo_medium_skin_tone:': u'\U0001F935\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_judge:': u'\U0001F469\U0000200D\U00002696\U0000FE0F', + u':woman_judge_dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U00002696\U0000FE0F', + u':woman_judge_light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U00002696\U0000FE0F', + u':woman_judge_medium-dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U00002696\U0000FE0F', + u':woman_judge_medium-light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U00002696\U0000FE0F', + u':woman_judge_medium_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U00002696\U0000FE0F', + u':woman_juggling:': u'\U0001F939\U0000200D\U00002640\U0000FE0F', + u':woman_juggling_dark_skin_tone:': u'\U0001F939\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_juggling_light_skin_tone:': u'\U0001F939\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_juggling_medium-dark_skin_tone:': u'\U0001F939\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_juggling_medium-light_skin_tone:': u'\U0001F939\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_juggling_medium_skin_tone:': u'\U0001F939\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_kneeling:': u'\U0001F9CE\U0000200D\U00002640\U0000FE0F', + u':woman_kneeling_dark_skin_tone:': u'\U0001F9CE\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_kneeling_light_skin_tone:': u'\U0001F9CE\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_kneeling_medium-dark_skin_tone:': u'\U0001F9CE\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_kneeling_medium-light_skin_tone:': u'\U0001F9CE\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_kneeling_medium_skin_tone:': u'\U0001F9CE\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_lifting_weights:': u'\U0001F3CB\U0000FE0F\U0000200D\U00002640\U0000FE0F', + u':woman_lifting_weights_dark_skin_tone:': u'\U0001F3CB\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_lifting_weights_light_skin_tone:': u'\U0001F3CB\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_lifting_weights_medium-dark_skin_tone:': u'\U0001F3CB\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_lifting_weights_medium-light_skin_tone:': u'\U0001F3CB\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_lifting_weights_medium_skin_tone:': u'\U0001F3CB\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_light_skin_tone:': u'\U0001F469\U0001F3FB', + u':woman_light_skin_tone_bald:': u'\U0001F469\U0001F3FB\U0000200D\U0001F9B2', + u':woman_light_skin_tone_beard:': u'\U0001F9D4\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_light_skin_tone_blond_hair:': u'\U0001F471\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_light_skin_tone_curly_hair:': u'\U0001F469\U0001F3FB\U0000200D\U0001F9B1', + u':woman_light_skin_tone_red_hair:': u'\U0001F469\U0001F3FB\U0000200D\U0001F9B0', + u':woman_light_skin_tone_white_hair:': u'\U0001F469\U0001F3FB\U0000200D\U0001F9B3', + u':woman_mage:': u'\U0001F9D9\U0000200D\U00002640\U0000FE0F', + u':woman_mage_dark_skin_tone:': u'\U0001F9D9\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_mage_light_skin_tone:': u'\U0001F9D9\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_mage_medium-dark_skin_tone:': u'\U0001F9D9\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_mage_medium-light_skin_tone:': u'\U0001F9D9\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_mage_medium_skin_tone:': u'\U0001F9D9\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_mechanic:': u'\U0001F469\U0000200D\U0001F527', + u':woman_mechanic_dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U0001F527', + u':woman_mechanic_light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U0001F527', + u':woman_mechanic_medium-dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U0001F527', + u':woman_mechanic_medium-light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U0001F527', + u':woman_mechanic_medium_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U0001F527', + u':woman_medium-dark_skin_tone:': u'\U0001F469\U0001F3FE', + u':woman_medium-dark_skin_tone_bald:': u'\U0001F469\U0001F3FE\U0000200D\U0001F9B2', + u':woman_medium-dark_skin_tone_beard:': u'\U0001F9D4\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_medium-dark_skin_tone_blond_hair:': u'\U0001F471\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_medium-dark_skin_tone_curly_hair:': u'\U0001F469\U0001F3FE\U0000200D\U0001F9B1', + u':woman_medium-dark_skin_tone_red_hair:': u'\U0001F469\U0001F3FE\U0000200D\U0001F9B0', + u':woman_medium-dark_skin_tone_white_hair:': u'\U0001F469\U0001F3FE\U0000200D\U0001F9B3', + u':woman_medium-light_skin_tone:': u'\U0001F469\U0001F3FC', + u':woman_medium-light_skin_tone_bald:': u'\U0001F469\U0001F3FC\U0000200D\U0001F9B2', + u':woman_medium-light_skin_tone_beard:': u'\U0001F9D4\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_medium-light_skin_tone_blond_hair:': u'\U0001F471\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_medium-light_skin_tone_curly_hair:': u'\U0001F469\U0001F3FC\U0000200D\U0001F9B1', + u':woman_medium-light_skin_tone_red_hair:': u'\U0001F469\U0001F3FC\U0000200D\U0001F9B0', + u':woman_medium-light_skin_tone_white_hair:': u'\U0001F469\U0001F3FC\U0000200D\U0001F9B3', + u':woman_medium_skin_tone:': u'\U0001F469\U0001F3FD', + u':woman_medium_skin_tone_bald:': u'\U0001F469\U0001F3FD\U0000200D\U0001F9B2', + u':woman_medium_skin_tone_beard:': u'\U0001F9D4\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_medium_skin_tone_blond_hair:': u'\U0001F471\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_medium_skin_tone_curly_hair:': u'\U0001F469\U0001F3FD\U0000200D\U0001F9B1', + u':woman_medium_skin_tone_red_hair:': u'\U0001F469\U0001F3FD\U0000200D\U0001F9B0', + u':woman_medium_skin_tone_white_hair:': u'\U0001F469\U0001F3FD\U0000200D\U0001F9B3', + u':woman_mountain_biking:': u'\U0001F6B5\U0000200D\U00002640\U0000FE0F', + u':woman_mountain_biking_dark_skin_tone:': u'\U0001F6B5\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_mountain_biking_light_skin_tone:': u'\U0001F6B5\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_mountain_biking_medium-dark_skin_tone:': u'\U0001F6B5\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_mountain_biking_medium-light_skin_tone:': u'\U0001F6B5\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_mountain_biking_medium_skin_tone:': u'\U0001F6B5\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_office_worker:': u'\U0001F469\U0000200D\U0001F4BC', + u':woman_office_worker_dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U0001F4BC', + u':woman_office_worker_light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U0001F4BC', + u':woman_office_worker_medium-dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U0001F4BC', + u':woman_office_worker_medium-light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U0001F4BC', + u':woman_office_worker_medium_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U0001F4BC', + u':woman_pilot:': u'\U0001F469\U0000200D\U00002708\U0000FE0F', + u':woman_pilot_dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U00002708\U0000FE0F', + u':woman_pilot_light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U00002708\U0000FE0F', + u':woman_pilot_medium-dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U00002708\U0000FE0F', + u':woman_pilot_medium-light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U00002708\U0000FE0F', + u':woman_pilot_medium_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U00002708\U0000FE0F', + u':woman_playing_handball:': u'\U0001F93E\U0000200D\U00002640\U0000FE0F', + u':woman_playing_handball_dark_skin_tone:': u'\U0001F93E\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_playing_handball_light_skin_tone:': u'\U0001F93E\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_playing_handball_medium-dark_skin_tone:': u'\U0001F93E\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_playing_handball_medium-light_skin_tone:': u'\U0001F93E\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_playing_handball_medium_skin_tone:': u'\U0001F93E\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_playing_water_polo:': u'\U0001F93D\U0000200D\U00002640\U0000FE0F', + u':woman_playing_water_polo_dark_skin_tone:': u'\U0001F93D\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_playing_water_polo_light_skin_tone:': u'\U0001F93D\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_playing_water_polo_medium-dark_skin_tone:': u'\U0001F93D\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_playing_water_polo_medium-light_skin_tone:': u'\U0001F93D\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_playing_water_polo_medium_skin_tone:': u'\U0001F93D\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_police_officer:': u'\U0001F46E\U0000200D\U00002640\U0000FE0F', + u':woman_police_officer_dark_skin_tone:': u'\U0001F46E\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_police_officer_light_skin_tone:': u'\U0001F46E\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_police_officer_medium-dark_skin_tone:': u'\U0001F46E\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_police_officer_medium-light_skin_tone:': u'\U0001F46E\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_police_officer_medium_skin_tone:': u'\U0001F46E\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_pouting:': u'\U0001F64E\U0000200D\U00002640\U0000FE0F', + u':woman_pouting_dark_skin_tone:': u'\U0001F64E\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_pouting_light_skin_tone:': u'\U0001F64E\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_pouting_medium-dark_skin_tone:': u'\U0001F64E\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_pouting_medium-light_skin_tone:': u'\U0001F64E\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_pouting_medium_skin_tone:': u'\U0001F64E\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_raising_hand:': u'\U0001F64B\U0000200D\U00002640\U0000FE0F', + u':woman_raising_hand_dark_skin_tone:': u'\U0001F64B\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_raising_hand_light_skin_tone:': u'\U0001F64B\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_raising_hand_medium-dark_skin_tone:': u'\U0001F64B\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_raising_hand_medium-light_skin_tone:': u'\U0001F64B\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_raising_hand_medium_skin_tone:': u'\U0001F64B\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_red_hair:': u'\U0001F469\U0000200D\U0001F9B0', + u':woman_rowing_boat:': u'\U0001F6A3\U0000200D\U00002640\U0000FE0F', + u':woman_rowing_boat_dark_skin_tone:': u'\U0001F6A3\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_rowing_boat_light_skin_tone:': u'\U0001F6A3\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_rowing_boat_medium-dark_skin_tone:': u'\U0001F6A3\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_rowing_boat_medium-light_skin_tone:': u'\U0001F6A3\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_rowing_boat_medium_skin_tone:': u'\U0001F6A3\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_running:': u'\U0001F3C3\U0000200D\U00002640\U0000FE0F', + u':woman_running_dark_skin_tone:': u'\U0001F3C3\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_running_light_skin_tone:': u'\U0001F3C3\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_running_medium-dark_skin_tone:': u'\U0001F3C3\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_running_medium-light_skin_tone:': u'\U0001F3C3\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_running_medium_skin_tone:': u'\U0001F3C3\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_scientist:': u'\U0001F469\U0000200D\U0001F52C', + u':woman_scientist_dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U0001F52C', + u':woman_scientist_light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U0001F52C', + u':woman_scientist_medium-dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U0001F52C', + u':woman_scientist_medium-light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U0001F52C', + u':woman_scientist_medium_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U0001F52C', + u':woman_shrugging:': u'\U0001F937\U0000200D\U00002640\U0000FE0F', + u':woman_shrugging_dark_skin_tone:': u'\U0001F937\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_shrugging_light_skin_tone:': u'\U0001F937\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_shrugging_medium-dark_skin_tone:': u'\U0001F937\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_shrugging_medium-light_skin_tone:': u'\U0001F937\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_shrugging_medium_skin_tone:': u'\U0001F937\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_singer:': u'\U0001F469\U0000200D\U0001F3A4', + u':woman_singer_dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U0001F3A4', + u':woman_singer_light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U0001F3A4', + u':woman_singer_medium-dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U0001F3A4', + u':woman_singer_medium-light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U0001F3A4', + u':woman_singer_medium_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U0001F3A4', + u':woman_standing:': u'\U0001F9CD\U0000200D\U00002640\U0000FE0F', + u':woman_standing_dark_skin_tone:': u'\U0001F9CD\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_standing_light_skin_tone:': u'\U0001F9CD\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_standing_medium-dark_skin_tone:': u'\U0001F9CD\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_standing_medium-light_skin_tone:': u'\U0001F9CD\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_standing_medium_skin_tone:': u'\U0001F9CD\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_student:': u'\U0001F469\U0000200D\U0001F393', + u':woman_student_dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U0001F393', + u':woman_student_light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U0001F393', + u':woman_student_medium-dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U0001F393', + u':woman_student_medium-light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U0001F393', + u':woman_student_medium_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U0001F393', + u':woman_superhero:': u'\U0001F9B8\U0000200D\U00002640\U0000FE0F', + u':woman_superhero_dark_skin_tone:': u'\U0001F9B8\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_superhero_light_skin_tone:': u'\U0001F9B8\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_superhero_medium-dark_skin_tone:': u'\U0001F9B8\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_superhero_medium-light_skin_tone:': u'\U0001F9B8\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_superhero_medium_skin_tone:': u'\U0001F9B8\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_supervillain:': u'\U0001F9B9\U0000200D\U00002640\U0000FE0F', + u':woman_supervillain_dark_skin_tone:': u'\U0001F9B9\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_supervillain_light_skin_tone:': u'\U0001F9B9\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_supervillain_medium-dark_skin_tone:': u'\U0001F9B9\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_supervillain_medium-light_skin_tone:': u'\U0001F9B9\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_supervillain_medium_skin_tone:': u'\U0001F9B9\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_surfing:': u'\U0001F3C4\U0000200D\U00002640\U0000FE0F', + u':woman_surfing_dark_skin_tone:': u'\U0001F3C4\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_surfing_light_skin_tone:': u'\U0001F3C4\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_surfing_medium-dark_skin_tone:': u'\U0001F3C4\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_surfing_medium-light_skin_tone:': u'\U0001F3C4\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_surfing_medium_skin_tone:': u'\U0001F3C4\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_swimming:': u'\U0001F3CA\U0000200D\U00002640\U0000FE0F', + u':woman_swimming_dark_skin_tone:': u'\U0001F3CA\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_swimming_light_skin_tone:': u'\U0001F3CA\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_swimming_medium-dark_skin_tone:': u'\U0001F3CA\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_swimming_medium-light_skin_tone:': u'\U0001F3CA\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_swimming_medium_skin_tone:': u'\U0001F3CA\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_teacher:': u'\U0001F469\U0000200D\U0001F3EB', + u':woman_teacher_dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U0001F3EB', + u':woman_teacher_light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U0001F3EB', + u':woman_teacher_medium-dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U0001F3EB', + u':woman_teacher_medium-light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U0001F3EB', + u':woman_teacher_medium_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U0001F3EB', + u':woman_technologist:': u'\U0001F469\U0000200D\U0001F4BB', + u':woman_technologist_dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U0001F4BB', + u':woman_technologist_light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U0001F4BB', + u':woman_technologist_medium-dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U0001F4BB', + u':woman_technologist_medium-light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U0001F4BB', + u':woman_technologist_medium_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U0001F4BB', + u':woman_tipping_hand:': u'\U0001F481\U0000200D\U00002640\U0000FE0F', + u':woman_tipping_hand_dark_skin_tone:': u'\U0001F481\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_tipping_hand_light_skin_tone:': u'\U0001F481\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_tipping_hand_medium-dark_skin_tone:': u'\U0001F481\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_tipping_hand_medium-light_skin_tone:': u'\U0001F481\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_tipping_hand_medium_skin_tone:': u'\U0001F481\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_vampire:': u'\U0001F9DB\U0000200D\U00002640\U0000FE0F', + u':woman_vampire_dark_skin_tone:': u'\U0001F9DB\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_vampire_light_skin_tone:': u'\U0001F9DB\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_vampire_medium-dark_skin_tone:': u'\U0001F9DB\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_vampire_medium-light_skin_tone:': u'\U0001F9DB\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_vampire_medium_skin_tone:': u'\U0001F9DB\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_walking:': u'\U0001F6B6\U0000200D\U00002640\U0000FE0F', + u':woman_walking_dark_skin_tone:': u'\U0001F6B6\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_walking_light_skin_tone:': u'\U0001F6B6\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_walking_medium-dark_skin_tone:': u'\U0001F6B6\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_walking_medium-light_skin_tone:': u'\U0001F6B6\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_walking_medium_skin_tone:': u'\U0001F6B6\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_wearing_turban:': u'\U0001F473\U0000200D\U00002640\U0000FE0F', + u':woman_wearing_turban_dark_skin_tone:': u'\U0001F473\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_wearing_turban_light_skin_tone:': u'\U0001F473\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_wearing_turban_medium-dark_skin_tone:': u'\U0001F473\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_wearing_turban_medium-light_skin_tone:': u'\U0001F473\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_wearing_turban_medium_skin_tone:': u'\U0001F473\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_white_hair:': u'\U0001F469\U0000200D\U0001F9B3', + u':woman_with_headscarf:': u'\U0001F9D5', + u':woman_with_headscarf_dark_skin_tone:': u'\U0001F9D5\U0001F3FF', + u':woman_with_headscarf_light_skin_tone:': u'\U0001F9D5\U0001F3FB', + u':woman_with_headscarf_medium-dark_skin_tone:': u'\U0001F9D5\U0001F3FE', + u':woman_with_headscarf_medium-light_skin_tone:': u'\U0001F9D5\U0001F3FC', + u':woman_with_headscarf_medium_skin_tone:': u'\U0001F9D5\U0001F3FD', + u':woman_with_veil:': u'\U0001F470\U0000200D\U00002640\U0000FE0F', + u':woman_with_veil_dark_skin_tone:': u'\U0001F470\U0001F3FF\U0000200D\U00002640\U0000FE0F', + u':woman_with_veil_light_skin_tone:': u'\U0001F470\U0001F3FB\U0000200D\U00002640\U0000FE0F', + u':woman_with_veil_medium-dark_skin_tone:': u'\U0001F470\U0001F3FE\U0000200D\U00002640\U0000FE0F', + u':woman_with_veil_medium-light_skin_tone:': u'\U0001F470\U0001F3FC\U0000200D\U00002640\U0000FE0F', + u':woman_with_veil_medium_skin_tone:': u'\U0001F470\U0001F3FD\U0000200D\U00002640\U0000FE0F', + u':woman_with_white_cane:': u'\U0001F469\U0000200D\U0001F9AF', + u':woman_with_white_cane_dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U0001F9AF', + u':woman_with_white_cane_light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U0001F9AF', + u':woman_with_white_cane_medium-dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U0001F9AF', + u':woman_with_white_cane_medium-light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U0001F9AF', + u':woman_with_white_cane_medium_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U0001F9AF', + u':woman_zombie:': u'\U0001F9DF\U0000200D\U00002640\U0000FE0F', + u':woman’s_boot:': u'\U0001F462', + u':woman’s_clothes:': u'\U0001F45A', + u':woman’s_hat:': u'\U0001F452', + u':woman’s_sandal:': u'\U0001F461', + u':women_holding_hands:': u'\U0001F46D', + u':women_holding_hands_dark_skin_tone:': u'\U0001F46D\U0001F3FF', + u':women_holding_hands_dark_skin_tone_light_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U0001F91D\U0000200D\U0001F469\U0001F3FB', + u':women_holding_hands_dark_skin_tone_medium-dark_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U0001F91D\U0000200D\U0001F469\U0001F3FE', + u':women_holding_hands_dark_skin_tone_medium-light_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U0001F91D\U0000200D\U0001F469\U0001F3FC', + u':women_holding_hands_dark_skin_tone_medium_skin_tone:': u'\U0001F469\U0001F3FF\U0000200D\U0001F91D\U0000200D\U0001F469\U0001F3FD', + u':women_holding_hands_light_skin_tone:': u'\U0001F46D\U0001F3FB', + u':women_holding_hands_light_skin_tone_dark_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U0001F91D\U0000200D\U0001F469\U0001F3FF', + u':women_holding_hands_light_skin_tone_medium-dark_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U0001F91D\U0000200D\U0001F469\U0001F3FE', + u':women_holding_hands_light_skin_tone_medium-light_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U0001F91D\U0000200D\U0001F469\U0001F3FC', + u':women_holding_hands_light_skin_tone_medium_skin_tone:': u'\U0001F469\U0001F3FB\U0000200D\U0001F91D\U0000200D\U0001F469\U0001F3FD', + u':women_holding_hands_medium-dark_skin_tone:': u'\U0001F46D\U0001F3FE', + u':women_holding_hands_medium-dark_skin_tone_dark_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U0001F91D\U0000200D\U0001F469\U0001F3FF', + u':women_holding_hands_medium-dark_skin_tone_light_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U0001F91D\U0000200D\U0001F469\U0001F3FB', + u':women_holding_hands_medium-dark_skin_tone_medium-light_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U0001F91D\U0000200D\U0001F469\U0001F3FC', + u':women_holding_hands_medium-dark_skin_tone_medium_skin_tone:': u'\U0001F469\U0001F3FE\U0000200D\U0001F91D\U0000200D\U0001F469\U0001F3FD', + u':women_holding_hands_medium-light_skin_tone:': u'\U0001F46D\U0001F3FC', + u':women_holding_hands_medium-light_skin_tone_dark_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U0001F91D\U0000200D\U0001F469\U0001F3FF', + u':women_holding_hands_medium-light_skin_tone_light_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U0001F91D\U0000200D\U0001F469\U0001F3FB', + u':women_holding_hands_medium-light_skin_tone_medium-dark_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U0001F91D\U0000200D\U0001F469\U0001F3FE', + u':women_holding_hands_medium-light_skin_tone_medium_skin_tone:': u'\U0001F469\U0001F3FC\U0000200D\U0001F91D\U0000200D\U0001F469\U0001F3FD', + u':women_holding_hands_medium_skin_tone:': u'\U0001F46D\U0001F3FD', + u':women_holding_hands_medium_skin_tone_dark_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U0001F91D\U0000200D\U0001F469\U0001F3FF', + u':women_holding_hands_medium_skin_tone_light_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U0001F91D\U0000200D\U0001F469\U0001F3FB', + u':women_holding_hands_medium_skin_tone_medium-dark_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U0001F91D\U0000200D\U0001F469\U0001F3FE', + u':women_holding_hands_medium_skin_tone_medium-light_skin_tone:': u'\U0001F469\U0001F3FD\U0000200D\U0001F91D\U0000200D\U0001F469\U0001F3FC', + u':women_with_bunny_ears:': u'\U0001F46F\U0000200D\U00002640\U0000FE0F', + u':women_wrestling:': u'\U0001F93C\U0000200D\U00002640\U0000FE0F', + u':women’s_room:': u'\U0001F6BA', + u':wood:': u'\U0001FAB5', + u':woozy_face:': u'\U0001F974', + u':world_map:': u'\U0001F5FA', + u':worm:': u'\U0001FAB1', + u':worried_face:': u'\U0001F61F', + u':wrapped_gift:': u'\U0001F381', + u':wrench:': u'\U0001F527', + u':writing_hand:': u'\U0000270D', + u':writing_hand_dark_skin_tone:': u'\U0000270D\U0001F3FF', + u':writing_hand_light_skin_tone:': u'\U0000270D\U0001F3FB', + u':writing_hand_medium-dark_skin_tone:': u'\U0000270D\U0001F3FE', + u':writing_hand_medium-light_skin_tone:': u'\U0000270D\U0001F3FC', + u':writing_hand_medium_skin_tone:': u'\U0000270D\U0001F3FD', + u':yarn:': u'\U0001F9F6', + u':yawning_face:': u'\U0001F971', + u':yellow_circle:': u'\U0001F7E1', + u':yellow_heart:': u'\U0001F49B', + u':yellow_square:': u'\U0001F7E8', + u':yen_banknote:': u'\U0001F4B4', + u':yin_yang:': u'\U0000262F', + u':yo-yo:': u'\U0001FA80', + u':zany_face:': u'\U0001F92A', + u':zebra:': u'\U0001F993', + u':zipper-mouth_face:': u'\U0001F910', + u':zombie:': u'\U0001F9DF', + u':zzz:': u'\U0001F4A4', + u':Åland_Islands:': u'\U0001F1E6\U0001F1FD', +} + +EMOJI_ALIAS_UNICODE = dict(EMOJI_UNICODE.items(), **{ + u':admission_tickets:': u'\U0001F39F', + u':aerial_tramway:': u'\U0001F6A1', + u':airplane:': u'\U00002708', + u':airplane_arriving:': u'\U0001F6EC', + u':airplane_departure:': u'\U0001F6EB', + u':alarm_clock:': u'\U000023F0', + u':alembic:': u'\U00002697', + u':space_invader:': u'\U0001F47E', + u':ambulance:': u'\U0001F691', + u':football:': u'\U0001F3C8', + u':amphora:': u'\U0001F3FA', + u':anchor:': u'\U00002693', + u':anger:': u'\U0001F4A2', + u':angry:': u'\U0001F620', + u':anguished:': u'\U0001F627', + u':ant:': u'\U0001F41C', + u':signal_strength:': u'\U0001F4F6', + u':arrows_counterclockwise:': u'\U0001F504', + u':aquarius:': u'\U00002652', + u':aries:': u'\U00002648', + u':arrow_heading_down:': u'\U00002935', + u':arrow_heading_up:': u'\U00002934', + u':articulated_lorry:': u'\U0001F69B', + u':art:': u'\U0001F3A8', + u':astonished:': u'\U0001F632', + u':athletic_shoe:': u'\U0001F45F', + u':atom_symbol:': u'\U0000269B', + u':eggplant:': u'\U0001F346', + u':atm:': u'\U0001F3E7', + u':car:': u'\U0001F697', + u':red_car:': u'\U0001F697', + u':baby:': u'\U0001F476', + u':angel:': u'\U0001F47C', + u':baby_bottle:': u'\U0001F37C', + u':baby_chick:': u'\U0001F424', + u':baby_symbol:': u'\U0001F6BC', + u':back:': u'\U0001F519', + u':camel:': u'\U0001F42B', + u':badminton_racquet_and_shuttlecock:': u'\U0001F3F8', + u':baggage_claim:': u'\U0001F6C4', + u':balloon:': u'\U0001F388', + u':ballot_box_with_ballot:': u'\U0001F5F3', + u':ballot_box_with_check:': u'\U00002611', + u':banana:': u'\U0001F34C', + u':bank:': u'\U0001F3E6', + u':dollar:': u'\U0001F4B5', + u':euro:': u'\U0001F4B6', + u':pound:': u'\U0001F4B7', + u':yen:': u'\U0001F4B4', + u':bar_chart:': u'\U0001F4CA', + u':barber:': u'\U0001F488', + u':baseball:': u'\U000026BE', + u':basketball:': u'\U0001F3C0', + u':bath:': u'\U0001F6C0', + u':bathtub:': u'\U0001F6C1', + u':battery:': u'\U0001F50B', + u':beach_with_umbrella:': u'\U0001F3D6', + u':bear:': u'\U0001F43B', + u':heartbeat:': u'\U0001F493', + u':bed:': u'\U0001F6CF', + u':beer:': u'\U0001F37A', + u':bell:': u'\U0001F514', + u':no_bell:': u'\U0001F515', + u':bellhop_bell:': u'\U0001F6CE', + u':bento:': u'\U0001F371', + u':bike:': u'\U0001F6B2', + u':bicyclist:': u'\U0001F6B4', + u':bikini:': u'\U0001F459', + u':8ball:': u'\U0001F3B1', + u':biohazard_sign:': u'\U00002623', + u':bird:': u'\U0001F426', + u':birthday:': u'\U0001F382', + u':black_circle_for_record:': u'\U000023FA', + u':clubs:': u'\U00002663', + u':diamonds:': u'\U00002666', + u':arrow_double_down:': u'\U000023EC', + u':hearts:': u'\U00002665', + u':black_large_square:': u'\U00002B1B', + u':rewind:': u'\U000023EA', + u':black_left__pointing_double_triangle_with_vertical_bar:': u'\U000023EE', + u':arrow_backward:': u'\U000025C0', + u':black_medium_small_square:': u'\U000025FE', + u':black_medium_square:': u'\U000025FC', + u':black_nib:': u'\U00002712', + u':question:': u'\U00002753', + u':fast_forward:': u'\U000023E9', + u':black_right__pointing_double_triangle_with_vertical_bar:': u'\U000023ED', + u':arrow_forward:': u'\U000025B6', + u':black_right__pointing_triangle_with_double_vertical_bar:': u'\U000023EF', + u':arrow_right:': u'\U000027A1', + u':scissors:': u'\U00002702', + u':black_small_square:': u'\U000025AA', + u':spades:': u'\U00002660', + u':black_square_button:': u'\U0001F532', + u':black_square_for_stop:': u'\U000023F9', + u':sunny:': u'\U00002600', + u':phone:': u'\U0000260E', + u':telephone:': u'\U0000260E', + u':recycle:': u'\U0000267B', + u':arrow_double_up:': u'\U000023EB', + u':blossom:': u'\U0001F33C', + u':blowfish:': u'\U0001F421', + u':blue_book:': u'\U0001F4D8', + u':blue_heart:': u'\U0001F499', + u':boar:': u'\U0001F417', + u':bomb:': u'\U0001F4A3', + u':bookmark:': u'\U0001F516', + u':bookmark_tabs:': u'\U0001F4D1', + u':books:': u'\U0001F4DA', + u':bottle_with_popping_cork:': u'\U0001F37E', + u':bouquet:': u'\U0001F490', + u':bow_and_arrow:': u'\U0001F3F9', + u':bowling:': u'\U0001F3B3', + u':boy:': u'\U0001F466', + u':bread:': u'\U0001F35E', + u':bride_with_veil:': u'\U0001F470', + u':bridge_at_night:': u'\U0001F309', + u':briefcase:': u'\U0001F4BC', + u':broken_heart:': u'\U0001F494', + u':bug:': u'\U0001F41B', + u':building_construction:': u'\U0001F3D7', + u':burrito:': u'\U0001F32F', + u':bus:': u'\U0001F68C', + u':busstop:': u'\U0001F68F', + u':bust_in_silhouette:': u'\U0001F464', + u':busts_in_silhouette:': u'\U0001F465', + u':cactus:': u'\U0001F335', + u':date:': u'\U0001F4C5', + u':camera:': u'\U0001F4F7', + u':camera_with_flash:': u'\U0001F4F8', + u':camping:': u'\U0001F3D5', + u':cancer:': u'\U0000264B', + u':candle:': u'\U0001F56F', + u':candy:': u'\U0001F36C', + u':capricorn:': u'\U00002651', + u':card_file_box:': u'\U0001F5C3', + u':card_index:': u'\U0001F4C7', + u':card_index_dividers:': u'\U0001F5C2', + u':carousel_horse:': u'\U0001F3A0', + u':flags:': u'\U0001F38F', + u':cat2:': u'\U0001F408', + u':cat:': u'\U0001F431', + u':joy_cat:': u'\U0001F639', + u':smirk_cat:': u'\U0001F63C', + u':chains:': u'\U000026D3', + u':chart_with_downwards_trend:': u'\U0001F4C9', + u':chart_with_upwards_trend:': u'\U0001F4C8', + u':chart:': u'\U0001F4B9', + u':mega:': u'\U0001F4E3', + u':cheese_wedge:': u'\U0001F9C0', + u':checkered_flag:': u'\U0001F3C1', + u':cherries:': u'\U0001F352', + u':cherry_blossom:': u'\U0001F338', + u':chestnut:': u'\U0001F330', + u':chicken:': u'\U0001F414', + u':children_crossing:': u'\U0001F6B8', + u':chipmunk:': u'\U0001F43F', + u':chocolate_bar:': u'\U0001F36B', + u':christmas_tree:': u'\U0001F384', + u':church:': u'\U000026EA', + u':cinema:': u'\U0001F3A6', + u':accept:': u'\U0001F251', + u':ideograph_advantage:': u'\U0001F250', + u':congratulations:': u'\U00003297', + u':secret:': u'\U00003299', + u':m:': u'\U000024C2', + u':circus_tent:': u'\U0001F3AA', + u':cityscape:': u'\U0001F3D9', + u':city_sunset:': u'\U0001F306', + u':clapper:': u'\U0001F3AC', + u':clap:': u'\U0001F44F', + u':classical_building:': u'\U0001F3DB', + u':beers:': u'\U0001F37B', + u':clipboard:': u'\U0001F4CB', + u':clock830:': u'\U0001F563', + u':clock8:': u'\U0001F557', + u':clock1130:': u'\U0001F566', + u':clock11:': u'\U0001F55A', + u':clock530:': u'\U0001F560', + u':clock5:': u'\U0001F554', + u':clock430:': u'\U0001F55F', + u':clock4:': u'\U0001F553', + u':clock930:': u'\U0001F564', + u':clock9:': u'\U0001F558', + u':clock130:': u'\U0001F55C', + u':clock1:': u'\U0001F550', + u':clock730:': u'\U0001F562', + u':clock7:': u'\U0001F556', + u':clock630:': u'\U0001F561', + u':clock6:': u'\U0001F555', + u':clock1030:': u'\U0001F565', + u':clock10:': u'\U0001F559', + u':clock330:': u'\U0001F55E', + u':clock3:': u'\U0001F552', + u':clock1230:': u'\U0001F567', + u':clock12:': u'\U0001F55B', + u':clock230:': u'\U0001F55D', + u':clock2:': u'\U0001F551', + u':arrows_clockwise:': u'\U0001F503', + u':repeat:': u'\U0001F501', + u':repeat_one:': u'\U0001F502', + u':closed_book:': u'\U0001F4D5', + u':closed_lock_with_key:': u'\U0001F510', + u':mailbox_closed:': u'\U0001F4EA', + u':mailbox:': u'\U0001F4EB', + u':closed_umbrella:': u'\U0001F302', + u':cloud:': u'\U00002601', + u':cloud_with_lightning:': u'\U0001F329', + u':cloud_with_rain:': u'\U0001F327', + u':cloud_with_snow:': u'\U0001F328', + u':cloud_with_tornado:': u'\U0001F32A', + u':cocktail:': u'\U0001F378', + u':coffin:': u'\U000026B0', + u':boom:': u'\U0001F4A5', + u':collision:': u'\U0001F4A5', + u':comet:': u'\U00002604', + u':compression:': u'\U0001F5DC', + u':confetti_ball:': u'\U0001F38A', + u':confounded:': u'\U0001F616', + u':confused:': u'\U0001F615', + u':construction:': u'\U0001F6A7', + u':construction_worker:': u'\U0001F477', + u':control_knobs:': u'\U0001F39B', + u':convenience_store:': u'\U0001F3EA', + u':rice:': u'\U0001F35A', + u':cookie:': u'\U0001F36A', + u':egg:': u'\U0001F373', + u':egg2:': u'\U0001F95A', + u':copyright:': u'\U000000A9', + u':couch_and_lamp:': u'\U0001F6CB', + u':couple_with_heart:': u'\U0001F491', + u':cow2:': u'\U0001F404', + u':cow:': u'\U0001F42E', + u':crab:': u'\U0001F980', + u':credit_card:': u'\U0001F4B3', + u':crescent_moon:': u'\U0001F319', + u':cricket_bat_and_ball:': u'\U0001F3CF', + u':crocodile:': u'\U0001F40A', + u':x:': u'\U0000274C', + u':crossed_flags:': u'\U0001F38C', + u':crossed_swords:': u'\U00002694', + u':crown:': u'\U0001F451', + u':crying_cat_face:': u'\U0001F63F', + u':cry:': u'\U0001F622', + u':crystal_ball:': u'\U0001F52E', + u':curly_loop:': u'\U000027B0', + u':currency_exchange:': u'\U0001F4B1', + u':curry:': u'\U0001F35B', + u':custard:': u'\U0001F36E', + u':customs:': u'\U0001F6C3', + u':cyclone:': u'\U0001F300', + u':dagger_knife:': u'\U0001F5E1', + u':dancer:': u'\U0001F483', + u':dango:': u'\U0001F361', + u':dark_sunglasses:': u'\U0001F576', + u':dash:': u'\U0001F4A8', + u':deciduous_tree:': u'\U0001F333', + u':truck:': u'\U0001F69A', + u':department_store:': u'\U0001F3EC', + u':derelict_house_building:': u'\U0001F3DA', + u':desert:': u'\U0001F3DC', + u':desert_island:': u'\U0001F3DD', + u':desktop_computer:': u'\U0001F5A5', + u':diamond_shape_with_a_dot_inside:': u'\U0001F4A0', + u':dart:': u'\U0001F3AF', + u':disappointed_relieved:': u'\U0001F625', + u':disappointed:': u'\U0001F61E', + u':dizzy_face:': u'\U0001F635', + u':dizzy:': u'\U0001F4AB', + u':do_not_litter:': u'\U0001F6AF', + u':dog2:': u'\U0001F415', + u':dog:': u'\U0001F436', + u':dolphin:': u'\U0001F42C', + u':flipper:': u'\U0001F42C', + u':door:': u'\U0001F6AA', + u':loop:': u'\U000027BF', + u':bangbang:': u'\U0000203C', + u':double_vertical_bar:': u'\U000023F8', + u':doughnut:': u'\U0001F369', + u':dove_of_peace:': u'\U0001F54A', + u':small_red_triangle_down:': u'\U0001F53B', + u':arrow_down_small:': u'\U0001F53D', + u':arrow_down:': u'\U00002B07', + u':dragon:': u'\U0001F409', + u':dragon_face:': u'\U0001F432', + u':dress:': u'\U0001F457', + u':dromedary_camel:': u'\U0001F42A', + u':droplet:': u'\U0001F4A7', + u':dvd:': u'\U0001F4C0', + u':e__mail:': u'\U0001F4E7', + u':ear:': u'\U0001F442', + u':corn:': u'\U0001F33D', + u':ear_of_rice:': u'\U0001F33E', + u':earth_americas:': u'\U0001F30E', + u':earth_asia:': u'\U0001F30F', + u':earth_africa:': u'\U0001F30D', + u':eight_pointed_black_star:': u'\U00002734', + u':eight_spoked_asterisk:': u'\U00002733', + u':eject_symbol:': u'\U000023CF', + u':bulb:': u'\U0001F4A1', + u':electric_plug:': u'\U0001F50C', + u':flashlight:': u'\U0001F526', + u':elephant:': u'\U0001F418', + u':emoji_modifier_fitzpatrick_type__1__2:': u'\U0001F3FB', + u':emoji_modifier_fitzpatrick_type__3:': u'\U0001F3FC', + u':emoji_modifier_fitzpatrick_type__4:': u'\U0001F3FD', + u':emoji_modifier_fitzpatrick_type__5:': u'\U0001F3FE', + u':emoji_modifier_fitzpatrick_type__6:': u'\U0001F3FF', + u':end:': u'\U0001F51A', + u':email:': u'\U00002709', + u':envelope:': u'\U00002709', + u':envelope_with_arrow:': u'\U0001F4E9', + u':european_castle:': u'\U0001F3F0', + u':european_post_office:': u'\U0001F3E4', + u':evergreen_tree:': u'\U0001F332', + u':interrobang:': u'\U00002049', + u':expressionless:': u'\U0001F611', + u':alien:': u'\U0001F47D', + u':eye:': u'\U0001F441', + u':eyeglasses:': u'\U0001F453', + u':eyes:': u'\U0001F440', + u':massage:': u'\U0001F486', + u':yum:': u'\U0001F60B', + u':scream:': u'\U0001F631', + u':kissing_heart:': u'\U0001F618', + u':sweat:': u'\U0001F613', + u':face_with_head__bandage:': u'\U0001F915', + u':triumph:': u'\U0001F624', + u':mask:': u'\U0001F637', + u':no_good:': u'\U0001F645', + u':ok_woman:': u'\U0001F646', + u':open_mouth:': u'\U0001F62E', + u':cold_sweat:': u'\U0001F630', + u':face_with_rolling_eyes:': u'\U0001F644', + u':stuck_out_tongue:': u'\U0001F61B', + u':stuck_out_tongue_closed_eyes:': u'\U0001F61D', + u':stuck_out_tongue_winking_eye:': u'\U0001F61C', + u':joy:': u'\U0001F602', + u':face_with_thermometer:': u'\U0001F912', + u':no_mouth:': u'\U0001F636', + u':factory:': u'\U0001F3ED', + u':fallen_leaf:': u'\U0001F342', + u':family:': u'\U0001F46A', + u':santa:': u'\U0001F385', + u':fax:': u'\U0001F4E0', + u':fearful:': u'\U0001F628', + u':ferris_wheel:': u'\U0001F3A1', + u':ferry:': u'\U000026F4', + u':field_hockey_stick_and_ball:': u'\U0001F3D1', + u':file_cabinet:': u'\U0001F5C4', + u':file_folder:': u'\U0001F4C1', + u':film_frames:': u'\U0001F39E', + u':film_projector:': u'\U0001F4FD', + u':fire:': u'\U0001F525', + u':fire_engine:': u'\U0001F692', + u':sparkler:': u'\U0001F387', + u':fireworks:': u'\U0001F386', + u':first_quarter_moon:': u'\U0001F313', + u':first_quarter_moon_with_face:': u'\U0001F31B', + u':fish:': u'\U0001F41F', + u':fish_cake:': u'\U0001F365', + u':fishing_pole_and_fish:': u'\U0001F3A3', + u':facepunch:': u'\U0001F44A', + u':punch:': u'\U0001F44A', + u':flag_for_Afghanistan:': u'\U0001F1E6\U0001F1EB', + u':flag_for_Albania:': u'\U0001F1E6\U0001F1F1', + u':flag_for_Algeria:': u'\U0001F1E9\U0001F1FF', + u':flag_for_American_Samoa:': u'\U0001F1E6\U0001F1F8', + u':flag_for_Andorra:': u'\U0001F1E6\U0001F1E9', + u':flag_for_Angola:': u'\U0001F1E6\U0001F1F4', + u':flag_for_Anguilla:': u'\U0001F1E6\U0001F1EE', + u':flag_for_Antarctica:': u'\U0001F1E6\U0001F1F6', + u':flag_for_Antigua_&_Barbuda:': u'\U0001F1E6\U0001F1EC', + u':flag_for_Argentina:': u'\U0001F1E6\U0001F1F7', + u':flag_for_Armenia:': u'\U0001F1E6\U0001F1F2', + u':flag_for_Aruba:': u'\U0001F1E6\U0001F1FC', + u':flag_for_Ascension_Island:': u'\U0001F1E6\U0001F1E8', + u':flag_for_Australia:': u'\U0001F1E6\U0001F1FA', + u':flag_for_Austria:': u'\U0001F1E6\U0001F1F9', + u':flag_for_Azerbaijan:': u'\U0001F1E6\U0001F1FF', + u':flag_for_Bahamas:': u'\U0001F1E7\U0001F1F8', + u':flag_for_Bahrain:': u'\U0001F1E7\U0001F1ED', + u':flag_for_Bangladesh:': u'\U0001F1E7\U0001F1E9', + u':flag_for_Barbados:': u'\U0001F1E7\U0001F1E7', + u':flag_for_Belarus:': u'\U0001F1E7\U0001F1FE', + u':flag_for_Belgium:': u'\U0001F1E7\U0001F1EA', + u':flag_for_Belize:': u'\U0001F1E7\U0001F1FF', + u':flag_for_Benin:': u'\U0001F1E7\U0001F1EF', + u':flag_for_Bermuda:': u'\U0001F1E7\U0001F1F2', + u':flag_for_Bhutan:': u'\U0001F1E7\U0001F1F9', + u':flag_for_Bolivia:': u'\U0001F1E7\U0001F1F4', + u':flag_for_Bosnia_&_Herzegovina:': u'\U0001F1E7\U0001F1E6', + u':flag_for_Botswana:': u'\U0001F1E7\U0001F1FC', + u':flag_for_Bouvet_Island:': u'\U0001F1E7\U0001F1FB', + u':flag_for_Brazil:': u'\U0001F1E7\U0001F1F7', + u':flag_for_British_Indian_Ocean_Territory:': u'\U0001F1EE\U0001F1F4', + u':flag_for_British_Virgin_Islands:': u'\U0001F1FB\U0001F1EC', + u':flag_for_Brunei:': u'\U0001F1E7\U0001F1F3', + u':flag_for_Bulgaria:': u'\U0001F1E7\U0001F1EC', + u':flag_for_Burkina_Faso:': u'\U0001F1E7\U0001F1EB', + u':flag_for_Burundi:': u'\U0001F1E7\U0001F1EE', + u':flag_for_Cambodia:': u'\U0001F1F0\U0001F1ED', + u':flag_for_Cameroon:': u'\U0001F1E8\U0001F1F2', + u':flag_for_Canada:': u'\U0001F1E8\U0001F1E6', + u':flag_for_Canary_Islands:': u'\U0001F1EE\U0001F1E8', + u':flag_for_Cape_Verde:': u'\U0001F1E8\U0001F1FB', + u':flag_for_Caribbean_Netherlands:': u'\U0001F1E7\U0001F1F6', + u':flag_for_Cayman_Islands:': u'\U0001F1F0\U0001F1FE', + u':flag_for_Central_African_Republic:': u'\U0001F1E8\U0001F1EB', + u':flag_for_Ceuta_&_Melilla:': u'\U0001F1EA\U0001F1E6', + u':flag_for_Chad:': u'\U0001F1F9\U0001F1E9', + u':flag_for_Chile:': u'\U0001F1E8\U0001F1F1', + u':flag_for_China:': u'\U0001F1E8\U0001F1F3', + u':flag_for_Christmas_Island:': u'\U0001F1E8\U0001F1FD', + u':flag_for_Clipperton_Island:': u'\U0001F1E8\U0001F1F5', + u':flag_for_Cocos__Islands:': u'\U0001F1E8\U0001F1E8', + u':flag_for_Colombia:': u'\U0001F1E8\U0001F1F4', + u':flag_for_Comoros:': u'\U0001F1F0\U0001F1F2', + u':flag_for_Congo____Brazzaville:': u'\U0001F1E8\U0001F1EC', + u':flag_for_Congo____Kinshasa:': u'\U0001F1E8\U0001F1E9', + u':flag_for_Cook_Islands:': u'\U0001F1E8\U0001F1F0', + u':flag_for_Costa_Rica:': u'\U0001F1E8\U0001F1F7', + u':flag_for_Croatia:': u'\U0001F1ED\U0001F1F7', + u':flag_for_Cuba:': u'\U0001F1E8\U0001F1FA', + u':flag_for_Curaçao:': u'\U0001F1E8\U0001F1FC', + u':flag_for_Cyprus:': u'\U0001F1E8\U0001F1FE', + u':flag_for_Czech_Republic:': u'\U0001F1E8\U0001F1FF', + u':flag_for_Côte_d’Ivoire:': u'\U0001F1E8\U0001F1EE', + u':flag_for_Denmark:': u'\U0001F1E9\U0001F1F0', + u':flag_for_Diego_Garcia:': u'\U0001F1E9\U0001F1EC', + u':flag_for_Djibouti:': u'\U0001F1E9\U0001F1EF', + u':flag_for_Dominica:': u'\U0001F1E9\U0001F1F2', + u':flag_for_Dominican_Republic:': u'\U0001F1E9\U0001F1F4', + u':flag_for_Ecuador:': u'\U0001F1EA\U0001F1E8', + u':flag_for_Egypt:': u'\U0001F1EA\U0001F1EC', + u':flag_for_El_Salvador:': u'\U0001F1F8\U0001F1FB', + u':flag_for_Equatorial_Guinea:': u'\U0001F1EC\U0001F1F6', + u':flag_for_Eritrea:': u'\U0001F1EA\U0001F1F7', + u':flag_for_Estonia:': u'\U0001F1EA\U0001F1EA', + u':flag_for_Ethiopia:': u'\U0001F1EA\U0001F1F9', + u':flag_for_European_Union:': u'\U0001F1EA\U0001F1FA', + u':flag_for_Falkland_Islands:': u'\U0001F1EB\U0001F1F0', + u':flag_for_Faroe_Islands:': u'\U0001F1EB\U0001F1F4', + u':flag_for_Fiji:': u'\U0001F1EB\U0001F1EF', + u':flag_for_Finland:': u'\U0001F1EB\U0001F1EE', + u':flag_for_France:': u'\U0001F1EB\U0001F1F7', + u':flag_for_French_Guiana:': u'\U0001F1EC\U0001F1EB', + u':flag_for_French_Polynesia:': u'\U0001F1F5\U0001F1EB', + u':flag_for_French_Southern_Territories:': u'\U0001F1F9\U0001F1EB', + u':flag_for_Gabon:': u'\U0001F1EC\U0001F1E6', + u':flag_for_Gambia:': u'\U0001F1EC\U0001F1F2', + u':flag_for_Georgia:': u'\U0001F1EC\U0001F1EA', + u':flag_for_Germany:': u'\U0001F1E9\U0001F1EA', + u':flag_for_Ghana:': u'\U0001F1EC\U0001F1ED', + u':flag_for_Gibraltar:': u'\U0001F1EC\U0001F1EE', + u':flag_for_Greece:': u'\U0001F1EC\U0001F1F7', + u':flag_for_Greenland:': u'\U0001F1EC\U0001F1F1', + u':flag_for_Grenada:': u'\U0001F1EC\U0001F1E9', + u':flag_for_Guadeloupe:': u'\U0001F1EC\U0001F1F5', + u':flag_for_Guam:': u'\U0001F1EC\U0001F1FA', + u':flag_for_Guatemala:': u'\U0001F1EC\U0001F1F9', + u':flag_for_Guernsey:': u'\U0001F1EC\U0001F1EC', + u':flag_for_Guinea:': u'\U0001F1EC\U0001F1F3', + u':flag_for_Guinea__Bissau:': u'\U0001F1EC\U0001F1FC', + u':flag_for_Guyana:': u'\U0001F1EC\U0001F1FE', + u':flag_for_Haiti:': u'\U0001F1ED\U0001F1F9', + u':flag_for_Heard_&_McDonald_Islands:': u'\U0001F1ED\U0001F1F2', + u':flag_for_Honduras:': u'\U0001F1ED\U0001F1F3', + u':flag_for_Hong_Kong:': u'\U0001F1ED\U0001F1F0', + u':flag_for_Hungary:': u'\U0001F1ED\U0001F1FA', + u':flag_for_Iceland:': u'\U0001F1EE\U0001F1F8', + u':flag_for_India:': u'\U0001F1EE\U0001F1F3', + u':flag_for_Indonesia:': u'\U0001F1EE\U0001F1E9', + u':flag_for_Iran:': u'\U0001F1EE\U0001F1F7', + u':flag_for_Iraq:': u'\U0001F1EE\U0001F1F6', + u':flag_for_Ireland:': u'\U0001F1EE\U0001F1EA', + u':flag_for_Isle_of_Man:': u'\U0001F1EE\U0001F1F2', + u':flag_for_Israel:': u'\U0001F1EE\U0001F1F1', + u':flag_for_Italy:': u'\U0001F1EE\U0001F1F9', + u':flag_for_Jamaica:': u'\U0001F1EF\U0001F1F2', + u':flag_for_Japan:': u'\U0001F1EF\U0001F1F5', + u':flag_for_Jersey:': u'\U0001F1EF\U0001F1EA', + u':flag_for_Jordan:': u'\U0001F1EF\U0001F1F4', + u':flag_for_Kazakhstan:': u'\U0001F1F0\U0001F1FF', + u':flag_for_Kenya:': u'\U0001F1F0\U0001F1EA', + u':flag_for_Kiribati:': u'\U0001F1F0\U0001F1EE', + u':flag_for_Kosovo:': u'\U0001F1FD\U0001F1F0', + u':flag_for_Kuwait:': u'\U0001F1F0\U0001F1FC', + u':flag_for_Kyrgyzstan:': u'\U0001F1F0\U0001F1EC', + u':flag_for_Laos:': u'\U0001F1F1\U0001F1E6', + u':flag_for_Latvia:': u'\U0001F1F1\U0001F1FB', + u':flag_for_Lebanon:': u'\U0001F1F1\U0001F1E7', + u':flag_for_Lesotho:': u'\U0001F1F1\U0001F1F8', + u':flag_for_Liberia:': u'\U0001F1F1\U0001F1F7', + u':flag_for_Libya:': u'\U0001F1F1\U0001F1FE', + u':flag_for_Liechtenstein:': u'\U0001F1F1\U0001F1EE', + u':flag_for_Lithuania:': u'\U0001F1F1\U0001F1F9', + u':flag_for_Luxembourg:': u'\U0001F1F1\U0001F1FA', + u':flag_for_Macau:': u'\U0001F1F2\U0001F1F4', + u':flag_for_Macedonia:': u'\U0001F1F2\U0001F1F0', + u':flag_for_Madagascar:': u'\U0001F1F2\U0001F1EC', + u':flag_for_Malawi:': u'\U0001F1F2\U0001F1FC', + u':flag_for_Malaysia:': u'\U0001F1F2\U0001F1FE', + u':flag_for_Maldives:': u'\U0001F1F2\U0001F1FB', + u':flag_for_Mali:': u'\U0001F1F2\U0001F1F1', + u':flag_for_Malta:': u'\U0001F1F2\U0001F1F9', + u':flag_for_Marshall_Islands:': u'\U0001F1F2\U0001F1ED', + u':flag_for_Martinique:': u'\U0001F1F2\U0001F1F6', + u':flag_for_Mauritania:': u'\U0001F1F2\U0001F1F7', + u':flag_for_Mauritius:': u'\U0001F1F2\U0001F1FA', + u':flag_for_Mayotte:': u'\U0001F1FE\U0001F1F9', + u':flag_for_Mexico:': u'\U0001F1F2\U0001F1FD', + u':flag_for_Micronesia:': u'\U0001F1EB\U0001F1F2', + u':flag_for_Moldova:': u'\U0001F1F2\U0001F1E9', + u':flag_for_Monaco:': u'\U0001F1F2\U0001F1E8', + u':flag_for_Mongolia:': u'\U0001F1F2\U0001F1F3', + u':flag_for_Montenegro:': u'\U0001F1F2\U0001F1EA', + u':flag_for_Montserrat:': u'\U0001F1F2\U0001F1F8', + u':flag_for_Morocco:': u'\U0001F1F2\U0001F1E6', + u':flag_for_Mozambique:': u'\U0001F1F2\U0001F1FF', + u':flag_for_Myanmar:': u'\U0001F1F2\U0001F1F2', + u':flag_for_Namibia:': u'\U0001F1F3\U0001F1E6', + u':flag_for_Nauru:': u'\U0001F1F3\U0001F1F7', + u':flag_for_Nepal:': u'\U0001F1F3\U0001F1F5', + u':flag_for_Netherlands:': u'\U0001F1F3\U0001F1F1', + u':flag_for_New_Caledonia:': u'\U0001F1F3\U0001F1E8', + u':flag_for_New_Zealand:': u'\U0001F1F3\U0001F1FF', + u':flag_for_Nicaragua:': u'\U0001F1F3\U0001F1EE', + u':flag_for_Niger:': u'\U0001F1F3\U0001F1EA', + u':flag_for_Nigeria:': u'\U0001F1F3\U0001F1EC', + u':flag_for_Niue:': u'\U0001F1F3\U0001F1FA', + u':flag_for_Norfolk_Island:': u'\U0001F1F3\U0001F1EB', + u':flag_for_North_Korea:': u'\U0001F1F0\U0001F1F5', + u':flag_for_Northern_Mariana_Islands:': u'\U0001F1F2\U0001F1F5', + u':flag_for_Norway:': u'\U0001F1F3\U0001F1F4', + u':flag_for_Oman:': u'\U0001F1F4\U0001F1F2', + u':flag_for_Pakistan:': u'\U0001F1F5\U0001F1F0', + u':flag_for_Palau:': u'\U0001F1F5\U0001F1FC', + u':flag_for_Palestinian_Territories:': u'\U0001F1F5\U0001F1F8', + u':flag_for_Panama:': u'\U0001F1F5\U0001F1E6', + u':flag_for_Papua_New_Guinea:': u'\U0001F1F5\U0001F1EC', + u':flag_for_Paraguay:': u'\U0001F1F5\U0001F1FE', + u':flag_for_Peru:': u'\U0001F1F5\U0001F1EA', + u':flag_for_Philippines:': u'\U0001F1F5\U0001F1ED', + u':flag_for_Pitcairn_Islands:': u'\U0001F1F5\U0001F1F3', + u':flag_for_Poland:': u'\U0001F1F5\U0001F1F1', + u':flag_for_Portugal:': u'\U0001F1F5\U0001F1F9', + u':flag_for_Puerto_Rico:': u'\U0001F1F5\U0001F1F7', + u':flag_for_Qatar:': u'\U0001F1F6\U0001F1E6', + u':flag_for_Romania:': u'\U0001F1F7\U0001F1F4', + u':flag_for_Russia:': u'\U0001F1F7\U0001F1FA', + u':flag_for_Rwanda:': u'\U0001F1F7\U0001F1FC', + u':flag_for_Réunion:': u'\U0001F1F7\U0001F1EA', + u':flag_for_Samoa:': u'\U0001F1FC\U0001F1F8', + u':flag_for_San_Marino:': u'\U0001F1F8\U0001F1F2', + u':flag_for_Saudi_Arabia:': u'\U0001F1F8\U0001F1E6', + u':flag_for_Senegal:': u'\U0001F1F8\U0001F1F3', + u':flag_for_Serbia:': u'\U0001F1F7\U0001F1F8', + u':flag_for_Seychelles:': u'\U0001F1F8\U0001F1E8', + u':flag_for_Sierra_Leone:': u'\U0001F1F8\U0001F1F1', + u':flag_for_Singapore:': u'\U0001F1F8\U0001F1EC', + u':flag_for_Sint_Maarten:': u'\U0001F1F8\U0001F1FD', + u':flag_for_Slovakia:': u'\U0001F1F8\U0001F1F0', + u':flag_for_Slovenia:': u'\U0001F1F8\U0001F1EE', + u':flag_for_Solomon_Islands:': u'\U0001F1F8\U0001F1E7', + u':flag_for_Somalia:': u'\U0001F1F8\U0001F1F4', + u':flag_for_South_Africa:': u'\U0001F1FF\U0001F1E6', + u':flag_for_South_Georgia_&_South_Sandwich_Islands:': u'\U0001F1EC\U0001F1F8', + u':flag_for_South_Korea:': u'\U0001F1F0\U0001F1F7', + u':flag_for_South_Sudan:': u'\U0001F1F8\U0001F1F8', + u':flag_for_Spain:': u'\U0001F1EA\U0001F1F8', + u':flag_for_Sri_Lanka:': u'\U0001F1F1\U0001F1F0', + u':flag_for_St._Barthélemy:': u'\U0001F1E7\U0001F1F1', + u':flag_for_St._Helena:': u'\U0001F1F8\U0001F1ED', + u':flag_for_St._Kitts_&_Nevis:': u'\U0001F1F0\U0001F1F3', + u':flag_for_St._Lucia:': u'\U0001F1F1\U0001F1E8', + u':flag_for_St._Martin:': u'\U0001F1F2\U0001F1EB', + u':flag_for_St._Pierre_&_Miquelon:': u'\U0001F1F5\U0001F1F2', + u':flag_for_St._Vincent_&_Grenadines:': u'\U0001F1FB\U0001F1E8', + u':flag_for_Sudan:': u'\U0001F1F8\U0001F1E9', + u':flag_for_Suriname:': u'\U0001F1F8\U0001F1F7', + u':flag_for_Svalbard_&_Jan_Mayen:': u'\U0001F1F8\U0001F1EF', + u':flag_for_Swaziland:': u'\U0001F1F8\U0001F1FF', + u':flag_for_Sweden:': u'\U0001F1F8\U0001F1EA', + u':flag_for_Switzerland:': u'\U0001F1E8\U0001F1ED', + u':flag_for_Syria:': u'\U0001F1F8\U0001F1FE', + u':flag_for_São_Tomé_&_Príncipe:': u'\U0001F1F8\U0001F1F9', + u':flag_for_Taiwan:': u'\U0001F1F9\U0001F1FC', + u':flag_for_Tajikistan:': u'\U0001F1F9\U0001F1EF', + u':flag_for_Tanzania:': u'\U0001F1F9\U0001F1FF', + u':flag_for_Thailand:': u'\U0001F1F9\U0001F1ED', + u':flag_for_Timor__Leste:': u'\U0001F1F9\U0001F1F1', + u':flag_for_Togo:': u'\U0001F1F9\U0001F1EC', + u':flag_for_Tokelau:': u'\U0001F1F9\U0001F1F0', + u':flag_for_Tonga:': u'\U0001F1F9\U0001F1F4', + u':flag_for_Trinidad_&_Tobago:': u'\U0001F1F9\U0001F1F9', + u':flag_for_Tristan_da_Cunha:': u'\U0001F1F9\U0001F1E6', + u':flag_for_Tunisia:': u'\U0001F1F9\U0001F1F3', + u':flag_for_Turkey:': u'\U0001F1F9\U0001F1F7', + u':flag_for_Turkmenistan:': u'\U0001F1F9\U0001F1F2', + u':flag_for_Turks_&_Caicos_Islands:': u'\U0001F1F9\U0001F1E8', + u':flag_for_Tuvalu:': u'\U0001F1F9\U0001F1FB', + u':flag_for_U.S._Outlying_Islands:': u'\U0001F1FA\U0001F1F2', + u':flag_for_U.S._Virgin_Islands:': u'\U0001F1FB\U0001F1EE', + u':flag_for_Uganda:': u'\U0001F1FA\U0001F1EC', + u':flag_for_Ukraine:': u'\U0001F1FA\U0001F1E6', + u':flag_for_United_Arab_Emirates:': u'\U0001F1E6\U0001F1EA', + u':flag_for_United_Kingdom:': u'\U0001F1EC\U0001F1E7', + u':flag_for_United_States:': u'\U0001F1FA\U0001F1F8', + u':flag_for_Uruguay:': u'\U0001F1FA\U0001F1FE', + u':flag_for_Uzbekistan:': u'\U0001F1FA\U0001F1FF', + u':flag_for_Vanuatu:': u'\U0001F1FB\U0001F1FA', + u':flag_for_Vatican_City:': u'\U0001F1FB\U0001F1E6', + u':flag_for_Venezuela:': u'\U0001F1FB\U0001F1EA', + u':flag_for_Vietnam:': u'\U0001F1FB\U0001F1F3', + u':flag_for_Wallis_&_Futuna:': u'\U0001F1FC\U0001F1EB', + u':flag_for_Western_Sahara:': u'\U0001F1EA\U0001F1ED', + u':flag_for_Yemen:': u'\U0001F1FE\U0001F1EA', + u':flag_for_Zambia:': u'\U0001F1FF\U0001F1F2', + u':flag_for_Zimbabwe:': u'\U0001F1FF\U0001F1FC', + u':flag_for_Åland_Islands:': u'\U0001F1E6\U0001F1FD', + u':golf:': u'\U000026F3', + u':fleur__de__lis:': u'\U0000269C', + u':muscle:': u'\U0001F4AA', + u':floppy_disk:': u'\U0001F4BE', + u':flower_playing_cards:': u'\U0001F3B4', + u':flushed:': u'\U0001F633', + u':fog:': u'\U0001F32B', + u':foggy:': u'\U0001F301', + u':footprints:': u'\U0001F463', + u':fork_and_knife:': u'\U0001F374', + u':fork_and_knife_with_plate:': u'\U0001F37D', + u':fountain:': u'\U000026F2', + u':four_leaf_clover:': u'\U0001F340', + u':frame_with_picture:': u'\U0001F5BC', + u':fries:': u'\U0001F35F', + u':fried_shrimp:': u'\U0001F364', + u':frog:': u'\U0001F438', + u':hatched_chick:': u'\U0001F425', + u':frowning:': u'\U0001F626', + u':fuelpump:': u'\U000026FD', + u':full_moon:': u'\U0001F315', + u':full_moon_with_face:': u'\U0001F31D', + u':funeral_urn:': u'\U000026B1', + u':game_die:': u'\U0001F3B2', + u':gear:': u'\U00002699', + u':gem:': u'\U0001F48E', + u':gemini:': u'\U0000264A', + u':ghost:': u'\U0001F47B', + u':girl:': u'\U0001F467', + u':globe_with_meridians:': u'\U0001F310', + u':star2:': u'\U0001F31F', + u':goat:': u'\U0001F410', + u':golfer:': u'\U0001F3CC', + u':mortar_board:': u'\U0001F393', + u':grapes:': u'\U0001F347', + u':green_apple:': u'\U0001F34F', + u':green_book:': u'\U0001F4D7', + u':green_heart:': u'\U0001F49A', + u':grimacing:': u'\U0001F62C', + u':smile_cat:': u'\U0001F638', + u':grinning:': u'\U0001F600', + u':grin:': u'\U0001F601', + u':heartpulse:': u'\U0001F497', + u':guardsman:': u'\U0001F482', + u':guitar:': u'\U0001F3B8', + u':haircut:': u'\U0001F487', + u':hamburger:': u'\U0001F354', + u':hammer:': u'\U0001F528', + u':hammer_and_pick:': u'\U00002692', + u':hammer_and_wrench:': u'\U0001F6E0', + u':hamster:': u'\U0001F439', + u':handbag:': u'\U0001F45C', + u':raising_hand:': u'\U0001F64B', + u':hatching_chick:': u'\U0001F423', + u':headphones:': u'\U0001F3A7', + u':hear_no_evil:': u'\U0001F649', + u':heart_decoration:': u'\U0001F49F', + u':cupid:': u'\U0001F498', + u':gift_heart:': u'\U0001F49D', + u':heart:': u'\U00002764', + u':heavy_check_mark:': u'\U00002714', + u':heavy_division_sign:': u'\U00002797', + u':heavy_dollar_sign:': u'\U0001F4B2', + u':exclamation:': u'\U00002757', + u':heavy_exclamation_mark:': u'\U00002757', + u':heavy_heart_exclamation_mark_ornament:': u'\U00002763', + u':o:': u'\U00002B55', + u':heavy_minus_sign:': u'\U00002796', + u':heavy_multiplication_x:': u'\U00002716', + u':heavy_plus_sign:': u'\U00002795', + u':helicopter:': u'\U0001F681', + u':helm_symbol:': u'\U00002388', + u':helmet_with_white_cross:': u'\U000026D1', + u':herb:': u'\U0001F33F', + u':hibiscus:': u'\U0001F33A', + u':high_heel:': u'\U0001F460', + u':bullettrain_side:': u'\U0001F684', + u':bullettrain_front:': u'\U0001F685', + u':high_brightness:': u'\U0001F506', + u':zap:': u'\U000026A1', + u':hocho:': u'\U0001F52A', + u':knife:': u'\U0001F52A', + u':hole:': u'\U0001F573', + u':honey_pot:': u'\U0001F36F', + u':bee:': u'\U0001F41D', + u':traffic_light:': u'\U0001F6A5', + u':racehorse:': u'\U0001F40E', + u':horse:': u'\U0001F434', + u':horse_racing:': u'\U0001F3C7', + u':hospital:': u'\U0001F3E5', + u':coffee:': u'\U00002615', + u':hot_dog:': u'\U0001F32D', + u':hot_pepper:': u'\U0001F336', + u':hotsprings:': u'\U00002668', + u':hotel:': u'\U0001F3E8', + u':hourglass:': u'\U0000231B', + u':hourglass_flowing_sand:': u'\U000023F3', + u':house:': u'\U0001F3E0', + u':house_buildings:': u'\U0001F3D8', + u':house_with_garden:': u'\U0001F3E1', + u':hugging_face:': u'\U0001F917', + u':100:': u'\U0001F4AF', + u':hushed:': u'\U0001F62F', + u':ice_cream:': u'\U0001F368', + u':ice_hockey_stick_and_puck:': u'\U0001F3D2', + u':ice_skate:': u'\U000026F8', + u':imp:': u'\U0001F47F', + u':inbox_tray:': u'\U0001F4E5', + u':incoming_envelope:': u'\U0001F4E8', + u':information_desk_person:': u'\U0001F481', + u':information_source:': u'\U00002139', + u':capital_abcd:': u'\U0001F520', + u':abc:': u'\U0001F524', + u':abcd:': u'\U0001F521', + u':1234:': u'\U0001F522', + u':symbols:': u'\U0001F523', + u':izakaya_lantern:': u'\U0001F3EE', + u':lantern:': u'\U0001F3EE', + u':jack_o_lantern:': u'\U0001F383', + u':japanese_castle:': u'\U0001F3EF', + u':dolls:': u'\U0001F38E', + u':japanese_goblin:': u'\U0001F47A', + u':japanese_ogre:': u'\U0001F479', + u':post_office:': u'\U0001F3E3', + u':beginner:': u'\U0001F530', + u':jeans:': u'\U0001F456', + u':joystick:': u'\U0001F579', + u':kaaba:': u'\U0001F54B', + u':key:': u'\U0001F511', + u':keyboard:': u'\U00002328', + u':zero:': u'\U00000030\U0000FE0F\U000020E3', + u':one:': u'\U00000031\U0000FE0F\U000020E3', + u':ten:': u'\U0001F51F', + u':two:': u'\U00000032\U0000FE0F\U000020E3', + u':three:': u'\U00000033\U0000FE0F\U000020E3', + u':four:': u'\U00000034\U0000FE0F\U000020E3', + u':five:': u'\U00000035\U0000FE0F\U000020E3', + u':six:': u'\U00000036\U0000FE0F\U000020E3', + u':seven:': u'\U00000037\U0000FE0F\U000020E3', + u':eight:': u'\U00000038\U0000FE0F\U000020E3', + u':nine:': u'\U00000039\U0000FE0F\U000020E3', + u':kimono:': u'\U0001F458', + u':couplekiss:': u'\U0001F48F', + u':kiss:': u'\U0001F48B', + u':kissing_cat:': u'\U0001F63D', + u':kissing:': u'\U0001F617', + u':kissing_closed_eyes:': u'\U0001F61A', + u':kissing_smiling_eyes:': u'\U0001F619', + u':koala:': u'\U0001F428', + u':label:': u'\U0001F3F7', + u':beetle:': u'\U0001F41E', + u':large_blue_circle:': u'\U0001F535', + u':large_blue_diamond:': u'\U0001F537', + u':large_orange_diamond:': u'\U0001F536', + u':red_circle:': u'\U0001F534', + u':last_quarter_moon:': u'\U0001F317', + u':last_quarter_moon_with_face:': u'\U0001F31C', + u':latin_cross:': u'\U0000271D', + u':leaves:': u'\U0001F343', + u':ledger:': u'\U0001F4D2', + u':mag:': u'\U0001F50D', + u':left_luggage:': u'\U0001F6C5', + u':left_right_arrow:': u'\U00002194', + u':leftwards_arrow_with_hook:': u'\U000021A9', + u':arrow_left:': u'\U00002B05', + u':lemon:': u'\U0001F34B', + u':leo:': u'\U0000264C', + u':leopard:': u'\U0001F406', + u':level_slider:': u'\U0001F39A', + u':libra:': u'\U0000264E', + u':light_rail:': u'\U0001F688', + u':link:': u'\U0001F517', + u':linked_paperclips:': u'\U0001F587', + u':lion_face:': u'\U0001F981', + u':lipstick:': u'\U0001F484', + u':lock:': u'\U0001F512', + u':lock_with_ink_pen:': u'\U0001F50F', + u':lollipop:': u'\U0001F36D', + u':sob:': u'\U0001F62D', + u':love_hotel:': u'\U0001F3E9', + u':love_letter:': u'\U0001F48C', + u':low_brightness:': u'\U0001F505', + u':lower_left_ballpoint_pen:': u'\U0001F58A', + u':lower_left_crayon:': u'\U0001F58D', + u':lower_left_fountain_pen:': u'\U0001F58B', + u':lower_left_paintbrush:': u'\U0001F58C', + u':mahjong:': u'\U0001F004', + u':man:': u'\U0001F468', + u':couple:': u'\U0001F46B', + u':man_in_business_suit_levitating:': u'\U0001F574', + u':man_with_gua_pi_mao:': u'\U0001F472', + u':man_with_turban:': u'\U0001F473', + u':mans_shoe:': u'\U0001F45E', + u':shoe:': u'\U0001F45E', + u':mantelpiece_clock:': u'\U0001F570', + u':maple_leaf:': u'\U0001F341', + u':meat_on_bone:': u'\U0001F356', + u':black_circle:': u'\U000026AB', + u':white_circle:': u'\U000026AA', + u':melon:': u'\U0001F348', + u':memo:': u'\U0001F4DD', + u':pencil:': u'\U0001F4DD', + u':menorah_with_nine_branches:': u'\U0001F54E', + u':mens:': u'\U0001F6B9', + u':metro:': u'\U0001F687', + u':microphone:': u'\U0001F3A4', + u':microscope:': u'\U0001F52C', + u':military_medal:': u'\U0001F396', + u':milky_way:': u'\U0001F30C', + u':minibus:': u'\U0001F690', + u':minidisc:': u'\U0001F4BD', + u':iphone:': u'\U0001F4F1', + u':mobile_phone_off:': u'\U0001F4F4', + u':calling:': u'\U0001F4F2', + u':money__mouth_face:': u'\U0001F911', + u':moneybag:': u'\U0001F4B0', + u':money_with_wings:': u'\U0001F4B8', + u':monkey:': u'\U0001F412', + u':monkey_face:': u'\U0001F435', + u':monorail:': u'\U0001F69D', + u':rice_scene:': u'\U0001F391', + u':mosque:': u'\U0001F54C', + u':motor_boat:': u'\U0001F6E5', + u':motorway:': u'\U0001F6E3', + u':mount_fuji:': u'\U0001F5FB', + u':mountain:': u'\U000026F0', + u':mountain_bicyclist:': u'\U0001F6B5', + u':mountain_cableway:': u'\U0001F6A0', + u':mountain_railway:': u'\U0001F69E', + u':mouse2:': u'\U0001F401', + u':mouse:': u'\U0001F42D', + u':lips:': u'\U0001F444', + u':movie_camera:': u'\U0001F3A5', + u':moyai:': u'\U0001F5FF', + u':notes:': u'\U0001F3B6', + u':mushroom:': u'\U0001F344', + u':musical_keyboard:': u'\U0001F3B9', + u':musical_note:': u'\U0001F3B5', + u':musical_score:': u'\U0001F3BC', + u':nail_care:': u'\U0001F485', + u':name_badge:': u'\U0001F4DB', + u':national_park:': u'\U0001F3DE', + u':necktie:': u'\U0001F454', + u':ab:': u'\U0001F18E', + u':negative_squared_cross_mark:': u'\U0000274E', + u':a:': u'\U0001F170', + u':b:': u'\U0001F171', + u':o2:': u'\U0001F17E', + u':parking:': u'\U0001F17F', + u':nerd_face:': u'\U0001F913', + u':neutral_face:': u'\U0001F610', + u':new_moon:': u'\U0001F311', + u':honeybee:': u'\U0001F41D', + u':new_moon_with_face:': u'\U0001F31A', + u':newspaper:': u'\U0001F4F0', + u':night_with_stars:': u'\U0001F303', + u':no_bicycles:': u'\U0001F6B3', + u':no_entry:': u'\U000026D4', + u':no_entry_sign:': u'\U0001F6AB', + u':no_mobile_phones:': u'\U0001F4F5', + u':underage:': u'\U0001F51E', + u':no_pedestrians:': u'\U0001F6B7', + u':no_smoking:': u'\U0001F6AD', + u':non__potable_water:': u'\U0001F6B1', + u':arrow_upper_right:': u'\U00002197', + u':arrow_upper_left:': u'\U00002196', + u':nose:': u'\U0001F443', + u':notebook:': u'\U0001F4D3', + u':notebook_with_decorative_cover:': u'\U0001F4D4', + u':nut_and_bolt:': u'\U0001F529', + u':octopus:': u'\U0001F419', + u':oden:': u'\U0001F362', + u':office:': u'\U0001F3E2', + u':oil_drum:': u'\U0001F6E2', + u':ok_hand:': u'\U0001F44C', + u':old_key:': u'\U0001F5DD', + u':older_man:': u'\U0001F474', + u':older_woman:': u'\U0001F475', + u':om_symbol:': u'\U0001F549', + u':on:': u'\U0001F51B', + u':oncoming_automobile:': u'\U0001F698', + u':oncoming_bus:': u'\U0001F68D', + u':oncoming_police_car:': u'\U0001F694', + u':oncoming_taxi:': u'\U0001F696', + u':book:': u'\U0001F4D6', + u':open_book:': u'\U0001F4D6', + u':open_file_folder:': u'\U0001F4C2', + u':open_hands:': u'\U0001F450', + u':unlock:': u'\U0001F513', + u':mailbox_with_no_mail:': u'\U0001F4ED', + u':mailbox_with_mail:': u'\U0001F4EC', + u':ophiuchus:': u'\U000026CE', + u':cd:': u'\U0001F4BF', + u':orange_book:': u'\U0001F4D9', + u':orthodox_cross:': u'\U00002626', + u':outbox_tray:': u'\U0001F4E4', + u':ox:': u'\U0001F402', + u':package:': u'\U0001F4E6', + u':page_facing_up:': u'\U0001F4C4', + u':page_with_curl:': u'\U0001F4C3', + u':pager:': u'\U0001F4DF', + u':palm_tree:': u'\U0001F334', + u':panda_face:': u'\U0001F43C', + u':paperclip:': u'\U0001F4CE', + u':part_alternation_mark:': u'\U0000303D', + u':tada:': u'\U0001F389', + u':passenger_ship:': u'\U0001F6F3', + u':passport_control:': u'\U0001F6C2', + u':feet:': u'\U0001F43E', + u':paw_prints:': u'\U0001F43E', + u':peace_symbol:': u'\U0000262E', + u':peach:': u'\U0001F351', + u':pear:': u'\U0001F350', + u':walking:': u'\U0001F6B6', + u':pencil2:': u'\U0000270F', + u':penguin:': u'\U0001F427', + u':pensive:': u'\U0001F614', + u':performing_arts:': u'\U0001F3AD', + u':persevere:': u'\U0001F623', + u':bow:': u'\U0001F647', + u':person_frowning:': u'\U0001F64D', + u':raised_hands:': u'\U0001F64C', + u':person_with_ball:': u'\U000026F9', + u':person_with_blond_hair:': u'\U0001F471', + u':pray:': u'\U0001F64F', + u':person_with_pouting_face:': u'\U0001F64E', + u':computer:': u'\U0001F4BB', + u':pick:': u'\U000026CF', + u':pig2:': u'\U0001F416', + u':pig:': u'\U0001F437', + u':pig_nose:': u'\U0001F43D', + u':hankey:': u'\U0001F4A9', + u':poop:': u'\U0001F4A9', + u':shit:': u'\U0001F4A9', + u':pill:': u'\U0001F48A', + u':bamboo:': u'\U0001F38D', + u':pineapple:': u'\U0001F34D', + u':pisces:': u'\U00002653', + u':gun:': u'\U0001F52B', + u':place_of_worship:': u'\U0001F6D0', + u':black_joker:': u'\U0001F0CF', + u':police_car:': u'\U0001F693', + u':rotating_light:': u'\U0001F6A8', + u':cop:': u'\U0001F46E', + u':poodle:': u'\U0001F429', + u':popcorn:': u'\U0001F37F', + u':postal_horn:': u'\U0001F4EF', + u':postbox:': u'\U0001F4EE', + u':stew:': u'\U0001F372', + u':potable_water:': u'\U0001F6B0', + u':pouch:': u'\U0001F45D', + u':poultry_leg:': u'\U0001F357', + u':pouting_cat:': u'\U0001F63E', + u':rage:': u'\U0001F621', + u':prayer_beads:': u'\U0001F4FF', + u':princess:': u'\U0001F478', + u':printer:': u'\U0001F5A8', + u':loudspeaker:': u'\U0001F4E2', + u':purple_heart:': u'\U0001F49C', + u':purse:': u'\U0001F45B', + u':pushpin:': u'\U0001F4CC', + u':put_litter_in_its_place:': u'\U0001F6AE', + u':rabbit2:': u'\U0001F407', + u':rabbit:': u'\U0001F430', + u':racing_car:': u'\U0001F3CE', + u':racing_motorcycle:': u'\U0001F3CD', + u':radio:': u'\U0001F4FB', + u':radio_button:': u'\U0001F518', + u':radioactive_sign:': u'\U00002622', + u':railway_car:': u'\U0001F683', + u':railway_track:': u'\U0001F6E4', + u':rainbow:': u'\U0001F308', + u':fist:': u'\U0000270A', + u':hand:': u'\U0000270B', + u':raised_hand:': u'\U0000270B', + u':raised_hand_with_fingers_splayed:': u'\U0001F590', + u':raised_hand_with_part_between_middle_and_ring_fingers:': u'\U0001F596', + u':ram:': u'\U0001F40F', + u':rat:': u'\U0001F400', + u':blue_car:': u'\U0001F699', + u':apple:': u'\U0001F34E', + u':registered:': u'\U000000AE', + u':relieved:': u'\U0001F60C', + u':reminder_ribbon:': u'\U0001F397', + u':restroom:': u'\U0001F6BB', + u':reversed_hand_with_middle_finger_extended:': u'\U0001F595', + u':revolving_hearts:': u'\U0001F49E', + u':ribbon:': u'\U0001F380', + u':rice_ball:': u'\U0001F359', + u':rice_cracker:': u'\U0001F358', + u':mag_right:': u'\U0001F50E', + u':right_anger_bubble:': u'\U0001F5EF', + u':arrow_right_hook:': u'\U000021AA', + u':ring:': u'\U0001F48D', + u':sweet_potato:': u'\U0001F360', + u':robot_face:': u'\U0001F916', + u':robot:': u'\U0001F916', + u':rocket:': u'\U0001F680', + u':rolled__up_newspaper:': u'\U0001F5DE', + u':roller_coaster:': u'\U0001F3A2', + u':rooster:': u'\U0001F413', + u':rose:': u'\U0001F339', + u':rosette:': u'\U0001F3F5', + u':round_pushpin:': u'\U0001F4CD', + u':rowboat:': u'\U0001F6A3', + u':rugby_football:': u'\U0001F3C9', + u':runner:': u'\U0001F3C3', + u':running:': u'\U0001F3C3', + u':running_shirt_with_sash:': u'\U0001F3BD', + u':sagittarius:': u'\U00002650', + u':boat:': u'\U000026F5', + u':sailboat:': u'\U000026F5', + u':sake:': u'\U0001F376', + u':satellite:': u'\U0001F4E1', + u':saxophone:': u'\U0001F3B7', + u':scales:': u'\U00002696', + u':school:': u'\U0001F3EB', + u':school_satchel:': u'\U0001F392', + u':scorpion:': u'\U0001F982', + u':scorpius:': u'\U0000264F', + u':scroll:': u'\U0001F4DC', + u':seat:': u'\U0001F4BA', + u':see_no_evil:': u'\U0001F648', + u':seedling:': u'\U0001F331', + u':shamrock:': u'\U00002618', + u':shaved_ice:': u'\U0001F367', + u':sheep:': u'\U0001F411', + u':shield:': u'\U0001F6E1', + u':shinto_shrine:': u'\U000026E9', + u':ship:': u'\U0001F6A2', + u':stars:': u'\U0001F320', + u':shopping_bags:': u'\U0001F6CD', + u':cake:': u'\U0001F370', + u':shower:': u'\U0001F6BF', + u':sign_of_the_horns:': u'\U0001F918', + u':japan:': u'\U0001F5FE', + u':six_pointed_star:': u'\U0001F52F', + u':ski:': u'\U0001F3BF', + u':skier:': u'\U000026F7', + u':skull:': u'\U0001F480', + u':skull_and_crossbones:': u'\U00002620', + u':sleeping_accommodation:': u'\U0001F6CC', + u':sleeping:': u'\U0001F634', + u':zzz:': u'\U0001F4A4', + u':sleepy:': u'\U0001F62A', + u':sleuth_or_spy:': u'\U0001F575', + u':pizza:': u'\U0001F355', + u':slightly_frowning_face:': u'\U0001F641', + u':slightly_smiling_face:': u'\U0001F642', + u':slot_machine:': u'\U0001F3B0', + u':small_airplane:': u'\U0001F6E9', + u':small_blue_diamond:': u'\U0001F539', + u':small_orange_diamond:': u'\U0001F538', + u':heart_eyes_cat:': u'\U0001F63B', + u':smiley_cat:': u'\U0001F63A', + u':innocent:': u'\U0001F607', + u':heart_eyes:': u'\U0001F60D', + u':smiling_imp:': u'\U0001F608', + u':smiley:': u'\U0001F603', + u':sweat_smile:': u'\U0001F605', + u':smile:': u'\U0001F604', + u':laughing:': u'\U0001F606', + u':satisfied:': u'\U0001F606', + u':blush:': u'\U0001F60A', + u':sunglasses:': u'\U0001F60E', + u':smirk:': u'\U0001F60F', + u':smoking:': u'\U0001F6AC', + u':snail:': u'\U0001F40C', + u':snake:': u'\U0001F40D', + u':snow_capped_mountain:': u'\U0001F3D4', + u':snowboarder:': u'\U0001F3C2', + u':snowflake:': u'\U00002744', + u':snowman:': u'\U00002603', + u':soccer:': u'\U000026BD', + u':icecream:': u'\U0001F366', + u':soon:': u'\U0001F51C', + u':arrow_lower_right:': u'\U00002198', + u':arrow_lower_left:': u'\U00002199', + u':spaghetti:': u'\U0001F35D', + u':sparkle:': u'\U00002747', + u':sparkles:': u'\U00002728', + u':sparkling_heart:': u'\U0001F496', + u':speak_no_evil:': u'\U0001F64A', + u':speaker:': u'\U0001F508', + u':mute:': u'\U0001F507', + u':sound:': u'\U0001F509', + u':loud_sound:': u'\U0001F50A', + u':speaking_head_in_silhouette:': u'\U0001F5E3', + u':speech_balloon:': u'\U0001F4AC', + u':speedboat:': u'\U0001F6A4', + u':spider:': u'\U0001F577', + u':spider_web:': u'\U0001F578', + u':spiral_calendar_pad:': u'\U0001F5D3', + u':spiral_note_pad:': u'\U0001F5D2', + u':shell:': u'\U0001F41A', + u':sweat_drops:': u'\U0001F4A6', + u':sports_medal:': u'\U0001F3C5', + u':whale:': u'\U0001F433', + u':u5272:': u'\U0001F239', + u':u5408:': u'\U0001F234', + u':u55b6:': u'\U0001F23A', + u':u6307:': u'\U0001F22F', + u':u6708:': u'\U0001F237', + u':u6709:': u'\U0001F236', + u':u6e80:': u'\U0001F235', + u':u7121:': u'\U0001F21A', + u':u7533:': u'\U0001F238', + u':u7981:': u'\U0001F232', + u':u7a7a:': u'\U0001F233', + u':cl:': u'\U0001F191', + u':cool:': u'\U0001F192', + u':free:': u'\U0001F193', + u':id:': u'\U0001F194', + u':koko:': u'\U0001F201', + u':sa:': u'\U0001F202', + u':new:': u'\U0001F195', + u':ng:': u'\U0001F196', + u':ok:': u'\U0001F197', + u':sos:': u'\U0001F198', + u':up:': u'\U0001F199', + u':vs:': u'\U0001F19A', + u':stadium:': u'\U0001F3DF', + u':star_and_crescent:': u'\U0000262A', + u':star_of_david:': u'\U00002721', + u':station:': u'\U0001F689', + u':statue_of_liberty:': u'\U0001F5FD', + u':steam_locomotive:': u'\U0001F682', + u':ramen:': u'\U0001F35C', + u':stopwatch:': u'\U000023F1', + u':straight_ruler:': u'\U0001F4CF', + u':strawberry:': u'\U0001F353', + u':studio_microphone:': u'\U0001F399', + u':partly_sunny:': u'\U000026C5', + u':sun_with_face:': u'\U0001F31E', + u':sunflower:': u'\U0001F33B', + u':sunrise:': u'\U0001F305', + u':sunrise_over_mountains:': u'\U0001F304', + u':city_sunrise:': u'\U0001F307', + u':surfer:': u'\U0001F3C4', + u':sushi:': u'\U0001F363', + u':suspension_railway:': u'\U0001F69F', + u':swimmer:': u'\U0001F3CA', + u':synagogue:': u'\U0001F54D', + u':syringe:': u'\U0001F489', + u':shirt:': u'\U0001F455', + u':tshirt:': u'\U0001F455', + u':table_tennis_paddle_and_ball:': u'\U0001F3D3', + u':taco:': u'\U0001F32E', + u':tanabata_tree:': u'\U0001F38B', + u':tangerine:': u'\U0001F34A', + u':taurus:': u'\U00002649', + u':taxi:': u'\U0001F695', + u':tea:': u'\U0001F375', + u':calendar:': u'\U0001F4C6', + u':telephone_receiver:': u'\U0001F4DE', + u':telescope:': u'\U0001F52D', + u':tv:': u'\U0001F4FA', + u':tennis:': u'\U0001F3BE', + u':tent:': u'\U000026FA', + u':thermometer:': u'\U0001F321', + u':thinking_face:': u'\U0001F914', + u':thought_balloon:': u'\U0001F4AD', + u':three_button_mouse:': u'\U0001F5B1', + u':+1:': u'\U0001F44D', + u':thumbsup:': u'\U0001F44D', + u':__1:': u'\U0001F44E', + u':-1:': u'\U0001F44E', + u':thumbsdown:': u'\U0001F44E', + u':thunder_cloud_and_rain:': u'\U000026C8', + u':ticket:': u'\U0001F3AB', + u':tiger2:': u'\U0001F405', + u':tiger:': u'\U0001F42F', + u':timer_clock:': u'\U000023F2', + u':tired_face:': u'\U0001F62B', + u':toilet:': u'\U0001F6BD', + u':tokyo_tower:': u'\U0001F5FC', + u':tomato:': u'\U0001F345', + u':tongue:': u'\U0001F445', + u':tophat:': u'\U0001F3A9', + u':top:': u'\U0001F51D', + u':trackball:': u'\U0001F5B2', + u':tractor:': u'\U0001F69C', + u':tm:': u'\U00002122', + u':train2:': u'\U0001F686', + u':tram:': u'\U0001F68A', + u':train:': u'\U0001F68B', + u':triangular_flag_on_post:': u'\U0001F6A9', + u':triangular_ruler:': u'\U0001F4D0', + u':trident:': u'\U0001F531', + u':trolleybus:': u'\U0001F68E', + u':trophy:': u'\U0001F3C6', + u':tropical_drink:': u'\U0001F379', + u':tropical_fish:': u'\U0001F420', + u':trumpet:': u'\U0001F3BA', + u':tulip:': u'\U0001F337', + u':turkey:': u'\U0001F983', + u':turtle:': u'\U0001F422', + u':twisted_rightwards_arrows:': u'\U0001F500', + u':two_hearts:': u'\U0001F495', + u':two_men_holding_hands:': u'\U0001F46C', + u':two_women_holding_hands:': u'\U0001F46D', + u':umbrella:': u'\U00002602', + u':umbrella_on_ground:': u'\U000026F1', + u':unamused:': u'\U0001F612', + u':unicorn_face:': u'\U0001F984', + u':small_red_triangle:': u'\U0001F53A', + u':arrow_up_small:': u'\U0001F53C', + u':arrow_up_down:': u'\U00002195', + u':upside__down_face:': u'\U0001F643', + u':arrow_up:': u'\U00002B06', + u':vertical_traffic_light:': u'\U0001F6A6', + u':vibration_mode:': u'\U0001F4F3', + u':v:': u'\U0000270C', + u':video_camera:': u'\U0001F4F9', + u':video_game:': u'\U0001F3AE', + u':vhs:': u'\U0001F4FC', + u':violin:': u'\U0001F3BB', + u':virgo:': u'\U0000264D', + u':volcano:': u'\U0001F30B', + u':volleyball:': u'\U0001F3D0', + u':waning_crescent_moon:': u'\U0001F318', + u':waning_gibbous_moon:': u'\U0001F316', + u':warning:': u'\U000026A0', + u':wastebasket:': u'\U0001F5D1', + u':watch:': u'\U0000231A', + u':water_buffalo:': u'\U0001F403', + u':wc:': u'\U0001F6BE', + u':ocean:': u'\U0001F30A', + u':watermelon:': u'\U0001F349', + u':waving_black_flag:': u'\U0001F3F4', + u':wave:': u'\U0001F44B', + u':waving_white_flag:': u'\U0001F3F3', + u':wavy_dash:': u'\U00003030', + u':waxing_crescent_moon:': u'\U0001F312', + u':moon:': u'\U0001F314', + u':waxing_gibbous_moon:': u'\U0001F314', + u':scream_cat:': u'\U0001F640', + u':weary:': u'\U0001F629', + u':wedding:': u'\U0001F492', + u':weight_lifter:': u'\U0001F3CB', + u':whale2:': u'\U0001F40B', + u':wheel_of_dharma:': u'\U00002638', + u':wheelchair:': u'\U0000267F', + u':point_down:': u'\U0001F447', + u':grey_exclamation:': u'\U00002755', + u':white_flower:': u'\U0001F4AE', + u':white_frowning_face:': u'\U00002639', + u':white_check_mark:': u'\U00002705', + u':white_large_square:': u'\U00002B1C', + u':point_left:': u'\U0001F448', + u':white_medium_small_square:': u'\U000025FD', + u':white_medium_square:': u'\U000025FB', + u':star:': u'\U00002B50', + u':grey_question:': u'\U00002754', + u':point_right:': u'\U0001F449', + u':white_small_square:': u'\U000025AB', + u':relaxed:': u'\U0000263A', + u':white_square_button:': u'\U0001F533', + u':white_sun_behind_cloud:': u'\U0001F325', + u':white_sun_behind_cloud_with_rain:': u'\U0001F326', + u':white_sun_with_small_cloud:': u'\U0001F324', + u':point_up_2:': u'\U0001F446', + u':point_up:': u'\U0000261D', + u':wind_blowing_face:': u'\U0001F32C', + u':wind_chime:': u'\U0001F390', + u':wine_glass:': u'\U0001F377', + u':wink:': u'\U0001F609', + u':wolf:': u'\U0001F43A', + u':woman:': u'\U0001F469', + u':dancers:': u'\U0001F46F', + u':boot:': u'\U0001F462', + u':womans_clothes:': u'\U0001F45A', + u':womans_hat:': u'\U0001F452', + u':sandal:': u'\U0001F461', + u':womens:': u'\U0001F6BA', + u':world_map:': u'\U0001F5FA', + u':worried:': u'\U0001F61F', + u':gift:': u'\U0001F381', + u':wrench:': u'\U0001F527', + u':writing_hand:': u'\U0000270D', + u':yellow_heart:': u'\U0001F49B', + u':yin_yang:': u'\U0000262F', + u':zipper__mouth_face:': u'\U0001F910', + u':regional_indicator_a:': u'\U0001F1E6', + u':regional_indicator_b:': u'\U0001F1E7', + u':regional_indicator_c:': u'\U0001F1E8', + u':regional_indicator_d:': u'\U0001F1E9', + u':regional_indicator_e:': u'\U0001F1EA', + u':regional_indicator_f:': u'\U0001F1EB', + u':regional_indicator_g:': u'\U0001F1EC', + u':regional_indicator_h:': u'\U0001F1ED', + u':regional_indicator_i:': u'\U0001F1EE', + u':regional_indicator_j:': u'\U0001F1EF', + u':regional_indicator_k:': u'\U0001F1F0', + u':regional_indicator_l:': u'\U0001F1F1', + u':regional_indicator_m:': u'\U0001F1F2', + u':regional_indicator_n:': u'\U0001F1F3', + u':regional_indicator_o:': u'\U0001F1F4', + u':regional_indicator_p:': u'\U0001F1F5', + u':regional_indicator_q:': u'\U0001F1F6', + u':regional_indicator_r:': u'\U0001F1F7', + u':regional_indicator_s:': u'\U0001F1F8', + u':regional_indicator_t:': u'\U0001F1F9', + u':regional_indicator_u:': u'\U0001F1FA', + u':regional_indicator_v:': u'\U0001F1FB', + u':regional_indicator_w:': u'\U0001F1FC', + u':regional_indicator_x:': u'\U0001F1FD', + u':regional_indicator_y:': u'\U0001F1FE', + u':regional_indicator_z:': u'\U0001F1FF', +}) + +UNICODE_EMOJI = {v: k for k, v in EMOJI_UNICODE.items()} + +UNICODE_EMOJI_ALIAS = {v: k for k, v in EMOJI_ALIAS_UNICODE.items()} \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_extra_spaces_refiner.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_extra_spaces_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..53a200c78b7ec7d63ac7a7f683bb1f6d54555d6f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_extra_spaces_refiner.py @@ -0,0 +1,69 @@ +import re +from tqdm import tqdm +from dataflow.utils.storage import DataFlowStorage +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.registry import OPERATOR_REGISTRY + +@OPERATOR_REGISTRY.register() +class RemoveExtraSpacesRefiner(OperatorABC): + def __init__(self): + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__} ...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于移除文本中的多余空格,将连续的多个空格替换为单个空格,并去除文本前后的空白字符。\n" + "通过字符串分割和连接实现空格标准化,提高文本格式一致性。\n" + "输入参数:\n" + "- 无初始化参数\n" + "运行参数:\n" + "- input_key:输入文本字段名\n" + "输出参数:\n" + "- 处理后的DataFrame,包含标准化空格的文本\n" + "- 返回包含输入字段名的列表,用于后续算子引用" + ) + elif lang == "en": + return ( + "This operator removes extra spaces from text, replacing consecutive spaces with single spaces and trimming leading/trailing whitespace.\n" + "Achieves space standardization through string splitting and joining to improve text format consistency.\n" + "Input Parameters:\n" + "- No initialization parameters\n" + "Runtime Parameters:\n" + "- input_key: Input text field name\n" + "Output Parameters:\n" + "- Processed DataFrame containing text with standardized spacing\n" + "- List containing input field name for subsequent operator reference" + ) + else: + return "Removes extra spaces and normalizes spacing in text." + + def run(self, storage: DataFlowStorage, input_key: str): + self.input_key = input_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key}...") + numbers = 0 + refined_data = [] + + for item in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + modified = False + original_text = item + refined_text = " ".join(original_text.split()) # Remove extra spaces + + if original_text != refined_text: + item = refined_text + modified = True + self.logger.debug(f"Modified text for key '{self.input_key}': Original: {original_text[:30]}... -> Refined: {refined_text[:30]}...") + + refined_data.append(item) + if modified: + numbers += 1 + self.logger.debug(f"Item modified, total modified so far: {numbers}") + + dataframe[self.input_key] = refined_data + storage.write(dataframe) + self.logger.info(f"Refining Complete. Total modified items: {numbers}") + + return [self.input_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_image_ref_refiner.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_image_ref_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..1046f096778ccee07bfd0cb6cf240936c3d031f5 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_image_ref_refiner.py @@ -0,0 +1,82 @@ +import re +from tqdm import tqdm +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY + +@OPERATOR_REGISTRY.register() +class RemoveImageRefsRefiner(OperatorABC): + def __init__(self): + self.logger = get_logger() + self.image_pattern = re.compile( + r'!\[\]\(images\/[0-9a-fA-F]\.jpg\)|' + r'[a-fA-F0-9]+\.[a-zA-Z]{3,4}\)|' + r'!\[\]\(images\/[a-f0-9]|' + r'图\s+\d+-\d+:[\u4e00-\u9fa5a-zA-Z0-9]+|' + r'(?:[0-9a-zA-Z]+){7,}|' # 正则5 + r'(?:[一二三四五六七八九十零壹贰叁肆伍陆柒捌玖拾佰仟万亿]+){5,}|' # 正则6(汉字数字) + r"u200e|" + r"÷|\? :|" + r"[�□]|\{\/U\}|" + r"U\+26[0-F][0-D]|U\+273[3-4]|U\+1F[3-6][0-4][0-F]|U\+1F6[8-F][0-F]" + ) + self.logger.info(f"Initializing {self.__class__.__name__} ...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于去除文本中的图片引用格式,包括Markdown图片链接、图片编号、特殊符号组合等图像引用模式。\n" + "通过多模式正则表达式匹配,识别并移除多种图片引用格式。\n" + "输入参数:\n" + "- 无初始化参数\n" + "运行参数:\n" + "- input_key:输入文本字段名\n" + "输出参数:\n" + "- 处理后的DataFrame,包含去除图片引用的文本\n" + "- 返回包含输入字段名的列表,用于后续算子引用" + ) + elif lang == "en": + return ( + "This operator removes image reference formats from text, including Markdown image links, image numbers, special symbol combinations and other image reference patterns.\n" + "Identifies and removes multiple image reference formats through multi-pattern regular expression matching.\n" + "Input Parameters:\n" + "- No initialization parameters\n" + "Runtime Parameters:\n" + "- input_key: Input text field name\n" + "Output Parameters:\n" + "- Processed DataFrame containing text with image references removed\n" + "- List containing input field name for subsequent operator reference" + ) + else: + return "Removes image reference formats from text using regular expressions." + + def run(self, storage: DataFlowStorage, input_key: str): + self.input_key = input_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key}...") + numbers = 0 + refined_data = [] + for item in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + modified = False + original_text = item + # 移除所有图片引用格式[1,2](@ref) + cleaned_text = self.image_pattern.sub('', original_text) + + if original_text != cleaned_text: + item = cleaned_text + modified = True + # 调试日志:显示修改前后的对比 + self.logger.debug(f"Modified text for key '{self.input_key}':") + self.logger.debug(f"Original: {original_text[:100]}...") + self.logger.debug(f"Refined : {cleaned_text[:100]}...") + + refined_data.append(item) + if modified: + numbers += 1 + self.logger.debug(f"Item modified, total modified so far: {numbers}") + self.logger.info(f"Refining Complete. Total modified items: {numbers}") + dataframe[self.input_key] = refined_data + output_file = storage.write(dataframe) + return [self.input_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_number_refiner.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_number_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..9e608bffe446e7219e8d84b1a5f3f1f53ddbd2fa --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_number_refiner.py @@ -0,0 +1,64 @@ +from tqdm import tqdm +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY + +@OPERATOR_REGISTRY.register() +class RemoveNumberRefiner(OperatorABC): + def __init__(self): + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__} ...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于移除文本中的数字字符,包括0-9的阿拉伯数字。\n" + "通过字符过滤实现数字移除,保留纯文本内容。\n" + "输入参数:\n" + "- 无初始化参数\n" + "运行参数:\n" + "- input_key:输入文本字段名\n" + "输出参数:\n" + "- 处理后的DataFrame,包含去除数字的文本\n" + "- 返回包含输入字段名的列表,用于后续算子引用" + ) + elif lang == "en": + return ( + "This operator removes numeric characters from text, including 0-9 Arabic numerals.\n" + "Implements number removal through character filtering to retain pure text content.\n" + "Input Parameters:\n" + "- No initialization parameters\n" + "Runtime Parameters:\n" + "- input_key: Input text field name\n" + "Output Parameters:\n" + "- Processed DataFrame containing text with numbers removed\n" + "- List containing input field name for subsequent operator reference" + ) + else: + return "Removes numeric characters from text through character filtering." + + def run(self, storage: DataFlowStorage, input_key: str): + self.input_key = input_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key}...") + numbers = 0 + refined_data = [] + for item in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + modified = False + original_text = item + no_number_text = ''.join([char for char in original_text if not char.isdigit()]) + if original_text != no_number_text: + item = no_number_text + modified = True + self.logger.debug(f"Modified text for key '{self.input_key}': Original: {original_text[:30]}... -> Refined: {no_number_text[:30]}...") + + refined_data.append(item) + if modified: + numbers += 1 + self.logger.debug(f"Item modified, total modified so far: {numbers}") + self.logger.info(f"Refining Complete. Total modified items: {numbers}") + dataframe[self.input_key] = refined_data + output_file = storage.write(dataframe) + return [self.input_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_punctuation_refiner.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_punctuation_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..ac4efc801cd9bfccb846bf711bd4351f5be43b6b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_punctuation_refiner.py @@ -0,0 +1,67 @@ +import string +from tqdm import tqdm +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY + +@OPERATOR_REGISTRY.register() +class RemovePunctuationRefiner(OperatorABC): + def __init__(self): + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__} ...") + self.punct_to_remove = string.punctuation + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于移除文本中的标点符号,包括英文标点符号集合中的所有符号。\n" + "使用string.punctuation定义的标点集合进行过滤,实现文本去标点处理。\n" + "输入参数:\n" + "- 无初始化参数\n" + "运行参数:\n" + "- input_key:输入文本字段名\n" + "输出参数:\n" + "- 处理后的DataFrame,包含去除标点的文本\n" + "- 返回包含输入字段名的列表,用于后续算子引用" + ) + elif lang == "en": + return ( + "This operator removes punctuation from text, including all symbols in the English punctuation set.\n" + "Uses the punctuation set defined by string.punctuation for filtering to achieve text punctuation removal.\n" + "Input Parameters:\n" + "- No initialization parameters\n" + "Runtime Parameters:\n" + "- input_key: Input text field name\n" + "Output Parameters:\n" + "- Processed DataFrame containing text with punctuation removed\n" + "- List containing input field name for subsequent operator reference" + ) + else: + return "Removes punctuation from text using string.punctuation set." + + def run(self, storage: DataFlowStorage, input_key: str): + self.input_key = input_key + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key}...") + dataframe = storage.read("dataframe") + numbers = 0 + refined_data = [] + for item in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + modified = False + original_text = item + no_punct_text = original_text.translate(str.maketrans('', '', self.punct_to_remove)) + + if original_text != no_punct_text: + item = no_punct_text + modified = True + self.logger.debug(f"Modified text for key '{self.input_key}': Original: {original_text[:30]}... -> Refined: {no_punct_text[:30]}...") + + refined_data.append(item) + if modified: + numbers += 1 + self.logger.debug(f"Item modified, total modified so far: {numbers}") + self.logger.info(f"Refining Complete. Total modified items: {numbers}") + dataframe[self.input_key] = refined_data + output_file = storage.write(dataframe) + return [self.input_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_repetitions_punctuation_refiner.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_repetitions_punctuation_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..d10161b1988b9c6913f9be047f55e4637f6be9e4 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_repetitions_punctuation_refiner.py @@ -0,0 +1,69 @@ +import re +import string +from tqdm import tqdm +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY + +@OPERATOR_REGISTRY.register() +class RemoveRepetitionsPunctuationRefiner(OperatorABC): + def __init__(self): + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__} ...") + self.punct_to_remove = string.punctuation + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于移除文本中重复的标点符号,例如将\"!!!\"变为\"!\",\",,\"变为\",\"。\n" + "通过正则表达式匹配连续重复的标点符号,替换为单个符号。\n" + "输入参数:\n" + "- 无初始化参数\n" + "运行参数:\n" + "- input_key:输入文本字段名\n" + "输出参数:\n" + "- 处理后的DataFrame,包含标准化标点的文本\n" + "- 返回包含输入字段名的列表,用于后续算子引用" + ) + elif lang == "en": + return ( + "This operator removes repeated punctuation in text, e.g., changing \"!!!\" to \"!\", \",,\" to \",\".\n" + "Matches consecutive repeated punctuation using regular expressions and replaces with single symbols.\n" + "Input Parameters:\n" + "- No initialization parameters\n" + "Runtime Parameters:\n" + "- input_key: Input text field name\n" + "Output Parameters:\n" + "- Processed DataFrame containing text with normalized punctuation\n" + "- List containing input field name for subsequent operator reference" + ) + else: + return "Removes repeated punctuation in text using regular expressions." + + def run(self, storage: DataFlowStorage, input_key: str): + self.input_key = input_key + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key}...") + dataframe = storage.read("dataframe") + numbers = 0 + refined_data = [] + for item in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + modified = False + original_text = item + no_extra_punct_text = re.sub(r'([^\w\s_])\1+|(_)\2+', r'\1\2', original_text) + + if original_text != no_extra_punct_text: + item = no_extra_punct_text + modified = True + + self.logger.debug(f"Modified text for key '{self.input_key}': Original: {original_text[:30]}... -> Refined: {no_extra_punct_text[:30]}...") + + refined_data.append(item) + if modified: + numbers += 1 + self.logger.debug(f"Item modified, total modified so far: {numbers}") + self.logger.info(f"Refining Complete. Total modified items: {numbers}") + dataframe[self.input_key] = refined_data + output_file = storage.write(dataframe) + return [self.input_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_stopwords_refiner.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_stopwords_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..21798c45b1ece64996b6b348f6679d3fc05314f2 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/remove_stopwords_refiner.py @@ -0,0 +1,84 @@ +import nltk +import os +from nltk.corpus import stopwords +from tqdm import tqdm +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY + +@OPERATOR_REGISTRY.register() +class RemoveStopwordsRefiner(OperatorABC): + def __init__(self): + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__} ...") + + # 设置 NLTK 数据路径(如果环境变量中有的话) + if 'NLTK_DATA' in os.environ: + nltk.data.path.insert(0, os.environ['NLTK_DATA']) + + # 尝试下载,如果已存在则跳过 + try: + nltk.data.find('corpora/stopwords') + except LookupError: + nltk.download('stopwords') + + def remove_stopwords(self, text): + words = text.split() + stopwords_list = set(stopwords.words('english')) + refined_words = [word for word in words if word.lower() not in stopwords_list] + return " ".join(refined_words) + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于移除文本中的英语停用词(如\"the\",\"is\",\"in\"等无实际意义的高频词汇)。\n" + "使用NLTK库的stopwords语料库进行停用词过滤,提高文本特征密度。\n" + "输入参数:\n" + "- model_cache_dir:模型缓存目录,默认为'./dataflow_cache'\n" + "运行参数:\n" + "- input_key:输入文本字段名\n" + "输出参数:\n" + "- 处理后的DataFrame,包含去除停用词的文本\n" + "- 返回包含输入字段名的列表,用于后续算子引用" + ) + elif lang == "en": + return ( + "This operator removes English stopwords from text (e.g., high-frequency words with little meaning like \"the\", \"is\", \"in\").\n" + "Uses NLTK library's stopwords corpus for stopword filtering to improve text feature density.\n" + "Input Parameters:\n" + "- model_cache_dir: Model cache directory, default is './dataflow_cache'\n" + "Runtime Parameters:\n" + "- input_key: Input text field name\n" + "Output Parameters:\n" + "- Processed DataFrame containing text with stopwords removed\n" + "- List containing input field name for subsequent operator reference" + ) + else: + return "Removes English stopwords from text using NLTK's stopwords corpus." + + def run(self, storage: DataFlowStorage, input_key: str): + self.input_key = input_key + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key}...") + dataframe = storage.read("dataframe") + numbers = 0 + refined_data = [] + for item in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + modified = False + original_text = item + refined_text = self.remove_stopwords(original_text) + + if original_text != refined_text: + item = refined_text + modified = True + self.logger.debug(f"Modified text for key '{self.input_key}': Original: {original_text[:30]}... -> Refined: {refined_text[:30]}...") + + refined_data.append(item) + if modified: + numbers += 1 + self.logger.debug(f"Item modified, total modified so far: {numbers}") + self.logger.info(f"Refining Complete. Total modified items: {numbers}") + dataframe[self.input_key] = refined_data + output_file = storage.write(dataframe) + return [self.input_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/spelling_correction_refiner.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/spelling_correction_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..213a59342238379eb82c9f78b86d9e98c79c78af --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/spelling_correction_refiner.py @@ -0,0 +1,108 @@ +import re +import os +import requests +from tqdm import tqdm +from symspellpy.symspellpy import SymSpell, Verbosity +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY + +@OPERATOR_REGISTRY.register() +class SpellingCorrectionRefiner(OperatorABC): + def __init__(self, max_edit_distance: int = 2, prefix_length: int = 7, dictionary_path: str = "frequency_dictionary_en_82_765.txt"): + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__} ...") + self.max_edit_distance = max_edit_distance # Default to 2 if not specified + self.prefix_length = prefix_length # Default to 7 if not specified + self.dictionary_path = dictionary_path + # If dictionary is not found locally, download it + if not os.path.exists(self.dictionary_path): + self.download_dictionary() + self.sym_spell = SymSpell(max_dictionary_edit_distance=self.max_edit_distance, prefix_length=self.prefix_length) + term_index = 0 + count_index = 1 + if not self.sym_spell.load_dictionary(self.dictionary_path, term_index, count_index): + self.logger.error(f"Error loading dictionary at {self.dictionary_path}") + self.logger.info(f"Successfully loaded dictionary at {self.dictionary_path}") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于通过SymSpell算法对文本中的拼写错误进行纠正,支持自定义编辑距离和词典路径。\n" + "若本地词典不存在则自动下载,使用近似字符串匹配实现拼写纠错功能。\n" + "输入参数:\n" + "- max_edit_distance:最大编辑距离,默认为2\n" + "- prefix_length:前缀长度,默认为7\n" + "- dictionary_path:词典路径,默认为'frequency_dictionary_en_82_765.txt'\n" + "运行参数:\n" + "- input_key:输入文本字段名\n" + "输出参数:\n" + "- 处理后的DataFrame,包含纠正拼写错误的文本\n" + "- 返回包含输入字段名的列表,用于后续算子引用" + ) + elif lang == "en": + return ( + "This operator corrects spelling errors in text using the SymSpell algorithm, supporting custom edit distance and dictionary path.\n" + "Automatically downloads dictionary if not locally available, using approximate string matching for spelling correction.\n" + "Input Parameters:\n" + "- max_edit_distance: Maximum edit distance, default is 2\n" + "- prefix_length: Prefix length, default is 7\n" + "- dictionary_path: Dictionary path, default is 'frequency_dictionary_en_82_765.txt'\n" + "Runtime Parameters:\n" + "- input_key: Input text field name\n" + "Output Parameters:\n" + "- Processed DataFrame containing text with corrected spelling\n" + "- List containing input field name for subsequent operator reference" + ) + else: + return "Corrects spelling errors in text using the SymSpell algorithm with configurable parameters." + + def run(self, storage: DataFlowStorage, input_key: str): + self.input_key = input_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key}...") + numbers = 0 + refined_data = [] + for item in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + modified = False + original_text = item + refined_text = self.spelling_checks(original_text) + if original_text != refined_text: + item = refined_text + modified = True + self.logger.debug(f"Modified text for key '{self.input_key}': Original: {original_text[:30]}... -> Refined: {refined_text[:30]}...") + + refined_data.append(item) + if modified: + numbers += 1 + self.logger.debug(f"Item modified, total modified so far: {numbers}") + self.logger.info(f"Refining Complete. Total modified items: {numbers}") + dataframe[self.input_key] = refined_data + output_file = storage.write(dataframe) + return [self.input_key] + + def spelling_checks(self, text): + correct_result = [] + for word in text.split(): + suggestions = self.sym_spell.lookup(word, Verbosity.CLOSEST, self.max_edit_distance) + corrected_word = suggestions[0].term if suggestions else word + correct_result.append(corrected_word) + + return " ".join(correct_result) + + def download_dictionary(self): + url = 'https://raw.githubusercontent.com/mammothb/symspellpy/master/symspellpy/frequency_dictionary_en_82_765.txt' + + try: + print("Downloading dictionary...") + response = requests.get(url) + response.raise_for_status() + + with open(self.dictionary_path, 'wb') as file: + file.write(response.content) + print(f"Dictionary downloaded and saved to {self.dictionary_path}") + except requests.exceptions.RequestException as e: + print(f"Error downloading dictionary: {e}") + \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/stemming_lemmatization_refiner.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/stemming_lemmatization_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..fae7ba3e92b6e6fccd7683206f2e1bd6dffe6b8d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/stemming_lemmatization_refiner.py @@ -0,0 +1,79 @@ +import nltk +from nltk.stem import PorterStemmer, WordNetLemmatizer +from tqdm import tqdm +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY + +@OPERATOR_REGISTRY.register() +class StemmingLemmatizationRefiner(OperatorABC): + def __init__(self, method: str = "stemming"): + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__} ...") + self.method = method.lower() + if self.method not in ["stemming", "lemmatization"]: + raise ValueError("Invalid method. Choose 'stemming' or 'lemmatization'.") + + nltk.download('wordnet') + nltk.download('omw-1.4') + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于对文本进行词干提取或词形还原处理,将词语转换为其基本形式。\n" + "支持两种处理方式:Porter词干提取(stemming)和WordNet词形还原(lemmatization),可通过参数选择。\n" + "输入参数:\n" + "- method:处理方法,可选'stemming'或'lemmatization',默认为'stemming'\n" + "运行参数:\n" + "- input_key:输入文本字段名\n" + "输出参数:\n" + "- 处理后的DataFrame,包含词干/词形还原后的文本\n" + "- 返回包含输入字段名的列表,用于后续算子引用" + ) + elif lang == "en": + return ( + "This operator applies stemming or lemmatization to text, converting words to their base forms.\n" + "Supports two processing methods: Porter stemming and WordNet lemmatization, selectable via parameter.\n" + "Input Parameters:\n" + "- method: Processing method, optional 'stemming' or 'lemmatization', default is 'stemming'\n" + "Runtime Parameters:\n" + "- input_key: Input text field name\n" + "Output Parameters:\n" + "- Processed DataFrame containing text with stemming/lemmatization applied\n" + "- List containing input field name for subsequent operator reference" + ) + else: + return "Applies stemming or lemmatization to text using NLTK's PorterStemmer or WordNetLemmatizer." + + def run(self, storage: DataFlowStorage, input_key: str): + self.input_key = input_key + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key}...") + dataframe = storage.read("dataframe") + numbers = 0 + refined_data = [] + stemmer = PorterStemmer() + lemmatizer = WordNetLemmatizer() + for item in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + modified = False + original_text = item + + if self.method == "stemming": + refined_text = " ".join([stemmer.stem(word) for word in original_text.split()]) + elif self.method == "lemmatization": + refined_text = " ".join([lemmatizer.lemmatize(word) for word in original_text.split()]) + + if original_text != refined_text: + item = refined_text + modified = True + self.logger.debug(f"Modified text for key '{self.input_key}': Original: {original_text[:30]}... -> Refined: {refined_text[:30]}...") + + refined_data.append(item) + if modified: + numbers += 1 + self.logger.debug(f"Item modified, total modified so far: {numbers}") + self.logger.info(f"Refining Complete. Total modified items: {numbers}") + dataframe[self.input_key] = refined_data + output_file = storage.write(dataframe) + return [self.input_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/text_normalization_refiner.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/text_normalization_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..05a6eac1528b392a0d60e6f62b5dc1b4e3c23578 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/general_text/refine/text_normalization_refiner.py @@ -0,0 +1,84 @@ +import re +from datetime import datetime +from tqdm import tqdm +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY + +@OPERATOR_REGISTRY.register() +class TextNormalizationRefiner(OperatorABC): + def __init__(self): + self.logger = get_logger() + self.logger.info(f"Initializing {self.__class__.__name__} ...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于规范化文本中的日期格式和货币格式,统一为标准表示形式。\n" + "日期格式统一转换为'YYYY-MM-DD'形式,货币格式转换为'金额 USD'形式,提高数据一致性。\n" + "输入参数:\n" + "- 无初始化参数\n" + "运行参数:\n" + "- input_key:输入文本字段名\n" + "输出参数:\n" + "- 处理后的DataFrame,包含格式规范化的文本\n" + "- 返回包含输入字段名的列表,用于后续算子引用" + ) + elif lang == "en": + return ( + "This operator normalizes date formats and currency formats in text to standard representations.\n" + "Unifies date formats to 'YYYY-MM-DD' and currency formats to 'amount USD' to improve data consistency.\n" + "Input Parameters:\n" + "- No initialization parameters\n" + "Runtime Parameters:\n" + "- input_key: Input text field name\n" + "Output Parameters:\n" + "- Processed DataFrame containing text with normalized formats\n" + "- List containing input field name for subsequent operator reference" + ) + else: + return "Normalizes date and currency formats in text to standard representations." + + def run(self, storage: DataFlowStorage, input_key: str): + self.input_key = input_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key}...") + numbers = 0 + refined_data = [] + for item in tqdm(dataframe[self.input_key], desc=f"Implementing {self.__class__.__name__}"): + modified = False + original_text = item + refined_text = original_text + + refined_text = re.sub(r'(\d{1,2})[/.](\d{1,2})[/.](\d{2,4})', r'\3-\2-\1', refined_text) + date_patterns = [ + (r'\b(\w+)\s+(\d{1,2}),\s+(\d{4})\b', '%B %d, %Y'), + (r'\b(\d{1,2})\s+(\w+)\s+(\d{4})\b', '%d %B %Y') + ] + for pattern, date_format in date_patterns: + match = re.search(pattern, refined_text) + if match: + date_str = match.group(0) + try: + parsed_date = datetime.strptime(date_str, date_format) + refined_text = refined_text.replace(date_str, parsed_date.strftime('%Y-%m-%d')) + except ValueError: + pass + + refined_text = re.sub(r'\$\s?(\d+)', r'\1 USD', refined_text) + + if original_text != refined_text: + item = refined_text + modified = True + self.logger.debug(f"Modified text for key '{self.input_key}': Original: {original_text[:30]}... -> Refined: {refined_text[:30]}...") + + refined_data.append(item) + if modified: + numbers += 1 + self.logger.debug(f"Item modified, total modified so far: {numbers}") + self.logger.info(f"Refining Complete. Total modified items: {numbers}") + dataframe[self.input_key] = refined_data + output_file = storage.write(dataframe) + return [self.input_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..72a13c8bdd6dcd7af09229faa4aa2e407612e10e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/__init__.py @@ -0,0 +1,28 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + # filter + from .generate.kbc_chunk_generator import KBCChunkGenerator + from .generate.kbc_chunk_generator_batch import KBCChunkGeneratorBatch + # from .generate.file_or_url_to_markdown_converter import FileOrURLToMarkdownConverter + from .generate.mineru_operators import FileOrURLToMarkdownConverterLocal + from .generate.mineru_operators import FileOrURLToMarkdownConverterAPI + from .generate.mineru_operators import FileOrURLToMarkdownConverterFlash + from .generate.kbc_text_cleaner import KBCTextCleaner + from .generate.kbc_text_cleaner_batch import KBCTextCleanerBatch + from .generate.mathbook_question_extract import MathBookQuestionExtract + # from .generate.kbc_multihop_qa_generator import KBCMultiHopQAGenerator + from .generate.kbc_multihop_qa_generator_batch import KBCMultiHopQAGeneratorBatch + from .generate.qa_extract import QAExtractor + +else: + import sys + from dataflow.utils.registry import LazyLoader, generate_import_structure_from_type_checking + + + + cur_path = "dataflow/operators/knowledge_cleaning/" + + + _import_structure = generate_import_structure_from_type_checking(__file__, cur_path) + sys.modules[__name__] = LazyLoader(__name__, "dataflow/operators/knowledge_cleaning/", _import_structure) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59ae6f159feebeef63e9aa73705e53d6c31f215a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/__pycache__/kbc_chunk_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/__pycache__/kbc_chunk_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7fcc3a1d13ba19a6501013369b2eab75142f6ebc Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/__pycache__/kbc_chunk_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/__pycache__/kbc_chunk_generator_batch.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/__pycache__/kbc_chunk_generator_batch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1538b728edbe801c19c31f3eaf6bed4235190a92 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/__pycache__/kbc_chunk_generator_batch.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/__pycache__/kbc_multihop_qa_generator_batch.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/__pycache__/kbc_multihop_qa_generator_batch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98ac26780c9555be16941909c21f6da4a2df5d1c Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/__pycache__/kbc_multihop_qa_generator_batch.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/__pycache__/kbc_text_cleaner.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/__pycache__/kbc_text_cleaner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a52537902fc57bc32928d3f315897cf1453cc8b0 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/__pycache__/kbc_text_cleaner.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/__pycache__/kbc_text_cleaner_batch.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/__pycache__/kbc_text_cleaner_batch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13e28a0be6b837b3ade489eae790286f90959bfe Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/__pycache__/kbc_text_cleaner_batch.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/__pycache__/mathbook_question_extract.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/__pycache__/mathbook_question_extract.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73a92395c2b4a9ccead9455c604e8cdb82c1eda7 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/__pycache__/mathbook_question_extract.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/__pycache__/mineru_operators.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/__pycache__/mineru_operators.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..319ddc51c5ee672d03c19476283a30b8a61867b5 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/__pycache__/mineru_operators.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/__pycache__/qa_extract.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/__pycache__/qa_extract.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f67179cbc116da8deb064003dd9d9a53fe46870d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/__pycache__/qa_extract.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/kbc_chunk_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/kbc_chunk_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..ceb5c5c18d552ad4dbc66c140e393ad48b18c2b2 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/kbc_chunk_generator.py @@ -0,0 +1,156 @@ +import os +import json +from typing import Dict, List, Optional +from chonkie import ( + TokenChunker, + SentenceChunker, + SemanticChunker, + RecursiveChunker +) +from tokenizers import Tokenizer +from transformers import AutoTokenizer +import pandas as pd +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC + +@OPERATOR_REGISTRY.register() +class KBCChunkGenerator(OperatorABC): + def __init__(self, + chunk_size: int = 512, + chunk_overlap: int = 50, + split_method: str = "token", + min_tokens_per_chunk: int = 100, + tokenizer_name: str = "bert-base-uncased", + ): + # 必需参数检查 + self.chunk_size = chunk_size + self.chunk_overlap = chunk_overlap + self.split_method = split_method + self.min_tokens_per_chunk = min_tokens_per_chunk + tokenizer_name = tokenizer_name + # 初始化tokenizer和chunker + self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name) + self.chunker = self._initialize_chunker() + self.logger = get_logger() + + @staticmethod + def get_desc(lang: str = "zh"): + if(lang=="zh"): + return ( + "CorpusTextSplitter是轻量级文本分割工具,", + "支持词/句/语义/递归分块,", + "可配置块大小、重叠和最小块长度", + ) + elif(lang=="en"): + return ( + "CorpusTextSplitter is a lightweight text segmentation tool", + "that supports multiple chunking methods", + "(token/sentence/semantic/recursive) with configurable size and overlap,", + "optimized for RAG applications." + ) + + def _initialize_chunker(self): + """Initialize the appropriate chunker based on method""" + if self.split_method == "token": + return TokenChunker( + tokenizer=self.tokenizer, + chunk_size=self.chunk_size, + chunk_overlap=self.chunk_overlap + ) + elif self.split_method == "sentence": + return SentenceChunker( + chunk_size=self.chunk_size, + chunk_overlap=self.chunk_overlap + ) + elif self.split_method == "semantic": + return SemanticChunker( + chunk_size=self.chunk_size, + ) + elif self.split_method == "recursive": + return RecursiveChunker( + chunk_size=self.chunk_size, + chunk_overlap=self.chunk_overlap + ) + else: + raise ValueError(f"Unsupported split method: {self.split_method}") + + def _load_text(self, file_path) -> str: + """Load text from input file""" + if not os.path.exists(file_path): + raise FileNotFoundError(f"Input file not found: {file_path}") + + if file_path.endswith('.txt') or file_path.endswith('.md') or file_path.endswith('.xml'): + with open(file_path, 'r', encoding='utf-8') as f: + return f.read() + + elif file_path.endswith(('.json', '.jsonl')): + with open(file_path, 'r', encoding='utf-8') as f: + data = json.load(f) if file_path.endswith('.json') else [json.loads(line) for line in f] + text_fields = ['text', 'content', 'body'] + for field in text_fields: + if isinstance(data, list) and len(data) > 0 and field in data[0]: + return "\n".join([item[field] for item in data]) + elif isinstance(data, dict) and field in data: + return data[field] + + raise ValueError("No text field found in JSON input") + else: + raise ValueError("Unsupported file format") + + def _validate_dataframe(self, dataframe: pd.DataFrame): + forbidden_keys = [self.output_key] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + if conflict: + raise ValueError(f"The following column(s) already exist and would be overwritten: {conflict}") + + def run(self, storage: DataFlowStorage, input_key:str='text_path', output_key:str="raw_chunk"): + """Perform text splitting and save results""" + # try: + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self._validate_dataframe(dataframe) + + text_paths = dataframe[self.input_key].tolist() + for input_path in text_paths: + if not input_path or not os.path.exists(input_path): + self.logger.error(f"无效的输入文件路径: {input_path}") + + new_records = [] + for row_dict, text_path in zip(dataframe.to_dict(orient='records'), text_paths): + text = self._load_text(text_path) + if(text): + # 计算总token数和最大限制 + tokens = self.tokenizer.encode(text) + total_tokens = len(tokens) + max_tokens = self.tokenizer.model_max_length # 假设这是tokenizer的最大token限制 + print("max_tokens: ", self.tokenizer.model_max_length) + + if total_tokens <= max_tokens: + chunks = self.chunker(text) + else: + # 计算需要分割的份数x(向上取整) + x = (total_tokens + max_tokens - 1) // max_tokens + + # 按词数等分文本(近似分割) + words = text.split() # 按空格分词 + words_per_chunk = (len(words) + x - 1) // x # 每份的词数 + + chunks = [] + for i in range(0, len(words), words_per_chunk): + chunk_text = ' '.join(words[i:i+words_per_chunk]) + chunks.extend(self.chunker(chunk_text)) + + # 每个chunk生成一条记录 + for chunk in chunks: + new_row = row_dict.copy() # 保留原行里所有字段(不会改动原 dataframe 的其他 key) + new_row[self.output_key] = chunk.text # 新增/覆盖 output_key 字段 + new_records.append(new_row) + + new_df = pd.DataFrame(new_records) + output_file = storage.write(new_df) + self.logger.info(f"Successfully split text for {len(text_paths)} files. Saved to {output_file}") + + return [output_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/kbc_chunk_generator_batch.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/kbc_chunk_generator_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..78acab715cff9b91508a7d5ff6a9334294543130 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/kbc_chunk_generator_batch.py @@ -0,0 +1,176 @@ +import os +import json +from typing import Dict, List, Optional +from chonkie import ( + TokenChunker, + SentenceChunker, + SemanticChunker, + RecursiveChunker +) +from tokenizers import Tokenizer +from transformers import AutoTokenizer +import pandas as pd +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC + + +@OPERATOR_REGISTRY.register() +class KBCChunkGeneratorBatch(OperatorABC): + def __init__(self, + chunk_size: int = 512, + chunk_overlap: int = 50, + split_method: str = "token", + min_tokens_per_chunk: int = 100, + tokenizer_name: str = "bert-base-uncased", + ): + # 必需参数检查 + self.chunk_size = chunk_size + self.chunk_overlap = chunk_overlap + self.split_method = split_method + self.min_tokens_per_chunk = min_tokens_per_chunk + tokenizer_name = tokenizer_name + # 初始化tokenizer和chunker + self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name) + self.chunker = self._initialize_chunker() + self.logger = get_logger() + + @staticmethod + def get_desc(lang: str = "zh"): + if (lang == "zh"): + return ( + "CorpusTextSplitter是轻量级文本分割工具,", + "支持词/句/语义/递归分块,", + "可配置块大小、重叠和最小块长度", + ) + elif (lang == "en"): + return ( + "CorpusTextSplitter is a lightweight text segmentation tool", + "that supports multiple chunking methods", + "(token/sentence/semantic/recursive) with configurable size and overlap,", + "optimized for RAG applications." + ) + + def _initialize_chunker(self): + """Initialize the appropriate chunker based on method""" + if self.split_method == "token": + return TokenChunker( + tokenizer=self.tokenizer, + chunk_size=self.chunk_size, + chunk_overlap=self.chunk_overlap + ) + elif self.split_method == "sentence": + return SentenceChunker( + chunk_size=self.chunk_size, + chunk_overlap=self.chunk_overlap + ) + elif self.split_method == "semantic": + return SemanticChunker( + chunk_size=self.chunk_size, + ) + elif self.split_method == "recursive": + return RecursiveChunker( + chunk_size=self.chunk_size, + chunk_overlap=self.chunk_overlap + ) + else: + raise ValueError(f"Unsupported split method: {self.split_method}") + + def _load_text(self, text_paths: List[str]) -> List[str]: + """Load text from file list""" + texts = [] + for text_path in text_paths: + if not os.path.exists(text_path): + self.logger.error(f"Input file not found: {text_path}") + texts.append("") + + elif text_path.endswith('.txt') or text_path.endswith('.md') or text_path.endswith('.xml'): + with open(text_path, 'r', encoding='utf-8') as f: + texts.append(f.read()) + + elif text_path.endswith(('.json', '.jsonl')): + with open(text_path, 'r', encoding='utf-8') as f: + data = json.load(f) if text_path.endswith( + '.json') else [json.loads(line) for line in f] + text_fields = ['text', 'content', 'body'] + for field in text_fields: + if isinstance(data, list) and len(data) > 0 and field in data[0]: + texts.append("\n".join([item[field] for item in data])) + elif isinstance(data, dict) and field in data: + texts.append(data[field]) + if (field not in text_fields): + raise ValueError("No text field found in JSON input") + else: + raise ValueError(f"Unsupported file format for {text_path}") + + return texts + + def _validate_dataframe(self, dataframe: pd.DataFrame): + forbidden_keys = [self.output_key] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + if conflict: + raise ValueError( + f"The following column(s) already exist and would be overwritten: {conflict}") + + def run(self, storage: DataFlowStorage, input_key: str = "text_path", output_key: str = "chunk_path"): + """Perform text splitting and save results""" + # try: + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self._validate_dataframe(dataframe) + + text_paths = dataframe[self.input_key].tolist() + texts = self._load_text(text_paths) + output_paths = [] + + chunks = [] + for i, text in enumerate(texts): + if(text): + # 计算总token数和最大限制 + tokens = self.tokenizer.encode(text) + total_tokens = len(tokens) + max_tokens = self.tokenizer.model_max_length # 假设这是tokenizer的最大token限制 + print("max_tokens: ", self.tokenizer.model_max_length) + + if total_tokens <= max_tokens: + chunks = self.chunker(text) + else: + # 计算需要分割的份数x(向上取整) + x = (total_tokens + max_tokens - 1) // max_tokens + + # 按词数等分文本(近似分割) + words = text.split() # 按空格分词 + words_per_chunk = (len(words) + x - 1) // x # 每份的词数 + + chunks = [] + for j in range(0, len(words), words_per_chunk): + chunk_text = ' '.join(words[j:j+words_per_chunk]) + chunks.extend(self.chunker(chunk_text)) + json_chunks = [{ + "raw_chunk": chunk.text, + } for chunk in chunks] + + output_dir = "/".join([os.path.dirname(text_paths[i]), "extract"]) + os.makedirs(output_dir, exist_ok=True) + file_name = os.path.splitext(os.path.basename(text_paths[i]))[0]+'_chunk.json' + output_path = os.path.join(output_dir, file_name) + output_paths.append(output_path) + + with open(output_path, "w", encoding="utf-8") as f: + json.dump(json_chunks, f, ensure_ascii=False, indent=4) + self.logger.info( + f"Successfully split {text_paths[i]} into {len(chunks)} chunks. Saved to {output_path}") + else: + output_paths.append("") + + print(">>>>>>>>>>>>>>>>>>>>>>>>>>>") + print(output_paths) + print("<<<<<<<<<<<<<<<<<<<<<<<<<<<") + dataframe[self.output_key] = output_paths + output_file = storage.write(dataframe) + self.logger.info( + f"Successfully split text into {len(chunks)} chunks. Saved to {output_file}") + + return [output_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/kbc_multihop_qa_generator_batch.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/kbc_multihop_qa_generator_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..a693c1b5896ff6138951530faf3e3ffca48db3fd --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/kbc_multihop_qa_generator_batch.py @@ -0,0 +1,637 @@ +from dataflow.prompts.text2qa import Text2MultiHopQAGeneratorPrompt +import pandas as pd +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger + +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +import random +from typing import Any, Dict, List, Optional, Sequence +import json +from tqdm import tqdm +import re + +from dataflow.core.prompt import prompt_restrict, DIYPromptABC +from typing import Union + +@prompt_restrict( + Text2MultiHopQAGeneratorPrompt +) +@OPERATOR_REGISTRY.register() +class KBCMultiHopQAGeneratorBatch(OperatorABC): + r"""A processor for generating multi-hop question-answer pairs from user + data. + + This class handles the processing of text data to generate multi-hop + question-answer pairs using either an AI model or rule-based approaches. + It manages the entire pipeline from text preprocessing to dataset curation. + """ + + def __init__(self, + llm_serving: LLMServingABC, + seed: int = 0, + lang="en", + prompt_template: Union[Text2MultiHopQAGeneratorPrompt, DIYPromptABC] = None + ): + r"""Initialize the UserDataProcessor. + + Args: + config (Optional[ProcessorConfig], optional): Configuration for + data processing. (default: :obj:`None`) + """ + self.rng = random.Random(seed) + self.llm_serving = llm_serving + self.lang = lang + self.logger = get_logger() + if prompt_template: + self.prompt_template = prompt_template + else: + self.prompt_template = Text2MultiHopQAGeneratorPrompt() + + @staticmethod + def get_desc(lang: str = "zh") -> tuple: + """Returns a description of the processor's functionality. + + Args: + lang (str, optional): Language for description ('zh' or 'en'). + + Returns: + tuple: Description strings in specified language, including format example + """ + if lang == "zh": + return ( + "MultiHopQAGenerator 是多跳问答对生成处理器,支持从文本中自动生成需要多步推理的问题与答案。", + "处理流程包括:文本预处理、信息抽取、问题生成与回答生成,支持自定义语言模型后端和参数。", + "输出格式如下:", + "输入:\n" + "text: <原始上下文文本>", + "输出:\n" + "{\n" + " \"text\": <处理后的文本字符串>,\n" + " \"qa_pairs\": [\n" + " {\n" + " \"question\": <字符串:生成的问题>,\n" + " \"reasoning_steps\": [\n" + " {\"step\": <推理过程的步骤 1>},\n" + " {\"step\": <步骤 2>} ...\n" + " ],\n" + " \"answer\": <字符串:最终答案>,\n" + " \"supporting_facts\": [<支持该答案的事实 1>, <事实 2>, ...],\n" + " \"type\": <可选:问题类型,如“生物学”、“历史”等>\n" + " },\n" + " ...\n" + " ],\n" + " \"metadata\": {\n" + " \"source\": <数据来源>,\n" + " \"timestamp\": <时间戳字符串>,\n" + " \"complexity\": <整数:问题复杂度标记>\n" + " }\n" + "}" + ) + else: + return ( + "MultiHopQAGenerator is a processor for generating multi-hop question-answer pairs from raw text.", + "It includes preprocessing, information extraction, and reasoning-based QA generation, with configurable LLM backends.", + "Expected output format:", + "Input:\n" + "text: ", + "Output:\n" + "{\n" + " \"text\": ,\n" + " \"qa_pairs\": [\n" + " {\n" + " \"question\": ,\n" + " \"reasoning_steps\": [\n" + " {\"step\": },\n" + " {\"step\": } ...\n" + " ],\n" + " \"answer\": ,\n" + " \"supporting_facts\": [, , ...],\n" + " \"type\": \n" + " },\n" + " ...\n" + " ],\n" + " \"metadata\": {\n" + " \"source\": ,\n" + " \"timestamp\": ,\n" + " \"complexity\": \n" + " }\n" + "}" + ) + + def process_text( + self, text: str, source: str = "user_input" + ) -> List[Dict[str, Any]]: + r"""Process a single text to generate multi-hop QA pairs. + + Args: + text (str): The input text to process. + source (str, optional): Source identifier for the text. + (default: :obj:`"user_input"`) + + Returns: + List[Dict[str, Any]]: List of processed examples with QA pairs and + metadata. + """ + # Convert text to standard format + raw_data = [ + { + 'text': text, + 'source': source, + } + ] + + # Construct examples + constructor = ExampleConstructor( + lang=self.lang, + llm_serving=self.llm_serving, + prompt_template = self.prompt_template + ) + examples = constructor.construct_examples(raw_data) + + # Manage data + # curator = DataCurator(self.config, self.rng) + # final_dataset = curator.curate_dataset(examples) + + return examples + + def process_batch( + self, texts: List[str], sources: Optional[List[str]] = None + ) -> List[Dict[str, Any]]: + r"""Process multiple texts in batch to generate multi-hop QA pairs. + + Args: + texts (List[str]): List of input texts to process. + sources (Optional[List[str]], optional): List of source + identifiers. (default: :obj:`None`) + + Returns: + List[Dict[str, Any]]: List of processed examples with QA pairs and + metadata. + + Raises: + ValueError: If length of sources doesn't match length of texts. + """ + if sources is None: + sources = ["default_source"] * len(texts) + elif len(sources) != len(texts): + raise ValueError("Length of sources must match length of texts") + + raw_data = [ + { + 'text': text, + 'source': source, + } + for text, source in zip(texts, sources) + ] + + # Construct examples + constructor = ExampleConstructor( + lang=self.lang, llm_serving=self.llm_serving, ) + examples = constructor.construct_examples(raw_data) + + # # Manage data + # curator = DataCurator(self.config, self.rng) + # final_dataset = curator.curate_dataset(examples) + + return examples + + def _validate_dataframe(self, dataframe: pd.DataFrame): + required_keys = [self.input_key] + forbidden_keys = [self.output_key] + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + raise ValueError(f"Missing required column(s): {missing}") + if conflict: + raise ValueError( + f"The following column(s) already exist and would be overwritten: {conflict}") + + def run( + self, + storage: DataFlowStorage = None, + input_key: str = 'chunk_path', + output_key: str = 'enhanced_chunk_path', + ): + self.input_key, self.output_key = input_key, output_key + dataframe = storage.read("dataframe") + self._validate_dataframe(dataframe) + chunk_paths = dataframe[self.input_key].tolist() + + for chunk_path in chunk_paths: + if(chunk_path): + texts = [] + + if str(chunk_path).endswith(".json"): + with open(chunk_path, "r", encoding="utf-8") as f: + data = json.load(f) + texts = [item["cleaned_chunk"] for item in data] + + elif str(chunk_path).endswith(".jsonl"): + with open(chunk_path, "r", encoding="utf-8") as f: + data = [json.loads(line) for line in f] + texts = [item["cleaned_chunk"] for item in data] + + else: + print(f"Unsupported file format: {chunk_path}") + continue + + # 生成 QA 对 + qa_pairs_batch = self.process_batch(texts) + + # 写入到原数据中 + for item, qa_pairs in zip(data, qa_pairs_batch): + item["qa_pairs"] = qa_pairs + + # 回写到原始文件中(覆盖写入) + with open(chunk_path, "w", encoding="utf-8") as f: + if str(chunk_path).endswith(".json"): + json.dump(data, f, ensure_ascii=False, indent=4) + else: # jsonl + for item in data: + f.write(json.dumps(item, ensure_ascii=False) + "\n") + + self.logger.info(f"constructed {len(qa_pairs)} multihop QA for {chunk_path}") + + dataframe[self.output_key] = chunk_paths + output_file = storage.write(dataframe) + + self.logger.info(f"Results saved to {output_file}") + + return [output_key] + + +class ExampleConstructor: + r"""Constructs training examples from raw text data. + + This class handles the construction of training examples by preprocessing + text, extracting information pairs, and generating question-answer pairs. + """ + + def __init__( + self, + lang: str = "en", + llm_serving: LLMServingABC = None, + min_text_length: int = 100, + max_text_length: int = 200000, + prompt_template = None + ): + r"""Initialize the ExampleConstructor. + + Args: + config (ProcessorConfig): Configuration for example construction. + multi_hop_agent (Optional[MultiHopGeneratorAgent], optional): + Agent for generating multi-hop QA pairs. (default: :obj:`None`) + """ + self.lang = lang + self.llm_sering = llm_serving + self.logger = get_logger() + self.max_length = max_text_length + self.min_length = min_text_length + # self.prompt = Text2MultiHopQAGeneratorPrompt(lang=self.lang) + if prompt_template: + self.prompt_template = prompt_template + else: + self.prompt_template = Text2MultiHopQAGeneratorPrompt() + + def construct_examples( + self, raw_data: List[Dict[str, Any]] + ) -> List[Dict[str, Any]]: + r"""Construct training examples from raw data. + + Args: + raw_data (List[Dict[str, Any]]): List of raw data dictionaries + containing text and metadata. + + Returns: + List[Dict[str, Any]]: List of constructed examples with QA pairs + and metadata. + """ + self.logger.info("Starting to construct examples...") + examples = [] + + for data in tqdm(raw_data, desc="Constructing examples"): + # 1. Text preprocessing + processed_text = self._preprocess_text(data.get('text', '')) + if not processed_text: + example = { + # 'text': processed_text, + 'qa_pairs': [], + 'metadata': { + 'source': data.get('source', 'unknown'), + 'timestamp': data.get('timestamp', ''), + 'complexity': 0, + }, + } + examples.append(example) + continue + + # 2. Generate key information pairs + info_pairs = self._extract_info_pairs(processed_text) + + # 3. Construct question-answer pairs + if(info_pairs): + qa_pairs = self._generate_qa_pairs(info_pairs) + else: + qa_pairs = [] + + # 4. Add metadata + example = { + # 'text': processed_text, + 'qa_pairs': qa_pairs, + 'metadata': { + 'source': data.get('source', 'unknown'), + 'timestamp': data.get('timestamp', ''), + 'complexity': self._calculate_complexity(qa_pairs) if qa_pairs else 0, + }, + } + + examples.append(example) + + # self.logger.info(f"Successfully constructed {len(examples)} examples") + return examples + + def _preprocess_text(self, text: str) -> str: + r"""Preprocess input text for example construction. + + Args: + text (str): Input text to preprocess. + + Returns: + str: Preprocessed text, or empty string if text fails quality + checks. + """ + if not isinstance(text, str): + return '' + + # 1. Basic cleaning + text = text.strip() + + # 2. Length check + if ( + len(text) < self.min_length + or len(text) > self.max_length + ): + self.logger.warning("text fail to pass length check.") + return '' + + # 3. Quality check + if not self._check_text_quality(text): + self.logger.warning("text fail to pass quality check.") + return '' + + return text + + def _calculate_special_char_ratio(self, text): + # 中文字符的Unicode范围(基本汉字+扩展) + chinese_ranges = [ + (0x4E00, 0x9FFF), # 基本汉字 + (0x3400, 0x4DBF), # 扩展A + (0x20000, 0x2A6DF), # 扩展B + (0x2A700, 0x2B73F), # 扩展C + (0x2B740, 0x2B81F), # 扩展D + (0x2B820, 0x2CEAF) # 扩展E + ] + + special_count = 0 + for c in text: + # 检查是否为中文、字母数字或空格 + is_chinese = any(start <= ord(c) <= end for start, + end in chinese_ranges) + if not (c.isalnum() or c.isspace() or is_chinese): + special_count += 1 + + return special_count / len(text) if text else 0 + + def _check_text_quality(self, text: str) -> bool: + r"""Check the quality of input text. + + Args: + text (str): Text to check quality for. + + Returns: + bool: True if text passes quality checks, False otherwise. + """ + # 1. Basic quality check + if (self.lang == "en" and text.count('.') < 2): # Must have at least 2 sentences + return False + elif (self.lang in ["zh", "ch"] and text.count("。") < 2): + return False + + # 2. Special character ratio check + special_char_ratio = self._calculate_special_char_ratio(text) + if special_char_ratio > 0.3: # No more than 30% special characters + return False + + return True + + def _extract_info_pairs(self, text: str) -> List[Dict[str, Sequence[str]]]: + r"""Extract information pairs and relationships from text. + + Args: + text (str): Input text to extract information from. + + Returns: + List[Dict[str, Sequence[str]]]: List of dictionaries containing + premise, intermediate, conclusion, and related contexts. + """ + # Split into sentences + if (self.lang == "en"): + sentences = [s.strip() for s in text.split('.') if s.strip()] + else: + sentences = [s.strip() for s in text.split('。') if s.strip()] + + info_pairs = [] + + # Extract combinations of multiple related sentences + for i in range(len(sentences) - 2): + if len(sentences[i]) > 10 and len(sentences[i + 1]) > 10: + info_pairs.append( + { + 'premise': sentences[i], + 'intermediate': sentences[i + 1], + 'conclusion': sentences[i + 2] + if i + 2 < len(sentences) + else '', + 'related_contexts': [ + s + for j, s in enumerate(sentences) + if j != i and j != i + 1 and len(s) > 10 + ][:2], + # Limit to 2 additional related contexts + } + ) + + return info_pairs + + def _generate_qa_pairs( + self, info_pairs: List[Dict[str, Sequence[str]]] + ) -> List[Dict[str, str]]: + r"""Generate multi-hop question-answer pairs from information pairs. + + Args: + info_pairs (List[Dict[str, Sequence[str]]]): List of information + pairs extracted from text. + + Returns: + List[Dict[str, str]]: List of generated QA pairs. + """ + user_inputs = [] + for pair in info_pairs: + # 1. Generate multi-hop question-answer pair using AI + # Construct full context + context = ( + f"{pair['premise']}. {pair['intermediate']}." + f" {pair['conclusion']}" + ) + user_inputs.append( + self.prompt_template.build_prompt(context)) + + sys_prompt = self.prompt_template.build_system_prompt() + + responses = self.llm_sering.generate_from_input( + user_inputs=user_inputs, system_prompt=sys_prompt) + qa_pairs = self._extract_qa_pairs(responses) + + return qa_pairs + + def _extract_qa_pairs(self, responses: List[str]) -> List[Dict[str, Any]]: + """ + 从原始响应中精确提取符合结构的QA对 + 自动跳过非法JSON和干扰文本 + """ + qa_pairs = [] + for response in responses: + # self.logger.info(f"generated qa: {response}") + + # 方法1:尝试直接解析整个响应为JSON + try: + qa_pair = json.loads(response) + if isinstance(qa_pair, dict) and "question" in qa_pair: + qa_pairs.append(qa_pair) + continue + elif isinstance(qa_pair, list): + for item in qa_pair: + if isinstance(item, dict) and "question" in item: + qa_pairs.append(item) + continue + except json.JSONDecodeError: + pass + + # 方法2:使用正则表达式查找所有JSON对象 + try: + # 查找所有以 { 开始的JSON对象 + json_pattern = r'\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}' + + # 更精确的模式,匹配完整的JSON对象 + brace_count = 0 + start_pos = -1 + json_objects = [] + + for i, char in enumerate(response): + if char == '{': + if brace_count == 0: + start_pos = i + brace_count += 1 + elif char == '}': + brace_count -= 1 + if brace_count == 0 and start_pos != -1: + json_str = response[start_pos:i+1] + json_objects.append(json_str) + start_pos = -1 + + # 尝试解析找到的每个JSON字符串 + for json_str in json_objects: + try: + qa_pair = json.loads(json_str) + if (isinstance(qa_pair, dict) and + "question" in qa_pair and + "reasoning_steps" in qa_pair and + "answer" in qa_pair and + "supporting_facts" in qa_pair and + "type" in qa_pair): + qa_pairs.append(qa_pair) + # self.logger.info( + # f"Successfully extracted QA pair: {qa_pair['question']}") + except json.JSONDecodeError as e: + self.logger.debug( + f"Failed to parse JSON object: {json_str[:100]}... Error: {e}") + continue + + # 对qa_pairs中重复的question进行去重 + if qa_pairs: + seen_questions = set() + unique_qa_pairs = [] + + for qa_pair in qa_pairs: + question = qa_pair.get("question", "").strip().lower() + if question and question not in seen_questions: + seen_questions.add(question) + unique_qa_pairs.append(qa_pair) + self.logger.debug( + f"Added unique question: {qa_pair['question']}") + else: + self.logger.debug( + f"Skipped duplicate question: {qa_pair.get('question', 'N/A')}") + + qa_pairs = unique_qa_pairs + # self.logger.info( + # f"After deduplication: {len(qa_pairs)} unique QA pairs") + + # 如果没有找到有效的JSON对象,记录警告 + if not json_objects: + self.logger.warning( + "No JSON objects found in model response.") + + except Exception as e: + self.logger.warning( + f"Failed to parse QA information from model response. Error: {e}") + + return qa_pairs + + def _calculate_complexity(self, qa_pairs: List[Dict[str, Any]]) -> float: + r"""Calculate the complexity score for a set of QA pairs. + + Args: + qa_pairs (List[Dict[str, Any]]): List of QA pairs to calculate + complexity for. + + Returns: + float: Complexity score between 0.0 and 1.0. + """ + if not qa_pairs: + return 0.0 + + # Calculate complexity based on multiple factors + complexities = [] + for qa in qa_pairs: + # 1. Number of reasoning steps + reasoning_steps_count = len(qa.get('reasoning_steps', [])) + + # 2. Number of supporting facts + supporting_facts_count = len(qa.get('supporting_facts', [])) + + # 3. Question length + question_length = len(qa.get('question', '').split()) + + # 4. Answer length + answer_length = len(qa.get('answer', '').split()) + + # Calculate complexity of a single QA pair + qa_complexity = ( + min(reasoning_steps_count / 3, 1.0) + * 0.4 # Weight for reasoning steps + + min(supporting_facts_count / 3, 1.0) + * 0.3 # Weight for supporting facts + + min(question_length / 20, 1.0) + * 0.15 # Weight for question length + + min(answer_length / 50, 1.0) * 0.15 + # Weight for answer length + ) + + complexities.append(qa_complexity) + + return sum(complexities) / len(complexities) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/kbc_text_cleaner.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/kbc_text_cleaner.py new file mode 100644 index 0000000000000000000000000000000000000000..06521176262273f201af00d8442d48ba3609bab3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/kbc_text_cleaner.py @@ -0,0 +1,137 @@ +from dataflow.prompts.kbcleaning import KnowledgeCleanerPrompt +import pandas as pd +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger + +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC + +from dataflow.core.prompt import prompt_restrict, DIYPromptABC +from typing import Union + +import re +@prompt_restrict( + KnowledgeCleanerPrompt +) + +@OPERATOR_REGISTRY.register() +class KBCTextCleaner(OperatorABC): + ''' + KnowledgeCleaner is a class that cleans knowledge for RAG to make them more accurate, reliable and readable. + ''' + def __init__(self, llm_serving: LLMServingABC, lang="en", prompt_template : Union[KnowledgeCleanerPrompt, DIYPromptABC] = None): + self.logger = get_logger() + self.prompts = KnowledgeCleanerPrompt(lang=lang) + self.llm_serving = llm_serving + if prompt_template: + self.prompt_template = prompt_template + else: + self.prompt_template = KnowledgeCleanerPrompt() + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "知识清洗算子:对原始知识内容进行标准化处理,包括HTML标签清理、特殊字符规范化、" + "链接处理和结构优化,提升RAG知识库的质量。主要功能:\n" + "1. 移除冗余HTML标签但保留语义化标签\n" + "2. 标准化引号/破折号等特殊字符\n" + "3. 处理超链接同时保留文本\n" + "4. 保持原始段落结构和代码缩进\n" + "5. 确保事实性内容零修改\n" + "\n输入格式示例:\n" + "
\n" + "

标题文本

\n" + "

正文段落,包括特殊符号,例如“弯引号”、–破折号等

\n" + " \"示意图\"\n" + " 链接文本\n" + "
代码片段
\n" + " ...\n" + "
\n" + "\n输出格式示例:\n" + "标题文本\n\n" + "正文段落,包括特殊符号,例如\"直引号\"、-破折号等\n\n" + "[Image: 示例图 example.jpg]\n\n" + "链接文本\n\n" + "代码片段\n\n" + "[结构保持,语义保留,敏感信息脱敏处理(如手机号、保密标记等)]" + ) + elif lang == "en": + return ( + "Knowledge Cleaning Operator: Standardizes raw HTML/text content for RAG quality improvement. Key functions:\n" + "1. Removes redundant HTML tags while preserving semantic tags\n" + "2. Normalizes special characters (e.g., curly quotes, dashes)\n" + "3. Processes hyperlinks and retains their text\n" + "4. Preserves paragraph structure and code indentation\n" + "5. Ensures factual content remains unchanged\n" + "\nExample Input Format:\n" + "
\n" + "

Title Text

\n" + "

Paragraph with “curly quotes” and – dashes

\n" + " \"Diagram\"\n" + " Link text\n" + "
Code block
\n" + " ...\n" + "
\n" + "\nExample Output Format:\n" + "Title Text\n\n" + "Paragraph with \"straight quotes\" and - dashes\n\n" + "[Image: Diagram example.jpg]\n\n" + "Link text\n\n" + "Code block\n\n" + "[Structure retained, semantics preserved, sensitive info masked (e.g., phone numbers, confidential tags)]" + ) + else: + return "Knowledge cleaning operator for RAG content standardization. Set lang='zh' or 'en' for examples." + + + + def _validate_dataframe(self, dataframe: pd.DataFrame): + required_keys = [self.input_key] + forbidden_keys = [self.output_key] + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + raise ValueError(f"Missing required column(s): {missing}") + if conflict: + raise ValueError(f"The following column(s) already exist and would be overwritten: {conflict}") + + def _reformat_prompt(self, dataframe): + """ + Reformat the prompts in the dataframe to generate questions. + """ + raw_contents = dataframe[self.input_key].tolist() + inputs = [self.prompt_template.build_prompt(raw_content) for raw_content in raw_contents] + + return inputs + + def run( + self, + storage: DataFlowStorage, + input_key:str = "raw_chunk", + output_key:str = "cleaned_chunk" + ): + ''' + Runs the knowledge cleaning process, reading from the input key and saving results to output key. + ''' + self.input_key, self.output_key = input_key, output_key + dataframe = storage.read("dataframe") + self._validate_dataframe(dataframe) + formatted_prompts = self._reformat_prompt(dataframe) + cleaned = self.llm_serving.generate_from_input(formatted_prompts,"") + + #for each in cleaned, only save the content in and + cleaned_extracted = [ + str(text).split('')[1].split('')[0].strip() + if '' in str(text) and '' in str(text) + else str(text).strip() + for text in cleaned + ] + dataframe[self.output_key] = cleaned_extracted + output_file = storage.write(dataframe) + self.logger.info(f"Results saved to {output_file}") + + return [output_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/kbc_text_cleaner_batch.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/kbc_text_cleaner_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..53a445f6ed6e900d2239f79d9a4c81cceaa5cc26 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/kbc_text_cleaner_batch.py @@ -0,0 +1,148 @@ +from dataflow.prompts.kbcleaning import KnowledgeCleanerPrompt +import pandas as pd +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +import json +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC + +from dataflow.core.prompt import prompt_restrict, DIYPromptABC +from typing import Union + +import re +@prompt_restrict( + KnowledgeCleanerPrompt +) + +@OPERATOR_REGISTRY.register() +class KBCTextCleanerBatch(OperatorABC): + ''' + KnowledgeCleaner is a class that cleans knowledge for RAG to make them more accurate, reliable and readable. + ''' + + def __init__(self, llm_serving: LLMServingABC, lang="en", prompt_template: Union[KnowledgeCleanerPrompt, DIYPromptABC] = None): + self.logger = get_logger() + self.prompts = KnowledgeCleanerPrompt(lang=lang) + self.llm_serving = llm_serving + if prompt_template: + self.prompt_template = prompt_template + else: + self.prompt_template = KnowledgeCleanerPrompt(lang=lang) + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "知识清洗算子:对原始知识内容进行标准化处理,包括HTML标签清理、特殊字符规范化、" + "链接处理和结构优化,提升RAG知识库的质量。主要功能:\n" + "1. 移除冗余HTML标签但保留语义化标签\n" + "2. 标准化引号/破折号等特殊字符\n" + "3. 处理超链接同时保留文本\n" + "4. 保持原始段落结构和代码缩进\n" + "5. 确保事实性内容零修改" + ) + elif lang == "en": + return ( + "Knowledge Cleaning Operator: Standardizes raw content for RAG by:\n" + "1. Removing redundant HTML tags while preserving semantic markup\n" + "2. Normalizing special characters (quotes/dashes)\n" + "3. Processing hyperlinks with text preservation\n" + "4. Maintaining original paragraph structure and code indentation\n" + "5. Guaranteeing zero modification of factual content" + ) + else: + return "Knowledge cleaning operator for RAG content standardization" + + def _validate_dataframe(self, dataframe: pd.DataFrame): + required_keys = [self.input_key] + forbidden_keys = [self.output_key] + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + raise ValueError(f"Missing required column(s): {missing}") + if conflict: + raise ValueError( + f"The following column(s) already exist and would be overwritten: {conflict}") + + def _reformat_prompt(self, dataframe): + """ + Reformat the prompts in the dataframe to generate questions. + """ + raw_contents = dataframe[self.input_key].tolist() + inputs = [self.prompt_template.build_prompt( + raw_content) for raw_content in raw_contents] + + return inputs + + + def _reformat_prompt_from_path(self, chunk_path: str) -> list: + """ + Reformat the prompts in the file (JSON or JSONL) to generate question prompts. + + Args: + chunk_path (str): Path to the .json or .jsonl file containing raw chunks. + + Returns: + list: A list of formatted prompt strings. + """ + if chunk_path.endswith(".json"): + dataframe = pd.read_json(chunk_path) + elif chunk_path.endswith(".jsonl"): + dataframe = pd.read_json(chunk_path, lines=True) + else: + raise ValueError( + "Unsupported file format. Only .json and .jsonl are supported.") + + if "raw_chunk" not in dataframe.columns: + raise KeyError("'raw_chunk' field not found in the input file.") + + raw_contents = dataframe["raw_chunk"].tolist() + inputs = [self.prompts.build_prompt( + raw_content) for raw_content in raw_contents] + + return raw_contents, inputs + + + def run( + self, + storage: DataFlowStorage, + input_key: str = "chunk_path", + output_key: str = "cleaned_chunk_path" + ): + ''' + Runs the knowledge cleaning process, reading from the input key and saving results to output key. + ''' + self.input_key, self.output_key = input_key, output_key + dataframe = storage.read("dataframe") + self._validate_dataframe(dataframe) + chunk_paths = dataframe[self.input_key].tolist() + + for chunk_path in chunk_paths: + if(chunk_path): + raw_chunks, formatted_prompts = self._reformat_prompt_from_path(chunk_path) + cleaned = self.llm_serving.generate_from_input(formatted_prompts, "") + + # for each in cleaned, only save the content in and + cleaned_extracted = [ + text.split('')[1].split('')[0].strip() + if '' in str(text) and '' in str(text) + else str(text).strip() + for text in cleaned + ] + json_items=[{ + "raw_chunk": raw_chunk, + "cleaned_chunk": cleaned_chunk + } for raw_chunk, cleaned_chunk in zip(raw_chunks, cleaned_extracted)] + + with open(chunk_path, "w", encoding="utf-8") as f: + json.dump(json_items, f, ensure_ascii=False, indent=4) + self.logger.info(f"Successfully cleaned contents in {chunk_path}") + + dataframe[self.output_key] = chunk_paths + output_file = storage.write(dataframe) + self.logger.info(f"Results saved to {output_file}") + + return [output_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/mathbook_question_extract.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/mathbook_question_extract.py new file mode 100644 index 0000000000000000000000000000000000000000..960928f474c0d58fba2ad744d51ada8bfdaf6c7d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/mathbook_question_extract.py @@ -0,0 +1,333 @@ +import sys +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.core import OperatorABC +import os +from pathlib import Path +import json +import shutil +import fitz # pip install pymupdf +from dataflow.prompts.kbcleaning import MathbookQuestionExtractPrompt +import re +from openai import OpenAI +import base64 +from typing import Literal, Union +from dataflow.core import LLMServingABC +from dataflow.serving import APIVLMServing_openai +from dataflow.core.prompt import DIYPromptABC +from dataflow.utils.storage import DataFlowStorage + +@OPERATOR_REGISTRY.register() +class MathBookQuestionExtract(OperatorABC): + def __init__(self, + llm_serving: APIVLMServing_openai, + prompt_template: Union[MathbookQuestionExtractPrompt, DIYPromptABC] = MathbookQuestionExtractPrompt(), + mineru_backend: str = "vlm-vllm-engine", + dpi: int = 300, + key_name_of_api_key: str = "DF_API_KEY", + model_name: str = "o4-mini", + max_workers: int = 20 + ): + self.logger = get_logger() + self.llm_serving = llm_serving + self.prompt_template = prompt_template + + self.mineru_backend = mineru_backend + self.dpi = dpi + self.key_name_of_api_key = key_name_of_api_key + self.model_name = model_name + self.max_workers = max_workers # 注意:这个参数在原逻辑中并未被使用,但仍按要求移入init + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于从数学教材PDF中提取问题和相关图片内容。它将PDF转换为图片,使用MinerU进行内容提取," + "然后组织图片并使用大语言模型分析内容,最终生成包含问题和图片的JSON和Markdown文件。\n" + "输入参数:\n" + "- llm_serving:VLM服务对象,需实现APIVLMServing_openai接口\n" + "- pdf_file_path:PDF文件路径\n" + "- output_file_name:输出文件名\n" + "- output_folder:输出文件夹路径\n" + "- MinerU_Backend:MinerU后端类型,默认为'vlm-sglang-engine'\n" + "- dpi:PDF转图片的分辨率,默认为300\n" + "- api_url:API服务URL\n" + "- key_name_of_api_key:API密钥的环境变量名\n" + "- model_name:使用的模型名称,默认为'o4-mini'\n" + "- max_workers:最大并行工作线程数,默认为20\n" + "输出参数:\n" + "- 返回布尔值表示处理是否成功\n" + "- 在指定文件夹生成JSON和Markdown格式的提取结果" + ) + elif lang == "en": + return ( + "This operator extracts questions and related images from mathematics textbook PDFs. It converts the PDF to images, " + "uses MinerU for content extraction, organizes the images, and analyzes the content using a large vision-language model, " + "ultimately generating JSON and Markdown files containing questions and images.\n" + "Input Parameters:\n" + "- llm_serving: VLM serving object implementing APIVLMServing_openai interface\n" + "- pdf_file_path: Path to the PDF file\n" + "- output_file_name: Name for the output files\n" + "- output_folder: Path to the output folder\n" + "- MinerU_Backend: MinerU backend type, default is 'vlm-sglang-engine'\n" + "- dpi: Resolution for PDF to image conversion, default is 300\n" + "- api_url: API service URL\n" + "- key_name_of_api_key: Environment variable name for API key\n" + "- model_name: Model name to use, default is 'o4-mini'\n" + "- max_workers: Maximum number of parallel workers, default is 20\n\n" + "Output Parameters:\n" + "- Returns boolean indicating success of processing\n" + "- Generates extraction results in JSON and Markdown formats in the specified folder" + ) + else: + return ( + "MathBookQuestionExtract processes mathematics textbook PDFs to extract questions and images using MinerU and VLM." + ) + + def mineru2_runner(self, + pdf_file_path:str, + output_folder:str, + # pipeline|vlm-transformers|vlm-vllm-engine|vlm-http-client + mineru_backend: Literal["pipeline", "vlm-transformers", "vlm-vllm-engine", "vlm-http-client"] = "pipeline" + ): + try: + import mineru + except ImportError: + raise Exception( + """ +MinerU is not installed in this environment yet. +Please refer to https://github.com/opendatalab/mineru to install. +Or you can just execute 'pip install mineru[pipeline]' and 'mineru-models-download' to fix this error. +Please make sure you have GPU on your machine. +""" + ) + + + os.environ['MINERU_MODEL_SOURCE'] = "local" # 可选:从本地加载模型 + + MinerU_Version = {"pipeline": "auto", "vlm-transformers": "vlm", 'vlm-vllm-engine': 'vlm', 'vlm-http-client': 'vlm'} + + raw_file = Path(pdf_file_path) + pdf_name = raw_file.stem + intermediate_dir = output_folder + try: + return_code = os.system( + f"mineru -p {raw_file} -o {intermediate_dir} -b {mineru_backend} --source local" + ) + if return_code != 0: + raise RuntimeError(f"MinerU execution failed with return code: {return_code}") + except Exception as e: + raise RuntimeError(f"Failed to process file with MinerU: {str(e)}") + + output_file = os.path.join(intermediate_dir, pdf_name, MinerU_Version[mineru_backend], f"{pdf_name}_content_list.json") + output_pic_folder = os.path.join(intermediate_dir, pdf_name, MinerU_Version[mineru_backend], "images") + self.logger.info(f"MinerU json file has been saved to {output_file}") + return output_file, output_pic_folder + + def organize_pics( + self, + mineru_content_json_path: str, + mineru_image_folder: str, + output_file_path: str, + output_pic_folder: str + ): + ''' + 用来把mineru切割出来的图片组织到最终文件夹下的辅助函数 + 输入: + mineru_content_json_path: mineru切割出来的json文件路径 + mineru_image_folder: mineru切割出来的图片文件夹路径 + 输出: + output_file_path: 组织图片后的图片信息记录文件,服务后续的图片处理 + output_pic_folder: 最终组织后的图片文件夹路径 + ''' + global_counter = 0 + global_json_data = [] + + # read mineru content json + json_data = json.load(open(mineru_content_json_path, 'r')) + + # if output_pic_folder is not exist, create it + if not os.path.exists(output_pic_folder): + os.makedirs(output_pic_folder) + + for item in json_data: + if item['type'] == 'image': + # get the image name + image_name = item['img_path'].split('/')[-1] + # get the image path + image_path = os.path.join(mineru_image_folder, image_name) + + page_idx = item['page_idx'] + + # rename the image + new_image_name = f"{global_counter}.jpg" + new_image_path = os.path.join(output_pic_folder, new_image_name) + shutil.copy(image_path, new_image_path) + + # add to global json data + global_json_data.append({ + "img_path": new_image_path, + "page_idx": page_idx, + }) + global_counter += 1 + + # write to json file + with open(output_file_path, 'w') as f: + json.dump(global_json_data, f, indent=4) + + + def pdf2images(self, pdf_path: str, output_folder: str, dpi: int = 300): + ''' + 用来把pdf文件转换为图片的辅助函数 + 输入: + pdf_path: pdf文件路径 + output_folder: 输出图片文件夹路径 + ''' + doc = fitz.open(pdf_path) + # make output directory if it doesn't exist + os.makedirs(output_folder, exist_ok=True) + # convert each page to image + for page_index in range(len(doc)): + page = doc.load_page(page_index) + pix = page.get_pixmap(dpi=dpi) + pix.save(f"{output_folder}/page_{page_index}.jpg") + self.logger.info(f"Converted page {page_index} to image") + return True + def encode_image_to_base64(self, image_path: str) -> str: + with open(image_path, "rb") as f: + return base64.b64encode(f.read()).decode("utf-8") + + def process_input(self, + page_folder: str, + img_json_path: str + ): + # 加载page_folder内所有的page_n.jpg + page_list = [os.path.join(page_folder, f) for f in os.listdir(page_folder) if f.endswith(('.jpg'))] + idx_list = [int(f.split("/")[-1].split(".")[0].split("_")[-1]) for f in page_list] + max_page_idx = max(idx_list) + + # load img_json + img_json = json.load(open(img_json_path, "r")) + img_dict = {} + for item in img_json: + if item["page_idx"] not in img_dict: + img_dict[item["page_idx"]] = [] + img_dict[item["page_idx"]].append(item["img_path"]) + + full_input_image_list = [] + full_input_label_list = [] + + for page_idx in range(max_page_idx): + image_list = [] + label_list = [] + image_list.append(os.path.join(page_folder, f"page_{page_idx}.jpg")) + label_list.append(f"page_{page_idx}") + image_list.append(os.path.join(page_folder, f"page_{page_idx+1}.jpg")) + label_list.append(f"page_{page_idx+1}") + + if page_idx in img_dict: + image_list.extend(img_dict[page_idx]) + label_list.extend([img_path.split("/")[-1] for img_path in img_dict[page_idx]]) + if page_idx+1 in img_dict: + image_list.extend(img_dict[page_idx+1]) + label_list.extend([img_path.split("/")[-1] for img_path in img_dict[page_idx+1]]) + full_input_image_list.append(image_list) + full_input_label_list.append(label_list) + return full_input_image_list,full_input_label_list + + def analyze_and_save(self,result_list,save_folder,img_folder,output_file_name): + # ... (analyze_and_save 方法保持不变) + # make save_folder if not exist + if not os.path.exists(save_folder): + os.makedirs(save_folder) + # make save_folder/images if not exist + if not os.path.exists(os.path.join(save_folder, "images")): + os.makedirs(os.path.join(save_folder, "images")) + + output_json = [] + output_markdown_text = "" + + for item in result_list: + if not item: + continue + split_text = item.split("") + for text in split_text: + if not text: + continue + # 检查所有形如index.jpg这样的内容,比如1.jpg,严格匹配*.jpg + pic_list = [] + pic_match = re.findall(r'(.*?)\.jpg', text) + if pic_match: + for pic_name in pic_match: + # 传入完整路径 + pic_list.append(os.path.join(img_folder, f"{pic_name}.jpg")) + + # 生成json风格tezt:直接删掉所有index.jpg + json_text = re.sub(r'(.*?)\.jpg', '', text) + + # 生成markdown风格text:把index.jpg替换为![index.jpg](img_folder/index.jpg) + markdown_text = text + for pic_name in pic_match: + # 把img_folder/pic_name.jpg copy 到 save_folder/images/pic_name.jpg + shutil.copy(os.path.join(img_folder, f"{pic_name}.jpg"), os.path.join(save_folder, "images", f"{pic_name}.jpg")) + markdown_text = markdown_text.replace(f"{pic_name}.jpg", f"![](images/{pic_name}.jpg)") + else: + json_text = text + markdown_text = text + pic_list = [] + json_data = { + "text": json_text, + "pics": pic_list + } + output_json.append(json_data) + output_markdown_text += markdown_text + "\n" + "---" + "\n" + # save output_json to save_folder + with open(os.path.join(save_folder, f"{output_file_name}.json"), "w") as f: + json.dump(output_json, f, indent=4, ensure_ascii=False) + # save output_markdown_text to save_folder + with open(os.path.join(save_folder, f"{output_file_name}.md"), "w", encoding="utf-8") as f: + f.write(output_markdown_text) + return output_json,output_markdown_text + + def run( + self, + storage: DataFlowStorage, + input_pdf_file_path: str, + output_file_name: str, + output_folder: str, + ): + # get the configuration parameters from self + api_key = os.environ.get(self.key_name_of_api_key) + if not api_key: + raise ValueError(f"API key not found in environment variable {self.key_name_of_api_key}") + + # 1. convert pdf to images + pdf2images_folder_name = os.path.join(output_folder, "pdfimages") + self.pdf2images(input_pdf_file_path, pdf2images_folder_name, self.dpi) + + # 2. use mineru to extract content and pics + json_content_file, pic_folder = self.mineru2_runner(input_pdf_file_path, output_folder, self.mineru_backend) + + # 3. organize_pics + output_image_folder = os.path.join(output_folder, "organized_images") + output_json_file = os.path.join(output_image_folder, "organized_info.json") + self.organize_pics(json_content_file, pic_folder, output_json_file, output_image_folder) + + # 4. process input + full_input_image_list, full_input_label_list = self.process_input(pdf2images_folder_name, output_json_file) + + # 5. init server and generate + system_prompt = self.prompt_template.build_prompt() + result_text_list = self.llm_serving.generate_from_input_multi_images( + list_of_image_paths=full_input_image_list, + list_of_image_labels=full_input_label_list, + system_prompt=system_prompt, + model=self.model_name, + timeout=1800 + ) + + # 6. save responses + self.analyze_and_save(result_text_list, output_folder, output_image_folder, output_file_name) + + # 7. return + return True diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/mineru_operators.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/mineru_operators.py new file mode 100644 index 0000000000000000000000000000000000000000..6d2fd72fa1383a21c3e17b02d136bca397f4be5c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/mineru_operators.py @@ -0,0 +1,626 @@ +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.kbc.mineru_api_caller import MinerUBatchExtractorViaAPI +import requests +from urllib.parse import urlparse +import os +from dataflow import get_logger +from trafilatura import fetch_url, extract +from tqdm import tqdm +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from pathlib import Path +from abc import abstractmethod + +def is_url(string): + try: + result = urlparse(string) + return all([result.scheme, result.netloc]) + except ValueError: + return False + +def is_pdf_url(url): + try: + # 发送HEAD请求,只获取响应头,不下载文件 + response = requests.head(url, allow_redirects=True) + # 如果响应的Content-Type是application/pdf + if response.status_code == 200 and response.headers.get('Content-Type') == 'application/pdf': + return True + else: + print(f"Content-Type: {response.headers.get('Content-Type')}") + return False + except requests.exceptions.RequestException: + # 如果请求失败,返回False + print("Request failed") + return False + +def download_pdf(url, save_path): + try: + # 发送GET请求下载PDF文件 + response = requests.get(url, stream=True) + # 确保响应内容是PDF + if response.status_code == 200 and response.headers.get('Content-Type') == 'application/pdf': + # 将PDF保存到本地 + pdf_folder = os.path.dirname(save_path) + os.makedirs(pdf_folder, exist_ok=True) + with open(save_path, 'wb') as f: + for chunk in response.iter_content(chunk_size=1024): + if chunk: + f.write(chunk) + print(f"PDF saved to {save_path}") + else: + print("The URL did not return a valid PDF file.") + except requests.exceptions.RequestException as e: + print(f"Error downloading PDF: {e}") + + + +class MinerUABC(OperatorABC): + + def __init__(self, intermediate_dir: str = "intermediate", mineru_backend: str = "vlm-sglang-engine"): + super().__init__() + self.logger = get_logger() + self.intermediate_dir=intermediate_dir + os.makedirs(self.intermediate_dir, exist_ok=True) + self.mineru_backend = mineru_backend + + def _parse_xml_to_md(self, raw_file:str=None, url:str=None, output_file:str=None): + logger=get_logger() + if(url): + downloaded=fetch_url(url) + if not downloaded: + downloaded = "fail to fetch this url. Please check your Internet Connection or URL correctness" + with open(output_file,"w", encoding="utf-8") as f: + f.write(downloaded) + return output_file + + elif(raw_file): + with open(raw_file, "r", encoding='utf-8') as f: + downloaded=f.read() + else: + raise Exception("Please provide at least one of file path and url string.") + + try: + result=extract(downloaded, output_format="markdown", with_metadata=True) + logger.info(f"Extracted content is written into {output_file}") + with open(output_file,"w", encoding="utf-8") as f: + f.write(result) + except Exception as e: + logger.error("Error during extract this file or link: ", e) + + return output_file + + def _batch_parse_html_or_xml(self, items: list): + """ + items: List[Dict] with keys: + - index + - raw_path or url + - output_path + """ + results = {} + for item in tqdm(items, desc="Parsing HTML/XML", ncols=80): + try: + if item.get("url"): + out = self._parse_xml_to_md(url=item["url"], output_file=item["output_path"]) + else: + out = self._parse_xml_to_md(raw_file=item["raw_path"], output_file=item["output_path"]) + results[item["index"]] = out + except Exception: + results[item["index"]] = "" + return results + + def _classify_raw_files(self, storage: DataFlowStorage, df, input_key): + + normalized = [] + + for idx, row in df.iterrows(): + src = row.get(input_key, "") + item = {"index": idx} + + # URL + if is_url(src): + if is_pdf_url(src): + pdf_path = os.path.join( + os.path.dirname(storage.first_entry_file_name), + f"raw/crawled/crawled_{idx}.pdf" + ) + download_pdf(src, pdf_path) + item.update({ + "type": "pdf", + "raw_path": pdf_path, + }) + else: + item.update({ + "type": "html", + "url": src, + }) + + # local file + else: + if not os.path.exists(src): + item["type"] = "invalid" + else: + ext = Path(src).suffix.lower() + if ext in [".pdf", ".png", ".jpg", ".jpeg", ".webp", ".gif"]: + item.update({"type": "pdf", "raw_path": src}) + elif ext in [".html", ".xml"]: + item.update({"type": "html", "raw_path": src}) + elif ext in [".txt", ".md"]: + item.update({"type": "text", "raw_path": src}) + else: + item["type"] = "unsupported" + + # output path + if "raw_path" in item: + name = Path(item["raw_path"]).stem + item["output_path"] = os.path.join(self.intermediate_dir, f"{name}.md") + elif "url" in item: + item["output_path"] = os.path.join(self.intermediate_dir, f"url_{idx}.md") + + normalized.append(item) + + pdf_items = [x for x in normalized if x["type"] == "pdf"] + html_items = [x for x in normalized if x["type"] == "html"] + text_items = [x for x in normalized if x["type"] == "text"] + + return pdf_items, html_items, text_items + + @abstractmethod + def _batch_parse_pdf_with_mineru(self, pdf_files: list): + pass + + def run(self, storage: DataFlowStorage, input_key: str = "source", output_key: str = "text_path"): + self.logger.info("Starting content extraction (batch mode)...") + dataframe = storage.read("dataframe") + self.logger.info(f"Loaded dataframe with {len(dataframe)} entries.") + + pdf_items, html_items, text_items = self._classify_raw_files(storage, dataframe, input_key) + + results = {} + + if html_items: + results.update(self._batch_parse_html_or_xml(html_items)) + + if pdf_items: + results.update( + self._batch_parse_pdf_with_mineru(pdf_items) + ) + + for item in text_items: + results[item["index"]] = item["raw_path"] + + # -------- Stage 4: merge back -------- + dataframe[output_key] = dataframe.index.map(lambda i: results.get(i, "")) + + out_path = storage.write(dataframe) + self.logger.info(f"Extraction finished. Results saved to {out_path}") + return out_path + + +@OPERATOR_REGISTRY.register() +class FileOrURLToMarkdownConverterAPI(MinerUABC): + """ + Including mineru via api calling. + Set your mineru key in `MINERU_API_KEY` environment parameter. + To get the mineru token, refer to https://mineru.net/apiManage/token. + For more details, refer to the MinerU GitHub: https://github.com/opendatalab/MinerU. + """ + def __init__(self, intermediate_dir: str = "intermediate", mineru_backend: str = "vlm", api_key:str = None): + super().__init__(intermediate_dir, mineru_backend) + if api_key is None or api_key.strip() == "": + try: + api_key = os.environ["MINERU_API_KEY"] + except KeyError: + raise ValueError("MinerU API key not provided. Please set the MINERU_API_KEY environment variable or pass the api_key parameter. To get a MinerU API key, visit https://mineru.net/apiManage/docs .") + + self.api_key = api_key + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "文件/URL 转 Markdown(MinerU API 版):批量将输入源转换为 Markdown,并把生成的 Markdown 路径回写到 DataFrame。\n\n" + "功能说明:\n" + "1) 自动识别输入类型(本地路径或 URL):\n" + " - URL:若为 PDF(Content-Type=application/pdf)会先下载到 raw/crawled/ 下再解析;否则按网页(HTML/XML)抓取正文转 Markdown。\n" + " - 本地文件:支持 PDF/图片(png/jpg/jpeg/webp/gif)、HTML/XML、TXT/MD;TXT/MD 直接透传。\n" + "2) PDF/图片:通过 MinerU 官方 API 批量解析,输出 Markdown 到 intermediate_dir。\n" + "3) HTML/XML:使用 trafilatura 抽取正文并输出 Markdown 到 intermediate_dir。\n\n" + "初始化参数(__init__):\n" + "- intermediate_dir: 中间产物目录,保存生成的 Markdown(默认 intermediate)\n" + "- mineru_backend: MinerU API 的 model_version(默认 vlm;可按后端/版本配置)\n" + "- api_key: MinerU API Key;不传则读取环境变量 MINERU_API_KEY\n\n" + "运行参数(run):\n" + "- storage: DataFlowStorage,需包含 dataframe\n" + "- input_key: 输入字段名,单元格为本地路径或 URL(默认 source)\n" + "- output_key: 输出字段名,写入对应行的 Markdown 文件路径(默认 text_path)\n\n" + "输出:\n" + "- 返回 storage.write(...) 的结果路径;并在 dataframe[output_key] 写入解析后的 Markdown 路径(失败为空字符串)。" + ) + else: + return ( + "File/URL to Markdown (MinerU API): batch converts sources to Markdown and writes Markdown paths back to the DataFrame.\n\n" + "What it does:\n" + "1) Auto-detects input type (local path or URL).\n" + " - URL: if it is a PDF (Content-Type=application/pdf), it downloads to raw/crawled/ then parses; otherwise treats it as HTML/XML and extracts main content.\n" + " - Local: supports PDF/images (png/jpg/jpeg/webp/gif), HTML/XML, TXT/MD; TXT/MD is passed through.\n" + "2) PDF/images: parsed in batch via MinerU official API, Markdown saved under intermediate_dir.\n" + "3) HTML/XML: main content extracted by trafilatura and saved as Markdown under intermediate_dir.\n\n" + "__init__ params:\n" + "- intermediate_dir: directory to store generated Markdown\n" + "- mineru_backend: MinerU API model_version\n" + "- api_key: MinerU API key (fallback to env MINERU_API_KEY)\n\n" + "run params:\n" + "- storage: DataFlowStorage containing a dataframe\n" + "- input_key: column holding local paths or URLs (default: source)\n" + "- output_key: column to store generated Markdown file paths (default: text_path)\n\n" + "Output:\n" + "- Returns the written dataframe path; dataframe[output_key] contains Markdown paths (empty on failure)." + ) + + + def _batch_parse_pdf_with_mineru(self, pdf_files: list): + """ + Batch parse PDFs using MinerU API. + + Args: + pdf_files (List[Dict]): each item has: + - index: row index in dataframe + - raw_path: local pdf path + - output_path: (ignored, kept for compatibility) + output_dir (str): base output directory for MinerU results + mineru_backend (str): MinerU backend name (currently informational) + + Returns: + Dict[int, str]: mapping from dataframe row index -> markdown path + """ + import os + + # -------- 1. collect pdf paths -------- + file_paths = [item["raw_path"] for item in pdf_files] + + if not file_paths: + return {} + + os.makedirs(self.intermediate_dir, exist_ok=True) + + # -------- 2. instantiate MinerU extractor -------- + extractor = MinerUBatchExtractorViaAPI( + api_key=self.api_key, + model_version=self.mineru_backend, # 你现在统一用 vlm + ) + + # -------- 3. run MinerU batch extraction -------- + result = extractor.extract_batch( + file_paths=file_paths, + out_dir=self.intermediate_dir, + ) + + # -------- 4. map data_id -> dataframe index -------- + # MinerU data_id 是 enumerate(file_paths) 的顺序字符串 + idx_map = { + str(i): pdf_files[i]["index"] + for i in range(len(pdf_files)) + } + + # -------- 5. build final index -> md_path mapping -------- + parsed_results = {} + + for item in result.get("items", []): + if item.get("state") != "done": + continue + + data_id = item.get("data_id") + md_path = item.get("md_path") + + if data_id not in idx_map: + continue + if not md_path or not os.path.exists(md_path): + continue + + parsed_results[idx_map[data_id]] = md_path + + return parsed_results + +@OPERATOR_REGISTRY.register() +class FileOrURLToMarkdownConverterLocal(MinerUABC): + """ + mineru_backend sets the backend engine for MinerU. Options include: + - "pipeline": Traditional pipeline processing (MinerU1) + - "vlm-sglang-engine": New engine based on multimodal language models (MinerU2) (default recommended) + Choose the appropriate backend based on your needs. Defaults to "vlm-sglang-engine". + For more details, refer to the MinerU GitHub: https://github.com/opendatalab/MinerU. + """ + def __init__(self, + intermediate_dir: str = "intermediate", + mineru_backend: str = "vlm-auto-engine", + mineru_source: str = "local", + mineru_model_path:str = None, + mineru_download_model_type:str = "vlm" + ): + """ + For mineru_* configeration, please refer to official https://opendatalab.github.io/MinerU/usage/model_source/ + - mineru_backend: backend type. check the `-b` section with `mineru --help` + - mineru_source: source type. check `--source` section with `mineru --help` + - mineru_model_path: where you put mineru model. check https://opendatalab.github.io/MinerU/usage/model_source/#1-download-models-to-local-storage + - mineru_download_model_type: which type of mineru you need to download. check `mineru-models-download --help` + """ + super().__init__(intermediate_dir, mineru_backend) + self.mineru_source = mineru_source + self.mineru_model_path = mineru_model_path + self.mineru_download_model_type = mineru_download_model_type + + @staticmethod + def get_desc(lang: str = "zh"): + """ + 返回算子功能描述 (根据run()函数的功能实现) + """ + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "文件/URL 转 Markdown(MinerU 本地批处理版):批量将输入源转换为 Markdown,并把生成的 Markdown 路径回写到 DataFrame。\n\n" + "功能说明:\n" + "1) 自动识别输入类型(本地路径或 URL):\n" + " - URL:若为 PDF(Content-Type=application/pdf)会先下载到 raw/crawled/ 下再解析;否则按网页(HTML/XML)抓取正文转 Markdown。\n" + " - 本地文件:支持 PDF/图片(png/jpg/jpeg/webp/gif)、HTML/XML、TXT/MD;TXT/MD 直接透传。\n" + "2) PDF/图片:通过本地 MinerU CLI(subprocess 调用 `mineru`)逐文件解析。\n" + " - 输出目录结构:{intermediate_dir}/{pdf_name}/{mineru_backend}/\n" + " - 默认 Markdown 路径:{intermediate_dir}/{pdf_name}/{mineru_backend}/{pdf_name}.md\n" + "3) HTML/XML:使用 trafilatura 抽取正文并输出 Markdown 到 intermediate_dir。\n\n" + "初始化参数(__init__):\n" + "- intermediate_dir: 中间产物目录(默认 intermediate)\n" + "- mineru_backend: MinerU CLI 后端(默认 vlm-auto-engine;也可 pipeline / vlm-sglang-engine 等)\n" + "- mineru_source: 模型来源(默认 local;对应 MINERU_MODEL_SOURCE)\n" + "- mineru_model_path: 本地模型目录;提供则会调用 configure_model 配置模型\n" + "- mineru_download_model_type: 配置模型类型(默认 vlm)\n\n" + "运行参数(run):\n" + "- storage: DataFlowStorage,需包含 dataframe\n" + "- input_key: 输入字段名(默认 source),值为本地路径或 URL\n" + "- output_key: 输出字段名(默认 text_path),写入对应行的 Markdown 文件路径\n\n" + "环境依赖:\n" + "- 需安装 mineru 并具备可用的运行环境(通常需要 GPU/模型文件);未安装会直接抛错。\n\n" + "输出:\n" + "- 返回 storage.write(...) 的结果路径;并在 dataframe[output_key] 写入解析后的 Markdown 路径(失败为空字符串)。" + ) + else: + return ( + "File/URL to Markdown (MinerU Local Batch): batch converts sources to Markdown and writes Markdown paths back to the DataFrame.\n\n" + "What it does:\n" + "1) Auto-detects input type (local path or URL).\n" + " - URL: if it is a PDF (Content-Type=application/pdf), it downloads to raw/crawled/ then parses; otherwise treats it as HTML/XML.\n" + " - Local: supports PDF/images, HTML/XML, TXT/MD; TXT/MD is passed through.\n" + "2) PDF/images: parsed via local MinerU CLI (`mineru`) per file.\n" + " - Output layout: {intermediate_dir}/{pdf_name}/{mineru_backend}/\n" + " - Default Markdown: {intermediate_dir}/{pdf_name}/{mineru_backend}/{pdf_name}.md\n" + "3) HTML/XML: extracted by trafilatura and saved as Markdown under intermediate_dir.\n\n" + "__init__ params:\n" + "- intermediate_dir: directory to store generated artifacts\n" + "- mineru_backend: MinerU CLI backend (e.g., vlm-auto-engine / pipeline / vlm-sglang-engine)\n" + "- mineru_source: model source (default local)\n" + "- mienru_model_path: local model path; if provided, configures models via configure_model\n" + "- mineru_download_model_type: model type for configuration\n\n" + "run params:\n" + "- storage: DataFlowStorage containing a dataframe\n" + "- input_key: column holding local paths or URLs\n" + "- output_key: column to store Markdown file paths\n\n" + "Dependencies:\n" + "- Requires MinerU installed and properly configured (often GPU/models).\n\n" + "Output:\n" + "- Returns the written dataframe path; dataframe[output_key] contains Markdown paths (empty on failure)." + ) + + def _batch_parse_pdf_with_mineru(self, pdf_files: list): + """ + Uses MinerU to parse PDF/image files (pdf/png/jpg/jpeg/webp/gif) into Markdown files. + + Internally, the parsed outputs for each item are stored in a structured directory: + 'intermediate_dir/pdf_name/MinerU_Version[mineru_backend]'. + This directory stores various MinerU parsing outputs, and you can customize + which content to extract based on your needs. + + Args: + raw_file: Input file path, supports .pdf/.png/.jpg/.jpeg/.webp/.gif + output_file: Full path for the output Markdown file + mineru_backend: Sets the backend engine for MinerU. Options include: + - "pipeline": Traditional pipeline processing (MinerU1) + - "vlm-sglang-engine": New engine based on multimodal language models (MinerU2) (default recommended) + Choose the appropriate backend based on your needs. Defaults to "vlm-sglang-engine". + For more details, refer to the MinerU GitHub: https://github.com/opendatalab/MinerU. + + Returns: + output_file: Path to the Markdown file + """ + + try: + import mineru + except ImportError: + raise Exception( + """ + MinerU is not installed in this environment yet. + Please refer to https://github.com/opendatalab/mineru to install. + Or you can just execute 'pip install mineru[pipeline]' and 'mineru-models-download' to fix this error. + Please make sure you have GPU on your machine. + """ + ) + logger=get_logger() + from mineru.cli.models_download import configure_model + + os.environ.setdefault("MINERU_MODEL_SOURCE", self.mineru_source) + + # load local model and config corresponding files https://github.com/opendatalab/MinerU/blob/a12610fb3e9e24488fe3e76cd233ba88ec64bbaf/mineru/cli/models_download.py#L19 + if self.mineru_model_path != None: + configure_model(self.mineru_model_path, self.mineru_download_model_type) + + parsed_results = {} + for item in pdf_files: + raw_file = Path(item["raw_path"]) + pdf_name = Path(raw_file).stem + intermediate_dir = self.intermediate_dir + + import subprocess + + command = [ + "mineru", + "-p", raw_file, + "-o", intermediate_dir, + "-b", self.mineru_backend, + "--source", "local" + ] + + try: + result = subprocess.run( + command, + #stdout=subprocess.DEVNULL, + #stderr=subprocess.DEVNULL, + check=True + ) + except Exception as e: + raise RuntimeError(f"Failed to process file with MinerU: {str(e)}") + + # Directory for storing raw data, including various MinerU parsing outputs. + # You can customize which content to extract based on your needs. + + # PerItemDir = os.path.join(intermediate_dir, pdf_name, MinerU_Version[mineru_backend]) + PerItemDir = os.path.join(intermediate_dir, pdf_name, self.mineru_backend) + output_file = os.path.join(PerItemDir, f"{pdf_name}.md") + parsed_results[item["index"]] = output_file + logger.info(f"Markdown saved to: {output_file}") + + return parsed_results + + +@OPERATOR_REGISTRY.register() +class FileOrURLToMarkdownConverterFlash(MinerUABC): + + def __init__(self, intermediate_dir: str = "intermediate", mineru_model_path=None, batch_size:int = 4, replicas:int = 1, num_gpus_per_replica:float = 1, engine_gpu_util_rate_to_ray_cap:float = 0.9): + try: + from flash_mineru import MineruEngine + except ImportError: + raise Exception( + """ + FlashMinerU is not installed in this environment yet. + Please refer to https://github.com/OpenDCAI/Flash-MinerU to install. + Or you can just execute 'pip install flash_mineru'. + Please make sure you have GPU on your machine. + """ + ) + except Exception as e: + raise RuntimeError(f"Failed to import MineruEngine: {e}") from e + + super().__init__(intermediate_dir, mineru_backend="vlm") + if mineru_model_path is None: + raise ValueError("Please provide the model_path for MinerUEngine. You can download the model from https://huggingface.co/opendatalab/MinerU2.5-2509-1.2B.") + + self.flash_mineru_engine = MineruEngine( + model=mineru_model_path, + save_dir=intermediate_dir, + batch_size=batch_size, + replicas=replicas, + num_gpus_per_replica=num_gpus_per_replica, engine_gpu_util_rate_to_ray_cap=engine_gpu_util_rate_to_ray_cap + ) + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "文件/URL 转 Markdown(FlashMinerU 加速版):使用 FlashMinerU 引擎批量解析 PDF/图片为 Markdown,并把生成的 Markdown 路径回写到 DataFrame。\n\n" + "功能说明:\n" + "1) 自动识别输入类型(本地路径或 URL):\n" + " - URL:若为 PDF(Content-Type=application/pdf)会先下载到 raw/crawled/ 下再解析;否则按网页(HTML/XML)抓取正文转 Markdown。\n" + " - 本地文件:支持 PDF/图片(png/jpg/jpeg/webp/gif)、HTML/XML、TXT/MD;TXT/MD 直接透传。\n" + "2) PDF/图片:调用 FlashMinerU 的 MineruEngine 批量运行解析。\n" + " - 解析后 Markdown 统一落盘到 intermediate_dir,并按 FlashMinerU 的目录结构组织。\n" + " - 本实现会将引擎返回的 md 文件名映射回对应 dataframe 行,并构造最终 md 绝对路径。\n" + "3) HTML/XML:使用 trafilatura 抽取正文并输出 Markdown 到 intermediate_dir。\n\n" + "初始化参数(__init__):\n" + "- intermediate_dir: 中间产物目录(默认 intermediate)\n" + "- mineru_model_path: FlashMinerU 使用的模型路径(必填;如 MinerU2.5-xxx 权重目录)\n" + "- batch_size: 批处理大小(默认 4)\n" + "- replicas: 引擎副本数(默认 1)\n" + "- num_gpus_per_replica: 每个副本占用 GPU 数(默认 1)\n" + "- engine_gpu_util_rate_to_ray_cap: Ray 资源利用率上限系数(默认 0.9)\n\n" + "运行参数(run):\n" + "- storage: DataFlowStorage,需包含 dataframe\n" + "- input_key: 输入字段名(默认 source),值为本地路径或 URL\n" + "- output_key: 输出字段名(默认 text_path),写入对应行的 Markdown 文件路径\n\n" + "环境依赖:\n" + "- 需安装 flash_mineru 并具备可用 GPU/模型文件;未安装会直接抛错。\n\n" + "输出:\n" + "- 返回 storage.write(...) 的结果路径;并在 dataframe[output_key] 写入解析后的 Markdown 路径(失败为空字符串)。" + ) + else: + return ( + "File/URL to Markdown (FlashMinerU): uses FlashMinerU to batch-parse PDF/images into Markdown and writes Markdown paths back to the DataFrame.\n\n" + "What it does:\n" + "1) Auto-detects input type (local path or URL).\n" + " - URL: if it is a PDF, downloads then parses; otherwise treats it as HTML/XML.\n" + " - Local: supports PDF/images, HTML/XML, TXT/MD; TXT/MD is passed through.\n" + "2) PDF/images: runs FlashMinerU MineruEngine in batch and maps produced Markdown back to dataframe rows.\n" + "3) HTML/XML: extracted by trafilatura and saved as Markdown under intermediate_dir.\n\n" + "__init__ params:\n" + "- intermediate_dir: directory to store generated artifacts\n" + "- mineru_model_path: model path for FlashMinerU (required)\n" + "- batch_size, replicas, num_gpus_per_replica, engine_gpu_util_rate_to_ray_cap: engine tuning params\n\n" + "run params:\n" + "- storage: DataFlowStorage containing a dataframe\n" + "- input_key: column holding local paths or URLs\n" + "- output_key: column to store Markdown file paths\n\n" + "Dependencies:\n" + "- Requires flash_mineru installed and GPU/models available.\n\n" + "Output:\n" + "- Returns the written dataframe path; dataframe[output_key] contains Markdown paths (empty on failure)." + ) + + def _batch_parse_pdf_with_mineru(self, pdf_files: list): + """ + Uses MinerU to parse PDF/image files (pdf/png/jpg/jpeg/webp/gif) into Markdown files. + + Internally, the parsed outputs for each item are stored in a structured directory: + 'intermediate_dir/pdf_name/MinerU_Version[mineru_backend]'. + This directory stores various MinerU parsing outputs, and you can customize + which content to extract based on your needs. + + Args: + raw_file: Input file path, supports .pdf/.png/.jpg/.jpeg/.webp/.gif + output_file: Full path for the output Markdown file + mineru_backend: Sets the backend engine for MinerU. Options include: + - "pipeline": Traditional pipeline processing (MinerU1) + - "vlm-sglang-engine": New engine based on multimodal language models (MinerU2) (default recommended) + Choose the appropriate backend based on your needs. Defaults to "vlm-sglang-engine". + For more details, refer to the MinerU GitHub: https://github.com/opendatalab/MinerU. + + Returns: + output_file: Path to the Markdown file + """ + + try: + import flash_mineru + except ImportError: + raise Exception( + """ + FlashMinerU is not installed in this environment yet. + Please refer to https://github.com/OpenDCAI/Flash-MinerU to install. + Or you can just execute 'pip install flash_mineru'. + Please make sure you have GPU on your machine. + """ + ) + + logger=get_logger() + pdf_path_list = [item["raw_path"] for item in pdf_files] + index_name_dict = {Path(item["raw_path"]).stem: item["index"] for item in pdf_files} + logger.info(f"Running FlashMinerU on {len(pdf_path_list)} files...") + results = self.flash_mineru_engine.run(pdf_path_list) + final_results = [] + # [['bitter_lesson.md', 'crawled_2.md', 'crawled_3.md'], [xxx]] to ['bitter_lesson.md', 'crawled_2.md', 'crawled_3.md'] + for res in results: + final_results.extend(res) + # results = [res[0] for res_list in results for res in res_list] # flatten [[res]] -> [res] + parsed_results = {} + print(final_results) + for res in final_results: + md_path = Path(res) + md_path = os.path.abspath(os.path.join(self.intermediate_dir, md_path.stem, 'vlm', md_path.name)) + parsed_results[index_name_dict[Path(md_path).stem]] = md_path + logger.info(f"Markdown saved to: {md_path}") + + return parsed_results \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/qa_extract.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/qa_extract.py new file mode 100644 index 0000000000000000000000000000000000000000..7c9bd8ce4ac59eeceb124ec9f471c1067e1bb8d9 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/knowledge_cleaning/generate/qa_extract.py @@ -0,0 +1,241 @@ +#!/usr/bin/env python3 +"""QA Extractor - 提取QA对并转换为Alpaca格式""" + +import json +from pathlib import Path +from typing import Optional, List +from dataflow.core import OperatorABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.storage import DataFlowStorage +from dataflow import get_logger +import pandas as pd + +@OPERATOR_REGISTRY.register() +class QAExtractor(OperatorABC): + """ + 从QA_pairs字段提取问答对,转换为Alpaca微调格式 + + Input: QA_pairs (nested structure) + Output: instruction, input, output (Alpaca format) + """ + + def __init__( + self, + output_json_file: Optional[str] = None, + input_instruction: Optional[str] = "Please answer the following question based on the provided information." + ): + self.logger = get_logger() + self.output_json_file = output_json_file + self.instruction = input_instruction + + @staticmethod + def get_desc(lang: str = "zh"): + """获取算子描述""" + if lang == "zh": + return ( + "QA对提取器 - 将嵌套的QA_pairs转换为Alpaca微调格式\n\n" + "核心功能:\n" + "从结构化的QA对数据中提取问答内容,自动整合推理步骤和支持事实,\n" + "输出符合Stanford Alpaca标准的instruction-input-output格式。\n\n" + "初始化参数:\n" + "• output_json_file: 输出JSON文件路径 (可选,不指定则只更新DataFrame)\n" + "• input_instruction: 统一的指令前缀 (默认: 'Please answer the following question...')\n\n" + "运行参数 (input_key):\n" + "• input_qa_key: QA对的字段名 (默认: 'QA_pairs')\n" + "• instruction: 本次运行的具体指令内容 (若不填则使用默认指令)\n" + "输出字段:\n" + "• output_instruction_key: prompt对应的key (若不填则使用默认字段)\n" + "• output_question_key: 问题字段 (若不填则使用默认字段)\n" + "• output_answer_key: 答案字段 (若不填则使用默认字段)\n\n" + "适用场景: 知识库QA微调、领域问答模型训练" + "instruct input output专门适用于llamafactory" + ) + else: # English + return ( + "QA Extractor - Convert nested QA_pairs to Alpaca fine-tuning format\n\n" + "Core Function:\n" + "Extract question-answer pairs from structured data, automatically integrate\n" + "reasoning steps and supporting facts, output in Stanford Alpaca standard\n" + "instruction-input-output format.\n\n" + "Initialization Parameters:\n" + "• output_json_file: Output JSON path (optional, skip to only update DataFrame)\n" + "• input_instruction: Unified instruction prefix (default: 'Please answer...')\n\n" + "Runtime Parameters (input_key):\n" + "• input_qa_key: Field name for QA pairs (default: 'QA_pairs')\n" + "• instruction: Specific instruction for this run (uses default if not provided)\n" + "Output Fields:\n" + "• output_instruction_key: Question as instruction (optional, skip to only update DataFrame)\n" + "• output_question_key: Context information (optional, skip to only update DataFrame)\n" + "• output_answer_key: Answer (optional, skip to only update DataFrame)\n\n" + "Use Cases: Knowledge base QA fine-tuning, domain-specific Q&A training" + ) + + def _parse_fields(self, input_key: Optional[str]) -> Optional[List[str]]: + """解析要包含的字段""" + if input_key is None: + return None # 包含所有 + if isinstance(input_key, list): + return input_key + if isinstance(input_key, str): + return [f.strip() for f in input_key.split(',') if f.strip()] if input_key.strip() else [] + return None + + def _extract_qa(self, row, fields: Optional[List[str]], + key_inst: str, key_q: str, key_a: str) -> List[dict]: + """核心提取逻辑""" + qa_data = row.get(self.qa_key) + if not qa_data:return [] + + # 兼容性处理 + qa_list = qa_data.get('qa_pairs', []) if isinstance(qa_data, dict) else qa_data + if not isinstance(qa_list, list): + qa_list = [qa_list] if isinstance(qa_list, dict) else [] + + results = [] + # 默认字段 + default_fields = ['question', 'reasoning_steps', 'supporting_facts'] + fields = fields if fields is not None else default_fields + + for qa in qa_list: + if not isinstance(qa, dict):continue + + question = qa.get('question', '').strip() + answer = qa.get('answer', '').strip() + if not question or not answer:continue + # 方便下游使用reasoning 暂时删除 + # # --- 1. 构建 Context (input内容) --- + # parts = [] + # for field in fields: + # if field == 'question': + # parts.append(f"Question: {question}") + # elif field == 'reasoning_steps' and qa.get('reasoning_steps'): + # if parts: parts.append("") + # parts.append("Reasoning Process:") + # for i, step in enumerate(qa['reasoning_steps'], 1): + # text = step.get('step', step) if isinstance(step, dict) else str(step) + # if text: parts.append(f"{i}. {text}") + # elif field == 'supporting_facts' and qa.get('supporting_facts'): + # if parts: parts.append("") + # parts.append("Supporting Information:") + # for fact in qa['supporting_facts']: + # text = fact.get('fact', fact) if isinstance(fact, dict) else str(fact) + # if text: parts.append(f"- {text}") + # elif field in qa and qa[field]: + # if parts: parts.append("") + # parts.append(f"{field}: {qa[field]}") + + # --- 2. 组装结果字典 (使用动态 Key) --- + item = { + key_inst: self.instruction, # Instruction 列 + key_q: question, # Question/Input 列 (内容由 fields 决定) + key_a: answer # Answer/Output 列 + } + results.append(item) + return results + + def _load_from_files(self, df): + """从chunk文件加载QA数据""" + path_keys = ['enhanced_chunk_path', 'cleaned_chunk_path', 'chunk_path'] + path_col = next((k for k in path_keys if k in df.columns), None) + + if not path_col: + raise ValueError(f"需要这些字段之一: {path_keys}") + + rows = [] + for _, row in df.iterrows(): + file_path = row[path_col] + if not file_path or not Path(file_path).exists(): + continue + + try: + with open(file_path, 'r', encoding='utf-8') as f: + chunks = json.load(f) + chunks = chunks if isinstance(chunks, list) else [chunks] + + for chunk in chunks: + if self.qa_key in chunk: + rows.append({ + self.qa_key: chunk[self.qa_key], + 'source_file': file_path + }) + except Exception as e: + self.logger.error(f"加载失败 {file_path}: {e}") + + if not rows: + raise ValueError("未找到有效QA数据") + + return pd.DataFrame(rows) + + def run( + self, + storage: DataFlowStorage, + input_qa_key: str = "QA_pairs", + output_instruction_key:Optional[str] = "instruction", + output_question_key: Optional[str] = "input", + output_answer_key: Optional[str] = "output" + ) -> List[str]: + """提取QA对""" + is_modified = False + modified_details = [] + self.qa_key = input_qa_key + + if output_question_key != "question": + is_modified = True + modified_details.append(f"output_question_key -> '{output_question_key}'") + + if output_answer_key != "answer": + is_modified = True + modified_details.append(f"output_answer_key -> '{output_answer_key}'") + + if is_modified: + self.logger.warning( + f"\n{'='*20} ⚠️ Configuration Change Warning {'='*20}\n" + f"Detected changes in output field names: {', '.join(modified_details)}\n\n" + f"Please note the following based on your downstream tasks:\n" + f"1. [SFT / LLaMA-Factory]: If you plan to use LLaMA-Factory directly, DO NOT modify the default keys arbitrarily. " + f"Otherwise, you must manually update the column mapping in 'dataset_info.json'.\n" + f"2. [Pretraining / Downstream]: If connecting to 'ReasoningPretrainFormatConvertGenerator', " + f"ensure you specify the corresponding read keys (input_read_key_question/answer) in the downstream operator.\n" + f"{'='*66}" + ) + self.logger.info("Start extract QA from QA pairs") + + df = storage.read(output_type="dataframe") + + # 如果没有QA_pairs,从文件加载 + if self.qa_key not in df.columns: + df = self._load_from_files(df) + + + # 提取所有QA对 + fields = self._parse_fields(None) + + all_qas = [] + for _, row in df.iterrows(): + qas = self._extract_qa( + row, + fields, + key_inst=output_instruction_key, + key_q=output_question_key, + key_a=output_answer_key + ) + all_qas.extend(qas) + + self.logger.info(f"Extracted {len(all_qas)} QA pairs") + + if not all_qas: + self.logger.warning("No QA pairs found!") + return [output_instruction_key, output_question_key, output_answer_key] + + # 保存JSON(可选) + if self.output_json_file: + output_path = Path(self.output_json_file) + output_path.parent.mkdir(parents=True, exist_ok=True) + with open(output_path, 'w', encoding='utf-8') as f: + json.dump(all_qas, f, indent=2, ensure_ascii=False) + self.logger.info(f"Saved to {output_path}") + + # 写回storage + storage.write(pd.DataFrame(all_qas)) + + return [output_instruction_key, output_question_key, output_answer_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f277bfd456decfa02f231ed3e1d1f2d9ae0fb07b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/__init__.py @@ -0,0 +1,20 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from .generate.mineru_to_llm_input_operator import MinerU2LLMInputOperator + from .generate.llm_output_parser import LLMOutputParser + from .generate.qa_merger import QA_Merger + from .generate.pdf_merger import PDF_Merger + + +else: + import sys + from dataflow.utils.registry import LazyLoader, generate_import_structure_from_type_checking + + + + cur_path = "dataflow/operators/pdf2vqa/" + + + _import_structure = generate_import_structure_from_type_checking(__file__, cur_path) + sys.modules[__name__] = LazyLoader(__name__, "dataflow/operators/pdf2vqa/", _import_structure) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2bd2c279e313847d5f57bdca657dceae94085f5 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/generate/__pycache__/llm_output_parser.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/generate/__pycache__/llm_output_parser.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9400a88a4c650809ef6f51a11e9535551402f07 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/generate/__pycache__/llm_output_parser.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/generate/__pycache__/mineru_to_llm_input_operator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/generate/__pycache__/mineru_to_llm_input_operator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ce5120104563b9ed7bab67dae89d323173f9c40 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/generate/__pycache__/mineru_to_llm_input_operator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/generate/__pycache__/pdf_merger.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/generate/__pycache__/pdf_merger.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9cafedd69827a6a842e9cbb1b0a34b77150d6dc4 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/generate/__pycache__/pdf_merger.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/generate/__pycache__/qa_merger.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/generate/__pycache__/qa_merger.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9008a584da00c711d65462e441643efc0eb67e81 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/generate/__pycache__/qa_merger.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/generate/llm_output_parser.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/generate/llm_output_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..01fb3c44592ff5b00a210db9c52308f4a786df03 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/generate/llm_output_parser.py @@ -0,0 +1,143 @@ +import os +import json +import re +import shutil +from pathlib import Path +from typing import Literal +from dataflow.core import OperatorABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.storage import DataFlowStorage +from dataflow import get_logger + +@OPERATOR_REGISTRY.register() +class LLMOutputParser(OperatorABC): + def __init__(self, + output_dir, + intermediate_dir: str = "intermediate", + ): + self.logger = get_logger() + self.output_dir = output_dir + self.intermediate_dir = intermediate_dir + + @staticmethod + def get_desc(lang: str = "zh") -> str: + if lang == 'zh': + return ( + "LLM输出解析算子。" + "将LLM生成的包含题目和答案ID的响应文本," + "转换为结构化的QA列表,并复制相关图片到输出目录。" + ) + else: + return ( + "LLM output parsing operator." + "Converts LLM-generated response text containing question and answer IDs" + "into a structured QA list and copies related images to the output directory." + ) + + def _id_to_text(self, input_ids, input_json, image_prefix="images"): + texts = [] + id_list = input_ids.replace(' ', '').split(',') + for id in id_list: + try: + int(id) + except Exception: + continue + if int(id) < len(input_json): + try: + item = input_json[int(id)] + except Exception: + continue + if 'text' in item: + texts.append(item['text']) + elif 'img_path' in item: + try: + img_path = item.get('img_path', '') + img_name = os.path.basename(img_path) + new_path = f"{image_prefix}/{img_name}" + texts.append(f"![{' '.join(item.get('image_caption','image'))}]({new_path})") + except Exception: + pass + elif item.get('type','') == 'list': + if item['sub_type'] == 'text': + try: + texts.append(input_json[int(id)]['list_items'].pop(0)) + except Exception: + pass + return '\n'.join(texts) + + def _convert_response(self, input_response, input_json_path, image_prefix="images"): + qa_list = [] + with open(input_json_path, 'r', encoding='utf-8') as infile: + input_json = list(json.load(infile)) + # 提取title + for chapter_block in re.findall(r'(.*?)', input_response, flags=re.DOTALL): + title = re.search(r'(.*?)', chapter_block, flags=re.DOTALL) + if title: + chapter_title = self._id_to_text(title.group(1).strip(), input_json, image_prefix) + else: + chapter_title = "" + # 找出所有 qa_pair 块 + for pair in re.findall(r'(.*?)', chapter_block, flags=re.DOTALL): + # 提取 question 部分 + q_match = re.search(r'(.*?)', pair, flags=re.DOTALL) + # 提取 answer 部分 + a_match = re.search(r'(.*?)', pair, flags=re.DOTALL) + # 提取solution部分 + s_match = re.search(r'(.*?)', pair, flags=re.DOTALL) + # 提取label + label_match = re.search(r'', pair, flags=re.DOTALL) + if not ((q_match and label_match) or (a_match and label_match) or (s_match and label_match)): + continue + label = label_match.group(1).strip() + qa_list.append({ + 'question': self._id_to_text(q_match.group(1).strip(), input_json, image_prefix) if q_match else "", + 'answer': a_match.group(1).strip() if a_match else "", + 'solution': self._id_to_text(s_match.group(1).strip(), input_json, image_prefix) if s_match else "", + 'label': label, + 'chapter_title': chapter_title + }) + return qa_list + + def run(self, storage: DataFlowStorage, + input_response_path_key, + input_converted_layout_path_key, + input_name_key, + output_qalist_path_key, + ): + dataframe = storage.read("dataframe") + + # Response 转换 + for idx, row in dataframe.iterrows(): + converted_json_path = row[input_converted_layout_path_key] + response = Path(row[input_response_path_key]).read_text(encoding='utf-8') + name = row[input_name_key] + + image_prefix = os.path.join(name, f"vqa_images") + qa_list = self._convert_response(response, converted_json_path, image_prefix) + output_qalist_path = os.path.join(self.output_dir, name, f"extracted_vqa.jsonl") + os.makedirs(os.path.dirname(output_qalist_path), exist_ok=True) + with open(output_qalist_path, 'w', encoding='utf-8') as outfile: + for qa in qa_list: + json.dump(qa, outfile, ensure_ascii=False) + outfile.write('\n') + + # 复制图片 + src_dir = os.path.dirname(converted_json_path) + src_images = os.path.join(src_dir, 'vlm', 'images') + if not os.path.exists(src_images): + src_images = os.path.join(src_dir, 'images') + if not os.path.exists(src_images): + raise ValueError(f"Images directory {src_images} not found! There might be a change in Mineru API!") + dst_images = os.path.join(self.output_dir, image_prefix) + + try: + if os.path.exists(src_images): + shutil.copytree(src_images, dst_images) + else: + self.logger.warning(f"Source images dir does not exist: {src_images}") + except Exception as e: + self.logger.warning(f"Failed to copy images from {src_images} to {dst_images}: {e}") + + dataframe.loc[idx, output_qalist_path_key] = output_qalist_path + + storage.write(dataframe) \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/generate/mineru_to_llm_input_operator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/generate/mineru_to_llm_input_operator.py new file mode 100644 index 0000000000000000000000000000000000000000..cc2e21558be3ce12045b51dd83b63413c38e361a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/generate/mineru_to_llm_input_operator.py @@ -0,0 +1,76 @@ +import json +from dataflow.core import OperatorABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.storage import DataFlowStorage + +from pathlib import Path + +@OPERATOR_REGISTRY.register() +class MinerU2LLMInputOperator(OperatorABC): + def __init__(self): + pass + + @staticmethod + def get_desc(lang: str = "zh") -> str: + if lang == 'zh': + return ( + "MinerU格式转换为LLM输入格式算子。" + "将MinerU生成的内容列表JSON文件转换为适合LLM处理的格式," + "包括展平列表项并重新编号。" + ) + else: + return ( + "Convert MinerU format to LLM input format operator." + "Transforms the content list JSON file generated by MinerU into a format suitable for LLM processing," + "including flattening list items and re-indexing." + ) + + def _convert_json(self, input_file, output_file): + with open(input_file, 'r', encoding="utf-8") as infile: + data = list(json.load(infile)) + + new_data = [] + id = 0 + for item in data: + item['id'] = id + item.pop('bbox', None) + item.pop('page_idx', None) + if item.get('type','') == 'list': + if item['sub_type'] == 'text': + for idx, list_item in enumerate(item.get('list_items', [])): + new_item = { + 'type': 'text', + 'text': list_item, + 'id': id + idx, + } + new_data.append(new_item) + id += len(item.get('list_items', [])) + else: + new_data.append(item) + id += 1 + + with open(output_file, 'w', encoding='utf-8') as outfile: + json.dump(new_data, outfile, ensure_ascii=False) + + def run(self, storage: DataFlowStorage, + input_markdown_path_key, + output_converted_layout_key, + ): + dataframe = storage.read("dataframe") + + for index, row in dataframe.iterrows(): + md_path = Path(row[input_markdown_path_key]) + try: + input_json_path = list(md_path.parent.glob("*_content_list.json"))[0] + except Exception: + raise ValueError("No _content_list.json file found in the api result. There might be an error with the Mineru api.") + + converted_path = str(input_json_path).replace('.json', '_converted.json') + self._convert_json(input_json_path, converted_path) + dataframe.at[index, output_converted_layout_key] = converted_path + + with open(converted_path, 'r', encoding='utf-8') as infile: + data = json.load(infile) + assert isinstance(data, list), f"Expected list, got {type(data)} for {input_json_path}" + + storage.write(dataframe) \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/generate/pdf_merger.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/generate/pdf_merger.py new file mode 100644 index 0000000000000000000000000000000000000000..8bbaddc89ed29623d36da4252c3f6df4ad12d580 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/generate/pdf_merger.py @@ -0,0 +1,83 @@ +import os +from pypdf import PdfWriter +from dataflow.core import OperatorABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.storage import DataFlowStorage + +@OPERATOR_REGISTRY.register() +class PDF_Merger(OperatorABC): + def __init__(self, output_dir: str): + """ + 初始化 PDF 合并算子。 + + :param output_dir: 合并后 PDF 文件的存放根目录 + """ + self.output_dir = output_dir + if not os.path.exists(self.output_dir): + os.makedirs(self.output_dir, exist_ok=True) + + @staticmethod + def get_desc(lang: str = "zh") -> str: + if lang == 'zh': + return ( + "PDF 文件合并算子。" + "输入 PDF 路径列表,按顺序合并为一个 PDF 文件," + "并保存到指定目录。" + ) + else: + return ( + "PDF merging operator." + "Takes a list of PDF paths, merges them in order into a single PDF," + "and saves it to the specified directory." + ) + + def run(self, + storage: DataFlowStorage, + input_pdf_list_key: str, + input_name_key: str, + output_pdf_path_key: str + ): + """ + 执行合并逻辑。 + + :param input_pdf_list_key: DataFrame 中存放 PDF 路径列表 (str或list[str]) 的列名 + :param input_name_key: DataFrame 中用于命名的列名(如文件名或ID) + :param output_pdf_path_key: 合并后结果路径存入的列名 + """ + dataframe = storage.read("dataframe") + + for idx, row in dataframe.iterrows(): + pdf_paths = row[input_pdf_list_key] + if isinstance(pdf_paths, str): + pdf_paths = [pdf_paths] + name = row[input_name_key] + + # 构建输出路径:output_dir/name/merged.pdf + save_dir = os.path.join(self.output_dir, str(name)) + os.makedirs(save_dir, exist_ok=True) + output_path = os.path.join(save_dir, f"{name}_merged.pdf") + + try: + merger = PdfWriter() + valid_count = 0 + + for path in pdf_paths: + if os.path.exists(path): + merger.append(path) + valid_count += 1 + + if valid_count > 0: + with open(output_path, "wb") as f: + merger.write(f) + merger.close() + + # 将结果写回 dataframe + dataframe.loc[idx, output_pdf_path_key] = output_path + else: + dataframe.loc[idx, output_pdf_path_key] = None + + except Exception as e: + print(f"Error merging PDFs for {name}: {e}") + dataframe.loc[idx, output_pdf_path_key] = None + + storage.write(dataframe) \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/generate/qa_merger.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/generate/qa_merger.py new file mode 100644 index 0000000000000000000000000000000000000000..d4b9969e9be39059ba088929d2bfec9bf1960a66 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/pdf2vqa/generate/qa_merger.py @@ -0,0 +1,64 @@ +import os +import json +from dataflow.core import OperatorABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.pdf2vqa.format_utils import merge_qa_pair, jsonl_to_md + +@OPERATOR_REGISTRY.register() +class QA_Merger(OperatorABC): + def __init__(self, output_dir, strict_title_match=False): + self.output_dir = output_dir + self.strict_title_match = strict_title_match + + @staticmethod + def get_desc(lang: str = "zh") -> str: + if lang == 'zh': + return ( + "QA对合并算子。" + "将问题和答案的QA列表进行合并,生成最终的QA对文件," + "并转换为Markdown格式。" + ) + else: + return ( + "QA pair merging operator." + "Merges question and answer QA lists to generate final QA pair files," + "and converts them to Markdown format." + ) + + def run(self, storage: DataFlowStorage, + input_qalist_path_key, + input_name_key, + output_merged_qalist_path_key, + output_merged_md_path_key, + output_qa_item_key="qa_item" # 新增:展开后的 QA 内容列名 + ): + dataframe = storage.read("dataframe") + + # 为了能存储 list 对象,先初始化该列为 object 类型 + dataframe[output_qa_item_key] = None + dataframe[output_qa_item_key] = dataframe[output_qa_item_key].astype(object) + + for idx, row in dataframe.iterrows(): + qa_list_path = row[input_qalist_path_key] + name = row[input_name_key] + + output_merged_qalist_path = os.path.join(self.output_dir, name, "merged_qa_pairs.jsonl") + merge_qa_pair(qa_list_path, output_merged_qalist_path, strict_title_match=self.strict_title_match) + + output_merged_md_path = os.path.join(self.output_dir, name, "merged_qa_pairs.md") + jsonl_to_md(output_merged_qalist_path, output_merged_md_path) + + qa_pairs = [] + if os.path.exists(output_merged_qalist_path): + with open(output_merged_qalist_path, 'r', encoding='utf-8') as f: + qa_pairs = [json.loads(line) for line in f] + + dataframe.at[idx, output_qa_item_key] = qa_pairs + + dataframe.loc[idx, output_merged_qalist_path_key] = output_merged_qalist_path + dataframe.loc[idx, output_merged_md_path_key] = output_merged_md_path + + dataframe = dataframe.explode(output_qa_item_key).reset_index(drop=True) + + storage.write(dataframe) \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bf307f4aac4677d130b6466dd734f3a4c7973217 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/__init__.py @@ -0,0 +1,36 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + # generate + from .generate.reasoning_answer_generator import ReasoningAnswerGenerator + from .generate.reasoning_question_generator import ReasoningQuestionGenerator + from .generate.reasoning_answer_extraction_qwenmatheval_generator import ReasoningAnswerExtractionQwenMathEvalGenerator + from .generate.reasoning_pseudo_answer_generator import ReasoningPseudoAnswerGenerator + from .generate.reasoning_pretrain_format_convert_generator import ReasoningPretrainFormatConvertGenerator + from .generate.reasoning_question_fusion_generator import ReasoningQuestionFusionGenerator + + # eval + from .eval.reasoning_category_dataset_evaluator import ReasoningCategoryDatasetEvaluator + from .eval.reasoning_difficulty_dataset_evaluator import ReasoningDifficultyDatasetEvaluator + from .eval.reasoning_token_dataset_evaluator import ReasoningTokenDatasetEvaluator + from .eval.reasoning_question_category_sample_evaluator import ReasoningQuestionCategorySampleEvaluator + from .eval.reasoning_question_difficulty_sample_evaluator import ReasoningQuestionDifficultySampleEvaluator + from .eval.reasoning_question_solvable_sample_evaluator import ReasoningQuestionSolvableSampleEvaluator + + # filter + from .filter.reasoning_answer_formatter_filter import ReasoningAnswerFormatterFilter + from .filter.reasoning_answer_groundtruth_filter import ReasoningAnswerGroundTruthFilter + from .filter.reasoning_answer_ngram_filter import ReasoningAnswerNgramFilter + from .filter.reasoning_answer_pipeline_root_filter import ReasoningAnswerPipelineRootFilter + from .filter.reasoning_answer_token_length_filter import ReasoningAnswerTokenLengthFilter + from .filter.reasoning_question_filter import ReasoningQuestionFilter + from .filter.reasoning_answer_model_judge_filter import ReasoningAnswerModelJudgeFilter + +else: + import sys + from dataflow.utils.registry import LazyLoader, generate_import_structure_from_type_checking + + cur_path = "dataflow/operators/reasoning/" + + _import_structure = generate_import_structure_from_type_checking(__file__, cur_path) + sys.modules[__name__] = LazyLoader(__name__, "dataflow/operators/reasoning/", _import_structure) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dcc181747ca460620be30f8ea31eb1751a3252ef Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/__pycache__/reasoning_category_dataset_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/__pycache__/reasoning_category_dataset_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d12c2ed2875ebc28da4377d9670b5770d92f5f0d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/__pycache__/reasoning_category_dataset_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/__pycache__/reasoning_difficulty_dataset_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/__pycache__/reasoning_difficulty_dataset_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b0cec9f646e50c6bf0179263cd07adc77c4dc32 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/__pycache__/reasoning_difficulty_dataset_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/__pycache__/reasoning_question_category_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/__pycache__/reasoning_question_category_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8b0955105ac37f70b0bf7cf114a8ef425030dab Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/__pycache__/reasoning_question_category_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/__pycache__/reasoning_question_difficulty_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/__pycache__/reasoning_question_difficulty_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d3fcf627764ff40db08d3f7e0414eb6caa9cc18 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/__pycache__/reasoning_question_difficulty_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/__pycache__/reasoning_question_solvable_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/__pycache__/reasoning_question_solvable_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..097bd145a44e37d06087e0161b4de6ebda60af4c Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/__pycache__/reasoning_question_solvable_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/__pycache__/reasoning_token_dataset_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/__pycache__/reasoning_token_dataset_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac8ebe2cc114a695d9cc0e1d55621722284799d2 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/__pycache__/reasoning_token_dataset_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/reasoning_category_dataset_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/reasoning_category_dataset_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..0d0c54d54fd031d9019dd1e273c0234a5226c4ae --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/reasoning_category_dataset_evaluator.py @@ -0,0 +1,80 @@ +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.reasoning.CategoryFuzz import CategoryUtils +import pandas as pd + + +@OPERATOR_REGISTRY.register() +class ReasoningCategoryDatasetEvaluator(OperatorABC): + def __init__(self): + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.logger.info(f'{self.__class__.__name__} initialized.') + self.information_name = "Category Information" + self.category_list = CategoryUtils().secondary_categories + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于统计数据集中的类别信息,包括主类别和次类别的分布情况。" + "它计算每个类别的样本数量,并返回类别分布的统计结果。\n" + "输入参数:\n" + "- input_primary_category_key:主类别字段名,默认为'primary_category'\n" + "- input_secondary_category_key:次类别字段名,默认为'secondary_category'\n" + "输出参数:\n" + "- 返回包含类别统计信息的字典,主类别作为键,值为包含该类别样本数量和次类别分布的字典" + ) + elif lang == "en": + return ( + "This operator analyzes category distribution in the dataset, including primary and secondary categories. " + "It counts the number of samples in each category and returns statistical results of category distribution.\n" + "Input Parameters:\n" + "- input_primary_category_key: Field name for primary category, default is 'primary_category'\n" + "- input_secondary_category_key: Field name for secondary category, default is 'secondary_category'\n\n" + "Output Parameters:\n" + "- Returns a dictionary containing category statistics, with primary categories as keys and values as dictionaries " + "containing sample counts and secondary category distribution" + ) + else: + return ( + "CategoryInfo analyzes and reports the distribution of primary and secondary categories in the dataset." + ) + + def get_category_info(self, samples, input_primary_category_key = "primary_category", input_secondary_category_key = "secondary_category"): + primary_categories = [sample.get(input_primary_category_key, '') for sample in samples] + secondary_categories = [sample.get(input_secondary_category_key, '') for sample in samples] + primary_categories_count = pd.Series(primary_categories).value_counts().to_dict() + secondary_categories_count = pd.Series(secondary_categories).value_counts().to_dict() + + output = [] + for primary in self.category_list: + js = {} + if primary not in primary_categories_count: + continue + js["primary_num"] = primary_categories_count[primary] + for secondary in self.category_list[primary]: + if secondary not in secondary_categories_count: + continue + js[secondary] = secondary_categories_count[secondary] + output[primary] = js + self.logger.info(f"Category information: {output}") + return output + + + + + + def run(self,storage: DataFlowStorage, input_primary_category_key: str = "primary_category", input_secondary_category_key: str = "secondary_category"): + self.input_primary_category_key = input_primary_category_key + self.input_secondary_category_key = input_secondary_category_key + dataframe = storage.read("dataframe") + if self.input_primary_category_key not in dataframe.columns or self.input_secondary_category_key not in dataframe.columns: + self.logger.error(f"Input keys {self.input_primary_category_key} or {self.input_secondary_category_key} not found in dataframe columns.") + return {} + samples = dataframe.to_dict(orient='records') + category_info = self.get_category_info(samples, self.input_primary_category_key, self.input_secondary_category_key) + return category_info + \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/reasoning_difficulty_dataset_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/reasoning_difficulty_dataset_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..0a3c48e9f5c5b710128724b5fce97c4701244b16 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/reasoning_difficulty_dataset_evaluator.py @@ -0,0 +1,61 @@ +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +import pandas as pd + + +@OPERATOR_REGISTRY.register() +class ReasoningDifficultyDatasetEvaluator(OperatorABC): + def __init__(self): + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.logger.info(f'{self.__class__.__name__} initialized.') + self.information_name = "Difficulty Information" + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于统计数据集中的难度信息,计算不同难度级别的样本数量分布。" + "它统计每个难度级别的样本数量,并返回难度分布的统计结果。\n" + "输入参数:\n" + "- input_diffulty_key:难度分数字段名,默认为'difficulty_score'\n" + "输出参数:\n" + "- 返回包含难度统计信息的字典,难度级别作为键,值为该难度级别的样本数量" + ) + elif lang == "en": + return ( + "This operator analyzes difficulty distribution in the dataset, calculating the number of samples at different difficulty levels. " + "It counts samples at each difficulty level and returns statistical results of difficulty distribution.\n" + "Input Parameters:\n" + "- input_diffulty_key: Field name for difficulty score, default is 'difficulty_score'\n\n" + "Output Parameters:\n" + "- Returns a dictionary containing difficulty statistics, with difficulty levels as keys and sample counts as values" + ) + else: + return ( + "DifficultyInfo analyzes and reports the distribution of difficulty levels in the dataset." + ) + + def get_category_info(self, samples, input_diffulty_key="difficulty_score"): + diffultys = [sample.get(input_diffulty_key, 'null') for sample in samples] + diffultys_count = pd.Series(diffultys).value_counts().to_dict() + self.logger.info(f"Difficulty information: {diffultys_count}") + return diffultys_count + + + + + + + def run(self,storage: DataFlowStorage, input_diffulty_key: str = "difficulty_score"): + self.input_diffulty_key = input_diffulty_key + dataframe = storage.read("dataframe") + if self.input_diffulty_key not in dataframe.columns: + self.logger.error(f"Input key {self.input_diffulty_key} not found in dataframe columns.") + return {} + samples = dataframe.to_dict(orient='records') + category_info = self.get_category_info(samples, self.input_diffulty_key) + return category_info + \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/reasoning_question_category_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/reasoning_question_category_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..e6ffdbc63220b65078acdaf498575cfa987fe129 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/reasoning_question_category_sample_evaluator.py @@ -0,0 +1,119 @@ +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core.prompt import prompt_restrict +from dataflow.utils.reasoning.CategoryFuzz import CategoryUtils +from dataflow.core import LLMServingABC +from dataflow.prompts.reasoning.math import MathQuestionCategoryPrompt + +import pandas as pd +import json +import re +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger + +@prompt_restrict( + MathQuestionCategoryPrompt +) + +@OPERATOR_REGISTRY.register() +class ReasoningQuestionCategorySampleEvaluator(OperatorABC): + def __init__(self, llm_serving: LLMServingABC = None): + """ + Initialize the ReasoningCategoryDatasetEvaluator with the provided configuration. + """ + self.logger = get_logger() + self.prompts = MathQuestionCategoryPrompt() + self.llm_serving = llm_serving + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于对用户问题进行多级分类(主分类和子分类)。" + "通过大语言模型对输入问题进行语义分析,输出分类编码结果。\n\n" + "输入参数:\n" + "- db_port/db_name/table_name:数据库连接参数(存储模式)\n" + "- input_file/output_file:文件路径(文件模式)\n" + "- input_key:输入数据中问题字段的键名\n" + "- generator_type:模型调用方式(aisuite/request)\n\n" + "输出参数:\n" + "- classification_result:包含主分类和子分类的编码结果" + ) + elif lang == "en": + return ( + "Performs hierarchical classification (primary and secondary) on user questions. " + "Utilizes LLM for semantic analysis and outputs category codes.\n\n" + "Input Parameters:\n" + "- db_port/db_name/table_name: Database connection params (storage mode)\n" + "- input_file/output_file: File paths (file mode)\n" + "- input_key: Key for question field in input data\n" + "- generator_type: Model invocation method (aisuite/request)\n\n" + "Output Parameters:\n" + "- classification_result: Combined category code" + ) + + def _validate_dataframe(self, dataframe: pd.DataFrame): + required_keys = [self.input_key] + forbidden_keys = [self.output_key] + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + raise ValueError(f"Missing required column(s): {missing}") + if conflict: + raise ValueError(f"The following column(s) already exist and would be overwritten: {conflict}") + + def _reformat_prompt(self, dataframe): + """ + Reformat the prompts in the dataframe to generate questions. + """ + # Check if input_key is in the dataframe + formatted_prompts = [] + for text in dataframe[self.input_key]: + used_prompt = self.prompts.build_prompt(text) + formatted_prompts.append(used_prompt.strip()) + + return formatted_prompts + + def run(self, storage: DataFlowStorage, input_key:str = "instruction", output_key:str="question_category") -> None: + """ + Run the question category classification process. + """ + self.input_key, self.output_key = input_key, output_key + dataframe = storage.read("dataframe") + self._validate_dataframe(dataframe) + formatted_prompts = self._reformat_prompt(dataframe) + responses = self.llm_serving.generate_from_input(formatted_prompts) + + for (idx, row), classification_str in zip(dataframe.iterrows(), responses): + try: + if not classification_str: + raise ValueError("空字符串") + + # 去除 Markdown 代码块包裹 + cleaned_str = re.sub(r"^```json\s*|\s*```$", "", classification_str.strip(), flags=re.DOTALL) + + # 去除非 ASCII 字符(可选) + cleaned_str = re.sub(r"[^\x00-\x7F]+", "", cleaned_str) + + classification = json.loads(cleaned_str) + + primary_raw = classification.get("primary_category", "") + secondary_raw = classification.get("secondary_category", "") + + category_info = CategoryUtils().normalize_categories(raw_primary=primary_raw, raw_secondary=secondary_raw) + + dataframe.at[idx, "primary_category"] = category_info["primary_category"] + dataframe.at[idx, "secondary_category"] = category_info["secondary_category"] + + except json.JSONDecodeError: + self.logger.warning(f"[警告] JSON 解析失败,收到的原始数据: {repr(classification_str)}") + except Exception as e: + self.logger.error(f"[错误] 解析分类结果失败: {e}") + self.logger.debug(f"[DEBUG] 原始字符串:{repr(classification_str)}") + + output_file = storage.write(dataframe) + self.logger.info(f"Classification results saved to {output_file}") + + return ["primary_category", "secondary_category"] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/reasoning_question_difficulty_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/reasoning_question_difficulty_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..b712ce6db951c88c43f00baee11747e0ff21b64c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/reasoning_question_difficulty_sample_evaluator.py @@ -0,0 +1,110 @@ +from dataflow.prompts.reasoning.math import MathQuestionDifficultyPrompt +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.core.prompt import prompt_restrict +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC + +import pandas as pd +import re + +@prompt_restrict( + MathQuestionDifficultyPrompt +) + +@OPERATOR_REGISTRY.register() +class ReasoningQuestionDifficultySampleEvaluator(OperatorABC): + def __init__(self, llm_serving: LLMServingABC = None): + """ + Initialize the ReasoningCategoryDatasetEvaluator with the provided configuration. + """ + self.logger = get_logger() + self.prompts = MathQuestionDifficultyPrompt() + self.llm_serving = llm_serving + + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于评估问题的难度等级。" + "通过大语言模型分析问题复杂度,输出1-10级的难度评分。\n\n" + "输入参数:\n" + "- eval_stage:评估阶段标识\n" + "- read_min/max_score:分数过滤阈值\n" + "- 其他参数同ReasoningCategoryDatasetEvaluator\n\n" + "输出参数:\n" + "- difficulty_score:数值型难度评分(1-10)" + ) + elif lang == "en": + return ( + "Evaluates question difficulty level using LLM analysis. " + "Outputs numerical difficulty score from 1 to 10.\n\n" + "Input Parameters:\n" + "- eval_stage: Evaluation stage identifier\n" + "- read_min/max_score: Score filtering thresholds\n" + "- Other params same as ReasoningCategoryDatasetEvaluator\n\n" + "Output Parameters:\n" + "- difficulty_score: Numerical difficulty rating (1-10)" + ) + + def _validate_dataframe(self, dataframe: pd.DataFrame, input_key: str = "instruction", output_key: str = "difficulty_score"): + required_keys = [self.input_key] + forbidden_keys = [self.output_key] + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + raise ValueError(f"Missing required column(s): {missing}") + if conflict: + raise ValueError(f"The following column(s) already exist and would be overwritten: {conflict}") + + + def _reformat_prompt(self, dataframe, input_key: str = "instruction") -> list: + """ + Reformat the prompts in the dataframe to generate questions. + """ + formatted_prompts = [] + for i, text in enumerate(dataframe[input_key]): + if text is not None: + used_prompt = self.prompts.build_prompt(text) + else: + used_prompt = None + formatted_prompts.append(used_prompt.strip()) + + return formatted_prompts + + def run(self, storage:DataFlowStorage, input_key: str, output_key:str="difficulty_score") -> None: + """ + Run the question difficulty classification process. + """ + self.input_key, self.output_key = input_key, output_key + dataframe = storage.read("dataframe") + self._validate_dataframe( + dataframe, + input_key=self.input_key, + output_key=self.output_key + ) + formatted_prompts = self._reformat_prompt(dataframe, input_key=self.input_key) + responses = self.llm_serving.generate_from_input(user_inputs=formatted_prompts) + + rating_scores = [] + for response in responses: + match = re.search(r'Rating:\s*((\d+\.\d+)|\d+)', response) + if match: + score_str = match.group(1).rstrip('.') + try: + score = float(score_str) + except ValueError: + score = -1 + else: + score = -1 + rating_scores.append(score) + dataframe[output_key] = rating_scores + + output_file = storage.write(dataframe) + self.logger.info(f"Classification results saved to {output_file}") + + return [output_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/reasoning_question_solvable_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/reasoning_question_solvable_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..8b0db447903a3409f0f27c3f102f3922f7aa6f79 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/reasoning_question_solvable_sample_evaluator.py @@ -0,0 +1,90 @@ +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core.prompt import prompt_restrict, DIYPromptABC +from dataflow.core import LLMServingABC +from dataflow.prompts.reasoning.math import MathQuestionEvaluatorPrompt +from typing import Union + +import pandas as pd +import json +import re +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger + +@prompt_restrict( + MathQuestionEvaluatorPrompt +) + +@OPERATOR_REGISTRY.register() +class ReasoningQuestionSolvableSampleEvaluator(OperatorABC): + def __init__(self, llm_serving: LLMServingABC = None, prompt_template: Union[MathQuestionEvaluatorPrompt, DIYPromptABC] = None): + """ + Initialize the ReasoningCategoryDatasetEvaluator with the provided configuration. + """ + self.logger = get_logger() + if prompt_template is None: + prompt_template = MathQuestionEvaluatorPrompt() + self.prompt_template = prompt_template + self.llm_serving = llm_serving + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于对用户问题进行多级分类(主分类和子分类)。" + "通过大语言模型对输入问题进行语义分析,输出分类编码结果。\n\n" + "输入参数:\n" + "- db_port/db_name/table_name:数据库连接参数(存储模式)\n" + "- input_file/output_file:文件路径(文件模式)\n" + "- input_key:输入数据中问题字段的键名\n" + "- generator_type:模型调用方式(aisuite/request)\n\n" + "输出参数:\n" + "- classification_result:包含主分类和子分类的编码结果" + ) + elif lang == "en": + return ( + "Performs hierarchical classification (primary and secondary) on user questions. " + "Utilizes LLM for semantic analysis and outputs category codes.\n\n" + "Input Parameters:\n" + "- db_port/db_name/table_name: Database connection params (storage mode)\n" + "- input_file/output_file: File paths (file mode)\n" + "- input_key: Key for question field in input data\n" + "- generator_type: Model invocation method (aisuite/request)\n\n" + "Output Parameters:\n" + "- classification_result: Combined category code" + ) + + def _validate_dataframe(self, dataframe: pd.DataFrame): + required_keys = [self.input_key] + forbidden_keys = [self.output_key] + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + raise ValueError(f"Missing required column(s): {missing}") + if conflict: + raise ValueError(f"The following column(s) already exist and would be overwritten: {conflict}") + + def _reformat_prompt(self, dataframe): + problem = dataframe[self.input_key].tolist() + system_prompt = self.prompt_template.build_system_prompt() + prompts = [self.prompt_template.build_prompt(p) for p in problem] + + return system_prompt, prompts + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str): + """ + Run the question generation process. + """ + self.input_key, self.output_key = input_key, output_key + dataframe = storage.read("dataframe") + self._validate_dataframe(dataframe) + + sys_prompts, user_prompts = self._reformat_prompt(dataframe) + responses = self.llm_serving.generate_from_input(user_prompts, sys_prompts) + dataframe[f"{output_key}"] = responses + self.logger.info(f"Generated questions for {output_key}") + + output_file = storage.write(dataframe) + self.logger.info(f"Generated questions saved to {output_file}") \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/reasoning_token_dataset_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/reasoning_token_dataset_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..3bb478cfe86575ff3c01a0444c8638c5429ef7e5 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/eval/reasoning_token_dataset_evaluator.py @@ -0,0 +1,95 @@ +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +import pandas as pd +from transformers import AutoTokenizer + +@OPERATOR_REGISTRY.register() +class ReasoningTokenDatasetEvaluator(OperatorABC): + def __init__(self, model_name_or_path: str): + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.logger.info(f'{self.__class__.__name__} initialized.') + self.information_name = "Token Information" + self.model_name_or_path = model_name_or_path + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于统计数据集中问题和回答的token信息,包括token数量的最小值、最大值、平均值和中位数等统计指标。" + "它使用指定的tokenizer对文本进行编码,并计算token长度的分布情况。\n" + "输入参数:\n" + "- input_question_key:问题文本字段名\n" + "- input_answer_key:回答文本字段名\n" + "- model_name_or_path:tokenizer模型名称或路径\n" + "输出参数:\n" + "- 返回包含token统计信息的字典,包括问题和回答的token数量的零值计数、最小值、最大值、平均值和中位数" + ) + elif lang == "en": + return ( + "This operator analyzes token information for questions and answers in the dataset, including statistical metrics " + "such as minimum, maximum, mean, and median token counts. It encodes text using the specified tokenizer and calculates " + "token length distribution.\n" + "Input Parameters:\n" + "- input_question_key: Field name for question text\n" + "- input_answer_key: Field name for answer text\n" + "- model_name_or_path: Tokenizer model name or path\n\n" + "Output Parameters:\n" + "- Returns a dictionary containing token statistics, including zero count, minimum, maximum, mean, and median token counts " + "for both questions and answers" + ) + else: + return ( + "ToKenInfo analyzes and reports token length statistics for questions and answers in the dataset using a specified tokenizer." + ) + + def get_token_info(self, samples, input_question_key, input_answer_key, model_name_or_path): + tokenizer = AutoTokenizer.from_pretrained(model_name_or_path) + questions = [sample.get(input_question_key, '') or '' for sample in samples] + answers = [sample.get(input_answer_key, '') or '' for sample in samples] + + questions_tokens_length = [len(tokenizer.encode(question, add_special_tokens=False)) for question in questions] + answers_tokens_length = [len(tokenizer.encode(answer, add_special_tokens=False)) for answer in answers] + + # count zeros in questions_tokens_length and answers_tokens_length + questions_zeros_count = questions_tokens_length.count(0) + answers_zeros_count = answers_tokens_length.count(0) + + # count min,max,mean, median of questions_tokens_length and answers_tokens_length + questions_min = min(questions_tokens_length) if questions_tokens_length else 0 + questions_max = max(questions_tokens_length) if questions_tokens_length else 0 + questions_mean = sum(questions_tokens_length) / len(questions_tokens_length) if questions_tokens_length else 0 + questions_median = sorted(questions_tokens_length)[len(questions_tokens_length) // 2] if questions_tokens_length else 0 + answers_min = min(answers_tokens_length) if answers_tokens_length else 0 + answers_max = max(answers_tokens_length) if answers_tokens_length else 0 + answers_mean = sum(answers_tokens_length) / len(answers_tokens_length) if answers_tokens_length else 0 + answers_median = sorted(answers_tokens_length)[len(answers_tokens_length) // 2] if answers_tokens_length else 0 + token_info = { + "questions_zeros_count": questions_zeros_count, + "answers_zeros_count": answers_zeros_count, + "questions_min": questions_min, + "questions_max": questions_max, + "questions_mean": questions_mean, + "questions_median": questions_median, + "answers_min": answers_min, + "answers_max": answers_max, + "answers_mean": answers_mean, + "answers_median": answers_median + } + self.logger.info(f"Token information: {token_info}") + return token_info + + def run(self,storage: DataFlowStorage, input_question_key: str, input_answer_key: str): + self.input_question_key = input_question_key + self.input_answer_key = input_answer_key + dataframe = storage.read("dataframe") + if self.input_question_key not in dataframe.columns: + self.logger.error(f"Input key {self.input_question_key} not found in dataframe columns.") + return {} + if self.input_answer_key not in dataframe.columns: + self.logger.warning(f"Input key {self.input_answer_key} not found in dataframe columns") + samples = dataframe.to_dict(orient='records') + token_info = self.get_token_info(samples, self.input_question_key, self.input_answer_key, self.model_name_or_path) + return token_info \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/__pycache__/reasoning_answer_formatter_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/__pycache__/reasoning_answer_formatter_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..014982a6809b59e2d8ab2fb88122c2724286a40f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/__pycache__/reasoning_answer_formatter_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/__pycache__/reasoning_answer_groundtruth_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/__pycache__/reasoning_answer_groundtruth_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea0b2f57c0467bda5d4d6452634bc59aa0e99ae2 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/__pycache__/reasoning_answer_groundtruth_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/__pycache__/reasoning_answer_model_judge_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/__pycache__/reasoning_answer_model_judge_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8313c8ade77e512176da82c4597437a337b275b6 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/__pycache__/reasoning_answer_model_judge_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/__pycache__/reasoning_answer_ngram_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/__pycache__/reasoning_answer_ngram_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f810c02cf5502116d90d3775c5288f335831eda8 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/__pycache__/reasoning_answer_ngram_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/__pycache__/reasoning_answer_pipeline_root_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/__pycache__/reasoning_answer_pipeline_root_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..460461f7e527c00401367016b5b9a10e17ae25c4 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/__pycache__/reasoning_answer_pipeline_root_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/__pycache__/reasoning_answer_token_length_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/__pycache__/reasoning_answer_token_length_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4469302299625467abc5c0d37b726bc1238ae61f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/__pycache__/reasoning_answer_token_length_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/__pycache__/reasoning_question_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/__pycache__/reasoning_question_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69dcce320c85a0cf7f026559d154afb5e99407e2 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/__pycache__/reasoning_question_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/reasoning_answer_formatter_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/reasoning_answer_formatter_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..ce8b776ada4d8e9a4f1e62a288014cfc26e8f3dd --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/reasoning_answer_formatter_filter.py @@ -0,0 +1,82 @@ +import numpy as np +import pandas as pd +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger + +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC + +@OPERATOR_REGISTRY.register() +class ReasoningAnswerFormatterFilter(OperatorABC): + def __init__(self): + + self.logger = get_logger() + + def is_valid_answer(answer: str) -> bool: + # check final answer in \boxed{} or not + # if not re.search(r'\\boxed{.*}', answer): + # return False + return True + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于检查答案格式是否符合规范,主要验证数学答案是否包含正确的\\boxed{}标记。\n\n" + "输入参数:\n" + "- input_key:输入字段名\n" + "- result_key:结果字段名\n\n" + "输出参数:\n" + "- 通过格式检查返回1,否则返回0" + ) + elif lang == "en": + return ( + "This operator validates answer formatting, specifically checking for correct \\boxed{} notation.\n\n" + "Input Parameters:\n" + "- input_key: Field name containing the answer\n" + "- result_key: Output result field name\n\n" + "Output Parameters:\n" + "- Returns 1 for valid format, 0 otherwise" + ) + else: + return "AnswerFormatterFilter validates mathematical answer formatting" + + def _validate_dataframe(self, dataframe: pd.DataFrame): + required_keys = [self.input_key] + forbidden_keys = [] + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + self.logger.error(f"Missing required column(s): {missing}") + if conflict: + self.logger.error(f"The following column(s) already exist and would be overwritten: {conflict}") + missing_keys = [key for key in required_keys if key not in dataframe.columns] + + if missing_keys: + self.logger.error(f"The following required columns are missing from the dataframe: {missing_keys}") + + def run( + self, + storage:DataFlowStorage, + input_key: str = "generated_cot", + ) -> list: + ''' + Execute the answer format filter process + ''' + self.input_key = input_key + dataframe = storage.read("dataframe") + self._validate_dataframe(dataframe) + + indexes = np.zeros(len(dataframe)).astype(int) + for i, item in dataframe.iterrows(): + answer = item[self.input_key] + if ReasoningAnswerFormatterFilter.is_valid_answer(answer): + indexes[i] = 1 + dataframe = dataframe[np.array(indexes) == 1] + + output_file = storage.write(dataframe) + self.logger.info(f"Results saved to {output_file}") + + return [self.input_key,] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/reasoning_answer_groundtruth_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/reasoning_answer_groundtruth_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..46d67b949e90ddf6b0bc34503e962419ba15b72b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/reasoning_answer_groundtruth_filter.py @@ -0,0 +1,86 @@ +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.reasoning.AnswerExtraction import StringCleaner, UnitTextManager, AnswerExtractor +from dataflow.utils.storage import DataFlowStorage +from dataflow import get_logger +from dataflow.core import OperatorABC +from typing import Literal +from math_verify import parse, verify +import pandas as pd + +@OPERATOR_REGISTRY.register() +class ReasoningAnswerGroundTruthFilter(OperatorABC): + def __init__(self, + compare_method: Literal["math_verify", "exact"] = "math_verify"): + + name2compare = { + 'exact': self.exact_compare, + 'math_verify': self.math_verify_compare + } + self.compare = name2compare[compare_method] + unit_manager = UnitTextManager() + string_cleaner = StringCleaner(unit_manager) + self.answer_extractor = AnswerExtractor(string_cleaner) + + self.logger = get_logger() + + def exact_compare(self, answer, ground_truth): + return str(answer) == str(ground_truth) + + def math_verify_compare(self, answer, ground_truth): + try: + return verify(parse(str(ground_truth)), parse(str(answer))) + except Exception: + try: + return verify(parse(ground_truth), parse(answer)) + except Exception: + return False + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于对比预测答案与标准答案的匹配度,支持精确匹配和数学验证两种方式。\n\n" + "输入参数:\n" + "- input_test_answer_key:预测答案字段名\n" + "- input_gt_answer_key:标准答案字段名\n" + "- compare_method:比较方法(exact/math_verify)\n\n" + "输出参数:\n" + "- 匹配成功返回1,否则返回0" + ) + elif lang == "en": + return ( + "This operator compares predicted answers against ground truth using exact or mathematical verification.\n\n" + "Input Parameters:\n" + "- test_answer_key: Predicted answer field\n" + "- gt_answer_key: Ground truth field\n" + "- compare_method: Comparison method (exact/math_verify)\n\n" + "Output Parameters:\n" + "- Returns 1 for matches, 0 otherwise" + ) + else: + return "AnswerGroundTruthFilter performs answer validation" + + def run( + self, + storage:DataFlowStorage, + input_test_answer_key: str = "generated_cot", + input_gt_answer_key: str = "golden_answer" + ) -> list: + + self.test_answer_key = input_test_answer_key + self.gt_answer_key = input_gt_answer_key + + dataframe = storage.read("dataframe") + output = [] + answers = dataframe[self.test_answer_key] + ground_truths = dataframe[self.gt_answer_key] + for i in range(len(answers)): + final_answer = self.answer_extractor.extract_answer(answers[i], None) + if self.compare(final_answer, ground_truths[i]): + output.append(dataframe.iloc[i]) + output = pd.DataFrame(output) + + output_file = storage.write(output) + self.logger.info(f"Filtered data saved to {output_file}") + + return [self.test_answer_key, self.gt_answer_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/reasoning_answer_model_judge_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/reasoning_answer_model_judge_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..28d454577f2e456e23b7ae534aa053cd8ba71c44 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/reasoning_answer_model_judge_filter.py @@ -0,0 +1,183 @@ +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import LLMServingABC +from dataflow.prompts.model_evaluation.general import AnswerJudgePromptQuestion, AnswerJudgePrompt +from dataflow.core.prompt import prompt_restrict, DIYPromptABC + +import re +import pandas as pd +import numpy as np +from typing import Union + +@prompt_restrict( + AnswerJudgePromptQuestion, + AnswerJudgePrompt, +) + +@OPERATOR_REGISTRY.register() +class ReasoningAnswerModelJudgeFilter(OperatorABC): + def __init__(self, + system_prompt: str = "You are a helpful assistant specialized in evaluating answer correctness.", + llm_serving: LLMServingABC = None, + prompt_template: Union[AnswerJudgePromptQuestion,AnswerJudgePrompt, DIYPromptABC] = AnswerJudgePromptQuestion, + keep_all_samples: bool = False, # 新增参数,控制是否保留所有样本 + ): + + self.logger = get_logger() + + if prompt_template is None: + prompt_template = AnswerJudgePrompt() + self.prompt_template = prompt_template + self.system_prompt = system_prompt + self.llm_serving = llm_serving + self.empty_responses_count = 0 # 添加空响应计数器 + self.keep_all_samples = keep_all_samples # 保存参数 + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于对答案进行正确性评判,通过比较当前答案与参考答案的语义一致性,判断答案是否正确。" + "调用大语言模型进行语义理解和判断,最终返回每个答案是否正确的二分类结果。\n" + "输入参数:\n" + "- system_prompt:系统提示词,用于定义模型行为\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口\n" + "- prompt_template:提示模板对象,用于构建评判提示词\n" + "- keep_all_samples:是否保留所有样本,默认为False(仅保留正确答案)\n" + "- question_key:问题字段名,默认为'question'\n" + "- answer_key:当前答案字段名,默认为'answer'\n" + "- reference_key:参考答案字段名,默认为'reference_answer'\n" + "输出参数:\n" + "- DataFrame,包含原始数据和判断结果(answer_match_result字段)\n" + "- 如果keep_all_samples为False,则仅保留判断结果为True的行\n" + "- 返回包含输入字段名的列表,用于后续算子引用" + ) + elif lang == "en": + return ( + "This operator evaluates the correctness of answers by comparing the semantic consistency between " + "the current answer and the reference answer. It uses a large language model for semantic understanding " + "and judgment, ultimately returning a binary classification result for each answer.\n" + "Input Parameters:\n" + "- system_prompt: System prompt to define model behavior\n" + "- llm_serving: LLM serving object implementing LLMServingABC interface\n" + "- prompt_template: Prompt template object for constructing evaluation prompts\n" + "- keep_all_samples: Whether to keep all samples, default is False (only keep correct answers)\n" + "- question_key: Field name for questions, default is 'question'\n" + "- answer_key: Field name for current answers, default is 'answer'\n" + "- reference_key: Field name for reference answers, default is 'reference_answer'\n\n" + "Output Parameters:\n" + "- DataFrame containing original data and judgment results (answer_match_result field)\n" + "- If keep_all_samples is False, only rows with True judgment results are retained\n" + "- List containing input field names for subsequent operator reference" + ) + else: + return ( + "AnswerJudge evaluates answer correctness by comparing semantic consistency with reference answers using LLM." + ) + + def ResolveResponse(self, response): + # 检查空响应 + if response is None or (isinstance(response, str) and response.strip() == ''): + self.empty_responses_count += 1 + return False + try: + pattern = re.compile(r'"judgement_result"\s*:\s*(true|false)', re.IGNORECASE) + match = pattern.search(response) + result_value = None + if match: + result_value = match.group(1).lower() + else: + # 备用解析逻辑,检查响应中是否包含true或false + if "true" in response.lower(): + result_value = "true" + else: + result_value = "false" + if result_value == "true": + return True + else: + return False + except Exception as e: + self.logger.error(f"Response format error: {response}. Error: {e}") + return False + + def run(self, storage: DataFlowStorage, input_question_key: str = "question", input_answer_key: str = "answer", input_reference_key: str = "reference_answer") -> list: + self.question_key = input_question_key + self.answer_key = input_answer_key + self.reference_key = input_reference_key + + dataframe = storage.read("dataframe") + + # 检查必要的列是否存在 + required_columns = [input_question_key, input_answer_key, input_reference_key] + for column in required_columns: + if column not in dataframe.columns: + self.logger.error(f"Required column '{column}' not found in dataframe") + return required_columns + + # 检查参考答案是否为空或不存在 + empty_reference_mask = dataframe[input_reference_key].isna() | (dataframe[input_reference_key] == '') + skipped_rows = dataframe[empty_reference_mask] + valid_rows = dataframe[~empty_reference_mask] + + # 记录跳过的行数 + skipped_count = len(skipped_rows) + + # 初始化结果列,默认所有行为False + dataframe['answer_match_result'] = False + + if len(valid_rows) == 0: + self.logger.warning("No valid samples with reference answers found. All samples skipped.") + if self.keep_all_samples: + output_file = storage.write(dataframe) # 保留所有行,但answer_match_result都为False + else: + output_file = storage.write(pd.DataFrame(columns=dataframe.columns)) # 不保留任何行 + self.logger.info(f"Dataframe saved to {output_file}. Skipped {skipped_count} samples due to missing reference answers.") + return required_columns + ['answer_match_result'] + + # 只对有参考答案的行构建提示词并调用LLM + inputs = [self.prompt_template.build_prompt( + question=row[input_question_key], + answer=row[input_answer_key], + reference_answer=row[input_reference_key] + ) for _, row in valid_rows.iterrows()] + + responses = self.llm_serving.generate_from_input(user_inputs=inputs, system_prompt=self.system_prompt) + results = [self.ResolveResponse(response) for response in responses] + + # 创建结果掩码,与valid_rows长度相同 + result_mask = np.array(results, dtype=bool) + + # 更新有效行的answer_match_result + valid_indices = valid_rows.index + for i, idx in enumerate(valid_indices): + dataframe.at[idx, 'answer_match_result'] = results[i] + + # 根据keep_all_samples决定是否保留所有样本 + if self.keep_all_samples: + # 保留所有样本,包括不匹配的和没有参考答案的 + final_dataframe = dataframe + else: + # 只保留匹配的样本 + final_dataframe = dataframe[dataframe['answer_match_result'] == True] + + output_file = storage.write(final_dataframe) + + # 记录统计信息 + total_samples = len(dataframe) + valid_samples = len(valid_rows) + matched_samples = sum(results) + accuracy = matched_samples / valid_samples if valid_samples > 0 else 0 + + self.logger.info(f"Processed answers saved to {output_file}.") + self.logger.info(f"Total samples: {total_samples}, Valid samples: {valid_samples}, Skipped samples: {skipped_count}") + self.logger.info(f"Matched answers: {matched_samples}, Accuracy: {accuracy:.2%}") + self.logger.info(f"Output samples: {len(final_dataframe)}") + + # 记录空响应数量并重置计数器 + if self.empty_responses_count > 0: + self.logger.error(f"Found {self.empty_responses_count} empty responses during evaluation.") + self.empty_responses_count = 0 + + return required_columns + ['answer_match_result'] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/reasoning_answer_ngram_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/reasoning_answer_ngram_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..651595cdaa2abcb378ecfbea7f57cd663bed152d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/reasoning_answer_ngram_filter.py @@ -0,0 +1,249 @@ +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC + +import numpy as np +import pandas as pd +import re +from typing import List + + +@OPERATOR_REGISTRY.register() +class ReasoningAnswerNgramFilter(OperatorABC): + """ + 适配中英文的 n-gram 重复度过滤算子: + - 若文本包含中文字符:按“字符 n-gram”计算重复度; + - 否则:按“英文单词 n-gram”计算重复度。 + 重复度得分 = unique_ngrams_count / total_ngrams ∈ [0, 1], + 数值越小表示重复越严重。 + """ + + def __init__( + self, + min_score: float = 0.1, + max_score: float = 1.0, + ngrams: int = 5, + ): + self.logger = get_logger() + + # 基本参数赋值 + self.min_score = float(min_score) + self.max_score = float(max_score) + self.ngrams = int(ngrams) + + # 参数合法性校正,不抛异常,只打日志并兜底修正 + if not (0.0 <= self.min_score <= 1.0): + self.logger.error( + f"[ReasoningAnswerNgramFilter] min_score={self.min_score} 不在 [0, 1],重置为 0.0" + ) + self.min_score = 0.0 + + if not (0.0 <= self.max_score <= 1.0): + self.logger.error( + f"[ReasoningAnswerNgramFilter] max_score={self.max_score} 不在 [0, 1],重置为 1.0" + ) + self.max_score = 1.0 + + if self.min_score > self.max_score: + self.logger.error( + f"[ReasoningAnswerNgramFilter] min_score({self.min_score}) > max_score({self.max_score}),交换二者数值" + ) + self.min_score, self.max_score = self.max_score, self.min_score + + if self.ngrams <= 0: + self.logger.error( + f"[ReasoningAnswerNgramFilter] ngrams={self.ngrams} 非正数,重置为 5" + ) + self.ngrams = 5 + + # ---------------- 公共说明 ---------------- + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子基于 n-gram 重复率过滤答案,支持中英文:\n" + "- 若文本包含中文:使用“字符 n-gram”来度量重复度;\n" + "- 若文本不含中文:使用“英文单词 n-gram”来度量重复度。\n\n" + "输入参数:\n" + "- min_score:最小可接受分数(0~1,越低表示越重复)\n" + "- max_score:最大可接受分数(0~1)\n" + "- ngrams:n-gram 的窗口大小\n\n" + "输出行为:\n" + "- 计算每条样本的重复度分数 repetition_score ∈ [0, 1]\n" + "- 仅保留分数在 [min_score, max_score] 区间内的样本。" + ) + elif lang == "en": + return ( + "This operator filters answers based on n-gram repetition scores and supports both Chinese and English.\n" + "- If the text contains Chinese characters: use character-level n-grams.\n" + "- Otherwise: use word-level n-grams for English.\n\n" + "Input Parameters:\n" + "- min_score: Minimum acceptable score (0~1, lower means more repetition)\n" + "- max_score: Maximum acceptable score (0~1)\n" + "- ngrams: Size of the n-gram window\n\n" + "Behavior:\n" + "- Compute repetition_score ∈ [0, 1] for each sample\n" + "- Keep only samples whose scores fall in [min_score, max_score]." + ) + else: + return "ReasoningAnswerNgramFilter detects repetition via n-gram scores." + + # ---------------- 内部工具函数 ---------------- + @staticmethod + def _contains_chinese(text: str) -> bool: + """判断文本中是否包含中文字符。""" + if not isinstance(text, str): + return False + return re.search(r"[\u4e00-\u9fff]", text) is not None + + def _build_char_ngrams(self, text: str) -> List[str]: + """ + 针对包含中文的文本,使用“字符 n-gram”。 + + 处理步骤: + 1. 转为小写; + 2. 仅保留:中文字符 + 英文字母 + 数字; + 3. 删除空白等非内容字符; + 4. 按连续 n 个“字符”构造 n-gram。 + """ + if not isinstance(text, str): + text = "" if text is None else str(text) + + text = text.lower() + # 保留中文、英文字母、数字 + text = re.sub(r"[^\u4e00-\u9fff0-9a-z]", "", text) + + chars = list(text) + if len(chars) < self.ngrams: + return [] + + ngrams = [ + "".join(chars[i : i + self.ngrams]) + for i in range(len(chars) - (self.ngrams - 1)) + ] + return ngrams + + def _build_word_ngrams(self, text: str) -> List[str]: + """ + 针对不含中文的文本,使用“英文单词 n-gram”。 + + 处理步骤: + 1. 转为小写; + 2. 去除标点,仅保留“单词字符 + 空白”; + 3. 按空格 split 得到单词序列; + 4. 按连续 n 个“单词”构造 n-gram。 + """ + if not isinstance(text, str): + text = "" if text is None else str(text) + + text = text.lower() + # 保留单词字符和空白(英文场景) + text = re.sub(r"[^\w\s]", " ", text) + words = text.split() + + if len(words) < self.ngrams: + return [] + + ngrams = [ + " ".join(words[i : i + self.ngrams]) + for i in range(len(words) - (self.ngrams - 1)) + ] + return ngrams + + def _compute_repetition_score(self, text: str) -> float: + """ + 根据是否包含中文,选择字符 n-gram 或单词 n-gram, + 并计算 repetition_score = unique_ngrams_count / total_ngrams。 + """ + if self._contains_chinese(text): + ngrams = self._build_char_ngrams(text) + mode = "char" + else: + ngrams = self._build_word_ngrams(text) + mode = "word" + + total_ngrams = len(ngrams) + if total_ngrams == 0: + # 太短或为空,视为极度重复(得分 0.0) + self.logger.info( + f"[ReasoningAnswerNgramFilter] 文本长度不足以构成 n-gram,mode={mode},视为 repetition_score=0.0" + ) + return 0.0 + + unique_ngrams_count = len(set(ngrams)) + repetition_score = unique_ngrams_count / total_ngrams + return repetition_score + + # ---------------- DataFrame 校验 ---------------- + def _validate_dataframe(self, dataframe: pd.DataFrame): + required_keys = [self.question_key, self.answer_key] + forbidden_keys = [] # 这里目前没有真正禁止的列,可以后续扩展 + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + self.logger.error(f"[ReasoningAnswerNgramFilter] Missing required column(s): {missing}") + if conflict: + self.logger.error( + f"[ReasoningAnswerNgramFilter] The following column(s) already exist and would be overwritten: {conflict}" + ) + + missing_keys = [key for key in required_keys if key not in dataframe.columns] + if missing_keys: + self.logger.error( + f"[ReasoningAnswerNgramFilter] The following required columns are missing from the dataframe: {missing_keys}" + ) + + # ---------------- 主入口 ---------------- + def run( + self, + storage: DataFlowStorage, + input_question_key: str = "instruction", + input_answer_key: str = "generated_cot", + ) -> list: + self.question_key = input_question_key + self.answer_key = input_answer_key + + dataframe = storage.read("dataframe") + self.logger.info( + f"[ReasoningAnswerNgramFilter] Found {len(dataframe)} rows, columns: {list(dataframe.columns)}" + ) + + self._validate_dataframe(dataframe) + + scores = [] + missing_answer_logged = False + + for _, sample in dataframe.iterrows(): + try: + q = sample.get(self.question_key, "") + a = sample.get(self.answer_key, "") + # question + answer 一起看,防止只在 answer 内截断造成偏差 + answer = f"{q} {a}" + except Exception: + if not missing_answer_logged: + self.logger.error( + "[ReasoningAnswerNgramFilter] 读取 answer 失败,仅使用 question 计算重复度" + ) + missing_answer_logged = True + answer = sample.get(self.question_key, "") + + score = self._compute_repetition_score(answer) + scores.append(score) + + scores = np.array(scores, dtype=float) + indexes = (scores >= self.min_score) & (scores <= self.max_score) + + filtered_df = dataframe[indexes] + self.logger.info( + f"[ReasoningAnswerNgramFilter] Filtered down to {len(filtered_df)} rows " + f"with repetition_score in [{self.min_score}, {self.max_score}]" + ) + + output_file = storage.write(filtered_df) + self.logger.info(f"[ReasoningAnswerNgramFilter] Results saved to {output_file}") + + # 返回保留的 key 列名 + return [input_question_key, input_answer_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/reasoning_answer_pipeline_root_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/reasoning_answer_pipeline_root_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..925ddf69811e9c701373629c86b044c4954647bb --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/reasoning_answer_pipeline_root_filter.py @@ -0,0 +1,95 @@ +from dataflow import get_logger +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.reasoning.AnswerExtraction import StringCleaner, UnitTextManager, AnswerExtractor +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage + +import pandas as pd + +@OPERATOR_REGISTRY.register() +class ReasoningAnswerPipelineRootFilter(OperatorABC): + def __init__(self): + + self.logger = get_logger() + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "答案处理流程根节点,负责将输入数据根据有无真实标签GT分发到不同处理分支。\n\n" + "输入参数:\n" + "- input_file:输入文件路径\n" + "- output_dir:输出目录路径\n" + "- branch_config:分支配置参数\n" + "- parallel_workers:并行工作线程数\n\n" + "输出参数:\n" + "- 多个输出文件路径(根据分支配置生成)" + ) + elif lang == "en": + return ( + "Root node of answer processing pipeline, distributes input data to different processing branches.\n\n" + "Input Parameters:\n" + "- input_file: Input file path\n" + "- output_dir: Output directory path\n" + "- branch_config: Branch configuration parameters\n" + "- parallel_workers: Number of parallel workers\n\n" + "Output Parameters:\n" + "- Multiple output file paths (generated based on branch config)" + ) + else: + return "AnswerPipelineRoot routes data to different processing branches." + + def run(self, storage: DataFlowStorage, input_answer_key: str = "output", input_gt_key: str = "golden_answer"): + self.input_answer_key = input_answer_key + self.input_gt_key = input_gt_key + + df = storage.read("dataframe") + + if not self.input_gt_key or self.input_gt_key not in df.columns: + self.logger.warning("No valid gt key in input file, copy input file to output file without gt") + return + + # 初始化答案提取器 + if self.input_answer_key in df.columns: + unit_text_manager = UnitTextManager() + string_cleaner = StringCleaner(unit_text_manager) + answer_extractor = AnswerExtractor(string_cleaner) + + def extract_gt(answer, gt): + try: + if gt != "" and not pd.isna(gt): + return gt + else: + if pd.isna(answer) or answer == "": + return None + else: + return answer_extractor.extract_answer(answer,None,True) + except Exception as e: + self.logger.error(f"Error in extract_gt: {e}", exc_info=True) + return None + + # 使用 apply 遍历 DataFrame, 避免显式循环索引问题 + df[self.input_gt_key] = df.apply(lambda row: extract_gt(row[self.input_answer_key], + row[self.input_gt_key]), + axis=1) + + # 拆分有gt和无gt的 DataFrame + df_with_gt = df[(df[self.input_gt_key].notna()) & (df[self.input_gt_key] != "")] + df_without_gt = df[(df[self.input_gt_key].isna()) | (df[self.input_gt_key] == "")].copy() + df_without_gt[self.input_gt_key] = None + + # 输出结果 + if len(df_with_gt) > 0: + output_file_gt = storage.write(df_with_gt) + self.logger.info(f"output {df_with_gt.shape[0]} rows with gt to {output_file_gt}") + + if len(df_without_gt) > 0: + output_file_without_gt = storage.write(df_without_gt) + self.logger.info(f"output {df_without_gt.shape[0]} rows without gt to {output_file_without_gt}") + + + + + + + \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/reasoning_answer_token_length_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/reasoning_answer_token_length_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..df5f03efc3ec8621693031847e12fb9dd82dfc24 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/reasoning_answer_token_length_filter.py @@ -0,0 +1,105 @@ +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from transformers import AutoTokenizer + +from tqdm import tqdm +import pandas as pd + +@OPERATOR_REGISTRY.register() +class ReasoningAnswerTokenLengthFilter(OperatorABC): + def __init__(self, + max_answer_token_length: int = 8192, + tokenizer_dir: str = "Qwen/Qwen2.5-0.5B-Instruct"): + + self.max_answer_token_length = max_answer_token_length + self.tokenizer_dir = tokenizer_dir + self.tokenizer = AutoTokenizer.from_pretrained(self.tokenizer_dir) + self.logger = get_logger() + self.empty_count = 0 # 添加空值计数器 + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子根据token数量过滤过长的答案。\n\n" + "输入参数:\n" + "- max_answer_token_length:最大token数\n" + "- tokenizer_dir:分词器路径\n" + "- read_min/max_score:分数范围\n\n" + "输出参数:\n" + "- 长度合规返回1,否则返回0" + ) + elif lang == "en": + return ( + "Filters answers exceeding specified token length limit.\n\n" + "Input Parameters:\n" + "- max_answer_token_length: Maximum allowed tokens\n" + "- tokenizer_dir: Tokenizer directory\n" + "- read_min/max_score: Score range\n\n" + "Output Parameters:\n" + "- Returns 1 if within limit, 0 otherwise" + ) + else: + return "AnswerTokenLengthFilter enforces answer length constraints" + + + def _validate_dataframe(self, dataframe: pd.DataFrame): + required_keys = [self.input_key] + forbidden_keys = [] + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + self.logger.error(f"Missing required column(s): {missing}") + if conflict: + self.logger.error(f"The following column(s) already exist and would be overwritten: {conflict}") + missing_keys = [key for key in required_keys if key not in dataframe.columns] + + if missing_keys: + self.logger.error(f"The following required columns are missing from the dataframe: {missing_keys}") + + def run( + self, + storage:DataFlowStorage, + input_key: str = "generated_cot" + ) -> list: + + dataframe = storage.read("dataframe") + + self.input_key = input_key + self.logger.info(f"Found {len(dataframe)} rows in the dataframe") + self._validate_dataframe(dataframe) + + def get_token_count(input_string): + # 检查None或空字符串 + if input_string is None or (isinstance(input_string, str) and input_string.strip() == ''): + self.empty_count += 1 + return self.max_answer_token_length + 1 # 确保被过滤 + try: + tokens = self.tokenizer.encode(input_string, add_special_tokens=False) + return len(tokens) + except Exception as e: + self.logger.error(f"Token encoding error: {e}") + self.empty_count += 1 + return self.max_answer_token_length + 1 + + output = [] + for i, text in tqdm(enumerate(dataframe[self.input_key]), desc="Checking token lengths"): + is_valid = get_token_count(text) <= self.max_answer_token_length + if is_valid: + output.append(dataframe.iloc[i]) + + dataframe = pd.DataFrame(output) + + output_file = storage.write(dataframe) + self.logger.info(f"Saved {len(dataframe)} filtered rows to {output_file}") + + # 记录空值数量并重置计数器 + if self.empty_count > 0: + self.logger.warning(f"Found {self.empty_count} empty or invalid entries during filtering") + self.empty_count = 0 + + return [self.input_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/reasoning_question_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/reasoning_question_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..bcf20adb437b839ca62f613952c19ea273a651db --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/filter/reasoning_question_filter.py @@ -0,0 +1,110 @@ +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import LLMServingABC + +from dataflow.core.prompt import DIYPromptABC +from dataflow.prompts.reasoning.math import MathQuestionFilterPrompt +from dataflow.prompts.reasoning.general import GeneralQuestionFilterPrompt +from dataflow.prompts.reasoning.diy import DiyQuestionFilterPrompt + +from dataflow.core.prompt import prompt_restrict +from typing import Union +import re +@prompt_restrict( + MathQuestionFilterPrompt, + GeneralQuestionFilterPrompt, + DiyQuestionFilterPrompt +) +@OPERATOR_REGISTRY.register() +class ReasoningQuestionFilter(OperatorABC): + def __init__(self, + system_prompt: str = "You are a helpful assistant.", + llm_serving: LLMServingABC = None, + prompt_template: Union[MathQuestionFilterPrompt, GeneralQuestionFilterPrompt, DiyQuestionFilterPrompt, DIYPromptABC] = MathQuestionFilterPrompt + ): + self.logger = get_logger() + if prompt_template is None: + prompt_template = MathQuestionFilterPrompt() + self.prompt_template = prompt_template + self.system_prompt = system_prompt + self.llm_serving = llm_serving + self.empty_responses_count = 0 # 添加空响应计数器 + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于对问题进行正确性检查,包括格式是否规范、语义是否合理、条件是否矛盾以及是否具备充分信息可解。" + "调用大语言模型依次执行四阶段判断,最终返回每个问题是否合格的二分类结果(保留合格样本)。\n" + "输入参数:\n" + "- system_prompt:系统提示词,用于定义模型行为\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口\n" + "- prompt_template:提示模板对象,用于构建检查提示词\n" + "- input_key:输入问题字段名,默认为'math_problem'\n" + "输出参数:\n" + "- 过滤后的DataFrame,仅保留判断结果为True的行\n" + "- 返回包含输入字段名的列表,用于后续算子引用" + ) + elif lang == "en": + return ( + "This operator checks the correctness of questions, including formatting, semantic validity, logical consistency, \n" + "and whether the problem is solvable. It performs a four-stage evaluation using a large language model and retains qualified samples.\n" + "Input Parameters:\n" + "- system_prompt: System prompt to define model behavior\n" + "- llm_serving: LLM serving object implementing LLMServingABC interface\n" + "- prompt_template: Prompt template object for constructing check prompts\n" + "- input_key: Field name for input questions, default is 'math_problem'\n\n" + "Output Parameters:\n" + "- Filtered DataFrame containing only rows with True judgment results\n" + "- List containing input field name for subsequent operator reference" + ) + else: + return ( + "QuestionFilter performs correctness checking on questions using a multi-stage LLM evaluation and retains qualified samples." + ) + + def ResolveResponse(self, response): + # 检查空响应 + if response is None or (isinstance(response, str) and response.strip() == ''): + self.empty_responses_count += 1 + return False + try: + pattern = re.compile(r'"judgement_test"\s*:\s*(true|false)', re.IGNORECASE) + match = pattern.search(response) + test_value = None + if match: + test_value = match.group(1).lower() + else: + if "true" in response.lower(): + test_value = "true" + else: + test_value = "false" + if test_value == "true": + return True + else: + return False + except Exception as e: + self.logger.error(f"Response format error for problem: {response}. Error: {e}") + return False + + def run(self, storage: DataFlowStorage, input_key: str = "math_problem") -> list: + self.input_key = input_key + dataframe = storage.read("dataframe") + questions = dataframe[input_key] + inputs = [self.prompt_template.build_prompt(question) for question in questions] + responses = self.llm_serving.generate_from_input(user_inputs=inputs, system_prompt=self.system_prompt) + results = [self.ResolveResponse(response) for response in responses] + + # 保留results为True的行 + dataframe = dataframe[results] + output_file = storage.write(dataframe) + self.logger.info(f"Filtered questions saved to {output_file}") + + # 记录空响应数量并重置计数器 + if self.empty_responses_count > 0: + self.logger.error(f"Found {self.empty_responses_count} empty responses during filtering.") + self.empty_responses_count = 0 + + return [input_key,] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/__pycache__/reasoning_answer_extraction_qwenmatheval_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/__pycache__/reasoning_answer_extraction_qwenmatheval_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40b7ad68239ca866a12bf2d240d11ade60fbe50c Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/__pycache__/reasoning_answer_extraction_qwenmatheval_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/__pycache__/reasoning_answer_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/__pycache__/reasoning_answer_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e9416dcc1a7b2503367ccc63ea7fbda8e71f059 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/__pycache__/reasoning_answer_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/__pycache__/reasoning_pretrain_format_convert_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/__pycache__/reasoning_pretrain_format_convert_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..038f2e4347e12e356fa5640009c58bb819687917 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/__pycache__/reasoning_pretrain_format_convert_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/__pycache__/reasoning_pseudo_answer_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/__pycache__/reasoning_pseudo_answer_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f3c230e723a3fe45c7baf2d5a824c63806503d0 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/__pycache__/reasoning_pseudo_answer_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/__pycache__/reasoning_question_fusion_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/__pycache__/reasoning_question_fusion_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9442be78affa4b3effe2eea4fce91a5f2a20f919 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/__pycache__/reasoning_question_fusion_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/__pycache__/reasoning_question_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/__pycache__/reasoning_question_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4cbef261b60f2a1780f592e4621e02e75ec96dce Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/__pycache__/reasoning_question_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/reasoning_answer_extraction_qwenmatheval_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/reasoning_answer_extraction_qwenmatheval_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..e182385284f641f20259ea0491f1225c948ef587 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/reasoning_answer_extraction_qwenmatheval_generator.py @@ -0,0 +1,79 @@ +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.reasoning.AnswerExtraction import StringCleaner, UnitTextManager, AnswerExtractor + +from word2number import w2n +from tqdm import tqdm +import pandas as pd +import logging +import re + +# The main class to manage the entire extraction process +@OPERATOR_REGISTRY.register() +class ReasoningAnswerExtractionQwenMathEvalGenerator(OperatorABC): + """ + A class to handle the process of extracting answers from a dataset. + """ + + def __init__(self, dataset_name:str = None): + """ + Initializes the AnswerExtraction_QwenMathEval class. + """ + self.logger = get_logger() + self.data_name = dataset_name + # Initialize helpers + unit_manager = UnitTextManager() + string_cleaner = StringCleaner(unit_manager) + self.answer_extractor = AnswerExtractor(string_cleaner) + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于从数学问题回答中提取规范化答案表达式,进行字符串清洗、单位处理和格式标准化。\n\n" + "输入参数:\n" + "- input_key:输入数据字段名\n" + "- answer_key:原始答案字段名\n" + "- output_key:处理后的答案字段名\n" + "- unit_texts:需要过滤的单位文本列表\n\n" + "输出参数:\n" + "- output_key:标准化后的数学表达式字段" + ) + elif lang == "en": + return ( + "This operator extracts and normalizes mathematical expressions from answers, " + "performing string cleaning, unit processing and format standardization.\n\n" + "Input Parameters:\n" + "- input_key: Input data field name\n" + "- answer_key: Raw answer field name\n" + "- output_key: Processed answer field name\n" + "- unit_texts: List of unit texts to filter\n\n" + "Output Parameters:\n" + "- output_key: Standardized mathematical expression field" + ) + else: + return "AnswerExtraction_QwenMathEval performs mathematical answer normalization and standardization." + + def run(self, storage: DataFlowStorage, input_key:str = "pseudo_correct_solution_example", output_key:str = "extraction"): + """ + Executes the answer extraction process. + """ + self.input_key, self.output_key = input_key, output_key + raw_dataframe = storage.read("dataframe") + key_list = raw_dataframe.columns.to_list() + if self.input_key not in key_list: + raise ValueError(f"input_key: {self.input_key} not found in dataframe columns.") + + self.logger.info(f"Found {len(raw_dataframe)} rows.") + extractions = [ + self.answer_extractor.extract_answer(resp, self.data_name) + for resp in tqdm(raw_dataframe[self.input_key], desc='Processing') + ] + raw_dataframe[self.output_key] = extractions + + output_file = storage.write(raw_dataframe) + self.logger.info(f"Extracted answers saved to {output_file}") + + return [output_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/reasoning_answer_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/reasoning_answer_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..da40a08d2e24a2fc6d9482666bdd483287082efe --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/reasoning_answer_generator.py @@ -0,0 +1,100 @@ +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC + +from dataflow.prompts.reasoning.math import MathAnswerGeneratorPrompt +from dataflow.prompts.reasoning.general import GeneralAnswerGeneratorPrompt +from dataflow.prompts.reasoning.diy import DiyAnswerGeneratorPrompt +from dataflow.core.prompt import prompt_restrict, DIYPromptABC + +import pandas as pd +from typing import Union + +@prompt_restrict( + MathAnswerGeneratorPrompt, + GeneralAnswerGeneratorPrompt, + DiyAnswerGeneratorPrompt +) +@OPERATOR_REGISTRY.register() +class ReasoningAnswerGenerator(OperatorABC): + ''' + Answer Generator is a class that generates answers for given questions. + ''' + def __init__(self, + llm_serving: LLMServingABC, + prompt_template: Union[MathAnswerGeneratorPrompt, GeneralAnswerGeneratorPrompt, DiyAnswerGeneratorPrompt, DIYPromptABC] = MathAnswerGeneratorPrompt + ): + + self.logger = get_logger() + + if prompt_template is None: + prompt_template = MathAnswerGeneratorPrompt() + self.prompts = prompt_template + self.llm_serving = llm_serving + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于为给定问题生成答案,调用大语言模型进行推理。\n" + "输入参数:\n" + "- llm_serving:LLM服务实例,用于生成答案\n" + "- prompt_template:提示模板对象,用于构建生成提示词\n" + "输出参数:\n" + "- output_key:生成的答案字段,默认'generated_cot'" + ) + elif lang == "en": + return ( + "This operator generates answers for given questions using LLMs for reasoning. \n" + "Input Parameters:\n" + "- llm_serving: LLM serving instance for answer generation\n" + "- prompt_template: Prompt template object for constructing generation prompts\n" + "Output Parameters:\n" + "- output_key: Generated answer field, default 'generated_cot'" + ) + else: + return "AnswerGenerator produces answers for questions using large language models." + + def _validate_dataframe(self, dataframe: pd.DataFrame): + required_keys = [self.input_key] + forbidden_keys = [self.output_key] + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + raise ValueError(f"Missing required column(s): {missing}") + if conflict: + raise ValueError(f"The following column(s) already exist and would be overwritten: {conflict}") + + def _reformat_prompt(self, dataframe): + """ + Reformat the prompts in the dataframe to generate questions. + """ + questions = dataframe[self.input_key].tolist() + inputs = [self.prompts.build_prompt(question) for question in questions] + + return inputs + + def run( + self, + storage: DataFlowStorage, + input_key:str = "instruction", + output_key:str = "generated_cot" + ): + ''' + Runs the answer generation process, reading from the input file and saving results to output. + ''' + self.input_key, self.output_key = input_key, output_key + dataframe = storage.read("dataframe") + self._validate_dataframe(dataframe) + formatted_prompts = self._reformat_prompt(dataframe) + answers = self.llm_serving.generate_from_input(formatted_prompts) + + dataframe[self.output_key] = answers + output_file = storage.write(dataframe) + self.logger.info(f"Results saved to {output_file}") + + return [output_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/reasoning_pretrain_format_convert_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/reasoning_pretrain_format_convert_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..48417b6b28c4dac9ef8783aadbdc4684d224c97f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/reasoning_pretrain_format_convert_generator.py @@ -0,0 +1,65 @@ +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow import get_logger + +import pandas as pd + +@OPERATOR_REGISTRY.register() +class ReasoningPretrainFormatConvertGenerator(OperatorABC): + def __init__(self): + self.logger = get_logger() + + def run(self, + storage: DataFlowStorage, + input_read_key_question: str = "question", + input_read_key_answer: str = "answer", + output_key: str = "text" + ): + self.read_key_question = input_read_key_question + self.read_key_answer = input_read_key_answer + self.output_key = output_key + + dataframe = storage.read("dataframe") + + output_rows = dataframe.where(pd.notnull(dataframe), None).to_dict(orient="records") + output_1 = [] + + for row in output_rows: + cur_q = row.get(self.read_key_question) if row.get(self.read_key_question) is not None else "" + cur_a = row.get(self.read_key_answer) if row.get(self.read_key_answer) is not None else "" + output_1.append({ + "text": cur_q + "\n" + cur_a, + }) + + output_file = storage.write(output_1) + self.logger.info(f"SFT to PT convertion results saved to {output_file}") + + return [input_read_key_question, input_read_key_answer, output_key] + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于将SFT格式数据转换为预训练格式。\n\n" + "输入参数:\n" + "- read_key_question:问题字段名\n" + "- read_key_answer:答案字段名\n" + "- output_key:输出文本字段名\n\n" + "输出参数:\n" + "- output_key:输出文本字段名,包含问题和答案的拼接结果\n" + "- 输出文件:转换后的预训练格式数据文件路径" + ) + elif lang == "en": + return ( + "Converts SFT format data to pretraining format.\n\n" + "Input Parameters:\n" + "- read_key_question: Question field name\n" + "- read_key_answer: Answer field name\n" + "- output_key: Output text field name\n\n" + "Output Parameters:\n" + "- output_key: Output text field name containing concatenated question and answer\n" + "- Output file: Path to pretraining format data file" + ) + else: + return "FormatConvert_SFT_to_Pretrain: SFT to Pretraining format converter" \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/reasoning_pseudo_answer_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/reasoning_pseudo_answer_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..5ad652afefd4fc315f90e4f1f02e4a39ef0b29ee --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/reasoning_pseudo_answer_generator.py @@ -0,0 +1,145 @@ +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +from dataflow.utils.reasoning.AnswerExtraction import StringCleaner, UnitTextManager, AnswerExtractor +from dataflow.prompts.reasoning.math import MathAnswerGeneratorPrompt +from dataflow.core.prompt import prompt_restrict + +from collections import defaultdict, Counter +import pandas as pd + +@prompt_restrict( + MathAnswerGeneratorPrompt +) + +@OPERATOR_REGISTRY.register() +class ReasoningPseudoAnswerGenerator(OperatorABC): + ''' + Pseudo Answer Generator is a class that generates answers for given questions, then choose the most frequent answer. + ''' + def __init__(self, llm_serving: LLMServingABC = None, max_times: int = 3): + self.logger = get_logger() + self.prompts = MathAnswerGeneratorPrompt() + self.llm_serving = llm_serving + self.max_times = max_times + + def check_config(self): + required_keys = ["input_file", "output_file", "input_key", "output_key_answer", "output_key_answer_value", "output_key_solutions", "output_key_correct_solution_example", "max_times"] + missing_keys = [key for key in required_keys if key not in self.config] + if missing_keys: + raise ValueError(f"Missing required config keys: {missing_keys}") + + def get_extractor(self): + unit_manager = UnitTextManager() + string_cleaner = StringCleaner(unit_manager) + answer_extractor = AnswerExtractor(string_cleaner) + return answer_extractor + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子生成多个候选答案并通过统计选择最优解,实现伪答案生成。\n\n" + "输入参数:\n" + "- input_file:输入文件路径\n" + "- output_file:输出文件路径\n" + "- max_times:最大生成次数\n" + "- selection_mode:统计选择模式(frequency/consistency)\n\n" + "输出参数:\n" + "- final_answer:最终选择答案字段\n" + "- candidate_answers:候选答案列表字段" + ) + elif lang == "en": + return ( + "This operator generates multiple candidate answers and selects the optimal solution " + "through statistical analysis.\n\n" + "Input Parameters:\n" + "- input_file: Input file path\n" + "- output_file: Output file path\n" + "- max_times: Maximum generation times\n" + "- selection_mode: Statistical selection mode (frequency/consistency)\n\n" + "Output Parameters:\n" + "- final_answer: Selected answer field\n" + "- candidate_answers: Candidate answers list field" + ) + else: + return "PseudoAnswerGenerator produces pseudo-answers through multi-round generation and selection." + + def _validate_dataframe(self, dataframe: pd.DataFrame): + required_keys = [self.input_key] + forbidden_keys = [ + self.output_key_answer, + self.output_key_answer_value, + self.output_key_solutions, + self.output_key_correct_solution_example, + ] + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + key_list = dataframe.columns.tolist() + raise ValueError( + f"read_key: {missing[0]} not found in the dataframe, " + f"please check the read_key: {key_list}" + ) + if conflict: + key_list = dataframe.columns.tolist() + raise ValueError( + f"Found {conflict} in the dataframe, which leads to overwriting the existing column(s), " + f"please check the output_key: {key_list}" + ) + + def run( + self, + storage: DataFlowStorage, + input_key: str = "instruction", + output_key_answer: str = "pseudo_answers", + output_key_answer_value: str = "pseudo_answer_value", + output_key_solutions: str = "pseudo_solutions", + output_key_correct_solution_example: str = "pseudo_correct_solution_example", + ): + + self.input_key, self.output_key_answer, self.output_key_answer_value = input_key, output_key_answer, output_key_answer_value + self.output_key_solutions, self.output_key_correct_solution_example = output_key_solutions, output_key_correct_solution_example + self.extractor = self.get_extractor() + dataframe = storage.read("dataframe") + self._validate_dataframe(dataframe) + + input_data_number = dataframe.shape[0] + user_prompts = dataframe[self.input_key].tolist() + answer_dict = defaultdict(list) + solution_dict = defaultdict(list) + self.logger.info(f"Generating answers for {len(user_prompts)} questions") + for i in range(self.max_times): + self.logger.info(f"Generating: {i+1} times") + solutions = self.llm_serving.generate_from_input(user_prompts) + answers = [self.extractor.extract_answer(solution, None) for solution in solutions] + for idx, answer in enumerate(answers): + answer_dict[idx].append(answer) + solution_dict[idx].append((answer, solutions[idx])) + self.logger.info(f"Generating final answers") + dataframe[self.output_key_answer] = dataframe.get(self.output_key_answer, None) + dataframe[self.output_key_solutions] = dataframe.get(self.output_key_solutions, None) + dataframe[self.output_key_correct_solution_example] = dataframe.get(self.output_key_correct_solution_example, None) + for key, value in answer_dict.items(): + count = Counter(value) + final_answer = count.most_common(1)[0][0] + dataframe.at[int(key),self.output_key_answer] = value + dataframe.at[int(key),self.output_key_solutions] = final_answer + correct_contents = [content for ans, content in solution_dict[key] if ans == final_answer] + dataframe.at[int(key), self.output_key_solutions] = correct_contents + correct_solution_example = correct_contents[0] if correct_contents else None + dataframe.at[int(key), self.output_key_correct_solution_example] = correct_solution_example + dataframe.at[int(key), self.output_key_answer_value] = final_answer + # 过滤掉没有答案的行 + dataframe = dataframe[dataframe[self.output_key_answer_value].notna()] + dataframe = dataframe[dataframe[self.output_key_correct_solution_example].notna()] + self.logger.info(f"Data number {input_data_number} -> {dataframe.shape[0]}") + + output_file = storage.write(dataframe) + self.logger.info(f"PsedoAnswerGenerator's results saved to {output_file}") + + return [output_key_answer, output_key_answer_value, output_key_solutions, output_key_correct_solution_example] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/reasoning_question_fusion_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/reasoning_question_fusion_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..2806feb6334d828856ab2b459901ca857c5267b7 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/reasoning_question_fusion_generator.py @@ -0,0 +1,111 @@ +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +from dataflow.prompts.reasoning.math import MathQuestionParallelFusionGeneratorPrompt,MathQuestionSequentialFusionGeneratorPrompt,MathQuestionConditionFusionGeneratorPrompt +from dataflow.core.prompt import prompt_restrict, DIYPromptABC +from typing import Union + +import pandas as pd +import random + +@prompt_restrict( + MathQuestionParallelFusionGeneratorPrompt, + MathQuestionSequentialFusionGeneratorPrompt, + MathQuestionConditionFusionGeneratorPrompt, +) + +@OPERATOR_REGISTRY.register() +class ReasoningQuestionFusionGenerator(OperatorABC): + def __init__(self, + num_prompts: int = 1, + llm_serving: LLMServingABC = None, + prompt_template: Union[MathQuestionParallelFusionGeneratorPrompt, MathQuestionSequentialFusionGeneratorPrompt, MathQuestionConditionFusionGeneratorPrompt, DIYPromptABC] = None + ): + """ + Initialize the QuestionGenerator with the provided configuration. + """ + self.logger = get_logger() + + if prompt_template is None: + prompt_template = MathQuestionParallelFusionGeneratorPrompt() + self.prompts = prompt_template + self.num_prompts = num_prompts + self.llm_serving = llm_serving + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于基于现有问题生成新问题。\n" + "输入参数:\n" + "- num_prompts:生成问题的数量,整数,范围1-5(含),默认1\n" + "- llm_serving:LLM服务实例,用于生成问题\n" + "- prompt_template:提示模板对象,用于构建生成提示词\n" + "输出参数:\n" + "- 原始输入列(由input_key指定):新增生成的问题\n" + "- Synth_or_Input:标识问题来源,'input'表示原始问题,'synth'表示生成的新问题" + ) + elif lang == "en": + return ( + "Generates new questions based on existing ones. \n" + "Input Parameters:\n" + "- num_prompts: Number of questions to generate per input, integer between 1-5 (inclusive), default 1\n" + "- llm_serving: LLM serving instance for question generation\n" + "- prompt_template: Prompt template object for constructing generation prompts\n" + "Output Parameters:\n" + "- Original input column (specified by input_key): Contains newly generated questions\n" + "- Synth_or_Input: Indicates question source, 'input' for original questions, 'synth' for generated questions" + ) + elif lang == "en": + return ( + "Generates new questions based on existing ones. " + "Produces 1-5 new questions per original question.\n" + "Input Parameters:\n" + "- eval_stage: Evaluation stage identifier\n" + "- read_min/max_score: Score filtering thresholds\n" + "- Other params same as base classifier\n" + "Output Parameters:\n" + "- generated_questions: List of newly generated questions" + ) + + def _validate_dataframe(self, dataframe: pd.DataFrame): + required_keys = [self.input_key] + forbidden_keys = ["Synth_or_Input"] + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + raise ValueError(f"Missing required column(s): {missing}") + if conflict: + raise ValueError(f"The following column(s) already exist and would be overwritten: {conflict}") + + + def _reformat_prompt(self, dataframe): + """ + Reformat the prompts in the dataframe to generate questions based on num_prompts. + """ + problem_1 = dataframe[self.input_problem_1].tolist() + problem_2 = dataframe[self.input_problem_2].tolist() + system_prompt = self.prompts.build_system_prompt() + prompts = [self.prompts.build_prompt(p1,p2) for p1,p2 in enumerate(zip(problem_1, problem_2))] + + return system_prompt, prompts + + def run(self, storage: DataFlowStorage, input_problem_1: str, input_problem_2: str, output_key: str): + """ + Run the question generation process. + """ + self.input_problem_1, self.input_problem_2 = input_problem_1, input_problem_2 + dataframe = storage.read("dataframe") + + for i in range(self.num_prompts): + sys_prompts, user_prompts = self._reformat_prompt(dataframe) + responses = self.llm_serving.generate_from_input(user_prompts, sys_prompts) + dataframe[f"{output_key}_question_{i}"] = responses + self.logger.info(f"Generated questions for {output_key}_{i}") + + output_file = storage.write(dataframe) + self.logger.info(f"Generated questions saved to {output_file}") \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/reasoning_question_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/reasoning_question_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..db13b146a7f67b81ab77027c5a2f33b40e73a393 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/reasoning/generate/reasoning_question_generator.py @@ -0,0 +1,163 @@ +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +from dataflow.prompts.reasoning.math import MathQuestionSynthesisPrompt +from dataflow.prompts.reasoning.general import GeneralQuestionSynthesisPrompt +from dataflow.prompts.reasoning.diy import DiyQuestionSynthesisPrompt +from dataflow.core.prompt import prompt_restrict, DIYPromptABC + +import pandas as pd +import random +import re +from typing import Union + +@prompt_restrict( + MathQuestionSynthesisPrompt, + GeneralQuestionSynthesisPrompt, + DiyQuestionSynthesisPrompt +) + +@OPERATOR_REGISTRY.register() +class ReasoningQuestionGenerator(OperatorABC): + def __init__(self, + num_prompts: int = 1, + llm_serving: LLMServingABC = None, + prompt_template: Union[MathQuestionSynthesisPrompt, GeneralQuestionSynthesisPrompt, DiyQuestionSynthesisPrompt, DIYPromptABC] = None + ): + """ + Initialize the QuestionGenerator with the provided configuration. + """ + self.logger = get_logger() + + if prompt_template is None: + prompt_template = MathQuestionSynthesisPrompt() + self.prompts = prompt_template + self.num_prompts = num_prompts + self.llm_serving = llm_serving + + if self.num_prompts not in range(1,6): + self.logger.debug("num_prompts must be an integer between 1 and 5 (inclusive)") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "该算子用于基于现有问题生成新问题。\n" + "输入参数:\n" + "- num_prompts:生成问题的数量,整数,范围1-5(含),默认1\n" + "- llm_serving:LLM服务实例,用于生成问题\n" + "- prompt_template:提示模板对象,用于构建生成提示词\n" + "输出参数:\n" + "- 原始输入列(由input_key指定):新增生成的问题\n" + "- Synth_or_Input:标识问题来源,'input'表示原始问题,'synth'表示生成的新问题" + ) + elif lang == "en": + return ( + "Generates new questions based on existing ones. \n" + "Input Parameters:\n" + "- num_prompts: Number of questions to generate per input, integer between 1-5 (inclusive), default 1\n" + "- llm_serving: LLM serving instance for question generation\n" + "- prompt_template: Prompt template object for constructing generation prompts\n" + "Output Parameters:\n" + "- Original input column (specified by input_key): Contains newly generated questions\n" + "- Synth_or_Input: Indicates question source, 'input' for original questions, 'synth' for generated questions" + ) + elif lang == "en": + return ( + "Generates new questions based on existing ones. " + "Produces 1-5 new questions per original question.\n" + "Input Parameters:\n" + "- eval_stage: Evaluation stage identifier\n" + "- read_min/max_score: Score filtering thresholds\n" + "- Other params same as base classifier\n" + "Output Parameters:\n" + "- generated_questions: List of newly generated questions" + ) + + def _validate_dataframe(self, dataframe: pd.DataFrame): + required_keys = [self.input_key] + forbidden_keys = ["Synth_or_Input"] + + missing = [k for k in required_keys if k not in dataframe.columns] + conflict = [k for k in forbidden_keys if k in dataframe.columns] + + if missing: + raise ValueError(f"Missing required column(s): {missing}") + if conflict: + raise ValueError(f"The following column(s) already exist and would be overwritten: {conflict}") + + + def _reformat_prompt(self, dataframe): + """ + Reformat the prompts in the dataframe to generate questions based on num_prompts. + """ + diversity_mode = [ + "1, 2, 3", + "1, 2, 4", + "1, 2, 5", + "1, 4, 5", + "1, 2, 3, 4, 5" + ] + + formatted_prompts = [] + + for question in dataframe[self.input_key]: + if self.num_prompts == 0: + formatted_prompts.append("") # Skip generating for this question + else: + if not isinstance(self.prompts, DiyQuestionSynthesisPrompt): + # Randomly choose the required number of transformations from diversity_mode + selected_items = random.sample(diversity_mode, self.num_prompts) + for selected_item in selected_items: + used_prompt = self.prompts.build_prompt(selected_item, question) + formatted_prompts.append(used_prompt.strip()) + else: ### diy prompt + try: + used_prompt = self.prompts.build_prompt(question=question) + formatted_prompts.append(used_prompt.strip()) + except Exception: + self.logger.debug(f"Please check if the symbol {{question}} in prompt is missing.") + + return formatted_prompts + + def _parse_response(self, response: str): + # useful for reasoning llms. If response is in format of Deepseek thinking: ......, keep only the answer part. + pattern = r"(.*?)(.*?)" + matches = re.findall(pattern, response) + if matches: + return matches[0][1] + else: + return response + + def run( + self, + storage: DataFlowStorage, + input_key: str, + output_synth_or_input_flag: str = "Synth_or_Input" + ): + """ + Run the question generation process. + """ + self.input_key = input_key + dataframe = storage.read("dataframe") + self._validate_dataframe(dataframe) + formatted_prompts = self._reformat_prompt(dataframe) + responses = self.llm_serving.generate_from_input(formatted_prompts) + responses = [self._parse_response(response) for response in responses] + + new_rows = pd.DataFrame({ + input_key: responses, + }) + new_rows[output_synth_or_input_flag] = "synth" + dataframe[output_synth_or_input_flag] = "input" + + dataframe = pd.concat([dataframe, new_rows], ignore_index=True) + dataframe = dataframe[dataframe[input_key].notna()] + dataframe = dataframe[dataframe[input_key] != ""] + + output_file = storage.write(dataframe) + self.logger.info(f"Generated questions saved to {output_file}") + + return [input_key, output_synth_or_input_flag] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a3978bc091517cf87b50fdb2be016f8f63d9e0db --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/__init__.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + # filter + from filter.sql_executability_filter import SQLExecutabilityFilter + from filter.sql_execution_filter import SQLExecutionFilter + from filter.text2sql_correspondence_filter import Text2SQLCorrespondenceFilter + + # generate + from generate.sql_generator import SQLGenerator + from generate.sql_by_column_generator import SQLByColumnGenerator + from generate.sql_variation_generator import SQLVariationGenerator + from generate.text2sql_cot_voting_generator import Text2SQLCoTVotingGenerator + from generate.text2sql_cot_generator import Text2SQLCoTGenerator + from generate.text2sql_prompt_generator import Text2SQLPromptGenerator + from generate.text2sql_question_generator import Text2SQLQuestionGenerator + + # eval + from eval.sql_component_classifier import SQLComponentClassifier + from eval.sql_execution_classifier import SQLExecutionClassifier + +else: + import sys + from dataflow.utils.registry import LazyLoader, generate_import_structure_from_type_checking + + + + cur_path = "dataflow/operators/text2sql/" + + + _import_structure = generate_import_structure_from_type_checking(__file__, cur_path) + sys.modules[__name__] = LazyLoader(__name__, "dataflow/operators/text2sql/", _import_structure) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8f24f681e705f9d04496a485843fc020f05e89b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/eval/__pycache__/sql_component_classifier.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/eval/__pycache__/sql_component_classifier.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6601661b4cf37e1e049d6bf06bb7d8a67152299 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/eval/__pycache__/sql_component_classifier.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/eval/__pycache__/sql_execution_classifier.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/eval/__pycache__/sql_execution_classifier.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6967b08e91084b4776ca55a203d70986f43b4624 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/eval/__pycache__/sql_execution_classifier.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/eval/sql_component_classifier.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/eval/sql_component_classifier.py new file mode 100644 index 0000000000000000000000000000000000000000..d85990aca96a45310ab46eca8231863cd1b34c03 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/eval/sql_component_classifier.py @@ -0,0 +1,759 @@ +from tqdm import tqdm +from nltk import word_tokenize +import pandas as pd +import sqlite3 +import re +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage + +class Schema: + def __init__(self, schema): + self._schema = self._normalize_schema(schema) + self._idMap = self._map(self._schema) + + @property + def schema(self): + return self._schema + + @property + def idMap(self): + return self._idMap + + def _normalize_schema(self, schema): + normalized = {} + for table, cols in schema.items(): + table_clean = table.strip().lower() + normalized[table_clean] = [col.strip().lower() for col in cols] + return normalized + + def _map(self, schema): + idMap = {'*': "__all__"} + for table, cols in schema.items(): + for col in cols: + full = f"{table}.{col}" + idMap[full] = f"__{full}__" + for table in schema: + idMap[table] = f"__{table}__" + return idMap + + +class EvalHardness: + CLAUSE_KEYWORDS = ('select', 'from', 'where', 'group', 'order', 'limit', 'intersect', 'union', 'except') + JOIN_KEYWORDS = ('join', 'on', 'as') + + WHERE_OPS = ('not', 'between', '=', '>', '<', '>=', '<=', '!=', 'in', 'like', 'is', 'exists') + UNIT_OPS = ('none', '-', '+', "*", '/') + AGG_OPS = ('none', 'max', 'min', 'count', 'sum', 'avg') + TABLE_TYPE = { + 'sql': "sql", + 'table_unit': "table_unit", + } + + COND_OPS = ('and', 'or') + SQL_OPS = ('intersect', 'union', 'except') + ORDER_OPS = ('desc', 'asc') + FUNC_OPS = ('cast', 'substring', 'date', 'round', 'coalesce') + def __init__(self, schema, query): + self.schema = schema + self.query = query + + @property + def tokenize(self): + string = str(self.query) + vals = {} + + def replace_literal(match): + val = match.group(0) + quote = val[0] + content = val[1:-1] + + if quote == '`': + key = f"__col_{len(vals)}__" + else: # ' 或 " + key = f"__str_{len(vals)}__" + + vals[key] = content + return key + + string = re.sub(r"(['\"`])(?:\\.|[^\\])*?\1", replace_literal, string) + + toks = [word.lower() for word in word_tokenize(string)] + for i in range(len(toks)): + if toks[i] in vals: + toks[i] = vals[toks[i]] + + eq_idxs = [idx for idx, tok in enumerate(toks) if tok == "="] + eq_idxs.reverse() + prefix = ('!', '>', '<') + for eq_idx in eq_idxs: + pre_tok = toks[eq_idx-1] + if pre_tok in prefix: + toks = toks[:eq_idx-1] + [pre_tok + "="] + toks[eq_idx+1: ] + + return toks + + def scan_alias(self, toks): + as_idxs = [idx for idx, tok in enumerate(toks) if tok == 'as'] + alias = {} + for idx in as_idxs: + alias[toks[idx+1]] = toks[idx-1] + return alias + + def get_tables_with_alias(self, toks): + tables = self.scan_alias(toks) + for key in self.schema.schema: + assert key not in tables, "Alias {} has the same name in table".format(key) + tables[key] = key + return tables + + def parse_col(self, toks, start_idx, tables_with_alias, schema, default_tables=None): + tok = toks[start_idx].strip().lower() + if tok == "*": + return start_idx + 1, schema.idMap[tok] + + if '.' in tok: + alias, col = tok.split('.') + key = tables_with_alias[alias] + "." + col + return start_idx+1, schema.idMap[key] + + assert default_tables is not None and len(default_tables) > 0, "Default tables should not be None or empty" + + for alias in default_tables: + table = tables_with_alias[alias] + if tok in schema.schema[table]: + key = table + "." + tok + return start_idx+1, schema.idMap[key] + + assert False, "Error col: {}".format(tok) + + + def parse_col_unit(self, toks, start_idx, tables_with_alias, schema, default_tables=None): + idx = start_idx + if toks[idx] in self.FUNC_OPS: + func_name = toks[idx] + idx += 1 + assert toks[idx] == '(' + idx += 1 + + if func_name == 'cast': + idx, col_id = self.parse_col(toks, idx, tables_with_alias, schema, default_tables) + assert toks[idx] == 'as' + idx += 1 + data_type = toks[idx] + idx += 1 + assert toks[idx] == ')' + idx += 1 + + func_call = ('func', func_name, col_id, data_type) + return idx, (self.AGG_OPS.index("none"), func_call, False) + + else: + idx, col_id = self.parse_col(toks, idx, tables_with_alias, schema, default_tables) + while toks[idx] != ')': + idx += 1 + idx += 1 + + func_call = ('func', func_name, col_id, None) + return idx, (self.AGG_OPS.index("none"), func_call, False) + len_ = len(toks) + isBlock = False + isDistinct = False + if toks[idx] == '(': + isBlock = True + idx += 1 + + if toks[idx] in self.AGG_OPS: + agg_id = self.AGG_OPS.index(toks[idx]) + idx += 1 + assert idx < len_ and toks[idx] == '(' + idx += 1 + if toks[idx] == "distinct": + idx += 1 + isDistinct = True + idx, col_id = self.parse_col(toks, idx, tables_with_alias, schema, default_tables) + assert idx < len_ and toks[idx] == ')' + idx += 1 + return idx, (agg_id, col_id, isDistinct) + + if toks[idx] == "distinct": + idx += 1 + isDistinct = True + agg_id = self.AGG_OPS.index("none") + idx, col_id = self.parse_col(toks, idx, tables_with_alias, schema, default_tables) + + if isBlock: + assert toks[idx] == ')' + idx += 1 + + return idx, (agg_id, col_id, isDistinct) + + def parse_val_unit(self, toks, start_idx, tables_with_alias, schema, default_tables=None): + idx = start_idx + if toks[idx] in self.FUNC_OPS: + func_name = toks[idx] + idx += 1 + assert toks[idx] == '(' + idx += 1 + + if func_name == 'cast': + idx, col_id = self.parse_col(toks, idx, tables_with_alias, schema, default_tables) + assert toks[idx] == 'as' + idx += 1 + data_type = toks[idx] + idx += 1 + assert toks[idx] == ')' + idx += 1 + + func_call = ('func', func_name, col_id, data_type) + return idx, (self.AGG_OPS.index("none"), func_call, False) + + else: + idx, col_id = self.parse_col(toks, idx, tables_with_alias, schema, default_tables) + while toks[idx] != ')': + idx += 1 + idx += 1 + + func_call = ('func', func_name, col_id, None) + return idx, (self.AGG_OPS.index("none"), func_call, False) + len_ = len(toks) + isBlock = False + if toks[idx] == '(': + isBlock = True + idx += 1 + + col_unit1 = None + col_unit2 = None + unit_op = self.UNIT_OPS.index('none') + + idx, col_unit1 = self.parse_col_unit(toks, idx, tables_with_alias, schema, default_tables) + if idx < len_ and toks[idx] in self.UNIT_OPS: + unit_op = self.UNIT_OPS.index(toks[idx]) + idx += 1 + idx, col_unit2 = self.parse_col_unit(toks, idx, tables_with_alias, schema, default_tables) + + if isBlock: + assert toks[idx] == ')' + idx += 1 + + return idx, (unit_op, col_unit1, col_unit2) + + + def parse_table_unit(self, toks, start_idx, tables_with_alias, schema): + idx = start_idx + len_ = len(toks) + key = tables_with_alias[toks[idx]] + + if idx + 1 < len_ and toks[idx+1] == "as": + idx += 3 + else: + idx += 1 + + return idx, schema.idMap[key], key + + + def parse_value(self, toks, start_idx, tables_with_alias, schema, default_tables=None): + idx = start_idx + len_ = len(toks) + + isBlock = False + if toks[idx] == '(': + isBlock = True + idx += 1 + + if toks[idx] == 'select': + idx, val = self.parse_sql(toks, idx, tables_with_alias, schema) + elif isinstance(toks[idx], str) and toks[idx] not in schema.idMap: + val = toks[idx] + idx += 1 + else: + try: + val = float(toks[idx]) + idx += 1 + except Exception: + end_idx = idx + while end_idx < len_ and toks[end_idx] not in (',', ')', 'and', *self.CLAUSE_KEYWORDS, *self.JOIN_KEYWORDS): + end_idx += 1 + + idx, val = self.parse_col_unit(toks[start_idx:end_idx], 0, tables_with_alias, schema, default_tables) + idx = end_idx + + if isBlock: + assert toks[idx] == ')' + idx += 1 + + return idx, val + + def parse_condition(self, toks, start_idx, tables_with_alias, schema, default_tables=None): + idx = start_idx + len_ = len(toks) + conds = [] + + while idx < len_: + idx, val_unit = self.parse_val_unit(toks, idx, tables_with_alias, schema, default_tables) + not_op = False + if toks[idx] == 'not': + not_op = True + idx += 1 + + assert idx < len_ and toks[idx] in self.WHERE_OPS, "Error condition: idx: {}, tok: {}".format(idx, toks[idx]) + op_id = self.WHERE_OPS.index(toks[idx]) + idx += 1 + val1 = val2 = None + if op_id == self.WHERE_OPS.index('between'): + idx, val1 = self.parse_value(toks, idx, tables_with_alias, schema, default_tables) + assert toks[idx] == 'and' + idx += 1 + idx, val2 = self.parse_value(toks, idx, tables_with_alias, schema, default_tables) + else: + idx, val1 = self.parse_value(toks, idx, tables_with_alias, schema, default_tables) + val2 = None + + conds.append((not_op, op_id, val_unit, val1, val2)) + + if idx < len_ and (toks[idx] in self.CLAUSE_KEYWORDS or toks[idx] in (")", ";") or toks[idx] in self.JOIN_KEYWORDS): + break + + if idx < len_ and toks[idx] in self.COND_OPS: + conds.append(toks[idx]) + idx += 1 + + return idx, conds + + + def parse_select(self, toks, start_idx, tables_with_alias, schema, default_tables=None): + idx = start_idx + len_ = len(toks) + + assert toks[idx] == 'select', "'select' not found" + idx += 1 + isDistinct = False + if idx < len_ and toks[idx] == 'distinct': + idx += 1 + isDistinct = True + val_units = [] + + while idx < len_ and toks[idx] not in self.CLAUSE_KEYWORDS: + agg_id = self.AGG_OPS.index("none") + if toks[idx] in self.AGG_OPS: + agg_id = self.AGG_OPS.index(toks[idx]) + idx += 1 + idx, val_unit = self.parse_val_unit(toks, idx, tables_with_alias, schema, default_tables) + val_units.append((agg_id, val_unit)) + if idx < len_ and toks[idx] == ',': + idx += 1 + + return idx, (isDistinct, val_units) + + + def parse_from(self, toks, start_idx, tables_with_alias, schema): + assert 'from' in toks[start_idx:], "'from' not found" + + len_ = len(toks) + idx = toks.index('from', start_idx) + 1 + default_tables = [] + table_units = [] + conds = [] + + while idx < len_: + isBlock = False + if toks[idx] == '(': + isBlock = True + idx += 1 + + if toks[idx] == 'select': + idx, sql = self.parse_sql(toks, idx, tables_with_alias, schema) + table_units.append((self.TABLE_TYPE['sql'], sql)) + else: + if idx < len_ and toks[idx] == 'join': + idx += 1 + idx, table_unit, table_name = self.parse_table_unit(toks, idx, tables_with_alias, schema) + table_units.append((self.TABLE_TYPE['table_unit'],table_unit)) + default_tables.append(table_name) + if idx < len_ and toks[idx] == "on": + idx += 1 + idx, this_conds = self.parse_condition(toks, idx, tables_with_alias, schema, default_tables) + if len(conds) > 0: + conds.append('and') + conds.extend(this_conds) + + if isBlock: + assert toks[idx] == ')' + idx += 1 + if idx < len_ and (toks[idx] in self.CLAUSE_KEYWORDS or toks[idx] in (")", ";")): + break + + return idx, table_units, conds, default_tables + + + def parse_where(self, toks, start_idx, tables_with_alias, schema, default_tables): + idx = start_idx + len_ = len(toks) + + if idx >= len_ or toks[idx] != 'where': + return idx, [] + + idx += 1 + idx, conds = self.parse_condition(toks, idx, tables_with_alias, schema, default_tables) + return idx, conds + + + def parse_group_by(self, toks, start_idx, tables_with_alias, schema, default_tables): + idx = start_idx + len_ = len(toks) + col_units = [] + + if idx >= len_ or toks[idx] != 'group': + return idx, col_units + + idx += 1 + assert toks[idx] == 'by' + idx += 1 + + while idx < len_ and not (toks[idx] in self.CLAUSE_KEYWORDS or toks[idx] in (")", ";")): + idx, col_unit = self.parse_col_unit(toks, idx, tables_with_alias, schema, default_tables) + col_units.append(col_unit) + if idx < len_ and toks[idx] == ',': + idx += 1 + else: + break + + return idx, col_units + + + def parse_order_by(self, toks, start_idx, tables_with_alias, schema, default_tables): + idx = start_idx + len_ = len(toks) + val_units = [] + order_type = 'asc' + + if idx >= len_ or toks[idx] != 'order': + return idx, val_units + + idx += 1 + assert toks[idx] == 'by' + idx += 1 + + while idx < len_ and not (toks[idx] in self.CLAUSE_KEYWORDS or toks[idx] in (")", ";")): + idx, val_unit = self.parse_val_unit(toks, idx, tables_with_alias, schema, default_tables) + val_units.append(val_unit) + if idx < len_ and toks[idx] in self.ORDER_OPS: + order_type = toks[idx] + idx += 1 + if idx < len_ and toks[idx] == ',': + idx += 1 + else: + break + + return idx, (order_type, val_units) + + + def parse_having(self, toks, start_idx, tables_with_alias, schema, default_tables): + idx = start_idx + len_ = len(toks) + + if idx >= len_ or toks[idx] != 'having': + return idx, [] + + idx += 1 + idx, conds = self.parse_condition(toks, idx, tables_with_alias, schema, default_tables) + return idx, conds + + + def parse_limit(self, toks, start_idx): + idx = start_idx + len_ = len(toks) + + if idx < len_ and toks[idx] == 'limit': + idx += 2 + if type(toks[idx-1]) != int: + return idx, 1 + + return idx, int(toks[idx-1]) + + return idx, None + + def skip_semicolon(self, toks, start_idx): + idx = start_idx + while idx < len(toks) and toks[idx] == ";": + idx += 1 + return idx + + def parse_sql(self, start_idx): + toks = self.tokenize + tables_with_alias = self.get_tables_with_alias(toks) + schema =self.schema + isBlock = False # indicate whether this is a block of sql/sub-sql + len_ = len(toks) + idx = start_idx + + sql = {} + if toks[idx] == '(': + isBlock = True + idx += 1 + + from_end_idx, table_units, conds, default_tables = self.parse_from(toks, start_idx, tables_with_alias, schema) + sql['from'] = {'table_units': table_units, 'conds': conds} + # select clause + _, select_col_units = self.parse_select(toks, idx, tables_with_alias, schema, default_tables) + idx = from_end_idx + sql['select'] = select_col_units + # where clause + idx, where_conds = self.parse_where(toks, idx, tables_with_alias, schema, default_tables) + sql['where'] = where_conds + # group by clause + idx, group_col_units = self.parse_group_by(toks, idx, tables_with_alias, schema, default_tables) + sql['groupBy'] = group_col_units + # having clause + idx, having_conds = self.parse_having(toks, idx, tables_with_alias, schema, default_tables) + sql['having'] = having_conds + # order by clause + idx, order_col_units = self.parse_order_by(toks, idx, tables_with_alias, schema, default_tables) + sql['orderBy'] = order_col_units + # limit clause + idx, limit_val = self.parse_limit(toks, idx) + sql['limit'] = limit_val + + idx = self.skip_semicolon(toks, idx) + if isBlock: + assert toks[idx] == ')' + idx += 1 + idx = self.skip_semicolon(toks, idx) + + # intersect/union/except clause + for op in self.SQL_OPS: # initialize IUE + sql[op] = None + if idx < len_ and toks[idx] in self.SQL_OPS: + sql_op = toks[idx] + idx += 1 + idx, IUE_sql = self.parse_sql(idx) + sql[sql_op] = IUE_sql + return idx, sql + + def has_agg(self, unit): + return unit[0] != self.AGG_OPS.index('none') + + def count_agg(self, units): + return len([unit for unit in units if self.has_agg(unit)]) + + def get_nestedSQL(self, sql): + nested = [] + for cond_unit in sql['from']['conds'][::2] + sql['where'][::2] + sql['having'][::2]: + if type(cond_unit[3]) is dict: + nested.append(cond_unit[3]) + if type(cond_unit[4]) is dict: + nested.append(cond_unit[4]) + if sql['intersect'] is not None: + nested.append(sql['intersect']) + if sql['except'] is not None: + nested.append(sql['except']) + if sql['union'] is not None: + nested.append(sql['union']) + return nested + + def count_component1(self, sql): + count = 0 + if len(sql['where']) > 0: + count += 1 + if len(sql['groupBy']) > 0: + count += 1 + if len(sql['orderBy']) > 0: + count += 1 + if sql['limit'] is not None: + count += 1 + if len(sql['from']['table_units']) > 0: + count += len(sql['from']['table_units']) - 1 + + ao = sql['from']['conds'][1::2] + sql['where'][1::2] + sql['having'][1::2] + count += len([token for token in ao if token == 'or']) + cond_units = sql['from']['conds'][::2] + sql['where'][::2] + sql['having'][::2] + count += len([cond_unit for cond_unit in cond_units if cond_unit[1] == self.WHERE_OPS.index('like')]) + + return count + + def count_component2(self, sql): + nested = self.get_nestedSQL(sql) + return len(nested) + + + def count_others(self, sql): + count = 0 + # number of aggregation + agg_count = self.count_agg(sql['select'][1]) + agg_count += self.count_agg(sql['where'][::2]) + agg_count += self.count_agg(sql['groupBy']) + if len(sql['orderBy']) > 0: + agg_count += self.count_agg([unit[1] for unit in sql['orderBy'][1] if unit[1]] + + [unit[2] for unit in sql['orderBy'][1] if unit[2]]) + agg_count += self.count_agg(sql['having']) + if agg_count > 1: + count += 1 + + # number of select columns + if len(sql['select'][1]) > 1: + count += 1 + + # number of where conditions + if len(sql['where']) > 1: + count += 1 + + # number of group by clauses + if len(sql['groupBy']) > 1: + count += 1 + + return count + + + def eval_hardness(self, sql): + count_comp1_ = self.count_component1(sql) + count_comp2_ = self.count_component2(sql) + count_others_ = self.count_others(sql) + + if count_comp1_ <= 1 and count_others_ == 0 and count_comp2_ == 0: + return "easy" + elif (count_others_ <= 2 and count_comp1_ <= 1 and count_comp2_ == 0) or \ + (count_comp1_ <= 2 and count_others_ < 2 and count_comp2_ == 0): + return "medium" + elif (count_others_ > 2 and count_comp1_ <= 2 and count_comp2_ == 0) or \ + (2 < count_comp1_ <= 3 and count_others_ <= 2 and count_comp2_ == 0) or \ + (count_comp1_ <= 1 and count_others_ == 0 and count_comp2_ <= 1): + return "hard" + else: + return "extra" + + def run(self): + _, sql = self.parse_sql(0) + hardness = self.eval_hardness(sql) + return hardness + + +class EvalHardnessLite: + def __init__(self, sql: str, difficulty_config: dict): + self.sql = sql.lower() + self.difficulty_config = difficulty_config + + def match(self, pattern): + return bool(re.search(pattern, self.sql)) + + def count_keyword(self, keyword): + return self.sql.count(keyword) + + def classify_difficulty(self, score: int) -> str: + thresholds = self.difficulty_config['thresholds'] + labels = self.difficulty_config['labels'] + + for i, threshold in enumerate(thresholds): + if score <= threshold: + return labels[i] + return labels[-1] + + def run(self): + sql = self.sql + score = 0 + + if self.match(r'\( *select'): + score += 2 + + if self.count_keyword(' join ') > 0: + score += self.count_keyword(' join ') + if self.count_keyword(',') > 0 and 'from' in sql: + score += 1 + + if self.count_keyword(' and ') + self.count_keyword(' or ') >= 2: + score += 1 + if any(kw in sql for kw in ['in', 'exists', 'like']): + score += 1 + + if 'group by' in sql: + score += 1 + if 'having' in sql: + score += 1 + + if any(func in sql for func in ['cast', 'round', 'substring', 'date', 'coalesce']): + score += 1 + + if 'order by' in sql: + score += 1 + if 'limit' in sql: + score += 1 + + if any(op in sql for op in ['union', 'intersect', 'except']): + score += 2 + + select_cols = re.findall(r'select\s+(distinct\s+)?(.+?)\s+from', sql, re.DOTALL) + if select_cols: + num_commas = select_cols[0][1].count(',') + if num_commas >= 1: + score += 1 + + difficulty = self.classify_difficulty(score) + return difficulty + + +@OPERATOR_REGISTRY.register() +class SQLComponentClassifier(OperatorABC): + def __init__(self, + difficulty_thresholds: list, + difficulty_labels: list + ): + self.difficulty_config = { + 'thresholds': difficulty_thresholds, + 'labels': difficulty_labels + } + self.logger = get_logger() + if len(self.difficulty_config['thresholds']) != len(self.difficulty_config['labels']) - 1: + raise ValueError("Thresholds and labels configuration mismatch") + + def check_column(self, dataframe): + required_columns = [self.input_sql_key] + missing_columns = [col for col in required_columns if col not in dataframe.columns] + if missing_columns: + raise ValueError(f"Missing required columns: {missing_columns}") + + @staticmethod + def get_desc(lang): + if lang == "zh": + return ( + "根据SQL的组件数量和复杂度,评估SQL的难度。\n\n" + "输入参数:\n" + "- input_sql_key: 输入SQL列名\n\n" + "输出参数:\n" + "- output_difficulty_key: 输出难度列名" + ) + elif lang == "en": + return ( + "This operator evaluates the difficulty of SQL components based on the number and complexity of components.\n\n" + "Input parameters:\n" + "- input_sql_key: The name of the input SQL column\n\n" + "Output parameters:\n" + "- output_difficulty_key: The name of the output difficulty column" + ) + else: + return "SQL component difficulty evaluator for Text2SQL tasks." + + def report_statistics(self, dataframe: pd.DataFrame): + counts = dataframe[self.output_difficulty_key].value_counts() + self.logger.info("SQL Difficulty Statistics") + difficulty_counts = {d: counts.get(d, 0) for d in ['easy', 'medium', 'hard', 'extra']} + self.logger.info(" | ".join([f"{d.title()}: {v}" for d, v in difficulty_counts.items()])) + + def run(self, storage: DataFlowStorage, + input_sql_key: str = "SQL", + output_difficulty_key: str = "sql_component_difficulty"): + + self.input_sql_key = input_sql_key + self.output_difficulty_key = output_difficulty_key + dataframe = storage.read("dataframe") + self.check_column(dataframe) + for idx, row in tqdm(dataframe.iterrows(), total=len(dataframe), desc="Processing"): + sql = row.get(self.input_sql_key) + sql_hardness = EvalHardnessLite(sql, self.difficulty_config) + hardness = sql_hardness.run() + dataframe.at[idx, self.output_difficulty_key] = hardness + + self.report_statistics(dataframe) + output_file = storage.write(dataframe) + self.logger.info(f"Extracted answers saved to {output_file}") + + return [self.output_difficulty_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/eval/sql_execution_classifier.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/eval/sql_execution_classifier.py new file mode 100644 index 0000000000000000000000000000000000000000..bacfc62f71264c571aedb2bbcb62d45054b7f7d0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/eval/sql_execution_classifier.py @@ -0,0 +1,318 @@ +import pandas as pd +import os +import re +from concurrent.futures import ThreadPoolExecutor, as_completed +from tqdm import tqdm +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.text2sql.database_manager import DatabaseManager + + +@OPERATOR_REGISTRY.register() +class SQLExecutionClassifier(OperatorABC): + def __init__(self, + llm_serving: LLMServingABC, + database_manager: DatabaseManager, + num_generations: int = 10, + difficulty_thresholds: list = [2, 5, 9], + difficulty_labels: list = ['extra', 'hard', 'medium', 'easy'] + ): + self.llm_serving = llm_serving + self.database_manager = database_manager + self.difficulty_config = { + 'thresholds': difficulty_thresholds, + 'labels': difficulty_labels + } + self.num_generations = num_generations + self.timeout = 5.0 # Default timeout for SQL execution + self.logger = get_logger() + + if self.num_generations <= self.difficulty_config["thresholds"][-1]: + nearest_multiple = ((self.difficulty_config["thresholds"][-1] // 5) + 1) * 5 + self.logger.warning(f"num_generations is less than the last threshold, will be set to {nearest_multiple}") + self.num_generations = nearest_multiple + if len(self.difficulty_config['thresholds']) != len(self.difficulty_config['labels']) - 1: + raise ValueError("Thresholds and labels configuration mismatch") + + @staticmethod + def get_desc(lang): + if lang == "zh": + return ( + "让模型根据自然语言问题、数据库Schema和提示词,多次生成SQL,通过生成SQL的准确率,评估该问题对于模型的难度。\n\n" + "输入参数:\n" + "- input_db_id_key: 输入数据库ID列名\n" + "- input_sql_key: 输入SQL列名\n" + "- input_prompt_key: 输入prompt列名\n\n" + "输出参数:\n" + "- output_difficulty_key: 输出难度列名" + ) + elif lang == "en": + return ( + "This operator evaluates the difficulty of SQL generation for a question based on the accuracy of generated SQLs.\n\n" + "Input parameters:\n" + "- input_db_id_key: The name of the input database ID column\n" + "- input_sql_key: The name of the input SQL column\n" + "- input_prompt_key: The name of the input prompt column\n\n" + "Output parameters:\n" + "- output_difficulty_key: The name of the output difficulty column" + ) + else: + return "SQL execution difficulty evaluator for Text2SQL tasks." + + def check_column(self, dataframe): + required_columns = [self.input_db_id_key, self.input_sql_key, self.input_prompt_key] + missing_columns = [col for col in required_columns if col not in dataframe.columns] + if missing_columns: + raise ValueError(f"Missing required columns: {missing_columns}") + + @staticmethod + def parse_response(response): + pattern = r"```sql\s*(.*?)\s*```" + + sql_blocks = re.findall(pattern, response, re.DOTALL) + + if sql_blocks: + last_sql = sql_blocks[-1].strip() + return last_sql + else: + return "" + + @staticmethod + def execute_model_batch(predicted_sqls_list, ground_truth_list, database_manager, db_ids, idxs, meta_time_out, logger): + comparisons = [] + sql_mapping = {} + + comparison_idx = 0 + for i, (predicted_sqls, ground_truth, db_id, idx) in enumerate(zip(predicted_sqls_list, ground_truth_list, db_ids, idxs)): + for j, predicted_sql in enumerate(predicted_sqls): + comparison = (db_id, predicted_sql, ground_truth) + comparisons.append(comparison) + sql_mapping[comparison_idx] = { + 'original_idx': i, + 'sql_idx': j, + 'idx': idx, + 'sql': predicted_sql + } + comparison_idx += 1 + + try: + batch_results = database_manager.batch_compare_queries(comparisons) + except Exception as e: + logger.error(f"Batch comparison failed: {e}") + results = [] + for i, (predicted_sqls, _, _, idx) in enumerate(zip(predicted_sqls_list, ground_truth_list, db_ids, idxs)): + result_data = [] + for predicted_sql in predicted_sqls: + result_data.append({'res': 0, 'sql': predicted_sql, 'error': 'batch_execution_failed'}) + results.append({"idx": idx, "cnt_true": -1, "results": result_data}) + return results + + results = {} + for i, (predicted_sqls, _, _, idx) in enumerate(zip(predicted_sqls_list, ground_truth_list, db_ids, idxs)): + results[i] = { + "idx": idx, + "cnt_true": 0, + "results": [None] * len(predicted_sqls) + } + + for batch_idx, comparison_result in enumerate(batch_results): + original_idx = sql_mapping[batch_idx]['original_idx'] + sql_idx = sql_mapping[batch_idx]['sql_idx'] + + if comparison_result['result1_success'] and comparison_result['result2_success']: + res = 1 if comparison_result['equal'] else 0 + results[original_idx]['results'][sql_idx] = { + 'res': res, + 'sql': sql_mapping[batch_idx]['sql'], + 'error': None + } + if res == 1: + results[original_idx]['cnt_true'] += 1 + else: + error_msg = "" + if not comparison_result['result1_success']: + error_msg += f"Predicted SQL failed; " + if not comparison_result['result2_success']: + error_msg += f"Ground truth SQL failed" + results[original_idx]['results'][sql_idx] = { + 'res': 0, + 'sql': sql_mapping[batch_idx]['sql'], + 'error': error_msg + } + + return [results[i] for i in sorted(results.keys())] + + def run_sqls_parallel(self, datas, database_manager, num_cpus, meta_time_out): + # pbar = tqdm(total=len(datas), desc="Executing SQLs") + exec_result = [] + + predicted_sqls_list = [] + ground_truth_list = [] + db_ids = [] + idxs = [] + + for i, data_pair in enumerate(datas): + predicted_sqls = data_pair[self.output_predicted_sqls_key] + ground_truth = data_pair[self.input_sql_key] + db_id = data_pair[self.input_db_id_key].replace('\n', '') + db_id = re.sub(r'[^A-Za-z0-9_]', '', db_id) + + predicted_sqls_list.append(predicted_sqls) + ground_truth_list.append(ground_truth) + db_ids.append(db_id) + idxs.append(i) + + # batch_size = max(1, len(datas) // num_cpus) if num_cpus > 1 else len(datas) + batch_size = len(datas) + + def process_batch(batch_data): + batch_predicted_sqls, batch_ground_truth, batch_db_ids, batch_idxs = batch_data + # Note: self.timeout is not defined, so I am removing it from the call + return SQLExecutionClassifier.execute_model_batch( + batch_predicted_sqls, batch_ground_truth, database_manager, + batch_db_ids, batch_idxs, meta_time_out, self.logger + ) + + batches = [] + for i in range(0, len(datas), batch_size): + end_idx = min(i + batch_size, len(datas)) + batch = ( + predicted_sqls_list[i:end_idx], + ground_truth_list[i:end_idx], + db_ids[i:end_idx], + idxs[i:end_idx] + ) + batches.append(batch) + + with ThreadPoolExecutor(max_workers=num_cpus) as executor: + futures = [executor.submit(process_batch, batch) for batch in batches] + + for future in as_completed(futures): + try: + batch_results = future.result() + exec_result.extend(batch_results) + # pbar.update(len(batch_results)) + except Exception as e: + self.logger.warning(f"Error in batch SQL execution: {e}") + # Add default results for failed batches to ensure all indices are covered + batch_idx = futures.index(future) + batch = batches[batch_idx] + batch_idxs = batch[3] # Get the indices for this batch + for idx in batch_idxs: + exec_result.append({ + "idx": idx, + "cnt_true": 0, + "results": [] + }) + # pbar.update(batch_size) + + # pbar.close() + return exec_result + + def sort_results(self, list_of_dicts): + # 增加对空列表的判断 + if not list_of_dicts: + return [] + return sorted(list_of_dicts, key=lambda x: x['idx']) + + def report_statistics(self, dataframe: pd.DataFrame): + # 增加对列是否存在的判断 + if self.output_difficulty_key not in dataframe.columns: + self.logger.warning(f"Column '{self.output_difficulty_key}' not found in dataframe for reporting stats. Skipping.") + return + + counts = dataframe[self.output_difficulty_key].value_counts() + self.logger.info("SQL Difficulty Statistics") + stats = [f"{difficulty.title()}: {counts.get(difficulty, 0)}" for difficulty in ['easy', 'medium', 'hard', 'extra']] + self.logger.info(", ".join(stats)) + + def classify_difficulty(self, score): + if score == -1: + return "gold error" + thresholds = self.difficulty_config['thresholds'] + labels = self.difficulty_config['labels'] + + for i, threshold in enumerate(thresholds): + if score <= threshold: + return labels[i] + return labels[-1] + + def run(self, storage: DataFlowStorage, + input_db_id_key: str = "db_id", + input_sql_key: str = "SQL", + input_prompt_key: str = "prompt", + output_difficulty_key: str = "sql_execution_difficulty" + ): + self.input_sql_key = input_sql_key + self.input_prompt_key = input_prompt_key + self.input_db_id_key = input_db_id_key + self.output_difficulty_key = output_difficulty_key + + self.output_predicted_sqls_key = "_temp_predicted_sqls" + self.output_cnt_true_key = "_temp_cnt_true" + + dataframe = storage.read("dataframe") + self.check_column(dataframe) + input_prompts = dataframe[self.input_prompt_key].tolist() + + self.logger.info(f"Processing {len(input_prompts)} questions, generating {self.num_generations} SQLs each...") + prompts = [q for q in input_prompts for _ in range(self.num_generations)] + responses = self.llm_serving.generate_from_input(prompts, system_prompt="You are a helpful assistant.") + datas = dataframe.to_dict(orient='records') + for i, data in enumerate(datas): + start_idx = i * self.num_generations + end_idx = start_idx + self.num_generations + question_responses = responses[start_idx:end_idx] + parsed_sqls = [] + for response in question_responses: + if response: + # Calling the static method correctly now + parsed_sql = SQLExecutionClassifier.parse_response(response) + parsed_sqls.append(parsed_sql) + else: + parsed_sqls.append("") + + data[self.output_predicted_sqls_key] = parsed_sqls + + exec_result = self.run_sqls_parallel(datas, self.database_manager, + num_cpus=os.cpu_count(), + meta_time_out=5.0) + exec_result = self.sort_results(exec_result) + + for execres in exec_result: + if execres is not None: + idx = execres["idx"] + cnt_true = execres["cnt_true"] + datas[idx][self.output_difficulty_key] = self.classify_difficulty(cnt_true) + datas[idx][self.output_cnt_true_key] = cnt_true + + for data in datas: + data.pop(self.output_predicted_sqls_key, None) + data.pop(self.output_cnt_true_key, None) + + dataframe = pd.DataFrame(datas) + + self.report_statistics(dataframe) + + if self.output_difficulty_key in dataframe.columns: + difficulty_counts = dataframe[self.output_difficulty_key].value_counts() + self.logger.info("\nDifficulty Distribution:") + for difficulty in ['easy', 'medium', 'hard', 'extra', 'gold error']: + count = difficulty_counts.get(difficulty, 0) + dataframe_len = len(dataframe) if dataframe is not None else 0 + if dataframe_len > 0: + percentage = count / dataframe_len * 100 + self.logger.info( + f" {difficulty}: {count} ({percentage:.1f}%)") + else: + self.logger.info(f" {difficulty}: {count} (0.0%)") + else: + self.logger.warning("Skipping difficulty distribution report because the column was not generated.") + + output_file = storage.write(dataframe) + self.logger.info(f"Difficulty classification results saved to {output_file}") + + return [self.output_difficulty_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/filter/__pycache__/sql_executability_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/filter/__pycache__/sql_executability_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f9f9a58f9d41e724ab9c5e1bdb80ad196326952 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/filter/__pycache__/sql_executability_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/filter/__pycache__/sql_execution_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/filter/__pycache__/sql_execution_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..834990541baf5a96070d26eea3b748970ca66ba8 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/filter/__pycache__/sql_execution_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/filter/__pycache__/text2sql_correspondence_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/filter/__pycache__/text2sql_correspondence_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06eb708fb8d1aefe779a7d9ef2b8f572dc14f77f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/filter/__pycache__/text2sql_correspondence_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/filter/sql_executability_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/filter/sql_executability_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..275d218f8e38ca1ee9983eedb7c76414e24fc3f7 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/filter/sql_executability_filter.py @@ -0,0 +1,84 @@ +import re +import os +import pandas as pd +import time +from tqdm import tqdm +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.text2sql.database_manager import DatabaseManager + + +@OPERATOR_REGISTRY.register() +class SQLExecutabilityFilter(OperatorABC): + def __init__(self, database_manager: DatabaseManager): + self.database_manager = database_manager + self.logger = get_logger() + + def filter_select_sql(self, sql): + ''' + remain SELECT-type queries + ''' + sql_wo_comments = re.sub(r'/\*.*?\*/', '', sql, flags=re.DOTALL) + sql_wo_comments = re.sub(r'--.*', '', sql_wo_comments) + sql_wo_comments = sql_wo_comments.strip() + + if sql_wo_comments.lower().startswith("select") or \ + sql_wo_comments.lower().startswith("with"): + return True + return False + + def check_column(self, dataframe): + required_columns = [self.input_sql_key, self.input_db_id_key] + missing_columns = [col for col in required_columns if col not in dataframe.columns] + if missing_columns: + raise ValueError(f"Missing required columns: {missing_columns}") + + def run(self, storage: DataFlowStorage, + input_sql_key: str = "SQL", + input_db_id_key: str = "db_id" + ): + self.input_sql_key = input_sql_key + self.input_db_id_key = input_db_id_key + dataframe = storage.read("dataframe") + self.check_column(dataframe) + + # Record input data count + input_count = len(dataframe) + + # Phase 1: Database check + db_id_need_to_check = dataframe[input_db_id_key].unique() + for db_id in db_id_need_to_check: + if not self.database_manager.database_exists(db_id): + self.logger.warning(f"Database {db_id} not found in registry, please check the database folder") + continue + + self.logger.info(f"Start to filter {len(dataframe)} SQLs") + + # Phase 2: SQL filtering + phase1_mask = dataframe[input_sql_key].apply(self.filter_select_sql) + phase1_df = dataframe[phase1_mask].copy() + + self.logger.info(f"Phase 1 completed: {len(phase1_df)}/{len(dataframe)} SQLs passed initial filter") + + if phase1_df.empty: + output_file = storage.write(phase1_df) + return [] + + sql_triples = list(zip(phase1_df[input_db_id_key].tolist(), + phase1_df[input_sql_key].tolist())) + + # Phase 3: SQL execution + exec_start = time.time() + execution_results = self.database_manager.batch_explain_queries(sql_triples) + + phase2_mask = [r.success for r in execution_results] + result_df = phase1_df[phase2_mask].copy() + + self.logger.info(f"Filter completed, remaining {len(result_df)} SQLs out of {len(phase1_df)} (phase1)") + + output_file = storage.write(result_df) + output_count = len(result_df) + + return [] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/filter/sql_execution_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/filter/sql_execution_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..0f0572f857821f5d8f38f02eb5b8fc7d4ce41713 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/filter/sql_execution_filter.py @@ -0,0 +1,96 @@ +import re +import os +import pandas as pd +from tqdm import tqdm +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.text2sql.database_manager import DatabaseManager + + +@OPERATOR_REGISTRY.register() +class SQLExecutionFilter(OperatorABC): + def __init__(self, database_manager: DatabaseManager): + self.database_manager = database_manager + self.logger = get_logger() + + @staticmethod + def get_desc(lang): + if lang == "zh": + return ( + "对条目进行过滤,在数据库中执行SQL,筛选掉不可执行的条目。\n\n" + "输入参数:\n" + "- input_sql_key: 输入SQL列名\n" + "- input_db_id_key: 输入数据库ID列名\n\n" + ) + elif lang == "en": + return ( + "This operator filters items based on whether the SQL can be executed in the database.\n\n" + "Input parameters:\n" + "- input_sql_key: The name of the input SQL column\n" + "- input_db_id_key: The name of the input database ID column\n\n" + ) + else: + return "SQL execution filter for Text2SQL tasks." + + def filter_select_sql(self, sql): + ''' + remain SELECT-type queries + ''' + sql_wo_comments = re.sub(r'/\*.*?\*/', '', sql, flags=re.DOTALL) + sql_wo_comments = re.sub(r'--.*', '', sql_wo_comments) + sql_wo_comments = sql_wo_comments.strip() + + if sql_wo_comments.lower().startswith("select") or \ + sql_wo_comments.lower().startswith("with"): + return True + return False + + def check_column(self, dataframe): + required_columns = [self.input_sql_key, self.input_db_id_key] + missing_columns = [col for col in required_columns if col not in dataframe.columns] + if missing_columns: + raise ValueError(f"Missing required columns: {missing_columns}") + + def run(self, storage: DataFlowStorage, + input_sql_key: str = "SQL", + input_db_id_key: str = "db_id" + ): + self.input_sql_key = input_sql_key + self.input_db_id_key = input_db_id_key + dataframe = storage.read("dataframe") + self.check_column(dataframe) + + db_id_need_to_check = dataframe[input_db_id_key].unique() + for db_id in db_id_need_to_check: + if not self.database_manager.database_exists(db_id): + self.logger.warning(f"Database {db_id} not found in registry, please check the database folder") + continue + + self.logger.info(f"Start to filter {len(dataframe)} SQLs") + + self.logger.info("Filtering SQLs using select component") + phase1_passed_indices = [] + for idx, row in dataframe.iterrows(): + sql = row[input_sql_key] + if self.filter_select_sql(sql): + phase1_passed_indices.append(idx) + + self.logger.info(f"Phase 1 completed: {len(phase1_passed_indices)}/{len(dataframe)} SQLs passed initial filter") + + phase1_df = dataframe.loc[phase1_passed_indices] + sql_triples = list(zip(phase1_df[input_db_id_key].tolist(), phase1_df[input_sql_key].tolist())) + execution_results = self.database_manager.batch_execute_queries(sql_triples) + + final_indices = [] + for idx, exec_result in enumerate(execution_results): + if exec_result.success: + final_indices.append(phase1_passed_indices[idx]) + + self.logger.info(f"Filter completed, remaining {len(final_indices)} SQLs out of {len(dataframe)} original SQLs") + + result_df = dataframe.loc[final_indices] + + output_file = storage.write(result_df) + return [] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/filter/text2sql_correspondence_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/filter/text2sql_correspondence_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..e8b3a9db0799cbe7355f59e9059f8f4d23ef11da --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/filter/text2sql_correspondence_filter.py @@ -0,0 +1,123 @@ +from typing import Dict, Union +from tqdm import tqdm +import re +import time +from dataflow.prompts.text2sql import Text2SQLCorrespondenceFilterPrompt +from dataflow.core.prompt import prompt_restrict, DIYPromptABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.text2sql.database_manager import DatabaseManager + +@prompt_restrict(Text2SQLCorrespondenceFilterPrompt) + +@OPERATOR_REGISTRY.register() +class Text2SQLCorrespondenceFilter(OperatorABC): + def __init__(self, + llm_serving: LLMServingABC, + database_manager: DatabaseManager, + prompt_template: Union[Text2SQLCorrespondenceFilterPrompt, DIYPromptABC] = None + ): + self.llm_serving = llm_serving + if prompt_template is None: + prompt_template = Text2SQLCorrespondenceFilterPrompt() + self.prompt_template = prompt_template + self.database_manager = database_manager + self.logger = get_logger() + + @staticmethod + def get_desc(lang): + if lang == "zh": + return ( + "对条目进行过滤,检测SQL和自然语言问题是否对应。\n\n" + "输入参数:\n" + "- input_sql_key: 输入SQL列名\n" + "- input_db_id_key: 输入数据库ID列名\n" + "- input_question_key: 输入问题列名\n\n" + ) + elif lang == "en": + return ( + "This operator filters items based on whether the SQL and question are corresponding.\n\n" + "Input parameters:\n" + "- input_sql_key: The name of the input SQL column\n" + "- input_db_id_key: The name of the input database ID column\n" + "- input_question_key: The name of the input question column\n\n" + ) + else: + return "SQL correspondence filter for Text2SQL tasks." + + def _parse_consistency_response(self, response): + if not isinstance(response, str): + self.logger.warning(f"Invalid response type: {type(response)}, expected str. Response: {response}") + return False + response_lower = response.lower() if response else "" + pattern = r"```\s*(.*?)\s*```" + ans_blocks = re.findall(pattern, response_lower, re.DOTALL) + for ans_block in ans_blocks: + if 'yes' in ans_block: + return True + return False + + def check_column(self, dataframe): + required_columns = [self.input_sql_key, self.input_db_id_key, self.input_question_key] + missing_columns = [col for col in required_columns if col not in dataframe.columns] + if missing_columns: + raise ValueError(f"Missing required columns: {missing_columns}") + + def run(self, storage: DataFlowStorage, + input_sql_key: str = "SQL", + input_db_id_key: str = "db_id", + input_question_key: str = "question", + input_evidence_key: str = "evidence", + ): + self.input_sql_key = input_sql_key + self.input_db_id_key = input_db_id_key + self.input_question_key = input_question_key + self.input_evidence_key = input_evidence_key + dataframe = storage.read("dataframe") + self.check_column(dataframe) + total_len = len(dataframe) + + prompts = [] + prompt_to_row_index = [] + for row_index, row in tqdm(dataframe.iterrows(), total=len(dataframe), desc="Processing consistency check"): + sql = row[self.input_sql_key] + question = row.get(self.input_question_key) + evidence = row.get(self.input_evidence_key, "") + if question is None or str(question).strip() == "": + continue + if evidence: + question = f"{question}\n{evidence}" + db_id = row[self.input_db_id_key] + + create_statements, _ = self.database_manager.get_create_statements_and_insert_statements( + db_id + ) + + db_details = "\n\n".join(create_statements) + prompt = self.prompt_template.build_prompt(question, sql, db_details) + prompts.append(prompt) + prompt_to_row_index.append(row_index) + responses = self.llm_serving.generate_from_input(prompts, "") + final_valid_indices = [] + for idx, response in enumerate(responses): + conclusion = self._parse_consistency_response(response) + if conclusion and idx < len(prompt_to_row_index): + final_valid_indices.append(prompt_to_row_index[idx]) + + correspondence_passed = len(final_valid_indices) + self.logger.info(f"Correspondence check results: {correspondence_passed} passed, total {total_len}") + + if final_valid_indices: + filtered_dataframe = dataframe.iloc[final_valid_indices].copy() + else: + self.logger.warning("No data passed all filters. Returning empty dataset.") + filtered_dataframe = dataframe.iloc[0:0].copy() + + output_file = storage.write(filtered_dataframe) + output_count = len(filtered_dataframe) + + self.logger.info(f"Filtered dataset saved to {output_file}") + return [] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/__pycache__/sql_by_column_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/__pycache__/sql_by_column_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b70cb6bbf61496a0895f803f46084f4842b638ce Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/__pycache__/sql_by_column_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/__pycache__/sql_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/__pycache__/sql_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..baa72514e22079613c6230d5f151a1ab0e5211b0 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/__pycache__/sql_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/__pycache__/sql_variation_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/__pycache__/sql_variation_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..128875c67113d0641a4fd43f2e004340b5844659 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/__pycache__/sql_variation_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/__pycache__/text2sql_cot_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/__pycache__/text2sql_cot_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19d7decd47c251dbdf3a9966319d7f6b3291e6f7 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/__pycache__/text2sql_cot_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/__pycache__/text2sql_cot_voting_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/__pycache__/text2sql_cot_voting_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67481741f4cc5d8444f752c65c0d836377a25296 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/__pycache__/text2sql_cot_voting_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/__pycache__/text2sql_prompt_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/__pycache__/text2sql_prompt_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a74b82a14d74c432f96b32c7006c5b8b75e35b5 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/__pycache__/text2sql_prompt_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/__pycache__/text2sql_question_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/__pycache__/text2sql_question_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b133cd80a1a32e9f6884c0211ec2e451910122d8 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/__pycache__/text2sql_question_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/sql_by_column_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/sql_by_column_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..dc39ec19149d6e99484fce26324ab4103e734c36 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/sql_by_column_generator.py @@ -0,0 +1,118 @@ +import random +import pandas as pd +import re +from dataflow.prompts.text2sql import SelectSQLGeneratorPrompt +from dataflow.prompts.text2sql import SelectVecSQLGeneratorPrompt +from dataflow.core.prompt import prompt_restrict, DIYPromptABC +from tqdm import tqdm +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.text2sql.database_manager import DatabaseManager + +from typing import Union + +@prompt_restrict(SelectSQLGeneratorPrompt, SelectVecSQLGeneratorPrompt) + +@OPERATOR_REGISTRY.register() +class SQLByColumnGenerator(OperatorABC): + def __init__(self, + llm_serving: LLMServingABC, + database_manager: DatabaseManager, + generate_num: int = 5, + prompt_template: Union[SelectSQLGeneratorPrompt, SelectVecSQLGeneratorPrompt, DIYPromptABC] = None + ): + self.llm_serving = llm_serving + self.logger = get_logger() + self.database_manager = database_manager + self.generate_num = generate_num + if prompt_template is None: + self.prompt_template = SelectSQLGeneratorPrompt() + else: + self.prompt_template = prompt_template + + @staticmethod + def get_desc(lang): + if lang == "zh": + return ( + "基于数据库信息,合成SQL,覆盖不同的难度、数据库Schema、函数和风格。\n\n" + "输出参数:\n" + "- output_sql_key: 输出SQL列名\n" + "- output_db_id_key: 数据库ID列名\n\n" + ) + elif lang == "en": + return ( + "This operator synthesizes SQL based on database information, covering different complexities, schemas, functions, and styles.\n\n" + "Output parameters:\n" + "- output_sql_key: The name of the output SQL column\n" + "- output_db_id_key: The name of the database ID column\n\n" + ) + else: + return "SQL generator for Text2SQL tasks." + + def parse_response(self, response): + if not response: + return "" + pattern = r"```sql\s*(.*?)\s*```" + sql_blocks = re.findall(pattern, response, re.DOTALL) + + if sql_blocks: + last_sql = sql_blocks[-1].strip() + return last_sql + else: + self.logger.warning("No SQL code block found in the response") + return "" + + def run(self, storage: DataFlowStorage, + output_sql_key: str = "SQL", + output_db_id_key: str = "db_id" + ): + self.output_sql_key = output_sql_key + self.output_db_id_key = output_db_id_key + raw_dataframe = storage.read("dataframe") + + db_names = self.database_manager.list_databases() + prompts = [] + self.logger.info(f"Generating {self.generate_num} SQLs for each database") + + for db_name in tqdm(db_names, desc="Processing Databases"): + special_col_count = self.database_manager.get_number_of_special_column(db_name) + sum_generate_num = special_col_count * self.generate_num + self.logger.info(f"Database '{db_name}' has {special_col_count} special columns. " + f"Generating {sum_generate_num} SQLs.") + + create_statements, insert_statements = self.database_manager.get_create_statements_and_insert_statements(db_name) + + for _ in range(sum_generate_num): + prompt = self.prompt_template.build_prompt( + insert_statements=insert_statements, + create_statements=create_statements, + db_engine=self.database_manager.db_type + ) + prompts.append({"prompt": prompt, "db_id": db_name}) + + if not prompts: + self.logger.warning("No prompts generated, please check the database path and file") + return [self.output_sql_key, self.output_db_id_key] + + db_ids = [data["db_id"] for data in prompts] + prompt_list = [data["prompt"] for data in prompts] + + try: + responses = self.llm_serving.generate_from_input(prompt_list, "") + except Exception as e: + self.logger.error(f"Failed to generate SQLs: {e}") + responses = [""] * len(prompt_list) + + results = [ + { + self.output_db_id_key: db_id, + self.output_sql_key: self.parse_response(response) + } + for db_id, response in zip(db_ids, responses) + ] + + output_file = storage.write(pd.DataFrame(results)) + return [self.output_sql_key, self.output_db_id_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/sql_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/sql_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..922baffda5cfad8896608019de2f8a8d152248f0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/sql_generator.py @@ -0,0 +1,117 @@ +import random +import pandas as pd +import re +from dataflow.prompts.text2sql import SelectSQLGeneratorPrompt +from dataflow.prompts.text2sql import SelectVecSQLGeneratorPrompt +from dataflow.core.prompt import prompt_restrict, DIYPromptABC +from tqdm import tqdm +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.text2sql.database_manager import DatabaseManager +from typing import Union + +@prompt_restrict(SelectSQLGeneratorPrompt, SelectVecSQLGeneratorPrompt) + +@OPERATOR_REGISTRY.register() +class SQLGenerator(OperatorABC): + def __init__(self, + llm_serving: LLMServingABC, + database_manager: DatabaseManager, + generate_num: int = 300, + prompt_template: Union[SelectSQLGeneratorPrompt, SelectVecSQLGeneratorPrompt, DIYPromptABC] = None + ): + self.llm_serving = llm_serving + self.logger = get_logger() + self.database_manager = database_manager + self.generate_num = generate_num + if prompt_template is None: + self.prompt_template = SelectSQLGeneratorPrompt() + else: + self.prompt_template = prompt_template + + @staticmethod + def get_desc(lang): + if lang == "zh": + return ( + "基于数据库信息,合成SQL,覆盖不同的难度、数据库Schema、函数和风格。\n\n" + "输出参数:\n" + "- output_sql_key: 输出SQL列名\n" + "- output_db_id_key: 数据库ID列名\n\n" + ) + elif lang == "en": + return ( + "This operator synthesizes SQL based on database information, covering different complexities, schemas, functions, and styles.\n\n" + "Output parameters:\n" + "- output_sql_key: The name of the output SQL column\n" + "- output_db_id_key: The name of the database ID column\n\n" + ) + else: + return "SQL generator for Text2SQL tasks." + + def parse_response(self, response): + if not response: + return "" + pattern = r"```sql\s*(.*?)\s*```" + sql_blocks = re.findall(pattern, response, re.DOTALL) + + if sql_blocks: + last_sql = sql_blocks[-1].strip() + return last_sql + else: + self.logger.warning("No SQL code block found in the response") + return "" + + def run(self, storage: DataFlowStorage, + output_sql_key: str = "SQL", + output_db_id_key: str = "db_id", + output_sql_complexity_key: str = "sql_complexity_type" + ): + self.output_sql_key = output_sql_key + self.output_db_id_key = output_db_id_key + self.output_sql_complexity_key = output_sql_complexity_key + raw_dataframe = storage.read("dataframe") + + db_names = self.database_manager.list_databases() + prompts = [] + self.logger.info(f"Generating {self.generate_num} SQLs for each database") + + for db_name in tqdm(db_names, desc="Processing Databases"): + sum_generate_num = self.generate_num + create_statements, insert_statements = self.database_manager.get_create_statements_and_insert_statements(db_name) + + for _ in range(sum_generate_num): + prompt, sql_complexity_type = self.prompt_template.build_prompt( + insert_statements=insert_statements, + create_statements=create_statements, + db_engine=self.database_manager.db_type + ) + prompts.append({"prompt": prompt, "db_id": db_name, "sql_complexity_type": sql_complexity_type}) + + if not prompts: + self.logger.warning("No prompts generated, please check the database path and file") + return [self.output_sql_key, self.output_db_id_key, self.output_sql_complexity_key] + + db_ids = [data["db_id"] for data in prompts] + prompt_list = [data["prompt"] for data in prompts] + sql_complexity_types = [data["sql_complexity_type"] for data in prompts] + + try: + responses = self.llm_serving.generate_from_input(prompt_list, "") + except Exception as e: + self.logger.error(f"Failed to generate SQLs: {e}") + responses = [""] * len(prompt_list) + + results = [ + { + self.output_db_id_key: db_id, + self.output_sql_key: self.parse_response(response), + self.output_sql_complexity_key: sql_complexity_type + } + for db_id, response, sql_complexity_type in zip(db_ids, responses, sql_complexity_types) + ] + + output_file = storage.write(pd.DataFrame(results)) + return [self.output_sql_key, self.output_db_id_key, self.output_sql_complexity_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/sql_variation_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/sql_variation_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..59311747dae6cbd8a90e7ee8e8ab4f50ba2c40bc --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/sql_variation_generator.py @@ -0,0 +1,143 @@ +import random +import pandas as pd +import re +from dataflow.prompts.text2sql import SQLVariationGeneratorPrompt +from dataflow.core.prompt import prompt_restrict, DIYPromptABC +from tqdm import tqdm +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.storage import (DataFlowStorage, RESERVED_SYS_FIELD_LIST, RESERVED_USER_FIELD_LIST, + SYS_FIELD_PREFIX, USER_FIELD_PREFIX) +from dataflow.utils.text2sql.database_manager import DatabaseManager +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC + +from typing import Union + +@prompt_restrict(SQLVariationGeneratorPrompt) + +@OPERATOR_REGISTRY.register() +class SQLVariationGenerator(OperatorABC): + def __init__(self, llm_serving: LLMServingABC, + database_manager: DatabaseManager, + num_variations: int = 10, + prompt_template: Union[SQLVariationGeneratorPrompt, DIYPromptABC] = None + ): + self.llm_serving = llm_serving + self.logger = get_logger() + self.database_manager = database_manager + if prompt_template is None: + self.prompt_template = SQLVariationGeneratorPrompt() + else: + self.prompt_template = prompt_template + self.num_variations = num_variations + + @staticmethod + def get_desc(lang): + if lang == "zh": + return ( + "对于每个条目,基于已有的SQL,指导模型生成SQL的变种,即在原有SQL的基础上,进行数据替换、函数变换、难度变换等操作,生成更加丰富的SQL。\n\n" + "输入参数:\n" + "- input_sql_key: SQL列名\n" + "- input_db_id_key: 数据库ID列名\n\n" + ) + elif lang == "en": + return ( + "This operator generates variations of SQL based on existing SQLs, including data replacement, function transformation, and difficulty transformation, to generate more diverse SQLs.\n\n" + "Input parameters:\n" + "- input_sql_key: The name of the SQL column\n" + "- input_db_id_key: The name of the database ID column\n\n" + ) + else: + return "SQL variation generator for Text2SQL tasks." + + def parse_response(self, response): + if not isinstance(response, str): + self.logger.warning(f"Invalid response type: {type(response)}, expected str. Response: {response}") + return "" + if not response: + return "" + + pattern = r"```sql\s*(.*?)\s*```" + sql_blocks = re.findall(pattern, response, re.DOTALL) + + if sql_blocks: + last_sql = sql_blocks[-1].strip() + return last_sql + else: + self.logger.warning("No SQL code block found in the response") + return "" + + def check_column(self, dataframe): + required_columns = [self.input_sql_key, self.input_db_id_key] + missing_columns = [col for col in required_columns if col not in dataframe.columns] + if missing_columns: + raise ValueError(f"Missing required columns: {missing_columns}") + + def run(self, storage: DataFlowStorage, + input_sql_key: str = "SQL", + input_db_id_key: str = "db_id", + output_sql_variation_type_key: str = "sql_variation_type" + ): + self.input_sql_key = input_sql_key + self.input_db_id_key = input_db_id_key + + dataframe = storage.read("dataframe") + self.check_column(dataframe) + self.output_sql_variation_type_key = output_sql_variation_type_key + + prompts_and_metadata = [] + # Phase 1: Prompt building + for _, row in tqdm(dataframe.iterrows(), total=len(dataframe), desc="Generating SQL Variations"): + try: + create_statements, insert_statements = self.database_manager.get_create_statements_and_insert_statements(row[self.input_db_id_key]) + original_sql = row[self.input_sql_key] + + for _ in range(self.num_variations): + prompt, variation_type = self.prompt_template.build_prompt( + original_sql=original_sql, + create_statements=create_statements, + insert_statements=insert_statements, + db_engine=self.database_manager.db_type + ) + + prompts_and_metadata.append(( + prompt, + row[self.input_db_id_key], + variation_type, + row.to_dict() + )) + + except Exception as e: + self.logger.error(f"Error processing database {row[self.input_db_id_key]}: {e}") + continue + + new_rows = [] + if prompts_and_metadata: + try: + prompts = [x[0] for x in prompts_and_metadata] + responses = self.llm_serving.generate_from_input(prompts, system_prompt="") + + # Phase 2: Post-processing + for i, ((prompt, db_id, variation_type, original_row), response) in enumerate(zip(prompts_and_metadata, responses)): + sql = self.parse_response(response) + if sql: + new_row = {col: None for col in dataframe.columns} + + new_row[self.input_db_id_key] = db_id + new_row[self.input_sql_key] = sql + new_row[output_sql_variation_type_key] = variation_type + + new_rows.append(new_row) + + except Exception as e: + self.logger.error(f"Error generating SQL variations: {e}") + + if new_rows: + dataframe = pd.DataFrame(new_rows) + + output_file = storage.write(dataframe) + output_count = len(dataframe) + + self.logger.info(f"Generated {output_count} records") + return [self.input_sql_key, self.input_db_id_key, self.output_sql_variation_type_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/text2sql_cot_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/text2sql_cot_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..f67bb946b35a53b32beaff17153476723293c571 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/text2sql_cot_generator.py @@ -0,0 +1,141 @@ +from typing import Dict, Optional, Tuple, List, Union, Any +import pandas as pd +import re +import random +from collections import defaultdict +from dataflow.prompts.text2sql import Text2SQLCotGeneratorPrompt +from dataflow.core.prompt import DIYPromptABC, prompt_restrict +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.core import OperatorABC, LLMServingABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.text2sql.database_manager import DatabaseManager + + +@prompt_restrict(Text2SQLCotGeneratorPrompt) +@OPERATOR_REGISTRY.register() +class Text2SQLCoTGenerator(OperatorABC): + def __init__( + self, + llm_serving: LLMServingABC, + database_manager: DatabaseManager, + prompt_template: Union[Text2SQLCotGeneratorPrompt, DIYPromptABC] = None, + sampling_num: int = 3, + ): + self.llm_serving = llm_serving + self.database_manager = database_manager + self.prompt_template = prompt_template or Text2SQLCotGeneratorPrompt() + self.logger = get_logger() + + self.sampling_num = int(sampling_num) + if self.sampling_num < 1: + raise ValueError("sampling_num must be >= 1") + + @staticmethod + def get_desc(lang): + if lang == "zh": + return ( + "对于每个条目,生成从自然语言问题和数据库Schema到SQL的CoT长链路推理过程。生成sampling_num条推理轨迹,但是不做验证" + "输入参数:\n" + "- input_sql_key: 输入SQL列名\n" + "- input_question_key: 输入问题列名\n" + "- input_db_id_key: 输入数据库ID列名\n\n" + "输出参数:\n" + "- output_cot_key: 输出CoT列名" + ) + elif lang == "en": + return ( + "For each item, generate a CoT long chain of reasoning from natural language question and database Schema to SQL. Generate sampling_num reasoning trajectories, but do not verify." + "Input parameters:\n" + "- input_sql_key: The name of the input SQL column\n" + "- input_question_key: The name of the input question column\n" + "- input_db_id_key: The name of the input database ID column\n\n" + "Output parameters:\n" + "- output_cot_key: The name of the output CoT column" + ) + else: + return "CoT generator for Text2SQL tasks." + + def check_column(self, dataframe): + required_columns = [self.input_sql_key, self.input_db_id_key, self.input_question_key] + missing = [c for c in required_columns if c not in dataframe.columns] + if missing: + raise ValueError(f"Missing required columns: {missing}") + + def extract_sql(self, response: str) -> str: + if not isinstance(response, str): + self.logger.warning(f"Invalid response type: {type(response)}, expected str. Response: {response}") + return "" + pattern = r"```sql\s*(.*?)\s*```" + blocks = re.findall(pattern, response, re.DOTALL | re.IGNORECASE) + if blocks: + return blocks[-1].strip() + return "" + + def _build_prompt(self, item: Dict[str, Any]) -> str: + db_id = item.get(self.input_db_id_key) + question = item.get(self.input_question_key) + gold_sql = item.get(self.input_sql_key) + evidence = item.get(self.input_evidence_key, "") + + create_statements, _ = self.database_manager.get_create_statements_and_insert_statements(db_id) + schema_str = "\n\n".join(create_statements) + return self.prompt_template.build_prompt(schema_str, question, gold_sql, evidence) + + def _process_items(self, items_with_index: List[Tuple[int, Dict]]) -> List[Dict]: + prompts = [] + mapping = [] + for orig_idx, item in items_with_index: + prompt = self._build_prompt(item) + for _ in range(self.sampling_num): + prompts.append(prompt) + mapping.append((orig_idx, item)) + responses = self.llm_serving.generate_from_input(prompts, "") + grouped: Dict[int, List[str]] = defaultdict(list) + for (orig_idx, item), resp in zip(mapping, responses): + grouped[orig_idx].append(resp) + + results = [] + for orig_idx, item in items_with_index: + results.append({ + **item, + "__orig_index": orig_idx, + "cot_responses": grouped.get(orig_idx, []), + }) + return results + + def run( + self, + storage: DataFlowStorage, + input_sql_key: str = "SQL", + input_question_key: str = "question", + input_db_id_key: str = "db_id", + input_evidence_key: str = "evidence", + output_cot_key: str = "cot_reasoning", + ): + self.input_question_key = input_question_key + self.input_sql_key = input_sql_key + self.input_db_id_key = input_db_id_key + self.input_evidence_key = input_evidence_key + self.output_cot_key = output_cot_key + + self.logger.info("Starting CoT generation (scheme C voting)...") + raw_df = storage.read("dataframe") + self.check_column(raw_df) + + items = raw_df.to_dict("records") + items_with_index = list(enumerate(items)) + + results = self._process_items(items_with_index) + + if not results: + self.logger.warning("No CoT results generated.") + return [] + + out_df = pd.DataFrame(results).sort_values("__orig_index").drop(columns=["__orig_index"]) + output_file = storage.write(out_df) + output_count = len(out_df) + self.logger.info(f"CoT responses generation completed, saved to {output_file}") + self.logger.info(f"Processed {output_count} items, original {len(items)} items") + + return ["cot_responses"] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/text2sql_cot_voting_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/text2sql_cot_voting_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..a32e30acbf2997fdd8f28a8a06dde2820d33b6a6 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/text2sql_cot_voting_generator.py @@ -0,0 +1,194 @@ +import re +import random +from collections import defaultdict +from typing import Dict, List, Optional, Any, Tuple + +import pandas as pd + +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.text2sql.database_manager import DatabaseManager +from dataflow.utils.text2sql.base import QueryResult + + +def _parse_response(response: str) -> str: + if not isinstance(response, str): + return "" + pattern = r"```sql\s*(.*?)\s*```" + blocks = re.findall(pattern, response, re.DOTALL | re.IGNORECASE) + if blocks: + sql = blocks[-1].strip() + if sql: + return sql + for pat in [ + r"```SQL\s*(.*?)\s*```", + r"SELECT.*?FROM", + ]: + matches = re.findall(pat, response, re.DOTALL | re.IGNORECASE) + if matches: + sql = matches[0].strip() if isinstance(matches[0], str) else matches[0] + if sql: + return sql + return "" + + +def _result_to_signature(result: QueryResult): + if not result.success or not result.data: + return None + columns = result.columns or [] + if not columns and result.data: + columns = list(result.data[0].keys()) + return frozenset( + tuple(row.get(c) for c in columns) for row in result.data + ) + + +def _tie_break(candidates: List[Dict[str, Any]], tie_breaker: str = "shortest_sql") -> Dict[str, Any]: + if not candidates: + raise ValueError("tie_break candidates empty") + if tie_breaker == "random": + return random.choice(candidates) + return min(candidates, key=lambda x: len(x.get("sql") or "")) + + +def _vote_select( + candidates: List[Dict[str, Any]], + tie_breaker: str = "shortest_sql", +) -> Optional[Dict[str, Any]]: + valid = [c for c in candidates if c.get("is_valid")] + v = len(valid) + if v == 0: + return None + if v == 1: + return valid[0] + + buckets = defaultdict(list) + for c in valid: + buckets[c["signature"]].append(c) + + best_sig = max(buckets, key=lambda s: len(buckets[s])) + best_bucket = buckets[best_sig] + max_votes = len(best_bucket) + + if v == 2: + if max_votes == 2: + return random.choice(best_bucket) + return _tie_break(valid, tie_breaker) + + if max_votes >= 2: + return random.choice(best_bucket) + return _tie_break(valid, tie_breaker) + + +@OPERATOR_REGISTRY.register() +class Text2SQLCoTVotingGenerator(OperatorABC): + """ + After Text2SQLCoTGenerator, execute SQL for each cot_responses and vote by execution consistency to select final cot_reasoning. + """ + + def __init__(self, database_manager: DatabaseManager): + self.database_manager = database_manager + self.tie_breaker = "shortest_sql" + self.logger = get_logger() + + @staticmethod + def get_desc(lang): + if lang == "zh": + return ( + "After Text2SQLCoTGenerator, execute SQL for each cot_responses and vote by execution consistency to select final cot_reasoning.\n\n" + "输入参数:\n" + "- input_cot_responses_key: 输入候选 CoT 列表列名(默认 cot_responses)\n" + "- input_db_id_key: 输入数据库 ID 列名\n\n" + "输出参数:\n" + "- output_cot_key: 输出最终 CoT 列名(默认 cot_reasoning)" + ) + elif lang == "en": + return ( + "Execute SQL from each cot_responses and vote by execution consistency to select final cot_reasoning. " + "Input parameters:\n" + "- input_cot_responses_key: The name of the input cot_responses column\n" + "- input_db_id_key: The name of the input database ID column\n\n" + "Output parameters:\n" + "- output_cot_key: The name of the output cot_reasoning column" + ) + return "CoT voting by execution-consistency." + + def check_column(self, dataframe: pd.DataFrame) -> None: + required = [self.input_cot_responses_key, self.input_db_id_key] + missing = [c for c in required if c not in dataframe.columns] + if missing: + raise ValueError(f"Missing required columns: {missing}") + + def run( + self, + storage: DataFlowStorage, + input_cot_responses_key: str = "cot_responses", + input_db_id_key: str = "db_id", + output_cot_key: str = "cot_reasoning", + + ): + self.input_cot_responses_key = input_cot_responses_key + self.input_db_id_key = input_db_id_key + self.output_cot_key = output_cot_key + + self.logger.info("Starting CoT voting (execution-consistency)...") + raw_df = storage.read("dataframe") + self.check_column(raw_df) + drop_cot_responses = True + + items = raw_df.to_dict("records") + + queries: List[Tuple[str, str]] = [] + mapping: List[Tuple[int, int, str, str]] = [] + + for item_idx, item in enumerate(items): + cot_responses = item.get(self.input_cot_responses_key, []) + if not isinstance(cot_responses, list): + continue + db_id = item.get(self.input_db_id_key) + if not db_id: + continue + for resp_idx, resp in enumerate(cot_responses): + sql = _parse_response(resp) + if sql: + queries.append((str(db_id).strip(), sql)) + mapping.append((item_idx, resp_idx, sql, resp)) + + if queries: + query_results = self.database_manager.batch_execute_queries(queries) + else: + query_results = [] + item_candidates: Dict[int, List[Dict[str, Any]]] = defaultdict(list) + + for (item_idx, _resp_idx, sql, cot), result in zip(mapping, query_results): + signature = _result_to_signature(result) + is_valid = result.success + item_candidates[item_idx].append({ + "cot": cot, + "sql": sql, + "signature": signature, + "is_valid": is_valid, + }) + + output_items = [] + for item_idx, item in enumerate(items): + candidates = item_candidates.get(item_idx, []) + chosen = _vote_select(candidates, self.tie_breaker) + + if chosen is None: + cot_responses = item.get(self.input_cot_responses_key, []) + chosen_cot = cot_responses[0] if cot_responses else "" + else: + chosen_cot = chosen["cot"] + + out_item = {k: v for k, v in item.items() if k != self.input_cot_responses_key} if drop_cot_responses else dict(item) + out_item[self.output_cot_key] = chosen_cot + output_items.append(out_item) + + out_df = pd.DataFrame(output_items) + output_file = storage.write(out_df) + self.logger.info(f"CoT voting completed, saved to {output_file}, {len(output_items)} items") + + return [self.output_cot_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/text2sql_prompt_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/text2sql_prompt_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..1c9c8be4c389b56f019c699c296d41bc368d6fd6 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/text2sql_prompt_generator.py @@ -0,0 +1,111 @@ +import pandas as pd +import re +import time +from tqdm import tqdm +from typing import Dict, Optional, Union +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.prompts.text2sql import Text2SQLPromptGeneratorPrompt, Text2VecSQLPromptGeneratorPrompt +from dataflow.core.prompt import prompt_restrict, DIYPromptABC +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.text2sql.database_manager import DatabaseManager + +@prompt_restrict(Text2SQLPromptGeneratorPrompt, Text2VecSQLPromptGeneratorPrompt) + +@OPERATOR_REGISTRY.register() +class Text2SQLPromptGenerator(OperatorABC): + def __init__(self, + database_manager: DatabaseManager, + prompt_template: Union[Text2SQLPromptGeneratorPrompt, Text2VecSQLPromptGeneratorPrompt, DIYPromptABC] = None + ): + + if prompt_template is None: + prompt_template = Text2SQLPromptGeneratorPrompt() + self.prompt_template = prompt_template + + self.logger = get_logger() + self.database_manager = database_manager + + @staticmethod + def get_desc(lang): + if lang == "zh": + return ( + "从数据库提取Schema信息,结合自然语言问题生成提示词。其中提示词模版支持自定义。\n\n" + "输入参数:\n" + "- input_question_key: 问题列名\n" + "- input_db_id_key: 数据库ID列名\n" + "- output_prompt_key: 输出prompt列名\n\n" + "输出参数:\n" + "- output_prompt_key: 生成的prompt" + ) + elif lang == "en": + return ( + "This operator generates prompts for Text2SQL tasks by extracting schema information from databases and combining it with natural language questions. The prompt template can be customized.\n\n" + "Input parameters:\n" + "- input_question_key: The name of the question column\n" + "- input_db_id_key: The name of the database ID column\n" + "- output_prompt_key: The name of the output prompt column\n\n" + "Output parameters:\n" + "- output_prompt_key: The generated prompt" + ) + else: + return "Prompt generator for Text2SQL tasks." + + def get_create_statements_and_insert_statements(self, db_id: str) -> str: + return self.database_manager.get_create_statements_and_insert_statements(db_id) + + def run(self, storage: DataFlowStorage, + input_question_key: str = "question", + input_db_id_key: str = "db_id", + input_evidence_key: str = "evidence", + output_prompt_key: str = "prompt" + ): + self.input_question_key = input_question_key + self.input_db_id_key = input_db_id_key + self.input_evidence_key = input_evidence_key + self.output_prompt_key = output_prompt_key + + self.logger.info("Starting prompt generation...") + raw_dataframe = storage.read("dataframe") + + required_cols = [input_question_key, input_db_id_key] + missing_cols = [col for col in required_cols if col not in raw_dataframe.columns] + if missing_cols: + raise ValueError(f"Missing required columns: {missing_cols}") + + items = raw_dataframe.to_dict('records') + final_results = [] + + for item in tqdm(items, desc="Generating prompts"): + db_id = item[self.input_db_id_key] + question = item[self.input_question_key] + evidence = item.get(self.input_evidence_key, "") + + db_id = str(db_id).replace('\n', '').replace('\r', '').strip() + + db_details = self.database_manager.get_db_details(db_id) + + prompt = self.prompt_template.build_prompt( + db_details=db_details, + question=question, + evidence=evidence, + db_engine=self.database_manager.db_type + ) + + result = { + **item, + self.output_prompt_key: prompt + } + final_results.append(result) + + if len(final_results) != len(items): + self.logger.warning(f"Results count mismatch: expected {len(items)}, got {len(final_results)}") + + output_df = pd.DataFrame(final_results) + output_file = storage.write(output_df) + output_count = len(output_df) + + self.logger.info(f"Prompt generation completed, saved to {output_file}") + + return [self.output_prompt_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/text2sql_question_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/text2sql_question_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..f2ea8726741fdc21bc92ef9a2ffb48a317d05c05 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text2sql/generate/text2sql_question_generator.py @@ -0,0 +1,244 @@ +import random +import re +import pandas as pd +from tqdm import tqdm +import numpy as np +from scipy.spatial.distance import cdist +from dataflow.prompts.text2sql import Text2SQLQuestionGeneratorPrompt, Text2VecSQLQuestionGeneratorPrompt +from dataflow.core.prompt import prompt_restrict, DIYPromptABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.core import OperatorABC, LLMServingABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.text2sql.database_manager import DatabaseManager +from typing import Union + +@prompt_restrict(Text2SQLQuestionGeneratorPrompt, Text2VecSQLQuestionGeneratorPrompt) + +@OPERATOR_REGISTRY.register() +class Text2SQLQuestionGenerator(OperatorABC): + def __init__(self, + llm_serving: LLMServingABC, + embedding_serving: LLMServingABC, + database_manager: DatabaseManager, + question_candidates_num: int = 5, + prompt_template: Union[Text2SQLQuestionGeneratorPrompt, Text2VecSQLQuestionGeneratorPrompt, DIYPromptABC] = None + ): + + self.llm_serving = llm_serving + self.embedding_serving = embedding_serving + self.database_manager = database_manager + if prompt_template is None: + self.prompt_template = Text2SQLQuestionGeneratorPrompt() + else: + self.prompt_template = prompt_template + self.logger = get_logger() + self.question_candidates_num = question_candidates_num + + @staticmethod + def get_desc(lang): + if lang == "zh": + return ( + "对于每个条目,如果自然语言问题为空,生成SQL对应的自然语言问题。为保证正确,生成多个候选问题,并选择最优的。\n\n" + "输入参数:\n" + "- input_sql_key: 输入SQL列名\n" + "- input_db_id_key: 数据库ID列名\n\n" + "输出参数:\n" + "- output_question_key: 输出问题列名" + ) + elif lang == "en": + return ( + "This operator generates natural language questions for Text2SQL tasks if the natural language question is empty. Multiple candidate questions are generated to ensure correctness.\n\n" + "Input parameters:\n" + "- input_sql_key: The name of the input SQL column\n" + "- input_db_id_key: The name of the database ID column\n\n" + "Output parameters:\n" + "- output_question_key: The name of the output question column" + ) + else: + return "Question generator for Text2SQL tasks." + + def extract_column_descriptions(self, create_statements): + column_name2column_desc = dict() + pattern = r'"(\w+)"\s+\w+\s*/\*\s*(.*?)\s*\*/' + + for create_statement in create_statements: + matches = re.findall(pattern, create_statement) + + for column_name, description in matches: + column_name = column_name.lower() + if column_name not in column_name2column_desc: + column_name2column_desc[column_name] = description + + return column_name2column_desc + + def parse_llm_response(self, response, style): + # 检查 response 是否为字符串类型 + if not isinstance(response, str): + self.logger.warning(f"Invalid response type: {type(response)}, expected str. Response: {response}") + return None + + explanation_pattern = re.compile(r'\[EXPLANATION-START\](.*?)\[EXPLANATION-END\]', re.DOTALL) + question_pattern = re.compile(r'\[QUESTION-START\](.*?)\[QUESTION-END\]', re.DOTALL) + external_knowledge_pattern = re.compile(r'\[EXTERNAL-KNOWLEDGE-START\](.*?)\[EXTERNAL-KNOWLEDGE-END\]', re.DOTALL) + + explanation_match = explanation_pattern.search(response) + question_match = question_pattern.search(response) + external_knowledge_match = external_knowledge_pattern.search(response) + + explanation_content = explanation_match.group(1).strip() if explanation_match else "" + question_content = question_match.group(1).strip() if question_match else "" + external_knowledge_content = external_knowledge_match.group(1).strip() if external_knowledge_match else "" + + if explanation_content == "" or question_content == "": + return None + else: + return { + "question": question_content.strip(), + "external_knowledge": external_knowledge_content.strip() + } + + def select_best_question(self, question_candidates, start_idx, embeddings): + if len(question_candidates) == 0: + return None + elif len(question_candidates) == 1: + return question_candidates[0] + elif len(question_candidates) == 2: + return random.sample(question_candidates, 1)[0] + else: + end_idx = start_idx + len(question_candidates) + candidate_embeddings = embeddings[start_idx:end_idx] + distance_matrix = cdist(candidate_embeddings, candidate_embeddings, metric='cosine') + distance_sums = distance_matrix.sum(axis=1) + min_index = np.argmin(distance_sums) + return question_candidates[min_index] + + def run(self, storage: DataFlowStorage, + input_sql_key: str = "SQL", + input_db_id_key: str = "db_id", + output_question_key: str = "question", + output_evidence_key: str = "evidence" + ): + self.input_sql_key = input_sql_key + self.input_db_id_key = input_db_id_key + self.output_question_key = output_question_key + self.output_evidence_key = output_evidence_key + raw_dataframe = storage.read("dataframe") + + existing_data = [] + raw_data = [] + + if self.output_question_key in raw_dataframe.columns: + for _, row in raw_dataframe.iterrows(): + if pd.notna(row.get(self.output_question_key)) and row.get(self.output_question_key) is not None: + existing_data.append(row.to_dict()) + else: + raw_data.append(row.to_dict()) + else: + raw_data = [row.to_dict() for _, row in raw_dataframe.iterrows()] + + # Phase 1: Database schema extraction + db_ids = list(set([data[self.input_db_id_key] for data in raw_data])) + db_id2column_info = dict() + + for db_id in tqdm(db_ids, desc="Extracting database schema"): + create_statements, _ = self.database_manager.get_create_statements_and_insert_statements(db_id) + db_id2column_info[db_id] = self.extract_column_descriptions(create_statements) + + # Phase 2: Prompt building + self.logger.info("Generating question candidates...") + prompts = [] + + for data in tqdm(raw_data, desc="Preparing prompts"): + prompt, question_type = self.prompt_template.build_prompt( + data[self.input_sql_key], + data[self.input_db_id_key], + db_id2column_info, + self.database_manager.db_type + ) + data["question_type"] = question_type + for _ in range(self.question_candidates_num): + prompts.append(prompt) + + # Phase 3: LLM generation + responses = self.llm_serving.generate_from_input(prompts, system_prompt="You are a helpful assistant.") + if len(responses) != len(prompts): + self.logger.warning( + f"LLM response count mismatch: prompts={len(prompts)}, responses={len(responses)}" + ) + min_len = min(len(prompts), len(responses)) + responses = responses[:min_len] + + # Phase 4: Response parsing + self.logger.info("Parsing responses and organizing candidates...") + grouped_responses = [ + responses[i:i + self.question_candidates_num] + for i in range(0, len(responses), self.question_candidates_num) + ] + + all_question_candidates = [] + question_groups = [] + embedding_texts = [] + + for data, response_group in zip(raw_data, grouped_responses): + question_candidates = [] + for response in response_group: + parsed_response = self.parse_llm_response(response, data.get("question_type", "Formal")) + if parsed_response: + question_candidates.append(parsed_response) + text = parsed_response["external_knowledge"] + " " + parsed_response["question"] + embedding_texts.append(text.strip()) + + question_groups.append(question_candidates) + all_question_candidates.extend(question_candidates) + + # Phase 5: Embedding generation (tracked in embedding serving layer) + self.logger.info("Generating embeddings for all question candidates...") + if embedding_texts: + embeddings = self.embedding_serving.generate_embedding_from_input(embedding_texts) + else: + embeddings = [] + + # Phase 6: Best question selection + processed_results = [] + failed_data = [] + embedding_start_idx = 0 + + for data, question_candidates in zip(raw_data, question_groups): + if question_candidates: + best_question = self.select_best_question( + question_candidates, + embedding_start_idx, + embeddings + ) + embedding_start_idx += len(question_candidates) + + if best_question: + result = { + **data, + self.output_question_key: best_question["question"], + self.output_evidence_key: best_question["external_knowledge"] + } + processed_results.append(result) + else: + self.logger.warning(f"No valid question generated for data: {data[self.input_db_id_key]}") + failed_data.append(data) + else: + self.logger.warning(f"No question candidates for data: {data[self.input_db_id_key]}") + failed_data.append(data) + + if self.output_question_key in raw_dataframe.columns: + all_results = existing_data + processed_results + else: + all_results = processed_results + + final_df = pd.DataFrame(all_results) + output_file = storage.write(final_df) + output_count = len(final_df) + + self.logger.info(f"Question generation results saved to {output_file}") + self.logger.info(f"Successfully processed: {len(processed_results)}") + if failed_data: + self.logger.warning(f"Failed to generate questions for: {len(failed_data)} entries") + + return [self.output_question_key, self.output_evidence_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d2f7b8b1cdc96295cb2adc1e72da03903b87352d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/__init__.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + # filter + from .filter.ccnet_deduplicate_filter import CCNetDeduplicateFilter + from .filter.debertav3_filter import DebertaV3Filter + from .filter.fineweb_edu_filter import FineWebEduFilter + from .filter.pair_qual_filter import PairQualFilter + from .filter.perplexity_filter import PerplexityFilter + from .filter.qurating_filter import QuratingFilter + from .filter.text_book_filter import TextbookFilter + + # generate + from .generate.phi4qa_generator import Phi4QAGenerator + + # eval + from .eval.debertav3_sample_evaluator import DebertaV3SampleEvaluator + from .eval.fineweb_edu_sample_evaluator import FineWebEduSampleEvaluator + from .eval.pair_qual_sample_evaluator import PairQualSampleEvaluator + from .eval.textbook_sample_evaluator import TextbookSampleEvaluator + from .eval.qurating_sample_evaluator import QuratingSampleEvaluator + from .eval.perplexity_sample_evaluator import PerplexitySampleEvaluator + from .eval.meta_sample_evaluator import MetaSampleEvaluator + +else: + import sys + from dataflow.utils.registry import LazyLoader, generate_import_structure_from_type_checking + + cur_path = "dataflow/operators/text_pt/" + + _import_structure = generate_import_structure_from_type_checking(__file__, cur_path) + sys.modules[__name__] = LazyLoader(__name__, "dataflow/operators/text_pt/", _import_structure) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c4a1a319ec06b6df0ddcd02c77c764227838ac8 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/Qurating/__pycache__/qurater_annotate.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/Qurating/__pycache__/qurater_annotate.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d61659ed1b34ac974cade20d6d7e6559476e8f8a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/Qurating/__pycache__/qurater_annotate.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/Qurating/modeling/__pycache__/modeling_flash_llama.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/Qurating/modeling/__pycache__/modeling_flash_llama.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f4a5cb692e79d95891005c8eea29da60c7e79d3 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/Qurating/modeling/__pycache__/modeling_flash_llama.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/Qurating/modeling/modeling_flash_llama.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/Qurating/modeling/modeling_flash_llama.py new file mode 100644 index 0000000000000000000000000000000000000000..725299d7b23d71585933beb71db21cc252f9b1a0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/Qurating/modeling/modeling_flash_llama.py @@ -0,0 +1,853 @@ +# coding=utf-8 +# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved. +# +# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX +# and OPT implementations in this library. It has been modified from its +# original forms to accommodate minor architectural differences compared +# to GPT-NeoX and OPT used by the Meta AI team that trained the model. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" PyTorch LLaMA model.""" +from typing import List, Optional, Tuple, Union, Any + +import torch +import torch.nn.functional as F +import torch.utils.checkpoint +from torch import nn +from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss + +import torch.distributed as dist + +from transformers.activations import ACT2FN +from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast +from transformers.modeling_utils import PreTrainedModel +from transformers.utils import logging +from transformers.models.llama.configuration_llama import LlamaConfig + +def try_import_flash_attention(): + try: + from flash_attn import flash_attn_kvpacked_func, flash_attn_varlen_kvpacked_func, flash_attn_with_kvcache + from flash_attn.bert_padding import unpad_input, pad_input + from flash_attn.layers.rotary import apply_rotary_emb_func + except ImportError as e: + if 'flash_attn.layers.rotary' in str(e): + raise ImportError('Please install RoPE kernels: `pip install git+https://github.com/HazyResearch/flash-attention.git#subdirectory=csrc/rotary`') + else: + raise ImportError('Please install flash_attention dependency in GPU environment') +from dataflow import get_logger + +logger = logging.get_logger(__name__) + +# @torch.jit.script +def rmsnorm_func(hidden_states, weight, variance_epsilon): + input_dtype = hidden_states.dtype + hidden_states = hidden_states.to(torch.float32) + variance = hidden_states.pow(2).mean(-1, keepdim=True) + hidden_states = hidden_states * torch.rsqrt(variance + variance_epsilon) + return (weight * hidden_states).to(input_dtype) + + +class LlamaRMSNorm(nn.Module): + def __init__(self, hidden_size, eps=1e-6): + """ + LlamaRMSNorm is equivalent to T5LayerNorm + """ + super().__init__() + self.weight = nn.Parameter(torch.ones(hidden_size)) + self.register_buffer( + "variance_epsilon", + torch.tensor(eps), + persistent=False, + ) + + def forward(self, hidden_states): + return rmsnorm_func(hidden_states, self.weight, self.variance_epsilon) + + +class FlashRotaryEmbedding(torch.nn.Module): + """ + The rotary position embeddings from RoFormer_ (Su et. al). + A crucial insight from the method is that the query and keys are + transformed by rotation matrices which depend on the relative positions. + + Other implementations are available in the Rotary Transformer repo_ and in + GPT-NeoX_, GPT-NeoX was an inspiration + + .. _RoFormer: https://arxiv.org/abs/2104.09864 + .. _repo: https://github.com/ZhuiyiTechnology/roformer + .. _GPT-NeoX: https://github.com/EleutherAI/gpt-neox + + If scale_base is not None, this implements XPos (Sun et al., https://arxiv.org/abs/2212.10554). + A recommended value for scale_base is 512: https://github.com/HazyResearch/flash-attention/issues/96 + Reference: https://github.com/sunyt32/torchscale/blob/main/torchscale/component/xpos_relative_position.py + """ + + def __init__(self, dim: int, base=10000.0, interleaved=False, scale_base=None, + scaling_factor=1.0, pos_idx_in_fp32=True, device=None): + """ + interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead + of 1st half and 2nd half (GPT-NeoX style). + pos_idx_in_fp32: if True, the position indices [0.0, ..., seqlen - 1] are in fp32, + otherwise they might be in lower precision. + This option was added because previously (before 2023-07-02), when we construct + the position indices, we use the dtype of self.inv_freq. In most cases this would + be fp32, but if the model is trained in pure bf16 (not mixed precision), then + self.inv_freq would be bf16, and the position indices are also in bf16. + Because of the limited precision of bf16 (e.g. 1995.0 is rounded to 2000.0), the + embeddings for some positions will coincide. + To maintain compatibility with models previously trained in pure bf16, + we add this option. + scaling_factor: RotaryEmbedding extended with linear scaling. + """ + super().__init__() + self.dim = dim + self.base = float(base) + self.pos_idx_in_fp32 = pos_idx_in_fp32 + # Generate and save the inverse frequency buffer (non trainable) + inv_freq = self._compute_inv_freq(device) + self.register_buffer("inv_freq", inv_freq, persistent=False) + self.interleaved = interleaved + self.scale_base = scale_base + self.scaling_factor = scaling_factor + scale = ((torch.arange(0, dim, 2, device=device, dtype=torch.float32) + 0.4 * dim) + / (1.4 * dim) if scale_base is not None else None) + self.register_buffer("scale", scale) + + self._seq_len_cached = 0 + self._cos_cached = None + self._sin_cached = None + self._cos_k_cached = None + self._sin_k_cached = None + + def _compute_inv_freq(self, device=None): + return 1 / (self.base ** (torch.arange(0, self.dim, 2, device=device, + dtype=torch.float32) / self.dim)) + + + def _update_cos_sin_cache(self, seqlen, device=None, dtype=None): + # Reset the tables if the sequence length has changed, + # if we're on a new device (possibly due to tracing for instance), + # or if we're switching from inference mode to training + if (seqlen > self._seq_len_cached or self._cos_cached.device != device + or self._cos_cached.dtype != dtype + or (self.training and self._cos_cached.is_inference())): + self._seq_len_cached = seqlen + # We want fp32 here, not self.inv_freq.dtype, since the model could be loaded in bf16 + # And the output of arange can be quite large, so bf16 would lose a lot of precision. + # However, for compatibility reason, we add an option to use the dtype of self.inv_freq. + if self.pos_idx_in_fp32: + t = torch.arange(seqlen, device=device, dtype=torch.float32) + t /= self.scaling_factor + # We want fp32 here as well since inv_freq will be multiplied with t, and the output + # will be large. Having it in bf16 will lose a lot of precision and cause the + # cos & sin output to change significantly. + # We want to recompute self.inv_freq if it was not loaded in fp32 + if self.inv_freq.dtype != torch.float32: + inv_freq = self.inv_freq.to(torch.float32) + else: + inv_freq = self.inv_freq + else: + t = torch.arange(seqlen, device=device, dtype=self.inv_freq.dtype) + t /= self.scaling_factor + inv_freq = self.inv_freq + # Don't do einsum, it converts fp32 to fp16 under AMP + # freqs = torch.einsum("i,j->ij", t, self.inv_freq) + freqs = torch.outer(t, inv_freq) + if self.scale is None: + self._cos_cached = torch.cos(freqs).to(dtype) + self._sin_cached = torch.sin(freqs).to(dtype) + else: + power = ((torch.arange(seqlen, dtype=self.scale.dtype, device=self.scale.device) + - seqlen // 2) / self.scale_base) + scale = self.scale.to(device=power.device) ** power.unsqueeze(-1) + # We want the multiplication by scale to happen in fp32 + self._cos_cached = (torch.cos(freqs) * scale).to(dtype) + self._sin_cached = (torch.sin(freqs) * scale).to(dtype) + self._cos_k_cached = (torch.cos(freqs) / scale).to(dtype) + self._sin_k_cached = (torch.sin(freqs) / scale).to(dtype) + + def forward(self, + q: torch.Tensor, k: torch.Tensor, + seqlen_offset: int = 0, + unpadded_lengths: Optional[Tuple[torch.Tensor]] = None) -> Tuple[torch.Tensor, torch.Tensor]: + """ + q: (batch, seqlen, nheads, headdim) + k: (batch, seqlen, nheads, headdim) + seqlen_offset: can be used in generation where the qkv being passed in is only the last + token in the batch. + """ + if unpadded_lengths is not None: + cu_seqlens, max_seqlen = unpadded_lengths + else: + cu_seqlens, max_seqlen = None, q.shape[1] + self._update_cos_sin_cache(max_seqlen + seqlen_offset, device=q.device, dtype=q.dtype) + + if self.scale is None: + return apply_rotary_emb_func( + q, self._cos_cached[seqlen_offset:], self._sin_cached[seqlen_offset:], + self.interleaved, True, # inplace=True, + cu_seqlens=cu_seqlens, max_seqlen=max_seqlen + ), apply_rotary_emb_func( + k, self._cos_cached[seqlen_offset:], self._sin_cached[seqlen_offset:], + self.interleaved, True, # inplace=True + cu_seqlens=cu_seqlens, max_seqlen=max_seqlen + ) + else: + assert False + + +class LlamaMLP(nn.Module): + def __init__(self, config): + super().__init__() + self.config = config + self.hidden_size = config.hidden_size + self.intermediate_size = config.intermediate_size + self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) + self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) + self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False) + self.act_fn = ACT2FN[config.hidden_act] + + def forward(self, x): + return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) + + +@torch.jit.script +def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: + if n_rep == 1: + return hidden_states + final_shape = list(hidden_states.shape[:-2]) + [-1] + [hidden_states.shape[-1]] + expand_shape = [-1] * (len(hidden_states.shape) - 1) + [n_rep] + [-1] + hidden_states = hidden_states.unsqueeze(-2).expand(expand_shape) + return hidden_states.reshape(final_shape) + + +class LlamaAttention(nn.Module): + """Multi-headed attention from 'Attention Is All You Need' paper""" + + def __init__(self, config: LlamaConfig): + super().__init__() + self.config = config + self.hidden_size = config.hidden_size + self.num_heads = config.num_attention_heads + self.head_dim = self.hidden_size // self.num_heads + self.num_key_value_heads = getattr(config, "num_key_value_heads", self.num_heads) + self.num_key_value_groups = self.num_heads // self.num_key_value_heads + self.max_position_embeddings = config.max_position_embeddings + + if (self.head_dim * self.num_heads) != self.hidden_size: + raise ValueError( + f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}" + f" and `num_heads`: {self.num_heads})." + ) + self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False) + self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False) + self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False) + self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False) + + self.register_buffer( + "norm_factor", + torch.sqrt(torch.tensor(self.head_dim, dtype=torch.float32)).to(torch.get_default_dtype()), + persistent=False, + ) + + if not getattr(self.config, "rope_scaling", None): + scaling_factor = 1 + else: + scaling_type = self.config.rope_scaling["type"] + scaling_factor = self.config.rope_scaling["factor"] + assert scaling_type == 'linear' + theta = getattr(self.config, "rope_theta", 10000) + self.rotary_emb = FlashRotaryEmbedding( + self.head_dim, base=theta, interleaved=False, scaling_factor=scaling_factor, + ) + + self.distributed_attn_func = flash_attn_kvpacked_func + + def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): + return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous() + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_value: Optional[Tuple[torch.Tensor]] = None, + output_attentions: bool = False, + use_cache: bool = False, + unpadded_lengths: Optional[Tuple[torch.Tensor]] = None, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + h_size = hidden_states.size(-1) + + has_layer_past = past_key_value is not None + + if has_layer_past: + past_kv = past_key_value[0] + past_len = past_key_value[1] + else: + past_len = 0 + + # NOTE: Hack to include position_ids, assuming they are increasing uniformly per block + if position_ids is not None: + past_len += position_ids.min() + + q = self.q_proj(hidden_states) + k = self.k_proj(hidden_states) + v = self.v_proj(hidden_states) + + q = q.view(*q.shape[:-1], self.num_heads, self.head_dim) + k = k.view(*k.shape[:-1], self.num_key_value_heads, self.head_dim) + v = v.view(*v.shape[:-1], self.num_key_value_heads, self.head_dim) + + q, k = self.rotary_emb(q, k, past_len, unpadded_lengths) + + kv = torch.stack([k, v], -3) + kv = repeat_kv(kv, self.num_key_value_groups) + + # Cache QKV values + if has_layer_past: + new_len = past_len+q.size(1) + if new_len > past_kv.size(1): + past_kv = torch.cat([past_kv, torch.empty(hidden_states.size(0), 256, 2, kv.size(3), kv.size(4), dtype=kv.dtype, device=kv.device)], 1) + past_kv[:, past_len:new_len] = kv + kv = past_kv[:, :new_len] + else: + past_kv = kv + + if unpadded_lengths is not None: + # varlen, ignore padding tokens, efficient for large batch with many paddings + assert attention_mask is not None + cu_seqlens, max_seqlen = unpadded_lengths + + attn_outputs = flash_attn_varlen_kvpacked_func( + q, kv, + cu_seqlens, cu_seqlens, + max_seqlen, max_seqlen, + dropout_p=0.0, softmax_scale=1.0/self.norm_factor, + causal=True, return_attn_probs=output_attentions + ) + # elif use_cache and past_key_value is not None: + # attn_outputs = flash_attn_with_kvcache( + # q, + # kv[:, :, 0], + # kv[:, :, 1], + # softmax_scale=1.0/self.norm_factor, + # causal=True, + # ) + else: + attn_outputs = flash_attn_kvpacked_func( + q, kv, + dropout_p=0.0, + softmax_scale=1.0/self.norm_factor, + causal=True, + return_attn_probs=output_attentions, + ) + past_key_value = (past_kv, past_len+q.size(1)) if use_cache else None + + + attn_output = attn_outputs[0] if output_attentions else attn_outputs + attn_output = attn_output.reshape(*attn_output.shape[:-2], h_size) + attn_weights = attn_outputs[2] if output_attentions else None + + attn_output = self.o_proj(attn_output) + + if not output_attentions: + attn_weights = None + + return attn_output, attn_weights, past_key_value + + +class LlamaDecoderLayer(nn.Module): + def __init__(self, config: LlamaConfig): + super().__init__() + self.hidden_size = config.hidden_size + self.self_attn = LlamaAttention(config=config) + self.mlp = LlamaMLP(config) + self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self._fsdp_wrap = True + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_value: Optional[Tuple[torch.Tensor]] = None, + unpadded_lengths: Optional[Tuple[torch.Tensor]] = None, + output_attentions: Optional[bool] = False, + use_cache: Optional[bool] = False, + ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: + """ + Args: + hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` + attention_mask (`torch.FloatTensor`, *optional*): attention mask of size + `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding + (see `past_key_values`). + past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states + """ + + residual = hidden_states + + hidden_states = self.input_layernorm(hidden_states) + + # Self Attention + hidden_states, self_attn_weights, present_key_value = self.self_attn( + hidden_states=hidden_states, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_value=past_key_value, + output_attentions=output_attentions, + use_cache=use_cache, + unpadded_lengths=unpadded_lengths, + ) + hidden_states = residual + hidden_states + + # Fully Connected + residual = hidden_states + hidden_states = self.post_attention_layernorm(hidden_states) + hidden_states = self.mlp(hidden_states) + hidden_states = residual + hidden_states + + outputs = (hidden_states,) + + if output_attentions: + outputs += (self_attn_weights,) + + if use_cache: + outputs += (present_key_value,) + + return outputs + + +class LlamaPreTrainedModel(PreTrainedModel): + config_class = LlamaConfig + base_model_prefix = "model" + supports_gradient_checkpointing = True + _no_split_modules = ["LlamaDecoderLayer"] + _skip_keys_device_placement = "past_key_values" + + def _init_weights(self, module): + std = self.config.initializer_range + if isinstance(module, nn.Linear): + module.weight.data.normal_(mean=0.0, std=std) + if module.bias is not None: + module.bias.data.zero_() + elif isinstance(module, nn.Embedding): + module.weight.data.normal_(mean=0.0, std=std) + if module.padding_idx is not None: + module.weight.data[module.padding_idx].zero_() + + +class LlamaModel(LlamaPreTrainedModel): + """ + Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`] + + Args: + config: LlamaConfig + """ + + def __init__(self, config: LlamaConfig): + super().__init__(config) + self.padding_idx = config.pad_token_id + self.vocab_size = config.vocab_size + + self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) + self.layers = nn.ModuleList([LlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)]) + self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + + self.gradient_checkpointing = False + # Initialize weights and apply final processing + try_import_flash_attention() + self.post_init() + + def get_input_embeddings(self): + return self.embed_tokens + + def set_input_embeddings(self, value): + self.embed_tokens = value + + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, BaseModelOutputWithPast]: + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + use_cache = use_cache if use_cache is not None else self.config.use_cache + + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # retrieve input_ids and inputs_embeds + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time") + elif input_ids is not None: + batch_size, seq_length = input_ids.shape + elif inputs_embeds is not None: + batch_size, seq_length, _ = inputs_embeds.shape + else: + raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds") + + # position_ids = None + + if inputs_embeds is None: + inputs_embeds = self.embed_tokens(input_ids) + + hidden_states = inputs_embeds + bsz = hidden_states.size(0) + + if self.gradient_checkpointing and self.training: + if use_cache: + logger.warning_once( + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." + ) + use_cache = False + + if ( + ((attention_mask is not None) and (not attention_mask.all().item())) + and not use_cache + ): + try: # for flash-attn latest version + hidden_states, unpad_indices, cu_seqlens, max_seqlen, _ = unpad_input(hidden_states, attention_mask) + except: # for flash-attn 2.3.3 verstion + hidden_states, unpad_indices, cu_seqlens, max_seqlen = unpad_input(hidden_states, attention_mask) + unpadded_lengths = (cu_seqlens, max_seqlen) + else: + unpadded_lengths = None + + # decoder layers + all_hidden_states = () if output_hidden_states else None + all_self_attns = () if output_attentions else None + next_decoder_cache = () if use_cache else None + + for idx, decoder_layer in enumerate(self.layers): + if output_hidden_states: + if unpadded_lengths is not None: + all_hidden_states += (pad_input(hidden_states, unpad_indices, bsz, max_seqlen),) + else: + all_hidden_states += (hidden_states,) + + past_key_value = past_key_values[idx] if past_key_values is not None else None + + if self.gradient_checkpointing and self.training: + layer_outputs = torch.utils.checkpoint.checkpoint( + decoder_layer, + hidden_states, + attention_mask, + position_ids, + None, + unpadded_lengths, + output_attentions, + False, + use_reentrant=False + ) + else: + layer_outputs = decoder_layer( + hidden_states, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_value=past_key_value, + unpadded_lengths=unpadded_lengths, + output_attentions=output_attentions, + use_cache=use_cache, + ) + + hidden_states = layer_outputs[0] + + if use_cache: + next_decoder_cache += (layer_outputs[2 if output_attentions else 1],) + + if output_attentions: + all_self_attns += (layer_outputs[1],) + + if unpadded_lengths is not None: + hidden_states = pad_input(hidden_states, unpad_indices, bsz, max_seqlen) + hidden_states = self.norm(hidden_states) + + # add hidden states from the last decoder layer + if output_hidden_states: + all_hidden_states += (hidden_states,) + + next_cache = next_decoder_cache if use_cache else None + if not return_dict: + return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None) + return BaseModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=next_cache, + hidden_states=all_hidden_states, + attentions=all_self_attns, + ) + + +class LlamaForCausalLM(LlamaPreTrainedModel): + _tied_weights_keys = ["lm_head.weight"] + + def __init__(self, config): + super().__init__(config) + self.model = LlamaModel(config) + self.vocab_size = config.vocab_size + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + try_import_flash_attention() + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.embed_tokens + + def set_input_embeddings(self, value): + self.model.embed_tokens = value + + def get_output_embeddings(self): + return self.lm_head + + def set_output_embeddings(self, new_embeddings): + self.lm_head = new_embeddings + + def set_decoder(self, decoder): + self.model = decoder + + def get_decoder(self): + return self.model + + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + avg_valid_labels_per_chunk: Optional[float] = None, + ) -> Union[Tuple, CausalLMOutputWithPast]: + r""" + Args: + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., + config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored + (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. + + Returns: + + Example: + + ```python + >>> from transformers import AutoTokenizer, LlamaForCausalLM + + >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS) + >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER) + + >>> prompt = "Hey, are you conscious? Can you talk to me?" + >>> inputs = tokenizer(prompt, return_tensors="pt") + + >>> # Generate + >>> generate_ids = model.generate(inputs.input_ids, max_length=30) + >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] + "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you." + ```""" + + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) + outputs = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + hidden_states = outputs[0] + logits = self.lm_head(hidden_states).float() + + loss = None + if labels is not None: + # Shift so that tokens < n predict n + shift_logits = logits[..., :-1, :].contiguous() + shift_labels = labels[..., 1:].contiguous() + # Flatten the tokens + loss_fct = CrossEntropyLoss() + shift_logits = shift_logits.view(-1, self.config.vocab_size) + shift_labels = shift_labels.view(-1) + # Enable model parallelism + shift_labels = shift_labels.to(shift_logits.device) + loss = loss_fct(shift_logits, shift_labels) + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + def prepare_inputs_for_generation( + self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs + ): + if past_key_values: + input_ids = input_ids[:, -1:] + + # if `inputs_embeds` are passed, we only want to use them in the 1st generation step + if inputs_embeds is not None and past_key_values is None: + model_inputs = {"inputs_embeds": inputs_embeds} + else: + model_inputs = {"input_ids": input_ids} + + model_inputs.update( + { + "past_key_values": past_key_values, + "use_cache": kwargs.get("use_cache"), + "attention_mask": attention_mask + } + ) + return model_inputs + + @staticmethod + def _reorder_cache(past_key_values, beam_idx): + reordered_past = () + for layer_past in past_key_values: + reordered_past += ( + tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past), + ) + return reordered_past + + +class LlamaForSequenceClassification(LlamaPreTrainedModel): + def __init__(self, config): + super().__init__(config) + self.num_labels = config.num_labels + self.model = LlamaModel(config) + self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False) + try_import_flash_attention() + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.embed_tokens + + def set_input_embeddings(self, value): + self.model.embed_tokens = value + + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, SequenceClassifierOutputWithPast]: + r""" + labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., + config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If + `config.num_labels > 1` a classification loss is computed (Cross-Entropy). + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + transformer_outputs = self.model( + input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + hidden_states = transformer_outputs[0] + logits = self.score(hidden_states) + + if input_ids is not None: + batch_size = input_ids.shape[0] + else: + batch_size = inputs_embeds.shape[0] + + if self.config.pad_token_id is None and batch_size != 1: + raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.") + if self.config.pad_token_id is None: + sequence_lengths = -1 + else: + if input_ids is not None: + sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device) + else: + sequence_lengths = -1 + + pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths] + + loss = None + if labels is not None: + labels = labels.to(logits.device) + if self.config.problem_type is None: + if self.num_labels == 1: + self.config.problem_type = "regression" + elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): + self.config.problem_type = "single_label_classification" + else: + self.config.problem_type = "multi_label_classification" + + if self.config.problem_type == "regression": + loss_fct = MSELoss() + if self.num_labels == 1: + loss = loss_fct(pooled_logits.squeeze(), labels.squeeze()) + else: + loss = loss_fct(pooled_logits, labels) + elif self.config.problem_type == "single_label_classification": + loss_fct = CrossEntropyLoss() + loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1)) + elif self.config.problem_type == "multi_label_classification": + loss_fct = BCEWithLogitsLoss() + loss = loss_fct(pooled_logits, labels) + if not return_dict: + output = (pooled_logits,) + transformer_outputs[1:] + return ((loss,) + output) if loss is not None else output + + return SequenceClassifierOutputWithPast( + loss=loss, + logits=pooled_logits, + past_key_values=transformer_outputs.past_key_values, + hidden_states=transformer_outputs.hidden_states, + attentions=transformer_outputs.attentions, + ) \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/Qurating/qurater_annotate.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/Qurating/qurater_annotate.py new file mode 100644 index 0000000000000000000000000000000000000000..28af58ea00ab997dd70420f808839e7e41163792 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/Qurating/qurater_annotate.py @@ -0,0 +1,190 @@ +from datasets import load_from_disk, load_dataset, concatenate_datasets +from transformers import AutoModelForSequenceClassification, AutoTokenizer +from .modeling.modeling_flash_llama import LlamaForSequenceClassification +import torch +import argparse +import numpy as np + +class TokenizeAndChunk: + def __init__(self, tokenizer_name, text_field, tokens_field, tokens, model_cache_dir): + self.tokens = tokens + self.tokenizer_name = tokenizer_name + self.text_field = text_field + self.tokens_field = tokens_field + + self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name, use_fast=True, cache_dir = model_cache_dir) + self.tokenizer.pad_token_id = 0 + + def __getstate__(self): + return { + "tokenizer_name": self.tokenizer_name, + "text_field": self.text_field, + "tokens_field": self.tokens_field, + "tokens": self.tokens, + } + + def __setstate__(self, state): + self.__init__(**state) + + def tokenize_and_chunk(self, source_tokens): + chunks_token_ids = [] + chunks_token_counts = [] + + for seq in source_tokens: + chunks = torch.tensor(seq, dtype=torch.long).split(self.tokens) + chunks_token_ids.append([chunk.tolist() for chunk in chunks]) + chunks_token_counts.append([len(x) for x in chunks]) + + return chunks_token_ids, chunks_token_counts + + def __call__(self, example): + if self.tokens_field in example: + source_tokens = example[self.tokens_field] + else: + source_tokens = self.tokenizer(example[self.text_field], truncation=False, padding=False, add_special_tokens=False).input_ids + + chunks_token_ids, chunks_token_counts = self.tokenize_and_chunk(source_tokens) + + assert len(example[self.text_field]) == len(chunks_token_ids) + assert len(example[self.text_field]) == len(chunks_token_counts) + + return { + "chunks_token_ids": chunks_token_ids, + "chunks_token_counts": chunks_token_counts, + } + + +class ModelAnnotator: + def __init__(self, model_name, labels, device_batch_size, device, model_cache_dir): + + self.model_name = model_name + self.labels = labels + self.device_batch_size = device_batch_size + + self.model = LlamaForSequenceClassification.from_pretrained( + self.model_name, + torch_dtype=torch.bfloat16, + cache_dir=model_cache_dir) + self.model.config.pad_token_id = 0 + self.model.eval() + + self.device = device + print(f"Using device {self.device}") + self.model.to(self.device) + + self.num_labels = len(labels) + assert self.num_labels == self.model.config.num_labels, f"Number of labels ({self.num_labels}) does not match model config ({self.model.config.num_labels})" + + def __getstate__(self): + return { + "model_name": self.model_name, + "labels": self.labels, + "device_batch_size": self.device_batch_size, + } + + def __setstate__(self, state): + self.__init__(**state) + + @torch.inference_mode() + def score_chunks(self, chunks_token_ids, chunks_token_counts): + sorted_indices = torch.argsort(chunks_token_counts) + + scores = torch.zeros(len(chunks_token_ids), self.num_labels, dtype=torch.float32) + + for batch_indices in sorted_indices.split(self.device_batch_size): + max_len = chunks_token_counts[batch_indices].max() + + input_ids = torch.zeros((len(batch_indices), max_len), dtype=torch.long) + attention_mask = torch.zeros((len(batch_indices), max_len), dtype=torch.long) + + for i, j in enumerate(batch_indices): + seq = chunks_token_ids[j] + input_ids[i, :len(seq)] = seq + attention_mask[i, :len(seq)] = 1 + + outputs = self.model(input_ids.to(self.device), attention_mask=attention_mask.to(self.device), use_cache=False) + scores[batch_indices] = outputs.logits.float().cpu() + return scores + + def __call__(self, example, indices): + num_seqs = len(indices) + + source_ids = [i for i, counts in enumerate(example["chunks_token_counts"]) for _ in range(len(counts))] + chunks_token_ids = [torch.tensor(chunk, dtype=torch.long) for chunks in example["chunks_token_ids"] for chunk in chunks] + flattened_chunks_token_counts = torch.tensor([chunk for chunks in example["chunks_token_counts"] for chunk in chunks], dtype=torch.long) + + flattened_scores = self.score_chunks(chunks_token_ids, flattened_chunks_token_counts) + + chunk_token_counts = example["chunks_token_counts"] + chunk_scores = [[[] for _ in range(num_seqs)] for _ in range(self.num_labels)] + + for source_id, score in zip(source_ids, flattened_scores): + for label in range(self.num_labels): + chunk_scores[label][source_id].append(score[label].item()) + + output = { + "index": indices, + "chunk_lengths": chunk_token_counts, + "length": [sum(counts) for counts in chunk_token_counts], + } + + for i, label in enumerate(self.labels): + output[f"{label}_chunks"] = chunk_scores[i] + output[f"{label}_average"] = [ + np.average(scores, weights=token_counts).item() + for scores, token_counts in zip(chunk_scores[i], chunk_token_counts) + ] + + return output + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("input", type=str) + parser.add_argument("output", type=str) + + parser.add_argument("-F", "--data_files", type=str, nargs="+", default=[]) + parser.add_argument("-S", "--shard", type=int, nargs=2, default=[0, 1]) + parser.add_argument("-M", "--model", type=str, required=True) + parser.add_argument("-t", "--tokens", type=int, default=512) + parser.add_argument("--map_batch_size", type=int, default=512) + parser.add_argument("-b", "--device_batch_size", type=int, default=16) + parser.add_argument("-w", "--num_workers", type=int, default=1) + parser.add_argument("--text_field", type=str, default="text") + parser.add_argument("--tokens_field", type=str, default="input_ids") + parser.add_argument("--labels", type=str, nargs="+") + + args = parser.parse_args() + print(args) + + if args.input == "json": + dataset = load_dataset("json", data_files=args.data_files, split="train") + else: + dataset = load_from_disk(args.input) + + src_dataset = dataset.shard(args.shard[1], args.shard[0], contiguous=True) + dataset = src_dataset + + print(dataset) + print("Total number of examples:", len(dataset)) + dataset = dataset.map( + TokenizeAndChunk(args.model, args.text_field, args.tokens_field, args.tokens), + batched=True, + batch_size=args.map_batch_size, + num_proc=args.num_workers, + remove_columns=dataset.column_names) + + print("After tokenization: Total number of examples:", len(dataset)) + dataset = dataset.map( + ModelAnnotator(args.model, args.labels, args.device_batch_size), + batched=True, + with_indices=True, + batch_size=args.map_batch_size, + remove_columns=dataset.column_names) + + dataset = concatenate_datasets([dataset, src_dataset], axis=1) + + print("After annotation: Total number of examples:", len(dataset)) + + print(f"Saving to {args.output}") + dataset.save_to_disk(args.output) \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f93549025469fab5ec7afb19b7b2e2946799410e Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/__pycache__/debertav3_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/__pycache__/debertav3_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4f4e46f4e88a02e3d474aa77e800185f7e24170 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/__pycache__/debertav3_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/__pycache__/fineweb_edu_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/__pycache__/fineweb_edu_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ffb291b1d8f5c95ad6643884d94efd6e579900d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/__pycache__/fineweb_edu_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/__pycache__/meta_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/__pycache__/meta_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..394d9ba933a062afed399c44f638f60c9690474c Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/__pycache__/meta_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/__pycache__/pair_qual_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/__pycache__/pair_qual_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f87154ca548e693ee752114dcaae3a96c8bacdb5 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/__pycache__/pair_qual_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/__pycache__/perplexity_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/__pycache__/perplexity_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28dac57565bc80bf2dd4a04e62f3864d3ce88099 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/__pycache__/perplexity_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/__pycache__/qurating_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/__pycache__/qurating_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e52b3dd039bc26aecb90eb8dc99fd9cc11a42b3 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/__pycache__/qurating_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/__pycache__/textbook_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/__pycache__/textbook_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36255d1084e0cc8288fb3426b8d5ab70506f0880 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/__pycache__/textbook_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/debertav3_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/debertav3_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..7ce31cb8c8ea72c41f9274a0f2f30504177c1ebc --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/debertav3_sample_evaluator.py @@ -0,0 +1,98 @@ +import torch +from torch import nn +from transformers import AutoModel, AutoTokenizer, AutoConfig +from huggingface_hub import PyTorchModelHubMixin +from dataflow.core import OperatorABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.storage import DataFlowStorage +from tqdm import tqdm +from dataflow import get_logger + +@OPERATOR_REGISTRY.register() +class DebertaV3SampleEvaluator(OperatorABC): + def __init__(self, model_name, model_cache_dir='./dataflow_cache', device='cuda'): + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.model_name = model_name + self.model_cache_dir = model_cache_dir + self.device = device or ('cuda' if torch.cuda.is_available() else 'cpu') + self.score_name = 'DebertaV3Score' + self.config = AutoConfig.from_pretrained(self.model_name, cache_dir=self.model_cache_dir) + self.tokenizer = AutoTokenizer.from_pretrained(self.model_name, cache_dir=self.model_cache_dir) + self.model = QualityModel.from_pretrained(self.model_name, cache_dir=self.model_cache_dir).to(self.device) + self.model.eval() + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于Nvidia Deberta V3模型的质量分类器,用于评估文本质量并返回分类结果。\n" + "输入参数:\n" + "- model_name:预训练模型名称\n" + "- model_cache_dir:模型缓存目录,默认为'./dataflow_cache'\n" + "- device:计算设备,默认为'cuda'\n" + "- input_key:输入文本字段名\n" + "- output_key:输出分类结果字段名,默认为'Debertav3Score'\n" + "输出参数:\n" + "- 包含文本质量分类结果的DataFrame" + ) + elif lang == "en": + return ( + "Text quality classifier based on Nvidia Deberta V3 model for quality assessment and classification.\n" + "Input Parameters:\n" + "- model_name: Pretrained model name\n" + "- model_cache_dir: Model cache directory, default './dataflow_cache'\n" + "- device: Computing device, default 'cuda'\n" + "- input_key: Field name for input text\n" + "- output_key: Field name for output classification, default 'Debertav3Score'\n" + "Output Parameters:\n" + "- DataFrame containing text quality classification results" + ) + else: + return "Text quality classifier based on Nvidia Deberta V3." + + def _score_func(self, sample): + inputs = self.tokenizer( + sample, return_tensors="pt", padding="longest", truncation=True + ).to(self.device) + with torch.no_grad(): + outputs = self.model(inputs["input_ids"], inputs["attention_mask"]) + predicted_classes = torch.argmax(outputs, dim=1) + predicted_domains = [ + self.config.id2label[class_idx.item()] for class_idx in predicted_classes.cpu().numpy() + ] + return predicted_domains[0] # Assuming one sample per batch + + def eval(self, dataframe, input_key): + scores = [] + self.logger.info(f"Evaluating {self.score_name}...") + for sample in tqdm(dataframe[input_key], desc="DebertaV3 modle evaluating..."): + score = self._score_func(sample) + scores.append(score) + self.logger.info("Evaluation complete!") + return scores + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='Debertav3Score'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + scores = self.eval(dataframe, input_key) + dataframe[self.output_key] = scores + storage.write(dataframe) + + +class QualityModel(nn.Module, PyTorchModelHubMixin): + def __init__(self, config): + super(QualityModel, self).__init__() + self.model = AutoModel.from_pretrained(config["base_model"]) + self.dropout = nn.Dropout(config["fc_dropout"]) + self.fc = nn.Linear(self.model.config.hidden_size, len(config["id2label"])) + + def forward(self, input_ids, attention_mask): + features = self.model( + input_ids=input_ids, attention_mask=attention_mask + ).last_hidden_state + dropped = self.dropout(features) + outputs = self.fc(dropped) + return torch.softmax(outputs[:, 0, :], dim=1) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/fineweb_edu_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/fineweb_edu_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..7f717197dda16998c009f51142d723c86755708f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/fineweb_edu_sample_evaluator.py @@ -0,0 +1,69 @@ +import torch +from transformers import AutoTokenizer, AutoModelForSequenceClassification +from dataflow.core import OperatorABC +from dataflow import get_logger +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.storage import DataFlowStorage +from tqdm import tqdm +import numpy as np + +@OPERATOR_REGISTRY.register() +class FineWebEduSampleEvaluator(OperatorABC): + def __init__(self, model_cache_dir: str = './dataflow_cache', device: str = 'cuda'): + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.model_name = 'HuggingFaceTB/fineweb-edu-classifier' + self.model_cache_dir = model_cache_dir + self.device = device or ('cuda' if torch.cuda.is_available() else 'cpu') + self.batch_size = 1 + self.tokenizer = AutoTokenizer.from_pretrained(self.model_name, cache_dir=self.model_cache_dir) + self.model = AutoModelForSequenceClassification.from_pretrained(self.model_name, cache_dir=self.model_cache_dir).to(self.device) + self.model.eval() + self.score_name = 'FineWebEduScore' + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于Fineweb-Edu分类器评估文本的教育价值。该分类器使用预训练的序列分类模型对文本进行评估,返回0-1之间的分数," + "分数越高表示文本的教育价值越高。适用于筛选具有教育意义的文本内容。\n" + "输入参数:\n" + "- text: 待评估的文本字符串\n" + "输出参数:\n" + "- float: 0-1之间的教育价值分数,越高表示教育价值越大" + ) + else: + return ( + "Evaluate the educational value of text using the Fineweb-Edu classifier. This classifier uses a pre-trained sequence classification model " + "to assess text and returns a score between 0 and 1, where higher scores indicate greater educational value. Suitable for filtering educational content.\n" + "Input parameters:\n" + "- text: Text string to be evaluated\n" + "Output parameters:\n" + "- float: Educational value score between 0 and 1, higher values indicate greater educational value" + ) + + def _score_func(self, sample): + tokenized_inputs = self.tokenizer(sample, return_tensors="pt", padding="longest", truncation=True).to(self.device) + with torch.no_grad(): + outputs = self.model(**tokenized_inputs) + logits = outputs.logits.squeeze(-1).float().detach().cpu().numpy() + + return logits.tolist()[0] # Return as list for individual sample + + def eval(self, dataframe, input_key): + scores = [] + self.logger.info(f"Evaluating {self.score_name}...") + for sample in tqdm(dataframe[input_key], desc="Fineweb-edu model evaluating..."): + score = self._score_func(sample) + scores.append(score) + self.logger.info("Evaluation complete!") + return np.array(scores) + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='FinewebEduScore'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + scores = self.eval(dataframe, input_key) + dataframe[self.output_key] = scores + storage.write(dataframe) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/meta_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/meta_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..393d7df675c658756eca4cb58c0493839a4fb6a7 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/meta_sample_evaluator.py @@ -0,0 +1,214 @@ +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +import pandas as pd +from dataflow.core import LLMServingABC +from dataflow.prompts.general_text import MetaPrompt +import ast +from dataflow.core.prompt import prompt_restrict + +example_dimensions = [ + { + "dimension_name": "Text Structure", + "description": "Evaluate the surface-level quality of the text, including spelling accuracy, grammar, vocabulary richness, and sentence structure.", + "example_list": [ + { + "text": "The experimental procedure was meticulously documented, with each variable clearly defined.", + "score": "5" + }, + { + "text": "teh data was wrong and we dont no why it happen like that", + "score": "2" + } + ] + }, + { + "dimension_name": "Diversity and Complexity", + "description": "Assess how rich and conceptually varied the content is, and whether it requires expert or deep reasoning to understand.", + "example_list": [ + { + "text": "This article compares Bayesian inference and frequentist approaches in statistical modeling, highlighting theoretical and practical trade-offs.", + "score": "5" + }, + { + "text": "Dogs are pets. They bark. They are friendly.", + "score": "2" + } + ] + }, + { + "dimension_name": "Fluency and Understandability", + "description": "Evaluate whether the text flows naturally, is easy to follow, and avoids awkward or disjointed phrasing.", + "example_list": [ + { + "text": "Despite initial challenges, the team successfully completed the deployment by adhering to a revised strategy.", + "score": "5" + }, + { + "text": "The problem was and then fixed by something happens deployment successful maybe.", + "score": "2" + } + ] + }, + { + "dimension_name": "Safety", + "description": "Identify whether the text contains profanities, hate speech, or excessive personally identifiable information (PII).", + "example_list": [ + { + "text": "The software collects anonymous usage data to improve performance.", + "score": "5" + }, + { + "text": "You idiot, your address 123 Main St will be posted online.", + "score": "1" + } + ] + }, + { + "dimension_name": "Educational Value", + "description": "Determine whether the text provides insight, stimulates thinking, or offers meaningful learning potential.", + "example_list": [ + { + "text": "Understanding the principles of thermodynamics allows engineers to design more efficient engines.", + "score": "5" + }, + { + "text": "The sky is blue. Water is wet. This is how it is.", + "score": "2" + } + ] + }, + { + "dimension_name": "Content Accuracy and Effectiveness", + "description": "Assess the truthfulness, relevance, and practical usefulness of the content.", + "example_list": [ + { + "text": "Newton's second law states that F = ma, which explains the relationship between force, mass, and acceleration.", + "score": "5" + }, + { + "text": "The Earth is flat and doesn't rotate around the Sun.", + "score": "1" + } + ] + } +] + +@prompt_restrict( + MetaPrompt +) + +@OPERATOR_REGISTRY.register() +class MetaSampleEvaluator(OperatorABC): + def __init__(self, + llm_serving: LLMServingABC = None, + dimensions: list[dict] = example_dimensions, + ): + + """ + Operator that evaluate the quality of the text based on the given dimensions. + Argument Dimensions should be list of dict, each dict should contain: + { + "dimension_name": "Dimension Name", + "description": "Description of the dimension", + "example_list": [ // a list of example text and score + { + "text": "example1 text to be evaluated", + "score": "the score of this dimension of the text above" + }, + { + "text": "example2 text to be evaluated", + "score": "the score of this dimension of the text above" + } + ] + } + """ + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.llm_serving = llm_serving + self.score_name = 'MetaScore' + self.prompt = MetaPrompt(dimensions=dimensions) + self.logger.info(f'{self.__class__.__name__} initialized.') + self.dimensions = dimensions + for item in dimensions: + if 'dimension_name' not in item or 'description' not in item or 'example_list' not in item: + raise ValueError('Invalid dimension format. Refer to the docstring for the correct format.') + for example in item['example_list']: + if 'text' not in example or 'score' not in example: + raise ValueError('Invalid example format. Refer to the docstring for the correct format.') + self.output_columns = [item['dimension_name'] for item in dimensions] + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "通过LLM评估文本的多个元属性,包括文本结构、多样性与复杂性、流畅性与可理解性、安全性、教育价值以及内容准确性与有效性。\n" + "输入参数:\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口\n" + "- dimensions:评估维度列表,每个维度对应的字典中包含dimension_name,description,和示例字段:\n" + " * dimension_name:维度名称\n" + " * description:维度的描述\n" + " * example_list:包含示例文本和得分的列表\n" + "- input_key:输入文本字段名\n" + "输出参数:\n" + "- 包含6个评估维度得分的DataFrame,列名为:Text Structure, Diversity & Complexity, Fluency & Understandability, Safety, Educational Value, Content Accuracy & Effectiveness" + ) + elif lang == "en": + return ( + "Evaluate multiple meta attributes of text using LLM, including Text Structure, Diversity & Complexity, Fluency & Understandability, Safety, Educational Value, and Content Accuracy & Effectiveness.\n" + "Input Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC interface\n" + "- dimensions: List of evaluation dimensions, each dimension corresponding to a dictionary containing dimension_name, description, and example field:\n" + " * dimension_name: Name of the dimension\n" + " * description: Description of the dimension\n" + " * example_list: List containing example texts and scores\n" + "- input_key: Field name for input text\n" + "Output Parameters:\n" + "- DataFrame containing scores for 6 evaluation dimensions with columns: Text Structure, Diversity & Complexity, Fluency & Understandability, Safety, Educational Value, Content Accuracy & Effectiveness" + ) + else: + return "Evaluate multiple meta attributes of text using LLM." + + def get_score(self, samples, input_key): + system_prompt = self.prompt.build_system_prompt() + user_prompts = [] + for sample in samples: + input_text = sample.get(input_key, '') + user_prompt = self.prompt.build_prompt(input_text) + full_prompt = system_prompt + "\n" + user_prompt + user_prompts.append(full_prompt) + + responses = self.llm_serving.generate_from_input(user_inputs=user_prompts) + scores = [] + + for i, response in enumerate(responses): + try: + lines = response.strip().split("\n") + last_line = lines[-1].strip() + parsed_scores = ast.literal_eval(last_line) + if isinstance(parsed_scores, list) and len(parsed_scores) == 6: + scores.append(parsed_scores) + else: + raise ValueError("Score format invalid") + except Exception as e: + self.logger.warning(f"Failed to extract score from response {i}: {e}") + scores.append([float('nan')] * 6) + + return scores + + def eval(self, dataframe: pd.DataFrame, input_key: str): + samples = dataframe.to_dict(orient='records') + self.logger.info(f"Evaluating {self.score_name}...") + scores = self.get_score(samples, input_key) + self.logger.info("Evaluation complete!") + return scores + + def run(self, storage: DataFlowStorage, input_key: str): + self.input_key = input_key + dataframe = storage.read("dataframe") + scores = self.eval(dataframe, self.input_key) + # 展开6列固定命名 + score_df = pd.DataFrame(scores, columns=self.output_columns) + dataframe = pd.concat([dataframe, score_df], axis=1) + storage.write(dataframe) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/pair_qual_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/pair_qual_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..d877f19a46cdb4ea6d79eac2b65d2b0e1b71efa3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/pair_qual_sample_evaluator.py @@ -0,0 +1,119 @@ +import torch +from torch import nn +from transformers import BertModel, BertConfig, PreTrainedModel, AutoTokenizer +from dataflow.core import OperatorABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.storage import DataFlowStorage +from tqdm import tqdm +from dataflow.utils.utils import get_logger +import numpy as np + +@OPERATOR_REGISTRY.register() +class PairQualSampleEvaluator(OperatorABC): + def __init__(self, model_cache_dir:str='./dataflow_cache', device="cuda", lang='en', max_length=512): + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.device = device or ('cuda' if torch.cuda.is_available() else 'cpu') + self.model_cache_dir = model_cache_dir + self.lang = lang + self.max_length = max_length + self.score_name = 'PairQualScore' + if lang not in ['en', 'zh']: + raise ValueError("Invalid value for 'lang'. Only 'en' or 'zh' are allowed.") + if self.lang == 'en': + model = "zks2856/PairQual-Scorer-en" + config = BertConfig.from_pretrained(model, cache_dir=self.model_cache_dir) + self.model = BertForRegression_en.from_pretrained(model, config=config, trust_remote_code=True, cache_dir=self.model_cache_dir).to(self.device).eval() + self.tokenizer = AutoTokenizer.from_pretrained(model, trust_remote_code=True, cache_dir=self.model_cache_dir) + else: + model = "zks2856/PairQual-Scorer-zh" + config = BertConfig.from_pretrained(model, cache_dir=self.model_cache_dir) + self.model = BertForRegression_zh.from_pretrained(model, config=config, trust_remote_code=True, cache_dir=self.model_cache_dir).to(self.device).eval() + self.tokenizer = AutoTokenizer.from_pretrained(model, trust_remote_code=True, cache_dir=self.model_cache_dir) + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于BGE模型和GPT成对比较数据训练的文本质量评分器,支持中英文输入。通过对文本进行单样本评估,返回0-1之间的质量分数," + "分数越高表示文本质量越好。模型分为英文版本(zks2856/PairQual-Scorer-en)和中文版本(zks2856/PairQual-Scorer-zh)。\n" + "输入参数:\n" + "- text: 待评估的文本字符串\n" + "- lang: 语言类型,可选'en'或'zh'\n" + "输出参数:\n" + "- float: 0-1之间的质量分数,越高表示质量越好" + ) + else: + return ( + "Text quality scorer trained on BGE model and GPT pairwise comparison data, supporting bilingual input. Evaluate text through single-sample assessment, " + "returning a quality score between 0 and 1, where higher scores indicate better text quality. Models include English version (zks2856/PairQual-Scorer-en) and Chinese version (zks2856/PairQual-Scorer-zh).\n" + "Input parameters:\n" + "- text: Text string to be evaluated\n" + "- lang: Language type, optional 'en' or 'zh'\n" + "Output parameters:\n" + "- float: Quality score between 0 and 1, higher values indicate better quality" + ) + + def inference(self, input_text): + inputs = self.tokenizer(input_text, return_tensors='pt', padding=True, truncation=True, max_length=self.max_length).to(self.device) + with torch.no_grad(): + _, score = self.model(inputs) + return score.item() + + def eval(self, dataframe, input_key): + self.logger.info(f"Evaluating {self.score_name}...") + scores = [] + for sample in tqdm(dataframe[input_key], desc="PairQualScorer Evaluating..."): + score = self.inference(sample) + scores.append(score) + self.logger.info("Evaluation complete!") + return np.array(scores) + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='PairQualScore'): + dataframe = storage.read("dataframe") + scores = self.eval(dataframe, input_key) + dataframe[output_key] = scores + storage.write(dataframe) + + +class BertForRegression_en(PreTrainedModel): + config_class = BertConfig + + def __init__(self, config): + super().__init__(config) + + self.bert = BertModel(config) + self.regression = nn.Sequential( + nn.Linear(config.hidden_size, 512), + nn.ReLU(), + nn.Dropout(0.2), + nn.Linear(512, 1) + ) + + self.post_init() + + def forward(self, inputs): + encoded = self.bert(**inputs) + score = self.regression(encoded['pooler_output']) + return encoded, score + +class BertForRegression_zh(PreTrainedModel): + config_class = BertConfig + + def __init__(self, config): + super().__init__(config) + + self.bert = BertModel(config) + self.regression = nn.Sequential( + nn.Linear(config.hidden_size, 256), + nn.ReLU(), + nn.Linear(256, 1) + ) + + self.post_init() + + def forward(self, inputs): + encoded = self.bert(**inputs) + score = self.regression(encoded['pooler_output']) + return encoded, score \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/perplexity_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/perplexity_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..2a1eea63321a6c2f119a7038afd12fefc5f4cbf5 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/perplexity_sample_evaluator.py @@ -0,0 +1,80 @@ +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM +from tqdm import tqdm +from dataflow.core import OperatorABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.utils import get_logger + +@OPERATOR_REGISTRY.register() +class PerplexitySampleEvaluator(OperatorABC): + def __init__(self, model_name: str = 'gpt2', device='cuda'): + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.model_name = model_name + self.score_name = 'PerplexityScore' + self.device = device or ('cuda' if torch.cuda.is_available() else 'cpu') + # Load Hugging Face model and tokenizer + try: + self.tokenizer = AutoTokenizer.from_pretrained(self.model_name) + self.model = AutoModelForCausalLM.from_pretrained(self.model_name).to(self.device) + self.model.eval() # Set the model to evaluation mode + self.logger.info(f'{self.__class__.__name__} initialized with model {self.model_name}.') + except Exception as e: + self.logger.error(f"Error loading model: {e}") + raise RuntimeError(f"Model loading failed. Please ensure the model is available from Hugging Face.") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于Huggingface语言模型计算文本的困惑度(Perplexity),困惑度越低表示文本的流畅性和可理解性越高。" + "输入参数:\n" + "- model_name:Huggingface模型路径或名称\n" + "- device:模型运行设备\n" + "输出参数:\n" + "- float: 困惑度值,越低表示文本流畅性越好" + ) + else: + return ( + "Calculate text perplexity using a Huggingface language model; lower perplexity indicates better fluency and understandability." + "Input Parameters:\n" + "- model_name: Huggingface model path or name\n" + "- device: Model device\n\n" + "Output Parameters:\n" + "- float: Perplexity score, lower values indicate better fluency and understandability" + ) + + def eval(self, dataframe, input_key): + input_texts = dataframe.get(input_key, '').to_list() + self.logger.info(f"Evaluating {self.score_name}...") + results = [] + + # Use tqdm to show progress + for text in tqdm(input_texts, desc="Evaluating perplexity", unit="text"): + perplexity = self.calculate_perplexity(text) + results.append(perplexity) + + self.logger.info("Evaluation complete!") + return results + + def calculate_perplexity(self, text: str) -> float: + """ 使用Hugging Face模型计算困惑度 """ + # Encode the input text + inputs = self.tokenizer(text, return_tensors='pt', padding="longest", truncation=True).to(self.device) + # Calculate log probability + with torch.no_grad(): + outputs = self.model(**inputs, labels=inputs['input_ids']) + log_likelihood = outputs.loss * inputs['input_ids'].size(1) + + # Perplexity calculation formula: exp(log_prob / N) -> Perplexity = exp(-average log probability) + perplexity = torch.exp(log_likelihood / inputs['input_ids'].size(1)).item() + return perplexity + + def run(self, storage: DataFlowStorage, input_key: str = 'raw_content', output_key: str = 'PerplexityScore'): + # Read the data, evaluate the score, and save the results + dataframe = storage.read("dataframe") + self.logger.info(f"Perplexity score ready to evaluate.") + scores = self.eval(dataframe, input_key) + dataframe[output_key] = scores + storage.write(dataframe) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/qurating_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/qurating_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..3802ef61c279ec9adee42009dba7143240a40694 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/qurating_sample_evaluator.py @@ -0,0 +1,130 @@ +from dataflow.core import OperatorABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.storage import DataFlowStorage +from datasets import Dataset +from tqdm import tqdm +from dataflow import get_logger +from dataflow.operators.text_pt.eval.Qurating.qurater_annotate import ModelAnnotator +from dataflow.operators.text_pt.eval.Qurating.qurater_annotate import TokenizeAndChunk +import torch + +@OPERATOR_REGISTRY.register() +class QuratingSampleEvaluator(OperatorABC): + def __init__(self, map_batch_size: int = 512, num_workers: int = 1, device_batch_size: int = 16, device: str = 'cuda', + labels: list = ['writing_style', 'required_expertise', 'facts_and_trivia', 'educational_value'], model_cache_dir: str = './dataflow_cache'): + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.model = 'princeton-nlp/QuRater-1.3B' + self.tokens_field = 'input_ids' + self.tokens = 512 + self.map_batch_size = map_batch_size + self.batch_size = -1 + self.num_workers = num_workers + self.model_cache_dir = model_cache_dir + self.labels = labels or [] + self.device_batch_size = device_batch_size + self.device = device or ('cuda' if torch.cuda.is_available() else 'cpu') + self.score_type = float + self.data_type = 'text' + self.score_name = 'QuratingScore' + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "通过Qurating模型(princeton-nlp/QuRater-1.3B)从四个维度评估文本质量:写作风格(writing_style)、所需专业程度(required_expertise)、" + "事实与趣闻(facts_and_trivia)和教育价值(educational_value)。每个维度返回0-1之间的分数,综合评估文本的整体质量。\n" + "输入参数:\n" + "- text: 待评估的文本字符串\n" + "- labels: 评估维度列表,默认为['writing_style', 'required_expertise', 'facts_and_trivia', 'educational_value']\n" + "输出参数:\n" + "- dict: 包含各维度分数的字典,键为维度名称,值为0-1之间的分数" + ) + else: + return ( + "Evaluate text quality across four dimensions using the Qurating model (princeton-nlp/QuRater-1.3B): writing_style, required_expertise, " + "facts_and_trivia, and educational_value. Each dimension returns a score between 0 and 1, providing a comprehensive assessment of overall text quality.\n" + "Input parameters:\n" + "- text: Text string to be evaluated\n" + "- labels: List of evaluation dimensions, default ['writing_style', 'required_expertise', 'facts_and_trivia', 'educational_value']\n" + "Output parameters:\n" + "- dict: Dictionary containing scores for each dimension, with keys as dimension names and values as scores between 0 and 1" + ) + + def _score_func(self, sample): + """Process a single sample and return the score.""" + batch_dict = {'text': [sample]} # Wrap sample into a list for processing + dataset = Dataset.from_dict(batch_dict) + + # Tokenize and chunk + dataset = dataset.map( + TokenizeAndChunk(self.model, 'text', self.tokens_field, self.tokens, self.model_cache_dir), + batched=True, + batch_size=self.map_batch_size, + num_proc=self.num_workers, + remove_columns=dataset.column_names + ) + + # Annotate the model results + dataset = dataset.map( + ModelAnnotator(self.model, self.labels, self.device_batch_size, self.device, self.model_cache_dir), + batched=True, + with_indices=True, + batch_size=self.map_batch_size, + remove_columns=dataset.column_names + ) + + results_dict = dataset.to_dict() + result_filtered = {} + + for key in results_dict: + for label in self.labels: + average_key = f"{label}_average" + if average_key in results_dict[key]: + new_key = f"Qurating{''.join([word.capitalize() for word in label.split('_')])}Score" + result_filtered[new_key] = results_dict[key] + + return result_filtered + + def eval(self, dataframe, input_key): + self.logger.info(f"Evaluating {self.score_name}...") + batch_dict = {'text': dataframe[input_key]} # Wrap sample into a list for processing + dataset = Dataset.from_dict(batch_dict) + # Tokenize and chunk + dataset = dataset.map( + TokenizeAndChunk(self.model, 'text', self.tokens_field, self.tokens, self.model_cache_dir), + batched=True, + batch_size=self.map_batch_size, + num_proc=self.num_workers, + remove_columns=dataset.column_names + ) + + # Annotate the model results + dataset = dataset.map( + ModelAnnotator(self.model, self.labels, self.device_batch_size, self.device, self.model_cache_dir), + batched=True, + with_indices=True, + batch_size=self.map_batch_size, + remove_columns=dataset.column_names + ) + results_dict = dataset.to_dict() + result_filtered = {} + for label in self.labels: + average_key = f"{label}_average" + if average_key in results_dict: + new_key = f"Qurating{''.join([word.capitalize() for word in label.split('_')])}Score" + result_filtered[new_key] = results_dict[average_key] # Use the average values + + self.logger.info("Evaluation complete!") + return result_filtered + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str): + dataframe = storage.read("dataframe") + scores = self.eval(dataframe, input_key) + for score_dict in scores: + for key, value in score_dict.items(): + if key not in dataframe: + dataframe[key] = value + + storage.write(dataframe) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/textbook_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/textbook_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..3242fd0152fa54a4ef65538b10a248354f0c5956 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/eval/textbook_sample_evaluator.py @@ -0,0 +1,89 @@ +from typing import List +import re +from huggingface_hub import hf_hub_download +import fasttext +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.storage import DataFlowStorage +from tqdm import tqdm +import numpy as np + +@OPERATOR_REGISTRY.register() +class TextbookSampleEvaluator(OperatorABC): + def __init__(self, model_cache_dir='./dataflow_cache'): + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + model_path = hf_hub_download( + repo_id='kenhktsui/llm-data-textbook-quality-fasttext-classifer-v2', + filename='model.bin', + cache_dir=model_cache_dir + ) + low_score=1.0 + mid_score=3.0 + high_score=5.0 + self.model = fasttext.load_model(model_path) + self.score_type = float + self.data_type = 'text' + self.score_name = 'TextbookScore' + self.score_dict = { + '__label__Low': low_score, + '__label__Mid': mid_score, + '__label__High': high_score + } + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于FastText分类器(kenhktsui/llm-data-textbook-quality-fasttext-classifer-v2)评估文本的教育价值,将文本分为低(Low)、中(Mid)、高(High)三个等级," + "并映射为1.0、3.0、5.0的分数。适用于筛选适合作为教材的高质量文本内容。\n" + "输入参数:\n" + "- text: 待评估的文本字符串\n" + "输出参数:\n" + "- float: 教育价值分数,可能值为1.0(低)、3.0(中)、5.0(高)" + ) + else: + return ( + "Assess the educational value of text using a FastText classifier (kenhktsui/llm-data-textbook-quality-fasttext-classifer-v2), categorizing text into Low, Mid, and High levels, " + "mapped to scores of 1.0, 3.0, and 5.0 respectively. Suitable for filtering high-quality text content suitable as teaching materials.\n" + "Input parameters:\n" + "- text: Text string to be evaluated\n" + "Output parameters:\n" + "- float: Educational value score, possible values 1.0 (Low), 3.0 (Mid), 5.0 (High)" + ) + + @staticmethod + def replace_newlines(text: str) -> str: + return re.sub("\n+", " ", text) + + def _score_func(self, text_list: List[str]) -> List[float]: + text_list = [self.replace_newlines(text) for text in text_list] + pred = self.model.predict(text_list, k=-1) + + score_list = [] + for labels, scores in zip(*pred): + score = 0 + for label, score_value in zip(labels, scores): + score += self.score_dict.get(label, 0) * score_value + score_list.append(float(score)) + + return score_list + + def eval(self, dataframe, input_key): + scores = [] + text_list = dataframe[input_key] + self.logger.info(f"Evaluating {self.score_name}...") + for sample in tqdm(text_list, desc="TextbookScorer Evaluating..."): + score = self._score_func([sample]) + scores.append(score) + self.logger.info("Evaluation complete!") + return np.array(scores) + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='TextbookScore'): + dataframe = storage.read("dataframe") + scores = self.eval(dataframe, input_key, output_key) + for i, score_list in enumerate(scores): + dataframe[output_key] = score_list + storage.write(dataframe) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..12beb15978911c1ad945755e66d45c2fe89995ae --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__init__.py @@ -0,0 +1,60 @@ +# import sys +# from dataflow.utils.registry import LazyLoader + +# cur_path = "dataflow/operators/filter/" + +# _import_structure = { +# # Primary filters +# "NgramFilter": (cur_path + "ngram_filter.py", "NgramFilter"), +# "LanguageFilter": (cur_path + "language_filter.py", "LanguageFilter"), +# "DeitaQualityFilter": (cur_path + "deita_quality_filter.py", "DeitaQualityFilter"), +# "DeitaComplexityFilter": (cur_path + "deita_complexity_filter.py", "DeitaComplexityFilter"), +# "InstagFilter": (cur_path + "instag_filter.py", "InstagFilter"), +# "PairQualFilter": (cur_path + "pair_qual_filter.py", "PairQualFilter"), +# "QuratingFilter": (cur_path + "qurating_filter.py", "QuratingFilter"), +# "SuperfilteringFilter": (cur_path + "superfiltering_filter.py", "SuperfilteringFilter"), +# "FineWebEduFilter": (cur_path + "fineweb_edu_filter.py", "FineWebEduFilter"), +# "TextbookFilter": (cur_path + "text_book_filter.py", "TextbookFilter"), +# "AlpagasusFilter": (cur_path + "alpagasus_filter.py", "AlpagasusFilter"), +# "DebertaV3Filter": (cur_path + "debertav3_filter.py", "DebertaV3Filter"), +# "LangkitFilter": (cur_path + "langkit_filter.py", "LangkitFilter"), +# "LexicalDiversityFilter": (cur_path + "lexical_diversity_filter.py", "LexicalDiversityFilter"), +# "PerplexityFilter": (cur_path + "perplexity_filter.py", "PerplexityFilter"), +# "PerspectiveFilter": (cur_path + "perspective_filter.py", "PerspectiveFilter"), +# "PresidioFilter": (cur_path + "presidio_filter.py", "PresidioFilter"), +# "RMFilter": (cur_path + "reward_model_filter.py", "RMFilter"), +# "TreeinstructFilter": (cur_path + "treeinstruct_filter.py", "TreeinstructFilter"), + +# # Heuristic filters +# "ColonEndFilter": (cur_path + "heuristics.py", "ColonEndFilter"), +# "WordNumberFilter": (cur_path + "heuristics.py", "WordNumberFilter"), +# "BlocklistFilter": (cur_path + "heuristics.py", "BlocklistFilter"), +# "SentenceNumberFilter": (cur_path + "heuristics.py", "SentenceNumberFilter"), +# "LineEndWithEllipsisFilter": (cur_path + "heuristics.py", "LineEndWithEllipsisFilter"), +# "ContentNullFilter": (cur_path + "heuristics.py", "ContentNullFilter"), +# "MeanWordLengthFilter": (cur_path + "heuristics.py", "MeanWordLengthFilter"), +# "SymbolWordRatioFilter": (cur_path + "heuristics.py", "SymbolWordRatioFilter"), +# "HtmlEntityFilter": (cur_path + "heuristics.py", "HtmlEntityFilter"), +# "IDCardFilter": (cur_path + "heuristics.py", "IDCardFilter"), +# "NoPuncFilter": (cur_path + "heuristics.py", "NoPuncFilter"), +# "SpecialCharacterFilter": (cur_path + "heuristics.py", "SpecialCharacterFilter"), +# "WatermarkFilter": (cur_path + "heuristics.py", "WatermarkFilter"), +# "StopWordFilter": (cur_path + "heuristics.py", "StopWordFilter"), +# "CurlyBracketFilter": (cur_path + "heuristics.py", "CurlyBracketFilter"), +# "CapitalWordsFilter": (cur_path + "heuristics.py", "CapitalWordsFilter"), +# "LoremIpsumFilter": (cur_path + "heuristics.py", "LoremIpsumFilter"), +# "UniqueWordsFilter": (cur_path + "heuristics.py", "UniqueWordsFilter"), +# "CharNumberFilter": (cur_path + "heuristics.py", "CharNumberFilter"), +# "LineStartWithBulletpointFilter": (cur_path + "heuristics.py", "LineStartWithBulletpointFilter"), +# "LineWithJavascriptFilter": (cur_path + "heuristics.py", "LineWithJavascriptFilter"), + +# # Deduplicators +# "MinHashDeduplicator": (cur_path + "minhash_deduplicator.py", "MinHashDeduplicator"), +# "CCNetDeduplicator": (cur_path + "ccnet_deduplicator.py", "CCNetDeduplicator"), +# "HashDeduplicator": (cur_path + "hash_deduplicator.py", "HashDeduplicator"), +# "NgramHashDeduplicator": (cur_path + "ngramhash_deduplicator.py", "NgramHashDeduplicator"), +# "SemDeduplicator": (cur_path + "sem_deduplicator.py", "SemDeduplicator"), +# "SimHashDeduplicator": (cur_path + "simhash_deduplicator.py", "SimHashDeduplicator"), +# } + +# sys.modules[__name__] = LazyLoader(__name__, cur_path, _import_structure) \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b53b5935d14dbafca9b655c893e95ba24cd95f85 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__pycache__/ccnet_deduplicate_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__pycache__/ccnet_deduplicate_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6c4ea887cc71344a0bd3a6c33ff0e4e55ff3b2b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__pycache__/ccnet_deduplicate_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__pycache__/debertav3_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__pycache__/debertav3_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85d25fb4f53f8ce7dcfaf936174eb4732784d362 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__pycache__/debertav3_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__pycache__/fineweb_edu_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__pycache__/fineweb_edu_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8312b0421733b3633a0a5907e2f7e260ebcdc9fb Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__pycache__/fineweb_edu_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__pycache__/pair_qual_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__pycache__/pair_qual_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7482efe65b8fc1e35cd7734c16d41206b751daac Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__pycache__/pair_qual_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__pycache__/perplexity_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__pycache__/perplexity_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8283cca78f2483994887bce4bae9a061da719280 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__pycache__/perplexity_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__pycache__/qurating_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__pycache__/qurating_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1188cbe987c9da18d41e47813e430fe43d2d76f5 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__pycache__/qurating_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__pycache__/text_book_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__pycache__/text_book_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..852a7827d81ec1f8b085c571bd0678e1202c71ea Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/__pycache__/text_book_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/ccnet_deduplicate_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/ccnet_deduplicate_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..1fd77e68f6a1122256c4e94a38b6b66cbc1acc01 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/ccnet_deduplicate_filter.py @@ -0,0 +1,115 @@ +import hashlib +import struct +from tqdm import tqdm +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY + +def sha1_hash(data: bytes, d: int = 32) -> int: + """ + Generate a d-bit hash value from the given data. + + Parameters + ---------- + data : bytes + The data to be hashed. + d : int + The number of bits of the hash value. + + Returns + ------- + int + The hash value. + + Examples + -------- + >>> sha1_hash(b"hello world", 32) + 896314922 + >>> sha1_hash(b"hello world", 64) + 13028719972609469994 + >>> sha1_hash(b"hello world", 128) + 310522945683037930239412421226792791594 + """ + if d == 32: + return struct.unpack(" str: + return sha1_hash(text, self.bit_length) + + def run(self, storage: DataFlowStorage, input_keys: list = None, input_key: str = None, output_key: str = 'minhash_deduplicated_label'): + if input_keys is None and input_key is None: + self.logger.error(f"Need to specify either input_keys or input_key!") + raise ValueError(f"Need to specify either input_keys or input_key!") + if input_keys is not None and input_key is not None: + self.logger.error(f"{self.__class__.__name__} only need one input args!") + raise ValueError(f"{self.__class__.__name__} only need one input args!") + if input_keys is not None: + self.logger.info(f"Running {self.__class__.__name__} with input_keys = {input_keys} and output_key = {output_key}") + else: + self.logger.info(f"Running {self.__class__.__name__} with input_key = {input_key} and output_key = {output_key}") + self.input_key = input_key + self.input_keys = input_keys + self.output_key = output_key + seen_hashes = set() + dataframe = storage.read("dataframe") + labels = [0] * len(dataframe) + for idx, sample in tqdm(enumerate(dataframe.to_dict(orient='records')), desc=f"Implementing {self.__class__.__name__}", total=len(dataframe)): + if input_keys is not None and len(input_keys) > 1: + text = '\n'.join([f"{k}:\n{sample[k]}" for k in input_keys]) + else: + text = sample[self.input_key] + text = text.encode('utf-8') + hash_value = self._compute_hash(text) + if hash_value not in seen_hashes: + labels[idx] = 1 + seen_hashes.add(hash_value) + dataframe[self.output_key] = labels + filtered_dataframe = dataframe[(dataframe[self.output_key] > 0)] + output_file = storage.write(filtered_dataframe) + self.logger.info(f"Deduplication completed. Total unique items: {sum(labels)}") + return [self.output_key,] + + + + + + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/debertav3_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/debertav3_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..344e00bbb43ee4f88934f084abb88067ba442620 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/debertav3_filter.py @@ -0,0 +1,65 @@ +import numpy as np +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.operators.text_pt import DebertaV3SampleEvaluator + +@OPERATOR_REGISTRY.register() +class DebertaV3Filter(OperatorABC): + + def __init__(self, allowed_scores : list = ['Medium', 'High'], model_name='nvidia/quality-classifier-deberta', model_cache_dir='./dataflow_cache', device='cuda', batch_size=16): + self.logger = get_logger() + self.allowed_scores = allowed_scores + self.scorer = DebertaV3SampleEvaluator( + model_name=model_name, + model_cache_dir=model_cache_dir, + device=device, + batch_size=batch_size, + ) + self.logger.info(f"Initializing {self.__class__.__name__} with allowed_scores = {self.allowed_scores}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于DebertaV3Scorer打分器的得分对数据进行过滤。使用Nvidia Deberta V3模型的质量分类器评估文本质量。\n\n" + "初始化参数:\n" + "- allowed_scores: 允许通过的分数列表,默认为['Medium', 'High']\n" + "- model_name: 模型名称,默认为'nvidia/quality-classifier-deberta'\n" + "- model_cache_dir: 模型缓存目录,默认为'./dataflow_cache'\n" + "- device: 运行设备,默认为'cuda'\n" + "- batch_size: 批处理大小,默认为16\n\n" + "运行参数:\n" + "- input_key: 输入文本字段名\n" + "- output_key: 输出分数字段名,默认为'Debertav3Score'\n\n" + "过滤逻辑:保留分类结果在allowed_scores列表中的数据" + ) + else: + return ( + "Filter data using scores from the DebertaV3Scorer. Evaluate text quality using Nvidia Deberta V3 model-based quality classifier.\n\n" + "Initialization Parameters:\n" + "- allowed_scores: List of allowed scores, default is ['Medium', 'High']\n" + "- model_name: Model name, default is 'nvidia/quality-classifier-deberta'\n" + "- model_cache_dir: Model cache directory, default is './dataflow_cache'\n" + "- device: Running device, default is 'cuda'\n" + "- batch_size: Batch size, default is 16\n\n" + "Run Parameters:\n" + "- input_key: Input text field name\n" + "- output_key: Output score field name, default is 'Debertav3Score'\n\n" + "Filter Logic: Keep data with classification results in allowed_scores list" + ) + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str = 'Debertav3Score'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + scores = self.scorer.eval(dataframe, self.input_key) + dataframe[self.output_key] = scores + labels = np.array([1 if score in self.allowed_scores else 0 for score in scores]) + filtered_dataframe = dataframe[labels == 1] + output_file = storage.write(filtered_dataframe) + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + return [self.output_key] + + \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/fineweb_edu_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/fineweb_edu_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..20e05d02796ad6e4fafd8fa054ffacb4b311e264 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/fineweb_edu_filter.py @@ -0,0 +1,59 @@ +from dataflow.operators.text_pt import FineWebEduSampleEvaluator +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.utils import get_logger + +@OPERATOR_REGISTRY.register() +class FineWebEduFilter(OperatorABC): + def __init__(self, min_score: float = 2.5, max_score: float = 10000, model_cache_dir: str = './dataflow_cache', device: str = 'cuda'): + self.min_score = min_score + self.max_score = max_score + self.logger = get_logger() + self.scorer = FineWebEduSampleEvaluator(model_cache_dir=model_cache_dir, device=device) + self.filter_name = 'FineWebEduFilter' + self.logger.info(f"Initializing {self.filter_name} with min_score = {self.min_score}, max_score = {self.max_score}, " + f"device = {device}, model_cache_dir = {model_cache_dir}") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于FineWebEduScorer打分器的得分对数据进行过滤。Fineweb-Edu是一个用于评估文本教育价值的分类器。\n\n" + "初始化参数:\n" + "- min_score: 最低分数阈值,默认为2.5\n" + "- max_score: 最高分数阈值,默认为10000\n" + "- model_cache_dir: 模型缓存目录,默认为'./dataflow_cache'\n" + "- device: 运行设备,默认为'cuda'\n\n" + "运行参数:\n" + "- input_key: 输入文本字段名\n" + "- output_key: 输出分数字段名,默认为'FinewebEduScore'\n\n" + "评分标准:0-5分,分数越高表示文本具有越高的教育价值\n" + "过滤逻辑:保留分数在[min_score, max_score]范围内的数据" + ) + else: + return ( + "Filter data using scores from the FineWebEduScorer. Fineweb-Edu is a classifier for evaluating educational value of text.\n\n" + "Initialization Parameters:\n" + "- min_score: Minimum score threshold, default is 2.5\n" + "- max_score: Maximum score threshold, default is 10000\n" + "- model_cache_dir: Model cache directory, default is './dataflow_cache'\n" + "- device: Running device, default is 'cuda'\n\n" + "Run Parameters:\n" + "- input_key: Input text field name\n" + "- output_key: Output score field name, default is 'FinewebEduScore'\n\n" + "Scoring Standard: 0-5 points, higher score indicates more educational content\n" + "Filter Logic: Keep data with scores in [min_score, max_score] range" + ) + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='FinewebEduScore'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.filter_name}...") + scores = self.scorer.eval(dataframe, input_key) + dataframe[self.output_key] = scores + filtered_dataframe = dataframe[(scores >= self.min_score) & (scores <= self.max_score)] + storage.write(filtered_dataframe) + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + return [self.output_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/pair_qual_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/pair_qual_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..56515af7795675c8c55b1b761e84a7deedc089e8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/pair_qual_filter.py @@ -0,0 +1,66 @@ +from dataflow.operators.text_pt import PairQualSampleEvaluator +import numpy as np +from dataflow.core import OperatorABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.utils import get_logger +from dataflow.utils.storage import DataFlowStorage + +@OPERATOR_REGISTRY.register() +class PairQualFilter(OperatorABC): + def __init__(self, min_score=0, max_score=10000, model_cache_dir='./dataflow_cache', lang='en'): + self.logger = get_logger() + self.min_score = min_score + self.max_score = max_score + + self.scorer = PairQualSampleEvaluator(model_cache_dir=model_cache_dir, lang=lang) + self.filter_name = 'PairQualFilter' + + self.logger.info(f"Initializing {self.filter_name} with min_score = {self.min_score}, max_score = {self.max_score}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于PairQualScorer打分器的得分对数据进行过滤。基于BGE模型,使用GPT对文本成对比较打分后训练而成的双语文本质量评分器,得分越高表示质量越高。\n" + "输入参数:\n" + "- min_score:最小质量得分阈值\n" + "- max_score:最大质量得分阈值\n" + "- model_cache_dir:模型缓存目录路径\n" + "- lang:文本语言类型\n" + "输出参数:\n" + "- 过滤后的DataFrame,仅保留质量得分在指定范围内的文本\n" + "- 返回包含质量得分字段名的列表" + ) + else: + return ( + "Filter data using scores from the PairQualScorer. Bilingual text quality scorer trained on GPT pairwise comparison annotations using BGE model; higher scores indicate better quality.\n" + "Input Parameters:\n" + "- min_score: Minimum quality score threshold\n" + "- max_score: Maximum quality score threshold\n" + "- model_cache_dir: Model cache directory path\n" + "- lang: Text language type\n\n" + "Output Parameters:\n" + "- Filtered DataFrame containing only texts with quality score within specified range\n" + "- List containing quality score field name" + ) + + def eval(self, dataframe, input_key): + self.logger.info(f"Start evaluating {self.filter_name}...") + + # Get the scores using the scorer + scores = self.scorer.eval(dataframe, input_key) + + # Return the scores for filtering + return np.array(scores) + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='PairQualScore'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.filter_name} with input_key = {self.input_key} and output_key = {self.output_key}...") + scores = np.array(self.scorer.eval(dataframe, input_key)) + dataframe[self.output_key] = scores + filtered_dataframe = dataframe[(scores >= self.min_score) & (scores <= self.max_score)] + storage.write(filtered_dataframe) + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + return [self.output_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/perplexity_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/perplexity_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..f5cfc3a687ebe996a4a858a33a733617cf9b22fc --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/perplexity_filter.py @@ -0,0 +1,60 @@ +import numpy as np +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.operators.text_pt import PerplexitySampleEvaluator + +@OPERATOR_REGISTRY.register() +class PerplexityFilter(OperatorABC): + def __init__(self, min_score: float = 10.0, max_score: float = 500.0, model_name: str = 'gpt2', device='cuda'): + self.logger = get_logger() + self.min_score = min_score + self.max_score = max_score + self.scorer = PerplexitySampleEvaluator(model_name=model_name, device=device) + self.logger.info(f"Initializing {self.__class__.__name__} with min_score = {self.min_score} and max_score = {self.max_score}") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于PerplexityScorer打分器的得分对数据进行过滤。基于Huggingface模型计算文本的困惑度,困惑度越低,文本的流畅性和可理解性越高。\n" + "输入参数:\n" + "- min_score:最小困惑度阈值\n" + "- max_score:最大困惑度阈值\n" + "- model_name:Huggingface模型路径或名称\n" + "- device:模型运行设备\n" + "输出参数:\n" + "- 过滤后的DataFrame,仅保留困惑度在指定范围内的文本\n" + "- 返回包含困惑度得分字段名的列表" + ) + else: + return ( + "Filter data using scores from the PerplexityScorer. Uses Huggingface model to calculate text perplexity; lower scores indicate better fluency and understandability.\n" + "Input Parameters:\n" + "- min_score: Minimum perplexity threshold\n" + "- max_score: Maximum perplexity threshold\n" + "- model_name: Huggingface model path or name\n" + "- device: Model device\n\n" + "Output Parameters:\n" + "- Filtered DataFrame containing only texts with perplexity within specified range\n" + "- List containing perplexity score field name" + ) + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str = 'PerplexityScore'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key} and output_key = {self.output_key}...") + + # 获取得分并过滤 + scores = np.array(self.scorer.eval(dataframe, self.input_key)) + dataframe[self.output_key] = scores + filtered_dataframe = dataframe[(scores >= self.min_score) & (scores <= self.max_score)] + + # 将过滤后的数据框写回存储 + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/qurating_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/qurating_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..c468e7badb79014571f6d8b873318248a7bc8776 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/qurating_filter.py @@ -0,0 +1,99 @@ +from dataflow.operators.text_pt import QuratingSampleEvaluator +import numpy as np +from dataflow.core import OperatorABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.utils import get_logger +from dataflow.utils.storage import DataFlowStorage + +@OPERATOR_REGISTRY.register() +class QuratingFilter(OperatorABC): + + def __init__(self, min_scores: dict = {'writing_style': 0,'required_expertise': 0,'facts_and_trivia': 0,'educational_value': 0}, max_scores: dict = {'writing_style': 9,'required_expertise': 9,'facts_and_trivia': 9,'educational_value': 9}, + map_batch_size: int = 512, num_workers: int = 1, device_batch_size: int = 16, device: str = 'cuda', + labels: list = ['writing_style', 'required_expertise', 'facts_and_trivia', 'educational_value'], model_cache_dir: str = './dataflow_cache'): + self.logger = get_logger() + self.min_scores = min_scores + self.max_scores = max_scores + + # Initialize the QuratingScorer with the passed parameters + self.scorer = QuratingSampleEvaluator(map_batch_size=map_batch_size, + num_workers=num_workers, device_batch_size=device_batch_size, device=device, + labels=labels, model_cache_dir=model_cache_dir) + + self.logger.info(f"Initializing {self.__class__.__name__} with min_scores = {self.min_scores} and max_scores = {self.max_scores}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于QuratingScorer打分器的得分对数据进行过滤。通过Qurating模型从四个维度评估文本质量:写作风格、所需专业知识、事实与 trivia 内容、教育价值。\n" + "每个维度评分范围为0-9分,综合判断文本质量,可用于筛选高质量教育类或知识类内容。\n" + "输入参数:\n" + "- min_scores:各维度保留样本的最小分数阈值,默认为{'writing_style':0,'required_expertise':0,'facts_and_trivia':0,'educational_value':0}\n" + "- max_scores:各维度保留样本的最大分数阈值,默认为{'writing_style':9,'required_expertise':9,'facts_and_trivia':9,'educational_value':9}\n" + "- map_batch_size:映射批次大小,默认为512\n" + "- num_workers:数据加载工作进程数,默认为1\n" + "- device_batch_size:设备批次大小,默认为16\n" + "- device:模型运行设备,默认为'cuda'\n" + "- labels:评估维度列表,默认为['writing_style', 'required_expertise', 'facts_and_trivia', 'educational_value']\n" + "- model_cache_dir:模型缓存目录,默认为'./dataflow_cache'\n" + "输出参数:\n" + "- 过滤后的DataFrame,仅保留所有维度分数均在对应阈值范围内的样本\n" + "- 返回包含各维度过滤结果字段名的列表,用于后续算子引用" + ) + elif lang == "en": + return ( + "Filter data using scores from the QuratingScorer. Evaluate text quality across four dimensions using Qurating model: writing style, required expertise, facts and trivia content, and educational value.\n" + "Each dimension is scored from 0-9, providing comprehensive quality assessment for filtering high-quality educational or knowledge-based content.\n" + "Input Parameters:\n" + "- min_scores: Minimum score thresholds for each dimension, default is {'writing_style':0,'required_expertise':0,'facts_and_trivia':0,'educational_value':0}\n" + "- max_scores: Maximum score thresholds for each dimension, default is {'writing_style':9,'required_expertise':9,'facts_and_trivia':9,'educational_value':9}\n" + "- map_batch_size: Mapping batch size, default is 512\n" + "- num_workers: Number of data loading workers, default is 1\n" + "- device_batch_size: Device batch size, default is 16\n" + "- device: Model running device, default is 'cuda'\n" + "- labels: List of evaluation dimensions, default is ['writing_style', 'required_expertise', 'facts_and_trivia', 'educational_value']\n" + "- model_cache_dir: Model cache directory, default is './dataflow_cache'\n" + "Output Parameters:\n" + "- Filtered DataFrame containing only samples with all dimension scores within corresponding threshold ranges\n" + "- List containing field names of each dimension's filtering results for subsequent operator reference" + ) + else: + return "Filter data based on multi-dimensional quality assessment using Qurating model." + + + def run(self, storage: DataFlowStorage, input_key: str): + self.input_key = input_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__}...") + + # Get the scores for filtering + scores = self.scorer.eval(dataframe, self.input_key) + + # Initialize results to all valid (1) + results = np.ones(len(dataframe), dtype=int) + + # Iterate over each label to apply the filter and add a column + for label in self.min_scores.keys(): + min_score = self.min_scores[label] + max_score = self.max_scores[label] + score_key = f"Qurating{''.join([word.capitalize() for word in label.split('_')])}Score" + metric_scores = np.array(scores[score_key]) + + # Apply score filter for the current label + metric_filter = (min_score <= metric_scores) & (metric_scores <= max_score) + results = results & metric_filter.astype(int) + + # Add a new column with the name '{label}_filter' containing 0 or 1 based on the filter + dataframe[f"{label}_label"] = metric_filter.astype(int) + + # Filter the dataframe based on the results + filtered_dataframe = dataframe[results == 1] + # Write the filtered dataframe back to storage + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + result = [f"{label}_label" for label in self.min_scores.keys()] + + return result diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/text_book_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/text_book_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..68c18e6bbb0721dc2a4415c33b58f0d3ced666b0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/filter/text_book_filter.py @@ -0,0 +1,61 @@ +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.operators.text_pt import TextbookSampleEvaluator + +@OPERATOR_REGISTRY.register() +class TextbookFilter(OperatorABC): + + def __init__(self, min_score=0.99, max_score=1, model_cache_dir:str='./dataflow_cache'): + self.logger = get_logger() + self.min_score = min_score + self.max_score = max_score + self.scorer = TextbookSampleEvaluator(model_cache_dir=model_cache_dir) + self.logger.info(f"Initializing {self.__class__.__name__} with min_score = {min_score} and max_score = {max_score}") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于TextbookScorer打分器的得分对数据进行过滤。使用FastText分类器评估文本的教育价值,判断文本是否适合作为教材内容。\n" + "分类器经过训练可识别具有教育意义、结构清晰、知识准确的文本,适用于构建教育类数据集。\n" + "输入参数:\n" + "- min_score:保留样本的最小教育价值分数阈值,默认为0.99\n" + "- max_score:保留样本的最大教育价值分数阈值,默认为1.0\n" + "- model_cache_dir:模型缓存目录,默认为'./dataflow_cache'\n" + "- input_key:输入文本字段名\n" + "- output_key:教育价值分数字段名,默认为'TextbookScore'\n" + "输出参数:\n" + "- 过滤后的DataFrame,仅保留教育价值分数在[min_score, max_score]范围内的样本\n" + "- 返回包含教育价值分数字段名的列表,用于后续算子引用" + ) + elif lang == "en": + return ( + "Filter data using scores from the TextbookScorer. Assess educational value of text using FastText classifier to determine if text is suitable as educational material.\n" + "Classifier is trained to identify text with educational significance, clear structure, and accurate knowledge, suitable for building educational datasets.\n" + "Input Parameters:\n" + "- min_score: Minimum educational value score threshold for retaining samples, default is 0.99\n" + "- max_score: Maximum educational value score threshold for retaining samples, default is 1.0\n" + "- model_cache_dir: Model cache directory, default is './dataflow_cache'\n" + "- input_key: Input text field name\n" + "- output_key: Educational value score field name, default is 'TextbookScore'\n" + "Output Parameters:\n" + "- Filtered DataFrame containing only samples with educational value scores within [min_score, max_score] range\n" + "- List containing educational value score field name for subsequent operator reference" + ) + else: + return "Filter data based on educational value assessment using FastText textbook classifier." + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str='TextbookScore'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + scores = self.scorer.eval(dataframe, self.input_key) + dataframe[self.output_key] = scores + filtered_dataframe = dataframe[(dataframe[self.output_key] >= self.min_score) & (dataframe[self.output_key] <= self.max_score)] + output_file = storage.write(filtered_dataframe) + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + return [self.output_key] + + \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/generate/__pycache__/phi4qa_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/generate/__pycache__/phi4qa_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0ed94fdf9895121d68d92997ace29c3e70b335d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/generate/__pycache__/phi4qa_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/generate/phi4qa_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/generate/phi4qa_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..7cdc4383c868d6a3ac33be2fe6730a7741352ff1 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_pt/generate/phi4qa_generator.py @@ -0,0 +1,87 @@ +from dataflow.prompts.general_text import Phi4QAGeneratorPrompt +import pandas as pd +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger + +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +from dataflow.core.prompt import prompt_restrict + +@prompt_restrict( + Phi4QAGeneratorPrompt +) + +@OPERATOR_REGISTRY.register() +class Phi4QAGenerator(OperatorABC): + ''' + Answer Generator is a class that generates answers for given questions. + ''' + def __init__(self, llm_serving: LLMServingABC): + self.logger = get_logger() + self.prompts = Phi4QAGeneratorPrompt() + self.llm_serving = llm_serving + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于给定文档内容,生成预训练格式的多轮对话问答数据。将原始文档内容转换为适合语言模型预训练的对话格式数据。" + "输入参数:\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口\n" + "- input_key:输入文档内容字段名,默认为'raw_content'\n" + "- output_key:输出生成内容字段名,默认为'generated_content'\n" + "输出参数:\n" + "- 包含原始内容和生成内容的DataFrame\n" + "- 返回输出字段名,用于后续算子引用" + ) + elif lang == "en": + return ( + "Generate pre-training format multi-turn dialogue Q&A data based on the given document content. \n" + "Converts raw document content into dialogue format data suitable for language model pre-training.\n" + "Input Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC interface\n" + "- input_key: Field name for input document content, default is 'raw_content'\n" + "- output_key: Field name for output generated content, default is 'generated_content'\n\n" + "Output Parameters:\n" + "- DataFrame containing original and generated content\n" + "- Returns output field name for subsequent operator reference" + ) + else: + return ( + "PretrainGenerator converts document content into pre-training format multi-turn dialogue data." + ) + + def run(self, storage: DataFlowStorage, input_key: str = "raw_content", output_key: str = "generated_content"): + self.input_key, self.output_key = input_key, output_key + self.logger.info("Running PretrainGenerator...") + + # Load the raw dataframe from the input file + dataframe = storage.read('dataframe') + self.logger.info(f"Loading, number of rows: {len(dataframe)}") + + # Create a list to hold all generated questions and answers + llm_inputs = [] + + # Prepare LLM inputs by formatting the prompt with raw content from the dataframe + for index, row in dataframe.iterrows(): + raw_content = row.get(self.input_key, '') + if raw_content: + llm_input = self.prompts.build_prompt(raw_content) + llm_inputs.append(llm_input) + + # Generate the text using the model + try: + self.logger.info("Generating text using the model...") + generated_outputs = self.llm_serving.generate_from_input(llm_inputs) + self.logger.info("Text generation completed.") + except Exception as e: + self.logger.error(f"Error during text generation: {e}") + return + + # Add the generated content back to the dataframe + dataframe['generated_content'] = generated_outputs + + # Save the updated dataframe to the output file + output_file = storage.write(dataframe) + return output_key \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5a5da160e2ee9c3c77758b6a231139255d847184 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/__init__.py @@ -0,0 +1,33 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from .eval.alpagasus_sample_evaluator import AlpagasusSampleEvaluator + from .eval.deita_quality_sample_evaluator import DeitaQualitySampleEvaluator + from .eval.deita_complexity_sample_evaluator import DeitaComplexitySampleEvaluator + from .eval.instag_sample_evaluator import InstagSampleEvaluator + from .eval.rm_sample_evaluator import RMSampleEvaluator + from .eval.superfiltering_sample_evaluator import SuperfilteringSampleEvaluator + from .eval.treeinstruct_sample_evaluator import TreeinstructSampleEvaluator + + + from .filter.alpagasus_filter import AlpagasusFilter + from .filter.deita_quality_filter import DeitaQualityFilter + from .filter.deita_complexity_filter import DeitaComplexityFilter + from .filter.instag_filter import InstagFilter + from .filter.rm_filter import RMFilter + from .filter.superfiltering_filter import SuperfilteringFilter + from .filter.treeinstruct_filter import TreeinstructFilter + + from .generate.condor_generator import CondorGenerator + from .generate.sft_generator_from_seed import SFTGeneratorSeed + + from .refine.condor_refiner import CondorRefiner + +else: + import sys + from dataflow.utils.registry import LazyLoader, generate_import_structure_from_type_checking + + cur_path = "dataflow/operators/text_sft/" + + _import_structure = generate_import_structure_from_type_checking(__file__, cur_path) + sys.modules[__name__] = LazyLoader(__name__, "dataflow/operators/text_sft/", _import_structure) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8fd01698d9217aaf850364899f6702926bce9ae Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/Superfiltering/__pycache__/data_analysis.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/Superfiltering/__pycache__/data_analysis.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ee8602362d66171d92f24f64203838eeed595f2 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/Superfiltering/__pycache__/data_analysis.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/Superfiltering/data_analysis.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/Superfiltering/data_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..26e72663de1fba86dc3066d2ac60b406e27c1443 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/Superfiltering/data_analysis.py @@ -0,0 +1,53 @@ +import os +import json +import torch +import argparse +from tqdm import tqdm + +from transformers import AutoTokenizer, AutoModelForCausalLM + + +PROMPT_DICT_NONE = { + "prompt_input": ( + "{instruction}\n{input}\n" + ), + "prompt_no_input": ( + "{instruction}\n" + ), +} +# Used to get the ppl and emb for the whole input +def get_perplexity_and_embedding_whole_text(tokenizer, model, text, max_length, device): + + input_ids = tokenizer.encode(text, return_tensors="pt", truncation=True, max_length=max_length).to(device) + + with torch.no_grad(): + outputs = model(input_ids, labels=input_ids.contiguous()) + loss = outputs.loss + perplexity = torch.exp(loss) + + return perplexity.to('cpu').item(), loss.to('cpu').item() + + +# Used to get the ppl and emb for part of input, used in conditional version, and token-wise loss +def get_perplexity_and_embedding_part_text(tokenizer, model, text, target_span, max_length, device): + + try: + input_ids = tokenizer.encode(text, return_tensors="pt", truncation=True, max_length=max_length).to(device) + + start_index = text.rfind(target_span) + start_token = len(tokenizer.encode(text[:start_index])) + end_token = input_ids.shape[1] + + labels = input_ids.clone() + labels[0, :start_token] = -100 + + with torch.no_grad(): + outputs = model(input_ids, labels=labels) + + loss = outputs.loss + perplexity = torch.exp(loss) + + return perplexity.to('cpu').item(), loss.to('cpu').item() + + except Exception: + return 0, 0 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/__pycache__/alpagasus_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/__pycache__/alpagasus_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be800b3b327bcc1f7a87b2cde501c78ecf174d48 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/__pycache__/alpagasus_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/__pycache__/deita_complexity_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/__pycache__/deita_complexity_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b528ef61dcd6b3986c690a52359e5f7f7ab2f251 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/__pycache__/deita_complexity_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/__pycache__/deita_quality_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/__pycache__/deita_quality_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e271f68d07a8bf875da3b6341b0f017bdd0bbebd Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/__pycache__/deita_quality_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/__pycache__/instag_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/__pycache__/instag_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25c1651d14feeb1d115aace956b54219993044ee Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/__pycache__/instag_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/__pycache__/rm_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/__pycache__/rm_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bbf31ec46183a6e410b615ce96e717d4b922aedb Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/__pycache__/rm_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/__pycache__/superfiltering_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/__pycache__/superfiltering_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b09d0d62f570ef7137f58c1c3b51b36dfc4cc650 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/__pycache__/superfiltering_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/__pycache__/treeinstruct_sample_evaluator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/__pycache__/treeinstruct_sample_evaluator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..877f634e227f483348e03b6246a356485054f85b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/__pycache__/treeinstruct_sample_evaluator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/alpagasus_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/alpagasus_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..d6a1fdc61140a3fe3808881e6aad98c2f0e701f3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/alpagasus_sample_evaluator.py @@ -0,0 +1,90 @@ +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +import pandas as pd +from dataflow.core import LLMServingABC +from dataflow.core.prompt import prompt_restrict +from dataflow.prompts.general_text import AlpagasusPrompt + +@prompt_restrict( + AlpagasusPrompt +) +@OPERATOR_REGISTRY.register() +class AlpagasusSampleEvaluator(OperatorABC): + def __init__(self, llm_serving: LLMServingABC = None, dimension: str = 'quality'): + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.llm_serving = llm_serving + self.score_name = 'AlpagasusScore' + self.dimension = dimension + self.prompt = AlpagasusPrompt(dimension=self.dimension) + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "通过调用GPT评估指令的质量,返回一个质量得分,得分越高表明指令的质量越高。\n" + "输入参数:\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口\n" + "- dimension:评估维度,默认为'quality'\n" + "- input_instruction_key:指令字段名\n" + "- input_input_key:输入文本字段名\n" + "- input_output_key:输出文本字段名\n" + "- output_key:输出得分字段名,默认'AlpagasusScore'\n" + "输出参数:\n" + "- 包含评估得分的DataFrame" + ) + elif lang == "en": + return ( + "Evaluate instruction quality using GPT; higher scores indicate better quality.\n" + "Input Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC interface\n" + "- dimension: Evaluation dimension, default 'quality'\n" + "- input_instruction_key: Field name for instruction\n" + "- input_input_key: Field name for input text\n" + "- input_output_key: Field name for output text\n" + "- output_key: Field name for output score, default 'AlpagasusScore'\n" + "Output Parameters:\n" + "- DataFrame containing evaluation scores" + ) + else: + return "Evaluate instruction quality using GPT; higher scores indicate better quality." + + def get_score(self, samples, input_instruction_key, input_input_key, input_output_key): + system_prompts = [] + user_prompts = [] + for sample in samples: + instruction = sample.get(input_instruction_key, ['']) + response = sample.get(input_output_key, ['']) + input_text = sample.get(input_input_key, ['']) + system_prompts.append(self.prompt.build_system_prompt(instruction, input_text, response)) + user_prompts.append(self.prompt.build_prompt()) + inputs = [system + "\n" + user for system, user in zip(system_prompts, user_prompts)] + responses = self.llm_serving.generate_from_input(user_inputs=inputs) + scores = [] + for response in responses: + score_line = response.strip().split("\n")[0] + score = float(score_line.split()[0]) + scores.append(score) + + return scores + + def eval(self, dataframe: pd.DataFrame, input_instruction_key: str, input_input_key: str, input_output_key: str): + samples = dataframe.to_dict(orient='records') + self.logger.info(f"Evaluating {self.score_name}...") + scores = self.get_score(samples, input_instruction_key, input_input_key, input_output_key) + self.logger.info("Evaluation complete!") + return scores + + + def run(self, storage: DataFlowStorage, input_instruction_key: str, input_input_key: str, input_output_key: str, output_key: str='AlpagasusScore'): + self.input_instruction_key = input_instruction_key + self.input_input_key = input_input_key + self.input_output_key = input_output_key + self.output_key = output_key + dataframe = storage.read("dataframe") + scores = self.eval(dataframe, self.input_instruction_key, self.input_input_key, self.input_output_key) + dataframe[self.output_key] = scores + storage.write(dataframe) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/deita_complexity_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/deita_complexity_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..e4ba8849f173c079c936541072a707733d1fd9e9 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/deita_complexity_sample_evaluator.py @@ -0,0 +1,96 @@ +from dataflow.core import OperatorABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.storage import DataFlowStorage +from transformers import AutoTokenizer, AutoModelForCausalLM +import numpy as np +from scipy.special import softmax +from dataflow import get_logger +import torch +from tqdm import tqdm + +@OPERATOR_REGISTRY.register() +class DeitaComplexitySampleEvaluator(OperatorABC): + def __init__(self, device='cuda', model_cache_dir='./dataflow_cache', max_length=512): + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.device = device or ('cuda' if torch.cuda.is_available() else 'cpu') + self.model_name = "hkust-nlp/deita-complexity-scorer" + self.model_cache_dir = model_cache_dir + self.max_length = max_length + self.tokenizer = AutoTokenizer.from_pretrained(self.model_name, cache_dir=self.model_cache_dir) + self.model = AutoModelForCausalLM.from_pretrained(self.model_name, cache_dir=self.model_cache_dir).to(self.device) + self.score_name = 'DeitaComplexityScore' + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于Llama模型的Deita指令复杂性评估器,通过生成1-6分的复杂性评分评估指令难度。\n" + "输入参数:\n" + "- device:计算设备,默认为'cuda'\n" + "- model_cache_dir:模型缓存目录,默认为'./dataflow_cache'\n" + "- max_length:最大序列长度,默认为512\n" + "- input_instruction_key:指令文本字段名,默认为'instruction'\n" + "- input_output_key:输出文本字段名,默认为'output'\n" + "- output_key:输出得分字段名,默认为'DeitaComplexityScore'\n" + "输出参数:\n" + "- 包含指令复杂性评分的DataFrame(1-6分)" + ) + elif lang == "en": + return ( + "Llama-based Deita instruction complexity evaluator generating 1-6 complexity scores.\n" + "Input Parameters:\n" + "- device: Computing device, default 'cuda'\n" + "- model_cache_dir: Model cache directory, default './dataflow_cache'\n" + "- max_length: Maximum sequence length, default 512\n" + "- input_instruction_key: Field name for instruction text, default 'instruction'\n" + "- input_output_key: Field name for output text, default 'output'\n" + "- output_key: Field name for output score, default 'DeitaComplexityScore'\n" + "Output Parameters:\n" + "- DataFrame containing instruction complexity scores (1-6)" + ) + else: + return "Measure instruction complexity using Llama-based Deita model." + + def infer_complexity(self, input_text): + complexity_template = ("You are a helpful assistant. Please identify the complexity score of the following user query. \n##Query: {instruction}\n##Complexity: ") + user_input = complexity_template.format(instruction=input_text) + input_ids = self.tokenizer.encode(user_input, return_tensors="pt").to(self.device) + outputs = self.model.generate(input_ids, max_new_tokens=self.max_length, num_return_sequences=1, return_dict_in_generate=True, output_scores=True) + logprobs_list = outputs.scores[0][0] + # Mapping of token IDs to complexity scores + id2score = { + 29896: 1, # Complexity level 1 + 29906: 2, # Complexity level 2 + 29941: 3, # Complexity level 3 + 29946: 4, # Complexity level 4 + 29945: 5, # Complexity level 5 + 29953: 6 # Complexity level 6 + } + score_template = np.array([1, 2, 3, 4, 5, 6]) # Define the score template + score_logits = [] + for k in id2score: + score_logits.append(logprobs_list[k].cpu().numpy()) + + score_logits = np.array(score_logits) + score_npy = softmax(score_logits, axis=0) # Apply softmax to get probabilities + score_npy = score_npy * score_template # Weight the scores by the corresponding complexity level + final_score = np.sum(score_npy, axis=0) # Sum the weighted scores to get the final score + return final_score + + def eval(self, dataframe, input_instruction_key: str = 'instruction', input_output_key: str = 'output'): + self.logger.info(f"Evaluating {self.score_name}...") + scores = [] + for sample in tqdm(dataframe[[input_instruction_key, input_output_key]].to_dict(orient='records'), desc="Deita complexity model evaluating..."): + quality_score = self.infer_complexity(sample[input_instruction_key]) + scores.append(quality_score) + self.logger.info("Evaluation complete!") + return scores + + def run(self, storage: DataFlowStorage, input_instruction_key: str = 'instruction', input_output_key: str = 'output', output_key: str = 'DeitaComplexityScore'): + + dataframe = storage.read("dataframe") + scores = self.eval(dataframe, input_instruction_key, input_output_key) + dataframe[output_key] = scores + storage.write(dataframe) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/deita_quality_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/deita_quality_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..2bd63e34abd13fb19d42d4ddc1d5a2aebbabc2db --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/deita_quality_sample_evaluator.py @@ -0,0 +1,102 @@ +from dataflow.core import OperatorABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.storage import DataFlowStorage +from transformers import AutoTokenizer, AutoModelForCausalLM +import numpy as np +from scipy.special import softmax +import requests +import torch +from dataflow import get_logger +from tqdm import tqdm + +@OPERATOR_REGISTRY.register() +class DeitaQualitySampleEvaluator(OperatorABC): + def __init__(self, device='cuda', model_cache_dir='./dataflow_cache', max_length=512): + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.device = device or ('cuda' if torch.cuda.is_available() else 'cpu') + self.model_name = 'hkust-nlp/deita-quality-scorer' + self.model_cache_dir = model_cache_dir + self.max_length = max_length + self.token_strs = ["1", "2", "3", "4", "5", "6"] + self.score_template = np.array([1, 2, 3, 4, 5, 6]) + self.tokenizer = AutoTokenizer.from_pretrained(self.model_name, cache_dir=self.model_cache_dir) + self.model = AutoModelForCausalLM.from_pretrained(self.model_name, cache_dir=self.model_cache_dir).to(self.device) + self.score_name = 'DeitaQualityScore' + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于Llama模型的Deita指令质量评估器,通过生成1-6分的质量评分评估指令质量。\n" + "输入参数:\n" + "- device:计算设备,默认为'cuda'\n" + "- model_cache_dir:模型缓存目录,默认为'./dataflow_cache'\n" + "- max_length:最大序列长度,默认为512\n" + "- input_instruction_key:指令文本字段名,默认为'instruction'\n" + "- input_output_key:输出文本字段名,默认为'output'\n" + "- output_key:输出得分字段名,默认为'DeitaQualityScore'\n" + "输出参数:\n" + "- 包含指令质量评分的DataFrame(1-6分)" + ) + elif lang == "en": + return ( + "Llama-based Deita instruction quality evaluator generating 1-6 quality scores.\n" + "Input Parameters:\n" + "- device: Computing device, default 'cuda'\n" + "- model_cache_dir: Model cache directory, default './dataflow_cache'\n" + "- max_length: Maximum sequence length, default 512\n" + "- input_instruction_key: Field name for instruction text, default 'instruction'\n" + "- input_output_key: Field name for output text, default 'output'\n" + "- output_key: Field name for output score, default 'DeitaQualityScore'\n" + "Output Parameters:\n" + "- DataFrame containing instruction quality scores (1-6)" + ) + else: + return "Evaluate instruction quality using Llama-based Deita model." + + def infer_quality(self, input_text, resp_text): + # Define the template and input format + quality_template = ("You are a helpful assistant. Please identify the quality score of the Response corresponding to the Question.\n" + "#Question#:\n{instruction}\n#Response#:\n{output}\n##Quality: ") + user_input = quality_template.format(instruction=input_text, output=resp_text) + + + input_ids = self.tokenizer.encode(user_input, return_tensors="pt").to(self.device) + outputs = self.model.generate(input_ids, max_new_tokens=self.max_length, num_return_sequences=1, return_dict_in_generate=True, output_scores=True) + logprobs_list = outputs.scores[0][0] + + id2score = { + 29896: "1", + 29906: "2", + 29941: "3", + 29946: "4", + 29945: "5", + 29953: "6" + } + + score_logits = [] + for k in id2score: + score_logits.append(logprobs_list[k].cpu().numpy()) + + score_logits = np.array(score_logits) + score_npy = softmax(score_logits, axis=0) + score_npy = score_npy * self.score_template + final_score = np.sum(score_npy, axis=0) + return final_score + + def eval(self, dataframe, input_instruction_key: str = 'instruction', input_output_key: str = 'output'): + scores = [] + self.logger.info(f"Evaluating {self.score_name}...") + for sample in tqdm(dataframe[[input_instruction_key, input_output_key]].to_dict(orient='records'), desc="Deita quality model Evaluating..."): + quality_score = self.infer_quality(sample[input_instruction_key], sample[input_output_key]) # assuming response and instruction are the same for now + scores.append(quality_score) + self.logger.info("Evaluation complete!") + return scores + + def run(self, storage: DataFlowStorage, input_instruction_key: str = 'instruction', input_output_key: str = 'output', output_key: str = 'DeitaQualityScore'): + dataframe = storage.read("dataframe") + scores = self.eval(dataframe, input_instruction_key, input_output_key) + dataframe[output_key] = scores + storage.write(dataframe) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/instag_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/instag_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..53afdfe8a809763f8bfcfc647195354a5c2e1ed7 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/instag_sample_evaluator.py @@ -0,0 +1,132 @@ +from dataflow.core import OperatorABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.storage import DataFlowStorage +from transformers import AutoTokenizer, AutoModelForCausalLM +import numpy as np +import pandas as pd +from tqdm import tqdm +import torch +from dataflow import get_logger +import json + +@OPERATOR_REGISTRY.register() +class InstagSampleEvaluator(OperatorABC): + def __init__(self, model_cache_dir='./dataflow_cache', device='cuda', max_new_tokens=1024, temperature=0, do_sample=False, num_return_sequences=1, return_dict_in_generate=True): + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.device = device or ('cuda' if torch.cuda.is_available() else 'cpu') + self.model_name = 'OFA-Sys/InsTagger' + self.model_cache_dir = model_cache_dir + self.max_new_tokens = max_new_tokens + self.temperature = temperature + self.do_sample = do_sample + self.num_return_sequences = num_return_sequences + self.return_dict_in_generate = return_dict_in_generate + self.token_strs = ["1", "2", "3", "4", "5", "6"] + self.score_template = np.array([1, 2, 3, 4, 5, 6]) + self.tokenizer = AutoTokenizer.from_pretrained(self.model_name, cache_dir=self.model_cache_dir) + self.model = AutoModelForCausalLM.from_pretrained(self.model_name, cache_dir=self.model_cache_dir).to(self.device) + self.model.requires_grad_(False) + self.model.eval() + self.score_name = 'InstagScore' + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "使用Instag评分器评估指令的内容多样性和意图标签。通过分析指令文本生成相关标签,标签数量越多表示内容多样性越大," + "同时返回标签的详细解释。基于OFA-Sys/InsTagger模型实现。\n" + "输入参数:\n" + "- query: 待评估的指令文本\n" + "输出参数:\n" + "- int: 标签数量(内容多样性指标)\n" + "- list: 包含标签和解释的字典列表" + ) + else: + return ( + "Evaluate instruction content diversity and intention tags using the Instag scorer. Generate relevant tags by analyzing instruction text, " + "with more tags indicating greater content diversity, while returning detailed explanations of tags. Implemented based on OFA-Sys/InsTagger model.\n" + "Input parameters:\n" + "- query: Instruction text to be evaluated\n" + "Output parameters:\n" + "- int: Number of tags (content diversity indicator)\n" + "- list: List of dictionaries containing tags and explanations" + ) + + def make_prompt(self, query): + prompt = f"Please identify tags of user intentions in the following user query and provide an explanation for each tag. Please respond in the JSON format {{\"tag\": str, \"explanation\": str}}.\nUser query: {query}" + messages = [("user", prompt), ("Assistant", None)] + seps = [" ", ""] + ret = "system: A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions." + seps[0] + for i, (role, message) in enumerate(messages): + if message: + ret += role + ": " + message + seps[i % 2] + else: + ret += role + ":" + return ret + + def inference_batch(self, queries): + """Process batch of queries using either local model or API.""" + input_strs = [self.make_prompt(query) for query in queries] + input_tokens = self.tokenizer(input_strs, return_tensors="pt", padding=True) + + if torch.cuda.is_available(): + input_tokens = {key: value.to(self.device) for key, value in input_tokens.items()} + + output = self.model.generate( + input_tokens['input_ids'], + temperature=self.temperature, + do_sample=self.do_sample, + max_new_tokens=self.max_new_tokens, + num_return_sequences=self.num_return_sequences, + return_dict_in_generate=self.return_dict_in_generate, + ) + + num_input_tokens = input_tokens["input_ids"].shape[1] + output_tokens = output.sequences + generated_tokens = output_tokens[:, num_input_tokens:] + generated_texts = self.tokenizer.batch_decode(generated_tokens, skip_special_tokens=True) + + json_outputs = [] + for generated_text in generated_texts: + string_output = generated_text.strip() + try: + json_output = json.loads(string_output) + except json.JSONDecodeError: + self.logger.warning(f"JSON parse error: {string_output}") + json_output = {"tag": "Parsing error", "explanation": string_output[:100]} + json_outputs.append(json_output) + + return json_outputs + + def _score_func(self, sample, input_instruction_key): + json_output = self.inference_batch([sample])[0] + complexity_score = None + if isinstance(json_output, list): + complexity_score = len(json_output) + self.logger.info(f"列表类型JSON,标签数量: {complexity_score}") + elif isinstance(json_output, dict) and "tag" in json_output: + complexity_score = 1 + self.logger.info(f"字典类型JSON,包含tag字段,评分为1") + elif isinstance(json_output, dict) and len(json_output) > 0: + complexity_score = 1 + self.logger.info(f"其他字典类型JSON,评分为1: {json_output}") + else: + complexity_score = 0 + self.logger.warning(f"未识别的JSON类型或空数据,评分为0: {json_output}") + return complexity_score + + def eval(self, dataframe: pd.DataFrame, input_instruction_key: str): + self.logger.info(f"Evaluating {self.score_name}...") + scores = [] + for sample in tqdm(dataframe[input_instruction_key], desc="Instagger mode evaluating..."): + scores.append(self._score_func(sample, input_instruction_key)) + self.logger.info("Evaluation complete!") + return scores + + def run(self, storage: DataFlowStorage, input_instruction_key: str = 'instruction', output_key: str = 'InstagScore'): + dataframe = storage.read("dataframe") + scores = self.eval(dataframe, input_instruction_key) + dataframe[output_key] = scores + storage.write(dataframe) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/rm_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/rm_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..0be42ee317c0a6cad372a6b0a0a29535a6787b8f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/rm_sample_evaluator.py @@ -0,0 +1,62 @@ +from transformers import AutoModelForSequenceClassification, AutoTokenizer +from dataflow.core import OperatorABC +from dataflow.utils.registry import OPERATOR_REGISTRY +import torch +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.utils import get_logger + +# RMScorer for evaluating based on reward-model-deberta-v3-large-v2 +@OPERATOR_REGISTRY.register() +class RMSampleEvaluator(OperatorABC): + def __init__(self, device='cuda', model_cache_dir='./dataflow_cache', ): + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.model_name = 'OpenAssistant/reward-model-deberta-v3-large-v2' + self.model_cache_dir = model_cache_dir + self.score_name = 'RewardModelScore' + self.device = device + self.rank_model = AutoModelForSequenceClassification.from_pretrained(self.model_name, cache_dir=self.model_cache_dir).to(self.device) + self.tokenizer = AutoTokenizer.from_pretrained(self.model_name, cache_dir=self.model_cache_dir) + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于人类偏好数据训练的奖励模型(OpenAssistant/reward-model-deberta-v3-large-v2)对文本质量进行打分,高分代表质量较高。" + "模型输入为指令和响应文本对,输出0-1之间的奖励分数,反映人类对文本质量的偏好判断。\n" + "输入参数:\n" + "- instruction: 指令文本字符串\n" + "- output: 响应文本字符串\n" + "输出参数:\n" + "- float: 0-1之间的奖励分数,越高表示质量越好" + ) + else: + return ( + "Score text quality using a reward model trained on human preference data (OpenAssistant/reward-model-deberta-v3-large-v2), where higher scores indicate better quality. " + "The model takes instruction-response text pairs as input and outputs a reward score between 0 and 1, reflecting human preference judgments on text quality.\n" + "Input parameters:\n" + "- instruction: Instruction text string\n" + "- output: Response text string\n" + "Output parameters:\n" + "- float: Reward score between 0 and 1, higher values indicate better quality" + ) + + def eval(self, dataframe, input_instruction_key: str = 'instruction', input_output_key: str = 'output'): + input_texts = dataframe.get(input_instruction_key, '').to_list() + output_texts = dataframe.get(input_output_key, '').to_list() + inputs = self.tokenizer(input_texts, output_texts, return_tensors='pt', padding=True, truncation=True).to(self.device) + self.logger.info(f"Evaluating {self.score_name}...") + with torch.no_grad(): + logits = self.rank_model(**inputs).logits.cpu().detach().numpy() + scores = logits.squeeze() + if scores.ndim == 0: + scores = [float(scores)] + self.logger.info("Evaluation complete!") + return scores.tolist() + + def run(self, storage: DataFlowStorage, input_instruction_key: str = 'instruction', input_output_key: str = 'output', output_key: str = 'RMScore'): + dataframe = storage.read("dataframe") + scores = self.eval(dataframe, input_instruction_key, input_output_key) + dataframe[output_key] = scores + storage.write(dataframe) \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/superfiltering_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/superfiltering_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..db6a816d7a235c298189ff8f945ec6f72a3fe3a3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/superfiltering_sample_evaluator.py @@ -0,0 +1,124 @@ +from dataflow.core import OperatorABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.operators.text_sft.eval.Superfiltering.data_analysis import get_perplexity_and_embedding_whole_text, get_perplexity_and_embedding_part_text +from transformers import AutoTokenizer, AutoModelForCausalLM +from tqdm import tqdm +import torch +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.utils import get_logger +import pandas as pd + +# Superfiltering instruction quality (ifd) evaluation +# cited from: Superfiltering: Weak-to-Strong Data Filtering for Fast Instruction-Tuning +@OPERATOR_REGISTRY.register() +class SuperfilteringSampleEvaluator(OperatorABC): + def __init__(self, device='cuda', model_cache_dir='./dataflow_cache', max_length=512): + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.device = device + self.model_name = 'gpt2' + self.model_cache_dir = model_cache_dir + self.max_length = max_length + self.tokenizer = AutoTokenizer.from_pretrained(self.model_name, cache_dir=self.model_cache_dir) + self.model = AutoModelForCausalLM.from_pretrained( + self.model_name, + device_map=self.device, + cache_dir=self.model_cache_dir, + output_hidden_states=True + ).to(self.device) + self.score_name = 'SuperfilteringScore' + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "使用Superfiltering方法评估指令的跟随难度,基于GPT-2模型计算条件困惑度与独立困惑度的比值,得分越高表示指令越难跟随。" + "该方法通过比较指令条件下的响应困惑度与独立响应困惑度,评估指令的清晰度和跟随难度。\n" + "输入参数:\n" + "- instruction: 指令文本\n" + "- input_text: 输入文本(可选)\n" + "- output: 响应文本\n" + "输出参数:\n" + "- float: 困惑度比值,越高表示指令跟随难度越大" + ) + else: + return ( + "Evaluate the follow difficulty of instructions using the Superfiltering method, which calculates the ratio of conditional perplexity to independent perplexity based on the GPT-2 model. " + "Higher scores indicate greater difficulty in following the instruction. This method assesses instruction clarity and follow difficulty by comparing response perplexity under instruction conditions with independent response perplexity.\n" + "Input parameters:\n" + "- instruction: Instruction text\n" + "- input_text: Input text (optional)\n" + "- output: Response text\n" + "Output parameters:\n" + "- float: Perplexity ratio, higher values indicate greater instruction following difficulty" + ) + + def inference(self, instruction, input_text, output): + PROMPT_DICT_NONE = { + "prompt_input": ( + "{instruction}\n{input}\n" + ), + "prompt_no_input": ( + "{instruction}\n" + ), + } + prompt_no_input = PROMPT_DICT_NONE["prompt_no_input"] + prompt_input = PROMPT_DICT_NONE["prompt_input"] + + if input_text == '': + temp_dict = {'instruction': instruction} + prompt_to_use = prompt_no_input.format_map(temp_dict) + whole_text = prompt_to_use + output + instruction = prompt_to_use + else: + temp_dict = {'instruction': instruction, 'input': input_text} + prompt_to_use = prompt_input.format_map(temp_dict) + whole_text = prompt_to_use + output + instruction = prompt_to_use + + if output == '': + return None + + instruction_input_ids = self.tokenizer.encode(instruction, return_tensors="pt", truncation=True, max_length=self.max_length).to(self.device) + instruction_len = instruction_input_ids.shape[1] + + ppl_out_alone, _ = get_perplexity_and_embedding_whole_text(self.tokenizer, self.model, output, self.max_length - instruction_len + 1, self.device) + ppl_out_condition, _ = get_perplexity_and_embedding_part_text(self.tokenizer, self.model, whole_text, output, self.max_length, self.device) + + if ppl_out_alone != 0: + score = ppl_out_condition / ppl_out_alone + else: + score = 0 + + if score != score: # 检查NaN + score = None + + return score + + def _score_func(self, sample, input_instruction_key: str = 'instruction', input_input_key: str = 'input', input_output_key: str = 'output'): + instruction = sample.get(input_instruction_key, ['']) + output = sample.get(input_output_key, ['']) + input_text = sample.get(input_input_key, ['']) if input_input_key is not None and input_input_key in sample else '' + + if not output: + score = None + else: + score = self.inference(instruction, input_text, output) + + return score + + def eval(self, dataframe: pd.DataFrame, input_instruction_key: str = 'instruction', input_input_key: str = None, input_output_key: str = 'output'): + self.logger.info(f"Evaluating {self.score_name}...") + key_list = [input_instruction_key, input_output_key] + if input_input_key is not None: + key_list.append(input_input_key) + scores = [self._score_func(sample, input_instruction_key, input_input_key, input_output_key) for sample in tqdm(dataframe[key_list].to_dict(orient='records'), desc="SuperfilteringScorer evaluating...")] + self.logger.info("Evaluation complete!") + return scores + + def run(self, storage: DataFlowStorage, input_instruction_key: str = 'instruction', input_input_key: str = None, input_output_key: str = 'output', output_key: str = 'SuperfilteringScore'): + dataframe = storage.read("dataframe") + scores = self.eval(dataframe, input_instruction_key, input_input_key, input_output_key) + dataframe[output_key] = scores + storage.write(dataframe) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/treeinstruct_sample_evaluator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/treeinstruct_sample_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..858a98abdf4f3bccba092435a4602c122b13d484 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/eval/treeinstruct_sample_evaluator.py @@ -0,0 +1,83 @@ +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +import pandas as pd +from dataflow.core import LLMServingABC +from dataflow.prompts.general_text import TreeinstructPrompt +from dataflow.core.prompt import prompt_restrict + +@prompt_restrict( + TreeinstructPrompt +) + +@OPERATOR_REGISTRY.register() +class TreeinstructSampleEvaluator(OperatorABC): + def __init__(self, llm_serving: LLMServingABC = None): + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.llm_serving = llm_serving + self.score_name = 'TreeinstructScore' + self.prompt = TreeinstructPrompt() + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "通过生成语法树的节点数来衡量指令复杂性,节点越多表示指令越复杂。\n" + "输入参数:\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口\n" + "- input_instruction_key:指令字段名\n" + "- output_key:输出得分字段名,默认'TreeinstructScore'\n" + "输出参数:\n" + "- 包含指令复杂性得分的DataFrame" + ) + elif lang == "en": + return ( + "Measure instruction complexity by syntax tree size; more nodes mean more complexity.\n" + "Input Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC interface\n" + "- input_instruction_key: Field name for instruction\n" + "- output_key: Field name for output score, default 'TreeinstructScore'\n" + "Output Parameters:\n" + "- DataFrame containing instruction complexity scores" + ) + else: + return "Measure instruction complexity by syntax tree size; more nodes mean more complexity." + + def get_score(self, samples, input_instruction_key): + system_prompts = [] + user_prompts = [] + for sample in samples: + instruction = sample.get(input_instruction_key, ['']) + system_prompts.append(self.prompt.build_system_prompt(instruction)) + user_prompts.append(self.prompt.build_prompt()) + + inputs = [system + "\n" + user for system, user in zip(system_prompts, user_prompts)] + responses = self.llm_serving.generate_from_input(user_inputs=inputs) + + scores = [] + for response in responses: + response_lines = response.strip().split("\n") + score_line = response_lines[-1] + score = float(score_line.split()[0]) + scores.append(score) + + return scores + + def eval(self, dataframe: pd.DataFrame, input_instruction_key: str): + self.logger.info(f"Evaluating {self.score_name}...") + samples = dataframe.to_dict(orient='records') + scores = self.get_score(samples, input_instruction_key) + self.logger.info("Evaluation complete!") + return scores + + + def run(self, storage: DataFlowStorage, input_instruction_key: str, output_key: str='TreeinstructScore'): + self.input_instruction_key = input_instruction_key + self.output_key = output_key + dataframe = storage.read("dataframe") + scores = self.eval(dataframe, self.input_instruction_key) + dataframe[self.output_key] = scores + storage.write(dataframe) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/__pycache__/alpagasus_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/__pycache__/alpagasus_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..771c6d9de011ca85ba04eb374ca213396675c694 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/__pycache__/alpagasus_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/__pycache__/deita_complexity_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/__pycache__/deita_complexity_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e98c68bbcfd06c51a755f64a9b45faf24335ac05 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/__pycache__/deita_complexity_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/__pycache__/deita_quality_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/__pycache__/deita_quality_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebee0dcc4613db6009dc2d20fb3166adc7d9d515 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/__pycache__/deita_quality_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/__pycache__/instag_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/__pycache__/instag_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22e6a2ce8e3f0b1769d72907d9062d812178ea07 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/__pycache__/instag_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/__pycache__/rm_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/__pycache__/rm_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca839348ba46a34532d38d98fd50aa5686900a73 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/__pycache__/rm_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/__pycache__/superfiltering_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/__pycache__/superfiltering_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf82c767233527e23098b932e7d7c72ac6260761 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/__pycache__/superfiltering_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/__pycache__/treeinstruct_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/__pycache__/treeinstruct_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e78a4b62fc35f9dd42b9bd2f58e35c7fa458f545 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/__pycache__/treeinstruct_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/alpagasus_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/alpagasus_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..75fb49bb1aa84795607326bfb51ade2a65628623 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/alpagasus_filter.py @@ -0,0 +1,66 @@ +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.core import LLMServingABC +from dataflow.operators.text_sft import AlpagasusSampleEvaluator + +@OPERATOR_REGISTRY.register() +class AlpagasusFilter(OperatorABC): + + def __init__(self, min_score=3, max_score=5, llm_serving: LLMServingABC = None, dimension='quality'): + self.logger = get_logger() + self.min_score = min_score + self.max_score = max_score + self.logger.info(f"Initializing {self.__class__.__name__} with min_score = {self.min_score} and max_score = {self.max_score}...") + self.scorer = AlpagasusSampleEvaluator(llm_serving, dimension) + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于AlpagasusScorer打分器的得分对数据进行过滤。通过调用GPT模型评估指令的质量,返回一个质量得分。\n\n" + "初始化参数:\n" + "- min_score: 最低分数阈值,默认为3\n" + "- max_score: 最高分数阈值,默认为5\n" + "- llm_serving: LLM服务实例\n" + "- dimension: 评估维度,默认为'quality'(质量)\n\n" + "运行参数:\n" + "- input_instruction_key: 输入指令字段名\n" + "- input_input_key: 输入内容字段名\n" + "- input_output_key: 输出内容字段名\n" + "- output_key: 输出分数字段名,默认为'AlpagasusScore'\n\n" + "过滤逻辑:保留分数在[min_score, max_score]范围内的数据" + ) + else: + return ( + "Filter data using scores from the AlpagasusScorer. Evaluate instruction quality using GPT model and return a quality score.\n\n" + "Initialization Parameters:\n" + "- min_score: Minimum score threshold, default is 3\n" + "- max_score: Maximum score threshold, default is 5\n" + "- llm_serving: LLM serving instance\n" + "- dimension: Evaluation dimension, default is 'quality'\n\n" + "Run Parameters:\n" + "- input_instruction_key: Input instruction field name\n" + "- input_input_key: Input content field name\n" + "- input_output_key: Output content field name\n" + "- output_key: Output score field name, default is 'AlpagasusScore'\n\n" + "Filter Logic: Keep data with scores in [min_score, max_score] range" + ) + + + def run(self, storage: DataFlowStorage, input_instruction_key: str, input_input_key: str, input_output_key: str, output_key: str='AlpagasusScore'): + self.input_instruction_key = input_instruction_key + self.input_input_key = input_input_key + self.input_output_key = input_output_key + self.output_key = output_key + self.logger.info(f"Running {self.__class__.__name__} with input_instruction_key = {self.input_instruction_key}, input_input_key = {self.input_input_key}, input_output_key = {self.input_output_key} and output_key = {self.output_key}...") + dataframe = storage.read("dataframe") + scores = self.scorer.eval(dataframe, self.input_instruction_key, self.input_input_key, self.input_output_key) + dataframe[self.output_key] = scores + filtered_dataframe = dataframe[(dataframe[self.output_key] >= self.min_score) & (dataframe[self.output_key] <= self.max_score)] + output_file = storage.write(filtered_dataframe) + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + return [self.output_key] + + \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/deita_complexity_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/deita_complexity_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..529af761e13a9538d098e06cd92468771226345e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/deita_complexity_filter.py @@ -0,0 +1,72 @@ +from dataflow.operators.text_sft import DeitaComplexitySampleEvaluator +from dataflow.core import OperatorABC +import numpy as np +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.utils import get_logger +from dataflow.utils.storage import DataFlowStorage + +@OPERATOR_REGISTRY.register() +class DeitaComplexityFilter(OperatorABC): + def __init__(self, min_score=3.0, max_score=5.0, device='cuda', model_cache_dir='./dataflow_cache', max_length=512): + self.logger = get_logger() + self.min_score = min_score + self.max_score = max_score + self.scorer = DeitaComplexitySampleEvaluator( + device=device, + model_cache_dir=model_cache_dir, + max_length=max_length, + ) + + self.logger.info(f"Initializing {self.__class__.__name__} with min_score = {self.min_score} and max_score = {self.max_score}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于DeitaComplexityScorer打分器的得分对数据进行过滤。使用基于Llama模型的Deita指令复杂性评估器,评估指令的复杂程度。\n\n" + "初始化参数:\n" + "- min_score: 最低分数阈值,默认为3.0\n" + "- max_score: 最高分数阈值,默认为5.0\n" + "- device: 运行设备,默认为'cuda'\n" + "- model_cache_dir: 模型缓存目录,默认为'./dataflow_cache'\n" + "- max_length: 最大序列长度,默认为512\n\n" + "运行参数:\n" + "- input_instruction_key: 输入指令字段名,默认为'instruction'\n" + "- input_output_key: 输入输出字段名,默认为'output'\n" + "- output_key: 输出分数字段名,默认为'DeitaComplexityScore'\n\n" + "评分标准:1-6分,分数越高表示指令复杂性越高\n" + "过滤逻辑:保留分数在[min_score, max_score]范围内的数据" + ) + else: + return ( + "Filter data using scores from the DeitaComplexityScorer. Evaluate instruction complexity using Llama-based Deita model.\n\n" + "Initialization Parameters:\n" + "- min_score: Minimum score threshold, default is 3.0\n" + "- max_score: Maximum score threshold, default is 5.0\n" + "- device: Running device, default is 'cuda'\n" + "- model_cache_dir: Model cache directory, default is './dataflow_cache'\n" + "- max_length: Maximum sequence length, default is 512\n\n" + "Run Parameters:\n" + "- input_instruction_key: Input instruction field name, default is 'instruction'\n" + "- input_output_key: Input output field name, default is 'output'\n" + "- output_key: Output score field name, default is 'DeitaComplexityScore'\n\n" + "Scoring Standard: 1-6 points, higher score indicates higher instruction complexity\n" + "Filter Logic: Keep data with scores in [min_score, max_score] range" + ) + + def run(self, storage: DataFlowStorage, input_instruction_key: str = 'instruction', input_output_key : str = 'output', output_key: str = "DeitaComplexityScore"): + self.input_instruction_key = input_instruction_key + self.input_output_key = input_output_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__}...") + + # Get the quality scores + scores = self.scorer.eval(dataframe, input_instruction_key, input_output_key) + dataframe[self.output_key] = scores + filtered_dataframe = dataframe[(dataframe[self.output_key] >= self.min_score) & (dataframe[self.output_key] <= self.max_score)] + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/deita_quality_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/deita_quality_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..c7d361245649976d9b22987a4931b9c6273ed29b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/deita_quality_filter.py @@ -0,0 +1,69 @@ +from dataflow.operators.text_sft import DeitaQualitySampleEvaluator +from dataflow.core import OperatorABC +import numpy as np +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.utils import get_logger +from dataflow.utils.storage import DataFlowStorage + +@OPERATOR_REGISTRY.register() +class DeitaQualityFilter(OperatorABC): + def __init__(self, min_score=2.5, max_score=10000.0, device='cuda', model_cache_dir='./dataflow_cache', max_length=512): + self.logger = get_logger() + self.min_score = min_score + self.max_score = max_score + self.scorer = DeitaQualitySampleEvaluator( + device=device, + model_cache_dir=model_cache_dir, + max_length=max_length, + ) + + self.logger.info(f"Initializing {self.__class__.__name__} with min_score = {self.min_score} and max_score = {self.max_score}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于DeitaQualityScorer打分器的得分对数据进行过滤。使用基于Llama模型的Deita指令质量评估器,评估指令的质量高低。\n\n" + "初始化参数:\n" + "- min_score: 最低分数阈值,默认为2.5\n" + "- max_score: 最高分数阈值,默认为10000.0\n" + "- device: 运行设备,默认为'cuda'\n" + "- model_cache_dir: 模型缓存目录,默认为'./dataflow_cache'\n" + "- max_length: 最大序列长度,默认为512\n\n" + "运行参数:\n" + "- input_instruction_key: 输入指令字段名,默认为'instruction'\n" + "- input_output_key: 输入输出字段名,默认为'output'\n" + "- output_key: 输出分数字段名,默认为'DeitaQualityScore'\n\n" + "评分标准:1-6分,分数越高表示指令质量越高\n" + "过滤逻辑:保留分数在[min_score, max_score]范围内的数据" + ) + else: + return ( + "Filter data using scores from the DeitaQualityScorer. Evaluate instruction quality using Llama-based Deita model.\n\n" + "Initialization Parameters:\n" + "- min_score: Minimum score threshold, default is 2.5\n" + "- max_score: Maximum score threshold, default is 10000.0\n" + "- device: Running device, default is 'cuda'\n" + "- model_cache_dir: Model cache directory, default is './dataflow_cache'\n" + "- max_length: Maximum sequence length, default is 512\n\n" + "Run Parameters:\n" + "- input_instruction_key: Input instruction field name, default is 'instruction'\n" + "- input_output_key: Input output field name, default is 'output'\n" + "- output_key: Output score field name, default is 'DeitaQualityScore'\n\n" + "Scoring Standard: 1-6 points, higher score indicates higher instruction quality\n" + "Filter Logic: Keep data with scores in [min_score, max_score] range" + ) + + def run(self, storage: DataFlowStorage, input_instruction_key: str = 'instruction', input_output_key : str = 'output', output_key: str = "DeitaQualityScore"): + self.input_instruction_key = input_instruction_key + self.input_output_key = input_output_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__}...") + + scores = self.scorer.eval(dataframe, input_instruction_key, input_output_key) + dataframe[self.output_key] = scores + filtered_dataframe = dataframe[(dataframe[self.output_key] >= self.min_score) & (dataframe[self.output_key] <= self.max_score)] + storage.write(filtered_dataframe) + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + return [self.output_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/instag_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/instag_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..cf4c1052b0d2205c3975d534cf0d558aeab0f0cb --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/instag_filter.py @@ -0,0 +1,44 @@ +from dataflow.operators.text_sft import InstagSampleEvaluator +from dataflow.core import OperatorABC +import numpy as np +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.utils import get_logger +from dataflow.utils.storage import DataFlowStorage + +@OPERATOR_REGISTRY.register() +class InstagFilter(OperatorABC): + + def __init__(self, min_score=0.0, max_score=1.0, model_cache_dir='./dataflow_cache', device='cuda', max_new_tokens=1024): + self.logger = get_logger() + self.min_score = min_score + self.max_score = max_score + + # Initialize the scorer + self.scorer = InstagSampleEvaluator( + model_cache_dir=model_cache_dir, + device=device, + max_new_tokens=max_new_tokens + ) + self.logger.info(f"Initializing {self.__class__.__name__} with min_score = {self.min_score} and max_score = {self.max_score}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return "基于InstagScorer打分器的过滤算子。使用预训练的Instag模型对指令进行分析,返回标签的数量来评估指令的内容多样性。参数包括模型缓存目录(model_cache_dir)、计算设备(device)和最大新生成标记数(max_new_tokens)。过滤范围由min_score和max_score参数控制,标签越多表示内容多样性越大。" + else: + return "Filter operator based on InstagScorer. Uses pre-trained Instag model to analyze instructions, returning the number of tags to evaluate content diversity. Parameters include model cache directory (model_cache_dir), computing device (device), and maximum new tokens (max_new_tokens). Filter range is controlled by min_score and max_score parameters, with more tags indicating greater content diversity." + + def run(self, storage: DataFlowStorage, input_instruction_key: str = 'instruction', output_key: str = 'InstagScore'): + self.input_instruction_key = input_instruction_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__}...") + + scores = self.scorer.eval(dataframe, self.input_instruction_key) + dataframe[self.output_key] = scores + filtered_dataframe = dataframe[(dataframe[self.output_key] >= self.min_score) & (dataframe[self.output_key] <= self.max_score)] + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/rm_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/rm_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..f36bf6b1eb918be43ca8f8375a32b4e9d7c52aeb --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/rm_filter.py @@ -0,0 +1,65 @@ +import numpy as np +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.operators.text_sft import RMSampleEvaluator + +@OPERATOR_REGISTRY.register() +class RMFilter(OperatorABC): + + def __init__(self, min_score: float = 0.2, max_score: float = 0.8, device='cuda', model_cache_dir='./dataflow_cache'): + self.logger = get_logger() + self.min_score = min_score + self.max_score = max_score + self.scorer = RMSampleEvaluator(device=device, model_cache_dir=model_cache_dir) + self.logger.info(f"Initializing {self.__class__.__name__} with min_score = {self.min_score}, max_score = {self.max_score}") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于RMScorer打分器的得分对数据进行过滤。使用基于人类偏好数据训练的奖励模型对文本质量进行评分,高分代表质量较高。\n" + "奖励模型能够评估文本的相关性、有用性、无害性等人类偏好指标,可用于筛选符合人类价值观的高质量文本。\n" + "输入参数:\n" + "- min_score:保留样本的最小奖励分数阈值,默认为0.2\n" + "- max_score:保留样本的最大奖励分数阈值,默认为0.8\n" + "- device:模型运行设备,默认为'cuda'\n" + "- model_cache_dir:模型缓存目录,默认为'./dataflow_cache'\n" + "- input_instruction_key:指令字段名,默认为'instruction'\n" + "- input_output_key:输出字段名,默认为'output'\n" + "输出参数:\n" + "- 过滤后的DataFrame,仅保留奖励分数在[min_score, max_score]范围内的样本\n" + "- 返回包含奖励分数字段名的列表,用于后续算子引用" + ) + elif lang == "en": + return ( + "Filter data using scores from the RMScorer. Quality scoring using reward model trained with human preference data, where higher scores indicate better quality.\n" + "Reward model evaluates human preference metrics such as relevance, helpfulness, and harmlessness, useful for filtering high-quality text aligned with human values.\n" + "Input Parameters:\n" + "- min_score: Minimum reward score threshold for retaining samples, default is 0.2\n" + "- max_score: Maximum reward score threshold for retaining samples, default is 0.8\n" + "- device: Model running device, default is 'cuda'\n" + "- model_cache_dir: Model cache directory, default is './dataflow_cache'\n" + "- input_instruction_key: Instruction field name, default is 'instruction'\n" + "- input_output_key: Output field name, default is 'output'\n" + "Output Parameters:\n" + "- Filtered DataFrame containing only samples with reward scores within [min_score, max_score] range\n" + "- List containing reward score field name for subsequent operator reference" + ) + else: + return "Filter data based on quality scores from human preference-trained reward model." + + def run(self, storage: DataFlowStorage, input_instruction_key: str = 'instruction', input_output_key: str = 'output', output_key: str = 'RMScore'): + self.input_instruction_key = input_instruction_key + self.input_output_key = input_output_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_instruction_key = {self.input_instruction_key}, intput_output_key = {self.input_output_key}, output_key = {self.output_key}...") + scores = np.array(self.scorer.eval(dataframe, self.input_instruction_key, self.input_output_key)) + dataframe[self.output_key] = scores + filtered_dataframe = dataframe[(scores >= self.min_score) & (scores <= self.max_score)] + storage.write(filtered_dataframe) + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/superfiltering_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/superfiltering_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..26dcb74187f1e577c789b103dbb7130690fafbc7 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/superfiltering_filter.py @@ -0,0 +1,80 @@ +from dataflow.operators.text_sft import SuperfilteringSampleEvaluator +import numpy as np +from dataflow.core import OperatorABC +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.utils.utils import get_logger +from dataflow.utils.storage import DataFlowStorage + +@OPERATOR_REGISTRY.register() +class SuperfilteringFilter(OperatorABC): + + def __init__(self, min_score=0.0, max_score=1.0, device='cuda', model_cache_dir='./dataflow_cache', max_length=512): + self.logger = get_logger() + self.min_score = min_score + self.max_score = max_score + + self.scorer = SuperfilteringSampleEvaluator( + device=device, + model_cache_dir=model_cache_dir, + max_length=max_length + ) + self.logger.info(f"Initializing {self.__class__.__name__} with min_score = {self.min_score} and max_score = {self.max_score}...") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "使用Superfiltering评分器过滤掉低质量数据。基于GPT-2模型计算困惑度比值来评估指令跟随难度,比值越低表示指令越容易被模型理解和执行。\n" + "适用于筛选适合特定模型能力的指令数据,提高模型训练效率和效果。\n" + "输入参数:\n" + "- min_score:保留样本的最小分数阈值,默认为0.0\n" + "- max_score:保留样本的最大分数阈值,默认为1.0\n" + "- device:模型运行设备,默认为'cuda'\n" + "- model_cache_dir:模型缓存目录,默认为'./dataflow_cache'\n" + "- max_length:文本最大长度,默认为512\n" + "- input_instruction_key:指令字段名,默认为'instruction'\n" + "- input_input_key:输入字段名,默认为'input'\n" + "- input_output_key:输出字段名,默认为'output'\n" + "- output_key:过滤结果分数字段名,默认为'SuperfilteringScore'\n" + "输出参数:\n" + "- 过滤后的DataFrame,仅保留分数在[min_score, max_score]范围内的样本\n" + "- 返回包含过滤结果分数字段名的列表,用于后续算子引用" + ) + elif lang == "en": + return ( + "Filter out low-quality data using the Superfiltering scorer. Evaluate instruction following difficulty by calculating perplexity ratio with GPT-2 model; lower ratios indicate instructions are easier for models to understand and execute.\n" + "Suitable for selecting instruction data appropriate for specific model capabilities, improving model training efficiency and effectiveness.\n" + "Input Parameters:\n" + "- min_score: Minimum score threshold for retaining samples, default is 0.0\n" + "- max_score: Maximum score threshold for retaining samples, default is 1.0\n" + "- device: Model running device, default is 'cuda'\n" + "- model_cache_dir: Model cache directory, default is './dataflow_cache'\n" + "- max_length: Maximum text length, default is 512\n" + "- input_instruction_key: Instruction field name, default is 'instruction'\n" + "- input_input_key: Input field name, default is 'input'\n" + "- input_output_key: Output field name, default is 'output'\n" + "- output_key: Filter result score field name, default is 'SuperfilteringScore'\n" + "Output Parameters:\n" + "- Filtered DataFrame containing only samples with scores within [min_score, max_score] range\n" + "- List containing filter result score field name for subsequent operator reference" + ) + else: + return "Filter low-quality data using perplexity ratio calculated with GPT-2 model." + + def run(self, storage: DataFlowStorage, input_instruction_key: str = 'instruction', input_input_key: str = 'input', input_output_key: str = 'output', output_key: str = "SuperfilteringScore"): + self.input_instruction_key = input_instruction_key + self.input_input_key = input_input_key + self.input_output_key = input_output_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__ } with input_instruction_key = {self.input_instruction_key}, intput_output_key = {self.input_output_key}, output_key = {self.output_key}...") + + # Get the scores for filtering + scores = self.scorer.eval(dataframe, input_instruction_key, input_input_key, input_output_key) + dataframe[self.output_key] = scores + filtered_dataframe = dataframe[(dataframe[self.output_key] >= self.min_score) & (dataframe[self.output_key] <= self.max_score)] + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/treeinstruct_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/treeinstruct_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..ee40cb8aae3e30c457c5cbf324ee4f3c83c0c500 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/filter/treeinstruct_filter.py @@ -0,0 +1,68 @@ +import numpy as np +from dataflow import get_logger +from dataflow.core import OperatorABC, LLMServingABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.operators.text_sft import TreeinstructSampleEvaluator + +@OPERATOR_REGISTRY.register() +class TreeinstructFilter(OperatorABC): + + def __init__(self, min_score: int = 7, max_score: int = 100, llm_serving: LLMServingABC = None): + self.logger = get_logger() + self.min_score = min_score + self.max_score = max_score + self.scorer = TreeinstructSampleEvaluator(llm_serving=llm_serving) + self.logger.info(f"Initializing {self.__class__.__name__} with min_score = {min_score} and max_score = {max_score}") + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于TreeinstructScore打分器的得分对数据进行过滤。通过生成语法树的节点数来衡量指令复杂性,节点越多表示指令越复杂。\n" + "适用于筛选特定复杂度范围内的指令数据,平衡数据集难度分布,优化模型训练效果。\n" + "输入参数:\n" + "- min_score:保留样本的最小语法树节点数阈值,默认为7\n" + "- max_score:保留样本的最大语法树节点数阈值,默认为100\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口\n" + "- input_key:输入指令字段名\n" + "- output_key:语法树节点数字段名,默认为'TreeinstructScore'\n" + "输出参数:\n" + "- 过滤后的DataFrame,仅保留语法树节点数在[min_score, max_score]范围内的样本\n" + "- 返回包含语法树节点数字段名的列表,用于后续算子引用" + ) + elif lang == "en": + return ( + "Filter data using scores from the TreeinstructScore. Measure instruction complexity by the number of nodes in the generated syntax tree; more nodes indicate more complex instructions.\n" + "Suitable for selecting instruction data within specific complexity ranges, balancing dataset difficulty distribution and optimizing model training effectiveness.\n" + "Input Parameters:\n" + "- min_score: Minimum syntax tree node count threshold for retaining samples, default is 7\n" + "- max_score: Maximum syntax tree node count threshold for retaining samples, default is 100\n" + "- llm_serving: LLM serving object implementing LLMServingABC interface\n" + "- input_key: Input instruction field name\n" + "- output_key: Syntax tree node count field name, default is 'TreeinstructScore'\n" + "Output Parameters:\n" + "- Filtered DataFrame containing only samples with syntax tree node count within [min_score, max_score] range\n" + "- List containing syntax tree node count field name for subsequent operator reference" + ) + else: + return "Filter data based on instruction complexity measured by syntax tree node count." + + def run(self, storage: DataFlowStorage, input_key: str, output_key: str = 'TreeinstructScore'): + self.input_key = input_key + self.output_key = output_key + dataframe = storage.read("dataframe") + self.logger.info(f"Running {self.__class__.__name__} with input_key = {self.input_key} and output_key = {self.output_key}...") + + # Get the scores for filtering + scores = np.array(self.scorer.eval(dataframe, self.input_key)) + + dataframe[self.output_key] = scores + filtered_dataframe = dataframe[(scores >= self.min_score) & (scores <= self.max_score)] + + # Write the filtered dataframe back to storage + storage.write(filtered_dataframe) + + self.logger.info(f"Filtering completed. Total records passing filter: {len(filtered_dataframe)}.") + + return [self.output_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/generate/__pycache__/condor_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/generate/__pycache__/condor_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e74a2e2148e8034471e80ed104d9f15a2aa67cc6 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/generate/__pycache__/condor_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/generate/__pycache__/sft_generator_from_seed.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/generate/__pycache__/sft_generator_from_seed.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd7e3fd85057ed7461b1074ea138bc7756007b14 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/generate/__pycache__/sft_generator_from_seed.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/generate/condor_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/generate/condor_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..672315c4340b676ca6da0fc5d3cea7f88b4ec854 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/generate/condor_generator.py @@ -0,0 +1,165 @@ +import json +import random +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +import pandas as pd +from dataflow.core import LLMServingABC +from dataflow.prompts.general_text import CondorQuestionPrompt +from dataflow.core.prompt import DIYPromptABC, prompt_restrict +from typing import Union + +@prompt_restrict( + CondorQuestionPrompt +) + +@OPERATOR_REGISTRY.register() +class CondorGenerator(OperatorABC): + def __init__(self, llm_serving: LLMServingABC = None, num_samples=15, use_task_diversity=True, prompt_template: Union[CondorQuestionPrompt, DIYPromptABC] = None): + # Based on the existing topics, it is recommended to set num_samples below 5000. Otherwise, it is recommended to add topics in dataflow.prompts.general_text.CondorPrompt on your own to increase data richness + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.llm_serving = llm_serving + self.num_questions = num_samples // 3 # 每个prompt生成3个难度的问题 + self.prompt = prompt_template + self.use_task_diversity = use_task_diversity # 是否使用任务场景增强多样性 + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于预置知识树标签,两阶段从0合成SFT格式数据(合成数量大于5000时建议增加标签数量)。第一阶段生成不同难度级别的问题,第二阶段为每个问题生成对应的答案。" + "输入参数:\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口\n" + "- num_samples:生成样本总数,建议小于5000,默认值为15\n" + "- prompt_template:提示词模板对象,用于定义提示结构\n" + "输出参数:\n" + "- 包含'difficulty'、'instruction'和'output'字段的DataFrame\n" + "- 返回生成的DataFrame用于后续处理" + ) + elif lang == "en": + return ( + "Two-stage generation of SFT-style data from scratch based on predefined knowledge tree tags (for over 5000 samples, consider increasing the number of tags). \n" + "First stage generates questions of varying difficulty levels, second stage generates answers for each question.\n" + "Input Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC interface\n" + "- num_samples: Total number of samples to generate, recommended to be less than 5000, default is 15\n\n" + "- prompt_template: Prompt template object, for defining the prompt structure\n" + "Output Parameters:\n" + "- DataFrame containing 'difficulty', 'instruction', and 'output' fields\n" + "- Returns generated DataFrame for subsequent processing" + ) + else: + return ( + "CondorGenerator generates SFT-style data through two-stage LLM generation based on predefined knowledge tree tags." + ) + + + def parse_generated_responses(self, questions_responses): + questions_data = [] + for response in questions_responses: + try: + if not isinstance(response, str): + raise ValueError("Invalid response type") + + # 解析问题字符串,提取不同难度级别的问题 + question_data = {} + lines = response.split('\n') + + for line in lines: + if line.startswith("[Easy]"): + question_data["Easy"] = line.replace("[Easy][Question Start]", "").replace("[Question End]", "").strip() + elif line.startswith("[Medium]"): + question_data["Medium"] = line.replace("[Medium][Question Start]", "").replace("[Question End]", "").strip() + elif line.startswith("[Hard]"): + question_data["Hard"] = line.replace("[Hard][Question Start]", "").replace("[Question End]", "").strip() + + if question_data: + questions_data.append(question_data) + except Exception as e: + self.logger.debug(f'Error while parsing the response: {str(e)}') + continue + + return questions_data + + def run(self, storage: DataFlowStorage, output_instruction_key: str = "instruction", output_output_key: str = "output", output_difficulty_key: str = "difficulty"): + # 生成所有的prompt + prompts = [] + prompt_metadata = [] # 记录每个prompt的元信息(用于后续追踪) + + for _ in range(self.num_questions): + # 每次随机选择topic, domain, theme + topic = random.choice(list(self.prompt.tag.keys())) + domain = random.choice(list(self.prompt.tag[topic].keys())) + theme = random.choice(self.prompt.tag[topic][domain]) + + # 如果启用任务场景多样性,随机选择一个任务类型 + task_type = None + if self.use_task_diversity: + task_type = random.choice(self.prompt.task_types) + + # 获取生成问题的prompt(保留原有的3难度生成逻辑) + prompt = self.prompt.build_prompt(theme, domain) + + # 如果使用任务场景,在prompt中添加场景说明 + if task_type: + prompt = f"""Task Scenario: {task_type} + +{prompt} + +Remember to frame the questions within the context of "{task_type}" scenario.""" + + prompts.append(prompt) + prompt_metadata.append({ + 'topic': topic, + 'domain': domain, + 'theme': theme, + 'task_type': task_type + }) + + + # 调用LLM一次性生成问题 + self.logger.info("Generating questions...") + questions_responses = self.llm_serving.generate_from_input(user_inputs=prompts) + + # 解析问题 + self.logger.info("Parsing questions...") + questions_data = self.parse_generated_responses(questions_responses) + # 生成答案的prompt + answer_prompts = [] + for question in questions_data: + for difficulty_level in ["Easy", "Medium", "Hard"]: + question_text = question.get(difficulty_level) + if question_text: + # 构造问题对应的answer prompt + answer_prompt = f"Please answer this questiong truthfully. Question: {question_text}" + answer_prompts.append(answer_prompt) + + # 调用LLM一次性生成所有答案 + self.logger.info("Generating answers...") + answer_responses = self.llm_serving.generate_from_input(user_inputs=answer_prompts) + + # 解析答案 + answers_data = [] + answer_idx = 0 # 用来追踪答案响应的索引 + for question in questions_data: + for difficulty_level in ["Easy", "Medium", "Hard"]: + question_text = question.get(difficulty_level) + if question_text: + # 获取对应的答案 + answer_text = answer_responses[answer_idx].strip() # 获取答案 + answers_data.append({ + output_difficulty_key: difficulty_level, + output_instruction_key: question_text, + output_output_key: answer_text + }) + answer_idx += 1 # 更新索引 + + # Step 4: Write to storage (e.g., save to DataFrame) + df = pd.DataFrame(answers_data) + storage.write(df) + self.logger.info(f'SFT data generated') + + return [output_instruction_key, output_output_key, output_difficulty_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/generate/sft_generator_from_seed.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/generate/sft_generator_from_seed.py new file mode 100644 index 0000000000000000000000000000000000000000..f68a672a155cb8f7a21a4dd4fbcf4b3158628d67 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/generate/sft_generator_from_seed.py @@ -0,0 +1,109 @@ +from dataflow.prompts.general_text import SFTGeneratorSeedPrompt +import re +import json +import pandas as pd +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger + +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +from dataflow.serving import LocalModelLLMServing_vllm +from dataflow.core.prompt import prompt_restrict + +@prompt_restrict( + SFTGeneratorSeedPrompt +) + +def extract_json_object(model_output): + """提取第一个包含 instruction 和 output 字段的 JSON 对象""" + json_pattern = r'\{[^}]*\}' + matches = re.findall(json_pattern, model_output) + for match in matches: + try: + obj = json.loads(match) + if 'instruction' in obj and 'output' in obj: + return obj + except json.JSONDecodeError: + continue + return None + +@OPERATOR_REGISTRY.register() +class SFTGeneratorSeed(OperatorABC): + def __init__(self, llm_serving: LLMServingABC, custom_prompt: str): + self.logger = get_logger() + self.prompts = SFTGeneratorSeedPrompt(custom_prompt=custom_prompt) + self.llm_serving = llm_serving + self.max_tokens = 4096 + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于给定文档内容,生成监督微调格式的问答数据。并支持用户自定义生成内容要求。从原始文档中提取信息,生成符合SFT格式的指令-响应对。" + "输入参数:\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口\n" + "- custom_prompt:用户自定义提示词\n" + "- input_key:输入文档内容字段名,默认为'raw_content'\n" + "- max_tokens:生成文本的最大token数,默认为4096\n" + "输出参数:\n" + "- 包含'instruction'、'output'和'raw_content'字段的DataFrame\n" + "- 返回包含'instruction'和'output'字段名的列表,用于后续算子引用" + ) + elif lang == "en": + return ( + "Generate supervised fine-tuning format Q&A data based on the given document content and support user-defined content generation requirements. \n" + "Extracts information from raw documents to generate instruction-response pairs in SFT format.\n" + "Input Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC interface\n" + "- custom_prompt: User-defined custom prompt\n" + "- input_key: Field name for input document content, default is 'raw_content'\n" + "- max_tokens: Maximum number of tokens for generated text, default is 4096\n\n" + "Output Parameters:\n" + "- DataFrame containing 'instruction', 'output', and 'raw_content' fields\n" + "- List containing 'instruction' and 'output' field names for subsequent operator reference" + ) + else: + return ( + "SFTGeneratorSeed generates SFT format Q&A data from document content with custom prompt support." + ) + + def run(self, storage: DataFlowStorage, input_key: str = "raw_content"): + self.input_key = input_key + self.logger.info("Running SFTGenerator...") + + # Load the raw dataframe from the input file + dataframe = storage.read('dataframe') + self.logger.info(f"Loading, number of rows: {len(dataframe)}") + + # Create a list to hold all generated questions and answers + llm_inputs = [] + + # Prepare LLM inputs by formatting the prompt with raw content from the dataframe + for index, row in dataframe.iterrows(): + raw_content = row.get(self.input_key, '') + llm_input = self.prompts.build_prompt(content=raw_content) + llm_inputs.append(llm_input) + + # Generate the text using the model + try: + self.logger.info("Generating text using the model...") + outputs = self.llm_serving.generate_from_input(llm_inputs) + self.logger.info("Text generation completed.") + except Exception as e: + self.logger.error(f"Error during text generation: {e}") + return + + valid_records = [] + for idx, output in enumerate(outputs): + result = extract_json_object(output) + if result: + result["raw_content"] = dataframe[self.input_key].iloc[idx] # 添加原文内容 + valid_records.append(result) + + # Add the generated content back to the dataframe + output_df = pd.DataFrame(valid_records) + + # Save the updated dataframe to the output file + output_file = storage.write(output_df) + return ['instruction', 'output'] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/refine/__pycache__/condor_refiner.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/refine/__pycache__/condor_refiner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..917a9877473ecd382cd0aab0233f546468652103 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/refine/__pycache__/condor_refiner.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/refine/condor_refiner.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/refine/condor_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..e848513c364434ce40c26b49ca7d16bf535e8a25 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/operators/text_sft/refine/condor_refiner.py @@ -0,0 +1,87 @@ +import json +import random +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger +from dataflow.core import OperatorABC +from dataflow.utils.storage import DataFlowStorage +import pandas as pd +from dataflow.core import LLMServingABC +from dataflow.prompts.general_text import CondorRefinePrompt +from dataflow.core.prompt import prompt_restrict, DIYPromptABC +from typing import Union + +@prompt_restrict( + CondorRefinePrompt +) + +@OPERATOR_REGISTRY.register() +class CondorRefiner(OperatorABC): + def __init__(self, llm_serving: LLMServingABC = None, prompt_template: Union[CondorRefinePrompt, DIYPromptABC] = None): + self.logger = get_logger() + self.logger.info(f'Initializing {self.__class__.__name__}...') + self.llm_serving = llm_serving + self.prompt_template = prompt_template + self.logger.info(f'{self.__class__.__name__} initialized.') + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "两阶段优化指令回复质量:第一阶段调用API生成对回复的评论,第二阶段利用评论调用API改写回复,提升指令对质量。通过迭代优化提高问答对的整体质量。" + "输入参数:\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口\n" + "- input_instruction_key:输入指令字段名,默认为'instruction'\n" + "- input_output_key:输入回复字段名,默认为'output'\n" + "- prompt_template:提示词模板对象,用于定义提示结构\n" + "输出参数:\n" + "- 包含优化后回复的DataFrame\n" + "- 返回包含优化后回复字段名的列表,用于后续算子引用" + ) + elif lang == "en": + return ( + "Two-stage optimization of instruction-response quality: First stage calls API to generate critique on responses, \n" + "second stage uses critique to call API to refine responses, improving the quality of QA pairs through iterative optimization.\n" + "Input Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC interface\n" + "- input_instruction_key: Field name for input instructions, default is 'instruction'\n" + "- input_output_key: Field name for input responses, default is 'output'\n" + "- prompt_template: Prompt template object, for defining the prompt structure\n" + "Output Parameters:\n" + "- DataFrame containing refined responses\n" + "- List containing refined response field name for subsequent operator reference" + ) + else: + return ( + "CondorRefiner improves QA pair quality through two-stage critique and refinement process." + ) + + def generate_critique(self, question, answer): + # 批量生成 Critique + critique_prompts = [self.prompt_template.build_prompt(mode="critique", question=q, answer=a) for q, a in zip(question, answer)] + critique_responses = self.llm_serving.generate_from_input(critique_prompts) + return critique_responses + + def generate_refined_answer(self, question, answer, critique): + # 批量生成修改后的答案 + refine_prompts = [self.prompt_template.build_prompt(mode="refine", question=q, answer=a, critique=c) for q, a, c in zip(question, answer, critique)] + refined_answers = self.llm_serving.generate_from_input(refine_prompts) + refined_answers = [answer.replace('[Improved Answer Start]', '').replace('[Improved Answer End]', '').strip() for answer in refined_answers] + return refined_answers + + def run(self, storage: DataFlowStorage, input_instruction_key: str='instruction', input_output_key: str='output'): + df = storage.read('dataframe') + # 从 storage 获取批量问题和答案 + questions = df.get(input_instruction_key).to_list() + answers = df.get(input_output_key).to_list() + # 生成 Critique + critique_responses = self.generate_critique(questions, answers) + self.logger.info(f'Generated Critiques for the answers.') + + # 生成修改后的答案 + refined_answers = self.generate_refined_answer(questions, answers, critique_responses) + self.logger.info(f'Refined Answers generated.') + df[input_output_key] = refined_answers + output_file = storage.write(df) + self.logger.info(f'Refined answers updated in storage.') + + return [input_output_key] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/pipeline/Pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/pipeline/Pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..9748c4c83a235953a34fb0916f05456e6b673062 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/pipeline/Pipeline.py @@ -0,0 +1,697 @@ +import os +import copy +import socket +import webbrowser +from http.server import HTTPServer, SimpleHTTPRequestHandler +from abc import ABC, abstractmethod +from collections import Counter, defaultdict +from dataflow.core.operator import OperatorABC +from dataflow.pipeline.nodes import OperatorNode, KeyNode +from dataflow.wrapper.auto_op import AutoOP, OPRuntime +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OPERATOR_CLASSES, LLM_SERVING_CLASSES +import atexit +from datetime import datetime +from dataflow.logger import get_logger +import colorsys +from tqdm import tqdm +class PipelineABC(ABC): + def __init__(self): + # list of dict, contains `OPRuntime` class and parameters for `operator.run()` + self.op_runtimes:list[OPRuntime] = [] + self.compiled = False + # accumulated keys in each operators, index 0 refers to the keys before the first operator + self.accumulated_keys = [] # list of lists, each sublist contains keys before the operator + + # other items + self.logger = get_logger() + self.active_llm_serving = None + # self.serving_resources = defaultdict(dict) + # self.serving_reference_counter = Counter() + + self.op_nodes_list : list[OperatorNode] = [] + self.llm_serving_list = [] # list of LLMServing objects + self.llm_serving_counter = Counter() # count of LLMServing objects + + @abstractmethod + def forward(self): + """ + Main Function to run the pipeline + """ + pass + + def compile(self): + self.compiled = True # flag the pipeline as compiled + for k, v in vars(self).items(): + if isinstance(v, OperatorABC): + setattr(self, k, AutoOP(v, k, self)) + self.forward() + # after call forward, call back function in AutoOP will add the OPRuntime object to self.op_runtimes + + self.forward = self._compiled_forward + self.logger.info( + f"Compiling pipeline and validating key integrity " + f"across {len(self.op_runtimes)} operator runtimes." + ) + self._build_operator_nodes_graph() + # self._draw_graph_for_operators() + # self._build_serving_resources_map() + + def _build_operator_nodes_graph(self): + """ + Build a graph of operator nodes, each node contains the operator object and its storage. + """ + for op_runtime in self.op_runtimes: + llm_serving_obj, storage_obj = None, None + # get llm_serving object from the operator + for _, v in vars(op_runtime.op).items(): + if isinstance(v, LLM_SERVING_CLASSES): + llm_serving_obj = v + # get storage object from the function dict + storage_obj = op_runtime.kwargs.pop("storage", None) + + assert isinstance(storage_obj, DataFlowStorage), f"Storage must be a DataFlowStorage object, but got {type(storage_obj)} in {op_runtime}'s `run` function with key `storage`." + + # create an operator node + op_node = OperatorNode( + op_obj=op_runtime.op, + op_name=op_runtime.op_name, + storage=storage_obj, + llm_serving=llm_serving_obj, + **op_runtime.kwargs + ) + + # append to lists, if None, just keep it + self.op_nodes_list.append(op_node) + self.llm_serving_list.append(llm_serving_obj) + if llm_serving_obj is not None: + self.llm_serving_counter[llm_serving_obj] += 1 + self.logger.debug(f"Built operator nodes graph with {self.op_nodes_list} nodes, \nand {self.llm_serving_list} LLM Serving objects.") + + # get keys in the first storage: + first_op = self.op_nodes_list[0] if self.op_nodes_list else None + if first_op and first_op.storage: + iter_storage_keys = first_op.storage.get_keys_from_dataframe() + else: + iter_storage_keys = [] + + # print("start keys", iter_storage_keys) + + # all keys in the first storage will be the initial keys for validation + self.accumulated_keys.append(copy.deepcopy(iter_storage_keys)) + + error_msg = [] + # build graph of all operators and keys from all states + for op_node in self.op_nodes_list: + # check if accumulated_keys have the input keys of this operator + # print(op_node, op_node.input_keys, op_node.output_keys) + for input_key in op_node.input_keys: + if input_key not in self.accumulated_keys[-1]: + error_msg.append( + { + "input_key": input_key, + "op_name": op_node.op_name, + "class_name": op_node.op_obj.__class__.__name__, + "key_para_name": op_node.input_key_nodes[input_key].key_para_name + } + ) + + # add output keys to accumulated keys + for output_key in op_node.output_keys: + if output_key not in iter_storage_keys: + iter_storage_keys.append(output_key) + self.accumulated_keys.append(copy.deepcopy(iter_storage_keys)) + if len(error_msg) != 0: + # final_error_str = "KeyError in following Operators during pipeline.compile():" + details = "\n".join( + f"- Input key '{e['input_key']}' in `{e['op_name']}` " + f"(class <{e['class_name']}>) does not match any output keys " + f"from previous operators or dataset keys. " + f"Check parameter '{e['key_para_name']}' in the `{e['op_name']}.run()`." + for e in error_msg + ) + msg = f"Key Matching Error in following Operators during pipeline.compile():\n{details}" + self.logger.warning(msg) + raise KeyError(msg) + + self.final_keys = copy.deepcopy(iter_storage_keys) + + + for i, keys in enumerate(self.accumulated_keys): + # print(i, keys) + pass + self.logger.debug(f"Accumulated keys after building graph: {self.accumulated_keys}") + + self.input_dataset_node = OperatorNode( + None, + "DATASET-INPUT", + None, + None, + + ) + self.input_dataset_node.init_output_keys_nodes(self.accumulated_keys[0]) + self.op_nodes_list.insert(0, self.input_dataset_node) + + self.output_dataset_node = OperatorNode( + None, + "DATASET-OUTPUT", + None, + None, + ) + self.output_dataset_node.init_input_keys_nodes(self.final_keys) + self.op_nodes_list.append(self.output_dataset_node) + + # set a default dict for all keys + self.last_modified_index_of_keys: dict[list] = {} + for key in self.final_keys: + self.last_modified_index_of_keys[key] = [] + # print(self.last_modified_index_of_keys) + + # now the first op node is THEDATASET op + for idx, i_op in enumerate(self.op_nodes_list): + # check for input keys + for input_key in i_op.input_keys: + current_keynode:KeyNode = i_op.input_key_nodes[input_key] + current_keynode.set_index(idx) + + if len(self.last_modified_index_of_keys[input_key]) > 0: + last_modified_idx = self.last_modified_index_of_keys[input_key][-1] + last_modified_keynode:KeyNode = self.op_nodes_list[last_modified_idx].output_keys_nodes[input_key] + # double side ptr for each nodes + last_modified_keynode.ptr.append(current_keynode) + current_keynode.ptr.append(last_modified_keynode) + # check for output keys + for output_key in i_op.output_keys: + current_keynode:KeyNode = i_op.output_keys_nodes[output_key] + current_keynode.set_index(idx) + self.last_modified_index_of_keys[output_key].append(idx) + + for key, value in self.last_modified_index_of_keys.items(): + # print(key, value) + pass + + for op in self.op_nodes_list: + # print(op) + self.logger.debug(f"Operator Node: {op}") + pass + + # deprecated, use `draw_graph` instead, archived for compatibility + def _draw_graph_for_operators(self): + raise DeprecationWarning( + "The `_draw_graph_for_operators` method is deprecated. " + "Please use `draw_graph` method instead for better visualization.") + + def _get_op_node_str(self, node:OperatorNode): + input_keys_string = "" + for i_key_node in node.input_key_nodes.values(): + input_keys_string += f"\n{i_key_node.key_para_name}={i_key_node.key}" + output_keys_string = "" + for o_key_node in node.output_keys_nodes.values(): + output_keys_string += f"\n{o_key_node.key_para_name}={o_key_node.key}" + # return f"{node.op_name}\n{node.op_obj.__class__.__name__}\n{node.llm_serving.__class__.__name__ if node.llm_serving else 'None'}\n{input_keys_string}\n --- \n{output_keys_string}" + return f"{node.op_name}\n{node.op_obj.__class__.__name__}\n" + + try: + import networkx + except Exception: + raise ImportError("Please install networkx to draw graph. Please run `pip install networkx[default]`.") + import matplotlib.pyplot as plt + G = networkx.DiGraph() + # add OP nodes + for op_node in self.op_nodes_list: + G.add_node(op_node, label=_get_op_node_str(self, op_node)) + # add edges between OP nodes + for op_node in self.op_nodes_list: + for output_key_nodes in op_node.output_keys_nodes.values(): + for ptr_key_node in output_key_nodes.ptr: + G.add_edge(op_node, self.op_nodes_list[ptr_key_node.index], label=ptr_key_node.key) + + # draw the figure + pos = networkx.spring_layout(G) + # pos = networkx.drawing.nx_agraph.graphviz_layout(G, prog='dot') + # pos = networkx.kamada_kawai_layout(G) + + + # pos = networkx.spectral_layout(G) + # 设置画布大小 + num_nodes = len(G.nodes) + plt.figure(figsize=(max(10, num_nodes * 0.5), max(8, num_nodes * 0.5))) + + # 绘制图形,使用自定义标签 + labels = {node: data['label'] for node, data in G.nodes(data=True)} + networkx.draw(G, pos, labels=labels, with_labels=True, node_size=1000, node_shape='s', node_color='lightblue', edge_color='gray', arrows=True) + + # 绘制边的标签 + edge_labels = networkx.get_edge_attributes(G, 'label') + networkx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels) + + # 保存图形 + plt.savefig("operators_graph.png", bbox_inches='tight') + plt.show() + + def draw_graph( + self, + port=0, + hide_no_changed_keys=True + ): + # compile check + if not self.compiled: + self.logger.error("Pipeline is not compiled yet. Please call `compile()` before drawing the graph.") + raise RuntimeError("Pipeline is not compiled yet. Please call `compile()` before drawing the graph.") + # import check if pyvis is installed + try: + from pyvis.network import Network + except ImportError: + raise ImportError("Please install pyvis to draw graph of current pipeline. Please run `pip install pyvis`.") + + + def _get_op_node_str(node, step = None): + op_class_name = node.op_obj.__class__.__name__ if node.op_obj.__class__.__name__ !="NoneType" else "Storage/No-Op" + if step is not None: + return f"{node.op_name}\n<{op_class_name}>\n(step={step})\n" + else: + return f"{node.op_name}\n<{op_class_name}>\n" + + def _get_op_node_title(node): + input_keys_string = "" + op_class_name = node.op_obj.__class__.__name__ if node.op_obj.__class__.__name__ !="NoneType" else "Storage/No-Op" + if op_class_name == "Storage/No-Op": + for i_key_node in node.input_key_nodes.values(): + input_keys_string += f" {i_key_node.key}\n" + output_keys_string = "" + for o_key_node in node.output_keys_nodes.values(): + output_keys_string += f" {o_key_node.key}\n" + else: + for i_key_node in node.input_key_nodes.values(): + input_keys_string += f" {i_key_node.key_para_name}={i_key_node.key}\n" + output_keys_string = "" + for o_key_node in node.output_keys_nodes.values(): + output_keys_string += f" {o_key_node.key_para_name}={o_key_node.key}\n" + + if input_keys_string == "": + input_keys_string = " None\n" + if output_keys_string == "": + output_keys_string = " None\n" + return ( + f"Attrbute: {node.op_name}\n" + f"Class: {op_class_name}\n" + f"------\n" + f"Input:\n {input_keys_string}" + f"------\n" + f"Output:\n {output_keys_string}" + ) + + def _hex_to_rgb(hex_color): + hex_color = hex_color.lstrip("#") + return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4)) + + def _rgb_to_hex(rgb): + return "#{:02x}{:02x}{:02x}".format(*rgb) + + def _lerp_color(c1, c2, t): + return tuple(int(c1[i] + (c2[i] - c1[i]) * t) for i in range(3)) + + def _step_to_color(step, total_steps): + """ + 冷淡风渐变: 灰蓝 → 灰紫 → 冷蓝 + """ + # start = _hex_to_rgb("#bfdefc") # 浅钢蓝 + # mid = _hex_to_rgb("#aaa1d3") # 灰紫 + # end = _hex_to_rgb("#888794") # 冷蓝灰 + # start = _hex_to_rgb("#FCF1D0") # 浅钢蓝 + # mid = _hex_to_rgb("#DBFFDD") # 灰紫 + # end = _hex_to_rgb("#C8E0F9") # 冷蓝灰 + start = _hex_to_rgb("#D5B4EC") # 浅钢蓝 + mid = _hex_to_rgb("#879DF8") # 灰紫 + end = _hex_to_rgb("#81CDF9") # 冷蓝灰 + + if total_steps <= 1: + return _rgb_to_hex(start) + + mid_point = (total_steps - 1) / 2 + if step <= mid_point: + t = step / mid_point + rgb = _lerp_color(start, mid, t) + else: + t = (step - mid_point) / mid_point + rgb = _lerp_color(mid, end, t) + + return _rgb_to_hex(rgb) + + # def _step_to_color(step, total_steps): + # # 红色 (255, 0, 0) → 蓝色 (0, 0, 255) + # r_start, g_start, b_start = (255, 0, 0) + # r_end, g_end, b_end = (0, 0, 255) + # t = step / max(total_steps - 1, 1) # 归一化到 [0, 1] + # r = int(r_start + (r_end - r_start) * t) + # g = int(g_start + (g_end - g_start) * t) + # b = int(b_start + (b_end - b_start) * t) + # return f"#{r:02x}{g:02x}{b:02x}" + + # def _step_to_color(step, total_steps): + # """ + # 从红 → 紫 → 蓝的平滑渐变 + # """ + # if total_steps <= 1: + # return "#ff0000" # 只有一个节点时直接红色 + + # mid_point = (total_steps - 1) / 2 + # if step <= mid_point: + # # 红(0°) → 紫(300°) + # h_start, h_end = 0 / 360, 300 / 360 + # t = step / mid_point + # else: + # # 紫(300°) → 蓝(240°) + # h_start, h_end = 300 / 360, 240 / 360 + # t = (step - mid_point) / mid_point + + # # 饱和度和亮度固定高值 + # s, l = 1.0, 0.5 + # h = h_start + (h_end - h_start) * t + # r, g, b = colorsys.hls_to_rgb(h, l, s) + + # return f"#{int(r*255):02x}{int(g*255):02x}{int(b*255):02x}" + + # 生成 PyVis 图 + net = Network(height="800px", width="100%", directed=True) + net.force_atlas_2based() + net.toggle_physics(True) + net.set_options(""" + { + "physics": { + "forceAtlas2Based": { + "springLength": 300, + "springConstant": 0.01 + }, + "minVelocity": 0.75, + "solver": "forceAtlas2Based" + } + } + """) + + + for idx, op_node in enumerate(self.op_nodes_list): + node_color = _step_to_color(idx, len(self.op_nodes_list)) + net.add_node( + n_id=id(op_node), + label=_get_op_node_str(op_node, step=idx), + title=_get_op_node_title(op_node), + color=node_color, + shape="box" + ) + + for op_node in self.op_nodes_list: + for output_key_nodes in op_node.output_keys_nodes.values(): + for ptr_key_node in output_key_nodes.ptr: + target_node = self.op_nodes_list[ptr_key_node.index] + if hide_no_changed_keys and op_node==self.op_nodes_list[0] and target_node==self.op_nodes_list[-1]: + # hide the keys that are not changed from input dataset to first operator + continue + + net.add_edge( + source=id(op_node), + to=id(target_node), + label=ptr_key_node.key, + color="gray" + ) + + + # Timestamped filename to avoid overwriting + ts = datetime.now().strftime("%Y%m%d_%H%M%S_%f") + os.makedirs(".pyvis", exist_ok=True) + output_html = os.path.abspath(os.path.join(".pyvis" ,f"operators_graph_{ts}.html")) + net.save_graph(output_html) + + # Automatically delete the file on exit (whether normal exit or Ctrl-C) + def _cleanup(): + try: + if os.path.exists(output_html): + os.remove(output_html) + print(f"🧹 Deleted temp file: {output_html}") + except Exception as e: + print(f"Failed to clean up file: {e}") + atexit.register(_cleanup) + + # Select port + if port == 0: + sock = socket.socket() + sock.bind(('', 0)) + port = sock.getsockname()[1] + sock.close() + + # Start HTTP service (main thread blocking) + class SilentHandler(SimpleHTTPRequestHandler): + def log_message(self, format, *args): + pass + + # Change to the directory where the file is located so the static service can find it + orig_cwd = os.getcwd() + try: + serve_dir = os.path.dirname(output_html) or "." + os.chdir(serve_dir) + url = f"http://localhost:{port}/{os.path.basename(output_html)}" + print(f"✅ Graph generated, access it at: {url}") + + + with HTTPServer(('0.0.0.0', port), SilentHandler) as httpd: + print(f"HTTP service started, listening on port {port} (Ctrl-C to exit, HTML file will be deleted on exit)") + try: + webbrowser.open(url) + httpd.serve_forever() + + except KeyboardInterrupt: + print("\n❌ Interrupt signal received, exiting and cleaning up file...") + except Exception as e: + print(f"❌ Failed to start HTTP service: {e}") + self.logger.error(f"Failed to start HTTP service: {e}") + finally: + os.chdir(orig_cwd) + + # atexit 会负责删除文件,这里无需重复删除 + # # 保存 HTML + # output_html = "operators_graph.html" + # net.save_graph(output_html) + + # # 选择端口 + # if port == 0: + # sock = socket.socket() + # sock.bind(('', 0)) + # port = sock.getsockname()[1] + # sock.close() + + # # 启动 HTTP 服务(主线程) + # class SilentHandler(SimpleHTTPRequestHandler): + # def log_message(self, format, *args): + # pass + + # os.chdir(os.path.dirname(os.path.abspath(output_html))) + # url = f"http://localhost:{port}/{output_html}" + # print(f"✅ 图已生成,访问: {url}") + # webbrowser.open(url) + + # # 阻塞运行直到 Ctrl-C + # try: + # with HTTPServer(('0.0.0.0', port), SilentHandler) as httpd: + # print(f"HTTP 服务已启动,监听端口 {port},按 Ctrl-C 退出") + # httpd.serve_forever() + # except KeyboardInterrupt: + # print("\n❌ 已退出可视化服务") + + # def _build_serving_resources_map(self): + # for op_runtime in self.op_runtimes: + # for _, v in vars(op_runtime.op).items(): + # if isinstance(v, LLMServingABC): + # self.serving_resources[op_runtime.op]["LLMServingABC"] = v + # self.serving_reference_count[v] += 1 + + def _compiled_forward(self, resume_step: int=0): + """ + resume_step (int): resume inference from this step + """ + # for loop for each op and its `storage` status + for idx, op_node in enumerate(self.op_nodes_list): + # resume from a expected step + if idx - 1 < resume_step: # minus one since INPUT-DATA Node + continue + + self.logger.debug(f"Ready to run {op_node}, with serving={op_node.llm_serving}, active_llm_serving={self.active_llm_serving}") + if op_node.llm_serving != None: + if self.active_llm_serving and self.active_llm_serving is not op_node.llm_serving: + self.logger.debug(f"Detected active LLM Serving {self.active_llm_serving}, new serving {op_node.llm_serving}, cleaning up...") + self.active_llm_serving.cleanup() + self.active_llm_serving = op_node.llm_serving + + if op_node.op_obj != None: + op_node.op_obj.run( + storage=op_node.storage, + **op_node.kwargs + ) + if op_node.llm_serving != None: + self.llm_serving_counter[self.active_llm_serving] -= 1 + if self.llm_serving_counter[self.active_llm_serving] == 0: + self.logger.debug(f"Detected LLM Serving {self.active_llm_serving} ref reduced to 0, cleaning up...") + self.active_llm_serving.cleanup() + self.active_llm_serving = None + + +class BatchedPipelineABC(PipelineABC): + def __init__(self): + super().__init__() + + def _compiled_forward(self, resume_step: int=0, batch_size: int|None=None, resume_from_last: bool=True): + """ + resume_step (int): resume inference from this step + batch_size (int|None): if set, run the pipeline in batch mode with this batch size + resume_from_last (bool): if True, resume from the last successful step and batch + """ + if not self.compiled: + raise RuntimeError("Pipeline is not compiled yet. Please call `compile()` before running the pipeline.") + + if resume_step > 0 and resume_from_last: + raise ValueError("Cannot set both `resume_step` and `resume_from_last` to True.") + + resume_batch = 0 + + if resume_from_last: + cache_path = os.path.join(self.op_nodes_list[1].storage.cache_path, f"{self.op_nodes_list[1].storage.file_name_prefix}_last_success_step.txt") + if not os.path.exists(cache_path): + resume_step = 0 + resume_batch = 0 + self.logger.info(f"No last success step cache found at {cache_path}, starting from step 0.") + else: + with open(cache_path, "r") as f: + line = f.readline().strip() + resume_step, resume_batch = map(int, line.split(",")) + self.logger.info(f"Resuming from last success step {resume_step}, batch step {resume_batch}.") + + # for loop for each op and its `storage` status + for idx, op_node in enumerate(self.op_nodes_list): + # resume from a expected step + if idx - 1 < resume_step: # minus one since INPUT-DATA Node + continue + + self.logger.debug(f"Ready to run {op_node}, with serving={op_node.llm_serving}, active_llm_serving={self.active_llm_serving}") + if op_node.llm_serving != None: + if self.active_llm_serving and self.active_llm_serving is not op_node.llm_serving: + self.logger.debug(f"Detected active LLM Serving {self.active_llm_serving}, new serving {op_node.llm_serving}, cleaning up...") + self.active_llm_serving.cleanup() + self.active_llm_serving = op_node.llm_serving + + if op_node.op_obj != None: + if batch_size is not None: + storage = op_node.storage + storage.batch_step = 0 if idx - 1 > resume_step else resume_batch + storage.batch_size = batch_size + storage.read() # read to set data count + record_count = storage.record_count + + RUN_TIMES = 1 if batch_size is None else ((record_count - 1) // batch_size + 1) - storage.batch_step + if batch_size is not None: + self.logger.info(f"Pipeline will run for {RUN_TIMES} iterations to cover {record_count} records with batch size {batch_size}.") + for _ in tqdm(range(RUN_TIMES), desc=f"\033[1;36mRunning {op_node.op_name} with batch size={batch_size}\033[0m", position=0, dynamic_ncols=True, colour='cyan'): + op_node.op_obj.run( + storage=op_node.storage, + **op_node.kwargs + ) + if batch_size is not None: + op_node.storage.batch_step += 1 + if resume_from_last: + resume_batch = op_node.storage.batch_step if batch_size is not None else 0 + with open(cache_path, "w") as f: + f.write(f"{idx-1},{resume_batch}\n") + if resume_from_last: + resume_batch = 0 # reset for next op_node + with open(cache_path, "w") as f: + f.write(f"{idx},{resume_batch}\n") + if op_node.llm_serving != None: + self.llm_serving_counter[self.active_llm_serving] -= 1 + if self.llm_serving_counter[self.active_llm_serving] == 0: + self.logger.debug(f"Detected LLM Serving {self.active_llm_serving} ref reduced to 0, cleaning up...") + self.active_llm_serving.cleanup() + self.active_llm_serving = None + +class StreamBatchedPipelineABC(BatchedPipelineABC): + def __init__(self): + super().__init__() + + def _compiled_forward(self, resume_step: int=0, batch_size: int|None=None, resume_from_last: bool=True): + """ + resume_step (int): resume inference from this step + batch_size (int|None): if set, run the pipeline in batch mode with this batch size + resume_from_last (bool): if True, resume from the last successful step and batch + """ + if not self.compiled: + raise RuntimeError("Pipeline is not compiled yet. Please call `compile()` before running the pipeline.") + + if resume_step > 0 and resume_from_last: + raise ValueError("Cannot set both `resume_step` and `resume_from_last` to True.") + + resume_batch = 0 + + if resume_from_last: + cache_path = os.path.join(self.op_nodes_list[1].storage.cache_path, f"{self.op_nodes_list[1].storage.file_name_prefix}_last_success_step.txt") + if not os.path.exists(cache_path): + resume_step = 0 + resume_batch = 0 + self.logger.info(f"No last success step cache found at {cache_path}, starting from step 0.") + else: + with open(cache_path, "r") as f: + line = f.readline().strip() + resume_step, resume_batch = map(int, line.split(",")) + self.logger.info(f"Resuming from last success step {resume_step}, batch step {resume_batch}.") + + # for loop for each op and its `storage` status + for idx, op_node in enumerate(self.op_nodes_list): + # resume from a expected step + if idx - 1 < resume_step: # minus one since INPUT-DATA Node + continue + + self.logger.debug(f"Ready to run {op_node}, with serving={op_node.llm_serving}, active_llm_serving={self.active_llm_serving}") + if op_node.llm_serving != None: + if self.active_llm_serving and self.active_llm_serving is not op_node.llm_serving: + self.logger.debug(f"Detected active LLM Serving {self.active_llm_serving}, new serving {op_node.llm_serving}, cleaning up...") + self.active_llm_serving.cleanup() + self.active_llm_serving = op_node.llm_serving + + if op_node.op_obj != None: + if batch_size is not None: + storage = op_node.storage + storage.batch_step = 0 if idx - 1 > resume_step else resume_batch + storage.batch_size = batch_size + record_count = storage.get_record_count() + data_stream = storage.iter_chunks() + for _ in range(storage.batch_step): + next(data_stream, None) + + RUN_TIMES = 1 if batch_size is None else ((record_count - 1) // batch_size + 1) - storage.batch_step + if batch_size is not None: + self.logger.info(f"Pipeline will run for {RUN_TIMES} iterations to cover {record_count} records with batch size {batch_size}.") + for _ in tqdm(range(RUN_TIMES), desc=f"\033[1;36mRunning {op_node.op_name} with batch size={batch_size}\033[0m", position=0, dynamic_ncols=True, colour='cyan'): + if batch_size is not None: + try: + current_batch_df = next(data_stream) + op_node.storage._current_streaming_chunk = current_batch_df + except StopIteration: + break + + op_node.op_obj.run( + storage=op_node.storage, + **op_node.kwargs + ) + if batch_size is not None: + op_node.storage._current_streaming_chunk = None + op_node.storage.batch_step += 1 + if resume_from_last: + resume_batch = op_node.storage.batch_step if batch_size is not None else 0 + with open(cache_path, "w") as f: + f.write(f"{idx-1},{resume_batch}\n") + if resume_from_last: + resume_batch = 0 # reset for next op_node + with open(cache_path, "w") as f: + f.write(f"{idx},{resume_batch}\n") + if op_node.llm_serving != None: + self.llm_serving_counter[self.active_llm_serving] -= 1 + if self.llm_serving_counter[self.active_llm_serving] == 0: + self.logger.debug(f"Detected LLM Serving {self.active_llm_serving} ref reduced to 0, cleaning up...") + self.active_llm_serving.cleanup() + self.active_llm_serving = None diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/pipeline/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/pipeline/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..609e2a0a1786920cdf8fd0f20f37c2ceb4e75300 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/pipeline/__init__.py @@ -0,0 +1,7 @@ +from .Pipeline import PipelineABC, BatchedPipelineABC, StreamBatchedPipelineABC + +__all__ = [ + 'PipelineABC', + 'BatchedPipelineABC', + 'StreamBatchedPipelineABC' +] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/pipeline/__pycache__/Pipeline.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/pipeline/__pycache__/Pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..271040dd2ce6ff87b71df2155c600cd8103c6580 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/pipeline/__pycache__/Pipeline.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/pipeline/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/pipeline/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4801179ae41f0406f8de82ffd7d27cd883b2a6f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/pipeline/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/pipeline/__pycache__/nodes.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/pipeline/__pycache__/nodes.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c000603e85fa6714f400addc759311ded8459032 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/pipeline/__pycache__/nodes.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/pipeline/nodes.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/pipeline/nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..bb59421e8a03de62dcce4e3b160032d9561f7f57 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/pipeline/nodes.py @@ -0,0 +1,95 @@ +from __future__ import annotations +from dataflow.core import OperatorABC +from dataflow.core import WrapperABC +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OPERATOR_CLASSES, LLM_SERVING_CLASSES +from typing import Union + +class KeyNode(object): + def __init__( + self, + key_para_name: str, + key: str, + ptr: list[KeyNode] = None + ): + self.key_para_name = key_para_name # name of the parameter in the operator's run functio + self.key = key + self.ptr = ptr if ptr != None else [] # ptr to next KeyNode(s), used to build a list of keys + + def set_index(self, index:int): + self.index = index + + def __str__(self): + current_id = hex(id(self)) + ptr_status = [ + (node.key, node.index, hex(id(node))) for node in self.ptr + ] if len(self.ptr) != 0 else ["None"] + ptr_str = "".join([ + f"\n <{item}>" for item in ptr_status + ]) + return f"\n KeyNode[{current_id}](key_para_name={self.key_para_name}, key={self.key}, ptr_keys={ptr_str})" + + def __repr__(self): + return self.__str__() + + +class OperatorNode(object): + def __init__( + self, + op_obj: OPERATOR_CLASSES = None, + op_name: str = None, + storage: DataFlowStorage = None, + llm_serving: LLM_SERVING_CLASSES = None, + **kwargs + ): + self.op_obj = op_obj + self.op_name = op_name + self.storage = storage # will be set when the operator is initialized + self.llm_serving = llm_serving # will be set when the operator is initialized + self.kwargs = kwargs # parameters for the operator's run function + + # Initialize input and output keys + self.input_keys = [] + self.input_key_nodes: dict[KeyNode] = {} + self.output_keys = [] + self.output_keys_nodes: dict[KeyNode] = {} + + self._get_keys_from_kwargs() # Extract keys from kwargs + + def _get_keys_from_kwargs(self): + for k, v in self.kwargs.items(): + if k.startswith("input_") and isinstance(v, str): + self.input_keys.append(v) + self.input_key_nodes[v] = KeyNode(k, v) + elif k.startswith("output_") and isinstance(v, str): + self.output_keys.append(v) + self.output_keys_nodes[v] = KeyNode(k, v) + else: # warning for unexpected keys with red color + print(f"\033[91mWarning: Unexpected key '{k}' in operator {self.op_obj.__class__.__name__}\033[0m") + + def init_output_keys_nodes(self, keys:list[str]): + for key in keys: + self.output_keys.append(key) + self.output_keys_nodes[key]= KeyNode(key,key) + def init_input_keys_nodes(self, keys:list[str]): + for key in keys: + self.input_keys.append(key) + self.input_key_nodes[key] = KeyNode(key, key) + + def __str__(self): + op_class = self.op_obj.__class__.__name__ if self.op_obj else None + input_keys_str = ', '.join(self.input_keys) + output_keys_str = ', '.join(self.output_keys) + return ( + f"OperatorNode(\n" + f" op_obj:{self.op_obj}" + f" Operator_class: {op_class},\n" + f" Operator_name: {self.op_name},\n" + f" Storage: {self.storage},\n" + f" Input Keys: [{input_keys_str}],\n" + f" Output Keys: [{output_keys_str}],\n" + f" Input Nodes: [{self.input_key_nodes}],\n" + f" Output Nodes: [{self.output_keys_nodes}],\n" + f" Additional Params: {self.kwargs}\n" + f")" + ) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d6c3e5fc749f976f925303fddd7e4764425ccef3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__init__.py @@ -0,0 +1 @@ +from .reasoning import * \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb466acb0f4e6da6be1bf413102427a0b58eb3a5 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/agenticrag.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/agenticrag.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e10f5fdd828aef7f0b9c58ca42d5b4758825f2ea Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/agenticrag.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/chemistry.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/chemistry.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b13039a83aa32fe8a9eef95d4f3f842b249e48c1 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/chemistry.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/code.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/code.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b83f48a00830e1b50abc455411681bf017324ba Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/code.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/core_text.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/core_text.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..266f4d4651fd319556be9b805c661d9b35d0409a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/core_text.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/func_call.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/func_call.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1496bd539f4e0251cf07ef009c93e0a4e9754443 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/func_call.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/general_text.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/general_text.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a82be58edba5e00df3e0078f30a5653e038c446b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/general_text.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/kbcleaning.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/kbcleaning.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85f928a7147b2cc9133b807db105d9a8f330e2bf Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/kbcleaning.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/pdf2vqa.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/pdf2vqa.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f81ed7f0a5bcac9969f5a2bd6898ee6d9b2f94a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/pdf2vqa.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/text2qa.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/text2qa.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4262d1083d18ad4688b95b6bb7ffb2da72242f11 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/__pycache__/text2qa.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/agenticrag.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/agenticrag.py new file mode 100644 index 0000000000000000000000000000000000000000..8f9ab5c544ca04f8cc6d8d2c5c5dd740e0749732 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/agenticrag.py @@ -0,0 +1,1922 @@ +import json +from dataflow.utils.registry import PROMPT_REGISTRY +from dataflow.core.prompt import PromptABC +""" +A collection of prompts for the AgenticRAG pipelines operator +""" + +@PROMPT_REGISTRY.register() +class AtomicTaskGeneratorGetIdentifierPrompt(PromptABC): + ''' + The prompt for the AtomicTaskGenerator to get identifier. + ''' + def __init__(self): + pass + + def build_system_prompt(self) -> str: + system_prompt = ''' + You need to extract the content_identifier from question. Here's how: + 1. For each question, identify the main subject/noun phrase that the question is about + 2. This should typically be: + - Proper nouns (names, titles) + - Specific technical terms + - Unique identifiers in the question + + Examples: + { + "question": "What is the third movie in the Avatar series?", + "content_identifier": "Avatar series" + }, + { + "question": "龙美术馆2025年展览展览时间范围是什么", + "content_identifier": "龙美术馆" + } + + Return JSON format with key "content_identifier" +''' + return system_prompt + + def build_prompt(self, input) -> str: + prompt = f''' + Now process this question:{input} + ''' + return prompt + +@PROMPT_REGISTRY.register() +class AtomicTaskGeneratorGetConlcusionPrompt(PromptABC): + ''' + The prompt for the AtomicTaskGenerator to get initial conclusion. + ''' + def __init__(self): + pass + + def build_system_prompt(self) -> str: + system_prompt = ''' + # Conclusion Extraction and Relationship Generation Specifications + + ## I. Input/Output Requirements + **Input**: Any document fragment + **Output**: JSON array where each element contains `conclusion` and `R` fields + + ## II. Conclusion Extraction Rules + 1. **Atomicity** + - Each conclusion must be an indivisible basic fact + - ✖ Prohibited combined conclusions: "A increased by 5% and B decreased by 2%" → Should be split into two conclusions + + 2. **Verifiability** + - Must contain at least one definite identifier: + ✓ Numeric value (59.0%) + ✓ Time (2025/04/28) + ✓ Unique name (Humpback65B) + - ✖ Reject vague expressions: "Performance has improved" + + 3. **Timeliness Handling** + - Explicitly mark time ranges when containing time-sensitive information + - Examples: + ✓ "Global GDP grew by 3.0% in 2023" + ✖ "Recent GDP growth of 3.0%" + + 4. **Citation Integrity** + - If a conclusion cites other content (e.g., "as stated in (2)"), the complete content of (2) must be embedded in the conclusion + + ## III. Relationship (R) Generation Standards + ### Attribute Requirements + - **Structured**: Use semicolons to separate multi-metrics (Example 3) + - **Operational**: Directly usable for database queries or calculations + ✓ "City with the highest temperature" + ✖ "Conclusions about temperature" + + ### Generation Templates + | Conclusion Type | R Template | Example | + |-------------------------|---------------------------------------|---------------------------------| + | Single Numeric Result | "[Indicator Name]" | A: "59.0%" → R: "Accuracy" | + | Comparative Conclusion | "[Indicator] compared to [baseline] in [change dimension]" | A: "4.2% higher than baseline" → R: "Improvement in accuracy compared to baseline" | + | Multi-dimensional Result| "[Primary Indicator] and its [sub-dimension] distribution" | A: "Average 59% (Humanities 65.6%)" → R: "Average accuracy and subject distribution" | + + ## IV. Output Specifications and Examples + [ + { + "conclusion": "Humpback65B achieved a zero-shot accuracy of 59.0% in the MMLU evaluation", + "R": "Humpback65B's zero-shot accuracy" + }, + { + "conclusion": "On 2025/04/28, the closing price of XL Er Nantes-U was $11.34 (up 14.0%)", + "R": "Closing price and percentage increase of XL Er Nantes-U on 2025/04/28" + }, + { + "conclusion": "90% of 27 million metric tons", + "R": "Proportion of new global LNG supply from North America in 2025" + }, + { + "conclusion": "Abstract", + "R": "Indexed part of Springer articles in databases" + }, + { + "conclusion": "2024-03-06", + "R": "Publication date of Psychology Top 100 of 2023" + }, + { + "conclusion": "2018-01", + "R": "Collection date of 'The Importance of Referencing - PMC'" + }, + { + "conclusion": "30-40%", + "R": "Percentage of science report dedicated to results section" + }, + { + "conclusion": "$500 billion", + "R": "Projected economic contribution of hybrid work models by 2030" + }, + { + "conclusion": "650,000+", + "R": "Number of youth insights in India Skills Report 2025" + }, + { + "conclusion": "July 2024 issue", + "R": "Consumer Reports publication in July 2024" + }, + { + "conclusion": "16th annual, 2024-12", + "R": "Edition and publication date of Deloitte's Tech Trends 2025" + }, + { + "conclusion": "January 2024 issue", + "R": "Consumer Reports publication in January 2024" + }, + { + "conclusion": "December 2021 issue", + "R": "Consumer Reports publication in December 2021" + }, + { + "conclusion": "November 2021 issue", + "R": "Consumer Reports publication in November 2021" + }, + { + "conclusion": "14", + "R": "Death count in listeria outbreak linked to frozen shakes" + }, + { + "conclusion": "$122 million", + "R": "Mega Millions jackpot amount for May 16" + }, + { + "conclusion": "32", + "R": "Number of consecutive years United Way met its goal" + }, + { + "conclusion": "62%", + "R": "Percentage increase in Chemical Sciences article submissions (2014-2021)" + }, + { + "conclusion": "11 pounds of fish", + "R": "Fish trade for Europa League semifinal ticket" + }, + { + "conclusion": "2-1", + "R": "PSG vs. Arsenal match result (Champions League)" + } + ] + ''' + return system_prompt + + def build_prompt(self, input) -> str: + prompt = f''' + The document content to be processed is as follows: {input} + ''' + return prompt + +@PROMPT_REGISTRY.register() +class AtomicTaskGeneratorQuestionPrompt(PromptABC): + ''' + The prompt for the AtomicTaskGenerator to get initial question. + ''' + def __init__(self): + pass + + def build_system_prompt(self) -> str: + system_prompt = '''Your task is to generate a corresponding question (Q) based on the given task identifier (ID), relationship (R), and answer (A). + + Input/Output Specifications: + Input: + - ID: Data source or query scope + - R: Logical relationship for extracting the answer from the data + - A: Known correct answer + + Output: + - Must be in strict JSON format: {"Q": "generated question"} + - No explanations or extra fields allowed + + Q must satisfy: + 1. Be a complete natural language question + 2. Allow deriving answer A by applying R after accessing context via ID + + Question Generation Principles: + 1. Exact correspondence - Each question must fully base on the original conclusion, with the answer being its core content. + 2. Derivability - The original conclusion must be directly derivable from the question and be the only correct answer. + 3. Self-containment - Questions must be complete and independent, not relying on external references or unspecified context. + 4. Information hiding - Do not reveal specific sources or data paths, but can include search hints. + 5. Specificity and clarity - Questions should include details like specific times to ensure unique answers. + 6. Single question - Generate only one question per conclusion. + 7. If the conclusion can only be obtained from input content, include hints via data source identifiers in the question. + 8. Language consistency - The language of each question must be the same as the conclusion's language. + + Examples: + Input: + ID: Global daily maximum temperatures + R: City with the highest temperature + A: xx City + Output: {"Q": "What is the city with the highest temperature in global daily maximum temperatures?"} + + Only output JSON without additional content. + ''' + return system_prompt + + def build_prompt(self, identifier, conclusion, relation) -> str: + prompt = f''' + Data to be Processed: + ID: {identifier} + R: {relation} + A: {conclusion} + ''' + + return prompt + +@PROMPT_REGISTRY.register() +class AtomicTaskGeneratorCleanQAPrompt(PromptABC): + ''' + The prompt for the AtomicTaskGenerator to clean QA. + ''' + def __init__(self): + pass + + def build_system_prompt(self) -> str: + system_prompt = '''Processing Rules: + 1. Extract ONLY the exact information requested in the question + 2. Preserve the original index numbering + 3. Never omit essential information + 4. Standardize all numerical formats: + - Percentages: 8% (not "8percent" or "eight percent") + - Numbers: Use commas for thousands (3,045) + - Currency: $1,000 (not "1000 dollars") + - Dates: YYYY-MM-DD format + - Units: include (5kg, 10cm, etc.) + + Example: + { + "question": "How many travel trends for 2022 does '2025 Annual Travel Trends Report' present?", + "original_answer": "The Neo4j graph database was used to organize 3,045 Raman spectra of exosomes.", + "refined_answer": "3,045" + } + + Required JSON format: + { + "question": str, + "original_answer": str, + "refined_answer": str + } + + Key requirements: + - Be extremely concise in refined_answer + - Never add information not present in original_answer + - Preserve all numerical values exactly + - If question asks for specific data, extract only that data + ''' + return system_prompt + + def build_prompt(self, input) -> str: + prompt = f''' + The data need to be processed is as follows: {input} + ''' + + return prompt + +@PROMPT_REGISTRY.register() +class AtomicTaskGeneratorAnswerPrompt(PromptABC): + ''' + The prompt for the AtomicTaskGenerator to get LLM's answer. + ''' + def __init__(self): + pass + + def build_prompt(self, input) -> str: + prompt = f'''Please solve the following problem and return as many relevant results as possible that meet the query requirements.\n Ensure responses are as concise as possible, focusing only on key information while omitting redundant details.\n The task is:\n {input} + '''.strip() + + return prompt + +@PROMPT_REGISTRY.register() +class AtomicTaskGeneratorRecallScorePrompt(PromptABC): + ''' + The prompt for the AtomicTaskGenerator to get recall score. + ''' + def __init__(self): + pass + + def build_system_prompt(self) -> str: + system_prompt = ''' +Evaluate the consistency of the core content of the golden answer and the other answer + # Scoring Criteria + 1) 2 points: the information between the golden answer and the other answer completely consistent, although the expression methods can be different. + 2) 1 point: the other answer contains all the information of the golden answer but has additional valid information. + 3) 0 point: the other answer lacks the necessary key information of the golden answer, or there are contradictions in both the information. + + # Examples: + 1) Examples for 2 points: + 1.1) two answers are completely consistent: + - Golden answer: Interest rates should be raised and inflation should be monitored. + - Other answer: It is necessary to raise interest rates and monitor inflation. + 2) Examples for 1 point: + 2.1) the other answer contains all the information of the golden answer and adds extra useful information: + - Golden answer: The interest rates should be raised. + - Other answer: The interest rates should be raised and inflation should be monitored. + 3) Examples for 0 point: + 3.1) the other answer lacks the key information of the golden answer: + - Golden answer: The interest rates should be raised and inflation should be monitored. + - Other answer: The interest rates should be raised. + 3.2) the other answer has contradictions: + - Golden answer: Interest rates should be raised by 50 basis points. + - Other answer: Interest rates should be raised by 25 basis points. + + # the output should be in JSON format as required without any irrelevant content + { + "answer_analysis":"give out the reason on how to score the llm_answer", + "answer_score":0/1/2 + } +''' + return system_prompt + + def build_prompt(self, golden_answer, llm_answer) -> str: + prompt = f''' + The inputs are as follows: + Golden Answer: {golden_answer} + Other Answer: {llm_answer} + ''' + return prompt + +@PROMPT_REGISTRY.register() +class AtomicTaskGeneratorOptionalAnswerPrompt(PromptABC): + ''' + The prompt for the AtomicTaskGenerator to get optional answer. + ''' + def __init__(self): + pass + + def build_system_prompt(self) -> str: + system_prompt = """ + You are an expert in **linguistic variation** and **data augmentation**. Your task is to generate a comprehensive list of all plausible and commonly recognized alternative expressions, formats, and aliases for a given input entity or piece of information. The goal is to create high-quality training data that captures diverse ways of referring to the same concept. + + **Key Guidelines:** + + 1. **Equivalence:** Each alternative expression must refer to *exactly the same entity or information* as the original input. Do not include broader categories, narrower sub-types, or related but distinct concepts. + 2. **Scope of Variation:** Focus on: + Different **formatting conventions** (e.g., dates, numbers, units). + Common **abbreviations, acronyms, or initialisms**. + Well-known **aliases, nicknames, or shorter forms** in common usage. + Synonyms or rephrasing should *only* be included if they are direct, commonly accepted equivalents. + 3. **Context-Agnosticism:** Unless the input itself implies a specific context, generate general-purpose variations. Avoid creating variations that are only valid in very niche or obscure contexts. + 4. **Inclusion of Original:** Always include the original input as the first item in the generated list. + 5. **Format:** Output the variations as a JSON list of strings. + + **Examples:** + + Input: 1977-01-26 + Output: ["1977-01-26", "1977 01 26", "1977.01.26", "January 26, 1977", "26 Jan 1977", "Jan 26, 1977"] + + Input: United Nations + Output: ["United Nations", "U.N.", "UN"] + + Input: 3.14159 + Output: ["3.14159", "π", "pi", "PI"] + + Input: Doctor of Philosophy + Output: ["Doctor of Philosophy", "Ph.D.", "PhD", "Doctorate"] + + Input: New York City + Output: ["New York City", "NYC", "The Big Apple"] + + Input: kilogram + Output: ["kilogram", "kg", "kilograms"] + + """ + + return system_prompt + + def build_prompt(self, answer) -> str: + prompt = f""" + The original answer is: {answer} + Please list all possible textual expressions that have the same meaning or refer to the same entity, especially in different formats (e.g., dates, names, abbreviations). + Respond with a JSON list of strings. Do not explain. + + """ + return prompt + +@PROMPT_REGISTRY.register() +class AtomicTaskGeneratorGoldenDocAnswerPrompt(PromptABC): + ''' + The prompt for the AtomicTaskGenerator to get LLM's answer with golden doc. + ''' + def __init__(self): + pass + + def build_prompt(self, golden_doc, question) -> str: + prompt = f"""You are given the following document that contains relevant information to help answer a question. +Document: +\"\"\" +{golden_doc} +\"\"\" +Question: +{question} +Please answer the question using ONLY the information in the provided document. Return the final answer directly, with no explanation. + """ + return prompt + +@PROMPT_REGISTRY.register() +class DepthQAGeneratorGetIdentifierPrompt(PromptABC): + ''' + The prompt for the AtomicTaskGenerator to get identifier. + ''' + def __init__(self): + pass + + def build_system_prompt(self) -> str: + system_prompt = ''' + You need to extract the content_identifier from question. Here's how: + 1. For each question, identify the main subject/noun phrase that the question is about + 2. This should typically be: + - Proper nouns (names, titles) + - Specific technical terms + - Unique identifiers in the question + + Examples: + { + "question": "What is the third movie in the Avatar series?", + "content_identifier": "Avatar series" + }, + { + "question": "龙美术馆2025年展览展览时间范围是什么", + "content_identifier": "龙美术馆" + } + + Return JSON format with key "content_identifier" +''' + return system_prompt + + def build_prompt(self, input) -> str: + prompt = f''' + Now process this question:{input} + ''' + return prompt + +@PROMPT_REGISTRY.register() +class DepthQAGeneratorBackwardTaskPrompt(PromptABC): + ''' + The prompt for the AtomicTaskGenerator to get backward task. + ''' + def __init__(self): + pass + + def build_prompt(self, input) -> str: + prompt = f''' + Conduct divergent searches based on the input element to find an appropriate superset related to its attributes, and elaborate on the relationship between the superset and the element (mine for special and uniquely pointing relationships to ensure that the superset + relationship does not mislead to other subsets). Example supersets include: + 1. The superset of a paragraph or sentence can be the text content it belongs to. + 2. The superset of a specific term can be its corresponding discipline or category. + 3. The superset of a specific date can be any date range containing it, such as the week or month it belongs to. + 4. The superset of a short event can be the complete specific event it belongs to. + 5. The superset of a page can be other pages referencing it or its parent page. + 6. Only generate one relationship, and the content of the relationship should preferably not include strongly specific proper nouns. + + Optional expressions for relationships: + 1. Clearly express hierarchical or ownership relationships. If the input is a sub-item of a series of works, the relation should indicate its position; if the input is a part of a superset, the relation should clarify its ownership. + 2. Provide the specific positioning of the input content, such as time range, field of paper publication, or specific role in the superset. + 3. Wording should conform to the research field or industry standards of the input content. + 4. Only provide necessary association information to avoid irrelevant content. Good example: "This study is part of the IRAM NOEMA Large Program research collection". Bad example: "This study is a very important research conducted by many scientists and has produced very meaningful results" (verbose and containing subjective evaluations). + + Note: + 1. Please return the identifier of the superset content, such as attribute name, web page title, paper title, etc., which uniquely locates the superset content. + 2. The content of the superset needs to be obtained through tool invocation, which can be specific web content, PDF text, or image understanding content. + 3. Please clearly describe the relationship between the superset content and the input element, that is, list the qualification conditions from the superset content to ensure that the conditions uniquely point to the input element, and the description of the conditions should be concise. + 4. Use a maximum of 3 search keywords per search; if more than 3 keywords are needed, perform multiple searches separately. + 5. The obtained identifier should preferably be derived from search results and not include the input content. + 6. If the input is a PDF document, give priority to invoking tools to read the document content. + + Return format requirements: Please return the result in JSON format with keys 'identifier': str (identifier) and 'relation': str (relationship). + + Here are some reference input-output examples: + Example1: + Input: Avatar 3: Fire and Ash + identifier: Avatar film series + relation: The third film + + Example2: + Input: The 15 social media trends that will shape your 2025 strategy + identifier: Hootsuite blog end of 2024 + relation: The authoritative trends report published by Hootsuite to guide social media strategy development + + Example3: + Input: SOLIS (Seeds of Life In Space) project + identifier: NOEMA Large Program + relation: A sub-project within NOEMA's specific large observation program related to research on the existence of life in the universe. + + Example4: + Input: SOLIS. XIX. The chemically rich SVS13-B protostellar jet + identifier: IRAM NOEMA Large Program research collection + relation: One of the imaged enriched molecular jet samples in the IRAM NOEMA Large Program research collection, specifically imaged and analyzed for molecular distribution and composition within the collection, uniquely locatable via observation data on SVS13-B in the collection. + + Example5: + Input: AdCare -VLM: Leveraging Large Vision Language Model (LVLM) to Monitor Long-Term Medication Adherence and Care + identifier: A Survey of State of the Art Large Vision Language Models: Alignment, Benchmark, Evaluations and Challenges + relation: A paper that introduces advancements in large vision language models in A Survey of State of the Art Large Vision Language Models: Alignment, Benchmark, Evaluations and Challenges, covering models including the LVLM described in the input paper. + + Example6: + Input: Immigration is a higher priority for Americans in 2025: AP-NORC poll | AP News + identifier: 2025 policy priorities report for AAPI communities + relation: The poll results about shifting immigration priorities featured in AP News and referenced in AAPI policy reports + + Example7: + Input: X-ray Absorption Spectroscopy (XAS) database for iron-containing proteins (arXiv:2504.18554) + identifier: iron-binding proteins database + relation: The specialized database that collects XAS data specifically for proteins containing iron + + Example8: + Input: live-action 'Snow White' movie controversy + identifier: Disney animated film adaptation + relation: The controversial live-action movie adapted from a Disney animated film featuring the main character Snow White + + Example9: + Input: Evaluating the evidence: a systematic review of reviews of the effectiveness and safety of digital interventions for ADHD | BMC Psychiatry | Full Text + identifier: BMC Psychiatry journal 2025 publications + relation: The full-text systematic review about digital ADHD interventions published in BMC Psychiatry + + Example10: + Input: Enron Corporation + identifier: 2001 Fortune Global 500 energy industry rankings + relation: The company that ranked first in revenue in the energy sector according to the 2001 Fortune Global 500 rankings + + Current input: + {input} + ''' + return prompt + +@PROMPT_REGISTRY.register() +class DepthQAGeneratorSupersetCheckPrompt(PromptABC): + ''' + The prompt for the AtomicTaskGenerator to check superset. + ''' + def __init__(self): + pass + + def build_system_prompt(self) -> str: + system_prompt = ''' +**Task**: Validate if a given "superset" can uniquely identify a "subset" based on the provided "relationship". + + **Rules**: + 1. **Superset-Subset Relationship**: + - The "superset" must be a true generalization of the "subset" (e.g., "Animal" is a valid superset of "Dog"). + - The "superset" CANNOT be a synonym of the "subset" (e.g., "Car" and "Automobile" are invalid). + + 2. **Relationship Validity**: + - The relationship must **explicitly and uniquely** link the superset to the subset. + - It CANNOT be a **many-to-one mapping**. + + **Output Format**: + Return a JSON with the key `new_query`. The value should be: + - `"valid"` if the superset and relationship can uniquely locate the subset. + - `"invalid"` otherwise. + + **Example Valid Output**: + {"new_query": "valid"} +''' + return system_prompt + + def build_prompt(self, new_id, relation, identifier) -> str: + prompt = f''' +Given superset: {new_id}\n +Given relationship: {relation}\n +Given subset: {identifier}\n +''' + return prompt + +@PROMPT_REGISTRY.register() +class DepthQAGeneratorQuestionPrompt(PromptABC): + ''' + The prompt for the AtomicTaskGenerator to get question. + ''' + def __init__(self): + pass + + def build_system_prompt(self) -> str: + system_prompt = ''' + Please generate a question based on the content of the input identifier, a certain answer, and a certain relationship (this relationship is the relationship between the content of the file corresponding to the identifier and the given answer), such that + The answer to this question is the input answer. + The content of this question is determined by the content of the identifier and the content of the given relationship. + The generated question should not involve the content of the input answer. + Please return it in JSON format, with the key of the JSON being new_query. +''' + return system_prompt + + def build_prompt(self, new_id, relation, identifier) -> str: + prompt = f''' + Certain answer: {identifier}\n + Identifier: {new_id}\n + Relationship: {relation}\n +''' + return prompt + +@PROMPT_REGISTRY.register() +class DepthQAGeneratorAnswerPrompt(PromptABC): + ''' + The prompt for the AtomicTaskGenerator to get LLM's answer. + ''' + def __init__(self): + pass + + def build_prompt(self, input) -> str: + prompt = f''' +Please solve the following problem and return as many relevant results as possible that " +"meet the query requirements. Ensure responses are as concise as possible, focusing only " +"on key information while omitting redundant details." +"Please return the result in JSON format with keys 'answer_list': List[str] the list of answers." +"\n\n" +"The task is: \n +{input} + '''.strip() + + return prompt + +@PROMPT_REGISTRY.register() +class DepthQAGeneratorRecallScorePrompt(PromptABC): + ''' + The prompt for the AtomicTaskGenerator to get recall score. + ''' + def __init__(self): + pass + + def build_system_prompt(self) -> str: + system_prompt = ''' +Evaluate the consistency of the core content of the golden answer and the other answer + # Scoring Criteria + 1) 2 points: the information between the golden answer and the other answer completely consistent, although the expression methods can be different. + 2) 1 point: the other answer contains all the information of the golden answer but has additional valid information. + 3) 0 point: the other answer lacks the necessary key information of the golden answer, or there are contradictions in both the information. + + # Examples: + 1) Examples for 2 points: + 1.1) two answers are completely consistent: + - Golden answer: Interest rates should be raised and inflation should be monitored. + - Other answer: It is necessary to raise interest rates and monitor inflation. + 2) Examples for 1 point: + 2.1) the other answer contains all the information of the golden answer and adds extra useful information: + - Golden answer: The interest rates should be raised. + - Other answer: The interest rates should be raised and inflation should be monitored. + 3) Examples for 0 point: + 3.1) the other answer lacks the key information of the golden answer: + - Golden answer: The interest rates should be raised and inflation should be monitored. + - Other answer: The interest rates should be raised. + 3.2) the other answer has contradictions: + - Golden answer: Interest rates should be raised by 50 basis points. + - Other answer: Interest rates should be raised by 25 basis points. + + # the output should be in JSON format as required without any irrelevant content + { + "answer_analysis":"give out the reason on how to score the llm_answer", + "answer_score":0/1/2 + } +''' + return system_prompt + + def build_prompt(self, golden_answer, llm_answer) -> str: + prompt = f''' + The inputs are as follows: + Golden Answer: {golden_answer} + Other Answer: {llm_answer} + ''' + return prompt + +@PROMPT_REGISTRY.register() +class WidthQAGeneratorMergePrompt(PromptABC): + ''' + The prompt for the WidthQAGenerator to merge prompt. + ''' + def __init__(self): + pass + + def build_system_prompt(self) -> str: + system_prompt = ''' + # Comprehensive Task Guide for Research Questions + + ## Core Objective: + Intelligently merge 2-3 related research questions into high-quality comprehensive questions while maintaining the integrity and accuracy of the original content. + + ## Input Requirements: + - Each question includes: index (unique ID), question (question text), golden_answer (standard answer), content_identifier (content identifier) + + ## Grouping Specifications: + + ### Grouping Strategies: + 1. **Content Matching Principle**: + - Priority: Merge questions with similar themes + + 2. **Quantity Control**: + - Each group must contain 2-3 original questions + - Ensure all original questions are grouped (no omissions) + + ### Standards for Question Synthesis: + 1. **Content Integrity**: + - Retain all elements of the original questions + - Do not add new facts or assumptions + - Completely preserve time-related elements in their original form + + 2. **Question Quality**: + - Clear and unambiguous expression + - Logically coherent merged questions + - Do not imply any solution methods + + 3. **Structural Requirements**: + - Form complete interrogative sentences (not simply connected with "and") + - Correct grammatical structure + - Preserve professional terminology in its original form + + ## Output Specifications: + [ + { + "question": "Text of the synthesized question", + "index": [1,2,3], // Original indices + "content_identifier": "Original content identifier" + } + ] + ''' + return system_prompt + + def build_prompt(self, input) -> str: + prompt = f''' + Here are the base questions to process: + {json.dumps(input, indent=2, ensure_ascii=False)} + Each dictionary contains: index (unique ID), question (original question), and content_identifier (identifier). +''' + return prompt + +@PROMPT_REGISTRY.register() +class WidthQAGeneratorOriginCheckPrompt(PromptABC): + ''' + The prompt for the WidthQAGenerator to check origin. + ''' + def __init__(self): + pass + + def build_system_prompt(self) -> str: + system_prompt = ''' + Task Instructions: + Verify if complex questions can be properly decomposed into their original questions. + Return state=1 if all conditions are met, state=0 otherwise: + + Conditions for state=1: + 1. The complex question clearly contains all elements from original questions + 2. No information distortion or ambiguity introduced + 3. Logical relationships between original questions are properly maintained + + + For example: + "index": 1 + "Complex Question": "In the Academia Insider article 'The best AI tools for research papers and academic research (Literature review, grants, PDFs and more)', how does Semantic Scholar enhance literature review efficiency? Who are the two contributors—one with a Master’s and Ph.D. in Chemistry from the UK and Australia, and the other a Ph.D. student at Simon Fraser University (SFU)—credited with contributing academic insights and initiating the list of AI research tools, respectively?" + "Original Questions": [ + "According to 'The best AI tools for research papers and academic research (Literature review, grants, PDFs and more) - Academia Insider', how does Semantic Scholar enhance literature review efficiency?", + "In the Academia Insider article 'The best AI tools for research papers and academic research (Literature review, grants, PDFs and more)', who is the contributor with a Master’s and Ph.D. in Chemistry from the UK and Australia and extensive research experience?", + "In the Academia Insider article 'The best AI tools for research papers and academic research (Literature review, grants, PDFs and more)', who is the contributor credited with helping to start the list of AI research tools?" + ] + The above complex question can be decomposed into these original questions without deviation in content, and the status is returned as 1. + + "index": 2 + "Complex Question": "Based on the trends reported in the 2025 scientific publications of the Academy of Articles and the information on open and free content from the JSTOR and Artstor 'About JSTOR' page, when does research on protecting cultural and linguistic diversity through AI reach its peak? What is the total number of research reports available, and how many policy institutes are represented in the collection?" + "Original Questions": [ + "According to the 2025 scientific publication trends of the Academy of Articles, when does research on protecting cultural and linguistic diversity through AI reach its peak?", + "According to the information on open and free content from the JSTOR and Artstor 'About JSTOR' page, what is the total number of research reports in the collection? How many policy institutes are covered?" + ] + The above complex question cannot be decomposed into original questions because the direction of the questions in the complex question is confusing and ambiguous, and the status is returned as 0. + + Example Output: + [{ + "index": 1, + "complex_question": "original complex question", + "state": 1 + }] +''' + return system_prompt + + def build_prompt(self, input) -> str: + prompt = f''' + Here are the base questions to process: + {json.dumps(input, indent=2, ensure_ascii=False)} + Each dictionary contains: index (unique ID), complex_question (original complex question), + and original_questions (list of original questions). +''' + return prompt + +@PROMPT_REGISTRY.register() +class WidthQAGeneratorQuestionVerifyPrompt(PromptABC): + ''' + The prompt for the WidthQAGenerator to verify question. + ''' + def __init__(self): + pass + + def build_system_prompt(self) -> str: + system_prompt = ''' + Answer the provided complex research questions based on your knowledge. + For each question, provide your answer. + + Output JSON format: + [{ + "index": 1 // original question indices + "complex_question": original complex question, + "llm_answer"://your answer + + }, + { + "index": 2 // original question indices + "complex_question": original complex question, + "llm_answer"://your answer + }] +''' + return system_prompt + + def build_prompt(self, input) -> str: + prompt = f''' + Please answer these research questions: + {json.dumps(input, indent=2, ensure_ascii=False)} +''' + return prompt + +@PROMPT_REGISTRY.register() +class WidthQAGeneratorAnswerPrompt(PromptABC): + ''' + The prompt for the WidthQAGenerator to get LLM's answer. + ''' + def __init__(self): + pass + + def build_prompt(self, input) -> str: + prompt = f''' +Please solve the following problem and return as many relevant results as possible that " +"meet the query requirements. Ensure responses are as concise as possible, focusing only " +"on key information while omitting redundant details." +"Please return the result in JSON format with keys 'answer_list': List[str] the list of answers." +"\n\n" +"The task is: \n +{input} + '''.strip() + + return prompt + +@PROMPT_REGISTRY.register() +class WidthQAGeneratorRecallScorePrompt(PromptABC): + ''' + The prompt for the WidthQAGenerator to get recall score. + ''' + def __init__(self): + pass + + def build_system_prompt(self) -> str: + system_prompt = ''' +Evaluate the consistency of the core content of the golden answer and the other answer + # Scoring Criteria + 1) 2 points: the information between the golden answer and the other answer completely consistent, although the expression methods can be different. + 2) 1 point: the other answer contains all the information of the golden answer but has additional valid information. + 3) 0 point: the other answer lacks the necessary key information of the golden answer, or there are contradictions in both the information. + + # Examples: + 1) Examples for 2 points: + 1.1) two answers are completely consistent: + - Golden answer: Interest rates should be raised and inflation should be monitored. + - Other answer: It is necessary to raise interest rates and monitor inflation. + 2) Examples for 1 point: + 2.1) the other answer contains all the information of the golden answer and adds extra useful information: + - Golden answer: The interest rates should be raised. + - Other answer: The interest rates should be raised and inflation should be monitored. + 3) Examples for 0 point: + 3.1) the other answer lacks the key information of the golden answer: + - Golden answer: The interest rates should be raised and inflation should be monitored. + - Other answer: The interest rates should be raised. + 3.2) the other answer has contradictions: + - Golden answer: Interest rates should be raised by 50 basis points. + - Other answer: Interest rates should be raised by 25 basis points. + + # the output should be in JSON format as required without any irrelevant content + { + "answer_analysis":"give out the reason on how to score the llm_answer", + "answer_score":0/1/2 + } +''' + return system_prompt + + def build_prompt(self, golden_answer, llm_answer) -> str: + prompt = f''' + The inputs are as follows: + Golden Answer: {golden_answer} + Other Answer: {llm_answer} + ''' + return prompt + +@PROMPT_REGISTRY.register() +class AtomicQAGeneratorPrompt(PromptABC): + ''' + The prompt for the AtomicQAGenerator. + ''' + def __init__(self): + self.prompt = '''You are an information extraction and question generation system. + # Task: + Given a document, extract a set of **atomic, verifiable facts** and convert each into a **QA pair**, where: + - The **question** focuses on a specific, retrievable detail from the document. + - The **answer** is concise, factual, and directly grounded in the document. + - For each document, generate **at most {gen_qa_num} QA pairs**. Prioritize the most concrete, unique, and verifiable facts. + - Only generate questions that require consulting the document to answer — avoid trivial facts or common-sense knowledge. + + # Rules for QA Generation + + 1. Atomicity + - Each QA must be based on a single indivisible fact (no conjunctions). + ✖ "A increased and B decreased" → must split into two questions. + + 2. Verifiability + - The answer must include at least one of: + - ✓ Numeric value (e.g., 59.0%) + - ✓ Time or date (e.g., 2025/04/28) + - ✓ Unique name/entity (e.g., Humpback65B) + - ✖ Reject vague expressions: "Performance has improved" + + 3. Time specificity + - Explicitly mark time ranges when containing time-sensitive information + - Examples: + ✓ "Global GDP grew by 3.0% in 2023" + ✖ "Recent GDP growth of 3.0%" + + 4. Relevance and Precision + - Avoid abstract questions. Focus on measurable and database-friendly details. + + 5. Answer Uniqueness + - The question must be **specific enough** to yield a **unique answer** from the document. + - ✖ Avoid under-specified questions that allow **multiple correct answers**. + - ✖ "What awards did Author X receive?" (if multiple awards are listed in the document) + - ✓ "What award did Author X receive in 2022?" (if only one is given for that year) + - ✖ Avoid vague superlatives like "notable," "important," "significant" without clear criteria. + + # Output Format: + A JSON array of QA pairs. Each item contains: + - `question`: A specific, answerable question. + - `answer`: The factual value from the document. + + # Examples + + ```json + [ + {{ + "question": "What is the number 1 sport in the usa?", + "answer": "American football" + }}, + {{ + "question": "Where did the Ottoman slave trade flourish?", + "answer": "In the Balkans" + }}, + {{ + "question": "Who was president when the white house was built?", + "answer": "John Adams" + }} + ] + ``` + + The document content to be processed is as follows: + {input_doc} + ''' + + def build_prompt(self, gen_qa_num: str, input_doc: str) -> str: + return self.prompt.format(gen_qa_num=gen_qa_num, input_doc=input_doc) + +@PROMPT_REGISTRY.register() +class MergeAtomicQAPrompt(PromptABC): + ''' + The prompt for the MergeAtomicQAPrompt. + ''' + def __init__(self): + self.prompt = '''You are an expert in constructing multi-hop questions grounded in document-based facts. + + ## Task + You are given multiple question-answer-document triples to generate multi-hop question that require reasoning over the **latest previous hop** (i.e., the final element in Previous_Hops) together with New_pair. Use Previous_Hops strictly as supporting context: they may be consulted to verify entities/constraints and must be preserved (not removed, weakened, or contradicted) by the final question. + Only produce a multi-hop question if it is logically valid, unambiguous, and well-supported by both documents. If there is any uncertainty or weak connection, return empty JSON list instead of forcing a question. + + ## Input Schema + Previous_Hops: + type: "list of objects (ordered oldest → latest)" + each_item: + - Hop_number + - Question: string + - Answer: string + - Doc: string + New_pair: + type: object (This is the candidate QA+Doc to attach to the chain.) + fields: + - Question: string + - Answer: string + - Doc: string + + ## Output Format (ONLY JSON) + Valid multi-hop case: + {{ + "type": "inference" | "comparison", + "final_question": "...", + "final_answer": "..." + }} + + If no high quality multi-hop question can be created: + Return an empty JSON object {{}} + + ## Types + - inference: + The final question chains information so that answering it requires (1) the last previous hop's facts and (2) the New_pair's facts. For inference cases, final_answer MUST equal New_pair Answer. + - comparison: + The final question compares a shared measurable dimension (e.g., date, numeric quantity, size). Both compared values must be supported explicitly in the documents. The answer should be one of the compared entities. + + ## Rules + - 1. Use Previous_Hops as supporting context. Do NOT remove, weaken, or contradict any fact, constraint, or entity presented in any Previous_Hops's Question/Answer/Doc. + - 2. The final question MUST be generated from (latest Previous_Hop) + (New_pair). DO NOT remove or weaken any Previous_Hops's Question important information in final_question + - 3. DO NOT leak intermediate answers (no explicit exposure of any Previous_Hop answer in the final_question). + - 4. Do not simply restate the New_pair question, and do not return an unexpanded Hop question that is missing or only partially uses the information from the Previous Hop. The final question MUST depend on all QA-doc pairs to be answerable. + - 5. Ensure that there is **sufficient and accurate** evidence to get the answer. + - 6. When linking entities across docs, explicitly verify from the document contents (not just question text) that they refer to the exactly same real-world entity or fact + - 7. For comparison, only compare facts on the same axis (e.g., date vs date, size vs size), not unrelated attributes. + - 8. Do not create final questions that just state multiple facts independently, without a reasoning link between them. + - 9. Favor precision and factual grounding over producing more questions. If the logical connection is weak, ambiguous, or speculative, reject (return {{}}). + - 10. Output only the final JSON object. Do NOT include chain-of-thought, explanations, or any extra text. + + ## Examples + ### final_question is inference + Case 1 (Extend 1-hop question to 2-hop): + Input: + Hop_1: + Question: What is the name of the performer of "Qui de nous deux"? + Answer: Matthieu Chedid + Doc: "Qui de nous deux" is performed by Matthieu Chedid. + + New_pair: + Question: Who is the father of Matthieu Chedid? + Answer: Louis Chedid + Doc: Matthieu Chedid is the son of Louis Chedid. + + Good Output: + {{ + "type": "inference", + "final_question": "Who is the father of the performer of 'Qui de nous deux'?", + "final_answer": "Louis Chedid" + }} + + ✖ Error Case (leaks intermediate answer): + -"final_question": "Who is the father of Matthieu Chedid?" + + Case 2 (Extend 2-hop inference question to 3-hop): + Input: + Hop_1: + Question: Who is the composer of "Al gran sole carico d'amore"? + Answer: Luigi Nono + Doc: "Al gran sole carico d'amore" is an opera with music by Luigi Nono. + + Hop_2: + Question: Where did the composer of "Al gran sole carico d'amore" work? + Answer: Venice + Doc: Luigi Nono was active as a painter in Venice. + type: inference + + New_pair: + Question: What is the name of the oldest bridge in Venice? + Answer: Rialto Bridge + Doc: The Rialto Bridge is the oldest bridge spanning the Grand Canal in Venice. + + Good Output: + {{ + "type": "inference", + "final_question": "What is the name of the oldest bridge in the city where the composer of 'Al gran sole carico d'amore' worked?", + "final_answer": "Rialto Bridge" + }} + + ✖ Error Case (leaks intermediate answer): + -"final_question": "What is the name of the oldest bridge in Luigi Nono worked?" + + Case 3 (Extend 3-hop inference question to 4-hop): + Input: + Hop_1: + Question: Where was Francisco Vázquez born? + Answer: Guadalajara + Doc: Francisco H. Vázquez (born June 11, 1949 in Guadalajara, Jalisco, Mexico) + + Hop_2: + Question: On which continent is Guadalajara located? + Answer: North America + Doc: Guadalajara is located in North America. + type: inference + + Hop_3: + Question: Who was the Italian navigator who sailed for England and explored the east coast of the continent where Francisco Vázquez was born? + Answer: John Cabot + Doc: John Cabot (Italian: Giovanni Caboto; c. 1450 -- c. 1500) was a Venetian navigator and explorer whose 1497 discovery of the coast of North America under the commission of Henry VII of England + type: inference + + New_pair: + Question: What is the name of the child of John Cabot? + Answer: Sebastian Cabot + Doc: Sebastian Cabot was the son of Italian explorer John Cabot (Giovanni Caboto) + + Good Output: + {{ + "type": "inference", + "final_question": "What is the name of the child of the Italian navigator who sailed for England and explored the east coast of the continent where Francisco Vázquez was born?", + "final_answer": "Sebastian Cabot" + }} + + ✖ Error Case (leaks intermediate answer): + -"final_question": "What is the name of the child of the Italian navigator who sailed for England and explored the east coast of North America?" + + ✖ Error Case (remove or weaken important information in Previous_Hops): + -"final_question": "What is the name of the child of the navigator who explored the east coast of Francisco Vázquez was born?" + + ### final_question is comparison + Input: + Question: When was John Beach born? + Answer: January 1, 1812 + Doc: Major John Beach( January 1, 1812 - August 31, 1874) was a United States Army officer during the Black Hawk and American Civil War. + + New_pair: + Question: When was Seth Gordon Persons born? + Answer: February 5, 1902 + Doc: Seth Gordon Persons( February 5, 1902 - May 29, 1965) was an American Democratic politician who was the 43rd Governor of Alabama from 1951 to 1955. + + Good Output: + {{ + "type": "comparison", + "final_question": "Who was born first, John Beach or Seth Gordon Persons?", + "final_answer": "John Beach" + }} + + Another Good Output: + {{ + "type": "comparison", + "final_question": "Was John Beach born before Seth Gordon Persons?", + "final_answer": "Yes" + }} + + ✖ Error Case (leaks intermediate answer): + -"final_question": "Who was born first, John Beach (January 1, 1812 - August 31, 1874) or Seth Gordon Persons?" + + ### ✖ Invalid (spurious linkage: the QA-doc pairs contain unrelated facts that are superficially similar but logically disconnected.) + Input: + Hop_1: + Question: How many cardinals entered the papal conclave on March 31? + Answer: 27 + Doc: Only twenty-seven cardinals entered the conclave on March 31, 1721. + + New_pair: + Question: Which band did 27 open for in the Czech Republic? + Answer: Robert Plant + Doc: 27 is a rock band that opened for Robert Plant in Prague. + + Correct Output: + {{}} + ✖ Error Output (In Example: Cardinals and the rock band '27' are unrelated entities): + final_question: Which band did the cardinals who entered the papal conclave on March 31 open for in the Czech Republic? + final_answer: Robert Plant + + ### ✖ Invalid (spurious linkage: there is no necessary logical connection between them.) + Input: + Hop_1: + Question: What was the deployment order date for the 16th Army to the Ukraine? + Answer: 25 May 1941 + Doc: The 16th Army was ordered to deploy to Ukraine on 25 May 1941. + + New_pair: + Question: Which two spheres of influence were involved in the division of Europe in the 1940s? + Answer: The Western world and the Soviet Union + Doc: Postwar Europe was divided into the Western and Soviet spheres of influence. + + Correct Output: + {{}} + ✖ Error Output (In Example: No causal or thematic link between army deployment date and geopolitical division): + final_question: What were the two major spheres of influence following the deployment of the 16th Army to the Ukraine in 1941? + final_answer: The Western world and the Soviet Union + + ### ✖ Invalid: (entity-based false link: a false connection between facts or documents that arises solely because different entities share identical or highly similar names, without any actual semantic or factual relationship.) + Input: + Hop_1: + Question: Who presents the Statewide Drive program at 107.9 ABC Ballarat? + Answer: Nicole Chvastek + Doc: "107.9 ABC Ballarat" has a total of 16 full time employees. A breakfast program is presented by Steve Martin from 6.15 am to 10.00 am weekdays. A mornings program is presented by Gavin McGrath from 10.00 am to 11.00 am weekdays. The regional "Statewide Drive" program (3.00 pm to 6.00 pm weekdays) is also broadcast from the Ballarat studios. It is presented by Nicole Chvastek and covers Victoria, southern New South Wales and a small part of eastern South Australia. It does not broadcast into the Melbourne metro area. 107.9 ABC Ballarat, callsign 3CRR, is an ABC Local Radio station. + + New_pair: + Question: What toolkit has Nicole Joseph designed for breast care? + Answer: Breast-CareSolutions toolkit + Doc: Nicole Joseph introduced the global and multi-lingual breast care awareness campaign "The Gesture That Saves" in San Francisco in 2016 to 100 global peers from 40 countries during the VV100 retreat. She has designed a comprehensive Breast-CareSolutions toolkit and is currently designing a reproductive-health advocacy program. Nicole Joseph-Chin is the Chief Innovator, Founder and CEO of Ms. Brafit Limited. + + Correct Output: + {{}} + ✖ Error Output (In Example: Nicole Chvastek and Nicole Joseph are different individuals): + final_question: What toolkit has the presenter of the Statewide Drive program at 107.9 ABC Ballarat designed for breast care? + final_answer: Breast-CareSolutions toolkit + + ### ✖ Invalid: (trivial concatenation: the final question simply combines facts without needing reasoning or integration.) + Input: + Hop_1: + Question: Where was the State Normal School at Cheney located by the end of the term's first week? + Answer: Pomeroy building + Doc: By the end of the term's first week, the State Normal School at Cheney was located in the Pomeroy building. + + New_pair: + Question: Who designed the Cheney Building? + Answer: H. H. Richardson + Doc: The Cheney Building was designed by H. H. Richardson. + + Correct Output: + {{}} + ✖ Error Output (In Example: Final_question simply concatenates the two questions together using 'and' without needing reasoning.): + final_question: Which building was used for the State Normal School at Cheney by the end of the term's first week, and who designed the Cheney Building? + final_answer: Pomeroy building, H. H. Richardson + + ### Invalid (lacking_evidence: one or both compared values are not explicitly supported in the provided documents with sufficient precision to support the asserted comparison.) + Hop_1: + Question: What year was the Cambridge Battery completed for the 100-ton gun? + Answer: 1886 + Doc: Cambridge Battery was ready in 1886. + + New_pair: + Question: When did the 1886 United Kingdom general election take place? + Answer: July 1-27, 1886 + Doc: The 1886 United Kingdom general election took place from 1 July to 27 July 1886. + + Correct Output: + {{}} + ✖ Error Output (In Example: The Cambridge Battery is only dated to the year (1886), while the election records include exact dates in July. This lack of precise dating in the document makes it impossible to determine which event occurred first.): + final_question: Which event occurred first, the completion of the Cambridge Battery in 1886 or the United Kingdom general election led by Charles Stewart Parnell in 1886? + final_answer: The completion of the Cambridge Battery in 1886. + + ## Checklist + - [ ] Do all docs describe logically connectable facts? + - [ ] For comparison: are both facts from the same measurable dimension? + - [ ] For inference: does the reasoning chain correctly lead to New_pair Answer? + - [ ] Is the final question truly unanswerable without all QA-doc pairs? + - [ ] Are all intermediate answers hidden? + - [ ] Are the linked entities explicitly confirmed as the same in both documents? + - [ ] Is there sufficient and accurate evidence to get the answer? + + The data need to be processed is as follows: + {Data} + + New_pair: + Question: {New_question} + Answer: {New_answer} + Doc: {New_document} + Only output the final JSON object. Do not explain your reasoning. + ''' + + def build_prompt(self, Data: str, New_question: str, New_answer: str, New_document: str) -> str: + return self.prompt.format(Data=Data, New_question=New_question, New_answer=New_answer, New_document=New_document) + +@PROMPT_REGISTRY.register() +class InferenceCheckPrompt(PromptABC): + ''' + The prompt for checking the inference multihop question. + ''' + def __init__(self): + self.prompt = '''You are a multi-hop QA verification system. + ## Task + You are given a multi-hop QA construction based on two question-answer-document triples: + (Question1, Answer1, Doc1) and (Question2, Answer2, Doc2), and a final multi-hop QA: + - Final_question + - Final_answer + - type: "inference" + + Your job is to **verify whether the final QA is logically valid** according to the reasoning paths and documents. + + ## Input Fields + - Question1, Answer1, Doc1 + - Question2, Answer2, Doc2 + - Final_question, Final_answer + - type: "inference" + + ## Output Format + Return a JSON object: + {{ + "valid": "true" | "false", + "error_type": "bad_linkage" | "entity_false_link" | "trivial_concatenation" | "other", + "justification": "Short explanation of the issue" + }} + + ## Definitions & Rules + - "inference": Final question requires combining QA1 and QA2 in a reasoning chain. The final_answer must exactly match Answer2. No intermediate answers should appear in final_question. + + - "bad_linkage": If the two QA-doc pairs contain unrelated facts that are superficially similar but logically disconnected. + - "entity_false_link": a false connection between two facts or documents that arises solely because different entities share identical or highly similar names, without any actual semantic or factual relationship. + - "trivial_concatenation": If the final question is formed by simply joining two or more independent facts from the given QA-document pairs into a single sentence (often using "and" or similar conjunctions), without any logical reasoning beyond listing the facts. + - "other": Other errors that you think are not included above. + + ## Examples + + ### ✓ Valid + Input: + Question1: What is the name of the performer of 'Qui de nous deux'? + Answer1: Matthieu Chedid + Doc1: "Qui de nous deux" is performed by Matthieu Chedid. + + Question2: Who is the father of Matthieu Chedid? + Answer2: Louis Chedid + Doc2: Matthieu Chedid is the son of Louis Chedid. + + Final_question: Who is the father of the performer of 'Qui de nous deux'? + Final_answer: Louis Chedid + type: "inference" + + Expected Output: + {{ + "valid": "true", + "error_type": "No Error", + "justification": "Reasoning chain is valid." + }} + + ### ✖ Invalid (bad linkage) + Input: + Question1: How many cardinals entered the papal conclave on March 31? + Answer1: 27 + Doc1: 27 cardinals entered the 1721 Papal Conclave. + + Question2: Which band did 27 open for in the Czech Republic? + Answer2: Robert Plant + Doc2: 27 is a rock band that opened for Robert Plant. + + Final_question: Which band did the cardinals who entered the papal conclave on March 31 open for in the Czech Republic? + Final_answer: Robert Plant + type: "inference" + + Expected Output: + {{ + "valid": "false", + "error_type": "bad_linkage", + "justification": "Cardinals and the rock band '27' are unrelated entities" + }} + + ### ✖ Invalid (bad linkage) + Input: + Question1: What was the deployment order date for the 16th Army to the Ukraine? + Answer1: 25 May 1941 + Doc1: The 16th Army was ordered to deploy to Ukraine on 25 May 1941. + + Question2: Which two spheres of influence were involved in the division of Europe in the 1940s? + Answer2: The Western world and the Soviet Union + Doc2: Postwar Europe was divided into the Western and Soviet spheres of influence. + + Final_question: What were the two major spheres of influence following the deployment of the 16th Army to the Ukraine in 1941? + Final_answer: The Western world and the Soviet Union + type: "inference" + + Expected Output: + {{ + "valid": "false", + "error_type": "bad_linkage", + "justification": "No causal or thematic link between army deployment date and geopolitical division" + }} + + ### ✖ Invalid (entity_false_link) + Input: + Question1: Who presents the Statewide Drive program at 107.9 ABC Ballarat? + Answer1: Nicole Chvastek + Doc1: "107.9 ABC Ballarat" has a total of 16 full time employees. A breakfast program is presented by Steve Martin from 6.15 am to 10.00 am weekdays. A mornings program is presented by Gavin McGrath from 10.00 am to 11.00 am weekdays. The regional "Statewide Drive" program (3.00 pm to 6.00 pm weekdays) is also broadcast from the Ballarat studios. It is presented by Nicole Chvastek and covers Victoria, southern New South Wales and a small part of eastern South Australia. It does not broadcast into the Melbourne metro area. 107.9 ABC Ballarat, callsign 3CRR, is an ABC Local Radio station. + + Question2: What toolkit has Nicole Joseph designed for breast care? + Answer2: Breast-CareSolutions toolkit + Doc2: Nicole Joseph introduced the global and multi-lingual breast care awareness campaign "The Gesture That Saves" in San Francisco in 2016 to 100 global peers from 40 countries during the VV100 retreat. She has designed a comprehensive Breast-CareSolutions toolkit and is currently designing a reproductive-health advocacy program. Nicole Joseph-Chin is the Chief Innovator, Founder and CEO of Ms. Brafit Limited. + + Final_question: What toolkit has the presenter of the Statewide Drive program at 107.9 ABC Ballarat designed for breast care? + Final_answer: Breast-CareSolutions toolkit + type: "inference" + + Expected Output: + {{ + "valid": "false", + "error_type": "entity_false_link", + "justification": "Nicole Chvastek and Nicole Joseph are different individuals" + }} + + ### ✖ Invalid: (trivial_concatenation) + Input: + Question1: Where was the State Normal School at Cheney located by the end of the term's first week? + Answer1: Pomeroy building + Doc1: By the end of the term's first week, the State Normal School at Cheney was located in the Pomeroy building. + + Question2: Who designed the Cheney Building? + Answer2: H. H. Richardson + Doc2: The Cheney Building was designed by H. H. Richardson. + + Final_question: Which building was used for the State Normal School at Cheney by the end of the term's first week, and who designed the Cheney Building? + Final_answer: Pomeroy building, H. H. Richardson + type: "inference" + + Expected Output: + {{ + "valid": "false", + "error_type": "trivial_concatenation", + "justification": "Final_question simply concatenates the two questions together using 'and' without needing reasoning." + }} + + The data need to be processed is as follows: + Question1: {Question1} + Answer1: {Answer1} + Doc1:{Document1} + Question2: {Question2} + Answer2: {Answer2} + Doc2:{Document2} + Final_question:{Final_question} + Final_answer:{Final_answer} + type:{qa_type} + Only return the JSON object as described. Do not include explanations unless requested. + ''' + + def build_prompt(self, Question1: str, Answer1: str, Document1: str, Question2: str, Answer2: str, Document2: str, Final_question: str, Final_answer: str, qa_type: str) -> str: + return self.prompt.format(Question1=Question1, Answer1=Answer1, Document1=Document1, Question2=Question2, Answer2=Answer2, Document2=Document2, Final_question=Final_question, Final_answer=Final_answer, qa_type=qa_type) + +@PROMPT_REGISTRY.register() +class ComparisonCheckPrompt(PromptABC): + ''' + The prompt for checking the comparison multihop question. + ''' + def __init__(self): + self.prompt = '''You are a multi-hop QA verification system. + ## Task + You are given two question-answer-document triples: + (Question1, Answer1, Doc1) and (Question2, Answer2, Doc2), plus a final multi-hop QA: + - Final_question + - Final_answer + - type: "comparison" + + Your job is to **verify whether the final QA is logically valid** according to the reasoning paths and documents. + + ## Input Fields + - Question1, Answer1, Doc1 + - Question2, Answer2, Doc2 + - Final_question, Final_answer + - type: "inference" + + ## Output Format + Return a JSON object: + {{ + "valid": "true" | "false", + "error_type": "forced_pairing" | "lacking_evidence" | "trivial_concatenation" | "other", + "justification": "Short explanation of the issue" + }} + + ## Definitions & Rules + - "comparison": Final question compares a **shared attribute/dimension** (e.g., date, numeric quantity, size) between two entities derived from QA1 and QA2. + + - "forced_pairing": The two QA-doc pairs do not share a meaningful, comparable dimension — the comparison is forced or domain-incoherent. + - "lacking_evidence": One or both compared values are not explicitly supported in the provided documents with sufficient precision to support the asserted comparison. + - "trivial_concatenation": If the final question is formed by simply joining two or more independent facts from the given QA-document pairs into a single sentence (often using "and" or similar conjunctions), without any logical comparing beyond listing the facts. + - "other": Other errors that you think are not included above. + + ## Examples + + ### ✓ Valid + Input: + Question1: When was John Beach born? + Answer1: January 1, 1812 + Doc1: Major John Beach (January 1, 1812 - August 31, 1874) was a United States Army officer during the Black Hawk and American Civil War. + + Question2: When was Seth Gordon Persons born? + Answer2: February 5, 1902 + Doc2: Seth Gordon Persons (February 5, 1902 - May 29, 1965) was an American Democratic politician and the 43rd Governor of Alabama. + + Final_question: Who was born first, John Beach or Seth Gordon Persons? + Final_answer: John Beach + type: "comparison" + + Expected Output: + {{ + "valid": "true", + "error_type": "No Error", + "justification": "Both docs provide explicit birth dates (1812 vs 1902) and John Beach is earlier." + }} + + ### ✖ Invalid (forced_pairing) + Input: + Question1: What was the renumbering date of the 17th Lancers? + Answer1: April 1763 + Doc1: The regiment was renumbered the 17th Regiment of (Light) Dragoons in April 1763. + + Question2: What year was the 67th English cricket season? + Answer2: 1763 + Doc2: The 1763 English cricket season was the 67th English cricket season. + + Final_question: Was the renumbering of the 17th Lancers in April 1763 before or during the 67th English cricket season? + Final_answer: During + type: "comparison" + + Expected Output: + {{ + "valid": "false", + "error_type": "forced_pairing", + "justification": "This forces a link between a military renumbering (point event) and a sports season (period) without a meaningful shared comparison dimension." + }} + + ### ✖ Invalid (lacking_evidence) + Input: + Question1: What year was the Cambridge Battery completed for the 100-ton gun? + Answer1: 1886 + Doc1: Cambridge Battery was ready in 1886. + + Question2: When did the 1886 United Kingdom general election take place? + Answer2: July 1-27, 1886 + Doc2: The 1886 United Kingdom general election took place from 1 July to 27 July 1886. + + Final_question: Which event occurred first, the completion of the Cambridge Battery in 1886 or the United Kingdom general election led by Charles Stewart Parnell in 1886? + Final_answer: The completion of the Cambridge Battery in 1886 + type: "comparison" + + Expected Output: + {{ + "valid": "false", + "error_type": "lacking_evidence", + "justification": "The Cambridge Battery is only dated to the year (1886), while the election records include exact dates in July. This lack of precise dating in the document makes it impossible to determine which event occurred first." + }} + + ### ✖ Invalid: (trivial_concatenation) + Input: + Question1: Where was the State Normal School at Cheney located by the end of the term's first week? + Answer1: Pomeroy building + Doc1: By the end of the term's first week, the State Normal School at Cheney was located in the Pomeroy building. + + Question2: Who designed the Cheney Building? + Answer2: H. H. Richardson + Doc2: The Cheney Building was designed by H. H. Richardson. + + Final_question: Which building was used for the State Normal School at Cheney by the end of the term's first week, and who designed the Cheney Building? + Final_answer: Pomeroy building, H. H. Richardson + type: "comparison" + + Expected Output: + {{ + "valid": "false", + "error_type": "trivial_concatenation", + "justification": "Final_question simply concatenates the two questions together using 'and' without needing reasoning." + }} + + The data need to be processed is as follows: + Question1: {Question1} + Answer1: {Answer1} + Doc1: {Document1} + Question2: {Question2} + Answer2: {Answer2} + Doc2: {Document2} + Final_question: {Final_question} + Final_answer: {Final_answer} + type: {qa_type} + Only return the JSON object as described. Do not include explanations unless requested. +''' + + def build_prompt(self, Question1: str, Answer1: str, Document1: str, Question2: str, Answer2: str, Document2: str, Final_question: str, Final_answer: str, qa_type: str) -> str: + return self.prompt.format(Question1=Question1, Answer1=Answer1, Document1=Document1, Question2=Question2, Answer2=Answer2, Document2=Document2, Final_question=Final_question, Final_answer=Final_answer, qa_type=qa_type) + +@PROMPT_REGISTRY.register() +class RefineAnswerPrompt(PromptABC): + ''' + The prompt for refining the answer. + ''' + def __init__(self): + self.prompt = '''You are an AI agent tasked with cleaning and extracting concise answers from original QA pairs. + ## Input: + You are given a **question** and its corresponding **original answer**. Your task is to extract the most precise and concise information that directly answers the question. + + ## Processing Rules: + 1. Extract **only** the exact information requested in the question. + 2. Keep the original index numbering or order if present. + 3. **Do not** omit essential information. + 4. **Never add or infer** information not explicitly stated in the original answer. + 5. Follow strict formatting conventions: + - Percentages: use format like `8%` (not "eight percent" or "8 percent") + - Currency: use `$1,000` format + - Dates: use `YYYY-MM-DD` + - Units: include units (e.g., `5kg`, `10cm`) + 6. For answers that consist of multiple parts or are comparative in nature, multiple core components and comparative statements should be included. + + ## Output Format (JSON): + For each input QA pair, output the following JSON object: + {{ + "question": "", + "original_answer": "", + "refined_answer": "" + }} + + ## Example: + Input: + question: What edition of the Wightman Cup was held in 1931? + original_answer: The 1931 Wightman Cup was its 9th edition. + + Output: + {{ + "question": "What edition of the Wightman Cup was held in 1931?", + "original_answer": "The 1931 Wightman Cup was its 9th edition.", + "refined_answer": "The 9th edition." + }} + + Input: + question: How does the percentage of individuals under age 18 living below the poverty line in Farina, Illinois compare to the statewide percentage in Illinois? + original_answer: In Farina, Illinois, 10.7% of individuals under age 18 were living below the poverty line, which is lower than the statewide percentage in Illinois of 16.1%. + + Output: + {{ + "question": "How does the percentage of individuals under age 18 living below the poverty line in Farina, Illinois compare to the statewide percentage in Illinois?", + "original_answer": "In Farina, Illinois, 10.7% of individuals under age 18 were living below the poverty line, which is lower than the statewide percentage in Illinois of 16.1%.", + "refined_answer": "10.7%, lower than the statewide percentage in Illinois of 16.1%." + }} + + The data need to be processed is as follows: + question: {question} + original_answer: {original_answer} +''' + + def build_prompt(self, question: str, original_answer: str) -> str: + return self.prompt.format(question=question, original_answer=original_answer) + +@PROMPT_REGISTRY.register() +class MoreOptionalAnswersPrompt(PromptABC): + ''' + The prompt for generating more optional answers. + ''' + def __init__(self): + self.prompt = '''You are an expert in **linguistic variation** and **data augmentation**. Your task is to generate a comprehensive list of all plausible and commonly recognized alternative expressions, formats, and aliases for a given input entity or piece of information. The goal is to create high-quality training data that captures diverse ways of referring to the same concept. + + **Key Guidelines:** + + 1. **Equivalence:** Each alternative expression must refer to *exactly the same entity or information* as the original input. Do not include broader categories, narrower sub-types, or related but distinct concepts. + 2. **Scope of Variation:** Focus on: + * Different **formatting conventions** (e.g., dates, numbers, units). + * Common **abbreviations, acronyms, or initialisms**. + * Well-known **aliases, nicknames, or shorter forms** in common usage. + * Synonyms or rephrasing should *only* be included if they are direct, commonly accepted equivalents. + 3. **Context-Agnosticism:** Unless the input itself implies a specific context, generate general-purpose variations. Avoid creating variations that are only valid in very niche or obscure contexts. + 4. **Inclusion of Original:** Always include the original input as the first item in the generated list. + 5. **Format:** Output the variations as a JSON list of strings. + + **Examples:** + + Input: 1977-01-26 + Output: ["1977-01-26", "1977 01 26", "1977.01.26", "January 26, 1977", "26 Jan 1977", "Jan 26, 1977"] + + Input: United Nations + Output: ["United Nations", "U.N.", "UN"] + + Input: 3.14159 + Output: ["3.14159", "π", "pi", "PI"] + + Input: Doctor of Philosophy + Output: ["Doctor of Philosophy", "Ph.D.", "PhD", "Doctorate"] + + Input: New York City + Output: ["New York City", "NYC", "The Big Apple"] + + Input: kilogram + Output: ["kilogram", "kg", "kilograms"] + + Input: {refined_answer} + Please list all possible textual expressions that have the same meaning or refer to the same entity, especially in different formats (e.g., dates, names, abbreviations). + Respond with a JSON list of strings. Do not explain. +''' + + def build_prompt(self, refined_answer: str) -> str: + return self.prompt.format(refined_answer=refined_answer) + +@PROMPT_REGISTRY.register() +class ReasoningPrompt(PromptABC): + ''' + The prompt for reasoning. + ''' + def __init__(self): + self.prompt = '''Please solve the following problem and return result. Ensure responses are as concise as possible, focusing only on key information while omitting redundant details. + The problem is: + {problem} +''' + + def build_prompt(self, problem: str) -> str: + return self.prompt.format(problem=problem) + +@PROMPT_REGISTRY.register() +class ComparisonReasoningPrompt(PromptABC): + ''' + The prompt for comparison question reasoning. + ''' + def __init__(self): + self.prompt = '''Please solve the following problem and return result. + For comparison question, if you are unsure of the answer, please do not guess or choose randomly. Instead, return "I cannot answer this question." + The problem is: + {problem} + Ensure responses are as concise as possible, focusing only on key information while omitting redundant details. +''' + + def build_prompt(self, problem: str) -> str: + return self.prompt.format(problem=problem) + +@PROMPT_REGISTRY.register() +class SingleHopPrompt(PromptABC): + ''' + The prompt for answer single hop question. + ''' + def __init__(self): + self.prompt = '''You are given the following document that contains relevant information to help answer a question. + Document: + {Document} + Question: + {Question} + Please answer the question using the information in the provided document. Ensure responses are as concise as possible, focusing only on key information while omitting redundant details. + If you cannot answer the question, return "I cannot answer this question. ". + ## For Example: + ### ✓ Can answer: + Document: + \"Olive Winchester\"\n1851 in Corinna, Maine; died October 2, 1892 in Yankton, South Dakota), and Sarah A. \"\"Sadie\"\" Blackstone Winchester (born May 1, 1853 in Pownal, Maine; died February 6, 1949 in Los Angeles, California). Winchester's parents were married in Portland, Maine on February 22, 1879 in the Methodist Episcopal Church. Winchester was a relative of Oliver Fisher Winchester (born November 30, 1810 in Brookline, Massachusetts; died December 11, 1880 in New Haven, Connecticut), the manufacturer and marketer of the Winchester repeating rifle. After June 25, 1880, the Winchester family left Monson, Maine and by 1881 had relocated to Forestburg, in Sanborn + Question: + When was the first woman to graduate with a Bachelor of Divinity degree from Glasgow, Olive Winchester, born? + Answer: + 1851 + + Document: + \"1996 North Indian Ocean cyclone season\"\ndue to flash flooding. Elsewhere in India, the storm killed 111 people, including 44 in Tamil Nadu where 18 boats were damaged or missing. In some areas, the rains helped end a drought. After the storm passed, the Andhra Pradesh government provided each family RS$1,000 (US$30) if their house was destroyed, and RS$100,000 (US$3,000) if they lost a family member. While the previous storm was paralleling the east Indian coastline, another disturbance formed off the west coast on June 15, also associated with the monsoon. The new area of convection persisted, developing a distinct circulation by the next day. + Question: + What is the prime factorization of the number of people killed by the storm in India during the 1996 North Indian Ocean cyclone season? + Answer: + 3 x 37 + + Document: + Seth Gordon Persons (February 5, 1902 - May 29, 1965) was an American Democratic politician who was the 43rd Governor of Alabama from 1951 to 1955. + Question: + Who was born first, John Beach (January 1, 1812 - August 31, 1874) or Seth Gordon Persons? + Answer: + John Beach + + ### ✖ Cannot answer: + Document: + The Rialto Bridge (Italian: Ponte di Rialto; Venetian: Ponte de Rialto) is the oldest of the four bridges spanning the Grand Canal in Venice, Italy. Connecting the sestieri (districts) of San Marco and San Polo, it has been rebuilt several times since its first construction as a pontoon bridge in the 12th century, and is now a significant tourist attractiojn the city. + Question: + What is the name of the famous bridge in the place where Al gran sole carico d'amore's composer worked? + Answer: + I cannot answer this question. I don’t know where the composer of Al gran sole carico d’amore has worked. + + Document: + Worst (manga) Worst is a Japanese delinquent manga series written and illustrated by Hiroshi Takahashi. It has the same setting as Takahashi's previous manga \"\"Crows\"\" and \"\"QP\"\" and revolves around a group of teenage boys who fight their way through the notorious high school, \"\"Suzuran\"\". The manga was first published by Shōnen Champion in 2002. The series is currently being serialized in Japan and has been collected into twenty-five tankōbon volumes. In North America, Digital Manga Publishing has released only three volumes, with the last graphic novel released in November 2004. The series is currently on hiatus but Digital Manga + Question: + Which of the following was critiqued as one of the worst manga, .hack//Legend of the Twilight or the manga Worst, published in 2002? + Answer: + I cannot answer this question. I don't have sufficient information about "hack/Legend of the Twilight". +''' + + def build_prompt(self, Document: str, Question: str) -> str: + return self.prompt.format(Document=Document, Question=Question) + +@PROMPT_REGISTRY.register() +class MultihopInferencePrompt(PromptABC): + ''' + The prompt for answer multihop inference question. + ''' + def __init__(self): + self.prompt = '''You are an expert at solving problems. Now you need to solve a multi-hop inference problem. + Multi-hop inference promblem: a question that requires combining information from multiple sources in a logical chain to reach an answer. + + ## For Example: + Input: + Question1: "What is the name of the performer of Qui de nous deux?" + Answer1: "Matthieu Chedid" + Supporting Document1: "'Qui de nous deux' is performed by Matthieu Chedid." + Question2: "Who is the father of Matthieu Chedid?" + Supporting Document2: "Matthieu Chedid is the son of Louis Chedid." + FinalQuestion: "Who is the father of the performer of Qui de nous deux?" + Output: + "Louis Chedid" + + ## The Example's Logic Chain (Just to help you better understand the multihop problem. Don't output something like this): + FinalQuestion:"Who is the father of the performer of Qui de nous deux?" -> Q:"What is the name of the performer of Qui de nous deux?" A:"Matthieu Chedid" -> Q:"Who is the father of Matthieu Chedid?" A:"Louis Chedid" -> FinalAnswer: "Louis Chedid" + + ## Now you are given some supporting fact to help answer a question. + {Data} + FinalQuestion: {FinalQuestion} + Now you need sole the promblem and return result. Ensure responses are as concise as possible, focusing only on key information while omitting redundant details. +''' + + def build_prompt(self, Data: str, FinalQuestion: str) -> str: + return self.prompt.format(Data=Data, FinalQuestion=FinalQuestion) + +@PROMPT_REGISTRY.register() +class MultihopComparisonPrompt(PromptABC): + ''' + The prompt for answer multihop comparison question. + ''' + def __init__(self): + self.prompt = '''You are an expert at solving problems. Now you need to solve a multi-hop comparison problem. + Multi-hop comparison promblem: a question that requires retrieving and comparing information from multiple sources to determine a relative fact. + + ## For Example: + Input: + Question1: "When was John Beach born?" + Answer1: "January 1, 1812" + Supporting Document1: "Major John Beach( January 1, 1812 - August 31, 1874) was a United States Army officer during the Black Hawk and American Civil War." + Question2: "When was Seth Gordon Persons born?" + Answer2: "February 5, 1902" + Supporting Document2: "Seth Gordon Persons( February 5, 1902 - May 29, 1965) was an American Democratic politician who was the 43rd Governor of Alabama from 1951 to 1955." + FinalQuestion: "Who was born first, John Beach or Seth Gordon Persons?" + Output: + "John Beach" + + ## The Example's Logic Chain (Just to help you better understand the multihop problem. Don't output something like this): + FinalQuestion: "Who was born first, John Beach or Seth Gordon Persons?" -> Q:"When was John Beach born?" A:"January 1, 1812" + Q:"When was Seth Gordon Persons born?" A:"February 5, 1902" -> FinalAnswer: "John Beach" + + ## Now you are given some supporting fact to help answer a question. + {Data} + FinalQuestion: {FinalQuestion} + Now you need sole the promblem and return result. Ensure responses are as concise as possible, focusing only on key information while omitting redundant details. +''' + + def build_prompt(self, Data: str, FinalQuestion: str) -> str: + return self.prompt.format(Data=Data, FinalQuestion=FinalQuestion) + +@PROMPT_REGISTRY.register() +class EssEqPrompt(PromptABC): + ''' + The prompt for llm judge. + ''' + def __init__(self): + self.prompt = '''You are an expert evaluator. Evaluate whether the OTHER ANSWER preserves **all essential information** in the GOLDEN ANSWER, **with respect to the QUESTION**. + # Scoring Criteria + - **2 points** → OTHER ANSWER is fully equivalent to the GOLDEN ANSWER. Same meaning, even if reworded or paraphrased. No missing or incorrect information. + - **1 point** → OTHER ANSWER includes ALL key information from the GOLDEN ANSWER but adds **extra non-contradictory information** that may not be strictly necessary but is still valid in context. + - **0 points** → OTHER ANSWER is **missing** critical information from the GOLDEN ANSWER or introduces **incorrect/contradictory** information, based on the QUESTION. + + Always consider what the QUESTION is asking when judging whether information is essential. + + # ✓ Positive Examples + + ## ✓ 2 points + + - Question: What year did the war end? + Golden: 1848 + Other: The year was 1848. + + - Question: Who became the first African American U.S. president? + Golden: Barack Obama + Other: Obama + + - Question: When did the battle begin? + Golden: The battle began in 1775. + Other: The conflict started in the year 1775. + + - Question: Which field of Nobel Prize did Marie Curie receive? + Golden: the Nobel Prize in Physics. + Other: Physics. + + ## ✓ 1 point + + - Question: What is the cause of death of Mercedesz Henger's father? + Golden: diabetes mellitus. + Other: Diabetes mellitus type 2. + + - Question: When did the war end? + Golden: 1848 + Other: The war ended in 1848. + + - Question: Who became the first African American U.S. president? + Golden: Barack Obama + Other: Barack Obama, the 44th president of the United States. + + - Question: Where is the Eiffel Tower located? + Golden: The Eiffel Tower is in Paris. + Other: The Eiffel Tower is in Paris, the capital of France. + + ## ✖ Negative Examples (0 points) + + - Question: How much is the price? + Golden: 50 + Other: 25 dollars + + - Question: When did the war end? + Golden: 1848 + Other: In 1846 + + - Question: Where is the Eiffel Tower located? + Golden: The Eiffel Tower is in Paris. + Other: The Eiffel Tower is in Berlin. + + - Question: Who became the first African American U.S. president? + Golden: Barack Obama + Other: Barack Obama and Abraham Lincoln were presidents during the same era. + + # Output Format: + Return ONLY JSON, no extra text. + ```json + {{ + "answer_reason": "reason for the score", + "answer_score": 0/1/2 + }} + ``` + Input: + Question: {question} + Golden answer: {golden_answer} + Other answer: {other_answer} +''' + + def build_prompt(self, question, golden_answer, other_answer) -> str: + return self.prompt.format(question=question, golden_answer=golden_answer, other_answer=other_answer) \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/chemistry.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/chemistry.py new file mode 100644 index 0000000000000000000000000000000000000000..193deeb36b7ce9551ed383aa12d5a09a5d330ebc --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/chemistry.py @@ -0,0 +1,38 @@ +from dataflow.core.prompt import PromptABC +from dataflow.utils.registry import PROMPT_REGISTRY +@PROMPT_REGISTRY.register() +class ExtractSmilesFromTextPrompt(PromptABC): + def __init__(self, prompt_template = None): + if prompt_template is None: + self.prompt_template = """Extract the monomer/small molecule information from the text and format it as a structured JSON object. + Follow these rules strictly: + 1. For each monomer/small molecule, extract: + - abbreviation: The commonly used abbreviated name + - full_name: The complete chemical name + - smiles: The SMILES notation of the molecular structure + + 2. General rules: + - Each monomer/small molecule should have a unique abbreviation + - If a monomer's information is incomplete, include only the available information + - Don't recognize polymer which have "poly" in the name as monomer + + Example output: + [ + { + "abbreviation": "4-ODA", + "full_name": "4,4′-Oxydianiline", + "smiles": "O(c1ccc(N)cc1)c2ccc(cc2)N" + }, + { + "abbreviation": "6FDA", + "full_name": "4,4'-(hexafluoroisopropylidene)diphthalic anhydride", + "smiles": "C1=CC2=C(C=C1C(C3=CC4=C(C=C3)C(=O)OC4=O)(C(F)(F)F)C(F)(F)F)C(=O)OC2=O" + } + ] + Please make sure to output pure json which can be saved into a json file, do not output like html. + """ + else: + self.prompt_template = prompt_template + def build_prompt(self, target_monomers: str) -> str: + target_prompt = "\nHere give you some monomers' abbreviation or full name, please only extract the information of these monomers. This rule have priority over the other rules. Here are the specific monomers: " + str(target_monomers) + return self.prompt_template + target_prompt \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/code.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/code.py new file mode 100644 index 0000000000000000000000000000000000000000..2d3d102ad150c8d21dbb80c0849f8ff2fc1c0f23 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/code.py @@ -0,0 +1,187 @@ +from dataflow.core.prompt import PromptABC +from dataflow.utils.registry import PROMPT_REGISTRY +''' +A collection of prompts for the code operators. +''' +@PROMPT_REGISTRY.register() +class CodeQualityEvaluatorPrompt(PromptABC): + ''' + The prompt for the code quality evaluator. + ''' + def __init__(self): + pass + + def build_prompt(self, instruction: str, code: str) -> str: + """ + Generate system prompt for code quality evaluation. + """ + prompt = ( + "You are a meticulous and critical code reviewer. Your task is to evaluate the quality of the " + "provided 'Generated Code' based on the given 'Instruction'.\n\n" + "Provide a single integer score from 1 (poor) to 10 (excellent) and brief, constructive feedback. " + "Your entire response MUST strictly follow the format below.\n\n" + "Instruction: {instruction}\n\n" + "Generated Code:\n" + "```python\n" + "{code}\n" + "```\n\n" + "Evaluation Criteria:\n" + "1. **Correctness & Completeness**: Does the code accurately and fully implement the instruction? Does it handle obvious edge cases? Are all necessary imports included (e.g., List, Dict, Optional from typing, other required modules)?\n" + "2. **Clarity & Best Practices**: Is the code clean, readable, and does it follow standard conventions (e.g., PEP 8 for Python)?\n" + "3. **Efficiency**: Is the implementation reasonably efficient for the given task?\n\n" + "Format your response EXACTLY as follows:\n" + "Score: [integer score from 1 to 10]\n" + "Feedback: [your feedback here]" + ) + return prompt.format(instruction=instruction, code=code) + +@PROMPT_REGISTRY.register() +class CodeCodeToInstructionGeneratorPrompt(PromptABC): + ''' + The prompt for the code to instruction generator. + ''' + def __init__(self): + pass + + def build_prompt(self, code: str) -> str: + """ + Generate system prompt for code to instruction generation. + """ + prompt = ( + "You are an expert programmer and a clear communicator. Your task is to analyze the " + "provided code snippet and generate a single, concise, and natural human instruction " + "that could have produced this code.\n\n" + "The instruction should be a directive, like 'Write a function that...' or 'Create a class to...'. " + "Do NOT add any explanations, comments, or markdown formatting. Output only the instruction text.\n\n" + "Code Snippet:\n" + "```\n" + "{code}\n" + "```\n\n" + "Generated Instruction:" + ) + return prompt.format(code=code) +@PROMPT_REGISTRY.register() +class CodeInstructionGeneratePrompt(PromptABC): + ''' + The prompt for generating new instructions based on few-shot examples. + ''' + def __init__(self): + pass + + def build_prompt(self, few_shot_examples) -> str: + """ + Generate prompt for creating new instructions similar to the few-shot examples. + """ + examples_text = "" + for i, example in enumerate(few_shot_examples, 1): + examples_text += f"Example {i}:\n{example['instruction']}\n\n" + + prompt = ( + "You are tasked with generating a NEW programming instruction similar in difficulty and style to the provided examples.\n\n" + "Output MUST follow EXACTLY this format (no extra text before/after):\n" + "Please provide a self-contained Python script that solves the following problem in a markdown code block\n" + "```\\n" + "[optional imports if needed]\\n" + "\\n" + "\\n" + "def function_name(...)-> ReturnType:\\n" + " \"\"\" Problem description derived from the original instruction.\\n" + " Include input/output description and constraints if any.\\n" + " Provide at least one doctest example:\\n" + " >>> function_name(example_input)\\n" + " expected_output\\n" + " \"\"\"\\n" + "```\\n" + "GIVEN EXAMPLES:\n" + f"{examples_text}" + "REQUIREMENTS:\n" + "1. Generate ONE new instruction that is similar in difficulty and complexity to the examples above\n" + "2. Make it diverse - do not simply copy or slightly modify the examples\n" + "3. The instruction should be clear, specific, and solvable\n" + "4. Maintain similar level of detail and specificity as the examples\n" + "NEW INSTRUCTION:" + ) + return prompt +@PROMPT_REGISTRY.register() +class CodeInstructionEnhancement(PromptABC): + ''' + The prompt for instruction standardization and enhancement. + Converts original instructions into a standardized format with proper Python function templates. + ''' + def __init__(self): + pass + + def build_prompt(self, instruction: str) -> str: + """ + Generate system prompt for instruction normalization. + Only require the output instruction to be about a Python function. + """ + prompt = ( + "Rewrite the ORIGINAL INSTRUCTION into a standardized English instruction + code block.\n" + "Output MUST follow EXACTLY this format (no extra text before/after):\n" + "Please provide a self-contained Python script that solves the following problem in a markdown code block\n" + "```\\n" + "[optional imports if needed]\\n" + "\\n" + "\\n" + "def function_name(...)-> ReturnType:\\n" + " \"\"\" Problem description derived from the original instruction.\\n" + " Include input/output description and constraints if any.\\n" + " Provide at least one doctest example:\\n" + " >>> function_name(example_input)\\n" + " expected_output\\n" + " \"\"\"\\n" + "```\\n" + "REQUIREMENTS:\n" + "1. The first line (sentence) must be exactly: Please provide a self-contained Python script that solves the following problem in a markdown code block\n" + "2. The code fence uses raw ``` (no language tag). Nothing outside the fence except the first sentence.\n" + "3. Inside the fence: optionally add needed imports (omit if unnecessary), then TWO blank lines, then ONE function.\n" + "4. Infer a concise snake_case function name from the original instruction.\n" + "5. Provide full type annotations for parameters and return value (use reasonable types; if uncertain use str / int / List[str] etc.).\n" + "6. The function body MUST contain ONLY the docstring (no pass, no implementation, no other statements).\n" + "7. Docstring must be English, multi-line, and include: problem description, input/output description, constraints (if any), and at least one doctest derived or plausibly inferred.\n" + "8. Do NOT add additional functions, classes, comments, blank sections, placeholders (no TODO, no ...).\n" + "9. Do NOT echo the original instruction verbatim if it contains formatting artifacts—clean it while preserving meaning.\n" + "10. Absolutely no extra explanatory text outside the specified output format.\n" + "ORIGINAL INSTRUCTION:\n{instruction}\n" + "Produce ONLY the final standardized instruction + code block per the rules." + ) + return prompt.format(instruction=instruction) +@PROMPT_REGISTRY.register() +class CodeInstructionToCodeGeneratorPrompt(PromptABC): + ''' + The prompt for the instruction to code generator. + ''' + def __init__(self): + pass + + def build_prompt(self, instruction: str) -> str: + """ + Generate system prompt for instruction to code generation. + """ + prompt = ( + "You are a world-class coding assistant. Your task is to fulfill the following request precisely. " + "Your response must contain ONLY the code that satisfies the instruction. " + "Do not add any explanations, introductory sentences, or markdown formatting like ```python ... ```.\n\n" + "Request: {instruction}\n\n" + "Generated Code:" + ) + return prompt.format(instruction=instruction) + +@PROMPT_REGISTRY.register() +class DiyCodePrompt(PromptABC): + ''' + The prompt for custom code operations. + ''' + def __init__(self, prompt_template: str): + self.prompt_template = prompt_template + + def build_prompt(self, **kwargs) -> str: + """ + Generate prompt using custom template. + """ + try: + return self.prompt_template.format(**kwargs) + except Exception as e: + # If formatting fails, return the original template + return self.prompt_template diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/core_text.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/core_text.py new file mode 100644 index 0000000000000000000000000000000000000000..fa519ad14d17bdeca5571d694839c46c010aa9ae --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/core_text.py @@ -0,0 +1,31 @@ +from dataflow.utils.registry import PROMPT_REGISTRY +from dataflow.core.prompt import PromptABC + +@PROMPT_REGISTRY.register() +class FormatStrPrompt(PromptABC): + """ + Only the f_str_template needs to be provided. + - Automatically parses the required fields from the template (self.fields) + - build_prompt(**kwargs) renders directly using kwargs + - on_missing: 'raise' | 'empty', controls behavior when fields are missing + """ + def __init__(self, f_str_template: str = "{input_text}", on_missing: str = "raise"): + self.f_str_template = f_str_template + if on_missing not in ("raise", "empty"): + raise ValueError("on_missing must be 'raise' or 'empty'") + self.on_missing = on_missing + + def build_prompt(self, need_fields, **kwargs): + # Validate missing fields + missing = [f for f in need_fields if f not in kwargs] + if missing: + if self.on_missing == "raise": + raise KeyError(f"Missing fields for prompt: {missing}") + # Lenient mode: fill missing fields with empty strings + for f in missing: + kwargs[f] = "" + + prompt = self.f_str_template + for key, value in kwargs.items(): + prompt = prompt.replace(f"{{{key}}}", str(value)) + return prompt diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/func_call.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/func_call.py new file mode 100644 index 0000000000000000000000000000000000000000..a467bafe483ee11a40ffd957575d16572dff2b34 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/func_call.py @@ -0,0 +1,522 @@ +''' +Prompts for Bottom-Up Then Top-dOwN (BUTTON) multi-turn dialogue generating pipeline. +''' +from dataflow.utils.registry import PROMPT_REGISTRY +from dataflow.core.prompt import PromptABC + +@PROMPT_REGISTRY.register() +class ExtractScenarioPrompt(PromptABC): + + def __init__(self): + pass + + def build_prompt(self, conversation): + prompt = """ + Please analyze the conversation below between a user and an + assistant bot and identify the general life scenario it + represents. Provide a concise overview of the scenario type, + such as 'booking flights' or 'ordering meals'. Avoid + mentioning specific details like numbers or items. Your + response should be a description of the scenario without + additional commentary, and should not exceed 10 words. + Conversation: + {conversation} + Concise Overview of the Scenario: + """ + return prompt.format(conversation=conversation) + +@PROMPT_REGISTRY.register() +class ExpandScenarioPrompt(PromptABC): + + def __init__(self): + pass + + def build_prompt(self, scenario): + prompt = """ + Based on the provided daily scenario, creatively generate a new + and entirely different scenario. The new scenario must meet + the following requirements: + 1. You may alter the action or subject of the original scenario. + 2. The new scenario should differ substantially from the + original. + 3. Ensure the new scenario is realistic and feasible within a + daily life context. + 4. Retain the same format as the original scenario. + 5. Limit your response to 10 words and present the new scenario + in a single sentence. + Original Scenario: + {scenario} + Modified Scenario: + """ + return prompt.format(scenario=scenario) + +@PROMPT_REGISTRY.register() +class FuncAtomicTaskGeneratePrompt(PromptABC): + + def __init__(self): + pass + + def build_prompt(self, scenario): + prompt = """ + You are training a model that can take a user's task description + or query, and available functions as input, and generate a + sequence of function calls to accomplish the task. Currently, + you are generating basic atom tasks. Given a general life + scenario as the context, please generate a basic atom task + that can be accomplished in one step. + Requirements of the task: + 1. The task should be a reasonable real life task based on the + given scenario, and can be accomplished in one step. + 2. If you mention some information, criteria or constraints in + the task, please give the details of these information, + criteria or constraints. Do not assume the model has access + to your personal information or prior knowledge, and it does + not have chance to ask you for clarification. + 3. Please give enough details and make the task description as + specific as possible, so the model can make deterministic + function calls with deterministic arguments. Do not include + any ambiguous or vague information. + 4. Do not mention specific tools or functions in the task + description, and do not propose solutions, hints, or project + outcomes. + 5. Limit the task description to 30 words, and avoid using + adjectives and ambiguous words. + Given Scenario: + {scenario} + Please give your response in one line directly, without any + extra notation or format: + """ + return prompt.format(scenario=scenario) + +@PROMPT_REGISTRY.register() +class SequentialTaskGeneratePrompt(PromptABC): + + def __init__(self): + pass + + def build_prompt(self, task): + prompt = """ + You are training a model that can take a user's task description + or query, and available functions as input, and generate a + sequence of function calls to accomplish the task. Currently, + you are generating complex tasks for model training. Given a + task, you need to add a subsequent task for this given task + to make a more complex task. + The requirements for the subsequent task are as follows: + 1. The subsequent task should use the output of the given task + as input. + 2. The subsequent can only be conducted after the given task has + been completed. + 3. The subsequent task and the given task can form a new + composition task, and composing them can make a more + complex multi-step task. + ## Examples: + ### Given Task: Give me a list of all the pets. + ### Subsequent Task: What is the most common kind of pet in the + list? + ### Composition Task: Check the most common kind of pet in the + list of all the pets. + ### Given Task: Who is author of the book "The Great Gatsby"? + ### Subsequent Task: When was the author of this book born? + ### Composition Task: When was the author of the book "The Great + Gatsby" born. + ### Given Task: Give me the flight schedule from London to + Edinburgh today. + ### Subsequent Task: Which fight has the shortest duration? + ### Composition Task: Give me the flight from London to + Edinburgh with the shortest duration according to the flight + schedule today. + ### Given Task: Retrieve the headlines of the news today from + BBC. + ### Subsequent Task: What is the sentiment of the news + respectively? + ### Composition Task: What is the sentiment of each headline in + today's news from BBC? + ### Given Task: Which team won the World Cup in 2018? + ### Subsequent Task: What is the team's captain? + ### Composition Task: Who is the captain of the team that won + the World Cup in 2018. + ## Here is the given task, please give your response following + the above format: + ### Given Task: {task} + """ + return prompt.format(task=task) + +@PROMPT_REGISTRY.register() +class ParathenSeqTaskGeneratePrompt(PromptABC): + + def __init__(self): + pass + + def build_prompt(self, task): + prompt = """ + You are training a model that can take a user's task description + or query, and available functions as input, and generate a + sequence of function calls to accomplish the task. Currently, + you are generating complex tasks for model training. Given a + task, you need to add a paralle task and a subsequent task + for this given task to make a more complex task. + The requirements for the parallel task are as follows: + 1. The parallel task should be related to the given task, and + the input should independent of the output of the given task. + 2. The parallel task can conduct at the same time as the given + task, and they can be independent of each other. + 3. The output of the given task and the parallel task can be + used together to conduct a subsequent task. + The requirements for the subsequent task are as follows: + 1. The subsequent task should use the output of the given task + and generate parallel task as input. + 2. The subsequent can only be conducted after the given task and + the parallel task have been completed. + 3. The subsequent task, the given task and the parallel task can + form a new composition task, and composing them can make a + more complex multi-step task. + ## Examples: + ### Given Task: Give me a list of all the pets. + ### Parallel Task: Find available pet food currently in the + store. + ### Subsequent Task: Check if the pet food is suitable for the + pets in the list. + ### Composition Task: Check if the pet food is suitable for the + pets in the list of all the pets. + ### Given Task: When was the author of the book "The Great + Gatsby" born. + ### Parallel Task: Find the publication date of the book "The + Great Gatsby". + ### Subsequent Task: When the book was published, how long had + it been since the author was born? + ### Composition Task: How old was the author of the book "The + Great Gatsby" when the book was published? + ### Given Task: Give me the flight schedule from London to + Edinburgh today. + ### Parallel Task: Find the every hour weather forecast in + Edinburgh today. + ### Subsequent Task: What is the weather condition when the + first flight arrives? + ### Composition Task: I am in London, and I want to know the + weather condition when the first flight arrives in Edinburgh + today. + ### Given Task: What is the sentiment of each headline in today' + s news from BBC? + ### Parallel Task: Find the sentiment of each headline in today' + s news from CNN. + ### Subsequent Task: Which news source has more positive news + today? + ### Composition Task: Compare the sentiment of each headline in + today's news from BBC and CNN, and check which news source + has more positive news. + ### Given Task: Who is the captain of the team that won the + World Cup in 2018? + ### Parallel Task: Who is the coach of the team that won the + World Cup in 2018? + ### Subsequent Task: Are the captain and the coach from the same + country? + ### Composition Task: Check if the captain and the coach of the + team that won the World Cup in 2018 are from the same country + . + ## Here is the given task, please give your response following + the above format: + ### Given Task: {task} + """ + return prompt.format(task=task) + +@PROMPT_REGISTRY.register() +class CompositionTaskFilterPrompt(PromptABC): + + def __init__(self): + pass + + def build_prompt(self, task, sub_tasks): + prompt = """ + You are an expert in task decomposition. Currently, you are + given a composition task and its potential task breakdown. + Please check if the sub-tasks can be used to complete the + composition task. + Composition task: + {task} + Potential task breakdown: + {sub_tasks} + Please check if the sub-tasks can be used to complete the + composition task. You should first give your analysis and + thinking, and finally give your conclusion (yes or no) + enclosed in , for example, yes or no: + """ + return prompt.format(task=task, sub_tasks=sub_tasks) + +@PROMPT_REGISTRY.register() +class FuncGeneratePrompt(PromptABC): + + def __init__(self): + pass + + def build_prompt(self, task, sub_tasks): + prompt = """ + You are training a model that can take a user's task description + or query, and available functions as input, and generate a + sequence of function calls to accomplish the task. Currently, + you are generating the training data for this model. + Given a composition task and its task breakdown, please + generate corresponding aviliable functions that can be used + to accomplish each sub-task, and finally the composition + task can be accomplished by calling these functions + sequentially. + ## Requirements for the functions: + 1. The functions must possess a succinct, comprehensible name + and description. + 2. The functions should not tailored for a current task, are to + be used for other future tasks as well, hence the design of + APIs should be sufficiently generalized. + 3. Avoid the recurrence of the task or its components in the + function description and name, offering a generic perspective + that can be employed across different contexts. + 4. Make every function sufficiently granular and independent, + avoiding the conflation of multiple tasks within a single + function and avert creating monolithic APIs. + 5. Consistency in terms of parameters and returns from each + function is critical. For instance, if two functions are + called sequentially, the output of the first should either + align with or constitute a part of the input for the second + function, irrespective of varying parameter terminologies. + ## Requirements for the number of functions: + 1. One sub-task may need zero, one or multiple functions to + complete it. + 2. If a sub-task is about logic, comparision, set operation or + calculation, which can be solved by large language models, + then no function is needed for this sub-task, just leave the + func_list of this sub-task empty. + ## Composition task: + {task} + ## Task breakdown: + {sub_tasks} + ## Response format: + '''json + [ + {{ + "sub_task": "a sub task from the task breakdown", + "func_list": [ + {{ + "name": "", + "description": "", + "parameters": {{ + "": {{ + "type": "", + "description": "", + ... + }}, + ... + }}, + "required": "" + "responses": {{ + "" {{ + "type": "", + "description": "" + }}, + "": {{ + "type": "", + "description": "" + }} + }} + }}, + {{ + ... + }} + ] + }} + ... + ] + ''' + ## Please respond following the format above: + """ + return prompt.format(task=task, sub_tasks=sub_tasks) + +@PROMPT_REGISTRY.register() +class ConversationUserPrompt(PromptABC): + + def __init__(self): + pass + + def build_prompt(self, task): + prompt = """ + Assume you are playing the role of a user engaging with an AI assistant in a multi-turn task-solving scenario. + Currently, your goal is to complete a predefined task, and you + are seeking the AI assistant for this purpose. + **Task** + {task} + During this conversation, you should take on an active role and + explore the AI assistant's capability to solve problems \ + within the **Task** using a series of function (tool) calls. You + should adhere to the following guidelines: + 1. Your task involves a complex task requiring multiple steps to + complete. In your initial question to the AI assistant, you + should provide a detailed explanation of the task, including + necessary information (such as potential data) that might be + needed to solve the problem. However, you should withhold + specific solution steps (e.g., avoid sequential terms like " + firstly," "secondly") and not dictate which functions (tools) + the AI should use - that is for the AI to determine. + 2. Remember, during this multi-turn dialogue, you are portraying + the role of a human user. Your questions and responses + should reflect this human aspect. All your outputs should + enclose within "" tag, for example, " ... ". + """ + return prompt.format(task=task) + +@PROMPT_REGISTRY.register() +class ConversationAssistantPrompt(PromptABC): + + def __init__(self): + pass + + def build_prompt(self, sub_task, sub_task_func): + prompt = """ + You are simulating the role of an expert in using functions (i.e + ., tools) to solve users' tasks. You already possess + knowledge on how to decompose the task into subtasks and + understand which tools to use for their resolution. + **Subtasks** + {sub_task} + **Available Functions for Subtasks** + {sub_task_func} + Please use the tools provided above to answer the question posed + by "". You must try as much as possible to use these + tools, instead of directly answering the question using your + prior knowledge. + Your response must obey the following format: + Observation: Carefully observe the user ""'s question as + well as the output of the function call (often enclosed + within the "" tag). Be sure to check for any + errors in previous outputs, as they may not always be + accurate. Enclose your observation within the "" + tag. + Thought: After observing and combining the previously listed + steps, give detailed and clear thoughts, reasonings, or + reflections, and according to the plan decide the next step. + Function Call: Name and arguments of the function call. The + function name must be same as its name in above function list + , and the arguments must obey the format required by the + function. Enclose the function call within the "" + tag. If possible, you can call multiple functions in parallel + , be sure the functions called parallelly are independent of + each other. + Final Answer: When you believe the task is complete, you may + use 'final_answer' to provide a detailed summary of the + results to give to the user, enclose the final answer within + the tag "". + Example 1 (regular function call): + User has provided two numbers - 15 and 25. + Based on user's request, we need to find the greatest + common divisor of these two numbers. We can use the function + 'find_greatest_common_divisor' to solve this problem. + [ + {{ + "name": "find_greatest_common_divisor", + "arguments": {{"num1": 15, "num2": 25}} + }} + ] + Example 2 (parallel function call): + User wants to know the weather in two cities - New + York and London. + We can use the function 'get_weather' to find the + weather in New York and London. And the call to this function + can be done in parallel. + [ + {{ + "name": "get_weather", + "arguments": {{"city": "New York"}} + }}, + {{ + "name": "get_weather", + "arguments": {{"city": "London"}} + }} + ] + Furthermore, when the user "" raises a question, you need + to provide a structured plan to solve the question (' + structured' means that the plan needs to include steps in + sequential order, such as Step 1, 2, 3, etc., or logic + processes that include loops and decision branches). The + contents of the plan can be placed in the first round + response's , and try as much as possible to follow + this plan in every subsequent function call. However, as + necessary, you may also modify the relevant plans according + to the result of the function call. + """ + return prompt.format(sub_task=sub_task, sub_task_func=sub_task_func) + +@PROMPT_REGISTRY.register() +class ConversationToolPrompt(PromptABC): + + def __init__(self): + pass + + def build_prompt(self, function): + prompt = """ + You are simulating a computer system with powerful computational + capabilities and a complete setup. You possess ample + external prior knowledge, allowing you to run any arbitrary + function and execute calls to produce results, and you never + make errors. Give a following function, you should simulate + the operation of a computer system program as closely as + possible. + **Function** + {function} + Given a function call, you should execute the function and + provide the results in JSON format. Your response should + directly provide the results in JSON format, should not + contain irrelevant information, and must enclose within "< + func_return>" tag. + ### Example of function return: + + {{ + "name": "get_weather", + "arguments": {{"city": "New York"}} + }} + + {{ + "temperature": "25C", + }} + + """ + return prompt.format(function=function) + +@PROMPT_REGISTRY.register() +class ConversationEvalPrompt(PromptABC): + + def __init__(self): + pass + + def build_prompt(self, conversation): + prompt = """ + You are a strict evaluator of function-calling dialogues. + + You will be given only the conversation content (a list of messages with role and content). + This may include tags like , , , , . + + Your task: Assign a quality score 1 to 5 based solely on the correctness and logical flow of tool usage. + + Scoring rules: + - 5 = Excellent: correct tool usage, logical sequence, arguments reasonable. + - 4 = Good: mostly correct, only minor flaws. + - 3 = Fair: noticeable problems but still somewhat usable. + - 2 = Poor: major issues, unreliable. + - 1 = Very Bad: incoherent or irrelevant tool use. + + You must output strictly in JSON format only, with no additional text. + Output format: + {{ + "score": , + "explanation": "" + }} + + Now evaluate this conversation: + + + {conversation} + + """ + return prompt.format(conversation=conversation) + \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/general_text.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/general_text.py new file mode 100644 index 0000000000000000000000000000000000000000..532570137625308362e42469db50699fc436dc83 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/general_text.py @@ -0,0 +1,1412 @@ +import random +from typing import Literal +from dataflow.utils.registry import PROMPT_REGISTRY +from dataflow.core.prompt import PromptABC +''' +A collection of prompts for the general text operator. +''' +from dataflow.utils.registry import PROMPT_REGISTRY +from dataflow.core.prompt import PromptABC + +@PROMPT_REGISTRY.register() +class Phi4QAGeneratorPrompt(PromptABC): + def __init__(self): + pass + + def build_prompt(self, content: str) -> str: + """ + Generate the LLM input prompt by inserting the raw content into the prompt template. + """ + prompt = """ + A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the questions. + Convert the following paragraph into a conversational format with multiple tags of "Question:" followed by "Answer:": + + You can only output as the given format: + Question: xxx Answer: xxx + Question: xxx Answer: xxx + Now please covert the content below. + {content} + """ + return prompt.format(content=content) + +@PROMPT_REGISTRY.register() +class SFTGeneratorSeedPrompt(PromptABC): + + def __init__(self, custom_prompt): + self.custom_prompt = custom_prompt + pass + + def build_prompt(self, content: str = "") -> str: + """ + Generate the LLM input prompt by inserting the raw content into the prompt template, + with optional custom instructions to enhance flexibility. + """ + base_prompt = """You are tasked with creating high-quality SFT data for LLM training. + Please generate one question based on the provided context, focusing on diversity, relevance, and clarity. + + Requirements: + 1. Generate exactly one distinct and well-formed question. + 2. The question must be based on the context and include enough background for clarity. + 3. Output must follow this JSON format: + {{ + "instruction": "QUESTION", + "output": "ANSWER" + }} + + Examples: + {{ + "instruction": "Can you provide a list of healthy habits to maintain a healthy lifestyle? Please format your response as an HTML page with bullet points.", + "output": "Here's an HTML page with bullet points for healthy habits:

Healthy Habits:

  • Eating a balanced diet...
" + }}, + {{ + "instruction": "How can we use Python to calculate the GCD (greatest common divisor) of five numbers and express each number in terms of the GCD?", + "output": "Here's a Python function that calculates the GCD of five numbers: def find_gcd(...) ..." + }} + + {custom_section} + + Now, based on the following context, please generate one question: + """ + + custom_section = f"Additional instruction:\n{self.custom_prompt}\n" if self.custom_prompt else "" + full_prompt = base_prompt.format(custom_section=custom_section) + + return f"<|im_start|>system\n{full_prompt}<|im_end|>\n<|im_start|>user\n{content}<|im_end|>\n<|im_start|>assistant" + + +import textwrap + +import textwrap + +@PROMPT_REGISTRY.register() +class MetaPrompt(PromptABC): + + def __init__(self, dimensions): + self.dimensions = self._format_dimensions(dimensions=dimensions) + + self.system_prompt_template = textwrap.dedent("""\ +You are an expert evaluator of text content. You will be given a single piece of text and must evaluate it across six specific dimensions listed below. Each dimension includes a description and a list of concrete examples (example_list), each labeled with a quality score. Higher scores indicate better quality. Use these examples to guide your assessment. +{dimensions_list} + +Instructions: +- Provide a clear evaluation for each of the six dimensions based on the input text. +- Each evaluation should be one short paragraph. +- Then assign an integer score from 1 to 5 for each dimension, where: + 5 = Excellent + 4 = Good + 3 = Fair + 2 = Poor + 1 = Very Poor + +- Your output should end with a **separate final line** that contains a Python-style list of six integers in this format: + [5, 4, 3, 5, 4, 5] + """) + + self.user_prompt_template = textwrap.dedent("""\ + Please analyze and evaluate the following text: + +Text: +{text} + +Your output should include: +- One paragraph of analysis for each of the six quality dimensions listed above. +- A final line with your scores in this exact format: + [score1, score2, score3, score4, score5, score6] + """) + + def _format_dimensions(self, dimensions): + formatted_list = [] + + for i, item in enumerate(dimensions, 1): + + examples_str = "\n".join([ + f'Example (Score: {ex["score"]}):\n"{ex["text"]}"\n' + for ex in item["example_list"] + ]) + block = f"""\"\"\"{i}. {item["dimension_name"]}: {item["description"]} + +{examples_str}\"\"\"""" + formatted_list.append(block) + return formatted_list + + + def build_system_prompt(self): + dimensions_text = "\n".join(self.dimensions) + return self.system_prompt_template.format(dimensions_list=dimensions_text) + + def build_prompt(self, text): + return self.user_prompt_template.format(text=text) + +@PROMPT_REGISTRY.register() +class AlpagasusPrompt(PromptABC): + def __init__(self, dimension='quality'): + self.dimension = dimension + self.system_prompt_template = """ + We would like to request your feedback on the performance of AI assistant in response to the instruction and the given input displayed following. + Instruction: {instruction} + Input: {input} + Response: {response} + """ + self.user_prompt_template = """ + Please rate according to the {dimension} of the response to the instruction and the input. Each assistant + receives a score on a scale of 0 to 5, where a higher score indicates a higher level of the {dimension}. Please + first output a single line containing the value indicating the scores. In the subsequent line, please provide a comprehensive explanation of your evaluation, avoiding any potential bias. + """ + + def build_system_prompt(self, instruction, input_text, response): + """ + 生成system prompt + """ + return self.system_prompt_template.format(instruction=instruction, input=input_text, response=response) + + def build_prompt(self): + """ + 生成user prompt + """ + return self.user_prompt_template.format(dimension=self.dimension) + +@PROMPT_REGISTRY.register() +class TreeinstructPrompt(PromptABC): + def __init__(self): + self.system_prompt_template = """ + You are an instruction rewriter. You need to parse a given user instruction into a TREE structure following Semantic Parsing in the natural language processing field. + Procedure: + step-1: Parse the old “instruction” to a TREE-1 through Semantic Parsing in the natural language processing field. + Count and return the number of nodes in TREE-1. + Old instruction: “{instruction}” + """ + + self.user_prompt_template = """ + Please count and return the number of nodes in TREE-1. This number represents the complexity of the original instruction. + Output the number in the single LAST line. You must ensure the last line is only the number of the tree, without other symbols, like ```. + For example: + 4 + """ + + def build_system_prompt(self, instruction): + """ + 根据给定的指令生成 system prompt + """ + return self.system_prompt_template.format(instruction=instruction) + + def build_prompt(self): + """ + 生成 user prompt + """ + return self.user_prompt_template + + +@PROMPT_REGISTRY.register() +class ConsistentChatPrompt(PromptABC): + def __init__(self): + self.query_intent_categories = { + "Problem Solving Interaction": [ + "From Problem Diagnosis to Solution Optimization" + ], + "Educational Interaction": [ + "From Broad Theory to Specific Scenarios", + "From Basic Concepts to Cross-Domain Connections" + ], + "Health Consultation Interaction": [ + "From Problem Diagnosis to Solution Optimization", + "From Hypothesis Testing to Substantive Discussion" + ], + "Exploratory Interaction": [ + "From Time Sequence Expansion to Explore Causes and Effects", + "From Hypothesis Testing to Substantive Discussion" + ], + "Entertainment Interaction": [ + "From Single Perspective to Multiple Perspectives", + "From Hypothesis Testing to Substantive Discussion" + ], + "Simulation Interaction": [ + "From User Needs to Solutions", + "From Broad Theory to Specific Scenarios" + ], + "Emotional Support Interaction": [ + "From Single Perspective to Multiple Perspectives", + "From User Needs to Solutions" + ], + "Information Retrieval Interaction": [ + "From Basic Concepts to Cross-Domain Connections", + "From Time Sequence Expansion to Explore Causes and Effects" + ], + "Transaction Interaction": [ + "From User Needs to Solutions", + "From Problem Diagnosis to Solution Optimization" + ] + } + self.query_topic_dict = { + "Problem Solving Interaction": [ + "Technical support for computer hardware issues", + "Home repair advice for plumbing problems", + "Planning a budget-friendly vacation", + "Fixing issues with internet connectivity", + "Setting up a smart home system", + "Solving problems with a broken washing machine", + "Troubleshooting a malfunctioning printer", + "How to repair a car engine", + "Fixing a cracked phone screen", + "Troubleshooting Wi-Fi network issues", + "Diagnosing problems with a non-responsive remote control", + "How to reset a frozen smartphone", + "Dealing with an overheating laptop", + "Replacing a broken laptop screen", + "How to upgrade computer RAM", + "Fixing a leaking faucet", + "How to unclog a kitchen sink", + "Diagnosing a noisy refrigerator", + "How to seal window drafts", + "Troubleshooting a non-working ceiling fan", + "Setting up a home office on a budget", + "Fixing a car that won’t start in cold weather", + "How to troubleshoot GPS navigation issues", + "Fixing problems with a garage door opener", + "Troubleshooting smart light bulbs that won’t connect", + "Replacing a broken door lock", + "Fixing a noisy air conditioning unit", + "Troubleshooting camera connectivity on a laptop", + "How to repair a broken headphone jack", + "Setting up a secure home Wi-Fi network", + "Replacing a smartphone battery", + "Installing a wall-mounted TV safely", + "Calibrating a smart thermostat", + "Fixing screen flickering on a monitor", + "Diagnosing strange noises from a desktop computer", + "Solving Bluetooth connection problems", + "Repairing a jammed paper shredder", + "Troubleshooting slow smartphone performance", + "How to stop water leakage under a bathroom sink", + "Installing weather stripping on doors", + "Setting up parental controls on a router", + "Fixing a dishwasher that won’t drain", + "Repairing a damaged phone charging port", + "Replacing a worn-out windshield wiper", + "How to fix a garage light that keeps flickering", + "Solving battery drain issues in electric vehicles", + "Resetting a smart TV to factory settings", + "Troubleshooting a wireless keyboard that won't connect", + "How to install a backup camera in a car" + ], + "Educational Interaction": [ + "Learning a new language online", + "Understanding the basics of physics", + "Music theory and basic chord progressions", + "The basics of machine learning and AI", + "Introduction to computer programming", + "Understanding the structure of DNA", + "Exploring the history of the Roman Empire", + "The principles of economics", + "The process of photosynthesis in plants", + "Studying the human circulatory system", + "Learning algebra and solving equations", + "The basics of chemistry and atomic structure", + "Studying world geography", + "Learning about climate change and sustainability", + "Understanding how the internet works", + "Intro to creative writing techniques", + "Basics of digital photography", + "Understanding historical timelines", + "Learning financial literacy and budgeting", + "Exploring different art movements", + "Understanding gravity and Newton’s laws", + "Learning HTML and CSS for web design", + "Exploring the solar system", + "Basics of environmental science", + "Introduction to statistics", + "Learning about the American Civil War", + "Understanding cultural anthropology", + "Exploring human anatomy", + "Learning basic sign language", + "Intro to public speaking skills", + "Introduction to ethical philosophy", + "Learning how to conduct scientific experiments", + "Studying global political systems", + "Understanding basic genetics and heredity", + "Learning how to analyze literature", + "Basics of entrepreneurship and starting a business", + "Studying ancient civilizations like Mesopotamia and Egypt", + "Introduction to psychology and behavior", + "Basics of digital citizenship and online safety", + "Understanding the water cycle and weather patterns", + "Learning how to write a research paper", + "Studying global religions and belief systems", + "Intro to logic and critical thinking", + "Understanding supply and demand in markets", + "Learning spreadsheet skills (e.g., Excel or Google Sheets)", + "Introduction to cybersecurity principles", + "Understanding different learning styles", + "Basics of health and nutrition science", + "Learning how to debate effectively" + ], + + "Health Consultation Interaction": [ + "Tips for maintaining a healthy diet", + "Analyzing symptoms of the common cold", + "Dealing with seasonal allergies", + "Understanding mental health and depression", + "Health benefits of regular exercise", + "Managing high blood pressure", + "Identifying signs of anxiety disorder", + "Dealing with insomnia and sleep problems", + "Coping with stress in the workplace", + "Understanding the impact of smoking on health", + "Preventing type 2 diabetes through lifestyle changes", + "Dealing with chronic back pain at home", + "How to support immune health naturally", + "Recognizing early signs of dehydration", + "Understanding the effects of caffeine on the body", + "Managing cholesterol through diet", + "How to build a sustainable workout routine", + "Mental health tips for remote workers", + "Safe exercises for people with joint pain", + "How to talk to a doctor about personal health concerns", + "Advice for managing menstrual cramps", + "Tips for healthy weight loss", + "Understanding the role of sleep in mental wellness", + "How to identify food intolerances", + "Preventing common sports injuries", + "Maintaining good posture while working", + "Recognizing early signs of burnout", + "How to manage asthma symptoms", + "The importance of hydration for brain function", + "Understanding the risks of sedentary lifestyles", + "Managing digestive issues like bloating or IBS", + "How to support bone health as you age", + "Tips for quitting alcohol or reducing intake", + "Understanding the benefits of mindfulness and meditation", + "Recognizing signs of vitamin deficiency", + "Safe stretching routines for flexibility", + "How to create a balanced meal plan", + "Managing migraines and chronic headaches", + "Supporting eye health in the digital age", + "Understanding how hormones affect mood and health", + "Caring for skin during seasonal changes", + "Understanding the basics of reproductive health", + "Dealing with minor injuries at home (cuts, sprains)", + "Tips for building mental resilience", + "Creating a daily self-care routine", + "Navigating food labels and nutrition facts", + "Identifying signs of eating disorders", + "How to stay active while traveling", + "The role of gut health in overall wellness" + ], + "Exploratory Interaction": [ + "Exploring the concept of time travel", + "Deep-sea exploration and underwater ecosystems", + "Historical events that shaped the world", + "The impact of artificial intelligence on society", + "Exploring the mysteries of the Bermuda Triangle", + "Investigating space exploration and Mars missions", + "The history of human migration", + "The future of renewable energy", + "The impact of global warming on biodiversity", + "Exploring the ancient pyramids of Egypt", + "Uncovering the secrets of black holes", + "The cultural significance of ancient myths", + "Exploring parallel universes and multiverse theories", + "The origins and evolution of language", + "How ancient civilizations built megastructures", + "The search for extraterrestrial life", + "How volcanoes have shaped Earth’s surface", + "The psychology of dreams and their meanings", + "The science behind natural disasters", + "Exploring the concept of simulated reality", + "How ancient trade routes influenced global development", + "Exploring lost civilizations and archaeological mysteries", + "The evolution of the internet and digital culture", + "How pandemics have influenced human history", + "The ethics of genetic modification", + "Exploring the possibility of underwater cities", + "How cultural identity evolves through migration", + "The role of philosophy in modern science", + "Unsolved mysteries in astrophysics", + "Exploring ancient astronomical observatories", + "The influence of mythologies on modern storytelling", + "How ancient weather patterns affected human settlement", + "Exploring the idea of colonizing other planets", + "The rise and fall of legendary empires", + "The possibility of time dilation in deep space travel", + "The influence of alchemy on early science", + "Understanding cryptids and mythological creatures", + "Exploring the legends of Atlantis", + "How music evolved across civilizations", + "The significance of sacred geometry in ancient structures", + "How ancient calendars predicted celestial events", + "The philosophy of consciousness and existence", + "Exploring the science behind telepathy and ESP", + "The history of espionage and intelligence gathering", + "How plagues transformed the course of empires", + "The psychology behind conspiracy theories", + "Exploring the idea of digital immortality", + "How ancient seafaring changed the world map", + "The role of chaos theory in understanding the universe" + ], + "Entertainment Interaction": [ + "Creating a video game character", + "Writing a mystery novel", + "Designing a new board game", + "Exploring a new fantasy world in literature", + "The psychology behind horror movies", + "The evolution of action films", + "Playing a strategic card game", + "Exploring the art of stand-up comedy", + "How to produce an indie film", + "Creating an engaging video game storyline", + "Writing a screenplay for a short film", + "Building a fantasy football team", + "Exploring behind-the-scenes movie production", + "Learning the basics of animation", + "Creating your own comic book series", + "Composing an original song", + "Understanding character arcs in drama series", + "Creating a YouTube channel for entertainment", + "Developing a murder mystery dinner party game", + "Exploring cosplay and costume design", + "Designing the rules for a role-playing game", + "Recording a podcast about pop culture", + "Writing a fan fiction story", + "Creating a music video on a budget", + "Directing a scene with amateur actors", + "Exploring live streaming as an entertainer", + "Hosting an online trivia night", + "Analyzing what makes a sitcom successful", + "Creating viral content for social media", + "Building a digital art portfolio for entertainment", + "Learning how to voice act for animations or games", + "Creating an interactive story with branching choices", + "Reviewing and critiquing movies or TV shows", + "Designing merchandise for a fictional brand", + "Building a fictional world map for a fantasy series", + "Creating theme music for a character or story", + "Learning stage acting vs. screen acting", + "Writing and performing a comedy skit", + "Planning a virtual concert or talent show", + "Designing a puzzle game with narrative elements", + "Writing a parody song or video", + "Hosting a fictional radio show", + "Analyzing storytelling techniques in video games", + "Developing an ARG (Alternate Reality Game)", + "Creating concept art for a fantasy setting", + "Writing dialogue for an animated series", + "Planning a short film festival with friends", + "Exploring sound design for entertainment media", + "Building a fan community around fictional works" + ], + "Simulation Interaction": [ + "Business negotiations and decision-making", + "Military strategy and planning simulations", + "Simulation for emergency disaster response", + "Flight training using simulators", + "Healthcare simulation for medical professionals", + "Simulating financial market crashes", + "Simulating environmental disaster scenarios", + "Running a simulated space mission", + "Simulating customer service interactions", + "Creating a disaster management simulation game", + "Simulating a day in the life of a CEO", + "Virtual reality driving test training", + "Crisis management simulation for public relations", + "Political campaign simulation and voter behavior", + "Simulating ethical dilemmas in AI development", + "Simulating the spread of infectious diseases", + "Urban planning simulation for smart cities", + "Simulating climate change over 100 years", + "Training simulations for cybersecurity breaches", + "Economic policy decision-making simulation", + "Simulating courtroom trials and legal strategy", + "Simulation for emergency room triage", + "Virtual surgery practice for medical students", + "Simulating supply chain disruptions", + "Simulating archaeological digs and discoveries", + "Spacewalk training in zero-gravity simulation", + "Language learning through role-playing simulation", + "Simulating diplomatic negotiations between countries", + "Astronaut survival training simulation", + "Simulating startup business pitch competitions", + "Simulating historical battles for education", + "Virtual restaurant management and customer flow simulation", + "Simulating the effects of social media algorithms", + "Driving public transportation in urban simulations", + "Simulating a courtroom debate in a mock trial", + "Disaster recovery planning for IT infrastructure", + "Simulating election outcomes based on real-time data", + "Simulation of water resource management in agriculture", + "Creating a theme park operations simulator", + "Simulating robotics navigation in dynamic environments", + "Simulated coaching for sports teams", + "Simulating ethical decision-making in journalism", + "Simulating airport ground operations and logistics", + "Simulating the development of a new pharmaceutical drug", + "Simulated investment portfolio risk management", + "Simulating refugee crisis response scenarios", + "Virtual museum curation and exhibition planning", + "Simulating interpersonal communication in therapy sessions", + "Simulating AI behavior in self-driving vehicles", + "Virtual internship simulation for workplace readiness" + ], + + "Emotional Support Interaction": [ + "Coping with the death of a loved one", + "Supporting a friend through a breakup", + "Dealing with feelings of loneliness", + "Coping with stress and work-life balance", + "Managing anxiety during uncertain times", + "Dealing with feelings of inadequacy", + "Supporting someone going through mental health challenges", + "Building resilience after a setback", + "Managing anger and frustration", + "Finding emotional support after a major life change", + "Handling the emotional impact of job loss", + "Coping with social anxiety in group settings", + "Dealing with the fear of failure", + "Recovering from a toxic relationship", + "Supporting a child through emotional distress", + "Dealing with homesickness when living abroad", + "Finding motivation during depressive episodes", + "Coping with a chronic illness diagnosis", + "Navigating emotional burnout as a caregiver", + "Overcoming feelings of rejection", + "Learning to forgive yourself after a mistake", + "Supporting a partner dealing with trauma", + "Handling the emotions of being a new parent", + "Rebuilding confidence after public embarrassment", + "Managing expectations during major life transitions", + "Dealing with guilt from past decisions", + "Helping someone through a panic attack", + "Coping with grief after a pet passes away", + "Facing loneliness during the holiday season", + "Balancing emotional vulnerability and self-protection", + "Processing emotions after a traumatic event", + "Helping teens deal with peer pressure", + "Managing jealousy in a relationship", + "Supporting an elderly parent with emotional needs", + "Navigating friendship breakups with maturity", + "Coping with fear of the future", + "Dealing with body image issues and self-worth", + "Handling emotional distance in long-term relationships", + "Managing stress related to academic pressure", + "Providing comfort to someone experiencing shame", + "Processing mixed emotions after a big achievement", + "Supporting someone with PTSD triggers", + "Coping with infertility and emotional distress", + "Rebuilding trust after betrayal", + "Helping a loved one experiencing suicidal thoughts", + "Dealing with emotional triggers in daily life", + "Finding peace with an unresolved conflict", + "Managing emotions after relocation or immigration", + "Coping with fear of abandonment" + ], + "Information Retrieval Interaction": [ + "Finding the best tech product reviews online", + "Looking up information on the latest scientific discoveries", + "How to find reliable health advice on the internet", + "Searching for a vacation destination based on reviews", + "Finding the most recent climate change data", + "Looking for historical documents on ancient civilizations", + "Researching news about artificial intelligence advancements", + "Finding user reviews for a new gadget", + "Searching for scholarly articles on quantum computing", + "Finding government reports on public health", + "Locating top-rated online courses for career development", + "Finding official information on visa requirements", + "Researching the latest trends in the stock market", + "Finding statistical data for academic research", + "Looking up real-time traffic and commute updates", + "Finding reviews and ratings for local restaurants", + "Searching for housing market reports in a specific city", + "Finding information on upcoming local events", + "Researching criminal records or public legal cases", + "Finding comparison data on different insurance policies", + "Searching for open-source software alternatives", + "Looking up case studies for business or marketing", + "Finding details on government aid programs", + "Researching side effects of prescription medications", + "Finding technical documentation for programming libraries", + "Looking up airline safety records", + "Searching for consumer complaint databases", + "Finding educational videos on historical topics", + "Researching the genealogy of a family name", + "Looking up employment law information by state", + "Finding patent information for a new invention", + "Researching cultural practices in different countries", + "Searching for reviews of online learning platforms", + "Finding data on renewable energy usage by country", + "Looking up public records on local property ownership", + "Finding historical weather data for a location", + "Searching for quotes and citations in classic literature", + "Finding nutrition information for restaurant meals", + "Researching ethical sourcing of fashion brands", + "Looking up vehicle recall history by VIN", + "Finding demographic data for a specific region", + "Researching nonprofit organization transparency reports", + "Searching for academic conference proceedings", + "Finding ratings and reviews of mobile apps", + "Looking up historical election results by district", + "Finding documentation on space exploration missions", + "Researching funding opportunities for small businesses", + "Searching for media coverage on social justice issues", + "Finding open data sets for machine learning training", + "Looking up safety information on household chemicals" + ], + "Transaction Interaction": [ + "Booking a flight online for a vacation", + "How to purchase concert tickets online", + "Making an appointment with a service provider", + "Ordering food online for delivery", + "Purchasing a product through an e-commerce site", + "How to buy insurance online", + "Scheduling a medical appointment", + "Making a donation to a charity online", + "Buying a gift card for a friend", + "How to apply for a mortgage loan", + "Renewing a vehicle registration online", + "Paying utility bills through a mobile app", + "Booking a hotel room for a weekend trip", + "Registering for an online course or certification", + "Subscribing to a streaming service", + "Buying event tickets with a digital wallet", + "Applying for a credit card through a website", + "Reserving a rental car at the airport", + "Paying property taxes online", + "Purchasing digital books or audiobooks", + "Ordering groceries from an online supermarket", + "Paying tuition fees through a university portal", + "Signing up for a gym membership online", + "Applying for unemployment benefits digitally", + "Reserving a table at a restaurant using an app", + "Buying and downloading software securely", + "Sending money internationally via online banking", + "Registering a domain and hosting a website", + "Buying stocks or cryptocurrency through a trading platform", + "Purchasing travel insurance before a trip", + "Ordering custom clothing or merchandise online", + "Buying a used car through an online marketplace", + "Paying for public transportation with a mobile wallet", + "Subscribing to a monthly subscription box service", + "Purchasing online advertising for a small business", + "Topping up a prepaid phone plan online", + "Paying for freelance services via a gig platform", + "Placing a mobile order for in-store pickup", + "Applying for a personal loan through a fintech app", + "Booking a guided tour or local experience online", + "Paying entry fees for a virtual event or webinar", + "Setting up automatic payments for monthly bills", + "Buying furniture or home goods with financing options", + "Purchasing digital game content or in-app items", + "Contributing to a crowdfunding campaign", + "Paying for parking through a mobile parking app", + "Ordering prescription medication online", + "Reserving coworking space for remote work", + "Paying for tutoring or online lessons" + ] + } + + def build_prompt(self, mode: Literal["query", "response"], num_dialogs_per_intent: int = None, topic: str = None, queries: list[str] = None) -> str: + if mode == "query": + if topic is not None or queries is not None: + raise ValueError("Topic and queries should be None when mode is query") + if num_dialogs_per_intent is None: + raise ValueError("num_dialogs_per_intent should be provided when mode is query") + prompt = """ + Task Description and Rules + 1. Generate multiple rounds of realistic user questions based on the provided topic: + - Based on a single core topic (provided directly by the user), generate multiple rounds of realistic user questions, comprising 6-8 turns in total. + - The questions should match the characteristics of real users in natural communication: sometimes simple, sometimes vague, or including contextual backgrounds, and should reflect the language style of daily communication. + - Note: Avoid directly including the exact expression of the input topic in the questions. Instead, abstract it with natural and conversational language in practical scenarios. + + 2. Dynamic Dialogue Information Flow in Conversations: Below are the relevant steps of the information flow: {info_flow} + + The dialogue style should adhere to the following requirements: + - Utilize natural phrasing and vivid language, avoiding overly mechanical responses. + - Favor shorter sentences in questions, with occasional subject omission allowed. + - Ensure smooth and logical transitions through lighthearted or entertaining interjections. + - Permit the expression of specific personality traits and individualized tones. + - Proactively introduce new topics when appropriate, ensuring relevance to the current theme. + + The dialogue should comply with the following generation rules: + - For each round of dialogue, only simulate user questions without providing answers. + - Ensure the conversation flows naturally and reflects realistic interactive thinking. + - Avoid overly polished or templated content, ensuring the questions feel authentic and relatable in life scenarios. + + Output Format: + Multi-turn Questions in JSON Format: + "category": "", + "turns": ["", "", "", "..."] + To generate multi-turn queries with high topic consistency, please think step-by-step. + The input core topic for this task is: {topic} + """ + all_query_prompts = [] + for intent, info_flows in self.query_intent_categories.items(): + for _ in range(num_dialogs_per_intent): + info_flow = random.choice(info_flows) + topic = random.choice(self.query_topic_dict[intent]) + query_prompt = prompt.format(info_flow=info_flow, topic=topic) + all_query_prompts.append(query_prompt) + return all_query_prompts + + elif mode == "response": + if topic is None or queries is None: + raise ValueError("Topic and queries should be provided when mode is response") + if num_dialogs_per_intent is not None: + raise ValueError("num_dialogs_per_intent should be None when mode is response") + prompt = f""" + Your task is to simulate a multi-turn conversation where you progressively answer a series of user questions provided under a given topic category. For each answer, focus on delivering a natural, contextually relevant, and actionable response while considering both the current question and future questions in the sequence. The goal is to ensure consistency and logical progression throughout the dialogue and to avoid unnecessary follow-up questions in the responses simultaneously. To generate multi-turn responses with high topic consistency, think step-by-step. Key Dialogue Style Requirements are as follows: + Content and Structure: + 1. Directly Answer the Current Question: + - Provide a complete, useful response to the current question without posing additional questions unless they are directly relevant to future queries. + - If clarification or additional steps are needed, frame these as suggestions or explanations rather than questions. + 2. Be Context-Aware: + - Always tailor each response to the current question while remaining mindful of the context provided by prior and future questions. + - Avoid prematurely addressing future queries but create subtle links where necessary to ensure smooth progression. + 3. Clear, Action-Oriented Responses: + - Focus on providing actionable advice, logical explanations, or troubleshooting steps rather than speculative or rhetorical remarks. + - Avoid long or overly complex explanations; aim for clarity and efficiency. + Tone and Style: + 1. Conversational and Supportive: + - Use a natural, empathetic tone that simulates real-life problem-solving interactions. + - Avoid mechanical or overly formal responses. + 2. Economical with Words: + - Keep responses concise but informative. Minimize extraneous content while ensuring answers have enough detail to be helpful. + 3. No Unnecessary Questions: + - Limit unnecessary questions in the responses and focus instead on providing actionable steps or solutions directly. Avoid follow-up questions that don’t align with the next user query. + Turn-by-Turn Instructions: + 1. Answer Exclusively for the Current Question: + - For each turn, generate an answer that directly addresses the immediate question. Avoid revisiting past details unnecessarily unless they are highly relevant. + - While you shouldn’t anticipate or directly answer future queries, your response should create natural openings for upcoming questions if applicable. + 2. Avoid Irrelevant Follow-Up Questions: + - If the immediate question doesn’t require clarification, frame your response as a statement or suggestion rather than a question. + - Maintain alignment with the logical flow of dialogue to ensure each turn is coherent. + 3. Proactively Provide Scenarios or Steps: + - Where appropriate, guide the user with specific recommendations, troubleshooting actions, or observations they can make without requiring back-and-forth clarification. + Output Requirements: + The output must simulate the conversation by only providing responses (one per turn) in a sequential manner. The final format must strictly adhere to valid JSON and include the required structure. + + The input core topic and questions-only turns for this task is: + core topic: {topic} + queries: + {', '.join([f'User query: {query}' for query in queries])} + """ + return prompt + + +@PROMPT_REGISTRY.register() +class CondorQuestionPrompt(PromptABC): + def __init__(self): + self.tag = { + "Marriage and Relationships": { + "Dating and Friendship": ["Dating Platforms", "Dating Tips", "Dating Events"], + "Marriage Management": ["Marital Relationships", "Marriage Law", "Marriage Counseling"], + "Wedding Planning": ["Wedding Planning", "Wedding Photography", "Wedding Venues"], + "Relationship Psychology": ["Relationship Psychology", "Communication Skills in Relationships", "Relationship Maintenance"], + "Emotional Counseling": ["Solving Emotional Issues", "Emotional Repair", "Emotional Growth"], + "Pre-Marriage Education": ["Pre-Marriage Preparation", "Pre-Marriage Psychology", "Pre-Marriage Legal Knowledge"] + }, + "Entertainment Gossip": { + "Celebrity News": ["Celebrity News", "Celebrity Interviews", "Celebrity Charity Events"], + "Variety Shows": ["Show Recommendations", "Behind the Scenes", "Show Interaction"], + "Film and TV Reviews": ["Movie Reviews", "TV Series Reviews", "Critics’ Opinions"], + "Entertainment News": ["Latest Entertainment News", "Entertainment Events", "Exclusive Interviews"], + "Fan Culture": ["Fan Activities", "Fan Support", "Fan Interactions"], + "Gossip": ["Celebrity Gossip", "Entertainment Industry Secrets", "Gossip Chasing"] + }, + "Artificial Intelligence": { + "Machine Learning": ["Algorithm Principles", "Application Cases", "Learning Resources"], + "Deep Learning": ["Neural Networks", "Deep Learning Frameworks", "Deep Learning Applications"], + "Natural Language Processing": ["Language Models", "Text Analysis", "Dialogue Systems"], + "Computer Vision": ["Image Recognition", "Video Processing", "Vision Algorithms"], + "Intelligent Robotics": ["Robotics Technology", "Service Robots", "Industrial Robots"], + "Autonomous Driving": ["Autonomous Driving Technology", "Autonomous Driving Regulations", "Autonomous Driving Testing"] + }, + "Healthcare": { + "Disease Prevention and Treatment": ["Common Diseases", "Preventive Measures", "Disease Treatment"], + "Health and Wellness": ["Dietary Wellness", "Exercise Wellness", "Traditional Chinese Medicine Wellness"], + "Psychological Counseling": ["Mental Health Issues", "Psychological Therapy", "Psychological Adjustment"], + "Medical Technology": ["Medical Equipment", "Medical Technology", "Medical Innovation"], + "Health Insurance": ["Types of Insurance", "Insurance Choices", "Insurance Claims"], + "Fitness": ["Fitness Methods", "Fitness Equipment", "Fitness Diet"] + }, + "Pets": { + "Pet Care": ["Daily Pet Care", "Pet Nutrition", "Pet Behavior"], + "Pet Medical Care": ["Pet Diseases", "Pet First Aid", "Pet Hospitals"], + "Pet Training": ["Basic Training", "Behavior Correction", "Training Techniques"], + "Pet Supplies": ["Toys", "Food", "Care Products"], + "Pet Adoption": ["Adoption Procedures", "Adoption Conditions", "Adoption Events"], + "Pet Activities": ["Pet Competitions", "Pet Gatherings", "Pet Festivals"] + }, + "Environment": { + "Environmental Protection": ["Ecological Protection", "Pollution Control", "Environmental Monitoring"], + "Sustainable Development": ["Green Energy", "Circular Economy", "Ecological Agriculture"], + "Energy Conservation and Emission Reduction": ["Energy-Saving Technology", "Emission Reduction Policies", "Low-Carbon Life"], + "Waste Sorting": ["Sorting Standards", "Sorting Methods", "Recycling"], + "Environmental Policies": ["Policy Regulations", "Policy Interpretation", "Policy Impact"], + "Green Living": ["Green Consumption", "Green Travel", "Green Buildings"] + }, + "Technology": { + "Internet": ["Network Technology", "Cybersecurity", "Online Services"], + "5G Communication": ["5G Technology", "5G Applications", "5G Devices"], + "Blockchain": ["Blockchain Principles", "Blockchain Applications", "Digital Currency"], + "Artificial Intelligence": ["AI Technology", "AI Ethics", "AI Industry Applications"], + "Aerospace": ["Aerospace Technology", "Aircraft", "Space Exploration"], + "New Energy": ["Solar Energy", "Wind Energy", "New Energy Vehicles", "Energy Storage"] + }, + "Education and Training": { + "Preschool Education": ["Choosing Kindergartens", "Early Childhood Education", "Preschool Education Policies"], + "K12 Education": ["Primary Education", "Secondary Education", "Family Education Guidance"], + "Higher Education": ["University Major Selection", "Graduate Education", "Higher Education Policies"], + "Vocational Training": ["Vocational Skills Training", "Professional Certifications", "Career Development Planning"], + "Online Education": ["Online Course Recommendations", "Distance Education", "Online Learning Tips"], + "Study Abroad and Immigration": ["Study Abroad Consultation", "Immigration Policies", "Overseas Living Guide"] + }, + "Career Development": { + "Career Planning": ["Career Positioning", "Career Development Paths", "Career Transition Guidance"], + "Job Search Skills": ["Resume Writing", "Interview Skills", "Job Search Channels"], + "Career Advancement": ["Promotion Strategies", "Workplace Performance", "Leadership Development"], + "Interpersonal Relationships": ["Colleague Interaction", "Workplace Communication", "Workplace Etiquette"], + "Entrepreneurship Guidance": ["Entrepreneurship Plans", "Entrepreneurship Resources", "Entrepreneurship Risk Management"], + "Team Management": ["Team Building", "Team Collaboration", "Team Performance Management"] + }, + "Finance and Investment": { + "Stocks": ["Stock Market Analysis", "Stock Investment Strategies", "Stock Research"], + "Funds": ["Fund Selection", "Systematic Investment Plans", "Fund Risk Management"], + "Futures": ["Futures Market", "Futures Trading Skills", "Futures Risk Control"], + "Foreign Exchange": ["Forex Trading", "Forex Market Analysis", "Forex Risk Management"], + "Insurance": ["Insurance Product Selection", "Insurance Planning", "Insurance Claims"], + "Financial Planning": ["Personal Finance", "Asset Allocation", "Retirement Planning"] + }, + "Real Estate and Home Living": { + "Real Estate Market": ["Market Trends", "Property Price Analysis", "Real Estate Policy Interpretation"], + "Home Buying Guide": ["Home Selection Tips", "Home Buying Process", "Mortgage Application"], + "Interior Design": ["Decorating Styles", "Decorating Materials", "Decorating Budget"], + "Home Living": ["Home Arrangement", "Home Maintenance", "Smart Homes"], + "Real Estate Policies": ["Policy Updates", "Policy Interpretation", "Policy Impact"], + "Rental Market": ["Rental Process", "Rental Agreements", "Rental Tips"] + }, + "Travel and Adventure": { + "Domestic Travel": ["Destination Recommendations", "Domestic Travel Guides", "Travel Safety"], + "International Travel": ["Visa Applications", "International Travel Guides", "Cultural Adaptation"], + "Outdoor Adventures": ["Hiking", "Mountain Climbing", "Wilderness Survival Skills"], + "Travel Guides": ["Travel Planning", "Travel Budget", "Travel Packing Lists"], + "Travel Equipment": ["Backpack Selection", "Outdoor Gear", "Travel Essentials"], + "Travel Photography": ["Photography Tips", "Travel Photography Works", "Photography Equipment Recommendations"] + }, + "Food and Cooking": { + "Food Recommendations": ["Local Delicacies", "Food Rankings", "Restaurant Recommendations"], + "Cooking Skills": ["Basic Cooking", "Creative Cooking", "Cooking Tool Usage"], + "Ingredient Selection": ["Ingredient Selection Tips", "Seasonal Ingredients", "Organic Ingredients"], + "Food Culture": ["Food Culture", "Local Food Customs", "Dietary Health"], + "Healthy Eating": ["Balanced Nutrition", "Healthy Recipes", "Dietary Wellness"], + "Baking and Desserts": ["Dessert Making", "Baking Skills", "Dessert Ingredients"] + }, + "Culture and Arts": { + "Literature": ["Literary Works", "Literary Criticism", "Creative Writing Skills"], + "Music": ["Music Styles", "Music Production", "Music Appreciation"], + "Painting": ["Painting Techniques", "Painting Schools", "Painting Appreciation"], + "Sculpture": ["Sculpture Art", "Sculpture Creation", "Sculpture Materials"], + "Theater": ["Theater Performance", "Theater Creation", "Theater History"], + "Film": ["Film Recommendations", "Film Reviews", "Film Production"] + }, + "Sports and Fitness": { + "Sports Events": ["Event Broadcasts", "Event Analysis", "Event History"], + "Fitness Methods": ["Fitness Tutorials", "Fitness Plans", "Fitness Diet"], + "Sports Equipment": ["Equipment Recommendations", "Equipment Usage", "Equipment Maintenance"], + "Sports Celebrities": ["Celebrity Introductions", "Celebrity Interviews", "Celebrity Events"], + "Sports Policies": ["Policy Interpretation", "Policy Impact", "Policy Updates"], + "Sports Industry": ["Industry Trends", "Industry Investment", "Industry Cases"] + }, + "Military and National Defense": { + "Military News": ["News Reports", "News Analysis", "Military Updates"], + "Defense Technology": ["Technology Advancements", "Technology Applications", "Innovative Technologies"], + "Weapons and Equipment": ["Equipment Introduction", "Equipment Comparison", "Equipment Maintenance"], + "Military History": ["Historical Events", "Historical Battles", "Historical Figures"], + "Military Service System": ["Service Regulations", "Enlistment Process", "Veterans' Policies"], + "National Security": ["Security Policies", "Security Education", "Security Awareness"] + }, + "Social Welfare": { + "Charity Donations": ["Donation Channels", "Donation Impact", "Donation Stories"], + "Volunteer Services": ["Service Projects", "Service Training", "Volunteer Stories"], + "Public Welfare Activities": ["Activity Organization", "Activity Participation", "Activity Impact"], + "Public Welfare Organizations": ["Organization Introductions", "Organization Activities", "Organization Cooperation"], + "Social Assistance": ["Assistance Targets", "Assistance Methods", "Assistance Policies"], + "Spreading Love": ["Spreading Methods", "Spreading Activities", "Spreading Impact"] + }, + "Automotive and Transportation": { + "Automotive News": ["New Car Releases", "Car Reviews", "Automotive Trends"], + "Driving Skills": ["Safe Driving", "Fuel-Efficient Driving", "Driver Training"], + "Vehicle Maintenance": ["Routine Maintenance", "Fault Diagnosis", "Repair Services"], + "Traffic Laws": ["Law Interpretation", "Safety Education", "Law Updates"], + "New Energy Vehicles": ["Technical Features", "Market Dynamics", "Policy Support"], + "Smart Transportation": ["Technology Applications", "Smart Systems", "Future Trends"] + }, + "E-commerce": { + "Online Shopping": ["Shopping Guides", "User Reviews", "Promotions"], + "E-commerce Operations": ["Operations Management", "Market Analysis", "Customer Service"], + "Cross-border E-commerce": ["International Logistics", "Tariff Policies", "Market Analysis"], + "E-commerce Policies": ["Policy Interpretation", "Policy Impact", "Compliance Operations"], + "E-commerce Marketing": ["Marketing Strategies", "Advertising Placement", "User Analysis"], + "E-commerce Logistics": ["Logistics Delivery", "Inventory Management", "Logistics Technology"] + }, + "Gaming and Animation": { + "Online Games": ["Popular Games", "Game Reviews", "Gaming Communities"], + "Single-player Games": ["Classic Games", "Game Guides", "Game Recommendations"], + "Animation Works": ["Popular Anime", "Anime Characters", "Anime Production"], + "Game Guides": ["Guide Sharing", "Skill Exchange", "Guide Videos"], + "Animation Industry": ["Industry Trends", "Market Analysis", "Industry Policies"], + "Game Merchandise": ["Merchandise Products", "Collecting Guides", "Merchandise Events"] + }, + "Infant and Child Education": { + "Early Education": ["Educational Philosophy", "Educational Methods", "Educational Toys"], + "Maternal and Infant Care": ["Care Knowledge", "Care Skills", "Care Products"], + "Child Psychology": ["Psychological Development", "Emotion Management", "Psychological Counseling"], + "Parent-child Relationship": ["Parent-child Activities", "Parent-child Communication", "Parent-child Education"], + "Baby Products": ["Product Selection", "Safety Standards", "Product Recommendations"], + "Child Health": ["Healthy Growth", "Nutritional Diet", "Disease Prevention"] + }, + "Senior Life": { + "Elderly Care Policies": ["Policy Interpretation", "Policy Consultation", "Policy Implementation"], + "Senior Health": ["Health Checkups", "Disease Prevention", "Healthy Eating"], + "Senior Activities": ["Cultural Activities", "Sports Activities", "Social Activities"], + "Senior Psychology": ["Psychological Adjustment", "Psychological Health", "Psychological Support"], + "Elderly Care Institutions": ["Institution Selection", "Service Quality", "Institution Evaluation"], + "Senior Products": ["Assistance Products", "Health Products", "Living Products"] + }, + "Psychological Counseling": { + "Mental Health": ["Mental Maintenance", "Mental Problem Prevention", "Mental Health Education"], + "Psychological Disorders": ["Disorder Identification", "Disorder Treatment", "Disorder Management"], + "Counseling Skills": ["Counseling Methods", "Communication Skills", "Case Studies"], + "Psychological Tests": ["Test Types", "Test Applications", "Test Interpretation"], + "Psychological Research": ["Research Trends", "Research Methods", "Research Results"], + "Psychological Guidance": ["Guidance Strategies", "Guidance Cases", "Guidance Resources"] + }, + "Religion and Belief": { + "Religious Culture": ["Cultural Traditions", "Cultural Festivals", "Cultural Influence"], + "Religious History": ["Historical Development", "Key Events", "Historical Figures"], + "Religious Art": ["Art Forms", "Art Works", "Art Value"], + "Religious Policies": ["Policy Regulations", "Policy Interpretation", "Policy Impact"], + "Religious Activities": ["Activity Organization", "Activity Participation", "Activity Significance"], + "Faith Discussions": ["Meaning of Faith", "Faith Conflicts", "Faith Diversity"] + }, + "Agriculture and Rural Development": { + "Agricultural Technology": ["Technology Applications", "Technological Innovation", "Technology Promotion"], + "Rural Development": ["Development Planning", "Development Models", "Development Cases"], + "Farmer Life": ["Life Improvement", "Quality of Life", "Living Customs"], + "Agricultural Products Market": ["Market Analysis", "Market Trends", "Market Transactions"], + "Agricultural Policies": ["Policy Support", "Policy Interpretation", "Policy Implementation"], + "Rural Tourism": ["Tourism Development", "Tourism Projects", "Tourism Experience"] + }, + "Urban Planning": { + "Urban Planning": ["Planning Philosophy", "Planning Methods", "Planning Cases"], + "Urban Design": ["Design Philosophy", "Design Elements", "Design Practice"], + "Infrastructure Development": ["Development Planning", "Development Management", "Development Technology"], + "Urban Transportation": ["Transportation Planning", "Transportation Management", "Transportation Tools"], + "Urban Greening": ["Greening Layout", "Greening Technology", "Greening Effects"], + "Protection of Historic Cities": ["Protection Policies", "Protection Measures", "Protection Cases"] + }, + "Laws and Regulations": { + "Civil Law": ["General Principles", "Property Law", "Contract Law"], + "Criminal Law": ["General Principles", "Types of Crimes", "Punishment Systems"], + "Administrative Law": ["Administrative Regulations", "Administrative Litigation", "Administrative Reconsideration"], + "Economic Law": ["Corporate Law", "Tax Law", "Intellectual Property Law"], + "International Law": ["Public International Law", "Private International Law", "International Trade Law"], + "Legal Consultation": ["Consultation Services", "Legal Aid", "Legal Education"] + }, + "Art": { + "Painting": ["Painting Techniques", "Painting Styles", "Painting Works"], + "Sculpture": ["Sculpture Materials", "Sculpture Styles", "Sculpture Creation"], + "Design": ["Design Philosophy", "Design Methods", "Design Works"], + "Photography": ["Photography Techniques", "Photography Themes", "Photography Works"], + "Calligraphy": ["Calligraphy Art", "Calligraphy Styles", "Calligraphy Works"], + "Handicrafts": ["Craft Making", "Craft Materials", "Craft Culture"] + }, + "Marketing": { + "Market Research": ["Research Methods", "Research Tools", "Research Reports"], + "Marketing Strategies": ["Strategy Formulation", "Strategy Execution", "Strategy Evaluation"], + "Brand Management": ["Brand Positioning", "Brand Promotion", "Brand Maintenance"], + "Advertising": ["Creative Advertising", "Advertising Media", "Advertising Effectiveness"], + "Public Relations": ["Event Planning", "Event Execution", "Event Evaluation"], + "Channel Development": ["Channel Expansion", "Channel Management", "Channel Optimization"] + }, + "Astronomy and Geography": { + "Astronomy": ["Astronomical Observations", "Astronomical Phenomena", "Astronomical Research"], + "Geography": ["Geographical Knowledge", "Geographical Exploration", "Geographical Education"], + "Geology": ["Geological Structure", "Geological Survey", "Geological Protection"], + "Meteorology": ["Weather Forecasting", "Weather Disasters", "Weather Services"], + "Space Exploration": ["Space Exploration", "Interstellar Travel", "Extraterrestrial Life"], + "Geographical Information Systems": ["GIS Technology", "GIS Applications", "GIS Development"] + }, + "Education and Exams": { + "College Entrance Exam Coaching": ["Preparation Strategies", "Practice Tests", "Exam Policy Interpretation"], + "Graduate School Entrance Exam Coaching": ["Preparation Planning", "Specialty Coaching", "Psychological Adjustment"], + "Civil Service Exams": ["Exam Techniques", "Essay Writing Guidance", "Interview Preparation"], + "Teaching Qualification Exams": ["Exam Process", "Interview Skills", "Teaching Ability Improvement"], + "Foreign Language Exams": ["CET-4/CET-6", "IELTS/TOEFL", "Foreign Language Speaking Training"], + "Professional Qualification Exams": ["Exam Subjects", "Career Development", "Qualification Certification"] + }, + "Cybersecurity": { + "Cybersecurity Protection": ["Protection Measures", "Security Tools", "Protection Strategies"], + "Hacker Attack and Defense": ["Attack and Defense Drills", "Security Vulnerabilities", "Hacking Techniques"], + "Data Encryption": ["Encryption Technology", "Data Protection", "Encryption Strategies"], + "Information Leak Prevention": ["Leakage Risks", "Prevention Measures", "Emergency Response"], + "Cybersecurity Policies": ["Policy Interpretation", "Regulations and Standards", "Policy Updates"], + "Cybersecurity Incidents": ["Incident Analysis", "Incident Tracking", "Incident Prevention"] + }, + "Fashion and Trends": { + "Clothing Matching": ["Everyday Outfits", "Dressing for Occasions", "Fashion Trends"], + "Beauty and Skincare": ["Skincare Knowledge", "Makeup Skills", "Beauty Products"], + "Fashion Accessories": ["Jewelry Matching", "Accessory Selection", "Trendy Accessories"], + "Trend Analysis": ["Fashion Week", "Trend Analysis", "Trend Forecasting"], + "Fashion Bloggers": ["Blogger Recommendations", "Blogger Styles", "Blogger Influence"], + "Fashion Brands": ["Brand Stories", "Brand Series", "Brand Events"] + }, + "Mental Health": { + "Emotion Management": ["Emotion Recognition", "Emotion Regulation", "Emotion Expression"], + "Stress Management": ["Stress Sources", "Stress Relief Techniques", "Stress Management"], + "Interpersonal Relationships": ["Communication Skills", "Conflict Resolution", "Social Skills"], + "Self-Awareness": ["Self-Exploration", "Self-Evaluation", "Personal Growth"], + "Psychological Adjustment": ["Adjustment Methods", "Psychological Balance", "Psychological Resilience"], + "Psychological Disorder Prevention": ["Disorder Knowledge", "Prevention Measures", "Health Promotion"] + }, + "Agricultural Technology": { + "Smart Agriculture": ["Smart Technology", "Precision Agriculture", "Agricultural Big Data"], + "Agricultural Mechanization": ["Mechanization Applications", "Technological Innovation", "Mechanization Maintenance"], + "Agricultural Product Processing": ["Processing Technology", "Product Innovation", "Quality Control"], + "Agricultural Innovation": ["Innovation Cases", "Innovation Policies", "Innovation-Driven Development"], + "Agricultural Policies": ["Policy Support", "Policy Interpretation", "Policy Implementation"], + "Agricultural Market Analysis": ["Market Trends", "Demand Analysis", "Price Fluctuations"] + }, + "Digital Products": { + "Smartphone Reviews": ["Performance Testing", "User Experience", "New Releases"], + "Computer Hardware": ["Hardware Configuration", "Hardware Upgrades", "Hardware Maintenance"], + "Digital Cameras": ["Camera Selection", "Photography Tips", "Camera Maintenance"], + "Wearable Devices": ["Device Functions", "Health Monitoring", "Smart Interactions"], + "Routers": ["Router Setup", "Signal Optimization", "Network Security"], + "Digital Accessories": ["Accessory Selection", "Device Protection", "Accessory Recommendations"] + }, + "Home Decoration": { + "Decoration Styles": ["Modern Minimalism", "Classical Chinese Style", "Luxurious European Style"], + "Decoration Materials": ["Material Selection", "Material Environmental Protection", "Material Costs"], + "Interior Design": ["Space Planning", "Furniture Selection", "Color Matching"], + "Soft Decoration": ["Curtain Selection", "Bedding Matching", "Decorative Paintings"], + "Feng Shui": ["Feng Shui Layout", "Feng Shui Taboos", "Feng Shui Improvements"], + "Renovation Construction": ["Construction Process", "Construction Supervision", "Construction Safety"] + }, + "History and Culture": { + "Chinese History": ["Ancient History", "Modern History", "History Education"], + "World History": ["Origins of Civilization", "Historical Events", "International Relations"], + "Archaeological Discoveries": ["Site Excavation", "Cultural Relic Protection", "Archaeological Techniques"], + "Historical Figures": ["Biographies", "Character Evaluations", "Historical Impact"], + "Cultural Heritage": ["Heritage Protection", "Heritage Value", "Heritage Inheritance"], + "Historical Research": ["Research Methods", "Academic Achievements", "Research Trends"] + }, + "Travel Guides": { + "Independent Travel Guides": ["Destination Recommendations", "Itinerary Planning", "Accommodation Selection"], + "Group Travel Guides": ["Tour Agency Selection", "Group Activities", "Group Travel Advantages"], + "Tourism Route Planning": ["Route Design", "Special Routes", "Theme Travel"], + "Money-Saving Travel Tips": ["Budget Planning", "Spending Guides", "Discount Information"], + "Travel Safety": ["Safety Tips", "Emergency Handling", "Insurance Selection"], + "Travel Visas": ["Visa Applications", "Visa Policies", "Visa Documentation"] + }, + "Food Sharing": { + "Recipe Sharing": ["Recipe Sharing", "Cooking Skills", "Ingredient Selection"], + "Food Recommendations": ["Special Dishes", "Local Snacks", "Restaurant Recommendations"], + "Food Exploration": ["Exploration Guides", "Shop Reviews", "Food Maps"], + "Food Photography": ["Photography Skills", "Food Presentation", "Visual Display"], + "Food Reviews": ["Dish Reviews", "Restaurant Reviews", "Ingredient Reviews"], + "Food Competitions": ["Competition Information", "Participation Guidelines", "Award-Winning Works"] + }, + "Film and Entertainment": { + "Movie Recommendations": ["New Movie Alerts", "Classic Movies", "Movie Rankings"], + "TV Series Reviews": ["Popular Drama Reviews", "Series Recommendations", "Plot Analysis"], + "Variety Show Reviews": ["Program Highlights", "Guest Performances", "Program Creativity"], + "Online Series": ["Popular Online Series", "Online Series Production", "Online Series Trends"], + "Short Videos": ["Short Video Creation", "Short Video Platforms", "Short Video Marketing"], + "Film Production": ["Production Process", "Behind the Scenes", "Production Techniques"] + }, + "Sports Activities": { + "Ball Sports": ["Football", "Basketball", "Volleyball"], + "Track and Field": ["Running", "Long Jump", "Throwing"], + "Water Sports": ["Swimming", "Rowing", "Surfing"], + "Winter Sports": ["Skiing", "Ice Skating", "Sledding"], + "Extreme Sports": ["Rock Climbing", "Skydiving", "Extreme Cycling"], + "Sports Events": ["International Events", "Domestic Events", "Local Events"] + }, + "Entrepreneurship and Investment": { + "Entrepreneurship Guidance": ["Entrepreneurship Plans", "Market Analysis", "Entrepreneurship Mindset"], + "Investment and Finance": ["Investment Strategies", "Asset Management", "Risk Control"], + "Entrepreneurship Policies": ["Policy Interpretation", "Policy Support", "Policy Utilization"], + "Entrepreneurship Cases": ["Success Stories", "Lessons Learned", "Case Analysis"], + "Venture Capital": ["Investment Opportunities", "Investment Evaluation", "Investment Negotiation"], + "Entrepreneurship Financing": ["Financing Channels", "Financing Strategies", "Financing Agreements"] + }, + "Music and Dance": { + "Music Appreciation": ["Music Styles", "Music Works", "Musicians"], + "Instrumental Performance": ["Instrument Selection", "Performance Techniques", "Instrument Maintenance"], + "Dance Performance": ["Dance Types", "Performance Techniques", "Performance Opportunities"], + "Music Production": ["Music Creation", "Music Recording", "Music Publishing"], + "Music Education": ["Education Methods", "Educational Resources", "Education Policies"], + "Dance Choreography": ["Choreography Techniques", "Choreography Creativity", "Choreography Practice"] + }, + "National Defense and Military": { + "Military Strategy": ["Strategy Analysis", "Strategy Planning", "Strategy Implementation"], + "Military Training": ["Basic Training", "Tactical Training", "Special Forces Training"], + "Weapons Development": ["Equipment Introduction", "Research and Development Updates", "Technological Innovation"], + "Military History": ["Historical Battles", "Historical Figures", "Historical Events"], + "National Defense Education": ["Educational Content", "Educational Methods", "Educational Significance"], + "Military Exercises": ["Exercise Types", "Exercise Scale", "Exercise Objectives"] + } + } + + # 任务类型(增强场景多样性,参考论文中的常见交互场景) + self.task_types = [ + "Daily Conversation", + "Creative Task", + "Role Playing", + "Problem Solving", + "Educational Explanation", + "Emotional Support", + "Information Retrieval" + ] + + def build_prompt(self, theme, domain): + """ + Generates the formatted prompt for LLM input based on the theme and domain. + + Parameters: + theme (str): The main theme of the questions. + domain (str): The domain under the given theme. + + Returns: + str: The formatted prompt for generating questions. + """ + prompt = f""" +Now we need to create high-quality SFT data for LLM training, so we need you to produce a batch of such data. You only +need to create Questions. I will give you a theme for SFT data Questions. You need to create three +Questions of different difficulty levels based on this new theme.\\ +Your Questions must meet the following requirements:\\ +1. You must strictly create only three Questions at a time. These three Questions must be in the domain of {domain} +and the Questions should align with the given theme of {theme}.\\ +2. The Questions you create must have context and sufficient information; they should not be abrupt and directly ask the +question.\\ +3. Your reply must strictly follow the format below. Your Questions need to be included between [Question Start] and +[Question End], and the difficulty level should be indicated at the beginning, as in the following format:\\ + +[Easy][Question Start]Question[Question End] + +[Medium][Question Start]Question[Question End] + +[Hard][Question Start]Question[Question End] + +4. Your Questions of different difficulty levels should be distinct and actually reflect the different levels of difficulty.\\ +\quad \\ + +Now it's your turn. Please provide the three Questions of different difficulty levels you created about the theme of {theme} for {domain}, according to the requirements. +""" + return prompt + + +@PROMPT_REGISTRY.register() +class CondorRefinePrompt(PromptABC): + + def __init__(self): + pass + + def build_prompt(self, mode: Literal["critique", "refine"], question: str = None, answer: str = None, critique: str = None): + + if mode == "critique": + if question is None or answer is None: + raise ValueError("Question and answer should be provided when mode is critique") + if critique is not None: + raise ValueError("Critique should be None when mode is critique") + dialogue = [question, answer] + base_critique_prompt = f""" +There is now a user’s question and a model’s response. You need to write a critique for this response, pointing out the +strengths and weaknesses of the model’s answer to help the model improve its response. + +Your critique must strictly adhere to the following format: + +[Critique Start] + +[Strength Start]Strength[Strength End] + +[Weakness Start]Weakness[Weakness End] + +[Suggestion Start]Suggestion[Suggestion End] + +[Critique End] + +Here is the user’s question and the model’s response: {dialogue} + +Now it’s your turn. Please provide your Critique as required: + """ + return base_critique_prompt + elif mode == "refine": + if question is None or answer is None or critique is None: + raise ValueError("Question, answer and critique should be provided when mode is refine") + base_refine_prompt = """ +Now there is a user's question, a model's answer, and the user's feedback. Please help modify the model's answer based on the user's feedback to make it better. +Your improved answer must strictly adhere to the following format: + +[Improved Answer Start]Your answer[Improved Answer End] + +Below is the user's question, the model's answer, and the feedback: +[Question Start]{question}[Question End] +[Answer Start]{answer}[Answer End] +[Feedback Start]{critique}[Feedback End] + +Now it's your turn, please provide your improved answer as required: + """ + return base_refine_prompt.format(question=question, answer=answer, critique=critique) + + +# @PROMPT_REGISTRY.register() +# class CondorRefinePrompt(PromptABC): + +# def __init__(self): +# pass + +# def build_prompt(self, question, answer, critique): +# base_refine_prompt = """ +# Now there is a user's question, a model's answer, and the user's feedback. Please help modify the model's answer based on the user's feedback to make it better. +# Your improved answer must strictly adhere to the following format: + +# [Improved Answer Start]Your answer[Improved Answer End] + +# Below is the user's question, the model's answer, and the feedback: +# [Question Start]{question}[Question End] +# [Answer Start]{answer}[Answer End] +# [Feedback Start]{critique}[Feedback End] + +# Now it's your turn, please provide your improved answer as required: +# """ +# return base_refine_prompt.format(question=question, answer=answer, critique=critique) + +@PROMPT_REGISTRY.register() +class LanguageFilterPrompt(PromptABC): + + def __init__(self): + pass + + def build_prompt(self, text): + prompt='''You are a language identification expert. Your task is to identify the language of the given text input. + + Follow these rules:You are a language identification expert. Your task is to identify the language of the given text input. + + - Respond with the ISO 639-1 two-letter language code (e.g., "en", "fr", "zh", "ar"). + - If the text contains multiple languages, identify the dominant one. + - If the language is not identifiable, respond with "Unknown". + - Do not translate or explain. Output only the language name. + + Here are some examples: + + Example 1: + Text: "Hello, how are you?" + Language: en + + Example 2: + Text: "Je suis très heureux de vous rencontrer." + Language: fr + + Example 3: + Text: "これは日本語の文です。" + Language: ja + + Example 4: + Text: "¿Dónde está la estación de tren?" + Language: es + + Example 5: + Text: "مرحبا، كيف حالك؟" + Language: ar + + Example 6: + Text: "Guten Morgen! Wie geht's dir?" + Language: de + + Example 7: + Text: "你好,我是一个程序员。" + Language: zh + + Example 8: + Text: "Привет, как дела?" + Language: ru + + Now, identify the language of the following text: + + Text: "{text}" + Language: + ''' + return prompt.format(text=text) + + + +@PROMPT_REGISTRY.register() +class SFTFromScratchGeneratorPrompt(PromptABC): + """ + Prompt for generating brand-new SFT samples from scratch. + """ + def __init__(self): + pass + + def build_prompt(self, domain_keys: str) -> str: + system_prompt = """You are a sophisticated data generation assistant specialized in creating high-quality Supervised Fine-Tuning (SFT) datasets for large language models. + +Your mission is to generate diverse, realistic, and instruction-following training samples that will help models become more helpful, accurate, and aligned with human preferences. + +## Core Principles: + +**1. Structural Excellence:** +- instruction: Clear, specific, and actionable user request +- input: Contextual information when relevant (empty string if none needed) +- output: Comprehensive, accurate, and genuinely helpful response +- domain: Single domain classification from the provided taxonomy + +**2. Quality Standards:** +- Responses must be factually accurate and demonstrate expertise +- Use natural, conversational language appropriate to the context +- Provide complete solutions that fully address the instruction +- Maintain consistency between instruction complexity and response depth +- Include relevant examples, explanations, or step-by-step guidance when beneficial + +**3. Diversity Requirements:** +- Vary instruction phrasing and complexity levels +- Mix different user personas and contexts +- Include both simple and complex scenarios within each domain +- Generate instructions that reflect real-world use cases + +**4. Safety & Ethics:** +- No harmful, illegal, discriminatory, or misleading content +- Respect privacy and avoid generating personal information +- Maintain neutrality on controversial topics +- Provide balanced perspectives when appropriate + +**5. Technical Format:** +- Output valid JSON in a single line with no formatting +- Properly escape special characters in strings +- Ensure all required fields are present and correctly typed""" + + user_prompt = f"""Generate ONE premium-quality SFT training sample as a single-line JSON object. + +## Requirements: +- **instruction**: A realistic user request that varies in style, complexity, and specificity +- **input**: Additional context when it enhances the scenario (otherwise empty string) +- **output**: A comprehensive, expert-level response that fully satisfies the instruction +- **domain**: Select the most appropriate domain from: {domain_keys} + +## Quality Checklist: +✓ Instruction is clear and represents authentic user needs +✓ Response demonstrates expertise and provides genuine value +✓ Appropriate level of detail for the complexity of the request +✓ Natural, human-like language throughout +✓ Perfect JSON formatting in a single line + +## Diversity Goals: +- Mix formal/informal language styles +- Include various difficulty levels and user contexts +- Represent different cultural perspectives when relevant +- Balance theoretical knowledge with practical applications + +## Format Example: +{{"instruction": "Create a Python function that calculates compound interest with error handling", "input": "", "output": "def compound_interest(principal, rate, time, n=1):\\n if principal <= 0 or rate < 0 or time < 0 or n <= 0:\\n raise ValueError('Invalid input: principal must be positive, rate and time non-negative, n positive')\\n return principal * (1 + rate/n)**(n*time)\\n\\n# Example usage:\\n# result = compound_interest(1000, 0.05, 2, 4)", "domain": "coding"}} + +Output only the JSON - no explanations or additional text.""" + return system_prompt + "\n\n" + user_prompt diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/kbcleaning.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/kbcleaning.py new file mode 100644 index 0000000000000000000000000000000000000000..16067fb8faafd5c9ca93c74a1a13744705707fba --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/kbcleaning.py @@ -0,0 +1,414 @@ +from dataflow.utils.registry import PROMPT_REGISTRY +from dataflow.core.prompt import PromptABC +import re +@PROMPT_REGISTRY.register() +class KnowledgeCleanerPrompt(PromptABC): + ''' + 知识清洗提示词生成器,支持中英文多语言适配 + Specialized in refining raw content with multilingual support. + ''' + def __init__(self, lang: str = "en", strict_mode: bool = True): + self.lang = lang + self.strict_mode = strict_mode + + def build_prompt(self, raw_content: str) -> str: + """生成知识清洗的思维链提示词(保持原有格式)""" + if self.lang == "en": + self.prompt_header = f""" +You are a meticulous Knowledge Refinement Engineer. Apply these rules STRICTLY: + +1. Remove redundant tags but retain: +- Semantic tags like , +- Meaningful attributes + +2. Normalize special characters: +- Standardize quotes and dashes +- Convert ellipsis (...) + +3. URL handling: +- Preserve footnote URLs +- Extract display texts + +4. Text structure: +- Maintain paragraph/list breaks +- Keep code indentation +- Limit empty lines (max=2) + +5. Reference processing (NEW): +- Images → "[Image: alt_text]" +- Signatures → "[Signature]" + +6. Code blocks: {"(strict)" if self.strict_mode else ""} +- {"Force closure" if self.strict_mode else "Preserve raw"} +- Mark fragments as /*...*/ + +7. Absolute fidelity: +- NO fact/number modifications +- NO term paraphrasing +- NO table structure changes + +8. Security Processing (NEW): +- PII: Phone/ID/Email must be masked, e.g. + Original: phone 13800138000 → Processed: phone 138****8000 +- Classified: Mark 【Confidential】as 〖SEC∶classified〗 +- Illegal: Replace sensitive content with 〖ILLEGAL∶removed〗 +- Encryption tags: Use 〖〗for encrypted sections + +Example: +Input: +
+

Knowledge Cleaning™

+
+ Cleaning Flowchart +
Fig.1: Core Process
+
+

Contact: +8613800138000

+

Text with "curly quotes" and – dash – here…

+
Table data
+
function test() {{
+
Signature: John e-signature
+

Confidential: Project budget is 【Secret】

+

Diagram:

+ + +Output: + +Knowledge Cleaning™ + +[Image: Cleaning Flowchart (Three Phases) Fig.1: Core Process] + +Contact: +86*****8000 + +Text with "straight quotes" and - dash - here... + +
Table data
+ +function test() {{ /*...*/ }} + +[Signature]Signature: John [Image: e-signature] + +〖SEC∶classified content〗 + +Diagram: [Image: Diagram demo.jpg] + +""" + else: + self.prompt_header =f""" +你是一名严谨的知识清洗工程师。请严格按照以下规则处理原始内容: + +1. 移除冗余HTML/XML标签,但保留: +- 语义化标签如 、、 +- 所有携带意义的属性值 + +2. 规范化特殊字符: +- 将花引号(“ ” ‘ ’)转为标准引号(" ") +- 将长破折号(– —)替换为短横线(-) +- 中文省略号(…)转为英文省略号(...) +- 保留数学符号和技术记号(如<<、>>等操作符) + +3. 链接处理: +- 脚注/参考文献中的URL保持原样 +- 移除超链接包装但保留显示文本 +示例:示例 → 示例 + +4. 文本结构: +- 保持原始段落/列表的换行 +- 保留代码/引用的缩进层级 +- 压缩连续空行为最多2行 + +5. 引用内容处理(新增): +- 图片引用转换为【引用图片:描述文本】 +- 签名区块标记为【签名引用】 + +6. 代码块处理:{"(严格模式)" if self.strict_mode else ""} +- {"确保代码块闭合(如补全缺失的括号)" if self.strict_mode else "保持代码原样"} +- 标记不完整代码为/*...*/ + +7. 绝对保真: +- 禁止增删任何事实、数字或命名实体 +- 禁止改写专业术语或专有名词 +- 禁止修改表格数据结构 + +8. 安全处理(新增): +- 个人隐私:身份证号/手机号/邮箱等需脱敏,示例: + 原文本:电话 13800138000 → 处理后:电话 138****8000 +- 涉密内容:检测到【机密】【秘密】等关键词时,整句替换为【涉密内容已加密】 +- 违规信息:政治敏感、暴恐等内容替换为【违规内容已屏蔽】 +- 加密标记:使用〖〗包裹加密区域,示例: + 〖PII∶身份证号〗〖SEC∶机密字段〗 + +示例: +输入: +
+

知识清洗®

+
+ 清洗流程图 +
图1:核心流程
+
+

联系电话:13800138000

+

这是包含"花引号"和—破折号—的文本…

+
表格数据
+
function test() {{
+
签名:张三 电子签名
+

机密信息:本项目预算为【机密】

+

示意图:

+ + +输出: + +知识清洗® + +[引用图片:清洗流程图(三阶段处理)图1:核心流程] + +联系电话:138****8000 + +这是包含"花引号"和-破折号-的文本... + +
表格数据
+ +function test() {{ /*...*/ }} + +[签名引用]签名:张三 [引用图片:电子签名] + +涉密内容已加密 + +示意图:[引用图片:示意图demo.jpg] + +""" + + if self.lang == "en": + processing_steps = """ +Processing Steps: +1. [Tag Analysis] Classify markup tags +2. [Reference Extraction] Isolate images/tables +3. [Character Audit] Log special chars +4. [Structure Check] Validate hierarchy +5. [Final Output] Generate cleaned text +""".strip() + output_requirement = 'Response must contain ONLY cleaned text between and .' + else: + processing_steps = """ +处理步骤: +1. [标签分析] 识别并分类所有标记标签 +2. [引用提取] 分离图片/表格/签名等引用内容 +3. [字符审核] 记录特殊字符变更 +4. [结构检查] 验证文本层级 +5. [最终输出] 生成清洗后文本 +""".strip() + output_requirement = '响应必须只包含清洗后文本,以开头,结尾,无其他内容。' + + return f""" +{self.prompt_header} + +待清洗内容: +{raw_content} + +{processing_steps} + +{output_requirement} +""".strip() + + def _post_process(self, cleaned_text: str) -> str: + """后处理逻辑(新增引用校验)""" + if self.strict_mode: + # 校验引用标记完整性 + cleaned_text = re.sub(r'(!$$.*?$$)$.+?$', + lambda m: f"【引用图片:{m.group(1)[2:-1]}" if "图片" in m.group(1) else m.group(0), + cleaned_text) + return cleaned_text + + + +@PROMPT_REGISTRY.register() +class MathbookQuestionExtractPrompt(PromptABC): + def __init__(self): + pass + + def build_prompt(self): + PROMPT = """You are given a collection of images: + +• page_n.jpg – the n-th page of a math textbook +• page_n+1.jpg – the (n+1)-th page of the same book +• index.jpg files (e.g. 1.jpg, 2.jpg, …) – all figures, diagrams or illustrations appearing on those two pages + +Your task: + +1. Extract every exercise (math problem) that has at least one line or element on page_n.jpg. You should extract the problem in its original language, do not translate it. +2. If a problem is split across page_n.jpg and page_n+1.jpg, include it in full (using page_n+1.jpg only to complete it). +3. Do not extract any problem that appears exclusively on page_n+1.jpg. +4. For each extracted problem, locate any referenced figures among the index.jpg files and insert the exact filename in ... (for example 3.jpg) at the correct place in the problem text. +5. Return all extracted problems concatenated into one string, using the literal token to separate them. For example: + PROBLEM_TEXT_1PROBLEM_TEXT_2PROBLEM_TEXT_3 +6. If no qualifying problems are found on page_n.jpg, return two consecutive spaces: "". + +Ensure that figure tags exactly match the provided image filenames and that no extra separators or punctuation are added. + """ + return PROMPT + + + # self._init_prompt_header() + +# def _init_prompt_header(self): +# """根据语言初始化提示词头部模板""" +# if self.lang == "en": +# self.prompt_header = f""" +# You are a meticulous Knowledge Refinement Engineer. Apply these rules STRICTLY: + +# 1. Remove redundant tags but retain: +# - Semantic tags like , +# - Meaningful attributes + +# 2. Normalize special characters: +# - Standardize quotes and dashes +# - Convert ellipsis (...) + +# 3. URL handling: +# - Preserve footnote URLs +# - Extract display texts + +# 4. Text structure: +# - Maintain paragraph/list breaks +# - Keep code indentation +# - Limit empty lines (max=2) + +# 5. Reference processing (NEW): +# - Images → "[Image: alt_text]" +# - Signatures → "[Signature]" + +# 6. Code blocks: {"(strict)" if self.strict_mode else ""} +# - {"Force closure" if self.strict_mode else "Preserve raw"} +# - Mark fragments as /*...*/ + +# 7. Absolute fidelity: +# - NO fact/number modifications +# - NO term paraphrasing +# - NO table structure changes + +# 8. Security Processing (NEW): +# - PII: Phone/ID/Email must be masked, e.g. +# Original: phone 13800138000 → Processed: phone 138****8000 +# - Classified: Mark 【Confidential】as 〖SEC∶classified〗 +# - Illegal: Replace sensitive content with 〖ILLEGAL∶removed〗 +# - Encryption tags: Use 〖〗for encrypted sections + +# Example: +# Input: +#
+#

Knowledge Cleaning™

+#
+# Cleaning Flowchart +#
Fig.1: Core Process
+#
+#

Contact: +8613800138000

+#

Text with "curly quotes" and – dash – here…

+#
Table data
+#
function test() {{
+#
Signature: John e-signature
+#

Confidential: Project budget is 【Secret】

+#

Diagram:

+# + +# Output: +# +# Knowledge Cleaning™ + +# [Image: Cleaning Flowchart (Three Phases) Fig.1: Core Process] + +# Contact: +86*****8000 + +# Text with "straight quotes" and - dash - here... + +#
Table data
+ +# function test() {{ /*...*/ }} + +# [Signature]Signature: John [Image: e-signature] + +# 〖SEC∶classified content〗 + +# Diagram: [Image: Diagram demo.jpg] +# +# """ +# else: +# self.prompt_header =f""" +# 你是一名严谨的知识清洗工程师。请严格按照以下规则处理原始内容: + +# 1. 移除冗余HTML/XML标签,但保留: +# - 语义化标签如 、、 +# - 所有携带意义的属性值 + +# 2. 规范化特殊字符: +# - 将花引号(“ ” ‘ ’)转为标准引号(" ") +# - 将长破折号(– —)替换为短横线(-) +# - 中文省略号(…)转为英文省略号(...) +# - 保留数学符号和技术记号(如<<、>>等操作符) + +# 3. 链接处理: +# - 脚注/参考文献中的URL保持原样 +# - 移除超链接包装但保留显示文本 +# 示例:示例 → 示例 + +# 4. 文本结构: +# - 保持原始段落/列表的换行 +# - 保留代码/引用的缩进层级 +# - 压缩连续空行为最多2行 + +# 5. 引用内容处理(新增): +# - 图片引用转换为【引用图片:描述文本】 +# - 签名区块标记为【签名引用】 + +# 6. 代码块处理:{"(严格模式)" if self.strict_mode else ""} +# - {"确保代码块闭合(如补全缺失的括号)" if self.strict_mode else "保持代码原样"} +# - 标记不完整代码为/*...*/ + +# 7. 绝对保真: +# - 禁止增删任何事实、数字或命名实体 +# - 禁止改写专业术语或专有名词 +# - 禁止修改表格数据结构 + +# 8. 安全处理(新增): +# - 个人隐私:身份证号/手机号/邮箱等需脱敏,示例: +# 原文本:电话 13800138000 → 处理后:电话 138****8000 +# - 涉密内容:检测到【机密】【秘密】等关键词时,整句替换为【涉密内容已加密】 +# - 违规信息:政治敏感、暴恐等内容替换为【违规内容已屏蔽】 +# - 加密标记:使用〖〗包裹加密区域,示例: +# 〖PII∶身份证号〗〖SEC∶机密字段〗 + +# 示例: +# 输入: +#
+#

知识清洗®

+#
+# 清洗流程图 +#
图1:核心流程
+#
+#

联系电话:13800138000

+#

这是包含"花引号"和—破折号—的文本…

+#
表格数据
+#
function test() {{
+#
签名:张三 电子签名
+#

机密信息:本项目预算为【机密】

+#

示意图:

+# + +# 输出: +# +# 知识清洗® + +# [引用图片:清洗流程图(三阶段处理)图1:核心流程] + +# 联系电话:138****8000 + +# 这是包含"花引号"和-破折号-的文本... + +#
表格数据
+ +# function test() {{ /*...*/ }} + +# [签名引用]签名:张三 [引用图片:电子签名] + +# 涉密内容已加密 + +# 示意图:[引用图片:示意图demo.jpg] +# +# """ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/model_evaluation/__pycache__/general.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/model_evaluation/__pycache__/general.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a94277b5e1172610d6bbcd320b50bb7d0f36875 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/model_evaluation/__pycache__/general.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/model_evaluation/general.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/model_evaluation/general.py new file mode 100644 index 0000000000000000000000000000000000000000..75eae22f23eb8855d4979b96ced1fb2639c0582e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/model_evaluation/general.py @@ -0,0 +1,109 @@ + +from dataflow.utils.registry import PROMPT_REGISTRY +from dataflow.core.prompt import PromptABC +''' +A collection of prompts for model evaluation. +''' + +@PROMPT_REGISTRY.register() +class AnswerJudgePrompt(PromptABC): + """ + 用于构建答案评判的提示词模板 + """ + def __init__(self): + pass + + def build_prompt(self, answer, reference_answer, question=None): + prompt = f""" + As an answer evaluation expert, please assess whether the following answer is correct. + + Reference Answer: {reference_answer} + + Current Answer: {answer} + + Please carefully analyze whether the current answer is semantically consistent with the reference answer. + Focus only on comparing the answers themselves, not on how the problem is solved. + Don't just look at the surface text, understand the essential content of the answers. + If the current answer is semantically consistent with the reference answer, even if expressed differently, it should be judged as correct. + + Please return your judgment result in JSON format: + {{"judgement_result": true}} indicates the answer is correct + {{"judgement_result": false}} indicates the answer is incorrect + + Your judgment: + """ + return prompt + +@PROMPT_REGISTRY.register() +class AnswerJudgePromptQuestion(PromptABC): + """ + 用于构建答案评判的提示词模板 + """ + def __init__(self): + pass + + def build_prompt(self, question, answer, reference_answer): + prompt = f""" + As an answer evaluation expert, please assess whether the following answer is correct. + + Question: {question} + + Reference Answer: {reference_answer} + + Current Answer: {answer} + + Please carefully analyze whether the current answer is semantically consistent with the reference answer. + Focus only on comparing the answers themselves, not on how the problem is solved. + Don't just look at the surface text, understand the essential content of the answers. + If the current answer is semantically consistent with the reference answer, even if expressed differently, it should be judged as correct. + + Please return your judgment result in JSON format: + {{"judgement_result": true}} indicates the answer is correct + {{"judgement_result": false}} indicates the answer is incorrect + + Your judgment: + """ + return prompt + +@PROMPT_REGISTRY.register() +class AnswerJudgeMultipleQuestionsPrompt(PromptABC): + """ + 用于构建答案评判的提示词模板,支持多个子问题的判断。 + """ + def __init__(self): + pass + + def build_prompt(self, answer, reference_answer, question=None): + prompt = f""" + As an answer evaluation expert, please assess whether the following answer is correct. + + Question: {question} + + Reference Answer: {reference_answer} + + Current Answer: {answer} + + Please carefully analyze whether the current answer is semantically consistent with the reference answer. + Focus only on comparing the answers themselves, not on how the problem is solved. + Don't just look at the surface text, understand the essential content of the answers. + If the current answer is semantically consistent with the reference answer, even if expressed differently, it should be judged as correct. + + The question may contain multiple sub-questions (e.g., ①②③ or (a)(b), etc.). + You should first identify the sub-questions in the question, then evaluate the correctness of each corresponding part in the current answer. + You need to provide your reason for each sub-question's judgment. + + Your judgement should be a JSON array, where each element is "true" or "false" (use string instead of boolean), indicating whether the answer to each sub-question is correct. + If there is only one question, also return a single-element array. + + If the reference answer is incomplete so that you are not able to judge some subquestions, mark the corresponding sub-questions as "empty". + + Example: + Question: ① 1+2=? ② What is 2+2? ③ What is 3+3? + Reference Answer: ① 3 ③ 6 + Current Answer: ① Three ② Four ③ Seven + Output: {{"reason": "The answer to sub-question 1 is correct as 'Three' is semantically consistent with '3'. The reference answer does not provide information for sub-question 2, so it is marked as 'empty'. The answer to sub-question 3 is incorrect as 'Seven' is not semantically consistent with '6'.", "judgement": ["true", "empty", "false"]}} + + + Your judgment: + """ + return prompt \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/pdf2vqa.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/pdf2vqa.py new file mode 100644 index 0000000000000000000000000000000000000000..42d29d6218310f28aba80ce3038410df4c50d191 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/pdf2vqa.py @@ -0,0 +1,161 @@ +from dataflow.utils.registry import PROMPT_REGISTRY +from dataflow.core.prompt import PromptABC + +@PROMPT_REGISTRY.register() +class VQAExtractPrompt(PromptABC): + def __init__(self): + pass + + def build_prompt(self, example_title, subject: str = "math", interleaved=True) -> str: + PROMPT = "" + if interleaved: + PROMPT = f""" + You are an expert in {subject} competition. You are given an image—page_n—annotated with detected bounding boxes and corresponding labels. Your task is to extract from page_n only: +1. All {subject} problems whose text begins on page_n and the answers with solutions to those problems. +2. If the problem or answer is not complete (because they continue onto page_n+1), omit them. If the problem is complete but the solution not, omit both the problem and the solution. DO NOT INCLUDE INCOMPLETE PROBLEMS OR ANSWERS. However, if only the solution is incomplete, you may still include the question and the short answer if they are complete and leave the solution empty. +3. Normally, a box at the beginning of a page with no problem number (such as "1.1", "例 1", "example 1", "解", "solution", "答案", "answer") is the continuation of the problem or solution from the previous page, even if it appears to be an independent paragraph. Omit them. +4. The chapter information as it appears on page_n. YOU MUST INCLUDE ALL TITLES APPEARING ON THE PAGE, EVEN IF NO QUESTIONS OR ANSWERS ARE PRESENT UNDER THAT TITLE. +""" + else: + PROMPT = f""" + You are an expert in {subject} competition. You are given an image—page_n—annotated with detected bounding boxes and corresponding labels. Your task is to extract from page_n only: +1. All {subject} problems whose text appears on page_n. In the provided page, there will be all questions or all answers with solutions, but not mixed. +2. If the problem or answer is not complete (because they continue onto page_n+1), omit them. DO NOT INCLUDE INCOMPLETE QUESTIONS OR ANSWERS. However, if only the solution is incomplete, you may still include the question and the short answer (sometimes only a letter or number) if they are complete and leave the solution empty. +3. Normally, a box at the beginning of a page with no problem number (such as "1.1", "例 1", "example 1", "解", "solution", "答案", "answer") is the continuation of the problem or solution from the previous page, even if it appears to be an independent paragraph. Omit them. +4. The chapter information as it appears on page_n. YOU MUST INCLUDE ALL TITLES APPEARING ON THE PAGE, EVEN IF NO QUESTIONS OR ANSWERS ARE PRESENT UNDER THAT TITLE. +""" + PROMPT +=f""" +When provided two column pages, you should read from **left to right**, top to bottom. Also output the extracted content from **left to right**, top to bottom. +Strict extraction rules: +** About questions and answers/solutions ** +- If you think the page is not the main text page, such as a cover page, catalog page, header/footer only, etc., output ``. +- Preserve each problem’s original label/number, such as "例1", "Example 3", "习题1", "11". Do not include the period after the number. Use Arabic numerals only. For example, if the label is "例一", convert it to "例1". If the label is "IV", convert it to "4". If the full label is "三、16", keep only "16". +- If there are multiple sub-questions under one main question, always put them together in the same ``…`` block. +- If a question and its answer/solution are contiguous on page_n, wrap them together as a single ``…`` block, e.g.: + `………` +- If only questions or only answers with solutions appear on page_n, wrap each question or answer with solution in a ``…`` block with the missing part left empty. For example, if only questions appear: + `…` +- If multiple questions and solutions appear on page_n, wrap each question/solution pair in its own ``…`` block. +- Sometimes a short answer may appear before the full solution. If you do not see the full solution on page_n, only extract the short answer and leave the solution empty. +** About chapter/section titles ** +- Enclose the output in a ``…`` block, where MAIN_TITLE is the chapter title or section title appearing on page_n. +- There could be multiple ``…`` blocks if multiple chapters/sections appear on page_n. +- Extract chapter titles only, and with no prefix number. For example, "{example_title}", please strictly follow this example title. If you see multiple titles piled together, use the one at the bottom only. +- **Do not keep subtitles. Any titles followed by a question/answer whose label is not 1 should be considered a subtitle. DO NOT EXTRACT THEM.** +- If you encounter a title with no problems or answers on the page, still extract the title within the ``…`` block, with an empty qa_pair block with label 0 ``. Normally this will happen when the title is at the end of the page. +- Do not use nested titles. +- Leave the title blank if there is no chapter title of the questions. +- Sometimes the chapter title may not appear at the beginning of the page. You should leave the title of all the qa pairs before the chapter title **blank**, but the title of the qa pairs after the chapter title should use this chapter title. +** About text and figures/diagrams ** +- For problem and answer/solution text, output exactly what appears (no translation). Render all mathematical expressions in LaTeX. +- Whenever the question or answer/solution refers to a figure or diagram, record it with `tagA:boxB`, such as `tag5:box7`. tagA:boxB is labeled (in exactly the same format) in the image beside the figure or diagram in RED color. Be careful that the original caption of the book may also exist, but usually in format A.B (normally in black color). Do NOT use the original caption in the book!!! Additionally, the figure/diagram may be surrounded by multiple labels (some from other boxes), be careful to pick the correct one. The correct one will be at the upper left of the figure/diagram. If you are not sure, you are free to put multiple labels, e.g. `tag5:box7 tag5:box8`. NEVER leave it blank or make up a label! +- You should always put the `...` tag at the exact position where the figure/diagram is referenced in the text. If there are multiple references, put multiple tags at the correct positions. + +If no qualifying content is found, output: + + +Output format (all tags run together, no extra whitespace or newlines except between entries): +MAIN_TITLE +QUESTION_TEXT…… +ANSWER_TEXT……SOLUTION_TEXT +QUESTION_TEXT…… +ANSWER_TEXT…… + +MAIN_TITLE +QUESTION_TEXT…… +ANSWER_TEXT……SOLUTION_TEXT + + + +Example: +Chapter 2 +Calculate \(x\) such that \(x^2-1=0\).tag5:box7 +\(x=\pm1\).SOLUTION_TEXT +Calculate \(x\) such that \(x^2-4=0\).tag5:box8 +\(x=\pm2\). + +Chapter 3 +Calculate \(x\) such that \(x^3-1=0\).tag6:box7 +\(x=1\).SOLUTION_TEXT + +Chapter 4 + + + +Please now process the provided page_n image and output your result. +""" + return PROMPT + + +@PROMPT_REGISTRY.register() +class QAExtractPrompt(PromptABC): + def __init__(self): + pass + + def build_prompt(self) -> str: + PROMPT = f""" + You are an expert in answer college-level questions. You are given a json file. Your task is to segment the content, insert images tags, and extract labels: +1. Every json item has an "id" field. Your main task is to output this field. +2. You need to segment the content into multiple ``…`` blocks, each containing a question and its corresponding answer with solution. +3. If the problem or answer/solution is not complete, omit them. An answer/solution should be considered complete as long as either the answer or solution exists. +4. You need to put the images id into proper positions. You could look at the caption or context to decide where to put the image tags. +5. You will also need to extract the chapter title and each problem's label/number from the text. +6. You only need to output "id" field for **chapter titles, questions and solutions**. DO NOT OUTPUT ORIGINAL TEXT. Use ',' to separate different ids. +7. However, use original labels/numbers for labels, and use original numbers for answers. DO NOT output "id" field for labels and answers. You will need to extract them from the text. +""" + PROMPT +=f""" +Strict extraction rules: +** About questions and answers/solutions ** +- Preserve each problem’s original label/number, such as "例1", "Example 3", "习题1", "11". Do not include the period after the number. Use Arabic numerals only. For example, if the label is "例一", convert it to "例1". If the label is "IV", convert it to "4". +- If the full label is "三、16", keep only "16". If the full label is "5.4", keep only "4". +- If there are multiple sub-questions (such as "(1)", "(a)") under one main question, always put them together in the same ``…`` block. +- If a question and its answer/solution are contiguous, wrap them together as a single ``…`` block, e.g.: + `………` +- If a question and its answer/solution are NOT contiguous (e.g. only question; only answer and/or solution; all questions at the front and all answers/solutions at the back), wrap each question or answer/solution in a ``…`` block with the missing part left empty. For example, if only questions appear: + `…` +- In total, there are 7 possibilities: only question, only answer, only solution, question with answer, question with solution, answer with solution, full question and answer and solution. +- If multiple qa pairs appear, wrap each qa pair in its own ``…`` block. +- If you do not see the full solution, only extract the short answer and leave the solution empty. YOU MUST KEEP SHORT ANSWERS !!! +** About chapter/section titles ** +- Always enclose qa pairs in a ``…`` block, where MAIN_TITLE_ID is the id of the chapter title or section title. +- Normally, chapter/section titles appear before the questions/answers in an independent json item. +- There could be multiple ``…`` blocks if multiple chapters/sections exist. +- **Any title followed by a question/answer whose label/number is not 1, or title with a score such as "一、选择题(每题1分,共10分)", should NOT be extracted.** +- Do not use nested titles. +- Leave the title blank if there is no chapter title. +** About figures/diagrams ** +- Whenever the question or answer/solution refers to a figure or diagram, record its "id" in question/answer/solution just like other text content. +- You MUST include all images referenced in the question/answer/solution. + + +If no qualifying content is found, output: + + +Output format (all tags run together, no extra whitespace or newlines except between entries): +MAIN_TITLE_ID +QUESTION_IDS +ANSWER(EXTRACTED FROM SOLUTION)SOLUTION_IDS +QUESTION_IDS +ANSWER(EXTRACTED FROM SOLUTION) + +MAIN_TITLE_ID +QUESTION_IDS +ANSWER(EXTRACTED FROM SOLUTION)SOLUTION_IDS + + + +Example: +7 +2,3 +Yes5,6,7 +8,9,10 +3.14 + +12 + +2^616 + + +Please now process the provided json and output your result. +""" + return PROMPT \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/reasoning/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/reasoning/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1dfb23eb3477cc69a9a4af254079717dcbdc11ab --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/reasoning/__init__.py @@ -0,0 +1,3 @@ +from .diy import * +from .general import * +from .math import * \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/reasoning/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/reasoning/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4630aa9a28fb8df1679af3baeba1f85bdeb5139 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/reasoning/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/reasoning/__pycache__/diy.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/reasoning/__pycache__/diy.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50c7413715cf686406ab38cc99113e7433ac905e Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/reasoning/__pycache__/diy.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/reasoning/__pycache__/general.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/reasoning/__pycache__/general.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43af7c57c445d674c5286709b1460110e356d6ed Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/reasoning/__pycache__/general.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/reasoning/__pycache__/math.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/reasoning/__pycache__/math.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..086f7cbc12b7fc258a06db0cb1514fb2841ea9a1 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/reasoning/__pycache__/math.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/reasoning/diy.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/reasoning/diy.py new file mode 100644 index 0000000000000000000000000000000000000000..cd1adbdb11d38d48746365f3df59e3284c6becd8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/reasoning/diy.py @@ -0,0 +1,41 @@ +from dataflow import get_logger +from dataflow.utils.registry import PROMPT_REGISTRY +from dataflow.core.prompt import PromptABC +''' +A collection of prompts for the diy reasoning operator. +''' +@PROMPT_REGISTRY.register() +class DiyAnswerGeneratorPrompt(PromptABC): + def __init__(self, prompt_template): + self.prompt_template = prompt_template + self.logger = get_logger() + + def build_prompt(self, question: str) -> str: + try: + return self.prompt_template + question + r'''Your response must start directly with "Solution:" without any preamble. Finish your response immediately after the solution.''' + except Exception: + self.logger.debug(f"Please check if the symbol {{question}} in prompt is missing.") + +@PROMPT_REGISTRY.register() +class DiyQuestionFilterPrompt(PromptABC): + def __init__(self, prompt_template): + self.prompt_template = prompt_template + self.logger = get_logger() + + def build_prompt(self, question: str) -> str: + try: + return self.prompt_template.format(question=question) + except Exception: + self.logger.debug(f"Please check if the symbol {{question}} in prompt is missing.") + +@PROMPT_REGISTRY.register() +class DiyQuestionSynthesisPrompt(PromptABC): + def __init__(self, prompt_template): + self.prompt_template = prompt_template + self.logger = get_logger() + + def build_prompt(self, question: str) -> str: + try: + return self.prompt_template.format(question=question) + except Exception: + self.logger.debug(f"Please check if the symbol {{question}} in prompt is missing.") \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/reasoning/general.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/reasoning/general.py new file mode 100644 index 0000000000000000000000000000000000000000..d6533de78ec995cda9cded18b043d8135e9625cc --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/reasoning/general.py @@ -0,0 +1,106 @@ +from dataflow.utils.registry import PROMPT_REGISTRY +from dataflow.core.prompt import PromptABC +''' +A collection of prompts for the general reasoning operator. +''' + +@PROMPT_REGISTRY.register() +class GeneralAnswerGeneratorPrompt(PromptABC): + ''' + The prompt for the answer generator. + ''' + def __init__(self): + pass + + def build_prompt(self, question: str) -> str: + """ + for general reasoning answer generation + """ + prompt = ( + r'''You are an intelligent chatbot designed for producing the answer to the given reasoning task. + Remember: DO NOT output anything else, only output the answer you generate. + Generate a solution to the given task strictly following this format: + 1. Identify key components and premises of the task + 2. Apply relevant principles, theorems, or methods with step-by-step derivation or argument + 3. Perform any necessary calculations or logical checks with intermediate verification + 4. Present the final answer or conclusion in a clear, unambiguous notation + + Format Requirements: + - Prefix each step with "→" (use the actual arrow symbol, not its Unicode escape sequence) + - Ensure all symbols and special characters are presented using appropriate markup (e.g., LaTeX commands for mathematical symbols, code formatting for code snippets) + + Example Template: + Task: Analyze the time complexity of the following sorting algorithm and prove its correctness. + + Solution: + 1. Identify components: + → Algorithm uses divide-and-conquer to split the list in half + → Merging step compares elements pairwise + + 2. Apply principles: + → Recurrence: T(n) = 2T(n/2) + O(n) + → By Master Theorem, T(n) = O(n log n) + + 3. Verification: + → Check base case T(1) = O(1) + → Inductive step holds for n = 2^k + + 4. Conclusion: + → The algorithm runs in \\boxed{O(n\\log n)} time and correctly sorts any input list. + + Here is the given task you need to solve: + ''' + ) + return prompt + question + r'''Your response must start directly with "Solution:" without any preamble. Finish your response immediately after the solution.''' + +@PROMPT_REGISTRY.register() +class GeneralQuestionSynthesisPrompt(PromptABC): + ''' + The prompt for the question synthesis. + ''' + def __init__(self): + pass + + def build_prompt(self, items: str, question: str) -> str: + prompt = f""" + Create a new, high‑quality reasoning task from the original by applying some of the following transformations (focus on all transformations of "{items}"): + + 1. Alter any quantitative or qualitative elements (numbers, dates, variables, data types, code snippets), ensuring the new task remains coherent and solvable. + 2. Change the task type or domain: e.g. switch from calculation to proof, from mathematical derivation to algorithm design, from text analysis to code debugging, or vice versa. + 3. Reframe the scenario in a different real‑world or abstract context (e.g. finance, engineering, language translation, data processing, robotics), incorporating relevant domain details. + 4. Introduce new premises or constraints that require separate consideration or conditional logic in the solution. + 5. Increase complexity by adding multiple interdependent steps, branching cases, or requiring integration of diverse skills (e.g. math + coding + reasoning). + 6. Vary the output format: require a formal proof, pseudocode, annotated explanation, or numeric answer as appropriate. + + Here is the original task: + {question} + + Generate a fully self‑contained new task inspired by the above. Start directly with the task statement; do NOT include any framing phrases like “Here is a new task inspired by…”. End your response immediately after the task description. + """ + return prompt +@PROMPT_REGISTRY.register() +class GeneralQuestionFilterPrompt(PromptABC): + def __init__(self): + pass + + def build_prompt(self, question: str) -> str: + prompt = f"""You are given a reasoning task. Follow these four steps in order and stop at the first failure: + 0. First, verify the input contains only a single clear reasoning task (no extra instructions like “rewrite”, “translate”, or a provided answer); if not, output judgement_test=false. + 1. Check spelling, grammar, and formatting (e.g. code indentation, LaTeX, Markdown), without interpreting semantics. + 2. For each minimal premise (cannot be further decomposed), verify it does not violate commonsense, domain facts, or task requirements (e.g. “half a person” is invalid; magical operations allowed only if explicitly assumed); if invalid, fail. + 3. Check for any contradictions among premises or in the reasoning process, or if the final result is clearly unreasonable or unsolvable; if so, fail. + 4. If all above pass, check whether there is enough information to complete the task; missing necessary conditions ⇒ fail, redundant details are acceptable. + + After these steps, output exactly: + {{ + "judgement_test": true/false, + "error_type": "" + }} + You may include your chain of thought, but the final output must be the JSON above. + + Here is the content to evaluate: + ------------------------------- + {question} + ------------------------------- + """ + return prompt \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/reasoning/math.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/reasoning/math.py new file mode 100644 index 0000000000000000000000000000000000000000..0aaa56cb94a0b65f01e52c4ae802dcd48e4ff8a0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/reasoning/math.py @@ -0,0 +1,480 @@ +from dataflow.utils.registry import PROMPT_REGISTRY +from dataflow.core.prompt import PromptABC +''' +A collection of prompts for the math reasoning operator. +''' +@PROMPT_REGISTRY.register() +class MathAnswerGeneratorPrompt(PromptABC): + ''' + The prompt for the answer generator. + ''' + def __init__(self): + pass + + def build_prompt(self, question: str) -> str: + """ + 为给定数学题目生成系统提示信息 + """ + prompt = ( + r'''You are an intelligent chatbot designed for writing the answer of the given math question. + Remember: DO NOT output anything else, only output the answer you make. + Generate a solution of a given math problem strictly following this format: + 1. Identify key components of the problem + 2. Apply theorems/formulas with step-by-step derivation + 3. Perform calculations with intermediate verification + 4. Final answer in \boxed{} notation + + Format Requirements: + - Prefix each step with "→" (use the actual arrow symbol, not its Unicode escape sequence) + - Ensure all symbols and special characters are presented using LaTeX commands where appropriate (e.g., ≥ as \\geq, ÷ as \\div) + + Example Template: + Problem: Find the minimum value of function f(x) = x³ - 3x² + 4 on interval [-1, 3] + + Solution: + 1. Find critical points: + → f'(x) = 3x² - 6x + → Set derivative to zero: 3x(x-2) = 0 ⇒ x=0, x=2 + + 2. Evaluate function at critical points and endpoints: + → f(-1) = (-1)^3 - 3(-1)^2 + 4 = -1 -3 +4 = 0.0000 + → f(0) = 0³ - 3(0)² +4 = 4.0000 + → f(2) = 8 - 12 +4 = 0.0000 + → f(3) = 27 - 27 +4 = 4.0000 + + 3. Compare values: + → Minimum occurs at x=-1 and x=2 + + Verification: + → Second derivative test: f''(x) = 6x-6 + → f''(-1) = -12 < 0 (local max) + → f''(2) = 6 > 0 (local min) + + \boxed{0} + + Here is the given problem you need to solve: + ''' + ) + return prompt + question + r'''Your response must directly start with "Solution:" without any preamble, After the answer is generated finish your response right away.''' + +@PROMPT_REGISTRY.register() +class MathQuestionSynthesisPrompt(PromptABC): + ''' + The prompt for the question synthesis. + ''' + def __init__(self): + pass + + def build_prompt(self, items: str, question: str) -> str: + prompt = f""" + Create a new reasonable and solvable math problem from the original problem by applying some of the following transformations(focus on all the transformations of "{items}"): + + 1. Alter numerical values or expressions, ensuring the new problem remains solvable. + 2. Modify the problem type: introduce concepts like ratios or percentages, switch between derivatives and integrals, change the question from finding an area to finding a perimeter, etc. + 3. Contextualize the problem within a real-world scenario, such as incorporating various payment methods or deferred payments with interest. + 4. Add additional premises that require considering an extra factor separately in solving the problem. + 5. Increase the complexity of the problem by introducing multiple conditions that necessitate case-by-case analysis for a solution. + + Here is the problem from the user: + {question} + Write another problem inspired by this one. + Not only change the problem scenario, but also try to create a new problem that requires another approach to solve. + Start directly with the problem statement and DO NOT include any phrases such as "Here is a new problem inspired by a given one". + After the problem is generated finish your response right away. + """ + return prompt + +@PROMPT_REGISTRY.register() +class MathQuestionCategoryPrompt(PromptABC): + ''' + The prompt for the question synthesis. + ''' + def __init__(self): + pass + + def build_prompt(self, question: str) -> str: + prompt = f""" + You are a classification assistant specialized in mathematics. Your task is to classify the given text into one primary category and one secondary category according to the following taxonomy. Do not output any extra explanation. Return only a JSON object with the keys "primary_category" and "secondary_category". + + Taxonomy: + 1. Foundations and Logic + - 1.1 Mathematical Logic and Set Theory + - 1.2 Basic Theory, Formalization, and History & Education + + 2. Algebra and Number Theory + - 2.1 Linear Algebra and Group Theory + - 2.2 Ring Theory, Field Theory, and Polynomial Algebra + - 2.3 Commutative Algebra and Homological/Categorical Methods + - 2.4 Number Theory + - 2.5 Algebraic Geometry + + 3. Analysis and Differential Equations + - 3.1 Real Analysis, Measure Theory, and Functional Analysis + - 3.2 Complex Analysis and Special Functions + - 3.3 Differential Equations and Dynamical Systems + - 3.4 Integral Transforms, Integral Equations, and Difference Equations + - 3.5 Harmonic Analysis + + 4. Geometry and Topology + - 4.1 Euclidean, Analytic, and Convex/Discrete Geometry + - 4.2 Differential Geometry and Manifold Theory + - 4.3 Topology and Algebraic Topology + + 5. Probability, Statistics, and Discrete Mathematics + - 5.1 Probability Theory and Stochastic Processes + - 5.2 Mathematical Statistics + - 5.3 Combinatorics and Graph Theory + + 6. Applied and Computational Mathematics + - 6.1 Numerical Analysis and Computational Methods + - 6.2 Optimal Control, Variational Methods, and Optimization + - 6.3 Operations Research and Game Theory + - 6.4 Systems Theory and Control + - 6.5 Computer Science and Algorithms + - 6.6 Mathematical Physics and Engineering Mathematics + - 6.7 Information and Communication + - 6.8 Biomathematics + + 7. Arithmetic + - 7.1 Basic Arithmetic and Number Operations + - 7.2 Word Problems and Real-Life Applications + + Classify the following text into one primary category and one secondary category based on the taxonomy above. The text is: + {question} + """ + return prompt + +@PROMPT_REGISTRY.register() +class MathQuestionDifficultyPrompt(PromptABC): + ''' + The prompt for the question synthesis. + ''' + def __init__(self): + pass + + def build_prompt(self, question: str) -> str: + prompt = r""" + # CONTEXT # + I am a teacher, and I have some high-level olympiad math problems. + I want to evaluate the difficulty of these math problems. There are some references available regarding the difficulty of the problems: + + For reference, here are some sample problems from each of the difficulty levels 1-10: + + 1: Jamie counted the number of edges of a cube, Jimmy counted the numbers of corners, and Judy counted the number of faces. They then added the three numbers. What was the resulting sum? (2003 AMC 8, Problem 1) + + 1: How many integer values of $x$ satisfy $|x| < 3\pi$? (2021 Spring AMC 10B, Problem 1) + + 1.5: A number is called flippy if its digits alternate between two distinct digits. For example, $2020$ and $37373$ are flippy, but $3883$ and $123123$ are not. How many five-digit flippy numbers are divisible by $15?$ (2020 AMC 8, Problem 19) + + 2: A fair $6$-sided die is repeatedly rolled until an odd number appears. What is the probability that every even number appears at least once before the first occurrence of an odd number? (2021 Spring AMC 10B, Problem 18) + + 2.5: $A$, $B$, $C$ are three piles of rocks. The mean weight of the rocks in $A$ is $40$ pounds, the mean weight of the rocks in $B$ is $50$ pounds, the mean weight of the rocks in the combined piles $A$ and $B$ is $43$ pounds, and the mean weight of the rocks in the combined piles $A$ and $C$ is $44$ pounds. What is the greatest possible integer value for the mean in pounds of the rocks in the combined piles $B$ and $C$? (2013 AMC 12A, Problem 16) + + 3: Triangle $ABC$ with $AB=50$ and $AC=10$ has area $120$. Let $D$ be the midpoint of $\overline{AB}$, and let $E$ be the midpoint of $\overline{AC}$. The angle bisector of $\angle BAC$ intersects $\overline{DE}$ and $\overline{BC}$ at $F$ and $G$, respectively. What is the area of quadrilateral $FDBG$? (2018 AMC 10A, Problem 24) + + 3.5: Find the number of integer values of $k$ in the closed interval $[-500,500]$ for which the equation $\log(kx)=2\log(x+2)$ has exactly one real solution. (2017 AIME II, Problem 7) + + 4: Define a sequence recursively by $x_0=5$ and + \[x_{n+1}=\frac{x_n^2+5x_n+4}{x_n+6}\] + for all nonnegative integers $n.$ Let $m$ be the least positive integer such that + \[x_m\leq 4+\frac{1}{2^{20}}.\] + In which of the following intervals does $m$ lie? + + $\textbf{(A) } [9,26] \qquad\textbf{(B) } [27,80] \qquad\textbf{(C) } [81,242]\qquad\textbf{(D) } [243,728] \qquad\textbf{(E) } [729,\infty)$ + (2019 AMC 10B, Problem 24 and 2019 AMC 12B, Problem 22) + + 4.5: Find, with proof, all positive integers $n$ for which $2^n + 12^n + 2011^n$ is a perfect square. (USAJMO 2011/1) + + 5: Find all triples $(a, b, c)$ of real numbers such that the following system holds: + \[ + a+b+c=\frac{1}{a}+\frac{1}{b}+\frac{1}{c}, + \] + \[ + a^2+b^2+c^2=\frac{1}{a^2}+\frac{1}{b^2}+\frac{1}{c^2}. + \] + (JBMO 2020/1) + + 5.5: Triangle $ABC$ has $\angle BAC = 60^{\circ}$, $\angle CBA \leq 90^{\circ}$, $BC=1$, and $AC \geq AB$. Let $H$, $I$, and $O$ be the orthocenter, incenter, and circumcenter of $\triangle ABC$, respectively. Assume that the area of pentagon $BCOIH$ is the maximum possible. What is $\angle CBA$? (2011 AMC 12A, Problem 25) + + 6: Let $\triangle ABC$ be an acute triangle with circumcircle $\omega,$ and let $H$ be the intersection of the altitudes of $\triangle ABC.$ Suppose the tangent to the circumcircle of $\triangle HBC$ at $H$ intersects $\omega$ at points $X$ and $Y$ with $HA=3,\ HX=2,$ and $HY=6.$ The area of $\triangle ABC$ can be written in the form $m\sqrt{n},$ where $m$ and $n$ are positive integers, and $n$ is not divisible by the square of any prime. Find $m+n.$ (2020 AIME I, Problem 15) + + 6.5: Rectangles $BCC_1B_2,$ $CAA_1C_2,$ and $ABB_1A_2$ are erected outside an acute triangle $ABC.$ Suppose that + \[\angle BC_1C+\angle CA_1A+\angle AB_1B=180^{\circ}.\] + Prove that lines $B_1C_2,$ $C_1A_2,$ and $A_1B_2$ are concurrent. (USAMO 2021/1, USAJMO 2021/2) + + 7: We say that a finite set $\mathcal{S}$ in the plane is balanced if, for any two different points $A$, $B$ in $\mathcal{S}$, there is a point $C$ in $\mathcal{S}$ such that $AC=BC$. We say that $\mathcal{S}$ is centre-free if for any three points $A$, $B$, $C$ in $\mathcal{S}$, there is no point $P$ in $\mathcal{S}$ such that $PA=PB=PC$. + + Show that for all integers $n\geq 3$, there exists a balanced set consisting of $n$ points. + Determine all integers $n\geq 3$ for which there exists a balanced centre-free set consisting of $n$ points. + (IMO 2015/1) + + 7.5: Let $\mathbb{Z}$ be the set of integers. Find all functions $f : \mathbb{Z} \rightarrow \mathbb{Z}$ such that + \[ + xf(2f(y)-x)+y^2f(2x-f(y))=\frac{f(x)^2}{x}+f(yf(y)) + \] + for all $x, y \in \mathbb{Z}$ with $x \neq 0$. (USAMO 2014/2) + + 8: For each positive integer $n$, the Bank of Cape Town issues coins of denomination $\frac1n$. Given a finite collection of such coins (of not necessarily different denominations) with total value at most $99+\frac{1}{2}$, prove that it is possible to split this collection into $100$ or fewer groups, such that each group has total value at most $1$. (IMO 2014/5) + + 8.5: Let $I$ be the incentre of acute triangle $ABC$ with $AB\neq AC$. The incircle $\omega$ of $ABC$ is tangent to sides $BC, CA$, and $AB$ at $D, E,$ and $F$, respectively. The line through $D$ perpendicular to $EF$ meets $\omega$ at $R$. Line $AR$ meets $\omega$ again at $P$. The circumcircles of triangle $PCE$ and $PBF$ meet again at $Q$. + + Prove that lines $DI$ and $PQ$ meet on the line through $A$ perpendicular to $AI$. (IMO 2019/6) + + 9: Let $k$ be a positive integer and let $S$ be a finite set of odd prime numbers. Prove that there is at most one way (up to rotation and reflection) to place the elements of $S$ around the circle such that the product of any two neighbors is of the form $x^2+x+k$ for some positive integer $x$. (IMO 2022/3) + + 9.5: An anti-Pascal triangle is an equilateral triangular array of numbers such that, except for the numbers in the bottom row, each number is the absolute value of the difference of the two numbers immediately below it. For example, the following is an anti-Pascal triangle with four rows which contains every integer from $1$ to $10$. + \[ + \begin{array}{ c@{\hspace{4pt}}c@{\hspace{4pt}} c@{\hspace{4pt}}c@{\hspace{2pt}}c@{\hspace{2pt}}c@{\hspace{4pt}}c } + & & & 4 & & & \\ + & & 2 & & 6 & & \\ + & 5 & & 7 & & 1 & \\ + 8 & & 3 & & 10 & & 9 \\ + \end{array} + \] + Does there exist an anti-Pascal triangle with $2018$ rows which contains every integer from $1$ to $1 + 2 + 3 + \dots + 2018$? (IMO 2018/3) + + 10: Prove that there exists a positive constant $c$ such that the following statement is true: Consider an integer $n > 1$, and a set $\mathcal S$ of $n$ points in the plane such that the distance between any two different points in $\mathcal S$ is at least 1. It follows that there is a line $\ell$ separating $\mathcal S$ such that the distance from any point of $\mathcal S$ to $\ell$ is at least $cn^{-1/3}$. + + (A line $\ell$ separates a set of points S if some segment joining two points in $\mathcal S$ crosses $\ell$.) (IMO 2020/6) + ## Some known difficulty ratings of the competitions. + + + + # OBJECTIVE # + A. Summarize the math problem in a brief sentence, describing the concepts involved in the math problem. + B. Based on the source of the given problem, as well as the difficulty of the problems referenced in these materials and the solution to the current problem, please provide + an overall difficulty score for the current problem. The score should be a number between 1 and 10, with increments of 0.5, and should align perfectly with the materials. + # STYLE # + Data report. + # TONE # + Professional, scientific. + # AUDIENCE # + Students. Enable them to better understand the difficulty of the math problems. + # RESPONSE: MARKDOWN REPORT # + ## Summarization + [Summarize the math problem in a brief paragraph.] + ## Difficulty + [Rate the difficulty of the math problem and give the reason.] + # ATTENTION #- Add "=== report over ===" at the end of the report. + + The problem requires finding the missing value in the equation + + \[ + \frac{1}{9}+\frac{1}{18}=\frac{1}{\square}. + \] + + In other words, determine the number that should replace the square such that the sum of the fractions on the left equals the fraction on the right. + + ## Summarization + The problem requires finding a value that makes the equation $\\frac{1}{9}+\\frac{1}{18}=\\frac{1}{\\square}$. + This involves adding two fractions and determining the equivalent fraction. + ## Difficulty + Rating: 1 + Reason: This problem is straightforward and primarily involves basic fraction addition, making it suitable for early middle school students. + === report over === + + Let $\mathcal{P}$ be a convex polygon with $n$ sides, $n\ge3$. Any set of $n - 3$ diagonals of $\mathcal{P}$ that do not intersect in the interior of the polygon determine a triangulation of $\mathcal{P}$ into $n - 2$ triangles. If $\mathcal{P}$ is regular and there is a triangulation of $\mathcal{P}$ consisting of only isosceles triangles, find all the possible values of $n$. + + ## Summarization + The problem asks for the possible values of $n$ for a regular n-sided polygon that can be completely triangulated into isosceles triangles using non-intersecting diagonals. + The solution involves analyzing the properties of the diagonals forming isosceles triangles and deducing that $n$ can be expressed in terms of powers of 2. + ## Difficulty + Rating: 7 + Reason: The problem involves understanding properties of isosceles triangles in the context of polygon triangulation and requires critical reasoning to establish + relationships between the number of sides and powers of 2, making it more complex than typical undergraduate-level problems. + === report over === + + [Question]: \n + + """ + + return prompt + question + +@PROMPT_REGISTRY.register() +class MathQuestionFilterPrompt(PromptABC): + ''' + The prompt for the question filter. + ''' + def __init__(self): + pass + + def build_prompt(self, question: str) -> str: + """Constructs an evaluation prompt with four progressive checks""" + prompt = f"""You are given a mathematical problem. Follow these four steps in order and stop at the first failure: + 0. Firstly check if it is only a math problem, if it has other instruction confused the model such as "rewrite" or has answer or other strange instruction, then judged as failure. If it is not a math problem, then the judgement_test is false. + 1. Check only for spelling, grammar, and LaTeX formatting correctness. Do not interpret semantic meaning. + 2. For each minimal condition stated in the problem (that cannot be further decomposed), check if it violates the mathematical domain or objective facts (for example, 'half a person' is incorrect). Note: Magical operations are acceptable if the necessary assumption is explicitly stated. Average values (e.g., 15.5 items per minute) are acceptable. + 3. Check whether the problem-solving process contains any contradictions. This includes any two minimal conditions contradicting each other or if the final solution would be unreasonable (including unsolvable). + 4. If the steps above pass, check if there are enough conditions provided in the problem to answer the target question. Redundant conditions that do not affect the problem - solving process are considered reasonable. Both analytical and numerical solutions are considered valid unless otherwise specified. + + After performing these steps in sequence, output your final judgment in JSON format with exactly the following keys: + {{ + "judgement_test": true/false, + "error_type": "" + }} + You may include your chain-of-thought, but the final answer must be the JSON object above. + + Here is the problem to evaluate: + ------------------------------- + {question} + ------------------------------- + """ + return prompt + +@PROMPT_REGISTRY.register() +class MathQuestionSequentialFusionGeneratorPrompt(PromptABC): + def __init__(self): + pass + + def build_system_prompt(self): + system_prompt = "" + return system_prompt + + def build_prompt(self, input_question_1, input_question_2): + prompt = f""" + # Role: Mathematical Problem Merger + ## Profile + Your role is to merge "#Problem 1#" and "#Problem 2#" into a combined problem. + ## Guidelines + Step 1: Identify input and output variables in both problems. Determine mathematical relationships and constraints in each + problem. Locate variables between "#Problem 1#" and "#Problem 2#" that can form sequential dependencies. + Step 2: Formulate a comprehensive plan to merge the two problems by using "#Problem 1#"’s output variable to + replace an input variable of "#Problem 2#"’s. Merge contextual elements by embedding both problems within a unified + real-world scenario or extended narrative, aligning units and measurement systems. + Step 3: Create a single "#New Problem#" where solving "#Problem 1#" is a prerequisite for "#Problem + ## Output Format + Please reply strictly in the following format: + #Elements Identified#: + #Plan#: + #New Problem#: + ## Input + ### #Problem 1# + {input_question_1} + ### #Problem 2# + {input_question_2} + 2#". Explicitly state variable dependencies and which variable is replaced. Adjust numerical ranges to maintain arithmetic + consistency. The "#New Problem#" should contain no supplementary explanation or note. + ## Output + + """ + return prompt + +@PROMPT_REGISTRY.register() +class MathQuestionParallelFusionGeneratorPrompt(PromptABC): + def __init__(self): + pass + + def build_system_prompt(self): + system_prompt = "" + return system_prompt + + def build_prompt(self, input_question_1, input_question_2): + prompt = f""" + # Role: Mathematical Problem Synthesizer + ## Profile Your role is to organically integrate "#Problem 1#" and "#Problem 2#" to create a novel problem that + requires advanced synthesis of their mathematical essence. + ## Guidelines + Step 1: Conduct deep structural analysis of both problems by identifying their fundamental mathematical operations, + contextual frameworks, and cognitive patterns. Extract the underlying logical architectures while preserving their distinctive + solution pathways. + Step 2: Develop an innovative fusion mechanism by discovering non-obvious mathematical connections between + the problems’ core concepts. Construct a multidimensional scenario that naturally embeds both original contexts through + temporal sequencing, spatial superposition, or conceptual analogy. Engineer hybrid parameters that inherit characteristics + from both source problems while introducing emergent properties. + Step 3: Formulate the synthesized problem through strategic recombination of mathematical elements, ensuring + the new problem requires concurrent application of both original solution strategies. Introduce controlled complexity + problems’ answers. + ## Output Format + Please reply strictly in the following format: + #Core Elements#: + #Synthesis Method#: + #New Problem#: + ## Input + ### #Problem 1# + {input_question_1} + ### #Problem 2# + {input_question_2} + through cross-domain constraints and self-verification mechanisms that establish mathematical consistency with both source + ## Output + + """ + return prompt + +@PROMPT_REGISTRY.register() +class MathQuestionConditionFusionGeneratorPrompt(PromptABC): + def __init__(self): + pass + + def build_system_prompt(self): + system_prompt = "" + return system_prompt + + def build_prompt(self, input_question_1, input_question_2): + prompt = f""" + # Role: Problem Integrator + ## Profile + Create a real-world problem where the solution requires solving both "#Problem 1#" and "#Problem 2#" independently. + **Ensure the the final answer is either from "#Problem 1#" or "#Problem 2#", depends on the "#New Question#"**. + ## Guidelines + Step 1: Analyze "#Problem 1#" and "#Problem 2#" and make sure that the output variables they ask about are of the same + type. If they are different (for example, one asks about time and the other asks about price), modify one of the problem so that + it asks about the same variable as the other. + Step 2: Design a unified problem scenario that combines "#Problem 1#" and "#Problem 2#". Introduce a "#New Question#", + which must be related with both "#Problem 1#" and "#Problem 2#". Ensure that final answer of the "#New Question#" must + either come from "#Problem 1#" or "#Problem 2#". This means that the "#New Question#" should be an **comparison** + and **selection** of the previous answers, not their **combination**. There are some examples for the "#New Question#": + 1. Who sells the most items? + 2. Howmuch money does the top earner make? + 3. Which is the cheaper plan? + 4. Someone has 200 dollor, which item can he afford? + phrases "#Problem 1#" and "#Problem 2#" in the generated "#New Problem#". + ## Output Format + Please reply strictly in the following format: + #Analysis#: + #New Question#: + #New Problem#: + ## Input + ### #Problem 1# + {input_question_1} + ### #Problem 2# + {input_question_2} + Step 3: Provide the "#New Problem#", which combine "#Problem 1#", "#Problem 2#", and "#New Question#" in a unified + real-world scenario. Don’t contain solution of "#Problem 1#" and "#Problem 2#" in "#New Problem#". + ## Output + + """ + return prompt + +@PROMPT_REGISTRY.register() +class MathQuestionEvaluatorPrompt(PromptABC): + def __init__(self): + pass + + def build_system_prompt(self): + system_prompt = "" + return system_prompt + + def build_prompt(self, input_question): + prompt = f""" + # Role: Mathematics Grading Teacher + ## Profile + You are a senior mathematics grading teacher in university, very skilled in high difficulty fields such as Intermediate Algebra, + Precalculus, Prealgebra, Number Theory, Geometry, Counting & Probability, Algebra and so on. + ## Guidelines + Your task is to act as an impartial judge to evaluate the statement completeness and correctness of math problem according to + the following rules: + 1. Assess the clarity and accuracy of the definition of each math problem. Ensure that the problem statement provides + sufficient information, conditions, and constraints. + 2. Consider whether the problem allows for multiple interpretations or if further clarification is needed. + 3. Evaluate the clarity of mathematical notation and terminology used in the problem. + ## Output Format + Please reply strictly in the following format: + #Judgement#: + #Explanation#: + ## Input + {input_question} + 4. Evaluate whether the math problem is solvable. If the math problem meet the rules above, output "True" in "#Judge + ment#", else "False". You should also give your explanation in "#Explanation#". + ## Output + """ + return prompt \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/text2qa.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/text2qa.py new file mode 100644 index 0000000000000000000000000000000000000000..a349e86800f5f8c0cedfebd77dce52ba6ceba084 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/text2qa.py @@ -0,0 +1,338 @@ +import json +from dataflow.utils.registry import PROMPT_REGISTRY +from dataflow.core.prompt import PromptABC +""" +A collection of prompts for the Text2QA pipelines operator +""" +@PROMPT_REGISTRY.register() +class Text2QAAutoPromptGeneratorPrompt(PromptABC): + ''' + The prompt for the AutoPromptGenerator. + ''' + def __init__(self): + pass + + def build_prompt(self, seed_data: str) -> str: + prompt = f'''You will be given a piece of seed data, which may consist of a paragraph, dialogue, or any other form of text containing potential question-answer information. +Your task is to analyze this seed data carefully and generate as much non-repeat clear and effective prompt as you can that can be used to instruct a language model to extract a single high-quality question-answer (QA) pair suitable for reinforcement learning (RL) training from this piece of data. + +The generated prompt should: +Clearly describe the type and format of input the model will receive; +Explicitly ask for the extraction of a relevant QA pair; +Optionally include instructions about the desired style, level of detail, or coverage; +Be written in natural, precise English that could be directly used with another LLM; +Be strictly the prompt used to extract QA pairs, not the QA pairs themselves. + +Your prompts should contain the following instructions: +The question should be clear, focused, and unambiguous, such that it targets specific factual content from the input; +The answer should be a few words that are concise, factual and directly verifiable from the source rather than a whole sentence, enabling accurate reward computation in the RL pipeline; +Both the question and answer should be simple enough to facilitate evaluation and automatic feedback. + +Don't include any additional explanations or comments in your output. +Don't repeat the seed data in your output. +Your output format should be in a list as follow: +["PROMPT_1","PROMPT_2",...] +Here is the seed data you need to analyze and generate a prompt for:\n{seed_data}''' + + return prompt + +@PROMPT_REGISTRY.register() +class Text2QASeedQuestionGeneratorPrompt(PromptABC): + ''' + The prompt for the Text2QAGenerator. + ''' + def __init__(self): + pass + + def build_prompt(self) -> str: + prompt = f'''"Format:\nQ: ...\nA: ..." + "\nSeed data:\n"''' + + return prompt + + +@PROMPT_REGISTRY.register() +class Text2QAQuestionQualityPrompt(PromptABC): + ''' + The prompt for the question quality scorer. + ''' + def __init__(self): + pass + + def build_prompt(self) -> str: + prompt = '''You are an expert question quality evaluator. Given a single question from a QA dataset, your job is to assess the **clarity and meaningfulness** of the question. Specifically, judge whether the question is clearly defined, unambiguous, and worth asking in a real-world or task-specific context. + +Assign a score from 1 to 5 based on the following rubric: +5 = Very clear and meaningful question, well-posed +4 = Clear but slightly underspecified or too general +3 = Somewhat unclear or poorly scoped, but understandable +2 = Ambiguous, vague, or unnatural +1 = Nonsensical or meaningless + +Output format: +**Grading**: [1-5] + +**Feedback**: Explain your score. Mention if the question is ambiguous, overly broad, or lacks practical purpose. Suggest how to improve clarity or specificity if needed. + +''' + + return prompt + +@PROMPT_REGISTRY.register() +class Text2QAAnswerAlignmentPrompt(PromptABC): + ''' + The prompt for the RAG answer alignment scorer. + ''' + def __init__(self): + pass + + def build_prompt(self) -> str: + prompt = '''You are a response alignment evaluator. Your task is to assess whether a given answer **directly and clearly addresses the given question**. + +Assign a score from 1 to 5 based on the following rubric: +5 = Fully and directly answers the question +4 = Mostly addresses the question, with minor gaps or irrelevant additions +3 = Partially answers the question but omits key aspects +2 = Barely addresses the question or is off-topic +1 = Completely unrelated to the question + +Output format: +**Grading**: [1-5] + +**Feedback**: Justify your score. Point out if the answer is evasive, incomplete, or misaligned. Suggest ways to better match the response to the question. + +''' + + return prompt + +@PROMPT_REGISTRY.register() +class Text2QAAnswerVerifiabilityPrompt(PromptABC): + ''' + The prompt for the RAG answer verifiability scorer. + ''' + def __init__(self): + pass + + def build_prompt(self) -> str: + prompt = '''You are an evaluator tasked with assessing how **easily verifiable** an answer is. You must determine whether the correctness of the answer can be **conveniently and unambiguously judged** — for example, whether it is fact-based, precise, and not subjective or vague. + +Assign a score from 1 to 5 based on the following rubric: +5 = Very easy to verify; answer is objective, concrete, and unambiguous +4 = Mostly verifiable, with minor ambiguities +3 = Verifiable in parts, but some subjectivity or fuzziness +2 = Hard to verify; answer is vague, speculative, or opinion-based +1 = Unverifiable or meaningless + +Output format: +**Grading**: [1-5] + +**Feedback**: Explain your score. Identify elements that make verification easier or harder. Suggest rephrasing or grounding techniques to improve verifiability. + +''' + + return prompt + +@PROMPT_REGISTRY.register() +class Text2QADownstreamValuePrompt(PromptABC): + ''' + The prompt for the RAG downstream value scorer. + ''' + def __init__(self): + pass + + def build_prompt(self) -> str: + prompt = '''You are a task relevance evaluator. Given a QA pair, assess how well this data point could **support a downstream task** such as classification, dialogue, retrieval, summarization, or knowledge grounding. + +Assign a score from 1 to 5 based on the following rubric: +5 = Highly valuable for downstream tasks; question and answer are precise and informative +4 = Useful with minor limitations +3 = Moderately helpful; limited in informativeness or specificity +2 = Of little value; vague or too generic to help the model learn +1 = Useless or irrelevant for any downstream learning objective + +Output format: +**Grading**: [1-5] + +**Feedback**: Describe how the QA pair does or does not benefit potential downstream tasks. If relevant, suggest how to make it more useful for training. + +''' + + return prompt + +import textwrap +from typing import Dict, Literal +from dataflow.utils.registry import PROMPT_REGISTRY +from dataflow.core.prompt import PromptABC + +@PROMPT_REGISTRY.register() +class Text2MultiHopQAGeneratorPrompt(PromptABC): + ''' + 多跳问答生成器(严格JSON格式输出) + 根据语言参数提供完全独立的专业提示模板 + ''' + def __init__(self, lang: str = "en"): + self.lang = lang + self.system_text = self.build_system_prompt() + + def build_system_prompt(self) -> str: + """构建专业级多跳问答提示""" + if self.lang == "en": + return textwrap.dedent("""\ + You are a professional multi-hop QA specialist with strict protocols: + + █ Core Requirements + 1. Must identify 2-3 interrelated facts in context + 2. Design complex questions requiring cross-fact reasoning + 3. Reasoning chains must: + - Contain 2-3 logical steps (numbered) + - Show clear causal/progressive relationships + - Each step must reference specific facts + 4. Final answer must synthesize all reasoning conclusions + 5. Focus solely on the main text and avoid synthesizing Q&A based on content found in links, references, or other supplementary sources. + + █ Output Specifications + 1. Only pure JSON in this structure: + { + "question": "Multi-fact reasoning question", + "reasoning_steps": [ + {"step": "First step (must use Fact 1)"}, + {"step": "Second step (must link Fact 2)"} + ], + "answer": "Synthesized final answer", + "supporting_facts": ["Verbatim Fact 1", "Verbatim Fact 2"], + "type": "domain_tag" + } + 2. Supporting facts must: + - Be verbatim from context + - Directly support corresponding steps + - No paraphrasing allowed + + █ Demonstration + Context: + "Photosynthesis converts CO2 to oxygen. This process sustains plant growth. Plants form the base of food chains." + + Valid Output: + { + "question": "How does photosynthesis impact ecosystems?", + "reasoning_steps": [ + {"step": "Photosynthesis produces oxygen"}, + {"step": "Plants using photosynthesis form food chain bases"} + ], + "answer": "It provides oxygen and sustains ecosystem food chains", + "supporting_facts": [ + "Photosynthesis converts CO2 to oxygen", + "Plants form the base of food chains" + ], + "type": "biology" + } + + █ Rejection Criteria + Reject if: + - Fewer than 2 reasoning steps + - Unreferenced supporting facts exist + - Any non-JSON content appears + """) + else: + return textwrap.dedent("""\ + 您是专业的多跳问答生成专家,必须严格遵循以下专业标准: + + █ 核心要求 + 1. 必须识别上下文中的2-3个关联事实 + 2. 设计需要跨事实推理的复杂问题 + 3. 推理链必须满足: + - 至少包含2-3个逻辑步骤 + - 每个步骤明确标注序号 + - 步骤间存在因果或递进关系 + 4. 最终答案必须整合所有推理结论 + 5. 只关注正文内容,避免根据链接、参考文献等附加信息合成问答。 + + █ 输出规范 + 1. 仅允许输出以下结构的纯JSON: + { + "question": "需要跨事实推理的问题", + "reasoning_steps": [ + {"step": "第一推理步骤(必须引用事实1)"}, + {"step": "第二推理步骤(必须关联事实2)"} + ], + "answer": "整合所有步骤的最终答案", + "supporting_facts": ["原文事实1", "原文事实2"], + "type": "领域标签" + } + 2. 支撑事实必须: + - 从上下文逐字提取 + - 与推理步骤严格对应 + - 不得改写或概括 + + █ 示例 + 上下文: + "量子纠缠现象由爱因斯坦提出质疑。后来贝尔实验证实了其真实性。该现象是量子计算的基础。" + + 合格输出: + { + "question": "为什么量子纠缠现象对量子计算很重要?", + "reasoning_steps": [ + {"step": "贝尔实验证实了量子纠缠的真实性"}, + {"step": "该现象是量子计算的基础"} + ], + "answer": "因为量子纠缠被证实真实且是量子计算的基础", + "supporting_facts": [ + "后来贝尔实验证实了其真实性", + "该现象是量子计算的基础" + ], + "type": "量子物理" + } + + █ 违规处理 + 以下情况将拒绝输出: + - 推理步骤少于2步 + - 存在未引用的支撑事实 + - JSON外出现任何附加文本 + """) + + def build_prompt(self, text: str) -> str: + """生成完全专业化的用户提示""" + if self.lang == "en": + user_prompt = textwrap.dedent(f"""\ + Generate professional multi-hop QA from: + + Context: + {text} + + Strict requirements: + 1. Extract exactly 2-3 interrelated facts + 2. Question must demonstrate cross-fact reasoning + 3. Use this exact JSON structure (include all quotes/braces): + {{ + "question": "...", + "reasoning_steps": [ + {{"step": "Must explicitly use Fact 1"}}, + {{"step": "Must explicitly link Fact 2"}} + ], + "answer": "...", + "supporting_facts": ["Verbatim Fact 1", "Verbatim Fact 2"], + "type": "..." + }} + """) + else: + user_prompt = textwrap.dedent(f"""\ + 请基于以下上下文生成专业级多跳问答: + + 上下文: + {text} + + 严格按照以下要求执行: + 1. 必须从上述上下文中提取2-3个关联事实 + 2. 问题需体现跨事实推理的复杂性 + 3. 使用此精确JSON结构(包括所有引号和括号): + {{ + "question": "...", + "reasoning_steps": [ + {{"step": "必须明确引用事实1"}}, + {{"step": "必须明确关联事实2"}} + ], + "answer": "...", + "supporting_facts": ["事实1原文", "事实2原文"], + "type": "..." + }} + """) + + return user_prompt \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/text2sql.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/text2sql.py new file mode 100644 index 0000000000000000000000000000000000000000..065bf5190d9c7bdfd3bab2ba590cf9f6f95ee1d8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/prompts/text2sql.py @@ -0,0 +1,1682 @@ +''' +A collection of prompts for the text2sql operator. +''' +import random +from re import template +import numpy as np +import json +from typing import List +from dataflow.utils.registry import PROMPT_REGISTRY +from dataflow.core.prompt import PromptABC + + +@PROMPT_REGISTRY.register() +class Text2SQLCorrespondenceFilterPrompt(PromptABC): + def __init__(self): + pass + + def build_prompt(self, question: str, sql: str, db_details: str) -> str: + prompt = f""" + **Task Overview** + Determine if the SQL query is correctly answering the given question based on the provided schema. + + **Question** + {question} + + **SQL** + {sql} + + **Schema** + {db_details} + + **Evaluation Criteria** + 1. **Logical Alignment**: Does the SQL query logically address what the question is asking? + 2. **Schema Compliance**: Are the tables, columns, and relationships used correctly according to the schema? + 3. **Completeness**: Does the SQL capture all necessary conditions and requirements from the question? + 4. **Correctness**: Are there any logical errors that would prevent getting the correct answer? + + **Output Format**: + The conclusion should be enclosed in a code block: + ``` + YES/NO + ``` + + **Decision Rules** + - YES: SQL correctly implements the question requirements + - NO: SQL has logical errors or doesn't address the question properly + - When uncertain about edge cases, explain the uncertainty in analysis but still provide a definitive YES/NO + + **Answer** + Let's proceed step by step. + """ + return prompt + +@PROMPT_REGISTRY.register() +class Text2SQLCotGeneratorPrompt(PromptABC): + def __init__(self): + pass + + def build_prompt(self, schema_str: str, question: str, sql: str, evidence: str) -> str: + if evidence: + question_with_evidence = question + "\n" + evidence + else: + question_with_evidence = question + prompt = f""" + You are a senior data analyst specializing in SQL. Your task is to translate a natural language question into an executable SQLite query, providing a detailed reasoning trace. + + You will also receive a reference solution from a colleague, which may or may not be correct. This extra information intends to help you generate your answer, but you are asked not to mention the reference solution in any form. + The reference solution might include: + 1. Unnecessary table and column selections. + 2. Incorrect or excessive joins. + 3. Misalignment with the question. + 4. Opportunities for simplification. + + Ensure the SQL query is presented in a Markdown code block with proper syntax highlighting, like this: + ```sql + SELECT * FROM table; + ``` + + [Database Schema]: + {schema_str} + + [Natural Language Question]: + {question_with_evidence} + + [Reference Solution]: + ```sql + {sql} + ``` + + Provide your step-by-step text-to-SQL solution here. + """ + return prompt + + +@PROMPT_REGISTRY.register() +class SelectSQLGeneratorPrompt(PromptABC): + def __init__(self): + self.simple_criterion = '''**Criteria:** + Simple SQL queries may satisfy one or more of the following criteria: + - Simple queries should select data from a single table only. + - Basic aggregate functions are permitted, such as `COUNT`, `SUM`, `AVG`, `MIN`, `MAX`. + - No joins are allowed; the query must operate on a single table. + + **Example of Simple SQL Query:** + ```sql + SELECT name, department_name + FROM employees + WHERE level > 5 + ORDER BY age DESC; + ```''' + + self.moderate_criterion = '''**Criteria:** + Moderate SQL queries may satisfy one or more of the following criteria: + - Involves table joins, such as `JOIN`, `INNER JOIN`, `LEFT JOIN`, `CROSS JOIN`, etc. + - Includes subqueries within the `SELECT` or `WHERE` clauses. + - Utilizes aggregate functions alongside a `GROUP BY` clause. + - Contains complex `WHERE` conditions, including `IN`, `BETWEEN`, `LIKE`. + - Incorporate a `HAVING` clause to filter aggregated results. + - Uses aggregate functions like `COUNT`, `SUM`, `AVG`, `MIN`, `MAX`, etc. + + **Example of Moderate SQL Query:** + ```sql + SELECT e.name, d.department_name, AVG(s.salary) AS average_salary + FROM employees e + INNER JOIN departments d ON e.department_id = d.department_id + LEFT JOIN salaries s ON e.employee_id = s.employee_id + WHERE e.age > 30 AND e.status = 'active' + GROUP BY e.name, d.department_name + HAVING AVG(s.salary) > 50000; + ```''' + + self.complex_criterion = '''**Criteria:** + Complex SQL queries may satisfy one or more of the following criteria: + - Contains complex nested subqueries. + - Utilizes multiple types of joins, including self-joins. + - Includes window functions, such as `ROW_NUMBER`, `RANK`, etc. + - Uses Common Table Expressions (CTEs) for improved readability. + - Combines multiple aggregate functions. + - Involves complex `WHERE` and `HAVING` clauses with multiple conditions. + - Utilizes advanced functions and operators. + + **Example of Complex SQL Query:** + ```sql + WITH EmployeeCTE AS ( + SELECT employee_id, name, department_id, ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rank + FROM employees + ) + SELECT e.name, d.department_name + FROM EmployeeCTE e + INNER JOIN departments d ON e.department_id = d.department_id + WHERE e.rank <= 3; + ```''' + + self.highly_complex_criterion = '''**Criteria:** + Highly complex SQL queries may satisfy one or more of the following criteria: + - Includes multiple Common Table Expressions (CTEs) for readability. + - Combines nested subqueries and various joins. + - Utilizes recursive CTEs for hierarchical or recursive queries. + - Extensively uses advanced window functions. + - May involve `UNION` or `UNION ALL` to combine result sets. + - Implements complex logic with advanced analytical functions. + - Employs a wide range of SQL clauses and conditions. + - Utilizes a broad spectrum of SQL functions and advanced features. + + **Example of Highly Complex SQL Query:** + ```sql + WITH RECURSIVE EmployeeHierarchy AS ( + SELECT employee_id, name, manager_id, department_id, 1 as level + FROM employees + WHERE manager_id IS NULL + UNION ALL + SELECT e.employee_id, e.name, e.manager_id, e.department_id, eh.level + 1 + FROM employees e + JOIN EmployeeHierarchy eh ON e.manager_id = eh.employee_id + ), + DepartmentSalaries AS ( + SELECT eh.employee_id, eh.name, eh.level, d.department_name, s.salary, d.department_id + FROM EmployeeHierarchy eh + INNER JOIN departments d ON eh.department_id = d.department_id + INNER JOIN salaries s ON eh.employee_id = s.employee_id + ), + DepartmentStats AS ( + SELECT + d.department_id, + COUNT(e.employee_id) AS employee_count, + AVG(s.salary) AS average_salary + FROM employees e + INNER JOIN salaries s ON e.employee_id = s.employee_id + INNER JOIN departments d ON e.department_id = d.department_id + GROUP BY d.department_id + ) + SELECT ds.name, ds.level, + SUM(ds.salary) OVER (PARTITION BY ds.department_id ORDER BY ds.level, ds.name) AS cumulative_salary + FROM DepartmentSalaries ds + INNER JOIN DepartmentStats dstat ON ds.department_id = dstat.department_id + ORDER BY ds.level, ds.name; + ```''' + self.complexity2criterion = { + "Simple": self.simple_criterion, + "Moderate": self.moderate_criterion, + "Complex": self.complex_criterion, + "Highly Complex": self.highly_complex_criterion + } + + self.complexity2criterion = { + "Simple": self.simple_criterion, + "Moderate": self.moderate_criterion, + "Complex": self.complex_criterion, + "Highly Complex": self.highly_complex_criterion + } + + self.functions = [ + "ABS(X) \nDescription: The ABS(X) function returns the absolute value of the numeric argument X. Abs(X) returns NULL if X is NULL. Abs(X) returns 0.0 if X is a string or blob that cannot be converted to a numeric value. If X is the integer -9223372036854775808 then ABS(X) throws an integer overflow error since there is no equivalent positive 64-bit two complement value. ", + "CHANGES() \nDescription: The CHANGES() function returns the number of database rows that were changed or inserted or deleted by the most recently completed INSERT, DELETE, or UPDATE statement, exclusive of statements in lower-level triggers. The CHANGES() SQL function is a wrapper around thesqlite3_changes64()C/C++ function and hence follows the same rules for counting changes. ", + "CHAR(X1,X2,...,XN) \nDescription: The CHAR(X1,X2,...,XN) function returns a string composed of characters having the unicode code point values of integers X1 through XN, respectively. ", + "COALESCE(X,Y,...) \nDescription: The COALESCE() function returns a copy of its first non-NULL argument, or NULL if all arguments are NULL. Coalesce() must have at least 2 arguments. ", + "CONCAT(X,...) \nDescription: The CONCAT(...) function returns a string which is the concatenation of the string representation of all of its non-NULL arguments. If all arguments are NULL, then CONCAT() returns an empty string. ", + "CONCAT_WS(SEP,X,...) \nDescription: The CONCAT_WS(SEP,...) function returns a string that is the concatenation of all non-null arguments beyond the first argument, using the text value of the first argument as a separator. If the first argument is NULL, then CONCAT_WS() returns NULL. If all arguments other than the first are NULL, then CONCAT_WS() returns an empty string. ", + "FORMAT(FORMAT,...) \nDescription: The FORMAT(FORMAT,...) SQL function works like thesqlite3_mprintf()C-language function and the printf() function from the standard C library. The first argument is a format string that specifies how to construct the output string using values taken from subsequent arguments. If the FORMAT argument is missing or NULL then the result is NULL. The %n format is silently ignored and does not consume an argument. The %p format is an alias for %X. The %z format is interchangeable with %s. If there are too few arguments in the argument list, missing arguments are assumed to have a NULL value, which is translated into 0 or 0.0 for numeric formats or an empty string for %s. See thebuilt-in printf()documentation for additional information. ", + "GLOB(X,Y) \nDescription: The GLOB(X,Y) function is equivalent to the expression \"Y GLOB X\". Note that the X and Y arguments are reversed in the GLOB() function relative to the infixGLOBoperator. Y is the string and X is the pattern. So, for example, the following expressions are equivalent:name GLOB '*helium*' GLOB('*helium*',name)If thesqlite3_create_function()interface is used to override the GLOB(X,Y) function with an alternative implementation then theGLOBoperator will invoke the alternative implementation. ", + "HEX(X) \nDescription: The HEX() function interprets its argument as a BLOB and returns a string which is the upper-case hexadecimal rendering of the content of that blob.If the argumentXin \"hex(X)\" is an integer or floating point number, then \"interprets its argument as a BLOB\" means that the binary number is first converted into a UTF8 text representation, then that text is interpreted as a BLOB. Hence, \"hex(12345678)\" renders as \"3132333435363738\" not the binary representation of the integer value \"0000000000BC614E\".See also:unhex() ", + "IFNULL(X,Y) \nDescription: The IFNULL() function returns a copy of its first non-NULL argument, or NULL if both arguments are NULL. Ifnull() must have exactly 2 arguments. The IFNULL() function is equivalent tocoalesce()with two arguments. ", + "IIF(X,Y,Z) \nDescription: The IIF(X,Y,Z) function returns the value Y if X is true, and Z otherwise. The IIF(X,Y,Z) function is logically equivalent to and generates the samebytecodeas theCASE expression\"CASE WHEN X THEN Y ELSE Z END\". ", + "INSTR(X,Y) \nDescription: The INSTR(X,Y) function finds the first occurrence of string Y within string X and returns the number of prior characters plus 1, or 0 if Y is nowhere found within X. Or, if X and Y are both BLOBs, then INSTR(X,Y) returns one more than the number bytes prior to the first occurrence of Y, or 0 if Y does not occur anywhere within X. If both arguments X and Y to INSTR(X,Y) are non-NULL and are not BLOBs then both are interpreted as strings. If either X or Y are NULL in INSTR(X,Y) then the result is NULL. ", + "LAST_INSERT_ROWID() \nDescription: The LAST_INSERT_ROWID() function returns theROWIDof the last row insert from the database connection which invoked the function. The LAST_INSERT_ROWID() SQL function is a wrapper around thesqlite3_last_insert_rowid()C/C++ interface function. ", + "LENGTH(X) \nDescription: For a string value X, the LENGTH(X) function returns the number of characters (not bytes) in X prior to the first NUL character. Since SQLite strings do not normally contain NUL characters, the LENGTH(X) function will usually return the total number of characters in the string X. For a blob value X, LENGTH(X) returns the number of bytes in the blob. If X is NULL then LENGTH(X) is NULL. If X is numeric then LENGTH(X) returns the length of a string representation of X.Note that for strings, the LENGTH(X) function returns thecharacterlength of the string, not the byte length. The character length is the number of characters in the string. The character length is always different from the byte length for UTF-16 strings, and can be different from the byte length for UTF-8 strings if the string contains multi-byte characters. Use theoctet_length()function to find the byte length of a string.For BLOB values, LENGTH(X) always returns the byte-length of the BLOB.For string values, LENGTH(X) must read the entire string into memory in order to compute the character length. But for BLOB values, that is not necessary as SQLite knows how many bytes are in the BLOB. Hence, for multi-megabyte values, the LENGTH(X) function is usually much faster for BLOBs than for strings, since it does not need to load the value into memory. ", + "LIKE(X,Y) or LIKE(X,Y,Z) \nDescription: The LIKE() function is used to implement the \"Y LIKE X [ESCAPE Z]\" expression. If the optional ESCAPE clause is present, then the LIKE() function is invoked with three arguments. Otherwise, it is invoked with two arguments only. Note that the X and Y parameters are reversed in the LIKE() function relative to the infixLIKEoperator. X is the pattern and Y is the string to match against that pattern. Hence, the following expressions are equivalent:name LIKE '%neon%' LIKE('%neon%',name)Thesqlite3_create_function()interface can be used to override the LIKE() function and thereby change the operation of theLIKEoperator. When overriding the LIKE() function, it may be important to override both the two and three argument versions of the LIKE() function. Otherwise, different code may be called to implement theLIKEoperator depending on whether or not an ESCAPE clause was specified. ", + "LIKELIHOOD(X,Y) \nDescription: The LIKELIHOOD(X,Y) function returns argument X unchanged. The value Y in LIKELIHOOD(X,Y) must be a floating point constant between 0.0 and 1.0, inclusive. The LIKELIHOOD(X) function is a no-op that the code generator optimizes away so that it consumes no CPU cycles during run-time (that is, during calls tosqlite3_step()). The purpose of the LIKELIHOOD(X,Y) function is to provide a hint to the query planner that the argument X is a boolean that is true with a probability of approximately Y. Theunlikely(X)function is short-hand for LIKELIHOOD(X,0.0625). Thelikely(X)function is short-hand for LIKELIHOOD(X,0.9375). ", + "LIKELY(X) \nDescription: The LIKELY(X) function returns the argument X unchanged. The LIKELY(X) function is a no-op that the code generator optimizes away so that it consumes no CPU cycles at run-time (that is, during calls tosqlite3_step()). The purpose of the LIKELY(X) function is to provide a hint to the query planner that the argument X is a boolean value that is usually true. The LIKELY(X) function is equivalent tolikelihood(X,0.9375). See also:unlikely(X). ", + "LOAD_EXTENSION(X) or LOAD_EXTENSION(X,Y) \nDescription: The LOAD_EXTENSION(X,Y) function loadsSQLite extensionsout of the shared library file named X using the entry point Y. The result of LOAD_EXTENSION() is always a NULL. If Y is omitted then the default entry point name is used. The LOAD_EXTENSION() function raises an exception if the extension fails to load or initialize correctly.The LOAD_EXTENSION() function will fail if the extension attempts to modify or delete an SQL function or collating sequence. The extension can add new functions or collating sequences, but cannot modify or delete existing functions or collating sequences because those functions and/or collating sequences might be used elsewhere in the currently running SQL statement. To load an extension that changes or deletes functions or collating sequences, use thesqlite3_load_extension()C-language API.For security reasons, extension loading is disabled by default and must be enabled by a prior call tosqlite3_enable_load_extension(). ", + "LOWER(X) \nDescription: The LOWER(X) function returns a copy of string X with all ASCII characters converted to lower case. The default built-in LOWER() function works for ASCII characters only. To do case conversions on non-ASCII characters, load the ICU extension. ", + "LTRIM(X) or LTRIM(X,Y) \nDescription: The LTRIM(X,Y) function returns a string formed by removing any and all characters that appear in Y from the left side of X. If the Y argument is omitted, LTRIM(X) removes spaces from the left side of X. ", + "MAX(X,Y,...) \nDescription: The multi-argument MAX() function returns the argument with the maximum value, or return NULL if any argument is NULL. The multi-argument MAX() function searches its arguments from left to right for an argument that defines a collating function and uses that collating function for all string comparisons. If none of the arguments to MAX() define a collating function, then the BINARY collating function is used. Note thatmax()is a simple function when it has 2 or more arguments but operates as anaggregate functionif given only a single argument. ", + "MIN(X,Y,...) \nDescription: The multi-argument MIN() function returns the argument with the minimum value. The multi-argument MIN() function searches its arguments from left to right for an argument that defines a collating function and uses that collating function for all string comparisons. If none of the arguments to MIN() define a collating function, then the BINARY collating function is used. Note thatmin()is a simple function when it has 2 or more arguments but operates as anaggregate functionif given only a single argument. ", + "NULLIF(X,Y) \nDescription: The NULLIF(X,Y) function returns its first argument if the arguments are different and NULL if the arguments are the same. The NULLIF(X,Y) function searches its arguments from left to right for an argument that defines a collating function and uses that collating function for all string comparisons. If neither argument to NULLIF() defines a collating function then the BINARY collating function is used. ", + "OCTET_LENGTH(X) \nDescription: The OCTET_LENGTH(X) function returns the number of bytes in the encoding of text string X. If X is NULL then OCTET_LENGTH(X) returns NULL. If X is a BLOB value, then OCTET_LENGTH(X) is the same aslength(X). If X is a numeric value, then OCTET_LENGTH(X) returns the number of bytes in a text rendering of that number.Because OCTET_LENGTH(X) returns the number of bytes in X, not the number of characters, the value returned depends on the database encoding. The OCTET_LENGTH() function can return different answers for the same input string if the database encoding is UTF16 instead of UTF8.If argument X is a table column and the value is of type text or blob, then OCTET_LENGTH(X) avoids reading the content of X from disk, as the byte length can be computed from metadata. Thus, OCTET_LENGTH(X) is efficient even if X is a column containing a multi-megabyte text or blob value. ", + "PRINTF(FORMAT,...) \nDescription: The PRINTF() SQL function is an alias for theformat() SQL function. The format() SQL function was originally named PRINTF(). But the name was later changed to format() for compatibility with other database engines. The PRINTF() name is retained as an alias so as not to break legacy code. ", + "QUOTE(X) \nDescription: The QUOTE(X) function returns the text of an SQL literal which is the value of its argument suitable for inclusion into an SQL statement. Strings are surrounded by single-quotes with escapes on interior quotes as needed. BLOBs are encoded as hexadecimal literals. Strings with embedded NUL characters cannot be represented as string literals in SQL and hence the returned string literal is truncated prior to the first NUL. ", + "RANDOM() \nDescription: The RANDOM() function returns a pseudo-random integer between -9223372036854775808 and +9223372036854775807. ", + "RANDOMBLOB(N) \nDescription: The RANDOMBLOB(N) function return an N-byte blob containing pseudo-random bytes. If N is less than 1 then a 1-byte random blob is returned.Hint: applications can generate globally unique identifiers using this function together withhex()and/orlower()like this:hex(randomblob(16))lower(hex(randomblob(16))) ", + "REPLACE(X,Y,Z) \nDescription: The REPLACE(X,Y,Z) function returns a string formed by substituting string Z for every occurrence of string Y in string X. TheBINARYcollating sequence is used for comparisons. If Y is an empty string then return X unchanged. If Z is not initially a string, it is cast to a UTF-8 string prior to processing. ", + "ROUND(X) or ROUND(X,Y) \nDescription: The ROUND(X,Y) function returns a floating-point value X rounded to Y digits to the right of the decimal point. If the Y argument is omitted or negative, it is taken to be 0. ", + "RTRIM(X) or RTRIM(X,Y) \nDescription: The RTRIM(X,Y) function returns a string formed by removing any and all characters that appear in Y from the right side of X. If the Y argument is omitted, RTRIM(X) removes spaces from the right side of X. ", + "SIGN(X) \nDescription: The SIGN(X) function returns -1, 0, or +1 if the argument X is a numeric value that is negative, zero, or positive, respectively. If the argument to SIGN(X) is NULL or is a string or blob that cannot be losslessly converted into a number, then SIGN(X) returns NULL. ", + "SOUNDEX(X) \nDescription: The SOUNDEX(X) function returns a string that is the soundex encoding of the string X. The string \"?000\" is returned if the argument is NULL or contains no ASCII alphabetic characters. This function is omitted from SQLite by default. It is only available if theSQLITE_SOUNDEXcompile-time option is used when SQLite is built. ", + "SQLITE_COMPILEOPTION_GET(N) \nDescription: The SQLITE_COMPILEOPTION_GET() SQL function is a wrapper around thesqlite3_compileoption_get()C/C++ function. This routine returns the N-th compile-time option used to build SQLite or NULL if N is out of range. See also thecompile_options pragma. ", + "SQLITE_COMPILEOPTION_USED(X) \nDescription: The SQLITE_COMPILEOPTION_USED() SQL function is a wrapper around thesqlite3_compileoption_used()C/C++ function. When the argument X to SQLITE_COMPILEOPTION_USED(X) is a string which is the name of a compile-time option, this routine returns true (1) or false (0) depending on whether or not that option was used during the build. ", + "SQLITE_OFFSET(X) \nDescription: The SQLITE_OFFSET(X) function returns the byte offset in the database file for the beginning of the record from which value would be read. If X is not a column in an ordinary table, then SQLITE_OFFSET(X) returns NULL. The value returned by SQLITE_OFFSET(X) might reference either the original table or an index, depending on the query. If the value X would normally be extracted from an index, the SQLITE_OFFSET(X) returns the offset to the corresponding index record. If the value X would be extracted from the original table, then SQLITE_OFFSET(X) returns the offset to the table record.The SQLITE_OFFSET(X) SQL function is only available if SQLite is built using the-DSQLITE_ENABLE_OFFSET_SQL_FUNCcompile-time option. ", + "SQLITE_SOURCE_ID() \nDescription: The SQLITE_SOURCE_ID() function returns a string that identifies the specific version of the source code that was used to build the SQLite library. The string returned by SQLITE_SOURCE_ID() is the date and time that the source code was checked in followed by the SHA3-256 hash for that check-in. This function is an SQL wrapper around thesqlite3_sourceid()C interface. ", + "SQLITE_VERSION() \nDescription: The SQLITE_VERSION() function returns the version string for the SQLite library that is running. This function is an SQL wrapper around thesqlite3_libversion()C-interface. ", + "SUBSTR(X,Y,Z) or SUBSTR(X,Y) or SUBSTRING(X,Y,Z) or SUBSTRING(X,Y) \nDescription: The SUBSTR(X,Y,Z) function returns a substring of input string X that begins with the Y-th character and which is Z characters long. If Z is omitted then SUBSTR(X,Y) returns all characters through the end of the string X beginning with the Y-th. The left-most character of X is number 1. If Y is negative then the first character of the substring is found by counting from the right rather than the left. If Z is negative then the abs(Z) characters preceding the Y-th character are returned. If X is a string then characters indices refer to actual UTF-8 characters. If X is a BLOB then the indices refer to bytes.\"substring()\" is an alias for \"substr()\" beginning with SQLite version 3.34. ", + "TOTAL_CHANGES() \nDescription: The TOTAL_CHANGES() function returns the number of row changes caused by INSERT, UPDATE or DELETE statements since the current database connection was opened. This function is a wrapper around thesqlite3_total_changes64()C/C++ interface. ", + "TRIM(X) or TRIM(X,Y) \nDescription: The TRIM(X,Y) function returns a string formed by removing any and all characters that appear in Y from both ends of X. If the Y argument is omitted, TRIM(X) removes spaces from both ends of X. ", + "TYPEOF(X) \nDescription: The TYPEOF(X) function returns a string that indicates thedatatypeof the expression X: \"null\", \"integer\", \"real\", \"text\", or \"blob\". ", + "UNHEX(X) or UNHEX(X,Y) \nDescription: The UNHEX(X,Y) function returns a BLOB value which is the decoding of the hexadecimal string X. If X contains any characters that are not hexadecimal digits and which are not in Y, then UNHEX(X,Y) returns NULL. If Y is omitted, it is understood to be an empty string and hence X must be a pure hexadecimal string. All hexadecimal digits in X must occur in pairs, with both digits of each pair beginning immediately adjacent to one another, or else UNHEX(X,Y) returns NULL. If either parameter X or Y is NULL, then UNHEX(X,Y) returns NULL. The X input may contain an arbitrary mix of upper and lower case hexadecimal digits. Hexadecimal digits in Y have no affect on the translation of X. Only characters in Y that are not hexadecimal digits are ignored in X.See also:hex() ", + "UNICODE(X) \nDescription: The UNICODE(X) function returns the numeric unicode code point corresponding to the first character of the string X. If the argument to UNICODE(X) is not a string then the result is undefined. ", + "UNLIKELY(X) \nDescription: The UNLIKELY(X) function returns the argument X unchanged. The UNLIKELY(X) function is a no-op that the code generator optimizes away so that it consumes no CPU cycles at run-time (that is, during calls tosqlite3_step()). The purpose of the UNLIKELY(X) function is to provide a hint to the query planner that the argument X is a boolean value that is usually not true. The UNLIKELY(X) function is equivalent tolikelihood(X, 0.0625). ", + "UPPER(X) \nDescription: The UPPER(X) function returns a copy of input string X in which all lower-case ASCII characters are converted to their upper-case equivalent. ", + "ZEROBLOB(N) \nDescription: The ZEROBLOB(N) function returns a BLOB consisting of N bytes of 0x00. SQLite manages these zeroblobs very efficiently. Zeroblobs can be used to reserve space for a BLOB that is later written usingincremental BLOB I/O. This SQL function is implemented using thesqlite3_result_zeroblob()routine from the C/C++ interface. ", + "AVG(X) \nDescription: The AVG() function returns the average value of all non-NULLXwithin a group. String and BLOB values that do not look like numbers are interpreted as 0. The result of AVG() is always a floating point value whenever there is at least one non-NULL input even if all inputs are integers. The result of AVG() is NULL if there are no non-NULL inputs. The result of AVG() is computed astotal()/count()so all of the constraints that apply tototal()also apply to AVG(). ", + "COUNT(X) or COUNT(*) \nDescription: The COUNT(X) function returns a count of the number of times thatXis not NULL in a group. The COUNT(*) function (with no arguments) returns the total number of rows in the group. ", + "GROUP_CONCAT(X) or GROUP_CONCAT(X,Y) or STRING_AGG(X,Y) \nDescription: The GROUP_CONCAT() function returns a string which is the concatenation of all non-NULL values ofX. If parameterYis present then it is used as the separator between instances ofX.A comma (\",\") is used as the separator ifYis omitted.The string_agg(X,Y) function is an alias for GROUP_CONCAT(X,Y). String_agg() is compatible with PostgreSQL and SQL-Server and GROUP_CONCAT() is compatible with MySQL.The order of the concatenated elements is arbitrary unless an ORDER BY argument is included immediately after the last parameter. ", + "MAX(X) \nDescription: The MAX() aggregate function returns the maximum value of all values in the group. The maximum value is the value that would be returned last in an ORDER BY on the same column. Aggregate MAX() returns NULL if and only if there are no non-NULL values in the group. ", + "MIN(X) \nDescription: The MIN() aggregate function returns the minimum non-NULL value of all values in the group. The minimum value is the first non-NULL value that would appear in an ORDER BY of the column. Aggregate MIN() returns NULL if and only if there are no non-NULL values in the group. ", + "SUM(X) or TOTAL(X) \nDescription: The SUM() and TOTAL() aggregate functions return the sum of all non-NULL values in the group. If there are no non-NULL input rows then SUM() returns NULL but TOTAL() returns 0.0. NULL is not normally a helpful result for the sum of no rows but the SQL standard requires it and most other SQL database engines implement SUM() that way so SQLite does it in the same way in order to be compatible. The non-standard TOTAL() function is provided as a convenient way to work around this design problem in the SQL language. ", + "ROW_NUMBER() \nDescription: The number of the row within the current partition. Rows are numbered starting from 1 in the order defined by the ORDER BY clause in the window definition, or in arbitrary order otherwise. ", + "RANK() \nDescription: The row_number() of the first peer in each group - the rank of the current row with gaps. If there is no ORDER BY clause, then all rows are considered peers and this function always returns 1. ", + "DENSE_RANK() \nDescription: The number of the current row's peer group within its partition - the rank of the current row without gaps. Rows are numbered starting from 1 in the order defined by the ORDER BY clause in the window definition. If there is no ORDER BY clause, then all rows are considered peers and this function always returns 1. ", + "PERCENT_RANK() \nDescription: Despite the name, this function always returns a value between 0.0 and 1.0 equal to (rank- 1)/(partition-rows- 1), whererankis the value returned by built-in window function rank() andpartition-rowsis the total number of rows in the partition. If the partition contains only one row, this function returns 0.0. ", + "CUME_DIST() \nDescription: The cumulative distribution. Calculated asrow-number/partition-rows, whererow-numberis the value returned by row_number() for the last peer in the group andpartition-rowsthe number of rows in the partition. ", + "NTILE(N) \nDescription: ArgumentNis handled as an integer. This function divides the partition into N groups as evenly as possible and assigns an integer between 1 andNto each group, in the order defined by the ORDER BY clause, or in arbitrary order otherwise. If necessary, larger groups occur first. This function returns the integer value assigned to the group that the current row is a part of. ", + "LAG(expr) or LAG(expr, offset) or LAG(expr, offset, default) \nDescription: The first form of the LAG() function returns the result of evaluating expressionexpragainst the previous row in the partition. Or, if there is no previous row (because the current row is the first), NULL. ", + "LEAD(expr) or LEAD(expr, offset) or LEAD(expr, offset, default) \nDescription: The first form of the LEAD() function returns the result of evaluating expressionexpragainst the next row in the partition. Or, if there is no next row (because the current row is the last), NULL. ", + "FIRST_VALUE(expr) \nDescription: This built-in window function calculates the window frame for each row in the same way as an aggregate window function. It returns the value ofexprevaluated against the first row in the window frame for each row. ", + "LAST_VALUE(expr) \nDescription: This built-in window function calculates the window frame for each row in the same way as an aggregate window function. It returns the value ofexprevaluated against the last row in the window frame for each row. ", + "NTH_VALUE(expr, N) \nDescription: This built-in window function calculates the window frame for each row in the same way as an aggregate window function. It returns the value ofexprevaluated against the rowNof the window frame. Rows are numbered within the window frame starting from 1 in the order defined by the ORDER BY clause if one is present, or in arbitrary order otherwise. If there is noNth row in the partition, then NULL is returned. ", + "ACOS(X) \nDescription: Return the arccosine of X. The result is in radians. ", + "ACOSH(X) \nDescription: Return the hyperbolic arccosine of X. ", + "ASIN(X) \nDescription: Return the arcsine of X. The result is in radians. ", + "ASINH(X) \nDescription: Return the hyperbolic arcsine of X. ", + "ATAN(X) \nDescription: Return the arctangent of X. The result is in radians. ", + "ATAN2(Y,X) \nDescription: Return the arctangent of Y/X. The result is in radians. The result is placed into correct quadrant depending on the signs of X and Y. ", + "ATANH(X) \nDescription: Return the hyperbolic arctangent of X. ", + "CEIL(X) or CEILING(X) \nDescription: Return the first representable integer value greater than or equal to X. For positive values of X, this routine rounds away from zero. For negative values of X, this routine rounds toward zero. ", + "COS(X) \nDescription: Return the cosine of X. X is in radians. ", + "COSH(X) \nDescription: Return the hyperbolic cosine of X. ", + "DEGREES(X) \nDescription: Convert value X from radians into degrees. ", + "EXP(X) \nDescription: Computee(Euler's number, approximately 2.71828182845905) raised to the power X. ", + "FLOOR(X) \nDescription: Return the first representable integer value less than or equal to X. For positive numbers, this function rounds toward zero. For negative numbers, this function rounds away from zero. ", + "LN(X) \nDescription: Return the natural logarithm of X. ", + "LOG(X) or LOG10(X) or LOG(B,X) \nDescription: Return the base-10 logarithm for X. Or, for the two-argument version, return the base-B logarithm of X.Compatibility note: SQLite works like PostgreSQL in that the LOG() function computes a base-10 logarithm. Most other SQL database engines compute a natural logarithm for LOG(). In the two-argument version of LOG(B,X), the first argument is the base and the second argument is the operand. This is the same as in PostgreSQL and MySQL, but is reversed from SQL Server which uses the second argument as the base and the first argument as the operand. ", + "LOG2(X) \nDescription: Return the logarithm base-2 for the number X. ", + "MOD(X,Y) \nDescription: Return the remainder after dividing X by Y. This is similar to the '%' operator, except that it works for non-integer arguments. ", + "PI() \nDescription: Return an approximation for π. ", + "POW(X,Y) or POWER(X,Y) \nDescription: Compute X raised to the power Y. ", + "RADIANS(X) \nDescription: Convert X from degrees into radians. ", + "SIN(X) \nDescription: Return the sine of X. X is in radians. ", + "SINH(X) \nDescription: Return the hyperbolic sine of X. ", + "SQRT(X) \nDescription: Return the square root of X. NULL is returned if X is negative. ", + "TAN(X) \nDescription: Return the tangent of X. X is in radians. ", + "TANH(X) \nDescription: Return the hyperbolic tangent of X. ", + "TRUNC(X) \nDescription: Return the representable integer in between X and 0 (inclusive) that is furthest away from zero. Or, in other words, return the integer part of X, rounding toward zero. The TRUNC() function is similar toceiling(X)andfloor(X)except that it always rounds toward zero whereas ceiling(X) and floor(X) round up and down, respectively. ", + "DATE(time-value, modifier, modifier, ...) \nDescription: Returns the date as text in this format: YYYY-MM-DD. ", + "TIME(time-value, modifier, modifier, ...) \nDescription: Returns the time as text in formatted as HH:MM:SS or as HH:MM:SS.SSS if the subsec modifier is used. ", + "DATETIME(time-value, modifier, modifier, ...) \nDescription: Returns the date and time formatted as YYYY-MM-DD HH:MM:SS or as YYYY-MM-DD HH:MM:SS.SSS if the subsec modifier is used. ", + "JULIANDAY(time-value, modifier, modifier, ...) \nDescription: Returns the Julian day - the fractional number of days since noon in Greenwich on November 24, 4714 B.C. (Proleptic Gregorian calendar). ", + "UNIXEPOCH(time-value, modifier, modifier, ...) \nDescription: Returns a unix timestamp - the number of seconds since 1970-01-01 00:00:00 UTC. The UNIXEPOCH() function normally returns an integer number of seconds, but with the optional subsec modifier it will return a floating point number which is the fractional number of seconds. ", + "STRFTIME(format, time-value, modifier, modifier, ...) \nDescription: Returns the date formatted according to the format string specified as the first argument. The format string supports the most common substitutions found in the STRFTIME() function from the standard C library plus two new substitutions, %f and %J. ", + "TIMEDIFF(time-value, time-value) \nDescription: Returns a string that describes the amount of time that must be added to B in order to reach time A. The format of the TIMEDIFF() result is designed to be human-readable. " + ] + + def _sql_func_template(self, sql_funcs: str) -> str: + template = """### SQL Functions + You may consider one or more of the following SQL functions while generating the query: + {sql_funcs} + Important tips: + Except for the functions listed above, you may use any other functions as long as they conform to the syntax of the database engine. + """ + return template.format(sql_funcs=sql_funcs) + + def _insert_stmts_template(self, insert_statements: str) -> str: + template = '''### INSERT INTO Statements + Below are several `INSERT INTO` statements. Use these to help generate predicates (i.e., `WHERE` clauses) in your SQL query: + {insert_statements} + ''' + return template.format(insert_statements=insert_statements) + + def _sql_synthesis_prompt(self, schema_str: str, sql_function_prompt: str, db_value_prompt: str, complexity: str, criterion: str, db_engine: str, column_count: int) -> str: + template = '''**Task Overview** + Create an executable SQL query based on the provided information. + + **Database Schema** + {schema_str} + + {sql_function_prompt} + + {db_value_prompt} + + **SQL Query Complexity** + Ensure the SQL query matches the {complexity} level, defined as follows: + {criterion} + + **Output Format Requirements** + Enclose the SQL query in a code block: + ```sql + -- Your SQL query here + ``` + + **SQL Query Requirements** + 1. Use the syntax specific to the {db_engine} database engine. + 2. Incorporate advanced functions if appropriate, but they are not mandatory. + 3. Address real-world data analysis needs. Avoid trivial or nonsensical queries. + 4. (Very important) Ensure the final SQL query selects {column_count} columns. + + **Answer** + Let's proceed step by step. + ''' + return template.format( + schema_str=schema_str, + sql_function_prompt=sql_function_prompt.strip(), + db_value_prompt=db_value_prompt.strip(), + complexity=complexity, + criterion=criterion.strip(), + db_engine=db_engine, + column_count=column_count + ) + + def build_prompt(self, insert_statements: List[str], create_statements: List[str], db_engine: str) -> str: + complexity = random.sample(["Simple", "Moderate", "Complex", "Highly Complex"], 1)[0] + if len(insert_statements) == 0: + db_value_prompt = "" + else: + if len(insert_statements) > 4: + insert_statements = random.sample(insert_statements, 4) + db_value_prompt = self._insert_stmts_template( + insert_statements="\n\n".join(insert_statements) + ) + + function_num = random.randint(0, 2) + if function_num == 0: + sql_function_prompt = "### SQL Functions\nYou can use any function supported by the database engine." + else: + sql_funcs = "" + sampled_functions = random.sample(self.functions, function_num) + for idx, func in enumerate(sampled_functions): + sql_funcs += f"Function {idx + 1}:\n{func.strip()}\n" + sql_function_prompt = self._sql_func_template(sql_funcs=sql_funcs) + + column_count = np.random.geometric(0.6, 1)[0] + prompt = self._sql_synthesis_prompt( + schema_str="\n\n".join(create_statements), + sql_function_prompt=sql_function_prompt.strip(), + db_value_prompt=db_value_prompt.strip(), + complexity=complexity, + criterion=self.complexity2criterion[complexity].strip(), + db_engine=db_engine, + column_count=column_count + ) + return prompt, complexity + + +@PROMPT_REGISTRY.register() +class SelectVecSQLGeneratorPrompt(PromptABC): + def __init__(self): + self.simple_vec_criterion = '''**Criteria:** + Simple KNN queries in SQLite-vec may satisfy one or more of the following criteria: + - Basic vector similarity search on a single table + - Uses simple `MATCH` operator with target vector + - Contains basic `LIMIT` or `AND` clause to restrict results after `MATCH` operator + - No joins or complex filtering beyond the vector search + + **Example of Simple KNN Query:** + ```sql + SELECT rowid, location_embedding + FROM vec_table + WHERE location_embedding MATCH lembed('all-MiniLM-L6-v2',"572 Main Street Los Angeles, CA 90210 USA") + ORDER BY distance + LIMIT 1; + ```''' + + self.moderate_vec_criterion = '''**Criteria:** + Moderate KNN queries in SQLite-vec may satisfy one or more of the following criteria: + - Includes simple joins with metadata tables + - Contains basic post-filtering of vector results + - May use multiple vector columns in query + + **Example of Moderate KNN Query:** + ```sql + SELECT d.doc_id, d.title, d.content + FROM documents d + JOIN categories c ON d.category_id = c.id + WHERE d.content_embedding MATCH lembed('all-MiniLM-L6-v2',"OmniSQL is a unified SQL engine that integrates Vector search and LLM augmentation.") + AND k = 2 + AND c.name = 'science' + ORDER BY d.distance; + ```''' + + self.complex_vec_criterion = '''**Criteria:** + Complex KNN queries in SQLite-vec may satisfy one or more of the following criteria: + - Combines vector search with complex joins + - Uses CTEs to organize vector search logic + - Contains hybrid search (vector + full-text) + - Implements multi-stage filtering of results + - May use window functions with vector results + - Includes complex distance threshold conditions + + **Example of Complex KNN Query:** + ```sql + WITH HighWDVOATeams AS ( + SELECT team_id, team_name + FROM teams + WHERE team_id IN ( + SELECT team_id + FROM team_metrics + WHERE wdvoa > 30 AND season = 2019 + ) + ), + SimilarTeams AS ( + SELECT team_id, team_name, distance + FROM teams + WHERE team_name_embedding MATCH lembed('all-MiniLM-L6-v2',"Woven Shadows") + ORDER BY distance + LIMIT 5 + ) + SELECT h.team_name, AVG(p.confidence_level) AS average_confidence + FROM HighWDVOATeams h + JOIN SimilarTeams s ON h.team_id = s.team_id + JOIN game_predictions p ON p.game_id IN ( + SELECT game_id + FROM games + WHERE home_team_id = h.team_id OR away_team_id = h.team_id + ) + GROUP BY h.team_name + HAVING average_confidence > 0.7; + ```''' + + self.highly_complex_vec_criterion = '''**Criteria:** + Highly complex KNN queries in SQLite-vec may satisfy one or more of the following criteria: + - Uses multiple CTEs with vector operations + - Combines multiple vector searches in one query + - Implements advanced hybrid search techniques + - Contains recursive vector search patterns + - Uses complex window functions over vector results + - May involve vector aggregation operations + - Implements custom distance calculations + + **Example of Highly Complex KNN Query:** + ```sql + WITH BettingAnalysis AS ( + SELECT + g.game_id, + AVG(bd.betting_spread) AS avg_initial_spread, + COUNT(*) AS total_bets + FROM games g + JOIN betting_data bd ON g.game_id = bd.game_id + GROUP BY g.game_id + ), + PredictionAnalysis AS ( + SELECT + gp.game_id, + AVG(gp.confidence_level) AS avg_confidence, + SUM(CASE WHEN gp.make_pick = 1 AND g.pick_right = 1 THEN 1 ELSE 0 END) AS correct_predictions + FROM games g + JOIN game_predictions gp ON g.game_id = gp.game_id + GROUP BY gp.game_id + ), + TeamPerformance AS ( + SELECT + tm.team_id, + tm.season, + AVG(tm.wdvoa) AS avg_wdvoa + FROM team_metrics tm + GROUP BY tm.team_id, tm.season + ), + LocationSimilarity AS ( + SELECT + g.game_id, + g.location, + vec.distance AS location_similarity + FROM games g + JOIN ( + SELECT rowid, distance + FROM games + WHERE location_embedding MATCH lembed('all-MiniLM-L6-v2',"New York") + ORDER BY distance + LIMIT 5 + ) AS vec ON g.rowid = vec.rowid + ) + SELECT + g.game_id, + ba.avg_initial_spread, + pa.avg_confidence, + tp.avg_wdvoa, + ls.location_similarity + FROM games g + JOIN BettingAnalysis ba ON g.game_id = ba.game_id + JOIN PredictionAnalysis pa ON g.game_id = pa.game_id + JOIN TeamPerformance tp ON g.home_team_id = tp.team_id + JOIN LocationSimilarity ls ON g.game_id = ls.game_id + WHERE pa.correct_predictions > 2 + ORDER BY g.game_id; + ```''' + + self.complexity2criterion_vec = { + "Simple": self.simple_vec_criterion, + "Moderate": self.moderate_vec_criterion, + "Complex": self.complex_vec_criterion, + "Highly Complex": self.highly_complex_vec_criterion + } + + + self.functions = [ + "ABS(X) \nDescription: The ABS(X) function returns the absolute value of the numeric argument X. Abs(X) returns NULL if X is NULL. Abs(X) returns 0.0 if X is a string or blob that cannot be converted to a numeric value. If X is the integer -9223372036854775808 then ABS(X) throws an integer overflow error since there is no equivalent positive 64-bit two complement value. ", + "CHANGES() \nDescription: The CHANGES() function returns the number of database rows that were changed or inserted or deleted by the most recently completed INSERT, DELETE, or UPDATE statement, exclusive of statements in lower-level triggers. The CHANGES() SQL function is a wrapper around thesqlite3_changes64()C/C++ function and hence follows the same rules for counting changes. ", + "CHAR(X1,X2,...,XN) \nDescription: The CHAR(X1,X2,...,XN) function returns a string composed of characters having the unicode code point values of integers X1 through XN, respectively. ", + "COALESCE(X,Y,...) \nDescription: The COALESCE() function returns a copy of its first non-NULL argument, or NULL if all arguments are NULL. Coalesce() must have at least 2 arguments. ", + "CONCAT(X,...) \nDescription: The CONCAT(...) function returns a string which is the concatenation of the string representation of all of its non-NULL arguments. If all arguments are NULL, then CONCAT() returns an empty string. ", + "CONCAT_WS(SEP,X,...) \nDescription: The CONCAT_WS(SEP,...) function returns a string that is the concatenation of all non-null arguments beyond the first argument, using the text value of the first argument as a separator. If the first argument is NULL, then CONCAT_WS() returns NULL. If all arguments other than the first are NULL, then CONCAT_WS() returns an empty string. ", + "FORMAT(FORMAT,...) \nDescription: The FORMAT(FORMAT,...) SQL function works like thesqlite3_mprintf()C-language function and the printf() function from the standard C library. The first argument is a format string that specifies how to construct the output string using values taken from subsequent arguments. If the FORMAT argument is missing or NULL then the result is NULL. The %n format is silently ignored and does not consume an argument. The %p format is an alias for %X. The %z format is interchangeable with %s. If there are too few arguments in the argument list, missing arguments are assumed to have a NULL value, which is translated into 0 or 0.0 for numeric formats or an empty string for %s. See thebuilt-in printf()documentation for additional information. ", + "GLOB(X,Y) \nDescription: The GLOB(X,Y) function is equivalent to the expression \"Y GLOB X\". Note that the X and Y arguments are reversed in the GLOB() function relative to the infixGLOBoperator. Y is the string and X is the pattern. So, for example, the following expressions are equivalent:name GLOB '*helium*' GLOB('*helium*',name)If thesqlite3_create_function()interface is used to override the GLOB(X,Y) function with an alternative implementation then theGLOBoperator will invoke the alternative implementation. ", + "HEX(X) \nDescription: The HEX() function interprets its argument as a BLOB and returns a string which is the upper-case hexadecimal rendering of the content of that blob.If the argumentXin \"hex(X)\" is an integer or floating point number, then \"interprets its argument as a BLOB\" means that the binary number is first converted into a UTF8 text representation, then that text is interpreted as a BLOB. Hence, \"hex(12345678)\" renders as \"3132333435363738\" not the binary representation of the integer value \"0000000000BC614E\".See also:unhex() ", + "IFNULL(X,Y) \nDescription: The IFNULL() function returns a copy of its first non-NULL argument, or NULL if both arguments are NULL. Ifnull() must have exactly 2 arguments. The IFNULL() function is equivalent tocoalesce()with two arguments. ", + "IIF(X,Y,Z) \nDescription: The IIF(X,Y,Z) function returns the value Y if X is true, and Z otherwise. The IIF(X,Y,Z) function is logically equivalent to and generates the samebytecodeas theCASE expression\"CASE WHEN X THEN Y ELSE Z END\". ", + "INSTR(X,Y) \nDescription: The INSTR(X,Y) function finds the first occurrence of string Y within string X and returns the number of prior characters plus 1, or 0 if Y is nowhere found within X. Or, if X and Y are both BLOBs, then INSTR(X,Y) returns one more than the number bytes prior to the first occurrence of Y, or 0 if Y does not occur anywhere within X. If both arguments X and Y to INSTR(X,Y) are non-NULL and are not BLOBs then both are interpreted as strings. If either X or Y are NULL in INSTR(X,Y) then the result is NULL. ", + "LAST_INSERT_ROWID() \nDescription: The LAST_INSERT_ROWID() function returns theROWIDof the last row insert from the database connection which invoked the function. The LAST_INSERT_ROWID() SQL function is a wrapper around thesqlite3_last_insert_rowid()C/C++ interface function. ", + "LENGTH(X) \nDescription: For a string value X, the LENGTH(X) function returns the number of characters (not bytes) in X prior to the first NUL character. Since SQLite strings do not normally contain NUL characters, the LENGTH(X) function will usually return the total number of characters in the string X. For a blob value X, LENGTH(X) returns the number of bytes in the blob. If X is NULL then LENGTH(X) is NULL. If X is numeric then LENGTH(X) returns the length of a string representation of X.Note that for strings, the LENGTH(X) function returns thecharacterlength of the string, not the byte length. The character length is the number of characters in the string. The character length is always different from the byte length for UTF-16 strings, and can be different from the byte length for UTF-8 strings if the string contains multi-byte characters. Use theoctet_length()function to find the byte length of a string.For BLOB values, LENGTH(X) always returns the byte-length of the BLOB.For string values, LENGTH(X) must read the entire string into memory in order to compute the character length. But for BLOB values, that is not necessary as SQLite knows how many bytes are in the BLOB. Hence, for multi-megabyte values, the LENGTH(X) function is usually much faster for BLOBs than for strings, since it does not need to load the value into memory. ", + "LIKE(X,Y) or LIKE(X,Y,Z) \nDescription: The LIKE() function is used to implement the \"Y LIKE X [ESCAPE Z]\" expression. If the optional ESCAPE clause is present, then the LIKE() function is invoked with three arguments. Otherwise, it is invoked with two arguments only. Note that the X and Y parameters are reversed in the LIKE() function relative to the infixLIKEoperator. X is the pattern and Y is the string to match against that pattern. Hence, the following expressions are equivalent:name LIKE '%neon%' LIKE('%neon%',name)Thesqlite3_create_function()interface can be used to override the LIKE() function and thereby change the operation of theLIKEoperator. When overriding the LIKE() function, it may be important to override both the two and three argument versions of the LIKE() function. Otherwise, different code may be called to implement theLIKEoperator depending on whether or not an ESCAPE clause was specified. ", + "LIKELIHOOD(X,Y) \nDescription: The LIKELIHOOD(X,Y) function returns argument X unchanged. The value Y in LIKELIHOOD(X,Y) must be a floating point constant between 0.0 and 1.0, inclusive. The LIKELIHOOD(X) function is a no-op that the code generator optimizes away so that it consumes no CPU cycles during run-time (that is, during calls tosqlite3_step()). The purpose of the LIKELIHOOD(X,Y) function is to provide a hint to the query planner that the argument X is a boolean that is true with a probability of approximately Y. Theunlikely(X)function is short-hand for LIKELIHOOD(X,0.0625). Thelikely(X)function is short-hand for LIKELIHOOD(X,0.9375). ", + "LIKELY(X) \nDescription: The LIKELY(X) function returns the argument X unchanged. The LIKELY(X) function is a no-op that the code generator optimizes away so that it consumes no CPU cycles at run-time (that is, during calls tosqlite3_step()). The purpose of the LIKELY(X) function is to provide a hint to the query planner that the argument X is a boolean value that is usually true. The LIKELY(X) function is equivalent tolikelihood(X,0.9375). See also:unlikely(X). ", + "LOAD_EXTENSION(X) or LOAD_EXTENSION(X,Y) \nDescription: The LOAD_EXTENSION(X,Y) function loadsSQLite extensionsout of the shared library file named X using the entry point Y. The result of LOAD_EXTENSION() is always a NULL. If Y is omitted then the default entry point name is used. The LOAD_EXTENSION() function raises an exception if the extension fails to load or initialize correctly.The LOAD_EXTENSION() function will fail if the extension attempts to modify or delete an SQL function or collating sequence. The extension can add new functions or collating sequences, but cannot modify or delete existing functions or collating sequences because those functions and/or collating sequences might be used elsewhere in the currently running SQL statement. To load an extension that changes or deletes functions or collating sequences, use thesqlite3_load_extension()C-language API.For security reasons, extension loading is disabled by default and must be enabled by a prior call tosqlite3_enable_load_extension(). ", + "LOWER(X) \nDescription: The LOWER(X) function returns a copy of string X with all ASCII characters converted to lower case. The default built-in LOWER() function works for ASCII characters only. To do case conversions on non-ASCII characters, load the ICU extension. ", + "LTRIM(X) or LTRIM(X,Y) \nDescription: The LTRIM(X,Y) function returns a string formed by removing any and all characters that appear in Y from the left side of X. If the Y argument is omitted, LTRIM(X) removes spaces from the left side of X. ", + "MAX(X,Y,...) \nDescription: The multi-argument MAX() function returns the argument with the maximum value, or return NULL if any argument is NULL. The multi-argument MAX() function searches its arguments from left to right for an argument that defines a collating function and uses that collating function for all string comparisons. If none of the arguments to MAX() define a collating function, then the BINARY collating function is used. Note thatmax()is a simple function when it has 2 or more arguments but operates as anaggregate functionif given only a single argument. ", + "MIN(X,Y,...) \nDescription: The multi-argument MIN() function returns the argument with the minimum value. The multi-argument MIN() function searches its arguments from left to right for an argument that defines a collating function and uses that collating function for all string comparisons. If none of the arguments to MIN() define a collating function, then the BINARY collating function is used. Note thatmin()is a simple function when it has 2 or more arguments but operates as anaggregate functionif given only a single argument. ", + "NULLIF(X,Y) \nDescription: The NULLIF(X,Y) function returns its first argument if the arguments are different and NULL if the arguments are the same. The NULLIF(X,Y) function searches its arguments from left to right for an argument that defines a collating function and uses that collating function for all string comparisons. If neither argument to NULLIF() defines a collating function then the BINARY collating function is used. ", + "OCTET_LENGTH(X) \nDescription: The OCTET_LENGTH(X) function returns the number of bytes in the encoding of text string X. If X is NULL then OCTET_LENGTH(X) returns NULL. If X is a BLOB value, then OCTET_LENGTH(X) is the same aslength(X). If X is a numeric value, then OCTET_LENGTH(X) returns the number of bytes in a text rendering of that number.Because OCTET_LENGTH(X) returns the number of bytes in X, not the number of characters, the value returned depends on the database encoding. The OCTET_LENGTH() function can return different answers for the same input string if the database encoding is UTF16 instead of UTF8.If argument X is a table column and the value is of type text or blob, then OCTET_LENGTH(X) avoids reading the content of X from disk, as the byte length can be computed from metadata. Thus, OCTET_LENGTH(X) is efficient even if X is a column containing a multi-megabyte text or blob value. ", + "PRINTF(FORMAT,...) \nDescription: The PRINTF() SQL function is an alias for theformat() SQL function. The format() SQL function was originally named PRINTF(). But the name was later changed to format() for compatibility with other database engines. The PRINTF() name is retained as an alias so as not to break legacy code. ", + "QUOTE(X) \nDescription: The QUOTE(X) function returns the text of an SQL literal which is the value of its argument suitable for inclusion into an SQL statement. Strings are surrounded by single-quotes with escapes on interior quotes as needed. BLOBs are encoded as hexadecimal literals. Strings with embedded NUL characters cannot be represented as string literals in SQL and hence the returned string literal is truncated prior to the first NUL. ", + "RANDOM() \nDescription: The RANDOM() function returns a pseudo-random integer between -9223372036854775808 and +9223372036854775807. ", + "RANDOMBLOB(N) \nDescription: The RANDOMBLOB(N) function return an N-byte blob containing pseudo-random bytes. If N is less than 1 then a 1-byte random blob is returned.Hint: applications can generate globally unique identifiers using this function together withhex()and/orlower()like this:hex(randomblob(16))lower(hex(randomblob(16))) ", + "REPLACE(X,Y,Z) \nDescription: The REPLACE(X,Y,Z) function returns a string formed by substituting string Z for every occurrence of string Y in string X. TheBINARYcollating sequence is used for comparisons. If Y is an empty string then return X unchanged. If Z is not initially a string, it is cast to a UTF-8 string prior to processing. ", + "ROUND(X) or ROUND(X,Y) \nDescription: The ROUND(X,Y) function returns a floating-point value X rounded to Y digits to the right of the decimal point. If the Y argument is omitted or negative, it is taken to be 0. ", + "RTRIM(X) or RTRIM(X,Y) \nDescription: The RTRIM(X,Y) function returns a string formed by removing any and all characters that appear in Y from the right side of X. If the Y argument is omitted, RTRIM(X) removes spaces from the right side of X. ", + "SIGN(X) \nDescription: The SIGN(X) function returns -1, 0, or +1 if the argument X is a numeric value that is negative, zero, or positive, respectively. If the argument to SIGN(X) is NULL or is a string or blob that cannot be losslessly converted into a number, then SIGN(X) returns NULL. ", + "SOUNDEX(X) \nDescription: The SOUNDEX(X) function returns a string that is the soundex encoding of the string X. The string \"?000\" is returned if the argument is NULL or contains no ASCII alphabetic characters. This function is omitted from SQLite by default. It is only available if theSQLITE_SOUNDEXcompile-time option is used when SQLite is built. ", + "SQLITE_COMPILEOPTION_GET(N) \nDescription: The SQLITE_COMPILEOPTION_GET() SQL function is a wrapper around thesqlite3_compileoption_get()C/C++ function. This routine returns the N-th compile-time option used to build SQLite or NULL if N is out of range. See also thecompile_options pragma. ", + "SQLITE_COMPILEOPTION_USED(X) \nDescription: The SQLITE_COMPILEOPTION_USED() SQL function is a wrapper around thesqlite3_compileoption_used()C/C++ function. When the argument X to SQLITE_COMPILEOPTION_USED(X) is a string which is the name of a compile-time option, this routine returns true (1) or false (0) depending on whether or not that option was used during the build. ", + "SQLITE_OFFSET(X) \nDescription: The SQLITE_OFFSET(X) function returns the byte offset in the database file for the beginning of the record from which value would be read. If X is not a column in an ordinary table, then SQLITE_OFFSET(X) returns NULL. The value returned by SQLITE_OFFSET(X) might reference either the original table or an index, depending on the query. If the value X would normally be extracted from an index, the SQLITE_OFFSET(X) returns the offset to the corresponding index record. If the value X would be extracted from the original table, then SQLITE_OFFSET(X) returns the offset to the table record.The SQLITE_OFFSET(X) SQL function is only available if SQLite is built using the-DSQLITE_ENABLE_OFFSET_SQL_FUNCcompile-time option. ", + "SQLITE_SOURCE_ID() \nDescription: The SQLITE_SOURCE_ID() function returns a string that identifies the specific version of the source code that was used to build the SQLite library. The string returned by SQLITE_SOURCE_ID() is the date and time that the source code was checked in followed by the SHA3-256 hash for that check-in. This function is an SQL wrapper around thesqlite3_sourceid()C interface. ", + "SQLITE_VERSION() \nDescription: The SQLITE_VERSION() function returns the version string for the SQLite library that is running. This function is an SQL wrapper around thesqlite3_libversion()C-interface. ", + "SUBSTR(X,Y,Z) or SUBSTR(X,Y) or SUBSTRING(X,Y,Z) or SUBSTRING(X,Y) \nDescription: The SUBSTR(X,Y,Z) function returns a substring of input string X that begins with the Y-th character and which is Z characters long. If Z is omitted then SUBSTR(X,Y) returns all characters through the end of the string X beginning with the Y-th. The left-most character of X is number 1. If Y is negative then the first character of the substring is found by counting from the right rather than the left. If Z is negative then the abs(Z) characters preceding the Y-th character are returned. If X is a string then characters indices refer to actual UTF-8 characters. If X is a BLOB then the indices refer to bytes.\"substring()\" is an alias for \"substr()\" beginning with SQLite version 3.34. ", + "TOTAL_CHANGES() \nDescription: The TOTAL_CHANGES() function returns the number of row changes caused by INSERT, UPDATE or DELETE statements since the current database connection was opened. This function is a wrapper around thesqlite3_total_changes64()C/C++ interface. ", + "TRIM(X) or TRIM(X,Y) \nDescription: The TRIM(X,Y) function returns a string formed by removing any and all characters that appear in Y from both ends of X. If the Y argument is omitted, TRIM(X) removes spaces from both ends of X. ", + "TYPEOF(X) \nDescription: The TYPEOF(X) function returns a string that indicates thedatatypeof the expression X: \"null\", \"integer\", \"real\", \"text\", or \"blob\". ", + "UNHEX(X) or UNHEX(X,Y) \nDescription: The UNHEX(X,Y) function returns a BLOB value which is the decoding of the hexadecimal string X. If X contains any characters that are not hexadecimal digits and which are not in Y, then UNHEX(X,Y) returns NULL. If Y is omitted, it is understood to be an empty string and hence X must be a pure hexadecimal string. All hexadecimal digits in X must occur in pairs, with both digits of each pair beginning immediately adjacent to one another, or else UNHEX(X,Y) returns NULL. If either parameter X or Y is NULL, then UNHEX(X,Y) returns NULL. The X input may contain an arbitrary mix of upper and lower case hexadecimal digits. Hexadecimal digits in Y have no affect on the translation of X. Only characters in Y that are not hexadecimal digits are ignored in X.See also:hex() ", + "UNICODE(X) \nDescription: The UNICODE(X) function returns the numeric unicode code point corresponding to the first character of the string X. If the argument to UNICODE(X) is not a string then the result is undefined. ", + "UNLIKELY(X) \nDescription: The UNLIKELY(X) function returns the argument X unchanged. The UNLIKELY(X) function is a no-op that the code generator optimizes away so that it consumes no CPU cycles at run-time (that is, during calls tosqlite3_step()). The purpose of the UNLIKELY(X) function is to provide a hint to the query planner that the argument X is a boolean value that is usually not true. The UNLIKELY(X) function is equivalent tolikelihood(X, 0.0625). ", + "UPPER(X) \nDescription: The UPPER(X) function returns a copy of input string X in which all lower-case ASCII characters are converted to their upper-case equivalent. ", + "ZEROBLOB(N) \nDescription: The ZEROBLOB(N) function returns a BLOB consisting of N bytes of 0x00. SQLite manages these zeroblobs very efficiently. Zeroblobs can be used to reserve space for a BLOB that is later written usingincremental BLOB I/O. This SQL function is implemented using thesqlite3_result_zeroblob()routine from the C/C++ interface. ", + "AVG(X) \nDescription: The AVG() function returns the average value of all non-NULLXwithin a group. String and BLOB values that do not look like numbers are interpreted as 0. The result of AVG() is always a floating point value whenever there is at least one non-NULL input even if all inputs are integers. The result of AVG() is NULL if there are no non-NULL inputs. The result of AVG() is computed astotal()/count()so all of the constraints that apply tototal()also apply to AVG(). ", + "COUNT(X) or COUNT(*) \nDescription: The COUNT(X) function returns a count of the number of times thatXis not NULL in a group. The COUNT(*) function (with no arguments) returns the total number of rows in the group. ", + "GROUP_CONCAT(X) or GROUP_CONCAT(X,Y) or STRING_AGG(X,Y) \nDescription: The GROUP_CONCAT() function returns a string which is the concatenation of all non-NULL values ofX. If parameterYis present then it is used as the separator between instances ofX.A comma (\",\") is used as the separator ifYis omitted.The string_agg(X,Y) function is an alias for GROUP_CONCAT(X,Y). String_agg() is compatible with PostgreSQL and SQL-Server and GROUP_CONCAT() is compatible with MySQL.The order of the concatenated elements is arbitrary unless an ORDER BY argument is included immediately after the last parameter. ", + "MAX(X) \nDescription: The MAX() aggregate function returns the maximum value of all values in the group. The maximum value is the value that would be returned last in an ORDER BY on the same column. Aggregate MAX() returns NULL if and only if there are no non-NULL values in the group. ", + "MIN(X) \nDescription: The MIN() aggregate function returns the minimum non-NULL value of all values in the group. The minimum value is the first non-NULL value that would appear in an ORDER BY of the column. Aggregate MIN() returns NULL if and only if there are no non-NULL values in the group. ", + "SUM(X) or TOTAL(X) \nDescription: The SUM() and TOTAL() aggregate functions return the sum of all non-NULL values in the group. If there are no non-NULL input rows then SUM() returns NULL but TOTAL() returns 0.0. NULL is not normally a helpful result for the sum of no rows but the SQL standard requires it and most other SQL database engines implement SUM() that way so SQLite does it in the same way in order to be compatible. The non-standard TOTAL() function is provided as a convenient way to work around this design problem in the SQL language. ", + "ROW_NUMBER() \nDescription: The number of the row within the current partition. Rows are numbered starting from 1 in the order defined by the ORDER BY clause in the window definition, or in arbitrary order otherwise. ", + "RANK() \nDescription: The row_number() of the first peer in each group - the rank of the current row with gaps. If there is no ORDER BY clause, then all rows are considered peers and this function always returns 1. ", + "DENSE_RANK() \nDescription: The number of the current row's peer group within its partition - the rank of the current row without gaps. Rows are numbered starting from 1 in the order defined by the ORDER BY clause in the window definition. If there is no ORDER BY clause, then all rows are considered peers and this function always returns 1. ", + "PERCENT_RANK() \nDescription: Despite the name, this function always returns a value between 0.0 and 1.0 equal to (rank- 1)/(partition-rows- 1), whererankis the value returned by built-in window function rank() andpartition-rowsis the total number of rows in the partition. If the partition contains only one row, this function returns 0.0. ", + "CUME_DIST() \nDescription: The cumulative distribution. Calculated asrow-number/partition-rows, whererow-numberis the value returned by row_number() for the last peer in the group andpartition-rowsthe number of rows in the partition. ", + "NTILE(N) \nDescription: ArgumentNis handled as an integer. This function divides the partition into N groups as evenly as possible and assigns an integer between 1 andNto each group, in the order defined by the ORDER BY clause, or in arbitrary order otherwise. If necessary, larger groups occur first. This function returns the integer value assigned to the group that the current row is a part of. ", + "LAG(expr) or LAG(expr, offset) or LAG(expr, offset, default) \nDescription: The first form of the LAG() function returns the result of evaluating expressionexpragainst the previous row in the partition. Or, if there is no previous row (because the current row is the first), NULL. ", + "LEAD(expr) or LEAD(expr, offset) or LEAD(expr, offset, default) \nDescription: The first form of the LEAD() function returns the result of evaluating expressionexpragainst the next row in the partition. Or, if there is no next row (because the current row is the last), NULL. ", + "FIRST_VALUE(expr) \nDescription: This built-in window function calculates the window frame for each row in the same way as an aggregate window function. It returns the value ofexprevaluated against the first row in the window frame for each row. ", + "LAST_VALUE(expr) \nDescription: This built-in window function calculates the window frame for each row in the same way as an aggregate window function. It returns the value ofexprevaluated against the last row in the window frame for each row. ", + "NTH_VALUE(expr, N) \nDescription: This built-in window function calculates the window frame for each row in the same way as an aggregate window function. It returns the value ofexprevaluated against the rowNof the window frame. Rows are numbered within the window frame starting from 1 in the order defined by the ORDER BY clause if one is present, or in arbitrary order otherwise. If there is noNth row in the partition, then NULL is returned. ", + "ACOS(X) \nDescription: Return the arccosine of X. The result is in radians. ", + "ACOSH(X) \nDescription: Return the hyperbolic arccosine of X. ", + "ASIN(X) \nDescription: Return the arcsine of X. The result is in radians. ", + "ASINH(X) \nDescription: Return the hyperbolic arcsine of X. ", + "ATAN(X) \nDescription: Return the arctangent of X. The result is in radians. ", + "ATAN2(Y,X) \nDescription: Return the arctangent of Y/X. The result is in radians. The result is placed into correct quadrant depending on the signs of X and Y. ", + "ATANH(X) \nDescription: Return the hyperbolic arctangent of X. ", + "CEIL(X) or CEILING(X) \nDescription: Return the first representable integer value greater than or equal to X. For positive values of X, this routine rounds away from zero. For negative values of X, this routine rounds toward zero. ", + "COS(X) \nDescription: Return the cosine of X. X is in radians. ", + "COSH(X) \nDescription: Return the hyperbolic cosine of X. ", + "DEGREES(X) \nDescription: Convert value X from radians into degrees. ", + "EXP(X) \nDescription: Computee(Euler's number, approximately 2.71828182845905) raised to the power X. ", + "FLOOR(X) \nDescription: Return the first representable integer value less than or equal to X. For positive numbers, this function rounds toward zero. For negative numbers, this function rounds away from zero. ", + "LN(X) \nDescription: Return the natural logarithm of X. ", + "LOG(X) or LOG10(X) or LOG(B,X) \nDescription: Return the base-10 logarithm for X. Or, for the two-argument version, return the base-B logarithm of X.Compatibility note: SQLite works like PostgreSQL in that the LOG() function computes a base-10 logarithm. Most other SQL database engines compute a natural logarithm for LOG(). In the two-argument version of LOG(B,X), the first argument is the base and the second argument is the operand. This is the same as in PostgreSQL and MySQL, but is reversed from SQL Server which uses the second argument as the base and the first argument as the operand. ", + "LOG2(X) \nDescription: Return the logarithm base-2 for the number X. ", + "MOD(X,Y) \nDescription: Return the remainder after dividing X by Y. This is similar to the '%' operator, except that it works for non-integer arguments. ", + "PI() \nDescription: Return an approximation for π. ", + "POW(X,Y) or POWER(X,Y) \nDescription: Compute X raised to the power Y. ", + "RADIANS(X) \nDescription: Convert X from degrees into radians. ", + "SIN(X) \nDescription: Return the sine of X. X is in radians. ", + "SINH(X) \nDescription: Return the hyperbolic sine of X. ", + "SQRT(X) \nDescription: Return the square root of X. NULL is returned if X is negative. ", + "TAN(X) \nDescription: Return the tangent of X. X is in radians. ", + "TANH(X) \nDescription: Return the hyperbolic tangent of X. ", + "TRUNC(X) \nDescription: Return the representable integer in between X and 0 (inclusive) that is furthest away from zero. Or, in other words, return the integer part of X, rounding toward zero. The TRUNC() function is similar toceiling(X)andfloor(X)except that it always rounds toward zero whereas ceiling(X) and floor(X) round up and down, respectively. ", + "DATE(time-value, modifier, modifier, ...) \nDescription: Returns the date as text in this format: YYYY-MM-DD. ", + "TIME(time-value, modifier, modifier, ...) \nDescription: Returns the time as text in formatted as HH:MM:SS or as HH:MM:SS.SSS if the subsec modifier is used. ", + "DATETIME(time-value, modifier, modifier, ...) \nDescription: Returns the date and time formatted as YYYY-MM-DD HH:MM:SS or as YYYY-MM-DD HH:MM:SS.SSS if the subsec modifier is used. ", + "JULIANDAY(time-value, modifier, modifier, ...) \nDescription: Returns the Julian day - the fractional number of days since noon in Greenwich on November 24, 4714 B.C. (Proleptic Gregorian calendar). ", + "UNIXEPOCH(time-value, modifier, modifier, ...) \nDescription: Returns a unix timestamp - the number of seconds since 1970-01-01 00:00:00 UTC. The UNIXEPOCH() function normally returns an integer number of seconds, but with the optional subsec modifier it will return a floating point number which is the fractional number of seconds. ", + "STRFTIME(format, time-value, modifier, modifier, ...) \nDescription: Returns the date formatted according to the format string specified as the first argument. The format string supports the most common substitutions found in the STRFTIME() function from the standard C library plus two new substitutions, %f and %J. ", + "TIMEDIFF(time-value, time-value) \nDescription: Returns a string that describes the amount of time that must be added to B in order to reach time A. The format of the TIMEDIFF() result is designed to be human-readable. " + ] + + def _sql_func_template(self, sql_funcs: str) -> str: + template = """### SQL Functions + You may consider one or more of the following SQL functions while generating the query: + {sql_funcs} + Important tips: + Except for the functions listed above, you may use any other functions as long as they conform to the syntax of the database engine. + """ + return template.format(sql_funcs=sql_funcs) + + def _insert_stmts_template(self, insert_statements: str) -> str: + template = '''### INSERT INTO Statements + Below are several `INSERT INTO` statements. Use these to help generate predicates (i.e., `WHERE` clauses) in your SQL query: + {insert_statements} + ''' + return template.format(insert_statements=insert_statements) + + def _sql_synthesis_prompt(self, schema_str: str, sql_function_prompt: str, db_value_prompt: str, complexity: str, criterion: str, db_engine: str, column_count: int, embedding_model: str) -> str: + template = '''**Task Overview** + Create an executable VecSQL query based on the provided information. + + **Database Schema** + {schema_str} + + {sql_function_prompt} + + {db_value_prompt} + + **SQL Query Complexity** + Ensure the SQL query matches the {complexity} level, defined as follows: + {criterion} + + **Output Format Requirements** + Enclose the SQL query in a code block: + ```sql + -- Your SQL query here + ``` + + **SQL Query Requirements** + 0. (MANDATORY) The generated SQL query MUST be a VecSQL query. It MUST contain a vector similarity search using the `MATCH lembed(...)` syntax. This search MUST be performed on a column that ends with `_embedding`. + 1. Use the syntax specific to the {db_engine} database engine. + 2. Incorporate advanced functions if appropriate, but they are not mandatory. + 3. Address real-world data analysis needs. Avoid trivial or nonsensical queries. + 4. (Very important) Ensure the final SQL query selects {column_count} columns. + 5. (Very important) Always verify that every column name you reference in a query exists in the tables you're querying. Before executing a query, ensure all referenced columns (e.g., column1, table1.id) are valid and spelled correctly. + + + **SQL extension** + Extension: sqlite_vec and sqlite_lembed. + + There are a few Requirements you should Comply with in addition, else you can ignore these requirements below. + 1. When generating SQL queries, you should prioritize utilizing KNN searches whenever contextually appropriate. However, you have to avoid unnecessary/forced KNN implementations for: + --Traditional relational data queries (especially for columns like: id, age, price) + --Cases where standard SQL operators (equality, range, or aggregation functions) are more efficient and semantically appropriate + 2. Only vector type(like: float[?]) support KNN queries and the name of vector column often end with "_embedding". So, you can use knn queries to search when the column name you need to search for ends with "_embedding" or when the column name with "_embedding" is also in the list. + 3. In any complexity level, you can choose to use KNN queries if need. + 4. When using KNN queries, you have to add LIMIT or 'And k = ?' constraint but do not use them all in the same statement. This rule is very important, do not forget to add LIMIT or 'And k = ?' constraint after MATCH operator. + 5. The lembed function is used to transform a string into a vector, whose type and size match the corresponding column type in the data table. The function has two parameters, the first parameter is the name of the embedding model used (default value: {embedding_model}), and the second parameter is the content of the string type you want to convert. So, you should generate some words or sentences with specific semantic information based on name, type and comment of this column. For example, you can generate "The Daily Grind Coffee Shop\n 456 Oak Avenue\n Springfield, IL 62704\n USA" when this column name is Location_embedding, column type is float[384] and comment of column is "the embedding of location". + 6. The lembed function's second parameter MUST be a SPECIFIC semantic description. + - For location_embedding: Generate REAL addresses (e.g. "Stadium: 123 Main St, Boston, MA. Capacity: 50,000. Home team: Patriots") + - For columns containing semantically meaningful data (e.g., descriptions), generate rich, contextually appropriate information. For columns without meaningful content (e.g., placeholder names), avoid creating semantically dense output to facilitate fuzzy matching operations. + - For name_embedding: You should generate variationsof the original names (e.g., altered spellings, phonetic approximations, or intentionally obfuscated words/characters) to enable Subsequent fuzzy matching to identify semantically similar names. Importantly, never generate redundant information. For example, you can generate "Lige", but do not generate "Ligand Lige", "Ligand example name", "Ligand similar to Aspirin" and "Ligand name variation". + Examples: + Correct: + name_embedding MATCH lembed('all-MiniLM-L6-v2', "Kri") + Wrong: + name_embedding MATCH lembed('all-MiniLM-L6-v2', "A leading publisher based in Germany specializing in + scientific journals and books.") + - For text_embedding: Use ACTUAL and meaningful sentences (e.g. "Harper Lee's To Kill a Mockingbirdis a timeless exploration of racial injustice and moral growth, seen through the innocent yet perceptive eyes of Scout Finch. With its powerful themes, unforgettable characters like Atticus Finch, and Lee's poignant prose, the novel remains a searing critique of society's failures and a testament to the courage of standing for what's right.") + - NEVER use vague words and generic phrases like "a book review" + Examples: + Correct: + lembed('all-MiniLM-L6-v2', "To Kill a Mockingbird") + Wrong: + lembed('all-MiniLM-L6-v2', "name of a famous book") + 7. When using MATCH, please fill in a vector using function lembed after MATCH that matches the column type (with the same dimension and type). Using details are in examples. + 8. The distance column is an implicitly generated metric that appears when performing vector similarity searches (using the MATCH operator) in SQLite vector extensions like sqlite-vec. If using JOIN operator, you have to clarify which table that distance belongs to. + 9. A SELECT statement should have no more than one MATCH operation. However, each subquery within a SELECT statement could also have no more than one MATCH operation, independent of the parent query." + 10. When performing a KNN/vector similarity search (e.g., using MATCH or lembed), always specify a LIMIT or k=N constraint directly on the vector search operation, even if the outer query already has a LIMIT. The vector search requires its own result cap to avoid ambiguity in ranking and performance issues. + 11. When both LIMIT and k operations are available for vector search queries, prioritize using k operation for Broader Compatibility. + Key Points: + --Vector search needs its own LIMIT/k - The outer LIMIT applies to the final filtered results, not the initial similarity search. + --LIMIT operator should follow closely after "ORDER BY distance". + Wrong Example: + ```sql + SELECT a.codec_name + FROM audio_codecs a + JOIN quality_levels q ON a.codec_id = q.quality_id + WHERE a.description_embedding MATCH lembed('all-MiniLM-L6-v2', "High efficiency audio codec with low latency and optimal bandwidth") + AND q.quality_name = 'HighQuality' + LIMIT 1; + ``` + Correct Example: + ```sql + SELECT a.codec_name + FROM audio_codecs a + JOIN quality_levels q ON a.codec_id = q.quality_id + WHERE a.description_embedding MATCH lembed('all-MiniLM-L6-v2', "High efficiency audio codec with low latency and optimal bandwidth") LIMIT 1 + AND q.quality_name = 'HighQuality'; + ``` + --When using JOIN operations, you need to ensure that k does not cause ambiguity in the query. In most cases, the k parameter logically belongs to the same table as the column used in the MATCH clause. So, when the column referenced in the MATCH clause includes a table qualifier (e.g., table1.embedding), the k parameter must be explicitly bound to the same table. + Wrong Example: + ```sql + SELECT s.stock_id, s.symbol + FROM stocks s + JOIN exchanges e ON s.exchange_id = e.exchange_id + WHERE s.sector_embedding MATCH lembed('all-MiniLM-L6-v2', "Tech industry sector in the USA") + AND e.country = 'USA' + AND k = 5 + ORDER BY s.stock_id; + ``` + Correct Example: + ```sql + SELECT s.stock_id, s.symbol + FROM stocks s + JOIN exchanges e ON s.exchange_id = e.exchange_id + WHERE s.sector_embedding MATCH lembed('all-MiniLM-L6-v2', "Tech industry sector in the USA") + AND e.country = 'USA' + AND s.k = 5 + ORDER BY s.stock_id; + ``` + 12. ​Avoids runtime errors - Many vector databases (e.g., SQLite with sqlite-vss, pgvector) enforce this requirement strictly. + 13. Only a single 'ORDER BY distance' clause is allowed on vec0 KNN queries, not on other columns. + ***Example of KNN queries of sqlite-vec*** + first example(type of vector_embedding is float[384]): + ```sql + SELECT rowid, distance + FROM vec_table + WHERE vector_embedding MATCH lembed({embedding_model},"vector of sun") + ORDER BY distance + LIMIT 1; + ``` + + second example(type of sentence_embedding is float[384]): + ```sql + select + movie_id, + title, + genre, + num_reviews, + mean_rating, + distance + from vec_movies + where sentence_embedding match lembed({embedding_model},"This is a great movie!") + and genre = 'scifi' + and num_reviews between 100 and 500 + and mean_rating > 3.5 + and k = 5; + ``` + + third example(type of vector_embedding is float[384]): + ```sql + select rowid, name1, name2, age, vec_to_json + from v + where vector_embedding match lembed({embedding_model},"aaa and xxx are good friends, whose age is 18.") + and k = 1 + and name1 in ('alex', 'brian', 'craig') + and name2 in ('Rick', 'Morty') + and age in (21, 18); + ``` + + **Answer** + Let's proceed step by step. + ''' + return template.format( + schema_str=schema_str, + sql_function_prompt=sql_function_prompt.strip(), + db_value_prompt=db_value_prompt.strip(), + complexity=complexity, + criterion=criterion.strip(), + db_engine=db_engine, + column_count=column_count, + embedding_model=embedding_model + ) + + def build_prompt(self, insert_statements: List[str], create_statements: List[str], db_engine: str) -> tuple[str, str]: + complexity = random.sample(list(self.complexity2criterion_vec.keys()), 1)[0] + + if len(insert_statements) == 0: + db_value_prompt = "" + else: + if len(insert_statements) > 4: + insert_statements = random.sample(insert_statements, 4) + db_value_prompt = self._insert_stmts_template( + insert_statements="\n\n".join(insert_statements) + ) + + function_num = random.randint(0, 2) + if function_num == 0: + sql_function_prompt = "### SQL Functions\nYou can use any function supported by the database engine." + else: + sql_funcs = "" + sampled_functions = random.sample(self.functions, min(function_num, len(self.functions))) + for idx, func in enumerate(sampled_functions): + sql_funcs += f"Function {idx + 1}:\n{func.strip()}\n" + sql_function_prompt = self._sql_func_template(sql_funcs=sql_funcs) + + column_count = np.random.geometric(0.6, 1)[0] + prompt = self._sql_synthesis_prompt( + schema_str="\n\n".join(create_statements), + sql_function_prompt=sql_function_prompt.strip(), + db_value_prompt=db_value_prompt.strip(), + complexity=complexity, + criterion=self.complexity2criterion_vec[complexity].strip(), + db_engine=db_engine, + column_count=column_count, + embedding_model="\'all-MiniLM-L6-v2\'" + ) + return prompt + + +@PROMPT_REGISTRY.register() +class Text2SQLQuestionGeneratorPrompt(PromptABC): + def __init__(self): + self.style2desc = { + "Formal": '''**Formal Style** + - Uses standard grammar and vocabulary. + - Example: Find all students older than 18 years and return their home addresses.''', + + "Colloquial": '''**Colloquial Style** + - Employs informal vocabulary and expressions. + - Example: Hey! Could you help me find all the students who are over 18? I'd love to know their names and where they live.''', + + "Imperative": '''**Imperative Style** + - Uses command or directive sentences. + - Example: Could you please gather all the students who are older than 18? I really need to know their names and where they live!''', + + "Interrogative": '''**Interrogative Style** + - Uses question forms. + - Example: Could you tell me which students are older than 18 and what their home addresses are?''', + + "Descriptive": '''**Descriptive Style** + - Uses detailed descriptions with contextual information. + - Example: I want to know the names and home addresses of all students older than 18.''', + + "Concise": '''**Concise Style** + - Use short sentences. + - Example: Students older than 18, return their names and addresses.''', + + "Vague": '''**Vague Style** + - Includes ambiguous vocabulary requiring inference. + - Example: What are the names and addresses of those older students? (External Knowledge: 'older students' refers to age >= 18.)''', + + "Metaphorical": '''**Metaphorical Style** + - Uses metaphors or metaphorical expressions. + - Example: Find the names and addresses of those who have reached adulthood. (External Knowledge: 'reached adulthood' refers to age >= 18.)''' + } + + self.steps_wo_ek = '''1. **Explain the SQL Query:** Provide a detailed explanation of what the query does. + 2. **Generate a Question:** Formulate a natural language question based on the SQL query and explanation.''' + + self.steps_w_ek = '''1. **Explain the SQL Query:** Provide a detailed explanation of what the query does. + 2. **Generate a Question:** Formulate a natural language question based on the SQL query and explanation. + 3. **External Knowledge:** For Vague or Metaphorical styles, include external knowledge to enhance clarity.''' + + self.steps_multi_round = '''1. **Explain the SQL Query:** Provide a detailed explanation of what the query does. + 2. **Generate a Dialogue:** Create a conversation between the User and the Assistant based on the SQL query and its explanation.''' + + self.guidelines_wo_ek = '''1. Clearly describe the columns being selected by the SQL query. For example: + - "SELECT * ... FROM ..." means "Find all ..."; + - "SELECT f.check_date, f.status, f.remarks, c.year, c.year_min, c.year_max, c.year_average, c.data_quality_score FROM ..." means "Return the check dates, statuses, remarks, years, minimum years, maximum years, average years, and quality scores for ...". + 2. Ensure the natural language question accurately captures the semantics of the SQL query, including conditions such as predicates, `ORDER BY`, and `LIMIT` clauses.''' + + self.guidelines_w_ek = '''1. Clearly describe the columns being selected by the SQL query. For example: + - "SELECT * ... FROM ..." means "Find all ..."; + - "SELECT f.check_date, f.status, f.remarks, c.year, c.year_min, c.year_max, c.year_average, c.data_quality_score FROM ..." means "Return the check dates, statuses, remarks, years, minimum years, maximum years, average years, and quality scores for ...". + 2. Ensure the natural language question accurately captures the semantics of the SQL query, including conditions such as predicates, `ORDER BY`, and `LIMIT` clauses. + 3. If necessary, incorporate external knowledge using multiple entries separated by semicolons (";"). These can include formulas, common sense, domain-specific knowledge, or extended context, such as information from long documents. Each entry should be concise.''' + + self.guidelines_multi_round = '''1. Clearly describe the columns being selected by the SQL query. For example: + - "SELECT * ... FROM ..." means "Find all ..."; + - "SELECT f.check_date, f.status, f.remarks, c.year, c.year_min, c.year_max, c.year_average, c.data_quality_score FROM ..." means "Return the check dates, statuses, remarks, years, minimum years, maximum years, average years, and quality scores for ...". + 2. Ensure the conversation accurately captures the semantics of the SQL query, including conditions such as predicates, `ORDER BY`, and `LIMIT` clauses.''' + + self.output_format_wo_ek = '''Please structure your response as follows: + + [EXPLANATION-START] + (SQL Explanation) + [EXPLANATION-END] + + [QUESTION-START] + (Natural Language Question) + [QUESTION-END] + + - **SQL Explanation**: Provide a clear and detailed explanation of the SQL query, enclosed within [EXPLANATION-START] and [EXPLANATION-END]. + - **Natural Language Question**: Translate the SQL query into a natural language question, enclosed within [QUESTION-START] and [QUESTION-END].''' + + self.output_format_w_ek = '''Please structure your response as follows: + + [EXPLANATION-START] + (SQL Explanation) + [EXPLANATION-END] + + [QUESTION-START] + (Natural Language Question) + [QUESTION-END] + + [EXTERNAL-KNOWLEDGE-START] + (External Knowledge) + [EXTERNAL-KNOWLEDGE-END] + + - **SQL Explanation**: Provide a clear and detailed explanation of the SQL query, enclosed within [EXPLANATION-START] and [EXPLANATION-END]. + - **Natural Language Question**: Translate the SQL query into a natural language question, enclosed within [QUESTION-START] and [QUESTION-END]. + - **External Knowledge**: Include any relevant external knowledge if applicable, enclosed within [EXTERNAL-KNOWLEDGE-START] and [EXTERNAL-KNOWLEDGE-END]. Leave this section blank if not needed.''' + + self.output_format_multi_round = '''Please structure your response as follows: + + [EXPLANATION-START] + (SQL Explanation) + [EXPLANATION-END] + + [QUESTION-START] + (Natural Language Question, in the format of [{"User": ...}, {"Assistant": ...}, {"User": ...}, ....]) + [QUESTION-END] + + - **SQL Explanation**: Provide a clear and detailed explanation of the SQL query, enclosed within [EXPLANATION-START] and [EXPLANATION-END]. + - **Natural Language Question**: Convert the SQL query into a multi-round dialogue, enclosed within [QUESTION-START] and [QUESTION-END]. Represent this as a list that captures multiple rounds of conversation between the User and the Assistant.''' + + self.instruction_wo_ek = "Based on the above information, follow the reasoning steps to generate the explanation and the question corresponding to the SQL query." + + self.instruction_w_ek = "Based on the above information, follow the reasoning steps to generate the explanation, the question, and the external knowledge corresponding to the SQL query." + + self.instruction_multi_round = "Based on the above information, follow the reasoning steps to generate the explanation and the dialogue corresponding to the SQL query." + + def _question_synthesis_prompt(self, style_desc, engine, column_info, sql, steps, guidelines, output_format, instruction): + template = '''**Task Overview** + Your task is to create a high-quality natural language question based on a given SQL query and other information. + + **Style** + The natural language question should follow this style: + {style_desc} + + **Database Engine** + {engine} + + **Column Information** + Below are column names and their corresponding descriptions: + {column_info} + + **SQL Query** + Given SQL query: + ```sql + {sql} + ``` + + **Reasoning Steps** + {steps} + + **Guidelines** + {guidelines} + + **Output Format** + {output_format} + + **Insturction** + {instruction} + ''' + return template.format( + style_desc = style_desc, + engine = engine, + column_info = column_info, + sql = sql, + steps = steps, + guidelines = guidelines, + output_format = output_format, + instruction = instruction + ) + + def build_prompt(self, sql, db_id, db_id2column_info, db_type) -> str: + styles = ["Formal", "Colloquial", "Imperative", "Interrogative", "Descriptive", "Concise", "Vague", "Metaphorical"] + style_name = random.sample(styles, 1)[0] + column_name2column_desc = db_id2column_info[db_id] + used_column_name2column_desc = dict() + + for column_name, column_desc in column_name2column_desc.items(): + if column_name.lower() in sql.lower(): + used_column_name2column_desc[column_name] = column_desc + + if style_name in ["Vague", "Metaphorical"]: + steps = self.steps_w_ek + guidelines = self.guidelines_w_ek + instruction = self.instruction_w_ek + output_format = self.output_format_w_ek + else: + steps = self.steps_wo_ek + guidelines = self.guidelines_wo_ek + instruction = self.instruction_wo_ek + output_format = self.output_format_wo_ek + + prompt = self._question_synthesis_prompt( + style_desc=self.style2desc[style_name].strip(), + engine=db_type, + column_info=json.dumps(used_column_name2column_desc, indent=2, ensure_ascii=False).strip(), + sql=sql.strip(), + steps=steps.strip(), + guidelines=guidelines.strip(), + output_format=output_format.strip(), + instruction=instruction.strip() + ) + + return prompt, style_name + + +@PROMPT_REGISTRY.register() +class Text2VecSQLQuestionGeneratorPrompt(PromptABC): + def __init__(self): + pass + + def _get_style2desc(self): + template = { + "Formal": '''**Formal Style** + - Uses standard grammar and vocabulary. + - Example: Find all students older than 18 years and return their home addresses. + - Vector Example: Find the three articles most closely related to Stable Diffusion and return them.''', + + "Colloquial": '''**Colloquial Style** + - Employs informal vocabulary and expressions. + - Example: Hey! Could you help me find all the students who are over 18? I'd love to know their names and where they live. + - Vector Example: Hey there! Can you grab me the top 3 articles that are most closely related to Stable Diffusion?''', + + "Imperative": '''**Imperative Style** + - Uses command or directive sentences. + - Example: Could you please gather all the students who are older than 18? I really need to know their names and where they live! + - Vector Example: Please find the three articles most closely related to Stable Diffusion and return their name.''', + + "Interrogative": '''**Interrogative Style** + - Uses question forms. + - Example: Could you tell me which students are older than 18 and what their home addresses are? + - Vector Example: Could you show me the 3 articles that most have to do with Stable Diffusion?''', + + "Descriptive": '''**Descriptive Style** + - Uses detailed descriptions with contextual information. + - Example: I want to know the names and home addresses of all students older than 18. + - Vector Example: I need to find articles that most closely related to Stable Diffusion, returning the top 3 matches sorted by cosine similarity.''', + + "Concise": '''**Concise Style** + - Use short sentences. + - Example: Students older than 18, return their names and addresses. + - Vector Example: Top 3 related articles to Stable Diffusion.''', + + "Vague": '''**Vague Style** + - Includes ambiguous vocabulary requiring inference. + - Example: What are the names and addresses of those older students? (External Knowledge: 'older students' refers to age >= 18.) + - Vector Example: Find a few articles have to do with Stable Diffusion. (External Knowledge: 'a few' refers to vector similarity search with k=3 limit)''', + + "Metaphorical": '''**Metaphorical Style** + - Uses metaphors or metaphorical expressions. + - Example: Find the names and addresses of those who have reached adulthood. (External Knowledge: 'reached adulthood' refers to age >= 18.) + - Vector Example: Find a few articles have to do with SD in ai. (External Knowledge: 'SD in ai' refers to Stable Diffusion)''', + + "Multi-turn Dialogue": '''**Multi-turn Dialogue Style** + - This involves a dialogue to clarify the user's query needs. + - Example: [{"User": "I want to query some student information."}, {"Assistant": "Which students' information would you like to query?"}, {"User": "Students older than 18."}, {"Assistant": "What other information would you like to know about them?"}, {"User": "Names and addresses."}, {"Assistant": "Is there anything else you need?"}, {"User": "No."}, {"Assistant": "OK, I will help you translate your request into an SQL query."}] + - Vector Example: + User: "I'm looking for some articles." + Assistant: "How many articles would you like to find and What field of paper are you looking for?" + User: "About 3, and they are related to Stable Diffusion." + Assistant: "I'll search for 3 articles that most closely related to Stable Diffusion."''' + } + return template + + def _get_steps_wo_ek(self): + template = '''1. **Explain the SQL Query:** Provide a detailed explanation of what the query does, including any vector search operations. + 2. **Generate a Question:** Formulate a natural language question based on the SQL query and explanation.''' + return template + + def _get_steps_w_ek(self): + template = '''1. **Explain the SQL Query:** Provide a detailed explanation of what the query does, including any vector search operations. + 2. **Generate a Question:** Formulate a natural language question based on the SQL query and explanation. + 3. **External Knowledge:** For Vague or Metaphorical styles, include external knowledge to enhance clarity, especially for vector operations.''' + return template + + def _get_steps_multi_round(self): + template = '''1. **Explain the SQL Query:** Provide a detailed explanation of what the query does, including any vector search operations. + 2. **Generate a Dialogue:** Create a conversation between the User and the Assistant based on the SQL query and its explanation, ensuring vector operations are properly discussed.''' + return template + + def _get_guidelines_wo_ek(self): + template = '''1. Clearly describe the columns being selected by the SQL query. For example: + - "SELECT * ... FROM ..." means "Find all ..."; + - "SELECT f.check_date, f.status, f.remarks, c.year, c.year_min, c.year_max, c.year_average, c.data_quality_score FROM ..." means "Return the check dates, statuses, remarks, years, minimum years, maximum years, average years, and quality scores for ...". + - "SELECT rowid, vec FROM vec_table WHERE vec MATCH lembed(_,"xxx") ORDER BY distance LIMIT 2;" means "Return two of the rowid and vec that most related to xxx from vec_table, ordered by similarity distance". + - "SELECT rowid, vec FROM vec_table WHERE vec MATCH lembed(_,"xxx") AND k = 2;" means "Return two of the rowid and vec that most related to xxx from vec_table, ordered by similarity distance". + - For vector searches: Always mention the LIMIT value or K value when explaining MATCH operations. + + 2. Ensure the natural language question accurately captures: + - All conditions including vector similarity searches + - ORDER BY clauses (especially for distance/similarity) + - LIMIT and K clauses + - Any window functions or complex joins''' + return template + + def _get_guidelines_w_ek(self): + template = '''1. Clearly describe the columns being selected by the SQL query (same as above). + 2. Ensure the natural language question captures all query semantics (same as above). + 3. For vector searches, include these common external knowledge points: + - "MATCH" operator performs approximate nearest neighbor (ANN) search; + - "k=N" specifies the number of similar items to return; + - Vectors are compared using Euclidean distance (L2 norm) by default; + - Similarity increases as distance decreases; + - Include any domain-specific knowledge about the vector meaning.''' + return template + + def _get_guidelines_multi_round(self): + template = '''1. Clearly describe the columns being selected by the SQL query (same as above). + 2. Ensure the dialogue naturally covers: + - The purpose of the vector search; + - How many similar items are needed (LIMIT); + - What the target vector represents; + - Any additional filtering or sorting requirements.''' + return template + + def _get_vector_question_guidelines(self): + template = ''' + **Guiding Principles for High-Quality Vector Questions:** + + Your ultimate goal is to create a question that a real human would ask. To do this, you must internalize the following principles: + + 1. **Translate Mechanism into Intent (The Golden Rule!)**: A vector search (`MATCH ... LIMIT N`) is a technical mechanism to find the "top N" or "best N" examples of something. Your question **MUST** reflect the user's *intent*, not the mechanism. + * **Prohibited Phrases**: Avoid technical jargon that describes the search process. Do NOT use phrases like: "most closely related to", "semantically similar to", "based on similarity", "concept of", "field of". + * **Approved Phrasing**: Instead, use natural language that implies ranking or quality. Use words like: "top 5", "best", "most representative", "leading", or simply state the entity directly. For example, a search for the top 5 professors should be phrased as "Who are the top 5 professors?", not "Who are the 5 professors most similar to the concept of a professor?". + + 2. **Identify and Preserve Key Entities**: Within the `lembed()` text, identify the core keywords (e.g., "Professor", "Computer Science", "leadership skills"). These **MUST** be present in the final question to ensure it is specific and meaningful. + + 3. **Rephrase Naturally, Do Not Copy Verbatim**: While preserving key entities, change the overall sentence structure to fit the requested style (Formal, Colloquial, etc.). Do not copy the entire `lembed()` string word-for-word. + + --- + **Examples of Correct vs. Incorrect Behavior:** + + **Example 1: Being Natural--like a real human would ask** + * **Input VecSQL**: `... WHERE p.hasPosition_embedding MATCH lembed('all-MiniLM-L6-v2', "Professor of Computer Science") AND k = 5 ...` + * **BAD Question**: `"Identify five professors whose roles most closely match the concept of teaching computer science at a professorial level..."` or `"Please provide the IDs, names, and course levels for the five professors who have positions most closely related to the field of computer science, ordered by similarity."` + * **Reasoning**: This is the classic mistake. It describes the vector search mechanism ("most closely related to") instead of asking a direct, human-like question. Too verbose and abstract. "concept of teaching computer science at a professorial level" or "who have positions most closely related to" is an unnatural way to say "Computer Science Professor". + * **GOOD Question**: `"Please provide the IDs and course levels for the 5 professors who specialize in computer science."` or `"Identify five computer science professors and list the levels of the courses they teach."` + * **Reasoning**: Correctly uses the key entities "Professor" and "Computer Science" in a formal and direct manner. + + **Example 2: Preserving Entities** + * **Input VecSQL**: `... WHERE p.hasPosition_embedding MATCH lembed('all-MiniLM-L6-v2', "Professor of Mathematics") LIMIT 5 ...` + * **BAD Question**: `"Could you please find the top 5 individuals most semantically related to a specialized academic teaching role..."` + * **Reasoning**: Completely fails by losing the essential key entities **"Professor"** and **"Mathematics"**. The question is now uselessly vague. + * **GOOD Question**: `"Get me the top 5 people who are very professional in mathematics, and show me their course levels."` + * **Reasoning**: Preserves the critical entities in a natural, imperative sentence. + + **Example 3: Being Natural** + * **Input VecSQL**: `... WHERE performance_embedding MATCH lembed('all-MiniLM-L6-v2', "exceptional performance with leadership skills") LIMIT 1;` + * **BAD Question**: `"Hey, could you help me find the employee whose performance is most closely related to being a standout leader?"` + * **Reasoning**: "most closely related to being..." is clunky and not like a real human would ask. It also loses the "exceptional performance" aspect. + * **GOOD Question**: `"Hey, can you find the employee who performance very well and with great leadership ability'? I need their SSN."` or `"Who's our top employee showing both great performance and leadership? Grab their SSN for me."` + * **Reasoning**: Sounds like a real person talking and naturally incorporates the key concepts. + --- + ''' + + def _get_output_format_wo_ek(self): + template = '''Please structure your response as follows: + + [EXPLANATION-START] + (SQL Explanation) + [EXPLANATION-END] + + [QUESTION-START] + (Natural Language Question) + [QUESTION-END] + + - **SQL Explanation**: Provide a clear and detailed explanation of the SQL query, enclosed within [EXPLANATION-START] and [EXPLANATION-END]. + - **Natural Language Question**: Translate the SQL query into a natural language question, enclosed within [QUESTION-START] and [QUESTION-END].''' + return template + + def _get_output_format_w_ek(self): + template = '''Please structure your response as follows: + + [EXPLANATION-START] + (SQL Explanation) + [EXPLANATION-END] + + [QUESTION-START] + (Natural Language Question) + [QUESTION-END] + + [EXTERNAL-KNOWLEDGE-START] + (External Knowledge) + [EXTERNAL-KNOWLEDGE-END] + + - **SQL Explanation**: Provide a clear and detailed explanation of the SQL query, enclosed within [EXPLANATION-START] and [EXPLANATION-END]. + - **Natural Language Question**: Translate the SQL query into a natural language question, enclosed within [QUESTION-START] and [QUESTION-END]. + - **External Knowledge**: Include any relevant external knowledge if applicable, enclosed within [EXTERNAL-KNOWLEDGE-START] and [EXTERNAL-KNOWLEDGE-END]. Leave this section blank if not needed.''' + return template + + def _get_output_format_multi_round(self): + template = '''Please structure your response as follows: + + [EXPLANATION-START] + (SQL Explanation) + [EXPLANATION-END] + + [QUESTION-START] + (Natural Language Question, in the format of [{"User": ...}, {"Assistant": ...}, {"User": ...}, ....]) + [QUESTION-END] + + - **SQL Explanation**: Provide a clear and detailed explanation of the SQL query, enclosed within [EXPLANATION-START] and [EXPLANATION-END]. + - **Natural Language Question**: Convert the SQL query into a multi-round dialogue, enclosed within [QUESTION-START] and [QUESTION-END]. Represent this as a list that captures multiple rounds of conversation between the User and the Assistant.''' + return template + + def _get_instruction_wo_ek(self): + template = '''Based on the above information: + 1. Analyze the SQL query, paying special attention to any vector operations + 2. Generate a clear explanation covering all query elements + 3. Formulate a precise natural language question + 4. Verify all vector operations (MATCH, LIMIT, ORDER BY distance) or (MATCH, And k = ?) are properly represented''' + return template + + def _get_instruction_w_ek(self): + template = '''Based on the above information: + 1. Analyze the SQL query, especially vector operations + 2. Generate explanation covering all elements + 3. Formulate precise question + 4. Add relevant external knowledge about vector operations + 5. Verify all vector elements are properly represented''' + return template + + def _get_instruction_multi_round(self): + template = '''Based on the above information: + 1. Analyze the SQL query, especially vector operations + 2. Generate explanation covering all elements + 3. Create natural dialogue that explores vector search parameters + 4. Ensure LIMIT, target vector and distance sorting are discussed''' + return template + + def _question_synthesis_prompt(self, using_knn, style_desc, engine, extension, column_info, sql, steps, guidelines, output_format, instruction): + + + template = '''**Task Overview** + Your task is to create a high-quality natural language question based on a given SQL query and other information. + {using_knn} + + **Style** + The natural language question should follow this style: + {style_desc} + + **Database Engine** + {engine} + + **Database Extension** + {extension} + + **Column Information** + Below are column names and their corresponding descriptions: + {column_info} + + **SQL Query** + Given SQL query: + ```sql + {sql} + ``` + + **Reasoning Steps** + {steps} + + **Guidelines** + {guidelines} + + **Output Format** + {output_format} + + **Insturction** + {instruction} + ''' + return template.format( + using_knn = using_knn, + style_desc = style_desc, + engine = engine, + extension = extension, + column_info = column_info, + sql = sql, + steps = steps, + guidelines = guidelines, + output_format = output_format, + instruction = instruction + ) + + def build_prompt(self, input_sql, input_db_id, db_id2column_info, db_type) -> str: + styles = ["Formal", "Colloquial", "Imperative", "Interrogative", "Descriptive", "Concise", "Vague", "Metaphorical"] + style_name = random.sample(styles, 1)[0] + column_name2column_desc = db_id2column_info[input_db_id] + used_column_name2column_desc = dict() + + for column_name, column_desc in column_name2column_desc.items(): + if column_name.lower() in input_sql.lower(): + used_column_name2column_desc[column_name] = column_desc + + if style_name in ["Vague", "Metaphorical"]: + steps = self._get_steps_w_ek() + guidelines = self._get_guidelines_w_ek() + instruction = self._get_instruction_w_ek() + output_format = self._get_output_format_w_ek() + else: + steps = self._get_steps_wo_ek() + guidelines = self._get_guidelines_wo_ek() + instruction = self._get_instruction_wo_ek() + output_format = self._get_output_format_wo_ek() + + using_knn = "Extension includes sqlite-vec, you have to use KNN queries of it." + extension="sqlite_vec and sqlite_lembed" + prompt = self._question_synthesis_prompt( + using_knn=using_knn, + style_desc=self._get_style2desc()[style_name].strip(), + engine=db_type, + extension=extension, + column_info=json.dumps(used_column_name2column_desc, indent=2, ensure_ascii=False).strip(), + sql=input_sql.strip(), + steps=steps.strip(), + guidelines=guidelines.strip(), + output_format=output_format.strip(), + instruction=instruction.strip() + ) + + return prompt + + +@PROMPT_REGISTRY.register() +class SQLVariationGeneratorPrompt(PromptABC): + def __init__(self): + self.variation_type_prompts = [ + ''' + Data Value Transformations + - Alter filter conditions, date ranges, or numerical thresholds + - Change sorting criteria or limit values + - Modify aggregation boundaries (e.g., GROUP BY different time periods) + ''', + + '''Query Structure Modifications + - Convert aggregation queries to window functions or vice versa + - Change from simple queries to subqueries or CTEs + - Transform JOINs to EXISTS/IN clauses or vice versa + - Switch between correlated and non-correlated subqueries + ''', + + '''Business Logic Changes + - Adapt the query for different business scenarios (sales → inventory, customers → suppliers) + - Modify to handle different data granularities (daily → monthly, individual → grouped) + - Change the analytical perspective (profit analysis → cost analysis) + - Alter the metrics being calculated (sum → average, count → percentage) + ''', + + '''Complexity Enhancements + - Add extra filtering conditions or business rules + - Introduce additional table joins + - Include conditional logic with CASE statements + - Add data validation or quality checks + ''', + + '''Advanced SQL Features + - Implement complex window functions with partitioning + - Create queries requiring UNION/INTERSECT/EXCEPT operations + - Add recursive CTEs for hierarchical data + - Include pivot/unpivot operations + ''', + + '''Performance and Optimization + - Add performance optimization hints + - Restructure for better index usage + - Convert to more efficient query patterns + - Add appropriate WHERE clause optimizations + ''', + ] + + def _insert_stmts_template(self, insert_statements): + template = '''### INSERT INTO Statements + Below are several `INSERT INTO` statements. Use these to help generate predicates (i.e., `WHERE` clauses) in your SQL query: + {insert_statements} + ''' + return template.format(insert_statements=insert_statements) + + def _sql_variation_prompt(self, original_sql, schema_str, db_value_prompt, variation_prompt, db_engine): + template = """**Task Overview** + Create a new reasonable and executable SQL query by applying the specified transformations to the original query. + + **Database Engine** + {db_engine} + + **Database Schema** + {schema_str} + + {db_value_prompt} + + **Original SQL Query** + ```sql + {original_sql} + ``` + + **Transformation Instructions** + {variation_prompt} + + **Requirements** + 1. The new query must be syntactically correct for {db_engine} + 2. All referenced tables/columns must exist in the provided schema + 3. Ensure the query is executable + + **Output Format** + The transformed SQL query should be enclosed in a code block: + ```sql + -- Your transformed SQL query here + ``` + + **Answer** + Let's proceed step by step. + """ + return template.format( + variation_prompt=variation_prompt, + schema_str=schema_str, + db_value_prompt=db_value_prompt, + original_sql=original_sql, + db_engine=db_engine + ) + + + def build_prompt(self, original_sql, create_statements, insert_statements, db_engine) -> tuple[str, str]: + if len(insert_statements) == 0: + db_value_prompt = "" + else: + if len(insert_statements) > 4: + insert_statements = random.sample(insert_statements, 4) + db_value_prompt = self._insert_stmts_template( + insert_statements="\n\n".join(insert_statements) + ) + + variation_type = random.randint(0, 5) + variation_type_name = ["Data Value Transformations", "Query Structure Modifications", "Business Logic Changes", "Complexity Enhancements", "Advanced SQL Features", "Performance and Optimization"][variation_type] + variation_prompt = self.variation_type_prompts[variation_type] + + prompt = self._sql_variation_prompt( + original_sql=original_sql, + schema_str="\n\n".join(create_statements), + db_value_prompt=db_value_prompt.strip(), + variation_prompt=variation_prompt.strip(), + db_engine=db_engine + ) + return prompt, variation_type_name + + +@PROMPT_REGISTRY.register() +class Text2SQLPromptGeneratorPrompt(PromptABC): + def __init__(self): + pass + + def build_prompt(self, db_details: str, question: str, evidence: str, db_engine: str) -> str: + question_and_evidence = f"{evidence}\n{question}" if evidence else question + + template = """Task Overview: +You are a data science expert. Below, you are provided with a database schema and a natural language question. Your task is to understand the schema and generate a valid SQL query to answer the question. + +Database Engine: +{db_engine} + +Database Schema: +{db_details} +This schema describes the database's structure, including tables, columns, primary keys, foreign keys, any relevant relationships or constraints. + +Question: +{question_and_evidence} + +Instructions: +- Make sure you only output the information that is asked in the question. If the question asks for a specific column, make sure to only include that column in the SELECT clause, nothing more. +- The generated query should return all of the information asked in the question without any missing or extra information. +- Before generating the final SQL query, please think through the steps of how to write the query. + +Output Format: +In your answer, please enclose the generated SQL query in a code block: +```sql +-- Your SQL query +``` + +Take a deep breath and think step by step to find the correct SQL query.""" + + prompt = template.format(db_details=db_details, question_and_evidence=question_and_evidence, db_engine=db_engine) + return prompt + +@PROMPT_REGISTRY.register() +class Text2VecSQLPromptGeneratorPrompt(PromptABC): + def __init__(self): + pass + + def _get_sqlite_vec_description(self): + return """There are a few Requirements you should Comply with in addition, else you can ignore these requirements below. +1. When generating SQL queries, you should prioritize utilizing KNN searches whenever contextually appropriate. However, you have to avoid unnecessary/forced KNN implementations for: +--Traditional relational data queries (especially for columns like: id, age, price) +--Cases where standard SQL operators (equality, range, or aggregation functions) are more efficient and semantically appropriate +2. Only vector type(like: float[?]) support KNN queries and the name of vector column often end with "_embedding". So, you can use knn queries to search when the column name you need to search for ends with "_embedding" or when the column name with "_embedding" is also in the list. +3. In any complexity level, you can choose to use KNN queries if need. +4. When using KNN queries, you have to add LIMIT or 'And k = ?' constraint but do not use them all in the same statement. This rule is very important, do not forget to add LIMIT or 'And k = ?' constraint after MATCH operator. +5. The lembed function is used to transform a string into a vector, whose type and size match the corresponding column type in the data table. The function has two parameters, the first parameter is the name of the embedding model used (default value: {embedding_model}), and the second parameter is the content of the string type you want to convert. So, you should generate some words or sentences with specific semantic information based on name, type and comment of this column. For example, you can generate "The Daily Grind Coffee Shop\n 456 Oak Avenue\n Springfield, IL 62704\n USA" when this column name is Location_embedding, column type is float[384] and comment of column is "the embedding of location". +6. The lembed function's second parameter MUST be a SPECIFIC semantic description. + - For location_embedding: Generate REAL addresses (e.g. "Stadium: 123 Main St, Boston, MA. Capacity: 50,000. Home team: Patriots") + - For columns containing semantically meaningful data (e.g., descriptions), generate rich, contextually appropriate information. For columns without meaningful content (e.g., placeholder names), avoid creating semantically dense output to facilitate fuzzy matching operations. + - For name_embedding: You should generate variationsof the original names (e.g., altered spellings, phonetic approximations, or intentionally obfuscated words/characters) to enable Subsequent fuzzy matching to identify semantically similar names. Importantly, never generate redundant information. For example, you can generate "Lige", but do not generate "Ligand Lige", "Ligand example name", "Ligand similar to Aspirin" and "Ligand name variation". + Examples: + ✅ Correct: + name_embedding MATCH lembed('all-MiniLM-L6-v2', "Kri") + ❌ Wrong: + name_embedding MATCH lembed('all-MiniLM-L6-v2', "A leading publisher based in Germany specializing in +scientific journals and books.") + - For text_embedding: Use ACTUAL and meaningful sentences (e.g. "Harper Lee’s To Kill a Mockingbirdis a timeless exploration of racial injustice and moral growth, seen through the innocent yet perceptive eyes of Scout Finch. With its powerful themes, unforgettable characters like Atticus Finch, and Lee’s poignant prose, the novel remains a searing critique of society’s failures and a testament to the courage of standing for what’s right.") + - NEVER use vague words and generic phrases like "a book review" + Examples: + ✅ Correct: + lembed('all-MiniLM-L6-v2', "To Kill a Mockingbird") + ❌ Wrong: + lembed('all-MiniLM-L6-v2', "name of a famous book") +7. When using MATCH, please fill in a vector using function lembed after MATCH that matches the column type (with the same dimension and type). Using details are in examples. +8. The distance column is an ​​implicitly generated metric​​ that appears when performing vector similarity searches (using the MATCH operator) in SQLite vector extensions like sqlite-vec. If using JOIN operator, you have to clarify which table that distance belongs to. +9. A SELECT statement should have no more than one MATCH operation. However, each subquery within a SELECT statement could also have no more than one MATCH operation, independent of the parent query." +10. When performing a KNN/vector similarity search (e.g., using MATCH or lembed), always specify a LIMIT or k=N constraint directly on the vector search operation, even if the outer query already has a LIMIT. The vector search requires its own result cap to avoid ambiguity in ranking and performance issues. +11. When both LIMIT and k operations are available for vector search queries, prioritize using k operation for ​​Broader Compatibility. +Key Points: +​--​Vector search needs its own LIMIT/k​​ – The outer LIMIT applies to the final filtered results, not the initial similarity search. +--LIMIT operator should follow closely after "ORDER BY distance". +❌ Wrong Example: +```sql +SELECT a.codec_name +FROM audio_codecs a +JOIN quality_levels q ON a.codec_id = q.quality_id +WHERE a.description_embedding MATCH lembed('all-MiniLM-L6-v2', "High efficiency audio codec with low latency and optimal bandwidth") +AND q.quality_name = 'HighQuality' +LIMIT 1; +``` +✅ Correct Example: +```sql +SELECT a.codec_name +FROM audio_codecs a +JOIN quality_levels q ON a.codec_id = q.quality_id +WHERE a.description_embedding MATCH lembed('all-MiniLM-L6-v2', "High efficiency audio codec with low latency and optimal bandwidth") LIMIT 1 +AND q.quality_name = 'HighQuality'; +``` +--When using JOIN operations, you need to ensure that k does not cause ambiguity in the query. In most cases, the k parameter logically belongs to the same table as the column used in the MATCH clause. So, when the column referenced in the MATCH clause includes a table qualifier (e.g., table1.embedding), the k parameter must be explicitly bound to the same table. +❌ Wrong Example: +```sql +SELECT s.stock_id, s.symbol +FROM stocks s +JOIN exchanges e ON s.exchange_id = e.exchange_id +WHERE s.sector_embedding MATCH lembed('all-MiniLM-L6-v2', "Tech industry sector in the USA") +AND e.country = 'USA' +AND k = 5 +ORDER BY s.stock_id; +``` +✅ Correct Example: +```sql +SELECT s.stock_id, s.symbol +FROM stocks s +JOIN exchanges e ON s.exchange_id = e.exchange_id +WHERE s.sector_embedding MATCH lembed('all-MiniLM-L6-v2', "Tech industry sector in the USA") +AND e.country = 'USA' +AND s.k = 5 +ORDER BY s.stock_id; +``` +12. ​Avoids runtime errors​​ – Many vector databases (e.g., SQLite with sqlite-vss, pgvector) enforce this requirement strictly. +13. Only a single 'ORDER BY distance' clause is allowed on vec0 KNN queries, not on other columns. +***Example of KNN queries of sqlite-vec*** +first example(type of vector_embedding is float[384]): +```sql +SELECT rowid, distance +FROM vec_table +WHERE vector_embedding MATCH lembed({embedding_model},"vector of sun") +ORDER BY distance +LIMIT 1; +``` + +second example(type of sentence_embedding is float[384]): +```sql +select + movie_id, + title, + genre, + num_reviews, + mean_rating, + distance +from vec_movies +where sentence_embedding match lembed({embedding_model},"This is a great movie!") + and genre = 'scifi' + and num_reviews between 100 and 500 + and mean_rating > 3.5 + and k = 5; +``` + +third example(type of vector_embedding is float[384]): +```sql +select rowid, name1, name2, age, vec_to_json +from v +where vector_embedding match lembed({embedding_model},"aaa and xxx are good friends, whose age is 18.") + and k = 1 + and name1 in ('alex', 'brian', 'craig') + and name2 in ('Rick', 'Morty') + and age in (21, 18); +```""" + + + def build_prompt(self, db_details: str, question: str, evidence: str, db_engine: str) -> str: + if evidence: + question_and_evidence = f"{evidence}\n{question}" + else: + question_and_evidence = question + + template = """Task Overview: +You are a data science expert. Below, you are provided with a database schema and a natural language question. Your task is to understand the schema and generate a valid SQL query to answer the question. + +Database Engine: +{db_engine} + +Database Schema: +{db_details} +This schema describes the database's structure, including tables, columns, primary keys, foreign keys, and any relevant relationships or constraints. + +Question: +{question_and_evidence} + +Database Extension: +{db_extension_description} + +Instructions: +- Make sure you only output the information that is asked in the question. If the question asks for a specific column, make sure to only include that column in the SELECT clause, nothing more. +- The generated query should return all of the information asked in the question without any missing or extra information. +- Before generating the final SQL query, please think through the steps of how to write the query. + +Output Format: +In your answer, please enclose the generated SQL query in a code block: +sql +-- Your SQL query + + +Take a deep breath and think step by step to find the correct SQL query. + """ + + prompt = template.format(db_details=db_details, question_and_evidence=question_and_evidence, db_engine=db_engine, db_extension_description=self._get_sqlite_vec_description()) + return prompt diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/LocalSentenceLLMServing.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/LocalSentenceLLMServing.py new file mode 100644 index 0000000000000000000000000000000000000000..0f82a6f708de669e9b2d14ed73a6fe3e837db177 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/LocalSentenceLLMServing.py @@ -0,0 +1,184 @@ +import os +import time +from typing import List +from dataflow.core import LLMServingABC +from dataflow import get_logger + + +class LocalEmbeddingServing(LLMServingABC): + """ + Generate embeddings using local sentence-transformer models. + Interface style aligns with APILLMServing_request and supports parallel computation through max_workers. + """ + def __init__(self, + model_name: str = 'all-MiniLM-L6-v2', + device: str = None, + max_workers: int = 2, + max_retries: int = 3 + ): + """ + Initialize local embedding model. + + Args: + model_name (str): Name of the sentence-transformer model to load. + device (str): Preferred device type ('cpu' or 'cuda'). If None, will auto-detect. + max_workers (int): Number of parallel workers. + - 1 (default): No parallelism, runs on single device. + - > 1: Enable parallel mode. + - On CPU: Will enable multiprocessing mode (using all available cores). + - On multi-GPU: Will use min(max_workers, local GPU count) GPUs for data parallelism. + max_retries (int): Maximum number of retries when errors occur. + """ + self.logger = get_logger() + self.model_name = model_name + self.max_workers = max_workers + self.max_retries = max_retries + + self._model = None + self._torch = None + self._SentenceTransformer = None + self._initialized = False + + self._device = device + + def _ensure_dependencies_available(self): + if self._torch is not None and self._SentenceTransformer is not None: + return + + try: + import torch + from sentence_transformers import SentenceTransformer + self._torch = torch + self._SentenceTransformer = SentenceTransformer + except ImportError: + raise ImportError( + "The 'embedding' optional dependencies are required but not installed.\n" + "Please run: pip install 'open-dataflow[vectorsql]'" + ) + + def _initialize_model(self): + if self._initialized: + return + + self._ensure_dependencies_available() + + self._execution_strategy = "single_device" + self._target_devices = None + + device = self._device + if device is None: + device = 'cuda' if self._torch.cuda.is_available() else 'cpu' + + if self.max_workers > 1: + if 'cpu' in device: + cpu_count = os.cpu_count() or 1 + if cpu_count > 1: + self._execution_strategy = "cpu_parallel" + self.logger.info(f"CPU parallel mode enabled (max_workers > 1).") + self.logger.warning(f"Note: sentence-transformers will use all {cpu_count} available CPU cores, " + "max_workers parameter only enables this mode, does not limit core count.") + else: + self.logger.warning("max_workers > 1 but only 1 CPU core detected, falling back to single device mode.") + + elif 'cuda' in device: + gpu_count = self._torch.cuda.device_count() + if gpu_count > 1: + num_gpus_to_use = min(self.max_workers, gpu_count) + + if num_gpus_to_use > 1: + self._execution_strategy = "gpu_parallel" + self._target_devices = [f'cuda:{i}' for i in range(num_gpus_to_use)] + self.logger.info(f"Multi-GPU parallel mode enabled. Will use {num_gpus_to_use} GPUs (min({self.max_workers}, {gpu_count})).") + self.logger.info(f"Target devices: {self._target_devices}") + else: + self.logger.warning("max_workers > 1 but final GPU count for computation is 1, falling back to single device mode.") + else: + self.logger.warning("max_workers > 1 but only 1 GPU detected, falling back to single device mode.") + + if self._execution_strategy == "gpu_parallel": + self.primary_device = self._target_devices[0] + else: + self.primary_device = 'cuda:0' if 'cuda' in device and self._torch.cuda.is_available() else 'cpu' + + self.logger.info(f"Loading model '{self.model_name}' to primary device '{self.primary_device}'...") + self._model = self._SentenceTransformer(self.model_name, device=self.primary_device) + self.logger.info("Model loaded successfully.") + + self._initialized = True + + @property + def model(self): + if not self._initialized: + self._initialize_model() + return self._model + + def start_serving(self) -> None: + self.logger.info("LocalEmbeddingServing: No need to start independent service, model is already in memory.") + + def generate_embedding_from_input(self, + texts: List[str], + batch_size: int = 32 + ) -> List[List[float]]: + """ + Generate embeddings for a list of texts, including retry logic and parallel execution logic. + """ + if not self._initialized: + self._initialize_model() + + last_exception = None + for attempt in range(self.max_retries): + try: + self.logger.info(f"Starting to generate embeddings for {len(texts)} texts (attempt {attempt + 1}/{self.max_retries})...") + + if self._execution_strategy == "gpu_parallel": + pool = self.model.start_multi_process_pool(target_devices=self._target_devices) + embeddings = self.model.encode_multi_process(texts, pool=pool, batch_size=batch_size) + self.model.stop_multi_process_pool(pool) + + elif self._execution_strategy == "cpu_parallel": + pool = self.model.start_multi_process_pool() + embeddings = self.model.encode_multi_process(texts, pool=pool, batch_size=batch_size) + self.model.stop_multi_process_pool(pool) + + else: # Single device mode + embeddings = self.model.encode(texts, batch_size=batch_size, show_progress_bar=True) + + self.logger.info("Embedding generation successful.") + return embeddings.tolist() + + except Exception as e: + last_exception = e + self.logger.error(f"Error occurred while generating embeddings (attempt {attempt + 1}): {e}") + if attempt + 1 < self.max_retries: + wait_time = 2 ** attempt + self.logger.info(f"Will retry after {wait_time} seconds...") + time.sleep(wait_time) + else: + self.logger.error("All retries failed.") + raise last_exception + + return [] + + def cleanup(self): + if not self._initialized: + self.logger.info("Model not initialized, nothing to clean up.") + return + + self.logger.info(f"Cleaning up resources for model '{self.model_name}'...") + if self._model is not None: + del self._model + self._model = None + + if self._torch is not None and self._torch.cuda.is_available(): + self._torch.cuda.empty_cache() + + self._initialized = False + self.logger.info("Cleanup completed.") + + def generate_from_input(self, user_inputs: List[str], system_prompt: str = "") -> List[str]: + self.logger.warning("generate_from_input is not applicable for LocalEmbeddingServing.") + return [None] * len(user_inputs) + + def generate_from_conversations(self, conversations: List[List[dict]]) -> List[str]: + self.logger.warning("generate_from_conversations is not applicable for LocalEmbeddingServing.") + return [None] * len(conversations) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..df759981028fe8097241656f94df3a917d18437b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__init__.py @@ -0,0 +1,29 @@ +from .api_llm_serving_request import APILLMServing_request +from .local_model_llm_serving import LocalModelLLMServing_vllm +from .local_model_llm_serving import LocalModelLLMServing_sglang +from .api_vlm_serving_openai import APIVLMServing_openai +from .google_api_serving import PerspectiveAPIServing +from .lite_llm_serving import LiteLLMServing + +from .localhost_llm_api_serving import LocalHostLLMAPIServing_vllm +from .localmodel_lalm_serving import LocalModelLALMServing_vllm + +from .LocalSentenceLLMServing import LocalEmbeddingServing +from .light_rag_serving import LightRAGServing +from .api_google_vertexai_serving import APIGoogleVertexAIServing + +from .local_model_vlm_serving import LocalVLMServing_vllm + + +__all__ = [ + "APIGoogleVertexAIServing", + "APILLMServing_request", + "LocalModelLLMServing_vllm", + "LocalModelLLMServing_sglang", + "APIVLMServing_openai", + "PerspectiveAPIServing", + "LiteLLMServing", + "LocalModelLALMServing_vllm", + "LocalHostLLMAPIServing_vllm", + "LocalVLMServing_vllm", +] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/LocalSentenceLLMServing.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/LocalSentenceLLMServing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1cba9c0c7052702fd7b656ac8d2820b8e5c081f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/LocalSentenceLLMServing.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e864c0b6e041bffcbc8a584e7e32a78c94aa9153 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/api_google_vertexai_serving.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/api_google_vertexai_serving.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a89858a51d8dcf821c4b817db6ca09a0e2c87c3a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/api_google_vertexai_serving.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/api_llm_serving_request.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/api_llm_serving_request.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0ef57a6e1ea4206a9ffe13e016af8fcd3a75157 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/api_llm_serving_request.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/api_vlm_serving_openai.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/api_vlm_serving_openai.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f3c14401d5960db8d3210a6c4c708e35f7c0153 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/api_vlm_serving_openai.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/flash_rag_serving.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/flash_rag_serving.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d13b52616620db111f8c76fd40479ae4c4b47ffc Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/flash_rag_serving.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/google_api_serving.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/google_api_serving.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..303ea56242b39952eea151d98d1362dd60af11e1 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/google_api_serving.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/light_rag_serving.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/light_rag_serving.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..708981d4de55218818e76a5b3091cb3c58f47e7f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/light_rag_serving.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/lite_llm_serving.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/lite_llm_serving.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..274236faae06afd5c6c7ceecbd62f1394b6f3c4f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/lite_llm_serving.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/local_model_llm_serving.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/local_model_llm_serving.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d7845a689f74cb99678feb9c78c7a2134bfec3e Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/local_model_llm_serving.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/local_model_vlm_serving.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/local_model_vlm_serving.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5209cc6a1af2525d1a2d9782b333e2475728c4bd Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/local_model_vlm_serving.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/localhost_llm_api_serving.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/localhost_llm_api_serving.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..061e8fc0e39cc36e25b4ec881cd5a2c6a14e7448 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/localhost_llm_api_serving.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/localmodel_lalm_serving.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/localmodel_lalm_serving.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d7eb06acee5ef2a7e566a52d20c70a56a906062 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/__pycache__/localmodel_lalm_serving.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/api_google_vertexai_serving.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/api_google_vertexai_serving.py new file mode 100644 index 0000000000000000000000000000000000000000..eec77d9312a839828064d05486defc362ccf8aeb --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/api_google_vertexai_serving.py @@ -0,0 +1,1051 @@ +import os +from pyexpat import model +import time +import logging +import json +import re +import uuid +import tempfile +from mimetypes import guess_type +from pathlib import Path +from typing import Any, List, Optional, Union +from abc import ABC, abstractmethod +from concurrent.futures import ThreadPoolExecutor, as_completed +from dataflow.core import LLMServingABC +import fsspec + +from tqdm import tqdm +from pydantic import BaseModel +import pandas as pd + +# --- Dependency: Google Vertex AI SDK --- +# Make sure to install the required library: +# pip install "google-cloud-aiplatform>=1.55" pydantic tqdm "pydantic-core<2" google-cloud-bigquery google-genai +try: + # NEW: Correct imports for the modern Vertex AI SDK + import vertexai + from vertexai.generative_models import ( + GenerativeModel, + Part, + Tool, + FunctionDeclaration, + GenerationConfig, + GenerationResponse, + ) + from google.api_core import exceptions as google_exceptions + from google.cloud import bigquery + + # For batch processing + from google import genai + from google.genai.types import CreateBatchJobConfig + +except ImportError: + raise ImportError( + "Google Cloud AI Platform library not found or is outdated. " + "Please run 'pip install \"google-cloud-aiplatform>=1.55\" pydantic tqdm google-cloud-bigquery google-genai'" + ) +# --- Gemini Client Logic (Updated for modern Vertex AI SDK) --- +class GeminiVertexAIClient: + def __init__(self, project: Optional[str] = None, location: str = 'us-central1'): + """Initialize Gemini client for Vertex AI.""" + # Check required environment variables + google_app_credentials = os.getenv("GOOGLE_APPLICATION_CREDENTIALS") + google_cloud_location = os.getenv("GOOGLE_CLOUD_LOCATION") + google_cloud_project = os.getenv("GOOGLE_CLOUD_PROJECT") + google_genai_use_vertexai = os.getenv("GOOGLE_GENAI_USE_VERTEXAI") + self.logger = logging.getLogger(__name__) + # Validate GOOGLE_APPLICATION_CREDENTIALS + if not google_app_credentials: + raise ValueError( + "GOOGLE_APPLICATION_CREDENTIALS environment variable is not set. " + "Please set it to the path of your service account key file, e.g.: " + "export GOOGLE_APPLICATION_CREDENTIALS=\"/path/to/your/key.json\"" + ) + + # Check if credentials file exists + if not os.path.exists(google_app_credentials): + raise ValueError( + f"GOOGLE_APPLICATION_CREDENTIALS file not found: {google_app_credentials}. " + "Please ensure the path is correct." + ) + + # Log environment variable status + if google_cloud_location: + location = google_cloud_location + self.logger.info(f"Using GOOGLE_CLOUD_LOCATION from environment: {location}") + + if google_cloud_project: + if project is None: + project = google_cloud_project + self.logger.info(f"Using GOOGLE_CLOUD_PROJECT from environment: {project}") + else: + self.logger.warning( + f"Project parameter '{project}' provided, but GOOGLE_CLOUD_PROJECT is also set. " + f"Using parameter value '{project}'." + ) + + if google_genai_use_vertexai: + self.logger.info(f"GOOGLE_GENAI_USE_VERTEXAI is set: {google_genai_use_vertexai}") + + vertexai.init(project=project, location=location) + + # NOTE: We remove the model instance cache because each model instance will now be + # tied to a specific system_instruction, which is dynamic. + + def _prepare_content(self, content: Union[str, Path]) -> List[Part]: + """Prepares content for the Gemini model. Always returns a list of Parts.""" + if isinstance(content, (str, Path)) and os.path.exists(content) and os.path.isfile(content): + mime_type, _ = guess_type(str(content)) + if not mime_type: + mime_type = "application/octet-stream" + # Using from_uri is generally more robust for Vertex AI with local files + return [Part.from_uri(uri=str(content), mime_type=mime_type)] + elif isinstance(content, str): + return [Part.from_text(content)] + else: + raise ValueError("Only support text (str) or local file path (str or Path) as input.") + + def generate( + self, + system_prompt: str, + content: Union[str, Path], + model: Optional[str] = None, + temperature: float = 0.0, + max_tokens: int = 4096, + response_schema: Optional[Union[type[BaseModel], dict]] = None, + use_function_call: bool = False, + ) -> GenerationResponse: + """Generate response from a Gemini model on Vertex AI.""" + model_name = model + + # --- MAJOR FIX HERE --- + # The system_instruction must be passed during the model's initialization, + # not to the generate_content() method. + model_instance = GenerativeModel( + model_name, + system_instruction=system_prompt + ) + + # 先准备 GenerationConfig 的参数字典 + config_params = { + "temperature": temperature, + "max_output_tokens": max_tokens, + } + + tools = None + if response_schema is not None: + if isinstance(response_schema, dict): + # 已经是 JSON Schema + schema_dict = response_schema + else: + # 是 BaseModel,转换成 JSON Schema + schema_dict = response_schema.model_json_schema() + + # 顶层 bool 控制是否启用 function_call + if use_function_call: + function_declaration = FunctionDeclaration( + name="extract_data", + description=f"Extracts structured data according to the provided schema.", + parameters=schema_dict, + ) + tools = [Tool(function_declarations=[function_declaration])] + else: + # 无论是否启用 function_call,只要有 schema 就按 JSON 返回 + # 必须在初始化时传入,不能后续修改 + config_params["response_mime_type"] = "application/json" + config_params["response_schema"] = schema_dict + + # 使用完整参数创建 GenerationConfig + generation_config = GenerationConfig(**config_params) + + contents = self._prepare_content(content) + + # --- MAJOR FIX HERE --- + # Remove the 'system_instruction' argument from this call. + response = model_instance.generate_content( + contents=contents, + generation_config=generation_config, + tools=tools, + ) + return response + +# --- Main Implementation: GeminiLLMServing --- +class APIGoogleVertexAIServing(LLMServingABC): + """ + LLM Serving class for Google's Gemini models via Vertex AI API. + """ + def __init__(self, + model_name: str = "gemini-2.5-flash", + project: Optional[str] = None, + location: str = 'us-central1', + max_workers: int = 10, + max_retries: int = 5, + temperature: float = 0.0, + max_tokens: int = 4096, + use_function_call: bool = True, + use_batch: bool = False, + batch_wait: bool = True, + batch_dataset: str = "dataflow_batch", + csv_filename: Optional[str] = None, + bq_csv_filename: Optional[str] = None, + ): + self.logger = logging.getLogger(__name__) + logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') + + self.model_name = model_name + self.max_workers = max_workers + self.max_retries = max_retries + self.temperature = temperature + self.max_tokens = max_tokens + self.project = project + self.location = location + # 顶层开关:控制是否启用 Vertex 的 function_call(Tool 调用) + self.use_function_call = use_function_call + self.use_batch = use_batch + self.batch_wait = batch_wait + self.batch_dataset = batch_dataset + self.csv_filename = csv_filename + self.bq_csv_filename = bq_csv_filename + + try: + self.client = GeminiVertexAIClient(project=project, location=location) + self.logger.info(f"GeminiVertexAIClient initialized successfully for model '{self.model_name}'.") + except ValueError as e: + self.logger.error(f"Failed to initialize GeminiVertexAIClient: {e}") + raise + + # Initialize BigQuery client for batch processing + try: + self.bq_client = bigquery.Client(project=project) + self.logger.info("BigQuery client initialized successfully.") + except Exception as e: + self.logger.warning(f"BigQuery client initialization failed: {e}. Batch processing features may not be available.") + self.bq_client = None + + # Initialize Google GenAI client for batch processing + try: + self.genai_client = genai.Client() + self.logger.info("Google GenAI client initialized successfully.") + except Exception as e: + self.logger.warning(f"Google GenAI client initialization failed: {e}. Batch processing features may not be available.") + self.genai_client = None + + def start_serving(self) -> None: + self.logger.info("GeminiLLMServing: Using Google Cloud API, no local service to start.") + + def cleanup(self) -> None: + self.logger.info("GeminiLLMServing: No specific cleanup actions needed for API-based client.") + + def load_model(self, model_name_or_path: str, **kwargs: Any): + self.logger.info(f"Switching model from '{self.model_name}' to '{model_name_or_path}'.") + self.model_name = model_name_or_path + + def _generate_single_with_retry( + self, + index: int, + user_input: str, + system_prompt: str, + response_schema: Optional[Union[type[BaseModel], dict]] = None, + use_function_call: Optional[bool] = None, + ) -> tuple[int, Optional[str]]: + """Generates a response for a single input with a retry mechanism.""" + if use_function_call is None: + use_function_call = self.use_function_call + + for attempt in range(self.max_retries): + try: + response = self.client.generate( + system_prompt=system_prompt, + content=user_input, + model=self.model_name, + temperature=self.temperature, + max_tokens=self.max_tokens, + response_schema=response_schema, + use_function_call=use_function_call, + ) + + # NEW: Robust response parsing for both text and function calls + if not response.candidates: + finish_reason = response.prompt_feedback.block_reason.name if response.prompt_feedback else "Unknown" + self.logger.warning( + f"Request {index} was blocked or produced no candidates. Reason: {finish_reason}. Attempt {attempt + 1}/{self.max_retries}." + ) + if attempt == self.max_retries - 1: + return index, f"Error: Content blocked by API. Reason: {finish_reason}" + time.sleep(2 ** attempt) + continue + + candidate = response.candidates[0] + + # Check for safety blocks or other stop reasons + if candidate.finish_reason.name not in ["STOP", "MAX_TOKENS"]: + self.logger.warning(f"Request {index} finished with reason '{candidate.finish_reason.name}'.") + + # Check for function call (structured output) + if candidate.content.parts and candidate.content.parts[0].function_call: + function_call = candidate.content.parts[0].function_call + # Convert the structured response to a JSON string + result_data = {key: val for key, val in function_call.args.items()} + return index, json.dumps(result_data, indent=2) + + # Otherwise, return the plain text response + return index, response.text + + except (google_exceptions.ResourceExhausted, google_exceptions.ServiceUnavailable, google_exceptions.InternalServerError) as e: + self.logger.warning( + f"API rate limit or server error for request {index} (Attempt {attempt + 1}/{self.max_retries}): {e}" + ) + if attempt == self.max_retries - 1: + self.logger.error(f"Request {index} failed after {self.max_retries} retries.") + return index, f"Error: API request failed after multiple retries. Details: {e}" + time.sleep(2 ** attempt) + + except Exception as e: + self.logger.error(f"An unexpected error occurred for request {index} (Attempt {attempt + 1}/{self.max_retries}): {e}") + if attempt == self.max_retries - 1: + return index, f"Error: An unexpected error occurred. Details: {e}" + time.sleep(2 ** attempt) + + return index, None + + def generate_from_input( + self, + user_inputs: List[str], + system_prompt: str = "", + json_schema: Optional[Union[type[BaseModel], dict]] = None, + use_function_call: Optional[bool] = None, + use_batch: Optional[bool] = None, + batch_wait: Optional[bool] = None, + batch_dataset: Optional[str] = None, + csv_filename: Optional[str] = None, + bq_csv_filename: Optional[str] = None, + ) -> Union[List[str], str]: + """ + Generates responses for a list of user inputs. + + Args: + user_inputs: List of user input strings to process. + system_prompt: System prompt for the model. + json_schema: Optional Pydantic BaseModel or dict for structured output. + use_batch: If True, use batch processing via BigQuery. If False, use parallel real-time generation. + batch_wait: If True (and use_batch=True), wait for batch job to complete and return results. + If False, return the batch job name immediately for later retrieval. + batch_dataset: BigQuery dataset name for batch processing (default: "dataflow_batch"). + csv_filename: Optional CSV filename for batch processing. If None, defaults to "batch_{timestamp}_{batch_id}.csv". + + Returns: + - If use_batch=False: List of generated responses (same length as user_inputs). + - If use_batch=True and batch_wait=True: List of generated responses from batch job. + - If use_batch=True and batch_wait=False: Batch job resource name (str) for later retrieval. + """ + # 顶层 control:如果调用时未指定,则使用实例上的默认值 + if use_function_call is None: + use_function_call = self.use_function_call + + if use_batch is None: + use_batch = self.use_batch + if batch_wait is None: + batch_wait = self.batch_wait + if batch_dataset is None: + batch_dataset = self.batch_dataset + if csv_filename is None: + csv_filename = self.csv_filename + if bq_csv_filename is None: + bq_csv_filename = self.bq_csv_filename + + if use_batch: + return self._generate_with_batch( + user_inputs=user_inputs, + system_prompt=system_prompt, + response_schema=json_schema, + use_function_call=use_function_call, + wait_for_completion=batch_wait, + dataset_name=batch_dataset, + csv_filename=csv_filename, + bq_csv_filename=bq_csv_filename + ) + else: + return self._generate_with_parallel( + user_inputs=user_inputs, + system_prompt=system_prompt, + response_schema=json_schema, + use_function_call=use_function_call, + ) + + def _generate_with_parallel( + self, + user_inputs: List[str], + system_prompt: str, + response_schema: Optional[Union[type[BaseModel], dict]], + use_function_call: Optional[bool] = None, + ) -> List[str]: + """Internal method: Generates responses using parallel real-time API calls.""" + if use_function_call is None: + use_function_call = self.use_function_call + + responses = [None] * len(user_inputs) + + with ThreadPoolExecutor(max_workers=self.max_workers) as executor: + future_to_index = { + executor.submit( + self._generate_single_with_retry, + i, + user_input, + system_prompt, + response_schema, + use_function_call, + ): i + for i, user_input in enumerate(user_inputs) + } + + progress = tqdm(as_completed(future_to_index), total=len(user_inputs), desc="Generating with Gemini (Real-time)") + for future in progress: + index, result = future.result() + responses[index] = result + + return responses + + def _generate_with_batch( + self, + user_inputs: List[str], + system_prompt: str, + response_schema: Optional[Union[type[BaseModel], dict]], + use_function_call: Optional[bool], + wait_for_completion: bool, + dataset_name: str, + csv_filename: Optional[str] = None, + bq_csv_filename: Optional[str] = None + ) -> Union[List[str], str]: + """Internal method: Generates responses using batch processing via BigQuery.""" + if not self.bq_client: + raise RuntimeError( + "BigQuery client is not initialized. Cannot use batch processing. " + "Please ensure GOOGLE_APPLICATION_CREDENTIALS is set correctly." + ) + + # Generate CSV filename if not provided + timestamp = int(time.time()) + if csv_filename is None: + if bq_csv_filename is None: + batch_id = str(uuid.uuid4())[:8] + bq_csv_filename = f"batch_{timestamp}_{batch_id}.csv" + else: + # Even if user provides a bq_csv_filename, must prefix with timestamp + bq_csv_filename = f"{bq_csv_filename}_{timestamp}" + temp_csv_path = os.path.join(tempfile.gettempdir(), bq_csv_filename) + else: + # Always prefix provided csv_filename with timestamp when copying to temp + base_csv_name = Path(csv_filename).name + bq_csv_filename = f"{base_csv_name}_{timestamp}" if bq_csv_filename is None else f"{bq_csv_filename}_{timestamp}" + temp_csv_path = os.path.join(tempfile.gettempdir(), bq_csv_filename) + + try: + # Step 1: Generate CSV for batch processing + self.logger.info(f"Batch mode: Generating CSV with {len(user_inputs)} inputs...") + temp_csv_path = os.path.join(tempfile.gettempdir(), csv_filename) + self.generate_bq_csv( + csv_filename=temp_csv_path, + system_prompt=system_prompt, + user_prompts=user_inputs, + response_schema=response_schema, + use_function_call=use_function_call, + max_token=self.max_tokens + ) + + # Step 2: Upload to BigQuery + self.logger.info("Batch mode: Uploading to BigQuery...") + bq_uri = self.create_bq_table(temp_csv_path, dataset_name=dataset_name) + + # Step 3: Submit batch prediction job + self.logger.info("Batch mode: Submitting batch prediction job...") + + batch_job_name = self.run_batch_prediction(bq_uri, model=self.model_name) + + # Clean up temporary CSV file + if os.path.exists(temp_csv_path): + os.remove(temp_csv_path) + self.logger.info(f"Cleaned up temporary CSV: {temp_csv_path}") + + # Step 4: Wait for completion if requested + if wait_for_completion: + self.logger.info("Batch mode: Waiting for batch job to complete...") + results = self._wait_and_retrieve_batch_results(batch_job_name, len(user_inputs)) + return results + else: + self.logger.info(f"Batch job submitted: {batch_job_name}. Use retrieve_batch_results() to get results later.") + return batch_job_name + + except Exception as e: + # Clean up temporary CSV file on error + if 'temp_csv_path' in locals() and os.path.exists(temp_csv_path): + os.remove(temp_csv_path) + self.logger.error(f"Batch processing failed: {e}") + raise + + def _wait_and_retrieve_batch_results(self, batch_job_name: str, expected_count: int) -> List[str]: + """ + Internal method: Waits for a batch job to complete and retrieves results. + + Args: + batch_job_name: The resource name of the batch job. + expected_count: Expected number of results. + + Returns: + List of generated responses. + """ + if not self.genai_client: + raise RuntimeError("Google GenAI client is not initialized. Cannot retrieve batch results.") + + try: + # Get the batch job + batch_job = self.genai_client.batches.get(name=batch_job_name) + + # Wait for completion with progress bar + self.logger.info("Waiting for batch job to complete (this may take several minutes)...") + + # Poll for completion + max_wait_time = 3600 * 1000 # 1000 hours max + poll_interval = 30 # Check every 30 seconds + elapsed_time = 0 + + with tqdm(total=expected_count, desc="Batch job progress") as pbar: + while elapsed_time < max_wait_time: + batch_job = self.genai_client.batches.get(name=batch_job_name) + state = batch_job.state + + if state == "JOB_STATE_SUCCEEDED": + pbar.update(100 - pbar.n) + self.logger.info("Batch job completed successfully!") + break + elif state in ["JOB_STATE_FAILED", "JOB_STATE_CANCELLED"]: + raise RuntimeError(f"Batch job failed with state: {state}") + + # Update progress bar (estimate based on time) + progress = min(90, int((elapsed_time / max_wait_time) * 100)) + pbar.update(progress - pbar.n) + + time.sleep(poll_interval) + elapsed_time += poll_interval + + if elapsed_time >= max_wait_time: + raise TimeoutError(f"Batch job did not complete within {max_wait_time} seconds") + + output_table = batch_job.dest.bigquery_uri.replace("bq://", "") + project, dataset, table = output_table.split(".") + table_id = f"{project}.{dataset}.{table}" + query = f"SELECT * FROM `{table_id}`" + df = self.bq_client.query(query).to_dataframe() + + results = self._parse_batch_results(df, expected_count) + + return results + + except Exception as e: + self.logger.error(f"Failed to retrieve batch results: {e}") + raise + + def _parse_batch_results(self, df: pd.DataFrame, expected_count: int) -> List[str]: + """ + Internal method: Parses batch results from DataFrame. + + Args: + df: DataFrame containing batch results. + expected_count: Expected number of results. + + Returns: + List of generated responses in original order. + """ + results = [None] * expected_count + + for _, row in df.iterrows(): + try: + # Get the index from the response + if 'index' in df.columns: + idx = int(row['index']) + else: + # Fallback to row number + idx = _ + + # Extract the response text + if 'response' in df.columns: + response_json = json.loads(row['response']) + # Navigate through the response structure + if 'candidates' in response_json and len(response_json['candidates']) > 0: + candidate = response_json['candidates'][0] + if 'content' in candidate and 'parts' in candidate['content']: + parts = candidate['content']['parts'] + if parts and 'text' in parts[0]: + results[idx] = parts[0]['text'] + elif parts and 'functionCall' in parts[0]: + # Structured output + results[idx] = json.dumps(parts[0]['functionCall']['args']) + + # Fallback: if we couldn't parse, store the raw response + if results[idx] is None and 'response' in df.columns: + results[idx] = row['response'] + + except Exception as e: + self.logger.warning(f"Failed to parse result at index {idx}: {e}") + results[idx] = f"Error: Failed to parse result" + + return results + + def retrieve_batch_results(self, batch_job_name: str, expected_count: int) -> List[str]: + """ + Retrieves results from a previously submitted batch job. + + Args: + batch_job_name: The resource name of the batch job (returned when use_batch=True and batch_wait=False). + expected_count: Expected number of results. + + Returns: + List of generated responses. + + Example: + # Submit batch job without waiting + job_name = serving.generate_from_input(inputs, system_prompt, use_batch=True, batch_wait=False) + + # Later, retrieve results + results = serving.retrieve_batch_results(job_name, len(inputs)) + """ + return self._wait_and_retrieve_batch_results(batch_job_name, expected_count) + + # --- Batch Processing Methods --- + + def create_bq_dataset(self, dataset_name: str = "polymer") -> None: + """ + Creates a BigQuery dataset if it does not already exist. + + Args: + dataset_name: The name of the dataset to create. Defaults to "polymer". + + Raises: + RuntimeError: If BigQuery client is not initialized. + """ + if not self.bq_client: + raise RuntimeError("BigQuery client is not initialized. Cannot create dataset.") + + dataset_ref = self.bq_client.dataset(dataset_name) + dataset = bigquery.Dataset(dataset_ref) + dataset.location = self.location + + try: + self.bq_client.create_dataset(dataset) + self.logger.info(f"Dataset '{dataset_name}' created successfully.") + except Exception as e: + if "Already Exists" in str(e): + self.logger.info(f"Dataset '{dataset_name}' already exists.") + else: + self.logger.error(f"Failed to create dataset '{dataset_name}': {e}") + raise + + def generate_bq_csv( + self, + csv_filename: str, + system_prompt: str, + user_prompts: List[str], + doi_list: Optional[List[str]] = None, + response_schema: Optional[Union[type[BaseModel], dict]] = None, + use_function_call: Optional[bool] = None, + max_token: int = 500 + ) -> str: + """ + Generates a CSV file for batch processing with the Gemini API. + + Args: + csv_filename: The name of the output CSV file. + system_prompt: The system prompt string. + user_prompts: A list of texts to be processed. + doi_list: Optional list of DOIs corresponding to user prompts. + response_schema: An optional Pydantic BaseModel class or dict for the response schema. + max_token: Maximum number of output tokens. Defaults to 500. + + Returns: + The name of the generated CSV file. + """ + # 如果未显式指定,则使用实例上的默认值 + if use_function_call is None: + use_function_call = self.use_function_call + + df = pd.DataFrame({"user_prompt": user_prompts}) + + def create_batch_request_json(row) -> str: + request_parts = [ + {"text": row["user_prompt"]}, + ] + + generation_config = { + "temperature": self.temperature, + "maxOutputTokens": max_token, + "stopSequences": ["\n\n\n\n"], + "responseLogprobs": True, + "logprobs": 10, + } + + if response_schema: + # 有 schema 时优先要求 JSON 输出 + generation_config["responseMimeType"] = "application/json" + + # 只有在 use_function_call=True 时才下发 responseSchema(等价于 schema 约束) + + # Handle both BaseModel and dict schemas + if hasattr(response_schema, "model_json_schema"): + generation_config["responseSchema"] = response_schema.model_json_schema() + else: + generation_config["responseSchema"] = response_schema + + # if isinstance(response_schema, dict): + # generation_config["responseSchema"] = response_schema + # else: + # generation_config["responseSchema"] = response_schema.model_json_schema() + else: + generation_config["responseMimeType"] = "text/plain" + + return json.dumps( + { + "contents": [ + { + "role": "user", + "parts": request_parts, + }, + ], + "systemInstruction": { + "parts": [{"text": system_prompt}] + }, + "generationConfig": generation_config, + } + ) + + df["request"] = df.apply(create_batch_request_json, axis=1) + if doi_list: + df["doi"] = doi_list + df.to_csv(csv_filename, index_label="index", columns=["doi", "request"]) + else: + df.to_csv(csv_filename, index_label="index", columns=["request"]) + + self.logger.info(f"Generated batch CSV file: {csv_filename}") + return csv_filename + + def create_bq_table(self, csv_path: str, dataset_name: str = "polymer") -> str: + """ + Creates a BigQuery table from a CSV file. + + Args: + csv_path: The path to the CSV file. + dataset_name: The name of the dataset to create the table in. Defaults to "polymer". + + Returns: + The BigQuery URI of the created table (e.g., "bq://project.dataset.table"). + + Raises: + RuntimeError: If BigQuery client is not initialized. + """ + if not self.bq_client: + raise RuntimeError("BigQuery client is not initialized. Cannot create table.") + + self.create_bq_dataset(dataset_name) + + timestamp = int(time.time()) + table_name = f"{timestamp}_{Path(csv_path).stem}" + table_id = f"{dataset_name}.{table_name}" + + job_config = bigquery.LoadJobConfig( + source_format=bigquery.SourceFormat.CSV, + autodetect=True, + skip_leading_rows=1, + write_disposition=bigquery.WriteDisposition.WRITE_TRUNCATE, + ) + + with open(csv_path, "rb") as source_file: + job = self.bq_client.load_table_from_file(source_file, table_id, job_config=job_config) + + job.result() + + self.logger.info(f"Loaded {job.output_rows} rows into {table_id}") + return f"bq://{self.bq_client.project}.{dataset_name}.{table_name}" + + def run_batch_prediction( + self, + input_bq_uri: str, + model: str = None, + output_file_path: str = "" + ) -> str: + """ + Runs a batch prediction job using the Gemini API. + + Args: + input_bq_uri: The BigQuery URI of the input table (e.g., "bq://project.dataset.table") + or a path to a CSV file. If a CSV path is provided, a BigQuery table + will be created from it. + model: The ID of the model to use for prediction. Defaults to the instance's model_name. + output_file_path: Optional. The desired path for the output file. If empty, defaults to + the input path with "_result" appended to the table name. + + Returns: + The name/resource path of the created batch prediction job. + + Raises: + RuntimeError: If BigQuery client or GenAI client is not initialized. + """ + if not self.bq_client: + raise RuntimeError("BigQuery client is not initialized. Cannot run batch prediction.") + + if not self.genai_client: + raise RuntimeError("Google GenAI client is not initialized. Cannot run batch prediction.") + + # Check if input_bq_uri is a CSV file path + if input_bq_uri.endswith(".csv") and Path(input_bq_uri).is_file(): + self.logger.info(f"CSV file detected: {input_bq_uri}. Creating BigQuery table...") + input_bq_uri = self.create_bq_table(input_bq_uri) + self.logger.info(f"BigQuery table created from CSV: {input_bq_uri}") + + # Parse input_bq_uri to get project, dataset, and table name + match = re.match(r"bq://([^.]+)\.([^.]+)\.(.+)", input_bq_uri) + if not match: + raise ValueError( + f"Invalid input_bq_uri format: {input_bq_uri}. " + "Must be a BigQuery URI (bq://project.dataset.table) or a valid CSV file path." + ) + + project_id = match.group(1) + dataset_name = match.group(2) + input_table_name = match.group(3) + + # Construct the output BigQuery URI + if output_file_path: + output_table_name = Path(output_file_path).stem + else: + output_table_name = f"{input_table_name}_result" + + output_uri = f"bq://{project_id}.{dataset_name}.{output_table_name}" + + # Use the model name from instance or provided parameter + model_name = model or self.model_name + + try: + # Create batch prediction job using Google GenAI API + batch_job = self.genai_client.batches.create( + model=model_name, + src=input_bq_uri, + config=CreateBatchJobConfig(dest=output_uri) + ) + + self.logger.info(f"Batch job '{batch_job.name}' created. State: {batch_job.state}") + return batch_job.name + + except Exception as e: + self.logger.error(f"Failed to create batch prediction job: {e}") + raise + + def download_bq_table(self, table_id: str, output_file_path: str = "") -> str: + """ + Downloads data from a BigQuery table to a CSV file. + + Args: + table_id: The full BigQuery table ID (e.g., "project.dataset.table"). + output_file_path: Optional. The path to save the downloaded CSV file. + If empty, defaults to the table name with a .csv extension. + + Returns: + The path to the downloaded CSV file. + + Raises: + RuntimeError: If BigQuery client is not initialized. + """ + if not self.bq_client: + raise RuntimeError("BigQuery client is not initialized. Cannot download table.") + + # Parse table_id to get project, dataset, and table name + parts = table_id.split('.') + if len(parts) != 3: + raise ValueError( + f"Invalid table_id format: {table_id}. Expected 'project.dataset.table'." + ) + + table_name = parts[2] + + if not output_file_path: + output_file_path = f"{table_name}.csv" + + try: + table = self.bq_client.get_table(table_id) + rows = self.bq_client.list_rows(table) + df = rows.to_dataframe() + df.to_csv(output_file_path, index=False) + + self.logger.info(f"Downloaded {rows.total_rows} rows from {table_id} to {output_file_path}") + return output_file_path + + except Exception as e: + self.logger.error(f"Error downloading BigQuery table {table_id}: {e}") + raise + +# --- Example Usage (Modified) --- +if __name__ == "__main__": + # IMPORTANT: Before running, ensure you have authenticated with Google Cloud. + # This is typically done by running `gcloud auth application-default login` in your terminal. + + # --- Step 1: Check for Authentication Credentials --- + # This is a hard requirement for the API to work. + # export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/private_project.json" + if not os.getenv("GOOGLE_APPLICATION_CREDENTIALS"): + print("=" * 80) + print("FATAL: GOOGLE_APPLICATION_CREDENTIALS environment variable is not set.") + print("This is required for Vertex AI authentication.") + print("Please authenticate with Google Cloud first by running:") + print("`gcloud auth application-default login`") + print("=" * 80) + exit(1) # Exit if authentication is not configured. + + # --- Step 2: Determine Project ID (Optional) --- + # The SDK can often auto-discover the project ID if the environment variable is not set. + gcp_project_id = os.getenv("GCP_PROJECT_ID") + if not gcp_project_id: + print("=" * 80) + print("INFO: GCP_PROJECT_ID environment variable is not set.") + print("The Vertex AI SDK will attempt to automatically discover the project ID from your environment.") + print("Ensure you have set a default project via `gcloud config set project YOUR_PROJECT_ID`.") + print("=" * 80) + + # --- Step 3: Run Generation Tests --- + try: + # --- Test Case 1: Normal Text Generation --- + print("\n--- Starting Test 1: Normal Text Generation ---") + gemini_server_text = APIGoogleVertexAIServing( + project=gcp_project_id, # Pass the project_id (can be None) + location='us-central1', + model_name="gemini-2.5-flash", + max_workers=5, + max_retries=3 + ) + system_prompt_text = "You are a helpful assistant that provides concise and accurate answers." + user_prompts_text = [ + "What is the capital of France?", + "Write a short poem about the moon.", + "Explain the concept of photosynthesis in one sentence.", + ] + results_text = gemini_server_text.generate_from_input(user_prompts_text, system_prompt_text) + print("--- Generation Complete ---") + for i, (prompt, result) in enumerate(zip(user_prompts_text, results_text)): + print(f"\n[Prompt {i+1}]: {prompt}") + print(f"[Gemini]: {result}") + + # --- Test Case 2: Structured Data Extraction (PyDantic) --- + print("\n--- Starting Test 2: Structured Data Extraction (JSON Output) ---") + class UserDetails(BaseModel): + name: str + age: int + city: str + + gemini_server_json =APIGoogleVertexAIServing( + project=gcp_project_id, # Pass the project_id (can be None) + location='us-central1', + model_name="gemini-2.5-flash", + ) + system_prompt_json = "Extract the user's information from the text and format it as JSON." + user_prompts_json = [ + "John Doe is 30 years old and lives in New York.", + "My name is Jane Smith, I am 25, and I reside in London." + ] + results_json = gemini_server_json.generate_from_input(user_prompts_json, system_prompt_json, json_schema=UserDetails) # Pass the schema here + print("--- Generation Complete ---") + for i, (prompt, result) in enumerate(zip(user_prompts_json, results_json)): + print(f"\n[Prompt {i+1}]: {prompt}") + print(f"[Gemini JSON]: {result}") + + # --- Test Case 3: Structured Data Extraction (Raw JSON Schema) --- + print("\n--- Starting Test 3: Structured Data Extraction (Raw JSON Schema) ---") + json_schema = { + "title": "UserDetails", + "type": "object", + "properties": { + "name": {"type": "string"}, + "age": {"type": "integer"}, + "city": {"type": "string"} + }, + "required": ["name", "age", "city"] + } + gemini_server_json_schema = APIGoogleVertexAIServing( + project=gcp_project_id, # Pass the project_id (can be None) + location='us-central1', + model_name="gemini-2.5-flash", + ) + system_prompt_json_schema = "Extract the user's information from the text and format it as JSON." + user_prompts_json_schema = [ + "Alice Johnson is 28 years old and lives in San Francisco.", + "Bob Brown, aged 35, resides in Toronto." + ] + results_json_schema = gemini_server_json_schema.generate_from_input(user_prompts_json_schema, system_prompt_json_schema, json_schema=json_schema) + print("--- Generation Complete ---") + for i, (prompt, result) in enumerate(zip(user_prompts_json_schema, results_json_schema)): + print(f"\n[Prompt {i+1}]: {prompt}") + print(f"[Gemini JSON Schema]: {result}") + + # --- Test Case 4: Batch Processing with BigQuery (Submit without waiting) --- + print("\n--- Starting Test 4: Batch Processing (Submit without waiting) ---") + from typing import Literal + + class Capital(BaseModel): + capital: Literal["Paris", "Beijing", "London", "Tokyo"] + + gemini_server_batch = APIGoogleVertexAIServing( + project=os.getenv("GCP_PROJECT_ID"), + location='us-central1', + model_name="gemini-2.5-flash", + ) + + system_prompt_batch = "You are a helpful assistant that answers geography questions." + user_prompts_batch = [ + "What is the capital of France?", + "What is the capital of China?", + "What is the capital of the United Kingdom?", + "What is the capital of Japan?" + ] + + try: + # Submit batch job without waiting (batch_wait=False) + batch_job_name = gemini_server_batch.generate_from_input( + user_inputs=user_prompts_batch, + system_prompt=system_prompt_batch, + json_schema=Capital, + use_batch=True, + batch_wait=False # Don't wait for completion + ) + print(f"Batch job submitted: {batch_job_name}") + print("Note: Use retrieve_batch_results(batch_job_name, len(inputs)) to get results later.") + + except Exception as e: + print(f"Batch processing test (no wait) failed: {e}") + + # --- Test Case 5: Batch Processing with BigQuery (Wait for completion) --- + print("\n--- Starting Test 5: Batch Processing (Wait for completion) ---") + print("WARNING: This test will wait for batch job completion, which may take several minutes.") + print("Skipping this test in automated runs. Set ENABLE_BATCH_WAIT_TEST=1 to enable.") + + try: + # Submit batch job and wait for completion (batch_wait=True, default) + results_batch = gemini_server_batch.generate_from_input( + user_inputs=user_prompts_batch, + system_prompt=system_prompt_batch, + json_schema=Capital, + use_batch=True, + batch_wait=True # Wait for completion + ) + print("--- Batch Generation Complete ---") + for i, (prompt, result) in enumerate(zip(user_prompts_batch, results_batch)): + print(f"\n[Prompt {i+1}]: {prompt}") + print(f"[Gemini Batch]: {result}") + + except Exception as e: + print(f"Batch processing test (with wait) failed: {e}") + + except google_exceptions.PermissionDenied as e: + print(f"\nERROR: Permission Denied. Details: {e}") + print("Please ensure your account has the 'Vertex AI User' role on the project.") + print("Also, verify that the Vertex AI API is enabled for your project.") + except google_exceptions.NotFound as e: + print(f"\nERROR: Not Found. Details: {e}") + print("This might mean the project ID could not be found or the specified model/location is incorrect.") + except Exception as e: + print(f"\nAn unexpected error occurred: {e}") + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/api_llm_serving_request.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/api_llm_serving_request.py new file mode 100644 index 0000000000000000000000000000000000000000..27c4b934e595be4ed30893277be6b1a002592a4c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/api_llm_serving_request.py @@ -0,0 +1,302 @@ +import json +import warnings +import requests +from requests.adapters import HTTPAdapter +import os +import logging +from ..logger import get_logger +from concurrent.futures import ThreadPoolExecutor, as_completed +from tqdm import tqdm +from dataflow.core import LLMServingABC +import re +import time + +class APILLMServing_request(LLMServingABC): + """Use OpenAI API to generate responses based on input messages. + """ + def start_serving(self) -> None: + self.logger.info("APILLMServing_request: no local service to start.") + return + + def __init__(self, + api_url: str = "https://api.openai.com/v1/chat/completions", + key_name_of_api_key: str = "DF_API_KEY", + model_name: str = "gpt-4o", + temperature: float = 0.0, + max_workers: int = 10, + max_retries: int = 5, + connect_timeout: float = 10.0, + read_timeout: float = 120.0, + **configs : dict + ): + # Get API key from environment variable or config + self.api_url = api_url + self.model_name = model_name + # self.temperature = temperature + self.max_workers = max_workers + self.max_retries = max_retries + + self.timeout = (connect_timeout, read_timeout) # (connect timeout, read timeout) + # check for deprecated timeout + if 'timeout' in configs: + warnings.warn("The `timeout` parameter is deprecated. Please use `connect_timeout` and `read_timeout` instead.", DeprecationWarning) + self.timeout = (connect_timeout, configs['timeout']) + configs.pop('timeout') + + self.configs = configs + self.configs.update({"temperature": temperature}) + + self.logger = get_logger() + + # config api_key in os.environ global, since safty issue. + self.api_key = os.environ.get(key_name_of_api_key) + if self.api_key is None: + error_msg = f"Lack of `{key_name_of_api_key}` in environment variables. Please set `{key_name_of_api_key}` as your api-key to {api_url} before using APILLMServing_request." + self.logger.error(error_msg) + raise ValueError(error_msg) + + + self.session = requests.Session() + adapter = HTTPAdapter( + pool_connections=self.max_workers, + pool_maxsize=self.max_workers, + max_retries=0, # 你已经有 _api_chat_id_retry 了,这里不要重复重试 + pool_block=True # 池满时阻塞,避免无限建连接导致资源抖动 + ) + self.session.mount("https://", adapter) + self.session.mount("http://", adapter) + + self.headers = { + 'Authorization': f"Bearer {self.api_key}", + 'Content-Type': 'application/json', + 'User-Agent': 'Apifox/1.0.0 (https://apifox.com)' + } + + + def format_response(self, response: dict, is_embedding: bool = False) -> str: + """Format API response, supporting both embedding and chat completion modes""" + + # Handle embedding requests + if is_embedding: + return response.get('data', [{}])[0].get('embedding', []) + + # Extract message content + message = response.get('choices', [{}])[0].get('message', {}) + content = message.get('content', '') + + # Return directly if content is already in think/answer format + if re.search(r'.*?.*?.*?', content, re.DOTALL): + return content + + # Check for reasoning_content + reasoning_content = message.get('reasoning_content') + + # Wrap with think/answer tags if reasoning_content exists and is not empty + if reasoning_content: + return f"{reasoning_content}\n{content}" + + return content + # deprecated + # def api_chat(self, system_info: str, messages: str, model: str): + # try: + # payload = json.dumps({ + # "model": model, + # "messages": [ + # {"role": "system", "content": system_info}, + # {"role": "user", "content": messages} + # ], + # "temperature": self.temperature + # }) + + # headers = { + # 'Authorization': f"Bearer {self.api_key}", + # 'Content-Type': 'application/json', + # 'User-Agent': 'Apifox/1.0.0 (https://apifox.com)' + # } + # # Make a POST request to the API + # response = requests.post(self.api_url, headers=headers, data=payload, timeout=60) + # if response.status_code == 200: + # response_data = response.json() + # return self.format_response(response_data) + # else: + # logging.error(f"API request failed with status {response.status_code}: {response.text}") + # return None + # except Exception as e: + # logging.error(f"API request error: {e}") + # return None + + def _api_chat_with_id( + self, + id: int, + payload, + model: str, + is_embedding: bool = False, + json_schema: dict = None + ): + start = time.time() + try: + if is_embedding: + payload = { + "model": model, + "input": payload + } + elif json_schema is None: + payload = { + "model": model, + "messages": payload + } + else: + payload = { + "model": model, + "messages": payload, + "response_format": { + "type": "json_schema", + "json_schema": { + "name": "custom_response", + "strict": True, + "schema": json_schema + } + } + } + + payload.update(self.configs) + payload = json.dumps(payload) + # Make a POST request to the API + response = self.session.post(self.api_url, headers=self.headers, data=payload, timeout=self.timeout) + cost = time.time() - start + if response.status_code == 200: + # logging.info(f"API request successful") + response_data = response.json() + # logging.info(f"API response: {response_data['choices'][0]['message']['content']}") + return id,self.format_response(response_data, is_embedding) + else: + # self.logger.exception(f"API request failed (id = {id}) with status {response.status_code}: {response.text}") + self.logger.error(f"API request failed id={id} status={response.status_code} cost={cost:.2f}s body={response.text[:500]}") + return id, None + # ✅ 1) 连接阶段超时:认为“根本连不上” => 统一抛 RuntimeError(Win/Linux 一致) + except requests.exceptions.ConnectTimeout as e: + cost = time.time() - start + self.logger.error(f"API connect timeout (id={id}) cost={cost:.2f}s: {e}") + raise RuntimeError(f"Cannot connect to LLM server (connect timeout): {e}") from e + + # ✅ 2) 读超时:服务可达但没有数据(排队/推理太久)=> warn + None + except requests.exceptions.ReadTimeout as e: + cost = time.time() - start + warnings.warn(f"API read timeout (id={id}) cost={cost:.2f}s: {e}", RuntimeWarning) + return id, None + + # ✅ 3) 其他 Timeout(极少)按 warn 处理 + except requests.exceptions.Timeout as e: + cost = time.time() - start + warnings.warn(f"API timeout (id={id}) cost={cost:.2f}s: {e}", RuntimeWarning) + return id, None + + # ✅ 4) ConnectionError:这里面 Win/Linux/urllib3 可能包装了各种“超时/断开” + except requests.exceptions.ConnectionError as e: + cost = time.time() - start + msg = str(e).lower() + + # requests/urllib3 有时会把 ReadTimeout 包装成 ConnectionError + if "read timed out" in msg: + warnings.warn(f"API read timeout (id={id}) cost={cost:.2f}s: {e}", RuntimeWarning) + return id, None + + # 连接阶段超时在某些平台也可能表现为 ConnectionError 文本 + if "connect timeout" in msg or ("timed out" in msg and "connect" in msg): + self.logger.error(f"API connect timeout (id={id}) cost={cost:.2f}s: {e}") + raise RuntimeError(f"Cannot connect to LLM server (connect timeout): {e}") from e + + # 其它连接错误:refused/reset/remote disconnected 等 => 统一抛 RuntimeError + self.logger.error(f"API connection error (id={id}) cost={cost:.2f}s: {e}") + raise RuntimeError(f"Cannot connect to LLM server: {e}") from e + + except Exception as e: + cost = time.time() - start + self.logger.exception(f"API request error (id = {id}) cost={cost:.2f}s: {e}") + return id, None + + def _api_chat_id_retry(self, id, payload, model, is_embedding : bool = False, json_schema: dict = None): + for i in range(self.max_retries): + id, response = self._api_chat_with_id(id, payload, model, is_embedding, json_schema) + if response is not None: + return id, response + time.sleep(2**i) + return id, None + + def _run_threadpool(self, task_args_list: list[dict], desc: str) -> list: + """ + task_args_list: 每个元素都是 _api_chat_id_retry 的入参 dict + e.g. {"id": 0, "payload": [...], "model": "...", "is_embedding": False, "json_schema": None} + 返回值按 id 回填到 responses + """ + responses = [None] * len(task_args_list) + + with ThreadPoolExecutor(max_workers=self.max_workers) as executor: + futures = [ + executor.submit(self._api_chat_id_retry, **task_args) + for task_args in task_args_list + ] + + for future in tqdm(as_completed(futures), total=len(futures), desc=desc): + try: + response = future.result() # (id, response) + # response[0] 是 id,response[1] 是实际响应, 用于按 id 回填 responses 列表 + responses[response[0]] = response[1] + except Exception: + # 理论上 worker 内部已经 try/except 了,但这里兜底更安全 + self.logger.exception("Worker crashed unexpectedly in threadpool") + + return responses + + def generate_from_input(self, + user_inputs: list[str], + system_prompt: str = "You are a helpful assistant", + json_schema: dict = None, + ) -> list[str]: + task_args_list = [ + dict( + id=idx, + payload=[ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": question}, + ], + model=self.model_name, + json_schema=json_schema, + ) + for idx, question in enumerate(user_inputs) + ] + return self._run_threadpool(task_args_list, desc="Generating responses from prompts......") + + + def generate_from_conversations(self, conversations: list[list[dict]]) -> list[str]: + + task_args_list = [ + dict( + id=idx, + payload=dialogue, + model=self.model_name, + ) + for idx, dialogue in enumerate(conversations) + ] + return self._run_threadpool(task_args_list, desc="Generating responses from conversations......") + + + def generate_embedding_from_input(self, texts: list[str]) -> list[list[float]]: + task_args_list = [ + dict( + id=idx, + payload=txt, + model=self.model_name, + is_embedding=True, + ) + for idx, txt in enumerate(texts) + ] + return self._run_threadpool(task_args_list, desc="Generating embedding......") + + def cleanup(self): + self.logger.info("Cleaning up resources in APILLMServing_request") + try: + if hasattr(self, "session") and self.session: + self.session.close() + except Exception: + self.logger.exception("Failed to close requests session") \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/api_vlm_serving_openai.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/api_vlm_serving_openai.py new file mode 100644 index 0000000000000000000000000000000000000000..670aecb29dcf76647196bf7c58144427c2ad5f78 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/api_vlm_serving_openai.py @@ -0,0 +1,376 @@ +import os +import base64 +import json +from typing import Any, Dict, List, Tuple +from concurrent.futures import ThreadPoolExecutor, as_completed +from dataflow.core import LLMServingABC +from openai import OpenAI +from tqdm import tqdm + +from ..logger import get_logger + + +class APIVLMServing_openai(LLMServingABC): + """ + Client for interacting with a Vision-Language Model (VLM) via OpenAI's API. + + Provides methods for single-image chat, batch image processing, and multi-image analysis, + with support for concurrent requests. + """ + def start_serving(self) -> None: + self.logger.info("APIVLMServing_opneai: no local service to start.") + return + + def __init__( + self, + api_url: str = "https://api.openai.com/v1", + key_name_of_api_key: str = "DF_API_KEY", + model_name: str = "o4-mini", + max_workers: int = 10, + timeout: int = 1800, + temperature = 0.0 + ): + """ + Initialize the OpenAI client and settings. + + :param api_url: Base URL of the VLM API endpoint. + :param key_name_of_api_key: Environment variable name for the API key. + :param model_name: Default model name to use for requests. + :param max_workers: Maximum number of threads for concurrent requests. + """ + self.api_url = api_url + self.model_name = model_name + self.max_workers = max_workers + self.logger = get_logger() + self.timeout = timeout + self.temperature = temperature + api_key = os.environ.get(key_name_of_api_key) + if not api_key: + self.logger.error(f"API key not found in environment variable '{key_name_of_api_key}'") + raise EnvironmentError(f"Missing environment variable '{key_name_of_api_key}'") + + self.client = OpenAI( + api_key=api_key, + base_url=api_url + ) + def _encode_image_to_base64(self, image_path: str) -> Tuple[str, str]: + """ + Read an image file and convert it to a base64-encoded string, returning the image data and MIME format. + + :param image_path: Path to the image file. + :return: Tuple of (base64-encoded string, image format, e.g. 'jpeg' or 'png'). + :raises ValueError: If the image format is unsupported. + """ + with open(image_path, "rb") as f: + raw = f.read() + b64 = base64.b64encode(raw).decode("utf-8") + ext = image_path.rsplit('.', 1)[-1].lower() + + if ext == 'jpg': + fmt = 'jpeg' + elif ext == 'jpeg': + fmt = 'jpeg' + elif ext == 'png': + fmt = 'png' + else: + raise ValueError(f"Unsupported image format: {ext}") + + return b64, fmt + + def _create_messages(self, content: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + """ + Wrap content items into the standard OpenAI messages structure. + + :param content: List of content dicts (text/image elements). + :return: Messages payload for the API call. + """ + return [{"role": "user", "content": content}] + + def _send_chat_request( + self, + model: str, + messages: List[Dict[str, Any]], + timeout: int, + json_schema: dict = None + ) -> str: + """ + Send a chat completion request to the OpenAI API and return the generated content. + + :param model: Model name for the request. + :param messages: Messages payload constructed by `_create_messages`. + :param timeout: Timeout in seconds for the API call. + :param json_schema: Optional JSON schema for structured output. + :return: Generated text response from the model. + """ + # 准备请求参数 + request_params = { + "model": model, + "messages": messages, + "timeout": timeout, + "temperature": self.temperature + } + + # 如果提供了 JSON schema,添加 response_format + if json_schema is not None: + request_params["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "chart_info_response", + "strict": True, + "schema": json_schema + } + } + + resp = self.client.chat.completions.create(**request_params) + return resp.choices[0].message.content + + def chat_with_one_image( + self, + image_path: str, + text_prompt: str, + model: str = None, + timeout: int = 1800, + json_schema: dict = None + ) -> str: + """ + Perform a chat completion using a single image and a text prompt. + + :param image_path: Path to the image file. + :param text_prompt: Text prompt to accompany the image. + :param model: (Optional) Model override; defaults to instance `model_name`. + :param timeout: Timeout in seconds for the API call. + :param json_schema: (Optional) JSON schema for structured output. + :return: Model's response as a string. + """ + model = model or self.model_name + b64, fmt = self._encode_image_to_base64(image_path) + content = [ + {"type": "text", "text": text_prompt}, + {"type": "image_url", "image_url": {"url": f"data:image/{fmt};base64,{b64}"}} + ] + messages = self._create_messages(content) + return self._send_chat_request(model, messages, timeout, json_schema) + + def chat_with_one_image_with_id( + self, + request_id: Any, + image_path: str, + text_prompt: str, + model: str = None, + timeout: int = 1800, + json_schema: dict = None, + ) -> Tuple[Any, str]: + """ + Same as `chat_with_one_image` but returns a tuple of (request_id, response). + + :param request_id: Arbitrary identifier for tracking the request. + :param image_path: Path to the image file. + :param text_prompt: Text prompt to accompany the image. + :param model: (Optional) Model override; defaults to instance `model_name`. + :param timeout: Timeout in seconds for the API call. + :return: Tuple of (request_id, model response). + """ + response = self.chat_with_one_image(image_path, text_prompt, model, timeout, json_schema) + return request_id, response + + def generate_from_input_one_image( + self, + image_paths: List[str], + text_prompts: List[str], + system_prompt: str = "", + model: str = None, + timeout: int = 1800, + json_schema: dict = None + ) -> List[str]: + """ + Batch process single-image chat requests concurrently. + + :param image_paths: List of image file paths. + :param text_prompts: List of text prompts (must match length of image_paths). + :param system_prompt: Optional system-level prompt prefixed to each user prompt. + :param model: (Optional) Model override; defaults to instance `model_name`. + :param timeout: Timeout in seconds for each API call. + :param json_schema: (Optional) JSON schema for structured output. + :return: List of model responses preserving input order. + :raises ValueError: If lengths of image_paths and text_prompts differ. + """ + if len(image_paths) != len(text_prompts): + raise ValueError("`image_paths` and `text_prompts` must have the same length") + + model = model or self.model_name + prompts = [f"{system_prompt}\n{p}" for p in text_prompts] + responses = [None] * len(image_paths) + + with ThreadPoolExecutor(max_workers=self.max_workers) as executor: + futures = { + executor.submit( + self.chat_with_one_image_with_id, + idx, + path, + prompt, + model, + timeout, + json_schema + ): idx + for idx, (path, prompt) in enumerate(zip(image_paths, prompts)) + } + + for future in tqdm(as_completed(futures), total=len(futures), desc="Generating..."): + idx, res = future.result() + responses[idx] = res + + return responses + + def analyze_images_with_gpt( + self, + image_paths: List[str], + image_labels: List[str], + system_prompt: str = "", + model: str = None, + timeout: int = 1800, + json_schema: dict = None + ) -> str: + """ + Analyze multiple images in a single request with labels. + + :param image_paths: List of image file paths. + :param image_labels: Corresponding labels for each image. + :param system_prompt: Overall prompt before listing images. + :param model: (Optional) Model override; defaults to instance `model_name`. + :param timeout: Timeout in seconds for the API call. + :return: Model's combined analysis as text. + """ + if len(image_paths) != len(image_labels): + raise ValueError("`image_paths` and `image_labels` must have the same length") + + model = model or self.model_name + content: List[Dict[str, Any]] = [] + if system_prompt: + content.append({"type": "text", "text": system_prompt}) + + for label, path in zip(image_labels, image_paths): + b64, fmt = self._encode_image_to_base64(path) + content.append({"type": "text", "text": f"{label}:"}) + content.append({ + "type": "image_url", + "image_url": {"url": f"data:image/{fmt};base64,{b64}"} + }) + + messages = self._create_messages(content) + return self._send_chat_request(model, messages, timeout, json_schema) + + def analyze_images_with_gpt_with_id( + self, + image_paths: List[str], + image_labels: List[str], + request_id: Any, + system_prompt: str = "", + model: str = None, + timeout: int = 1800, + json_schema: dict = None + ) -> Tuple[Any, str]: + """ + Batch-tracked version of `analyze_images_with_gpt`, returning (request_id, analysis). + + :param image_paths: List of image file paths. + :param image_labels: Corresponding labels for each image. + :param request_id: Identifier for tracking the request. + :param system_prompt: Overall prompt before listing images. + :param model: (Optional) Model override; defaults to instance `model_name`. + :param timeout: Timeout in seconds for the API call. + :return: Tuple of (request_id, model's analysis). + """ + result = self.analyze_images_with_gpt( + image_paths, + image_labels, + system_prompt, + model, + timeout, + json_schema + ) + # self.logger.info(f"Request {request_id} completed") + return request_id, result + + def generate_from_input_multi_images( + self, + list_of_image_paths: List[List[str]], + list_of_image_labels: List[List[str]], + system_prompt: str = "", + user_prompts: List[str] = None, + model: str = None, + timeout: int = 1800, + json_schema: dict = None + ) -> List[str]: + """ + Concurrently analyze multiple sets of images with labels. + + :param list_of_image_paths: List of image path lists. + :param list_of_image_labels: Parallel list of label lists. + :param system_prompt: Prompt prefixed to each batch. + :param model: (Optional) Model override; defaults to instance `model_name`. + :param timeout: Timeout in seconds for each API call. + :return: List of analysis results in input order. + :raises ValueError: If outer lists lengths differ. + """ + if len(list_of_image_paths) != len(list_of_image_labels): + raise ValueError( + "`list_of_image_paths` and `list_of_image_labels` must have the same length" + ) + + model = model or self.model_name + responses = [None] * len(list_of_image_paths) + + if user_prompts == None: + user_prompts = [""] * len(list_of_image_paths) + + with ThreadPoolExecutor(max_workers=self.max_workers) as executor: + futures = { + executor.submit( + self.analyze_images_with_gpt_with_id, + paths, + labels, + idx, + system_prompt + user_prompt, + model, + timeout, + json_schema + ): idx + for idx, (paths, labels, user_prompt) in enumerate( + zip(list_of_image_paths, list_of_image_labels, user_prompts) + ) + } + + for future in tqdm(as_completed(futures), total=len(futures), desc="Generating..."): + idx, res = future.result() + responses[idx] = res + + return responses + + def cleanup(self) -> None: + """ + Clean up any resources (e.g., close HTTP connections). + """ + self.client.close() + + def generate_from_input(self, user_inputs: List[str], system_prompt: str = "Describe the image in detail.", json_schema: dict = None): + """ + user_inputs: List[str], list of picture paths + system_prompt: str, system prompt + return: List[str], list of generated contents + """ + futures = [] + result_text_list = [None] * len(user_inputs) + with ThreadPoolExecutor(max_workers=self.max_workers) as executor: + for idx,user_input in enumerate(user_inputs): + futures.append(executor.submit(self.chat_with_one_image_with_id, + idx, + user_input, + system_prompt, + self.model_name, + self.timeout, + json_schema = json_schema,)) + for future in tqdm(as_completed(futures), total=len(futures), desc="Generating"): + idx,res = future.result() + result_text_list[idx] = res + return result_text_list + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/flash_rag_serving.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/flash_rag_serving.py new file mode 100644 index 0000000000000000000000000000000000000000..89049a56a72dab10c92acfe822b7d889f7de2fe9 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/flash_rag_serving.py @@ -0,0 +1,126 @@ +import asyncio +from typing import List, Any, Dict +from concurrent.futures import ThreadPoolExecutor + +from dataflow.logger import get_logger +from flashrag.config import Config +from flashrag.utils import get_retriever +from dataflow.core import LLMServingABC + +import asyncio +from typing import List, Any, Dict, Optional +from concurrent.futures import ThreadPoolExecutor + +from dataflow.core import LLMServingABC +from dataflow.logger import get_logger + +from flashrag.config import Config +from flashrag.utils import get_retriever + +class FlashRAGServing(LLMServingABC): + def __init__(self, + retrieval_method: str = "e5", + retrieval_model_path: str = None, + index_path: str = None, + corpus_path: str = None, + faiss_gpu: bool = False, + gpu_id: str = "", + + max_workers: int = 1, + topk: int = 2, + **kwargs + ): + """ + Args: + retrieval_method: 检索方法名称 (e.g. "e5", "bm25") + retrieval_model_path: 检索模型路径 + index_path: 索引文件路径 + corpus_path: 语料库路径 (.jsonl) + faiss_gpu: 是否使用 GPU 进行 FAISS 检索 + gpu_id: 指定使用的 GPU ID + max_workers: 线程池最大工作线程数 + topk: 默认检索数量 + **kwargs: 其他可能传递给 FlashRAG Config 的参数 + """ + self.logger = get_logger() + + if not retrieval_model_path or not index_path or not corpus_path: + self.logger.warning("FlashRAGServing initialized without critical paths (model, index, or corpus). " + "Ensure they are passed before loading.") + + self.rag_config_dict = { + "retrieval_method": retrieval_method, + "retrieval_model_path": retrieval_model_path, + "index_path": index_path, + "corpus_path": corpus_path, + "faiss_gpu": faiss_gpu, + "gpu_id": gpu_id, + } + + # 将额外的 kwargs 也合并进去,以支持更高级的 FlashRAG 配置 + self.rag_config_dict.update(kwargs) + + self.topk = topk + self.executor = ThreadPoolExecutor(max_workers=max_workers) + self.retriever = None + + def load_model(self, model_name_or_path: str = None, **kwargs: Any): + """ + 加载 Retriever。 + 注意:这里不再读取文件,而是使用 init 中保存的字典配置。 + model_name_or_path 参数保留是为了兼容基类接口,实际上不使用。 + """ + self.logger.info("Initializing FlashRAG Config from parameters...") + + try: + # 使用 config_dict 初始化 FlashRAG Config + # FlashRAG 的 Config 类通常接受 config_file_path 和 config_dict + config = Config(config_dict=self.rag_config_dict) + + self.logger.info(f"Loading Retriever with method: {self.rag_config_dict.get('retrieval_method')}...") + self.retriever = get_retriever(config) + self.logger.info("FlashRAG Retriever loaded successfully.") + except Exception as e: + self.logger.error(f"Failed to load FlashRAG retriever: {e}") + raise e + + def start_serving(self): + if self.retriever is None: + self.logger.warning("FlashRAGServing started but retriever is NOT loaded. Call load_model() first.") + else: + self.logger.info("FlashRAGServing is ready to serve.") + + async def cleanup(self): + self.logger.info("Cleaning up FlashRAGServing resources...") + self.executor.shutdown(wait=True) + + async def generate_from_input(self, user_inputs: List[str], system_prompt: str = "") -> List[List[str]]: + if self.retriever is None: + self.logger.warning("Retriever not loaded explicitly. Triggering lazy load...") + loop = asyncio.get_running_loop() + await loop.run_in_executor(self.executor, lambda: self.load_model()) + + topk = self.topk + loop = asyncio.get_running_loop() + + def _run_sync_search(): + return self.retriever.batch_search(user_inputs, topk, return_score=True) + + try: + results, scores = await loop.run_in_executor(self.executor, _run_sync_search) + + # results 结构: [ [doc1_obj, doc2_obj...], [doc1_obj, doc2_obj...] ] + formatted_outputs = [] + + for docs in results: + # 提取 content,保持 List[str] 结构以便后续 explode + docs_content_list = [doc.get('contents', '') for doc in docs] + formatted_outputs.append(docs_content_list) + + # 返回 List[List[str]] + return formatted_outputs + + except Exception as e: + self.logger.error(f"Error during retrieval: {e}") + # 出错时返回空列表的列表,保持维度一致 + return [[] for _ in user_inputs] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/google_api_serving.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/google_api_serving.py new file mode 100644 index 0000000000000000000000000000000000000000..6df77bad19c22aabaf2af0b2ecf279bd3c2a481c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/google_api_serving.py @@ -0,0 +1,53 @@ +import os +from concurrent.futures import ThreadPoolExecutor, as_completed +from tqdm import tqdm +from googleapiclient import discovery +from dataflow.core import LLMServingABC + +class PerspectiveAPIServing(LLMServingABC): + """Service adapter for Google Perspective API.""" + def __init__(self, max_workers: int = 10): + self.api_key = os.environ.get("GOOGLE_API_KEY") + if self.api_key is None: + raise ValueError("Lack of Google API_KEY") + self.max_workers = max_workers + self.client = discovery.build( + "commentanalyzer", + "v1alpha1", + developerKey=self.api_key, + discoveryServiceUrl="https://commentanalyzer.googleapis.com/$discovery/rest?version=v1alpha1", + static_discovery=False, + ) + + + def _call_api(self, text: str) -> float: + """Invoke the Perspective API for a single text chunk and return toxicity score.""" + analyze_request = { + 'comment': { 'text': text }, + 'requestedAttributes': {'TOXICITY': {}} + } + + response = self.client.comments().analyze(body=analyze_request).execute() + # extract the first span score + return response['attributeScores']['TOXICITY']['spanScores'][0]['score']['value'] + + def generate_from_input(self, user_inputs: list[str]) -> list[float]: # type: ignore + """ + Process a list of input texts concurrently and return toxicity scores. + """ + scores: dict[int, float] = {} + with ThreadPoolExecutor(max_workers=self.max_workers) as executor: + futures = {executor.submit(self._call_api, text): idx + for idx, text in enumerate(user_inputs)} + for fut in tqdm(as_completed(futures), total=len(futures), desc="Scoring"): + idx = futures[fut] + try: + scores[idx] = fut.result() + except Exception as e: + scores[idx] = float('nan') + return [scores[i] for i in range(len(user_inputs))] + + def cleanup(self) -> None: + """Cleanup any resources or open connections if necessary.""" + # No persistent resources to clean up + return \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/light_rag_serving.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/light_rag_serving.py new file mode 100644 index 0000000000000000000000000000000000000000..68fed440844f3f87ffc274f9ea1567044fbfa1eb --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/light_rag_serving.py @@ -0,0 +1,146 @@ +import os +import time +import re +from typing import List, Optional, Dict, Any, Union, Tuple + +from dataflow.core import LLMServingABC +from dataflow.logger import get_logger + +import asyncio +from tqdm.asyncio import tqdm_asyncio + +WORKING_DIR = "./LightRAG" + +async def initialize_rag( + llm_model_name, api_url, api_key, embed_model_name, embed_binding_host, embedding_dim, max_embed_tokens): + + async def llm_model_func( + prompt, system_prompt=None, history_messages=[], keyword_extraction=False, **kwargs + ) -> str: + return await openai_complete_if_cache( + llm_model_name, + prompt, + system_prompt=system_prompt, + history_messages=history_messages, + api_key=api_key, + base_url=api_url, + **kwargs, + ) + + rag = LightRAG( + working_dir=WORKING_DIR, + llm_model_func=llm_model_func, + embedding_func=EmbeddingFunc( + embedding_dim=embedding_dim, + max_token_size=max_embed_tokens, + func=lambda texts: ollama_embed( + texts, + embed_model=embed_model_name, + host=embed_binding_host + ), + ), + ) + + await rag.initialize_storages() + await initialize_pipeline_status() + return rag + +class LightRAGServing(LLMServingABC): + def __init__(self, + api_url: str = "https://api.openai.com/v1", + key_name_of_api_key: str = "DF_API_KEY", + llm_model_name: str = "gpt-4o", + embed_model_name: str = "bge-m3:latest", + embed_binding_host: str = "http://localhost:11434", + embedding_dim: int = 1024, + max_embed_tokens: int = 8192, + document_list: List[str] = [] + ): + try: + from lightrag import LightRAG, QueryParam + from lightrag.llm.openai import openai_complete_if_cache + from lightrag.llm.ollama import ollama_embed + from lightrag.utils import EmbeddingFunc + from lightrag.kg.shared_storage import initialize_pipeline_status + except ImportError: + raise Exception( + """ + lightrag is not installed in this environment yet. + Please use pip install lightrag-hku. + """ + ) + + self.rag: LightRAG = None + self.api_url = api_url + self.llm_model_name = llm_model_name + self.embed_model_name = embed_model_name + self.embed_binding_host = embed_binding_host + self.embedding_dim = embedding_dim + self.max_embed_tokens = max_embed_tokens + self.logger = get_logger() + self.document_list = document_list + + # config api_key in os.environ global, since safty issue. + self.api_key = os.environ.get(key_name_of_api_key) + if self.api_key is None: + error_msg = f"Lack of `{key_name_of_api_key}` in environment variables. Please set `{key_name_of_api_key}` as your api-key to {api_url} before using APILLMServing_request." + self.logger.error(error_msg) + raise ValueError(error_msg) + + @classmethod + async def create(cls, *args, **kwargs) -> "LightRAGServing": + instance = cls(*args, **kwargs) + if instance.rag is None: + instance.rag = await initialize_rag( + instance.llm_model_name, + instance.api_url, + instance.api_key, + instance.embed_model_name, + instance.embed_binding_host, + instance.embedding_dim, + instance.max_embed_tokens + ) + try: + instance.logger.info("Loading documents...") + await instance.load_documents(instance.document_list) + instance.logger.info("Documents processing completed.") + except Exception as e: + instance.logger.error(f"Error during documents processing: {e}\n") + return + + return instance + + def start_serving(self): + pass + + async def cleanup(self): + if self.rag: + storages = [ + self.rag.text_chunks, + self.rag.full_docs, + self.rag.entities_vdb, + self.rag.relationships_vdb, + self.rag.chunks_vdb, + self.rag.chunk_entity_relation_graph, + self.rag.doc_status, + self.rag.llm_response_cache + ] + await asyncio.gather(*[s.drop() for s in storages], return_exceptions=True) + + await self.rag.finalize_storages() + + async def load_documents(self, document_paths: List[str]): + tasks = [] + for path in document_paths: + with open(path, "r", encoding="utf-8") as f: + tasks.append(self.rag.ainsert(f.read())) + await asyncio.gather(*tasks, return_exceptions=True) + + async def generate_from_input(self, user_inputs: List[str], system_prompt: str) -> List[str]: + tasks = [ + self.rag.aquery(question, system_prompt=system_prompt, param=QueryParam(mode="hybrid")) + for question in user_inputs + ] + responses = await tqdm_asyncio.gather(*tasks) + return list(responses) + \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/lite_llm_serving.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/lite_llm_serving.py new file mode 100644 index 0000000000000000000000000000000000000000..706684aa9ddc54d9e126cbd98402b0f09250f3e4 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/lite_llm_serving.py @@ -0,0 +1,453 @@ +import os +import time +import re +from typing import List, Optional, Dict, Any, Tuple, Literal +from concurrent.futures import ThreadPoolExecutor, as_completed +from tqdm import tqdm +from dataflow.core import LLMServingABC +from dataflow.logger import get_logger + +class LiteLLMServing(LLMServingABC): + """ + LiteLLM-based serving class that provides unified interface for multiple LLM providers. + Supports OpenAI, Anthropic, Cohere, Azure, AWS Bedrock, Google and many more providers. + + This implementation avoids global state pollution by passing configuration parameters + directly to each litellm.completion() call, ensuring thread safety and proper isolation + between different instances. Configuration parameters are immutable after initialization. + + Doc: https://docs.litellm.ai/docs/providers + """ + def start_serving(self) -> None: + self.logger.info("LiteLLMServing: no local service to start.") + return + def start_serving(self) -> None: + self.logger.info("LiteLLMServing: no local service to start.") + return + + def __init__(self, + serving_type: Literal["chat", "embedding"] = "chat", + validate_on_init: bool = True, + api_url: str = "https://api.openai.com/v1/chat/completions", + key_name_of_api_key: str = "DF_API_KEY", + model_name: str = "gpt-4o", + max_workers: int = 10, + max_retries: int = 5, + api_version: Optional[str] = None, + temperature: float = 0.7, + max_tokens: int = 1024, + top_p: float = 1.0, + timeout: int = 60, + custom_llm_provider: str = None, + **kwargs: Any): + """ + Initialize LiteLLM serving instance. + + Args: + serving_type: Type of serving, "chat" or "embedding" + validate_on_init: Whether to validate the model and API configuration on initialization + api_url: Custom API base URL + key_name_of_api_key: Environment variable name for API key (default: "DF_API_KEY") + model_name: Model name (e.g., "gpt-4o", "claude-3-sonnet", "command-r-plus") + max_workers: Number of concurrent workers for batch processing + max_retries: Number of LLM inference retry chances for each input + api_url: Custom API base URL + key_name_of_api_key: Environment variable name for API key (default: "DF_API_KEY") + model_name: Model name (e.g., "gpt-4o", "claude-3-sonnet", "command-r-plus") + max_workers: Number of concurrent workers for batch processing + max_retries: Number of LLM inference retry chances for each input + api_version: API version for providers that support it + temperature: Sampling temperature + max_tokens: Maximum tokens to generate + top_p: Top-p sampling parameter + timeout: Request timeout in seconds + custom_llm_provider: + Optional custom provider name registered in LiteLLM for routing requests to + non-default backends (e.g., self-hosted OpenAI-compatible APIs or private endpoints). + Example: `"my_local_llm"` or `"company-internal-provider"`. + **kwargs: Additional parameters passed to litellm.completion() + + Note: + All configuration parameters are immutable after initialization. + If you need different settings, create a new instance. + """ + + # Import litellm at initialization time to support lazy importing + try: + import litellm + self._litellm = litellm + except ImportError: + raise ImportError( + "litellm is not installed. Please install it with: " + "pip install open-dataflow[litellm] or pip install litellm" + ) + + self.serving_type = serving_type + self.model_name = model_name + self.api_url = api_url + self.api_version = api_version + self.temperature = temperature + self.max_tokens = max_tokens + self.max_retries = max_retries + self.top_p = top_p + self.max_workers = max_workers + self.timeout = timeout + self.kwargs = kwargs + self.logger = get_logger() + + # Get API key from environment variable + self.api_key = os.environ.get(key_name_of_api_key) + if self.api_key is None: + error_msg = f"Lack of `{key_name_of_api_key}` in environment variables. Please set `{key_name_of_api_key}` as your api-key before using LiteLLMServing." + self.logger.error(error_msg) + raise ValueError(error_msg) + self.key_name_of_api_key = key_name_of_api_key + if custom_llm_provider is not None: + self.custom_llm_provider = custom_llm_provider + # Validate model by making a test call + if validate_on_init: + self._validate_setup() + + self.logger.info(f"LiteLLMServing initialized with model: {model_name}") + + def switch_model(self, + model_name: str, + key_name_of_api_key: Optional[str] = None, + api_url: Optional[str] = None, + api_version: Optional[str] = None, + **kwargs: Any): + """ + Switch to a different model with potentially different API configuration. + + Args: + model_name: Model name to switch to + key_name_of_api_key: New environment variable name for API key (optional) + api_url: New API base URL (optional) + api_version: New API version (optional) + **kwargs: Additional parameters for the new model + """ + # Update model + self.model_name = model_name + + # Update API key if new environment variable provided + if key_name_of_api_key is not None: + self.api_key = os.environ.get(key_name_of_api_key) + if self.api_key is None: + error_msg = f"Lack of `{key_name_of_api_key}` in environment variables. Please set `{key_name_of_api_key}` as your api-key before switching model." + self.logger.error(error_msg) + raise ValueError(error_msg) + self.key_name_of_api_key = key_name_of_api_key + + # Update other API configuration if provided + if api_url is not None: + self.api_url = api_url + if api_version is not None: + self.api_version = api_version + + # Update other parameters from kwargs + for key, value in kwargs.items(): + if hasattr(self, key): + setattr(self, key, value) + else: + self.kwargs[key] = value + + # Validate the new configuration + self._validate_setup() + self.logger.success(f"Switched to model: {model_name}") + + def format_response(self, response: Dict[str, Any]) -> str: + """ + Format LiteLLM response to include reasoning content in a structured format. + + This method handles the standardized LiteLLM response format and extracts + both the main content and any reasoning_content if available. + + Args: + response: The response dictionary from LiteLLM + + Returns: + Formatted string with think/answer tags if reasoning is present, + otherwise just the content + """ + try: + # Extract the main content + content = response['choices'][0]['message']['content'] + + # Check if content already has think/answer format + if re.search(r'.*.*.*', content, re.DOTALL): + return content + + # Try to extract reasoning_content from LiteLLM standardized format + reasoning_content = "" + try: + # LiteLLM provides reasoning_content in the message object + message = response['choices'][0]['message'] + if hasattr(message, 'reasoning_content') and message.reasoning_content: + reasoning_content = message.reasoning_content + elif isinstance(message, dict) and 'reasoning_content' in message: + reasoning_content = message['reasoning_content'] + except (KeyError, AttributeError): + pass + + # Format the response based on whether reasoning content exists + if reasoning_content: + return f"{reasoning_content}\n{content}" + else: + return content + + except (KeyError, IndexError) as e: + self.logger.error(f"Error formatting response: {e}") + # Return original response as string if formatting fails + return str(response) + + def _validate_setup(self): + """Validate the model and API configuration.""" + try: + # Prepare common parameters + common_params = { + "model": self.model_name, + "timeout": self.timeout + } + + # Add optional parameters if provided + if self.api_key: + common_params["api_key"] = self.api_key + if self.api_url: + common_params["api_base"] = self.api_url + if self.api_version: + common_params["api_version"] = self.api_version + if hasattr(self, "custom_llm_provider"): + common_params["custom_llm_provider"] = self.custom_llm_provider + + # Make a minimal test call to validate setup + if self.serving_type == "embedding": + self._litellm.embedding( + input=["test"], + **common_params, + ) + else: + self._litellm.completion( + messages=[{"role": "user", "content": "Hi"}], + max_tokens=1, + **common_params, + ) + + self.logger.success("LiteLLM setup validation successful") + except Exception as e: + self.logger.error(f"LiteLLM setup validation failed: {e}") + raise ValueError(f"Failed to validate LiteLLM setup: {e}") + + def _generate_single(self, user_input: str, system_prompt: str, json_schema: dict = None) -> str: + """Generate response for a single input with retry logic. + + Args: + user_input: User input text + system_prompt: System prompt + + Returns: + Generated response string + + Raises: + Exception: If generation fails after all retries + """ + messages = [ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": user_input} + ] + + # Prepare completion parameters + completion_params = { + "model": self.model_name, + "messages": messages, + "temperature": self.temperature, + "max_tokens": self.max_tokens, + "top_p": self.top_p, + "timeout": self.timeout, + **self.kwargs + } + + # Add optional parameters if provided + if self.api_key: + completion_params["api_key"] = self.api_key + if self.api_url: + completion_params["api_base"] = self.api_url + if self.api_version: + completion_params["api_version"] = self.api_version + if json_schema is not None: + completion_params["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "structural_response", + "strict": True, + "schema": json_schema + } + } + + if hasattr(self, "custom_llm_provider"): + completion_params["custom_llm_provider"] = self.custom_llm_provider + + last_error = None + for attempt in range(self.max_retries): + try: + response = self._litellm.completion(**completion_params) + # Convert response to dict format for format_response + response_dict = response.model_dump() if hasattr(response, 'model_dump') else response.dict() + return self.format_response(response_dict) + except Exception as e: + last_error = e + if attempt < self.max_retries - 1: + # Check if error is retryable + error_str = str(e).lower() + if any(retryable in error_str for retryable in + ["rate limit", "timeout", "connection", "503", "502", "429"]): + wait_time = min(2 ** attempt, 10) # Exponential backoff with max 10s + self.logger.warning(f"Retryable error, waiting {wait_time}s: {e}") + time.sleep(wait_time) + continue + + # Non-retryable error or last attempt + self.logger.error(f"Error generating response (attempt {attempt + 1}/{self.max_retries}): {e}") + break + + # Raise the last error instead of returning error string + raise last_error + + def generate_from_input(self, + user_inputs: List[str], + system_prompt: str = "You are a helpful assistant", + json_schema: dict = None, + ) -> List[str]: + """ + Generate responses for a list of inputs using concurrent processing. + + Args: + user_inputs: List of user input strings + system_prompt: System prompt to use for all generations + + Returns: + List of generated responses + """ + if not user_inputs: + return [] + + # Single input case + if len(user_inputs) == 1: + try: + return [self._generate_single(user_inputs[0], system_prompt, json_schema)] + except Exception as e: + # For consistency with batch processing, return error message in list + error_msg = f"Error: {str(e)}" + self.logger.error(f"Failed to generate response: {e}") + return [error_msg] + + # Batch processing with threading + responses = [None] * len(user_inputs) + + def generate_with_index(idx: int, user_input: str) -> Tuple[int, str]: + try: + response = self._generate_single(user_input, system_prompt,json_schema) + return idx, response + except Exception as e: + # For batch processing, return error message to maintain list structure + error_msg = f"Error: {str(e)}" + self.logger.error(f"Failed to generate response for input {idx}: {e}") + return idx, error_msg + + with ThreadPoolExecutor(max_workers=self.max_workers) as executor: + futures = [ + executor.submit(generate_with_index, idx, user_input) + for idx, user_input in enumerate(user_inputs) + ] + + for future in tqdm(as_completed(futures), total=len(futures), desc="Generating"): + idx, response = future.result() + responses[idx] = response + + return responses + + def generate_embedding_from_input(self, texts: List[str]) -> List[List[float]]: + """ + Generate embeddings for a list of texts. + + Args: + texts: List of text strings to embed + + Returns: + List of embedding vectors + """ + if not texts: + return [] + + embeddings = [] + + # Prepare embedding parameters + embedding_params = { + "model": self.model_name, + "timeout": self.timeout + } + + # Add optional parameters if provided + if self.api_key: + embedding_params["api_key"] = self.api_key + if self.api_url: + embedding_params["api_base"] = self.api_url + if self.api_version: + embedding_params["api_version"] = self.api_version + + # Process embeddings with retry logic + def embed_with_retry(text: str): + last_error = None + for attempt in range(self.max_retries): + try: + response = self._litellm.embedding( + input=[text], + **embedding_params + ) + return response['data'][0]['embedding'] + except Exception as e: + last_error = e + if attempt < self.max_retries - 1: + error_str = str(e).lower() + if any(retryable in error_str for retryable in + ["rate limit", "timeout", "connection", "503", "502", "429"]): + wait_time = min(2 ** attempt, 10) + self.logger.warning(f"Retryable error in embedding, waiting {wait_time}s: {e}") + time.sleep(wait_time) + continue + self.logger.error(f"Error generating embedding (attempt {attempt + 1}/{self.max_retries}): {e}") + break + raise last_error + + # Process in batches for better performance + with ThreadPoolExecutor(max_workers=self.max_workers) as executor: + futures = [executor.submit(embed_with_retry, text) for text in texts] + + for future in tqdm(as_completed(futures), total=len(futures), desc="Generating embeddings"): + try: + embedding = future.result() + embeddings.append(embedding) + except Exception as e: + self.logger.error(f"Failed to generate embedding: {e}") + # Return empty embedding for failed cases to maintain list structure + embeddings.append([]) + + return embeddings + + def get_supported_models(self) -> List[str]: + """Get list of supported models for the current provider.""" + try: + return self._litellm.model_list + except Exception as e: + self.logger.warning(f"Could not retrieve model list: {e}") + return [] + + + def cleanup(self) -> None: + """Cleanup resources.""" + self.logger.info("Cleaning up LiteLLMServing resources") + # LiteLLM doesn't require explicit cleanup since we don't use global state + # Instance variables will be garbage collected when the instance is destroyed + # Clear any references to ensure proper cleanup + self.api_key = None + self.kwargs = None + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/local_model_llm_serving.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/local_model_llm_serving.py new file mode 100644 index 0000000000000000000000000000000000000000..86e10fbf240ae5717247edbd1d0b31f8df25c22a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/local_model_llm_serving.py @@ -0,0 +1,460 @@ +import os +import torch +import contextlib +import time +from typing import Optional, Union, List, Dict, Any +from dataflow import get_logger +from huggingface_hub import snapshot_download +from dataflow.core import LLMServingABC +from transformers import AutoTokenizer + +class LocalModelLLMServing_vllm(LLMServingABC): + ''' + A class for generating text using vllm, with model from huggingface or local directory + ''' + def __init__(self, + hf_model_name_or_path: str = None, + hf_cache_dir: str = None, + hf_local_dir: str = None, + vllm_tensor_parallel_size: int = 1, + vllm_temperature: float = 0.7, + vllm_top_p: float = 0.9, + vllm_max_tokens: int = 1024, + vllm_top_k: int = 40, + vllm_repetition_penalty: float = 1.0, + vllm_seed: int = None, + vllm_max_model_len: int = None, + vllm_gpu_memory_utilization: float=0.9, + ): + self.logger = get_logger() + self.load_model( + hf_model_name_or_path=hf_model_name_or_path, + hf_cache_dir=hf_cache_dir, + hf_local_dir=hf_local_dir, + vllm_tensor_parallel_size=vllm_tensor_parallel_size, + vllm_temperature=vllm_temperature, + vllm_top_p=vllm_top_p, + vllm_max_tokens=vllm_max_tokens, + vllm_top_k=vllm_top_k, + vllm_repetition_penalty=vllm_repetition_penalty, + vllm_seed=vllm_seed, + vllm_max_model_len=vllm_max_model_len, + vllm_gpu_memory_utilization=vllm_gpu_memory_utilization, + ) + self.backend_initialized = False + + def load_model(self, + hf_model_name_or_path: str = None, + hf_cache_dir: str = None, + hf_local_dir: str = None, + vllm_tensor_parallel_size: int = 1, + vllm_temperature: float = 0.7, + vllm_top_p: float = 0.9, + vllm_max_tokens: int = 1024, + vllm_top_k: int = 40, + vllm_repetition_penalty: float = 1.0, + vllm_seed: int = 42, + vllm_max_model_len: int = None, + vllm_gpu_memory_utilization: float=0.9, + ): + + self.hf_model_name_or_path = hf_model_name_or_path + self.hf_cache_dir = hf_cache_dir + self.hf_local_dir = hf_local_dir + self.vllm_tensor_parallel_size = vllm_tensor_parallel_size + self.vllm_temperature = vllm_temperature + self.vllm_top_p = vllm_top_p + self.vllm_max_tokens = vllm_max_tokens + self.vllm_top_k = vllm_top_k + self.vllm_repetition_penalty = vllm_repetition_penalty + self.vllm_seed = vllm_seed + self.vllm_max_model_len = vllm_max_model_len + self.vllm_gpu_memory_utilization = vllm_gpu_memory_utilization + + def start_serving(self): + self.backend_initialized = True + self.logger = get_logger() + if self.hf_model_name_or_path is None: + raise ValueError("hf_model_name_or_path is required") + elif os.path.exists(self.hf_model_name_or_path): + self.logger.info(f"Using local model path: {self.hf_model_name_or_path}") + self.real_model_path = self.hf_model_name_or_path + else: + self.logger.info(f"Downloading model from HuggingFace: {self.hf_model_name_or_path}") + self.real_model_path = snapshot_download( + repo_id=self.hf_model_name_or_path, + cache_dir=self.hf_cache_dir, + local_dir=self.hf_local_dir, + ) + + # Import vLLM and set up the environment for multiprocessing + # vLLM requires the multiprocessing method to be set to spawn + try: + from vllm import LLM, SamplingParams + except ValueError as ve: + # A ValueError typically indicates a transformers version mismatch + raise ImportError( + "Failed to import vllm due to a ValueError: this is often caused by a transformers version conflict. " + "Please check your transformers package and upgrade or downgrade it to the version required by vllm." + ) from ve + except ImportError as ie: + # vllm is not installed + raise ImportError( + "vllm is not installed. Please install it by running:\n" + " pip install open-dataflow[vllm]\n" + "If it is already installed, ensure that the installation environment matches your current runtime environment." + ) from ie + + + # Set the environment variable for vllm to use spawn method for multiprocessing + # See https://docs.vllm.ai/en/v0.7.1/design/multiprocessing.html + os.environ['VLLM_WORKER_MULTIPROC_METHOD'] = "spawn" + + self.sampling_params = SamplingParams( + temperature=self.vllm_temperature, + top_p=self.vllm_top_p, + max_tokens=self.vllm_max_tokens, + top_k=self.vllm_top_k, + repetition_penalty=self.vllm_repetition_penalty, + seed=self.vllm_seed + ) + + self.llm = LLM( + model=self.real_model_path, + tensor_parallel_size=self.vllm_tensor_parallel_size, + max_model_len=self.vllm_max_model_len, + gpu_memory_utilization=self.vllm_gpu_memory_utilization, + ) + self.tokenizer = AutoTokenizer.from_pretrained(self.real_model_path, cache_dir=self.hf_cache_dir) + self.logger.success(f"Model loaded from {self.real_model_path} by vLLM backend") + + def generate_from_input(self, + user_inputs: list[str], + system_prompt: str = "You are a helpful assistant", + json_schema: dict = None, + ) -> list[str]: + if not self.backend_initialized: + self.start_serving() + full_prompts = [] + for question in user_inputs: + messages = [ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": question} + ] + full_prompts.append(messages) + full_template = self.tokenizer.apply_chat_template( + full_prompts, + tokenize=False, + add_generation_prompt=True, + enable_thinking=True, # Set to False to strictly disable thinking + ) + if json_schema is not None: + try: + from vllm import SamplingParams + from vllm.sampling_params import GuidedDecodingParams + except Exception: + raise ImportError("please install vllm first like 'pip install open-dataflow[vllm]'") + + guided_decoding_params = GuidedDecodingParams( + json=json_schema + ) + + self.sampling_params = SamplingParams( + temperature=self.vllm_temperature, + top_p=self.vllm_top_p, + max_tokens=self.vllm_max_tokens, + top_k=self.vllm_top_k, + repetition_penalty=self.vllm_repetition_penalty, + seed=self.vllm_seed, + guided_decoding=guided_decoding_params + ) + + responses = self.llm.generate(full_template, self.sampling_params) + return [output.outputs[0].text for output in responses] + + def generate_embedding_from_input(self, texts: list[str]) -> list[list[float]]: + if not self.backend_initialized: + self.start_serving() + outputs = self.llm.embed(texts) + return [output.outputs.embedding for output in outputs] + + def cleanup(self): + self.backend_initialized = False + + if torch.cuda.is_available(): + free_mem = torch.cuda.mem_get_info()[0] + total_mem = torch.cuda.get_device_properties(0).total_memory + self.logger.info(f"Free memory: {free_mem / (1024 ** 2):.2f} MB / {total_mem / (1024 ** 2):.2f} MB") + + self.logger.info("Cleaning up vLLM backend resources...") + + if not hasattr(self, "llm") or self.llm is None: + import gc + gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + try: + import ray + ray.shutdown() + except Exception: + pass + return + + from vllm.distributed.parallel_state import ( + destroy_model_parallel, + destroy_distributed_environment, + ) + + if hasattr(self.llm, "llm_engine"): + del self.llm.llm_engine + del self.llm + destroy_model_parallel() + destroy_distributed_environment() + with contextlib.suppress(AssertionError): + torch.distributed.destroy_process_group() + import gc + gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + try: + import ray + ray.shutdown() + except Exception: + pass + + if torch.cuda.is_available(): + free_mem = torch.cuda.mem_get_info()[0] + total_mem = torch.cuda.get_device_properties(0).total_memory + self.logger.info(f"Free memory: {free_mem / (1024 ** 2):.2f} MB / {total_mem / (1024 ** 2):.2f} MB") + +class LocalModelLLMServing_sglang(LLMServingABC): + def __init__( + self, + hf_model_name_or_path: str = None, + hf_cache_dir: str = None, + hf_local_dir: str = None, + sgl_tp_size: int = 1, # tensor parallel size + sgl_dp_size: int = 1, # data parallel size + sgl_mem_fraction_static: float = 0.9, # memory fraction for static memory allocation + sgl_max_new_tokens: int = 2048, # maximum number of new tokens to generate + sgl_stop: Optional[Union[str, List[str]]] = None, + sgl_stop_token_ids: Optional[List[int]] = None, + sgl_temperature: float = 1.0, + sgl_top_p: float = 1.0, + sgl_top_k: int = -1, + sgl_min_p: float = 0.0, + sgl_frequency_penalty: float = 0.0, + sgl_presence_penalty: float = 0.0, + sgl_repetition_penalty: float = 1.0, + sgl_min_new_tokens: int = 0, + sgl_n: int = 1, + sgl_json_schema: Optional[str] = None, + sgl_regex: Optional[str] = None, + sgl_ebnf: Optional[str] = None, + sgl_structural_tag: Optional[str] = None, + sgl_ignore_eos: bool = False, + sgl_skip_special_tokens: bool = True, + sgl_spaces_between_special_tokens: bool = True, + sgl_no_stop_trim: bool = False, + sgl_custom_params: Optional[Dict[str, Any]] = None, + sgl_stream_interval: Optional[int] = None, + sgl_logit_bias: Optional[Dict[str, float]] = None, + ): + self.logger = get_logger() + self.load_model( + hf_model_name_or_path=hf_model_name_or_path, + hf_cache_dir=hf_cache_dir, + hf_local_dir=hf_local_dir, + sgl_tp_size=sgl_tp_size, + sgl_dp_size=sgl_dp_size, + sgl_mem_fraction_static=sgl_mem_fraction_static, # memory fraction for static + sgl_max_new_tokens=sgl_max_new_tokens, + sgl_stop=sgl_stop, + sgl_stop_token_ids=sgl_stop_token_ids, + sgl_temperature=sgl_temperature, + sgl_top_p=sgl_top_p, + sgl_top_k=sgl_top_k, + sgl_min_p=sgl_min_p, + sgl_frequency_penalty=sgl_frequency_penalty, + sgl_presence_penalty=sgl_presence_penalty, + sgl_repetition_penalty=sgl_repetition_penalty, + sgl_min_new_tokens=sgl_min_new_tokens, + sgl_n=sgl_n, + sgl_json_schema=sgl_json_schema, + sgl_regex=sgl_regex, + sgl_ebnf=sgl_ebnf, + sgl_structural_tag=sgl_structural_tag, + sgl_ignore_eos=sgl_ignore_eos, + sgl_skip_special_tokens=sgl_skip_special_tokens, + sgl_spaces_between_special_tokens=sgl_spaces_between_special_tokens, + sgl_no_stop_trim=sgl_no_stop_trim, + sgl_custom_params=sgl_custom_params, + sgl_stream_interval=sgl_stream_interval, + sgl_logit_bias=sgl_logit_bias, + ) + self.backend_initialized = False + + def load_model( + self, + hf_model_name_or_path:str = None, + hf_cache_dir:str = None, + hf_local_dir:str = None, + sgl_tp_size: int = 1, + sgl_dp_size: int = 1, + sgl_mem_fraction_static: float = 0.9, # memory fraction for static memory allocation + sgl_max_new_tokens: int = 2048, + sgl_stop: Optional[Union[str, List[str]]] = None, + sgl_stop_token_ids: Optional[List[int]] = None, + sgl_temperature: float = 1.0, + sgl_top_p: float = 1.0, + sgl_top_k: int = -1, + sgl_min_p: float = 0.0, + sgl_frequency_penalty: float = 0.0, + sgl_presence_penalty: float = 0.0, + sgl_repetition_penalty: float = 1.0, + sgl_min_new_tokens: int = 0, + sgl_n: int = 1, + sgl_json_schema: Optional[str] = None, + sgl_regex: Optional[str] = None, + sgl_ebnf: Optional[str] = None, + sgl_structural_tag: Optional[str] = None, + sgl_ignore_eos: bool = False, + sgl_skip_special_tokens: bool = True, + sgl_spaces_between_special_tokens: bool = True, + sgl_no_stop_trim: bool = False, + sgl_custom_params: Optional[Dict[str, Any]] = None, + sgl_stream_interval: Optional[int] = None, + sgl_logit_bias: Optional[Dict[str, float]] = None, + ): + self.hf_model_name_or_path = hf_model_name_or_path + self.hf_cache_dir = hf_cache_dir + self.hf_local_dir = hf_local_dir + self.sgl_tp_size = sgl_tp_size + self.sgl_dp_size = sgl_dp_size + self.sgl_mem_fraction_static = sgl_mem_fraction_static + self.sgl_max_new_tokens = sgl_max_new_tokens + self.sgl_stop = sgl_stop + self.sgl_stop_token_ids = sgl_stop_token_ids + self.sgl_temperature = sgl_temperature + self.sgl_top_p = sgl_top_p + self.sgl_top_k = sgl_top_k + self.sgl_min_p = sgl_min_p + self.sgl_frequency_penalty = sgl_frequency_penalty + self.sgl_presence_penalty = sgl_presence_penalty + self.sgl_repetition_penalty = sgl_repetition_penalty + self.sgl_min_new_tokens = sgl_min_new_tokens + self.sgl_n = sgl_n + self.sgl_json_schema = sgl_json_schema + self.sgl_regex = sgl_regex + self.sgl_ebnf = sgl_ebnf + self.sgl_structural_tag = sgl_structural_tag + self.sgl_ignore_eos = sgl_ignore_eos + self.sgl_skip_special_tokens = sgl_skip_special_tokens + self.sgl_spaces_between_special_tokens = sgl_spaces_between_special_tokens + self.sgl_no_stop_trim = sgl_no_stop_trim + self.sgl_custom_params = sgl_custom_params + self.sgl_stream_interval = sgl_stream_interval + self.sgl_logit_bias = sgl_logit_bias + + def start_serving(self): + self.backend_initialized = True + self.logger = get_logger() + if self.hf_model_name_or_path is None: + raise ValueError("hf_model_name_or_path is required") + elif os.path.exists(self.hf_model_name_or_path): + self.logger.info(f"Using local model path: {self.hf_model_name_or_path}") + self.real_model_path = self.hf_model_name_or_path + else: + self.logger.info(f"Downloading model from HuggingFace: {self.hf_model_name_or_path}") + self.real_model_path = snapshot_download( + repo_id=self.hf_model_name_or_path, + cache_dir=self.hf_cache_dir, + local_dir=self.hf_local_dir, + ) + + # import sglang and set up the environment for multiprocessing + try: + import sglang as sgl + except ImportError: + raise ImportError("please install sglang first like 'pip install open-dataflow[sglang]'") + self.llm = sgl.Engine( + model_path=self.real_model_path, + tp_size=self.sgl_tp_size, + dp_size=self.sgl_dp_size, + mem_fraction_static=self.sgl_mem_fraction_static, # memory fraction for static memory allocation + ) + self.sampling_params = { + "max_new_tokens": self.sgl_max_new_tokens, + "stop": self.sgl_stop, + "stop_token_ids": self.sgl_stop_token_ids, + "temperature": self.sgl_temperature, + "top_p": self.sgl_top_p, + "top_k": self.sgl_top_k, + "min_p": self.sgl_min_p, + "frequency_penalty": self.sgl_frequency_penalty, + "presence_penalty": self.sgl_presence_penalty, + "repetition_penalty": self.sgl_repetition_penalty, + "min_new_tokens": self.sgl_min_new_tokens, + "n": self.sgl_n, + "json_schema": self.sgl_json_schema, + "regex": self.sgl_regex, + "ebnf":self.sgl_ebnf, + "structural_tag": self.sgl_structural_tag, + "ignore_eos": self.sgl_ignore_eos, + "skip_special_tokens": self.sgl_skip_special_tokens, + "spaces_between_special_tokens": self.sgl_spaces_between_special_tokens, + "no_stop_trim": self.sgl_no_stop_trim, + "custom_params": self.sgl_custom_params, + "stream_interval":self.sgl_stream_interval, + "logit_bias": self.sgl_logit_bias, + } + # remove all keys equal to None + self.sampling_params = {k: v for k, v in self.sampling_params.items() if v is not None} + + self.tokenizer = AutoTokenizer.from_pretrained(self.real_model_path, cache_dir=self.hf_cache_dir) + self.logger.success(f"Model loaded from {self.real_model_path} by SGLang backend") + + def generate_from_input(self, + user_inputs: list[str], + system_prompt: str = "You are a helpful assistant" + ) -> list[str]: + if not self.backend_initialized: + self.start_serving() + full_prompts = [] + for question in user_inputs: + messages = [ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": question} + ] + full_prompts.append(messages) + full_template = self.tokenizer.apply_chat_template( + full_prompts, + tokenize=False, + add_generation_prompt=True, + enable_thinking=True, # Set to False to strictly disable thinking + ) + try: + responses = self.llm.generate(full_template, self.sampling_params) + except Exception as e: + self.logger.error(f"Error during Sglang Backend generation, please check your parameters.: {e}") + raise e + + return [output['text'] for output in responses] + + def generate_embedding_from_input(self, texts: list[str]) -> list[list[float]]: + raise NotImplementedError("SGLang backend does not support embedding generation yet. If you have experience with SGLang, please contribute to this feature in Pull Request.") + # if not self.backend_initialized: + # self.start_serving() + # self.llm. + # outputs = self.llm.embed(texts) + # return [output['embedding'] for output in outputs] + + def cleanup(self): + self.logger.info("Cleaning up SGLang backend resources...") + self.backend_initialized = False + self.llm.shutdown() + del self.llm + import gc; + gc.collect() + torch.cuda.empty_cache() + \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/local_model_vlm_serving.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/local_model_vlm_serving.py new file mode 100644 index 0000000000000000000000000000000000000000..046f76708d285a5c69c3d83af57ee0b2e4c3b665 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/local_model_vlm_serving.py @@ -0,0 +1,361 @@ +import os +import torch +import contextlib +from typing import List, Optional, Union, Dict, Any +from PIL import Image +import re + +from dataflow import get_logger +from huggingface_hub import snapshot_download +from dataflow.core import LLMServingABC +from transformers import AutoTokenizer + +class LocalVLMServing_vllm(LLMServingABC): + """ + Client for serving a Vision-Language Model (VLM) locally using vLLM. + Combines the interface of APIVLMServing with the backend efficiency of vLLM. + """ + def __init__(self, + hf_model_name_or_path: str = None, + hf_cache_dir: str = None, + hf_local_dir: str = None, + vllm_tensor_parallel_size: int = 1, + vllm_temperature: float = 0.2, # Lower temperature is usually better for VLM tasks + vllm_top_p: float = 0.9, + vllm_max_tokens: int = 1024, + vllm_max_model_len: int = None, + vllm_top_k: int = 40, + vllm_repetition_penalty: float = 1.0, + vllm_seed: int = None, + vllm_gpu_memory_utilization: float = 0.9, + vllm_limit_mm_per_prompt: int = 1, # Specific to VLMs: max images per prompt + trust_remote_code: bool = True, + enable_thinking:bool =True, # Set to False to strictly disable thinking + batch_size: int = 128 + ): + """ + Initialize the Local VLM Serving client. + """ + self.logger = get_logger() + QWEN_VL_PATTERN = re.compile(r'Qwen-VL|Qwen[0-9\.]+-VL') + # 报Warning显示目前经过测试的VLM主要是QwenVL + if hf_model_name_or_path and not QWEN_VL_PATTERN.search(hf_model_name_or_path): + self.logger.warning( + "Model Compatibility Alert: LocalVLMServing_vllm is primarily tested with Qwen-VL models " + "(e.g., Qwen-VL-Chat, Qwen2.5-VL-Chat). Other VLMs may require additional adjustments " + "for correct functionality." + ) + self.load_model( + hf_model_name_or_path=hf_model_name_or_path, + hf_cache_dir=hf_cache_dir, + hf_local_dir=hf_local_dir, + vllm_tensor_parallel_size=vllm_tensor_parallel_size, + vllm_temperature=vllm_temperature, + vllm_top_p=vllm_top_p, + vllm_max_tokens=vllm_max_tokens, + vllm_top_k=vllm_top_k, + vllm_repetition_penalty=vllm_repetition_penalty, + vllm_seed=vllm_seed, + vllm_max_model_len=vllm_max_model_len, + vllm_gpu_memory_utilization=vllm_gpu_memory_utilization, + vllm_limit_mm_per_prompt=vllm_limit_mm_per_prompt, + trust_remote_code=trust_remote_code, + enable_thinking=enable_thinking + ) + self.backend_initialized = False + self.batch_size = batch_size + + def load_model(self, + hf_model_name_or_path: str = None, + hf_cache_dir: str = None, + hf_local_dir: str = None, + vllm_tensor_parallel_size: int = 1, + vllm_temperature: float = 0.2, + vllm_top_p: float = 0.9, + vllm_max_tokens: int = 1024, + vllm_max_model_len: int = None, + vllm_top_k: int = 40, + vllm_repetition_penalty: float = 1.0, + vllm_seed: int = None, + vllm_gpu_memory_utilization: float = 0.9, + vllm_limit_mm_per_prompt: int = 1, + trust_remote_code: bool = True, + enable_thinking:bool =True, + ): + + self.hf_model_name_or_path = hf_model_name_or_path + self.hf_cache_dir = hf_cache_dir + self.hf_local_dir = hf_local_dir + self.vllm_tensor_parallel_size = vllm_tensor_parallel_size + self.vllm_temperature = vllm_temperature + self.vllm_top_p = vllm_top_p + self.vllm_max_tokens = vllm_max_tokens + self.vllm_max_model_len = vllm_max_model_len + self.vllm_top_k = vllm_top_k + self.vllm_repetition_penalty = vllm_repetition_penalty + self.vllm_seed = vllm_seed + self.vllm_gpu_memory_utilization = vllm_gpu_memory_utilization + self.vllm_limit_mm_per_prompt = vllm_limit_mm_per_prompt + self.trust_remote_code = trust_remote_code + self.enable_thinking = enable_thinking + + def start_serving(self): + self.backend_initialized = True + self.logger = get_logger() + + # 1. Handle Model Path (HuggingFace or Local) + if self.hf_model_name_or_path is None: + raise ValueError("hf_model_name_or_path is required") + elif os.path.exists(self.hf_model_name_or_path): + self.logger.info(f"Using local model path: {self.hf_model_name_or_path}") + self.real_model_path = self.hf_model_name_or_path + else: + self.logger.info(f"Downloading model from HuggingFace: {self.hf_model_name_or_path}") + self.real_model_path = snapshot_download( + repo_id=self.hf_model_name_or_path, + cache_dir=self.hf_cache_dir, + local_dir=self.hf_local_dir, + ) + + # 2. Import vLLM and Setup Environment + try: + from vllm import LLM, SamplingParams + except ImportError: + raise ImportError("please install vllm first like 'pip install open-dataflow[vllm]'") + + # Set environment for multiprocessing compatibility + os.environ['VLLM_WORKER_MULTIPROC_METHOD'] = "spawn" + + self.sampling_params = SamplingParams( + temperature=self.vllm_temperature, + top_p=self.vllm_top_p, + max_tokens=self.vllm_max_tokens, + top_k=self.vllm_top_k, + repetition_penalty=self.vllm_repetition_penalty, + seed=self.vllm_seed + ) + + # 3. Initialize LLM Engine with VLM specific params + self.llm = LLM( + model=self.real_model_path, + tensor_parallel_size=self.vllm_tensor_parallel_size, + max_model_len=self.vllm_max_model_len, + gpu_memory_utilization=self.vllm_gpu_memory_utilization, + limit_mm_per_prompt={"image": self.vllm_limit_mm_per_prompt}, # Specific config for image limits + trust_remote_code=self.trust_remote_code + ) + + # Load tokenizer for chat templating + self.tokenizer = AutoTokenizer.from_pretrained( + self.real_model_path, + cache_dir=self.hf_cache_dir, + trust_remote_code=self.trust_remote_code, + enable_thinking=self.enable_thinking + ) + self.logger.success(f"VLM Model loaded from {self.real_model_path} by vLLM backend") + + def _load_image(self, image_path: str) -> Image.Image: + """ + Helper to load image from path using PIL. + Replaces API _encode_image_to_base64 logic with PIL loading for vLLM. + """ + try: + return Image.open(image_path).convert("RGB") + except Exception as e: + self.logger.error(f"Failed to load image at {image_path}: {e}") + raise e + + def _run_batch_inference(self, vllm_inputs, batch_size): + all_outputs = [] + # 按 batch_size 分批处理 + for i in range(0, len(vllm_inputs), batch_size): + batch_inputs = vllm_inputs[i:i+batch_size] + outputs = self.llm.generate(batch_inputs, sampling_params=self.sampling_params) + all_outputs.extend([output.outputs[0].text for output in outputs]) + return all_outputs + + def generate_from_input_one_image( + self, + image_paths: List[str], + text_prompts: List[str], + system_prompt: str = "Describe the image in detail.", + model: str = None, # Unused, kept for interface compatibility + timeout: int = 1800 # Unused, kept for interface compatibility + ) -> List[str]: + """ + Batch process single-image chat requests concurrently using vLLM. + Matches the signature of APIVLMServing_openai.generate_from_input_one_image. + """ + if not self.backend_initialized: + self.start_serving() + + if len(image_paths) != len(text_prompts): + raise ValueError("`image_paths` and `text_prompts` must have the same length") + + inputs = [] + + # Prepare inputs for vLLM + for img_path, user_text in zip(image_paths, text_prompts): + image = self._load_image(img_path) + + # Construct messages using standard chat format + # Note: Specific VLMs might require specific placeholder tokens (e.g., ) + # but AutoTokenizer.apply_chat_template usually handles this if configured correctly. + messages = [ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": [ + {"type": "image"}, + {"type": "text", "text": user_text} + ]} + ] + + # Apply template to get the prompt string + prompt = self.tokenizer.apply_chat_template( + messages, + tokenize=False, + add_generation_prompt=True + ) + + # Construct vLLM input dictionary + inputs.append({ + "prompt": prompt, + "multi_modal_data": { + "image": image + } + }) + + # Run Inference + outputs = self.llm.generate(inputs, sampling_params=self.sampling_params) + + # Extract Text + responses = [] + for output in outputs: + responses.append(output.outputs[0].text) + + return responses + + def generate_from_input_multi_images( + self, + list_of_image_paths: List[List[str]], + list_of_image_labels: List[List[str]], + user_prompts: List[str], + system_prompt: str = "Analyze the provided images.", + model: str = None, # 保持接口一致性,实际不使用 + timeout: int = 1800 # 保持接口一致性,实际不使用 + ) -> List[str]: + """ + Batch process multi-image chat requests using vLLM. + + :param list_of_image_paths: Outer list is the batch, inner list contains paths for one request. + :param list_of_image_labels: Corresponding labels/prompts for each image in the inner list. + """ + if not self.backend_initialized: + self.start_serving() + + if len(list_of_image_paths) != len(list_of_image_labels): + raise ValueError("`list_of_image_paths` and `list_of_image_labels` must have the same length") + + vllm_inputs = [] + + # 遍历每一个请求 (Batch Loop) + for paths, labels, user_prompt in zip(list_of_image_paths, list_of_image_labels, user_prompts): + if len(paths) != len(labels): + raise ValueError("Inner lists of paths and labels must have the same length") + + # 1. 加载该请求下的所有图片 + # vLLM 支持传入 PIL Image 列表 + current_images = [self._load_image(p) for p in paths] + + # 检查是否超过了初始化时设定的最大图片数 + if len(current_images) > self.vllm_limit_mm_per_prompt: + self.logger.warning( + f"Request contains {len(current_images)} images, but limit is {self.vllm_limit_mm_per_prompt}. " + "This might cause vLLM errors. Increase `vllm_limit_mm_per_prompt` in init." + ) + + # 2. 构建 User Content + # 我们需要交替插入文本(Label)和图片占位符 + user_content = [{"type": "text", "text": user_prompt}] + for label, _ in zip(labels, paths): + # 插入标签文本(如果有) + if label: + user_content.append({"type": "text", "text": f"{label}\n"}) + # 插入图片占位符 + user_content.append({"type": "image"}) + + # 3. 构建完整的 Messages + messages = [ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": user_content} + ] + + # 4. 应用 Chat Template + # 大多数现代 VLM 的 template 会自动处理多个 {"type": "image"} + # 并将其转换为类似 ... 的 token 序列 + prompt = self.tokenizer.apply_chat_template( + messages, + tokenize=False, + add_generation_prompt=True + ) + + # 5. 构建 vLLM 输入 payload + # 当有多张图片时,multi_modal_data["image"] 应该是一个列表 + vllm_inputs.append({ + "prompt": prompt, + "multi_modal_data": { + "image": current_images + } + }) + + # 6. 执行批量推理 + all_outputs = self._run_batch_inference(vllm_inputs, batch_size=self.batch_size) + return all_outputs + + def cleanup(self): + """ + Clean up vLLM backend resources. + Identical logic to LocalModelLLMServing_vllm.cleanup. + """ + free_mem = torch.cuda.mem_get_info()[0] + total_mem = torch.cuda.get_device_properties(0).total_memory + self.logger.info(f"Free memory before cleanup: {free_mem / (1024 ** 2):.2f} MB / {total_mem / (1024 ** 2):.2f} MB") + + self.logger.info("Cleaning up vLLM VLM backend resources...") + self.backend_initialized = False + + # vLLM Distributed Cleanup + from vllm.distributed.parallel_state import ( + destroy_model_parallel, + destroy_distributed_environment, + ) + + if hasattr(self, 'llm'): + del self.llm.llm_engine + del self.llm + + destroy_model_parallel() + destroy_distributed_environment() + + with contextlib.suppress(AssertionError): + torch.distributed.destroy_process_group() + + import gc + import ray + + gc.collect() + torch.cuda.empty_cache() + ray.shutdown() + + free_mem = torch.cuda.mem_get_info()[0] + self.logger.info(f"Free memory after cleanup: {free_mem / (1024 ** 2):.2f} MB") + + def generate_from_input(self, user_inputs: List[str], system_prompt: str = "Describe the image in detail.", json_schema: dict = None): + """ + 保持接口一致性,实际不使用 + """ + + return self.generate_from_input_one_image( + image_paths=user_inputs, + text_prompts=[""] * len(user_inputs), + system_prompt=system_prompt + ) \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/localhost_llm_api_serving.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/localhost_llm_api_serving.py new file mode 100644 index 0000000000000000000000000000000000000000..eb82d301a6ddd7a06430ff2ebfa255c11142785b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/localhost_llm_api_serving.py @@ -0,0 +1,242 @@ +import subprocess +import signal +import os +import re +import time +import requests +from threading import Thread +from tqdm import tqdm +from dataflow import get_logger +from dataflow.core import LLMServingABC +from concurrent.futures import ThreadPoolExecutor, as_completed + + +class LocalHostLLMAPIServing_vllm(LLMServingABC): + """ + A class to serve vLLM via a subprocess (e.g., localhost API server) + """ + def __init__(self, + hf_model_name_or_path: str, + hf_cache_dir: str = None, + max_workers: int = 16, + vllm_server_port: int = 12345, + vllm_server_host: str = "127.0.0.1", + vllm_tensor_parallel_size: int = 1, + vllm_temperature: float = 0.7, + vllm_top_p: float = 0.9, + vllm_max_tokens: int = 1024, + vllm_top_k: int = 40, + vllm_max_model_len: int = None, + vllm_gpu_memory_utilization: float = 0.9, + vllm_server_start_timeout: int = 120, + ): + self.logger = get_logger() + self.hf_model_name_or_path = hf_model_name_or_path + self.port = vllm_server_port + self.host = vllm_server_host + self.tensor_parallel_size = vllm_tensor_parallel_size + self.temperature = vllm_temperature + self.top_p = vllm_top_p + self.max_tokens = vllm_max_tokens + self.top_k = vllm_top_k + self.max_model_len = vllm_max_model_len + self.gpu_memory_utilization = vllm_gpu_memory_utilization + self.hf_cache_dir = hf_cache_dir + self.server_start_timeout = vllm_server_start_timeout + self.max_workers = max_workers + self.process = None + self.backend_initialized = False + + def _stream_subprocess_logs(self, pipe): + """ + 持续读取子进程输出,只保留 INFO/ERROR/Traceback + """ + traceback_mode = False + is_keyboard_interrupted = False + traceback_info_list = [] + for line in iter(pipe.readline, ''): + line = line.rstrip("\n") + if not line: + continue + + # 判断traceback + if line.startswith("Traceback"): + traceback_mode = True + traceback_info_list.append(line) + if "KeyboardInterrupt: MQLLMEngine terminated" in line: + is_keyboard_interrupted = True + continue + + # 如果处于traceback模式,输出所有行直到空行结束 + if traceback_mode: + traceback_info_list.append(line) + if "MQLLMEngine terminated" in line: + is_keyboard_interrupted = True + if line == "": + traceback_mode = False + continue + + # 仅保留 INFO 和 ERROR + if re.match(r"^(INFO|ERROR):", line): + if "INFO:" in line: + if "POST" in line: + self.logger.debug(line) + else: + self.logger.info(line) + else: + self.logger.error(line) + + if is_keyboard_interrupted: + self.logger.success("MQLLMEngine terminated") + else: + for log in traceback_info_list: + print(log) + self.is_error = not is_keyboard_interrupted + + def start_serving(self): + if self.backend_initialized: + self.logger.info("vLLM server already running.") + return + + command = [ + "python", "-m", "vllm.entrypoints.openai.api_server", + "--model", self.hf_model_name_or_path, + "--tensor-parallel-size", str(self.tensor_parallel_size), + "--port", str(self.port), + "--gpu-memory-utilization", str(self.gpu_memory_utilization), + ] + + if self.max_model_len: + command += ["--max-model-len", str(self.max_model_len)] + if self.hf_cache_dir: + command += ["--download-dir", self.hf_cache_dir] + + self.logger.info(f"Starting vLLM server with command: {' '.join(command)}") + self.process = subprocess.Popen( + command, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + preexec_fn=os.setsid + ) + + # 后台线程处理日志 + Thread(target=self._stream_subprocess_logs, args=(self.process.stdout,), daemon=True).start() + Thread(target=self._stream_subprocess_logs, args=(self.process.stderr,), daemon=True).start() + + for i in range(self.server_start_timeout): # 增加等待时间 + if hasattr(self, "is_error") and self.is_error: + break + try: + response = requests.get(f"http://{self.host}:{self.port}/v1/models", timeout=1.0) + status = response.status_code + self.logger.debug(f"[{i+1}/{self.server_start_timeout}] Status: {status}") + if status == 200: + self.backend_initialized = True + self.logger.success("vLLM server started successfully!") + return + except Exception as e: + self.logger.debug(f"[{i+1}/90] Connection failed: {repr(e)}") + time.sleep(1) + + self.cleanup() + if self.is_error: + raise RuntimeError("Failed to start vLLM server. Please check the logs for more information.") + else: + raise RuntimeError("Failed to start vLLM server within timeout. You can try increase server_start_timeout argument.") + + def format_response(self, response: dict) -> str: + # check if content is formatted like ......... + content = response['choices'][0]['message']['content'] + if re.search(r'.*.*.*', content): + return content + + try: + reasoning_content = response['choices'][0]["message"]["reasoning_content"] + except Exception: + reasoning_content = "" + + if reasoning_content != "": + return f"{reasoning_content}\n{content}" + else: + return content + + def _api_chat_with_id(self, id, payload, model): + try: + payload = { + "model": self.hf_model_name_or_path, + "messages": payload, + "temperature": self.temperature, + "top_p": self.top_p, + "top_k": self.top_k, + "max_tokens": self.max_tokens + } + + response = requests.post(f"http://{self.host}:{self.port}/v1/chat/completions", json=payload) + if response.status_code == 200: + # logging.info(f"API request successful") + response_data = response.json() + # logging.info(f"API response: {response_data['choices'][0]['message']['content']}") + return id,self.format_response(response_data) + else: + self.logger.error(f"API request failed with status {response.status_code}: {response.text}") + return id, None + except Exception as e: + self.logger.error(f"API request error: {e}") + return id, None + + def generate_from_input(self, + user_inputs: list[str], system_prompt: str = "You are a helpful assistant" + ) -> list[str]: + + if not self.backend_initialized: + self.start_serving() + responses = [None] * len(user_inputs) + + # 使用 ThreadPoolExecutor 并行处理多个问题 + # logging.info(f"Generating {len(questions)} responses") + with ThreadPoolExecutor(max_workers=self.max_workers) as executor: + futures = [ + executor.submit( + self._api_chat_with_id, + payload = [ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": question} + ], + model = self.hf_model_name_or_path, + id = idx + ) for idx, question in enumerate(user_inputs) + ] + for future in tqdm(as_completed(futures), total=len(futures), desc="Generating......"): + response = future.result() # (id, response) + responses[response[0]] = response[1] + return responses + + # def generate_from_input(self, user_inputs: list[str], system_prompt: str = "You are a helpful assistant") -> list[str]: + # if not self.backend_initialized: + # self.start_serving() + + # messages = [{"role": "system", "content": system_prompt}] + \ + # [{"role": "user", "content": q} for q in user_inputs] + + # payload = { + # "model": self.hf_model_name_or_path, + # "messages": messages, + # "temperature": 0.7, + # "top_p": 0.9, + # "max_tokens": 1024 + # } + + # response = requests.post(f"http://{self.host}:{self.port}/v1/chat/completions", json=payload) + # response.raise_for_status() + # data = response.json() + # return [choice["message"]["content"] for choice in data["choices"]] + + def cleanup(self): + if self.process: + self.logger.info("Shutting down vLLM subprocess...") + os.killpg(os.getpgid(self.process.pid), signal.SIGTERM) + self.process.wait() + time.sleep(10) + self.logger.success("vLLM subprocess terminated.") + self.backend_initialized = False \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/localmodel_lalm_serving.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/localmodel_lalm_serving.py new file mode 100644 index 0000000000000000000000000000000000000000..8fcf12d1dcff7bcc6451f7acdd39798c67f94eb5 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/serving/localmodel_lalm_serving.py @@ -0,0 +1,256 @@ +import os +import torch +from dataflow import get_logger +from huggingface_hub import snapshot_download +from dataflow.core import LLMServingABC +from transformers import AutoProcessor +from typing import Optional, Union, List, Dict, Any, Tuple + +import librosa +import requests +import numpy as np +from io import BytesIO + +# 不重采样 +DEFAULT_SR = None + +def _read_audio_remote(path: str, sr: Optional[int] = DEFAULT_SR) -> Tuple[np.ndarray, int]: + url = path + resp = requests.get(url, stream=True) + + audio_bytes = BytesIO(resp.content) + y, sr = librosa.load(audio_bytes, sr=sr) + return y, sr + +def _read_audio_local(path: str, sr: Optional[int] = DEFAULT_SR) -> Tuple[np.ndarray, int]: + return librosa.load(path, sr=sr, mono=True) + +def _read_audio_bytes(data: bytes, sr: Optional[int] = DEFAULT_SR) -> Tuple[np.ndarray, int]: + return librosa.load(BytesIO(data), sr=sr, mono=True) + +def _read_audio_base64(b64: str, sr: Optional[int] = DEFAULT_SR) -> Tuple[np.ndarray, int]: + header, b64data = b64.split(",", 1) + data = base64.b64decode(b64data) + return _read_audio_bytes(data, sr=sr) + +def process_audio_info( + conversations: List[dict] | List[List[dict]], # 这个conversation对应的是vllm中的messages列表(对应的是conversation_to_message函数的message) + sampling_rate: Optional[int] +) -> Tuple[ + Optional[List[np.ndarray]], + Optional[List[int]], + Optional[List[str]] +]: + """ + 类似于 vision 的 process_vision_info,从 message 列表中提取音频输入。 + 支持三种格式输入: + - 本地或 http(s) URL 路径(通过 librosa 接口处理) + - base64 编码 (data:audio/…;base64,…) + - 直接传入 bytes 对象 + 返回二元组: + - audio_arrays: 解码后的 waveform (List[np.ndarray]) + - sample_rates: 采样率列表 (List[int]) + """ + if isinstance(conversations, list) and conversations and isinstance(conversations[0], dict): + # 单条 conversaion + conversations = [conversations] # conversations被统一为List[List[dict]] + + audio_arrays = [] + sampling_rates = [] + + for conv in conversations: + for msg in conv: + if not isinstance(msg.get("content"), list): + continue + for ele in msg["content"]: + if ele.get("type") != "audio": + continue + aud = ele.get("audio") + if isinstance(aud, str): + if aud.startswith("data:audio") and "base64," in aud: + arr, sr = _read_audio_base64(aud, sr=sampling_rate) + audio_arrays.append(arr) + sampling_rates.append(sr) + elif aud.startswith("http://") or aud.startswith("https://"): + # 使用 librosa 支持远程路径 + arr, sr = _read_audio_remote(aud, sr=sampling_rate) + audio_arrays.append(arr) + sampling_rates.append(sr) + else: + # 本地路径 + arr, sr = _read_audio_local(aud, sr=sampling_rate) + audio_arrays.append(arr) + sampling_rates.append(sr) + elif isinstance(aud, (bytes, bytearray)): + arr, sr = _read_audio_bytes(bytes(aud), sr=sampling_rate) + audio_arrays.append(arr) + sampling_rates.append(sr) + else: + raise ValueError(f"Unsupported audio type: {type(aud)}") + + if not audio_arrays: + return None, None + return audio_arrays, sampling_rates + +class LocalModelLALMServing_vllm(LLMServingABC): + ''' + A class for generating text using vllm, with model from huggingface or local directory + ''' + def __init__(self, + hf_model_name_or_path: str = None, + hf_cache_dir: str = None, + hf_local_dir: str = None, + vllm_tensor_parallel_size: int = 1, + vllm_temperature: float = 0.7, + vllm_top_p: float = 0.9, + vllm_max_tokens: int = 1024, + vllm_top_k: int = 40, + vllm_repetition_penalty: float = 1.0, + vllm_seed: int = 42, + vllm_max_model_len: int = None, + vllm_gpu_memory_utilization: float=0.9, + ): + self.logger = get_logger() + self.load_model( + hf_model_name_or_path=hf_model_name_or_path, + hf_cache_dir=hf_cache_dir, + hf_local_dir=hf_local_dir, + vllm_tensor_parallel_size=vllm_tensor_parallel_size, + vllm_temperature=vllm_temperature, + vllm_top_p=vllm_top_p, + vllm_max_tokens=vllm_max_tokens, + vllm_top_k=vllm_top_k, + vllm_repetition_penalty=vllm_repetition_penalty, + vllm_seed=vllm_seed, + vllm_max_model_len=vllm_max_model_len, + vllm_gpu_memory_utilization=vllm_gpu_memory_utilization, + ) + self.backend_initialized = False + + def load_model(self, + hf_model_name_or_path: str = None, + hf_cache_dir: str = None, + hf_local_dir: str = None, + vllm_tensor_parallel_size: int = 1, + vllm_temperature: float = 0.7, + vllm_top_p: float = 0.9, + vllm_max_tokens: int = 1024, + vllm_top_k: int = 40, + vllm_repetition_penalty: float = 1.0, + vllm_seed: int = 42, + vllm_max_model_len: int = None, + vllm_gpu_memory_utilization: float=0.9, + ): + + self.hf_model_name_or_path = hf_model_name_or_path + self.hf_cache_dir = hf_cache_dir + self.hf_local_dir = hf_local_dir + self.vllm_tensor_parallel_size = vllm_tensor_parallel_size + self.vllm_temperature = vllm_temperature + self.vllm_top_p = vllm_top_p + self.vllm_max_tokens = vllm_max_tokens + self.vllm_top_k = vllm_top_k + self.vllm_repetition_penalty = vllm_repetition_penalty + self.vllm_seed = vllm_seed + self.vllm_max_model_len = vllm_max_model_len + self.vllm_gpu_memory_utilization = vllm_gpu_memory_utilization + + def start_serving(self): + self.backend_initialized = True + self.logger = get_logger() + if self.hf_model_name_or_path is None: + raise ValueError("hf_model_name_or_path is required") + elif os.path.exists(self.hf_model_name_or_path): + self.logger.info(f"Using local model path: {self.hf_model_name_or_path}") + self.real_model_path = self.hf_model_name_or_path + else: + self.logger.info(f"Downloading model from HuggingFace: {self.hf_model_name_or_path}") + self.real_model_path = snapshot_download( + repo_id=self.hf_model_name_or_path, + cache_dir=self.hf_cache_dir, + local_dir=self.hf_local_dir, + ) + + # Import vLLM and set up the environment for multiprocessing + # vLLM requires the multiprocessing method to be set to spawn + try: + from vllm import LLM,SamplingParams + except Exception: + raise ImportError("please install vllm first like 'pip install open-dataflow[vllm]'") + # Set the environment variable for vllm to use spawn method for multiprocessing + # See https://docs.vllm.ai/en/v0.7.1/design/multiprocessing.html + os.environ['VLLM_WORKER_MULTIPROC_METHOD'] = "spawn" + + self.sampling_params = SamplingParams( + temperature=self.vllm_temperature, + top_p=self.vllm_top_p, + max_tokens=self.vllm_max_tokens, + top_k=self.vllm_top_k, + repetition_penalty=self.vllm_repetition_penalty, + seed=self.vllm_seed + ) + + self.llm = LLM( + model=self.real_model_path, + tensor_parallel_size=self.vllm_tensor_parallel_size, + max_model_len=self.vllm_max_model_len, + gpu_memory_utilization=self.vllm_gpu_memory_utilization, + ) + self.processor = AutoProcessor.from_pretrained(self.real_model_path, cache_dir=self.hf_cache_dir) + self.logger.success(f"Model loaded from {self.real_model_path} by vLLM backend") + + def generate_from_input(self, + user_inputs: list[str], + system_prompt: str = "You are a helpful assistant", + ) -> list[str]: + if not self.backend_initialized: + self.start_serving() + + messages = [] + for path_or_url in user_inputs: + message = [ + {"role": "system", "content": system_prompt}, + { + "role": "user", + "content": [ + {"type": "text", "text": "请帮我把这段音频的文字翻译成中文"}, + {"type": "audio", "audio": path_or_url} + ] + } + ] + messages.append(message) + + user_inputs = [self.processor.apply_chat_template( + msg, + tokenize=False, + add_generation_prompt=True, + add_audio_id = True + ) for msg in messages] + + audio_arrays, sampling_rates = process_audio_info(conversations=messages, sampling_rate=16000) + audio_inputs = [(audio_array, sampling_rate) for audio_array, sampling_rate in zip(audio_arrays, sampling_rates)] + + prompts = self.processor.apply_chat_template( + messages, + tokenize=False, + add_generation_prompt=True, + enable_thinking=True, # Set to False to strictly disable thinking + ) + + mm_entries = [ + { + "prompt": prompt, + "multi_modal_data": {"audio": (audio_array, sampling_rate)} + } + for prompt, audio_array, sampling_rate in zip(prompts, audio_arrays, sampling_rates) + ] + + responses = self.llm.generate(mm_entries, self.sampling_params) + return [output.outputs[0].text for output in responses] + + def cleanup(self): + del self.llm + import gc; + gc.collect() + torch.cuda.empty_cache() + \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36e01492f7b6fc500d1d5d2bdc6573ee6c48bb03 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/agentic_rag_multihop_core_pipeline.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/agentic_rag_multihop_core_pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..487a7a565054d42e6f80025554feb76c761c1454 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/agentic_rag_multihop_core_pipeline.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/agentic_rag_pipeline.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/agentic_rag_pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6294e88bd4087f62dd0d0cfe3694dab885618cda Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/agentic_rag_pipeline.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/chemistry_smiles.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/chemistry_smiles.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cdc39483031b11723b610d76d80fbf891e5a4368 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/chemistry_smiles.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/code_code_to_sft_data_pipeline.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/code_code_to_sft_data_pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b221ae2b0b0e600d626b4a392aeac090a6dbdac7 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/code_code_to_sft_data_pipeline.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/code_gen_dataset_pipeline.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/code_gen_dataset_pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89a500abd24df3be1c1d9b06ba0b8799b07eccaf Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/code_gen_dataset_pipeline.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/core_text_bencheval_semantic_pipeline.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/core_text_bencheval_semantic_pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ce648e0421e39a06788bf0555335fba7f4b61a4 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/core_text_bencheval_semantic_pipeline.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/core_text_bencheval_semantic_pipeline_question.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/core_text_bencheval_semantic_pipeline_question.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0abd08de2e74ffba544535eea15bacec65ae9ba4 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/core_text_bencheval_semantic_pipeline_question.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/core_text_bencheval_semantic_pipeline_question_single_step.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/core_text_bencheval_semantic_pipeline_question_single_step.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..588becd2b67926a322fbf32abcfc5da4ec677279 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/core_text_bencheval_semantic_pipeline_question_single_step.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/func_call_synthesis.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/func_call_synthesis.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22288560cba3922449b441e7d0c306de2b165169 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/func_call_synthesis.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/kbcleaning_pipeline.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/kbcleaning_pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a697ec8ad3a031566b6a72765e8d82ffe85391a9 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/kbcleaning_pipeline.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/pdf_vqa_extract_pipeline.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/pdf_vqa_extract_pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fb3718fde995749e7628e2996400e952f67ec0e Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/pdf_vqa_extract_pipeline.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/reasoning_diy_pipeline.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/reasoning_diy_pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8bcc13dcdc712e4b535c84e22f413be136af862b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/reasoning_diy_pipeline.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/reasoning_general_pipeline.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/reasoning_general_pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c04601153c0946de8aeb357fc11ef8f44830a65f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/reasoning_general_pipeline.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/reasoning_math_pipeline.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/reasoning_math_pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c6bf45c2843416a7a64fdd4fd527760e7018a1e Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/reasoning_math_pipeline.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/reasoning_math_pipeline_mathfusion.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/reasoning_math_pipeline_mathfusion.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d867d54f6e7357dceffa789b2247ded937f2462e Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/reasoning_math_pipeline_mathfusion.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/reasoning_pretrain_pipeline.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/reasoning_pretrain_pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9e307f6bc0374daf85895772f212712e03cd7f4 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/reasoning_pretrain_pipeline.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/text2qa_pipeline.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/text2qa_pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fca5b82e0fdea30943dc68b47c1ffd9c6b4ccd75 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/text2qa_pipeline.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/text2sql_pipeline_gen.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/text2sql_pipeline_gen.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8eec75d1e5cc01465bac0094a2db9f02f7694c65 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/text2sql_pipeline_gen.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/text2sql_pipeline_refine.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/text2sql_pipeline_refine.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b759c7f9ca1a97c783ef241da2e067b009c5f51 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/text2sql_pipeline_refine.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/text2vecsql_pipeline_gen.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/text2vecsql_pipeline_gen.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..797506b831b287bc71da226478bd866ca1c336b7 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/text2vecsql_pipeline_gen.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/text_conversation_synthesis_pipeline.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/text_conversation_synthesis_pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b71305069890f27b3d76c68d0d8e2905b71d0acb Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/text_conversation_synthesis_pipeline.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/text_sft_synthesis_pipeline.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/text_sft_synthesis_pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e19a502931e049e30a0097cedcd7e8ce1b091dc Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/__pycache__/text_sft_synthesis_pipeline.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/agentic_rag_multihop_core_pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/agentic_rag_multihop_core_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..4ad6a3fd91b7da87d797abbdada911614b92f5b7 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/agentic_rag_multihop_core_pipeline.py @@ -0,0 +1,498 @@ +import asyncio +import json +import re +import string +import pandas as pd +from itertools import combinations +from typing import Any, List, Dict + +# --- Dataflow 核心组件 --- +from dataflow.utils.storage import FileStorage +from dataflow.serving import APILLMServing_request +from dataflow.serving import FlashRAGServing + +# --- 算子导入 --- +from dataflow.operators.core_text import ( + PandasOperator, + FormatStrPromptedGenerator, + RetrievalGenerator, + GeneralFilter +) + +# --- Prompt 模板导入 --- +from dataflow.prompts.core_text import FormatStrPrompt +from dataflow.prompts.agenticrag import ( + AtomicQAGeneratorPrompt, + MergeAtomicQAPrompt, + RefineAnswerPrompt, + MoreOptionalAnswersPrompt, + # Verifier Prompts + InferenceCheckPrompt, + ComparisonCheckPrompt, + ReasoningPrompt, + ComparisonReasoningPrompt, + SingleHopPrompt, + MultihopInferencePrompt, + MultihopComparisonPrompt, + EssEqPrompt, +) + +# ========================================== +# 1. 通用辅助函数 +# ========================================== + +def _clean_json_block(item: Any) -> str: + if not isinstance(item, str): return "{}" + return item.strip().removeprefix("```json").removeprefix("```").removesuffix("```").strip() + +def safe_parse_json(text: Any) -> Any: + try: + return json.loads(_clean_json_block(text)) + except Exception: + return {} + +def normalize_answer(s: str) -> str: + if not isinstance(s, str): return "" + if s.strip() in ["A", "B", "C", "D", "E"]: + return s.strip().upper() + def remove_articles(text): + return re.sub(r"\b(a|an|the|do|does|is|are|was|were|of|under|in|at|on|with|by|for|from|about)\b", " ", text) + def white_space_fix(text): + return " ".join(text.split()) + def remove_punc(text): + exclude = set(string.punctuation) + return "".join(ch for ch in text if ch not in exclude) + return white_space_fix(remove_articles(remove_punc(s.lower()))) + +# ========================================== +# 2. 生成阶段辅助函数 +# ========================================== + +def prepare_retrieval_query(df: pd.DataFrame, hop_key: str) -> pd.DataFrame: + df['retrieval_query'] = df[hop_key].apply(lambda x: x.get('answer', '') if isinstance(x, dict) else '') + return df + +def format_history_string(row: pd.Series, current_hop: int) -> str: + history = [] + for h in range(1, current_hop + 1): + k = f"hop_{h}" + if k in row and isinstance(row[k], dict): + data = row[k] + q = data.get('final_question', data.get('question', '')) + a = data.get('final_answer', data.get('answer', '')) + d = data.get('doc', '') + history.append(f"Hop_{h}:\nQuestion: {q}\nAnswer: {a}\nDocument: {d}") + return "\n".join(history) + +def filter_inference_logic(df: pd.DataFrame) -> pd.Series: + def check_row(row): + merge_data = row.get('merge_data') + if not isinstance(merge_data, dict): return False + m_type = merge_data.get('type', '') + final_ans = merge_data.get('final_answer', '') + mid_ans = row.get('mid_answer', '') + if m_type == "inference": + return normalize_answer(str(final_ans)) == normalize_answer(str(mid_ans)) + return True + return df.apply(check_row, axis=1) + +def pack_next_hop(row: pd.Series) -> dict: + return { + "question": row.get("mid_question"), + "answer": row.get("mid_answer"), + "doc": row.get("doc_content"), + "final_question": row.get("merge_data", {}).get("final_question"), + "final_answer": row.get("refine_data", {}).get("refined_answer"), + "optional_answers": row.get("opt_data"), + "qa_type": row.get("merge_data", {}).get("type"), + } + +# ========================================== +# 3. 验证阶段辅助函数 +# ========================================== + +def build_check_prompt_str(row: pd.Series, current_hop: int) -> str: + hop_key = f"hop_{current_hop + 1}" + prev_hop_key = f"hop_{current_hop}" + curr = row[hop_key] + prev = row[prev_hop_key] + qa_type = curr.get("qa_type", "inference") + + kwargs = { + "Question1": prev.get("final_question"), + "Answer1": prev.get("final_answer"), + "Document1": prev.get("doc"), + "Question2": curr.get("question"), + "Answer2": curr.get("answer"), + "Document2": curr.get("doc"), + "Final_question": curr.get("final_question"), + "Final_answer": curr.get("final_answer"), + "qa_type": qa_type, + } + + if qa_type == 'inference': + return InferenceCheckPrompt().build_prompt(**kwargs) + else: + return ComparisonCheckPrompt().build_prompt(**kwargs) + +def build_reasoning_prompt_str(row: pd.Series, current_hop: int) -> str: + hop_key = f"hop_{current_hop + 1}" + curr = row[hop_key] + qa_type = curr.get("qa_type", "inference") + question = curr.get("final_question") + + if qa_type == 'inference': + return ReasoningPrompt().build_prompt(problem=question) + else: + return ComparisonReasoningPrompt().build_prompt(problem=question) + +def generate_doc_combinations(row: pd.Series, current_hop: int) -> List[str]: + all_docs = [] + for h in range(1, current_hop + 1): + k = f"hop_{h}" + if k in row and isinstance(row[k], dict): + all_docs.append(row[k].get("doc", "")) + + combos_str = [] + for combo in combinations(all_docs, max(1, len(all_docs)-1)): + if len(combo) == 1: + combos_str.append(combo[0]) + else: + combos_str.append("\n\n".join(combo)) + return combos_str + +def build_multihop_prompt_str(row: pd.Series, current_hop: int) -> str: + total_hops = current_hop + 1 + hop_key = f"hop_{total_hops}" + curr = row[hop_key] + qa_type = curr.get("qa_type", "inference") + + Data = [] + for h in range(1, total_hops): + info = row[f"hop_{h}"] + Data.append(f"Question{h}: {info['question']}\nAnswer{h}: {info['answer']}\nSupporting Document{h}: {info['doc']}") + + last_info = row[f"hop_{total_hops}"] + if qa_type == 'inference': + Data.append(f"Question{total_hops}: {last_info['question']}\nSupporting Document{total_hops}: {last_info['doc']}") + return MultihopInferencePrompt().build_prompt( + Data="\n".join(Data), + FinalQuestion=curr.get("final_question") + ) + else: + Data.append(f"Question{total_hops}: {last_info['question']}\nAnswer{total_hops}: {last_info['answer']}\nSupporting Document{total_hops}: {last_info['doc']}") + return MultihopComparisonPrompt().build_prompt( + Data="\n".join(Data), + FinalQuestion=curr.get("final_question") + ) + +# ========================================== +# 4. Pipeline 类 +# ========================================== + +class MultiHopRAGPipeline: + def __init__(self, input_hop: int = 1, topk: int = 5): + self.input_hop = input_hop + self.hop_key = f"hop_{input_hop}" + self.next_hop_key = f"hop_{input_hop + 1}" + self.topk = topk + + # 1. 初始化 + self.storage = FileStorage( + first_entry_file_name="../example_data/AgenticRAGPipeline/multihop_pipeline_data.jsonl", + cache_path=f"./agenticRAG_multihop_cache", + file_name_prefix=f"multihop_input_hop{input_hop}", + cache_type="jsonl", + ) + + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="o4-mini", + max_workers=50 + ) + + self.retriever_serving = FlashRAGServing( + retrieval_method="e5", # name of your retrieval_method. + retrieval_model_path="/path/to/retrieval/model", # name or path of the retrieval model. + index_path="/path/to/index", # path to the indexed file + corpus_path="/path/to/corpus", # path to corpus in '.jsonl' format that store the documents + faiss_gpu=False, # whether use gpu to hold index + gpu_id="", + max_workers=1, + topk=self.topk + ) + + # ======================================================= + # Generator Operators (生成阶段) + # ======================================================= + + self.op_prep_retrieval = PandasOperator(process_fn=[ + lambda df: prepare_retrieval_query(df, self.hop_key) + ]) + + self.op_retrieval = RetrievalGenerator( + llm_serving=self.retriever_serving, + ) + + self.op_explode_docs = PandasOperator(process_fn=[ + lambda df: df.explode('retrieved_docs').reset_index(drop=True), + lambda df: df.rename(columns={'retrieved_docs': 'doc_content'}), + lambda df: df.dropna(subset=['doc_content']), + lambda df: df.assign(gen_qa_num=1) + ]) + + # Step: Atomic QA + self.op_atomic_gen = FormatStrPromptedGenerator( + llm_serving=self.llm_serving, + prompt_template=FormatStrPrompt(f_str_template=AtomicQAGeneratorPrompt().prompt) + ) + + self.op_parse_atomic = PandasOperator(process_fn=[ + lambda df: df.assign(atomic_list=df['atomic_raw'].apply(safe_parse_json)), + lambda df: df.explode('atomic_list').reset_index(drop=True).dropna(subset=['atomic_list']), + lambda df: df.join(pd.json_normalize(df['atomic_list']).add_prefix('mid_')) + ]) + + # Step: Merge QA + self.op_prep_merge = PandasOperator(process_fn=[ + lambda df: df.assign(history_str=df.apply(lambda r: format_history_string(r, self.input_hop), axis=1)) + ]) + + # 使用字段映射: {Data} <- history_str, {New_question} <- mid_question ... + self.op_merge_gen = FormatStrPromptedGenerator( + llm_serving=self.llm_serving, + prompt_template=FormatStrPrompt(f_str_template=MergeAtomicQAPrompt().prompt) + ) + + self.op_parse_merge = PandasOperator(process_fn=[ + lambda df: df.assign(merge_data=df['merge_raw'].apply(safe_parse_json)) + ]) + + self.op_filter = GeneralFilter(filter_rules=[filter_inference_logic]) + + # Step: Refine + self.op_prep_refine = PandasOperator(process_fn=[ + lambda df: df.assign( + merge_final_q=df['merge_data'].apply(lambda x: x.get('final_question', '')), + merge_final_a=df['merge_data'].apply(lambda x: x.get('final_answer', '')) + ) + ]) + + self.op_refine_gen = FormatStrPromptedGenerator( + llm_serving=self.llm_serving, + prompt_template=FormatStrPrompt(f_str_template=RefineAnswerPrompt().prompt) + ) + + self.op_parse_refine = PandasOperator(process_fn=[ + lambda df: df.assign(refine_data=df['refine_raw'].apply(safe_parse_json)), + lambda df: df.assign(temp_refined_a=df.apply(lambda r: r['refine_data'].get('refined_answer', '') if isinstance(r['refine_data'], dict) else '', axis=1)) + ]) + + # Step: Optional Answers + self.op_optional_gen = FormatStrPromptedGenerator( + llm_serving=self.llm_serving, + prompt_template=FormatStrPrompt(f_str_template=MoreOptionalAnswersPrompt().prompt) + ) + + self.op_finalize = PandasOperator(process_fn=[ + lambda df: df.assign(opt_data=df['opt_raw'].apply(safe_parse_json)), + lambda df: df.assign(**{self.next_hop_key: df.apply(pack_next_hop, axis=1)}), + lambda df: df.assign(row_id=range(len(df))) + ]) + + # ======================================================= + # Verifier Operators (验证阶段) + # ======================================================= + + # --- Phase 1: Check (Dynamic) --- + self.op_verify_prep_check = PandasOperator(process_fn=[ + lambda df: df if df.empty else df.assign(check_prompt_str=df.apply(lambda r: build_check_prompt_str(r, self.input_hop), axis=1)) + ]) + + self.op_verify_gen_check = FormatStrPromptedGenerator( + llm_serving=self.llm_serving, + prompt_template=FormatStrPrompt(f_str_template="{input_str}"), + ) + + self.op_verify_filter_check = PandasOperator(process_fn=[ + lambda df: df if df.empty else df.assign(check_json=df['check_raw'].apply(safe_parse_json)), + lambda df: df[df['check_json'].apply(lambda x: str(x.get('valid', '')).lower() == 'true')] + ]) + + # --- Phase 2: Reasoning (Dynamic) --- + self.op_verify_prep_reasoning = PandasOperator(process_fn=[ + lambda df: df if df.empty else df.assign(reason_prompt_str=df.apply(lambda r: build_reasoning_prompt_str(r, self.input_hop), axis=1)), + lambda df: df if df.empty else df.assign(target_ans=df[self.next_hop_key].apply(lambda x: x.get('final_answer') if isinstance(x, dict) else '')) + ]) + + self.op_verify_gen_reasoning = FormatStrPromptedGenerator( + llm_serving=self.llm_serving, + prompt_template=FormatStrPrompt(f_str_template="{input_str}"), + ) + + # --- Phase 3: Judge Reasoning (Static) --- + self.op_verify_judge_reasoning = FormatStrPromptedGenerator( + llm_serving=self.llm_serving, + prompt_template=FormatStrPrompt(f_str_template=EssEqPrompt().prompt) + ) + + self.op_verify_filter_reasoning = PandasOperator(process_fn=[ + lambda df: df if df.empty else df.assign(judge_reason_json=df['judge_reason_raw'].apply(safe_parse_json)), + lambda df: df[df['judge_reason_json'].apply(lambda x: x.get('answer_score', 0) < 1)] + ]) + + # --- Phase 4: Shortcut Check (Static) --- + self.op_verify_prep_shortcut = PandasOperator(process_fn=[ + lambda df: df if df.empty else df.assign(doc_combos=df.apply(lambda r: generate_doc_combinations(r, self.input_hop), axis=1)), + lambda df: df.explode('doc_combos').reset_index(drop=True).dropna(subset=['doc_combos']) + ]) + + self.op_verify_gen_shortcut = FormatStrPromptedGenerator( + llm_serving=self.llm_serving, + prompt_template=FormatStrPrompt(f_str_template=SingleHopPrompt().prompt) + ) + + # --- Phase 5: Judge Shortcut (Static) --- + self.op_verify_judge_shortcut = FormatStrPromptedGenerator( + llm_serving=self.llm_serving, + prompt_template=FormatStrPrompt(f_str_template=EssEqPrompt().prompt) + ) + + self.op_verify_filter_shortcut = PandasOperator(process_fn=[ + lambda df: df if df.empty else df.assign(sc_judge_json=df['sc_judge_raw'].apply(safe_parse_json)), + lambda df: df if df.empty else df.assign(sc_score=df['sc_judge_json'].apply(lambda x: x.get('answer_score', 0))), + lambda df: df if df.empty else df.groupby('row_id').filter(lambda x: x['sc_score'].max() < 1), + lambda df: df.drop_duplicates(subset=['row_id']) + ]) + + # --- Phase 6: Final Verification (Dynamic) --- + self.op_verify_prep_final = PandasOperator(process_fn=[ + lambda df: df if df.empty else df.assign(final_prompt_str=df.apply(lambda r: build_multihop_prompt_str(r, self.input_hop), axis=1)) + ]) + + self.op_verify_gen_final = FormatStrPromptedGenerator( + llm_serving=self.llm_serving, + prompt_template=FormatStrPrompt(f_str_template="{input_str}"), + ) + + # --- Phase 7: Final Judge (Static) --- + self.op_verify_judge_final = FormatStrPromptedGenerator( + llm_serving=self.llm_serving, + prompt_template=FormatStrPrompt(f_str_template=EssEqPrompt().prompt) + ) + + self.op_verify_filter_final = PandasOperator(process_fn=[ + lambda df: df if df.empty else df.assign(final_judge_json=df['final_judge_raw'].apply(safe_parse_json)), + lambda df: df if df.empty else df[df['final_judge_json'].apply(lambda x: x.get('answer_score', 0) >= 1)], + lambda df: df[[col for col in df.columns if col.startswith("hop_")]] + ]) + + + async def forward(self): + # --- Generation Phase --- + self.op_prep_retrieval.run(self.storage.step()) + await self.op_retrieval.run(self.storage.step(), input_key="retrieval_query", output_key="retrieved_docs") + self.op_explode_docs.run(self.storage.step()) + + # Atomic (Standardized) + self.op_atomic_gen.run( + self.storage.step(), + output_key='atomic_raw', + gen_qa_num='gen_qa_num', + input_doc='doc_content' + ) + self.op_parse_atomic.run(self.storage.step()) + + # Merge (Standardized) + self.op_prep_merge.run(self.storage.step()) + self.op_merge_gen.run( + self.storage.step(), + output_key='merge_raw', + Data='history_str', + New_question='mid_question', + New_answer='mid_answer', + New_document='doc_content' + ) + self.op_parse_merge.run(self.storage.step()) + self.op_filter.run(self.storage.step()) + + # Refine (Standardized) + self.op_prep_refine.run(self.storage.step()) + self.op_refine_gen.run( + self.storage.step(), + output_key='refine_raw', + question='merge_final_q', + original_answer='merge_final_a' + ) + self.op_parse_refine.run(self.storage.step()) + + # Optional (Standardized) + self.op_optional_gen.run( + self.storage.step(), + output_key='opt_raw', + refined_answer='temp_refined_a' + ) + + self.op_finalize.run(self.storage.step()) + + # --- Verification Phase --- + print("--- Starting Verification ---") + + # 1. Check (Dynamic) + self.op_verify_prep_check.run(self.storage.step()) + self.op_verify_gen_check.run(self.storage.step(), output_key='check_raw', input_str='check_prompt_str') + self.op_verify_filter_check.run(self.storage.step()) + + # 2. Reasoning (Dynamic) + self.op_verify_prep_reasoning.run(self.storage.step()) + self.op_verify_gen_reasoning.run(self.storage.step(), output_key='reasoning_raw', input_str='reason_prompt_str') + + # 3. Judge Reasoning (Standardized) + self.op_verify_judge_reasoning.run( + self.storage.step(), + output_key='judge_reason_raw', + question='merge_final_q', + golden_answer='target_ans', + other_answer='reasoning_raw' + ) + self.op_verify_filter_reasoning.run(self.storage.step()) + + # 4. Shortcut Check (Standardized) + self.op_verify_prep_shortcut.run(self.storage.step()) + self.op_verify_gen_shortcut.run( + self.storage.step(), + output_key='sc_raw', + Document='doc_combos', + Question='merge_final_q' + ) + + # 5. Judge Shortcut (Standardized) + self.op_verify_judge_shortcut.run( + self.storage.step(), + output_key='sc_judge_raw', + question='merge_final_q', + golden_answer='target_ans', + other_answer='sc_raw' + ) + self.op_verify_filter_shortcut.run(self.storage.step()) + + # 6. Final Gen (Dynamic) + self.op_verify_prep_final.run(self.storage.step()) + self.op_verify_gen_final.run(self.storage.step(), output_key='final_raw', input_str='final_prompt_str') + + # 7. Final Judge (Standardized) + self.op_verify_judge_final.run( + self.storage.step(), + output_key='final_judge_raw', + question='merge_final_q', + golden_answer='target_ans', + other_answer='final_raw' + ) + self.op_verify_filter_final.run(self.storage.step()) + + await self.retriever_serving.cleanup() + print(f"Pipeline Hop {self.input_hop} -> {self.input_hop + 1} Completed and Verified.") + +if __name__ == "__main__": + pipeline = MultiHopRAGPipeline(input_hop=1, topk=5) + asyncio.run(pipeline.forward()) \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/agentic_rag_pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/agentic_rag_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..9a91dfa9fd097a176ce68b7747692325ea9a5cab --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/agentic_rag_pipeline.py @@ -0,0 +1,53 @@ +import pandas as pd +from dataflow.operators.agentic_rag import AgenticRAGQAF1SampleEvaluator + +from dataflow.operators.agentic_rag import ( + AgenticRAGAtomicTaskGenerator, + AgenticRAGDepthQAGenerator, + AgenticRAGWidthQAGenerator +) + +from dataflow.utils.storage import FileStorage +from dataflow.serving import APILLMServing_request +from dataflow.core import LLMServingABC + +class AgenticRAGEval_APIPipeline(): + + def __init__(self, llm_serving=None): + + self.storage = FileStorage( + first_entry_file_name="../example_data/AgenticRAGPipeline/eval_test_data.jsonl", + cache_path="./agenticRAG_eval_cache", + file_name_prefix="agentic_rag_eval", + cache_type="jsonl", + ) + + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o-mini", + max_workers=500 + ) + + self.task_step1 = AgenticRAGAtomicTaskGenerator( + llm_serving=self.llm_serving + ) + + self.task_step2 = AgenticRAGQAF1SampleEvaluator() + + def forward(self): + + self.task_step1.run( + storage = self.storage.step(), + input_key = "contents", + ) + + self.task_step2.run( + storage=self.storage.step(), + output_key="F1Score", + input_prediction_key="refined_answer", + input_ground_truth_key="golden_doc_answer" + ) + +if __name__ == "__main__": + model = AgenticRAGEval_APIPipeline() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/chemistry_smiles.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/chemistry_smiles.py new file mode 100644 index 0000000000000000000000000000000000000000..4fcabe1c9712d5e763741c7d3e0aa322832658b6 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/chemistry_smiles.py @@ -0,0 +1,110 @@ +from dataflow.operators.chemistry import ExtractSmilesFromTextGenerator +from dataflow.operators.chemistry import SmilesEquivalenceDatasetEvaluator + +from dataflow.serving import APILLMServing_request +from dataflow.utils.storage import FileStorage +from dataflow.prompts.chemistry import ExtractSmilesFromTextPrompt + +smiles_prompt = """Extract the monomer/small molecule information from the text and format it as a structured JSON object. + Follow these rules strictly: + 1. For each monomer/small molecule, extract: + - abbreviation: The commonly used abbreviated name + - full_name: The complete chemical name + - smiles: The SMILES notation of the molecular structure + + 2. General rules: + - Each monomer/small molecule should have a unique abbreviation + - If a monomer's information is incomplete, include only the available information + - Don't recognize polymer which have "poly" in the name as monomer + + Example output: + [ + { + "abbreviation": "4-ODA", + "full_name": "4,4′-Oxydianiline", + "smiles": "O(c1ccc(N)cc1)c2ccc(cc2)N" + }, + { + "abbreviation": "6FDA", + "full_name": "4,4'-(hexafluoroisopropylidene)diphthalic anhydride", + "smiles": "C1=CC2=C(C=C1C(C3=CC4=C(C=C3)C(=O)OC4=O)(C(F)(F)F)C(F)(F)F)C(=O)OC2=O" + } + ] + Please make sure to output pure json which can be saved into a json file, do not output like html. + """ + +response_format = { + "type": "json_schema", + "json_schema": { + "name": "chemical_structures_response", + "strict": True, + "schema": { + "type": "object", + "properties": { + "chemical_structures": { + "type": "array", + "items": { + "type": "object", + "properties": { + "abbreviation": { + "type": "string" + }, + "full_name": { + "type": "string" + }, + "smiles": { + "type": "string" + } + }, + "required": ["abbreviation", "full_name", "smiles"], + "additionalProperties": False + } + } + }, + "required": ["chemical_structures"], + "additionalProperties": False + } + } +} + + + +class ExtractSmiles(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/chemistry/matched_sample_10.json", + #first_entry_file_name="/Users/lianghao/Desktop/dataflow_code/test_0901/example_data/chemistry/matched_sample_10.json", + cache_path="./cache_all_17_24_gpt_5", + file_name_prefix="math_QA", + cache_type="json", + ) + self.model_cache_dir = './dataflow_cache' + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gemini-2.5-flash", + max_workers=200, + ) + self.prompt_smile_extractor = ExtractSmilesFromTextGenerator( + llm_serving = self.llm_serving, + prompt_template=ExtractSmilesFromTextPrompt(smiles_prompt), + ) + self.smile_eval = SmilesEquivalenceDatasetEvaluator() + + def forward(self): + # Initial filters + self.prompt_smile_extractor.run( + storage = self.storage.step(), + input_content_key = "text", + input_abbreviation_key = "abbreviations", + output_key = "synth_smiles" + ) + self.smile_eval.run( + storage = self.storage.step(), + ) + + +if __name__ == "__main__": + # This is the entry point for the pipeline + + model = ExtractSmiles() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/code_code_to_sft_data_pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/code_code_to_sft_data_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..c589614303a1bdbe8fb3e6dcd348c119ffd6a825 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/code_code_to_sft_data_pipeline.py @@ -0,0 +1,94 @@ +from dataflow.operators.code import ( + CodeCodeToInstructionGenerator, + CodeInstructionToCodeGenerator, + CodeQualitySampleEvaluator, + CodeQualityScoreFilter, + CodeSandboxSampleEvaluator, +) +from dataflow.utils.storage import FileStorage +from dataflow.serving import APILLMServing_request +from dataflow.core import LLMServingABC + +class CodeSFTSynthesis_APIPipeline(): + def __init__(self, llm_serving: LLMServingABC = None): + + self.storage = FileStorage( + first_entry_file_name="../example_data/CodePipeline/code_synthesis_input.jsonl", + cache_path="./cache", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + # use API server as LLM serving + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=100 + ) + + # Step 1: Code to Instruction synthesizer + self.instruction_synthesizer_step1 = CodeCodeToInstructionGenerator( + llm_serving=self.llm_serving + ) + + # Step 2: Instruction to Code generator + self.code_generator_step2 = CodeInstructionToCodeGenerator( + llm_serving=self.llm_serving + ) + + # Step 3: Quality evaluator for (instruction, code) pairs + self.pair_evaluator_step3 = CodeQualitySampleEvaluator( + llm_serving=self.llm_serving + ) + + # Step 4: Score-based filter + self.score_filter_step4 = CodeQualityScoreFilter( + llm_serving=self.llm_serving, + min_score=0.0, + max_score=10.0 + ) + + # Step 5: Sandbox evaluator + self.sandbox_evaluator_step5 = CodeSandboxSampleEvaluator( + language='python' + ) + + def forward(self): + # Step 1: Generate instructions from raw code + self.instruction_synthesizer_step1.run( + storage=self.storage.step(), + input_key="raw_code", + output_key="generated_instruction" + ) + + # Step 2: Generate code from instructions + self.code_generator_step2.run( + storage=self.storage.step(), + input_key="generated_instruction", + output_key="generated_code" + ) + + # Step 3: Evaluate the generated (instruction, code) pairs + self.pair_evaluator_step3.run( + storage=self.storage.step(), + input_instruction_key="generated_instruction", + input_code_key="generated_code" + ) + + # Step 4: Filter out low-quality samples + self.score_filter_step4.run( + storage=self.storage.step(), + input_instruction_key = "generated_instruction", + input_code_key = "generated_code", + output_key="quality_score_filter_label" + ) + + # Step 5: Evaluate high-quality code in sandbox + self.sandbox_evaluator_step5.run( + storage=self.storage.step(), + input_key="generated_code" + ) + +if __name__ == "__main__": + model = CodeSFTSynthesis_APIPipeline() + model.forward() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/code_gen_dataset_pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/code_gen_dataset_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..e4a03005b8e60a964db01ebfcd46422dbb00da68 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/code_gen_dataset_pipeline.py @@ -0,0 +1,98 @@ +from dataflow.operators.code import ( + CodeCodeToInstructionGenerator, + CodeInstructionToCodeGenerator, + CodeQualitySampleEvaluator, + CodeQualityScoreFilter, + CodeSandboxSampleEvaluator, + CodeEnhancementInstructionGenerator, + CodeInstructionGenerator +) +from dataflow.utils.storage import FileStorage +from dataflow.serving import APILLMServing_request +from dataflow.core import LLMServingABC + +class CodeGenDataset_APIPipeline(): + def __init__(self, llm_serving: LLMServingABC = None): + + self.storage = FileStorage( + first_entry_file_name="../example_data/CodePipeline/raw_code.jsonl", + cache_path="./cache", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + # use API server as LLM serving + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=10 + ) + + # Step 1: Instruction Enhancement + self.instruction_generater_step1 = CodeEnhancementInstructionGenerator( + llm_serving=self.llm_serving + ) + + # Step 2: Instruction to Code generator + self.code_generator_step2 = CodeInstructionToCodeGenerator( + llm_serving=self.llm_serving + ) + + # Step 3: Quality evaluator for (instruction, code) pairs + self.pair_evaluator_step3 = CodeQualitySampleEvaluator( + llm_serving=self.llm_serving + ) + + # Step 4: Score-based filter + self.score_filter_step4 = CodeQualityScoreFilter( + llm_serving=self.llm_serving, + min_score=7.0, + max_score=10.0 + ) + + # Step 4: Sandbox evaluator + self.sandbox_evaluator_step5 = CodeSandboxSampleEvaluator( + language='python' + ) + + def forward(self): + # Step 1: Generate instructions from raw data + self.instruction_generater_step1.run( + storage=self.storage.step(), + input_key="input", + output_key="generated_instruction", + ) + + #Step 2: Generate code from instructions + self.code_generator_step2.run( + storage=self.storage.step(), + input_key="generated_instruction", + output_key="generated_code" + ) + + # Step 3: Evaluate the generated (instruction, code) pairs + self.pair_evaluator_step3.run( + storage=self.storage.step(), + input_instruction_key="generated_instruction", + input_code_key="generated_code" + ) + + # Step 4: Filter out low-quality samples + self.score_filter_step4.run( + storage=self.storage.step(), + input_instruction_key = "generated_instruction", + input_code_key = "generated_code", + output_score_key = "quality_score", + output_feedback_key = "quality_feedback", + output_key="quality_score_filter_label" + ) + + # Step 5: Evaluate high-quality code in sandbox + self.sandbox_evaluator_step5.run( + storage=self.storage.step(), + input_key="generated_code" + ) + +if __name__ == "__main__": + model = CodeGenDataset_APIPipeline() + model.forward() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/core_text_bencheval_semantic_pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/core_text_bencheval_semantic_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..82066d5d5c3a4ef12eff5bd46a1cf4e6abe72f57 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/core_text_bencheval_semantic_pipeline.py @@ -0,0 +1,45 @@ +from dataflow.operators.core_text import BenchDatasetEvaluator +from dataflow.operators.reasoning import ReasoningAnswerGenerator +from dataflow.utils.storage import FileStorage +from dataflow.serving import APILLMServing_request, LocalModelLLMServing_vllm +from dataflow.core import LLMServingABC +from dataflow.prompts.reasoning.diy import ( + DiyAnswerGeneratorPrompt, +) + +DIY_PROMPT_ANSWER = """Please output the answer.""" + +class BenchEvalPipeline(): + def __init__(self, llm_serving_generator: LLMServingABC = None, llm_serving_judger: LLMServingABC = None): + + self.storage = FileStorage( + first_entry_file_name="../example_data/core_text_data/bench_eval_data_2.jsonl", + cache_path="./cache_local", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + # use API server as LLM serving + self.llm_serving_judger = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=30 + ) + + self.evaluator_step = BenchDatasetEvaluator( + eval_result_path="./cache_local/eval_result/eval_result.jsonl", + compare_method="semantic", # or match + llm_serving=self.llm_serving_judger, + prompt_template = None # you can diy your judger prompt in dataflow.prompts.reasoning.general.AnswerJudgePrompt + ) + + def forward(self): + self.evaluator_step.run( + storage = self.storage.step(), + input_test_answer_key="model_answer", + input_gt_answer_key="golden_label" + ) + +if __name__ == "__main__": + pl = BenchEvalPipeline() + pl.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/core_text_bencheval_semantic_pipeline_question.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/core_text_bencheval_semantic_pipeline_question.py new file mode 100644 index 0000000000000000000000000000000000000000..68d1c3362822be1a4558be12243edded6dc09522 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/core_text_bencheval_semantic_pipeline_question.py @@ -0,0 +1,62 @@ +from dataflow.operators.core_text import BenchDatasetEvaluatorQuestion +from dataflow.operators.reasoning import ReasoningAnswerGenerator +from dataflow.utils.storage import FileStorage +from dataflow.serving import APILLMServing_request, LocalModelLLMServing_vllm +from dataflow.core import LLMServingABC +from dataflow.prompts.reasoning.diy import ( + DiyAnswerGeneratorPrompt, +) + +DIY_PROMPT_ANSWER = """Please output the answer.""" + +class BenchEvalPipeline(): + def __init__(self, llm_serving_generator: LLMServingABC = None, llm_serving_judger: LLMServingABC = None): + + self.storage = FileStorage( + first_entry_file_name="../example_data/core_text_data/bench_eval_data.jsonl", + cache_path="./cache_local", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + self.llm_serving_generator = LocalModelLLMServing_vllm( + hf_model_name_or_path="Qwen/Qwen2.5-7B-Instruct", # set to your own model path + vllm_tensor_parallel_size=1, + vllm_max_tokens=2048, + ) + + # use API server as LLM serving + self.llm_serving_judger = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=30 + ) + + self.answer_generator_step1 = ReasoningAnswerGenerator( + llm_serving=self.llm_serving_generator, + prompt_template=DiyAnswerGeneratorPrompt(DIY_PROMPT_ANSWER) + ) + + self.evaluator_step2 = BenchDatasetEvaluatorQuestion( + eval_result_path="./cache_local/eval_result/eval_result.jsonl", + compare_method="semantic", # or match + llm_serving=self.llm_serving_judger, + prompt_template = None # you can diy your judger prompt in dataflow.prompts.reasoning.general.AnswerJudgePrompt + ) + + def forward(self): + self.answer_generator_step1.run( + storage = self.storage.step(), + input_key = "instruction", + output_key = "generated_cot" + ) + self.evaluator_step2.run( + storage = self.storage.step(), + input_test_answer_key="generated_cot", + input_gt_answer_key="golden_answer", + input_question_key="instruction", + ) + +if __name__ == "__main__": + pl = BenchEvalPipeline() + pl.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/core_text_bencheval_semantic_pipeline_question_single_step.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/core_text_bencheval_semantic_pipeline_question_single_step.py new file mode 100644 index 0000000000000000000000000000000000000000..24e8145c7d79f749740cf195a9e957cb0c36eb70 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/core_text_bencheval_semantic_pipeline_question_single_step.py @@ -0,0 +1,46 @@ +from dataflow.operators.core_text import BenchDatasetEvaluatorQuestion +from dataflow.operators.reasoning import ReasoningAnswerGenerator +from dataflow.utils.storage import FileStorage +from dataflow.serving import APILLMServing_request, LocalModelLLMServing_vllm +from dataflow.core import LLMServingABC +from dataflow.prompts.reasoning.diy import ( + DiyAnswerGeneratorPrompt, +) + +DIY_PROMPT_ANSWER = """Please output the answer.""" + +class BenchEvalPipeline(): + def __init__(self, llm_serving_generator: LLMServingABC = None, llm_serving_judger: LLMServingABC = None): + + self.storage = FileStorage( + first_entry_file_name="../example_data/core_text_data/bench_eval_data_2.jsonl", + cache_path="./cache_local", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + # use API server as LLM serving + self.llm_serving_judger = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=30 + ) + + self.evaluator_step = BenchDatasetEvaluatorQuestion( + eval_result_path="./cache_local/eval_result/eval_result.jsonl", + compare_method="semantic", # or match + llm_serving=self.llm_serving_judger, + prompt_template = None # you can diy your judger prompt in dataflow.prompts.reasoning.general.AnswerJudgePrompt + ) + + def forward(self): + self.evaluator_step.run( + storage = self.storage.step(), + input_test_answer_key="model_answer", + input_gt_answer_key="golden_label", + input_question_key="question", + ) + +if __name__ == "__main__": + pl = BenchEvalPipeline() + pl.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/func_call_synthesis.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/func_call_synthesis.py new file mode 100644 index 0000000000000000000000000000000000000000..294c28e6bb0642f7dbc1ac8c2a7b60665f1ad725 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/func_call_synthesis.py @@ -0,0 +1,90 @@ +from dataflow.utils.storage import FileStorage +from dataflow.serving import APILLMServing_request +from dataflow.operators.conversations import ( + ScenarioExtractGenerator, + ScenarioExpandGenerator, + AtomTaskGenerator, + SequentialTaskGenerator, + ParaSeqTaskGenerator, + CompositionTaskFilter, + FunctionGenerator, + MultiTurnConversationGenerator, + FuncCallConversationSampleEvaluator +) + +class FuncCall_APIPipeline: + def __init__(self): + + self.storage = FileStorage( + first_entry_file_name="../example_data/FuncCallPipeline/chat_data.jsonl", + cache_path="./cache", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + self.llm_serving = APILLMServing_request( + api_url="http://123.129.219.111:3000/v1/chat/completions", + model_name="gpt-4o", + max_workers=128 + ) + + self.scenario_extractor = ScenarioExtractGenerator(llm_serving=self.llm_serving) + self.scenario_expander = ScenarioExpandGenerator(llm_serving=self.llm_serving) + self.atom_task_generator = AtomTaskGenerator(llm_serving=self.llm_serving) + self.sequential_task_generator = SequentialTaskGenerator(llm_serving=self.llm_serving) + self.parallel_sequential_stak_generator = ParaSeqTaskGenerator(llm_serving=self.llm_serving) + self.composition_task_filter = CompositionTaskFilter(llm_serving=self.llm_serving) + self.function_generator = FunctionGenerator(llm_serving=self.llm_serving) + self.multi_turn_conversations_generator = MultiTurnConversationGenerator(llm_serving=self.llm_serving) + self.evaluator = FuncCallConversationSampleEvaluator(llm_serving=self.llm_serving) + + def forward(self): + self.scenario_extractor.run( + self.storage.step(), + input_chat_key="chat" + ) + self.scenario_expander.run( + self.storage.step(), + input_scenario_key="scenario" + ) + self.atom_task_generator.run( + self.storage.step(), + input_scenario_key="scenario" + ) + # self.atom_task_generator.run( + # self.storage.step(), + # input_scenario_key="modified_scenario", + # output_key='subsequent_task' + # ) + self.sequential_task_generator.run( + self.storage.step(), + input_task_key="atom_task" + ) + # self.parallel_sequential_stak_generator.run( + # self.storage.step(), + # input_task_key="atom_task" + # ) + self.composition_task_filter.run( + self.storage.step(), + input_composition_task_key="composition_task", + input_sub_tasks_keys=["atom_task", "subsequent_task"] + ) + self.function_generator.run( + self.storage.step(), + input_composition_task_key="composition_task", + input_sub_tasks_keys=["atom_task", "subsequent_task"] + ) + self.multi_turn_conversations_generator.run( + self.storage.step(), + input_task_key="composition_task", + input_sub_tasks_keys=["atom_task", "subsequent_task"], + input_functions_key="functions", + ) + self.evaluator.run( + self.storage.step(), + input_conversation_key='conversations' + ) + +if __name__ == "__main__": + pipeline = FuncCall_APIPipeline() + pipeline.forward() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/kbcleaning_pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/kbcleaning_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..fec30f1a288dc5656c7055e6d543dafc33c41040 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/kbcleaning_pipeline.py @@ -0,0 +1,101 @@ +from dataflow.operators.knowledge_cleaning import ( + KBCChunkGenerator, + FileOrURLToMarkdownConverterAPI, + FileOrURLToMarkdownConverterFlash, + FileOrURLToMarkdownConverterLocal, + KBCTextCleaner, + # KBCMultiHopQAGenerator, +) +from dataflow.operators.core_text import Text2MultiHopQAGenerator +from dataflow.utils.storage import FileStorage +from dataflow.serving import APILLMServing_request + +class KBCleaningPDF_APIPipeline(): + def __init__(self): + + self.storage = FileStorage( + first_entry_file_name="../example_data/KBCleaningPipeline/kbc_test_1.jsonl", + cache_path="./.cache/api", + file_name_prefix="knowledge_cleaning_step", + cache_type="json", + ) + + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=100 + ) + + # ------------case1: use MinerU official API (by default) ------------ + # by default we use API provided by MinerU official + # https://mineru.net/apiManage/docs + # self.knowledge_cleaning_step1 = FileOrURLToMarkdownConverterAPI( + # intermediate_dir="../example_data/KBCleaningPipeline/API/", + # mineru_backend="vlm", # vlm or pipeline + # api_key=None # !!! place your api key here or set environment variable MINERU_API_KEY!!! + # ) + # ------------case2: use Flash-MinerU inference locally with GPU ------------ + # https://github.com/OpenDCAI/Flash-MinerU + self.knowledge_cleaning_step1 = FileOrURLToMarkdownConverterFlash( + intermediate_dir="../example_data/KBCleaningPipeline/flash/", + mineru_model_path="/MinerU2.5-2509-1.2B", # !!! place your local model path here !!! + # https://huggingface.co/opendatalab/MinerU2.5-2509-1.2B. + batch_size=4, # batchsize per vllm worker + replicas=1, # num of vllm workers + num_gpus_per_replica=0.5, # for ray to schedule vllm workers to GPU, can be float, e.g. 0.5 means each worker uses half GPU, 1 means each worker uses whole GPU + engine_gpu_util_rate_to_ray_cap=0.9 # actuall GPU utilization for each worker; acturall memory per worker= num_gpus_per_replica * engine_gpu_util_rate_to_ray_cap; this is to avoid OOM, you can set it to 0.9 or 0.8 to leave some buffer for other processes on GPU + ) + + # ------------case3: use MinerU official inference locally (much slower than other two) ------------ + # self.knowledge_cleaning_step1 = FileOrURLToMarkdownConverterLocal( + # intermediate_dir="../example_data/KBCleaningPipeline/local/", + # mineru_backend="vlm-local-engine", + # # https://huggingface.co/opendatalab/MinerU2.5-2509-1.2B. + # mineru_model_path="/MinerU2.5-2509-1.2B", + # ) + + self.knowledge_cleaning_step2 = KBCChunkGenerator( + split_method="token", + chunk_size=512, + tokenizer_name="Qwen/Qwen2.5-7B-Instruct", + ) + + self.knowledge_cleaning_step3 = KBCTextCleaner( + llm_serving=self.llm_serving, + lang="en" + ) + + self.knowledge_cleaning_step4 = Text2MultiHopQAGenerator( + llm_serving=self.llm_serving, + lang="en", + num_q = 5 + ) + + def forward(self): + extracted=self.knowledge_cleaning_step1.run( + storage=self.storage.step(), + input_key="source", + output_key="text_path" + ) + + self.knowledge_cleaning_step2.run( + storage=self.storage.step(), + input_key="text_path", + output_key="raw_chunk" + ) + + self.knowledge_cleaning_step3.run( + storage=self.storage.step(), + input_key="raw_chunk", + output_key="cleaned_chunk" + ) + self.knowledge_cleaning_step4.run( + storage=self.storage.step(), + input_key="cleaned_chunk", + output_key="QA_pairs", + output_meta_key="QA_metadata" + ) + +if __name__ == "__main__": + model = KBCleaningPDF_APIPipeline() + model.forward() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/pdf_vqa_extract_pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/pdf_vqa_extract_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..a5d68c1f749546329900f0916657bb0a42efe630 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/pdf_vqa_extract_pipeline.py @@ -0,0 +1,86 @@ +from dataflow.operators.knowledge_cleaning import FileOrURLToMarkdownConverterAPI + +from dataflow.serving import APILLMServing_request +from dataflow.utils.storage import FileStorage +from dataflow.operators.pdf2vqa import MinerU2LLMInputOperator, LLMOutputParser, QA_Merger, PDF_Merger +from dataflow.operators.core_text import ChunkedPromptedGenerator + +from dataflow.pipeline import PipelineABC +from dataflow.prompts.pdf2vqa import QAExtractPrompt + +from pypdf import PdfWriter + +class PDF_VQA_extract_optimized_pipeline(PipelineABC): + def __init__(self): + super().__init__() + self.storage = FileStorage( + first_entry_file_name="./example_data/PDF2VQAPipeline/vqa_extract_test.jsonl", + cache_path="./cache", + file_name_prefix="vqa", + cache_type="jsonl", + ) + + self.llm_serving = APILLMServing_request( + api_url="http://123.129.219.111:3000/v1/chat/completions", + key_name_of_api_key="DF_API_KEY", + model_name="gemini-2.5-pro", + max_workers=100, + ) + + self.vqa_extract_prompt = QAExtractPrompt() + + self.pdf_merger = PDF_Merger(output_dir="./cache") + self.mineru_executor = FileOrURLToMarkdownConverterAPI(intermediate_dir = "intermediate") + self.input_formatter = MinerU2LLMInputOperator() + self.vqa_extractor = ChunkedPromptedGenerator( + llm_serving=self.llm_serving, + system_prompt = self.vqa_extract_prompt.build_prompt(), + max_chunk_len=128000, + ) + self.llm_output_parser = LLMOutputParser(output_dir="./cache", intermediate_dir="intermediate") + self.qa_merger = QA_Merger(output_dir="./cache", strict_title_match=False) + def forward(self): + self.pdf_merger.run( + storage=self.storage.step(), + input_pdf_list_key="input_pdf_paths", + input_name_key="name", + output_pdf_path_key="merged_pdf_path", + ) + self.mineru_executor.run( + storage=self.storage.step(), + input_key="merged_pdf_path", + output_key="vqa_markdown_path", + ) + self.input_formatter.run( + storage=self.storage.step(), + input_markdown_path_key="vqa_markdown_path", + output_converted_layout_key="converted_vqa_layout_path", + ) + self.vqa_extractor.run( + storage=self.storage.step(), + input_path_key="converted_vqa_layout_path", + output_path_key="extracted_llm_vqa_path", + ) + self.llm_output_parser.run( + storage=self.storage.step(), + input_response_path_key="extracted_llm_vqa_path", + input_converted_layout_path_key="converted_vqa_layout_path", + input_name_key="name", + output_qalist_path_key="extracted_vqa_path", + ) + self.qa_merger.run( + storage=self.storage.step(), + input_qalist_path_key="extracted_vqa_path", + input_name_key="name", + output_merged_qalist_path_key="output_merged_vqalist_path", + output_merged_md_path_key="output_merged_md_path", + output_qa_item_key="vqa_pair", + ) + + + +if __name__ == "__main__": + # jsonl中每一行包含input_pdf_path, name (math1, math2, physics1, chemistry1, ...) + pipeline = PDF_VQA_extract_optimized_pipeline() + pipeline.compile() + pipeline.forward() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/reasoning_diy_pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/reasoning_diy_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..e72b15b33b85828eac3a8a4231026d1e7394da3e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/reasoning_diy_pipeline.py @@ -0,0 +1,109 @@ +from dataflow.operators.reasoning import ( + ReasoningQuestionGenerator, + ReasoningAnswerGenerator, +) +from dataflow.operators.reasoning import ReasoningQuestionFilter, ReasoningAnswerNgramFilter + +from dataflow.utils.storage import FileStorage +from dataflow.serving import APILLMServing_request +from dataflow.core import LLMServingABC +from dataflow.prompts.reasoning.diy import ( + DiyQuestionFilterPrompt, + DiyAnswerGeneratorPrompt, + DiyQuestionSynthesisPrompt +) + +""" +if the 'prompt_template' is not None and the 'content_type is set to 'diy', please check the input and output format, the same as default prompt +""" + +DIY_PROMPT_QUESTION = """Please only keep the medical related data (judgement_test is true), for other data the judgement_test is false. + After these steps, output exactly: + {{ + "judgement_test": true/false, + "error_type": "" + }} + You may include your chain of thought, but the final output must be the JSON above. + + Here is the content to evaluate: + ------------------------------- + {question} + ------------------------------- + """ + +DIY_PROMPT_SYNTHESIS = """ + Please construct some new sports related data from source problem. + Here is the problem from the user: + {question} + Write another problem inspired by this one. + Not only change the problem scenario, but also try to create a new problem that requires another approach to solve. + Start directly with the problem statement and DO NOT include any phrases such as "Here is a new problem inspired by a given one". + After the problem is generated finish your response right away. + """ + +DIY_PROMPT_ANSWER = """Please firstly output a symbol "Yeah, It is the answer:", and then output the answer.""" + +class DiyReasoning_APIPipeline(): + def __init__(self, llm_serving: LLMServingABC = None): + + self.storage = FileStorage( + first_entry_file_name="../example_data/ReasoningPipeline/pipeline_general.json", + cache_path="./cache_local", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + # use API server as LLM serving + self.llm_serving = APILLMServing_request( + api_url="http://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=30 + ) + + self.question_filter_step1 = ReasoningQuestionFilter( + system_prompt="You are an expert in evaluating problems. Follow the user's instructions strictly and output your final judgment in the required JSON format.", + llm_serving=self.llm_serving, + prompt_template=DiyQuestionFilterPrompt(DIY_PROMPT_QUESTION) + ) + + self.question_gen_step2 = ReasoningQuestionGenerator( + num_prompts=1, + llm_serving=self.llm_serving, + prompt_template=DiyQuestionSynthesisPrompt(DIY_PROMPT_SYNTHESIS) + ) + + self.answer_generator_step3 = ReasoningAnswerGenerator( + llm_serving=self.llm_serving, + prompt_template=DiyAnswerGeneratorPrompt(DIY_PROMPT_ANSWER) + ) + + self.answer_ngram_filter_step4 = ReasoningAnswerNgramFilter( + min_score = 0.1, + max_score = 1.0, + ngrams = 5 + ) + + def forward(self): + self.question_filter_step1.run( + storage = self.storage.step(), + input_key = "instruction", + ) + + self.question_gen_step2.run( + storage = self.storage.step(), + input_key = "instruction", + ) + self.answer_generator_step3.run( + storage = self.storage.step(), + input_key = "instruction", + output_key = "generated_cot" + ) + self.answer_ngram_filter_step4.run( + storage = self.storage.step(), + input_question_key = "instruction", + input_answer_key = "generated_cot" + ) + +if __name__ == "__main__": + pl = DiyReasoning_APIPipeline() + pl.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/reasoning_general_pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/reasoning_general_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..38fd42a1cd2ba9d25aa4e2dd02ad5a8ce441c7e3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/reasoning_general_pipeline.py @@ -0,0 +1,89 @@ +from dataflow.operators.reasoning import ( + ReasoningQuestionGenerator, + ReasoningAnswerGenerator, +) +from dataflow.operators.reasoning import ReasoningQuestionFilter, ReasoningAnswerNgramFilter, ReasoningAnswerModelJudgeFilter +from dataflow.utils.storage import FileStorage +from dataflow.serving import APILLMServing_request +from dataflow.core import LLMServingABC +from dataflow.prompts.reasoning.general import ( + GeneralQuestionFilterPrompt, + GeneralAnswerGeneratorPrompt, + GeneralQuestionSynthesisPrompt, +) +from dataflow.prompts.model_evaluation.general import AnswerJudgePrompt + +class GeneralReasoning_APIPipeline(): + def __init__(self, llm_serving: LLMServingABC = None): + + self.storage = FileStorage( + first_entry_file_name="../example_data/ReasoningPipeline/pipeline_general.json", + cache_path="./cache_local", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + # use API server as LLM serving + self.llm_serving = APILLMServing_request( + api_url="http://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=30 + ) + + self.question_filter_step1 = ReasoningQuestionFilter( + system_prompt="You are an expert in evaluating problems. Follow the user's instructions strictly and output your final judgment in the required JSON format.", + llm_serving=self.llm_serving, + prompt_template=GeneralQuestionFilterPrompt() + ) + + self.question_gen_step2 = ReasoningQuestionGenerator( + num_prompts=1, + llm_serving=self.llm_serving, + prompt_template=GeneralQuestionSynthesisPrompt() + ) + + self.answer_generator_step3 = ReasoningAnswerGenerator( + llm_serving=self.llm_serving, + prompt_template=GeneralAnswerGeneratorPrompt() + ) + self.answer_model_judge_step4 = ReasoningAnswerModelJudgeFilter( + llm_serving=self.llm_serving, + prompt_template=AnswerJudgePrompt(), + keep_all_samples=True + ) + self.answer_ngram_filter_step5 = ReasoningAnswerNgramFilter( + min_score = 0.1, + max_score = 1.0, + ngrams = 5 + ) + + def forward(self): + self.question_filter_step1.run( + storage = self.storage.step(), + input_key = "instruction", + ) + + self.question_gen_step2.run( + storage = self.storage.step(), + input_key = "instruction", + ) + self.answer_generator_step3.run( + storage = self.storage.step(), + input_key = "instruction", + output_key = "generated_cot" + ), + self.answer_model_judge_step4.run( + storage = self.storage.step(), + input_question_key = "instruction", + input_answer_key = "generated_cot", + input_reference_key = "golden_answer" + ), + self.answer_ngram_filter_step5.run( + storage = self.storage.step(), + input_question_key = "instruction", + input_answer_key = "generated_cot" + ) + +if __name__ == "__main__": + pl = GeneralReasoning_APIPipeline() + pl.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/reasoning_math_pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/reasoning_math_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..8e3f5705dae985101192d89e2a435645c2e92ea7 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/reasoning_math_pipeline.py @@ -0,0 +1,160 @@ +from dataflow.operators.reasoning import ( + ReasoningQuestionCategorySampleEvaluator, + ReasoningQuestionDifficultySampleEvaluator, + ReasoningQuestionGenerator, + ReasoningAnswerGenerator, +) + +from dataflow.operators.reasoning import ( + ReasoningQuestionFilter, + ReasoningAnswerFormatterFilter, + ReasoningAnswerGroundTruthFilter, + ReasoningAnswerTokenLengthFilter, + ReasoningAnswerNgramFilter +) + +from dataflow.prompts.reasoning.math import ( + MathQuestionFilterPrompt, + MathAnswerGeneratorPrompt, + MathQuestionSynthesisPrompt +) + +from dataflow.utils.storage import FileStorage +from dataflow.serving import APILLMServing_request +from dataflow.core import LLMServingABC + +# 这里或许未来可以有个pipeline基类 +class ReasoningMath_APIPipeline(): + def __init__(self, llm_serving: LLMServingABC = None): + + self.storage = FileStorage( + first_entry_file_name="../example_data/ReasoningPipeline/pipeline_math_short.json", + cache_path="./cache_local", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + # use API server as LLM serving + self.llm_serving = APILLMServing_request( + api_url="http://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=100 + ) + + # if llm_serving is None: + # # use local model as LLM serving + # llm_serving = LocalModelLLMServing( + # # model_name_or_path="/data0/models/Qwen2.5-7B-Instruct", # set to your own model path + # model_name_or_path="/mnt/public/model/huggingface/Qwen2.5-7B-Instruct", + # tensor_parallel_size=4, + # max_tokens=8192, + # model_source="local" + # ) + + self.question_filter_step1 = ReasoningQuestionFilter( + system_prompt="You are an expert in evaluating mathematical problems. Follow the user's instructions strictly and output your final judgment in the required JSON format.", + llm_serving=self.llm_serving, + prompt_template=MathQuestionFilterPrompt() + ) + self.question_gen_step2 = ReasoningQuestionGenerator( + num_prompts=3, + llm_serving=self.llm_serving, + prompt_template=MathQuestionSynthesisPrompt() + ) + self.question_filter_step3 = ReasoningQuestionFilter( + system_prompt="You are an expert in evaluating mathematical problems. Follow the user's instructions strictly and output your final judgment in the required JSON format.", + llm_serving=self.llm_serving, + prompt_template=MathQuestionFilterPrompt() + ) + self.question_difficulty_classifier_step4 = ReasoningQuestionDifficultySampleEvaluator( + llm_serving=self.llm_serving + ) + self.question_category_classifier_step5 = ReasoningQuestionCategorySampleEvaluator( + llm_serving=self.llm_serving + ) + ########################## branch ############################ + # self.answer_pipeline_root_step6 = AnswerPipelineRoot() + ########################## answer ############################ + self.answer_generator_step7 = ReasoningAnswerGenerator( + llm_serving=self.llm_serving, + prompt_template=MathAnswerGeneratorPrompt() + ) + + self.answer_format_filter_step8 = ReasoningAnswerFormatterFilter() + + self.answer_token_length_filter_step9 = ReasoningAnswerTokenLengthFilter( + max_answer_token_length = 8192, + tokenizer_dir = "Qwen/Qwen2.5-0.5B-Instruct" + ) + + self.answer_groundtruth_filter_step10 = ReasoningAnswerGroundTruthFilter() + + self.answer_ngram_filter_step11 = ReasoningAnswerNgramFilter( + min_score = 0.1, + max_score = 1.0, + ngrams = 5 + ) + + # 未来或许可以维护一个类似nn.sequential的容器,方便添加并实例化多个算子 + def forward(self): + + self.question_filter_step1.run( + storage = self.storage.step(), + input_key = "instruction", + ) + + self.question_gen_step2.run( + storage = self.storage.step(), + input_key = "instruction", + ) + + self.question_filter_step3.run( + storage = self.storage.step(), + input_key = "instruction", + ) + + self.question_difficulty_classifier_step4.run( + storage = self.storage.step(), + input_key = "instruction", + output_key = "question_difficulty" + ) + + self.question_category_classifier_step5.run( + storage = self.storage.step(), + input_key = "instruction", + output_key = "question_category" + ) + ############# branch ############# + # self.answer_pipeline_root_step6.run( + # storage = self.storage.step(), + # input_answer_key = "output", + # input_gt_key = "golden_answer" + # ) + ############## answer ############# + self.answer_generator_step7.run( + storage = self.storage.step(), + input_key = "instruction", + output_key = "generated_cot" + ) + self.answer_format_filter_step8.run( + storage = self.storage.step(), + input_key = "generated_cot", + ) + self.answer_token_length_filter_step9.run( + storage = self.storage.step(), + input_key = "generated_cot" + ) + self.answer_groundtruth_filter_step10.run( + storage = self.storage.step(), + input_test_answer_key = "generated_cot", + input_gt_answer_key = "golden_answer" + ) + self.answer_ngram_filter_step11.run( + storage = self.storage.step(), + input_question_key = "instruction", + input_answer_key = "generated_cot" + ) + +if __name__ == "__main__": + model = ReasoningMath_APIPipeline() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/reasoning_math_pipeline_mathfusion.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/reasoning_math_pipeline_mathfusion.py new file mode 100644 index 0000000000000000000000000000000000000000..2da34a2a10fb05dbc2b53eb62c666476c39f8f6a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/reasoning_math_pipeline_mathfusion.py @@ -0,0 +1,193 @@ +from dataflow.operators.reasoning import ( + ReasoningQuestionFusionGenerator, + ReasoningQuestionSolvableSampleEvaluator, +) +from dataflow.operators.core_text import ( + PandasOperator, + EmbeddingGenerator, +) + +from dataflow.prompts.reasoning.math import ( + MathQuestionParallelFusionGeneratorPrompt, + MathQuestionSequentialFusionGeneratorPrompt, + MathQuestionConditionFusionGeneratorPrompt, + MathQuestionEvaluatorPrompt +) + +from dataflow.utils.storage import FileStorage +from dataflow.serving import APILLMServing_request +from dataflow.core import LLMServingABC +import torch +import numpy as np +import pandas as pd +import re + +# 这里或许未来可以有个pipeline基类 +class ReasoningMath_APIPipeline_Mathfusion(): + def __init__(self, llm_serving: LLMServingABC = None): + + self.storage = FileStorage( + first_entry_file_name="../example_data/ReasoningPipeline/pipeline_math_short.json", + cache_path="./cache", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + # use API server as LLM serving + llm_serving = APILLMServing_request( + api_url="http://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=10 + ) + + embedding_serving = APILLMServing_request( + api_url="http://api.openai.com/v1/embeddings", + model_name="text-embedding-ada-002", + max_workers=10 + ) + + self.embedding_generator = EmbeddingGenerator(embedding_serving=embedding_serving) + + def find_most_similar_questions(df): + df = df.dropna(subset=['embeddings']).reset_index(drop=True) + embeddings = torch.tensor(np.stack(df['embeddings'].values), dtype=torch.float32).cuda() # shape: (n, d) + sim_matrix = torch.matmul(embeddings, embeddings.T) # shape: (n, n) + sim_matrix.fill_diagonal_(-float('inf')) + most_similar_idx = torch.argmax(sim_matrix, dim=1).cpu().numpy() + df['most_similar_problem'] = df['question'].iloc[most_similar_idx].values + + return df + + self.most_similar_matcher = PandasOperator([ + find_most_similar_questions + ]) + + self.extract_pair = PandasOperator([ # dropping embeddings to decrease file size + lambda df: df.drop(columns=[col for col in df.columns if "embeddings" in col]) + ]) + + self.sequential_fusion = ReasoningQuestionFusionGenerator( + num_prompts=1, + llm_serving=llm_serving, + prompt_template=MathQuestionSequentialFusionGeneratorPrompt() + ) + + self.parallel_fusion = ReasoningQuestionFusionGenerator( + num_prompts=1, + llm_serving=llm_serving, + prompt_template=MathQuestionParallelFusionGeneratorPrompt() + ) + + self.condition_fusion = ReasoningQuestionFusionGenerator( + num_prompts=2, + llm_serving=llm_serving, + prompt_template=MathQuestionConditionFusionGeneratorPrompt() + ) + + def combined(df: pd.DataFrame) -> pd.DataFrame: + """ + Combine all question-related columns into a single long-format DataFrame. + Automatically detects columns containing '_question_{i}' patterns. + """ + # 始终保留原始 question + question_cols = ["question"] if "question" in df.columns else [] + + # 匹配所有类似 *_question_0, *_question_1, ... + pattern = re.compile(r".*_question_\d+$") + question_cols.extend([col for col in df.columns if pattern.match(col)]) + + if not question_cols: + raise ValueError("No question columns found matching pattern '_question_{i}'.") + + # 转换成长表 + long_df = df.melt(value_vars=question_cols, value_name="questions")[["questions"]] + + # 去除空值与重复项(通常同一问题会出现重复) + long_df = long_df.dropna(subset=["questions"]).drop_duplicates().reset_index(drop=True) + + return long_df + + self.combined_question = PandasOperator([combined]) + + self.question_evaluation = ReasoningQuestionSolvableSampleEvaluator(llm_serving=llm_serving, prompt_template=MathQuestionEvaluatorPrompt()) + + def extract_new_problem(df: pd.DataFrame) -> pd.DataFrame: + """ + Extract the content after '#New Problem#' from the 'questions' column + and store it in a new column 'new_problem'. + """ + if "questions" not in df.columns: + raise ValueError("Input DataFrame must contain a 'questions' column.") + + def _extract(text: str) -> str: + if not isinstance(text, str): + return None + match = re.search(r"#New Problem#[:\s]*(.*)", text, re.DOTALL) + return match.group(1).strip() if match else None + + df = df.copy() + df["refined_question"] = df["questions"].apply(_extract) + df = df.dropna(subset=["refined_question"]).reset_index(drop=True) + + return df + + self.extract_new_problem = PandasOperator([extract_new_problem]) + + def forward(self): + # self.first10.run( + # storage = self.storage.step(), + # ) + + self.embedding_generator.run( + storage = self.storage.step(), + input_key = "question", + output_key = "embeddings", + ) + + self.most_similar_matcher.run( + storage = self.storage.step(), + ) + + self.extract_pair.run( + storage = self.storage.step(), + ) + + self.sequential_fusion.run( + storage = self.storage.step(), + input_problem_1= "question", + input_problem_2= "most_similar_problem", + output_key="sequential_fusion", + ) + + self.parallel_fusion.run( + storage = self.storage.step(), + input_problem_1= "question", + input_problem_2= "most_similar_problem", + output_key="parallel_fusion" + ) + + self.condition_fusion.run( + storage = self.storage.step(), + input_problem_1= "question", + input_problem_2= "most_similar_problem", + output_key="condition_fusion" + ) + + self.combined_question.run( + storage = self.storage.step() + ) + + self.question_evaluation.run( + storage = self.storage.step(), + input_key = "questions", + output_key= "question_solvability" + ) + self.extract_new_problem.run( + storage = self.storage.step() + ) + + + +if __name__ == "__main__": + pl = ReasoningMath_APIPipeline_Mathfusion() + pl.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/reasoning_pretrain_pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/reasoning_pretrain_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..f6c599b6415b73c4b834c9d8f6d348c10ce86c19 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/reasoning_pretrain_pipeline.py @@ -0,0 +1,109 @@ +from dataflow.operators.reasoning import ( + ReasoningQuestionGenerator, + ReasoningAnswerGenerator, + ReasoningPretrainFormatConvertGenerator +) +from dataflow.prompts.reasoning.math import ( + MathQuestionFilterPrompt, + MathQuestionSynthesisPrompt, + MathAnswerGeneratorPrompt +) +from dataflow.operators.reasoning import ReasoningQuestionFilter, ReasoningAnswerNgramFilter, ReasoningAnswerPipelineRootFilter +from dataflow.utils.storage import FileStorage +from dataflow.serving import APILLMServing_request + +# 这里或许未来可以有个pipeline基类 +class Reasoning_APIPipeline_Pretrain(): + def __init__(self, llm_serving=None): + + self.storage = FileStorage( + first_entry_file_name="../example_data/ReasoningPipeline/pipeline_math_short.json", + cache_path="./cache_local", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + if llm_serving is None: + # use API server as LLM serving + self.llm_serving = APILLMServing_request( + api_url="http://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=100 + ) + + ## use local model as LLM serving + # llm_serving = LocalModelLLMServing( + # # model_name_or_path="/data0/models/Qwen2.5-7B-Instruct", # set to your own model path + # model_name_or_path="/mnt/public/model/huggingface/Qwen2.5-7B-Instruct", + # tensor_parallel_size=4, + # max_tokens=1024, + # model_source="local" + # ) + + self.question_filter_step1 = ReasoningQuestionFilter( + system_prompt="You are an expert in evaluating mathematical problems. Follow the user's instructions strictly and output your final judgment in the required JSON format.", + llm_serving=self.llm_serving, + prompt_template=MathQuestionFilterPrompt() + ) + self.question_gen_step2 = ReasoningQuestionGenerator( + num_prompts=3, + llm_serving=self.llm_serving, + prompt_template=MathQuestionSynthesisPrompt() + ) + + ########################## branch ############################ + self.answer_pipeline_root_step3 = ReasoningAnswerPipelineRootFilter() + ########################## answer ############################ + self.answer_generator_step4 = ReasoningAnswerGenerator( + llm_serving=self.llm_serving, + prompt_template=MathAnswerGeneratorPrompt() + ) + + self.answer_ngram_filter_step5 = ReasoningAnswerNgramFilter( + min_score = 0.1, + max_score = 1.0, + ngrams = 5 + ) + + self.sft_to_pretrain_step6 = ReasoningPretrainFormatConvertGenerator() + + # 未来或许可以维护一个类似nn.sequential的容器,方便添加并实例化多个算子 + def forward(self): + + self.question_filter_step1.run( + storage = self.storage.step(), + input_key = "instruction", + ) + + self.question_gen_step2.run( + storage = self.storage.step(), + input_key = "instruction", + ) + + ############# branch ############# + self.answer_pipeline_root_step3.run( + storage = self.storage.step(), + input_answer_key = "output", + input_gt_key = "golden_answer" + ) + ############## answer ############# + self.answer_generator_step4.run( + storage = self.storage.step(), + input_key = "instruction", + output_key = "generated_cot" + ) + self.answer_ngram_filter_step5.run( + storage = self.storage.step(), + input_question_key = "instruction", + input_answer_key = "generated_cot" + ) + self.sft_to_pretrain_step6.run( + storage = self.storage.step(), + input_read_key_question="instruction", + input_read_key_answer="generated_cot", + output_key="text", + ) + +if __name__ == "__main__": + pipeline = Reasoning_APIPipeline_Pretrain() + pipeline.forward() + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/text2qa_pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/text2qa_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..419800e12a61294dd72d20ec285b852add70fa80 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/text2qa_pipeline.py @@ -0,0 +1,69 @@ +from dataflow.operators.core_text import ( + Text2QASampleEvaluator, + Text2QAGenerator, + KCenterGreedyFilter +) + +from dataflow.utils.storage import FileStorage +from dataflow.serving import APILLMServing_request +from dataflow.serving import LocalModelLLMServing_vllm + +class Text2QA_APIPipeline(): + def __init__(self): + + self.storage = FileStorage( + first_entry_file_name="../example_data/core_text_data/pipeline_small_chunk.json", + cache_path="./cache_local", + file_name_prefix="dataflow_cache_step", + cache_type="json", + ) + + # use API server as LLM serving + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=1 + ) + + embedding_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/embeddings", + model_name="text-embedding-ada-002", + max_workers=100 + ) + + self.content_chooser_step1 = KCenterGreedyFilter(embedding_serving=embedding_serving, num_samples=5) + + self.text2qa_generator_step3 = Text2QAGenerator(self.llm_serving) + + self.text2qa_scorer_step4 = Text2QASampleEvaluator(self.llm_serving) + + def forward(self): + + self.content_chooser_step1.run( + storage = self.storage.step(), + input_key = "text" + ) + + self.text2qa_generator_step3.run( + storage = self.storage.step(), + input_key="text", + input_question_num= 3, + output_prompt_key="generated_prompt", + output_quesion_key="generated_question", + output_answer_key="generated_answer" + ) + + self.text2qa_scorer_step4.run( + storage = self.storage.step(), + input_question_key="generated_question", + input_answer_key="generated_answer", + output_question_quality_key="question_quality_grades", + output_question_quality_feedback_key="question_quality_feedbacks", + output_answer_alignment_key="answer_alignment_grades", + output_answer_alignment_feedback_key="answer_alignment_feedbacks", + output_answer_verifiability_key="answer_verifiability_grades", + ) + +if __name__ == "__main__": + model = Text2QA_APIPipeline() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/text2sql_pipeline_gen.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/text2sql_pipeline_gen.py new file mode 100644 index 0000000000000000000000000000000000000000..c9fd8f0576b89aac9594f25f34a026970c3a91b9 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/text2sql_pipeline_gen.py @@ -0,0 +1,261 @@ +import os +from dataflow import get_logger +import zipfile +from huggingface_hub import snapshot_download + +from dataflow.operators.text2sql import ( + SQLGenerator, + SQLByColumnGenerator, + Text2SQLQuestionGenerator, + Text2SQLPromptGenerator, + Text2SQLCoTGenerator, + Text2SQLCoTVotingGenerator +) +from dataflow.operators.text2sql import ( + SQLExecutabilityFilter, + Text2SQLCorrespondenceFilter +) +from dataflow.operators.text2sql import ( + SQLComponentClassifier, + SQLExecutionClassifier +) +from dataflow.prompts.text2sql import ( + Text2SQLCotGeneratorPrompt, + SelectSQLGeneratorPrompt, + Text2SQLQuestionGeneratorPrompt, + Text2SQLPromptGeneratorPrompt, + Text2SQLCorrespondenceFilterPrompt +) +from dataflow.utils.storage import FileStorage +from dataflow.serving import APILLMServing_request +from dataflow.utils.text2sql.database_manager import DatabaseManager + + +def download_and_extract_database(logger): + dataset_repo_id = "Open-Dataflow/dataflow-Text2SQL-database-example" + local_dir = "./hf_cache" + extract_to = "./downloaded_databases" + + logger.info(f"Downloading and extracting database from {dataset_repo_id}...") + os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com' + + db_exp_folder_path = os.path.join(extract_to, "databases") + + if os.path.exists(db_exp_folder_path): + return db_exp_folder_path + + os.makedirs(local_dir, exist_ok=True) + os.makedirs(extract_to, exist_ok=True) + + downloaded_path = snapshot_download( + repo_id=dataset_repo_id, + repo_type="dataset", + local_dir=local_dir, + resume_download=True + ) + + logger.info(f"Files downloaded to: {downloaded_path}") + + zip_path = os.path.join(downloaded_path, "databases.zip") + if os.path.exists(zip_path): + with zipfile.ZipFile(zip_path, 'r') as zip_ref: + zip_ref.extractall(extract_to) + logger.info(f"Database files extracted to {extract_to}") + return db_exp_folder_path + else: + raise FileNotFoundError(f"Database zip file not found at {zip_path}") + +class Text2SQLGeneration_APIPipeline(): + def __init__(self, db_root_path=""): + self.logger = get_logger() + self.db_root_path = db_root_path + + if not db_root_path: + try: + self.db_root_path = download_and_extract_database(self.logger) + self.logger.info(f"Using automatically downloaded database at: {self.db_root_path}") + except Exception as e: + self.logger.error(f"Failed to auto-download database: {e}") + raise + else: + self.logger.info(f"Using manually specified database path: {self.db_root_path}") + + if not os.path.exists(self.db_root_path): + raise FileNotFoundError(f"Database path does not exist: {self.db_root_path}") + + self.storage = FileStorage( + first_entry_file_name="../example_data/Text2SQLPipeline/empty.jsonl", + cache_path="./cache", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=100 + ) + + self.embedding_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/embeddings", + model_name="text-embedding-ada-002", + max_workers=100 + ) + + # SQLite and MySQL are currently supported + # db_type can be sqlite or mysql, which must match your database type + # If sqlite is selected, root_path must be provided, this path must exist and contain database files + # If mysql is selected, host, user, password must be provided, these credentials must be correct and have access permissions + # MySQL example: + # database_manager = DatabaseManager( + # db_type="mysql", + # config={ + # "host": "localhost", + # "user": "root", + # "password": "your_password", + # "database": "your_database_name" + # } + # ) + # SQLite example: + database_manager = DatabaseManager( + db_type="sqlite", + config={ + "root_path": self.db_root_path + } + ) + + self.sql_generator_step1 = SQLGenerator( + llm_serving=self.llm_serving, + database_manager=database_manager, + generate_num=2, + prompt_template=SelectSQLGeneratorPrompt() + ) + + self.sql_executability_filter_step2 = SQLExecutabilityFilter( + database_manager=database_manager + ) + + self.text2sql_question_generator_step3 = Text2SQLQuestionGenerator( + llm_serving=self.llm_serving, + embedding_serving=self.embedding_serving, + database_manager=database_manager, + question_candidates_num=3, + prompt_template=Text2SQLQuestionGeneratorPrompt() + ) + + self.text2sql_correspondence_filter_step4 = Text2SQLCorrespondenceFilter( + llm_serving=self.llm_serving, + database_manager=database_manager, + prompt_template=Text2SQLCorrespondenceFilterPrompt() + ) + + self.text2sql_prompt_generator_step5 = Text2SQLPromptGenerator( + database_manager=database_manager, + prompt_template=Text2SQLPromptGeneratorPrompt() + ) + + self.sql_cot_generator_step6 = Text2SQLCoTGenerator( + llm_serving=self.llm_serving, + database_manager=database_manager, + prompt_template=Text2SQLCotGeneratorPrompt() + ) + + self.sql_cot_voting_generator_step7 = Text2SQLCoTVotingGenerator( + database_manager=database_manager + ) + + self.sql_component_classifier_step8 = SQLComponentClassifier( + difficulty_thresholds=[2, 4, 6], + difficulty_labels=['easy', 'medium', 'hard', 'extra'] + ) + + self.sql_execution_classifier_step9 = SQLExecutionClassifier( + llm_serving=self.llm_serving, + database_manager=database_manager, + num_generations=10, + difficulty_thresholds=[2, 5, 9], + difficulty_labels=['extra', 'hard', 'medium', 'easy'] + ) + + def forward(self): + + sql_key = "SQL" + db_id_key = "db_id" + question_key = "question" + evidence_key = "evidence" + + self.sql_generator_step1.run( + storage=self.storage.step(), + output_sql_key=sql_key, + output_db_id_key=db_id_key, + output_sql_complexity_key="sql_complexity_type" + ) + + self.sql_executability_filter_step2.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_db_id_key=db_id_key + ) + + self.text2sql_question_generator_step3.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_db_id_key=db_id_key, + output_question_key=question_key, + output_evidence_key=evidence_key + ) + + self.text2sql_correspondence_filter_step4.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_db_id_key=db_id_key, + input_question_key=question_key, + input_evidence_key=evidence_key + ) + + self.text2sql_prompt_generator_step5.run( + storage=self.storage.step(), + input_question_key=question_key, + input_db_id_key=db_id_key, + input_evidence_key=evidence_key, + output_prompt_key="prompt" + ) + + self.sql_cot_generator_step6.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_question_key=question_key, + input_db_id_key=db_id_key, + input_evidence_key=evidence_key, + output_cot_key="cot_reasoning" + ) + + self.sql_cot_voting_generator_step7.run( + storage=self.storage.step(), + input_cot_responses_key="cot_responses", + input_db_id_key=db_id_key, + output_cot_key="cot_reasoning" + ) + + self.sql_component_classifier_step8.run( + storage=self.storage.step(), + input_sql_key=sql_key, + output_difficulty_key="sql_component_difficulty" + ) + + self.sql_execution_classifier_step9.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_db_id_key=db_id_key, + input_prompt_key="prompt", + output_difficulty_key="sql_execution_difficulty" + ) + +if __name__ == "__main__": + # If you have your own database files, you can set the db_root_path to the path of your database files + # If not, please set the db_root_path "", and we will download the example database files automatically + db_root_path = "" + + model = Text2SQLGeneration_APIPipeline(db_root_path=db_root_path) + model.forward() + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/text2sql_pipeline_refine.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/text2sql_pipeline_refine.py new file mode 100644 index 0000000000000000000000000000000000000000..56a7b6f69c8a7b002fe286533d3d16a936947ea3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/text2sql_pipeline_refine.py @@ -0,0 +1,271 @@ +import os +from dataflow import get_logger +import zipfile +from pathlib import Path +from huggingface_hub import snapshot_download + +from dataflow.operators.text2sql import ( + SQLVariationGenerator, + Text2SQLQuestionGenerator, + Text2SQLPromptGenerator, + Text2SQLCoTGenerator, + Text2SQLCoTVotingGenerator +) +from dataflow.operators.text2sql import ( + SQLExecutabilityFilter, + Text2SQLCorrespondenceFilter +) +from dataflow.operators.text2sql import ( + SQLComponentClassifier, + SQLExecutionClassifier +) +from dataflow.prompts.text2sql import ( + Text2SQLCorrespondenceFilterPrompt, + Text2SQLCotGeneratorPrompt, + Text2SQLQuestionGeneratorPrompt, + SQLVariationGeneratorPrompt, + Text2SQLPromptGeneratorPrompt +) +from dataflow.utils.storage import FileStorage +from dataflow.serving import APILLMServing_request +from dataflow.utils.text2sql.database_manager import DatabaseManager + + +def download_and_extract_database(logger): + dataset_repo_id = "Open-Dataflow/dataflow-Text2SQL-database-example" + local_dir = "./hf_cache" + extract_to = "./downloaded_databases" + + logger.info(f"Downloading and extracting database from {dataset_repo_id}...") + os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com' + + db_exp_folder_path = os.path.join(extract_to, "databases") + + if os.path.exists(db_exp_folder_path): + return db_exp_folder_path + + os.makedirs(local_dir, exist_ok=True) + os.makedirs(extract_to, exist_ok=True) + + downloaded_path = snapshot_download( + repo_id=dataset_repo_id, + repo_type="dataset", + local_dir=local_dir, + resume_download=True + ) + + logger.info(f"Files downloaded to: {downloaded_path}") + + zip_path = os.path.join(downloaded_path, "databases.zip") + if os.path.exists(zip_path): + with zipfile.ZipFile(zip_path, 'r') as zip_ref: + zip_ref.extractall(extract_to) + logger.info(f"Database files extracted to {extract_to}") + return db_exp_folder_path + else: + raise FileNotFoundError(f"Database zip file not found at {zip_path}") + +class Text2SQLRefine_APIPipeline(): + def __init__(self, db_root_path=""): + self.logger = get_logger() + self.db_root_path = db_root_path + + if not db_root_path: + try: + self.db_root_path = download_and_extract_database(self.logger) + self.logger.info(f"Using automatically downloaded database at: {self.db_root_path}") + except Exception as e: + self.logger.error(f"Failed to auto-download database: {e}") + raise + else: + self.logger.info(f"Using manually specified database path: {self.db_root_path}") + + if not os.path.exists(self.db_root_path): + raise FileNotFoundError(f"Database path does not exist: {self.db_root_path}") + + self.storage = FileStorage( + first_entry_file_name="../example_data/Text2SQLPipeline/pipeline_refine.jsonl", + cache_path="./cache", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl" + ) + + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=100 + ) + + self.embedding_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/embeddings", + model_name="text-embedding-ada-002", + max_workers=100 + ) + + # SQLite and MySQL are currently supported + # db_type can be sqlite or mysql, which must match your database type + # If sqlite is selected, root_path must be provided, this path must exist and contain database files + # If mysql is selected, host, user, password must be provided, these credentials must be correct and have access permissions + # MySQL example: + # database_manager = DatabaseManager( + # db_type="mysql", + # config={ + # "host": "localhost", + # "user": "root", + # "password": "your_password", + # "database": "your_database_name" + # } + # ) + # SQLite example: + database_manager = DatabaseManager( + db_type="sqlite", + config={ + "root_path": self.db_root_path + } + ) + + self.sql_executability_filter_step1 = SQLExecutabilityFilter( + database_manager=database_manager + ) + + self.sql_variation_generator_step2 = SQLVariationGenerator( + llm_serving=self.llm_serving, + database_manager=database_manager, + num_variations=3, # Number of variations to generate for each SQL + prompt_template=SQLVariationGeneratorPrompt() + ) + + self.sql_executability_filter_step3 = SQLExecutabilityFilter( + database_manager=database_manager + ) + + self.text2sql_question_generator_step4 = Text2SQLQuestionGenerator( + llm_serving=self.llm_serving, + embedding_serving=self.embedding_serving, + database_manager=database_manager, + question_candidates_num=3, + prompt_template=Text2SQLQuestionGeneratorPrompt() + ) + + self.text2sql_correspondence_filter_step5 = Text2SQLCorrespondenceFilter( + llm_serving=self.llm_serving, + database_manager=database_manager, + prompt_template=Text2SQLCorrespondenceFilterPrompt() + ) + + self.text2sql_prompt_generator_step6 = Text2SQLPromptGenerator( + database_manager=database_manager, + prompt_template=Text2SQLPromptGeneratorPrompt() + ) + + self.sql_cot_generator_step7 = Text2SQLCoTGenerator( + llm_serving=self.llm_serving, + database_manager=database_manager, + prompt_template=Text2SQLCotGeneratorPrompt() + ) + + self.sql_cot_voting_generator_step8 = Text2SQLCoTVotingGenerator( + database_manager=database_manager + ) + + self.sql_component_classifier_step9 = SQLComponentClassifier( + difficulty_thresholds=[2, 4, 6], + difficulty_labels=['easy', 'medium', 'hard', 'extra'] + ) + + self.sql_execution_classifier_step10 = SQLExecutionClassifier( + llm_serving=self.llm_serving, + database_manager=database_manager, + num_generations=10, + difficulty_thresholds=[2, 5, 9], + difficulty_labels=['extra', 'hard', 'medium', 'easy'] + ) + + + def forward(self): + + sql_key = "SQL" + db_id_key = "db_id" + question_key = "question" + evidence_key = "evidence" + + self.sql_executability_filter_step1.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_db_id_key=db_id_key + ) + + self.sql_variation_generator_step2.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_db_id_key=db_id_key, + output_sql_variation_type_key="sql_variation_type" + ) + + self.sql_executability_filter_step3.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_db_id_key=db_id_key + ) + + self.text2sql_question_generator_step4.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_db_id_key=db_id_key, + output_question_key=question_key, + output_evidence_key=evidence_key + ) + + self.text2sql_correspondence_filter_step5.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_db_id_key=db_id_key, + input_question_key=question_key, + input_evidence_key=evidence_key + ) + + self.text2sql_prompt_generator_step6.run( + storage=self.storage.step(), + input_question_key=question_key, + input_db_id_key=db_id_key, + input_evidence_key=evidence_key, + output_prompt_key="prompt" + ) + + self.sql_cot_generator_step7.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_question_key=question_key, + input_db_id_key=db_id_key, + input_evidence_key=evidence_key, + output_cot_key="cot_reasoning" + ) + + self.sql_cot_voting_generator_step8.run( + storage=self.storage.step(), + input_cot_responses_key="cot_responses", + input_db_id_key=db_id_key, + output_cot_key="cot_reasoning" + ) + + self.sql_component_classifier_step9.run( + storage=self.storage.step(), + input_sql_key=sql_key, + output_difficulty_key="sql_component_difficulty" + ) + + self.sql_execution_classifier_step10.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_db_id_key=db_id_key, + input_prompt_key="prompt", + output_difficulty_key="sql_execution_difficulty" + ) + +if __name__ == "__main__": + # If you have your own database files, you can set the db_root_path to the path of your database files + # If not, please set the db_root_path "", and we will download the example database files automatically + db_root_path = "" + + model = Text2SQLRefine_APIPipeline(db_root_path=db_root_path) + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/text2vecsql_pipeline_gen.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/text2vecsql_pipeline_gen.py new file mode 100644 index 0000000000000000000000000000000000000000..cba0e162af83bd66fc89dab7dfd3bf3c96a3c17e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/text2vecsql_pipeline_gen.py @@ -0,0 +1,225 @@ +import os +from dataflow import get_logger +import zipfile +from pathlib import Path +from huggingface_hub import snapshot_download + +from dataflow.operators.text2sql import ( + SQLByColumnGenerator, + Text2SQLQuestionGenerator, + Text2SQLPromptGenerator +) +from dataflow.operators.text2sql import ( + SQLExecutionFilter +) +from dataflow.operators.text2sql import ( + SQLComponentClassifier, + SQLExecutionClassifier +) +from dataflow.prompts.text2sql import ( + SelectVecSQLGeneratorPrompt, + Text2VecSQLQuestionGeneratorPrompt, + Text2VecSQLPromptGeneratorPrompt +) +from dataflow.utils.storage import FileStorage +from dataflow.serving import APILLMServing_request +from dataflow.serving import LocalEmbeddingServing +from dataflow.utils.text2sql.database_manager import DatabaseManager + + +def download_and_extract_database(logger): + dataset_repo_id = "Open-Dataflow/dataflow-Text2SQL-vector-database-example" + subfolder = "databases_vec" + local_dir = "./hf_cache" + extract_to = "./downloaded_databases_vec" + + logger.info(f"Downloading and extracting database from {dataset_repo_id}...") + # os.environ['HF_ENDPOINT'] = 'https://alpha.hf-mirror.com' + + os.makedirs(local_dir, exist_ok=True) + os.makedirs(extract_to, exist_ok=True) + + downloaded_path = snapshot_download( + repo_id=dataset_repo_id, + repo_type="dataset", + local_dir=local_dir, + resume_download=True + ) + + logger.info(f"Database files downloaded to {downloaded_path}") + + zip_path = os.path.join(downloaded_path, "vector_databases.zip") + if os.path.exists(zip_path): + with zipfile.ZipFile(zip_path, 'r') as zip_ref: + zip_ref.extractall(extract_to) + logger.info(f"Database files extracted to {extract_to}") + return extract_to + else: + raise FileNotFoundError(f"Database zip file not found at {zip_path}") + + +class Text2VecSQLGeneration_APIPipeline(): + def __init__(self, db_root_path=""): + self.logger = get_logger() + self.db_root_path = db_root_path + + if not db_root_path: + try: + self.db_root_path = download_and_extract_database(self.logger) + self.logger.info(f"Using automatically downloaded database at: {self.db_root_path}") + except Exception as e: + self.logger.error(f"Failed to auto-download database: {e}") + raise + else: + self.logger.info(f"Using manually specified database path: {self.db_root_path}") + + if not os.path.exists(self.db_root_path): + raise FileNotFoundError(f"Database path does not exist: {self.db_root_path}") + + self.storage = FileStorage( + first_entry_file_name="../example_data/Text2SQLPipeline/empty.jsonl", + cache_path="./cache", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=100 + ) + + # It is recommended to use better LLMs for the generation of Chain-of-Thought (CoT) reasoning process. + # cot_generation_api_llm_serving = APILLMServing_request( + # api_url="http://api.openai.com/v1/chat/completions", + # model_name="gpt-4o", # You can change to a more powerful model for CoT generation + # max_workers=100 + # ) + + embedding_serving = LocalEmbeddingServing( + model_name='sentence-transformers/all-MiniLM-L6-v2' + ) + + # SQLite and MySQL are currently supported + # db_type can be sqlite or mysql, which must match your database type + # If sqlite is selected, root_path must be provided, this path must exist and contain database files + # If mysql is selected, host, user, password must be provided, these credentials must be correct and have access permissions + # MySQL example: + # database_manager = DatabaseManager( + # db_type="mysql", + # config={ + # "host": "localhost", + # "user": "root", + # "password": "your_password", + # "database": "your_database_name" + # } + # ) + # SQLite example: + database_manager = DatabaseManager( + db_type="sqlite-vec", + config={ + "root_path": self.db_root_path, + "model_name": "all-MiniLM-L6-v2", + "model_path": "./hf_cache/all-MiniLM-L6-v2.e4ce9877.q8_0.gguf", + "enable_lembed": False + }, + embedding_serving=embedding_serving + ) + + self.sql_generator_step1 = SQLByColumnGenerator( + llm_serving=self.llm_serving, + database_manager=database_manager, + generate_num=2, + prompt_template=SelectVecSQLGeneratorPrompt() + ) + + self.sql_execution_filter_step2 = SQLExecutionFilter( + database_manager=database_manager, + ) + + self.text2sql_question_generator_step3 = Text2SQLQuestionGenerator( + llm_serving=self.llm_serving, + embedding_serving=embedding_serving, + database_manager=database_manager, + question_candidates_num=5, + prompt_template=Text2VecSQLQuestionGeneratorPrompt() + ) + + self.text2sql_prompt_generator_step4 = Text2SQLPromptGenerator( + database_manager=database_manager, + prompt_template=Text2VecSQLPromptGeneratorPrompt() + ) + + self.sql_component_classifier_step5 = SQLComponentClassifier( + difficulty_thresholds=[2, 4, 6], + difficulty_labels=['easy', 'medium', 'hard', 'extra'] + ) + + self.sql_execution_classifier_step6 = SQLExecutionClassifier( + llm_serving=self.llm_serving, + database_manager=database_manager, + num_generations=10, + difficulty_thresholds=[2, 5, 9], + difficulty_labels=['extra', 'hard', 'medium', 'easy'] + ) + + def forward(self): + + sql_key = "SQL" + db_id_key = "db_id" + question_key = "question" + + self.sql_generator_step1.run( + storage=self.storage.step(), + output_sql_key=sql_key, + output_db_id_key=db_id_key + ) + + self.sql_execution_filter_step2.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_db_id_key=db_id_key + ) + + self.text2sql_question_generator_step3.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_db_id_key=db_id_key, + output_question_key=question_key + ) + + self.text2sql_prompt_generator_step4.run( + storage=self.storage.step(), + input_question_key=question_key, + input_db_id_key=db_id_key, + output_prompt_key="prompt" + ) + + # self.sql_cot_generator_step5.run( + # storage=self.storage.step(), + # input_sql_key=sql_key, + # input_question_key=question_key, + # input_db_id_key=db_id_key, + # output_cot_key="cot_reasoning" + # ) + + self.sql_component_classifier_step5.run( + storage=self.storage.step(), + input_sql_key=sql_key, + output_difficulty_key="sql_component_difficulty" + ) + + self.sql_execution_classifier_step6.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_db_id_key=db_id_key, + input_prompt_key="prompt", + output_difficulty_key="sql_execution_difficulty" + ) + +if __name__ == "__main__": + # If you have your own database files, you can set the db_root_path to the path of your database files + # If not, please set the db_root_path "", and we will download the example database files automatically + db_root_path = "" + model = Text2VecSQLGeneration_APIPipeline(db_root_path) + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/text_conversation_synthesis_pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/text_conversation_synthesis_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..a823e9ac5e2ab89e24694fc2fa6f0807250e1485 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/text_conversation_synthesis_pipeline.py @@ -0,0 +1,33 @@ +from dataflow.operators.conversations import ConsistentChatGenerator +from dataflow.prompts.general_text import ConsistentChatPrompt +from dataflow.utils.storage import FileStorage +from dataflow.serving import APILLMServing_request + +class TextConversationSynthesis_APIPipeline(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/GeneralTextPipeline/empty.jsonl", + cache_path="./cache", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=100 + ) + self.model_cache_dir = './dataflow_cache' + self.processor = ConsistentChatGenerator(llm_serving=self.llm_serving, num_dialogs_per_intent=5, prompt_template=ConsistentChatPrompt()) + + def forward(self): + self.processor.run( + storage=self.storage.step() + ) + +if __name__ == "__main__": + # This is a test entry point for the TextPipeline + # It will run the forward method of the TextPipeline class + # to process the data and generate the output. + print("Running TextPipeline...") + model = TextConversationSynthesis_APIPipeline() + model.forward() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/text_sft_synthesis_pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/text_sft_synthesis_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..417da44e4a9a0cc2fffaa85109131373e7424269 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/api_pipelines/text_sft_synthesis_pipeline.py @@ -0,0 +1,46 @@ + +from dataflow.operators.text_sft import AlpagasusFilter +from dataflow.operators.text_sft import CondorGenerator +from dataflow.operators.text_sft import CondorRefiner +from dataflow.utils.storage import FileStorage +from dataflow.serving import APILLMServing_request +from dataflow.prompts.general_text import CondorQuestionPrompt, CondorRefinePrompt + +class TextSFTSynthesis_APIPipeline(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/GeneralTextPipeline/empty.jsonl", + cache_path="./cache", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + self.model_cache_dir = './dataflow_cache' + self.num_generated_samples = 3 + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=100 + ) + self.generator = CondorGenerator(llm_serving=self.llm_serving, num_samples=self.num_generated_samples, prompt_template=CondorQuestionPrompt()) + self.refiner = CondorRefiner(llm_serving=self.llm_serving, prompt_template=CondorRefinePrompt()) + self.alpagasus_filter = AlpagasusFilter(min_score=3,max_score=5,llm_serving=self.llm_serving) + + def forward(self): + self.generator.run( + storage=self.storage.step() + ) + self.refiner.run( + storage=self.storage.step(), + input_instruction_key='instruction', + input_output_key='output' + ) + self.alpagasus_filter.run( + storage=self.storage.step(), + input_instruction_key='instruction', + input_input_key="input", + input_output_key='output' + ) + +if __name__ == "__main__": + model = TextSFTSynthesis_APIPipeline() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/core_text/__pycache__/prompted_eval.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/core_text/__pycache__/prompted_eval.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5119b4f950119fe774d33b54e7e1c3495ed24d21 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/core_text/__pycache__/prompted_eval.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/core_text/__pycache__/prompted_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/core_text/__pycache__/prompted_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb60eadffbe69d4a0be189eae545385dd0570ce7 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/core_text/__pycache__/prompted_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/core_text/__pycache__/prompted_refine.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/core_text/__pycache__/prompted_refine.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03ed574a10f77030264bba6132141d200d12cbf9 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/core_text/__pycache__/prompted_refine.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/core_text/prompted_eval.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/core_text/prompted_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..6cf3342534bb7c995c531f7487978f44f47d8dba --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/core_text/prompted_eval.py @@ -0,0 +1,35 @@ +from dataflow.operators.core_text import PromptedEvaluator +from dataflow.serving import APILLMServing_request +from dataflow.utils.storage import FileStorage + +class GPT_evaluator(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/core_text_data/eval_data.json", + cache_path="./cache_1", + file_name_prefix="math_QA", + cache_type="json", + ) + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=10 + ) + self.prompt_evaluator = PromptedEvaluator( + llm_serving = self.llm_serving, + ) + + def forward(self): + # Initial filters + self.prompt_evaluator.run( + storage = self.storage.step(), + input_key = "conversations", + output_key = "eval_dim_1", + ) + + +if __name__ == "__main__": + # This is the entry point for the pipeline + + model = GPT_evaluator() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/core_text/prompted_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/core_text/prompted_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..27dce6454fd6ba9d64bde3c98fb309c632f1482b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/core_text/prompted_filter.py @@ -0,0 +1,35 @@ +from dataflow.operators.core_text import PromptedFilter +from dataflow.serving import APILLMServing_request +from dataflow.utils.storage import FileStorage + +class GPT_evaluator(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/core_text_data/eval_data.json", + cache_path="./cache_1", + file_name_prefix="math_QA", + cache_type="json", + ) + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=10 + ) + self.prompt_evaluator = PromptedFilter( + llm_serving = self.llm_serving, + ) + + def forward(self): + # Initial filters + self.prompt_evaluator.run( + storage = self.storage.step(), + input_key = "conversations", + output_key = "eval_dim_1", + ) + + +if __name__ == "__main__": + # This is the entry point for the pipeline + + model = GPT_evaluator() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/core_text/prompted_refine.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/core_text/prompted_refine.py new file mode 100644 index 0000000000000000000000000000000000000000..1d3db52c34facd37d0dc75b7945353bc4883260c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/core_text/prompted_refine.py @@ -0,0 +1,36 @@ +from dataflow.operators.core_text import PromptedRefiner +from dataflow.serving import APILLMServing_request +from dataflow.utils.storage import FileStorage + +class GPT_generator(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/GeneralTextPipeline/abbreviation.jsonl", + cache_path="./cache", + file_name_prefix="math_QA", + cache_type="jsonl", + ) + self.model_cache_dir = './dataflow_cache' + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=10 + ) + self.prompt_refiner = PromptedRefiner( + llm_serving = self.llm_serving, + system_prompt = "Please rewrite this sentence into a better one.", # System prompt for math problem solving + ) + + def forward(self): + # Initial filters + self.prompt_refiner.run( + storage = self.storage.step(), + input_key = "raw_content", + ) + + +if __name__ == "__main__": + # This is the entry point for the pipeline + + model = GPT_generator() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/__pycache__/code_pt_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/__pycache__/code_pt_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e7e127e872df840ac1af1d4288f13cba53aac7a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/__pycache__/code_pt_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/__pycache__/kbcleaning_pipeline_url.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/__pycache__/kbcleaning_pipeline_url.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f11bde50344ba336b526f0b67d7efd2d852a4978 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/__pycache__/kbcleaning_pipeline_url.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/__pycache__/reasoning_pipeline.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/__pycache__/reasoning_pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e5b7fcc8ab874b0f865d533b9a3446e5478e8ca Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/__pycache__/reasoning_pipeline.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/__pycache__/text2sql_pipeline.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/__pycache__/text2sql_pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f460e4de5eae3f34a3e1992815e4113b2c0557d9 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/__pycache__/text2sql_pipeline.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/__pycache__/text_pt_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/__pycache__/text_pt_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..236431a4b51511641aa45136f41c7c7864ebda28 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/__pycache__/text_pt_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/__pycache__/text_sft_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/__pycache__/text_sft_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bbf25e484c2c42ecb78c94d58942a20e1858e9db Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/__pycache__/text_sft_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/code_pt_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/code_pt_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..d11db5367f9634f7d5b9ab64fe3e788691dbfd3c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/code_pt_filter.py @@ -0,0 +1,111 @@ +from dataflow.operators.code import ( + CodeAutoGeneratedFilter, + CodeLengthSampleFilter, + CodeTextCompositionFilter, + CodeEncodedDataFilter, + CodeDocumentQualityFilter, + CodeFileTypeContentFilter, + CodeGenericScoreFilter, +) +from dataflow.utils.storage import FileStorage + +class PTCodeFilter_CPUPipeline(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/CodePipeline/code_input.jsonl", + cache_path="./cache", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + self.autogen_filter_step1 = CodeAutoGeneratedFilter( + min_score=1.0, + max_score=1.0 + ) + + self.length_filter_step2 = CodeLengthSampleFilter( + min_score=1.0, + max_score=1.0 + ) + + self.text_composition_filter_step3 = CodeTextCompositionFilter( + min_score=1.0, + max_score=1.0 + ) + + self.encoded_data_filter_step4 = CodeEncodedDataFilter( + min_score=1.0, + max_score=1.0 + ) + + self.doc_quality_filter_step5 = CodeDocumentQualityFilter( + min_score=1.0, + max_score=1.0, + thresholds={ + 'min_num_chars': 100, + 'max_num_chars': 100000, + 'min_num_words': 10, + 'max_num_words': 50000, + 'max_frac_duplicate_lines': 0.3, + 'max_frac_duplicate_2gram': 0.3, + 'max_frac_duplicate_3gram': 0.3, + 'max_frac_duplicate_4gram': 0.3, + 'max_frac_duplicate_5gram': 0.3, + 'max_frac_curly_bracket': 0.1, + 'max_frac_all_caps_words': 0.3, + 'min_entropy_unigram': 2.0, + } + ) + + self.file_type_filter_step6 = CodeFileTypeContentFilter() + + self.score_filter_step7 = CodeGenericScoreFilter() + + def forward(self): + self.autogen_filter_step1.run( + storage=self.storage.step(), + input_key="lines", + output_key="autogen_filter_label" + ) + + self.length_filter_step2.run( + storage=self.storage.step(), + input_key="lines", + output_key="length_filter_label" + ) + + self.text_composition_filter_step3.run( + storage=self.storage.step(), + input_key="text", + output_key="text_composition_filter_label" + ) + + self.encoded_data_filter_step4.run( + storage=self.storage.step(), + input_key="text", + output_key="encoded_data_filter_label" + ) + + self.doc_quality_filter_step5.run( + storage=self.storage.step(), + input_key="text", + output_key="doc_quality_filter_label" + ) + + self.file_type_filter_step6.run( + storage=self.storage.step(), + input_key="dataframe", + output_key="file_type_filter_label" + ) + + # self.score_filter_step7.run( + # storage=self.storage.step(), + # input_key="quality_score", + # output_key="score_filter_label", + # score_threshold=8, + # filter_method="greater_equal" + # ) + +if __name__ == "__main__": + model = PTCodeFilter_CPUPipeline() + model.forward() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/kbcleaning_pipeline_url.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/kbcleaning_pipeline_url.py new file mode 100644 index 0000000000000000000000000000000000000000..b45f9affca685407fb59603b89e18df8b758a9bc --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/kbcleaning_pipeline_url.py @@ -0,0 +1,43 @@ +from dataflow.operators.knowledge_cleaning import ( + KBCChunkGenerator, + FileOrURLToMarkdownConverterAPI +) +from dataflow.utils.storage import FileStorage +class KBCleaning_CPUPipeline(): + def __init__(self): + + self.storage = FileStorage( + first_entry_file_name="../example_data/KBCleaningPipeline/kbc_test_1.jsonl", + cache_path="./.cache/cpu", + file_name_prefix="url_cleaning_step", + cache_type="json", + ) + + self.knowledge_cleaning_step1 = FileOrURLToMarkdownConverterAPI( + intermediate_dir="../example_data/KBCleaningPipeline/raw/", + mineru_backend="pipeline", + ) + + self.knowledge_cleaning_step2 = KBCChunkGenerator( + split_method="token", + chunk_size=512, + tokenizer_name="Qwen/Qwen2.5-7B-Instruct", + ) + + def forward(self): + self.knowledge_cleaning_step1.run( + storage=self.storage.step(), + # input_file=, + # output_key=, + ) + + self.knowledge_cleaning_step2.run( + storage=self.storage.step(), + # input_file=, + # output_key=, + ) + +if __name__ == "__main__": + model = KBCleaning_CPUPipeline() + model.forward() + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/reasoning_pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/reasoning_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..8b1106d575f063e26b3dd8f07a8703e1888e57af --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/reasoning_pipeline.py @@ -0,0 +1,48 @@ +from dataflow.operators.reasoning import ( + ReasoningAnswerFormatterFilter, + ReasoningAnswerGroundTruthFilter, + ReasoningAnswerNgramFilter, +) +from dataflow.utils.storage import FileStorage + +class Reasoning_CPUPipeline(): + def __init__(self): + + self.storage = FileStorage( + first_entry_file_name="../example_data/ReasoningPipeline/pipeline_math_short.json", + cache_path="./cache_local", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + self.answer_format_filter_step1 = ReasoningAnswerFormatterFilter() + + self.answer_groundtruth_filter_step2 = ReasoningAnswerGroundTruthFilter() + + self.answer_ngram_filter_step3 = ReasoningAnswerNgramFilter( + min_score = 0.1, + max_score = 1.0, + ngrams = 5 + ) + + def forward(self): + self.answer_format_filter_step1.run( + storage = self.storage.step(), + input_key = "output", + ) + + self.answer_groundtruth_filter_step2.run( + storage = self.storage.step(), + input_test_answer_key = "output", + input_gt_answer_key = "golden_answer" + ) + + self.answer_ngram_filter_step3.run( + storage = self.storage.step(), + input_question_key = "instruction", + input_answer_key = "output" + ) + +if __name__ == "__main__": + model = Reasoning_CPUPipeline() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/text2sql_pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/text2sql_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..2e6a8fd39f8c0ab49386b89c46b063f99731fe09 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/text2sql_pipeline.py @@ -0,0 +1,151 @@ +import os +import zipfile +from dataflow import get_logger +from pathlib import Path +from huggingface_hub import snapshot_download + +from dataflow.operators.text2sql import ( + Text2SQLPromptGenerator +) +from dataflow.operators.text2sql import ( + SQLExecutionFilter +) +from dataflow.operators.text2sql import ( + SQLComponentClassifier +) +from dataflow.prompts.text2sql import ( + Text2SQLPromptGeneratorPrompt +) +from dataflow.utils.storage import FileStorage +from dataflow.utils.text2sql.database_manager import DatabaseManager + + +def download_and_extract_database(logger): + dataset_repo_id = "Open-Dataflow/dataflow-Text2SQL-database-example" + local_dir = "./hf_cache" + extract_to = "./downloaded_databases" + + logger.info(f"Downloading and extracting database from {dataset_repo_id}...") + os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com' + + os.makedirs(local_dir, exist_ok=True) + os.makedirs(extract_to, exist_ok=True) + + downloaded_path = snapshot_download( + repo_id=dataset_repo_id, + repo_type="dataset", + local_dir=local_dir, + resume_download=True + ) + + logger.info(f"Files downloaded to: {downloaded_path}") + + zip_path = os.path.join(downloaded_path, "databases.zip") + if os.path.exists(zip_path): + with zipfile.ZipFile(zip_path, 'r') as zip_ref: + zip_ref.extractall(extract_to) + logger.info(f"Database files extracted to {extract_to}") + return extract_to + else: + raise FileNotFoundError(f"Database zip file not found at {zip_path}") + + +class Text2SQL_CPUPipeline(): + def __init__(self, db_root_path=""): + self.logger = get_logger() + self.db_root_path = db_root_path + + if not db_root_path: + try: + self.db_root_path = download_and_extract_database(self.logger) + self.logger.info(f"Using automatically downloaded database at: {self.db_root_path}") + except Exception as e: + self.logger.error(f"Failed to auto-download database: {e}") + raise + else: + self.logger.info(f"Using manually specified database path: {self.db_root_path}") + + if not os.path.exists(self.db_root_path): + raise FileNotFoundError(f"Database path does not exist: {self.db_root_path}") + + self.storage = FileStorage( + first_entry_file_name="../example_data/Text2SQLPipeline/pipeline_refine.jsonl", + cache_path="./cache", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + # SQLite and MySQL are currently supported + # db_type can be sqlite or mysql, which must match your database type + # If sqlite is selected, root_path must be provided, this path must exist and contain database files + # If mysql is selected, host, user, password must be provided, these credentials must be correct and have access permissions + # MySQL example: + # database_manager = DatabaseManager( + # db_type="mysql", + # config={ + # "host": "localhost", + # "user": "root", + # "password": "your_password", + # "database": "your_database_name" + # } + # ) + # SQLite example: + database_manager = DatabaseManager( + db_type="sqlite", + config={ + "root_path": self.db_root_path + }, + logger=None, + sql_execution_timeout = 2, + max_connections_per_db=100, + max_workers=100 + ) + + self.sql_execution_filter_step1 = SQLExecutionFilter( + database_manager=database_manager, + ) + + self.text2sql_prompt_generator_step2 = Text2SQLPromptGenerator( + database_manager=database_manager, + prompt_template=Text2SQLPromptGeneratorPrompt() + ) + + self.sql_component_classifier_step3 = SQLComponentClassifier( + difficulty_thresholds=[2, 4, 6], + difficulty_labels=['easy', 'medium', 'hard', 'extra'] + ) + + + def forward(self): + + sql_key = "SQL" + db_id_key = "db_id" + question_key = "question" + + self.sql_execution_filter_step1.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_db_id_key=db_id_key + ) + + self.text2sql_prompt_generator_step2.run( + storage=self.storage.step(), + input_question_key=question_key, + input_db_id_key=db_id_key, + output_prompt_key="prompt" + ) + + self.sql_component_classifier_step3.run( + storage=self.storage.step(), + input_sql_key=sql_key, + output_difficulty_key="sql_component_difficulty" + ) + +if __name__ == "__main__": + # If you have your own database files, you can set the db_root_path to the path of your database files + # If not, please set the db_root_path "", and we will download the example database files automatically + db_root_path = "" + + model = Text2SQL_CPUPipeline(db_root_path=db_root_path) + model.forward() + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/text_pt_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/text_pt_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..4a8b4d7b340226b6735fa250c285885a2aa54597 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/text_pt_filter.py @@ -0,0 +1,160 @@ +from dataflow.operators.general_text import ( + WordNumberFilter, + BlocklistFilter, + MinHashDeduplicateFilter, + ColonEndFilter, + SentenceNumberFilter, + LineEndWithEllipsisFilter, + ContentNullFilter, + MeanWordLengthFilter, + SymbolWordRatioFilter, + HtmlEntityFilter, + NoPuncFilter, + SpecialCharacterFilter, + WatermarkFilter, + CurlyBracketFilter, + CapitalWordsFilter, + LoremIpsumFilter, + UniqueWordsFilter, + CharNumberFilter, + LineStartWithBulletpointFilter, + LineWithJavascriptFilter, + HtmlUrlRemoverRefiner, + RemoveEmojiRefiner, + RemoveExtraSpacesRefiner +) +from dataflow.operators.text_pt import ( + MetaSampleEvaluator, +) + +from dataflow.utils.storage import FileStorage + +class PTTextFilter_CPUPipeline(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/GeneralTextPipeline/pt_input.jsonl", + cache_path="./cache", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + self.remove_extra_spaces_refiner = RemoveExtraSpacesRefiner() + self.remove_emoji_refiner = RemoveEmojiRefiner() + self.html_remove_refiner = HtmlUrlRemoverRefiner() + self.minhash_deduplicator = MinHashDeduplicateFilter(num_perm=128, threshold=0.9, use_n_gram=True, ngram=5) + self.blocklist_filter = BlocklistFilter() + self.word_number_filter = WordNumberFilter(min_words=20, max_words=100000) + self.colon_end_filter = ColonEndFilter() + self.sentence_number_filter = SentenceNumberFilter(min_sentences=3, max_sentences=7500) + self.line_end_with_ellipsis_filter = LineEndWithEllipsisFilter(threshold=0.3) + self.content_null_filter = ContentNullFilter() + self.mean_word_length_filter = MeanWordLengthFilter(min_length=3, max_length=10) + self.symbol_word_ratio_filter = SymbolWordRatioFilter(threshold=0.4) + self.html_entity_filter = HtmlEntityFilter() + self.no_punc_filter = NoPuncFilter(threshold=112) + self.special_character_filter = SpecialCharacterFilter() + self.watermark_filter = WatermarkFilter(watermarks=['Copyright', 'Watermark', 'Confidential']) + self.curly_bracket_filter = CurlyBracketFilter(threshold=0.025) + self.capital_words_filter = CapitalWordsFilter(threshold=0.2, use_tokenizer=False) + self.lorem_ipsum_filter = LoremIpsumFilter(threshold=3e-8) + self.unique_words_filter = UniqueWordsFilter(threshold=0.1) + self.char_number_filter = CharNumberFilter(threshold=100) + self.line_start_with_bulletpoint_filter = LineStartWithBulletpointFilter(threshold=0.9) + self.line_with_javascript_filter = LineWithJavascriptFilter(threshold=3) + + def forward(self): + self.remove_emoji_refiner.run( + storage=self.storage.step(), + input_key="raw_content" + ) + self.html_remove_refiner.run( + storage=self.storage.step(), + input_key="raw_content" + ) + self.remove_extra_spaces_refiner.run( + storage=self.storage.step(), + input_key="raw_content" + ) + self.minhash_deduplicator.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.blocklist_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.word_number_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.colon_end_filter.run( + storage = self.storage.step(), + input_key = 'raw_content' + ) + self.sentence_number_filter.run( + storage = self.storage.step(), + input_key = 'raw_content' + ) + self.line_end_with_ellipsis_filter.run( + storage = self.storage.step(), + input_key = 'raw_content' + ) + self.content_null_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.mean_word_length_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.symbol_word_ratio_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.html_entity_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.no_punc_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.special_character_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.watermark_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.curly_bracket_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.capital_words_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.lorem_ipsum_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.unique_words_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.char_number_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.line_start_with_bulletpoint_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.line_with_javascript_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) +if __name__ == "__main__": + # This is the entry point for the pipeline + model = PTTextFilter_CPUPipeline() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/text_sft_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/text_sft_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..da23e5adc9c959f9b536224ca196b54a1b26ae2e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/cpu_pipelines/text_sft_filter.py @@ -0,0 +1,32 @@ +from dataflow.operators.general_text import WordNumberFilter +from dataflow.utils.storage import FileStorage + + +class SFTTextFilter_CPUPipeline(): + + def __init__(self): + + self.storage = FileStorage( + first_entry_file_name="../example_data/GeneralTextPipeline/sft_input.jsonl", + cache_path="./cache", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + self.model_cache_dir = './dataflow_cache' + self.word_number_filter_step1 = WordNumberFilter( + min_words=20, + max_words=1000 + ) + + def forward(self): + + self.word_number_filter_step1.run( + storage=self.storage.step(), + input_key="output", + ) + +if __name__ == "__main__": + # This is the entry point for the pipeline + pipeline = SFTTextFilter_CPUPipeline() + pipeline.forward() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/core_text_bencheval_match_pipeline.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/core_text_bencheval_match_pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5687fa48784abe9e98d2c0d62992fd4490da3a6 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/core_text_bencheval_match_pipeline.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/reasoning_math_pipeline.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/reasoning_math_pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4443a4c48e44540dfdefef8035d06f89499ca9d9 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/reasoning_math_pipeline.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/speechtranscription_pipeline.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/speechtranscription_pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b0f30cdce49669b86ddf0c5be2ab19f31473116 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/speechtranscription_pipeline.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/text2sql_pipeline_gen.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/text2sql_pipeline_gen.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f889c537e24370f12ebec3907335eacaca70ef09 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/text2sql_pipeline_gen.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/text2sql_pipeline_refine.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/text2sql_pipeline_refine.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b7a99027680c4860ef9b00d77b2989e86fcbd47 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/text2sql_pipeline_refine.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/text_pt_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/text_pt_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e419bdabdef7bdd6b1d93867b32c5b6d92bfd1b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/text_pt_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/text_pt_synthetic.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/text_pt_synthetic.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c360dd454c8019719a772de0e324c8933e26af65 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/text_pt_synthetic.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/text_sft_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/text_sft_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a245412a3e3a1286f8dc135afd94c2acbe6e1ce Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/text_sft_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/text_sft_synthetic.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/text_sft_synthetic.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a29d8076fae2a8a8b653e5b087a65809a68621e Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/__pycache__/text_sft_synthetic.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/__pycache__/unified_bench_eval_type1.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/__pycache__/unified_bench_eval_type1.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ab35e183774f97cd397a5c39b9d7a1b682fcc81 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/__pycache__/unified_bench_eval_type1.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/__pycache__/unified_bench_eval_type2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/__pycache__/unified_bench_eval_type2.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb8c1eb5e5cbfb55e40272b1549c5900073768a6 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/__pycache__/unified_bench_eval_type2.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/__pycache__/unified_bench_eval_type3.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/__pycache__/unified_bench_eval_type3.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9017fd9022bd6e028d942d2dec8c1eee29367427 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/__pycache__/unified_bench_eval_type3.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/__pycache__/unified_bench_eval_type4.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/__pycache__/unified_bench_eval_type4.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..856bcbe0f3489ac541558e49cdd337e679b20b6c Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/__pycache__/unified_bench_eval_type4.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/__pycache__/unified_bench_eval_type5.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/__pycache__/unified_bench_eval_type5.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0dfdae49180f2d9bb523f744c1f1d180ac1f7a53 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/__pycache__/unified_bench_eval_type5.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/__pycache__/unified_bench_eval_type6.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/__pycache__/unified_bench_eval_type6.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf5b7bc4fa31e0aaac4b3d283433f4e2d2f3c8e8 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/__pycache__/unified_bench_eval_type6.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/__pycache__/unified_bench_eval_type_semantic.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/__pycache__/unified_bench_eval_type_semantic.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2084fbe187ee97b37fcef98bc876d2af4cfcb85d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/__pycache__/unified_bench_eval_type_semantic.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/unified_bench_eval_type1.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/unified_bench_eval_type1.py new file mode 100644 index 0000000000000000000000000000000000000000..37aa98f58484fa95f8fe3f9f6546687da6efaee3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/unified_bench_eval_type1.py @@ -0,0 +1,68 @@ +from dataflow.operators.core_text import BenchAnswerGenerator, UnifiedBenchDatasetEvaluator +from dataflow.utils.storage import FileStorage +from dataflow.serving import LocalModelLLMServing_vllm +from dataflow.core import LLMServingABC + +""" +all types: +"key1_text_score", +"key2_qa", +"key2_q_ma", +"key3_q_choices_a", +"key3_q_choices_as", +"key3_q_a_rejected", +""" + +EVAL_TYPE = "key1_text_score" + +class UnifiedBenchEvalPipeline(): + def __init__(self, llm_serving_generator: LLMServingABC = None, llm_serving_judger: LLMServingABC = None): + + self.storage = FileStorage( + first_entry_file_name="../example_data/core_text_data/unified_bench_eval_type1.jsonl", + cache_path="./cache_local", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + self.llm_serving_generator = LocalModelLLMServing_vllm( + hf_model_name_or_path="Qwen/Qwen2.5-7B-Instruct", # set to your own model path + vllm_tensor_parallel_size=1, + vllm_max_tokens=2048, + ) + + self.answer_generator_step1 = BenchAnswerGenerator( + llm_serving=self.llm_serving_generator, + eval_type=EVAL_TYPE, + prompt_template=None, + allow_overwrite=False, + force_generate=False, + ) + + self.evaluator_step2 = UnifiedBenchDatasetEvaluator( + eval_result_path="./cache_local/eval_result/eval_result.jsonl", + llm_serving=self.llm_serving_generator, + eval_type=EVAL_TYPE, + prompt_template=None, + use_semantic_judge=False, + metric_type=None, # use default metric + ) + + def forward(self): + self.answer_generator_step1.run( + storage=self.storage.step(), + input_text_key="text", + input_context_key=None, + output_key="generated_ans", + ) + + self.evaluator_step2.run( + storage=self.storage.step(), + input_text_key="text", + input_context_key=None, + input_pred_key="generated_ans", + ) + +if __name__ == "__main__": + pl = UnifiedBenchEvalPipeline() + pl.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/unified_bench_eval_type2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/unified_bench_eval_type2.py new file mode 100644 index 0000000000000000000000000000000000000000..605df4e069d40147f8dcf2d1bbe7329b1a1d57f3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/unified_bench_eval_type2.py @@ -0,0 +1,76 @@ +from dataflow.operators.core_text import BenchAnswerGenerator, UnifiedBenchDatasetEvaluator +from dataflow.prompts.core_text import FormatStrPrompt +from dataflow.core.prompt import DIYPromptABC +from dataflow.utils.storage import FileStorage +from dataflow.serving import LocalModelLLMServing_vllm +from dataflow.core import LLMServingABC + +""" +all types: +"key1_text_score", +"key2_qa", +"key2_q_ma", +"key3_q_choices_a", +"key3_q_choices_as", +"key3_q_a_rejected", +""" + +EVAL_TYPE = "key2_qa" + +class UnifiedBenchEvalPipeline(): + def __init__(self, llm_serving_generator: LLMServingABC = None, llm_serving_judger: LLMServingABC = None): + + self.storage = FileStorage( + first_entry_file_name="../example_data/core_text_data/unified_bench_eval_type2.jsonl", + cache_path="./cache_local", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + self.llm_serving_generator = LocalModelLLMServing_vllm( + hf_model_name_or_path="Qwen/Qwen2.5-7B-Instruct", # set to your own model path + vllm_tensor_parallel_size=1, + vllm_max_tokens=2048, + ) + + self.generation_prompt_template = FormatStrPrompt( + f_str_template="Question: {question}\nAnswer:", + ) + + self.answer_generator_step1 = BenchAnswerGenerator( + llm_serving=self.llm_serving_generator, + eval_type=EVAL_TYPE, + prompt_template=self.generation_prompt_template, + allow_overwrite=False, + force_generate=False, + ) + + self.evaluator_step2 = UnifiedBenchDatasetEvaluator( + eval_result_path="./cache_local/eval_result/eval_result.jsonl", + llm_serving=self.llm_serving_generator, + eval_type=EVAL_TYPE, + prompt_template=None, + use_semantic_judge=False, + metric_type=None, # use default metric + ) + + def forward(self): + self.answer_generator_step1.run( + storage=self.storage.step(), + input_question_key="question", + input_target_key="golden_label", + input_context_key=None, + output_key="generated_ans", + ) + + self.evaluator_step2.run( + storage=self.storage.step(), + input_question_key="question", + input_target_key="golden_label", + input_context_key=None, + input_pred_key="generated_ans", + ) + +if __name__ == "__main__": + pl = UnifiedBenchEvalPipeline() + pl.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/unified_bench_eval_type3.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/unified_bench_eval_type3.py new file mode 100644 index 0000000000000000000000000000000000000000..9be6f44140c08e7dbb5b33c743913a66509c402a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/unified_bench_eval_type3.py @@ -0,0 +1,79 @@ +from dataflow.pipeline.Pipeline import PipelineABC +from dataflow.operators.core_text import BenchAnswerGenerator, UnifiedBenchDatasetEvaluator +from dataflow.prompts.core_text import FormatStrPrompt +from dataflow.core.prompt import DIYPromptABC +from dataflow.utils.storage import FileStorage +from dataflow.serving import LocalModelLLMServing_vllm +from dataflow.core import LLMServingABC + +""" +all types: +"key1_text_score", +"key2_qa", +"key2_q_ma", +"key3_q_choices_a", +"key3_q_choices_as", +"key3_q_a_rejected", +""" + +EVAL_TYPE = "key2_q_ma" + +class UnifiedBenchEvalPipeline(PipelineABC): + def __init__(self, llm_serving_generator: LLMServingABC = None, llm_serving_judger: LLMServingABC = None): + super().__init__() + + self.storage = FileStorage( + first_entry_file_name="../example_data/core_text_data/unified_bench_eval_type3.jsonl", + cache_path="./cache_local", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + self.llm_serving_generator = LocalModelLLMServing_vllm( + hf_model_name_or_path="Qwen/Qwen2.5-7B-Instruct", # set to your own model path + vllm_tensor_parallel_size=1, + vllm_max_tokens=2048, + ) + + self.generation_prompt_template = FormatStrPrompt( + f_str_template="Question: {question}\nAnswer:", + ) + + self.answer_generator_step1 = BenchAnswerGenerator( + llm_serving=self.llm_serving_generator, + eval_type=EVAL_TYPE, + prompt_template=self.generation_prompt_template, + allow_overwrite=False, + force_generate=False, + ) + + self.evaluator_step2 = UnifiedBenchDatasetEvaluator( + eval_result_path="./cache_local/eval_result/eval_result.jsonl", + llm_serving=self.llm_serving_generator, + eval_type=EVAL_TYPE, + prompt_template=None, + use_semantic_judge=False, + metric_type=None, # use default metric + ) + + def forward(self): + self.answer_generator_step1.run( + storage=self.storage.step(), + input_context_key="context", + input_question_key="question", + input_targets_key="targets", + output_key="generated_ans", + ) + + self.evaluator_step2.run( + storage=self.storage.step(), + input_context_key="context", + input_question_key="question", + input_targets_key="targets", + input_pred_key="generated_ans", + ) + +if __name__ == "__main__": + pl = UnifiedBenchEvalPipeline() + pl.compile() + pl.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/unified_bench_eval_type4.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/unified_bench_eval_type4.py new file mode 100644 index 0000000000000000000000000000000000000000..3716cc574fb53c2f3402f5131902955260724e3b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/unified_bench_eval_type4.py @@ -0,0 +1,79 @@ +from dataflow.pipeline.Pipeline import PipelineABC +from dataflow.operators.core_text import BenchAnswerGenerator, UnifiedBenchDatasetEvaluator +from dataflow.prompts.core_text import FormatStrPrompt +from dataflow.utils.storage import FileStorage +from dataflow.serving import LocalModelLLMServing_vllm +from dataflow.core import LLMServingABC + +""" +all types: +"key1_text_score", +"key2_qa", +"key2_q_ma", +"key3_q_choices_a", +"key3_q_choices_as", +"key3_q_a_rejected", +""" + +EVAL_TYPE = "key3_q_choices_a" + +class UnifiedBenchEvalPipeline(PipelineABC): + def __init__(self, llm_serving_generator: LLMServingABC = None, llm_serving_judger: LLMServingABC = None): + super().__init__() + + self.storage = FileStorage( + first_entry_file_name="../example_data/core_text_data/unified_bench_eval_type4.jsonl", + cache_path="./cache_local", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + self.llm_serving_generator = LocalModelLLMServing_vllm( + hf_model_name_or_path="Qwen/Qwen2.5-7B-Instruct", # set to your own model path + vllm_tensor_parallel_size=1, + vllm_max_tokens=2048, + ) + + self.generation_prompt_template = FormatStrPrompt( + f_str_template="{context}Question:\n{question}\n\nChoices:\n{choices_text}\n\nAnswer:", + ) + + self.answer_generator_step1 = BenchAnswerGenerator( + llm_serving=self.llm_serving_generator, + eval_type=EVAL_TYPE, + prompt_template=self.generation_prompt_template, + allow_overwrite=False, + force_generate=False, + ) + + self.evaluator_step2 = UnifiedBenchDatasetEvaluator( + eval_result_path="./cache_local/eval_result/eval_result.jsonl", + llm_serving=self.llm_serving_generator, + eval_type=EVAL_TYPE, + prompt_template=None, + use_semantic_judge=False, + metric_type=None, # use default metric + ) + + def forward(self): + self.answer_generator_step1.run( + storage=self.storage.step(), + input_context_key="context", + input_question_key="question", + input_choices_key="choices", + output_key="generated_ans", + ) + + self.evaluator_step2.run( + storage=self.storage.step(), + input_context_key="context", + input_question_key="question", + input_choices_key="choices", + input_label_key="label", + input_pred_key="generated_ans", + ) + +if __name__ == "__main__": + pl = UnifiedBenchEvalPipeline() + pl.compile() + pl.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/unified_bench_eval_type5.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/unified_bench_eval_type5.py new file mode 100644 index 0000000000000000000000000000000000000000..56705cae64a5edf6351fb25fbedad76bf599f2f1 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/unified_bench_eval_type5.py @@ -0,0 +1,79 @@ +from dataflow.pipeline.Pipeline import PipelineABC +from dataflow.operators.core_text import BenchAnswerGenerator, UnifiedBenchDatasetEvaluator +from dataflow.prompts.core_text import FormatStrPrompt +from dataflow.utils.storage import FileStorage +from dataflow.serving import LocalModelLLMServing_vllm +from dataflow.core import LLMServingABC + +""" +all types: +"key1_text_score", +"key2_qa", +"key2_q_ma", +"key3_q_choices_a", +"key3_q_choices_as", +"key3_q_a_rejected", +""" + +EVAL_TYPE = "key3_q_choices_as" + +class UnifiedBenchEvalPipeline(PipelineABC): + def __init__(self, llm_serving_generator: LLMServingABC = None, llm_serving_judger: LLMServingABC = None): + super().__init__() + + self.storage = FileStorage( + first_entry_file_name="../example_data/core_text_data/unified_bench_eval_type5.jsonl", + cache_path="./cache_local", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + self.llm_serving_generator = LocalModelLLMServing_vllm( + hf_model_name_or_path="Qwen/Qwen2.5-7B-Instruct", # set to your own model path + vllm_tensor_parallel_size=1, + vllm_max_tokens=2048, + ) + + self.generation_prompt_template = FormatStrPrompt( + f_str_template="{context}Question:\n{question}\n\nChoices:\n{choices_text}\n\nAnswer:", + ) + + self.answer_generator_step1 = BenchAnswerGenerator( + llm_serving=self.llm_serving_generator, + eval_type=EVAL_TYPE, + prompt_template=self.generation_prompt_template, + allow_overwrite=False, + force_generate=False, + ) + + self.evaluator_step2 = UnifiedBenchDatasetEvaluator( + eval_result_path="./cache_local/eval_result/eval_result.jsonl", + llm_serving=self.llm_serving_generator, + eval_type=EVAL_TYPE, + prompt_template=None, + use_semantic_judge=False, + metric_type=None, # use default metric + ) + + def forward(self): + self.answer_generator_step1.run( + storage=self.storage.step(), + input_context_key="context", + input_question_key="question", + input_choices_key="choices", + output_key="generated_ans", + ) + + self.evaluator_step2.run( + storage=self.storage.step(), + input_context_key="context", + input_question_key="question", + input_choices_key="choices", + input_labels_key="labels", + input_pred_key="generated_ans", + ) + +if __name__ == "__main__": + pl = UnifiedBenchEvalPipeline() + pl.compile() + pl.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/unified_bench_eval_type6.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/unified_bench_eval_type6.py new file mode 100644 index 0000000000000000000000000000000000000000..041c6b1469f88feb16e0105d7b70ae11623851f4 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/unified_bench_eval_type6.py @@ -0,0 +1,78 @@ +from dataflow.pipeline.Pipeline import PipelineABC +from dataflow.operators.core_text import BenchAnswerGenerator, UnifiedBenchDatasetEvaluator +from dataflow.prompts.core_text import FormatStrPrompt +from dataflow.utils.storage import FileStorage +from dataflow.serving import LocalModelLLMServing_vllm +from dataflow.core import LLMServingABC + +""" +all types: +"key1_text_score", +"key2_qa", +"key2_q_ma", +"key3_q_choices_a", +"key3_q_choices_as", +"key3_q_a_rejected", +""" + +EVAL_TYPE = "key3_q_a_rejected" + +class UnifiedBenchEvalPipeline(PipelineABC): + def __init__(self, llm_serving_generator: LLMServingABC = None, llm_serving_judger: LLMServingABC = None): + super().__init__() + + self.storage = FileStorage( + first_entry_file_name="../example_data/core_text_data/unified_bench_eval_type6.jsonl", + cache_path="./cache_local", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + self.llm_serving_generator = LocalModelLLMServing_vllm( + hf_model_name_or_path="Qwen/Qwen2.5-7B-Instruct", # set to your own model path + vllm_tensor_parallel_size=1, + vllm_max_tokens=2048, + ) + + self.generation_prompt_template = FormatStrPrompt( + f_str_template="{context}Question:\n{question}\n\nAnswer:", + ) + + self.answer_generator_step1 = BenchAnswerGenerator( + llm_serving=self.llm_serving_generator, + eval_type=EVAL_TYPE, + prompt_template=self.generation_prompt_template, + allow_overwrite=False, + force_generate=False, + ) + + self.evaluator_step2 = UnifiedBenchDatasetEvaluator( + eval_result_path="./cache_local/eval_result/eval_result.jsonl", + llm_serving=self.llm_serving_generator, + eval_type=EVAL_TYPE, + prompt_template=None, + use_semantic_judge=False, + metric_type=None, # use default metric + ) + + def forward(self): + self.answer_generator_step1.run( + storage=self.storage.step(), + input_context_key="context", + input_question_key="question", + output_key="generated_ans", + ) + + self.evaluator_step2.run( + storage=self.storage.step(), + input_context_key="context", + input_question_key="question", + input_better_key="better", + input_rejected_key="rejected", + input_pred_key="generated_ans", + ) + +if __name__ == "__main__": + pl = UnifiedBenchEvalPipeline() + pl.compile() + pl.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/unified_bench_eval_type_semantic.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/unified_bench_eval_type_semantic.py new file mode 100644 index 0000000000000000000000000000000000000000..fae6fb8126bc99bcbae606648786e08a5280c8f7 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/benchmark_eval/unified_bench_eval_type_semantic.py @@ -0,0 +1,83 @@ +from dataflow.operators.core_text import BenchAnswerGenerator, UnifiedBenchDatasetEvaluator +from dataflow.prompts.core_text import FormatStrPrompt +from dataflow.core.prompt import DIYPromptABC +from dataflow.utils.storage import FileStorage +from dataflow.serving import LocalModelLLMServing_vllm, APILLMServing_request +from dataflow.core import LLMServingABC + +""" +all types: +"key1_text_score", +"key2_qa", +"key2_q_ma", +"key3_q_choices_a", +"key3_q_choices_as", +"key3_q_a_rejected", +""" + +EVAL_TYPE = "key2_qa" + +class UnifiedBenchEvalPipeline(): + def __init__(self, llm_serving_generator: LLMServingABC = None, llm_serving_judger: LLMServingABC = None): + + self.storage = FileStorage( + first_entry_file_name="../example_data/core_text_data/unified_bench_eval_type2.jsonl", + cache_path="./cache_local", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + self.llm_serving_generator = LocalModelLLMServing_vllm( + hf_model_name_or_path="/mnt/DataFlow/models/Qwen2.5-7B-Instruct", # set to your own model path + vllm_tensor_parallel_size=1, + vllm_max_tokens=2048, + ) + + # use API server as LLM serving + self.llm_serving_judger = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=5 + ) + + self.generation_prompt_template = FormatStrPrompt( + f_str_template="Question: {question}\nAnswer:", + ) + + self.answer_generator_step1 = BenchAnswerGenerator( + llm_serving=self.llm_serving_generator, + eval_type=EVAL_TYPE, + prompt_template=self.generation_prompt_template, + allow_overwrite=False, + force_generate=False, + ) + + self.evaluator_step2 = UnifiedBenchDatasetEvaluator( + eval_result_path="./cache_local/eval_result/eval_result.jsonl", + llm_serving=self.llm_serving_judger, + eval_type=EVAL_TYPE, + prompt_template=None, + use_semantic_judge=True, + metric_type=None, # use default metric + ) + + def forward(self): + self.answer_generator_step1.run( + storage=self.storage.step(), + input_question_key="question", + input_target_key="golden_label", + input_context_key=None, + output_key="generated_ans", + ) + + self.evaluator_step2.run( + storage=self.storage.step(), + input_question_key="question", + input_target_key="golden_label", + input_context_key=None, + input_pred_key="generated_ans", + ) + +if __name__ == "__main__": + pl = UnifiedBenchEvalPipeline() + pl.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/core_text_bencheval_match_pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/core_text_bencheval_match_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..12c87aa6b56f8f2c4e044458d74b0c3f0a12c46e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/core_text_bencheval_match_pipeline.py @@ -0,0 +1,54 @@ +from dataflow.operators.core_text import BenchDatasetEvaluator +from dataflow.operators.reasoning import ReasoningAnswerGenerator +from dataflow.utils.storage import FileStorage +from dataflow.serving import LocalModelLLMServing_vllm +from dataflow.core import LLMServingABC +from dataflow.prompts.reasoning.diy import ( + DiyAnswerGeneratorPrompt, +) + +DIY_PROMPT_ANSWER = """Please output the answer.""" + +class BenchEvalPipeline(): + def __init__(self, llm_serving_generator: LLMServingABC = None, llm_serving_judger: LLMServingABC = None): + + self.storage = FileStorage( + first_entry_file_name="../example_data/core_text_data/bench_eval_data.jsonl", + cache_path="./cache_local", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + self.llm_serving_generator = LocalModelLLMServing_vllm( + hf_model_name_or_path="Qwen/Qwen2.5-7B-Instruct", # set to your own model path + vllm_tensor_parallel_size=1, + vllm_max_tokens=2048, + ) + + self.answer_generator_step1 = ReasoningAnswerGenerator( + llm_serving=self.llm_serving_generator, + prompt_template=DiyAnswerGeneratorPrompt(DIY_PROMPT_ANSWER) + ) + + self.evaluator_step2 = BenchDatasetEvaluator( + eval_result_path="./cache_local/eval_result/eval_result.jsonl", + compare_method="match", # or semantic + prompt_template = None # you can diy your judger prompt in dataflow.prompts.reasoning.general.AnswerJudgePrompt + ) + + def forward(self): + self.answer_generator_step1.run( + storage = self.storage.step(), + input_key = "instruction", + output_key = "generated_cot" + ) + self.evaluator_step2.run( + storage = self.storage.step(), + input_test_answer_key="generated_cot", + input_gt_answer_key="golden_answer", + input_question_key="instruction", + ) + +if __name__ == "__main__": + pl = BenchEvalPipeline() + pl.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/kbcleaning/__pycache__/kbcleaning_pipeline_batch_sglang.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/kbcleaning/__pycache__/kbcleaning_pipeline_batch_sglang.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af0cb00c8f210adda778545a6bf2b37ab84de5bf Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/kbcleaning/__pycache__/kbcleaning_pipeline_batch_sglang.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/kbcleaning/__pycache__/kbcleaning_pipeline_batch_vllm.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/kbcleaning/__pycache__/kbcleaning_pipeline_batch_vllm.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd6ad2e22f5e8ff52ceba8920aac34d8c9d75521 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/kbcleaning/__pycache__/kbcleaning_pipeline_batch_vllm.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/kbcleaning/__pycache__/kbcleaning_pipeline_sglang.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/kbcleaning/__pycache__/kbcleaning_pipeline_sglang.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aaab67eed332380ba8f598ec44a0a525d7e44965 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/kbcleaning/__pycache__/kbcleaning_pipeline_sglang.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/kbcleaning/__pycache__/kbcleaning_pipeline_vllm.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/kbcleaning/__pycache__/kbcleaning_pipeline_vllm.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..354a9eccbf1fa001a08c4167223a666b6442903c Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/kbcleaning/__pycache__/kbcleaning_pipeline_vllm.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/kbcleaning/kbcleaning_pipeline_batch_sglang.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/kbcleaning/kbcleaning_pipeline_batch_sglang.py new file mode 100644 index 0000000000000000000000000000000000000000..affdd6fcbc7f80e2a4a2fce5968330add9d9ace0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/kbcleaning/kbcleaning_pipeline_batch_sglang.py @@ -0,0 +1,72 @@ +from dataflow.operators.knowledge_cleaning import ( + KBCChunkGeneratorBatch, + FileOrURLToMarkdownConverterFlash, + KBCTextCleanerBatch, + KBCMultiHopQAGeneratorBatch, +) +from dataflow.utils.storage import FileStorage +from dataflow.serving import LocalModelLLMServing_vllm, LocalModelLLMServing_sglang + + +class KBCleaning_batchSglang_GPUPipeline(): + def __init__(self): + + self.storage = FileStorage( + first_entry_file_name="../../example_data/KBCleaningPipeline/kbc_test.jsonl", + cache_path="./.cache/gpu", + file_name_prefix="batch_cleaning_step", + cache_type="json", + ) + + self.knowledge_cleaning_step1 = FileOrURLToMarkdownConverterFlash( + intermediate_dir="../example_data/KBCleaningPipeline/flash/", + mineru_model_path="/MinerU2.5-2509-1.2B", # !!! place your local model path here !!! + # https://huggingface.co/opendatalab/MinerU2.5-2509-1.2B. + batch_size=4, # batchsize per vllm worker + replicas=1, # num of vllm workers + num_gpus_per_replica=0.5, # for ray to schedule vllm workers to GPU, can be float, e.g. 0.5 means each worker uses half GPU, 1 means each worker uses whole GPU + engine_gpu_util_rate_to_ray_cap=0.9 # actuall GPU utilization for each worker; acturall memory per worker= num_gpus_per_replica * engine_gpu_util_rate_to_ray_cap; this is to avoid OOM, you can set it to 0.9 or 0.8 to leave some buffer for other processes on + ) + self.knowledge_cleaning_step2 = KBCChunkGeneratorBatch( + split_method="token", + chunk_size=512, + tokenizer_name="Qwen/Qwen2.5-7B-Instruct", + ) + + def forward(self): + self.knowledge_cleaning_step1.run( + storage=self.storage.step(), + ) + + self.knowledge_cleaning_step2.run( + storage=self.storage.step(), + ) + + self.llm_serving = LocalModelLLMServing_sglang( + hf_model_name_or_path="Qwen/Qwen2.5-7B-Instruct", + sgl_dp_size=1, # data parallel size + sgl_tp_size=1, # tensor parallel size + sgl_max_new_tokens=2048, + ) + + self.knowledge_cleaning_step3 = KBCTextCleanerBatch( + llm_serving=self.llm_serving, + lang="en" + ) + + self.knowledge_cleaning_step4 = KBCMultiHopQAGeneratorBatch( + llm_serving=self.llm_serving, + lang="en" + ) + + self.knowledge_cleaning_step3.run( + storage=self.storage.step(), + ) + self.knowledge_cleaning_step4.run( + storage=self.storage.step(), + ) + + +if __name__ == "__main__": + model = KBCleaning_batchSglang_GPUPipeline() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/kbcleaning/kbcleaning_pipeline_batch_vllm.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/kbcleaning/kbcleaning_pipeline_batch_vllm.py new file mode 100644 index 0000000000000000000000000000000000000000..a621f8f2f1ae434b255972047ef68b7122b70c6a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/kbcleaning/kbcleaning_pipeline_batch_vllm.py @@ -0,0 +1,74 @@ +from dataflow.operators.knowledge_cleaning import ( + KBCChunkGeneratorBatch, + FileOrURLToMarkdownConverterFlash, + KBCTextCleanerBatch, + KBCMultiHopQAGeneratorBatch, +) +from dataflow.utils.storage import FileStorage +from dataflow.serving import LocalModelLLMServing_vllm, LocalModelLLMServing_sglang + + +class KBCleaning_batchvllm_GPUPipeline(): + def __init__(self): + + self.storage = FileStorage( + first_entry_file_name="../../example_data/KBCleaningPipeline/kbc_test.jsonl", + cache_path="./.cache/gpu", + file_name_prefix="batch_cleaning_step", + cache_type="json", + ) + + self.knowledge_cleaning_step1 = FileOrURLToMarkdownConverterFlash( + intermediate_dir="../example_data/KBCleaningPipeline/flash/", + mineru_model_path="/MinerU2.5-2509-1.2B", # !!! place your local model path here !!! + # https://huggingface.co/opendatalab/MinerU2.5-2509-1.2B. + batch_size=4, # batchsize per vllm worker + replicas=1, # num of vllm workers + num_gpus_per_replica=0.5, # for ray to schedule vllm workers to GPU, can be float, e.g. 0.5 means each worker uses half GPU, 1 means each worker uses whole GPU + engine_gpu_util_rate_to_ray_cap=0.9 # actuall GPU utilization for each worker; acturall memory per worker= num_gpus_per_replica * engine_gpu_util_rate_to_ray_cap; this is to avoid OOM, you can set it to 0.9 or 0.8 to leave some buffer for other processes on + ) + + self.knowledge_cleaning_step2 = KBCChunkGeneratorBatch( + split_method="token", + chunk_size=512, + tokenizer_name="Qwen/Qwen2.5-7B-Instruct", + ) + + def forward(self): + self.knowledge_cleaning_step1.run( + storage=self.storage.step(), + ) + + self.knowledge_cleaning_step2.run( + storage=self.storage.step(), + ) + + self.llm_serving = LocalModelLLMServing_vllm( + hf_model_name_or_path="Qwen/Qwen2.5-7B-Instruct", + vllm_max_tokens=2048, + vllm_tensor_parallel_size=4, + vllm_gpu_memory_utilization=0.6, + vllm_repetition_penalty=1.2 + ) + + self.knowledge_cleaning_step3 = KBCTextCleanerBatch( + llm_serving=self.llm_serving, + lang="en" + ) + + self.knowledge_cleaning_step4 = KBCMultiHopQAGeneratorBatch( + llm_serving=self.llm_serving, + lang="en" + ) + + self.knowledge_cleaning_step3.run( + storage=self.storage.step(), + ) + self.knowledge_cleaning_step4.run( + storage=self.storage.step(), + ) + + +if __name__ == "__main__": + model = KBCleaning_batchvllm_GPUPipeline() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/kbcleaning/kbcleaning_pipeline_sglang.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/kbcleaning/kbcleaning_pipeline_sglang.py new file mode 100644 index 0000000000000000000000000000000000000000..936adfb38b9911f884c253ff6563ce144a196c2b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/kbcleaning/kbcleaning_pipeline_sglang.py @@ -0,0 +1,80 @@ +from dataflow.operators.knowledge_cleaning import ( + KBCChunkGenerator, + FileOrURLToMarkdownConverterFlash, + KBCTextCleaner, + # KBCMultiHopQAGenerator, +) +from dataflow.operators.core_text import Text2MultiHopQAGenerator +from dataflow.utils.storage import FileStorage +from dataflow.serving import LocalModelLLMServing_vllm, LocalModelLLMServing_sglang + +class KBCleaning_PDFSglang_GPUPipeline(): + def __init__(self): + + self.storage = FileStorage( + first_entry_file_name="../../example_data/KBCleaningPipeline/kbc_test.jsonl", + cache_path="./.cache/gpu", + file_name_prefix="knowledge_cleaning_step_sglang_engine", + cache_type="json", + ) + + self.knowledge_cleaning_step1 = FileOrURLToMarkdownConverterFlash( + intermediate_dir="../example_data/KBCleaningPipeline/flash/", + mineru_model_path="/MinerU2.5-2509-1.2B", # !!! place your local model path here !!! + # https://huggingface.co/opendatalab/MinerU2.5-2509-1.2B. + batch_size=4, # batchsize per vllm worker + replicas=1, # num of vllm workers + num_gpus_per_replica=0.5, # for ray to schedule vllm workers to GPU, can be float, e.g. 0.5 means each worker uses half GPU, 1 means each worker uses whole GPU + engine_gpu_util_rate_to_ray_cap=0.9 # actuall GPU utilization for each worker; acturall memory per worker= num_gpus_per_replica * engine_gpu_util_rate_to_ray_cap; this is to avoid OOM, you can set it to 0.9 or 0.8 to leave some buffer for other processes on + ) + self.knowledge_cleaning_step2 = KBCChunkGenerator( + split_method="token", + chunk_size=512, + tokenizer_name="Qwen/Qwen2.5-7B-Instruct", + ) + + def forward(self): + self.knowledge_cleaning_step1.run( + storage=self.storage.step(), + # input_key= + # output_key= + ) + + self.knowledge_cleaning_step2.run( + storage=self.storage.step(), + # input_key= + # output_key= + ) + + self.llm_serving = LocalModelLLMServing_sglang( + hf_model_name_or_path="Qwen/Qwen2.5-7B-Instruct", + sgl_dp_size=1, # data parallel size + sgl_tp_size=1, # tensor parallel size + sgl_max_new_tokens=2048, + ) + + self.knowledge_cleaning_step3 = KBCTextCleaner( + llm_serving=self.llm_serving, + lang="en" + ) + + self.knowledge_cleaning_step4 = Text2MultiHopQAGenerator( + llm_serving=self.llm_serving, + lang="en", + num_q = 5 + ) + + self.knowledge_cleaning_step3.run( + storage=self.storage.step(), + # input_key= + # output_key= + ) + self.knowledge_cleaning_step4.run( + storage=self.storage.step(), + # input_key= + # output_key= + ) + +if __name__ == "__main__": + model = KBCleaning_PDFSglang_GPUPipeline() + model.forward() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/kbcleaning/kbcleaning_pipeline_vllm.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/kbcleaning/kbcleaning_pipeline_vllm.py new file mode 100644 index 0000000000000000000000000000000000000000..44c62d1b4fcc134d3d1e639f6102c6ffb315fd38 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/kbcleaning/kbcleaning_pipeline_vllm.py @@ -0,0 +1,82 @@ +from dataflow.operators.knowledge_cleaning import ( + KBCChunkGenerator, + FileOrURLToMarkdownConverterFlash, + KBCTextCleaner, + # KBCMultiHopQAGenerator, +) +from dataflow.operators.core_text import Text2MultiHopQAGenerator +from dataflow.utils.storage import FileStorage +from dataflow.serving import LocalModelLLMServing_vllm + +class KBCleaning_PDFvllm_GPUPipeline(): + def __init__(self): + + self.storage = FileStorage( + first_entry_file_name="../../example_data/KBCleaningPipeline/kbc_test.jsonl", + cache_path="./.cache/gpu", + file_name_prefix="knowledge_cleaning_step_vllm_engine", + cache_type="json", + ) + + self.knowledge_cleaning_step1 = FileOrURLToMarkdownConverterFlash( + intermediate_dir="../example_data/KBCleaningPipeline/flash/", + mineru_model_path="/MinerU2.5-2509-1.2B", # !!! place your local model path here !!! + # https://huggingface.co/opendatalab/MinerU2.5-2509-1.2B. + batch_size=4, # batchsize per vllm worker + replicas=1, # num of vllm workers + num_gpus_per_replica=0.5, # for ray to schedule vllm workers to GPU, can be float, e.g. 0.5 means each worker uses half GPU, 1 means each worker uses whole GPU + engine_gpu_util_rate_to_ray_cap=0.9 # actuall GPU utilization for each worker; acturall memory per worker= num_gpus_per_replica * engine_gpu_util_rate_to_ray_cap; this is to avoid OOM, you can set it to 0.9 or 0.8 to leave some buffer for other processes on + ) + + self.knowledge_cleaning_step2 = KBCChunkGenerator( + split_method="token", + chunk_size=512, + tokenizer_name="Qwen/Qwen2.5-7B-Instruct", + ) + + def forward(self): + self.knowledge_cleaning_step1.run( + storage=self.storage.step(), + # input_key= + # output_key= + ) + + self.knowledge_cleaning_step2.run( + storage=self.storage.step(), + # input_key= + # output_key= + ) + + self.llm_serving = LocalModelLLMServing_vllm( + hf_model_name_or_path="Qwen/Qwen2.5-7B-Instruct", + vllm_max_tokens=2048, + vllm_tensor_parallel_size=4, + vllm_gpu_memory_utilization=0.6, + vllm_repetition_penalty=1.2 + ) + + self.knowledge_cleaning_step3 = KBCTextCleaner( + llm_serving=self.llm_serving, + lang="en" + ) + + self.knowledge_cleaning_step4 = Text2MultiHopQAGenerator( + llm_serving=self.llm_serving, + lang="en", + num_q = 5 + ) + + self.knowledge_cleaning_step3.run( + storage=self.storage.step(), + # input_key= + # output_key= + ) + self.knowledge_cleaning_step4.run( + storage=self.storage.step(), + # input_key= + # output_key= + ) + +if __name__ == "__main__": + model = KBCleaning_PDFvllm_GPUPipeline() + model.forward() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/reasoning_math_pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/reasoning_math_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..322bf99b46687e279fc5a9442bdcb0a7ba17c121 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/reasoning_math_pipeline.py @@ -0,0 +1,155 @@ +from dataflow.operators.reasoning import ( + ReasoningCategoryDatasetEvaluator, + ReasoningDifficultyDatasetEvaluator, + ReasoningQuestionGenerator, + ReasoningAnswerGenerator, +) + +from dataflow.operators.reasoning import ( + ReasoningQuestionFilter, + ReasoningAnswerPipelineRootFilter, + ReasoningAnswerFormatterFilter, + ReasoningAnswerTokenLengthFilter, + ReasoningAnswerGroundTruthFilter, + ReasoningAnswerNgramFilter, +) + +from dataflow.prompts.reasoning.math import ( + MathQuestionFilterPrompt, + MathAnswerGeneratorPrompt, + MathQuestionSynthesisPrompt +) + +from dataflow.utils.storage import FileStorage +from dataflow.serving import LocalModelLLMServing_vllm, LocalModelLLMServing_sglang + +class ReasoningMath_GPUPipeline(): + def __init__(self): + + self.storage = FileStorage( + first_entry_file_name="../example_data/ReasoningPipeline/pipeline_math_short.json", + cache_path="./cache_local", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + # use vllm as LLM serving + self.llm_serving = LocalModelLLMServing_vllm( + hf_model_name_or_path="Qwen/Qwen2.5-7B-Instruct", # set to your own model path + vllm_tensor_parallel_size=1, + vllm_max_tokens=8192, + ) + # use SGLang as LLM serving + # llm_serving = LocalModelLLMServing_sglang( + # hf_model_name_or_path="Qwen/Qwen2.5-7B-Instruct", + # sgl_dp_size=1, # data parallel size + # sgl_tp_size=1, # tensor parallel size + # sgl_max_tokens=1024, + # sgl_tensor_parallel_size=4 + # ) + + self.question_filter_step1 = ReasoningQuestionFilter( + system_prompt="You are an expert in evaluating mathematical problems. Follow the user's instructions strictly and output your final judgment in the required JSON format.", + llm_serving=self.llm_serving, + prompt_template=MathQuestionFilterPrompt() + ) + self.question_gen_step2 = ReasoningQuestionGenerator( + num_prompts=3, + llm_serving=self.llm_serving, + prompt_template=MathQuestionSynthesisPrompt() + ) + self.question_filter_step3 = ReasoningQuestionFilter( + system_prompt="You are an expert in evaluating mathematical problems. Follow the user's instructions strictly and output your final judgment in the required JSON format.", + llm_serving=self.llm_serving, + prompt_template=MathQuestionFilterPrompt() + ) + self.question_difficulty_classifier_step4 = ReasoningDifficultyDatasetEvaluator( + llm_serving=self.llm_serving + ) + self.question_category_classifier_step5 = ReasoningCategoryDatasetEvaluator( + llm_serving=self.llm_serving + ) + ########################## branch ############################ + # self.answer_pipeline_root_step6 = AnswerPipelineRoot() + ########################## answer ############################ + self.answer_generator_step7 = ReasoningAnswerGenerator( + llm_serving=self.llm_serving, + prompt_template=MathAnswerGeneratorPrompt() + ) + + self.answer_format_filter_step8 = ReasoningAnswerFormatterFilter() + + self.answer_token_length_filter_step9 = ReasoningAnswerTokenLengthFilter( + max_answer_token_length = 8192, + tokenizer_dir = "Qwen/Qwen2.5-0.5B-Instruct" + ) + + self.answer_groundtruth_filter_step10 = ReasoningAnswerGroundTruthFilter() + + self.answer_ngram_filter_step11 = ReasoningAnswerNgramFilter( + min_score = 0.1, + max_score = 1.0, + ngrams = 5 + ) + + def forward(self): + + self.question_filter_step1.run( + storage = self.storage.step(), + input_key = "instruction", + ) + + self.question_gen_step2.run( + storage = self.storage.step(), + input_key = "instruction", + ) + + self.question_filter_step3.run( + storage = self.storage.step(), + input_key = "instruction", + ) + + self.question_difficulty_classifier_step4.run( + storage = self.storage.step(), + input_key = "instruction", + output_key = "question_difficulty" + ) + + self.question_category_classifier_step5.run( + storage = self.storage.step(), + input_key = "instruction", + output_key = "question_category" + ) + ############# branch ############# + # self.answer_pipeline_root_step6.run( + # storage = self.storage.step(), + # input_answer_key = "output", + # input_gt_key = "golden_answer" + # ) + ############## answer ############# + self.answer_generator_step7.run( + storage = self.storage.step(), + input_key = "instruction", + output_key = "generated_cot" + ) + self.answer_format_filter_step8.run( + storage = self.storage.step(), + input_key = "generated_cot", + ) + self.answer_token_length_filter_step9.run( + storage = self.storage.step(), + input_key = "generated_cot" + ) + self.answer_groundtruth_filter_step10.run( + storage = self.storage.step(), + input_test_answer_key = "generated_cot", + input_gt_answer_key = "golden_answer" + ) + self.answer_ngram_filter_step11.run( + storage = self.storage.step(), + input_question_key = "instruction", + input_answer_key = "generated_cot" + ) + +if __name__ == "__main__": + model = ReasoningMath_GPUPipeline() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/speechtranscription_pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/speechtranscription_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..50c856ea6bef768b3506798441ccb869e524fcc1 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/speechtranscription_pipeline.py @@ -0,0 +1,32 @@ +from dataflow.operators.core_speech import Speech2TextGenerator +from dataflow.serving import LocalModelLALMServing_vllm +from dataflow.utils.storage import FileStorage + +class SpeechTranscription_GPUPipeline(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/SpeechTranscription/pipeline_speechtranscription.jsonl", + cache_path="./cache", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + self.llm_serving = LocalModelLALMServing_vllm( + hf_model_name_or_path='Qwen/Qwen2-Audio-7B-Instruct', + vllm_tensor_parallel_size=4, + vllm_max_tokens=8192, + ) + self.speech_transcriptor = Speech2TextGenerator( + llm_serving = self.llm_serving, + system_prompt="你是一个专业的翻译员,你需要将语音转录为文本。" + ) + + def forward(self): + self.speech_transcriptor.run( + storage=self.storage.step(), + input_key="raw_content" + ) + +if __name__ == "__main__": + pipeline = SpeechTranscription_GPUPipeline() + pipeline.forward() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/text2sql_pipeline_gen.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/text2sql_pipeline_gen.py new file mode 100644 index 0000000000000000000000000000000000000000..1a65a974b6213ca790158ed591df1660dd73b6d2 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/text2sql_pipeline_gen.py @@ -0,0 +1,242 @@ +import os +from dataflow import get_logger +import zipfile +from pathlib import Path +from huggingface_hub import snapshot_download + +from dataflow.operators.text2sql import ( + SQLGenerator, + Text2SQLQuestionGenerator, + Text2SQLPromptGenerator, + Text2SQLCoTGenerator +) +from dataflow.operators.text2sql import ( + SQLExecutionFilter +) +from dataflow.operators.text2sql import ( + SQLComponentClassifier, + SQLExecutionClassifier +) +from dataflow.prompts.text2sql import ( + Text2SQLCotGeneratorPrompt, + SelectSQLGeneratorPrompt, + Text2SQLQuestionGeneratorPrompt, + Text2SQLPromptGeneratorPrompt +) +from dataflow.utils.storage import FileStorage +from dataflow.serving import LocalModelLLMServing_vllm, LocalModelLLMServing_sglang +from dataflow.utils.text2sql.database_manager import DatabaseManager + +def download_and_extract_database(logger): + dataset_repo_id = "Open-Dataflow/dataflow-Text2SQL-database-example" + local_dir = "./hf_cache" + extract_to = "./downloaded_databases" + + logger.info(f"Downloading and extracting database from {dataset_repo_id}...") + os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com' + + os.makedirs(local_dir, exist_ok=True) + os.makedirs(extract_to, exist_ok=True) + + downloaded_path = snapshot_download( + repo_id=dataset_repo_id, + repo_type="dataset", + local_dir=local_dir, + resume_download=True + ) + + logger.info(f"Files downloaded to: {downloaded_path}") + + zip_path = os.path.join(downloaded_path, "databases.zip") + if os.path.exists(zip_path): + with zipfile.ZipFile(zip_path, 'r') as zip_ref: + zip_ref.extractall(extract_to) + logger.info(f"Database files extracted to {extract_to}") + return extract_to + else: + raise FileNotFoundError(f"Database zip file not found at {zip_path}") + +class Text2SQLGeneration_GPUPipeline(): + def __init__(self, db_root_path=""): + self.logger = get_logger() + self.db_root_path = db_root_path + + if not db_root_path: + try: + self.db_root_path = download_and_extract_database(self.logger) + self.logger.info(f"Using automatically downloaded database at: {self.db_root_path}") + except Exception as e: + self.logger.error(f"Failed to auto-download database: {e}") + raise + else: + self.logger.info(f"Using manually specified database path: {self.db_root_path}") + + if not os.path.exists(self.db_root_path): + raise FileNotFoundError(f"Database path does not exist: {self.db_root_path}") + + self.storage = FileStorage( + first_entry_file_name="../example_data/Text2SQLPipeline/empty.jsonl", + cache_path="./cache", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + self.llm_serving = LocalModelLLMServing_vllm( + hf_model_name_or_path="Qwen/Qwen2.5-7B-Instruct", # set to your own model path + vllm_tensor_parallel_size=1, + vllm_max_tokens=8192, + ) + + # use SGLang as LLM serving + # llm_serving = LocalModelLLMServing_sglang( + # hf_model_name_or_path="Qwen/Qwen2.5-7B-Instruct", + # sgl_dp_size=1, # data parallel size + # sgl_tp_size=1, # tensor parallel size + # sgl_max_tokens=1024, + # sgl_tensor_parallel_size=4 + # ) + + # It is recommended to use better LLMs for the generation of Chain-of-Thought (CoT) reasoning process. + cot_generation_llm_serving = LocalModelLLMServing_vllm( + hf_model_name_or_path="Qwen/Qwen2.5-7B-Instruct", # set to your own model path + vllm_tensor_parallel_size=1, + vllm_max_tokens=8192, + ) + + embedding_serving = LocalModelLLMServing_vllm( + hf_model_name_or_path="Alibaba-NLP/gte-Qwen2-7B-instruct", + vllm_max_tokens=8192 + ) + + # SQLite and MySQL are currently supported + # db_type can be sqlite or mysql, which must match your database type + # If sqlite is selected, root_path must be provided, this path must exist and contain database files + # If mysql is selected, host, user, password must be provided, these credentials must be correct and have access permissions + # MySQL example: + # database_manager = DatabaseManager( + # db_type="mysql", + # config={ + # "host": "localhost", + # "user": "root", + # "password": "your_password", + # "database": "your_database_name" + # } + # ) + # SQLite example: + database_manager = DatabaseManager( + db_type="sqlite", + config={ + "root_path": self.db_root_path + }, + logger=None, + max_connections_per_db=100, + max_workers=100 + ) + + self.sql_generator_step1 = SQLGenerator( + llm_serving=self.llm_serving, + database_manager=database_manager, + generate_num=10, + prompt_template=SelectSQLGeneratorPrompt() + ) + + self.sql_execution_filter_step2 = SQLExecutionFilter( + database_manager=database_manager, + ) + + self.text2sql_question_generator_step3 = Text2SQLQuestionGenerator( + llm_serving=self.llm_serving, + embedding_serving=embedding_serving, + database_manager=database_manager, + question_candidates_num=5, + prompt_template=Text2SQLQuestionGeneratorPrompt() + ) + + self.text2sql_prompt_generator_step4 = Text2SQLPromptGenerator( + database_manager=database_manager, + prompt_template=Text2SQLPromptGeneratorPrompt() + ) + + self.sql_cot_generator_step5 = Text2SQLCoTGenerator( + llm_serving=cot_generation_llm_serving, + database_manager=database_manager, + max_retries=3, + enable_retry=True, + prompt_template=Text2SQLCotGeneratorPrompt() + ) + + self.sql_component_classifier_step6 = SQLComponentClassifier( + difficulty_thresholds=[2, 4, 6], + difficulty_labels=['easy', 'medium', 'hard', 'extra'] + ) + + self.sql_execution_classifier_step7 = SQLExecutionClassifier( + llm_serving=self.llm_serving, + database_manager=database_manager, + num_generations=10, + difficulty_thresholds=[2, 5, 9], + difficulty_labels=['extra', 'hard', 'medium', 'easy'] + ) + + + def forward(self): + + sql_key = "SQL" + db_id_key = "db_id" + question_key = "question" + + self.sql_generator_step1.run( + storage=self.storage.step(), + output_sql_key=sql_key, + output_db_id_key=db_id_key + ) + + self.sql_execution_filter_step2.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_db_id_key=db_id_key + ) + + self.text2sql_question_generator_step3.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_db_id_key=db_id_key, + output_question_key=question_key + ) + + self.text2sql_prompt_generator_step4.run( + storage=self.storage.step(), + input_question_key=question_key, + input_db_id_key=db_id_key, + output_prompt_key="prompt" + ) + + self.sql_cot_generator_step5.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_question_key=question_key, + input_db_id_key=db_id_key, + output_cot_key="cot_reasoning" + ) + + self.sql_component_classifier_step6.run( + storage=self.storage.step(), + input_sql_key=sql_key, + output_difficulty_key="sql_component_difficulty" + ) + + self.sql_execution_classifier_step7.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_db_id_key=db_id_key, + input_prompt_key="prompt", + output_difficulty_key="sql_execution_difficulty" + ) + +if __name__ == "__main__": + # If you have your own database files, you can set the db_root_path to the path of your database files + # If not, please set the db_root_path "", and we will download the example database files automatically + db_root_path = "" + + model = Text2SQLGeneration_GPUPipeline(db_root_path=db_root_path) + model.forward() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/text2sql_pipeline_refine.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/text2sql_pipeline_refine.py new file mode 100644 index 0000000000000000000000000000000000000000..07ba54b31cbe2a3dbb9c9e8ebd5bc49e8062995b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/text2sql_pipeline_refine.py @@ -0,0 +1,259 @@ +import os +from dataflow import get_logger +import zipfile +from huggingface_hub import snapshot_download + +from dataflow.operators.text2sql import ( + SQLVariationGenerator, + Text2SQLQuestionGenerator, + Text2SQLPromptGenerator, + Text2SQLCoTGenerator +) +from dataflow.operators.text2sql import ( + SQLExecutionFilter, + SQLConsistencyFilter +) +from dataflow.operators.text2sql import ( + SQLComponentClassifier, + SQLExecutionClassifier +) +from dataflow.prompts.text2sql import ( + SQLConsistencyFilterPrompt, + Text2SQLCotGeneratorPrompt, + Text2SQLQuestionGeneratorPrompt, + SQLVariationGeneratorPrompt, + Text2SQLPromptGeneratorPrompt +) +from dataflow.utils.storage import FileStorage +from dataflow.serving import LocalModelLLMServing_vllm, LocalModelLLMServing_sglang +from dataflow.utils.text2sql.database_manager import DatabaseManager + +def download_and_extract_database(logger): + dataset_repo_id = "Open-Dataflow/dataflow-Text2SQL-database-example" + local_dir = "./hf_cache" + extract_to = "./downloaded_databases" + + logger.info(f"Downloading and extracting database from {dataset_repo_id}...") + os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com' + + os.makedirs(local_dir, exist_ok=True) + os.makedirs(extract_to, exist_ok=True) + + downloaded_path = snapshot_download( + repo_id=dataset_repo_id, + repo_type="dataset", + local_dir=local_dir, + resume_download=True + ) + + logger.info(f"Files downloaded to: {downloaded_path}") + + zip_path = os.path.join(downloaded_path, "databases.zip") + if os.path.exists(zip_path): + with zipfile.ZipFile(zip_path, 'r') as zip_ref: + zip_ref.extractall(extract_to) + logger.info(f"Database files extracted to {extract_to}") + return extract_to + else: + raise FileNotFoundError(f"Database zip file not found at {zip_path}") + +class Text2SQLRefine_GPUPipeline(): + def __init__(self, db_root_path=""): + self.logger = get_logger() + self.db_root_path = db_root_path + + if not db_root_path: + try: + self.db_root_path = download_and_extract_database(self.logger) + self.logger.info(f"Using automatically downloaded database at: {self.db_root_path}") + except Exception as e: + self.logger.error(f"Failed to auto-download database: {e}") + raise + else: + self.logger.info(f"Using manually specified database path: {self.db_root_path}") + + if not os.path.exists(self.db_root_path): + raise FileNotFoundError(f"Database path does not exist: {self.db_root_path}") + + self.storage = FileStorage( + first_entry_file_name="../example_data/Text2SQLPipeline/pipeline_refine.jsonl", + cache_path="./cache_local", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl" + ) + + self.llm_serving = LocalModelLLMServing_vllm( + hf_model_name_or_path="Qwen/Qwen2.5-7B-Instruct", # set to your own model path + vllm_tensor_parallel_size=1, + vllm_max_tokens=8192, + ) + + # It is recommended to use better LLMs for the generation of Chain-of-Thought (CoT) reasoning process. + cot_generation_llm_serving = LocalModelLLMServing_vllm( + hf_model_name_or_path="Qwen/Qwen2.5-7B-Instruct", # set to your own model path + vllm_tensor_parallel_size=1, + vllm_max_tokens=8192, + ) + + embedding_serving = LocalModelLLMServing_vllm( + hf_model_name_or_path="Alibaba-NLP/gte-Qwen2-7B-instruct", + vllm_max_tokens=8192 + ) + + # SQLite and MySQL are currently supported + # db_type can be sqlite or mysql, which must match your database type + # If sqlite is selected, root_path must be provided, this path must exist and contain database files + # If mysql is selected, host, user, password must be provided, these credentials must be correct and have access permissions + # MySQL example: + # database_manager = DatabaseManager( + # db_type="mysql", + # config={ + # "host": "localhost", + # "user": "root", + # "password": "your_password", + # "database": "your_database_name" + # } + # ) + # SQLite example: + database_manager = DatabaseManager( + db_type="sqlite", + config={ + "root_path": self.db_root_path + }, + logger=None, + sql_execution_timeout = 2, + max_connections_per_db=100, + max_workers=100 + ) + + self.sql_execution_filter_step1 = SQLExecutionFilter( + database_manager=database_manager + ) + + self.sql_consistency_filter_step2 = SQLConsistencyFilter( + llm_serving=self.llm_serving, + database_manager=database_manager, + prompt_template=SQLConsistencyFilterPrompt() + ) + + self.sql_variation_generator_step3 = SQLVariationGenerator( + llm_serving=self.llm_serving, + database_manager=database_manager, + num_variations=5, + prompt_template=SQLVariationGeneratorPrompt() + ) + + self.sql_execution_filter_step4 = SQLExecutionFilter( + database_manager=database_manager + ) + + self.text2sql_question_generator_step5 = Text2SQLQuestionGenerator( + llm_serving=self.llm_serving, + embedding_serving=embedding_serving, + database_manager=database_manager, + question_candidates_num=5, + prompt_template=Text2SQLQuestionGeneratorPrompt() + ) + + self.text2sql_prompt_generator_step6 = Text2SQLPromptGenerator( + database_manager=database_manager, + prompt_template=Text2SQLPromptGeneratorPrompt() + ) + + self.sql_cot_generator_step7 = Text2SQLCoTGenerator( + llm_serving=cot_generation_llm_serving, + database_manager=database_manager, + max_retries=3, + enable_retry=True, + prompt_template=Text2SQLCotGeneratorPrompt() + ) + + self.sql_component_classifier_step8 = SQLComponentClassifier( + num_generations = 10, + difficulty_thresholds = [2, 4, 6], + difficulty_labels = ['easy', 'medium', 'hard', 'extra'] + ) + + self.sql_execution_classifier_step9 = SQLExecutionClassifier( + llm_serving=self.llm_serving, + database_manager=database_manager, + num_generations = 10, + difficulty_thresholds = [2, 5, 9], + difficulty_labels = ['extra', 'hard', 'medium', 'easy'] + ) + + + def forward(self): + + sql_key = "SQL" + db_id_key = "db_id" + question_key = "question" + + self.sql_execution_filter_step1.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_db_id_key=db_id_key + ) + + self.sql_consistency_filter_step2.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_db_id_key=db_id_key, + input_question_key=question_key + ) + + self.sql_variation_generator_step3.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_db_id_key=db_id_key + ) + + self.sql_execution_filter_step4.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_db_id_key=db_id_key + ) + + self.text2sql_question_generator_step5.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_db_id_key=db_id_key, + output_question_key=question_key + ) + + self.text2sql_prompt_generator_step6.run( + storage=self.storage.step(), + input_question_key=question_key, + input_db_id_key=db_id_key, + output_prompt_key="prompt" + ) + + self.sql_cot_generator_step7.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_question_key=question_key, + input_db_id_key=db_id_key, + output_cot_key="cot_reasoning" + ) + + self.sql_component_classifier_step8.run( + storage=self.storage.step(), + input_sql_key=sql_key, + output_difficulty_key="sql_component_difficulty" + ) + + self.sql_execution_classifier_step9.run( + storage=self.storage.step(), + input_sql_key=sql_key, + input_db_id_key=db_id_key, + input_prompt_key="prompt", + output_difficulty_key="sql_execution_difficulty" + ) + +if __name__ == "__main__": + # If you have your own database files, you can set the db_root_path to the path of your database files + # If not, please set the db_root_path "", and we will download the example database files automatically + db_root_path = "" + + model = Text2SQLRefine_GPUPipeline(db_root_path=db_root_path) + model.forward() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/text_pt_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/text_pt_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..ad69416ee845c04bd6b1501c14cc72ae5314b727 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/text_pt_filter.py @@ -0,0 +1,173 @@ +from dataflow.operators.general_text import ( + MinHashDeduplicateFilter, + LanguageFilter, + WordNumberFilter, + BlocklistFilter, + ColonEndFilter, + SentenceNumberFilter, + LineEndWithEllipsisFilter, + ContentNullFilter, + MeanWordLengthFilter, + SymbolWordRatioFilter, + HtmlEntityFilter, + NoPuncFilter, + SpecialCharacterFilter, + WatermarkFilter, + CurlyBracketFilter, + CapitalWordsFilter, + LoremIpsumFilter, + UniqueWordsFilter, + CharNumberFilter, + LineStartWithBulletpointFilter, + LineWithJavascriptFilter, + RemoveExtraSpacesRefiner, + RemoveEmojiRefiner, + HtmlUrlRemoverRefiner, +) +from dataflow.operators.text_pt import ( + PairQualFilter +) + +from dataflow.utils.storage import FileStorage + +class PTTextFilter_GPUPipeline(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/GeneralTextPipeline/pt_input.jsonl", + cache_path="./cache", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + self.model_cache_dir = './dataflow_cache' + self.language_filter = LanguageFilter(allowed_languages = '__label__eng_Latn', model_cache_dir = self.model_cache_dir) + self.remove_extra_spaces_refiner = RemoveExtraSpacesRefiner() + self.remove_emoji_refiner = RemoveEmojiRefiner() + self.html_remove_refiner = HtmlUrlRemoverRefiner() + self.minhash_deduplicator = MinHashDeduplicateFilter(num_perm=128, threshold=0.9, use_n_gram=True, ngram=5) + self.blocklist_filter = BlocklistFilter() + self.word_number_filter = WordNumberFilter(min_words=20, max_words=100000) + self.colon_end_filter = ColonEndFilter() + self.sentence_number_filter = SentenceNumberFilter(min_sentences=3, max_sentences=7500) + self.line_end_with_ellipsis_filter = LineEndWithEllipsisFilter(threshold=0.3) + self.content_null_filter = ContentNullFilter() + self.mean_word_length_filter = MeanWordLengthFilter(min_length=3, max_length=10) + self.symbol_word_ratio_filter = SymbolWordRatioFilter(threshold=0.4) + self.html_entity_filter = HtmlEntityFilter() + self.no_punc_filter = NoPuncFilter(threshold=112) + self.special_character_filter = SpecialCharacterFilter() + self.watermark_filter = WatermarkFilter(watermarks=['Copyright', 'Watermark', 'Confidential']) + self.curly_bracket_filter = CurlyBracketFilter(threshold=0.025) + self.capital_words_filter = CapitalWordsFilter(threshold=0.2, use_tokenizer=False) + self.lorem_ipsum_filter = LoremIpsumFilter(threshold=3e-8) + self.unique_words_filter = UniqueWordsFilter(threshold=0.1) + self.char_number_filter = CharNumberFilter(threshold=100) + self.line_start_with_bulletpoint_filter = LineStartWithBulletpointFilter(threshold=0.9) + self.line_with_javascript_filter = LineWithJavascriptFilter(threshold=3) + self.quality_filter = PairQualFilter(min_score=2, max_score=10000, lang='en') + + def forward(self): + self.remove_emoji_refiner.run( + storage=self.storage.step(), + input_key="raw_content" + ) + self.html_remove_refiner.run( + storage=self.storage.step(), + input_key="raw_content" + ) + self.remove_extra_spaces_refiner.run( + storage=self.storage.step(), + input_key="raw_content" + ) + self.blocklist_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.word_number_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.colon_end_filter.run( + storage = self.storage.step(), + input_key = 'raw_content' + ) + self.sentence_number_filter.run( + storage = self.storage.step(), + input_key = 'raw_content' + ) + self.line_end_with_ellipsis_filter.run( + storage = self.storage.step(), + input_key = 'raw_content' + ) + self.content_null_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.mean_word_length_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.symbol_word_ratio_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.html_entity_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.no_punc_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.special_character_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.watermark_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.curly_bracket_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.capital_words_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.lorem_ipsum_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.unique_words_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.char_number_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.line_start_with_bulletpoint_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.line_with_javascript_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.quality_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.language_filter.run( + storage = self.storage.step(), + input_key = "raw_content" + ) + self.minhash_deduplicator.run( + storage = self.storage.step(), + input_key='raw_content', + ) + +if __name__ == "__main__": + # This is the entry point for the pipeline + model = PTTextFilter_GPUPipeline() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/text_pt_synthetic.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/text_pt_synthetic.py new file mode 100644 index 0000000000000000000000000000000000000000..923b2732e3883b9f1f0e04e998b844d889bb7717 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/text_pt_synthetic.py @@ -0,0 +1,214 @@ +from dataflow.operators.general_text import ( + MinHashDeduplicateFilter, + LanguageFilter, + WordNumberFilter, + BlocklistFilter, + ColonEndFilter, + SentenceNumberFilter, + LineEndWithEllipsisFilter, + ContentNullFilter, + MeanWordLengthFilter, + SymbolWordRatioFilter, + HtmlEntityFilter, + IDCardFilter, + NoPuncFilter, + SpecialCharacterFilter, + WatermarkFilter, + CurlyBracketFilter, + CapitalWordsFilter, + LoremIpsumFilter, + UniqueWordsFilter, + CharNumberFilter, + LineStartWithBulletpointFilter, + LineWithJavascriptFilter, + RemoveExtraSpacesRefiner, + RemoveEmojiRefiner, + HtmlUrlRemoverRefiner, +) +from dataflow.operators.text_pt import ( + PairQualFilter, + QuratingFilter +) + +from dataflow.operators.text_pt import Phi4QAGenerator +from dataflow.serving import LocalModelLLMServing_vllm, LocalModelLLMServing_sglang +from dataflow.utils.storage import FileStorage + +class PTTextSynthetic_GPUPipeline(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/GeneralTextPipeline/pt_input.jsonl", + cache_path="./cache", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + + self.model_cache_dir = './dataflow_cache' + # use local model as LLM serving + self.llm_serving = LocalModelLLMServing_vllm( + hf_model_name_or_path='Qwen/Qwen2.5-7B-Instruct', + vllm_tensor_parallel_size=1, + vllm_max_tokens=8192, + ) + # use SGLang as LLM serving + # self.llm_serving = LocalModelLLMServing_sglang( + # hf_model_name_or_path="Qwen/Qwen2.5-7B-Instruct", + # sgl_dp_size=1, # data parallel size + # sgl_tp_size=1, # tensor parallel size + # sgl_max_tokens=1024, + # sgl_tensor_parallel_size=4 + # ) + + self.language_filter = LanguageFilter(allowed_languages = '__label__eng_Latn', model_cache_dir = self.model_cache_dir) + self.remove_extra_spaces_refiner = RemoveExtraSpacesRefiner() + self.remove_emoji_refiner = RemoveEmojiRefiner() + self.html_remove_refiner = HtmlUrlRemoverRefiner() + self.minhash_deduplicator = MinHashDeduplicateFilter(num_perm=128, threshold=0.9, use_n_gram=True, ngram=5) + self.blocklist_filter = BlocklistFilter() + self.word_number_filter = WordNumberFilter(min_words=20, max_words=100000) + self.colon_end_filter = ColonEndFilter() + self.sentence_number_filter = SentenceNumberFilter(min_sentences=3, max_sentences=7500) + self.line_end_with_ellipsis_filter = LineEndWithEllipsisFilter(threshold=0.3) + self.content_null_filter = ContentNullFilter() + self.mean_word_length_filter = MeanWordLengthFilter(min_length=3, max_length=10) + self.symbol_word_ratio_filter = SymbolWordRatioFilter(threshold=0.4) + self.html_entity_filter = HtmlEntityFilter() + self.id_card_filter = IDCardFilter(threshold=3) + self.no_punc_filter = NoPuncFilter(threshold=112) + self.special_character_filter = SpecialCharacterFilter() + self.watermark_filter = WatermarkFilter(watermarks=['Copyright', 'Watermark', 'Confidential']) + self.curly_bracket_filter = CurlyBracketFilter(threshold=0.025) + self.capital_words_filter = CapitalWordsFilter(threshold=0.2, use_tokenizer=False) + self.lorem_ipsum_filter = LoremIpsumFilter(threshold=3e-8) + self.unique_words_filter = UniqueWordsFilter(threshold=0.1) + self.char_number_filter = CharNumberFilter(threshold=100) + self.line_start_with_bulletpoint_filter = LineStartWithBulletpointFilter(threshold=0.9) + self.line_with_javascript_filter = LineWithJavascriptFilter(threshold=3) + self.quality_filter = PairQualFilter(min_score=-2, max_score=10000, lang='en') + self.pt_generator = Phi4QAGenerator( + llm_serving=self.llm_serving + ) + self.qurating_filter = QuratingFilter(min_scores = {'writing_style': 0,'required_expertise': 0,'facts_and_trivia': 0,'educational_value': 0}, max_scores = {'writing_style': 9,'required_expertise': 9,'facts_and_trivia': 9,'educational_value': 9}) + + def forward(self): + # Initial filters + self.language_filter.run( + storage = self.storage.step(), + input_key = "raw_content" + ) + # refiners + self.remove_extra_spaces_refiner.run( + storage=self.storage.step(), + input_key="raw_content" + ) + self.remove_emoji_refiner.run( + storage=self.storage.step(), + input_key="raw_content" + ) + self.html_remove_refiner.run( + storage=self.storage.step(), + input_key="raw_content" + ) + self.minhash_deduplicator.run( + storage = self.storage.step(), + input_key='raw_content', + output_key='minhash_deduplicated_label', + ) + self.blocklist_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.word_number_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.colon_end_filter.run( + storage = self.storage.step(), + input_key = 'raw_content' + ) + self.sentence_number_filter.run( + storage = self.storage.step(), + input_key = 'raw_content' + ) + self.line_end_with_ellipsis_filter.run( + storage = self.storage.step(), + input_key = 'raw_content' + ) + # Add the additional filters here + self.content_null_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.mean_word_length_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.symbol_word_ratio_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.html_entity_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.id_card_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.no_punc_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.special_character_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.watermark_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.curly_bracket_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.capital_words_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.lorem_ipsum_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.unique_words_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.char_number_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.line_start_with_bulletpoint_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.line_with_javascript_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.quality_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.pt_generator.run( + storage=self.storage.step(), + input_key='raw_content', + output_key='generated_content' + ) + self.qurating_filter.run( + storage=self.storage.step(), + input_key='generated_content' + ) +if __name__ == "__main__": + model = PTTextSynthetic_GPUPipeline() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/text_sft_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/text_sft_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..1cc762a2dd8b01aef659f09768ef755707261aca --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/text_sft_filter.py @@ -0,0 +1,62 @@ +from dataflow.operators.general_text import ( + WordNumberFilter, +) +from dataflow.operators.text_sft import ( + SuperfilteringFilter, + DeitaQualityFilter +) +from dataflow.utils.storage import FileStorage + + +class SFTTextFilter_GPUPipeline(): + + def __init__(self): + + self.storage = FileStorage( + first_entry_file_name="../example_data/GeneralTextPipeline/sft_input.jsonl", + cache_path="./cache", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + self.model_cache_dir = './dataflow_cache' + self.word_number_filter_step1 = WordNumberFilter( + min_words=20, + max_words=1000 + ) + self.super_filtering_filter_step2 = SuperfilteringFilter( + min_score=0.5, + max_score=1.0, + model_cache_dir=self.model_cache_dir + ) + self.deita_quality_filter_step3 = DeitaQualityFilter( + min_score=2.5, + max_score=10000, + max_length=512, + model_cache_dir=self.model_cache_dir + ) + + def forward(self): + + self.word_number_filter_step1.run( + storage=self.storage.step(), + input_key="output", + ) + + self.super_filtering_filter_step2.run( + storage=self.storage.step(), + input_instruction_key='instruction', + input_input_key=None, + input_output_key='output' + ) + + self.deita_quality_filter_step3.run( + storage=self.storage.step(), + input_instruction_key='instruction', + input_output_key='output' + ) + +if __name__ == "__main__": + # This is the entry point for the pipeline + pipeline = SFTTextFilter_GPUPipeline() + pipeline.forward() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/text_sft_synthetic.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/text_sft_synthetic.py new file mode 100644 index 0000000000000000000000000000000000000000..ebf1928a59261e7e2461f5b9a23349aa305ec8a2 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/pipelines/gpu_pipelines/text_sft_synthetic.py @@ -0,0 +1,233 @@ +from dataflow.operators.general_text import ( + MinHashDeduplicateFilter, + LanguageFilter, + WordNumberFilter, + BlocklistFilter, + HtmlUrlRemoverRefiner, + RemoveEmojiRefiner, + RemoveExtraSpacesRefiner, + ColonEndFilter, + SentenceNumberFilter, + LineEndWithEllipsisFilter, + ContentNullFilter, + MeanWordLengthFilter, + SymbolWordRatioFilter, + HtmlEntityFilter, + NoPuncFilter, + SpecialCharacterFilter, + WatermarkFilter, + CurlyBracketFilter, + CapitalWordsFilter, + LoremIpsumFilter, + UniqueWordsFilter, + CharNumberFilter, + LineStartWithBulletpointFilter, + LineWithJavascriptFilter, +) +from dataflow.operators.text_pt import ( + PairQualFilter, +) +from dataflow.operators.text_sft import ( + SuperfilteringFilter, + DeitaQualityFilter +) +from dataflow.operators.text_sft import SFTGeneratorSeed +from dataflow.serving import LocalModelLLMServing_vllm, LocalModelLLMServing_sglang +from dataflow.utils.storage import FileStorage + +class SFTTextSynthetic_GPUPipeline(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/GeneralTextPipeline/pt_input.jsonl", + cache_path="./cache", + file_name_prefix="dataflow_cache", + cache_type="jsonl", + ) + self.model_cache_dir = './dataflow_cache' + # use vllm as LLM serving + self.llm_serving = LocalModelLLMServing_vllm( + hf_model_name_or_path='Qwen/Qwen2.5-7B-Instruct', + vllm_tensor_parallel_size=1, + vllm_max_tokens=8192, + ) + # use SGLang as LLM serving + # self.llm_serving = LocalModelLLMServing_sglang( + # hf_model_name_or_path="Qwen/Qwen2.5-7B-Instruct", + # sgl_dp_size=1, # data parallel size + # sgl_tp_size=1, # tensor parallel size + # sgl_max_tokens=1024, + # sgl_tensor_parallel_size=4 + # ) + + self.language_filter = LanguageFilter(allowed_languages = '__label__eng_Latn', model_cache_dir = self.model_cache_dir) + self.remove_extra_spaces_refiner = RemoveExtraSpacesRefiner() + self.remove_emoji_refiner = RemoveEmojiRefiner() + self.html_remove_refiner = HtmlUrlRemoverRefiner() + self.minhash_deduplicator = MinHashDeduplicateFilter(num_perm=128, threshold=0.9, use_n_gram=True, ngram=5) + self.blocklist_filter = BlocklistFilter() + self.word_number_filter = WordNumberFilter(min_words=20, max_words=100000) + self.colon_end_filter = ColonEndFilter() + self.sentence_number_filter = SentenceNumberFilter(min_sentences=3, max_sentences=7500) + self.line_end_with_ellipsis_filter = LineEndWithEllipsisFilter(threshold=0.3) + self.content_null_filter = ContentNullFilter() + self.mean_word_length_filter = MeanWordLengthFilter(min_length=3, max_length=10) + self.symbol_word_ratio_filter = SymbolWordRatioFilter(threshold=0.4) + self.html_entity_filter = HtmlEntityFilter() + self.no_punc_filter = NoPuncFilter(threshold=112) + self.special_character_filter = SpecialCharacterFilter() + self.watermark_filter = WatermarkFilter(watermarks=['Copyright', 'Watermark', 'Confidential']) + self.curly_bracket_filter = CurlyBracketFilter(threshold=0.025) + self.capital_words_filter = CapitalWordsFilter(threshold=0.2, use_tokenizer=False) + self.lorem_ipsum_filter = LoremIpsumFilter(threshold=3e-8) + self.unique_words_filter = UniqueWordsFilter(threshold=0.1) + self.char_number_filter = CharNumberFilter(threshold=100) + self.line_start_with_bulletpoint_filter = LineStartWithBulletpointFilter(threshold=0.9) + self.line_with_javascript_filter = LineWithJavascriptFilter(threshold=3) + self.quality_filter = PairQualFilter(min_score=-2, max_score=10000, lang='en') + self.sft_generator = SFTGeneratorSeed( + llm_serving=self.llm_serving + ) + self.word_number_filter_syn = WordNumberFilter( + min_words=20, + max_words=5000 + ) + self.super_filtering_filter = SuperfilteringFilter( + min_score=0.5, + max_score=10000, + model_cache_dir=self.model_cache_dir + ) + self.deita_quality_filter = DeitaQualityFilter( + min_score=2.5, + max_score=10000, + max_length=512, + model_cache_dir=self.model_cache_dir + ) + + def forward(self): + self.remove_emoji_refiner.run( + storage=self.storage.step(), + input_key="raw_content" + ) + self.html_remove_refiner.run( + storage=self.storage.step(), + input_key="raw_content" + ) + self.remove_extra_spaces_refiner.run( + storage=self.storage.step(), + input_key="raw_content" + ) + self.blocklist_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.word_number_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.colon_end_filter.run( + storage = self.storage.step(), + input_key = 'raw_content' + ) + self.sentence_number_filter.run( + storage = self.storage.step(), + input_key = 'raw_content' + ) + self.line_end_with_ellipsis_filter.run( + storage = self.storage.step(), + input_key = 'raw_content' + ) + # Add the additional filters here + self.content_null_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.mean_word_length_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.symbol_word_ratio_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.html_entity_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.no_punc_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.special_character_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.watermark_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.curly_bracket_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.capital_words_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.lorem_ipsum_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.unique_words_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.char_number_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.line_start_with_bulletpoint_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.line_with_javascript_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.quality_filter.run( + storage = self.storage.step(), + input_key='raw_content', + ) + self.language_filter.run( + storage = self.storage.step(), + input_key = "raw_content" + ) + self.minhash_deduplicator.run( + storage = self.storage.step(), + input_key='raw_content', + output_key='minhash_deduplicated_label', + ) + self.sft_generator.run( + storage=self.storage.step(), + input_key='raw_content', + ) + self.llm_serving.cleanup() + self.word_number_filter_syn.run( + storage=self.storage.step(), + input_key="output", + ) + self.super_filtering_filter.run( + storage=self.storage.step(), + input_instruction_key='instruction', + input_input_key=None, + input_output_key='output' + ) + self.deita_quality_filter.run( + storage=self.storage.step(), + input_instruction_key='instruction', + input_output_key='output' + ) +if __name__ == "__main__": + # This is the entry point for the pipeline + + model = SFTTextSynthetic_GPUPipeline() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/__pycache__/kbcleaning_pipeline_vllm.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/__pycache__/kbcleaning_pipeline_vllm.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e43a876a59c7a3927f44ce4531addf68a10fea5 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/__pycache__/kbcleaning_pipeline_vllm.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/__pycache__/mathbook_extract.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/__pycache__/mathbook_extract.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e127ea95cc5988d27a481046eee9019f80b1aefd Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/__pycache__/mathbook_extract.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/__pycache__/quick_evaluate.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/__pycache__/quick_evaluate.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f32f7bebcbd5c050638685afdb0cf39d9d64c139 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/__pycache__/quick_evaluate.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/__pycache__/reasoning_general_pipeline.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/__pycache__/reasoning_general_pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68712f87d3eb4700e3c7184fcee62cac39fb35ee Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/__pycache__/reasoning_general_pipeline.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/__pycache__/text_conversation_synthesis_pipeline.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/__pycache__/text_conversation_synthesis_pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..520d04f262bb9b552ee78c8978103209cd61cd90 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/__pycache__/text_conversation_synthesis_pipeline.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/__pycache__/text_sft_synthesis_from_scratch.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/__pycache__/text_sft_synthesis_from_scratch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7737b8bf01c70389cebcf215b42c048e8f54e7e8 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/__pycache__/text_sft_synthesis_from_scratch.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/__pycache__/text_sft_synthesis_from_seed.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/__pycache__/text_sft_synthesis_from_seed.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a17794b79e4a2abf1d83616089b745e2e6edbb3 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/__pycache__/text_sft_synthesis_from_seed.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/__pycache__/vqa.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/__pycache__/vqa.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..736f612b66fd5986cd873445f1372daad20c61ee Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/__pycache__/vqa.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/format_str_prompt_generator/__pycache__/double_column_input.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/format_str_prompt_generator/__pycache__/double_column_input.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..681789957cdd9d43c582e8fd56ffed511a84af43 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/format_str_prompt_generator/__pycache__/double_column_input.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/format_str_prompt_generator/double_column_input.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/format_str_prompt_generator/double_column_input.py new file mode 100644 index 0000000000000000000000000000000000000000..67e77448de297ea58b45f72c8fc4df5603089305 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/format_str_prompt_generator/double_column_input.py @@ -0,0 +1,40 @@ +from dataflow.operators.core_text import FormatStrPromptedGenerator +from dataflow.serving import APILLMServing_request +from dataflow.utils.storage import FileStorage + +from dataflow.prompts.core_text import FormatStrPrompt + + +class DoubleColumnInputTestCase(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/core_text_data/double_column_input.json", + file_name_prefix="double_column_input", + cache_path="./cache", + cache_type="jsonl", + ) + + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o" + ) + + self.prompt_template = FormatStrPrompt( + f_str_template="What does a {input_role} like to {input_term}?" + ) + self.operator = FormatStrPromptedGenerator( + llm_serving=self.llm_serving, + prompt_template=self.prompt_template + ) + + def forward(self): + self.operator.run( + storage=self.storage.step(), + input_role="role", + input_term="term", + output_key="answer", + ) +if __name__ == "__main__": + + model = DoubleColumnInputTestCase() + model.forward() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/kbcleaning_pipeline_vllm.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/kbcleaning_pipeline_vllm.py new file mode 100644 index 0000000000000000000000000000000000000000..6a4a225df5482dbfc0043463a3f5c5bd04c3ec57 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/kbcleaning_pipeline_vllm.py @@ -0,0 +1,82 @@ +from dataflow.operators.knowledge_cleaning import ( + KBCChunkGenerator, + FileOrURLToMarkdownConverterFlash, + KBCTextCleaner, + # KBCMultiHopQAGenerator, +) +from dataflow.operators.core_text import Text2MultiHopQAGenerator +from dataflow.utils.storage import FileStorage +from dataflow.serving import LocalModelLLMServing_vllm + +class KBCleaning_PDFvllm_GPUPipeline(): + def __init__(self): + + self.storage = FileStorage( + first_entry_file_name="../example_data/KBCleaningPipeline/kbc_test.jsonl", + cache_path="./.cache/gpu", + file_name_prefix="knowledge_cleaning_step_vllm_engine_playground", + cache_type="json", + ) + + self.knowledge_cleaning_step1 = FileOrURLToMarkdownConverterFlash( + intermediate_dir="../example_data/KBCleaningPipeline/flash/", + mineru_model_path="/MinerU2.5-2509-1.2B", # !!! place your local model path here !!! + # https://huggingface.co/opendatalab/MinerU2.5-2509-1.2B. + batch_size=4, # batchsize per vllm worker + replicas=1, # num of vllm workers + num_gpus_per_replica=0.5, # for ray to schedule vllm workers to GPU, can be float, e.g. 0.5 means each worker uses half GPU, 1 means each worker uses whole GPU + engine_gpu_util_rate_to_ray_cap=0.9 # actuall GPU utilization for each worker; acturall memory per worker= num_gpus_per_replica * engine_gpu_util_rate_to_ray_cap; this is to avoid OOM, you can set it to 0.9 or 0.8 to leave some buffer for other processes on + ) + + self.knowledge_cleaning_step2 = KBCChunkGenerator( + split_method="token", + chunk_size=512, + tokenizer_name="Qwen/Qwen2.5-7B-Instruct", + ) + + def forward(self): + self.knowledge_cleaning_step1.run( + storage=self.storage.step(), + # input_key= + # output_key= + ) + + self.knowledge_cleaning_step2.run( + storage=self.storage.step(), + # input_key= + # output_key= + ) + + self.llm_serving = LocalModelLLMServing_vllm( + hf_model_name_or_path="Qwen/Qwen2.5-7B-Instruct", + vllm_max_tokens=2048, + vllm_tensor_parallel_size=4, + vllm_gpu_memory_utilization=0.6, + vllm_repetition_penalty=1.2 + ) + + self.knowledge_cleaning_step3 = KBCTextCleaner( + llm_serving=self.llm_serving, + lang="en" + ) + + self.knowledge_cleaning_step4 = Text2MultiHopQAGenerator( + llm_serving=self.llm_serving, + lang="en", + num_q = 5 + ) + + self.knowledge_cleaning_step3.run( + storage=self.storage.step(), + # input_key= + # output_key= + ) + self.knowledge_cleaning_step4.run( + storage=self.storage.step(), + # input_key= + # output_key= + ) + +if __name__ == "__main__": + model = KBCleaning_PDFvllm_GPUPipeline() + model.forward() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/materials/__pycache__/mat_names_df.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/materials/__pycache__/mat_names_df.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfacdd10656fb14d69c19c0a735ed025825c183f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/materials/__pycache__/mat_names_df.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/materials/__pycache__/mat_prop1_df.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/materials/__pycache__/mat_prop1_df.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4cfb7f7370aa706ddb7106e8e9ff2c376cb7749 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/materials/__pycache__/mat_prop1_df.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/materials/__pycache__/mat_recipe_df.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/materials/__pycache__/mat_recipe_df.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..729a738149fa85b8b42f4ebb76edca44bafdb451 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/materials/__pycache__/mat_recipe_df.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/materials/mat_names_df.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/materials/mat_names_df.py new file mode 100644 index 0000000000000000000000000000000000000000..90d88104f7060f81336e42603585c7b0551241d0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/materials/mat_names_df.py @@ -0,0 +1,69 @@ +from dataflow.operators.core_text import PromptedGenerator +from dataflow.operators.chemistry import EvaluateSmilesEquivalence + +from dataflow.serving import APILLMServing_request +from dataflow.utils.storage import FileStorage +from dataflow.prompts.chemistry import ExtractSmilesFromTextPrompt + +prompt = """You are an expert in materials science. You need analyze the composition and synthesis/process of the materials and extract the material names from the text. + Follow these rules strictly: + 1. For composition and synthesis process analysis: + - Describe all materials and their contents, synthesis process, etc. you find in the text, like: + Base materials: Material1, Material2, Material3 + Modifiers identified: Additive with contents of 1 mass%, 3 mass%, and 5 mass% + Additional components: Curing agent, etc. + Synthesis: The materials were synthesized by mixing the base materials and modifiers. + Process: The materials were annealed at 1000°C for 1 hour. + + 2. For material names: + - List all materials that were actually tested, following these rules strictly, only use to distinguish different materials: + - Include only materials with measured properties, this rule has priority over the other rules. + - Use the abbreviations of sample provided by the author if possible, such as P1, P2, P3, etc. + - If no name is provided, generate a unique name based on the composition and synthesis process. The process is not required, and only needed when different materials with different processes are tested. + - The name should be as concise as possible, and should not be too long. + - If the text is not related to materials, return empty string. + + 3. For material types: + - List the material type corresponding to each material listed above in material names. + - Use "linear" or "cross_linked" to indicate the structure of polymers, instead of "polymer". + - If the polymer structure ("linear" or "cross_linked") is not specified, default to "cross_linked". + - Ensure the number of material types matches the number of material names. + Do not include explanations, markdown formatting, or code fences (```). + """ + +class ExtractSmiles(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/chemistry/matched_sample_10.json", + #first_entry_file_name="/Users/lianghao/Desktop/dataflow_code/test_dataflow/test/matched_sample_10.json", + cache_path="./cache_all_1", + file_name_prefix="math_QA", + cache_type="json", + ) + self.model_cache_dir = './dataflow_cache' + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=200, + response_format = "" + ) + self.prompt_generator = PromptedGenerator( + llm_serving = self.llm_serving, + system_prompt=prompt + ) + self.smile_eval = EvaluateSmilesEquivalence() + + def forward(self): + # Initial filters + self.prompt_generator.run( + storage = self.storage.step(), + input_key = "text", + output_key = "synth" + ) + + +if __name__ == "__main__": + # This is the entry point for the pipeline + + model = ExtractSmiles() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/materials/mat_prop1_df.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/materials/mat_prop1_df.py new file mode 100644 index 0000000000000000000000000000000000000000..3527180267a9a2c72e255287f372b3b8c663a49a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/materials/mat_prop1_df.py @@ -0,0 +1,74 @@ +from dataflow.operators.core_text import PromptedGenerator +from dataflow.operators.chemistry import EvaluateSmilesEquivalence + +from dataflow.serving import APILLMServing_request +from dataflow.utils.storage import FileStorage +from dataflow.prompts.chemistry import ExtractSmilesFromTextPrompt + +base_prompt = """You are an expert in polymer materials. + Several polymers are mentioned in this article. + Your task is to extract the following glass transition temperature (Tg)–related information for each polymer as explicitly stated in the article only (do not use general knowledge or cited references). + If any information is not present in the article, leave the corresponding cell empty. + + Field descriptions: + - name: material name. + - tg: The glass transition temperature of the polymer, including its unit (e.g. "250 °C"). + - method: The method used to measure Tg (e.g. DSC, DMA). + - parameter: Experimental parameters of the Tg measurement, such as scan cycle, scan range, heating rate, frequency, etc. Do not include parameters unrelated to Tg measurements (e.g. cure process parameters). + - instrument: The model of the device used to measure Tg. + - tg_note: Supplementary information for the Tg data, such as the state of the material, synthesis process, test process, cycle number, or other remarks. + + Output format: + Return the result as a raw CSV table with the header: name,tg,method,parameter,instrument,tg_note + + Requirments: + - List each polymer as one separate row under the header. + - If multiple variants or versions of the same polymer are tested under different conditions, list all combinations as separate rows (e.g. Cartesian product if applicable). + - Do not output JSON, Markdown, or any extra explanatory text. + - Do not add any text before or after the CSV table. + - For each material, if there is no Tg data, do not output the material. + + Example output: + name,tg,method,parameter,instrument,tg_note + Polymer A,250 °C,DSC,5 °C/min to 400 °C,TA Q200,as-cured + Polymer B,180 °C,DMA,1 Hz; 3 °C/min,TA Q800,cured 2 h at 180 °C + """ + +system_prompt = base_prompt + f"\nThis rule has the highest priority: Only extract information for the following materials:\n \"meta-meta-linked BPDA-ODA PAE\", \"meta-para-linked BPDA-ODA PAE\", \"para-para-linked BPDA-ODA PAE\", \"mixed BPDA-ODA PAE\" " + +class ExtractSmiles(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/chemistry/matched_sample_10.json", + #first_entry_file_name="/Users/lianghao/Desktop/dataflow_code/test_dataflow/test/matched_sample_10.json", + cache_path="./cache_all_2", + file_name_prefix="math_QA", + cache_type="json", + ) + self.model_cache_dir = './dataflow_cache' + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=200, + response_format = "" + ) + self.prompt_generator = PromptedGenerator( + llm_serving = self.llm_serving, + system_prompt=system_prompt + ) + self.smile_eval = EvaluateSmilesEquivalence() + + def forward(self): + # Initial filters + self.prompt_generator.run( + storage = self.storage.step(), + input_key = "text", + output_key = "synth" + ) + + +if __name__ == "__main__": + # This is the entry point for the pipeline + + model = ExtractSmiles() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/materials/mat_recipe_df.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/materials/mat_recipe_df.py new file mode 100644 index 0000000000000000000000000000000000000000..f5b2081c2704f88844f8a12e67a63934e45542c5 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/materials/mat_recipe_df.py @@ -0,0 +1,121 @@ +from dataflow.operators.core_text import PromptedGenerator +from dataflow.operators.chemistry import EvaluateSmilesEquivalence + +from dataflow.serving import APILLMServing_request +from dataflow.utils.storage import FileStorage +from dataflow.prompts.chemistry import ExtractSmilesFromTextPrompt + +prompt = """Extract the polyimide recipe information from the text and format it as a structured JSON object. + Follow these rules strictly: + Only use the name in "meta-meta-linked BPDA-ODA PAE", "meta-para-linked BPDA-ODA PAE", "para-para-linked BPDA-ODA PAE", "mixed BPDA-ODA PAE" + 1. For name: + - Use the sample name if provided, otherwise generate a name based on the dianhydride and diamine + - Example: "PI-1" or "PI-2" + + 2. For dianhydride and diamine: + - Use ComponentInfo structure with components array and ratio array + - All ratios are molar ratios + - List all monomers in components array + - List corresponding molar ratios in ratio array + - Use abbreviation of the monomer name if possible + - Example for dianhydride: {{ + "components": ["4-ODA", "6-FDA"], + "ratio": [1, 1] + }} + - Example for single monomer: {{ + "components": ["6-FDA"], + "ratio": [1] + }} + + 3. General rules: + + - Extract ALL recipes mentioned in the text + - Each recipe should have a unique name + - If multiple recipes are mentioned, return them as a list in the "recipes" field + - Do not include any polyimide name from references + - If the text is not related to polyimide, return empty string + + Example input texts and their corresponding outputs: + + 1. Simple case: + Input: "The polyimide PI-1 was synthesized from 4-ODA and 6-FDA (1:1) with HPMDA and 3,4'-ODA (1:1)." + Output: + [ + {{ + "name": "PI-1", + "dianhydride": {{ + "components": ["4-ODA", "6-FDA"], + "ratio": [1, 1] + }}, + "diamine": {{ + "components": ["HPMDA", "3,4'-ODA"], + "ratio": [1, 1] + }} + }} + ] + + 2. Multiple recipes case: + Input: "Two polyimides were prepared: (1) PI-1 from 6-FDA and ODA (1:1), and (2) PI-2 from PMDA and PDA (1:1)." + Output: + [ + {{ + "name": "PI-1", + "dianhydride": {{ + "components": ["6-FDA"], + "ratio": [1] + }}, + "diamine": {{ + "components": ["ODA"], + "ratio": [1] + }} + }}, + {{ + "name": "PI-2", + "dianhydride": {{ + "components": ["PMDA"], + "ratio": [1] + }}, + "diamine": {{ + "components": ["PDA"], + "ratio": [1] + }} + }} + ] + """ + +class ExtractSmiles(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/chemistry/matched_sample_10.json", + #first_entry_file_name="/Users/lianghao/Desktop/dataflow_code/test_dataflow/test/matched_sample_10.json", + cache_path="./cache_all_3", + file_name_prefix="math_QA", + cache_type="json", + ) + self.model_cache_dir = './dataflow_cache' + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gemini-2.5-flash", + max_workers=200, + response_format = "" + ) + self.prompt_generator = PromptedGenerator( + llm_serving = self.llm_serving, + system_prompt=prompt + ) + self.smile_eval = EvaluateSmilesEquivalence() + + def forward(self): + # Initial filters + self.prompt_generator.run( + storage = self.storage.step(), + input_key = "text", + output_key = "synth" + ) + + +if __name__ == "__main__": + # This is the entry point for the pipeline + + model = ExtractSmiles() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/mathbook_extract.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/mathbook_extract.py new file mode 100644 index 0000000000000000000000000000000000000000..33b43c124e23318e5067526bf3e50b10f1810154 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/mathbook_extract.py @@ -0,0 +1,45 @@ +from dataflow.operators.knowledge_cleaning import MathBookQuestionExtract +from dataflow.serving import APIVLMServing_openai + +class QuestionExtractPipeline: + def __init__(self, + llm_serving: APIVLMServing_openai, + api_url: str = "https://api.openai.com/v1", # end with /v1 + key_name_of_api_key: str = "DF_API_KEY", # set in environment first: export DF_API_KEY="your_openai_api_key" + model_name: str = "o4-mini", + max_workers: int = 20 + ): + self.extractor = MathBookQuestionExtract( + llm_serving=llm_serving, + key_name_of_api_key=key_name_of_api_key, + model_name=model_name, + max_workers=max_workers + ) + self.test_pdf = "../example_data/PDF2VQAPipeline/questionextract_test.pdf" + + def forward( + self, + pdf_path: str, + output_name: str, + output_dir: str, + ): + self.extractor.run( + storage=None, + input_pdf_file_path=pdf_path, + output_file_name=output_name, + output_folder=output_dir + ) + +if __name__ == "__main__": + llm_serving = APIVLMServing_openai( + api_url="https://api.openai.com/v1", + model_name="o4-mini", + max_workers=20 + ) + + pipeline = QuestionExtractPipeline(llm_serving=llm_serving) + pipeline.forward( + pdf_path=pipeline.test_pdf, + output_name="test_question_extract", + output_dir="./output" + ) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/abbreviation_qa_api.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/abbreviation_qa_api.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c9fdba58d066be0b85d56f35dc8ca3220b3073d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/abbreviation_qa_api.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/abbreviation_qa_local.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/abbreviation_qa_local.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..039e0ef9c5f5faeedea5829d49afd065a7fdd5d7 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/abbreviation_qa_local.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/generate_qa_api.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/generate_qa_api.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e3ed0d5effcd980bc4f55cdff0c7f561e575be1 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/generate_qa_api.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/generate_qa_local.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/generate_qa_local.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83c042c75483ddabf1bc4f65b38014653ee303da Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/generate_qa_local.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/retrieval_api.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/retrieval_api.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e47bc17dd72dd26460a8a8d26efaa8418c348f50 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/retrieval_api.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/translation_api.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/translation_api.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56951f6316f1d9c87b0824afae3326faf883256c Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/translation_api.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/translation_api_json_schema.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/translation_api_json_schema.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..618d9bfa9c17a22320a07a992dbeac4d509b623a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/translation_api_json_schema.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/translation_litellm.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/translation_litellm.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..884e39bd6011a3b55ad0f486ade4f249d036a854 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/translation_litellm.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/translation_litellm_json_schema.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/translation_litellm_json_schema.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9e7060a4a98864301ca9f47297a63aaa42c52df Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/translation_litellm_json_schema.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/translation_local.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/translation_local.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57286af4d1d32d160ae7568e0411f120481deeba Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/translation_local.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/translation_local_json_schema.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/translation_local_json_schema.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a938308b07b3429aae5dffb548dd18a2c81d6b20 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/__pycache__/translation_local_json_schema.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/abbreviation_qa_api.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/abbreviation_qa_api.py new file mode 100644 index 0000000000000000000000000000000000000000..a052f7d5e6c395a77943a0feac1592af5a81c1fd --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/abbreviation_qa_api.py @@ -0,0 +1,36 @@ +from dataflow.operators.core_text import PromptedGenerator +from dataflow.serving import APILLMServing_request +from dataflow.utils.storage import FileStorage + +class GPT_generator(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/GeneralTextPipeline/abbreviation.jsonl", + cache_path="./cache", + file_name_prefix="math_QA", + cache_type="jsonl", + ) + self.model_cache_dir = './dataflow_cache' + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=2 + ) + self.prompt_generator = PromptedGenerator( + llm_serving = self.llm_serving, + system_prompt = "Please rewrite the following paragraph into a concise summary that preserves the core meaning and key information:", # System prompt for math problem solving + ) + + def forward(self): + # Initial filters + self.prompt_generator.run( + storage = self.storage.step(), + input_key = "raw_content", + ) + + +if __name__ == "__main__": + # This is the entry point for the pipeline + + model = GPT_generator() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/abbreviation_qa_local.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/abbreviation_qa_local.py new file mode 100644 index 0000000000000000000000000000000000000000..09ce20528f8c3e9cf4ee77718f784487e721855d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/abbreviation_qa_local.py @@ -0,0 +1,37 @@ +from dataflow.operators.core_text import PromptedGenerator +from dataflow.serving import LocalModelLLMServing_vllm +from dataflow.utils.storage import FileStorage + +class Qwen_generator(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/GeneralTextPipeline/abbreviation.jsonl", + cache_path="./cache", + file_name_prefix="math_QA", + cache_type="jsonl", + ) + self.model_cache_dir = './dataflow_cache' + self.llm_serving = LocalModelLLMServing_vllm( + hf_model_name_or_path="Qwen2.5-7B-Instruct", # set to your own model path + vllm_tensor_parallel_size=1, + vllm_max_tokens=8192, + ) + + self.prompt_generator = PromptedGenerator( + llm_serving = self.llm_serving, + system_prompt = "Please rewrite the following paragraph into a concise summary that preserves the core meaning and key information:", # System prompt for math problem solving + ) + + def forward(self): + # Initial filters + self.prompt_generator.run( + storage = self.storage.step(), + input_key = "raw_content", + ) + + +if __name__ == "__main__": + # This is the entry point for the pipeline + + model = Qwen_generator() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/generate_qa_api.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/generate_qa_api.py new file mode 100644 index 0000000000000000000000000000000000000000..64f692d4d004d643b4911ccccf138639959a2c39 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/generate_qa_api.py @@ -0,0 +1,36 @@ +from dataflow.operators.core_text import PromptedGenerator +from dataflow.serving import APILLMServing_request +from dataflow.utils.storage import FileStorage + +class GPT_generator(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/GeneralTextPipeline/math_100.jsonl", + cache_path="./cache", + file_name_prefix="math_QA", + cache_type="jsonl", + ) + self.model_cache_dir = './dataflow_cache' + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=2 + ) + self.prompt_generator = PromptedGenerator( + llm_serving = self.llm_serving, + system_prompt = "Please solve this math problem.", # System prompt for math problem solving + ) + + def forward(self): + # Initial filters + self.prompt_generator.run( + storage = self.storage.step(), + input_key = "problem", + ) + + +if __name__ == "__main__": + # This is the entry point for the pipeline + + model = GPT_generator() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/generate_qa_local.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/generate_qa_local.py new file mode 100644 index 0000000000000000000000000000000000000000..892a7517b4d2ccd4c910e912ceb7f4883aa57377 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/generate_qa_local.py @@ -0,0 +1,37 @@ +from dataflow.operators.core_text import PromptedGenerator +from dataflow.serving import LocalModelLLMServing_vllm +from dataflow.utils.storage import FileStorage + +class Qwen_generator(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/GeneralTextPipeline/math_100.jsonl", + cache_path="./cache", + file_name_prefix="math_QA", + cache_type="jsonl", + ) + self.model_cache_dir = './dataflow_cache' + self.llm_serving = LocalModelLLMServing_vllm( + hf_model_name_or_path="Qwen2.5-7B-Instruct", # set to your own model path + vllm_tensor_parallel_size=1, + vllm_max_tokens=8192, + ) + + self.prompt_generator = PromptedGenerator( + llm_serving = self.llm_serving, + system_prompt = "Please solve this math problem.", # System prompt for math problem solving + ) + + def forward(self): + # Initial filters + self.prompt_generator.run( + storage = self.storage.step(), + input_key = "problem", + ) + + +if __name__ == "__main__": + # This is the entry point for the pipeline + + model = Qwen_generator() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/retrieval_api.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/retrieval_api.py new file mode 100644 index 0000000000000000000000000000000000000000..892e9f9eb9a01e47c9f69a4d6a3bb7111a443d02 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/retrieval_api.py @@ -0,0 +1,40 @@ +from dataflow.logger import get_logger +from dataflow.operators.core_text import RetrievalGenerator +from dataflow.utils.storage import FileStorage +from dataflow.serving import LightRAGServing +import asyncio + +class RAG(): + def __init__(self, docs): + self.storage = FileStorage( + first_entry_file_name="./paperquestion.jsonl", + cache_path="./cache", + file_name_prefix="paper_question", + cache_type="jsonl", + ) + + self.model_cache_dir = './dataflow_cache' + self.llm_serving = None + self.retrieval_generator = None + self.docs = docs + + async def initialize(self): + self.llm_serving = await LightRAGServing.create(api_url="https://api.openai.com/v1", document_list=self.docs) + self.retrieval_generator = RetrievalGenerator( + llm_serving = self.llm_serving, + system_prompt="Answer the question based on the text." + ) + + async def forward(self): + await self.retrieval_generator.run( + storage=self.storage.step() + ) + +async def main(): + doc = ["./text1.txt"] + model = RAG(doc) + await model.initialize() + await model.forward() + +if __name__ == "__main__": + asyncio.run(main()) \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/translation_api.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/translation_api.py new file mode 100644 index 0000000000000000000000000000000000000000..4b9dc27f2c653bbf836b1f3e10e3402580afd208 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/translation_api.py @@ -0,0 +1,35 @@ +from dataflow.operators.core_text import PromptedGenerator +from dataflow.serving import APILLMServing_request +from dataflow.utils.storage import FileStorage + +class GPT_generator(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/GeneralTextPipeline/translation.jsonl", + cache_path="./cache", + file_name_prefix="translation", + cache_type="jsonl", + ) + self.model_cache_dir = './dataflow_cache' + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=2 + ) + self.prompt_generator = PromptedGenerator( + llm_serving = self.llm_serving, + system_prompt = "Please translate to Chinese.", # System prompt for translation + ) + + def forward(self): + # Initial filters + self.prompt_generator.run( + storage = self.storage.step(), + input_key = "raw_content", + ) + +if __name__ == "__main__": + # This is the entry point for the pipeline + + model = GPT_generator() + model.forward() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/translation_api_json_schema.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/translation_api_json_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..3db11f8299b45adfd5a9bb789621dd3f894b5f9f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/translation_api_json_schema.py @@ -0,0 +1,44 @@ +from dataflow.operators.core_text import PromptedGenerator +from dataflow.serving import APILLMServing_request +from dataflow.utils.storage import FileStorage + +class GPT_generator(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/GeneralTextPipeline/translation.jsonl", + cache_path="./cache", + file_name_prefix="translation", + cache_type="jsonl", + ) + self.model_cache_dir = './dataflow_cache' + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=2 + ) + self.prompt_generator = PromptedGenerator( + llm_serving = self.llm_serving, + system_prompt = "Please translate to Chinese.Please answer in JSON format.", + json_schema = { + "type": "object", + "properties": { + "original": {"type": "string"}, + "translation": {"type": "string"} + }, + "required": ["original", "translation"], + "additionalProperties": False + } + ) + + def forward(self): + # Initial filters + self.prompt_generator.run( + storage = self.storage.step(), + input_key = "raw_content", + ) + +if __name__ == "__main__": + # This is the entry point for the pipeline + + model = GPT_generator() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/translation_litellm.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/translation_litellm.py new file mode 100644 index 0000000000000000000000000000000000000000..7533ef36894250bb7fdd95135c0d03a556315bb0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/translation_litellm.py @@ -0,0 +1,39 @@ +from dataflow.operators.core_text import PromptedGenerator +from dataflow.serving import APILLMServing_request, LiteLLMServing +from dataflow.utils.storage import FileStorage + +class GPT_generator(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name= "../example_data/GeneralTextPipeline/translation.jsonl", + cache_path="./cache", + file_name_prefix="translation", + cache_type="jsonl", + ) + self.model_cache_dir = './dataflow_cache' + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=10, + # custom_llm_provider="openai", # if your are using custom llm provider's api + ) + + self.prompt_generator = PromptedGenerator( + llm_serving = self.llm_serving, + system_prompt = "Please translate to Chinese.", + + ) + + def forward(self): + # Initial filters + self.prompt_generator.run( + storage = self.storage.step(), + input_key = "raw_content", + ) + + +if __name__ == "__main__": + # This is the entry point for the pipeline + + model = GPT_generator() + model.forward() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/translation_litellm_json_schema.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/translation_litellm_json_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..8232dc3cc0cf60a02312eb08f9085f1c901c1b39 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/translation_litellm_json_schema.py @@ -0,0 +1,47 @@ +from dataflow.operators.core_text import PromptedGenerator +from dataflow.serving import APILLMServing_request, LiteLLMServing +from dataflow.utils.storage import FileStorage + +class GPT_generator(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name= "../example_data/GeneralTextPipeline/translation.jsonl", + cache_path="./cache", + file_name_prefix="translation", + cache_type="jsonl", + ) + self.model_cache_dir = './dataflow_cache' + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=10, + # custom_llm_provider="openai", # if your are using custom llm provider's api + ) + + self.prompt_generator = PromptedGenerator( + llm_serving = self.llm_serving, + system_prompt = "Please translate to Chinese. Please answer in JSON format.", + json_schema={ + "type": "object", + "properties": { + "original": {"type": "string"}, + "translation": {"type": "string"} + }, + "required": ["original", "translation"], + "additionalProperties": False, + }, + ) + + def forward(self): + # Initial filters + self.prompt_generator.run( + storage = self.storage.step(), + input_key = "raw_content", + ) + + +if __name__ == "__main__": + # This is the entry point for the pipeline + + model = GPT_generator() + model.forward() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/translation_local.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/translation_local.py new file mode 100644 index 0000000000000000000000000000000000000000..f1d683757aaac47b6795c6157656ffe18e8a1f11 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/translation_local.py @@ -0,0 +1,35 @@ +from dataflow.operators.core_text import PromptedGenerator +from dataflow.serving import LocalModelLLMServing_vllm +from dataflow.utils.storage import FileStorage + +class Qwen_generator(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/GeneralTextPipeline/translation.jsonl", + cache_path="./cache", + file_name_prefix="translation", + cache_type="jsonl", + ) + self.model_cache_dir = './dataflow_cache' + self.llm_serving = LocalModelLLMServing_vllm( + hf_model_name_or_path="Qwen2.5-7B-Instruct", # set to your own model path + vllm_tensor_parallel_size=1, + vllm_max_tokens=8192, + ) + self.prompt_generator = PromptedGenerator( + llm_serving = self.llm_serving, + system_prompt = "Please translate to Chinese.", # System prompt for translation + ) + + def forward(self): + # Initial filters + self.prompt_generator.run( + storage = self.storage.step(), + input_key = "raw_content", + ) + +if __name__ == "__main__": + # This is the entry point for the pipeline + + model = Qwen_generator() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/translation_local_json_schema.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/translation_local_json_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..88df4e95f27f0623bed5df842c25020199c88f3f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/prompted_generator/translation_local_json_schema.py @@ -0,0 +1,43 @@ +from dataflow.operators.core_text import PromptedGenerator +from dataflow.serving import LocalModelLLMServing_vllm +from dataflow.utils.storage import FileStorage + +class Qwen_generator(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/GeneralTextPipeline/translation.jsonl", + cache_path="./cache", + file_name_prefix="translation", + cache_type="jsonl", + ) + self.model_cache_dir = './dataflow_cache' + self.llm_serving = LocalModelLLMServing_vllm( + hf_model_name_or_path="Qwen2.5-7B-Instruct", # set to your own model path + vllm_tensor_parallel_size=1, + vllm_max_tokens=8192, + ) + self.prompt_generator = PromptedGenerator( + llm_serving = self.llm_serving, + system_prompt = "Please translate to Chinese.", # System prompt for translation + json_schema={ + "type": "object", + "properties": { + "original": {"type": "string"}, + "translation": {"type": "string"} + }, + "required": ["original", "translation"], + }, + ) + + def forward(self): + # Initial filters + self.prompt_generator.run( + storage = self.storage.step(), + input_key = "raw_content", + ) + +if __name__ == "__main__": + # This is the entry point for the pipeline + + model = Qwen_generator() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/quick_evaluate.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/quick_evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..76cf8fb23743430c2046cb662c63649c2b8a6574 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/quick_evaluate.py @@ -0,0 +1,28 @@ +from dataflow.operators.text_pt import MetaSampleEvaluator +from dataflow.serving import APILLMServing_request +from dataflow.utils.storage import FileStorage + +class QuickEvaluatePipeline(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/GeneralTextPipeline/pt_input.jsonl", + cache_path="./cache", + file_name_prefix="dataflow_cache_step_langc", + cache_type="jsonl", + ) + self.llm_serving = APILLMServing_request( + api_url="http://123.129.219.111:3000/v1/chat/completions", + model_name="gpt-4o" + ) + self.meta_scorer = MetaSampleEvaluator(llm_serving=self.llm_serving) + + + def forward(self): + self.meta_scorer.run( + self.storage.step(), + input_key='raw_content' + ) + +if __name__ == "__main__": + pipeline = QuickEvaluatePipeline() + pipeline.forward() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/reasoning_general_pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/reasoning_general_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..92f533c874773610579087a17534a0d97e417e24 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/reasoning_general_pipeline.py @@ -0,0 +1,89 @@ +from dataflow.operators.reasoning import ( + ReasoningQuestionGenerator, + ReasoningAnswerGenerator, +) +from dataflow.operators.reasoning import ReasoningQuestionFilter, ReasoningAnswerNgramFilter, ReasoningAnswerModelJudgeFilter +from dataflow.utils.storage import FileStorage +from dataflow.serving import APILLMServing_request +from dataflow.core import LLMServingABC +from dataflow.prompts.reasoning.general import ( + GeneralQuestionFilterPrompt, + GeneralAnswerGeneratorPrompt, + GeneralQuestionSynthesisPrompt, +) +from dataflow.prompts.model_evaluation.general import AnswerJudgePrompt + +class GeneralReasoning_APIPipeline(): + def __init__(self, llm_serving: LLMServingABC = None): + + self.storage = FileStorage( + first_entry_file_name="../example_data/ReasoningPipeline/pipeline_general.json", + cache_path="./cache_local", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + + # use API server as LLM serving + self.llm_serving = APILLMServing_request( + api_url="http://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=30 + ) + + self.question_filter_step1 = ReasoningQuestionFilter( + system_prompt="You are an expert in evaluating mathematical problems. Follow the user's instructions strictly and output your final judgment in the required JSON format.", + llm_serving=self.llm_serving, + prompt_template=GeneralQuestionFilterPrompt() + ) + + self.question_gen_step2 = ReasoningQuestionGenerator( + num_prompts=1, + llm_serving=self.llm_serving, + prompt_template=GeneralQuestionSynthesisPrompt() + ) + + self.answer_generator_step3 = ReasoningAnswerGenerator( + llm_serving=self.llm_serving, + prompt_template=GeneralAnswerGeneratorPrompt() + ) + self.answer_model_judge_step4 = ReasoningAnswerModelJudgeFilter( + llm_serving=self.llm_serving, + prompt_template=AnswerJudgePrompt(), + keep_all_samples=True + ) + self.answer_ngram_filter_step5 = ReasoningAnswerNgramFilter( + min_score = 0.1, + max_score = 1.0, + ngrams = 5 + ) + + def forward(self): + self.question_filter_step1.run( + storage = self.storage.step(), + input_key = "instruction", + ) + + self.question_gen_step2.run( + storage = self.storage.step(), + input_key = "instruction", + ) + self.answer_generator_step3.run( + storage = self.storage.step(), + input_key = "instruction", + output_key = "generated_cot" + ), + self.answer_model_judge_step4.run( + storage = self.storage.step(), + input_question_key = "instruction", + input_answer_key = "generated_cot", + input_reference_key = "golden_answer" + ), + self.answer_ngram_filter_step5.run( + storage = self.storage.step(), + input_question_key = "instruction", + input_answer_key = "generated_cot" + ) + +if __name__ == "__main__": + pl = GeneralReasoning_APIPipeline() + pl.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/text_conversation_synthesis_pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/text_conversation_synthesis_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..a3302ce9b061b5d406a78c4591226ec43a8ff51c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/text_conversation_synthesis_pipeline.py @@ -0,0 +1,33 @@ +from dataflow.operators.conversations import ConsistentChatGenerator +from dataflow.utils.storage import FileStorage +from dataflow.serving import APILLMServing_request +from dataflow.prompts.general_text import ConsistentChatPrompt + +class TextPipeline(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="", + cache_path="./cache", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + serving = APILLMServing_request( + api_url="http://123.129.219.111:3000/v1/chat/completions", + model_name="gpt-4o", + max_workers=100 + ) + self.model_cache_dir = './dataflow_cache' + self.processor = ConsistentChatGenerator(llm_serving=serving, num_dialogs_per_intent=5, prompt_template=ConsistentChatPrompt()) + + def forward(self): + self.processor.run( + storage=self.storage.step() + ) + +if __name__ == "__main__": + # This is a test entry point for the TextPipeline + # It will run the forward method of the TextPipeline class + # to process the data and generate the output. + print("Running TextPipeline...") + model = TextPipeline() + model.forward() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/text_sft_synthesis_from_scratch.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/text_sft_synthesis_from_scratch.py new file mode 100644 index 0000000000000000000000000000000000000000..b20a9d3111607fe3ec8362021dca73fb365c99a7 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/text_sft_synthesis_from_scratch.py @@ -0,0 +1,45 @@ + +from dataflow.operators.text_sft import AlpagasusFilter +from dataflow.operators.text_sft import CondorGenerator +from dataflow.operators.text_sft import CondorRefiner +from dataflow.prompts.general_text import CondorQuestionPrompt, CondorRefinePrompt +from dataflow.utils.storage import FileStorage +from dataflow.serving import APILLMServing_request + +class TextPipeline(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="", + cache_path="./cache", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + self.model_cache_dir = './dataflow_cache' + self.num_generated_samples = 3 + llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=100 + ) + self.generator = CondorGenerator(llm_serving=llm_serving, num_samples=self.num_generated_samples, prompt_template=CondorQuestionPrompt()) + self.refiner = CondorRefiner(llm_serving=llm_serving, prompt_template=CondorRefinePrompt()) + self.alpagasus_filter = AlpagasusFilter(min_score=3,max_score=5,llm_serving=llm_serving) + + def forward(self): + self.generator.run( + storage=self.storage.step() + ) + self.refiner.run( + storage=self.storage.step(), + input_instruction_key='instruction', + input_output_key='output' + ) + self.alpagasus_filter.run( + storage=self.storage.step(), + input_instruction_key='instruction', + input_input_key="input", + input_output_key='output' + ) + +model = TextPipeline() +model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/text_sft_synthesis_from_seed.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/text_sft_synthesis_from_seed.py new file mode 100644 index 0000000000000000000000000000000000000000..98598caa81ad292d2e2714e2dfc9ccb2f8ad58e8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/text_sft_synthesis_from_seed.py @@ -0,0 +1,28 @@ +from dataflow.operators.text_sft import SFTGeneratorSeed +from dataflow.utils.storage import FileStorage +from dataflow.serving import APILLMServing_request + +class TextPipeline(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/GeneralTextPipeline/pt_input.jsonl", + cache_path="./cache", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + self.model_cache_dir = './dataflow_cache' + self.num_generated_samples = 3 + llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=100 + ) + self.generator = SFTGeneratorSeed(llm_serving=llm_serving, custom_prompt="Try to make the question suitable for middle school students.") + + def forward(self): + self.generator.run( + storage=self.storage.step() + ) + +model = TextPipeline() +model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/vqa.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/vqa.py new file mode 100644 index 0000000000000000000000000000000000000000..5259d62a673289c09c31d345780d589653ece060 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/playground/vqa.py @@ -0,0 +1,32 @@ +from dataflow.operators.core_vision import PromptedVQAGenerator +from dataflow.serving import APIVLMServing_openai +from dataflow.utils.storage import FileStorage + +class VQA_generator(): + def __init__(self): + self.prompt = "Describe the image in detail." + self.storage = FileStorage( + first_entry_file_name="../example_data/VQA/pic_path.json", + cache_path="./cache", + file_name_prefix="vqa", + cache_type="json", + ) + self.llm_serving = APIVLMServing_openai( + model_name="o4-mini", + api_url="https://api.openai.com/v1", # openai api url + key_name_of_api_key="DF_API_KEY", + ) + self.vqa_generate = PromptedVQAGenerator( + self.llm_serving, + self.prompt + ) + + def forward(self): + self.vqa_generate.run( + storage = self.storage.step(), + input_key = "raw_content", + ) + +if __name__ == "__main__": + VQA_generator = VQA_generator() + VQA_generator.forward() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/simple_text_pipelines/__pycache__/eval_match.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/simple_text_pipelines/__pycache__/eval_match.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2b725949eee5fbb35571f443e770c1aadb8fd2f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/simple_text_pipelines/__pycache__/eval_match.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/simple_text_pipelines/__pycache__/eval_semantic.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/simple_text_pipelines/__pycache__/eval_semantic.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9bf2c7ecaa34ae9c8e0cdcf2ef97c93a21e15b0d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/simple_text_pipelines/__pycache__/eval_semantic.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/simple_text_pipelines/__pycache__/pt_simple_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/simple_text_pipelines/__pycache__/pt_simple_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f92c55c6d1f49cbb135feb4202e99a8ee9b2ffe6 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/simple_text_pipelines/__pycache__/pt_simple_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/simple_text_pipelines/__pycache__/sft_from_scratch.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/simple_text_pipelines/__pycache__/sft_from_scratch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa0661bcec16ae739dd913258696c86a59d2c758 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/simple_text_pipelines/__pycache__/sft_from_scratch.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/simple_text_pipelines/eval_match.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/simple_text_pipelines/eval_match.py new file mode 100644 index 0000000000000000000000000000000000000000..e6ecfe7d1cdee1cbb91a3d8640f594ac6be5df35 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/simple_text_pipelines/eval_match.py @@ -0,0 +1,91 @@ +""" +本文件用于以字符串匹配的方式做Benchmark评测,主要流程包括: +1. 通过AnswerGenerator生成模型回答(generated_cot); +2. 使用BenchEvaluator进行精确匹配评估,查找测试答案中是否包含标准答案串(match); +3. 评估结果会保存在指定的eval_result_path路径下。 + +使用方法: +1. 设置您自己的提示模板(DIY_PROMPT_ANSWER); +2. 配置您要评估的模型路径(model_paths); +3. 指定评估数据集路径和缓存路径(Benchs); +4. 运行本文件即可自动完成评估流程,最终结果会保存在指定路径下。 +""" +from dataflow.operators.reasoning import ReasoningAnswerGenerator +from dataflow.operators.core_text import BenchDatasetEvaluator +from dataflow.serving import APILLMServing_request, LocalModelLLMServing_vllm +from dataflow.prompts.reasoning.diy import DiyAnswerGeneratorPrompt +from dataflow.utils.storage import FileStorage +from dataflow.core import LLMServingABC + +import os + +""" 3 steps for evaluating your own model using personal bench """ +# Step 1, your own prompt +DIY_PROMPT_ANSWER ="""<|im_start|>system\nPlease reason step by step, and put your final answer within \\boxed{{}}.<|im_end|>\n +<|im_start|>user\n{question}<|im_end|>\n +<|im_start|>assistant\n""" + +# Step 2, your own model path, support multi-model path +model_paths = [ + "Qwen/Qwen2.5-7B-Instruct", +] + +prefixs = [os.path.basename(path) for path in model_paths] + +for prefix, model_path in zip(prefixs, model_paths): +# Step 3, your own bench path, prefix is according to model_path + Benchs = [ + { # every data must include: "question", "answer" + "file_path": "../example_data/core_text_data/bench_eval_data.jsonl", + "cache_path": f"../bench_result/{prefix}_test" + }, + ] +################################################### + +class BenchEvalPipeline(): + def __init__(self, first_entry_file_name: str, cache_path: str, llm_serving: LLMServingABC = None): + self.storage = FileStorage( + first_entry_file_name=first_entry_file_name, + cache_path=cache_path, + file_name_prefix="bench_cache_step", + cache_type="jsonl", + ) + + self.answer_generator_step1 = ReasoningAnswerGenerator( + llm_serving=llm_serving, + prompt_template=DiyAnswerGeneratorPrompt(DIY_PROMPT_ANSWER) + ) + + self.eval_step2 = BenchDatasetEvaluator( + eval_result_path="../eval_result.json", + compare_method="match" + ) + + def forward(self): + + self.answer_generator_step1.run( + storage = self.storage.step(), + input_key = "question", + output_key = "generated_cot" + ), + self.eval_step2.run( + storage=self.storage.step(), + input_test_answer_key="generated_cot", + input_gt_answer_key="answer" + ) + +if __name__ == "__main__": + # use vllm as LLM serving + llm_serving = LocalModelLLMServing_vllm( + hf_model_name_or_path=model_path, # set to your own model path + vllm_tensor_parallel_size=1, + vllm_max_tokens=512, + ) + + for bench in Benchs: + pl = BenchEvalPipeline( + first_entry_file_name=bench["file_path"], + cache_path=bench["cache_path"], + llm_serving=llm_serving + ) + pl.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/simple_text_pipelines/eval_semantic.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/simple_text_pipelines/eval_semantic.py new file mode 100644 index 0000000000000000000000000000000000000000..b32b118b5709511149ee0501d2ac473e0f05f52e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/simple_text_pipelines/eval_semantic.py @@ -0,0 +1,101 @@ +""" +本文件用于以语义匹配的方式做Benchmark评测,主要流程包括: +1. 通过AnswerGenerator生成模型回答(generated_cot); +2. 使用BenchEvaluator进行语义比较评估(semantic); +3. 评估结果会保存在指定的eval_result_path路径下。 + +使用方法: +1. 设置您自己的提示模板(DIY_PROMPT_ANSWER); +2. 配置您要评估的模型路径(model_paths); +3. 指定评估数据集路径和缓存路径(Benchs); +4. 运行本文件即可自动完成评估流程,最终结果会保存在指定路径下。 +""" +from dataflow.operators.reasoning import ReasoningAnswerGenerator +from dataflow.operators.core_text import BenchDatasetEvaluator +from dataflow.serving import APILLMServing_request, LocalModelLLMServing_vllm +from dataflow.prompts.reasoning.diy import DiyAnswerGeneratorPrompt +from dataflow.utils.storage import FileStorage +from dataflow.core import LLMServingABC + +import os + +""" 3 steps for evaluating your own model using personal bench """ + # Step 1, your own prompt +DIY_PROMPT_ANSWER ="""<|im_start|>system\nPlease reason step by step, and put your final answer within \\boxed{{}}.<|im_end|>\n +<|im_start|>user\n{question}<|im_end|>\n +<|im_start|>assistant\n""" + + # Step 2, your own model path, support multi-model path +model_paths = [ + "Qwen/Qwen2.5-7B-Instruct", +] + +prefixs = [os.path.basename(path) for path in model_paths] + +for prefix, model_path in zip(prefixs, model_paths): + # Step 3, your own bench path, prefix is according to model_path + Benchs = [ + { + "file_path": "../example_data/core_text_data/bench_eval_data.jsonl", + "cache_path": f"../bench_result/{prefix}_test" + }, + ] +################################################### + +class SemanticBenchEvalPipeline(): + def __init__(self, first_entry_file_name: str, cache_path: str, llm_serving: LLMServingABC = None, llm_serving_judger: LLMServingABC = None): + self.storage = FileStorage( + first_entry_file_name=first_entry_file_name, + cache_path=cache_path, + file_name_prefix="bench_cache_step", + cache_type="jsonl", + ) + + self.answer_generator_step1 = ReasoningAnswerGenerator( + llm_serving=llm_serving, + prompt_template=DiyAnswerGeneratorPrompt(DIY_PROMPT_ANSWER) + ) + + self.eval_step2 = BenchDatasetEvaluator( + compare_method="semantic", + llm_serving=llm_serving_judger, + prompt_template=None, # using default prompt + eval_result_path="../eval_result.json", + ) + + def forward(self): + + self.answer_generator_step1.run( + storage = self.storage.step(), + input_key = "question", + output_key = "generated_cot" + ), + self.eval_step2.run( + storage=self.storage.step(), + input_question_key="question", + input_test_answer_key="generated_cot", + input_gt_answer_key="answer" + ) + +if __name__ == "__main__": + # use vllm as LLM serving + llm_serving = LocalModelLLMServing_vllm( + hf_model_name_or_path=model_path, # set to your own model path + vllm_tensor_parallel_size=1, + vllm_max_tokens=512, + ) + llm_serving_judger = APILLMServing_request( + api_url="your api url", + model_name="your model name", + max_workers=30 + ) + + for bench in Benchs: + pl = SemanticBenchEvalPipeline( + first_entry_file_name=bench["file_path"], + cache_path=bench["cache_path"], + llm_serving=llm_serving, + llm_serving_judger=llm_serving_judger + ) + pl.forward() + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/simple_text_pipelines/pt_simple_filter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/simple_text_pipelines/pt_simple_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..a7222967553093415a101005297ea9d5270a63cf --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/simple_text_pipelines/pt_simple_filter.py @@ -0,0 +1,201 @@ +""" +本文件主要作用: + - 用于对数据进行自动化质量过滤、精炼。 + - 主要流程包括:初始打分、初筛、精炼。 + - 支持多阶段Prompted LLM打分与数据增强,适用于大规模数据自动清洗与提升。 + +使用说明: + 直接运行本文件,将自动读取指定的原始数据文件,经过多轮筛选与增强,最终输出高质量SFT数据到cache目录。 + 需根据实际环境配置好cache路径与API参数。 + +""" + +import pandas as pd +from dataflow.operators.core_text import PromptedGenerator +from dataflow.operators.core_text import GeneralFilter +from dataflow.utils.storage import FileStorage +from dataflow.serving import APILLMServing_request + +def GetFilterInitScorerPrompt(): + system_prompt = ( + "You are a data quality assessor performing initial content evaluation. " + "Your task is to score content based on information density and basic quality on a scale of 1-5.\n\n" + "Scoring Guidelines:\n" + "• 1: Meaningless/empty content - should be filtered out\n" + "• 2: Minimal useful information - needs significant refinement\n" + "• 3: Basic information present - needs moderate refinement\n" + "• 4: Good information quality - suitable for expansion\n" + "• 5: High-quality, rich information - ideal for expansion\n\n" + "Focus on: information completeness, factual accuracy, and basic coherence. " + "This score determines processing path: 1=filter, 2-3=refine, 4-5=expand.\n\n" + "Respond with only the integer score (1-5)." + ) + + user_prompt = ( + f"Score this content for information quality and completeness (1-5):\n\n" + f"Output format: single integer 1-5, no other text" + ) + return system_prompt + "\n\n" + user_prompt + +def GetFilterRefinerPrompt(): + system_prompt = ( + "You are a specialized content optimization expert tasked with transforming medium-quality data into clear, valuable information. " + "Focus on enhancing clarity, precision, and information density while preserving core meaning.\n\n" + "Core Refinement Principles:\n" + "• Transform vague expressions into specific, actionable statements\n" + "• Eliminate redundant phrases while retaining essential meaning\n" + "• Reorganize content for optimal logical progression\n" + "• Correct linguistic errors and enhance vocabulary precision\n" + "• Bridge information gaps through contextual inference\n" + "• Strengthen connections between related concepts\n" + "• Preserve factual integrity and original author intent\n\n" + "STRICT JSON OUTPUT PROTOCOL:\n" + "1. Input format: JSON object containing multiple data fields\n" + "2. Output requirement: Valid JSON with IDENTICAL field structure\n" + "3. Field preservation: NO addition, deletion, or modification of keys\n" + "4. Format compliance: RAW JSON only - no markdown, comments, or explanatory text\n" + "5. Character handling: Proper escaping of quotes and special characters\n" + "6. Response boundary: Begin with '{' and terminate with '}'\n" + "7. Content validation: Each refined value must be clear and actionable\n\n" + "Processing Example:\n" + "Input: {\"concept\": \"somewhat unclear idea\", \"details\": \"repetitive explanation\"}\n" + "Output: {\"concept\": \"precise, well-defined concept\", \"details\": \"streamlined, focused explanation\"}\n\n" + "Execute refinement and output the enhanced JSON structure immediately." + ) + + user_prompt = ( + f"Refine this medium-quality JSON content to improve clarity and information value. " + f"Respond with ONLY the refined JSON object (no code blocks, no explanations, just the JSON):\n\n" + f"Output format: single valid JSON object only" + ) + return system_prompt + "\n\n" + user_prompt + +def GetFilterRewriterPrompt(): + system_prompt = ( + "You are an advanced content enrichment specialist working with premium-quality source materials. " + "Your mission is to amplify already excellent content by incorporating depth, comprehensive context, and actionable insights.\n\n" + "Strategic Expansion Framework:\n" + "• Integrate practical examples and real-world implementation scenarios\n" + "• Provide comprehensive background context and foundational knowledge\n" + "• Incorporate multiple analytical perspectives and considerations\n" + "• Elaborate on downstream effects and broader implications\n" + "• Enrich with supporting evidence and detailed explanations\n" + "• Establish connections to related domains and interdisciplinary insights\n" + "• Embed actionable guidance and implementation strategies\n" + "• Maintain superior organizational structure and narrative flow\n\n" + "MANDATORY JSON OUTPUT SPECIFICATIONS:\n" + "1. Input structure: JSON object with established field architecture\n" + "2. Output mandate: JSON object maintaining exact key-value structure\n" + "3. Field integrity: Absolute preservation of original field names and hierarchy\n" + "4. Format restrictions: Pure JSON output without markdown, annotations, or commentary\n" + "5. Content expansion: Significantly enrich each field with additional value\n" + "6. Syntax compliance: Validate JSON formatting with proper character escaping\n" + "7. Response parameters: Direct JSON output from '{' to '}'\n\n" + "Transformation Pattern:\n" + "Input: {\"topic\": \"basic concept\", \"description\": \"simple explanation\"}\n" + "Output: {\"topic\": \"comprehensive concept with context, examples, and applications...\", " + "\"description\": \"detailed explanation with multiple perspectives, implications, and practical guidance...\"}\n\n" + "Proceed with comprehensive content expansion and deliver the enriched JSON structure." + ) + + user_prompt = ( + f"Expand the content in this JSON object with additional depth, examples, and context. " + f"Respond with ONLY the expanded JSON object (no code blocks, no explanations, just the JSON):\n\n" + f"Output format: single valid JSON object only" + ) + return system_prompt + "\n\n" + user_prompt + +def GetFilterFinalScorerPrompt(): + system_prompt = ( + "You are a senior content quality evaluator performing final assessment. " + "Rate the processed content on a 1-5 scale for overall excellence and utility.\n\n" + "Final Scoring Criteria:\n" + "• 1: Poor - significant quality issues remain\n" + "• 2: Below standard - limited value or clarity problems\n" + "• 3: Acceptable - meets basic requirements but unremarkable\n" + "• 4: High quality - well-crafted, informative, and valuable\n" + "• 5: Excellent - exceptional content that serves as exemplary reference\n\n" + "Evaluate holistically:\n" + "- Information completeness and accuracy\n" + "- Clarity and readability\n" + "- Practical value and usefulness\n" + "- Structure and logical flow\n" + "- Overall contribution to knowledge/understanding\n\n" + "Only content scoring 4-5 will be retained for final dataset. " + "Be appropriately selective to ensure high standards.\n\n" + "Respond with only the integer score (1-5)." + ) + + user_prompt = ( + f"Provide a final quality score (1-5) for this processed content:\n\n" + f"Output format: single integer 1-5, no other text" + ) + return system_prompt + "\n\n" + user_prompt + + +class PTSimpleFilter: + """ + SFT数据自动过滤与增强主流程 + """ + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/GeneralTextPipeline/pt_input.jsonl", + cache_path="./dataflow_cache", + file_name_prefix="core_filter", + cache_type="jsonl", + ) + llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=100 + ) + + # 各阶段Prompted LLM与过滤器 + self.init_scorer = PromptedGenerator( + llm_serving=llm_serving, + system_prompt=GetFilterInitScorerPrompt() + ) + self.init_filter = GeneralFilter([lambda df: df['init_score'] > 1]) + self.refiner = PromptedGenerator( + llm_serving=llm_serving, + system_prompt=GetFilterRefinerPrompt() + ) + self.rewriter = PromptedGenerator( + llm_serving=llm_serving, + system_prompt=GetFilterRewriterPrompt() + ) + self.final_scorer = PromptedGenerator( + llm_serving=llm_serving, + system_prompt=GetFilterFinalScorerPrompt() + ) + self.final_filter = GeneralFilter([lambda df: df['final_score'] >= 3]) + + def forward(self): + """ + 主流程:初筛-精炼/扩写-终筛-输出 + """ + self.init_scorer.run( + storage=self.storage.step(), + input_key="raw_content", + output_key="init_score" + ) + self.init_filter.run( + storage=self.storage.step(), + ) + self.refiner.run( + storage=self.storage.step(), + input_key="raw_content", + output_key="refine_content" + ) + self.final_scorer.run( + storage=self.storage.step(), + input_key="refine_content", + output_key="final_score" + ) + self.final_filter.run( + storage=self.storage.step() + ) + +if __name__ == "__main__": + model = PTSimpleFilter() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/simple_text_pipelines/sft_from_scratch.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/simple_text_pipelines/sft_from_scratch.py new file mode 100644 index 0000000000000000000000000000000000000000..28de19b4e29a3f5d3e80abf77a12df54ed418082 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/playground/simple_text_pipelines/sft_from_scratch.py @@ -0,0 +1,73 @@ + +from dataflow.operators.text_sft import CondorGenerator +from dataflow.prompts.general_text import CondorQuestionPrompt +from dataflow.operators.core_text import PromptedGenerator,FormatStrPromptedGenerator +from dataflow.operators.core_text import GeneralFilter +from dataflow.utils.storage import FileStorage +from dataflow.serving import APILLMServing_request +from dataflow.prompts.core_text import FormatStrPrompt + +prompt = ( + "You are a senior content quality evaluator performing final assessment. " + "Rate the processed content on a 1-5 scale for overall excellence and utility.\n\n" + "Final Scoring Criteria:\n" + "• 1: Poor - significant quality issues remain\n" + "• 2: Below standard - limited value or clarity problems\n" + "• 3: Acceptable - meets basic requirements but unremarkable\n" + "• 4: High quality - well-crafted, informative, and valuable\n" + "• 5: Excellent - exceptional content that serves as exemplary reference\n\n" + "Evaluate holistically:\n" + "- Information completeness and accuracy\n" + "- Clarity and readability\n" + "- Practical value and usefulness\n" + "- Structure and logical flow\n" + "- Overall contribution to knowledge/understanding\n\n" + "Only content scoring 4-5 will be retained for final dataset. " + "Be appropriately selective to ensure high standards.\n\n" + "Respond with only the integer score (1-5)." + ) +class SFT_From_Scratch(): + def __init__(self): + self.storage = FileStorage( + first_entry_file_name="../example_data/GeneralTextPipeline/empty.jsonl", + cache_path="./cache", + file_name_prefix="dataflow_cache_step", + cache_type="jsonl", + ) + self.model_cache_dir = './dataflow_cache_1' + self.num_generated_samples = 3 + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o", + max_workers=100 + ) + self.instruction_generator = CondorGenerator(llm_serving=self.llm_serving, num_samples=self.num_generated_samples, prompt_template=CondorQuestionPrompt()) + self.answer_generator = PromptedGenerator(llm_serving=self.llm_serving, system_prompt="Please answer this question.") + self.prompt_template = FormatStrPrompt( + f_str_template="Please rate the following SFT data: instruction: {instruction}, output: {output}?" + ) + self.rater = FormatStrPromptedGenerator(llm_serving=self.llm_serving, system_prompt = prompt, prompt_template=self.prompt_template) + self.filter = GeneralFilter([lambda df: df['data_score'] >= 3]) + + def forward(self): + self.instruction_generator.run( + storage=self.storage.step() + ) + self.answer_generator.run( + storage=self.storage.step(), + input_key='instruction', + output_key="output", + ) + self.rater.run( + storage=self.storage.step(), + output_key = "data_score", + instruction = "instruction", + output = "output", + ) + self.filter.run( + storage=self.storage.step(), + ) + +if __name__ == "__main__": + model = SFT_From_Scratch() + model.forward() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/cookiecutter.json b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/cookiecutter.json new file mode 100644 index 0000000000000000000000000000000000000000..ea11901602bd85568a60d81253b2529292ff69a5 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/cookiecutter.json @@ -0,0 +1,25 @@ +{ + "repo_name": "my-dataflow-extension", + "package_name": "my_dataflow_extension", + "author": "Your Name", + "description": "A DataFlow extension with operator + prompt + pipeline", + "init_version": "0.0.1", + "license": [ + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "Proprietary" + ], + "python_version": ["3.10", "3.11", "3.12"], + "include_examples": ["yes", "no"], + "_copy_without_render": [ + ".github/*", + ".github/**/*.yml", + ".github/**/*.yaml", + "*.yml", + "*.yaml" + ], + "__prompts__": { + "include_examples": "Wether include exmaple operator & pipeline & prompt_template files in this DataFlow-extension template?" + } +} diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/hooks/__pycache__/post_gen_project.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/hooks/__pycache__/post_gen_project.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a7c88f0ec123ee19db791070233e06ad79cf287 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/hooks/__pycache__/post_gen_project.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/hooks/post_gen_project.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/hooks/post_gen_project.py new file mode 100644 index 0000000000000000000000000000000000000000..71dc436f5e8d2635c1ce86753af8a972167b0c24 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/hooks/post_gen_project.py @@ -0,0 +1,72 @@ +# --- include_examples: simple & explicit --- +import os +import shutil + +PROJECT_DIR = os.getcwd() +PACKAGE_NAME = "{{ cookiecutter.package_name }}" +INCLUDE_EXAMPLES = "{{ cookiecutter.include_examples }}" + +def clear_dir(path): + """Remove all contents under a directory, but keep the directory itself.""" + if not os.path.isdir(path): + return + for name in os.listdir(path): + p = os.path.join(path, name) + if os.path.isdir(p): + shutil.rmtree(p) + else: + os.remove(p) + +if INCLUDE_EXAMPLES != "yes": + print("Clearing operators / pipelines / prompts directories...") + + base_dirs = [ + os.path.join(PROJECT_DIR, PACKAGE_NAME), + os.path.join(PROJECT_DIR, "src", PACKAGE_NAME), + ] + + for base in base_dirs: + if not os.path.isdir(base): + continue + + for sub in ("operators", "pipelines", "prompts"): + target = os.path.join(base, sub) + if os.path.isdir(target): + clear_dir(target) + print(" cleared:", os.path.relpath(target, PROJECT_DIR)) + + +# License +def read_file(path): + with open(path, "r", encoding="utf-8") as f: + return f.read() + +def write_file(path, content): + with open(path, "w", encoding="utf-8") as f: + f.write(content) + +license_choice = "{{ cookiecutter.license }}" +author = "{{ cookiecutter.author }}" + +# --- handle LICENSE file --- +licenses_dir = "licenses" +target_license_file = "LICENSE" + +if license_choice == "Proprietary": + write_file( + target_license_file, + f"Copyright (c) {author}\n\nAll rights reserved.\n" + ) +else: + license_template = os.path.join(licenses_dir, f"{license_choice}.txt") + if not os.path.exists(license_template): + raise RuntimeError(f"License template not found: {license_template}") + + content = read_file(license_template) + write_file(target_license_file, content) + +# remove licenses directory from generated project +if os.path.isdir(licenses_dir): + shutil.rmtree(licenses_dir) + +print(f"Applied license: {license_choice}") diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/.github/ISSUE_TEMPLATE/1-bug-reports.yaml b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/.github/ISSUE_TEMPLATE/1-bug-reports.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eaf5a261a5ebbb039714ec16c219aabe2ce16562 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/.github/ISSUE_TEMPLATE/1-bug-reports.yaml @@ -0,0 +1,72 @@ +name: "🐞 Bug Report" +description: "Report bugs to help us improve Dataflow. 请报告错误以帮助我们改进 Dataflow。" +labels: + - bug + +body: + - type: checkboxes + id: reminder + attributes: + label: "Reminder / 提示" + description: | + - Please ensure you have carefully searched existing issues before submitting. + - 请确保您已认真搜索过现有的 Issues。 + options: + - label: "I have read the above reminder and searched existing issues. / 我已阅读上述提示并搜索过现有 Issues。" + required: true + + - type: textarea + id: problem-description + attributes: + label: "Problem Description / 问题描述" + description: | + Please describe your issue. + 请描述您的问题。 + placeholder: | + e.g. When I run `dataflow run`, it fails with a segmentation fault. + 例如:当我执行 `dataflow run` 时,出现段错误。 + validations: + required: true + + - type: textarea + id: system-info + attributes: + label: "System Info (`dataflow env`) / 系统信息(`dataflow env`)" + description: | + Please run `dataflow env` in your terminal and paste the full output here. + 请在终端运行 `dataflow env` 并将完整输出粘贴在此处。 + placeholder: | + dataflow version: x.y.z + platform: macOS/Linux/Windows + python version: 3.x.x + validations: + required: true + + - type: textarea + id: reproduction + attributes: + label: "Reproduction Steps & Logs / 重现步骤及日志" + description: | + Provide the entry arguments, error message(s), and full stack trace to help us reproduce the issue. + 请提供入口参数、错误信息和完整的异常堆栈,以便我们复现问题。 + value: | + ```text + # e.g. + $ dataflow run --arg1 foo + Error: ... + Stack trace: + ... + ``` + validations: + required: true + + - type: textarea + id: others + attributes: + label: "Additional Information / 其他补充" + description: | + Any other details, screenshots, or logs that might help. + 任何其他可能有帮助的细节、截图或日志。 + placeholder: Optional + validations: + required: false \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/.github/ISSUE_TEMPLATE/2-ask-for-help.yaml b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/.github/ISSUE_TEMPLATE/2-ask-for-help.yaml new file mode 100644 index 0000000000000000000000000000000000000000..72ac86a791f16415d669f6db4bc663fc4abafd5c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/.github/ISSUE_TEMPLATE/2-ask-for-help.yaml @@ -0,0 +1,59 @@ +name: "🤔 Ask for Help" +description: "Ask for help to others here, like model performance, something won't work. 在这里请求帮助,比如模型表现不佳,某些功能无法使用。" +labels: + - question + +body: + - type: textarea + id: problem-description + attributes: + label: "Problem Description / 问题描述" + description: | + Please describe your question or issue. + 请描述您的问题或困惑。 + placeholder: | + e.g. When I run `dataflow train`, the model accuracy stays at 50%. + 例如:当我执行 `dataflow train` 时,模型准确率一直保持在 50%。 + validations: + required: true + + - type: textarea + id: system-info + attributes: + label: "System Info (`dataflow env`) / 系统信息(`dataflow env`)" + description: | + Please run `dataflow env` in your terminal and paste the full output here. + 请在终端运行 `dataflow env` 并将完整输出粘贴在此处。 + placeholder: | + dataflow version: x.y.z + platform: macOS/Linux/Windows + python version: 3.x.x + validations: + required: true + + - type: textarea + id: reproduction + attributes: + label: "Minimal Reproducible Example / 最小可复现示例" + description: | + Please provide the smallest code snippet or script to reproduce or illustrate the problem. + 请提供最小可复现的脚本或代码片段以演示问题。 + value: | + ```text + # e.g. + from dataflow.operators.generate import PromptedVQA + ... + ``` + validations: + required: true + + - type: textarea + id: others + attributes: + label: "Additional Information / 其他补充" + description: | + Any other details, screenshots, or logs that might help. + 任何其他可能有帮助的细节、截图或日志。 + placeholder: Optional + validations: + required: false \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/.github/ISSUE_TEMPLATE/3-feature-request.yaml b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/.github/ISSUE_TEMPLATE/3-feature-request.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0315d51f63e908264dc6d0720ea19d92af95b32b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/.github/ISSUE_TEMPLATE/3-feature-request.yaml @@ -0,0 +1,43 @@ +name: "✨ Feature Request" +description: "Suggest an idea for new features. 请求加入的有趣的新功能。" +labels: + - enhancement + +body: + - type: textarea + id: feature-description + attributes: + label: "Feature Description / 功能描述" + description: | + Please describe the feature you are suggesting. + 请描述您所建议的功能。 + placeholder: | + e.g. Add support for PyTorch models in dataflow. + 例如:在 dataflow 中添加对 PyTorch 模型的支持。 + validations: + required: true + + - type: textarea + id: system-info + attributes: + label: "System Info (`dataflow env`) / 系统信息(`dataflow env`)" + description: | + Please run `dataflow env` in your terminal and paste the full output here. + 请在终端运行 `dataflow env` 并将完整输出粘贴在此处。 + placeholder: | + dataflow version: x.y.z + platform: macOS/Linux/Windows + python version: 3.x.x + validations: + required: true + + - type: textarea + id: others + attributes: + label: "Additional Information / 其他补充" + description: | + Any other details, screenshots, or logs that might help. + 任何其他可能有帮助的细节、截图或日志。 + placeholder: Optional + validations: + required: false \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/.github/workflows/test.yaml b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/.github/workflows/test.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4bfab062c2f4785ebafa3064b2a41fd0ef173c7b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/.github/workflows/test.yaml @@ -0,0 +1,77 @@ +name: Python tests + +on: + push: + branches: [ "main" ] + paths: + - "**/*.py" + - "requirements*.txt" + - ".github/workflows/*.yml" + pull_request: + branches: [ "main" ] + paths: + - "**/*.py" + - "requirements*.txt" + - ".github/workflows/*.yml" + +jobs: + test: + name: Run tests on ${{ matrix.os }} with Python ${{ matrix.python }} + + strategy: + fail-fast: false + matrix: + os: ["ubuntu-latest", "macos-latest", "windows-latest"] + python: ["3.10", "3.11", "3.12"] + + runs-on: ${{ matrix.os }} + + steps: + - uses: actions/checkout@v4 + + - name: Set up Python ${{ matrix.python }} + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + + # 仅 Linux:释放 GitHub runner 的大块预装组件,立刻回收十几 GB + - name: Free up disk space on Linux + if: runner.os == 'Linux' + run: | + df -h + sudo rm -rf /usr/local/lib/android || true + sudo rm -rf /usr/share/dotnet || true + sudo rm -rf /opt/ghc || true + sudo rm -rf /opt/hostedtoolcache/CodeQL || true + docker system prune -af || true + sudo apt-get clean + sudo rm -rf /var/lib/apt/lists/* + df -h + + # 安装 uv(正确的官方 action) + - name: Install uv + uses: astral-sh/setup-uv@v7 + with: + enable-cache: true # 远端缓存 uv 自身(对磁盘占用很小) + + # 用系统 Python 安装依赖,禁用缓存,避免写入大体积 wheel 缓存 + - name: Install dependencies + env: + UV_SYSTEM_PYTHON: "1" + run: | + uv pip install --no-cache -r requirements.txt + uv pip install -e . + + - name: Run tests on Windows + if: startsWith(matrix.os, 'windows') + env: + PYTHONDONTWRITEBYTECODE: 1 + run: | + pytest -m cpu test + + - name: Run tests on Linux / macOS + if: ${{ !startsWith(matrix.os, 'windows') }} + env: + PYTHONDONTWRITEBYTECODE: 1 + run: | + pytest -m cpu test \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/licenses/Apache-2.0.txt b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/licenses/Apache-2.0.txt new file mode 100644 index 0000000000000000000000000000000000000000..f49a4e16e68b128803cc2dcea614603632b04eac --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/licenses/Apache-2.0.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/licenses/MIT.txt b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/licenses/MIT.txt new file mode 100644 index 0000000000000000000000000000000000000000..3198bb2e1c0fef62dafef78908052d860e9ba042 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/licenses/MIT.txt @@ -0,0 +1,7 @@ +Copyright {{cookiecutter.author}} + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/requirements.txt b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..60cb4e4543e7d21395c8a09abaaa7e9408e908b0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/requirements.txt @@ -0,0 +1,2 @@ +# Add your requirements here +open-dataflow \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/test/__pycache__/test_registed_op.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/test/__pycache__/test_registed_op.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..043df1b692c13f398236772e1410be9cd055947b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/test/__pycache__/test_registed_op.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/test/test_registed_op.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/test/test_registed_op.py new file mode 100644 index 0000000000000000000000000000000000000000..9f84a73cdcb8ca33f5d5d0d2940d4c6a2c169f82 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/test/test_registed_op.py @@ -0,0 +1,83 @@ +import importlib +import sys +import pytest + +from dataflow.utils.registry import OPERATOR_REGISTRY, PROMPT_REGISTRY + + +# ----------------------------- +# Color utilities (ANSI escape) +# ----------------------------- +class C: + GREEN = "\033[92m" + CYAN = "\033[96m" + YELLOW = "\033[93m" + RED = "\033[91m" + BOLD = "\033[1m" + RESET = "\033[0m" + + +def green(msg): return f"{C.GREEN}{msg}{C.RESET}" +def cyan(msg): return f"{C.CYAN}{msg}{C.RESET}" +def yellow(msg): return f"{C.YELLOW}{msg}{C.RESET}" +def red(msg): return f"{C.RED}{msg}{C.RESET}" +def bold(msg): return f"{C.BOLD}{msg}{C.RESET}" + + +# ================================================== +# Single test that verifies both registries at once +# (Import extension package exactly once) +# ================================================== +@pytest.mark.cpu +def test_operator_and_prompt_registered_once(): + """Ensure importing the extension package registers new operators and prompts. + The package is imported exactly once in this test. + """ + # --- 1) snapshot registry contents before import --- + op_before = set(OPERATOR_REGISTRY._obj_map.keys()) + pr_before = set(PROMPT_REGISTRY._obj_map.keys()) + + print(cyan(f"[Before Import] Operator count = {len(op_before)}")) + print(cyan(f"[Before Import] Prompt count = {len(pr_before)}")) + + # --- 2) Import the extension package exactly once --- + pkg_name = "{{cookiecutter.package_name}}" + if pkg_name in sys.modules: + # We will NOT reload — respect the requirement: import only once. + print(yellow(f"[Warning] {pkg_name} already in sys.modules; not reloading.")) + else: + importlib.import_module(pkg_name) + print(cyan(f"[Import] Imported package '{pkg_name}'")) + + # --- 3) snapshot registry contents after import --- + op_after = set(OPERATOR_REGISTRY._obj_map.keys()) + pr_after = set(PROMPT_REGISTRY._obj_map.keys()) + + print(cyan(f"[After Import] Operator count = {len(op_after)}")) + print(cyan(f"[After Import] Prompt count = {len(pr_after)}")) + + # --- 4) compute deltas --- + op_added = sorted(op_after - op_before) + pr_added = sorted(pr_after - pr_before) + + print(yellow(f"[Delta] Newly registered operators ({len(op_added)}):")) + for k in op_added: + print(green(f" + {k}")) + + print(yellow(f"[Delta] Newly registered prompts ({len(pr_added)}):")) + for k in pr_added: + print(green(f" + {k}")) + + # --- 5) assertions --- + # Require that both registries gained at least one new entry. + # If the package was already loaded before the test (and thus no new items), + # the test will fail — this enforces "import once and test after import" behavior. + assert len(op_added) > 0, "No new operators were registered after importing the package." + assert len(pr_added) > 0, "No new prompts were registered after importing the package." + + print(green(bold("[PASS] Both operator and prompt registry tests passed!"))) + + +# Allow running the test file directly (useful during local debugging) +if __name__ == "__main__": + test_operator_and_prompt_registered_once() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ba068c60b80a5091c7685dd51c323bb94938a79d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/__init__.py @@ -0,0 +1,36 @@ +import importlib +import pkgutil + + +def _auto_import_operators(): + """ + Recursively import all modules under operators.* in this package. + As long as a module is imported, any @OPERATOR_REGISTRY.register() + inside it will be executed automatically. + """ + base_pkg_name = __name__ + ".operators" + + try: + operators_pkg = importlib.import_module(base_pkg_name) + except ImportError: + # If there is no operators directory, just return + return + + # Recursively traverse all submodules / subpackages under the operators package + for _, module_name, is_pkg in pkgutil.walk_packages( + operators_pkg.__path__, operators_pkg.__name__ + "." + ): + # No need to distinguish is_pkg; if a package's __init__ contains operators, + # they will also be imported + importlib.import_module(module_name) + + +# 1. Simply importing dataflow_ext_cases will automatically import everything under operators +_auto_import_operators() + +# 2. If you want to provide an explicit entry point for external use, you can also expose a main +def main(): + _auto_import_operators() + + +__all__ = ["main"] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d35d95edbcc86a26cae39bff8a66938c403436a7 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/__pycache__/version.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/__pycache__/version.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..837b0ebd918b8966eca4928823d403f5ef5b7544 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/__pycache__/version.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/data/example_data.json b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/data/example_data.json new file mode 100644 index 0000000000000000000000000000000000000000..fda2a4f852bd683b906bfae817eafbb8d42d9812 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/data/example_data.json @@ -0,0 +1,18 @@ +[ + { + "role": "pig", + "term": "eat" + }, + { + "role": "tiger", + "term": "chase" + }, + { + "role": "people", + "term": "drink" + }, + { + "role": "bird", + "term": "dance" + } +] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/operators/core/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/operators/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/operators/core/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/operators/core/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70a56d015427fed9e59152c126a86546dd1fb76a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/operators/core/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/operators/core/__pycache__/my_prompted_generator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/operators/core/__pycache__/my_prompted_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c92d373b71b21265f463ab326eb47b91f0aa01d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/operators/core/__pycache__/my_prompted_generator.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/operators/core/my_format_str_prompted_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/operators/core/my_format_str_prompted_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..cc4f4b56e1e46450928f47488c23f3b19964b284 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/operators/core/my_format_str_prompted_generator.py @@ -0,0 +1,103 @@ + +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger + +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC +from dataflow.core.prompt import prompt_restrict, DIYPromptABC +from typing import Union, Any + +from {{cookiecutter.package_name}}.prompts.core import MyFormatStringPrompt + +@prompt_restrict( + MyFormatStringPrompt, +) +@OPERATOR_REGISTRY.register() +class MyFormatStrPromptedGenerator(OperatorABC): + def __init__( + self, + llm_serving: LLMServingABC, + system_prompt: str = "You are a helpful agent.", + prompt_template: Union[MyFormatStringPrompt, DIYPromptABC] = MyFormatStringPrompt, + json_schema: dict = None, + ): + self.logger = get_logger() + self.llm_serving = llm_serving + self.system_prompt = system_prompt + self.prompt_template = prompt_template + self.json_schema = json_schema + if prompt_template is None: + raise ValueError("prompt_template cannot be None") + + + def run( + self, + storage: DataFlowStorage, + output_key: str = "generated_content", + **input_keys: Any + ): + self.storage: DataFlowStorage = storage + self.output_key = output_key + self.logger.info("Running PromptTemplatedGenerator...") + self.input_keys = input_keys + need_fields = set(input_keys.keys()) + # Load the raw dataframe from the input file + dataframe = storage.read('dataframe') + self.logger.info(f"Loading, number of rows: {len(dataframe)}") + llm_inputs = [] + + for idx, row in dataframe.iterrows(): + key_dict = {} + for key in need_fields: + key_dict[key] = row[input_keys[key]] + prompt_text = self.prompt_template.build_prompt(need_fields, **key_dict) + llm_inputs.append(prompt_text) + self.logger.info(f"Prepared {len(llm_inputs)} prompts for LLM generation.") + # Create a list to hold all generated contents + # Generate content using the LLM serving + generated_outputs = self.llm_serving.generate_from_input(user_inputs = llm_inputs, system_prompt = self.system_prompt, json_schema = self.json_schema) + + dataframe[self.output_key] = generated_outputs + + output_file = self.storage.write(dataframe) + return output_key + + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于模板化提示词(Prompt Template)生成内容的算子。" + "该算子使用用户定义的提示模板(StrFormatPrompt 或 DIYPrompt)," + "结合输入数据中的字段自动构造完整提示词并调用大语言模型生成结果。\n\n" + "输入参数:\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口,用于执行文本生成任务\n" + "- prompt_template:提示词模板对象(StrFormatPrompt 或 DIYPromptABC),用于定义提示结构\n" + "- input_keys:输入字段映射字典,用于将DataFrame中的列名映射到模板字段\n" + "- output_key:输出生成内容字段名,默认为'generated_content'\n\n" + "输出参数:\n" + "- 包含生成结果的新DataFrame\n" + "- 返回输出字段名,以便后续算子引用\n\n" + "使用场景:\n" + "适用于需要通过模板化提示构建多样输入、批量生成文本内容的场景,例如标题生成、摘要生成、问答模板填充等。" + ) + elif lang == "en": + return ( + "An operator for content generation based on templated prompts. " + "This operator uses a user-defined prompt template (StrFormatPrompt or DIYPromptABC) " + "to automatically construct full prompts from input data fields and generate outputs via an LLM.\n\n" + "Input Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC interface, responsible for text generation\n" + "- prompt_template: Prompt template object (StrFormatPrompt or DIYPromptABC) defining the prompt structure\n" + "- input_keys: Dictionary mapping DataFrame column names to template fields\n" + "- output_key: Field name for generated content, default is 'generated_content'\n\n" + "Output Parameters:\n" + "- DataFrame containing generated outputs\n" + "- Returns the output field name for downstream operator reference\n\n" + "Use Case:\n" + "Ideal for tasks requiring templated prompt-driven generation, such as title generation, text summarization, or Q&A filling." + ) + else: + return ( + "PromptTemplatedGenerator generates text based on a user-defined prompt template." + ) \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/operators/core/my_prompted_generator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/operators/core/my_prompted_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..536c3cbb128442dcfc8989bf38a7f2231b9e892a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/operators/core/my_prompted_generator.py @@ -0,0 +1,88 @@ +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow import get_logger + +from dataflow.utils.storage import DataFlowStorage +from dataflow.core import OperatorABC +from dataflow.core import LLMServingABC + +@OPERATOR_REGISTRY.register() +class MyPromptedGenerator(OperatorABC): + ''' + This is an simple Operator as a template, you can modify it to meet your own needs. + ''' + def __init__(self, + llm_serving: LLMServingABC, + system_prompt: str = "You are a helpful agent.", + user_prompt: str = "", + json_schema: dict = None, + ): + self.logger = get_logger() + self.llm_serving = llm_serving + self.json_schema = json_schema + self.system_prompt = system_prompt + self.user_prompt = user_prompt + @staticmethod + def get_desc(lang: str = "zh"): + if lang == "zh": + return ( + "基于用户提供的提示词(prompt)生成数据。结合系统提示词和输入内容生成符合要求的输出文本。" + "输入参数:\n" + "- llm_serving:LLM服务对象,需实现LLMServingABC接口\n" + "- system_prompt:系统提示词,定义模型行为,默认为'You are a helpful agent.'\n" + "- input_key:输入内容字段名,默认为'raw_content'\n" + "- output_key:输出生成内容字段名,默认为'generated_content'\n" + "输出参数:\n" + "- 包含生成内容的DataFrame\n" + "- 返回输出字段名,用于后续算子引用" + ) + elif lang == "en": + return ( + "Generate data from user-provided prompts. Combines system prompt and input content to generate desired output text.\n" + "Input Parameters:\n" + "- llm_serving: LLM serving object implementing LLMServingABC interface\n" + "- system_prompt: System prompt to define model behavior, default is 'You are a helpful agent.'\n" + "- input_key: Field name for input content, default is 'raw_content'\n" + "- output_key: Field name for output generated content, default is 'generated_content'\n\n" + "Output Parameters:\n" + "- DataFrame containing generated content\n" + "- Returns output field name for subsequent operator reference" + ) + else: + return ( + "This operator generates text based on system prompt and input content." + ) + + def run(self, storage: DataFlowStorage, input_key: str = "raw_content", output_key: str = "generated_content"): + self.input_key, self.output_key = input_key, output_key + class_name = self.__class__.__name__ + self.logger.info(f"Running {class_name}...") + + # Load the raw dataframe from the input file + dataframe = storage.read('dataframe') + self.logger.info(f"Loading, number of rows: {len(dataframe)}") + + # Create a list to hold all generated questions and answers + llm_inputs = [] + + # Prepare LLM inputs by formatting the prompt with raw content from the dataframe + for index, row in dataframe.iterrows(): + raw_content = row.get(self.input_key, '') + if raw_content: + llm_input = self.user_prompt + str(raw_content) + llm_inputs.append(llm_input) + + # Generate the text using the model + try: + self.logger.info("Generating text using the model...") + generated_outputs = self.llm_serving.generate_from_input(user_inputs = llm_inputs, system_prompt = self.system_prompt, json_schema = self.json_schema) + self.logger.info("Text generation completed.") + except Exception as e: + self.logger.error(f"Error during text generation: {e}") + return + + # Add the generated content back to the dataframe + dataframe[self.output_key] = generated_outputs + + # Save the updated dataframe to the output file + output_file = storage.write(dataframe) + return output_key \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/pipelines/my_pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/pipelines/my_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..c4527ec8bf77dd91570b970834facb2fbb0cb9fe --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/pipelines/my_pipeline.py @@ -0,0 +1,50 @@ +from {{cookiecutter.package_name}}.operators.core.my_format_str_prompted_generator import MyFormatStrPromptedGenerator +from {{cookiecutter.package_name}}.operators.core.my_prompted_generator import MyPromptedGenerator +from dataflow.serving import APILLMServing_request +from dataflow.utils.storage import FileStorage +from dataflow.pipeline import PipelineABC + +from {{cookiecutter.package_name}}.prompts.core import MyFormatStringPrompt + +class MySimplePipeline(PipelineABC): + def __init__(self): + super().__init__() + self.storage = FileStorage( + first_entry_file_name="../data/example_data.json", + file_name_prefix="dataflow{{cookiecutter.package_name}}", + cache_path="./cache", + cache_type="jsonl", + ) + self.llm_serving = APILLMServing_request( + api_url="https://api.openai.com/v1/chat/completions", + model_name="gpt-4o" + ) + self.prompt_template = MyFormatStringPrompt( + f_str_template="What does a {input_role} like to {input_term}?" + ) + self.op1 = MyFormatStrPromptedGenerator( + llm_serving=self.llm_serving, + prompt_template=self.prompt_template + ) + self.op2 = MyPromptedGenerator( + llm_serving = self.llm_serving, + system_prompt="Summary this answer" + ) + + def forward(self): + self.op1.run( + storage=self.storage.step(), + input_role="role", + input_term="term", + output_key="answer", + ) + self.op2.run( + storage=self.storage.step(), + input_key="answer", + output_key="summary_answer" + ) + +if __name__ == "__main__": + model = MySimplePipeline() + model.compile() + model.forward() \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/prompts/core.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/prompts/core.py new file mode 100644 index 0000000000000000000000000000000000000000..824668763014de7daee3d2ff8158d750b967167e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/prompts/core.py @@ -0,0 +1,33 @@ +from dataflow.utils.registry import PROMPT_REGISTRY +from dataflow.core.prompt import PromptABC + +@PROMPT_REGISTRY.register() +class MyFormatStringPrompt(PromptABC): + """ + Only the f_str_template needs to be provided. + - Automatically parses the required fields from the template (self.fields) + - build_prompt(**kwargs) renders directly using kwargs + - on_missing: 'raise' | 'empty', controls behavior when fields are missing + """ + def __init__(self, f_str_template: str = "{input_text}", on_missing: str = "raise"): + self.f_str_template = f_str_template + if on_missing not in ("raise", "empty"): + raise ValueError("on_missing must be 'raise' or 'empty'") + self.on_missing = on_missing + + + def build_prompt(self, need_fields, **kwargs): + # Validate missing fields + missing = [f for f in need_fields if f not in kwargs] + if missing: + if self.on_missing == "raise": + raise KeyError(f"Missing fields for prompt: {missing}") + # Lenient mode: fill missing fields with empty strings + for f in missing: + kwargs[f] = "" + {% raw %} + prompt = self.f_str_template + for key, value in kwargs.items(): + prompt = prompt.replace(f"{{{key}}}", str(value)) + return prompt + {% endraw %} \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/version.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/version.py new file mode 100644 index 0000000000000000000000000000000000000000..b4b6ed8b22e0f84963a1d45da14f9c991b26aef9 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/statics/scaffold/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/version.py @@ -0,0 +1,23 @@ +__version__ = "{{cookiecutter.init_version}}" +short_version = __version__ + +def parse_version_info(version_str): + """Parse a version string into a tuple. + + Args: + version_str (str): The version string. + Returns: + tuple[int | str]: The version info, e.g., "1.3.0" is parsed into + (1, 3, 0), and "2.0.0rc1" is parsed into (2, 0, 0, 'rc1'). + """ + version_info = [] + for x in version_str.split('.'): + if x.isdigit(): + version_info.append(int(x)) + elif x.find('rc') != -1: + patch_version = x.split('rc') + version_info.append(int(patch_version[0])) + version_info.append(f'rc{patch_version[1]}') + return tuple(version_info) + +version_info = parse_version_info(__version__) \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ebf6b905158134d4c510194acaf15de161c38657 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/__init__.py @@ -0,0 +1,5 @@ +from .registry import OPERATOR_REGISTRY +__all__ = [ + + 'OPERATOR_REGISTRY', +] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed866b934dde672a8318f49b46dba7f2058fbfe2 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/__pycache__/registry.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/__pycache__/registry.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..692a4b13bb86ba7da25feb8e26d79ab3127c138b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/__pycache__/registry.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/__pycache__/storage.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/__pycache__/storage.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..454811475253641e8bad7a422ba786a74fbb6bf2 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/__pycache__/storage.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/__pycache__/utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c605ba0d1d6a44bed13f77300dea42f685c16d8c Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/__pycache__/utils.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/db_pool/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/db_pool/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..14b71d964a437de383e94a1e52d7eba12c357702 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/db_pool/__init__.py @@ -0,0 +1,8 @@ +# Database connection pool management +""" +This package manages database connection pools for different database types. +""" + +from .myscale_pool import ClickHouseConnectionPool + +__all__ = ['ClickHouseConnectionPool'] \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/db_pool/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/db_pool/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70460dcec129ad060838757b279aef705ad65858 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/db_pool/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/db_pool/__pycache__/myscale_pool.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/db_pool/__pycache__/myscale_pool.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0485e6f8946b6c5cdadace8c0daca6024fc648eb Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/db_pool/__pycache__/myscale_pool.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/db_pool/myscale_pool.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/db_pool/myscale_pool.py new file mode 100644 index 0000000000000000000000000000000000000000..7a8b0c83a80e73f035e7c5cd9034964147930771 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/db_pool/myscale_pool.py @@ -0,0 +1,164 @@ +import threading +import logging +import time +from contextlib import contextmanager +from typing import Generator, Optional + +logger = logging.getLogger(__name__) + + + +class ClickHouseConnectionPool: + + class ClickHousePoolError(Exception): + """Base exception for ClickHouse pool.""" + + class TooManyConnections(ClickHousePoolError): + """Raised when the pool is exhausted.""" + + def __init__( + self, + host: str, + port: int, + user: str, + password: str, + database: str, + min_connections: int = 5, + max_connections: int = 20, + health_check_interval: int = 30, + connect_timeout: int = 10, + **kwargs + ): + # Lazy import to avoid dependency if not used + try: + from clickhouse_driver import Client + from clickhouse_driver.errors import Error as ClickHouseError + # Store references for use in other methods + self._Client = Client + self._ClickHouseError = ClickHouseError + except ImportError as e: + raise ImportError("clickhouse-driver is required for ClickHouseConnectionPool, please install it via `pip install clickhouse-driver`") from e + + self._config = { + "host": host, + "port": port, + "user": user, + "password": password, + "database": database, + "connect_timeout": connect_timeout, + **kwargs + } + self._min = min_connections + self._max = max_connections + self._health_check_interval = health_check_interval + + self._pool = [] + self._lock = threading.Lock() + self._cond = threading.Condition(self._lock) + self._closed = False + + # 修复:添加正确的连接计数 + self._in_use_connections = 0 + self._total_created = 0 + + # 初始化最小连接 + for _ in range(self._min): + self._pool.append(self._create_connection()) + + def _create_connection(self): + try: + self._total_created += 1 + return self._Client(**self._config) + except self._ClickHouseError as e: + logger.error("Failed to create ClickHouse client: %s", e) + raise + + def _is_connection_alive(self, client) -> bool: + try: + client.execute("SELECT 1") + return True + except Exception: + return False + + def _get_connection(self): + with self._cond: + while True: + if self._closed: + raise ClickHousePoolError("Pool is closed.") + + if self._pool: + client = self._pool.pop() + if not self._is_connection_alive(client): + logger.warning("Dropping stale connection.") + self._in_use_connections -= 1 + continue + self._in_use_connections += 1 + return client + + if self._in_use_connections < self._max: + client = self._create_connection() + self._in_use_connections += 1 + return client + + self._cond.wait(timeout=10) + + def _release_connection(self, client, close: bool = False): + with self._cond: + self._in_use_connections -= 1 + + if close or self._closed: + try: + client.disconnect() + except Exception: + pass + elif len(self._pool) < self._min: + self._pool.append(client) + else: + try: + client.disconnect() + except Exception: + pass + self._cond.notify() + + def _in_use_count(self): + # 修复:返回正确的连接数 + return self._in_use_connections + + @contextmanager + def get_connection(self): + conn = None + try: + conn = self._get_connection() + yield conn + finally: + if conn: + self._release_connection(conn) + + def close(self): + with self._cond: + self._closed = True + while self._pool: + conn = self._pool.pop() + try: + conn.disconnect() + except Exception: + pass + self._cond.notify_all() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + + # 新增:获取连接池状态 + def get_status(self): + """获取连接池状态""" + return { + "pool_size": len(self._pool), + "in_use": self._in_use_connections, + "max_connections": self._max, + "min_connections": self._min, + "total_created": self._total_created, + "closed": self._closed + } \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/kbc/__pycache__/mineru_api_caller.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/kbc/__pycache__/mineru_api_caller.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c244f59c08865e7dfeb7bd9a019a50608c0c563 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/kbc/__pycache__/mineru_api_caller.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/kbc/mineru_api_caller.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/kbc/mineru_api_caller.py new file mode 100644 index 0000000000000000000000000000000000000000..18ce3e5eeb537f12cc1e0d3bdcc5bb8320289481 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/kbc/mineru_api_caller.py @@ -0,0 +1,207 @@ +import os +import time +import json +import requests +from typing import List, Dict +import zipfile + +def _safe_basename(path_or_name: str) -> str: + base = os.path.basename(path_or_name) + if base.lower().endswith(".pdf"): + base = base[:-4] + # keep it filesystem-safe + return "".join(c if c.isalnum() or c in ("-", "_", ".") else "_" for c in base) + +def _zip_name(item: dict) -> str: + data_id = item.get("data_id", "unknown") + name = _safe_basename(item.get("file_name", f"file_{data_id}")) + return f"{data_id}_{name}.zip" + +def _unzip_and_get_md(zip_path: str, extract_dir: str) -> str: + """ + Unzip zip_path into extract_dir and return extract_dir/full.md + """ + os.makedirs(extract_dir, exist_ok=True) + + with zipfile.ZipFile(zip_path, "r") as zf: + zf.extractall(extract_dir) + + md_path = os.path.join(extract_dir, "full.md") + if not os.path.exists(md_path): + raise RuntimeError(f"Expected markdown not found: {md_path}") + + return md_path + + +class MinerUBatchExtractorViaAPI: + def __init__( + self, + api_key: str, + model_version: str = "vlm", + poll_interval: int = 5, + timeout: int = 600, + ): + self.api_key = api_key + self.model_version = model_version + self.poll_interval = poll_interval + self.timeout = timeout + + self.base_url = "https://mineru.net/api/v4" + self.headers = { + "Authorization": f"Bearer {self.api_key}", + "Content-Type": "application/json", + } + + # ---------- Step 1: apply upload urls ---------- + def apply_upload_urls(self, file_paths: List[str]) -> Dict: + files = [ + {"name": path, "data_id": str(i)} + for i, path in enumerate(file_paths) + ] + + payload = { + "files": files, + "model_version": self.model_version, + } + + resp = requests.post( + f"{self.base_url}/file-urls/batch", + headers=self.headers, + json=payload, + ) + resp.raise_for_status() + data = resp.json() + + if data["code"] != 0: + raise RuntimeError(f"Apply upload urls failed: {data}") + + return data["data"] # batch_id + file_urls + + # ---------- Step 2: upload files ---------- + def upload_files(self, file_paths: List[str], file_urls: List[str]): + assert len(file_paths) == len(file_urls) + + for path, url in zip(file_paths, file_urls): + with open(path, "rb") as f: + r = requests.put(url, data=f) + if r.status_code != 200: + raise RuntimeError(f"Upload failed for {path}") + + # ---------- Step 3: poll extraction result ---------- + def poll_results(self, batch_id: str) -> dict: + start = time.time() + url = f"{self.base_url}/extract-results/batch/{batch_id}" + + while True: + resp = requests.get(url, headers=self.headers) + resp.raise_for_status() + data = resp.json() + + if data["code"] != 0: + raise RuntimeError(f"Polling failed: {data}") + + result_list = data["data"].get("extract_result", []) + + if not result_list: + raise RuntimeError("No extract_result returned") + + states = [item["state"] for item in result_list] + + # ---- derive batch status ---- + if all(s == "done" for s in states): + return data["data"] + + if any(s == "failed" for s in states): + failed = [i for i in result_list if i["state"] == "failed"] + raise RuntimeError(f"Extraction failed: {failed}") + + # still running + if time.time() - start > self.timeout: + raise TimeoutError("Polling timed out") + + time.sleep(self.poll_interval) + + + # ---------- Step 4: download results --------- + def download_results(self, extract_result: list, out_dir: str): + os.makedirs(out_dir, exist_ok=True) + + md_results = {} + + for item in extract_result: + if item.get("state") != "done": + continue + + zip_url = item.get("full_zip_url") + if not zip_url: + raise RuntimeError(f"Missing full_zip_url for item: {item}") + + data_id = item.get("data_id", "unknown") + + # 解压目录固定为 ./ + extract_dir = os.path.join(out_dir, str(data_id)) + zip_path = os.path.join(out_dir, f"{data_id}.zip") + + # 1. download zip + r = requests.get(zip_url, timeout=120) + r.raise_for_status() + with open(zip_path, "wb") as f: + f.write(r.content) + + print(f"[OK] Downloaded ZIP: {zip_path}") + + # 2. unzip and get full.md + md_path = _unzip_and_get_md(zip_path, extract_dir) + + print(f"[OK] Markdown ready: {md_path}") + + md_results[data_id] = { + "zip_path": zip_path, + "extract_dir": extract_dir, + "md_path": md_path, + } + + return md_results + + + + # ---------- One-call pipeline ---------- + def extract_batch(self, file_paths: list, out_dir: str) -> dict: + apply_data = self.apply_upload_urls(file_paths) + + batch_id = apply_data["batch_id"] + file_urls = apply_data["file_urls"] + + self.upload_files(file_paths, file_urls) + + result_data = self.poll_results(batch_id) + + # 关键:接住 download_results 的返回值 + md_results = self.download_results( + result_data["extract_result"], + out_dir + ) + + items = [] + for it in result_data.get("extract_result", []): + data_id = it.get("data_id") + + info = md_results.get(data_id, {}) + + items.append({ + "data_id": data_id, + "file_name": it.get("file_name"), + "state": it.get("state"), + + # 来自 download_results + "zip_path": info.get("zip_path"), + "extract_dir": info.get("extract_dir"), + "md_path": info.get("md_path"), + }) + + return { + "batch_id": batch_id, + "output_dir": out_dir, + "num_files": len(file_paths), + "items": items, + } diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/pdf2vqa/__pycache__/format_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/pdf2vqa/__pycache__/format_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77deecf2e5953010526713f4018a545329b00292 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/pdf2vqa/__pycache__/format_utils.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/pdf2vqa/format_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/pdf2vqa/format_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e567d0f5bada59f790111da0c1441d696f844e85 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/pdf2vqa/format_utils.py @@ -0,0 +1,135 @@ +import json +import re + +def refine_title(title: str, strict_title_match=False): + # TODO : 这里可能需要更复杂的title清洗逻辑 + # 删除title中的空格与换行符 + title = re.sub(r'\s+', '', title) + if not strict_title_match: + try: + # 优先提取阿拉伯数字章节编号(如1.1,2等) + new_title = re.search(r"\d+\.\d+|\d+", title).group() + except: + try: + # 其次提取中文数字章节编号(如六、二十四等) + new_title = re.search(r'[一二三四五六七八九零十百]+', title).group() + except Exception: + new_title = title + title = new_title + return title + +def merge_qa_pair(vqa_jsonl, output_jsonl, strict_title_match=False): + already_complete_count = 0 + question_list = [] + answer_list = [] + with open(vqa_jsonl, 'r', encoding='utf-8') as vqa_file: + for line in vqa_file: + data = json.loads(line) + if data["question"] != "": + question_list.append(data) + else: + # 用于支持题目在前面,答案在后面的pdf + answer_list.append(data) + + with open(output_jsonl, 'w', encoding='utf-8') as out_file: + chapter_id = 0 + chapter_title = "" + label = float('inf') + questions = {} + answers = {} + for data in question_list: + label_match = re.search(r'\d+', data["label"]) + if label_match: + data["label"] = label_match.group() + if data["chapter_title"] == "": + data["chapter_title"] = chapter_title + + try: + data["label"] = int(data["label"]) + except Exception: + continue + + if data["chapter_title"] != "" and data["chapter_title"] != chapter_title: + if data["label"] < label: + chapter_id += 1 + chapter_title = data["chapter_title"] + else: + # 如果题号增加,章节标题却发生变化,说明可能错误提取了子标题。因此继续使用之前的章节标题。 + data["chapter_title"] = chapter_title + label = data["label"] + data["chapter_title"] = refine_title(data["chapter_title"], strict_title_match) + if data['label'] > 0: + # 已经完整的题目直接写入out_file + if data["answer"] or data["solution"]: + already_complete_count += 1 + qa_pair = { + "question_chapter_title": data["chapter_title"], + "answer_chapter_title": data["chapter_title"], + "label": data['label'], + "question": data["question"], + "answer": data["answer"], + "solution": data.get("solution", "") + } + out_file.write(json.dumps(qa_pair, ensure_ascii=False) + '\n') + + else: + questions[(data["chapter_title"], data['label'])] = data + + chapter_id = 0 + chapter_title = "" + label = float('inf') + for data in answer_list: + label_match = re.search(r'\d+', data["label"]) + if label_match: + data["label"] = label_match.group() + if data["chapter_title"] == "": + data["chapter_title"] = chapter_title + + try: + data["label"] = int(data["label"]) + except Exception: + continue + + if data["chapter_title"] != "" and data["chapter_title"] != chapter_title: + if data["label"] < label: + chapter_id += 1 + chapter_title = data["chapter_title"] + else: + # 如果题号增加,章节标题却发生变化,说明可能错误提取了子标题。因此继续使用之前的章节标题。 + data["chapter_title"] = chapter_title + label = data["label"] + data["chapter_title"] = refine_title(data["chapter_title"], strict_title_match) + # 动态更新,防止错误的重复label覆盖掉之前的solution或answer + if data['label'] > 0: + if not answers.get((data["chapter_title"], data['label'])): + answers[(data["chapter_title"], data['label'])] = data + else: + if not answers[(data["chapter_title"], data['label'])].get("solution") and data.get("solution"): + answers[(data["chapter_title"], data['label'])]["solution"] = data["solution"] + if not answers[(data["chapter_title"], data['label'])].get("answer") and data.get("answer"): + answers[(data["chapter_title"], data['label'])]["answer"] = data["answer"] + + for label in questions: + if label in answers: + qa_pair = { + "question_chapter_title": questions[label]["chapter_title"], + "answer_chapter_title": answers[label]["chapter_title"], + "label": label[1], + "question": questions[label]["question"], + "answer": answers[label]["answer"], + "solution": answers[label].get("solution", "") + } + out_file.write(json.dumps(qa_pair, ensure_ascii=False) + '\n') + + print(f"Merged QA pairs: {len(questions.keys() & answers.keys()) + already_complete_count}") + +def jsonl_to_md(jsonl_file, md_file): + with open(jsonl_file, 'r', encoding='utf-8') as in_file, open(md_file, 'w', encoding='utf-8') as out_file: + for line in in_file: + data = json.loads(line) + out_file.write(f"### Question {data['label']}\n\n") + out_file.write(f"{data['question']}\n\n") + out_file.write(f"**Answer:** {data['answer']}\n\n") + if data.get('solution'): + out_file.write(f"**Solution:**\n\n{data['solution']}\n\n") + out_file.write("---\n\n") \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/reasoning/AnswerExtraction.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/reasoning/AnswerExtraction.py new file mode 100644 index 0000000000000000000000000000000000000000..3670d0f09b3749257026792ce4a2c29575ea39e0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/reasoning/AnswerExtraction.py @@ -0,0 +1,212 @@ +import pandas as pd +from tqdm import tqdm +import logging +import re +from word2number import w2n +from dataflow.utils.utils import get_logger + +class StringProcessor: + """ + A class that encapsulates various string processing functions for mathematical expressions. + """ + + @staticmethod + def _fix_fracs(string): + """ + Fixes fraction expressions in the string, ensuring they are properly formatted as \frac{a}{b}. + """ + substrs = string.split("\\frac") + new_str = substrs[0] + if len(substrs) > 1: + for substr in substrs[1:]: + new_str += "\\frac" + if len(substr) > 0 and substr[0] == "{": + new_str += substr + else: + if len(substr) >= 2: + a, b = substr[0], substr[1] + if b != "{": + new_str += f"{{{a}}}{{{b}}}{substr[2:]}" if len(substr) > 2 else f"{{{a}}}{{{b}}}" + else: + new_str += f"{{{a}}}{b}{substr[2:]}" if len(substr) > 2 else f"{{{a}}}{b}" + else: + return string + return new_str + + @staticmethod + def _fix_a_slash_b(string): + """ + Fixes cases where a fraction is represented as a simple division (e.g., a/b) and converts it to \frac{a}{b}. + """ + if len(string.split("/")) != 2: + return string + a, b = string.split("/") + try: + a, b = int(a) if "sqrt" not in a else a, int(b) if "sqrt" not in b else b + assert string == f"{a}/{b}" + return f"\\frac{{{a}}}{{{b}}}" + except Exception: + return string + + @staticmethod + def _fix_sqrt(string): + """ + Ensures that square root expressions are properly formatted as \sqrt{...}. + """ + return re.sub(r"\\sqrt(\w+)", r"\\sqrt{\1}", string) + + @staticmethod + def convert_word_number(text: str) -> str: + """ + Converts a word representation of a number to a digit. + """ + try: + return str(w2n.word_to_num(text)) + except Exception: + return text + + +# Unit Text Class to Manage Unit Texts +class UnitTextManager: + """ + A class that encapsulates unit text management to remove unwanted unit terms from strings. + """ + + def __init__(self): + """ + Initializes the unit texts and their plural forms. + """ + self.unit_texts = [ + "east", "degree", "mph", "kmph", "ft", "m sqaure", "m east", "sq m", "deg", "mile", "q .", "monkey", "prime", + "ratio", "profit of rs", "rd", "o", "gm", "p . m", "lb", "tile", "per", "dm", "lt", "gain", "ab", "way", "west", + "a .", "b .", "c .", "d .", "e .", "f .", "g .", "h .", "t", "a", "h", "no change", "men", "soldier", "pie", "bc", + "excess", "st", "inches", "noon", "percent", "by", "gal", "kmh", "c", "acre", "rise", "a . m", "th", "π r 2", "sq", + "mark", "l", "toy", "coin", "sq . m", "gallon", "° f", "profit", "minw", "yr", "women", "feet", "am", "pm", "hr", + "cu cm", "square", "v â € ™", "are", "rupee", "rounds", "cubic", "cc", "mtr", "s", "ohm", "number", "kmph", "day", + "hour", "minute", "min", "second", "man", "woman", "sec", "cube", "mt", "sq inch", "mp", "∏ cm ³", "hectare", + "more", "sec", "unit", "cu . m", "cm 2", "rs .", "rs", "kg", "g", "month", "km", "m", "cm", "mm", "apple", "liter", + "loss", "yard", "pure", "year", "increase", "decrease", "d", "less", "Surface", "litre", "pi sq m", "s .", "metre", + "meter", "inch", + ] + self.unit_texts.extend([t + "s" for t in self.unit_texts]) + + def clean_units(self, string: str): + """ + Cleans the string by removing unit terms from it. + """ + for unit_text in self.unit_texts: + string = re.sub(r"(^|\W)" + unit_text + r"($|\W)", r"\1\2", string) + return string + + +# Main String Processing Class +class StringCleaner: + """ + A class responsible for cleaning and formatting strings in mathematical expressions. + """ + + def __init__(self, unit_manager: UnitTextManager): + """ + Initializes the StringCleaner class with a unit manager. + """ + self.unit_manager = unit_manager + + def strip_string(self, string, skip_unit=False): + """ + Strips unwanted characters and units from the string. + """ + string = str(string).strip().replace("\n", "").rstrip(".").replace("\\!", "") + string = re.sub(r"\\begin\{array\}\{.*?\}", r"\\begin{pmatrix}", string) + string = re.sub(r"\\end\{array\}", r"\\end{pmatrix}", string).replace("bmatrix", "pmatrix") + string = string.replace("tfrac", "frac").replace("dfrac", "frac").replace("\\neq", "\\ne").replace("\\leq", "\\le").replace("\\geq", "\\ge") + string = string.replace("\\left", "").replace("\\right", "").replace("\\{", "{").replace("\\}", "}") + + # Clean unit texts if needed + if not skip_unit: + string = self.unit_manager.clean_units(string) + + string = string.replace("^{\\circ}", "").replace("^\\circ", "").replace("\\$", "").replace("$", "").replace("\\(", "").replace("\\)", "") + string = StringProcessor.convert_word_number(string) + string = re.sub(r"\\text\{(.*?)\}", r"\1", string) + + for key in ["x=", "y=", "z=", "x\\in", "y\\in", "z\\in", "x\\to", "y\\to", "z\\to"]: + string = string.replace(key, "") + + string = string.replace("\\emptyset", r"{}").replace("(-\\infty,\\infty)", "\\mathbb{R}") + string = string.replace("%", "").replace(" .", " 0.").replace("{.", "{0.") + + return string + + +# Core Answer Extraction Logic Class +class AnswerExtractor: + """ + A class responsible for extracting the final answer from a prediction string. + """ + + def __init__(self, string_cleaner: StringCleaner): + """ + Initializes the AnswerExtractor class with a string cleaner. + """ + self.string_cleaner = string_cleaner + self.logger = get_logger() + + def extract_answer(self, pred_str, data_name, use_last_number=True): + """ + Extracts the final answer from the prediction string, processing various formats. + """ + if not pred_str: + pred_str = "" + pred_str = str(pred_str).replace("\u043a\u0438", "") + + # Handle special cases based on data_name or pattern + if "final answer is $" in pred_str and "$. I hope" in pred_str: + pred = pred_str.split("final answer is $", 1)[1].split("$. I hope", 1)[0].strip() + elif "boxed" in pred_str: + pred = self._extract_boxed_answer(pred_str) + elif "he answer is" in pred_str: + pred = pred_str.split("he answer is")[-1].strip() + else: + pred = self._get_last_number_answer(pred_str, use_last_number) + + pred = self.string_cleaner.strip_string(pred, skip_unit=data_name in ["carp_en", "minerva_math"]) + return pred + + def _extract_boxed_answer(self, pred_str): + """ + Extracts answers enclosed in 'boxed' notation. + """ + ans = pred_str.split("boxed")[-1] + if ans.startswith("{"): + return self._extract_bracketed_answer(ans) + else: + return ans.split("$")[0].strip() + + def _extract_bracketed_answer(self, ans): + """ + Handles answers that are enclosed within brackets. + """ + stack = 1 + result = "" + for c in ans[1:]: + if c == "{": + stack += 1 + result += c + elif c == "}": + stack -= 1 + if stack == 0: + break + result += c + else: + result += c + return result + + def _get_last_number_answer(self, pred_str, use_last_number): + """ + Extracts the last number from the string if use_last_number is True. + """ + if use_last_number: + pattern = "-?\d*\.?\d+" + pred = re.findall(pattern, pred_str.replace(",", "")) + return pred[-1] if pred else "" + return "" diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/reasoning/CategoryFuzz.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/reasoning/CategoryFuzz.py new file mode 100644 index 0000000000000000000000000000000000000000..efa2e02d274b96f0adf6b978fa605602e170de4a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/reasoning/CategoryFuzz.py @@ -0,0 +1,151 @@ +from rapidfuzz import process, fuzz +import re + + +class CategoryUtils: + primary_categories = [ + "Foundations and Logic", + "Algebra and Number Theory", + "Analysis and Differential Equations", + "Geometry and Topology", + "Probability, Statistics, and Discrete Mathematics", + "Applied and Computational Mathematics", + "Arithmetic", +] + secondary_categories = { + "Foundations and Logic": [ + "Mathematical Logic and Set Theory", + "Basic Theory, Formalization, and History & Education", + ], + "Algebra and Number Theory": [ + "Linear Algebra and Group Theory", + "Ring Theory, Field Theory, and Polynomial Algebra", + "Commutative Algebra and Homological/Categorical Methods", + "Number Theory", + "Algebraic Geometry", + ], + "Analysis and Differential Equations": [ + "Real Analysis, Measure Theory, and Functional Analysis", + "Complex Analysis and Special Functions", + "Differential Equations and Dynamical Systems", + "Integral Transforms, Integral Equations, and Difference Equations", + "Harmonic Analysis", + ], + "Geometry and Topology": [ + "Euclidean, Analytic, and Convex/Discrete Geometry", + "Differential Geometry and Manifold Theory", + "Topology and Algebraic Topology", + ], + "Probability, Statistics, and Discrete Mathematics": [ + "Probability Theory and Stochastic Processes", + "Mathematical Statistics", + "Combinatorics and Graph Theory", + ], + "Applied and Computational Mathematics": [ + "Numerical Analysis and Computational Methods", + "Optimal Control, Variational Methods, and Optimization", + "Operations Research and Game Theory", + "Systems Theory and Control", + "Computer Science and Algorithms", + "Mathematical Physics and Engineering Mathematics", + "Information and Communication", + "Bimathematics", + ], + "Arithmetic": [ + "Basic Arithmetic and Number Operations", + "Word Problems and Real-Life Applications", + ], +} + + def normalize_text(self,s: str) -> str: + s = s.lower() + # 去数字、点、连字符、下划线、逗号等 + s = re.sub(r"[0-9\.\-\_\(\)\[\],&/]", " ", s) + s = re.sub(r"\s+", " ", s).strip() + return s + + def fuzzy_match_label(self, + raw_label: str, + choices: list[str], + scorer=fuzz.WRatio, + threshold: int = 70) -> str | None: + raw_clean = self.normalize_text(raw_label) + best, score, _ = process.extractOne( + query=raw_clean, + choices=choices, + scorer=scorer + ) + return best if score >= threshold else None + + def normalize_categories( + self, + raw_primary: str, + raw_secondary: str, + primary_choices: list[str] = primary_categories, + secondary_map: dict[str, list[str]] = secondary_categories, + thresh_primary: int = 50, + thresh_secondary: int = 50 + ) -> dict: + """ + 优先解析纯数字编号(如"1"、"1."或"1.1"),否则再走 fuzzy-match。 + 返回 {'primary_category': ..., 'secondary_category': ...}。 + """ + # 1) 尝试直接按 "X.Y" 解析子类编号 + m = re.match(r"^\s*(\d+)\s*\.\s*(\d+)\s*\.?\s*$", raw_secondary) + if m: + pi, si = int(m.group(1)), int(m.group(2)) + if 1 <= pi <= len(primary_choices): + primary = primary_choices[pi - 1] + secs = secondary_map.get(primary, []) + if 1 <= si <= len(secs): + return { + "primary_category": primary, + "secondary_category": secs[si - 1] + } + # 2) 再尝试按 "X" 解析主类编号 + m = re.match(r"^\s*(\d+)\s*\.?\s*$", raw_primary) + if m: + pi = int(m.group(1)) + if 1 <= pi <= len(primary_choices): + primary = primary_choices[pi - 1] + else: + primary = None + else: + primary = None + + # 3) 如果编号解析不到,再 fuzzy-match 主类 + if primary is None: + primary = self.fuzzy_match_label(raw_primary, primary_choices, threshold=thresh_primary) + + # 如果主类依然没匹配上,直接返回 "" + if not primary: + return {"primary_category": "", "secondary_category": ""} + + # 4) 在该主类对应的二级列表中做 fuzzy-match + sec_choices = secondary_map.get(primary, []) + secondary = self.fuzzy_match_label(raw_secondary, sec_choices, threshold=thresh_secondary) + if not secondary: + secondary = "" + + return { + "primary_category": primary, + "secondary_category": secondary + } + + def category_hasher(self,primary: str, secondary: str) -> float: + # 对于第k个大类的第m个二级类,返回k * 8 + m + try: + k = self.primary_categories.index(primary) + m = self.secondary_categories[primary].index(secondary) + return k * 8 + m + except Exception: + return 170 + + def category_hasher_reverse(self,hash: float) -> tuple[str, str]: + if hash < 0 or hash > 56: + return None, None + k = int(hash / 8) + m = int(hash % 8) + return self.primary_categories[k], self.secondary_categories[self.primary_categories[k]][m] + + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/reasoning/__pycache__/AnswerExtraction.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/reasoning/__pycache__/AnswerExtraction.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..acfb2e9397fb6cfb6239d5bf13dd898c703b82fc Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/reasoning/__pycache__/AnswerExtraction.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/reasoning/__pycache__/CategoryFuzz.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/reasoning/__pycache__/CategoryFuzz.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97f4209469ac79fcbde06f126692417186a8d811 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/reasoning/__pycache__/CategoryFuzz.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/registry.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..a61754df495c7980466e51d81f260e92de2652c4 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/registry.py @@ -0,0 +1,364 @@ +import importlib +import importlib.util +import sys +import types +import os +from dataflow.logger import get_logger +from pathlib import Path + +from rich.console import Console +from rich.table import Table + +import ast +from pathlib import Path + +def generate_import_structure_from_type_checking(source_file: str, base_path: str) -> dict: + source = Path(source_file).read_text(encoding="utf-8") + tree = ast.parse(source) + + import_structure = {} + + for node in ast.walk(tree): + if isinstance(node, ast.If) and getattr(node.test, 'id', '') == 'TYPE_CHECKING': + for subnode in node.body: + if isinstance(subnode, ast.ImportFrom): + module_rel = subnode.module.replace(".", "/") + for alias in subnode.names: + name = alias.name + module_file = str(Path(base_path) / f"{module_rel}.py") + import_structure[name] = (module_file, name) + + return import_structure + + +class Registry(): + """ + The registry that provides name -> object mapping, to support third-party + users' custom modules. + + To create a registry (e.g. a backbone registry): + + .. code-block:: python + + BACKBONE_REGISTRY = Registry('BACKBONE') + + To register an object: + + .. code-block:: python + + @BACKBONE_REGISTRY.register() + class MyBackbone(): + ... + + Or: + + .. code-block:: python + + BACKBONE_REGISTRY.register(MyBackbone) + """ + + def __init__(self, name): + """ + Args: + name (str): the name of this registry + """ + self._name = name + self._obj_map = {} + self._base_folder = Path(__file__).resolve().parents[1] + self._sub_modules = list(os.listdir(self._base_folder / name)) + if "__init__.py" in self._sub_modules: + self._sub_modules.remove("__init__.py") + if "__pycache__" in self._sub_modules: + self._sub_modules.remove("__pycache__") + if len(self._sub_modules) > 0: + self.loader_map = dict(zip(self._sub_modules, [None] * len(self._sub_modules))) + + def _init_loaders(self): + for module_name in self.loader_map.keys(): + module_path = f"dataflow.{self._name}.{module_name}" + self.loader_map[module_name] = importlib.import_module(module_path) + + def _do_register(self, name, obj): + if name not in self._obj_map: + self._obj_map[name] = obj + + def register(self, obj=None): + """ + Register the given object under the the name `obj.__name__`. + Can be used as either a decorator or not. + See docstring of this class for usage. + """ + if obj is None: + # used as a decorator + def deco(func_or_class): + name = func_or_class.__name__ + self._do_register(name, func_or_class) + return func_or_class + + return deco + + # used as a function call + name = obj.__name__ + self._do_register(name, obj) + + def get(self, name): + ret = self._obj_map.get(name) + logger = get_logger() + if ret is None: + if None in self.loader_map.values(): + self._init_loaders() + for module_lib in self.loader_map.values(): + # module_path = "dataflow.operators." + x + try: + # module_lib = importlib.import_module(module_path) + clss = getattr(module_lib, name) + self._obj_map[name] = clss + return clss + except AttributeError as e: + logger.debug(f"{str(e)}") + continue + except Exception as e: + raise e + logger.error(f"No object named '{name}' found in '{self._name}' registry!") + raise KeyError(f"No object named '{name}' found in '{self._name}' registry!") + + if ret is None: + logger.error(f"No object named '{name}' found in '{self._name}' registry!") + assert ret is not None, f"No object named '{name}' found in '{self._name}' registry!" + + return ret + + def apply_whitelist(self, names, *, verbose: bool = True): + """ + 在已调用 _get_all() 之后执行: + 仅保留 `names`(白名单)中的对象,其他对象从 _obj_map 中移除。 + 同时返回一份详尽报告,并(可选)输出日志摘要。 + + :param names: Iterable[str],白名单 + :param verbose: 是否用 logger 输出摘要信息 + :return: dict 报告,字段如下: + { + "requested_whitelist": [str, ...], # 传入的白名单(去重、排序后) + "missing_in_registry": [str, ...], # 在白名单里但不在 obj_map 的 + "kept": [str, ...], # 实际保留 + "removed": [str, ...], # 实际移除 + "total_before": int, # 裁剪前数量 + "total_after": int, # 裁剪后数量 + "trimmed_by": int # 裁掉的数量(= before - after) + } + """ + logger = get_logger() + + # 1) 规范化输入 + names = [] if names is None else list(names) + keep_set = set(map(str, names)) + + # 2) 快照当前注册表 + before_keys = set(self._obj_map.keys()) + total_before = len(before_keys) + + # 3) 计算三类集合 + missing_in_registry = sorted(keep_set - before_keys) # 白名单中缺失的 + to_keep = sorted(before_keys & keep_set) # 真正保留的 + to_remove = sorted(before_keys - keep_set) # 将被移除的(不在白名单) + + # 4) 执行就地裁剪 + for k in to_remove: + self._obj_map.pop(k, None) + + # 5) 统计结果 + total_after = len(self._obj_map) + trimmed_by = total_before - total_after + + # 6) 构造报告 + report = { + "requested_whitelist": sorted(keep_set), + "missing_in_registry": missing_in_registry, + "kept": to_keep, + "removed": to_remove, + "total_before": total_before, + "total_after": total_after, + "trimmed_by": trimmed_by, + } + + # 7) 可读日志摘要(尽可能合理且完整) + if verbose: + logger.info( + f"[Registry:{self._name}] whitelist applied: " + f"before={total_before}, after={total_after}, trimmed_by={trimmed_by}" + ) + if to_keep: + logger.info(f"[Registry:{self._name}] kept ({len(to_keep)}): {to_keep}") + else: + logger.info(f"[Registry:{self._name}] kept (0): []") + + if to_remove: + logger.info(f"[Registry:{self._name}] removed ({len(to_remove)}): {to_remove}") + else: + logger.info(f"[Registry:{self._name}] removed (0): []") + + if missing_in_registry: + logger.warning( + f"[Registry:{self._name}] in-whitelist-but-missing " + f"({len(missing_in_registry)}): {missing_in_registry}" + ) + + return report + + def __contains__(self, name): + return name in self._obj_map + + def __iter__(self): + return iter(self._obj_map.items()) + + def keys(self): + return self._obj_map.keys() + + def __repr__(self): + table = Table(title=f'Registry of {self._name}') + table.add_column('Names', justify='left', style='cyan') + table.add_column('Objects', justify='left', style='green') + + for name, obj in sorted(self._obj_map.items()): + table.add_row(name, str(obj)) + + console = Console() + with console.capture() as capture: + console.print(table, end='') + + return capture.get() + + def _get_all(self): + if None in self.loader_map.values(): + self._init_loaders() + for loader in self.loader_map.values(): + loader._import_all() + + def get_obj_map(self): + """ + Get the object map of the registry. + """ + return self._obj_map + + def get_type_of_objects(self): + """ + Classify the object type by its path of registration. + This is used to classify objects into different categories. + :return: A dictionary with object type as keys and their name as values. + """ + object_types_dict = {} + for name, obj in self._obj_map.items(): + module_str = obj.__module__ + # print(obj.__name__, module_str) + parts = module_str.split(".") + object_types_dict[name] = parts[0:] + return object_types_dict + +OPERATOR_REGISTRY = Registry(name='operators') + +PROMPT_REGISTRY = Registry(name='prompts') + +class LazyLoader(types.ModuleType): + + def __init__(self, name, path, import_structure): + """ + 初始化 LazyLoader 模块。 + + :param name: 模块名称 + :param import_structure: 定义类名到文件路径的映射字典 + """ + super().__init__(name) + self._import_structure = import_structure + self._loaded_classes = {} + self._base_folder = Path(__file__).resolve().parents[2] + self.__path__ = [path] + self.__all__ = list(import_structure.keys()) + + def _import_all(self): + for cls_name in self.__all__: + self.__getattr__(cls_name) + + def _load_class_from_file(self, file_path, class_name): + """ + 从指定文件中加载类。 + + :param file_path: 脚本文件的路径 + :param class_name: 类的名字 + :return: 类对象 + """ + p = Path(file_path) + if p.is_absolute(): + abs_file_path = str(p) + else: + abs_file_path = str(Path(self._base_folder) / p) + if not os.path.exists(abs_file_path): + raise FileNotFoundError(abs_file_path) + rel_path = Path(abs_file_path).relative_to(self._base_folder) + # 去掉后缀得到 ('dataflow', 'operators', 'generate', ... , 'question_generator') + rel_parts = rel_path.with_suffix('').parts + prefix_parts = tuple(self.__name__.split('.')) + if rel_parts[:len(prefix_parts)] == prefix_parts: + rel_parts = rel_parts[len(prefix_parts):] + mod_name = '.'.join((*prefix_parts, *rel_parts)) + logger = get_logger() + # 动态加载模块 + + try: + parts = mod_name.split(".") + for i in range(1, len(parts)): + parent = ".".join(parts[:i]) + if parent not in sys.modules: + dummy_mod = importlib.util.module_from_spec( + importlib.util.spec_from_loader(parent, loader=None) + ) + dummy_mod.__path__ = [os.path.dirname(abs_file_path)] + sys.modules[parent] = dummy_mod + + spec = importlib.util.spec_from_file_location(mod_name, abs_file_path) + logger.debug(f"LazyLoader {self.__path__} successfully imported spec {spec.__str__()}") + module = importlib.util.module_from_spec(spec) + sys.modules[mod_name] = module + logger.debug(f"LazyLoader {self.__path__} successfully imported module {module.__str__()} from spec {spec.__str__()}") + logger.debug(f"Module name: {module.__name__}") + logger.debug(f"Module file: {module.__file__}") + logger.debug(f"Module package: {module.__package__}") + spec.loader.exec_module(module) + + except Exception as e: + import traceback + logger.exception("Import failed for %s from %s", mod_name, abs_file_path) + # 可选:再打印一份,CI 日志更清楚 + print("=== Lazy import traceback ===") + print("Module:", mod_name) + print("File:", abs_file_path) + print("".join(traceback.format_exception(e))) + raise + + + # 提取类 + if not hasattr(module, class_name): + raise AttributeError(f"Class {class_name} not found in {abs_file_path}") + return getattr(module, class_name) + + def __getattr__(self, item): + """ + 动态加载类。 + + :param item: 类名 + :return: 动态加载的类对象 + """ + logger = get_logger() + if item in self._loaded_classes: + cls = self._loaded_classes[item] + logger.debug(f"Lazyloader {self.__path__} got cached class {cls}") + return cls + # 从映射结构中获取文件路径和类名 + if item in self._import_structure: + file_path, class_name = self._import_structure[item] + logger.info(f"Lazyloader {self.__path__} trying to import {item} ") + cls = self._load_class_from_file(file_path, class_name) + logger.debug(f"Lazyloader {self.__path__} got and cached class {cls}") + self._loaded_classes[item] = cls + return cls + logger.debug(f"Module {self.__name__} has no attribute {item}") + raise AttributeError(f"Module {self.__name__} has no attribute {item}") diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/storage.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/storage.py new file mode 100644 index 0000000000000000000000000000000000000000..ac0a82a94ea5f28088a7fb571e1fe295aba78aef --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/storage.py @@ -0,0 +1,1184 @@ +from abc import ABC, abstractmethod +import atexit +import signal +import tempfile +import weakref + +from dataflow import get_logger +import pandas as pd +import json +from typing import Any, Dict, Literal, Generator +import os +import copy + +class DataFlowStorage(ABC): + """ + Abstract base class for data storage. + """ + @abstractmethod + def get_keys_from_dataframe(self) -> list[str]: + """ + Get keys from the dataframe stored in the storage. + This method should be implemented by subclasses to extract keys from the data. + """ + pass + @abstractmethod + def read(self, output_type) -> Any: + """ + Read data from file. + type: type that you want to read to, such as "datatrame", List[dict], etc. + """ + pass + + @abstractmethod + def write(self, data: Any) -> Any: + pass + +# --- 新增的 __repr__ 方法 --- + def __repr__(self): + """ + 返回一个表示该对象所有成员变量及其键值对的字符串。 + """ + # 获取实例的所有属性(成员变量) + attrs = self.__dict__ + + # 格式化键值对列表 + attr_strs = [] + for key, value in attrs.items(): + # 特殊处理 pandas DataFrame 或其他大型对象 + if isinstance(value, pd.DataFrame): + # 如果是 DataFrame,只显示其类型和形状,避免输出过多内容 + value_repr = f"" + elif isinstance(value, set): + # 简化集合的显示 + value_repr = f"<{type(value).__name__} size={len(value)}>" + elif isinstance(value, dict): + # 简化字典的显示 + value_repr = f"<{type(value).__name__} size={len(value)}>" + else: + # 使用标准的 repr() 获取值表示,并限制长度 + value_repr = repr(value) + if len(value_repr) > 100: # 限制长度以避免超长输出 + value_repr = value_repr[:97] + "..." + + attr_strs.append(f" {key} = {value_repr}") + + # 构造最终的字符串 + body = "\n".join(attr_strs) + return f"<{self.__class__.__name__} Object:\n{body}\n>" + # --------------------------- +class LazyFileStorage(DataFlowStorage): + """ + LazyFileStorage + ---------------- + - 平时仅在内存中读写;只在进程正常结束/被中断或显式 flush 时落盘 + - 与传统 FileStorage 的接口保持一致(step/reset/read/write/…) + - 支持首步数据源: 本地文件 / 'hf:' / 'ms:' + - 原子落盘(os.replace),多线程安全(RLock) + """ + + def __init__( + self, + first_entry_file_name: str, + cache_path:str="./cache", + file_name_prefix:str="dataflow_cache_step", + cache_type:Literal["json", "jsonl", "csv", "parquet", "pickle"] = "jsonl", + save_on_exit: bool = True, # 进程退出时自动 flush + flush_all_steps: bool = False # True: 所有缓冲步落盘;False: 仅最新一步 + ): + """ + Initialize a LazyFileStorage. + + This storage keeps read/write operations in memory and only persists to disk + when explicitly flushed or when the process exits / is interrupted (if + save_on_exit is enabled). The class preserves an interface compatible with + a traditional FileStorage (step / reset / read / write / ...). Step 0 + (the "first entry") may be loaded from a local file path or from remote + dataset identifiers prefixed with "hf:" (HuggingFace datasets) or "ms:" + (ModelScope datasets). Disk writes are performed atomically via os.replace, + and internal buffers are protected with an RLock for thread safety. + + Args: + first_entry_file_name (str): + Path or source identifier used as the data source for step 0. + - If it starts with "hf:" the remainder is interpreted as a + HuggingFace dataset specification (dataset[:config][:split]). + - If it starts with "ms:" the remainder is interpreted as a + ModelScope dataset specification (dataset[:split]). + - Otherwise it is treated as a local file path; the file extension + (json, jsonl, csv, parquet, pickle) determines how it is loaded. + cache_path (str, optional): + Directory where per-step cache files are written. Defaults to "./cache". + file_name_prefix (str, optional): + Prefix used when composing cache filenames for non-zero steps. + Defaults to "dataflow_cache_step" (files will be like + "{file_name_prefix}_step{n}.{cache_type}"). + cache_type (Literal["json","jsonl","csv","parquet","pickle"], optional): + Serialization format used when persisting buffers to disk. + - "json": full JSON array + - "jsonl": JSON Lines (one record per line) + - "csv": comma-separated values + - "parquet": Apache Parquet + - "pickle": Python pickle + Defaults to "jsonl". + save_on_exit (bool, optional): + If True (default), register handlers so that buffered data is flushed + automatically when the process exits or when SIGINT/SIGTERM is received. + In restricted environments registering signal handlers may fail silently. + flush_all_steps (bool, optional): + Controls flush_all() behavior: + - True: flush_all() persists all buffered steps. + - False (default): flush_all() persists only the most recently buffered step. + + Returns: + None + + Notes: + - The instance maintains an internal operator_step counter (initially -1). + Calling step() increments this counter; write() buffers data for + operator_step + 1. + - write(...) buffers data in memory and returns the file path that will + be used when the buffer is ultimately flushed to disk (useful for logging). + - Disk writes are atomic: data is first written to a temporary file and + then moved into place with os.replace to avoid partial files. + - Thread-safety: an RLock protects buffer and dirty-step state. + - Errors: + - Reading a non-existent local file raises FileNotFoundError. + - Unsupported file types raise ValueError. + """ + self.first_entry_file_name = first_entry_file_name + self.cache_path = cache_path + self.file_name_prefix = file_name_prefix + self.cache_type = cache_type + self.operator_step = -1 + self.logger = get_logger() + + # 内存缓冲:step -> DataFrame + self._buffers: Dict[int, pd.DataFrame] = {} + self._dirty_steps: set[int] = set() + self._lock = RLock() + + self._save_on_exit = save_on_exit + self._flush_all_steps = flush_all_steps + + if self._save_on_exit: + self._register_exit_hooks() + + # ---------- 生命周期 & 信号 ---------- + def _register_exit_hooks(self): + _self_ref = weakref.ref(self) + atexit.register(lambda: _self_ref() and _self_ref()._flush_if_dirty(reason="atexit")) + for sig in (signal.SIGINT, signal.SIGTERM): + try: + signal.signal(sig, self._make_signal_handler(sig)) + except Exception: + # 某些环境(子线程/受限容器)可能设置失败 + pass + + def _make_signal_handler(self, sig): + def handler(signum, frame): + try: + self._flush_if_dirty(reason=f"signal:{signum}") + finally: + try: + signal.signal(signum, signal.SIG_DFL) + except Exception: + pass + try: + os.kill(os.getpid(), signum) + except Exception: + # 某些解释器环境不允许再次发送信号,忽略 + pass + return handler + + def _flush_if_dirty(self, reason: str): + with self._lock: + dirty = bool(self._dirty_steps) + if dirty: + self.logger.info(f"[flush] Triggered by {reason}, flushing...") + self.flush_all() + else: + self.logger.info(f"[flush] Triggered by {reason}, but no dirty buffers.") + + # ---------- step & 路径 ---------- + def _get_cache_file_path(self, step) -> str: + if step == -1: + self.logger.error("You must call storage.step() before reading or writing data. Please call storage.step() first for each operator step.") + raise ValueError("You must call storage.step() before reading or writing data. Please call storage.step() first for each operator step.") + if step == 0: + # 首步来源可能是远端或本地 + return os.path.join(self.first_entry_file_name) + else: + return os.path.join(self.cache_path, f"{self.file_name_prefix}_step{step}.{self.cache_type}") + + def step(self): + self.operator_step += 1 + return copy.copy(self) # 保持与原 FileStorage 兼容的使用方式 + + def reset(self): + self.operator_step = -1 + return self + + # ---------- 工具方法 ---------- + def get_keys_from_dataframe(self) -> list[str]: + dataframe = self.read(output_type="dataframe") + return dataframe.columns.tolist() if isinstance(dataframe, pd.DataFrame) else [] + + def _load_local_file(self, file_path: str, file_type: str) -> pd.DataFrame: + if not os.path.exists(file_path): + raise FileNotFoundError(f"File {file_path} does not exist. Please check the path.") + try: + if file_type == "json": + return pd.read_json(file_path) + elif file_type == "jsonl": + return pd.read_json(file_path, lines=True) + elif file_type == "csv": + return pd.read_csv(file_path) + elif file_type == "parquet": + return pd.read_parquet(file_path) + elif file_type == "pickle": + return pd.read_pickle(file_path) + else: + raise ValueError(f"Unsupported file type: {file_type}") + except Exception as e: + raise ValueError(f"Failed to load {file_type} file: {str(e)}") + + def _convert_output(self, dataframe: pd.DataFrame, output_type: str) -> Any: + if output_type == "dataframe": + return dataframe + elif output_type == "dict": + return dataframe.to_dict(orient="records") + raise ValueError(f"Unsupported output type: {output_type}") + + def _read_first_entry_source(self) -> pd.DataFrame: + source = self.first_entry_file_name + if source.startswith("hf:"): + from datasets import load_dataset + _, dataset_name, *parts = source.split(":") + if len(parts) == 1: + config, split = None, parts[0] + elif len(parts) == 2: + config, split = parts + else: + config, split = None, "train" + dataset = ( + load_dataset(dataset_name, config, split=split) + if config + else load_dataset(dataset_name, split=split) + ) + return dataset.to_pandas() + elif source.startswith("ms:"): + from modelscope import MsDataset + _, dataset_name, *split_parts = source.split(":") + split = split_parts[0] if split_parts else "train" + dataset = MsDataset.load(dataset_name, split=split) + return pd.DataFrame(dataset) + else: + # 本地首文件 + local_cache = source.split(".")[-1] + return self._load_local_file(source, local_cache) + + # ---------- 读 ---------- + def read(self, output_type: Literal["dataframe", "dict"]="dataframe") -> Any: + if self.operator_step == 0 and self.first_entry_file_name == "": + self.logger.info("first_entry_file_name is empty, returning empty dataframe") + empty_dataframe = pd.DataFrame() + return self._convert_output(empty_dataframe, output_type) + + step = self.operator_step + with self._lock: + if step in self._buffers: + self.logger.info(f"[buffer] Reading step {step} from in-memory buffer.") + return self._convert_output(self._buffers[step], output_type) + + file_path = self._get_cache_file_path(step) + self.logger.info(f"[read] step={step}, path={file_path}, type={output_type}") + + if step == 0: + df = self._read_first_entry_source() + with self._lock: + self._buffers[step] = df + return self._convert_output(df, output_type) + + # 兜底:磁盘已有则载入(例如复跑时) + local_cache = self.cache_type + df = self._load_local_file(file_path, local_cache) + with self._lock: + self._buffers[step] = df + return self._convert_output(df, output_type) + + # ---------- 写(仅缓冲,不落盘) ---------- + def write(self, data: Any) -> Any: + """ + 将数据写入内存缓冲(目标 step = operator_step + 1),不触盘。 + 返回该 step 对应未来落盘的文件路径,便于日志对齐。 + """ + def clean_surrogates(obj): + if isinstance(obj, str): + return obj.encode('utf-8', 'replace').decode('utf-8') + elif isinstance(obj, dict): + return {k: clean_surrogates(v) for k, v in obj.items()} + elif isinstance(obj, list): + return [clean_surrogates(item) for item in obj] + elif isinstance(obj, (int, float, bool)) or obj is None: + return obj + else: + try: + return clean_surrogates(str(obj)) + except Exception: + return obj + + if isinstance(data, list): + if len(data) > 0 and isinstance(data[0], dict): + cleaned_data = [clean_surrogates(item) for item in data] + dataframe = pd.DataFrame(cleaned_data) + else: + raise ValueError(f"Unsupported data type: {type(data[0]) if data else 'empty list'}") + elif isinstance(data, pd.DataFrame): + dataframe = data.applymap(clean_surrogates) + else: + raise ValueError(f"Unsupported data type: {type(data)}") + + target_step = self.operator_step + 1 + with self._lock: + self._buffers[target_step] = dataframe.reset_index(drop=True) + self._dirty_steps.add(target_step) + + self.logger.success(f"[buffer] Buffered data for step {target_step} (type={self.cache_type}); not persisted yet.") + return self._get_cache_file_path(target_step) + + # ---------- 落盘 ---------- + def flush_step(self, step: int): + with self._lock: + if step not in self._buffers: + self.logger.info(f"No buffer for step {step}; nothing to flush.") + return + df = self._buffers[step] + + file_path = self._get_cache_file_path(step) + os.makedirs(os.path.dirname(file_path) or ".", exist_ok=True) + + # 原子写:先写临时文件,再替换 + dir_name = os.path.dirname(file_path) or "." + fd, tmp_path = tempfile.mkstemp(prefix=".tmp_", dir=dir_name) + os.close(fd) + try: + if self.cache_type == "json": + df.to_json(tmp_path, orient="records", force_ascii=False, indent=2) + elif self.cache_type == "jsonl": + df.to_json(tmp_path, orient="records", lines=True, force_ascii=False) + elif self.cache_type == "csv": + df.to_csv(tmp_path, index=False) + elif self.cache_type == "parquet": + df.to_parquet(tmp_path) + elif self.cache_type == "pickle": + df.to_pickle(tmp_path) + else: + raise ValueError(f"Unsupported file type: {self.cache_type}, output file should end with json, jsonl, csv, parquet, pickle") + + os.replace(tmp_path, file_path) + with self._lock: + self._dirty_steps.discard(step) + self.logger.success(f"[flush] Persisted step {step} -> {file_path}") + finally: + try: + if os.path.exists(tmp_path): + os.remove(tmp_path) + except Exception: + pass + + def flush_all(self): + with self._lock: + if not self._buffers: + self.logger.info("No buffers to flush.") + return + steps = sorted(self._buffers.keys()) if self._flush_all_steps else [max(self._buffers.keys())] + for s in steps: + self.flush_step(s) + +class DummyStorage(DataFlowStorage): + def __init__( + self, + cache_path:str=None, + file_name_prefix:str=None, + cache_type: Literal["json", "jsonl", "csv", "parquet", "pickle", None] = None + ): + self._data = None + self.cache_path = cache_path + self.file_name_prefix = file_name_prefix + self.cache_type = cache_type + + def set_data(self, data: Any): + """ + Set data to be written later. + """ + self._data = data + + def set_file_name_prefix(self, file_name_prefix: str): + """ + Set the file name prefix for cache files. + """ + self.file_name_prefix = file_name_prefix + + def read(self, output_type: Literal["dataframe", "dict"] = "dataframe") -> Any: + return self._data + + def write(self, data): + self._data = data + if self.cache_type != None: + cache_file_path = os.path.join(self.cache_path, f"{self.file_name_prefix}.{self.cache_type}") + os.makedirs(os.path.dirname(cache_file_path), exist_ok=True) + if self.cache_type == "json": + data.to_json(cache_file_path, orient="records", force_ascii=False, indent=2) + elif self.cache_type == "jsonl": + data.to_json(cache_file_path, orient="records", lines=True, force_ascii=False) + elif self.cache_type == "csv": + data.to_csv(cache_file_path, index=False) + elif self.cache_type == "parquet": + data.to_parquet(cache_file_path) + elif self.cache_type == "pickle": + data.to_pickle(cache_file_path) + else: + raise ValueError(f"Unsupported file type: {self.cache_type}, output file should end with json, jsonl, csv, parquet, pickle") + +class FileStorage(DataFlowStorage): + """ + Storage for file system. + """ + def __init__( + self, + first_entry_file_name: str, + cache_path:str="./cache", + file_name_prefix:str="dataflow_cache_step", + cache_type:Literal["json", "jsonl", "csv", "parquet", "pickle"] = "jsonl" + ): + """ + Initialize a FileStorage. + + FileStorage is a disk-backed storage implementation that reads from and + writes to the local filesystem on every read/write operation. Unlike + LazyFileStorage, data is persisted immediately and no in-memory buffering + is maintained across steps. + + The storage follows a step-based access pattern compatible with + DataFlowStorage. Step 0 (the "first entry") can be loaded from: + - a local file path, or + - a remote dataset specified with the "hf:" (HuggingFace) or "ms:" + (ModelScope) prefix. + + Subsequent steps are materialized as files on disk under `cache_path`, + with filenames derived from `file_name_prefix`, the step index, and + `cache_type`. + + Args: + first_entry_file_name (str): + Path or source identifier used as the data source for step 0. + - "hf:{dataset}[:config][:split]" loads a HuggingFace dataset. + - "ms:{dataset}[:split]" loads a ModelScope dataset. + - Otherwise, this is treated as a local file path, and the file + extension determines how it is read. + cache_path (str, optional): + Directory where cache files for steps >= 1 are stored. + Defaults to "./cache". + file_name_prefix (str, optional): + Prefix used when generating filenames for cached steps. + Cache files are named as + "{file_name_prefix}_step{n}.{cache_type}". + Defaults to "dataflow_cache_step". + cache_type (Literal["json","jsonl","csv","parquet","pickle"], optional): + File format used when writing step outputs to disk. + Defaults to "jsonl". + + Returns: + None + + Notes: + - The internal `operator_step` counter starts at -1 and is incremented + by calling `step()`. + - Calling `write(...)` writes data immediately to disk for + `operator_step + 1`. + - No atomic-write or buffering guarantees are provided beyond the + underlying pandas file writers. + - This class is simpler but less fault-tolerant than LazyFileStorage, + as partially written files may exist if a process is interrupted. + """ + self.first_entry_file_name = first_entry_file_name + self.cache_path = cache_path + self.file_name_prefix = file_name_prefix + self.cache_type = cache_type + self.operator_step = -1 + self.logger = get_logger() + + def _get_cache_file_path(self, step) -> str: + if step == -1: + self.logger.error("You must call storage.step() before reading or writing data. Please call storage.step() first for each operator step.") + raise ValueError("You must call storage.step() before reading or writing data. Please call storage.step() first for each operator step.") + if step == 0: + # If it's the first step, use the first entry file name + return os.path.join(self.first_entry_file_name) + else: + return os.path.join(self.cache_path, f"{self.file_name_prefix}_step{step}.{self.cache_type}") + + def step(self): + self.operator_step += 1 + return copy.copy(self) # TODO if future maintain an object in memory, we need to apply a deepcopy (except the dataframe object during copy to avoid OOM) + + def reset(self): + self.operator_step = -1 + return self + + def get_keys_from_dataframe(self) -> list[str]: + dataframe = self.read(output_type="dataframe") + return dataframe.columns.tolist() if isinstance(dataframe, pd.DataFrame) else [] + + def _load_local_file(self, file_path: str, file_type: str) -> pd.DataFrame: + """Load data from local file based on file type.""" + # check if file exists + if not os.path.exists(file_path): + raise FileNotFoundError(f"File {file_path} does not exist. Please check the path.") + # Load file based on type + try: + if file_type == "json": + return pd.read_json(file_path) + elif file_type == "jsonl": + return pd.read_json(file_path, lines=True) + elif file_type == "csv": + return pd.read_csv(file_path) + elif file_type == "parquet": + return pd.read_parquet(file_path) + elif file_type == "pickle": + return pd.read_pickle(file_path) + elif self.cache_type == "xlsx": + return pd.read_excel(file_path) + else: + raise ValueError(f"Unsupported file type: {file_type}") + except Exception as e: + raise ValueError(f"Failed to load {file_type} file: {str(e)}") + + def _convert_output(self, dataframe: pd.DataFrame, output_type: str) -> Any: + """Convert dataframe to requested output type.""" + if output_type == "dataframe": + return dataframe + elif output_type == "dict": + return dataframe.to_dict(orient="records") + raise ValueError(f"Unsupported output type: {output_type}") + + def read(self, output_type: Literal["dataframe", "dict"]="dataframe") -> Any: + """ + Read data from current file managed by storage. + + Args: + output_type: Type that you want to read to, either "dataframe" or "dict". + Also supports remote datasets with prefix: + - "hf:{dataset_name}{:config}{:split}" => HuggingFace dataset eg. "hf:openai/gsm8k:main:train" + - "ms:{dataset_name}{}:split}" => ModelScope dataset eg. "ms:modelscope/gsm8k:train" + + Returns: + Depending on output_type: + - "dataframe": pandas DataFrame + - "dict": List of dictionaries + + Raises: + ValueError: For unsupported file types or output types + """ + if self.operator_step == 0 and self.first_entry_file_name == "": + self.logger.info("first_entry_file_name is empty, returning empty dataframe") + empty_dataframe = pd.DataFrame() + return self._convert_output(empty_dataframe, output_type) + + file_path = self._get_cache_file_path(self.operator_step) + self.logger.info(f"Reading data from {file_path} with type {output_type}") + + if self.operator_step == 0: + source = self.first_entry_file_name + self.logger.info(f"Reading remote dataset from {source} with type {output_type}") + if source.startswith("hf:"): + from datasets import load_dataset + _, dataset_name, *parts = source.split(":") + + if len(parts) == 1: + config, split = None, parts[0] + elif len(parts) == 2: + config, split = parts + else: + config, split = None, "train" + + dataset = ( + load_dataset(dataset_name, config, split=split) + if config + else load_dataset(dataset_name, split=split) + ) + dataframe = dataset.to_pandas() + return self._convert_output(dataframe, output_type) + + elif source.startswith("ms:"): + from modelscope import MsDataset + _, dataset_name, *split_parts = source.split(":") + split = split_parts[0] if split_parts else "train" + + dataset = MsDataset.load(dataset_name, split=split) + dataframe = pd.DataFrame(dataset) + return self._convert_output(dataframe, output_type) + + else: + local_cache = file_path.split(".")[-1] + else: + local_cache = self.cache_type + + dataframe = self._load_local_file(file_path, local_cache) + return self._convert_output(dataframe, output_type) + + def write(self, data: Any) -> Any: + """ + Write data to current file managed by storage. + data: Any, the data to write, it should be a dataframe, List[dict], etc. + """ + def clean_surrogates(obj): + """递归清理数据中的无效Unicode代理对字符""" + if isinstance(obj, str): + # 替换无效的Unicode代理对字符(如\udc00) + return obj.encode('utf-8', 'replace').decode('utf-8') + elif isinstance(obj, dict): + return {k: clean_surrogates(v) for k, v in obj.items()} + elif isinstance(obj, list): + return [clean_surrogates(item) for item in obj] + elif isinstance(obj, (int, float, bool)) or obj is None: + # 数字、布尔值和None直接返回 + return obj + else: + # 其他类型(如自定义对象)尝试转为字符串处理 + try: + return clean_surrogates(str(obj)) + except Exception: + # 如果转换失败,返回原对象或空字符串(根据需求选择) + return obj + + # 转换数据为DataFrame + if isinstance(data, list): + if len(data) > 0 and isinstance(data[0], dict): + # 清洗列表中的每个字典 + cleaned_data = [clean_surrogates(item) for item in data] + dataframe = pd.DataFrame(cleaned_data) + else: + raise ValueError(f"Unsupported data type: {type(data[0])}") + elif isinstance(data, pd.DataFrame): + # 对DataFrame的每个元素进行清洗 + dataframe = data.map(clean_surrogates) + else: + raise ValueError(f"Unsupported data type: {type(data)}") + + # if type(data) == list: + # if type(data[0]) == dict: + # dataframe = pd.DataFrame(data) + # else: + # raise ValueError(f"Unsupported data type: {type(data[0])}") + # elif type(data) == pd.DataFrame: + # dataframe = data + # else: + # raise ValueError(f"Unsupported data type: {type(data)}") + + file_path = self._get_cache_file_path(self.operator_step + 1) + os.makedirs(os.path.dirname(file_path), exist_ok=True) + self.logger.success(f"Writing data to {file_path} with type {self.cache_type}") + if self.cache_type == "json": + dataframe.to_json(file_path, orient="records", force_ascii=False, indent=2) + elif self.cache_type == "jsonl": + dataframe.to_json(file_path, orient="records", lines=True, force_ascii=False) + elif self.cache_type == "csv": + dataframe.to_csv(file_path, index=False) + elif self.cache_type == "parquet": + dataframe.to_parquet(file_path) + elif self.cache_type == "pickle": + dataframe.to_pickle(file_path) + elif self.cache_type == "xlsx": + dataframe.to_excel(file_path, index=False) + else: + raise ValueError(f"Unsupported file type: {self.cache_type}, output file should end with json, jsonl, csv, parquet, pickle or xlsx") + + return file_path + +from threading import Lock, RLock +import math +from dataflow.utils.db_pool.myscale_pool import ClickHouseConnectionPool + +# 推荐在模块级别创建全局池 +myscale_pool = None + +def get_myscale_pool(db_config): + global myscale_pool + if myscale_pool is None: + myscale_pool = ClickHouseConnectionPool( + host=db_config['host'], + port=db_config.get('port', 9000), + user=db_config.get('user', 'default'), + password=db_config.get('password', ''), + database=db_config.get('database', 'default'), + min_connections=5, + max_connections=50, + ) + return myscale_pool + +# 预定义字段前缀 +SYS_FIELD_PREFIX = 'sys:' +USER_FIELD_PREFIX = 'user:' + +# 保留字段列表 +RESERVED_SYS_FIELD_LIST=["raw_data_id"] +RESERVED_USER_FIELD_LIST=[] + +# 安全加载 json 数据 +def safe_json_loads(x): + if isinstance(x, dict): + return x + if isinstance(x, str): + try: + return json.loads(x) + except Exception: + return x # 保留原始字符串 + if pd.isna(x): + return None + return x # 其它类型原样返回 + +# 安全合并列到 data 字段 +def safe_merge(row, col): + val = row[col] + if isinstance(val, float) and math.isnan(val): + return row['data'] + return {**row['data'], col: val} + +# 预定义 min_hashes 计算方法,当前全部返回[0] +def _default_min_hashes(data_dict): + return [0] + +class MyScaleDBStorage(DataFlowStorage): + """ + Storage for Myscale/ClickHouse database using clickhouse_driver. + """ + def validate_required_params(self): + """ + 校验 MyScaleDBStorage 实例的关键参数有效性: + - pipeline_id, input_task_id, output_task_id 必须非空,否则抛出异常。 + - page_size, page_num 若未设置则赋默认值(page_size=10000, page_num=0)。 + 所有算子在使用 storage 前应调用本方法。 + """ + missing = [] + if not self.pipeline_id: + missing.append('pipeline_id') + if not self.input_task_id: + missing.append('input_task_id') + if not self.output_task_id: + missing.append('output_task_id') + if missing: + raise ValueError(f"Missing required storage parameters: {', '.join(missing)}") + if not hasattr(self, 'page_size') or self.page_size is None: + self.page_size = 10000 + if not hasattr(self, 'page_num') or self.page_num is None: + self.page_num = 0 + + def __init__( + self, + db_config: dict, + pipeline_id: str = None, + input_task_id: str = None, + output_task_id: str = None, + parent_pipeline_id: str = None, + page_size: int = 10000, + page_num: int = 0 + ): + """ + db_config: { + 'host': 'localhost', + 'port': 9000, + 'user': 'default', + 'password': '', + 'database': 'dataflow', + 'table': 'dataflow_table' + } + pipeline_id: str, 当前 pipeline 的标识(可选,默认 None) + input_task_id: str, 输入任务的标识(可选,默认 None) + output_task_id: str, 输出任务的标识(可选,默认 None) + parent_pipeline_id: str, 父 pipeline 的标识(可选,默认 None) + page_size: int, 分页时每页的记录数(默认 10000) + page_num: int, 当前页码(默认 0) + """ + self.db_config = db_config + self.table = db_config.get('table', 'dataflow_table') + self.logger = get_logger() + self.pipeline_id: str = pipeline_id + self.input_task_id: str = input_task_id + self.output_task_id: str = output_task_id + self.parent_pipeline_id: str = parent_pipeline_id + self.page_size: int = page_size + self.page_num: int = page_num + self.validate_required_params() + + def read(self, output_type: Literal["dataframe", "dict"]) -> Any: + """ + Read data from Myscale/ClickHouse table. + """ + pool = get_myscale_pool(self.db_config) + with pool.get_connection() as client: + where_clauses = [] + params = {} + if self.pipeline_id: + where_clauses.append("pipeline_id = %(pipeline_id)s") + params['pipeline_id'] = self.pipeline_id + if self.input_task_id: + where_clauses.append("task_id = %(task_id)s") + params['task_id'] = self.input_task_id + if hasattr(self, 'parent_pipeline_id') and self.parent_pipeline_id: + where_clauses.append("parent_pipeline_id = %(parent_pipeline_id)s") + params['parent_pipeline_id'] = self.parent_pipeline_id + where_sql = f"WHERE {' AND '.join(where_clauses)}" if where_clauses else "" + limit_offset = f"LIMIT {self.page_size} OFFSET {(self.page_num-1)*self.page_size}" if self.page_size else "" + sql = f"SELECT * FROM {self.table} {where_sql} {limit_offset}" + self.logger.info(f"Reading from DB: {sql} with params {params}") + result = client.execute(sql, params, with_column_types=True) + rows, col_types = result + columns = [col[0] for col in col_types] + df = pd.DataFrame(rows, columns=columns) + # 解析 data 字段为 dict + if 'data' not in df.columns: + raise ValueError("Result does not contain required 'data' field.") + + # 只保留 data 字段 + data_series = df['data'].apply(safe_json_loads) + if output_type == "dataframe": + # 提取 data 一列并自动展开为多列(如果 data 是 dict) + result_df = pd.DataFrame({'data': data_series}) + if not data_series.empty and isinstance(data_series.iloc[0], dict): + expanded = data_series.apply(pd.Series) + # 合并展开列和原始 data 列 + result_df = pd.concat([result_df, expanded], axis=1) + return result_df + elif output_type == "dict": + # 返回 data 字段的 dict 列表 + return list(data_series) + else: + raise ValueError(f"Unsupported output type: {output_type}") + + def write(self, data: Any) -> Any: + """ + Write data to Myscale/ClickHouse table. + data: pd.DataFrame or List[dict],每行是data字段内容(dict)。 + """ + pool = get_myscale_pool(self.db_config) + with pool.get_connection() as client: + if isinstance(data, list): + df = pd.DataFrame(data) + elif isinstance(data, pd.DataFrame): + df = data + else: + raise ValueError(f"Unsupported data type: {type(data)}") + # data 字段本身就是每行的内容 + if 'data' not in df.columns: + # 兼容直接传入 dict 列表的情况 + df['data'] = df.apply(lambda row: row.to_dict(), axis=1) + # 统一处理 data 列 + df['data'] = df['data'].apply(lambda x: x if isinstance(x, dict) else (json.loads(x) if isinstance(x, str) else {})) + # 合并所有非系统字段到 data 字段并删除原列 + system_cols = {'pipeline_id', 'task_id', 'raw_data_id', 'min_hashes', 'file_id', 'filename', 'parent_pipeline_id', 'data'} + for col in df.columns: + if col not in system_cols: + df['data'] = df.apply(lambda row: safe_merge(row, col), axis=1) + df = df.drop(columns=[col]) + # 自动填充 pipeline_id, task_id, raw_data_id, min_hashes, file_id, filename, parent_pipeline_id + df['pipeline_id'] = self.pipeline_id + df['task_id'] = self.output_task_id + df['raw_data_id'] = df['data'].apply(lambda d: d.get(SYS_FIELD_PREFIX + 'raw_data_id', 0) if isinstance(d, dict) else 0) + df['min_hashes'] = df['data'].apply(lambda d: _default_min_hashes(d) if isinstance(d, dict) else [0]) + # 从 data 中提取 file_id、filename、parent_pipeline_id 字段 + df['file_id'] = df['data'].apply(lambda d: d.get(SYS_FIELD_PREFIX + 'file_id', '') if isinstance(d, dict) else '') + df['filename'] = df['data'].apply(lambda d: d.get(SYS_FIELD_PREFIX + 'filename', '') if isinstance(d, dict) else '') + df['parent_pipeline_id'] = df['data'].apply(lambda d: d.get(SYS_FIELD_PREFIX + 'parent_pipeline_id', '') if isinstance(d, dict) else '') + # 若 data 中未提供 parent_pipeline_id,使用实例属性回填 + if hasattr(self, 'parent_pipeline_id') and self.parent_pipeline_id: + df['parent_pipeline_id'] = df['parent_pipeline_id'].apply(lambda v: v if v else self.parent_pipeline_id) + # data 字段转为 JSON 字符串 + df['data'] = df['data'].apply(lambda x: json.dumps(x, ensure_ascii=False) if not isinstance(x, str) else x) + # 只保留必需字段 + required_cols = ['pipeline_id', 'task_id', 'raw_data_id', 'min_hashes', 'file_id', 'filename', 'parent_pipeline_id', 'data'] + df = df[required_cols] + records = df.to_dict(orient="records") + values = [ + ( + rec['pipeline_id'], + rec['task_id'], + int(rec['raw_data_id']), + rec['min_hashes'], + rec['file_id'], + rec['filename'], + rec['parent_pipeline_id'], + rec['data'] + ) for rec in records + ] + insert_sql = f""" + INSERT INTO {self.table} (pipeline_id, task_id, raw_data_id, min_hashes, file_id, filename, parent_pipeline_id, data) + VALUES + """ + self.logger.info(f"Inserting {len(values)} rows into {self.table}") + client.execute(insert_sql, values) + return f"Inserted {len(values)} rows into {self.table}" + + def get_keys_from_dataframe(self) -> list[str]: + """ + Get keys from the dataframe stored in MyScale/ClickHouse database. + Returns column names from the dataframe after reading from database. + """ + dataframe = self.read(output_type="dataframe") + return dataframe.columns.tolist() if isinstance(dataframe, pd.DataFrame) else [] + + +class BatchedFileStorage(FileStorage): + """ + 批量文件存储,支持按批次读写数据。 + """ + def __init__( + self, + first_entry_file_name: str, + cache_path:str="./cache", + file_name_prefix:str="dataflow_cache_step", + cache_type:Literal["jsonl", "csv"] = "jsonl", + ): + super().__init__(first_entry_file_name, cache_path, file_name_prefix, cache_type) + self.batch_size = None + self.batch_step = 0 + self._dataframe_buffer = {} + if cache_type not in ["jsonl", "csv"]: + raise ValueError(f"BatchedFileStorage only supports 'jsonl' and 'csv' cache types, got: {cache_type}") + + def read(self, output_type: Literal["dataframe", "dict"]="dataframe") -> Any: + """ + Read data from current file managed by storage. + + Args: + output_type: Type that you want to read to, either "dataframe" or "dict". + Also supports remote datasets with prefix: + - "hf:{dataset_name}{:config}{:split}" => HuggingFace dataset eg. "hf:openai/gsm8k:main:train" + - "ms:{dataset_name}{}:split}" => ModelScope dataset eg. "ms:modelscope/gsm8k:train" + + Returns: + Depending on output_type: + - "dataframe": pandas DataFrame + - "dict": List of dictionaries + + Raises: + ValueError: For unsupported file types or output types + """ + if self.operator_step == 0 and self.first_entry_file_name == "": + self.logger.info("first_entry_file_name is empty, returning empty dataframe") + empty_dataframe = pd.DataFrame() + return self._convert_output(empty_dataframe, output_type) + + file_path = self._get_cache_file_path(self.operator_step) + self.logger.info(f"Reading data from {file_path} with type {output_type}") + + if self.operator_step == 0: + source = self.first_entry_file_name + self.logger.info(f"Reading remote dataset from {source} with type {output_type}") + if source.startswith("hf:"): + from datasets import load_dataset + _, dataset_name, *parts = source.split(":") + + if len(parts) == 1: + config, split = None, parts[0] + elif len(parts) == 2: + config, split = parts + else: + config, split = None, "train" + + dataset = ( + load_dataset(dataset_name, config, split=split) + if config + else load_dataset(dataset_name, split=split) + ) + dataframe = dataset.to_pandas() + return self._convert_output(dataframe, output_type) + + elif source.startswith("ms:"): + from modelscope import MsDataset + _, dataset_name, *split_parts = source.split(":") + split = split_parts[0] if split_parts else "train" + + dataset = MsDataset.load(dataset_name, split=split) + dataframe = pd.DataFrame(dataset) + return self._convert_output(dataframe, output_type) + + else: + local_cache = file_path.split(".")[-1] + else: + local_cache = self.cache_type + if self._dataframe_buffer.get(self.operator_step) is not None: + dataframe = self._dataframe_buffer[self.operator_step].copy() + else: + dataframe = self._load_local_file(file_path, local_cache) + self._dataframe_buffer[self.operator_step] = dataframe.copy() + self.record_count = len(dataframe) + # 读出当前批次数据 + if self.batch_size: + dataframe = dataframe.iloc[ + self.batch_step * self.batch_size : (self.batch_step + 1) * self.batch_size + ].reset_index(drop=True) # reset_index, make the new index of every batch start from 0. Instead of its original index. + return self._convert_output(dataframe, output_type) + + def write(self, data: Any) -> Any: + """ + Write data to current file managed by storage. + data: Any, the data to write, it should be a dataframe, List[dict], etc. + """ + def clean_surrogates(obj): + """递归清理数据中的无效Unicode代理对字符""" + if isinstance(obj, str): + # 替换无效的Unicode代理对字符(如\udc00) + return obj.encode('utf-8', 'replace').decode('utf-8') + elif isinstance(obj, dict): + return {k: clean_surrogates(v) for k, v in obj.items()} + elif isinstance(obj, list): + return [clean_surrogates(item) for item in obj] + elif isinstance(obj, (int, float, bool)) or obj is None: + # 数字、布尔值和None直接返回 + return obj + else: + # 其他类型(如自定义对象)尝试转为字符串处理 + try: + return clean_surrogates(str(obj)) + except Exception: + # 如果转换失败,返回原对象或空字符串(根据需求选择) + return obj + + # 转换数据为DataFrame + if isinstance(data, list): + if len(data) > 0 and isinstance(data[0], dict): + # 清洗列表中的每个字典 + cleaned_data = [clean_surrogates(item) for item in data] + dataframe = pd.DataFrame(cleaned_data) + else: + raise ValueError(f"Unsupported data type: {type(data[0])}") + elif isinstance(data, pd.DataFrame): + # 对DataFrame的每个元素进行清洗 + dataframe = data.map(clean_surrogates) + else: + raise ValueError(f"Unsupported data type: {type(data)}") + + file_path = self._get_cache_file_path(self.operator_step + 1) + os.makedirs(os.path.dirname(file_path), exist_ok=True) + self.logger.success(f"Writing data to {file_path} with type {self.cache_type}") + if self.cache_type == "jsonl": + open_mode = 'w' if self.batch_step == 0 else 'a' + with open(file_path, open_mode, encoding='utf-8') as f: + dataframe.to_json(f, orient="records", lines=True, force_ascii=False) + elif self.cache_type == "csv": + if self.batch_step == 0: + dataframe.to_csv(file_path, index=False) + else: + dataframe.to_csv(file_path, index=False, header=False, mode='a') + else: + raise ValueError(f"Unsupported file type: {self.cache_type}, output file should end with jsonl, csv") + + return file_path + +class StreamBatchedFileStorage(BatchedFileStorage): + """ + 流式批量文件存储,支持按批次读写数据。 + """ + def __init__( + self, + first_entry_file_name: str, + cache_path:str="./cache", + file_name_prefix:str="dataflow_cache_step", + cache_type:Literal["jsonl", "csv"] = "jsonl", + ): + super().__init__(first_entry_file_name, cache_path, file_name_prefix, cache_type) + + def get_keys_from_dataframe(self) -> list[str]: + if self._dataframe_buffer.get(self.operator_step) is not None: + return self._dataframe_buffer[self.operator_step].columns.tolist() + + file_path = self._get_cache_file_path(self.operator_step) + ext = self.cache_type if self.operator_step != 0 else file_path.split(".")[-1].lower() + try: + if ext == "csv": + return pd.read_csv(file_path, nrows=0).columns.tolist() + + elif ext == "jsonl": + with open(file_path, 'r', encoding='utf-8') as f: + line = f.readline() + if line: + return list(json.loads(line).keys()) + return [] + + elif ext == "parquet": + # Parquet 格式在 Footer 存有 Schema,读取开销几乎为零 + import pyarrow.parquet as pq + return pq.ParquetFile(file_path).schema.names + + except Exception as e: + self.logger.warning(f"Failed to read header from {file_path} directly: {e}. Falling back to read().") + return [] + + def _load_local_file(self, file_path: str, file_type: str,batchsize: int=None) -> pd.DataFrame: + """Load data from local file based on file type.""" + # check if file exists + if not os.path.exists(file_path): + raise FileNotFoundError(f"File {file_path} does not exist. Please check the path.") + + try: + if file_type == "jsonl": + return pd.read_json(file_path, lines=True, chunksize=batchsize) + elif file_type == "csv": + return pd.read_csv(file_path, chunksize=batchsize) + return super()._load_local_file(file_path, file_type) + except Exception as e: + raise ValueError(f"Failed to load {file_type} file: {str(e)}") + + def get_record_count(self) -> int: + """显式获取记录总数,支持缓存以提高性能""" + if hasattr(self, "_cached_record_count"): + return self._cached_record_count + + file_path = self._get_cache_file_path(self.operator_step) + local_cache = self.cache_type if self.operator_step != 0 else file_path.split(".")[-1] + + if local_cache == "parquet": + import pyarrow.parquet as pq + count = pq.ParquetFile(file_path).metadata.num_rows + elif local_cache in ["jsonl", "csv"]: + count = 0 + with open(file_path, 'rb') as f: + for _ in f: count += 1 + if local_cache == "csv": count -= 1 # 扣除表头 + else: + df = self._load_local_file(file_path, local_cache) + count = len(df) + + self._cached_record_count = count + return count + + def read(self, output_type: Literal["dataframe", "dict"]="dataframe") -> Any: + + if hasattr(self, "_current_streaming_chunk") and self._current_streaming_chunk is not None: + return self._convert_output(self._current_streaming_chunk, output_type) + + if self.cache_type not in ["jsonl", "csv"]: + self.logger.warning( + f"Current cache_type '{self.cache_type}' does not support optimized streaming. " + f"The storage will fall back to loading the full file into memory." + ) + return super().read(output_type) + + def iter_chunks(self) -> Generator[pd.DataFrame, None, None]: + """ + 专门供 Pipeline 调用:产生原始的 DataFrame 流。 + """ + file_path = self._get_cache_file_path(self.operator_step) + local_cache = self.cache_type if self.operator_step != 0 else file_path.split(".")[-1] + + # 这里的 _load_local_file 必须确保在 batch_size 不为 None 时返回迭代器 + reader = self._load_local_file(file_path, local_cache, self.batch_size) + + # 确保 reader 是可迭代的 + if hasattr(reader, "__iter__") or isinstance(reader, pd.io.json._json.JsonReader): + for chunk in reader: + yield chunk + else: + yield reader # 如果不支持流式,就产出整个 DF diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/__pycache__/base.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99469e2ec3de8bf49144f83ae38f768c5f68c4c1 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/__pycache__/base.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/__pycache__/database_manager.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/__pycache__/database_manager.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be6b9e92478fa1c2bae5e5855862a16f1569037c Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/__pycache__/database_manager.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/base.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/base.py new file mode 100644 index 0000000000000000000000000000000000000000..04690842baabe1cb08ce2c73dac4c5669ff1f4a0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/base.py @@ -0,0 +1,76 @@ +from dataclasses import dataclass, field +from typing import Dict, Any, List, Optional, Tuple +from abc import ABC, abstractmethod +from dataflow import get_logger + + +# ============== Base Data Classes ============== +@dataclass +class DatabaseInfo: + """Database connection information""" + db_id: str + db_type: str + connection_info: Dict[str, Any] + metadata: Dict[str, Any] = field(default_factory=dict) + +@dataclass +class QueryResult: + """Standard query result format""" + success: bool + data: List[Dict[str, Any]] = field(default_factory=list) + columns: List[str] = field(default_factory=list) + error: Optional[str] = None + row_count: int = 0 + +# ============== Base Database Connector ============== +class DatabaseConnectorABC(ABC): + + def __init__(self): + self.logger = get_logger() + + @abstractmethod + def connect(self, connection_info: Dict) -> Any: + """Create database connection""" + pass + + @abstractmethod + def execute_query(self, connection: Any, sql: str, params: Optional[Tuple] = None) -> QueryResult: + """Execute SQL query and return standardized result""" + pass + + @abstractmethod + def explain_query(self, connection: Any, sql: str, params: Optional[Tuple] = None) -> QueryResult: + """Explain SQL query without executing it""" + pass + + @abstractmethod + def get_schema_info(self, connection: Any, db_id: Optional[str] = None) -> Dict[str, Any]: + """Get complete database schema information""" + pass + + @abstractmethod + def discover_databases(self, config: Dict) -> Dict[str, DatabaseInfo]: + """Discover available databases""" + pass + + @abstractmethod + def get_number_of_special_column(self, connection: Any): + """Get number of column which has spicial meaning""" + pass + + def validate_connection(self, connection: Any) -> bool: + """Check if connection is still valid""" + try: + self.execute_query(connection, "SELECT 1") + return True + except Exception as e: + self.logger.debug(f"Connection validation failed: {e}") + return False + + def close(self, connection: Any): + """Close database connection""" + try: + if hasattr(connection, 'close'): + connection.close() + except Exception as e: + self.logger.debug(f"Error closing connection: {e}") diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/database_connector/__pycache__/mysql_connector.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/database_connector/__pycache__/mysql_connector.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a93b110848e04cdb612272053562accfcedee1b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/database_connector/__pycache__/mysql_connector.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/database_connector/__pycache__/sqlite_connector.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/database_connector/__pycache__/sqlite_connector.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40337fd28c4f645ca279696f06d54bfd46329e20 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/database_connector/__pycache__/sqlite_connector.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/database_connector/__pycache__/sqlite_vec_connector.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/database_connector/__pycache__/sqlite_vec_connector.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..035054481b319f454ced6840697d8c5c181989b4 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/database_connector/__pycache__/sqlite_vec_connector.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/database_connector/mysql_connector.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/database_connector/mysql_connector.py new file mode 100644 index 0000000000000000000000000000000000000000..ca93552538da986581dd6b13f8427e3d5da2f260 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/database_connector/mysql_connector.py @@ -0,0 +1,343 @@ +from typing import Dict, Any, Optional, Tuple +from dataflow import get_logger +from ..base import DatabaseConnectorABC, DatabaseInfo, QueryResult +import pymysql +import pymysql.cursors +import time +import re + +class MySQLConnector(DatabaseConnectorABC): + """MySQL database connector implementation with full schema support""" + + def __init__(self): + self.logger = get_logger() + + def connect(self, connection_info: Dict) -> pymysql.Connection: + """Connect to MySQL database with read-only settings""" + config = { + 'connect_timeout': 10, + 'read_timeout': 30, + 'write_timeout': 30, + 'charset': 'utf8mb4', + 'cursorclass': pymysql.cursors.DictCursor, + 'autocommit': True + } + config.update(connection_info) + + try: + conn = pymysql.connect(**config) + with conn.cursor() as cursor: + cursor.execute("SET SESSION TRANSACTION READ ONLY") + cursor.execute("SET SESSION sql_mode = 'ANSI'") + return conn + except pymysql.Error as e: + self.logger.error(f"MySQL connection failed: {e}") + raise + + def execute_query(self, connection: pymysql.Connection, sql: str, params: Optional[Tuple] = None) -> QueryResult: + """Execute query with enhanced error handling and result processing""" + start_time = time.time() + cursor = None + + try: + cursor = connection.cursor() + if params: + cursor.execute(sql, params) + else: + cursor.execute(sql) + + # Handle different query types + if sql.strip().upper().startswith(('SELECT', 'SHOW', 'DESC', 'EXPLAIN')): + rows = cursor.fetchall() + columns = [desc[0] for desc in cursor.description] if cursor.description else [] + # Since we're using DictCursor, rows are already dictionaries + data = rows if rows else [] + else: + raise Exception("Write operations are not allowed in read-only mode") + + return QueryResult( + success=True, + data=data, + columns=columns, + row_count=len(data) + ) + except Exception as e: + self.logger.error(f"Query failed: {e}\nSQL: {sql}") + return QueryResult( + success=False, + error=str(e) + ) + finally: + if cursor: + cursor.close() + + def explain_query(self, connection: pymysql.Connection, sql: str, params: Optional[Tuple] = None) -> QueryResult: + stripped = sql.lstrip() + if not re.match(r'(?i)^explain\b', stripped): + sql = f"EXPLAIN {sql}" + return self.execute_query(connection, sql, params) + + def get_schema_info(self, connection: pymysql.Connection, db_id: Optional[str] = None) -> Dict[str, Any]: + """Get complete schema information with formatted DDL""" + schema = {'tables': {}} + + # Get current database + db_result = self.execute_query(connection, "SELECT DATABASE() AS db") + if not db_result.success or not db_result.data: + return schema + + db_name = db_result.data[0]['db'] + if not db_name: + self.logger.warning("No database selected") + return schema + + # Get all tables + tables_result = self.execute_query(connection, + "SELECT TABLE_NAME FROM information_schema.tables " + "WHERE table_schema = %s AND table_type = 'BASE TABLE'", + (db_name,)) + + if not tables_result.success: + return schema + + for row in tables_result.data: + table_name = row['TABLE_NAME'] + table_info = self._get_table_info(connection, db_name, table_name) + schema['tables'][table_name] = table_info + + schema['db_details'] = self._get_db_details(schema) + return schema + + def _get_table_info(self, connection: pymysql.Connection, db_name: str, table_name: str) -> Dict[str, Any]: + """Get detailed table information""" + table_info = { + 'columns': {}, + 'primary_keys': [], + 'foreign_keys': [], + 'sample_data': [], + 'create_statement': None, + 'insert_statement': [] + } + + # Get columns information + col_result = self.execute_query(connection, """ + SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_KEY, + EXTRA, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION + FROM information_schema.columns + WHERE table_schema = %s AND table_name = %s + ORDER BY ORDINAL_POSITION + """, (db_name, table_name)) + + if col_result.success: + for col in col_result.data: + col_name = col['COLUMN_NAME'] + default = col['COLUMN_DEFAULT'] + + # Format default value + if default is not None: + if isinstance(default, str) and default.upper() not in ('CURRENT_TIMESTAMP', 'NULL'): + default = f"'{default}'" + elif isinstance(default, bool): + default = str(int(default)) + + table_info['columns'][col_name] = { + 'type': col['COLUMN_TYPE'], + 'nullable': col['IS_NULLABLE'] == 'YES', + 'default': default, + 'primary_key': col['COLUMN_KEY'] == 'PRI' + } + if col['COLUMN_KEY'] == 'PRI': + table_info['primary_keys'].append(col_name) + + # Get foreign keys + fk_result = self.execute_query(connection, """ + SELECT + kcu.COLUMN_NAME, + kcu.REFERENCED_TABLE_NAME, + kcu.REFERENCED_COLUMN_NAME, + rc.UPDATE_RULE, + rc.DELETE_RULE + FROM information_schema.key_column_usage kcu + LEFT JOIN information_schema.referential_constraints rc + ON rc.CONSTRAINT_SCHEMA = kcu.TABLE_SCHEMA + AND rc.TABLE_NAME = kcu.TABLE_NAME + AND rc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME + WHERE kcu.TABLE_SCHEMA = %s + AND kcu.TABLE_NAME = %s + AND kcu.REFERENCED_TABLE_NAME IS NOT NULL + """, (db_name, table_name)) + + if fk_result.success: + for fk in fk_result.data: + table_info['foreign_keys'].append({ + 'column': fk['COLUMN_NAME'], + 'referenced_table': fk['REFERENCED_TABLE_NAME'], + 'referenced_column': fk['REFERENCED_COLUMN_NAME'], + 'update_rule': fk['UPDATE_RULE'], + 'delete_rule': fk['DELETE_RULE'] + }) + + # Get sample data (limited to 2 rows) + sample_result = self.execute_query(connection, + f"SELECT * FROM `{table_name}` LIMIT 2") + + if sample_result.success and sample_result.data: + table_info['sample_data'] = sample_result.data + column_names = list(sample_result.data[0].keys()) + + # Generate INSERT statements + for row in sample_result.data: + values = [] + for val in row.values(): + if val is None: + values.append('NULL') + elif isinstance(val, (int, float)): + values.append(str(val)) + elif isinstance(val, bool): + values.append('1' if val else '0') + else: + escaped = str(val).replace("'", "''").replace("\\", "\\\\") + values.append(f"'{escaped}'") + + insert_sql = ( + f"INSERT INTO `{table_name}` ({', '.join(f'`{c}`' for c in column_names)}) " + f"VALUES ({', '.join(values)});" + ) + table_info['insert_statement'].append(insert_sql) + + # Get create statement + create_result = self.execute_query(connection, + f"SHOW CREATE TABLE `{table_name}`") + + if create_result.success and create_result.data: + table_info['create_statement'] = create_result.data[0]['Create Table'] + + return table_info + + def _get_db_details(self, schema: Dict[str, Any]) -> str: + """Generate formatted DDL statements from schema information""" + db_details = [] + + for table_name, table_info in schema['tables'].items(): + # Use original create statement if available + if table_info['create_statement']: + create_table = table_info['create_statement'] + else: + # Build create statement from metadata + column_defs = [] + for col_name, col_info in table_info['columns'].items(): + col_def = f" `{col_name}` {col_info['type']}" + + if not col_info['nullable']: + col_def += " NOT NULL" + + if col_info['default'] is not None: + col_def += f" DEFAULT {col_info['default']}" + + if 'auto_increment' in col_info.get('extra', '').lower(): + col_def += " AUTO_INCREMENT" + + column_defs.append(col_def) + + # Add constraints + constraints = [] + + # Primary keys + if table_info['primary_keys']: + pk_cols = ", ".join(f"`{pk}`" for pk in table_info['primary_keys']) + constraints.append(f" PRIMARY KEY ({pk_cols})") + + # Foreign keys + for fk in table_info['foreign_keys']: + fk_def = ( + f" CONSTRAINT `fk_{table_name}_{fk['column']}` " + f"FOREIGN KEY (`{fk['column']}`) " + f"REFERENCES `{fk['referenced_table']}` (`{fk['referenced_column']}`)" + ) + if fk.get('update_rule'): + fk_def += f" ON UPDATE {fk['update_rule']}" + if fk.get('delete_rule'): + fk_def += f" ON DELETE {fk['delete_rule']}" + constraints.append(fk_def) + + create_table = f"CREATE TABLE `{table_name}` (\n" + create_table += ",\n".join(column_defs + constraints) + create_table += "\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;" + + db_details.append(create_table) + + # Add sample data if available + if table_info['sample_data']: + db_details.append("\n-- Sample data:") + db_details.extend(table_info['insert_statement']) + + return "\n\n".join(db_details) + + + + def discover_databases(self, config: Dict) -> Dict[str, DatabaseInfo]: + """Discover MySQL databases on server""" + databases = {} + + try: + # Create temp connection without specific database + temp_config = {k: v for k, v in config.items() if k != 'database'} + conn = self.connect(temp_config) + + # Get database list + result = self.execute_query(conn, + "SELECT schema_name as db_name FROM information_schema.schemata " + "WHERE schema_name NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys')") + + if result.success: + for row in result.data: + db_name = row.get('db_name') + if not db_name: + continue + databases[db_name] = DatabaseInfo( + db_id=db_name, + db_type='mysql', + connection_info={**config, 'database': db_name}, + metadata={ + 'host': config.get('host', 'localhost'), + 'port': config.get('port', 3306), + 'charset': config.get('charset', 'utf8mb4') + } + ) + self.logger.info(f"Discovered MySQL database: {db_name}") + + conn.close() + except Exception as e: + self.logger.error(f"Database discovery failed: {e}") + + return databases + + def get_number_of_special_column(self, connection: pymysql.Connection) -> int: + """ + Get the number of columns ending with '_embedding' in database + """ + count = 0 + try: + # Get the complete structure information of the database + schema = self.get_schema_info(connection) + + # Get all the table information from the schema + tables = schema.get('tables', {}) + + # Traverse each table + for table_name, table_info in tables.items(): + # Get all the column names from the table information + columns = table_info.get('columns', {}) + + # Traverse the column names + for column_name in columns.keys(): + # Check if the column name ends with '_embedding' + if isinstance(column_name, str) and column_name.endswith('_embedding'): + count += 1 + + except Exception as e: + self.logger.error(f"Error counting embedding columns: {e}") + + if count == 0: + self.logger.warning("No columns ending with '_embedding' found.") + return count \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/database_connector/sqlite_connector.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/database_connector/sqlite_connector.py new file mode 100644 index 0000000000000000000000000000000000000000..99cad52a2a15ba91ec67e0f18e76646c81e991a8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/database_connector/sqlite_connector.py @@ -0,0 +1,393 @@ +from typing import Dict, Any, Optional, Tuple +from ..base import DatabaseConnectorABC, DatabaseInfo, QueryResult +import sqlite3 +import glob +import os +import time +import re +import datetime +import decimal + +# ============== SQLite Connector ============== +class SQLiteConnector(DatabaseConnectorABC): + + def connect(self, connection_info: Dict) -> sqlite3.Connection: + db_path = connection_info['path'] + conn = sqlite3.connect(db_path, timeout=30) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA query_only = ON") + return conn + + def execute_query(self, connection: sqlite3.Connection, sql: str, params: Optional[Tuple] = None) -> QueryResult: + start_time = time.time() + cursor = None + try: + cursor = connection.cursor() + if params: + # Ensure params is a tuple and all values are properly formatted + if not isinstance(params, (tuple, list)): + params = (params,) + # Convert all params to strings and handle None values + if params and not isinstance(params, (tuple, list)): + params = (params,) + cursor.execute(sql, params or ()) + else: + cursor.execute(sql) + + rows = cursor.fetchall() + columns = [desc[0] for desc in cursor.description] if cursor.description else [] + data = [dict(zip(columns, row)) for row in rows] if columns else [] + + return QueryResult( + success=True, + data=data, + columns=columns, + row_count=len(data) + ) + except Exception as e: + self.logger.debug(f"Query execution failed (expected during filtering): {e}") + self.logger.debug(f"SQL: {sql}") + self.logger.debug(f"Params: {params}") + return QueryResult( + success=False, + error=str(e) + ) + finally: + if cursor: + cursor.close() + + def explain_query(self, connection: sqlite3.Connection, sql: str, params: Optional[Tuple] = None) -> QueryResult: + cursor = None + try: + cursor = connection.cursor() + stripped = sql.lstrip() + if not re.match(r'(?i)^explain(\s+query\s+plan)?\b', stripped): + sql = f"EXPLAIN QUERY PLAN {sql}" + if params: + if not isinstance(params, (tuple, list)): + params = (params,) + cursor.execute(sql, tuple(params)) + else: + cursor.execute(sql) + rows = cursor.fetchall() + columns = [desc[0] for desc in cursor.description] if cursor.description else [] + data = [dict(zip(columns, row)) for row in rows] if columns else [] + return QueryResult( + success=True, + data=data, + columns=columns, + row_count=len(data) + ) + except Exception as e: + self.logger.debug(f"Query explain failed (expected during filtering): {e}") + self.logger.debug(f"SQL: {sql}") + self.logger.debug(f"Params: {params}") + return QueryResult( + success=False, + error=str(e) + ) + finally: + if cursor: + cursor.close() + + def get_schema_info(self, connection: sqlite3.Connection, db_id: Optional[str] = None) -> Dict[str, Any]: + """Get complete schema information with formatted M-Schema""" + schema = {'tables': {}} + + result = self.execute_query( + connection, + "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'" + ) + + if not result.success: + return schema + + for row in result.data: + table_name = row['name'] + table_info = self._get_table_info(connection, table_name) + schema['tables'][table_name] = table_info + + if not db_id: + db_id = self._get_db_id_from_connection(connection) + schema['db_details'] = self._get_db_details(schema, db_id=db_id) + return schema + + def _get_table_info(self, connection: sqlite3.Connection, table_name: str) -> Dict[str, Any]: + """Get detailed table information""" + table_info = { + 'columns': {}, + 'primary_keys': [], + 'foreign_keys': [], + 'sample_data': [], + 'create_statement': None, + 'insert_statement': [] + } + + result = self.execute_query(connection, f"PRAGMA table_info({table_name})") + if result.success: + for col in result.data: + col_name = col['name'] + default_value = col['dflt_value'] + if default_value is not None and isinstance(default_value, str): + if default_value.upper() in ('CURRENT_TIMESTAMP', 'NULL'): + default_value = default_value.upper() + else: + default_value = f"'{default_value}'" + + table_info['columns'][col_name] = { + 'type': col['type'], + 'nullable': not col['notnull'], + 'default': default_value, + 'primary_key': bool(col['pk']), + 'comment': '', + 'examples': [] + } + if col['pk']: + table_info['primary_keys'].append(col_name) + + result = self.execute_query(connection, f"PRAGMA foreign_key_list({table_name})") + if result.success: + for fk in result.data: + table_info['foreign_keys'].append({ + 'column': fk['from'], + 'referenced_table': fk['table'], + 'referenced_column': fk['to'] + }) + + result = self.execute_query(connection, f"SELECT * FROM `{table_name}` LIMIT 2") + if result.success and result.data: + table_info['sample_data'] = result.data + column_names = list(result.data[0].keys()) + + for row in result.data: + values = [] + for value in row.values(): + if value is None: + values.append('NULL') + elif isinstance(value, (int, float)): + values.append(str(value)) + else: + escaped = str(value).replace("'", "''") + values.append(f"'{escaped}'") + + table_info['insert_statement'].append( + f"INSERT INTO `{table_name}` ({', '.join(column_names)}) VALUES ({', '.join(values)});" + ) + + result = self.execute_query(connection, + "SELECT sql FROM sqlite_master WHERE type='table' AND name = ?", + (table_name,)) + if result.success and result.data: + table_info['create_statement'] = result.data[0]['sql'] + + for column_name in table_info['columns'].keys(): + examples = self._fetch_distinct_values(connection, table_name, column_name, max_num=5) + table_info['columns'][column_name]['examples'] = self._examples_to_str(examples) + + return table_info + + def _get_db_details(self, schema: Dict[str, Any], db_id: str) -> str: + """Generate formatted M-Schema statements from schema information""" + output = [] + output.append(f"【DB_ID】 {db_id}") + output.append("【Schema】") + + for table_name, table_info in schema['tables'].items(): + table_comment = table_info.get('comment', '') + table_comment = '' if table_comment is None else table_comment.strip() + + if table_comment and table_comment != 'None': + output.append(f"# Table: {table_name}, {table_comment}") + else: + output.append(f"# Table: {table_name}") + + field_lines = [] + for field_name, field_info in table_info['columns'].items(): + raw_type = self._get_field_type(field_info.get('type', ''), simple_mode=True) + field_line = f"({field_name}:{raw_type.upper()}" + + field_comment = field_info.get('comment', '') + if field_comment is not None and field_comment != '': + field_line += f", {field_comment.strip()}" + + if field_info.get('primary_key', False): + field_line += ", Primary Key" + + examples = field_info.get('examples', []) + examples = [s for s in examples if s is not None] + examples = self._examples_to_str(examples) + example_num = 3 + + if len(examples) > example_num: + examples = examples[:example_num] + + if raw_type in ['DATE', 'TIME', 'DATETIME', 'TIMESTAMP']: + examples = [examples[0]] if examples else [] + elif len(examples) > 0 and max(len(s) for s in examples) > 20: + if max(len(s) for s in examples) > 50: + examples = [] + else: + examples = [examples[0]] + + if len(examples) > 0: + example_str = ', '.join([str(example) for example in examples]) + field_line += f", Examples: [{example_str}]" + + field_line += ")" + field_lines.append(field_line) + + output.append('[') + output.append(',\n'.join(field_lines)) + output.append(']') + + foreign_keys = [] + for table_name, table_info in schema['tables'].items(): + for fk in table_info.get('foreign_keys', []): + foreign_keys.append( + f"{table_name}.{fk['column']}={fk['referenced_table']}.{fk['referenced_column']}" + ) + + if foreign_keys: + output.append("【Foreign keys】") + output.extend(foreign_keys) + + return '\n'.join(output) + + def _get_db_id_from_connection(self, connection: sqlite3.Connection) -> str: + cursor = None + try: + cursor = connection.execute("PRAGMA database_list") + rows = cursor.fetchall() + except Exception: + rows = [] + finally: + if cursor: + cursor.close() + + for row in rows: + try: + name = row["name"] + file_path = row["file"] + except Exception: + name = row[1] if len(row) > 1 else None + file_path = row[2] if len(row) > 2 else None + if name == "main" and file_path: + return os.path.splitext(os.path.basename(file_path))[0] + return "Anonymous" + + def _fetch_distinct_values(self, connection: sqlite3.Connection, table_name: str, + column_name: str, max_num: int = 5) -> list: + quoted_table = self._quote_identifier(table_name) + quoted_column = self._quote_identifier(column_name) + sql = ( + f"SELECT DISTINCT {quoted_column} AS value " + f"FROM {quoted_table} " + f"WHERE {quoted_column} IS NOT NULL " + f"LIMIT {int(max_num)}" + ) + result = self.execute_query(connection, sql) + if not result.success: + return [] + return [row.get('value') for row in result.data if 'value' in row] + + def _quote_identifier(self, identifier: str) -> str: + return '"' + identifier.replace('"', '""') + '"' + + def _get_field_type(self, field_type: str, simple_mode: bool = True) -> str: + if not simple_mode: + return field_type + return field_type.split("(")[0] + + def _examples_to_str(self, examples: list) -> list: + values = list(examples) + for i in range(len(values)): + if isinstance(values[i], datetime.date): + values = [values[i]] + break + if isinstance(values[i], datetime.datetime): + values = [values[i]] + break + if isinstance(values[i], decimal.Decimal): + values[i] = str(float(values[i])) + if self._is_email(str(values[i])): + values = [] + break + if 'http://' in str(values[i]) or 'https://' in str(values[i]): + values = [] + break + if values[i] is not None and not isinstance(values[i], str): + pass + elif values[i] is not None and '.com' in values[i]: + pass + + return [str(v) for v in values if v is not None and len(str(v)) > 0] + + def _is_email(self, string: str) -> bool: + pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$' + match = re.match(pattern, string) + return match is not None + + def discover_databases(self, config: Dict) -> Dict[str, DatabaseInfo]: + """Discover SQLite database files""" + databases = {} + root_path = config.get('root_path', '.') + patterns = config.get('patterns', ['*.sqlite', '*.sqlite3', '*.db']) + + if isinstance(root_path, (list, tuple, set)): + root_paths = list(root_path) + else: + root_paths = [root_path] + + for root in root_paths: + for pattern in patterns: + for db_path in glob.glob(os.path.join(root, '**', pattern), recursive=True): + if os.path.isfile(db_path): + rel_path = os.path.relpath(db_path, root) + parts = rel_path.split(os.sep) + db_id = parts[0] if len(parts) > 1 else os.path.splitext(parts[0])[0] + + original_id = db_id + counter = 1 + while db_id in databases: + db_id = f"{original_id}_{counter}" + counter += 1 + + databases[db_id] = DatabaseInfo( + db_id=db_id, + db_type='sqlite', + connection_info={'path': db_path}, + metadata={'file_path': db_path, 'file_size': os.path.getsize(db_path)} + ) + self.logger.info(f"Discovered SQLite database: {db_id} at {db_path}") + + return databases + + def get_number_of_special_column(self, connection: sqlite3.Connection) -> int: + """ + Get the number of columns in database + """ + count = 0 + try: + # Get the complete structure information of the database + schema = self.get_schema_info(connection) + + # Get all the table information from the schema + tables = schema.get('tables', {}) + + # Traverse each table + for table_name, table_info in tables.items(): + # Get all the column names from the table information + columns = table_info.get('columns', {}) + + # Traverse the dictionary of columns (key is column name) + for column_name in columns: + # Check if the variable is a string + if isinstance(column_name, str): + count += 1 + + except Exception as e: + print(f"error: Error counting embedding columns: {e}") + + if count == 0: + print(f"error: No columns ending with '_embedding'.") + return count diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/database_connector/sqlite_vec_connector.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/database_connector/sqlite_vec_connector.py new file mode 100644 index 0000000000000000000000000000000000000000..467e5d2b8fffb502903e7106bffb9a6bd7ccc8c2 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/database_connector/sqlite_vec_connector.py @@ -0,0 +1,608 @@ +from typing import Dict, Any, Optional, Tuple +from ..base import DatabaseConnectorABC, DatabaseInfo, QueryResult +import sqlite3 +import glob +import os +import re +import threading +import time +from filelock import FileLock +from dataflow import get_logger + + +# ============== SQLite Connector ============== +class SQLiteVecConnector(DatabaseConnectorABC): + _class_lock = threading.Lock() + _db_init_locks: Dict[str, threading.Lock] = {} + _initialized_dbs = set() + + def __init__(self): + self.logger = get_logger() + self._thread_local = threading.local() + self._extensions_loaded = False + + def _ensure_vec_available(self): + if hasattr(self, '_sqlite_vec'): + return + try: + import sqlite_vec + self._sqlite_vec = sqlite_vec + except ImportError: + raise ImportError( + "The 'vectorsql' optional dependencies are required but not installed.\n" + "Please run: pip install 'open-dataflow[vectorsql]'" + ) + + def _ensure_lembed_available(self): + if hasattr(self, '_sqlite_lembed'): + return + try: + import sqlite_lembed + self._sqlite_lembed = sqlite_lembed + except ImportError: + raise ImportError( + "sqlite_lembed is required for vector SQL execution. " + "Please run: pip install 'open-dataflow[vectorsql]'" + ) + + def connect(self, connection_info: Dict) -> sqlite3.Connection: + """ + Connect to the database. Returns an independent connection for each calling thread, + ensuring that dangerous initialization is performed only once, while safely loading + the model into memory for each connection. + """ + self._ensure_vec_available() + + db_path = connection_info.get('path') + if not db_path: + raise ValueError("Connection info must contain a 'path' key.") + + if not hasattr(self._thread_local, 'connections'): + self._thread_local.connections = {} + if db_path in self._thread_local.connections: + return self._thread_local.connections[db_path] + + # Step 1: One-time initialization (ensure model has been written to DB file) + # This code block is executed only once for each DB file in each process. + # Use class-level lock to ensure the check and _initialize_database_disk_state call are thread-safe. + with self._class_lock: + if db_path not in self._initialized_dbs: + self.logger.info(f"'{db_path}' is not initialized in this process. Performing one-time disk setup...") + self._initialize_database_disk_state(connection_info) + self._initialized_dbs.add(db_path) + + # Step 2: Create a connection for the current thread + self.logger.debug(f"Thread {threading.get_ident()} creating new DB connection for '{db_path}'...") + conn = sqlite3.connect( + db_path, + timeout=30.0, + check_same_thread=False + ) + conn.row_factory = sqlite3.Row + + # Step 3: Load extensions and activate model for each new connection + model_name = connection_info.get('model_name') + model_path = connection_info.get('model_path') + enable_lembed = connection_info.get('enable_lembed', True) + if model_path: + model_path = os.path.abspath(model_path) + + lock_path = db_path + ".lock" + file_lock = FileLock(lock_path, timeout=120) + + with file_lock: + self.logger.debug(f"Process-safe lock acquired by thread {threading.get_ident()}. Configuring connection...") + conn.enable_load_extension(True) + self._sqlite_vec.load(conn) + + if enable_lembed: + self._ensure_lembed_available() + self._sqlite_lembed.load(conn) + self._ensure_trusted_schema_enabled(conn) + + if enable_lembed and model_name and model_path: + self.logger.debug(f"Activating model '{model_name}' for connection...") + register_sql = """ + INSERT OR IGNORE INTO main.lembed_models (name, model) + VALUES (?, lembed_model_from_file(?)) + """ + temp_register_sql = """ + INSERT OR IGNORE INTO temp.lembed_models (name, model) + VALUES (?, lembed_model_from_file(?)) + """ + def _register(sql: str, target: str) -> bool: + for attempt in range(3): + try: + conn.execute(sql, (model_name, model_path)) + conn.commit() + return True + except Exception as exc: + try: + conn.rollback() + except Exception: + pass + if attempt < 2: + wait = 0.5 * (attempt + 1) + self.logger.debug( + f"Registering model '{model_name}' in {target} failed (attempt {attempt + 1}/3). " + f"Retrying in {wait:.1f}s. Error: {exc}", + extra={ + "db_path": db_path, + "model_name": model_name, + "target": target, + "trusted_schema": self._get_trusted_schema_value(conn), + }, + exc_info=True + ) + time.sleep(wait) + else: + self.logger.debug( + f"Registration attempt exhausted for '{model_name}' in {target}: {exc}", + extra={ + "db_path": db_path, + "model_name": model_name, + "target": target, + "trusted_schema": self._get_trusted_schema_value(conn), + }, + exc_info=True + ) + return False + + if not _register(register_sql, "main.lembed_models"): + if not _register(temp_register_sql, "temp.lembed_models"): + raise RuntimeError( + f"Failed to register model '{model_name}' for database '{db_path}' even in temp schema." + ) + else: + self.logger.info( + f"Model '{model_name}' registered in temp.lembed_models for connection '{db_path}'." + ) + + self._thread_local.connections[db_path] = conn + self.logger.debug(f"Connection for thread {threading.get_ident()} created and configured successfully.") + return conn + + def _get_trusted_schema_value(self, connection: sqlite3.Connection) -> Optional[int]: + try: + cursor = connection.execute("PRAGMA trusted_schema") + result = cursor.fetchone() + cursor.close() + except Exception as exc: + self.logger.debug(f"Unable to read PRAGMA trusted_schema: {exc}") + return None + + if result: + try: + return int(result[0]) + except (TypeError, ValueError): + return None + return None + + def _ensure_trusted_schema_enabled(self, connection: sqlite3.Connection) -> None: + """Enable trusted_schema when sqlite is built with it disabled by default.""" + value = self._get_trusted_schema_value(connection) + + if value == 1: + return + + self.logger.info( + "trusted_schema is disabled for current SQLite connection. Enabling it to allow sqlite_lembed to load models." + ) + connection.execute("PRAGMA trusted_schema=ON;") + self.logger.debug("trusted_schema set to 1 for current SQLite connection.") + + def _initialize_database_disk_state(self, connection_info: Dict): + self._ensure_vec_available() + + db_path = connection_info['path'] + model_name = connection_info.get('model_name') + model_path = connection_info.get('model_path') + enable_lembed = connection_info.get('enable_lembed', True) + if model_path: + model_path = os.path.abspath(model_path) + + lock_path = db_path + ".lock" + file_lock = FileLock(lock_path, timeout=120) + + with file_lock: + init_conn = None + try: + init_conn = sqlite3.connect(db_path, timeout=30.0) + init_conn.execute("PRAGMA journal_mode=WAL;") + init_conn.enable_load_extension(True) + self._sqlite_vec.load(init_conn) + + if enable_lembed: + self._ensure_lembed_available() + self._sqlite_lembed.load(init_conn) + self._ensure_trusted_schema_enabled(init_conn) + trusted_schema = self._get_trusted_schema_value(init_conn) + else: + trusted_schema = None + + if enable_lembed and model_name and model_path: + if not os.path.exists(model_path): + raise FileNotFoundError(f"Embedding model file not found at path: {model_path}") + abs_model_path = os.path.abspath(model_path) + + self.logger.info( + f"Lock acquired. Ensuring model '{model_name}' is persisted in '{db_path}' " + f"(source model path: '{abs_model_path}')..." + ) + self.logger.debug( + f"trusted_schema value before model registration for '{db_path}': {trusted_schema}" + ) + register_sql = """ + INSERT OR IGNORE INTO main.lembed_models (name, model) + VALUES (?, lembed_model_from_file(?)) + """ + persisted = False + for attempt in range(3): + try: + init_conn.execute(register_sql, (model_name, abs_model_path)) + init_conn.commit() + self.logger.info(f"Model '{model_name}' persistence check completed.") + persisted = True + break + except Exception as exc: + try: + init_conn.rollback() + except Exception: + pass + if attempt < 2: + wait_time = 0.5 * (attempt + 1) + self.logger.warning( + "Persisting embedding model into database failed (attempt %d/3). " + "Retrying in %.1fs. Error: %s", + attempt + 1, + wait_time, + exc, + extra={ + "db_path": db_path, + "model_name": model_name, + "model_path": abs_model_path, + "trusted_schema": trusted_schema, + }, + exc_info=True + ) + time.sleep(wait_time) + else: + self.logger.warning( + "Failed to persist embedding model into database after retries. " + "Will rely on per-connection loading. Error: %s", + exc, + extra={ + "db_path": db_path, + "model_name": model_name, + "model_path": abs_model_path, + "trusted_schema": trusted_schema, + }, + exc_info=True + ) + if not persisted: + self.logger.debug( + f"Model '{model_name}' not stored in '{db_path}'. Runtime registration will be used." + ) + finally: + if init_conn: + init_conn.close() + + def close(self, connection: Optional[sqlite3.Connection] = None): + if hasattr(self._thread_local, 'connections'): + if connection: + for db_path, conn in list(self._thread_local.connections.items()): + if conn == connection: + try: + conn.close() + self.logger.debug(f"Thread {threading.get_ident()} closed the specified connection to '{db_path}'.") + del self._thread_local.connections[db_path] + except Exception as e: + self.logger.error(f"Error closing specified connection to '{db_path}': {e}", exc_info=True) + break + else: + for db_path, conn in self._thread_local.connections.items(): + try: + conn.close() + self.logger.debug(f"Thread {threading.get_ident()} closed connection to '{db_path}'.") + except Exception as e: + self.logger.error(f"Error closing connection to '{db_path}': {e}", exc_info=True) + self._thread_local.connections = {} + + def execute_query(self, connection: sqlite3.Connection, sql: str, params: Optional[Tuple] = None) -> QueryResult: + cursor = None + try: + cursor = connection.cursor() + if params: + cursor.execute(sql, params) + else: + cursor.execute(sql) + + rows = cursor.fetchall() + columns = [desc[0] for desc in cursor.description] if cursor.description else [] + data = [dict(zip(columns, row)) for row in rows] if columns else [] + + return QueryResult( + success=True, + data=data, + columns=columns, + row_count=len(data) + ) + except Exception as e: + self.logger.debug(f"Query execution error: {e}") + return QueryResult( + success=False, + error=str(e) + ) + finally: + if cursor: + try: + cursor.close() + except Exception: + pass + + def explain_query(self, connection: sqlite3.Connection, sql: str, params: Optional[Tuple] = None) -> QueryResult: + cursor = None + try: + cursor = connection.cursor() + stripped = sql.lstrip() + if not re.match(r'(?i)^explain(\s+query\s+plan)?\b', stripped): + sql = f"EXPLAIN QUERY PLAN {sql}" + if params: + cursor.execute(sql, params) + else: + cursor.execute(sql) + rows = cursor.fetchall() + columns = [desc[0] for desc in cursor.description] if cursor.description else [] + data = [dict(zip(columns, row)) for row in rows] if columns else [] + return QueryResult( + success=True, + data=data, + columns=columns, + row_count=len(data) + ) + except Exception as e: + self.logger.debug(f"Query explain error: {e}") + return QueryResult( + success=False, + error=str(e) + ) + finally: + if cursor: + try: + cursor.close() + except Exception: + pass + + def _get_db_details(self, schema: Dict[str, Any]) -> str: + db_details = [] + + for table_name, table_info in schema['tables'].items(): + original_create_statement = table_info.get('create_statement', '') + is_virtual_table = "CREATE VIRTUAL TABLE" in original_create_statement.upper() + + if is_virtual_table: + db_details.append(original_create_statement) + else: + column_defs = [] + for col_name, col_info in table_info.get('columns', {}).items(): + col_def = f" `{col_name}` {col_info['type']}" + if not col_info.get('nullable', True): + col_def += " NOT NULL" + if col_info.get('default') is not None: + col_def += f" DEFAULT {col_info['default']}" + column_defs.append(col_def) + + constraints = [] + primary_keys = table_info.get('primary_keys', []) + if primary_keys: + pk_cols = ", ".join(f"`{col}`" for col in primary_keys) + constraints.append(f" PRIMARY KEY ({pk_cols})") + + foreign_keys = table_info.get('foreign_keys', []) + for i, fk in enumerate(foreign_keys): + constraints.append( + f" CONSTRAINT fk_{table_name}_{fk['column']}_{i} " + f"FOREIGN KEY (`{fk['column']}`) " + f"REFERENCES `{fk['referenced_table']}` (`{fk['referenced_column']}`)" + ) + + create_table = f"CREATE TABLE `{table_name}` (\n" + all_parts = column_defs + constraints + create_table += ",\n".join(all_parts) + create_table += "\n);" + + insert_statements = table_info.get('insert_statement', []) + if insert_statements: + create_table += "\n\n-- Sample data:\n" + if isinstance(insert_statements, list): + create_table += "\n".join(insert_statements) + else: + create_table += str(insert_statements) + + db_details.append(create_table) + + return "\n\n".join(db_details) + + def get_schema_info(self, connection: sqlite3.Connection, db_id: Optional[str] = None) -> Dict[str, Any]: + schema = {'tables': {}} + + result = self.execute_query( + connection, + "SELECT name, sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'" + ) + + if not result.success: + return schema + + for row in result.data: + table_name = row['name'] + create_statement = row['sql'] + table_info = self._get_table_info(connection, table_name, create_statement) + schema['tables'][table_name] = table_info + + schema['db_details'] = self._get_db_details(schema) + return schema + + def generate_create_statement(self, table_name: str, table_info: Dict[str, Any]) -> str: + create_stmt = "" + columns = [] + for col_name, col_info in table_info.get('columns', {}).items(): + col_def = f"`{col_name}` {col_info['type']}" + if not col_info.get('nullable', True): + col_def += " NOT NULL" + if col_info.get('default') is not None: + col_def += f" DEFAULT {col_info['default']}" + columns.append(col_def) + + pk_cols = table_info.get('primary_keys', []) + if pk_cols: + columns.append(f"PRIMARY KEY ({', '.join(f'`{pk}`' for pk in pk_cols)})") + + for fk in table_info.get('foreign_keys', []): + fk_def = (f"FOREIGN KEY (`{fk['column']}`) " + f"REFERENCES `{fk['referenced_table']}`(`{fk['referenced_column']}`)") + columns.append(fk_def) + + if columns: + create_stmt = f"CREATE TABLE `{table_name}` (\n " + ",\n ".join(columns) + "\n);" + + return create_stmt + + def _get_table_info(self, connection: sqlite3.Connection, table_name: str, create_statement: str) -> Dict[str, Any]: + is_vec_table = "USING vec0" in create_statement.upper() + + table_info = { + 'columns': {}, 'primary_keys': [], 'foreign_keys': [], 'sample_data': [], + 'create_statement': create_statement, 'insert_statement': None + } + + result = self.execute_query(connection, f"PRAGMA table_info([{table_name}])") + if result.success: + for col in result.data: + col_name = col['name'] + table_info['columns'][col_name] = { + 'type': col['type'], 'nullable': not col['notnull'], + 'default': col['dflt_value'], 'primary_key': bool(col['pk']) + } + + if is_vec_table: + self.logger.info(f"Detected sqlite-vec virtual table: '{table_name}'. Skipping sample data and foreign key retrieval.") + else: + for col in result.data: + if col['pk']: + table_info['primary_keys'].append(col['name']) + + fk_result = self.execute_query(connection, f"PRAGMA foreign_key_list([{table_name}])") + if fk_result.success: + for fk in fk_result.data: + table_info['foreign_keys'].append({ + 'column': fk['from'], 'referenced_table': fk['table'], 'referenced_column': fk['to'] + }) + + all_columns = list(table_info['columns'].keys()) + columns_to_select = [f"`{col}`" for col in all_columns if not col.endswith('_embedding')] + + if columns_to_select: + select_clause = ", ".join(columns_to_select) + sample_query = f"SELECT {select_clause} FROM [{table_name}] LIMIT 3" + sample_result = self.execute_query(connection, sample_query) + + if sample_result.success and sample_result.data: + is_data_too_long = False + for row in sample_result.data: + row_char_length = sum(len(str(value)) for value in row.values()) + if row_char_length > 10000: + self.logger.warning(f"A row of sample data for table '{table_name}' exceeds 10,000 characters and will be ignored.") + is_data_too_long = True + break + + if not is_data_too_long: + table_info['sample_data'] = sample_result.data + + table_info['create_statement'] = self.generate_create_statement(table_name, table_info) + + if table_info['sample_data']: + insert_statement_list = [] + for row in table_info['sample_data']: + columns = list(row.keys()) + values = [] + for col in columns: + val = row[col] + if val is None: + values.append('NULL') + elif isinstance(val, (int, float)): + values.append(str(val)) + else: + escaped_val = str(val).replace("'", "''") + values.append(f"'{escaped_val}'") + + table_ref = f"[{table_name}]" + col_ref = [f"[{col}]" for col in columns] + insert_sql = f"INSERT INTO {table_ref} ({', '.join(col_ref)}) VALUES ({', '.join(values)})" + insert_statement_list.append(insert_sql) + table_info['insert_statement'] = "\n\n".join(insert_statement_list) + + return table_info + + def discover_databases(self, config: Dict) -> Dict[str, DatabaseInfo]: + databases = {} + root_path = config.get('root_path', '.') + patterns = config.get('patterns', ['*.sqlite', '*.sqlite3', '*.db']) + + for pattern in patterns: + for db_path in glob.glob(os.path.join(root_path, '**', pattern), recursive=True): + if os.path.isfile(db_path): + db_id = os.path.splitext(os.path.basename(db_path))[0] + + original_id = db_id + counter = 1 + while db_id in databases: + db_id = f"{original_id}_{counter}" + counter += 1 + + connection_info = { + 'path': db_path, + 'model_name': config.get('model_name'), + 'model_path': config.get('model_path'), + 'enable_lembed': config.get('enable_lembed', True) + } + + databases[db_id] = DatabaseInfo( + db_id=db_id, + db_type='sqlite-vec', + connection_info=connection_info, + metadata={'file_path': db_path, 'file_size': os.path.getsize(db_path)} + ) + self.logger.info(f"Discovered SQLite database: {db_id} at {db_path}") + + return databases + + def get_number_of_special_column(self, connection: sqlite3.Connection) -> int: + """ + get the number of vector columns in database + """ + count = 0 + try: + # Get the complete structure information of the database + schema = self.get_schema_info(connection) + + # Get all the table information from the schema + tables = schema.get('tables', {}) + + # Traverse each table + for table_name, table_info in tables.items(): + # Get all the column names from the table information + columns = table_info.get('columns', []) + + # Directly traverse the list of column names + for column_name in columns: + # Check if the variable is a string, and whether it ends with "_embedding" + if isinstance(column_name, str) and column_name.endswith("_embedding"): + count += 1 + + except Exception as e: + print(f"error: Error counting embedding columns {e}") + + if count == 0: + print(f"error: No columns ending with '_embedding'.") + return count diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/database_manager.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/database_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..38d1c351de832517a7f9de03bb4331ad8abb2082 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/text2sql/database_manager.py @@ -0,0 +1,400 @@ +from typing import Dict, List, Optional, Any, Tuple +from contextlib import contextmanager +from concurrent.futures import ThreadPoolExecutor, as_completed, TimeoutError +import threading +import hashlib +import time +import os +import json +import re +from dataflow import get_logger +from .base import DatabaseInfo, QueryResult +from .database_connector.sqlite_connector import SQLiteConnector +from .database_connector.sqlite_vec_connector import SQLiteVecConnector +from .database_connector.mysql_connector import MySQLConnector +from dataflow.core import LLMServingABC + + +# ============== Cache Manager ============== +class CacheManager: + + def __init__(self, max_size: int = 100, ttl: int = 1800): + self.max_size = max_size + self.ttl = ttl + self._cache = {} + self._timestamps = {} + self._lock = threading.RLock() + self._last_cleanup = time.time() + + def _make_key(self, *args) -> str: + """Generate cache key from arguments""" + key_str = '|'.join(str(arg) for arg in args) + return hashlib.md5(key_str.encode()).hexdigest() + + def get(self, *args) -> Optional[Any]: + """Get value from cache""" + key = self._make_key(*args) + with self._lock: + current_time = time.time() + if current_time - self._last_cleanup > 300: + self._cleanup_expired() + self._last_cleanup = current_time + + if key in self._cache: + if current_time - self._timestamps[key] < self.ttl: + return self._cache[key] + else: + del self._cache[key] + del self._timestamps[key] + return None + + def set(self, value: Any, *args): + """Set value in cache""" + key = self._make_key(*args) + with self._lock: + if len(self._cache) >= self.max_size: + items_to_remove = len(self._cache) - self.max_size + 1 + oldest = sorted(self._timestamps.items(), key=lambda x: x[1])[:items_to_remove] + for old_key, _ in oldest: + del self._cache[old_key] + del self._timestamps[old_key] + + self._cache[key] = value + self._timestamps[key] = time.time() + + def clear(self): + """Clear all cache entries""" + with self._lock: + self._cache.clear() + self._timestamps.clear() + + def _cleanup_expired(self): + """Clean up expired cache entries""" + current_time = time.time() + expired_keys = [ + key for key, timestamp in self._timestamps.items() + if current_time - timestamp >= self.ttl + ] + for key in expired_keys: + del self._cache[key] + del self._timestamps[key] + + +# ============== Database Manager ============== +class DatabaseManager: + _LEMBED_PATTERN = re.compile( + r"lembed\s*\(\s*(['\"]?)[^,]*?\1\s*,\s*(['\"])(.*?)\2\s*\)", + re.IGNORECASE | re.DOTALL + ) + + # Registry of available connectors + # You must add the database connector class here if you want to support a new database type + CONNECTORS = { + 'sqlite': SQLiteConnector, + 'mysql': MySQLConnector, + 'sqlite-vec': SQLiteVecConnector, + # Add new database types here + # 'postgres': PostgresConnector + } + + def __init__(self, db_type: str = "sqlite", config: Optional[Dict] = None, + embedding_serving: Optional[LLMServingABC] = None): + self.db_type = db_type.lower() + self.config = config or {} + self.embedding_serving = embedding_serving + self._embedding_cache: Dict[str, List[float]] = {} + + self.logger = get_logger() + default_workers = 20 + self.max_connections_per_db = 3 + self.max_workers = 20 + self.query_timeout = 5 + + if self.db_type not in self.CONNECTORS: + raise ValueError(f"Unsupported database type: {self.db_type}") + + self.connector = self.CONNECTORS[self.db_type]() + self.databases = {} + self.cache = CacheManager() + + self._discover_databases() + + + # ============== Database Discovery ============== + + def _discover_databases(self): + """Traverse to discover all available databases""" + self.databases = self.connector.discover_databases(self.config) + + + # ============== Connection Management ============== + + @contextmanager + def get_connection(self, db_id: str): + if db_id not in self.databases: + raise ValueError(f"Database '{db_id}' not found") + + conn = None + try: + conn = self.connector.connect(self.databases[db_id].connection_info) + yield conn + except Exception as e: + self.logger.error(f"Connection error for database '{db_id}': {e}") + raise + finally: + if conn: + try: + self.connector.close(conn) + except Exception as e: + self.logger.error(f"Error closing connection: {e}") + + # ============== SQL Execution ============== + def batch_compare_queries(self, query_triples: List[Tuple[str, str, str]]) -> List[Dict[str, Any]]: + """ + Compare multiple pairs of queries across different databases in parallel. + """ + unique_db_ids = set(db_id for db_id, _, _ in query_triples) + for db_id in unique_db_ids: + if not self.database_exists(db_id): + error_msg = f"Database '{db_id}' not found" + return [self._create_error_result(error_msg) for _ in query_triples] + + all_queries = [] + for idx, (db_id, gold_sql, pred_sql) in enumerate(query_triples): + all_queries.extend([ + (db_id, gold_sql), + (db_id, pred_sql) + ]) + + # Batch execute all queries + all_results = self.batch_execute_queries(all_queries) + + # Group results by comparison pairs + comparisons = [] + for i in range(len(query_triples)): + result1 = all_results[2*i] + result2 = all_results[2*i + 1] + comparisons.append(self.compare_results(result1, result2)) + + return comparisons + + def batch_execute_queries(self, queries: List[Tuple[str, str]]) -> List[QueryResult]: + results = [QueryResult(success=False, error="Not executed") for _ in queries] + + with ThreadPoolExecutor(max_workers=self.max_workers) as executor: + futures = {} + semaphores = {db_id: threading.Semaphore(self.max_connections_per_db) for db_id, _ in set(queries)} + + def execute_with_limit(idx, db_id, sql): + with semaphores[db_id]: + try: + with self.get_connection(db_id) as conn: + result = self.connector.execute_query(conn, sql) + results[idx] = result + except Exception as e: + results[idx] = QueryResult( + success=False, + error=f"{type(e).__name__}: {str(e)}" + ) + + for idx, (db_id, sql) in enumerate(queries): + try: + processed_sql = self._preprocess_sql_for_execution(sql) + except Exception as exc: + results[idx] = QueryResult(success=False, error=f"Preprocessing error: {exc}") + continue + futures[executor.submit(execute_with_limit, idx, db_id, processed_sql)] = idx + + try: + if futures: + for future in as_completed(futures, timeout=self.query_timeout*len(futures)): + future.result() + except TimeoutError: + self.logger.warning("Batch execution timed out") + + return results + + def batch_explain_queries(self, queries: List[Tuple[str, str]]) -> List[QueryResult]: + results = [QueryResult(success=False, error="Not explained") for _ in queries] + + with ThreadPoolExecutor(max_workers=self.max_workers) as executor: + futures = {} + semaphores = {db_id: threading.Semaphore(self.max_connections_per_db) for db_id, _ in set(queries)} + + def explain_with_limit(idx, db_id, sql): + with semaphores[db_id]: + try: + with self.get_connection(db_id) as conn: + result = self.connector.explain_query(conn, sql) + results[idx] = result + except Exception as e: + results[idx] = QueryResult( + success=False, + error=f"{type(e).__name__}: {str(e)}" + ) + + for idx, (db_id, sql) in enumerate(queries): + try: + processed_sql = self._preprocess_sql_for_execution(sql) + except Exception as exc: + results[idx] = QueryResult(success=False, error=f"Preprocessing error: {exc}") + continue + futures[executor.submit(explain_with_limit, idx, db_id, processed_sql)] = idx + + try: + if futures: + for future in as_completed(futures, timeout=self.query_timeout*len(futures)): + future.result() + except TimeoutError: + self.logger.warning("Batch explain timed out") + + return results + + def compare_queries(self, db_id: str, sql1: str, sql2: str) -> Dict[str, Any]: + """Compare results of two SQL queries""" + results = self.batch_execute_queries([(db_id, sql1), (db_id, sql2)]) + return self.compare_results(results[0], results[1]) + + + def compare_results(self, result1: QueryResult, result2: QueryResult) -> Dict[str, Any]: + """Compare two query results""" + comparison = { + 'equal': False, + 'differences': [], + 'result1_success': result1.success, + 'result2_success': result2.success, + } + + if not result1.success or not result2.success: + if not result1.success: + comparison['differences'].append(f'Query 1 failed: {result1.error}') + if not result2.success: + comparison['differences'].append(f'Query 2 failed: {result2.error}') + return comparison + + # Compare row counts + if result1.row_count != result2.row_count: + comparison['differences'].append( + f'Row count mismatch: {result1.row_count} vs {result2.row_count}' + ) + return comparison + + # Compare columns + if set(result1.columns) != set(result2.columns): + comparison['differences'].append( + f'Column mismatch: {result1.columns} vs {result2.columns}' + ) + return comparison + + # Compare data - use a simpler approach that avoids None comparison issues + def normalize_row(row): + """Normalize row data, converting None to empty string to avoid comparison issues""" + normalized_items = [] + for k, v in row.items(): + # Convert None to empty string to avoid comparison issues + normalized_value = "" if v is None else str(v) + normalized_items.append((k, normalized_value)) + return tuple(sorted(normalized_items)) + + data1 = sorted([normalize_row(row) for row in result1.data]) + data2 = sorted([normalize_row(row) for row in result2.data]) + + if data1 == data2: + comparison['equal'] = True + else: + for i, (row1, row2) in enumerate(zip(data1, data2)): + if row1 != row2: + comparison['differences'].append(f'Row {i} differs: {dict(row1)} vs {dict(row2)}') + if len(comparison['differences']) >= 10: + comparison['differences'].append('... and more differences') + break + + return comparison + + + # ============== Schema Generation ============== + # In our application case, only create_statements and insert_statements are needed + # You can add more schema generation methods here if needed + + def _get_schema(self, db_id: str) -> Dict[str, Any]: + schema_cache = self.cache.get('schema', db_id) + if schema_cache: + return schema_cache + + with self.get_connection(db_id) as conn: + schema = self.connector.get_schema_info(conn, db_id=db_id) + self.cache.set(schema, 'schema', db_id) + return schema + + def _get_create_statements(self, schema: Dict[str, Any]) -> List[str]: + create_statement_list = [table_info['create_statement'] for table_info in schema['tables'].values()] + return create_statement_list + + def _get_insert_statements(self, schema: Dict[str, Any]) -> List[str]: + insert_statement_list = [] + for table_info in schema['tables'].values(): + insert_statements_for_table = table_info.get('insert_statement') + if insert_statements_for_table: + insert_statement_list.extend(insert_statements_for_table) + + return insert_statement_list + + def get_create_statements_and_insert_statements(self, db_id: str) -> tuple: + if not self.database_exists(db_id): + raise ValueError(f"Database '{db_id}' not found") + + schema = self._get_schema(db_id) + create_statements = self._get_create_statements(schema) + insert_statements = self._get_insert_statements(schema) + return (create_statements, insert_statements) + + def get_db_details(self, db_id: str) -> str: + if not self.database_exists(db_id): + raise ValueError(f"Database '{db_id}' not found") + schema = self._get_schema(db_id) + return schema['db_details'] + + + # ============== Utility Methods ============== + def database_exists(self, db_id: str) -> bool: + """Check if database exists""" + return db_id in self.databases + + def list_databases(self) -> List[str]: + """List all available databases""" + return list(self.databases.keys()) + + def _create_error_result(self, error_msg: str) -> Dict[str, Any]: + """Create standardized error result""" + return { + 'equal': False, + 'differences': [error_msg], + 'result1_success': False, + 'result2_success': False, + } + + def _get_embedding_vector(self, text: str) -> List[float]: + if text in self._embedding_cache: + return self._embedding_cache[text] + + if not self.embedding_serving: + raise RuntimeError("Embedding serving is not configured.") + + vectors = self.embedding_serving.generate_embedding_from_input([text]) + if not vectors: + raise RuntimeError("Embedding serving returned empty result.") + + embedding = vectors[0] + self._embedding_cache[text] = embedding + return embedding + + def _preprocess_sql_for_execution(self, sql: str) -> str: + if not sql or self.embedding_serving is None or self.db_type != 'sqlite-vec': + return sql + + def replacer(match: re.Match) -> str: + text = match.group(3) + embedding = self._get_embedding_vector(text) + return "'" + json.dumps(embedding, ensure_ascii=False) + "'" + + return self._LEMBED_PATTERN.sub(replacer, sql) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2ac8892cb3992de3a95f2c038f84f786bc926968 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/utils/utils.py @@ -0,0 +1,28 @@ +import numpy as np +import subprocess +import logging +from dataflow.logger import get_logger +from dataflow.core import get_operator + +def pipeline_step(yaml_path, step_name): + import yaml + logger = get_logger() + logger.info(f"Loading yaml {yaml_path} ......") + with open(yaml_path, "r") as f: + config = yaml.safe_load(f) + config = merge_yaml(config) + logger.info(f"Load yaml success, config: {config}") + algorithm = get_operator(step_name, config) + logger.info("Start running ...") + algorithm.run() + +def merge_yaml(config): + if not config.get("vllm_used"): + return config + else: + vllm_args_list = config.get("vllm_args", []) + if isinstance(vllm_args_list, list) and len(vllm_args_list) > 0 and isinstance(vllm_args_list[0], dict): + vllm_args = vllm_args_list[0] + config.update(vllm_args) # 合并进顶层 + return config + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..734037c981f9cfd99dfe96fb3e463f54c20f9740 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/__pycache__/kb_sglang_server.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/__pycache__/kb_sglang_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6f39c5d020b6950ed84abcdb75503eda36649a9 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/__pycache__/kb_sglang_server.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/__pycache__/kbclean_webui.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/__pycache__/kbclean_webui.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f2240679dd1e285405d4e77ef701d29db84294b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/__pycache__/kbclean_webui.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/__pycache__/kbcleaning_tools.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/__pycache__/kbcleaning_tools.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b489bd3745e15cba4e6031b9197cbb85a414a48 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/__pycache__/kbcleaning_tools.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/__pycache__/operator_pipeline.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/__pycache__/operator_pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8da58f853bf40dd2a1d7ad53a224be93677dcb96 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/__pycache__/operator_pipeline.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/kb_sglang_server.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/kb_sglang_server.py new file mode 100644 index 0000000000000000000000000000000000000000..021c6753dd76847d22e7a866b0c56d91e17c0b58 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/kb_sglang_server.py @@ -0,0 +1,152 @@ +import os +import socket +import subprocess +import time +import signal +import logging +import threading +from typing import List, Optional +from concurrent.futures import ThreadPoolExecutor, as_completed +from tqdm import tqdm +from transformers import AutoTokenizer + +import requests + + +logger = logging.getLogger(__name__) +logging.basicConfig( + format="[%(asctime)s] [%(levelname)s] %(message)s", + level=logging.INFO +) +from sglang.test.test_utils import is_in_ci +if is_in_ci(): + from patch import launch_server_cmd +else: + from sglang.utils import launch_server_cmd + +from sglang.utils import wait_for_server, print_highlight, terminate_process + +class SGLangServer: + """ + Robust manager for a local sglang_router server process, + with real-time log capture and health checks. + """ + + def __init__( + self, + model_path: str, + tp: int = 1, + max_total_tokens: int = 2048, + max_workers: int = 10, + temperature: float = 0.7, + ): + """ + Initialize the server manager. + + Args: + model_path: HuggingFace Hub path or local model directory. + dp: data parallel degree. + tp: tensor parallel degree. + max_total_tokens: maximum tokens to generate per request. + host: bind address for the server. + startup_timeout: seconds to wait for server to become healthy. + server_args: additional flags passed to the sglang_router server. + """ + self.model_path = model_path + self.tp = tp + self.max_total_tokens = max_total_tokens + self.max_workers = max_workers + self.temperature = temperature + self.url = None + self.tokenizer = AutoTokenizer.from_pretrained(self.model_path) + def find_free_port(self) -> int: + """自动查找系统空闲端口""" + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind(("", 0)) + return s.getsockname()[1] + + + def launch_server(self) -> str: + """ + Launch the sglang_router server process, and wait until it's healthy. + """ + server_process, port = launch_server_cmd( + f"python3 -m sglang.launch_server --model-path {self.model_path} --host 0.0.0.0 --tp {self.tp} --port {self.find_free_port()}" + ) + logging.info(f"Waiting for server to become healthy...") + wait_for_server(f"http://localhost:{port}") + self.url = f"http://localhost:{port}/generate" + logging.info(f"Server running at {self.url}") + return f"http://localhost:{port}/generate" + + + def generate_from_input( + self, + user_inputs: List[str], + system_prompt: str = "You are a helpful assistant", + ) -> List[str]: + """ + Generate responses for each user input via the local server. + + Args: + user_inputs: list of user query strings. + system_prompt: system message prefix for each conversation. + + Returns: + list of response strings. + """ + if not self.url: + self.launch_server() + + responses = [None] * len(user_inputs) + def get_response_with_id(text, id): + response = requests.post( + self.url, + json={ + "text": text, + "sampling_params": { + "temperature": self.temperature, + "max_new_tokens": self.max_total_tokens, + }, + }, + ) + # print(response.json()) + return response.json()["text"], id + fp = [] + for question in user_inputs: + messages = [ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": question} + ] + fp.append(messages) + ft = self.tokenizer.apply_chat_template( + fp, + tokenize=False, + add_generation_prompt=True, + enable_thinking=True, # Set to False to strictly disable thinking + ) + with ThreadPoolExecutor(max_workers=self.max_workers) as executor: + futures = [executor.submit(get_response_with_id, text, i) for i, text in enumerate(ft)] + for future in tqdm(as_completed(futures), total=len(futures), desc="Generating responses"): + response, id = future.result() + responses[id] = response + return responses + + + + +if __name__ == '__main__': + server = SGLangServer( + model_path="/data0/public_models/Qwen2.5-7B-Instruct", + tp=2, + max_total_tokens=2048, + max_workers=10, + temperature=0.7, + ) + server.launch_server() + print(f"Server running at {server.url}") + responses = server.generate_from_input( + ["介绍一下你自己","介绍一下Qwen"], + system_prompt="You are a helpful assistant", + ) + print(responses) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/kbclean_webui.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/kbclean_webui.py new file mode 100644 index 0000000000000000000000000000000000000000..19dcbf11190fd7613f7d132dc780100fb21a4892 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/kbclean_webui.py @@ -0,0 +1,178 @@ +import gradio as gr +import os +import shutil +import pandas as pd +from typing import List +from contextlib import redirect_stdout, redirect_stderr +import io +import threading +import time +from dataflow.webui.kbcleaning_tools import KBCleaning_Tools + +CACHE_DIR = "./.cache" +os.makedirs(CACHE_DIR, exist_ok=True) + +def upload_files(files: List[str], current_list: List[str]): + new_list = current_list.copy() + for fp in files: + if not fp.lower().endswith(".pdf"): + continue + dst = os.path.join(CACHE_DIR, os.path.basename(fp)) + shutil.copy(fp, dst) + if dst not in new_list: + new_list.append(dst) + return new_list, pd.DataFrame(new_list, columns=["PDF Files"]) + + +def add_pdf_path(path: str, current_list: List[str]): + new_list = current_list.copy() + if path and path.lower().endswith(".pdf") and os.path.exists(path): + if path not in new_list: + new_list.append(path) + return new_list, pd.DataFrame(new_list, columns=["PDF Files"]) + + +def add_url(url: str, current_list: List[str]): + new_list = current_list.copy() + if url and url not in new_list: + new_list.append(url) + return new_list, pd.DataFrame(new_list, columns=["URLs"]) + + +def run_pipeline_ui(pdf_list: List[str], url_list: List[str], + serving_type: str, + model_name: str, + vllm_max_tokens: int, vllm_tensor_parallel: int, + api_url: str, api_key: str, api_max_workers: int, + sglang_max_tokens: int, sglang_tensor_parallel: int, sglang_max_workers: int, sglang_temperature: float): + kb = KBCleaning_Tools() + inputs = pdf_list + url_list + out_buffer = io.StringIO() + + # Choose parameters based on serving type + if serving_type == "vllm": + max_tokens = vllm_max_tokens + tensor_parallel_size = vllm_tensor_parallel + max_workers = None + temperature = None + _api_url, _api_key = None, None + elif serving_type == "api": + # Save provided API key into environment variable + os.environ["DF_API_KEY"] = api_key + max_tokens = None + tensor_parallel_size = None + max_workers = api_max_workers + temperature = None + _api_url, _api_key = api_url, "DF_API_KEY" + else: # sglang + max_tokens = sglang_max_tokens + tensor_parallel_size = sglang_tensor_parallel + max_workers = sglang_max_workers + temperature = sglang_temperature + _api_url, _api_key = None, None + + def target(): + with redirect_stdout(out_buffer), redirect_stderr(out_buffer): + kb.run_pipeline( + pdf_or_url_list=inputs, + serving_type=serving_type, + model_name=model_name, + max_tokens=max_tokens, + tensor_parallel_size=tensor_parallel_size, + api_url=_api_url, + api_key=_api_key, + max_workers=max_workers, + temperature=temperature + ) + thread = threading.Thread(target=target) + thread.start() + + while thread.is_alive(): + time.sleep(0.2) + lines = out_buffer.getvalue().splitlines() + yield "\n".join(lines[-10:]) + lines = out_buffer.getvalue().splitlines() + yield "\n".join(lines[-10:]) + + +def update_param_visibility(selected): + return ( + gr.update(visible=(selected == "vllm")), + gr.update(visible=(selected == "api")), + gr.update(visible=(selected == "sglang")) + ) + + +def create_ui(): + with gr.Blocks() as demo: + gr.Markdown("## Knowledge Cleaning Pipeline") + + # File and URL inputs + file_input = gr.File(label="Drag & Drop PDF files", file_count="multiple", type="filepath") + pdf_path_input = gr.Textbox(label="Or input PDF path", placeholder="e.g. /path/to/doc.pdf") + add_pdf_btn = gr.Button("Add PDF Path") + url_input = gr.Textbox(label="Input URL", placeholder="e.g. https://example.com/doc") + add_url_btn = gr.Button("Add URL") + pdf_table = gr.DataFrame(headers=["PDF Files"]) + url_table = gr.DataFrame(headers=["URLs"]) + pdf_state = gr.State([]) + url_state = gr.State([]) + + # Serving type selector + serving_type = gr.Radio(choices=["vllm", "api", "sglang"], value="vllm", label="Serving Type") + + # Common parameter + model_name = gr.Textbox(value="Qwen/Qwen2.5-7B-Instruct", label="Model Name") + + # Parameter groups + vllm_params = gr.Column(visible=True) + with vllm_params: + vllm_max_tokens = gr.Number(value=2048, label="Max Tokens") + vllm_tensor_parallel = gr.Number(value=1, label="Tensor Parallel Size") + + api_params = gr.Column(visible=False) + with api_params: + api_url = gr.Textbox(label="API URL", placeholder="e.g. http://api.server") + api_key = gr.Textbox(label="API Key", type="password") + api_max_workers = gr.Number(value=1, label="Max Workers") + + sglang_params = gr.Column(visible=False) + with sglang_params: + sglang_max_tokens = gr.Number(value=2048, label="Max New Tokens (SGLang)") + sglang_tensor_parallel = gr.Number(value=1, label="Tensor Parallel Size") + sglang_max_workers = gr.Number(value=1, label="Max Workers") + sglang_temperature = gr.Number(value=0.7, label="Temperature") + + # Bind visibility update + serving_type.change(update_param_visibility, + inputs=[serving_type], + outputs=[vllm_params, api_params, sglang_params]) + + # Run button and output + run_btn = gr.Button("Run Pipeline") + output = gr.Textbox(label="Console Output", interactive=False, lines=10) + + # Event bindings + file_input.change(upload_files, + inputs=[file_input, pdf_state], + outputs=[pdf_state, pdf_table]) + add_pdf_btn.click(add_pdf_path, + inputs=[pdf_path_input, pdf_state], + outputs=[pdf_state, pdf_table]) + add_url_btn.click(add_url, + inputs=[url_input, url_state], + outputs=[url_state, url_table]) + run_btn.click(run_pipeline_ui, + inputs=[pdf_state, url_state, + serving_type, model_name, + vllm_max_tokens, vllm_tensor_parallel, + api_url, api_key, api_max_workers, + sglang_max_tokens, sglang_tensor_parallel, sglang_max_workers, sglang_temperature], + outputs=output, + queue=True) + demo.queue() + + return demo + +if __name__ == "__main__": + create_ui().launch() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/kbcleaning_tools.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/kbcleaning_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..e430bcf3ee0196c27c82923476d21bf7589d4417 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/kbcleaning_tools.py @@ -0,0 +1,133 @@ +from dataflow.operators.generate import ( + CorpusTextSplitterBatch, + FileOrURLToMarkdownConverterBatch, + KnowledgeCleanerBatch, + MultiHopQAGeneratorBatch, +) +from dataflow.utils.storage import FileStorage +from dataflow.serving import LocalModelLLMServing_vllm, APILLMServing_request +from dataflow.webui.kb_sglang_server import SGLangServer +import pandas as pd +import os +from typing import Literal +import logging + +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + + +class KBCleaning_Tools(): + def __init__(self): + pass + + def multi_pdf_or_url_to_json(self, pdf_or_url_list: list[str], cache_path: str = "./.cache", file_name: str = "pdf_or_urls.jsonl"): + output_list = [] + for pdf_or_url in pdf_or_url_list: + output_list.append({"raw_content": pdf_or_url}) + os.makedirs(cache_path, exist_ok=True) + pd.DataFrame(output_list).to_json(os.path.join(cache_path, file_name), orient="records", lines=True, force_ascii=False) + file_path = os.path.join(cache_path, file_name) + return file_path + + def _get_storage(self, file_name: str): + storage = FileStorage( + first_entry_file_name=file_name, + cache_path="./.cache/gpu", + file_name_prefix="batch_cleaning_step", + cache_type="json", + ) + return storage + + def _get_llm_serving(self, + serving_type: Literal["vllm", "sglang", "api"], + model_name_or_path: str, + max_tokens: int, + tensor_parallel_size: int, + api_url: str, + api_key: str, + max_workers: int, + temperature: float + ): + if serving_type == "vllm": + logger.info(f"Using VLLM to serve the model {model_name_or_path}, pipeline parallel is unavailable") + llm_serving = LocalModelLLMServing_vllm( + hf_model_name_or_path=model_name_or_path, + vllm_max_tokens=max_tokens, + vllm_tensor_parallel_size=tensor_parallel_size, + vllm_gpu_memory_utilization=0.6, + vllm_repetition_penalty=1.2 + ) + elif serving_type == "sglang": + logger.info(f"Using SGLang to serve the model {model_name_or_path}, max_tokens refer to sgl_max_new_tokens") + llm_serving = SGLangServer( + model_path=model_name_or_path, + tp=tensor_parallel_size, + max_total_tokens=max_tokens, + max_workers=max_workers, + temperature=temperature, + ) + elif serving_type == "api": + logger.info(f"Using API to serve the model {model_name_or_path}, max_tokens refer to max_new_tokens") + llm_serving = APILLMServing_request( + api_url=api_url, + key_name_of_api_key="DF_API_KEY", + model_name=model_name_or_path, + max_workers=max_workers + ) + return llm_serving + + def run_pipeline(self, + pdf_or_url_list: list[str], + serving_type: Literal["vllm", "sglang", "api"], + model_name: str, + max_tokens: int, + tensor_parallel_size: int, + api_url: str, + api_key: str, + max_workers: int, + temperature: float, + ): + file_path = self.multi_pdf_or_url_to_json(pdf_or_url_list) + storage = self._get_storage(file_path) + knowledge_cleaning_step1 = FileOrURLToMarkdownConverterBatch( + intermediate_dir="./.cache/raw", + lang="en", + mineru_backend="vlm-sglang-engine", + ) + if serving_type == "api": + tokenizer_name = "Qwen/Qwen2.5-7B-Instruct" + else: + tokenizer_name = model_name + knowledge_cleaning_step2 = CorpusTextSplitterBatch( + split_method="token", + chunk_size=512, + tokenizer_name=tokenizer_name, + ) + knowledge_cleaning_step1.run(storage=storage.step()) + knowledge_cleaning_step2.run(storage=storage.step()) + llm_serving = self._get_llm_serving( + serving_type=serving_type, + model_name_or_path=model_name, + max_tokens=max_tokens, + tensor_parallel_size=tensor_parallel_size, + api_url=api_url, + api_key=api_key, + max_workers=max_workers, + temperature=temperature, + ) + knowledge_cleaning_step3 = KnowledgeCleanerBatch( + llm_serving=llm_serving, + lang="en", + ) + knowledge_cleaning_step3.run(storage=storage.step()) + knowledge_cleaning_step4 = MultiHopQAGeneratorBatch( + llm_serving=llm_serving, + lang="en", + ) + knowledge_cleaning_step4.run(storage=storage.step()) + + return + + + + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/operator_pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/operator_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..37055a944e90036cde93d5583979b96a1f5d5703 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/webui/operator_pipeline.py @@ -0,0 +1,678 @@ +import os +import inspect +import json +import pandas as pd +import gradio as gr +import importlib.util +from typing import Dict, List, Any, Optional +from dataclasses import dataclass +from dataflow.logger import get_logger +from dataflow.utils.registry import OPERATOR_REGISTRY +from dataflow.core import LLMServingABC +from dataflow.utils.storage import FileStorage +import logging +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') + +# ========================= +# 1. 强制初始化注册表 +# ========================= +try: + OPERATOR_REGISTRY._get_all() +except Exception as e: + print(f"[Warning] Failed to initialize operator registry: {e}") + +@dataclass +class ParameterInfo: + name: str + type_annotation: str + default_value: Any + has_default: bool + description: str = "" + +@dataclass +class OperatorInfo: + name: str + class_obj: type + init_params: List[ParameterInfo] + run_params: List[ParameterInfo] + description: str = "" + +@dataclass +class PipelineInfo: + name: str + category: str # 'api' + class_obj: type + file_path: str + description: str = "" + +class DynamicOperatorSystem: + def __init__(self): + self.logger = get_logger() + self.operators: Dict[str, OperatorInfo] = {} + self.pipelines: Dict[str, PipelineInfo] = {} + self._discover_operators() + self._discover_pipelines() + + def _discover_operators(self): + try: + for name, obj in OPERATOR_REGISTRY.get_obj_map().items(): + try: + info = self._analyze_operator(name, obj) + self.operators[name] = info + except Exception as e: + print(f"[Warning] analyze operator `{name}` failed: {e}") + except Exception as e: + print(f"[Warning] Failed to discover operators: {e}") + + def _discover_pipelines(self): + """只发现 API Pipelines""" + try: + pipeline_base = os.path.join(os.path.dirname(__file__), "..", "statics", "pipelines") + for category in ["api_pipelines"]: + path = os.path.join(pipeline_base, category) + if not os.path.exists(path): + continue + for fn in os.listdir(path): + if fn.endswith(".py") and not fn.startswith("__"): + try: + info = self._analyze_pipeline(category, fn, path) + if info: + self.pipelines[info.name] = info + except Exception as e: + print(f"[Warning] analyze pipeline `{fn}` failed: {e}") + except Exception as e: + print(f"[Warning] Failed to discover pipelines: {e}") + + def _extract_class_names(self, file_path): + import ast + with open(file_path, "r", encoding="utf-8") as f: + tree = ast.parse(f.read()) + classes = [n.name for n in ast.walk(tree) if isinstance(n, ast.ClassDef)] + if len(classes) != 1: + self.logger.error(f"Expected exactly 1 class in {file_path}, found {classes}") + raise ImportError(f"Multiple or no classes in {file_path}: {classes}") + return classes[0] + + def _analyze_pipeline(self, category: str, file_name: str, dir_path: str) -> Optional[PipelineInfo]: + file_path = os.path.join(dir_path, file_name) + module_name = self._extract_class_names(file_path) + try: + spec = importlib.util.spec_from_file_location(module_name, file_path) + if not spec or not spec.loader: + return None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + cls = None + for attr in dir(module): + obj = getattr(module, attr) + if inspect.isclass(obj) and attr.endswith("Pipeline"): + cls = obj + break + if not cls: + return None + desc = cls.__doc__ or f"{module_name} pipeline" + return PipelineInfo(name=module_name, category="api", class_obj=cls, file_path=file_path, description=desc) + except Exception as e: + print(f"[Warning] Failed to analyze pipeline {file_name}: {e}") + return None + + def _analyze_operator(self, name: str, obj: type) -> OperatorInfo: + def extract(sig: inspect.Signature, exclude: List[str]) -> List[ParameterInfo]: + out = [] + for pname, p in sig.parameters.items(): + if pname in exclude: + continue + has_def = (p.default is not inspect._empty) + anno = p.annotation if p.annotation is not inspect._empty else Any + anno_str = getattr(anno, "__name__", str(anno)) + default = p.default if has_def else None + out.append(ParameterInfo(pname, anno_str, default, has_def)) + return out + + init_sig = inspect.signature(obj.__init__) + init_params = extract(init_sig, exclude=["self"]) + run_params = [] + if hasattr(obj, "run"): + run_sig = inspect.signature(obj.run) + run_params = extract(run_sig, exclude=["self", "storage"]) + desc = obj.__doc__ or "" + return OperatorInfo(name, obj, init_params, run_params, desc) + + def get_operator_names(self) -> List[str]: + return sorted(self.operators.keys()) + + def get_pipeline_names_by_category(self, category: str) -> List[str]: + return sorted([n for n, info in self.pipelines.items() if info.category == category]) + + def get_operator_info(self, name: str) -> Optional[OperatorInfo]: + return self.operators.get(name) + + def get_pipeline_info(self, name: str) -> Optional[PipelineInfo]: + return self.pipelines.get(name) + + def create_serving_instance(self, serving_type: str, **kwargs) -> LLMServingABC: + if serving_type == "API": + api_key = kwargs.pop("api_key", None) + api_url = kwargs.get("api_url", "https://api.openai.com/v1/chat/completions") + if api_key: + os.environ["DF_API_KEY"] = api_key + from dataflow.serving import APILLMServing_request + return APILLMServing_request( + api_url=api_url, + model_name=kwargs.get("model_name"), + max_workers=int(kwargs.get("max_workers", 2)), + ) + from dataflow.serving import LocalModelLLMServing_vllm + return LocalModelLLMServing_vllm( + hf_model_name_or_path=kwargs.get("model_path"), + vllm_tensor_parallel_size=int(kwargs.get("tensor_parallel_size", 1)), + vllm_temperature=float(kwargs.get("temperature", 0.7)), + vllm_top_p=float(kwargs.get("top_p", 0.9)), + vllm_max_tokens=int(kwargs.get("max_tokens", 1024)), + ) + + def create_storage_instance(self, **kwargs) -> FileStorage: + return FileStorage( + first_entry_file_name=kwargs.get("input_file_path"), + cache_path=kwargs.get("cache_path", "./cache"), + file_name_prefix=kwargs.get("file_name_prefix", "result"), + cache_type=kwargs.get("cache_type", "jsonl"), + ) + +dynamic_system = DynamicOperatorSystem() + +# ========================= +# 中英文文案字典 +# ========================= +zh_t = { + "header": "# DataFlow 动态算子和Pipeline可视化", + "operators_mode": "算子模式", + "pipelines_mode": "Pipeline模式", + "mode_switch": "模式切换", + "select_operator": "选择算子", + "select_pipeline": "选择Pipeline", + "desc_placeholder": "描述在这里显示", + "init_section": "## 初始化参数(除 llm_serving)", + "other_init": "其他初始化参数 (JSON)", + "call_method": "调用方式", + "api_section": "### API 参数", + "api_url": "API URL", + "model_name": "模型名称", + "api_key": "API Key", + "max_workers": "最大并发数", + "local_section": "### 本地模型参数", + "local_model_path": "本地模型路径", + "tensor_parallel_size": "张量并行大小", + "temperature": "Temperature", + "top_p": "Top P", + "max_tokens": "最大Token数", + "storage_section": "## 存储参数", + "input_file_path": "输入文件路径", + "cache_path": "缓存路径", + "file_name_prefix": "文件名前缀", + "run_section": "## 运行参数", + "run_params": "运行参数 (JSON)", + "run_button": "执行算子", + "run_pipeline_button": "运行Pipeline", + "summary": "执行汇总", + "preview": "前 5 条预览(自动换行)", + "api_pipeline_section": "### API Pipeline 配置", + "pipeline_input_file": "Pipeline 输入文件路径", +} + +en_t = { + "header": "# DataFlow Dynamic Operators and Pipeline Visualization", + "operators_mode": "Operators Mode", + "pipelines_mode": "Pipeline Mode", + "mode_switch": "Switch Mode", + "select_operator": "Select Operator", + "select_pipeline": "Select Pipeline", + "desc_placeholder": "Description appears here", + "init_section": "## Initialization Parameters (except llm_serving)", + "other_init": "Other init params (JSON)", + "call_method": "Call Method", + "api_section": "### API Parameters", + "api_url": "API URL", + "model_name": "Model Name", + "api_key": "API Key", + "max_workers": "Max Workers", + "local_section": "### Local Model Parameters", + "local_model_path": "Local Model Path", + "tensor_parallel_size": "Tensor Parallel Size", + "temperature": "Temperature", + "top_p": "Top P", + "max_tokens": "Max Tokens", + "storage_section": "## Storage Parameters", + "input_file_path": "Input File Path", + "cache_path": "Cache Path", + "file_name_prefix": "File Name Prefix", + "run_section": "## Run Parameters", + "run_params": "Run Params (JSON)", + "run_button": "Run Operator", + "run_pipeline_button": "Run Pipeline", + "summary": "Execution Summary", + "preview": "Top 5 Preview (wrapped)", + "api_pipeline_section": "### API Pipeline Config", + "pipeline_input_file": "Pipeline Input File", +} + +# 默认中文 +current_t = zh_t + +# ========================= +# 回调:切换语言 +# ========================= +def switch_language(lang): + global current_t + current_t = zh_t if lang == "中文" else en_t + return ( + # 1. 顶部标题 + gr.update(value=current_t["header"]), + # 2. 模式切换控件 + gr.update(choices=[current_t["operators_mode"], current_t["pipelines_mode"]], + label=current_t["mode_switch"], + value=current_t["operators_mode"]), + # 3. 算子选择下拉 + gr.update(label=current_t["select_operator"]), + # 4. Pipeline 选择下拉 + gr.update(label=current_t["select_pipeline"]), + # 5. 算子描述 Markdown + gr.update(value=current_t["desc_placeholder"]), + # 6. Pipeline 描述 Markdown + gr.update(value=current_t["desc_placeholder"]), + # 7. 初始化参数区域标题 + gr.update(value=current_t["init_section"]), + # 8. init_editor 标签 + gr.update(label=current_t["other_init"]), + # 9. 调用方式单选 + gr.update(label=current_t["call_method"], + choices=[current_t["api_section"], current_t["local_section"]], + value=current_t["api_section"]), + # 10. API 参数区域标题 + gr.update(value=current_t["api_section"]), + # 11–14. API 参数输入框 + gr.update(label=current_t["api_url"]), + gr.update(label=current_t["model_name"]), + gr.update(label=current_t["api_key"]), + gr.update(label=current_t["max_workers"]), + # 15. 本地模型参数区域标题 + gr.update(value=current_t["local_section"]), + # 16–20. 本地模型参数输入框 + gr.update(label=current_t["local_model_path"]), + gr.update(label=current_t["tensor_parallel_size"]), + gr.update(label=current_t["temperature"]), + gr.update(label=current_t["top_p"]), + gr.update(label=current_t["max_tokens"]), + # 21. 算子存储区域标题 + gr.update(value=current_t["storage_section"]), + # 22–24. 算子存储输入框 + gr.update(label=current_t["input_file_path"]), + gr.update(label=current_t["cache_path"]), + gr.update(label=current_t["file_name_prefix"]), + # 25. 运行参数区域标题 + gr.update(value=current_t["run_section"]), + # 26. run_editor 标签 + gr.update(label=current_t["run_params"]), + # 27. API Pipeline 区域标题 + gr.update(value=current_t["api_pipeline_section"]), + # 28. pipeline_input_file 标签 + gr.update(label=current_t["pipeline_input_file"]), + # 29. Pipeline 存储区域标题 + gr.update(value=current_t["storage_section"]), + # 30–31. Pipeline 存储输入框 + gr.update(label=current_t["cache_path"]), + gr.update(label=current_t["file_name_prefix"]), + # 32–35. Pipeline API 输入框 + gr.update(label=current_t["api_url"]), + gr.update(label=current_t["model_name"]), + gr.update(label=current_t["api_key"]), + gr.update(label=current_t["max_workers"]), + # 36–37. 按钮文字 + gr.update(value=current_t["run_button"]), + gr.update(value=current_t["run_pipeline_button"]), + ) + +# ========================= +# 其他已有回调与函数(保持不变) +# ========================= +def switch_mode(m): + if m == current_t["operators_mode"]: + return ( + gr.update(visible=True), + gr.update(visible=False), + gr.update(visible=True), + gr.update(visible=False), + ) + return ( + gr.update(visible=False), + gr.update(visible=True), + gr.update(visible=False), + gr.update(visible=True), + ) + +def build_param_templates(op_name): + blank = "{}" + if not op_name: + return ( + gr.update(value=current_t["desc_placeholder"]), + gr.update(value=blank), + gr.update(value=blank), + gr.update(visible=False), + gr.update(visible=False), + ) + info = dynamic_system.get_operator_info(op_name) + if not info: + return ( + gr.update(value="未找到算子信息" if current_t is zh_t else "Operator info not found"), + gr.update(value=blank), + gr.update(value=blank), + gr.update(visible=False), + gr.update(visible=False), + ) + desc = info.description or "" + init_dict = {p.name: (p.default_value if p.has_default else "") + for p in info.init_params if p.name != "llm_serving"} + run_dict = {p.name: (p.default_value if p.has_default else "") + for p in info.run_params} + init_str = json.dumps(init_dict, ensure_ascii=False, indent=2) + run_str = json.dumps(run_dict, ensure_ascii=False, indent=2) + has_llm = any(p.name == "llm_serving" for p in info.init_params) + return ( + gr.update(value=desc), + gr.update(value=init_str), + gr.update(value=run_str), + gr.update(visible=has_llm), + gr.update(visible=has_llm), + ) + +def build_pipeline_info(name): + if not name: + return gr.update(value=current_t["desc_placeholder"]) + info = dynamic_system.get_pipeline_info(name) + if not info: + msg = "Pipeline 未找到" if current_t is zh_t else "Pipeline not found" + return gr.update(value=msg) + return gr.update(value=info.description or name) + +def gradio_run( + op_name, init_str, run_str, + api_url, model_name, api_key, max_workers, + local_model_path, tensor_parallel_size, temperature, top_p, max_tokens, + input_file_path, cache_path, file_name_prefix +): + try: + if api_key: + os.environ["DF_API_KEY"] = api_key + other_init = json.loads(init_str) + run_params = json.loads(run_str) + info = dynamic_system.get_operator_info(op_name) + if any(p.name == "llm_serving" for p in info.init_params): + cfg = {"serving_type": "API", "api_url": api_url, "model_name": model_name, + "api_key": api_key, "max_workers": max_workers} + other_init["llm_serving"] = dynamic_system.create_serving_instance(**cfg) + op_inst = info.class_obj(**other_init) + storage = dynamic_system.create_storage_instance( + input_file_path=input_file_path, + cache_path=cache_path, + file_name_prefix=file_name_prefix + ) + op_inst.run(storage=storage.step(), **run_params) + out_fn = storage._get_cache_file_path(storage.operator_step + 1) + df = pd.read_json(out_fn, lines=True) + summary = f"**{current_t['summary']}** {len(df)} ; `{out_fn}`" + preview = df.head(5).to_html(index=False, escape=True) + wrapped = "" + preview + return summary, wrapped + except Exception as e: + return f"[Error] {e}", "
"
+
+def gradio_run_pipeline(
+    pipeline_name,
+    pipeline_input_file,
+    cache_path, file_name_prefix,
+    api_url, api_model_name, api_key, api_max_workers
+):
+    try:
+        info = dynamic_system.get_pipeline_info(pipeline_name)
+        if not info:
+            return f"[Error] Pipeline '{pipeline_name}' not found", "
"
+        pipeline_inst = info.class_obj()
+
+        pipeline_inst.storage = FileStorage(
+            first_entry_file_name=pipeline_input_file or pipeline_inst.storage.first_entry_file_name,
+            cache_path=cache_path,
+            file_name_prefix=file_name_prefix,
+            cache_type="jsonl"
+        )
+
+        if api_key:
+            os.environ["DF_API_KEY"] = api_key
+
+        new_serving = dynamic_system.create_serving_instance(
+            "API",
+            api_url=api_url,
+            model_name=api_model_name,
+            api_key=api_key,
+            max_workers=api_max_workers
+        )
+        for comp in vars(pipeline_inst).values():
+            if hasattr(comp, "llm_serving"):
+                comp.llm_serving = new_serving
+
+        pipeline_inst.forward()
+
+        out_fn = pipeline_inst.storage._get_cache_file_path(pipeline_inst.storage.operator_step)
+        if os.path.exists(out_fn):
+            try:
+                df = pd.read_json(out_fn, lines=True)
+                summary = f"**Pipeline执行完成**  {len(df)} 条记录; {out_fn}"
+                preview = df.head(5).to_html(index=False, escape=True)
+                wrapped = "" + preview
+                return summary, wrapped
+            except Exception:
+                return f"**Pipeline执行完成** 输出文件: {out_fn}", "
无法预览结果
" + else: + return "**Pipeline执行完成** 但未找到输出文件", "
"
+    except Exception as e:
+        return f"[Error] {e}", "
"
+
+# =========================
+# 新增:保存 Pipeline API Key 到环境变量
+# =========================
+def save_pipeline_api_key(key):
+    import os, logging
+    os.environ["DF_API_KEY"] = key
+    logging.info("DF_API_KEY 已保存到环境变量")  # 终端会看到 INFO 提示
+
+
+# =========================
+# Gradio 界面
+# =========================
+with gr.Blocks(title="DataFlow 动态算子和Pipeline可视化") as demo:
+    # 0. 语言切换
+    lang_switch = gr.Radio(
+        choices=["中文", "English"],
+        value="中文",
+        label="Language / 语言"
+    )
+
+    # 1. 顶部标题
+    header_md = gr.Markdown(current_t["header"])
+
+    # 2. 模式切换
+    mode_switch = gr.Radio(
+        choices=[current_t["operators_mode"], current_t["pipelines_mode"]],
+        value=current_t["operators_mode"],
+        label=current_t["mode_switch"]
+    )
+
+    # 算子模式区
+    with gr.Column(visible=True) as operator_section:
+        operator_dropdown = gr.Dropdown(
+            choices=dynamic_system.get_operator_names(),
+            label=current_t["select_operator"]
+        )
+        operator_desc_md = gr.Markdown(current_t["desc_placeholder"])
+
+    # Pipeline 模式区
+    with gr.Column(visible=False) as pipeline_section:
+        pipeline_dropdown = gr.Dropdown(
+            choices=dynamic_system.get_pipeline_names_by_category("api"),
+            label=current_t["select_pipeline"]
+        )
+        pipeline_desc_md = gr.Markdown(current_t["desc_placeholder"])
+
+    # 参数与存储区
+    with gr.Row():
+        # 算子运行区
+        with gr.Column(scale=1):
+            with gr.Column(visible=True) as operator_run_section:
+                init_section_md = gr.Markdown(current_t["init_section"])
+                init_editor = gr.Code(
+                    label=current_t["other_init"],
+                    language="json",
+                    interactive=True,
+                    lines=6,
+                    value="{}"
+                )
+                call_method = gr.Radio(
+                    choices=[current_t["api_section"], current_t["local_section"]],
+                    value=current_t["api_section"],
+                    label=current_t["call_method"]
+                )
+                with gr.Column(visible=True) as api_group:
+                    api_section_md = gr.Markdown(current_t["api_section"])
+                    api_url = gr.Textbox(label=current_t["api_url"])
+                    model_name = gr.Textbox(label=current_t["model_name"])
+                    api_key = gr.Textbox(label=current_t["api_key"], type="password")
+                    max_workers = gr.Number(label=current_t["max_workers"], value=2)
+                with gr.Column(visible=False) as local_group:
+                    local_section_md = gr.Markdown(current_t["local_section"])
+                    local_model_path = gr.Textbox(label=current_t["local_model_path"])
+                    tensor_parallel_size = gr.Number(label=current_t["tensor_parallel_size"], value=1)
+                    temperature = gr.Number(label=current_t["temperature"], value=0.7)
+                    top_p = gr.Number(label=current_t["top_p"], value=0.9)
+                    max_tokens = gr.Number(label=current_t["max_tokens"], value=1024)
+
+        # Pipeline 运行区
+        with gr.Column(visible=False) as pipeline_run_section:
+            api_pipeline_section_md = gr.Markdown(current_t["api_pipeline_section"])
+            pipeline_input_file = gr.Textbox(label=current_t["pipeline_input_file"], value="")
+            storage_section_md2 = gr.Markdown(current_t["storage_section"])
+            pipeline_cache_path = gr.Textbox(label=current_t["cache_path"], value="./cache")
+            pipeline_file_name_prefix = gr.Textbox(label=current_t["file_name_prefix"], value="result")
+            pipeline_api_url = gr.Textbox(label=current_t["api_url"], value="https://api.openai.com/v1/chat/completions")
+            pipeline_api_model_name = gr.Textbox(label=current_t["model_name"], value="gpt-4o-mini")
+            pipeline_api_key = gr.Textbox(label=current_t["api_key"], type="password")
+            # 新增保存 API Key 按钮
+            save_api_key_btn = gr.Button(value="保存 API Key", variant="secondary")
+            # 绑定:点击按钮时执行保存环境变量的操作
+            save_api_key_btn.click(
+                fn=save_pipeline_api_key,
+                inputs=[pipeline_api_key],
+                outputs=[]
+            )
+            pipeline_api_max_workers = gr.Number(label=current_t["max_workers"], value=2)
+
+        # 算子存储区
+        with gr.Column(scale=1) as operator_storage_section:
+            storage_section_md1 = gr.Markdown(current_t["storage_section"])
+            input_file_path = gr.Textbox(label=current_t["input_file_path"], value="")
+            cache_path = gr.Textbox(label=current_t["cache_path"], value="./cache")
+            file_name_prefix = gr.Textbox(label=current_t["file_name_prefix"], value="result")
+            run_section_md = gr.Markdown(current_t["run_section"])
+            run_editor = gr.Code(
+                label=current_t["run_params"],
+                language="json",
+                interactive=True,
+                lines=4,
+                value="{}"
+            )
+
+    # 按钮
+    with gr.Row():
+        run_btn = gr.Button(value=current_t["run_button"], variant="primary", visible=True)
+        run_pipeline_btn = gr.Button(value=current_t["run_pipeline_button"], variant="primary", visible=False)
+
+    # 输出区
+    summary_md   = gr.Markdown()
+    preview_html = gr.HTML()
+
+    # 事件绑定
+    lang_switch.change(
+        fn=switch_language,
+        inputs=[lang_switch],
+        outputs=[
+            header_md, mode_switch,
+            operator_dropdown, pipeline_dropdown,
+            operator_desc_md, pipeline_desc_md,
+            init_section_md, init_editor, call_method,
+            api_section_md, api_url, model_name, api_key, max_workers,
+            local_section_md, local_model_path, tensor_parallel_size, temperature, top_p, max_tokens,
+            storage_section_md1, input_file_path, cache_path, file_name_prefix,
+            run_section_md, run_editor,
+            api_pipeline_section_md, pipeline_input_file,
+            storage_section_md2, pipeline_cache_path, pipeline_file_name_prefix,
+            pipeline_api_url, pipeline_api_model_name, pipeline_api_key, pipeline_api_max_workers,
+            run_btn, run_pipeline_btn
+        ]
+    )
+
+    mode_switch.change(
+        fn=switch_mode,
+        inputs=[mode_switch],
+        outputs=[operator_section, pipeline_section, operator_run_section, pipeline_run_section]
+    ).then(
+        fn=lambda m: (
+            gr.update(visible=(m == current_t["operators_mode"])),
+            gr.update(visible=(m != current_t["operators_mode"])),
+            gr.update(visible=(m == current_t["operators_mode"]))
+        ),
+        inputs=[mode_switch],
+        outputs=[run_btn, run_pipeline_btn, operator_storage_section]
+    )
+
+    operator_dropdown.change(
+        fn=build_param_templates,
+        inputs=[operator_dropdown],
+        outputs=[operator_desc_md, init_editor, run_editor, api_group, local_group]
+    )
+
+    pipeline_dropdown.change(
+        fn=build_pipeline_info,
+        inputs=[pipeline_dropdown],
+        outputs=[pipeline_desc_md]
+    )
+
+    call_method.change(
+        fn=lambda m: (
+            gr.update(visible=(m==current_t["api_section"])),
+            gr.update(visible=(m!=current_t["api_section"]))
+        ),
+        inputs=[call_method],
+        outputs=[api_group, local_group]
+    )
+
+    run_btn.click(
+        fn=gradio_run,
+        inputs=[
+            operator_dropdown, init_editor, run_editor,
+            api_url, model_name, api_key, max_workers,
+            local_model_path, tensor_parallel_size, temperature, top_p, max_tokens,
+            input_file_path, cache_path, file_name_prefix
+        ],
+        outputs=[summary_md, preview_html]
+    )
+
+    run_pipeline_btn.click(
+        fn=gradio_run_pipeline,
+        inputs=[
+            pipeline_dropdown, pipeline_input_file,
+            pipeline_cache_path, pipeline_file_name_prefix,
+            pipeline_api_url, pipeline_api_model_name, pipeline_api_key, pipeline_api_max_workers
+        ],
+        outputs=[summary_md, preview_html]
+    )
+
+if __name__ == "__main__":
+    demo.launch(server_name="0.0.0.0", server_port=7862, show_error=True)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/wrapper/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/wrapper/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a849477ca1494ffcc6eb91439162073a389ebe04
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/wrapper/__init__.py
@@ -0,0 +1,6 @@
+from .batch_wrapper import BatchWrapper
+
+
+__all__ = [
+    "BatchWrapper"
+]
\ No newline at end of file
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/wrapper/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/wrapper/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..11a551764e47050ef587a122272e107cb6569619
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/wrapper/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/wrapper/__pycache__/auto_op.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/wrapper/__pycache__/auto_op.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e20ebf29be19d8c7d41feaa04622a13c22361343
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/wrapper/__pycache__/auto_op.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/wrapper/__pycache__/batch_wrapper.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/wrapper/__pycache__/batch_wrapper.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..19065bba89a827196c22722b841ae6716d54127d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/wrapper/__pycache__/batch_wrapper.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/wrapper/auto_op.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/wrapper/auto_op.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c988fa1c6821fcafafc1a8f8913362e90df34fa
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/wrapper/auto_op.py
@@ -0,0 +1,105 @@
+from typing import OrderedDict, ParamSpec, TypeVar, Generic, Protocol, Any, Dict
+from functools import wraps
+import inspect
+from dataflow.logger import get_logger
+from dataflow.core import OperatorABC
+# from dataflow.core.graph import nodes
+from tqdm import tqdm
+import pandas as pd
+P = ParamSpec("P")
+R = TypeVar("R")
+
+class HasRun(Protocol[P, R]):
+    def run(self, *args: P.args, **kwargs: P.kwargs) -> R:
+        """
+        这里写一份通用的 run 文档也可以,
+        不写的话会被下面动态拷贝原 operator.run 的 __doc__。
+        """
+        ...
+        
+class OPRuntime:
+    def __init__(
+        self, 
+        operator: OperatorABC, 
+        operator_name: str,
+        # func: callable, 
+        args: Dict[str, Any]
+        ):
+        self.op = operator
+        self.op_name = operator_name
+        # self.func = func
+        self.kwargs = args
+        self.logger = get_logger()
+
+    def __repr__(self):
+        # return f"OPRuntime(operator={repr(self.op)}, func={self.func.__qualname__}, args={self.kwargs})"        
+        return f"OPRuntime(operator={repr(self.op)}, args={self.kwargs})"
+
+class AutoOP(Generic[P, R]):
+    """
+    自动化运行 Operator 的 Wrapper。
+
+    在静态检查/IDE 里,AutoOp.run 的签名和 operator.run 完全一致。
+    运行时,会把 operator.run 的 __doc__ 和 __signature__ 也拷过来,
+    这样 help(bw.run) 时能看到原 operator 的文档。
+    """
+    
+    def __init__(self, operator: HasRun[P, R], operator_name, pipeline):
+        self._operator = operator
+        self._operator_name = operator_name
+        self._pipeline = pipeline # 
+        self._logger = get_logger()
+        
+        # 动态拷贝 operator.run 的 __doc__ 和 inspect.signature
+        self._orig_run = operator.run
+        self._signature = inspect.signature(operator.run)
+        self.__doc__ = self._orig_run.__doc__
+
+    def _flatten_bound_arguments(self, bound: inspect.BoundArguments, sig: inspect.Signature) -> "OrderedDict[str, object]":
+        """
+        将 bound.arguments(OrderedDict)中的 **kwargs 展平到顶层,
+        保留调用顺序;其余参数(含 *args)原样保留。
+        """
+        # 找出签名中 **kwargs 的参数名(若存在)
+        var_kw_name = None
+        for name, p in sig.parameters.items():
+            # print(name, p.kind)
+            if p.kind == inspect.Parameter.VAR_KEYWORD:
+                var_kw_name = name
+                break
+
+        out = OrderedDict()
+        for name, value in bound.arguments.items():
+            if name == var_kw_name and isinstance(value, dict):
+                # 展平 **kwargs:按调用顺序插入
+                for k, v in value.items():
+                    if k in out:                   # 理论上不该冲突;保险起见
+                        out[f"__kw__{k}"] = v
+                    else:
+                        out[k] = v
+            else:
+                out[name] = value
+        return out
+
+    def run(self, *args: P.args, **kwargs: P.kwargs) -> R:
+        """
+        这里写一份通用的 run 文档也可以,
+        不写的话会被上面动态拷贝原 operator.run 的 __doc__。
+        """
+        self._signature = inspect.signature(self._orig_run)
+        bound_args = self._signature.bind(*args, **kwargs)
+        bound_args.apply_defaults()
+
+        final_kwargs = self._flatten_bound_arguments(bound_args, self._signature)  # OrderedDict
+        (final_kwargs)
+        self._logger.debug(final_kwargs)
+        # final_kwargs = bound_args.arguments  # OrderedDict
+        # 添加一条运行记录
+        # self._pipeline.op_runtimes.append(OPRuntime(self._operator, self._orig_run, dict(final_kwargs)))
+        self._pipeline.op_runtimes.append(
+            OPRuntime(
+                operator=self._operator, 
+                operator_name=self._operator_name,
+                args=dict(final_kwargs)
+            )
+        )
\ No newline at end of file
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/wrapper/batch_wrapper.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/wrapper/batch_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f30c8ff97588f6e400fd0947685c6e72a3baa8b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/wrapper/batch_wrapper.py
@@ -0,0 +1,98 @@
+from typing import ParamSpec, TypeVar, Generic, Protocol, List
+from functools import wraps
+import inspect
+from dataflow.logger import get_logger
+from dataflow.core import OperatorABC
+from dataflow.utils.storage import DataFlowStorage, DummyStorage, FileStorage
+from tqdm import tqdm
+import pandas as pd
+P = ParamSpec("P")
+R = TypeVar("R")
+
+class HasRun(Protocol[P, R]):
+    def run(self, *args: P.args, **kwargs: P.kwargs) -> R:
+        """
+        这里写一份通用的 run 文档也可以,
+        不写的话会被下面动态拷贝原 operator.run 的 __doc__。
+        """
+        ...
+
+class BatchWrapper(Generic[P, R]):
+    """
+    通用的批处理 Wrapper。
+
+    在静态检查/IDE 里,BatchWrapper.run 的签名和 operator.run 完全一致。
+    运行时,会把 operator.run 的 __doc__ 和 __signature__ 也拷过来,
+    这样 help(bw.run) 时能看到原 operator 的文档。
+    """
+    def __init__(self, operator: HasRun[P, R], batch_size: int = 32, batch_cache: bool = False) -> None:
+        self._operator = operator
+        self._logger = get_logger()
+        self._batch_size = batch_size
+        self._batch_cache = batch_cache
+
+        # 动态拷贝 operator.run 的 __doc__ 和 inspect.signature
+        orig = operator.run
+        sig = inspect.signature(orig)
+        # wrapped = wraps(orig)(self.run)        # 先 wrap docstring, __name__…
+        # wrapped.__signature__ = sig            # 再贴上准确的 signature
+        # 把它绑到实例上覆盖掉 class method,这样 help(instance.run) 能看到原文档
+        # object.__setattr__(self, "run", wrapped)
+
+    def run(self, *args: P.args, **kwargs: P.kwargs) -> List[R]:
+        # —— 1. 提取 storage —— 
+        # only support FileStorage for now
+        if args:
+            storage: FileStorage = args[0]    # type: ignore[assignment]
+            rest_args = args[1:]
+            rest_kwargs = kwargs
+        else:
+            storage: FileStorage = kwargs.get("storage")      # type: ignore[assignment]
+            if storage is None:
+                raise ValueError(
+                    f"A DataFlowStorage is required for {self._operator!r}.run()"
+                )
+            rest_kwargs = {k: v for k, v in kwargs.items() if k != "storage"}
+            rest_args = ()
+            
+        # prepare a dummy storage,for batch processing
+        if self._batch_cache: # if we need to cache each batch result
+            self._dummy_storage = DummyStorage(
+                cache_path=storage.cache_path,
+                file_name_prefix=storage.file_name_prefix,
+                cache_type=storage.cache_type
+            )
+        else:  # if we don't need to cache each batch result
+            self._dummy_storage = DummyStorage()
+
+        # —— 2. 读出全量数据并按 batch_size 切分 —— 
+        whole_dataframe = storage.read()
+        num_batches = (len(whole_dataframe) + self._batch_size - 1) // self._batch_size  # Calculate number of batches
+
+        self._logger.info(f"Total {len(whole_dataframe)} items, will process in {num_batches} batches of size {self._batch_size}.")
+        for batch_num in tqdm(range(num_batches)):
+            start_index = batch_num * self._batch_size
+            end_index = min((batch_num + 1) * self._batch_size, len(whole_dataframe))
+            batch_df = whole_dataframe.iloc[start_index:end_index]
+            # Clear and write the current batch
+            self._dummy_storage.set_data(batch_df)
+            self._dummy_storage.set_file_name_prefix(
+                f"{storage.file_name_prefix}_step{storage.operator_step}_batch{batch_num}"
+            )
+            # Run the operator with the dummy storage
+            self._logger.info(f"Running batch with {len(batch_df)} items...")
+            self._operator.run(self._dummy_storage, *rest_args, **rest_kwargs)
+
+            res: pd.DataFrame = self._dummy_storage.read()
+
+            # Find columns in res that are not in whole_dataframe
+            new_cols = [c for c in res.columns if c not in whole_dataframe.columns]
+
+            # Create new columns in whole_dataframe with NaN values
+            for c in new_cols:
+                whole_dataframe[c] = pd.NA
+
+            # Write the values from res back to whole_dataframe
+            whole_dataframe.loc[res.index, res.columns] = res
+
+        storage.write(whole_dataframe)
\ No newline at end of file
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google_api_core-2.30.3.dist-info/licenses/LICENSE b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google_api_core-2.30.3.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google_api_core-2.30.3.dist-info/licenses/LICENSE
@@ -0,0 +1,202 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d213d5b0bd902d851f50471774134d5ad443e362
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/__pycache__/conftest.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/__pycache__/conftest.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5961647292bc3bd7a921e650f4b01da4490b286a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/__pycache__/conftest.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/__pycache__/convert.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/__pycache__/convert.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b08f8467a79fa268b6370b76a9abcf646467a8a8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/__pycache__/convert.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/__pycache__/convert_matrix.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/__pycache__/convert_matrix.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9b2c10588eca59cd7d0eb33a4da7b6ee3e387761
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/__pycache__/convert_matrix.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/__pycache__/exception.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/__pycache__/exception.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2581680abdae286eea621141a8d8ae28f6adb5ad
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/__pycache__/exception.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/__pycache__/lazy_imports.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/__pycache__/lazy_imports.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0dfeb0ac79dd02545e114982f0df9297a408a6b8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/__pycache__/lazy_imports.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/__pycache__/relabel.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/__pycache__/relabel.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..23bdcc7141f21c37f489a5d0a3bf5e782cccb9ae
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/__pycache__/relabel.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6439d56fe1364cf9b08e2a20affe4362cb56cbe8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/__init__.py
@@ -0,0 +1,134 @@
+from networkx.algorithms.assortativity import *
+from networkx.algorithms.asteroidal import *
+from networkx.algorithms.boundary import *
+from networkx.algorithms.broadcasting import *
+from networkx.algorithms.bridges import *
+from networkx.algorithms.chains import *
+from networkx.algorithms.centrality import *
+from networkx.algorithms.chordal import *
+from networkx.algorithms.cluster import *
+from networkx.algorithms.clique import *
+from networkx.algorithms.communicability_alg import *
+from networkx.algorithms.components import *
+from networkx.algorithms.coloring import *
+from networkx.algorithms.core import *
+from networkx.algorithms.covering import *
+from networkx.algorithms.cycles import *
+from networkx.algorithms.cuts import *
+from networkx.algorithms.d_separation import *
+from networkx.algorithms.dag import *
+from networkx.algorithms.distance_measures import *
+from networkx.algorithms.distance_regular import *
+from networkx.algorithms.dominance import *
+from networkx.algorithms.dominating import *
+from networkx.algorithms.efficiency_measures import *
+from networkx.algorithms.euler import *
+from networkx.algorithms.graphical import *
+from networkx.algorithms.hierarchy import *
+from networkx.algorithms.hybrid import *
+from networkx.algorithms.link_analysis import *
+from networkx.algorithms.link_prediction import *
+from networkx.algorithms.lowest_common_ancestors import *
+from networkx.algorithms.isolate import *
+from networkx.algorithms.matching import *
+from networkx.algorithms.minors import *
+from networkx.algorithms.mis import *
+from networkx.algorithms.moral import *
+from networkx.algorithms.non_randomness import *
+from networkx.algorithms.operators import *
+from networkx.algorithms.planarity import *
+from networkx.algorithms.planar_drawing import *
+from networkx.algorithms.polynomials import *
+from networkx.algorithms.perfect_graph import *
+from networkx.algorithms.reciprocity import *
+from networkx.algorithms.regular import *
+from networkx.algorithms.richclub import *
+from networkx.algorithms.shortest_paths import *
+from networkx.algorithms.similarity import *
+from networkx.algorithms.graph_hashing import *
+from networkx.algorithms.simple_paths import *
+from networkx.algorithms.smallworld import *
+from networkx.algorithms.smetric import *
+from networkx.algorithms.structuralholes import *
+from networkx.algorithms.sparsifiers import *
+from networkx.algorithms.summarization import *
+from networkx.algorithms.swap import *
+from networkx.algorithms.time_dependent import *
+from networkx.algorithms.traversal import *
+from networkx.algorithms.triads import *
+from networkx.algorithms.vitality import *
+from networkx.algorithms.voronoi import *
+from networkx.algorithms.walks import *
+from networkx.algorithms.wiener import *
+
+# Make certain subpackages available to the user as direct imports from
+# the `networkx` namespace.
+from networkx.algorithms import approximation
+from networkx.algorithms import assortativity
+from networkx.algorithms import bipartite
+from networkx.algorithms import node_classification
+from networkx.algorithms import centrality
+from networkx.algorithms import chordal
+from networkx.algorithms import cluster
+from networkx.algorithms import clique
+from networkx.algorithms import components
+from networkx.algorithms import connectivity
+from networkx.algorithms import community
+from networkx.algorithms import coloring
+from networkx.algorithms import flow
+from networkx.algorithms import isomorphism
+from networkx.algorithms import link_analysis
+from networkx.algorithms import lowest_common_ancestors
+from networkx.algorithms import operators
+from networkx.algorithms import shortest_paths
+from networkx.algorithms import tournament
+from networkx.algorithms import traversal
+from networkx.algorithms import tree
+
+# Make certain functions from some of the previous subpackages available
+# to the user as direct imports from the `networkx` namespace.
+from networkx.algorithms.bipartite import complete_bipartite_graph
+from networkx.algorithms.bipartite import is_bipartite
+from networkx.algorithms.bipartite import projected_graph
+from networkx.algorithms.connectivity import all_pairs_node_connectivity
+from networkx.algorithms.connectivity import all_node_cuts
+from networkx.algorithms.connectivity import average_node_connectivity
+from networkx.algorithms.connectivity import edge_connectivity
+from networkx.algorithms.connectivity import edge_disjoint_paths
+from networkx.algorithms.connectivity import k_components
+from networkx.algorithms.connectivity import k_edge_components
+from networkx.algorithms.connectivity import k_edge_subgraphs
+from networkx.algorithms.connectivity import k_edge_augmentation
+from networkx.algorithms.connectivity import is_k_edge_connected
+from networkx.algorithms.connectivity import minimum_edge_cut
+from networkx.algorithms.connectivity import minimum_node_cut
+from networkx.algorithms.connectivity import node_connectivity
+from networkx.algorithms.connectivity import node_disjoint_paths
+from networkx.algorithms.connectivity import stoer_wagner
+from networkx.algorithms.flow import capacity_scaling
+from networkx.algorithms.flow import cost_of_flow
+from networkx.algorithms.flow import gomory_hu_tree
+from networkx.algorithms.flow import max_flow_min_cost
+from networkx.algorithms.flow import maximum_flow
+from networkx.algorithms.flow import maximum_flow_value
+from networkx.algorithms.flow import min_cost_flow
+from networkx.algorithms.flow import min_cost_flow_cost
+from networkx.algorithms.flow import minimum_cut
+from networkx.algorithms.flow import minimum_cut_value
+from networkx.algorithms.flow import network_simplex
+from networkx.algorithms.isomorphism import could_be_isomorphic
+from networkx.algorithms.isomorphism import fast_could_be_isomorphic
+from networkx.algorithms.isomorphism import faster_could_be_isomorphic
+from networkx.algorithms.isomorphism import is_isomorphic
+from networkx.algorithms.isomorphism.vf2pp import *
+from networkx.algorithms.tree.branchings import maximum_branching
+from networkx.algorithms.tree.branchings import maximum_spanning_arborescence
+from networkx.algorithms.tree.branchings import minimum_branching
+from networkx.algorithms.tree.branchings import minimum_spanning_arborescence
+from networkx.algorithms.tree.branchings import ArborescenceIterator
+from networkx.algorithms.tree.coding import *
+from networkx.algorithms.tree.decomposition import *
+from networkx.algorithms.tree.mst import *
+from networkx.algorithms.tree.operations import *
+from networkx.algorithms.tree.recognition import *
+from networkx.algorithms.tournament import is_tournament
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/assortativity/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/assortativity/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d9888609cbc43d4ba2121fcd0feda0985d1aebd
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/assortativity/__init__.py
@@ -0,0 +1,5 @@
+from networkx.algorithms.assortativity.connectivity import *
+from networkx.algorithms.assortativity.correlation import *
+from networkx.algorithms.assortativity.mixing import *
+from networkx.algorithms.assortativity.neighbor_degree import *
+from networkx.algorithms.assortativity.pairs import *
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/assortativity/connectivity.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/assortativity/connectivity.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3fde0da68a1990da29ced6996620d709c52c13d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/assortativity/connectivity.py
@@ -0,0 +1,122 @@
+from collections import defaultdict
+
+import networkx as nx
+
+__all__ = ["average_degree_connectivity"]
+
+
+@nx._dispatchable(edge_attrs="weight")
+def average_degree_connectivity(
+    G, source="in+out", target="in+out", nodes=None, weight=None
+):
+    r"""Compute the average degree connectivity of graph.
+
+    The average degree connectivity is the average nearest neighbor degree of
+    nodes with degree k. For weighted graphs, an analogous measure can
+    be computed using the weighted average neighbors degree defined in
+    [1]_, for a node `i`, as
+
+    .. math::
+
+        k_{nn,i}^{w} = \frac{1}{s_i} \sum_{j \in N(i)} w_{ij} k_j
+
+    where `s_i` is the weighted degree of node `i`,
+    `w_{ij}` is the weight of the edge that links `i` and `j`,
+    and `N(i)` are the neighbors of node `i`.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    source :  "in"|"out"|"in+out" (default:"in+out")
+       Directed graphs only. Use "in"- or "out"-degree for source node.
+
+    target : "in"|"out"|"in+out" (default:"in+out"
+       Directed graphs only. Use "in"- or "out"-degree for target node.
+
+    nodes : list or iterable (optional)
+        Compute neighbor connectivity for these nodes. The default is all
+        nodes.
+
+    weight : string or None, optional (default=None)
+       The edge attribute that holds the numerical value used as a weight.
+       If None, then each edge has weight 1.
+
+    Returns
+    -------
+    d : dict
+       A dictionary keyed by degree k with the value of average connectivity.
+
+    Raises
+    ------
+    NetworkXError
+        If either `source` or `target` are not one of 'in',
+        'out', or 'in+out'.
+        If either `source` or `target` is passed for an undirected graph.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> G.edges[1, 2]["weight"] = 3
+    >>> nx.average_degree_connectivity(G)
+    {1: 2.0, 2: 1.5}
+    >>> nx.average_degree_connectivity(G, weight="weight")
+    {1: 2.0, 2: 1.75}
+
+    See Also
+    --------
+    average_neighbor_degree
+
+    References
+    ----------
+    .. [1] A. Barrat, M. Barthélemy, R. Pastor-Satorras, and A. Vespignani,
+       "The architecture of complex weighted networks".
+       PNAS 101 (11): 3747–3752 (2004).
+    """
+    # First, determine the type of neighbors and the type of degree to use.
+    if G.is_directed():
+        if source not in ("in", "out", "in+out"):
+            raise nx.NetworkXError('source must be one of "in", "out", or "in+out"')
+        if target not in ("in", "out", "in+out"):
+            raise nx.NetworkXError('target must be one of "in", "out", or "in+out"')
+        direction = {"out": G.out_degree, "in": G.in_degree, "in+out": G.degree}
+        neighbor_funcs = {
+            "out": G.successors,
+            "in": G.predecessors,
+            "in+out": G.neighbors,
+        }
+        source_degree = direction[source]
+        target_degree = direction[target]
+        neighbors = neighbor_funcs[source]
+        # `reverse` indicates whether to look at the in-edge when
+        # computing the weight of an edge.
+        reverse = source == "in"
+    else:
+        if source != "in+out" or target != "in+out":
+            raise nx.NetworkXError(
+                f"source and target arguments are only supported for directed graphs"
+            )
+        source_degree = G.degree
+        target_degree = G.degree
+        neighbors = G.neighbors
+        reverse = False
+    dsum = defaultdict(int)
+    dnorm = defaultdict(int)
+    # Check if `source_nodes` is actually a single node in the graph.
+    source_nodes = source_degree(nodes)
+    if nodes in G:
+        source_nodes = [(nodes, source_degree(nodes))]
+    for n, k in source_nodes:
+        nbrdeg = target_degree(neighbors(n))
+        if weight is None:
+            s = sum(d for n, d in nbrdeg)
+        else:  # weight nbr degree by weight of (n,nbr) edge
+            if reverse:
+                s = sum(G[nbr][n].get(weight, 1) * d for nbr, d in nbrdeg)
+            else:
+                s = sum(G[n][nbr].get(weight, 1) * d for nbr, d in nbrdeg)
+        dnorm[k] += source_degree(n, weight=weight)
+        dsum[k] += s
+
+    # normalize
+    return {k: avg if dnorm[k] == 0 else avg / dnorm[k] for k, avg in dsum.items()}
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/assortativity/correlation.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/assortativity/correlation.py
new file mode 100644
index 0000000000000000000000000000000000000000..52ae7a12fa9de5705412538fc6bbe873755d9b7a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/assortativity/correlation.py
@@ -0,0 +1,302 @@
+"""Node assortativity coefficients and correlation measures."""
+
+import networkx as nx
+from networkx.algorithms.assortativity.mixing import (
+    attribute_mixing_matrix,
+    degree_mixing_matrix,
+)
+from networkx.algorithms.assortativity.pairs import node_degree_xy
+
+__all__ = [
+    "degree_pearson_correlation_coefficient",
+    "degree_assortativity_coefficient",
+    "attribute_assortativity_coefficient",
+    "numeric_assortativity_coefficient",
+]
+
+
+@nx._dispatchable(edge_attrs="weight")
+def degree_assortativity_coefficient(G, x="out", y="in", weight=None, nodes=None):
+    """Compute degree assortativity of graph.
+
+    Assortativity measures the similarity of connections
+    in the graph with respect to the node degree.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    x: string ('in','out')
+       The degree type for source node (directed graphs only).
+
+    y: string ('in','out')
+       The degree type for target node (directed graphs only).
+
+    weight: string or None, optional (default=None)
+       The edge attribute that holds the numerical value used
+       as a weight.  If None, then each edge has weight 1.
+       The degree is the sum of the edge weights adjacent to the node.
+
+    nodes: list or iterable (optional)
+        Compute degree assortativity only for nodes in container.
+        The default is all nodes.
+
+    Returns
+    -------
+    r : float
+       Assortativity of graph by degree.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> r = nx.degree_assortativity_coefficient(G)
+    >>> print(f"{r:3.1f}")
+    -0.5
+
+    See Also
+    --------
+    attribute_assortativity_coefficient
+    numeric_assortativity_coefficient
+    degree_mixing_dict
+    degree_mixing_matrix
+
+    Notes
+    -----
+    This computes Eq. (21) in Ref. [1]_ , where e is the joint
+    probability distribution (mixing matrix) of the degrees.  If G is
+    directed than the matrix e is the joint probability of the
+    user-specified degree type for the source and target.
+
+    References
+    ----------
+    .. [1] M. E. J. Newman, Mixing patterns in networks,
+       Physical Review E, 67 026126, 2003
+    .. [2] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M.
+       Edge direction and the structure of networks, PNAS 107, 10815-20 (2010).
+    """
+    if nodes is None:
+        nodes = G.nodes
+
+    degrees = None
+
+    if G.is_directed():
+        indeg = (
+            {d for _, d in G.in_degree(nodes, weight=weight)}
+            if "in" in (x, y)
+            else set()
+        )
+        outdeg = (
+            {d for _, d in G.out_degree(nodes, weight=weight)}
+            if "out" in (x, y)
+            else set()
+        )
+        degrees = set.union(indeg, outdeg)
+    else:
+        degrees = {d for _, d in G.degree(nodes, weight=weight)}
+
+    mapping = {d: i for i, d in enumerate(degrees)}
+    M = degree_mixing_matrix(G, x=x, y=y, nodes=nodes, weight=weight, mapping=mapping)
+
+    return _numeric_ac(M, mapping=mapping)
+
+
+@nx._dispatchable(edge_attrs="weight")
+def degree_pearson_correlation_coefficient(G, x="out", y="in", weight=None, nodes=None):
+    """Compute degree assortativity of graph.
+
+    Assortativity measures the similarity of connections
+    in the graph with respect to the node degree.
+
+    This is the same as degree_assortativity_coefficient but uses the
+    potentially faster scipy.stats.pearsonr function.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    x: string ('in','out')
+       The degree type for source node (directed graphs only).
+
+    y: string ('in','out')
+       The degree type for target node (directed graphs only).
+
+    weight: string or None, optional (default=None)
+       The edge attribute that holds the numerical value used
+       as a weight.  If None, then each edge has weight 1.
+       The degree is the sum of the edge weights adjacent to the node.
+
+    nodes: list or iterable (optional)
+        Compute pearson correlation of degrees only for specified nodes.
+        The default is all nodes.
+
+    Returns
+    -------
+    r : float
+       Assortativity of graph by degree.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> r = nx.degree_pearson_correlation_coefficient(G)
+    >>> print(f"{r:3.1f}")
+    -0.5
+
+    Notes
+    -----
+    This calls scipy.stats.pearsonr.
+
+    References
+    ----------
+    .. [1] M. E. J. Newman, Mixing patterns in networks
+           Physical Review E, 67 026126, 2003
+    .. [2] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M.
+       Edge direction and the structure of networks, PNAS 107, 10815-20 (2010).
+    """
+    import scipy as sp
+
+    xy = node_degree_xy(G, x=x, y=y, nodes=nodes, weight=weight)
+    x, y = zip(*xy)
+    return float(sp.stats.pearsonr(x, y)[0])
+
+
+@nx._dispatchable(node_attrs="attribute")
+def attribute_assortativity_coefficient(G, attribute, nodes=None):
+    """Compute assortativity for node attributes.
+
+    Assortativity measures the similarity of connections
+    in the graph with respect to the given attribute.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    attribute : string
+        Node attribute key
+
+    nodes: list or iterable (optional)
+        Compute attribute assortativity for nodes in container.
+        The default is all nodes.
+
+    Returns
+    -------
+    r: float
+       Assortativity of graph for given attribute
+
+    Examples
+    --------
+    >>> G = nx.Graph()
+    >>> G.add_nodes_from([0, 1], color="red")
+    >>> G.add_nodes_from([2, 3], color="blue")
+    >>> G.add_edges_from([(0, 1), (2, 3)])
+    >>> print(nx.attribute_assortativity_coefficient(G, "color"))
+    1.0
+
+    Notes
+    -----
+    This computes Eq. (2) in Ref. [1]_ , (trace(M)-sum(M^2))/(1-sum(M^2)),
+    where M is the joint probability distribution (mixing matrix)
+    of the specified attribute.
+
+    References
+    ----------
+    .. [1] M. E. J. Newman, Mixing patterns in networks,
+       Physical Review E, 67 026126, 2003
+    """
+    M = attribute_mixing_matrix(G, attribute, nodes)
+    return attribute_ac(M)
+
+
+@nx._dispatchable(node_attrs="attribute")
+def numeric_assortativity_coefficient(G, attribute, nodes=None):
+    """Compute assortativity for numerical node attributes.
+
+    Assortativity measures the similarity of connections
+    in the graph with respect to the given numeric attribute.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    attribute : string
+        Node attribute key.
+
+    nodes: list or iterable (optional)
+        Compute numeric assortativity only for attributes of nodes in
+        container. The default is all nodes.
+
+    Returns
+    -------
+    r: float
+       Assortativity of graph for given attribute
+
+    Examples
+    --------
+    >>> G = nx.Graph()
+    >>> G.add_nodes_from([0, 1], size=2)
+    >>> G.add_nodes_from([2, 3], size=3)
+    >>> G.add_edges_from([(0, 1), (2, 3)])
+    >>> print(nx.numeric_assortativity_coefficient(G, "size"))
+    1.0
+
+    Notes
+    -----
+    This computes Eq. (21) in Ref. [1]_ , which is the Pearson correlation
+    coefficient of the specified (scalar valued) attribute across edges.
+
+    References
+    ----------
+    .. [1] M. E. J. Newman, Mixing patterns in networks
+           Physical Review E, 67 026126, 2003
+    """
+    if nodes is None:
+        nodes = G.nodes
+    vals = {G.nodes[n][attribute] for n in nodes}
+    mapping = {d: i for i, d in enumerate(vals)}
+    M = attribute_mixing_matrix(G, attribute, nodes, mapping)
+    return _numeric_ac(M, mapping)
+
+
+def attribute_ac(M):
+    """Compute assortativity for attribute matrix M.
+
+    Parameters
+    ----------
+    M : numpy.ndarray
+        2D ndarray representing the attribute mixing matrix.
+
+    Notes
+    -----
+    This computes Eq. (2) in Ref. [1]_ , (trace(e)-sum(e^2))/(1-sum(e^2)),
+    where e is the joint probability distribution (mixing matrix)
+    of the specified attribute.
+
+    References
+    ----------
+    .. [1] M. E. J. Newman, Mixing patterns in networks,
+       Physical Review E, 67 026126, 2003
+    """
+    if M.sum() != 1.0:
+        M = M / M.sum()
+    s = (M @ M).sum()
+    t = M.trace()
+    r = (t - s) / (1 - s)
+    return float(r)
+
+
+def _numeric_ac(M, mapping):
+    # M is a 2D numpy array
+    # numeric assortativity coefficient, pearsonr
+    import numpy as np
+
+    if M.sum() != 1.0:
+        M = M / M.sum()
+    x = np.array(list(mapping.keys()))
+    y = x  # x and y have the same support
+    idx = list(mapping.values())
+    a = M.sum(axis=0)
+    b = M.sum(axis=1)
+    vara = (a[idx] * x**2).sum() - ((a[idx] * x).sum()) ** 2
+    varb = (b[idx] * y**2).sum() - ((b[idx] * y).sum()) ** 2
+    xy = np.outer(x, y)
+    ab = np.outer(a[idx], b[idx])
+    return float((xy * (M - ab)).sum() / np.sqrt(vara * varb))
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/assortativity/mixing.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/assortativity/mixing.py
new file mode 100644
index 0000000000000000000000000000000000000000..1762d4e56c96624ecb4cccf1f2247f46159a12e4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/assortativity/mixing.py
@@ -0,0 +1,255 @@
+"""
+Mixing matrices for node attributes and degree.
+"""
+
+import networkx as nx
+from networkx.algorithms.assortativity.pairs import node_attribute_xy, node_degree_xy
+from networkx.utils import dict_to_numpy_array
+
+__all__ = [
+    "attribute_mixing_matrix",
+    "attribute_mixing_dict",
+    "degree_mixing_matrix",
+    "degree_mixing_dict",
+    "mixing_dict",
+]
+
+
+@nx._dispatchable(node_attrs="attribute")
+def attribute_mixing_dict(G, attribute, nodes=None, normalized=False):
+    """Returns dictionary representation of mixing matrix for attribute.
+
+    Parameters
+    ----------
+    G : graph
+       NetworkX graph object.
+
+    attribute : string
+       Node attribute key.
+
+    nodes: list or iterable (optional)
+        Unse nodes in container to build the dict. The default is all nodes.
+
+    normalized : bool (default=False)
+       Return counts if False or probabilities if True.
+
+    Examples
+    --------
+    >>> G = nx.Graph()
+    >>> G.add_nodes_from([0, 1], color="red")
+    >>> G.add_nodes_from([2, 3], color="blue")
+    >>> G.add_edge(1, 3)
+    >>> d = nx.attribute_mixing_dict(G, "color")
+    >>> print(d["red"]["blue"])
+    1
+    >>> print(d["blue"]["red"])  # d symmetric for undirected graphs
+    1
+
+    Returns
+    -------
+    d : dictionary
+       Counts or joint probability of occurrence of attribute pairs.
+    """
+    xy_iter = node_attribute_xy(G, attribute, nodes)
+    return mixing_dict(xy_iter, normalized=normalized)
+
+
+@nx._dispatchable(node_attrs="attribute")
+def attribute_mixing_matrix(G, attribute, nodes=None, mapping=None, normalized=True):
+    """Returns mixing matrix for attribute.
+
+    Parameters
+    ----------
+    G : graph
+       NetworkX graph object.
+
+    attribute : string
+       Node attribute key.
+
+    nodes: list or iterable (optional)
+        Use only nodes in container to build the matrix. The default is
+        all nodes.
+
+    mapping : dictionary, optional
+       Mapping from node attribute to integer index in matrix.
+       If not specified, an arbitrary ordering will be used.
+
+    normalized : bool (default=True)
+       Return counts if False or probabilities if True.
+
+    Returns
+    -------
+    m: numpy array
+       Counts or joint probability of occurrence of attribute pairs.
+
+    Notes
+    -----
+    If each node has a unique attribute value, the unnormalized mixing matrix
+    will be equal to the adjacency matrix. To get a denser mixing matrix,
+    the rounding can be performed to form groups of nodes with equal values.
+    For example, the exact height of persons in cm (180.79155222, 163.9080892,
+    163.30095355, 167.99016217, 168.21590163, ...) can be rounded to (180, 163,
+    163, 168, 168, ...).
+
+    Definitions of attribute mixing matrix vary on whether the matrix
+    should include rows for attribute values that don't arise. Here we
+    do not include such empty-rows. But you can force them to appear
+    by inputting a `mapping` that includes those values.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(3)
+    >>> gender = {0: "male", 1: "female", 2: "female"}
+    >>> nx.set_node_attributes(G, gender, "gender")
+    >>> mapping = {"male": 0, "female": 1}
+    >>> mix_mat = nx.attribute_mixing_matrix(G, "gender", mapping=mapping)
+    >>> mix_mat
+    array([[0.  , 0.25],
+           [0.25, 0.5 ]])
+    """
+    d = attribute_mixing_dict(G, attribute, nodes)
+    a = dict_to_numpy_array(d, mapping=mapping)
+    if normalized:
+        a = a / a.sum()
+    return a
+
+
+@nx._dispatchable(edge_attrs="weight")
+def degree_mixing_dict(G, x="out", y="in", weight=None, nodes=None, normalized=False):
+    """Returns dictionary representation of mixing matrix for degree.
+
+    Parameters
+    ----------
+    G : graph
+        NetworkX graph object.
+
+    x: string ('in','out')
+       The degree type for source node (directed graphs only).
+
+    y: string ('in','out')
+       The degree type for target node (directed graphs only).
+
+    weight: string or None, optional (default=None)
+       The edge attribute that holds the numerical value used
+       as a weight.  If None, then each edge has weight 1.
+       The degree is the sum of the edge weights adjacent to the node.
+
+    normalized : bool (default=False)
+        Return counts if False or probabilities if True.
+
+    Returns
+    -------
+    d: dictionary
+       Counts or joint probability of occurrence of degree pairs.
+    """
+    xy_iter = node_degree_xy(G, x=x, y=y, nodes=nodes, weight=weight)
+    return mixing_dict(xy_iter, normalized=normalized)
+
+
+@nx._dispatchable(edge_attrs="weight")
+def degree_mixing_matrix(
+    G, x="out", y="in", weight=None, nodes=None, normalized=True, mapping=None
+):
+    """Returns mixing matrix for attribute.
+
+    Parameters
+    ----------
+    G : graph
+       NetworkX graph object.
+
+    x: string ('in','out')
+       The degree type for source node (directed graphs only).
+
+    y: string ('in','out')
+       The degree type for target node (directed graphs only).
+
+    nodes: list or iterable (optional)
+        Build the matrix using only nodes in container.
+        The default is all nodes.
+
+    weight: string or None, optional (default=None)
+       The edge attribute that holds the numerical value used
+       as a weight.  If None, then each edge has weight 1.
+       The degree is the sum of the edge weights adjacent to the node.
+
+    normalized : bool (default=True)
+       Return counts if False or probabilities if True.
+
+    mapping : dictionary, optional
+       Mapping from node degree to integer index in matrix.
+       If not specified, an arbitrary ordering will be used.
+
+    Returns
+    -------
+    m: numpy array
+       Counts, or joint probability, of occurrence of node degree.
+
+    Notes
+    -----
+    Definitions of degree mixing matrix vary on whether the matrix
+    should include rows for degree values that don't arise. Here we
+    do not include such empty-rows. But you can force them to appear
+    by inputting a `mapping` that includes those values. See examples.
+
+    Examples
+    --------
+    >>> G = nx.star_graph(3)
+    >>> mix_mat = nx.degree_mixing_matrix(G)
+    >>> mix_mat
+    array([[0. , 0.5],
+           [0.5, 0. ]])
+
+    If you want every possible degree to appear as a row, even if no nodes
+    have that degree, use `mapping` as follows,
+
+    >>> max_degree = max(deg for n, deg in G.degree)
+    >>> mapping = {x: x for x in range(max_degree + 1)}  # identity mapping
+    >>> mix_mat = nx.degree_mixing_matrix(G, mapping=mapping)
+    >>> mix_mat
+    array([[0. , 0. , 0. , 0. ],
+           [0. , 0. , 0. , 0.5],
+           [0. , 0. , 0. , 0. ],
+           [0. , 0.5, 0. , 0. ]])
+    """
+    d = degree_mixing_dict(G, x=x, y=y, nodes=nodes, weight=weight)
+    a = dict_to_numpy_array(d, mapping=mapping)
+    if normalized:
+        a = a / a.sum()
+    return a
+
+
+def mixing_dict(xy, normalized=False):
+    """Returns a dictionary representation of mixing matrix.
+
+    Parameters
+    ----------
+    xy : list or container of two-tuples
+       Pairs of (x,y) items.
+
+    attribute : string
+       Node attribute key
+
+    normalized : bool (default=False)
+       Return counts if False or probabilities if True.
+
+    Returns
+    -------
+    d: dictionary
+       Counts or Joint probability of occurrence of values in xy.
+    """
+    d = {}
+    psum = 0.0
+    for x, y in xy:
+        if x not in d:
+            d[x] = {}
+        if y not in d:
+            d[y] = {}
+        v = d[x].get(y, 0)
+        d[x][y] = v + 1
+        psum += 1
+
+    if normalized:
+        for _, jdict in d.items():
+            for j in jdict:
+                jdict[j] /= psum
+    return d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/assortativity/neighbor_degree.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/assortativity/neighbor_degree.py
new file mode 100644
index 0000000000000000000000000000000000000000..6488d041a8bdc93ef3591283781b81bcf7f47dab
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/assortativity/neighbor_degree.py
@@ -0,0 +1,160 @@
+import networkx as nx
+
+__all__ = ["average_neighbor_degree"]
+
+
+@nx._dispatchable(edge_attrs="weight")
+def average_neighbor_degree(G, source="out", target="out", nodes=None, weight=None):
+    r"""Returns the average degree of the neighborhood of each node.
+
+    In an undirected graph, the neighborhood `N(i)` of node `i` contains the
+    nodes that are connected to `i` by an edge.
+
+    For directed graphs, `N(i)` is defined according to the parameter `source`:
+
+        - if source is 'in', then `N(i)` consists of predecessors of node `i`.
+        - if source is 'out', then `N(i)` consists of successors of node `i`.
+        - if source is 'in+out', then `N(i)` is both predecessors and successors.
+
+    The average neighborhood degree of a node `i` is
+
+    .. math::
+
+        k_{nn,i} = \frac{1}{|N(i)|} \sum_{j \in N(i)} k_j
+
+    where `N(i)` are the neighbors of node `i` and `k_j` is
+    the degree of node `j` which belongs to `N(i)`. For weighted
+    graphs, an analogous measure can be defined [1]_,
+
+    .. math::
+
+        k_{nn,i}^{w} = \frac{1}{s_i} \sum_{j \in N(i)} w_{ij} k_j
+
+    where `s_i` is the weighted degree of node `i`, `w_{ij}`
+    is the weight of the edge that links `i` and `j` and
+    `N(i)` are the neighbors of node `i`.
+
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    source : string ("in"|"out"|"in+out"), optional (default="out")
+       Directed graphs only.
+       Use "in"- or "out"-neighbors of source node.
+
+    target : string ("in"|"out"|"in+out"), optional (default="out")
+       Directed graphs only.
+       Use "in"- or "out"-degree for target node.
+
+    nodes : list or iterable, optional (default=G.nodes)
+        Compute neighbor degree only for specified nodes.
+
+    weight : string or None, optional (default=None)
+       The edge attribute that holds the numerical value used as a weight.
+       If None, then each edge has weight 1.
+
+    Returns
+    -------
+    d: dict
+       A dictionary keyed by node to the average degree of its neighbors.
+
+    Raises
+    ------
+    NetworkXError
+        If either `source` or `target` are not one of 'in', 'out', or 'in+out'.
+        If either `source` or `target` is passed for an undirected graph.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> G.edges[0, 1]["weight"] = 5
+    >>> G.edges[2, 3]["weight"] = 3
+
+    >>> nx.average_neighbor_degree(G)
+    {0: 2.0, 1: 1.5, 2: 1.5, 3: 2.0}
+    >>> nx.average_neighbor_degree(G, weight="weight")
+    {0: 2.0, 1: 1.1666666666666667, 2: 1.25, 3: 2.0}
+
+    >>> G = nx.DiGraph()
+    >>> nx.add_path(G, [0, 1, 2, 3])
+    >>> nx.average_neighbor_degree(G, source="in", target="in")
+    {0: 0.0, 1: 0.0, 2: 1.0, 3: 1.0}
+
+    >>> nx.average_neighbor_degree(G, source="out", target="out")
+    {0: 1.0, 1: 1.0, 2: 0.0, 3: 0.0}
+
+    See Also
+    --------
+    average_degree_connectivity
+
+    References
+    ----------
+    .. [1] A. Barrat, M. Barthélemy, R. Pastor-Satorras, and A. Vespignani,
+       "The architecture of complex weighted networks".
+       PNAS 101 (11): 3747–3752 (2004).
+    """
+    if G.is_directed():
+        if source == "in":
+            source_degree = G.in_degree
+        elif source == "out":
+            source_degree = G.out_degree
+        elif source == "in+out":
+            source_degree = G.degree
+        else:
+            raise nx.NetworkXError(
+                f"source argument {source} must be 'in', 'out' or 'in+out'"
+            )
+
+        if target == "in":
+            target_degree = G.in_degree
+        elif target == "out":
+            target_degree = G.out_degree
+        elif target == "in+out":
+            target_degree = G.degree
+        else:
+            raise nx.NetworkXError(
+                f"target argument {target} must be 'in', 'out' or 'in+out'"
+            )
+    else:
+        if source != "out" or target != "out":
+            raise nx.NetworkXError(
+                f"source and target arguments are only supported for directed graphs"
+            )
+        source_degree = target_degree = G.degree
+
+    # precompute target degrees -- should *not* be weighted degree
+    t_deg = dict(target_degree())
+
+    # Set up both predecessor and successor neighbor dicts leaving empty if not needed
+    G_P = G_S = {n: {} for n in G}
+    if G.is_directed():
+        # "in" or "in+out" cases: G_P contains predecessors
+        if "in" in source:
+            G_P = G.pred
+        # "out" or "in+out" cases: G_S contains successors
+        if "out" in source:
+            G_S = G.succ
+    else:
+        # undirected leave G_P empty but G_S is the adjacency
+        G_S = G.adj
+
+    # Main loop: Compute average degree of neighbors
+    avg = {}
+    for n, deg in source_degree(nodes, weight=weight):
+        # handle degree zero average
+        if deg == 0:
+            avg[n] = 0.0
+            continue
+
+        # we sum over both G_P and G_S, but one of the two is usually empty.
+        if weight is None:
+            avg[n] = (
+                sum(t_deg[nbr] for nbr in G_S[n]) + sum(t_deg[nbr] for nbr in G_P[n])
+            ) / deg
+        else:
+            avg[n] = (
+                sum(dd.get(weight, 1) * t_deg[nbr] for nbr, dd in G_S[n].items())
+                + sum(dd.get(weight, 1) * t_deg[nbr] for nbr, dd in G_P[n].items())
+            ) / deg
+    return avg
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/assortativity/pairs.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/assortativity/pairs.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea5fd287545c80dd2ebbb2b253d5ab0ab7480743
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/assortativity/pairs.py
@@ -0,0 +1,127 @@
+"""Generators of x-y pairs of node data."""
+
+import networkx as nx
+
+__all__ = ["node_attribute_xy", "node_degree_xy"]
+
+
+@nx._dispatchable(node_attrs="attribute")
+def node_attribute_xy(G, attribute, nodes=None):
+    """Yields 2-tuples of node attribute values for all edges in `G`.
+
+    This generator yields, for each edge in `G` incident to a node in `nodes`,
+    a 2-tuple of form ``(attribute value,  attribute value)`` for the parameter
+    specified node-attribute.
+
+    Parameters
+    ----------
+    G: NetworkX graph
+
+    attribute: key
+        The node attribute key.
+
+    nodes: list or iterable (optional)
+        Use only edges that are incident to specified nodes.
+        The default is all nodes.
+
+    Yields
+    ------
+    (x, y): 2-tuple
+        Generates 2-tuple of (attribute, attribute) values.
+
+    Examples
+    --------
+    >>> G = nx.DiGraph()
+    >>> G.add_node(1, color="red")
+    >>> G.add_node(2, color="blue")
+    >>> G.add_node(3, color="green")
+    >>> G.add_edge(1, 2)
+    >>> list(nx.node_attribute_xy(G, "color"))
+    [('red', 'blue')]
+
+    Notes
+    -----
+    For undirected graphs, each edge is produced twice, once for each edge
+    representation (u, v) and (v, u), with the exception of self-loop edges
+    which only appear once.
+    """
+    if nodes is None:
+        nodes = set(G)
+    else:
+        nodes = set(nodes)
+    Gnodes = G.nodes
+    for u, nbrsdict in G.adjacency():
+        if u not in nodes:
+            continue
+        uattr = Gnodes[u].get(attribute, None)
+        if G.is_multigraph():
+            for v, keys in nbrsdict.items():
+                vattr = Gnodes[v].get(attribute, None)
+                for _ in keys:
+                    yield (uattr, vattr)
+        else:
+            for v in nbrsdict:
+                vattr = Gnodes[v].get(attribute, None)
+                yield (uattr, vattr)
+
+
+@nx._dispatchable(edge_attrs="weight")
+def node_degree_xy(G, x="out", y="in", weight=None, nodes=None):
+    """Yields 2-tuples of ``(degree, degree)`` values for edges in `G`.
+
+    This generator yields, for each edge in `G` incident to a node in `nodes`,
+    a 2-tuple of form ``(degree, degree)``. The node degrees are weighted
+    when a `weight` attribute is specified.
+
+    Parameters
+    ----------
+    G: NetworkX graph
+
+    x: string ('in','out')
+       The degree type for source node (directed graphs only).
+
+    y: string ('in','out')
+       The degree type for target node (directed graphs only).
+
+    weight: string or None, optional (default=None)
+       The edge attribute that holds the numerical value used
+       as a weight.  If None, then each edge has weight 1.
+       The degree is the sum of the edge weights adjacent to the node.
+
+    nodes: list or iterable (optional)
+        Use only edges that are adjacency to specified nodes.
+        The default is all nodes.
+
+    Yields
+    ------
+    (x, y): 2-tuple
+        Generates 2-tuple of (degree, degree) values.
+
+    Examples
+    --------
+    >>> G = nx.DiGraph()
+    >>> G.add_edge(1, 2)
+    >>> list(nx.node_degree_xy(G, x="out", y="in"))
+    [(1, 1)]
+    >>> list(nx.node_degree_xy(G, x="in", y="out"))
+    [(0, 0)]
+
+    Notes
+    -----
+    For undirected graphs, each edge is produced twice, once for each edge
+    representation (u, v) and (v, u), with the exception of self-loop edges
+    which only appear once.
+    """
+    nodes = set(G) if nodes is None else set(nodes)
+    if G.is_directed():
+        direction = {"out": G.out_degree, "in": G.in_degree}
+        xdeg = direction[x]
+        ydeg = direction[y]
+    else:
+        xdeg = ydeg = G.degree
+
+    for u, degu in xdeg(nodes, weight=weight):
+        # use G.edges to treat multigraphs correctly
+        neighbors = (nbr for _, nbr in G.edges(u) if nbr in nodes)
+        for _, degv in ydeg(neighbors, weight=weight):
+            yield degu, degv
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/asteroidal.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/asteroidal.py
new file mode 100644
index 0000000000000000000000000000000000000000..b308392a48626ade3b964aa544373e29d8a3a22b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/asteroidal.py
@@ -0,0 +1,164 @@
+"""
+Algorithms for asteroidal triples and asteroidal numbers in graphs.
+
+An asteroidal triple in a graph G is a set of three non-adjacent vertices
+u, v and w such that there exist a path between any two of them that avoids
+closed neighborhood of the third. More formally, v_j, v_k belongs to the same
+connected component of G - N[v_i], where N[v_i] denotes the closed neighborhood
+of v_i. A graph which does not contain any asteroidal triples is called
+an AT-free graph. The class of AT-free graphs is a graph class for which
+many NP-complete problems are solvable in polynomial time. Amongst them,
+independent set and coloring.
+"""
+
+import networkx as nx
+from networkx.utils import not_implemented_for
+
+__all__ = ["is_at_free", "find_asteroidal_triple"]
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable
+def find_asteroidal_triple(G):
+    r"""Find an asteroidal triple in the given graph.
+
+    An asteroidal triple is a triple of non-adjacent vertices such that
+    there exists a path between any two of them which avoids the closed
+    neighborhood of the third. It checks all independent triples of vertices
+    and whether they are an asteroidal triple or not. This is done with the
+    help of a data structure called a component structure.
+    A component structure encodes information about which vertices belongs to
+    the same connected component when the closed neighborhood of a given vertex
+    is removed from the graph. The algorithm used to check is the trivial
+    one, outlined in [1]_, which has a runtime of
+    :math:`O(|V||\overline{E} + |V||E|)`, where the second term is the
+    creation of the component structure.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+        The graph to check whether is AT-free or not
+
+    Returns
+    -------
+    list or None
+        An asteroidal triple is returned as a list of nodes. If no asteroidal
+        triple exists, i.e. the graph is AT-free, then None is returned.
+
+    Notes
+    -----
+    The component structure and the algorithm is described in [1]_. The current
+    implementation implements the trivial algorithm for simple graphs.
+
+    References
+    ----------
+    .. [1] Ekkehard Köhler,
+       "Recognizing Graphs without asteroidal triples",
+       Journal of Discrete Algorithms 2, pages 439-452, 2004.
+       https://www.sciencedirect.com/science/article/pii/S157086670400019X
+    """
+    V = set(G.nodes)
+
+    if len(V) < 6:
+        # An asteroidal triple cannot exist in a graph with 5 or less vertices.
+        return None
+
+    component_structure = create_component_structure(G)
+
+    for u, v in nx.non_edges(G):
+        u_neighborhood = set(G[u]).union([u])
+        v_neighborhood = set(G[v]).union([v])
+        union_of_neighborhoods = u_neighborhood.union(v_neighborhood)
+        for w in V - union_of_neighborhoods:
+            # Check for each pair of vertices whether they belong to the
+            # same connected component when the closed neighborhood of the
+            # third is removed.
+            if (
+                component_structure[u][v] == component_structure[u][w]
+                and component_structure[v][u] == component_structure[v][w]
+                and component_structure[w][u] == component_structure[w][v]
+            ):
+                return [u, v, w]
+    return None
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable
+def is_at_free(G):
+    """Check if a graph is AT-free.
+
+    The method uses the `find_asteroidal_triple` method to recognize
+    an AT-free graph. If no asteroidal triple is found the graph is
+    AT-free and True is returned. If at least one asteroidal triple is
+    found the graph is not AT-free and False is returned.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+        The graph to check whether is AT-free or not.
+
+    Returns
+    -------
+    bool
+        True if G is AT-free and False otherwise.
+
+    Examples
+    --------
+    >>> G = nx.Graph([(0, 1), (0, 2), (1, 2), (1, 3), (1, 4), (4, 5)])
+    >>> nx.is_at_free(G)
+    True
+
+    >>> G = nx.cycle_graph(6)
+    >>> nx.is_at_free(G)
+    False
+    """
+    return find_asteroidal_triple(G) is None
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable
+def create_component_structure(G):
+    r"""Create component structure for G.
+
+    A *component structure* is an `nxn` array, denoted `c`, where `n` is
+    the number of vertices,  where each row and column corresponds to a vertex.
+
+    .. math::
+        c_{uv} = \begin{cases} 0, if v \in N[u] \\
+            k, if v \in component k of G \setminus N[u] \end{cases}
+
+    Where `k` is an arbitrary label for each component. The structure is used
+    to simplify the detection of asteroidal triples.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+        Undirected, simple graph.
+
+    Returns
+    -------
+    component_structure : dictionary
+        A dictionary of dictionaries, keyed by pairs of vertices.
+
+    """
+    V = set(G.nodes)
+    component_structure = {}
+    for v in V:
+        label = 0
+        closed_neighborhood = set(G[v]).union({v})
+        row_dict = {}
+        for u in closed_neighborhood:
+            row_dict[u] = 0
+
+        G_reduced = G.subgraph(set(G.nodes) - closed_neighborhood)
+        for cc in nx.connected_components(G_reduced):
+            label += 1
+            for u in cc:
+                row_dict[u] = label
+
+        component_structure[v] = row_dict
+
+    return component_structure
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/boundary.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/boundary.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba05d803037d8812bfff83df5382e8ea942711b2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/boundary.py
@@ -0,0 +1,168 @@
+"""Routines to find the boundary of a set of nodes.
+
+An edge boundary is a set of edges, each of which has exactly one
+endpoint in a given set of nodes (or, in the case of directed graphs,
+the set of edges whose source node is in the set).
+
+A node boundary of a set *S* of nodes is the set of (out-)neighbors of
+nodes in *S* that are outside *S*.
+
+"""
+
+from itertools import chain
+
+import networkx as nx
+
+__all__ = ["edge_boundary", "node_boundary"]
+
+
+@nx._dispatchable(edge_attrs={"data": "default"}, preserve_edge_attrs="data")
+def edge_boundary(G, nbunch1, nbunch2=None, data=False, keys=False, default=None):
+    """Returns the edge boundary of `nbunch1`.
+
+    The *edge boundary* of a set *S* with respect to a set *T* is the
+    set of edges (*u*, *v*) such that *u* is in *S* and *v* is in *T*.
+    If *T* is not specified, it is assumed to be the set of all nodes
+    not in *S*.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    nbunch1 : iterable
+        Iterable of nodes in the graph representing the set of nodes
+        whose edge boundary will be returned. (This is the set *S* from
+        the definition above.)
+
+    nbunch2 : iterable
+        Iterable of nodes representing the target (or "exterior") set of
+        nodes. (This is the set *T* from the definition above.) If not
+        specified, this is assumed to be the set of all nodes in `G`
+        not in `nbunch1`.
+
+    keys : bool
+        This parameter has the same meaning as in
+        :meth:`MultiGraph.edges`.
+
+    data : bool or object
+        This parameter has the same meaning as in
+        :meth:`MultiGraph.edges`.
+
+    default : object
+        This parameter has the same meaning as in
+        :meth:`MultiGraph.edges`.
+
+    Returns
+    -------
+    iterator
+        An iterator over the edges in the boundary of `nbunch1` with
+        respect to `nbunch2`. If `keys`, `data`, or `default`
+        are specified and `G` is a multigraph, then edges are returned
+        with keys and/or data, as in :meth:`MultiGraph.edges`.
+
+    Examples
+    --------
+    >>> G = nx.wheel_graph(6)
+
+    When nbunch2=None:
+
+    >>> list(nx.edge_boundary(G, (1, 3)))
+    [(1, 0), (1, 2), (1, 5), (3, 0), (3, 2), (3, 4)]
+
+    When nbunch2 is given:
+
+    >>> list(nx.edge_boundary(G, (1, 3), (2, 0)))
+    [(1, 0), (1, 2), (3, 0), (3, 2)]
+
+    Notes
+    -----
+    Any element of `nbunch` that is not in the graph `G` will be
+    ignored.
+
+    `nbunch1` and `nbunch2` are usually meant to be disjoint, but in
+    the interest of speed and generality, that is not required here.
+
+    """
+    nset1 = {n for n in nbunch1 if n in G}
+    # Here we create an iterator over edges incident to nodes in the set
+    # `nset1`. The `Graph.edges()` method does not provide a guarantee
+    # on the orientation of the edges, so our algorithm below must
+    # handle the case in which exactly one orientation, either (u, v) or
+    # (v, u), appears in this iterable.
+    if G.is_multigraph():
+        edges = G.edges(nset1, data=data, keys=keys, default=default)
+    else:
+        edges = G.edges(nset1, data=data, default=default)
+    # If `nbunch2` is not provided, then it is assumed to be the set
+    # complement of `nbunch1`. For the sake of efficiency, this is
+    # implemented by using the `not in` operator, instead of by creating
+    # an additional set and using the `in` operator.
+    if nbunch2 is None:
+        return (e for e in edges if (e[0] in nset1) ^ (e[1] in nset1))
+    nset2 = set(nbunch2)
+    return (
+        e
+        for e in edges
+        if (e[0] in nset1 and e[1] in nset2) or (e[1] in nset1 and e[0] in nset2)
+    )
+
+
+@nx._dispatchable
+def node_boundary(G, nbunch1, nbunch2=None):
+    """Returns the node boundary of `nbunch1`.
+
+    The *node boundary* of a set *S* with respect to a set *T* is the
+    set of nodes *v* in *T* such that for some *u* in *S*, there is an
+    edge joining *u* to *v*. If *T* is not specified, it is assumed to
+    be the set of all nodes not in *S*.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    nbunch1 : iterable
+        Iterable of nodes in the graph representing the set of nodes
+        whose node boundary will be returned. (This is the set *S* from
+        the definition above.)
+
+    nbunch2 : iterable
+        Iterable of nodes representing the target (or "exterior") set of
+        nodes. (This is the set *T* from the definition above.) If not
+        specified, this is assumed to be the set of all nodes in `G`
+        not in `nbunch1`.
+
+    Returns
+    -------
+    set
+        The node boundary of `nbunch1` with respect to `nbunch2`.
+
+    Examples
+    --------
+    >>> G = nx.wheel_graph(6)
+
+    When nbunch2=None:
+
+    >>> list(nx.node_boundary(G, (3, 4)))
+    [0, 2, 5]
+
+    When nbunch2 is given:
+
+    >>> list(nx.node_boundary(G, (3, 4), (0, 1, 5)))
+    [0, 5]
+
+    Notes
+    -----
+    Any element of `nbunch` that is not in the graph `G` will be
+    ignored.
+
+    `nbunch1` and `nbunch2` are usually meant to be disjoint, but in
+    the interest of speed and generality, that is not required here.
+
+    """
+    nset1 = {n for n in nbunch1 if n in G}
+    bdy = set(chain.from_iterable(G[v] for v in nset1)) - nset1
+    # If `nbunch2` is not specified, it is assumed to be the set
+    # complement of `nbunch1`.
+    if nbunch2 is not None:
+        bdy &= set(nbunch2)
+    return bdy
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/bridges.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/bridges.py
new file mode 100644
index 0000000000000000000000000000000000000000..eaa6fd3bd7ef881abf93682315b76dc3b11e40ce
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/bridges.py
@@ -0,0 +1,205 @@
+"""Bridge-finding algorithms."""
+
+from itertools import chain
+
+import networkx as nx
+from networkx.utils import not_implemented_for
+
+__all__ = ["bridges", "has_bridges", "local_bridges"]
+
+
+@not_implemented_for("directed")
+@nx._dispatchable
+def bridges(G, root=None):
+    """Generate all bridges in a graph.
+
+    A *bridge* in a graph is an edge whose removal causes the number of
+    connected components of the graph to increase.  Equivalently, a bridge is an
+    edge that does not belong to any cycle. Bridges are also known as cut-edges,
+    isthmuses, or cut arcs.
+
+    Parameters
+    ----------
+    G : undirected graph
+
+    root : node (optional)
+       A node in the graph `G`. If specified, only the bridges in the
+       connected component containing this node will be returned.
+
+    Yields
+    ------
+    e : edge
+       An edge in the graph whose removal disconnects the graph (or
+       causes the number of connected components to increase).
+
+    Raises
+    ------
+    NodeNotFound
+       If `root` is not in the graph `G`.
+
+    NetworkXNotImplemented
+        If `G` is a directed graph.
+
+    Examples
+    --------
+    The barbell graph with parameter zero has a single bridge:
+
+    >>> G = nx.barbell_graph(10, 0)
+    >>> list(nx.bridges(G))
+    [(9, 10)]
+
+    Notes
+    -----
+    This is an implementation of the algorithm described in [1]_.  An edge is a
+    bridge if and only if it is not contained in any chain. Chains are found
+    using the :func:`networkx.chain_decomposition` function.
+
+    The algorithm described in [1]_ requires a simple graph. If the provided
+    graph is a multigraph, we convert it to a simple graph and verify that any
+    bridges discovered by the chain decomposition algorithm are not multi-edges.
+
+    Ignoring polylogarithmic factors, the worst-case time complexity is the
+    same as the :func:`networkx.chain_decomposition` function,
+    $O(m + n)$, where $n$ is the number of nodes in the graph and $m$ is
+    the number of edges.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Bridge_%28graph_theory%29#Bridge-Finding_with_Chain_Decompositions
+    """
+    multigraph = G.is_multigraph()
+    H = nx.Graph(G) if multigraph else G
+    chains = nx.chain_decomposition(H, root=root)
+    chain_edges = set(chain.from_iterable(chains))
+    if root is not None:
+        H = H.subgraph(nx.node_connected_component(H, root)).copy()
+    for u, v in H.edges():
+        if (u, v) not in chain_edges and (v, u) not in chain_edges:
+            if multigraph and len(G[u][v]) > 1:
+                continue
+            yield u, v
+
+
+@not_implemented_for("directed")
+@nx._dispatchable
+def has_bridges(G, root=None):
+    """Decide whether a graph has any bridges.
+
+    A *bridge* in a graph is an edge whose removal causes the number of
+    connected components of the graph to increase.
+
+    Parameters
+    ----------
+    G : undirected graph
+
+    root : node (optional)
+       A node in the graph `G`. If specified, only the bridges in the
+       connected component containing this node will be considered.
+
+    Returns
+    -------
+    bool
+       Whether the graph (or the connected component containing `root`)
+       has any bridges.
+
+    Raises
+    ------
+    NodeNotFound
+       If `root` is not in the graph `G`.
+
+    NetworkXNotImplemented
+        If `G` is a directed graph.
+
+    Examples
+    --------
+    The barbell graph with parameter zero has a single bridge::
+
+        >>> G = nx.barbell_graph(10, 0)
+        >>> nx.has_bridges(G)
+        True
+
+    On the other hand, the cycle graph has no bridges::
+
+        >>> G = nx.cycle_graph(5)
+        >>> nx.has_bridges(G)
+        False
+
+    Notes
+    -----
+    This implementation uses the :func:`networkx.bridges` function, so
+    it shares its worst-case time complexity, $O(m + n)$, ignoring
+    polylogarithmic factors, where $n$ is the number of nodes in the
+    graph and $m$ is the number of edges.
+
+    """
+    try:
+        next(bridges(G, root=root))
+    except StopIteration:
+        return False
+    else:
+        return True
+
+
+@not_implemented_for("multigraph")
+@not_implemented_for("directed")
+@nx._dispatchable(edge_attrs="weight")
+def local_bridges(G, with_span=True, weight=None):
+    """Iterate over local bridges of `G` optionally computing the span
+
+    A *local bridge* is an edge whose endpoints have no common neighbors.
+    That is, the edge is not part of a triangle in the graph.
+
+    The *span* of a *local bridge* is the shortest path length between
+    the endpoints if the local bridge is removed.
+
+    Parameters
+    ----------
+    G : undirected graph
+
+    with_span : bool
+        If True, yield a 3-tuple `(u, v, span)`
+
+    weight : function, string or None (default: None)
+        If function, used to compute edge weights for the span.
+        If string, the edge data attribute used in calculating span.
+        If None, all edges have weight 1.
+
+    Yields
+    ------
+    e : edge
+        The local bridges as an edge 2-tuple of nodes `(u, v)` or
+        as a 3-tuple `(u, v, span)` when `with_span is True`.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is a directed graph or multigraph.
+
+    Examples
+    --------
+    A cycle graph has every edge a local bridge with span N-1.
+
+       >>> G = nx.cycle_graph(9)
+       >>> (0, 8, 8) in set(nx.local_bridges(G))
+       True
+    """
+    if with_span is not True:
+        for u, v in G.edges:
+            if not (set(G[u]) & set(G[v])):
+                yield u, v
+    else:
+        wt = nx.weighted._weight_function(G, weight)
+        for u, v in G.edges:
+            if not (set(G[u]) & set(G[v])):
+                enodes = {u, v}
+
+                def hide_edge(n, nbr, d):
+                    if n not in enodes or nbr not in enodes:
+                        return wt(n, nbr, d)
+                    return None
+
+                try:
+                    span = nx.shortest_path_length(G, u, v, weight=hide_edge)
+                    yield u, v, span
+                except nx.NetworkXNoPath:
+                    yield u, v, float("inf")
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/broadcasting.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/broadcasting.py
new file mode 100644
index 0000000000000000000000000000000000000000..c2e2718a5a3dc549a09dc72469462f80f8c0af77
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/broadcasting.py
@@ -0,0 +1,164 @@
+"""Routines to calculate the broadcast time of certain graphs.
+
+Broadcasting is an information dissemination problem in which a node in a graph,
+called the originator, must distribute a message to all other nodes by placing
+a series of calls along the edges of the graph. Once informed, other nodes aid
+the originator in distributing the message.
+
+The broadcasting must be completed as quickly as possible subject to the
+following constraints:
+- Each call requires one unit of time.
+- A node can only participate in one call per unit of time.
+- Each call only involves two adjacent nodes: a sender and a receiver.
+"""
+
+import networkx as nx
+from networkx.utils import not_implemented_for
+
+__all__ = [
+    "tree_broadcast_center",
+    "tree_broadcast_time",
+]
+
+
+def _get_max_broadcast_value(G, U, v, values):
+    adj = sorted(set(G.neighbors(v)) & U, key=values.get, reverse=True)
+    return max(values[u] + i for i, u in enumerate(adj, start=1))
+
+
+def _get_broadcast_centers(G, v, values, target):
+    adj = sorted(G.neighbors(v), key=values.get, reverse=True)
+    j = next(i for i, u in enumerate(adj, start=1) if values[u] + i == target)
+    return set([v] + adj[:j])
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable
+def tree_broadcast_center(G):
+    """Return the broadcast center of a tree.
+
+    The broadcast center of a graph `G` denotes the set of nodes having
+    minimum broadcast time [1]_. This function implements a linear algorithm
+    for determining the broadcast center of a tree with ``n`` nodes. As a
+    by-product, it also determines the broadcast time from the broadcast center.
+
+    Parameters
+    ----------
+    G : Graph
+        The graph should be an undirected tree.
+
+    Returns
+    -------
+    b_T, b_C : (int, set) tuple
+        Minimum broadcast time of the broadcast center in `G`, set of nodes
+        in the broadcast center.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is directed or is a multigraph.
+
+    NotATree
+        If `G` is not a tree.
+
+    References
+    ----------
+    .. [1] Slater, P.J., Cockayne, E.J., Hedetniemi, S.T,
+       Information dissemination in trees. SIAM J.Comput. 10(4), 692–701 (1981)
+    """
+    # Assert that the graph G is a tree
+    if not nx.is_tree(G):
+        raise nx.NotATree("G is not a tree")
+    # step 0
+    if (n := len(G)) < 3:
+        return n - 1, set(G)
+
+    # step 1
+    U = {node for node, deg in G.degree if deg == 1}
+    values = {n: 0 for n in U}
+    T = G.copy()
+    T.remove_nodes_from(U)
+
+    # step 2
+    W = {node for node, deg in T.degree if deg == 1}
+    values.update((w, G.degree[w] - 1) for w in W)
+
+    # step 3
+    while len(T) >= 2:
+        # step 4
+        w = min(W, key=values.get)
+        v = next(T.neighbors(w))
+
+        # step 5
+        U.add(w)
+        W.remove(w)
+        T.remove_node(w)
+
+        # step 6
+        if T.degree(v) == 1:
+            # update t(v)
+            values.update({v: _get_max_broadcast_value(G, U, v, values)})
+            W.add(v)
+
+    # step 7
+    v = nx.utils.arbitrary_element(T)
+    b_T = _get_max_broadcast_value(G, U, v, values)
+    return b_T, _get_broadcast_centers(G, v, values, b_T)
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable
+def tree_broadcast_time(G, node=None):
+    """Return the minimum broadcast time of a (node in a) tree.
+
+    The minimum broadcast time of a node is defined as the minimum amount
+    of time required to complete broadcasting starting from that node.
+    The broadcast time of a graph is the maximum over
+    all nodes of the minimum broadcast time from that node [1]_.
+    This function returns the minimum broadcast time of `node`.
+    If `node` is `None`, the broadcast time for the graph is returned.
+
+    Parameters
+    ----------
+    G : Graph
+        The graph should be an undirected tree.
+
+    node : node, optional (default=None)
+        Starting node for the broadcasting. If `None`, the algorithm
+        returns the broadcast time of the graph instead.
+
+    Returns
+    -------
+    int
+        Minimum broadcast time of `node` in `G`, or broadcast time of `G`
+        if no node is provided.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is directed or is a multigraph.
+
+    NodeNotFound
+        If `node` is not a node in `G`.
+
+    NotATree
+        If `G` is not a tree.
+
+    References
+    ----------
+    .. [1] Harutyunyan, H. A. and Li, Z.
+        "A Simple Construction of Broadcast Graphs."
+        In Computing and Combinatorics. COCOON 2019
+        (Ed. D. Z. Du and C. Tian.) Springer, pp. 240-253, 2019.
+    """
+    if node is not None and node not in G:
+        err = f"node {node} not in G"
+        raise nx.NodeNotFound(err)
+    b_T, b_C = tree_broadcast_center(G)
+    if node is None:
+        return b_T + sum(1 for _ in nx.bfs_layers(G, b_C)) - 1
+    return b_T + next(
+        d for d, layer in enumerate(nx.bfs_layers(G, b_C)) if node in layer
+    )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/chains.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/chains.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae342d9c8669acd832a3bdb4fe8eecf3e300464f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/chains.py
@@ -0,0 +1,172 @@
+"""Functions for finding chains in a graph."""
+
+import networkx as nx
+from networkx.utils import not_implemented_for
+
+__all__ = ["chain_decomposition"]
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable
+def chain_decomposition(G, root=None):
+    """Returns the chain decomposition of a graph.
+
+    The *chain decomposition* of a graph with respect a depth-first
+    search tree is a set of cycles or paths derived from the set of
+    fundamental cycles of the tree in the following manner. Consider
+    each fundamental cycle with respect to the given tree, represented
+    as a list of edges beginning with the nontree edge oriented away
+    from the root of the tree. For each fundamental cycle, if it
+    overlaps with any previous fundamental cycle, just take the initial
+    non-overlapping segment, which is a path instead of a cycle. Each
+    cycle or path is called a *chain*. For more information, see [1]_.
+
+    Parameters
+    ----------
+    G : undirected graph
+
+    root : node (optional)
+       A node in the graph `G`. If specified, only the chain
+       decomposition for the connected component containing this node
+       will be returned. This node indicates the root of the depth-first
+       search tree.
+
+    Yields
+    ------
+    chain : list
+       A list of edges representing a chain. There is no guarantee on
+       the orientation of the edges in each chain (for example, if a
+       chain includes the edge joining nodes 1 and 2, the chain may
+       include either (1, 2) or (2, 1)).
+
+    Raises
+    ------
+    NodeNotFound
+       If `root` is not in the graph `G`.
+
+    Examples
+    --------
+    >>> G = nx.Graph([(0, 1), (1, 4), (3, 4), (3, 5), (4, 5)])
+    >>> list(nx.chain_decomposition(G))
+    [[(4, 5), (5, 3), (3, 4)]]
+
+    Notes
+    -----
+    The worst-case running time of this implementation is linear in the
+    number of nodes and number of edges [1]_.
+
+    References
+    ----------
+    .. [1] Jens M. Schmidt (2013). "A simple test on 2-vertex-
+       and 2-edge-connectivity." *Information Processing Letters*,
+       113, 241–244. Elsevier. 
+
+    """
+
+    def _dfs_cycle_forest(G, root=None):
+        """Builds a directed graph composed of cycles from the given graph.
+
+        `G` is an undirected simple graph. `root` is a node in the graph
+        from which the depth-first search is started.
+
+        This function returns both the depth-first search cycle graph
+        (as a :class:`~networkx.DiGraph`) and the list of nodes in
+        depth-first preorder. The depth-first search cycle graph is a
+        directed graph whose edges are the edges of `G` oriented toward
+        the root if the edge is a tree edge and away from the root if
+        the edge is a non-tree edge. If `root` is not specified, this
+        performs a depth-first search on each connected component of `G`
+        and returns a directed forest instead.
+
+        If `root` is not in the graph, this raises :exc:`KeyError`.
+
+        """
+        # Create a directed graph from the depth-first search tree with
+        # root node `root` in which tree edges are directed toward the
+        # root and nontree edges are directed away from the root. For
+        # each node with an incident nontree edge, this creates a
+        # directed cycle starting with the nontree edge and returning to
+        # that node.
+        #
+        # The `parent` node attribute stores the parent of each node in
+        # the DFS tree. The `nontree` edge attribute indicates whether
+        # the edge is a tree edge or a nontree edge.
+        #
+        # We also store the order of the nodes found in the depth-first
+        # search in the `nodes` list.
+        H = nx.DiGraph()
+        nodes = []
+        for u, v, d in nx.dfs_labeled_edges(G, source=root):
+            if d == "forward":
+                # `dfs_labeled_edges()` yields (root, root, 'forward')
+                # if it is beginning the search on a new connected
+                # component.
+                if u == v:
+                    H.add_node(v, parent=None)
+                    nodes.append(v)
+                else:
+                    H.add_node(v, parent=u)
+                    H.add_edge(v, u, nontree=False)
+                    nodes.append(v)
+            # `dfs_labeled_edges` considers nontree edges in both
+            # orientations, so we need to not add the edge if it its
+            # other orientation has been added.
+            elif d == "nontree" and v not in H[u]:
+                H.add_edge(v, u, nontree=True)
+            else:
+                # Do nothing on 'reverse' edges; we only care about
+                # forward and nontree edges.
+                pass
+        return H, nodes
+
+    def _build_chain(G, u, v, visited):
+        """Generate the chain starting from the given nontree edge.
+
+        `G` is a DFS cycle graph as constructed by
+        :func:`_dfs_cycle_graph`. The edge (`u`, `v`) is a nontree edge
+        that begins a chain. `visited` is a set representing the nodes
+        in `G` that have already been visited.
+
+        This function yields the edges in an initial segment of the
+        fundamental cycle of `G` starting with the nontree edge (`u`,
+        `v`) that includes all the edges up until the first node that
+        appears in `visited`. The tree edges are given by the 'parent'
+        node attribute. The `visited` set is updated to add each node in
+        an edge yielded by this function.
+
+        """
+        while v not in visited:
+            yield u, v
+            visited.add(v)
+            u, v = v, G.nodes[v]["parent"]
+        yield u, v
+
+    # Check if the root is in the graph G. If not, raise NodeNotFound
+    if root is not None and root not in G:
+        raise nx.NodeNotFound(f"Root node {root} is not in graph")
+
+    # Create a directed version of H that has the DFS edges directed
+    # toward the root and the nontree edges directed away from the root
+    # (in each connected component).
+    H, nodes = _dfs_cycle_forest(G, root)
+
+    # Visit the nodes again in DFS order. For each node, and for each
+    # nontree edge leaving that node, compute the fundamental cycle for
+    # that nontree edge starting with that edge. If the fundamental
+    # cycle overlaps with any visited nodes, just take the prefix of the
+    # cycle up to the point of visited nodes.
+    #
+    # We repeat this process for each connected component (implicitly,
+    # since `nodes` already has a list of the nodes grouped by connected
+    # component).
+    visited = set()
+    for u in nodes:
+        visited.add(u)
+        # For each nontree edge going out of node u...
+        edges = ((u, v) for u, v, d in H.out_edges(u, data="nontree") if d)
+        for u, v in edges:
+            # Create the cycle or cycle prefix starting with the
+            # nontree edge.
+            chain = list(_build_chain(H, u, v, visited))
+            yield chain
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/chordal.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/chordal.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab71c243f314d02b74eac9a7b0b4e601ed7e484d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/chordal.py
@@ -0,0 +1,443 @@
+"""
+Algorithms for chordal graphs.
+
+A graph is chordal if every cycle of length at least 4 has a chord
+(an edge joining two nodes not adjacent in the cycle).
+https://en.wikipedia.org/wiki/Chordal_graph
+"""
+
+import sys
+
+import networkx as nx
+from networkx.algorithms.components import connected_components
+from networkx.utils import arbitrary_element, not_implemented_for
+
+__all__ = [
+    "is_chordal",
+    "find_induced_nodes",
+    "chordal_graph_cliques",
+    "chordal_graph_treewidth",
+    "NetworkXTreewidthBoundExceeded",
+    "complete_to_chordal_graph",
+]
+
+
+class NetworkXTreewidthBoundExceeded(nx.NetworkXException):
+    """Exception raised when a treewidth bound has been provided and it has
+    been exceeded"""
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable
+def is_chordal(G):
+    """Checks whether G is a chordal graph.
+
+    A graph is chordal if every cycle of length at least 4 has a chord
+    (an edge joining two nodes not adjacent in the cycle).
+
+    Parameters
+    ----------
+    G : graph
+      A NetworkX graph.
+
+    Returns
+    -------
+    chordal : bool
+      True if G is a chordal graph and False otherwise.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        The algorithm does not support DiGraph, MultiGraph and MultiDiGraph.
+
+    Examples
+    --------
+    >>> e = [
+    ...     (1, 2),
+    ...     (1, 3),
+    ...     (2, 3),
+    ...     (2, 4),
+    ...     (3, 4),
+    ...     (3, 5),
+    ...     (3, 6),
+    ...     (4, 5),
+    ...     (4, 6),
+    ...     (5, 6),
+    ... ]
+    >>> G = nx.Graph(e)
+    >>> nx.is_chordal(G)
+    True
+
+    Notes
+    -----
+    The routine tries to go through every node following maximum cardinality
+    search. It returns False when it finds that the separator for any node
+    is not a clique.  Based on the algorithms in [1]_.
+
+    Self loops are ignored.
+
+    References
+    ----------
+    .. [1] R. E. Tarjan and M. Yannakakis, Simple linear-time algorithms
+       to test chordality of graphs, test acyclicity of hypergraphs, and
+       selectively reduce acyclic hypergraphs, SIAM J. Comput., 13 (1984),
+       pp. 566–579.
+    """
+    if len(G.nodes) <= 3:
+        return True
+    return len(_find_chordality_breaker(G)) == 0
+
+
+@nx._dispatchable
+def find_induced_nodes(G, s, t, treewidth_bound=sys.maxsize):
+    """Returns the set of induced nodes in the path from s to t.
+
+    Parameters
+    ----------
+    G : graph
+      A chordal NetworkX graph
+    s : node
+        Source node to look for induced nodes
+    t : node
+        Destination node to look for induced nodes
+    treewidth_bound: float
+        Maximum treewidth acceptable for the graph H. The search
+        for induced nodes will end as soon as the treewidth_bound is exceeded.
+
+    Returns
+    -------
+    induced_nodes : Set of nodes
+        The set of induced nodes in the path from s to t in G
+
+    Raises
+    ------
+    NetworkXError
+        The algorithm does not support DiGraph, MultiGraph and MultiDiGraph.
+        If the input graph is an instance of one of these classes, a
+        :exc:`NetworkXError` is raised.
+        The algorithm can only be applied to chordal graphs. If the input
+        graph is found to be non-chordal, a :exc:`NetworkXError` is raised.
+
+    Examples
+    --------
+    >>> G = nx.Graph()
+    >>> G = nx.generators.classic.path_graph(10)
+    >>> induced_nodes = nx.find_induced_nodes(G, 1, 9, 2)
+    >>> sorted(induced_nodes)
+    [1, 2, 3, 4, 5, 6, 7, 8, 9]
+
+    Notes
+    -----
+    G must be a chordal graph and (s,t) an edge that is not in G.
+
+    If a treewidth_bound is provided, the search for induced nodes will end
+    as soon as the treewidth_bound is exceeded.
+
+    The algorithm is inspired by Algorithm 4 in [1]_.
+    A formal definition of induced node can also be found on that reference.
+
+    Self Loops are ignored
+
+    References
+    ----------
+    .. [1] Learning Bounded Treewidth Bayesian Networks.
+       Gal Elidan, Stephen Gould; JMLR, 9(Dec):2699--2731, 2008.
+       http://jmlr.csail.mit.edu/papers/volume9/elidan08a/elidan08a.pdf
+    """
+    if not is_chordal(G):
+        raise nx.NetworkXError("Input graph is not chordal.")
+
+    H = nx.Graph(G)
+    H.add_edge(s, t)
+    induced_nodes = set()
+    triplet = _find_chordality_breaker(H, s, treewidth_bound)
+    while triplet:
+        (u, v, w) = triplet
+        induced_nodes.update(triplet)
+        for n in triplet:
+            if n != s:
+                H.add_edge(s, n)
+        triplet = _find_chordality_breaker(H, s, treewidth_bound)
+    if induced_nodes:
+        # Add t and the second node in the induced path from s to t.
+        induced_nodes.add(t)
+        for u in G[s]:
+            if len(induced_nodes & set(G[u])) == 2:
+                induced_nodes.add(u)
+                break
+    return induced_nodes
+
+
+@nx._dispatchable
+def chordal_graph_cliques(G):
+    """Returns all maximal cliques of a chordal graph.
+
+    The algorithm breaks the graph in connected components and performs a
+    maximum cardinality search in each component to get the cliques.
+
+    Parameters
+    ----------
+    G : graph
+      A NetworkX graph
+
+    Yields
+    ------
+    frozenset of nodes
+        Maximal cliques, each of which is a frozenset of
+        nodes in `G`. The order of cliques is arbitrary.
+
+    Raises
+    ------
+    NetworkXError
+        The algorithm does not support DiGraph, MultiGraph and MultiDiGraph.
+        The algorithm can only be applied to chordal graphs. If the input
+        graph is found to be non-chordal, a :exc:`NetworkXError` is raised.
+
+    Examples
+    --------
+    >>> e = [
+    ...     (1, 2),
+    ...     (1, 3),
+    ...     (2, 3),
+    ...     (2, 4),
+    ...     (3, 4),
+    ...     (3, 5),
+    ...     (3, 6),
+    ...     (4, 5),
+    ...     (4, 6),
+    ...     (5, 6),
+    ...     (7, 8),
+    ... ]
+    >>> G = nx.Graph(e)
+    >>> G.add_node(9)
+    >>> cliques = [c for c in chordal_graph_cliques(G)]
+    >>> cliques[0]
+    frozenset({1, 2, 3})
+    """
+    for C in (G.subgraph(c).copy() for c in connected_components(G)):
+        if C.number_of_nodes() == 1:
+            if nx.number_of_selfloops(C) > 0:
+                raise nx.NetworkXError("Input graph is not chordal.")
+            yield frozenset(C.nodes())
+        else:
+            unnumbered = set(C.nodes())
+            v = arbitrary_element(C)
+            unnumbered.remove(v)
+            numbered = {v}
+            clique_wanna_be = {v}
+            while unnumbered:
+                v = _max_cardinality_node(C, unnumbered, numbered)
+                unnumbered.remove(v)
+                numbered.add(v)
+                new_clique_wanna_be = set(C.neighbors(v)) & numbered
+                sg = C.subgraph(clique_wanna_be)
+                if _is_complete_graph(sg):
+                    new_clique_wanna_be.add(v)
+                    if not new_clique_wanna_be >= clique_wanna_be:
+                        yield frozenset(clique_wanna_be)
+                    clique_wanna_be = new_clique_wanna_be
+                else:
+                    raise nx.NetworkXError("Input graph is not chordal.")
+            yield frozenset(clique_wanna_be)
+
+
+@nx._dispatchable
+def chordal_graph_treewidth(G):
+    """Returns the treewidth of the chordal graph G.
+
+    Parameters
+    ----------
+    G : graph
+      A NetworkX graph
+
+    Returns
+    -------
+    treewidth : int
+        The size of the largest clique in the graph minus one.
+
+    Raises
+    ------
+    NetworkXError
+        The algorithm does not support DiGraph, MultiGraph and MultiDiGraph.
+        The algorithm can only be applied to chordal graphs. If the input
+        graph is found to be non-chordal, a :exc:`NetworkXError` is raised.
+
+    Examples
+    --------
+    >>> e = [
+    ...     (1, 2),
+    ...     (1, 3),
+    ...     (2, 3),
+    ...     (2, 4),
+    ...     (3, 4),
+    ...     (3, 5),
+    ...     (3, 6),
+    ...     (4, 5),
+    ...     (4, 6),
+    ...     (5, 6),
+    ...     (7, 8),
+    ... ]
+    >>> G = nx.Graph(e)
+    >>> G.add_node(9)
+    >>> nx.chordal_graph_treewidth(G)
+    3
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Tree_decomposition#Treewidth
+    """
+    if not is_chordal(G):
+        raise nx.NetworkXError("Input graph is not chordal.")
+
+    max_clique = -1
+    for clique in nx.chordal_graph_cliques(G):
+        max_clique = max(max_clique, len(clique))
+    return max_clique - 1
+
+
+def _is_complete_graph(G):
+    """Returns True if G is a complete graph."""
+    if nx.number_of_selfloops(G) > 0:
+        raise nx.NetworkXError("Self loop found in _is_complete_graph()")
+    n = G.number_of_nodes()
+    if n < 2:
+        return True
+    e = G.number_of_edges()
+    max_edges = (n * (n - 1)) / 2
+    return e == max_edges
+
+
+def _find_missing_edge(G):
+    """Given a non-complete graph G, returns a missing edge."""
+    nodes = set(G)
+    for u in G:
+        missing = nodes - set(list(G[u].keys()) + [u])
+        if missing:
+            return (u, missing.pop())
+
+
+def _max_cardinality_node(G, choices, wanna_connect):
+    """Returns a the node in choices that has more connections in G
+    to nodes in wanna_connect.
+    """
+    max_number = -1
+    for x in choices:
+        number = len([y for y in G[x] if y in wanna_connect])
+        if number > max_number:
+            max_number = number
+            max_cardinality_node = x
+    return max_cardinality_node
+
+
+def _find_chordality_breaker(G, s=None, treewidth_bound=sys.maxsize):
+    """Given a graph G, starts a max cardinality search
+    (starting from s if s is given and from an arbitrary node otherwise)
+    trying to find a non-chordal cycle.
+
+    If it does find one, it returns (u,v,w) where u,v,w are the three
+    nodes that together with s are involved in the cycle.
+
+    It ignores any self loops.
+    """
+    if len(G) == 0:
+        raise nx.NetworkXPointlessConcept("Graph has no nodes.")
+    unnumbered = set(G)
+    if s is None:
+        s = arbitrary_element(G)
+    unnumbered.remove(s)
+    numbered = {s}
+    current_treewidth = -1
+    while unnumbered:  # and current_treewidth <= treewidth_bound:
+        v = _max_cardinality_node(G, unnumbered, numbered)
+        unnumbered.remove(v)
+        numbered.add(v)
+        clique_wanna_be = set(G[v]) & numbered
+        sg = G.subgraph(clique_wanna_be)
+        if _is_complete_graph(sg):
+            # The graph seems to be chordal by now. We update the treewidth
+            current_treewidth = max(current_treewidth, len(clique_wanna_be))
+            if current_treewidth > treewidth_bound:
+                raise nx.NetworkXTreewidthBoundExceeded(
+                    f"treewidth_bound exceeded: {current_treewidth}"
+                )
+        else:
+            # sg is not a clique,
+            # look for an edge that is not included in sg
+            (u, w) = _find_missing_edge(sg)
+            return (u, v, w)
+    return ()
+
+
+@not_implemented_for("directed")
+@nx._dispatchable(returns_graph=True)
+def complete_to_chordal_graph(G):
+    """Return a copy of G completed to a chordal graph
+
+    Adds edges to a copy of G to create a chordal graph. A graph G=(V,E) is
+    called chordal if for each cycle with length bigger than 3, there exist
+    two non-adjacent nodes connected by an edge (called a chord).
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        Undirected graph
+
+    Returns
+    -------
+    H : NetworkX graph
+        The chordal enhancement of G
+    alpha : Dictionary
+            The elimination ordering of nodes of G
+
+    Notes
+    -----
+    There are different approaches to calculate the chordal
+    enhancement of a graph. The algorithm used here is called
+    MCS-M and gives at least minimal (local) triangulation of graph. Note
+    that this triangulation is not necessarily a global minimum.
+
+    https://en.wikipedia.org/wiki/Chordal_graph
+
+    References
+    ----------
+    .. [1] Berry, Anne & Blair, Jean & Heggernes, Pinar & Peyton, Barry. (2004)
+           Maximum Cardinality Search for Computing Minimal Triangulations of
+           Graphs.  Algorithmica. 39. 287-298. 10.1007/s00453-004-1084-3.
+
+    Examples
+    --------
+    >>> from networkx.algorithms.chordal import complete_to_chordal_graph
+    >>> G = nx.wheel_graph(10)
+    >>> H, alpha = complete_to_chordal_graph(G)
+    """
+    H = G.copy()
+    alpha = {node: 0 for node in H}
+    if nx.is_chordal(H):
+        return H, alpha
+    chords = set()
+    weight = {node: 0 for node in H.nodes()}
+    unnumbered_nodes = list(H.nodes())
+    for i in range(len(H.nodes()), 0, -1):
+        # get the node in unnumbered_nodes with the maximum weight
+        z = max(unnumbered_nodes, key=lambda node: weight[node])
+        unnumbered_nodes.remove(z)
+        alpha[z] = i
+        update_nodes = []
+        for y in unnumbered_nodes:
+            if G.has_edge(y, z):
+                update_nodes.append(y)
+            else:
+                # y_weight will be bigger than node weights between y and z
+                y_weight = weight[y]
+                lower_nodes = [
+                    node for node in unnumbered_nodes if weight[node] < y_weight
+                ]
+                if nx.has_path(H.subgraph(lower_nodes + [z, y]), y, z):
+                    update_nodes.append(y)
+                    chords.add((z, y))
+        # during calculation of paths the weights should not be updated
+        for node in update_nodes:
+            weight[node] += 1
+    H.add_edges_from(chords)
+    return H, alpha
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/clique.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/clique.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a1aba4acf6947da9681433b13d293995188fe4d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/clique.py
@@ -0,0 +1,818 @@
+"""Functions for finding and manipulating cliques.
+
+Finding the largest clique in a graph is NP-complete problem, so most of
+these algorithms have an exponential running time; for more information,
+see the Wikipedia article on the clique problem [1]_.
+
+.. [1] clique problem:: https://en.wikipedia.org/wiki/Clique_problem
+
+"""
+
+from collections import Counter, defaultdict, deque
+from itertools import chain, combinations, islice
+
+import networkx as nx
+from networkx.utils import not_implemented_for
+
+__all__ = [
+    "find_cliques",
+    "find_cliques_recursive",
+    "make_max_clique_graph",
+    "make_clique_bipartite",
+    "node_clique_number",
+    "number_of_cliques",
+    "enumerate_all_cliques",
+    "max_weight_clique",
+]
+
+
+@not_implemented_for("directed")
+@nx._dispatchable
+def enumerate_all_cliques(G):
+    """Returns all cliques in an undirected graph.
+
+    This function returns an iterator over cliques, each of which is a
+    list of nodes. The iteration is ordered by cardinality of the
+    cliques: first all cliques of size one, then all cliques of size
+    two, etc.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        An undirected graph.
+
+    Returns
+    -------
+    iterator
+        An iterator over cliques, each of which is a list of nodes in
+        `G`. The cliques are ordered according to size.
+
+    Notes
+    -----
+    To obtain a list of all cliques, use
+    `list(enumerate_all_cliques(G))`. However, be aware that in the
+    worst-case, the length of this list can be exponential in the number
+    of nodes in the graph (for example, when the graph is the complete
+    graph). This function avoids storing all cliques in memory by only
+    keeping current candidate node lists in memory during its search.
+
+    The implementation is adapted from the algorithm by Zhang, et
+    al. (2005) [1]_ to output all cliques discovered.
+
+    This algorithm ignores self-loops and parallel edges, since cliques
+    are not conventionally defined with such edges.
+
+    References
+    ----------
+    .. [1] Yun Zhang, Abu-Khzam, F.N., Baldwin, N.E., Chesler, E.J.,
+           Langston, M.A., Samatova, N.F.,
+           "Genome-Scale Computational Approaches to Memory-Intensive
+           Applications in Systems Biology".
+           *Supercomputing*, 2005. Proceedings of the ACM/IEEE SC 2005
+           Conference, pp. 12, 12--18 Nov. 2005.
+           .
+
+    """
+    index = {}
+    nbrs = {}
+    for u in G:
+        index[u] = len(index)
+        # Neighbors of u that appear after u in the iteration order of G.
+        nbrs[u] = {v for v in G[u] if v not in index}
+
+    queue = deque(([u], sorted(nbrs[u], key=index.__getitem__)) for u in G)
+    # Loop invariants:
+    # 1. len(base) is nondecreasing.
+    # 2. (base + cnbrs) is sorted with respect to the iteration order of G.
+    # 3. cnbrs is a set of common neighbors of nodes in base.
+    while queue:
+        base, cnbrs = map(list, queue.popleft())
+        yield base
+        for i, u in enumerate(cnbrs):
+            # Use generators to reduce memory consumption.
+            queue.append(
+                (
+                    chain(base, [u]),
+                    filter(nbrs[u].__contains__, islice(cnbrs, i + 1, None)),
+                )
+            )
+
+
+@not_implemented_for("directed")
+@nx._dispatchable
+def find_cliques(G, nodes=None):
+    """Returns all maximal cliques in an undirected graph.
+
+    For each node *n*, a *maximal clique for n* is a largest complete
+    subgraph containing *n*. The largest maximal clique is sometimes
+    called the *maximum clique*.
+
+    This function returns an iterator over cliques, each of which is a
+    list of nodes. It is an iterative implementation, so should not
+    suffer from recursion depth issues.
+
+    This function accepts a list of `nodes` and only the maximal cliques
+    containing all of these `nodes` are returned. It can considerably speed up
+    the running time if some specific cliques are desired.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        An undirected graph.
+
+    nodes : list, optional (default=None)
+        If provided, only yield *maximal cliques* containing all nodes in `nodes`.
+        If `nodes` isn't a clique itself, a ValueError is raised.
+
+    Returns
+    -------
+    iterator
+        An iterator over maximal cliques, each of which is a list of
+        nodes in `G`. If `nodes` is provided, only the maximal cliques
+        containing all the nodes in `nodes` are returned. The order of
+        cliques is arbitrary.
+
+    Raises
+    ------
+    ValueError
+        If `nodes` is not a clique.
+
+    Examples
+    --------
+    >>> from pprint import pprint  # For nice dict formatting
+    >>> G = nx.karate_club_graph()
+    >>> sum(1 for c in nx.find_cliques(G))  # The number of maximal cliques in G
+    36
+    >>> max(nx.find_cliques(G), key=len)  # The largest maximal clique in G
+    [0, 1, 2, 3, 13]
+
+    The size of the largest maximal clique is known as the *clique number* of
+    the graph, which can be found directly with:
+
+    >>> max(len(c) for c in nx.find_cliques(G))
+    5
+
+    One can also compute the number of maximal cliques in `G` that contain a given
+    node. The following produces a dictionary keyed by node whose
+    values are the number of maximal cliques in `G` that contain the node:
+
+    >>> from collections import Counter
+    >>> from itertools import chain
+    >>> counts = Counter(chain.from_iterable(nx.find_cliques(G)))
+    >>> pprint(dict(counts))
+    {0: 13,
+     1: 6,
+     2: 7,
+     3: 3,
+     4: 2,
+     5: 3,
+     6: 3,
+     7: 1,
+     8: 3,
+     9: 2,
+     10: 2,
+     11: 1,
+     12: 1,
+     13: 2,
+     14: 1,
+     15: 1,
+     16: 1,
+     17: 1,
+     18: 1,
+     19: 2,
+     20: 1,
+     21: 1,
+     22: 1,
+     23: 3,
+     24: 2,
+     25: 2,
+     26: 1,
+     27: 3,
+     28: 2,
+     29: 2,
+     30: 2,
+     31: 4,
+     32: 9,
+     33: 14}
+
+    Or, similarly, the maximal cliques in `G` that contain a given node.
+    For example, the 4 maximal cliques that contain node 31:
+
+    >>> [c for c in nx.find_cliques(G) if 31 in c]
+    [[0, 31], [33, 32, 31], [33, 28, 31], [24, 25, 31]]
+
+    See Also
+    --------
+    find_cliques_recursive
+        A recursive version of the same algorithm.
+
+    Notes
+    -----
+    To obtain a list of all maximal cliques, use
+    `list(find_cliques(G))`. However, be aware that in the worst-case,
+    the length of this list can be exponential in the number of nodes in
+    the graph. This function avoids storing all cliques in memory by
+    only keeping current candidate node lists in memory during its search.
+
+    This implementation is based on the algorithm published by Bron and
+    Kerbosch (1973) [1]_, as adapted by Tomita, Tanaka and Takahashi
+    (2006) [2]_ and discussed in Cazals and Karande (2008) [3]_. It
+    essentially unrolls the recursion used in the references to avoid
+    issues of recursion stack depth (for a recursive implementation, see
+    :func:`find_cliques_recursive`).
+
+    This algorithm ignores self-loops and parallel edges, since cliques
+    are not conventionally defined with such edges.
+
+    References
+    ----------
+    .. [1] Bron, C. and Kerbosch, J.
+       "Algorithm 457: finding all cliques of an undirected graph".
+       *Communications of the ACM* 16, 9 (Sep. 1973), 575--577.
+       
+
+    .. [2] Etsuji Tomita, Akira Tanaka, Haruhisa Takahashi,
+       "The worst-case time complexity for generating all maximal
+       cliques and computational experiments",
+       *Theoretical Computer Science*, Volume 363, Issue 1,
+       Computing and Combinatorics,
+       10th Annual International Conference on
+       Computing and Combinatorics (COCOON 2004), 25 October 2006, Pages 28--42
+       
+
+    .. [3] F. Cazals, C. Karande,
+       "A note on the problem of reporting maximal cliques",
+       *Theoretical Computer Science*,
+       Volume 407, Issues 1--3, 6 November 2008, Pages 564--568,
+       
+
+    """
+    if len(G) == 0:
+        return
+
+    adj = {u: {v for v in G[u] if v != u} for u in G}
+
+    # Initialize Q with the given nodes and subg, cand with their nbrs
+    Q = nodes[:] if nodes is not None else []
+    cand = set(G)
+    for node in Q:
+        if node not in cand:
+            raise ValueError(f"The given `nodes` {nodes} do not form a clique")
+        cand &= adj[node]
+
+    if not cand:
+        yield Q[:]
+        return
+
+    subg = cand.copy()
+    stack = []
+    Q.append(None)
+
+    u = max(subg, key=lambda u: len(cand & adj[u]))
+    ext_u = cand - adj[u]
+
+    try:
+        while True:
+            if ext_u:
+                q = ext_u.pop()
+                cand.remove(q)
+                Q[-1] = q
+                adj_q = adj[q]
+                subg_q = subg & adj_q
+                if not subg_q:
+                    yield Q[:]
+                else:
+                    cand_q = cand & adj_q
+                    if cand_q:
+                        stack.append((subg, cand, ext_u))
+                        Q.append(None)
+                        subg = subg_q
+                        cand = cand_q
+                        u = max(subg, key=lambda u: len(cand & adj[u]))
+                        ext_u = cand - adj[u]
+            else:
+                Q.pop()
+                subg, cand, ext_u = stack.pop()
+    except IndexError:
+        pass
+
+
+@not_implemented_for("directed")
+@nx._dispatchable
+def find_cliques_recursive(G, nodes=None):
+    """Returns all maximal cliques in a graph.
+
+    For each node *v*, a *maximal clique for v* is a largest complete
+    subgraph containing *v*. The largest maximal clique is sometimes
+    called the *maximum clique*.
+
+    This function returns an iterator over cliques, each of which is a
+    list of nodes. It is a recursive implementation, so may suffer from
+    recursion depth issues, but is included for pedagogical reasons.
+    For a non-recursive implementation, see :func:`find_cliques`.
+
+    This function accepts a list of `nodes` and only the maximal cliques
+    containing all of these `nodes` are returned. It can considerably speed up
+    the running time if some specific cliques are desired.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        An undirected graph.
+
+    nodes : list, optional (default=None)
+        If provided, only yield *maximal cliques* containing all nodes in `nodes`.
+        If `nodes` isn't a clique itself, a ValueError is raised.
+
+    Returns
+    -------
+    iterator
+        An iterator over maximal cliques, each of which is a list of
+        nodes in `G`. If `nodes` is provided, only the maximal cliques
+        containing all the nodes in `nodes` are yielded. The order of
+        cliques is arbitrary.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is directed.
+
+    ValueError
+        If `nodes` is not a clique.
+
+    See Also
+    --------
+    find_cliques
+        An iterative version of the same algorithm. See docstring for examples.
+
+    Notes
+    -----
+    To obtain a list of all maximal cliques, use
+    `list(find_cliques_recursive(G))`. However, be aware that in the
+    worst-case, the length of this list can be exponential in the number
+    of nodes in the graph. This function avoids storing all cliques in memory
+    by only keeping current candidate node lists in memory during its search.
+
+    This implementation is based on the algorithm published by Bron and
+    Kerbosch (1973) [1]_, as adapted by Tomita, Tanaka and Takahashi
+    (2006) [2]_ and discussed in Cazals and Karande (2008) [3]_. For a
+    non-recursive implementation, see :func:`find_cliques`.
+
+    This algorithm ignores self-loops and parallel edges, since cliques
+    are not conventionally defined with such edges.
+
+    References
+    ----------
+    .. [1] Bron, C. and Kerbosch, J.
+       "Algorithm 457: finding all cliques of an undirected graph".
+       *Communications of the ACM* 16, 9 (Sep. 1973), 575--577.
+       
+
+    .. [2] Etsuji Tomita, Akira Tanaka, Haruhisa Takahashi,
+       "The worst-case time complexity for generating all maximal
+       cliques and computational experiments",
+       *Theoretical Computer Science*, Volume 363, Issue 1,
+       Computing and Combinatorics,
+       10th Annual International Conference on
+       Computing and Combinatorics (COCOON 2004), 25 October 2006, Pages 28--42
+       
+
+    .. [3] F. Cazals, C. Karande,
+       "A note on the problem of reporting maximal cliques",
+       *Theoretical Computer Science*,
+       Volume 407, Issues 1--3, 6 November 2008, Pages 564--568,
+       
+
+    """
+    if len(G) == 0:
+        return iter([])
+
+    adj = {u: {v for v in G[u] if v != u} for u in G}
+
+    # Initialize Q with the given nodes and subg, cand with their nbrs
+    Q = nodes[:] if nodes is not None else []
+    cand_init = set(G)
+    for node in Q:
+        if node not in cand_init:
+            raise ValueError(f"The given `nodes` {nodes} do not form a clique")
+        cand_init &= adj[node]
+
+    if not cand_init:
+        return iter([Q])
+
+    subg_init = cand_init.copy()
+
+    def expand(subg, cand):
+        u = max(subg, key=lambda u: len(cand & adj[u]))
+        for q in cand - adj[u]:
+            cand.remove(q)
+            Q.append(q)
+            adj_q = adj[q]
+            subg_q = subg & adj_q
+            if not subg_q:
+                yield Q[:]
+            else:
+                cand_q = cand & adj_q
+                if cand_q:
+                    yield from expand(subg_q, cand_q)
+            Q.pop()
+
+    return expand(subg_init, cand_init)
+
+
+@nx._dispatchable(returns_graph=True)
+def make_max_clique_graph(G, create_using=None):
+    """Returns the maximal clique graph of the given graph.
+
+    The nodes of the maximal clique graph of `G` are the cliques of
+    `G` and an edge joins two cliques if the cliques are not disjoint.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    NetworkX graph
+        A graph whose nodes are the cliques of `G` and whose edges
+        join two cliques if they are not disjoint.
+
+    Notes
+    -----
+    This function behaves like the following code::
+
+        import networkx as nx
+
+        G = nx.make_clique_bipartite(G)
+        cliques = [v for v in G.nodes() if G.nodes[v]["bipartite"] == 0]
+        G = nx.bipartite.projected_graph(G, cliques)
+        G = nx.relabel_nodes(G, {-v: v - 1 for v in G})
+
+    It should be faster, though, since it skips all the intermediate
+    steps.
+
+    """
+    if create_using is None:
+        B = G.__class__()
+    else:
+        B = nx.empty_graph(0, create_using)
+    cliques = list(enumerate(set(c) for c in find_cliques(G)))
+    # Add a numbered node for each clique.
+    B.add_nodes_from(i for i, c in cliques)
+    # Join cliques by an edge if they share a node.
+    clique_pairs = combinations(cliques, 2)
+    B.add_edges_from((i, j) for (i, c1), (j, c2) in clique_pairs if c1 & c2)
+    return B
+
+
+@nx._dispatchable(returns_graph=True)
+def make_clique_bipartite(G, fpos=None, create_using=None, name=None):
+    """Returns the bipartite clique graph corresponding to `G`.
+
+    In the returned bipartite graph, the "bottom" nodes are the nodes of
+    `G` and the "top" nodes represent the maximal cliques of `G`.
+    There is an edge from node *v* to clique *C* in the returned graph
+    if and only if *v* is an element of *C*.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        An undirected graph.
+
+    fpos : bool
+        If True or not None, the returned graph will have an
+        additional attribute, `pos`, a dictionary mapping node to
+        position in the Euclidean plane.
+
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    NetworkX graph
+        A bipartite graph whose "bottom" set is the nodes of the graph
+        `G`, whose "top" set is the cliques of `G`, and whose edges
+        join nodes of `G` to the cliques that contain them.
+
+        The nodes of the graph `G` have the node attribute
+        'bipartite' set to 1 and the nodes representing cliques
+        have the node attribute 'bipartite' set to 0, as is the
+        convention for bipartite graphs in NetworkX.
+
+    """
+    B = nx.empty_graph(0, create_using)
+    B.clear()
+    # The "bottom" nodes in the bipartite graph are the nodes of the
+    # original graph, G.
+    B.add_nodes_from(G, bipartite=1)
+    for i, cl in enumerate(find_cliques(G)):
+        # The "top" nodes in the bipartite graph are the cliques. These
+        # nodes get negative numbers as labels.
+        name = -i - 1
+        B.add_node(name, bipartite=0)
+        B.add_edges_from((v, name) for v in cl)
+    return B
+
+
+@nx._dispatchable
+def node_clique_number(G, nodes=None, cliques=None, separate_nodes=False):
+    """Returns the size of the largest maximal clique containing each given node.
+
+    Returns a single or list depending on input nodes.
+    An optional list of cliques can be input if already computed.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        An undirected graph.
+
+    cliques : list, optional (default=None)
+        A list of cliques, each of which is itself a list of nodes.
+        If not specified, the list of all cliques will be computed
+        using :func:`find_cliques`.
+
+    Returns
+    -------
+    int or dict
+        If `nodes` is a single node, returns the size of the
+        largest maximal clique in `G` containing that node.
+        Otherwise return a dict keyed by node to the size
+        of the largest maximal clique containing that node.
+
+    See Also
+    --------
+    find_cliques
+        find_cliques yields the maximal cliques of G.
+        It accepts a `nodes` argument which restricts consideration to
+        maximal cliques containing all the given `nodes`.
+        The search for the cliques is optimized for `nodes`.
+    number_of_cliques
+    """
+    if cliques is None:
+        if nodes is not None:
+            # Use ego_graph to decrease size of graph
+            # check for single node
+            if nodes in G:
+                return max(len(c) for c in find_cliques(nx.ego_graph(G, nodes)))
+            # handle multiple nodes
+            return {
+                n: max(len(c) for c in find_cliques(nx.ego_graph(G, n))) for n in nodes
+            }
+
+        # nodes is None--find all cliques
+        cliques = list(find_cliques(G))
+
+    # single node requested
+    if nodes in G:
+        return max(len(c) for c in cliques if nodes in c)
+
+    # multiple nodes requested
+    # preprocess all nodes (faster than one at a time for even 2 nodes)
+    size_for_n = defaultdict(int)
+    for c in cliques:
+        size_of_c = len(c)
+        for n in c:
+            if size_for_n[n] < size_of_c:
+                size_for_n[n] = size_of_c
+    if nodes is None:
+        return size_for_n
+    return {n: size_for_n[n] for n in nodes}
+
+
+def number_of_cliques(G, nodes=None, cliques=None):
+    """Return the number of maximal cliques each node is part of.
+
+    Output is a single value or dict depending on `nodes`.
+    Optional list of cliques can be input if already computed.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        An undirected graph.
+
+    nodes : list or None, optional (default=None)
+        A list of nodes to return the number of maximal cliques for.
+        If `None`, return the number of maximal cliques for all nodes.
+
+    cliques : list or None, optional (default=None)
+        A precomputed list of maximal cliques to use for the calculation.
+
+    Returns
+    -------
+    int or dict
+        If `nodes` is a single node, return the number of maximal cliques it is
+        part of. If `nodes` is a list, return a dictionary keyed by node to the
+        number of maximal cliques it is part of.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is directed.
+
+    See Also
+    --------
+    find_cliques
+    node_clique_number
+
+    Examples
+    --------
+    Compute the number of maximal cliques a node is part of:
+
+    >>> G = nx.complete_graph(3)
+    >>> nx.add_cycle(G, [0, 3, 4])
+    >>> nx.number_of_cliques(G, nodes=0)
+    2
+    >>> nx.number_of_cliques(G, nodes=1)
+    1
+
+    Or, for a list of nodes:
+
+    >>> nx.number_of_cliques(G, nodes=[0, 1])
+    {0: 2, 1: 1}
+
+    If no explicit `nodes` are provided, all nodes are considered:
+
+    >>> nx.number_of_cliques(G)
+    {0: 2, 1: 1, 2: 1, 3: 1, 4: 1}
+
+    The list of maximal cliques can also be precomputed:
+
+    >>> cl = list(nx.find_cliques(G))
+    >>> nx.number_of_cliques(G, cliques=cl)
+    {0: 2, 1: 1, 2: 1, 3: 1, 4: 1}
+    """
+    if cliques is None:
+        cliques = find_cliques(G)
+
+    if nodes is None:
+        nodes = list(G.nodes())  # none, get entire graph
+
+    if not isinstance(nodes, list):  # check for a list
+        v = nodes
+        # assume it is a single value
+        numcliq = sum(1 for c in cliques if v in c)
+    else:
+        numcliq = Counter(chain.from_iterable(cliques))
+        numcliq = {v: numcliq[v] for v in nodes}  # return a dict
+    return numcliq
+
+
+class MaxWeightClique:
+    """A class for the maximum weight clique algorithm.
+
+    This class is a helper for the `max_weight_clique` function.  The class
+    should not normally be used directly.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        The undirected graph for which a maximum weight clique is sought
+    weight : string or None, optional (default='weight')
+        The node attribute that holds the integer value used as a weight.
+        If None, then each node has weight 1.
+
+    Attributes
+    ----------
+    G : NetworkX graph
+        The undirected graph for which a maximum weight clique is sought
+    node_weights: dict
+        The weight of each node
+    incumbent_nodes : list
+        The nodes of the incumbent clique (the best clique found so far)
+    incumbent_weight: int
+        The weight of the incumbent clique
+    """
+
+    def __init__(self, G, weight):
+        self.G = G
+        self.incumbent_nodes = []
+        self.incumbent_weight = 0
+
+        if weight is None:
+            self.node_weights = {v: 1 for v in G.nodes()}
+        else:
+            for v in G.nodes():
+                if weight not in G.nodes[v]:
+                    errmsg = f"Node {v!r} does not have the requested weight field."
+                    raise KeyError(errmsg)
+                if not isinstance(G.nodes[v][weight], int):
+                    errmsg = f"The {weight!r} field of node {v!r} is not an integer."
+                    raise ValueError(errmsg)
+            self.node_weights = {v: G.nodes[v][weight] for v in G.nodes()}
+
+    def update_incumbent_if_improved(self, C, C_weight):
+        """Update the incumbent if the node set C has greater weight.
+
+        C is assumed to be a clique.
+        """
+        if C_weight > self.incumbent_weight:
+            self.incumbent_nodes = C[:]
+            self.incumbent_weight = C_weight
+
+    def greedily_find_independent_set(self, P):
+        """Greedily find an independent set of nodes from a set of
+        nodes P."""
+        independent_set = []
+        P = P[:]
+        while P:
+            v = P[0]
+            independent_set.append(v)
+            P = [w for w in P if v != w and not self.G.has_edge(v, w)]
+        return independent_set
+
+    def find_branching_nodes(self, P, target):
+        """Find a set of nodes to branch on."""
+        residual_wt = {v: self.node_weights[v] for v in P}
+        total_wt = 0
+        P = P[:]
+        while P:
+            independent_set = self.greedily_find_independent_set(P)
+            min_wt_in_class = min(residual_wt[v] for v in independent_set)
+            total_wt += min_wt_in_class
+            if total_wt > target:
+                break
+            for v in independent_set:
+                residual_wt[v] -= min_wt_in_class
+            P = [v for v in P if residual_wt[v] != 0]
+        return P
+
+    def expand(self, C, C_weight, P):
+        """Look for the best clique that contains all the nodes in C and zero or
+        more of the nodes in P, backtracking if it can be shown that no such
+        clique has greater weight than the incumbent.
+        """
+        self.update_incumbent_if_improved(C, C_weight)
+        branching_nodes = self.find_branching_nodes(P, self.incumbent_weight - C_weight)
+        while branching_nodes:
+            v = branching_nodes.pop()
+            P.remove(v)
+            new_C = C + [v]
+            new_C_weight = C_weight + self.node_weights[v]
+            new_P = [w for w in P if self.G.has_edge(v, w)]
+            self.expand(new_C, new_C_weight, new_P)
+
+    def find_max_weight_clique(self):
+        """Find a maximum weight clique."""
+        # Sort nodes in reverse order of degree for speed
+        nodes = sorted(self.G.nodes(), key=lambda v: self.G.degree(v), reverse=True)
+        nodes = [v for v in nodes if self.node_weights[v] > 0]
+        self.expand([], 0, nodes)
+
+
+@not_implemented_for("directed")
+@nx._dispatchable(node_attrs="weight")
+def max_weight_clique(G, weight="weight"):
+    """Find a maximum weight clique in G.
+
+    A *clique* in a graph is a set of nodes such that every two distinct nodes
+    are adjacent.  The *weight* of a clique is the sum of the weights of its
+    nodes.  A *maximum weight clique* of graph G is a clique C in G such that
+    no clique in G has weight greater than the weight of C.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        Undirected graph
+    weight : string or None, optional (default='weight')
+        The node attribute that holds the integer value used as a weight.
+        If None, then each node has weight 1.
+
+    Returns
+    -------
+    clique : list
+        the nodes of a maximum weight clique
+    weight : int
+        the weight of a maximum weight clique
+
+    Notes
+    -----
+    The implementation is recursive, and therefore it may run into recursion
+    depth issues if G contains a clique whose number of nodes is close to the
+    recursion depth limit.
+
+    At each search node, the algorithm greedily constructs a weighted
+    independent set cover of part of the graph in order to find a small set of
+    nodes on which to branch.  The algorithm is very similar to the algorithm
+    of Tavares et al. [1]_, other than the fact that the NetworkX version does
+    not use bitsets.  This style of algorithm for maximum weight clique (and
+    maximum weight independent set, which is the same problem but on the
+    complement graph) has a decades-long history.  See Algorithm B of Warren
+    and Hicks [2]_ and the references in that paper.
+
+    References
+    ----------
+    .. [1] Tavares, W.A., Neto, M.B.C., Rodrigues, C.D., Michelon, P.: Um
+           algoritmo de branch and bound para o problema da clique máxima
+           ponderada.  Proceedings of XLVII SBPO 1 (2015).
+
+    .. [2] Warren, Jeffrey S, Hicks, Illya V.: Combinatorial Branch-and-Bound
+           for the Maximum Weight Independent Set Problem.  Technical Report,
+           Texas A&M University (2016).
+    """
+
+    mwc = MaxWeightClique(G, weight)
+    mwc.find_max_weight_clique()
+    return mwc.incumbent_nodes, mwc.incumbent_weight
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/cluster.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/cluster.py
new file mode 100644
index 0000000000000000000000000000000000000000..e4ac54edfadf6fe851cbafdbfe5991f1e6df4946
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/cluster.py
@@ -0,0 +1,732 @@
+"""Algorithms to characterize the number of triangles in a graph."""
+
+from collections import Counter
+from itertools import chain, combinations
+
+import networkx as nx
+from networkx.utils import not_implemented_for
+
+__all__ = [
+    "triangles",
+    "all_triangles",
+    "average_clustering",
+    "clustering",
+    "transitivity",
+    "square_clustering",
+    "generalized_degree",
+]
+
+
+@not_implemented_for("directed")
+@nx._dispatchable
+def triangles(G, nodes=None):
+    """Compute the number of triangles.
+
+    Finds the number of triangles that include a node as one vertex.
+
+    Parameters
+    ----------
+    G : graph
+       A networkx graph
+
+    nodes : node, iterable of nodes, or None (default=None)
+        If a singleton node, return the number of triangles for that node.
+        If an iterable, compute the number of triangles for each of those nodes.
+        If `None` (the default) compute the number of triangles for all nodes in `G`.
+
+    Returns
+    -------
+    out : dict or int
+       If `nodes` is a container of nodes, returns number of triangles keyed by node (dict).
+       If `nodes` is a specific node, returns number of triangles for the node (int).
+
+    Examples
+    --------
+    >>> G = nx.complete_graph(5)
+    >>> print(nx.triangles(G, 0))
+    6
+    >>> print(nx.triangles(G))
+    {0: 6, 1: 6, 2: 6, 3: 6, 4: 6}
+    >>> print(list(nx.triangles(G, [0, 1]).values()))
+    [6, 6]
+
+    The total number of unique triangles in `G` can be determined by summing
+    the number of triangles for each node and dividing by 3 (because a given
+    triangle gets counted three times, once for each of its nodes).
+
+    >>> sum(nx.triangles(G).values()) // 3
+    10
+
+    Notes
+    -----
+    Self loops are ignored.
+
+    """
+    if nodes is not None:
+        # If `nodes` represents a single node, return only its number of triangles
+        if nodes in G:
+            return next(_triangles_and_degree_iter(G, nodes))[2] // 2
+
+        # if `nodes` is a container of nodes, then return a
+        # dictionary mapping node to number of triangles.
+        return {v: t // 2 for v, d, t, _ in _triangles_and_degree_iter(G, nodes)}
+
+    # if nodes is None, then compute triangles for the complete graph
+
+    # dict used to avoid visiting the same nodes twice
+    # this allows calculating/counting each triangle only once
+    later_nbrs = {}
+
+    # iterate over the nodes in a graph
+    for node, neighbors in G.adjacency():
+        later_nbrs[node] = {n for n in neighbors if n not in later_nbrs and n != node}
+
+    # instantiate Counter for each node to include isolated nodes
+    # add 1 to the count if a nodes neighbor's neighbor is also a neighbor
+    triangle_counts = Counter(dict.fromkeys(G, 0))
+    for node1, neighbors in later_nbrs.items():
+        for node2 in neighbors:
+            third_nodes = neighbors & later_nbrs[node2]
+            m = len(third_nodes)
+            triangle_counts[node1] += m
+            triangle_counts[node2] += m
+            triangle_counts.update(third_nodes)
+
+    return dict(triangle_counts)
+
+
+@not_implemented_for("multigraph")
+def _triangles_and_degree_iter(G, nodes=None):
+    """Return an iterator of (node, degree, triangles, generalized degree).
+
+    This double counts triangles so you may want to divide by 2.
+    See degree(), triangles() and generalized_degree() for definitions
+    and details.
+
+    """
+    if nodes is None:
+        nodes_nbrs = G.adj.items()
+    else:
+        nodes_nbrs = ((n, G[n]) for n in G.nbunch_iter(nodes))
+
+    for v, v_nbrs in nodes_nbrs:
+        vs = set(v_nbrs) - {v}
+        gen_degree = Counter(len(vs & (set(G[w]) - {w})) for w in vs)
+        ntriangles = sum(k * val for k, val in gen_degree.items())
+        yield (v, len(vs), ntriangles, gen_degree)
+
+
+@not_implemented_for("multigraph")
+def _weighted_triangles_and_degree_iter(G, nodes=None, weight="weight"):
+    """Return an iterator of (node, degree, weighted_triangles).
+
+    Used for weighted clustering.
+    Note: this returns the geometric average weight of edges in the triangle.
+    Also, each triangle is counted twice (each direction).
+    So you may want to divide by 2.
+
+    """
+    import numpy as np
+
+    if weight is None or G.number_of_edges() == 0:
+        max_weight = 1
+    else:
+        max_weight = max(d.get(weight, 1) for u, v, d in G.edges(data=True))
+    if nodes is None:
+        nodes_nbrs = G.adj.items()
+    else:
+        nodes_nbrs = ((n, G[n]) for n in G.nbunch_iter(nodes))
+
+    def wt(u, v):
+        return G[u][v].get(weight, 1) / max_weight
+
+    for i, nbrs in nodes_nbrs:
+        inbrs = set(nbrs) - {i}
+        weighted_triangles = 0
+        seen = set()
+        for j in inbrs:
+            seen.add(j)
+            # This avoids counting twice -- we double at the end.
+            jnbrs = set(G[j]) - seen
+            # Only compute the edge weight once, before the inner inner
+            # loop.
+            wij = wt(i, j)
+            weighted_triangles += np.cbrt(
+                [(wij * wt(j, k) * wt(k, i)) for k in inbrs & jnbrs]
+            ).sum()
+        yield (i, len(inbrs), 2 * float(weighted_triangles))
+
+
+@not_implemented_for("multigraph")
+def _directed_triangles_and_degree_iter(G, nodes=None):
+    """Return an iterator of
+    (node, total_degree, reciprocal_degree, directed_triangles).
+
+    Used for directed clustering.
+    Note that unlike `_triangles_and_degree_iter()`, this function counts
+    directed triangles so does not count triangles twice.
+
+    """
+    nodes_nbrs = ((n, G._pred[n], G._succ[n]) for n in G.nbunch_iter(nodes))
+
+    for i, preds, succs in nodes_nbrs:
+        ipreds = set(preds) - {i}
+        isuccs = set(succs) - {i}
+
+        directed_triangles = 0
+        for j in chain(ipreds, isuccs):
+            jpreds = set(G._pred[j]) - {j}
+            jsuccs = set(G._succ[j]) - {j}
+            directed_triangles += sum(
+                1
+                for k in chain(
+                    (ipreds & jpreds),
+                    (ipreds & jsuccs),
+                    (isuccs & jpreds),
+                    (isuccs & jsuccs),
+                )
+            )
+        dtotal = len(ipreds) + len(isuccs)
+        dbidirectional = len(ipreds & isuccs)
+        yield (i, dtotal, dbidirectional, directed_triangles)
+
+
+@not_implemented_for("multigraph")
+def _directed_weighted_triangles_and_degree_iter(G, nodes=None, weight="weight"):
+    """Return an iterator of
+    (node, total_degree, reciprocal_degree, directed_weighted_triangles).
+
+    Used for directed weighted clustering.
+    Note that unlike `_weighted_triangles_and_degree_iter()`, this function counts
+    directed triangles so does not count triangles twice.
+
+    """
+    import numpy as np
+
+    if weight is None or G.number_of_edges() == 0:
+        max_weight = 1
+    else:
+        max_weight = max(d.get(weight, 1) for u, v, d in G.edges(data=True))
+
+    nodes_nbrs = ((n, G._pred[n], G._succ[n]) for n in G.nbunch_iter(nodes))
+
+    def wt(u, v):
+        return G[u][v].get(weight, 1) / max_weight
+
+    for i, preds, succs in nodes_nbrs:
+        ipreds = set(preds) - {i}
+        isuccs = set(succs) - {i}
+
+        directed_triangles = 0
+        for j in ipreds:
+            jpreds = set(G._pred[j]) - {j}
+            jsuccs = set(G._succ[j]) - {j}
+            directed_triangles += np.cbrt(
+                [(wt(j, i) * wt(k, i) * wt(k, j)) for k in ipreds & jpreds]
+            ).sum()
+            directed_triangles += np.cbrt(
+                [(wt(j, i) * wt(k, i) * wt(j, k)) for k in ipreds & jsuccs]
+            ).sum()
+            directed_triangles += np.cbrt(
+                [(wt(j, i) * wt(i, k) * wt(k, j)) for k in isuccs & jpreds]
+            ).sum()
+            directed_triangles += np.cbrt(
+                [(wt(j, i) * wt(i, k) * wt(j, k)) for k in isuccs & jsuccs]
+            ).sum()
+
+        for j in isuccs:
+            jpreds = set(G._pred[j]) - {j}
+            jsuccs = set(G._succ[j]) - {j}
+            directed_triangles += np.cbrt(
+                [(wt(i, j) * wt(k, i) * wt(k, j)) for k in ipreds & jpreds]
+            ).sum()
+            directed_triangles += np.cbrt(
+                [(wt(i, j) * wt(k, i) * wt(j, k)) for k in ipreds & jsuccs]
+            ).sum()
+            directed_triangles += np.cbrt(
+                [(wt(i, j) * wt(i, k) * wt(k, j)) for k in isuccs & jpreds]
+            ).sum()
+            directed_triangles += np.cbrt(
+                [(wt(i, j) * wt(i, k) * wt(j, k)) for k in isuccs & jsuccs]
+            ).sum()
+
+        dtotal = len(ipreds) + len(isuccs)
+        dbidirectional = len(ipreds & isuccs)
+        yield (i, dtotal, dbidirectional, float(directed_triangles))
+
+
+@not_implemented_for("directed")
+@nx._dispatchable
+def all_triangles(G, nbunch=None):
+    """
+    Yields all unique triangles in an undirected graph.
+
+    A triangle is a set of three distinct nodes where each node is connected to
+    the other two.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        An undirected graph.
+
+    nbunch : node, iterable of nodes, or None (default=None)
+        If a node or iterable of nodes, only triangles involving at least one
+        node in `nbunch` are yielded.
+        If ``None``, yields all unique triangles in the graph.
+
+    Yields
+    ------
+    tuple
+        A tuple of three nodes forming a triangle ``(u, v, w)``.
+
+    Examples
+    --------
+    >>> G = nx.complete_graph(4)
+    >>> sorted([sorted(t) for t in all_triangles(G)])
+    [[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]]
+
+    Notes
+    -----
+    This algorithm ensures each triangle is yielded once using an internal node ordering.
+    In multigraphs, triangles are identified by their unique set of nodes,
+    ignoring multiple edges between the same nodes. Self-loops are ignored.
+    Runs in ``O(m * d)`` time in the worst case, where ``m`` the number of edges
+    and ``d`` the maximum degree.
+
+    See Also
+    --------
+    :func:`~networkx.algorithms.triads.all_triads` : related function for directed graphs
+    """
+    if nbunch is None:
+        nbunch = relevant_nodes = G
+    else:
+        nbunch = dict.fromkeys(G.nbunch_iter(nbunch))
+        relevant_nodes = chain(
+            nbunch,
+            (nbr for node in nbunch for nbr in G.neighbors(node) if nbr not in nbunch),
+        )
+
+    node_to_id = {node: i for i, node in enumerate(relevant_nodes)}
+
+    for u in nbunch:
+        u_id = node_to_id[u]
+        u_nbrs = G._adj[u].keys()
+        for v in u_nbrs:
+            v_id = node_to_id.get(v, -1)
+            if v_id <= u_id:
+                continue
+            v_nbrs = G._adj[v].keys()
+            for w in v_nbrs & u_nbrs:
+                if node_to_id.get(w, -1) > v_id:
+                    yield u, v, w
+
+
+@nx._dispatchable(edge_attrs="weight")
+def average_clustering(G, nodes=None, weight=None, count_zeros=True):
+    r"""Compute the average clustering coefficient for the graph G.
+
+    The clustering coefficient for the graph is the average,
+
+    .. math::
+
+       C = \frac{1}{n}\sum_{v \in G} c_v,
+
+    where :math:`n` is the number of nodes in `G`.
+
+    Parameters
+    ----------
+    G : graph
+
+    nodes : container of nodes, optional (default=all nodes in G)
+       Compute average clustering for nodes in this container.
+
+    weight : string or None, optional (default=None)
+       The edge attribute that holds the numerical value used as a weight.
+       If None, then each edge has weight 1.
+
+    count_zeros : bool
+       If False include only the nodes with nonzero clustering in the average.
+
+    Returns
+    -------
+    avg : float
+       Average clustering
+
+    Examples
+    --------
+    >>> G = nx.complete_graph(5)
+    >>> print(nx.average_clustering(G))
+    1.0
+
+    Notes
+    -----
+    This is a space saving routine; it might be faster
+    to use the clustering function to get a list and then take the average.
+
+    Self loops are ignored.
+
+    References
+    ----------
+    .. [1] Generalizations of the clustering coefficient to weighted
+       complex networks by J. Saramäki, M. Kivelä, J.-P. Onnela,
+       K. Kaski, and J. Kertész, Physical Review E, 75 027105 (2007).
+       http://jponnela.com/web_documents/a9.pdf
+    .. [2] Marcus Kaiser,  Mean clustering coefficients: the role of isolated
+       nodes and leafs on clustering measures for small-world networks.
+       https://arxiv.org/abs/0802.2512
+    """
+    c = clustering(G, nodes, weight=weight).values()
+    if not count_zeros:
+        c = [v for v in c if abs(v) > 0]
+    return sum(c) / len(c)
+
+
+@nx._dispatchable(edge_attrs="weight")
+def clustering(G, nodes=None, weight=None):
+    r"""Compute the clustering coefficient for nodes.
+
+    For unweighted graphs, the clustering of a node :math:`u`
+    is the fraction of possible triangles through that node that exist,
+
+    .. math::
+
+      c_u = \frac{2 T(u)}{deg(u)(deg(u)-1)},
+
+    where :math:`T(u)` is the number of triangles through node :math:`u` and
+    :math:`deg(u)` is the degree of :math:`u`.
+
+    For weighted graphs, there are several ways to define clustering [1]_.
+    the one used here is defined
+    as the geometric average of the subgraph edge weights [2]_,
+
+    .. math::
+
+       c_u = \frac{1}{deg(u)(deg(u)-1))}
+             \sum_{vw} (\hat{w}_{uv} \hat{w}_{uw} \hat{w}_{vw})^{1/3}.
+
+    The edge weights :math:`\hat{w}_{uv}` are normalized by the maximum weight
+    in the network :math:`\hat{w}_{uv} = w_{uv}/\max(w)`.
+
+    The value of :math:`c_u` is assigned to 0 if :math:`deg(u) < 2`.
+
+    Additionally, this weighted definition has been generalized to support negative edge weights [3]_.
+
+    For directed graphs, the clustering is similarly defined as the fraction
+    of all possible directed triangles or geometric average of the subgraph
+    edge weights for unweighted and weighted directed graph respectively [4]_.
+
+    .. math::
+
+       c_u = \frac{T(u)}{2(deg^{tot}(u)(deg^{tot}(u)-1) - 2deg^{\leftrightarrow}(u))},
+
+    where :math:`T(u)` is the number of directed triangles through node
+    :math:`u`, :math:`deg^{tot}(u)` is the sum of in degree and out degree of
+    :math:`u` and :math:`deg^{\leftrightarrow}(u)` is the reciprocal degree of
+    :math:`u`.
+
+
+    Parameters
+    ----------
+    G : graph
+
+    nodes : node, iterable of nodes, or None (default=None)
+        If a singleton node, return the number of triangles for that node.
+        If an iterable, compute the number of triangles for each of those nodes.
+        If `None` (the default) compute the number of triangles for all nodes in `G`.
+
+    weight : string or None, optional (default=None)
+       The edge attribute that holds the numerical value used as a weight.
+       If None, then each edge has weight 1.
+
+    Returns
+    -------
+    out : float, or dictionary
+       Clustering coefficient at specified nodes
+
+    Examples
+    --------
+    >>> G = nx.complete_graph(5)
+    >>> print(nx.clustering(G, 0))
+    1.0
+    >>> print(nx.clustering(G))
+    {0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0}
+
+    Notes
+    -----
+    Self loops are ignored.
+
+    References
+    ----------
+    .. [1] Generalizations of the clustering coefficient to weighted
+       complex networks by J. Saramäki, M. Kivelä, J.-P. Onnela,
+       K. Kaski, and J. Kertész, Physical Review E, 75 027105 (2007).
+       http://jponnela.com/web_documents/a9.pdf
+    .. [2] Intensity and coherence of motifs in weighted complex
+       networks by J. P. Onnela, J. Saramäki, J. Kertész, and K. Kaski,
+       Physical Review E, 71(6), 065103 (2005).
+    .. [3] Generalization of Clustering Coefficients to Signed Correlation Networks
+       by G. Costantini and M. Perugini, PloS one, 9(2), e88669 (2014).
+    .. [4] Clustering in complex directed networks by G. Fagiolo,
+       Physical Review E, 76(2), 026107 (2007).
+    """
+    if G.is_directed():
+        if weight is not None:
+            td_iter = _directed_weighted_triangles_and_degree_iter(G, nodes, weight)
+            clusterc = {
+                v: 0 if t == 0 else t / ((dt * (dt - 1) - 2 * db) * 2)
+                for v, dt, db, t in td_iter
+            }
+        else:
+            td_iter = _directed_triangles_and_degree_iter(G, nodes)
+            clusterc = {
+                v: 0 if t == 0 else t / ((dt * (dt - 1) - 2 * db) * 2)
+                for v, dt, db, t in td_iter
+            }
+    else:
+        # The formula 2*T/(d*(d-1)) from docs is t/(d*(d-1)) here b/c t==2*T
+        if weight is not None:
+            td_iter = _weighted_triangles_and_degree_iter(G, nodes, weight)
+            clusterc = {v: 0 if t == 0 else t / (d * (d - 1)) for v, d, t in td_iter}
+        else:
+            td_iter = _triangles_and_degree_iter(G, nodes)
+            clusterc = {v: 0 if t == 0 else t / (d * (d - 1)) for v, d, t, _ in td_iter}
+    if nodes in G:
+        # Return the value of the sole entry in the dictionary.
+        return clusterc[nodes]
+    return clusterc
+
+
+@nx._dispatchable
+def transitivity(G):
+    r"""Compute graph transitivity, the fraction of all possible triangles
+    present in G.
+
+    Possible triangles are identified by the number of "triads"
+    (two edges with a shared vertex).
+
+    The transitivity is
+
+    .. math::
+
+        T = 3\frac{\#triangles}{\#triads}.
+
+    Parameters
+    ----------
+    G : graph
+
+    Returns
+    -------
+    out : float
+       Transitivity
+
+    Notes
+    -----
+    Self loops are ignored.
+
+    Examples
+    --------
+    >>> G = nx.complete_graph(5)
+    >>> print(nx.transitivity(G))
+    1.0
+    """
+    triangles_contri = [
+        (t, d * (d - 1)) for v, d, t, _ in _triangles_and_degree_iter(G)
+    ]
+    # If the graph is empty
+    if len(triangles_contri) == 0:
+        return 0
+    triangles, contri = map(sum, zip(*triangles_contri))
+    return 0 if triangles == 0 else triangles / contri
+
+
+@nx._dispatchable
+def square_clustering(G, nodes=None):
+    r"""Compute the squares clustering coefficient for nodes.
+
+    For each node return the fraction of possible squares that exist at
+    the node [1]_
+
+    .. math::
+       C_4(v) = \frac{ \sum_{u=1}^{k_v}
+       \sum_{w=u+1}^{k_v} q_v(u,w) }{ \sum_{u=1}^{k_v}
+       \sum_{w=u+1}^{k_v} [a_v(u,w) + q_v(u,w)]},
+
+    where :math:`q_v(u,w)` are the number of common neighbors of :math:`u` and
+    :math:`w` other than :math:`v` (ie squares), and :math:`a_v(u,w) = (k_u -
+    (1+q_v(u,w)+\theta_{uv})) + (k_w - (1+q_v(u,w)+\theta_{uw}))`, where
+    :math:`\theta_{uw} = 1` if :math:`u` and :math:`w` are connected and 0
+    otherwise. [2]_
+
+    Parameters
+    ----------
+    G : graph
+
+    nodes : container of nodes, optional (default=all nodes in G)
+       Compute clustering for nodes in this container.
+
+    Returns
+    -------
+    c4 : dictionary
+       A dictionary keyed by node with the square clustering coefficient value.
+
+    Examples
+    --------
+    >>> G = nx.complete_graph(5)
+    >>> print(nx.square_clustering(G, 0))
+    1.0
+    >>> print(nx.square_clustering(G))
+    {0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0}
+
+    Notes
+    -----
+    Self loops are ignored.
+
+    While :math:`C_3(v)` (triangle clustering) gives the probability that
+    two neighbors of node v are connected with each other, :math:`C_4(v)` is
+    the probability that two neighbors of node v share a common
+    neighbor different from v. This algorithm can be applied to both
+    bipartite and unipartite networks.
+
+    References
+    ----------
+    .. [1] Pedro G. Lind, Marta C. González, and Hans J. Herrmann. 2005
+        Cycles and clustering in bipartite networks.
+        Physical Review E (72) 056127.
+    .. [2] Zhang, Peng et al. Clustering Coefficient and Community Structure of
+        Bipartite Networks. Physica A: Statistical Mechanics and its Applications 387.27 (2008): 6869–6875.
+        https://arxiv.org/abs/0710.0117v1
+    """
+    if nodes is None:
+        node_iter = G
+    else:
+        node_iter = G.nbunch_iter(nodes)
+    clustering = {}
+    _G_adj = G._adj
+
+    class GAdj(dict):
+        """Calculate (and cache) node neighbor sets excluding self-loops."""
+
+        def __missing__(self, v):
+            v_neighbors = self[v] = set(_G_adj[v])
+            v_neighbors.discard(v)  # Ignore self-loops
+            return v_neighbors
+
+    G_adj = GAdj()  # Values are sets of neighbors (no self-loops)
+
+    for v in node_iter:
+        v_neighbors = G_adj[v]
+        v_degrees_m1 = len(v_neighbors) - 1  # degrees[v] - 1 (used below)
+        if v_degrees_m1 <= 0:
+            # Can't form a square without at least two neighbors
+            clustering[v] = 0
+            continue
+
+        # Count squares with nodes u-v-w-x from the current node v.
+        # Terms of the denominator: potential = uw_degrees - uw_count - triangles - squares
+        # uw_degrees: degrees[u] + degrees[w] for each u-w combo
+        uw_degrees = 0
+        # uw_count: 1 for each u and 1 for each w for all combos (degrees * (degrees - 1))
+        uw_count = len(v_neighbors) * v_degrees_m1
+        # triangles: 1 for each edge where u-w or w-u are connected (i.e. triangles)
+        triangles = 0
+        # squares: the number of squares (also the numerator)
+        squares = 0
+
+        # Iterate over all neighbors
+        for u in v_neighbors:
+            u_neighbors = G_adj[u]
+            uw_degrees += len(u_neighbors) * v_degrees_m1
+            # P2 from https://arxiv.org/abs/2007.11111
+            p2 = len(u_neighbors & v_neighbors)
+            # triangles is C_3, sigma_4 from https://arxiv.org/abs/2007.11111
+            # This double-counts triangles compared to `triangles` function
+            triangles += p2
+            # squares is C_4, sigma_12 from https://arxiv.org/abs/2007.11111
+            # Include this term, b/c a neighbor u can also be a neighbor of neighbor x
+            squares += p2 * (p2 - 1)  # Will divide by 2 later
+
+        # And iterate over all neighbors of neighbors.
+        # These nodes x may be the corners opposite v in squares u-v-w-x.
+        two_hop_neighbors = set.union(*(G_adj[u] for u in v_neighbors))
+        two_hop_neighbors -= v_neighbors  # Neighbors already counted above
+        two_hop_neighbors.discard(v)
+        for x in two_hop_neighbors:
+            p2 = len(v_neighbors & G_adj[x])
+            squares += p2 * (p2 - 1)  # Will divide by 2 later
+
+        squares //= 2
+        potential = uw_degrees - uw_count - triangles - squares
+        if potential > 0:
+            clustering[v] = squares / potential
+        else:
+            clustering[v] = 0
+    if nodes in G:
+        # Return the value of the sole entry in the dictionary.
+        return clustering[nodes]
+    return clustering
+
+
+@not_implemented_for("directed")
+@nx._dispatchable
+def generalized_degree(G, nodes=None):
+    r"""Compute the generalized degree for nodes.
+
+    For each node, the generalized degree shows how many edges of given
+    triangle multiplicity the node is connected to. The triangle multiplicity
+    of an edge is the number of triangles an edge participates in. The
+    generalized degree of node :math:`i` can be written as a vector
+    :math:`\mathbf{k}_i=(k_i^{(0)}, \dotsc, k_i^{(N-2)})` where
+    :math:`k_i^{(j)}` is the number of edges attached to node :math:`i` that
+    participate in :math:`j` triangles.
+
+    Parameters
+    ----------
+    G : graph
+
+    nodes : container of nodes, optional (default=all nodes in G)
+       Compute the generalized degree for nodes in this container.
+
+    Returns
+    -------
+    out : Counter, or dictionary of Counters
+       Generalized degree of specified nodes. The Counter is keyed by edge
+       triangle multiplicity.
+
+    Examples
+    --------
+    >>> G = nx.complete_graph(5)
+    >>> print(nx.generalized_degree(G, 0))
+    Counter({3: 4})
+    >>> print(nx.generalized_degree(G))
+    {0: Counter({3: 4}), 1: Counter({3: 4}), 2: Counter({3: 4}), 3: Counter({3: 4}), 4: Counter({3: 4})}
+
+    To recover the number of triangles attached to a node:
+
+    >>> k1 = nx.generalized_degree(G, 0)
+    >>> sum([k * v for k, v in k1.items()]) / 2 == nx.triangles(G, 0)
+    True
+
+    Notes
+    -----
+    Self loops are ignored.
+
+    In a network of N nodes, the highest triangle multiplicity an edge can have
+    is N-2.
+
+    The return value does not include a `zero` entry if no edges of a
+    particular triangle multiplicity are present.
+
+    The number of triangles node :math:`i` is attached to can be recovered from
+    the generalized degree :math:`\mathbf{k}_i=(k_i^{(0)}, \dotsc,
+    k_i^{(N-2)})` by :math:`(k_i^{(1)}+2k_i^{(2)}+\dotsc +(N-2)k_i^{(N-2)})/2`.
+
+    References
+    ----------
+    .. [1] Networks with arbitrary edge multiplicities by V. Zlatić,
+        D. Garlaschelli and G. Caldarelli, EPL (Europhysics Letters),
+        Volume 97, Number 2 (2012).
+        https://iopscience.iop.org/article/10.1209/0295-5075/97/28005
+    """
+    if nodes in G:
+        return next(_triangles_and_degree_iter(G, nodes))[3]
+    return {v: gd for v, d, t, gd in _triangles_and_degree_iter(G, nodes)}
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/coloring/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/coloring/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..39381d9f163a5400f362b91a89215bfc915a8022
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/coloring/__init__.py
@@ -0,0 +1,4 @@
+from networkx.algorithms.coloring.greedy_coloring import *
+from networkx.algorithms.coloring.equitable_coloring import equitable_color
+
+__all__ = ["greedy_color", "equitable_color"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/coloring/equitable_coloring.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/coloring/equitable_coloring.py
new file mode 100644
index 0000000000000000000000000000000000000000..e464a07447045fcdaa8e7ca4ea56552fb00e2826
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/coloring/equitable_coloring.py
@@ -0,0 +1,505 @@
+"""
+Equitable coloring of graphs with bounded degree.
+"""
+
+from collections import defaultdict
+
+import networkx as nx
+
+__all__ = ["equitable_color"]
+
+
+@nx._dispatchable
+def is_coloring(G, coloring):
+    """Determine if the coloring is a valid coloring for the graph G."""
+    # Verify that the coloring is valid.
+    return all(coloring[s] != coloring[d] for s, d in G.edges)
+
+
+@nx._dispatchable
+def is_equitable(G, coloring, num_colors=None):
+    """Determines if the coloring is valid and equitable for the graph G."""
+
+    if not is_coloring(G, coloring):
+        return False
+
+    # Verify whether it is equitable.
+    color_set_size = defaultdict(int)
+    for color in coloring.values():
+        color_set_size[color] += 1
+
+    if num_colors is not None:
+        for color in range(num_colors):
+            if color not in color_set_size:
+                # These colors do not have any vertices attached to them.
+                color_set_size[color] = 0
+
+    # If there are more than 2 distinct values, the coloring cannot be equitable
+    all_set_sizes = set(color_set_size.values())
+    if len(all_set_sizes) == 0 and num_colors is None:  # Was an empty graph
+        return True
+    elif len(all_set_sizes) == 1:
+        return True
+    elif len(all_set_sizes) == 2:
+        a, b = list(all_set_sizes)
+        return abs(a - b) <= 1
+    else:  # len(all_set_sizes) > 2:
+        return False
+
+
+def make_C_from_F(F):
+    C = defaultdict(list)
+    for node, color in F.items():
+        C[color].append(node)
+
+    return C
+
+
+def make_N_from_L_C(L, C):
+    nodes = L.keys()
+    colors = C.keys()
+    return {
+        (node, color): sum(1 for v in L[node] if v in C[color])
+        for node in nodes
+        for color in colors
+    }
+
+
+def make_H_from_C_N(C, N):
+    return {
+        (c1, c2): sum(1 for node in C[c1] if N[(node, c2)] == 0) for c1 in C for c2 in C
+    }
+
+
+def change_color(u, X, Y, N, H, F, C, L):
+    """Change the color of 'u' from X to Y and update N, H, F, C."""
+    assert F[u] == X and X != Y
+
+    # Change the class of 'u' from X to Y
+    F[u] = Y
+
+    for k in C:
+        # 'u' witnesses an edge from k -> Y instead of from k -> X now.
+        if N[u, k] == 0:
+            H[(X, k)] -= 1
+            H[(Y, k)] += 1
+
+    for v in L[u]:
+        # 'v' has lost a neighbor in X and gained one in Y
+        N[(v, X)] -= 1
+        N[(v, Y)] += 1
+
+        if N[(v, X)] == 0:
+            # 'v' witnesses F[v] -> X
+            H[(F[v], X)] += 1
+
+        if N[(v, Y)] == 1:
+            # 'v' no longer witnesses F[v] -> Y
+            H[(F[v], Y)] -= 1
+
+    C[X].remove(u)
+    C[Y].append(u)
+
+
+def move_witnesses(src_color, dst_color, N, H, F, C, T_cal, L):
+    """Move witness along a path from src_color to dst_color."""
+    X = src_color
+    while X != dst_color:
+        Y = T_cal[X]
+        # Move _any_ witness from X to Y = T_cal[X]
+        w = next(x for x in C[X] if N[(x, Y)] == 0)
+        change_color(w, X, Y, N=N, H=H, F=F, C=C, L=L)
+        X = Y
+
+
+@nx._dispatchable(mutates_input=True)
+def pad_graph(G, num_colors):
+    """Add a disconnected complete clique K_p such that the number of nodes in
+    the graph becomes a multiple of `num_colors`.
+
+    Assumes that the graph's nodes are labelled using integers.
+
+    Returns the number of nodes with each color.
+    """
+
+    n_ = len(G)
+    r = num_colors - 1
+
+    # Ensure that the number of nodes in G is a multiple of (r + 1)
+    s = n_ // (r + 1)
+    if n_ != s * (r + 1):
+        p = (r + 1) - n_ % (r + 1)
+        s += 1
+
+        # Complete graph K_p between (imaginary) nodes [n_, ... , n_ + p]
+        K = nx.relabel_nodes(nx.complete_graph(p), {idx: idx + n_ for idx in range(p)})
+        G.add_edges_from(K.edges)
+
+    return s
+
+
+def procedure_P(V_minus, V_plus, N, H, F, C, L, excluded_colors=None):
+    """Procedure P as described in the paper."""
+
+    if excluded_colors is None:
+        excluded_colors = set()
+
+    A_cal = set()
+    T_cal = {}
+    R_cal = []
+
+    # BFS to determine A_cal, i.e. colors reachable from V-
+    reachable = [V_minus]
+    marked = set(reachable)
+    idx = 0
+
+    while idx < len(reachable):
+        pop = reachable[idx]
+        idx += 1
+
+        A_cal.add(pop)
+        R_cal.append(pop)
+
+        # TODO: Checking whether a color has been visited can be made faster by
+        # using a look-up table instead of testing for membership in a set by a
+        # logarithmic factor.
+        next_layer = []
+        for k in C:
+            if (
+                H[(k, pop)] > 0
+                and k not in A_cal
+                and k not in excluded_colors
+                and k not in marked
+            ):
+                next_layer.append(k)
+
+        for dst in next_layer:
+            # Record that `dst` can reach `pop`
+            T_cal[dst] = pop
+
+        marked.update(next_layer)
+        reachable.extend(next_layer)
+
+    # Variables for the algorithm
+    b = len(C) - len(A_cal)
+
+    if V_plus in A_cal:
+        # Easy case: V+ is in A_cal
+        # Move one node from V+ to V- using T_cal to find the parents.
+        move_witnesses(V_plus, V_minus, N=N, H=H, F=F, C=C, T_cal=T_cal, L=L)
+    else:
+        # If there is a solo edge, we can resolve the situation by
+        # moving witnesses from B to A, making G[A] equitable and then
+        # recursively balancing G[B - w] with a different V_minus and
+        # but the same V_plus.
+
+        A_0 = set()
+        A_cal_0 = set()
+        num_terminal_sets_found = 0
+        made_equitable = False
+
+        for W_1 in R_cal[::-1]:
+            for v in C[W_1]:
+                X = None
+
+                for U in C:
+                    if N[(v, U)] == 0 and U in A_cal and U != W_1:
+                        X = U
+
+                # v does not witness an edge in H[A_cal]
+                if X is None:
+                    continue
+
+                for U in C:
+                    # Note: Departing from the paper here.
+                    if N[(v, U)] >= 1 and U not in A_cal:
+                        X_prime = U
+                        w = v
+
+                        try:
+                            # Finding the solo neighbor of w in X_prime
+                            y = next(
+                                node
+                                for node in L[w]
+                                if F[node] == X_prime and N[(node, W_1)] == 1
+                            )
+                        except StopIteration:
+                            pass
+                        else:
+                            W = W_1
+
+                            # Move w from W to X, now X has one extra node.
+                            change_color(w, W, X, N=N, H=H, F=F, C=C, L=L)
+
+                            # Move witness from X to V_minus, making the coloring
+                            # equitable.
+                            move_witnesses(
+                                src_color=X,
+                                dst_color=V_minus,
+                                N=N,
+                                H=H,
+                                F=F,
+                                C=C,
+                                T_cal=T_cal,
+                                L=L,
+                            )
+
+                            # Move y from X_prime to W, making W the correct size.
+                            change_color(y, X_prime, W, N=N, H=H, F=F, C=C, L=L)
+
+                            # Then call the procedure on G[B - y]
+                            procedure_P(
+                                V_minus=X_prime,
+                                V_plus=V_plus,
+                                N=N,
+                                H=H,
+                                C=C,
+                                F=F,
+                                L=L,
+                                excluded_colors=excluded_colors.union(A_cal),
+                            )
+                            made_equitable = True
+                            break
+
+                if made_equitable:
+                    break
+            else:
+                # No node in W_1 was found such that
+                # it had a solo-neighbor.
+                A_cal_0.add(W_1)
+                A_0.update(C[W_1])
+                num_terminal_sets_found += 1
+
+            if num_terminal_sets_found == b:
+                # Otherwise, construct the maximal independent set and find
+                # a pair of z_1, z_2 as in Case II.
+
+                # BFS to determine B_cal': the set of colors reachable from V+
+                B_cal_prime = set()
+                T_cal_prime = {}
+
+                reachable = [V_plus]
+                marked = set(reachable)
+                idx = 0
+                while idx < len(reachable):
+                    pop = reachable[idx]
+                    idx += 1
+
+                    B_cal_prime.add(pop)
+
+                    # No need to check for excluded_colors here because
+                    # they only exclude colors from A_cal
+                    next_layer = [
+                        k
+                        for k in C
+                        if H[(pop, k)] > 0 and k not in B_cal_prime and k not in marked
+                    ]
+
+                    for dst in next_layer:
+                        T_cal_prime[pop] = dst
+
+                    marked.update(next_layer)
+                    reachable.extend(next_layer)
+
+                # Construct the independent set of G[B']
+                I_set = set()
+                I_covered = set()
+                W_covering = {}
+
+                B_prime = [node for k in B_cal_prime for node in C[k]]
+
+                # Add the nodes in V_plus to I first.
+                for z in C[V_plus] + B_prime:
+                    if z in I_covered or F[z] not in B_cal_prime:
+                        continue
+
+                    I_set.add(z)
+                    I_covered.add(z)
+                    I_covered.update(list(L[z]))
+
+                    for w in L[z]:
+                        if F[w] in A_cal_0 and N[(z, F[w])] == 1:
+                            if w not in W_covering:
+                                W_covering[w] = z
+                            else:
+                                # Found z1, z2 which have the same solo
+                                # neighbor in some W
+                                z_1 = W_covering[w]
+                                # z_2 = z
+
+                                Z = F[z_1]
+                                W = F[w]
+
+                                # shift nodes along W, V-
+                                move_witnesses(
+                                    W, V_minus, N=N, H=H, F=F, C=C, T_cal=T_cal, L=L
+                                )
+
+                                # shift nodes along V+ to Z
+                                move_witnesses(
+                                    V_plus,
+                                    Z,
+                                    N=N,
+                                    H=H,
+                                    F=F,
+                                    C=C,
+                                    T_cal=T_cal_prime,
+                                    L=L,
+                                )
+
+                                # change color of z_1 to W
+                                change_color(z_1, Z, W, N=N, H=H, F=F, C=C, L=L)
+
+                                # change color of w to some color in B_cal
+                                W_plus = next(
+                                    k for k in C if N[(w, k)] == 0 and k not in A_cal
+                                )
+                                change_color(w, W, W_plus, N=N, H=H, F=F, C=C, L=L)
+
+                                # recurse with G[B \cup W*]
+                                excluded_colors.update(
+                                    [k for k in C if k != W and k not in B_cal_prime]
+                                )
+                                procedure_P(
+                                    V_minus=W,
+                                    V_plus=W_plus,
+                                    N=N,
+                                    H=H,
+                                    C=C,
+                                    F=F,
+                                    L=L,
+                                    excluded_colors=excluded_colors,
+                                )
+
+                                made_equitable = True
+                                break
+
+                    if made_equitable:
+                        break
+                else:
+                    assert False, (
+                        "Must find a w which is the solo neighbor "
+                        "of two vertices in B_cal_prime."
+                    )
+
+            if made_equitable:
+                break
+
+
+@nx._dispatchable
+def equitable_color(G, num_colors):
+    """Provides an equitable coloring for nodes of `G`.
+
+    Attempts to color a graph using `num_colors` colors, where no neighbors of
+    a node can have same color as the node itself and the number of nodes with
+    each color differ by at most 1. `num_colors` must be greater than the
+    maximum degree of `G`. The algorithm is described in [1]_ and has
+    complexity O(num_colors * n**2).
+
+    Parameters
+    ----------
+    G : networkX graph
+       The nodes of this graph will be colored.
+
+    num_colors : number of colors to use
+       This number must be at least one more than the maximum degree of nodes
+       in the graph.
+
+    Returns
+    -------
+    A dictionary with keys representing nodes and values representing
+    corresponding coloring.
+
+    Examples
+    --------
+    >>> G = nx.cycle_graph(4)
+    >>> nx.coloring.equitable_color(G, num_colors=3)  # doctest: +SKIP
+    {0: 2, 1: 1, 2: 2, 3: 0}
+
+    Raises
+    ------
+    NetworkXAlgorithmError
+        If `num_colors` is not at least the maximum degree of the graph `G`
+
+    References
+    ----------
+    .. [1] Kierstead, H. A., Kostochka, A. V., Mydlarz, M., & Szemerédi, E.
+        (2010). A fast algorithm for equitable coloring. Combinatorica, 30(2),
+        217-224.
+    """
+
+    # Map nodes to integers for simplicity later.
+    nodes_to_int = {}
+    int_to_nodes = {}
+
+    for idx, node in enumerate(G.nodes):
+        nodes_to_int[node] = idx
+        int_to_nodes[idx] = node
+
+    G = nx.relabel_nodes(G, nodes_to_int, copy=True)
+
+    # Basic graph statistics and sanity check.
+    if len(G.nodes) > 0:
+        r_ = max(G.degree(node) for node in G.nodes)
+    else:
+        r_ = 0
+
+    if r_ >= num_colors:
+        raise nx.NetworkXAlgorithmError(
+            f"Graph has maximum degree {r_}, needs "
+            f"{r_ + 1} (> {num_colors}) colors for guaranteed coloring."
+        )
+
+    # Ensure that the number of nodes in G is a multiple of (r + 1)
+    pad_graph(G, num_colors)
+
+    # Starting the algorithm.
+    # L = {node: list(G.neighbors(node)) for node in G.nodes}
+    L_ = {node: [] for node in G.nodes}
+
+    # Arbitrary equitable allocation of colors to nodes.
+    F = {node: idx % num_colors for idx, node in enumerate(G.nodes)}
+
+    C = make_C_from_F(F)
+
+    # The neighborhood is empty initially.
+    N = make_N_from_L_C(L_, C)
+
+    # Currently all nodes witness all edges.
+    H = make_H_from_C_N(C, N)
+
+    # Start of algorithm.
+    edges_seen = set()
+
+    for u in sorted(G.nodes):
+        for v in sorted(G.neighbors(u)):
+            # Do not double count edges if (v, u) has already been seen.
+            if (v, u) in edges_seen:
+                continue
+
+            edges_seen.add((u, v))
+
+            L_[u].append(v)
+            L_[v].append(u)
+
+            N[(u, F[v])] += 1
+            N[(v, F[u])] += 1
+
+            if F[u] != F[v]:
+                # Were 'u' and 'v' witnesses for F[u] -> F[v] or F[v] -> F[u]?
+                if N[(u, F[v])] == 1:
+                    H[F[u], F[v]] -= 1  # u cannot witness an edge between F[u], F[v]
+
+                if N[(v, F[u])] == 1:
+                    H[F[v], F[u]] -= 1  # v cannot witness an edge between F[v], F[u]
+
+        if N[(u, F[u])] != 0:
+            # Find the first color where 'u' does not have any neighbors.
+            Y = next(k for k in C if N[(u, k)] == 0)
+            X = F[u]
+            change_color(u, X, Y, N=N, H=H, F=F, C=C, L=L_)
+
+            # Procedure P
+            procedure_P(V_minus=X, V_plus=Y, N=N, H=H, F=F, C=C, L=L_)
+
+    return {int_to_nodes[x]: F[x] for x in int_to_nodes}
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/coloring/greedy_coloring.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/coloring/greedy_coloring.py
new file mode 100644
index 0000000000000000000000000000000000000000..311bc3a929f76dc2cac0b85bc02459ce0a29ffd0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/coloring/greedy_coloring.py
@@ -0,0 +1,565 @@
+"""
+Greedy graph coloring using various strategies.
+"""
+
+import itertools
+from collections import defaultdict, deque
+
+import networkx as nx
+from networkx.utils import arbitrary_element, py_random_state
+
+__all__ = [
+    "greedy_color",
+    "strategy_connected_sequential",
+    "strategy_connected_sequential_bfs",
+    "strategy_connected_sequential_dfs",
+    "strategy_independent_set",
+    "strategy_largest_first",
+    "strategy_random_sequential",
+    "strategy_saturation_largest_first",
+    "strategy_smallest_last",
+]
+
+
+def strategy_largest_first(G, colors):
+    """Returns a list of the nodes of ``G`` in decreasing order by
+    degree.
+
+    ``G`` is a NetworkX graph. ``colors`` is ignored.
+
+    """
+    return sorted(G, key=G.degree, reverse=True)
+
+
+@py_random_state(2)
+def strategy_random_sequential(G, colors, seed=None):
+    """Returns a random permutation of the nodes of ``G`` as a list.
+
+    ``G`` is a NetworkX graph. ``colors`` is ignored.
+
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    """
+    nodes = list(G)
+    seed.shuffle(nodes)
+    return nodes
+
+
+def strategy_smallest_last(G, colors):
+    """Returns a deque of the nodes of ``G``, "smallest" last.
+
+    Specifically, the degrees of each node are tracked in a bucket queue.
+    From this, the node of minimum degree is repeatedly popped from the
+    graph, updating its neighbors' degrees.
+
+    ``G`` is a NetworkX graph. ``colors`` is ignored.
+
+    This implementation of the strategy runs in $O(n + m)$ time
+    (ignoring polylogarithmic factors), where $n$ is the number of nodes
+    and $m$ is the number of edges.
+
+    This strategy is related to :func:`strategy_independent_set`: if we
+    interpret each node removed as an independent set of size one, then
+    this strategy chooses an independent set of size one instead of a
+    maximal independent set.
+
+    """
+    H = G.copy()
+    result = deque()
+
+    # Build initial degree list (i.e. the bucket queue data structure)
+    degrees = defaultdict(set)  # set(), for fast random-access removals
+    lbound = float("inf")
+    for node, d in H.degree():
+        degrees[d].add(node)
+        lbound = min(lbound, d)  # Lower bound on min-degree.
+
+    def find_min_degree():
+        # Save time by starting the iterator at `lbound`, not 0.
+        # The value that we find will be our new `lbound`, which we set later.
+        return next(d for d in itertools.count(lbound) if d in degrees)
+
+    for _ in G:
+        # Pop a min-degree node and add it to the list.
+        min_degree = find_min_degree()
+        u = degrees[min_degree].pop()
+        if not degrees[min_degree]:  # Clean up the degree list.
+            del degrees[min_degree]
+        result.appendleft(u)
+
+        # Update degrees of removed node's neighbors.
+        for v in H[u]:
+            degree = H.degree(v)
+            degrees[degree].remove(v)
+            if not degrees[degree]:  # Clean up the degree list.
+                del degrees[degree]
+            degrees[degree - 1].add(v)
+
+        # Finally, remove the node.
+        H.remove_node(u)
+        lbound = min_degree - 1  # Subtract 1 in case of tied neighbors.
+
+    return result
+
+
+def _maximal_independent_set(G):
+    """Returns a maximal independent set of nodes in ``G`` by repeatedly
+    choosing an independent node of minimum degree (with respect to the
+    subgraph of unchosen nodes).
+
+    """
+    result = set()
+    remaining = set(G)
+    while remaining:
+        G = G.subgraph(remaining)
+        v = min(remaining, key=G.degree)
+        result.add(v)
+        remaining -= set(G[v]) | {v}
+    return result
+
+
+def strategy_independent_set(G, colors):
+    """Uses a greedy independent set removal strategy to determine the
+    colors.
+
+    This function updates ``colors`` **in-place** and return ``None``,
+    unlike the other strategy functions in this module.
+
+    This algorithm repeatedly finds and removes a maximal independent
+    set, assigning each node in the set an unused color.
+
+    ``G`` is a NetworkX graph.
+
+    This strategy is related to :func:`strategy_smallest_last`: in that
+    strategy, an independent set of size one is chosen at each step
+    instead of a maximal independent set.
+
+    """
+    remaining_nodes = set(G)
+    while len(remaining_nodes) > 0:
+        nodes = _maximal_independent_set(G.subgraph(remaining_nodes))
+        remaining_nodes -= nodes
+        yield from nodes
+
+
+def strategy_connected_sequential_bfs(G, colors):
+    """Returns an iterable over nodes in ``G`` in the order given by a
+    breadth-first traversal.
+
+    The generated sequence has the property that for each node except
+    the first, at least one neighbor appeared earlier in the sequence.
+
+    ``G`` is a NetworkX graph. ``colors`` is ignored.
+
+    """
+    return strategy_connected_sequential(G, colors, "bfs")
+
+
+def strategy_connected_sequential_dfs(G, colors):
+    """Returns an iterable over nodes in ``G`` in the order given by a
+    depth-first traversal.
+
+    The generated sequence has the property that for each node except
+    the first, at least one neighbor appeared earlier in the sequence.
+
+    ``G`` is a NetworkX graph. ``colors`` is ignored.
+
+    """
+    return strategy_connected_sequential(G, colors, "dfs")
+
+
+def strategy_connected_sequential(G, colors, traversal="bfs"):
+    """Returns an iterable over nodes in ``G`` in the order given by a
+    breadth-first or depth-first traversal.
+
+    ``traversal`` must be one of the strings ``'dfs'`` or ``'bfs'``,
+    representing depth-first traversal or breadth-first traversal,
+    respectively.
+
+    The generated sequence has the property that for each node except
+    the first, at least one neighbor appeared earlier in the sequence.
+
+    ``G`` is a NetworkX graph. ``colors`` is ignored.
+
+    """
+    if traversal == "bfs":
+        traverse = nx.bfs_edges
+    elif traversal == "dfs":
+        traverse = nx.dfs_edges
+    else:
+        raise nx.NetworkXError(
+            "Please specify one of the strings 'bfs' or"
+            " 'dfs' for connected sequential ordering"
+        )
+    for component in nx.connected_components(G):
+        source = arbitrary_element(component)
+        # Yield the source node, then all the nodes in the specified
+        # traversal order.
+        yield source
+        for _, end in traverse(G.subgraph(component), source):
+            yield end
+
+
+def strategy_saturation_largest_first(G, colors):
+    """Iterates over all the nodes of ``G`` in "saturation order" (also
+    known as "DSATUR").
+
+    ``G`` is a NetworkX graph. ``colors`` is a dictionary mapping nodes of
+    ``G`` to colors, for those nodes that have already been colored.
+
+    """
+    distinct_colors = {v: set() for v in G}
+
+    # Add the node color assignments given in colors to the
+    # distinct colors set for each neighbor of that node
+    for node, color in colors.items():
+        for neighbor in G[node]:
+            distinct_colors[neighbor].add(color)
+
+    # Check that the color assignments in colors are valid
+    # i.e. no neighboring nodes have the same color
+    if len(colors) >= 2:
+        for node, color in colors.items():
+            if color in distinct_colors[node]:
+                raise nx.NetworkXError("Neighboring nodes must have different colors")
+
+    # If 0 nodes have been colored, simply choose the node of highest degree.
+    if not colors:
+        node = max(G, key=G.degree)
+        yield node
+        # Add the color 0 to the distinct colors set for each
+        # neighbor of that node.
+        for v in G[node]:
+            distinct_colors[v].add(0)
+
+    while len(G) != len(colors):
+        # Update the distinct color sets for the neighbors.
+        for node, color in colors.items():
+            for neighbor in G[node]:
+                distinct_colors[neighbor].add(color)
+
+        # Compute the maximum saturation and the set of nodes that
+        # achieve that saturation.
+        saturation = {v: len(c) for v, c in distinct_colors.items() if v not in colors}
+        # Yield the node with the highest saturation, and break ties by
+        # degree.
+        node = max(saturation, key=lambda v: (saturation[v], G.degree(v)))
+        yield node
+
+
+#: Dictionary mapping name of a strategy as a string to the strategy function.
+STRATEGIES = {
+    "largest_first": strategy_largest_first,
+    "random_sequential": strategy_random_sequential,
+    "smallest_last": strategy_smallest_last,
+    "independent_set": strategy_independent_set,
+    "connected_sequential_bfs": strategy_connected_sequential_bfs,
+    "connected_sequential_dfs": strategy_connected_sequential_dfs,
+    "connected_sequential": strategy_connected_sequential,
+    "saturation_largest_first": strategy_saturation_largest_first,
+    "DSATUR": strategy_saturation_largest_first,
+}
+
+
+@nx._dispatchable
+def greedy_color(G, strategy="largest_first", interchange=False):
+    """Color a graph using various strategies of greedy graph coloring.
+
+    Attempts to color a graph using as few colors as possible, where no
+    neighbors of a node can have same color as the node itself. The
+    given strategy determines the order in which nodes are colored.
+
+    The strategies are described in [1]_, and smallest-last is based on
+    [2]_.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    strategy : string or function(G, colors)
+       A function (or a string representing a function) that provides
+       the coloring strategy, by returning nodes in the ordering they
+       should be colored. ``G`` is the graph, and ``colors`` is a
+       dictionary of the currently assigned colors, keyed by nodes. The
+       function must return an iterable over all the nodes in ``G``.
+
+       If the strategy function is an iterator generator (that is, a
+       function with ``yield`` statements), keep in mind that the
+       ``colors`` dictionary will be updated after each ``yield``, since
+       this function chooses colors greedily.
+
+       If ``strategy`` is a string, it must be one of the following,
+       each of which represents one of the built-in strategy functions.
+
+       * ``'largest_first'``
+       * ``'random_sequential'``
+       * ``'smallest_last'``
+       * ``'independent_set'``
+       * ``'connected_sequential_bfs'``
+       * ``'connected_sequential_dfs'``
+       * ``'connected_sequential'`` (alias for the previous strategy)
+       * ``'saturation_largest_first'``
+       * ``'DSATUR'`` (alias for the previous strategy)
+
+    interchange: bool
+       Will use the color interchange algorithm described by [3]_ if set
+       to ``True``.
+
+       Note that ``saturation_largest_first`` and ``independent_set``
+       do not work with interchange. Furthermore, if you use
+       interchange with your own strategy function, you cannot rely
+       on the values in the ``colors`` argument.
+
+    Returns
+    -------
+    A dictionary with keys representing nodes and values representing
+    corresponding coloring.
+
+    Examples
+    --------
+    >>> G = nx.cycle_graph(4)
+    >>> d = nx.coloring.greedy_color(G, strategy="largest_first")
+    >>> d in [{0: 0, 1: 1, 2: 0, 3: 1}, {0: 1, 1: 0, 2: 1, 3: 0}]
+    True
+
+    Raises
+    ------
+    NetworkXPointlessConcept
+        If ``strategy`` is ``saturation_largest_first`` or
+        ``independent_set`` and ``interchange`` is ``True``.
+
+    References
+    ----------
+    .. [1] Adrian Kosowski, and Krzysztof Manuszewski,
+       Classical Coloring of Graphs, Graph Colorings, 2-19, 2004.
+       ISBN 0-8218-3458-4.
+    .. [2] David W. Matula, and Leland L. Beck, "Smallest-last
+       ordering and clustering and graph coloring algorithms." *J. ACM* 30,
+       3 (July 1983), 417–427. 
+    .. [3] Maciej M. Sysło, Narsingh Deo, Janusz S. Kowalik,
+       Discrete Optimization Algorithms with Pascal Programs, 415-424, 1983.
+       ISBN 0-486-45353-7.
+
+    """
+    if len(G) == 0:
+        return {}
+    # Determine the strategy provided by the caller.
+    strategy = STRATEGIES.get(strategy, strategy)
+    if not callable(strategy):
+        raise nx.NetworkXError(
+            f"strategy must be callable or a valid string. {strategy} not valid."
+        )
+    # Perform some validation on the arguments before executing any
+    # strategy functions.
+    if interchange:
+        if strategy is strategy_independent_set:
+            msg = "interchange cannot be used with independent_set"
+            raise nx.NetworkXPointlessConcept(msg)
+        if strategy is strategy_saturation_largest_first:
+            msg = "interchange cannot be used with saturation_largest_first"
+            raise nx.NetworkXPointlessConcept(msg)
+    colors = {}
+    nodes = strategy(G, colors)
+    if interchange:
+        return _greedy_coloring_with_interchange(G, nodes)
+    for u in nodes:
+        # Set to keep track of colors of neighbors
+        nbr_colors = {colors[v] for v in G[u] if v in colors}
+        # Find the first unused color.
+        for color in itertools.count():
+            if color not in nbr_colors:
+                break
+        # Assign the new color to the current node.
+        colors[u] = color
+    return colors
+
+
+# Tools for coloring with interchanges
+class _Node:
+    __slots__ = ["node_id", "color", "adj_list", "adj_color"]
+
+    def __init__(self, node_id, n):
+        self.node_id = node_id
+        self.color = -1
+        self.adj_list = None
+        self.adj_color = [None for _ in range(n)]
+
+    def __repr__(self):
+        return (
+            f"Node_id: {self.node_id}, Color: {self.color}, "
+            f"Adj_list: ({self.adj_list}), adj_color: ({self.adj_color})"
+        )
+
+    def assign_color(self, adj_entry, color):
+        adj_entry.col_prev = None
+        adj_entry.col_next = self.adj_color[color]
+        self.adj_color[color] = adj_entry
+        if adj_entry.col_next is not None:
+            adj_entry.col_next.col_prev = adj_entry
+
+    def clear_color(self, adj_entry, color):
+        if adj_entry.col_prev is None:
+            self.adj_color[color] = adj_entry.col_next
+        else:
+            adj_entry.col_prev.col_next = adj_entry.col_next
+        if adj_entry.col_next is not None:
+            adj_entry.col_next.col_prev = adj_entry.col_prev
+
+    def iter_neighbors(self):
+        adj_node = self.adj_list
+        while adj_node is not None:
+            yield adj_node
+            adj_node = adj_node.next
+
+    def iter_neighbors_color(self, color):
+        adj_color_node = self.adj_color[color]
+        while adj_color_node is not None:
+            yield adj_color_node.node_id
+            adj_color_node = adj_color_node.col_next
+
+
+class _AdjEntry:
+    __slots__ = ["node_id", "next", "mate", "col_next", "col_prev"]
+
+    def __init__(self, node_id):
+        self.node_id = node_id
+        self.next = None
+        self.mate = None
+        self.col_next = None
+        self.col_prev = None
+
+    def __repr__(self):
+        col_next = None if self.col_next is None else self.col_next.node_id
+        col_prev = None if self.col_prev is None else self.col_prev.node_id
+        return (
+            f"Node_id: {self.node_id}, Next: ({self.next}), "
+            f"Mate: ({self.mate.node_id}), "
+            f"col_next: ({col_next}), col_prev: ({col_prev})"
+        )
+
+
+def _greedy_coloring_with_interchange(G, nodes):
+    """Return a coloring for `original_graph` using interchange approach
+
+    This procedure is an adaption of the algorithm described by [1]_,
+    and is an implementation of coloring with interchange. Please be
+    advised, that the datastructures used are rather complex because
+    they are optimized to minimize the time spent identifying
+    subcomponents of the graph, which are possible candidates for color
+    interchange.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        The graph to be colored
+
+    nodes : list
+        nodes ordered using the strategy of choice
+
+    Returns
+    -------
+    dict :
+        A dictionary keyed by node to a color value
+
+    References
+    ----------
+    .. [1] Maciej M. Syslo, Narsingh Deo, Janusz S. Kowalik,
+       Discrete Optimization Algorithms with Pascal Programs, 415-424, 1983.
+       ISBN 0-486-45353-7.
+    """
+    n = len(G)
+
+    graph = {node: _Node(node, n) for node in G}
+
+    for node1, node2 in G.edges():
+        adj_entry1 = _AdjEntry(node2)
+        adj_entry2 = _AdjEntry(node1)
+        adj_entry1.mate = adj_entry2
+        adj_entry2.mate = adj_entry1
+        node1_head = graph[node1].adj_list
+        adj_entry1.next = node1_head
+        graph[node1].adj_list = adj_entry1
+        node2_head = graph[node2].adj_list
+        adj_entry2.next = node2_head
+        graph[node2].adj_list = adj_entry2
+
+    k = 0
+    for node in nodes:
+        # Find the smallest possible, unused color
+        neighbors = graph[node].iter_neighbors()
+        col_used = {graph[adj_node.node_id].color for adj_node in neighbors}
+        col_used.discard(-1)
+        k1 = next(itertools.dropwhile(lambda x: x in col_used, itertools.count()))
+
+        # k1 is now the lowest available color
+        if k1 > k:
+            connected = True
+            visited = set()
+            col1 = -1
+            col2 = -1
+            while connected and col1 < k:
+                col1 += 1
+                neighbor_cols = graph[node].iter_neighbors_color(col1)
+                col1_adj = list(neighbor_cols)
+
+                col2 = col1
+                while connected and col2 < k:
+                    col2 += 1
+                    visited = set(col1_adj)
+                    frontier = list(col1_adj)
+                    i = 0
+                    while i < len(frontier):
+                        search_node = frontier[i]
+                        i += 1
+                        col_opp = col2 if graph[search_node].color == col1 else col1
+                        neighbor_cols = graph[search_node].iter_neighbors_color(col_opp)
+
+                        for neighbor in neighbor_cols:
+                            if neighbor not in visited:
+                                visited.add(neighbor)
+                                frontier.append(neighbor)
+
+                    # Search if node is not adj to any col2 vertex
+                    connected = (
+                        len(
+                            visited.intersection(graph[node].iter_neighbors_color(col2))
+                        )
+                        > 0
+                    )
+
+            # If connected is false then we can swap !!!
+            if not connected:
+                # Update all the nodes in the component
+                for search_node in visited:
+                    graph[search_node].color = (
+                        col2 if graph[search_node].color == col1 else col1
+                    )
+                    col2_adj = graph[search_node].adj_color[col2]
+                    graph[search_node].adj_color[col2] = graph[search_node].adj_color[
+                        col1
+                    ]
+                    graph[search_node].adj_color[col1] = col2_adj
+
+                # Update all the neighboring nodes
+                for search_node in visited:
+                    col = graph[search_node].color
+                    col_opp = col1 if col == col2 else col2
+                    for adj_node in graph[search_node].iter_neighbors():
+                        if graph[adj_node.node_id].color != col_opp:
+                            # Direct reference to entry
+                            adj_mate = adj_node.mate
+                            graph[adj_node.node_id].clear_color(adj_mate, col_opp)
+                            graph[adj_node.node_id].assign_color(adj_mate, col)
+                k1 = col1
+
+        # We can color this node color k1
+        graph[node].color = k1
+        k = max(k1, k)
+
+        # Update the neighbors of this node
+        for adj_node in graph[node].iter_neighbors():
+            adj_mate = adj_node.mate
+            graph[adj_node.node_id].assign_color(adj_mate, k1)
+
+    return {node.node_id: node.color for node in graph.values()}
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/communicability_alg.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/communicability_alg.py
new file mode 100644
index 0000000000000000000000000000000000000000..dea156b633a2b367c184f4bf31ab465812de68b4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/communicability_alg.py
@@ -0,0 +1,163 @@
+"""
+Communicability.
+"""
+
+import networkx as nx
+from networkx.utils import not_implemented_for
+
+__all__ = ["communicability", "communicability_exp"]
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable
+def communicability(G):
+    r"""Returns communicability between all pairs of nodes in G.
+
+    The communicability between pairs of nodes in G is the sum of
+    walks of different lengths starting at node u and ending at node v.
+
+    Parameters
+    ----------
+    G: graph
+
+    Returns
+    -------
+    comm: dictionary of dictionaries
+        Dictionary of dictionaries keyed by nodes with communicability
+        as the value.
+
+    Raises
+    ------
+    NetworkXError
+       If the graph is not undirected and simple.
+
+    See Also
+    --------
+    communicability_exp:
+       Communicability between all pairs of nodes in G  using spectral
+       decomposition.
+    communicability_betweenness_centrality:
+       Communicability betweenness centrality for each node in G.
+
+    Notes
+    -----
+    This algorithm uses a spectral decomposition of the adjacency matrix.
+    Let G=(V,E) be a simple undirected graph.  Using the connection between
+    the powers  of the adjacency matrix and the number of walks in the graph,
+    the communicability  between nodes `u` and `v` based on the graph spectrum
+    is [1]_
+
+    .. math::
+        C(u,v)=\sum_{j=1}^{n}\phi_{j}(u)\phi_{j}(v)e^{\lambda_{j}},
+
+    where `\phi_{j}(u)` is the `u\rm{th}` element of the `j\rm{th}` orthonormal
+    eigenvector of the adjacency matrix associated with the eigenvalue
+    `\lambda_{j}`.
+
+    References
+    ----------
+    .. [1] Ernesto Estrada, Naomichi Hatano,
+       "Communicability in complex networks",
+       Phys. Rev. E 77, 036111 (2008).
+       https://arxiv.org/abs/0707.0756
+
+    Examples
+    --------
+    >>> G = nx.Graph([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)])
+    >>> c = nx.communicability(G)
+    """
+    import numpy as np
+
+    nodelist = list(G)  # ordering of nodes in matrix
+    A = nx.to_numpy_array(G, nodelist)
+    # convert to 0-1 matrix
+    A[A != 0.0] = 1
+    w, vec = np.linalg.eigh(A)
+    expw = np.exp(w)
+    mapping = dict(zip(nodelist, range(len(nodelist))))
+    c = {}
+    # computing communicabilities
+    for u in G:
+        c[u] = {}
+        for v in G:
+            s = 0
+            p = mapping[u]
+            q = mapping[v]
+            for j in range(len(nodelist)):
+                s += vec[:, j][p] * vec[:, j][q] * expw[j]
+            c[u][v] = float(s)
+    return c
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable
+def communicability_exp(G):
+    r"""Returns communicability between all pairs of nodes in G.
+
+    Communicability between pair of node (u,v) of node in G is the sum of
+    walks of different lengths starting at node u and ending at node v.
+
+    Parameters
+    ----------
+    G: graph
+
+    Returns
+    -------
+    comm: dictionary of dictionaries
+        Dictionary of dictionaries keyed by nodes with communicability
+        as the value.
+
+    Raises
+    ------
+    NetworkXError
+        If the graph is not undirected and simple.
+
+    See Also
+    --------
+    communicability:
+       Communicability between pairs of nodes in G.
+    communicability_betweenness_centrality:
+       Communicability betweenness centrality for each node in G.
+
+    Notes
+    -----
+    This algorithm uses matrix exponentiation of the adjacency matrix.
+
+    Let G=(V,E) be a simple undirected graph.  Using the connection between
+    the powers  of the adjacency matrix and the number of walks in the graph,
+    the communicability between nodes u and v is [1]_,
+
+    .. math::
+        C(u,v) = (e^A)_{uv},
+
+    where `A` is the adjacency matrix of G.
+
+    References
+    ----------
+    .. [1] Ernesto Estrada, Naomichi Hatano,
+       "Communicability in complex networks",
+       Phys. Rev. E 77, 036111 (2008).
+       https://arxiv.org/abs/0707.0756
+
+    Examples
+    --------
+    >>> G = nx.Graph([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)])
+    >>> c = nx.communicability_exp(G)
+    """
+    import scipy as sp
+
+    nodelist = list(G)  # ordering of nodes in matrix
+    A = nx.to_numpy_array(G, nodelist)
+    # convert to 0-1 matrix
+    A[A != 0.0] = 1
+    # communicability matrix
+    expA = sp.linalg.expm(A)
+    mapping = dict(zip(nodelist, range(len(nodelist))))
+    c = {}
+    for u in G:
+        c[u] = {}
+        for v in G:
+            c[u][v] = float(expA[mapping[u], mapping[v]])
+    return c
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8014032c41e195bee307e4c638c627ca2ddf16c6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/__init__.py
@@ -0,0 +1,28 @@
+"""Functions for computing and measuring community structure.
+
+The ``community`` subpackage can be accessed by using :mod:`networkx.community`, then accessing the
+functions as attributes of ``community``. For example::
+
+    >>> import networkx as nx
+    >>> G = nx.barbell_graph(5, 1)
+    >>> communities_generator = nx.community.girvan_newman(G)
+    >>> top_level_communities = next(communities_generator)
+    >>> next_level_communities = next(communities_generator)
+    >>> sorted(map(sorted, next_level_communities))
+    [[0, 1, 2, 3, 4], [5], [6, 7, 8, 9, 10]]
+
+"""
+
+from networkx.algorithms.community.asyn_fluid import *
+from networkx.algorithms.community.bipartitions import *
+from networkx.algorithms.community.centrality import *
+from networkx.algorithms.community.divisive import *
+from networkx.algorithms.community.kclique import *
+from networkx.algorithms.community.label_propagation import *
+from networkx.algorithms.community.lukes import *
+from networkx.algorithms.community.modularity_max import *
+from networkx.algorithms.community.quality import *
+from networkx.algorithms.community.community_utils import *
+from networkx.algorithms.community.louvain import *
+from networkx.algorithms.community.leiden import *
+from networkx.algorithms.community.local import *
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/asyn_fluid.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/asyn_fluid.py
new file mode 100644
index 0000000000000000000000000000000000000000..47a4dfcaa36ac5136d582ae28d92ee9210d90286
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/asyn_fluid.py
@@ -0,0 +1,153 @@
+"""Asynchronous Fluid Communities algorithm for community detection."""
+
+from collections import Counter
+
+import networkx as nx
+from networkx.algorithms.components import is_connected
+from networkx.exception import NetworkXError
+from networkx.utils import groups, not_implemented_for, py_random_state
+
+__all__ = ["asyn_fluidc"]
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@py_random_state(3)
+@nx._dispatchable
+def asyn_fluidc(G, k, max_iter=100, seed=None):
+    """Returns communities in `G` as detected by Fluid Communities algorithm.
+
+    The asynchronous fluid communities algorithm is described in
+    [1]_. The algorithm is based on the simple idea of fluids interacting
+    in an environment, expanding and pushing each other. Its initialization is
+    random, so found communities may vary on different executions.
+
+    The algorithm proceeds as follows. First each of the initial k communities
+    is initialized in a random vertex in the graph. Then the algorithm iterates
+    over all vertices in a random order, updating the community of each vertex
+    based on its own community and the communities of its neighbors. This
+    process is performed several times until convergence.
+    At all times, each community has a total density of 1, which is equally
+    distributed among the vertices it contains. If a vertex changes of
+    community, vertex densities of affected communities are adjusted
+    immediately. When a complete iteration over all vertices is done, such that
+    no vertex changes the community it belongs to, the algorithm has converged
+    and returns.
+
+    This is the original version of the algorithm described in [1]_.
+    Unfortunately, it does not support weighted graphs yet.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        Graph must be simple and undirected.
+
+    k : integer
+        The number of communities to be found.
+
+    max_iter : integer
+        The number of maximum iterations allowed. By default 100.
+
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    communities : iterable
+        Iterable of communities given as sets of nodes.
+
+    Notes
+    -----
+    k variable is not an optional argument.
+
+    References
+    ----------
+    .. [1] Parés F., Garcia-Gasulla D. et al. "Fluid Communities: A
+       Competitive and Highly Scalable Community Detection Algorithm".
+       [https://arxiv.org/pdf/1703.09307.pdf].
+    """
+    # Initial checks
+    if not isinstance(k, int):
+        raise NetworkXError("k must be an integer.")
+    if not k > 0:
+        raise NetworkXError("k must be greater than 0.")
+    if not is_connected(G):
+        raise NetworkXError("Fluid Communities require connected Graphs.")
+    if len(G) < k:
+        raise NetworkXError("k cannot be bigger than the number of nodes.")
+    if max_iter <= 0:
+        msg = f"{max_iter=} must be greater than 0"
+        raise ValueError(msg)
+    # Initialization
+    max_density = 1.0
+    vertices = list(G)
+    seed.shuffle(vertices)
+    communities = {n: i for i, n in enumerate(vertices[:k])}
+    density = {}
+    com_to_numvertices = {}
+    for vertex in communities:
+        com_to_numvertices[communities[vertex]] = 1
+        density[communities[vertex]] = max_density
+    # Set up control variables and start iterating
+    iter_count = 0
+    cont = True
+    while cont and iter_count < max_iter:
+        cont = False
+        iter_count += 1
+        # Loop over all vertices in graph in a random order
+        vertices = list(G)
+        seed.shuffle(vertices)
+        for vertex in vertices:
+            # Updating rule
+            com_counter = Counter()
+            # Take into account self vertex community
+            try:
+                com_counter.update({communities[vertex]: density[communities[vertex]]})
+            except KeyError:
+                pass
+            # Gather neighbor vertex communities
+            for v in G[vertex]:
+                try:
+                    com_counter.update({communities[v]: density[communities[v]]})
+                except KeyError:
+                    continue
+            # Check which is the community with highest density
+            new_com = -1
+            if len(com_counter.keys()) > 0:
+                max_freq = max(com_counter.values())
+                best_communities = [
+                    com
+                    for com, freq in com_counter.items()
+                    if (max_freq - freq) < 0.0001
+                ]
+                # If actual vertex com in best communities, it is preserved
+                try:
+                    if communities[vertex] in best_communities:
+                        new_com = communities[vertex]
+                except KeyError:
+                    pass
+
+                # If vertex community changes...
+                if new_com == -1:
+                    # Set flag of non-convergence
+                    cont = True
+                    # Randomly chose a new community from candidates
+                    new_com = seed.choice(best_communities)
+                    # Update previous community status
+                    try:
+                        com_to_numvertices[communities[vertex]] -= 1
+                        density[communities[vertex]] = (
+                            max_density / com_to_numvertices[communities[vertex]]
+                        )
+                    except KeyError:
+                        pass
+                    # Update new community status
+                    communities[vertex] = new_com
+                    com_to_numvertices[communities[vertex]] += 1
+                    density[communities[vertex]] = (
+                        max_density / com_to_numvertices[communities[vertex]]
+                    )
+    # If maximum iterations reached --> output actual results
+    # Return results by grouping communities as list of vertices
+    return iter(groups(communities).values())
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/bipartitions.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/bipartitions.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e0b44d6138850a85b179e9e19608a757230b9d3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/bipartitions.py
@@ -0,0 +1,354 @@
+"""Functions for splitting a network into two communities (finding a bipartition)."""
+
+import random
+from copy import deepcopy
+from itertools import count
+
+import networkx as nx
+
+__all__ = [
+    "kernighan_lin_bisection",
+    "spectral_modularity_bipartition",
+    "greedy_node_swap_bipartition",
+]
+
+
+def _kernighan_lin_sweep(edge_info, side):
+    """
+    This is a modified form of Kernighan-Lin, which moves single nodes at a
+    time, alternating between sides to keep the bisection balanced.  We keep
+    two min-heaps of swap costs to make optimal-next-move selection fast.
+    """
+    heap0, heap1 = cost_heaps = nx.utils.BinaryHeap(), nx.utils.BinaryHeap()
+    # we use heap methods insert, pop, and get
+    for u, nbrs in edge_info.items():
+        cost_u = sum(wt if side[v] else -wt for v, wt in nbrs.items())
+        if side[u]:
+            heap1.insert(u, cost_u)
+        else:
+            heap0.insert(u, -cost_u)
+
+    def _update_heap_values(node):
+        side_node = side[node]
+        for nbr, wt in edge_info[node].items():
+            side_nbr = side[nbr]
+            if side_nbr == side_node:
+                wt = -wt
+            heap_nbr = cost_heaps[side_nbr]
+            if nbr in heap_nbr:
+                cost_nbr = heap_nbr.get(nbr) + 2 * wt
+                # allow_increase lets us update a value already on the heap
+                heap_nbr.insert(nbr, cost_nbr, allow_increase=True)
+
+    i = 0
+    totcost = 0
+    while heap0 and heap1:
+        u, cost_u = heap0.pop()
+        _update_heap_values(u)
+        v, cost_v = heap1.pop()
+        _update_heap_values(v)
+        totcost += cost_u + cost_v
+        i += 1
+        yield totcost, i, (u, v)
+
+
+@nx.utils.not_implemented_for("directed")
+@nx.utils.py_random_state(4)
+@nx._dispatchable(edge_attrs="weight")
+def kernighan_lin_bisection(G, partition=None, max_iter=10, weight="weight", seed=None):
+    """Partition a graph into two blocks using the Kernighan–Lin algorithm.
+
+    This algorithm partitions a network into two sets by iteratively
+    swapping pairs of nodes to reduce the edge cut between the two sets.  The
+    pairs are chosen according to a modified form of Kernighan-Lin [1]_, which
+    moves nodes individually, alternating between sides to keep the bisection
+    balanced.
+
+    Kernighan-Lin is an approximate algorithm for maximal modularity bisection.
+    In [2]_ they suggest that fine-tuned improvements can be made using
+    greedy node swapping, (see `greedy_node_swap_bipartition`).
+    The improvements are typically only a few percent of the modularity value.
+    But they claim that can make a difference between a good and excellent method.
+    This function does not perform any improvements. But you can do that yourself.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        Graph must be undirected.
+
+    partition : tuple
+        Pair of iterables containing an initial partition. If not
+        specified, a random balanced partition is used.
+
+    max_iter : int
+        Maximum number of times to attempt swaps to find an
+        improvement before giving up.
+
+    weight : string or function (default: "weight")
+        If this is a string, then edge weights will be accessed via the
+        edge attribute with this key (that is, the weight of the edge
+        joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
+        such edge attribute exists, the weight of the edge is assumed to
+        be one.
+
+        If this is a function, the weight of an edge is the value
+        returned by the function. The function must accept exactly three
+        positional arguments: the two endpoints of an edge and the
+        dictionary of edge attributes for that edge. The function must
+        return a number or None to indicate a hidden edge.
+
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+        Only used if partition is None
+
+    Returns
+    -------
+    partition : tuple
+        A pair of sets of nodes representing the bipartition.
+
+    Raises
+    ------
+    NetworkXError
+        If `partition` is not a valid partition of the nodes of the graph.
+
+    References
+    ----------
+    .. [1] Kernighan, B. W.; Lin, Shen (1970).
+       "An efficient heuristic procedure for partitioning graphs."
+       *Bell Systems Technical Journal* 49: 291--307.
+       Oxford University Press 2011.
+    .. [2] M. E. J. Newman,
+       "Modularity and community structure in networks",
+       PNAS, 103 (23), p. 8577-8582,
+       https://doi.org/10.1073/pnas.0601602103
+
+    """
+    nodes = list(G)
+
+    if partition is None:
+        seed.shuffle(nodes)
+        mid = len(nodes) // 2
+        A, B = nodes[:mid], nodes[mid:]
+    else:
+        try:
+            A, B = partition
+        except (TypeError, ValueError) as err:
+            raise nx.NetworkXError("partition must be two sets") from err
+        if not nx.community.is_partition(G, [A, B]):
+            raise nx.NetworkXError("partition invalid")
+
+    side = {node: (node in A) for node in nodes}
+
+    # ruff: noqa: E731   skips check for no lambda functions
+    # Using shortest_paths _weight_function with sum instead of min on multiedges
+    if callable(weight):
+        sum_weight = weight
+    elif G.is_multigraph():
+        sum_weight = lambda u, v, d: sum(dd.get(weight, 1) for dd in d.values())
+    else:
+        sum_weight = lambda u, v, d: d.get(weight, 1)
+
+    edge_info = {
+        u: {v: wt for v, d in nbrs.items() if (wt := sum_weight(u, v, d)) is not None}
+        for u, nbrs in G._adj.items()
+    }
+
+    for i in range(max_iter):
+        costs = list(_kernighan_lin_sweep(edge_info, side))
+        # find out how many edges to update: min_i
+        min_cost, min_i, _ = min(costs)
+        if min_cost >= 0:
+            break
+
+        for _, _, (u, v) in costs[:min_i]:
+            side[u] = 1
+            side[v] = 0
+
+    part1 = {u for u, s in side.items() if s == 0}
+    part2 = {u for u, s in side.items() if s == 1}
+    return part1, part2
+
+
+@nx.utils.not_implemented_for("directed")
+@nx.utils.not_implemented_for("multigraph")
+def spectral_modularity_bipartition(G):
+    r"""Return a bipartition of the nodes based on the spectrum of the
+    modularity matrix of the graph.
+
+    This method calculates the eigenvector associated with the second
+    largest eigenvalue of the modularity matrix, where the modularity
+    matrix *B* is defined by
+
+    ..math::
+
+        B_{i j} = A_{i j} - \frac{k_i k_j}{2 m},
+
+    where *A* is the adjacency matrix, `k_i` is the degree of node *i*,
+    and *m* is the number of edges in the graph. Nodes whose
+    corresponding values in the eigenvector are negative are placed in
+    one block, nodes whose values are nonnegative are placed in another
+    block.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    Returns
+    -------
+    C : tuple
+        Pair of communities as two sets of nodes of ``G``, partitioned
+        according to second largest eigenvalue of the modularity matrix.
+
+    Examples
+    --------
+    >>> G = nx.karate_club_graph()
+    >>> MrHi, Officer = nx.community.spectral_modularity_bipartition(G)
+    >>> MrHi, Officer = sorted([sorted(MrHi), sorted(Officer)])
+    >>> MrHi
+    [0, 1, 2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 16, 17, 19, 21]
+    >>> Officer
+    [8, 9, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]
+
+    References
+    ----------
+    .. [1] M. E. J. Newman *Networks: An Introduction*, pages 373--378
+       Oxford University Press 2011.
+    .. [2] M. E. J. Newman,
+       "Modularity and community structure in networks",
+       PNAS, 103 (23), p. 8577-8582,
+       https://doi.org/10.1073/pnas.0601602103
+
+    """
+    import numpy as np
+
+    B = nx.linalg.modularity_matrix(G)
+    eigenvalues, eigenvectors = np.linalg.eig(B)
+    index = np.argsort(eigenvalues)[-1]
+    v2 = zip(np.real(eigenvectors[:, index]), G)
+    left, right = set(), set()
+    for u, n in v2:
+        if u < 0:
+            left.add(n)
+        else:
+            right.add(n)
+    return left, right
+
+
+@nx.utils.not_implemented_for("multigraph")
+def greedy_node_swap_bipartition(G, *, init_split=None, max_iter=10):
+    """Split the nodes into two communities based on greedy
+    modularity maximization.
+
+    The algorithm works by selecting a node to change communities which
+    will maximize the modularity. The swap is made and the community
+    structure with the highest modularity is kept.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    init_split : 2-tuple of sets of nodes
+        Pair of sets of nodes in ``G`` providing an initial bipartition
+        for the algorithm. If not specified, a random balanced partition
+        is used. If this pair of sets is not a partition of the nodes of `G`,
+        :exc:`NetworkXException` is raised.
+
+    max_iter : int
+      Maximum number of iterations of attempting swaps to find an improvement.
+
+    Returns
+    -------
+    max_split : 2-tuple of sets of nodes
+        Pair of sets of nodes of ``G``, partitioned according to a
+        node swap greedy modularity maximization algorithm.
+
+    Raises
+    ------
+    NetworkXError
+      if init_split is not a valid partition of the
+      graph into two communities or if G is a MultiGraph
+
+    Examples
+    --------
+    >>> G = nx.barbell_graph(3, 0)
+    >>> left, right = nx.community.greedy_node_swap_bipartition(G)
+    >>> # Sort the communities so the nodes appear in increasing order.
+    >>> left, right = sorted([sorted(left), sorted(right)])
+    >>> sorted(left)
+    [0, 1, 2]
+    >>> sorted(right)
+    [3, 4, 5]
+
+    Notes
+    -----
+    This function is not implemented for multigraphs.
+
+    References
+    ----------
+    .. [1] M. E. J. Newman "Networks: An Introduction", pages 373--375.
+       Oxford University Press 2011.
+
+    """
+    if init_split is None:
+        m1 = len(G) // 2
+        m2 = len(G) - m1
+        some_nodes = set(random.sample(list(G), m1))
+        other_nodes = {n for n in G if n not in some_nodes}
+        best_split_so_far = (some_nodes, other_nodes)
+    else:
+        if not nx.community.is_partition(G, init_split):
+            raise nx.NetworkXError("init_split is not a partition of G")
+        if not len(init_split) == 2:
+            raise nx.NetworkXError("init_split must be a bipartition")
+        best_split_so_far = deepcopy(init_split)
+
+    best_mod = nx.community.modularity(G, best_split_so_far)
+
+    max_split, max_mod = best_split_so_far, best_mod
+    its = 0
+    m = G.number_of_edges()
+    G_degree = dict(G.degree)
+
+    while max_mod >= best_mod and its < max_iter:
+        best_split_so_far = max_split
+        best_mod = max_mod
+        next_split = deepcopy(max_split)
+        next_mod = max_mod
+        nodes = set(G)
+        while nodes:
+            max_swap = -1
+            max_node = None
+            max_node_comm = None
+            left, right = next_split
+            leftd = sum(G_degree[n] for n in left)
+            rightd = sum(G_degree[n] for n in right)
+            for n in nodes:
+                if n in left:
+                    in_comm, out_comm = left, right
+                    in_deg, out_deg = leftd, rightd
+                else:
+                    in_comm, out_comm = right, left
+                    in_deg, out_deg = rightd, leftd
+
+                d_eii = -len(G[n].keys() & in_comm) / m
+                d_ejj = len(G[n].keys() & out_comm) / m
+                deg = G_degree[n]
+                d_sum_ai = (deg / (2 * m**2)) * (in_deg - out_deg - deg)
+                swap_change = d_eii + d_ejj + d_sum_ai
+
+                if swap_change > max_swap:
+                    max_swap = swap_change
+                    max_node = n
+                    max_node_comm = in_comm
+                    non_max_node_comm = out_comm
+            # swap the node from one comm to the other
+            max_node_comm.remove(max_node)
+            non_max_node_comm.add(max_node)
+            next_mod += max_swap
+            # deepcopy next_split each time it reaches a high (might go lower later)
+            if next_mod > max_mod:
+                max_split, max_mod = deepcopy(next_split), next_mod
+            nodes.remove(max_node)
+        its += 1
+    return best_split_so_far
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/centrality.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/centrality.py
new file mode 100644
index 0000000000000000000000000000000000000000..43281701d2b630710acba8f3cef6693356aa461a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/centrality.py
@@ -0,0 +1,171 @@
+"""Functions for computing communities based on centrality notions."""
+
+import networkx as nx
+
+__all__ = ["girvan_newman"]
+
+
+@nx._dispatchable(preserve_edge_attrs="most_valuable_edge")
+def girvan_newman(G, most_valuable_edge=None):
+    """Finds communities in a graph using the Girvan–Newman method.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    most_valuable_edge : function
+        Function that takes a graph as input and outputs an edge. The
+        edge returned by this function will be recomputed and removed at
+        each iteration of the algorithm.
+
+        If not specified, the edge with the highest
+        :func:`networkx.edge_betweenness_centrality` will be used.
+
+    Returns
+    -------
+    iterator
+        Iterator over tuples of sets of nodes in `G`. Each set of node
+        is a community, each tuple is a sequence of communities at a
+        particular level of the algorithm.
+
+    Examples
+    --------
+    To get the first pair of communities::
+
+        >>> G = nx.path_graph(10)
+        >>> comp = nx.community.girvan_newman(G)
+        >>> tuple(sorted(c) for c in next(comp))
+        ([0, 1, 2, 3, 4], [5, 6, 7, 8, 9])
+
+    To get only the first *k* tuples of communities, use
+    :func:`itertools.islice`::
+
+        >>> import itertools
+        >>> G = nx.path_graph(8)
+        >>> k = 2
+        >>> comp = nx.community.girvan_newman(G)
+        >>> for communities in itertools.islice(comp, k):
+        ...     print(tuple(sorted(c) for c in communities))
+        ...
+        ([0, 1, 2, 3], [4, 5, 6, 7])
+        ([0, 1], [2, 3], [4, 5, 6, 7])
+
+    To stop getting tuples of communities once the number of communities
+    is greater than *k*, use :func:`itertools.takewhile`::
+
+        >>> import itertools
+        >>> G = nx.path_graph(8)
+        >>> k = 4
+        >>> comp = nx.community.girvan_newman(G)
+        >>> limited = itertools.takewhile(lambda c: len(c) <= k, comp)
+        >>> for communities in limited:
+        ...     print(tuple(sorted(c) for c in communities))
+        ...
+        ([0, 1, 2, 3], [4, 5, 6, 7])
+        ([0, 1], [2, 3], [4, 5, 6, 7])
+        ([0, 1], [2, 3], [4, 5], [6, 7])
+
+    To just choose an edge to remove based on the weight::
+
+        >>> from operator import itemgetter
+        >>> G = nx.path_graph(10)
+        >>> edges = G.edges()
+        >>> nx.set_edge_attributes(G, {(u, v): v for u, v in edges}, "weight")
+        >>> def heaviest(G):
+        ...     u, v, w = max(G.edges(data="weight"), key=itemgetter(2))
+        ...     return (u, v)
+        ...
+        >>> comp = nx.community.girvan_newman(G, most_valuable_edge=heaviest)
+        >>> tuple(sorted(c) for c in next(comp))
+        ([0, 1, 2, 3, 4, 5, 6, 7, 8], [9])
+
+    To utilize edge weights when choosing an edge with, for example, the
+    highest betweenness centrality::
+
+        >>> from networkx import edge_betweenness_centrality as betweenness
+        >>> def most_central_edge(G):
+        ...     centrality = betweenness(G, weight="weight")
+        ...     return max(centrality, key=centrality.get)
+        ...
+        >>> G = nx.path_graph(10)
+        >>> comp = nx.community.girvan_newman(G, most_valuable_edge=most_central_edge)
+        >>> tuple(sorted(c) for c in next(comp))
+        ([0, 1, 2, 3, 4], [5, 6, 7, 8, 9])
+
+    To specify a different ranking algorithm for edges, use the
+    `most_valuable_edge` keyword argument::
+
+        >>> from networkx import edge_betweenness_centrality
+        >>> from random import random
+        >>> def most_central_edge(G):
+        ...     centrality = edge_betweenness_centrality(G)
+        ...     max_cent = max(centrality.values())
+        ...     # Scale the centrality values so they are between 0 and 1,
+        ...     # and add some random noise.
+        ...     centrality = {e: c / max_cent for e, c in centrality.items()}
+        ...     # Add some random noise.
+        ...     centrality = {e: c + random() for e, c in centrality.items()}
+        ...     return max(centrality, key=centrality.get)
+        ...
+        >>> G = nx.path_graph(10)
+        >>> comp = nx.community.girvan_newman(G, most_valuable_edge=most_central_edge)
+
+    Notes
+    -----
+    The Girvan–Newman algorithm detects communities by progressively
+    removing edges from the original graph. The algorithm removes the
+    "most valuable" edge, traditionally the edge with the highest
+    betweenness centrality, at each step. As the graph breaks down into
+    pieces, the tightly knit community structure is exposed and the
+    result can be depicted as a dendrogram.
+
+    """
+    # If the graph is already empty, simply return its connected
+    # components.
+    if G.number_of_edges() == 0:
+        yield tuple(nx.connected_components(G))
+        return
+    # If no function is provided for computing the most valuable edge,
+    # use the edge betweenness centrality.
+    if most_valuable_edge is None:
+
+        def most_valuable_edge(G):
+            """Returns the edge with the highest betweenness centrality
+            in the graph `G`.
+
+            """
+            # We have guaranteed that the graph is non-empty, so this
+            # dictionary will never be empty.
+            betweenness = nx.edge_betweenness_centrality(G)
+            return max(betweenness, key=betweenness.get)
+
+    # The copy of G here must include the edge weight data.
+    g = G.copy().to_undirected()
+    # Self-loops must be removed because their removal has no effect on
+    # the connected components of the graph.
+    g.remove_edges_from(nx.selfloop_edges(g))
+    while g.number_of_edges() > 0:
+        yield _without_most_central_edges(g, most_valuable_edge)
+
+
+def _without_most_central_edges(G, most_valuable_edge):
+    """Returns the connected components of the graph that results from
+    repeatedly removing the most "valuable" edge in the graph.
+
+    `G` must be a non-empty graph. This function modifies the graph `G`
+    in-place; that is, it removes edges on the graph `G`.
+
+    `most_valuable_edge` is a function that takes the graph `G` as input
+    (or a subgraph with one or more edges of `G` removed) and returns an
+    edge. That edge will be removed and this process will be repeated
+    until the number of connected components in the graph increases.
+
+    """
+    original_num_components = nx.number_connected_components(G)
+    num_new_components = original_num_components
+    while num_new_components <= original_num_components:
+        edge = most_valuable_edge(G)
+        G.remove_edge(*edge)
+        new_components = tuple(nx.connected_components(G))
+        num_new_components = len(new_components)
+    return new_components
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/divisive.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/divisive.py
new file mode 100644
index 0000000000000000000000000000000000000000..be3c7d863e9d28f6e9c56faea4a60a640f8892bb
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/divisive.py
@@ -0,0 +1,216 @@
+import functools
+
+import networkx as nx
+
+__all__ = [
+    "edge_betweenness_partition",
+    "edge_current_flow_betweenness_partition",
+]
+
+
+@nx._dispatchable(edge_attrs="weight")
+def edge_betweenness_partition(G, number_of_sets, *, weight=None):
+    """Partition created by iteratively removing the highest edge betweenness edge.
+
+    This algorithm works by calculating the edge betweenness for all
+    edges and removing the edge with the highest value. It is then
+    determined whether the graph has been broken into at least
+    `number_of_sets` connected components.
+    If not the process is repeated.
+
+    Parameters
+    ----------
+    G : NetworkX Graph, DiGraph or MultiGraph
+      Graph to be partitioned
+
+    number_of_sets : int
+      Number of sets in the desired partition of the graph
+
+    weight : key, optional, default=None
+      The key to use if using weights for edge betweenness calculation
+
+    Returns
+    -------
+    C : list of sets
+      Partition of the nodes of G
+
+    Raises
+    ------
+    NetworkXError
+      If number_of_sets is <= 0 or if number_of_sets > len(G)
+
+    Examples
+    --------
+    >>> G = nx.karate_club_graph()
+    >>> part = nx.community.edge_betweenness_partition(G, 2)
+    >>> {0, 1, 3, 4, 5, 6, 7, 10, 11, 12, 13, 16, 17, 19, 21} in part
+    True
+    >>> {
+    ...     2,
+    ...     8,
+    ...     9,
+    ...     14,
+    ...     15,
+    ...     18,
+    ...     20,
+    ...     22,
+    ...     23,
+    ...     24,
+    ...     25,
+    ...     26,
+    ...     27,
+    ...     28,
+    ...     29,
+    ...     30,
+    ...     31,
+    ...     32,
+    ...     33,
+    ... } in part
+    True
+
+    See Also
+    --------
+    edge_current_flow_betweenness_partition
+
+    Notes
+    -----
+    This algorithm is fairly slow, as both the calculation of connected
+    components and edge betweenness relies on all pairs shortest
+    path algorithms. They could potentially be combined to cut down
+    on overall computation time.
+
+    References
+    ----------
+    .. [1] Santo Fortunato 'Community Detection in Graphs' Physical Reports
+       Volume 486, Issue 3-5 p. 75-174
+       http://arxiv.org/abs/0906.0612
+    """
+    if number_of_sets <= 0:
+        raise nx.NetworkXError("number_of_sets must be >0")
+    if number_of_sets == 1:
+        return [set(G)]
+    if number_of_sets == len(G):
+        return [{n} for n in G]
+    if number_of_sets > len(G):
+        raise nx.NetworkXError("number_of_sets must be <= len(G)")
+
+    H = G.copy()
+    partition = list(nx.connected_components(H))
+    while len(partition) < number_of_sets:
+        ranking = nx.edge_betweenness_centrality(H, weight=weight)
+        edge = max(ranking, key=ranking.get)
+        H.remove_edge(*edge)
+        partition = list(nx.connected_components(H))
+    return partition
+
+
+@nx._dispatchable(edge_attrs="weight")
+def edge_current_flow_betweenness_partition(G, number_of_sets, *, weight=None):
+    """Partition created by removing the highest edge current flow betweenness edge.
+
+    This algorithm works by calculating the edge current flow
+    betweenness for all edges and removing the edge with the
+    highest value. It is then determined whether the graph has
+    been broken into at least `number_of_sets` connected
+    components. If not the process is repeated.
+
+    Parameters
+    ----------
+    G : NetworkX Graph, DiGraph or MultiGraph
+      Graph to be partitioned
+
+    number_of_sets : int
+      Number of sets in the desired partition of the graph
+
+    weight : key, optional (default=None)
+      The edge attribute key to use as weights for
+      edge current flow betweenness calculations
+
+    Returns
+    -------
+    C : list of sets
+      Partition of G
+
+    Raises
+    ------
+    NetworkXError
+      If number_of_sets is <= 0 or number_of_sets > len(G)
+
+    Examples
+    --------
+    >>> G = nx.karate_club_graph()
+    >>> part = nx.community.edge_current_flow_betweenness_partition(G, 2)
+    >>> {0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 16, 17, 19, 21} in part
+    True
+    >>> {8, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33} in part
+    True
+
+
+    See Also
+    --------
+    edge_betweenness_partition
+
+    Notes
+    -----
+    This algorithm is extremely slow, as the recalculation of the edge
+    current flow betweenness is extremely slow.
+
+    References
+    ----------
+    .. [1] Santo Fortunato 'Community Detection in Graphs' Physical Reports
+       Volume 486, Issue 3-5 p. 75-174
+       http://arxiv.org/abs/0906.0612
+    """
+    if number_of_sets <= 0:
+        raise nx.NetworkXError("number_of_sets must be >0")
+    elif number_of_sets == 1:
+        return [set(G)]
+    elif number_of_sets == len(G):
+        return [{n} for n in G]
+    elif number_of_sets > len(G):
+        raise nx.NetworkXError("number_of_sets must be <= len(G)")
+
+    rank = functools.partial(
+        nx.edge_current_flow_betweenness_centrality, normalized=False, weight=weight
+    )
+
+    # current flow requires a connected network so we track the components explicitly
+    H = G.copy()
+    partition = list(nx.connected_components(H))
+    if len(partition) > 1:
+        Hcc_subgraphs = [H.subgraph(cc).copy() for cc in partition]
+    else:
+        Hcc_subgraphs = [H]
+
+    ranking = {}
+    for Hcc in Hcc_subgraphs:
+        ranking.update(rank(Hcc))
+
+    while len(partition) < number_of_sets:
+        edge = max(ranking, key=ranking.get)
+        for cc, Hcc in zip(partition, Hcc_subgraphs):
+            if edge[0] in cc:
+                Hcc.remove_edge(*edge)
+                del ranking[edge]
+                splitcc_list = list(nx.connected_components(Hcc))
+                if len(splitcc_list) > 1:
+                    # there are 2 connected components. split off smaller one
+                    cc_new = min(splitcc_list, key=len)
+                    Hcc_new = Hcc.subgraph(cc_new).copy()
+                    # update edge rankings for Hcc_new
+                    newranks = rank(Hcc_new)
+                    for e, r in newranks.items():
+                        ranking[e if e in ranking else e[::-1]] = r
+                    # append new cc and Hcc to their lists.
+                    partition.append(cc_new)
+                    Hcc_subgraphs.append(Hcc_new)
+
+                    # leave existing cc and Hcc in their lists, but shrink them
+                    Hcc.remove_nodes_from(cc_new)
+                    cc.difference_update(cc_new)
+                # update edge rankings for Hcc whether it was split or not
+                newranks = rank(Hcc)
+                for e, r in newranks.items():
+                    ranking[e if e in ranking else e[::-1]] = r
+                break
+    return partition
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/kclique.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/kclique.py
new file mode 100644
index 0000000000000000000000000000000000000000..c72491042046b6f79ba5c7cb4a90ac8822491d84
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/kclique.py
@@ -0,0 +1,79 @@
+from collections import defaultdict
+
+import networkx as nx
+
+__all__ = ["k_clique_communities"]
+
+
+@nx._dispatchable
+def k_clique_communities(G, k, cliques=None):
+    """Find k-clique communities in graph using the percolation method.
+
+    A k-clique community is the union of all cliques of size k that
+    can be reached through adjacent (sharing k-1 nodes) k-cliques.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    k : int
+       Size of smallest clique
+
+    cliques: list or generator
+       Precomputed cliques (use networkx.find_cliques(G))
+
+    Returns
+    -------
+    Yields sets of nodes, one for each k-clique community.
+
+    Examples
+    --------
+    >>> G = nx.complete_graph(5)
+    >>> K5 = nx.convert_node_labels_to_integers(G, first_label=2)
+    >>> G.add_edges_from(K5.edges())
+    >>> c = list(nx.community.k_clique_communities(G, 4))
+    >>> sorted(list(c[0]))
+    [0, 1, 2, 3, 4, 5, 6]
+    >>> list(nx.community.k_clique_communities(G, 6))
+    []
+
+    References
+    ----------
+    .. [1] Gergely Palla, Imre Derényi, Illés Farkas1, and Tamás Vicsek,
+       Uncovering the overlapping community structure of complex networks
+       in nature and society Nature 435, 814-818, 2005,
+       doi:10.1038/nature03607
+    """
+    if k < 2:
+        raise nx.NetworkXError(f"k={k}, k must be greater than 1.")
+    if cliques is None:
+        cliques = nx.find_cliques(G)
+    cliques = [frozenset(c) for c in cliques if len(c) >= k]
+
+    # First index which nodes are in which cliques
+    membership_dict = defaultdict(list)
+    for clique in cliques:
+        for node in clique:
+            membership_dict[node].append(clique)
+
+    # For each clique, see which adjacent cliques percolate
+    perc_graph = nx.Graph()
+    perc_graph.add_nodes_from(cliques)
+    for clique in cliques:
+        for adj_clique in _get_adjacent_cliques(clique, membership_dict):
+            if len(clique.intersection(adj_clique)) >= (k - 1):
+                perc_graph.add_edge(clique, adj_clique)
+
+    # Connected components of clique graph with perc edges
+    # are the percolated cliques
+    for component in nx.connected_components(perc_graph):
+        yield (frozenset.union(*component))
+
+
+def _get_adjacent_cliques(clique, membership_dict):
+    adjacent_cliques = set()
+    for n in clique:
+        for adj_clique in membership_dict[n]:
+            if clique != adj_clique:
+                adjacent_cliques.add(adj_clique)
+    return adjacent_cliques
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/leiden.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/leiden.py
new file mode 100644
index 0000000000000000000000000000000000000000..a37ad6591ceac8337db41ae99c5d55b144db3002
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/leiden.py
@@ -0,0 +1,162 @@
+"""Functions for detecting communities based on Leiden Community Detection
+algorithm.
+
+These functions do not have NetworkX implementations.
+They may only be run with an installable :doc:`backend `
+that supports them.
+"""
+
+import itertools
+from collections import deque
+
+import networkx as nx
+from networkx.utils import not_implemented_for, py_random_state
+
+__all__ = ["leiden_communities", "leiden_partitions"]
+
+
+@not_implemented_for("directed")
+@py_random_state("seed")
+@nx._dispatchable(edge_attrs="weight", implemented_by_nx=False)
+def leiden_communities(G, weight="weight", resolution=1, max_level=None, seed=None):
+    r"""Find a best partition of `G` using Leiden Community Detection (backend required)
+
+    Leiden Community Detection is an algorithm to extract the community structure
+    of a network based on modularity optimization. It is an improvement upon the
+    Louvain Community Detection algorithm. See :any:`louvain_communities`.
+
+    Unlike the Louvain algorithm, it guarantees that communities are well connected in addition
+    to being faster and uncovering better partitions. [1]_
+
+    The algorithm works in 3 phases. On the first phase, it adds the nodes to a queue randomly
+    and assigns every node to be in its own community. For each node it tries to find the
+    maximum positive modularity gain by moving each node to all of its neighbor communities.
+    If a node is moved from its community, it adds to the rear of the queue all neighbors of
+    the node that do not belong to the node’s new community and that are not in the queue.
+
+    The first phase continues until the queue is empty.
+
+    The second phase consists in refining the partition $P$ obtained from the first phase. It starts
+    with a singleton partition $P_{refined}$. Then it merges nodes locally in $P_{refined}$ within
+    each community of the partition $P$. Nodes are merged with a community in $P_{refined}$ only if
+    both are sufficiently well connected to their community in $P$. This means that after the
+    refinement phase is concluded, communities in $P$ sometimes will have been split into multiple
+    communities.
+
+    The third phase consists of aggregating the network by building a new network whose nodes are
+    now the communities found in the second phase. However, the non-refined partition is used to create
+    an initial partition for the aggregate network.
+
+    Once this phase is complete it is possible to reapply the first and second phases creating bigger
+    communities with increased modularity.
+
+    The above three phases are executed until no modularity gain is achieved or `max_level` number
+    of iterations have been performed.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+    weight : string or None, optional (default="weight")
+        The name of an edge attribute that holds the numerical value
+        used as a weight. If None then each edge has weight 1.
+    resolution : float, optional (default=1)
+        If resolution is less than 1, the algorithm favors larger communities.
+        Greater than 1 favors smaller communities.
+    max_level : int or None, optional (default=None)
+        The maximum number of levels (steps of the algorithm) to compute.
+        Must be a positive integer or None. If None, then there is no max
+        level and the algorithm will run until converged.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    list
+        A list of disjoint sets (partition of `G`). Each set represents one community.
+        All communities together contain all the nodes in `G`.
+
+    Examples
+    --------
+    >>> import networkx as nx
+    >>> G = nx.petersen_graph()
+    >>> nx.community.leiden_communities(G, backend="example_backend")  # doctest: +SKIP
+    [{2, 3, 5, 7, 8}, {0, 1, 4, 6, 9}]
+
+    Notes
+    -----
+    The order in which the nodes are considered can affect the final output. In the algorithm
+    the ordering happens using a random shuffle.
+
+    References
+    ----------
+    .. [1] Traag, V.A., Waltman, L. & van Eck, N.J. From Louvain to Leiden: guaranteeing
+       well-connected communities. Sci Rep 9, 5233 (2019). https://doi.org/10.1038/s41598-019-41695-z
+
+    See Also
+    --------
+    leiden_partitions
+    :any:`louvain_communities`
+    """
+    partitions = leiden_partitions(G, weight, resolution, seed)
+    if max_level is not None:
+        if max_level <= 0:
+            raise ValueError("max_level argument must be a positive integer or None")
+        partitions = itertools.islice(partitions, max_level)
+    final_partition = deque(partitions, maxlen=1)
+    return final_partition.pop()
+
+
+@not_implemented_for("directed")
+@py_random_state("seed")
+@nx._dispatchable(edge_attrs="weight", implemented_by_nx=False)
+def leiden_partitions(G, weight="weight", resolution=1, seed=None):
+    """Yield partitions for each level of Leiden Community Detection (backend required)
+
+    Leiden Community Detection is an algorithm to extract the community
+    structure of a network based on modularity optimization.
+
+    The partitions across levels (steps of the algorithm) form a dendrogram
+    of communities. A dendrogram is a diagram representing a tree and each
+    level represents a partition of the G graph. The top level contains the
+    smallest communities and as you traverse to the bottom of the tree the
+    communities get bigger and the overall modularity increases making
+    the partition better.
+
+    Each level is generated by executing the three phases of the Leiden Community
+    Detection algorithm. See :any:`leiden_communities`.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+    weight : string or None, optional (default="weight")
+        The name of an edge attribute that holds the numerical value
+        used as a weight. If None then each edge has weight 1.
+    resolution : float, optional (default=1)
+        If resolution is less than 1, the algorithm favors larger communities.
+        Greater than 1 favors smaller communities.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Yields
+    ------
+    list
+        A list of disjoint sets (partition of `G`). Each set represents one community.
+        All communities together contain all the nodes in `G`. The yielded partitions
+        increase modularity with each iteration.
+
+    References
+    ----------
+    .. [1] Traag, V.A., Waltman, L. & van Eck, N.J. From Louvain to Leiden: guaranteeing
+       well-connected communities. Sci Rep 9, 5233 (2019). https://doi.org/10.1038/s41598-019-41695-z
+
+    See Also
+    --------
+    leiden_communities
+    :any:`louvain_partitions`
+    """
+    raise NotImplementedError(
+        "'leiden_partitions' is not implemented by networkx. "
+        "Please try a different backend."
+    )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/local.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/local.py
new file mode 100644
index 0000000000000000000000000000000000000000..68fc06a0f25823f5be51ff804134a1bfa82a0e07
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/local.py
@@ -0,0 +1,220 @@
+"""
+Local Community Detection Algorithms
+
+Local Community Detection (LCD) aims to detected one or a few communities
+starting from certain source nodes in the network. This differs from Global
+Community Detection (GCD), which aims to partition an entire network into
+communities.
+
+LCD is often useful when only a portion of the graph is known or the
+graph is large enough that GCD is infeasable
+
+[1]_ Gives a good introduction and overview of LCD
+
+References
+----------
+.. [1] Baltsou, Georgia, Konstantinos Christopoulos, and Konstantinos Tsichlas.
+   Local community detection: A survey. IEEE Access 10 (2022): 110701-110726.
+   https://doi.org/10.1109/ACCESS.2022.3213980
+
+
+"""
+
+__all__ = ["greedy_source_expansion"]
+
+
+def _clauset_greedy_source_expansion(G, *, source, cutoff=None):
+    if cutoff is None:
+        cutoff = float("inf")
+    C = {source}
+    B = {source}
+    U = G[source].keys() - C
+    T = {frozenset([node, nbr]) for node in B for nbr in G.neighbors(node)}
+    I = {edge for edge in T if all(node in C for node in edge)}
+
+    R_value = 0
+    while len(C) < cutoff:
+        if not U:
+            break
+
+        max_R = 0
+        best_node = None
+        best_node_B = best_node_T = best_node_I = set()
+
+        for v in U:
+            R_tmp, B_tmp, T_tmp, I_tmp = _calculate_local_modularity_for_candidate(
+                G, v, C, B, T, I
+            )
+            if R_tmp > max_R:
+                max_R = R_tmp
+                best_node = v
+                best_node_B = B_tmp
+                best_node_T = T_tmp
+                best_node_I = I_tmp
+
+        C = C | {best_node}
+        U.update(G[best_node].keys() - C)
+        U.remove(best_node)
+        B = best_node_B
+        T = best_node_T
+        I = best_node_I
+        if max_R < R_value:
+            break
+        R_value = max_R
+
+    return C
+
+
+def _calculate_local_modularity_for_candidate(G, v, C, B, T, I):
+    """
+    Compute the local modularity R and updated variables when adding node v to the community.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        The input graph.
+    v : node
+        The candidate node to add to the community.
+    C : set
+        The current set of community nodes.
+    B : set
+        The current set of boundary nodes.
+    T : set of frozenset
+        The current set of boundary edges.
+    I : set of frozenset
+        The current set of internal boundary edges.
+
+    Returns
+    -------
+    R_tmp : float
+        The local modularity after adding node v.
+    B_tmp : set
+        The updated set of boundary nodes.
+    T_tmp : set of frozenset
+        The updated set of boundary edges.
+    I_tmp : set of frozenset
+        The updated set of internal boundary edges.
+    """
+    C_tmp = C | {v}
+    B_tmp = B.copy()
+    T_tmp = T.copy()
+    I_tmp = I.copy()
+    removed_B_nodes = set()
+
+    # Update boundary nodes and edges
+    for nbr in G[v]:
+        if nbr not in C_tmp:
+            # v has nbrs not in the community, so it remains a boundary node
+            B_tmp.add(v)
+            # Add edge between v and nbr to boundary edges
+            T_tmp.add(frozenset([v, nbr]))
+
+        if nbr in B:
+            # Check if nbr should be removed from boundary nodes
+            # Go through nbrs nbrs to see if it is still a boundary node
+            nbr_still_in_B = any(nbr_nbr not in C_tmp for nbr_nbr in G[nbr])
+            if not nbr_still_in_B:
+                B_tmp.remove(nbr)
+                removed_B_nodes.add(nbr)
+
+        if nbr in C_tmp:
+            # Add edge between v and nbr to internal edges
+            I_tmp.add(frozenset([v, nbr]))
+
+    # Remove edges no longer in the boundary
+    for removed_node in removed_B_nodes:
+        for removed_node_nbr in G[removed_node]:
+            if removed_node_nbr not in B_tmp:
+                T_tmp.discard(frozenset([removed_node_nbr, removed_node]))
+                I_tmp.discard(frozenset([removed_node_nbr, removed_node]))
+
+    R_tmp = len(I_tmp) / len(T_tmp) if len(T_tmp) > 0 else 1
+    return R_tmp, B_tmp, T_tmp, I_tmp
+
+
+ALGORITHMS = {
+    "clauset": _clauset_greedy_source_expansion,
+}
+
+
+def greedy_source_expansion(G, *, source, cutoff=None, method="clauset"):
+    r"""Find the local community around a source node.
+
+    Find the local community around a source node using Greedy Source
+    Expansion. Greedy Source Expansion generally identifies a local community
+    starting from the source node and expands it based on the criteria of the
+    chosen algorithm.
+
+    The algorithm is specified with the `method` keyword argument.
+
+    * `"clauset"` [1]_ uses local modularity gain to determine local communities.
+        The algorithm adds nbring nodes that maximize local modularity to the
+        community iteratively, stopping when no additional nodes improve the modularity
+        or when a predefined cutoff is reached.
+
+        Local modularity measures the density of edges within a community relative
+        to the total graph. By focusing on local modularity, the algorithm efficiently
+        uncovers communities around a specific node without requiring global
+        optimization over the entire graph.
+
+        The algorithm assumes that the graph $G$ consists of a known community $C$ and
+        an unknown set of nodes $U$, which are adjacent to $C$ . The boundary of the
+        community $B$, consists of nodes in $C$ that have at least one nbr in $U$.
+
+        Mathematically, the local modularity is expressed as:
+
+        .. math::
+            R = \frac{I}{T}
+
+        where $T$ is the number of edges with one or more endpoints in $B$, and $I$ is the
+        number of those edges with neither endpoint in $U$.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        The input graph.
+
+    source : node
+        The source node from which the community expansion begins.
+
+    cutoff : int, optional (default=None)
+        The maximum number of nodes to include in the community. If None, the algorithm
+        expands until no further modularity gain can be made.
+
+    method : string, optional (default='clauset')
+        The algorithm to use to carry out greedy source expansion.
+        Supported options: 'clauset'. Other inputs produce a ValueError
+
+    Returns
+    -------
+    set
+        A set of nodes representing the local community around the source node.
+
+    Examples
+    --------
+    >>> G = nx.karate_club_graph()
+    >>> nx.community.greedy_source_expansion(G, source=16)
+    {16, 0, 4, 5, 6, 10}
+
+    Notes
+    -----
+    This algorithm is designed for detecting local communities around a specific node,
+    which is useful for large networks where global community detection is computationally
+    expensive.
+
+    The result of the algorithm may vary based on the structure of the graph, the choice of
+    the source node, and the presence of ties between nodes during the greedy expansion process.
+
+    References
+    ----------
+    .. [1] Clauset, Aaron. Finding local community structure in networks.
+      Physical Review E—Statistical, Nonlinear, and Soft Matter Physics 72, no. 2 (2005): 026132.
+      https://arxiv.org/pdf/physics/0503036
+
+    """
+    try:
+        algo = ALGORITHMS[method]
+    except KeyError as e:
+        raise ValueError(f"{method} is not a valid choice for an algorithm.") from e
+
+    return algo(G, source=source, cutoff=cutoff)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/louvain.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/louvain.py
new file mode 100644
index 0000000000000000000000000000000000000000..c8407a8acabadb7df04268d0489337392773e557
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/louvain.py
@@ -0,0 +1,384 @@
+"""Functions for detecting communities based on Louvain Community Detection
+Algorithm"""
+
+import itertools
+from collections import defaultdict, deque
+
+import networkx as nx
+from networkx.algorithms.community import modularity
+from networkx.utils import py_random_state
+
+__all__ = ["louvain_communities", "louvain_partitions"]
+
+
+@py_random_state("seed")
+@nx._dispatchable(edge_attrs="weight")
+def louvain_communities(
+    G, weight="weight", resolution=1, threshold=0.0000001, max_level=None, seed=None
+):
+    r"""Find the best partition of a graph using the Louvain Community Detection
+    Algorithm.
+
+    Louvain Community Detection Algorithm is a simple method to extract the community
+    structure of a network. This is a heuristic method based on modularity optimization. [1]_
+
+    The algorithm works in 2 steps. On the first step it assigns every node to be
+    in its own community and then for each node it tries to find the maximum positive
+    modularity gain by moving each node to all of its neighbor communities. If no positive
+    gain is achieved the node remains in its original community.
+
+    The modularity gain obtained by moving an isolated node $i$ into a community $C$ can
+    easily be calculated by the following formula (combining [1]_ [2]_ and some algebra):
+
+    .. math::
+        \Delta Q = \frac{k_{i,in}}{2m} - \gamma\frac{ \Sigma_{tot} \cdot k_i}{2m^2}
+
+    where $m$ is the size of the graph, $k_{i,in}$ is the sum of the weights of the links
+    from $i$ to nodes in $C$, $k_i$ is the sum of the weights of the links incident to node $i$,
+    $\Sigma_{tot}$ is the sum of the weights of the links incident to nodes in $C$ and $\gamma$
+    is the resolution parameter.
+
+    For the directed case the modularity gain can be computed using this formula according to [3]_
+
+    .. math::
+        \Delta Q = \frac{k_{i,in}}{m}
+        - \gamma\frac{k_i^{out} \cdot\Sigma_{tot}^{in} + k_i^{in} \cdot \Sigma_{tot}^{out}}{m^2}
+
+    where $k_i^{out}$, $k_i^{in}$ are the outer and inner weighted degrees of node $i$ and
+    $\Sigma_{tot}^{in}$, $\Sigma_{tot}^{out}$ are the sum of in-going and out-going links incident
+    to nodes in $C$.
+
+    The first phase continues until no individual move can improve the modularity.
+
+    The second phase consists in building a new network whose nodes are now the communities
+    found in the first phase. To do so, the weights of the links between the new nodes are given by
+    the sum of the weight of the links between nodes in the corresponding two communities. Once this
+    phase is complete it is possible to reapply the first phase creating bigger communities with
+    increased modularity.
+
+    The above two phases are executed until no modularity gain is achieved (or is less than
+    the `threshold`, or until `max_levels` is reached).
+
+    Be careful with self-loops in the input graph. These are treated as
+    previously reduced communities -- as if the process had been started
+    in the middle of the algorithm. Large self-loop edge weights thus
+    represent strong communities and in practice may be hard to add
+    other nodes to.  If your input graph edge weights for self-loops
+    do not represent already reduced communities you may want to remove
+    the self-loops before inputting that graph.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+    weight : string or None, optional (default="weight")
+        The name of an edge attribute that holds the numerical value
+        used as a weight. If None then each edge has weight 1.
+    resolution : float, optional (default=1)
+        If resolution is less than 1, the algorithm favors larger communities.
+        Greater than 1 favors smaller communities
+    threshold : float, optional (default=0.0000001)
+        Modularity gain threshold for each level. If the gain of modularity
+        between 2 levels of the algorithm is less than the given threshold
+        then the algorithm stops and returns the resulting communities.
+    max_level : int or None, optional (default=None)
+        The maximum number of levels (steps of the algorithm) to compute.
+        Must be a positive integer or None. If None, then there is no max
+        level and the threshold parameter determines the stopping condition.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    list
+        A list of sets (partition of `G`). Each set represents one community and contains
+        all the nodes that constitute it.
+
+    Examples
+    --------
+    >>> import networkx as nx
+    >>> G = nx.petersen_graph()
+    >>> nx.community.louvain_communities(G, seed=123)
+    [{0, 4, 5, 7, 9}, {1, 2, 3, 6, 8}]
+
+    Notes
+    -----
+    The order in which the nodes are considered can affect the final output. In the algorithm
+    the ordering happens using a random shuffle.
+
+    References
+    ----------
+    .. [1] Blondel, V.D. et al. Fast unfolding of communities in
+       large networks. J. Stat. Mech 10008, 1-12(2008). https://doi.org/10.1088/1742-5468/2008/10/P10008
+    .. [2] Traag, V.A., Waltman, L. & van Eck, N.J. From Louvain to Leiden: guaranteeing
+       well-connected communities. Sci Rep 9, 5233 (2019). https://doi.org/10.1038/s41598-019-41695-z
+    .. [3] Nicolas Dugué, Anthony Perez. Directed Louvain : maximizing modularity in directed networks.
+        [Research Report] Université d’Orléans. 2015. hal-01231784. https://hal.archives-ouvertes.fr/hal-01231784
+
+    See Also
+    --------
+    louvain_partitions
+    :any:`leiden_communities`
+    """
+
+    partitions = louvain_partitions(G, weight, resolution, threshold, seed)
+    if max_level is not None:
+        if max_level <= 0:
+            raise ValueError("max_level argument must be a positive integer or None")
+        partitions = itertools.islice(partitions, max_level)
+    final_partition = deque(partitions, maxlen=1)
+    return final_partition.pop()
+
+
+@py_random_state("seed")
+@nx._dispatchable(edge_attrs="weight")
+def louvain_partitions(
+    G, weight="weight", resolution=1, threshold=0.0000001, seed=None
+):
+    """Yield partitions for each level of the Louvain Community Detection Algorithm
+
+    Louvain Community Detection Algorithm is a simple method to extract the community
+    structure of a network. This is a heuristic method based on modularity optimization. [1]_
+
+    The partitions at each level (step of the algorithm) form a dendrogram of communities.
+    A dendrogram is a diagram representing a tree and each level represents
+    a partition of the G graph. The top level contains the smallest communities
+    and as you traverse to the bottom of the tree the communities get bigger
+    and the overall modularity increases making the partition better.
+
+    Each level is generated by executing the two phases of the Louvain Community
+    Detection Algorithm.
+
+    Be careful with self-loops in the input graph. These are treated as
+    previously reduced communities -- as if the process had been started
+    in the middle of the algorithm. Large self-loop edge weights thus
+    represent strong communities and in practice may be hard to add
+    other nodes to.  If your input graph edge weights for self-loops
+    do not represent already reduced communities you may want to remove
+    the self-loops before inputting that graph.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+    weight : string or None, optional (default="weight")
+     The name of an edge attribute that holds the numerical value
+     used as a weight. If None then each edge has weight 1.
+    resolution : float, optional (default=1)
+        If resolution is less than 1, the algorithm favors larger communities.
+        Greater than 1 favors smaller communities
+    threshold : float, optional (default=0.0000001)
+     Modularity gain threshold for each level. If the gain of modularity
+     between 2 levels of the algorithm is less than the given threshold
+     then the algorithm stops and returns the resulting communities.
+    seed : integer, random_state, or None (default)
+     Indicator of random number generation state.
+     See :ref:`Randomness`.
+
+    Yields
+    ------
+    list
+        A list of sets (partition of `G`). Each set represents one community and contains
+        all the nodes that constitute it.
+
+    References
+    ----------
+    .. [1] Blondel, V.D. et al. Fast unfolding of communities in
+       large networks. J. Stat. Mech 10008, 1-12(2008)
+
+    See Also
+    --------
+    louvain_communities
+    :any:`leiden_partitions`
+    """
+
+    partition = [{u} for u in G.nodes()]
+    if nx.is_empty(G):
+        yield partition
+        return
+    mod = modularity(G, partition, resolution=resolution, weight=weight)
+    is_directed = G.is_directed()
+    if G.is_multigraph():
+        graph = _convert_multigraph(G, weight, is_directed)
+    else:
+        graph = G.__class__()
+        graph.add_nodes_from(G)
+        graph.add_weighted_edges_from(G.edges(data=weight, default=1))
+
+    m = graph.size(weight="weight")
+    partition, inner_partition, improvement = _one_level(
+        graph, m, partition, resolution, is_directed, seed
+    )
+    improvement = True
+    while improvement:
+        # gh-5901 protect the sets in the yielded list from further manipulation here
+        yield [s.copy() for s in partition]
+        new_mod = modularity(
+            graph, inner_partition, resolution=resolution, weight="weight"
+        )
+        if new_mod - mod <= threshold:
+            return
+        mod = new_mod
+        graph = _gen_graph(graph, inner_partition)
+        partition, inner_partition, improvement = _one_level(
+            graph, m, partition, resolution, is_directed, seed
+        )
+
+
+def _one_level(G, m, partition, resolution=1, is_directed=False, seed=None):
+    """Calculate one level of the Louvain partitions tree
+
+    Parameters
+    ----------
+    G : NetworkX Graph/DiGraph
+        The graph from which to detect communities
+    m : number
+        The size of the graph `G`.
+    partition : list of sets of nodes
+        A valid partition of the graph `G`
+    resolution : positive number
+        The resolution parameter for computing the modularity of a partition
+    is_directed : bool
+        True if `G` is a directed graph.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    """
+    node2com = {u: i for i, u in enumerate(G.nodes())}
+    inner_partition = [{u} for u in G.nodes()]
+    if is_directed:
+        in_degrees = dict(G.in_degree(weight="weight"))
+        out_degrees = dict(G.out_degree(weight="weight"))
+        Stot_in = list(in_degrees.values())
+        Stot_out = list(out_degrees.values())
+        # Calculate weights for both in and out neighbors without considering self-loops
+        nbrs = {}
+        for u in G:
+            nbrs[u] = defaultdict(float)
+            for _, n, wt in G.out_edges(u, data="weight"):
+                if u != n:
+                    nbrs[u][n] += wt
+            for n, _, wt in G.in_edges(u, data="weight"):
+                if u != n:
+                    nbrs[u][n] += wt
+    else:
+        degrees = dict(G.degree(weight="weight"))
+        Stot = list(degrees.values())
+        nbrs = {u: {v: data["weight"] for v, data in G[u].items() if v != u} for u in G}
+    rand_nodes = list(G.nodes)
+    seed.shuffle(rand_nodes)
+    nb_moves = 1
+    improvement = False
+    while nb_moves > 0:
+        nb_moves = 0
+        for u in rand_nodes:
+            best_mod = 0
+            best_com = node2com[u]
+            weights2com = _neighbor_weights(nbrs[u], node2com)
+            if is_directed:
+                in_degree = in_degrees[u]
+                out_degree = out_degrees[u]
+                Stot_in[best_com] -= in_degree
+                Stot_out[best_com] -= out_degree
+                remove_cost = (
+                    -weights2com[best_com] / m
+                    + resolution
+                    * (out_degree * Stot_in[best_com] + in_degree * Stot_out[best_com])
+                    / m**2
+                )
+            else:
+                degree = degrees[u]
+                Stot[best_com] -= degree
+                remove_cost = -weights2com[best_com] / m + resolution * (
+                    Stot[best_com] * degree
+                ) / (2 * m**2)
+            for nbr_com, wt in weights2com.items():
+                if is_directed:
+                    gain = (
+                        remove_cost
+                        + wt / m
+                        - resolution
+                        * (
+                            out_degree * Stot_in[nbr_com]
+                            + in_degree * Stot_out[nbr_com]
+                        )
+                        / m**2
+                    )
+                else:
+                    gain = (
+                        remove_cost
+                        + wt / m
+                        - resolution * (Stot[nbr_com] * degree) / (2 * m**2)
+                    )
+                if gain > best_mod:
+                    best_mod = gain
+                    best_com = nbr_com
+            if is_directed:
+                Stot_in[best_com] += in_degree
+                Stot_out[best_com] += out_degree
+            else:
+                Stot[best_com] += degree
+            if best_com != node2com[u]:
+                com = G.nodes[u].get("nodes", {u})
+                partition[node2com[u]].difference_update(com)
+                inner_partition[node2com[u]].remove(u)
+                partition[best_com].update(com)
+                inner_partition[best_com].add(u)
+                improvement = True
+                nb_moves += 1
+                node2com[u] = best_com
+    partition = list(filter(len, partition))
+    inner_partition = list(filter(len, inner_partition))
+    return partition, inner_partition, improvement
+
+
+def _neighbor_weights(nbrs, node2com):
+    """Calculate weights between node and its neighbor communities.
+
+    Parameters
+    ----------
+    nbrs : dictionary
+           Dictionary with nodes' neighbors as keys and their edge weight as value.
+    node2com : dictionary
+           Dictionary with all graph's nodes as keys and their community index as value.
+
+    """
+    weights = defaultdict(float)
+    for nbr, wt in nbrs.items():
+        weights[node2com[nbr]] += wt
+    return weights
+
+
+def _gen_graph(G, partition):
+    """Generate a new graph based on the partitions of a given graph"""
+    H = G.__class__()
+    node2com = {}
+    for i, part in enumerate(partition):
+        nodes = set()
+        for node in part:
+            node2com[node] = i
+            nodes.update(G.nodes[node].get("nodes", {node}))
+        H.add_node(i, nodes=nodes)
+
+    for node1, node2, wt in G.edges(data=True):
+        wt = wt["weight"]
+        com1 = node2com[node1]
+        com2 = node2com[node2]
+        temp = H.get_edge_data(com1, com2, {"weight": 0})["weight"]
+        H.add_edge(com1, com2, weight=wt + temp)
+    return H
+
+
+def _convert_multigraph(G, weight, is_directed):
+    """Convert a Multigraph to normal Graph"""
+    if is_directed:
+        H = nx.DiGraph()
+    else:
+        H = nx.Graph()
+    H.add_nodes_from(G)
+    for u, v, wt in G.edges(data=weight, default=1):
+        if H.has_edge(u, v):
+            H[u][v]["weight"] += wt
+        else:
+            H.add_edge(u, v, weight=wt)
+    return H
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/lukes.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/lukes.py
new file mode 100644
index 0000000000000000000000000000000000000000..08dd7cd52ff414c1397e3effea504853f3c9caf7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/lukes.py
@@ -0,0 +1,227 @@
+"""Lukes Algorithm for exact optimal weighted tree partitioning."""
+
+from copy import deepcopy
+from functools import lru_cache
+from random import choice
+
+import networkx as nx
+from networkx.utils import not_implemented_for
+
+__all__ = ["lukes_partitioning"]
+
+D_EDGE_W = "weight"
+D_EDGE_VALUE = 1.0
+D_NODE_W = "weight"
+D_NODE_VALUE = 1
+PKEY = "partitions"
+CLUSTER_EVAL_CACHE_SIZE = 2048
+
+
+def _split_n_from(n, min_size_of_first_part):
+    # splits j in two parts of which the first is at least
+    # the second argument
+    assert n >= min_size_of_first_part
+    for p1 in range(min_size_of_first_part, n + 1):
+        yield p1, n - p1
+
+
+@nx._dispatchable(node_attrs="node_weight", edge_attrs="edge_weight")
+def lukes_partitioning(G, max_size, node_weight=None, edge_weight=None):
+    """Optimal partitioning of a weighted tree using the Lukes algorithm.
+
+    This algorithm partitions a connected, acyclic graph featuring integer
+    node weights and float edge weights. The resulting clusters are such
+    that the total weight of the nodes in each cluster does not exceed
+    max_size and that the weight of the edges that are cut by the partition
+    is minimum. The algorithm is based on [1]_.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    max_size : int
+        Maximum weight a partition can have in terms of sum of
+        node_weight for all nodes in the partition
+
+    edge_weight : key
+        Edge data key to use as weight. If None, the weights are all
+        set to one.
+
+    node_weight : key
+        Node data key to use as weight. If None, the weights are all
+        set to one. The data must be int.
+
+    Returns
+    -------
+    partition : list
+        A list of sets of nodes representing the clusters of the
+        partition.
+
+    Raises
+    ------
+    NotATree
+        If G is not a tree.
+    TypeError
+        If any of the values of node_weight is not int.
+
+    References
+    ----------
+    .. [1] Lukes, J. A. (1974).
+       "Efficient Algorithm for the Partitioning of Trees."
+       IBM Journal of Research and Development, 18(3), 217–224.
+
+    """
+    # First sanity check and tree preparation
+    if not nx.is_tree(G):
+        raise nx.NotATree("lukes_partitioning works only on trees")
+    else:
+        if nx.is_directed(G):
+            root = [n for n, d in G.in_degree() if d == 0]
+            assert len(root) == 1
+            root = root[0]
+            t_G = deepcopy(G)
+        else:
+            root = choice(list(G.nodes))
+            # this has the desirable side effect of not inheriting attributes
+            t_G = nx.dfs_tree(G, root)
+
+    # Since we do not want to screw up the original graph,
+    # if we have a blank attribute, we make a deepcopy
+    if edge_weight is None or node_weight is None:
+        safe_G = deepcopy(G)
+        if edge_weight is None:
+            nx.set_edge_attributes(safe_G, D_EDGE_VALUE, D_EDGE_W)
+            edge_weight = D_EDGE_W
+        if node_weight is None:
+            nx.set_node_attributes(safe_G, D_NODE_VALUE, D_NODE_W)
+            node_weight = D_NODE_W
+    else:
+        safe_G = G
+
+    # Second sanity check
+    # The values of node_weight MUST BE int.
+    # I cannot see any room for duck typing without incurring serious
+    # danger of subtle bugs.
+    all_n_attr = nx.get_node_attributes(safe_G, node_weight).values()
+    for x in all_n_attr:
+        if not isinstance(x, int):
+            raise TypeError(
+                "lukes_partitioning needs integer "
+                f"values for node_weight ({node_weight})"
+            )
+
+    # SUBROUTINES -----------------------
+    # these functions are defined here for two reasons:
+    # - brevity: we can leverage global "safe_G"
+    # - caching: signatures are hashable
+
+    @not_implemented_for("undirected")
+    # this is intended to be called only on t_G
+    def _leaves(gr):
+        for x in gr.nodes:
+            if not nx.descendants(gr, x):
+                yield x
+
+    @not_implemented_for("undirected")
+    def _a_parent_of_leaves_only(gr):
+        tleaves = set(_leaves(gr))
+        for n in set(gr.nodes) - tleaves:
+            if all(x in tleaves for x in nx.descendants(gr, n)):
+                return n
+
+    @lru_cache(CLUSTER_EVAL_CACHE_SIZE)
+    def _value_of_cluster(cluster):
+        valid_edges = [e for e in safe_G.edges if e[0] in cluster and e[1] in cluster]
+        return sum(safe_G.edges[e][edge_weight] for e in valid_edges)
+
+    def _value_of_partition(partition):
+        return sum(_value_of_cluster(frozenset(c)) for c in partition)
+
+    @lru_cache(CLUSTER_EVAL_CACHE_SIZE)
+    def _weight_of_cluster(cluster):
+        return sum(safe_G.nodes[n][node_weight] for n in cluster)
+
+    def _pivot(partition, node):
+        ccx = [c for c in partition if node in c]
+        assert len(ccx) == 1
+        return ccx[0]
+
+    def _concatenate_or_merge(partition_1, partition_2, x, i, ref_weight):
+        ccx = _pivot(partition_1, x)
+        cci = _pivot(partition_2, i)
+        merged_xi = ccx.union(cci)
+
+        # We first check if we can do the merge.
+        # If so, we do the actual calculations, otherwise we concatenate
+        if _weight_of_cluster(frozenset(merged_xi)) <= ref_weight:
+            cp1 = list(filter(lambda x: x != ccx, partition_1))
+            cp2 = list(filter(lambda x: x != cci, partition_2))
+
+            option_2 = [merged_xi] + cp1 + cp2
+            return option_2, _value_of_partition(option_2)
+        else:
+            option_1 = partition_1 + partition_2
+            return option_1, _value_of_partition(option_1)
+
+    # INITIALIZATION -----------------------
+    leaves = set(_leaves(t_G))
+    for lv in leaves:
+        t_G.nodes[lv][PKEY] = {}
+        slot = safe_G.nodes[lv][node_weight]
+        t_G.nodes[lv][PKEY][slot] = [{lv}]
+        t_G.nodes[lv][PKEY][0] = [{lv}]
+
+    for inner in [x for x in t_G.nodes if x not in leaves]:
+        t_G.nodes[inner][PKEY] = {}
+        slot = safe_G.nodes[inner][node_weight]
+        t_G.nodes[inner][PKEY][slot] = [{inner}]
+    nx._clear_cache(t_G)
+
+    # CORE ALGORITHM -----------------------
+    while True:
+        x_node = _a_parent_of_leaves_only(t_G)
+        weight_of_x = safe_G.nodes[x_node][node_weight]
+        best_value = 0
+        best_partition = None
+        bp_buffer = {}
+        x_descendants = nx.descendants(t_G, x_node)
+        for i_node in x_descendants:
+            for j in range(weight_of_x, max_size + 1):
+                for a, b in _split_n_from(j, weight_of_x):
+                    if (
+                        a not in t_G.nodes[x_node][PKEY]
+                        or b not in t_G.nodes[i_node][PKEY]
+                    ):
+                        # it's not possible to form this particular weight sum
+                        continue
+
+                    part1 = t_G.nodes[x_node][PKEY][a]
+                    part2 = t_G.nodes[i_node][PKEY][b]
+                    part, value = _concatenate_or_merge(part1, part2, x_node, i_node, j)
+
+                    if j not in bp_buffer or bp_buffer[j][1] < value:
+                        # we annotate in the buffer the best partition for j
+                        bp_buffer[j] = part, value
+
+                    # we also keep track of the overall best partition
+                    if best_value <= value:
+                        best_value = value
+                        best_partition = part
+
+            # as illustrated in Lukes, once we finished a child, we can
+            # discharge the partitions we found into the graph
+            # (the key phrase is make all x == x')
+            # so that they are used by the subsequent children
+            for w, (best_part_for_vl, vl) in bp_buffer.items():
+                t_G.nodes[x_node][PKEY][w] = best_part_for_vl
+            bp_buffer.clear()
+
+        # the absolute best partition for this node
+        # across all weights has to be stored at 0
+        t_G.nodes[x_node][PKEY][0] = best_partition
+        t_G.remove_nodes_from(x_descendants)
+
+        if x_node == root:
+            # the 0-labeled partition of root
+            # is the optimal one for the whole tree
+            return t_G.nodes[root][PKEY][0]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/quality.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/quality.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b4dcbba1ce88f55f667cbe010fa89bf71cb99db
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/community/quality.py
@@ -0,0 +1,347 @@
+"""Functions for measuring the quality of a partition (into
+communities).
+
+"""
+
+from itertools import combinations
+
+import networkx as nx
+from networkx import NetworkXError
+from networkx.algorithms.community.community_utils import is_partition
+from networkx.utils.decorators import argmap
+
+__all__ = ["modularity", "partition_quality"]
+
+
+class NotAPartition(NetworkXError):
+    """Raised if a given collection is not a partition."""
+
+    def __init__(self, G, collection):
+        msg = f"{collection} is not a valid partition of the graph {G}"
+        super().__init__(msg)
+
+
+def _require_partition(G, partition):
+    """Decorator to check that a valid partition is input to a function
+
+    Raises :exc:`networkx.NetworkXError` if the partition is not valid.
+
+    This decorator should be used on functions whose first two arguments
+    are a graph and a partition of the nodes of that graph (in that
+    order)::
+
+        >>> @require_partition
+        ... def foo(G, partition):
+        ...     print("partition is valid!")
+        ...
+        >>> G = nx.complete_graph(5)
+        >>> partition = [{0, 1}, {2, 3}, {4}]
+        >>> foo(G, partition)
+        partition is valid!
+        >>> partition = [{0}, {2, 3}, {4}]
+        >>> foo(G, partition)
+        Traceback (most recent call last):
+          ...
+        networkx.exception.NetworkXError: `partition` is not a valid partition of the nodes of G
+        >>> partition = [{0, 1}, {1, 2, 3}, {4}]
+        >>> foo(G, partition)
+        Traceback (most recent call last):
+          ...
+        networkx.exception.NetworkXError: `partition` is not a valid partition of the nodes of G
+
+    """
+    if is_partition(G, partition):
+        return G, partition
+    raise nx.NetworkXError("`partition` is not a valid partition of the nodes of G")
+
+
+require_partition = argmap(_require_partition, (0, 1))
+
+
+@nx._dispatchable
+def intra_community_edges(G, partition):
+    """Returns the number of intra-community edges for a partition of `G`.
+
+    Parameters
+    ----------
+    G : NetworkX graph.
+
+    partition : iterable of sets of nodes
+        This must be a partition of the nodes of `G`.
+
+    The "intra-community edges" are those edges joining a pair of nodes
+    in the same block of the partition.
+
+    """
+    return sum(G.subgraph(block).size() for block in partition)
+
+
+@nx._dispatchable
+def inter_community_edges(G, partition):
+    """Returns the number of inter-community edges for a partition of `G`.
+    according to the given
+    partition of the nodes of `G`.
+
+    Parameters
+    ----------
+    G : NetworkX graph.
+
+    partition : iterable of sets of nodes
+        This must be a partition of the nodes of `G`.
+
+    The *inter-community edges* are those edges joining a pair of nodes
+    in different blocks of the partition.
+
+    Implementation note: this function creates an intermediate graph
+    that may require the same amount of memory as that of `G`.
+
+    """
+    # Alternate implementation that does not require constructing a new
+    # graph object (but does require constructing an affiliation
+    # dictionary):
+    #
+    #     aff = dict(chain.from_iterable(((v, block) for v in block)
+    #                                    for block in partition))
+    #     return sum(1 for u, v in G.edges() if aff[u] != aff[v])
+    #
+    MG = nx.MultiDiGraph if G.is_directed() else nx.MultiGraph
+    return nx.quotient_graph(G, partition, create_using=MG).size()
+
+
+@nx._dispatchable
+def inter_community_non_edges(G, partition):
+    """Returns the number of inter-community non-edges according to the
+    given partition of the nodes of `G`.
+
+    Parameters
+    ----------
+    G : NetworkX graph.
+
+    partition : iterable of sets of nodes
+        This must be a partition of the nodes of `G`.
+
+    A *non-edge* is a pair of nodes (undirected if `G` is undirected)
+    that are not adjacent in `G`. The *inter-community non-edges* are
+    those non-edges on a pair of nodes in different blocks of the
+    partition.
+
+    Implementation note: this function creates two intermediate graphs,
+    which may require up to twice the amount of memory as required to
+    store `G`.
+
+    """
+    # Alternate implementation that does not require constructing two
+    # new graph objects (but does require constructing an affiliation
+    # dictionary):
+    #
+    #     aff = dict(chain.from_iterable(((v, block) for v in block)
+    #                                    for block in partition))
+    #     return sum(1 for u, v in nx.non_edges(G) if aff[u] != aff[v])
+    #
+    return inter_community_edges(nx.complement(G), partition)
+
+
+@nx._dispatchable(edge_attrs="weight")
+def modularity(G, communities, weight="weight", resolution=1):
+    r"""Returns the modularity of the given partition of the graph.
+
+    Modularity is defined in [1]_ as
+
+    .. math::
+        Q = \frac{1}{2m} \sum_{ij} \left( A_{ij} - \gamma\frac{k_ik_j}{2m}\right)
+            \delta(c_i,c_j)
+
+    where $m$ is the number of edges (or sum of all edge weights as in [5]_),
+    $A$ is the adjacency matrix of `G`, $k_i$ is the (weighted) degree of $i$,
+    $\gamma$ is the resolution parameter, and $\delta(c_i, c_j)$ is 1 if $i$ and
+    $j$ are in the same community else 0.
+
+    According to [2]_ (and verified by some algebra) this can be reduced to
+
+    .. math::
+       Q = \sum_{c=1}^{n}
+       \left[ \frac{L_c}{m} - \gamma\left( \frac{k_c}{2m} \right) ^2 \right]
+
+    where the sum iterates over all communities $c$, $m$ is the number of edges,
+    $L_c$ is the number of intra-community links for community $c$,
+    $k_c$ is the sum of degrees of the nodes in community $c$,
+    and $\gamma$ is the resolution parameter.
+
+    The resolution parameter sets an arbitrary tradeoff between intra-group
+    edges and inter-group edges. More complex grouping patterns can be
+    discovered by analyzing the same network with multiple values of gamma
+    and then combining the results [3]_. That said, it is very common to
+    simply use gamma=1. More on the choice of gamma is in [4]_.
+
+    The second formula is the one actually used in calculation of the modularity.
+    For directed graphs the second formula replaces $k_c$ with $k^{in}_c k^{out}_c$.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+
+    communities : list or iterable of set of nodes
+        These node sets must represent a partition of G's nodes.
+
+    weight : string or None, optional (default="weight")
+        The edge attribute that holds the numerical value used
+        as a weight. If None or an edge does not have that attribute,
+        then that edge has weight 1.
+
+    resolution : float (default=1)
+        If resolution is less than 1, modularity favors larger communities.
+        Greater than 1 favors smaller communities.
+
+    Returns
+    -------
+    Q : float
+        The modularity of the partition.
+
+    Raises
+    ------
+    NotAPartition
+        If `communities` is not a partition of the nodes of `G`.
+
+    Examples
+    --------
+    >>> G = nx.barbell_graph(3, 0)
+    >>> nx.community.modularity(G, [{0, 1, 2}, {3, 4, 5}])
+    0.35714285714285715
+    >>> nx.community.modularity(G, nx.community.label_propagation_communities(G))
+    0.35714285714285715
+
+    References
+    ----------
+    .. [1] M. E. J. Newman "Networks: An Introduction", page 224.
+       Oxford University Press, 2011.
+    .. [2] Clauset, Aaron, Mark EJ Newman, and Cristopher Moore.
+       "Finding community structure in very large networks."
+       Phys. Rev. E 70.6 (2004). 
+    .. [3] Reichardt and Bornholdt "Statistical Mechanics of Community Detection"
+       Phys. Rev. E 74, 016110, 2006. https://doi.org/10.1103/PhysRevE.74.016110
+    .. [4] M. E. J. Newman, "Equivalence between modularity optimization and
+       maximum likelihood methods for community detection"
+       Phys. Rev. E 94, 052315, 2016. https://doi.org/10.1103/PhysRevE.94.052315
+    .. [5] Blondel, V.D. et al. "Fast unfolding of communities in large
+       networks" J. Stat. Mech 10008, 1-12 (2008).
+       https://doi.org/10.1088/1742-5468/2008/10/P10008
+    """
+    if not isinstance(communities, list):
+        communities = list(communities)
+    if not is_partition(G, communities):
+        raise NotAPartition(G, communities)
+
+    directed = G.is_directed()
+    if directed:
+        out_degree = dict(G.out_degree(weight=weight))
+        in_degree = dict(G.in_degree(weight=weight))
+        m = sum(out_degree.values())
+        norm = 1 / m**2
+    else:
+        out_degree = in_degree = dict(G.degree(weight=weight))
+        deg_sum = sum(out_degree.values())
+        m = deg_sum / 2
+        norm = 1 / deg_sum**2
+
+    def community_contribution(community):
+        comm = set(community)
+        L_c = sum(wt for u, v, wt in G.edges(comm, data=weight, default=1) if v in comm)
+
+        out_degree_sum = sum(out_degree[u] for u in comm)
+        in_degree_sum = sum(in_degree[u] for u in comm) if directed else out_degree_sum
+
+        return L_c / m - resolution * out_degree_sum * in_degree_sum * norm
+
+    return sum(map(community_contribution, communities))
+
+
+@require_partition
+@nx._dispatchable
+def partition_quality(G, partition):
+    """Returns the coverage and performance of a partition of G.
+
+    The *coverage* of a partition is the ratio of the number of
+    intra-community edges to the total number of edges in the graph.
+
+    The *performance* of a partition is the number of
+    intra-community edges plus inter-community non-edges divided by the total
+    number of potential edges.
+
+    This algorithm has complexity $O(C^2 + L)$ where C is the number of
+    communities and L is the number of links.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    partition : sequence
+        Partition of the nodes of `G`, represented as a sequence of
+        sets of nodes (blocks). Each block of the partition represents a
+        community.
+
+    Returns
+    -------
+    (float, float)
+        The (coverage, performance) tuple of the partition, as defined above.
+
+    Raises
+    ------
+    NetworkXError
+        If `partition` is not a valid partition of the nodes of `G`.
+
+    Notes
+    -----
+    If `G` is a multigraph;
+        - for coverage, the multiplicity of edges is counted
+        - for performance, the result is -1 (total number of possible edges is not defined)
+
+    References
+    ----------
+    .. [1] Santo Fortunato.
+           "Community Detection in Graphs".
+           *Physical Reports*, Volume 486, Issue 3--5 pp. 75--174
+           
+    """
+
+    node_community = {}
+    for i, community in enumerate(partition):
+        for node in community:
+            node_community[node] = i
+
+    # `performance` is not defined for multigraphs
+    if not G.is_multigraph():
+        # Iterate over the communities, quadratic, to calculate `possible_inter_community_edges`
+        possible_inter_community_edges = sum(
+            len(p1) * len(p2) for p1, p2 in combinations(partition, 2)
+        )
+
+        if G.is_directed():
+            possible_inter_community_edges *= 2
+    else:
+        possible_inter_community_edges = 0
+
+    # Compute the number of edges in the complete graph -- `n` nodes,
+    # directed or undirected, depending on `G`
+    n = len(G)
+    total_pairs = n * (n - 1)
+    if not G.is_directed():
+        total_pairs //= 2
+
+    intra_community_edges = 0
+    inter_community_non_edges = possible_inter_community_edges
+
+    # Iterate over the links to count `intra_community_edges` and `inter_community_non_edges`
+    for e in G.edges():
+        if node_community[e[0]] == node_community[e[1]]:
+            intra_community_edges += 1
+        else:
+            inter_community_non_edges -= 1
+
+    coverage = intra_community_edges / len(G.edges)
+
+    if G.is_multigraph():
+        performance = -1.0
+    else:
+        performance = (intra_community_edges + inter_community_non_edges) / total_pairs
+
+    return coverage, performance
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/components/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/components/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f9ae2caba856daba534037f4a6f967abfad49552
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/components/__init__.py
@@ -0,0 +1,6 @@
+from .connected import *
+from .strongly_connected import *
+from .weakly_connected import *
+from .attracting import *
+from .biconnected import *
+from .semiconnected import *
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/components/attracting.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/components/attracting.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d77cd93d70efab5f29c77c7d135f4730e4c3a4a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/components/attracting.py
@@ -0,0 +1,115 @@
+"""Attracting components."""
+
+import networkx as nx
+from networkx.utils.decorators import not_implemented_for
+
+__all__ = [
+    "number_attracting_components",
+    "attracting_components",
+    "is_attracting_component",
+]
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable
+def attracting_components(G):
+    """Generates the attracting components in `G`.
+
+    An attracting component in a directed graph `G` is a strongly connected
+    component with the property that a random walker on the graph will never
+    leave the component, once it enters the component.
+
+    The nodes in attracting components can also be thought of as recurrent
+    nodes.  If a random walker enters the attractor containing the node, then
+    the node will be visited infinitely often.
+
+    To obtain induced subgraphs on each component use:
+    ``(G.subgraph(c).copy() for c in attracting_components(G))``
+
+    Parameters
+    ----------
+    G : DiGraph, MultiDiGraph
+        The graph to be analyzed.
+
+    Returns
+    -------
+    attractors : generator of sets
+        A generator of sets of nodes, one for each attracting component of G.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If the input graph is undirected.
+
+    See Also
+    --------
+    number_attracting_components
+    is_attracting_component
+
+    """
+    scc = list(nx.strongly_connected_components(G))
+    cG = nx.condensation(G, scc)
+    for n in cG:
+        if cG.out_degree(n) == 0:
+            yield scc[n]
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable
+def number_attracting_components(G):
+    """Returns the number of attracting components in `G`.
+
+    Parameters
+    ----------
+    G : DiGraph, MultiDiGraph
+        The graph to be analyzed.
+
+    Returns
+    -------
+    n : int
+        The number of attracting components in G.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If the input graph is undirected.
+
+    See Also
+    --------
+    attracting_components
+    is_attracting_component
+
+    """
+    return sum(1 for ac in attracting_components(G))
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable
+def is_attracting_component(G):
+    """Returns True if `G` consists of a single attracting component.
+
+    Parameters
+    ----------
+    G : DiGraph, MultiDiGraph
+        The graph to be analyzed.
+
+    Returns
+    -------
+    attracting : bool
+        True if `G` has a single attracting component. Otherwise, False.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If the input graph is undirected.
+
+    See Also
+    --------
+    attracting_components
+    number_attracting_components
+
+    """
+    ac = list(attracting_components(G))
+    if len(ac) == 1:
+        return len(ac[0]) == len(G)
+    return False
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/components/biconnected.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/components/biconnected.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd0f3865bb18e9c9eb37d768c7fd3caceb1cde86
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/components/biconnected.py
@@ -0,0 +1,394 @@
+"""Biconnected components and articulation points."""
+
+from itertools import chain
+
+import networkx as nx
+from networkx.utils.decorators import not_implemented_for
+
+__all__ = [
+    "biconnected_components",
+    "biconnected_component_edges",
+    "is_biconnected",
+    "articulation_points",
+]
+
+
+@not_implemented_for("directed")
+@nx._dispatchable
+def is_biconnected(G):
+    """Returns True if the graph is biconnected, False otherwise.
+
+    A graph is biconnected if, and only if, it cannot be disconnected by
+    removing only one node (and all edges incident on that node).  If
+    removing a node increases the number of disconnected components
+    in the graph, that node is called an articulation point, or cut
+    vertex.  A biconnected graph has no articulation points.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+        An undirected graph.
+
+    Returns
+    -------
+    biconnected : bool
+        True if the graph is biconnected, False otherwise.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If the input graph is not undirected.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> print(nx.is_biconnected(G))
+    False
+    >>> G.add_edge(0, 3)
+    >>> print(nx.is_biconnected(G))
+    True
+
+    See Also
+    --------
+    biconnected_components
+    articulation_points
+    biconnected_component_edges
+    is_strongly_connected
+    is_weakly_connected
+    is_connected
+    is_semiconnected
+
+    Notes
+    -----
+    The algorithm to find articulation points and biconnected
+    components is implemented using a non-recursive depth-first-search
+    (DFS) that keeps track of the highest level that back edges reach
+    in the DFS tree.  A node `n` is an articulation point if, and only
+    if, there exists a subtree rooted at `n` such that there is no
+    back edge from any successor of `n` that links to a predecessor of
+    `n` in the DFS tree.  By keeping track of all the edges traversed
+    by the DFS we can obtain the biconnected components because all
+    edges of a bicomponent will be traversed consecutively between
+    articulation points.
+
+    References
+    ----------
+    .. [1] Hopcroft, J.; Tarjan, R. (1973).
+       "Efficient algorithms for graph manipulation".
+       Communications of the ACM 16: 372–378. doi:10.1145/362248.362272
+
+    """
+    bccs = biconnected_components(G)
+    try:
+        bcc = next(bccs)
+    except StopIteration:
+        # No bicomponents (empty graph?)
+        return False
+    try:
+        next(bccs)
+    except StopIteration:
+        # Only one bicomponent
+        return len(bcc) == len(G)
+    else:
+        # Multiple bicomponents
+        return False
+
+
+@not_implemented_for("directed")
+@nx._dispatchable
+def biconnected_component_edges(G):
+    """Returns a generator of lists of edges, one list for each biconnected
+    component of the input graph.
+
+    Biconnected components are maximal subgraphs such that the removal of a
+    node (and all edges incident on that node) will not disconnect the
+    subgraph.  Note that nodes may be part of more than one biconnected
+    component.  Those nodes are articulation points, or cut vertices.
+    However, each edge belongs to one, and only one, biconnected component.
+
+    Notice that by convention a dyad is considered a biconnected component.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+        An undirected graph.
+
+    Returns
+    -------
+    edges : generator of lists
+        Generator of lists of edges, one list for each bicomponent.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If the input graph is not undirected.
+
+    Examples
+    --------
+    >>> G = nx.barbell_graph(4, 2)
+    >>> print(nx.is_biconnected(G))
+    False
+    >>> bicomponents_edges = list(nx.biconnected_component_edges(G))
+    >>> len(bicomponents_edges)
+    5
+    >>> G.add_edge(2, 8)
+    >>> print(nx.is_biconnected(G))
+    True
+    >>> bicomponents_edges = list(nx.biconnected_component_edges(G))
+    >>> len(bicomponents_edges)
+    1
+
+    See Also
+    --------
+    is_biconnected,
+    biconnected_components,
+    articulation_points,
+
+    Notes
+    -----
+    The algorithm to find articulation points and biconnected
+    components is implemented using a non-recursive depth-first-search
+    (DFS) that keeps track of the highest level that back edges reach
+    in the DFS tree.  A node `n` is an articulation point if, and only
+    if, there exists a subtree rooted at `n` such that there is no
+    back edge from any successor of `n` that links to a predecessor of
+    `n` in the DFS tree.  By keeping track of all the edges traversed
+    by the DFS we can obtain the biconnected components because all
+    edges of a bicomponent will be traversed consecutively between
+    articulation points.
+
+    References
+    ----------
+    .. [1] Hopcroft, J.; Tarjan, R. (1973).
+           "Efficient algorithms for graph manipulation".
+           Communications of the ACM 16: 372–378. doi:10.1145/362248.362272
+
+    """
+    yield from _biconnected_dfs(G, components=True)
+
+
+@not_implemented_for("directed")
+@nx._dispatchable
+def biconnected_components(G):
+    """Returns a generator of sets of nodes, one set for each biconnected
+    component of the graph
+
+    Biconnected components are maximal subgraphs such that the removal of a
+    node (and all edges incident on that node) will not disconnect the
+    subgraph. Note that nodes may be part of more than one biconnected
+    component.  Those nodes are articulation points, or cut vertices.  The
+    removal of articulation points will increase the number of connected
+    components of the graph.
+
+    Notice that by convention a dyad is considered a biconnected component.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+        An undirected graph.
+
+    Returns
+    -------
+    nodes : generator
+        Generator of sets of nodes, one set for each biconnected component.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If the input graph is not undirected.
+
+    Examples
+    --------
+    >>> G = nx.lollipop_graph(5, 1)
+    >>> print(nx.is_biconnected(G))
+    False
+    >>> bicomponents = list(nx.biconnected_components(G))
+    >>> len(bicomponents)
+    2
+    >>> G.add_edge(0, 5)
+    >>> print(nx.is_biconnected(G))
+    True
+    >>> bicomponents = list(nx.biconnected_components(G))
+    >>> len(bicomponents)
+    1
+
+    You can generate a sorted list of biconnected components, largest
+    first, using sort.
+
+    >>> G.remove_edge(0, 5)
+    >>> [len(c) for c in sorted(nx.biconnected_components(G), key=len, reverse=True)]
+    [5, 2]
+
+    If you only want the largest connected component, it's more
+    efficient to use max instead of sort.
+
+    >>> Gc = max(nx.biconnected_components(G), key=len)
+
+    To create the components as subgraphs use:
+    ``(G.subgraph(c).copy() for c in biconnected_components(G))``
+
+    See Also
+    --------
+    is_biconnected
+    articulation_points
+    biconnected_component_edges
+    k_components : this function is a special case where k=2
+    bridge_components : similar to this function, but is defined using
+        2-edge-connectivity instead of 2-node-connectivity.
+
+    Notes
+    -----
+    The algorithm to find articulation points and biconnected
+    components is implemented using a non-recursive depth-first-search
+    (DFS) that keeps track of the highest level that back edges reach
+    in the DFS tree.  A node `n` is an articulation point if, and only
+    if, there exists a subtree rooted at `n` such that there is no
+    back edge from any successor of `n` that links to a predecessor of
+    `n` in the DFS tree.  By keeping track of all the edges traversed
+    by the DFS we can obtain the biconnected components because all
+    edges of a bicomponent will be traversed consecutively between
+    articulation points.
+
+    References
+    ----------
+    .. [1] Hopcroft, J.; Tarjan, R. (1973).
+           "Efficient algorithms for graph manipulation".
+           Communications of the ACM 16: 372–378. doi:10.1145/362248.362272
+
+    """
+    for comp in _biconnected_dfs(G, components=True):
+        yield set(chain.from_iterable(comp))
+
+
+@not_implemented_for("directed")
+@nx._dispatchable
+def articulation_points(G):
+    """Yield the articulation points, or cut vertices, of a graph.
+
+    An articulation point or cut vertex is any node whose removal (along with
+    all its incident edges) increases the number of connected components of
+    a graph.  An undirected connected graph without articulation points is
+    biconnected. Articulation points belong to more than one biconnected
+    component of a graph.
+
+    Notice that by convention a dyad is considered a biconnected component.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+        An undirected graph.
+
+    Yields
+    ------
+    node
+        An articulation point in the graph.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If the input graph is not undirected.
+
+    Examples
+    --------
+
+    >>> G = nx.barbell_graph(4, 2)
+    >>> print(nx.is_biconnected(G))
+    False
+    >>> len(list(nx.articulation_points(G)))
+    4
+    >>> G.add_edge(2, 8)
+    >>> print(nx.is_biconnected(G))
+    True
+    >>> len(list(nx.articulation_points(G)))
+    0
+
+    See Also
+    --------
+    is_biconnected
+    biconnected_components
+    biconnected_component_edges
+
+    Notes
+    -----
+    The algorithm to find articulation points and biconnected
+    components is implemented using a non-recursive depth-first-search
+    (DFS) that keeps track of the highest level that back edges reach
+    in the DFS tree.  A node `n` is an articulation point if, and only
+    if, there exists a subtree rooted at `n` such that there is no
+    back edge from any successor of `n` that links to a predecessor of
+    `n` in the DFS tree.  By keeping track of all the edges traversed
+    by the DFS we can obtain the biconnected components because all
+    edges of a bicomponent will be traversed consecutively between
+    articulation points.
+
+    References
+    ----------
+    .. [1] Hopcroft, J.; Tarjan, R. (1973).
+           "Efficient algorithms for graph manipulation".
+           Communications of the ACM 16: 372–378. doi:10.1145/362248.362272
+
+    """
+    seen = set()
+    for articulation in _biconnected_dfs(G, components=False):
+        if articulation not in seen:
+            seen.add(articulation)
+            yield articulation
+
+
+@not_implemented_for("directed")
+def _biconnected_dfs(G, components=True):
+    # depth-first search algorithm to generate articulation points
+    # and biconnected components
+    visited = set()
+    for start in G:
+        if start in visited:
+            continue
+        discovery = {start: 0}  # time of first discovery of node during search
+        low = {start: 0}
+        root_children = 0
+        visited.add(start)
+        edge_stack = []
+        stack = [(start, start, iter(G[start]))]
+        edge_index = {}
+        while stack:
+            grandparent, parent, children = stack[-1]
+            try:
+                child = next(children)
+                if grandparent == child:
+                    continue
+                if child in visited:
+                    if discovery[child] <= discovery[parent]:  # back edge
+                        low[parent] = min(low[parent], discovery[child])
+                        if components:
+                            edge_index[parent, child] = len(edge_stack)
+                            edge_stack.append((parent, child))
+                else:
+                    low[child] = discovery[child] = len(discovery)
+                    visited.add(child)
+                    stack.append((parent, child, iter(G[child])))
+                    if components:
+                        edge_index[parent, child] = len(edge_stack)
+                        edge_stack.append((parent, child))
+
+            except StopIteration:
+                stack.pop()
+                if len(stack) > 1:
+                    if low[parent] >= discovery[grandparent]:
+                        if components:
+                            ind = edge_index[grandparent, parent]
+                            yield edge_stack[ind:]
+                            del edge_stack[ind:]
+
+                        else:
+                            yield grandparent
+                    low[grandparent] = min(low[parent], low[grandparent])
+                elif stack:  # length 1 so grandparent is root
+                    root_children += 1
+                    if components:
+                        ind = edge_index[grandparent, parent]
+                        yield edge_stack[ind:]
+                        del edge_stack[ind:]
+        if not components:
+            # root node is articulation point if it has more than 1 child
+            if root_children > 1:
+                yield start
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/components/connected.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/components/connected.py
new file mode 100644
index 0000000000000000000000000000000000000000..0dd009a8220b08ce47c71afe8239958786f09209
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/components/connected.py
@@ -0,0 +1,282 @@
+"""Connected components."""
+
+import networkx as nx
+from networkx.utils.decorators import not_implemented_for
+
+from ...utils import arbitrary_element
+
+__all__ = [
+    "number_connected_components",
+    "connected_components",
+    "is_connected",
+    "node_connected_component",
+]
+
+
+@not_implemented_for("directed")
+@nx._dispatchable
+def connected_components(G):
+    """Generate connected components.
+
+    The connected components of an undirected graph partition the graph into
+    disjoint sets of nodes. Each of these sets induces a subgraph of graph
+    `G` that is connected and not part of any larger connected subgraph.
+
+    A graph is connected (:func:`is_connected`) if, for every pair of distinct
+    nodes, there is a path between them. If there is a pair of nodes for
+    which such path does not exist, the graph is not connected (also referred
+    to as "disconnected").
+
+    A graph consisting of a single node and no edges is connected.
+    Connectivity is undefined for the null graph (graph with no nodes).
+
+    Parameters
+    ----------
+    G : NetworkX graph
+       An undirected graph
+
+    Yields
+    ------
+    comp : set
+       A set of nodes in one connected component of the graph.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If G is directed.
+
+    Examples
+    --------
+    Generate a sorted list of connected components, largest first.
+
+    >>> G = nx.path_graph(4)
+    >>> nx.add_path(G, [10, 11, 12])
+    >>> [len(c) for c in sorted(nx.connected_components(G), key=len, reverse=True)]
+    [4, 3]
+
+    If you only want the largest connected component, it's more
+    efficient to use max instead of sort.
+
+    >>> largest_cc = max(nx.connected_components(G), key=len)
+
+    To create the induced subgraph of each component use:
+
+    >>> S = [G.subgraph(c).copy() for c in nx.connected_components(G)]
+
+    See Also
+    --------
+    number_connected_components
+    is_connected
+    number_weakly_connected_components
+    number_strongly_connected_components
+
+    Notes
+    -----
+    This function is for undirected graphs only. For directed graphs, use
+    :func:`strongly_connected_components` or
+    :func:`weakly_connected_components`.
+
+    The algorithm is based on a Breadth-First Search (BFS) traversal and its
+    time complexity is $O(n + m)$, where $n$ is the number of nodes and $m$ the
+    number of edges in the graph.
+
+    """
+    seen = set()
+    n = len(G)  # must be outside the loop to avoid performance hit with graph views
+    for v in G:
+        if v not in seen:
+            c = _plain_bfs(G, n - len(seen), v)
+            seen.update(c)
+            yield c
+
+
+@not_implemented_for("directed")
+@nx._dispatchable
+def number_connected_components(G):
+    """Returns the number of connected components.
+
+    The connected components of an undirected graph partition the graph into
+    disjoint sets of nodes. Each of these sets induces a subgraph of graph
+    `G` that is connected and not part of any larger connected subgraph.
+
+    A graph is connected (:func:`is_connected`) if, for every pair of distinct
+    nodes, there is a path between them. If there is a pair of nodes for
+    which such path does not exist, the graph is not connected (also referred
+    to as "disconnected").
+
+    A graph consisting of a single node and no edges is connected.
+    Connectivity is undefined for the null graph (graph with no nodes).
+
+    Parameters
+    ----------
+    G : NetworkX graph
+       An undirected graph.
+
+    Returns
+    -------
+    n : integer
+       Number of connected components
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If G is directed.
+
+    Examples
+    --------
+    >>> G = nx.Graph([(0, 1), (1, 2), (5, 6), (3, 4)])
+    >>> nx.number_connected_components(G)
+    3
+
+    See Also
+    --------
+    connected_components
+    is_connected
+    number_weakly_connected_components
+    number_strongly_connected_components
+
+    Notes
+    -----
+    This function is for undirected graphs only. For directed graphs, use
+    :func:`number_strongly_connected_components` or
+    :func:`number_weakly_connected_components`.
+
+    The algorithm is based on a Breadth-First Search (BFS) traversal and its
+    time complexity is $O(n + m)$, where $n$ is the number of nodes and $m$ the
+    number of edges in the graph.
+
+    """
+    return sum(1 for _ in connected_components(G))
+
+
+@not_implemented_for("directed")
+@nx._dispatchable
+def is_connected(G):
+    """Returns True if the graph is connected, False otherwise.
+
+    A graph is connected if, for every pair of distinct nodes, there is a
+    path between them. If there is a pair of nodes for which such path does
+    not exist, the graph is not connected (also referred to as "disconnected").
+
+    A graph consisting of a single node and no edges is connected.
+    Connectivity is undefined for the null graph (graph with no nodes).
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+       An undirected graph.
+
+    Returns
+    -------
+    connected : bool
+      True if the graph is connected, False otherwise.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If G is directed.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> print(nx.is_connected(G))
+    True
+
+    See Also
+    --------
+    is_strongly_connected
+    is_weakly_connected
+    is_semiconnected
+    is_biconnected
+    connected_components
+
+    Notes
+    -----
+    This function is for undirected graphs only. For directed graphs, use
+    :func:`is_strongly_connected` or :func:`is_weakly_connected`.
+
+    The algorithm is based on a Breadth-First Search (BFS) traversal and its
+    time complexity is $O(n + m)$, where $n$ is the number of nodes and $m$ the
+    number of edges in the graph.
+
+    """
+    n = len(G)
+    if n == 0:
+        raise nx.NetworkXPointlessConcept(
+            "Connectivity is undefined for the null graph."
+        )
+    return len(next(connected_components(G))) == n
+
+
+@not_implemented_for("directed")
+@nx._dispatchable
+def node_connected_component(G, n):
+    """Returns the set of nodes in the component of graph containing node n.
+
+    A connected component is a set of nodes that induces a subgraph of graph
+    `G` that is connected and not part of any larger connected subgraph.
+
+    A graph is connected (:func:`is_connected`) if, for every pair of distinct
+    nodes, there is a path between them. If there is a pair of nodes for
+    which such path does not exist, the graph is not connected (also referred
+    to as "disconnected").
+
+    A graph consisting of a single node and no edges is connected.
+    Connectivity is undefined for the null graph (graph with no nodes).
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+       An undirected graph.
+
+    n : node label
+       A node in G
+
+    Returns
+    -------
+    comp : set
+       A set of nodes in the component of G containing node n.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If G is directed.
+
+    Examples
+    --------
+    >>> G = nx.Graph([(0, 1), (1, 2), (5, 6), (3, 4)])
+    >>> nx.node_connected_component(G, 0)  # nodes of component that contains node 0
+    {0, 1, 2}
+
+    See Also
+    --------
+    connected_components
+
+    Notes
+    -----
+    This function is for undirected graphs only.
+
+    The algorithm is based on a Breadth-First Search (BFS) traversal and its
+    time complexity is $O(n + m)$, where $n$ is the number of nodes and $m$ the
+    number of edges in the graph.
+
+    """
+    return _plain_bfs(G, len(G), n)
+
+
+def _plain_bfs(G, n, source):
+    """A fast BFS node generator"""
+    adj = G._adj
+    seen = {source}
+    nextlevel = [source]
+    while nextlevel:
+        thislevel = nextlevel
+        nextlevel = []
+        for v in thislevel:
+            for w in adj[v]:
+                if w not in seen:
+                    seen.add(w)
+                    nextlevel.append(w)
+            if len(seen) == n:
+                return seen
+    return seen
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/components/semiconnected.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/components/semiconnected.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ca5d762ca882524d1406f9295fa3a238fedb724
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/components/semiconnected.py
@@ -0,0 +1,71 @@
+"""Semiconnectedness."""
+
+import networkx as nx
+from networkx.utils import not_implemented_for, pairwise
+
+__all__ = ["is_semiconnected"]
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable
+def is_semiconnected(G):
+    r"""Returns True if the graph is semiconnected, False otherwise.
+
+    A graph is semiconnected if and only if for any pair of nodes, either one
+    is reachable from the other, or they are mutually reachable.
+
+    This function uses a theorem that states that a DAG is semiconnected
+    if for any topological sort, for node $v_n$ in that sort, there is an
+    edge $(v_i, v_{i+1})$. That allows us to check if a non-DAG `G` is
+    semiconnected by condensing the graph: i.e. constructing a new graph `H`
+    with nodes being the strongly connected components of `G`, and edges
+    (scc_1, scc_2) if there is a edge $(v_1, v_2)$ in `G` for some
+    $v_1 \in scc_1$ and $v_2 \in scc_2$. That results in a DAG, so we compute
+    the topological sort of `H` and check if for every $n$ there is an edge
+    $(scc_n, scc_{n+1})$.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        A directed graph.
+
+    Returns
+    -------
+    semiconnected : bool
+        True if the graph is semiconnected, False otherwise.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If the input graph is undirected.
+
+    NetworkXPointlessConcept
+        If the graph is empty.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4, create_using=nx.DiGraph())
+    >>> print(nx.is_semiconnected(G))
+    True
+    >>> G = nx.DiGraph([(1, 2), (3, 2)])
+    >>> print(nx.is_semiconnected(G))
+    False
+
+    See Also
+    --------
+    is_strongly_connected
+    is_weakly_connected
+    is_connected
+    is_biconnected
+    """
+    if len(G) == 0:
+        raise nx.NetworkXPointlessConcept(
+            "Connectivity is undefined for the null graph."
+        )
+
+    if not nx.is_weakly_connected(G):
+        return False
+
+    H = nx.condensation(G)
+
+    return all(H.has_edge(u, v) for u, v in pairwise(nx.topological_sort(H)))
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/components/strongly_connected.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/components/strongly_connected.py
new file mode 100644
index 0000000000000000000000000000000000000000..a69a6c8801fe896bd0bf6813637072480e1a28d5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/components/strongly_connected.py
@@ -0,0 +1,359 @@
+"""Strongly connected components."""
+
+import networkx as nx
+from networkx.utils.decorators import not_implemented_for
+
+__all__ = [
+    "number_strongly_connected_components",
+    "strongly_connected_components",
+    "is_strongly_connected",
+    "kosaraju_strongly_connected_components",
+    "condensation",
+]
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable
+def strongly_connected_components(G):
+    """Generate nodes in strongly connected components of graph.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+        A directed graph.
+
+    Returns
+    -------
+    comp : generator of sets
+        A generator of sets of nodes, one for each strongly connected
+        component of G.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If G is undirected.
+
+    Examples
+    --------
+    Generate a sorted list of strongly connected components, largest first.
+
+    >>> G = nx.cycle_graph(4, create_using=nx.DiGraph())
+    >>> nx.add_cycle(G, [10, 11, 12])
+    >>> [
+    ...     len(c)
+    ...     for c in sorted(nx.strongly_connected_components(G), key=len, reverse=True)
+    ... ]
+    [4, 3]
+
+    If you only want the largest component, it's more efficient to
+    use max instead of sort.
+
+    >>> largest = max(nx.strongly_connected_components(G), key=len)
+
+    See Also
+    --------
+    connected_components
+    weakly_connected_components
+    kosaraju_strongly_connected_components
+
+    Notes
+    -----
+    Uses Tarjan's algorithm[1]_ with Nuutila's modifications[2]_.
+    Nonrecursive version of algorithm.
+
+    References
+    ----------
+    .. [1] Depth-first search and linear graph algorithms, R. Tarjan
+       SIAM Journal of Computing 1(2):146-160, (1972).
+
+    .. [2] On finding the strongly connected components in a directed graph.
+       E. Nuutila and E. Soisalon-Soinen
+       Information Processing Letters 49(1): 9-14, (1994)..
+
+    """
+    preorder = {}
+    lowlink = {}
+    scc_found = set()
+    scc_queue = []
+    i = 0  # Preorder counter
+    neighbors = {v: iter(G._adj[v]) for v in G}
+    for source in G:
+        if source not in scc_found:
+            queue = [source]
+            while queue:
+                v = queue[-1]
+                if v not in preorder:
+                    i = i + 1
+                    preorder[v] = i
+                done = True
+                for w in neighbors[v]:
+                    if w not in preorder:
+                        queue.append(w)
+                        done = False
+                        break
+                if done:
+                    lowlink[v] = preorder[v]
+                    for w in G._adj[v]:
+                        if w not in scc_found:
+                            if preorder[w] > preorder[v]:
+                                lowlink[v] = min([lowlink[v], lowlink[w]])
+                            else:
+                                lowlink[v] = min([lowlink[v], preorder[w]])
+                    queue.pop()
+                    if lowlink[v] == preorder[v]:
+                        scc = {v}
+                        while scc_queue and preorder[scc_queue[-1]] > preorder[v]:
+                            k = scc_queue.pop()
+                            scc.add(k)
+                        scc_found.update(scc)
+                        yield scc
+                    else:
+                        scc_queue.append(v)
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable
+def kosaraju_strongly_connected_components(G, source=None):
+    """Generate nodes in strongly connected components of graph.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+        A directed graph.
+
+    source : node, optional (default=None)
+        Specify a node from which to start the depth-first search.
+        If not provided, the algorithm will start from an arbitrary node.
+
+    Yields
+    ------
+    set
+        A set of all nodes in a strongly connected component of `G`.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is undirected.
+
+    NetworkXError
+        If `source` is not a node in `G`.
+
+    Examples
+    --------
+    Generate a list of strongly connected components of a graph:
+
+    >>> G = nx.cycle_graph(4, create_using=nx.DiGraph())
+    >>> nx.add_cycle(G, [10, 11, 12])
+    >>> sorted(nx.kosaraju_strongly_connected_components(G), key=len, reverse=True)
+    [{0, 1, 2, 3}, {10, 11, 12}]
+
+    If you only want the largest component, it's more efficient to
+    use `max()` instead of `sorted()`.
+
+    >>> max(nx.kosaraju_strongly_connected_components(G), key=len)
+    {0, 1, 2, 3}
+
+    See Also
+    --------
+    strongly_connected_components
+
+    Notes
+    -----
+    Uses Kosaraju's algorithm.
+    """
+    post = list(nx.dfs_postorder_nodes(G.reverse(copy=False), source=source))
+    n = len(post)
+    seen = set()
+    while post and len(seen) < n:
+        r = post.pop()
+        if r in seen:
+            continue
+        new = {r}
+        seen.add(r)
+        stack = [r]
+        while stack and len(seen) < n:
+            v = stack.pop()
+            for w in G._adj[v]:
+                if w not in seen:
+                    new.add(w)
+                    seen.add(w)
+                    stack.append(w)
+        yield new
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable
+def number_strongly_connected_components(G):
+    """Returns number of strongly connected components in graph.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+       A directed graph.
+
+    Returns
+    -------
+    n : integer
+       Number of strongly connected components
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If G is undirected.
+
+    Examples
+    --------
+    >>> G = nx.DiGraph(
+    ...     [(0, 1), (1, 2), (2, 0), (2, 3), (4, 5), (3, 4), (5, 6), (6, 3), (6, 7)]
+    ... )
+    >>> nx.number_strongly_connected_components(G)
+    3
+
+    See Also
+    --------
+    strongly_connected_components
+    number_connected_components
+    number_weakly_connected_components
+
+    Notes
+    -----
+    For directed graphs only.
+    """
+    return sum(1 for scc in strongly_connected_components(G))
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable
+def is_strongly_connected(G):
+    """Test directed graph for strong connectivity.
+
+    A directed graph is strongly connected if and only if every vertex in
+    the graph is reachable from every other vertex.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+       A directed graph.
+
+    Returns
+    -------
+    connected : bool
+      True if the graph is strongly connected, False otherwise.
+
+    Examples
+    --------
+    >>> G = nx.DiGraph([(0, 1), (1, 2), (2, 3), (3, 0), (2, 4), (4, 2)])
+    >>> nx.is_strongly_connected(G)
+    True
+    >>> G.remove_edge(2, 3)
+    >>> nx.is_strongly_connected(G)
+    False
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If G is undirected.
+
+    See Also
+    --------
+    is_weakly_connected
+    is_semiconnected
+    is_connected
+    is_biconnected
+    strongly_connected_components
+
+    Notes
+    -----
+    For directed graphs only.
+    """
+    if len(G) == 0:
+        raise nx.NetworkXPointlessConcept(
+            """Connectivity is undefined for the null graph."""
+        )
+
+    return len(next(strongly_connected_components(G))) == len(G)
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable(returns_graph=True)
+def condensation(G, scc=None):
+    """Returns the condensation of G.
+
+    The condensation of G is the graph with each of the strongly connected
+    components contracted into a single node.
+
+    Parameters
+    ----------
+    G : NetworkX DiGraph
+       A directed graph.
+
+    scc:  list or generator (optional, default=None)
+       Strongly connected components. If provided, the elements in
+       `scc` must partition the nodes in `G`. If not provided, it will be
+       calculated as scc=nx.strongly_connected_components(G).
+
+    Returns
+    -------
+    C : NetworkX DiGraph
+       The condensation graph C of G.  The node labels are integers
+       corresponding to the index of the component in the list of
+       strongly connected components of G.  C has a graph attribute named
+       'mapping' with a dictionary mapping the original nodes to the
+       nodes in C to which they belong.  Each node in C also has a node
+       attribute 'members' with the set of original nodes in G that
+       form the SCC that the node in C represents.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If G is undirected.
+
+    Examples
+    --------
+    Contracting two sets of strongly connected nodes into two distinct SCC
+    using the barbell graph.
+
+    >>> G = nx.barbell_graph(4, 0)
+    >>> G.remove_edge(3, 4)
+    >>> G = nx.DiGraph(G)
+    >>> H = nx.condensation(G)
+    >>> H.nodes.data()
+    NodeDataView({0: {'members': {0, 1, 2, 3}}, 1: {'members': {4, 5, 6, 7}}})
+    >>> H.graph["mapping"]
+    {0: 0, 1: 0, 2: 0, 3: 0, 4: 1, 5: 1, 6: 1, 7: 1}
+
+    Contracting a complete graph into one single SCC.
+
+    >>> G = nx.complete_graph(7, create_using=nx.DiGraph)
+    >>> H = nx.condensation(G)
+    >>> H.nodes
+    NodeView((0,))
+    >>> H.nodes.data()
+    NodeDataView({0: {'members': {0, 1, 2, 3, 4, 5, 6}}})
+
+    Notes
+    -----
+    After contracting all strongly connected components to a single node,
+    the resulting graph is a directed acyclic graph.
+
+    """
+    if scc is None:
+        scc = nx.strongly_connected_components(G)
+    mapping = {}
+    members = {}
+    C = nx.DiGraph()
+    # Add mapping dict as graph attribute
+    C.graph["mapping"] = mapping
+    if len(G) == 0:
+        return C
+    for i, component in enumerate(scc):
+        members[i] = component
+        mapping.update((n, i) for n in component)
+    number_of_components = i + 1
+    C.add_nodes_from(range(number_of_components))
+    C.add_edges_from(
+        (mapping[u], mapping[v]) for u, v in G.edges() if mapping[u] != mapping[v]
+    )
+    # Add a list of members (ie original nodes) to each node (ie scc) in C.
+    nx.set_node_attributes(C, members, "members")
+    return C
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/components/weakly_connected.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/components/weakly_connected.py
new file mode 100644
index 0000000000000000000000000000000000000000..fdb07ff7de5d93b1b01889217d5d8698bbf7fa32
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/components/weakly_connected.py
@@ -0,0 +1,196 @@
+"""Weakly connected components."""
+
+import networkx as nx
+from networkx.utils.decorators import not_implemented_for
+
+__all__ = [
+    "number_weakly_connected_components",
+    "weakly_connected_components",
+    "is_weakly_connected",
+]
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable
+def weakly_connected_components(G):
+    """Generate weakly connected components of G.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        A directed graph
+
+    Returns
+    -------
+    comp : generator of sets
+        A generator of sets of nodes, one for each weakly connected
+        component of G.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If G is undirected.
+
+    Examples
+    --------
+    Generate a sorted list of weakly connected components, largest first.
+
+    >>> G = nx.path_graph(4, create_using=nx.DiGraph())
+    >>> nx.add_path(G, [10, 11, 12])
+    >>> [
+    ...     len(c)
+    ...     for c in sorted(nx.weakly_connected_components(G), key=len, reverse=True)
+    ... ]
+    [4, 3]
+
+    If you only want the largest component, it's more efficient to
+    use max instead of sort:
+
+    >>> largest_cc = max(nx.weakly_connected_components(G), key=len)
+
+    See Also
+    --------
+    connected_components
+    strongly_connected_components
+
+    Notes
+    -----
+    For directed graphs only.
+
+    """
+    seen = set()
+    n = len(G)  # must be outside the loop to avoid performance hit with graph views
+    for v in G:
+        if v not in seen:
+            c = _plain_bfs(G, n - len(seen), v)
+            seen.update(c)
+            yield c
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable
+def number_weakly_connected_components(G):
+    """Returns the number of weakly connected components in G.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        A directed graph.
+
+    Returns
+    -------
+    n : integer
+        Number of weakly connected components
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If G is undirected.
+
+    Examples
+    --------
+    >>> G = nx.DiGraph([(0, 1), (2, 1), (3, 4)])
+    >>> nx.number_weakly_connected_components(G)
+    2
+
+    See Also
+    --------
+    weakly_connected_components
+    number_connected_components
+    number_strongly_connected_components
+
+    Notes
+    -----
+    For directed graphs only.
+
+    """
+    return sum(1 for _ in weakly_connected_components(G))
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable
+def is_weakly_connected(G):
+    """Test directed graph for weak connectivity.
+
+    A directed graph is weakly connected if and only if the graph
+    is connected when the direction of the edge between nodes is ignored.
+
+    Note that if a graph is strongly connected (i.e. the graph is connected
+    even when we account for directionality), it is by definition weakly
+    connected as well.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+        A directed graph.
+
+    Returns
+    -------
+    connected : bool
+        True if the graph is weakly connected, False otherwise.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If G is undirected.
+
+    Examples
+    --------
+    >>> G = nx.DiGraph([(0, 1), (2, 1)])
+    >>> G.add_node(3)
+    >>> nx.is_weakly_connected(G)  # node 3 is not connected to the graph
+    False
+    >>> G.add_edge(2, 3)
+    >>> nx.is_weakly_connected(G)
+    True
+
+    See Also
+    --------
+    is_strongly_connected
+    is_semiconnected
+    is_connected
+    is_biconnected
+    weakly_connected_components
+
+    Notes
+    -----
+    For directed graphs only.
+
+    """
+    n = len(G)
+    if n == 0:
+        raise nx.NetworkXPointlessConcept(
+            """Connectivity is undefined for the null graph."""
+        )
+
+    return len(next(weakly_connected_components(G))) == n
+
+
+def _plain_bfs(G, n, source):
+    """A fast BFS node generator
+
+    The direction of the edge between nodes is ignored.
+
+    For directed graphs only.
+
+    """
+    Gsucc = G._succ
+    Gpred = G._pred
+    seen = {source}
+    nextlevel = [source]
+
+    while nextlevel:
+        thislevel = nextlevel
+        nextlevel = []
+        for v in thislevel:
+            for w in Gsucc[v]:
+                if w not in seen:
+                    seen.add(w)
+                    nextlevel.append(w)
+            for w in Gpred[v]:
+                if w not in seen:
+                    seen.add(w)
+                    nextlevel.append(w)
+            if len(seen) == n:
+                return seen
+    return seen
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/core.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/core.py
new file mode 100644
index 0000000000000000000000000000000000000000..fec26ec984161eb2d927019d90540690cbc5aa45
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/core.py
@@ -0,0 +1,588 @@
+"""
+Find the k-cores of a graph.
+
+The k-core is found by recursively pruning nodes with degrees less than k.
+
+See the following references for details:
+
+An O(m) Algorithm for Cores Decomposition of Networks
+Vladimir Batagelj and Matjaz Zaversnik, 2003.
+https://arxiv.org/abs/cs.DS/0310049
+
+Generalized Cores
+Vladimir Batagelj and Matjaz Zaversnik, 2002.
+https://arxiv.org/pdf/cs/0202039
+
+For directed graphs a more general notion is that of D-cores which
+looks at (k, l) restrictions on (in, out) degree. The (k, k) D-core
+is the k-core.
+
+D-cores: Measuring Collaboration of Directed Graphs Based on Degeneracy
+Christos Giatsidis, Dimitrios M. Thilikos, Michalis Vazirgiannis, ICDM 2011.
+http://www.graphdegeneracy.org/dcores_ICDM_2011.pdf
+
+Multi-scale structure and topological anomaly detection via a new network \
+statistic: The onion decomposition
+L. Hébert-Dufresne, J. A. Grochow, and A. Allard
+Scientific Reports 6, 31708 (2016)
+http://doi.org/10.1038/srep31708
+
+"""
+
+import networkx as nx
+
+__all__ = [
+    "core_number",
+    "k_core",
+    "k_shell",
+    "k_crust",
+    "k_corona",
+    "k_truss",
+    "onion_layers",
+]
+
+
+@nx.utils.not_implemented_for("multigraph")
+@nx._dispatchable
+def core_number(G):
+    """Returns the core number for each node.
+
+    A k-core is a maximal subgraph that contains nodes of degree k or more.
+
+    The core number of a node is the largest value k of a k-core containing
+    that node.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+       An undirected or directed graph
+
+    Returns
+    -------
+    core_number : dictionary
+       A dictionary keyed by node to the core number.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is a multigraph or contains self loops.
+
+    Notes
+    -----
+    For directed graphs the node degree is defined to be the
+    in-degree + out-degree.
+
+    Examples
+    --------
+    >>> degrees = [0, 1, 2, 2, 2, 2, 3]
+    >>> H = nx.havel_hakimi_graph(degrees)
+    >>> nx.core_number(H)
+    {0: 1, 1: 2, 2: 2, 3: 2, 4: 1, 5: 2, 6: 0}
+    >>> G = nx.DiGraph()
+    >>> G.add_edges_from([(1, 2), (2, 1), (2, 3), (2, 4), (3, 4), (4, 3)])
+    >>> nx.core_number(G)
+    {1: 2, 2: 2, 3: 2, 4: 2}
+
+    References
+    ----------
+    .. [1] An O(m) Algorithm for Cores Decomposition of Networks
+       Vladimir Batagelj and Matjaz Zaversnik, 2003.
+       https://arxiv.org/abs/cs.DS/0310049
+    """
+    if nx.number_of_selfloops(G) > 0:
+        msg = (
+            "Input graph has self loops which is not permitted; "
+            "Consider using G.remove_edges_from(nx.selfloop_edges(G))."
+        )
+        raise nx.NetworkXNotImplemented(msg)
+    degrees = dict(G.degree())
+    # Sort nodes by degree.
+    nodes = sorted(degrees, key=degrees.get)
+    bin_boundaries = [0]
+    curr_degree = 0
+    for i, v in enumerate(nodes):
+        if degrees[v] > curr_degree:
+            bin_boundaries.extend([i] * (degrees[v] - curr_degree))
+            curr_degree = degrees[v]
+    node_pos = {v: pos for pos, v in enumerate(nodes)}
+    # The initial guess for the core number of a node is its degree.
+    core = degrees
+    nbrs = {v: list(nx.all_neighbors(G, v)) for v in G}
+    for v in nodes:
+        for u in nbrs[v]:
+            if core[u] > core[v]:
+                nbrs[u].remove(v)
+                pos = node_pos[u]
+                bin_start = bin_boundaries[core[u]]
+                node_pos[u] = bin_start
+                node_pos[nodes[bin_start]] = pos
+                nodes[bin_start], nodes[pos] = nodes[pos], nodes[bin_start]
+                bin_boundaries[core[u]] += 1
+                core[u] -= 1
+    return core
+
+
+def _core_subgraph(G, k_filter, k=None, core=None):
+    """Returns the subgraph induced by nodes passing filter `k_filter`.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+       The graph or directed graph to process
+    k_filter : filter function
+       This function filters the nodes chosen. It takes three inputs:
+       A node of G, the filter's cutoff, and the core dict of the graph.
+       The function should return a Boolean value.
+    k : int, optional
+      The order of the core. If not specified use the max core number.
+      This value is used as the cutoff for the filter.
+    core : dict, optional
+      Precomputed core numbers keyed by node for the graph `G`.
+      If not specified, the core numbers will be computed from `G`.
+
+    """
+    if core is None:
+        core = core_number(G)
+    if k is None:
+        k = max(core.values())
+    nodes = (v for v in core if k_filter(v, k, core))
+    return G.subgraph(nodes).copy()
+
+
+@nx.utils.not_implemented_for("multigraph")
+@nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
+def k_core(G, k=None, core_number=None):
+    """Returns the k-core of G.
+
+    A k-core is a maximal subgraph that contains nodes of degree `k` or more.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+      A graph or directed graph
+    k : int, optional
+      The order of the core. If not specified return the main core.
+    core_number : dictionary, optional
+      Precomputed core numbers for the graph G.
+
+    Returns
+    -------
+    G : NetworkX graph
+      The k-core subgraph
+
+    Raises
+    ------
+    NetworkXNotImplemented
+      The k-core is not defined for multigraphs or graphs with self loops.
+
+    Notes
+    -----
+    The main core is the core with `k` as the largest core_number.
+
+    For directed graphs the node degree is defined to be the
+    in-degree + out-degree.
+
+    Graph, node, and edge attributes are copied to the subgraph.
+
+    Examples
+    --------
+    >>> degrees = [0, 1, 2, 2, 2, 2, 3]
+    >>> H = nx.havel_hakimi_graph(degrees)
+    >>> H.degree
+    DegreeView({0: 1, 1: 2, 2: 2, 3: 2, 4: 2, 5: 3, 6: 0})
+    >>> nx.k_core(H).nodes
+    NodeView((1, 2, 3, 5))
+
+    See Also
+    --------
+    core_number
+
+    References
+    ----------
+    .. [1] An O(m) Algorithm for Cores Decomposition of Networks
+       Vladimir Batagelj and Matjaz Zaversnik,  2003.
+       https://arxiv.org/abs/cs.DS/0310049
+    """
+
+    def k_filter(v, k, c):
+        return c[v] >= k
+
+    return _core_subgraph(G, k_filter, k, core_number)
+
+
+@nx.utils.not_implemented_for("multigraph")
+@nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
+def k_shell(G, k=None, core_number=None):
+    """Returns the k-shell of G.
+
+    The k-shell is the subgraph induced by nodes with core number k.
+    That is, nodes in the k-core that are not in the (k+1)-core.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+      A graph or directed graph.
+    k : int, optional
+      The order of the shell. If not specified return the outer shell.
+    core_number : dictionary, optional
+      Precomputed core numbers for the graph G.
+
+
+    Returns
+    -------
+    G : NetworkX graph
+       The k-shell subgraph
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        The k-shell is not implemented for multigraphs or graphs with self loops.
+
+    Notes
+    -----
+    This is similar to k_corona but in that case only neighbors in the
+    k-core are considered.
+
+    For directed graphs the node degree is defined to be the
+    in-degree + out-degree.
+
+    Graph, node, and edge attributes are copied to the subgraph.
+
+    Examples
+    --------
+    >>> degrees = [0, 1, 2, 2, 2, 2, 3]
+    >>> H = nx.havel_hakimi_graph(degrees)
+    >>> H.degree
+    DegreeView({0: 1, 1: 2, 2: 2, 3: 2, 4: 2, 5: 3, 6: 0})
+    >>> nx.k_shell(H, k=1).nodes
+    NodeView((0, 4))
+
+    See Also
+    --------
+    core_number
+    k_corona
+
+
+    References
+    ----------
+    .. [1] A model of Internet topology using k-shell decomposition
+       Shai Carmi, Shlomo Havlin, Scott Kirkpatrick, Yuval Shavitt,
+       and Eran Shir, PNAS  July 3, 2007   vol. 104  no. 27  11150-11154
+       http://www.pnas.org/content/104/27/11150.full
+    """
+
+    def k_filter(v, k, c):
+        return c[v] == k
+
+    return _core_subgraph(G, k_filter, k, core_number)
+
+
+@nx.utils.not_implemented_for("multigraph")
+@nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
+def k_crust(G, k=None, core_number=None):
+    """Returns the k-crust of G.
+
+    The k-crust is the graph G with the edges of the k-core removed
+    and isolated nodes found after the removal of edges are also removed.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+       A graph or directed graph.
+    k : int, optional
+      The order of the shell. If not specified return the main crust.
+    core_number : dictionary, optional
+      Precomputed core numbers for the graph G.
+
+    Returns
+    -------
+    G : NetworkX graph
+       The k-crust subgraph
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        The k-crust is not implemented for multigraphs or graphs with self loops.
+
+    Notes
+    -----
+    This definition of k-crust is different than the definition in [1]_.
+    The k-crust in [1]_ is equivalent to the k+1 crust of this algorithm.
+
+    For directed graphs the node degree is defined to be the
+    in-degree + out-degree.
+
+    Graph, node, and edge attributes are copied to the subgraph.
+
+    Examples
+    --------
+    >>> degrees = [0, 1, 2, 2, 2, 2, 3]
+    >>> H = nx.havel_hakimi_graph(degrees)
+    >>> H.degree
+    DegreeView({0: 1, 1: 2, 2: 2, 3: 2, 4: 2, 5: 3, 6: 0})
+    >>> nx.k_crust(H, k=1).nodes
+    NodeView((0, 4, 6))
+
+    See Also
+    --------
+    core_number
+
+    References
+    ----------
+    .. [1] A model of Internet topology using k-shell decomposition
+       Shai Carmi, Shlomo Havlin, Scott Kirkpatrick, Yuval Shavitt,
+       and Eran Shir, PNAS  July 3, 2007   vol. 104  no. 27  11150-11154
+       http://www.pnas.org/content/104/27/11150.full
+    """
+    # Default for k is one less than in _core_subgraph, so just inline.
+    #    Filter is c[v] <= k
+    if core_number is None:
+        core_number = nx.core_number(G)
+    if k is None:
+        k = max(core_number.values()) - 1
+    nodes = (v for v in core_number if core_number[v] <= k)
+    return G.subgraph(nodes).copy()
+
+
+@nx.utils.not_implemented_for("multigraph")
+@nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
+def k_corona(G, k, core_number=None):
+    """Returns the k-corona of G.
+
+    The k-corona is the subgraph of nodes in the k-core which have
+    exactly k neighbors in the k-core.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+       A graph or directed graph
+    k : int
+       The order of the corona.
+    core_number : dictionary, optional
+       Precomputed core numbers for the graph G.
+
+    Returns
+    -------
+    G : NetworkX graph
+       The k-corona subgraph
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        The k-corona is not defined for multigraphs or graphs with self loops.
+
+    Notes
+    -----
+    For directed graphs the node degree is defined to be the
+    in-degree + out-degree.
+
+    Graph, node, and edge attributes are copied to the subgraph.
+
+    Examples
+    --------
+    >>> degrees = [0, 1, 2, 2, 2, 2, 3]
+    >>> H = nx.havel_hakimi_graph(degrees)
+    >>> H.degree
+    DegreeView({0: 1, 1: 2, 2: 2, 3: 2, 4: 2, 5: 3, 6: 0})
+    >>> nx.k_corona(H, k=2).nodes
+    NodeView((1, 2, 3, 5))
+
+    See Also
+    --------
+    core_number
+
+    References
+    ----------
+    .. [1]  k -core (bootstrap) percolation on complex networks:
+       Critical phenomena and nonlocal effects,
+       A. V. Goltsev, S. N. Dorogovtsev, and J. F. F. Mendes,
+       Phys. Rev. E 73, 056101 (2006)
+       http://link.aps.org/doi/10.1103/PhysRevE.73.056101
+    """
+
+    def func(v, k, c):
+        return c[v] == k and k == sum(1 for w in G[v] if c[w] >= k)
+
+    return _core_subgraph(G, func, k, core_number)
+
+
+@nx.utils.not_implemented_for("directed")
+@nx.utils.not_implemented_for("multigraph")
+@nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
+def k_truss(G, k):
+    """Returns the k-truss of `G`.
+
+    The k-truss is the maximal induced subgraph of `G` which contains at least
+    three vertices where every edge is incident to at least `k-2` triangles.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+      An undirected graph
+    k : int
+      The order of the truss
+
+    Returns
+    -------
+    H : NetworkX graph
+      The k-truss subgraph
+
+    Raises
+    ------
+    NetworkXNotImplemented
+      If `G` is a multigraph or directed graph or if it contains self loops.
+
+    Notes
+    -----
+    A k-clique is a (k-2)-truss and a k-truss is a (k+1)-core.
+
+    Graph, node, and edge attributes are copied to the subgraph.
+
+    K-trusses were originally defined in [2] which states that the k-truss
+    is the maximal induced subgraph where each edge belongs to at least
+    `k-2` triangles. A more recent paper, [1], uses a slightly different
+    definition requiring that each edge belong to at least `k` triangles.
+    This implementation uses the original definition of `k-2` triangles.
+
+    Examples
+    --------
+    >>> degrees = [0, 1, 2, 2, 2, 2, 3]
+    >>> H = nx.havel_hakimi_graph(degrees)
+    >>> H.degree
+    DegreeView({0: 1, 1: 2, 2: 2, 3: 2, 4: 2, 5: 3, 6: 0})
+    >>> nx.k_truss(H, k=2).nodes
+    NodeView((0, 1, 2, 3, 4, 5))
+
+    References
+    ----------
+    .. [1] Bounds and Algorithms for k-truss. Paul Burkhardt, Vance Faber,
+       David G. Harris, 2018. https://arxiv.org/abs/1806.05523v2
+    .. [2] Trusses: Cohesive Subgraphs for Social Network Analysis. Jonathan
+       Cohen, 2005.
+    """
+    if nx.number_of_selfloops(G) > 0:
+        msg = (
+            "Input graph has self loops which is not permitted; "
+            "Consider using G.remove_edges_from(nx.selfloop_edges(G))."
+        )
+        raise nx.NetworkXNotImplemented(msg)
+
+    H = G.copy()
+
+    n_dropped = 1
+    while n_dropped > 0:
+        n_dropped = 0
+        to_drop = []
+        seen = set()
+        for u in H:
+            nbrs_u = set(H[u])
+            seen.add(u)
+            new_nbrs = [v for v in nbrs_u if v not in seen]
+            for v in new_nbrs:
+                if len(nbrs_u & set(H[v])) < (k - 2):
+                    to_drop.append((u, v))
+        H.remove_edges_from(to_drop)
+        n_dropped = len(to_drop)
+        H.remove_nodes_from(list(nx.isolates(H)))
+
+    return H
+
+
+@nx.utils.not_implemented_for("multigraph")
+@nx.utils.not_implemented_for("directed")
+@nx._dispatchable
+def onion_layers(G):
+    """Returns the layer of each vertex in an onion decomposition of the graph.
+
+    The onion decomposition refines the k-core decomposition by providing
+    information on the internal organization of each k-shell. It is usually
+    used alongside the `core numbers`.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        An undirected graph without self loops.
+
+    Returns
+    -------
+    od_layers : dictionary
+        A dictionary keyed by node to the onion layer. The layers are
+        contiguous integers starting at 1.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is a multigraph or directed graph or if it contains self loops.
+
+    Examples
+    --------
+    >>> degrees = [0, 1, 2, 2, 2, 2, 3]
+    >>> H = nx.havel_hakimi_graph(degrees)
+    >>> H.degree
+    DegreeView({0: 1, 1: 2, 2: 2, 3: 2, 4: 2, 5: 3, 6: 0})
+    >>> nx.onion_layers(H)
+    {6: 1, 0: 2, 4: 3, 1: 4, 2: 4, 3: 4, 5: 4}
+
+    See Also
+    --------
+    core_number
+
+    References
+    ----------
+    .. [1] Multi-scale structure and topological anomaly detection via a new
+       network statistic: The onion decomposition
+       L. Hébert-Dufresne, J. A. Grochow, and A. Allard
+       Scientific Reports 6, 31708 (2016)
+       http://doi.org/10.1038/srep31708
+    .. [2] Percolation and the effective structure of complex networks
+       A. Allard and L. Hébert-Dufresne
+       Physical Review X 9, 011023 (2019)
+       http://doi.org/10.1103/PhysRevX.9.011023
+    """
+    if nx.number_of_selfloops(G) > 0:
+        msg = (
+            "Input graph contains self loops which is not permitted; "
+            "Consider using G.remove_edges_from(nx.selfloop_edges(G))."
+        )
+        raise nx.NetworkXNotImplemented(msg)
+    # Dictionaries to register the k-core/onion decompositions.
+    od_layers = {}
+    # Adjacency list
+    neighbors = {v: list(nx.all_neighbors(G, v)) for v in G}
+    # Effective degree of nodes.
+    degrees = dict(G.degree())
+    # Performs the onion decomposition.
+    current_core = 1
+    current_layer = 1
+    # Sets vertices of degree 0 to layer 1, if any.
+    isolated_nodes = list(nx.isolates(G))
+    if len(isolated_nodes) > 0:
+        for v in isolated_nodes:
+            od_layers[v] = current_layer
+            degrees.pop(v)
+        current_layer = 2
+    # Finds the layer for the remaining nodes.
+    while len(degrees) > 0:
+        # Sets the order for looking at nodes.
+        nodes = sorted(degrees, key=degrees.get)
+        # Sets properly the current core.
+        min_degree = degrees[nodes[0]]
+        if min_degree > current_core:
+            current_core = min_degree
+        # Identifies vertices in the current layer.
+        this_layer = []
+        for n in nodes:
+            if degrees[n] > current_core:
+                break
+            this_layer.append(n)
+        # Identifies the core/layer of the vertices in the current layer.
+        for v in this_layer:
+            od_layers[v] = current_layer
+            for n in neighbors[v]:
+                neighbors[n].remove(v)
+                degrees[n] = degrees[n] - 1
+            degrees.pop(v)
+        # Updates the layer count.
+        current_layer = current_layer + 1
+    # Returns the dictionaries containing the onion layer of each vertices.
+    return od_layers
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/covering.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/covering.py
new file mode 100644
index 0000000000000000000000000000000000000000..cdf607b3d798a9d2efeabb0bb95721d6370ca8cd
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/covering.py
@@ -0,0 +1,142 @@
+"""Functions related to graph covers."""
+
+from functools import partial
+from itertools import chain
+
+import networkx as nx
+from networkx.utils import arbitrary_element, not_implemented_for
+
+__all__ = ["min_edge_cover", "is_edge_cover"]
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable
+def min_edge_cover(G, matching_algorithm=None):
+    """Returns the min cardinality edge cover of the graph as a set of edges.
+
+    A smallest edge cover can be found in polynomial time by finding
+    a maximum matching and extending it greedily so that all nodes
+    are covered. This function follows that process. A maximum matching
+    algorithm can be specified for the first step of the algorithm.
+    The resulting set may return a set with one 2-tuple for each edge,
+    (the usual case) or with both 2-tuples `(u, v)` and `(v, u)` for
+    each edge. The latter is only done when a bipartite matching algorithm
+    is specified as `matching_algorithm`.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        An undirected graph.
+
+    matching_algorithm : function
+        A function that returns a maximum cardinality matching for `G`.
+        The function must take one input, the graph `G`, and return
+        either a set of edges (with only one direction for the pair of nodes)
+        or a dictionary mapping each node to its mate. If not specified,
+        :func:`~networkx.algorithms.matching.max_weight_matching` is used.
+        Common bipartite matching functions include
+        :func:`~networkx.algorithms.bipartite.matching.hopcroft_karp_matching`
+        or
+        :func:`~networkx.algorithms.bipartite.matching.eppstein_matching`.
+
+    Returns
+    -------
+    min_cover : set
+
+        A set of the edges in a minimum edge cover in the form of tuples.
+        It contains only one of the equivalent 2-tuples `(u, v)` and `(v, u)`
+        for each edge. If a bipartite method is used to compute the matching,
+        the returned set contains both the 2-tuples `(u, v)` and `(v, u)`
+        for each edge of a minimum edge cover.
+
+    Examples
+    --------
+    >>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
+    >>> sorted(nx.min_edge_cover(G))
+    [(2, 1), (3, 0)]
+
+    Notes
+    -----
+    An edge cover of a graph is a set of edges such that every node of
+    the graph is incident to at least one edge of the set.
+    The minimum edge cover is an edge covering of smallest cardinality.
+
+    Due to its implementation, the worst-case running time of this algorithm
+    is bounded by the worst-case running time of the function
+    ``matching_algorithm``.
+
+    Minimum edge cover for `G` can also be found using
+    :func:`~networkx.algorithms.bipartite.covering.min_edge_covering` which is
+    simply this function with a default matching algorithm of
+    :func:`~networkx.algorithms.bipartite.matching.hopcroft_karp_matching`
+    """
+    if len(G) == 0:
+        return set()
+    if nx.number_of_isolates(G) > 0:
+        # ``min_cover`` does not exist as there is an isolated node
+        raise nx.NetworkXException(
+            "Graph has a node with no edge incident on it, so no edge cover exists."
+        )
+    if matching_algorithm is None:
+        matching_algorithm = partial(nx.max_weight_matching, maxcardinality=True)
+    maximum_matching = matching_algorithm(G)
+    # ``min_cover`` is superset of ``maximum_matching``
+    try:
+        # bipartite matching algs return dict so convert if needed
+        min_cover = set(maximum_matching.items())
+        bipartite_cover = True
+    except AttributeError:
+        min_cover = maximum_matching
+        bipartite_cover = False
+    # iterate for uncovered nodes
+    uncovered_nodes = set(G) - {v for u, v in min_cover} - {u for u, v in min_cover}
+    for v in uncovered_nodes:
+        # Since `v` is uncovered, each edge incident to `v` will join it
+        # with a covered node (otherwise, if there were an edge joining
+        # uncovered nodes `u` and `v`, the maximum matching algorithm
+        # would have found it), so we can choose an arbitrary edge
+        # incident to `v`. (This applies only in a simple graph, not a
+        # multigraph.)
+        u = arbitrary_element(G[v])
+        min_cover.add((u, v))
+        if bipartite_cover:
+            min_cover.add((v, u))
+    return min_cover
+
+
+@not_implemented_for("directed")
+@nx._dispatchable
+def is_edge_cover(G, cover):
+    """Decides whether a set of edges is a valid edge cover of the graph.
+
+    Given a set of edges, whether it is an edge covering can
+    be decided if we just check whether all nodes of the graph
+    has an edge from the set, incident on it.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        An undirected bipartite graph.
+
+    cover : set
+        Set of edges to be checked.
+
+    Returns
+    -------
+    bool
+        Whether the set of edges is a valid edge cover of the graph.
+
+    Examples
+    --------
+    >>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
+    >>> cover = {(2, 1), (3, 0)}
+    >>> nx.is_edge_cover(G, cover)
+    True
+
+    Notes
+    -----
+    An edge cover of a graph is a set of edges such that every node of
+    the graph is incident to at least one edge of the set.
+    """
+    return set(G) <= set(chain.from_iterable(cover))
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/cuts.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/cuts.py
new file mode 100644
index 0000000000000000000000000000000000000000..040f4d49de1cb544410660ec0e4ca758fbd5975b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/cuts.py
@@ -0,0 +1,416 @@
+"""Functions for finding and evaluating cuts in a graph."""
+
+from itertools import chain
+
+import networkx as nx
+
+__all__ = [
+    "boundary_expansion",
+    "conductance",
+    "cut_size",
+    "edge_expansion",
+    "mixing_expansion",
+    "node_expansion",
+    "normalized_cut_size",
+    "volume",
+]
+
+
+# TODO STILL NEED TO UPDATE ALL THE DOCUMENTATION!
+
+
+@nx._dispatchable(edge_attrs="weight")
+def cut_size(G, S, T=None, weight=None):
+    """Returns the size of the cut between two sets of nodes.
+
+    A *cut* is a partition of the nodes of a graph into two sets. The
+    *cut size* is the sum of the weights of the edges "between" the two
+    sets of nodes.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    S : collection
+        A collection of nodes in `G`.
+
+    T : collection
+        A collection of nodes in `G`. If not specified, this is taken to
+        be the set complement of `S`.
+
+    weight : object
+        Edge attribute key to use as weight. If not specified, edges
+        have weight one.
+
+    Returns
+    -------
+    number
+        Total weight of all edges from nodes in set `S` to nodes in
+        set `T` (and, in the case of directed graphs, all edges from
+        nodes in `T` to nodes in `S`).
+
+    Examples
+    --------
+    In the graph with two cliques joined by a single edges, the natural
+    bipartition of the graph into two blocks, one for each clique,
+    yields a cut of weight one:
+
+    >>> G = nx.barbell_graph(3, 0)
+    >>> S = {0, 1, 2}
+    >>> T = {3, 4, 5}
+    >>> nx.cut_size(G, S, T)
+    1
+
+    Each parallel edge in a multigraph is counted when determining the
+    cut size:
+
+    >>> G = nx.MultiGraph(["ab", "ab"])
+    >>> S = {"a"}
+    >>> T = {"b"}
+    >>> nx.cut_size(G, S, T)
+    2
+
+    Notes
+    -----
+    In a multigraph, the cut size is the total weight of edges including
+    multiplicity.
+
+    """
+    edges = nx.edge_boundary(G, S, T, data=weight, default=1)
+    if G.is_directed():
+        edges = chain(edges, nx.edge_boundary(G, T, S, data=weight, default=1))
+    return sum(weight for u, v, weight in edges)
+
+
+@nx._dispatchable(edge_attrs="weight")
+def volume(G, S, weight=None):
+    """Returns the volume of a set of nodes.
+
+    The *volume* of a set *S* is the sum of the (out-)degrees of nodes
+    in *S* (taking into account parallel edges in multigraphs). [1]
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    S : collection
+        A collection of nodes in `G`.
+
+    weight : object
+        Edge attribute key to use as weight. If not specified, edges
+        have weight one.
+
+    Returns
+    -------
+    number
+        The volume of the set of nodes represented by `S` in the graph
+        `G`.
+
+    See also
+    --------
+    conductance
+    cut_size
+    edge_expansion
+    edge_boundary
+    normalized_cut_size
+
+    References
+    ----------
+    .. [1] David Gleich.
+           *Hierarchical Directed Spectral Graph Partitioning*.
+           
+
+    """
+    degree = G.out_degree if G.is_directed() else G.degree
+    return sum(d for v, d in degree(S, weight=weight))
+
+
+@nx._dispatchable(edge_attrs="weight")
+def normalized_cut_size(G, S, T=None, weight=None):
+    """Returns the normalized size of the cut between two sets of nodes.
+
+    The *normalized cut size* is the cut size times the sum of the
+    reciprocal sizes of the volumes of the two sets. [1]
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    S : collection
+        A collection of nodes in `G`.
+
+    T : collection
+        A collection of nodes in `G`.
+
+    weight : object
+        Edge attribute key to use as weight. If not specified, edges
+        have weight one.
+
+    Returns
+    -------
+    number
+        The normalized cut size between the two sets `S` and `T`.
+
+    Notes
+    -----
+    In a multigraph, the cut size is the total weight of edges including
+    multiplicity.
+
+    See also
+    --------
+    conductance
+    cut_size
+    edge_expansion
+    volume
+
+    References
+    ----------
+    .. [1] David Gleich.
+           *Hierarchical Directed Spectral Graph Partitioning*.
+           
+
+    """
+    if T is None:
+        T = set(G) - set(S)
+    num_cut_edges = cut_size(G, S, T=T, weight=weight)
+    volume_S = volume(G, S, weight=weight)
+    volume_T = volume(G, T, weight=weight)
+    return num_cut_edges * ((1 / volume_S) + (1 / volume_T))
+
+
+@nx._dispatchable(edge_attrs="weight")
+def conductance(G, S, T=None, weight=None):
+    """Returns the conductance of two sets of nodes.
+
+    The *conductance* is the quotient of the cut size and the smaller of
+    the volumes of the two sets. [1]
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    S : collection
+        A collection of nodes in `G`.
+
+    T : collection
+        A collection of nodes in `G`.
+
+    weight : object
+        Edge attribute key to use as weight. If not specified, edges
+        have weight one.
+
+    Returns
+    -------
+    number
+        The conductance between the two sets `S` and `T`.
+
+    See also
+    --------
+    cut_size
+    edge_expansion
+    normalized_cut_size
+    volume
+
+    References
+    ----------
+    .. [1] David Gleich.
+           *Hierarchical Directed Spectral Graph Partitioning*.
+           
+
+    """
+    if T is None:
+        T = set(G) - set(S)
+    num_cut_edges = cut_size(G, S, T, weight=weight)
+    volume_S = volume(G, S, weight=weight)
+    volume_T = volume(G, T, weight=weight)
+    return num_cut_edges / min(volume_S, volume_T)
+
+
+@nx._dispatchable(edge_attrs="weight")
+def edge_expansion(G, S, T=None, weight=None):
+    """Returns the edge expansion between two node sets.
+
+    The *edge expansion* is the quotient of the cut size and the smaller
+    of the cardinalities of the two sets. [1]
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    S : collection
+        A collection of nodes in `G`.
+
+    T : collection
+        A collection of nodes in `G`.
+
+    weight : object
+        Edge attribute key to use as weight. If not specified, edges
+        have weight one.
+
+    Returns
+    -------
+    number
+        The edge expansion between the two sets `S` and `T`.
+
+    See also
+    --------
+    boundary_expansion
+    mixing_expansion
+    node_expansion
+
+    References
+    ----------
+    .. [1] Fan Chung.
+           *Spectral Graph Theory*.
+           (CBMS Regional Conference Series in Mathematics, No. 92),
+           American Mathematical Society, 1997, ISBN 0-8218-0315-8
+           
+
+    """
+    if T is None:
+        T = set(G) - set(S)
+    num_cut_edges = cut_size(G, S, T=T, weight=weight)
+    return num_cut_edges / min(len(S), len(T))
+
+
+@nx._dispatchable(edge_attrs="weight")
+def mixing_expansion(G, S, T=None, weight=None):
+    """Returns the mixing expansion between two node sets.
+
+    The *mixing expansion* is the quotient of the cut size and twice the
+    number of edges in the graph. [1]
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    S : collection
+        A collection of nodes in `G`.
+
+    T : collection
+        A collection of nodes in `G`.
+
+    weight : object
+        Edge attribute key to use as weight. If not specified, edges
+        have weight one.
+
+    Returns
+    -------
+    number
+        The mixing expansion between the two sets `S` and `T`.
+
+    See also
+    --------
+    boundary_expansion
+    edge_expansion
+    node_expansion
+
+    References
+    ----------
+    .. [1] Vadhan, Salil P.
+           "Pseudorandomness."
+           *Foundations and Trends
+           in Theoretical Computer Science* 7.1–3 (2011): 1–336.
+           
+
+    """
+    num_cut_edges = cut_size(G, S, T=T, weight=weight)
+    num_total_edges = G.number_of_edges()
+    return num_cut_edges / (2 * num_total_edges)
+
+
+# TODO What is the generalization to two arguments, S and T? Does the
+# denominator become `min(len(S), len(T))`?
+@nx._dispatchable
+def node_expansion(G, S):
+    """Returns the node expansion of the set `S`.
+
+    The *node expansion* is the quotient of the size of the node
+    boundary of *S* and the cardinality of *S*. [1]
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    S : collection
+        A collection of nodes in `G`.
+
+    Returns
+    -------
+    number
+        The node expansion of the set `S`.
+
+    See also
+    --------
+    boundary_expansion
+    edge_expansion
+    mixing_expansion
+
+    References
+    ----------
+    .. [1] Vadhan, Salil P.
+           "Pseudorandomness."
+           *Foundations and Trends
+           in Theoretical Computer Science* 7.1–3 (2011): 1–336.
+           
+
+    """
+    neighborhood = set(chain.from_iterable(G.neighbors(v) for v in S))
+    return len(neighborhood) / len(S)
+
+
+@nx._dispatchable
+def boundary_expansion(G, S):
+    """Returns the boundary expansion of the set `S`.
+
+    The *boundary expansion* of a set `S` is the ratio between the size of its
+    node boundary and the cardinality of the set itself [1]_ .
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        The input graph.
+
+    S : collection
+        A collection of nodes in `G`.
+
+    Returns
+    -------
+    number
+        The boundary expansion ratio: size of node boundary / size of `S`.
+
+    Examples
+    --------
+    The node boundary is {2, 3} (size 2), divided by ``|S|=2``:
+
+    >>> G = nx.cycle_graph(4)
+    >>> S = {0, 1}
+    >>> nx.boundary_expansion(G, S)
+    1.0
+
+    For disconnected sets, e.g. here where the node boundary is ``{1, 3, 5}``:
+
+    >>> G = nx.cycle_graph(6)
+    >>> S = {0, 2, 4}
+    >>> nx.boundary_expansion(G, S)
+    1.0
+
+    See also
+    --------
+    :func:`~networkx.algorithms.boundary.node_boundary`
+    edge_expansion
+    mixing_expansion
+    node_expansion
+
+    Notes
+    -----
+    The node boundary is defined as all nodes not in `S` that are adjacent to
+    nodes in `S`.
+
+    References
+    ----------
+    .. [1] Vadhan, Salil P.
+       "Pseudorandomness." *Foundations and Trends in Theoretical Computer Science*
+       7.1–3 (2011): 1–336. 
+    """
+    return len(nx.node_boundary(G, S)) / len(S)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/cycles.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/cycles.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8d82be1c4ace22262d7045cbae0b3e69837bb16
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/cycles.py
@@ -0,0 +1,1234 @@
+"""
+========================
+Cycle finding algorithms
+========================
+"""
+
+from collections import defaultdict
+from itertools import combinations, product
+from math import inf
+
+import networkx as nx
+from networkx.utils import not_implemented_for, pairwise
+
+__all__ = [
+    "cycle_basis",
+    "simple_cycles",
+    "recursive_simple_cycles",
+    "find_cycle",
+    "minimum_cycle_basis",
+    "chordless_cycles",
+    "girth",
+]
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable
+def cycle_basis(G, root=None):
+    """Returns a list of cycles which form a basis for cycles of G.
+
+    A basis for cycles of a network is a minimal collection of
+    cycles such that any cycle in the network can be written
+    as a sum of cycles in the basis.  Here summation of cycles
+    is defined as "exclusive or" of the edges. Cycle bases are
+    useful, e.g. when deriving equations for electric circuits
+    using Kirchhoff's Laws.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+    root : node, optional
+       Specify starting node for basis.
+
+    Returns
+    -------
+    A list of cycle lists.  Each cycle list is a list of nodes
+    which forms a cycle (loop) in G.
+
+    Examples
+    --------
+    >>> G = nx.Graph()
+    >>> nx.add_cycle(G, [0, 1, 2, 3])
+    >>> nx.add_cycle(G, [0, 3, 4, 5])
+    >>> nx.cycle_basis(G, 0)
+    [[3, 4, 5, 0], [1, 2, 3, 0]]
+
+    Notes
+    -----
+    This is adapted from algorithm CACM 491 [1]_.
+
+    References
+    ----------
+    .. [1] Paton, K. An algorithm for finding a fundamental set of
+       cycles of a graph. Comm. ACM 12, 9 (Sept 1969), 514-518.
+
+    See Also
+    --------
+    simple_cycles
+    minimum_cycle_basis
+    """
+    gnodes = dict.fromkeys(G)  # set-like object that maintains node order
+    cycles = []
+    while gnodes:  # loop over connected components
+        if root is None:
+            root = gnodes.popitem()[0]
+        stack = [root]
+        pred = {root: root}
+        used = {root: set()}
+        while stack:  # walk the spanning tree finding cycles
+            z = stack.pop()  # use last-in so cycles easier to find
+            zused = used[z]
+            for nbr in G[z]:
+                if nbr not in used:  # new node
+                    pred[nbr] = z
+                    stack.append(nbr)
+                    used[nbr] = {z}
+                elif nbr == z:  # self loops
+                    cycles.append([z])
+                elif nbr not in zused:  # found a cycle
+                    pn = used[nbr]
+                    cycle = [nbr, z]
+                    p = pred[z]
+                    while p not in pn:
+                        cycle.append(p)
+                        p = pred[p]
+                    cycle.append(p)
+                    cycles.append(cycle)
+                    used[nbr].add(z)
+        for node in pred:
+            gnodes.pop(node, None)
+        root = None
+    return cycles
+
+
+@nx._dispatchable
+def simple_cycles(G, length_bound=None):
+    """Find simple cycles (elementary circuits) of a graph.
+
+    A "simple cycle", or "elementary circuit", is a closed path where
+    no node appears twice.  In a directed graph, two simple cycles are distinct
+    if they are not cyclic permutations of each other.  In an undirected graph,
+    two simple cycles are distinct if they are not cyclic permutations of each
+    other nor of the other's reversal.
+
+    Optionally, the cycles are bounded in length.  In the unbounded case, we use
+    a nonrecursive, iterator/generator version of Johnson's algorithm [1]_.  In
+    the bounded case, we use a version of the algorithm of Gupta and
+    Suzumura [2]_. There may be better algorithms for some cases [3]_ [4]_ [5]_.
+
+    The algorithms of Johnson, and Gupta and Suzumura, are enhanced by some
+    well-known preprocessing techniques.  When `G` is directed, we restrict our
+    attention to strongly connected components of `G`, generate all simple cycles
+    containing a certain node, remove that node, and further decompose the
+    remainder into strongly connected components.  When `G` is undirected, we
+    restrict our attention to biconnected components, generate all simple cycles
+    containing a particular edge, remove that edge, and further decompose the
+    remainder into biconnected components.
+
+    Note that multigraphs are supported by this function -- and in undirected
+    multigraphs, a pair of parallel edges is considered a cycle of length 2.
+    Likewise, self-loops are considered to be cycles of length 1.  We define
+    cycles as sequences of nodes; so the presence of loops and parallel edges
+    does not change the number of simple cycles in a graph.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+       A networkx graph. Undirected, directed, and multigraphs are all supported.
+
+    length_bound : int or None, optional (default=None)
+       If `length_bound` is an int, generate all simple cycles of `G` with length at
+       most `length_bound`.  Otherwise, generate all simple cycles of `G`.
+
+    Yields
+    ------
+    list of nodes
+       Each cycle is represented by a list of nodes along the cycle.
+
+    Examples
+    --------
+    >>> G = nx.DiGraph([(0, 0), (0, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2)])
+    >>> sorted(nx.simple_cycles(G))
+    [[0], [0, 1, 2], [0, 2], [1, 2], [2]]
+
+    To filter the cycles so that they don't include certain nodes or edges,
+    copy your graph and eliminate those nodes or edges before calling.
+    For example, to exclude self-loops from the above example:
+
+    >>> H = G.copy()
+    >>> H.remove_edges_from(nx.selfloop_edges(G))
+    >>> sorted(nx.simple_cycles(H))
+    [[0, 1, 2], [0, 2], [1, 2]]
+
+    Notes
+    -----
+    When `length_bound` is None, the time complexity is $O((n+e)(c+1))$ for $n$
+    nodes, $e$ edges and $c$ simple circuits.  Otherwise, when ``length_bound > 1``,
+    the time complexity is $O((c+n)(k-1)d^k)$ where $d$ is the average degree of
+    the nodes of `G` and $k$ = `length_bound`.
+
+    Raises
+    ------
+    ValueError
+        when ``length_bound < 0``.
+
+    References
+    ----------
+    .. [1] Finding all the elementary circuits of a directed graph.
+       D. B. Johnson, SIAM Journal on Computing 4, no. 1, 77-84, 1975.
+       https://doi.org/10.1137/0204007
+    .. [2] Finding All Bounded-Length Simple Cycles in a Directed Graph
+       A. Gupta and T. Suzumura https://arxiv.org/abs/2105.10094
+    .. [3] Enumerating the cycles of a digraph: a new preprocessing strategy.
+       G. Loizou and P. Thanish, Information Sciences, v. 27, 163-182, 1982.
+    .. [4] A search strategy for the elementary cycles of a directed graph.
+       J.L. Szwarcfiter and P.E. Lauer, BIT NUMERICAL MATHEMATICS,
+       v. 16, no. 2, 192-204, 1976.
+    .. [5] Optimal Listing of Cycles and st-Paths in Undirected Graphs
+        R. Ferreira and R. Grossi and A. Marino and N. Pisanti and R. Rizzi and
+        G. Sacomoto https://arxiv.org/abs/1205.2766
+
+    See Also
+    --------
+    cycle_basis
+    chordless_cycles
+    """
+
+    if length_bound is not None:
+        if length_bound == 0:
+            return
+        elif length_bound < 0:
+            raise ValueError("length bound must be non-negative")
+
+    directed = G.is_directed()
+    yield from ([v] for v, Gv in G.adj.items() if v in Gv)
+
+    if length_bound is not None and length_bound == 1:
+        return
+
+    if G.is_multigraph() and not directed:
+        visited = set()
+        for u, Gu in G.adj.items():
+            multiplicity = ((v, len(Guv)) for v, Guv in Gu.items() if v in visited)
+            yield from ([u, v] for v, m in multiplicity if m > 1)
+            visited.add(u)
+
+    # explicitly filter out loops; implicitly filter out parallel edges
+    if directed:
+        G = nx.DiGraph((u, v) for u, Gu in G.adj.items() for v in Gu if v != u)
+    else:
+        G = nx.Graph((u, v) for u, Gu in G.adj.items() for v in Gu if v != u)
+
+    # this case is not strictly necessary but improves performance
+    if length_bound is not None and length_bound == 2:
+        if directed:
+            visited = set()
+            for u, Gu in G.adj.items():
+                yield from (
+                    [v, u] for v in visited.intersection(Gu) if G.has_edge(v, u)
+                )
+                visited.add(u)
+        return
+
+    if directed:
+        yield from _directed_cycle_search(G, length_bound)
+    else:
+        yield from _undirected_cycle_search(G, length_bound)
+
+
+def _directed_cycle_search(G, length_bound):
+    """A dispatch function for `simple_cycles` for directed graphs.
+
+    We generate all cycles of G through binary partition.
+
+        1. Pick a node v in G which belongs to at least one cycle
+            a. Generate all cycles of G which contain the node v.
+            b. Recursively generate all cycles of G \\ v.
+
+    This is accomplished through the following:
+
+        1. Compute the strongly connected components SCC of G.
+        2. Select and remove a biconnected component C from BCC.  Select a
+           non-tree edge (u, v) of a depth-first search of G[C].
+        3. For each simple cycle P containing v in G[C], yield P.
+        4. Add the biconnected components of G[C \\ v] to BCC.
+
+    If the parameter length_bound is not None, then step 3 will be limited to
+    simple cycles of length at most length_bound.
+
+    Parameters
+    ----------
+    G : NetworkX DiGraph
+       A directed graph
+
+    length_bound : int or None
+       If length_bound is an int, generate all simple cycles of G with length at most length_bound.
+       Otherwise, generate all simple cycles of G.
+
+    Yields
+    ------
+    list of nodes
+       Each cycle is represented by a list of nodes along the cycle.
+    """
+
+    scc = nx.strongly_connected_components
+    components = [c for c in scc(G) if len(c) >= 2]
+    while components:
+        c = components.pop()
+        Gc = G.subgraph(c)
+        v = next(iter(c))
+        if length_bound is None:
+            yield from _johnson_cycle_search(Gc, [v])
+        else:
+            yield from _bounded_cycle_search(Gc, [v], length_bound)
+        # delete v after searching G, to make sure we can find v
+        G.remove_node(v)
+        components.extend(c for c in scc(Gc) if len(c) >= 2)
+
+
+def _undirected_cycle_search(G, length_bound):
+    """A dispatch function for `simple_cycles` for undirected graphs.
+
+    We generate all cycles of G through binary partition.
+
+        1. Pick an edge (u, v) in G which belongs to at least one cycle
+            a. Generate all cycles of G which contain the edge (u, v)
+            b. Recursively generate all cycles of G \\ (u, v)
+
+    This is accomplished through the following:
+
+        1. Compute the biconnected components BCC of G.
+        2. Select and remove a biconnected component C from BCC.  Select a
+           non-tree edge (u, v) of a depth-first search of G[C].
+        3. For each (v -> u) path P remaining in G[C] \\ (u, v), yield P.
+        4. Add the biconnected components of G[C] \\ (u, v) to BCC.
+
+    If the parameter length_bound is not None, then step 3 will be limited to simple paths
+    of length at most length_bound.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+       An undirected graph
+
+    length_bound : int or None
+       If length_bound is an int, generate all simple cycles of G with length at most length_bound.
+       Otherwise, generate all simple cycles of G.
+
+    Yields
+    ------
+    list of nodes
+       Each cycle is represented by a list of nodes along the cycle.
+    """
+
+    bcc = nx.biconnected_components
+    components = [c for c in bcc(G) if len(c) >= 3]
+    while components:
+        c = components.pop()
+        Gc = G.subgraph(c)
+        uv = list(next(iter(Gc.edges)))
+        G.remove_edge(*uv)
+        # delete (u, v) before searching G, to avoid fake 3-cycles [u, v, u]
+        if length_bound is None:
+            yield from _johnson_cycle_search(Gc, uv)
+        else:
+            yield from _bounded_cycle_search(Gc, uv, length_bound)
+        components.extend(c for c in bcc(Gc) if len(c) >= 3)
+
+
+class _NeighborhoodCache(dict):
+    """Very lightweight graph wrapper which caches neighborhoods as list.
+
+    This dict subclass uses the __missing__ functionality to query graphs for
+    their neighborhoods, and store the result as a list.  This is used to avoid
+    the performance penalty incurred by subgraph views.
+    """
+
+    def __init__(self, G):
+        self.G = G
+
+    def __missing__(self, v):
+        Gv = self[v] = list(self.G[v])
+        return Gv
+
+
+def _johnson_cycle_search(G, path):
+    """The main loop of the cycle-enumeration algorithm of Johnson.
+
+    Parameters
+    ----------
+    G : NetworkX Graph or DiGraph
+       A graph
+
+    path : list
+       A cycle prefix.  All cycles generated will begin with this prefix.
+
+    Yields
+    ------
+    list of nodes
+       Each cycle is represented by a list of nodes along the cycle.
+
+    References
+    ----------
+        .. [1] Finding all the elementary circuits of a directed graph.
+       D. B. Johnson, SIAM Journal on Computing 4, no. 1, 77-84, 1975.
+       https://doi.org/10.1137/0204007
+
+    """
+
+    G = _NeighborhoodCache(G)
+    blocked = set(path)
+    B = defaultdict(set)  # graph portions that yield no elementary circuit
+    start = path[0]
+    stack = [iter(G[path[-1]])]
+    closed = [False]
+    while stack:
+        nbrs = stack[-1]
+        for w in nbrs:
+            if w == start:
+                yield path[:]
+                closed[-1] = True
+            elif w not in blocked:
+                path.append(w)
+                closed.append(False)
+                stack.append(iter(G[w]))
+                blocked.add(w)
+                break
+        else:  # no more nbrs
+            stack.pop()
+            v = path.pop()
+            if closed.pop():
+                if closed:
+                    closed[-1] = True
+                unblock_stack = {v}
+                while unblock_stack:
+                    u = unblock_stack.pop()
+                    if u in blocked:
+                        blocked.remove(u)
+                        unblock_stack.update(B[u])
+                        B[u].clear()
+            else:
+                for w in G[v]:
+                    B[w].add(v)
+
+
+def _bounded_cycle_search(G, path, length_bound):
+    """The main loop of the cycle-enumeration algorithm of Gupta and Suzumura.
+
+    Parameters
+    ----------
+    G : NetworkX Graph or DiGraph
+       A graph
+
+    path : list
+       A cycle prefix.  All cycles generated will begin with this prefix.
+
+    length_bound: int
+        A length bound.  All cycles generated will have length at most length_bound.
+
+    Yields
+    ------
+    list of nodes
+       Each cycle is represented by a list of nodes along the cycle.
+
+    References
+    ----------
+    .. [1] Finding All Bounded-Length Simple Cycles in a Directed Graph
+       A. Gupta and T. Suzumura https://arxiv.org/abs/2105.10094
+
+    """
+    G = _NeighborhoodCache(G)
+    lock = {v: 0 for v in path}
+    B = defaultdict(set)
+    start = path[0]
+    stack = [iter(G[path[-1]])]
+    blen = [length_bound]
+    while stack:
+        nbrs = stack[-1]
+        for w in nbrs:
+            if w == start:
+                yield path[:]
+                blen[-1] = 1
+            elif len(path) < lock.get(w, length_bound):
+                path.append(w)
+                blen.append(length_bound)
+                lock[w] = len(path)
+                stack.append(iter(G[w]))
+                break
+        else:
+            stack.pop()
+            v = path.pop()
+            bl = blen.pop()
+            if blen:
+                blen[-1] = min(blen[-1], bl)
+            if bl < length_bound:
+                relax_stack = [(bl, v)]
+                while relax_stack:
+                    bl, u = relax_stack.pop()
+                    if lock.get(u, length_bound) < length_bound - bl + 1:
+                        lock[u] = length_bound - bl + 1
+                        relax_stack.extend((bl + 1, w) for w in B[u].difference(path))
+            else:
+                for w in G[v]:
+                    B[w].add(v)
+
+
+@nx._dispatchable
+def chordless_cycles(G, length_bound=None):
+    """Find simple chordless cycles of a graph.
+
+    A `simple cycle` is a closed path where no node appears twice.  In a simple
+    cycle, a `chord` is an additional edge between two nodes in the cycle.  A
+    `chordless cycle` is a simple cycle without chords.  Said differently, a
+    chordless cycle is a cycle C in a graph G where the number of edges in the
+    induced graph G[C] is equal to the length of `C`.
+
+    Note that some care must be taken in the case that G is not a simple graph
+    nor a simple digraph.  Some authors limit the definition of chordless cycles
+    to have a prescribed minimum length; we do not.
+
+        1. We interpret self-loops to be chordless cycles, except in multigraphs
+           with multiple loops in parallel.  Likewise, in a chordless cycle of
+           length greater than 1, there can be no nodes with self-loops.
+
+        2. We interpret directed two-cycles to be chordless cycles, except in
+           multi-digraphs when any edge in a two-cycle has a parallel copy.
+
+        3. We interpret parallel pairs of undirected edges as two-cycles, except
+           when a third (or more) parallel edge exists between the two nodes.
+
+        4. Generalizing the above, edges with parallel clones may not occur in
+           chordless cycles.
+
+    In a directed graph, two chordless cycles are distinct if they are not
+    cyclic permutations of each other.  In an undirected graph, two chordless
+    cycles are distinct if they are not cyclic permutations of each other nor of
+    the other's reversal.
+
+    Optionally, the cycles are bounded in length.
+
+    We use an algorithm strongly inspired by that of Dias et al [1]_.  It has
+    been modified in the following ways:
+
+        1. Recursion is avoided, per Python's limitations.
+
+        2. The labeling function is not necessary, because the starting paths
+           are chosen (and deleted from the host graph) to prevent multiple
+           occurrences of the same path.
+
+        3. The search is optionally bounded at a specified length.
+
+        4. Support for directed graphs is provided by extending cycles along
+           forward edges, and blocking nodes along forward and reverse edges.
+
+        5. Support for multigraphs is provided by omitting digons from the set
+           of forward edges.
+
+    Parameters
+    ----------
+    G : NetworkX DiGraph
+       A directed graph
+
+    length_bound : int or None, optional (default=None)
+       If length_bound is an int, generate all simple cycles of G with length at
+       most length_bound.  Otherwise, generate all simple cycles of G.
+
+    Yields
+    ------
+    list of nodes
+       Each cycle is represented by a list of nodes along the cycle.
+
+    Examples
+    --------
+    >>> sorted(list(nx.chordless_cycles(nx.complete_graph(4))))
+    [[1, 0, 2], [1, 0, 3], [2, 0, 3], [2, 1, 3]]
+
+    Notes
+    -----
+    When length_bound is None, and the graph is simple, the time complexity is
+    $O((n+e)(c+1))$ for $n$ nodes, $e$ edges and $c$ chordless cycles.
+
+    Raises
+    ------
+    ValueError
+        when length_bound < 0.
+
+    References
+    ----------
+    .. [1] Efficient enumeration of chordless cycles
+       E. Dias and D. Castonguay and H. Longo and W.A.R. Jradi
+       https://arxiv.org/abs/1309.1051
+
+    See Also
+    --------
+    simple_cycles
+    """
+
+    if length_bound is not None:
+        if length_bound == 0:
+            return
+        elif length_bound < 0:
+            raise ValueError("length bound must be non-negative")
+
+    directed = G.is_directed()
+    multigraph = G.is_multigraph()
+
+    if multigraph:
+        yield from ([v] for v, Gv in G.adj.items() if len(Gv.get(v, ())) == 1)
+    else:
+        yield from ([v] for v, Gv in G.adj.items() if v in Gv)
+
+    if length_bound is not None and length_bound == 1:
+        return
+
+    # Nodes with loops cannot belong to longer cycles.  Let's delete them here.
+    # also, we implicitly reduce the multiplicity of edges down to 1 in the case
+    # of multiedges.
+    loops = set(nx.nodes_with_selfloops(G))
+    edges = ((u, v) for u in G if u not in loops for v in G._adj[u] if v not in loops)
+    if directed:
+        F = nx.DiGraph(edges)
+        B = F.to_undirected(as_view=False)
+    else:
+        F = nx.Graph(edges)
+        B = None
+
+    # If we're given a multigraph, we have a few cases to consider with parallel
+    # edges.
+    #
+    # 1. If we have 2 or more edges in parallel between the nodes (u, v), we
+    #    must not construct longer cycles along (u, v).
+    # 2. If G is not directed, then a pair of parallel edges between (u, v) is a
+    #    chordless cycle unless there exists a third (or more) parallel edge.
+    # 3. If G is directed, then parallel edges do not form cycles, but do
+    #    preclude back-edges from forming cycles (handled in the next section),
+    #    Thus, if an edge (u, v) is duplicated and the reverse (v, u) is also
+    #    present, then we remove both from F.
+    #
+    # In directed graphs, we need to consider both directions that edges can
+    # take, so iterate over all edges (u, v) and possibly (v, u).  In undirected
+    # graphs, we need to be a little careful to only consider every edge once,
+    # so we use a "visited" set to emulate node-order comparisons.
+
+    if multigraph:
+        if not directed:
+            B = F.copy()
+            visited = set()
+        for u, Gu in G.adj.items():
+            if u in loops:
+                continue
+            if directed:
+                multiplicity = ((v, len(Guv)) for v, Guv in Gu.items())
+                for v, m in multiplicity:
+                    if m > 1:
+                        F.remove_edges_from(((u, v), (v, u)))
+            else:
+                multiplicity = ((v, len(Guv)) for v, Guv in Gu.items() if v in visited)
+                for v, m in multiplicity:
+                    if m == 2:
+                        yield [u, v]
+                    if m > 1:
+                        F.remove_edge(u, v)
+                visited.add(u)
+
+    # If we're given a directed graphs, we need to think about digons.  If we
+    # have two edges (u, v) and (v, u), then that's a two-cycle.  If either edge
+    # was duplicated above, then we removed both from F.  So, any digons we find
+    # here are chordless.  After finding digons, we remove their edges from F
+    # to avoid traversing them in the search for chordless cycles.
+    if directed:
+        for u, Fu in F.adj.items():
+            digons = [[u, v] for v in Fu if F.has_edge(v, u)]
+            yield from digons
+            F.remove_edges_from(digons)
+            F.remove_edges_from(e[::-1] for e in digons)
+
+    if length_bound is not None and length_bound == 2:
+        return
+
+    # Now, we prepare to search for cycles.  We have removed all cycles of
+    # lengths 1 and 2, so F is a simple graph or simple digraph.  We repeatedly
+    # separate digraphs into their strongly connected components, and undirected
+    # graphs into their biconnected components.  For each component, we pick a
+    # node v, search for chordless cycles based at each "stem" (u, v, w), and
+    # then remove v from that component before separating the graph again.
+    if directed:
+        separate = nx.strongly_connected_components
+
+        # Directed stems look like (u -> v -> w), so we use the product of
+        # predecessors of v with successors of v.
+        def stems(C, v):
+            for u, w in product(C.pred[v], C.succ[v]):
+                if not G.has_edge(u, w):  # omit stems with acyclic chords
+                    yield [u, v, w], F.has_edge(w, u)
+
+    else:
+        separate = nx.biconnected_components
+
+        # Undirected stems look like (u ~ v ~ w), but we must not also search
+        # (w ~ v ~ u), so we use combinations of v's neighbors of length 2.
+        def stems(C, v):
+            yield from (([u, v, w], F.has_edge(w, u)) for u, w in combinations(C[v], 2))
+
+    components = [c for c in separate(F) if len(c) > 2]
+    while components:
+        c = components.pop()
+        v = next(iter(c))
+        Fc = F.subgraph(c)
+        Fcc = Bcc = None
+        for S, is_triangle in stems(Fc, v):
+            if is_triangle:
+                yield S
+            else:
+                if Fcc is None:
+                    Fcc = _NeighborhoodCache(Fc)
+                    Bcc = Fcc if B is None else _NeighborhoodCache(B.subgraph(c))
+                yield from _chordless_cycle_search(Fcc, Bcc, S, length_bound)
+
+        components.extend(c for c in separate(F.subgraph(c - {v})) if len(c) > 2)
+
+
+def _chordless_cycle_search(F, B, path, length_bound):
+    """The main loop for chordless cycle enumeration.
+
+    This algorithm is strongly inspired by that of Dias et al [1]_.  It has been
+    modified in the following ways:
+
+        1. Recursion is avoided, per Python's limitations
+
+        2. The labeling function is not necessary, because the starting paths
+            are chosen (and deleted from the host graph) to prevent multiple
+            occurrences of the same path
+
+        3. The search is optionally bounded at a specified length
+
+        4. Support for directed graphs is provided by extending cycles along
+            forward edges, and blocking nodes along forward and reverse edges
+
+        5. Support for multigraphs is provided by omitting digons from the set
+            of forward edges
+
+    Parameters
+    ----------
+    F : _NeighborhoodCache
+       A graph of forward edges to follow in constructing cycles
+
+    B : _NeighborhoodCache
+       A graph of blocking edges to prevent the production of chordless cycles
+
+    path : list
+       A cycle prefix.  All cycles generated will begin with this prefix.
+
+    length_bound : int
+       A length bound.  All cycles generated will have length at most length_bound.
+
+
+    Yields
+    ------
+    list of nodes
+       Each cycle is represented by a list of nodes along the cycle.
+
+    References
+    ----------
+    .. [1] Efficient enumeration of chordless cycles
+       E. Dias and D. Castonguay and H. Longo and W.A.R. Jradi
+       https://arxiv.org/abs/1309.1051
+
+    """
+    blocked = defaultdict(int)
+    target = path[0]
+    blocked[path[1]] = 1
+    for w in path[1:]:
+        for v in B[w]:
+            blocked[v] += 1
+
+    stack = [iter(F[path[2]])]
+    while stack:
+        nbrs = stack[-1]
+        for w in nbrs:
+            if blocked[w] == 1 and (length_bound is None or len(path) < length_bound):
+                Fw = F[w]
+                if target in Fw:
+                    yield path + [w]
+                else:
+                    Bw = B[w]
+                    if target in Bw:
+                        continue
+                    for v in Bw:
+                        blocked[v] += 1
+                    path.append(w)
+                    stack.append(iter(Fw))
+                    break
+        else:
+            stack.pop()
+            for v in B[path.pop()]:
+                blocked[v] -= 1
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable(mutates_input=True)
+def recursive_simple_cycles(G):
+    """Find simple cycles (elementary circuits) of a directed graph.
+
+    A `simple cycle`, or `elementary circuit`, is a closed path where
+    no node appears twice. Two elementary circuits are distinct if they
+    are not cyclic permutations of each other.
+
+    This version uses a recursive algorithm to build a list of cycles.
+    You should probably use the iterator version called simple_cycles().
+    Warning: This recursive version uses lots of RAM!
+    It appears in NetworkX for pedagogical value.
+
+    Parameters
+    ----------
+    G : NetworkX DiGraph
+       A directed graph
+
+    Returns
+    -------
+    A list of cycles, where each cycle is represented by a list of nodes
+    along the cycle.
+
+    Example:
+
+    >>> edges = [(0, 0), (0, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2)]
+    >>> G = nx.DiGraph(edges)
+    >>> nx.recursive_simple_cycles(G)
+    [[0], [2], [0, 1, 2], [0, 2], [1, 2]]
+
+    Notes
+    -----
+    The implementation follows pp. 79-80 in [1]_.
+
+    The time complexity is $O((n+e)(c+1))$ for $n$ nodes, $e$ edges and $c$
+    elementary circuits.
+
+    References
+    ----------
+    .. [1] Finding all the elementary circuits of a directed graph.
+       D. B. Johnson, SIAM Journal on Computing 4, no. 1, 77-84, 1975.
+       https://doi.org/10.1137/0204007
+
+    See Also
+    --------
+    simple_cycles, cycle_basis
+    """
+
+    # Jon Olav Vik, 2010-08-09
+    def _unblock(thisnode):
+        """Recursively unblock and remove nodes from B[thisnode]."""
+        if blocked[thisnode]:
+            blocked[thisnode] = False
+            while B[thisnode]:
+                _unblock(B[thisnode].pop())
+
+    def circuit(thisnode, startnode, component):
+        closed = False  # set to True if elementary path is closed
+        path.append(thisnode)
+        blocked[thisnode] = True
+        for nextnode in component[thisnode]:  # direct successors of thisnode
+            if nextnode == startnode:
+                result.append(path[:])
+                closed = True
+            elif not blocked[nextnode]:
+                if circuit(nextnode, startnode, component):
+                    closed = True
+        if closed:
+            _unblock(thisnode)
+        else:
+            for nextnode in component[thisnode]:
+                if thisnode not in B[nextnode]:  # TODO: use set for speedup?
+                    B[nextnode].append(thisnode)
+        path.pop()  # remove thisnode from path
+        return closed
+
+    path = []  # stack of nodes in current path
+    blocked = defaultdict(bool)  # vertex: blocked from search?
+    B = defaultdict(list)  # graph portions that yield no elementary circuit
+    result = []  # list to accumulate the circuits found
+
+    # Johnson's algorithm exclude self cycle edges like (v, v)
+    # To be backward compatible, we record those cycles in advance
+    # and then remove from subG
+    for v in G:
+        if G.has_edge(v, v):
+            result.append([v])
+            G.remove_edge(v, v)
+
+    # Johnson's algorithm requires some ordering of the nodes.
+    # They might not be sortable so we assign an arbitrary ordering.
+    ordering = dict(zip(G, range(len(G))))
+    for s in ordering:
+        # Build the subgraph induced by s and following nodes in the ordering
+        subgraph = G.subgraph(node for node in G if ordering[node] >= ordering[s])
+        # Find the strongly connected component in the subgraph
+        # that contains the least node according to the ordering
+        strongcomp = nx.strongly_connected_components(subgraph)
+        mincomp = min(strongcomp, key=lambda ns: min(ordering[n] for n in ns))
+        component = G.subgraph(mincomp)
+        if len(component) > 1:
+            # smallest node in the component according to the ordering
+            startnode = min(component, key=ordering.__getitem__)
+            for node in component:
+                blocked[node] = False
+                B[node][:] = []
+            dummy = circuit(startnode, startnode, component)
+    return result
+
+
+@nx._dispatchable
+def find_cycle(G, source=None, orientation=None):
+    """Returns a cycle found via depth-first traversal.
+
+    The cycle is a list of edges indicating the cyclic path.
+    Orientation of directed edges is controlled by `orientation`.
+
+    Parameters
+    ----------
+    G : graph
+        A directed/undirected graph/multigraph.
+
+    source : node, list of nodes
+        The node from which the traversal begins. If None, then a source
+        is chosen arbitrarily and repeatedly until all edges from each node in
+        the graph are searched.
+
+    orientation : None | 'original' | 'reverse' | 'ignore' (default: None)
+        For directed graphs and directed multigraphs, edge traversals need not
+        respect the original orientation of the edges.
+        When set to 'reverse' every edge is traversed in the reverse direction.
+        When set to 'ignore', every edge is treated as undirected.
+        When set to 'original', every edge is treated as directed.
+        In all three cases, the yielded edge tuples add a last entry to
+        indicate the direction in which that edge was traversed.
+        If orientation is None, the yielded edge has no direction indicated.
+        The direction is respected, but not reported.
+
+    Returns
+    -------
+    edges : directed edges
+        A list of directed edges indicating the path taken for the loop.
+        If no cycle is found, then an exception is raised.
+        For graphs, an edge is of the form `(u, v)` where `u` and `v`
+        are the tail and head of the edge as determined by the traversal.
+        For multigraphs, an edge is of the form `(u, v, key)`, where `key` is
+        the key of the edge. When the graph is directed, then `u` and `v`
+        are always in the order of the actual directed edge.
+        If orientation is not None then the edge tuple is extended to include
+        the direction of traversal ('forward' or 'reverse') on that edge.
+
+    Raises
+    ------
+    NetworkXNoCycle
+        If no cycle was found.
+
+    Examples
+    --------
+    In this example, we construct a DAG and find, in the first call, that there
+    are no directed cycles, and so an exception is raised. In the second call,
+    we ignore edge orientations and find that there is an undirected cycle.
+    Note that the second call finds a directed cycle while effectively
+    traversing an undirected graph, and so, we found an "undirected cycle".
+    This means that this DAG structure does not form a directed tree (which
+    is also known as a polytree).
+
+    >>> G = nx.DiGraph([(0, 1), (0, 2), (1, 2)])
+    >>> nx.find_cycle(G, orientation="original")
+    Traceback (most recent call last):
+        ...
+    networkx.exception.NetworkXNoCycle: No cycle found.
+    >>> list(nx.find_cycle(G, orientation="ignore"))
+    [(0, 1, 'forward'), (1, 2, 'forward'), (0, 2, 'reverse')]
+
+    See Also
+    --------
+    simple_cycles
+    """
+    if not G.is_directed() or orientation in (None, "original"):
+
+        def tailhead(edge):
+            return edge[:2]
+
+    elif orientation == "reverse":
+
+        def tailhead(edge):
+            return edge[1], edge[0]
+
+    elif orientation == "ignore":
+
+        def tailhead(edge):
+            if edge[-1] == "reverse":
+                return edge[1], edge[0]
+            return edge[:2]
+
+    explored = set()
+    cycle = []
+    final_node = None
+    for start_node in G.nbunch_iter(source):
+        if start_node in explored:
+            # No loop is possible.
+            continue
+
+        edges = []
+        # All nodes seen in this iteration of edge_dfs
+        seen = {start_node}
+        # Nodes in active path.
+        active_nodes = {start_node}
+        previous_head = None
+
+        for edge in nx.edge_dfs(G, start_node, orientation):
+            # Determine if this edge is a continuation of the active path.
+            tail, head = tailhead(edge)
+            if head in explored:
+                # Then we've already explored it. No loop is possible.
+                continue
+            if previous_head is not None and tail != previous_head:
+                # This edge results from backtracking.
+                # Pop until we get a node whose head equals the current tail.
+                # So for example, we might have:
+                #  (0, 1), (1, 2), (2, 3), (1, 4)
+                # which must become:
+                #  (0, 1), (1, 4)
+                while True:
+                    try:
+                        popped_edge = edges.pop()
+                    except IndexError:
+                        edges = []
+                        active_nodes = {tail}
+                        break
+                    else:
+                        popped_head = tailhead(popped_edge)[1]
+                        active_nodes.remove(popped_head)
+
+                    if edges:
+                        last_head = tailhead(edges[-1])[1]
+                        if tail == last_head:
+                            break
+            edges.append(edge)
+
+            if head in active_nodes:
+                # We have a loop!
+                cycle.extend(edges)
+                final_node = head
+                break
+            else:
+                seen.add(head)
+                active_nodes.add(head)
+                previous_head = head
+
+        if cycle:
+            break
+        else:
+            explored.update(seen)
+
+    else:
+        assert len(cycle) == 0
+        raise nx.exception.NetworkXNoCycle("No cycle found.")
+
+    # We now have a list of edges which ends on a cycle.
+    # So we need to remove from the beginning edges that are not relevant.
+
+    for i, edge in enumerate(cycle):
+        tail, head = tailhead(edge)
+        if tail == final_node:
+            break
+
+    return cycle[i:]
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable(edge_attrs="weight")
+def minimum_cycle_basis(G, weight=None):
+    """Returns a minimum weight cycle basis for G
+
+    Minimum weight means a cycle basis for which the total weight
+    (length for unweighted graphs) of all the cycles is minimum.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+    weight: string
+        name of the edge attribute to use for edge weights
+
+    Returns
+    -------
+    A list of cycle lists.  Each cycle list is a list of nodes
+    which forms a cycle (loop) in G. Note that the nodes are not
+    necessarily returned in a order by which they appear in the cycle
+
+    Examples
+    --------
+    >>> G = nx.Graph()
+    >>> nx.add_cycle(G, [0, 1, 2, 3])
+    >>> nx.add_cycle(G, [0, 3, 4, 5])
+    >>> nx.minimum_cycle_basis(G)
+    [[5, 4, 3, 0], [3, 2, 1, 0]]
+
+    References:
+        [1] Kavitha, Telikepalli, et al. "An O(m^2n) Algorithm for
+        Minimum Cycle Basis of Graphs."
+        http://link.springer.com/article/10.1007/s00453-007-9064-z
+        [2] de Pina, J. 1995. Applications of shortest path methods.
+        Ph.D. thesis, University of Amsterdam, Netherlands
+
+    See Also
+    --------
+    simple_cycles, cycle_basis
+    """
+    # We first split the graph in connected subgraphs
+    return sum(
+        (_min_cycle_basis(G.subgraph(c), weight) for c in nx.connected_components(G)),
+        [],
+    )
+
+
+def _min_cycle_basis(G, weight):
+    cb = []
+    # We  extract the edges not in a spanning tree. We do not really need a
+    # *minimum* spanning tree. That is why we call the next function with
+    # weight=None. Depending on implementation, it may be faster as well
+    tree_edges = list(nx.minimum_spanning_edges(G, weight=None, data=False))
+    chords = G.edges - tree_edges - {(v, u) for u, v in tree_edges}
+
+    # We maintain a set of vectors orthogonal to sofar found cycles
+    set_orth = [{edge} for edge in chords]
+    while set_orth:
+        base = set_orth.pop()
+        # kth cycle is "parallel" to kth vector in set_orth
+        cycle_edges = _min_cycle(G, base, weight)
+        cb.append([v for u, v in cycle_edges])
+
+        # now update set_orth so that k+1,k+2... th elements are
+        # orthogonal to the newly found cycle, as per [p. 336, 1]
+        set_orth = [
+            (
+                {e for e in orth if e not in base if e[::-1] not in base}
+                | {e for e in base if e not in orth if e[::-1] not in orth}
+            )
+            if sum((e in orth or e[::-1] in orth) for e in cycle_edges) % 2
+            else orth
+            for orth in set_orth
+        ]
+    return cb
+
+
+def _min_cycle(G, orth, weight):
+    """
+    Computes the minimum weight cycle in G,
+    orthogonal to the vector orth as per [p. 338, 1]
+    Use (u, 1) to indicate the lifted copy of u (denoted u' in paper).
+    """
+    Gi = nx.Graph()
+
+    # Add 2 copies of each edge in G to Gi.
+    # If edge is in orth, add cross edge; otherwise in-plane edge
+    for u, v, wt in G.edges(data=weight, default=1):
+        if (u, v) in orth or (v, u) in orth:
+            Gi.add_edges_from([(u, (v, 1)), ((u, 1), v)], Gi_weight=wt)
+        else:
+            Gi.add_edges_from([(u, v), ((u, 1), (v, 1))], Gi_weight=wt)
+
+    # find the shortest length in Gi between n and (n, 1) for each n
+    # Note: Use "Gi_weight" for name of weight attribute
+    spl = nx.shortest_path_length
+    lift = {n: spl(Gi, source=n, target=(n, 1), weight="Gi_weight") for n in G}
+
+    # Now compute that short path in Gi, which translates to a cycle in G
+    start = min(lift, key=lift.get)
+    end = (start, 1)
+    min_path_i = nx.shortest_path(Gi, source=start, target=end, weight="Gi_weight")
+
+    # Now we obtain the actual path, re-map nodes in Gi to those in G
+    min_path = [n if n in G else n[0] for n in min_path_i]
+
+    # Now remove the edges that occur two times
+    # two passes: flag which edges get kept, then build it
+    edgelist = list(pairwise(min_path))
+    edgeset = set()
+    for e in edgelist:
+        if e in edgeset:
+            edgeset.remove(e)
+        elif e[::-1] in edgeset:
+            edgeset.remove(e[::-1])
+        else:
+            edgeset.add(e)
+
+    min_edgelist = []
+    for e in edgelist:
+        if e in edgeset:
+            min_edgelist.append(e)
+            edgeset.remove(e)
+        elif e[::-1] in edgeset:
+            min_edgelist.append(e[::-1])
+            edgeset.remove(e[::-1])
+
+    return min_edgelist
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable
+def girth(G):
+    """Returns the girth of the graph.
+
+    The girth of a graph is the length of its shortest cycle, or infinity if
+    the graph is acyclic. The algorithm follows the description given on the
+    Wikipedia page [1]_, and runs in time O(mn) on a graph with m edges and n
+    nodes.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+
+    Returns
+    -------
+    int or math.inf
+
+    Examples
+    --------
+    All examples below (except P_5) can easily be checked using Wikipedia,
+    which has a page for each of these famous graphs.
+
+    >>> nx.girth(nx.chvatal_graph())
+    4
+    >>> nx.girth(nx.tutte_graph())
+    4
+    >>> nx.girth(nx.petersen_graph())
+    5
+    >>> nx.girth(nx.heawood_graph())
+    6
+    >>> nx.girth(nx.pappus_graph())
+    6
+    >>> nx.girth(nx.path_graph(5))
+    inf
+
+    References
+    ----------
+    .. [1] `Wikipedia: Girth `_
+
+    """
+    girth = depth_limit = inf
+    tree_edge = nx.algorithms.traversal.breadth_first_search.TREE_EDGE
+    level_edge = nx.algorithms.traversal.breadth_first_search.LEVEL_EDGE
+    for n in G:
+        # run a BFS from source n, keeping track of distances; since we want
+        # the shortest cycle, no need to explore beyond the current minimum length
+        depth = {n: 0}
+        for u, v, label in nx.bfs_labeled_edges(G, n):
+            du = depth[u]
+            if du > depth_limit:
+                break
+            if label is tree_edge:
+                depth[v] = du + 1
+            else:
+                # if (u, v) is a level edge, the length is du + du + 1 (odd)
+                # otherwise, it's a forward edge; length is du + (du + 1) + 1 (even)
+                delta = label is level_edge
+                length = du + du + 2 - delta
+                if length < girth:
+                    girth = length
+                    depth_limit = du - delta
+
+    return girth
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/d_separation.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/d_separation.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d85a2c724fa0a1e14ab99db2be7a3c46b404b4a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/d_separation.py
@@ -0,0 +1,677 @@
+"""
+Algorithm for testing d-separation in DAGs.
+
+*d-separation* is a test for conditional independence in probability
+distributions that can be factorized using DAGs.  It is a purely
+graphical test that uses the underlying graph and makes no reference
+to the actual distribution parameters.  See [1]_ for a formal
+definition.
+
+The implementation is based on the conceptually simple linear time
+algorithm presented in [2]_.  Refer to [3]_, [4]_ for a couple of
+alternative algorithms.
+
+The functional interface in NetworkX consists of three functions:
+
+- `find_minimal_d_separator` returns a minimal d-separator set ``z``.
+  That is, removing any node or nodes from it makes it no longer a d-separator.
+- `is_d_separator` checks if a given set is a d-separator.
+- `is_minimal_d_separator` checks if a given set is a minimal d-separator.
+
+D-separators
+------------
+
+Here, we provide a brief overview of d-separation and related concepts that
+are relevant for understanding it:
+
+The ideas of d-separation and d-connection relate to paths being open or blocked.
+
+- A "path" is a sequence of nodes connected in order by edges. Unlike for most
+  graph theory analysis, the direction of the edges is ignored. Thus the path
+  can be thought of as a traditional path on the undirected version of the graph.
+- A "candidate d-separator" ``z`` is a set of nodes being considered as
+  possibly blocking all paths between two prescribed sets ``x`` and ``y`` of nodes.
+  We refer to each node in the candidate d-separator as "known".
+- A "collider" node on a path is a node that is a successor of its two neighbor
+  nodes on the path. That is, ``c`` is a collider if the edge directions
+  along the path look like ``... u -> c <- v ...``.
+- If a collider node or any of its descendants are "known", the collider
+  is called an "open collider". Otherwise it is a "blocking collider".
+- Any path can be "blocked" in two ways. If the path contains a "known" node
+  that is not a collider, the path is blocked. Also, if the path contains a
+  collider that is not a "known" node, the path is blocked.
+- A path is "open" if it is not blocked. That is, it is open if every node is
+  either an open collider or not a "known". Said another way, every
+  "known" in the path is a collider and every collider is open (has a
+  "known" as a inclusive descendant). The concept of "open path" is meant to
+  demonstrate a probabilistic conditional dependence between two nodes given
+  prescribed knowledge ("known" nodes).
+- Two sets ``x`` and ``y`` of nodes are "d-separated" by a set of nodes ``z``
+  if all paths between nodes in ``x`` and nodes in ``y`` are blocked. That is,
+  if there are no open paths from any node in ``x`` to any node in ``y``.
+  Such a set ``z`` is a "d-separator" of ``x`` and ``y``.
+- A "minimal d-separator" is a d-separator ``z`` for which no node or subset
+  of nodes can be removed with it still being a d-separator.
+
+The d-separator blocks some paths between ``x`` and ``y`` but opens others.
+Nodes in the d-separator block paths if the nodes are not colliders.
+But if a collider or its descendant nodes are in the d-separation set, the
+colliders are open, allowing a path through that collider.
+
+Illustration of D-separation with examples
+------------------------------------------
+
+A pair of two nodes, ``u`` and ``v``, are d-connected if there is a path
+from ``u`` to ``v`` that is not blocked. That means, there is an open
+path from ``u`` to ``v``.
+
+For example, if the d-separating set is the empty set, then the following paths are
+open between ``u`` and ``v``:
+
+- u <- n -> v
+- u -> w -> ... -> n -> v
+
+If  on the other hand, ``n`` is in the d-separating set, then ``n`` blocks
+those paths between ``u`` and ``v``.
+
+Colliders block a path if they and their descendants are not included
+in the d-separating set. An example of a path that is blocked when the
+d-separating set is empty is:
+
+- u -> w -> ... -> n <- v
+
+The node ``n`` is a collider in this path and is not in the d-separating set.
+So ``n`` blocks this path. However, if ``n`` or a descendant of ``n`` is
+included in the d-separating set, then the path through the collider
+at ``n`` (... -> n <- ...) is "open".
+
+D-separation is concerned with blocking all paths between nodes from ``x`` to ``y``.
+A d-separating set between ``x`` and ``y`` is one where all paths are blocked.
+
+D-separation and its applications in probability
+------------------------------------------------
+
+D-separation is commonly used in probabilistic causal-graph models. D-separation
+connects the idea of probabilistic "dependence" with separation in a graph. If
+one assumes the causal Markov condition [5]_, (every node is conditionally
+independent of its non-descendants, given its parents) then d-separation implies
+conditional independence in probability distributions.
+Symmetrically, d-connection implies dependence.
+
+The intuition is as follows. The edges on a causal graph indicate which nodes
+influence the outcome of other nodes directly. An edge from u to v
+implies that the outcome of event ``u`` influences the probabilities for
+the outcome of event ``v``. Certainly knowing ``u`` changes predictions for ``v``.
+But also knowing ``v`` changes predictions for ``u``. The outcomes are dependent.
+Furthermore, an edge from ``v`` to ``w`` would mean that ``w`` and ``v`` are dependent
+and thus that ``u`` could indirectly influence ``w``.
+
+Without any knowledge about the system (candidate d-separating set is empty)
+a causal graph ``u -> v -> w`` allows all three nodes to be dependent. But
+if we know the outcome of ``v``, the conditional probabilities of outcomes for
+``u`` and ``w`` are independent of each other. That is, once we know the outcome
+for ``v``, the probabilities for ``w`` do not depend on the outcome for ``u``.
+This is the idea behind ``v`` blocking the path if it is "known" (in the candidate
+d-separating set).
+
+The same argument works whether the direction of the edges are both
+left-going and when both arrows head out from the middle. Having a "known"
+node on a path blocks the collider-free path because those relationships
+make the conditional probabilities independent.
+
+The direction of the causal edges does impact dependence precisely in the
+case of a collider e.g. ``u -> v <- w``. In that situation, both ``u`` and ``w``
+influence ``v``. But they do not directly influence each other. So without any
+knowledge of any outcomes, ``u`` and ``w`` are independent. That is the idea behind
+colliders blocking the path. But, if ``v`` is known, the conditional probabilities
+of ``u`` and ``w`` can be dependent. This is the heart of Berkson's Paradox [6]_.
+For example, suppose ``u`` and ``w`` are boolean events (they either happen or do not)
+and ``v`` represents the outcome "at least one of ``u`` and ``w`` occur". Then knowing
+``v`` is true makes the conditional probabilities of ``u`` and ``w`` dependent.
+Essentially, knowing that at least one of them is true raises the probability of
+each. But further knowledge that ``w`` is true (or false) change the conditional
+probability of ``u`` to either the original value or 1. So the conditional
+probability of ``u`` depends on the outcome of ``w`` even though there is no
+causal relationship between them. When a collider is known, dependence can
+occur across paths through that collider. This is the reason open colliders
+do not block paths.
+
+Furthermore, even if ``v`` is not "known", if one of its descendants is "known"
+we can use that information to know more about ``v`` which again makes
+``u`` and ``w`` potentially dependent. Suppose the chance of ``n`` occurring
+is much higher when ``v`` occurs ("at least one of ``u`` and ``w`` occur").
+Then if we know ``n`` occurred, it is more likely that ``v`` occurred and that
+makes the chance of ``u`` and ``w`` dependent. This is the idea behind why
+a collider does no block a path if any descendant of the collider is "known".
+
+When two sets of nodes ``x`` and ``y`` are d-separated by a set ``z``,
+it means that given the outcomes of the nodes in ``z``, the probabilities
+of outcomes of the nodes in ``x`` are independent of the outcomes of the
+nodes in ``y`` and vice versa.
+
+Examples
+--------
+A Hidden Markov Model with 5 observed states and 5 hidden states
+where the hidden states have causal relationships resulting in
+a path results in the following causal network. We check that
+early states along the path are separated from late state in
+the path by the d-separator of the middle hidden state.
+Thus if we condition on the middle hidden state, the early
+state probabilities are independent of the late state outcomes.
+
+>>> G = nx.DiGraph()
+>>> G.add_edges_from(
+...     [
+...         ("H1", "H2"),
+...         ("H2", "H3"),
+...         ("H3", "H4"),
+...         ("H4", "H5"),
+...         ("H1", "O1"),
+...         ("H2", "O2"),
+...         ("H3", "O3"),
+...         ("H4", "O4"),
+...         ("H5", "O5"),
+...     ]
+... )
+>>> x, y, z = ({"H1", "O1"}, {"H5", "O5"}, {"H3"})
+>>> nx.is_d_separator(G, x, y, z)
+True
+>>> nx.is_minimal_d_separator(G, x, y, z)
+True
+>>> nx.is_minimal_d_separator(G, x, y, z | {"O3"})
+False
+>>> z = nx.find_minimal_d_separator(G, x | y, {"O2", "O3", "O4"})
+>>> z == {"H2", "H4"}
+True
+
+If no minimal_d_separator exists, `None` is returned
+
+>>> other_z = nx.find_minimal_d_separator(G, x | y, {"H2", "H3"})
+>>> other_z is None
+True
+
+
+References
+----------
+
+.. [1] Pearl, J.  (2009).  Causality.  Cambridge: Cambridge University Press.
+
+.. [2] Darwiche, A.  (2009).  Modeling and reasoning with Bayesian networks.
+   Cambridge: Cambridge University Press.
+
+.. [3] Shachter, Ross D. "Bayes-ball: The rational pastime (for
+   determining irrelevance and requisite information in belief networks
+   and influence diagrams)." In Proceedings of the Fourteenth Conference
+   on Uncertainty in Artificial Intelligence (UAI), (pp. 480–487). 1998.
+
+.. [4] Koller, D., & Friedman, N. (2009).
+   Probabilistic graphical models: principles and techniques. The MIT Press.
+
+.. [5] https://en.wikipedia.org/wiki/Causal_Markov_condition
+
+.. [6] https://en.wikipedia.org/wiki/Berkson%27s_paradox
+
+"""
+
+from collections import deque
+from itertools import chain
+
+import networkx as nx
+from networkx.utils import UnionFind, not_implemented_for
+
+__all__ = [
+    "is_d_separator",
+    "is_minimal_d_separator",
+    "find_minimal_d_separator",
+]
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable
+def is_d_separator(G, x, y, z):
+    """Return whether node sets `x` and `y` are d-separated by `z`.
+
+    Parameters
+    ----------
+    G : nx.DiGraph
+        A NetworkX DAG.
+
+    x : node or set of nodes
+        First node or set of nodes in `G`.
+
+    y : node or set of nodes
+        Second node or set of nodes in `G`.
+
+    z : node or set of nodes
+        Potential separator (set of conditioning nodes in `G`). Can be empty set.
+
+    Returns
+    -------
+    b : bool
+        A boolean that is true if `x` is d-separated from `y` given `z` in `G`.
+
+    Raises
+    ------
+    NetworkXError
+        The *d-separation* test is commonly used on disjoint sets of
+        nodes in acyclic directed graphs.  Accordingly, the algorithm
+        raises a :exc:`NetworkXError` if the node sets are not
+        disjoint or if the input graph is not a DAG.
+
+    NodeNotFound
+        If any of the input nodes are not found in the graph,
+        a :exc:`NodeNotFound` exception is raised
+
+    Notes
+    -----
+    A d-separating set in a DAG is a set of nodes that
+    blocks all paths between the two sets. Nodes in `z`
+    block a path if they are part of the path and are not a collider,
+    or a descendant of a collider. Also colliders that are not in `z`
+    block a path. A collider structure along a path
+    is ``... -> c <- ...`` where ``c`` is the collider node.
+
+    https://en.wikipedia.org/wiki/Bayesian_network#d-separation
+    """
+    try:
+        x = {x} if x in G else x
+        y = {y} if y in G else y
+        z = {z} if z in G else z
+
+        intersection = x & y or x & z or y & z
+        if intersection:
+            raise nx.NetworkXError(
+                f"The sets are not disjoint, with intersection {intersection}"
+            )
+
+        set_v = x | y | z
+        if set_v - G.nodes:
+            raise nx.NodeNotFound(f"The node(s) {set_v - G.nodes} are not found in G")
+    except TypeError:
+        raise nx.NodeNotFound("One of x, y, or z is not a node or a set of nodes in G")
+
+    if not nx.is_directed_acyclic_graph(G):
+        raise nx.NetworkXError("graph should be directed acyclic")
+
+    # contains -> and <-> edges from starting node T
+    forward_deque = deque([])
+    forward_visited = set()
+
+    # contains <- and - edges from starting node T
+    backward_deque = deque(x)
+    backward_visited = set()
+
+    ancestors_or_z = set().union(*[nx.ancestors(G, node) for node in x]) | z | x
+
+    while forward_deque or backward_deque:
+        if backward_deque:
+            node = backward_deque.popleft()
+            backward_visited.add(node)
+            if node in y:
+                return False
+            if node in z:
+                continue
+
+            # add <- edges to backward deque
+            backward_deque.extend(G.pred[node].keys() - backward_visited)
+            # add -> edges to forward deque
+            forward_deque.extend(G.succ[node].keys() - forward_visited)
+
+        if forward_deque:
+            node = forward_deque.popleft()
+            forward_visited.add(node)
+            if node in y:
+                return False
+
+            # Consider if -> node <- is opened due to ancestor of node in z
+            if node in ancestors_or_z:
+                # add <- edges to backward deque
+                backward_deque.extend(G.pred[node].keys() - backward_visited)
+            if node not in z:
+                # add -> edges to forward deque
+                forward_deque.extend(G.succ[node].keys() - forward_visited)
+
+    return True
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable
+def find_minimal_d_separator(G, x, y, *, included=None, restricted=None):
+    """Returns a minimal d-separating set between `x` and `y` if possible
+
+    A d-separating set in a DAG is a set of nodes that blocks all
+    paths between the two sets of nodes, `x` and `y`. This function
+    constructs a d-separating set that is "minimal", meaning no nodes can
+    be removed without it losing the d-separating property for `x` and `y`.
+    If no d-separating sets exist for `x` and `y`, this returns `None`.
+
+    In a DAG there may be more than one minimal d-separator between two
+    sets of nodes. Minimal d-separators are not always unique. This function
+    returns one minimal d-separator, or `None` if no d-separator exists.
+
+    Uses the algorithm presented in [1]_. The complexity of the algorithm
+    is :math:`O(m)`, where :math:`m` stands for the number of edges in
+    the subgraph of G consisting of only the ancestors of `x` and `y`.
+    For full details, see [1]_.
+
+    Parameters
+    ----------
+    G : graph
+        A networkx DAG.
+    x : set | node
+        A node or set of nodes in the graph.
+    y : set | node
+        A node or set of nodes in the graph.
+    included : set | node | None
+        A node or set of nodes which must be included in the found separating set,
+        default is None, which means the empty set.
+    restricted : set | node | None
+        Restricted node or set of nodes to consider. Only these nodes can be in
+        the found separating set, default is None meaning all nodes in ``G``.
+
+    Returns
+    -------
+    z : set | None
+        The minimal d-separating set, if at least one d-separating set exists,
+        otherwise None.
+
+    Raises
+    ------
+    NetworkXError
+        Raises a :exc:`NetworkXError` if the input graph is not a DAG
+        or if node sets `x`, `y`, and `included` are not disjoint.
+
+    NodeNotFound
+        If any of the input nodes are not found in the graph,
+        a :exc:`NodeNotFound` exception is raised.
+
+    References
+    ----------
+    .. [1] van der Zander, Benito, and Maciej Liśkiewicz. "Finding
+        minimal d-separators in linear time and applications." In
+        Uncertainty in Artificial Intelligence, pp. 637-647. PMLR, 2020.
+    """
+    if not nx.is_directed_acyclic_graph(G):
+        raise nx.NetworkXError("graph should be directed acyclic")
+
+    try:
+        x = {x} if x in G else x
+        y = {y} if y in G else y
+
+        if included is None:
+            included = set()
+        elif included in G:
+            included = {included}
+
+        if restricted is None:
+            restricted = set(G)
+        elif restricted in G:
+            restricted = {restricted}
+
+        set_y = x | y | included | restricted
+        if set_y - G.nodes:
+            raise nx.NodeNotFound(f"The node(s) {set_y - G.nodes} are not found in G")
+    except TypeError:
+        raise nx.NodeNotFound(
+            "One of x, y, included or restricted is not a node or set of nodes in G"
+        )
+
+    if not included <= restricted:
+        raise nx.NetworkXError(
+            f"Included nodes {included} must be in restricted nodes {restricted}"
+        )
+
+    intersection = x & y or x & included or y & included
+    if intersection:
+        raise nx.NetworkXError(
+            f"The sets x, y, included are not disjoint. Overlap: {intersection}"
+        )
+
+    nodeset = x | y | included
+    ancestors_x_y_included = nodeset.union(*[nx.ancestors(G, node) for node in nodeset])
+
+    z_init = restricted & (ancestors_x_y_included - (x | y))
+
+    x_closure = _reachable(G, x, ancestors_x_y_included, z_init)
+    if x_closure & y:
+        return None
+
+    z_updated = z_init & (x_closure | included)
+    y_closure = _reachable(G, y, ancestors_x_y_included, z_updated)
+    return z_updated & (y_closure | included)
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable
+def is_minimal_d_separator(G, x, y, z, *, included=None, restricted=None):
+    """Determine if `z` is a minimal d-separator for `x` and `y`.
+
+    A d-separator, `z`, in a DAG is a set of nodes that blocks
+    all paths from nodes in set `x` to nodes in set `y`.
+    A minimal d-separator is a d-separator `z` such that removing
+    any subset of nodes makes it no longer a d-separator.
+
+    Note: This function checks whether `z` is a d-separator AND is
+    minimal. One can use the function `is_d_separator` to only check if
+    `z` is a d-separator. See examples below.
+
+    Parameters
+    ----------
+    G : nx.DiGraph
+        A NetworkX DAG.
+    x : node | set
+        A node or set of nodes in the graph.
+    y : node | set
+        A node or set of nodes in the graph.
+    z : node | set
+        The node or set of nodes to check if it is a minimal d-separating set.
+        The function :func:`is_d_separator` is called inside this function
+        to verify that `z` is in fact a d-separator.
+    included : set | node | None
+        A node or set of nodes which must be included in the found separating set,
+        default is ``None``, which means the empty set.
+    restricted : set | node | None
+        Restricted node or set of nodes to consider. Only these nodes can be in
+        the found separating set, default is ``None`` meaning all nodes in ``G``.
+
+    Returns
+    -------
+    bool
+        Whether or not the set `z` is a minimal d-separator subject to
+        `restricted` nodes and `included` node constraints.
+
+    Examples
+    --------
+    >>> G = nx.path_graph([0, 1, 2, 3], create_using=nx.DiGraph)
+    >>> G.add_node(4)
+    >>> nx.is_minimal_d_separator(G, 0, 2, {1})
+    True
+    >>> # since {1} is the minimal d-separator, {1, 3, 4} is not minimal
+    >>> nx.is_minimal_d_separator(G, 0, 2, {1, 3, 4})
+    False
+    >>> # alternatively, if we only want to check that {1, 3, 4} is a d-separator
+    >>> nx.is_d_separator(G, 0, 2, {1, 3, 4})
+    True
+
+    Raises
+    ------
+    NetworkXError
+        Raises a :exc:`NetworkXError` if the input graph is not a DAG.
+
+    NodeNotFound
+        If any of the input nodes are not found in the graph,
+        a :exc:`NodeNotFound` exception is raised.
+
+    References
+    ----------
+    .. [1] van der Zander, Benito, and Maciej Liśkiewicz. "Finding
+        minimal d-separators in linear time and applications." In
+        Uncertainty in Artificial Intelligence, pp. 637-647. PMLR, 2020.
+
+    Notes
+    -----
+    This function works on verifying that a set is minimal and
+    d-separating between two nodes. Uses criterion (a), (b), (c) on
+    page 4 of [1]_. a) closure(`x`) and `y` are disjoint. b) `z` contains
+    all nodes from `included` and is contained in the `restricted`
+    nodes and in the union of ancestors of `x`, `y`, and `included`.
+    c) the nodes in `z` not in `included` are contained in both
+    closure(x) and closure(y). The closure of a set is the set of nodes
+    connected to the set by a directed path in G.
+
+    The complexity is :math:`O(m)`, where :math:`m` stands for the
+    number of edges in the subgraph of G consisting of only the
+    ancestors of `x` and `y`.
+
+    For full details, see [1]_.
+    """
+    if not nx.is_directed_acyclic_graph(G):
+        raise nx.NetworkXError("graph should be directed acyclic")
+
+    try:
+        x = {x} if x in G else x
+        y = {y} if y in G else y
+        z = {z} if z in G else z
+
+        if included is None:
+            included = set()
+        elif included in G:
+            included = {included}
+
+        if restricted is None:
+            restricted = set(G)
+        elif restricted in G:
+            restricted = {restricted}
+
+        set_y = x | y | included | restricted
+        if set_y - G.nodes:
+            raise nx.NodeNotFound(f"The node(s) {set_y - G.nodes} are not found in G")
+    except TypeError:
+        raise nx.NodeNotFound(
+            "One of x, y, z, included or restricted is not a node or set of nodes in G"
+        )
+
+    if not included <= z:
+        raise nx.NetworkXError(
+            f"Included nodes {included} must be in proposed separating set z {x}"
+        )
+    if not z <= restricted:
+        raise nx.NetworkXError(
+            f"Separating set {z} must be contained in restricted set {restricted}"
+        )
+
+    intersection = x.intersection(y) or x.intersection(z) or y.intersection(z)
+    if intersection:
+        raise nx.NetworkXError(
+            f"The sets are not disjoint, with intersection {intersection}"
+        )
+
+    nodeset = x | y | included
+    ancestors_x_y_included = nodeset.union(*[nx.ancestors(G, n) for n in nodeset])
+
+    # criterion (a) -- check that z is actually a separator
+    x_closure = _reachable(G, x, ancestors_x_y_included, z)
+    if x_closure & y:
+        return False
+
+    # criterion (b) -- basic constraint; included and restricted already checked above
+    if not (z <= ancestors_x_y_included):
+        return False
+
+    # criterion (c) -- check that z is minimal
+    y_closure = _reachable(G, y, ancestors_x_y_included, z)
+    if not ((z - included) <= (x_closure & y_closure)):
+        return False
+    return True
+
+
+@not_implemented_for("undirected")
+def _reachable(G, x, a, z):
+    """Modified Bayes-Ball algorithm for finding d-connected nodes.
+
+    Find all nodes in `a` that are d-connected to those in `x` by
+    those in `z`. This is an implementation of the function
+    `REACHABLE` in [1]_ (which is itself a modification of the
+    Bayes-Ball algorithm [2]_) when restricted to DAGs.
+
+    Parameters
+    ----------
+    G : nx.DiGraph
+        A NetworkX DAG.
+    x : node | set
+        A node in the DAG, or a set of nodes.
+    a : node | set
+        A (set of) node(s) in the DAG containing the ancestors of `x`.
+    z : node | set
+        The node or set of nodes conditioned on when checking d-connectedness.
+
+    Returns
+    -------
+    w : set
+        The closure of `x` in `a` with respect to d-connectedness
+        given `z`.
+
+    References
+    ----------
+    .. [1] van der Zander, Benito, and Maciej Liśkiewicz. "Finding
+        minimal d-separators in linear time and applications." In
+        Uncertainty in Artificial Intelligence, pp. 637-647. PMLR, 2020.
+
+    .. [2] Shachter, Ross D. "Bayes-ball: The rational pastime
+       (for determining irrelevance and requisite information in
+       belief networks and influence diagrams)." In Proceedings of the
+       Fourteenth Conference on Uncertainty in Artificial Intelligence
+       (UAI), (pp. 480–487). 1998.
+    """
+
+    def _pass(e, v, f, n):
+        """Whether a ball entering node `v` along edge `e` passes to `n` along `f`.
+
+        Boolean function defined on page 6 of [1]_.
+
+        Parameters
+        ----------
+        e : bool
+            Directed edge by which the ball got to node `v`; `True` iff directed into `v`.
+        v : node
+            Node where the ball is.
+        f : bool
+            Directed edge connecting nodes `v` and `n`; `True` iff directed `n`.
+        n : node
+            Checking whether the ball passes to this node.
+
+        Returns
+        -------
+        b : bool
+            Whether the ball passes or not.
+
+        References
+        ----------
+        .. [1] van der Zander, Benito, and Maciej Liśkiewicz. "Finding
+           minimal d-separators in linear time and applications." In
+           Uncertainty in Artificial Intelligence, pp. 637-647. PMLR, 2020.
+        """
+        is_element_of_A = n in a
+        # almost_definite_status = True  # always true for DAGs; not so for RCGs
+        collider_if_in_Z = v not in z or (e and not f)
+        return is_element_of_A and collider_if_in_Z  # and almost_definite_status
+
+    queue = deque([])
+    for node in x:
+        if bool(G.pred[node]):
+            queue.append((True, node))
+        if bool(G.succ[node]):
+            queue.append((False, node))
+    processed = queue.copy()
+
+    while any(queue):
+        e, v = queue.popleft()
+        preds = ((False, n) for n in G.pred[v])
+        succs = ((True, n) for n in G.succ[v])
+        f_n_pairs = chain(preds, succs)
+        for f, n in f_n_pairs:
+            if (f, n) not in processed and _pass(e, v, f, n):
+                queue.append((f, n))
+                processed.append((f, n))
+
+    return {w for (_, w) in processed}
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/dag.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/dag.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7f07eca4f16c05391df34f0637132aae5da2866
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/dag.py
@@ -0,0 +1,1392 @@
+"""Algorithms for directed acyclic graphs (DAGs).
+
+Note that most of these functions are only guaranteed to work for DAGs.
+In general, these functions do not check for acyclic-ness, so it is up
+to the user to check for that.
+"""
+
+import heapq
+from collections import deque
+from functools import partial
+from itertools import chain, combinations, product, starmap
+from math import gcd
+
+import networkx as nx
+from networkx.utils import arbitrary_element, not_implemented_for, pairwise
+
+__all__ = [
+    "descendants",
+    "ancestors",
+    "topological_sort",
+    "lexicographical_topological_sort",
+    "all_topological_sorts",
+    "topological_generations",
+    "is_directed_acyclic_graph",
+    "is_aperiodic",
+    "transitive_closure",
+    "transitive_closure_dag",
+    "transitive_reduction",
+    "antichains",
+    "dag_longest_path",
+    "dag_longest_path_length",
+    "dag_to_branching",
+]
+
+chaini = chain.from_iterable
+
+
+@nx._dispatchable
+def descendants(G, source):
+    """Returns all nodes reachable from `source` in `G`.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+    source : node in `G`
+
+    Returns
+    -------
+    set()
+        The descendants of `source` in `G`
+
+    Raises
+    ------
+    NetworkXError
+        If node `source` is not in `G`.
+
+    Examples
+    --------
+    >>> DG = nx.path_graph(5, create_using=nx.DiGraph)
+    >>> sorted(nx.descendants(DG, 2))
+    [3, 4]
+
+    The `source` node is not a descendant of itself, but can be included manually:
+
+    >>> sorted(nx.descendants(DG, 2) | {2})
+    [2, 3, 4]
+
+    See also
+    --------
+    ancestors
+    """
+    return {child for parent, child in nx.bfs_edges(G, source)}
+
+
+@nx._dispatchable
+def ancestors(G, source):
+    """Returns all nodes having a path to `source` in `G`.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+    source : node in `G`
+
+    Returns
+    -------
+    set()
+        The ancestors of `source` in `G`
+
+    Raises
+    ------
+    NetworkXError
+        If node `source` is not in `G`.
+
+    Examples
+    --------
+    >>> DG = nx.path_graph(5, create_using=nx.DiGraph)
+    >>> sorted(nx.ancestors(DG, 2))
+    [0, 1]
+
+    The `source` node is not an ancestor of itself, but can be included manually:
+
+    >>> sorted(nx.ancestors(DG, 2) | {2})
+    [0, 1, 2]
+
+    See also
+    --------
+    descendants
+    """
+    return {child for parent, child in nx.bfs_edges(G, source, reverse=True)}
+
+
+@nx._dispatchable
+def has_cycle(G):
+    """Decides whether the directed graph has a cycle."""
+    try:
+        # Feed the entire iterator into a zero-length deque.
+        deque(topological_sort(G), maxlen=0)
+    except nx.NetworkXUnfeasible:
+        return True
+    else:
+        return False
+
+
+@nx._dispatchable
+def is_directed_acyclic_graph(G):
+    """Returns True if the graph `G` is a directed acyclic graph (DAG) or
+    False if not.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    Returns
+    -------
+    bool
+        True if `G` is a DAG, False otherwise
+
+    Examples
+    --------
+    Undirected graph::
+
+        >>> G = nx.Graph([(1, 2), (2, 3)])
+        >>> nx.is_directed_acyclic_graph(G)
+        False
+
+    Directed graph with cycle::
+
+        >>> G = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
+        >>> nx.is_directed_acyclic_graph(G)
+        False
+
+    Directed acyclic graph::
+
+        >>> G = nx.DiGraph([(1, 2), (2, 3)])
+        >>> nx.is_directed_acyclic_graph(G)
+        True
+
+    See also
+    --------
+    topological_sort
+    """
+    return G.is_directed() and not has_cycle(G)
+
+
+@nx._dispatchable
+def topological_generations(G):
+    """Stratifies a DAG into generations.
+
+    A topological generation is node collection in which ancestors of a node in each
+    generation are guaranteed to be in a previous generation, and any descendants of
+    a node are guaranteed to be in a following generation. Nodes are guaranteed to
+    be in the earliest possible generation that they can belong to.
+
+    Parameters
+    ----------
+    G : NetworkX digraph
+        A directed acyclic graph (DAG)
+
+    Yields
+    ------
+    sets of nodes
+        Yields sets of nodes representing each generation.
+
+    Raises
+    ------
+    NetworkXError
+        Generations are defined for directed graphs only. If the graph
+        `G` is undirected, a :exc:`NetworkXError` is raised.
+
+    NetworkXUnfeasible
+        If `G` is not a directed acyclic graph (DAG) no topological generations
+        exist and a :exc:`NetworkXUnfeasible` exception is raised.  This can also
+        be raised if `G` is changed while the returned iterator is being processed
+
+    RuntimeError
+        If `G` is changed while the returned iterator is being processed.
+
+    Examples
+    --------
+    >>> DG = nx.DiGraph([(2, 1), (3, 1)])
+    >>> [sorted(generation) for generation in nx.topological_generations(DG)]
+    [[2, 3], [1]]
+
+    Notes
+    -----
+    The generation in which a node resides can also be determined by taking the
+    max-path-distance from the node to the farthest leaf node. That value can
+    be obtained with this function using `enumerate(topological_generations(G))`.
+
+    See also
+    --------
+    topological_sort
+    """
+    if not G.is_directed():
+        raise nx.NetworkXError("Topological sort not defined on undirected graphs.")
+
+    multigraph = G.is_multigraph()
+    indegree_map = {v: d for v, d in G.in_degree() if d > 0}
+    zero_indegree = [v for v, d in G.in_degree() if d == 0]
+
+    while zero_indegree:
+        this_generation = zero_indegree
+        zero_indegree = []
+        for node in this_generation:
+            if node not in G:
+                raise RuntimeError("Graph changed during iteration")
+            for child in G.neighbors(node):
+                try:
+                    indegree_map[child] -= len(G[node][child]) if multigraph else 1
+                except KeyError as err:
+                    raise RuntimeError("Graph changed during iteration") from err
+                if indegree_map[child] == 0:
+                    zero_indegree.append(child)
+                    del indegree_map[child]
+        yield this_generation
+
+    if indegree_map:
+        raise nx.NetworkXUnfeasible(
+            "Graph contains a cycle or graph changed during iteration"
+        )
+
+
+@nx._dispatchable
+def topological_sort(G):
+    """Returns a generator of nodes in topologically sorted order.
+
+    A topological sort is a nonunique permutation of the nodes of a
+    directed graph such that an edge from u to v implies that u
+    appears before v in the topological sort order. This ordering is
+    valid only if the graph has no directed cycles.
+
+    Parameters
+    ----------
+    G : NetworkX digraph
+        A directed acyclic graph (DAG)
+
+    Yields
+    ------
+    nodes
+        Yields the nodes in topological sorted order.
+
+    Raises
+    ------
+    NetworkXError
+        Topological sort is defined for directed graphs only. If the graph `G`
+        is undirected, a :exc:`NetworkXError` is raised.
+
+    NetworkXUnfeasible
+        If `G` is not a directed acyclic graph (DAG) no topological sort exists
+        and a :exc:`NetworkXUnfeasible` exception is raised.  This can also be
+        raised if `G` is changed while the returned iterator is being processed
+
+    RuntimeError
+        If `G` is changed while the returned iterator is being processed.
+
+    Examples
+    --------
+    To get the reverse order of the topological sort:
+
+    >>> DG = nx.DiGraph([(1, 2), (2, 3)])
+    >>> list(reversed(list(nx.topological_sort(DG))))
+    [3, 2, 1]
+
+    If your DiGraph naturally has the edges representing tasks/inputs
+    and nodes representing people/processes that initiate tasks, then
+    topological_sort is not quite what you need. You will have to change
+    the tasks to nodes with dependence reflected by edges. The result is
+    a kind of topological sort of the edges. This can be done
+    with :func:`networkx.line_graph` as follows:
+
+    >>> list(nx.topological_sort(nx.line_graph(DG)))
+    [(1, 2), (2, 3)]
+
+    Notes
+    -----
+    This algorithm is based on a description and proof in
+    "Introduction to Algorithms: A Creative Approach" [1]_ .
+
+    See also
+    --------
+    is_directed_acyclic_graph, lexicographical_topological_sort
+
+    References
+    ----------
+    .. [1] Manber, U. (1989).
+       *Introduction to Algorithms - A Creative Approach.* Addison-Wesley.
+    """
+    for generation in nx.topological_generations(G):
+        yield from generation
+
+
+@nx._dispatchable
+def lexicographical_topological_sort(G, key=None):
+    """Generate the nodes in the unique lexicographical topological sort order.
+
+    Generates a unique ordering of nodes by first sorting topologically (for which there are often
+    multiple valid orderings) and then additionally by sorting lexicographically.
+
+    A topological sort arranges the nodes of a directed graph so that the
+    upstream node of each directed edge precedes the downstream node.
+    It is always possible to find a solution for directed graphs that have no cycles.
+    There may be more than one valid solution.
+
+    Lexicographical sorting is just sorting alphabetically. It is used here to break ties in the
+    topological sort and to determine a single, unique ordering.  This can be useful in comparing
+    sort results.
+
+    The lexicographical order can be customized by providing a function to the `key=` parameter.
+    The definition of the key function is the same as used in python's built-in `sort()`.
+    The function takes a single argument and returns a key to use for sorting purposes.
+
+    Lexicographical sorting can fail if the node names are un-sortable. See the example below.
+    The solution is to provide a function to the `key=` argument that returns sortable keys.
+
+
+    Parameters
+    ----------
+    G : NetworkX digraph
+        A directed acyclic graph (DAG)
+
+    key : function, optional
+        A function of one argument that converts a node name to a comparison key.
+        It defines and resolves ambiguities in the sort order.  Defaults to the identity function.
+
+    Yields
+    ------
+    nodes
+        Yields the nodes of G in lexicographical topological sort order.
+
+    Raises
+    ------
+    NetworkXError
+        Topological sort is defined for directed graphs only. If the graph `G`
+        is undirected, a :exc:`NetworkXError` is raised.
+
+    NetworkXUnfeasible
+        If `G` is not a directed acyclic graph (DAG) no topological sort exists
+        and a :exc:`NetworkXUnfeasible` exception is raised.  This can also be
+        raised if `G` is changed while the returned iterator is being processed
+
+    RuntimeError
+        If `G` is changed while the returned iterator is being processed.
+
+    TypeError
+        Results from un-sortable node names.
+        Consider using `key=` parameter to resolve ambiguities in the sort order.
+
+    Examples
+    --------
+    >>> DG = nx.DiGraph([(2, 1), (2, 5), (1, 3), (1, 4), (5, 4)])
+    >>> list(nx.lexicographical_topological_sort(DG))
+    [2, 1, 3, 5, 4]
+    >>> list(nx.lexicographical_topological_sort(DG, key=lambda x: -x))
+    [2, 5, 1, 4, 3]
+
+    The sort will fail for any graph with integer and string nodes. Comparison of integer to strings
+    is not defined in python.  Is 3 greater or less than 'red'?
+
+    >>> DG = nx.DiGraph([(1, "red"), (3, "red"), (1, "green"), (2, "blue")])
+    >>> list(nx.lexicographical_topological_sort(DG))
+    Traceback (most recent call last):
+    ...
+    TypeError: '<' not supported between instances of 'str' and 'int'
+    ...
+
+    Incomparable nodes can be resolved using a `key` function. This example function
+    allows comparison of integers and strings by returning a tuple where the first
+    element is True for `str`, False otherwise. The second element is the node name.
+    This groups the strings and integers separately so they can be compared only among themselves.
+
+    >>> key = lambda node: (isinstance(node, str), node)
+    >>> list(nx.lexicographical_topological_sort(DG, key=key))
+    [1, 2, 3, 'blue', 'green', 'red']
+
+    Notes
+    -----
+    This algorithm is based on a description and proof in
+    "Introduction to Algorithms: A Creative Approach" [1]_ .
+
+    See also
+    --------
+    topological_sort
+
+    References
+    ----------
+    .. [1] Manber, U. (1989).
+       *Introduction to Algorithms - A Creative Approach.* Addison-Wesley.
+    """
+    if not G.is_directed():
+        msg = "Topological sort not defined on undirected graphs."
+        raise nx.NetworkXError(msg)
+
+    if key is None:
+
+        def key(node):
+            return node
+
+    nodeid_map = {n: i for i, n in enumerate(G)}
+
+    def create_tuple(node):
+        return key(node), nodeid_map[node], node
+
+    indegree_map = {v: d for v, d in G.in_degree() if d > 0}
+    # These nodes have zero indegree and ready to be returned.
+    zero_indegree = [create_tuple(v) for v, d in G.in_degree() if d == 0]
+    heapq.heapify(zero_indegree)
+
+    while zero_indegree:
+        _, _, node = heapq.heappop(zero_indegree)
+
+        if node not in G:
+            raise RuntimeError("Graph changed during iteration")
+        for _, child in G.edges(node):
+            try:
+                indegree_map[child] -= 1
+            except KeyError as err:
+                raise RuntimeError("Graph changed during iteration") from err
+            if indegree_map[child] == 0:
+                try:
+                    heapq.heappush(zero_indegree, create_tuple(child))
+                except TypeError as err:
+                    raise TypeError(
+                        f"{err}\nConsider using `key=` parameter to resolve ambiguities in the sort order."
+                    )
+                del indegree_map[child]
+
+        yield node
+
+    if indegree_map:
+        msg = "Graph contains a cycle or graph changed during iteration"
+        raise nx.NetworkXUnfeasible(msg)
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable
+def all_topological_sorts(G):
+    """Returns a generator of _all_ topological sorts of the directed graph G.
+
+    A topological sort is a nonunique permutation of the nodes such that an
+    edge from u to v implies that u appears before v in the topological sort
+    order.
+
+    Parameters
+    ----------
+    G : NetworkX DiGraph
+        A directed graph
+
+    Yields
+    ------
+    topological_sort_order : list
+        a list of nodes in `G`, representing one of the topological sort orders
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is not directed
+    NetworkXUnfeasible
+        If `G` is not acyclic
+
+    Examples
+    --------
+    To enumerate all topological sorts of directed graph:
+
+    >>> DG = nx.DiGraph([(1, 2), (2, 3), (2, 4)])
+    >>> list(nx.all_topological_sorts(DG))
+    [[1, 2, 4, 3], [1, 2, 3, 4]]
+
+    Notes
+    -----
+    Implements an iterative version of the algorithm given in [1].
+
+    References
+    ----------
+    .. [1] Knuth, Donald E., Szwarcfiter, Jayme L. (1974).
+       "A Structured Program to Generate All Topological Sorting Arrangements"
+       Information Processing Letters, Volume 2, Issue 6, 1974, Pages 153-157,
+       ISSN 0020-0190,
+       https://doi.org/10.1016/0020-0190(74)90001-5.
+       Elsevier (North-Holland), Amsterdam
+    """
+    if not G.is_directed():
+        raise nx.NetworkXError("Topological sort not defined on undirected graphs.")
+
+    # the names of count and D are chosen to match the global variables in [1]
+    # number of edges originating in a vertex v
+    count = dict(G.in_degree())
+    # vertices with indegree 0
+    D = deque([v for v, d in G.in_degree() if d == 0])
+    # stack of first value chosen at a position k in the topological sort
+    bases = []
+    current_sort = []
+
+    # do-while construct
+    while True:
+        assert all(count[v] == 0 for v in D)
+
+        if len(current_sort) == len(G):
+            yield list(current_sort)
+
+            # clean-up stack
+            while len(current_sort) > 0:
+                assert len(bases) == len(current_sort)
+                q = current_sort.pop()
+
+                # "restores" all edges (q, x)
+                # NOTE: it is important to iterate over edges instead
+                # of successors, so count is updated correctly in multigraphs
+                for _, j in G.out_edges(q):
+                    count[j] += 1
+                    assert count[j] >= 0
+                # remove entries from D
+                while len(D) > 0 and count[D[-1]] > 0:
+                    D.pop()
+
+                # corresponds to a circular shift of the values in D
+                # if the first value chosen (the base) is in the first
+                # position of D again, we are done and need to consider the
+                # previous condition
+                D.appendleft(q)
+                if D[-1] == bases[-1]:
+                    # all possible values have been chosen at current position
+                    # remove corresponding marker
+                    bases.pop()
+                else:
+                    # there are still elements that have not been fixed
+                    # at the current position in the topological sort
+                    # stop removing elements, escape inner loop
+                    break
+
+        else:
+            if len(D) == 0:
+                raise nx.NetworkXUnfeasible("Graph contains a cycle.")
+
+            # choose next node
+            q = D.pop()
+            # "erase" all edges (q, x)
+            # NOTE: it is important to iterate over edges instead
+            # of successors, so count is updated correctly in multigraphs
+            for _, j in G.out_edges(q):
+                count[j] -= 1
+                assert count[j] >= 0
+                if count[j] == 0:
+                    D.append(j)
+            current_sort.append(q)
+
+            # base for current position might _not_ be fixed yet
+            if len(bases) < len(current_sort):
+                bases.append(q)
+
+        if len(bases) == 0:
+            break
+
+
+@nx._dispatchable
+def is_aperiodic(G):
+    """Returns True if `G` is aperiodic.
+
+    A strongly connected directed graph is aperiodic if there is no integer ``k > 1``
+    that divides the length of every cycle in the graph.
+
+    This function requires the graph `G` to be strongly connected and will raise
+    an error if it's not. For graphs that are not strongly connected, you should
+    first identify their strongly connected components
+    (using :func:`~networkx.algorithms.components.strongly_connected_components`)
+    or attracting components
+    (using :func:`~networkx.algorithms.components.attracting_components`),
+    and then apply this function to those individual components.
+
+    Parameters
+    ----------
+    G : NetworkX DiGraph
+        A directed graph
+
+    Returns
+    -------
+    bool
+        True if the graph is aperiodic False otherwise
+
+    Raises
+    ------
+    NetworkXError
+        If `G` is not directed
+    NetworkXError
+        If `G` is not strongly connected
+    NetworkXPointlessConcept
+        If `G` has no nodes
+
+    Examples
+    --------
+    A graph consisting of one cycle, the length of which is 2. Therefore ``k = 2``
+    divides the length of every cycle in the graph and thus the graph
+    is *not aperiodic*::
+
+        >>> DG = nx.DiGraph([(1, 2), (2, 1)])
+        >>> nx.is_aperiodic(DG)
+        False
+
+    A graph consisting of two cycles: one of length 2 and the other of length 3.
+    The cycle lengths are coprime, so there is no single value of k where ``k > 1``
+    that divides each cycle length and therefore the graph is *aperiodic*::
+
+        >>> DG = nx.DiGraph([(1, 2), (2, 3), (3, 1), (1, 4), (4, 1)])
+        >>> nx.is_aperiodic(DG)
+        True
+
+    A graph created from cycles of the same length can still be aperiodic since
+    the cycles can overlap and form new cycles of different lengths. For example,
+    the following graph contains a cycle ``[4, 2, 3, 1]`` of length 4, which is coprime
+    with the explicitly added cycles of length 3, so the graph is aperiodic::
+
+        >>> DG = nx.DiGraph()
+        >>> nx.add_cycle(DG, [1, 2, 3])
+        >>> nx.add_cycle(DG, [2, 1, 4])
+        >>> nx.is_aperiodic(DG)
+        True
+
+    A single-node graph's aperiodicity depends on whether it has a self-loop:
+    it is aperiodic if a self-loop exists, and periodic otherwise::
+
+        >>> G = nx.DiGraph()
+        >>> G.add_node(1)
+        >>> nx.is_aperiodic(G)
+        False
+        >>> G.add_edge(1, 1)
+        >>> nx.is_aperiodic(G)
+        True
+
+    A Markov chain can be modeled as a directed graph, with nodes representing
+    states and edges representing transitions with non-zero probability.
+    Aperiodicity is typically considered for irreducible Markov chains,
+    which are those that are *strongly connected* as graphs.
+
+    The following Markov chain is irreducible and aperiodic, and thus
+    ergodic. It is guaranteed to have a unique stationary distribution::
+
+        >>> G = nx.DiGraph()
+        >>> nx.add_cycle(G, [1, 2, 3, 4])
+        >>> G.add_edge(1, 3)
+        >>> nx.is_aperiodic(G)
+        True
+
+    Reducible Markov chains can sometimes have a unique stationary distribution.
+    This occurs if the chain has exactly one closed communicating class and
+    that class itself is aperiodic (see [1]_). You can use
+    :func:`~networkx.algorithms.components.attracting_components`
+    to find these closed communicating classes::
+
+        >>> G = nx.DiGraph([(1, 3), (2, 3)])
+        >>> nx.add_cycle(G, [3, 4, 5, 6])
+        >>> nx.add_cycle(G, [3, 5, 6])
+        >>> communicating_classes = list(nx.strongly_connected_components(G))
+        >>> len(communicating_classes)
+        3
+        >>> closed_communicating_classes = list(nx.attracting_components(G))
+        >>> len(closed_communicating_classes)
+        1
+        >>> nx.is_aperiodic(G.subgraph(closed_communicating_classes[0]))
+        True
+
+    Notes
+    -----
+    This uses the method outlined in [1]_, which runs in $O(m)$ time
+    given $m$ edges in `G`.
+
+    References
+    ----------
+    .. [1] Jarvis, J. P.; Shier, D. R. (1996),
+       "Graph-theoretic analysis of finite Markov chains,"
+       in Shier, D. R.; Wallenius, K. T., Applied Mathematical Modeling:
+       A Multidisciplinary Approach, CRC Press.
+    """
+    if not G.is_directed():
+        raise nx.NetworkXError("is_aperiodic not defined for undirected graphs")
+    if len(G) == 0:
+        raise nx.NetworkXPointlessConcept("Graph has no nodes.")
+    if not nx.is_strongly_connected(G):
+        raise nx.NetworkXError("Graph is not strongly connected.")
+    s = arbitrary_element(G)
+    levels = {s: 0}
+    this_level = [s]
+    g = 0
+    lev = 1
+    while this_level:
+        next_level = []
+        for u in this_level:
+            for v in G[u]:
+                if v in levels:  # Non-Tree Edge
+                    g = gcd(g, levels[u] - levels[v] + 1)
+                else:  # Tree Edge
+                    next_level.append(v)
+                    levels[v] = lev
+        this_level = next_level
+        lev += 1
+    return g == 1
+
+
+@nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
+def transitive_closure(G, reflexive=False):
+    """Returns transitive closure of a graph
+
+    The transitive closure of G = (V,E) is a graph G+ = (V,E+) such that
+    for all v, w in V there is an edge (v, w) in E+ if and only if there
+    is a path from v to w in G.
+
+    Handling of paths from v to v has some flexibility within this definition.
+    A reflexive transitive closure creates a self-loop for the path
+    from v to v of length 0. The usual transitive closure creates a
+    self-loop only if a cycle exists (a path from v to v with length > 0).
+    We also allow an option for no self-loops.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+        A directed/undirected graph/multigraph.
+    reflexive : Bool or None, optional (default: False)
+        Determines when cycles create self-loops in the Transitive Closure.
+        If True, trivial cycles (length 0) create self-loops. The result
+        is a reflexive transitive closure of G.
+        If False (the default) non-trivial cycles create self-loops.
+        If None, self-loops are not created.
+
+    Returns
+    -------
+    NetworkX graph
+        The transitive closure of `G`
+
+    Raises
+    ------
+    NetworkXError
+        If `reflexive` not in `{None, True, False}`
+
+    Examples
+    --------
+    The treatment of trivial (i.e. length 0) cycles is controlled by the
+    `reflexive` parameter.
+
+    Trivial (i.e. length 0) cycles do not create self-loops when
+    ``reflexive=False`` (the default)::
+
+        >>> DG = nx.DiGraph([(1, 2), (2, 3)])
+        >>> TC = nx.transitive_closure(DG, reflexive=False)
+        >>> TC.edges()
+        OutEdgeView([(1, 2), (1, 3), (2, 3)])
+
+    However, nontrivial (i.e. length greater than 0) cycles create self-loops
+    when ``reflexive=False`` (the default)::
+
+        >>> DG = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
+        >>> TC = nx.transitive_closure(DG, reflexive=False)
+        >>> TC.edges()
+        OutEdgeView([(1, 2), (1, 3), (1, 1), (2, 3), (2, 1), (2, 2), (3, 1), (3, 2), (3, 3)])
+
+    Trivial cycles (length 0) create self-loops when ``reflexive=True``::
+
+        >>> DG = nx.DiGraph([(1, 2), (2, 3)])
+        >>> TC = nx.transitive_closure(DG, reflexive=True)
+        >>> TC.edges()
+        OutEdgeView([(1, 2), (1, 1), (1, 3), (2, 3), (2, 2), (3, 3)])
+
+    And the third option is not to create self-loops at all when ``reflexive=None``::
+
+        >>> DG = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
+        >>> TC = nx.transitive_closure(DG, reflexive=None)
+        >>> TC.edges()
+        OutEdgeView([(1, 2), (1, 3), (2, 3), (2, 1), (3, 1), (3, 2)])
+
+    References
+    ----------
+    .. [1] https://www.ics.uci.edu/~eppstein/PADS/PartialOrder.py
+    """
+    TC = G.copy()
+
+    if reflexive not in {None, True, False}:
+        raise nx.NetworkXError("Incorrect value for the parameter `reflexive`")
+
+    for v in G:
+        if reflexive is None:
+            TC.add_edges_from((v, u) for u in nx.descendants(G, v) if u not in TC[v])
+        elif reflexive is True:
+            TC.add_edges_from(
+                (v, u) for u in nx.descendants(G, v) | {v} if u not in TC[v]
+            )
+        elif reflexive is False:
+            TC.add_edges_from((v, e[1]) for e in nx.edge_bfs(G, v) if e[1] not in TC[v])
+
+    return TC
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
+def transitive_closure_dag(G, topo_order=None):
+    """Returns the transitive closure of a directed acyclic graph.
+
+    This function is faster than the function `transitive_closure`, but fails
+    if the graph has a cycle.
+
+    The transitive closure of G = (V,E) is a graph G+ = (V,E+) such that
+    for all v, w in V there is an edge (v, w) in E+ if and only if there
+    is a non-null path from v to w in G.
+
+    Parameters
+    ----------
+    G : NetworkX DiGraph
+        A directed acyclic graph (DAG)
+
+    topo_order: list or tuple, optional
+        A topological order for G (if None, the function will compute one)
+
+    Returns
+    -------
+    NetworkX DiGraph
+        The transitive closure of `G`
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is not directed
+    NetworkXUnfeasible
+        If `G` has a cycle
+
+    Examples
+    --------
+    >>> DG = nx.DiGraph([(1, 2), (2, 3)])
+    >>> TC = nx.transitive_closure_dag(DG)
+    >>> TC.edges()
+    OutEdgeView([(1, 2), (1, 3), (2, 3)])
+
+    Notes
+    -----
+    This algorithm is probably simple enough to be well-known but I didn't find
+    a mention in the literature.
+    """
+    if topo_order is None:
+        topo_order = list(topological_sort(G))
+
+    TC = G.copy()
+
+    # idea: traverse vertices following a reverse topological order, connecting
+    # each vertex to its descendants at distance 2 as we go
+    for v in reversed(topo_order):
+        TC.add_edges_from((v, u) for u in nx.descendants_at_distance(TC, v, 2))
+
+    return TC
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable(returns_graph=True)
+def transitive_reduction(G):
+    """Returns transitive reduction of a directed graph
+
+    The transitive reduction of G = (V,E) is a graph G- = (V,E-) such that
+    for all v,w in V there is an edge (v,w) in E- if and only if (v,w) is
+    in E and there is no path from v to w in G with length greater than 1.
+
+    Parameters
+    ----------
+    G : NetworkX DiGraph
+        A directed acyclic graph (DAG)
+
+    Returns
+    -------
+    NetworkX DiGraph
+        The transitive reduction of `G`
+
+    Raises
+    ------
+    NetworkXError
+        If `G` is not a directed acyclic graph (DAG) transitive reduction is
+        not uniquely defined and a :exc:`NetworkXError` exception is raised.
+
+    Examples
+    --------
+    To perform transitive reduction on a DiGraph:
+
+    >>> DG = nx.DiGraph([(1, 2), (2, 3), (1, 3)])
+    >>> TR = nx.transitive_reduction(DG)
+    >>> list(TR.edges)
+    [(1, 2), (2, 3)]
+
+    To avoid unnecessary data copies, this implementation does not return a
+    DiGraph with node/edge data.
+    To perform transitive reduction on a DiGraph and transfer node/edge data:
+
+    >>> DG = nx.DiGraph()
+    >>> DG.add_edges_from([(1, 2), (2, 3), (1, 3)], color="red")
+    >>> TR = nx.transitive_reduction(DG)
+    >>> TR.add_nodes_from(DG.nodes(data=True))
+    >>> TR.add_edges_from((u, v, DG.edges[u, v]) for u, v in TR.edges)
+    >>> list(TR.edges(data=True))
+    [(1, 2, {'color': 'red'}), (2, 3, {'color': 'red'})]
+
+    References
+    ----------
+    https://en.wikipedia.org/wiki/Transitive_reduction
+
+    """
+    if not is_directed_acyclic_graph(G):
+        msg = "Directed Acyclic Graph required for transitive_reduction"
+        raise nx.NetworkXError(msg)
+    TR = nx.DiGraph()
+    TR.add_nodes_from(G.nodes())
+    descendants = {}
+    # count before removing set stored in descendants
+    check_count = dict(G.in_degree)
+    for u in G:
+        u_nbrs = set(G[u])
+        for v in G[u]:
+            if v in u_nbrs:
+                if v not in descendants:
+                    descendants[v] = {y for x, y in nx.dfs_edges(G, v)}
+                u_nbrs -= descendants[v]
+            check_count[v] -= 1
+            if check_count[v] == 0:
+                del descendants[v]
+        TR.add_edges_from((u, v) for v in u_nbrs)
+    return TR
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable
+def antichains(G, topo_order=None):
+    """Generates antichains from a directed acyclic graph (DAG).
+
+    An antichain is a subset of a partially ordered set such that any
+    two elements in the subset are incomparable.
+
+    Parameters
+    ----------
+    G : NetworkX DiGraph
+        A directed acyclic graph (DAG)
+
+    topo_order: list or tuple, optional
+        A topological order for G (if None, the function will compute one)
+
+    Yields
+    ------
+    antichain : list
+        a list of nodes in `G` representing an antichain
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is not directed
+
+    NetworkXUnfeasible
+        If `G` contains a cycle
+
+    Examples
+    --------
+    >>> DG = nx.DiGraph([(1, 2), (1, 3)])
+    >>> list(nx.antichains(DG))
+    [[], [3], [2], [2, 3], [1]]
+
+    Notes
+    -----
+    This function was originally developed by Peter Jipsen and Franco Saliola
+    for the SAGE project. It's included in NetworkX with permission from the
+    authors. Original SAGE code at:
+
+    https://github.com/sagemath/sage/blob/master/src/sage/combinat/posets/hasse_diagram.py
+
+    References
+    ----------
+    .. [1] Free Lattices, by R. Freese, J. Jezek and J. B. Nation,
+       AMS, Vol 42, 1995, p. 226.
+    """
+    if topo_order is None:
+        topo_order = list(nx.topological_sort(G))
+
+    TC = nx.transitive_closure_dag(G, topo_order)
+    antichains_stacks = [([], list(reversed(topo_order)))]
+
+    while antichains_stacks:
+        (antichain, stack) = antichains_stacks.pop()
+        # Invariant:
+        #  - the elements of antichain are independent
+        #  - the elements of stack are independent from those of antichain
+        yield antichain
+        while stack:
+            x = stack.pop()
+            new_antichain = antichain + [x]
+            new_stack = [t for t in stack if not ((t in TC[x]) or (x in TC[t]))]
+            antichains_stacks.append((new_antichain, new_stack))
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable(edge_attrs={"weight": "default_weight"})
+def dag_longest_path(G, weight="weight", default_weight=1, topo_order=None):
+    """Returns the longest path in a directed acyclic graph (DAG).
+
+    If `G` has edges with `weight` attribute the edge data are used as
+    weight values.
+
+    Parameters
+    ----------
+    G : NetworkX DiGraph
+        A directed acyclic graph (DAG)
+
+    weight : str, optional
+        Edge data key to use for weight
+
+    default_weight : int, optional
+        The weight of edges that do not have a weight attribute
+
+    topo_order: list or tuple, optional
+        A topological order for `G` (if None, the function will compute one)
+
+    Returns
+    -------
+    list
+        Longest path
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is not directed
+
+    Examples
+    --------
+    >>> DG = nx.DiGraph(
+    ...     [(0, 1, {"cost": 1}), (1, 2, {"cost": 1}), (0, 2, {"cost": 42})]
+    ... )
+    >>> list(nx.all_simple_paths(DG, 0, 2))
+    [[0, 1, 2], [0, 2]]
+    >>> nx.dag_longest_path(DG)
+    [0, 1, 2]
+    >>> nx.dag_longest_path(DG, weight="cost")
+    [0, 2]
+
+    In the case where multiple valid topological orderings exist, `topo_order`
+    can be used to specify a specific ordering:
+
+    >>> DG = nx.DiGraph([(0, 1), (0, 2)])
+    >>> sorted(nx.all_topological_sorts(DG))  # Valid topological orderings
+    [[0, 1, 2], [0, 2, 1]]
+    >>> nx.dag_longest_path(DG, topo_order=[0, 1, 2])
+    [0, 1]
+    >>> nx.dag_longest_path(DG, topo_order=[0, 2, 1])
+    [0, 2]
+
+    See also
+    --------
+    dag_longest_path_length
+
+    """
+    if not G:
+        return []
+
+    if topo_order is None:
+        topo_order = nx.topological_sort(G)
+
+    dist = {}  # stores {v : (length, u)}
+    for v in topo_order:
+        us = [
+            (
+                dist[u][0]
+                + (
+                    max(data.values(), key=lambda x: x.get(weight, default_weight))
+                    if G.is_multigraph()
+                    else data
+                ).get(weight, default_weight),
+                u,
+            )
+            for u, data in G.pred[v].items()
+        ]
+
+        # Use the best predecessor if there is one and its distance is
+        # non-negative, otherwise terminate.
+        maxu = max(us, key=lambda x: x[0]) if us else (0, v)
+        dist[v] = maxu if maxu[0] >= 0 else (0, v)
+
+    u = None
+    v = max(dist, key=lambda x: dist[x][0])
+    path = []
+    while u != v:
+        path.append(v)
+        u = v
+        v = dist[v][1]
+
+    path.reverse()
+    return path
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable(edge_attrs={"weight": "default_weight"})
+def dag_longest_path_length(G, weight="weight", default_weight=1):
+    """Returns the longest path length in a DAG
+
+    Parameters
+    ----------
+    G : NetworkX DiGraph
+        A directed acyclic graph (DAG)
+
+    weight : string, optional
+        Edge data key to use for weight
+
+    default_weight : int, optional
+        The weight of edges that do not have a weight attribute
+
+    Returns
+    -------
+    int
+        Longest path length
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is not directed
+
+    Examples
+    --------
+    >>> DG = nx.DiGraph(
+    ...     [(0, 1, {"cost": 1}), (1, 2, {"cost": 1}), (0, 2, {"cost": 42})]
+    ... )
+    >>> list(nx.all_simple_paths(DG, 0, 2))
+    [[0, 1, 2], [0, 2]]
+    >>> nx.dag_longest_path_length(DG)
+    2
+    >>> nx.dag_longest_path_length(DG, weight="cost")
+    42
+
+    See also
+    --------
+    dag_longest_path
+    """
+    path = nx.dag_longest_path(G, weight, default_weight)
+    path_length = 0
+    if G.is_multigraph():
+        for u, v in pairwise(path):
+            i = max(G[u][v], key=lambda x: G[u][v][x].get(weight, default_weight))
+            path_length += G[u][v][i].get(weight, default_weight)
+    else:
+        for u, v in pairwise(path):
+            path_length += G[u][v].get(weight, default_weight)
+
+    return path_length
+
+
+@nx._dispatchable
+def root_to_leaf_paths(G):
+    """Yields root-to-leaf paths in a directed acyclic graph.
+
+    `G` must be a directed acyclic graph. If not, the behavior of this
+    function is undefined. A "root" in this graph is a node of in-degree
+    zero and a "leaf" a node of out-degree zero.
+
+    When invoked, this function iterates over each path from any root to
+    any leaf. A path is a list of nodes.
+
+    """
+    roots = (v for v, d in G.in_degree() if d == 0)
+    leaves = (v for v, d in G.out_degree() if d == 0)
+    all_paths = partial(nx.all_simple_paths, G)
+    # TODO In Python 3, this would be better as `yield from ...`.
+    return chaini(starmap(all_paths, product(roots, leaves)))
+
+
+@not_implemented_for("multigraph")
+@not_implemented_for("undirected")
+@nx._dispatchable(returns_graph=True)
+def dag_to_branching(G):
+    """Returns a branching representing all (overlapping) paths from
+    root nodes to leaf nodes in the given directed acyclic graph.
+
+    As described in :mod:`networkx.algorithms.tree.recognition`, a
+    *branching* is a directed forest in which each node has at most one
+    parent. In other words, a branching is a disjoint union of
+    *arborescences*. For this function, each node of in-degree zero in
+    `G` becomes a root of one of the arborescences, and there will be
+    one leaf node for each distinct path from that root to a leaf node
+    in `G`.
+
+    Each node `v` in `G` with *k* parents becomes *k* distinct nodes in
+    the returned branching, one for each parent, and the sub-DAG rooted
+    at `v` is duplicated for each copy. The algorithm then recurses on
+    the children of each copy of `v`.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        A directed acyclic graph.
+
+    Returns
+    -------
+    DiGraph
+        The branching in which there is a bijection between root-to-leaf
+        paths in `G` (in which multiple paths may share the same leaf)
+        and root-to-leaf paths in the branching (in which there is a
+        unique path from a root to a leaf).
+
+        Each node has an attribute 'source' whose value is the original
+        node to which this node corresponds. No other graph, node, or
+        edge attributes are copied into this new graph.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is not directed, or if `G` is a multigraph.
+
+    HasACycle
+        If `G` is not acyclic.
+
+    Examples
+    --------
+    To examine which nodes in the returned branching were produced by
+    which original node in the directed acyclic graph, we can collect
+    the mapping from source node to new nodes into a dictionary. For
+    example, consider the directed diamond graph::
+
+        >>> from collections import defaultdict
+        >>> from operator import itemgetter
+        >>>
+        >>> G = nx.DiGraph(nx.utils.pairwise("abd"))
+        >>> G.add_edges_from(nx.utils.pairwise("acd"))
+        >>> B = nx.dag_to_branching(G)
+        >>>
+        >>> sources = defaultdict(set)
+        >>> for v, source in B.nodes(data="source"):
+        ...     sources[source].add(v)
+        >>> len(sources["a"])
+        1
+        >>> len(sources["d"])
+        2
+
+    To copy node attributes from the original graph to the new graph,
+    you can use a dictionary like the one constructed in the above
+    example::
+
+        >>> for source, nodes in sources.items():
+        ...     for v in nodes:
+        ...         B.nodes[v].update(G.nodes[source])
+
+    Notes
+    -----
+    This function is not idempotent in the sense that the node labels in
+    the returned branching may be uniquely generated each time the
+    function is invoked. In fact, the node labels may not be integers;
+    in order to relabel the nodes to be more readable, you can use the
+    :func:`networkx.convert_node_labels_to_integers` function.
+
+    The current implementation of this function uses
+    :func:`networkx.prefix_tree`, so it is subject to the limitations of
+    that function.
+
+    """
+    if has_cycle(G):
+        msg = "dag_to_branching is only defined for acyclic graphs"
+        raise nx.HasACycle(msg)
+    paths = root_to_leaf_paths(G)
+    B = nx.prefix_tree(paths)
+    # Remove the synthetic `root`(0) and `NIL`(-1) nodes from the tree
+    B.remove_node(0)
+    B.remove_node(-1)
+    return B
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable
+def v_structures(G):
+    """Yields 3-node tuples that represent the v-structures in `G`.
+
+    Colliders are triples in the directed acyclic graph (DAG) where two parent nodes
+    point to the same child node. V-structures are colliders where the two parent
+    nodes are not adjacent. In a causal graph setting, the parents do not directly
+    depend on each other, but conditioning on the child node provides an association.
+
+    Parameters
+    ----------
+    G : graph
+        A networkx `~networkx.DiGraph`.
+
+    Yields
+    ------
+    A 3-tuple representation of a v-structure
+        Each v-structure is a 3-tuple with the parent, collider, and other parent.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is an undirected graph.
+
+    Examples
+    --------
+    >>> G = nx.DiGraph([(1, 2), (0, 4), (3, 1), (2, 4), (0, 5), (4, 5), (1, 5)])
+    >>> nx.is_directed_acyclic_graph(G)
+    True
+    >>> list(nx.dag.v_structures(G))
+    [(0, 4, 2), (0, 5, 1), (4, 5, 1)]
+
+    See Also
+    --------
+    colliders
+
+    Notes
+    -----
+    This function was written to be used on DAGs, however it works on cyclic graphs
+    too. Since colliders are referred to in the cyclic causal graph literature
+    [2]_ we allow cyclic graphs in this function. It is suggested that you test if
+    your input graph is acyclic as in the example if you want that property.
+
+    References
+    ----------
+    .. [1]  `Pearl's PRIMER `_
+            Ch-2 page 50: v-structures def.
+    .. [2] A Hyttinen, P.O. Hoyer, F. Eberhardt, M J ̈arvisalo, (2013)
+           "Discovering cyclic causal models with latent variables:
+           a general SAT-based procedure", UAI'13: Proceedings of the Twenty-Ninth
+           Conference on Uncertainty in Artificial Intelligence, pg 301–310,
+           `doi:10.5555/3023638.3023669 `_
+    """
+    for p1, c, p2 in colliders(G):
+        if not (G.has_edge(p1, p2) or G.has_edge(p2, p1)):
+            yield (p1, c, p2)
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable
+def colliders(G):
+    """Yields 3-node tuples that represent the colliders in `G`.
+
+    In a Directed Acyclic Graph (DAG), if you have three nodes A, B, and C, and
+    there are edges from A to C and from B to C, then C is a collider [1]_ . In
+    a causal graph setting, this means that both events A and B are "causing" C,
+    and conditioning on C provide an association between A and B even if
+    no direct causal relationship exists between A and B.
+
+    Parameters
+    ----------
+    G : graph
+        A networkx `~networkx.DiGraph`.
+
+    Yields
+    ------
+    A 3-tuple representation of a collider
+        Each collider is a 3-tuple with the parent, collider, and other parent.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is an undirected graph.
+
+    Examples
+    --------
+    >>> G = nx.DiGraph([(1, 2), (0, 4), (3, 1), (2, 4), (0, 5), (4, 5), (1, 5)])
+    >>> nx.is_directed_acyclic_graph(G)
+    True
+    >>> list(nx.dag.colliders(G))
+    [(0, 4, 2), (0, 5, 4), (0, 5, 1), (4, 5, 1)]
+
+    See Also
+    --------
+    v_structures
+
+    Notes
+    -----
+    This function was written to be used on DAGs, however it works on cyclic graphs
+    too. Since colliders are referred to in the cyclic causal graph literature
+    [2]_ we allow cyclic graphs in this function. It is suggested that you test if
+    your input graph is acyclic as in the example if you want that property.
+
+    References
+    ----------
+    .. [1] `Wikipedia: Collider in causal graphs `_
+    .. [2] A Hyttinen, P.O. Hoyer, F. Eberhardt, M J ̈arvisalo, (2013)
+           "Discovering cyclic causal models with latent variables:
+           a general SAT-based procedure", UAI'13: Proceedings of the Twenty-Ninth
+           Conference on Uncertainty in Artificial Intelligence, pg 301–310,
+           `doi:10.5555/3023638.3023669 `_
+    """
+    for node in G.nodes:
+        for p1, p2 in combinations(G.predecessors(node), 2):
+            yield (p1, node, p2)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/distance_measures.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/distance_measures.py
new file mode 100644
index 0000000000000000000000000000000000000000..728cc5f1c2af07eaeb8e96a91603be231fa69230
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/distance_measures.py
@@ -0,0 +1,1095 @@
+"""Graph diameter, radius, eccentricity and other properties."""
+
+import math
+
+import networkx as nx
+from networkx.utils import not_implemented_for
+
+__all__ = [
+    "eccentricity",
+    "diameter",
+    "harmonic_diameter",
+    "radius",
+    "periphery",
+    "center",
+    "barycenter",
+    "resistance_distance",
+    "kemeny_constant",
+    "effective_graph_resistance",
+]
+
+
+def _extrema_bounding(G, compute="diameter", weight=None):
+    """Compute requested extreme distance metric of undirected graph G
+
+    Computation is based on smart lower and upper bounds, and in practice
+    linear in the number of nodes, rather than quadratic (except for some
+    border cases such as complete graphs or circle shaped graphs).
+
+    Parameters
+    ----------
+    G : NetworkX graph
+       An undirected graph
+
+    compute : string denoting the requesting metric
+       "diameter" for the maximal eccentricity value,
+       "radius" for the minimal eccentricity value,
+       "periphery" for the set of nodes with eccentricity equal to the diameter,
+       "center" for the set of nodes with eccentricity equal to the radius,
+       "eccentricities" for the maximum distance from each node to all other nodes in G
+
+    weight : string, function, or None
+        If this is a string, then edge weights will be accessed via the
+        edge attribute with this key (that is, the weight of the edge
+        joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
+        such edge attribute exists, the weight of the edge is assumed to
+        be one.
+
+        If this is a function, the weight of an edge is the value
+        returned by the function. The function must accept exactly three
+        positional arguments: the two endpoints of an edge and the
+        dictionary of edge attributes for that edge. The function must
+        return a number.
+
+        If this is None, every edge has weight/distance/cost 1.
+
+        Weights stored as floating point values can lead to small round-off
+        errors in distances. Use integer weights to avoid this.
+
+        Weights should be positive, since they are distances.
+
+    Returns
+    -------
+    value : value of the requested metric
+       int for "diameter" and "radius" or
+       list of nodes for "center" and "periphery" or
+       dictionary of eccentricity values keyed by node for "eccentricities"
+
+    Raises
+    ------
+    NetworkXError
+        If the graph consists of multiple components
+    ValueError
+        If `compute` is not one of "diameter", "radius", "periphery", "center", or "eccentricities".
+
+    Notes
+    -----
+    This algorithm was proposed in [1]_ and discussed further in [2]_ and [3]_.
+
+    References
+    ----------
+    .. [1] F. W. Takes, W. A. Kosters,
+       "Determining the diameter of small world networks."
+       Proceedings of the 20th ACM international conference on Information and
+       knowledge management, 2011
+       https://dl.acm.org/doi/abs/10.1145/2063576.2063748
+    .. [2] F. W. Takes, W. A. Kosters,
+       "Computing the Eccentricity Distribution of Large Graphs."
+       Algorithms, 2013
+       https://www.mdpi.com/1999-4893/6/1/100
+    .. [3] M. Borassi, P. Crescenzi, M. Habib, W. A. Kosters, A. Marino, F. W. Takes,
+       "Fast diameter and radius BFS-based computation in (weakly connected)
+       real-world graphs: With an application to the six degrees of separation
+       games."
+       Theoretical Computer Science, 2015
+       https://www.sciencedirect.com/science/article/pii/S0304397515001644
+    """
+    # init variables
+    degrees = dict(G.degree())  # start with the highest degree node
+    minlowernode = max(degrees, key=degrees.get)
+    N = len(degrees)  # number of nodes
+    # alternate between smallest lower and largest upper bound
+    high = False
+    # status variables
+    ecc_lower = dict.fromkeys(G, 0)
+    ecc_upper = dict.fromkeys(G, math.inf)
+    candidates = set(G)
+
+    # (re)set bound extremes
+    minlower = math.inf
+    maxlower = 0
+    minupper = math.inf
+    maxupper = 0
+
+    # repeat the following until there are no more candidates
+    while candidates:
+        if high:
+            current = maxuppernode  # select node with largest upper bound
+        else:
+            current = minlowernode  # select node with smallest lower bound
+        high = not high
+
+        # get distances from/to current node and derive eccentricity
+        dist = nx.shortest_path_length(G, source=current, weight=weight)
+
+        if len(dist) != N:
+            msg = "Cannot compute metric because graph is not connected."
+            raise nx.NetworkXError(msg)
+        current_ecc = max(dist.values())
+
+        # print status update
+        #        print ("ecc of " + str(current) + " (" + str(ecc_lower[current]) + "/"
+        #        + str(ecc_upper[current]) + ", deg: " + str(dist[current]) + ") is "
+        #        + str(current_ecc))
+        #        print(ecc_upper)
+
+        # (re)set bound extremes
+        maxuppernode = None
+        minlowernode = None
+
+        # update node bounds
+        for i in candidates:
+            # update eccentricity bounds
+            d = dist[i]
+            ecc_lower[i] = low = max(ecc_lower[i], max(d, (current_ecc - d)))
+            ecc_upper[i] = upp = min(ecc_upper[i], current_ecc + d)
+
+            # update min/max values of lower and upper bounds
+            minlower = min(ecc_lower[i], minlower)
+            maxlower = max(ecc_lower[i], maxlower)
+            minupper = min(ecc_upper[i], minupper)
+            maxupper = max(ecc_upper[i], maxupper)
+
+        # update candidate set
+        if compute == "diameter":
+            ruled_out = {
+                i
+                for i in candidates
+                if ecc_upper[i] <= maxlower and 2 * ecc_lower[i] >= maxupper
+            }
+        elif compute == "radius":
+            ruled_out = {
+                i
+                for i in candidates
+                if ecc_lower[i] >= minupper and ecc_upper[i] + 1 <= 2 * minlower
+            }
+        elif compute == "periphery":
+            ruled_out = {
+                i
+                for i in candidates
+                if ecc_upper[i] < maxlower
+                and (maxlower == maxupper or ecc_lower[i] > maxupper)
+            }
+        elif compute == "center":
+            ruled_out = {
+                i
+                for i in candidates
+                if ecc_lower[i] > minupper
+                and (minlower == minupper or ecc_upper[i] + 1 < 2 * minlower)
+            }
+        elif compute == "eccentricities":
+            ruled_out = set()
+        else:
+            msg = "compute must be one of 'diameter', 'radius', 'periphery', 'center', 'eccentricities'"
+            raise ValueError(msg)
+
+        ruled_out.update(i for i in candidates if ecc_lower[i] == ecc_upper[i])
+        candidates -= ruled_out
+
+        #        for i in ruled_out:
+        #            print("removing %g: ecc_u: %g maxl: %g ecc_l: %g maxu: %g"%
+        #                    (i,ecc_upper[i],maxlower,ecc_lower[i],maxupper))
+        #        print("node %g: ecc_u: %g maxl: %g ecc_l: %g maxu: %g"%
+        #                    (4,ecc_upper[4],maxlower,ecc_lower[4],maxupper))
+        #        print("NODE 4: %g"%(ecc_upper[4] <= maxlower))
+        #        print("NODE 4: %g"%(2 * ecc_lower[4] >= maxupper))
+        #        print("NODE 4: %g"%(ecc_upper[4] <= maxlower
+        #                            and 2 * ecc_lower[4] >= maxupper))
+
+        # updating maxuppernode and minlowernode for selection in next round
+        for i in candidates:
+            if (
+                minlowernode is None
+                or (
+                    ecc_lower[i] == ecc_lower[minlowernode]
+                    and degrees[i] > degrees[minlowernode]
+                )
+                or (ecc_lower[i] < ecc_lower[minlowernode])
+            ):
+                minlowernode = i
+
+            if (
+                maxuppernode is None
+                or (
+                    ecc_upper[i] == ecc_upper[maxuppernode]
+                    and degrees[i] > degrees[maxuppernode]
+                )
+                or (ecc_upper[i] > ecc_upper[maxuppernode])
+            ):
+                maxuppernode = i
+
+        # print status update
+    #        print (" min=" + str(minlower) + "/" + str(minupper) +
+    #        " max=" + str(maxlower) + "/" + str(maxupper) +
+    #        " candidates: " + str(len(candidates)))
+    #        print("cand:",candidates)
+    #        print("ecc_l",ecc_lower)
+    #        print("ecc_u",ecc_upper)
+    #        wait = input("press Enter to continue")
+
+    # return the correct value of the requested metric
+    if compute == "diameter":
+        return maxlower
+    if compute == "radius":
+        return minupper
+    if compute == "periphery":
+        p = [v for v in G if ecc_lower[v] == maxlower]
+        return p
+    if compute == "center":
+        c = [v for v in G if ecc_upper[v] == minupper]
+        return c
+    if compute == "eccentricities":
+        return ecc_lower
+    return None
+
+
+@nx._dispatchable(edge_attrs="weight")
+def eccentricity(G, v=None, sp=None, weight=None):
+    """Returns the eccentricity of nodes in G.
+
+    The eccentricity of a node v is the maximum distance from v to
+    all other nodes in G.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+       A graph
+
+    v : node, optional
+       Return value of specified node
+
+    sp : dict of dicts, optional
+       All pairs shortest path lengths as a dictionary of dictionaries
+
+    weight : string, function, or None (default=None)
+        If this is a string, then edge weights will be accessed via the
+        edge attribute with this key (that is, the weight of the edge
+        joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
+        such edge attribute exists, the weight of the edge is assumed to
+        be one.
+
+        If this is a function, the weight of an edge is the value
+        returned by the function. The function must accept exactly three
+        positional arguments: the two endpoints of an edge and the
+        dictionary of edge attributes for that edge. The function must
+        return a number.
+
+        If this is None, every edge has weight/distance/cost 1.
+
+        Weights stored as floating point values can lead to small round-off
+        errors in distances. Use integer weights to avoid this.
+
+        Weights should be positive, since they are distances.
+
+    Returns
+    -------
+    ecc : dictionary
+       A dictionary of eccentricity values keyed by node.
+
+    Examples
+    --------
+    >>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
+    >>> dict(nx.eccentricity(G))
+    {1: 2, 2: 3, 3: 2, 4: 2, 5: 3}
+
+    >>> dict(
+    ...     nx.eccentricity(G, v=[1, 5])
+    ... )  # This returns the eccentricity of node 1 & 5
+    {1: 2, 5: 3}
+
+    """
+    #    if v is None:                # none, use entire graph
+    #        nodes=G.nodes()
+    #    elif v in G:               # is v a single node
+    #        nodes=[v]
+    #    else:                      # assume v is a container of nodes
+    #        nodes=v
+    order = G.order()
+    e = {}
+    for n in G.nbunch_iter(v):
+        if sp is None:
+            length = nx.shortest_path_length(G, source=n, weight=weight)
+
+            L = len(length)
+        else:
+            try:
+                length = sp[n]
+                L = len(length)
+            except TypeError as err:
+                raise nx.NetworkXError('Format of "sp" is invalid.') from err
+        if L != order:
+            if G.is_directed():
+                msg = (
+                    "Found infinite path length because the digraph is not"
+                    " strongly connected"
+                )
+            else:
+                msg = "Found infinite path length because the graph is not connected"
+            raise nx.NetworkXError(msg)
+
+        e[n] = max(length.values())
+
+    if v in G:
+        return e[v]  # return single value
+    return e
+
+
+@nx._dispatchable(edge_attrs="weight")
+def diameter(G, e=None, usebounds=False, weight=None):
+    """Returns the diameter of the graph G.
+
+    The diameter is the maximum eccentricity.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+       A graph
+
+    e : eccentricity dictionary, optional
+      A precomputed dictionary of eccentricities.
+
+    usebounds : bool, optional
+        If `True`, use extrema bounding (see Notes) when computing the diameter
+        for undirected graphs. Extrema bounding may accelerate the
+        distance calculation for some graphs. `usebounds` is ignored if `G` is
+        directed or if `e` is not `None`. Default is `False`.
+
+    weight : string, function, or None
+        If this is a string, then edge weights will be accessed via the
+        edge attribute with this key (that is, the weight of the edge
+        joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
+        such edge attribute exists, the weight of the edge is assumed to
+        be one.
+
+        If this is a function, the weight of an edge is the value
+        returned by the function. The function must accept exactly three
+        positional arguments: the two endpoints of an edge and the
+        dictionary of edge attributes for that edge. The function must
+        return a number.
+
+        If this is None, every edge has weight/distance/cost 1.
+
+        Weights stored as floating point values can lead to small round-off
+        errors in distances. Use integer weights to avoid this.
+
+        Weights should be positive, since they are distances.
+
+    Returns
+    -------
+    d : integer
+       Diameter of graph
+
+    Notes
+    -----
+    When ``usebounds=True``, the computation makes use of smart lower
+    and upper bounds and is often linear in the number of nodes, rather than
+    quadratic (except for some border cases such as complete graphs or circle
+    shaped-graphs).
+
+    Examples
+    --------
+    >>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
+    >>> nx.diameter(G)
+    3
+
+    See Also
+    --------
+    eccentricity
+    """
+    if usebounds is True and e is None and not G.is_directed():
+        return _extrema_bounding(G, compute="diameter", weight=weight)
+    if e is None:
+        e = eccentricity(G, weight=weight)
+    return max(e.values())
+
+
+@nx._dispatchable(edge_attrs="weight")
+def harmonic_diameter(G, sp=None, *, weight=None):
+    """Returns the harmonic diameter of the graph G.
+
+    The harmonic diameter of a graph is the harmonic mean of the distances
+    between all pairs of distinct vertices. Graphs that are not strongly
+    connected have infinite diameter and mean distance, making such
+    measures not useful. Restricting the diameter or mean distance to
+    finite distances yields paradoxical values (e.g., a perfect match
+    would have diameter one). The harmonic mean handles gracefully
+    infinite distances (e.g., a perfect match has harmonic diameter equal
+    to the number of vertices minus one), making it possible to assign a
+    meaningful value to all graphs.
+
+    Note that in [1] the harmonic diameter is called "connectivity length":
+    however, "harmonic diameter" is a more standard name from the
+    theory of metric spaces. The name "harmonic mean distance" is perhaps
+    a more descriptive name, but is not used in the literature, so we use the
+    name "harmonic diameter" here.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+       A graph
+
+    sp : dict of dicts, optional
+       All-pairs shortest path lengths as a dictionary of dictionaries
+
+    weight : string, function, or None (default=None)
+        If None, every edge has weight/distance 1.
+        If a string, use this edge attribute as the edge weight.
+        Any edge attribute not present defaults to 1.
+        If a function, the weight of an edge is the value returned by the function.
+        The function must accept exactly three positional arguments:
+        the two endpoints of an edge and the dictionary of edge attributes for
+        that edge. The function must return a number.
+
+    Returns
+    -------
+    hd : float
+       Harmonic diameter of graph
+
+    References
+    ----------
+    .. [1] Massimo Marchiori and Vito Latora, "Harmony in the small-world".
+           *Physica A: Statistical Mechanics and Its Applications*
+           285(3-4), pages 539-546, 2000.
+           
+    """
+    order = G.order()
+
+    sum_invd = 0
+    for n in G:
+        if sp is None:
+            length = nx.single_source_dijkstra_path_length(G, n, weight=weight)
+        else:
+            try:
+                length = sp[n]
+                L = len(length)
+            except TypeError as err:
+                raise nx.NetworkXError('Format of "sp" is invalid.') from err
+
+        for d in length.values():
+            # Note that this will skip the zero distance from n to itself,
+            # as it should be, but also zero-weight paths in weighted graphs.
+            if d != 0:
+                sum_invd += 1 / d
+
+    if sum_invd != 0:
+        return order * (order - 1) / sum_invd
+    if order > 1:
+        return math.inf
+    return math.nan
+
+
+@nx._dispatchable(edge_attrs="weight")
+def periphery(G, e=None, usebounds=False, weight=None):
+    """Returns the periphery of the graph G.
+
+    The periphery is the set of nodes with eccentricity equal to the diameter.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+       A graph
+
+    e : eccentricity dictionary, optional
+      A precomputed dictionary of eccentricities.
+
+    usebounds : bool, optional
+        If `True`, use extrema bounding (see Notes) when computing the periphery
+        for undirected graphs. Extrema bounding may accelerate the
+        distance calculation for some graphs. `usebounds` is ignored if `G` is
+        directed or if `e` is not `None`. Default is `False`.
+
+    weight : string, function, or None
+        If this is a string, then edge weights will be accessed via the
+        edge attribute with this key (that is, the weight of the edge
+        joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
+        such edge attribute exists, the weight of the edge is assumed to
+        be one.
+
+        If this is a function, the weight of an edge is the value
+        returned by the function. The function must accept exactly three
+        positional arguments: the two endpoints of an edge and the
+        dictionary of edge attributes for that edge. The function must
+        return a number.
+
+        If this is None, every edge has weight/distance/cost 1.
+
+        Weights stored as floating point values can lead to small round-off
+        errors in distances. Use integer weights to avoid this.
+
+        Weights should be positive, since they are distances.
+
+    Returns
+    -------
+    p : list
+       List of nodes in periphery
+
+    Notes
+    -----
+    When ``usebounds=True``, the computation makes use of smart lower
+    and upper bounds and is often linear in the number of nodes, rather than
+    quadratic (except for some border cases such as complete graphs or circle
+    shaped-graphs).
+
+    Examples
+    --------
+    >>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
+    >>> nx.periphery(G)
+    [2, 5]
+
+    See Also
+    --------
+    barycenter
+    center
+    """
+    if usebounds is True and e is None and not G.is_directed():
+        return _extrema_bounding(G, compute="periphery", weight=weight)
+    if e is None:
+        e = eccentricity(G, weight=weight)
+    diameter = max(e.values())
+    p = [v for v in e if e[v] == diameter]
+    return p
+
+
+@nx._dispatchable(edge_attrs="weight")
+def radius(G, e=None, usebounds=False, weight=None):
+    """Returns the radius of the graph G.
+
+    The radius is the minimum eccentricity.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+       A graph
+
+    e : eccentricity dictionary, optional
+      A precomputed dictionary of eccentricities.
+
+    usebounds : bool, optional
+        If `True`, use extrema bounding (see Notes) when computing the radius
+        for undirected graphs. Extrema bounding may accelerate the
+        distance calculation for some graphs. `usebounds` is ignored if `G` is
+        directed or if `e` is not `None`. Default is `False`.
+
+    weight : string, function, or None
+        If this is a string, then edge weights will be accessed via the
+        edge attribute with this key (that is, the weight of the edge
+        joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
+        such edge attribute exists, the weight of the edge is assumed to
+        be one.
+
+        If this is a function, the weight of an edge is the value
+        returned by the function. The function must accept exactly three
+        positional arguments: the two endpoints of an edge and the
+        dictionary of edge attributes for that edge. The function must
+        return a number.
+
+        If this is None, every edge has weight/distance/cost 1.
+
+        Weights stored as floating point values can lead to small round-off
+        errors in distances. Use integer weights to avoid this.
+
+        Weights should be positive, since they are distances.
+
+    Returns
+    -------
+    r : integer
+       Radius of graph
+
+    Notes
+    -----
+    When ``usebounds=True``, the computation makes use of smart lower
+    and upper bounds and is often linear in the number of nodes, rather than
+    quadratic (except for some border cases such as complete graphs or circle
+    shaped-graphs).
+
+    Examples
+    --------
+    >>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
+    >>> nx.radius(G)
+    2
+
+    """
+    if usebounds is True and e is None and not G.is_directed():
+        return _extrema_bounding(G, compute="radius", weight=weight)
+    if e is None:
+        e = eccentricity(G, weight=weight)
+    return min(e.values())
+
+
+@nx._dispatchable(edge_attrs="weight")
+def center(G, e=None, usebounds=False, weight=None):
+    """Returns the center of the graph G.
+
+    The center is the set of nodes with eccentricity equal to radius.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+       A graph
+
+    e : eccentricity dictionary, optional
+      A precomputed dictionary of eccentricities.
+
+    usebounds : bool, optional
+        If `True`, use extrema bounding (see Notes) when computing the center
+        for undirected graphs. Extrema bounding may accelerate the
+        distance calculation for some graphs. `usebounds` is ignored if `G` is
+        directed or if `e` is not `None`. Default is `False`.
+
+    weight : string, function, or None
+        If this is a string, then edge weights will be accessed via the
+        edge attribute with this key (that is, the weight of the edge
+        joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
+        such edge attribute exists, the weight of the edge is assumed to
+        be one.
+
+        If this is a function, the weight of an edge is the value
+        returned by the function. The function must accept exactly three
+        positional arguments: the two endpoints of an edge and the
+        dictionary of edge attributes for that edge. The function must
+        return a number.
+
+        If this is None, every edge has weight/distance/cost 1.
+
+        Weights stored as floating point values can lead to small round-off
+        errors in distances. Use integer weights to avoid this.
+
+        Weights should be positive, since they are distances.
+
+    Returns
+    -------
+    c : list
+       List of nodes in center
+
+    Notes
+    -----
+    When ``usebounds=True``, the computation makes use of smart lower
+    and upper bounds and is often linear in the number of nodes, rather than
+    quadratic (except for some border cases such as complete graphs or circle
+    shaped-graphs).
+
+    Examples
+    --------
+    >>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
+    >>> list(nx.center(G))
+    [1, 3, 4]
+
+    See Also
+    --------
+    :func:`~networkx.algorithms.tree.distance_measures.center` : tree center
+    barycenter
+    periphery
+    :func:`~networkx.algorithms.tree.distance_measures.centroid` : tree centroid
+    """
+    if usebounds is True and e is None and not G.is_directed():
+        return _extrema_bounding(G, compute="center", weight=weight)
+    if e is None and weight is None and not G.is_directed() and nx.is_tree(G):
+        return nx.tree.center(G)
+    if e is None:
+        e = eccentricity(G, weight=weight)
+    radius = min(e.values())
+    p = [v for v in e if e[v] == radius]
+    return p
+
+
+@nx._dispatchable(edge_attrs="weight", mutates_input={"attr": 2})
+def barycenter(G, weight=None, attr=None, sp=None):
+    r"""Calculate barycenter of a connected graph, optionally with edge weights.
+
+    The :dfn:`barycenter` a
+    :func:`connected ` graph
+    :math:`G` is the subgraph induced by the set of its nodes :math:`v`
+    minimizing the objective function
+
+    .. math::
+
+        \sum_{u \in V(G)} d_G(u, v),
+
+    where :math:`d_G` is the (possibly weighted) :func:`path length
+    `.
+    The barycenter is also called the :dfn:`median`. See [West01]_, p. 78.
+
+    Parameters
+    ----------
+    G : :class:`networkx.Graph`
+        The connected graph :math:`G`.
+    weight : :class:`str`, optional
+        Passed through to
+        :func:`~networkx.algorithms.shortest_paths.generic.shortest_path_length`.
+    attr : :class:`str`, optional
+        If given, write the value of the objective function to each node's
+        `attr` attribute. Otherwise do not store the value.
+    sp : dict of dicts, optional
+       All pairs shortest path lengths as a dictionary of dictionaries
+
+    Returns
+    -------
+    list
+        Nodes of `G` that induce the barycenter of `G`.
+
+    Raises
+    ------
+    NetworkXNoPath
+        If `G` is disconnected. `G` may appear disconnected to
+        :func:`barycenter` if `sp` is given but is missing shortest path
+        lengths for any pairs.
+    ValueError
+        If `sp` and `weight` are both given.
+
+    Examples
+    --------
+    >>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
+    >>> nx.barycenter(G)
+    [1, 3, 4]
+
+    See Also
+    --------
+    center
+    periphery
+    :func:`~networkx.algorithms.tree.distance_measures.centroid` : tree centroid
+    """
+    if weight is None and attr is None and sp is None:
+        if not G.is_directed() and nx.is_tree(G):
+            return nx.tree.centroid(G)
+
+    if sp is None:
+        sp = nx.shortest_path_length(G, weight=weight)
+    else:
+        sp = sp.items()
+        if weight is not None:
+            raise ValueError("Cannot use both sp, weight arguments together")
+    smallest, barycenter_vertices, n = float("inf"), [], len(G)
+    for v, dists in sp:
+        if len(dists) < n:
+            raise nx.NetworkXNoPath(
+                f"Input graph {G} is disconnected, so every induced subgraph "
+                "has infinite barycentricity."
+            )
+        barycentricity = sum(dists.values())
+        if attr is not None:
+            G.nodes[v][attr] = barycentricity
+        if barycentricity < smallest:
+            smallest = barycentricity
+            barycenter_vertices = [v]
+        elif barycentricity == smallest:
+            barycenter_vertices.append(v)
+    if attr is not None:
+        nx._clear_cache(G)
+    return barycenter_vertices
+
+
+@not_implemented_for("directed")
+@nx._dispatchable(edge_attrs="weight")
+def resistance_distance(G, nodeA=None, nodeB=None, weight=None, invert_weight=True):
+    """Returns the resistance distance between pairs of nodes in graph G.
+
+    The resistance distance between two nodes of a graph is akin to treating
+    the graph as a grid of resistors with a resistance equal to the provided
+    weight [1]_, [2]_.
+
+    If weight is not provided, then a weight of 1 is used for all edges.
+
+    If two nodes are the same, the resistance distance is zero.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+       A graph
+
+    nodeA : node or None, optional (default=None)
+      A node within graph G.
+      If None, compute resistance distance using all nodes as source nodes.
+
+    nodeB : node or None, optional (default=None)
+      A node within graph G.
+      If None, compute resistance distance using all nodes as target nodes.
+
+    weight : string or None, optional (default=None)
+       The edge data key used to compute the resistance distance.
+       If None, then each edge has weight 1.
+
+    invert_weight : boolean (default=True)
+        Proper calculation of resistance distance requires building the
+        Laplacian matrix with the reciprocal of the weight. Not required
+        if the weight is already inverted. Weight cannot be zero.
+
+    Returns
+    -------
+    rd : dict or float
+       If `nodeA` and `nodeB` are given, resistance distance between `nodeA`
+       and `nodeB`. If `nodeA` or `nodeB` is unspecified (the default), a
+       dictionary of nodes with resistance distances as the value.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is a directed graph.
+
+    NetworkXError
+        If `G` is not connected, or contains no nodes,
+        or `nodeA` is not in `G` or `nodeB` is not in `G`.
+
+    Examples
+    --------
+    >>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
+    >>> round(nx.resistance_distance(G, 1, 3), 10)
+    0.625
+
+    Notes
+    -----
+    The implementation is based on Theorem A in [2]_. Self-loops are ignored.
+    Multi-edges are contracted in one edge with weight equal to the harmonic sum of the weights.
+
+    References
+    ----------
+    .. [1] Wikipedia
+       "Resistance distance."
+       https://en.wikipedia.org/wiki/Resistance_distance
+    .. [2] D. J. Klein and M. Randic.
+        Resistance distance.
+        J. of Math. Chem. 12:81-95, 1993.
+    """
+    import numpy as np
+
+    if len(G) == 0:
+        raise nx.NetworkXError("Graph G must contain at least one node.")
+    if not nx.is_connected(G):
+        raise nx.NetworkXError("Graph G must be strongly connected.")
+    if nodeA is not None and nodeA not in G:
+        raise nx.NetworkXError("Node A is not in graph G.")
+    if nodeB is not None and nodeB not in G:
+        raise nx.NetworkXError("Node B is not in graph G.")
+
+    G = G.copy()
+    node_list = list(G)
+
+    # Invert weights
+    if invert_weight and weight is not None:
+        if G.is_multigraph():
+            for u, v, k, d in G.edges(keys=True, data=True):
+                d[weight] = 1 / d[weight]
+        else:
+            for u, v, d in G.edges(data=True):
+                d[weight] = 1 / d[weight]
+
+    # Compute resistance distance using the Pseudo-inverse of the Laplacian
+    # Self-loops are ignored
+    L = nx.laplacian_matrix(G, weight=weight).todense()
+    Linv = np.linalg.pinv(L, hermitian=True)
+
+    # Return relevant distances
+    if nodeA is not None and nodeB is not None:
+        i = node_list.index(nodeA)
+        j = node_list.index(nodeB)
+        return Linv.item(i, i) + Linv.item(j, j) - Linv.item(i, j) - Linv.item(j, i)
+
+    elif nodeA is not None:
+        i = node_list.index(nodeA)
+        d = {}
+        for n in G:
+            j = node_list.index(n)
+            d[n] = Linv.item(i, i) + Linv.item(j, j) - Linv.item(i, j) - Linv.item(j, i)
+        return d
+
+    elif nodeB is not None:
+        j = node_list.index(nodeB)
+        d = {}
+        for n in G:
+            i = node_list.index(n)
+            d[n] = Linv.item(i, i) + Linv.item(j, j) - Linv.item(i, j) - Linv.item(j, i)
+        return d
+
+    else:
+        d = {}
+        for n in G:
+            i = node_list.index(n)
+            d[n] = {}
+            for n2 in G:
+                j = node_list.index(n2)
+                d[n][n2] = (
+                    Linv.item(i, i)
+                    + Linv.item(j, j)
+                    - Linv.item(i, j)
+                    - Linv.item(j, i)
+                )
+        return d
+
+
+@not_implemented_for("directed")
+@nx._dispatchable(edge_attrs="weight")
+def effective_graph_resistance(G, weight=None, invert_weight=True):
+    """Returns the Effective graph resistance of G.
+
+    Also known as the Kirchhoff index.
+
+    The effective graph resistance is defined as the sum
+    of the resistance distance of every node pair in G [1]_.
+
+    If weight is not provided, then a weight of 1 is used for all edges.
+
+    The effective graph resistance of a disconnected graph is infinite.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+       A graph
+
+    weight : string or None, optional (default=None)
+       The edge data key used to compute the effective graph resistance.
+       If None, then each edge has weight 1.
+
+    invert_weight : boolean (default=True)
+        Proper calculation of resistance distance requires building the
+        Laplacian matrix with the reciprocal of the weight. Not required
+        if the weight is already inverted. Weight cannot be zero.
+
+    Returns
+    -------
+    RG : float
+        The effective graph resistance of `G`.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is a directed graph.
+
+    NetworkXError
+        If `G` does not contain any nodes.
+
+    Examples
+    --------
+    >>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
+    >>> round(nx.effective_graph_resistance(G), 10)
+    10.25
+
+    Notes
+    -----
+    The implementation is based on Theorem 2.2 in [2]_. Self-loops are ignored.
+    Multi-edges are contracted in one edge with weight equal to the harmonic sum of the weights.
+
+    References
+    ----------
+    .. [1] Wolfram
+       "Kirchhoff Index."
+       https://mathworld.wolfram.com/KirchhoffIndex.html
+    .. [2] W. Ellens, F. M. Spieksma, P. Van Mieghem, A. Jamakovic, R. E. Kooij.
+        Effective graph resistance.
+        Lin. Alg. Appl. 435:2491-2506, 2011.
+    """
+    import numpy as np
+
+    if len(G) == 0:
+        raise nx.NetworkXError("Graph G must contain at least one node.")
+
+    # Disconnected graphs have infinite Effective graph resistance
+    if not nx.is_connected(G):
+        return float("inf")
+
+    # Invert weights
+    G = G.copy()
+    if invert_weight and weight is not None:
+        if G.is_multigraph():
+            for u, v, k, d in G.edges(keys=True, data=True):
+                d[weight] = 1 / d[weight]
+        else:
+            for u, v, d in G.edges(data=True):
+                d[weight] = 1 / d[weight]
+
+    # Get Laplacian eigenvalues
+    mu = np.sort(nx.laplacian_spectrum(G, weight=weight))
+
+    # Compute Effective graph resistance based on spectrum of the Laplacian
+    # Self-loops are ignored
+    return float(np.sum(1 / mu[1:]) * G.number_of_nodes())
+
+
+@nx.utils.not_implemented_for("directed")
+@nx._dispatchable(edge_attrs="weight")
+def kemeny_constant(G, *, weight=None):
+    """Returns the Kemeny constant of the given graph.
+
+    The *Kemeny constant* (or Kemeny's constant) of a graph `G`
+    can be computed by regarding the graph as a Markov chain.
+    The Kemeny constant is then the expected number of time steps
+    to transition from a starting state i to a random destination state
+    sampled from the Markov chain's stationary distribution.
+    The Kemeny constant is independent of the chosen initial state [1]_.
+
+    The Kemeny constant measures the time needed for spreading
+    across a graph. Low values indicate a closely connected graph
+    whereas high values indicate a spread-out graph.
+
+    If weight is not provided, then a weight of 1 is used for all edges.
+
+    Since `G` represents a Markov chain, the weights must be positive.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    weight : string or None, optional (default=None)
+       The edge data key used to compute the Kemeny constant.
+       If None, then each edge has weight 1.
+
+    Returns
+    -------
+    float
+        The Kemeny constant of the graph `G`.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If the graph `G` is directed.
+
+    NetworkXError
+        If the graph `G` is not connected, or contains no nodes,
+        or has edges with negative weights.
+
+    Examples
+    --------
+    >>> G = nx.complete_graph(5)
+    >>> round(nx.kemeny_constant(G), 10)
+    3.2
+
+    Notes
+    -----
+    The implementation is based on equation (3.3) in [2]_.
+    Self-loops are allowed and indicate a Markov chain where
+    the state can remain the same. Multi-edges are contracted
+    in one edge with weight equal to the sum of the weights.
+
+    References
+    ----------
+    .. [1] Wikipedia
+       "Kemeny's constant."
+       https://en.wikipedia.org/wiki/Kemeny%27s_constant
+    .. [2] Lovász L.
+        Random walks on graphs: A survey.
+        Paul Erdös is Eighty, vol. 2, Bolyai Society,
+        Mathematical Studies, Keszthely, Hungary (1993), pp. 1-46
+    """
+    import numpy as np
+    import scipy as sp
+
+    if len(G) == 0:
+        raise nx.NetworkXError("Graph G must contain at least one node.")
+    if not nx.is_connected(G):
+        raise nx.NetworkXError("Graph G must be connected.")
+    if nx.is_negatively_weighted(G, weight=weight):
+        raise nx.NetworkXError("The weights of graph G must be nonnegative.")
+
+    # Compute matrix H = D^-1/2 A D^-1/2
+    A = nx.adjacency_matrix(G, weight=weight)
+    n, m = A.shape
+    diags = A.sum(axis=1)
+    with np.errstate(divide="ignore"):
+        diags_sqrt = 1.0 / np.sqrt(diags)
+    diags_sqrt[np.isinf(diags_sqrt)] = 0
+    DH = sp.sparse.dia_array((diags_sqrt, 0), shape=(m, n)).tocsr()
+    H = DH @ (A @ DH)
+
+    # Compute eigenvalues of H
+    eig = np.sort(sp.linalg.eigvalsh(H.todense()))
+
+    # Compute the Kemeny constant
+    return float(np.sum(1 / (1 - eig[:-1])))
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/distance_regular.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/distance_regular.py
new file mode 100644
index 0000000000000000000000000000000000000000..e97b0f843b91220f183f3df4554d5bb25619cfc5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/distance_regular.py
@@ -0,0 +1,272 @@
+"""
+=======================
+Distance-regular graphs
+=======================
+"""
+
+from collections import defaultdict
+from itertools import combinations_with_replacement
+from math import log
+
+import networkx as nx
+from networkx.utils import not_implemented_for
+
+from .distance_measures import diameter
+
+__all__ = [
+    "is_distance_regular",
+    "is_strongly_regular",
+    "intersection_array",
+    "global_parameters",
+]
+
+
+@nx._dispatchable
+def is_distance_regular(G):
+    """Returns True if the graph is distance regular, False otherwise.
+
+    A connected graph G is distance-regular if for any nodes x,y
+    and any integers i,j=0,1,...,d (where d is the graph
+    diameter), the number of vertices at distance i from x and
+    distance j from y depends only on i,j and the graph distance
+    between x and y, independently of the choice of x and y.
+
+    Parameters
+    ----------
+    G: Networkx graph (undirected)
+
+    Returns
+    -------
+    bool
+      True if the graph is Distance Regular, False otherwise
+
+    Examples
+    --------
+    >>> G = nx.hypercube_graph(6)
+    >>> nx.is_distance_regular(G)
+    True
+
+    See Also
+    --------
+    intersection_array, global_parameters
+
+    Notes
+    -----
+    For undirected and simple graphs only
+
+    References
+    ----------
+    .. [1] Brouwer, A. E.; Cohen, A. M.; and Neumaier, A.
+        Distance-Regular Graphs. New York: Springer-Verlag, 1989.
+    .. [2] Weisstein, Eric W. "Distance-Regular Graph."
+        http://mathworld.wolfram.com/Distance-RegularGraph.html
+
+    """
+    try:
+        intersection_array(G)
+        return True
+    except nx.NetworkXError:
+        return False
+
+
+def global_parameters(b, c):
+    """Returns global parameters for a given intersection array.
+
+    Given a distance-regular graph G with diameter d and integers b_i,
+    c_i,i = 0,....,d such that for any 2 vertices x,y in G at a distance
+    i=d(x,y), there are exactly c_i neighbors of y at a distance of i-1 from x
+    and b_i neighbors of y at a distance of i+1 from x.
+
+    Thus, a distance regular graph has the global parameters,
+    [[c_0,a_0,b_0],[c_1,a_1,b_1],......,[c_d,a_d,b_d]] for the
+    intersection array  [b_0,b_1,.....b_{d-1};c_1,c_2,.....c_d]
+    where a_i+b_i+c_i=k , k= degree of every vertex.
+
+    Parameters
+    ----------
+    b : list
+
+    c : list
+
+    Returns
+    -------
+    iterable
+       An iterable over three tuples.
+
+    Examples
+    --------
+    >>> G = nx.dodecahedral_graph()
+    >>> b, c = nx.intersection_array(G)
+    >>> list(nx.global_parameters(b, c))
+    [(0, 0, 3), (1, 0, 2), (1, 1, 1), (1, 1, 1), (2, 0, 1), (3, 0, 0)]
+
+    References
+    ----------
+    .. [1] Weisstein, Eric W. "Global Parameters."
+       From MathWorld--A Wolfram Web Resource.
+       http://mathworld.wolfram.com/GlobalParameters.html
+
+    See Also
+    --------
+    intersection_array
+    """
+    return ((y, b[0] - x - y, x) for x, y in zip(b + [0], [0] + c))
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable
+def intersection_array(G):
+    """Returns the intersection array of a distance-regular graph.
+
+    Given a distance-regular graph G with integers b_i, c_i,i = 0,....,d
+    such that for any 2 vertices x,y in G at a distance i=d(x,y), there
+    are exactly c_i neighbors of y at a distance of i-1 from x and b_i
+    neighbors of y at a distance of i+1 from x.
+
+    A distance regular graph's intersection array is given by,
+    [b_0,b_1,.....b_{d-1};c_1,c_2,.....c_d]
+
+    Parameters
+    ----------
+    G: Networkx graph (undirected)
+
+    Returns
+    -------
+    b,c: tuple of lists
+
+    Examples
+    --------
+    >>> G = nx.icosahedral_graph()
+    >>> nx.intersection_array(G)
+    ([5, 2, 1], [1, 2, 5])
+
+    References
+    ----------
+    .. [1] Weisstein, Eric W. "Intersection Array."
+       From MathWorld--A Wolfram Web Resource.
+       http://mathworld.wolfram.com/IntersectionArray.html
+
+    See Also
+    --------
+    global_parameters
+    """
+    # the input graph is very unlikely to be distance-regular: here are the
+    # number a(n) of connected simple graphs, and the number b(n) of
+    # distance-regular graphs among them:
+    #
+    #    n  | 1 2 3 4  5   6   7     8      9       10
+    #  -----+------------------------------------------------------------------
+    #  a(n) | 1 1 2 6 21 112 853 11117 261080 11716571 https://oeis.org/A001349
+    #  b(n) | 1 1 1 2  2   4   2     5      4        7 https://oeis.org/A241814
+    #
+    # in light of this, let's compute shortest path lengths as we go instead of
+    # precomputing them all
+    # test for regular graph (all degrees must be equal)
+    if not nx.is_regular(G) or not nx.is_connected(G):
+        raise nx.NetworkXError("Graph is not distance regular.")
+
+    path_length = defaultdict(dict)
+    bint = {}  # 'b' intersection array
+    cint = {}  # 'c' intersection array
+
+    # see https://doi.org/10.1016/j.ejc.2004.07.004, Theorem 1.5, page 81:
+    # the diameter of a distance-regular graph is at most (8 log_2 n) / 3,
+    # so let's compute it as we go in the hope that we can stop early
+    diam = 0
+    max_diameter_for_dr_graphs = (8 * log(len(G), 2)) / 3
+    for u, v in combinations_with_replacement(G, 2):
+        # compute needed shortest path lengths
+        pl_u = path_length[u]
+        if v not in pl_u:
+            pl_u.update(nx.single_source_shortest_path_length(G, u))
+            for x, distance in pl_u.items():
+                path_length[x][u] = distance
+
+        i = path_length[u][v]
+        diam = max(diam, i)
+
+        # diameter too large: graph can't be distance-regular
+        if diam > max_diameter_for_dr_graphs:
+            raise nx.NetworkXError("Graph is not distance regular.")
+
+        vnbrs = G[v]
+        # compute needed path lengths
+        for n in vnbrs:
+            pl_n = path_length[n]
+            if u not in pl_n:
+                pl_n.update(nx.single_source_shortest_path_length(G, n))
+                for x, distance in pl_n.items():
+                    path_length[x][n] = distance
+
+        # number of neighbors of v at a distance of i-1 from u
+        c = sum(1 for n in vnbrs if pl_u[n] == i - 1)
+        # number of neighbors of v at a distance of i+1 from u
+        b = sum(1 for n in vnbrs if pl_u[n] == i + 1)
+        # b, c are independent of u and v
+        if cint.get(i, c) != c or bint.get(i, b) != b:
+            raise nx.NetworkXError("Graph is not distance regular")
+        bint[i] = b
+        cint[i] = c
+
+    return (
+        [bint.get(j, 0) for j in range(diam)],
+        [cint.get(j + 1, 0) for j in range(diam)],
+    )
+
+
+# TODO There is a definition for directed strongly regular graphs.
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable
+def is_strongly_regular(G):
+    """Returns True if and only if the given graph is strongly
+    regular.
+
+    An undirected graph is *strongly regular* if
+
+    * it is regular,
+    * each pair of adjacent vertices has the same number of neighbors in
+      common,
+    * each pair of nonadjacent vertices has the same number of neighbors
+      in common.
+
+    Each strongly regular graph is a distance-regular graph.
+    Conversely, if a distance-regular graph has diameter two, then it is
+    a strongly regular graph. For more information on distance-regular
+    graphs, see :func:`is_distance_regular`.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        An undirected graph.
+
+    Returns
+    -------
+    bool
+        Whether `G` is strongly regular.
+
+    Examples
+    --------
+
+    The cycle graph on five vertices is strongly regular. It is
+    two-regular, each pair of adjacent vertices has no shared neighbors,
+    and each pair of nonadjacent vertices has one shared neighbor::
+
+        >>> G = nx.cycle_graph(5)
+        >>> nx.is_strongly_regular(G)
+        True
+
+    """
+    # Here is an alternate implementation based directly on the
+    # definition of strongly regular graphs:
+    #
+    #     return (all_equal(G.degree().values())
+    #             and all_equal(len(common_neighbors(G, u, v))
+    #                           for u, v in G.edges())
+    #             and all_equal(len(common_neighbors(G, u, v))
+    #                           for u, v in non_edges(G)))
+    #
+    # We instead use the fact that a distance-regular graph of diameter
+    # two is strongly regular.
+    return is_distance_regular(G) and diameter(G) == 2
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/dominance.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/dominance.py
new file mode 100644
index 0000000000000000000000000000000000000000..6429498ad5a22c8423cf3f62a17d0f429c2d286a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/dominance.py
@@ -0,0 +1,142 @@
+"""
+Dominance algorithms.
+"""
+
+from functools import reduce
+
+import networkx as nx
+from networkx.utils import not_implemented_for
+
+__all__ = ["immediate_dominators", "dominance_frontiers"]
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable
+def immediate_dominators(G, start):
+    """Returns the immediate dominators of all nodes of a directed graph.
+
+    Parameters
+    ----------
+    G : a DiGraph or MultiDiGraph
+        The graph where dominance is to be computed.
+
+    start : node
+        The start node of dominance computation.
+
+    Returns
+    -------
+    idom : dict keyed by nodes
+        A dict containing the immediate dominators of each node reachable from
+        `start`, except for `start` itself.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is undirected.
+
+    NetworkXError
+        If `start` is not in `G`.
+
+    Notes
+    -----
+    The immediate dominators are the parents of their corresponding nodes in
+    the dominator tree. Every node reachable from `start` has an immediate
+    dominator, except for `start` itself.
+
+    Examples
+    --------
+    >>> G = nx.DiGraph([(1, 2), (1, 3), (2, 5), (3, 4), (4, 5)])
+    >>> sorted(nx.immediate_dominators(G, 1).items())
+    [(2, 1), (3, 1), (4, 3), (5, 1)]
+
+    References
+    ----------
+    .. [1] Cooper, Keith D., Harvey, Timothy J. and Kennedy, Ken.
+           "A simple, fast dominance algorithm." (2006).
+           https://hdl.handle.net/1911/96345
+    .. [2] Lengauer, Thomas; Tarjan, Robert Endre (July 1979).
+           "A fast algorithm for finding dominators in a flowgraph".
+           ACM Transactions on Programming Languages and Systems. 1 (1): 121--141.
+           https://dl.acm.org/doi/10.1145/357062.357071
+    """
+    if start not in G:
+        raise nx.NetworkXError("start is not in G")
+
+    idom = {start: None}
+
+    order = list(nx.dfs_postorder_nodes(G, start))
+    dfn = {u: i for i, u in enumerate(order)}
+    order.pop()
+    order.reverse()
+
+    def intersect(u, v):
+        while u != v:
+            while dfn[u] < dfn[v]:
+                u = idom[u]
+            while dfn[u] > dfn[v]:
+                v = idom[v]
+        return u
+
+    changed = True
+    while changed:
+        changed = False
+        for u in order:
+            new_idom = reduce(intersect, (v for v in G.pred[u] if v in idom))
+            if u not in idom or idom[u] != new_idom:
+                idom[u] = new_idom
+                changed = True
+
+    del idom[start]
+    return idom
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable
+def dominance_frontiers(G, start):
+    """Returns the dominance frontiers of all nodes of a directed graph.
+
+    Parameters
+    ----------
+    G : a DiGraph or MultiDiGraph
+        The graph where dominance is to be computed.
+
+    start : node
+        The start node of dominance computation.
+
+    Returns
+    -------
+    df : dict keyed by nodes
+        A dict containing the dominance frontiers of each node reachable from
+        `start` as lists.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is undirected.
+
+    NetworkXError
+        If `start` is not in `G`.
+
+    Examples
+    --------
+    >>> G = nx.DiGraph([(1, 2), (1, 3), (2, 5), (3, 4), (4, 5)])
+    >>> sorted((u, sorted(df)) for u, df in nx.dominance_frontiers(G, 1).items())
+    [(1, []), (2, [5]), (3, [5]), (4, [5]), (5, [])]
+
+    References
+    ----------
+    .. [1] Cooper, Keith D., Harvey, Timothy J. and Kennedy, Ken.
+           "A simple, fast dominance algorithm." (2006).
+           https://hdl.handle.net/1911/96345
+    """
+    idom = nx.immediate_dominators(G, start) | {start: None}
+
+    df = {u: set() for u in idom}
+    for u in idom:
+        if u == start or len(G.pred[u]) >= 2:
+            for v in G.pred[u]:
+                if v in idom:
+                    while v != idom[u]:
+                        df[v].add(u)
+                        v = idom[v]
+    return df
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/dominating.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/dominating.py
new file mode 100644
index 0000000000000000000000000000000000000000..41c102a5bc10805a67e8bf26a8348b19abf7fea2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/dominating.py
@@ -0,0 +1,268 @@
+"""Functions for computing dominating sets in a graph."""
+
+import math
+from heapq import heappop, heappush
+from itertools import chain, count
+
+import networkx as nx
+
+__all__ = [
+    "dominating_set",
+    "is_dominating_set",
+    "connected_dominating_set",
+    "is_connected_dominating_set",
+]
+
+
+@nx._dispatchable
+def dominating_set(G, start_with=None):
+    r"""Finds a dominating set for the graph G.
+
+    A *dominating set* for a graph with node set *V* is a subset *D* of
+    *V* such that every node not in *D* is adjacent to at least one
+    member of *D* [1]_.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    start_with : node (default=None)
+        Node to use as a starting point for the algorithm.
+
+    Returns
+    -------
+    D : set
+        A dominating set for G.
+
+    Notes
+    -----
+    This function is an implementation of algorithm 7 in [2]_ which
+    finds some dominating set, not necessarily the smallest one.
+
+    See also
+    --------
+    is_dominating_set
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Dominating_set
+
+    .. [2] Abdol-Hossein Esfahanian. Connectivity Algorithms.
+        http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
+
+    """
+    all_nodes = set(G)
+    if start_with is None:
+        start_with = nx.utils.arbitrary_element(all_nodes)
+    if start_with not in G:
+        raise nx.NetworkXError(f"node {start_with} is not in G")
+    dominating_set = {start_with}
+    dominated_nodes = set(G[start_with])
+    remaining_nodes = all_nodes - dominated_nodes - dominating_set
+    while remaining_nodes:
+        # Choose an arbitrary node and determine its undominated neighbors.
+        v = remaining_nodes.pop()
+        undominated_nbrs = set(G[v]) - dominating_set
+        # Add the node to the dominating set and the neighbors to the
+        # dominated set. Finally, remove all of those nodes from the set
+        # of remaining nodes.
+        dominating_set.add(v)
+        dominated_nodes |= undominated_nbrs
+        remaining_nodes -= undominated_nbrs
+    return dominating_set
+
+
+@nx._dispatchable
+def is_dominating_set(G, nbunch):
+    """Checks if `nbunch` is a dominating set for `G`.
+
+    A *dominating set* for a graph with node set *V* is a subset *D* of
+    *V* such that every node not in *D* is adjacent to at least one
+    member of *D* [1]_.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    nbunch : iterable
+        An iterable of nodes in the graph `G`.
+
+    Returns
+    -------
+    dominating : bool
+        True if `nbunch` is a dominating set of `G`, false otherwise.
+
+    See also
+    --------
+    dominating_set
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Dominating_set
+
+    """
+    testset = {n for n in nbunch if n in G}
+    nbrs = set(chain.from_iterable(G[n] for n in testset))
+    return len(set(G) - testset - nbrs) == 0
+
+
+@nx.utils.not_implemented_for("directed")
+@nx._dispatchable
+def connected_dominating_set(G):
+    """Returns a connected dominating set.
+
+    A *dominating set* for a graph *G* with node set *V* is a subset *D* of *V*
+    such that every node not in *D* is adjacent to at least one member of *D*
+    [1]_. A *connected dominating set* is a dominating set *C* that induces a
+    connected subgraph of *G* [2]_.
+    Note that connected dominating sets are not unique in general and that there
+    may be other connected dominating sets.
+
+    Parameters
+    ----------
+    G : NewtorkX graph
+        Undirected connected graph.
+
+    Returns
+    -------
+    connected_dominating_set : set
+        A dominating set of nodes which induces a connected subgraph of G.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If G is directed.
+
+    NetworkXError
+        If G is disconnected.
+
+    Examples
+    ________
+    >>> G = nx.Graph(
+    ...     [
+    ...         (1, 2),
+    ...         (1, 3),
+    ...         (1, 4),
+    ...         (1, 5),
+    ...         (1, 6),
+    ...         (2, 7),
+    ...         (3, 8),
+    ...         (4, 9),
+    ...         (5, 10),
+    ...         (6, 11),
+    ...         (7, 12),
+    ...         (8, 12),
+    ...         (9, 12),
+    ...         (10, 12),
+    ...         (11, 12),
+    ...     ]
+    ... )
+    >>> nx.connected_dominating_set(G)
+    {1, 2, 3, 4, 5, 6, 7}
+
+    Notes
+    -----
+    This function implements Algorithm I in its basic version as described
+    in [3]_. The idea behind the algorithm is the following: grow a tree *T*,
+    starting from a node with maximum degree. Throughout the growing process,
+    nonleaf nodes in *T* are our connected dominating set (CDS), leaf nodes in
+    *T* are marked as "seen" and nodes in G that are not yet in *T* are marked as
+    "unseen". We maintain a max-heap of all "seen" nodes, and track the number
+    of "unseen" neighbors for each node. At each step we pop the heap top -- a
+    "seen" (leaf) node with maximal number of "unseen" neighbors, add it to the
+    CDS and mark all its "unseen" neighbors as "seen". For each one of the newly
+    created "seen" nodes, we also decrement the number of "unseen" neighbors for
+    all its neighbors. The algorithm terminates when there are no more "unseen"
+    nodes.
+    Runtime complexity of this implementation is $O(|E|*log|V|)$ (amortized).
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Dominating_set
+    .. [2] https://en.wikipedia.org/wiki/Connected_dominating_set
+    .. [3] Guha, S. and Khuller, S.
+           *Approximation Algorithms for Connected Dominating Sets*,
+           Algorithmica, 20, 374-387, 1998.
+
+    """
+    if len(G) == 0:
+        return set()
+
+    if not nx.is_connected(G):
+        raise nx.NetworkXError("G must be a connected graph")
+
+    if len(G) == 1:
+        return set(G)
+
+    G_succ = G._adj  # For speed-up
+
+    # Use the count c to avoid comparing nodes
+    c = count()
+
+    # Keep track of the number of unseen nodes adjacent to each node
+    unseen_degree = dict(G.degree)
+
+    # Find node with highest degree and update its neighbors
+    (max_deg_node, max_deg) = max(unseen_degree.items(), key=lambda x: x[1])
+    for nbr in G_succ[max_deg_node]:
+        unseen_degree[nbr] -= 1
+
+    # Initially all nodes except max_deg_node are unseen
+    unseen = set(G) - {max_deg_node}
+
+    # We want a max-heap of the unseen-degree using heapq, which is a min-heap
+    # So we store the negative of the unseen-degree
+    seen = [(-max_deg, next(c), max_deg_node)]
+
+    connected_dominating_set = set()
+
+    # Main loop
+    while unseen:
+        (neg_deg, cnt, u) = heappop(seen)
+        # Check if u's unseen-degree changed while in the heap
+        if -neg_deg > unseen_degree[u]:
+            heappush(seen, (-unseen_degree[u], cnt, u))
+            continue
+        # Mark all u's unseen neighbors as seen and add them to the heap
+        for v in G_succ[u]:
+            if v in unseen:
+                unseen.remove(v)
+                for nbr in G_succ[v]:
+                    unseen_degree[nbr] -= 1
+                heappush(seen, (-unseen_degree[v], next(c), v))
+        # Add u to the dominating set
+        connected_dominating_set.add(u)
+
+    return connected_dominating_set
+
+
+@nx.utils.not_implemented_for("directed")
+@nx._dispatchable
+def is_connected_dominating_set(G, nbunch):
+    """Checks if `nbunch` is a connected dominating set for `G`.
+
+    A *dominating set* for a graph *G* with node set *V* is a subset *D* of
+    *V* such that every node not in *D* is adjacent to at least one
+    member of *D* [1]_. A *connected dominating set* is a dominating
+    set *C* that induces a connected subgraph of *G* [2]_.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        Undirected graph.
+
+    nbunch : iterable
+        An iterable of nodes in the graph `G`.
+
+    Returns
+    -------
+    connected_dominating : bool
+        True if `nbunch` is connected dominating set of `G`, false otherwise.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Dominating_set
+    .. [2] https://en.wikipedia.org/wiki/Connected_dominating_set
+
+    """
+    return nx.is_dominating_set(G, nbunch) and nx.is_connected(nx.subgraph(G, nbunch))
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/efficiency_measures.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/efficiency_measures.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8e9d7a9e680e7db5d61b87e067c03a6d603c3af
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/efficiency_measures.py
@@ -0,0 +1,167 @@
+"""Provides functions for computing the efficiency of nodes and graphs."""
+
+import networkx as nx
+from networkx.exception import NetworkXNoPath
+
+from ..utils import not_implemented_for
+
+__all__ = ["efficiency", "local_efficiency", "global_efficiency"]
+
+
+@not_implemented_for("directed")
+@nx._dispatchable
+def efficiency(G, u, v):
+    """Returns the efficiency of a pair of nodes in a graph.
+
+    The *efficiency* of a pair of nodes is the multiplicative inverse of the
+    shortest path distance between the nodes [1]_. Returns 0 if no path
+    between nodes.
+
+    Parameters
+    ----------
+    G : :class:`networkx.Graph`
+        An undirected graph for which to compute the average local efficiency.
+    u, v : node
+        Nodes in the graph ``G``.
+
+    Returns
+    -------
+    float
+        Multiplicative inverse of the shortest path distance between the nodes.
+
+    Examples
+    --------
+    >>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
+    >>> nx.efficiency(G, 2, 3)  # this gives efficiency for node 2 and 3
+    0.5
+
+    Notes
+    -----
+    Edge weights are ignored when computing the shortest path distances.
+
+    See also
+    --------
+    local_efficiency
+    global_efficiency
+
+    References
+    ----------
+    .. [1] Latora, Vito, and Massimo Marchiori.
+           "Efficient behavior of small-world networks."
+           *Physical Review Letters* 87.19 (2001): 198701.
+           
+
+    """
+    try:
+        eff = 1 / nx.shortest_path_length(G, u, v)
+    except NetworkXNoPath:
+        eff = 0
+    return eff
+
+
+@not_implemented_for("directed")
+@nx._dispatchable
+def global_efficiency(G):
+    """Returns the average global efficiency of the graph.
+
+    The *efficiency* of a pair of nodes in a graph is the multiplicative
+    inverse of the shortest path distance between the nodes. The *average
+    global efficiency* of a graph is the average efficiency of all pairs of
+    nodes [1]_.
+
+    Parameters
+    ----------
+    G : :class:`networkx.Graph`
+        An undirected graph for which to compute the average global efficiency.
+
+    Returns
+    -------
+    float
+        The average global efficiency of the graph.
+
+    Examples
+    --------
+    >>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
+    >>> round(nx.global_efficiency(G), 12)
+    0.916666666667
+
+    Notes
+    -----
+    Edge weights are ignored when computing the shortest path distances.
+
+    See also
+    --------
+    local_efficiency
+
+    References
+    ----------
+    .. [1] Latora, Vito, and Massimo Marchiori.
+           "Efficient behavior of small-world networks."
+           *Physical Review Letters* 87.19 (2001): 198701.
+           
+
+    """
+    n = len(G)
+    denom = n * (n - 1)
+    if denom != 0:
+        lengths = nx.all_pairs_shortest_path_length(G)
+        g_eff = 0
+        for source, targets in lengths:
+            for target, distance in targets.items():
+                if distance > 0:
+                    g_eff += 1 / distance
+        g_eff /= denom
+        # g_eff = sum(1 / d for s, tgts in lengths
+        #                   for t, d in tgts.items() if d > 0) / denom
+    else:
+        g_eff = 0
+    # TODO This can be made more efficient by computing all pairs shortest
+    # path lengths in parallel.
+    return g_eff
+
+
+@not_implemented_for("directed")
+@nx._dispatchable
+def local_efficiency(G):
+    """Returns the average local efficiency of the graph.
+
+    The *efficiency* of a pair of nodes in a graph is the multiplicative
+    inverse of the shortest path distance between the nodes. The *local
+    efficiency* of a node in the graph is the average global efficiency of the
+    subgraph induced by the neighbors of the node. The *average local
+    efficiency* is the average of the local efficiencies of each node [1]_.
+
+    Parameters
+    ----------
+    G : :class:`networkx.Graph`
+        An undirected graph for which to compute the average local efficiency.
+
+    Returns
+    -------
+    float
+        The average local efficiency of the graph.
+
+    Examples
+    --------
+    >>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
+    >>> nx.local_efficiency(G)
+    0.9166666666666667
+
+    Notes
+    -----
+    Edge weights are ignored when computing the shortest path distances.
+
+    See also
+    --------
+    global_efficiency
+
+    References
+    ----------
+    .. [1] Latora, Vito, and Massimo Marchiori.
+           "Efficient behavior of small-world networks."
+           *Physical Review Letters* 87.19 (2001): 198701.
+           
+
+    """
+    efficiency_list = (global_efficiency(G.subgraph(G[v])) for v in G)
+    return sum(efficiency_list) / len(G)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/euler.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/euler.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c308e380c774a6450d4ce275118ccffd65defaa
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/euler.py
@@ -0,0 +1,470 @@
+"""
+Eulerian circuits and graphs.
+"""
+
+from itertools import combinations
+
+import networkx as nx
+
+from ..utils import arbitrary_element, not_implemented_for
+
+__all__ = [
+    "is_eulerian",
+    "eulerian_circuit",
+    "eulerize",
+    "is_semieulerian",
+    "has_eulerian_path",
+    "eulerian_path",
+]
+
+
+@nx._dispatchable
+def is_eulerian(G):
+    """Returns True if and only if `G` is Eulerian.
+
+    A graph is *Eulerian* if it has an Eulerian circuit. An *Eulerian
+    circuit* is a closed walk that includes each edge of a graph exactly
+    once.
+
+    Graphs with isolated vertices (i.e. vertices with zero degree) are not
+    considered to have Eulerian circuits. Therefore, if the graph is not
+    connected (or not strongly connected, for directed graphs), this function
+    returns False.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+       A graph, either directed or undirected.
+
+    Examples
+    --------
+    >>> nx.is_eulerian(nx.DiGraph({0: [3], 1: [2], 2: [3], 3: [0, 1]}))
+    True
+    >>> nx.is_eulerian(nx.complete_graph(5))
+    True
+    >>> nx.is_eulerian(nx.petersen_graph())
+    False
+
+    If you prefer to allow graphs with isolated vertices to have Eulerian circuits,
+    you can first remove such vertices and then call `is_eulerian` as below example shows.
+
+    >>> G = nx.Graph([(0, 1), (1, 2), (0, 2)])
+    >>> G.add_node(3)
+    >>> nx.is_eulerian(G)
+    False
+
+    >>> G.remove_nodes_from(list(nx.isolates(G)))
+    >>> nx.is_eulerian(G)
+    True
+
+
+    """
+    if G.is_directed():
+        # Every node must have equal in degree and out degree and the
+        # graph must be strongly connected
+        return all(
+            G.in_degree(n) == G.out_degree(n) for n in G
+        ) and nx.is_strongly_connected(G)
+    # An undirected Eulerian graph has no vertices of odd degree and
+    # must be connected.
+    return all(d % 2 == 0 for v, d in G.degree()) and nx.is_connected(G)
+
+
+@nx._dispatchable
+def is_semieulerian(G):
+    """Return True iff `G` is semi-Eulerian.
+
+    G is semi-Eulerian if it has an Eulerian path but no Eulerian circuit.
+
+    See Also
+    --------
+    has_eulerian_path
+    is_eulerian
+    """
+    return has_eulerian_path(G) and not is_eulerian(G)
+
+
+def _find_path_start(G):
+    """Return a suitable starting vertex for an Eulerian path.
+
+    If no path exists, return None.
+    """
+    if not has_eulerian_path(G):
+        return None
+
+    if is_eulerian(G):
+        return arbitrary_element(G)
+
+    if G.is_directed():
+        v1, v2 = (v for v in G if G.in_degree(v) != G.out_degree(v))
+        # Determines which is the 'start' node (as opposed to the 'end')
+        if G.out_degree(v1) > G.in_degree(v1):
+            return v1
+        else:
+            return v2
+
+    else:
+        # In an undirected graph randomly choose one of the possibilities
+        start = [v for v in G if G.degree(v) % 2 != 0][0]
+        return start
+
+
+def _simplegraph_eulerian_circuit(G, source):
+    if G.is_directed():
+        degree = G.out_degree
+        edges = G.out_edges
+    else:
+        degree = G.degree
+        edges = G.edges
+    vertex_stack = [source]
+    last_vertex = None
+    while vertex_stack:
+        current_vertex = vertex_stack[-1]
+        if degree(current_vertex) == 0:
+            if last_vertex is not None:
+                yield (last_vertex, current_vertex)
+            last_vertex = current_vertex
+            vertex_stack.pop()
+        else:
+            _, next_vertex = arbitrary_element(edges(current_vertex))
+            vertex_stack.append(next_vertex)
+            G.remove_edge(current_vertex, next_vertex)
+
+
+def _multigraph_eulerian_circuit(G, source):
+    if G.is_directed():
+        degree = G.out_degree
+        edges = G.out_edges
+    else:
+        degree = G.degree
+        edges = G.edges
+    vertex_stack = [(source, None)]
+    last_vertex = None
+    last_key = None
+    while vertex_stack:
+        current_vertex, current_key = vertex_stack[-1]
+        if degree(current_vertex) == 0:
+            if last_vertex is not None:
+                yield (last_vertex, current_vertex, last_key)
+            last_vertex, last_key = current_vertex, current_key
+            vertex_stack.pop()
+        else:
+            triple = arbitrary_element(edges(current_vertex, keys=True))
+            _, next_vertex, next_key = triple
+            vertex_stack.append((next_vertex, next_key))
+            G.remove_edge(current_vertex, next_vertex, next_key)
+
+
+@nx._dispatchable
+def eulerian_circuit(G, source=None, keys=False):
+    """Returns an iterator over the edges of an Eulerian circuit in `G`.
+
+    An *Eulerian circuit* is a closed walk that includes each edge of a
+    graph exactly once.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+       A graph, either directed or undirected.
+
+    source : node, optional
+       Starting node for circuit.
+
+    keys : bool
+       If False, edges generated by this function will be of the form
+       ``(u, v)``. Otherwise, edges will be of the form ``(u, v, k)``.
+       This option is ignored unless `G` is a multigraph.
+
+    Returns
+    -------
+    edges : iterator
+       An iterator over edges in the Eulerian circuit.
+
+    Raises
+    ------
+    NetworkXError
+       If the graph is not Eulerian.
+
+    See Also
+    --------
+    is_eulerian
+
+    Notes
+    -----
+    This is a linear time implementation of an algorithm adapted from [1]_.
+
+    For general information about Euler tours, see [2]_.
+
+    References
+    ----------
+    .. [1] J. Edmonds, E. L. Johnson.
+       Matching, Euler tours and the Chinese postman.
+       Mathematical programming, Volume 5, Issue 1 (1973), 111-114.
+    .. [2] https://en.wikipedia.org/wiki/Eulerian_path
+
+    Examples
+    --------
+    To get an Eulerian circuit in an undirected graph::
+
+        >>> G = nx.complete_graph(3)
+        >>> list(nx.eulerian_circuit(G))
+        [(0, 2), (2, 1), (1, 0)]
+        >>> list(nx.eulerian_circuit(G, source=1))
+        [(1, 2), (2, 0), (0, 1)]
+
+    To get the sequence of vertices in an Eulerian circuit::
+
+        >>> [u for u, v in nx.eulerian_circuit(G)]
+        [0, 2, 1]
+
+    """
+    if not is_eulerian(G):
+        raise nx.NetworkXError("G is not Eulerian.")
+    if G.is_directed():
+        G = G.reverse()
+    else:
+        G = G.copy()
+    if source is None:
+        source = arbitrary_element(G)
+    if G.is_multigraph():
+        for u, v, k in _multigraph_eulerian_circuit(G, source):
+            if keys:
+                yield u, v, k
+            else:
+                yield u, v
+    else:
+        yield from _simplegraph_eulerian_circuit(G, source)
+
+
+@nx._dispatchable
+def has_eulerian_path(G, source=None):
+    """Return True iff `G` has an Eulerian path.
+
+    An Eulerian path is a path in a graph which uses each edge of a graph
+    exactly once. If `source` is specified, then this function checks
+    whether an Eulerian path that starts at node `source` exists.
+
+    A directed graph has an Eulerian path iff:
+        - at most one vertex has out_degree - in_degree = 1,
+        - at most one vertex has in_degree - out_degree = 1,
+        - every other vertex has equal in_degree and out_degree,
+        - and all of its vertices belong to a single connected
+          component of the underlying undirected graph.
+
+    If `source` is not None, an Eulerian path starting at `source` exists if no
+    other node has out_degree - in_degree = 1. This is equivalent to either
+    there exists an Eulerian circuit or `source` has out_degree - in_degree = 1
+    and the conditions above hold.
+
+    An undirected graph has an Eulerian path iff:
+        - exactly zero or two vertices have odd degree,
+        - and all of its vertices belong to a single connected component.
+
+    If `source` is not None, an Eulerian path starting at `source` exists if
+    either there exists an Eulerian circuit or `source` has an odd degree and the
+    conditions above hold.
+
+    Graphs with isolated vertices (i.e. vertices with zero degree) are not considered
+    to have an Eulerian path. Therefore, if the graph is not connected (or not strongly
+    connected, for directed graphs), this function returns False.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+        The graph to find an euler path in.
+
+    source : node, optional
+        Starting node for path.
+
+    Returns
+    -------
+    Bool : True if G has an Eulerian path.
+
+    Examples
+    --------
+    If you prefer to allow graphs with isolated vertices to have Eulerian path,
+    you can first remove such vertices and then call `has_eulerian_path` as below example shows.
+
+    >>> G = nx.Graph([(0, 1), (1, 2), (0, 2)])
+    >>> G.add_node(3)
+    >>> nx.has_eulerian_path(G)
+    False
+
+    >>> G.remove_nodes_from(list(nx.isolates(G)))
+    >>> nx.has_eulerian_path(G)
+    True
+
+    See Also
+    --------
+    is_eulerian
+    eulerian_path
+    """
+    if nx.is_eulerian(G):
+        return True
+
+    if G.is_directed():
+        ins = G.in_degree
+        outs = G.out_degree
+        # Since we know it is not eulerian, outs - ins must be 1 for source
+        if source is not None and outs[source] - ins[source] != 1:
+            return False
+
+        unbalanced_ins = 0
+        unbalanced_outs = 0
+        for v in G:
+            if ins[v] - outs[v] == 1:
+                unbalanced_ins += 1
+            elif outs[v] - ins[v] == 1:
+                unbalanced_outs += 1
+            elif ins[v] != outs[v]:
+                return False
+
+        return (
+            unbalanced_ins <= 1 and unbalanced_outs <= 1 and nx.is_weakly_connected(G)
+        )
+    else:
+        # We know it is not eulerian, so degree of source must be odd.
+        if source is not None and G.degree[source] % 2 != 1:
+            return False
+
+        # Sum is 2 since we know it is not eulerian (which implies sum is 0)
+        return sum(d % 2 == 1 for v, d in G.degree()) == 2 and nx.is_connected(G)
+
+
+@nx._dispatchable
+def eulerian_path(G, source=None, keys=False):
+    """Return an iterator over the edges of an Eulerian path in `G`.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+        The graph in which to look for an eulerian path.
+    source : node or None (default: None)
+        The node at which to start the search. None means search over all
+        starting nodes.
+    keys : Bool (default: False)
+        Indicates whether to yield edge 3-tuples (u, v, edge_key).
+        The default yields edge 2-tuples
+
+    Yields
+    ------
+    Edge tuples along the eulerian path.
+
+    Warning: If `source` provided is not the start node of an Euler path
+    will raise error even if an Euler Path exists.
+    """
+    if not has_eulerian_path(G, source):
+        raise nx.NetworkXError("Graph has no Eulerian paths.")
+    if G.is_directed():
+        G = G.reverse()
+        if source is None or nx.is_eulerian(G) is False:
+            source = _find_path_start(G)
+        if G.is_multigraph():
+            for u, v, k in _multigraph_eulerian_circuit(G, source):
+                if keys:
+                    yield u, v, k
+                else:
+                    yield u, v
+        else:
+            yield from _simplegraph_eulerian_circuit(G, source)
+    else:
+        G = G.copy()
+        if source is None:
+            source = _find_path_start(G)
+        if G.is_multigraph():
+            if keys:
+                yield from reversed(
+                    [(v, u, k) for u, v, k in _multigraph_eulerian_circuit(G, source)]
+                )
+            else:
+                yield from reversed(
+                    [(v, u) for u, v, k in _multigraph_eulerian_circuit(G, source)]
+                )
+        else:
+            yield from reversed(
+                [(v, u) for u, v in _simplegraph_eulerian_circuit(G, source)]
+            )
+
+
+@not_implemented_for("directed")
+@nx._dispatchable(returns_graph=True)
+def eulerize(G):
+    """Transforms a graph into an Eulerian graph.
+
+    If `G` is Eulerian the result is `G` as a MultiGraph, otherwise the result is a smallest
+    (in terms of the number of edges) multigraph whose underlying simple graph is `G`.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+       An undirected graph
+
+    Returns
+    -------
+    G : NetworkX multigraph
+
+    Raises
+    ------
+    NetworkXError
+       If the graph is not connected.
+
+    See Also
+    --------
+    is_eulerian
+    eulerian_circuit
+
+    References
+    ----------
+    .. [1] J. Edmonds, E. L. Johnson.
+       Matching, Euler tours and the Chinese postman.
+       Mathematical programming, Volume 5, Issue 1 (1973), 111-114.
+    .. [2] https://en.wikipedia.org/wiki/Eulerian_path
+    .. [3] http://web.math.princeton.edu/math_alive/5/Notes1.pdf
+
+    Examples
+    --------
+        >>> G = nx.complete_graph(10)
+        >>> H = nx.eulerize(G)
+        >>> nx.is_eulerian(H)
+        True
+
+    """
+    if G.order() == 0:
+        raise nx.NetworkXPointlessConcept("Cannot Eulerize null graph")
+    if not nx.is_connected(G):
+        raise nx.NetworkXError("G is not connected")
+    odd_degree_nodes = [n for n, d in G.degree() if d % 2 == 1]
+    G = nx.MultiGraph(G)
+    if len(odd_degree_nodes) == 0:
+        return G
+
+    # get all shortest paths between vertices of odd degree
+    odd_deg_pairs_paths = [
+        (m, {n: nx.shortest_path(G, source=m, target=n)})
+        for m, n in combinations(odd_degree_nodes, 2)
+    ]
+
+    # use the number of vertices in a graph + 1 as an upper bound on
+    # the maximum length of a path in G
+    upper_bound_on_max_path_length = len(G) + 1
+
+    # use "len(G) + 1 - len(P)",
+    # where P is a shortest path between vertices n and m,
+    # as edge-weights in a new graph
+    # store the paths in the graph for easy indexing later
+    Gp = nx.Graph()
+    for n, Ps in odd_deg_pairs_paths:
+        for m, P in Ps.items():
+            if n != m:
+                Gp.add_edge(
+                    m, n, weight=upper_bound_on_max_path_length - len(P), path=P
+                )
+
+    # find the minimum weight matching of edges in the weighted graph
+    best_matching = nx.Graph(list(nx.max_weight_matching(Gp)))
+
+    # duplicate each edge along each path in the set of paths in Gp
+    for m, n in best_matching.edges():
+        path = Gp[m][n]["path"]
+        G.add_edges_from(nx.utils.pairwise(path))
+    return G
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/graph_hashing.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/graph_hashing.py
new file mode 100644
index 0000000000000000000000000000000000000000..96a76ffa41ae1f6b3aaa749ab7d9eef550bf36d8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/graph_hashing.py
@@ -0,0 +1,435 @@
+"""
+Functions for hashing graphs to strings.
+Isomorphic graphs should be assigned identical hashes.
+For now, only Weisfeiler-Lehman hashing is implemented.
+"""
+
+import warnings
+from collections import Counter, defaultdict
+from hashlib import blake2b
+
+import networkx as nx
+
+__all__ = ["weisfeiler_lehman_graph_hash", "weisfeiler_lehman_subgraph_hashes"]
+
+
+def _hash_label(label, digest_size):
+    return blake2b(label.encode("ascii"), digest_size=digest_size).hexdigest()
+
+
+def _init_node_labels(G, edge_attr, node_attr):
+    if node_attr:
+        return {u: str(dd[node_attr]) for u, dd in G.nodes(data=True)}
+    elif edge_attr:
+        return {u: "" for u in G}
+    else:
+        warnings.warn(
+            "The hashes produced for graphs without node or edge attributes "
+            "changed in v3.5 due to a bugfix (see documentation).",
+            UserWarning,
+            stacklevel=2,
+        )
+        if nx.is_directed(G):
+            return {u: str(G.in_degree(u)) + "_" + str(G.out_degree(u)) for u in G}
+        else:
+            return {u: str(deg) for u, deg in G.degree()}
+
+
+def _neighborhood_aggregate_undirected(G, node, node_labels, edge_attr=None):
+    """
+    Compute new labels for given node in an undirected graph by aggregating
+    the labels of each node's neighbors.
+    """
+    label_list = []
+    for nbr in G.neighbors(node):
+        prefix = "" if edge_attr is None else str(G[node][nbr][edge_attr])
+        label_list.append(prefix + node_labels[nbr])
+    return node_labels[node] + "".join(sorted(label_list))
+
+
+def _neighborhood_aggregate_directed(G, node, node_labels, edge_attr=None):
+    """
+    Compute new labels for given node in a directed graph by aggregating
+    the labels of each node's neighbors.
+    """
+    successor_labels = []
+    for nbr in G.successors(node):
+        prefix = "s_" + "" if edge_attr is None else str(G[node][nbr][edge_attr])
+        successor_labels.append(prefix + node_labels[nbr])
+
+    predecessor_labels = []
+    for nbr in G.predecessors(node):
+        prefix = "p_" + "" if edge_attr is None else str(G[nbr][node][edge_attr])
+        predecessor_labels.append(prefix + node_labels[nbr])
+    return (
+        node_labels[node]
+        + "".join(sorted(successor_labels))
+        + "".join(sorted(predecessor_labels))
+    )
+
+
+@nx.utils.not_implemented_for("multigraph")
+@nx._dispatchable(edge_attrs={"edge_attr": None}, node_attrs="node_attr")
+def weisfeiler_lehman_graph_hash(
+    G, edge_attr=None, node_attr=None, iterations=3, digest_size=16
+):
+    """Return Weisfeiler Lehman (WL) graph hash.
+
+    .. Warning:: Hash values for directed graphs and graphs without edge or
+        node attributes have changed in v3.5. In previous versions,
+        directed graphs did not distinguish in- and outgoing edges. Also,
+        graphs without attributes set initial states such that effectively
+        one extra iteration of WL occurred than indicated by `iterations`.
+        For undirected graphs without node or edge labels, the old
+        hashes can be obtained by increasing the iteration count by one.
+        For more details, see `issue #7806
+        `_.
+
+    The function iteratively aggregates and hashes neighborhoods of each node.
+    After each node's neighbors are hashed to obtain updated node labels,
+    a hashed histogram of resulting labels is returned as the final hash.
+
+    Hashes are identical for isomorphic graphs and strong guarantees that
+    non-isomorphic graphs will get different hashes. See [1]_ for details.
+
+    If no node or edge attributes are provided, the degree of each node
+    is used as its initial label.
+    Otherwise, node and/or edge labels are used to compute the hash.
+
+    Parameters
+    ----------
+    G : graph
+        The graph to be hashed.
+        Can have node and/or edge attributes. Can also have no attributes.
+    edge_attr : string, optional (default=None)
+        The key in edge attribute dictionary to be used for hashing.
+        If None, edge labels are ignored.
+    node_attr: string, optional (default=None)
+        The key in node attribute dictionary to be used for hashing.
+        If None, and no edge_attr given, use the degrees of the nodes as labels.
+    iterations: int, optional (default=3)
+        Number of neighbor aggregations to perform.
+        Should be larger for larger graphs.
+    digest_size: int, optional (default=16)
+        Size (in bytes) of blake2b hash digest to use for hashing node labels.
+
+    Returns
+    -------
+    h : string
+        Hexadecimal string corresponding to hash of `G` (length ``2 * digest_size``).
+
+    Raises
+    ------
+    ValueError
+        If `iterations` is not a positve number.
+
+    Examples
+    --------
+    Two graphs with edge attributes that are isomorphic, except for
+    differences in the edge labels.
+
+    >>> G1 = nx.Graph()
+    >>> G1.add_edges_from(
+    ...     [
+    ...         (1, 2, {"label": "A"}),
+    ...         (2, 3, {"label": "A"}),
+    ...         (3, 1, {"label": "A"}),
+    ...         (1, 4, {"label": "B"}),
+    ...     ]
+    ... )
+    >>> G2 = nx.Graph()
+    >>> G2.add_edges_from(
+    ...     [
+    ...         (5, 6, {"label": "B"}),
+    ...         (6, 7, {"label": "A"}),
+    ...         (7, 5, {"label": "A"}),
+    ...         (7, 8, {"label": "A"}),
+    ...     ]
+    ... )
+
+    Omitting the `edge_attr` option, results in identical hashes.
+
+    >>> nx.weisfeiler_lehman_graph_hash(G1)
+    'c045439172215f49e0bef8c3d26c6b61'
+    >>> nx.weisfeiler_lehman_graph_hash(G2)
+    'c045439172215f49e0bef8c3d26c6b61'
+
+    With edge labels, the graphs are no longer assigned
+    the same hash digest.
+
+    >>> nx.weisfeiler_lehman_graph_hash(G1, edge_attr="label")
+    'c653d85538bcf041d88c011f4f905f10'
+    >>> nx.weisfeiler_lehman_graph_hash(G2, edge_attr="label")
+    '3dcd84af1ca855d0eff3c978d88e7ec7'
+
+    Notes
+    -----
+    To return the WL hashes of each subgraph of a graph, use
+    `weisfeiler_lehman_subgraph_hashes`
+
+    Similarity between hashes does not imply similarity between graphs.
+
+    References
+    ----------
+    .. [1] Shervashidze, Nino, Pascal Schweitzer, Erik Jan Van Leeuwen,
+       Kurt Mehlhorn, and Karsten M. Borgwardt. Weisfeiler Lehman
+       Graph Kernels. Journal of Machine Learning Research. 2011.
+       http://www.jmlr.org/papers/volume12/shervashidze11a/shervashidze11a.pdf
+
+    See also
+    --------
+    weisfeiler_lehman_subgraph_hashes
+    """
+
+    if G.is_directed():
+        _neighborhood_aggregate = _neighborhood_aggregate_directed
+        warnings.warn(
+            "The hashes produced for directed graphs changed in version v3.5"
+            " due to a bugfix to track in and out edges separately (see documentation).",
+            UserWarning,
+            stacklevel=2,
+        )
+    else:
+        _neighborhood_aggregate = _neighborhood_aggregate_undirected
+
+    def weisfeiler_lehman_step(G, labels, edge_attr=None):
+        """
+        Apply neighborhood aggregation to each node
+        in the graph.
+        Computes a dictionary with labels for each node.
+        """
+        new_labels = {}
+        for node in G.nodes():
+            label = _neighborhood_aggregate(G, node, labels, edge_attr=edge_attr)
+            new_labels[node] = _hash_label(label, digest_size)
+        return new_labels
+
+    if iterations <= 0:
+        raise ValueError("The WL algorithm requires that `iterations` be positive")
+
+    # set initial node labels
+    node_labels = _init_node_labels(G, edge_attr, node_attr)
+
+    # If the graph has no attributes, initial labels are the nodes' degrees.
+    # This is equivalent to doing the first iterations of WL.
+    if not edge_attr and not node_attr:
+        iterations -= 1
+
+    subgraph_hash_counts = []
+    for _ in range(iterations):
+        node_labels = weisfeiler_lehman_step(G, node_labels, edge_attr=edge_attr)
+        counter = Counter(node_labels.values())
+        # sort the counter, extend total counts
+        subgraph_hash_counts.extend(sorted(counter.items(), key=lambda x: x[0]))
+
+    # hash the final counter
+    return _hash_label(str(tuple(subgraph_hash_counts)), digest_size)
+
+
+@nx.utils.not_implemented_for("multigraph")
+@nx._dispatchable(edge_attrs={"edge_attr": None}, node_attrs="node_attr")
+def weisfeiler_lehman_subgraph_hashes(
+    G,
+    edge_attr=None,
+    node_attr=None,
+    iterations=3,
+    digest_size=16,
+    include_initial_labels=False,
+):
+    """
+    Return a dictionary of subgraph hashes by node.
+
+    .. Warning:: Hash values for directed graphs have changed in version
+        v3.5. In previous versions, directed graphs did not distinguish in-
+        and outgoing edges.
+        Graphs without attributes previously performed an extra iteration of
+        WL at initialisation, which was not visible in the output of this
+        function. This hash value is now included in the returned dictionary,
+        shifting the other calculated hashes one position to the right. To
+        obtain the same last subgraph hash, increase the number of iterations
+        by one.
+        For more details, see `issue #7806
+        `_.
+
+    Dictionary keys are nodes in `G`, and values are a list of hashes.
+    Each hash corresponds to a subgraph rooted at a given node u in `G`.
+    Lists of subgraph hashes are sorted in increasing order of depth from
+    their root node, with the hash at index i corresponding to a subgraph
+    of nodes at most i-hops (i edges) distance from u. Thus, each list will contain
+    `iterations` elements - a hash for a subgraph at each depth. If
+    `include_initial_labels` is set to `True`, each list will additionally
+    have contain a hash of the initial node label (or equivalently a
+    subgraph of depth 0) prepended, totalling ``iterations + 1`` elements.
+
+    The function iteratively aggregates and hashes neighborhoods of each node.
+    This is achieved for each step by replacing for each node its label from
+    the previous iteration with its hashed 1-hop neighborhood aggregate.
+    The new node label is then appended to a list of node labels for each
+    node.
+
+    To aggregate neighborhoods for a node $u$ at each step, all labels of
+    nodes adjacent to $u$ are concatenated. If the `edge_attr` parameter is set,
+    labels for each neighboring node are prefixed with the value of this attribute
+    along the connecting edge from this neighbor to node $u$. The resulting string
+    is then hashed to compress this information into a fixed digest size.
+
+    Thus, at the i-th iteration, nodes within i hops influence any given
+    hashed node label. We can therefore say that at depth $i$ for node $u$
+    we have a hash for a subgraph induced by the i-hop neighborhood of $u$.
+
+    The output can be used to create general Weisfeiler-Lehman graph kernels,
+    or generate features for graphs or nodes - for example to generate 'words' in
+    a graph as seen in the 'graph2vec' algorithm.
+    See [1]_ & [2]_ respectively for details.
+
+    Hashes are identical for isomorphic subgraphs and there exist strong
+    guarantees that non-isomorphic graphs will get different hashes.
+    See [1]_ for details.
+
+    If no node or edge attributes are provided, the degree of each node
+    is used as its initial label.
+    Otherwise, node and/or edge labels are used to compute the hash.
+
+    Parameters
+    ----------
+    G : graph
+        The graph to be hashed.
+        Can have node and/or edge attributes. Can also have no attributes.
+    edge_attr : string, optional (default=None)
+        The key in edge attribute dictionary to be used for hashing.
+        If None, edge labels are ignored.
+    node_attr : string, optional (default=None)
+        The key in node attribute dictionary to be used for hashing.
+        If None, and no edge_attr given, use the degrees of the nodes as labels.
+        If None, and edge_attr is given, each node starts with an identical label.
+    iterations : int, optional (default=3)
+        Number of neighbor aggregations to perform.
+        Should be larger for larger graphs.
+    digest_size : int, optional (default=16)
+        Size (in bytes) of blake2b hash digest to use for hashing node labels.
+        The default size is 16 bytes.
+    include_initial_labels : bool, optional (default=False)
+        If True, include the hashed initial node label as the first subgraph
+        hash for each node.
+
+    Returns
+    -------
+    node_subgraph_hashes : dict
+        A dictionary with each key given by a node in G, and each value given
+        by the subgraph hashes in order of depth from the key node.
+        Hashes are hexadecimal strings (hence ``2 * digest_size`` long).
+
+
+    Raises
+    ------
+    ValueError
+        If `iterations` is not a positve number.
+
+    Examples
+    --------
+    Finding similar nodes in different graphs:
+
+    >>> G1 = nx.Graph()
+    >>> G1.add_edges_from([(1, 2), (2, 3), (2, 4), (3, 5), (4, 6), (5, 7), (6, 7)])
+    >>> G2 = nx.Graph()
+    >>> G2.add_edges_from([(1, 3), (2, 3), (1, 6), (1, 5), (4, 6)])
+    >>> g1_hashes = nx.weisfeiler_lehman_subgraph_hashes(
+    ...     G1, iterations=4, digest_size=8
+    ... )
+    >>> g2_hashes = nx.weisfeiler_lehman_subgraph_hashes(
+    ...     G2, iterations=4, digest_size=8
+    ... )
+
+    Even though G1 and G2 are not isomorphic (they have different numbers of edges),
+    the hash sequence of depth 3 for node 1 in G1 and node 5 in G2 are similar:
+
+    >>> g1_hashes[1]
+    ['f6fc42039fba3776', 'a93b64973cfc8897', 'db1b43ae35a1878f', '57872a7d2059c1c0']
+    >>> g2_hashes[5]
+    ['f6fc42039fba3776', 'a93b64973cfc8897', 'db1b43ae35a1878f', '1716d2a4012fa4bc']
+
+    The first 3 WL subgraph hashes match. From this we can conclude that it's very
+    likely the neighborhood of 3 hops around these nodes are isomorphic.
+
+    However the 4-hop neighborhoods of ``G1`` and ``G2`` are not isomorphic since the
+    4th hashes in the lists above are not equal.
+
+    These nodes may be candidates to be classified together since their local topology
+    is similar.
+
+    Notes
+    -----
+    To hash the full graph when subgraph hashes are not needed, use
+    `weisfeiler_lehman_graph_hash` for efficiency.
+
+    Similarity between hashes does not imply similarity between graphs.
+
+    References
+    ----------
+    .. [1] Shervashidze, Nino, Pascal Schweitzer, Erik Jan Van Leeuwen,
+       Kurt Mehlhorn, and Karsten M. Borgwardt. Weisfeiler Lehman
+       Graph Kernels. Journal of Machine Learning Research. 2011.
+       http://www.jmlr.org/papers/volume12/shervashidze11a/shervashidze11a.pdf
+    .. [2] Annamalai Narayanan, Mahinthan Chandramohan, Rajasekar Venkatesan,
+       Lihui Chen, Yang Liu and Shantanu Jaiswa. graph2vec: Learning
+       Distributed Representations of Graphs. arXiv. 2017
+       https://arxiv.org/pdf/1707.05005.pdf
+
+    See also
+    --------
+    weisfeiler_lehman_graph_hash
+    """
+
+    if G.is_directed():
+        _neighborhood_aggregate = _neighborhood_aggregate_directed
+        warnings.warn(
+            "The hashes produced for directed graphs changed in v3.5"
+            " due to a bugfix (see documentation).",
+            UserWarning,
+            stacklevel=2,
+        )
+    else:
+        _neighborhood_aggregate = _neighborhood_aggregate_undirected
+
+    def weisfeiler_lehman_step(G, labels, node_subgraph_hashes, edge_attr=None):
+        """
+        Apply neighborhood aggregation to each node
+        in the graph.
+        Computes a dictionary with labels for each node.
+        Appends the new hashed label to the dictionary of subgraph hashes
+        originating from and indexed by each node in G
+        """
+        new_labels = {}
+        for node in G.nodes():
+            label = _neighborhood_aggregate(G, node, labels, edge_attr=edge_attr)
+            hashed_label = _hash_label(label, digest_size)
+            new_labels[node] = hashed_label
+            node_subgraph_hashes[node].append(hashed_label)
+        return new_labels
+
+    if iterations <= 0:
+        raise ValueError("The WL algorithm requires that `iterations` be positive")
+
+    node_labels = _init_node_labels(G, edge_attr, node_attr)
+
+    if include_initial_labels:
+        node_subgraph_hashes = {
+            k: [_hash_label(v, digest_size)] for k, v in node_labels.items()
+        }
+    else:
+        node_subgraph_hashes = defaultdict(list)
+
+    # If the graph has no attributes, initial labels are the nodes' degrees.
+    # This is equivalent to doing the first iterations of WL.
+    if not edge_attr and not node_attr:
+        iterations -= 1
+        for node in G.nodes():
+            hashed_label = _hash_label(node_labels[node], digest_size)
+            node_subgraph_hashes[node].append(hashed_label)
+
+    for _ in range(iterations):
+        node_labels = weisfeiler_lehman_step(
+            G, node_labels, node_subgraph_hashes, edge_attr
+        )
+
+    return dict(node_subgraph_hashes)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/graphical.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/graphical.py
new file mode 100644
index 0000000000000000000000000000000000000000..d5d82dedda6f9810e3f51bc4c82a9a2b252fa998
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/graphical.py
@@ -0,0 +1,483 @@
+"""Test sequences for graphiness."""
+
+import heapq
+
+import networkx as nx
+
+__all__ = [
+    "is_graphical",
+    "is_multigraphical",
+    "is_pseudographical",
+    "is_digraphical",
+    "is_valid_degree_sequence_erdos_gallai",
+    "is_valid_degree_sequence_havel_hakimi",
+]
+
+
+@nx._dispatchable(graphs=None)
+def is_graphical(sequence, method="eg"):
+    """Returns True if sequence is a valid degree sequence.
+
+    A degree sequence is valid if some graph can realize it.
+
+    Parameters
+    ----------
+    sequence : list or iterable container
+        A sequence of integer node degrees
+
+    method : "eg" | "hh"  (default: 'eg')
+        The method used to validate the degree sequence.
+        "eg" corresponds to the Erdős-Gallai algorithm
+        [EG1960]_, [choudum1986]_, and
+        "hh" to the Havel-Hakimi algorithm
+        [havel1955]_, [hakimi1962]_, [CL1996]_.
+
+    Returns
+    -------
+    valid : bool
+        True if the sequence is a valid degree sequence and False if not.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> sequence = (d for n, d in G.degree())
+    >>> nx.is_graphical(sequence)
+    True
+
+    To test a non-graphical sequence:
+    >>> sequence_list = [d for n, d in G.degree()]
+    >>> sequence_list[-1] += 1
+    >>> nx.is_graphical(sequence_list)
+    False
+
+    References
+    ----------
+    .. [EG1960] Erdős and Gallai, Mat. Lapok 11 264, 1960.
+    .. [choudum1986] S.A. Choudum. "A simple proof of the Erdős-Gallai theorem on
+       graph sequences." Bulletin of the Australian Mathematical Society, 33,
+       pp 67-70, 1986. https://doi.org/10.1017/S0004972700002872
+    .. [havel1955] Havel, V. "A Remark on the Existence of Finite Graphs"
+       Casopis Pest. Mat. 80, 477-480, 1955.
+    .. [hakimi1962] Hakimi, S. "On the Realizability of a Set of Integers as
+       Degrees of the Vertices of a Graph." SIAM J. Appl. Math. 10, 496-506, 1962.
+    .. [CL1996] G. Chartrand and L. Lesniak, "Graphs and Digraphs",
+       Chapman and Hall/CRC, 1996.
+    """
+    if method == "eg":
+        valid = is_valid_degree_sequence_erdos_gallai(list(sequence))
+    elif method == "hh":
+        valid = is_valid_degree_sequence_havel_hakimi(list(sequence))
+    else:
+        msg = "`method` must be 'eg' or 'hh'"
+        raise nx.NetworkXException(msg)
+    return valid
+
+
+def _basic_graphical_tests(deg_sequence):
+    # Sort and perform some simple tests on the sequence
+    deg_sequence = nx.utils.make_list_of_ints(deg_sequence)
+    p = len(deg_sequence)
+    num_degs = [0] * p
+    dmax, dmin, dsum, n = 0, p, 0, 0
+    for d in deg_sequence:
+        # Reject if degree is negative or larger than the sequence length
+        if d < 0 or d >= p:
+            raise nx.NetworkXUnfeasible
+        # Process only the non-zero integers
+        elif d > 0:
+            dmax, dmin, dsum, n = max(dmax, d), min(dmin, d), dsum + d, n + 1
+            num_degs[d] += 1
+    # Reject sequence if it has odd sum or is oversaturated
+    if dsum % 2 or dsum > n * (n - 1):
+        raise nx.NetworkXUnfeasible
+    return dmax, dmin, dsum, n, num_degs
+
+
+@nx._dispatchable(graphs=None)
+def is_valid_degree_sequence_havel_hakimi(deg_sequence):
+    r"""Returns True if deg_sequence can be realized by a simple graph.
+
+    The validation proceeds using the Havel-Hakimi theorem
+    [havel1955]_, [hakimi1962]_, [CL1996]_.
+    Worst-case run time is $O(s)$ where $s$ is the sum of the sequence.
+
+    Parameters
+    ----------
+    deg_sequence : list
+        A list of integers where each element specifies the degree of a node
+        in a graph.
+
+    Returns
+    -------
+    valid : bool
+        True if deg_sequence is graphical and False if not.
+
+    Examples
+    --------
+    >>> G = nx.Graph([(1, 2), (1, 3), (2, 3), (3, 4), (4, 2), (5, 1), (5, 4)])
+    >>> sequence = (d for _, d in G.degree())
+    >>> nx.is_valid_degree_sequence_havel_hakimi(sequence)
+    True
+
+    To test a non-valid sequence:
+    >>> sequence_list = [d for _, d in G.degree()]
+    >>> sequence_list[-1] += 1
+    >>> nx.is_valid_degree_sequence_havel_hakimi(sequence_list)
+    False
+
+    Notes
+    -----
+    The ZZ condition says that for the sequence d if
+
+    .. math::
+        |d| >= \frac{(\max(d) + \min(d) + 1)^2}{4*\min(d)}
+
+    then d is graphical.  This was shown in Theorem 6 in [1]_.
+
+    References
+    ----------
+    .. [1] I.E. Zverovich and V.E. Zverovich. "Contributions to the theory
+       of graphic sequences", Discrete Mathematics, 105, pp. 292-303 (1992).
+    .. [havel1955] Havel, V. "A Remark on the Existence of Finite Graphs"
+       Casopis Pest. Mat. 80, 477-480, 1955.
+    .. [hakimi1962] Hakimi, S. "On the Realizability of a Set of Integers as
+       Degrees of the Vertices of a Graph." SIAM J. Appl. Math. 10, 496-506, 1962.
+    .. [CL1996] G. Chartrand and L. Lesniak, "Graphs and Digraphs",
+       Chapman and Hall/CRC, 1996.
+    """
+    try:
+        dmax, dmin, dsum, n, num_degs = _basic_graphical_tests(deg_sequence)
+    except nx.NetworkXUnfeasible:
+        return False
+    # Accept if sequence has no non-zero degrees or passes the ZZ condition
+    if n == 0 or 4 * dmin * n >= (dmax + dmin + 1) * (dmax + dmin + 1):
+        return True
+
+    modstubs = [0] * (dmax + 1)
+    # Successively reduce degree sequence by removing the maximum degree
+    while n > 0:
+        # Retrieve the maximum degree in the sequence
+        while num_degs[dmax] == 0:
+            dmax -= 1
+        # If there are not enough stubs to connect to, then the sequence is
+        # not graphical
+        if dmax > n - 1:
+            return False
+
+        # Remove largest stub in list
+        num_degs[dmax], n = num_degs[dmax] - 1, n - 1
+        # Reduce the next dmax largest stubs
+        mslen = 0
+        k = dmax
+        for i in range(dmax):
+            while num_degs[k] == 0:
+                k -= 1
+            num_degs[k], n = num_degs[k] - 1, n - 1
+            if k > 1:
+                modstubs[mslen] = k - 1
+                mslen += 1
+        # Add back to the list any non-zero stubs that were removed
+        for i in range(mslen):
+            stub = modstubs[i]
+            num_degs[stub], n = num_degs[stub] + 1, n + 1
+    return True
+
+
+@nx._dispatchable(graphs=None)
+def is_valid_degree_sequence_erdos_gallai(deg_sequence):
+    r"""Returns True if deg_sequence can be realized by a simple graph.
+
+    The validation is done using the Erdős-Gallai theorem [EG1960]_.
+
+    Parameters
+    ----------
+    deg_sequence : list
+        A list of integers
+
+    Returns
+    -------
+    valid : bool
+        True if deg_sequence is graphical and False if not.
+
+    Examples
+    --------
+    >>> G = nx.Graph([(1, 2), (1, 3), (2, 3), (3, 4), (4, 2), (5, 1), (5, 4)])
+    >>> sequence = (d for _, d in G.degree())
+    >>> nx.is_valid_degree_sequence_erdos_gallai(sequence)
+    True
+
+    To test a non-valid sequence:
+    >>> sequence_list = [d for _, d in G.degree()]
+    >>> sequence_list[-1] += 1
+    >>> nx.is_valid_degree_sequence_erdos_gallai(sequence_list)
+    False
+
+    Notes
+    -----
+
+    This implementation uses an equivalent form of the Erdős-Gallai criterion.
+    Worst-case run time is $O(n)$ where $n$ is the length of the sequence.
+
+    Specifically, a sequence d is graphical if and only if the
+    sum of the sequence is even and for all strong indices k in the sequence,
+
+     .. math::
+
+       \sum_{i=1}^{k} d_i \leq k(k-1) + \sum_{j=k+1}^{n} \min(d_i,k)
+             = k(n-1) - ( k \sum_{j=0}^{k-1} n_j - \sum_{j=0}^{k-1} j n_j )
+
+    A strong index k is any index where d_k >= k and the value n_j is the
+    number of occurrences of j in d.  The maximal strong index is called the
+    Durfee index.
+
+    This particular rearrangement comes from the proof of Theorem 3 in [2]_.
+
+    The ZZ condition says that for the sequence d if
+
+    .. math::
+        |d| >= \frac{(\max(d) + \min(d) + 1)^2}{4*\min(d)}
+
+    then d is graphical.  This was shown in Theorem 6 in [2]_.
+
+    References
+    ----------
+    .. [1] A. Tripathi and S. Vijay. "A note on a theorem of Erdős & Gallai",
+       Discrete Mathematics, 265, pp. 417-420 (2003).
+    .. [2] I.E. Zverovich and V.E. Zverovich. "Contributions to the theory
+       of graphic sequences", Discrete Mathematics, 105, pp. 292-303 (1992).
+    .. [EG1960] Erdős and Gallai, Mat. Lapok 11 264, 1960.
+    """
+    try:
+        dmax, dmin, dsum, n, num_degs = _basic_graphical_tests(deg_sequence)
+    except nx.NetworkXUnfeasible:
+        return False
+    # Accept if sequence has no non-zero degrees or passes the ZZ condition
+    if n == 0 or 4 * dmin * n >= (dmax + dmin + 1) * (dmax + dmin + 1):
+        return True
+
+    # Perform the EG checks using the reformulation of Zverovich and Zverovich
+    k, sum_deg, sum_nj, sum_jnj = 0, 0, 0, 0
+    for dk in range(dmax, dmin - 1, -1):
+        if dk < k + 1:  # Check if already past Durfee index
+            return True
+        if num_degs[dk] > 0:
+            run_size = num_degs[dk]  # Process a run of identical-valued degrees
+            if dk < k + run_size:  # Check if end of run is past Durfee index
+                run_size = dk - k  # Adjust back to Durfee index
+            sum_deg += run_size * dk
+            for v in range(run_size):
+                sum_nj += num_degs[k + v]
+                sum_jnj += (k + v) * num_degs[k + v]
+            k += run_size
+            if sum_deg > k * (n - 1) - k * sum_nj + sum_jnj:
+                return False
+    return True
+
+
+@nx._dispatchable(graphs=None)
+def is_multigraphical(sequence):
+    """Returns True if some multigraph can realize the sequence.
+
+    Parameters
+    ----------
+    sequence : list
+        A list of integers
+
+    Returns
+    -------
+    valid : bool
+        True if deg_sequence is a multigraphic degree sequence and False if not.
+
+    Examples
+    --------
+    >>> G = nx.MultiGraph([(1, 2), (1, 3), (2, 3), (3, 4), (4, 2), (5, 1), (5, 4)])
+    >>> sequence = (d for _, d in G.degree())
+    >>> nx.is_multigraphical(sequence)
+    True
+
+    To test a non-multigraphical sequence:
+    >>> sequence_list = [d for _, d in G.degree()]
+    >>> sequence_list[-1] += 1
+    >>> nx.is_multigraphical(sequence_list)
+    False
+
+    Notes
+    -----
+    The worst-case run time is $O(n)$ where $n$ is the length of the sequence.
+
+    References
+    ----------
+    .. [1] S. L. Hakimi. "On the realizability of a set of integers as
+       degrees of the vertices of a linear graph", J. SIAM, 10, pp. 496-506
+       (1962).
+    """
+    try:
+        deg_sequence = nx.utils.make_list_of_ints(sequence)
+    except nx.NetworkXError:
+        return False
+    dsum, dmax = 0, 0
+    for d in deg_sequence:
+        if d < 0:
+            return False
+        dsum, dmax = dsum + d, max(dmax, d)
+    if dsum % 2 or dsum < 2 * dmax:
+        return False
+    return True
+
+
+@nx._dispatchable(graphs=None)
+def is_pseudographical(sequence):
+    """Returns True if some pseudograph can realize the sequence.
+
+    Every nonnegative integer sequence with an even sum is pseudographical
+    (see [1]_).
+
+    Parameters
+    ----------
+    sequence : list or iterable container
+        A sequence of integer node degrees
+
+    Returns
+    -------
+    valid : bool
+      True if the sequence is a pseudographic degree sequence and False if not.
+
+    Examples
+    --------
+    >>> G = nx.Graph([(1, 2), (1, 3), (2, 3), (3, 4), (4, 2), (5, 1), (5, 4)])
+    >>> sequence = (d for _, d in G.degree())
+    >>> nx.is_pseudographical(sequence)
+    True
+
+    To test a non-pseudographical sequence:
+    >>> sequence_list = [d for _, d in G.degree()]
+    >>> sequence_list[-1] += 1
+    >>> nx.is_pseudographical(sequence_list)
+    False
+
+    Notes
+    -----
+    The worst-case run time is $O(n)$ where n is the length of the sequence.
+
+    References
+    ----------
+    .. [1] F. Boesch and F. Harary. "Line removal algorithms for graphs
+       and their degree lists", IEEE Trans. Circuits and Systems, CAS-23(12),
+       pp. 778-782 (1976).
+    """
+    try:
+        deg_sequence = nx.utils.make_list_of_ints(sequence)
+    except nx.NetworkXError:
+        return False
+    return sum(deg_sequence) % 2 == 0 and min(deg_sequence) >= 0
+
+
+@nx._dispatchable(graphs=None)
+def is_digraphical(in_sequence, out_sequence):
+    r"""Returns True if some directed graph can realize the in- and out-degree
+    sequences.
+
+    Parameters
+    ----------
+    in_sequence : list or iterable container
+        A sequence of integer node in-degrees
+
+    out_sequence : list or iterable container
+        A sequence of integer node out-degrees
+
+    Returns
+    -------
+    valid : bool
+      True if in and out-sequences are digraphic False if not.
+
+    Examples
+    --------
+    >>> G = nx.DiGraph([(1, 2), (1, 3), (2, 3), (3, 4), (4, 2), (5, 1), (5, 4)])
+    >>> in_seq = (d for n, d in G.in_degree())
+    >>> out_seq = (d for n, d in G.out_degree())
+    >>> nx.is_digraphical(in_seq, out_seq)
+    True
+
+    To test a non-digraphical scenario:
+    >>> in_seq_list = [d for n, d in G.in_degree()]
+    >>> in_seq_list[-1] += 1
+    >>> nx.is_digraphical(in_seq_list, out_seq)
+    False
+
+    Notes
+    -----
+    This algorithm is from Kleitman and Wang [1]_.
+    The worst case runtime is $O(s \times \log n)$ where $s$ and $n$ are the
+    sum and length of the sequences respectively.
+
+    References
+    ----------
+    .. [1] D.J. Kleitman and D.L. Wang
+       Algorithms for Constructing Graphs and Digraphs with Given Valences
+       and Factors, Discrete Mathematics, 6(1), pp. 79-88 (1973)
+    """
+    try:
+        in_deg_sequence = nx.utils.make_list_of_ints(in_sequence)
+        out_deg_sequence = nx.utils.make_list_of_ints(out_sequence)
+    except nx.NetworkXError:
+        return False
+    # Process the sequences and form two heaps to store degree pairs with
+    # either zero or non-zero out degrees
+    sumin, sumout, nin, nout = 0, 0, len(in_deg_sequence), len(out_deg_sequence)
+    maxn = max(nin, nout)
+    maxin = 0
+    if maxn == 0:
+        return True
+    stubheap, zeroheap = [], []
+    for n in range(maxn):
+        in_deg, out_deg = 0, 0
+        if n < nout:
+            out_deg = out_deg_sequence[n]
+        if n < nin:
+            in_deg = in_deg_sequence[n]
+        if in_deg < 0 or out_deg < 0:
+            return False
+        sumin, sumout, maxin = sumin + in_deg, sumout + out_deg, max(maxin, in_deg)
+        if in_deg > 0:
+            stubheap.append((-1 * out_deg, -1 * in_deg))
+        elif out_deg > 0:
+            zeroheap.append(-1 * out_deg)
+    if sumin != sumout:
+        return False
+    heapq.heapify(stubheap)
+    heapq.heapify(zeroheap)
+
+    modstubs = [(0, 0)] * (maxin + 1)
+    # Successively reduce degree sequence by removing the maximum out degree
+    while stubheap:
+        # Take the first value in the sequence with non-zero in degree
+        (freeout, freein) = heapq.heappop(stubheap)
+        freein *= -1
+        if freein > len(stubheap) + len(zeroheap):
+            return False
+
+        # Attach out stubs to the nodes with the most in stubs
+        mslen = 0
+        for i in range(freein):
+            if zeroheap and (not stubheap or stubheap[0][0] > zeroheap[0]):
+                stubout = heapq.heappop(zeroheap)
+                stubin = 0
+            else:
+                (stubout, stubin) = heapq.heappop(stubheap)
+            if stubout == 0:
+                return False
+            # Check if target is now totally connected
+            if stubout + 1 < 0 or stubin < 0:
+                modstubs[mslen] = (stubout + 1, stubin)
+                mslen += 1
+
+        # Add back the nodes to the heap that still have available stubs
+        for i in range(mslen):
+            stub = modstubs[i]
+            if stub[1] < 0:
+                heapq.heappush(stubheap, stub)
+            else:
+                heapq.heappush(zeroheap, stub[0])
+        if freeout < 0:
+            heapq.heappush(zeroheap, freeout)
+    return True
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/hierarchy.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/hierarchy.py
new file mode 100644
index 0000000000000000000000000000000000000000..d5a05525e7ddf1e98b1e07f120df0b0b5b52414b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/hierarchy.py
@@ -0,0 +1,57 @@
+"""
+Flow Hierarchy.
+"""
+
+import networkx as nx
+
+__all__ = ["flow_hierarchy"]
+
+
+@nx._dispatchable(edge_attrs="weight")
+def flow_hierarchy(G, weight=None):
+    """Returns the flow hierarchy of a directed network.
+
+    Flow hierarchy is defined as the fraction of edges not participating
+    in cycles in a directed graph [1]_.
+
+    Parameters
+    ----------
+    G : DiGraph or MultiDiGraph
+       A directed graph
+
+    weight : string, optional (default=None)
+       Attribute to use for edge weights. If None the weight defaults to 1.
+
+    Returns
+    -------
+    h : float
+       Flow hierarchy value
+
+    Raises
+    ------
+    NetworkXError
+       If `G` is not a directed graph or if `G` has no edges.
+
+    Notes
+    -----
+    The algorithm described in [1]_ computes the flow hierarchy through
+    exponentiation of the adjacency matrix.  This function implements an
+    alternative approach that finds strongly connected components.
+    An edge is in a cycle if and only if it is in a strongly connected
+    component, which can be found in $O(m)$ time using Tarjan's algorithm.
+
+    References
+    ----------
+    .. [1] Luo, J.; Magee, C.L. (2011),
+       Detecting evolving patterns of self-organizing networks by flow
+       hierarchy measurement, Complexity, Volume 16 Issue 6 53-61.
+       DOI: 10.1002/cplx.20368
+       http://web.mit.edu/~cmagee/www/documents/28-DetectingEvolvingPatterns_FlowHierarchy.pdf
+    """
+    # corner case: G has no edges
+    if nx.is_empty(G):
+        raise nx.NetworkXError("flow_hierarchy not applicable to empty graphs")
+    if not G.is_directed():
+        raise nx.NetworkXError("G must be a digraph in flow_hierarchy")
+    scc = nx.strongly_connected_components(G)
+    return 1 - sum(G.subgraph(c).size(weight) for c in scc) / G.size(weight)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/hybrid.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/hybrid.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d3dd3078cd25fb520a20f5866043ad977ef02f5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/hybrid.py
@@ -0,0 +1,196 @@
+"""
+Provides functions for finding and testing for locally `(k, l)`-connected
+graphs.
+
+"""
+
+import copy
+
+import networkx as nx
+
+__all__ = ["kl_connected_subgraph", "is_kl_connected"]
+
+
+@nx._dispatchable(returns_graph=True)
+def kl_connected_subgraph(G, k, l, low_memory=False, same_as_graph=False):
+    """Returns the maximum locally `(k, l)`-connected subgraph of `G`.
+
+    A graph is locally `(k, l)`-connected if for each edge `(u, v)` in the
+    graph there are at least `l` edge-disjoint paths of length at most `k`
+    joining `u` to `v`.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        The graph in which to find a maximum locally `(k, l)`-connected
+        subgraph.
+
+    k : integer
+        The maximum length of paths to consider. A higher number means a looser
+        connectivity requirement.
+
+    l : integer
+        The number of edge-disjoint paths. A higher number means a stricter
+        connectivity requirement.
+
+    low_memory : bool
+        If this is True, this function uses an algorithm that uses slightly
+        more time but less memory.
+
+    same_as_graph : bool
+        If True then return a tuple of the form `(H, is_same)`,
+        where `H` is the maximum locally `(k, l)`-connected subgraph and
+        `is_same` is a Boolean representing whether `G` is locally `(k,
+        l)`-connected (and hence, whether `H` is simply a copy of the input
+        graph `G`).
+
+    Returns
+    -------
+    NetworkX graph or two-tuple
+        If `same_as_graph` is True, then this function returns a
+        two-tuple as described above. Otherwise, it returns only the maximum
+        locally `(k, l)`-connected subgraph.
+
+    See also
+    --------
+    is_kl_connected
+
+    References
+    ----------
+    .. [1] Chung, Fan and Linyuan Lu. "The Small World Phenomenon in Hybrid
+           Power Law Graphs." *Complex Networks*. Springer Berlin Heidelberg,
+           2004. 89--104.
+
+    """
+    H = copy.deepcopy(G)  # subgraph we construct by removing from G
+
+    graphOK = True
+    deleted_some = True  # hack to start off the while loop
+    while deleted_some:
+        deleted_some = False
+        # We use `for edge in list(H.edges()):` instead of
+        # `for edge in H.edges():` because we edit the graph `H` in
+        # the loop. Hence using an iterator will result in
+        # `RuntimeError: dictionary changed size during iteration`
+        for edge in list(H.edges()):
+            (u, v) = edge
+            # Get copy of graph needed for this search
+            if low_memory:
+                verts = {u, v}
+                for i in range(k):
+                    for w in verts.copy():
+                        verts.update(G[w])
+                G2 = G.subgraph(verts).copy()
+            else:
+                G2 = copy.deepcopy(G)
+            ###
+            path = [u, v]
+            cnt = 0
+            accept = 0
+            while path:
+                cnt += 1  # Found a path
+                if cnt >= l:
+                    accept = 1
+                    break
+                # record edges along this graph
+                prev = u
+                for w in path:
+                    if prev != w:
+                        G2.remove_edge(prev, w)
+                        prev = w
+                #                path = shortest_path(G2, u, v, k) # ??? should "Cutoff" be k+1?
+                try:
+                    path = nx.shortest_path(G2, u, v)  # ??? should "Cutoff" be k+1?
+                except nx.NetworkXNoPath:
+                    path = False
+            # No Other Paths
+            if accept == 0:
+                H.remove_edge(u, v)
+                deleted_some = True
+                if graphOK:
+                    graphOK = False
+    # We looked through all edges and removed none of them.
+    # So, H is the maximal (k,l)-connected subgraph of G
+    if same_as_graph:
+        return (H, graphOK)
+    return H
+
+
+@nx._dispatchable
+def is_kl_connected(G, k, l, low_memory=False):
+    """Returns True if and only if `G` is locally `(k, l)`-connected.
+
+    A graph is locally `(k, l)`-connected if for each edge `(u, v)` in the
+    graph there are at least `l` edge-disjoint paths of length at most `k`
+    joining `u` to `v`.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        The graph to test for local `(k, l)`-connectedness.
+
+    k : integer
+        The maximum length of paths to consider. A higher number means a looser
+        connectivity requirement.
+
+    l : integer
+        The number of edge-disjoint paths. A higher number means a stricter
+        connectivity requirement.
+
+    low_memory : bool
+        If this is True, this function uses an algorithm that uses slightly
+        more time but less memory.
+
+    Returns
+    -------
+    bool
+        Whether the graph is locally `(k, l)`-connected subgraph.
+
+    See also
+    --------
+    kl_connected_subgraph
+
+    References
+    ----------
+    .. [1] Chung, Fan and Linyuan Lu. "The Small World Phenomenon in Hybrid
+           Power Law Graphs." *Complex Networks*. Springer Berlin Heidelberg,
+           2004. 89--104.
+
+    """
+    graphOK = True
+    for edge in G.edges():
+        (u, v) = edge
+        # Get copy of graph needed for this search
+        if low_memory:
+            verts = {u, v}
+            for i in range(k):
+                [verts.update(G.neighbors(w)) for w in verts.copy()]
+            G2 = G.subgraph(verts)
+        else:
+            G2 = copy.deepcopy(G)
+        ###
+        path = [u, v]
+        cnt = 0
+        accept = 0
+        while path:
+            cnt += 1  # Found a path
+            if cnt >= l:
+                accept = 1
+                break
+            # record edges along this graph
+            prev = u
+            for w in path:
+                if w != prev:
+                    G2.remove_edge(prev, w)
+                    prev = w
+            #            path = shortest_path(G2, u, v, k) # ??? should "Cutoff" be k+1?
+            try:
+                path = nx.shortest_path(G2, u, v)  # ??? should "Cutoff" be k+1?
+            except nx.NetworkXNoPath:
+                path = False
+        # No Other Paths
+        if accept == 0:
+            graphOK = False
+            break
+    # return status
+    return graphOK
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/isolate.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/isolate.py
new file mode 100644
index 0000000000000000000000000000000000000000..134cdff49f3a2b6079b13602309a66015af00f2c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/isolate.py
@@ -0,0 +1,107 @@
+"""
+Functions for identifying isolate (degree zero) nodes.
+"""
+
+import networkx as nx
+
+__all__ = ["is_isolate", "isolates", "number_of_isolates"]
+
+
+@nx._dispatchable
+def is_isolate(G, n):
+    """Determines whether a node is an isolate.
+
+    An *isolate* is a node with no neighbors (that is, with degree
+    zero). For directed graphs, this means no in-neighbors and no
+    out-neighbors.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    n : node
+        A node in `G`.
+
+    Returns
+    -------
+    is_isolate : bool
+       True if and only if `n` has no neighbors.
+
+    Examples
+    --------
+    >>> G = nx.Graph()
+    >>> G.add_edge(1, 2)
+    >>> G.add_node(3)
+    >>> nx.is_isolate(G, 2)
+    False
+    >>> nx.is_isolate(G, 3)
+    True
+    """
+    return G.degree(n) == 0
+
+
+@nx._dispatchable
+def isolates(G):
+    """Iterator over isolates in the graph.
+
+    An *isolate* is a node with no neighbors (that is, with degree
+    zero). For directed graphs, this means no in-neighbors and no
+    out-neighbors.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    Returns
+    -------
+    iterator
+        An iterator over the isolates of `G`.
+
+    Examples
+    --------
+    To get a list of all isolates of a graph, use the :class:`list`
+    constructor:
+
+    >>> G = nx.Graph()
+    >>> G.add_edge(1, 2)
+    >>> G.add_node(3)
+    >>> list(nx.isolates(G))
+    [3]
+
+    To remove all isolates in the graph, first create a list of the
+    isolates, then use :meth:`Graph.remove_nodes_from`:
+
+    >>> G.remove_nodes_from(list(nx.isolates(G)))
+    >>> list(G)
+    [1, 2]
+
+    For digraphs, isolates have zero in-degree and zero out_degree:
+
+    >>> G = nx.DiGraph([(0, 1), (1, 2)])
+    >>> G.add_node(3)
+    >>> list(nx.isolates(G))
+    [3]
+
+    """
+    return (n for n, d in G.degree() if d == 0)
+
+
+@nx._dispatchable
+def number_of_isolates(G):
+    """Returns the number of isolates in the graph.
+
+    An *isolate* is a node with no neighbors (that is, with degree
+    zero). For directed graphs, this means no in-neighbors and no
+    out-neighbors.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    Returns
+    -------
+    int
+        The number of degree zero nodes in the graph `G`.
+
+    """
+    return sum(1 for v in isolates(G))
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/link_analysis/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/link_analysis/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6009f000814753ab436278e2d2cc38e961e80f3f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/link_analysis/__init__.py
@@ -0,0 +1,2 @@
+from networkx.algorithms.link_analysis.hits_alg import *
+from networkx.algorithms.link_analysis.pagerank_alg import *
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/link_analysis/hits_alg.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/link_analysis/hits_alg.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a292f9b2b755d0711f6f8d760f3036736864a74
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/link_analysis/hits_alg.py
@@ -0,0 +1,337 @@
+"""Hubs and authorities analysis of graph structure."""
+
+import networkx as nx
+
+__all__ = ["hits"]
+
+
+@nx._dispatchable(preserve_edge_attrs={"G": {"weight": 1}})
+def hits(G, max_iter=100, tol=1.0e-8, nstart=None, normalized=True):
+    """Returns HITS hubs and authorities values for nodes.
+
+    The HITS algorithm computes two numbers for a node.
+    Authorities estimates the node value based on the incoming links.
+    Hubs estimates the node value based on outgoing links.
+
+    Parameters
+    ----------
+    G : graph
+      A NetworkX graph
+
+    max_iter : integer, optional
+      Maximum number of iterations in power method.
+
+    tol : float, optional
+      Error tolerance used to check convergence in power method iteration.
+
+    nstart : dictionary, optional
+      Starting value of each node for power method iteration.
+
+    normalized : bool (default=True)
+       Normalize results by the sum of all of the values.
+
+    Returns
+    -------
+    (hubs,authorities) : two-tuple of dictionaries
+       Two dictionaries keyed by node containing the hub and authority
+       values.
+
+    Raises
+    ------
+    PowerIterationFailedConvergence
+        If the algorithm fails to converge to the specified tolerance
+        within the specified number of iterations of the power iteration
+        method.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> h, a = nx.hits(G)
+
+    Notes
+    -----
+    The eigenvector calculation is done by the power iteration method
+    and has no guarantee of convergence.  The iteration will stop
+    after max_iter iterations or an error tolerance of
+    number_of_nodes(G)*tol has been reached.
+
+    The HITS algorithm was designed for directed graphs but this
+    algorithm does not check if the input graph is directed and will
+    execute on undirected graphs.
+
+    References
+    ----------
+    .. [1] A. Langville and C. Meyer,
+       "A survey of eigenvector methods of web information retrieval."
+       https://epubs.siam.org/doi/epdf/10.1137/S0036144503424786
+    .. [2] Jon Kleinberg,
+       Authoritative sources in a hyperlinked environment
+       Journal of the ACM 46 (5): 604-32, 1999.
+       https://www.cs.cornell.edu/home/kleinber/auth.pdf
+       doi:10.1145/324133.324140.
+    """
+    import numpy as np
+    import scipy as sp
+
+    if len(G) == 0:
+        return {}, {}
+    A = nx.adjacency_matrix(G, nodelist=list(G), dtype=float)
+
+    if nstart is not None:
+        nstart = np.array(list(nstart.values()))
+    if max_iter <= 0:
+        raise nx.PowerIterationFailedConvergence(max_iter)
+    try:
+        _, _, vt = sp.sparse.linalg.svds(A, k=1, v0=nstart, maxiter=max_iter, tol=tol)
+    except sp.sparse.linalg.ArpackNoConvergence as exc:
+        raise nx.PowerIterationFailedConvergence(max_iter) from exc
+
+    a = vt.flatten().real
+    h = A @ a
+    if normalized:
+        h /= h.sum()
+        a /= a.sum()
+    hubs = dict(zip(G, map(float, h)))
+    authorities = dict(zip(G, map(float, a)))
+    return hubs, authorities
+
+
+def _hits_python(G, max_iter=100, tol=1.0e-8, nstart=None, normalized=True):
+    if isinstance(G, nx.MultiGraph | nx.MultiDiGraph):
+        raise Exception("hits() not defined for graphs with multiedges.")
+    if len(G) == 0:
+        return {}, {}
+    # choose fixed starting vector if not given
+    if nstart is None:
+        h = dict.fromkeys(G, 1.0 / G.number_of_nodes())
+    else:
+        h = nstart
+        # normalize starting vector
+        s = 1.0 / sum(h.values())
+        for k in h:
+            h[k] *= s
+    for _ in range(max_iter):  # power iteration: make up to max_iter iterations
+        hlast = h
+        h = dict.fromkeys(hlast.keys(), 0)
+        a = dict.fromkeys(hlast.keys(), 0)
+        # this "matrix multiply" looks odd because it is
+        # doing a left multiply a^T=hlast^T*G
+        for n in h:
+            for nbr in G[n]:
+                a[nbr] += hlast[n] * G[n][nbr].get("weight", 1)
+        # now multiply h=Ga
+        for n in h:
+            for nbr in G[n]:
+                h[n] += a[nbr] * G[n][nbr].get("weight", 1)
+        # normalize vector
+        s = 1.0 / max(h.values())
+        for n in h:
+            h[n] *= s
+        # normalize vector
+        s = 1.0 / max(a.values())
+        for n in a:
+            a[n] *= s
+        # check convergence, l1 norm
+        err = sum(abs(h[n] - hlast[n]) for n in h)
+        if err < tol:
+            break
+    else:
+        raise nx.PowerIterationFailedConvergence(max_iter)
+    if normalized:
+        s = 1.0 / sum(a.values())
+        for n in a:
+            a[n] *= s
+        s = 1.0 / sum(h.values())
+        for n in h:
+            h[n] *= s
+    return h, a
+
+
+def _hits_numpy(G, normalized=True):
+    """Returns HITS hubs and authorities values for nodes.
+
+    The HITS algorithm computes two numbers for a node.
+    Authorities estimates the node value based on the incoming links.
+    Hubs estimates the node value based on outgoing links.
+
+    Parameters
+    ----------
+    G : graph
+      A NetworkX graph
+
+    normalized : bool (default=True)
+       Normalize results by the sum of all of the values.
+
+    Returns
+    -------
+    (hubs,authorities) : two-tuple of dictionaries
+       Two dictionaries keyed by node containing the hub and authority
+       values.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+
+    The `hubs` and `authorities` are given by the eigenvectors corresponding to the
+    maximum eigenvalues of the hubs_matrix and the authority_matrix, respectively.
+
+    The ``hubs`` and ``authority`` matrices are computed from the adjacency
+    matrix:
+
+    >>> adj_ary = nx.to_numpy_array(G)
+    >>> hubs_matrix = adj_ary @ adj_ary.T
+    >>> authority_matrix = adj_ary.T @ adj_ary
+
+    `_hits_numpy` maps the eigenvector corresponding to the maximum eigenvalue
+    of the respective matrices to the nodes in `G`:
+
+    >>> from networkx.algorithms.link_analysis.hits_alg import _hits_numpy
+    >>> hubs, authority = _hits_numpy(G)
+
+    Notes
+    -----
+    The eigenvector calculation uses NumPy's interface to LAPACK.
+
+    The HITS algorithm was designed for directed graphs but this
+    algorithm does not check if the input graph is directed and will
+    execute on undirected graphs.
+
+    References
+    ----------
+    .. [1] A. Langville and C. Meyer,
+       "A survey of eigenvector methods of web information retrieval."
+       http://citeseer.ist.psu.edu/713792.html
+    .. [2] Jon Kleinberg,
+       Authoritative sources in a hyperlinked environment
+       Journal of the ACM 46 (5): 604-32, 1999.
+       doi:10.1145/324133.324140.
+       http://www.cs.cornell.edu/home/kleinber/auth.pdf.
+    """
+    import numpy as np
+
+    if len(G) == 0:
+        return {}, {}
+    adj_ary = nx.to_numpy_array(G)
+    # Hub matrix
+    H = adj_ary @ adj_ary.T
+    e, ev = np.linalg.eig(H)
+    h = ev[:, np.argmax(e)]  # eigenvector corresponding to the maximum eigenvalue
+    # Authority matrix
+    A = adj_ary.T @ adj_ary
+    e, ev = np.linalg.eig(A)
+    a = ev[:, np.argmax(e)]  # eigenvector corresponding to the maximum eigenvalue
+    if normalized:
+        h /= h.sum()
+        a /= a.sum()
+    else:
+        h /= h.max()
+        a /= a.max()
+    hubs = dict(zip(G, map(float, h)))
+    authorities = dict(zip(G, map(float, a)))
+    return hubs, authorities
+
+
+def _hits_scipy(G, max_iter=100, tol=1.0e-6, nstart=None, normalized=True):
+    """Returns HITS hubs and authorities values for nodes.
+
+
+    The HITS algorithm computes two numbers for a node.
+    Authorities estimates the node value based on the incoming links.
+    Hubs estimates the node value based on outgoing links.
+
+    Parameters
+    ----------
+    G : graph
+      A NetworkX graph
+
+    max_iter : integer, optional
+      Maximum number of iterations in power method.
+
+    tol : float, optional
+      Error tolerance used to check convergence in power method iteration.
+
+    nstart : dictionary, optional
+      Starting value of each node for power method iteration.
+
+    normalized : bool (default=True)
+       Normalize results by the sum of all of the values.
+
+    Returns
+    -------
+    (hubs,authorities) : two-tuple of dictionaries
+       Two dictionaries keyed by node containing the hub and authority
+       values.
+
+    Examples
+    --------
+    >>> from networkx.algorithms.link_analysis.hits_alg import _hits_scipy
+    >>> G = nx.path_graph(4)
+    >>> h, a = _hits_scipy(G)
+
+    Notes
+    -----
+    This implementation uses SciPy sparse matrices.
+
+    The eigenvector calculation is done by the power iteration method
+    and has no guarantee of convergence.  The iteration will stop
+    after max_iter iterations or an error tolerance of
+    number_of_nodes(G)*tol has been reached.
+
+    The HITS algorithm was designed for directed graphs but this
+    algorithm does not check if the input graph is directed and will
+    execute on undirected graphs.
+
+    Raises
+    ------
+    PowerIterationFailedConvergence
+        If the algorithm fails to converge to the specified tolerance
+        within the specified number of iterations of the power iteration
+        method.
+
+    References
+    ----------
+    .. [1] A. Langville and C. Meyer,
+       "A survey of eigenvector methods of web information retrieval."
+       http://citeseer.ist.psu.edu/713792.html
+    .. [2] Jon Kleinberg,
+       Authoritative sources in a hyperlinked environment
+       Journal of the ACM 46 (5): 604-632, 1999.
+       doi:10.1145/324133.324140.
+       http://www.cs.cornell.edu/home/kleinber/auth.pdf.
+    """
+    import numpy as np
+
+    if len(G) == 0:
+        return {}, {}
+    A = nx.to_scipy_sparse_array(G, nodelist=list(G))
+    (n, _) = A.shape  # should be square
+    ATA = A.T @ A  # authority matrix
+    # choose fixed starting vector if not given
+    if nstart is None:
+        x = np.ones((n, 1)) / n
+    else:
+        x = np.array([nstart.get(n, 0) for n in list(G)], dtype=float)
+        x /= x.sum()
+
+    # power iteration on authority matrix
+    i = 0
+    while True:
+        xlast = x
+        x = ATA @ x
+        x /= x.max()
+        # check convergence, l1 norm
+        err = np.absolute(x - xlast).sum()
+        if err < tol:
+            break
+        if i > max_iter:
+            raise nx.PowerIterationFailedConvergence(max_iter)
+        i += 1
+
+    a = x.flatten()
+    h = A @ a
+    if normalized:
+        h /= h.sum()
+        a /= a.sum()
+    hubs = dict(zip(G, map(float, h)))
+    authorities = dict(zip(G, map(float, a)))
+    return hubs, authorities
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/link_analysis/pagerank_alg.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/link_analysis/pagerank_alg.py
new file mode 100644
index 0000000000000000000000000000000000000000..220d17350113e0e11b80f638cf29bfb5afdc7759
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/link_analysis/pagerank_alg.py
@@ -0,0 +1,498 @@
+"""PageRank analysis of graph structure."""
+
+import networkx as nx
+
+__all__ = ["pagerank", "google_matrix"]
+
+
+@nx._dispatchable(edge_attrs="weight")
+def pagerank(
+    G,
+    alpha=0.85,
+    personalization=None,
+    max_iter=100,
+    tol=1.0e-6,
+    nstart=None,
+    weight="weight",
+    dangling=None,
+):
+    """Returns the PageRank of the nodes in the graph.
+
+    PageRank computes a ranking of the nodes in the graph G based on
+    the structure of the incoming links. It was originally designed as
+    an algorithm to rank web pages.
+
+    Parameters
+    ----------
+    G : graph
+      A NetworkX graph.  Undirected graphs will be converted to a directed
+      graph with two directed edges for each undirected edge.
+
+    alpha : float, optional
+      Damping parameter for PageRank, default=0.85.
+
+    personalization: dict, optional
+      The "personalization vector" consisting of a dictionary with a
+      key some subset of graph nodes and personalization value each of those.
+      At least one personalization value must be non-zero.
+      If not specified, a nodes personalization value will be zero.
+      By default, a uniform distribution is used.
+
+    max_iter : integer, optional
+      Maximum number of iterations in power method eigenvalue solver.
+
+    tol : float, optional
+      Error tolerance used to check convergence in power method solver.
+      The iteration will stop after a tolerance of ``len(G) * tol`` is reached.
+
+    nstart : dictionary, optional
+      Starting value of PageRank iteration for each node.
+
+    weight : key, optional
+      Edge data key to use as weight.  If None weights are set to 1.
+
+    dangling: dict, optional
+      The outedges to be assigned to any "dangling" nodes, i.e., nodes without
+      any outedges. The dict key is the node the outedge points to and the dict
+      value is the weight of that outedge. By default, dangling nodes are given
+      outedges according to the personalization vector (uniform if not
+      specified). This must be selected to result in an irreducible transition
+      matrix (see notes under google_matrix). It may be common to have the
+      dangling dict to be the same as the personalization dict.
+
+
+    Returns
+    -------
+    pagerank : dictionary
+       Dictionary of nodes with PageRank as value
+
+    Examples
+    --------
+    >>> G = nx.DiGraph(nx.path_graph(4))
+    >>> pr = nx.pagerank(G, alpha=0.9)
+
+    Notes
+    -----
+    The eigenvector calculation is done by the power iteration method
+    and has no guarantee of convergence.  The iteration will stop after
+    an error tolerance of ``len(G) * tol`` has been reached. If the
+    number of iterations exceed `max_iter`, a
+    :exc:`networkx.exception.PowerIterationFailedConvergence` exception
+    is raised.
+
+    The PageRank algorithm was designed for directed graphs but this
+    algorithm does not check if the input graph is directed and will
+    execute on undirected graphs by converting each edge in the
+    directed graph to two edges.
+
+    See Also
+    --------
+    google_matrix
+    :func:`~networkx.algorithms.bipartite.link_analysis.birank`
+
+    Raises
+    ------
+    PowerIterationFailedConvergence
+        If the algorithm fails to converge to the specified tolerance
+        within the specified number of iterations of the power iteration
+        method.
+
+    References
+    ----------
+    .. [1] A. Langville and C. Meyer,
+       "A survey of eigenvector methods of web information retrieval."
+       http://citeseer.ist.psu.edu/713792.html
+    .. [2] Page, Lawrence; Brin, Sergey; Motwani, Rajeev and Winograd, Terry,
+       The PageRank citation ranking: Bringing order to the Web. 1999
+       http://dbpubs.stanford.edu:8090/pub/showDoc.Fulltext?lang=en&doc=1999-66&format=pdf
+
+    """
+    return _pagerank_scipy(
+        G, alpha, personalization, max_iter, tol, nstart, weight, dangling
+    )
+
+
+def _pagerank_python(
+    G,
+    alpha=0.85,
+    personalization=None,
+    max_iter=100,
+    tol=1.0e-6,
+    nstart=None,
+    weight="weight",
+    dangling=None,
+):
+    if len(G) == 0:
+        return {}
+
+    D = G.to_directed()
+
+    # Create a copy in (right) stochastic form
+    W = nx.stochastic_graph(D, weight=weight)
+    N = W.number_of_nodes()
+
+    # Choose fixed starting vector if not given
+    if nstart is None:
+        x = dict.fromkeys(W, 1.0 / N)
+    else:
+        # Normalized nstart vector
+        s = sum(nstart.values())
+        x = {k: v / s for k, v in nstart.items()}
+
+    if personalization is None:
+        # Assign uniform personalization vector if not given
+        p = dict.fromkeys(W, 1.0 / N)
+    else:
+        s = sum(personalization.values())
+        p = {k: v / s for k, v in personalization.items()}
+
+    if dangling is None:
+        # Use personalization vector if dangling vector not specified
+        dangling_weights = p
+    else:
+        s = sum(dangling.values())
+        dangling_weights = {k: v / s for k, v in dangling.items()}
+    dangling_nodes = [n for n in W if W.out_degree(n, weight=weight) == 0.0]
+
+    # power iteration: make up to max_iter iterations
+    for _ in range(max_iter):
+        xlast = x
+        x = dict.fromkeys(xlast.keys(), 0)
+        danglesum = alpha * sum(xlast[n] for n in dangling_nodes)
+        for n in x:
+            # this matrix multiply looks odd because it is
+            # doing a left multiply x^T=xlast^T*W
+            for _, nbr, wt in W.edges(n, data=weight):
+                x[nbr] += alpha * xlast[n] * wt
+            x[n] += danglesum * dangling_weights.get(n, 0) + (1.0 - alpha) * p.get(n, 0)
+        # check convergence, l1 norm
+        err = sum(abs(x[n] - xlast[n]) for n in x)
+        if err < N * tol:
+            return x
+    raise nx.PowerIterationFailedConvergence(max_iter)
+
+
+@nx._dispatchable(edge_attrs="weight")
+def google_matrix(
+    G, alpha=0.85, personalization=None, nodelist=None, weight="weight", dangling=None
+):
+    """Returns the Google matrix of the graph.
+
+    Parameters
+    ----------
+    G : graph
+      A NetworkX graph.  Undirected graphs will be converted to a directed
+      graph with two directed edges for each undirected edge.
+
+    alpha : float
+      The damping factor.
+
+    personalization: dict, optional
+      The "personalization vector" consisting of a dictionary with a
+      key some subset of graph nodes and personalization value each of those.
+      At least one personalization value must be non-zero.
+      If not specified, a nodes personalization value will be zero.
+      By default, a uniform distribution is used.
+
+    nodelist : list, optional
+      The rows and columns are ordered according to the nodes in nodelist.
+      If nodelist is None, then the ordering is produced by G.nodes().
+
+    weight : key, optional
+      Edge data key to use as weight.  If None weights are set to 1.
+
+    dangling: dict, optional
+      The outedges to be assigned to any "dangling" nodes, i.e., nodes without
+      any outedges. The dict key is the node the outedge points to and the dict
+      value is the weight of that outedge. By default, dangling nodes are given
+      outedges according to the personalization vector (uniform if not
+      specified) This must be selected to result in an irreducible transition
+      matrix (see notes below). It may be common to have the dangling dict to
+      be the same as the personalization dict.
+
+    Returns
+    -------
+    A : 2D NumPy ndarray
+       Google matrix of the graph
+
+    Notes
+    -----
+    The array returned represents the transition matrix that describes the
+    Markov chain used in PageRank. For PageRank to converge to a unique
+    solution (i.e., a unique stationary distribution in a Markov chain), the
+    transition matrix must be irreducible. In other words, it must be that
+    there exists a path between every pair of nodes in the graph, or else there
+    is the potential of "rank sinks."
+
+    This implementation works with Multi(Di)Graphs. For multigraphs the
+    weight between two nodes is set to be the sum of all edge weights
+    between those nodes.
+
+    See Also
+    --------
+    pagerank
+    """
+    import numpy as np
+
+    if nodelist is None:
+        nodelist = list(G)
+
+    A = nx.to_numpy_array(G, nodelist=nodelist, weight=weight)
+    N = len(G)
+    if N == 0:
+        return A
+
+    # Personalization vector
+    if personalization is None:
+        p = np.repeat(1.0 / N, N)
+    else:
+        p = np.array([personalization.get(n, 0) for n in nodelist], dtype=float)
+        if p.sum() == 0:
+            raise ZeroDivisionError
+        p /= p.sum()
+
+    # Dangling nodes
+    if dangling is None:
+        dangling_weights = p
+    else:
+        # Convert the dangling dictionary into an array in nodelist order
+        dangling_weights = np.array([dangling.get(n, 0) for n in nodelist], dtype=float)
+        dangling_weights /= dangling_weights.sum()
+    dangling_nodes = np.where(A.sum(axis=1) == 0)[0]
+
+    # Assign dangling_weights to any dangling nodes (nodes with no out links)
+    A[dangling_nodes] = dangling_weights
+
+    A /= A.sum(axis=1)[:, np.newaxis]  # Normalize rows to sum to 1
+
+    return alpha * A + (1 - alpha) * p
+
+
+def _pagerank_numpy(
+    G, alpha=0.85, personalization=None, weight="weight", dangling=None
+):
+    """Returns the PageRank of the nodes in the graph.
+
+    PageRank computes a ranking of the nodes in the graph G based on
+    the structure of the incoming links. It was originally designed as
+    an algorithm to rank web pages.
+
+    Parameters
+    ----------
+    G : graph
+      A NetworkX graph.  Undirected graphs will be converted to a directed
+      graph with two directed edges for each undirected edge.
+
+    alpha : float, optional
+      Damping parameter for PageRank, default=0.85.
+
+    personalization: dict, optional
+      The "personalization vector" consisting of a dictionary with a
+      key some subset of graph nodes and personalization value each of those.
+      At least one personalization value must be non-zero.
+      If not specified, a nodes personalization value will be zero.
+      By default, a uniform distribution is used.
+
+    weight : key, optional
+      Edge data key to use as weight.  If None weights are set to 1.
+
+    dangling: dict, optional
+      The outedges to be assigned to any "dangling" nodes, i.e., nodes without
+      any outedges. The dict key is the node the outedge points to and the dict
+      value is the weight of that outedge. By default, dangling nodes are given
+      outedges according to the personalization vector (uniform if not
+      specified) This must be selected to result in an irreducible transition
+      matrix (see notes under google_matrix). It may be common to have the
+      dangling dict to be the same as the personalization dict.
+
+    Returns
+    -------
+    pagerank : dictionary
+       Dictionary of nodes with PageRank as value.
+
+    Examples
+    --------
+    >>> from networkx.algorithms.link_analysis.pagerank_alg import _pagerank_numpy
+    >>> G = nx.DiGraph(nx.path_graph(4))
+    >>> pr = _pagerank_numpy(G, alpha=0.9)
+
+    Notes
+    -----
+    The eigenvector calculation uses NumPy's interface to the LAPACK
+    eigenvalue solvers.  This will be the fastest and most accurate
+    for small graphs.
+
+    This implementation works with Multi(Di)Graphs. For multigraphs the
+    weight between two nodes is set to be the sum of all edge weights
+    between those nodes.
+
+    See Also
+    --------
+    pagerank, google_matrix
+
+    References
+    ----------
+    .. [1] A. Langville and C. Meyer,
+       "A survey of eigenvector methods of web information retrieval."
+       http://citeseer.ist.psu.edu/713792.html
+    .. [2] Page, Lawrence; Brin, Sergey; Motwani, Rajeev and Winograd, Terry,
+       The PageRank citation ranking: Bringing order to the Web. 1999
+       http://dbpubs.stanford.edu:8090/pub/showDoc.Fulltext?lang=en&doc=1999-66&format=pdf
+    """
+    import numpy as np
+
+    if len(G) == 0:
+        return {}
+    M = google_matrix(
+        G, alpha, personalization=personalization, weight=weight, dangling=dangling
+    )
+    # use numpy LAPACK solver
+    eigenvalues, eigenvectors = np.linalg.eig(M.T)
+    ind = np.argmax(eigenvalues)
+    # eigenvector of largest eigenvalue is at ind, normalized
+    largest = np.array(eigenvectors[:, ind]).flatten().real
+    norm = largest.sum()
+    return dict(zip(G, map(float, largest / norm)))
+
+
+def _pagerank_scipy(
+    G,
+    alpha=0.85,
+    personalization=None,
+    max_iter=100,
+    tol=1.0e-6,
+    nstart=None,
+    weight="weight",
+    dangling=None,
+):
+    """Returns the PageRank of the nodes in the graph.
+
+    PageRank computes a ranking of the nodes in the graph G based on
+    the structure of the incoming links. It was originally designed as
+    an algorithm to rank web pages.
+
+    Parameters
+    ----------
+    G : graph
+      A NetworkX graph.  Undirected graphs will be converted to a directed
+      graph with two directed edges for each undirected edge.
+
+    alpha : float, optional
+      Damping parameter for PageRank, default=0.85.
+
+    personalization: dict, optional
+      The "personalization vector" consisting of a dictionary with a
+      key some subset of graph nodes and personalization value each of those.
+      At least one personalization value must be non-zero.
+      If not specified, a nodes personalization value will be zero.
+      By default, a uniform distribution is used.
+
+    max_iter : integer, optional
+      Maximum number of iterations in power method eigenvalue solver.
+
+    tol : float, optional
+      Error tolerance used to check convergence in power method solver.
+      The iteration will stop after a tolerance of ``len(G) * tol`` is reached.
+
+    nstart : dictionary, optional
+      Starting value of PageRank iteration for each node.
+
+    weight : key, optional
+      Edge data key to use as weight.  If None weights are set to 1.
+
+    dangling: dict, optional
+      The outedges to be assigned to any "dangling" nodes, i.e., nodes without
+      any outedges. The dict key is the node the outedge points to and the dict
+      value is the weight of that outedge. By default, dangling nodes are given
+      outedges according to the personalization vector (uniform if not
+      specified) This must be selected to result in an irreducible transition
+      matrix (see notes under google_matrix). It may be common to have the
+      dangling dict to be the same as the personalization dict.
+
+    Returns
+    -------
+    pagerank : dictionary
+       Dictionary of nodes with PageRank as value
+
+    Examples
+    --------
+    >>> from networkx.algorithms.link_analysis.pagerank_alg import _pagerank_scipy
+    >>> G = nx.DiGraph(nx.path_graph(4))
+    >>> pr = _pagerank_scipy(G, alpha=0.9)
+
+    Notes
+    -----
+    The eigenvector calculation uses power iteration with a SciPy
+    sparse matrix representation.
+
+    This implementation works with Multi(Di)Graphs. For multigraphs the
+    weight between two nodes is set to be the sum of all edge weights
+    between those nodes.
+
+    See Also
+    --------
+    pagerank
+
+    Raises
+    ------
+    PowerIterationFailedConvergence
+        If the algorithm fails to converge to the specified tolerance
+        within the specified number of iterations of the power iteration
+        method.
+
+    References
+    ----------
+    .. [1] A. Langville and C. Meyer,
+       "A survey of eigenvector methods of web information retrieval."
+       http://citeseer.ist.psu.edu/713792.html
+    .. [2] Page, Lawrence; Brin, Sergey; Motwani, Rajeev and Winograd, Terry,
+       The PageRank citation ranking: Bringing order to the Web. 1999
+       http://dbpubs.stanford.edu:8090/pub/showDoc.Fulltext?lang=en&doc=1999-66&format=pdf
+    """
+    import numpy as np
+    import scipy as sp
+
+    N = len(G)
+    if N == 0:
+        return {}
+
+    nodelist = list(G)
+    A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, dtype=float)
+    S = A.sum(axis=1)
+    S[S != 0] = 1.0 / S[S != 0]
+    Q = sp.sparse.dia_array((S.T, 0), shape=A.shape).tocsr()
+    A = Q @ A
+
+    # initial vector
+    if nstart is None:
+        x = np.repeat(1.0 / N, N)
+    else:
+        x = np.array([nstart.get(n, 0) for n in nodelist], dtype=float)
+        x /= x.sum()
+
+    # Personalization vector
+    if personalization is None:
+        p = np.repeat(1.0 / N, N)
+    else:
+        p = np.array([personalization.get(n, 0) for n in nodelist], dtype=float)
+        if p.sum() == 0:
+            raise ZeroDivisionError
+        p /= p.sum()
+    # Dangling nodes
+    if dangling is None:
+        dangling_weights = p
+    else:
+        # Convert the dangling dictionary into an array in nodelist order
+        dangling_weights = np.array([dangling.get(n, 0) for n in nodelist], dtype=float)
+        dangling_weights /= dangling_weights.sum()
+    is_dangling = np.where(S == 0)[0]
+
+    # power iteration: make up to max_iter iterations
+    for _ in range(max_iter):
+        xlast = x
+        x = alpha * (x @ A + sum(x[is_dangling]) * dangling_weights) + (1 - alpha) * p
+        # check convergence, l1 norm
+        err = np.absolute(x - xlast).sum()
+        if err < N * tol:
+            return dict(zip(nodelist, map(float, x)))
+    raise nx.PowerIterationFailedConvergence(max_iter)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/link_prediction.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/link_prediction.py
new file mode 100644
index 0000000000000000000000000000000000000000..3615f26deb6d3c2f3c01e55f3fcf8ca3361968b3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/link_prediction.py
@@ -0,0 +1,687 @@
+"""
+Link prediction algorithms.
+"""
+
+from math import log
+
+import networkx as nx
+from networkx.utils import not_implemented_for
+
+__all__ = [
+    "resource_allocation_index",
+    "jaccard_coefficient",
+    "adamic_adar_index",
+    "preferential_attachment",
+    "cn_soundarajan_hopcroft",
+    "ra_index_soundarajan_hopcroft",
+    "within_inter_cluster",
+    "common_neighbor_centrality",
+]
+
+
+def _apply_prediction(G, func, ebunch=None):
+    """Applies the given function to each edge in the specified iterable
+    of edges.
+
+    `G` is an instance of :class:`networkx.Graph`.
+
+    `func` is a function on two inputs, each of which is a node in the
+    graph. The function can return anything, but it should return a
+    value representing a prediction of the likelihood of a "link"
+    joining the two nodes.
+
+    `ebunch` is an iterable of pairs of nodes. If not specified, all
+    non-edges in the graph `G` will be used.
+
+    """
+    if ebunch is None:
+        ebunch = nx.non_edges(G)
+    else:
+        for u, v in ebunch:
+            if u not in G:
+                raise nx.NodeNotFound(f"Node {u} not in G.")
+            if v not in G:
+                raise nx.NodeNotFound(f"Node {v} not in G.")
+    return ((u, v, func(u, v)) for u, v in ebunch)
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable
+def resource_allocation_index(G, ebunch=None):
+    r"""Compute the resource allocation index of all node pairs in ebunch.
+
+    Resource allocation index of `u` and `v` is defined as
+
+    .. math::
+
+        \sum_{w \in \Gamma(u) \cap \Gamma(v)} \frac{1}{|\Gamma(w)|}
+
+    where $\Gamma(u)$ denotes the set of neighbors of $u$.
+
+    Parameters
+    ----------
+    G : graph
+        A NetworkX undirected graph.
+
+    ebunch : iterable of node pairs, optional (default = None)
+        Resource allocation index will be computed for each pair of
+        nodes given in the iterable. The pairs must be given as
+        2-tuples (u, v) where u and v are nodes in the graph. If ebunch
+        is None then all nonexistent edges in the graph will be used.
+        Default value: None.
+
+    Returns
+    -------
+    piter : iterator
+        An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
+        pair of nodes and p is their resource allocation index.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.
+
+    NodeNotFound
+        If `ebunch` has a node that is not in `G`.
+
+    Examples
+    --------
+    >>> G = nx.complete_graph(5)
+    >>> preds = nx.resource_allocation_index(G, [(0, 1), (2, 3)])
+    >>> for u, v, p in preds:
+    ...     print(f"({u}, {v}) -> {p:.8f}")
+    (0, 1) -> 0.75000000
+    (2, 3) -> 0.75000000
+
+    References
+    ----------
+    .. [1] T. Zhou, L. Lu, Y.-C. Zhang.
+       Predicting missing links via local information.
+       Eur. Phys. J. B 71 (2009) 623.
+       https://arxiv.org/pdf/0901.0553.pdf
+    """
+
+    def predict(u, v):
+        return sum(1 / G.degree(w) for w in nx.common_neighbors(G, u, v))
+
+    return _apply_prediction(G, predict, ebunch)
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable
+def jaccard_coefficient(G, ebunch=None):
+    r"""Compute the Jaccard coefficient of all node pairs in ebunch.
+
+    Jaccard coefficient of nodes `u` and `v` is defined as
+
+    .. math::
+
+        \frac{|\Gamma(u) \cap \Gamma(v)|}{|\Gamma(u) \cup \Gamma(v)|}
+
+    where $\Gamma(u)$ denotes the set of neighbors of $u$.
+
+    Parameters
+    ----------
+    G : graph
+        A NetworkX undirected graph.
+
+    ebunch : iterable of node pairs, optional (default = None)
+        Jaccard coefficient will be computed for each pair of nodes
+        given in the iterable. The pairs must be given as 2-tuples
+        (u, v) where u and v are nodes in the graph. If ebunch is None
+        then all nonexistent edges in the graph will be used.
+        Default value: None.
+
+    Returns
+    -------
+    piter : iterator
+        An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
+        pair of nodes and p is their Jaccard coefficient.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.
+
+    NodeNotFound
+        If `ebunch` has a node that is not in `G`.
+
+    Examples
+    --------
+    >>> G = nx.complete_graph(5)
+    >>> preds = nx.jaccard_coefficient(G, [(0, 1), (2, 3)])
+    >>> for u, v, p in preds:
+    ...     print(f"({u}, {v}) -> {p:.8f}")
+    (0, 1) -> 0.60000000
+    (2, 3) -> 0.60000000
+
+    References
+    ----------
+    .. [1] D. Liben-Nowell, J. Kleinberg.
+           The Link Prediction Problem for Social Networks (2004).
+           http://www.cs.cornell.edu/home/kleinber/link-pred.pdf
+    """
+
+    def predict(u, v):
+        union_size = len(set(G[u]) | set(G[v]))
+        if union_size == 0:
+            return 0
+        return len(nx.common_neighbors(G, u, v)) / union_size
+
+    return _apply_prediction(G, predict, ebunch)
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable
+def adamic_adar_index(G, ebunch=None):
+    r"""Compute the Adamic-Adar index of all node pairs in ebunch.
+
+    Adamic-Adar index of `u` and `v` is defined as
+
+    .. math::
+
+        \sum_{w \in \Gamma(u) \cap \Gamma(v)} \frac{1}{\log |\Gamma(w)|}
+
+    where $\Gamma(u)$ denotes the set of neighbors of $u$.
+    This index leads to zero-division for nodes only connected via self-loops.
+    It is intended to be used when no self-loops are present.
+
+    Parameters
+    ----------
+    G : graph
+        NetworkX undirected graph.
+
+    ebunch : iterable of node pairs, optional (default = None)
+        Adamic-Adar index will be computed for each pair of nodes given
+        in the iterable. The pairs must be given as 2-tuples (u, v)
+        where u and v are nodes in the graph. If ebunch is None then all
+        nonexistent edges in the graph will be used.
+        Default value: None.
+
+    Returns
+    -------
+    piter : iterator
+        An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
+        pair of nodes and p is their Adamic-Adar index.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.
+
+    NodeNotFound
+        If `ebunch` has a node that is not in `G`.
+
+    Examples
+    --------
+    >>> G = nx.complete_graph(5)
+    >>> preds = nx.adamic_adar_index(G, [(0, 1), (2, 3)])
+    >>> for u, v, p in preds:
+    ...     print(f"({u}, {v}) -> {p:.8f}")
+    (0, 1) -> 2.16404256
+    (2, 3) -> 2.16404256
+
+    References
+    ----------
+    .. [1] D. Liben-Nowell, J. Kleinberg.
+           The Link Prediction Problem for Social Networks (2004).
+           http://www.cs.cornell.edu/home/kleinber/link-pred.pdf
+    """
+
+    def predict(u, v):
+        return sum(1 / log(G.degree(w)) for w in nx.common_neighbors(G, u, v))
+
+    return _apply_prediction(G, predict, ebunch)
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable
+def common_neighbor_centrality(G, ebunch=None, alpha=0.8):
+    r"""Return the CCPA score for each pair of nodes.
+
+    Compute the Common Neighbor and Centrality based Parameterized Algorithm(CCPA)
+    score of all node pairs in ebunch.
+
+    CCPA score of `u` and `v` is defined as
+
+    .. math::
+
+        \alpha \cdot (|\Gamma (u){\cap }^{}\Gamma (v)|)+(1-\alpha )\cdot \frac{N}{{d}_{uv}}
+
+    where $\Gamma(u)$ denotes the set of neighbors of $u$, $\Gamma(v)$ denotes the
+    set of neighbors of $v$, $\alpha$ is  parameter varies between [0,1], $N$ denotes
+    total number of nodes in the Graph and ${d}_{uv}$ denotes shortest distance
+    between $u$ and $v$.
+
+    This algorithm is based on two vital properties of nodes, namely the number
+    of common neighbors and their centrality. Common neighbor refers to the common
+    nodes between two nodes. Centrality refers to the prestige that a node enjoys
+    in a network.
+
+    .. seealso::
+
+        :func:`common_neighbors`
+
+    Parameters
+    ----------
+    G : graph
+        NetworkX undirected graph.
+
+    ebunch : iterable of node pairs, optional (default = None)
+        Preferential attachment score will be computed for each pair of
+        nodes given in the iterable. The pairs must be given as
+        2-tuples (u, v) where u and v are nodes in the graph. If ebunch
+        is None then all nonexistent edges in the graph will be used.
+        Default value: None.
+
+    alpha : Parameter defined for participation of Common Neighbor
+            and Centrality Algorithm share. Values for alpha should
+            normally be between 0 and 1. Default value set to 0.8
+            because author found better performance at 0.8 for all the
+            dataset.
+            Default value: 0.8
+
+
+    Returns
+    -------
+    piter : iterator
+        An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
+        pair of nodes and p is their Common Neighbor and Centrality based
+        Parameterized Algorithm(CCPA) score.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.
+
+    NetworkXAlgorithmError
+        If self loops exist in `ebunch` or in `G` (if `ebunch` is `None`).
+
+    NodeNotFound
+        If `ebunch` has a node that is not in `G`.
+
+    Examples
+    --------
+    >>> G = nx.complete_graph(5)
+    >>> preds = nx.common_neighbor_centrality(G, [(0, 1), (2, 3)])
+    >>> for u, v, p in preds:
+    ...     print(f"({u}, {v}) -> {p}")
+    (0, 1) -> 3.4000000000000004
+    (2, 3) -> 3.4000000000000004
+
+    References
+    ----------
+    .. [1] Ahmad, I., Akhtar, M.U., Noor, S. et al.
+           Missing Link Prediction using Common Neighbor and Centrality based Parameterized Algorithm.
+           Sci Rep 10, 364 (2020).
+           https://doi.org/10.1038/s41598-019-57304-y
+    """
+
+    # When alpha == 1, the CCPA score simplifies to the number of common neighbors.
+    if alpha == 1:
+
+        def predict(u, v):
+            if u == v:
+                raise nx.NetworkXAlgorithmError("Self loops are not supported")
+
+            return len(nx.common_neighbors(G, u, v))
+
+    else:
+        spl = dict(nx.shortest_path_length(G))
+        inf = float("inf")
+
+        def predict(u, v):
+            if u == v:
+                raise nx.NetworkXAlgorithmError("Self loops are not supported")
+            path_len = spl[u].get(v, inf)
+
+            n_nbrs = len(nx.common_neighbors(G, u, v))
+            return alpha * n_nbrs + (1 - alpha) * len(G) / path_len
+
+    return _apply_prediction(G, predict, ebunch)
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable
+def preferential_attachment(G, ebunch=None):
+    r"""Compute the preferential attachment score of all node pairs in ebunch.
+
+    Preferential attachment score of `u` and `v` is defined as
+
+    .. math::
+
+        |\Gamma(u)| |\Gamma(v)|
+
+    where $\Gamma(u)$ denotes the set of neighbors of $u$.
+
+    Parameters
+    ----------
+    G : graph
+        NetworkX undirected graph.
+
+    ebunch : iterable of node pairs, optional (default = None)
+        Preferential attachment score will be computed for each pair of
+        nodes given in the iterable. The pairs must be given as
+        2-tuples (u, v) where u and v are nodes in the graph. If ebunch
+        is None then all nonexistent edges in the graph will be used.
+        Default value: None.
+
+    Returns
+    -------
+    piter : iterator
+        An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
+        pair of nodes and p is their preferential attachment score.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.
+
+    NodeNotFound
+        If `ebunch` has a node that is not in `G`.
+
+    Examples
+    --------
+    >>> G = nx.complete_graph(5)
+    >>> preds = nx.preferential_attachment(G, [(0, 1), (2, 3)])
+    >>> for u, v, p in preds:
+    ...     print(f"({u}, {v}) -> {p}")
+    (0, 1) -> 16
+    (2, 3) -> 16
+
+    References
+    ----------
+    .. [1] D. Liben-Nowell, J. Kleinberg.
+           The Link Prediction Problem for Social Networks (2004).
+           http://www.cs.cornell.edu/home/kleinber/link-pred.pdf
+    """
+
+    def predict(u, v):
+        return G.degree(u) * G.degree(v)
+
+    return _apply_prediction(G, predict, ebunch)
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable(node_attrs="community")
+def cn_soundarajan_hopcroft(G, ebunch=None, community="community"):
+    r"""Count the number of common neighbors of all node pairs in ebunch
+        using community information.
+
+    For two nodes $u$ and $v$, this function computes the number of
+    common neighbors and bonus one for each common neighbor belonging to
+    the same community as $u$ and $v$. Mathematically,
+
+    .. math::
+
+        |\Gamma(u) \cap \Gamma(v)| + \sum_{w \in \Gamma(u) \cap \Gamma(v)} f(w)
+
+    where $f(w)$ equals 1 if $w$ belongs to the same community as $u$
+    and $v$ or 0 otherwise and $\Gamma(u)$ denotes the set of
+    neighbors of $u$.
+
+    Parameters
+    ----------
+    G : graph
+        A NetworkX undirected graph.
+
+    ebunch : iterable of node pairs, optional (default = None)
+        The score will be computed for each pair of nodes given in the
+        iterable. The pairs must be given as 2-tuples (u, v) where u
+        and v are nodes in the graph. If ebunch is None then all
+        nonexistent edges in the graph will be used.
+        Default value: None.
+
+    community : string, optional (default = 'community')
+        Nodes attribute name containing the community information.
+        G[u][community] identifies which community u belongs to. Each
+        node belongs to at most one community. Default value: 'community'.
+
+    Returns
+    -------
+    piter : iterator
+        An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
+        pair of nodes and p is their score.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.
+
+    NetworkXAlgorithmError
+        If no community information is available for a node in `ebunch` or in `G` (if `ebunch` is `None`).
+
+    NodeNotFound
+        If `ebunch` has a node that is not in `G`.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(3)
+    >>> G.nodes[0]["community"] = 0
+    >>> G.nodes[1]["community"] = 0
+    >>> G.nodes[2]["community"] = 0
+    >>> preds = nx.cn_soundarajan_hopcroft(G, [(0, 2)])
+    >>> for u, v, p in preds:
+    ...     print(f"({u}, {v}) -> {p}")
+    (0, 2) -> 2
+
+    References
+    ----------
+    .. [1] Sucheta Soundarajan and John Hopcroft.
+       Using community information to improve the precision of link
+       prediction methods.
+       In Proceedings of the 21st international conference companion on
+       World Wide Web (WWW '12 Companion). ACM, New York, NY, USA, 607-608.
+       http://doi.acm.org/10.1145/2187980.2188150
+    """
+
+    def predict(u, v):
+        Cu = _community(G, u, community)
+        Cv = _community(G, v, community)
+        cnbors = nx.common_neighbors(G, u, v)
+        neighbors = (
+            sum(_community(G, w, community) == Cu for w in cnbors) if Cu == Cv else 0
+        )
+        return len(cnbors) + neighbors
+
+    return _apply_prediction(G, predict, ebunch)
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable(node_attrs="community")
+def ra_index_soundarajan_hopcroft(G, ebunch=None, community="community"):
+    r"""Compute the resource allocation index of all node pairs in
+    ebunch using community information.
+
+    For two nodes $u$ and $v$, this function computes the resource
+    allocation index considering only common neighbors belonging to the
+    same community as $u$ and $v$. Mathematically,
+
+    .. math::
+
+        \sum_{w \in \Gamma(u) \cap \Gamma(v)} \frac{f(w)}{|\Gamma(w)|}
+
+    where $f(w)$ equals 1 if $w$ belongs to the same community as $u$
+    and $v$ or 0 otherwise and $\Gamma(u)$ denotes the set of
+    neighbors of $u$.
+
+    Parameters
+    ----------
+    G : graph
+        A NetworkX undirected graph.
+
+    ebunch : iterable of node pairs, optional (default = None)
+        The score will be computed for each pair of nodes given in the
+        iterable. The pairs must be given as 2-tuples (u, v) where u
+        and v are nodes in the graph. If ebunch is None then all
+        nonexistent edges in the graph will be used.
+        Default value: None.
+
+    community : string, optional (default = 'community')
+        Nodes attribute name containing the community information.
+        G[u][community] identifies which community u belongs to. Each
+        node belongs to at most one community. Default value: 'community'.
+
+    Returns
+    -------
+    piter : iterator
+        An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
+        pair of nodes and p is their score.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.
+
+    NetworkXAlgorithmError
+        If no community information is available for a node in `ebunch` or in `G` (if `ebunch` is `None`).
+
+    NodeNotFound
+        If `ebunch` has a node that is not in `G`.
+
+    Examples
+    --------
+    >>> G = nx.Graph()
+    >>> G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
+    >>> G.nodes[0]["community"] = 0
+    >>> G.nodes[1]["community"] = 0
+    >>> G.nodes[2]["community"] = 1
+    >>> G.nodes[3]["community"] = 0
+    >>> preds = nx.ra_index_soundarajan_hopcroft(G, [(0, 3)])
+    >>> for u, v, p in preds:
+    ...     print(f"({u}, {v}) -> {p:.8f}")
+    (0, 3) -> 0.50000000
+
+    References
+    ----------
+    .. [1] Sucheta Soundarajan and John Hopcroft.
+       Using community information to improve the precision of link
+       prediction methods.
+       In Proceedings of the 21st international conference companion on
+       World Wide Web (WWW '12 Companion). ACM, New York, NY, USA, 607-608.
+       http://doi.acm.org/10.1145/2187980.2188150
+    """
+
+    def predict(u, v):
+        Cu = _community(G, u, community)
+        Cv = _community(G, v, community)
+        if Cu != Cv:
+            return 0
+        cnbors = nx.common_neighbors(G, u, v)
+        return sum(1 / G.degree(w) for w in cnbors if _community(G, w, community) == Cu)
+
+    return _apply_prediction(G, predict, ebunch)
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable(node_attrs="community")
+def within_inter_cluster(G, ebunch=None, delta=0.001, community="community"):
+    """Compute the ratio of within- and inter-cluster common neighbors
+    of all node pairs in ebunch.
+
+    For two nodes `u` and `v`, if a common neighbor `w` belongs to the
+    same community as them, `w` is considered as within-cluster common
+    neighbor of `u` and `v`. Otherwise, it is considered as
+    inter-cluster common neighbor of `u` and `v`. The ratio between the
+    size of the set of within- and inter-cluster common neighbors is
+    defined as the WIC measure. [1]_
+
+    Parameters
+    ----------
+    G : graph
+        A NetworkX undirected graph.
+
+    ebunch : iterable of node pairs, optional (default = None)
+        The WIC measure will be computed for each pair of nodes given in
+        the iterable. The pairs must be given as 2-tuples (u, v) where
+        u and v are nodes in the graph. If ebunch is None then all
+        nonexistent edges in the graph will be used.
+        Default value: None.
+
+    delta : float, optional (default = 0.001)
+        Value to prevent division by zero in case there is no
+        inter-cluster common neighbor between two nodes. See [1]_ for
+        details. Default value: 0.001.
+
+    community : string, optional (default = 'community')
+        Nodes attribute name containing the community information.
+        G[u][community] identifies which community u belongs to. Each
+        node belongs to at most one community. Default value: 'community'.
+
+    Returns
+    -------
+    piter : iterator
+        An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
+        pair of nodes and p is their WIC measure.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.
+
+    NetworkXAlgorithmError
+        - If `delta` is less than or equal to zero.
+        - If no community information is available for a node in `ebunch` or in `G` (if `ebunch` is `None`).
+
+    NodeNotFound
+        If `ebunch` has a node that is not in `G`.
+
+    Examples
+    --------
+    >>> G = nx.Graph()
+    >>> G.add_edges_from([(0, 1), (0, 2), (0, 3), (1, 4), (2, 4), (3, 4)])
+    >>> G.nodes[0]["community"] = 0
+    >>> G.nodes[1]["community"] = 1
+    >>> G.nodes[2]["community"] = 0
+    >>> G.nodes[3]["community"] = 0
+    >>> G.nodes[4]["community"] = 0
+    >>> preds = nx.within_inter_cluster(G, [(0, 4)])
+    >>> for u, v, p in preds:
+    ...     print(f"({u}, {v}) -> {p:.8f}")
+    (0, 4) -> 1.99800200
+    >>> preds = nx.within_inter_cluster(G, [(0, 4)], delta=0.5)
+    >>> for u, v, p in preds:
+    ...     print(f"({u}, {v}) -> {p:.8f}")
+    (0, 4) -> 1.33333333
+
+    References
+    ----------
+    .. [1] Jorge Carlos Valverde-Rebaza and Alneu de Andrade Lopes.
+       Link prediction in complex networks based on cluster information.
+       In Proceedings of the 21st Brazilian conference on Advances in
+       Artificial Intelligence (SBIA'12)
+       https://doi.org/10.1007/978-3-642-34459-6_10
+    """
+    if delta <= 0:
+        raise nx.NetworkXAlgorithmError("Delta must be greater than zero")
+
+    def predict(u, v):
+        Cu = _community(G, u, community)
+        Cv = _community(G, v, community)
+        if Cu != Cv:
+            return 0
+        cnbors = nx.common_neighbors(G, u, v)
+        within = {w for w in cnbors if _community(G, w, community) == Cu}
+        inter = cnbors - within
+        return len(within) / (len(inter) + delta)
+
+    return _apply_prediction(G, predict, ebunch)
+
+
+def _community(G, u, community):
+    """Get the community of the given node."""
+    node_u = G.nodes[u]
+    try:
+        return node_u[community]
+    except KeyError as err:
+        raise nx.NetworkXAlgorithmError(
+            f"No community information available for Node {u}"
+        ) from err
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/lowest_common_ancestors.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/lowest_common_ancestors.py
new file mode 100644
index 0000000000000000000000000000000000000000..963a7839800b11d621a35e3e44b87711cbe40d63
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/lowest_common_ancestors.py
@@ -0,0 +1,280 @@
+"""Algorithms for finding the lowest common ancestor of trees and DAGs."""
+
+from collections import defaultdict
+from collections.abc import Mapping, Set
+from itertools import combinations_with_replacement
+
+import networkx as nx
+from networkx.utils import UnionFind, arbitrary_element, not_implemented_for
+
+__all__ = [
+    "all_pairs_lowest_common_ancestor",
+    "tree_all_pairs_lowest_common_ancestor",
+    "lowest_common_ancestor",
+]
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable
+def all_pairs_lowest_common_ancestor(G, pairs=None):
+    """Return the lowest common ancestor of all pairs or the provided pairs
+
+    Parameters
+    ----------
+    G : NetworkX directed graph
+
+    pairs : iterable of pairs of nodes, optional (default: all pairs)
+        The pairs of nodes of interest.
+        If None, will find the LCA of all pairs of nodes.
+
+    Yields
+    ------
+    ((node1, node2), lca) : 2-tuple
+        Where lca is least common ancestor of node1 and node2.
+        Note that for the default case, the order of the node pair is not considered,
+        e.g. you will not get both ``(a, b)`` and ``(b, a)``
+
+    Raises
+    ------
+    NetworkXPointlessConcept
+        If `G` is null.
+    NetworkXError
+        If `G` is not a DAG.
+
+    Examples
+    --------
+    >>> from pprint import pprint
+
+    The default behavior is to yield the lowest common ancestor for all
+    possible combinations of nodes in `G`, including self-pairings:
+
+    >>> G = nx.DiGraph([(0, 1), (0, 3), (1, 2)])
+    >>> pprint(dict(nx.all_pairs_lowest_common_ancestor(G)))
+    {(0, 0): 0,
+     (0, 1): 0,
+     (0, 2): 0,
+     (0, 3): 0,
+     (1, 1): 1,
+     (1, 2): 1,
+     (1, 3): 0,
+     (2, 2): 2,
+     (3, 2): 0,
+     (3, 3): 3}
+
+    The pairs argument can be used to limit the output to only the
+    specified node pairings:
+
+    >>> dict(nx.all_pairs_lowest_common_ancestor(G, pairs=[(1, 2), (2, 3)]))
+    {(1, 2): 1, (2, 3): 0}
+
+    Notes
+    -----
+    Only defined on non-null directed acyclic graphs.
+
+    See Also
+    --------
+    lowest_common_ancestor
+    """
+    if not nx.is_directed_acyclic_graph(G):
+        raise nx.NetworkXError("LCA only defined on directed acyclic graphs.")
+    if len(G) == 0:
+        raise nx.NetworkXPointlessConcept("LCA meaningless on null graphs.")
+
+    if pairs is None:
+        pairs = combinations_with_replacement(G, 2)
+    else:
+        # Convert iterator to iterable, if necessary. Trim duplicates.
+        pairs = dict.fromkeys(pairs)
+        # Verify that each of the nodes in the provided pairs is in G
+        nodeset = set(G)
+        for pair in pairs:
+            if set(pair) - nodeset:
+                raise nx.NodeNotFound(
+                    f"Node(s) {set(pair) - nodeset} from pair {pair} not in G."
+                )
+
+    # Once input validation is done, construct the generator
+    def generate_lca_from_pairs(G, pairs):
+        ancestor_cache = {}
+
+        for v, w in pairs:
+            if v not in ancestor_cache:
+                ancestor_cache[v] = nx.ancestors(G, v)
+                ancestor_cache[v].add(v)
+            if w not in ancestor_cache:
+                ancestor_cache[w] = nx.ancestors(G, w)
+                ancestor_cache[w].add(w)
+
+            common_ancestors = ancestor_cache[v] & ancestor_cache[w]
+
+            if common_ancestors:
+                common_ancestor = next(iter(common_ancestors))
+                while True:
+                    successor = None
+                    for lower_ancestor in G.successors(common_ancestor):
+                        if lower_ancestor in common_ancestors:
+                            successor = lower_ancestor
+                            break
+                    if successor is None:
+                        break
+                    common_ancestor = successor
+                yield ((v, w), common_ancestor)
+
+    return generate_lca_from_pairs(G, pairs)
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable
+def lowest_common_ancestor(G, node1, node2, default=None):
+    """Compute the lowest common ancestor of the given pair of nodes.
+
+    Parameters
+    ----------
+    G : NetworkX directed graph
+
+    node1, node2 : nodes in the graph.
+
+    default : object
+        Returned if no common ancestor between `node1` and `node2`
+
+    Returns
+    -------
+    The lowest common ancestor of node1 and node2,
+    or default if they have no common ancestors.
+
+    Examples
+    --------
+    >>> G = nx.DiGraph()
+    >>> nx.add_path(G, (0, 1, 2, 3))
+    >>> nx.add_path(G, (0, 4, 3))
+    >>> nx.lowest_common_ancestor(G, 2, 4)
+    0
+
+    See Also
+    --------
+    all_pairs_lowest_common_ancestor"""
+
+    ans = list(all_pairs_lowest_common_ancestor(G, pairs=[(node1, node2)]))
+    if ans:
+        assert len(ans) == 1
+        return ans[0][1]
+    return default
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable
+def tree_all_pairs_lowest_common_ancestor(G, root=None, pairs=None):
+    r"""Yield the lowest common ancestor for sets of pairs in a tree.
+
+    Parameters
+    ----------
+    G : NetworkX directed graph (must be a tree)
+
+    root : node, optional (default: None)
+        The root of the subtree to operate on.
+        If None, assume the entire graph has exactly one source and use that.
+
+    pairs : iterable or iterator of pairs of nodes, optional (default: None)
+        The pairs of interest. If None, Defaults to all pairs of nodes
+        under `root` that have a lowest common ancestor.
+
+    Returns
+    -------
+    lcas : generator of tuples `((u, v), lca)` where `u` and `v` are nodes
+        in `pairs` and `lca` is their lowest common ancestor.
+
+    Examples
+    --------
+    >>> import pprint
+    >>> G = nx.DiGraph([(1, 3), (2, 4), (1, 2)])
+    >>> pprint.pprint(dict(nx.tree_all_pairs_lowest_common_ancestor(G)))
+    {(1, 1): 1,
+     (2, 1): 1,
+     (2, 2): 2,
+     (3, 1): 1,
+     (3, 2): 1,
+     (3, 3): 3,
+     (3, 4): 1,
+     (4, 1): 1,
+     (4, 2): 2,
+     (4, 4): 4}
+
+    We can also use `pairs` argument to specify the pairs of nodes for which we
+    want to compute lowest common ancestors. Here is an example:
+
+    >>> dict(nx.tree_all_pairs_lowest_common_ancestor(G, pairs=[(1, 4), (2, 3)]))
+    {(2, 3): 1, (1, 4): 1}
+
+    Notes
+    -----
+    Only defined on non-null trees represented with directed edges from
+    parents to children. Uses Tarjan's off-line lowest-common-ancestors
+    algorithm. Runs in time $O(4 \times (V + E + P))$ time, where 4 is the largest
+    value of the inverse Ackermann function likely to ever come up in actual
+    use, and $P$ is the number of pairs requested (or $V^2$ if all are needed).
+
+    Tarjan, R. E. (1979), "Applications of path compression on balanced trees",
+    Journal of the ACM 26 (4): 690-715, doi:10.1145/322154.322161.
+
+    See Also
+    --------
+    all_pairs_lowest_common_ancestor: similar routine for general DAGs
+    lowest_common_ancestor: just a single pair for general DAGs
+    """
+    if len(G) == 0:
+        raise nx.NetworkXPointlessConcept("LCA meaningless on null graphs.")
+
+    # Index pairs of interest for efficient lookup from either side.
+    if pairs is not None:
+        pair_dict = defaultdict(set)
+        # See note on all_pairs_lowest_common_ancestor.
+        if not isinstance(pairs, Mapping | Set):
+            pairs = set(pairs)
+        for u, v in pairs:
+            for n in (u, v):
+                if n not in G:
+                    msg = f"The node {str(n)} is not in the digraph."
+                    raise nx.NodeNotFound(msg)
+            pair_dict[u].add(v)
+            pair_dict[v].add(u)
+
+    # If root is not specified, find the exactly one node with in degree 0 and
+    # use it. Raise an error if none are found, or more than one is. Also check
+    # for any nodes with in degree larger than 1, which would imply G is not a
+    # tree.
+    if root is None:
+        for n, deg in G.in_degree:
+            if deg == 0:
+                if root is not None:
+                    msg = "No root specified and tree has multiple sources."
+                    raise nx.NetworkXError(msg)
+                root = n
+            # checking deg>1 is not sufficient for MultiDiGraphs
+            elif deg > 1 and len(G.pred[n]) > 1:
+                msg = "Tree LCA only defined on trees; use DAG routine."
+                raise nx.NetworkXError(msg)
+    if root is None:
+        raise nx.NetworkXError("Graph contains a cycle.")
+
+    # Iterative implementation of Tarjan's offline lca algorithm
+    # as described in CLRS on page 521 (2nd edition)/page 584 (3rd edition)
+    uf = UnionFind()
+    ancestors = {}
+    for node in G:
+        ancestors[node] = uf[node]
+
+    colors = defaultdict(bool)
+    for node in nx.dfs_postorder_nodes(G, root):
+        colors[node] = True
+        for v in pair_dict[node] if pairs is not None else G:
+            if colors[v]:
+                # If the user requested both directions of a pair, give it.
+                # Otherwise, just give one.
+                if pairs is not None and (node, v) in pairs:
+                    yield (node, v), ancestors[uf[v]]
+                if pairs is None or (v, node) in pairs:
+                    yield (v, node), ancestors[uf[v]]
+        if node != root:
+            parent = arbitrary_element(G.pred[node])
+            uf.union(parent, node)
+            ancestors[uf[parent]] = parent
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/matching.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/matching.py
new file mode 100644
index 0000000000000000000000000000000000000000..b2dc7c63e569f26e4f0933a26fb7f8bebdff8f0e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/matching.py
@@ -0,0 +1,1148 @@
+"""Functions for computing and verifying matchings in a graph."""
+
+from itertools import combinations, repeat
+
+import networkx as nx
+from networkx.utils import not_implemented_for
+
+__all__ = [
+    "is_matching",
+    "is_maximal_matching",
+    "is_perfect_matching",
+    "max_weight_matching",
+    "min_weight_matching",
+    "maximal_matching",
+]
+
+
+@not_implemented_for("multigraph")
+@not_implemented_for("directed")
+@nx._dispatchable
+def maximal_matching(G):
+    r"""Find a maximal matching in the graph.
+
+    A matching is a subset of edges in which no node occurs more than once.
+    A maximal matching cannot add more edges and still be a matching.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        Undirected graph
+
+    Returns
+    -------
+    matching : set
+        A maximal matching of the graph.
+
+    Examples
+    --------
+    >>> G = nx.Graph([(1, 2), (1, 3), (2, 3), (2, 4), (3, 5), (4, 5)])
+    >>> sorted(nx.maximal_matching(G))
+    [(1, 2), (3, 5)]
+
+    Notes
+    -----
+    The algorithm greedily selects a maximal matching M of the graph G
+    (i.e. no superset of M exists). It runs in $O(|E|)$ time.
+    """
+    matching = set()
+    nodes = set()
+    for edge in G.edges():
+        # If the edge isn't covered, add it to the matching
+        # then remove neighborhood of u and v from consideration.
+        u, v = edge
+        if u not in nodes and v not in nodes and u != v:
+            matching.add(edge)
+            nodes.update(edge)
+    return matching
+
+
+def matching_dict_to_set(matching):
+    """Converts matching dict format to matching set format
+
+    Converts a dictionary representing a matching (as returned by
+    :func:`max_weight_matching`) to a set representing a matching (as
+    returned by :func:`maximal_matching`).
+
+    In the definition of maximal matching adopted by NetworkX,
+    self-loops are not allowed, so the provided dictionary is expected
+    to never have any mapping from a key to itself. However, the
+    dictionary is expected to have mirrored key/value pairs, for
+    example, key ``u`` with value ``v`` and key ``v`` with value ``u``.
+
+    """
+    edges = set()
+    for edge in matching.items():
+        u, v = edge
+        if (v, u) in edges or edge in edges:
+            continue
+        if u == v:
+            raise nx.NetworkXError(f"Selfloops cannot appear in matchings {edge}")
+        edges.add(edge)
+    return edges
+
+
+@nx._dispatchable
+def is_matching(G, matching):
+    """Return True if ``matching`` is a valid matching of ``G``
+
+    A *matching* in a graph is a set of edges in which no two distinct
+    edges share a common endpoint. Each node is incident to at most one
+    edge in the matching. The edges are said to be independent.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    matching : dict or set
+        A dictionary or set representing a matching. If a dictionary, it
+        must have ``matching[u] == v`` and ``matching[v] == u`` for each
+        edge ``(u, v)`` in the matching. If a set, it must have elements
+        of the form ``(u, v)``, where ``(u, v)`` is an edge in the
+        matching.
+
+    Returns
+    -------
+    bool
+        Whether the given set or dictionary represents a valid matching
+        in the graph.
+
+    Raises
+    ------
+    NetworkXError
+        If the proposed matching has an edge to a node not in G.
+        Or if the matching is not a collection of 2-tuple edges.
+
+    Examples
+    --------
+    >>> G = nx.Graph([(1, 2), (1, 3), (2, 3), (2, 4), (3, 5), (4, 5)])
+    >>> nx.is_maximal_matching(G, {1: 3, 2: 4})  # using dict to represent matching
+    True
+
+    >>> nx.is_matching(G, {(1, 3), (2, 4)})  # using set to represent matching
+    True
+
+    """
+    if isinstance(matching, dict):
+        matching = matching_dict_to_set(matching)
+
+    nodes = set()
+    for edge in matching:
+        if len(edge) != 2:
+            raise nx.NetworkXError(f"matching has non-2-tuple edge {edge}")
+        u, v = edge
+        if u not in G or v not in G:
+            raise nx.NetworkXError(f"matching contains edge {edge} with node not in G")
+        if u == v:
+            return False
+        if not G.has_edge(u, v):
+            return False
+        if u in nodes or v in nodes:
+            return False
+        nodes.update(edge)
+    return True
+
+
+@nx._dispatchable
+def is_maximal_matching(G, matching):
+    """Return True if ``matching`` is a maximal matching of ``G``
+
+    A *maximal matching* in a graph is a matching in which adding any
+    edge would cause the set to no longer be a valid matching.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    matching : dict or set
+        A dictionary or set representing a matching. If a dictionary, it
+        must have ``matching[u] == v`` and ``matching[v] == u`` for each
+        edge ``(u, v)`` in the matching. If a set, it must have elements
+        of the form ``(u, v)``, where ``(u, v)`` is an edge in the
+        matching.
+
+    Returns
+    -------
+    bool
+        Whether the given set or dictionary represents a valid maximal
+        matching in the graph.
+
+    Examples
+    --------
+    >>> G = nx.Graph([(1, 2), (1, 3), (2, 3), (3, 4), (3, 5)])
+    >>> nx.is_maximal_matching(G, {(1, 2), (3, 4)})
+    True
+
+    """
+    if isinstance(matching, dict):
+        matching = matching_dict_to_set(matching)
+    # If the given set is not a matching, then it is not a maximal matching.
+    edges = set()
+    nodes = set()
+    for edge in matching:
+        if len(edge) != 2:
+            raise nx.NetworkXError(f"matching has non-2-tuple edge {edge}")
+        u, v = edge
+        if u not in G or v not in G:
+            raise nx.NetworkXError(f"matching contains edge {edge} with node not in G")
+        if u == v:
+            return False
+        if not G.has_edge(u, v):
+            return False
+        if u in nodes or v in nodes:
+            return False
+        nodes.update(edge)
+        edges.add(edge)
+        edges.add((v, u))
+    # A matching is maximal if adding any new edge from G to it
+    # causes the resulting set to match some node twice.
+    # Be careful to check for adding selfloops
+    for u, v in G.edges:
+        if (u, v) not in edges:
+            # could add edge (u, v) to edges and have a bigger matching
+            if u not in nodes and v not in nodes and u != v:
+                return False
+    return True
+
+
+@nx._dispatchable
+def is_perfect_matching(G, matching):
+    """Return True if ``matching`` is a perfect matching for ``G``
+
+    A *perfect matching* in a graph is a matching in which exactly one edge
+    is incident upon each vertex.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    matching : dict or set
+        A dictionary or set representing a matching. If a dictionary, it
+        must have ``matching[u] == v`` and ``matching[v] == u`` for each
+        edge ``(u, v)`` in the matching. If a set, it must have elements
+        of the form ``(u, v)``, where ``(u, v)`` is an edge in the
+        matching.
+
+    Returns
+    -------
+    bool
+        Whether the given set or dictionary represents a valid perfect
+        matching in the graph.
+
+    Examples
+    --------
+    >>> G = nx.Graph([(1, 2), (1, 3), (2, 3), (2, 4), (3, 5), (4, 5), (4, 6)])
+    >>> my_match = {1: 2, 3: 5, 4: 6}
+    >>> nx.is_perfect_matching(G, my_match)
+    True
+
+    """
+    if isinstance(matching, dict):
+        matching = matching_dict_to_set(matching)
+
+    nodes = set()
+    for edge in matching:
+        if len(edge) != 2:
+            raise nx.NetworkXError(f"matching has non-2-tuple edge {edge}")
+        u, v = edge
+        if u not in G or v not in G:
+            raise nx.NetworkXError(f"matching contains edge {edge} with node not in G")
+        if u == v:
+            return False
+        if not G.has_edge(u, v):
+            return False
+        if u in nodes or v in nodes:
+            return False
+        nodes.update(edge)
+    return len(nodes) == len(G)
+
+
+@not_implemented_for("multigraph")
+@not_implemented_for("directed")
+@nx._dispatchable(edge_attrs="weight")
+def min_weight_matching(G, weight="weight"):
+    """Compute a minimum-weight maximum-cardinality matching of `G`.
+
+    The minimum-weight maximum-cardinality matching is the matching
+    that has the minimum weight among all maximum-cardinality matchings.
+
+    Use the maximum-weight algorithm with edge weights subtracted
+    from the maximum weight of all edges.
+
+    A matching is a subset of edges in which no node occurs more than once.
+    The weight of a matching is the sum of the weights of its edges.
+    A maximal matching cannot add more edges and still be a matching.
+    The cardinality of a matching is the number of matched edges.
+
+    This method replaces the edge weights with 1 plus the maximum edge weight
+    minus the original edge weight.
+
+    new_weight = (max_weight + 1) - edge_weight
+
+    then runs :func:`max_weight_matching` with the new weights.
+    The max weight matching with these new weights corresponds
+    to the min weight matching using the original weights.
+    Adding 1 to the max edge weight keeps all edge weights positive
+    and as integers if they started as integers.
+
+    Read the documentation of `max_weight_matching` for more information.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+      Undirected graph
+
+    weight: string, optional (default='weight')
+       Edge data key corresponding to the edge weight.
+       If key not found, uses 1 as weight.
+
+    Returns
+    -------
+    matching : set
+        A minimal weight matching of the graph.
+
+    See Also
+    --------
+    max_weight_matching
+    """
+    if len(G.edges) == 0:
+        return max_weight_matching(G, maxcardinality=True, weight=weight)
+    G_edges = G.edges(data=weight, default=1)
+    max_weight = 1 + max(w for _, _, w in G_edges)
+    InvG = nx.Graph()
+    edges = ((u, v, max_weight - w) for u, v, w in G_edges)
+    InvG.add_weighted_edges_from(edges, weight=weight)
+    return max_weight_matching(InvG, maxcardinality=True, weight=weight)
+
+
+@not_implemented_for("multigraph")
+@not_implemented_for("directed")
+@nx._dispatchable(edge_attrs="weight")
+def max_weight_matching(G, maxcardinality=False, weight="weight"):
+    """Compute a maximum-weighted matching of G.
+
+    A matching is a subset of edges in which no node occurs more than once.
+    The weight of a matching is the sum of the weights of its edges.
+    A maximal matching cannot add more edges and still be a matching.
+    The cardinality of a matching is the number of matched edges.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+      Undirected graph
+
+    maxcardinality: bool, optional (default=False)
+       If maxcardinality is True, compute the maximum-cardinality matching
+       with maximum weight among all maximum-cardinality matchings.
+
+    weight: string, optional (default='weight')
+       Edge data key corresponding to the edge weight.
+       If key not found, uses 1 as weight.
+
+
+    Returns
+    -------
+    matching : set
+        A maximal matching of the graph.
+
+     Examples
+    --------
+    >>> G = nx.Graph()
+    >>> edges = [(1, 2, 6), (1, 3, 2), (2, 3, 1), (2, 4, 7), (3, 5, 9), (4, 5, 3)]
+    >>> G.add_weighted_edges_from(edges)
+    >>> sorted(nx.max_weight_matching(G))
+    [(2, 4), (5, 3)]
+
+    Notes
+    -----
+    If G has edges with weight attributes the edge data are used as
+    weight values else the weights are assumed to be 1.
+
+    This function takes time O(number_of_nodes ** 3).
+
+    If all edge weights are integers, the algorithm uses only integer
+    computations.  If floating point weights are used, the algorithm
+    could return a slightly suboptimal matching due to numeric
+    precision errors.
+
+    This method is based on the "blossom" method for finding augmenting
+    paths and the "primal-dual" method for finding a matching of maximum
+    weight, both methods invented by Jack Edmonds [1]_.
+
+    Bipartite graphs can also be matched using the functions present in
+    :mod:`networkx.algorithms.bipartite.matching`.
+
+    References
+    ----------
+    .. [1] "Efficient Algorithms for Finding Maximum Matching in Graphs",
+       Zvi Galil, ACM Computing Surveys, 1986.
+    """
+    #
+    # The algorithm is taken from "Efficient Algorithms for Finding Maximum
+    # Matching in Graphs" by Zvi Galil, ACM Computing Surveys, 1986.
+    # It is based on the "blossom" method for finding augmenting paths and
+    # the "primal-dual" method for finding a matching of maximum weight, both
+    # methods invented by Jack Edmonds.
+    #
+    # A C program for maximum weight matching by Ed Rothberg was used
+    # extensively to validate this new code.
+    #
+    # Many terms used in the code comments are explained in the paper
+    # by Galil. You will probably need the paper to make sense of this code.
+    #
+
+    class NoNode:
+        """Dummy value which is different from any node."""
+
+    class Blossom:
+        """Representation of a non-trivial blossom or sub-blossom."""
+
+        __slots__ = ["childs", "edges", "mybestedges"]
+
+        # b.childs is an ordered list of b's sub-blossoms, starting with
+        # the base and going round the blossom.
+
+        # b.edges is the list of b's connecting edges, such that
+        # b.edges[i] = (v, w) where v is a vertex in b.childs[i]
+        # and w is a vertex in b.childs[wrap(i+1)].
+
+        # If b is a top-level S-blossom,
+        # b.mybestedges is a list of least-slack edges to neighboring
+        # S-blossoms, or None if no such list has been computed yet.
+        # This is used for efficient computation of delta3.
+
+        # Generate the blossom's leaf vertices.
+        def leaves(self):
+            stack = [*self.childs]
+            while stack:
+                t = stack.pop()
+                if isinstance(t, Blossom):
+                    stack.extend(t.childs)
+                else:
+                    yield t
+
+    # Get a list of vertices.
+    gnodes = list(G)
+    if not gnodes:
+        return set()  # don't bother with empty graphs
+
+    # Find the maximum edge weight.
+    maxweight = 0
+    allinteger = True
+    for i, j, d in G.edges(data=True):
+        wt = d.get(weight, 1)
+        if i != j and wt > maxweight:
+            maxweight = wt
+        allinteger = allinteger and (str(type(wt)).split("'")[1] in ("int", "long"))
+
+    # If v is a matched vertex, mate[v] is its partner vertex.
+    # If v is a single vertex, v does not occur as a key in mate.
+    # Initially all vertices are single; updated during augmentation.
+    mate = {}
+
+    # If b is a top-level blossom,
+    # label.get(b) is None if b is unlabeled (free),
+    #                 1 if b is an S-blossom,
+    #                 2 if b is a T-blossom.
+    # The label of a vertex is found by looking at the label of its top-level
+    # containing blossom.
+    # If v is a vertex inside a T-blossom, label[v] is 2 iff v is reachable
+    # from an S-vertex outside the blossom.
+    # Labels are assigned during a stage and reset after each augmentation.
+    label = {}
+
+    # If b is a labeled top-level blossom,
+    # labeledge[b] = (v, w) is the edge through which b obtained its label
+    # such that w is a vertex in b, or None if b's base vertex is single.
+    # If w is a vertex inside a T-blossom and label[w] == 2,
+    # labeledge[w] = (v, w) is an edge through which w is reachable from
+    # outside the blossom.
+    labeledge = {}
+
+    # If v is a vertex, inblossom[v] is the top-level blossom to which v
+    # belongs.
+    # If v is a top-level vertex, inblossom[v] == v since v is itself
+    # a (trivial) top-level blossom.
+    # Initially all vertices are top-level trivial blossoms.
+    inblossom = dict(zip(gnodes, gnodes))
+
+    # If b is a sub-blossom,
+    # blossomparent[b] is its immediate parent (sub-)blossom.
+    # If b is a top-level blossom, blossomparent[b] is None.
+    blossomparent = dict(zip(gnodes, repeat(None)))
+
+    # If b is a (sub-)blossom,
+    # blossombase[b] is its base VERTEX (i.e. recursive sub-blossom).
+    blossombase = dict(zip(gnodes, gnodes))
+
+    # If w is a free vertex (or an unreached vertex inside a T-blossom),
+    # bestedge[w] = (v, w) is the least-slack edge from an S-vertex,
+    # or None if there is no such edge.
+    # If b is a (possibly trivial) top-level S-blossom,
+    # bestedge[b] = (v, w) is the least-slack edge to a different S-blossom
+    # (v inside b), or None if there is no such edge.
+    # This is used for efficient computation of delta2 and delta3.
+    bestedge = {}
+
+    # If v is a vertex,
+    # dualvar[v] = 2 * u(v) where u(v) is the v's variable in the dual
+    # optimization problem (if all edge weights are integers, multiplication
+    # by two ensures that all values remain integers throughout the algorithm).
+    # Initially, u(v) = maxweight / 2.
+    dualvar = dict(zip(gnodes, repeat(maxweight)))
+
+    # If b is a non-trivial blossom,
+    # blossomdual[b] = z(b) where z(b) is b's variable in the dual
+    # optimization problem.
+    blossomdual = {}
+
+    # If (v, w) in allowedge or (w, v) in allowedg, then the edge
+    # (v, w) is known to have zero slack in the optimization problem;
+    # otherwise the edge may or may not have zero slack.
+    allowedge = {}
+
+    # Queue of newly discovered S-vertices.
+    queue = []
+
+    # Return 2 * slack of edge (v, w) (does not work inside blossoms).
+    def slack(v, w):
+        return dualvar[v] + dualvar[w] - 2 * G[v][w].get(weight, 1)
+
+    # Assign label t to the top-level blossom containing vertex w,
+    # coming through an edge from vertex v.
+    def assignLabel(w, t, v):
+        b = inblossom[w]
+        assert label.get(w) is None and label.get(b) is None
+        label[w] = label[b] = t
+        if v is not None:
+            labeledge[w] = labeledge[b] = (v, w)
+        else:
+            labeledge[w] = labeledge[b] = None
+        bestedge[w] = bestedge[b] = None
+        if t == 1:
+            # b became an S-vertex/blossom; add it(s vertices) to the queue.
+            if isinstance(b, Blossom):
+                queue.extend(b.leaves())
+            else:
+                queue.append(b)
+        elif t == 2:
+            # b became a T-vertex/blossom; assign label S to its mate.
+            # (If b is a non-trivial blossom, its base is the only vertex
+            # with an external mate.)
+            base = blossombase[b]
+            assignLabel(mate[base], 1, base)
+
+    # Trace back from vertices v and w to discover either a new blossom
+    # or an augmenting path. Return the base vertex of the new blossom,
+    # or NoNode if an augmenting path was found.
+    def scanBlossom(v, w):
+        # Trace back from v and w, placing breadcrumbs as we go.
+        path = []
+        base = NoNode
+        while v is not NoNode:
+            # Look for a breadcrumb in v's blossom or put a new breadcrumb.
+            b = inblossom[v]
+            if label[b] & 4:
+                base = blossombase[b]
+                break
+            assert label[b] == 1
+            path.append(b)
+            label[b] = 5
+            # Trace one step back.
+            if labeledge[b] is None:
+                # The base of blossom b is single; stop tracing this path.
+                assert blossombase[b] not in mate
+                v = NoNode
+            else:
+                assert labeledge[b][0] == mate[blossombase[b]]
+                v = labeledge[b][0]
+                b = inblossom[v]
+                assert label[b] == 2
+                # b is a T-blossom; trace one more step back.
+                v = labeledge[b][0]
+            # Swap v and w so that we alternate between both paths.
+            if w is not NoNode:
+                v, w = w, v
+        # Remove breadcrumbs.
+        for b in path:
+            label[b] = 1
+        # Return base vertex, if we found one.
+        return base
+
+    # Construct a new blossom with given base, through S-vertices v and w.
+    # Label the new blossom as S; set its dual variable to zero;
+    # relabel its T-vertices to S and add them to the queue.
+    def addBlossom(base, v, w):
+        bb = inblossom[base]
+        bv = inblossom[v]
+        bw = inblossom[w]
+        # Create blossom.
+        b = Blossom()
+        blossombase[b] = base
+        blossomparent[b] = None
+        blossomparent[bb] = b
+        # Make list of sub-blossoms and their interconnecting edge endpoints.
+        b.childs = path = []
+        b.edges = edgs = [(v, w)]
+        # Trace back from v to base.
+        while bv != bb:
+            # Add bv to the new blossom.
+            blossomparent[bv] = b
+            path.append(bv)
+            edgs.append(labeledge[bv])
+            assert label[bv] == 2 or (
+                label[bv] == 1 and labeledge[bv][0] == mate[blossombase[bv]]
+            )
+            # Trace one step back.
+            v = labeledge[bv][0]
+            bv = inblossom[v]
+        # Add base sub-blossom; reverse lists.
+        path.append(bb)
+        path.reverse()
+        edgs.reverse()
+        # Trace back from w to base.
+        while bw != bb:
+            # Add bw to the new blossom.
+            blossomparent[bw] = b
+            path.append(bw)
+            edgs.append((labeledge[bw][1], labeledge[bw][0]))
+            assert label[bw] == 2 or (
+                label[bw] == 1 and labeledge[bw][0] == mate[blossombase[bw]]
+            )
+            # Trace one step back.
+            w = labeledge[bw][0]
+            bw = inblossom[w]
+        # Set label to S.
+        assert label[bb] == 1
+        label[b] = 1
+        labeledge[b] = labeledge[bb]
+        # Set dual variable to zero.
+        blossomdual[b] = 0
+        # Relabel vertices.
+        for v in b.leaves():
+            if label[inblossom[v]] == 2:
+                # This T-vertex now turns into an S-vertex because it becomes
+                # part of an S-blossom; add it to the queue.
+                queue.append(v)
+            inblossom[v] = b
+        # Compute b.mybestedges.
+        bestedgeto = {}
+        for bv in path:
+            if isinstance(bv, Blossom):
+                if bv.mybestedges is not None:
+                    # Walk this subblossom's least-slack edges.
+                    nblist = bv.mybestedges
+                    # The sub-blossom won't need this data again.
+                    bv.mybestedges = None
+                else:
+                    # This subblossom does not have a list of least-slack
+                    # edges; get the information from the vertices.
+                    nblist = [
+                        (v, w) for v in bv.leaves() for w in G.neighbors(v) if v != w
+                    ]
+            else:
+                nblist = [(bv, w) for w in G.neighbors(bv) if bv != w]
+            for k in nblist:
+                (i, j) = k
+                if inblossom[j] == b:
+                    i, j = j, i
+                bj = inblossom[j]
+                if (
+                    bj != b
+                    and label.get(bj) == 1
+                    and ((bj not in bestedgeto) or slack(i, j) < slack(*bestedgeto[bj]))
+                ):
+                    bestedgeto[bj] = k
+            # Forget about least-slack edge of the subblossom.
+            bestedge[bv] = None
+        b.mybestedges = list(bestedgeto.values())
+        # Select bestedge[b].
+        mybestedge = None
+        bestedge[b] = None
+        for k in b.mybestedges:
+            kslack = slack(*k)
+            if mybestedge is None or kslack < mybestslack:
+                mybestedge = k
+                mybestslack = kslack
+        bestedge[b] = mybestedge
+
+    # Expand the given top-level blossom.
+    def expandBlossom(b, endstage):
+        # This is an obnoxiously complicated recursive function for the sake of
+        # a stack-transformation.  So, we hack around the complexity by using
+        # a trampoline pattern.  By yielding the arguments to each recursive
+        # call, we keep the actual callstack flat.
+
+        def _recurse(b, endstage):
+            # Convert sub-blossoms into top-level blossoms.
+            for s in b.childs:
+                blossomparent[s] = None
+                if isinstance(s, Blossom):
+                    if endstage and blossomdual[s] == 0:
+                        # Recursively expand this sub-blossom.
+                        yield s
+                    else:
+                        for v in s.leaves():
+                            inblossom[v] = s
+                else:
+                    inblossom[s] = s
+            # If we expand a T-blossom during a stage, its sub-blossoms must be
+            # relabeled.
+            if (not endstage) and label.get(b) == 2:
+                # Start at the sub-blossom through which the expanding
+                # blossom obtained its label, and relabel sub-blossoms untili
+                # we reach the base.
+                # Figure out through which sub-blossom the expanding blossom
+                # obtained its label initially.
+                entrychild = inblossom[labeledge[b][1]]
+                # Decide in which direction we will go round the blossom.
+                j = b.childs.index(entrychild)
+                if j & 1:
+                    # Start index is odd; go forward and wrap.
+                    j -= len(b.childs)
+                    jstep = 1
+                else:
+                    # Start index is even; go backward.
+                    jstep = -1
+                # Move along the blossom until we get to the base.
+                v, w = labeledge[b]
+                while j != 0:
+                    # Relabel the T-sub-blossom.
+                    if jstep == 1:
+                        p, q = b.edges[j]
+                    else:
+                        q, p = b.edges[j - 1]
+                    label[w] = None
+                    label[q] = None
+                    assignLabel(w, 2, v)
+                    # Step to the next S-sub-blossom and note its forward edge.
+                    allowedge[(p, q)] = allowedge[(q, p)] = True
+                    j += jstep
+                    if jstep == 1:
+                        v, w = b.edges[j]
+                    else:
+                        w, v = b.edges[j - 1]
+                    # Step to the next T-sub-blossom.
+                    allowedge[(v, w)] = allowedge[(w, v)] = True
+                    j += jstep
+                # Relabel the base T-sub-blossom WITHOUT stepping through to
+                # its mate (so don't call assignLabel).
+                bw = b.childs[j]
+                label[w] = label[bw] = 2
+                labeledge[w] = labeledge[bw] = (v, w)
+                bestedge[bw] = None
+                # Continue along the blossom until we get back to entrychild.
+                j += jstep
+                while b.childs[j] != entrychild:
+                    # Examine the vertices of the sub-blossom to see whether
+                    # it is reachable from a neighboring S-vertex outside the
+                    # expanding blossom.
+                    bv = b.childs[j]
+                    if label.get(bv) == 1:
+                        # This sub-blossom just got label S through one of its
+                        # neighbors; leave it be.
+                        j += jstep
+                        continue
+                    if isinstance(bv, Blossom):
+                        for v in bv.leaves():
+                            if label.get(v):
+                                break
+                    else:
+                        v = bv
+                    # If the sub-blossom contains a reachable vertex, assign
+                    # label T to the sub-blossom.
+                    if label.get(v):
+                        assert label[v] == 2
+                        assert inblossom[v] == bv
+                        label[v] = None
+                        label[mate[blossombase[bv]]] = None
+                        assignLabel(v, 2, labeledge[v][0])
+                    j += jstep
+            # Remove the expanded blossom entirely.
+            label.pop(b, None)
+            labeledge.pop(b, None)
+            bestedge.pop(b, None)
+            del blossomparent[b]
+            del blossombase[b]
+            del blossomdual[b]
+
+        # Now, we apply the trampoline pattern.  We simulate a recursive
+        # callstack by maintaining a stack of generators, each yielding a
+        # sequence of function arguments.  We grow the stack by appending a call
+        # to _recurse on each argument tuple, and shrink the stack whenever a
+        # generator is exhausted.
+        stack = [_recurse(b, endstage)]
+        while stack:
+            top = stack[-1]
+            for s in top:
+                stack.append(_recurse(s, endstage))
+                break
+            else:
+                stack.pop()
+
+    # Swap matched/unmatched edges over an alternating path through blossom b
+    # between vertex v and the base vertex. Keep blossom bookkeeping
+    # consistent.
+    def augmentBlossom(b, v):
+        # This is an obnoxiously complicated recursive function for the sake of
+        # a stack-transformation.  So, we hack around the complexity by using
+        # a trampoline pattern.  By yielding the arguments to each recursive
+        # call, we keep the actual callstack flat.
+
+        def _recurse(b, v):
+            # Bubble up through the blossom tree from vertex v to an immediate
+            # sub-blossom of b.
+            t = v
+            while blossomparent[t] != b:
+                t = blossomparent[t]
+            # Recursively deal with the first sub-blossom.
+            if isinstance(t, Blossom):
+                yield (t, v)
+            # Decide in which direction we will go round the blossom.
+            i = j = b.childs.index(t)
+            if i & 1:
+                # Start index is odd; go forward and wrap.
+                j -= len(b.childs)
+                jstep = 1
+            else:
+                # Start index is even; go backward.
+                jstep = -1
+            # Move along the blossom until we get to the base.
+            while j != 0:
+                # Step to the next sub-blossom and augment it recursively.
+                j += jstep
+                t = b.childs[j]
+                if jstep == 1:
+                    w, x = b.edges[j]
+                else:
+                    x, w = b.edges[j - 1]
+                if isinstance(t, Blossom):
+                    yield (t, w)
+                # Step to the next sub-blossom and augment it recursively.
+                j += jstep
+                t = b.childs[j]
+                if isinstance(t, Blossom):
+                    yield (t, x)
+                # Match the edge connecting those sub-blossoms.
+                mate[w] = x
+                mate[x] = w
+            # Rotate the list of sub-blossoms to put the new base at the front.
+            b.childs = b.childs[i:] + b.childs[:i]
+            b.edges = b.edges[i:] + b.edges[:i]
+            blossombase[b] = blossombase[b.childs[0]]
+            assert blossombase[b] == v
+
+        # Now, we apply the trampoline pattern.  We simulate a recursive
+        # callstack by maintaining a stack of generators, each yielding a
+        # sequence of function arguments.  We grow the stack by appending a call
+        # to _recurse on each argument tuple, and shrink the stack whenever a
+        # generator is exhausted.
+        stack = [_recurse(b, v)]
+        while stack:
+            top = stack[-1]
+            for args in top:
+                stack.append(_recurse(*args))
+                break
+            else:
+                stack.pop()
+
+    # Swap matched/unmatched edges over an alternating path between two
+    # single vertices. The augmenting path runs through S-vertices v and w.
+    def augmentMatching(v, w):
+        for s, j in ((v, w), (w, v)):
+            # Match vertex s to vertex j. Then trace back from s
+            # until we find a single vertex, swapping matched and unmatched
+            # edges as we go.
+            while 1:
+                bs = inblossom[s]
+                assert label[bs] == 1
+                assert (labeledge[bs] is None and blossombase[bs] not in mate) or (
+                    labeledge[bs][0] == mate[blossombase[bs]]
+                )
+                # Augment through the S-blossom from s to base.
+                if isinstance(bs, Blossom):
+                    augmentBlossom(bs, s)
+                # Update mate[s]
+                mate[s] = j
+                # Trace one step back.
+                if labeledge[bs] is None:
+                    # Reached single vertex; stop.
+                    break
+                t = labeledge[bs][0]
+                bt = inblossom[t]
+                assert label[bt] == 2
+                # Trace one more step back.
+                s, j = labeledge[bt]
+                # Augment through the T-blossom from j to base.
+                assert blossombase[bt] == t
+                if isinstance(bt, Blossom):
+                    augmentBlossom(bt, j)
+                # Update mate[j]
+                mate[j] = s
+
+    # Verify that the optimum solution has been reached.
+    def verifyOptimum():
+        if maxcardinality:
+            # Vertices may have negative dual;
+            # find a constant non-negative number to add to all vertex duals.
+            vdualoffset = max(0, -min(dualvar.values()))
+        else:
+            vdualoffset = 0
+        # 0. all dual variables are non-negative
+        assert min(dualvar.values()) + vdualoffset >= 0
+        assert len(blossomdual) == 0 or min(blossomdual.values()) >= 0
+        # 0. all edges have non-negative slack and
+        # 1. all matched edges have zero slack;
+        for i, j, d in G.edges(data=True):
+            wt = d.get(weight, 1)
+            if i == j:
+                continue  # ignore self-loops
+            s = dualvar[i] + dualvar[j] - 2 * wt
+            iblossoms = [i]
+            jblossoms = [j]
+            while blossomparent[iblossoms[-1]] is not None:
+                iblossoms.append(blossomparent[iblossoms[-1]])
+            while blossomparent[jblossoms[-1]] is not None:
+                jblossoms.append(blossomparent[jblossoms[-1]])
+            iblossoms.reverse()
+            jblossoms.reverse()
+            for bi, bj in zip(iblossoms, jblossoms):
+                if bi != bj:
+                    break
+                s += 2 * blossomdual[bi]
+            assert s >= 0
+            if mate.get(i) == j or mate.get(j) == i:
+                assert mate[i] == j and mate[j] == i
+                assert s == 0
+        # 2. all single vertices have zero dual value;
+        for v in gnodes:
+            assert (v in mate) or dualvar[v] + vdualoffset == 0
+        # 3. all blossoms with positive dual value are full.
+        for b in blossomdual:
+            if blossomdual[b] > 0:
+                assert len(b.edges) % 2 == 1
+                for i, j in b.edges[1::2]:
+                    assert mate[i] == j and mate[j] == i
+        # Ok.
+
+    # Main loop: continue until no further improvement is possible.
+    while 1:
+        # Each iteration of this loop is a "stage".
+        # A stage finds an augmenting path and uses that to improve
+        # the matching.
+
+        # Remove labels from top-level blossoms/vertices.
+        label.clear()
+        labeledge.clear()
+
+        # Forget all about least-slack edges.
+        bestedge.clear()
+        for b in blossomdual:
+            b.mybestedges = None
+
+        # Loss of labeling means that we can not be sure that currently
+        # allowable edges remain allowable throughout this stage.
+        allowedge.clear()
+
+        # Make queue empty.
+        queue[:] = []
+
+        # Label single blossoms/vertices with S and put them in the queue.
+        for v in gnodes:
+            if (v not in mate) and label.get(inblossom[v]) is None:
+                assignLabel(v, 1, None)
+
+        # Loop until we succeed in augmenting the matching.
+        augmented = 0
+        while 1:
+            # Each iteration of this loop is a "substage".
+            # A substage tries to find an augmenting path;
+            # if found, the path is used to improve the matching and
+            # the stage ends. If there is no augmenting path, the
+            # primal-dual method is used to pump some slack out of
+            # the dual variables.
+
+            # Continue labeling until all vertices which are reachable
+            # through an alternating path have got a label.
+            while queue and not augmented:
+                # Take an S vertex from the queue.
+                v = queue.pop()
+                assert label[inblossom[v]] == 1
+
+                # Scan its neighbors:
+                for w in G.neighbors(v):
+                    if w == v:
+                        continue  # ignore self-loops
+                    # w is a neighbor to v
+                    bv = inblossom[v]
+                    bw = inblossom[w]
+                    if bv == bw:
+                        # this edge is internal to a blossom; ignore it
+                        continue
+                    if (v, w) not in allowedge:
+                        kslack = slack(v, w)
+                        if kslack <= 0:
+                            # edge k has zero slack => it is allowable
+                            allowedge[(v, w)] = allowedge[(w, v)] = True
+                    if (v, w) in allowedge:
+                        if label.get(bw) is None:
+                            # (C1) w is a free vertex;
+                            # label w with T and label its mate with S (R12).
+                            assignLabel(w, 2, v)
+                        elif label.get(bw) == 1:
+                            # (C2) w is an S-vertex (not in the same blossom);
+                            # follow back-links to discover either an
+                            # augmenting path or a new blossom.
+                            base = scanBlossom(v, w)
+                            if base is not NoNode:
+                                # Found a new blossom; add it to the blossom
+                                # bookkeeping and turn it into an S-blossom.
+                                addBlossom(base, v, w)
+                            else:
+                                # Found an augmenting path; augment the
+                                # matching and end this stage.
+                                augmentMatching(v, w)
+                                augmented = 1
+                                break
+                        elif label.get(w) is None:
+                            # w is inside a T-blossom, but w itself has not
+                            # yet been reached from outside the blossom;
+                            # mark it as reached (we need this to relabel
+                            # during T-blossom expansion).
+                            assert label[bw] == 2
+                            label[w] = 2
+                            labeledge[w] = (v, w)
+                    elif label.get(bw) == 1:
+                        # keep track of the least-slack non-allowable edge to
+                        # a different S-blossom.
+                        if bestedge.get(bv) is None or kslack < slack(*bestedge[bv]):
+                            bestedge[bv] = (v, w)
+                    elif label.get(w) is None:
+                        # w is a free vertex (or an unreached vertex inside
+                        # a T-blossom) but we can not reach it yet;
+                        # keep track of the least-slack edge that reaches w.
+                        if bestedge.get(w) is None or kslack < slack(*bestedge[w]):
+                            bestedge[w] = (v, w)
+
+            if augmented:
+                break
+
+            # There is no augmenting path under these constraints;
+            # compute delta and reduce slack in the optimization problem.
+            # (Note that our vertex dual variables, edge slacks and delta's
+            # are pre-multiplied by two.)
+            deltatype = -1
+            delta = deltaedge = deltablossom = None
+
+            # Compute delta1: the minimum value of any vertex dual.
+            if not maxcardinality:
+                deltatype = 1
+                delta = min(dualvar.values())
+
+            # Compute delta2: the minimum slack on any edge between
+            # an S-vertex and a free vertex.
+            for v in G.nodes():
+                if label.get(inblossom[v]) is None and bestedge.get(v) is not None:
+                    d = slack(*bestedge[v])
+                    if deltatype == -1 or d < delta:
+                        delta = d
+                        deltatype = 2
+                        deltaedge = bestedge[v]
+
+            # Compute delta3: half the minimum slack on any edge between
+            # a pair of S-blossoms.
+            for b in blossomparent:
+                if (
+                    blossomparent[b] is None
+                    and label.get(b) == 1
+                    and bestedge.get(b) is not None
+                ):
+                    kslack = slack(*bestedge[b])
+                    if allinteger:
+                        assert (kslack % 2) == 0
+                        d = kslack // 2
+                    else:
+                        d = kslack / 2.0
+                    if deltatype == -1 or d < delta:
+                        delta = d
+                        deltatype = 3
+                        deltaedge = bestedge[b]
+
+            # Compute delta4: minimum z variable of any T-blossom.
+            for b in blossomdual:
+                if (
+                    blossomparent[b] is None
+                    and label.get(b) == 2
+                    and (deltatype == -1 or blossomdual[b] < delta)
+                ):
+                    delta = blossomdual[b]
+                    deltatype = 4
+                    deltablossom = b
+
+            if deltatype == -1:
+                # No further improvement possible; max-cardinality optimum
+                # reached. Do a final delta update to make the optimum
+                # verifiable.
+                assert maxcardinality
+                deltatype = 1
+                delta = max(0, min(dualvar.values()))
+
+            # Update dual variables according to delta.
+            for v in gnodes:
+                if label.get(inblossom[v]) == 1:
+                    # S-vertex: 2*u = 2*u - 2*delta
+                    dualvar[v] -= delta
+                elif label.get(inblossom[v]) == 2:
+                    # T-vertex: 2*u = 2*u + 2*delta
+                    dualvar[v] += delta
+            for b in blossomdual:
+                if blossomparent[b] is None:
+                    if label.get(b) == 1:
+                        # top-level S-blossom: z = z + 2*delta
+                        blossomdual[b] += delta
+                    elif label.get(b) == 2:
+                        # top-level T-blossom: z = z - 2*delta
+                        blossomdual[b] -= delta
+
+            # Take action at the point where minimum delta occurred.
+            if deltatype == 1:
+                # No further improvement possible; optimum reached.
+                break
+            elif deltatype == 2:
+                # Use the least-slack edge to continue the search.
+                (v, w) = deltaedge
+                assert label[inblossom[v]] == 1
+                allowedge[(v, w)] = allowedge[(w, v)] = True
+                queue.append(v)
+            elif deltatype == 3:
+                # Use the least-slack edge to continue the search.
+                (v, w) = deltaedge
+                allowedge[(v, w)] = allowedge[(w, v)] = True
+                assert label[inblossom[v]] == 1
+                queue.append(v)
+            elif deltatype == 4:
+                # Expand the least-z blossom.
+                expandBlossom(deltablossom, False)
+
+            # End of a this substage.
+
+        # Paranoia check that the matching is symmetric.
+        for v in mate:
+            assert mate[mate[v]] == v
+
+        # Stop when no more augmenting path can be found.
+        if not augmented:
+            break
+
+        # End of a stage; expand all S-blossoms which have zero dual.
+        for b in list(blossomdual.keys()):
+            if b not in blossomdual:
+                continue  # already expanded
+            if blossomparent[b] is None and label.get(b) == 1 and blossomdual[b] == 0:
+                expandBlossom(b, True)
+
+    # Verify that we reached the optimum solution (only for integer weights).
+    if allinteger:
+        verifyOptimum()
+
+    return matching_dict_to_set(mate)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/mis.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/mis.py
new file mode 100644
index 0000000000000000000000000000000000000000..0652ac4acec51c86edef8e8ed963d634c40f12ad
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/mis.py
@@ -0,0 +1,78 @@
+"""
+Algorithm to find a maximal (not maximum) independent set.
+
+"""
+
+import networkx as nx
+from networkx.utils import not_implemented_for, py_random_state
+
+__all__ = ["maximal_independent_set"]
+
+
+@not_implemented_for("directed")
+@py_random_state(2)
+@nx._dispatchable
+def maximal_independent_set(G, nodes=None, seed=None):
+    """Returns a random maximal independent set guaranteed to contain
+    a given set of nodes.
+
+    An independent set is a set of nodes such that the subgraph
+    of G induced by these nodes contains no edges. A maximal
+    independent set is an independent set such that it is not possible
+    to add a new node and still get an independent set.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    nodes : list or iterable
+       Nodes that must be part of the independent set. This set of nodes
+       must be independent.
+
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    indep_nodes : list
+       List of nodes that are part of a maximal independent set.
+
+    Raises
+    ------
+    NetworkXUnfeasible
+       If the nodes in the provided list are not part of the graph or
+       do not form an independent set, an exception is raised.
+
+    NetworkXNotImplemented
+        If `G` is directed.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(5)
+    >>> nx.maximal_independent_set(G)  # doctest: +SKIP
+    [4, 0, 2]
+    >>> nx.maximal_independent_set(G, [1])  # doctest: +SKIP
+    [1, 3]
+
+    Notes
+    -----
+    This algorithm does not solve the maximum independent set problem.
+
+    """
+    if not nodes:
+        nodes = {seed.choice(list(G))}
+    else:
+        nodes = set(nodes)
+    if not nodes.issubset(G):
+        raise nx.NetworkXUnfeasible(f"{nodes} is not a subset of the nodes of G")
+    neighbors = set.union(*[set(G.adj[v]) for v in nodes])
+    if set.intersection(neighbors, nodes):
+        raise nx.NetworkXUnfeasible(f"{nodes} is not an independent set of G")
+    indep_nodes = list(nodes)
+    available_nodes = set(G.nodes()).difference(neighbors.union(nodes))
+    while available_nodes:
+        node = seed.choice(list(available_nodes))
+        indep_nodes.append(node)
+        available_nodes.difference_update(list(G.adj[node]) + [node])
+    return indep_nodes
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/moral.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/moral.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2acf80f6c3715da57dfc92e4c2d2daf986b3c29
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/moral.py
@@ -0,0 +1,59 @@
+r"""Function for computing the moral graph of a directed graph."""
+
+import itertools
+
+import networkx as nx
+from networkx.utils import not_implemented_for
+
+__all__ = ["moral_graph"]
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable(returns_graph=True)
+def moral_graph(G):
+    r"""Return the Moral Graph
+
+    Returns the moralized graph of a given directed graph.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        Directed graph
+
+    Returns
+    -------
+    H : NetworkX graph
+        The undirected moralized graph of G
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If `G` is undirected.
+
+    Examples
+    --------
+    >>> G = nx.DiGraph([(1, 2), (2, 3), (2, 5), (3, 4), (4, 3)])
+    >>> G_moral = nx.moral_graph(G)
+    >>> G_moral.edges()
+    EdgeView([(1, 2), (2, 3), (2, 5), (2, 4), (3, 4)])
+
+    Notes
+    -----
+    A moral graph is an undirected graph H = (V, E) generated from a
+    directed Graph, where if a node has more than one parent node, edges
+    between these parent nodes are inserted and all directed edges become
+    undirected.
+
+    https://en.wikipedia.org/wiki/Moral_graph
+
+    References
+    ----------
+    .. [1] Wray L. Buntine. 1995. Chain graphs for learning.
+           In Proceedings of the Eleventh conference on Uncertainty
+           in artificial intelligence (UAI'95)
+    """
+    H = G.to_undirected()
+    for preds in G.pred.values():
+        predecessors_combinations = itertools.combinations(preds, r=2)
+        H.add_edges_from(predecessors_combinations)
+    return H
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/node_classification.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/node_classification.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b5088e10c481b9a19380228dbae57efed4c7a36
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/node_classification.py
@@ -0,0 +1,219 @@
+"""This module provides the functions for node classification problem.
+
+The functions in this module are not imported
+into the top level `networkx` namespace.
+You can access these functions by importing
+the `networkx.algorithms.node_classification` modules,
+then accessing the functions as attributes of `node_classification`.
+For example:
+
+  >>> from networkx.algorithms import node_classification
+  >>> G = nx.path_graph(4)
+  >>> G.edges()
+  EdgeView([(0, 1), (1, 2), (2, 3)])
+  >>> G.nodes[0]["label"] = "A"
+  >>> G.nodes[3]["label"] = "B"
+  >>> node_classification.harmonic_function(G)
+  ['A', 'A', 'B', 'B']
+
+References
+----------
+Zhu, X., Ghahramani, Z., & Lafferty, J. (2003, August).
+Semi-supervised learning using gaussian fields and harmonic functions.
+In ICML (Vol. 3, pp. 912-919).
+"""
+
+import networkx as nx
+
+__all__ = ["harmonic_function", "local_and_global_consistency"]
+
+
+@nx.utils.not_implemented_for("directed")
+@nx._dispatchable(node_attrs="label_name")
+def harmonic_function(G, max_iter=30, label_name="label"):
+    """Node classification by Harmonic function
+
+    Function for computing Harmonic function algorithm by Zhu et al.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+    max_iter : int
+        maximum number of iterations allowed
+    label_name : string
+        name of target labels to predict
+
+    Returns
+    -------
+    predicted : list
+        List of length ``len(G)`` with the predicted labels for each node.
+
+    Raises
+    ------
+    NetworkXError
+        If no nodes in `G` have attribute `label_name`.
+
+    Examples
+    --------
+    >>> from networkx.algorithms import node_classification
+    >>> G = nx.path_graph(4)
+    >>> G.nodes[0]["label"] = "A"
+    >>> G.nodes[3]["label"] = "B"
+    >>> G.nodes(data=True)
+    NodeDataView({0: {'label': 'A'}, 1: {}, 2: {}, 3: {'label': 'B'}})
+    >>> G.edges()
+    EdgeView([(0, 1), (1, 2), (2, 3)])
+    >>> predicted = node_classification.harmonic_function(G)
+    >>> predicted
+    ['A', 'A', 'B', 'B']
+
+    References
+    ----------
+    Zhu, X., Ghahramani, Z., & Lafferty, J. (2003, August).
+    Semi-supervised learning using gaussian fields and harmonic functions.
+    In ICML (Vol. 3, pp. 912-919).
+    """
+    import numpy as np
+    import scipy as sp
+
+    X = nx.to_scipy_sparse_array(G)  # adjacency matrix
+    labels, label_dict = _get_label_info(G, label_name)
+
+    if labels.shape[0] == 0:
+        raise nx.NetworkXError(
+            f"No node on the input graph is labeled by '{label_name}'."
+        )
+
+    n_samples = X.shape[0]
+    n_classes = label_dict.shape[0]
+    F = np.zeros((n_samples, n_classes))
+
+    # Build propagation matrix
+    degrees = X.sum(axis=0)
+    degrees[degrees == 0] = 1  # Avoid division by 0
+    D = sp.sparse.dia_array((1.0 / degrees, 0), shape=(n_samples, n_samples)).tocsr()
+    P = (D @ X).tolil()
+    P[labels[:, 0]] = 0  # labels[:, 0] indicates IDs of labeled nodes
+    # Build base matrix
+    B = np.zeros((n_samples, n_classes))
+    B[labels[:, 0], labels[:, 1]] = 1
+
+    for _ in range(max_iter):
+        F = (P @ F) + B
+
+    return label_dict[np.argmax(F, axis=1)].tolist()
+
+
+@nx.utils.not_implemented_for("directed")
+@nx._dispatchable(node_attrs="label_name")
+def local_and_global_consistency(G, alpha=0.99, max_iter=30, label_name="label"):
+    """Node classification by Local and Global Consistency
+
+    Function for computing Local and global consistency algorithm by Zhou et al.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+    alpha : float
+        Clamping factor
+    max_iter : int
+        Maximum number of iterations allowed
+    label_name : string
+        Name of target labels to predict
+
+    Returns
+    -------
+    predicted : list
+        List of length ``len(G)`` with the predicted labels for each node.
+
+    Raises
+    ------
+    NetworkXError
+        If no nodes in `G` have attribute `label_name`.
+
+    Examples
+    --------
+    >>> from networkx.algorithms import node_classification
+    >>> G = nx.path_graph(4)
+    >>> G.nodes[0]["label"] = "A"
+    >>> G.nodes[3]["label"] = "B"
+    >>> G.nodes(data=True)
+    NodeDataView({0: {'label': 'A'}, 1: {}, 2: {}, 3: {'label': 'B'}})
+    >>> G.edges()
+    EdgeView([(0, 1), (1, 2), (2, 3)])
+    >>> predicted = node_classification.local_and_global_consistency(G)
+    >>> predicted
+    ['A', 'A', 'B', 'B']
+
+    References
+    ----------
+    Zhou, D., Bousquet, O., Lal, T. N., Weston, J., & Schölkopf, B. (2004).
+    Learning with local and global consistency.
+    Advances in neural information processing systems, 16(16), 321-328.
+    """
+    import numpy as np
+    import scipy as sp
+
+    X = nx.to_scipy_sparse_array(G)  # adjacency matrix
+    labels, label_dict = _get_label_info(G, label_name)
+
+    if labels.shape[0] == 0:
+        raise nx.NetworkXError(
+            f"No node on the input graph is labeled by '{label_name}'."
+        )
+
+    n_samples = X.shape[0]
+    n_classes = label_dict.shape[0]
+    F = np.zeros((n_samples, n_classes))
+
+    # Build propagation matrix
+    degrees = X.sum(axis=0)
+    degrees[degrees == 0] = 1  # Avoid division by 0
+    D2 = sp.sparse.dia_array(
+        (1.0 / np.sqrt(degrees), 0), shape=(n_samples, n_samples)
+    ).tocsr()
+    P = alpha * ((D2 @ X) @ D2)
+    # Build base matrix
+    B = np.zeros((n_samples, n_classes))
+    B[labels[:, 0], labels[:, 1]] = 1 - alpha
+
+    for _ in range(max_iter):
+        F = (P @ F) + B
+
+    return label_dict[np.argmax(F, axis=1)].tolist()
+
+
+def _get_label_info(G, label_name):
+    """Get and return information of labels from the input graph
+
+    Parameters
+    ----------
+    G : Network X graph
+    label_name : string
+        Name of the target label
+
+    Returns
+    -------
+    labels : numpy array, shape = [n_labeled_samples, 2]
+        Array of pairs of labeled node ID and label ID
+    label_dict : numpy array, shape = [n_classes]
+        Array of labels
+        i-th element contains the label corresponding label ID `i`
+    """
+    import numpy as np
+
+    labels = []
+    label_to_id = {}
+    lid = 0
+    for i, n in enumerate(G.nodes(data=True)):
+        if label_name in n[1]:
+            label = n[1][label_name]
+            if label not in label_to_id:
+                label_to_id[label] = lid
+                lid += 1
+            labels.append([i, label_to_id[label]])
+    labels = np.array(labels)
+    label_dict = np.array(
+        [label for label, _ in sorted(label_to_id.items(), key=lambda x: x[1])]
+    )
+    return (labels, label_dict)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/non_randomness.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/non_randomness.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b3a94f0d7855abcfaa2e022720592c3accb69e8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/non_randomness.py
@@ -0,0 +1,155 @@
+r"""Computation of graph non-randomness."""
+
+import math
+
+import networkx as nx
+from networkx.utils import not_implemented_for
+
+__all__ = ["non_randomness"]
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable(edge_attrs="weight")
+def non_randomness(G, k=None, weight="weight"):
+    """Compute the non-randomness of a graph.
+
+    The first value $R_G$ is the sum of non-randomness values of all
+    edges within the graph (where the non-randomness of an edge tends to be
+    small when the two nodes linked by that edge are from two different
+    communities).
+
+    The second value $R_G^*$ is a relative measure that indicates
+    to what extent `G` is different from a random graph in terms
+    of probability. The closer it is to 0, the higher the likelihood
+    the graph was generated by an Erdős--Rényi model.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        Graph must be undirected, connected, and without self-loops.
+
+    k : int or None, optional (default=None)
+        The number of communities in `G`.
+        If `k` is not set, the function uses a default community detection
+        algorithm (:func:`~networkx.algorithms.community.label_propagation_communities`)
+        to set it.
+
+    weight : string or None, optional (default="weight")
+        The name of an edge attribute that holds the numerical value used
+        as a weight. If `None`, then each edge has weight 1, i.e., the graph is
+        binary.
+
+    Returns
+    -------
+    (float, float) tuple
+        The first value is $R_G$, the non-randomness of the graph,
+        the second is $R_G^*$, the relative non-randomness
+        w.r.t. the Erdős--Rényi model.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If the input graph is directed or a multigraph.
+
+    NetworkXException
+        If the input graph is not connected.
+
+    NetworkXError
+        If the input graph contains self-loops or has no edges.
+
+    ValueError
+        If `k` is not in $\\{1, \\dots, n-1\\}$, where $n$ is the number of nodes,
+        or if `k` is such that the computed edge probability
+        $p = \\frac{2km}{n(n-k)}$ does not satisfy $0 < p < 1$.
+
+    Examples
+    --------
+    >>> G = nx.karate_club_graph()
+    >>> nr, nr_rd = nx.non_randomness(G, 2)
+    >>> nr, nr_rd = nx.non_randomness(G, 2, "weight")
+
+    When the number of communities `k` is not specified,
+    :func:`~networkx.algorithms.community.label_propagation_communities`
+    is used to compute it.
+    This algorithm can give different results depending on
+    the order of nodes and edges in the graph.
+    For example, while the following graphs are identical,
+    computing the non-randomness of each of them yields different results:
+
+    >>> G1, G2 = nx.Graph(), nx.Graph()
+    >>> G1.add_edges_from([(0, 1), (1, 2), (1, 3), (3, 4)])
+    >>> G2.add_edges_from([(0, 1), (1, 3), (1, 2), (3, 4)])
+    >>> [round(r, 6) for r in nx.non_randomness(G1)]
+    [-1.847759, -5.842437]
+    >>> [round(r, 6) for r in nx.non_randomness(G2)]
+    Traceback (most recent call last):
+     ...
+    ValueError: invalid number of communities for graph with 5 nodes and 4 edges: 2
+
+    This is because the community detection algorithm finds
+    1 community in `G1` and 2 communities in `G2`.
+    This can be resolved by specifying the number of communities `k`:
+
+    >>> [round(r, 6) for r in nx.non_randomness(G2, k=1)]
+    [-1.847759, -5.842437]
+
+    Notes
+    -----
+    If a `weight` argument is passed, this algorithm will use the eigenvalues
+    of the weighted adjacency matrix instead.
+
+    The output of this function corresponds to (4.4) and (4.5) in [1]_.
+    A lower value of $R^*_G$ indicates a more random graph;
+    one can think of $1 - \\Phi(R_G^*)$ as the similarity
+    between the graph and a random graph,
+    where $\\Phi(x)$ is the cumulative distribution function
+    of the standard normal distribution.
+
+    Theorem 2 in [2]_ states that for any graph $G$
+    with $n$ nodes, $m$ edges, and $k$ communities,
+    its non-randomness is bounded below by the non-randomness of an
+    $r$-regular graph (a graph where each node has degree $r$),
+    and bounded above by the non-randomness of an $l$-complete graph
+    (a graph where each community is a clique of $l$ nodes).
+
+    References
+    ----------
+    .. [1] Xiaowei Ying and Xintao Wu,
+           On Randomness Measures for Social Networks,
+           SIAM International Conference on Data Mining. 2009
+           https://doi.org/10.1137/1.9781611972795.61
+    .. [2] Ying, Xiaowei & Wu, Leting & Wu, Xintao. (2012).
+           A Spectrum-Based Framework for Quantifying Randomness of Social Networks.
+           IEEE Transactions on Knowledge and Data Engineering 23(12):1842--1856.
+           https://dl.acm.org/doi/abs/10.1109/TKDE.2010.218
+    """
+    import numpy as np
+
+    # corner case: graph has no edges
+    if nx.is_empty(G):
+        raise nx.NetworkXError("non_randomness not applicable to empty graphs")
+    if not nx.is_connected(G):
+        raise nx.NetworkXException("Non connected graph.")
+    if len(list(nx.selfloop_edges(G))) > 0:
+        raise nx.NetworkXError("Graph must not contain self-loops")
+
+    n = G.number_of_nodes()
+    m = G.number_of_edges()
+
+    if k is None:
+        k = len(tuple(nx.community.label_propagation_communities(G)))
+    if not 1 <= k < n or not 0 < (p := (2 * k * m) / (n * (n - k))) < 1:
+        err = (
+            f"invalid number of communities for graph with {n} nodes and {m} edges: {k}"
+        )
+        raise ValueError(err)
+
+    # eq. 4.4
+    eigenvalues = np.linalg.eigvals(nx.to_numpy_array(G, weight=weight))
+    nr = float(np.real(np.sum(eigenvalues[:k])))
+
+    # eq. 4.5
+    nr_rd = (nr - ((n - 2 * k) * p + k)) / math.sqrt(2 * k * p * (1 - p))
+
+    return nr, nr_rd
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/perfect_graph.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/perfect_graph.py
new file mode 100644
index 0000000000000000000000000000000000000000..d84cafb527310173931e8176d5851c2e420a710b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/perfect_graph.py
@@ -0,0 +1,73 @@
+import itertools
+
+import networkx as nx
+from networkx.utils.decorators import not_implemented_for
+
+__all__ = ["is_perfect_graph"]
+
+
+@nx._dispatchable
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+def is_perfect_graph(G):
+    r"""Return True if G is a perfect graph, else False.
+
+    A graph G is perfect if, for every induced subgraph H of G, the chromatic
+    number of H equals the size of the largest clique in H.
+
+    According to the **Strong Perfect Graph Theorem (SPGT)**:
+    A graph is perfect if and only if neither the graph G nor its complement
+    :math:`\overline{G}` contains an **induced odd hole** — an induced cycle of
+    odd length at least five without chords.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+        The graph to check. Must be a finite, simple, undirected graph.
+
+    Returns
+    -------
+    bool
+        True if G is a perfect graph, else False.
+
+    Notes
+    -----
+    This function uses a direct approach: cycle enumeration to detect
+    chordless odd cycles in G and :math:`\overline{G}`. This implementation
+    runs in exponential time in the worst case, since the number of chordless
+    cycles can grow exponentially.
+
+    The perfect-graph recognition problem is theoretically solvable in
+    polynomial time. Chudnovsky *et al.* (2006) proved it can be solved in
+    :math:`O(n^9)` time via a complex structural decomposition [1]_, [2]_.
+    This implementation opts for a direct, transparent check rather than
+    implementing that high-degree polynomial-time decomposition algorithm.
+
+    See Also
+    --------
+    is_chordal, is_bipartite :
+        Related checks for specific categories of perfect graphs, such as chordal
+        graphs, and bipartite graphs.
+    chordless_cycles :
+        Used to detect "holes" in the graph
+
+    References
+    ----------
+    .. [1] M. Chudnovsky, N. Robertson, P. Seymour, and R. Thomas,
+           *The Strong Perfect Graph Theorem*,
+           Annals of Mathematics, vol. 164, no. 1, pp. 51–229, 2006.
+           https://doi.org/10.4007/annals.2006.164.51
+    .. [2] M. Chudnovsky, G. Cornuéjols, X. Liu, P. Seymour, and K. Vušković,
+           *Recognizing Berge Graphs*,
+           Combinatorica 25(2): 143–186, 2005.
+           DOI: 10.1007/s00493-005-0003-8
+           Preprint available at:
+           https://web.math.princeton.edu/~pds/papers/algexp/Bergealg.pdf
+    """
+
+    return not any(
+        (len(c) >= 5) and (len(c) % 2 == 1)
+        for c in itertools.chain(
+            nx.chordless_cycles(G), nx.chordless_cycles(nx.complement(G))
+        )
+    )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/planar_drawing.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/planar_drawing.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea25809b6aeb198b23b44fe9878775d11b7e109c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/planar_drawing.py
@@ -0,0 +1,464 @@
+from collections import defaultdict
+
+import networkx as nx
+
+__all__ = ["combinatorial_embedding_to_pos"]
+
+
+def combinatorial_embedding_to_pos(embedding, fully_triangulate=False):
+    """Assigns every node a (x, y) position based on the given embedding
+
+    The algorithm iteratively inserts nodes of the input graph in a certain
+    order and rearranges previously inserted nodes so that the planar drawing
+    stays valid. This is done efficiently by only maintaining relative
+    positions during the node placements and calculating the absolute positions
+    at the end. For more information see [1]_.
+
+    Parameters
+    ----------
+    embedding : nx.PlanarEmbedding
+        This defines the order of the edges
+
+    fully_triangulate : bool
+        If set to True the algorithm adds edges to a copy of the input
+        embedding and makes it chordal.
+
+    Returns
+    -------
+    pos : dict
+        Maps each node to a tuple that defines the (x, y) position
+
+    References
+    ----------
+    .. [1] M. Chrobak and T.H. Payne:
+        A Linear-time Algorithm for Drawing a Planar Graph on a Grid 1989
+        http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.51.6677
+
+    """
+    if len(embedding.nodes()) < 4:
+        # Position the node in any triangle
+        default_positions = [(0, 0), (2, 0), (1, 1)]
+        pos = {}
+        for i, v in enumerate(embedding.nodes()):
+            pos[v] = default_positions[i]
+        return pos
+
+    embedding, outer_face = triangulate_embedding(embedding, fully_triangulate)
+
+    # The following dicts map a node to another node
+    # If a node is not in the key set it means that the node is not yet in G_k
+    # If a node maps to None then the corresponding subtree does not exist
+    left_t_child = {}
+    right_t_child = {}
+
+    # The following dicts map a node to an integer
+    delta_x = {}
+    y_coordinate = {}
+
+    node_list = get_canonical_ordering(embedding, outer_face)
+
+    # 1. Phase: Compute relative positions
+
+    # Initialization
+    v1, v2, v3 = node_list[0][0], node_list[1][0], node_list[2][0]
+
+    delta_x[v1] = 0
+    y_coordinate[v1] = 0
+    right_t_child[v1] = v3
+    left_t_child[v1] = None
+
+    delta_x[v2] = 1
+    y_coordinate[v2] = 0
+    right_t_child[v2] = None
+    left_t_child[v2] = None
+
+    delta_x[v3] = 1
+    y_coordinate[v3] = 1
+    right_t_child[v3] = v2
+    left_t_child[v3] = None
+
+    for k in range(3, len(node_list)):
+        vk, contour_nbrs = node_list[k]
+        wp = contour_nbrs[0]
+        wp1 = contour_nbrs[1]
+        wq = contour_nbrs[-1]
+        wq1 = contour_nbrs[-2]
+        adds_mult_tri = len(contour_nbrs) > 2
+
+        # Stretch gaps:
+        delta_x[wp1] += 1
+        delta_x[wq] += 1
+
+        delta_x_wp_wq = sum(delta_x[x] for x in contour_nbrs[1:])
+
+        # Adjust offsets
+        delta_x[vk] = (-y_coordinate[wp] + delta_x_wp_wq + y_coordinate[wq]) // 2
+        y_coordinate[vk] = (y_coordinate[wp] + delta_x_wp_wq + y_coordinate[wq]) // 2
+        delta_x[wq] = delta_x_wp_wq - delta_x[vk]
+        if adds_mult_tri:
+            delta_x[wp1] -= delta_x[vk]
+
+        # Install v_k:
+        right_t_child[wp] = vk
+        right_t_child[vk] = wq
+        if adds_mult_tri:
+            left_t_child[vk] = wp1
+            right_t_child[wq1] = None
+        else:
+            left_t_child[vk] = None
+
+    # 2. Phase: Set absolute positions
+    pos = {}
+    pos[v1] = (0, y_coordinate[v1])
+    remaining_nodes = [v1]
+    while remaining_nodes:
+        parent_node = remaining_nodes.pop()
+
+        # Calculate position for left child
+        set_position(
+            parent_node, left_t_child, remaining_nodes, delta_x, y_coordinate, pos
+        )
+        # Calculate position for right child
+        set_position(
+            parent_node, right_t_child, remaining_nodes, delta_x, y_coordinate, pos
+        )
+    return pos
+
+
+def set_position(parent, tree, remaining_nodes, delta_x, y_coordinate, pos):
+    """Helper method to calculate the absolute position of nodes."""
+    child = tree[parent]
+    parent_node_x = pos[parent][0]
+    if child is not None:
+        # Calculate pos of child
+        child_x = parent_node_x + delta_x[child]
+        pos[child] = (child_x, y_coordinate[child])
+        # Remember to calculate pos of its children
+        remaining_nodes.append(child)
+
+
+def get_canonical_ordering(embedding, outer_face):
+    """Returns a canonical ordering of the nodes
+
+    The canonical ordering of nodes (v1, ..., vn) must fulfill the following
+    conditions:
+    (See Lemma 1 in [2]_)
+
+    - For the subgraph G_k of the input graph induced by v1, ..., vk it holds:
+        - 2-connected
+        - internally triangulated
+        - the edge (v1, v2) is part of the outer face
+    - For a node v(k+1) the following holds:
+        - The node v(k+1) is part of the outer face of G_k
+        - It has at least two neighbors in G_k
+        - All neighbors of v(k+1) in G_k lie consecutively on the outer face of
+          G_k (excluding the edge (v1, v2)).
+
+    The algorithm used here starts with G_n (containing all nodes). It first
+    selects the nodes v1 and v2. And then tries to find the order of the other
+    nodes by checking which node can be removed in order to fulfill the
+    conditions mentioned above. This is done by calculating the number of
+    chords of nodes on the outer face. For more information see [1]_.
+
+    Parameters
+    ----------
+    embedding : nx.PlanarEmbedding
+        The embedding must be triangulated
+    outer_face : list
+        The nodes on the outer face of the graph
+
+    Returns
+    -------
+    ordering : list
+        A list of tuples `(vk, wp_wq)`. Here `vk` is the node at this position
+        in the canonical ordering. The element `wp_wq` is a list of nodes that
+        make up the outer face of G_k.
+
+    References
+    ----------
+    .. [1] Steven Chaplick.
+        Canonical Orders of Planar Graphs and (some of) Their Applications 2015
+        https://wuecampus2.uni-wuerzburg.de/moodle/pluginfile.php/545727/mod_resource/content/0/vg-ss15-vl03-canonical-orders-druckversion.pdf
+    .. [2] M. Chrobak and T.H. Payne:
+        A Linear-time Algorithm for Drawing a Planar Graph on a Grid 1989
+        http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.51.6677
+
+    """
+    v1 = outer_face[0]
+    v2 = outer_face[1]
+    chords = defaultdict(int)  # Maps nodes to the number of their chords
+    marked_nodes = set()
+    ready_to_pick = set(outer_face)
+
+    # Initialize outer_face_ccw_nbr (do not include v1 -> v2)
+    outer_face_ccw_nbr = {}
+    prev_nbr = v2
+    for idx in range(2, len(outer_face)):
+        outer_face_ccw_nbr[prev_nbr] = outer_face[idx]
+        prev_nbr = outer_face[idx]
+    outer_face_ccw_nbr[prev_nbr] = v1
+
+    # Initialize outer_face_cw_nbr (do not include v2 -> v1)
+    outer_face_cw_nbr = {}
+    prev_nbr = v1
+    for idx in range(len(outer_face) - 1, 0, -1):
+        outer_face_cw_nbr[prev_nbr] = outer_face[idx]
+        prev_nbr = outer_face[idx]
+
+    def is_outer_face_nbr(x, y):
+        if x not in outer_face_ccw_nbr:
+            return outer_face_cw_nbr[x] == y
+        if x not in outer_face_cw_nbr:
+            return outer_face_ccw_nbr[x] == y
+        return outer_face_ccw_nbr[x] == y or outer_face_cw_nbr[x] == y
+
+    def is_on_outer_face(x):
+        return x not in marked_nodes and (x in outer_face_ccw_nbr or x == v1)
+
+    # Initialize number of chords
+    for v in outer_face:
+        for nbr in embedding.neighbors_cw_order(v):
+            if is_on_outer_face(nbr) and not is_outer_face_nbr(v, nbr):
+                chords[v] += 1
+                ready_to_pick.discard(v)
+
+    # Initialize canonical_ordering
+    canonical_ordering = [None] * len(embedding.nodes())
+    canonical_ordering[0] = (v1, [])
+    canonical_ordering[1] = (v2, [])
+    ready_to_pick.discard(v1)
+    ready_to_pick.discard(v2)
+
+    for k in range(len(embedding.nodes()) - 1, 1, -1):
+        # 1. Pick v from ready_to_pick
+        v = ready_to_pick.pop()
+        marked_nodes.add(v)
+
+        # v has exactly two neighbors on the outer face (wp and wq)
+        wp = None
+        wq = None
+        # Iterate over neighbors of v to find wp and wq
+        nbr_iterator = iter(embedding.neighbors_cw_order(v))
+        while True:
+            nbr = next(nbr_iterator)
+            if nbr in marked_nodes:
+                # Only consider nodes that are not yet removed
+                continue
+            if is_on_outer_face(nbr):
+                # nbr is either wp or wq
+                if nbr == v1:
+                    wp = v1
+                elif nbr == v2:
+                    wq = v2
+                else:
+                    if outer_face_cw_nbr[nbr] == v:
+                        # nbr is wp
+                        wp = nbr
+                    else:
+                        # nbr is wq
+                        wq = nbr
+            if wp is not None and wq is not None:
+                # We don't need to iterate any further
+                break
+
+        # Obtain new nodes on outer face (neighbors of v from wp to wq)
+        wp_wq = [wp]
+        nbr = wp
+        while nbr != wq:
+            # Get next neighbor (clockwise on the outer face)
+            next_nbr = embedding[v][nbr]["ccw"]
+            wp_wq.append(next_nbr)
+            # Update outer face
+            outer_face_cw_nbr[nbr] = next_nbr
+            outer_face_ccw_nbr[next_nbr] = nbr
+            # Move to next neighbor of v
+            nbr = next_nbr
+
+        if len(wp_wq) == 2:
+            # There was a chord between wp and wq, decrease number of chords
+            chords[wp] -= 1
+            if chords[wp] == 0:
+                ready_to_pick.add(wp)
+            chords[wq] -= 1
+            if chords[wq] == 0:
+                ready_to_pick.add(wq)
+        else:
+            # Update all chords involving w_(p+1) to w_(q-1)
+            new_face_nodes = set(wp_wq[1:-1])
+            for w in new_face_nodes:
+                # If we do not find a chord for w later we can pick it next
+                ready_to_pick.add(w)
+                for nbr in embedding.neighbors_cw_order(w):
+                    if is_on_outer_face(nbr) and not is_outer_face_nbr(w, nbr):
+                        # There is a chord involving w
+                        chords[w] += 1
+                        ready_to_pick.discard(w)
+                        if nbr not in new_face_nodes:
+                            # Also increase chord for the neighbor
+                            # We only iterator over new_face_nodes
+                            chords[nbr] += 1
+                            ready_to_pick.discard(nbr)
+        # Set the canonical ordering node and the list of contour neighbors
+        canonical_ordering[k] = (v, wp_wq)
+
+    return canonical_ordering
+
+
+def triangulate_face(embedding, v1, v2):
+    """Triangulates the face given by half edge (v, w)
+
+    Parameters
+    ----------
+    embedding : nx.PlanarEmbedding
+    v1 : node
+        The half-edge (v1, v2) belongs to the face that gets triangulated
+    v2 : node
+    """
+    _, v3 = embedding.next_face_half_edge(v1, v2)
+    _, v4 = embedding.next_face_half_edge(v2, v3)
+    if v1 in (v2, v3):
+        # The component has less than 3 nodes
+        return
+    while v1 != v4:
+        # Add edge if not already present on other side
+        if embedding.has_edge(v1, v3):
+            # Cannot triangulate at this position
+            v1, v2, v3 = v2, v3, v4
+        else:
+            # Add edge for triangulation
+            embedding.add_half_edge(v1, v3, ccw=v2)
+            embedding.add_half_edge(v3, v1, cw=v2)
+            v1, v2, v3 = v1, v3, v4
+        # Get next node
+        _, v4 = embedding.next_face_half_edge(v2, v3)
+
+
+def triangulate_embedding(embedding, fully_triangulate=True):
+    """Triangulates the embedding.
+
+    Traverses faces of the embedding and adds edges to a copy of the
+    embedding to triangulate it.
+    The method also ensures that the resulting graph is 2-connected by adding
+    edges if the same vertex is contained twice on a path around a face.
+
+    Parameters
+    ----------
+    embedding : nx.PlanarEmbedding
+        The input graph must contain at least 3 nodes.
+
+    fully_triangulate : bool
+        If set to False the face with the most nodes is chooses as outer face.
+        This outer face does not get triangulated.
+
+    Returns
+    -------
+    (embedding, outer_face) : (nx.PlanarEmbedding, list) tuple
+        The element `embedding` is a new embedding containing all edges from
+        the input embedding and the additional edges to triangulate the graph.
+        The element `outer_face` is a list of nodes that lie on the outer face.
+        If the graph is fully triangulated these are three arbitrary connected
+        nodes.
+
+    """
+    if len(embedding.nodes) <= 1:
+        return embedding, list(embedding.nodes)
+    embedding = nx.PlanarEmbedding(embedding)
+
+    # Get a list with a node for each connected component
+    component_nodes = [next(iter(x)) for x in nx.connected_components(embedding)]
+
+    # 1. Make graph a single component (add edge between components)
+    for i in range(len(component_nodes) - 1):
+        v1 = component_nodes[i]
+        v2 = component_nodes[i + 1]
+        embedding.connect_components(v1, v2)
+
+    # 2. Calculate faces, ensure 2-connectedness and determine outer face
+    outer_face = []  # A face with the most number of nodes
+    face_list = []
+    edges_visited = set()  # Used to keep track of already visited faces
+    for v in embedding.nodes():
+        for w in embedding.neighbors_cw_order(v):
+            new_face = make_bi_connected(embedding, v, w, edges_visited)
+            if new_face:
+                # Found a new face
+                face_list.append(new_face)
+                if len(new_face) > len(outer_face):
+                    # The face is a candidate to be the outer face
+                    outer_face = new_face
+
+    # 3. Triangulate (internal) faces
+    for face in face_list:
+        if face is not outer_face or fully_triangulate:
+            # Triangulate this face
+            triangulate_face(embedding, face[0], face[1])
+
+    if fully_triangulate:
+        v1 = outer_face[0]
+        v2 = outer_face[1]
+        v3 = embedding[v2][v1]["ccw"]
+        outer_face = [v1, v2, v3]
+
+    return embedding, outer_face
+
+
+def make_bi_connected(embedding, starting_node, outgoing_node, edges_counted):
+    """Triangulate a face and make it 2-connected
+
+    This method also adds all edges on the face to `edges_counted`.
+
+    Parameters
+    ----------
+    embedding: nx.PlanarEmbedding
+        The embedding that defines the faces
+    starting_node : node
+        A node on the face
+    outgoing_node : node
+        A node such that the half edge (starting_node, outgoing_node) belongs
+        to the face
+    edges_counted: set
+        Set of all half-edges that belong to a face that have been visited
+
+    Returns
+    -------
+    face_nodes: list
+        A list of all nodes at the border of this face
+    """
+
+    # Check if the face has already been calculated
+    if (starting_node, outgoing_node) in edges_counted:
+        # This face was already counted
+        return []
+    edges_counted.add((starting_node, outgoing_node))
+
+    # Add all edges to edges_counted which have this face to their left
+    v1 = starting_node
+    v2 = outgoing_node
+    face_list = [starting_node]  # List of nodes around the face
+    face_set = set(face_list)  # Set for faster queries
+    _, v3 = embedding.next_face_half_edge(v1, v2)
+
+    # Move the nodes v1, v2, v3 around the face:
+    while v2 != starting_node or v3 != outgoing_node:
+        if v1 == v2:
+            raise nx.NetworkXException("Invalid half-edge")
+        # cycle is not completed yet
+        if v2 in face_set:
+            # v2 encountered twice: Add edge to ensure 2-connectedness
+            embedding.add_half_edge(v1, v3, ccw=v2)
+            embedding.add_half_edge(v3, v1, cw=v2)
+            edges_counted.add((v2, v3))
+            edges_counted.add((v3, v1))
+            v2 = v1
+        else:
+            face_set.add(v2)
+            face_list.append(v2)
+
+        # set next edge
+        v1 = v2
+        v2, v3 = embedding.next_face_half_edge(v2, v3)
+
+        # remember that this edge has been counted
+        edges_counted.add((v1, v2))
+
+    return face_list
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/planarity.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/planarity.py
new file mode 100644
index 0000000000000000000000000000000000000000..52f0b576071c969dd0449a941493573b5c807448
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/planarity.py
@@ -0,0 +1,1463 @@
+from collections import defaultdict
+from copy import deepcopy
+
+import networkx as nx
+
+__all__ = ["check_planarity", "is_planar", "PlanarEmbedding"]
+
+
+@nx._dispatchable
+def is_planar(G):
+    """Returns True if and only if `G` is planar.
+
+    A graph is *planar* iff it can be drawn in a plane without
+    any edge intersections.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    Returns
+    -------
+    bool
+       Whether the graph is planar.
+
+    Examples
+    --------
+    >>> G = nx.Graph([(0, 1), (0, 2)])
+    >>> nx.is_planar(G)
+    True
+    >>> nx.is_planar(nx.complete_graph(5))
+    False
+
+    See Also
+    --------
+    check_planarity :
+        Check if graph is planar *and* return a `PlanarEmbedding` instance if True.
+    """
+
+    return check_planarity(G, counterexample=False)[0]
+
+
+@nx._dispatchable(returns_graph=True)
+def check_planarity(G, counterexample=False):
+    """Check if a graph is planar and return a counterexample or an embedding.
+
+    A graph is planar iff it can be drawn in a plane without
+    any edge intersections.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+    counterexample : bool
+        A Kuratowski subgraph (to proof non planarity) is only returned if set
+        to true.
+
+    Returns
+    -------
+    (is_planar, certificate) : (bool, NetworkX graph) tuple
+        is_planar is true if the graph is planar.
+        If the graph is planar `certificate` is a PlanarEmbedding
+        otherwise it is a Kuratowski subgraph.
+
+    Examples
+    --------
+    >>> G = nx.Graph([(0, 1), (0, 2)])
+    >>> is_planar, P = nx.check_planarity(G)
+    >>> print(is_planar)
+    True
+
+    When `G` is planar, a `PlanarEmbedding` instance is returned:
+
+    >>> P.get_data()
+    {0: [1, 2], 1: [0], 2: [0]}
+
+    Notes
+    -----
+    A (combinatorial) embedding consists of cyclic orderings of the incident
+    edges at each vertex. Given such an embedding there are multiple approaches
+    discussed in literature to drawing the graph (subject to various
+    constraints, e.g. integer coordinates), see e.g. [2].
+
+    The planarity check algorithm and extraction of the combinatorial embedding
+    is based on the Left-Right Planarity Test [1].
+
+    A counterexample is only generated if the corresponding parameter is set,
+    because the complexity of the counterexample generation is higher.
+
+    See also
+    --------
+    is_planar :
+        Check for planarity without creating a `PlanarEmbedding` or counterexample.
+
+    References
+    ----------
+    .. [1] Ulrik Brandes:
+        The Left-Right Planarity Test
+        2009
+        http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.217.9208
+    .. [2] Takao Nishizeki, Md Saidur Rahman:
+        Planar graph drawing
+        Lecture Notes Series on Computing: Volume 12
+        2004
+    """
+
+    planarity_state = LRPlanarity(G)
+    embedding = planarity_state.lr_planarity()
+    if embedding is None:
+        # graph is not planar
+        if counterexample:
+            return False, get_counterexample(G)
+        else:
+            return False, None
+    else:
+        # graph is planar
+        return True, embedding
+
+
+@nx._dispatchable(returns_graph=True)
+def check_planarity_recursive(G, counterexample=False):
+    """Recursive version of :meth:`check_planarity`."""
+    planarity_state = LRPlanarity(G)
+    embedding = planarity_state.lr_planarity_recursive()
+    if embedding is None:
+        # graph is not planar
+        if counterexample:
+            return False, get_counterexample_recursive(G)
+        else:
+            return False, None
+    else:
+        # graph is planar
+        return True, embedding
+
+
+@nx._dispatchable(returns_graph=True)
+def get_counterexample(G):
+    """Obtains a Kuratowski subgraph.
+
+    Raises nx.NetworkXException if G is planar.
+
+    The function removes edges such that the graph is still not planar.
+    At some point the removal of any edge would make the graph planar.
+    This subgraph must be a Kuratowski subgraph.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    Returns
+    -------
+    subgraph : NetworkX graph
+        A Kuratowski subgraph that proves that G is not planar.
+
+    """
+    # copy graph
+    G = nx.Graph(G)
+
+    if check_planarity(G)[0]:
+        raise nx.NetworkXException("G is planar - no counter example.")
+
+    # find Kuratowski subgraph
+    subgraph = nx.Graph()
+    for u in G:
+        nbrs = list(G[u])
+        for v in nbrs:
+            G.remove_edge(u, v)
+            if check_planarity(G)[0]:
+                G.add_edge(u, v)
+                subgraph.add_edge(u, v)
+
+    return subgraph
+
+
+@nx._dispatchable(returns_graph=True)
+def get_counterexample_recursive(G):
+    """Recursive version of :meth:`get_counterexample`."""
+
+    # copy graph
+    G = nx.Graph(G)
+
+    if check_planarity_recursive(G)[0]:
+        raise nx.NetworkXException("G is planar - no counter example.")
+
+    # find Kuratowski subgraph
+    subgraph = nx.Graph()
+    for u in G:
+        nbrs = list(G[u])
+        for v in nbrs:
+            G.remove_edge(u, v)
+            if check_planarity_recursive(G)[0]:
+                G.add_edge(u, v)
+                subgraph.add_edge(u, v)
+
+    return subgraph
+
+
+class Interval:
+    """Represents a set of return edges.
+
+    All return edges in an interval induce a same constraint on the contained
+    edges, which means that all edges must either have a left orientation or
+    all edges must have a right orientation.
+    """
+
+    def __init__(self, low=None, high=None):
+        self.low = low
+        self.high = high
+
+    def empty(self):
+        """Check if the interval is empty"""
+        return self.low is None and self.high is None
+
+    def copy(self):
+        """Returns a copy of this interval"""
+        return Interval(self.low, self.high)
+
+    def conflicting(self, b, planarity_state):
+        """Returns True if interval I conflicts with edge b"""
+        return (
+            not self.empty()
+            and planarity_state.lowpt[self.high] > planarity_state.lowpt[b]
+        )
+
+
+class ConflictPair:
+    """Represents a different constraint between two intervals.
+
+    The edges in the left interval must have a different orientation than
+    the one in the right interval.
+    """
+
+    def __init__(self, left=Interval(), right=Interval()):
+        self.left = left
+        self.right = right
+
+    def swap(self):
+        """Swap left and right intervals"""
+        temp = self.left
+        self.left = self.right
+        self.right = temp
+
+    def lowest(self, planarity_state):
+        """Returns the lowest lowpoint of a conflict pair"""
+        if self.left.empty():
+            return planarity_state.lowpt[self.right.low]
+        if self.right.empty():
+            return planarity_state.lowpt[self.left.low]
+        return min(
+            planarity_state.lowpt[self.left.low], planarity_state.lowpt[self.right.low]
+        )
+
+
+def top_of_stack(l):
+    """Returns the element on top of the stack."""
+    if not l:
+        return None
+    return l[-1]
+
+
+class LRPlanarity:
+    """A class to maintain the state during planarity check."""
+
+    __slots__ = [
+        "G",
+        "roots",
+        "height",
+        "lowpt",
+        "lowpt2",
+        "nesting_depth",
+        "parent_edge",
+        "DG",
+        "adjs",
+        "ordered_adjs",
+        "ref",
+        "side",
+        "S",
+        "stack_bottom",
+        "lowpt_edge",
+        "left_ref",
+        "right_ref",
+        "embedding",
+    ]
+
+    def __init__(self, G):
+        # copy G without adding self-loops
+        self.G = nx.Graph()
+        self.G.add_nodes_from(G.nodes)
+        for e in G.edges:
+            if e[0] != e[1]:
+                self.G.add_edge(e[0], e[1])
+
+        self.roots = []
+
+        # distance from tree root
+        self.height = defaultdict(lambda: None)
+
+        self.lowpt = {}  # height of lowest return point of an edge
+        self.lowpt2 = {}  # height of second lowest return point
+        self.nesting_depth = {}  # for nesting order
+
+        # None -> missing edge
+        self.parent_edge = defaultdict(lambda: None)
+
+        # oriented DFS graph
+        self.DG = nx.DiGraph()
+        self.DG.add_nodes_from(G.nodes)
+
+        self.adjs = {}
+        self.ordered_adjs = {}
+
+        self.ref = defaultdict(lambda: None)
+        self.side = defaultdict(lambda: 1)
+
+        # stack of conflict pairs
+        self.S = []
+        self.stack_bottom = {}
+        self.lowpt_edge = {}
+
+        self.left_ref = {}
+        self.right_ref = {}
+
+        self.embedding = PlanarEmbedding()
+
+    def lr_planarity(self):
+        """Execute the LR planarity test.
+
+        Returns
+        -------
+        embedding : dict
+            If the graph is planar an embedding is returned. Otherwise None.
+        """
+        if self.G.order() > 2 and self.G.size() > 3 * self.G.order() - 6:
+            # graph is not planar
+            return None
+
+        # make adjacency lists for dfs
+        for v in self.G:
+            self.adjs[v] = list(self.G[v])
+
+        # orientation of the graph by depth first search traversal
+        for v in self.G:
+            if self.height[v] is None:
+                self.height[v] = 0
+                self.roots.append(v)
+                self.dfs_orientation(v)
+
+        # Free no longer used variables
+        self.G = None
+        self.lowpt2 = None
+        self.adjs = None
+
+        # testing
+        for v in self.DG:  # sort the adjacency lists by nesting depth
+            # note: this sorting leads to non linear time
+            self.ordered_adjs[v] = sorted(
+                self.DG[v], key=lambda x: self.nesting_depth[(v, x)]
+            )
+        for v in self.roots:
+            if not self.dfs_testing(v):
+                return None
+
+        # Free no longer used variables
+        self.height = None
+        self.lowpt = None
+        self.S = None
+        self.stack_bottom = None
+        self.lowpt_edge = None
+
+        for e in self.DG.edges:
+            self.nesting_depth[e] = self.sign(e) * self.nesting_depth[e]
+
+        self.embedding.add_nodes_from(self.DG.nodes)
+        for v in self.DG:
+            # sort the adjacency lists again
+            self.ordered_adjs[v] = sorted(
+                self.DG[v], key=lambda x: self.nesting_depth[(v, x)]
+            )
+            # initialize the embedding
+            previous_node = None
+            for w in self.ordered_adjs[v]:
+                self.embedding.add_half_edge(v, w, ccw=previous_node)
+                previous_node = w
+
+        # Free no longer used variables
+        self.DG = None
+        self.nesting_depth = None
+        self.ref = None
+
+        # compute the complete embedding
+        for v in self.roots:
+            self.dfs_embedding(v)
+
+        # Free no longer used variables
+        self.roots = None
+        self.parent_edge = None
+        self.ordered_adjs = None
+        self.left_ref = None
+        self.right_ref = None
+        self.side = None
+
+        return self.embedding
+
+    def lr_planarity_recursive(self):
+        """Recursive version of :meth:`lr_planarity`."""
+        if self.G.order() > 2 and self.G.size() > 3 * self.G.order() - 6:
+            # graph is not planar
+            return None
+
+        # orientation of the graph by depth first search traversal
+        for v in self.G:
+            if self.height[v] is None:
+                self.height[v] = 0
+                self.roots.append(v)
+                self.dfs_orientation_recursive(v)
+
+        # Free no longer used variable
+        self.G = None
+
+        # testing
+        for v in self.DG:  # sort the adjacency lists by nesting depth
+            # note: this sorting leads to non linear time
+            self.ordered_adjs[v] = sorted(
+                self.DG[v], key=lambda x: self.nesting_depth[(v, x)]
+            )
+        for v in self.roots:
+            if not self.dfs_testing_recursive(v):
+                return None
+
+        for e in self.DG.edges:
+            self.nesting_depth[e] = self.sign_recursive(e) * self.nesting_depth[e]
+
+        self.embedding.add_nodes_from(self.DG.nodes)
+        for v in self.DG:
+            # sort the adjacency lists again
+            self.ordered_adjs[v] = sorted(
+                self.DG[v], key=lambda x: self.nesting_depth[(v, x)]
+            )
+            # initialize the embedding
+            previous_node = None
+            for w in self.ordered_adjs[v]:
+                self.embedding.add_half_edge(v, w, ccw=previous_node)
+                previous_node = w
+
+        # compute the complete embedding
+        for v in self.roots:
+            self.dfs_embedding_recursive(v)
+
+        return self.embedding
+
+    def dfs_orientation(self, v):
+        """Orient the graph by DFS, compute lowpoints and nesting order."""
+        # the recursion stack
+        dfs_stack = [v]
+        # index of next edge to handle in adjacency list of each node
+        ind = defaultdict(lambda: 0)
+        # boolean to indicate whether to skip the initial work for an edge
+        skip_init = defaultdict(lambda: False)
+
+        while dfs_stack:
+            v = dfs_stack.pop()
+            e = self.parent_edge[v]
+
+            for w in self.adjs[v][ind[v] :]:
+                vw = (v, w)
+
+                if not skip_init[vw]:
+                    if (v, w) in self.DG.edges or (w, v) in self.DG.edges:
+                        ind[v] += 1
+                        continue  # the edge was already oriented
+
+                    self.DG.add_edge(v, w)  # orient the edge
+
+                    self.lowpt[vw] = self.height[v]
+                    self.lowpt2[vw] = self.height[v]
+                    if self.height[w] is None:  # (v, w) is a tree edge
+                        self.parent_edge[w] = vw
+                        self.height[w] = self.height[v] + 1
+
+                        dfs_stack.append(v)  # revisit v after finishing w
+                        dfs_stack.append(w)  # visit w next
+                        skip_init[vw] = True  # don't redo this block
+                        break  # handle next node in dfs_stack (i.e. w)
+                    else:  # (v, w) is a back edge
+                        self.lowpt[vw] = self.height[w]
+
+                # determine nesting graph
+                self.nesting_depth[vw] = 2 * self.lowpt[vw]
+                if self.lowpt2[vw] < self.height[v]:  # chordal
+                    self.nesting_depth[vw] += 1
+
+                # update lowpoints of parent edge e
+                if e is not None:
+                    if self.lowpt[vw] < self.lowpt[e]:
+                        self.lowpt2[e] = min(self.lowpt[e], self.lowpt2[vw])
+                        self.lowpt[e] = self.lowpt[vw]
+                    elif self.lowpt[vw] > self.lowpt[e]:
+                        self.lowpt2[e] = min(self.lowpt2[e], self.lowpt[vw])
+                    else:
+                        self.lowpt2[e] = min(self.lowpt2[e], self.lowpt2[vw])
+
+                ind[v] += 1
+
+    def dfs_orientation_recursive(self, v):
+        """Recursive version of :meth:`dfs_orientation`."""
+        e = self.parent_edge[v]
+        for w in self.G[v]:
+            if (v, w) in self.DG.edges or (w, v) in self.DG.edges:
+                continue  # the edge was already oriented
+            vw = (v, w)
+            self.DG.add_edge(v, w)  # orient the edge
+
+            self.lowpt[vw] = self.height[v]
+            self.lowpt2[vw] = self.height[v]
+            if self.height[w] is None:  # (v, w) is a tree edge
+                self.parent_edge[w] = vw
+                self.height[w] = self.height[v] + 1
+                self.dfs_orientation_recursive(w)
+            else:  # (v, w) is a back edge
+                self.lowpt[vw] = self.height[w]
+
+            # determine nesting graph
+            self.nesting_depth[vw] = 2 * self.lowpt[vw]
+            if self.lowpt2[vw] < self.height[v]:  # chordal
+                self.nesting_depth[vw] += 1
+
+            # update lowpoints of parent edge e
+            if e is not None:
+                if self.lowpt[vw] < self.lowpt[e]:
+                    self.lowpt2[e] = min(self.lowpt[e], self.lowpt2[vw])
+                    self.lowpt[e] = self.lowpt[vw]
+                elif self.lowpt[vw] > self.lowpt[e]:
+                    self.lowpt2[e] = min(self.lowpt2[e], self.lowpt[vw])
+                else:
+                    self.lowpt2[e] = min(self.lowpt2[e], self.lowpt2[vw])
+
+    def dfs_testing(self, v):
+        """Test for LR partition."""
+        # the recursion stack
+        dfs_stack = [v]
+        # index of next edge to handle in adjacency list of each node
+        ind = defaultdict(lambda: 0)
+        # boolean to indicate whether to skip the initial work for an edge
+        skip_init = defaultdict(lambda: False)
+
+        while dfs_stack:
+            v = dfs_stack.pop()
+            e = self.parent_edge[v]
+            # to indicate whether to skip the final block after the for loop
+            skip_final = False
+
+            for w in self.ordered_adjs[v][ind[v] :]:
+                ei = (v, w)
+
+                if not skip_init[ei]:
+                    self.stack_bottom[ei] = top_of_stack(self.S)
+
+                    if ei == self.parent_edge[w]:  # tree edge
+                        dfs_stack.append(v)  # revisit v after finishing w
+                        dfs_stack.append(w)  # visit w next
+                        skip_init[ei] = True  # don't redo this block
+                        skip_final = True  # skip final work after breaking
+                        break  # handle next node in dfs_stack (i.e. w)
+                    else:  # back edge
+                        self.lowpt_edge[ei] = ei
+                        self.S.append(ConflictPair(right=Interval(ei, ei)))
+
+                # integrate new return edges
+                if self.lowpt[ei] < self.height[v]:
+                    if w == self.ordered_adjs[v][0]:  # e_i has return edge
+                        self.lowpt_edge[e] = self.lowpt_edge[ei]
+                    else:  # add constraints of e_i
+                        if not self.add_constraints(ei, e):
+                            # graph is not planar
+                            return False
+
+                ind[v] += 1
+
+            if not skip_final:
+                # remove back edges returning to parent
+                if e is not None:  # v isn't root
+                    self.remove_back_edges(e)
+
+        return True
+
+    def dfs_testing_recursive(self, v):
+        """Recursive version of :meth:`dfs_testing`."""
+        e = self.parent_edge[v]
+        for w in self.ordered_adjs[v]:
+            ei = (v, w)
+            self.stack_bottom[ei] = top_of_stack(self.S)
+            if ei == self.parent_edge[w]:  # tree edge
+                if not self.dfs_testing_recursive(w):
+                    return False
+            else:  # back edge
+                self.lowpt_edge[ei] = ei
+                self.S.append(ConflictPair(right=Interval(ei, ei)))
+
+            # integrate new return edges
+            if self.lowpt[ei] < self.height[v]:
+                if w == self.ordered_adjs[v][0]:  # e_i has return edge
+                    self.lowpt_edge[e] = self.lowpt_edge[ei]
+                else:  # add constraints of e_i
+                    if not self.add_constraints(ei, e):
+                        # graph is not planar
+                        return False
+
+        # remove back edges returning to parent
+        if e is not None:  # v isn't root
+            self.remove_back_edges(e)
+        return True
+
+    def add_constraints(self, ei, e):
+        P = ConflictPair()
+        # merge return edges of e_i into P.right
+        while True:
+            Q = self.S.pop()
+            if not Q.left.empty():
+                Q.swap()
+            if not Q.left.empty():  # not planar
+                return False
+            if self.lowpt[Q.right.low] > self.lowpt[e]:
+                # merge intervals
+                if P.right.empty():  # topmost interval
+                    P.right = Q.right.copy()
+                else:
+                    self.ref[P.right.low] = Q.right.high
+                P.right.low = Q.right.low
+            else:  # align
+                self.ref[Q.right.low] = self.lowpt_edge[e]
+            if top_of_stack(self.S) == self.stack_bottom[ei]:
+                break
+        # merge conflicting return edges of e_1,...,e_i-1 into P.L
+        while top_of_stack(self.S).left.conflicting(ei, self) or top_of_stack(
+            self.S
+        ).right.conflicting(ei, self):
+            Q = self.S.pop()
+            if Q.right.conflicting(ei, self):
+                Q.swap()
+            if Q.right.conflicting(ei, self):  # not planar
+                return False
+            # merge interval below lowpt(e_i) into P.R
+            self.ref[P.right.low] = Q.right.high
+            if Q.right.low is not None:
+                P.right.low = Q.right.low
+
+            if P.left.empty():  # topmost interval
+                P.left = Q.left.copy()
+            else:
+                self.ref[P.left.low] = Q.left.high
+            P.left.low = Q.left.low
+
+        if not (P.left.empty() and P.right.empty()):
+            self.S.append(P)
+        return True
+
+    def remove_back_edges(self, e):
+        u = e[0]
+        # trim back edges ending at parent u
+        # drop entire conflict pairs
+        while self.S and top_of_stack(self.S).lowest(self) == self.height[u]:
+            P = self.S.pop()
+            if P.left.low is not None:
+                self.side[P.left.low] = -1
+
+        if self.S:  # one more conflict pair to consider
+            P = self.S.pop()
+            # trim left interval
+            while P.left.high is not None and P.left.high[1] == u:
+                P.left.high = self.ref[P.left.high]
+            if P.left.high is None and P.left.low is not None:
+                # just emptied
+                self.ref[P.left.low] = P.right.low
+                self.side[P.left.low] = -1
+                P.left.low = None
+            # trim right interval
+            while P.right.high is not None and P.right.high[1] == u:
+                P.right.high = self.ref[P.right.high]
+            if P.right.high is None and P.right.low is not None:
+                # just emptied
+                self.ref[P.right.low] = P.left.low
+                self.side[P.right.low] = -1
+                P.right.low = None
+            self.S.append(P)
+
+        # side of e is side of a highest return edge
+        if self.lowpt[e] < self.height[u]:  # e has return edge
+            hl = top_of_stack(self.S).left.high
+            hr = top_of_stack(self.S).right.high
+
+            if hl is not None and (hr is None or self.lowpt[hl] > self.lowpt[hr]):
+                self.ref[e] = hl
+            else:
+                self.ref[e] = hr
+
+    def dfs_embedding(self, v):
+        """Completes the embedding."""
+        # the recursion stack
+        dfs_stack = [v]
+        # index of next edge to handle in adjacency list of each node
+        ind = defaultdict(lambda: 0)
+
+        while dfs_stack:
+            v = dfs_stack.pop()
+
+            for w in self.ordered_adjs[v][ind[v] :]:
+                ind[v] += 1
+                ei = (v, w)
+
+                if ei == self.parent_edge[w]:  # tree edge
+                    self.embedding.add_half_edge_first(w, v)
+                    self.left_ref[v] = w
+                    self.right_ref[v] = w
+
+                    dfs_stack.append(v)  # revisit v after finishing w
+                    dfs_stack.append(w)  # visit w next
+                    break  # handle next node in dfs_stack (i.e. w)
+                else:  # back edge
+                    if self.side[ei] == 1:
+                        self.embedding.add_half_edge(w, v, ccw=self.right_ref[w])
+                    else:
+                        self.embedding.add_half_edge(w, v, cw=self.left_ref[w])
+                        self.left_ref[w] = v
+
+    def dfs_embedding_recursive(self, v):
+        """Recursive version of :meth:`dfs_embedding`."""
+        for w in self.ordered_adjs[v]:
+            ei = (v, w)
+            if ei == self.parent_edge[w]:  # tree edge
+                self.embedding.add_half_edge_first(w, v)
+                self.left_ref[v] = w
+                self.right_ref[v] = w
+                self.dfs_embedding_recursive(w)
+            else:  # back edge
+                if self.side[ei] == 1:
+                    # place v directly after right_ref[w] in embed. list of w
+                    self.embedding.add_half_edge(w, v, ccw=self.right_ref[w])
+                else:
+                    # place v directly before left_ref[w] in embed. list of w
+                    self.embedding.add_half_edge(w, v, cw=self.left_ref[w])
+                    self.left_ref[w] = v
+
+    def sign(self, e):
+        """Resolve the relative side of an edge to the absolute side."""
+        # the recursion stack
+        dfs_stack = [e]
+        # dict to remember reference edges
+        old_ref = defaultdict(lambda: None)
+
+        while dfs_stack:
+            e = dfs_stack.pop()
+
+            if self.ref[e] is not None:
+                dfs_stack.append(e)  # revisit e after finishing self.ref[e]
+                dfs_stack.append(self.ref[e])  # visit self.ref[e] next
+                old_ref[e] = self.ref[e]  # remember value of self.ref[e]
+                self.ref[e] = None
+            else:
+                self.side[e] *= self.side[old_ref[e]]
+
+        return self.side[e]
+
+    def sign_recursive(self, e):
+        """Recursive version of :meth:`sign`."""
+        if self.ref[e] is not None:
+            self.side[e] = self.side[e] * self.sign_recursive(self.ref[e])
+            self.ref[e] = None
+        return self.side[e]
+
+
+class PlanarEmbedding(nx.DiGraph):
+    """Represents a planar graph with its planar embedding.
+
+    The planar embedding is given by a `combinatorial embedding
+    `_.
+
+    .. note:: `check_planarity` is the preferred way to check if a graph is planar.
+
+    **Neighbor ordering:**
+
+    In comparison to a usual graph structure, the embedding also stores the
+    order of all neighbors for every vertex.
+    The order of the neighbors can be given in clockwise (cw) direction or
+    counterclockwise (ccw) direction. This order is stored as edge attributes
+    in the underlying directed graph. For the edge (u, v) the edge attribute
+    'cw' is set to the neighbor of u that follows immediately after v in
+    clockwise direction.
+
+    In order for a PlanarEmbedding to be valid it must fulfill multiple
+    conditions. It is possible to check if these conditions are fulfilled with
+    the method :meth:`check_structure`.
+    The conditions are:
+
+    * Edges must go in both directions (because the edge attributes differ)
+    * Every edge must have a 'cw' and 'ccw' attribute which corresponds to a
+      correct planar embedding.
+
+    As long as a PlanarEmbedding is invalid only the following methods should
+    be called:
+
+    * :meth:`add_half_edge`
+    * :meth:`connect_components`
+
+    Even though the graph is a subclass of nx.DiGraph, it can still be used
+    for algorithms that require undirected graphs, because the method
+    :meth:`is_directed` is overridden. This is possible, because a valid
+    PlanarGraph must have edges in both directions.
+
+    **Half edges:**
+
+    In methods like `add_half_edge` the term "half-edge" is used, which is
+    a term that is used in `doubly connected edge lists
+    `_. It is used
+    to emphasize that the edge is only in one direction and there exists
+    another half-edge in the opposite direction.
+    While conventional edges always have two faces (including outer face) next
+    to them, it is possible to assign each half-edge *exactly one* face.
+    For a half-edge (u, v) that is oriented such that u is below v then the
+    face that belongs to (u, v) is to the right of this half-edge.
+
+    See Also
+    --------
+    is_planar :
+        Preferred way to check if an existing graph is planar.
+
+    check_planarity :
+        A convenient way to create a `PlanarEmbedding`. If not planar,
+        it returns a subgraph that shows this.
+
+    Examples
+    --------
+
+    Create an embedding of a star graph (compare `nx.star_graph(3)`):
+
+    >>> G = nx.PlanarEmbedding()
+    >>> G.add_half_edge(0, 1)
+    >>> G.add_half_edge(0, 2, ccw=1)
+    >>> G.add_half_edge(0, 3, ccw=2)
+    >>> G.add_half_edge(1, 0)
+    >>> G.add_half_edge(2, 0)
+    >>> G.add_half_edge(3, 0)
+
+    Alternatively the same embedding can also be defined in counterclockwise
+    orientation. The following results in exactly the same PlanarEmbedding:
+
+    >>> G = nx.PlanarEmbedding()
+    >>> G.add_half_edge(0, 1)
+    >>> G.add_half_edge(0, 3, cw=1)
+    >>> G.add_half_edge(0, 2, cw=3)
+    >>> G.add_half_edge(1, 0)
+    >>> G.add_half_edge(2, 0)
+    >>> G.add_half_edge(3, 0)
+
+    After creating a graph, it is possible to validate that the PlanarEmbedding
+    object is correct:
+
+    >>> G.check_structure()
+
+    """
+
+    def __init__(self, incoming_graph_data=None, **attr):
+        super().__init__(incoming_graph_data=incoming_graph_data, **attr)
+        self.add_edge = self._forbidden
+        self.add_edges_from = self._forbidden
+        self.add_weighted_edges_from = self._forbidden
+
+    def _forbidden(self, *args, **kwargs):
+        """Forbidden operation
+
+        Any edge additions to a PlanarEmbedding should be done using
+        method `add_half_edge`.
+        """
+        raise NotImplementedError(
+            "Use `add_half_edge` method to add edges to a PlanarEmbedding."
+        )
+
+    def get_data(self):
+        """Converts the adjacency structure into a better readable structure.
+
+        Returns
+        -------
+        embedding : dict
+            A dict mapping all nodes to a list of neighbors sorted in
+            clockwise order.
+
+        See Also
+        --------
+        set_data
+
+        """
+        embedding = {}
+        for v in self:
+            embedding[v] = list(self.neighbors_cw_order(v))
+        return embedding
+
+    def set_data(self, data):
+        """Inserts edges according to given sorted neighbor list.
+
+        The input format is the same as the output format of get_data().
+
+        Parameters
+        ----------
+        data : dict
+            A dict mapping all nodes to a list of neighbors sorted in
+            clockwise order.
+
+        See Also
+        --------
+        get_data
+
+        """
+        for v in data:
+            ref = None
+            for w in reversed(data[v]):
+                self.add_half_edge(v, w, cw=ref)
+                ref = w
+
+    def remove_node(self, n):
+        """Remove node n.
+
+        Removes the node n and all adjacent edges, updating the
+        PlanarEmbedding to account for any resulting edge removal.
+        Attempting to remove a non-existent node will raise an exception.
+
+        Parameters
+        ----------
+        n : node
+           A node in the graph
+
+        Raises
+        ------
+        NetworkXError
+           If n is not in the graph.
+
+        See Also
+        --------
+        remove_nodes_from
+
+        """
+        try:
+            for u in self._pred[n]:
+                succs_u = self._succ[u]
+                un_cw = succs_u[n]["cw"]
+                un_ccw = succs_u[n]["ccw"]
+                del succs_u[n]
+                del self._pred[u][n]
+                if n != un_cw:
+                    succs_u[un_cw]["ccw"] = un_ccw
+                    succs_u[un_ccw]["cw"] = un_cw
+            del self._node[n]
+            del self._succ[n]
+            del self._pred[n]
+        except KeyError as err:  # NetworkXError if n not in self
+            raise nx.NetworkXError(
+                f"The node {n} is not in the planar embedding."
+            ) from err
+        nx._clear_cache(self)
+
+    def remove_nodes_from(self, nodes):
+        """Remove multiple nodes.
+
+        Parameters
+        ----------
+        nodes : iterable container
+            A container of nodes (list, dict, set, etc.).  If a node
+            in the container is not in the graph it is silently ignored.
+
+        See Also
+        --------
+        remove_node
+
+        Notes
+        -----
+        When removing nodes from an iterator over the graph you are changing,
+        a `RuntimeError` will be raised with message:
+        `RuntimeError: dictionary changed size during iteration`. This
+        happens when the graph's underlying dictionary is modified during
+        iteration. To avoid this error, evaluate the iterator into a separate
+        object, e.g. by using `list(iterator_of_nodes)`, and pass this
+        object to `G.remove_nodes_from`.
+
+        """
+        for n in nodes:
+            if n in self._node:
+                self.remove_node(n)
+            # silently skip non-existing nodes
+
+    def neighbors_cw_order(self, v):
+        """Generator for the neighbors of v in clockwise order.
+
+        Parameters
+        ----------
+        v : node
+
+        Yields
+        ------
+        node
+
+        """
+        succs = self._succ[v]
+        if not succs:
+            # v has no neighbors
+            return
+        start_node = next(reversed(succs))
+        yield start_node
+        current_node = succs[start_node]["cw"]
+        while start_node != current_node:
+            yield current_node
+            current_node = succs[current_node]["cw"]
+
+    def add_half_edge(self, start_node, end_node, *, cw=None, ccw=None):
+        """Adds a half-edge from `start_node` to `end_node`.
+
+        If the half-edge is not the first one out of `start_node`, a reference
+        node must be provided either in the clockwise (parameter `cw`) or in
+        the counterclockwise (parameter `ccw`) direction. Only one of `cw`/`ccw`
+        can be specified (or neither in the case of the first edge).
+        Note that specifying a reference in the clockwise (`cw`) direction means
+        inserting the new edge in the first counterclockwise position with
+        respect to the reference (and vice-versa).
+
+        Parameters
+        ----------
+        start_node : node
+            Start node of inserted edge.
+        end_node : node
+            End node of inserted edge.
+        cw, ccw: node
+            End node of reference edge.
+            Omit or pass `None` if adding the first out-half-edge of `start_node`.
+
+
+        Raises
+        ------
+        NetworkXException
+            If the `cw` or `ccw` node is not a successor of `start_node`.
+            If `start_node` has successors, but neither `cw` or `ccw` is provided.
+            If both `cw` and `ccw` are specified.
+
+        See Also
+        --------
+        connect_components
+        """
+
+        succs = self._succ.get(start_node)
+        if succs:
+            # there is already some edge out of start_node
+            leftmost_nbr = next(reversed(self._succ[start_node]))
+            if cw is not None:
+                if cw not in succs:
+                    raise nx.NetworkXError("Invalid clockwise reference node.")
+                if ccw is not None:
+                    raise nx.NetworkXError("Only one of cw/ccw can be specified.")
+                ref_ccw = succs[cw]["ccw"]
+                super().add_edge(start_node, end_node, cw=cw, ccw=ref_ccw)
+                succs[ref_ccw]["cw"] = end_node
+                succs[cw]["ccw"] = end_node
+                # when (cw == leftmost_nbr), the newly added neighbor is
+                # already at the end of dict self._succ[start_node] and
+                # takes the place of the former leftmost_nbr
+                move_leftmost_nbr_to_end = cw != leftmost_nbr
+            elif ccw is not None:
+                if ccw not in succs:
+                    raise nx.NetworkXError("Invalid counterclockwise reference node.")
+                ref_cw = succs[ccw]["cw"]
+                super().add_edge(start_node, end_node, cw=ref_cw, ccw=ccw)
+                succs[ref_cw]["ccw"] = end_node
+                succs[ccw]["cw"] = end_node
+                move_leftmost_nbr_to_end = True
+            else:
+                raise nx.NetworkXError(
+                    "Node already has out-half-edge(s), either cw or ccw reference node required."
+                )
+            if move_leftmost_nbr_to_end:
+                # LRPlanarity (via self.add_half_edge_first()) requires that
+                # we keep track of the leftmost neighbor, which we accomplish
+                # by keeping it as the last key in dict self._succ[start_node]
+                succs[leftmost_nbr] = succs.pop(leftmost_nbr)
+
+        else:
+            if cw is not None or ccw is not None:
+                raise nx.NetworkXError("Invalid reference node.")
+            # adding the first edge out of start_node
+            super().add_edge(start_node, end_node, ccw=end_node, cw=end_node)
+
+    def check_structure(self):
+        """Runs without exceptions if this object is valid.
+
+        Checks that the following properties are fulfilled:
+
+        * Edges go in both directions (because the edge attributes differ).
+        * Every edge has a 'cw' and 'ccw' attribute which corresponds to a
+          correct planar embedding.
+
+        Running this method verifies that the underlying Graph must be planar.
+
+        Raises
+        ------
+        NetworkXException
+            This exception is raised with a short explanation if the
+            PlanarEmbedding is invalid.
+        """
+        # Check fundamental structure
+        for v in self:
+            try:
+                sorted_nbrs = set(self.neighbors_cw_order(v))
+            except KeyError as err:
+                msg = f"Bad embedding. Missing orientation for a neighbor of {v}"
+                raise nx.NetworkXException(msg) from err
+
+            unsorted_nbrs = set(self[v])
+            if sorted_nbrs != unsorted_nbrs:
+                msg = "Bad embedding. Edge orientations not set correctly."
+                raise nx.NetworkXException(msg)
+            for w in self[v]:
+                # Check if opposite half-edge exists
+                if not self.has_edge(w, v):
+                    msg = "Bad embedding. Opposite half-edge is missing."
+                    raise nx.NetworkXException(msg)
+
+        # Check planarity
+        counted_half_edges = set()
+        for component in nx.connected_components(self):
+            if len(component) == 1:
+                # Don't need to check single node component
+                continue
+            num_nodes = len(component)
+            num_half_edges = 0
+            num_faces = 0
+            for v in component:
+                for w in self.neighbors_cw_order(v):
+                    num_half_edges += 1
+                    if (v, w) not in counted_half_edges:
+                        # We encountered a new face
+                        num_faces += 1
+                        # Mark all half-edges belonging to this face
+                        self.traverse_face(v, w, counted_half_edges)
+            num_edges = num_half_edges // 2  # num_half_edges is even
+            if num_nodes - num_edges + num_faces != 2:
+                # The result does not match Euler's formula
+                msg = "Bad embedding. The graph does not match Euler's formula"
+                raise nx.NetworkXException(msg)
+
+    def add_half_edge_ccw(self, start_node, end_node, reference_neighbor):
+        """Adds a half-edge from start_node to end_node.
+
+        The half-edge is added counter clockwise next to the existing half-edge
+        (start_node, reference_neighbor).
+
+        Parameters
+        ----------
+        start_node : node
+            Start node of inserted edge.
+        end_node : node
+            End node of inserted edge.
+        reference_neighbor: node
+            End node of reference edge.
+
+        Raises
+        ------
+        NetworkXException
+            If the reference_neighbor does not exist.
+
+        See Also
+        --------
+        add_half_edge
+        add_half_edge_cw
+        connect_components
+
+        """
+        self.add_half_edge(start_node, end_node, cw=reference_neighbor)
+
+    def add_half_edge_cw(self, start_node, end_node, reference_neighbor):
+        """Adds a half-edge from start_node to end_node.
+
+        The half-edge is added clockwise next to the existing half-edge
+        (start_node, reference_neighbor).
+
+        Parameters
+        ----------
+        start_node : node
+            Start node of inserted edge.
+        end_node : node
+            End node of inserted edge.
+        reference_neighbor: node
+            End node of reference edge.
+
+        Raises
+        ------
+        NetworkXException
+            If the reference_neighbor does not exist.
+
+        See Also
+        --------
+        add_half_edge
+        add_half_edge_ccw
+        connect_components
+        """
+        self.add_half_edge(start_node, end_node, ccw=reference_neighbor)
+
+    def remove_edge(self, u, v):
+        """Remove the edge between u and v.
+
+        Parameters
+        ----------
+        u, v : nodes
+        Remove the half-edges (u, v) and (v, u) and update the
+        edge ordering around the removed edge.
+
+        Raises
+        ------
+        NetworkXError
+        If there is not an edge between u and v.
+
+        See Also
+        --------
+        remove_edges_from : remove a collection of edges
+        """
+        try:
+            succs_u = self._succ[u]
+            succs_v = self._succ[v]
+            uv_cw = succs_u[v]["cw"]
+            uv_ccw = succs_u[v]["ccw"]
+            vu_cw = succs_v[u]["cw"]
+            vu_ccw = succs_v[u]["ccw"]
+            del succs_u[v]
+            del self._pred[v][u]
+            del succs_v[u]
+            del self._pred[u][v]
+            if v != uv_cw:
+                succs_u[uv_cw]["ccw"] = uv_ccw
+                succs_u[uv_ccw]["cw"] = uv_cw
+            if u != vu_cw:
+                succs_v[vu_cw]["ccw"] = vu_ccw
+                succs_v[vu_ccw]["cw"] = vu_cw
+        except KeyError as err:
+            raise nx.NetworkXError(
+                f"The edge {u}-{v} is not in the planar embedding."
+            ) from err
+        nx._clear_cache(self)
+
+    def remove_edges_from(self, ebunch):
+        """Remove all edges specified in ebunch.
+
+        Parameters
+        ----------
+        ebunch: list or container of edge tuples
+            Each pair of half-edges between the nodes given in the tuples
+            will be removed from the graph. The nodes can be passed as:
+
+                - 2-tuples (u, v) half-edges (u, v) and (v, u).
+                - 3-tuples (u, v, k) where k is ignored.
+
+        See Also
+        --------
+        remove_edge : remove a single edge
+
+        Notes
+        -----
+        Will fail silently if an edge in ebunch is not in the graph.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> ebunch = [(1, 2), (2, 3)]
+        >>> G.remove_edges_from(ebunch)
+        """
+        for e in ebunch:
+            u, v = e[:2]  # ignore edge data
+            # assuming that the PlanarEmbedding is valid, if the half_edge
+            # (u, v) is in the graph, then so is half_edge (v, u)
+            if u in self._succ and v in self._succ[u]:
+                self.remove_edge(u, v)
+
+    def connect_components(self, v, w):
+        """Adds half-edges for (v, w) and (w, v) at some position.
+
+        This method should only be called if v and w are in different
+        components, or it might break the embedding.
+        This especially means that if `connect_components(v, w)`
+        is called it is not allowed to call `connect_components(w, v)`
+        afterwards. The neighbor orientations in both directions are
+        all set correctly after the first call.
+
+        Parameters
+        ----------
+        v : node
+        w : node
+
+        See Also
+        --------
+        add_half_edge
+        """
+        if v in self._succ and self._succ[v]:
+            ref = next(reversed(self._succ[v]))
+        else:
+            ref = None
+        self.add_half_edge(v, w, cw=ref)
+        if w in self._succ and self._succ[w]:
+            ref = next(reversed(self._succ[w]))
+        else:
+            ref = None
+        self.add_half_edge(w, v, cw=ref)
+
+    def add_half_edge_first(self, start_node, end_node):
+        """Add a half-edge and set end_node as start_node's leftmost neighbor.
+
+        The new edge is inserted counterclockwise with respect to the current
+        leftmost neighbor, if there is one.
+
+        Parameters
+        ----------
+        start_node : node
+        end_node : node
+
+        See Also
+        --------
+        add_half_edge
+        connect_components
+        """
+        succs = self._succ.get(start_node)
+        # the leftmost neighbor is the last entry in the
+        # self._succ[start_node] dict
+        leftmost_nbr = next(reversed(succs)) if succs else None
+        self.add_half_edge(start_node, end_node, cw=leftmost_nbr)
+
+    def next_face_half_edge(self, v, w):
+        """Returns the following half-edge left of a face.
+
+        Parameters
+        ----------
+        v : node
+        w : node
+
+        Returns
+        -------
+        half-edge : tuple
+        """
+        new_node = self[w][v]["ccw"]
+        return w, new_node
+
+    def traverse_face(self, v, w, mark_half_edges=None):
+        """Returns nodes on the face that belong to the half-edge (v, w).
+
+        The face that is traversed lies to the right of the half-edge (in an
+        orientation where v is below w).
+
+        Optionally it is possible to pass a set to which all encountered half
+        edges are added. Before calling this method, this set must not include
+        any half-edges that belong to the face.
+
+        Parameters
+        ----------
+        v : node
+            Start node of half-edge.
+        w : node
+            End node of half-edge.
+        mark_half_edges: set, optional
+            Set to which all encountered half-edges are added.
+
+        Returns
+        -------
+        face : list
+            A list of nodes that lie on this face.
+        """
+        if mark_half_edges is None:
+            mark_half_edges = set()
+
+        face_nodes = [v]
+        mark_half_edges.add((v, w))
+        prev_node = v
+        cur_node = w
+        # Last half-edge is (incoming_node, v)
+        incoming_node = self[v][w]["cw"]
+
+        while cur_node != v or prev_node != incoming_node:
+            face_nodes.append(cur_node)
+            prev_node, cur_node = self.next_face_half_edge(prev_node, cur_node)
+            if (prev_node, cur_node) in mark_half_edges:
+                raise nx.NetworkXException("Bad planar embedding. Impossible face.")
+            mark_half_edges.add((prev_node, cur_node))
+
+        return face_nodes
+
+    def is_directed(self):
+        """A valid PlanarEmbedding is undirected.
+
+        All reverse edges are contained, i.e. for every existing
+        half-edge (v, w) the half-edge in the opposite direction (w, v) is also
+        contained.
+        """
+        return False
+
+    def copy(self, as_view=False):
+        if as_view is True:
+            return nx.graphviews.generic_graph_view(self)
+        G = self.__class__()
+        G.graph.update(self.graph)
+        G.add_nodes_from((n, d.copy()) for n, d in self._node.items())
+        super(self.__class__, G).add_edges_from(
+            (u, v, datadict.copy())
+            for u, nbrs in self._adj.items()
+            for v, datadict in nbrs.items()
+        )
+        return G
+
+    def to_undirected(self, reciprocal=False, as_view=False):
+        """
+        Returns a non-embedding undirected representation of the graph.
+
+        This method strips the planar embedding information and provides
+        a simple undirected graph representation. While creating the undirected graph,
+        all edge attributes are retained except the ``"cw"`` and ``"ccw"`` attributes
+        which are removed from the edge data. Those attributes are specific to
+        the requirements of planar embeddings.
+
+        Parameters
+        ----------
+        reciprocal : bool (optional)
+            Not supported for PlanarEmbedding. This parameter raises an exception
+            if used. All valid embeddings include reciprocal half-edges by definition,
+            making this parameter unnecessary.
+        as_view : bool (optional, default=False)
+            Not supported for PlanarEmbedding. This parameter raises an exception
+            if used.
+
+        Returns
+        -------
+        G : Graph
+            An undirected graph with the same name and nodes as the PlanarEmbedding.
+            Edges are included with their data, except for the ``"cw"`` and ``"ccw"``
+            attributes, which are omitted.
+
+
+        Notes
+        -----
+        - If edges exist in both directions ``(u, v)`` and ``(v, u)`` in the PlanarEmbedding,
+          attributes for the resulting undirected edge will be combined, excluding ``"cw"``
+          and ``"ccw"``.
+        - A deep copy is made of the other edge attributes as well as the
+          node and graph attributes, ensuring independence of the resulting graph.
+        - Subclass-specific data structures used in the original graph may not transfer
+          to the undirected graph. The resulting graph will be of type ``nx.Graph``.
+        """
+
+        if reciprocal:
+            raise ValueError(
+                "'reciprocal=True' is not supported for PlanarEmbedding.\n"
+                "All valid embeddings include reciprocal half-edges by definition,\n"
+                "making this parameter unnecessary."
+            )
+
+        if as_view:
+            raise ValueError("'as_view=True' is not supported for PlanarEmbedding.")
+
+        graph_class = self.to_undirected_class()
+        G = graph_class()
+        G.graph.update(deepcopy(self.graph))
+        G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
+        G.add_edges_from(
+            (u, v, {k: deepcopy(v) for k, v in d.items() if k not in {"cw", "ccw"}})
+            for u, nbrs in self._adj.items()
+            for v, d in nbrs.items()
+        )
+        return G
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/polynomials.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/polynomials.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ebc7554a7654c8961c9d8a8024d17210ccf44ca
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/polynomials.py
@@ -0,0 +1,306 @@
+"""Provides algorithms supporting the computation of graph polynomials.
+
+Graph polynomials are polynomial-valued graph invariants that encode a wide
+variety of structural information. Examples include the Tutte polynomial,
+chromatic polynomial, characteristic polynomial, and matching polynomial. An
+extensive treatment is provided in [1]_.
+
+For a simple example, the `~sympy.matrices.matrices.MatrixDeterminant.charpoly`
+method can be used to compute the characteristic polynomial from the adjacency
+matrix of a graph. Consider the complete graph ``K_4``:
+
+>>> import sympy
+>>> x = sympy.Symbol("x")
+>>> G = nx.complete_graph(4)
+>>> A = nx.to_numpy_array(G, dtype=int)
+>>> M = sympy.SparseMatrix(A)
+>>> M.charpoly(x).as_expr()
+x**4 - 6*x**2 - 8*x - 3
+
+
+.. [1] Y. Shi, M. Dehmer, X. Li, I. Gutman,
+   "Graph Polynomials"
+"""
+
+from collections import deque
+
+import networkx as nx
+from networkx.utils import not_implemented_for
+
+__all__ = ["tutte_polynomial", "chromatic_polynomial"]
+
+
+@not_implemented_for("directed")
+@nx._dispatchable
+def tutte_polynomial(G):
+    r"""Returns the Tutte polynomial of `G`
+
+    This function computes the Tutte polynomial via an iterative version of
+    the deletion-contraction algorithm.
+
+    The Tutte polynomial `T_G(x, y)` is a fundamental graph polynomial invariant in
+    two variables. It encodes a wide array of information related to the
+    edge-connectivity of a graph; "Many problems about graphs can be reduced to
+    problems of finding and evaluating the Tutte polynomial at certain values" [1]_.
+    In fact, every deletion-contraction-expressible feature of a graph is a
+    specialization of the Tutte polynomial [2]_ (see Notes for examples).
+
+    There are several equivalent definitions; here are three:
+
+    Def 1 (rank-nullity expansion): For `G` an undirected graph, `n(G)` the
+    number of vertices of `G`, `E` the edge set of `G`, `V` the vertex set of
+    `G`, and `c(A)` the number of connected components of the graph with vertex
+    set `V` and edge set `A` [3]_:
+
+    .. math::
+
+        T_G(x, y) = \sum_{A \in E} (x-1)^{c(A) - c(E)} (y-1)^{c(A) + |A| - n(G)}
+
+    Def 2 (spanning tree expansion): Let `G` be an undirected graph, `T` a spanning
+    tree of `G`, and `E` the edge set of `G`. Let `E` have an arbitrary strict
+    linear order `L`. Let `B_e` be the unique minimal nonempty edge cut of
+    $E \setminus T \cup {e}$. An edge `e` is internally active with respect to
+    `T` and `L` if `e` is the least edge in `B_e` according to the linear order
+    `L`. The internal activity of `T` (denoted `i(T)`) is the number of edges
+    in $E \setminus T$ that are internally active with respect to `T` and `L`.
+    Let `P_e` be the unique path in $T \cup {e}$ whose source and target vertex
+    are the same. An edge `e` is externally active with respect to `T` and `L`
+    if `e` is the least edge in `P_e` according to the linear order `L`. The
+    external activity of `T` (denoted `e(T)`) is the number of edges in
+    $E \setminus T$ that are externally active with respect to `T` and `L`.
+    Then [4]_ [5]_:
+
+    .. math::
+
+        T_G(x, y) = \sum_{T \text{ a spanning tree of } G} x^{i(T)} y^{e(T)}
+
+    Def 3 (deletion-contraction recurrence): For `G` an undirected graph, `G-e`
+    the graph obtained from `G` by deleting edge `e`, `G/e` the graph obtained
+    from `G` by contracting edge `e`, `k(G)` the number of cut-edges of `G`,
+    and `l(G)` the number of self-loops of `G`:
+
+    .. math::
+        T_G(x, y) = \begin{cases}
+    	   x^{k(G)} y^{l(G)}, & \text{if all edges are cut-edges or self-loops} \\
+           T_{G-e}(x, y) + T_{G/e}(x, y), & \text{otherwise, for an arbitrary edge $e$ not a cut-edge or loop}
+        \end{cases}
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    Returns
+    -------
+    instance of `sympy.core.add.Add`
+        A Sympy expression representing the Tutte polynomial for `G`.
+
+    Examples
+    --------
+    >>> C = nx.cycle_graph(5)
+    >>> nx.tutte_polynomial(C)
+    x**4 + x**3 + x**2 + x + y
+
+    >>> D = nx.diamond_graph()
+    >>> nx.tutte_polynomial(D)
+    x**3 + 2*x**2 + 2*x*y + x + y**2 + y
+
+    Notes
+    -----
+    Some specializations of the Tutte polynomial:
+
+    - `T_G(1, 1)` counts the number of spanning trees of `G`
+    - `T_G(1, 2)` counts the number of connected spanning subgraphs of `G`
+    - `T_G(2, 1)` counts the number of spanning forests in `G`
+    - `T_G(0, 2)` counts the number of strong orientations of `G`
+    - `T_G(2, 0)` counts the number of acyclic orientations of `G`
+
+    Edge contraction is defined and deletion-contraction is introduced in [6]_.
+    Combinatorial meaning of the coefficients is introduced in [7]_.
+    Universality, properties, and applications are discussed in [8]_.
+
+    Practically, up-front computation of the Tutte polynomial may be useful when
+    users wish to repeatedly calculate edge-connectivity-related information
+    about one or more graphs.
+
+    References
+    ----------
+    .. [1] M. Brandt,
+       "The Tutte Polynomial."
+       Talking About Combinatorial Objects Seminar, 2015
+       https://math.berkeley.edu/~brandtm/talks/tutte.pdf
+    .. [2] A. Björklund, T. Husfeldt, P. Kaski, M. Koivisto,
+       "Computing the Tutte polynomial in vertex-exponential time"
+       49th Annual IEEE Symposium on Foundations of Computer Science, 2008
+       https://ieeexplore.ieee.org/abstract/document/4691000
+    .. [3] Y. Shi, M. Dehmer, X. Li, I. Gutman,
+       "Graph Polynomials," p. 14
+    .. [4] Y. Shi, M. Dehmer, X. Li, I. Gutman,
+       "Graph Polynomials," p. 46
+    .. [5] A. Nešetril, J. Goodall,
+       "Graph invariants, homomorphisms, and the Tutte polynomial"
+       https://iuuk.mff.cuni.cz/~andrew/Tutte.pdf
+    .. [6] D. B. West,
+       "Introduction to Graph Theory," p. 84
+    .. [7] G. Coutinho,
+       "A brief introduction to the Tutte polynomial"
+       Structural Analysis of Complex Networks, 2011
+       https://homepages.dcc.ufmg.br/~gabriel/seminars/coutinho_tuttepolynomial_seminar.pdf
+    .. [8] J. A. Ellis-Monaghan, C. Merino,
+       "Graph polynomials and their applications I: The Tutte polynomial"
+       Structural Analysis of Complex Networks, 2011
+       https://arxiv.org/pdf/0803.3079.pdf
+    """
+    import sympy
+
+    x = sympy.Symbol("x")
+    y = sympy.Symbol("y")
+    stack = deque()
+    stack.append(nx.MultiGraph(G))
+
+    polynomial = 0
+    while stack:
+        G = stack.pop()
+        bridges = set(nx.bridges(G))
+
+        e = None
+        for i in G.edges:
+            if (i[0], i[1]) not in bridges and i[0] != i[1]:
+                e = i
+                break
+        if not e:
+            loops = list(nx.selfloop_edges(G, keys=True))
+            polynomial += x ** len(bridges) * y ** len(loops)
+        else:
+            # deletion-contraction
+            C = nx.contracted_edge(G, e, self_loops=True)
+            C.remove_edge(e[0], e[0])
+            G.remove_edge(*e)
+            stack.append(G)
+            stack.append(C)
+    return sympy.simplify(polynomial)
+
+
+@not_implemented_for("directed")
+@nx._dispatchable
+def chromatic_polynomial(G):
+    r"""Returns the chromatic polynomial of `G`
+
+    This function computes the chromatic polynomial via an iterative version of
+    the deletion-contraction algorithm.
+
+    The chromatic polynomial `X_G(x)` is a fundamental graph polynomial
+    invariant in one variable. Evaluating `X_G(k)` for an natural number `k`
+    enumerates the proper k-colorings of `G`.
+
+    There are several equivalent definitions; here are three:
+
+    Def 1 (explicit formula):
+    For `G` an undirected graph, `c(G)` the number of connected components of
+    `G`, `E` the edge set of `G`, and `G(S)` the spanning subgraph of `G` with
+    edge set `S` [1]_:
+
+    .. math::
+
+        X_G(x) = \sum_{S \subseteq E} (-1)^{|S|} x^{c(G(S))}
+
+
+    Def 2 (interpolating polynomial):
+    For `G` an undirected graph, `n(G)` the number of vertices of `G`, `k_0 = 0`,
+    and `k_i` the number of distinct ways to color the vertices of `G` with `i`
+    unique colors (for `i` a natural number at most `n(G)`), `X_G(x)` is the
+    unique Lagrange interpolating polynomial of degree `n(G)` through the points
+    `(0, k_0), (1, k_1), \dots, (n(G), k_{n(G)})` [2]_.
+
+
+    Def 3 (chromatic recurrence):
+    For `G` an undirected graph, `G-e` the graph obtained from `G` by deleting
+    edge `e`, `G/e` the graph obtained from `G` by contracting edge `e`, `n(G)`
+    the number of vertices of `G`, and `e(G)` the number of edges of `G` [3]_:
+
+    .. math::
+        X_G(x) = \begin{cases}
+    	   x^{n(G)}, & \text{if $e(G)=0$} \\
+           X_{G-e}(x) - X_{G/e}(x), & \text{otherwise, for an arbitrary edge $e$}
+        \end{cases}
+
+    This formulation is also known as the Fundamental Reduction Theorem [4]_.
+
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    Returns
+    -------
+    instance of `sympy.core.add.Add`
+        A Sympy expression representing the chromatic polynomial for `G`.
+
+    Examples
+    --------
+    >>> C = nx.cycle_graph(5)
+    >>> nx.chromatic_polynomial(C)
+    x**5 - 5*x**4 + 10*x**3 - 10*x**2 + 4*x
+
+    >>> G = nx.complete_graph(4)
+    >>> nx.chromatic_polynomial(G)
+    x**4 - 6*x**3 + 11*x**2 - 6*x
+
+    Notes
+    -----
+    Interpretation of the coefficients is discussed in [5]_. Several special
+    cases are listed in [2]_.
+
+    The chromatic polynomial is a specialization of the Tutte polynomial; in
+    particular, ``X_G(x) = T_G(x, 0)`` [6]_.
+
+    The chromatic polynomial may take negative arguments, though evaluations
+    may not have chromatic interpretations. For instance, ``X_G(-1)`` enumerates
+    the acyclic orientations of `G` [7]_.
+
+    References
+    ----------
+    .. [1] D. B. West,
+       "Introduction to Graph Theory," p. 222
+    .. [2] E. W. Weisstein
+       "Chromatic Polynomial"
+       MathWorld--A Wolfram Web Resource
+       https://mathworld.wolfram.com/ChromaticPolynomial.html
+    .. [3] D. B. West,
+       "Introduction to Graph Theory," p. 221
+    .. [4] J. Zhang, J. Goodall,
+       "An Introduction to Chromatic Polynomials"
+       https://math.mit.edu/~apost/courses/18.204_2018/Julie_Zhang_paper.pdf
+    .. [5] R. C. Read,
+       "An Introduction to Chromatic Polynomials"
+       Journal of Combinatorial Theory, 1968
+       https://math.berkeley.edu/~mrklug/ReadChromatic.pdf
+    .. [6] W. T. Tutte,
+       "Graph-polynomials"
+       Advances in Applied Mathematics, 2004
+       https://www.sciencedirect.com/science/article/pii/S0196885803000411
+    .. [7] R. P. Stanley,
+       "Acyclic orientations of graphs"
+       Discrete Mathematics, 2006
+       https://math.mit.edu/~rstan/pubs/pubfiles/18.pdf
+    """
+    import sympy
+
+    x = sympy.Symbol("x")
+    stack = deque()
+    stack.append(nx.MultiGraph(G, contraction_idx=0))
+
+    polynomial = 0
+    while stack:
+        G = stack.pop()
+        edges = list(G.edges)
+        if not edges:
+            polynomial += (-1) ** G.graph["contraction_idx"] * x ** len(G)
+        else:
+            e = edges[0]
+            C = nx.contracted_edge(G, e, self_loops=True)
+            C.graph["contraction_idx"] = G.graph["contraction_idx"] + 1
+            C.remove_edge(e[0], e[0])
+            G.remove_edge(*e)
+            stack.append(G)
+            stack.append(C)
+    return polynomial
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/reciprocity.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/reciprocity.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ea7ed2ce26ab973e07bcc6ec0d92aa4799d9a6a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/reciprocity.py
@@ -0,0 +1,98 @@
+"""Algorithms to calculate reciprocity in a directed graph."""
+
+import networkx as nx
+from networkx import NetworkXError
+
+from ..utils import not_implemented_for
+
+__all__ = ["reciprocity", "overall_reciprocity"]
+
+
+@not_implemented_for("undirected", "multigraph")
+@nx._dispatchable
+def reciprocity(G, nodes=None):
+    r"""Compute the reciprocity in a directed graph.
+
+    The reciprocity of a directed graph is defined as the ratio
+    of the number of edges pointing in both directions to the total
+    number of edges in the graph.
+    Formally, $r = |{(u,v) \in G|(v,u) \in G}| / |{(u,v) \in G}|$.
+
+    The reciprocity of a single node u is defined similarly,
+    it is the ratio of the number of edges in both directions to
+    the total number of edges attached to node u.
+
+    Parameters
+    ----------
+    G : graph
+       A networkx directed graph
+    nodes : container of nodes, optional (default=whole graph)
+       Compute reciprocity for nodes in this container.
+
+    Returns
+    -------
+    out : dictionary
+       Reciprocity keyed by node label.
+
+    Notes
+    -----
+    The reciprocity is not defined for isolated nodes.
+    In such cases this function will return None.
+
+    """
+    # If `nodes` is not specified, calculate the reciprocity of the graph.
+    if nodes is None:
+        return overall_reciprocity(G)
+
+    # If `nodes` represents a single node in the graph, return only its
+    # reciprocity.
+    if nodes in G:
+        reciprocity = next(_reciprocity_iter(G, nodes))[1]
+        if reciprocity is None:
+            raise NetworkXError("Not defined for isolated nodes.")
+        else:
+            return reciprocity
+
+    # Otherwise, `nodes` represents an iterable of nodes, so return a
+    # dictionary mapping node to its reciprocity.
+    return dict(_reciprocity_iter(G, nodes))
+
+
+def _reciprocity_iter(G, nodes):
+    """Return an iterator of (node, reciprocity)."""
+    n = G.nbunch_iter(nodes)
+    for node in n:
+        pred = set(G.predecessors(node))
+        succ = set(G.successors(node))
+        overlap = pred & succ
+        n_total = len(pred) + len(succ)
+
+        # Reciprocity is not defined for isolated nodes.
+        # Return None.
+        if n_total == 0:
+            yield (node, None)
+        else:
+            reciprocity = 2 * len(overlap) / n_total
+            yield (node, reciprocity)
+
+
+@not_implemented_for("undirected", "multigraph")
+@nx._dispatchable
+def overall_reciprocity(G):
+    """Compute the reciprocity for the whole graph.
+
+    See the doc of reciprocity for the definition.
+
+    Parameters
+    ----------
+    G : graph
+       A networkx graph
+
+    """
+    n_all_edge = G.number_of_edges()
+    n_overlap_edge = (n_all_edge - G.to_undirected().number_of_edges()) * 2
+
+    if n_all_edge == 0:
+        raise NetworkXError("Not defined for empty graphs")
+
+    return n_overlap_edge / n_all_edge
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/regular.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/regular.py
new file mode 100644
index 0000000000000000000000000000000000000000..a0032e2d4fb94df69110b99c38ba4c688565399d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/regular.py
@@ -0,0 +1,167 @@
+"""Functions for computing and verifying regular graphs."""
+
+import networkx as nx
+from networkx.utils import not_implemented_for
+
+__all__ = ["is_regular", "is_k_regular", "k_factor"]
+
+
+@nx._dispatchable
+def is_regular(G):
+    """Determines whether a graph is regular.
+
+    A regular graph is a graph where all nodes have the same degree. A regular
+    digraph is a graph where all nodes have the same indegree and all nodes
+    have the same outdegree.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    Returns
+    -------
+    bool
+        Whether the given graph or digraph is regular.
+
+    Examples
+    --------
+    >>> G = nx.DiGraph([(1, 2), (2, 3), (3, 4), (4, 1)])
+    >>> nx.is_regular(G)
+    True
+
+    """
+    if len(G) == 0:
+        raise nx.NetworkXPointlessConcept("Graph has no nodes.")
+    n1 = nx.utils.arbitrary_element(G)
+    if not G.is_directed():
+        d1 = G.degree(n1)
+        return all(d1 == d for _, d in G.degree)
+    else:
+        d_in = G.in_degree(n1)
+        in_regular = (d_in == d for _, d in G.in_degree)
+        d_out = G.out_degree(n1)
+        out_regular = (d_out == d for _, d in G.out_degree)
+        return all(in_regular) and all(out_regular)
+
+
+@not_implemented_for("directed")
+@nx._dispatchable
+def is_k_regular(G, k):
+    """Determines whether the graph ``G`` is a k-regular graph.
+
+    A k-regular graph is a graph where each vertex has degree k.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    Returns
+    -------
+    bool
+        Whether the given graph is k-regular.
+
+    Examples
+    --------
+    >>> G = nx.Graph([(1, 2), (2, 3), (3, 4), (4, 1)])
+    >>> nx.is_k_regular(G, k=3)
+    False
+
+    """
+    return all(d == k for n, d in G.degree)
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable(preserve_edge_attrs=True, returns_graph=True)
+def k_factor(G, k, matching_weight="weight"):
+    """Compute a `k`-factor of a graph.
+
+    A `k`-factor of a graph is a spanning `k`-regular subgraph.
+    A spanning `k`-regular subgraph of `G` is a subgraph that contains
+    each node of `G` and a subset of the edges of `G` such that each
+    node has degree `k`.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        An undirected graph.
+
+    k : int
+        The degree of the `k`-factor.
+
+    matching_weight: string, optional (default="weight")
+        Edge attribute name corresponding to the edge weight.
+        If not present, the edge is assumed to have weight 1.
+        Used for finding the max-weighted perfect matching.
+
+    Returns
+    -------
+    NetworkX graph
+        A `k`-factor of `G`.
+
+    Examples
+    --------
+    >>> G = nx.Graph([(1, 2), (2, 3), (3, 4), (4, 1)])
+    >>> KF = nx.k_factor(G, k=1)
+    >>> KF.edges()
+    EdgeView([(1, 2), (3, 4)])
+
+    References
+    ----------
+    .. [1] "An algorithm for computing simple k-factors.",
+       Meijer, Henk, Yurai Núñez-Rodríguez, and David Rappaport,
+       Information processing letters, 2009.
+    """
+    # Validate minimum degree requirement.
+    if any(d < k for _, d in G.degree):
+        raise nx.NetworkXUnfeasible("Graph contains a vertex with degree less than k")
+
+    g = G.copy()
+    gadgets = []
+
+    # Replace each node with a gadget.
+    for node, degree in G.degree:
+        is_large = k >= degree / 2.0
+
+        # Create gadget nodes.
+        outer = [(node, i) for i in range(degree)]
+        if is_large:
+            core = [(node, i) for i in range(degree, 2 * degree - k)]
+            inner = []
+        else:
+            core = [(node, i) for i in range(2 * degree, 2 * degree + k)]
+            inner = [(node, i) for i in range(degree, 2 * degree)]
+
+        # Connect gadget nodes to neighbors.
+        g.add_edges_from(zip(outer, inner))
+        for outer_n, (neighbor, attrs) in zip(outer, g[node].items()):
+            g.add_edge(outer_n, neighbor, **attrs)
+
+        # Add internal edges.
+        g.add_edges_from((u, v) for u in core for v in (outer if is_large else inner))
+
+        g.remove_node(node)
+        gadgets.append((node, outer, core, inner))
+
+    # Find perfect matching.
+    m = nx.max_weight_matching(g, maxcardinality=True, weight=matching_weight)
+    if not nx.is_perfect_matching(g, m):
+        raise nx.NetworkXUnfeasible(
+            "Cannot find k-factor because no perfect matching exists"
+        )
+
+    # Keep only edges in matching.
+    g.remove_edges_from(e for e in g.edges if e not in m and e[::-1] not in m)
+
+    # Restore original nodes and remove gadgets.
+    for node, outer, core, inner in gadgets:
+        g.add_node(node)
+        core_set = set(core)
+        for outer_n in outer:
+            for neighbor, attrs in g._adj[outer_n].items():
+                if neighbor not in core_set:
+                    g.add_edge(node, neighbor, **attrs)
+                    break
+        g.remove_nodes_from(outer + core + inner)
+
+    return g
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/richclub.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/richclub.py
new file mode 100644
index 0000000000000000000000000000000000000000..445b27d142547e5cad04e00abc9ca33d45edbee6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/richclub.py
@@ -0,0 +1,138 @@
+"""Functions for computing rich-club coefficients."""
+
+from itertools import accumulate
+
+import networkx as nx
+from networkx.utils import not_implemented_for
+
+__all__ = ["rich_club_coefficient"]
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable
+def rich_club_coefficient(G, normalized=True, Q=100, seed=None):
+    r"""Returns the rich-club coefficient of the graph `G`.
+
+    For each degree *k*, the *rich-club coefficient* is the ratio of the
+    number of actual to the number of potential edges for nodes with
+    degree greater than *k*:
+
+    .. math::
+
+        \phi(k) = \frac{2 E_k}{N_k (N_k - 1)}
+
+    where `N_k` is the number of nodes with degree larger than *k*, and
+    `E_k` is the number of edges among those nodes.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        Undirected graph with neither parallel edges nor self-loops.
+    normalized : bool (optional)
+        Normalize using randomized network as in [1]_
+    Q : float (optional, default=100)
+        If `normalized` is True, perform `Q * m` double-edge
+        swaps, where `m` is the number of edges in `G`, to use as a
+        null-model for normalization.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    rc : dictionary
+       A dictionary, keyed by degree, with rich-club coefficient values.
+
+    Raises
+    ------
+    NetworkXError
+        If `G` has fewer than four nodes and ``normalized=True``.
+        A randomly sampled graph for normalization cannot be generated in this case.
+
+    Examples
+    --------
+    >>> G = nx.Graph([(0, 1), (0, 2), (1, 2), (1, 3), (1, 4), (4, 5)])
+    >>> rc = nx.rich_club_coefficient(G, normalized=False, seed=42)
+    >>> rc[0]
+    0.4
+
+    Notes
+    -----
+    The rich club definition and algorithm are found in [1]_.  This
+    algorithm ignores any edge weights and is not defined for directed
+    graphs or graphs with parallel edges or self loops.
+
+    Normalization is done by computing the rich club coefficient for a randomly
+    sampled graph with the same degree distribution as `G` by
+    repeatedly swapping the endpoints of existing edges. For graphs with fewer than 4
+    nodes, it is not possible to generate a random graph with a prescribed
+    degree distribution, as the degree distribution fully determines the graph
+    (hence making the coefficients trivially normalized to 1).
+    This function raises an exception in this case.
+
+    Estimates for appropriate values of `Q` are found in [2]_.
+
+    References
+    ----------
+    .. [1] Julian J. McAuley, Luciano da Fontoura Costa,
+       and Tibério S. Caetano,
+       "The rich-club phenomenon across complex network hierarchies",
+       Applied Physics Letters Vol 91 Issue 8, August 2007.
+       https://arxiv.org/abs/physics/0701290
+    .. [2] R. Milo, N. Kashtan, S. Itzkovitz, M. E. J. Newman, U. Alon,
+       "Uniform generation of random graphs with arbitrary degree
+       sequences", 2006. https://arxiv.org/abs/cond-mat/0312028
+    """
+    if nx.number_of_selfloops(G) > 0:
+        raise Exception(
+            "rich_club_coefficient is not implemented for graphs with self loops."
+        )
+    rc = _compute_rc(G)
+    if normalized:
+        # make R a copy of G, randomize with Q*|E| double edge swaps
+        # and use rich_club coefficient of R to normalize
+        R = G.copy()
+        E = R.number_of_edges()
+        nx.double_edge_swap(R, Q * E, max_tries=Q * E * 10, seed=seed)
+        rcran = _compute_rc(R)
+        rc = {k: v / rcran[k] for k, v in rc.items()}
+    return rc
+
+
+def _compute_rc(G):
+    """Returns the rich-club coefficient for each degree in the graph
+    `G`.
+
+    `G` is an undirected graph without multiedges.
+
+    Returns a dictionary mapping degree to rich-club coefficient for
+    that degree.
+
+    """
+    deghist = nx.degree_histogram(G)
+    total = sum(deghist)
+    # Compute the number of nodes with degree greater than `k`, for each
+    # degree `k` (omitting the last entry, which is zero).
+    nks = (total - cs for cs in accumulate(deghist) if total - cs > 1)
+    # Create a sorted list of pairs of edge endpoint degrees.
+    #
+    # The list is sorted in reverse order so that we can pop from the
+    # right side of the list later, instead of popping from the left
+    # side of the list, which would have a linear time cost.
+    edge_degrees = sorted((sorted(map(G.degree, e)) for e in G.edges()), reverse=True)
+    ek = G.number_of_edges()
+    if ek == 0:
+        return {}
+
+    k1, k2 = edge_degrees.pop()
+    rc = {}
+    for d, nk in enumerate(nks):
+        while k1 <= d:
+            if len(edge_degrees) == 0:
+                ek = 0
+                break
+            k1, k2 = edge_degrees.pop()
+            ek -= 1
+        rc[d] = 2 * ek / (nk * (nk - 1))
+    return rc
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/similarity.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/similarity.py
new file mode 100644
index 0000000000000000000000000000000000000000..25aada68d0a6c2c80545c8db54ceb3e775def44c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/similarity.py
@@ -0,0 +1,2107 @@
+"""Functions measuring similarity using graph edit distance.
+
+The graph edit distance is the number of edge/node changes needed
+to make two graphs isomorphic.
+
+The default algorithm/implementation is sub-optimal for some graphs.
+The problem of finding the exact Graph Edit Distance (GED) is NP-hard
+so it is often slow. If the simple interface `graph_edit_distance`
+takes too long for your graph, try `optimize_graph_edit_distance`
+and/or `optimize_edit_paths`.
+
+At the same time, I encourage capable people to investigate
+alternative GED algorithms, in order to improve the choices available.
+"""
+
+import math
+import time
+from dataclasses import dataclass
+from itertools import product
+
+import networkx as nx
+from networkx.utils import np_random_state
+
+__all__ = [
+    "graph_edit_distance",
+    "optimal_edit_paths",
+    "optimize_graph_edit_distance",
+    "optimize_edit_paths",
+    "simrank_similarity",
+    "panther_similarity",
+    "panther_vector_similarity",
+    "generate_random_paths",
+]
+
+
+@nx._dispatchable(
+    graphs={"G1": 0, "G2": 1}, preserve_edge_attrs=True, preserve_node_attrs=True
+)
+def graph_edit_distance(
+    G1,
+    G2,
+    node_match=None,
+    edge_match=None,
+    node_subst_cost=None,
+    node_del_cost=None,
+    node_ins_cost=None,
+    edge_subst_cost=None,
+    edge_del_cost=None,
+    edge_ins_cost=None,
+    roots=None,
+    upper_bound=None,
+    timeout=None,
+):
+    """Returns GED (graph edit distance) between graphs G1 and G2.
+
+    Graph edit distance is a graph similarity measure analogous to
+    Levenshtein distance for strings.  It is defined as minimum cost
+    of edit path (sequence of node and edge edit operations)
+    transforming graph G1 to graph isomorphic to G2.
+
+    Parameters
+    ----------
+    G1, G2: graphs
+        The two graphs G1 and G2 must be of the same type.
+
+    node_match : callable
+        A function that returns True if node n1 in G1 and n2 in G2
+        should be considered equal during matching.
+
+        The function will be called like
+
+           node_match(G1.nodes[n1], G2.nodes[n2]).
+
+        That is, the function will receive the node attribute
+        dictionaries for n1 and n2 as inputs.
+
+        Ignored if node_subst_cost is specified.  If neither
+        node_match nor node_subst_cost are specified then node
+        attributes are not considered.
+
+    edge_match : callable
+        A function that returns True if the edge attribute dictionaries
+        for the pair of nodes (u1, v1) in G1 and (u2, v2) in G2 should
+        be considered equal during matching.
+
+        The function will be called like
+
+           edge_match(G1[u1][v1], G2[u2][v2]).
+
+        That is, the function will receive the edge attribute
+        dictionaries of the edges under consideration.
+
+        Ignored if edge_subst_cost is specified.  If neither
+        edge_match nor edge_subst_cost are specified then edge
+        attributes are not considered.
+
+    node_subst_cost, node_del_cost, node_ins_cost : callable
+        Functions that return the costs of node substitution, node
+        deletion, and node insertion, respectively.
+
+        The functions will be called like
+
+           node_subst_cost(G1.nodes[n1], G2.nodes[n2]),
+           node_del_cost(G1.nodes[n1]),
+           node_ins_cost(G2.nodes[n2]).
+
+        That is, the functions will receive the node attribute
+        dictionaries as inputs.  The functions are expected to return
+        positive numeric values.
+
+        Function node_subst_cost overrides node_match if specified.
+        If neither node_match nor node_subst_cost are specified then
+        default node substitution cost of 0 is used (node attributes
+        are not considered during matching).
+
+        If node_del_cost is not specified then default node deletion
+        cost of 1 is used.  If node_ins_cost is not specified then
+        default node insertion cost of 1 is used.
+
+    edge_subst_cost, edge_del_cost, edge_ins_cost : callable
+        Functions that return the costs of edge substitution, edge
+        deletion, and edge insertion, respectively.
+
+        The functions will be called like
+
+           edge_subst_cost(G1[u1][v1], G2[u2][v2]),
+           edge_del_cost(G1[u1][v1]),
+           edge_ins_cost(G2[u2][v2]).
+
+        That is, the functions will receive the edge attribute
+        dictionaries as inputs.  The functions are expected to return
+        positive numeric values.
+
+        Function edge_subst_cost overrides edge_match if specified.
+        If neither edge_match nor edge_subst_cost are specified then
+        default edge substitution cost of 0 is used (edge attributes
+        are not considered during matching).
+
+        If edge_del_cost is not specified then default edge deletion
+        cost of 1 is used.  If edge_ins_cost is not specified then
+        default edge insertion cost of 1 is used.
+
+    roots : 2-tuple
+        Tuple where first element is a node in G1 and the second
+        is a node in G2.
+        These nodes are forced to be matched in the comparison to
+        allow comparison between rooted graphs.
+
+    upper_bound : numeric
+        Maximum edit distance to consider.  Return None if no edit
+        distance under or equal to upper_bound exists.
+
+    timeout : numeric
+        Maximum number of seconds to execute.
+        After timeout is met, the current best GED is returned.
+
+    Examples
+    --------
+    >>> G1 = nx.cycle_graph(6)
+    >>> G2 = nx.wheel_graph(7)
+    >>> nx.graph_edit_distance(G1, G2)
+    7.0
+
+    >>> G1 = nx.star_graph(5)
+    >>> G2 = nx.star_graph(5)
+    >>> nx.graph_edit_distance(G1, G2, roots=(0, 0))
+    0.0
+    >>> nx.graph_edit_distance(G1, G2, roots=(1, 0))
+    8.0
+
+    See Also
+    --------
+    optimal_edit_paths, optimize_graph_edit_distance,
+
+    is_isomorphic: test for graph edit distance of 0
+
+    References
+    ----------
+    .. [1] Zeina Abu-Aisheh, Romain Raveaux, Jean-Yves Ramel, Patrick
+       Martineau. An Exact Graph Edit Distance Algorithm for Solving
+       Pattern Recognition Problems. 4th International Conference on
+       Pattern Recognition Applications and Methods 2015, Jan 2015,
+       Lisbon, Portugal. 2015,
+       <10.5220/0005209202710278>. 
+       https://hal.archives-ouvertes.fr/hal-01168816
+
+    """
+    bestcost = None
+    for _, _, cost in optimize_edit_paths(
+        G1,
+        G2,
+        node_match,
+        edge_match,
+        node_subst_cost,
+        node_del_cost,
+        node_ins_cost,
+        edge_subst_cost,
+        edge_del_cost,
+        edge_ins_cost,
+        upper_bound,
+        True,
+        roots,
+        timeout,
+    ):
+        # assert bestcost is None or cost < bestcost
+        bestcost = cost
+    return bestcost
+
+
+@nx._dispatchable(graphs={"G1": 0, "G2": 1})
+def optimal_edit_paths(
+    G1,
+    G2,
+    node_match=None,
+    edge_match=None,
+    node_subst_cost=None,
+    node_del_cost=None,
+    node_ins_cost=None,
+    edge_subst_cost=None,
+    edge_del_cost=None,
+    edge_ins_cost=None,
+    upper_bound=None,
+):
+    """Returns all minimum-cost edit paths transforming G1 to G2.
+
+    Graph edit path is a sequence of node and edge edit operations
+    transforming graph G1 to graph isomorphic to G2.  Edit operations
+    include substitutions, deletions, and insertions.
+
+    Parameters
+    ----------
+    G1, G2: graphs
+        The two graphs G1 and G2 must be of the same type.
+
+    node_match : callable
+        A function that returns True if node n1 in G1 and n2 in G2
+        should be considered equal during matching.
+
+        The function will be called like
+
+           node_match(G1.nodes[n1], G2.nodes[n2]).
+
+        That is, the function will receive the node attribute
+        dictionaries for n1 and n2 as inputs.
+
+        Ignored if node_subst_cost is specified.  If neither
+        node_match nor node_subst_cost are specified then node
+        attributes are not considered.
+
+    edge_match : callable
+        A function that returns True if the edge attribute dictionaries
+        for the pair of nodes (u1, v1) in G1 and (u2, v2) in G2 should
+        be considered equal during matching.
+
+        The function will be called like
+
+           edge_match(G1[u1][v1], G2[u2][v2]).
+
+        That is, the function will receive the edge attribute
+        dictionaries of the edges under consideration.
+
+        Ignored if edge_subst_cost is specified.  If neither
+        edge_match nor edge_subst_cost are specified then edge
+        attributes are not considered.
+
+    node_subst_cost, node_del_cost, node_ins_cost : callable
+        Functions that return the costs of node substitution, node
+        deletion, and node insertion, respectively.
+
+        The functions will be called like
+
+           node_subst_cost(G1.nodes[n1], G2.nodes[n2]),
+           node_del_cost(G1.nodes[n1]),
+           node_ins_cost(G2.nodes[n2]).
+
+        That is, the functions will receive the node attribute
+        dictionaries as inputs.  The functions are expected to return
+        positive numeric values.
+
+        Function node_subst_cost overrides node_match if specified.
+        If neither node_match nor node_subst_cost are specified then
+        default node substitution cost of 0 is used (node attributes
+        are not considered during matching).
+
+        If node_del_cost is not specified then default node deletion
+        cost of 1 is used.  If node_ins_cost is not specified then
+        default node insertion cost of 1 is used.
+
+    edge_subst_cost, edge_del_cost, edge_ins_cost : callable
+        Functions that return the costs of edge substitution, edge
+        deletion, and edge insertion, respectively.
+
+        The functions will be called like
+
+           edge_subst_cost(G1[u1][v1], G2[u2][v2]),
+           edge_del_cost(G1[u1][v1]),
+           edge_ins_cost(G2[u2][v2]).
+
+        That is, the functions will receive the edge attribute
+        dictionaries as inputs.  The functions are expected to return
+        positive numeric values.
+
+        Function edge_subst_cost overrides edge_match if specified.
+        If neither edge_match nor edge_subst_cost are specified then
+        default edge substitution cost of 0 is used (edge attributes
+        are not considered during matching).
+
+        If edge_del_cost is not specified then default edge deletion
+        cost of 1 is used.  If edge_ins_cost is not specified then
+        default edge insertion cost of 1 is used.
+
+    upper_bound : numeric
+        Maximum edit distance to consider.
+
+    Returns
+    -------
+    edit_paths : list of tuples (node_edit_path, edge_edit_path)
+       - node_edit_path : list of tuples ``(u, v)`` indicating node transformations
+         between `G1` and `G2`. ``u`` is `None` for insertion, ``v`` is `None`
+         for deletion.
+       - edge_edit_path : list of tuples ``((u1, v1), (u2, v2))`` indicating edge
+         transformations between `G1` and `G2`. ``(None, (u2,v2))`` for insertion
+         and ``((u1,v1), None)`` for deletion.
+
+    cost : numeric
+        Optimal edit path cost (graph edit distance). When the cost
+        is zero, it indicates that `G1` and `G2` are isomorphic.
+
+    Examples
+    --------
+    >>> G1 = nx.cycle_graph(4)
+    >>> G2 = nx.wheel_graph(5)
+    >>> paths, cost = nx.optimal_edit_paths(G1, G2)
+    >>> len(paths)
+    40
+    >>> cost
+    5.0
+
+    Notes
+    -----
+    To transform `G1` into a graph isomorphic to `G2`, apply the node
+    and edge edits in the returned ``edit_paths``.
+    In the case of isomorphic graphs, the cost is zero, and the paths
+    represent different isomorphic mappings (isomorphisms). That is, the
+    edits involve renaming nodes and edges to match the structure of `G2`.
+
+    See Also
+    --------
+    graph_edit_distance, optimize_edit_paths
+
+    References
+    ----------
+    .. [1] Zeina Abu-Aisheh, Romain Raveaux, Jean-Yves Ramel, Patrick
+       Martineau. An Exact Graph Edit Distance Algorithm for Solving
+       Pattern Recognition Problems. 4th International Conference on
+       Pattern Recognition Applications and Methods 2015, Jan 2015,
+       Lisbon, Portugal. 2015,
+       <10.5220/0005209202710278>. 
+       https://hal.archives-ouvertes.fr/hal-01168816
+
+    """
+    paths = []
+    bestcost = None
+    for vertex_path, edge_path, cost in optimize_edit_paths(
+        G1,
+        G2,
+        node_match,
+        edge_match,
+        node_subst_cost,
+        node_del_cost,
+        node_ins_cost,
+        edge_subst_cost,
+        edge_del_cost,
+        edge_ins_cost,
+        upper_bound,
+        False,
+    ):
+        # assert bestcost is None or cost <= bestcost
+        if bestcost is not None and cost < bestcost:
+            paths = []
+        paths.append((vertex_path, edge_path))
+        bestcost = cost
+    return paths, bestcost
+
+
+@nx._dispatchable(graphs={"G1": 0, "G2": 1})
+def optimize_graph_edit_distance(
+    G1,
+    G2,
+    node_match=None,
+    edge_match=None,
+    node_subst_cost=None,
+    node_del_cost=None,
+    node_ins_cost=None,
+    edge_subst_cost=None,
+    edge_del_cost=None,
+    edge_ins_cost=None,
+    upper_bound=None,
+):
+    """Returns consecutive approximations of GED (graph edit distance)
+    between graphs G1 and G2.
+
+    Graph edit distance is a graph similarity measure analogous to
+    Levenshtein distance for strings.  It is defined as minimum cost
+    of edit path (sequence of node and edge edit operations)
+    transforming graph G1 to graph isomorphic to G2.
+
+    Parameters
+    ----------
+    G1, G2: graphs
+        The two graphs G1 and G2 must be of the same type.
+
+    node_match : callable
+        A function that returns True if node n1 in G1 and n2 in G2
+        should be considered equal during matching.
+
+        The function will be called like
+
+           node_match(G1.nodes[n1], G2.nodes[n2]).
+
+        That is, the function will receive the node attribute
+        dictionaries for n1 and n2 as inputs.
+
+        Ignored if node_subst_cost is specified.  If neither
+        node_match nor node_subst_cost are specified then node
+        attributes are not considered.
+
+    edge_match : callable
+        A function that returns True if the edge attribute dictionaries
+        for the pair of nodes (u1, v1) in G1 and (u2, v2) in G2 should
+        be considered equal during matching.
+
+        The function will be called like
+
+           edge_match(G1[u1][v1], G2[u2][v2]).
+
+        That is, the function will receive the edge attribute
+        dictionaries of the edges under consideration.
+
+        Ignored if edge_subst_cost is specified.  If neither
+        edge_match nor edge_subst_cost are specified then edge
+        attributes are not considered.
+
+    node_subst_cost, node_del_cost, node_ins_cost : callable
+        Functions that return the costs of node substitution, node
+        deletion, and node insertion, respectively.
+
+        The functions will be called like
+
+           node_subst_cost(G1.nodes[n1], G2.nodes[n2]),
+           node_del_cost(G1.nodes[n1]),
+           node_ins_cost(G2.nodes[n2]).
+
+        That is, the functions will receive the node attribute
+        dictionaries as inputs.  The functions are expected to return
+        positive numeric values.
+
+        Function node_subst_cost overrides node_match if specified.
+        If neither node_match nor node_subst_cost are specified then
+        default node substitution cost of 0 is used (node attributes
+        are not considered during matching).
+
+        If node_del_cost is not specified then default node deletion
+        cost of 1 is used.  If node_ins_cost is not specified then
+        default node insertion cost of 1 is used.
+
+    edge_subst_cost, edge_del_cost, edge_ins_cost : callable
+        Functions that return the costs of edge substitution, edge
+        deletion, and edge insertion, respectively.
+
+        The functions will be called like
+
+           edge_subst_cost(G1[u1][v1], G2[u2][v2]),
+           edge_del_cost(G1[u1][v1]),
+           edge_ins_cost(G2[u2][v2]).
+
+        That is, the functions will receive the edge attribute
+        dictionaries as inputs.  The functions are expected to return
+        positive numeric values.
+
+        Function edge_subst_cost overrides edge_match if specified.
+        If neither edge_match nor edge_subst_cost are specified then
+        default edge substitution cost of 0 is used (edge attributes
+        are not considered during matching).
+
+        If edge_del_cost is not specified then default edge deletion
+        cost of 1 is used.  If edge_ins_cost is not specified then
+        default edge insertion cost of 1 is used.
+
+    upper_bound : numeric
+        Maximum edit distance to consider.
+
+    Returns
+    -------
+    Generator of consecutive approximations of graph edit distance.
+
+    Examples
+    --------
+    >>> G1 = nx.cycle_graph(6)
+    >>> G2 = nx.wheel_graph(7)
+    >>> for v in nx.optimize_graph_edit_distance(G1, G2):
+    ...     minv = v
+    >>> minv
+    7.0
+
+    See Also
+    --------
+    graph_edit_distance, optimize_edit_paths
+
+    References
+    ----------
+    .. [1] Zeina Abu-Aisheh, Romain Raveaux, Jean-Yves Ramel, Patrick
+       Martineau. An Exact Graph Edit Distance Algorithm for Solving
+       Pattern Recognition Problems. 4th International Conference on
+       Pattern Recognition Applications and Methods 2015, Jan 2015,
+       Lisbon, Portugal. 2015,
+       <10.5220/0005209202710278>. 
+       https://hal.archives-ouvertes.fr/hal-01168816
+    """
+    for _, _, cost in optimize_edit_paths(
+        G1,
+        G2,
+        node_match,
+        edge_match,
+        node_subst_cost,
+        node_del_cost,
+        node_ins_cost,
+        edge_subst_cost,
+        edge_del_cost,
+        edge_ins_cost,
+        upper_bound,
+        True,
+    ):
+        yield cost
+
+
+@nx._dispatchable(
+    graphs={"G1": 0, "G2": 1}, preserve_edge_attrs=True, preserve_node_attrs=True
+)
+def optimize_edit_paths(
+    G1,
+    G2,
+    node_match=None,
+    edge_match=None,
+    node_subst_cost=None,
+    node_del_cost=None,
+    node_ins_cost=None,
+    edge_subst_cost=None,
+    edge_del_cost=None,
+    edge_ins_cost=None,
+    upper_bound=None,
+    strictly_decreasing=True,
+    roots=None,
+    timeout=None,
+):
+    """GED (graph edit distance) calculation: advanced interface.
+
+    Graph edit path is a sequence of node and edge edit operations
+    transforming graph G1 to graph isomorphic to G2.  Edit operations
+    include substitutions, deletions, and insertions.
+
+    Graph edit distance is defined as minimum cost of edit path.
+
+    Parameters
+    ----------
+    G1, G2: graphs
+        The two graphs G1 and G2 must be of the same type.
+
+    node_match : callable
+        A function that returns True if node n1 in G1 and n2 in G2
+        should be considered equal during matching.
+
+        The function will be called like
+
+           node_match(G1.nodes[n1], G2.nodes[n2]).
+
+        That is, the function will receive the node attribute
+        dictionaries for n1 and n2 as inputs.
+
+        Ignored if node_subst_cost is specified.  If neither
+        node_match nor node_subst_cost are specified then node
+        attributes are not considered.
+
+    edge_match : callable
+        A function that returns True if the edge attribute dictionaries
+        for the pair of nodes (u1, v1) in G1 and (u2, v2) in G2 should
+        be considered equal during matching.
+
+        The function will be called like
+
+           edge_match(G1[u1][v1], G2[u2][v2]).
+
+        That is, the function will receive the edge attribute
+        dictionaries of the edges under consideration.
+
+        Ignored if edge_subst_cost is specified.  If neither
+        edge_match nor edge_subst_cost are specified then edge
+        attributes are not considered.
+
+    node_subst_cost, node_del_cost, node_ins_cost : callable
+        Functions that return the costs of node substitution, node
+        deletion, and node insertion, respectively.
+
+        The functions will be called like
+
+           node_subst_cost(G1.nodes[n1], G2.nodes[n2]),
+           node_del_cost(G1.nodes[n1]),
+           node_ins_cost(G2.nodes[n2]).
+
+        That is, the functions will receive the node attribute
+        dictionaries as inputs.  The functions are expected to return
+        positive numeric values.
+
+        Function node_subst_cost overrides node_match if specified.
+        If neither node_match nor node_subst_cost are specified then
+        default node substitution cost of 0 is used (node attributes
+        are not considered during matching).
+
+        If node_del_cost is not specified then default node deletion
+        cost of 1 is used.  If node_ins_cost is not specified then
+        default node insertion cost of 1 is used.
+
+    edge_subst_cost, edge_del_cost, edge_ins_cost : callable
+        Functions that return the costs of edge substitution, edge
+        deletion, and edge insertion, respectively.
+
+        The functions will be called like
+
+           edge_subst_cost(G1[u1][v1], G2[u2][v2]),
+           edge_del_cost(G1[u1][v1]),
+           edge_ins_cost(G2[u2][v2]).
+
+        That is, the functions will receive the edge attribute
+        dictionaries as inputs.  The functions are expected to return
+        positive numeric values.
+
+        Function edge_subst_cost overrides edge_match if specified.
+        If neither edge_match nor edge_subst_cost are specified then
+        default edge substitution cost of 0 is used (edge attributes
+        are not considered during matching).
+
+        If edge_del_cost is not specified then default edge deletion
+        cost of 1 is used.  If edge_ins_cost is not specified then
+        default edge insertion cost of 1 is used.
+
+    upper_bound : numeric
+        Maximum edit distance to consider.
+
+    strictly_decreasing : bool
+        If True, return consecutive approximations of strictly
+        decreasing cost.  Otherwise, return all edit paths of cost
+        less than or equal to the previous minimum cost.
+
+    roots : 2-tuple
+        Tuple where first element is a node in G1 and the second
+        is a node in G2.
+        These nodes are forced to be matched in the comparison to
+        allow comparison between rooted graphs.
+
+    timeout : numeric
+        Maximum number of seconds to execute.
+        After timeout is met, the current best GED is returned.
+
+    Returns
+    -------
+    Generator of tuples (node_edit_path, edge_edit_path, cost)
+        node_edit_path : list of tuples (u, v)
+        edge_edit_path : list of tuples ((u1, v1), (u2, v2))
+        cost : numeric
+
+    See Also
+    --------
+    graph_edit_distance, optimize_graph_edit_distance, optimal_edit_paths
+
+    References
+    ----------
+    .. [1] Zeina Abu-Aisheh, Romain Raveaux, Jean-Yves Ramel, Patrick
+       Martineau. An Exact Graph Edit Distance Algorithm for Solving
+       Pattern Recognition Problems. 4th International Conference on
+       Pattern Recognition Applications and Methods 2015, Jan 2015,
+       Lisbon, Portugal. 2015,
+       <10.5220/0005209202710278>. 
+       https://hal.archives-ouvertes.fr/hal-01168816
+
+    """
+    # TODO: support DiGraph
+
+    import numpy as np
+    import scipy as sp
+
+    @dataclass
+    class CostMatrix:
+        C: ...
+        lsa_row_ind: ...
+        lsa_col_ind: ...
+        ls: ...
+
+    def make_CostMatrix(C, m, n):
+        # assert(C.shape == (m + n, m + n))
+        lsa_row_ind, lsa_col_ind = sp.optimize.linear_sum_assignment(C)
+
+        # Fixup dummy assignments:
+        # each substitution i<->j should have dummy assignment m+j<->n+i
+        # NOTE: fast reduce of Cv relies on it
+        # Create masks for substitution and dummy indices
+        is_subst = (lsa_row_ind < m) & (lsa_col_ind < n)
+        is_dummy = (lsa_row_ind >= m) & (lsa_col_ind >= n)
+
+        # Map dummy assignments to the correct indices
+        lsa_row_ind[is_dummy] = lsa_col_ind[is_subst] + m
+        lsa_col_ind[is_dummy] = lsa_row_ind[is_subst] + n
+
+        return CostMatrix(
+            C, lsa_row_ind, lsa_col_ind, C[lsa_row_ind, lsa_col_ind].sum()
+        )
+
+    def extract_C(C, i, j, m, n):
+        # assert(C.shape == (m + n, m + n))
+        row_ind = [k in i or k - m in j for k in range(m + n)]
+        col_ind = [k in j or k - n in i for k in range(m + n)]
+        return C[row_ind, :][:, col_ind]
+
+    def reduce_C(C, i, j, m, n):
+        # assert(C.shape == (m + n, m + n))
+        row_ind = [k not in i and k - m not in j for k in range(m + n)]
+        col_ind = [k not in j and k - n not in i for k in range(m + n)]
+        return C[row_ind, :][:, col_ind]
+
+    def reduce_ind(ind, i):
+        # assert set(ind) == set(range(len(ind)))
+        rind = ind[[k not in i for k in ind]]
+        for k in set(i):
+            rind[rind >= k] -= 1
+        return rind
+
+    def match_edges(u, v, pending_g, pending_h, Ce, matched_uv=None):
+        """
+        Parameters:
+            u, v: matched vertices, u=None or v=None for
+               deletion/insertion
+            pending_g, pending_h: lists of edges not yet mapped
+            Ce: CostMatrix of pending edge mappings
+            matched_uv: partial vertex edit path
+                list of tuples (u, v) of previously matched vertex
+                    mappings u<->v, u=None or v=None for
+                    deletion/insertion
+
+        Returns:
+            list of (i, j): indices of edge mappings g<->h
+            localCe: local CostMatrix of edge mappings
+                (basically submatrix of Ce at cross of rows i, cols j)
+        """
+        M = len(pending_g)
+        N = len(pending_h)
+        # assert Ce.C.shape == (M + N, M + N)
+
+        # only attempt to match edges after one node match has been made
+        # this will stop self-edges on the first node being automatically deleted
+        # even when a substitution is the better option
+
+        substitution_possible = M and N
+        at_least_one_node_match = matched_uv is None or len(matched_uv) == 0
+        if at_least_one_node_match and substitution_possible:
+            g_ind = []
+            h_ind = []
+        else:
+            g_ind = [
+                i
+                for i in range(M)
+                if pending_g[i][:2] == (u, u)
+                or any(
+                    pending_g[i][:2] in ((p, u), (u, p), (p, p)) for p, q in matched_uv
+                )
+            ]
+            h_ind = [
+                j
+                for j in range(N)
+                if pending_h[j][:2] == (v, v)
+                or any(
+                    pending_h[j][:2] in ((q, v), (v, q), (q, q)) for p, q in matched_uv
+                )
+            ]
+
+        m = len(g_ind)
+        n = len(h_ind)
+
+        if m or n:
+            C = extract_C(Ce.C, g_ind, h_ind, M, N)
+            # assert C.shape == (m + n, m + n)
+
+            # Forbid structurally invalid matches
+            # NOTE: inf remembered from Ce construction
+            for k, i in enumerate(g_ind):
+                g = pending_g[i][:2]
+                for l, j in enumerate(h_ind):
+                    h = pending_h[j][:2]
+                    if nx.is_directed(G1) or nx.is_directed(G2):
+                        if any(
+                            g == (p, u) and h == (q, v) or g == (u, p) and h == (v, q)
+                            for p, q in matched_uv
+                        ):
+                            continue
+                    else:
+                        if any(
+                            g in ((p, u), (u, p)) and h in ((q, v), (v, q))
+                            for p, q in matched_uv
+                        ):
+                            continue
+                    if g == (u, u) or any(g == (p, p) for p, q in matched_uv):
+                        continue
+                    if h == (v, v) or any(h == (q, q) for p, q in matched_uv):
+                        continue
+                    C[k, l] = inf
+
+            localCe = make_CostMatrix(C, m, n)
+            ij = [
+                (
+                    g_ind[k] if k < m else M + h_ind[l],
+                    h_ind[l] if l < n else N + g_ind[k],
+                )
+                for k, l in zip(localCe.lsa_row_ind, localCe.lsa_col_ind)
+                if k < m or l < n
+            ]
+
+        else:
+            ij = []
+            localCe = CostMatrix(np.empty((0, 0)), [], [], 0)
+
+        return ij, localCe
+
+    def reduce_Ce(Ce, ij, m, n):
+        if len(ij):
+            i, j = zip(*ij)
+            m_i = m - sum(1 for t in i if t < m)
+            n_j = n - sum(1 for t in j if t < n)
+            return make_CostMatrix(reduce_C(Ce.C, i, j, m, n), m_i, n_j)
+        return Ce
+
+    def get_edit_ops(
+        matched_uv, pending_u, pending_v, Cv, pending_g, pending_h, Ce, matched_cost
+    ):
+        """
+        Parameters:
+            matched_uv: partial vertex edit path
+                list of tuples (u, v) of vertex mappings u<->v,
+                u=None or v=None for deletion/insertion
+            pending_u, pending_v: lists of vertices not yet mapped
+            Cv: CostMatrix of pending vertex mappings
+            pending_g, pending_h: lists of edges not yet mapped
+            Ce: CostMatrix of pending edge mappings
+            matched_cost: cost of partial edit path
+
+        Returns:
+            sequence of
+                (i, j): indices of vertex mapping u<->v
+                Cv_ij: reduced CostMatrix of pending vertex mappings
+                    (basically Cv with row i, col j removed)
+                list of (x, y): indices of edge mappings g<->h
+                Ce_xy: reduced CostMatrix of pending edge mappings
+                    (basically Ce with rows x, cols y removed)
+                cost: total cost of edit operation
+            NOTE: most promising ops first
+        """
+        m = len(pending_u)
+        n = len(pending_v)
+        # assert Cv.C.shape == (m + n, m + n)
+
+        # 1) a vertex mapping from optimal linear sum assignment
+        i, j = min(
+            (k, l) for k, l in zip(Cv.lsa_row_ind, Cv.lsa_col_ind) if k < m or l < n
+        )
+        xy, localCe = match_edges(
+            pending_u[i] if i < m else None,
+            pending_v[j] if j < n else None,
+            pending_g,
+            pending_h,
+            Ce,
+            matched_uv,
+        )
+        Ce_xy = reduce_Ce(Ce, xy, len(pending_g), len(pending_h))
+        # assert Ce.ls <= localCe.ls + Ce_xy.ls
+        if prune(matched_cost + Cv.ls + localCe.ls + Ce_xy.ls):
+            pass
+        else:
+            # get reduced Cv efficiently
+            Cv_ij = CostMatrix(
+                reduce_C(Cv.C, (i,), (j,), m, n),
+                reduce_ind(Cv.lsa_row_ind, (i, m + j)),
+                reduce_ind(Cv.lsa_col_ind, (j, n + i)),
+                Cv.ls - Cv.C[i, j],
+            )
+            yield (i, j), Cv_ij, xy, Ce_xy, Cv.C[i, j] + localCe.ls
+
+        # 2) other candidates, sorted by lower-bound cost estimate
+        other = []
+        fixed_i, fixed_j = i, j
+        if m <= n:
+            candidates = (
+                (t, fixed_j)
+                for t in range(m + n)
+                if t != fixed_i and (t < m or t == m + fixed_j)
+            )
+        else:
+            candidates = (
+                (fixed_i, t)
+                for t in range(m + n)
+                if t != fixed_j and (t < n or t == n + fixed_i)
+            )
+        for i, j in candidates:
+            if prune(matched_cost + Cv.C[i, j] + Ce.ls):
+                continue
+            Cv_ij = make_CostMatrix(
+                reduce_C(Cv.C, (i,), (j,), m, n),
+                m - 1 if i < m else m,
+                n - 1 if j < n else n,
+            )
+            # assert Cv.ls <= Cv.C[i, j] + Cv_ij.ls
+            if prune(matched_cost + Cv.C[i, j] + Cv_ij.ls + Ce.ls):
+                continue
+            xy, localCe = match_edges(
+                pending_u[i] if i < m else None,
+                pending_v[j] if j < n else None,
+                pending_g,
+                pending_h,
+                Ce,
+                matched_uv,
+            )
+            if prune(matched_cost + Cv.C[i, j] + Cv_ij.ls + localCe.ls):
+                continue
+            Ce_xy = reduce_Ce(Ce, xy, len(pending_g), len(pending_h))
+            # assert Ce.ls <= localCe.ls + Ce_xy.ls
+            if prune(matched_cost + Cv.C[i, j] + Cv_ij.ls + localCe.ls + Ce_xy.ls):
+                continue
+            other.append(((i, j), Cv_ij, xy, Ce_xy, Cv.C[i, j] + localCe.ls))
+
+        yield from sorted(other, key=lambda t: t[4] + t[1].ls + t[3].ls)
+
+    def get_edit_paths(
+        matched_uv,
+        pending_u,
+        pending_v,
+        Cv,
+        matched_gh,
+        pending_g,
+        pending_h,
+        Ce,
+        matched_cost,
+    ):
+        """
+        Parameters:
+            matched_uv: partial vertex edit path
+                list of tuples (u, v) of vertex mappings u<->v,
+                u=None or v=None for deletion/insertion
+            pending_u, pending_v: lists of vertices not yet mapped
+            Cv: CostMatrix of pending vertex mappings
+            matched_gh: partial edge edit path
+                list of tuples (g, h) of edge mappings g<->h,
+                g=None or h=None for deletion/insertion
+            pending_g, pending_h: lists of edges not yet mapped
+            Ce: CostMatrix of pending edge mappings
+            matched_cost: cost of partial edit path
+
+        Returns:
+            sequence of (vertex_path, edge_path, cost)
+                vertex_path: complete vertex edit path
+                    list of tuples (u, v) of vertex mappings u<->v,
+                    u=None or v=None for deletion/insertion
+                edge_path: complete edge edit path
+                    list of tuples (g, h) of edge mappings g<->h,
+                    g=None or h=None for deletion/insertion
+                cost: total cost of edit path
+            NOTE: path costs are non-increasing
+        """
+        if prune(matched_cost + Cv.ls + Ce.ls):
+            return
+
+        if not max(len(pending_u), len(pending_v)):
+            # assert not len(pending_g)
+            # assert not len(pending_h)
+            # path completed!
+            # assert matched_cost <= maxcost_value
+            nonlocal maxcost_value
+            maxcost_value = min(maxcost_value, matched_cost)
+            yield matched_uv, matched_gh, matched_cost
+
+        else:
+            edit_ops = get_edit_ops(
+                matched_uv,
+                pending_u,
+                pending_v,
+                Cv,
+                pending_g,
+                pending_h,
+                Ce,
+                matched_cost,
+            )
+            for ij, Cv_ij, xy, Ce_xy, edit_cost in edit_ops:
+                i, j = ij
+                # assert Cv.C[i, j] + sum(Ce.C[t] for t in xy) == edit_cost
+                if prune(matched_cost + edit_cost + Cv_ij.ls + Ce_xy.ls):
+                    continue
+
+                # dive deeper
+                u = pending_u.pop(i) if i < len(pending_u) else None
+                v = pending_v.pop(j) if j < len(pending_v) else None
+                matched_uv.append((u, v))
+                for x, y in xy:
+                    len_g = len(pending_g)
+                    len_h = len(pending_h)
+                    matched_gh.append(
+                        (
+                            pending_g[x] if x < len_g else None,
+                            pending_h[y] if y < len_h else None,
+                        )
+                    )
+                sortedx = sorted(x for x, y in xy)
+                sortedy = sorted(y for x, y in xy)
+                G = [
+                    (pending_g.pop(x) if x < len(pending_g) else None)
+                    for x in reversed(sortedx)
+                ]
+                H = [
+                    (pending_h.pop(y) if y < len(pending_h) else None)
+                    for y in reversed(sortedy)
+                ]
+
+                yield from get_edit_paths(
+                    matched_uv,
+                    pending_u,
+                    pending_v,
+                    Cv_ij,
+                    matched_gh,
+                    pending_g,
+                    pending_h,
+                    Ce_xy,
+                    matched_cost + edit_cost,
+                )
+
+                # backtrack
+                if u is not None:
+                    pending_u.insert(i, u)
+                if v is not None:
+                    pending_v.insert(j, v)
+                matched_uv.pop()
+                for x, g in zip(sortedx, reversed(G)):
+                    if g is not None:
+                        pending_g.insert(x, g)
+                for y, h in zip(sortedy, reversed(H)):
+                    if h is not None:
+                        pending_h.insert(y, h)
+                for _ in xy:
+                    matched_gh.pop()
+
+    # Initialization
+
+    pending_u = list(G1.nodes)
+    pending_v = list(G2.nodes)
+
+    initial_cost = 0
+    if roots:
+        root_u, root_v = roots
+        if root_u not in pending_u or root_v not in pending_v:
+            raise nx.NodeNotFound("Root node not in graph.")
+
+        # remove roots from pending
+        pending_u.remove(root_u)
+        pending_v.remove(root_v)
+
+    # cost matrix of vertex mappings
+    m = len(pending_u)
+    n = len(pending_v)
+    C = np.zeros((m + n, m + n))
+    if node_subst_cost:
+        C[0:m, 0:n] = np.array(
+            [
+                node_subst_cost(G1.nodes[u], G2.nodes[v])
+                for u in pending_u
+                for v in pending_v
+            ]
+        ).reshape(m, n)
+        if roots:
+            initial_cost = node_subst_cost(G1.nodes[root_u], G2.nodes[root_v])
+    elif node_match:
+        C[0:m, 0:n] = np.array(
+            [
+                1 - int(node_match(G1.nodes[u], G2.nodes[v]))
+                for u in pending_u
+                for v in pending_v
+            ]
+        ).reshape(m, n)
+        if roots:
+            initial_cost = 1 - node_match(G1.nodes[root_u], G2.nodes[root_v])
+    else:
+        # all zeroes
+        pass
+    # assert not min(m, n) or C[0:m, 0:n].min() >= 0
+    if node_del_cost:
+        del_costs = [node_del_cost(G1.nodes[u]) for u in pending_u]
+    else:
+        del_costs = [1] * len(pending_u)
+    # assert not m or min(del_costs) >= 0
+    if node_ins_cost:
+        ins_costs = [node_ins_cost(G2.nodes[v]) for v in pending_v]
+    else:
+        ins_costs = [1] * len(pending_v)
+    # assert not n or min(ins_costs) >= 0
+    inf = C[0:m, 0:n].sum() + sum(del_costs) + sum(ins_costs) + 1
+    C[0:m, n : n + m] = np.array(
+        [del_costs[i] if i == j else inf for i in range(m) for j in range(m)]
+    ).reshape(m, m)
+    C[m : m + n, 0:n] = np.array(
+        [ins_costs[i] if i == j else inf for i in range(n) for j in range(n)]
+    ).reshape(n, n)
+    Cv = make_CostMatrix(C, m, n)
+
+    pending_g = list(G1.edges)
+    pending_h = list(G2.edges)
+
+    # cost matrix of edge mappings
+    m = len(pending_g)
+    n = len(pending_h)
+    C = np.zeros((m + n, m + n))
+    if edge_subst_cost:
+        C[0:m, 0:n] = np.array(
+            [
+                edge_subst_cost(G1.edges[g], G2.edges[h])
+                for g in pending_g
+                for h in pending_h
+            ]
+        ).reshape(m, n)
+    elif edge_match:
+        C[0:m, 0:n] = np.array(
+            [
+                1 - int(edge_match(G1.edges[g], G2.edges[h]))
+                for g in pending_g
+                for h in pending_h
+            ]
+        ).reshape(m, n)
+    else:
+        # all zeroes
+        pass
+    # assert not min(m, n) or C[0:m, 0:n].min() >= 0
+    if edge_del_cost:
+        del_costs = [edge_del_cost(G1.edges[g]) for g in pending_g]
+    else:
+        del_costs = [1] * len(pending_g)
+    # assert not m or min(del_costs) >= 0
+    if edge_ins_cost:
+        ins_costs = [edge_ins_cost(G2.edges[h]) for h in pending_h]
+    else:
+        ins_costs = [1] * len(pending_h)
+    # assert not n or min(ins_costs) >= 0
+    inf = C[0:m, 0:n].sum() + sum(del_costs) + sum(ins_costs) + 1
+    C[0:m, n : n + m] = np.array(
+        [del_costs[i] if i == j else inf for i in range(m) for j in range(m)]
+    ).reshape(m, m)
+    C[m : m + n, 0:n] = np.array(
+        [ins_costs[i] if i == j else inf for i in range(n) for j in range(n)]
+    ).reshape(n, n)
+    Ce = make_CostMatrix(C, m, n)
+
+    maxcost_value = Cv.C.sum() + Ce.C.sum() + 1
+
+    if timeout is not None:
+        if timeout <= 0:
+            raise nx.NetworkXError("Timeout value must be greater than 0")
+        start = time.perf_counter()
+
+    def prune(cost):
+        if timeout is not None:
+            if time.perf_counter() - start > timeout:
+                return True
+        if upper_bound is not None:
+            if cost > upper_bound:
+                return True
+        if cost > maxcost_value:
+            return True
+        if strictly_decreasing and cost >= maxcost_value:
+            return True
+        return False
+
+    # Now go!
+
+    done_uv = [] if roots is None else [roots]
+
+    for vertex_path, edge_path, cost in get_edit_paths(
+        done_uv, pending_u, pending_v, Cv, [], pending_g, pending_h, Ce, initial_cost
+    ):
+        # assert sorted(G1.nodes) == sorted(u for u, v in vertex_path if u is not None)
+        # assert sorted(G2.nodes) == sorted(v for u, v in vertex_path if v is not None)
+        # assert sorted(G1.edges) == sorted(g for g, h in edge_path if g is not None)
+        # assert sorted(G2.edges) == sorted(h for g, h in edge_path if h is not None)
+        # print(vertex_path, edge_path, cost, file = sys.stderr)
+        # assert cost == maxcost_value
+        yield list(vertex_path), list(edge_path), float(cost)
+
+
+@nx._dispatchable
+def simrank_similarity(
+    G,
+    source=None,
+    target=None,
+    importance_factor=0.9,
+    max_iterations=1000,
+    tolerance=1e-4,
+):
+    """Returns the SimRank similarity of nodes in the graph ``G``.
+
+    SimRank is a similarity metric that says "two objects are considered
+    to be similar if they are referenced by similar objects." [1]_.
+
+    The pseudo-code definition from the paper is::
+
+        def simrank(G, u, v):
+            in_neighbors_u = G.predecessors(u)
+            in_neighbors_v = G.predecessors(v)
+            scale = C / (len(in_neighbors_u) * len(in_neighbors_v))
+            return scale * sum(
+                simrank(G, w, x) for w, x in product(in_neighbors_u, in_neighbors_v)
+            )
+
+    where ``G`` is the graph, ``u`` is the source, ``v`` is the target,
+    and ``C`` is a float decay or importance factor between 0 and 1.
+
+    The SimRank algorithm for determining node similarity is defined in
+    [2]_.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        A NetworkX graph
+
+    source : node
+        If this is specified, the returned dictionary maps each node
+        ``v`` in the graph to the similarity between ``source`` and
+        ``v``.
+
+    target : node
+        If both ``source`` and ``target`` are specified, the similarity
+        value between ``source`` and ``target`` is returned. If
+        ``target`` is specified but ``source`` is not, this argument is
+        ignored.
+
+    importance_factor : float
+        The relative importance of indirect neighbors with respect to
+        direct neighbors.
+
+    max_iterations : integer
+        Maximum number of iterations.
+
+    tolerance : float
+        Error tolerance used to check convergence. When an iteration of
+        the algorithm finds that no similarity value changes more than
+        this amount, the algorithm halts.
+
+    Returns
+    -------
+    similarity : dictionary or float
+        If ``source`` and ``target`` are both ``None``, this returns a
+        dictionary of dictionaries, where keys are node pairs and value
+        are similarity of the pair of nodes.
+
+        If ``source`` is not ``None`` but ``target`` is, this returns a
+        dictionary mapping node to the similarity of ``source`` and that
+        node.
+
+        If neither ``source`` nor ``target`` is ``None``, this returns
+        the similarity value for the given pair of nodes.
+
+    Raises
+    ------
+    ExceededMaxIterations
+        If the algorithm does not converge within ``max_iterations``.
+
+    NodeNotFound
+        If either ``source`` or ``target`` is not in `G`.
+
+    Examples
+    --------
+    >>> G = nx.cycle_graph(2)
+    >>> nx.simrank_similarity(G)
+    {0: {0: 1.0, 1: 0.0}, 1: {0: 0.0, 1: 1.0}}
+    >>> nx.simrank_similarity(G, source=0)
+    {0: 1.0, 1: 0.0}
+    >>> nx.simrank_similarity(G, source=0, target=0)
+    1.0
+
+    The result of this function can be converted to a numpy array
+    representing the SimRank matrix by using the node order of the
+    graph to determine which row and column represent each node.
+    Other ordering of nodes is also possible.
+
+    >>> import numpy as np
+    >>> sim = nx.simrank_similarity(G)
+    >>> np.array([[sim[u][v] for v in G] for u in G])
+    array([[1., 0.],
+           [0., 1.]])
+    >>> sim_1d = nx.simrank_similarity(G, source=0)
+    >>> np.array([sim[0][v] for v in G])
+    array([1., 0.])
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/SimRank
+    .. [2] G. Jeh and J. Widom.
+           "SimRank: a measure of structural-context similarity",
+           In KDD'02: Proceedings of the Eighth ACM SIGKDD
+           International Conference on Knowledge Discovery and Data Mining,
+           pp. 538--543. ACM Press, 2002.
+    """
+    import numpy as np
+
+    nodelist = list(G)
+    if source is not None:
+        if source not in nodelist:
+            raise nx.NodeNotFound(f"Source node {source} not in G")
+        else:
+            s_indx = nodelist.index(source)
+    else:
+        s_indx = None
+
+    if target is not None:
+        if target not in nodelist:
+            raise nx.NodeNotFound(f"Target node {target} not in G")
+        else:
+            t_indx = nodelist.index(target)
+    else:
+        t_indx = None
+
+    x = _simrank_similarity_numpy(
+        G, s_indx, t_indx, importance_factor, max_iterations, tolerance
+    )
+
+    if isinstance(x, np.ndarray):
+        if x.ndim == 1:
+            return dict(zip(G, x.tolist()))
+        # else x.ndim == 2
+        return {u: dict(zip(G, row)) for u, row in zip(G, x.tolist())}
+    return float(x)
+
+
+def _simrank_similarity_python(
+    G,
+    source=None,
+    target=None,
+    importance_factor=0.9,
+    max_iterations=1000,
+    tolerance=1e-4,
+):
+    """Returns the SimRank similarity of nodes in the graph ``G``.
+
+    This pure Python version is provided for pedagogical purposes.
+
+    Examples
+    --------
+    >>> G = nx.cycle_graph(2)
+    >>> nx.similarity._simrank_similarity_python(G)
+    {0: {0: 1, 1: 0.0}, 1: {0: 0.0, 1: 1}}
+    >>> nx.similarity._simrank_similarity_python(G, source=0)
+    {0: 1, 1: 0.0}
+    >>> nx.similarity._simrank_similarity_python(G, source=0, target=0)
+    1
+    """
+    # build up our similarity adjacency dictionary output
+    newsim = {u: {v: 1 if u == v else 0 for v in G} for u in G}
+
+    # These functions compute the update to the similarity value of the nodes
+    # `u` and `v` with respect to the previous similarity values.
+    def avg_sim(s):
+        return sum(newsim[w][x] for (w, x) in s) / len(s) if s else 0.0
+
+    Gadj = G.pred if G.is_directed() else G.adj
+
+    def sim(u, v):
+        return importance_factor * avg_sim(list(product(Gadj[u], Gadj[v])))
+
+    for its in range(max_iterations):
+        oldsim = newsim
+        newsim = {u: {v: sim(u, v) if u != v else 1 for v in G} for u in G}
+        is_close = all(
+            all(
+                abs(newsim[u][v] - old) <= tolerance * (1 + abs(old))
+                for v, old in nbrs.items()
+            )
+            for u, nbrs in oldsim.items()
+        )
+        if is_close:
+            break
+
+    if its + 1 == max_iterations:
+        raise nx.ExceededMaxIterations(
+            f"simrank did not converge after {max_iterations} iterations."
+        )
+
+    if source is not None and target is not None:
+        return newsim[source][target]
+    if source is not None:
+        return newsim[source]
+    return newsim
+
+
+def _simrank_similarity_numpy(
+    G,
+    source=None,
+    target=None,
+    importance_factor=0.9,
+    max_iterations=1000,
+    tolerance=1e-4,
+):
+    """Calculate SimRank of nodes in ``G`` using matrices with ``numpy``.
+
+    The SimRank algorithm for determining node similarity is defined in
+    [1]_.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        A NetworkX graph
+
+    source : node
+        If this is specified, the returned dictionary maps each node
+        ``v`` in the graph to the similarity between ``source`` and
+        ``v``.
+
+    target : node
+        If both ``source`` and ``target`` are specified, the similarity
+        value between ``source`` and ``target`` is returned. If
+        ``target`` is specified but ``source`` is not, this argument is
+        ignored.
+
+    importance_factor : float
+        The relative importance of indirect neighbors with respect to
+        direct neighbors.
+
+    max_iterations : integer
+        Maximum number of iterations.
+
+    tolerance : float
+        Error tolerance used to check convergence. When an iteration of
+        the algorithm finds that no similarity value changes more than
+        this amount, the algorithm halts.
+
+    Returns
+    -------
+    similarity : numpy array or float
+        If ``source`` and ``target`` are both ``None``, this returns a
+        2D array containing SimRank scores of the nodes.
+
+        If ``source`` is not ``None`` but ``target`` is, this returns an
+        1D array containing SimRank scores of ``source`` and that
+        node.
+
+        If neither ``source`` nor ``target`` is ``None``, this returns
+        the similarity value for the given pair of nodes.
+
+    Examples
+    --------
+    >>> G = nx.cycle_graph(2)
+    >>> nx.similarity._simrank_similarity_numpy(G)
+    array([[1., 0.],
+           [0., 1.]])
+    >>> nx.similarity._simrank_similarity_numpy(G, source=0)
+    array([1., 0.])
+    >>> nx.similarity._simrank_similarity_numpy(G, source=0, target=0)
+    1.0
+
+    References
+    ----------
+    .. [1] G. Jeh and J. Widom.
+           "SimRank: a measure of structural-context similarity",
+           In KDD'02: Proceedings of the Eighth ACM SIGKDD
+           International Conference on Knowledge Discovery and Data Mining,
+           pp. 538--543. ACM Press, 2002.
+    """
+    # This algorithm follows roughly
+    #
+    #     S = max{C * (A.T * S * A), I}
+    #
+    # where C is the importance factor, A is the column normalized
+    # adjacency matrix, and I is the identity matrix.
+    import numpy as np
+
+    adjacency_matrix = nx.to_numpy_array(G)
+
+    # column-normalize the ``adjacency_matrix``
+    s = np.array(adjacency_matrix.sum(axis=0))
+    s[s == 0] = 1
+    adjacency_matrix /= s  # adjacency_matrix.sum(axis=0)
+
+    newsim = np.eye(len(G), dtype=np.float64)
+    for its in range(max_iterations):
+        prevsim = newsim.copy()
+        newsim = importance_factor * ((adjacency_matrix.T @ prevsim) @ adjacency_matrix)
+        np.fill_diagonal(newsim, 1.0)
+
+        if np.allclose(prevsim, newsim, atol=tolerance):
+            break
+
+    if its + 1 == max_iterations:
+        raise nx.ExceededMaxIterations(
+            f"simrank did not converge after {max_iterations} iterations."
+        )
+
+    if source is not None and target is not None:
+        return float(newsim[source, target])
+    if source is not None:
+        return newsim[source]
+    return newsim
+
+
+@np_random_state("seed")
+def _prepare_panther_paths(
+    G,
+    source,
+    path_length=5,
+    c=0.5,
+    delta=0.1,
+    eps=None,
+    weight="weight",
+    remove_isolates=True,
+    k=None,
+    seed=None,
+):
+    """Common preparation code for Panther similarity algorithms.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        A NetworkX graph
+    source : node
+        Source node for similarity calculation
+    path_length : int
+        How long the randomly generated paths should be
+    c : float
+        A universal constant that controls the number of random paths to generate
+    delta : float
+        The probability parameter for similarity approximation
+    eps : float or None
+        The error bound for similarity approximation
+    weight : string or None
+        The name of an edge attribute that holds the numerical value used as a weight
+    remove_isolates : bool
+        Whether to remove isolated nodes from graph processing
+    k : int or None
+        The number of most similar nodes to return. If provided, validates that
+       ``k`` is not greater than the number of nodes in the graph.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    PantherPaths
+        A tuple containing the prepared data:
+        - G: The graph (possibly with isolates removed)
+        - inv_node_map: Dictionary mapping node names to indices
+        - index_map: Populated index map of paths
+        - inv_sample_size: Inverse of sample size (for fast calculation)
+        - eps: Error bound for similarity approximation
+    """
+    import numpy as np
+
+    if source not in G:
+        raise nx.NodeNotFound(f"Source node {source} not in G")
+
+    isolates = set(nx.isolates(G))
+
+    if source in isolates:
+        raise nx.NetworkXUnfeasible(
+            f"Panther similarity is not defined for the isolated source node {source}."
+        )
+
+    if remove_isolates:
+        G = G.subgraph(node for node in G if node not in isolates).copy()
+
+    # According to [1], they empirically determined
+    # a good value for ``eps`` to be sqrt( 1 / |E| )
+    if eps is None:
+        eps = np.sqrt(1.0 / G.number_of_edges())
+
+    num_nodes = G.number_of_nodes()
+
+    # Check if k is provided and validate it against the number of nodes
+    if k is not None and not remove_isolates:  # For panther_vector_similarity
+        if num_nodes < k:
+            raise nx.NetworkXUnfeasible(
+                f"The number of requested nodes {k} is greater than the number of nodes {num_nodes}."
+            )
+
+    inv_node_map = {name: index for index, name in enumerate(G)}
+
+    # Calculate the sample size ``R`` for how many paths
+    # to randomly generate
+    t_choose_2 = math.comb(path_length, 2)
+    sample_size = int((c / eps**2) * (np.log2(t_choose_2) + 1 + np.log(1 / delta)))
+    index_map = {}
+
+    # Check for isolated nodes before generating random paths
+    # If there are still isolated nodes in the graph after filtering,
+    # they will cause issues with path generation
+    remaining_isolates = set(nx.isolates(G))
+    if remaining_isolates:
+        raise nx.NetworkXUnfeasible(
+            f"Cannot generate random paths with isolated nodes present: {remaining_isolates}"
+        )
+
+    # Generate the random paths and populate the index_map
+    for _ in generate_random_paths(
+        G,
+        sample_size,
+        path_length=path_length,
+        index_map=index_map,
+        weight=weight,
+        seed=seed,
+    ):
+        # NOTE: index_map is modified in-place by `generate_random_paths`
+        pass
+
+    return (
+        G,  # The graph with isolated nodes removed
+        inv_node_map,
+        index_map,
+        1 / sample_size,
+        eps,
+    )
+
+
+@np_random_state("seed")
+@nx._dispatchable(edge_attrs="weight")
+def panther_similarity(
+    G,
+    source,
+    k=5,
+    path_length=5,
+    c=0.5,
+    delta=0.1,
+    eps=None,
+    weight="weight",
+    seed=None,
+):
+    r"""Returns the Panther similarity of nodes in the graph `G` to node ``v``.
+
+    Panther is a similarity metric that says "two objects are considered
+    to be similar if they frequently appear on the same paths." [1]_.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        A NetworkX graph
+    source : node
+        Source node for which to find the top `k` similar other nodes
+    k : int (default = 5)
+        The number of most similar nodes to return.
+    path_length : int (default = 5)
+        How long the randomly generated paths should be (``T`` in [1]_)
+    c : float (default = 0.5)
+        A universal constant that controls the number of random paths to generate.
+        Higher values increase the number of sample paths and potentially improve
+        accuracy at the cost of more computation. Defaults to 0.5 as recommended
+        in [1]_.
+    delta : float (default = 0.1)
+        The probability that the similarity $S$ is not an epsilon-approximation to (R, phi),
+        where $R$ is the number of random paths and $\phi$ is the probability
+        that an element sampled from a set $A \subseteq D$, where $D$ is the domain.
+    eps : float or None (default = None)
+        The error bound for similarity approximation. This controls the accuracy
+        of the sampled paths in representing the true similarity. Smaller values
+        yield more accurate results but require more sample paths. If `None`, a
+        value of ``sqrt(1/|E|)`` is used, which the authors found empirically
+        effective.
+    weight : string or None, optional (default="weight")
+        The name of an edge attribute that holds the numerical value
+        used as a weight. If None then each edge has weight 1.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    similarity : dictionary
+        Dictionary of nodes to similarity scores (as floats). Note:
+        the self-similarity (i.e., ``v``) will not be included in
+        the returned dictionary. So, for ``k = 5``, a dictionary of
+        top 4 nodes and their similarity scores will be returned.
+
+    Raises
+    ------
+    NetworkXUnfeasible
+        If `source` is an isolated node.
+
+    NodeNotFound
+        If `source` is not in `G`.
+
+    Notes
+    -----
+        The isolated nodes in `G` are ignored.
+
+    Examples
+    --------
+    >>> G = nx.star_graph(10)
+    >>> sim = nx.panther_similarity(G, 0)
+
+    References
+    ----------
+    .. [1] Zhang, J., Tang, J., Ma, C., Tong, H., Jing, Y., & Li, J.
+           Panther: Fast top-k similarity search on large networks.
+           In Proceedings of the ACM SIGKDD International Conference
+           on Knowledge Discovery and Data Mining (Vol. 2015-August, pp. 1445–1454).
+           Association for Computing Machinery. https://doi.org/10.1145/2783258.2783267.
+    """
+    import numpy as np
+
+    # Use helper method to prepare common data structures
+    G, inv_node_map, index_map, inv_sample_size, eps = _prepare_panther_paths(
+        G,
+        source,
+        path_length=path_length,
+        c=c,
+        delta=delta,
+        eps=eps,
+        weight=weight,
+        k=k,
+        seed=seed,
+    )
+
+    num_nodes = G.number_of_nodes()
+    node_list = list(G.nodes)
+
+    # Check number of nodes after any modifications by _prepare_panther_paths
+    if num_nodes < k:
+        raise nx.NetworkXUnfeasible(
+            f"The number of requested nodes {k} is greater than the number of nodes {num_nodes}."
+        )
+
+    S = np.zeros(num_nodes)
+    source_paths = set(index_map[source])
+
+    # Calculate the path similarities
+    # between ``source`` (v) and ``node`` (v_j)
+    # using our inverted index mapping of
+    # vertices to paths
+    for node, paths in index_map.items():
+        # Only consider paths where both
+        # ``node`` and ``source`` are present
+        common_paths = source_paths.intersection(paths)
+        S[inv_node_map[node]] = len(common_paths) * inv_sample_size
+
+    # Retrieve top ``k+1`` similar to account for removing self-similarity
+    # Note: the below performed anywhere from 4-10x faster
+    # (depending on input sizes) vs the equivalent ``np.argsort(S)[::-1]``
+    partition_k = min(k + 1, num_nodes)
+    top_k_unsorted = np.argpartition(S, -partition_k)[-partition_k:]
+    top_k_sorted = top_k_unsorted[np.argsort(S[top_k_unsorted])][::-1]
+
+    # Add back the similarity scores
+    # Convert numpy scalars to native Python types for dispatch compatibility
+    top_k_with_val = dict(
+        zip((node_list[i] for i in top_k_sorted), S[top_k_sorted].tolist())
+    )
+
+    # Remove the self-similarity
+    top_k_with_val.pop(source, None)
+    return top_k_with_val
+
+
+@np_random_state("seed")
+@nx._dispatchable(edge_attrs="weight")
+def panther_vector_similarity(
+    G,
+    source,
+    *,
+    D=10,
+    k=5,
+    path_length=5,
+    c=0.5,
+    delta=0.1,
+    eps=None,
+    weight="weight",
+    seed=None,
+):
+    r"""Returns the Panther vector similarity (Panther++) of nodes in `G`.
+
+    Computes similarity between nodes based on the "Panther++" algorithm [1]_, which extends
+    the basic Panther algorithm by using feature vectors to better capture structural
+    similarity.
+
+    While basic Panther similarity measures how often two nodes appear on the same paths,
+    Panther vector similarity (Panther++) creates a ``D``-dimensional feature vector for each
+    node using its top similarity scores with other nodes, then computes similarity based
+    on the Euclidean distance between these feature vectors. This approach better captures
+    structural similarity and addresses the bias towards close neighbors present in
+    the original Panther algorithm.
+
+    This approach is preferred when:
+
+    1. You need better structural similarity than basic path co-occurrence
+    2. You want to overcome the close-neighbor bias of standard Panther
+    3. You're working with large graphs where k-d tree indexing would be beneficial
+    4. Graph edit distance-like similarity is more appropriate than path co-occurrence
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        A NetworkX graph
+    source : node
+        Source node for which to find the top ``k`` similar other nodes
+    D : int
+        The number of similarity scores to use (in descending order)
+        for each feature vector. Defaults to 10. Note that the original paper
+        used D=50 [1]_, but KDTree is optimized for lower dimensions.
+    k : int
+        The number of most similar nodes to return
+    path_length : int
+        How long the randomly generated paths should be (``T`` in [1]_)
+    c : float
+        A universal constant that controls the number of random paths to generate.
+        Higher values increase the number of sample paths and potentially improve
+        accuracy at the cost of more computation. Defaults to 0.5 as recommended
+        in [1]_.
+    delta : float
+        The probability that ``S`` is not an epsilon-approximation to (R, phi)
+    eps : float
+        The error bound for similarity approximation. This controls the accuracy
+        of the sampled paths in representing the true similarity. Smaller values
+        yield more accurate results but require more sample paths. If None, a
+        value of ``sqrt(1/|E|)`` is used, which the authors found empirically
+        effective.
+    weight : string or None, optional (default="weight")
+        The name of an edge attribute that holds the numerical value
+        used as a weight. If `None` then each edge has weight 1.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    similarity : dict
+        Dict of nodes to similarity scores (as floats).
+        Note: the self-similarity (i.e., `node`) is not included in the dict.
+
+    Examples
+    --------
+    >>> G = nx.star_graph(100)
+
+    The "hub" node is distinct from the "spoke" nodes
+
+    >>> from pprint import pprint
+    >>> pprint(nx.panther_vector_similarity(G, source=0, seed=42))
+    {35: 0.10402634656233918,
+     61: 0.10434063328712018,
+     65: 0.10401247833456054,
+     85: 0.10506718868571752,
+     88: 0.10402634656233918}
+
+    But "spoke" nodes are similar to one another
+
+    >>> result = nx.panther_vector_similarity(G, source=1, seed=42)
+    >>> len(result)
+    5
+    >>> all(similarity == 1.0 for similarity in result.values())
+    True
+
+    Notes
+    -----
+    Results may be nondeterministic when feature vectors have the same distances,
+    as the KDTree's internal tie-breaking behavior can vary between runs.
+    Using the same ``seed`` parameter ensures reproducible results.
+
+    References
+    ----------
+    .. [1] Zhang, J., Tang, J., Ma, C., Tong, H., Jing, Y., & Li, J.
+           Panther: Fast top-k similarity search on large networks.
+           In Proceedings of the ACM SIGKDD International Conference
+           on Knowledge Discovery and Data Mining (Vol. 2015-August, pp. 1445–1454).
+           Association for Computing Machinery. https://doi.org/10.1145/2783258.2783267.
+    """
+    import numpy as np
+    import scipy as sp
+
+    # Use helper method to prepare common data structures but keep isolates in the graph
+    G, inv_node_map, index_map, inv_sample_size, eps = _prepare_panther_paths(
+        G,
+        source,
+        path_length=path_length,
+        c=c,
+        delta=delta,
+        eps=eps,
+        weight=weight,
+        remove_isolates=False,
+        k=k,
+        seed=seed,
+    )
+    num_nodes = G.number_of_nodes()
+    node_list = list(G.nodes)
+
+    # Ensure D doesn't exceed the number of nodes
+    if num_nodes < D:
+        raise nx.NetworkXUnfeasible(
+            f"The number of requested similarity scores {D} is greater than the number of nodes {num_nodes}."
+        )
+
+    similarities = np.zeros((num_nodes, num_nodes))
+    theta = np.zeros((num_nodes, D))
+    index_map_sets = {node: set(paths) for node, paths in index_map.items()}
+
+    # Calculate the path similarities for each node
+    for vi_idx, vi in enumerate(G.nodes):
+        vi_paths = index_map_sets[vi]
+
+        for node, node_paths in index_map_sets.items():
+            # Calculate similarity score
+            common_path_count = len(vi_paths.intersection(node_paths))
+            similarities[vi_idx, inv_node_map[node]] = (
+                common_path_count * inv_sample_size
+            )
+
+        # Build up the feature vector using the largest D similarity scores
+        theta[vi_idx] = np.sort(np.partition(similarities[vi_idx], -D)[-D:])[::-1]
+
+    # Insert the feature vectors into a k-d tree
+    # for fast retrieval
+    kdtree = sp.spatial.KDTree(theta)
+
+    # Retrieve top ``k+1`` similar vertices (i.e., vectors)
+    # (based on their Euclidean distance)
+    # Note that it's k+1 because the source node will be included and later removed
+    query_k = min(k + 1, num_nodes)
+    neighbor_distances, nearest_neighbors = kdtree.query(
+        theta[inv_node_map[source]], k=query_k
+    )
+
+    # Ensure results are always arrays (KDTree returns scalars when k=1)
+    neighbor_distances = np.atleast_1d(neighbor_distances)
+    nearest_neighbors = np.atleast_1d(nearest_neighbors)
+
+    # The paper defines the similarity S(v_i, v_j) as
+    # 1 / || Theta(v_i) - Theta(v_j) ||
+    # Calculate reciprocals and normalize to [0, 1] range
+
+    # Handle the case where distances are very small or zero (common in small graphs)
+    # Use the passed in eps parameter instead of defining a new epsilon
+    neighbor_distances = np.maximum(neighbor_distances, eps)
+    similarities = 1 / neighbor_distances
+
+    # Always normalize to ensure values are between 0 and 1
+    if len(similarities) > 0 and (max_sim := np.max(similarities)) > 0:
+        similarities /= max_sim
+
+    # Add back the similarity scores (i.e., distances)
+    # Convert numpy scalars to native Python types for dispatch compatibility
+    top_k_with_val = dict(
+        zip((node_list[n] for n in nearest_neighbors), similarities.tolist())
+    )
+
+    # Remove the self-similarity
+    top_k_with_val.pop(source, None)
+
+    # Ensure we return exactly k results (sorted by similarity)
+    if len(top_k_with_val) > k:
+        sorted_items = sorted(top_k_with_val.items(), key=lambda x: x[1], reverse=True)
+        top_k_with_val = dict(sorted_items[:k])
+
+    return top_k_with_val
+
+
+@np_random_state("seed")
+@nx._dispatchable(edge_attrs="weight")
+def generate_random_paths(
+    G,
+    sample_size,
+    path_length=5,
+    index_map=None,
+    weight="weight",
+    seed=None,
+    *,
+    source=None,
+):
+    """Randomly generate `sample_size` paths of length `path_length`.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        A NetworkX graph
+    sample_size : integer
+        The number of paths to generate. This is ``R`` in [1]_.
+    path_length : integer (default = 5)
+        The maximum size of the path to randomly generate.
+        This is ``T`` in [1]_. According to the paper, ``T >= 5`` is
+        recommended.
+    index_map : dictionary, optional
+        If provided, this will be populated with the inverted
+        index of nodes mapped to the set of generated random path
+        indices within ``paths``.
+    weight : string or None, optional (default="weight")
+        The name of an edge attribute that holds the numerical value
+        used as a weight. If None then each edge has weight 1.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    source : node, optional
+        Node to use as the starting point for all generated paths.
+        If None then starting nodes are selected at random with uniform probability.
+
+    Returns
+    -------
+    paths : generator of lists
+        Generator of `sample_size` paths each with length `path_length`.
+
+    Examples
+    --------
+    The generator yields `sample_size` number of paths of length `path_length`
+    drawn from `G`:
+
+    >>> G = nx.complete_graph(5)
+    >>> next(nx.generate_random_paths(G, sample_size=1, path_length=3, seed=42))
+    [3, 4, 2, 3]
+    >>> list(nx.generate_random_paths(G, sample_size=3, path_length=4, seed=42))
+    [[3, 4, 2, 3, 0], [2, 0, 2, 1, 0], [2, 0, 4, 3, 0]]
+
+    By passing a dictionary into `index_map`, it will build an
+    inverted index mapping of nodes to the paths in which that node is present:
+
+    >>> G = nx.wheel_graph(10)
+    >>> index_map = {}
+    >>> random_paths = list(
+    ...     nx.generate_random_paths(G, sample_size=3, index_map=index_map, seed=2771)
+    ... )
+    >>> random_paths
+    [[3, 2, 1, 9, 8, 7], [4, 0, 5, 6, 7, 8], [3, 0, 5, 0, 9, 8]]
+    >>> paths_containing_node_0 = [
+    ...     random_paths[path_idx] for path_idx in index_map.get(0, [])
+    ... ]
+    >>> paths_containing_node_0
+    [[4, 0, 5, 6, 7, 8], [3, 0, 5, 0, 9, 8]]
+
+    References
+    ----------
+    .. [1] Zhang, J., Tang, J., Ma, C., Tong, H., Jing, Y., & Li, J.
+           Panther: Fast top-k similarity search on large networks.
+           In Proceedings of the ACM SIGKDD International Conference
+           on Knowledge Discovery and Data Mining (Vol. 2015-August, pp. 1445–1454).
+           Association for Computing Machinery. https://doi.org/10.1145/2783258.2783267.
+    """
+    import numpy as np
+
+    randint_fn = (
+        seed.integers if isinstance(seed, np.random.Generator) else seed.randint
+    )
+
+    # Calculate transition probabilities between
+    # every pair of vertices according to Eq. (3)
+    adj_mat = nx.to_numpy_array(G, weight=weight)
+
+    # Handle isolated nodes by checking for zero row sums
+    row_sums = adj_mat.sum(axis=1).reshape(-1, 1)
+    inv_row_sums = np.reciprocal(row_sums)
+    transition_probabilities = adj_mat * inv_row_sums
+
+    node_map = list(G)
+    num_nodes = G.number_of_nodes()
+
+    for path_index in range(sample_size):
+        if source is None:
+            # Sample current vertex v = v_i uniformly at random
+            node_index = randint_fn(num_nodes)
+            node = node_map[node_index]
+        else:
+            if source not in node_map:
+                raise nx.NodeNotFound(f"Initial node {source} not in G")
+
+            node = source
+            node_index = node_map.index(node)
+
+        # Add v into p_r and add p_r into the path set
+        # of v, i.e., P_v
+        path = [node]
+
+        # Build the inverted index (P_v) of vertices to paths
+        if index_map is not None:
+            if node in index_map:
+                index_map[node].add(path_index)
+            else:
+                index_map[node] = {path_index}
+
+        starting_index = node_index
+        for _ in range(path_length):
+            # Randomly sample a neighbor (v_j) according
+            # to transition probabilities from ``node`` (v) to its neighbors
+            nbr_index = seed.choice(
+                num_nodes, p=transition_probabilities[starting_index]
+            )
+
+            # Set current vertex (v = v_j)
+            starting_index = nbr_index
+
+            # Add v into p_r
+            nbr_node = node_map[nbr_index]
+            path.append(nbr_node)
+
+            # Add p_r into P_v
+            if index_map is not None:
+                if nbr_node in index_map:
+                    index_map[nbr_node].add(path_index)
+                else:
+                    index_map[nbr_node] = {path_index}
+
+        yield path
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/simple_paths.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/simple_paths.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9656ba53c3ae48b07fa47c1ac3e691b32e2d8ca
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/simple_paths.py
@@ -0,0 +1,966 @@
+from heapq import heappop, heappush
+from itertools import count
+
+import networkx as nx
+from networkx.algorithms.shortest_paths.weighted import _weight_function
+from networkx.utils import not_implemented_for, pairwise
+
+__all__ = [
+    "all_simple_paths",
+    "is_simple_path",
+    "shortest_simple_paths",
+    "all_simple_edge_paths",
+]
+
+
+@nx._dispatchable
+def is_simple_path(G, nodes):
+    """Returns True if and only if `nodes` form a simple path in `G`.
+
+    A *simple path* in a graph is a nonempty sequence of nodes in which
+    no node appears more than once in the sequence, and each adjacent
+    pair of nodes in the sequence is adjacent in the graph.
+
+    Parameters
+    ----------
+    G : graph
+        A NetworkX graph.
+    nodes : list
+        A list of one or more nodes in the graph `G`.
+
+    Returns
+    -------
+    bool
+        Whether the given list of nodes represents a simple path in `G`.
+
+    Notes
+    -----
+    An empty list of nodes is not a path but a list of one node is a
+    path. Here's an explanation why.
+
+    This function operates on *node paths*. One could also consider
+    *edge paths*. There is a bijection between node paths and edge
+    paths.
+
+    The *length of a path* is the number of edges in the path, so a list
+    of nodes of length *n* corresponds to a path of length *n* - 1.
+    Thus the smallest edge path would be a list of zero edges, the empty
+    path. This corresponds to a list of one node.
+
+    To convert between a node path and an edge path, you can use code
+    like the following::
+
+        >>> from networkx.utils import pairwise
+        >>> nodes = [0, 1, 2, 3]
+        >>> edges = list(pairwise(nodes))
+        >>> edges
+        [(0, 1), (1, 2), (2, 3)]
+        >>> nodes = [edges[0][0]] + [v for u, v in edges]
+        >>> nodes
+        [0, 1, 2, 3]
+
+    Examples
+    --------
+    >>> G = nx.cycle_graph(4)
+    >>> nx.is_simple_path(G, [2, 3, 0])
+    True
+    >>> nx.is_simple_path(G, [0, 2])
+    False
+
+    """
+    # The empty list is not a valid path. Could also return
+    # NetworkXPointlessConcept here.
+    if len(nodes) == 0:
+        return False
+
+    # If the list is a single node, just check that the node is actually
+    # in the graph.
+    if len(nodes) == 1:
+        return nodes[0] in G
+
+    # check that all nodes in the list are in the graph, if at least one
+    # is not in the graph, then this is not a simple path
+    if not all(n in G for n in nodes):
+        return False
+
+    # If the list contains repeated nodes, then it's not a simple path
+    if len(set(nodes)) != len(nodes):
+        return False
+
+    # Test that each adjacent pair of nodes is adjacent.
+    return all(v in G[u] for u, v in pairwise(nodes))
+
+
+@nx._dispatchable
+def all_simple_paths(G, source, target, cutoff=None):
+    """Generate all simple paths in the graph G from source to target.
+
+    A simple path is a path with no repeated nodes.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    source : node
+       Starting node for path
+
+    target : nodes
+       Single node or iterable of nodes at which to end path
+
+    cutoff : integer, optional
+        Depth to stop the search. Only paths with length <= `cutoff` are returned.
+        where the mathematical "length of a path" is `len(path) -1` (number of edges).
+
+    Returns
+    -------
+    path_generator: generator
+       A generator that produces lists of simple paths.  If there are no paths
+       between the source and target within the given cutoff the generator
+       produces no output. If it is possible to traverse the same sequence of
+       nodes in multiple ways, namely through parallel edges, then it will be
+       returned multiple times (once for each viable edge combination).
+
+    Examples
+    --------
+    This iterator generates lists of nodes::
+
+        >>> G = nx.complete_graph(4)
+        >>> for path in nx.all_simple_paths(G, source=0, target=3):
+        ...     print(path)
+        ...
+        [0, 1, 2, 3]
+        [0, 1, 3]
+        [0, 2, 1, 3]
+        [0, 2, 3]
+        [0, 3]
+
+    You can generate only those paths that are shorter than a certain
+    length by using the `cutoff` keyword argument::
+
+        >>> paths = nx.all_simple_paths(G, source=0, target=3, cutoff=2)
+        >>> print(list(paths))
+        [[0, 1, 3], [0, 2, 3], [0, 3]]
+
+    To get each path as the corresponding list of edges, you can use the
+    :func:`networkx.utils.pairwise` helper function::
+
+        >>> paths = nx.all_simple_paths(G, source=0, target=3)
+        >>> for path in map(nx.utils.pairwise, paths):
+        ...     print(list(path))
+        [(0, 1), (1, 2), (2, 3)]
+        [(0, 1), (1, 3)]
+        [(0, 2), (2, 1), (1, 3)]
+        [(0, 2), (2, 3)]
+        [(0, 3)]
+
+    Pass an iterable of nodes as target to generate all paths ending in any of several nodes::
+
+        >>> G = nx.complete_graph(4)
+        >>> for path in nx.all_simple_paths(G, source=0, target=[3, 2]):
+        ...     print(path)
+        ...
+        [0, 1, 2]
+        [0, 1, 2, 3]
+        [0, 1, 3]
+        [0, 1, 3, 2]
+        [0, 2]
+        [0, 2, 1, 3]
+        [0, 2, 3]
+        [0, 3]
+        [0, 3, 1, 2]
+        [0, 3, 2]
+
+    The singleton path from ``source`` to itself is considered a simple path and is
+    included in the results:
+
+        >>> G = nx.empty_graph(5)
+        >>> list(nx.all_simple_paths(G, source=0, target=0))
+        [[0]]
+
+        >>> G = nx.path_graph(3)
+        >>> list(nx.all_simple_paths(G, source=0, target={0, 1, 2}))
+        [[0], [0, 1], [0, 1, 2]]
+
+    Iterate over each path from the root nodes to the leaf nodes in a
+    directed acyclic graph using a functional programming approach::
+
+        >>> from itertools import chain
+        >>> from itertools import product
+        >>> from itertools import starmap
+        >>> from functools import partial
+        >>>
+        >>> chaini = chain.from_iterable
+        >>>
+        >>> G = nx.DiGraph([(0, 1), (1, 2), (0, 3), (3, 2)])
+        >>> roots = (v for v, d in G.in_degree() if d == 0)
+        >>> leaves = (v for v, d in G.out_degree() if d == 0)
+        >>> all_paths = partial(nx.all_simple_paths, G)
+        >>> list(chaini(starmap(all_paths, product(roots, leaves))))
+        [[0, 1, 2], [0, 3, 2]]
+
+    The same list computed using an iterative approach::
+
+        >>> G = nx.DiGraph([(0, 1), (1, 2), (0, 3), (3, 2)])
+        >>> roots = (v for v, d in G.in_degree() if d == 0)
+        >>> leaves = (v for v, d in G.out_degree() if d == 0)
+        >>> all_paths = []
+        >>> for root in roots:
+        ...     for leaf in leaves:
+        ...         paths = nx.all_simple_paths(G, root, leaf)
+        ...         all_paths.extend(paths)
+        >>> all_paths
+        [[0, 1, 2], [0, 3, 2]]
+
+    Iterate over each path from the root nodes to the leaf nodes in a
+    directed acyclic graph passing all leaves together to avoid unnecessary
+    compute::
+
+        >>> G = nx.DiGraph([(0, 1), (2, 1), (1, 3), (1, 4)])
+        >>> roots = (v for v, d in G.in_degree() if d == 0)
+        >>> leaves = [v for v, d in G.out_degree() if d == 0]
+        >>> all_paths = []
+        >>> for root in roots:
+        ...     paths = nx.all_simple_paths(G, root, leaves)
+        ...     all_paths.extend(paths)
+        >>> all_paths
+        [[0, 1, 3], [0, 1, 4], [2, 1, 3], [2, 1, 4]]
+
+    If parallel edges offer multiple ways to traverse a given sequence of
+    nodes, this sequence of nodes will be returned multiple times:
+
+        >>> G = nx.MultiDiGraph([(0, 1), (0, 1), (1, 2)])
+        >>> list(nx.all_simple_paths(G, 0, 2))
+        [[0, 1, 2], [0, 1, 2]]
+
+    Notes
+    -----
+    This algorithm uses a modified depth-first search to generate the
+    paths [1]_.  A single path can be found in $O(V+E)$ time but the
+    number of simple paths in a graph can be very large, e.g. $O(n!)$ in
+    the complete graph of order $n$.
+
+    This function does not check that a path exists between `source` and
+    `target`. For large graphs, this may result in very long runtimes.
+    Consider using `has_path` to check that a path exists between `source` and
+    `target` before calling this function on large graphs.
+
+    References
+    ----------
+    .. [1] R. Sedgewick, "Algorithms in C, Part 5: Graph Algorithms",
+       Addison Wesley Professional, 3rd ed., 2001.
+
+    See Also
+    --------
+    all_shortest_paths, shortest_path, has_path
+
+    """
+    for edge_path in all_simple_edge_paths(G, source, target, cutoff):
+        yield [source] + [edge[1] for edge in edge_path]
+
+
+@nx._dispatchable
+def all_simple_edge_paths(G, source, target, cutoff=None):
+    """Generate lists of edges for all simple paths in G from source to target.
+
+    A simple path is a path with no repeated nodes.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    source : node
+       Starting node for path
+
+    target : nodes
+       Single node or iterable of nodes at which to end path
+
+    cutoff : integer, optional
+        Depth to stop the search. Only paths with length <= `cutoff` are returned.
+        Note that the length of an edge path is the number of edges.
+
+    Returns
+    -------
+    path_generator: generator
+       A generator that produces lists of simple paths.  If there are no paths
+       between the source and target within the given cutoff the generator
+       produces no output.
+       For multigraphs, the list of edges have elements of the form `(u,v,k)`.
+       Where `k` corresponds to the edge key.
+
+    Examples
+    --------
+
+    Print the simple path edges of a Graph::
+
+        >>> g = nx.Graph([(1, 2), (2, 4), (1, 3), (3, 4)])
+        >>> for path in sorted(nx.all_simple_edge_paths(g, 1, 4)):
+        ...     print(path)
+        [(1, 2), (2, 4)]
+        [(1, 3), (3, 4)]
+
+    Print the simple path edges of a MultiGraph. Returned edges come with
+    their associated keys::
+
+        >>> mg = nx.MultiGraph()
+        >>> mg.add_edge(1, 2, key="k0")
+        'k0'
+        >>> mg.add_edge(1, 2, key="k1")
+        'k1'
+        >>> mg.add_edge(2, 3, key="k0")
+        'k0'
+        >>> for path in sorted(nx.all_simple_edge_paths(mg, 1, 3)):
+        ...     print(path)
+        [(1, 2, 'k0'), (2, 3, 'k0')]
+        [(1, 2, 'k1'), (2, 3, 'k0')]
+
+    When ``source`` is one of the targets, the empty path starting and ending at
+    ``source`` without traversing any edge is considered a valid simple edge path
+    and is included in the results:
+
+        >>> G = nx.Graph()
+        >>> G.add_node(0)
+        >>> paths = list(nx.all_simple_edge_paths(G, 0, 0))
+        >>> for path in paths:
+        ...     print(path)
+        []
+        >>> len(paths)
+        1
+
+    You can use the `cutoff` parameter to only generate paths that are
+    shorter than a certain length:
+
+        >>> g = nx.Graph([(1, 2), (2, 3), (3, 4), (4, 5), (1, 4), (1, 5)])
+        >>> for path in sorted(nx.all_simple_edge_paths(g, 1, 5)):
+        ...     print(path)
+        [(1, 2), (2, 3), (3, 4), (4, 5)]
+        [(1, 4), (4, 5)]
+        [(1, 5)]
+        >>> for path in sorted(nx.all_simple_edge_paths(g, 1, 5, cutoff=1)):
+        ...     print(path)
+        [(1, 5)]
+        >>> for path in sorted(nx.all_simple_edge_paths(g, 1, 5, cutoff=2)):
+        ...     print(path)
+        [(1, 4), (4, 5)]
+        [(1, 5)]
+
+    Notes
+    -----
+    This algorithm uses a modified depth-first search to generate the
+    paths [1]_.  A single path can be found in $O(V+E)$ time but the
+    number of simple paths in a graph can be very large, e.g. $O(n!)$ in
+    the complete graph of order $n$.
+
+    References
+    ----------
+    .. [1] R. Sedgewick, "Algorithms in C, Part 5: Graph Algorithms",
+       Addison Wesley Professional, 3rd ed., 2001.
+
+    See Also
+    --------
+    all_shortest_paths, shortest_path, all_simple_paths
+
+    """
+    if source not in G:
+        raise nx.NodeNotFound(f"source node {source} not in graph")
+
+    if target in G:
+        targets = {target}
+    else:
+        try:
+            targets = set(target)
+        except TypeError as err:
+            raise nx.NodeNotFound(f"target node {target} not in graph") from err
+
+    cutoff = cutoff if cutoff is not None else len(G) - 1
+
+    if cutoff >= 0 and targets:
+        yield from _all_simple_edge_paths(G, source, targets, cutoff)
+
+
+def _all_simple_edge_paths(G, source, targets, cutoff):
+    # We simulate recursion with a stack, keeping the current path being explored
+    # and the outgoing edge iterators at each point in the stack.
+    # To avoid unnecessary checks, the loop is structured in a way such that a path
+    # is considered for yielding only after a new node/edge is added.
+    # We bootstrap the search by adding a dummy iterator to the stack that only yields
+    # a dummy edge to source (so that the trivial path has a chance of being included).
+
+    get_edges = (
+        (lambda node: G.edges(node, keys=True))
+        if G.is_multigraph()
+        else (lambda node: G.edges(node))
+    )
+
+    # The current_path is a dictionary that maps nodes in the path to the edge that was
+    # used to enter that node (instead of a list of edges) because we want both a fast
+    # membership test for nodes in the path and the preservation of insertion order.
+    current_path = {None: None}
+    stack = [iter([(None, source)])]
+
+    while stack:
+        # 1. Try to extend the current path.
+        next_edge = next((e for e in stack[-1] if e[1] not in current_path), None)
+        if next_edge is None:
+            # All edges of the last node in the current path have been explored.
+            stack.pop()
+            current_path.popitem()
+            continue
+        previous_node, next_node, *_ = next_edge
+
+        # 2. Check if we've reached a target.
+        if next_node in targets:
+            yield (list(current_path.values()) + [next_edge])[2:]  # remove dummy edge
+
+        # 3. Only expand the search through the next node if it makes sense.
+        if len(current_path) - 1 < cutoff and (
+            targets - current_path.keys() - {next_node}
+        ):
+            current_path[next_node] = next_edge
+            stack.append(iter(get_edges(next_node)))
+
+
+@not_implemented_for("multigraph")
+@nx._dispatchable(edge_attrs="weight")
+def shortest_simple_paths(G, source, target, weight=None):
+    """Generate all simple paths in the graph G from source to target,
+       starting from shortest ones.
+
+    A simple path is a path with no repeated nodes.
+
+    If a weighted shortest path search is to be used, no negative weights
+    are allowed.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    source : node
+       Starting node for path
+
+    target : node
+       Ending node for path
+
+    weight : string or function
+        If it is a string, it is the name of the edge attribute to be
+        used as a weight.
+
+        If it is a function, the weight of an edge is the value returned
+        by the function. The function must accept exactly three positional
+        arguments: the two endpoints of an edge and the dictionary of edge
+        attributes for that edge. The function must return a number or None.
+        The weight function can be used to hide edges by returning None.
+        So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
+        will find the shortest red path.
+
+        If None all edges are considered to have unit weight. Default
+        value None.
+
+    Returns
+    -------
+    path_generator: generator
+       A generator that produces lists of simple paths, in order from
+       shortest to longest.
+
+    Raises
+    ------
+    NetworkXNoPath
+       If no path exists between source and target.
+
+    NetworkXError
+       If source or target nodes are not in the input graph.
+
+    NetworkXNotImplemented
+       If the input graph is a Multi[Di]Graph.
+
+    Examples
+    --------
+
+    >>> G = nx.cycle_graph(7)
+    >>> paths = list(nx.shortest_simple_paths(G, 0, 3))
+    >>> print(paths)
+    [[0, 1, 2, 3], [0, 6, 5, 4, 3]]
+
+    You can use this function to efficiently compute the k shortest/best
+    paths between two nodes.
+
+    >>> from itertools import islice
+    >>> def k_shortest_paths(G, source, target, k, weight=None):
+    ...     return list(
+    ...         islice(nx.shortest_simple_paths(G, source, target, weight=weight), k)
+    ...     )
+    >>> for path in k_shortest_paths(G, 0, 3, 2):
+    ...     print(path)
+    [0, 1, 2, 3]
+    [0, 6, 5, 4, 3]
+
+    Notes
+    -----
+    This procedure is based on algorithm by Jin Y. Yen [1]_.  Finding
+    the first $K$ paths requires $O(KN^3)$ operations.
+
+    See Also
+    --------
+    all_shortest_paths
+    shortest_path
+    all_simple_paths
+
+    References
+    ----------
+    .. [1] Jin Y. Yen, "Finding the K Shortest Loopless Paths in a
+       Network", Management Science, Vol. 17, No. 11, Theory Series
+       (Jul., 1971), pp. 712-716.
+
+    """
+    if source not in G:
+        raise nx.NodeNotFound(f"source node {source} not in graph")
+
+    if target not in G:
+        raise nx.NodeNotFound(f"target node {target} not in graph")
+
+    if weight is None:
+        length_func = len
+        shortest_path_func = _bidirectional_shortest_path
+    else:
+        wt = _weight_function(G, weight)
+
+        def length_func(path):
+            return sum(
+                wt(u, v, G.get_edge_data(u, v)) for (u, v) in zip(path, path[1:])
+            )
+
+        shortest_path_func = _bidirectional_dijkstra
+
+    listA = []
+    listB = PathBuffer()
+    prev_path = None
+    while True:
+        if not prev_path:
+            length, path = shortest_path_func(G, source, target, weight=weight)
+            listB.push(length, path)
+        else:
+            ignore_nodes = set()
+            ignore_edges = set()
+            for i in range(1, len(prev_path)):
+                root = prev_path[:i]
+                root_length = length_func(root)
+                for path in listA:
+                    if path[:i] == root:
+                        ignore_edges.add((path[i - 1], path[i]))
+                try:
+                    length, spur = shortest_path_func(
+                        G,
+                        root[-1],
+                        target,
+                        ignore_nodes=ignore_nodes,
+                        ignore_edges=ignore_edges,
+                        weight=weight,
+                    )
+                    path = root[:-1] + spur
+                    listB.push(root_length + length, path)
+                except nx.NetworkXNoPath:
+                    pass
+                ignore_nodes.add(root[-1])
+
+        if listB:
+            path = listB.pop()
+            yield path
+            listA.append(path)
+            prev_path = path
+        else:
+            break
+
+
+class PathBuffer:
+    def __init__(self):
+        self.paths = set()
+        self.sortedpaths = []
+        self.counter = count()
+
+    def __len__(self):
+        return len(self.sortedpaths)
+
+    def push(self, cost, path):
+        hashable_path = tuple(path)
+        if hashable_path not in self.paths:
+            heappush(self.sortedpaths, (cost, next(self.counter), path))
+            self.paths.add(hashable_path)
+
+    def pop(self):
+        (cost, num, path) = heappop(self.sortedpaths)
+        hashable_path = tuple(path)
+        self.paths.remove(hashable_path)
+        return path
+
+
+def _bidirectional_shortest_path(
+    G, source, target, ignore_nodes=None, ignore_edges=None, weight=None
+):
+    """Returns the shortest path between source and target ignoring
+       nodes and edges in the containers ignore_nodes and ignore_edges.
+
+    This is a custom modification of the standard bidirectional shortest
+    path implementation at networkx.algorithms.unweighted
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    source : node
+       starting node for path
+
+    target : node
+       ending node for path
+
+    ignore_nodes : container of nodes
+       nodes to ignore, optional
+
+    ignore_edges : container of edges
+       edges to ignore, optional
+
+    weight : None
+       This function accepts a weight argument for convenience of
+       shortest_simple_paths function. It will be ignored.
+
+    Returns
+    -------
+    path: list
+       List of nodes in a path from source to target.
+
+    Raises
+    ------
+    NetworkXNoPath
+       If no path exists between source and target.
+
+    See Also
+    --------
+    shortest_path
+
+    """
+    # call helper to do the real work
+    results = _bidirectional_pred_succ(G, source, target, ignore_nodes, ignore_edges)
+    pred, succ, w = results
+
+    # build path from pred+w+succ
+    path = []
+    # from w to target
+    while w is not None:
+        path.append(w)
+        w = succ[w]
+    # from source to w
+    w = pred[path[0]]
+    while w is not None:
+        path.insert(0, w)
+        w = pred[w]
+
+    return len(path), path
+
+
+def _bidirectional_pred_succ(G, source, target, ignore_nodes=None, ignore_edges=None):
+    """Bidirectional shortest path helper.
+    Returns (pred,succ,w) where
+    pred is a dictionary of predecessors from w to the source, and
+    succ is a dictionary of successors from w to the target.
+    """
+    # does BFS from both source and target and meets in the middle
+    if ignore_nodes and (source in ignore_nodes or target in ignore_nodes):
+        raise nx.NetworkXNoPath(f"No path between {source} and {target}.")
+    if target == source:
+        return ({target: None}, {source: None}, source)
+
+    # handle either directed or undirected
+    if G.is_directed():
+        Gpred = G.predecessors
+        Gsucc = G.successors
+    else:
+        Gpred = G.neighbors
+        Gsucc = G.neighbors
+
+    # support optional nodes filter
+    if ignore_nodes:
+
+        def filter_iter(nodes):
+            def iterate(v):
+                for w in nodes(v):
+                    if w not in ignore_nodes:
+                        yield w
+
+            return iterate
+
+        Gpred = filter_iter(Gpred)
+        Gsucc = filter_iter(Gsucc)
+
+    # support optional edges filter
+    if ignore_edges:
+        if G.is_directed():
+
+            def filter_pred_iter(pred_iter):
+                def iterate(v):
+                    for w in pred_iter(v):
+                        if (w, v) not in ignore_edges:
+                            yield w
+
+                return iterate
+
+            def filter_succ_iter(succ_iter):
+                def iterate(v):
+                    for w in succ_iter(v):
+                        if (v, w) not in ignore_edges:
+                            yield w
+
+                return iterate
+
+            Gpred = filter_pred_iter(Gpred)
+            Gsucc = filter_succ_iter(Gsucc)
+
+        else:
+
+            def filter_iter(nodes):
+                def iterate(v):
+                    for w in nodes(v):
+                        if (v, w) not in ignore_edges and (w, v) not in ignore_edges:
+                            yield w
+
+                return iterate
+
+            Gpred = filter_iter(Gpred)
+            Gsucc = filter_iter(Gsucc)
+
+    # predecessor and successors in search
+    pred = {source: None}
+    succ = {target: None}
+
+    # initialize fringes, start with forward
+    forward_fringe = [source]
+    reverse_fringe = [target]
+
+    while forward_fringe and reverse_fringe:
+        if len(forward_fringe) <= len(reverse_fringe):
+            this_level = forward_fringe
+            forward_fringe = []
+            for v in this_level:
+                for w in Gsucc(v):
+                    if w not in pred:
+                        forward_fringe.append(w)
+                        pred[w] = v
+                    if w in succ:
+                        # found path
+                        return pred, succ, w
+        else:
+            this_level = reverse_fringe
+            reverse_fringe = []
+            for v in this_level:
+                for w in Gpred(v):
+                    if w not in succ:
+                        succ[w] = v
+                        reverse_fringe.append(w)
+                    if w in pred:
+                        # found path
+                        return pred, succ, w
+
+    raise nx.NetworkXNoPath(f"No path between {source} and {target}.")
+
+
+def _bidirectional_dijkstra(
+    G, source, target, weight="weight", ignore_nodes=None, ignore_edges=None
+):
+    """Dijkstra's algorithm for shortest paths using bidirectional search.
+
+    This function returns the shortest path between source and target
+    ignoring nodes and edges in the containers ignore_nodes and
+    ignore_edges.
+
+    This is a custom modification of the standard Dijkstra bidirectional
+    shortest path implementation at networkx.algorithms.weighted
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    source : node
+        Starting node.
+
+    target : node
+        Ending node.
+
+    weight: string, function, optional (default='weight')
+        Edge data key or weight function corresponding to the edge weight
+        If this is a function, the weight of an edge is the value
+        returned by the function. The function must accept exactly three
+        positional arguments: the two endpoints of an edge and the
+        dictionary of edge attributes for that edge. The function must
+        return a number or None to indicate a hidden edge.
+
+    ignore_nodes : container of nodes
+        nodes to ignore, optional
+
+    ignore_edges : container of edges
+        edges to ignore, optional
+
+    Returns
+    -------
+    length : number
+        Shortest path length.
+
+    Returns a tuple of two dictionaries keyed by node.
+    The first dictionary stores distance from the source.
+    The second stores the path from the source to that node.
+
+    Raises
+    ------
+    NetworkXNoPath
+        If no path exists between source and target.
+
+    Notes
+    -----
+    Edge weight attributes must be numerical.
+    Distances are calculated as sums of weighted edges traversed.
+
+    The weight function can be used to hide edges by returning None.
+    So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
+    will find the shortest red path.
+
+    In practice  bidirectional Dijkstra is much more than twice as fast as
+    ordinary Dijkstra.
+
+    Ordinary Dijkstra expands nodes in a sphere-like manner from the
+    source. The radius of this sphere will eventually be the length
+    of the shortest path. Bidirectional Dijkstra will expand nodes
+    from both the source and the target, making two spheres of half
+    this radius. Volume of the first sphere is pi*r*r while the
+    others are 2*pi*r/2*r/2, making up half the volume.
+
+    This algorithm is not guaranteed to work if edge weights
+    are negative or are floating point numbers
+    (overflows and roundoff errors can cause problems).
+
+    See Also
+    --------
+    shortest_path
+    shortest_path_length
+    """
+    if ignore_nodes and (source in ignore_nodes or target in ignore_nodes):
+        raise nx.NetworkXNoPath(f"No path between {source} and {target}.")
+    if source == target:
+        if source not in G:
+            raise nx.NodeNotFound(f"Node {source} not in graph")
+        return (0, [source])
+
+    # handle either directed or undirected
+    if G.is_directed():
+        Gpred = G.predecessors
+        Gsucc = G.successors
+    else:
+        Gpred = G.neighbors
+        Gsucc = G.neighbors
+
+    # support optional nodes filter
+    if ignore_nodes:
+
+        def filter_iter(nodes):
+            def iterate(v):
+                for w in nodes(v):
+                    if w not in ignore_nodes:
+                        yield w
+
+            return iterate
+
+        Gpred = filter_iter(Gpred)
+        Gsucc = filter_iter(Gsucc)
+
+    # support optional edges filter
+    if ignore_edges:
+        if G.is_directed():
+
+            def filter_pred_iter(pred_iter):
+                def iterate(v):
+                    for w in pred_iter(v):
+                        if (w, v) not in ignore_edges:
+                            yield w
+
+                return iterate
+
+            def filter_succ_iter(succ_iter):
+                def iterate(v):
+                    for w in succ_iter(v):
+                        if (v, w) not in ignore_edges:
+                            yield w
+
+                return iterate
+
+            Gpred = filter_pred_iter(Gpred)
+            Gsucc = filter_succ_iter(Gsucc)
+
+        else:
+
+            def filter_iter(nodes):
+                def iterate(v):
+                    for w in nodes(v):
+                        if (v, w) not in ignore_edges and (w, v) not in ignore_edges:
+                            yield w
+
+                return iterate
+
+            Gpred = filter_iter(Gpred)
+            Gsucc = filter_iter(Gsucc)
+
+    wt = _weight_function(G, weight)
+    # Init:   Forward             Backward
+    dists = [{}, {}]  # dictionary of final distances
+    paths = [{source: [source]}, {target: [target]}]  # dictionary of paths
+    fringe = [[], []]  # heap of (distance, node) tuples for
+    # extracting next node to expand
+    seen = [{source: 0}, {target: 0}]  # dictionary of distances to
+    # nodes seen
+    c = count()
+    # initialize fringe heap
+    heappush(fringe[0], (0, next(c), source))
+    heappush(fringe[1], (0, next(c), target))
+    # neighs for extracting correct neighbor information
+    neighs = [Gsucc, Gpred]
+    # variables to hold shortest discovered path
+    # finaldist = 1e30000
+    finalpath = []
+    dir = 1
+    while fringe[0] and fringe[1]:
+        # choose direction
+        # dir == 0 is forward direction and dir == 1 is back
+        dir = 1 - dir
+        # extract closest to expand
+        (dist, _, v) = heappop(fringe[dir])
+        if v in dists[dir]:
+            # Shortest path to v has already been found
+            continue
+        # update distance
+        dists[dir][v] = dist  # equal to seen[dir][v]
+        if v in dists[1 - dir]:
+            # if we have scanned v in both directions we are done
+            # we have now discovered the shortest path
+            return (finaldist, finalpath)
+
+        for w in neighs[dir](v):
+            if dir == 0:  # forward
+                minweight = wt(v, w, G.get_edge_data(v, w))
+            else:  # back, must remember to change v,w->w,v
+                minweight = wt(w, v, G.get_edge_data(w, v))
+            if minweight is None:
+                continue
+            vwLength = dists[dir][v] + minweight
+
+            if w in dists[dir]:
+                if vwLength < dists[dir][w]:
+                    raise ValueError("Contradictory paths found: negative weights?")
+            elif w not in seen[dir] or vwLength < seen[dir][w]:
+                # relaxing
+                seen[dir][w] = vwLength
+                heappush(fringe[dir], (vwLength, next(c), w))
+                paths[dir][w] = paths[dir][v] + [w]
+                if w in seen[0] and w in seen[1]:
+                    # see if this path is better than the already
+                    # discovered shortest path
+                    totaldist = seen[0][w] + seen[1][w]
+                    if finalpath == [] or finaldist > totaldist:
+                        finaldist = totaldist
+                        revpath = paths[1][w][:]
+                        revpath.reverse()
+                        finalpath = paths[0][w] + revpath[1:]
+    raise nx.NetworkXNoPath(f"No path between {source} and {target}.")
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/smallworld.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/smallworld.py
new file mode 100644
index 0000000000000000000000000000000000000000..456a4ca11c0aa19d1d770bf90e5713ce80e270d8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/smallworld.py
@@ -0,0 +1,404 @@
+"""Functions for estimating the small-world-ness of graphs.
+
+A small world network is characterized by a small average shortest path length,
+and a large clustering coefficient.
+
+Small-worldness is commonly measured with the coefficient sigma or omega.
+
+Both coefficients compare the average clustering coefficient and shortest path
+length of a given graph against the same quantities for an equivalent random
+or lattice graph.
+
+For more information, see the Wikipedia article on small-world network [1]_.
+
+.. [1] Small-world network:: https://en.wikipedia.org/wiki/Small-world_network
+
+"""
+
+import networkx as nx
+from networkx.utils import not_implemented_for, py_random_state
+
+__all__ = ["random_reference", "lattice_reference", "sigma", "omega"]
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@py_random_state(3)
+@nx._dispatchable(returns_graph=True)
+def random_reference(G, niter=1, connectivity=True, seed=None):
+    """Compute a random graph by swapping edges of a given graph.
+
+    Parameters
+    ----------
+    G : graph
+        An undirected graph with 4 or more nodes.
+
+    niter : integer (optional, default=1)
+        An edge is rewired approximately `niter` times.
+
+    connectivity : boolean (optional, default=True)
+        When True, ensure connectivity for the randomized graph.
+
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    G : graph
+        The randomized graph.
+
+    Raises
+    ------
+    NetworkXError
+        If there are fewer than 4 nodes or 2 edges in `G`
+
+    Notes
+    -----
+    The implementation is adapted from the algorithm by Maslov and Sneppen
+    (2002) [1]_.
+
+    References
+    ----------
+    .. [1] Maslov, Sergei, and Kim Sneppen.
+           "Specificity and stability in topology of protein networks."
+           Science 296.5569 (2002): 910-913.
+    """
+    if len(G) < 4:
+        raise nx.NetworkXError("Graph has fewer than four nodes.")
+    if len(G.edges) < 2:
+        raise nx.NetworkXError("Graph has fewer that 2 edges")
+
+    from networkx.utils import cumulative_distribution, discrete_sequence
+
+    local_conn = nx.connectivity.local_edge_connectivity
+
+    G = G.copy()
+    keys, degrees = zip(*G.degree())  # keys, degree
+    cdf = cumulative_distribution(degrees)  # cdf of degree
+    nnodes = len(G)
+    nedges = nx.number_of_edges(G)
+    niter = niter * nedges
+    ntries = int(nnodes * nedges / (nnodes * (nnodes - 1) / 2))
+    swapcount = 0
+
+    for i in range(niter):
+        n = 0
+        while n < ntries:
+            # pick two random edges without creating edge list
+            # choose source node indices from discrete distribution
+            (ai, ci) = discrete_sequence(2, cdistribution=cdf, seed=seed)
+            if ai == ci:
+                continue  # same source, skip
+            a = keys[ai]  # convert index to label
+            c = keys[ci]
+            # choose target uniformly from neighbors
+            b = seed.choice(list(G.neighbors(a)))
+            d = seed.choice(list(G.neighbors(c)))
+            if b in [a, c, d] or d in [a, b, c]:
+                continue  # all vertices should be different
+
+            # don't create parallel edges
+            if (d not in G[a]) and (b not in G[c]):
+                G.add_edge(a, d)
+                G.add_edge(c, b)
+                G.remove_edge(a, b)
+                G.remove_edge(c, d)
+
+                # Check if the graph is still connected
+                if connectivity and local_conn(G, a, b) == 0:
+                    # Not connected, revert the swap
+                    G.remove_edge(a, d)
+                    G.remove_edge(c, b)
+                    G.add_edge(a, b)
+                    G.add_edge(c, d)
+                else:
+                    swapcount += 1
+                    break
+            n += 1
+    return G
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@py_random_state(4)
+@nx._dispatchable(returns_graph=True)
+def lattice_reference(G, niter=5, D=None, connectivity=True, seed=None):
+    """Latticize the given graph by swapping edges.
+
+    Parameters
+    ----------
+    G : graph
+        An undirected graph.
+
+    niter : integer (optional, default=1)
+        An edge is rewired approximately niter times.
+
+    D : numpy.array (optional, default=None)
+        Distance to the diagonal matrix.
+
+    connectivity : boolean (optional, default=True)
+        Ensure connectivity for the latticized graph when set to True.
+
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    G : graph
+        The latticized graph.
+
+    Raises
+    ------
+    NetworkXError
+        If there are fewer than 4 nodes or 2 edges in `G`
+
+    Notes
+    -----
+    The implementation is adapted from the algorithm by Sporns et al. [1]_.
+    which is inspired from the original work by Maslov and Sneppen(2002) [2]_.
+
+    References
+    ----------
+    .. [1] Sporns, Olaf, and Jonathan D. Zwi.
+       "The small world of the cerebral cortex."
+       Neuroinformatics 2.2 (2004): 145-162.
+    .. [2] Maslov, Sergei, and Kim Sneppen.
+       "Specificity and stability in topology of protein networks."
+       Science 296.5569 (2002): 910-913.
+    """
+    import numpy as np
+
+    from networkx.utils import cumulative_distribution, discrete_sequence
+
+    local_conn = nx.connectivity.local_edge_connectivity
+
+    if len(G) < 4:
+        raise nx.NetworkXError("Graph has fewer than four nodes.")
+    if len(G.edges) < 2:
+        raise nx.NetworkXError("Graph has fewer that 2 edges")
+    # Instead of choosing uniformly at random from a generated edge list,
+    # this algorithm chooses nonuniformly from the set of nodes with
+    # probability weighted by degree.
+    G = G.copy()
+    keys, degrees = zip(*G.degree())  # keys, degree
+    cdf = cumulative_distribution(degrees)  # cdf of degree
+
+    nnodes = len(G)
+    nedges = nx.number_of_edges(G)
+    if D is None:
+        D = np.zeros((nnodes, nnodes))
+        un = np.arange(1, nnodes)
+        um = np.arange(nnodes - 1, 0, -1)
+        u = np.append((0,), np.where(un < um, un, um))
+
+        for v in range(int(np.ceil(nnodes / 2))):
+            D[nnodes - v - 1, :] = np.append(u[v + 1 :], u[: v + 1])
+            D[v, :] = D[nnodes - v - 1, :][::-1]
+
+    niter = niter * nedges
+    # maximal number of rewiring attempts per 'niter'
+    max_attempts = int(nnodes * nedges / (nnodes * (nnodes - 1) / 2))
+
+    for _ in range(niter):
+        n = 0
+        while n < max_attempts:
+            # pick two random edges without creating edge list
+            # choose source node indices from discrete distribution
+            (ai, ci) = discrete_sequence(2, cdistribution=cdf, seed=seed)
+            if ai == ci:
+                continue  # same source, skip
+            a = keys[ai]  # convert index to label
+            c = keys[ci]
+            # choose target uniformly from neighbors
+            b = seed.choice(list(G.neighbors(a)))
+            d = seed.choice(list(G.neighbors(c)))
+            bi = keys.index(b)
+            di = keys.index(d)
+
+            if b in [a, c, d] or d in [a, b, c]:
+                continue  # all vertices should be different
+
+            # don't create parallel edges
+            if (d not in G[a]) and (b not in G[c]):
+                if D[ai, bi] + D[ci, di] >= D[ai, ci] + D[bi, di]:
+                    # only swap if we get closer to the diagonal
+                    G.add_edge(a, d)
+                    G.add_edge(c, b)
+                    G.remove_edge(a, b)
+                    G.remove_edge(c, d)
+
+                    # Check if the graph is still connected
+                    if connectivity and local_conn(G, a, b) == 0:
+                        # Not connected, revert the swap
+                        G.remove_edge(a, d)
+                        G.remove_edge(c, b)
+                        G.add_edge(a, b)
+                        G.add_edge(c, d)
+                    else:
+                        break
+            n += 1
+
+    return G
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@py_random_state(3)
+@nx._dispatchable
+def sigma(G, niter=100, nrand=10, seed=None):
+    """Returns the small-world coefficient (sigma) of the given graph.
+
+    The small-world coefficient is defined as:
+    sigma = C/Cr / L/Lr
+    where C and L are respectively the average clustering coefficient and
+    average shortest path length of G. Cr and Lr are respectively the average
+    clustering coefficient and average shortest path length of an equivalent
+    random graph.
+
+    A graph is commonly classified as small-world if sigma>1.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        An undirected graph.
+    niter : integer (optional, default=100)
+        Approximate number of rewiring per edge to compute the equivalent
+        random graph.
+    nrand : integer (optional, default=10)
+        Number of random graphs generated to compute the average clustering
+        coefficient (Cr) and average shortest path length (Lr).
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    sigma : float
+        The small-world coefficient of G.
+
+    Notes
+    -----
+    The implementation is adapted from Humphries et al. [1]_ [2]_.
+
+    References
+    ----------
+    .. [1] The brainstem reticular formation is a small-world, not scale-free,
+           network M. D. Humphries, K. Gurney and T. J. Prescott,
+           Proc. Roy. Soc. B 2006 273, 503-511, doi:10.1098/rspb.2005.3354.
+    .. [2] Humphries and Gurney (2008).
+           "Network 'Small-World-Ness': A Quantitative Method for Determining
+           Canonical Network Equivalence".
+           PLoS One. 3 (4). PMID 18446219. doi:10.1371/journal.pone.0002051.
+    """
+    import numpy as np
+
+    # Compute the mean clustering coefficient and average shortest path length
+    # for an equivalent random graph
+    randMetrics = {"C": [], "L": []}
+    for i in range(nrand):
+        Gr = random_reference(G, niter=niter, seed=seed)
+        randMetrics["C"].append(nx.transitivity(Gr))
+        randMetrics["L"].append(nx.average_shortest_path_length(Gr))
+
+    C = nx.transitivity(G)
+    L = nx.average_shortest_path_length(G)
+    Cr = np.mean(randMetrics["C"])
+    Lr = np.mean(randMetrics["L"])
+
+    sigma = (C / Cr) / (L / Lr)
+
+    return float(sigma)
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@py_random_state(3)
+@nx._dispatchable
+def omega(G, niter=5, nrand=10, seed=None):
+    """Returns the small-world coefficient (omega) of a graph
+
+    The small-world coefficient of a graph G is:
+
+    omega = Lr/L - C/Cl
+
+    where C and L are respectively the average clustering coefficient and
+    average shortest path length of G. Lr is the average shortest path length
+    of an equivalent random graph and Cl is the average clustering coefficient
+    of an equivalent lattice graph.
+
+    The small-world coefficient (omega) measures how much G is like a lattice
+    or a random graph. Negative values mean G is similar to a lattice whereas
+    positive values mean G is a random graph.
+    Values close to 0 mean that G has small-world characteristics.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        An undirected graph.
+
+    niter: integer (optional, default=5)
+        Approximate number of rewiring per edge to compute the equivalent
+        random graph.
+
+    nrand: integer (optional, default=10)
+        Number of random graphs generated to compute the maximal clustering
+        coefficient (Cr) and average shortest path length (Lr).
+
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+
+    Returns
+    -------
+    omega : float
+        The small-world coefficient (omega)
+
+    Notes
+    -----
+    The implementation is adapted from the algorithm by Telesford et al. [1]_.
+
+    References
+    ----------
+    .. [1] Telesford, Joyce, Hayasaka, Burdette, and Laurienti (2011).
+           "The Ubiquity of Small-World Networks".
+           Brain Connectivity. 1 (0038): 367-75.  PMC 3604768. PMID 22432451.
+           doi:10.1089/brain.2011.0038.
+    """
+    import numpy as np
+
+    # Compute the mean clustering coefficient and average shortest path length
+    # for an equivalent random graph
+    randMetrics = {"C": [], "L": []}
+
+    # Calculate initial average clustering coefficient which potentially will
+    # get replaced by higher clustering coefficients from generated lattice
+    # reference graphs
+    Cl = nx.average_clustering(G)
+
+    niter_lattice_reference = niter
+    niter_random_reference = niter * 2
+
+    for _ in range(nrand):
+        # Generate random graph
+        Gr = random_reference(G, niter=niter_random_reference, seed=seed)
+        randMetrics["L"].append(nx.average_shortest_path_length(Gr))
+
+        # Generate lattice graph
+        Gl = lattice_reference(G, niter=niter_lattice_reference, seed=seed)
+
+        # Replace old clustering coefficient, if clustering is higher in
+        # generated lattice reference
+        Cl_temp = nx.average_clustering(Gl)
+        if Cl_temp > Cl:
+            Cl = Cl_temp
+
+    C = nx.average_clustering(G)
+    L = nx.average_shortest_path_length(G)
+    Lr = np.mean(randMetrics["L"])
+
+    omega = (Lr / L) - (C / Cl)
+
+    return float(omega)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/smetric.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/smetric.py
new file mode 100644
index 0000000000000000000000000000000000000000..d985aa805b4fb21300680afe389aae4732793a73
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/smetric.py
@@ -0,0 +1,30 @@
+import networkx as nx
+
+__all__ = ["s_metric"]
+
+
+@nx._dispatchable
+def s_metric(G):
+    """Returns the s-metric [1]_ of graph.
+
+    The s-metric is defined as the sum of the products ``deg(u) * deg(v)``
+    for every edge ``(u, v)`` in `G`.
+
+    Parameters
+    ----------
+    G : graph
+        The graph used to compute the s-metric.
+
+    Returns
+    -------
+    s : float
+        The s-metric of the graph.
+
+    References
+    ----------
+    .. [1] Lun Li, David Alderson, John C. Doyle, and Walter Willinger,
+           Towards a Theory of Scale-Free Graphs:
+           Definition, Properties, and  Implications (Extended Version), 2005.
+           https://arxiv.org/abs/cond-mat/0501169
+    """
+    return float(sum(G.degree(u) * G.degree(v) for (u, v) in G.edges()))
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/sparsifiers.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/sparsifiers.py
new file mode 100644
index 0000000000000000000000000000000000000000..59322372e6c1e06d595d8dff0f8680d1daa8a99e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/sparsifiers.py
@@ -0,0 +1,296 @@
+"""Functions for computing sparsifiers of graphs."""
+
+import math
+
+import networkx as nx
+from networkx.utils import not_implemented_for, py_random_state
+
+__all__ = ["spanner"]
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@py_random_state(3)
+@nx._dispatchable(edge_attrs="weight", returns_graph=True)
+def spanner(G, stretch, weight=None, seed=None):
+    """Returns a spanner of the given graph with the given stretch.
+
+    A spanner of a graph G = (V, E) with stretch t is a subgraph
+    H = (V, E_S) such that E_S is a subset of E and the distance between
+    any pair of nodes in H is at most t times the distance between the
+    nodes in G.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        An undirected simple graph.
+
+    stretch : float
+        The stretch of the spanner.
+
+    weight : object
+        The edge attribute to use as distance.
+
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    NetworkX graph
+        A spanner of the given graph with the given stretch.
+
+    Raises
+    ------
+    ValueError
+        If a stretch less than 1 is given.
+
+    Notes
+    -----
+    This function implements the spanner algorithm by Baswana and Sen,
+    see [1].
+
+    This algorithm is a randomized las vegas algorithm: The expected
+    running time is O(km) where k = (stretch + 1) // 2 and m is the
+    number of edges in G. The returned graph is always a spanner of the
+    given graph with the specified stretch. For weighted graphs the
+    number of edges in the spanner is O(k * n^(1 + 1 / k)) where k is
+    defined as above and n is the number of nodes in G. For unweighted
+    graphs the number of edges is O(n^(1 + 1 / k) + kn).
+
+    References
+    ----------
+    [1] S. Baswana, S. Sen. A Simple and Linear Time Randomized
+    Algorithm for Computing Sparse Spanners in Weighted Graphs.
+    Random Struct. Algorithms 30(4): 532-563 (2007).
+    """
+    if stretch < 1:
+        raise ValueError("stretch must be at least 1")
+
+    k = (stretch + 1) // 2
+
+    # initialize spanner H with empty edge set
+    H = nx.empty_graph()
+    H.add_nodes_from(G.nodes)
+
+    # phase 1: forming the clusters
+    # the residual graph has V' from the paper as its node set
+    # and E' from the paper as its edge set
+    residual_graph = _setup_residual_graph(G, weight)
+    # clustering is a dictionary that maps nodes in a cluster to the
+    # cluster center
+    clustering = {v: v for v in G.nodes}
+    sample_prob = math.pow(G.number_of_nodes(), -1 / k)
+    size_limit = 2 * math.pow(G.number_of_nodes(), 1 + 1 / k)
+
+    i = 0
+    while i < k - 1:
+        # step 1: sample centers
+        sampled_centers = set()
+        for center in set(clustering.values()):
+            if seed.random() < sample_prob:
+                sampled_centers.add(center)
+
+        # combined loop for steps 2 and 3
+        edges_to_add = set()
+        edges_to_remove = set()
+        new_clustering = {}
+        for v in residual_graph.nodes:
+            if clustering[v] in sampled_centers:
+                continue
+
+            # step 2: find neighboring (sampled) clusters and
+            # lightest edges to them
+            lightest_edge_neighbor, lightest_edge_weight = _lightest_edge_dicts(
+                residual_graph, clustering, v
+            )
+            neighboring_sampled_centers = (
+                set(lightest_edge_weight.keys()) & sampled_centers
+            )
+
+            # step 3: add edges to spanner
+            if not neighboring_sampled_centers:
+                # connect to each neighboring center via lightest edge
+                for neighbor in lightest_edge_neighbor.values():
+                    edges_to_add.add((v, neighbor))
+                # remove all incident edges
+                for neighbor in residual_graph.adj[v]:
+                    edges_to_remove.add((v, neighbor))
+
+            else:  # there is a neighboring sampled center
+                closest_center = min(
+                    neighboring_sampled_centers, key=lightest_edge_weight.get
+                )
+                closest_center_weight = lightest_edge_weight[closest_center]
+                closest_center_neighbor = lightest_edge_neighbor[closest_center]
+
+                edges_to_add.add((v, closest_center_neighbor))
+                new_clustering[v] = closest_center
+
+                # connect to centers with edge weight less than
+                # closest_center_weight
+                for center, edge_weight in lightest_edge_weight.items():
+                    if edge_weight < closest_center_weight:
+                        neighbor = lightest_edge_neighbor[center]
+                        edges_to_add.add((v, neighbor))
+
+                # remove edges to centers with edge weight less than
+                # closest_center_weight
+                for neighbor in residual_graph.adj[v]:
+                    nbr_cluster = clustering[neighbor]
+                    nbr_weight = lightest_edge_weight[nbr_cluster]
+                    if (
+                        nbr_cluster == closest_center
+                        or nbr_weight < closest_center_weight
+                    ):
+                        edges_to_remove.add((v, neighbor))
+
+        # check whether iteration added too many edges to spanner,
+        # if so repeat
+        if len(edges_to_add) > size_limit:
+            # an iteration is repeated O(1) times on expectation
+            continue
+
+        # iteration succeeded
+        i = i + 1
+
+        # actually add edges to spanner
+        for u, v in edges_to_add:
+            _add_edge_to_spanner(H, residual_graph, u, v, weight)
+
+        # actually delete edges from residual graph
+        residual_graph.remove_edges_from(edges_to_remove)
+
+        # copy old clustering data to new_clustering
+        for node, center in clustering.items():
+            if center in sampled_centers:
+                new_clustering[node] = center
+        clustering = new_clustering
+
+        # step 4: remove intra-cluster edges
+        for u in residual_graph.nodes:
+            for v in list(residual_graph.adj[u]):
+                if clustering[u] == clustering[v]:
+                    residual_graph.remove_edge(u, v)
+
+        # update residual graph node set
+        for v in list(residual_graph.nodes):
+            if v not in clustering:
+                residual_graph.remove_node(v)
+
+    # phase 2: vertex-cluster joining
+    for v in residual_graph.nodes:
+        lightest_edge_neighbor, _ = _lightest_edge_dicts(residual_graph, clustering, v)
+        for neighbor in lightest_edge_neighbor.values():
+            _add_edge_to_spanner(H, residual_graph, v, neighbor, weight)
+
+    return H
+
+
+def _setup_residual_graph(G, weight):
+    """Setup residual graph as a copy of G with unique edges weights.
+
+    The node set of the residual graph corresponds to the set V' from
+    the Baswana-Sen paper and the edge set corresponds to the set E'
+    from the paper.
+
+    This function associates distinct weights to the edges of the
+    residual graph (even for unweighted input graphs), as required by
+    the algorithm.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        An undirected simple graph.
+
+    weight : object
+        The edge attribute to use as distance.
+
+    Returns
+    -------
+    NetworkX graph
+        The residual graph used for the Baswana-Sen algorithm.
+    """
+    residual_graph = G.copy()
+
+    # establish unique edge weights, even for unweighted graphs
+    for u, v in G.edges():
+        if not weight:
+            residual_graph[u][v]["weight"] = (id(u), id(v))
+        else:
+            residual_graph[u][v]["weight"] = (G[u][v][weight], id(u), id(v))
+
+    return residual_graph
+
+
+def _lightest_edge_dicts(residual_graph, clustering, node):
+    """Find the lightest edge to each cluster.
+
+    Searches for the minimum-weight edge to each cluster adjacent to
+    the given node.
+
+    Parameters
+    ----------
+    residual_graph : NetworkX graph
+        The residual graph used by the Baswana-Sen algorithm.
+
+    clustering : dictionary
+        The current clustering of the nodes.
+
+    node : node
+        The node from which the search originates.
+
+    Returns
+    -------
+    lightest_edge_neighbor, lightest_edge_weight : dictionary, dictionary
+        lightest_edge_neighbor is a dictionary that maps a center C to
+        a node v in the corresponding cluster such that the edge from
+        the given node to v is the lightest edge from the given node to
+        any node in cluster. lightest_edge_weight maps a center C to the
+        weight of the aforementioned edge.
+
+    Notes
+    -----
+    If a cluster has no node that is adjacent to the given node in the
+    residual graph then the center of the cluster is not a key in the
+    returned dictionaries.
+    """
+    lightest_edge_neighbor = {}
+    lightest_edge_weight = {}
+    for neighbor in residual_graph.adj[node]:
+        nbr_center = clustering[neighbor]
+        weight = residual_graph[node][neighbor]["weight"]
+        if (
+            nbr_center not in lightest_edge_weight
+            or weight < lightest_edge_weight[nbr_center]
+        ):
+            lightest_edge_neighbor[nbr_center] = neighbor
+            lightest_edge_weight[nbr_center] = weight
+    return lightest_edge_neighbor, lightest_edge_weight
+
+
+def _add_edge_to_spanner(H, residual_graph, u, v, weight):
+    """Add the edge {u, v} to the spanner H and take weight from
+    the residual graph.
+
+    Parameters
+    ----------
+    H : NetworkX graph
+        The spanner under construction.
+
+    residual_graph : NetworkX graph
+        The residual graph used by the Baswana-Sen algorithm. The weight
+        for the edge is taken from this graph.
+
+    u : node
+        One endpoint of the edge.
+
+    v : node
+        The other endpoint of the edge.
+
+    weight : object
+        The edge attribute to use as distance.
+    """
+    H.add_edge(u, v)
+    if weight:
+        H[u][v][weight] = residual_graph[u][v]["weight"][0]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/structuralholes.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/structuralholes.py
new file mode 100644
index 0000000000000000000000000000000000000000..f43c58c5fd91f13ec10c5adba9c20decb26b708b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/structuralholes.py
@@ -0,0 +1,374 @@
+"""Functions for computing measures of structural holes."""
+
+import networkx as nx
+
+__all__ = ["constraint", "local_constraint", "effective_size"]
+
+
+@nx._dispatchable(edge_attrs="weight")
+def mutual_weight(G, u, v, weight=None):
+    """Returns the sum of the weights of the edge from `u` to `v` and
+    the edge from `v` to `u` in `G`.
+
+    `weight` is the edge data key that represents the edge weight. If
+    the specified key is `None` or is not in the edge data for an edge,
+    that edge is assumed to have weight 1.
+
+    Pre-conditions: `u` and `v` must both be in `G`.
+
+    """
+    try:
+        a_uv = G[u][v].get(weight, 1)
+    except KeyError:
+        a_uv = 0
+    try:
+        a_vu = G[v][u].get(weight, 1)
+    except KeyError:
+        a_vu = 0
+    return a_uv + a_vu
+
+
+@nx._dispatchable(edge_attrs="weight")
+def normalized_mutual_weight(G, u, v, norm=sum, weight=None):
+    """Returns normalized mutual weight of the edges from `u` to `v`
+    with respect to the mutual weights of the neighbors of `u` in `G`.
+
+    `norm` specifies how the normalization factor is computed. It must
+    be a function that takes a single argument and returns a number.
+    The argument will be an iterable of mutual weights
+    of pairs ``(u, w)``, where ``w`` ranges over each (in- and
+    out-)neighbor of ``u``. Commons values for `normalization` are
+    ``sum`` and ``max``.
+
+    `weight` can be ``None`` or a string, if None, all edge weights
+    are considered equal. Otherwise holds the name of the edge
+    attribute used as weight.
+
+    """
+    scale = norm(mutual_weight(G, u, w, weight) for w in set(nx.all_neighbors(G, u)))
+    return 0 if scale == 0 else mutual_weight(G, u, v, weight) / scale
+
+
+@nx._dispatchable(edge_attrs="weight")
+def effective_size(G, nodes=None, weight=None):
+    r"""Returns the effective size of all nodes in the graph ``G``.
+
+    The *effective size* of a node's ego network is based on the concept
+    of redundancy. A person's ego network has redundancy to the extent
+    that her contacts are connected to each other as well. The
+    nonredundant part of a person's relationships is the effective
+    size of her ego network [1]_.  Formally, the effective size of a
+    node $u$, denoted $e(u)$, is defined by
+
+    .. math::
+
+       e(u) = \sum_{v \in N(u) \setminus \{u\}}
+       \left(1 - \sum_{w \in N(v)} p_{uw} m_{vw}\right)
+
+    where $N(u)$ is the set of neighbors of $u$ and $p_{uw}$ is the
+    normalized mutual weight of the (directed or undirected) edges
+    joining $u$ and $v$, for each vertex $u$ and $v$ [1]_. And $m_{vw}$
+    is the mutual weight of $v$ and $w$ divided by $v$ highest mutual
+    weight with any of its neighbors. The *mutual weight* of $u$ and $v$
+    is the sum of the weights of edges joining them (edge weights are
+    assumed to be one if the graph is unweighted).
+
+    For the case of unweighted and undirected graphs, Borgatti proposed
+    a simplified formula to compute effective size [2]_
+
+    .. math::
+
+       e(u) = n - \frac{2t}{n}
+
+    where `t` is the number of ties in the ego network (not including
+    ties to ego) and `n` is the number of nodes (excluding ego).
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        The graph containing ``v``. Directed graphs are treated like
+        undirected graphs when computing neighbors of ``v``.
+
+    nodes : container, optional
+        Container of nodes in the graph ``G`` to compute the effective size.
+        If None, the effective size of every node is computed.
+
+    weight : None or string, optional
+      If None, all edge weights are considered equal.
+      Otherwise holds the name of the edge attribute used as weight.
+
+    Returns
+    -------
+    dict
+        Dictionary with nodes as keys and the effective size of the node as values.
+
+    Notes
+    -----
+    Isolated nodes, including nodes which only have self-loop edges, do not
+    have a well-defined effective size::
+
+        >>> G = nx.path_graph(3)
+        >>> G.add_edge(4, 4)
+        >>> nx.effective_size(G)
+        {0: 1.0, 1: 2.0, 2: 1.0, 4: nan}
+
+    Burt also defined the related concept of *efficiency* of a node's ego
+    network, which is its effective size divided by the degree of that
+    node [1]_. So you can easily compute efficiency:
+
+    >>> G = nx.DiGraph()
+    >>> G.add_edges_from([(0, 1), (0, 2), (1, 0), (2, 1)])
+    >>> esize = nx.effective_size(G)
+    >>> efficiency = {n: v / G.degree(n) for n, v in esize.items()}
+
+    See also
+    --------
+    constraint
+
+    References
+    ----------
+    .. [1] Burt, Ronald S.
+           *Structural Holes: The Social Structure of Competition.*
+           Cambridge: Harvard University Press, 1995.
+
+    .. [2] Borgatti, S.
+           "Structural Holes: Unpacking Burt's Redundancy Measures"
+           CONNECTIONS 20(1):35-38.
+           http://www.analytictech.com/connections/v20(1)/holes.htm
+
+    """
+
+    def redundancy(G, u, v, weight=None):
+        nmw = normalized_mutual_weight
+        r = sum(
+            nmw(G, u, w, weight=weight) * nmw(G, v, w, norm=max, weight=weight)
+            for w in set(nx.all_neighbors(G, u))
+        )
+        return 1 - r
+
+    # Check if scipy is available
+    try:
+        # Needed for errstate
+        import numpy as np
+
+        # make sure nx.adjacency_matrix will not raise
+        import scipy as sp
+
+        has_scipy = True
+    except:
+        has_scipy = False
+
+    if nodes is None and has_scipy:
+        # In order to compute constraint of all nodes,
+        # algorithms based on sparse matrices can be much faster
+
+        # Obtain the adjacency matrix
+        P = nx.adjacency_matrix(G, weight=weight)
+
+        # Calculate mutual weights
+        mutual_weights1 = P + P.T
+        mutual_weights2 = mutual_weights1.copy()
+
+        with np.errstate(divide="ignore"):
+            # Mutual_weights1 = Normalize mutual weights by row sums
+            mutual_weights1 /= mutual_weights1.sum(axis=1)[:, np.newaxis]
+
+            # Mutual_weights2 = Normalize mutual weights by row max
+            mutual_weights2 /= mutual_weights2.max(axis=1).toarray()
+
+        # Calculate effective sizes
+        r = 1 - (mutual_weights1 @ mutual_weights2.T).toarray()
+        effective_size = ((mutual_weights1 > 0) * r).sum(axis=1)
+
+        # Special treatment: isolated nodes (ignoring selfloops) marked with "nan"
+        sum_mutual_weights = mutual_weights1.sum(axis=1) - mutual_weights1.diagonal()
+        isolated_nodes = sum_mutual_weights == 0
+        effective_size[isolated_nodes] = float("nan")
+        # Use tolist() to automatically convert numpy scalars -> Python scalars
+        return dict(zip(G, effective_size.tolist()))
+
+    # Results for only requested nodes
+    effective_size = {}
+    if nodes is None:
+        nodes = G
+    # Use Borgatti's simplified formula for unweighted and undirected graphs
+    if not G.is_directed() and weight is None:
+        for v in nodes:
+            # Effective size is not defined for isolated nodes, including nodes
+            # with only self-edges
+            if all(u == v for u in G[v]):
+                effective_size[v] = float("nan")
+                continue
+            E = nx.ego_graph(G, v, center=False, undirected=True)
+            effective_size[v] = len(E) - (2 * E.size()) / len(E)
+    else:
+        for v in nodes:
+            # Effective size is not defined for isolated nodes, including nodes
+            # with only self-edges
+            if all(u == v for u in G[v]):
+                effective_size[v] = float("nan")
+                continue
+            effective_size[v] = sum(
+                redundancy(G, v, u, weight) for u in set(nx.all_neighbors(G, v))
+            )
+    return effective_size
+
+
+@nx._dispatchable(edge_attrs="weight")
+def constraint(G, nodes=None, weight=None):
+    r"""Returns the constraint on all nodes in the graph ``G``.
+
+    The *constraint* is a measure of the extent to which a node *v* is
+    invested in those nodes that are themselves invested in the
+    neighbors of *v*. Formally, the *constraint on v*, denoted `c(v)`,
+    is defined by
+
+    .. math::
+
+       c(v) = \sum_{w \in N(v) \setminus \{v\}} \ell(v, w)
+
+    where $N(v)$ is the subset of the neighbors of `v` that are either
+    predecessors or successors of `v` and $\ell(v, w)$ is the local
+    constraint on `v` with respect to `w` [1]_. For the definition of local
+    constraint, see :func:`local_constraint`.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        The graph containing ``v``. This can be either directed or undirected.
+
+    nodes : container, optional
+        Container of nodes in the graph ``G`` to compute the constraint. If
+        None, the constraint of every node is computed.
+
+    weight : None or string, optional
+      If None, all edge weights are considered equal.
+      Otherwise holds the name of the edge attribute used as weight.
+
+    Returns
+    -------
+    dict
+        Dictionary with nodes as keys and the constraint on the node as values.
+
+    See also
+    --------
+    local_constraint
+
+    References
+    ----------
+    .. [1] Burt, Ronald S.
+           "Structural holes and good ideas".
+           American Journal of Sociology (110): 349–399.
+
+    """
+
+    # Check if scipy is available
+    try:
+        # Needed for errstate
+        import numpy as np
+
+        # make sure nx.adjacency_matrix will not raise
+        import scipy as sp
+
+        has_scipy = True
+    except:
+        has_scipy = False
+
+    if nodes is None and has_scipy:
+        # In order to compute constraint of all nodes,
+        # algorithms based on sparse matrices can be much faster
+
+        # Obtain the adjacency matrix
+        P = nx.adjacency_matrix(G, weight=weight)
+
+        # Calculate mutual weights
+        mutual_weights = P + P.T
+
+        # Normalize mutual weights by row sums
+        sum_mutual_weights = mutual_weights.sum(axis=1)
+        with np.errstate(divide="ignore"):
+            mutual_weights /= sum_mutual_weights[:, np.newaxis]
+
+        # Calculate local constraints and constraints
+        local_constraints = (mutual_weights + mutual_weights @ mutual_weights) ** 2
+        constraints = ((mutual_weights > 0) * local_constraints).sum(axis=1)
+
+        # Special treatment: isolated nodes marked with "nan"
+        isolated_nodes = sum_mutual_weights - 2 * mutual_weights.diagonal() == 0
+        constraints[isolated_nodes] = float("nan")
+        # Use tolist() to automatically convert numpy scalars -> Python scalars
+        return dict(zip(G, constraints.tolist()))
+
+    # Result for only requested nodes
+    constraint = {}
+    if nodes is None:
+        nodes = G
+    for v in nodes:
+        # Constraint is not defined for isolated nodes
+        if len(G[v]) == 0:
+            constraint[v] = float("nan")
+            continue
+        constraint[v] = sum(
+            local_constraint(G, v, n, weight) for n in set(nx.all_neighbors(G, v))
+        )
+    return constraint
+
+
+@nx._dispatchable(edge_attrs="weight")
+def local_constraint(G, u, v, weight=None):
+    r"""Returns the local constraint on the node ``u`` with respect to
+    the node ``v`` in the graph ``G``.
+
+    Formally, the *local constraint on u with respect to v*, denoted
+    $\ell(u, v)$, is defined by
+
+    .. math::
+
+       \ell(u, v) = \left(p_{uv} + \sum_{w \in N(v)} p_{uw} p_{wv}\right)^2,
+
+    where $N(v)$ is the set of neighbors of $v$ and $p_{uv}$ is the
+    normalized mutual weight of the (directed or undirected) edges
+    joining $u$ and $v$, for each vertex $u$ and $v$ [1]_. The *mutual
+    weight* of $u$ and $v$ is the sum of the weights of edges joining
+    them (edge weights are assumed to be one if the graph is
+    unweighted).
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        The graph containing ``u`` and ``v``. This can be either
+        directed or undirected.
+
+    u : node
+        A node in the graph ``G``.
+
+    v : node
+        A node in the graph ``G``.
+
+    weight : None or string, optional
+      If None, all edge weights are considered equal.
+      Otherwise holds the name of the edge attribute used as weight.
+
+    Returns
+    -------
+    float
+        The constraint of the node ``v`` in the graph ``G``.
+
+    See also
+    --------
+    constraint
+
+    References
+    ----------
+    .. [1] Burt, Ronald S.
+           "Structural holes and good ideas".
+           American Journal of Sociology (110): 349–399.
+
+    """
+    nmw = normalized_mutual_weight
+    direct = nmw(G, u, v, weight=weight)
+    indirect = sum(
+        nmw(G, u, w, weight=weight) * nmw(G, w, v, weight=weight)
+        for w in set(nx.all_neighbors(G, u))
+    )
+    return (direct + indirect) ** 2
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/summarization.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/summarization.py
new file mode 100644
index 0000000000000000000000000000000000000000..23db8da4efffa7dcbabfb75e031187d1b2b190dc
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/summarization.py
@@ -0,0 +1,564 @@
+"""
+Graph summarization finds smaller representations of graphs resulting in faster
+runtime of algorithms, reduced storage needs, and noise reduction.
+Summarization has applications in areas such as visualization, pattern mining,
+clustering and community detection, and more.  Core graph summarization
+techniques are grouping/aggregation, bit-compression,
+simplification/sparsification, and influence based. Graph summarization
+algorithms often produce either summary graphs in the form of supergraphs or
+sparsified graphs, or a list of independent structures. Supergraphs are the
+most common product, which consist of supernodes and original nodes and are
+connected by edges and superedges, which represent aggregate edges between
+nodes and supernodes.
+
+Grouping/aggregation based techniques compress graphs by representing
+close/connected nodes and edges in a graph by a single node/edge in a
+supergraph. Nodes can be grouped together into supernodes based on their
+structural similarities or proximity within a graph to reduce the total number
+of nodes in a graph. Edge-grouping techniques group edges into lossy/lossless
+nodes called compressor or virtual nodes to reduce the total number of edges in
+a graph. Edge-grouping techniques can be lossless, meaning that they can be
+used to re-create the original graph, or techniques can be lossy, requiring
+less space to store the summary graph, but at the expense of lower
+reconstruction accuracy of the original graph.
+
+Bit-compression techniques minimize the amount of information needed to
+describe the original graph, while revealing structural patterns in the
+original graph.  The two-part minimum description length (MDL) is often used to
+represent the model and the original graph in terms of the model.  A key
+difference between graph compression and graph summarization is that graph
+summarization focuses on finding structural patterns within the original graph,
+whereas graph compression focuses on compressions the original graph to be as
+small as possible.  **NOTE**: Some bit-compression methods exist solely to
+compress a graph without creating a summary graph or finding comprehensible
+structural patterns.
+
+Simplification/Sparsification techniques attempt to create a sparse
+representation of a graph by removing unimportant nodes and edges from the
+graph.  Sparsified graphs differ from supergraphs created by
+grouping/aggregation by only containing a subset of the original nodes and
+edges of the original graph.
+
+Influence based techniques aim to find a high-level description of influence
+propagation in a large graph.  These methods are scarce and have been mostly
+applied to social graphs.
+
+*dedensification* is a grouping/aggregation based technique to compress the
+neighborhoods around high-degree nodes in unweighted graphs by adding
+compressor nodes that summarize multiple edges of the same type to
+high-degree nodes (nodes with a degree greater than a given threshold).
+Dedensification was developed for the purpose of increasing performance of
+query processing around high-degree nodes in graph databases and enables direct
+operations on the compressed graph.  The structural patterns surrounding
+high-degree nodes in the original is preserved while using fewer edges and
+adding a small number of compressor nodes.  The degree of nodes present in the
+original graph is also preserved. The current implementation of dedensification
+supports graphs with one edge type.
+
+For more information on graph summarization, see `Graph Summarization Methods
+and Applications: A Survey `_
+"""
+
+from collections import Counter, defaultdict
+
+import networkx as nx
+
+__all__ = ["dedensify", "snap_aggregation"]
+
+
+@nx._dispatchable(mutates_input={"not copy": 3}, returns_graph=True)
+def dedensify(G, threshold, prefix=None, copy=True):
+    """Compresses neighborhoods around high-degree nodes
+
+    Reduces the number of edges to high-degree nodes by adding compressor nodes
+    that summarize multiple edges of the same type to high-degree nodes (nodes
+    with a degree greater than a given threshold).  Dedensification also has
+    the added benefit of reducing the number of edges around high-degree nodes.
+    The implementation currently supports graphs with a single edge type.
+
+    Parameters
+    ----------
+    G: graph
+       A networkx graph
+    threshold: int
+       Minimum degree threshold of a node to be considered a high degree node.
+       The threshold must be greater than or equal to 2.
+    prefix: str or None, optional (default: None)
+       An optional prefix for denoting compressor nodes
+    copy: bool, optional (default: True)
+       Indicates if dedensification should be done inplace
+
+    Returns
+    -------
+    dedensified networkx graph : (graph, set)
+        2-tuple of the dedensified graph and set of compressor nodes
+
+    Notes
+    -----
+    According to the algorithm in [1]_, removes edges in a graph by
+    compressing/decompressing the neighborhoods around high degree nodes by
+    adding compressor nodes that summarize multiple edges of the same type
+    to high-degree nodes.  Dedensification will only add a compressor node when
+    doing so will reduce the total number of edges in the given graph. This
+    implementation currently supports graphs with a single edge type.
+
+    Examples
+    --------
+    Dedensification will only add compressor nodes when doing so would result
+    in fewer edges::
+
+        >>> original_graph = nx.DiGraph()
+        >>> original_graph.add_nodes_from(
+        ...     ["1", "2", "3", "4", "5", "6", "A", "B", "C"]
+        ... )
+        >>> original_graph.add_edges_from(
+        ...     [
+        ...         ("1", "C"), ("1", "B"),
+        ...         ("2", "C"), ("2", "B"), ("2", "A"),
+        ...         ("3", "B"), ("3", "A"), ("3", "6"),
+        ...         ("4", "C"), ("4", "B"), ("4", "A"),
+        ...         ("5", "B"), ("5", "A"),
+        ...         ("6", "5"),
+        ...         ("A", "6")
+        ...     ]
+        ... )
+        >>> c_graph, c_nodes = nx.dedensify(original_graph, threshold=2)
+        >>> original_graph.number_of_edges()
+        15
+        >>> c_graph.number_of_edges()
+        14
+
+    A dedensified, directed graph can be "densified" to reconstruct the
+    original graph::
+
+        >>> original_graph = nx.DiGraph()
+        >>> original_graph.add_nodes_from(
+        ...     ["1", "2", "3", "4", "5", "6", "A", "B", "C"]
+        ... )
+        >>> original_graph.add_edges_from(
+        ...     [
+        ...         ("1", "C"), ("1", "B"),
+        ...         ("2", "C"), ("2", "B"), ("2", "A"),
+        ...         ("3", "B"), ("3", "A"), ("3", "6"),
+        ...         ("4", "C"), ("4", "B"), ("4", "A"),
+        ...         ("5", "B"), ("5", "A"),
+        ...         ("6", "5"),
+        ...         ("A", "6")
+        ...     ]
+        ... )
+        >>> c_graph, c_nodes = nx.dedensify(original_graph, threshold=2)
+        >>> # re-densifies the compressed graph into the original graph
+        >>> for c_node in c_nodes:
+        ...     all_neighbors = set(nx.all_neighbors(c_graph, c_node))
+        ...     out_neighbors = set(c_graph.neighbors(c_node))
+        ...     for out_neighbor in out_neighbors:
+        ...         c_graph.remove_edge(c_node, out_neighbor)
+        ...     in_neighbors = all_neighbors - out_neighbors
+        ...     for in_neighbor in in_neighbors:
+        ...         c_graph.remove_edge(in_neighbor, c_node)
+        ...         for out_neighbor in out_neighbors:
+        ...             c_graph.add_edge(in_neighbor, out_neighbor)
+        ...     c_graph.remove_node(c_node)
+        ...
+        >>> nx.is_isomorphic(original_graph, c_graph)
+        True
+
+    References
+    ----------
+    .. [1] Maccioni, A., & Abadi, D. J. (2016, August).
+       Scalable pattern matching over compressed graphs via dedensification.
+       In Proceedings of the 22nd ACM SIGKDD International Conference on
+       Knowledge Discovery and Data Mining (pp. 1755-1764).
+       http://www.cs.umd.edu/~abadi/papers/graph-dedense.pdf
+    """
+    if threshold < 2:
+        raise nx.NetworkXError("The degree threshold must be >= 2")
+
+    degrees = G.in_degree if G.is_directed() else G.degree
+    # Group nodes based on degree threshold
+    high_degree_nodes = {n for n, d in degrees if d > threshold}
+    low_degree_nodes = G.nodes() - high_degree_nodes
+
+    auxiliary = {}
+    for node in G:
+        high_degree_nbrs = frozenset(high_degree_nodes & set(G[node]))
+        if high_degree_nbrs:
+            if high_degree_nbrs in auxiliary:
+                auxiliary[high_degree_nbrs].add(node)
+            else:
+                auxiliary[high_degree_nbrs] = {node}
+
+    if copy:
+        G = G.copy()
+
+    compressor_nodes = set()
+    for index, (high_degree_nodes, low_degree_nodes) in enumerate(auxiliary.items()):
+        low_degree_node_count = len(low_degree_nodes)
+        high_degree_node_count = len(high_degree_nodes)
+        old_edges = high_degree_node_count * low_degree_node_count
+        new_edges = high_degree_node_count + low_degree_node_count
+        if old_edges <= new_edges:
+            continue
+        compression_node = "".join(str(node) for node in high_degree_nodes)
+        if prefix:
+            compression_node = str(prefix) + compression_node
+        for node in low_degree_nodes:
+            for high_node in high_degree_nodes:
+                if G.has_edge(node, high_node):
+                    G.remove_edge(node, high_node)
+
+            G.add_edge(node, compression_node)
+        for node in high_degree_nodes:
+            G.add_edge(compression_node, node)
+        compressor_nodes.add(compression_node)
+    return G, compressor_nodes
+
+
+def _snap_build_graph(
+    G,
+    groups,
+    node_attributes,
+    edge_attributes,
+    neighbor_info,
+    edge_types,
+    prefix,
+    supernode_attribute,
+    superedge_attribute,
+):
+    """
+    Build the summary graph from the data structures produced in the SNAP aggregation algorithm
+
+    Used in the SNAP aggregation algorithm to build the output summary graph and supernode
+    lookup dictionary.  This process uses the original graph and the data structures to
+    create the supernodes with the correct node attributes, and the superedges with the correct
+    edge attributes
+
+    Parameters
+    ----------
+    G: networkx.Graph
+        the original graph to be summarized
+    groups: dict
+        A dictionary of unique group IDs and their corresponding node groups
+    node_attributes: iterable
+        An iterable of the node attributes considered in the summarization process
+    edge_attributes: iterable
+        An iterable of the edge attributes considered in the summarization process
+    neighbor_info: dict
+        A data structure indicating the number of edges a node has with the
+        groups in the current summarization of each edge type
+    edge_types: dict
+        dictionary of edges in the graph and their corresponding attributes recognized
+        in the summarization
+    prefix: string
+        The prefix to be added to all supernodes
+    supernode_attribute: str
+        The node attribute for recording the supernode groupings of nodes
+    superedge_attribute: str
+        The edge attribute for recording the edge types represented by superedges
+
+    Returns
+    -------
+    summary graph: Networkx graph
+    """
+    output = G.__class__()
+    node_label_lookup = {}
+    for index, group_id in enumerate(groups):
+        group_set = groups[group_id]
+        supernode = f"{prefix}{index}"
+        node_label_lookup[group_id] = supernode
+        supernode_attributes = {
+            attr: G.nodes[next(iter(group_set))][attr] for attr in node_attributes
+        }
+        supernode_attributes[supernode_attribute] = group_set
+        output.add_node(supernode, **supernode_attributes)
+
+    for group_id in groups:
+        group_set = groups[group_id]
+        source_supernode = node_label_lookup[group_id]
+        for other_group, group_edge_types in neighbor_info[
+            next(iter(group_set))
+        ].items():
+            if group_edge_types:
+                target_supernode = node_label_lookup[other_group]
+                summary_graph_edge = (source_supernode, target_supernode)
+
+                edge_types = [
+                    dict(zip(edge_attributes, edge_type))
+                    for edge_type in group_edge_types
+                ]
+
+                has_edge = output.has_edge(*summary_graph_edge)
+                if output.is_multigraph():
+                    if not has_edge:
+                        for edge_type in edge_types:
+                            output.add_edge(*summary_graph_edge, **edge_type)
+                    elif not output.is_directed():
+                        existing_edge_data = output.get_edge_data(*summary_graph_edge)
+                        for edge_type in edge_types:
+                            if edge_type not in existing_edge_data.values():
+                                output.add_edge(*summary_graph_edge, **edge_type)
+                else:
+                    superedge_attributes = {superedge_attribute: edge_types}
+                    output.add_edge(*summary_graph_edge, **superedge_attributes)
+
+    return output
+
+
+def _snap_eligible_group(G, groups, group_lookup, edge_types):
+    """
+    Determines if a group is eligible to be split.
+
+    A group is eligible to be split if all nodes in the group have edges of the same type(s)
+    with the same other groups.
+
+    Parameters
+    ----------
+    G: graph
+        graph to be summarized
+    groups: dict
+        A dictionary of unique group IDs and their corresponding node groups
+    group_lookup: dict
+        dictionary of nodes and their current corresponding group ID
+    edge_types: dict
+        dictionary of edges in the graph and their corresponding attributes recognized
+        in the summarization
+
+    Returns
+    -------
+    tuple: group ID to split, and neighbor-groups participation_counts data structure
+    """
+    nbr_info = {node: {gid: Counter() for gid in groups} for node in group_lookup}
+    for group_id in groups:
+        current_group = groups[group_id]
+
+        # build nbr_info for nodes in group
+        for node in current_group:
+            nbr_info[node] = {group_id: Counter() for group_id in groups}
+            edges = G.edges(node, keys=True) if G.is_multigraph() else G.edges(node)
+            for edge in edges:
+                neighbor = edge[1]
+                edge_type = edge_types[edge]
+                neighbor_group_id = group_lookup[neighbor]
+                nbr_info[node][neighbor_group_id][edge_type] += 1
+
+        # check if group_id is eligible to be split
+        group_size = len(current_group)
+        for other_group_id in groups:
+            edge_counts = Counter()
+            for node in current_group:
+                edge_counts.update(nbr_info[node][other_group_id].keys())
+
+            if not all(count == group_size for count in edge_counts.values()):
+                # only the nbr_info of the returned group_id is required for handling group splits
+                return group_id, nbr_info
+
+    # if no eligible groups, complete nbr_info is calculated
+    return None, nbr_info
+
+
+def _snap_split(groups, neighbor_info, group_lookup, group_id):
+    """
+    Splits a group based on edge types and updates the groups accordingly
+
+    Splits the group with the given group_id based on the edge types
+    of the nodes so that each new grouping will all have the same
+    edges with other nodes.
+
+    Parameters
+    ----------
+    groups: dict
+        A dictionary of unique group IDs and their corresponding node groups
+    neighbor_info: dict
+        A data structure indicating the number of edges a node has with the
+        groups in the current summarization of each edge type
+    edge_types: dict
+        dictionary of edges in the graph and their corresponding attributes recognized
+        in the summarization
+    group_lookup: dict
+        dictionary of nodes and their current corresponding group ID
+    group_id: object
+        ID of group to be split
+
+    Returns
+    -------
+    dict
+        The updated groups based on the split
+    """
+    new_group_mappings = defaultdict(set)
+    for node in groups[group_id]:
+        signature = tuple(
+            frozenset(edge_types) for edge_types in neighbor_info[node].values()
+        )
+        new_group_mappings[signature].add(node)
+
+    # leave the biggest new_group as the original group
+    new_groups = sorted(new_group_mappings.values(), key=len)
+    for new_group in new_groups[:-1]:
+        # Assign unused integer as the new_group_id
+        # ids are tuples, so will not interact with the original group_ids
+        new_group_id = len(groups)
+        groups[new_group_id] = new_group
+        groups[group_id] -= new_group
+        for node in new_group:
+            group_lookup[node] = new_group_id
+
+    return groups
+
+
+@nx._dispatchable(
+    node_attrs="[node_attributes]", edge_attrs="[edge_attributes]", returns_graph=True
+)
+def snap_aggregation(
+    G,
+    node_attributes,
+    edge_attributes=(),
+    prefix="Supernode-",
+    supernode_attribute="group",
+    superedge_attribute="types",
+):
+    """Creates a summary graph based on attributes and connectivity.
+
+    This function uses the Summarization by Grouping Nodes on Attributes
+    and Pairwise edges (SNAP) algorithm for summarizing a given
+    graph by grouping nodes by node attributes and their edge attributes
+    into supernodes in a summary graph.  This name SNAP should not be
+    confused with the Stanford Network Analysis Project (SNAP).
+
+    Here is a high-level view of how this algorithm works:
+
+    1) Group nodes by node attribute values.
+
+    2) Iteratively split groups until all nodes in each group have edges
+    to nodes in the same groups. That is, until all the groups are homogeneous
+    in their member nodes' edges to other groups.  For example,
+    if all the nodes in group A only have edge to nodes in group B, then the
+    group is homogeneous and does not need to be split. If all nodes in group B
+    have edges with nodes in groups {A, C}, but some also have edges with other
+    nodes in B, then group B is not homogeneous and needs to be split into
+    groups have edges with {A, C} and a group of nodes having
+    edges with {A, B, C}.  This way, viewers of the summary graph can
+    assume that all nodes in the group have the exact same node attributes and
+    the exact same edges.
+
+    3) Build the output summary graph, where the groups are represented by
+    super-nodes. Edges represent the edges shared between all the nodes in each
+    respective groups.
+
+    A SNAP summary graph can be used to visualize graphs that are too large to display
+    or visually analyze, or to efficiently identify sets of similar nodes with similar connectivity
+    patterns to other sets of similar nodes based on specified node and/or edge attributes in a graph.
+
+    Parameters
+    ----------
+    G: graph
+        Networkx Graph to be summarized
+    node_attributes: iterable, required
+        An iterable of the node attributes used to group nodes in the summarization process. Nodes
+        with the same values for these attributes will be grouped together in the summary graph.
+    edge_attributes: iterable, optional
+        An iterable of the edge attributes considered in the summarization process.  If provided, unique
+        combinations of the attribute values found in the graph are used to
+        determine the edge types in the graph.  If not provided, all edges
+        are considered to be of the same type.
+    prefix: str
+        The prefix used to denote supernodes in the summary graph. Defaults to 'Supernode-'.
+    supernode_attribute: str
+        The node attribute for recording the supernode groupings of nodes. Defaults to 'group'.
+    superedge_attribute: str
+        The edge attribute for recording the edge types of multiple edges. Defaults to 'types'.
+
+    Returns
+    -------
+    networkx.Graph: summary graph
+
+    Examples
+    --------
+    SNAP aggregation takes a graph and summarizes it in the context of user-provided
+    node and edge attributes such that a viewer can more easily extract and
+    analyze the information represented by the graph
+
+    >>> nodes = {
+    ...     "A": dict(color="Red"),
+    ...     "B": dict(color="Red"),
+    ...     "C": dict(color="Red"),
+    ...     "D": dict(color="Red"),
+    ...     "E": dict(color="Blue"),
+    ...     "F": dict(color="Blue"),
+    ... }
+    >>> edges = [
+    ...     ("A", "E", "Strong"),
+    ...     ("B", "F", "Strong"),
+    ...     ("C", "E", "Weak"),
+    ...     ("D", "F", "Weak"),
+    ... ]
+    >>> G = nx.Graph()
+    >>> for node in nodes:
+    ...     attributes = nodes[node]
+    ...     G.add_node(node, **attributes)
+    >>> for source, target, type in edges:
+    ...     G.add_edge(source, target, type=type)
+    >>> node_attributes = ("color",)
+    >>> edge_attributes = ("type",)
+    >>> summary_graph = nx.snap_aggregation(
+    ...     G, node_attributes=node_attributes, edge_attributes=edge_attributes
+    ... )
+
+    Notes
+    -----
+    The summary graph produced is called a maximum Attribute-edge
+    compatible (AR-compatible) grouping.  According to [1]_, an
+    AR-compatible grouping means that all nodes in each group have the same
+    exact node attribute values and the same exact edges and
+    edge types to one or more nodes in the same groups.  The maximal
+    AR-compatible grouping is the grouping with the minimal cardinality.
+
+    The AR-compatible grouping is the most detailed grouping provided by
+    any of the SNAP algorithms.
+
+    References
+    ----------
+    .. [1] Y. Tian, R. A. Hankins, and J. M. Patel. Efficient aggregation
+       for graph summarization. In Proc. 2008 ACM-SIGMOD Int. Conf.
+       Management of Data (SIGMOD’08), pages 567–580, Vancouver, Canada,
+       June 2008.
+    """
+    edge_types = {
+        edge: tuple(attrs.get(attr) for attr in edge_attributes)
+        for edge, attrs in G.edges.items()
+    }
+    if not G.is_directed():
+        if G.is_multigraph():
+            # list is needed to avoid mutating while iterating
+            edges = [((v, u, k), etype) for (u, v, k), etype in edge_types.items()]
+        else:
+            # list is needed to avoid mutating while iterating
+            edges = [((v, u), etype) for (u, v), etype in edge_types.items()]
+        edge_types.update(edges)
+
+    group_lookup = {
+        node: tuple(attrs[attr] for attr in node_attributes)
+        for node, attrs in G.nodes.items()
+    }
+    groups = defaultdict(set)
+    for node, node_type in group_lookup.items():
+        groups[node_type].add(node)
+
+    eligible_group_id, nbr_info = _snap_eligible_group(
+        G, groups, group_lookup, edge_types
+    )
+    while eligible_group_id:
+        groups = _snap_split(groups, nbr_info, group_lookup, eligible_group_id)
+        eligible_group_id, nbr_info = _snap_eligible_group(
+            G, groups, group_lookup, edge_types
+        )
+    return _snap_build_graph(
+        G,
+        groups,
+        node_attributes,
+        edge_attributes,
+        nbr_info,
+        edge_types,
+        prefix,
+        supernode_attribute,
+        superedge_attribute,
+    )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/swap.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/swap.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb3cc1c0e75c375ae49976e21fcccf2dc6c76231
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/swap.py
@@ -0,0 +1,406 @@
+"""Swap edges in a graph."""
+
+import math
+
+import networkx as nx
+from networkx.utils import py_random_state
+
+__all__ = ["double_edge_swap", "connected_double_edge_swap", "directed_edge_swap"]
+
+
+@nx.utils.not_implemented_for("undirected")
+@py_random_state(3)
+@nx._dispatchable(mutates_input=True, returns_graph=True)
+def directed_edge_swap(G, *, nswap=1, max_tries=100, seed=None):
+    """Swap three edges in a directed graph while keeping the node degrees fixed.
+
+    A directed edge swap swaps three edges such that a -> b -> c -> d becomes
+    a -> c -> b -> d. This pattern of swapping allows all possible states with the
+    same in- and out-degree distribution in a directed graph to be reached.
+
+    If the swap would create parallel edges (e.g. if a -> c already existed in the
+    previous example), another attempt is made to find a suitable trio of edges.
+
+    Parameters
+    ----------
+    G : DiGraph
+       A directed graph
+
+    nswap : integer (optional, default=1)
+       Number of three-edge (directed) swaps to perform
+
+    max_tries : integer (optional, default=100)
+       Maximum number of attempts to swap edges
+
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    G : DiGraph
+       The graph after the edges are swapped.
+
+    Raises
+    ------
+    NetworkXError
+        If `G` is not directed, or
+        If nswap > max_tries, or
+        If there are fewer than 4 nodes or 3 edges in `G`.
+    NetworkXAlgorithmError
+        If the number of swap attempts exceeds `max_tries` before `nswap` swaps are made
+
+    Notes
+    -----
+    Does not enforce any connectivity constraints.
+
+    The graph G is modified in place.
+
+    A later swap is allowed to undo a previous swap.
+
+    References
+    ----------
+    .. [1] Erdős, Péter L., et al. “A Simple Havel-Hakimi Type Algorithm to Realize
+           Graphical Degree Sequences of Directed Graphs.” ArXiv:0905.4913 [Math],
+           Jan. 2010. https://doi.org/10.48550/arXiv.0905.4913.
+           Published  2010 in Elec. J. Combinatorics (17(1)). R66.
+           http://www.combinatorics.org/Volume_17/PDF/v17i1r66.pdf
+    .. [2] “Combinatorics - Reaching All Possible Simple Directed Graphs with a given
+           Degree Sequence with 2-Edge Swaps.” Mathematics Stack Exchange,
+           https://math.stackexchange.com/questions/22272/. Accessed 30 May 2022.
+    """
+    if nswap > max_tries:
+        raise nx.NetworkXError("Number of swaps > number of tries allowed.")
+    if len(G) < 4:
+        raise nx.NetworkXError("DiGraph has fewer than four nodes.")
+    if len(G.edges) < 3:
+        raise nx.NetworkXError("DiGraph has fewer than 3 edges")
+
+    # Instead of choosing uniformly at random from a generated edge list,
+    # this algorithm chooses nonuniformly from the set of nodes with
+    # probability weighted by degree.
+    tries = 0
+    swapcount = 0
+    keys, degrees = zip(*G.degree())  # keys, degree
+    cdf = nx.utils.cumulative_distribution(degrees)  # cdf of degree
+    discrete_sequence = nx.utils.discrete_sequence
+
+    while swapcount < nswap:
+        # choose source node index from discrete distribution
+        start_index = discrete_sequence(1, cdistribution=cdf, seed=seed)[0]
+        start = keys[start_index]
+        tries += 1
+
+        if tries > max_tries:
+            msg = f"Maximum number of swap attempts ({tries}) exceeded before desired swaps achieved ({nswap})."
+            raise nx.NetworkXAlgorithmError(msg)
+
+        # If the given node doesn't have any out edges, then there isn't anything to swap
+        if G.out_degree(start) == 0:
+            continue
+        second = seed.choice(list(G.succ[start]))
+        if start == second:
+            continue
+
+        if G.out_degree(second) == 0:
+            continue
+        third = seed.choice(list(G.succ[second]))
+        if second == third:
+            continue
+
+        if G.out_degree(third) == 0:
+            continue
+        fourth = seed.choice(list(G.succ[third]))
+        if third == fourth:
+            continue
+
+        if (
+            third not in G.succ[start]
+            and fourth not in G.succ[second]
+            and second not in G.succ[third]
+        ):
+            # Swap nodes
+            G.add_edge(start, third)
+            G.add_edge(third, second)
+            G.add_edge(second, fourth)
+            G.remove_edge(start, second)
+            G.remove_edge(second, third)
+            G.remove_edge(third, fourth)
+            swapcount += 1
+
+    return G
+
+
+@py_random_state(3)
+@nx._dispatchable(mutates_input=True, returns_graph=True)
+def double_edge_swap(G, nswap=1, max_tries=100, seed=None):
+    """Swap two edges in the graph while keeping the node degrees fixed.
+
+    A double-edge swap removes two randomly chosen edges u-v and x-y
+    and creates the new edges u-x and v-y::
+
+     u--v            u  v
+            becomes  |  |
+     x--y            x  y
+
+    If either the edge u-x or v-y already exist no swap is performed
+    and another attempt is made to find a suitable edge pair.
+
+    Parameters
+    ----------
+    G : graph
+       An undirected graph
+
+    nswap : integer (optional, default=1)
+       Number of double-edge swaps to perform
+
+    max_tries : integer (optional)
+       Maximum number of attempts to swap edges
+
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    G : graph
+       The graph after double edge swaps.
+
+    Raises
+    ------
+    NetworkXError
+        If `G` is directed, or
+        If `nswap` > `max_tries`, or
+        If there are fewer than 4 nodes or 2 edges in `G`.
+    NetworkXAlgorithmError
+        If the number of swap attempts exceeds `max_tries` before `nswap` swaps are made
+
+    Notes
+    -----
+    Does not enforce any connectivity constraints.
+
+    The graph G is modified in place.
+    """
+    if G.is_directed():
+        raise nx.NetworkXError(
+            "double_edge_swap() not defined for directed graphs. Use directed_edge_swap instead."
+        )
+    if nswap > max_tries:
+        raise nx.NetworkXError("Number of swaps > number of tries allowed.")
+    if len(G) < 4:
+        raise nx.NetworkXError("Graph has fewer than four nodes.")
+    if len(G.edges) < 2:
+        raise nx.NetworkXError("Graph has fewer than 2 edges")
+    # Instead of choosing uniformly at random from a generated edge list,
+    # this algorithm chooses nonuniformly from the set of nodes with
+    # probability weighted by degree.
+    n = 0
+    swapcount = 0
+    keys, degrees = zip(*G.degree())  # keys, degree
+    cdf = nx.utils.cumulative_distribution(degrees)  # cdf of degree
+    discrete_sequence = nx.utils.discrete_sequence
+    while swapcount < nswap:
+        #        if random.random() < 0.5: continue # trick to avoid periodicities?
+        # pick two random edges without creating edge list
+        # choose source node indices from discrete distribution
+        (ui, xi) = discrete_sequence(2, cdistribution=cdf, seed=seed)
+        if ui == xi:
+            continue  # same source, skip
+        u = keys[ui]  # convert index to label
+        x = keys[xi]
+        # choose target uniformly from neighbors
+        v = seed.choice(list(G[u]))
+        y = seed.choice(list(G[x]))
+        if v == y:
+            continue  # same target, skip
+        if (x not in G[u]) and (y not in G[v]):  # don't create parallel edges
+            G.add_edge(u, x)
+            G.add_edge(v, y)
+            G.remove_edge(u, v)
+            G.remove_edge(x, y)
+            swapcount += 1
+        if n >= max_tries:
+            e = (
+                f"Maximum number of swap attempts ({n}) exceeded "
+                f"before desired swaps achieved ({nswap})."
+            )
+            raise nx.NetworkXAlgorithmError(e)
+        n += 1
+    return G
+
+
+@py_random_state(3)
+@nx._dispatchable(mutates_input=True)
+def connected_double_edge_swap(G, nswap=1, _window_threshold=3, seed=None):
+    """Attempts the specified number of double-edge swaps in the graph `G`.
+
+    A double-edge swap removes two randomly chosen edges `(u, v)` and `(x,
+    y)` and creates the new edges `(u, x)` and `(v, y)`::
+
+     u--v            u  v
+            becomes  |  |
+     x--y            x  y
+
+    If either `(u, x)` or `(v, y)` already exist, then no swap is performed
+    so the actual number of swapped edges is always *at most* `nswap`.
+
+    Parameters
+    ----------
+    G : graph
+       An undirected graph
+
+    nswap : integer (optional, default=1)
+       Number of double-edge swaps to perform
+
+    _window_threshold : integer
+
+       The window size below which connectedness of the graph will be checked
+       after each swap.
+
+       The "window" in this function is a dynamically updated integer that
+       represents the number of swap attempts to make before checking if the
+       graph remains connected. It is an optimization used to decrease the
+       running time of the algorithm in exchange for increased complexity of
+       implementation.
+
+       If the window size is below this threshold, then the algorithm checks
+       after each swap if the graph remains connected by checking if there is a
+       path joining the two nodes whose edge was just removed. If the window
+       size is above this threshold, then the algorithm performs do all the
+       swaps in the window and only then check if the graph is still connected.
+
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    int
+       The number of successful swaps
+
+    Raises
+    ------
+
+    NetworkXError
+
+       If the input graph is not connected, or if the graph has fewer than four
+       nodes.
+
+    Notes
+    -----
+
+    The initial graph `G` must be connected, and the resulting graph is
+    connected. The graph `G` is modified in place.
+
+    References
+    ----------
+    .. [1] C. Gkantsidis and M. Mihail and E. Zegura,
+           The Markov chain simulation method for generating connected
+           power law random graphs, 2003.
+           http://citeseer.ist.psu.edu/gkantsidis03markov.html
+    """
+    if not nx.is_connected(G):
+        raise nx.NetworkXError("Graph not connected")
+    if len(G) < 4:
+        raise nx.NetworkXError("Graph has fewer than four nodes.")
+    n = 0
+    swapcount = 0
+    deg = G.degree()
+    # Label key for nodes
+    dk = [n for n, d in G.degree()]
+    cdf = nx.utils.cumulative_distribution([d for n, d in G.degree()])
+    discrete_sequence = nx.utils.discrete_sequence
+    window = 1
+    while n < nswap:
+        wcount = 0
+        swapped = []
+        # If the window is small, we just check each time whether the graph is
+        # connected by checking if the nodes that were just separated are still
+        # connected.
+        if window < _window_threshold:
+            # This Boolean keeps track of whether there was a failure or not.
+            fail = False
+            while wcount < window and n < nswap:
+                # Pick two random edges without creating the edge list. Choose
+                # source nodes from the discrete degree distribution.
+                (ui, xi) = discrete_sequence(2, cdistribution=cdf, seed=seed)
+                # If the source nodes are the same, skip this pair.
+                if ui == xi:
+                    continue
+                # Convert an index to a node label.
+                u = dk[ui]
+                x = dk[xi]
+                # Choose targets uniformly from neighbors.
+                v = seed.choice(list(G.neighbors(u)))
+                y = seed.choice(list(G.neighbors(x)))
+                # If the target nodes are the same, skip this pair.
+                if v == y:
+                    continue
+                if x not in G[u] and y not in G[v]:
+                    G.remove_edge(u, v)
+                    G.remove_edge(x, y)
+                    G.add_edge(u, x)
+                    G.add_edge(v, y)
+                    swapped.append((u, v, x, y))
+                    swapcount += 1
+                n += 1
+                # If G remains connected...
+                if nx.has_path(G, u, v):
+                    wcount += 1
+                # Otherwise, undo the changes.
+                else:
+                    G.add_edge(u, v)
+                    G.add_edge(x, y)
+                    G.remove_edge(u, x)
+                    G.remove_edge(v, y)
+                    swapcount -= 1
+                    fail = True
+            # If one of the swaps failed, reduce the window size.
+            if fail:
+                window = math.ceil(window / 2)
+            else:
+                window += 1
+        # If the window is large, then there is a good chance that a bunch of
+        # swaps will work. It's quicker to do all those swaps first and then
+        # check if the graph remains connected.
+        else:
+            while wcount < window and n < nswap:
+                # Pick two random edges without creating the edge list. Choose
+                # source nodes from the discrete degree distribution.
+                (ui, xi) = discrete_sequence(2, cdistribution=cdf, seed=seed)
+                # If the source nodes are the same, skip this pair.
+                if ui == xi:
+                    continue
+                # Convert an index to a node label.
+                u = dk[ui]
+                x = dk[xi]
+                # Choose targets uniformly from neighbors.
+                v = seed.choice(list(G.neighbors(u)))
+                y = seed.choice(list(G.neighbors(x)))
+                # If the target nodes are the same, skip this pair.
+                if v == y:
+                    continue
+                if x not in G[u] and y not in G[v]:
+                    G.remove_edge(u, v)
+                    G.remove_edge(x, y)
+                    G.add_edge(u, x)
+                    G.add_edge(v, y)
+                    swapped.append((u, v, x, y))
+                    swapcount += 1
+                n += 1
+                wcount += 1
+            # If the graph remains connected, increase the window size.
+            if nx.is_connected(G):
+                window += 1
+            # Otherwise, undo the changes from the previous window and decrease
+            # the window size.
+            else:
+                while swapped:
+                    (u, v, x, y) = swapped.pop()
+                    G.add_edge(u, v)
+                    G.add_edge(x, y)
+                    G.remove_edge(u, x)
+                    G.remove_edge(v, y)
+                    swapcount -= 1
+                window = math.ceil(window / 2)
+    return swapcount
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_asteroidal.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_asteroidal.py
new file mode 100644
index 0000000000000000000000000000000000000000..67131b2d05026317b496d06e6b382836c8c26367
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_asteroidal.py
@@ -0,0 +1,23 @@
+import networkx as nx
+
+
+def test_is_at_free():
+    is_at_free = nx.asteroidal.is_at_free
+
+    cycle = nx.cycle_graph(6)
+    assert not is_at_free(cycle)
+
+    path = nx.path_graph(6)
+    assert is_at_free(path)
+
+    small_graph = nx.complete_graph(2)
+    assert is_at_free(small_graph)
+
+    petersen = nx.petersen_graph()
+    assert not is_at_free(petersen)
+
+    clique = nx.complete_graph(6)
+    assert is_at_free(clique)
+
+    line_clique = nx.line_graph(clique)
+    assert not is_at_free(line_clique)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_boundary.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_boundary.py
new file mode 100644
index 0000000000000000000000000000000000000000..856be465556941fe6f2bfc2c8bab6d4b508cf999
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_boundary.py
@@ -0,0 +1,154 @@
+"""Unit tests for the :mod:`networkx.algorithms.boundary` module."""
+
+from itertools import combinations
+
+import pytest
+
+import networkx as nx
+from networkx import convert_node_labels_to_integers as cnlti
+from networkx.utils import edges_equal
+
+
+class TestNodeBoundary:
+    """Unit tests for the :func:`~networkx.node_boundary` function."""
+
+    def test_null_graph(self):
+        """Tests that the null graph has empty node boundaries."""
+        null = nx.null_graph()
+        assert nx.node_boundary(null, []) == set()
+        assert nx.node_boundary(null, [], []) == set()
+        assert nx.node_boundary(null, [1, 2, 3]) == set()
+        assert nx.node_boundary(null, [1, 2, 3], [4, 5, 6]) == set()
+        assert nx.node_boundary(null, [1, 2, 3], [3, 4, 5]) == set()
+
+    def test_path_graph(self):
+        P10 = cnlti(nx.path_graph(10), first_label=1)
+        assert nx.node_boundary(P10, []) == set()
+        assert nx.node_boundary(P10, [], []) == set()
+        assert nx.node_boundary(P10, [1, 2, 3]) == {4}
+        assert nx.node_boundary(P10, [4, 5, 6]) == {3, 7}
+        assert nx.node_boundary(P10, [3, 4, 5, 6, 7]) == {2, 8}
+        assert nx.node_boundary(P10, [8, 9, 10]) == {7}
+        assert nx.node_boundary(P10, [4, 5, 6], [9, 10]) == set()
+
+    def test_complete_graph(self):
+        K10 = cnlti(nx.complete_graph(10), first_label=1)
+        assert nx.node_boundary(K10, []) == set()
+        assert nx.node_boundary(K10, [], []) == set()
+        assert nx.node_boundary(K10, [1, 2, 3]) == {4, 5, 6, 7, 8, 9, 10}
+        assert nx.node_boundary(K10, [4, 5, 6]) == {1, 2, 3, 7, 8, 9, 10}
+        assert nx.node_boundary(K10, [3, 4, 5, 6, 7]) == {1, 2, 8, 9, 10}
+        assert nx.node_boundary(K10, [4, 5, 6], []) == set()
+        assert nx.node_boundary(K10, K10) == set()
+        assert nx.node_boundary(K10, [1, 2, 3], [3, 4, 5]) == {4, 5}
+
+    def test_petersen(self):
+        """Check boundaries in the petersen graph
+
+        cheeger(G,k)=min(|bdy(S)|/|S| for |S|=k, 0>> list(cycles("abc"))
+        [('a', 'b', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b')]
+
+    """
+    n = len(seq)
+    cycled_seq = cycle(seq)
+    for x in seq:
+        yield tuple(islice(cycled_seq, n))
+        next(cycled_seq)
+
+
+def cyclic_equals(seq1, seq2):
+    """Decide whether two sequences are equal up to cyclic permutations.
+
+    For example::
+
+        >>> cyclic_equals("xyz", "zxy")
+        True
+        >>> cyclic_equals("xyz", "zyx")
+        False
+
+    """
+    # Cast seq2 to a tuple since `cycles()` yields tuples.
+    seq2 = tuple(seq2)
+    return any(x == tuple(seq2) for x in cycles(seq1))
+
+
+class TestChainDecomposition:
+    """Unit tests for the chain decomposition function."""
+
+    def assertContainsChain(self, chain, expected):
+        # A cycle could be expressed in two different orientations, one
+        # forward and one backward, so we need to check for cyclic
+        # equality in both orientations.
+        reversed_chain = list(reversed([tuple(reversed(e)) for e in chain]))
+        for candidate in expected:
+            if cyclic_equals(chain, candidate):
+                break
+            if cyclic_equals(reversed_chain, candidate):
+                break
+        else:
+            self.fail("chain not found")
+
+    def test_decomposition(self):
+        edges = [
+            # DFS tree edges.
+            (1, 2),
+            (2, 3),
+            (3, 4),
+            (3, 5),
+            (5, 6),
+            (6, 7),
+            (7, 8),
+            (5, 9),
+            (9, 10),
+            # Nontree edges.
+            (1, 3),
+            (1, 4),
+            (2, 5),
+            (5, 10),
+            (6, 8),
+        ]
+        G = nx.Graph(edges)
+        expected = [
+            [(1, 3), (3, 2), (2, 1)],
+            [(1, 4), (4, 3)],
+            [(2, 5), (5, 3)],
+            [(5, 10), (10, 9), (9, 5)],
+            [(6, 8), (8, 7), (7, 6)],
+        ]
+        chains = list(nx.chain_decomposition(G, root=1))
+        assert len(chains) == len(expected)
+
+    def test_barbell_graph(self):
+        # The (3, 0) barbell graph has two triangles joined by a single edge.
+        G = nx.barbell_graph(3, 0)
+        chains = list(nx.chain_decomposition(G, root=0))
+        expected = [[(0, 1), (1, 2), (2, 0)], [(3, 4), (4, 5), (5, 3)]]
+        assert len(chains) == len(expected)
+        for chain in chains:
+            self.assertContainsChain(chain, expected)
+
+    def test_disconnected_graph(self):
+        """Test for a graph with multiple connected components."""
+        G = nx.barbell_graph(3, 0)
+        H = nx.barbell_graph(3, 0)
+        mapping = dict(zip(range(6), "abcdef"))
+        nx.relabel_nodes(H, mapping, copy=False)
+        G = nx.union(G, H)
+        chains = list(nx.chain_decomposition(G))
+        expected = [
+            [(0, 1), (1, 2), (2, 0)],
+            [(3, 4), (4, 5), (5, 3)],
+            [("a", "b"), ("b", "c"), ("c", "a")],
+            [("d", "e"), ("e", "f"), ("f", "d")],
+        ]
+        assert len(chains) == len(expected)
+        for chain in chains:
+            self.assertContainsChain(chain, expected)
+
+    def test_disconnected_graph_root_node(self):
+        """Test for a single component of a disconnected graph."""
+        G = nx.barbell_graph(3, 0)
+        H = nx.barbell_graph(3, 0)
+        mapping = dict(zip(range(6), "abcdef"))
+        nx.relabel_nodes(H, mapping, copy=False)
+        G = nx.union(G, H)
+        chains = list(nx.chain_decomposition(G, root="a"))
+        expected = [
+            [("a", "b"), ("b", "c"), ("c", "a")],
+            [("d", "e"), ("e", "f"), ("f", "d")],
+        ]
+        assert len(chains) == len(expected)
+        for chain in chains:
+            self.assertContainsChain(chain, expected)
+
+    def test_chain_decomposition_root_not_in_G(self):
+        """Test chain decomposition when root is not in graph"""
+        G = nx.Graph()
+        G.add_nodes_from([1, 2, 3])
+        with pytest.raises(nx.NodeNotFound):
+            nx.has_bridges(G, root=6)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_chordal.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_chordal.py
new file mode 100644
index 0000000000000000000000000000000000000000..148b22f2632d722522483b556f11285a8e823126
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_chordal.py
@@ -0,0 +1,129 @@
+import pytest
+
+import networkx as nx
+
+
+class TestMCS:
+    @classmethod
+    def setup_class(cls):
+        # simple graph
+        connected_chordal_G = nx.Graph()
+        connected_chordal_G.add_edges_from(
+            [
+                (1, 2),
+                (1, 3),
+                (2, 3),
+                (2, 4),
+                (3, 4),
+                (3, 5),
+                (3, 6),
+                (4, 5),
+                (4, 6),
+                (5, 6),
+            ]
+        )
+        cls.connected_chordal_G = connected_chordal_G
+
+        chordal_G = nx.Graph()
+        chordal_G.add_edges_from(
+            [
+                (1, 2),
+                (1, 3),
+                (2, 3),
+                (2, 4),
+                (3, 4),
+                (3, 5),
+                (3, 6),
+                (4, 5),
+                (4, 6),
+                (5, 6),
+                (7, 8),
+            ]
+        )
+        chordal_G.add_node(9)
+        cls.chordal_G = chordal_G
+
+        non_chordal_G = nx.Graph()
+        non_chordal_G.add_edges_from([(1, 2), (1, 3), (2, 4), (2, 5), (3, 4), (3, 5)])
+        cls.non_chordal_G = non_chordal_G
+
+        self_loop_G = nx.Graph()
+        self_loop_G.add_edges_from([(1, 1)])
+        cls.self_loop_G = self_loop_G
+
+    @pytest.mark.parametrize("G", (nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()))
+    def test_is_chordal_not_implemented(self, G):
+        with pytest.raises(nx.NetworkXNotImplemented):
+            nx.is_chordal(G)
+
+    def test_is_chordal(self):
+        assert not nx.is_chordal(self.non_chordal_G)
+        assert nx.is_chordal(self.chordal_G)
+        assert nx.is_chordal(self.connected_chordal_G)
+        assert nx.is_chordal(nx.Graph())
+        assert nx.is_chordal(nx.complete_graph(3))
+        assert nx.is_chordal(nx.cycle_graph(3))
+        assert not nx.is_chordal(nx.cycle_graph(5))
+        assert nx.is_chordal(self.self_loop_G)
+
+    def test_induced_nodes(self):
+        G = nx.generators.classic.path_graph(10)
+        Induced_nodes = nx.find_induced_nodes(G, 1, 9, 2)
+        assert Induced_nodes == {1, 2, 3, 4, 5, 6, 7, 8, 9}
+        pytest.raises(
+            nx.NetworkXTreewidthBoundExceeded, nx.find_induced_nodes, G, 1, 9, 1
+        )
+        Induced_nodes = nx.find_induced_nodes(self.chordal_G, 1, 6)
+        assert Induced_nodes == {1, 2, 4, 6}
+        pytest.raises(nx.NetworkXError, nx.find_induced_nodes, self.non_chordal_G, 1, 5)
+
+    def test_graph_treewidth(self):
+        with pytest.raises(nx.NetworkXError, match="Input graph is not chordal"):
+            nx.chordal_graph_treewidth(self.non_chordal_G)
+
+    def test_chordal_find_cliques(self):
+        cliques = {
+            frozenset([9]),
+            frozenset([7, 8]),
+            frozenset([1, 2, 3]),
+            frozenset([2, 3, 4]),
+            frozenset([3, 4, 5, 6]),
+        }
+        assert set(nx.chordal_graph_cliques(self.chordal_G)) == cliques
+        with pytest.raises(nx.NetworkXError, match="Input graph is not chordal"):
+            set(nx.chordal_graph_cliques(self.non_chordal_G))
+        with pytest.raises(nx.NetworkXError, match="Input graph is not chordal"):
+            set(nx.chordal_graph_cliques(self.self_loop_G))
+
+    def test_chordal_find_cliques_path(self):
+        G = nx.path_graph(10)
+        cliqueset = nx.chordal_graph_cliques(G)
+        for u, v in G.edges():
+            assert frozenset([u, v]) in cliqueset or frozenset([v, u]) in cliqueset
+
+    def test_chordal_find_cliquesCC(self):
+        cliques = {frozenset([1, 2, 3]), frozenset([2, 3, 4]), frozenset([3, 4, 5, 6])}
+        cgc = nx.chordal_graph_cliques
+        assert set(cgc(self.connected_chordal_G)) == cliques
+
+    def test_complete_to_chordal_graph(self):
+        fgrg = nx.fast_gnp_random_graph
+        test_graphs = [
+            nx.barbell_graph(6, 2),
+            nx.cycle_graph(15),
+            nx.wheel_graph(20),
+            nx.grid_graph([10, 4]),
+            nx.ladder_graph(15),
+            nx.star_graph(5),
+            nx.bull_graph(),
+            fgrg(20, 0.3, seed=1),
+        ]
+        for G in test_graphs:
+            H, a = nx.complete_to_chordal_graph(G)
+            assert nx.is_chordal(H)
+            assert len(a) == H.number_of_nodes()
+            if nx.is_chordal(G):
+                assert G.number_of_edges() == H.number_of_edges()
+                assert set(a.values()) == {0}
+            else:
+                assert len(set(a.values())) == H.number_of_nodes()
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_clique.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_clique.py
new file mode 100644
index 0000000000000000000000000000000000000000..118b3093cf3fd12ffe458983b37549faf78c83c3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_clique.py
@@ -0,0 +1,300 @@
+import pytest
+
+import networkx as nx
+from networkx import convert_node_labels_to_integers as cnlti
+
+
+class TestCliques:
+    def setup_method(self):
+        z = [3, 4, 3, 4, 2, 4, 2, 1, 1, 1, 1]
+        self.G = cnlti(nx.generators.havel_hakimi_graph(z), first_label=1)
+        self.cl = list(nx.find_cliques(self.G))
+        H = nx.complete_graph(6)
+        H = nx.relabel_nodes(H, {i: i + 1 for i in range(6)})
+        H.remove_edges_from([(2, 6), (2, 5), (2, 4), (1, 3), (5, 3)])
+        self.H = H
+
+    def test_find_cliques1(self):
+        cl = list(nx.find_cliques(self.G))
+        rcl = nx.find_cliques_recursive(self.G)
+        expected = [[2, 6, 1, 3], [2, 6, 4], [5, 4, 7], [8, 9], [10, 11]]
+        assert sorted(map(sorted, cl)) == sorted(map(sorted, rcl))
+        assert sorted(map(sorted, cl)) == sorted(map(sorted, expected))
+
+    def test_selfloops(self):
+        self.G.add_edge(1, 1)
+        cl = list(nx.find_cliques(self.G))
+        rcl = list(nx.find_cliques_recursive(self.G))
+        assert set(map(frozenset, cl)) == set(map(frozenset, rcl))
+        answer = [{2, 6, 1, 3}, {2, 6, 4}, {5, 4, 7}, {8, 9}, {10, 11}]
+        assert len(answer) == len(cl)
+        assert all(set(c) in answer for c in cl)
+
+    def test_find_cliques2(self):
+        hcl = list(nx.find_cliques(self.H))
+        assert sorted(map(sorted, hcl)) == [[1, 2], [1, 4, 5, 6], [2, 3], [3, 4, 6]]
+
+    def test_find_cliques3(self):
+        # all cliques are [[2, 6, 1, 3], [2, 6, 4], [5, 4, 7], [8, 9], [10, 11]]
+
+        cl = list(nx.find_cliques(self.G, [2]))
+        rcl = nx.find_cliques_recursive(self.G, [2])
+        expected = [[2, 6, 1, 3], [2, 6, 4]]
+        assert sorted(map(sorted, rcl)) == sorted(map(sorted, expected))
+        assert sorted(map(sorted, cl)) == sorted(map(sorted, expected))
+
+        cl = list(nx.find_cliques(self.G, [2, 3]))
+        rcl = nx.find_cliques_recursive(self.G, [2, 3])
+        expected = [[2, 6, 1, 3]]
+        assert sorted(map(sorted, rcl)) == sorted(map(sorted, expected))
+        assert sorted(map(sorted, cl)) == sorted(map(sorted, expected))
+
+        cl = list(nx.find_cliques(self.G, [2, 6, 4]))
+        rcl = nx.find_cliques_recursive(self.G, [2, 6, 4])
+        expected = [[2, 6, 4]]
+        assert sorted(map(sorted, rcl)) == sorted(map(sorted, expected))
+        assert sorted(map(sorted, cl)) == sorted(map(sorted, expected))
+
+        cl = list(nx.find_cliques(self.G, [2, 6, 4]))
+        rcl = nx.find_cliques_recursive(self.G, [2, 6, 4])
+        expected = [[2, 6, 4]]
+        assert sorted(map(sorted, rcl)) == sorted(map(sorted, expected))
+        assert sorted(map(sorted, cl)) == sorted(map(sorted, expected))
+
+        with pytest.raises(ValueError):
+            list(nx.find_cliques(self.G, [2, 6, 4, 1]))
+
+        with pytest.raises(ValueError):
+            list(nx.find_cliques_recursive(self.G, [2, 6, 4, 1]))
+
+    def test_find_cliques_directed(self):
+        G = nx.path_graph(4, create_using=nx.DiGraph)
+        msg = "not implemented for directed"
+        with pytest.raises(nx.NetworkXNotImplemented, match=msg):
+            list(nx.find_cliques(G))
+
+        with pytest.raises(nx.NetworkXNotImplemented, match=msg):
+            list(nx.find_cliques_recursive(G))
+
+    def test_number_of_cliques(self):
+        G = self.G
+        assert nx.number_of_cliques(G, 1) == 1
+        assert list(nx.number_of_cliques(G, [1]).values()) == [1]
+        assert list(nx.number_of_cliques(G, [1, 2]).values()) == [1, 2]
+        assert nx.number_of_cliques(G, [1, 2]) == {1: 1, 2: 2}
+        assert nx.number_of_cliques(G, 2) == 2
+        assert nx.number_of_cliques(G) == {
+            1: 1,
+            2: 2,
+            3: 1,
+            4: 2,
+            5: 1,
+            6: 2,
+            7: 1,
+            8: 1,
+            9: 1,
+            10: 1,
+            11: 1,
+        }
+        assert nx.number_of_cliques(G, nodes=list(G)) == {
+            1: 1,
+            2: 2,
+            3: 1,
+            4: 2,
+            5: 1,
+            6: 2,
+            7: 1,
+            8: 1,
+            9: 1,
+            10: 1,
+            11: 1,
+        }
+        assert nx.number_of_cliques(G, nodes=[2, 3, 4]) == {2: 2, 3: 1, 4: 2}
+        assert nx.number_of_cliques(G, cliques=self.cl) == {
+            1: 1,
+            2: 2,
+            3: 1,
+            4: 2,
+            5: 1,
+            6: 2,
+            7: 1,
+            8: 1,
+            9: 1,
+            10: 1,
+            11: 1,
+        }
+        assert nx.number_of_cliques(G, list(G), cliques=self.cl) == {
+            1: 1,
+            2: 2,
+            3: 1,
+            4: 2,
+            5: 1,
+            6: 2,
+            7: 1,
+            8: 1,
+            9: 1,
+            10: 1,
+            11: 1,
+        }
+
+    def test_node_clique_number(self):
+        G = self.G
+        assert nx.node_clique_number(G, 1) == 4
+        assert list(nx.node_clique_number(G, [1]).values()) == [4]
+        assert list(nx.node_clique_number(G, [1, 2]).values()) == [4, 4]
+        assert nx.node_clique_number(G, [1, 2]) == {1: 4, 2: 4}
+        assert nx.node_clique_number(G, 1) == 4
+        assert nx.node_clique_number(G) == {
+            1: 4,
+            2: 4,
+            3: 4,
+            4: 3,
+            5: 3,
+            6: 4,
+            7: 3,
+            8: 2,
+            9: 2,
+            10: 2,
+            11: 2,
+        }
+        assert nx.node_clique_number(G, cliques=self.cl) == {
+            1: 4,
+            2: 4,
+            3: 4,
+            4: 3,
+            5: 3,
+            6: 4,
+            7: 3,
+            8: 2,
+            9: 2,
+            10: 2,
+            11: 2,
+        }
+        assert nx.node_clique_number(G, [1, 2], cliques=self.cl) == {1: 4, 2: 4}
+        assert nx.node_clique_number(G, 1, cliques=self.cl) == 4
+
+    def test_make_clique_bipartite(self):
+        G = self.G
+        B = nx.make_clique_bipartite(G)
+        assert sorted(B) == [-5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
+        # Project onto the nodes of the original graph.
+        H = nx.projected_graph(B, range(1, 12))
+        assert H.adj == G.adj
+        # Project onto the nodes representing the cliques.
+        H1 = nx.projected_graph(B, range(-5, 0))
+        # Relabel the negative numbers as positive ones.
+        H1 = nx.relabel_nodes(H1, {-v: v for v in range(1, 6)})
+        assert sorted(H1) == [1, 2, 3, 4, 5]
+
+    def test_make_max_clique_graph(self):
+        """Tests that the maximal clique graph is the same as the bipartite
+        clique graph after being projected onto the nodes representing the
+        cliques.
+
+        """
+        G = self.G
+        B = nx.make_clique_bipartite(G)
+        # Project onto the nodes representing the cliques.
+        H1 = nx.projected_graph(B, range(-5, 0))
+        # Relabel the negative numbers as nonnegative ones, starting at
+        # 0.
+        H1 = nx.relabel_nodes(H1, {-v: v - 1 for v in range(1, 6)})
+        H2 = nx.make_max_clique_graph(G)
+        assert H1.adj == H2.adj
+
+    def test_directed(self):
+        with pytest.raises(nx.NetworkXNotImplemented):
+            next(nx.find_cliques(nx.DiGraph()))
+
+    def test_find_cliques_trivial(self):
+        G = nx.Graph()
+        assert sorted(nx.find_cliques(G)) == []
+        assert sorted(nx.find_cliques_recursive(G)) == []
+
+    def test_make_max_clique_graph_create_using(self):
+        G = nx.Graph([(1, 2), (3, 1), (4, 1), (5, 6)])
+        E = nx.Graph([(0, 1), (0, 2), (1, 2)])
+        E.add_node(3)
+        assert nx.is_isomorphic(nx.make_max_clique_graph(G, create_using=nx.Graph), E)
+
+
+class TestEnumerateAllCliques:
+    def test_paper_figure_4(self):
+        # Same graph as given in Fig. 4 of paper enumerate_all_cliques is
+        # based on.
+        # http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=1559964&isnumber=33129
+        G = nx.Graph()
+        edges_fig_4 = [
+            ("a", "b"),
+            ("a", "c"),
+            ("a", "d"),
+            ("a", "e"),
+            ("b", "c"),
+            ("b", "d"),
+            ("b", "e"),
+            ("c", "d"),
+            ("c", "e"),
+            ("d", "e"),
+            ("f", "b"),
+            ("f", "c"),
+            ("f", "g"),
+            ("g", "f"),
+            ("g", "c"),
+            ("g", "d"),
+            ("g", "e"),
+        ]
+        G.add_edges_from(edges_fig_4)
+
+        cliques = list(nx.enumerate_all_cliques(G))
+        clique_sizes = list(map(len, cliques))
+        assert sorted(clique_sizes) == clique_sizes
+
+        expected_cliques = [
+            ["a"],
+            ["b"],
+            ["c"],
+            ["d"],
+            ["e"],
+            ["f"],
+            ["g"],
+            ["a", "b"],
+            ["a", "b", "d"],
+            ["a", "b", "d", "e"],
+            ["a", "b", "e"],
+            ["a", "c"],
+            ["a", "c", "d"],
+            ["a", "c", "d", "e"],
+            ["a", "c", "e"],
+            ["a", "d"],
+            ["a", "d", "e"],
+            ["a", "e"],
+            ["b", "c"],
+            ["b", "c", "d"],
+            ["b", "c", "d", "e"],
+            ["b", "c", "e"],
+            ["b", "c", "f"],
+            ["b", "d"],
+            ["b", "d", "e"],
+            ["b", "e"],
+            ["b", "f"],
+            ["c", "d"],
+            ["c", "d", "e"],
+            ["c", "d", "e", "g"],
+            ["c", "d", "g"],
+            ["c", "e"],
+            ["c", "e", "g"],
+            ["c", "f"],
+            ["c", "f", "g"],
+            ["c", "g"],
+            ["d", "e"],
+            ["d", "e", "g"],
+            ["d", "g"],
+            ["e", "g"],
+            ["f", "g"],
+            ["a", "b", "c"],
+            ["a", "b", "c", "d"],
+            ["a", "b", "c", "d", "e"],
+            ["a", "b", "c", "e"],
+        ]
+
+        assert sorted(map(sorted, cliques)) == sorted(map(sorted, expected_cliques))
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_cluster.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_cluster.py
new file mode 100644
index 0000000000000000000000000000000000000000..f4741b420af781cec73c86e917af6ad68fa091a7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_cluster.py
@@ -0,0 +1,678 @@
+import pytest
+
+import networkx as nx
+
+
+def test_square_clustering_adjacent_squares():
+    G = nx.Graph([(1, 2), (1, 3), (2, 4), (3, 4), (3, 5), (4, 6), (5, 6)])
+    # Corner nodes: C_4 == 0.5, central face nodes: C_4 = 1 / 3
+    expected = {1: 0.5, 2: 0.5, 3: 1 / 3, 4: 1 / 3, 5: 0.5, 6: 0.5}
+    assert nx.square_clustering(G) == expected
+
+
+def test_square_clustering_2d_grid():
+    G = nx.grid_2d_graph(3, 3)
+    # Central node: 4 squares out of 20 potential
+    expected = {
+        (0, 0): 1 / 3,
+        (0, 1): 0.25,
+        (0, 2): 1 / 3,
+        (1, 0): 0.25,
+        (1, 1): 0.2,
+        (1, 2): 0.25,
+        (2, 0): 1 / 3,
+        (2, 1): 0.25,
+        (2, 2): 1 / 3,
+    }
+    assert nx.square_clustering(G) == expected
+
+
+def test_square_clustering_multiple_squares_non_complete():
+    """An example where all nodes are part of all squares, but not every node
+    is connected to every other."""
+    G = nx.Graph([(0, 1), (0, 2), (1, 3), (2, 3), (1, 4), (2, 4), (1, 5), (2, 5)])
+    expected = {n: 1 for n in G}
+    assert nx.square_clustering(G) == expected
+
+
+class TestTriangles:
+    def test_empty(self):
+        G = nx.Graph()
+        assert list(nx.triangles(G).values()) == []
+
+    def test_path(self):
+        G = nx.path_graph(10)
+        assert list(nx.triangles(G).values()) == [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
+        assert nx.triangles(G) == {
+            0: 0,
+            1: 0,
+            2: 0,
+            3: 0,
+            4: 0,
+            5: 0,
+            6: 0,
+            7: 0,
+            8: 0,
+            9: 0,
+        }
+
+    def test_cubical(self):
+        G = nx.cubical_graph()
+        assert list(nx.triangles(G).values()) == [0, 0, 0, 0, 0, 0, 0, 0]
+        assert nx.triangles(G, 1) == 0
+        assert list(nx.triangles(G, [1, 2]).values()) == [0, 0]
+        assert nx.triangles(G, 1) == 0
+        assert nx.triangles(G, [1, 2]) == {1: 0, 2: 0}
+
+    def test_k5(self):
+        G = nx.complete_graph(5)
+        assert list(nx.triangles(G).values()) == [6, 6, 6, 6, 6]
+        assert sum(nx.triangles(G).values()) / 3 == 10
+        assert nx.triangles(G, 1) == 6
+        G.remove_edge(1, 2)
+        assert list(nx.triangles(G).values()) == [5, 3, 3, 5, 5]
+        assert nx.triangles(G, 1) == 3
+        G.add_edge(3, 3)  # ignore self-edges
+        assert list(nx.triangles(G).values()) == [5, 3, 3, 5, 5]
+        assert nx.triangles(G, 3) == 5
+
+
+def test_all_triangles_non_integer_nodes():
+    G = nx.Graph()
+    G.add_edges_from(
+        [
+            ("a", "b"),
+            ("b", "c"),
+            ("c", "a"),  # triangle: a-b-c
+        ]
+    )
+    expected = {frozenset({"a", "b", "c"})}
+    assert {frozenset(t) for t in nx.all_triangles(G)} == expected
+
+
+def test_all_triangles_overlapping():
+    G = nx.Graph()
+    G.add_edges_from(
+        [
+            (0, 1),
+            (1, 2),
+            (2, 0),  # triangle: 0-1-2
+            (0, 2),
+            (2, 3),
+            (3, 0),  # triangle: 0-2-3
+        ]
+    )
+    expected = {frozenset({0, 1, 2}), frozenset({0, 2, 3})}
+    assert {frozenset(t) for t in nx.all_triangles(G)} == expected
+
+
+def test_all_triangles_subset():
+    G = nx.Graph()
+    G.add_edges_from(
+        [
+            (0, 1),
+            (1, 2),
+            (2, 0),  # triangle: 0-1-2
+            (2, 3),
+            (3, 4),
+            (4, 2),  # triangle: 2-3-4
+        ]
+    )
+    assert {frozenset(t) for t in nx.all_triangles(G, nbunch=[0, 1])} == {
+        frozenset({0, 1, 2})
+    }
+
+
+def test_all_triangles_subset_empty():
+    G = nx.Graph()
+    G.add_edges_from(
+        [
+            (0, 1),
+            (1, 2),
+            (2, 0),  # triangle: 0-1-2
+            (2, 3),
+            (3, 4),
+            (4, 2),  # triangle: 2-3-4
+            (5, 2),
+        ]
+    )
+    assert list(nx.all_triangles(G, nbunch=[5])) == []
+
+
+def test_all_triangles_no_triangles():
+    G = nx.path_graph(4)
+    assert list(nx.all_triangles(G)) == []
+
+
+def test_all_triangles_complete_graph_exact():
+    G = nx.complete_graph(4)
+
+    expected = {
+        frozenset({0, 1, 2}),
+        frozenset({0, 1, 3}),
+        frozenset({0, 2, 3}),
+        frozenset({1, 2, 3}),
+    }
+
+    assert {frozenset(t) for t in nx.all_triangles(G)} == expected
+
+
+def test_all_triangles_directed_graph():
+    G = nx.DiGraph()
+    G.add_edges_from([(0, 1), (1, 2), (2, 0)])
+    with pytest.raises(nx.NetworkXNotImplemented):
+        list(nx.all_triangles(G))
+
+
+@pytest.mark.parametrize("graph_type", [nx.Graph, nx.MultiGraph])
+def test_all_triangles_multiedges(graph_type):
+    G = graph_type()
+    G.add_edges_from([(0, 1), (0, 2), (1, 2), (1, 2)])
+    assert {frozenset(t) for t in nx.all_triangles(G)} == {frozenset({0, 1, 2})}
+
+
+class TestDirectedClustering:
+    def test_clustering(self):
+        G = nx.DiGraph()
+        assert list(nx.clustering(G).values()) == []
+        assert nx.clustering(G) == {}
+
+    def test_path(self):
+        G = nx.path_graph(10, create_using=nx.DiGraph())
+        assert list(nx.clustering(G).values()) == [
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+        ]
+        assert nx.clustering(G) == {
+            0: 0,
+            1: 0,
+            2: 0,
+            3: 0,
+            4: 0,
+            5: 0,
+            6: 0,
+            7: 0,
+            8: 0,
+            9: 0,
+        }
+        assert nx.clustering(G, 0) == 0
+
+    def test_k5(self):
+        G = nx.complete_graph(5, create_using=nx.DiGraph())
+        assert list(nx.clustering(G).values()) == [1, 1, 1, 1, 1]
+        assert nx.average_clustering(G) == 1
+        G.remove_edge(1, 2)
+        assert list(nx.clustering(G).values()) == [
+            11 / 12,
+            1,
+            1,
+            11 / 12,
+            11 / 12,
+        ]
+        assert nx.clustering(G, [1, 4]) == {1: 1, 4: 11 / 12}
+        G.remove_edge(2, 1)
+        assert list(nx.clustering(G).values()) == [
+            5 / 6,
+            1,
+            1,
+            5 / 6,
+            5 / 6,
+        ]
+        assert nx.clustering(G, [1, 4]) == {1: 1, 4: 0.83333333333333337}
+        assert nx.clustering(G, 4) == 5 / 6
+
+    def test_triangle_and_edge(self):
+        G = nx.cycle_graph(3, create_using=nx.DiGraph())
+        G.add_edge(0, 4)
+        assert nx.clustering(G)[0] == 1 / 6
+
+
+class TestDirectedWeightedClustering:
+    @classmethod
+    def setup_class(cls):
+        global np
+        np = pytest.importorskip("numpy")
+
+    def test_clustering(self):
+        G = nx.DiGraph()
+        assert list(nx.clustering(G, weight="weight").values()) == []
+        assert nx.clustering(G) == {}
+
+    def test_path(self):
+        G = nx.path_graph(10, create_using=nx.DiGraph())
+        assert list(nx.clustering(G, weight="weight").values()) == [
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+        ]
+        assert nx.clustering(G, weight="weight") == {
+            0: 0,
+            1: 0,
+            2: 0,
+            3: 0,
+            4: 0,
+            5: 0,
+            6: 0,
+            7: 0,
+            8: 0,
+            9: 0,
+        }
+
+    def test_k5(self):
+        G = nx.complete_graph(5, create_using=nx.DiGraph())
+        assert list(nx.clustering(G, weight="weight").values()) == [1, 1, 1, 1, 1]
+        assert nx.average_clustering(G, weight="weight") == 1
+        G.remove_edge(1, 2)
+        assert list(nx.clustering(G, weight="weight").values()) == [
+            11 / 12,
+            1,
+            1,
+            11 / 12,
+            11 / 12,
+        ]
+        assert nx.clustering(G, [1, 4], weight="weight") == {1: 1, 4: 11 / 12}
+        G.remove_edge(2, 1)
+        assert list(nx.clustering(G, weight="weight").values()) == [
+            5 / 6,
+            1,
+            1,
+            5 / 6,
+            5 / 6,
+        ]
+        assert nx.clustering(G, [1, 4], weight="weight") == {
+            1: 1,
+            4: 0.83333333333333337,
+        }
+
+    def test_triangle_and_edge(self):
+        G = nx.cycle_graph(3, create_using=nx.DiGraph())
+        G.add_edge(0, 4, weight=2)
+        assert nx.clustering(G)[0] == 1 / 6
+        # Relaxed comparisons to allow graphblas-algorithms to pass tests
+        np.testing.assert_allclose(nx.clustering(G, weight="weight")[0], 1 / 12)
+        np.testing.assert_allclose(nx.clustering(G, 0, weight="weight"), 1 / 12)
+
+
+class TestWeightedClustering:
+    @classmethod
+    def setup_class(cls):
+        global np
+        np = pytest.importorskip("numpy")
+
+    def test_clustering(self):
+        G = nx.Graph()
+        assert list(nx.clustering(G, weight="weight").values()) == []
+        assert nx.clustering(G) == {}
+
+    def test_path(self):
+        G = nx.path_graph(10)
+        assert list(nx.clustering(G, weight="weight").values()) == [
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+        ]
+        assert nx.clustering(G, weight="weight") == {
+            0: 0,
+            1: 0,
+            2: 0,
+            3: 0,
+            4: 0,
+            5: 0,
+            6: 0,
+            7: 0,
+            8: 0,
+            9: 0,
+        }
+
+    def test_cubical(self):
+        G = nx.cubical_graph()
+        assert list(nx.clustering(G, weight="weight").values()) == [
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+        ]
+        assert nx.clustering(G, 1) == 0
+        assert list(nx.clustering(G, [1, 2], weight="weight").values()) == [0, 0]
+        assert nx.clustering(G, 1, weight="weight") == 0
+        assert nx.clustering(G, [1, 2], weight="weight") == {1: 0, 2: 0}
+
+    def test_k5(self):
+        G = nx.complete_graph(5)
+        assert list(nx.clustering(G, weight="weight").values()) == [1, 1, 1, 1, 1]
+        assert nx.average_clustering(G, weight="weight") == 1
+        G.remove_edge(1, 2)
+        assert list(nx.clustering(G, weight="weight").values()) == [
+            5 / 6,
+            1,
+            1,
+            5 / 6,
+            5 / 6,
+        ]
+        assert nx.clustering(G, [1, 4], weight="weight") == {
+            1: 1,
+            4: 0.83333333333333337,
+        }
+
+    def test_triangle_and_edge(self):
+        G = nx.cycle_graph(3)
+        G.add_edge(0, 4, weight=2)
+        assert nx.clustering(G)[0] == 1 / 3
+        np.testing.assert_allclose(nx.clustering(G, weight="weight")[0], 1 / 6)
+        np.testing.assert_allclose(nx.clustering(G, 0, weight="weight"), 1 / 6)
+
+    def test_triangle_and_signed_edge(self):
+        G = nx.cycle_graph(3)
+        G.add_edge(0, 1, weight=-1)
+        G.add_edge(3, 0, weight=0)
+        assert nx.clustering(G)[0] == 1 / 3
+        assert nx.clustering(G, weight="weight")[0] == -1 / 3
+
+
+class TestClustering:
+    @classmethod
+    def setup_class(cls):
+        pytest.importorskip("numpy")
+
+    def test_clustering(self):
+        G = nx.Graph()
+        assert list(nx.clustering(G).values()) == []
+        assert nx.clustering(G) == {}
+
+    def test_path(self):
+        G = nx.path_graph(10)
+        assert list(nx.clustering(G).values()) == [
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+        ]
+        assert nx.clustering(G) == {
+            0: 0,
+            1: 0,
+            2: 0,
+            3: 0,
+            4: 0,
+            5: 0,
+            6: 0,
+            7: 0,
+            8: 0,
+            9: 0,
+        }
+
+    def test_cubical(self):
+        G = nx.cubical_graph()
+        assert list(nx.clustering(G).values()) == [0, 0, 0, 0, 0, 0, 0, 0]
+        assert nx.clustering(G, 1) == 0
+        assert list(nx.clustering(G, [1, 2]).values()) == [0, 0]
+        assert nx.clustering(G, 1) == 0
+        assert nx.clustering(G, [1, 2]) == {1: 0, 2: 0}
+
+    def test_k5(self):
+        G = nx.complete_graph(5)
+        assert list(nx.clustering(G).values()) == [1, 1, 1, 1, 1]
+        assert nx.average_clustering(G) == 1
+        G.remove_edge(1, 2)
+        assert list(nx.clustering(G).values()) == [
+            5 / 6,
+            1,
+            1,
+            5 / 6,
+            5 / 6,
+        ]
+        assert nx.clustering(G, [1, 4]) == {1: 1, 4: 0.83333333333333337}
+
+    def test_k5_signed(self):
+        G = nx.complete_graph(5)
+        assert list(nx.clustering(G).values()) == [1, 1, 1, 1, 1]
+        assert nx.average_clustering(G) == 1
+        G.remove_edge(1, 2)
+        G.add_edge(0, 1, weight=-1)
+        assert list(nx.clustering(G, weight="weight").values()) == [
+            1 / 6,
+            -1 / 3,
+            1,
+            3 / 6,
+            3 / 6,
+        ]
+
+
+class TestTransitivity:
+    def test_transitivity(self):
+        G = nx.Graph()
+        assert nx.transitivity(G) == 0
+
+    def test_path(self):
+        G = nx.path_graph(10)
+        assert nx.transitivity(G) == 0
+
+    def test_cubical(self):
+        G = nx.cubical_graph()
+        assert nx.transitivity(G) == 0
+
+    def test_k5(self):
+        G = nx.complete_graph(5)
+        assert nx.transitivity(G) == 1
+        G.remove_edge(1, 2)
+        assert nx.transitivity(G) == 0.875
+
+
+class TestSquareClustering:
+    def test_clustering(self):
+        G = nx.Graph()
+        assert list(nx.square_clustering(G).values()) == []
+        assert nx.square_clustering(G) == {}
+
+    def test_path(self):
+        G = nx.path_graph(10)
+        assert list(nx.square_clustering(G).values()) == [
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+            0,
+        ]
+        assert nx.square_clustering(G) == {
+            0: 0,
+            1: 0,
+            2: 0,
+            3: 0,
+            4: 0,
+            5: 0,
+            6: 0,
+            7: 0,
+            8: 0,
+            9: 0,
+        }
+
+    def test_cubical(self):
+        G = nx.cubical_graph()
+        assert list(nx.square_clustering(G).values()) == [
+            1 / 3,
+            1 / 3,
+            1 / 3,
+            1 / 3,
+            1 / 3,
+            1 / 3,
+            1 / 3,
+            1 / 3,
+        ]
+        assert list(nx.square_clustering(G, [1, 2]).values()) == [1 / 3, 1 / 3]
+        assert nx.square_clustering(G, [1])[1] == 1 / 3
+        assert nx.square_clustering(G, 1) == 1 / 3
+        assert nx.square_clustering(G, [1, 2]) == {1: 1 / 3, 2: 1 / 3}
+
+    def test_k5(self):
+        G = nx.complete_graph(5)
+        assert list(nx.square_clustering(G).values()) == [1, 1, 1, 1, 1]
+
+    def test_bipartite_k5(self):
+        G = nx.complete_bipartite_graph(5, 5)
+        assert list(nx.square_clustering(G).values()) == [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
+
+    def test_lind_square_clustering(self):
+        """Test C4 for figure 1 Lind et al (2005)"""
+        G = nx.Graph(
+            [
+                (1, 2),
+                (1, 3),
+                (1, 6),
+                (1, 7),
+                (2, 4),
+                (2, 5),
+                (3, 4),
+                (3, 5),
+                (6, 7),
+                (7, 8),
+                (6, 8),
+                (7, 9),
+                (7, 10),
+                (6, 11),
+                (6, 12),
+                (2, 13),
+                (2, 14),
+                (3, 15),
+                (3, 16),
+            ]
+        )
+        G1 = G.subgraph([1, 2, 3, 4, 5, 13, 14, 15, 16])
+        G2 = G.subgraph([1, 6, 7, 8, 9, 10, 11, 12])
+        assert nx.square_clustering(G, [1])[1] == 3 / 43
+        assert nx.square_clustering(G1, [1])[1] == 2 / 6
+        assert nx.square_clustering(G2, [1])[1] == 1 / 5
+
+    def test_peng_square_clustering(self):
+        """Test eq2 for figure 1 Peng et al (2008)"""
+        # Example graph from figure 1b
+        G = nx.Graph([(1, 2), (1, 3), (2, 4), (3, 4), (3, 5), (3, 6)])
+        # From table 1, row 2
+        expected = {1: 1 / 3, 2: 1, 3: 0.2, 4: 1 / 3, 5: 0, 6: 0}
+        assert nx.square_clustering(G) == expected
+
+    def test_self_loops_square_clustering(self):
+        G = nx.path_graph(5)
+        assert nx.square_clustering(G) == {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}
+        G.add_edges_from([(0, 0), (1, 1), (2, 2)])
+        assert nx.square_clustering(G) == {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}
+
+
+class TestAverageClustering:
+    @classmethod
+    def setup_class(cls):
+        pytest.importorskip("numpy")
+
+    def test_empty(self):
+        G = nx.Graph()
+        with pytest.raises(ZeroDivisionError):
+            nx.average_clustering(G)
+
+    def test_average_clustering(self):
+        G = nx.cycle_graph(3)
+        G.add_edge(2, 3)
+        assert nx.average_clustering(G) == (1 + 1 + 1 / 3) / 4
+        assert nx.average_clustering(G, count_zeros=True) == (1 + 1 + 1 / 3) / 4
+        assert nx.average_clustering(G, count_zeros=False) == (1 + 1 + 1 / 3) / 3
+        assert nx.average_clustering(G, [1, 2, 3]) == (1 + 1 / 3) / 3
+        assert nx.average_clustering(G, [1, 2, 3], count_zeros=True) == (1 + 1 / 3) / 3
+        assert nx.average_clustering(G, [1, 2, 3], count_zeros=False) == (1 + 1 / 3) / 2
+
+    def test_average_clustering_signed(self):
+        G = nx.cycle_graph(3)
+        G.add_edge(2, 3)
+        G.add_edge(0, 1, weight=-1)
+        assert nx.average_clustering(G, weight="weight") == (-1 - 1 - 1 / 3) / 4
+        assert (
+            nx.average_clustering(G, weight="weight", count_zeros=True)
+            == (-1 - 1 - 1 / 3) / 4
+        )
+        assert (
+            nx.average_clustering(G, weight="weight", count_zeros=False)
+            == (-1 - 1 - 1 / 3) / 3
+        )
+
+
+class TestDirectedAverageClustering:
+    @classmethod
+    def setup_class(cls):
+        pytest.importorskip("numpy")
+
+    def test_empty(self):
+        G = nx.DiGraph()
+        with pytest.raises(ZeroDivisionError):
+            nx.average_clustering(G)
+
+    def test_average_clustering(self):
+        G = nx.cycle_graph(3, create_using=nx.DiGraph())
+        G.add_edge(2, 3)
+        assert nx.average_clustering(G) == (1 + 1 + 1 / 3) / 8
+        assert nx.average_clustering(G, count_zeros=True) == (1 + 1 + 1 / 3) / 8
+        assert nx.average_clustering(G, count_zeros=False) == (1 + 1 + 1 / 3) / 6
+        assert nx.average_clustering(G, [1, 2, 3]) == (1 + 1 / 3) / 6
+        assert nx.average_clustering(G, [1, 2, 3], count_zeros=True) == (1 + 1 / 3) / 6
+        assert nx.average_clustering(G, [1, 2, 3], count_zeros=False) == (1 + 1 / 3) / 4
+
+
+class TestGeneralizedDegree:
+    def test_generalized_degree(self):
+        G = nx.Graph()
+        assert nx.generalized_degree(G) == {}
+
+    def test_path(self):
+        G = nx.path_graph(5)
+        assert nx.generalized_degree(G, 0) == {0: 1}
+        assert nx.generalized_degree(G, 1) == {0: 2}
+
+    def test_cubical(self):
+        G = nx.cubical_graph()
+        assert nx.generalized_degree(G, 0) == {0: 3}
+
+    def test_k5(self):
+        G = nx.complete_graph(5)
+        assert nx.generalized_degree(G, 0) == {3: 4}
+        G.remove_edge(0, 1)
+        assert nx.generalized_degree(G, 0) == {2: 3}
+        assert nx.generalized_degree(G, [1, 2]) == {1: {2: 3}, 2: {2: 2, 3: 2}}
+        assert nx.generalized_degree(G) == {
+            0: {2: 3},
+            1: {2: 3},
+            2: {2: 2, 3: 2},
+            3: {2: 2, 3: 2},
+            4: {2: 2, 3: 2},
+        }
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_communicability.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_communicability.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f447094548415c089710b9b62ac4d73a27efeb5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_communicability.py
@@ -0,0 +1,80 @@
+from collections import defaultdict
+
+import pytest
+
+pytest.importorskip("numpy")
+pytest.importorskip("scipy")
+
+import networkx as nx
+from networkx.algorithms.communicability_alg import communicability, communicability_exp
+
+
+class TestCommunicability:
+    def test_communicability(self):
+        answer = {
+            0: {0: 1.5430806348152435, 1: 1.1752011936438012},
+            1: {0: 1.1752011936438012, 1: 1.5430806348152435},
+        }
+        #        answer={(0, 0): 1.5430806348152435,
+        #                (0, 1): 1.1752011936438012,
+        #                (1, 0): 1.1752011936438012,
+        #                (1, 1): 1.5430806348152435}
+
+        result = communicability(nx.path_graph(2))
+        for k1, val in result.items():
+            for k2 in val:
+                assert answer[k1][k2] == pytest.approx(result[k1][k2], abs=1e-7)
+
+    def test_communicability2(self):
+        answer_orig = {
+            ("1", "1"): 1.6445956054135658,
+            ("1", "Albert"): 0.7430186221096251,
+            ("1", "Aric"): 0.7430186221096251,
+            ("1", "Dan"): 1.6208126320442937,
+            ("1", "Franck"): 0.42639707170035257,
+            ("Albert", "1"): 0.7430186221096251,
+            ("Albert", "Albert"): 2.4368257358712189,
+            ("Albert", "Aric"): 1.4368257358712191,
+            ("Albert", "Dan"): 2.0472097037446453,
+            ("Albert", "Franck"): 1.8340111678944691,
+            ("Aric", "1"): 0.7430186221096251,
+            ("Aric", "Albert"): 1.4368257358712191,
+            ("Aric", "Aric"): 2.4368257358712193,
+            ("Aric", "Dan"): 2.0472097037446457,
+            ("Aric", "Franck"): 1.8340111678944691,
+            ("Dan", "1"): 1.6208126320442937,
+            ("Dan", "Albert"): 2.0472097037446453,
+            ("Dan", "Aric"): 2.0472097037446457,
+            ("Dan", "Dan"): 3.1306328496328168,
+            ("Dan", "Franck"): 1.4860372442192515,
+            ("Franck", "1"): 0.42639707170035257,
+            ("Franck", "Albert"): 1.8340111678944691,
+            ("Franck", "Aric"): 1.8340111678944691,
+            ("Franck", "Dan"): 1.4860372442192515,
+            ("Franck", "Franck"): 2.3876142275231915,
+        }
+
+        answer = defaultdict(dict)
+        for (k1, k2), v in answer_orig.items():
+            answer[k1][k2] = v
+
+        G1 = nx.Graph(
+            [
+                ("Franck", "Aric"),
+                ("Aric", "Dan"),
+                ("Dan", "Albert"),
+                ("Albert", "Franck"),
+                ("Dan", "1"),
+                ("Franck", "Albert"),
+            ]
+        )
+
+        result = communicability(G1)
+        for k1, val in result.items():
+            for k2 in val:
+                assert answer[k1][k2] == pytest.approx(result[k1][k2], abs=1e-7)
+
+        result = communicability_exp(G1)
+        for k1, val in result.items():
+            for k2 in val:
+                assert answer[k1][k2] == pytest.approx(result[k1][k2], abs=1e-7)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_core.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_core.py
new file mode 100644
index 0000000000000000000000000000000000000000..7cbaf759be2ae91cd053629f73353e33bd3a5ee5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_core.py
@@ -0,0 +1,266 @@
+import pytest
+
+import networkx as nx
+from networkx.utils import nodes_equal
+
+
+class TestCore:
+    @classmethod
+    def setup_class(cls):
+        # G is the example graph in Figure 1 from Batagelj and
+        # Zaversnik's paper titled An O(m) Algorithm for Cores
+        # Decomposition of Networks, 2003,
+        # http://arXiv.org/abs/cs/0310049.  With nodes labeled as
+        # shown, the 3-core is given by nodes 1-8, the 2-core by nodes
+        # 9-16, the 1-core by nodes 17-20 and node 21 is in the
+        # 0-core.
+        t1 = nx.convert_node_labels_to_integers(nx.tetrahedral_graph(), 1)
+        t2 = nx.convert_node_labels_to_integers(t1, 5)
+        G = nx.union(t1, t2)
+        G.add_edges_from(
+            [
+                (3, 7),
+                (2, 11),
+                (11, 5),
+                (11, 12),
+                (5, 12),
+                (12, 19),
+                (12, 18),
+                (3, 9),
+                (7, 9),
+                (7, 10),
+                (9, 10),
+                (9, 20),
+                (17, 13),
+                (13, 14),
+                (14, 15),
+                (15, 16),
+                (16, 13),
+            ]
+        )
+        G.add_node(21)
+        cls.G = G
+
+        # Create the graph H resulting from the degree sequence
+        # [0, 1, 2, 2, 2, 2, 3] when using the Havel-Hakimi algorithm.
+
+        degseq = [0, 1, 2, 2, 2, 2, 3]
+        H = nx.havel_hakimi_graph(degseq)
+        mapping = {6: 0, 0: 1, 4: 3, 5: 6, 3: 4, 1: 2, 2: 5}
+        cls.H = nx.relabel_nodes(H, mapping)
+
+    def test_trivial(self):
+        """Empty graph"""
+        G = nx.Graph()
+        assert nx.core_number(G) == {}
+
+    def test_core_number(self):
+        core = nx.core_number(self.G)
+        nodes_by_core = [sorted(n for n in core if core[n] == val) for val in range(4)]
+        assert nodes_equal(nodes_by_core[0], [21])
+        assert nodes_equal(nodes_by_core[1], [17, 18, 19, 20])
+        assert nodes_equal(nodes_by_core[2], [9, 10, 11, 12, 13, 14, 15, 16])
+        assert nodes_equal(nodes_by_core[3], [1, 2, 3, 4, 5, 6, 7, 8])
+
+    def test_core_number2(self):
+        core = nx.core_number(self.H)
+        nodes_by_core = [sorted(n for n in core if core[n] == val) for val in range(3)]
+        assert nodes_equal(nodes_by_core[0], [0])
+        assert nodes_equal(nodes_by_core[1], [1, 3])
+        assert nodes_equal(nodes_by_core[2], [2, 4, 5, 6])
+
+    def test_core_number_multigraph(self):
+        G = nx.complete_graph(3)
+        G = nx.MultiGraph(G)
+        G.add_edge(1, 2)
+        with pytest.raises(
+            nx.NetworkXNotImplemented, match="not implemented for multigraph type"
+        ):
+            nx.core_number(G)
+
+    def test_core_number_self_loop(self):
+        G = nx.cycle_graph(3)
+        G.add_edge(0, 0)
+        with pytest.raises(
+            nx.NetworkXNotImplemented, match="Input graph has self loops"
+        ):
+            nx.core_number(G)
+
+    def test_directed_core_number(self):
+        """core number had a bug for directed graphs found in issue #1959"""
+        # small example where too timid edge removal can make cn[2] = 3
+        G = nx.DiGraph()
+        edges = [(1, 2), (2, 1), (2, 3), (2, 4), (3, 4), (4, 3)]
+        G.add_edges_from(edges)
+        assert nx.core_number(G) == {1: 2, 2: 2, 3: 2, 4: 2}
+        # small example where too aggressive edge removal can make cn[2] = 2
+        more_edges = [(1, 5), (3, 5), (4, 5), (3, 6), (4, 6), (5, 6)]
+        G.add_edges_from(more_edges)
+        assert nx.core_number(G) == {1: 3, 2: 3, 3: 3, 4: 3, 5: 3, 6: 3}
+
+    def test_main_core(self):
+        main_core_subgraph = nx.k_core(self.H)
+        assert sorted(main_core_subgraph.nodes()) == [2, 4, 5, 6]
+
+    def test_k_core(self):
+        # k=0
+        k_core_subgraph = nx.k_core(self.H, k=0)
+        assert sorted(k_core_subgraph.nodes()) == sorted(self.H.nodes())
+        # k=1
+        k_core_subgraph = nx.k_core(self.H, k=1)
+        assert sorted(k_core_subgraph.nodes()) == [1, 2, 3, 4, 5, 6]
+        # k = 2
+        k_core_subgraph = nx.k_core(self.H, k=2)
+        assert sorted(k_core_subgraph.nodes()) == [2, 4, 5, 6]
+
+    def test_k_core_multigraph(self):
+        core_number = nx.core_number(self.H)
+        H = nx.MultiGraph(self.H)
+        with pytest.raises(nx.NetworkXNotImplemented):
+            nx.k_core(H, k=0, core_number=core_number)
+
+    def test_main_crust(self):
+        main_crust_subgraph = nx.k_crust(self.H)
+        assert sorted(main_crust_subgraph.nodes()) == [0, 1, 3]
+
+    def test_k_crust(self):
+        # k = 0
+        k_crust_subgraph = nx.k_crust(self.H, k=2)
+        assert sorted(k_crust_subgraph.nodes()) == sorted(self.H.nodes())
+        # k=1
+        k_crust_subgraph = nx.k_crust(self.H, k=1)
+        assert sorted(k_crust_subgraph.nodes()) == [0, 1, 3]
+        # k=2
+        k_crust_subgraph = nx.k_crust(self.H, k=0)
+        assert sorted(k_crust_subgraph.nodes()) == [0]
+
+    def test_k_crust_multigraph(self):
+        core_number = nx.core_number(self.H)
+        H = nx.MultiGraph(self.H)
+        with pytest.raises(nx.NetworkXNotImplemented):
+            nx.k_crust(H, k=0, core_number=core_number)
+
+    def test_main_shell(self):
+        main_shell_subgraph = nx.k_shell(self.H)
+        assert sorted(main_shell_subgraph.nodes()) == [2, 4, 5, 6]
+
+    def test_k_shell(self):
+        # k=0
+        k_shell_subgraph = nx.k_shell(self.H, k=2)
+        assert sorted(k_shell_subgraph.nodes()) == [2, 4, 5, 6]
+        # k=1
+        k_shell_subgraph = nx.k_shell(self.H, k=1)
+        assert sorted(k_shell_subgraph.nodes()) == [1, 3]
+        # k=2
+        k_shell_subgraph = nx.k_shell(self.H, k=0)
+        assert sorted(k_shell_subgraph.nodes()) == [0]
+
+    def test_k_shell_multigraph(self):
+        core_number = nx.core_number(self.H)
+        H = nx.MultiGraph(self.H)
+        with pytest.raises(nx.NetworkXNotImplemented):
+            nx.k_shell(H, k=0, core_number=core_number)
+
+    def test_k_corona(self):
+        # k=0
+        k_corona_subgraph = nx.k_corona(self.H, k=2)
+        assert sorted(k_corona_subgraph.nodes()) == [2, 4, 5, 6]
+        # k=1
+        k_corona_subgraph = nx.k_corona(self.H, k=1)
+        assert sorted(k_corona_subgraph.nodes()) == [1]
+        # k=2
+        k_corona_subgraph = nx.k_corona(self.H, k=0)
+        assert sorted(k_corona_subgraph.nodes()) == [0]
+
+    def test_k_corona_multigraph(self):
+        core_number = nx.core_number(self.H)
+        H = nx.MultiGraph(self.H)
+        with pytest.raises(nx.NetworkXNotImplemented):
+            nx.k_corona(H, k=0, core_number=core_number)
+
+    def test_k_truss(self):
+        # k=-1
+        k_truss_subgraph = nx.k_truss(self.G, -1)
+        assert sorted(k_truss_subgraph.nodes()) == list(range(1, 21))
+        # k=0
+        k_truss_subgraph = nx.k_truss(self.G, 0)
+        assert sorted(k_truss_subgraph.nodes()) == list(range(1, 21))
+        # k=1
+        k_truss_subgraph = nx.k_truss(self.G, 1)
+        assert sorted(k_truss_subgraph.nodes()) == list(range(1, 21))
+        # k=2
+        k_truss_subgraph = nx.k_truss(self.G, 2)
+        assert sorted(k_truss_subgraph.nodes()) == list(range(1, 21))
+        # k=3
+        k_truss_subgraph = nx.k_truss(self.G, 3)
+        assert sorted(k_truss_subgraph.nodes()) == list(range(1, 13))
+
+        k_truss_subgraph = nx.k_truss(self.G, 4)
+        assert sorted(k_truss_subgraph.nodes()) == list(range(1, 9))
+
+        k_truss_subgraph = nx.k_truss(self.G, 5)
+        assert sorted(k_truss_subgraph.nodes()) == []
+
+    def test_k_truss_digraph(self):
+        G = nx.complete_graph(3)
+        G = nx.DiGraph(G)
+        G.add_edge(2, 1)
+        with pytest.raises(
+            nx.NetworkXNotImplemented, match="not implemented for directed type"
+        ):
+            nx.k_truss(G, k=1)
+
+    def test_k_truss_multigraph(self):
+        G = nx.complete_graph(3)
+        G = nx.MultiGraph(G)
+        G.add_edge(1, 2)
+        with pytest.raises(
+            nx.NetworkXNotImplemented, match="not implemented for multigraph type"
+        ):
+            nx.k_truss(G, k=1)
+
+    def test_k_truss_self_loop(self):
+        G = nx.cycle_graph(3)
+        G.add_edge(0, 0)
+        with pytest.raises(
+            nx.NetworkXNotImplemented, match="Input graph has self loops"
+        ):
+            nx.k_truss(G, k=1)
+
+    def test_onion_layers(self):
+        layers = nx.onion_layers(self.G)
+        nodes_by_layer = [
+            sorted(n for n in layers if layers[n] == val) for val in range(1, 7)
+        ]
+        assert nodes_equal(nodes_by_layer[0], [21])
+        assert nodes_equal(nodes_by_layer[1], [17, 18, 19, 20])
+        assert nodes_equal(nodes_by_layer[2], [10, 12, 13, 14, 15, 16])
+        assert nodes_equal(nodes_by_layer[3], [9, 11])
+        assert nodes_equal(nodes_by_layer[4], [1, 2, 4, 5, 6, 8])
+        assert nodes_equal(nodes_by_layer[5], [3, 7])
+
+    def test_onion_digraph(self):
+        G = nx.complete_graph(3)
+        G = nx.DiGraph(G)
+        G.add_edge(2, 1)
+        with pytest.raises(
+            nx.NetworkXNotImplemented, match="not implemented for directed type"
+        ):
+            nx.onion_layers(G)
+
+    def test_onion_multigraph(self):
+        G = nx.complete_graph(3)
+        G = nx.MultiGraph(G)
+        G.add_edge(1, 2)
+        with pytest.raises(
+            nx.NetworkXNotImplemented, match="not implemented for multigraph type"
+        ):
+            nx.onion_layers(G)
+
+    def test_onion_self_loop(self):
+        G = nx.cycle_graph(3)
+        G.add_edge(0, 0)
+        with pytest.raises(
+            nx.NetworkXNotImplemented, match="Input graph contains self loops"
+        ):
+            nx.onion_layers(G)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_covering.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_covering.py
new file mode 100644
index 0000000000000000000000000000000000000000..b2f97a866b0e09c199c2edb9f40f20986caa8fbc
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_covering.py
@@ -0,0 +1,85 @@
+import pytest
+
+import networkx as nx
+
+
+class TestMinEdgeCover:
+    """Tests for :func:`networkx.algorithms.min_edge_cover`"""
+
+    def test_empty_graph(self):
+        G = nx.Graph()
+        assert nx.min_edge_cover(G) == set()
+
+    def test_graph_with_loop(self):
+        G = nx.Graph()
+        G.add_edge(0, 0)
+        assert nx.min_edge_cover(G) == {(0, 0)}
+
+    def test_graph_with_isolated_v(self):
+        G = nx.Graph()
+        G.add_node(1)
+        with pytest.raises(
+            nx.NetworkXException,
+            match="Graph has a node with no edge incident on it, so no edge cover exists.",
+        ):
+            nx.min_edge_cover(G)
+
+    def test_graph_single_edge(self):
+        G = nx.Graph([(0, 1)])
+        assert nx.min_edge_cover(G) in ({(0, 1)}, {(1, 0)})
+
+    def test_graph_two_edge_path(self):
+        G = nx.path_graph(3)
+        min_cover = nx.min_edge_cover(G)
+        assert len(min_cover) == 2
+        for u, v in G.edges:
+            assert (u, v) in min_cover or (v, u) in min_cover
+
+    def test_bipartite_explicit(self):
+        G = nx.Graph()
+        G.add_nodes_from([1, 2, 3, 4], bipartite=0)
+        G.add_nodes_from(["a", "b", "c"], bipartite=1)
+        G.add_edges_from([(1, "a"), (1, "b"), (2, "b"), (2, "c"), (3, "c"), (4, "a")])
+        # Use bipartite method by prescribing the algorithm
+        min_cover = nx.min_edge_cover(
+            G, nx.algorithms.bipartite.matching.eppstein_matching
+        )
+        assert nx.is_edge_cover(G, min_cover)
+        assert len(min_cover) == 8
+        # Use the default method which is not specialized for bipartite
+        min_cover2 = nx.min_edge_cover(G)
+        assert nx.is_edge_cover(G, min_cover2)
+        assert len(min_cover2) == 4
+
+    def test_complete_graph_even(self):
+        G = nx.complete_graph(10)
+        min_cover = nx.min_edge_cover(G)
+        assert nx.is_edge_cover(G, min_cover)
+        assert len(min_cover) == 5
+
+    def test_complete_graph_odd(self):
+        G = nx.complete_graph(11)
+        min_cover = nx.min_edge_cover(G)
+        assert nx.is_edge_cover(G, min_cover)
+        assert len(min_cover) == 6
+
+
+class TestIsEdgeCover:
+    """Tests for :func:`networkx.algorithms.is_edge_cover`"""
+
+    def test_empty_graph(self):
+        G = nx.Graph()
+        assert nx.is_edge_cover(G, set())
+
+    def test_graph_with_loop(self):
+        G = nx.Graph()
+        G.add_edge(1, 1)
+        assert nx.is_edge_cover(G, {(1, 1)})
+
+    def test_graph_single_edge(self):
+        G = nx.Graph()
+        G.add_edge(0, 1)
+        assert nx.is_edge_cover(G, {(0, 0), (1, 1)})
+        assert nx.is_edge_cover(G, {(0, 1), (1, 0)})
+        assert nx.is_edge_cover(G, {(0, 1)})
+        assert not nx.is_edge_cover(G, {(0, 0)})
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_cuts.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_cuts.py
new file mode 100644
index 0000000000000000000000000000000000000000..923efa502acc623650f36ff41e72884e5e508bc9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_cuts.py
@@ -0,0 +1,171 @@
+"""Unit tests for the :mod:`networkx.algorithms.cuts` module."""
+
+import networkx as nx
+
+
+class TestCutSize:
+    """Unit tests for the :func:`~networkx.cut_size` function."""
+
+    def test_symmetric(self):
+        """Tests that the cut size is symmetric."""
+        G = nx.barbell_graph(3, 0)
+        S = {0, 1, 4}
+        T = {2, 3, 5}
+        assert nx.cut_size(G, S, T) == 4
+        assert nx.cut_size(G, T, S) == 4
+
+    def test_single_edge(self):
+        """Tests for a cut of a single edge."""
+        G = nx.barbell_graph(3, 0)
+        S = {0, 1, 2}
+        T = {3, 4, 5}
+        assert nx.cut_size(G, S, T) == 1
+        assert nx.cut_size(G, T, S) == 1
+
+    def test_directed(self):
+        """Tests that each directed edge is counted once in the cut."""
+        G = nx.barbell_graph(3, 0).to_directed()
+        S = {0, 1, 2}
+        T = {3, 4, 5}
+        assert nx.cut_size(G, S, T) == 2
+        assert nx.cut_size(G, T, S) == 2
+
+    def test_directed_symmetric(self):
+        """Tests that a cut in a directed graph is symmetric."""
+        G = nx.barbell_graph(3, 0).to_directed()
+        S = {0, 1, 4}
+        T = {2, 3, 5}
+        assert nx.cut_size(G, S, T) == 8
+        assert nx.cut_size(G, T, S) == 8
+
+    def test_multigraph(self):
+        """Tests that parallel edges are each counted for a cut."""
+        G = nx.MultiGraph(["ab", "ab"])
+        assert nx.cut_size(G, {"a"}, {"b"}) == 2
+
+
+class TestVolume:
+    """Unit tests for the :func:`~networkx.volume` function."""
+
+    def test_graph(self):
+        G = nx.cycle_graph(4)
+        assert nx.volume(G, {0, 1}) == 4
+
+    def test_digraph(self):
+        G = nx.DiGraph([(0, 1), (1, 2), (2, 3), (3, 0)])
+        assert nx.volume(G, {0, 1}) == 2
+
+    def test_multigraph(self):
+        edges = list(nx.cycle_graph(4).edges())
+        G = nx.MultiGraph(edges * 2)
+        assert nx.volume(G, {0, 1}) == 8
+
+    def test_multidigraph(self):
+        edges = [(0, 1), (1, 2), (2, 3), (3, 0)]
+        G = nx.MultiDiGraph(edges * 2)
+        assert nx.volume(G, {0, 1}) == 4
+
+    def test_barbell(self):
+        G = nx.barbell_graph(3, 0)
+        assert nx.volume(G, {0, 1, 2}) == 7
+        assert nx.volume(G, {3, 4, 5}) == 7
+
+
+class TestNormalizedCutSize:
+    """Unit tests for the :func:`~networkx.normalized_cut_size` function."""
+
+    def test_graph(self):
+        G = nx.path_graph(4)
+        S = {1, 2}
+        T = set(G) - S
+        size = nx.normalized_cut_size(G, S, T)
+        # The cut looks like this: o-{-o--o-}-o
+        expected = 2 * ((1 / 4) + (1 / 2))
+        assert expected == size
+        # Test with no input T
+        assert expected == nx.normalized_cut_size(G, S)
+
+    def test_directed(self):
+        G = nx.DiGraph([(0, 1), (1, 2), (2, 3)])
+        S = {1, 2}
+        T = set(G) - S
+        size = nx.normalized_cut_size(G, S, T)
+        # The cut looks like this: o-{->o-->o-}->o
+        expected = 2 * ((1 / 2) + (1 / 1))
+        assert expected == size
+        # Test with no input T
+        assert expected == nx.normalized_cut_size(G, S)
+
+
+class TestConductance:
+    """Unit tests for the :func:`~networkx.conductance` function."""
+
+    def test_graph(self):
+        G = nx.barbell_graph(5, 0)
+        # Consider the singleton sets containing the "bridge" nodes.
+        # There is only one cut edge, and each set has volume five.
+        S = {4}
+        T = {5}
+        conductance = nx.conductance(G, S, T)
+        expected = 1 / 5
+        assert expected == conductance
+        # Test with no input T
+        G2 = nx.barbell_graph(3, 0)
+        # There is only one cut edge, and each set has volume seven.
+        S2 = {0, 1, 2}
+        assert nx.conductance(G2, S2) == 1 / 7
+
+
+class TestEdgeExpansion:
+    """Unit tests for the :func:`~networkx.edge_expansion` function."""
+
+    def test_graph(self):
+        G = nx.barbell_graph(5, 0)
+        S = set(range(5))
+        T = set(G) - S
+        expansion = nx.edge_expansion(G, S, T)
+        expected = 1 / 5
+        assert expected == expansion
+        # Test with no input T
+        assert expected == nx.edge_expansion(G, S)
+
+
+class TestNodeExpansion:
+    """Unit tests for the :func:`~networkx.node_expansion` function."""
+
+    def test_graph(self):
+        G = nx.path_graph(8)
+        S = {3, 4, 5}
+        expansion = nx.node_expansion(G, S)
+        # The neighborhood of S has cardinality five, and S has
+        # cardinality three.
+        expected = 5 / 3
+        assert expected == expansion
+
+
+class TestBoundaryExpansion:
+    """Unit tests for the :func:`~networkx.boundary_expansion` function."""
+
+    def test_graph(self):
+        G = nx.complete_graph(10)
+        S = set(range(4))
+        expansion = nx.boundary_expansion(G, S)
+        # The node boundary of S has cardinality six, and S has
+        # cardinality three.
+        expected = 6 / 4
+        assert expected == expansion
+
+
+class TestMixingExpansion:
+    """Unit tests for the :func:`~networkx.mixing_expansion` function."""
+
+    def test_graph(self):
+        G = nx.barbell_graph(5, 0)
+        S = set(range(5))
+        T = set(G) - S
+        expansion = nx.mixing_expansion(G, S, T)
+        # There is one cut edge, and the total number of edges in the
+        # graph is twice the total number of edges in a clique of size
+        # five, plus one more for the bridge.
+        expected = 1 / (2 * (5 * 4 + 1))
+        assert expected == expansion
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_cycles.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_cycles.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b43929aae00be120f7fb2cd2780cd7d4ad20b03
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_cycles.py
@@ -0,0 +1,984 @@
+import random
+from itertools import chain, islice, tee
+from math import inf
+
+import pytest
+
+import networkx as nx
+from networkx.algorithms.traversal.edgedfs import FORWARD, REVERSE
+
+
+def check_independent(basis):
+    if len(basis) == 0:
+        return
+
+    np = pytest.importorskip("numpy")
+    sp = pytest.importorskip("scipy")  # Required by incidence_matrix
+
+    H = nx.Graph()
+    for b in basis:
+        nx.add_cycle(H, b)
+    inc = nx.incidence_matrix(H, oriented=True)
+    rank = np.linalg.matrix_rank(inc.toarray(), tol=None, hermitian=False)
+    assert inc.shape[1] - rank == len(basis)
+
+
+class TestCycles:
+    @classmethod
+    def setup_class(cls):
+        G = nx.Graph()
+        nx.add_cycle(G, [0, 1, 2, 3])
+        nx.add_cycle(G, [0, 3, 4, 5])
+        nx.add_cycle(G, [0, 1, 6, 7, 8])
+        G.add_edge(8, 9)
+        cls.G = G
+
+    def is_cyclic_permutation(self, a, b):
+        n = len(a)
+        if len(b) != n:
+            return False
+        l = a + a
+        return any(l[i : i + n] == b for i in range(n))
+
+    def test_cycle_basis(self):
+        G = self.G
+        cy = nx.cycle_basis(G, 0)
+        sort_cy = sorted(sorted(c) for c in cy)
+        assert sort_cy == [[0, 1, 2, 3], [0, 1, 6, 7, 8], [0, 3, 4, 5]]
+        cy = nx.cycle_basis(G, 1)
+        sort_cy = sorted(sorted(c) for c in cy)
+        assert sort_cy == [[0, 1, 2, 3], [0, 1, 6, 7, 8], [0, 3, 4, 5]]
+        cy = nx.cycle_basis(G, 9)
+        sort_cy = sorted(sorted(c) for c in cy)
+        assert sort_cy == [[0, 1, 2, 3], [0, 1, 6, 7, 8], [0, 3, 4, 5]]
+        # test disconnected graphs
+        nx.add_cycle(G, "ABC")
+        cy = nx.cycle_basis(G, 9)
+        sort_cy = sorted(sorted(c) for c in cy[:-1]) + [sorted(cy[-1])]
+        assert sort_cy == [[0, 1, 2, 3], [0, 1, 6, 7, 8], [0, 3, 4, 5], ["A", "B", "C"]]
+
+    def test_cycle_basis2(self):
+        with pytest.raises(nx.NetworkXNotImplemented):
+            G = nx.DiGraph()
+            cy = nx.cycle_basis(G, 0)
+
+    def test_cycle_basis3(self):
+        with pytest.raises(nx.NetworkXNotImplemented):
+            G = nx.MultiGraph()
+            cy = nx.cycle_basis(G, 0)
+
+    def test_cycle_basis_ordered(self):
+        # see gh-6654 replace sets with (ordered) dicts
+        G = nx.cycle_graph(5)
+        G.update(nx.cycle_graph(range(3, 8)))
+        cbG = nx.cycle_basis(G)
+
+        perm = {1: 0, 0: 1}  # switch 0 and 1
+        H = nx.relabel_nodes(G, perm)
+        cbH = [[perm.get(n, n) for n in cyc] for cyc in nx.cycle_basis(H)]
+        assert cbG == cbH
+
+    def test_cycle_basis_self_loop(self):
+        """Tests the function for graphs with self loops"""
+        G = nx.Graph()
+        nx.add_cycle(G, [0, 1, 2, 3])
+        nx.add_cycle(G, [0, 0, 6, 2])
+        cy = nx.cycle_basis(G)
+        sort_cy = sorted(sorted(c) for c in cy)
+        assert sort_cy == [[0], [0, 1, 2], [0, 2, 3], [0, 2, 6]]
+
+    def test_simple_cycles(self):
+        edges = [(0, 0), (0, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2)]
+        G = nx.DiGraph(edges)
+        cc = sorted(nx.simple_cycles(G))
+        ca = [[0], [0, 1, 2], [0, 2], [1, 2], [2]]
+        assert len(cc) == len(ca)
+        for c in cc:
+            assert any(self.is_cyclic_permutation(c, rc) for rc in ca)
+
+    def test_simple_cycles_singleton(self):
+        G = nx.Graph([(0, 0)])  # self-loop
+        assert list(nx.simple_cycles(G)) == [[0]]
+
+    def test_unsortable(self):
+        # this test ensures that graphs whose nodes without an intrinsic
+        # ordering do not cause issues
+        G = nx.DiGraph()
+        nx.add_cycle(G, ["a", 1])
+        c = list(nx.simple_cycles(G))
+        assert len(c) == 1
+
+    def test_simple_cycles_small(self):
+        G = nx.DiGraph()
+        nx.add_cycle(G, [1, 2, 3])
+        c = sorted(nx.simple_cycles(G))
+        assert len(c) == 1
+        assert self.is_cyclic_permutation(c[0], [1, 2, 3])
+        nx.add_cycle(G, [10, 20, 30])
+        cc = sorted(nx.simple_cycles(G))
+        assert len(cc) == 2
+        ca = [[1, 2, 3], [10, 20, 30]]
+        for c in cc:
+            assert any(self.is_cyclic_permutation(c, rc) for rc in ca)
+
+    def test_simple_cycles_empty(self):
+        G = nx.DiGraph()
+        assert list(nx.simple_cycles(G)) == []
+
+    def worst_case_graph(self, k):
+        # see figure 1 in Johnson's paper
+        # this graph has exactly 3k simple cycles
+        G = nx.DiGraph()
+        for n in range(2, k + 2):
+            G.add_edge(1, n)
+            G.add_edge(n, k + 2)
+        G.add_edge(2 * k + 1, 1)
+        for n in range(k + 2, 2 * k + 2):
+            G.add_edge(n, 2 * k + 2)
+            G.add_edge(n, n + 1)
+        G.add_edge(2 * k + 3, k + 2)
+        for n in range(2 * k + 3, 3 * k + 3):
+            G.add_edge(2 * k + 2, n)
+            G.add_edge(n, 3 * k + 3)
+        G.add_edge(3 * k + 3, 2 * k + 2)
+        return G
+
+    def test_worst_case_graph(self):
+        # see figure 1 in Johnson's paper
+        for k in range(3, 10):
+            G = self.worst_case_graph(k)
+            l = len(list(nx.simple_cycles(G)))
+            assert l == 3 * k
+
+    def test_recursive_simple_and_not(self):
+        for k in range(2, 10):
+            G = self.worst_case_graph(k)
+            cc = sorted(nx.simple_cycles(G))
+            rcc = sorted(nx.recursive_simple_cycles(G))
+            assert len(cc) == len(rcc)
+            for c in cc:
+                assert any(self.is_cyclic_permutation(c, r) for r in rcc)
+            for rc in rcc:
+                assert any(self.is_cyclic_permutation(rc, c) for c in cc)
+
+    def test_simple_graph_with_reported_bug(self):
+        G = nx.DiGraph()
+        edges = [
+            (0, 2),
+            (0, 3),
+            (1, 0),
+            (1, 3),
+            (2, 1),
+            (2, 4),
+            (3, 2),
+            (3, 4),
+            (4, 0),
+            (4, 1),
+            (4, 5),
+            (5, 0),
+            (5, 1),
+            (5, 2),
+            (5, 3),
+        ]
+        G.add_edges_from(edges)
+        cc = sorted(nx.simple_cycles(G))
+        assert len(cc) == 26
+        rcc = sorted(nx.recursive_simple_cycles(G))
+        assert len(cc) == len(rcc)
+        for c in cc:
+            assert any(self.is_cyclic_permutation(c, rc) for rc in rcc)
+        for rc in rcc:
+            assert any(self.is_cyclic_permutation(rc, c) for c in cc)
+
+
+def pairwise(iterable):
+    a, b = tee(iterable)
+    next(b, None)
+    return zip(a, b)
+
+
+def cycle_edges(c):
+    return pairwise(chain(c, islice(c, 1)))
+
+
+def directed_cycle_edgeset(c):
+    return frozenset(cycle_edges(c))
+
+
+def undirected_cycle_edgeset(c):
+    if len(c) == 1:
+        return frozenset(cycle_edges(c))
+    return frozenset(map(frozenset, cycle_edges(c)))
+
+
+def multigraph_cycle_edgeset(c):
+    if len(c) <= 2:
+        return frozenset(cycle_edges(c))
+    else:
+        return frozenset(map(frozenset, cycle_edges(c)))
+
+
+class TestCycleEnumeration:
+    @staticmethod
+    def K(n):
+        return nx.complete_graph(n)
+
+    @staticmethod
+    def D(n):
+        return nx.complete_graph(n).to_directed()
+
+    @staticmethod
+    def edgeset_function(g):
+        if g.is_directed():
+            return directed_cycle_edgeset
+        elif g.is_multigraph():
+            return multigraph_cycle_edgeset
+        else:
+            return undirected_cycle_edgeset
+
+    def check_cycle(self, g, c, es, cache, source, original_c, length_bound, chordless):
+        if length_bound is not None and len(c) > length_bound:
+            raise RuntimeError(
+                f"computed cycle {original_c} exceeds length bound {length_bound}"
+            )
+        if source == "computed":
+            if es in cache:
+                raise RuntimeError(
+                    f"computed cycle {original_c} has already been found!"
+                )
+            else:
+                cache[es] = tuple(original_c)
+        else:
+            if es in cache:
+                cache.pop(es)
+            else:
+                raise RuntimeError(f"expected cycle {original_c} was not computed")
+
+        if not all(g.has_edge(*e) for e in es):
+            raise RuntimeError(
+                f"{source} claimed cycle {original_c} is not a cycle of g"
+            )
+        if chordless and len(g.subgraph(c).edges) > len(c):
+            raise RuntimeError(f"{source} cycle {original_c} is not chordless")
+
+    def check_cycle_algorithm(
+        self,
+        g,
+        expected_cycles,
+        length_bound=None,
+        chordless=False,
+        algorithm=None,
+    ):
+        if algorithm is None:
+            algorithm = nx.chordless_cycles if chordless else nx.simple_cycles
+
+        # note: we shuffle the labels of g to rule out accidentally-correct
+        # behavior which occurred during the development of chordless cycle
+        # enumeration algorithms
+
+        relabel = list(range(len(g)))
+        rng = random.Random(42)
+        rng.shuffle(relabel)
+        label = dict(zip(g, relabel))
+        unlabel = dict(zip(relabel, g))
+        h = nx.relabel_nodes(g, label, copy=True)
+
+        edgeset = self.edgeset_function(h)
+
+        params = {}
+        if length_bound is not None:
+            params["length_bound"] = length_bound
+
+        cycle_cache = {}
+        for c in algorithm(h, **params):
+            original_c = [unlabel[x] for x in c]
+            es = edgeset(c)
+            self.check_cycle(
+                h, c, es, cycle_cache, "computed", original_c, length_bound, chordless
+            )
+
+        if isinstance(expected_cycles, int):
+            if len(cycle_cache) != expected_cycles:
+                raise RuntimeError(
+                    f"expected {expected_cycles} cycles, got {len(cycle_cache)}"
+                )
+            return
+        for original_c in expected_cycles:
+            c = [label[x] for x in original_c]
+            es = edgeset(c)
+            self.check_cycle(
+                h, c, es, cycle_cache, "expected", original_c, length_bound, chordless
+            )
+
+        if len(cycle_cache):
+            for c in cycle_cache.values():
+                raise RuntimeError(
+                    f"computed cycle {c} is valid but not in the expected cycle set!"
+                )
+
+    def check_cycle_enumeration_integer_sequence(
+        self,
+        g_family,
+        cycle_counts,
+        length_bound=None,
+        chordless=False,
+        algorithm=None,
+    ):
+        for g, num_cycles in zip(g_family, cycle_counts):
+            self.check_cycle_algorithm(
+                g,
+                num_cycles,
+                length_bound=length_bound,
+                chordless=chordless,
+                algorithm=algorithm,
+            )
+
+    def test_directed_chordless_cycle_digons(self):
+        g = nx.DiGraph()
+        nx.add_cycle(g, range(5))
+        nx.add_cycle(g, range(5)[::-1])
+        g.add_edge(0, 0)
+        expected_cycles = [(0,), (1, 2), (2, 3), (3, 4)]
+        self.check_cycle_algorithm(g, expected_cycles, chordless=True)
+
+        self.check_cycle_algorithm(g, expected_cycles, chordless=True, length_bound=2)
+
+        expected_cycles = [c for c in expected_cycles if len(c) < 2]
+        self.check_cycle_algorithm(g, expected_cycles, chordless=True, length_bound=1)
+
+    def test_chordless_cycles_multigraph_self_loops(self):
+        G = nx.MultiGraph([(1, 1), (2, 2), (1, 2), (1, 2)])
+        expected_cycles = [[1], [2]]
+        self.check_cycle_algorithm(G, expected_cycles, chordless=True)
+
+        G.add_edges_from([(2, 3), (3, 4), (3, 4), (1, 3)])
+        expected_cycles = [[1], [2], [3, 4]]
+        self.check_cycle_algorithm(G, expected_cycles, chordless=True)
+
+    def test_directed_chordless_cycle_undirected(self):
+        g = nx.DiGraph([(1, 2), (2, 3), (3, 4), (4, 5), (5, 0), (5, 1), (0, 2)])
+        expected_cycles = [(0, 2, 3, 4, 5), (1, 2, 3, 4, 5)]
+        self.check_cycle_algorithm(g, expected_cycles, chordless=True)
+
+        g = nx.DiGraph()
+        nx.add_cycle(g, range(5))
+        nx.add_cycle(g, range(4, 9))
+        g.add_edge(7, 3)
+        expected_cycles = [(0, 1, 2, 3, 4), (3, 4, 5, 6, 7), (4, 5, 6, 7, 8)]
+        self.check_cycle_algorithm(g, expected_cycles, chordless=True)
+
+        g.add_edge(3, 7)
+        expected_cycles = [(0, 1, 2, 3, 4), (3, 7), (4, 5, 6, 7, 8)]
+        self.check_cycle_algorithm(g, expected_cycles, chordless=True)
+
+        expected_cycles = [(3, 7)]
+        self.check_cycle_algorithm(g, expected_cycles, chordless=True, length_bound=4)
+
+        g.remove_edge(7, 3)
+        expected_cycles = [(0, 1, 2, 3, 4), (4, 5, 6, 7, 8)]
+        self.check_cycle_algorithm(g, expected_cycles, chordless=True)
+
+        g = nx.DiGraph((i, j) for i in range(10) for j in range(i))
+        expected_cycles = []
+        self.check_cycle_algorithm(g, expected_cycles, chordless=True)
+
+    def test_chordless_cycles_directed(self):
+        G = nx.DiGraph()
+        nx.add_cycle(G, range(5))
+        nx.add_cycle(G, range(4, 12))
+        expected = [[*range(5)], [*range(4, 12)]]
+        self.check_cycle_algorithm(G, expected, chordless=True)
+        self.check_cycle_algorithm(
+            G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
+        )
+
+        G.add_edge(7, 3)
+        expected.append([*range(3, 8)])
+        self.check_cycle_algorithm(G, expected, chordless=True)
+        self.check_cycle_algorithm(
+            G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
+        )
+
+        G.add_edge(3, 7)
+        expected[-1] = [7, 3]
+        self.check_cycle_algorithm(G, expected, chordless=True)
+        self.check_cycle_algorithm(
+            G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
+        )
+
+        expected.pop()
+        G.remove_edge(7, 3)
+        self.check_cycle_algorithm(G, expected, chordless=True)
+        self.check_cycle_algorithm(
+            G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
+        )
+
+    def test_directed_chordless_cycle_diclique(self):
+        g_family = [self.D(n) for n in range(10)]
+        expected_cycles = [(n * n - n) // 2 for n in range(10)]
+        self.check_cycle_enumeration_integer_sequence(
+            g_family, expected_cycles, chordless=True
+        )
+
+        expected_cycles = [(n * n - n) // 2 for n in range(10)]
+        self.check_cycle_enumeration_integer_sequence(
+            g_family, expected_cycles, length_bound=2
+        )
+
+    def test_directed_chordless_loop_blockade(self):
+        g = nx.DiGraph((i, i) for i in range(10))
+        nx.add_cycle(g, range(10))
+        expected_cycles = [(i,) for i in range(10)]
+        self.check_cycle_algorithm(g, expected_cycles, chordless=True)
+
+        self.check_cycle_algorithm(g, expected_cycles, length_bound=1)
+
+        g = nx.MultiDiGraph(g)
+        g.add_edges_from((i, i) for i in range(0, 10, 2))
+        expected_cycles = [(i,) for i in range(1, 10, 2)]
+        self.check_cycle_algorithm(g, expected_cycles, chordless=True)
+
+    def test_simple_cycles_notable_clique_sequences(self):
+        # A000292: Number of labeled graphs on n+3 nodes that are triangles.
+        g_family = [self.K(n) for n in range(2, 12)]
+        expected = [0, 1, 4, 10, 20, 35, 56, 84, 120, 165, 220]
+        self.check_cycle_enumeration_integer_sequence(
+            g_family, expected, length_bound=3
+        )
+
+        def triangles(g, **kwargs):
+            yield from (c for c in nx.simple_cycles(g, **kwargs) if len(c) == 3)
+
+        # directed complete graphs have twice as many triangles thanks to reversal
+        g_family = [self.D(n) for n in range(2, 12)]
+        expected = [2 * e for e in expected]
+        self.check_cycle_enumeration_integer_sequence(
+            g_family, expected, length_bound=3, algorithm=triangles
+        )
+
+        def four_cycles(g, **kwargs):
+            yield from (c for c in nx.simple_cycles(g, **kwargs) if len(c) == 4)
+
+        # A050534: the number of 4-cycles in the complete graph K_{n+1}
+        expected = [0, 0, 0, 3, 15, 45, 105, 210, 378, 630, 990]
+        g_family = [self.K(n) for n in range(1, 12)]
+        self.check_cycle_enumeration_integer_sequence(
+            g_family, expected, length_bound=4, algorithm=four_cycles
+        )
+
+        # directed complete graphs have twice as many 4-cycles thanks to reversal
+        expected = [2 * e for e in expected]
+        g_family = [self.D(n) for n in range(1, 15)]
+        self.check_cycle_enumeration_integer_sequence(
+            g_family, expected, length_bound=4, algorithm=four_cycles
+        )
+
+        # A006231: the number of elementary circuits in a complete directed graph with n nodes
+        expected = [0, 1, 5, 20, 84, 409, 2365]
+        g_family = [self.D(n) for n in range(1, 8)]
+        self.check_cycle_enumeration_integer_sequence(g_family, expected)
+
+        # A002807: Number of cycles in the complete graph on n nodes K_{n}.
+        expected = [0, 0, 0, 1, 7, 37, 197, 1172]
+        g_family = [self.K(n) for n in range(8)]
+        self.check_cycle_enumeration_integer_sequence(g_family, expected)
+
+    def test_directed_chordless_cycle_parallel_multiedges(self):
+        g = nx.MultiGraph()
+
+        nx.add_cycle(g, range(5))
+        expected = [[*range(5)]]
+        self.check_cycle_algorithm(g, expected, chordless=True)
+
+        nx.add_cycle(g, range(5))
+        expected = [*cycle_edges(range(5))]
+        self.check_cycle_algorithm(g, expected, chordless=True)
+
+        nx.add_cycle(g, range(5))
+        expected = []
+        self.check_cycle_algorithm(g, expected, chordless=True)
+
+        g = nx.MultiDiGraph()
+
+        nx.add_cycle(g, range(5))
+        expected = [[*range(5)]]
+        self.check_cycle_algorithm(g, expected, chordless=True)
+
+        nx.add_cycle(g, range(5))
+        self.check_cycle_algorithm(g, [], chordless=True)
+
+        nx.add_cycle(g, range(5))
+        self.check_cycle_algorithm(g, [], chordless=True)
+
+        g = nx.MultiDiGraph()
+
+        nx.add_cycle(g, range(5))
+        nx.add_cycle(g, range(5)[::-1])
+        expected = [*cycle_edges(range(5))]
+        self.check_cycle_algorithm(g, expected, chordless=True)
+
+        nx.add_cycle(g, range(5))
+        self.check_cycle_algorithm(g, [], chordless=True)
+
+    def test_chordless_cycles_graph(self):
+        G = nx.Graph()
+        nx.add_cycle(G, range(5))
+        nx.add_cycle(G, range(4, 12))
+        expected = [[*range(5)], [*range(4, 12)]]
+        self.check_cycle_algorithm(G, expected, chordless=True)
+        self.check_cycle_algorithm(
+            G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
+        )
+
+        G.add_edge(7, 3)
+        expected.append([*range(3, 8)])
+        expected.append([4, 3, 7, 8, 9, 10, 11])
+        self.check_cycle_algorithm(G, expected, chordless=True)
+        self.check_cycle_algorithm(
+            G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
+        )
+
+    def test_chordless_cycles_giant_hamiltonian(self):
+        # ... o - e - o - e - o ... # o = odd, e = even
+        # ... ---/ \-----/ \--- ... # <-- "long" edges
+        #
+        # each long edge belongs to exactly one triangle, and one giant cycle
+        # of length n/2.  The remaining edges each belong to a triangle
+
+        n = 1000
+        assert n % 2 == 0
+        G = nx.Graph()
+        for v in range(n):
+            if not v % 2:
+                G.add_edge(v, (v + 2) % n)
+            G.add_edge(v, (v + 1) % n)
+
+        expected = [[*range(0, n, 2)]] + [
+            [x % n for x in range(i, i + 3)] for i in range(0, n, 2)
+        ]
+        self.check_cycle_algorithm(G, expected, chordless=True)
+        self.check_cycle_algorithm(
+            G, [c for c in expected if len(c) <= 3], length_bound=3, chordless=True
+        )
+
+        # ... o -> e -> o -> e -> o ... # o = odd, e = even
+        # ... <---/ \---<---/ \---< ... # <-- "long" edges
+        #
+        # this time, we orient the short and long edges in opposition
+        # the cycle structure of this graph is the same, but we need to reverse
+        # the long one in our representation.  Also, we need to drop the size
+        # because our partitioning algorithm uses strongly connected components
+        # instead of separating graphs by their strong articulation points
+
+        n = 100
+        assert n % 2 == 0
+        G = nx.DiGraph()
+        for v in range(n):
+            G.add_edge(v, (v + 1) % n)
+            if not v % 2:
+                G.add_edge((v + 2) % n, v)
+
+        expected = [[*range(n - 2, -2, -2)]] + [
+            [x % n for x in range(i, i + 3)] for i in range(0, n, 2)
+        ]
+        self.check_cycle_algorithm(G, expected, chordless=True)
+        self.check_cycle_algorithm(
+            G, [c for c in expected if len(c) <= 3], length_bound=3, chordless=True
+        )
+
+    def test_simple_cycles_acyclic_tournament(self):
+        n = 10
+        G = nx.DiGraph((x, y) for x in range(n) for y in range(x))
+        self.check_cycle_algorithm(G, [])
+        self.check_cycle_algorithm(G, [], chordless=True)
+
+        for k in range(n + 1):
+            self.check_cycle_algorithm(G, [], length_bound=k)
+            self.check_cycle_algorithm(G, [], length_bound=k, chordless=True)
+
+    def test_simple_cycles_graph(self):
+        testG = nx.cycle_graph(8)
+        cyc1 = tuple(range(8))
+        self.check_cycle_algorithm(testG, [cyc1])
+
+        testG.add_edge(4, -1)
+        nx.add_path(testG, [3, -2, -3, -4])
+        self.check_cycle_algorithm(testG, [cyc1])
+
+        testG.update(nx.cycle_graph(range(8, 16)))
+        cyc2 = tuple(range(8, 16))
+        self.check_cycle_algorithm(testG, [cyc1, cyc2])
+
+        testG.update(nx.cycle_graph(range(4, 12)))
+        cyc3 = tuple(range(4, 12))
+        expected = {
+            (0, 1, 2, 3, 4, 5, 6, 7),  # cyc1
+            (8, 9, 10, 11, 12, 13, 14, 15),  # cyc2
+            (4, 5, 6, 7, 8, 9, 10, 11),  # cyc3
+            (4, 5, 6, 7, 8, 15, 14, 13, 12, 11),  # cyc2 + cyc3
+            (0, 1, 2, 3, 4, 11, 10, 9, 8, 7),  # cyc1 + cyc3
+            (0, 1, 2, 3, 4, 11, 12, 13, 14, 15, 8, 7),  # cyc1 + cyc2 + cyc3
+        }
+        self.check_cycle_algorithm(testG, expected)
+        assert len(expected) == (2**3 - 1) - 1  # 1 disjoint comb: cyc1 + cyc2
+
+        # Basis size = 5 (2 loops overlapping gives 5 small loops
+        #        E
+        #       / \         Note: A-F = 10-15
+        #    1-2-3-4-5
+        #    / |   |  \   cyc1=012DAB -- left
+        #   0  D   F  6   cyc2=234E   -- top
+        #   \  |   |  /   cyc3=45678F -- right
+        #    B-A-9-8-7    cyc4=89AC   -- bottom
+        #       \ /       cyc5=234F89AD -- middle
+        #        C
+        #
+        # combinations of 5 basis elements: 2^5 - 1  (one includes no cycles)
+        #
+        # disjoint combs: (11 total) not simple cycles
+        #   Any pair not including cyc5 => choose(4, 2) = 6
+        #   Any triple not including cyc5 => choose(4, 3) = 4
+        #   Any quad not including cyc5 => choose(4, 4) = 1
+        #
+        # we expect 31 - 11 = 20 simple cycles
+        #
+        testG = nx.cycle_graph(12)
+        testG.update(nx.cycle_graph([12, 10, 13, 2, 14, 4, 15, 8]).edges)
+        expected = (2**5 - 1) - 11  # 11 disjoint combinations
+        self.check_cycle_algorithm(testG, expected)
+
+    def test_simple_cycles_bounded(self):
+        # iteratively construct a cluster of nested cycles running in the same direction
+        # there should be one cycle of every length
+        d = nx.DiGraph()
+        expected = []
+        for n in range(10):
+            nx.add_cycle(d, range(n))
+            expected.append(n)
+            for k, e in enumerate(expected):
+                self.check_cycle_algorithm(d, e, length_bound=k)
+
+        # iteratively construct a path of undirected cycles, connected at articulation
+        # points.  there should be one cycle of every length except 2: no digons
+        g = nx.Graph()
+        top = 0
+        expected = []
+        for n in range(10):
+            expected.append(n if n < 2 else n - 1)
+            if n == 2:
+                # no digons in undirected graphs
+                continue
+            nx.add_cycle(g, range(top, top + n))
+            top += n
+            for k, e in enumerate(expected):
+                self.check_cycle_algorithm(g, e, length_bound=k)
+
+    def test_simple_cycles_bound_corner_cases(self):
+        G = nx.cycle_graph(4)
+        DG = nx.cycle_graph(4, create_using=nx.DiGraph)
+        assert list(nx.simple_cycles(G, length_bound=0)) == []
+        assert list(nx.simple_cycles(DG, length_bound=0)) == []
+        assert list(nx.chordless_cycles(G, length_bound=0)) == []
+        assert list(nx.chordless_cycles(DG, length_bound=0)) == []
+
+    def test_simple_cycles_bound_error(self):
+        with pytest.raises(ValueError):
+            G = nx.DiGraph()
+            for c in nx.simple_cycles(G, -1):
+                assert False
+
+        with pytest.raises(ValueError):
+            G = nx.Graph()
+            for c in nx.simple_cycles(G, -1):
+                assert False
+
+        with pytest.raises(ValueError):
+            G = nx.Graph()
+            for c in nx.chordless_cycles(G, -1):
+                assert False
+
+        with pytest.raises(ValueError):
+            G = nx.DiGraph()
+            for c in nx.chordless_cycles(G, -1):
+                assert False
+
+    def test_chordless_cycles_clique(self):
+        g_family = [self.K(n) for n in range(2, 15)]
+        expected = [0, 1, 4, 10, 20, 35, 56, 84, 120, 165, 220, 286, 364]
+        self.check_cycle_enumeration_integer_sequence(
+            g_family, expected, chordless=True
+        )
+
+        # directed cliques have as many digons as undirected graphs have edges
+        expected = [(n * n - n) // 2 for n in range(15)]
+        g_family = [self.D(n) for n in range(15)]
+        self.check_cycle_enumeration_integer_sequence(
+            g_family, expected, chordless=True
+        )
+
+
+# These tests might fail with hash randomization since they depend on
+# edge_dfs. For more information, see the comments in:
+#    networkx/algorithms/traversal/tests/test_edgedfs.py
+
+
+class TestFindCycle:
+    @classmethod
+    def setup_class(cls):
+        cls.nodes = [0, 1, 2, 3]
+        cls.edges = [(-1, 0), (0, 1), (1, 0), (1, 0), (2, 1), (3, 1)]
+
+    def test_graph_nocycle(self):
+        G = nx.Graph(self.edges)
+        pytest.raises(nx.exception.NetworkXNoCycle, nx.find_cycle, G, self.nodes)
+
+    def test_graph_cycle(self):
+        G = nx.Graph(self.edges)
+        G.add_edge(2, 0)
+        x = list(nx.find_cycle(G, self.nodes))
+        x_ = [(0, 1), (1, 2), (2, 0)]
+        assert x == x_
+
+    def test_graph_orientation_none(self):
+        G = nx.Graph(self.edges)
+        G.add_edge(2, 0)
+        x = list(nx.find_cycle(G, self.nodes, orientation=None))
+        x_ = [(0, 1), (1, 2), (2, 0)]
+        assert x == x_
+
+    def test_graph_orientation_original(self):
+        G = nx.Graph(self.edges)
+        G.add_edge(2, 0)
+        x = list(nx.find_cycle(G, self.nodes, orientation="original"))
+        x_ = [(0, 1, FORWARD), (1, 2, FORWARD), (2, 0, FORWARD)]
+        assert x == x_
+
+    def test_digraph(self):
+        G = nx.DiGraph(self.edges)
+        x = list(nx.find_cycle(G, self.nodes))
+        x_ = [(0, 1), (1, 0)]
+        assert x == x_
+
+    def test_digraph_orientation_none(self):
+        G = nx.DiGraph(self.edges)
+        x = list(nx.find_cycle(G, self.nodes, orientation=None))
+        x_ = [(0, 1), (1, 0)]
+        assert x == x_
+
+    def test_digraph_orientation_original(self):
+        G = nx.DiGraph(self.edges)
+        x = list(nx.find_cycle(G, self.nodes, orientation="original"))
+        x_ = [(0, 1, FORWARD), (1, 0, FORWARD)]
+        assert x == x_
+
+    def test_multigraph(self):
+        G = nx.MultiGraph(self.edges)
+        x = list(nx.find_cycle(G, self.nodes))
+        x_ = [(0, 1, 0), (1, 0, 1)]  # or (1, 0, 2)
+        # Hash randomization...could be any edge.
+        assert x[0] == x_[0]
+        assert x[1][:2] == x_[1][:2]
+
+    def test_multidigraph(self):
+        G = nx.MultiDiGraph(self.edges)
+        x = list(nx.find_cycle(G, self.nodes))
+        x_ = [(0, 1, 0), (1, 0, 0)]  # (1, 0, 1)
+        assert x[0] == x_[0]
+        assert x[1][:2] == x_[1][:2]
+
+    def test_digraph_ignore(self):
+        G = nx.DiGraph(self.edges)
+        x = list(nx.find_cycle(G, self.nodes, orientation="ignore"))
+        x_ = [(0, 1, FORWARD), (1, 0, FORWARD)]
+        assert x == x_
+
+    def test_digraph_reverse(self):
+        G = nx.DiGraph(self.edges)
+        x = list(nx.find_cycle(G, self.nodes, orientation="reverse"))
+        x_ = [(1, 0, REVERSE), (0, 1, REVERSE)]
+        assert x == x_
+
+    def test_multidigraph_ignore(self):
+        G = nx.MultiDiGraph(self.edges)
+        x = list(nx.find_cycle(G, self.nodes, orientation="ignore"))
+        x_ = [(0, 1, 0, FORWARD), (1, 0, 0, FORWARD)]  # or (1, 0, 1, 1)
+        assert x[0] == x_[0]
+        assert x[1][:2] == x_[1][:2]
+        assert x[1][3] == x_[1][3]
+
+    def test_multidigraph_ignore2(self):
+        # Loop traversed an edge while ignoring its orientation.
+        G = nx.MultiDiGraph([(0, 1), (1, 2), (1, 2)])
+        x = list(nx.find_cycle(G, [0, 1, 2], orientation="ignore"))
+        x_ = [(1, 2, 0, FORWARD), (1, 2, 1, REVERSE)]
+        assert x == x_
+
+    def test_multidigraph_original(self):
+        # Node 2 doesn't need to be searched again from visited from 4.
+        # The goal here is to cover the case when 2 to be researched from 4,
+        # when 4 is visited from the first time (so we must make sure that 4
+        # is not visited from 2, and hence, we respect the edge orientation).
+        G = nx.MultiDiGraph([(0, 1), (1, 2), (2, 3), (4, 2)])
+        pytest.raises(
+            nx.exception.NetworkXNoCycle,
+            nx.find_cycle,
+            G,
+            [0, 1, 2, 3, 4],
+            orientation="original",
+        )
+
+    def test_dag(self):
+        G = nx.DiGraph([(0, 1), (0, 2), (1, 2)])
+        pytest.raises(
+            nx.exception.NetworkXNoCycle, nx.find_cycle, G, orientation="original"
+        )
+        x = list(nx.find_cycle(G, orientation="ignore"))
+        assert x == [(0, 1, FORWARD), (1, 2, FORWARD), (0, 2, REVERSE)]
+
+    def test_prev_explored(self):
+        # https://github.com/networkx/networkx/issues/2323
+
+        G = nx.DiGraph()
+        G.add_edges_from([(1, 0), (2, 0), (1, 2), (2, 1)])
+        pytest.raises(nx.NetworkXNoCycle, nx.find_cycle, G, source=0)
+        x = list(nx.find_cycle(G, 1))
+        x_ = [(1, 2), (2, 1)]
+        assert x == x_
+
+        x = list(nx.find_cycle(G, 2))
+        x_ = [(2, 1), (1, 2)]
+        assert x == x_
+
+        x = list(nx.find_cycle(G))
+        x_ = [(1, 2), (2, 1)]
+        assert x == x_
+
+    def test_no_cycle(self):
+        # https://github.com/networkx/networkx/issues/2439
+
+        G = nx.DiGraph()
+        G.add_edges_from([(1, 2), (2, 0), (3, 1), (3, 2)])
+        pytest.raises(nx.NetworkXNoCycle, nx.find_cycle, G, source=0)
+        pytest.raises(nx.NetworkXNoCycle, nx.find_cycle, G)
+
+
+def assert_basis_equal(a, b):
+    assert sorted(a) == sorted(b)
+
+
+class TestMinimumCycleBasis:
+    @classmethod
+    def setup_class(cls):
+        T = nx.Graph()
+        nx.add_cycle(T, [1, 2, 3, 4], weight=1)
+        T.add_edge(2, 4, weight=5)
+        cls.diamond_graph = T
+
+    def test_unweighted_diamond(self):
+        mcb = nx.minimum_cycle_basis(self.diamond_graph)
+        assert_basis_equal(mcb, [[2, 4, 1], [3, 4, 2]])
+
+    def test_weighted_diamond(self):
+        mcb = nx.minimum_cycle_basis(self.diamond_graph, weight="weight")
+        assert_basis_equal(mcb, [[2, 4, 1], [4, 3, 2, 1]])
+
+    def test_dimensionality(self):
+        # checks |MCB|=|E|-|V|+|NC|
+        ntrial = 10
+        for seed in range(1234, 1234 + ntrial):
+            rg = nx.erdos_renyi_graph(10, 0.3, seed=seed)
+            nnodes = rg.number_of_nodes()
+            nedges = rg.number_of_edges()
+            ncomp = nx.number_connected_components(rg)
+
+            mcb = nx.minimum_cycle_basis(rg)
+            assert len(mcb) == nedges - nnodes + ncomp
+            check_independent(mcb)
+
+    def test_complete_graph(self):
+        cg = nx.complete_graph(5)
+        mcb = nx.minimum_cycle_basis(cg)
+        assert all(len(cycle) == 3 for cycle in mcb)
+        check_independent(mcb)
+
+    def test_tree_graph(self):
+        tg = nx.balanced_tree(3, 3)
+        assert not nx.minimum_cycle_basis(tg)
+
+    def test_petersen_graph(self):
+        G = nx.petersen_graph()
+        mcb = list(nx.minimum_cycle_basis(G))
+        expected = [
+            [4, 9, 7, 5, 0],
+            [1, 2, 3, 4, 0],
+            [1, 6, 8, 5, 0],
+            [4, 3, 8, 5, 0],
+            [1, 6, 9, 4, 0],
+            [1, 2, 7, 5, 0],
+        ]
+        assert len(mcb) == len(expected)
+        assert all(c in expected for c in mcb)
+
+        # check that order of the nodes is a path
+        for c in mcb:
+            assert all(G.has_edge(u, v) for u, v in nx.utils.pairwise(c, cyclic=True))
+        # check independence of the basis
+        check_independent(mcb)
+
+    def test_gh6787_variable_weighted_complete_graph(self):
+        N = 8
+        cg = nx.complete_graph(N)
+        cg.add_weighted_edges_from([(u, v, 9) for u, v in cg.edges])
+        cg.add_weighted_edges_from([(u, v, 1) for u, v in nx.cycle_graph(N).edges])
+        mcb = nx.minimum_cycle_basis(cg, weight="weight")
+        check_independent(mcb)
+
+    def test_gh6787_and_edge_attribute_names(self):
+        G = nx.cycle_graph(4)
+        G.add_weighted_edges_from([(0, 2, 10), (1, 3, 10)], weight="dist")
+        expected = [[1, 3, 0], [3, 2, 1, 0], [1, 2, 0]]
+        mcb = list(nx.minimum_cycle_basis(G, weight="dist"))
+        assert len(mcb) == len(expected)
+        assert all(c in expected for c in mcb)
+
+        # test not using a weight with weight attributes
+        expected = [[1, 3, 0], [1, 2, 0], [3, 2, 0]]
+        mcb = list(nx.minimum_cycle_basis(G))
+        assert len(mcb) == len(expected)
+        assert all(c in expected for c in mcb)
+
+
+class TestGirth:
+    @pytest.mark.parametrize(
+        ("G", "expected"),
+        (
+            (nx.chvatal_graph(), 4),
+            (nx.tutte_graph(), 4),
+            (nx.petersen_graph(), 5),
+            (nx.heawood_graph(), 6),
+            (nx.pappus_graph(), 6),
+            (nx.random_labeled_tree(10, seed=42), inf),
+            (nx.empty_graph(10), inf),
+            (nx.Graph(chain(cycle_edges(range(5)), cycle_edges(range(6, 10)))), 4),
+            (
+                nx.Graph(
+                    [
+                        (0, 6),
+                        (0, 8),
+                        (0, 9),
+                        (1, 8),
+                        (2, 8),
+                        (2, 9),
+                        (4, 9),
+                        (5, 9),
+                        (6, 8),
+                        (6, 9),
+                        (7, 8),
+                    ]
+                ),
+                3,
+            ),
+        ),
+    )
+    def test_girth(self, G, expected):
+        assert nx.girth(G) == expected
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_d_separation.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_d_separation.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7608295afa2e8e20116e5e3cc0b655b0f2a23d6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_d_separation.py
@@ -0,0 +1,340 @@
+from itertools import combinations
+
+import pytest
+
+import networkx as nx
+
+
+def path_graph():
+    """Return a path graph of length three."""
+    G = nx.path_graph(3, create_using=nx.DiGraph)
+    G.graph["name"] = "path"
+    nx.freeze(G)
+    return G
+
+
+def fork_graph():
+    """Return a three node fork graph."""
+    G = nx.DiGraph(name="fork")
+    G.add_edges_from([(0, 1), (0, 2)])
+    nx.freeze(G)
+    return G
+
+
+def collider_graph():
+    """Return a collider/v-structure graph with three nodes."""
+    G = nx.DiGraph(name="collider")
+    G.add_edges_from([(0, 2), (1, 2)])
+    nx.freeze(G)
+    return G
+
+
+def naive_bayes_graph():
+    """Return a simply Naive Bayes PGM graph."""
+    G = nx.DiGraph(name="naive_bayes")
+    G.add_edges_from([(0, 1), (0, 2), (0, 3), (0, 4)])
+    nx.freeze(G)
+    return G
+
+
+def asia_graph():
+    """Return the 'Asia' PGM graph."""
+    G = nx.DiGraph(name="asia")
+    G.add_edges_from(
+        [
+            ("asia", "tuberculosis"),
+            ("smoking", "cancer"),
+            ("smoking", "bronchitis"),
+            ("tuberculosis", "either"),
+            ("cancer", "either"),
+            ("either", "xray"),
+            ("either", "dyspnea"),
+            ("bronchitis", "dyspnea"),
+        ]
+    )
+    nx.freeze(G)
+    return G
+
+
+@pytest.fixture(name="path_graph")
+def path_graph_fixture():
+    return path_graph()
+
+
+@pytest.fixture(name="fork_graph")
+def fork_graph_fixture():
+    return fork_graph()
+
+
+@pytest.fixture(name="collider_graph")
+def collider_graph_fixture():
+    return collider_graph()
+
+
+@pytest.fixture(name="naive_bayes_graph")
+def naive_bayes_graph_fixture():
+    return naive_bayes_graph()
+
+
+@pytest.fixture(name="asia_graph")
+def asia_graph_fixture():
+    return asia_graph()
+
+
+@pytest.fixture()
+def large_collider_graph():
+    edge_list = [("A", "B"), ("C", "B"), ("B", "D"), ("D", "E"), ("B", "F"), ("G", "E")]
+    G = nx.DiGraph(edge_list)
+    return G
+
+
+@pytest.fixture()
+def chain_and_fork_graph():
+    edge_list = [("A", "B"), ("B", "C"), ("B", "D"), ("D", "C")]
+    G = nx.DiGraph(edge_list)
+    return G
+
+
+@pytest.fixture()
+def no_separating_set_graph():
+    edge_list = [("A", "B")]
+    G = nx.DiGraph(edge_list)
+    return G
+
+
+@pytest.fixture()
+def large_no_separating_set_graph():
+    edge_list = [("A", "B"), ("C", "A"), ("C", "B")]
+    G = nx.DiGraph(edge_list)
+    return G
+
+
+@pytest.fixture()
+def collider_trek_graph():
+    edge_list = [("A", "B"), ("C", "B"), ("C", "D")]
+    G = nx.DiGraph(edge_list)
+    return G
+
+
+@pytest.mark.parametrize(
+    "graph",
+    [path_graph(), fork_graph(), collider_graph(), naive_bayes_graph(), asia_graph()],
+)
+def test_markov_condition(graph):
+    """Test that the Markov condition holds for each PGM graph."""
+    for node in graph.nodes:
+        parents = set(graph.predecessors(node))
+        non_descendants = graph.nodes - nx.descendants(graph, node) - {node} - parents
+        assert nx.is_d_separator(graph, {node}, non_descendants, parents)
+
+
+def test_path_graph_dsep(path_graph):
+    """Example-based test of d-separation for path_graph."""
+    assert nx.is_d_separator(path_graph, {0}, {2}, {1})
+    assert not nx.is_d_separator(path_graph, {0}, {2}, set())
+
+
+def test_fork_graph_dsep(fork_graph):
+    """Example-based test of d-separation for fork_graph."""
+    assert nx.is_d_separator(fork_graph, {1}, {2}, {0})
+    assert not nx.is_d_separator(fork_graph, {1}, {2}, set())
+
+
+def test_collider_graph_dsep(collider_graph):
+    """Example-based test of d-separation for collider_graph."""
+    assert nx.is_d_separator(collider_graph, {0}, {1}, set())
+    assert not nx.is_d_separator(collider_graph, {0}, {1}, {2})
+
+
+def test_naive_bayes_dsep(naive_bayes_graph):
+    """Example-based test of d-separation for naive_bayes_graph."""
+    for u, v in combinations(range(1, 5), 2):
+        assert nx.is_d_separator(naive_bayes_graph, {u}, {v}, {0})
+        assert not nx.is_d_separator(naive_bayes_graph, {u}, {v}, set())
+
+
+def test_asia_graph_dsep(asia_graph):
+    """Example-based test of d-separation for asia_graph."""
+    assert nx.is_d_separator(
+        asia_graph, {"asia", "smoking"}, {"dyspnea", "xray"}, {"bronchitis", "either"}
+    )
+    assert nx.is_d_separator(
+        asia_graph, {"tuberculosis", "cancer"}, {"bronchitis"}, {"smoking", "xray"}
+    )
+
+
+def test_undirected_graphs_are_not_supported():
+    """
+    Test that undirected graphs are not supported.
+
+    d-separation and its related algorithms do not apply in
+    the case of undirected graphs.
+    """
+    g = nx.path_graph(3, nx.Graph)
+    with pytest.raises(nx.NetworkXNotImplemented):
+        nx.is_d_separator(g, {0}, {1}, {2})
+    with pytest.raises(nx.NetworkXNotImplemented):
+        nx.is_minimal_d_separator(g, {0}, {1}, {2})
+    with pytest.raises(nx.NetworkXNotImplemented):
+        nx.find_minimal_d_separator(g, {0}, {1})
+
+
+def test_cyclic_graphs_raise_error():
+    """
+    Test that cycle graphs should cause erroring.
+
+    This is because PGMs assume a directed acyclic graph.
+    """
+    g = nx.cycle_graph(3, nx.DiGraph)
+    with pytest.raises(nx.NetworkXError):
+        nx.is_d_separator(g, {0}, {1}, {2})
+    with pytest.raises(nx.NetworkXError):
+        nx.find_minimal_d_separator(g, {0}, {1})
+    with pytest.raises(nx.NetworkXError):
+        nx.is_minimal_d_separator(g, {0}, {1}, {2})
+
+
+def test_invalid_nodes_raise_error(asia_graph):
+    """
+    Test that graphs that have invalid nodes passed in raise errors.
+    """
+    # Check both set and node arguments
+    with pytest.raises(nx.NodeNotFound):
+        nx.is_d_separator(asia_graph, {0}, {1}, {2})
+    with pytest.raises(nx.NodeNotFound):
+        nx.is_d_separator(asia_graph, 0, 1, 2)
+    with pytest.raises(nx.NodeNotFound):
+        nx.is_minimal_d_separator(asia_graph, {0}, {1}, {2})
+    with pytest.raises(nx.NodeNotFound):
+        nx.is_minimal_d_separator(asia_graph, 0, 1, 2)
+    with pytest.raises(nx.NodeNotFound):
+        nx.find_minimal_d_separator(asia_graph, {0}, {1})
+    with pytest.raises(nx.NodeNotFound):
+        nx.find_minimal_d_separator(asia_graph, 0, 1)
+
+
+def test_nondisjoint_node_sets_raise_error(collider_graph):
+    """
+    Test that error is raised when node sets aren't disjoint.
+    """
+    with pytest.raises(nx.NetworkXError):
+        nx.is_d_separator(collider_graph, 0, 1, 0)
+    with pytest.raises(nx.NetworkXError):
+        nx.is_d_separator(collider_graph, 0, 2, 0)
+    with pytest.raises(nx.NetworkXError):
+        nx.is_d_separator(collider_graph, 0, 0, 1)
+    with pytest.raises(nx.NetworkXError):
+        nx.is_d_separator(collider_graph, 1, 0, 0)
+    with pytest.raises(nx.NetworkXError):
+        nx.find_minimal_d_separator(collider_graph, 0, 0)
+    with pytest.raises(nx.NetworkXError):
+        nx.find_minimal_d_separator(collider_graph, 0, 1, included=0)
+    with pytest.raises(nx.NetworkXError):
+        nx.find_minimal_d_separator(collider_graph, 1, 0, included=0)
+    with pytest.raises(nx.NetworkXError):
+        nx.is_minimal_d_separator(collider_graph, 0, 0, set())
+    with pytest.raises(nx.NetworkXError):
+        nx.is_minimal_d_separator(collider_graph, 0, 1, set(), included=0)
+    with pytest.raises(nx.NetworkXError):
+        nx.is_minimal_d_separator(collider_graph, 1, 0, set(), included=0)
+
+
+def test_is_minimal_d_separator(
+    large_collider_graph,
+    chain_and_fork_graph,
+    no_separating_set_graph,
+    large_no_separating_set_graph,
+    collider_trek_graph,
+):
+    # Case 1:
+    # create a graph A -> B <- C
+    # B -> D -> E;
+    # B -> F;
+    # G -> E;
+    assert not nx.is_d_separator(large_collider_graph, {"B"}, {"E"}, set())
+
+    # minimal set of the corresponding graph
+    # for B and E should be (D,)
+    Zmin = nx.find_minimal_d_separator(large_collider_graph, "B", "E")
+    # check that the minimal d-separator is a d-separating set
+    assert nx.is_d_separator(large_collider_graph, "B", "E", Zmin)
+    # the minimal separating set should also pass the test for minimality
+    assert nx.is_minimal_d_separator(large_collider_graph, "B", "E", Zmin)
+    # function should also work with set arguments
+    assert nx.is_minimal_d_separator(large_collider_graph, {"A", "B"}, {"G", "E"}, Zmin)
+    assert Zmin == {"D"}
+
+    # Case 2:
+    # create a graph A -> B -> C
+    # B -> D -> C;
+    assert not nx.is_d_separator(chain_and_fork_graph, {"A"}, {"C"}, set())
+    Zmin = nx.find_minimal_d_separator(chain_and_fork_graph, "A", "C")
+
+    # the minimal separating set should pass the test for minimality
+    assert nx.is_minimal_d_separator(chain_and_fork_graph, "A", "C", Zmin)
+    assert Zmin == {"B"}
+    Znotmin = Zmin.union({"D"})
+    assert not nx.is_minimal_d_separator(chain_and_fork_graph, "A", "C", Znotmin)
+
+    # Case 3:
+    # create a graph A -> B
+
+    # there is no m-separating set between A and B at all, so
+    # no minimal m-separating set can exist
+    assert not nx.is_d_separator(no_separating_set_graph, {"A"}, {"B"}, set())
+    assert nx.find_minimal_d_separator(no_separating_set_graph, "A", "B") is None
+
+    # Case 4:
+    # create a graph A -> B with A <- C -> B
+
+    # there is no m-separating set between A and B at all, so
+    # no minimal m-separating set can exist
+    # however, the algorithm will initially propose C as a
+    # minimal (but invalid) separating set
+    assert not nx.is_d_separator(large_no_separating_set_graph, {"A"}, {"B"}, {"C"})
+    assert nx.find_minimal_d_separator(large_no_separating_set_graph, "A", "B") is None
+
+    # Test `included` and `excluded` args
+    # create graph A -> B <- C -> D
+    assert nx.find_minimal_d_separator(collider_trek_graph, "A", "D", included="B") == {
+        "B",
+        "C",
+    }
+    assert (
+        nx.find_minimal_d_separator(
+            collider_trek_graph, "A", "D", included="B", restricted="B"
+        )
+        is None
+    )
+
+
+def test_is_minimal_d_separator_checks_dsep():
+    """Test that is_minimal_d_separator checks for d-separation as well."""
+    g = nx.DiGraph()
+    g.add_edges_from(
+        [
+            ("A", "B"),
+            ("A", "E"),
+            ("B", "C"),
+            ("B", "D"),
+            ("D", "C"),
+            ("D", "F"),
+            ("E", "D"),
+            ("E", "F"),
+        ]
+    )
+
+    assert not nx.is_d_separator(g, {"C"}, {"F"}, {"D"})
+
+    # since {'D'} and {} are not d-separators, we return false
+    assert not nx.is_minimal_d_separator(g, "C", "F", {"D"})
+    assert not nx.is_minimal_d_separator(g, "C", "F", set())
+
+
+def test__reachable(large_collider_graph):
+    reachable = nx.algorithms.d_separation._reachable
+    g = large_collider_graph
+    x = {"F", "D"}
+    ancestors = {"A", "B", "C", "D", "F"}
+    assert reachable(g, x, ancestors, {"B"}) == {"B", "F", "D"}
+    assert reachable(g, x, ancestors, set()) == ancestors
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_dag.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_dag.py
new file mode 100644
index 0000000000000000000000000000000000000000..0c76be8119c44096703dbd276a3275a4c33bc5b6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_dag.py
@@ -0,0 +1,835 @@
+from collections import deque
+from itertools import combinations, permutations
+
+import pytest
+
+import networkx as nx
+from networkx.utils import edges_equal, pairwise
+
+
+# Recipe from the itertools documentation.
+def _consume(iterator):
+    "Consume the iterator entirely."
+    # Feed the entire iterator into a zero-length deque.
+    deque(iterator, maxlen=0)
+
+
+class TestDagLongestPath:
+    """Unit tests computing the longest path in a directed acyclic graph."""
+
+    def test_empty(self):
+        G = nx.DiGraph()
+        assert nx.dag_longest_path(G) == []
+
+    def test_unweighted1(self):
+        edges = [(1, 2), (2, 3), (2, 4), (3, 5), (5, 6), (3, 7)]
+        G = nx.DiGraph(edges)
+        assert nx.dag_longest_path(G) == [1, 2, 3, 5, 6]
+
+    def test_unweighted2(self):
+        edges = [(1, 2), (2, 3), (3, 4), (4, 5), (1, 3), (1, 5), (3, 5)]
+        G = nx.DiGraph(edges)
+        assert nx.dag_longest_path(G) == [1, 2, 3, 4, 5]
+
+    def test_weighted(self):
+        G = nx.DiGraph()
+        edges = [(1, 2, -5), (2, 3, 1), (3, 4, 1), (4, 5, 0), (3, 5, 4), (1, 6, 2)]
+        G.add_weighted_edges_from(edges)
+        assert nx.dag_longest_path(G) == [2, 3, 5]
+
+    def test_undirected_not_implemented(self):
+        G = nx.Graph()
+        pytest.raises(nx.NetworkXNotImplemented, nx.dag_longest_path, G)
+
+    def test_unorderable_nodes(self):
+        """Tests that computing the longest path does not depend on
+        nodes being orderable.
+
+        For more information, see issue #1989.
+
+        """
+        # Create the directed path graph on four nodes in a diamond shape,
+        # with nodes represented as (unorderable) Python objects.
+        nodes = [object() for n in range(4)]
+        G = nx.DiGraph()
+        G.add_edge(nodes[0], nodes[1])
+        G.add_edge(nodes[0], nodes[2])
+        G.add_edge(nodes[2], nodes[3])
+        G.add_edge(nodes[1], nodes[3])
+
+        # this will raise NotImplementedError when nodes need to be ordered
+        nx.dag_longest_path(G)
+
+    def test_multigraph_unweighted(self):
+        edges = [(1, 2), (2, 3), (2, 3), (3, 4), (4, 5), (1, 3), (1, 5), (3, 5)]
+        G = nx.MultiDiGraph(edges)
+        assert nx.dag_longest_path(G) == [1, 2, 3, 4, 5]
+
+    def test_multigraph_weighted(self):
+        G = nx.MultiDiGraph()
+        edges = [
+            (1, 2, 2),
+            (2, 3, 2),
+            (1, 3, 1),
+            (1, 3, 5),
+            (1, 3, 2),
+        ]
+        G.add_weighted_edges_from(edges)
+        assert nx.dag_longest_path(G) == [1, 3]
+
+    def test_multigraph_weighted_default_weight(self):
+        G = nx.MultiDiGraph([(1, 2), (2, 3)])  # Unweighted edges
+        G.add_weighted_edges_from([(1, 3, 1), (1, 3, 5), (1, 3, 2)])
+
+        # Default value for default weight is 1
+        assert nx.dag_longest_path(G) == [1, 3]
+        assert nx.dag_longest_path(G, default_weight=3) == [1, 2, 3]
+
+
+class TestDagLongestPathLength:
+    """Unit tests for computing the length of a longest path in a
+    directed acyclic graph.
+
+    """
+
+    def test_unweighted(self):
+        edges = [(1, 2), (2, 3), (2, 4), (3, 5), (5, 6), (5, 7)]
+        G = nx.DiGraph(edges)
+        assert nx.dag_longest_path_length(G) == 4
+
+        edges = [(1, 2), (2, 3), (3, 4), (4, 5), (1, 3), (1, 5), (3, 5)]
+        G = nx.DiGraph(edges)
+        assert nx.dag_longest_path_length(G) == 4
+
+        # test degenerate graphs
+        G = nx.DiGraph()
+        G.add_node(1)
+        assert nx.dag_longest_path_length(G) == 0
+
+    def test_undirected_not_implemented(self):
+        G = nx.Graph()
+        pytest.raises(nx.NetworkXNotImplemented, nx.dag_longest_path_length, G)
+
+    def test_weighted(self):
+        edges = [(1, 2, -5), (2, 3, 1), (3, 4, 1), (4, 5, 0), (3, 5, 4), (1, 6, 2)]
+        G = nx.DiGraph()
+        G.add_weighted_edges_from(edges)
+        assert nx.dag_longest_path_length(G) == 5
+
+    def test_multigraph_unweighted(self):
+        edges = [(1, 2), (2, 3), (2, 3), (3, 4), (4, 5), (1, 3), (1, 5), (3, 5)]
+        G = nx.MultiDiGraph(edges)
+        assert nx.dag_longest_path_length(G) == 4
+
+    def test_multigraph_weighted(self):
+        G = nx.MultiDiGraph()
+        edges = [
+            (1, 2, 2),
+            (2, 3, 2),
+            (1, 3, 1),
+            (1, 3, 5),
+            (1, 3, 2),
+        ]
+        G.add_weighted_edges_from(edges)
+        assert nx.dag_longest_path_length(G) == 5
+
+
+class TestDAG:
+    @classmethod
+    def setup_class(cls):
+        pass
+
+    def test_topological_sort1(self):
+        DG = nx.DiGraph([(1, 2), (1, 3), (2, 3)])
+
+        for algorithm in [nx.topological_sort, nx.lexicographical_topological_sort]:
+            assert tuple(algorithm(DG)) == (1, 2, 3)
+
+        DG.add_edge(3, 2)
+
+        for algorithm in [nx.topological_sort, nx.lexicographical_topological_sort]:
+            pytest.raises(nx.NetworkXUnfeasible, _consume, algorithm(DG))
+
+        DG.remove_edge(2, 3)
+
+        for algorithm in [nx.topological_sort, nx.lexicographical_topological_sort]:
+            assert tuple(algorithm(DG)) == (1, 3, 2)
+
+        DG.remove_edge(3, 2)
+
+        assert tuple(nx.topological_sort(DG)) in {(1, 2, 3), (1, 3, 2)}
+        assert tuple(nx.lexicographical_topological_sort(DG)) == (1, 2, 3)
+
+    def test_is_directed_acyclic_graph(self):
+        G = nx.generators.complete_graph(2)
+        assert not nx.is_directed_acyclic_graph(G)
+        assert not nx.is_directed_acyclic_graph(G.to_directed())
+        assert not nx.is_directed_acyclic_graph(nx.Graph([(3, 4), (4, 5)]))
+        assert nx.is_directed_acyclic_graph(nx.DiGraph([(3, 4), (4, 5)]))
+
+    def test_topological_sort2(self):
+        DG = nx.DiGraph(
+            {
+                1: [2],
+                2: [3],
+                3: [4],
+                4: [5],
+                5: [1],
+                11: [12],
+                12: [13],
+                13: [14],
+                14: [15],
+            }
+        )
+        pytest.raises(nx.NetworkXUnfeasible, _consume, nx.topological_sort(DG))
+
+        assert not nx.is_directed_acyclic_graph(DG)
+
+        DG.remove_edge(1, 2)
+        _consume(nx.topological_sort(DG))
+        assert nx.is_directed_acyclic_graph(DG)
+
+    def test_topological_sort3(self):
+        DG = nx.DiGraph()
+        DG.add_edges_from([(1, i) for i in range(2, 5)])
+        DG.add_edges_from([(2, i) for i in range(5, 9)])
+        DG.add_edges_from([(6, i) for i in range(9, 12)])
+        DG.add_edges_from([(4, i) for i in range(12, 15)])
+
+        def validate(order):
+            assert isinstance(order, list)
+            assert set(order) == set(DG)
+            for u, v in combinations(order, 2):
+                assert not nx.has_path(DG, v, u)
+
+        validate(list(nx.topological_sort(DG)))
+
+        DG.add_edge(14, 1)
+        pytest.raises(nx.NetworkXUnfeasible, _consume, nx.topological_sort(DG))
+
+    def test_topological_sort4(self):
+        G = nx.Graph()
+        G.add_edge(1, 2)
+        # Only directed graphs can be topologically sorted.
+        pytest.raises(nx.NetworkXError, _consume, nx.topological_sort(G))
+
+    def test_topological_sort5(self):
+        G = nx.DiGraph()
+        G.add_edge(0, 1)
+        assert list(nx.topological_sort(G)) == [0, 1]
+
+    def test_topological_sort6(self):
+        for algorithm in [nx.topological_sort, nx.lexicographical_topological_sort]:
+
+            def runtime_error():
+                DG = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
+                first = True
+                for x in algorithm(DG):
+                    if first:
+                        first = False
+                        DG.add_edge(5 - x, 5)
+
+            def unfeasible_error():
+                DG = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
+                first = True
+                for x in algorithm(DG):
+                    if first:
+                        first = False
+                        DG.remove_node(4)
+
+            def runtime_error2():
+                DG = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
+                first = True
+                for x in algorithm(DG):
+                    if first:
+                        first = False
+                        DG.remove_node(2)
+
+            pytest.raises(RuntimeError, runtime_error)
+            pytest.raises(RuntimeError, runtime_error2)
+            pytest.raises(nx.NetworkXUnfeasible, unfeasible_error)
+
+    def test_all_topological_sorts_1(self):
+        DG = nx.DiGraph([(1, 2), (2, 3), (3, 4), (4, 5)])
+        assert list(nx.all_topological_sorts(DG)) == [[1, 2, 3, 4, 5]]
+
+    def test_all_topological_sorts_2(self):
+        DG = nx.DiGraph([(1, 3), (2, 1), (2, 4), (4, 3), (4, 5)])
+        assert sorted(nx.all_topological_sorts(DG)) == [
+            [2, 1, 4, 3, 5],
+            [2, 1, 4, 5, 3],
+            [2, 4, 1, 3, 5],
+            [2, 4, 1, 5, 3],
+            [2, 4, 5, 1, 3],
+        ]
+
+    def test_all_topological_sorts_3(self):
+        def unfeasible():
+            DG = nx.DiGraph([(1, 2), (2, 3), (3, 4), (4, 2), (4, 5)])
+            # convert to list to execute generator
+            list(nx.all_topological_sorts(DG))
+
+        def not_implemented():
+            G = nx.Graph([(1, 2), (2, 3)])
+            # convert to list to execute generator
+            list(nx.all_topological_sorts(G))
+
+        def not_implemented_2():
+            G = nx.MultiGraph([(1, 2), (1, 2), (2, 3)])
+            list(nx.all_topological_sorts(G))
+
+        pytest.raises(nx.NetworkXUnfeasible, unfeasible)
+        pytest.raises(nx.NetworkXNotImplemented, not_implemented)
+        pytest.raises(nx.NetworkXNotImplemented, not_implemented_2)
+
+    def test_all_topological_sorts_4(self):
+        DG = nx.DiGraph()
+        for i in range(7):
+            DG.add_node(i)
+        assert sorted(map(list, permutations(DG.nodes))) == sorted(
+            nx.all_topological_sorts(DG)
+        )
+
+    def test_all_topological_sorts_multigraph_1(self):
+        DG = nx.MultiDiGraph([(1, 2), (1, 2), (2, 3), (3, 4), (3, 5), (3, 5), (3, 5)])
+        assert sorted(nx.all_topological_sorts(DG)) == sorted(
+            [[1, 2, 3, 4, 5], [1, 2, 3, 5, 4]]
+        )
+
+    def test_all_topological_sorts_multigraph_2(self):
+        N = 9
+        edges = []
+        for i in range(1, N):
+            edges.extend([(i, i + 1)] * i)
+        DG = nx.MultiDiGraph(edges)
+        assert list(nx.all_topological_sorts(DG)) == [list(range(1, N + 1))]
+
+    def test_ancestors(self):
+        G = nx.DiGraph()
+        ancestors = nx.algorithms.dag.ancestors
+        G.add_edges_from([(1, 2), (1, 3), (4, 2), (4, 3), (4, 5), (2, 6), (5, 6)])
+        assert ancestors(G, 6) == {1, 2, 4, 5}
+        assert ancestors(G, 3) == {1, 4}
+        assert ancestors(G, 1) == set()
+        pytest.raises(nx.NetworkXError, ancestors, G, 8)
+
+    def test_descendants(self):
+        G = nx.DiGraph()
+        descendants = nx.algorithms.dag.descendants
+        G.add_edges_from([(1, 2), (1, 3), (4, 2), (4, 3), (4, 5), (2, 6), (5, 6)])
+        assert descendants(G, 1) == {2, 3, 6}
+        assert descendants(G, 4) == {2, 3, 5, 6}
+        assert descendants(G, 3) == set()
+        pytest.raises(nx.NetworkXError, descendants, G, 8)
+
+    def test_transitive_closure(self):
+        G = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
+        solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
+        assert edges_equal(nx.transitive_closure(G).edges(), solution, directed=True)
+        G = nx.DiGraph([(1, 2), (2, 3), (2, 4)])
+        solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4)]
+        assert edges_equal(nx.transitive_closure(G).edges(), solution, directed=True)
+        G = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
+        solution = [(1, 2), (2, 1), (2, 3), (3, 2), (1, 3), (3, 1)]
+        soln = sorted(solution + [(n, n) for n in G])
+        assert edges_equal(
+            sorted(nx.transitive_closure(G).edges()), soln, directed=True
+        )
+
+        G = nx.Graph([(1, 2), (2, 3), (3, 4)])
+        solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
+        assert edges_equal(sorted(nx.transitive_closure(G).edges()), solution)
+
+        G = nx.MultiGraph([(1, 2), (2, 3), (3, 4)])
+        solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
+        assert edges_equal(sorted(nx.transitive_closure(G).edges()), solution)
+
+        G = nx.MultiDiGraph([(1, 2), (2, 3), (3, 4)])
+        solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
+        assert edges_equal(
+            sorted(nx.transitive_closure(G).edges()), solution, directed=True
+        )
+
+        # test if edge data is copied
+        G = nx.DiGraph([(1, 2, {"a": 3}), (2, 3, {"b": 0}), (3, 4)])
+        H = nx.transitive_closure(G)
+        for u, v in G.edges():
+            assert G.get_edge_data(u, v) == H.get_edge_data(u, v)
+
+        k = 10
+        G = nx.DiGraph((i, i + 1, {"f": "b", "weight": i}) for i in range(k))
+        H = nx.transitive_closure(G)
+        for u, v in G.edges():
+            assert G.get_edge_data(u, v) == H.get_edge_data(u, v)
+
+        G = nx.Graph()
+        with pytest.raises(nx.NetworkXError):
+            nx.transitive_closure(G, reflexive="wrong input")
+
+    def test_reflexive_transitive_closure(self):
+        G = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
+        solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
+        soln = sorted(solution + [(n, n) for n in G])
+        assert edges_equal(nx.transitive_closure(G).edges(), solution, directed=True)
+        assert edges_equal(
+            nx.transitive_closure(G, False).edges(), solution, directed=True
+        )
+        assert edges_equal(nx.transitive_closure(G, True).edges(), soln, directed=True)
+        assert edges_equal(
+            nx.transitive_closure(G, None).edges(), solution, directed=True
+        )
+
+        G = nx.DiGraph([(1, 2), (2, 3), (2, 4)])
+        solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4)]
+        soln = sorted(solution + [(n, n) for n in G])
+        assert edges_equal(nx.transitive_closure(G).edges(), solution, directed=True)
+        assert edges_equal(
+            nx.transitive_closure(G, False).edges(), solution, directed=True
+        )
+        assert edges_equal(nx.transitive_closure(G, True).edges(), soln, directed=True)
+        assert edges_equal(
+            nx.transitive_closure(G, None).edges(), solution, directed=True
+        )
+
+        G = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
+        solution = sorted([(1, 2), (2, 1), (2, 3), (3, 2), (1, 3), (3, 1)])
+        soln = sorted(solution + [(n, n) for n in G])
+        assert edges_equal(
+            sorted(nx.transitive_closure(G).edges()), soln, directed=True
+        )
+        assert edges_equal(
+            sorted(nx.transitive_closure(G, False).edges()), soln, directed=True
+        )
+        assert edges_equal(
+            sorted(nx.transitive_closure(G, None).edges()), solution, directed=True
+        )
+        assert edges_equal(
+            sorted(nx.transitive_closure(G, True).edges()), soln, directed=True
+        )
+
+        G = nx.Graph([(1, 2), (2, 3), (3, 4)])
+        solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
+        soln = sorted(solution + [(n, n) for n in G])
+        assert edges_equal(nx.transitive_closure(G).edges(), solution)
+        assert edges_equal(nx.transitive_closure(G, False).edges(), solution)
+        assert edges_equal(nx.transitive_closure(G, True).edges(), soln)
+        assert edges_equal(nx.transitive_closure(G, None).edges(), solution)
+
+        G = nx.MultiGraph([(1, 2), (2, 3), (3, 4)])
+        solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
+        soln = sorted(solution + [(n, n) for n in G])
+        assert edges_equal(nx.transitive_closure(G).edges(), solution)
+        assert edges_equal(nx.transitive_closure(G, False).edges(), solution)
+        assert edges_equal(nx.transitive_closure(G, True).edges(), soln)
+        assert edges_equal(nx.transitive_closure(G, None).edges(), solution)
+
+        G = nx.MultiDiGraph([(1, 2), (2, 3), (3, 4)])
+        solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
+        soln = sorted(solution + [(n, n) for n in G])
+        assert edges_equal(nx.transitive_closure(G).edges(), solution, directed=True)
+        assert edges_equal(
+            nx.transitive_closure(G, False).edges(), solution, directed=True
+        )
+        assert edges_equal(nx.transitive_closure(G, True).edges(), soln, directed=True)
+        assert edges_equal(
+            nx.transitive_closure(G, None).edges(), solution, directed=True
+        )
+
+    def test_transitive_closure_dag(self):
+        G = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
+        transitive_closure = nx.algorithms.dag.transitive_closure_dag
+        solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
+        assert edges_equal(transitive_closure(G).edges(), solution, directed=True)
+        G = nx.DiGraph([(1, 2), (2, 3), (2, 4)])
+        solution = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4)]
+        assert edges_equal(transitive_closure(G).edges(), solution, directed=True)
+        G = nx.Graph([(1, 2), (2, 3), (3, 4)])
+        pytest.raises(nx.NetworkXNotImplemented, transitive_closure, G)
+
+        # test if edge data is copied
+        G = nx.DiGraph([(1, 2, {"a": 3}), (2, 3, {"b": 0}), (3, 4)])
+        H = transitive_closure(G)
+        for u, v in G.edges():
+            assert G.get_edge_data(u, v) == H.get_edge_data(u, v)
+
+        k = 10
+        G = nx.DiGraph((i, i + 1, {"foo": "bar", "weight": i}) for i in range(k))
+        H = transitive_closure(G)
+        for u, v in G.edges():
+            assert G.get_edge_data(u, v) == H.get_edge_data(u, v)
+
+    def test_transitive_reduction(self):
+        G = nx.DiGraph([(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)])
+        transitive_reduction = nx.algorithms.dag.transitive_reduction
+        solution = [(1, 2), (2, 3), (3, 4)]
+        assert edges_equal(transitive_reduction(G).edges(), solution, directed=True)
+        G = nx.DiGraph([(1, 2), (1, 3), (1, 4), (2, 3), (2, 4)])
+        transitive_reduction = nx.algorithms.dag.transitive_reduction
+        solution = [(1, 2), (2, 3), (2, 4)]
+        assert edges_equal(transitive_reduction(G).edges(), solution, directed=True)
+        G = nx.Graph([(1, 2), (2, 3), (3, 4)])
+        pytest.raises(nx.NetworkXNotImplemented, transitive_reduction, G)
+
+    def _check_antichains(self, solution, result):
+        sol = [frozenset(a) for a in solution]
+        res = [frozenset(a) for a in result]
+        assert set(sol) == set(res)
+
+    def test_antichains(self):
+        antichains = nx.algorithms.dag.antichains
+        G = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
+        solution = [[], [4], [3], [2], [1]]
+        self._check_antichains(list(antichains(G)), solution)
+        G = nx.DiGraph([(1, 2), (2, 3), (2, 4), (3, 5), (5, 6), (5, 7)])
+        solution = [
+            [],
+            [4],
+            [7],
+            [7, 4],
+            [6],
+            [6, 4],
+            [6, 7],
+            [6, 7, 4],
+            [5],
+            [5, 4],
+            [3],
+            [3, 4],
+            [2],
+            [1],
+        ]
+        self._check_antichains(list(antichains(G)), solution)
+        G = nx.DiGraph([(1, 2), (1, 3), (3, 4), (3, 5), (5, 6)])
+        solution = [
+            [],
+            [6],
+            [5],
+            [4],
+            [4, 6],
+            [4, 5],
+            [3],
+            [2],
+            [2, 6],
+            [2, 5],
+            [2, 4],
+            [2, 4, 6],
+            [2, 4, 5],
+            [2, 3],
+            [1],
+        ]
+        self._check_antichains(list(antichains(G)), solution)
+        G = nx.DiGraph({0: [1, 2], 1: [4], 2: [3], 3: [4]})
+        solution = [[], [4], [3], [2], [1], [1, 3], [1, 2], [0]]
+        self._check_antichains(list(antichains(G)), solution)
+        G = nx.DiGraph()
+        self._check_antichains(list(antichains(G)), [[]])
+        G = nx.DiGraph()
+        G.add_nodes_from([0, 1, 2])
+        solution = [[], [0], [1], [1, 0], [2], [2, 0], [2, 1], [2, 1, 0]]
+        self._check_antichains(list(antichains(G)), solution)
+
+        def f(x):
+            return list(antichains(x))
+
+        G = nx.Graph([(1, 2), (2, 3), (3, 4)])
+        pytest.raises(nx.NetworkXNotImplemented, f, G)
+        G = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
+        pytest.raises(nx.NetworkXUnfeasible, f, G)
+
+    def test_lexicographical_topological_sort(self):
+        G = nx.DiGraph([(1, 2), (2, 3), (1, 4), (1, 5), (2, 6)])
+        assert list(nx.lexicographical_topological_sort(G)) == [1, 2, 3, 4, 5, 6]
+        assert list(nx.lexicographical_topological_sort(G, key=lambda x: x)) == [
+            1,
+            2,
+            3,
+            4,
+            5,
+            6,
+        ]
+        assert list(nx.lexicographical_topological_sort(G, key=lambda x: -x)) == [
+            1,
+            5,
+            4,
+            2,
+            6,
+            3,
+        ]
+
+    def test_lexicographical_topological_sort2(self):
+        """
+        Check the case of two or more nodes with same key value.
+        Want to avoid exception raised due to comparing nodes directly.
+        See Issue #3493
+        """
+
+        class Test_Node:
+            def __init__(self, n):
+                self.label = n
+                self.priority = 1
+
+            def __repr__(self):
+                return f"Node({self.label})"
+
+        def sorting_key(node):
+            return node.priority
+
+        test_nodes = [Test_Node(n) for n in range(4)]
+        G = nx.DiGraph()
+        edges = [(0, 1), (0, 2), (0, 3), (2, 3)]
+        G.add_edges_from((test_nodes[a], test_nodes[b]) for a, b in edges)
+
+        sorting = list(nx.lexicographical_topological_sort(G, key=sorting_key))
+        assert sorting == test_nodes
+
+
+def test_topological_generations():
+    G = nx.DiGraph(
+        {1: [2, 3], 2: [4, 5], 3: [7], 4: [], 5: [6, 7], 6: [], 7: []}
+    ).reverse()
+    # order within each generation is inconsequential
+    generations = [sorted(gen) for gen in nx.topological_generations(G)]
+    expected = [[4, 6, 7], [3, 5], [2], [1]]
+    assert generations == expected
+
+    MG = nx.MultiDiGraph(G.edges)
+    MG.add_edge(2, 1)
+    generations = [sorted(gen) for gen in nx.topological_generations(MG)]
+    assert generations == expected
+
+
+def test_topological_generations_empty():
+    G = nx.DiGraph()
+    assert list(nx.topological_generations(G)) == []
+
+
+def test_topological_generations_cycle():
+    G = nx.DiGraph([[2, 1], [3, 1], [1, 2]])
+    with pytest.raises(nx.NetworkXUnfeasible):
+        list(nx.topological_generations(G))
+
+
+def test_is_aperiodic_cycle():
+    G = nx.DiGraph()
+    nx.add_cycle(G, [1, 2, 3, 4])
+    assert not nx.is_aperiodic(G)
+
+
+def test_is_aperiodic_cycle2():
+    G = nx.DiGraph()
+    nx.add_cycle(G, [1, 2, 3, 4])
+    nx.add_cycle(G, [3, 4, 5, 6, 7])
+    assert nx.is_aperiodic(G)
+
+
+def test_is_aperiodic_cycle3():
+    G = nx.DiGraph()
+    nx.add_cycle(G, [1, 2, 3, 4])
+    nx.add_cycle(G, [3, 4, 5, 6])
+    assert not nx.is_aperiodic(G)
+
+
+def test_is_aperiodic_cycle4():
+    G = nx.DiGraph()
+    nx.add_cycle(G, [1, 2, 3, 4])
+    G.add_edge(1, 3)
+    assert nx.is_aperiodic(G)
+
+
+def test_is_aperiodic_selfloop():
+    G = nx.DiGraph()
+    nx.add_cycle(G, [1, 2, 3, 4])
+    G.add_edge(1, 1)
+    assert nx.is_aperiodic(G)
+
+
+def test_is_aperiodic_null_graph_raises():
+    G = nx.DiGraph()
+    pytest.raises(nx.NetworkXPointlessConcept, nx.is_aperiodic, G)
+
+
+def test_is_aperiodic_undirected_raises():
+    G = nx.Graph([(1, 2), (2, 3), (3, 1)])
+    pytest.raises(nx.NetworkXError, nx.is_aperiodic, G)
+
+
+def test_is_aperiodic_disconnected_raises():
+    G = nx.DiGraph()
+    nx.add_cycle(G, [0, 1, 2])
+    G.add_edge(3, 3)
+    pytest.raises(nx.NetworkXError, nx.is_aperiodic, G)
+
+
+def test_is_aperiodic_weakly_connected_raises():
+    G = nx.DiGraph([(1, 2), (2, 3)])
+    pytest.raises(nx.NetworkXError, nx.is_aperiodic, G)
+
+
+def test_is_aperiodic_empty_graph():
+    G = nx.empty_graph(create_using=nx.DiGraph)
+    with pytest.raises(nx.NetworkXPointlessConcept, match="Graph has no nodes."):
+        nx.is_aperiodic(G)
+
+
+def test_is_aperiodic_bipartite():
+    # Bipartite graph
+    G = nx.DiGraph(nx.davis_southern_women_graph())
+    assert not nx.is_aperiodic(G)
+
+
+def test_is_aperiodic_single_node():
+    G = nx.DiGraph()
+    G.add_node(0)
+    assert not nx.is_aperiodic(G)
+    G.add_edge(0, 0)
+    assert nx.is_aperiodic(G)
+
+
+class TestDagToBranching:
+    """Unit tests for the :func:`networkx.dag_to_branching` function."""
+
+    def test_single_root(self):
+        """Tests that a directed acyclic graph with a single degree
+        zero node produces an arborescence.
+
+        """
+        G = nx.DiGraph([(0, 1), (0, 2), (1, 3), (2, 3)])
+        B = nx.dag_to_branching(G)
+        expected = nx.DiGraph([(0, 1), (1, 3), (0, 2), (2, 4)])
+        assert nx.is_arborescence(B)
+        assert nx.is_isomorphic(B, expected)
+
+    def test_multiple_roots(self):
+        """Tests that a directed acyclic graph with multiple degree zero
+        nodes creates an arborescence with multiple (weakly) connected
+        components.
+
+        """
+        G = nx.DiGraph([(0, 1), (0, 2), (1, 3), (2, 3), (5, 2)])
+        B = nx.dag_to_branching(G)
+        expected = nx.DiGraph([(0, 1), (1, 3), (0, 2), (2, 4), (5, 6), (6, 7)])
+        assert nx.is_branching(B)
+        assert not nx.is_arborescence(B)
+        assert nx.is_isomorphic(B, expected)
+
+    # # Attributes are not copied by this function. If they were, this would
+    # # be a good test to uncomment.
+    # def test_copy_attributes(self):
+    #     """Tests that node attributes are copied in the branching."""
+    #     G = nx.DiGraph([(0, 1), (0, 2), (1, 3), (2, 3)])
+    #     for v in G:
+    #         G.node[v]['label'] = str(v)
+    #     B = nx.dag_to_branching(G)
+    #     # Determine the root node of the branching.
+    #     root = next(v for v, d in B.in_degree() if d == 0)
+    #     assert_equal(B.node[root]['label'], '0')
+    #     children = B[root]
+    #     # Get the left and right children, nodes 1 and 2, respectively.
+    #     left, right = sorted(children, key=lambda v: B.node[v]['label'])
+    #     assert_equal(B.node[left]['label'], '1')
+    #     assert_equal(B.node[right]['label'], '2')
+    #     # Get the left grandchild.
+    #     children = B[left]
+    #     assert_equal(len(children), 1)
+    #     left_grandchild = arbitrary_element(children)
+    #     assert_equal(B.node[left_grandchild]['label'], '3')
+    #     # Get the right grandchild.
+    #     children = B[right]
+    #     assert_equal(len(children), 1)
+    #     right_grandchild = arbitrary_element(children)
+    #     assert_equal(B.node[right_grandchild]['label'], '3')
+
+    def test_already_arborescence(self):
+        """Tests that a directed acyclic graph that is already an
+        arborescence produces an isomorphic arborescence as output.
+
+        """
+        A = nx.balanced_tree(2, 2, create_using=nx.DiGraph())
+        B = nx.dag_to_branching(A)
+        assert nx.is_isomorphic(A, B)
+
+    def test_already_branching(self):
+        """Tests that a directed acyclic graph that is already a
+        branching produces an isomorphic branching as output.
+
+        """
+        T1 = nx.balanced_tree(2, 2, create_using=nx.DiGraph())
+        T2 = nx.balanced_tree(2, 2, create_using=nx.DiGraph())
+        G = nx.disjoint_union(T1, T2)
+        B = nx.dag_to_branching(G)
+        assert nx.is_isomorphic(G, B)
+
+    def test_not_acyclic(self):
+        """Tests that a non-acyclic graph causes an exception."""
+        with pytest.raises(nx.HasACycle):
+            G = nx.DiGraph(pairwise("abc", cyclic=True))
+            nx.dag_to_branching(G)
+
+    def test_undirected(self):
+        with pytest.raises(nx.NetworkXNotImplemented):
+            nx.dag_to_branching(nx.Graph())
+
+    def test_multigraph(self):
+        with pytest.raises(nx.NetworkXNotImplemented):
+            nx.dag_to_branching(nx.MultiGraph())
+
+    def test_multidigraph(self):
+        with pytest.raises(nx.NetworkXNotImplemented):
+            nx.dag_to_branching(nx.MultiDiGraph())
+
+
+def test_ancestors_descendants_undirected():
+    """Regression test to ensure ancestors and descendants work as expected on
+    undirected graphs."""
+    G = nx.path_graph(5)
+    nx.ancestors(G, 2) == nx.descendants(G, 2) == {0, 1, 3, 4}
+
+
+def test_v_structures_raise():
+    G = nx.Graph()
+    with pytest.raises(nx.NetworkXNotImplemented, match="for undirected type"):
+        nx.dag.v_structures(G)
+
+
+@pytest.mark.parametrize(
+    ("edgelist", "expected"),
+    (
+        (
+            [(0, 1), (0, 2), (3, 2)],
+            {(0, 2, 3)},
+        ),
+        (
+            [("A", "B"), ("C", "B"), ("D", "G"), ("D", "E"), ("G", "E")],
+            {("A", "B", "C")},
+        ),
+        ([(0, 1), (2, 1), (0, 2)], set()),  # adjacent parents case: see gh-7385
+    ),
+)
+def test_v_structures(edgelist, expected):
+    G = nx.DiGraph(edgelist)
+    v_structs = set(nx.dag.v_structures(G))
+    assert v_structs == expected
+
+
+def test_colliders_raise():
+    G = nx.Graph()
+    with pytest.raises(nx.NetworkXNotImplemented, match="for undirected type"):
+        nx.dag.colliders(G)
+
+
+@pytest.mark.parametrize(
+    ("edgelist", "expected"),
+    (
+        (
+            [(0, 1), (0, 2), (3, 2)],
+            {(0, 2, 3)},
+        ),
+        (
+            [("A", "B"), ("C", "B"), ("D", "G"), ("D", "E"), ("G", "E")],
+            {("A", "B", "C"), ("D", "E", "G")},
+        ),
+    ),
+)
+def test_colliders(edgelist, expected):
+    G = nx.DiGraph(edgelist)
+    colliders = set(nx.dag.colliders(G))
+    assert colliders == expected
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_distance_measures.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_distance_measures.py
new file mode 100644
index 0000000000000000000000000000000000000000..1668fefdf4bb68985bc58de5658e149adeef32bd
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_distance_measures.py
@@ -0,0 +1,831 @@
+import itertools
+import math
+from random import Random
+
+import pytest
+
+import networkx as nx
+from networkx import convert_node_labels_to_integers as cnlti
+from networkx.algorithms.distance_measures import _extrema_bounding
+
+
+def test__extrema_bounding_invalid_compute_kwarg():
+    G = nx.path_graph(3)
+    with pytest.raises(ValueError, match="compute must be one of"):
+        _extrema_bounding(G, compute="spam")
+
+
+class TestDistance:
+    def setup_method(self):
+        self.G = cnlti(nx.grid_2d_graph(4, 4), first_label=1, ordering="sorted")
+
+    @pytest.mark.parametrize("seed", list(range(10)))
+    @pytest.mark.parametrize("n", list(range(10, 20)))
+    @pytest.mark.parametrize("prob", [x / 10 for x in range(0, 10, 2)])
+    def test_use_bounds_on_off_consistency(self, seed, n, prob):
+        """Test for consistency of distance metrics when using usebounds=True.
+
+        We validate consistency for `networkx.diameter`, `networkx.radius`, `networkx.periphery`
+        and `networkx.center` when passing `usebounds=True`. Expectation is that method
+        returns the same result whether we pass usebounds=True or not.
+
+        For this we generate random connected graphs and validate method returns the same.
+        """
+        metrics = [nx.diameter, nx.radius, nx.periphery, nx.center]
+        max_weight = [5, 10, 1000]
+        rng = Random(seed)
+        # we compose it with a random tree to ensure graph is connected
+        G = nx.compose(
+            nx.random_labeled_tree(n, seed=rng),
+            nx.erdos_renyi_graph(n, prob, seed=rng),
+        )
+        for metric in metrics:
+            # checking unweighted case
+            assert metric(G) == metric(G, usebounds=True)
+            for w in max_weight:
+                for u, v in G.edges():
+                    G[u][v]["w"] = rng.randint(0, w)
+                # checking weighted case
+                assert metric(G, weight="w") == metric(G, weight="w", usebounds=True)
+
+    def test_eccentricity(self):
+        assert nx.eccentricity(self.G, 1) == 6
+        e = nx.eccentricity(self.G)
+        assert e[1] == 6
+
+        sp = dict(nx.shortest_path_length(self.G))
+        e = nx.eccentricity(self.G, sp=sp)
+        assert e[1] == 6
+
+        e = nx.eccentricity(self.G, v=1)
+        assert e == 6
+
+        # This behavior changed in version 1.8 (ticket #739)
+        e = nx.eccentricity(self.G, v=[1, 1])
+        assert e[1] == 6
+        e = nx.eccentricity(self.G, v=[1, 2])
+        assert e[1] == 6
+
+        # test against graph with one node
+        G = nx.path_graph(1)
+        e = nx.eccentricity(G)
+        assert e[0] == 0
+        e = nx.eccentricity(G, v=0)
+        assert e == 0
+        pytest.raises(nx.NetworkXError, nx.eccentricity, G, 1)
+
+        # test against empty graph
+        G = nx.empty_graph()
+        e = nx.eccentricity(G)
+        assert e == {}
+
+    def test_diameter(self):
+        assert nx.diameter(self.G) == 6
+
+    def test_harmonic_diameter(self):
+        assert nx.harmonic_diameter(self.G) == pytest.approx(2.0477815699658715)
+        assert nx.harmonic_diameter(nx.star_graph(3)) == pytest.approx(1.333333)
+
+    def test_harmonic_diameter_empty(self):
+        assert math.isnan(nx.harmonic_diameter(nx.empty_graph()))
+
+    def test_harmonic_diameter_single_node(self):
+        assert math.isnan(nx.harmonic_diameter(nx.empty_graph(1)))
+
+    def test_harmonic_diameter_discrete(self):
+        assert math.isinf(nx.harmonic_diameter(nx.empty_graph(3)))
+
+    def test_harmonic_diameter_not_strongly_connected(self):
+        DG = nx.DiGraph()
+        DG.add_edge(0, 1)
+        assert nx.harmonic_diameter(DG) == 2
+
+    def test_harmonic_diameter_weighted_paths(self):
+        G = nx.star_graph(3)
+        # check defaults
+        G.add_weighted_edges_from([(*e, 1) for i, e in enumerate(G.edges)], "weight")
+        assert nx.harmonic_diameter(G) == pytest.approx(1.333333)
+        assert nx.harmonic_diameter(G, weight="weight") == pytest.approx(1.333333)
+
+        # check impact of weights and alternate weight name
+        G.add_weighted_edges_from([(*e, i) for i, e in enumerate(G.edges)], "dist")
+        assert nx.harmonic_diameter(G, weight="dist") == pytest.approx(1.8)
+
+    def test_radius(self):
+        assert nx.radius(self.G) == 4
+
+    def test_periphery(self):
+        assert set(nx.periphery(self.G)) == {1, 4, 13, 16}
+
+    def test_center_simple_tree(self):
+        G = nx.Graph([(1, 2), (1, 3), (2, 4), (2, 5)])
+        assert nx.center(G) == [1, 2]
+
+    @pytest.mark.parametrize("r", range(2, 5))
+    @pytest.mark.parametrize("h", range(1, 5))
+    def test_center_balanced_tree(self, r, h):
+        G = nx.balanced_tree(r, h)
+        assert nx.center(G) == [0]
+
+    def test_center(self):
+        assert set(nx.center(self.G)) == {6, 7, 10, 11}
+
+    @pytest.mark.parametrize("n", [1, 2, 99, 100])
+    def test_center_path_graphs(self, n):
+        G = nx.path_graph(n)
+        expected = {(n - 1) // 2, math.ceil((n - 1) / 2)}
+        assert set(nx.center(G)) == expected
+
+    def test_bound_diameter(self):
+        assert nx.diameter(self.G, usebounds=True) == 6
+
+    def test_bound_radius(self):
+        assert nx.radius(self.G, usebounds=True) == 4
+
+    def test_bound_periphery(self):
+        result = {1, 4, 13, 16}
+        assert set(nx.periphery(self.G, usebounds=True)) == result
+
+    def test_bound_center(self):
+        result = {6, 7, 10, 11}
+        assert set(nx.center(self.G, usebounds=True)) == result
+
+    def test_radius_exception(self):
+        G = nx.Graph()
+        G.add_edge(1, 2)
+        G.add_edge(3, 4)
+        pytest.raises(nx.NetworkXError, nx.diameter, G)
+
+    def test_eccentricity_infinite(self):
+        with pytest.raises(nx.NetworkXError):
+            G = nx.Graph([(1, 2), (3, 4)])
+            e = nx.eccentricity(G)
+
+    def test_eccentricity_undirected_not_connected(self):
+        with pytest.raises(nx.NetworkXError):
+            G = nx.Graph([(1, 2), (3, 4)])
+            e = nx.eccentricity(G, sp=1)
+
+    def test_eccentricity_directed_weakly_connected(self):
+        with pytest.raises(nx.NetworkXError):
+            DG = nx.DiGraph([(1, 2), (1, 3)])
+            nx.eccentricity(DG)
+
+
+class TestWeightedDistance:
+    def setup_method(self):
+        G = nx.Graph()
+        G.add_edge(0, 1, weight=0.6, cost=0.6, high_cost=6)
+        G.add_edge(0, 2, weight=0.2, cost=0.2, high_cost=2)
+        G.add_edge(2, 3, weight=0.1, cost=0.1, high_cost=1)
+        G.add_edge(2, 4, weight=0.7, cost=0.7, high_cost=7)
+        G.add_edge(2, 5, weight=0.9, cost=0.9, high_cost=9)
+        G.add_edge(1, 5, weight=0.3, cost=0.3, high_cost=3)
+        self.G = G
+        self.weight_fn = lambda v, u, e: 2
+
+    def test_eccentricity_weight_None(self):
+        assert nx.eccentricity(self.G, 1, weight=None) == 3
+        e = nx.eccentricity(self.G, weight=None)
+        assert e[1] == 3
+
+        e = nx.eccentricity(self.G, v=1, weight=None)
+        assert e == 3
+
+        # This behavior changed in version 1.8 (ticket #739)
+        e = nx.eccentricity(self.G, v=[1, 1], weight=None)
+        assert e[1] == 3
+        e = nx.eccentricity(self.G, v=[1, 2], weight=None)
+        assert e[1] == 3
+
+    def test_eccentricity_weight_attr(self):
+        assert nx.eccentricity(self.G, 1, weight="weight") == 1.5
+        e = nx.eccentricity(self.G, weight="weight")
+        assert (
+            e
+            == nx.eccentricity(self.G, weight="cost")
+            != nx.eccentricity(self.G, weight="high_cost")
+        )
+        assert e[1] == 1.5
+
+        e = nx.eccentricity(self.G, v=1, weight="weight")
+        assert e == 1.5
+
+        # This behavior changed in version 1.8 (ticket #739)
+        e = nx.eccentricity(self.G, v=[1, 1], weight="weight")
+        assert e[1] == 1.5
+        e = nx.eccentricity(self.G, v=[1, 2], weight="weight")
+        assert e[1] == 1.5
+
+    def test_eccentricity_weight_fn(self):
+        assert nx.eccentricity(self.G, 1, weight=self.weight_fn) == 6
+        e = nx.eccentricity(self.G, weight=self.weight_fn)
+        assert e[1] == 6
+
+        e = nx.eccentricity(self.G, v=1, weight=self.weight_fn)
+        assert e == 6
+
+        # This behavior changed in version 1.8 (ticket #739)
+        e = nx.eccentricity(self.G, v=[1, 1], weight=self.weight_fn)
+        assert e[1] == 6
+        e = nx.eccentricity(self.G, v=[1, 2], weight=self.weight_fn)
+        assert e[1] == 6
+
+    def test_diameter_weight_None(self):
+        assert nx.diameter(self.G, weight=None) == 3
+
+    def test_diameter_weight_attr(self):
+        assert (
+            nx.diameter(self.G, weight="weight")
+            == nx.diameter(self.G, weight="cost")
+            == 1.6
+            != nx.diameter(self.G, weight="high_cost")
+        )
+
+    def test_diameter_weight_fn(self):
+        assert nx.diameter(self.G, weight=self.weight_fn) == 6
+
+    def test_radius_weight_None(self):
+        assert pytest.approx(nx.radius(self.G, weight=None)) == 2
+
+    def test_radius_weight_attr(self):
+        assert (
+            pytest.approx(nx.radius(self.G, weight="weight"))
+            == pytest.approx(nx.radius(self.G, weight="cost"))
+            == 0.9
+            != nx.radius(self.G, weight="high_cost")
+        )
+
+    def test_radius_weight_fn(self):
+        assert nx.radius(self.G, weight=self.weight_fn) == 4
+
+    def test_periphery_weight_None(self):
+        for v in set(nx.periphery(self.G, weight=None)):
+            assert nx.eccentricity(self.G, v, weight=None) == nx.diameter(
+                self.G, weight=None
+            )
+
+    def test_periphery_weight_attr(self):
+        periphery = set(nx.periphery(self.G, weight="weight"))
+        assert (
+            periphery
+            == set(nx.periphery(self.G, weight="cost"))
+            == set(nx.periphery(self.G, weight="high_cost"))
+        )
+        for v in periphery:
+            assert (
+                nx.eccentricity(self.G, v, weight="high_cost")
+                != nx.eccentricity(self.G, v, weight="weight")
+                == nx.eccentricity(self.G, v, weight="cost")
+                == nx.diameter(self.G, weight="weight")
+                == nx.diameter(self.G, weight="cost")
+                != nx.diameter(self.G, weight="high_cost")
+            )
+            assert nx.eccentricity(self.G, v, weight="high_cost") == nx.diameter(
+                self.G, weight="high_cost"
+            )
+
+    def test_periphery_weight_fn(self):
+        for v in set(nx.periphery(self.G, weight=self.weight_fn)):
+            assert nx.eccentricity(self.G, v, weight=self.weight_fn) == nx.diameter(
+                self.G, weight=self.weight_fn
+            )
+
+    def test_center_weight_None(self):
+        for v in set(nx.center(self.G, weight=None)):
+            assert pytest.approx(nx.eccentricity(self.G, v, weight=None)) == nx.radius(
+                self.G, weight=None
+            )
+
+    def test_center_weight_attr(self):
+        center = set(nx.center(self.G, weight="weight"))
+        assert (
+            center
+            == set(nx.center(self.G, weight="cost"))
+            != set(nx.center(self.G, weight="high_cost"))
+        )
+        for v in center:
+            assert (
+                nx.eccentricity(self.G, v, weight="high_cost")
+                != pytest.approx(nx.eccentricity(self.G, v, weight="weight"))
+                == pytest.approx(nx.eccentricity(self.G, v, weight="cost"))
+                == nx.radius(self.G, weight="weight")
+                == nx.radius(self.G, weight="cost")
+                != nx.radius(self.G, weight="high_cost")
+            )
+            assert nx.eccentricity(self.G, v, weight="high_cost") == nx.radius(
+                self.G, weight="high_cost"
+            )
+
+    def test_center_weight_fn(self):
+        for v in set(nx.center(self.G, weight=self.weight_fn)):
+            assert nx.eccentricity(self.G, v, weight=self.weight_fn) == nx.radius(
+                self.G, weight=self.weight_fn
+            )
+
+    def test_bound_diameter_weight_None(self):
+        assert nx.diameter(self.G, usebounds=True, weight=None) == 3
+
+    def test_bound_diameter_weight_attr(self):
+        assert (
+            nx.diameter(self.G, usebounds=True, weight="high_cost")
+            != nx.diameter(self.G, usebounds=True, weight="weight")
+            == nx.diameter(self.G, usebounds=True, weight="cost")
+            == 1.6
+            != nx.diameter(self.G, usebounds=True, weight="high_cost")
+        )
+        assert nx.diameter(self.G, usebounds=True, weight="high_cost") == nx.diameter(
+            self.G, usebounds=True, weight="high_cost"
+        )
+
+    def test_bound_diameter_weight_fn(self):
+        assert nx.diameter(self.G, usebounds=True, weight=self.weight_fn) == 6
+
+    def test_bound_radius_weight_None(self):
+        assert pytest.approx(nx.radius(self.G, usebounds=True, weight=None)) == 2
+
+    def test_bound_radius_weight_attr(self):
+        assert (
+            nx.radius(self.G, usebounds=True, weight="high_cost")
+            != pytest.approx(nx.radius(self.G, usebounds=True, weight="weight"))
+            == pytest.approx(nx.radius(self.G, usebounds=True, weight="cost"))
+            == 0.9
+            != nx.radius(self.G, usebounds=True, weight="high_cost")
+        )
+        assert nx.radius(self.G, usebounds=True, weight="high_cost") == nx.radius(
+            self.G, usebounds=True, weight="high_cost"
+        )
+
+    def test_bound_radius_weight_fn(self):
+        assert nx.radius(self.G, usebounds=True, weight=self.weight_fn) == 4
+
+    def test_bound_periphery_weight_None(self):
+        result = {1, 3, 4}
+        assert set(nx.periphery(self.G, usebounds=True, weight=None)) == result
+
+    def test_bound_periphery_weight_attr(self):
+        result = {4, 5}
+        assert (
+            set(nx.periphery(self.G, usebounds=True, weight="weight"))
+            == set(nx.periphery(self.G, usebounds=True, weight="cost"))
+            == result
+        )
+
+    def test_bound_periphery_weight_fn(self):
+        result = {1, 3, 4}
+        assert (
+            set(nx.periphery(self.G, usebounds=True, weight=self.weight_fn)) == result
+        )
+
+    def test_bound_center_weight_None(self):
+        result = {0, 2, 5}
+        assert set(nx.center(self.G, usebounds=True, weight=None)) == result
+
+    def test_bound_center_weight_attr(self):
+        result = {0}
+        assert (
+            set(nx.center(self.G, usebounds=True, weight="weight"))
+            == set(nx.center(self.G, usebounds=True, weight="cost"))
+            == result
+        )
+
+    def test_bound_center_weight_fn(self):
+        result = {0, 2, 5}
+        assert set(nx.center(self.G, usebounds=True, weight=self.weight_fn)) == result
+
+
+class TestResistanceDistance:
+    @classmethod
+    def setup_class(cls):
+        global np
+        np = pytest.importorskip("numpy")
+        sp = pytest.importorskip("scipy")
+
+    def setup_method(self):
+        G = nx.Graph()
+        G.add_edge(1, 2, weight=2)
+        G.add_edge(2, 3, weight=4)
+        G.add_edge(3, 4, weight=1)
+        G.add_edge(1, 4, weight=3)
+        self.G = G
+
+    def test_resistance_distance_directed_graph(self):
+        G = nx.DiGraph()
+        with pytest.raises(nx.NetworkXNotImplemented):
+            nx.resistance_distance(G)
+
+    def test_resistance_distance_empty(self):
+        G = nx.Graph()
+        with pytest.raises(nx.NetworkXError):
+            nx.resistance_distance(G)
+
+    def test_resistance_distance_not_connected(self):
+        with pytest.raises(nx.NetworkXError):
+            self.G.add_node(5)
+            nx.resistance_distance(self.G, 1, 5)
+
+    def test_resistance_distance_nodeA_not_in_graph(self):
+        with pytest.raises(nx.NetworkXError):
+            nx.resistance_distance(self.G, 9, 1)
+
+    def test_resistance_distance_nodeB_not_in_graph(self):
+        with pytest.raises(nx.NetworkXError):
+            nx.resistance_distance(self.G, 1, 9)
+
+    def test_resistance_distance(self):
+        rd = nx.resistance_distance(self.G, 1, 3, "weight", True)
+        test_data = 1 / (1 / (2 + 4) + 1 / (1 + 3))
+        assert round(rd, 5) == round(test_data, 5)
+
+    def test_resistance_distance_noinv(self):
+        rd = nx.resistance_distance(self.G, 1, 3, "weight", False)
+        test_data = 1 / (1 / (1 / 2 + 1 / 4) + 1 / (1 / 1 + 1 / 3))
+        assert round(rd, 5) == round(test_data, 5)
+
+    def test_resistance_distance_no_weight(self):
+        rd = nx.resistance_distance(self.G, 1, 3)
+        assert round(rd, 5) == 1
+
+    def test_resistance_distance_neg_weight(self):
+        self.G[2][3]["weight"] = -4
+        rd = nx.resistance_distance(self.G, 1, 3, "weight", True)
+        test_data = 1 / (1 / (2 + -4) + 1 / (1 + 3))
+        assert round(rd, 5) == round(test_data, 5)
+
+    def test_multigraph(self):
+        G = nx.MultiGraph()
+        G.add_edge(1, 2, weight=2)
+        G.add_edge(2, 3, weight=4)
+        G.add_edge(3, 4, weight=1)
+        G.add_edge(1, 4, weight=3)
+        rd = nx.resistance_distance(G, 1, 3, "weight", True)
+        assert np.isclose(rd, 1 / (1 / (2 + 4) + 1 / (1 + 3)))
+
+    def test_resistance_distance_div0(self):
+        with pytest.raises(ZeroDivisionError):
+            self.G[1][2]["weight"] = 0
+            nx.resistance_distance(self.G, 1, 3, "weight")
+
+    def test_resistance_distance_same_node(self):
+        assert nx.resistance_distance(self.G, 1, 1) == 0
+
+    def test_resistance_distance_only_nodeA(self):
+        rd = nx.resistance_distance(self.G, nodeA=1)
+        test_data = {}
+        test_data[1] = 0
+        test_data[2] = 0.75
+        test_data[3] = 1
+        test_data[4] = 0.75
+        assert isinstance(rd, dict)
+        assert sorted(rd.keys()) == sorted(test_data.keys())
+        for key in rd:
+            assert np.isclose(rd[key], test_data[key])
+
+    def test_resistance_distance_only_nodeB(self):
+        rd = nx.resistance_distance(self.G, nodeB=1)
+        test_data = {}
+        test_data[1] = 0
+        test_data[2] = 0.75
+        test_data[3] = 1
+        test_data[4] = 0.75
+        assert isinstance(rd, dict)
+        assert sorted(rd.keys()) == sorted(test_data.keys())
+        for key in rd:
+            assert np.isclose(rd[key], test_data[key])
+
+    def test_resistance_distance_all(self):
+        rd = nx.resistance_distance(self.G)
+        assert isinstance(rd, dict)
+        assert round(rd[1][3], 5) == 1
+
+
+class TestEffectiveGraphResistance:
+    @classmethod
+    def setup_class(cls):
+        global np
+        np = pytest.importorskip("numpy")
+        sp = pytest.importorskip("scipy")
+
+    def setup_method(self):
+        G = nx.Graph()
+        G.add_edge(1, 2, weight=2)
+        G.add_edge(1, 3, weight=1)
+        G.add_edge(2, 3, weight=4)
+        self.G = G
+
+    def test_effective_graph_resistance_directed_graph(self):
+        G = nx.DiGraph()
+        with pytest.raises(nx.NetworkXNotImplemented):
+            nx.effective_graph_resistance(G)
+
+    def test_effective_graph_resistance_empty(self):
+        G = nx.Graph()
+        with pytest.raises(nx.NetworkXError):
+            nx.effective_graph_resistance(G)
+
+    def test_effective_graph_resistance_not_connected(self):
+        G = nx.Graph([(1, 2), (3, 4)])
+        RG = nx.effective_graph_resistance(G)
+        assert np.isinf(RG)
+
+    def test_effective_graph_resistance(self):
+        RG = nx.effective_graph_resistance(self.G, "weight", True)
+        rd12 = 1 / (1 / (1 + 4) + 1 / 2)
+        rd13 = 1 / (1 / (1 + 2) + 1 / 4)
+        rd23 = 1 / (1 / (2 + 4) + 1 / 1)
+        assert np.isclose(RG, rd12 + rd13 + rd23)
+
+    def test_effective_graph_resistance_noinv(self):
+        RG = nx.effective_graph_resistance(self.G, "weight", False)
+        rd12 = 1 / (1 / (1 / 1 + 1 / 4) + 1 / (1 / 2))
+        rd13 = 1 / (1 / (1 / 1 + 1 / 2) + 1 / (1 / 4))
+        rd23 = 1 / (1 / (1 / 2 + 1 / 4) + 1 / (1 / 1))
+        assert np.isclose(RG, rd12 + rd13 + rd23)
+
+    def test_effective_graph_resistance_no_weight(self):
+        RG = nx.effective_graph_resistance(self.G)
+        assert np.isclose(RG, 2)
+
+    def test_effective_graph_resistance_neg_weight(self):
+        self.G[2][3]["weight"] = -4
+        RG = nx.effective_graph_resistance(self.G, "weight", True)
+        rd12 = 1 / (1 / (1 + -4) + 1 / 2)
+        rd13 = 1 / (1 / (1 + 2) + 1 / (-4))
+        rd23 = 1 / (1 / (2 + -4) + 1 / 1)
+        assert np.isclose(RG, rd12 + rd13 + rd23)
+
+    def test_effective_graph_resistance_multigraph(self):
+        G = nx.MultiGraph()
+        G.add_edge(1, 2, weight=2)
+        G.add_edge(1, 3, weight=1)
+        G.add_edge(2, 3, weight=1)
+        G.add_edge(2, 3, weight=3)
+        RG = nx.effective_graph_resistance(G, "weight", True)
+        edge23 = 1 / (1 / 1 + 1 / 3)
+        rd12 = 1 / (1 / (1 + edge23) + 1 / 2)
+        rd13 = 1 / (1 / (1 + 2) + 1 / edge23)
+        rd23 = 1 / (1 / (2 + edge23) + 1 / 1)
+        assert np.isclose(RG, rd12 + rd13 + rd23)
+
+    def test_effective_graph_resistance_div0(self):
+        with pytest.raises(ZeroDivisionError):
+            self.G[1][2]["weight"] = 0
+            nx.effective_graph_resistance(self.G, "weight")
+
+    def test_effective_graph_resistance_complete_graph(self):
+        N = 10
+        G = nx.complete_graph(N)
+        RG = nx.effective_graph_resistance(G)
+        assert np.isclose(RG, N - 1)
+
+    def test_effective_graph_resistance_path_graph(self):
+        N = 10
+        G = nx.path_graph(N)
+        RG = nx.effective_graph_resistance(G)
+        assert np.isclose(RG, (N - 1) * N * (N + 1) // 6)
+
+
+class TestBarycenter:
+    """Test :func:`networkx.algorithms.distance_measures.barycenter`."""
+
+    def barycenter_as_subgraph(self, g, **kwargs):
+        """Return the subgraph induced on the barycenter of g"""
+        b = nx.barycenter(g, **kwargs)
+        assert isinstance(b, list)
+        assert set(b) <= set(g)
+        return g.subgraph(b)
+
+    def test_must_be_connected(self):
+        pytest.raises(nx.NetworkXNoPath, nx.barycenter, nx.empty_graph(5))
+
+    def test_sp_kwarg(self):
+        # Complete graph K_5. Normally it works...
+        K_5 = nx.complete_graph(5)
+        sp = dict(nx.shortest_path_length(K_5))
+        assert nx.barycenter(K_5, sp=sp) == list(K_5)
+
+        # ...but not with the weight argument
+        for u, v, data in K_5.edges.data():
+            data["weight"] = 1
+        pytest.raises(ValueError, nx.barycenter, K_5, sp=sp, weight="weight")
+
+        # ...and a corrupted sp can make it seem like K_5 is disconnected
+        del sp[0][1]
+        pytest.raises(nx.NetworkXNoPath, nx.barycenter, K_5, sp=sp)
+
+    def test_trees(self):
+        """The barycenter of a tree is a single vertex or an edge.
+
+        See [West01]_, p. 78.
+        """
+        prng = Random(0xDEADBEEF)
+        for i in range(50):
+            RT = nx.random_labeled_tree(prng.randint(1, 75), seed=prng)
+            b = self.barycenter_as_subgraph(RT)
+            if len(b) == 2:
+                assert b.size() == 1
+            else:
+                assert len(b) == 1
+                assert b.size() == 0
+
+    def test_this_one_specific_tree(self):
+        """Test the tree pictured at the bottom of [West01]_, p. 78."""
+        g = nx.Graph(
+            {
+                "a": ["b"],
+                "b": ["a", "x"],
+                "x": ["b", "y"],
+                "y": ["x", "z"],
+                "z": ["y", 0, 1, 2, 3, 4],
+                0: ["z"],
+                1: ["z"],
+                2: ["z"],
+                3: ["z"],
+                4: ["z"],
+            }
+        )
+        b = self.barycenter_as_subgraph(g, attr="barycentricity")
+        assert list(b) == ["z"]
+        assert not b.edges
+        expected_barycentricity = {
+            0: 23,
+            1: 23,
+            2: 23,
+            3: 23,
+            4: 23,
+            "a": 35,
+            "b": 27,
+            "x": 21,
+            "y": 17,
+            "z": 15,
+        }
+        for node, barycentricity in expected_barycentricity.items():
+            assert g.nodes[node]["barycentricity"] == barycentricity
+
+        # Doubling weights should do nothing but double the barycentricities
+        for edge in g.edges:
+            g.edges[edge]["weight"] = 2
+        b = self.barycenter_as_subgraph(g, weight="weight", attr="barycentricity2")
+        assert list(b) == ["z"]
+        assert not b.edges
+        for node, barycentricity in expected_barycentricity.items():
+            assert g.nodes[node]["barycentricity2"] == barycentricity * 2
+
+
+class TestKemenyConstant:
+    @classmethod
+    def setup_class(cls):
+        global np
+        np = pytest.importorskip("numpy")
+        sp = pytest.importorskip("scipy")
+
+    def setup_method(self):
+        G = nx.Graph()
+        w12 = 2
+        w13 = 3
+        w23 = 4
+        G.add_edge(1, 2, weight=w12)
+        G.add_edge(1, 3, weight=w13)
+        G.add_edge(2, 3, weight=w23)
+        self.G = G
+
+    def test_kemeny_constant_directed(self):
+        G = nx.DiGraph()
+        G.add_edge(1, 2)
+        G.add_edge(1, 3)
+        G.add_edge(2, 3)
+        with pytest.raises(nx.NetworkXNotImplemented):
+            nx.kemeny_constant(G)
+
+    def test_kemeny_constant_not_connected(self):
+        self.G.add_node(5)
+        with pytest.raises(nx.NetworkXError):
+            nx.kemeny_constant(self.G)
+
+    def test_kemeny_constant_no_nodes(self):
+        G = nx.Graph()
+        with pytest.raises(nx.NetworkXError):
+            nx.kemeny_constant(G)
+
+    def test_kemeny_constant_negative_weight(self):
+        G = nx.Graph()
+        w12 = 2
+        w13 = 3
+        w23 = -10
+        G.add_edge(1, 2, weight=w12)
+        G.add_edge(1, 3, weight=w13)
+        G.add_edge(2, 3, weight=w23)
+        with pytest.raises(nx.NetworkXError):
+            nx.kemeny_constant(G, weight="weight")
+
+    def test_kemeny_constant(self):
+        K = nx.kemeny_constant(self.G, weight="weight")
+        w12 = 2
+        w13 = 3
+        w23 = 4
+        test_data = (
+            3
+            / 2
+            * (w12 + w13)
+            * (w12 + w23)
+            * (w13 + w23)
+            / (
+                w12**2 * (w13 + w23)
+                + w13**2 * (w12 + w23)
+                + w23**2 * (w12 + w13)
+                + 3 * w12 * w13 * w23
+            )
+        )
+        assert np.isclose(K, test_data)
+
+    def test_kemeny_constant_no_weight(self):
+        K = nx.kemeny_constant(self.G)
+        assert np.isclose(K, 4 / 3)
+
+    def test_kemeny_constant_multigraph(self):
+        G = nx.MultiGraph()
+        w12_1 = 2
+        w12_2 = 1
+        w13 = 3
+        w23 = 4
+        G.add_edge(1, 2, weight=w12_1)
+        G.add_edge(1, 2, weight=w12_2)
+        G.add_edge(1, 3, weight=w13)
+        G.add_edge(2, 3, weight=w23)
+        K = nx.kemeny_constant(G, weight="weight")
+        w12 = w12_1 + w12_2
+        test_data = (
+            3
+            / 2
+            * (w12 + w13)
+            * (w12 + w23)
+            * (w13 + w23)
+            / (
+                w12**2 * (w13 + w23)
+                + w13**2 * (w12 + w23)
+                + w23**2 * (w12 + w13)
+                + 3 * w12 * w13 * w23
+            )
+        )
+        assert np.isclose(K, test_data)
+
+    def test_kemeny_constant_weight0(self):
+        G = nx.Graph()
+        w12 = 0
+        w13 = 3
+        w23 = 4
+        G.add_edge(1, 2, weight=w12)
+        G.add_edge(1, 3, weight=w13)
+        G.add_edge(2, 3, weight=w23)
+        K = nx.kemeny_constant(G, weight="weight")
+        test_data = (
+            3
+            / 2
+            * (w12 + w13)
+            * (w12 + w23)
+            * (w13 + w23)
+            / (
+                w12**2 * (w13 + w23)
+                + w13**2 * (w12 + w23)
+                + w23**2 * (w12 + w13)
+                + 3 * w12 * w13 * w23
+            )
+        )
+        assert np.isclose(K, test_data)
+
+    def test_kemeny_constant_selfloop(self):
+        G = nx.Graph()
+        w11 = 1
+        w12 = 2
+        w13 = 3
+        w23 = 4
+        G.add_edge(1, 1, weight=w11)
+        G.add_edge(1, 2, weight=w12)
+        G.add_edge(1, 3, weight=w13)
+        G.add_edge(2, 3, weight=w23)
+        K = nx.kemeny_constant(G, weight="weight")
+        test_data = (
+            (2 * w11 + 3 * w12 + 3 * w13)
+            * (w12 + w23)
+            * (w13 + w23)
+            / (
+                (w12 * w13 + w12 * w23 + w13 * w23)
+                * (w11 + 2 * w12 + 2 * w13 + 2 * w23)
+            )
+        )
+        assert np.isclose(K, test_data)
+
+    def test_kemeny_constant_complete_bipartite_graph(self):
+        # Theorem 1 in https://www.sciencedirect.com/science/article/pii/S0166218X20302912
+        n1 = 5
+        n2 = 4
+        G = nx.complete_bipartite_graph(n1, n2)
+        K = nx.kemeny_constant(G)
+        assert np.isclose(K, n1 + n2 - 3 / 2)
+
+    def test_kemeny_constant_path_graph(self):
+        # Theorem 2 in https://www.sciencedirect.com/science/article/pii/S0166218X20302912
+        n = 10
+        G = nx.path_graph(n)
+        K = nx.kemeny_constant(G)
+        assert np.isclose(K, n**2 / 3 - 2 * n / 3 + 1 / 2)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_distance_regular.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_distance_regular.py
new file mode 100644
index 0000000000000000000000000000000000000000..545fb6dee6a915230971cf4b5a141e47adc2cc15
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_distance_regular.py
@@ -0,0 +1,85 @@
+import pytest
+
+import networkx as nx
+from networkx import is_strongly_regular
+
+
+@pytest.mark.parametrize(
+    "f", (nx.is_distance_regular, nx.intersection_array, nx.is_strongly_regular)
+)
+@pytest.mark.parametrize("graph_constructor", (nx.DiGraph, nx.MultiGraph))
+def test_raises_on_directed_and_multigraphs(f, graph_constructor):
+    G = graph_constructor([(0, 1), (1, 2)])
+    with pytest.raises(nx.NetworkXNotImplemented):
+        f(G)
+
+
+class TestDistanceRegular:
+    def test_is_distance_regular(self):
+        assert nx.is_distance_regular(nx.icosahedral_graph())
+        assert nx.is_distance_regular(nx.petersen_graph())
+        assert nx.is_distance_regular(nx.cubical_graph())
+        assert nx.is_distance_regular(nx.complete_bipartite_graph(3, 3))
+        assert nx.is_distance_regular(nx.tetrahedral_graph())
+        assert nx.is_distance_regular(nx.dodecahedral_graph())
+        assert nx.is_distance_regular(nx.pappus_graph())
+        assert nx.is_distance_regular(nx.heawood_graph())
+        assert nx.is_distance_regular(nx.cycle_graph(3))
+        # no distance regular
+        assert not nx.is_distance_regular(nx.path_graph(4))
+
+    def test_not_connected(self):
+        G = nx.cycle_graph(4)
+        nx.add_cycle(G, [5, 6, 7])
+        assert not nx.is_distance_regular(G)
+
+    def test_global_parameters(self):
+        b, c = nx.intersection_array(nx.cycle_graph(5))
+        g = nx.global_parameters(b, c)
+        assert list(g) == [(0, 0, 2), (1, 0, 1), (1, 1, 0)]
+        b, c = nx.intersection_array(nx.cycle_graph(3))
+        g = nx.global_parameters(b, c)
+        assert list(g) == [(0, 0, 2), (1, 1, 0)]
+
+    def test_intersection_array(self):
+        b, c = nx.intersection_array(nx.cycle_graph(5))
+        assert b == [2, 1]
+        assert c == [1, 1]
+        b, c = nx.intersection_array(nx.dodecahedral_graph())
+        assert b == [3, 2, 1, 1, 1]
+        assert c == [1, 1, 1, 2, 3]
+        b, c = nx.intersection_array(nx.icosahedral_graph())
+        assert b == [5, 2, 1]
+        assert c == [1, 2, 5]
+
+
+@pytest.mark.parametrize("f", (nx.is_distance_regular, nx.is_strongly_regular))
+def test_empty_graph_raises(f):
+    G = nx.Graph()
+    with pytest.raises(nx.NetworkXPointlessConcept, match="Graph has no nodes"):
+        f(G)
+
+
+class TestStronglyRegular:
+    """Unit tests for the :func:`~networkx.is_strongly_regular`
+    function.
+
+    """
+
+    def test_cycle_graph(self):
+        """Tests that the cycle graph on five vertices is strongly
+        regular.
+
+        """
+        G = nx.cycle_graph(5)
+        assert is_strongly_regular(G)
+
+    def test_petersen_graph(self):
+        """Tests that the Petersen graph is strongly regular."""
+        G = nx.petersen_graph()
+        assert is_strongly_regular(G)
+
+    def test_path_graph(self):
+        """Tests that the path graph is not strongly regular."""
+        G = nx.path_graph(4)
+        assert not is_strongly_regular(G)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_dominance.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_dominance.py
new file mode 100644
index 0000000000000000000000000000000000000000..480b3a5c841af11b807ba533ae9f809eb1e52672
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_dominance.py
@@ -0,0 +1,299 @@
+import pytest
+
+import networkx as nx
+
+
+class TestImmediateDominators:
+    @pytest.mark.parametrize("G", [nx.Graph(), nx.MultiGraph()])
+    def test_raises_undirected(self, G):
+        """Check that `immediate_dominators` raises for undirected graphs."""
+        with pytest.raises(
+            nx.NetworkXNotImplemented, match=r"not implemented for undirected"
+        ):
+            nx.immediate_dominators(G, 0)
+
+    def test_raises_node(self):
+        """Check that `immediate_dominators` raises when `start` is not in the graph."""
+        G = nx.empty_graph(1, create_using=nx.DiGraph)
+        with pytest.raises(nx.NetworkXError, match=r"not in G"):
+            nx.immediate_dominators(G, 1)
+
+    def test_singleton(self):
+        G = nx.DiGraph()
+        G.add_node(0)
+        assert nx.immediate_dominators(G, 0) == {}
+        G.add_edge(0, 0)
+        assert nx.immediate_dominators(G, 0) == {}
+
+    @pytest.mark.parametrize("gen", [nx.path_graph, nx.cycle_graph])
+    @pytest.mark.parametrize("n", [5, 10, 20])
+    def test_path_and_cycle(self, gen, n):
+        """Check `immediate_dominators` is correct for path and cycle graphs."""
+        G = gen(n, create_using=nx.DiGraph())
+        idom = nx.immediate_dominators(G, 0)
+        assert idom == {i: i - 1 for i in range(1, n)}
+
+    def test_unreachable(self):
+        n = 5
+        G = nx.path_graph(n, create_using=nx.DiGraph())
+        idom = nx.immediate_dominators(G, 1)
+        assert idom == {i: i - 1 for i in range(2, n)}
+
+    @pytest.mark.parametrize(
+        ["edgelist", "start"],
+        [
+            ([(1, 2), (2, 1), (3, 2), (4, 1), (5, 3), (5, 4)], 5),
+            (
+                [
+                    (1, 2),
+                    (2, 1),
+                    (2, 3),
+                    (3, 2),
+                    (4, 2),
+                    (4, 3),
+                    (5, 1),
+                    (6, 4),
+                    (6, 5),
+                ],
+                6,
+            ),
+        ],
+    )
+    def test_irreducible(self, edgelist, start):
+        """
+        Check `immediate_dominators` on irreducible reference graphs.
+
+        Graphs taken from figures 2 and 4 of "A simple, fast dominance algorithm." (2006).
+        https://hdl.handle.net/1911/96345
+        """
+        G = nx.DiGraph(edgelist)
+        idom = nx.immediate_dominators(G, start)
+        assert idom == dict.fromkeys(range(1, start), start)
+
+    def test_domrel_png(self):
+        # Graph taken from https://commons.wikipedia.org/wiki/File:Domrel.png
+        edges = [(1, 2), (2, 3), (2, 4), (2, 6), (3, 5), (4, 5), (5, 2)]
+        G = nx.DiGraph(edges)
+        result = nx.immediate_dominators(G, 1)
+        assert result == {2: 1, 3: 2, 4: 2, 5: 2, 6: 2}
+        # Test postdominance.
+        result = nx.immediate_dominators(G.reverse(copy=False), 6)
+        assert result == {1: 2, 2: 6, 3: 5, 4: 5, 5: 2}
+
+    def test_boost_example(self):
+        # Graph taken from Figure 1 of
+        # http://www.boost.org/doc/libs/1_56_0/libs/graph/doc/lengauer_tarjan_dominator.htm
+        edges = [(0, 1), (1, 2), (1, 3), (2, 7), (3, 4), (4, 5), (4, 6), (5, 7), (6, 4)]
+        G = nx.DiGraph(edges)
+        result = nx.immediate_dominators(G, 0)
+        assert result == {1: 0, 2: 1, 3: 1, 4: 3, 5: 4, 6: 4, 7: 1}
+        # Test postdominance.
+        result = nx.immediate_dominators(G.reverse(copy=False), 7)
+        assert result == {0: 1, 1: 7, 2: 7, 3: 4, 4: 5, 5: 7, 6: 4}
+
+
+class TestDominanceFrontiers:
+    @pytest.mark.parametrize("G", [nx.Graph(), nx.MultiGraph()])
+    def test_raises_undirected(self, G):
+        """Check that `dominance_frontiers` raises for undirected graphs."""
+        with pytest.raises(
+            nx.NetworkXNotImplemented, match=r"not implemented for undirected"
+        ):
+            nx.dominance_frontiers(G, 0)
+
+    def test_raises_node(self):
+        """Check that `dominance_frontiers` raises when `start` is not in the graph."""
+        G = nx.empty_graph(1, create_using=nx.DiGraph)
+        with pytest.raises(nx.NetworkXError, match=r"not in G"):
+            nx.dominance_frontiers(G, 1)
+
+    def test_singleton(self):
+        G = nx.DiGraph()
+        G.add_node(0)
+        assert nx.dominance_frontiers(G, 0) == {0: set()}
+        G.add_edge(0, 0)
+        assert nx.dominance_frontiers(G, 0) == {0: {0}}
+
+    @pytest.mark.parametrize("gen, df", [(nx.path_graph, set()), (nx.cycle_graph, {0})])
+    @pytest.mark.parametrize("n", [5, 10, 20])
+    def test_path_and_cycle(self, gen, df, n):
+        """Check that `dominance_frontiers` is correct for path and cycle graphs."""
+        G = gen(n, create_using=nx.DiGraph())
+        assert nx.dominance_frontiers(G, 0) == dict.fromkeys(range(n), df)
+
+    def test_unreachable(self):
+        n = 5
+        G = nx.path_graph(n, create_using=nx.DiGraph())
+        assert nx.dominance_frontiers(G, 1) == dict.fromkeys(range(1, n), set())
+
+    def test_irreducible1(self):
+        """
+        Graph taken from figure 2 of "A simple, fast dominance algorithm." (2006).
+        https://hdl.handle.net/1911/96345
+        """
+        edges = [(1, 2), (2, 1), (3, 2), (4, 1), (5, 3), (5, 4)]
+        G = nx.DiGraph(edges)
+        assert nx.dominance_frontiers(G, 5) == {
+            1: {2},
+            2: {1},
+            3: {2},
+            4: {1},
+            5: set(),
+        }
+
+    def test_irreducible2(self):
+        """
+        Graph taken from figure 4 of "A simple, fast dominance algorithm." (2006).
+        https://hdl.handle.net/1911/96345
+        """
+        edges = [(1, 2), (2, 1), (2, 3), (3, 2), (4, 2), (4, 3), (5, 1), (6, 4), (6, 5)]
+        G = nx.DiGraph(edges)
+        assert nx.dominance_frontiers(G, 6) == {
+            1: {2},
+            2: {1, 3},
+            3: {2},
+            4: {2, 3},
+            5: {1},
+            6: set(),
+        }
+
+    def test_domrel_png(self):
+        # Graph taken from https://commons.wikipedia.org/wiki/File:Domrel.png
+        edges = [(1, 2), (2, 3), (2, 4), (2, 6), (3, 5), (4, 5), (5, 2)]
+        G = nx.DiGraph(edges)
+        assert nx.dominance_frontiers(G, 1) == {
+            1: set(),
+            2: {2},
+            3: {5},
+            4: {5},
+            5: {2},
+            6: set(),
+        }
+        # Test postdominance.
+        result = nx.dominance_frontiers(G.reverse(copy=False), 6)
+        assert result == {1: set(), 2: {2}, 3: {2}, 4: {2}, 5: {2}, 6: set()}
+
+    def test_boost_example(self):
+        # Graph taken from Figure 1 of
+        # http://www.boost.org/doc/libs/1_56_0/libs/graph/doc/lengauer_tarjan_dominator.htm
+        edges = [(0, 1), (1, 2), (1, 3), (2, 7), (3, 4), (4, 5), (4, 6), (5, 7), (6, 4)]
+        G = nx.DiGraph(edges)
+        assert nx.dominance_frontiers(G, 0) == {
+            0: set(),
+            1: set(),
+            2: {7},
+            3: {7},
+            4: {4, 7},
+            5: {7},
+            6: {4},
+            7: set(),
+        }
+        # Test postdominance.
+        result = nx.dominance_frontiers(G.reverse(copy=False), 7)
+        expected = {
+            0: set(),
+            1: set(),
+            2: {1},
+            3: {1},
+            4: {1, 4},
+            5: {1},
+            6: {4},
+            7: set(),
+        }
+        assert result == expected
+
+    def test_discard_issue(self):
+        # https://github.com/networkx/networkx/issues/2071
+        g = nx.DiGraph()
+        g.add_edges_from(
+            [
+                ("b0", "b1"),
+                ("b1", "b2"),
+                ("b2", "b3"),
+                ("b3", "b1"),
+                ("b1", "b5"),
+                ("b5", "b6"),
+                ("b5", "b8"),
+                ("b6", "b7"),
+                ("b8", "b7"),
+                ("b7", "b3"),
+                ("b3", "b4"),
+            ]
+        )
+        df = nx.dominance_frontiers(g, "b0")
+        assert df == {
+            "b4": set(),
+            "b5": {"b3"},
+            "b6": {"b7"},
+            "b7": {"b3"},
+            "b0": set(),
+            "b1": {"b1"},
+            "b2": {"b3"},
+            "b3": {"b1"},
+            "b8": {"b7"},
+        }
+
+    def test_loop(self):
+        g = nx.DiGraph()
+        g.add_edges_from([("a", "b"), ("b", "c"), ("b", "a")])
+        df = nx.dominance_frontiers(g, "a")
+        assert df == {"a": {"a"}, "b": {"a"}, "c": set()}
+
+    def test_missing_immediate_doms(self):
+        # see https://github.com/networkx/networkx/issues/2070
+        g = nx.DiGraph()
+        edges = [
+            ("entry_1", "b1"),
+            ("b1", "b2"),
+            ("b2", "b3"),
+            ("b3", "exit"),
+            ("entry_2", "b3"),
+        ]
+
+        # entry_1
+        #   |
+        #   b1
+        #   |
+        #   b2  entry_2
+        #    |  /
+        #    b3
+        #    |
+        #   exit
+
+        g.add_edges_from(edges)
+        # formerly raised KeyError on entry_2 when parsing b3
+        # because entry_2 does not have immediate doms (no path)
+        nx.dominance_frontiers(g, "entry_1")
+
+    def test_loops_larger(self):
+        # from
+        # http://ecee.colorado.edu/~waite/Darmstadt/motion.html
+        g = nx.DiGraph()
+        edges = [
+            ("entry", "exit"),
+            ("entry", "1"),
+            ("1", "2"),
+            ("2", "3"),
+            ("3", "4"),
+            ("4", "5"),
+            ("5", "6"),
+            ("6", "exit"),
+            ("6", "2"),
+            ("5", "3"),
+            ("4", "4"),
+        ]
+
+        g.add_edges_from(edges)
+        df = nx.dominance_frontiers(g, "entry")
+        answer = {
+            "entry": set(),
+            "1": {"exit"},
+            "2": {"exit", "2"},
+            "3": {"exit", "3", "2"},
+            "4": {"exit", "4", "3", "2"},
+            "5": {"exit", "3", "2"},
+            "6": {"exit", "2"},
+            "exit": set(),
+        }
+        for n in df:
+            assert set(df[n]) == set(answer[n])
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_dominating.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_dominating.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f51777c72c7d4b9cc22e77a6aa6f470200b66a7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_dominating.py
@@ -0,0 +1,115 @@
+import pytest
+
+import networkx as nx
+
+
+def test_dominating_set():
+    G = nx.gnp_random_graph(100, 0.1)
+    D = nx.dominating_set(G)
+    assert nx.is_dominating_set(G, D)
+    D = nx.dominating_set(G, start_with=0)
+    assert nx.is_dominating_set(G, D)
+
+
+def test_complete():
+    """In complete graphs each node is a dominating set.
+    Thus the dominating set has to be of cardinality 1.
+    """
+    K4 = nx.complete_graph(4)
+    assert len(nx.dominating_set(K4)) == 1
+    K5 = nx.complete_graph(5)
+    assert len(nx.dominating_set(K5)) == 1
+
+
+def test_raise_dominating_set():
+    with pytest.raises(nx.NetworkXError):
+        G = nx.path_graph(4)
+        D = nx.dominating_set(G, start_with=10)
+
+
+def test_is_dominating_set():
+    G = nx.path_graph(4)
+    d = {1, 3}
+    assert nx.is_dominating_set(G, d)
+    d = {0, 2}
+    assert nx.is_dominating_set(G, d)
+    d = {1}
+    assert not nx.is_dominating_set(G, d)
+
+
+def test_wikipedia_is_dominating_set():
+    """Example from https://en.wikipedia.org/wiki/Dominating_set"""
+    G = nx.cycle_graph(4)
+    G.add_edges_from([(0, 4), (1, 4), (2, 5)])
+    assert nx.is_dominating_set(G, {4, 3, 5})
+    assert nx.is_dominating_set(G, {0, 2})
+    assert nx.is_dominating_set(G, {1, 2})
+
+
+def test_is_connected_dominating_set():
+    G = nx.path_graph(4)
+    D = {1, 2}
+    assert nx.is_connected_dominating_set(G, D)
+    D = {1, 3}
+    assert not nx.is_connected_dominating_set(G, D)
+    D = {2, 3}
+    assert nx.is_connected(nx.subgraph(G, D))
+    assert not nx.is_connected_dominating_set(G, D)
+
+
+def test_null_graph_connected_dominating_set():
+    G = nx.Graph()
+    assert 0 == len(nx.connected_dominating_set(G))
+
+
+def test_single_node_graph_connected_dominating_set():
+    G = nx.Graph()
+    G.add_node(1)
+    CD = nx.connected_dominating_set(G)
+    assert nx.is_connected_dominating_set(G, CD)
+
+
+def test_raise_disconnected_graph_connected_dominating_set():
+    with pytest.raises(nx.NetworkXError):
+        G = nx.Graph()
+        G.add_node(1)
+        G.add_node(2)
+        nx.connected_dominating_set(G)
+
+
+def test_complete_graph_connected_dominating_set():
+    K5 = nx.complete_graph(5)
+    assert 1 == len(nx.connected_dominating_set(K5))
+    K7 = nx.complete_graph(7)
+    assert 1 == len(nx.connected_dominating_set(K7))
+
+
+def test_docstring_example_connected_dominating_set():
+    G = nx.Graph(
+        [
+            (1, 2),
+            (1, 3),
+            (1, 4),
+            (1, 5),
+            (1, 6),
+            (2, 7),
+            (3, 8),
+            (4, 9),
+            (5, 10),
+            (6, 11),
+            (7, 12),
+            (8, 12),
+            (9, 12),
+            (10, 12),
+            (11, 12),
+        ]
+    )
+    assert {1, 2, 3, 4, 5, 6, 7} == nx.connected_dominating_set(G)
+
+
+@pytest.mark.parametrize("seed", [1, 13, 29])
+@pytest.mark.parametrize("n,k,p", [(10, 3, 0.2), (100, 10, 0.7), (1000, 50, 0.5)])
+def test_connected_watts_strogatz_graph_connected_dominating_set(n, k, p, seed):
+    G = nx.connected_watts_strogatz_graph(n, k, p, seed=seed)
+    D = nx.connected_dominating_set(G)
+    assert nx.is_connected_dominating_set(G, D)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_efficiency.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_efficiency.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a2e7d0463b3a0abeb8395df4ab870456faa64b7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_efficiency.py
@@ -0,0 +1,58 @@
+"""Unit tests for the :mod:`networkx.algorithms.efficiency` module."""
+
+import networkx as nx
+
+
+class TestEfficiency:
+    def setup_method(self):
+        # G1 is a disconnected graph
+        self.G1 = nx.Graph()
+        self.G1.add_nodes_from([1, 2, 3])
+        # G2 is a cycle graph
+        self.G2 = nx.cycle_graph(4)
+        # G3 is the triangle graph with one additional edge
+        self.G3 = nx.lollipop_graph(3, 1)
+
+    def test_efficiency_disconnected_nodes(self):
+        """
+        When nodes are disconnected, efficiency is 0
+        """
+        assert nx.efficiency(self.G1, 1, 2) == 0
+
+    def test_local_efficiency_disconnected_graph(self):
+        """
+        In a disconnected graph the efficiency is 0
+        """
+        assert nx.local_efficiency(self.G1) == 0
+
+    def test_efficiency(self):
+        assert nx.efficiency(self.G2, 0, 1) == 1
+        assert nx.efficiency(self.G2, 0, 2) == 1 / 2
+
+    def test_global_efficiency(self):
+        assert nx.global_efficiency(self.G2) == 5 / 6
+
+    def test_global_efficiency_complete_graph(self):
+        """
+        Tests that the average global efficiency of the complete graph is one.
+        """
+        for n in range(2, 10):
+            G = nx.complete_graph(n)
+            assert nx.global_efficiency(G) == 1
+
+    def test_local_efficiency_complete_graph(self):
+        """
+        Test that the local efficiency for a complete graph with at least 3
+        nodes should be one. For a graph with only 2 nodes, the induced
+        subgraph has no edges.
+        """
+        for n in range(3, 10):
+            G = nx.complete_graph(n)
+            assert nx.local_efficiency(G) == 1
+
+    def test_using_ego_graph(self):
+        """
+        Test that the ego graph is used when computing local efficiency.
+        For more information, see GitHub issue #2710.
+        """
+        assert nx.local_efficiency(self.G3) == 7 / 12
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_euler.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_euler.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5871f09b5a309df2bb00d9945ca9cf662e6f656
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_euler.py
@@ -0,0 +1,314 @@
+import collections
+
+import pytest
+
+import networkx as nx
+
+
+@pytest.mark.parametrize("f", (nx.is_eulerian, nx.is_semieulerian))
+def test_empty_graph_raises(f):
+    G = nx.Graph()
+    with pytest.raises(nx.NetworkXPointlessConcept, match="Connectivity is undefined"):
+        f(G)
+
+
+class TestIsEulerian:
+    def test_is_eulerian(self):
+        assert nx.is_eulerian(nx.complete_graph(5))
+        assert nx.is_eulerian(nx.complete_graph(7))
+        assert nx.is_eulerian(nx.hypercube_graph(4))
+        assert nx.is_eulerian(nx.hypercube_graph(6))
+
+        assert not nx.is_eulerian(nx.complete_graph(4))
+        assert not nx.is_eulerian(nx.complete_graph(6))
+        assert not nx.is_eulerian(nx.hypercube_graph(3))
+        assert not nx.is_eulerian(nx.hypercube_graph(5))
+
+        assert not nx.is_eulerian(nx.petersen_graph())
+        assert not nx.is_eulerian(nx.path_graph(4))
+
+    def test_is_eulerian2(self):
+        # not connected
+        G = nx.Graph()
+        G.add_nodes_from([1, 2, 3])
+        assert not nx.is_eulerian(G)
+        # not strongly connected
+        G = nx.DiGraph()
+        G.add_nodes_from([1, 2, 3])
+        assert not nx.is_eulerian(G)
+        G = nx.MultiDiGraph()
+        G.add_edge(1, 2)
+        G.add_edge(2, 3)
+        G.add_edge(2, 3)
+        G.add_edge(3, 1)
+        assert not nx.is_eulerian(G)
+
+
+class TestEulerianCircuit:
+    def test_eulerian_circuit_cycle(self):
+        G = nx.cycle_graph(4)
+
+        edges = list(nx.eulerian_circuit(G, source=0))
+        nodes = [u for u, v in edges]
+        assert nodes == [0, 3, 2, 1]
+        assert edges == [(0, 3), (3, 2), (2, 1), (1, 0)]
+
+        edges = list(nx.eulerian_circuit(G, source=1))
+        nodes = [u for u, v in edges]
+        assert nodes == [1, 2, 3, 0]
+        assert edges == [(1, 2), (2, 3), (3, 0), (0, 1)]
+
+        G = nx.complete_graph(3)
+
+        edges = list(nx.eulerian_circuit(G, source=0))
+        nodes = [u for u, v in edges]
+        assert nodes == [0, 2, 1]
+        assert edges == [(0, 2), (2, 1), (1, 0)]
+
+        edges = list(nx.eulerian_circuit(G, source=1))
+        nodes = [u for u, v in edges]
+        assert nodes == [1, 2, 0]
+        assert edges == [(1, 2), (2, 0), (0, 1)]
+
+    def test_eulerian_circuit_digraph(self):
+        G = nx.DiGraph()
+        nx.add_cycle(G, [0, 1, 2, 3])
+
+        edges = list(nx.eulerian_circuit(G, source=0))
+        nodes = [u for u, v in edges]
+        assert nodes == [0, 1, 2, 3]
+        assert edges == [(0, 1), (1, 2), (2, 3), (3, 0)]
+
+        edges = list(nx.eulerian_circuit(G, source=1))
+        nodes = [u for u, v in edges]
+        assert nodes == [1, 2, 3, 0]
+        assert edges == [(1, 2), (2, 3), (3, 0), (0, 1)]
+
+    def test_multigraph(self):
+        G = nx.MultiGraph()
+        nx.add_cycle(G, [0, 1, 2, 3])
+        G.add_edge(1, 2)
+        G.add_edge(1, 2)
+        edges = list(nx.eulerian_circuit(G, source=0))
+        nodes = [u for u, v in edges]
+        assert nodes == [0, 3, 2, 1, 2, 1]
+        assert edges == [(0, 3), (3, 2), (2, 1), (1, 2), (2, 1), (1, 0)]
+
+    def test_multigraph_with_keys(self):
+        G = nx.MultiGraph()
+        nx.add_cycle(G, [0, 1, 2, 3])
+        G.add_edge(1, 2)
+        G.add_edge(1, 2)
+        edges = list(nx.eulerian_circuit(G, source=0, keys=True))
+        nodes = [u for u, v, k in edges]
+        assert nodes == [0, 3, 2, 1, 2, 1]
+        assert edges[:2] == [(0, 3, 0), (3, 2, 0)]
+        assert collections.Counter(edges[2:5]) == collections.Counter(
+            [(2, 1, 0), (1, 2, 1), (2, 1, 2)]
+        )
+        assert edges[5:] == [(1, 0, 0)]
+
+    def test_not_eulerian(self):
+        with pytest.raises(nx.NetworkXError):
+            f = list(nx.eulerian_circuit(nx.complete_graph(4)))
+
+
+class TestIsSemiEulerian:
+    def test_is_semieulerian(self):
+        # Test graphs with Eulerian paths but no cycles return True.
+        assert nx.is_semieulerian(nx.path_graph(4))
+        G = nx.path_graph(6, create_using=nx.DiGraph)
+        assert nx.is_semieulerian(G)
+
+        # Test graphs with Eulerian cycles return False.
+        assert not nx.is_semieulerian(nx.complete_graph(5))
+        assert not nx.is_semieulerian(nx.complete_graph(7))
+        assert not nx.is_semieulerian(nx.hypercube_graph(4))
+        assert not nx.is_semieulerian(nx.hypercube_graph(6))
+
+
+class TestHasEulerianPath:
+    def test_has_eulerian_path_cyclic(self):
+        # Test graphs with Eulerian cycles return True.
+        assert nx.has_eulerian_path(nx.complete_graph(5))
+        assert nx.has_eulerian_path(nx.complete_graph(7))
+        assert nx.has_eulerian_path(nx.hypercube_graph(4))
+        assert nx.has_eulerian_path(nx.hypercube_graph(6))
+
+    def test_has_eulerian_path_non_cyclic(self):
+        # Test graphs with Eulerian paths but no cycles return True.
+        assert nx.has_eulerian_path(nx.path_graph(4))
+        G = nx.path_graph(6, create_using=nx.DiGraph)
+        assert nx.has_eulerian_path(G)
+
+    def test_has_eulerian_path_directed_graph(self):
+        # Test directed graphs and returns False
+        G = nx.DiGraph()
+        G.add_edges_from([(0, 1), (1, 2), (0, 2)])
+        assert not nx.has_eulerian_path(G)
+
+        # Test directed graphs without isolated node returns True
+        G = nx.DiGraph()
+        G.add_edges_from([(0, 1), (1, 2), (2, 0)])
+        assert nx.has_eulerian_path(G)
+
+        # Test directed graphs with isolated node returns False
+        G.add_node(3)
+        assert not nx.has_eulerian_path(G)
+
+    @pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph()))
+    def test_has_eulerian_path_not_weakly_connected(self, G):
+        G.add_edges_from([(0, 1), (2, 3), (3, 2)])
+        assert not nx.has_eulerian_path(G)
+
+    @pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph()))
+    def test_has_eulerian_path_unbalancedins_more_than_one(self, G):
+        G.add_edges_from([(0, 1), (2, 3)])
+        assert not nx.has_eulerian_path(G)
+
+
+class TestFindPathStart:
+    def testfind_path_start(self):
+        find_path_start = nx.algorithms.euler._find_path_start
+        # Test digraphs return correct starting node.
+        G = nx.path_graph(6, create_using=nx.DiGraph)
+        assert find_path_start(G) == 0
+        edges = [(0, 1), (1, 2), (2, 0), (4, 0)]
+        assert find_path_start(nx.DiGraph(edges)) == 4
+
+        # Test graph with no Eulerian path return None.
+        edges = [(0, 1), (1, 2), (2, 3), (2, 4)]
+        assert find_path_start(nx.DiGraph(edges)) is None
+
+
+class TestEulerianPath:
+    def test_eulerian_path(self):
+        x = [(4, 0), (0, 1), (1, 2), (2, 0)]
+        for e1, e2 in zip(x, nx.eulerian_path(nx.DiGraph(x))):
+            assert e1 == e2
+
+    def test_eulerian_path_straight_link(self):
+        G = nx.DiGraph()
+        result = [(1, 2), (2, 3), (3, 4), (4, 5)]
+        G.add_edges_from(result)
+        assert result == list(nx.eulerian_path(G))
+        assert result == list(nx.eulerian_path(G, source=1))
+        with pytest.raises(nx.NetworkXError):
+            list(nx.eulerian_path(G, source=3))
+        with pytest.raises(nx.NetworkXError):
+            list(nx.eulerian_path(G, source=4))
+        with pytest.raises(nx.NetworkXError):
+            list(nx.eulerian_path(G, source=5))
+
+    def test_eulerian_path_multigraph(self):
+        G = nx.MultiDiGraph()
+        result = [(2, 1), (1, 2), (2, 1), (1, 2), (2, 3), (3, 4), (4, 3)]
+        G.add_edges_from(result)
+        assert result == list(nx.eulerian_path(G))
+        assert result == list(nx.eulerian_path(G, source=2))
+        with pytest.raises(nx.NetworkXError):
+            list(nx.eulerian_path(G, source=3))
+        with pytest.raises(nx.NetworkXError):
+            list(nx.eulerian_path(G, source=4))
+
+    def test_eulerian_path_eulerian_circuit(self):
+        G = nx.DiGraph()
+        result = [(1, 2), (2, 3), (3, 4), (4, 1)]
+        result2 = [(2, 3), (3, 4), (4, 1), (1, 2)]
+        result3 = [(3, 4), (4, 1), (1, 2), (2, 3)]
+        G.add_edges_from(result)
+        assert result == list(nx.eulerian_path(G))
+        assert result == list(nx.eulerian_path(G, source=1))
+        assert result2 == list(nx.eulerian_path(G, source=2))
+        assert result3 == list(nx.eulerian_path(G, source=3))
+
+    def test_eulerian_path_undirected(self):
+        G = nx.Graph()
+        result = [(1, 2), (2, 3), (3, 4), (4, 5)]
+        result2 = [(5, 4), (4, 3), (3, 2), (2, 1)]
+        G.add_edges_from(result)
+        assert list(nx.eulerian_path(G)) in (result, result2)
+        assert result == list(nx.eulerian_path(G, source=1))
+        assert result2 == list(nx.eulerian_path(G, source=5))
+        with pytest.raises(nx.NetworkXError):
+            list(nx.eulerian_path(G, source=3))
+        with pytest.raises(nx.NetworkXError):
+            list(nx.eulerian_path(G, source=2))
+
+    def test_eulerian_path_multigraph_undirected(self):
+        G = nx.MultiGraph()
+        result = [(2, 1), (1, 2), (2, 1), (1, 2), (2, 3), (3, 4)]
+        G.add_edges_from(result)
+        assert result == list(nx.eulerian_path(G))
+        assert result == list(nx.eulerian_path(G, source=2))
+        with pytest.raises(nx.NetworkXError):
+            list(nx.eulerian_path(G, source=3))
+        with pytest.raises(nx.NetworkXError):
+            list(nx.eulerian_path(G, source=1))
+
+    @pytest.mark.parametrize(
+        ("graph_type", "result"),
+        (
+            (nx.MultiGraph, [(0, 1, 0), (1, 0, 1)]),
+            (nx.MultiDiGraph, [(0, 1, 0), (1, 0, 0)]),
+        ),
+    )
+    def test_eulerian_with_keys(self, graph_type, result):
+        G = graph_type([(0, 1), (1, 0)])
+        answer = nx.eulerian_path(G, keys=True)
+        assert list(answer) == result
+
+
+class TestEulerize:
+    def test_disconnected(self):
+        with pytest.raises(nx.NetworkXError):
+            G = nx.from_edgelist([(0, 1), (2, 3)])
+            nx.eulerize(G)
+
+    def test_null_graph(self):
+        with pytest.raises(nx.NetworkXPointlessConcept):
+            nx.eulerize(nx.Graph())
+
+    def test_null_multigraph(self):
+        with pytest.raises(nx.NetworkXPointlessConcept):
+            nx.eulerize(nx.MultiGraph())
+
+    def test_on_empty_graph(self):
+        with pytest.raises(nx.NetworkXError):
+            nx.eulerize(nx.empty_graph(3))
+
+    def test_on_eulerian(self):
+        G = nx.cycle_graph(3)
+        H = nx.eulerize(G)
+        assert nx.is_isomorphic(G, H)
+
+    def test_on_eulerian_multigraph(self):
+        G = nx.MultiGraph(nx.cycle_graph(3))
+        G.add_edge(0, 1)
+        H = nx.eulerize(G)
+        assert nx.is_eulerian(H)
+
+    def test_on_complete_graph(self):
+        G = nx.complete_graph(4)
+        assert nx.is_eulerian(nx.eulerize(G))
+        assert nx.is_eulerian(nx.eulerize(nx.MultiGraph(G)))
+
+    def test_on_non_eulerian_graph(self):
+        G = nx.cycle_graph(18)
+        G.add_edge(0, 18)
+        G.add_edge(18, 19)
+        G.add_edge(17, 19)
+        G.add_edge(4, 20)
+        G.add_edge(20, 21)
+        G.add_edge(21, 22)
+        G.add_edge(22, 23)
+        G.add_edge(23, 24)
+        G.add_edge(24, 25)
+        G.add_edge(25, 26)
+        G.add_edge(26, 27)
+        G.add_edge(27, 28)
+        G.add_edge(28, 13)
+        assert not nx.is_eulerian(G)
+        G = nx.eulerize(G)
+        assert nx.is_eulerian(G)
+        assert nx.number_of_edges(G) == 39
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_graph_hashing.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_graph_hashing.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c90c8ff128a02143c48322853bc2dcaa5f6fffc
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_graph_hashing.py
@@ -0,0 +1,872 @@
+import copy
+
+import pytest
+
+import networkx as nx
+
+# Unit tests relevant for both functions in this module.
+
+
+def test_positive_iters():
+    G1 = nx.empty_graph()
+    with pytest.raises(
+        ValueError,
+        match="The WL algorithm requires that `iterations` be positive",
+    ):
+        nx.weisfeiler_lehman_graph_hash(G1, iterations=-3)
+    with pytest.raises(
+        ValueError,
+        match="The WL algorithm requires that `iterations` be positive",
+    ):
+        nx.weisfeiler_lehman_subgraph_hashes(G1, iterations=-3)
+    with pytest.raises(
+        ValueError,
+        match="The WL algorithm requires that `iterations` be positive",
+    ):
+        nx.weisfeiler_lehman_graph_hash(G1, iterations=0)
+    with pytest.raises(
+        ValueError,
+        match="The WL algorithm requires that `iterations` be positive",
+    ):
+        nx.weisfeiler_lehman_subgraph_hashes(G1, iterations=0)
+
+
+# Unit tests for the :func:`~networkx.weisfeiler_lehman_graph_hash` function
+
+
+def test_empty_graph_hash():
+    """
+    empty graphs should give hashes regardless of other params
+    """
+    G1 = nx.empty_graph()
+    G2 = nx.empty_graph()
+
+    h1 = nx.weisfeiler_lehman_graph_hash(G1)
+    h2 = nx.weisfeiler_lehman_graph_hash(G2)
+    h3 = nx.weisfeiler_lehman_graph_hash(G2, edge_attr="edge_attr1")
+    h4 = nx.weisfeiler_lehman_graph_hash(G2, node_attr="node_attr1")
+    h5 = nx.weisfeiler_lehman_graph_hash(
+        G2, edge_attr="edge_attr1", node_attr="node_attr1"
+    )
+    h6 = nx.weisfeiler_lehman_graph_hash(G2, iterations=10)
+
+    assert h1 == h2
+    assert h1 == h3
+    assert h1 == h4
+    assert h1 == h5
+    assert h1 == h6
+
+
+def test_directed():
+    """
+    A directed graph with no bi-directional edges should yield different a graph hash
+    to the same graph taken as undirected if there are no hash collisions.
+    """
+    r = 10
+    for i in range(r):
+        G_directed = nx.gn_graph(10 + r, seed=100 + i)
+        G_undirected = nx.to_undirected(G_directed)
+
+        h_directed = nx.weisfeiler_lehman_graph_hash(G_directed)
+        h_undirected = nx.weisfeiler_lehman_graph_hash(G_undirected)
+
+        assert h_directed != h_undirected
+
+
+def test_reversed():
+    """
+    A directed graph with no bi-directional edges should yield different a graph hash
+    to the same graph taken with edge directions reversed if there are no hash
+    collisions. Here we test a cycle graph which is the minimal counterexample
+    """
+    G = nx.cycle_graph(5, create_using=nx.DiGraph)
+    nx.set_node_attributes(G, {n: str(n) for n in G.nodes()}, name="label")
+
+    G_reversed = G.reverse()
+
+    h = nx.weisfeiler_lehman_graph_hash(G, node_attr="label")
+    h_reversed = nx.weisfeiler_lehman_graph_hash(G_reversed, node_attr="label")
+
+    assert h != h_reversed
+
+
+def test_isomorphic():
+    """
+    graph hashes should be invariant to node-relabeling (when the output is reindexed
+    by the same mapping)
+    """
+    n, r = 100, 10
+    p = 1.0 / r
+    for i in range(1, r + 1):
+        G1 = nx.erdos_renyi_graph(n, p * i, seed=200 + i)
+        G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
+
+        g1_hash = nx.weisfeiler_lehman_graph_hash(G1)
+        g2_hash = nx.weisfeiler_lehman_graph_hash(G2)
+
+        assert g1_hash == g2_hash
+
+
+def test_isomorphic_edge_attr():
+    """
+    Isomorphic graphs with differing edge attributes should yield different graph
+    hashes if the 'edge_attr' argument is supplied and populated in the graph,
+    and there are no hash collisions.
+    The output should still be invariant to node-relabeling
+    """
+    n, r = 100, 10
+    p = 1.0 / r
+    for i in range(1, r + 1):
+        G1 = nx.erdos_renyi_graph(n, p * i, seed=300 + i)
+
+        for a, b in G1.edges:
+            G1[a][b]["edge_attr1"] = f"{a}-{b}-1"
+            G1[a][b]["edge_attr2"] = f"{a}-{b}-2"
+
+        g1_hash_with_edge_attr1 = nx.weisfeiler_lehman_graph_hash(
+            G1, edge_attr="edge_attr1"
+        )
+        g1_hash_with_edge_attr2 = nx.weisfeiler_lehman_graph_hash(
+            G1, edge_attr="edge_attr2"
+        )
+        g1_hash_no_edge_attr = nx.weisfeiler_lehman_graph_hash(G1, edge_attr=None)
+
+        assert g1_hash_with_edge_attr1 != g1_hash_no_edge_attr
+        assert g1_hash_with_edge_attr2 != g1_hash_no_edge_attr
+        assert g1_hash_with_edge_attr1 != g1_hash_with_edge_attr2
+
+        G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
+
+        g2_hash_with_edge_attr1 = nx.weisfeiler_lehman_graph_hash(
+            G2, edge_attr="edge_attr1"
+        )
+        g2_hash_with_edge_attr2 = nx.weisfeiler_lehman_graph_hash(
+            G2, edge_attr="edge_attr2"
+        )
+
+        assert g1_hash_with_edge_attr1 == g2_hash_with_edge_attr1
+        assert g1_hash_with_edge_attr2 == g2_hash_with_edge_attr2
+
+
+def test_missing_edge_attr():
+    """
+    If the 'edge_attr' argument is supplied but is missing from an edge in the graph,
+    we should raise a KeyError
+    """
+    G = nx.Graph()
+    G.add_edges_from([(1, 2, {"edge_attr1": "a"}), (1, 3, {})])
+    pytest.raises(KeyError, nx.weisfeiler_lehman_graph_hash, G, edge_attr="edge_attr1")
+
+
+def test_isomorphic_node_attr():
+    """
+    Isomorphic graphs with differing node attributes should yield different graph
+    hashes if the 'node_attr' argument is supplied and populated in the graph, and
+    there are no hash collisions.
+    The output should still be invariant to node-relabeling
+    """
+    n, r = 100, 10
+    p = 1.0 / r
+    for i in range(1, r + 1):
+        G1 = nx.erdos_renyi_graph(n, p * i, seed=400 + i)
+
+        for u in G1.nodes():
+            G1.nodes[u]["node_attr1"] = f"{u}-1"
+            G1.nodes[u]["node_attr2"] = f"{u}-2"
+
+        g1_hash_with_node_attr1 = nx.weisfeiler_lehman_graph_hash(
+            G1, node_attr="node_attr1"
+        )
+        g1_hash_with_node_attr2 = nx.weisfeiler_lehman_graph_hash(
+            G1, node_attr="node_attr2"
+        )
+        g1_hash_no_node_attr = nx.weisfeiler_lehman_graph_hash(G1, node_attr=None)
+
+        assert g1_hash_with_node_attr1 != g1_hash_no_node_attr
+        assert g1_hash_with_node_attr2 != g1_hash_no_node_attr
+        assert g1_hash_with_node_attr1 != g1_hash_with_node_attr2
+
+        G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
+
+        g2_hash_with_node_attr1 = nx.weisfeiler_lehman_graph_hash(
+            G2, node_attr="node_attr1"
+        )
+        g2_hash_with_node_attr2 = nx.weisfeiler_lehman_graph_hash(
+            G2, node_attr="node_attr2"
+        )
+
+        assert g1_hash_with_node_attr1 == g2_hash_with_node_attr1
+        assert g1_hash_with_node_attr2 == g2_hash_with_node_attr2
+
+
+def test_missing_node_attr():
+    """
+    If the 'node_attr' argument is supplied but is missing from a node in the graph,
+    we should raise a KeyError
+    """
+    G = nx.Graph()
+    G.add_nodes_from([(1, {"node_attr1": "a"}), (2, {})])
+    G.add_edges_from([(1, 2), (2, 3), (3, 1), (1, 4)])
+    pytest.raises(KeyError, nx.weisfeiler_lehman_graph_hash, G, node_attr="node_attr1")
+
+
+def test_isomorphic_edge_attr_and_node_attr():
+    """
+    Isomorphic graphs with differing node attributes should yield different graph
+    hashes if the 'node_attr' and 'edge_attr' argument is supplied and populated in
+    the graph, and there are no hash collisions.
+    The output should still be invariant to node-relabeling
+    """
+    n, r = 100, 10
+    p = 1.0 / r
+    for i in range(1, r + 1):
+        G1 = nx.erdos_renyi_graph(n, p * i, seed=500 + i)
+
+        for u in G1.nodes():
+            G1.nodes[u]["node_attr1"] = f"{u}-1"
+            G1.nodes[u]["node_attr2"] = f"{u}-2"
+
+        for a, b in G1.edges:
+            G1[a][b]["edge_attr1"] = f"{a}-{b}-1"
+            G1[a][b]["edge_attr2"] = f"{a}-{b}-2"
+
+        g1_hash_edge1_node1 = nx.weisfeiler_lehman_graph_hash(
+            G1, edge_attr="edge_attr1", node_attr="node_attr1"
+        )
+        g1_hash_edge2_node2 = nx.weisfeiler_lehman_graph_hash(
+            G1, edge_attr="edge_attr2", node_attr="node_attr2"
+        )
+        g1_hash_edge1_node2 = nx.weisfeiler_lehman_graph_hash(
+            G1, edge_attr="edge_attr1", node_attr="node_attr2"
+        )
+        g1_hash_no_attr = nx.weisfeiler_lehman_graph_hash(G1)
+
+        assert g1_hash_edge1_node1 != g1_hash_no_attr
+        assert g1_hash_edge2_node2 != g1_hash_no_attr
+        assert g1_hash_edge1_node1 != g1_hash_edge2_node2
+        assert g1_hash_edge1_node2 != g1_hash_edge2_node2
+        assert g1_hash_edge1_node2 != g1_hash_edge1_node1
+
+        G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
+
+        g2_hash_edge1_node1 = nx.weisfeiler_lehman_graph_hash(
+            G2, edge_attr="edge_attr1", node_attr="node_attr1"
+        )
+        g2_hash_edge2_node2 = nx.weisfeiler_lehman_graph_hash(
+            G2, edge_attr="edge_attr2", node_attr="node_attr2"
+        )
+
+        assert g1_hash_edge1_node1 == g2_hash_edge1_node1
+        assert g1_hash_edge2_node2 == g2_hash_edge2_node2
+
+
+def test_digest_size():
+    """
+    The hash string lengths should be as expected for a variety of graphs and
+    digest sizes
+    """
+    n, r = 100, 10
+    p = 1.0 / r
+    for i in range(1, r + 1):
+        G = nx.erdos_renyi_graph(n, p * i, seed=1000 + i)
+
+        h16 = nx.weisfeiler_lehman_graph_hash(G)
+        h32 = nx.weisfeiler_lehman_graph_hash(G, digest_size=32)
+
+        assert h16 != h32
+        assert len(h16) == 16 * 2
+        assert len(h32) == 32 * 2
+
+
+def test_directed_bugs():
+    """
+    These were bugs for directed graphs as discussed in issue #7806
+    """
+    Ga = nx.DiGraph()
+    Gb = nx.DiGraph()
+    Ga.add_nodes_from([1, 2, 3, 4])
+    Gb.add_nodes_from([1, 2, 3, 4])
+    Ga.add_edges_from([(1, 2), (3, 2)])
+    Gb.add_edges_from([(1, 2), (3, 4)])
+    Ga_hash = nx.weisfeiler_lehman_graph_hash(Ga)
+    Gb_hash = nx.weisfeiler_lehman_graph_hash(Gb)
+    assert Ga_hash != Gb_hash
+
+    Tree1 = nx.DiGraph()
+    Tree1.add_edges_from([(0, 4), (1, 5), (2, 6), (3, 7)])
+    Tree1.add_edges_from([(4, 8), (5, 8), (6, 9), (7, 9)])
+    Tree1.add_edges_from([(8, 10), (9, 10)])
+    nx.set_node_attributes(
+        Tree1, {10: "s", 8: "a", 9: "a", 4: "b", 5: "b", 6: "b", 7: "b"}, "weight"
+    )
+    Tree2 = copy.deepcopy(Tree1)
+    nx.set_node_attributes(Tree1, {0: "d", 1: "c", 2: "d", 3: "c"}, "weight")
+    nx.set_node_attributes(Tree2, {0: "d", 1: "d", 2: "c", 3: "c"}, "weight")
+    Tree1_hash_short = nx.weisfeiler_lehman_graph_hash(
+        Tree1, iterations=1, node_attr="weight"
+    )
+    Tree2_hash_short = nx.weisfeiler_lehman_graph_hash(
+        Tree2, iterations=1, node_attr="weight"
+    )
+    assert Tree1_hash_short == Tree2_hash_short
+    Tree1_hash = nx.weisfeiler_lehman_graph_hash(
+        Tree1, node_attr="weight"
+    )  # Default is 3 iterations
+    Tree2_hash = nx.weisfeiler_lehman_graph_hash(Tree2, node_attr="weight")
+    assert Tree1_hash != Tree2_hash
+
+
+def test_trivial_labels_isomorphism():
+    """
+    Trivial labelling of the graph should not change isomorphism verdicts.
+    """
+    n, r = 100, 10
+    p = 1.0 / r
+    for i in range(1, r + 1):
+        G1 = nx.erdos_renyi_graph(n, p * i, seed=500 + i)
+        G2 = nx.erdos_renyi_graph(n, p * i, seed=42 + i)
+        G1_hash = nx.weisfeiler_lehman_graph_hash(G1)
+        G2_hash = nx.weisfeiler_lehman_graph_hash(G2)
+        equal = G1_hash == G2_hash
+
+        nx.set_node_attributes(G1, values=1, name="weight")
+        nx.set_node_attributes(G2, values=1, name="weight")
+        G1_hash_node = nx.weisfeiler_lehman_graph_hash(G1, node_attr="weight")
+        G2_hash_node = nx.weisfeiler_lehman_graph_hash(G2, node_attr="weight")
+        equal_node = G1_hash_node == G2_hash_node
+
+        nx.set_edge_attributes(G1, values="a", name="e_weight")
+        nx.set_edge_attributes(G2, values="a", name="e_weight")
+        G1_hash_edge = nx.weisfeiler_lehman_graph_hash(G1, edge_attr="e_weight")
+        G2_hash_edge = nx.weisfeiler_lehman_graph_hash(G2, edge_attr="e_weight")
+        equal_edge = G1_hash_edge == G2_hash_edge
+
+        G1_hash_both = nx.weisfeiler_lehman_graph_hash(
+            G1, edge_attr="e_weight", node_attr="weight"
+        )
+        G2_hash_both = nx.weisfeiler_lehman_graph_hash(
+            G2, edge_attr="e_weight", node_attr="weight"
+        )
+        equal_both = G1_hash_both == G2_hash_both
+
+        assert equal == equal_node
+        assert equal_node == equal_edge
+        assert equal_edge == equal_both
+
+
+def test_trivial_labels_isomorphism_directed():
+    """
+    Trivial labelling of the graph should not change isomorphism verdicts on digraphs.
+    """
+    n, r = 100, 10
+    p = 1.0 / r
+    for i in range(1, r + 1):
+        G1 = nx.erdos_renyi_graph(n, p * i, directed=True, seed=500 + i)
+        G2 = nx.erdos_renyi_graph(n, p * i, directed=True, seed=42 + i)
+        G1_hash = nx.weisfeiler_lehman_graph_hash(G1)
+        G2_hash = nx.weisfeiler_lehman_graph_hash(G2)
+        equal = G1_hash == G2_hash
+
+        nx.set_node_attributes(G1, values=1, name="weight")
+        nx.set_node_attributes(G2, values=1, name="weight")
+        G1_hash_node = nx.weisfeiler_lehman_graph_hash(G1, node_attr="weight")
+        G2_hash_node = nx.weisfeiler_lehman_graph_hash(G2, node_attr="weight")
+        equal_node = G1_hash_node == G2_hash_node
+
+        nx.set_edge_attributes(G1, values="a", name="e_weight")
+        nx.set_edge_attributes(G2, values="a", name="e_weight")
+        G1_hash_edge = nx.weisfeiler_lehman_graph_hash(G1, edge_attr="e_weight")
+        G2_hash_edge = nx.weisfeiler_lehman_graph_hash(G2, edge_attr="e_weight")
+        equal_edge = G1_hash_edge == G2_hash_edge
+
+        G1_hash_both = nx.weisfeiler_lehman_graph_hash(
+            G1, edge_attr="e_weight", node_attr="weight"
+        )
+        G2_hash_both = nx.weisfeiler_lehman_graph_hash(
+            G2, edge_attr="e_weight", node_attr="weight"
+        )
+        equal_both = G1_hash_both == G2_hash_both
+
+        assert equal == equal_node
+        assert equal_node == equal_edge
+        assert equal_edge == equal_both
+
+    # Specific case that was found to be a bug in issue #7806
+    # Without weights worked
+    Ga = nx.DiGraph()
+    Ga.add_nodes_from([1, 2, 3, 4])
+    Gb = copy.deepcopy(Ga)
+    Ga.add_edges_from([(1, 2), (3, 2)])
+    Gb.add_edges_from([(1, 2), (3, 4)])
+    Ga_hash = nx.weisfeiler_lehman_graph_hash(Ga)
+    Gb_hash = nx.weisfeiler_lehman_graph_hash(Gb)
+    assert Ga_hash != Gb_hash
+
+    # Now with trivial weights
+    nx.set_node_attributes(Ga, values=1, name="weight")
+    nx.set_node_attributes(Gb, values=1, name="weight")
+    Ga_hash = nx.weisfeiler_lehman_graph_hash(Ga, node_attr="weight")
+    Gb_hash = nx.weisfeiler_lehman_graph_hash(Gb, node_attr="weight")
+    assert Ga_hash != Gb_hash
+
+
+def test_trivial_labels_hashes():
+    """
+    Test that 'empty' labelling of nodes or edges shouldn't have a different impact
+    on the calculated hash. Note that we cannot assume that trivial weights have no
+    impact at all. Without (trivial) weights, a node will start with hashing its
+    degree. This step is omitted when there are weights.
+    """
+    n, r = 100, 10
+    p = 1.0 / r
+    for i in range(1, r + 1):
+        G1 = nx.erdos_renyi_graph(n, p * i, seed=500 + i)
+        nx.set_node_attributes(G1, values="", name="weight")
+        first = nx.weisfeiler_lehman_graph_hash(G1, node_attr="weight")
+        nx.set_edge_attributes(G1, values="", name="e_weight")
+        second = nx.weisfeiler_lehman_graph_hash(G1, edge_attr="e_weight")
+        assert first == second
+        third = nx.weisfeiler_lehman_graph_hash(
+            G1, edge_attr="e_weight", node_attr="weight"
+        )
+        assert second == third
+
+
+# Unit tests for the :func:`~networkx.weisfeiler_lehman_subgraph_hashes` function
+
+
+def is_subiteration(a, b):
+    """
+    returns True if that each hash sequence in 'a' is a prefix for
+    the corresponding sequence indexed by the same node in 'b'.
+    """
+    return all(b[node][: len(hashes)] == hashes for node, hashes in a.items())
+
+
+def hexdigest_sizes_correct(a, digest_size):
+    """
+    returns True if all hex digest sizes are the expected length in a
+    node:subgraph-hashes dictionary. Hex digest string length == 2 * bytes digest
+    length since each pair of hex digits encodes 1 byte
+    (https://docs.python.org/3/library/hashlib.html)
+    """
+    hexdigest_size = digest_size * 2
+
+    def list_digest_sizes_correct(l):
+        return all(len(x) == hexdigest_size for x in l)
+
+    return all(list_digest_sizes_correct(hashes) for hashes in a.values())
+
+
+def test_empty_graph_subgraph_hash():
+    """ "
+    empty graphs should give empty dict subgraph hashes regardless of other params
+    """
+    G = nx.empty_graph()
+
+    subgraph_hashes1 = nx.weisfeiler_lehman_subgraph_hashes(G)
+    subgraph_hashes2 = nx.weisfeiler_lehman_subgraph_hashes(G, edge_attr="edge_attr")
+    subgraph_hashes3 = nx.weisfeiler_lehman_subgraph_hashes(G, node_attr="edge_attr")
+    subgraph_hashes4 = nx.weisfeiler_lehman_subgraph_hashes(G, iterations=2)
+    subgraph_hashes5 = nx.weisfeiler_lehman_subgraph_hashes(G, digest_size=64)
+
+    assert subgraph_hashes1 == {}
+    assert subgraph_hashes2 == {}
+    assert subgraph_hashes3 == {}
+    assert subgraph_hashes4 == {}
+    assert subgraph_hashes5 == {}
+
+
+def test_directed_subgraph_hash():
+    """
+    A directed graph with no bi-directional edges should yield different subgraph
+    hashes to the same graph taken as undirected, if all hashes don't collide.
+    """
+    r = 10
+    for i in range(r):
+        G_directed = nx.gn_graph(10 + r, seed=100 + i)
+        G_undirected = nx.to_undirected(G_directed)
+
+        directed_subgraph_hashes = nx.weisfeiler_lehman_subgraph_hashes(G_directed)
+        undirected_subgraph_hashes = nx.weisfeiler_lehman_subgraph_hashes(G_undirected)
+
+        assert directed_subgraph_hashes != undirected_subgraph_hashes
+
+
+def test_reversed_subgraph_hash():
+    """
+    A directed graph with no bi-directional edges should yield different subgraph
+    hashes to the same graph taken with edge directions reversed if there are no
+    hash collisions. Here we test a cycle graph which is the minimal counterexample
+    """
+    G = nx.cycle_graph(5, create_using=nx.DiGraph)
+    nx.set_node_attributes(G, {n: str(n) for n in G.nodes()}, name="label")
+
+    G_reversed = G.reverse()
+
+    h = nx.weisfeiler_lehman_subgraph_hashes(G, node_attr="label")
+    h_reversed = nx.weisfeiler_lehman_subgraph_hashes(G_reversed, node_attr="label")
+
+    assert h != h_reversed
+
+
+def test_isomorphic_subgraph_hash():
+    """
+    the subgraph hashes should be invariant to node-relabeling when the output is
+    reindexed by the same mapping and all hashes don't collide.
+    """
+    n, r = 100, 10
+    p = 1.0 / r
+    for i in range(1, r + 1):
+        G1 = nx.erdos_renyi_graph(n, p * i, seed=200 + i)
+        G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
+
+        g1_subgraph_hashes = nx.weisfeiler_lehman_subgraph_hashes(G1)
+        g2_subgraph_hashes = nx.weisfeiler_lehman_subgraph_hashes(G2)
+
+        assert g1_subgraph_hashes == {-1 * k: v for k, v in g2_subgraph_hashes.items()}
+
+
+def test_isomorphic_edge_attr_subgraph_hash():
+    """
+    Isomorphic graphs with differing edge attributes should yield different subgraph
+    hashes if the 'edge_attr' argument is supplied and populated in the graph, and
+    all hashes don't collide.
+    The output should still be invariant to node-relabeling
+    """
+    n, r = 100, 10
+    p = 1.0 / r
+    for i in range(1, r + 1):
+        G1 = nx.erdos_renyi_graph(n, p * i, seed=300 + i)
+
+        for a, b in G1.edges:
+            G1[a][b]["edge_attr1"] = f"{a}-{b}-1"
+            G1[a][b]["edge_attr2"] = f"{a}-{b}-2"
+
+        g1_hash_with_edge_attr1 = nx.weisfeiler_lehman_subgraph_hashes(
+            G1, edge_attr="edge_attr1"
+        )
+        g1_hash_with_edge_attr2 = nx.weisfeiler_lehman_subgraph_hashes(
+            G1, edge_attr="edge_attr2"
+        )
+        g1_hash_no_edge_attr = nx.weisfeiler_lehman_subgraph_hashes(G1, edge_attr=None)
+
+        assert g1_hash_with_edge_attr1 != g1_hash_no_edge_attr
+        assert g1_hash_with_edge_attr2 != g1_hash_no_edge_attr
+        assert g1_hash_with_edge_attr1 != g1_hash_with_edge_attr2
+
+        G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
+
+        g2_hash_with_edge_attr1 = nx.weisfeiler_lehman_subgraph_hashes(
+            G2, edge_attr="edge_attr1"
+        )
+        g2_hash_with_edge_attr2 = nx.weisfeiler_lehman_subgraph_hashes(
+            G2, edge_attr="edge_attr2"
+        )
+
+        assert g1_hash_with_edge_attr1 == {
+            -1 * k: v for k, v in g2_hash_with_edge_attr1.items()
+        }
+        assert g1_hash_with_edge_attr2 == {
+            -1 * k: v for k, v in g2_hash_with_edge_attr2.items()
+        }
+
+
+def test_missing_edge_attr_subgraph_hash():
+    """
+    If the 'edge_attr' argument is supplied but is missing from an edge in the graph,
+    we should raise a KeyError
+    """
+    G = nx.Graph()
+    G.add_edges_from([(1, 2, {"edge_attr1": "a"}), (1, 3, {})])
+    pytest.raises(
+        KeyError, nx.weisfeiler_lehman_subgraph_hashes, G, edge_attr="edge_attr1"
+    )
+
+
+def test_isomorphic_node_attr_subgraph_hash():
+    """
+    Isomorphic graphs with differing node attributes should yield different subgraph
+    hashes if the 'node_attr' argument is supplied and populated in the graph, and
+    all hashes don't collide.
+    The output should still be invariant to node-relabeling
+    """
+    n, r = 100, 10
+    p = 1.0 / r
+    for i in range(1, r + 1):
+        G1 = nx.erdos_renyi_graph(n, p * i, seed=400 + i)
+
+        for u in G1.nodes():
+            G1.nodes[u]["node_attr1"] = f"{u}-1"
+            G1.nodes[u]["node_attr2"] = f"{u}-2"
+
+        g1_hash_with_node_attr1 = nx.weisfeiler_lehman_subgraph_hashes(
+            G1, node_attr="node_attr1"
+        )
+        g1_hash_with_node_attr2 = nx.weisfeiler_lehman_subgraph_hashes(
+            G1, node_attr="node_attr2"
+        )
+        g1_hash_no_node_attr = nx.weisfeiler_lehman_subgraph_hashes(G1, node_attr=None)
+
+        assert g1_hash_with_node_attr1 != g1_hash_no_node_attr
+        assert g1_hash_with_node_attr2 != g1_hash_no_node_attr
+        assert g1_hash_with_node_attr1 != g1_hash_with_node_attr2
+
+        G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
+
+        g2_hash_with_node_attr1 = nx.weisfeiler_lehman_subgraph_hashes(
+            G2, node_attr="node_attr1"
+        )
+        g2_hash_with_node_attr2 = nx.weisfeiler_lehman_subgraph_hashes(
+            G2, node_attr="node_attr2"
+        )
+
+        assert g1_hash_with_node_attr1 == {
+            -1 * k: v for k, v in g2_hash_with_node_attr1.items()
+        }
+        assert g1_hash_with_node_attr2 == {
+            -1 * k: v for k, v in g2_hash_with_node_attr2.items()
+        }
+
+
+def test_missing_node_attr_subgraph_hash():
+    """
+    If the 'node_attr' argument is supplied but is missing from a node in the graph,
+    we should raise a KeyError
+    """
+    G = nx.Graph()
+    G.add_nodes_from([(1, {"node_attr1": "a"}), (2, {})])
+    G.add_edges_from([(1, 2), (2, 3), (3, 1), (1, 4)])
+    pytest.raises(
+        KeyError, nx.weisfeiler_lehman_subgraph_hashes, G, node_attr="node_attr1"
+    )
+
+
+def test_isomorphic_edge_attr_and_node_attr_subgraph_hash():
+    """
+    Isomorphic graphs with differing node attributes should yield different subgraph
+    hashes if the 'node_attr' and 'edge_attr' argument is supplied and populated in
+    the graph, and all hashes don't collide
+    The output should still be invariant to node-relabeling
+    """
+    n, r = 100, 10
+    p = 1.0 / r
+    for i in range(1, r + 1):
+        G1 = nx.erdos_renyi_graph(n, p * i, seed=500 + i)
+
+        for u in G1.nodes():
+            G1.nodes[u]["node_attr1"] = f"{u}-1"
+            G1.nodes[u]["node_attr2"] = f"{u}-2"
+
+        for a, b in G1.edges:
+            G1[a][b]["edge_attr1"] = f"{a}-{b}-1"
+            G1[a][b]["edge_attr2"] = f"{a}-{b}-2"
+
+        g1_hash_edge1_node1 = nx.weisfeiler_lehman_subgraph_hashes(
+            G1, edge_attr="edge_attr1", node_attr="node_attr1"
+        )
+        g1_hash_edge2_node2 = nx.weisfeiler_lehman_subgraph_hashes(
+            G1, edge_attr="edge_attr2", node_attr="node_attr2"
+        )
+        g1_hash_edge1_node2 = nx.weisfeiler_lehman_subgraph_hashes(
+            G1, edge_attr="edge_attr1", node_attr="node_attr2"
+        )
+        g1_hash_no_attr = nx.weisfeiler_lehman_subgraph_hashes(G1)
+
+        assert g1_hash_edge1_node1 != g1_hash_no_attr
+        assert g1_hash_edge2_node2 != g1_hash_no_attr
+        assert g1_hash_edge1_node1 != g1_hash_edge2_node2
+        assert g1_hash_edge1_node2 != g1_hash_edge2_node2
+        assert g1_hash_edge1_node2 != g1_hash_edge1_node1
+
+        G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()})
+
+        g2_hash_edge1_node1 = nx.weisfeiler_lehman_subgraph_hashes(
+            G2, edge_attr="edge_attr1", node_attr="node_attr1"
+        )
+        g2_hash_edge2_node2 = nx.weisfeiler_lehman_subgraph_hashes(
+            G2, edge_attr="edge_attr2", node_attr="node_attr2"
+        )
+
+        assert g1_hash_edge1_node1 == {
+            -1 * k: v for k, v in g2_hash_edge1_node1.items()
+        }
+        assert g1_hash_edge2_node2 == {
+            -1 * k: v for k, v in g2_hash_edge2_node2.items()
+        }
+
+
+def test_iteration_depth():
+    """
+    All nodes should have the correct number of subgraph hashes in the output when
+    using degree as initial node labels.
+    Subsequent iteration depths for the same graph should be additive for each node
+    """
+    n, r = 100, 10
+    p = 1.0 / r
+    for i in range(1, r + 1):
+        G = nx.erdos_renyi_graph(n, p * i, seed=600 + i)
+
+        depth3 = nx.weisfeiler_lehman_subgraph_hashes(G, iterations=3)
+        depth4 = nx.weisfeiler_lehman_subgraph_hashes(G, iterations=4)
+        depth5 = nx.weisfeiler_lehman_subgraph_hashes(G, iterations=5)
+
+        assert all(len(hashes) == 3 for hashes in depth3.values())
+        assert all(len(hashes) == 4 for hashes in depth4.values())
+        assert all(len(hashes) == 5 for hashes in depth5.values())
+
+        assert is_subiteration(depth3, depth4)
+        assert is_subiteration(depth4, depth5)
+        assert is_subiteration(depth3, depth5)
+
+
+def test_iteration_depth_edge_attr():
+    """
+    All nodes should have the correct number of subgraph hashes in the output when
+    setting initial node labels empty and using an edge attribute when aggregating
+    neighborhoods.
+    Subsequent iteration depths for the same graph should be additive for each node
+    """
+    n, r = 100, 10
+    p = 1.0 / r
+    for i in range(1, r + 1):
+        G = nx.erdos_renyi_graph(n, p * i, seed=700 + i)
+
+        for a, b in G.edges:
+            G[a][b]["edge_attr1"] = f"{a}-{b}-1"
+
+        depth3 = nx.weisfeiler_lehman_subgraph_hashes(
+            G, edge_attr="edge_attr1", iterations=3
+        )
+        depth4 = nx.weisfeiler_lehman_subgraph_hashes(
+            G, edge_attr="edge_attr1", iterations=4
+        )
+        depth5 = nx.weisfeiler_lehman_subgraph_hashes(
+            G, edge_attr="edge_attr1", iterations=5
+        )
+
+        assert all(len(hashes) == 3 for hashes in depth3.values())
+        assert all(len(hashes) == 4 for hashes in depth4.values())
+        assert all(len(hashes) == 5 for hashes in depth5.values())
+
+        assert is_subiteration(depth3, depth4)
+        assert is_subiteration(depth4, depth5)
+        assert is_subiteration(depth3, depth5)
+
+
+def test_iteration_depth_node_attr():
+    """
+    All nodes should have the correct number of subgraph hashes in the output when
+    setting initial node labels to an attribute.
+    Subsequent iteration depths for the same graph should be additive for each node
+    """
+    n, r = 100, 10
+    p = 1.0 / r
+    for i in range(1, r + 1):
+        G = nx.erdos_renyi_graph(n, p * i, seed=800 + i)
+
+        for u in G.nodes():
+            G.nodes[u]["node_attr1"] = f"{u}-1"
+
+        depth3 = nx.weisfeiler_lehman_subgraph_hashes(
+            G, node_attr="node_attr1", iterations=3
+        )
+        depth4 = nx.weisfeiler_lehman_subgraph_hashes(
+            G, node_attr="node_attr1", iterations=4
+        )
+        depth5 = nx.weisfeiler_lehman_subgraph_hashes(
+            G, node_attr="node_attr1", iterations=5
+        )
+
+        assert all(len(hashes) == 3 for hashes in depth3.values())
+        assert all(len(hashes) == 4 for hashes in depth4.values())
+        assert all(len(hashes) == 5 for hashes in depth5.values())
+
+        assert is_subiteration(depth3, depth4)
+        assert is_subiteration(depth4, depth5)
+        assert is_subiteration(depth3, depth5)
+
+
+def test_iteration_depth_node_edge_attr():
+    """
+    All nodes should have the correct number of subgraph hashes in the output when
+    setting initial node labels to an attribute and also using an edge attribute when
+    aggregating neighborhoods.
+    Subsequent iteration depths for the same graph should be additive for each node
+    """
+    n, r = 100, 10
+    p = 1.0 / r
+    for i in range(1, r + 1):
+        G = nx.erdos_renyi_graph(n, p * i, seed=900 + i)
+
+        for u in G.nodes():
+            G.nodes[u]["node_attr1"] = f"{u}-1"
+
+        for a, b in G.edges:
+            G[a][b]["edge_attr1"] = f"{a}-{b}-1"
+
+        depth3 = nx.weisfeiler_lehman_subgraph_hashes(
+            G, edge_attr="edge_attr1", node_attr="node_attr1", iterations=3
+        )
+        depth4 = nx.weisfeiler_lehman_subgraph_hashes(
+            G, edge_attr="edge_attr1", node_attr="node_attr1", iterations=4
+        )
+        depth5 = nx.weisfeiler_lehman_subgraph_hashes(
+            G, edge_attr="edge_attr1", node_attr="node_attr1", iterations=5
+        )
+
+        assert all(len(hashes) == 3 for hashes in depth3.values())
+        assert all(len(hashes) == 4 for hashes in depth4.values())
+        assert all(len(hashes) == 5 for hashes in depth5.values())
+
+        assert is_subiteration(depth3, depth4)
+        assert is_subiteration(depth4, depth5)
+        assert is_subiteration(depth3, depth5)
+
+
+def test_digest_size_subgraph_hash():
+    """
+    The hash string lengths should be as expected for a variety of graphs and
+    digest sizes
+    """
+    n, r = 100, 10
+    p = 1.0 / r
+    for i in range(1, r + 1):
+        G = nx.erdos_renyi_graph(n, p * i, seed=1000 + i)
+
+        digest_size16_hashes = nx.weisfeiler_lehman_subgraph_hashes(G)
+        digest_size32_hashes = nx.weisfeiler_lehman_subgraph_hashes(G, digest_size=32)
+
+        assert digest_size16_hashes != digest_size32_hashes
+
+        assert hexdigest_sizes_correct(digest_size16_hashes, 16)
+        assert hexdigest_sizes_correct(digest_size32_hashes, 32)
+
+
+def test_initial_node_labels_subgraph_hash():
+    """
+    Including the hashed initial label prepends an extra hash to the lists
+    """
+    G = nx.path_graph(5)
+    nx.set_node_attributes(G, {i: int(0 < i < 4) for i in G}, "label")
+    # initial node labels:
+    # 0--1--1--1--0
+
+    without_initial_label = nx.weisfeiler_lehman_subgraph_hashes(G, node_attr="label")
+    assert all(len(v) == 3 for v in without_initial_label.values())
+    # 3 different 1 hop nhds
+    assert len({v[0] for v in without_initial_label.values()}) == 3
+
+    with_initial_label = nx.weisfeiler_lehman_subgraph_hashes(
+        G, node_attr="label", include_initial_labels=True
+    )
+    assert all(len(v) == 4 for v in with_initial_label.values())
+    # 2 different initial labels
+    assert len({v[0] for v in with_initial_label.values()}) == 2
+
+    # check hashes match otherwise
+    for u in G:
+        for a, b in zip(
+            with_initial_label[u][1:], without_initial_label[u], strict=True
+        ):
+            assert a == b
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_graphical.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_graphical.py
new file mode 100644
index 0000000000000000000000000000000000000000..99f766f799d8573e80d905482f4b685a2d16bcc0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_graphical.py
@@ -0,0 +1,163 @@
+import pytest
+
+import networkx as nx
+
+
+def test_valid_degree_sequence1():
+    n = 100
+    p = 0.3
+    for i in range(10):
+        G = nx.erdos_renyi_graph(n, p)
+        deg = (d for n, d in G.degree())
+        assert nx.is_graphical(deg, method="eg")
+        assert nx.is_graphical(deg, method="hh")
+
+
+def test_valid_degree_sequence2():
+    n = 100
+    for i in range(10):
+        G = nx.barabasi_albert_graph(n, 1)
+        deg = (d for n, d in G.degree())
+        assert nx.is_graphical(deg, method="eg")
+        assert nx.is_graphical(deg, method="hh")
+
+
+def test_string_input():
+    pytest.raises(nx.NetworkXException, nx.is_graphical, [], "foo")
+    pytest.raises(nx.NetworkXException, nx.is_graphical, ["red"], "hh")
+    pytest.raises(nx.NetworkXException, nx.is_graphical, ["red"], "eg")
+
+
+def test_non_integer_input():
+    pytest.raises(nx.NetworkXException, nx.is_graphical, [72.5], "eg")
+    pytest.raises(nx.NetworkXException, nx.is_graphical, [72.5], "hh")
+
+
+def test_negative_input():
+    assert not nx.is_graphical([-1], "hh")
+    assert not nx.is_graphical([-1], "eg")
+
+
+class TestAtlas:
+    @classmethod
+    def setup_class(cls):
+        global atlas
+        from networkx.generators import atlas
+
+        cls.GAG = atlas.graph_atlas_g()
+
+    def test_atlas(self):
+        for graph in self.GAG:
+            deg = (d for n, d in graph.degree())
+            assert nx.is_graphical(deg, method="eg")
+            assert nx.is_graphical(deg, method="hh")
+
+
+def test_small_graph_true():
+    z = [5, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
+    assert nx.is_graphical(z, method="hh")
+    assert nx.is_graphical(z, method="eg")
+    z = [10, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2]
+    assert nx.is_graphical(z, method="hh")
+    assert nx.is_graphical(z, method="eg")
+    z = [1, 1, 1, 1, 1, 2, 2, 2, 3, 4]
+    assert nx.is_graphical(z, method="hh")
+    assert nx.is_graphical(z, method="eg")
+
+
+def test_small_graph_false():
+    z = [1000, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
+    assert not nx.is_graphical(z, method="hh")
+    assert not nx.is_graphical(z, method="eg")
+    z = [6, 5, 4, 4, 2, 1, 1, 1]
+    assert not nx.is_graphical(z, method="hh")
+    assert not nx.is_graphical(z, method="eg")
+    z = [1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 4]
+    assert not nx.is_graphical(z, method="hh")
+    assert not nx.is_graphical(z, method="eg")
+
+
+def test_directed_degree_sequence():
+    # Test a range of valid directed degree sequences
+    n, r = 100, 10
+    p = 1.0 / r
+    for i in range(r):
+        G = nx.erdos_renyi_graph(n, p * (i + 1), None, True)
+        din = (d for n, d in G.in_degree())
+        dout = (d for n, d in G.out_degree())
+        assert nx.is_digraphical(din, dout)
+
+
+def test_small_directed_sequences():
+    dout = [5, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
+    din = [3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 1]
+    assert nx.is_digraphical(din, dout)
+    # Test nongraphical directed sequence
+    dout = [1000, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
+    din = [103, 102, 102, 102, 102, 102, 102, 102, 102, 102]
+    assert not nx.is_digraphical(din, dout)
+    # Test digraphical small sequence
+    dout = [1, 1, 1, 1, 1, 2, 2, 2, 3, 4]
+    din = [2, 2, 2, 2, 2, 2, 2, 2, 1, 1]
+    assert nx.is_digraphical(din, dout)
+    # Test nonmatching sum
+    din = [2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1]
+    assert not nx.is_digraphical(din, dout)
+    # Test for negative integer in sequence
+    din = [2, 2, 2, -2, 2, 2, 2, 2, 1, 1, 4]
+    assert not nx.is_digraphical(din, dout)
+    # Test for noninteger
+    din = dout = [1, 1, 1.1, 1]
+    assert not nx.is_digraphical(din, dout)
+    din = dout = [1, 1, "rer", 1]
+    assert not nx.is_digraphical(din, dout)
+
+
+def test_multi_sequence():
+    # Test nongraphical multi sequence
+    seq = [1000, 3, 3, 3, 3, 2, 2, 2, 1, 1]
+    assert not nx.is_multigraphical(seq)
+    # Test small graphical multi sequence
+    seq = [6, 5, 4, 4, 2, 1, 1, 1]
+    assert nx.is_multigraphical(seq)
+    # Test for negative integer in sequence
+    seq = [6, 5, 4, -4, 2, 1, 1, 1]
+    assert not nx.is_multigraphical(seq)
+    # Test for sequence with odd sum
+    seq = [1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 4]
+    assert not nx.is_multigraphical(seq)
+    # Test for noninteger
+    seq = [1, 1, 1.1, 1]
+    assert not nx.is_multigraphical(seq)
+    seq = [1, 1, "rer", 1]
+    assert not nx.is_multigraphical(seq)
+
+
+def test_pseudo_sequence():
+    # Test small valid pseudo sequence
+    seq = [1000, 3, 3, 3, 3, 2, 2, 2, 1, 1]
+    assert nx.is_pseudographical(seq)
+    # Test for sequence with odd sum
+    seq = [1000, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
+    assert not nx.is_pseudographical(seq)
+    # Test for negative integer in sequence
+    seq = [1000, 3, 3, 3, 3, 2, 2, -2, 1, 1]
+    assert not nx.is_pseudographical(seq)
+    # Test for noninteger
+    seq = [1, 1, 1.1, 1]
+    assert not nx.is_pseudographical(seq)
+    seq = [1, 1, "rer", 1]
+    assert not nx.is_pseudographical(seq)
+
+
+def test_numpy_degree_sequence():
+    np = pytest.importorskip("numpy")
+    ds = np.array([1, 2, 2, 2, 1], dtype=np.int64)
+    assert nx.is_graphical(ds, "eg")
+    assert nx.is_graphical(ds, "hh")
+    ds = np.array([1, 2, 2, 2, 1], dtype=np.float64)
+    assert nx.is_graphical(ds, "eg")
+    assert nx.is_graphical(ds, "hh")
+    ds = np.array([1.1, 2, 2, 2, 1], dtype=np.float64)
+    pytest.raises(nx.NetworkXException, nx.is_graphical, ds, "eg")
+    pytest.raises(nx.NetworkXException, nx.is_graphical, ds, "hh")
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_hierarchy.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_hierarchy.py
new file mode 100644
index 0000000000000000000000000000000000000000..eaa6a67b8b7f048719aa189b8365ef8e4c65951c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_hierarchy.py
@@ -0,0 +1,46 @@
+import pytest
+
+import networkx as nx
+
+
+def test_hierarchy_undirected():
+    G = nx.cycle_graph(5)
+    pytest.raises(nx.NetworkXError, nx.flow_hierarchy, G)
+
+
+def test_hierarchy_cycle():
+    G = nx.cycle_graph(5, create_using=nx.DiGraph())
+    assert nx.flow_hierarchy(G) == 0.0
+
+
+def test_hierarchy_tree():
+    G = nx.full_rary_tree(2, 16, create_using=nx.DiGraph())
+    assert nx.flow_hierarchy(G) == 1.0
+
+
+def test_hierarchy_1():
+    G = nx.DiGraph()
+    G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 1), (3, 4), (0, 4)])
+    assert nx.flow_hierarchy(G) == 0.5
+
+
+def test_hierarchy_weight():
+    G = nx.DiGraph()
+    G.add_edges_from(
+        [
+            (0, 1, {"weight": 0.3}),
+            (1, 2, {"weight": 0.1}),
+            (2, 3, {"weight": 0.1}),
+            (3, 1, {"weight": 0.1}),
+            (3, 4, {"weight": 0.3}),
+            (0, 4, {"weight": 0.3}),
+        ]
+    )
+    assert nx.flow_hierarchy(G, weight="weight") == 0.75
+
+
+@pytest.mark.parametrize("n", (0, 1, 3))
+def test_hierarchy_empty_graph(n):
+    G = nx.empty_graph(n, create_using=nx.DiGraph)
+    with pytest.raises(nx.NetworkXError, match=".*not applicable to empty graphs"):
+        nx.flow_hierarchy(G)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_hybrid.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_hybrid.py
new file mode 100644
index 0000000000000000000000000000000000000000..6af0016498549caed58772e304c93113a8b693d9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_hybrid.py
@@ -0,0 +1,24 @@
+import networkx as nx
+
+
+def test_2d_grid_graph():
+    # FC article claims 2d grid graph of size n is (3,3)-connected
+    # and (5,9)-connected, but I don't think it is (5,9)-connected
+    G = nx.grid_2d_graph(8, 8, periodic=True)
+    assert nx.is_kl_connected(G, 3, 3)
+    assert not nx.is_kl_connected(G, 5, 9)
+    (H, graphOK) = nx.kl_connected_subgraph(G, 5, 9, same_as_graph=True)
+    assert not graphOK
+
+
+def test_small_graph():
+    G = nx.Graph()
+    G.add_edge(1, 2)
+    G.add_edge(1, 3)
+    G.add_edge(2, 3)
+    assert nx.is_kl_connected(G, 2, 2)
+    H = nx.kl_connected_subgraph(G, 2, 2)
+    (H, graphOK) = nx.kl_connected_subgraph(
+        G, 2, 2, low_memory=True, same_as_graph=True
+    )
+    assert graphOK
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_isolate.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_isolate.py
new file mode 100644
index 0000000000000000000000000000000000000000..d29b306d2b13c2457905c41218e5c60793b309ba
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_isolate.py
@@ -0,0 +1,26 @@
+"""Unit tests for the :mod:`networkx.algorithms.isolates` module."""
+
+import networkx as nx
+
+
+def test_is_isolate():
+    G = nx.Graph()
+    G.add_edge(0, 1)
+    G.add_node(2)
+    assert not nx.is_isolate(G, 0)
+    assert not nx.is_isolate(G, 1)
+    assert nx.is_isolate(G, 2)
+
+
+def test_isolates():
+    G = nx.Graph()
+    G.add_edge(0, 1)
+    G.add_nodes_from([2, 3])
+    assert sorted(nx.isolates(G)) == [2, 3]
+
+
+def test_number_of_isolates():
+    G = nx.Graph()
+    G.add_edge(0, 1)
+    G.add_nodes_from([2, 3])
+    assert nx.number_of_isolates(G) == 2
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_link_prediction.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_link_prediction.py
new file mode 100644
index 0000000000000000000000000000000000000000..0220d9cd24dc5f1eceb8937e3274a21415529349
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_link_prediction.py
@@ -0,0 +1,615 @@
+import math
+from functools import partial
+
+import pytest
+
+import networkx as nx
+
+
+def _test_func(G, ebunch, expected, predict_func, **kwargs):
+    result = predict_func(G, ebunch, **kwargs)
+    exp_dict = {tuple(sorted([u, v])): score for u, v, score in expected}
+    res_dict = {tuple(sorted([u, v])): score for u, v, score in result}
+
+    assert len(exp_dict) == len(res_dict)
+    for p in exp_dict:
+        assert exp_dict[p] == pytest.approx(res_dict[p], abs=1e-7)
+
+
+class TestResourceAllocationIndex:
+    @classmethod
+    def setup_class(cls):
+        cls.func = staticmethod(nx.resource_allocation_index)
+        cls.test = staticmethod(partial(_test_func, predict_func=cls.func))
+
+    def test_K5(self):
+        G = nx.complete_graph(5)
+        self.test(G, [(0, 1)], [(0, 1, 0.75)])
+
+    def test_P3(self):
+        G = nx.path_graph(3)
+        self.test(G, [(0, 2)], [(0, 2, 0.5)])
+
+    def test_S4(self):
+        G = nx.star_graph(4)
+        self.test(G, [(1, 2)], [(1, 2, 0.25)])
+
+    @pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
+    def test_notimplemented(self, graph_type):
+        G = graph_type([(0, 1), (1, 2)])
+        with pytest.raises(nx.NetworkXNotImplemented):
+            self.func(G, [(0, 2)])
+
+    def test_node_not_found(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (2, 3)])
+        with pytest.raises(nx.NodeNotFound):
+            self.func(G, [(0, 4)])
+
+    def test_no_common_neighbor(self):
+        G = nx.Graph()
+        G.add_nodes_from([0, 1])
+        self.test(G, [(0, 1)], [(0, 1, 0)])
+
+    def test_equal_nodes(self):
+        G = nx.complete_graph(4)
+        self.test(G, [(0, 0)], [(0, 0, 1)])
+
+    def test_all_nonexistent_edges(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (2, 3)])
+        self.test(G, None, [(0, 3, 0.5), (1, 2, 0.5), (1, 3, 0)])
+
+
+class TestJaccardCoefficient:
+    @classmethod
+    def setup_class(cls):
+        cls.func = staticmethod(nx.jaccard_coefficient)
+        cls.test = staticmethod(partial(_test_func, predict_func=cls.func))
+
+    def test_K5(self):
+        G = nx.complete_graph(5)
+        self.test(G, [(0, 1)], [(0, 1, 0.6)])
+
+    def test_P4(self):
+        G = nx.path_graph(4)
+        self.test(G, [(0, 2)], [(0, 2, 0.5)])
+
+    @pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
+    def test_notimplemented(self, graph_type):
+        G = graph_type([(0, 1), (1, 2)])
+        with pytest.raises(nx.NetworkXNotImplemented):
+            self.func(G, [(0, 2)])
+
+    def test_node_not_found(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (2, 3)])
+        with pytest.raises(nx.NodeNotFound):
+            self.func(G, [(0, 4)])
+
+    def test_no_common_neighbor(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (2, 3)])
+        self.test(G, [(0, 2)], [(0, 2, 0)])
+
+    def test_isolated_nodes(self):
+        G = nx.Graph()
+        G.add_nodes_from([0, 1])
+        self.test(G, [(0, 1)], [(0, 1, 0)])
+
+    def test_all_nonexistent_edges(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (2, 3)])
+        self.test(G, None, [(0, 3, 0.5), (1, 2, 0.5), (1, 3, 0)])
+
+
+class TestAdamicAdarIndex:
+    @classmethod
+    def setup_class(cls):
+        cls.func = staticmethod(nx.adamic_adar_index)
+        cls.test = staticmethod(partial(_test_func, predict_func=cls.func))
+
+    def test_K5(self):
+        G = nx.complete_graph(5)
+        self.test(G, [(0, 1)], [(0, 1, 3 / math.log(4))])
+
+    def test_P3(self):
+        G = nx.path_graph(3)
+        self.test(G, [(0, 2)], [(0, 2, 1 / math.log(2))])
+
+    def test_S4(self):
+        G = nx.star_graph(4)
+        self.test(G, [(1, 2)], [(1, 2, 1 / math.log(4))])
+
+    @pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
+    def test_notimplemented(self, graph_type):
+        with pytest.raises(nx.NetworkXNotImplemented):
+            G = graph_type([(0, 1), (1, 2)])
+            self.func(G, [(0, 2)])
+
+    def test_node_not_found(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (2, 3)])
+        with pytest.raises(nx.NodeNotFound):
+            self.func(G, [(0, 4)])
+
+    def test_no_common_neighbor(self):
+        G = nx.Graph()
+        G.add_nodes_from([0, 1])
+        self.test(G, [(0, 1)], [(0, 1, 0)])
+
+    def test_equal_nodes(self):
+        G = nx.complete_graph(4)
+        self.test(G, [(0, 0)], [(0, 0, 3 / math.log(3))])
+
+    def test_all_nonexistent_edges(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (2, 3)])
+        self.test(
+            G, None, [(0, 3, 1 / math.log(2)), (1, 2, 1 / math.log(2)), (1, 3, 0)]
+        )
+
+
+class TestCommonNeighborCentrality:
+    @classmethod
+    def setup_class(cls):
+        cls.func = staticmethod(nx.common_neighbor_centrality)
+        cls.test = staticmethod(partial(_test_func, predict_func=cls.func))
+
+    def test_K5(self):
+        G = nx.complete_graph(5)
+        self.test(G, [(0, 1)], [(0, 1, 3.0)], alpha=1)
+        self.test(G, [(0, 1)], [(0, 1, 5.0)], alpha=0)
+
+    def test_P3(self):
+        G = nx.path_graph(3)
+        self.test(G, [(0, 2)], [(0, 2, 1.25)], alpha=0.5)
+
+    def test_S4(self):
+        G = nx.star_graph(4)
+        self.test(G, [(1, 2)], [(1, 2, 1.75)], alpha=0.5)
+
+    @pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
+    def test_notimplemented(self, graph_type):
+        G = graph_type([(0, 1), (1, 2)])
+        with pytest.raises(nx.NetworkXNotImplemented):
+            self.func(G, [(0, 2)])
+
+    def test_node_u_not_found(self):
+        G = nx.Graph()
+        G.add_edges_from([(1, 3), (2, 3)])
+        with pytest.raises(nx.NodeNotFound):
+            self.func(G, [(0, 1)])
+
+    def test_node_v_not_found(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (2, 3)])
+        with pytest.raises(nx.NodeNotFound):
+            self.func(G, [(0, 4)])
+
+    def test_no_common_neighbor(self):
+        G = nx.Graph()
+        G.add_nodes_from([0, 1])
+        self.test(G, [(0, 1)], [(0, 1, 0)])
+
+    def test_equal_nodes(self):
+        G = nx.complete_graph(4)
+        with pytest.raises(nx.NetworkXAlgorithmError):
+            self.test(G, [(0, 0)], [])
+
+    def test_equal_nodes_with_alpha_one_raises_error(self):
+        G = nx.complete_graph(4)
+        with pytest.raises(nx.NetworkXAlgorithmError):
+            self.test(G, [(0, 0)], [], alpha=1.0)
+
+    def test_all_nonexistent_edges(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (2, 3)])
+        self.test(G, None, [(0, 3, 1.5), (1, 2, 1.5), (1, 3, 2 / 3)], alpha=0.5)
+
+
+class TestPreferentialAttachment:
+    @classmethod
+    def setup_class(cls):
+        cls.func = staticmethod(nx.preferential_attachment)
+        cls.test = staticmethod(partial(_test_func, predict_func=cls.func))
+
+    def test_K5(self):
+        G = nx.complete_graph(5)
+        self.test(G, [(0, 1)], [(0, 1, 16)])
+
+    def test_P3(self):
+        G = nx.path_graph(3)
+        self.test(G, [(0, 1)], [(0, 1, 2)])
+
+    def test_S4(self):
+        G = nx.star_graph(4)
+        self.test(G, [(0, 2)], [(0, 2, 4)])
+
+    @pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
+    def test_notimplemented(self, graph_type):
+        G = graph_type([(0, 1), (1, 2)])
+        with pytest.raises(nx.NetworkXNotImplemented):
+            self.func(G, [(0, 2)])
+
+    def test_node_not_found(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (2, 3)])
+        with pytest.raises(nx.NodeNotFound):
+            self.func(G, [(0, 4)])
+
+    def test_zero_degrees(self):
+        G = nx.Graph()
+        G.add_nodes_from([0, 1])
+        self.test(G, [(0, 1)], [(0, 1, 0)])
+
+    def test_all_nonexistent_edges(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (2, 3)])
+        self.test(G, None, [(0, 3, 2), (1, 2, 2), (1, 3, 1)])
+
+
+class TestCNSoundarajanHopcroft:
+    @classmethod
+    def setup_class(cls):
+        cls.func = staticmethod(nx.cn_soundarajan_hopcroft)
+        cls.test = staticmethod(
+            partial(_test_func, predict_func=cls.func, community="community")
+        )
+
+    def test_K5(self):
+        G = nx.complete_graph(5)
+        G.nodes[0]["community"] = 0
+        G.nodes[1]["community"] = 0
+        G.nodes[2]["community"] = 0
+        G.nodes[3]["community"] = 0
+        G.nodes[4]["community"] = 1
+        self.test(G, [(0, 1)], [(0, 1, 5)])
+
+    def test_P3(self):
+        G = nx.path_graph(3)
+        G.nodes[0]["community"] = 0
+        G.nodes[1]["community"] = 1
+        G.nodes[2]["community"] = 0
+        self.test(G, [(0, 2)], [(0, 2, 1)])
+
+    def test_S4(self):
+        G = nx.star_graph(4)
+        G.nodes[0]["community"] = 1
+        G.nodes[1]["community"] = 1
+        G.nodes[2]["community"] = 1
+        G.nodes[3]["community"] = 0
+        G.nodes[4]["community"] = 0
+        self.test(G, [(1, 2)], [(1, 2, 2)])
+
+    @pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
+    def test_notimplemented(self, graph_type):
+        G = graph_type([(0, 1), (1, 2)])
+        G.add_nodes_from([0, 1, 2], community=0)
+        with pytest.raises(nx.NetworkXNotImplemented):
+            self.func(G, [(0, 2)])
+
+    def test_node_not_found(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (2, 3)])
+        G.nodes[0]["community"] = 0
+        G.nodes[1]["community"] = 1
+        G.nodes[2]["community"] = 0
+        G.nodes[3]["community"] = 0
+        with pytest.raises(nx.NodeNotFound):
+            self.func(G, [(0, 4)])
+
+    def test_no_common_neighbor(self):
+        G = nx.Graph()
+        G.add_nodes_from([0, 1])
+        G.nodes[0]["community"] = 0
+        G.nodes[1]["community"] = 0
+        self.test(G, [(0, 1)], [(0, 1, 0)])
+
+    def test_equal_nodes(self):
+        G = nx.complete_graph(3)
+        G.nodes[0]["community"] = 0
+        G.nodes[1]["community"] = 0
+        G.nodes[2]["community"] = 0
+        self.test(G, [(0, 0)], [(0, 0, 4)])
+
+    def test_different_community(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
+        G.nodes[0]["community"] = 0
+        G.nodes[1]["community"] = 0
+        G.nodes[2]["community"] = 0
+        G.nodes[3]["community"] = 1
+        self.test(G, [(0, 3)], [(0, 3, 2)])
+
+    def test_no_community_information(self):
+        G = nx.complete_graph(5)
+        with pytest.raises(nx.NetworkXAlgorithmError):
+            list(self.func(G, [(0, 1)]))
+
+    def test_insufficient_community_information(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
+        G.nodes[0]["community"] = 0
+        G.nodes[1]["community"] = 0
+        G.nodes[3]["community"] = 0
+        with pytest.raises(nx.NetworkXAlgorithmError):
+            list(self.func(G, [(0, 3)]))
+
+    def test_sufficient_community_information(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (1, 2), (1, 3), (2, 4), (3, 4), (4, 5)])
+        G.nodes[1]["community"] = 0
+        G.nodes[2]["community"] = 0
+        G.nodes[3]["community"] = 0
+        G.nodes[4]["community"] = 0
+        self.test(G, [(1, 4)], [(1, 4, 4)])
+
+    def test_custom_community_attribute_name(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
+        G.nodes[0]["cmty"] = 0
+        G.nodes[1]["cmty"] = 0
+        G.nodes[2]["cmty"] = 0
+        G.nodes[3]["cmty"] = 1
+        self.test(G, [(0, 3)], [(0, 3, 2)], community="cmty")
+
+    def test_all_nonexistent_edges(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (2, 3)])
+        G.nodes[0]["community"] = 0
+        G.nodes[1]["community"] = 1
+        G.nodes[2]["community"] = 0
+        G.nodes[3]["community"] = 0
+        self.test(G, None, [(0, 3, 2), (1, 2, 1), (1, 3, 0)])
+
+
+class TestRAIndexSoundarajanHopcroft:
+    @classmethod
+    def setup_class(cls):
+        cls.func = staticmethod(nx.ra_index_soundarajan_hopcroft)
+        cls.test = staticmethod(
+            partial(_test_func, predict_func=cls.func, community="community")
+        )
+
+    def test_K5(self):
+        G = nx.complete_graph(5)
+        G.nodes[0]["community"] = 0
+        G.nodes[1]["community"] = 0
+        G.nodes[2]["community"] = 0
+        G.nodes[3]["community"] = 0
+        G.nodes[4]["community"] = 1
+        self.test(G, [(0, 1)], [(0, 1, 0.5)])
+
+    def test_P3(self):
+        G = nx.path_graph(3)
+        G.nodes[0]["community"] = 0
+        G.nodes[1]["community"] = 1
+        G.nodes[2]["community"] = 0
+        self.test(G, [(0, 2)], [(0, 2, 0)])
+
+    def test_S4(self):
+        G = nx.star_graph(4)
+        G.nodes[0]["community"] = 1
+        G.nodes[1]["community"] = 1
+        G.nodes[2]["community"] = 1
+        G.nodes[3]["community"] = 0
+        G.nodes[4]["community"] = 0
+        self.test(G, [(1, 2)], [(1, 2, 0.25)])
+
+    @pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
+    def test_notimplemented(self, graph_type):
+        G = graph_type([(0, 1), (1, 2)])
+        G.add_nodes_from([0, 1, 2], community=0)
+        with pytest.raises(nx.NetworkXNotImplemented):
+            self.func(G, [(0, 2)])
+
+    def test_node_not_found(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (2, 3)])
+        G.nodes[0]["community"] = 0
+        G.nodes[1]["community"] = 1
+        G.nodes[2]["community"] = 0
+        G.nodes[3]["community"] = 0
+        with pytest.raises(nx.NodeNotFound):
+            self.func(G, [(0, 4)])
+
+    def test_no_common_neighbor(self):
+        G = nx.Graph()
+        G.add_nodes_from([0, 1])
+        G.nodes[0]["community"] = 0
+        G.nodes[1]["community"] = 0
+        self.test(G, [(0, 1)], [(0, 1, 0)])
+
+    def test_equal_nodes(self):
+        G = nx.complete_graph(3)
+        G.nodes[0]["community"] = 0
+        G.nodes[1]["community"] = 0
+        G.nodes[2]["community"] = 0
+        self.test(G, [(0, 0)], [(0, 0, 1)])
+
+    def test_different_community(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
+        G.nodes[0]["community"] = 0
+        G.nodes[1]["community"] = 0
+        G.nodes[2]["community"] = 0
+        G.nodes[3]["community"] = 1
+        self.test(G, [(0, 3)], [(0, 3, 0)])
+
+    def test_no_community_information(self):
+        G = nx.complete_graph(5)
+        with pytest.raises(nx.NetworkXAlgorithmError):
+            list(self.func(G, [(0, 1)]))
+
+    def test_insufficient_community_information(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
+        G.nodes[0]["community"] = 0
+        G.nodes[1]["community"] = 0
+        G.nodes[3]["community"] = 0
+        with pytest.raises(nx.NetworkXAlgorithmError):
+            list(self.func(G, [(0, 3)]))
+
+    def test_sufficient_community_information(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (1, 2), (1, 3), (2, 4), (3, 4), (4, 5)])
+        G.nodes[1]["community"] = 0
+        G.nodes[2]["community"] = 0
+        G.nodes[3]["community"] = 0
+        G.nodes[4]["community"] = 0
+        self.test(G, [(1, 4)], [(1, 4, 1)])
+
+    def test_custom_community_attribute_name(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
+        G.nodes[0]["cmty"] = 0
+        G.nodes[1]["cmty"] = 0
+        G.nodes[2]["cmty"] = 0
+        G.nodes[3]["cmty"] = 1
+        self.test(G, [(0, 3)], [(0, 3, 0)], community="cmty")
+
+    def test_all_nonexistent_edges(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (2, 3)])
+        G.nodes[0]["community"] = 0
+        G.nodes[1]["community"] = 1
+        G.nodes[2]["community"] = 0
+        G.nodes[3]["community"] = 0
+        self.test(G, None, [(0, 3, 0.5), (1, 2, 0), (1, 3, 0)])
+
+
+class TestWithinInterCluster:
+    @classmethod
+    def setup_class(cls):
+        cls.delta = 0.001
+        cls.func = staticmethod(nx.within_inter_cluster)
+        cls.test = staticmethod(
+            partial(
+                _test_func,
+                predict_func=cls.func,
+                delta=cls.delta,
+                community="community",
+            )
+        )
+
+    def test_K5(self):
+        G = nx.complete_graph(5)
+        G.nodes[0]["community"] = 0
+        G.nodes[1]["community"] = 0
+        G.nodes[2]["community"] = 0
+        G.nodes[3]["community"] = 0
+        G.nodes[4]["community"] = 1
+        self.test(G, [(0, 1)], [(0, 1, 2 / (1 + self.delta))])
+
+    def test_P3(self):
+        G = nx.path_graph(3)
+        G.nodes[0]["community"] = 0
+        G.nodes[1]["community"] = 1
+        G.nodes[2]["community"] = 0
+        self.test(G, [(0, 2)], [(0, 2, 0)])
+
+    def test_S4(self):
+        G = nx.star_graph(4)
+        G.nodes[0]["community"] = 1
+        G.nodes[1]["community"] = 1
+        G.nodes[2]["community"] = 1
+        G.nodes[3]["community"] = 0
+        G.nodes[4]["community"] = 0
+        self.test(G, [(1, 2)], [(1, 2, 1 / self.delta)])
+
+    @pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
+    def test_notimplemented(self, graph_type):
+        G = graph_type([(0, 1), (1, 2)])
+        G.add_nodes_from([0, 1, 2], community=0)
+        with pytest.raises(nx.NetworkXNotImplemented):
+            self.func(G, [(0, 2)])
+
+    def test_node_not_found(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (2, 3)])
+        G.nodes[0]["community"] = 0
+        G.nodes[1]["community"] = 1
+        G.nodes[2]["community"] = 0
+        G.nodes[3]["community"] = 0
+        with pytest.raises(nx.NodeNotFound):
+            self.func(G, [(0, 4)])
+
+    def test_no_common_neighbor(self):
+        G = nx.Graph()
+        G.add_nodes_from([0, 1])
+        G.nodes[0]["community"] = 0
+        G.nodes[1]["community"] = 0
+        self.test(G, [(0, 1)], [(0, 1, 0)])
+
+    def test_equal_nodes(self):
+        G = nx.complete_graph(3)
+        G.nodes[0]["community"] = 0
+        G.nodes[1]["community"] = 0
+        G.nodes[2]["community"] = 0
+        self.test(G, [(0, 0)], [(0, 0, 2 / self.delta)])
+
+    def test_different_community(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
+        G.nodes[0]["community"] = 0
+        G.nodes[1]["community"] = 0
+        G.nodes[2]["community"] = 0
+        G.nodes[3]["community"] = 1
+        self.test(G, [(0, 3)], [(0, 3, 0)])
+
+    def test_no_inter_cluster_common_neighbor(self):
+        G = nx.complete_graph(4)
+        G.nodes[0]["community"] = 0
+        G.nodes[1]["community"] = 0
+        G.nodes[2]["community"] = 0
+        G.nodes[3]["community"] = 0
+        self.test(G, [(0, 3)], [(0, 3, 2 / self.delta)])
+
+    def test_no_community_information(self):
+        G = nx.complete_graph(5)
+        with pytest.raises(nx.NetworkXAlgorithmError):
+            list(self.func(G, [(0, 1)]))
+
+    def test_insufficient_community_information(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
+        G.nodes[0]["community"] = 0
+        G.nodes[1]["community"] = 0
+        G.nodes[3]["community"] = 0
+        with pytest.raises(nx.NetworkXAlgorithmError):
+            list(self.func(G, [(0, 3)]))
+
+    def test_sufficient_community_information(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (1, 2), (1, 3), (2, 4), (3, 4), (4, 5)])
+        G.nodes[1]["community"] = 0
+        G.nodes[2]["community"] = 0
+        G.nodes[3]["community"] = 0
+        G.nodes[4]["community"] = 0
+        self.test(G, [(1, 4)], [(1, 4, 2 / self.delta)])
+
+    def test_invalid_delta(self):
+        G = nx.complete_graph(3)
+        G.add_nodes_from([0, 1, 2], community=0)
+        with pytest.raises(nx.NetworkXAlgorithmError):
+            self.func(G, [(0, 1)], 0)
+        with pytest.raises(nx.NetworkXAlgorithmError):
+            self.func(G, [(0, 1)], -0.5)
+
+    def test_custom_community_attribute_name(self):
+        G = nx.complete_graph(4)
+        G.nodes[0]["cmty"] = 0
+        G.nodes[1]["cmty"] = 0
+        G.nodes[2]["cmty"] = 0
+        G.nodes[3]["cmty"] = 0
+        self.test(G, [(0, 3)], [(0, 3, 2 / self.delta)], community="cmty")
+
+    def test_all_nonexistent_edges(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (2, 3)])
+        G.nodes[0]["community"] = 0
+        G.nodes[1]["community"] = 1
+        G.nodes[2]["community"] = 0
+        G.nodes[3]["community"] = 0
+        self.test(G, None, [(0, 3, 1 / self.delta), (1, 2, 0), (1, 3, 0)])
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_lowest_common_ancestors.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_lowest_common_ancestors.py
new file mode 100644
index 0000000000000000000000000000000000000000..639a31fd5f306e2df432cf03d45154f5ee3ea48d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_lowest_common_ancestors.py
@@ -0,0 +1,459 @@
+from itertools import chain, combinations, product
+
+import pytest
+
+import networkx as nx
+
+tree_all_pairs_lca = nx.tree_all_pairs_lowest_common_ancestor
+all_pairs_lca = nx.all_pairs_lowest_common_ancestor
+
+
+def get_pair(dictionary, n1, n2):
+    if (n1, n2) in dictionary:
+        return dictionary[n1, n2]
+    else:
+        return dictionary[n2, n1]
+
+
+class TestTreeLCA:
+    @classmethod
+    def setup_class(cls):
+        cls.DG = nx.DiGraph()
+        edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6)]
+        cls.DG.add_edges_from(edges)
+        cls.ans = dict(tree_all_pairs_lca(cls.DG, 0))
+        gold = {(n, n): n for n in cls.DG}
+        gold.update({(0, i): 0 for i in range(1, 7)})
+        gold.update(
+            {
+                (1, 2): 0,
+                (1, 3): 1,
+                (1, 4): 1,
+                (1, 5): 0,
+                (1, 6): 0,
+                (2, 3): 0,
+                (2, 4): 0,
+                (2, 5): 2,
+                (2, 6): 2,
+                (3, 4): 1,
+                (3, 5): 0,
+                (3, 6): 0,
+                (4, 5): 0,
+                (4, 6): 0,
+                (5, 6): 2,
+            }
+        )
+
+        cls.gold = gold
+
+    @staticmethod
+    def assert_has_same_pairs(d1, d2):
+        for a, b in ((min(pair), max(pair)) for pair in chain(d1, d2)):
+            assert get_pair(d1, a, b) == get_pair(d2, a, b)
+
+    def test_tree_all_pairs_lca_default_root(self):
+        assert dict(tree_all_pairs_lca(self.DG)) == self.ans
+
+    def test_tree_all_pairs_lca_return_subset(self):
+        test_pairs = [(0, 1), (0, 1), (1, 0)]
+        ans = dict(tree_all_pairs_lca(self.DG, 0, test_pairs))
+        assert (0, 1) in ans and (1, 0) in ans
+        assert len(ans) == 2
+
+    def test_tree_all_pairs_lca(self):
+        all_pairs = chain(combinations(self.DG, 2), ((node, node) for node in self.DG))
+
+        ans = dict(tree_all_pairs_lca(self.DG, 0, all_pairs))
+        self.assert_has_same_pairs(ans, self.ans)
+
+    def test_tree_all_pairs_gold_example(self):
+        ans = dict(tree_all_pairs_lca(self.DG))
+        self.assert_has_same_pairs(self.gold, ans)
+
+    def test_tree_all_pairs_lca_invalid_input(self):
+        empty_digraph = tree_all_pairs_lca(nx.DiGraph())
+        pytest.raises(nx.NetworkXPointlessConcept, list, empty_digraph)
+
+        bad_pairs_digraph = tree_all_pairs_lca(self.DG, pairs=[(-1, -2)])
+        pytest.raises(nx.NodeNotFound, list, bad_pairs_digraph)
+
+    def test_tree_all_pairs_lca_subtrees(self):
+        ans = dict(tree_all_pairs_lca(self.DG, 1))
+        gold = {
+            pair: lca
+            for (pair, lca) in self.gold.items()
+            if all(n in (1, 3, 4) for n in pair)
+        }
+        self.assert_has_same_pairs(gold, ans)
+
+    def test_tree_all_pairs_lca_disconnected_nodes(self):
+        G = nx.DiGraph()
+        G.add_node(1)
+        assert {(1, 1): 1} == dict(tree_all_pairs_lca(G))
+
+        G.add_node(0)
+        assert {(1, 1): 1} == dict(tree_all_pairs_lca(G, 1))
+        assert {(0, 0): 0} == dict(tree_all_pairs_lca(G, 0))
+
+        pytest.raises(nx.NetworkXError, list, tree_all_pairs_lca(G))
+
+    def test_tree_all_pairs_lca_error_if_input_not_tree(self):
+        # Cycle
+        G = nx.DiGraph([(1, 2), (2, 1)])
+        pytest.raises(nx.NetworkXError, list, tree_all_pairs_lca(G))
+        # DAG
+        G = nx.DiGraph([(0, 2), (1, 2)])
+        pytest.raises(nx.NetworkXError, list, tree_all_pairs_lca(G))
+
+    def test_tree_all_pairs_lca_generator(self):
+        pairs = iter([(0, 1), (0, 1), (1, 0)])
+        some_pairs = dict(tree_all_pairs_lca(self.DG, 0, pairs))
+        assert (0, 1) in some_pairs and (1, 0) in some_pairs
+        assert len(some_pairs) == 2
+
+    def test_tree_all_pairs_lca_nonexisting_pairs_exception(self):
+        lca = tree_all_pairs_lca(self.DG, 0, [(-1, -1)])
+        pytest.raises(nx.NodeNotFound, list, lca)
+        # check if node is None
+        lca = tree_all_pairs_lca(self.DG, None, [(-1, -1)])
+        pytest.raises(nx.NodeNotFound, list, lca)
+
+    def test_tree_all_pairs_lca_routine_bails_on_DAGs(self):
+        G = nx.DiGraph([(3, 4), (5, 4)])
+        pytest.raises(nx.NetworkXError, list, tree_all_pairs_lca(G))
+
+    def test_tree_all_pairs_lca_not_implemented(self):
+        NNI = nx.NetworkXNotImplemented
+        G = nx.Graph([(0, 1)])
+        with pytest.raises(NNI):
+            next(tree_all_pairs_lca(G))
+        with pytest.raises(NNI):
+            next(all_pairs_lca(G))
+        pytest.raises(NNI, nx.lowest_common_ancestor, G, 0, 1)
+        G = nx.MultiGraph([(0, 1)])
+        with pytest.raises(NNI):
+            next(tree_all_pairs_lca(G))
+        with pytest.raises(NNI):
+            next(all_pairs_lca(G))
+        pytest.raises(NNI, nx.lowest_common_ancestor, G, 0, 1)
+
+    def test_tree_all_pairs_lca_trees_without_LCAs(self):
+        G = nx.DiGraph()
+        G.add_node(3)
+        ans = list(tree_all_pairs_lca(G))
+        assert ans == [((3, 3), 3)]
+
+
+class TestMultiTreeLCA(TestTreeLCA):
+    @classmethod
+    def setup_class(cls):
+        cls.DG = nx.MultiDiGraph()
+        edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6)]
+        cls.DG.add_edges_from(edges)
+        cls.ans = dict(tree_all_pairs_lca(cls.DG, 0))
+        # add multiedges
+        cls.DG.add_edges_from(edges)
+
+        gold = {(n, n): n for n in cls.DG}
+        gold.update({(0, i): 0 for i in range(1, 7)})
+        gold.update(
+            {
+                (1, 2): 0,
+                (1, 3): 1,
+                (1, 4): 1,
+                (1, 5): 0,
+                (1, 6): 0,
+                (2, 3): 0,
+                (2, 4): 0,
+                (2, 5): 2,
+                (2, 6): 2,
+                (3, 4): 1,
+                (3, 5): 0,
+                (3, 6): 0,
+                (4, 5): 0,
+                (4, 6): 0,
+                (5, 6): 2,
+            }
+        )
+
+        cls.gold = gold
+
+
+class TestDAGLCA:
+    @classmethod
+    def setup_class(cls):
+        cls.DG = nx.DiGraph()
+        nx.add_path(cls.DG, (0, 1, 2, 3))
+        nx.add_path(cls.DG, (0, 4, 3))
+        nx.add_path(cls.DG, (0, 5, 6, 8, 3))
+        nx.add_path(cls.DG, (5, 7, 8))
+        cls.DG.add_edge(6, 2)
+        cls.DG.add_edge(7, 2)
+
+        cls.root_distance = nx.shortest_path_length(cls.DG, source=0)
+
+        cls.gold = {
+            (1, 1): 1,
+            (1, 2): 1,
+            (1, 3): 1,
+            (1, 4): 0,
+            (1, 5): 0,
+            (1, 6): 0,
+            (1, 7): 0,
+            (1, 8): 0,
+            (2, 2): 2,
+            (2, 3): 2,
+            (2, 4): 0,
+            (2, 5): 5,
+            (2, 6): 6,
+            (2, 7): 7,
+            (2, 8): 7,
+            (3, 3): 3,
+            (3, 4): 4,
+            (3, 5): 5,
+            (3, 6): 6,
+            (3, 7): 7,
+            (3, 8): 8,
+            (4, 4): 4,
+            (4, 5): 0,
+            (4, 6): 0,
+            (4, 7): 0,
+            (4, 8): 0,
+            (5, 5): 5,
+            (5, 6): 5,
+            (5, 7): 5,
+            (5, 8): 5,
+            (6, 6): 6,
+            (6, 7): 5,
+            (6, 8): 6,
+            (7, 7): 7,
+            (7, 8): 7,
+            (8, 8): 8,
+        }
+        cls.gold.update(((0, n), 0) for n in cls.DG)
+
+    def assert_lca_dicts_same(self, d1, d2, G=None):
+        """Checks if d1 and d2 contain the same pairs and
+        have a node at the same distance from root for each.
+        If G is None use self.DG."""
+        if G is None:
+            G = self.DG
+            root_distance = self.root_distance
+        else:
+            roots = [n for n, deg in G.in_degree if deg == 0]
+            assert len(roots) == 1
+            root_distance = nx.shortest_path_length(G, source=roots[0])
+
+        for a, b in ((min(pair), max(pair)) for pair in chain(d1, d2)):
+            assert (
+                root_distance[get_pair(d1, a, b)] == root_distance[get_pair(d2, a, b)]
+            )
+
+    def test_all_pairs_lca_gold_example(self):
+        self.assert_lca_dicts_same(dict(all_pairs_lca(self.DG)), self.gold)
+
+    def test_all_pairs_lca_all_pairs_given(self):
+        all_pairs = list(product(self.DG.nodes(), self.DG.nodes()))
+        ans = all_pairs_lca(self.DG, pairs=all_pairs)
+        self.assert_lca_dicts_same(dict(ans), self.gold)
+
+    def test_all_pairs_lca_generator(self):
+        all_pairs = product(self.DG.nodes(), self.DG.nodes())
+        ans = all_pairs_lca(self.DG, pairs=all_pairs)
+        self.assert_lca_dicts_same(dict(ans), self.gold)
+
+    def test_all_pairs_lca_input_graph_with_two_roots(self):
+        G = self.DG.copy()
+        G.add_edge(9, 10)
+        G.add_edge(9, 4)
+        gold = self.gold.copy()
+        gold[9, 9] = 9
+        gold[9, 10] = 9
+        gold[9, 4] = 9
+        gold[9, 3] = 9
+        gold[10, 4] = 9
+        gold[10, 3] = 9
+        gold[10, 10] = 10
+
+        testing = dict(all_pairs_lca(G))
+
+        G.add_edge(-1, 9)
+        G.add_edge(-1, 0)
+        self.assert_lca_dicts_same(testing, gold, G)
+
+    def test_all_pairs_lca_nonexisting_pairs_exception(self):
+        pytest.raises(nx.NodeNotFound, all_pairs_lca, self.DG, [(-1, -1)])
+
+    def test_all_pairs_lca_pairs_without_lca(self):
+        G = self.DG.copy()
+        G.add_node(-1)
+        gen = all_pairs_lca(G, [(-1, -1), (-1, 0)])
+        assert dict(gen) == {(-1, -1): -1}
+
+    def test_all_pairs_lca_null_graph(self):
+        pytest.raises(nx.NetworkXPointlessConcept, all_pairs_lca, nx.DiGraph())
+
+    def test_all_pairs_lca_non_dags(self):
+        pytest.raises(nx.NetworkXError, all_pairs_lca, nx.DiGraph([(3, 4), (4, 3)]))
+
+    def test_all_pairs_lca_nonempty_graph_without_lca(self):
+        G = nx.DiGraph()
+        G.add_node(3)
+        ans = list(all_pairs_lca(G))
+        assert ans == [((3, 3), 3)]
+
+    def test_all_pairs_lca_bug_gh4942(self):
+        G = nx.DiGraph([(0, 2), (1, 2), (2, 3)])
+        ans = list(all_pairs_lca(G))
+        assert len(ans) == 9
+
+    def test_all_pairs_lca_default_kwarg(self):
+        G = nx.DiGraph([(0, 1), (2, 1)])
+        sentinel = object()
+        assert nx.lowest_common_ancestor(G, 0, 2, default=sentinel) is sentinel
+
+    def test_all_pairs_lca_identity(self):
+        G = nx.DiGraph()
+        G.add_node(3)
+        assert nx.lowest_common_ancestor(G, 3, 3) == 3
+
+    def test_all_pairs_lca_issue_4574(self):
+        G = nx.DiGraph()
+        G.add_nodes_from(range(17))
+        G.add_edges_from(
+            [
+                (2, 0),
+                (1, 2),
+                (3, 2),
+                (5, 2),
+                (8, 2),
+                (11, 2),
+                (4, 5),
+                (6, 5),
+                (7, 8),
+                (10, 8),
+                (13, 11),
+                (14, 11),
+                (15, 11),
+                (9, 10),
+                (12, 13),
+                (16, 15),
+            ]
+        )
+
+        assert nx.lowest_common_ancestor(G, 7, 9) is None
+
+    def test_all_pairs_lca_one_pair_gh4942(self):
+        G = nx.DiGraph()
+        # Note: order edge addition is critical to the test
+        G.add_edge(0, 1)
+        G.add_edge(2, 0)
+        G.add_edge(2, 3)
+        G.add_edge(4, 0)
+        G.add_edge(5, 2)
+
+        assert nx.lowest_common_ancestor(G, 1, 3) == 2
+
+
+class TestMultiDiGraph_DAGLCA(TestDAGLCA):
+    @classmethod
+    def setup_class(cls):
+        cls.DG = nx.MultiDiGraph()
+        nx.add_path(cls.DG, (0, 1, 2, 3))
+        # add multiedges
+        nx.add_path(cls.DG, (0, 1, 2, 3))
+        nx.add_path(cls.DG, (0, 4, 3))
+        nx.add_path(cls.DG, (0, 5, 6, 8, 3))
+        nx.add_path(cls.DG, (5, 7, 8))
+        cls.DG.add_edge(6, 2)
+        cls.DG.add_edge(7, 2)
+
+        cls.root_distance = nx.shortest_path_length(cls.DG, source=0)
+
+        cls.gold = {
+            (1, 1): 1,
+            (1, 2): 1,
+            (1, 3): 1,
+            (1, 4): 0,
+            (1, 5): 0,
+            (1, 6): 0,
+            (1, 7): 0,
+            (1, 8): 0,
+            (2, 2): 2,
+            (2, 3): 2,
+            (2, 4): 0,
+            (2, 5): 5,
+            (2, 6): 6,
+            (2, 7): 7,
+            (2, 8): 7,
+            (3, 3): 3,
+            (3, 4): 4,
+            (3, 5): 5,
+            (3, 6): 6,
+            (3, 7): 7,
+            (3, 8): 8,
+            (4, 4): 4,
+            (4, 5): 0,
+            (4, 6): 0,
+            (4, 7): 0,
+            (4, 8): 0,
+            (5, 5): 5,
+            (5, 6): 5,
+            (5, 7): 5,
+            (5, 8): 5,
+            (6, 6): 6,
+            (6, 7): 5,
+            (6, 8): 6,
+            (7, 7): 7,
+            (7, 8): 7,
+            (8, 8): 8,
+        }
+        cls.gold.update(((0, n), 0) for n in cls.DG)
+
+
+def test_all_pairs_lca_self_ancestors():
+    """Self-ancestors should always be the node itself, i.e. lca of (0, 0) is 0.
+    See gh-4458."""
+    # DAG for test - note order of node/edge addition is relevant
+    G = nx.DiGraph()
+    G.add_nodes_from(range(5))
+    G.add_edges_from([(1, 0), (2, 0), (3, 2), (4, 1), (4, 3)])
+
+    ap_lca = nx.all_pairs_lowest_common_ancestor
+    assert all(u == v == a for (u, v), a in ap_lca(G) if u == v)
+    MG = nx.MultiDiGraph(G)
+    assert all(u == v == a for (u, v), a in ap_lca(MG) if u == v)
+    MG.add_edges_from([(1, 0), (2, 0)])
+    assert all(u == v == a for (u, v), a in ap_lca(MG) if u == v)
+
+
+def test_lca_on_null_graph():
+    G = nx.null_graph(create_using=nx.DiGraph)
+    with pytest.raises(
+        nx.NetworkXPointlessConcept, match="LCA meaningless on null graphs"
+    ):
+        nx.lowest_common_ancestor(G, 0, 0)
+
+
+def test_lca_on_cycle_graph():
+    G = nx.cycle_graph(6, create_using=nx.DiGraph)
+    with pytest.raises(
+        nx.NetworkXError, match="LCA only defined on directed acyclic graphs"
+    ):
+        nx.lowest_common_ancestor(G, 0, 3)
+
+
+def test_lca_multiple_valid_solutions():
+    G = nx.DiGraph()
+    G.add_nodes_from(range(4))
+    G.add_edges_from([(2, 0), (3, 0), (2, 1), (3, 1)])
+    assert nx.lowest_common_ancestor(G, 0, 1) in {2, 3}
+
+
+def test_lca_dont_rely_on_single_successor():
+    # Nodes 0 and 1 have nodes 2 and 3 as immediate ancestors,
+    # and node 2 also has node 3 as an immediate ancestor.
+    G = nx.DiGraph()
+    G.add_nodes_from(range(4))
+    G.add_edges_from([(2, 0), (2, 1), (3, 1), (3, 0), (3, 2)])
+    assert nx.lowest_common_ancestor(G, 0, 1) == 2
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_matching.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_matching.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c98900669edf2cd1edbe37471b2cb1b56ae466e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_matching.py
@@ -0,0 +1,556 @@
+import math
+from itertools import permutations
+
+import pytest
+
+import networkx as nx
+from networkx.utils import edges_equal
+
+
+@pytest.mark.parametrize(
+    "fn", (nx.is_matching, nx.is_maximal_matching, nx.is_perfect_matching)
+)
+@pytest.mark.parametrize(
+    "edgeset",
+    (
+        {(0, 5)},  # Single edge, node not in G
+        {(5, 0)},  # for both edge orders
+        {(0, 5), (2, 3)},  # node not in G, but other edge is valid matching
+        {(5, 5), (2, 3)},  # Self-loop hits node not in G validation first
+    ),
+)
+def test_is_matching_node_not_in_G(fn, edgeset):
+    """All is_*matching functions have consistent exception message for node
+    not in G."""
+    G = nx.path_graph(4)
+    with pytest.raises(nx.NetworkXError, match="matching.*with node not in G"):
+        fn(G, edgeset)
+
+
+@pytest.mark.parametrize(
+    "fn", (nx.is_matching, nx.is_maximal_matching, nx.is_perfect_matching)
+)
+@pytest.mark.parametrize(
+    "edgeset",
+    (
+        {(0, 1, 2), (2, 3)},  # 3-tuple
+        {(0,), (2, 3)},  # 1-tuple
+    ),
+)
+def test_is_matching_invalid_edge(fn, edgeset):
+    """All is_*matching functions have consistent exception message for invalid
+    edges in matching."""
+    G = nx.path_graph(4)
+    with pytest.raises(nx.NetworkXError, match=".*non-2-tuple edge.*"):
+        fn(G, edgeset)
+
+
+@pytest.mark.parametrize("graph_type", (nx.MultiGraph, nx.DiGraph, nx.MultiDiGraph))
+@pytest.mark.parametrize(
+    "fn", (nx.max_weight_matching, nx.min_weight_matching, nx.maximal_matching)
+)
+def test_wrong_graph_type(fn, graph_type):
+    G = graph_type()
+    with pytest.raises(nx.NetworkXNotImplemented):
+        fn(G)
+
+
+class TestMaxWeightMatching:
+    """Unit tests for the
+    :func:`~networkx.algorithms.matching.max_weight_matching` function.
+
+    """
+
+    def test_trivial1(self):
+        """Empty graph"""
+        G = nx.Graph()
+        assert nx.max_weight_matching(G) == set()
+        assert nx.min_weight_matching(G) == set()
+
+    def test_selfloop(self):
+        G = nx.Graph()
+        G.add_edge(0, 0, weight=100)
+        assert nx.max_weight_matching(G) == set()
+        assert nx.min_weight_matching(G) == set()
+
+    def test_single_edge(self):
+        G = nx.Graph()
+        G.add_edge(0, 1)
+        assert edges_equal(nx.max_weight_matching(G), {(0, 1)})
+        assert edges_equal(nx.min_weight_matching(G), {(0, 1)})
+
+    def test_two_path(self):
+        G = nx.Graph()
+        G.add_edge("one", "two", weight=10)
+        G.add_edge("two", "three", weight=11)
+        assert edges_equal(nx.max_weight_matching(G), {("two", "three")})
+        assert edges_equal(nx.min_weight_matching(G), {("one", "two")})
+
+    def test_path(self):
+        G = nx.Graph()
+        G.add_edge(1, 2, weight=5)
+        G.add_edge(2, 3, weight=11)
+        G.add_edge(3, 4, weight=5)
+        assert edges_equal(nx.max_weight_matching(G), {(2, 3)})
+        assert edges_equal(nx.max_weight_matching(G, weight=None), {(1, 2), (3, 4)})
+        assert edges_equal(nx.min_weight_matching(G), {(1, 2), (3, 4)})
+        assert edges_equal(nx.min_weight_matching(G, weight=None), {(1, 2), (3, 4)})
+
+    def test_square(self):
+        G = nx.Graph()
+        G.add_edge(1, 4, weight=2)
+        G.add_edge(2, 3, weight=2)
+        G.add_edge(1, 2, weight=1)
+        G.add_edge(3, 4, weight=4)
+        assert edges_equal(nx.max_weight_matching(G), {(1, 2), (3, 4)})
+        assert edges_equal(nx.min_weight_matching(G), {(1, 4), (2, 3)})
+
+    def test_edge_attribute_name(self):
+        G = nx.Graph()
+        G.add_edge("one", "two", weight=10, abcd=11)
+        G.add_edge("two", "three", weight=11, abcd=10)
+        assert edges_equal(nx.max_weight_matching(G, weight="abcd"), {("one", "two")})
+        assert edges_equal(nx.min_weight_matching(G, weight="abcd"), {("two", "three")})
+
+    def test_floating_point_weights(self):
+        G = nx.Graph()
+        G.add_edge(1, 2, weight=math.pi)
+        G.add_edge(2, 3, weight=math.exp(1))
+        G.add_edge(1, 3, weight=3.0)
+        G.add_edge(1, 4, weight=math.sqrt(2.0))
+        assert edges_equal(nx.max_weight_matching(G), {(1, 4), (2, 3)})
+        assert edges_equal(nx.min_weight_matching(G), {(1, 4), (2, 3)})
+
+    def test_negative_weights(self):
+        G = nx.Graph()
+        G.add_edge(1, 2, weight=2)
+        G.add_edge(1, 3, weight=-2)
+        G.add_edge(2, 3, weight=1)
+        G.add_edge(2, 4, weight=-1)
+        G.add_edge(3, 4, weight=-6)
+        assert edges_equal(nx.max_weight_matching(G), {(1, 2)})
+        assert edges_equal(
+            nx.max_weight_matching(G, maxcardinality=True), {(1, 3), (2, 4)}
+        )
+        assert edges_equal(nx.min_weight_matching(G), {(1, 2), (3, 4)})
+
+    def test_s_blossom(self):
+        """Create S-blossom and use it for augmentation:"""
+        G = nx.Graph()
+        G.add_weighted_edges_from([(1, 2, 8), (1, 3, 9), (2, 3, 10), (3, 4, 7)])
+        answer = {(1, 2), (3, 4)}
+        assert edges_equal(nx.max_weight_matching(G), answer)
+        assert edges_equal(nx.min_weight_matching(G), answer)
+
+        G.add_weighted_edges_from([(1, 6, 5), (4, 5, 6)])
+        answer = {(1, 6), (2, 3), (4, 5)}
+        assert edges_equal(nx.max_weight_matching(G), answer)
+        assert edges_equal(nx.min_weight_matching(G), answer)
+
+    def test_s_t_blossom(self):
+        """Create S-blossom, relabel as T-blossom, use for augmentation:"""
+        G = nx.Graph()
+        G.add_weighted_edges_from(
+            [(1, 2, 9), (1, 3, 8), (2, 3, 10), (1, 4, 5), (4, 5, 4), (1, 6, 3)]
+        )
+        answer = {(1, 6), (2, 3), (4, 5)}
+        assert edges_equal(nx.max_weight_matching(G), answer)
+        assert edges_equal(nx.min_weight_matching(G), answer)
+
+        G.add_edge(4, 5, weight=3)
+        G.add_edge(1, 6, weight=4)
+        assert edges_equal(nx.max_weight_matching(G), answer)
+        assert edges_equal(nx.min_weight_matching(G), answer)
+
+        G.remove_edge(1, 6)
+        G.add_edge(3, 6, weight=4)
+        answer = {(1, 2), (3, 6), (4, 5)}
+        assert edges_equal(nx.max_weight_matching(G), answer)
+        assert edges_equal(nx.min_weight_matching(G), answer)
+
+    def test_nested_s_blossom(self):
+        """Create nested S-blossom, use for augmentation:"""
+
+        G = nx.Graph()
+        G.add_weighted_edges_from(
+            [
+                (1, 2, 9),
+                (1, 3, 9),
+                (2, 3, 10),
+                (2, 4, 8),
+                (3, 5, 8),
+                (4, 5, 10),
+                (5, 6, 6),
+            ]
+        )
+        expected_edgeset = {(1, 3), (2, 4), (5, 6)}
+        expected = {frozenset(e) for e in expected_edgeset}
+        answer = {frozenset(e) for e in nx.max_weight_matching(G)}
+        assert answer == expected
+        answer = {frozenset(e) for e in nx.min_weight_matching(G)}
+        assert answer == expected
+
+    def test_nested_s_blossom_relabel(self):
+        """Create S-blossom, relabel as S, include in nested S-blossom:"""
+        G = nx.Graph()
+        G.add_weighted_edges_from(
+            [
+                (1, 2, 10),
+                (1, 7, 10),
+                (2, 3, 12),
+                (3, 4, 20),
+                (3, 5, 20),
+                (4, 5, 25),
+                (5, 6, 10),
+                (6, 7, 10),
+                (7, 8, 8),
+            ]
+        )
+        answer = {(1, 2), (3, 4), (5, 6), (7, 8)}
+        assert edges_equal(nx.max_weight_matching(G), answer)
+        assert edges_equal(nx.min_weight_matching(G), answer)
+
+    def test_nested_s_blossom_expand(self):
+        """Create nested S-blossom, augment, expand recursively:"""
+        G = nx.Graph()
+        G.add_weighted_edges_from(
+            [
+                (1, 2, 8),
+                (1, 3, 8),
+                (2, 3, 10),
+                (2, 4, 12),
+                (3, 5, 12),
+                (4, 5, 14),
+                (4, 6, 12),
+                (5, 7, 12),
+                (6, 7, 14),
+                (7, 8, 12),
+            ]
+        )
+        answer = {(1, 2), (3, 5), (4, 6), (7, 8)}
+        assert edges_equal(nx.max_weight_matching(G), answer)
+        assert edges_equal(nx.min_weight_matching(G), answer)
+
+    def test_s_blossom_relabel_expand(self):
+        """Create S-blossom, relabel as T, expand:"""
+        G = nx.Graph()
+        G.add_weighted_edges_from(
+            [
+                (1, 2, 23),
+                (1, 5, 22),
+                (1, 6, 15),
+                (2, 3, 25),
+                (3, 4, 22),
+                (4, 5, 25),
+                (4, 8, 14),
+                (5, 7, 13),
+            ]
+        )
+        answer = {(1, 6), (2, 3), (4, 8), (5, 7)}
+        assert edges_equal(nx.max_weight_matching(G), answer)
+        assert edges_equal(nx.min_weight_matching(G), answer)
+
+    def test_nested_s_blossom_relabel_expand(self):
+        """Create nested S-blossom, relabel as T, expand:"""
+        G = nx.Graph()
+        G.add_weighted_edges_from(
+            [
+                (1, 2, 19),
+                (1, 3, 20),
+                (1, 8, 8),
+                (2, 3, 25),
+                (2, 4, 18),
+                (3, 5, 18),
+                (4, 5, 13),
+                (4, 7, 7),
+                (5, 6, 7),
+            ]
+        )
+        answer = {(1, 8), (2, 3), (4, 7), (5, 6)}
+        assert edges_equal(nx.max_weight_matching(G), answer)
+        assert edges_equal(nx.min_weight_matching(G), answer)
+
+    def test_nasty_blossom1(self):
+        """Create blossom, relabel as T in more than one way, expand,
+        augment:
+        """
+        G = nx.Graph()
+        G.add_weighted_edges_from(
+            [
+                (1, 2, 45),
+                (1, 5, 45),
+                (2, 3, 50),
+                (3, 4, 45),
+                (4, 5, 50),
+                (1, 6, 30),
+                (3, 9, 35),
+                (4, 8, 35),
+                (5, 7, 26),
+                (9, 10, 5),
+            ]
+        )
+        answer = {(1, 6), (2, 3), (4, 8), (5, 7), (9, 10)}
+        assert edges_equal(nx.max_weight_matching(G), answer)
+        assert edges_equal(nx.min_weight_matching(G), answer)
+
+    def test_nasty_blossom2(self):
+        """Again but slightly different:"""
+        G = nx.Graph()
+        G.add_weighted_edges_from(
+            [
+                (1, 2, 45),
+                (1, 5, 45),
+                (2, 3, 50),
+                (3, 4, 45),
+                (4, 5, 50),
+                (1, 6, 30),
+                (3, 9, 35),
+                (4, 8, 26),
+                (5, 7, 40),
+                (9, 10, 5),
+            ]
+        )
+        answer = {(1, 6), (2, 3), (4, 8), (5, 7), (9, 10)}
+        assert edges_equal(nx.max_weight_matching(G), answer)
+        assert edges_equal(nx.min_weight_matching(G), answer)
+
+    def test_nasty_blossom_least_slack(self):
+        """Create blossom, relabel as T, expand such that a new
+        least-slack S-to-free dge is produced, augment:
+        """
+        G = nx.Graph()
+        G.add_weighted_edges_from(
+            [
+                (1, 2, 45),
+                (1, 5, 45),
+                (2, 3, 50),
+                (3, 4, 45),
+                (4, 5, 50),
+                (1, 6, 30),
+                (3, 9, 35),
+                (4, 8, 28),
+                (5, 7, 26),
+                (9, 10, 5),
+            ]
+        )
+        answer = {(1, 6), (2, 3), (4, 8), (5, 7), (9, 10)}
+        assert edges_equal(nx.max_weight_matching(G), answer)
+        assert edges_equal(nx.min_weight_matching(G), answer)
+
+    def test_nasty_blossom_augmenting(self):
+        """Create nested blossom, relabel as T in more than one way"""
+        # expand outer blossom such that inner blossom ends up on an
+        # augmenting path:
+        G = nx.Graph()
+        G.add_weighted_edges_from(
+            [
+                (1, 2, 45),
+                (1, 7, 45),
+                (2, 3, 50),
+                (3, 4, 45),
+                (4, 5, 95),
+                (4, 6, 94),
+                (5, 6, 94),
+                (6, 7, 50),
+                (1, 8, 30),
+                (3, 11, 35),
+                (5, 9, 36),
+                (7, 10, 26),
+                (11, 12, 5),
+            ]
+        )
+        answer = {(1, 8), (2, 3), (4, 6), (5, 9), (7, 10), (11, 12)}
+        assert edges_equal(nx.max_weight_matching(G), answer)
+        assert edges_equal(nx.min_weight_matching(G), answer)
+
+    def test_nasty_blossom_expand_recursively(self):
+        """Create nested S-blossom, relabel as S, expand recursively:"""
+        G = nx.Graph()
+        G.add_weighted_edges_from(
+            [
+                (1, 2, 40),
+                (1, 3, 40),
+                (2, 3, 60),
+                (2, 4, 55),
+                (3, 5, 55),
+                (4, 5, 50),
+                (1, 8, 15),
+                (5, 7, 30),
+                (7, 6, 10),
+                (8, 10, 10),
+                (4, 9, 30),
+            ]
+        )
+        answer = {(1, 2), (3, 5), (4, 9), (6, 7), (8, 10)}
+        assert edges_equal(nx.max_weight_matching(G), answer)
+        assert edges_equal(nx.min_weight_matching(G), answer)
+
+    def test_min_weight_matching_max_cardinality(self):
+        G = nx.Graph()
+        G.add_weighted_edges_from([(1, 2, 1000), (2, 3, 2), (3, 4, 3000)])
+        # The minimum-weight maximal matching is {(2, 3)}; the minimum-weight
+        # maximum-cardinality matching is {(1, 2), (3, 4)}. See gh-8062.
+        answer = {(1, 2), (3, 4)}
+        assert edges_equal(nx.min_weight_matching(G), answer)
+
+
+class TestIsMatching:
+    """Unit tests for the
+    :func:`~networkx.algorithms.matching.is_matching` function.
+
+    """
+
+    def test_dict(self):
+        G = nx.path_graph(4)
+        assert nx.is_matching(G, {0: 1, 1: 0, 2: 3, 3: 2})
+
+    def test_empty_matching(self):
+        G = nx.path_graph(4)
+        assert nx.is_matching(G, set())
+
+    def test_single_edge(self):
+        G = nx.path_graph(4)
+        assert nx.is_matching(G, {(1, 2)})
+
+    def test_edge_order(self):
+        G = nx.path_graph(4)
+        assert nx.is_matching(G, {(0, 1), (2, 3)})
+        assert nx.is_matching(G, {(1, 0), (2, 3)})
+        assert nx.is_matching(G, {(0, 1), (3, 2)})
+        assert nx.is_matching(G, {(1, 0), (3, 2)})
+
+    def test_valid_matching(self):
+        G = nx.path_graph(4)
+        assert nx.is_matching(G, {(0, 1), (2, 3)})
+
+    def test_selfloops(self):
+        G = nx.path_graph(4)
+        # selfloop edge not in G
+        assert not nx.is_matching(G, {(0, 0), (1, 2), (2, 3)})
+        # selfloop edge in G
+        G.add_edge(0, 0)
+        assert not nx.is_matching(G, {(0, 0), (1, 2)})
+
+    def test_invalid_matching(self):
+        G = nx.path_graph(4)
+        assert not nx.is_matching(G, {(0, 1), (1, 2), (2, 3)})
+
+    def test_invalid_edge(self):
+        G = nx.path_graph(4)
+        assert not nx.is_matching(G, {(0, 3), (1, 2)})
+
+        G = nx.DiGraph(G.edges)
+        assert nx.is_matching(G, {(0, 1)})
+        assert not nx.is_matching(G, {(1, 0)})
+
+
+class TestIsMaximalMatching:
+    """Unit tests for the
+    :func:`~networkx.algorithms.matching.is_maximal_matching` function.
+
+    """
+
+    def test_dict(self):
+        G = nx.path_graph(4)
+        assert nx.is_maximal_matching(G, {0: 1, 1: 0, 2: 3, 3: 2})
+
+    def test_valid(self):
+        G = nx.path_graph(4)
+        assert nx.is_maximal_matching(G, {(0, 1), (2, 3)})
+
+    def test_not_matching(self):
+        G = nx.path_graph(4)
+        assert not nx.is_maximal_matching(G, {(0, 1), (1, 2), (2, 3)})
+        assert not nx.is_maximal_matching(G, {(0, 3)})
+        G.add_edge(0, 0)
+        assert not nx.is_maximal_matching(G, {(0, 0)})
+
+    def test_not_maximal(self):
+        G = nx.path_graph(4)
+        assert not nx.is_maximal_matching(G, {(0, 1)})
+
+
+class TestIsPerfectMatching:
+    """Unit tests for the
+    :func:`~networkx.algorithms.matching.is_perfect_matching` function.
+
+    """
+
+    def test_dict(self):
+        G = nx.path_graph(4)
+        assert nx.is_perfect_matching(G, {0: 1, 1: 0, 2: 3, 3: 2})
+
+    def test_valid(self):
+        G = nx.path_graph(4)
+        assert nx.is_perfect_matching(G, {(0, 1), (2, 3)})
+
+    def test_valid_not_path(self):
+        G = nx.cycle_graph(4)
+        G.add_edge(0, 4)
+        G.add_edge(1, 4)
+        G.add_edge(5, 2)
+
+        assert nx.is_perfect_matching(G, {(1, 4), (0, 3), (5, 2)})
+
+    def test_selfloops(self):
+        G = nx.path_graph(4)
+        # selfloop edge not in G
+        assert not nx.is_perfect_matching(G, {(0, 0), (1, 2), (2, 3)})
+        # selfloop edge in G
+        G.add_edge(0, 0)
+        assert not nx.is_perfect_matching(G, {(0, 0), (1, 2)})
+
+    def test_not_matching(self):
+        G = nx.path_graph(4)
+        assert not nx.is_perfect_matching(G, {(0, 3)})
+        assert not nx.is_perfect_matching(G, {(0, 1), (1, 2), (2, 3)})
+
+    def test_maximal_but_not_perfect(self):
+        G = nx.cycle_graph(4)
+        G.add_edge(0, 4)
+        G.add_edge(1, 4)
+
+        assert not nx.is_perfect_matching(G, {(1, 4), (0, 3)})
+
+
+class TestMaximalMatching:
+    """Unit tests for the
+    :func:`~networkx.algorithms.matching.maximal_matching`.
+
+    """
+
+    def test_valid_matching(self):
+        edges = [(1, 2), (1, 5), (2, 3), (2, 5), (3, 4), (3, 6), (5, 6)]
+        G = nx.Graph(edges)
+        matching = nx.maximal_matching(G)
+        assert nx.is_maximal_matching(G, matching)
+
+    def test_single_edge_matching(self):
+        # In the star graph, any maximal matching has just one edge.
+        G = nx.star_graph(5)
+        matching = nx.maximal_matching(G)
+        assert 1 == len(matching)
+        assert nx.is_maximal_matching(G, matching)
+
+    def test_self_loops(self):
+        # Create the path graph with two self-loops.
+        G = nx.path_graph(3)
+        G.add_edges_from([(0, 0), (1, 1)])
+        matching = nx.maximal_matching(G)
+        assert len(matching) == 1
+        # The matching should never include self-loops.
+        assert not any(u == v for u, v in matching)
+        assert nx.is_maximal_matching(G, matching)
+
+    def test_ordering(self):
+        """Tests that a maximal matching is computed correctly
+        regardless of the order in which nodes are added to the graph.
+
+        """
+        for nodes in permutations(range(3)):
+            G = nx.Graph()
+            G.add_nodes_from(nodes)
+            G.add_edges_from([(0, 1), (0, 2)])
+            matching = nx.maximal_matching(G)
+            assert len(matching) == 1
+            assert nx.is_maximal_matching(G, matching)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_max_weight_clique.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_max_weight_clique.py
new file mode 100644
index 0000000000000000000000000000000000000000..6cd8584ebd5c2ab04741234018a976472a92ef91
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_max_weight_clique.py
@@ -0,0 +1,179 @@
+"""Maximum weight clique test suite."""
+
+import pytest
+
+import networkx as nx
+
+
+class TestMaximumWeightClique:
+    def test_basic_cases(self):
+        def check_basic_case(graph_func, expected_weight, weight_accessor):
+            graph = graph_func()
+            clique, weight = nx.algorithms.max_weight_clique(graph, weight_accessor)
+            assert verify_clique(
+                graph, clique, weight, expected_weight, weight_accessor
+            )
+
+        for graph_func, (expected_weight, expected_size) in TEST_CASES.items():
+            check_basic_case(graph_func, expected_weight, "weight")
+            check_basic_case(graph_func, expected_size, None)
+
+    def test_key_error(self):
+        graph = two_node_graph()
+        with pytest.raises(KeyError):
+            nx.algorithms.max_weight_clique(graph, "nonexistent-key")
+
+    def test_error_on_non_integer_weight(self):
+        graph = two_node_graph()
+        graph.nodes[2]["weight"] = 1.5
+        with pytest.raises(ValueError):
+            nx.algorithms.max_weight_clique(graph)
+
+    def test_unaffected_by_self_loops(self):
+        graph = two_node_graph()
+        graph.add_edge(1, 1)
+        graph.add_edge(2, 2)
+        clique, weight = nx.algorithms.max_weight_clique(graph, "weight")
+        assert verify_clique(graph, clique, weight, 30, "weight")
+        graph = three_node_independent_set()
+        graph.add_edge(1, 1)
+        clique, weight = nx.algorithms.max_weight_clique(graph, "weight")
+        assert verify_clique(graph, clique, weight, 20, "weight")
+
+    def test_30_node_prob(self):
+        G = nx.Graph()
+        G.add_nodes_from(range(1, 31))
+        for i in range(1, 31):
+            G.nodes[i]["weight"] = i + 1
+        # fmt: off
+        G.add_edges_from(
+            [
+                (1, 12), (1, 13), (1, 15), (1, 16), (1, 18), (1, 19), (1, 20),
+                (1, 23), (1, 26), (1, 28), (1, 29), (1, 30), (2, 3), (2, 4),
+                (2, 5), (2, 8), (2, 9), (2, 10), (2, 14), (2, 17), (2, 18),
+                (2, 21), (2, 22), (2, 23), (2, 27), (3, 9), (3, 15), (3, 21),
+                (3, 22), (3, 23), (3, 24), (3, 27), (3, 28), (3, 29), (4, 5),
+                (4, 6), (4, 8), (4, 21), (4, 22), (4, 23), (4, 26), (4, 28),
+                (4, 30), (5, 6), (5, 8), (5, 9), (5, 13), (5, 14), (5, 15),
+                (5, 16), (5, 20), (5, 21), (5, 22), (5, 25), (5, 28), (5, 29),
+                (6, 7), (6, 8), (6, 13), (6, 17), (6, 18), (6, 19), (6, 24),
+                (6, 26), (6, 27), (6, 28), (6, 29), (7, 12), (7, 14), (7, 15),
+                (7, 16), (7, 17), (7, 20), (7, 25), (7, 27), (7, 29), (7, 30),
+                (8, 10), (8, 15), (8, 16), (8, 18), (8, 20), (8, 22), (8, 24),
+                (8, 26), (8, 27), (8, 28), (8, 30), (9, 11), (9, 12), (9, 13),
+                (9, 14), (9, 15), (9, 16), (9, 19), (9, 20), (9, 21), (9, 24),
+                (9, 30), (10, 12), (10, 15), (10, 18), (10, 19), (10, 20),
+                (10, 22), (10, 23), (10, 24), (10, 26), (10, 27), (10, 29),
+                (10, 30), (11, 13), (11, 15), (11, 16), (11, 17), (11, 18),
+                (11, 19), (11, 20), (11, 22), (11, 29), (11, 30), (12, 14),
+                (12, 17), (12, 18), (12, 19), (12, 20), (12, 21), (12, 23),
+                (12, 25), (12, 26), (12, 30), (13, 20), (13, 22), (13, 23),
+                (13, 24), (13, 30), (14, 16), (14, 20), (14, 21), (14, 22),
+                (14, 23), (14, 25), (14, 26), (14, 27), (14, 29), (14, 30),
+                (15, 17), (15, 18), (15, 20), (15, 21), (15, 26), (15, 27),
+                (15, 28), (16, 17), (16, 18), (16, 19), (16, 20), (16, 21),
+                (16, 29), (16, 30), (17, 18), (17, 21), (17, 22), (17, 25),
+                (17, 27), (17, 28), (17, 30), (18, 19), (18, 20), (18, 21),
+                (18, 22), (18, 23), (18, 24), (19, 20), (19, 22), (19, 23),
+                (19, 24), (19, 25), (19, 27), (19, 30), (20, 21), (20, 23),
+                (20, 24), (20, 26), (20, 28), (20, 29), (21, 23), (21, 26),
+                (21, 27), (21, 29), (22, 24), (22, 25), (22, 26), (22, 29),
+                (23, 25), (23, 30), (24, 25), (24, 26), (25, 27), (25, 29),
+                (26, 27), (26, 28), (26, 30), (28, 29), (29, 30),
+            ]
+        )
+        # fmt: on
+        clique, weight = nx.algorithms.max_weight_clique(G)
+        assert verify_clique(G, clique, weight, 111, "weight")
+
+
+#  ############################  Utility functions ############################
+def verify_clique(
+    graph, clique, reported_clique_weight, expected_clique_weight, weight_accessor
+):
+    for node1 in clique:
+        for node2 in clique:
+            if node1 == node2:
+                continue
+            if not graph.has_edge(node1, node2):
+                return False
+
+    if weight_accessor is None:
+        clique_weight = len(clique)
+    else:
+        clique_weight = sum(graph.nodes[v]["weight"] for v in clique)
+
+    if clique_weight != expected_clique_weight:
+        return False
+    if clique_weight != reported_clique_weight:
+        return False
+
+    return True
+
+
+#  ############################  Graph Generation ############################
+
+
+def empty_graph():
+    return nx.Graph()
+
+
+def one_node_graph():
+    graph = nx.Graph()
+    graph.add_nodes_from([1])
+    graph.nodes[1]["weight"] = 10
+    return graph
+
+
+def two_node_graph():
+    graph = nx.Graph()
+    graph.add_nodes_from([1, 2])
+    graph.add_edges_from([(1, 2)])
+    graph.nodes[1]["weight"] = 10
+    graph.nodes[2]["weight"] = 20
+    return graph
+
+
+def three_node_clique():
+    graph = nx.Graph()
+    graph.add_nodes_from([1, 2, 3])
+    graph.add_edges_from([(1, 2), (1, 3), (2, 3)])
+    graph.nodes[1]["weight"] = 10
+    graph.nodes[2]["weight"] = 20
+    graph.nodes[3]["weight"] = 5
+    return graph
+
+
+def three_node_independent_set():
+    graph = nx.Graph()
+    graph.add_nodes_from([1, 2, 3])
+    graph.nodes[1]["weight"] = 10
+    graph.nodes[2]["weight"] = 20
+    graph.nodes[3]["weight"] = 5
+    return graph
+
+
+def disconnected():
+    graph = nx.Graph()
+    graph.add_edges_from([(1, 2), (2, 3), (4, 5), (5, 6)])
+    graph.nodes[1]["weight"] = 10
+    graph.nodes[2]["weight"] = 20
+    graph.nodes[3]["weight"] = 5
+    graph.nodes[4]["weight"] = 100
+    graph.nodes[5]["weight"] = 200
+    graph.nodes[6]["weight"] = 50
+    return graph
+
+
+# --------------------------------------------------------------------------
+# Basic tests for all strategies
+# For each basic graph function, specify expected weight of max weight clique
+# and expected size of maximum clique
+TEST_CASES = {
+    empty_graph: (0, 0),
+    one_node_graph: (10, 1),
+    two_node_graph: (30, 2),
+    three_node_clique: (35, 3),
+    three_node_independent_set: (20, 1),
+    disconnected: (300, 2),
+}
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_mis.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_mis.py
new file mode 100644
index 0000000000000000000000000000000000000000..02be02d4c33f233d27d2838e5e3d361c4212c40b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_mis.py
@@ -0,0 +1,62 @@
+"""
+Tests for maximal (not maximum) independent sets.
+
+"""
+
+import random
+
+import pytest
+
+import networkx as nx
+
+
+def test_random_seed():
+    G = nx.empty_graph(5)
+    assert nx.maximal_independent_set(G, seed=1) == [1, 0, 3, 2, 4]
+
+
+@pytest.mark.parametrize("graph", [nx.complete_graph(5), nx.complete_graph(55)])
+def test_K5(graph):
+    """Maximal independent set for complete graphs"""
+    assert all(nx.maximal_independent_set(graph, [n]) == [n] for n in graph)
+
+
+def test_exceptions():
+    """Bad input should raise exception."""
+    G = nx.florentine_families_graph()
+    pytest.raises(nx.NetworkXUnfeasible, nx.maximal_independent_set, G, ["Smith"])
+    pytest.raises(
+        nx.NetworkXUnfeasible, nx.maximal_independent_set, G, ["Salviati", "Pazzi"]
+    )
+    # MaximalIndependentSet is not implemented for directed graphs
+    pytest.raises(nx.NetworkXNotImplemented, nx.maximal_independent_set, nx.DiGraph(G))
+
+
+def test_florentine_family():
+    G = nx.florentine_families_graph()
+    indep = nx.maximal_independent_set(G, ["Medici", "Bischeri"])
+    assert set(indep) == {
+        "Medici",
+        "Bischeri",
+        "Castellani",
+        "Pazzi",
+        "Ginori",
+        "Lamberteschi",
+    }
+
+
+def test_bipartite():
+    G = nx.complete_bipartite_graph(12, 34)
+    indep = nx.maximal_independent_set(G, [4, 5, 9, 10])
+    assert sorted(indep) == list(range(12))
+
+
+def test_random_graphs():
+    """Generate 5 random graphs of different types and sizes and
+    make sure that all sets are independent and maximal."""
+    for i in range(0, 50, 10):
+        G = nx.erdos_renyi_graph(i * 10 + 1, random.random())
+        IS = nx.maximal_independent_set(G)
+        assert G.subgraph(IS).number_of_edges() == 0
+        nbrs_of_MIS = set.union(*(set(G.neighbors(v)) for v in IS))
+        assert all(v in nbrs_of_MIS for v in set(G.nodes()).difference(IS))
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_moral.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_moral.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc98c9729a95897857013ae22333e3b8c17202fb
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_moral.py
@@ -0,0 +1,15 @@
+import networkx as nx
+from networkx.algorithms.moral import moral_graph
+
+
+def test_get_moral_graph():
+    graph = nx.DiGraph()
+    graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
+    graph.add_edges_from([(1, 2), (3, 2), (4, 1), (4, 5), (6, 5), (7, 5)])
+    H = moral_graph(graph)
+    assert not H.is_directed()
+    assert H.has_edge(1, 3)
+    assert H.has_edge(4, 6)
+    assert H.has_edge(6, 7)
+    assert H.has_edge(4, 7)
+    assert not H.has_edge(1, 5)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_node_classification.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_node_classification.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e1fc79d48ae830625c3528f52e805d2e0d183ad
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_node_classification.py
@@ -0,0 +1,140 @@
+import pytest
+
+pytest.importorskip("numpy")
+pytest.importorskip("scipy")
+
+import networkx as nx
+from networkx.algorithms import node_classification
+
+
+class TestHarmonicFunction:
+    def test_path_graph(self):
+        G = nx.path_graph(4)
+        label_name = "label"
+        G.nodes[0][label_name] = "A"
+        G.nodes[3][label_name] = "B"
+        predicted = node_classification.harmonic_function(G, label_name=label_name)
+        assert predicted[0] == "A"
+        assert predicted[1] == "A"
+        assert predicted[2] == "B"
+        assert predicted[3] == "B"
+
+    def test_no_labels(self):
+        with pytest.raises(nx.NetworkXError):
+            G = nx.path_graph(4)
+            node_classification.harmonic_function(G)
+
+    def test_no_nodes(self):
+        with pytest.raises(nx.NetworkXError):
+            G = nx.Graph()
+            node_classification.harmonic_function(G)
+
+    def test_no_edges(self):
+        with pytest.raises(nx.NetworkXError):
+            G = nx.Graph()
+            G.add_node(1)
+            G.add_node(2)
+            node_classification.harmonic_function(G)
+
+    def test_digraph(self):
+        with pytest.raises(nx.NetworkXNotImplemented):
+            G = nx.DiGraph()
+            G.add_edge(0, 1)
+            G.add_edge(1, 2)
+            G.add_edge(2, 3)
+            label_name = "label"
+            G.nodes[0][label_name] = "A"
+            G.nodes[3][label_name] = "B"
+            node_classification.harmonic_function(G)
+
+    def test_one_labeled_node(self):
+        G = nx.path_graph(4)
+        label_name = "label"
+        G.nodes[0][label_name] = "A"
+        predicted = node_classification.harmonic_function(G, label_name=label_name)
+        assert predicted[0] == "A"
+        assert predicted[1] == "A"
+        assert predicted[2] == "A"
+        assert predicted[3] == "A"
+
+    def test_nodes_all_labeled(self):
+        G = nx.karate_club_graph()
+        label_name = "club"
+        predicted = node_classification.harmonic_function(G, label_name=label_name)
+        for i in range(len(G)):
+            assert predicted[i] == G.nodes[i][label_name]
+
+    def test_labeled_nodes_are_not_changed(self):
+        G = nx.karate_club_graph()
+        label_name = "club"
+        label_removed = {0, 1, 2, 3, 4, 5, 6, 7}
+        for i in label_removed:
+            del G.nodes[i][label_name]
+        predicted = node_classification.harmonic_function(G, label_name=label_name)
+        label_not_removed = set(range(len(G))) - label_removed
+        for i in label_not_removed:
+            assert predicted[i] == G.nodes[i][label_name]
+
+
+class TestLocalAndGlobalConsistency:
+    def test_path_graph(self):
+        G = nx.path_graph(4)
+        label_name = "label"
+        G.nodes[0][label_name] = "A"
+        G.nodes[3][label_name] = "B"
+        predicted = node_classification.local_and_global_consistency(
+            G, label_name=label_name
+        )
+        assert predicted[0] == "A"
+        assert predicted[1] == "A"
+        assert predicted[2] == "B"
+        assert predicted[3] == "B"
+
+    def test_no_labels(self):
+        with pytest.raises(nx.NetworkXError):
+            G = nx.path_graph(4)
+            node_classification.local_and_global_consistency(G)
+
+    def test_no_nodes(self):
+        with pytest.raises(nx.NetworkXError):
+            G = nx.Graph()
+            node_classification.local_and_global_consistency(G)
+
+    def test_no_edges(self):
+        with pytest.raises(nx.NetworkXError):
+            G = nx.Graph()
+            G.add_node(1)
+            G.add_node(2)
+            node_classification.local_and_global_consistency(G)
+
+    def test_digraph(self):
+        with pytest.raises(nx.NetworkXNotImplemented):
+            G = nx.DiGraph()
+            G.add_edge(0, 1)
+            G.add_edge(1, 2)
+            G.add_edge(2, 3)
+            label_name = "label"
+            G.nodes[0][label_name] = "A"
+            G.nodes[3][label_name] = "B"
+            node_classification.harmonic_function(G)
+
+    def test_one_labeled_node(self):
+        G = nx.path_graph(4)
+        label_name = "label"
+        G.nodes[0][label_name] = "A"
+        predicted = node_classification.local_and_global_consistency(
+            G, label_name=label_name
+        )
+        assert predicted[0] == "A"
+        assert predicted[1] == "A"
+        assert predicted[2] == "A"
+        assert predicted[3] == "A"
+
+    def test_nodes_all_labeled(self):
+        G = nx.karate_club_graph()
+        label_name = "club"
+        predicted = node_classification.local_and_global_consistency(
+            G, alpha=0, label_name=label_name
+        )
+        for i in range(len(G)):
+            assert predicted[i] == G.nodes[i][label_name]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_non_randomness.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_non_randomness.py
new file mode 100644
index 0000000000000000000000000000000000000000..bdbcdaf15445f17fb22a7e3ec737a9f1a774b51c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_non_randomness.py
@@ -0,0 +1,60 @@
+import pytest
+
+import networkx as nx
+
+np = pytest.importorskip("numpy")
+
+
+@pytest.mark.parametrize(
+    "k, weight, expected",
+    [
+        (None, None, 7.21),  # infers 3 communities
+        (2, None, 11.7),
+        (None, "weight", 25.45),
+        (2, "weight", 38.8),
+    ],
+)
+def test_non_randomness(k, weight, expected):
+    G = nx.karate_club_graph()
+    np.testing.assert_almost_equal(
+        nx.non_randomness(G, k, weight)[0], expected, decimal=2
+    )
+
+
+def test_non_connected():
+    G = nx.Graph([(1, 2)])
+    G.add_node(3)
+    with pytest.raises(nx.NetworkXException, match="Non connected"):
+        nx.non_randomness(G)
+
+
+def test_self_loops():
+    G = nx.Graph()
+    G.add_edge(1, 2)
+    G.add_edge(1, 1)
+    with pytest.raises(nx.NetworkXError, match="Graph must not contain self-loops"):
+        nx.non_randomness(G)
+
+
+def test_empty_graph():
+    G = nx.empty_graph(1)
+    with pytest.raises(nx.NetworkXError, match=".*not applicable to empty graphs"):
+        nx.non_randomness(G)
+
+
+@pytest.mark.parametrize("k", [-1, 0, 2, 5])
+def test_value_error(k):
+    """
+    Check that invalid values of k raise (must be between 1 and n - 1, inclusive,
+    and such that the probability is between 0 and 1, exclusive).
+    """
+    G = nx.path_graph(5)
+    with pytest.raises(ValueError, match=r"invalid number of communities"):
+        nx.non_randomness(G, k=k)
+
+
+@pytest.mark.parametrize("G", [nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()])
+def test_not_implemented(G):
+    """Check that non-randomness is not implemented for directed or multigraphs."""
+    with pytest.raises(nx.NetworkXNotImplemented, match=r"not implemented for"):
+        nx.non_randomness(G)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_perfect_graph.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_perfect_graph.py
new file mode 100644
index 0000000000000000000000000000000000000000..51c12589fb713176d1a06b272c63e095d04ad2af
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_perfect_graph.py
@@ -0,0 +1,27 @@
+import networkx as nx
+
+
+def test_chordal_graph():
+    G = nx.complete_graph(5)
+    assert nx.is_perfect_graph(G)
+
+
+def test_odd_cycle():
+    G = nx.cycle_graph(5)  # Induced odd cycle
+    assert not nx.is_perfect_graph(G)
+
+
+def test_even_cycle():
+    G = nx.cycle_graph(6)  # Even cycle is perfect
+    assert nx.is_perfect_graph(G)
+
+
+def test_complement_of_odd_cycle():
+    G = nx.cycle_graph(7)
+    GC = nx.complement(G)
+    assert not nx.is_perfect_graph(GC)
+
+
+def test_disconnected_union_of_cliques():
+    G = nx.disjoint_union(nx.complete_graph(3), nx.complete_graph(4))
+    assert nx.is_perfect_graph(G)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_planar_drawing.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_planar_drawing.py
new file mode 100644
index 0000000000000000000000000000000000000000..b59d5c17331d6aac71e688b3dfde46991ea2ef97
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_planar_drawing.py
@@ -0,0 +1,274 @@
+import math
+
+import pytest
+
+import networkx as nx
+from networkx.algorithms.planar_drawing import triangulate_embedding
+
+
+def test_graph1():
+    embedding_data = {0: [1, 2, 3], 1: [2, 0], 2: [3, 0, 1], 3: [2, 0]}
+    check_embedding_data(embedding_data)
+
+
+def test_graph2():
+    embedding_data = {
+        0: [8, 6],
+        1: [2, 6, 9],
+        2: [8, 1, 7, 9, 6, 4],
+        3: [9],
+        4: [2],
+        5: [6, 8],
+        6: [9, 1, 0, 5, 2],
+        7: [9, 2],
+        8: [0, 2, 5],
+        9: [1, 6, 2, 7, 3],
+    }
+    check_embedding_data(embedding_data)
+
+
+def test_circle_graph():
+    embedding_data = {
+        0: [1, 9],
+        1: [0, 2],
+        2: [1, 3],
+        3: [2, 4],
+        4: [3, 5],
+        5: [4, 6],
+        6: [5, 7],
+        7: [6, 8],
+        8: [7, 9],
+        9: [8, 0],
+    }
+    check_embedding_data(embedding_data)
+
+
+def test_grid_graph():
+    embedding_data = {
+        (0, 1): [(0, 0), (1, 1), (0, 2)],
+        (1, 2): [(1, 1), (2, 2), (0, 2)],
+        (0, 0): [(0, 1), (1, 0)],
+        (2, 1): [(2, 0), (2, 2), (1, 1)],
+        (1, 1): [(2, 1), (1, 2), (0, 1), (1, 0)],
+        (2, 0): [(1, 0), (2, 1)],
+        (2, 2): [(1, 2), (2, 1)],
+        (1, 0): [(0, 0), (2, 0), (1, 1)],
+        (0, 2): [(1, 2), (0, 1)],
+    }
+    check_embedding_data(embedding_data)
+
+
+def test_one_node_graph():
+    embedding_data = {0: []}
+    check_embedding_data(embedding_data)
+
+
+def test_two_node_graph():
+    embedding_data = {0: [1], 1: [0]}
+    check_embedding_data(embedding_data)
+
+
+def test_three_node_graph():
+    embedding_data = {0: [1, 2], 1: [0, 2], 2: [0, 1]}
+    check_embedding_data(embedding_data)
+
+
+def test_multiple_component_graph1():
+    embedding_data = {0: [], 1: []}
+    check_embedding_data(embedding_data)
+
+
+def test_multiple_component_graph2():
+    embedding_data = {0: [1, 2], 1: [0, 2], 2: [0, 1], 3: [4, 5], 4: [3, 5], 5: [3, 4]}
+    check_embedding_data(embedding_data)
+
+
+def test_invalid_half_edge():
+    with pytest.raises(nx.NetworkXException):
+        embedding_data = {1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2, 4], 4: [1, 2, 3]}
+        embedding = nx.PlanarEmbedding()
+        embedding.set_data(embedding_data)
+        nx.combinatorial_embedding_to_pos(embedding)
+
+
+def test_triangulate_embedding1():
+    embedding = nx.PlanarEmbedding()
+    embedding.add_node(1)
+    expected_embedding = {1: []}
+    check_triangulation(embedding, expected_embedding)
+
+
+def test_triangulate_embedding2():
+    embedding = nx.PlanarEmbedding()
+    embedding.connect_components(1, 2)
+    expected_embedding = {1: [2], 2: [1]}
+    check_triangulation(embedding, expected_embedding)
+
+
+def check_triangulation(embedding, expected_embedding):
+    res_embedding, _ = triangulate_embedding(embedding, True)
+    assert res_embedding.get_data() == expected_embedding, (
+        "Expected embedding incorrect"
+    )
+    res_embedding, _ = triangulate_embedding(embedding, False)
+    assert res_embedding.get_data() == expected_embedding, (
+        "Expected embedding incorrect"
+    )
+
+
+def check_embedding_data(embedding_data):
+    """Checks that the planar embedding of the input is correct"""
+    embedding = nx.PlanarEmbedding()
+    embedding.set_data(embedding_data)
+    pos_fully = nx.combinatorial_embedding_to_pos(embedding, False)
+    msg = "Planar drawing does not conform to the embedding (fully triangulation)"
+    assert planar_drawing_conforms_to_embedding(embedding, pos_fully), msg
+    check_edge_intersections(embedding, pos_fully)
+    pos_internally = nx.combinatorial_embedding_to_pos(embedding, True)
+    msg = "Planar drawing does not conform to the embedding (internal triangulation)"
+    assert planar_drawing_conforms_to_embedding(embedding, pos_internally), msg
+    check_edge_intersections(embedding, pos_internally)
+
+
+def is_close(a, b, rel_tol=1e-09, abs_tol=0.0):
+    # Check if float numbers are basically equal, for python >=3.5 there is
+    # function for that in the standard library
+    return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
+
+
+def point_in_between(a, b, p):
+    # checks if p is on the line between a and b
+    x1, y1 = a
+    x2, y2 = b
+    px, py = p
+    dist_1_2 = math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
+    dist_1_p = math.sqrt((x1 - px) ** 2 + (y1 - py) ** 2)
+    dist_2_p = math.sqrt((x2 - px) ** 2 + (y2 - py) ** 2)
+    return is_close(dist_1_p + dist_2_p, dist_1_2)
+
+
+def check_edge_intersections(G, pos):
+    """Check all edges in G for intersections.
+
+    Raises an exception if an intersection is found.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+    pos : dict
+        Maps every node to a tuple (x, y) representing its position
+
+    """
+    for a, b in G.edges():
+        for c, d in G.edges():
+            # Check if end points are different
+            if a != c and b != d and b != c and a != d:
+                x1, y1 = pos[a]
+                x2, y2 = pos[b]
+                x3, y3 = pos[c]
+                x4, y4 = pos[d]
+                determinant = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
+                if determinant != 0:  # the lines are not parallel
+                    # calculate intersection point, see:
+                    # https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection
+                    px = (x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (
+                        x3 * y4 - y3 * x4
+                    ) / determinant
+                    py = (x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (
+                        x3 * y4 - y3 * x4
+                    ) / determinant
+
+                    # Check if intersection lies between the points
+                    if point_in_between(pos[a], pos[b], (px, py)) and point_in_between(
+                        pos[c], pos[d], (px, py)
+                    ):
+                        msg = f"There is an intersection at {px},{py}"
+                        raise nx.NetworkXException(msg)
+
+                #  Check overlap
+                msg = "A node lies on a edge connecting two other nodes"
+                if (
+                    point_in_between(pos[a], pos[b], pos[c])
+                    or point_in_between(pos[a], pos[b], pos[d])
+                    or point_in_between(pos[c], pos[d], pos[a])
+                    or point_in_between(pos[c], pos[d], pos[b])
+                ):
+                    raise nx.NetworkXException(msg)
+    # No edge intersection found
+
+
+class Vector:
+    """Compare vectors by their angle without loss of precision
+
+    All vectors in direction [0, 1] are the smallest.
+    The vectors grow in clockwise direction.
+    """
+
+    __slots__ = ["x", "y", "node", "quadrant"]
+
+    def __init__(self, x, y, node):
+        self.x = x
+        self.y = y
+        self.node = node
+        if self.x >= 0 and self.y > 0:
+            self.quadrant = 1
+        elif self.x > 0 and self.y <= 0:
+            self.quadrant = 2
+        elif self.x <= 0 and self.y < 0:
+            self.quadrant = 3
+        else:
+            self.quadrant = 4
+
+    def __eq__(self, other):
+        return self.quadrant == other.quadrant and self.x * other.y == self.y * other.x
+
+    def __lt__(self, other):
+        if self.quadrant < other.quadrant:
+            return True
+        elif self.quadrant > other.quadrant:
+            return False
+        else:
+            return self.x * other.y < self.y * other.x
+
+    def __ne__(self, other):
+        return self != other
+
+    def __le__(self, other):
+        return not other < self
+
+    def __gt__(self, other):
+        return other < self
+
+    def __ge__(self, other):
+        return not self < other
+
+
+def planar_drawing_conforms_to_embedding(embedding, pos):
+    """Checks if pos conforms to the planar embedding
+
+    Returns true iff the neighbors are actually oriented in the orientation
+    specified of the embedding
+    """
+    for v in embedding:
+        nbr_vectors = []
+        v_pos = pos[v]
+        for nbr in embedding[v]:
+            new_vector = Vector(pos[nbr][0] - v_pos[0], pos[nbr][1] - v_pos[1], nbr)
+            nbr_vectors.append(new_vector)
+        # Sort neighbors according to their phi angle
+        nbr_vectors.sort()
+        for idx, nbr_vector in enumerate(nbr_vectors):
+            cw_vector = nbr_vectors[(idx + 1) % len(nbr_vectors)]
+            ccw_vector = nbr_vectors[idx - 1]
+            if (
+                embedding[v][nbr_vector.node]["cw"] != cw_vector.node
+                or embedding[v][nbr_vector.node]["ccw"] != ccw_vector.node
+            ):
+                return False
+            if cw_vector.node != nbr_vector.node and cw_vector == nbr_vector:
+                # Lines overlap
+                return False
+            if ccw_vector.node != nbr_vector.node and ccw_vector == nbr_vector:
+                # Lines overlap
+                return False
+    return True
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_planarity.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_planarity.py
new file mode 100644
index 0000000000000000000000000000000000000000..af2d9a981d0120f97dce4a3a32bef457431c2e3d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_planarity.py
@@ -0,0 +1,556 @@
+import pytest
+
+import networkx as nx
+from networkx.algorithms.planarity import (
+    check_planarity_recursive,
+    get_counterexample,
+    get_counterexample_recursive,
+)
+
+
+class TestLRPlanarity:
+    """Nose Unit tests for the :mod:`networkx.algorithms.planarity` module.
+
+    Tests three things:
+    1. Check that the result is correct
+        (returns planar if and only if the graph is actually planar)
+    2. In case a counter example is returned: Check if it is correct
+    3. In case an embedding is returned: Check if its actually an embedding
+    """
+
+    @staticmethod
+    def check_graph(G, is_planar=None):
+        """Raises an exception if the lr_planarity check returns a wrong result
+
+        Parameters
+        ----------
+        G : NetworkX graph
+        is_planar : bool
+            The expected result of the planarity check.
+            If set to None only counter example or embedding are verified.
+
+        """
+
+        # obtain results of planarity check
+        is_planar_lr, result = nx.check_planarity(G, True)
+        is_planar_lr_rec, result_rec = check_planarity_recursive(G, True)
+
+        if is_planar is not None:
+            # set a message for the assert
+            if is_planar:
+                msg = "Wrong planarity check result. Should be planar."
+            else:
+                msg = "Wrong planarity check result. Should be non-planar."
+
+            # check if the result is as expected
+            assert is_planar == is_planar_lr, msg
+            assert is_planar == is_planar_lr_rec, msg
+
+        if is_planar_lr:
+            # check embedding
+            check_embedding(G, result)
+            check_embedding(G, result_rec)
+        else:
+            # check counter example
+            check_counterexample(G, result)
+            check_counterexample(G, result_rec)
+
+    def test_simple_planar_graph(self):
+        e = [
+            (1, 2),
+            (2, 3),
+            (3, 4),
+            (4, 6),
+            (6, 7),
+            (7, 1),
+            (1, 5),
+            (5, 2),
+            (2, 4),
+            (4, 5),
+            (5, 7),
+        ]
+        self.check_graph(nx.Graph(e), is_planar=True)
+
+    def test_planar_with_selfloop(self):
+        e = [
+            (1, 1),
+            (2, 2),
+            (3, 3),
+            (4, 4),
+            (5, 5),
+            (1, 2),
+            (1, 3),
+            (1, 5),
+            (2, 5),
+            (2, 4),
+            (3, 4),
+            (3, 5),
+            (4, 5),
+        ]
+        self.check_graph(nx.Graph(e), is_planar=True)
+
+    def test_k3_3(self):
+        self.check_graph(nx.complete_bipartite_graph(3, 3), is_planar=False)
+
+    def test_k5(self):
+        self.check_graph(nx.complete_graph(5), is_planar=False)
+
+    def test_multiple_components_planar(self):
+        e = [(1, 2), (2, 3), (3, 1), (4, 5), (5, 6), (6, 4)]
+        self.check_graph(nx.Graph(e), is_planar=True)
+
+    def test_multiple_components_non_planar(self):
+        G = nx.complete_graph(5)
+        # add another planar component to the non planar component
+        # G stays non planar
+        G.add_edges_from([(6, 7), (7, 8), (8, 6)])
+        self.check_graph(G, is_planar=False)
+
+    def test_non_planar_with_selfloop(self):
+        G = nx.complete_graph(5)
+        # add self loops
+        for i in range(5):
+            G.add_edge(i, i)
+        self.check_graph(G, is_planar=False)
+
+    def test_non_planar1(self):
+        # tests a graph that has no subgraph directly isomorph to K5 or K3_3
+        e = [
+            (1, 5),
+            (1, 6),
+            (1, 7),
+            (2, 6),
+            (2, 3),
+            (3, 5),
+            (3, 7),
+            (4, 5),
+            (4, 6),
+            (4, 7),
+        ]
+        self.check_graph(nx.Graph(e), is_planar=False)
+
+    def test_loop(self):
+        # test a graph with a selfloop
+        e = [(1, 2), (2, 2)]
+        G = nx.Graph(e)
+        self.check_graph(G, is_planar=True)
+
+    def test_comp(self):
+        # test multiple component graph
+        e = [(1, 2), (3, 4)]
+        G = nx.Graph(e)
+        G.remove_edge(1, 2)
+        self.check_graph(G, is_planar=True)
+
+    def test_goldner_harary(self):
+        # test goldner-harary graph (a maximal planar graph)
+        e = [
+            (1, 2),
+            (1, 3),
+            (1, 4),
+            (1, 5),
+            (1, 7),
+            (1, 8),
+            (1, 10),
+            (1, 11),
+            (2, 3),
+            (2, 4),
+            (2, 6),
+            (2, 7),
+            (2, 9),
+            (2, 10),
+            (2, 11),
+            (3, 4),
+            (4, 5),
+            (4, 6),
+            (4, 7),
+            (5, 7),
+            (6, 7),
+            (7, 8),
+            (7, 9),
+            (7, 10),
+            (8, 10),
+            (9, 10),
+            (10, 11),
+        ]
+        G = nx.Graph(e)
+        self.check_graph(G, is_planar=True)
+
+    def test_planar_multigraph(self):
+        G = nx.MultiGraph([(1, 2), (1, 2), (1, 2), (1, 2), (2, 3), (3, 1)])
+        self.check_graph(G, is_planar=True)
+
+    def test_non_planar_multigraph(self):
+        G = nx.MultiGraph(nx.complete_graph(5))
+        G.add_edges_from([(1, 2)] * 5)
+        self.check_graph(G, is_planar=False)
+
+    def test_planar_digraph(self):
+        G = nx.DiGraph([(1, 2), (2, 3), (2, 4), (4, 1), (4, 2), (1, 4), (3, 2)])
+        self.check_graph(G, is_planar=True)
+
+    def test_non_planar_digraph(self):
+        G = nx.DiGraph(nx.complete_graph(5))
+        G.remove_edge(1, 2)
+        G.remove_edge(4, 1)
+        self.check_graph(G, is_planar=False)
+
+    def test_single_component(self):
+        # Test a graph with only a single node
+        G = nx.Graph()
+        G.add_node(1)
+        self.check_graph(G, is_planar=True)
+
+    def test_graph1(self):
+        G = nx.Graph(
+            [
+                (3, 10),
+                (2, 13),
+                (1, 13),
+                (7, 11),
+                (0, 8),
+                (8, 13),
+                (0, 2),
+                (0, 7),
+                (0, 10),
+                (1, 7),
+            ]
+        )
+        self.check_graph(G, is_planar=True)
+
+    def test_graph2(self):
+        G = nx.Graph(
+            [
+                (1, 2),
+                (4, 13),
+                (0, 13),
+                (4, 5),
+                (7, 10),
+                (1, 7),
+                (0, 3),
+                (2, 6),
+                (5, 6),
+                (7, 13),
+                (4, 8),
+                (0, 8),
+                (0, 9),
+                (2, 13),
+                (6, 7),
+                (3, 6),
+                (2, 8),
+            ]
+        )
+        self.check_graph(G, is_planar=False)
+
+    def test_graph3(self):
+        G = nx.Graph(
+            [
+                (0, 7),
+                (3, 11),
+                (3, 4),
+                (8, 9),
+                (4, 11),
+                (1, 7),
+                (1, 13),
+                (1, 11),
+                (3, 5),
+                (5, 7),
+                (1, 3),
+                (0, 4),
+                (5, 11),
+                (5, 13),
+            ]
+        )
+        self.check_graph(G, is_planar=False)
+
+    def test_counterexample_planar(self):
+        with pytest.raises(nx.NetworkXException):
+            # Try to get a counterexample of a planar graph
+            G = nx.Graph()
+            G.add_node(1)
+            get_counterexample(G)
+
+    def test_counterexample_planar_recursive(self):
+        with pytest.raises(nx.NetworkXException):
+            # Try to get a counterexample of a planar graph
+            G = nx.Graph()
+            G.add_node(1)
+            get_counterexample_recursive(G)
+
+    def test_edge_removal_from_planar_embedding(self):
+        # PlanarEmbedding.check_structure() must succeed after edge removal
+        edges = ((0, 1), (1, 2), (2, 3), (3, 4), (4, 0), (0, 2), (0, 3))
+        G = nx.Graph(edges)
+        cert, P = nx.check_planarity(G)
+        assert cert is True
+        P.remove_edge(0, 2)
+        self.check_graph(P, is_planar=True)
+        P.add_half_edge_ccw(1, 3, 2)
+        P.add_half_edge_cw(3, 1, 2)
+        self.check_graph(P, is_planar=True)
+        P.remove_edges_from(((0, 3), (1, 3)))
+        self.check_graph(P, is_planar=True)
+
+    @pytest.mark.parametrize("graph_type", (nx.Graph, nx.MultiGraph))
+    def test_graph_planar_embedding_to_undirected(self, graph_type):
+        G = graph_type([(0, 1), (0, 1), (1, 2), (2, 3), (3, 0), (0, 2)])
+        is_planar, P = nx.check_planarity(G)
+        assert is_planar
+        U = P.to_undirected()
+        assert isinstance(U, nx.Graph)
+        assert all((d == {} for _, _, d in U.edges(data=True)))
+
+    @pytest.mark.parametrize(
+        "reciprocal, as_view", [(True, True), (True, False), (False, True)]
+    )
+    def test_planar_embedding_to_undirected_invalid_parameters(
+        self, reciprocal, as_view
+    ):
+        G = nx.Graph([(0, 1), (1, 2), (2, 3), (3, 0), (0, 2)])
+        is_planar, P = nx.check_planarity(G)
+        assert is_planar
+        with pytest.raises(ValueError, match="is not supported for PlanarEmbedding."):
+            P.to_undirected(reciprocal=reciprocal, as_view=as_view)
+
+
+def check_embedding(G, embedding):
+    """Raises an exception if the combinatorial embedding is not correct
+
+    Parameters
+    ----------
+    G : NetworkX graph
+    embedding : a dict mapping nodes to a list of edges
+        This specifies the ordering of the outgoing edges from a node for
+        a combinatorial embedding
+
+    Notes
+    -----
+    Checks the following things:
+        - The type of the embedding is correct
+        - The nodes and edges match the original graph
+        - Every half edge has its matching opposite half edge
+        - No intersections of edges (checked by Euler's formula)
+    """
+
+    if not isinstance(embedding, nx.PlanarEmbedding):
+        raise nx.NetworkXException("Bad embedding. Not of type nx.PlanarEmbedding")
+
+    # Check structure
+    embedding.check_structure()
+
+    # Check that graphs are equivalent
+
+    assert set(G.nodes) == set(embedding.nodes), (
+        "Bad embedding. Nodes don't match the original graph."
+    )
+
+    # Check that the edges are equal
+    g_edges = set()
+    for edge in G.edges:
+        if edge[0] != edge[1]:
+            g_edges.add((edge[0], edge[1]))
+            g_edges.add((edge[1], edge[0]))
+    assert g_edges == set(embedding.edges), (
+        "Bad embedding. Edges don't match the original graph."
+    )
+
+
+def check_counterexample(G, sub_graph):
+    """Raises an exception if the counterexample is wrong.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+    subdivision_nodes : set
+        A set of nodes inducing a subgraph as a counterexample
+    """
+    # 1. Create the sub graph
+    sub_graph = nx.Graph(sub_graph)
+
+    # 2. Remove self loops
+    for u in sub_graph:
+        if sub_graph.has_edge(u, u):
+            sub_graph.remove_edge(u, u)
+
+    # keep track of nodes we might need to contract
+    contract = list(sub_graph)
+
+    # 3. Contract Edges
+    while len(contract) > 0:
+        contract_node = contract.pop()
+        if contract_node not in sub_graph:
+            # Node was already contracted
+            continue
+        degree = sub_graph.degree[contract_node]
+        # Check if we can remove the node
+        if degree == 2:
+            # Get the two neighbors
+            neighbors = iter(sub_graph[contract_node])
+            u = next(neighbors)
+            v = next(neighbors)
+            # Save nodes for later
+            contract.append(u)
+            contract.append(v)
+            # Contract edge
+            sub_graph.remove_node(contract_node)
+            sub_graph.add_edge(u, v)
+
+    # 4. Check for isomorphism with K5 or K3_3 graphs
+    if len(sub_graph) == 5:
+        if not nx.is_isomorphic(nx.complete_graph(5), sub_graph):
+            raise nx.NetworkXException("Bad counter example.")
+    elif len(sub_graph) == 6:
+        if not nx.is_isomorphic(nx.complete_bipartite_graph(3, 3), sub_graph):
+            raise nx.NetworkXException("Bad counter example.")
+    else:
+        raise nx.NetworkXException("Bad counter example.")
+
+
+class TestPlanarEmbeddingClass:
+    def test_add_half_edge(self):
+        embedding = nx.PlanarEmbedding()
+        embedding.add_half_edge(0, 1)
+        with pytest.raises(
+            nx.NetworkXException, match="Invalid clockwise reference node."
+        ):
+            embedding.add_half_edge(0, 2, cw=3)
+        with pytest.raises(
+            nx.NetworkXException, match="Invalid counterclockwise reference node."
+        ):
+            embedding.add_half_edge(0, 2, ccw=3)
+        with pytest.raises(
+            nx.NetworkXException, match="Only one of cw/ccw can be specified."
+        ):
+            embedding.add_half_edge(0, 2, cw=1, ccw=1)
+        with pytest.raises(
+            nx.NetworkXException,
+            match=(
+                r"Node already has out-half-edge\(s\), either"
+                " cw or ccw reference node required."
+            ),
+        ):
+            embedding.add_half_edge(0, 2)
+        # these should work
+        embedding.add_half_edge(0, 2, cw=1)
+        embedding.add_half_edge(0, 3, ccw=1)
+        assert sorted(embedding.edges(data=True)) == [
+            (0, 1, {"ccw": 2, "cw": 3}),
+            (0, 2, {"cw": 1, "ccw": 3}),
+            (0, 3, {"cw": 2, "ccw": 1}),
+        ]
+
+    def test_get_data(self):
+        embedding = self.get_star_embedding(4)
+        data = embedding.get_data()
+        data_cmp = {0: [3, 2, 1], 1: [0], 2: [0], 3: [0]}
+        assert data == data_cmp
+
+    def test_edge_removal(self):
+        embedding = nx.PlanarEmbedding()
+        embedding.set_data(
+            {
+                1: [2, 5, 7],
+                2: [1, 3, 4, 5],
+                3: [2, 4],
+                4: [3, 6, 5, 2],
+                5: [7, 1, 2, 4],
+                6: [4, 7],
+                7: [6, 1, 5],
+            }
+        )
+        # remove_edges_from() calls remove_edge(), so both are tested here
+        embedding.remove_edges_from(((5, 4), (1, 5)))
+        embedding.check_structure()
+        embedding_expected = nx.PlanarEmbedding()
+        embedding_expected.set_data(
+            {
+                1: [2, 7],
+                2: [1, 3, 4, 5],
+                3: [2, 4],
+                4: [3, 6, 2],
+                5: [7, 2],
+                6: [4, 7],
+                7: [6, 1, 5],
+            }
+        )
+        assert nx.utils.graphs_equal(embedding, embedding_expected)
+
+    def test_missing_edge_orientation(self):
+        embedding = nx.PlanarEmbedding({1: {2: {}}, 2: {1: {}}})
+        with pytest.raises(nx.NetworkXException):
+            # Invalid structure because the orientation of the edge was not set
+            embedding.check_structure()
+
+    def test_invalid_edge_orientation(self):
+        embedding = nx.PlanarEmbedding(
+            {
+                1: {2: {"cw": 2, "ccw": 2}},
+                2: {1: {"cw": 1, "ccw": 1}},
+                1: {3: {}},
+                3: {1: {}},
+            }
+        )
+        with pytest.raises(nx.NetworkXException):
+            embedding.check_structure()
+
+    def test_missing_half_edge(self):
+        embedding = nx.PlanarEmbedding()
+        embedding.add_half_edge(1, 2)
+        with pytest.raises(nx.NetworkXException):
+            # Invalid structure because other half edge is missing
+            embedding.check_structure()
+
+    def test_not_fulfilling_euler_formula(self):
+        embedding = nx.PlanarEmbedding()
+        for i in range(5):
+            ref = None
+            for j in range(5):
+                if i != j:
+                    embedding.add_half_edge(i, j, cw=ref)
+                    ref = j
+        with pytest.raises(nx.NetworkXException):
+            embedding.check_structure()
+
+    def test_missing_reference(self):
+        embedding = nx.PlanarEmbedding()
+        with pytest.raises(nx.NetworkXException, match="Invalid reference node."):
+            embedding.add_half_edge(1, 2, ccw=3)
+
+    def test_connect_components(self):
+        embedding = nx.PlanarEmbedding()
+        embedding.connect_components(1, 2)
+
+    def test_successful_face_traversal(self):
+        embedding = nx.PlanarEmbedding()
+        embedding.add_half_edge(1, 2)
+        embedding.add_half_edge(2, 1)
+        face = embedding.traverse_face(1, 2)
+        assert face == [1, 2]
+
+    def test_unsuccessful_face_traversal(self):
+        embedding = nx.PlanarEmbedding(
+            {1: {2: {"cw": 3, "ccw": 2}}, 2: {1: {"cw": 3, "ccw": 1}}}
+        )
+        with pytest.raises(nx.NetworkXException):
+            embedding.traverse_face(1, 2)
+
+    def test_forbidden_methods(self):
+        embedding = nx.PlanarEmbedding()
+        embedding.add_node(42)  # no exception
+        embedding.add_nodes_from([(23, 24)])  # no exception
+        with pytest.raises(NotImplementedError):
+            embedding.add_edge(1, 3)
+        with pytest.raises(NotImplementedError):
+            embedding.add_edges_from([(0, 2), (1, 4)])
+        with pytest.raises(NotImplementedError):
+            embedding.add_weighted_edges_from([(0, 2, 350), (1, 4, 125)])
+
+    @staticmethod
+    def get_star_embedding(n):
+        embedding = nx.PlanarEmbedding()
+        ref = None
+        for i in range(1, n):
+            embedding.add_half_edge(0, i, cw=ref)
+            ref = i
+            embedding.add_half_edge(i, 0)
+        return embedding
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_polynomials.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_polynomials.py
new file mode 100644
index 0000000000000000000000000000000000000000..a81d6a69551ead74d3335fda408111a0b580bf6a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_polynomials.py
@@ -0,0 +1,57 @@
+"""Unit tests for the :mod:`networkx.algorithms.polynomials` module."""
+
+import pytest
+
+import networkx as nx
+
+sympy = pytest.importorskip("sympy")
+
+
+# Mapping of input graphs to a string representation of their tutte polynomials
+_test_tutte_graphs = {
+    nx.complete_graph(1): "1",
+    nx.complete_graph(4): "x**3 + 3*x**2 + 4*x*y + 2*x + y**3 + 3*y**2 + 2*y",
+    nx.cycle_graph(5): "x**4 + x**3 + x**2 + x + y",
+    nx.diamond_graph(): "x**3 + 2*x**2 + 2*x*y + x + y**2 + y",
+}
+
+_test_chromatic_graphs = {
+    nx.complete_graph(1): "x",
+    nx.complete_graph(4): "x**4 - 6*x**3 + 11*x**2 - 6*x",
+    nx.cycle_graph(5): "x**5 - 5*x**4 + 10*x**3 - 10*x**2 + 4*x",
+    nx.diamond_graph(): "x**4 - 5*x**3 + 8*x**2 - 4*x",
+    nx.path_graph(5): "x**5 - 4*x**4 + 6*x**3 - 4*x**2 + x",
+}
+
+
+@pytest.mark.parametrize(("G", "expected"), _test_tutte_graphs.items())
+def test_tutte_polynomial(G, expected):
+    assert nx.tutte_polynomial(G).equals(expected)
+
+
+@pytest.mark.parametrize("G", _test_tutte_graphs.keys())
+def test_tutte_polynomial_disjoint(G):
+    """Tutte polynomial factors into the Tutte polynomials of its components.
+    Verify this property with the disjoint union of two copies of the input graph.
+    """
+    t_g = nx.tutte_polynomial(G)
+    H = nx.disjoint_union(G, G)
+    t_h = nx.tutte_polynomial(H)
+    assert sympy.simplify(t_g * t_g).equals(t_h)
+
+
+@pytest.mark.parametrize(("G", "expected"), _test_chromatic_graphs.items())
+def test_chromatic_polynomial(G, expected):
+    assert nx.chromatic_polynomial(G).equals(expected)
+
+
+@pytest.mark.parametrize("G", _test_chromatic_graphs.keys())
+def test_chromatic_polynomial_disjoint(G):
+    """Chromatic polynomial factors into the Chromatic polynomials of its
+    components. Verify this property with the disjoint union of two copies of
+    the input graph.
+    """
+    x_g = nx.chromatic_polynomial(G)
+    H = nx.disjoint_union(G, G)
+    x_h = nx.chromatic_polynomial(H)
+    assert sympy.simplify(x_g * x_g).equals(x_h)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_reciprocity.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_reciprocity.py
new file mode 100644
index 0000000000000000000000000000000000000000..e713bc4303f9bfea1199f01d8369c6bdab1a221f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_reciprocity.py
@@ -0,0 +1,37 @@
+import pytest
+
+import networkx as nx
+
+
+class TestReciprocity:
+    # test overall reciprocity by passing whole graph
+    def test_reciprocity_digraph(self):
+        DG = nx.DiGraph([(1, 2), (2, 1)])
+        reciprocity = nx.reciprocity(DG)
+        assert reciprocity == 1.0
+
+    # test empty graph's overall reciprocity which will throw an error
+    def test_overall_reciprocity_empty_graph(self):
+        with pytest.raises(nx.NetworkXError):
+            DG = nx.DiGraph()
+            nx.overall_reciprocity(DG)
+
+    # test for reciprocity for a list of nodes
+    def test_reciprocity_graph_nodes(self):
+        DG = nx.DiGraph([(1, 2), (2, 3), (3, 2)])
+        reciprocity = nx.reciprocity(DG, [1, 2])
+        expected_reciprocity = {1: 0.0, 2: 0.6666666666666666}
+        assert reciprocity == expected_reciprocity
+
+    # test for reciprocity for a single node
+    def test_reciprocity_graph_node(self):
+        DG = nx.DiGraph([(1, 2), (2, 3), (3, 2)])
+        reciprocity = nx.reciprocity(DG, 2)
+        assert reciprocity == 0.6666666666666666
+
+    # test for reciprocity for an isolated node
+    def test_reciprocity_graph_isolated_nodes(self):
+        with pytest.raises(nx.NetworkXError):
+            DG = nx.DiGraph([(1, 2)])
+            DG.add_node(4)
+            nx.reciprocity(DG, 4)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_regular.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_regular.py
new file mode 100644
index 0000000000000000000000000000000000000000..b652089a65c927256efda2bae2f4510d7aead739
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_regular.py
@@ -0,0 +1,88 @@
+import pytest
+
+import networkx as nx
+import networkx.algorithms.regular as reg
+import networkx.generators as gen
+
+
+class TestKFactor:
+    @pytest.mark.parametrize("n", [3, 4, 5])
+    def test_k_factor_cycle(self, n):
+        g = nx.cycle_graph(n)
+        kf = nx.k_factor(g, 2)
+        assert g.edges == kf.edges
+        assert g.nodes == kf.nodes
+
+    @pytest.mark.parametrize("k", range(3))
+    def test_k_factor_grid(self, k):
+        g = nx.grid_2d_graph(4, 4)
+        kf = nx.k_factor(g, k)
+        assert g.nodes == kf.nodes
+        assert all(g.has_edge(*e) for e in kf.edges)
+        assert nx.is_k_regular(kf, k)
+
+    @pytest.mark.parametrize("k", range(6))
+    def test_k_factor_complete(self, k):
+        g = nx.complete_graph(6)
+        kf = nx.k_factor(g, k)
+        assert g.nodes == kf.nodes
+        assert all(g.has_edge(*e) for e in kf.edges)
+        assert nx.is_k_regular(kf, k)
+
+    def test_k_factor_degree(self):
+        g = nx.grid_2d_graph(4, 4)
+        with pytest.raises(nx.NetworkXUnfeasible, match=r"degree less than"):
+            nx.k_factor(g, 3)
+
+    def test_k_factor_no_matching(self):
+        g = nx.hexagonal_lattice_graph(4, 4)
+        # Perfect matching doesn't exist for 4,4 hexagonal lattice graph
+        with pytest.raises(nx.NetworkXUnfeasible, match=r"no perfect matching"):
+            nx.k_factor(g, 2)
+
+    @pytest.mark.parametrize("graph_type", [nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph])
+    def test_k_factor_not_implemented(self, graph_type):
+        with pytest.raises(nx.NetworkXNotImplemented, match=r"not implemented for"):
+            nx.k_factor(graph_type(), 2)
+
+
+class TestIsRegular:
+    @pytest.mark.parametrize(
+        "graph,expected",
+        [
+            (nx.cycle_graph(4), True),
+            (nx.complete_graph(5), True),
+            (nx.path_graph(5), False),
+            (nx.lollipop_graph(5, 5), False),
+            (nx.cycle_graph(3, create_using=nx.DiGraph), True),
+            (nx.Graph([(0, 1)]), True),
+            (nx.DiGraph([(0, 1)]), False),
+            (nx.MultiGraph([(0, 1), (0, 1)]), True),
+            (nx.MultiDiGraph([(0, 1), (0, 1)]), False),
+        ],
+    )
+    def test_is_regular(self, graph, expected):
+        assert reg.is_regular(graph) == expected
+
+    def test_is_regular_empty_graph_raises(self):
+        G = nx.Graph()
+        with pytest.raises(nx.NetworkXPointlessConcept, match="Graph has no nodes"):
+            nx.is_regular(G)
+
+
+class TestIsKRegular:
+    def test_is_k_regular1(self):
+        g = gen.cycle_graph(4)
+        assert reg.is_k_regular(g, 2)
+        assert not reg.is_k_regular(g, 3)
+
+    def test_is_k_regular2(self):
+        g = gen.complete_graph(5)
+        assert reg.is_k_regular(g, 4)
+        assert not reg.is_k_regular(g, 3)
+        assert not reg.is_k_regular(g, 6)
+
+    def test_is_k_regular3(self):
+        g = gen.lollipop_graph(5, 5)
+        assert not reg.is_k_regular(g, 5)
+        assert not reg.is_k_regular(g, 6)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_richclub.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_richclub.py
new file mode 100644
index 0000000000000000000000000000000000000000..21721577fed219aebcfe9a4388b25503ad252140
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_richclub.py
@@ -0,0 +1,149 @@
+import pytest
+
+import networkx as nx
+
+
+def test_richclub():
+    G = nx.Graph([(0, 1), (0, 2), (1, 2), (1, 3), (1, 4), (4, 5)])
+    rc = nx.richclub.rich_club_coefficient(G, normalized=False)
+    assert rc == {0: 12.0 / 30, 1: 8.0 / 12}
+
+    # test single value
+    rc0 = nx.richclub.rich_club_coefficient(G, normalized=False)[0]
+    assert rc0 == 12.0 / 30.0
+
+
+def test_richclub_seed():
+    G = nx.Graph([(0, 1), (0, 2), (1, 2), (1, 3), (1, 4), (4, 5)])
+    rcNorm = nx.richclub.rich_club_coefficient(G, Q=2, seed=1)
+    assert rcNorm == {0: 1.0, 1: 1.0}
+
+
+def test_richclub_normalized():
+    G = nx.Graph([(0, 1), (0, 2), (1, 2), (1, 3), (1, 4), (4, 5)])
+    rcNorm = nx.richclub.rich_club_coefficient(G, Q=2, seed=42)
+    assert rcNorm == {0: 1.0, 1: 1.0}
+
+
+def test_richclub2():
+    T = nx.balanced_tree(2, 10)
+    rc = nx.richclub.rich_club_coefficient(T, normalized=False)
+    assert rc == {
+        0: 4092 / (2047 * 2046.0),
+        1: (2044.0 / (1023 * 1022)),
+        2: (2040.0 / (1022 * 1021)),
+    }
+
+
+def test_richclub3():
+    # tests edgecase
+    G = nx.karate_club_graph()
+    rc = nx.rich_club_coefficient(G, normalized=False)
+    assert rc == {
+        0: 156.0 / 1122,
+        1: 154.0 / 1056,
+        2: 110.0 / 462,
+        3: 78.0 / 240,
+        4: 44.0 / 90,
+        5: 22.0 / 42,
+        6: 10.0 / 20,
+        7: 10.0 / 20,
+        8: 10.0 / 20,
+        9: 6.0 / 12,
+        10: 2.0 / 6,
+        11: 2.0 / 6,
+        12: 0.0,
+        13: 0.0,
+        14: 0.0,
+        15: 0.0,
+    }
+
+
+def test_richclub4():
+    G = nx.Graph()
+    G.add_edges_from(
+        [(0, 1), (0, 2), (0, 3), (0, 4), (4, 5), (5, 9), (6, 9), (7, 9), (8, 9)]
+    )
+    rc = nx.rich_club_coefficient(G, normalized=False)
+    assert rc == {0: 18 / 90.0, 1: 6 / 12.0, 2: 0.0, 3: 0.0}
+
+
+def test_richclub_exception():
+    with pytest.raises(nx.NetworkXNotImplemented):
+        G = nx.DiGraph()
+        nx.rich_club_coefficient(G)
+
+
+def test_rich_club_exception2():
+    with pytest.raises(nx.NetworkXNotImplemented):
+        G = nx.MultiGraph()
+        nx.rich_club_coefficient(G)
+
+
+def test_rich_club_selfloop():
+    G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+    G.add_edge(1, 1)  # self loop
+    G.add_edge(1, 2)
+    with pytest.raises(
+        Exception,
+        match="rich_club_coefficient is not implemented for graphs with self loops.",
+    ):
+        nx.rich_club_coefficient(G)
+
+
+def test_rich_club_leq_3_nodes_unnormalized():
+    # edgeless graphs upto 3 nodes
+    G = nx.Graph()
+    rc = nx.rich_club_coefficient(G, normalized=False)
+    assert rc == {}
+
+    for i in range(3):
+        G.add_node(i)
+        rc = nx.rich_club_coefficient(G, normalized=False)
+        assert rc == {}
+
+    # 2 nodes, single edge
+    G = nx.Graph()
+    G.add_edge(0, 1)
+    rc = nx.rich_club_coefficient(G, normalized=False)
+    assert rc == {0: 1}
+
+    # 3 nodes, single edge
+    G = nx.Graph()
+    G.add_nodes_from([0, 1, 2])
+    G.add_edge(0, 1)
+    rc = nx.rich_club_coefficient(G, normalized=False)
+    assert rc == {0: 1}
+
+    # 3 nodes, 2 edges
+    G.add_edge(1, 2)
+    rc = nx.rich_club_coefficient(G, normalized=False)
+    assert rc == {0: 2 / 3}
+
+    # 3 nodes, 3 edges
+    G.add_edge(0, 2)
+    rc = nx.rich_club_coefficient(G, normalized=False)
+    assert rc == {0: 1, 1: 1}
+
+
+def test_rich_club_leq_3_nodes_normalized():
+    G = nx.Graph()
+    with pytest.raises(
+        nx.exception.NetworkXError,
+        match="Graph has fewer than four nodes",
+    ):
+        rc = nx.rich_club_coefficient(G, normalized=True)
+
+    for i in range(3):
+        G.add_node(i)
+        with pytest.raises(
+            nx.exception.NetworkXError,
+            match="Graph has fewer than four nodes",
+        ):
+            rc = nx.rich_club_coefficient(G, normalized=True)
+
+
+# def test_richclub2_normalized():
+#    T = nx.balanced_tree(2,10)
+#    rcNorm = nx.richclub.rich_club_coefficient(T,Q=2)
+#    assert_true(rcNorm[0] ==1.0 and rcNorm[1] < 0.9 and rcNorm[2] < 0.9)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_similarity.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_similarity.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ee0a1fd10bb25d57af5d355ec3ff91b2140fd0e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_similarity.py
@@ -0,0 +1,1158 @@
+import pytest
+
+import networkx as nx
+from networkx.algorithms.similarity import (
+    graph_edit_distance,
+    optimal_edit_paths,
+    optimize_graph_edit_distance,
+)
+from networkx.generators.classic import (
+    circular_ladder_graph,
+    cycle_graph,
+    path_graph,
+    wheel_graph,
+)
+
+
+@pytest.mark.parametrize("source", (10, "foo"))
+def test_generate_random_paths_source_not_in_G(source):
+    pytest.importorskip("numpy")
+    G = nx.complete_graph(5)
+    # No exception at generator construction time
+    path_gen = nx.generate_random_paths(G, sample_size=3, source=source)
+    with pytest.raises(nx.NodeNotFound, match="Initial node.*not in G"):
+        next(path_gen)
+
+
+@pytest.mark.filterwarnings("ignore::RuntimeWarning")
+def test_generate_random_paths_with_isolated_nodes():
+    pytest.importorskip("numpy")
+    G = nx.Graph()
+    G.add_nodes_from([0, 1, 2])
+    G.add_edge(0, 1)
+
+    # Connected source node
+    paths = list(nx.generate_random_paths(G, 2, path_length=2, source=0, seed=42))
+    assert len(paths) == 2
+    assert all(len(path) == 3 for path in paths)
+    assert all(path[0] == 0 for path in paths)
+
+    # Isolated source node
+    path_gen = nx.generate_random_paths(G, 2, path_length=2, source=2, seed=42)
+    with pytest.raises(ValueError, match="probabilities contain NaN"):
+        list(path_gen)
+
+    # Random source that might pick isolated node
+    path_gen = nx.generate_random_paths(G, 2, path_length=2, seed=42)
+    with pytest.raises(ValueError, match="probabilities contain NaN"):
+        list(path_gen)
+
+
+def nmatch(n1, n2):
+    return n1 == n2
+
+
+def ematch(e1, e2):
+    return e1 == e2
+
+
+def getCanonical():
+    G = nx.Graph()
+    G.add_node("A", label="A")
+    G.add_node("B", label="B")
+    G.add_node("C", label="C")
+    G.add_node("D", label="D")
+    G.add_edge("A", "B", label="a-b")
+    G.add_edge("B", "C", label="b-c")
+    G.add_edge("B", "D", label="b-d")
+    return G
+
+
+class TestSimilarity:
+    @classmethod
+    def setup_class(cls):
+        global np
+        np = pytest.importorskip("numpy")
+        pytest.importorskip("scipy")
+
+    def test_graph_edit_distance_roots_and_timeout(self):
+        G0 = nx.star_graph(5)
+        G1 = G0.copy()
+        pytest.raises(ValueError, graph_edit_distance, G0, G1, roots=[2])
+        pytest.raises(ValueError, graph_edit_distance, G0, G1, roots=[2, 3, 4])
+        pytest.raises(nx.NodeNotFound, graph_edit_distance, G0, G1, roots=(9, 3))
+        pytest.raises(nx.NodeNotFound, graph_edit_distance, G0, G1, roots=(3, 9))
+        pytest.raises(nx.NodeNotFound, graph_edit_distance, G0, G1, roots=(9, 9))
+        assert graph_edit_distance(G0, G1, roots=(1, 2)) == 0
+        assert graph_edit_distance(G0, G1, roots=(0, 1)) == 8
+        assert graph_edit_distance(G0, G1, roots=(1, 2), timeout=5) == 0
+        assert graph_edit_distance(G0, G1, roots=(0, 1), timeout=5) == 8
+        assert graph_edit_distance(G0, G1, roots=(0, 1), timeout=0.0001) is None
+        # test raise on 0 timeout
+        pytest.raises(nx.NetworkXError, graph_edit_distance, G0, G1, timeout=0)
+
+    def test_graph_edit_distance(self):
+        G0 = nx.Graph()
+        G1 = path_graph(6)
+        G2 = cycle_graph(6)
+        G3 = wheel_graph(7)
+
+        assert graph_edit_distance(G0, G0) == 0
+        assert graph_edit_distance(G0, G1) == 11
+        assert graph_edit_distance(G1, G0) == 11
+        assert graph_edit_distance(G0, G2) == 12
+        assert graph_edit_distance(G2, G0) == 12
+        assert graph_edit_distance(G0, G3) == 19
+        assert graph_edit_distance(G3, G0) == 19
+
+        assert graph_edit_distance(G1, G1) == 0
+        assert graph_edit_distance(G1, G2) == 1
+        assert graph_edit_distance(G2, G1) == 1
+        assert graph_edit_distance(G1, G3) == 8
+        assert graph_edit_distance(G3, G1) == 8
+
+        assert graph_edit_distance(G2, G2) == 0
+        assert graph_edit_distance(G2, G3) == 7
+        assert graph_edit_distance(G3, G2) == 7
+
+        assert graph_edit_distance(G3, G3) == 0
+
+    def test_graph_edit_distance_node_match(self):
+        G1 = cycle_graph(5)
+        G2 = cycle_graph(5)
+        for n, attr in G1.nodes.items():
+            attr["color"] = "red" if n % 2 == 0 else "blue"
+        for n, attr in G2.nodes.items():
+            attr["color"] = "red" if n % 2 == 1 else "blue"
+        assert graph_edit_distance(G1, G2) == 0
+        assert (
+            graph_edit_distance(
+                G1, G2, node_match=lambda n1, n2: n1["color"] == n2["color"]
+            )
+            == 1
+        )
+
+    def test_graph_edit_distance_edge_match(self):
+        G1 = path_graph(6)
+        G2 = path_graph(6)
+        for e, attr in G1.edges.items():
+            attr["color"] = "red" if min(e) % 2 == 0 else "blue"
+        for e, attr in G2.edges.items():
+            attr["color"] = "red" if min(e) // 3 == 0 else "blue"
+        assert graph_edit_distance(G1, G2) == 0
+        assert (
+            graph_edit_distance(
+                G1, G2, edge_match=lambda e1, e2: e1["color"] == e2["color"]
+            )
+            == 2
+        )
+
+    def test_graph_edit_distance_node_cost(self):
+        G1 = path_graph(6)
+        G2 = path_graph(6)
+        for n, attr in G1.nodes.items():
+            attr["color"] = "red" if n % 2 == 0 else "blue"
+        for n, attr in G2.nodes.items():
+            attr["color"] = "red" if n % 2 == 1 else "blue"
+
+        def node_subst_cost(uattr, vattr):
+            if uattr["color"] == vattr["color"]:
+                return 1
+            else:
+                return 10
+
+        def node_del_cost(attr):
+            if attr["color"] == "blue":
+                return 20
+            else:
+                return 50
+
+        def node_ins_cost(attr):
+            if attr["color"] == "blue":
+                return 40
+            else:
+                return 100
+
+        assert (
+            graph_edit_distance(
+                G1,
+                G2,
+                node_subst_cost=node_subst_cost,
+                node_del_cost=node_del_cost,
+                node_ins_cost=node_ins_cost,
+            )
+            == 6
+        )
+
+    def test_graph_edit_distance_edge_cost(self):
+        G1 = path_graph(6)
+        G2 = path_graph(6)
+        for e, attr in G1.edges.items():
+            attr["color"] = "red" if min(e) % 2 == 0 else "blue"
+        for e, attr in G2.edges.items():
+            attr["color"] = "red" if min(e) // 3 == 0 else "blue"
+
+        def edge_subst_cost(gattr, hattr):
+            if gattr["color"] == hattr["color"]:
+                return 0.01
+            else:
+                return 0.1
+
+        def edge_del_cost(attr):
+            if attr["color"] == "blue":
+                return 0.2
+            else:
+                return 0.5
+
+        def edge_ins_cost(attr):
+            if attr["color"] == "blue":
+                return 0.4
+            else:
+                return 1.0
+
+        assert (
+            graph_edit_distance(
+                G1,
+                G2,
+                edge_subst_cost=edge_subst_cost,
+                edge_del_cost=edge_del_cost,
+                edge_ins_cost=edge_ins_cost,
+            )
+            == 0.23
+        )
+
+    def test_graph_edit_distance_upper_bound(self):
+        G1 = circular_ladder_graph(2)
+        G2 = circular_ladder_graph(6)
+        assert graph_edit_distance(G1, G2, upper_bound=5) is None
+        assert graph_edit_distance(G1, G2, upper_bound=24) == 22
+        assert graph_edit_distance(G1, G2) == 22
+
+    def test_optimal_edit_paths(self):
+        G1 = path_graph(3)
+        G2 = cycle_graph(3)
+        paths, cost = optimal_edit_paths(G1, G2)
+        assert cost == 1
+        assert len(paths) == 6
+
+        def canonical(vertex_path, edge_path):
+            return (
+                tuple(sorted(vertex_path)),
+                tuple(sorted(edge_path, key=lambda x: (None in x, x))),
+            )
+
+        expected_paths = [
+            (
+                [(0, 0), (1, 1), (2, 2)],
+                [((0, 1), (0, 1)), ((1, 2), (1, 2)), (None, (0, 2))],
+            ),
+            (
+                [(0, 0), (1, 2), (2, 1)],
+                [((0, 1), (0, 2)), ((1, 2), (1, 2)), (None, (0, 1))],
+            ),
+            (
+                [(0, 1), (1, 0), (2, 2)],
+                [((0, 1), (0, 1)), ((1, 2), (0, 2)), (None, (1, 2))],
+            ),
+            (
+                [(0, 1), (1, 2), (2, 0)],
+                [((0, 1), (1, 2)), ((1, 2), (0, 2)), (None, (0, 1))],
+            ),
+            (
+                [(0, 2), (1, 0), (2, 1)],
+                [((0, 1), (0, 2)), ((1, 2), (0, 1)), (None, (1, 2))],
+            ),
+            (
+                [(0, 2), (1, 1), (2, 0)],
+                [((0, 1), (1, 2)), ((1, 2), (0, 1)), (None, (0, 2))],
+            ),
+        ]
+        assert {canonical(*p) for p in paths} == {canonical(*p) for p in expected_paths}
+
+    def test_optimize_graph_edit_distance(self):
+        G1 = circular_ladder_graph(2)
+        G2 = circular_ladder_graph(6)
+        bestcost = 1000
+        for cost in optimize_graph_edit_distance(G1, G2):
+            assert cost < bestcost
+            bestcost = cost
+        assert bestcost == 22
+
+    # def test_graph_edit_distance_bigger(self):
+    #     G1 = circular_ladder_graph(12)
+    #     G2 = circular_ladder_graph(16)
+    #     assert_equal(graph_edit_distance(G1, G2), 22)
+
+    def test_selfloops(self):
+        G0 = nx.Graph()
+        G1 = nx.Graph()
+        G1.add_edges_from((("A", "A"), ("A", "B")))
+        G2 = nx.Graph()
+        G2.add_edges_from((("A", "B"), ("B", "B")))
+        G3 = nx.Graph()
+        G3.add_edges_from((("A", "A"), ("A", "B"), ("B", "B")))
+
+        assert graph_edit_distance(G0, G0) == 0
+        assert graph_edit_distance(G0, G1) == 4
+        assert graph_edit_distance(G1, G0) == 4
+        assert graph_edit_distance(G0, G2) == 4
+        assert graph_edit_distance(G2, G0) == 4
+        assert graph_edit_distance(G0, G3) == 5
+        assert graph_edit_distance(G3, G0) == 5
+
+        assert graph_edit_distance(G1, G1) == 0
+        assert graph_edit_distance(G1, G2) == 0
+        assert graph_edit_distance(G2, G1) == 0
+        assert graph_edit_distance(G1, G3) == 1
+        assert graph_edit_distance(G3, G1) == 1
+
+        assert graph_edit_distance(G2, G2) == 0
+        assert graph_edit_distance(G2, G3) == 1
+        assert graph_edit_distance(G3, G2) == 1
+
+        assert graph_edit_distance(G3, G3) == 0
+
+    def test_digraph(self):
+        G0 = nx.DiGraph()
+        G1 = nx.DiGraph()
+        G1.add_edges_from((("A", "B"), ("B", "C"), ("C", "D"), ("D", "A")))
+        G2 = nx.DiGraph()
+        G2.add_edges_from((("A", "B"), ("B", "C"), ("C", "D"), ("A", "D")))
+        G3 = nx.DiGraph()
+        G3.add_edges_from((("A", "B"), ("A", "C"), ("B", "D"), ("C", "D")))
+
+        assert graph_edit_distance(G0, G0) == 0
+        assert graph_edit_distance(G0, G1) == 8
+        assert graph_edit_distance(G1, G0) == 8
+        assert graph_edit_distance(G0, G2) == 8
+        assert graph_edit_distance(G2, G0) == 8
+        assert graph_edit_distance(G0, G3) == 8
+        assert graph_edit_distance(G3, G0) == 8
+
+        assert graph_edit_distance(G1, G1) == 0
+        assert graph_edit_distance(G1, G2) == 2
+        assert graph_edit_distance(G2, G1) == 2
+        assert graph_edit_distance(G1, G3) == 4
+        assert graph_edit_distance(G3, G1) == 4
+
+        assert graph_edit_distance(G2, G2) == 0
+        assert graph_edit_distance(G2, G3) == 2
+        assert graph_edit_distance(G3, G2) == 2
+
+        assert graph_edit_distance(G3, G3) == 0
+
+    def test_multigraph(self):
+        G0 = nx.MultiGraph()
+        G1 = nx.MultiGraph()
+        G1.add_edges_from((("A", "B"), ("B", "C"), ("A", "C")))
+        G2 = nx.MultiGraph()
+        G2.add_edges_from((("A", "B"), ("B", "C"), ("B", "C"), ("A", "C")))
+        G3 = nx.MultiGraph()
+        G3.add_edges_from((("A", "B"), ("B", "C"), ("A", "C"), ("A", "C"), ("A", "C")))
+
+        assert graph_edit_distance(G0, G0) == 0
+        assert graph_edit_distance(G0, G1) == 6
+        assert graph_edit_distance(G1, G0) == 6
+        assert graph_edit_distance(G0, G2) == 7
+        assert graph_edit_distance(G2, G0) == 7
+        assert graph_edit_distance(G0, G3) == 8
+        assert graph_edit_distance(G3, G0) == 8
+
+        assert graph_edit_distance(G1, G1) == 0
+        assert graph_edit_distance(G1, G2) == 1
+        assert graph_edit_distance(G2, G1) == 1
+        assert graph_edit_distance(G1, G3) == 2
+        assert graph_edit_distance(G3, G1) == 2
+
+        assert graph_edit_distance(G2, G2) == 0
+        assert graph_edit_distance(G2, G3) == 1
+        assert graph_edit_distance(G3, G2) == 1
+
+        assert graph_edit_distance(G3, G3) == 0
+
+    def test_multidigraph(self):
+        G1 = nx.MultiDiGraph()
+        G1.add_edges_from(
+            (
+                ("hardware", "kernel"),
+                ("kernel", "hardware"),
+                ("kernel", "userspace"),
+                ("userspace", "kernel"),
+            )
+        )
+        G2 = nx.MultiDiGraph()
+        G2.add_edges_from(
+            (
+                ("winter", "spring"),
+                ("spring", "summer"),
+                ("summer", "autumn"),
+                ("autumn", "winter"),
+            )
+        )
+
+        assert graph_edit_distance(G1, G2) == 5
+        assert graph_edit_distance(G2, G1) == 5
+
+    # by https://github.com/jfbeaumont
+    def testCopy(self):
+        G = nx.Graph()
+        G.add_node("A", label="A")
+        G.add_node("B", label="B")
+        G.add_edge("A", "B", label="a-b")
+        assert (
+            graph_edit_distance(G, G.copy(), node_match=nmatch, edge_match=ematch) == 0
+        )
+
+    def testSame(self):
+        G1 = nx.Graph()
+        G1.add_node("A", label="A")
+        G1.add_node("B", label="B")
+        G1.add_edge("A", "B", label="a-b")
+        G2 = nx.Graph()
+        G2.add_node("A", label="A")
+        G2.add_node("B", label="B")
+        G2.add_edge("A", "B", label="a-b")
+        assert graph_edit_distance(G1, G2, node_match=nmatch, edge_match=ematch) == 0
+
+    def testOneEdgeLabelDiff(self):
+        G1 = nx.Graph()
+        G1.add_node("A", label="A")
+        G1.add_node("B", label="B")
+        G1.add_edge("A", "B", label="a-b")
+        G2 = nx.Graph()
+        G2.add_node("A", label="A")
+        G2.add_node("B", label="B")
+        G2.add_edge("A", "B", label="bad")
+        assert graph_edit_distance(G1, G2, node_match=nmatch, edge_match=ematch) == 1
+
+    def testOneNodeLabelDiff(self):
+        G1 = nx.Graph()
+        G1.add_node("A", label="A")
+        G1.add_node("B", label="B")
+        G1.add_edge("A", "B", label="a-b")
+        G2 = nx.Graph()
+        G2.add_node("A", label="Z")
+        G2.add_node("B", label="B")
+        G2.add_edge("A", "B", label="a-b")
+        assert graph_edit_distance(G1, G2, node_match=nmatch, edge_match=ematch) == 1
+
+    def testOneExtraNode(self):
+        G1 = nx.Graph()
+        G1.add_node("A", label="A")
+        G1.add_node("B", label="B")
+        G1.add_edge("A", "B", label="a-b")
+        G2 = nx.Graph()
+        G2.add_node("A", label="A")
+        G2.add_node("B", label="B")
+        G2.add_edge("A", "B", label="a-b")
+        G2.add_node("C", label="C")
+        assert graph_edit_distance(G1, G2, node_match=nmatch, edge_match=ematch) == 1
+
+    def testOneExtraEdge(self):
+        G1 = nx.Graph()
+        G1.add_node("A", label="A")
+        G1.add_node("B", label="B")
+        G1.add_node("C", label="C")
+        G1.add_node("C", label="C")
+        G1.add_edge("A", "B", label="a-b")
+        G2 = nx.Graph()
+        G2.add_node("A", label="A")
+        G2.add_node("B", label="B")
+        G2.add_node("C", label="C")
+        G2.add_edge("A", "B", label="a-b")
+        G2.add_edge("A", "C", label="a-c")
+        assert graph_edit_distance(G1, G2, node_match=nmatch, edge_match=ematch) == 1
+
+    def testOneExtraNodeAndEdge(self):
+        G1 = nx.Graph()
+        G1.add_node("A", label="A")
+        G1.add_node("B", label="B")
+        G1.add_edge("A", "B", label="a-b")
+        G2 = nx.Graph()
+        G2.add_node("A", label="A")
+        G2.add_node("B", label="B")
+        G2.add_node("C", label="C")
+        G2.add_edge("A", "B", label="a-b")
+        G2.add_edge("A", "C", label="a-c")
+        assert graph_edit_distance(G1, G2, node_match=nmatch, edge_match=ematch) == 2
+
+    def testGraph1(self):
+        G1 = getCanonical()
+        G2 = nx.Graph()
+        G2.add_node("A", label="A")
+        G2.add_node("B", label="B")
+        G2.add_node("D", label="D")
+        G2.add_node("E", label="E")
+        G2.add_edge("A", "B", label="a-b")
+        G2.add_edge("B", "D", label="b-d")
+        G2.add_edge("D", "E", label="d-e")
+        assert graph_edit_distance(G1, G2, node_match=nmatch, edge_match=ematch) == 3
+
+    def testGraph2(self):
+        G1 = getCanonical()
+        G2 = nx.Graph()
+        G2.add_node("A", label="A")
+        G2.add_node("B", label="B")
+        G2.add_node("C", label="C")
+        G2.add_node("D", label="D")
+        G2.add_node("E", label="E")
+        G2.add_edge("A", "B", label="a-b")
+        G2.add_edge("B", "C", label="b-c")
+        G2.add_edge("C", "D", label="c-d")
+        G2.add_edge("C", "E", label="c-e")
+        assert graph_edit_distance(G1, G2, node_match=nmatch, edge_match=ematch) == 4
+
+    def testGraph3(self):
+        G1 = getCanonical()
+        G2 = nx.Graph()
+        G2.add_node("A", label="A")
+        G2.add_node("B", label="B")
+        G2.add_node("C", label="C")
+        G2.add_node("D", label="D")
+        G2.add_node("E", label="E")
+        G2.add_node("F", label="F")
+        G2.add_node("G", label="G")
+        G2.add_edge("A", "C", label="a-c")
+        G2.add_edge("A", "D", label="a-d")
+        G2.add_edge("D", "E", label="d-e")
+        G2.add_edge("D", "F", label="d-f")
+        G2.add_edge("D", "G", label="d-g")
+        G2.add_edge("E", "B", label="e-b")
+        assert graph_edit_distance(G1, G2, node_match=nmatch, edge_match=ematch) == 12
+
+    def testGraph4(self):
+        G1 = getCanonical()
+        G2 = nx.Graph()
+        G2.add_node("A", label="A")
+        G2.add_node("B", label="B")
+        G2.add_node("C", label="C")
+        G2.add_node("D", label="D")
+        G2.add_edge("A", "B", label="a-b")
+        G2.add_edge("B", "C", label="b-c")
+        G2.add_edge("C", "D", label="c-d")
+        assert graph_edit_distance(G1, G2, node_match=nmatch, edge_match=ematch) == 2
+
+    def testGraph4_a(self):
+        G1 = getCanonical()
+        G2 = nx.Graph()
+        G2.add_node("A", label="A")
+        G2.add_node("B", label="B")
+        G2.add_node("C", label="C")
+        G2.add_node("D", label="D")
+        G2.add_edge("A", "B", label="a-b")
+        G2.add_edge("B", "C", label="b-c")
+        G2.add_edge("A", "D", label="a-d")
+        assert graph_edit_distance(G1, G2, node_match=nmatch, edge_match=ematch) == 2
+
+    def testGraph4_b(self):
+        G1 = getCanonical()
+        G2 = nx.Graph()
+        G2.add_node("A", label="A")
+        G2.add_node("B", label="B")
+        G2.add_node("C", label="C")
+        G2.add_node("D", label="D")
+        G2.add_edge("A", "B", label="a-b")
+        G2.add_edge("B", "C", label="b-c")
+        G2.add_edge("B", "D", label="bad")
+        assert graph_edit_distance(G1, G2, node_match=nmatch, edge_match=ematch) == 1
+
+    # note: nx.simrank_similarity_numpy not included because returns np.array
+    simrank_algs = [
+        nx.simrank_similarity,
+        nx.algorithms.similarity._simrank_similarity_python,
+    ]
+
+    @pytest.mark.parametrize("simrank_similarity", simrank_algs)
+    def test_simrank_no_source_no_target(self, simrank_similarity):
+        G = nx.cycle_graph(5)
+        expected = {
+            0: {
+                0: 1,
+                1: 0.3951219505902448,
+                2: 0.5707317069281646,
+                3: 0.5707317069281646,
+                4: 0.3951219505902449,
+            },
+            1: {
+                0: 0.3951219505902448,
+                1: 1,
+                2: 0.3951219505902449,
+                3: 0.5707317069281646,
+                4: 0.5707317069281646,
+            },
+            2: {
+                0: 0.5707317069281646,
+                1: 0.3951219505902449,
+                2: 1,
+                3: 0.3951219505902449,
+                4: 0.5707317069281646,
+            },
+            3: {
+                0: 0.5707317069281646,
+                1: 0.5707317069281646,
+                2: 0.3951219505902449,
+                3: 1,
+                4: 0.3951219505902449,
+            },
+            4: {
+                0: 0.3951219505902449,
+                1: 0.5707317069281646,
+                2: 0.5707317069281646,
+                3: 0.3951219505902449,
+                4: 1,
+            },
+        }
+        actual = simrank_similarity(G)
+        for k, v in expected.items():
+            assert v == pytest.approx(actual[k], abs=1e-2)
+
+        # For a DiGraph test, use the first graph from the paper cited in
+        # the docs: https://dl.acm.org/doi/pdf/10.1145/775047.775126
+        G = nx.DiGraph()
+        G.add_node(0, label="Univ")
+        G.add_node(1, label="ProfA")
+        G.add_node(2, label="ProfB")
+        G.add_node(3, label="StudentA")
+        G.add_node(4, label="StudentB")
+        G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 4), (4, 2), (3, 0)])
+
+        expected = {
+            0: {0: 1, 1: 0.0, 2: 0.1323363991265798, 3: 0.0, 4: 0.03387811817640443},
+            1: {0: 0.0, 1: 1, 2: 0.4135512472705618, 3: 0.0, 4: 0.10586911930126384},
+            2: {
+                0: 0.1323363991265798,
+                1: 0.4135512472705618,
+                2: 1,
+                3: 0.04234764772050554,
+                4: 0.08822426608438655,
+            },
+            3: {0: 0.0, 1: 0.0, 2: 0.04234764772050554, 3: 1, 4: 0.3308409978164495},
+            4: {
+                0: 0.03387811817640443,
+                1: 0.10586911930126384,
+                2: 0.08822426608438655,
+                3: 0.3308409978164495,
+                4: 1,
+            },
+        }
+        # Use the importance_factor from the paper to get the same numbers.
+        actual = simrank_similarity(G, importance_factor=0.8)
+        for k, v in expected.items():
+            assert v == pytest.approx(actual[k], abs=1e-2)
+
+    @pytest.mark.parametrize("simrank_similarity", simrank_algs)
+    def test_simrank_source_no_target(self, simrank_similarity):
+        G = nx.cycle_graph(5)
+        expected = {
+            0: 1,
+            1: 0.3951219505902448,
+            2: 0.5707317069281646,
+            3: 0.5707317069281646,
+            4: 0.3951219505902449,
+        }
+        actual = simrank_similarity(G, source=0)
+        assert expected == pytest.approx(actual, abs=1e-2)
+
+        # For a DiGraph test, use the first graph from the paper cited in
+        # the docs: https://dl.acm.org/doi/pdf/10.1145/775047.775126
+        G = nx.DiGraph()
+        G.add_node(0, label="Univ")
+        G.add_node(1, label="ProfA")
+        G.add_node(2, label="ProfB")
+        G.add_node(3, label="StudentA")
+        G.add_node(4, label="StudentB")
+        G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 4), (4, 2), (3, 0)])
+
+        expected = {0: 1, 1: 0.0, 2: 0.1323363991265798, 3: 0.0, 4: 0.03387811817640443}
+        # Use the importance_factor from the paper to get the same numbers.
+        actual = simrank_similarity(G, importance_factor=0.8, source=0)
+        assert expected == pytest.approx(actual, abs=1e-2)
+
+    @pytest.mark.parametrize("simrank_similarity", simrank_algs)
+    def test_simrank_noninteger_nodes(self, simrank_similarity):
+        G = nx.cycle_graph(5)
+        G = nx.relabel_nodes(G, dict(enumerate("abcde")))
+        expected = {
+            "a": 1,
+            "b": 0.3951219505902448,
+            "c": 0.5707317069281646,
+            "d": 0.5707317069281646,
+            "e": 0.3951219505902449,
+        }
+        actual = simrank_similarity(G, source="a")
+        assert expected == pytest.approx(actual, abs=1e-2)
+
+        # For a DiGraph test, use the first graph from the paper cited in
+        # the docs: https://dl.acm.org/doi/pdf/10.1145/775047.775126
+        G = nx.DiGraph()
+        G.add_node(0, label="Univ")
+        G.add_node(1, label="ProfA")
+        G.add_node(2, label="ProfB")
+        G.add_node(3, label="StudentA")
+        G.add_node(4, label="StudentB")
+        G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 4), (4, 2), (3, 0)])
+        node_labels = dict(enumerate(nx.get_node_attributes(G, "label").values()))
+        G = nx.relabel_nodes(G, node_labels)
+
+        expected = {
+            "Univ": 1,
+            "ProfA": 0.0,
+            "ProfB": 0.1323363991265798,
+            "StudentA": 0.0,
+            "StudentB": 0.03387811817640443,
+        }
+        # Use the importance_factor from the paper to get the same numbers.
+        actual = simrank_similarity(G, importance_factor=0.8, source="Univ")
+        assert expected == pytest.approx(actual, abs=1e-2)
+
+    @pytest.mark.parametrize("simrank_similarity", simrank_algs)
+    def test_simrank_source_and_target(self, simrank_similarity):
+        G = nx.cycle_graph(5)
+        expected = 1
+        actual = simrank_similarity(G, source=0, target=0)
+        assert expected == pytest.approx(actual, abs=1e-2)
+
+        # For a DiGraph test, use the first graph from the paper cited in
+        # the docs: https://dl.acm.org/doi/pdf/10.1145/775047.775126
+        G = nx.DiGraph()
+        G.add_node(0, label="Univ")
+        G.add_node(1, label="ProfA")
+        G.add_node(2, label="ProfB")
+        G.add_node(3, label="StudentA")
+        G.add_node(4, label="StudentB")
+        G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 4), (4, 2), (3, 0)])
+
+        expected = 0.1323363991265798
+        # Use the importance_factor from the paper to get the same numbers.
+        # Use the pair (0,2) because (0,0) and (0,1) have trivial results.
+        actual = simrank_similarity(G, importance_factor=0.8, source=0, target=2)
+        assert expected == pytest.approx(actual, abs=1e-5)
+
+    @pytest.mark.parametrize("alg", simrank_algs)
+    def test_simrank_max_iterations(self, alg):
+        G = nx.cycle_graph(5)
+        pytest.raises(nx.ExceededMaxIterations, alg, G, max_iterations=10)
+
+    def test_simrank_source_not_found(self):
+        G = nx.cycle_graph(5)
+        with pytest.raises(nx.NodeNotFound, match="Source node 10 not in G"):
+            nx.simrank_similarity(G, source=10)
+
+    def test_simrank_target_not_found(self):
+        G = nx.cycle_graph(5)
+        with pytest.raises(nx.NodeNotFound, match="Target node 10 not in G"):
+            nx.simrank_similarity(G, target=10)
+
+    def test_simrank_between_versions(self):
+        G = nx.cycle_graph(5)
+        # _python tolerance 1e-4
+        expected_python_tol4 = {
+            0: 1,
+            1: 0.394512499239852,
+            2: 0.5703550452791322,
+            3: 0.5703550452791323,
+            4: 0.394512499239852,
+        }
+        # _numpy tolerance 1e-4
+        expected_numpy_tol4 = {
+            0: 1.0,
+            1: 0.3947180735764555,
+            2: 0.570482097206368,
+            3: 0.570482097206368,
+            4: 0.3947180735764555,
+        }
+        actual = nx.simrank_similarity(G, source=0)
+        assert expected_numpy_tol4 == pytest.approx(actual, abs=1e-7)
+        # versions differ at 1e-4 level but equal at 1e-3
+        assert expected_python_tol4 != pytest.approx(actual, abs=1e-4)
+        assert expected_python_tol4 == pytest.approx(actual, abs=1e-3)
+
+        actual = nx.similarity._simrank_similarity_python(G, source=0)
+        assert expected_python_tol4 == pytest.approx(actual, abs=1e-7)
+        # versions differ at 1e-4 level but equal at 1e-3
+        assert expected_numpy_tol4 != pytest.approx(actual, abs=1e-4)
+        assert expected_numpy_tol4 == pytest.approx(actual, abs=1e-3)
+
+    def test_simrank_numpy_no_source_no_target(self):
+        G = nx.cycle_graph(5)
+        expected = np.array(
+            [
+                [
+                    1.0,
+                    0.3947180735764555,
+                    0.570482097206368,
+                    0.570482097206368,
+                    0.3947180735764555,
+                ],
+                [
+                    0.3947180735764555,
+                    1.0,
+                    0.3947180735764555,
+                    0.570482097206368,
+                    0.570482097206368,
+                ],
+                [
+                    0.570482097206368,
+                    0.3947180735764555,
+                    1.0,
+                    0.3947180735764555,
+                    0.570482097206368,
+                ],
+                [
+                    0.570482097206368,
+                    0.570482097206368,
+                    0.3947180735764555,
+                    1.0,
+                    0.3947180735764555,
+                ],
+                [
+                    0.3947180735764555,
+                    0.570482097206368,
+                    0.570482097206368,
+                    0.3947180735764555,
+                    1.0,
+                ],
+            ]
+        )
+        actual = nx.similarity._simrank_similarity_numpy(G)
+        np.testing.assert_allclose(expected, actual, atol=1e-7)
+
+    def test_simrank_numpy_source_no_target(self):
+        G = nx.cycle_graph(5)
+        expected = np.array(
+            [
+                1.0,
+                0.3947180735764555,
+                0.570482097206368,
+                0.570482097206368,
+                0.3947180735764555,
+            ]
+        )
+        actual = nx.similarity._simrank_similarity_numpy(G, source=0)
+        np.testing.assert_allclose(expected, actual, atol=1e-7)
+
+    def test_simrank_numpy_source_and_target(self):
+        G = nx.cycle_graph(5)
+        expected = 1.0
+        actual = nx.similarity._simrank_similarity_numpy(G, source=0, target=0)
+        np.testing.assert_allclose(expected, actual, atol=1e-7)
+
+    def test_panther_similarity_unweighted(self):
+        G = nx.Graph()
+        G.add_edge(0, 1)
+        G.add_edge(0, 2)
+        G.add_edge(0, 3)
+        G.add_edge(1, 2)
+        G.add_edge(2, 4)
+        expected = {3: 0.5, 2: 0.5, 1: 0.5, 4: 0.125}
+        sim = nx.panther_similarity(G, 0, path_length=2, seed=42)
+        assert sim == expected
+
+    def test_panther_similarity_weighted(self):
+        G = nx.Graph()
+        G.add_edge("v1", "v2", w=5)
+        G.add_edge("v1", "v3", w=1)
+        G.add_edge("v1", "v4", w=2)
+        G.add_edge("v2", "v3", w=0.1)
+        G.add_edge("v3", "v5", w=1)
+        expected = {"v3": 0.75, "v4": 0.5, "v2": 0.5, "v5": 0.25}
+        sim = nx.panther_similarity(G, "v1", path_length=2, weight="w", seed=42)
+        assert sim == expected
+
+    def test_panther_similarity_source_not_found(self):
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (0, 3), (1, 2), (2, 4)])
+        with pytest.raises(nx.NodeNotFound, match="Source node 10 not in G"):
+            nx.panther_similarity(G, source=10)
+
+    def test_panther_similarity_isolated(self):
+        G = nx.Graph()
+        G.add_nodes_from(range(5))
+        with pytest.raises(
+            nx.NetworkXUnfeasible,
+            match="Panther similarity is not defined for the isolated source node 1.",
+        ):
+            nx.panther_similarity(G, source=1)
+
+    @pytest.mark.parametrize("num_paths", (1, 3, 10))
+    @pytest.mark.parametrize("source", (0, 1))
+    def test_generate_random_paths_with_start(self, num_paths, source):
+        G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (2, 4)])
+        index_map = {}
+
+        path_gen = nx.generate_random_paths(
+            G,
+            num_paths,
+            path_length=2,
+            index_map=index_map,
+            source=source,
+        )
+        paths = list(path_gen)
+
+        # There should be num_paths paths
+        assert len(paths) == num_paths
+        # And they should all start with `source`
+        assert all(p[0] == source for p in paths)
+        # The index_map for the `source` node should contain the indices for
+        # all of the generated paths.
+        assert sorted(index_map[source]) == list(range(num_paths))
+
+    def test_generate_random_paths_unweighted(self):
+        index_map = {}
+        num_paths = 10
+        path_length = 2
+        G = nx.Graph()
+        G.add_edge(0, 1)
+        G.add_edge(0, 2)
+        G.add_edge(0, 3)
+        G.add_edge(1, 2)
+        G.add_edge(2, 4)
+        paths = nx.generate_random_paths(
+            G, num_paths, path_length=path_length, index_map=index_map, seed=42
+        )
+        expected_paths = [
+            [3, 0, 3],
+            [4, 2, 1],
+            [2, 1, 0],
+            [2, 0, 3],
+            [3, 0, 1],
+            [3, 0, 1],
+            [4, 2, 0],
+            [2, 1, 0],
+            [3, 0, 2],
+            [2, 1, 2],
+        ]
+        expected_map = {
+            0: {0, 2, 3, 4, 5, 6, 7, 8},
+            1: {1, 2, 4, 5, 7, 9},
+            2: {1, 2, 3, 6, 7, 8, 9},
+            3: {0, 3, 4, 5, 8},
+            4: {1, 6},
+        }
+
+        assert expected_paths == list(paths)
+        assert expected_map == index_map
+
+    def test_generate_random_paths_weighted(self):
+        index_map = {}
+        num_paths = 10
+        path_length = 6
+        G = nx.Graph()
+        G.add_edge("a", "b", weight=0.6)
+        G.add_edge("a", "c", weight=0.2)
+        G.add_edge("c", "d", weight=0.1)
+        G.add_edge("c", "e", weight=0.7)
+        G.add_edge("c", "f", weight=0.9)
+        G.add_edge("a", "d", weight=0.3)
+        paths = nx.generate_random_paths(
+            G, num_paths, path_length=path_length, index_map=index_map, seed=42
+        )
+
+        expected_paths = [
+            ["d", "c", "f", "c", "d", "a", "b"],
+            ["e", "c", "f", "c", "f", "c", "e"],
+            ["d", "a", "b", "a", "b", "a", "c"],
+            ["b", "a", "d", "a", "b", "a", "b"],
+            ["d", "a", "b", "a", "b", "a", "d"],
+            ["d", "a", "b", "a", "b", "a", "c"],
+            ["d", "a", "b", "a", "b", "a", "b"],
+            ["f", "c", "f", "c", "f", "c", "e"],
+            ["d", "a", "d", "a", "b", "a", "b"],
+            ["e", "c", "f", "c", "e", "c", "d"],
+        ]
+        expected_map = {
+            "d": {0, 2, 3, 4, 5, 6, 8, 9},
+            "c": {0, 1, 2, 5, 7, 9},
+            "f": {0, 1, 9, 7},
+            "a": {0, 2, 3, 4, 5, 6, 8},
+            "b": {0, 2, 3, 4, 5, 6, 8},
+            "e": {1, 9, 7},
+        }
+
+        assert expected_paths == list(paths)
+        assert expected_map == index_map
+
+    def test_one_node_one_loop_and_empty_graph(self):
+        G1 = nx.DiGraph([(0, 0)])
+        G2 = nx.DiGraph()
+        assert nx.graph_edit_distance(G1, G2) == 2
+
+    def test_one_node_two_loops_and_empty_graph(self):
+        G1 = nx.MultiDiGraph([(0, 0), (0, 0)])
+        assert nx.graph_edit_distance(G1, nx.DiGraph()) == 3
+        assert nx.graph_edit_distance(G1, nx.MultiDiGraph()) == 3
+
+    def test_two_directed_loops(self):
+        G = nx.DiGraph([(0, 0), (1, 1)])
+        assert nx.graph_edit_distance(G, nx.DiGraph()) == 4
+
+    def test_symmetry_with_custom_matching(self):
+        """G2 has edge (a,b) and G3 has edge (a,a) but node order for G2 is (a,b)
+        while for G3 it is (b,a)"""
+
+        a, b = "A", "B"
+        G2 = nx.Graph()
+        G2.add_nodes_from((a, b))
+        G2.add_edges_from([(a, b)])
+        G3 = nx.Graph()
+        G3.add_nodes_from((b, a))
+        G3.add_edges_from([(a, a)])
+        for G in (G2, G3):
+            for n in G:
+                G.nodes[n]["attr"] = n
+            for e in G.edges:
+                G.edges[e]["attr"] = e
+
+        def user_match(x, y):
+            return x == y
+
+        assert (
+            nx.graph_edit_distance(G2, G3, node_match=user_match, edge_match=user_match)
+            == 1
+        )
+        assert (
+            nx.graph_edit_distance(G3, G2, node_match=user_match, edge_match=user_match)
+            == 1
+        )
+
+    def test_panther_vector_similarity_basic(self):
+        """Basic test for panther_vector_similarity function."""
+        G = nx.Graph()
+        G.add_edge(0, 1)
+        G.add_edge(0, 2)
+        G.add_edge(0, 3)
+        G.add_edge(1, 2)
+        G.add_edge(2, 4)
+
+        sim = nx.panther_vector_similarity(G, 0, D=3, k=4, path_length=2, seed=42)
+
+        assert len(sim) > 0
+        assert 0 not in sim  # Source node should not be included
+        assert all(node in [1, 2, 3, 4] for node in sim)  # Only valid nodes
+        assert all(0 <= score <= 1 for score in sim.values())  # Valid scores
+
+    def test_panther_vector_similarity_unweighted(self):
+        """Test panther_vector_similarity with unweighted graph."""
+        G = nx.Graph()
+        G.add_edge(0, 1)
+        G.add_edge(0, 2)
+        G.add_edge(0, 3)
+        G.add_edge(1, 2)
+        G.add_edge(2, 4)
+
+        sim = nx.panther_vector_similarity(G, 0, D=3, k=4, path_length=2, seed=42)
+
+        assert len(sim) == 4
+        assert 0 not in sim
+        assert all(node in sim for node in [1, 2, 3, 4])
+        assert all(0 <= score <= 1 for score in sim.values())
+
+    def test_panther_vector_similarity_weighted(self):
+        """Test panther_vector_similarity with weighted graph."""
+        G = nx.Graph()
+        G.add_edge("v1", "v2", weight=5)
+        G.add_edge("v1", "v3", weight=1)
+        G.add_edge("v1", "v4", weight=2)
+        G.add_edge("v2", "v3", weight=0.1)
+        G.add_edge("v3", "v5", weight=1)
+
+        sim = nx.panther_vector_similarity(
+            G, "v1", D=3, k=4, path_length=2, weight="weight", seed=42
+        )
+
+        assert len(sim) == 4
+        assert "v1" not in sim
+        assert all(0 <= score <= 1 for score in sim.values())
+        assert all(node in sim for node in ["v2", "v3", "v4"])
+
+    def test_panther_vector_similarity_source_not_found(self):
+        """Test panther_vector_similarity with non-existent source node."""
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (0, 3), (1, 2), (2, 4)])
+
+        with pytest.raises(nx.NodeNotFound):
+            nx.panther_vector_similarity(G, source=10)
+
+    def test_panther_vector_similarity_isolated(self):
+        """Test panther_vector_similarity with isolated source node."""
+        G = nx.Graph()
+        G.add_nodes_from(range(5))
+        G.add_edge(0, 1)
+
+        with pytest.raises(nx.NetworkXUnfeasible):
+            nx.panther_vector_similarity(G, source=2)
+
+    def test_panther_vector_similarity_too_large_D(self):
+        """Test raises when D > number of nodes."""
+        G = nx.star_graph(3)
+
+        with pytest.raises(nx.NetworkXUnfeasible):
+            nx.panther_vector_similarity(G, 0, D=5, k=3)
+
+    def test_panther_vector_similarity_too_large_k(self):
+        """Test raises when k > number of nodes."""
+        G = nx.star_graph(3)
+
+        with pytest.raises(nx.NetworkXUnfeasible):
+            nx.panther_vector_similarity(G, 0, k=5)
+
+    def test_panther_vector_similarity_small_graph(self):
+        """Test panther_vector_similarity with a very small graph."""
+        G = nx.Graph()
+        G.add_edge(0, 1)
+
+        sim = nx.panther_vector_similarity(G, 0, D=2, k=2, seed=42)
+
+        assert len(sim) == 1
+        assert 1 in sim
+        assert sim[1] > 0
+
+    def test_panther_vector_similarity_deterministic(self):
+        """Test that results are deterministic with fixed seed."""
+        G = nx.Graph()
+        G.add_edges_from([(0, 1), (0, 2), (0, 3), (1, 2), (2, 4)])
+
+        sim1 = nx.panther_vector_similarity(G, 0, D=3, path_length=2, seed=42)
+
+        sim2 = nx.panther_vector_similarity(G, 0, D=3, path_length=2, seed=42)
+
+        assert sim1 == sim2
+
+    def test_panther_similarity_string_nodes(self):
+        """Test panther_similarity with string node names."""
+        pytest.importorskip("numpy")
+        G = nx.Graph()
+        G.add_edges_from([("A", "B"), ("A", "C"), ("A", "D"), ("B", "C")])
+
+        sim = nx.panther_similarity(G, "A", k=2, path_length=2, seed=42)
+
+        assert "A" not in sim  # Source node should not be included
+        assert all(isinstance(node, str) for node in sim)  # Nodes should remain strings
+
+    def test_panther_vector_similarity_string_nodes(self):
+        """Test panther_vector_similarity with string node names."""
+        pytest.importorskip("numpy")
+        G = nx.Graph()
+        G.add_edges_from([("A", "B"), ("A", "C"), ("A", "D"), ("B", "C")])
+
+        sim = nx.panther_vector_similarity(G, "A", D=3, k=2, path_length=2, seed=42)
+
+        assert "A" not in sim  # Source node should not be included
+        assert all(isinstance(node, str) for node in sim)  # Nodes should remain strings
+
+    def test_panther_similarity_k_parameter_returns_k_results(self):
+        pytest.importorskip("numpy")
+        G = nx.star_graph(100)
+
+        for k_val in [1, 2, 3, 4, 5, 10]:
+            result_panther = nx.panther_similarity(G, source=1, k=k_val, seed=42)
+            assert len(result_panther) == k_val, (
+                f"panther_similarity k={k_val} returned {len(result_panther)} results"
+            )
+            assert 1 not in result_panther, "Source node should not be in results"
+
+            result_vector = nx.panther_vector_similarity(G, source=1, k=k_val, seed=42)
+            assert len(result_vector) == k_val, (
+                f"panther_vector_similarity k={k_val} returned {len(result_vector)} results"
+            )
+            assert 1 not in result_vector, "Source node should not be in results"
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_simple_paths.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_simple_paths.py
new file mode 100644
index 0000000000000000000000000000000000000000..7855bbad27b896750faa932a74062aa2bc8ca143
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_simple_paths.py
@@ -0,0 +1,803 @@
+import random
+
+import pytest
+
+import networkx as nx
+from networkx import convert_node_labels_to_integers as cnlti
+from networkx.algorithms.simple_paths import (
+    _bidirectional_dijkstra,
+    _bidirectional_shortest_path,
+)
+from networkx.utils import arbitrary_element, pairwise
+
+
+class TestIsSimplePath:
+    """Unit tests for the
+    :func:`networkx.algorithms.simple_paths.is_simple_path` function.
+
+    """
+
+    def test_empty_list(self):
+        """Tests that the empty list is not a valid path, since there
+        should be a one-to-one correspondence between paths as lists of
+        nodes and paths as lists of edges.
+
+        """
+        G = nx.trivial_graph()
+        assert not nx.is_simple_path(G, [])
+
+    def test_trivial_path(self):
+        """Tests that the trivial path, a path of length one, is
+        considered a simple path in a graph.
+
+        """
+        G = nx.trivial_graph()
+        assert nx.is_simple_path(G, [0])
+
+    def test_trivial_nonpath(self):
+        """Tests that a list whose sole element is an object not in the
+        graph is not considered a simple path.
+
+        """
+        G = nx.trivial_graph()
+        assert not nx.is_simple_path(G, ["not a node"])
+
+    def test_simple_path(self):
+        G = nx.path_graph(2)
+        assert nx.is_simple_path(G, [0, 1])
+
+    def test_non_simple_path(self):
+        G = nx.path_graph(2)
+        assert not nx.is_simple_path(G, [0, 1, 0])
+
+    def test_cycle(self):
+        G = nx.cycle_graph(3)
+        assert not nx.is_simple_path(G, [0, 1, 2, 0])
+
+    def test_missing_node(self):
+        G = nx.path_graph(2)
+        assert not nx.is_simple_path(G, [0, 2])
+
+    def test_missing_starting_node(self):
+        G = nx.path_graph(2)
+        assert not nx.is_simple_path(G, [2, 0])
+
+    def test_directed_path(self):
+        G = nx.DiGraph([(0, 1), (1, 2)])
+        assert nx.is_simple_path(G, [0, 1, 2])
+
+    def test_directed_non_path(self):
+        G = nx.DiGraph([(0, 1), (1, 2)])
+        assert not nx.is_simple_path(G, [2, 1, 0])
+
+    def test_directed_cycle(self):
+        G = nx.DiGraph([(0, 1), (1, 2), (2, 0)])
+        assert not nx.is_simple_path(G, [0, 1, 2, 0])
+
+    def test_multigraph(self):
+        G = nx.MultiGraph([(0, 1), (0, 1)])
+        assert nx.is_simple_path(G, [0, 1])
+
+    def test_multidigraph(self):
+        G = nx.MultiDiGraph([(0, 1), (0, 1), (1, 0), (1, 0)])
+        assert nx.is_simple_path(G, [0, 1])
+
+
+# Tests for all_simple_paths
+def test_all_simple_paths():
+    G = nx.path_graph(4)
+    paths = nx.all_simple_paths(G, 0, 3)
+    assert {tuple(p) for p in paths} == {(0, 1, 2, 3)}
+
+
+def test_all_simple_paths_with_two_targets_emits_two_paths():
+    G = nx.path_graph(4)
+    G.add_edge(2, 4)
+    paths = nx.all_simple_paths(G, 0, [3, 4])
+    assert {tuple(p) for p in paths} == {(0, 1, 2, 3), (0, 1, 2, 4)}
+
+
+def test_digraph_all_simple_paths_with_two_targets_emits_two_paths():
+    G = nx.path_graph(4, create_using=nx.DiGraph())
+    G.add_edge(2, 4)
+    paths = nx.all_simple_paths(G, 0, [3, 4])
+    assert {tuple(p) for p in paths} == {(0, 1, 2, 3), (0, 1, 2, 4)}
+
+
+def test_all_simple_paths_with_two_targets_cutoff():
+    G = nx.path_graph(4)
+    G.add_edge(2, 4)
+    paths = nx.all_simple_paths(G, 0, [3, 4], cutoff=3)
+    assert {tuple(p) for p in paths} == {(0, 1, 2, 3), (0, 1, 2, 4)}
+
+
+def test_digraph_all_simple_paths_with_two_targets_cutoff():
+    G = nx.path_graph(4, create_using=nx.DiGraph())
+    G.add_edge(2, 4)
+    paths = nx.all_simple_paths(G, 0, [3, 4], cutoff=3)
+    assert {tuple(p) for p in paths} == {(0, 1, 2, 3), (0, 1, 2, 4)}
+
+
+def test_all_simple_paths_with_two_targets_in_line_emits_two_paths():
+    G = nx.path_graph(4)
+    paths = nx.all_simple_paths(G, 0, [2, 3])
+    assert {tuple(p) for p in paths} == {(0, 1, 2), (0, 1, 2, 3)}
+
+
+def test_all_simple_paths_ignores_cycle():
+    G = nx.cycle_graph(3, create_using=nx.DiGraph())
+    G.add_edge(1, 3)
+    paths = nx.all_simple_paths(G, 0, 3)
+    assert {tuple(p) for p in paths} == {(0, 1, 3)}
+
+
+def test_all_simple_paths_with_two_targets_inside_cycle_emits_two_paths():
+    G = nx.cycle_graph(3, create_using=nx.DiGraph())
+    G.add_edge(1, 3)
+    paths = nx.all_simple_paths(G, 0, [2, 3])
+    assert {tuple(p) for p in paths} == {(0, 1, 2), (0, 1, 3)}
+
+
+def test_all_simple_paths_source_target():
+    G = nx.path_graph(4)
+    assert list(nx.all_simple_paths(G, 1, 1)) == [[1]]
+
+
+def test_all_simple_paths_cutoff():
+    G = nx.complete_graph(4)
+    paths = nx.all_simple_paths(G, 0, 1, cutoff=1)
+    assert {tuple(p) for p in paths} == {(0, 1)}
+    paths = nx.all_simple_paths(G, 0, 1, cutoff=2)
+    assert {tuple(p) for p in paths} == {(0, 1), (0, 2, 1), (0, 3, 1)}
+
+
+def test_all_simple_paths_on_non_trivial_graph():
+    """you may need to draw this graph to make sure it is reasonable"""
+    G = nx.path_graph(5, create_using=nx.DiGraph())
+    G.add_edges_from([(0, 5), (1, 5), (1, 3), (5, 4), (4, 2), (4, 3)])
+    paths = nx.all_simple_paths(G, 1, [2, 3])
+    assert {tuple(p) for p in paths} == {
+        (1, 2),
+        (1, 3, 4, 2),
+        (1, 5, 4, 2),
+        (1, 3),
+        (1, 2, 3),
+        (1, 5, 4, 3),
+        (1, 5, 4, 2, 3),
+    }
+    paths = nx.all_simple_paths(G, 1, [2, 3], cutoff=3)
+    assert {tuple(p) for p in paths} == {
+        (1, 2),
+        (1, 3, 4, 2),
+        (1, 5, 4, 2),
+        (1, 3),
+        (1, 2, 3),
+        (1, 5, 4, 3),
+    }
+    paths = nx.all_simple_paths(G, 1, [2, 3], cutoff=2)
+    assert {tuple(p) for p in paths} == {(1, 2), (1, 3), (1, 2, 3)}
+
+
+def test_all_simple_paths_multigraph():
+    G = nx.MultiGraph([(1, 2), (1, 2)])
+    assert list(nx.all_simple_paths(G, 1, 1)) == [[1]]
+    nx.add_path(G, [3, 1, 10, 2])
+    paths = list(nx.all_simple_paths(G, 1, 2))
+    assert len(paths) == 3
+    assert {tuple(p) for p in paths} == {(1, 2), (1, 2), (1, 10, 2)}
+
+
+def test_all_simple_paths_multigraph_with_cutoff():
+    G = nx.MultiGraph([(1, 2), (1, 2), (1, 10), (10, 2)])
+    paths = list(nx.all_simple_paths(G, 1, 2, cutoff=1))
+    assert len(paths) == 2
+    assert {tuple(p) for p in paths} == {(1, 2), (1, 2)}
+
+    # See GitHub issue #6732.
+    G = nx.MultiGraph([(0, 1), (0, 2)])
+    assert list(nx.all_simple_paths(G, 0, {1, 2}, cutoff=1)) == [[0, 1], [0, 2]]
+
+
+def test_all_simple_paths_directed():
+    G = nx.DiGraph()
+    nx.add_path(G, [1, 2, 3])
+    nx.add_path(G, [3, 2, 1])
+    paths = nx.all_simple_paths(G, 1, 3)
+    assert {tuple(p) for p in paths} == {(1, 2, 3)}
+
+
+def test_all_simple_paths_empty():
+    G = nx.path_graph(4)
+    paths = nx.all_simple_paths(G, 0, 3, cutoff=2)
+    assert list(paths) == []
+
+
+def test_all_simple_paths_corner_cases():
+    assert list(nx.all_simple_paths(nx.empty_graph(2), 0, 0)) == [[0]]
+    assert list(nx.all_simple_paths(nx.empty_graph(2), 0, 1)) == []
+    assert list(nx.all_simple_paths(nx.path_graph(9), 0, 8, 0)) == []
+
+
+def test_all_simple_paths_source_in_targets():
+    # See GitHub issue #6690.
+    G = nx.path_graph(3)
+    assert list(nx.all_simple_paths(G, 0, {0, 1, 2})) == [[0], [0, 1], [0, 1, 2]]
+
+
+def hamiltonian_path(G, source):
+    source = arbitrary_element(G)
+    neighbors = set(G[source]) - {source}
+    n = len(G)
+    for target in neighbors:
+        for path in nx.all_simple_paths(G, source, target):
+            if len(path) == n:
+                yield path
+
+
+def test_hamiltonian_path():
+    from itertools import permutations
+
+    G = nx.complete_graph(4)
+    paths = [list(p) for p in hamiltonian_path(G, 0)]
+    exact = [[0] + list(p) for p in permutations([1, 2, 3], 3)]
+    assert sorted(paths) == sorted(exact)
+
+
+def test_cutoff_zero():
+    G = nx.complete_graph(4)
+    paths = nx.all_simple_paths(G, 0, 3, cutoff=0)
+    assert [list(p) for p in paths] == []
+    paths = nx.all_simple_paths(nx.MultiGraph(G), 0, 3, cutoff=0)
+    assert [list(p) for p in paths] == []
+
+
+def test_source_missing():
+    with pytest.raises(nx.NodeNotFound):
+        G = nx.Graph()
+        nx.add_path(G, [1, 2, 3])
+        list(nx.all_simple_paths(nx.MultiGraph(G), 0, 3))
+
+
+def test_target_missing():
+    with pytest.raises(nx.NodeNotFound):
+        G = nx.Graph()
+        nx.add_path(G, [1, 2, 3])
+        list(nx.all_simple_paths(nx.MultiGraph(G), 1, 4))
+
+
+# Tests for all_simple_edge_paths
+def test_all_simple_edge_paths():
+    G = nx.path_graph(4)
+    paths = nx.all_simple_edge_paths(G, 0, 3)
+    assert {tuple(p) for p in paths} == {((0, 1), (1, 2), (2, 3))}
+
+
+def test_all_simple_edge_paths_empty_path():
+    G = nx.empty_graph(1)
+    assert list(nx.all_simple_edge_paths(G, 0, 0)) == [[]]
+
+
+def test_all_simple_edge_paths_with_two_targets_emits_two_paths():
+    G = nx.path_graph(4)
+    G.add_edge(2, 4)
+    paths = nx.all_simple_edge_paths(G, 0, [3, 4])
+    assert {tuple(p) for p in paths} == {
+        ((0, 1), (1, 2), (2, 3)),
+        ((0, 1), (1, 2), (2, 4)),
+    }
+
+
+def test_digraph_all_simple_edge_paths_with_two_targets_emits_two_paths():
+    G = nx.path_graph(4, create_using=nx.DiGraph())
+    G.add_edge(2, 4)
+    paths = nx.all_simple_edge_paths(G, 0, [3, 4])
+    assert {tuple(p) for p in paths} == {
+        ((0, 1), (1, 2), (2, 3)),
+        ((0, 1), (1, 2), (2, 4)),
+    }
+
+
+def test_all_simple_edge_paths_with_two_targets_cutoff():
+    G = nx.path_graph(4)
+    G.add_edge(2, 4)
+    paths = nx.all_simple_edge_paths(G, 0, [3, 4], cutoff=3)
+    assert {tuple(p) for p in paths} == {
+        ((0, 1), (1, 2), (2, 3)),
+        ((0, 1), (1, 2), (2, 4)),
+    }
+
+
+def test_digraph_all_simple_edge_paths_with_two_targets_cutoff():
+    G = nx.path_graph(4, create_using=nx.DiGraph())
+    G.add_edge(2, 4)
+    paths = nx.all_simple_edge_paths(G, 0, [3, 4], cutoff=3)
+    assert {tuple(p) for p in paths} == {
+        ((0, 1), (1, 2), (2, 3)),
+        ((0, 1), (1, 2), (2, 4)),
+    }
+
+
+def test_all_simple_edge_paths_with_two_targets_in_line_emits_two_paths():
+    G = nx.path_graph(4)
+    paths = nx.all_simple_edge_paths(G, 0, [2, 3])
+    assert {tuple(p) for p in paths} == {((0, 1), (1, 2)), ((0, 1), (1, 2), (2, 3))}
+
+
+def test_all_simple_edge_paths_ignores_cycle():
+    G = nx.cycle_graph(3, create_using=nx.DiGraph())
+    G.add_edge(1, 3)
+    paths = nx.all_simple_edge_paths(G, 0, 3)
+    assert {tuple(p) for p in paths} == {((0, 1), (1, 3))}
+
+
+def test_all_simple_edge_paths_with_two_targets_inside_cycle_emits_two_paths():
+    G = nx.cycle_graph(3, create_using=nx.DiGraph())
+    G.add_edge(1, 3)
+    paths = nx.all_simple_edge_paths(G, 0, [2, 3])
+    assert {tuple(p) for p in paths} == {((0, 1), (1, 2)), ((0, 1), (1, 3))}
+
+
+def test_all_simple_edge_paths_source_target():
+    G = nx.path_graph(4)
+    paths = nx.all_simple_edge_paths(G, 1, 1)
+    assert list(paths) == [[]]
+
+
+def test_all_simple_edge_paths_cutoff():
+    G = nx.complete_graph(4)
+    paths = nx.all_simple_edge_paths(G, 0, 1, cutoff=1)
+    assert {tuple(p) for p in paths} == {((0, 1),)}
+    paths = nx.all_simple_edge_paths(G, 0, 1, cutoff=2)
+    assert {tuple(p) for p in paths} == {((0, 1),), ((0, 2), (2, 1)), ((0, 3), (3, 1))}
+
+
+def test_all_simple_edge_paths_on_non_trivial_graph():
+    """you may need to draw this graph to make sure it is reasonable"""
+    G = nx.path_graph(5, create_using=nx.DiGraph())
+    G.add_edges_from([(0, 5), (1, 5), (1, 3), (5, 4), (4, 2), (4, 3)])
+    paths = nx.all_simple_edge_paths(G, 1, [2, 3])
+    assert {tuple(p) for p in paths} == {
+        ((1, 2),),
+        ((1, 3), (3, 4), (4, 2)),
+        ((1, 5), (5, 4), (4, 2)),
+        ((1, 3),),
+        ((1, 2), (2, 3)),
+        ((1, 5), (5, 4), (4, 3)),
+        ((1, 5), (5, 4), (4, 2), (2, 3)),
+    }
+    paths = nx.all_simple_edge_paths(G, 1, [2, 3], cutoff=3)
+    assert {tuple(p) for p in paths} == {
+        ((1, 2),),
+        ((1, 3), (3, 4), (4, 2)),
+        ((1, 5), (5, 4), (4, 2)),
+        ((1, 3),),
+        ((1, 2), (2, 3)),
+        ((1, 5), (5, 4), (4, 3)),
+    }
+    paths = nx.all_simple_edge_paths(G, 1, [2, 3], cutoff=2)
+    assert {tuple(p) for p in paths} == {((1, 2),), ((1, 3),), ((1, 2), (2, 3))}
+
+
+def test_all_simple_edge_paths_multigraph():
+    G = nx.MultiGraph([(1, 2), (1, 2)])
+    paths = nx.all_simple_edge_paths(G, 1, 1)
+    assert list(paths) == [[]]
+    nx.add_path(G, [3, 1, 10, 2])
+    paths = list(nx.all_simple_edge_paths(G, 1, 2))
+    assert len(paths) == 3
+    assert {tuple(p) for p in paths} == {
+        ((1, 2, 0),),
+        ((1, 2, 1),),
+        ((1, 10, 0), (10, 2, 0)),
+    }
+
+
+def test_all_simple_edge_paths_multigraph_with_cutoff():
+    G = nx.MultiGraph([(1, 2), (1, 2), (1, 10), (10, 2)])
+    paths = list(nx.all_simple_edge_paths(G, 1, 2, cutoff=1))
+    assert len(paths) == 2
+    assert {tuple(p) for p in paths} == {((1, 2, 0),), ((1, 2, 1),)}
+
+
+def test_all_simple_edge_paths_directed():
+    G = nx.DiGraph()
+    nx.add_path(G, [1, 2, 3])
+    nx.add_path(G, [3, 2, 1])
+    paths = nx.all_simple_edge_paths(G, 1, 3)
+    assert {tuple(p) for p in paths} == {((1, 2), (2, 3))}
+
+
+def test_all_simple_edge_paths_empty():
+    G = nx.path_graph(4)
+    paths = nx.all_simple_edge_paths(G, 0, 3, cutoff=2)
+    assert list(paths) == []
+
+
+def test_all_simple_edge_paths_corner_cases():
+    assert list(nx.all_simple_edge_paths(nx.empty_graph(2), 0, 0)) == [[]]
+    assert list(nx.all_simple_edge_paths(nx.empty_graph(2), 0, 1)) == []
+    assert list(nx.all_simple_edge_paths(nx.path_graph(9), 0, 8, 0)) == []
+
+
+def test_all_simple_edge_paths_ignores_self_loop():
+    G = nx.Graph([(0, 0), (0, 1), (1, 1), (1, 2)])
+    assert list(nx.all_simple_edge_paths(G, 0, 2)) == [[(0, 1), (1, 2)]]
+
+
+def hamiltonian_edge_path(G, source):
+    source = arbitrary_element(G)
+    neighbors = set(G[source]) - {source}
+    n = len(G)
+    for target in neighbors:
+        for path in nx.all_simple_edge_paths(G, source, target):
+            if len(path) == n - 1:
+                yield path
+
+
+def test_hamiltonian__edge_path():
+    from itertools import permutations
+
+    G = nx.complete_graph(4)
+    paths = hamiltonian_edge_path(G, 0)
+    exact = [list(pairwise([0] + list(p))) for p in permutations([1, 2, 3], 3)]
+    assert sorted(exact) == sorted(paths)
+
+
+def test_edge_cutoff_zero():
+    G = nx.complete_graph(4)
+    paths = nx.all_simple_edge_paths(G, 0, 3, cutoff=0)
+    assert [list(p) for p in paths] == []
+    paths = nx.all_simple_edge_paths(nx.MultiGraph(G), 0, 3, cutoff=0)
+    assert [list(p) for p in paths] == []
+
+
+def test_edge_source_missing():
+    with pytest.raises(nx.NodeNotFound):
+        G = nx.Graph()
+        nx.add_path(G, [1, 2, 3])
+        list(nx.all_simple_edge_paths(nx.MultiGraph(G), 0, 3))
+
+
+def test_edge_target_missing():
+    with pytest.raises(nx.NodeNotFound):
+        G = nx.Graph()
+        nx.add_path(G, [1, 2, 3])
+        list(nx.all_simple_edge_paths(nx.MultiGraph(G), 1, 4))
+
+
+# Tests for shortest_simple_paths
+def test_shortest_simple_paths():
+    G = cnlti(nx.grid_2d_graph(4, 4), first_label=1, ordering="sorted")
+    paths = nx.shortest_simple_paths(G, 1, 12)
+    assert next(paths) == [1, 2, 3, 4, 8, 12]
+    assert next(paths) == [1, 5, 6, 7, 8, 12]
+    assert [len(path) for path in nx.shortest_simple_paths(G, 1, 12)] == sorted(
+        len(path) for path in nx.all_simple_paths(G, 1, 12)
+    )
+
+
+def test_shortest_simple_paths_singleton_path():
+    G = nx.empty_graph(3)
+    assert list(nx.shortest_simple_paths(G, 0, 0)) == [[0]]
+
+
+def test_shortest_simple_paths_directed():
+    G = nx.cycle_graph(7, create_using=nx.DiGraph())
+    paths = nx.shortest_simple_paths(G, 0, 3)
+    assert list(paths) == [[0, 1, 2, 3]]
+
+
+def test_shortest_simple_paths_directed_with_weight_function():
+    def cost(u, v, x):
+        return 1
+
+    G = cnlti(nx.grid_2d_graph(4, 4), first_label=1, ordering="sorted")
+    paths = nx.shortest_simple_paths(G, 1, 12)
+    assert next(paths) == [1, 2, 3, 4, 8, 12]
+    assert next(paths) == [1, 5, 6, 7, 8, 12]
+    assert [
+        len(path) for path in nx.shortest_simple_paths(G, 1, 12, weight=cost)
+    ] == sorted(len(path) for path in nx.all_simple_paths(G, 1, 12))
+
+
+def test_shortest_simple_paths_with_weight_function():
+    def cost(u, v, x):
+        return 1
+
+    G = nx.cycle_graph(7, create_using=nx.DiGraph())
+    paths = nx.shortest_simple_paths(G, 0, 3, weight=cost)
+    assert list(paths) == [[0, 1, 2, 3]]
+
+
+def test_shortest_simple_paths_with_none_weight_function():
+    def cost(u, v, x):
+        delta = abs(u - v)
+        # ignore interior edges
+        return 1 if (delta == 1 or delta == 4) else None
+
+    G = nx.complete_graph(5)
+    paths = nx.shortest_simple_paths(G, 0, 2, weight=cost)
+    assert list(paths) == [[0, 1, 2], [0, 4, 3, 2]]
+
+
+def test_Greg_Bernstein():
+    g1 = nx.Graph()
+    g1.add_nodes_from(["N0", "N1", "N2", "N3", "N4"])
+    g1.add_edge("N4", "N1", weight=10.0, capacity=50, name="L5")
+    g1.add_edge("N4", "N0", weight=7.0, capacity=40, name="L4")
+    g1.add_edge("N0", "N1", weight=10.0, capacity=45, name="L1")
+    g1.add_edge("N3", "N0", weight=10.0, capacity=50, name="L0")
+    g1.add_edge("N2", "N3", weight=12.0, capacity=30, name="L2")
+    g1.add_edge("N1", "N2", weight=15.0, capacity=42, name="L3")
+    solution = [["N1", "N0", "N3"], ["N1", "N2", "N3"], ["N1", "N4", "N0", "N3"]]
+    result = list(nx.shortest_simple_paths(g1, "N1", "N3", weight="weight"))
+    assert result == solution
+
+
+def test_weighted_shortest_simple_path():
+    def cost_func(path):
+        return sum(G.adj[u][v]["weight"] for (u, v) in zip(path, path[1:]))
+
+    G = nx.complete_graph(5)
+    weight = {(u, v): random.randint(1, 100) for (u, v) in G.edges()}
+    nx.set_edge_attributes(G, weight, "weight")
+    cost = 0
+    for path in nx.shortest_simple_paths(G, 0, 3, weight="weight"):
+        this_cost = cost_func(path)
+        assert cost <= this_cost
+        cost = this_cost
+
+
+def test_directed_weighted_shortest_simple_path():
+    def cost_func(path):
+        return sum(G.adj[u][v]["weight"] for (u, v) in zip(path, path[1:]))
+
+    G = nx.complete_graph(5)
+    G = G.to_directed()
+    weight = {(u, v): random.randint(1, 100) for (u, v) in G.edges()}
+    nx.set_edge_attributes(G, weight, "weight")
+    cost = 0
+    for path in nx.shortest_simple_paths(G, 0, 3, weight="weight"):
+        this_cost = cost_func(path)
+        assert cost <= this_cost
+        cost = this_cost
+
+
+def test_weighted_shortest_simple_path_issue2427():
+    G = nx.Graph()
+    G.add_edge("IN", "OUT", weight=2)
+    G.add_edge("IN", "A", weight=1)
+    G.add_edge("IN", "B", weight=2)
+    G.add_edge("B", "OUT", weight=2)
+    assert list(nx.shortest_simple_paths(G, "IN", "OUT", weight="weight")) == [
+        ["IN", "OUT"],
+        ["IN", "B", "OUT"],
+    ]
+    G = nx.Graph()
+    G.add_edge("IN", "OUT", weight=10)
+    G.add_edge("IN", "A", weight=1)
+    G.add_edge("IN", "B", weight=1)
+    G.add_edge("B", "OUT", weight=1)
+    assert list(nx.shortest_simple_paths(G, "IN", "OUT", weight="weight")) == [
+        ["IN", "B", "OUT"],
+        ["IN", "OUT"],
+    ]
+
+
+def test_directed_weighted_shortest_simple_path_issue2427():
+    G = nx.DiGraph()
+    G.add_edge("IN", "OUT", weight=2)
+    G.add_edge("IN", "A", weight=1)
+    G.add_edge("IN", "B", weight=2)
+    G.add_edge("B", "OUT", weight=2)
+    assert list(nx.shortest_simple_paths(G, "IN", "OUT", weight="weight")) == [
+        ["IN", "OUT"],
+        ["IN", "B", "OUT"],
+    ]
+    G = nx.DiGraph()
+    G.add_edge("IN", "OUT", weight=10)
+    G.add_edge("IN", "A", weight=1)
+    G.add_edge("IN", "B", weight=1)
+    G.add_edge("B", "OUT", weight=1)
+    assert list(nx.shortest_simple_paths(G, "IN", "OUT", weight="weight")) == [
+        ["IN", "B", "OUT"],
+        ["IN", "OUT"],
+    ]
+
+
+def test_weight_name():
+    G = nx.cycle_graph(7)
+    nx.set_edge_attributes(G, 1, "weight")
+    nx.set_edge_attributes(G, 1, "foo")
+    G.adj[1][2]["foo"] = 7
+    paths = list(nx.shortest_simple_paths(G, 0, 3, weight="foo"))
+    solution = [[0, 6, 5, 4, 3], [0, 1, 2, 3]]
+    assert paths == solution
+
+
+def test_ssp_source_missing():
+    with pytest.raises(nx.NodeNotFound):
+        G = nx.Graph()
+        nx.add_path(G, [1, 2, 3])
+        list(nx.shortest_simple_paths(G, 0, 3))
+
+
+def test_ssp_target_missing():
+    with pytest.raises(nx.NodeNotFound):
+        G = nx.Graph()
+        nx.add_path(G, [1, 2, 3])
+        list(nx.shortest_simple_paths(G, 1, 4))
+
+
+def test_ssp_multigraph():
+    with pytest.raises(nx.NetworkXNotImplemented):
+        G = nx.MultiGraph()
+        nx.add_path(G, [1, 2, 3])
+        list(nx.shortest_simple_paths(G, 1, 4))
+
+
+def test_ssp_source_missing2():
+    with pytest.raises(nx.NetworkXNoPath):
+        G = nx.Graph()
+        nx.add_path(G, [0, 1, 2])
+        nx.add_path(G, [3, 4, 5])
+        list(nx.shortest_simple_paths(G, 0, 3))
+
+
+def test_bidirectional_shortest_path_restricted_cycle():
+    cycle = nx.cycle_graph(7)
+    length, path = _bidirectional_shortest_path(cycle, 0, 3)
+    assert path == [0, 1, 2, 3]
+    length, path = _bidirectional_shortest_path(cycle, 0, 3, ignore_nodes=[1])
+    assert path == [0, 6, 5, 4, 3]
+
+
+def test_bidirectional_shortest_path_restricted_wheel():
+    wheel = nx.wheel_graph(6)
+    length, path = _bidirectional_shortest_path(wheel, 1, 3)
+    assert path in [[1, 0, 3], [1, 2, 3]]
+    length, path = _bidirectional_shortest_path(wheel, 1, 3, ignore_nodes=[0])
+    assert path == [1, 2, 3]
+    length, path = _bidirectional_shortest_path(wheel, 1, 3, ignore_nodes=[0, 2])
+    assert path == [1, 5, 4, 3]
+    length, path = _bidirectional_shortest_path(
+        wheel, 1, 3, ignore_edges=[(1, 0), (5, 0), (2, 3)]
+    )
+    assert path in [[1, 2, 0, 3], [1, 5, 4, 3]]
+
+
+def test_bidirectional_shortest_path_restricted_directed_cycle():
+    directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph())
+    length, path = _bidirectional_shortest_path(directed_cycle, 0, 3)
+    assert path == [0, 1, 2, 3]
+    pytest.raises(
+        nx.NetworkXNoPath,
+        _bidirectional_shortest_path,
+        directed_cycle,
+        0,
+        3,
+        ignore_nodes=[1],
+    )
+    length, path = _bidirectional_shortest_path(
+        directed_cycle, 0, 3, ignore_edges=[(2, 1)]
+    )
+    assert path == [0, 1, 2, 3]
+    pytest.raises(
+        nx.NetworkXNoPath,
+        _bidirectional_shortest_path,
+        directed_cycle,
+        0,
+        3,
+        ignore_edges=[(1, 2)],
+    )
+
+
+def test_bidirectional_shortest_path_ignore():
+    G = nx.Graph()
+    nx.add_path(G, [1, 2])
+    nx.add_path(G, [1, 3])
+    nx.add_path(G, [1, 4])
+    pytest.raises(
+        nx.NetworkXNoPath, _bidirectional_shortest_path, G, 1, 2, ignore_nodes=[1]
+    )
+    pytest.raises(
+        nx.NetworkXNoPath, _bidirectional_shortest_path, G, 1, 2, ignore_nodes=[2]
+    )
+    G = nx.Graph()
+    nx.add_path(G, [1, 3])
+    nx.add_path(G, [1, 4])
+    nx.add_path(G, [3, 2])
+    pytest.raises(
+        nx.NetworkXNoPath, _bidirectional_shortest_path, G, 1, 2, ignore_nodes=[1, 2]
+    )
+
+
+def validate_path(G, s, t, soln_len, path):
+    assert path[0] == s
+    assert path[-1] == t
+    assert soln_len == sum(
+        G[u][v].get("weight", 1) for u, v in zip(path[:-1], path[1:])
+    )
+
+
+def validate_length_path(G, s, t, soln_len, length, path):
+    assert soln_len == length
+    validate_path(G, s, t, length, path)
+
+
+def test_bidirectional_dijkstra_restricted():
+    XG = nx.DiGraph()
+    XG.add_weighted_edges_from(
+        [
+            ("s", "u", 10),
+            ("s", "x", 5),
+            ("u", "v", 1),
+            ("u", "x", 2),
+            ("v", "y", 1),
+            ("x", "u", 3),
+            ("x", "v", 5),
+            ("x", "y", 2),
+            ("y", "s", 7),
+            ("y", "v", 6),
+        ]
+    )
+
+    XG3 = nx.Graph()
+    XG3.add_weighted_edges_from(
+        [[0, 1, 2], [1, 2, 12], [2, 3, 1], [3, 4, 5], [4, 5, 1], [5, 0, 10]]
+    )
+    validate_length_path(XG, "s", "v", 9, *_bidirectional_dijkstra(XG, "s", "v"))
+    validate_length_path(
+        XG, "s", "v", 10, *_bidirectional_dijkstra(XG, "s", "v", ignore_nodes=["u"])
+    )
+    validate_length_path(
+        XG,
+        "s",
+        "v",
+        11,
+        *_bidirectional_dijkstra(XG, "s", "v", ignore_edges=[("s", "x")]),
+    )
+    pytest.raises(
+        nx.NetworkXNoPath,
+        _bidirectional_dijkstra,
+        XG,
+        "s",
+        "v",
+        ignore_nodes=["u"],
+        ignore_edges=[("s", "x")],
+    )
+    validate_length_path(XG3, 0, 3, 15, *_bidirectional_dijkstra(XG3, 0, 3))
+    validate_length_path(
+        XG3, 0, 3, 16, *_bidirectional_dijkstra(XG3, 0, 3, ignore_nodes=[1])
+    )
+    validate_length_path(
+        XG3, 0, 3, 16, *_bidirectional_dijkstra(XG3, 0, 3, ignore_edges=[(2, 3)])
+    )
+    pytest.raises(
+        nx.NetworkXNoPath,
+        _bidirectional_dijkstra,
+        XG3,
+        0,
+        3,
+        ignore_nodes=[1],
+        ignore_edges=[(5, 4)],
+    )
+
+
+def test_bidirectional_dijkstra_no_path():
+    with pytest.raises(nx.NetworkXNoPath):
+        G = nx.Graph()
+        nx.add_path(G, [1, 2, 3])
+        nx.add_path(G, [4, 5, 6])
+        _bidirectional_dijkstra(G, 1, 6)
+
+
+def test_bidirectional_dijkstra_ignore():
+    G = nx.Graph()
+    nx.add_path(G, [1, 2, 10])
+    nx.add_path(G, [1, 3, 10])
+    pytest.raises(nx.NetworkXNoPath, _bidirectional_dijkstra, G, 1, 2, ignore_nodes=[1])
+    pytest.raises(nx.NetworkXNoPath, _bidirectional_dijkstra, G, 1, 2, ignore_nodes=[2])
+    pytest.raises(
+        nx.NetworkXNoPath, _bidirectional_dijkstra, G, 1, 2, ignore_nodes=[1, 2]
+    )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_smallworld.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_smallworld.py
new file mode 100644
index 0000000000000000000000000000000000000000..c8e454293b4325a5c7557480182b1e1271a1118e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_smallworld.py
@@ -0,0 +1,76 @@
+import pytest
+
+pytest.importorskip("numpy")
+
+import networkx as nx
+from networkx import lattice_reference, omega, random_reference, sigma
+
+rng = 42
+
+
+def test_random_reference():
+    G = nx.connected_watts_strogatz_graph(50, 6, 0.1, seed=rng)
+    Gr = random_reference(G, niter=1, seed=rng)
+    C = nx.average_clustering(G)
+    Cr = nx.average_clustering(Gr)
+    assert C > Cr
+
+    with pytest.raises(nx.NetworkXError):
+        next(random_reference(nx.Graph()))
+    with pytest.raises(nx.NetworkXNotImplemented):
+        next(random_reference(nx.DiGraph()))
+
+    H = nx.Graph(((0, 1), (2, 3)))
+    Hl = random_reference(H, niter=1, seed=rng)
+
+
+def test_lattice_reference():
+    G = nx.connected_watts_strogatz_graph(50, 6, 1, seed=rng)
+    Gl = lattice_reference(G, niter=1, seed=rng)
+    L = nx.average_shortest_path_length(G)
+    Ll = nx.average_shortest_path_length(Gl)
+    assert Ll > L
+
+    pytest.raises(nx.NetworkXError, lattice_reference, nx.Graph())
+    pytest.raises(nx.NetworkXNotImplemented, lattice_reference, nx.DiGraph())
+
+    H = nx.Graph(((0, 1), (2, 3)))
+    Hl = lattice_reference(H, niter=1)
+
+
+def test_sigma():
+    Gs = nx.connected_watts_strogatz_graph(50, 6, 0.1, seed=rng)
+    Gr = nx.connected_watts_strogatz_graph(50, 6, 1, seed=rng)
+    sigmas = sigma(Gs, niter=1, nrand=2, seed=rng)
+    sigmar = sigma(Gr, niter=1, nrand=2, seed=rng)
+    assert sigmar < sigmas
+
+
+def test_omega():
+    Gl = nx.connected_watts_strogatz_graph(50, 6, 0, seed=rng)
+    Gr = nx.connected_watts_strogatz_graph(50, 6, 1, seed=rng)
+    Gs = nx.connected_watts_strogatz_graph(50, 6, 0.1, seed=rng)
+    omegal = omega(Gl, niter=1, nrand=1, seed=rng)
+    omegar = omega(Gr, niter=1, nrand=1, seed=rng)
+    omegas = omega(Gs, niter=1, nrand=1, seed=rng)
+    assert omegal < omegas and omegas < omegar
+
+    # Test that omega lies within the [-1, 1] bounds
+    G_barbell = nx.barbell_graph(5, 1)
+    G_karate = nx.karate_club_graph()
+
+    omega_barbell = nx.omega(G_barbell)
+    omega_karate = nx.omega(G_karate, nrand=2)
+
+    omegas = (omegal, omegar, omegas, omega_barbell, omega_karate)
+
+    for o in omegas:
+        assert -1 <= o <= 1
+
+
+@pytest.mark.parametrize("f", (nx.random_reference, nx.lattice_reference))
+def test_graph_no_edges(f):
+    G = nx.Graph()
+    G.add_nodes_from([0, 1, 2, 3])
+    with pytest.raises(nx.NetworkXError, match="Graph has fewer that 2 edges"):
+        f(G)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_smetric.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_smetric.py
new file mode 100644
index 0000000000000000000000000000000000000000..528dbc8d69bf5dca221c17cd16118cf3ba01a2a9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_smetric.py
@@ -0,0 +1,8 @@
+import pytest
+
+import networkx as nx
+
+
+def test_smetric():
+    G = nx.Graph([(1, 2), (2, 3), (2, 4), (1, 4)])
+    assert nx.s_metric(G) == 19.0
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_sparsifiers.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_sparsifiers.py
new file mode 100644
index 0000000000000000000000000000000000000000..e8604e61ae45aca9092226a793a02b082b126738
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_sparsifiers.py
@@ -0,0 +1,138 @@
+"""Unit tests for the sparsifier computation functions."""
+
+import pytest
+
+import networkx as nx
+from networkx.utils import py_random_state
+
+_seed = 2
+
+
+def _test_spanner(G, spanner, stretch, weight=None):
+    """Test whether a spanner is valid.
+
+    This function tests whether the given spanner is a subgraph of the
+    given graph G with the same node set. It also tests for all shortest
+    paths whether they adhere to the given stretch.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        The original graph for which the spanner was constructed.
+
+    spanner : NetworkX graph
+        The spanner to be tested.
+
+    stretch : float
+        The proclaimed stretch of the spanner.
+
+    weight : object
+        The edge attribute to use as distance.
+    """
+    # check node set
+    assert set(G.nodes()) == set(spanner.nodes())
+
+    # check edge set and weights
+    for u, v in spanner.edges():
+        assert G.has_edge(u, v)
+        if weight:
+            assert spanner[u][v][weight] == G[u][v][weight]
+
+    # check connectivity and stretch
+    original_length = dict(nx.shortest_path_length(G, weight=weight))
+    spanner_length = dict(nx.shortest_path_length(spanner, weight=weight))
+    for u in G.nodes():
+        for v in G.nodes():
+            if u in original_length and v in original_length[u]:
+                assert spanner_length[u][v] <= stretch * original_length[u][v]
+
+
+@py_random_state(1)
+def _assign_random_weights(G, seed=None):
+    """Assigns random weights to the edges of a graph.
+
+    Parameters
+    ----------
+
+    G : NetworkX graph
+        The original graph for which the spanner was constructed.
+
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    """
+    for u, v in G.edges():
+        G[u][v]["weight"] = seed.random()
+
+
+def test_spanner_trivial():
+    """Test a trivial spanner with stretch 1."""
+    G = nx.complete_graph(20)
+    spanner = nx.spanner(G, 1, seed=_seed)
+
+    for u, v in G.edges:
+        assert spanner.has_edge(u, v)
+
+
+def test_spanner_unweighted_complete_graph():
+    """Test spanner construction on a complete unweighted graph."""
+    G = nx.complete_graph(20)
+
+    spanner = nx.spanner(G, 4, seed=_seed)
+    _test_spanner(G, spanner, 4)
+
+    spanner = nx.spanner(G, 10, seed=_seed)
+    _test_spanner(G, spanner, 10)
+
+
+def test_spanner_weighted_complete_graph():
+    """Test spanner construction on a complete weighted graph."""
+    G = nx.complete_graph(20)
+    _assign_random_weights(G, seed=_seed)
+
+    spanner = nx.spanner(G, 4, weight="weight", seed=_seed)
+    _test_spanner(G, spanner, 4, weight="weight")
+
+    spanner = nx.spanner(G, 10, weight="weight", seed=_seed)
+    _test_spanner(G, spanner, 10, weight="weight")
+
+
+def test_spanner_unweighted_gnp_graph():
+    """Test spanner construction on an unweighted gnp graph."""
+    G = nx.gnp_random_graph(20, 0.4, seed=_seed)
+
+    spanner = nx.spanner(G, 4, seed=_seed)
+    _test_spanner(G, spanner, 4)
+
+    spanner = nx.spanner(G, 10, seed=_seed)
+    _test_spanner(G, spanner, 10)
+
+
+def test_spanner_weighted_gnp_graph():
+    """Test spanner construction on an weighted gnp graph."""
+    G = nx.gnp_random_graph(20, 0.4, seed=_seed)
+    _assign_random_weights(G, seed=_seed)
+
+    spanner = nx.spanner(G, 4, weight="weight", seed=_seed)
+    _test_spanner(G, spanner, 4, weight="weight")
+
+    spanner = nx.spanner(G, 10, weight="weight", seed=_seed)
+    _test_spanner(G, spanner, 10, weight="weight")
+
+
+def test_spanner_unweighted_disconnected_graph():
+    """Test spanner construction on a disconnected graph."""
+    G = nx.disjoint_union(nx.complete_graph(10), nx.complete_graph(10))
+
+    spanner = nx.spanner(G, 4, seed=_seed)
+    _test_spanner(G, spanner, 4)
+
+    spanner = nx.spanner(G, 10, seed=_seed)
+    _test_spanner(G, spanner, 10)
+
+
+def test_spanner_invalid_stretch():
+    """Check whether an invalid stretch is caught."""
+    with pytest.raises(ValueError):
+        G = nx.empty_graph()
+        nx.spanner(G, 0)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_structuralholes.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_structuralholes.py
new file mode 100644
index 0000000000000000000000000000000000000000..d0f53cd14e2bb4459197416932d3e297d4bde0f7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_structuralholes.py
@@ -0,0 +1,191 @@
+"""Unit tests for the :mod:`networkx.algorithms.structuralholes` module."""
+
+import math
+
+import pytest
+
+import networkx as nx
+from networkx.classes.tests import dispatch_interface
+
+
+class TestStructuralHolesNoScipy:
+    """Unit tests for computing measures of structural holes.
+
+    The expected values for these functions were originally computed using the
+    proprietary software `UCINET`_ and the free software `IGraph`_ , and then
+    computed by hand to make sure that the results are correct.
+
+    .. _UCINET: https://sites.google.com/site/ucinetsoftware/home
+    .. _IGraph: http://igraph.org/
+
+    """
+
+    def setup_method(self):
+        self.D = nx.DiGraph()
+        self.D.add_edges_from([(0, 1), (0, 2), (1, 0), (2, 1)])
+        self.D_weights = {(0, 1): 2, (0, 2): 2, (1, 0): 1, (2, 1): 1}
+        # Example from http://www.analytictech.com/connections/v20(1)/holes.htm
+        self.G = nx.Graph()
+        self.G.add_edges_from(
+            [
+                ("A", "B"),
+                ("A", "F"),
+                ("A", "G"),
+                ("A", "E"),
+                ("E", "G"),
+                ("F", "G"),
+                ("B", "G"),
+                ("B", "D"),
+                ("D", "G"),
+                ("G", "C"),
+            ]
+        )
+        self.G_weights = {
+            ("A", "B"): 2,
+            ("A", "F"): 3,
+            ("A", "G"): 5,
+            ("A", "E"): 2,
+            ("E", "G"): 8,
+            ("F", "G"): 3,
+            ("B", "G"): 4,
+            ("B", "D"): 1,
+            ("D", "G"): 3,
+            ("G", "C"): 10,
+        }
+        self.Dnodes = list(self.D)
+        self.Gnodes = list(self.G)
+
+    def test_constraint_directed(self):
+        constraint = nx.constraint(self.D, nodes=self.Dnodes)
+        assert constraint[0] == pytest.approx(1.003, abs=1e-3)
+        assert constraint[1] == pytest.approx(1.003, abs=1e-3)
+        assert constraint[2] == pytest.approx(1.389, abs=1e-3)
+
+    def test_effective_size_directed(self):
+        effective_size = nx.effective_size(self.D, nodes=self.Dnodes)
+        assert effective_size[0] == pytest.approx(1.167, abs=1e-3)
+        assert effective_size[1] == pytest.approx(1.167, abs=1e-3)
+        assert effective_size[2] == pytest.approx(1, abs=1e-3)
+
+    def test_constraint_weighted_directed(self):
+        D = self.D.copy()
+        nx.set_edge_attributes(D, self.D_weights, "weight")
+        constraint = nx.constraint(D, weight="weight", nodes=self.Dnodes)
+        assert constraint[0] == pytest.approx(0.840, abs=1e-3)
+        assert constraint[1] == pytest.approx(1.143, abs=1e-3)
+        assert constraint[2] == pytest.approx(1.378, abs=1e-3)
+
+    def test_effective_size_weighted_directed(self):
+        D = self.D.copy()
+        nx.set_edge_attributes(D, self.D_weights, "weight")
+        effective_size = nx.effective_size(D, weight="weight", nodes=self.Dnodes)
+        assert effective_size[0] == pytest.approx(1.567, abs=1e-3)
+        assert effective_size[1] == pytest.approx(1.083, abs=1e-3)
+        assert effective_size[2] == pytest.approx(1, abs=1e-3)
+
+    def test_constraint_undirected(self):
+        constraint = nx.constraint(self.G, nodes=self.Gnodes)
+        assert constraint["G"] == pytest.approx(0.400, abs=1e-3)
+        assert constraint["A"] == pytest.approx(0.595, abs=1e-3)
+        assert constraint["C"] == pytest.approx(1, abs=1e-3)
+
+    def test_effective_size_undirected_borgatti(self):
+        effective_size = nx.effective_size(self.G, nodes=self.Gnodes)
+        assert effective_size["G"] == pytest.approx(4.67, abs=1e-2)
+        assert effective_size["A"] == pytest.approx(2.50, abs=1e-2)
+        assert effective_size["C"] == pytest.approx(1, abs=1e-2)
+
+    def test_effective_size_undirected(self):
+        G = self.G.copy()
+        nx.set_edge_attributes(G, 1, "weight")
+        effective_size = nx.effective_size(G, weight="weight", nodes=self.Gnodes)
+        assert effective_size["G"] == pytest.approx(4.67, abs=1e-2)
+        assert effective_size["A"] == pytest.approx(2.50, abs=1e-2)
+        assert effective_size["C"] == pytest.approx(1, abs=1e-2)
+
+    def test_constraint_weighted_undirected(self):
+        G = self.G.copy()
+        nx.set_edge_attributes(G, self.G_weights, "weight")
+        constraint = nx.constraint(G, weight="weight", nodes=self.Gnodes)
+        assert constraint["G"] == pytest.approx(0.299, abs=1e-3)
+        assert constraint["A"] == pytest.approx(0.795, abs=1e-3)
+        assert constraint["C"] == pytest.approx(1, abs=1e-3)
+
+    def test_effective_size_weighted_undirected(self):
+        G = self.G.copy()
+        nx.set_edge_attributes(G, self.G_weights, "weight")
+        effective_size = nx.effective_size(G, weight="weight", nodes=self.Gnodes)
+        assert effective_size["G"] == pytest.approx(5.47, abs=1e-2)
+        assert effective_size["A"] == pytest.approx(2.47, abs=1e-2)
+        assert effective_size["C"] == pytest.approx(1, abs=1e-2)
+
+    def test_constraint_isolated(self):
+        G = self.G.copy()
+        G.add_node(1)
+        constraint = nx.constraint(G, nodes=self.Gnodes + [1])
+        assert math.isnan(constraint[1])
+
+    def test_effective_size_isolated(self):
+        G = self.G.copy()
+        G.add_node(1)
+        nx.set_edge_attributes(G, self.G_weights, "weight")
+        effective_size = nx.effective_size(G, weight="weight", nodes=self.Gnodes + [1])
+        assert math.isnan(effective_size[1])
+
+    def test_effective_size_borgatti_isolated(self):
+        G = self.G.copy()
+        G.add_node(1)
+        effective_size = nx.effective_size(G, nodes=self.Gnodes + [1])
+        assert math.isnan(effective_size[1])
+
+
+class TestStructuralHoles(TestStructuralHolesNoScipy):
+    pytest.importorskip("scipy")
+    Dnodes = None
+    Gnodes = None
+
+
+@pytest.mark.parametrize("graph", (nx.Graph, nx.DiGraph))
+@pytest.mark.parametrize("nodes", (None, [0]))
+def test_effective_size_isolated_node_with_selfloop(graph, nodes):
+    """Behavior consistent with isolated node without self-loop. See gh-6916"""
+    G = graph([(0, 0)])  # Single node with one self-edge
+    assert math.isnan(nx.effective_size(G, nodes=nodes)[0])
+
+
+@pytest.mark.parametrize("graph", (nx.Graph, nx.DiGraph))
+@pytest.mark.parametrize("nodes", (None, [0]))
+def test_effective_size_isolated_node_with_selfloop_weighted(graph, nodes):
+    """Weighted self-loop. See gh-6916"""
+    G = graph()
+    G.add_weighted_edges_from([(0, 0, 10)])
+    assert math.isnan(nx.effective_size(G, nodes=nodes)[0])
+
+
+@pytest.mark.parametrize("graph", (nx.Graph, nx.DiGraph))
+def test_constraint_isolated_node_with_selfloop(graph):
+    """Behavior consistent with isolated node without self-loop. See gh-6916"""
+    G = graph([(0, 0)])  # Single node with one self-edge
+    assert math.isnan(nx.constraint(G)[0])
+
+
+@pytest.mark.parametrize("graph", (nx.Graph, nx.DiGraph))
+def test_constraint_isolated_node_with_selfloop_using_nodes_kwarg(graph):
+    """Behavior consistent with isolated node without self-loop. See gh-6916"""
+    G = graph([(0, 0)])  # Single node with one self-edge
+    assert nx.constraint(G, nodes=[0])[0] == 4
+
+
+@pytest.mark.parametrize("graph", (nx.Graph, nx.DiGraph))
+def test_constraint_isolated_node_with_selfloop_weighted(graph):
+    """Weighted self-loop. See gh-6916"""
+    G = graph()
+    G.add_weighted_edges_from([(0, 0, 10)])
+    assert math.isnan(nx.constraint(G)[0])
+
+
+@pytest.mark.parametrize("graph", (nx.Graph, nx.DiGraph))
+def test_constraint_isolated_node_with_selfloop_weighted_using_nodes_kwarg(graph):
+    G = graph()
+    G.add_weighted_edges_from([(0, 0, 10)])
+    assert nx.constraint(G, nodes=[0])[0] == 4
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_summarization.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_summarization.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3bf82fa53b2564b13e555d994bd73b5885e1915
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_summarization.py
@@ -0,0 +1,642 @@
+"""
+Unit tests for dedensification and graph summarization
+"""
+
+import pytest
+
+import networkx as nx
+
+
+class TestDirectedDedensification:
+    def build_original_graph(self):
+        original_matrix = [
+            ("1", "BC"),
+            ("2", "ABC"),
+            ("3", ["A", "B", "6"]),
+            ("4", "ABC"),
+            ("5", "AB"),
+            ("6", ["5"]),
+            ("A", ["6"]),
+        ]
+        graph = nx.DiGraph()
+        for source, targets in original_matrix:
+            for target in targets:
+                graph.add_edge(source, target)
+        return graph
+
+    def build_compressed_graph(self):
+        compressed_matrix = [
+            ("1", "BC"),
+            ("2", ["ABC"]),
+            ("3", ["A", "B", "6"]),
+            ("4", ["ABC"]),
+            ("5", "AB"),
+            ("6", ["5"]),
+            ("A", ["6"]),
+            ("ABC", "ABC"),
+        ]
+        compressed_graph = nx.DiGraph()
+        for source, targets in compressed_matrix:
+            for target in targets:
+                compressed_graph.add_edge(source, target)
+        return compressed_graph
+
+    def test_empty(self):
+        """
+        Verify that an empty directed graph results in no compressor nodes
+        """
+        G = nx.DiGraph()
+        compressed_graph, c_nodes = nx.dedensify(G, threshold=2)
+        assert c_nodes == set()
+
+    @staticmethod
+    def densify(G, compressor_nodes, copy=True):
+        """
+        Reconstructs the original graph from a dedensified, directed graph
+
+        Parameters
+        ----------
+        G: dedensified graph
+           A networkx graph
+        compressor_nodes: iterable
+           Iterable of compressor nodes in the dedensified graph
+        inplace: bool, optional (default: False)
+           Indicates if densification should be done inplace
+
+        Returns
+        -------
+        G: graph
+           A densified networkx graph
+        """
+        if copy:
+            G = G.copy()
+        for compressor_node in compressor_nodes:
+            all_neighbors = set(nx.all_neighbors(G, compressor_node))
+            out_neighbors = set(G.neighbors(compressor_node))
+            for out_neighbor in out_neighbors:
+                G.remove_edge(compressor_node, out_neighbor)
+            in_neighbors = all_neighbors - out_neighbors
+            for in_neighbor in in_neighbors:
+                G.remove_edge(in_neighbor, compressor_node)
+                for out_neighbor in out_neighbors:
+                    G.add_edge(in_neighbor, out_neighbor)
+            G.remove_node(compressor_node)
+        return G
+
+    def setup_method(self):
+        self.c_nodes = ("ABC",)
+
+    def test_dedensify_edges(self):
+        """
+        Verifies that dedensify produced the correct edges to/from compressor
+        nodes in a directed graph
+        """
+        G = self.build_original_graph()
+        compressed_G = self.build_compressed_graph()
+        compressed_graph, c_nodes = nx.dedensify(G, threshold=2)
+        for s, t in compressed_graph.edges():
+            o_s = "".join(sorted(s))
+            o_t = "".join(sorted(t))
+            compressed_graph_exists = compressed_graph.has_edge(s, t)
+            verified_compressed_exists = compressed_G.has_edge(o_s, o_t)
+            assert compressed_graph_exists == verified_compressed_exists
+        assert len(c_nodes) == len(self.c_nodes)
+
+    def test_dedensify_edge_count(self):
+        """
+        Verifies that dedensify produced the correct number of compressor nodes
+        in a directed graph
+        """
+        G = self.build_original_graph()
+        original_edge_count = len(G.edges())
+        c_G, c_nodes = nx.dedensify(G, threshold=2)
+        compressed_edge_count = len(c_G.edges())
+        assert compressed_edge_count <= original_edge_count
+        compressed_G = self.build_compressed_graph()
+        assert compressed_edge_count == len(compressed_G.edges())
+
+    def test_densify_edges(self):
+        """
+        Verifies that densification produces the correct edges from the
+        original directed graph
+        """
+        compressed_G = self.build_compressed_graph()
+        original_graph = self.densify(compressed_G, self.c_nodes, copy=True)
+        G = self.build_original_graph()
+        for s, t in G.edges():
+            assert G.has_edge(s, t) == original_graph.has_edge(s, t)
+
+    def test_densify_edge_count(self):
+        """
+        Verifies that densification produces the correct number of edges in the
+        original directed graph
+        """
+        compressed_G = self.build_compressed_graph()
+        compressed_edge_count = len(compressed_G.edges())
+        original_graph = self.densify(compressed_G, self.c_nodes)
+        original_edge_count = len(original_graph.edges())
+        assert compressed_edge_count <= original_edge_count
+        G = self.build_original_graph()
+        assert original_edge_count == len(G.edges())
+
+
+class TestUnDirectedDedensification:
+    def build_original_graph(self):
+        """
+        Builds graph shown in the original research paper
+        """
+        original_matrix = [
+            ("1", "CB"),
+            ("2", "ABC"),
+            ("3", ["A", "B", "6"]),
+            ("4", "ABC"),
+            ("5", "AB"),
+            ("6", ["5"]),
+            ("A", ["6"]),
+        ]
+        graph = nx.Graph()
+        for source, targets in original_matrix:
+            for target in targets:
+                graph.add_edge(source, target)
+        return graph
+
+    def test_empty(self):
+        """
+        Verify that an empty undirected graph results in no compressor nodes
+        """
+        G = nx.Graph()
+        compressed_G, c_nodes = nx.dedensify(G, threshold=2)
+        assert c_nodes == set()
+
+    def setup_method(self):
+        self.c_nodes = ("6AB", "ABC")
+
+    def build_compressed_graph(self):
+        compressed_matrix = [
+            ("1", ["B", "C"]),
+            ("2", ["ABC"]),
+            ("3", ["6AB"]),
+            ("4", ["ABC"]),
+            ("5", ["6AB"]),
+            ("6", ["6AB", "A"]),
+            ("A", ["6AB", "ABC"]),
+            ("B", ["ABC", "6AB"]),
+            ("C", ["ABC"]),
+        ]
+        compressed_graph = nx.Graph()
+        for source, targets in compressed_matrix:
+            for target in targets:
+                compressed_graph.add_edge(source, target)
+        return compressed_graph
+
+    def test_dedensify_edges(self):
+        """
+        Verifies that dedensify produced correct compressor nodes and the
+        correct edges to/from the compressor nodes in an undirected graph
+        """
+        G = self.build_original_graph()
+        c_G, c_nodes = nx.dedensify(G, threshold=2)
+        v_compressed_G = self.build_compressed_graph()
+        for s, t in c_G.edges():
+            o_s = "".join(sorted(s))
+            o_t = "".join(sorted(t))
+            has_compressed_edge = c_G.has_edge(s, t)
+            verified_has_compressed_edge = v_compressed_G.has_edge(o_s, o_t)
+            assert has_compressed_edge == verified_has_compressed_edge
+        assert len(c_nodes) == len(self.c_nodes)
+
+    def test_dedensify_edge_count(self):
+        """
+        Verifies that dedensify produced the correct number of edges in an
+        undirected graph
+        """
+        G = self.build_original_graph()
+        c_G, c_nodes = nx.dedensify(G, threshold=2, copy=True)
+        compressed_edge_count = len(c_G.edges())
+        verified_original_edge_count = len(G.edges())
+        assert compressed_edge_count <= verified_original_edge_count
+        verified_compressed_G = self.build_compressed_graph()
+        verified_compressed_edge_count = len(verified_compressed_G.edges())
+        assert compressed_edge_count == verified_compressed_edge_count
+
+
+@pytest.mark.parametrize(
+    "graph_type", [nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph]
+)
+def test_summarization_empty(graph_type):
+    G = graph_type()
+    summary_graph = nx.snap_aggregation(G, node_attributes=("color",))
+    assert nx.is_isomorphic(summary_graph, G)
+
+
+class AbstractSNAP:
+    node_attributes = ("color",)
+
+    def build_original_graph(self):
+        pass
+
+    def build_summary_graph(self):
+        pass
+
+    def test_summary_graph(self):
+        original_graph = self.build_original_graph()
+        summary_graph = self.build_summary_graph()
+
+        relationship_attributes = ("type",)
+        generated_summary_graph = nx.snap_aggregation(
+            original_graph, self.node_attributes, relationship_attributes
+        )
+        relabeled_summary_graph = self.deterministic_labels(generated_summary_graph)
+        assert nx.is_isomorphic(summary_graph, relabeled_summary_graph)
+
+    def deterministic_labels(self, G):
+        node_labels = list(G.nodes)
+        node_labels = sorted(node_labels, key=lambda n: sorted(G.nodes[n]["group"])[0])
+        node_labels.sort()
+
+        label_mapping = {}
+        for index, node in enumerate(node_labels):
+            label = f"Supernode-{index}"
+            label_mapping[node] = label
+
+        return nx.relabel_nodes(G, label_mapping)
+
+
+class TestSNAPNoEdgeTypes(AbstractSNAP):
+    relationship_attributes = ()
+
+    def test_summary_graph(self):
+        original_graph = self.build_original_graph()
+        summary_graph = self.build_summary_graph()
+
+        relationship_attributes = ("type",)
+        generated_summary_graph = nx.snap_aggregation(
+            original_graph, self.node_attributes
+        )
+        relabeled_summary_graph = self.deterministic_labels(generated_summary_graph)
+        assert nx.is_isomorphic(summary_graph, relabeled_summary_graph)
+
+    def build_original_graph(self):
+        nodes = {
+            "A": {"color": "Red"},
+            "B": {"color": "Red"},
+            "C": {"color": "Red"},
+            "D": {"color": "Red"},
+            "E": {"color": "Blue"},
+            "F": {"color": "Blue"},
+            "G": {"color": "Blue"},
+            "H": {"color": "Blue"},
+            "I": {"color": "Yellow"},
+            "J": {"color": "Yellow"},
+            "K": {"color": "Yellow"},
+            "L": {"color": "Yellow"},
+        }
+        edges = [
+            ("A", "B"),
+            ("A", "C"),
+            ("A", "E"),
+            ("A", "I"),
+            ("B", "D"),
+            ("B", "J"),
+            ("B", "F"),
+            ("C", "G"),
+            ("D", "H"),
+            ("I", "J"),
+            ("J", "K"),
+            ("I", "L"),
+        ]
+        G = nx.Graph()
+        for node in nodes:
+            attributes = nodes[node]
+            G.add_node(node, **attributes)
+
+        for source, target in edges:
+            G.add_edge(source, target)
+
+        return G
+
+    def build_summary_graph(self):
+        nodes = {
+            "Supernode-0": {"color": "Red"},
+            "Supernode-1": {"color": "Red"},
+            "Supernode-2": {"color": "Blue"},
+            "Supernode-3": {"color": "Blue"},
+            "Supernode-4": {"color": "Yellow"},
+            "Supernode-5": {"color": "Yellow"},
+        }
+        edges = [
+            ("Supernode-0", "Supernode-0"),
+            ("Supernode-0", "Supernode-1"),
+            ("Supernode-0", "Supernode-2"),
+            ("Supernode-0", "Supernode-4"),
+            ("Supernode-1", "Supernode-3"),
+            ("Supernode-4", "Supernode-4"),
+            ("Supernode-4", "Supernode-5"),
+        ]
+        G = nx.Graph()
+        for node in nodes:
+            attributes = nodes[node]
+            G.add_node(node, **attributes)
+
+        for source, target in edges:
+            G.add_edge(source, target)
+
+        supernodes = {
+            "Supernode-0": {"A", "B"},
+            "Supernode-1": {"C", "D"},
+            "Supernode-2": {"E", "F"},
+            "Supernode-3": {"G", "H"},
+            "Supernode-4": {"I", "J"},
+            "Supernode-5": {"K", "L"},
+        }
+        nx.set_node_attributes(G, supernodes, "group")
+        return G
+
+
+class TestSNAPUndirected(AbstractSNAP):
+    def build_original_graph(self):
+        nodes = {
+            "A": {"color": "Red"},
+            "B": {"color": "Red"},
+            "C": {"color": "Red"},
+            "D": {"color": "Red"},
+            "E": {"color": "Blue"},
+            "F": {"color": "Blue"},
+            "G": {"color": "Blue"},
+            "H": {"color": "Blue"},
+            "I": {"color": "Yellow"},
+            "J": {"color": "Yellow"},
+            "K": {"color": "Yellow"},
+            "L": {"color": "Yellow"},
+        }
+        edges = [
+            ("A", "B", "Strong"),
+            ("A", "C", "Weak"),
+            ("A", "E", "Strong"),
+            ("A", "I", "Weak"),
+            ("B", "D", "Weak"),
+            ("B", "J", "Weak"),
+            ("B", "F", "Strong"),
+            ("C", "G", "Weak"),
+            ("D", "H", "Weak"),
+            ("I", "J", "Strong"),
+            ("J", "K", "Strong"),
+            ("I", "L", "Strong"),
+        ]
+        G = nx.Graph()
+        for node in nodes:
+            attributes = nodes[node]
+            G.add_node(node, **attributes)
+
+        for source, target, type in edges:
+            G.add_edge(source, target, type=type)
+
+        return G
+
+    def build_summary_graph(self):
+        nodes = {
+            "Supernode-0": {"color": "Red"},
+            "Supernode-1": {"color": "Red"},
+            "Supernode-2": {"color": "Blue"},
+            "Supernode-3": {"color": "Blue"},
+            "Supernode-4": {"color": "Yellow"},
+            "Supernode-5": {"color": "Yellow"},
+        }
+        edges = [
+            ("Supernode-0", "Supernode-0", "Strong"),
+            ("Supernode-0", "Supernode-1", "Weak"),
+            ("Supernode-0", "Supernode-2", "Strong"),
+            ("Supernode-0", "Supernode-4", "Weak"),
+            ("Supernode-1", "Supernode-3", "Weak"),
+            ("Supernode-4", "Supernode-4", "Strong"),
+            ("Supernode-4", "Supernode-5", "Strong"),
+        ]
+        G = nx.Graph()
+        for node in nodes:
+            attributes = nodes[node]
+            G.add_node(node, **attributes)
+
+        for source, target, type in edges:
+            G.add_edge(source, target, types=[{"type": type}])
+
+        supernodes = {
+            "Supernode-0": {"A", "B"},
+            "Supernode-1": {"C", "D"},
+            "Supernode-2": {"E", "F"},
+            "Supernode-3": {"G", "H"},
+            "Supernode-4": {"I", "J"},
+            "Supernode-5": {"K", "L"},
+        }
+        nx.set_node_attributes(G, supernodes, "group")
+        return G
+
+
+class TestSNAPDirected(AbstractSNAP):
+    def build_original_graph(self):
+        nodes = {
+            "A": {"color": "Red"},
+            "B": {"color": "Red"},
+            "C": {"color": "Green"},
+            "D": {"color": "Green"},
+            "E": {"color": "Blue"},
+            "F": {"color": "Blue"},
+            "G": {"color": "Yellow"},
+            "H": {"color": "Yellow"},
+        }
+        edges = [
+            ("A", "C", "Strong"),
+            ("A", "E", "Strong"),
+            ("A", "F", "Weak"),
+            ("B", "D", "Strong"),
+            ("B", "E", "Weak"),
+            ("B", "F", "Strong"),
+            ("C", "G", "Strong"),
+            ("C", "F", "Strong"),
+            ("D", "E", "Strong"),
+            ("D", "H", "Strong"),
+            ("G", "E", "Strong"),
+            ("H", "F", "Strong"),
+        ]
+        G = nx.DiGraph()
+        for node in nodes:
+            attributes = nodes[node]
+            G.add_node(node, **attributes)
+
+        for source, target, type in edges:
+            G.add_edge(source, target, type=type)
+
+        return G
+
+    def build_summary_graph(self):
+        nodes = {
+            "Supernode-0": {"color": "Red"},
+            "Supernode-1": {"color": "Green"},
+            "Supernode-2": {"color": "Blue"},
+            "Supernode-3": {"color": "Yellow"},
+        }
+        edges = [
+            ("Supernode-0", "Supernode-1", [{"type": "Strong"}]),
+            ("Supernode-0", "Supernode-2", [{"type": "Weak"}, {"type": "Strong"}]),
+            ("Supernode-1", "Supernode-2", [{"type": "Strong"}]),
+            ("Supernode-1", "Supernode-3", [{"type": "Strong"}]),
+            ("Supernode-3", "Supernode-2", [{"type": "Strong"}]),
+        ]
+        G = nx.DiGraph()
+        for node in nodes:
+            attributes = nodes[node]
+            G.add_node(node, **attributes)
+
+        for source, target, types in edges:
+            G.add_edge(source, target, types=types)
+
+        supernodes = {
+            "Supernode-0": {"A", "B"},
+            "Supernode-1": {"C", "D"},
+            "Supernode-2": {"E", "F"},
+            "Supernode-3": {"G", "H"},
+            "Supernode-4": {"I", "J"},
+            "Supernode-5": {"K", "L"},
+        }
+        nx.set_node_attributes(G, supernodes, "group")
+        return G
+
+
+class TestSNAPUndirectedMulti(AbstractSNAP):
+    def build_original_graph(self):
+        nodes = {
+            "A": {"color": "Red"},
+            "B": {"color": "Red"},
+            "C": {"color": "Red"},
+            "D": {"color": "Blue"},
+            "E": {"color": "Blue"},
+            "F": {"color": "Blue"},
+            "G": {"color": "Yellow"},
+            "H": {"color": "Yellow"},
+            "I": {"color": "Yellow"},
+        }
+        edges = [
+            ("A", "D", ["Weak", "Strong"]),
+            ("B", "E", ["Weak", "Strong"]),
+            ("D", "I", ["Strong"]),
+            ("E", "H", ["Strong"]),
+            ("F", "G", ["Weak"]),
+            ("I", "G", ["Weak", "Strong"]),
+            ("I", "H", ["Weak", "Strong"]),
+            ("G", "H", ["Weak", "Strong"]),
+        ]
+        G = nx.MultiGraph()
+        for node in nodes:
+            attributes = nodes[node]
+            G.add_node(node, **attributes)
+
+        for source, target, types in edges:
+            for type in types:
+                G.add_edge(source, target, type=type)
+
+        return G
+
+    def build_summary_graph(self):
+        nodes = {
+            "Supernode-0": {"color": "Red"},
+            "Supernode-1": {"color": "Blue"},
+            "Supernode-2": {"color": "Yellow"},
+            "Supernode-3": {"color": "Blue"},
+            "Supernode-4": {"color": "Yellow"},
+            "Supernode-5": {"color": "Red"},
+        }
+        edges = [
+            ("Supernode-1", "Supernode-2", [{"type": "Weak"}]),
+            ("Supernode-2", "Supernode-4", [{"type": "Weak"}, {"type": "Strong"}]),
+            ("Supernode-3", "Supernode-4", [{"type": "Strong"}]),
+            ("Supernode-3", "Supernode-5", [{"type": "Weak"}, {"type": "Strong"}]),
+            ("Supernode-4", "Supernode-4", [{"type": "Weak"}, {"type": "Strong"}]),
+        ]
+        G = nx.MultiGraph()
+        for node in nodes:
+            attributes = nodes[node]
+            G.add_node(node, **attributes)
+
+        for source, target, types in edges:
+            for type in types:
+                G.add_edge(source, target, type=type)
+
+        supernodes = {
+            "Supernode-0": {"A", "B"},
+            "Supernode-1": {"C", "D"},
+            "Supernode-2": {"E", "F"},
+            "Supernode-3": {"G", "H"},
+            "Supernode-4": {"I", "J"},
+            "Supernode-5": {"K", "L"},
+        }
+        nx.set_node_attributes(G, supernodes, "group")
+        return G
+
+
+class TestSNAPDirectedMulti(AbstractSNAP):
+    def build_original_graph(self):
+        nodes = {
+            "A": {"color": "Red"},
+            "B": {"color": "Red"},
+            "C": {"color": "Green"},
+            "D": {"color": "Green"},
+            "E": {"color": "Blue"},
+            "F": {"color": "Blue"},
+            "G": {"color": "Yellow"},
+            "H": {"color": "Yellow"},
+        }
+        edges = [
+            ("A", "C", ["Weak", "Strong"]),
+            ("A", "E", ["Strong"]),
+            ("A", "F", ["Weak"]),
+            ("B", "D", ["Weak", "Strong"]),
+            ("B", "E", ["Weak"]),
+            ("B", "F", ["Strong"]),
+            ("C", "G", ["Weak", "Strong"]),
+            ("C", "F", ["Strong"]),
+            ("D", "E", ["Strong"]),
+            ("D", "H", ["Weak", "Strong"]),
+            ("G", "E", ["Strong"]),
+            ("H", "F", ["Strong"]),
+        ]
+        G = nx.MultiDiGraph()
+        for node in nodes:
+            attributes = nodes[node]
+            G.add_node(node, **attributes)
+
+        for source, target, types in edges:
+            for type in types:
+                G.add_edge(source, target, type=type)
+
+        return G
+
+    def build_summary_graph(self):
+        nodes = {
+            "Supernode-0": {"color": "Red"},
+            "Supernode-1": {"color": "Blue"},
+            "Supernode-2": {"color": "Yellow"},
+            "Supernode-3": {"color": "Blue"},
+        }
+        edges = [
+            ("Supernode-0", "Supernode-1", ["Weak", "Strong"]),
+            ("Supernode-0", "Supernode-2", ["Weak", "Strong"]),
+            ("Supernode-1", "Supernode-2", ["Strong"]),
+            ("Supernode-1", "Supernode-3", ["Weak", "Strong"]),
+            ("Supernode-3", "Supernode-2", ["Strong"]),
+        ]
+        G = nx.MultiDiGraph()
+        for node in nodes:
+            attributes = nodes[node]
+            G.add_node(node, **attributes)
+
+        for source, target, types in edges:
+            for type in types:
+                G.add_edge(source, target, type=type)
+
+        supernodes = {
+            "Supernode-0": {"A", "B"},
+            "Supernode-1": {"C", "D"},
+            "Supernode-2": {"E", "F"},
+            "Supernode-3": {"G", "H"},
+        }
+        nx.set_node_attributes(G, supernodes, "group")
+        return G
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_swap.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_swap.py
new file mode 100644
index 0000000000000000000000000000000000000000..e765bd5e11496841072990aa792b90ca8772b4d3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_swap.py
@@ -0,0 +1,179 @@
+import pytest
+
+import networkx as nx
+
+cycle = nx.cycle_graph(5, create_using=nx.DiGraph)
+tree = nx.DiGraph()
+tree.add_edges_from(nx.random_labeled_tree(10, seed=42).edges)
+path = nx.path_graph(5, create_using=nx.DiGraph)
+binomial = nx.binomial_tree(3, create_using=nx.DiGraph)
+HH = nx.directed_havel_hakimi_graph([1, 2, 1, 2, 2, 2], [3, 1, 0, 1, 2, 3])
+balanced_tree = nx.balanced_tree(2, 3, create_using=nx.DiGraph)
+
+
+@pytest.mark.parametrize("G", [path, binomial, HH, cycle, tree, balanced_tree])
+def test_directed_edge_swap(G):
+    in_degree = set(G.in_degree)
+    out_degree = set(G.out_degree)
+    edges = set(G.edges)
+    nx.directed_edge_swap(G, nswap=1, max_tries=100, seed=1)
+    assert in_degree == set(G.in_degree)
+    assert out_degree == set(G.out_degree)
+    assert edges != set(G.edges)
+    assert 3 == sum(e not in edges for e in G.edges)
+
+
+def test_directed_edge_swap_undo_previous_swap():
+    G = nx.DiGraph(nx.path_graph(4).edges)  # only 1 swap possible
+    edges = set(G.edges)
+    nx.directed_edge_swap(G, nswap=2, max_tries=100)
+    assert edges == set(G.edges)
+
+    nx.directed_edge_swap(G, nswap=1, max_tries=100, seed=1)
+    assert {(0, 2), (1, 3), (2, 1)} == set(G.edges)
+    nx.directed_edge_swap(G, nswap=1, max_tries=100, seed=1)
+    assert edges == set(G.edges)
+
+
+def test_edge_cases_directed_edge_swap():
+    # Tests cases when swaps are impossible, either too few edges exist, or self loops/cycles are unavoidable
+    # TODO: Rewrite function to explicitly check for impossible swaps and raise error
+    e = (
+        "Maximum number of swap attempts \\(11\\) exceeded "
+        "before desired swaps achieved \\(\\d\\)."
+    )
+    graph = nx.DiGraph([(0, 0), (0, 1), (1, 0), (2, 3), (3, 2)])
+    with pytest.raises(nx.NetworkXAlgorithmError, match=e):
+        nx.directed_edge_swap(graph, nswap=1, max_tries=10, seed=1)
+
+
+def test_double_edge_swap():
+    graph = nx.barabasi_albert_graph(200, 1)
+    degrees = sorted(d for n, d in graph.degree())
+    G = nx.double_edge_swap(graph, 40)
+    assert degrees == sorted(d for n, d in graph.degree())
+
+
+def test_double_edge_swap_seed():
+    graph = nx.barabasi_albert_graph(200, 1)
+    degrees = sorted(d for n, d in graph.degree())
+    G = nx.double_edge_swap(graph, 40, seed=1)
+    assert degrees == sorted(d for n, d in graph.degree())
+
+
+def test_connected_double_edge_swap():
+    graph = nx.barabasi_albert_graph(200, 1)
+    degrees = sorted(d for n, d in graph.degree())
+    G = nx.connected_double_edge_swap(graph, 40, seed=1)
+    assert nx.is_connected(graph)
+    assert degrees == sorted(d for n, d in graph.degree())
+
+
+def test_connected_double_edge_swap_low_window_threshold():
+    graph = nx.barabasi_albert_graph(200, 1)
+    degrees = sorted(d for n, d in graph.degree())
+    G = nx.connected_double_edge_swap(graph, 40, _window_threshold=0, seed=1)
+    assert nx.is_connected(graph)
+    assert degrees == sorted(d for n, d in graph.degree())
+
+
+def test_connected_double_edge_swap_star():
+    # Testing ui==xi in connected_double_edge_swap
+    graph = nx.star_graph(40)
+    degrees = sorted(d for n, d in graph.degree())
+    G = nx.connected_double_edge_swap(graph, 1, seed=4)
+    assert nx.is_connected(graph)
+    assert degrees == sorted(d for n, d in graph.degree())
+
+
+def test_connected_double_edge_swap_star_low_window_threshold():
+    # Testing ui==xi in connected_double_edge_swap with low window threshold
+    graph = nx.star_graph(40)
+    degrees = sorted(d for n, d in graph.degree())
+    G = nx.connected_double_edge_swap(graph, 1, _window_threshold=0, seed=4)
+    assert nx.is_connected(graph)
+    assert degrees == sorted(d for n, d in graph.degree())
+
+
+def test_directed_edge_swap_small():
+    with pytest.raises(nx.NetworkXError):
+        G = nx.directed_edge_swap(nx.path_graph(3, create_using=nx.DiGraph))
+
+
+def test_directed_edge_swap_tries():
+    with pytest.raises(nx.NetworkXError):
+        G = nx.directed_edge_swap(
+            nx.path_graph(3, create_using=nx.DiGraph), nswap=1, max_tries=0
+        )
+
+
+def test_directed_exception_undirected():
+    graph = nx.Graph([(0, 1), (2, 3)])
+    with pytest.raises(nx.NetworkXNotImplemented):
+        G = nx.directed_edge_swap(graph)
+
+
+def test_directed_edge_max_tries():
+    with pytest.raises(nx.NetworkXAlgorithmError):
+        G = nx.directed_edge_swap(
+            nx.complete_graph(4, nx.DiGraph()), nswap=1, max_tries=5
+        )
+
+
+def test_double_edge_swap_small():
+    with pytest.raises(nx.NetworkXError):
+        G = nx.double_edge_swap(nx.path_graph(3))
+
+
+def test_double_edge_swap_tries():
+    with pytest.raises(nx.NetworkXError):
+        G = nx.double_edge_swap(nx.path_graph(10), nswap=1, max_tries=0)
+
+
+def test_double_edge_directed():
+    graph = nx.DiGraph([(0, 1), (2, 3)])
+    with pytest.raises(nx.NetworkXError, match="not defined for directed graphs."):
+        G = nx.double_edge_swap(graph)
+
+
+def test_double_edge_max_tries():
+    with pytest.raises(nx.NetworkXAlgorithmError):
+        G = nx.double_edge_swap(nx.complete_graph(4), nswap=1, max_tries=5)
+
+
+def test_connected_double_edge_swap_small():
+    with pytest.raises(nx.NetworkXError):
+        G = nx.connected_double_edge_swap(nx.path_graph(3))
+
+
+def test_connected_double_edge_swap_not_connected():
+    with pytest.raises(nx.NetworkXError):
+        G = nx.path_graph(3)
+        nx.add_path(G, [10, 11, 12])
+        G = nx.connected_double_edge_swap(G)
+
+
+def test_degree_seq_c4():
+    G = nx.cycle_graph(4)
+    degrees = sorted(d for n, d in G.degree())
+    G = nx.double_edge_swap(G, 1, 100)
+    assert degrees == sorted(d for n, d in G.degree())
+
+
+def test_fewer_than_4_nodes():
+    G = nx.DiGraph()
+    G.add_nodes_from([0, 1, 2])
+    with pytest.raises(nx.NetworkXError, match=".*fewer than four nodes."):
+        nx.directed_edge_swap(G)
+
+
+def test_less_than_3_edges():
+    G = nx.DiGraph([(0, 1), (1, 2)])
+    G.add_nodes_from([3, 4])
+    with pytest.raises(nx.NetworkXError, match=".*fewer than 3 edges"):
+        nx.directed_edge_swap(G)
+
+    G = nx.Graph()
+    G.add_nodes_from([0, 1, 2, 3])
+    with pytest.raises(nx.NetworkXError, match=".*fewer than 2 edges"):
+        nx.double_edge_swap(G)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_threshold.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_threshold.py
new file mode 100644
index 0000000000000000000000000000000000000000..d8806fd61df539d97e814e2a5cb92bc33dc71559
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_threshold.py
@@ -0,0 +1,270 @@
+"""
+Threshold Graphs
+================
+"""
+
+import pytest
+
+import networkx as nx
+import networkx.algorithms.threshold as nxt
+
+cnlti = nx.convert_node_labels_to_integers
+
+
+def test_threshold_graph_invalid_creation_sequence():
+    bad_creation_sequence = [2.0, 2, 1, 0]  # floats are not allowed
+    with pytest.raises(ValueError, match="not a valid creation sequence"):
+        nxt.threshold_graph(bad_creation_sequence)
+
+
+class TestGeneratorThreshold:
+    def test_threshold_sequence_graph_test(self):
+        G = nx.star_graph(10)
+        assert nxt.is_threshold_graph(G)
+        assert nxt.is_threshold_sequence([d for n, d in G.degree()])
+
+        G = nx.complete_graph(10)
+        assert nxt.is_threshold_graph(G)
+        assert nxt.is_threshold_sequence([d for n, d in G.degree()])
+
+        deg = [3, 2, 2, 1, 1, 1]
+        assert not nxt.is_threshold_sequence(deg)
+
+        deg = [3, 2, 2, 1]
+        assert nxt.is_threshold_sequence(deg)
+
+        G = nx.generators.havel_hakimi_graph(deg)
+        assert nxt.is_threshold_graph(G)
+
+    def test_creation_sequences(self):
+        deg = [3, 2, 2, 1]
+        G = nx.generators.havel_hakimi_graph(deg)
+
+        with pytest.raises(ValueError):
+            nxt.creation_sequence(deg, with_labels=True, compact=True)
+
+        cs0 = nxt.creation_sequence(deg)
+        H0 = nxt.threshold_graph(cs0)
+        assert "".join(cs0) == "ddid"
+
+        cs1 = nxt.creation_sequence(deg, with_labels=True)
+        H1 = nxt.threshold_graph(cs1)
+        assert cs1 == [(1, "d"), (2, "d"), (3, "i"), (0, "d")]
+
+        cs2 = nxt.creation_sequence(deg, compact=True)
+        H2 = nxt.threshold_graph(cs2)
+        assert cs2 == [2, 1, 1]
+        assert "".join(nxt.uncompact(cs2)) == "ddid"
+        assert nx.could_be_isomorphic(H0, G)
+        assert nx.could_be_isomorphic(H0, H1)
+        assert nx.could_be_isomorphic(H0, H2)
+
+    def test_make_compact(self):
+        assert nxt.make_compact(["d", "d", "d", "i", "d", "d"]) == [3, 1, 2]
+        assert nxt.make_compact([3, 1, 2]) == [3, 1, 2]
+        pytest.raises(TypeError, nxt.make_compact, [3.0, 1.0, 2.0])
+
+    def test_uncompact(self):
+        assert nxt.uncompact([3, 1, 2]) == ["d", "d", "d", "i", "d", "d"]
+        assert nxt.uncompact(["d", "d", "i", "d"]) == ["d", "d", "i", "d"]
+        assert nxt.uncompact(
+            nxt.uncompact([(1, "d"), (2, "d"), (3, "i"), (0, "d")])
+        ) == nxt.uncompact([(1, "d"), (2, "d"), (3, "i"), (0, "d")])
+        pytest.raises(TypeError, nxt.uncompact, [3.0, 1.0, 2.0])
+
+    def test_creation_sequence_to_weights(self):
+        assert nxt.creation_sequence_to_weights([3, 1, 2]) == [
+            0.5,
+            0.5,
+            0.5,
+            0.25,
+            0.75,
+            0.75,
+        ]
+        pytest.raises(TypeError, nxt.creation_sequence_to_weights, [3.0, 1.0, 2.0])
+
+    def test_weights_to_creation_sequence(self):
+        deg = [3, 2, 2, 1]
+        with pytest.raises(ValueError):
+            nxt.weights_to_creation_sequence(deg, with_labels=True, compact=True)
+        assert nxt.weights_to_creation_sequence(deg, with_labels=True) == [
+            (3, "d"),
+            (1, "d"),
+            (2, "d"),
+            (0, "d"),
+        ]
+        assert nxt.weights_to_creation_sequence(deg, compact=True) == [4]
+
+    def test_find_alternating_4_cycle(self):
+        G = nx.Graph()
+        G.add_edge(1, 2)
+        assert not nxt.find_alternating_4_cycle(G)
+
+    def test_shortest_path(self):
+        deg = [3, 2, 2, 1]
+        G = nx.generators.havel_hakimi_graph(deg)
+        cs1 = nxt.creation_sequence(deg, with_labels=True)
+        for n, m in [(3, 0), (0, 3), (0, 2), (0, 1), (1, 3), (3, 1), (1, 2), (2, 3)]:
+            assert nxt.shortest_path(cs1, n, m) == nx.shortest_path(G, n, m)
+
+        spl = nxt.shortest_path_length(cs1, 3)
+        spl2 = nxt.shortest_path_length([t for v, t in cs1], 2)
+        assert spl == spl2
+
+        spld = {}
+        for j, pl in enumerate(spl):
+            n = cs1[j][0]
+            spld[n] = pl
+        assert spld == nx.single_source_shortest_path_length(G, 3)
+
+        assert nxt.shortest_path(["d", "d", "d", "i", "d", "d"], 1, 2) == [1, 2]
+        assert nxt.shortest_path([3, 1, 2], 1, 2) == [1, 2]
+        pytest.raises(TypeError, nxt.shortest_path, [3.0, 1.0, 2.0], 1, 2)
+        pytest.raises(ValueError, nxt.shortest_path, [3, 1, 2], "a", 2)
+        pytest.raises(ValueError, nxt.shortest_path, [3, 1, 2], 1, "b")
+        assert nxt.shortest_path([3, 1, 2], 1, 1) == [1]
+
+    def test_shortest_path_length(self):
+        assert nxt.shortest_path_length([3, 1, 2], 1) == [1, 0, 1, 2, 1, 1]
+        assert nxt.shortest_path_length(["d", "d", "d", "i", "d", "d"], 1) == [
+            1,
+            0,
+            1,
+            2,
+            1,
+            1,
+        ]
+        assert nxt.shortest_path_length(("d", "d", "d", "i", "d", "d"), 1) == [
+            1,
+            0,
+            1,
+            2,
+            1,
+            1,
+        ]
+        pytest.raises(TypeError, nxt.shortest_path, [3.0, 1.0, 2.0], 1)
+
+    def test_random_threshold_sequence(self):
+        assert len(nxt.random_threshold_sequence(10, 0.5)) == 10
+        assert nxt.random_threshold_sequence(10, 0.5, seed=42) == [
+            "d",
+            "i",
+            "d",
+            "d",
+            "d",
+            "i",
+            "i",
+            "i",
+            "d",
+            "d",
+        ]
+        pytest.raises(ValueError, nxt.random_threshold_sequence, 10, 1.5)
+
+    def test_right_d_threshold_sequence(self):
+        assert nxt.right_d_threshold_sequence(3, 2) == ["d", "i", "d"]
+        pytest.raises(ValueError, nxt.right_d_threshold_sequence, 2, 3)
+
+    def test_left_d_threshold_sequence(self):
+        assert nxt.left_d_threshold_sequence(3, 2) == ["d", "i", "d"]
+        pytest.raises(ValueError, nxt.left_d_threshold_sequence, 2, 3)
+
+    def test_weights_thresholds(self):
+        wseq = [3, 4, 3, 3, 5, 6, 5, 4, 5, 6]
+        cs = nxt.weights_to_creation_sequence(wseq, threshold=10)
+        wseq = nxt.creation_sequence_to_weights(cs)
+        cs2 = nxt.weights_to_creation_sequence(wseq)
+        assert cs == cs2
+
+        wseq = nxt.creation_sequence_to_weights(nxt.uncompact([3, 1, 2, 3, 3, 2, 3]))
+        assert wseq == [
+            s * 0.125 for s in [4, 4, 4, 3, 5, 5, 2, 2, 2, 6, 6, 6, 1, 1, 7, 7, 7]
+        ]
+
+        wseq = nxt.creation_sequence_to_weights([3, 1, 2, 3, 3, 2, 3])
+        assert wseq == [
+            s * 0.125 for s in [4, 4, 4, 3, 5, 5, 2, 2, 2, 6, 6, 6, 1, 1, 7, 7, 7]
+        ]
+
+        wseq = nxt.creation_sequence_to_weights(list(enumerate("ddidiiidididi")))
+        assert wseq == [s * 0.1 for s in [5, 5, 4, 6, 3, 3, 3, 7, 2, 8, 1, 9, 0]]
+
+        wseq = nxt.creation_sequence_to_weights("ddidiiidididi")
+        assert wseq == [s * 0.1 for s in [5, 5, 4, 6, 3, 3, 3, 7, 2, 8, 1, 9, 0]]
+
+        wseq = nxt.creation_sequence_to_weights("ddidiiidididid")
+        ws = [s / 12 for s in [6, 6, 5, 7, 4, 4, 4, 8, 3, 9, 2, 10, 1, 11]]
+        assert sum(abs(c - d) for c, d in zip(wseq, ws)) < 1e-14
+
+    def test_finding_routines(self):
+        G = nx.Graph({1: [2], 2: [3], 3: [4], 4: [5], 5: [6]})
+        G.add_edge(2, 4)
+        G.add_edge(2, 5)
+        G.add_edge(2, 7)
+        G.add_edge(3, 6)
+        G.add_edge(4, 6)
+
+        # Alternating 4 cycle
+        assert nxt.find_alternating_4_cycle(G) == [1, 2, 3, 6]
+
+        # Threshold graph
+        TG = nxt.find_threshold_graph(G)
+        assert nxt.is_threshold_graph(TG)
+        assert sorted(TG.nodes()) == [1, 2, 3, 4, 5, 7]
+
+        cs = nxt.creation_sequence(dict(TG.degree()), with_labels=True)
+        assert nxt.find_creation_sequence(G) == cs
+
+    def test_fast_versions_properties_threshold_graphs(self):
+        cs = "ddiiddid"
+        G = nxt.threshold_graph(cs)
+        assert nxt.density("ddiiddid") == nx.density(G)
+        assert sorted(nxt.degree_sequence(cs)) == sorted(d for n, d in G.degree())
+
+        ts = nxt.triangle_sequence(cs)
+        assert ts == list(nx.triangles(G).values())
+        assert sum(ts) // 3 == nxt.triangles(cs)
+
+        c1 = nxt.cluster_sequence(cs)
+        c2 = list(nx.clustering(G).values())
+        assert sum(abs(c - d) for c, d in zip(c1, c2)) == pytest.approx(0, abs=1e-7)
+
+        b1 = nx.betweenness_centrality(G).values()
+        b2 = nxt.betweenness_sequence(cs)
+        assert sum(abs(c - d) for c, d in zip(b1, b2)) < 1e-7
+
+        assert nxt.eigenvalues(cs) == [0, 1, 3, 3, 5, 7, 7, 8]
+
+        # Degree Correlation
+        assert abs(nxt.degree_correlation(cs) + 0.593038821954) < 1e-12
+        assert nxt.degree_correlation("diiiddi") == -0.8
+        assert nxt.degree_correlation("did") == -1.0
+        assert nxt.degree_correlation("ddd") == 1.0
+        assert nxt.eigenvalues("dddiii") == [0, 0, 0, 0, 3, 3]
+        assert nxt.eigenvalues("dddiiid") == [0, 1, 1, 1, 4, 4, 7]
+
+    def test_tg_creation_routines(self):
+        s = nxt.left_d_threshold_sequence(5, 7)
+        s = nxt.right_d_threshold_sequence(5, 7)
+
+    def test_eigenvectors(self):
+        np = pytest.importorskip("numpy")
+        eigenval = np.linalg.eigvals
+        pytest.importorskip("scipy")
+
+        cs = "ddiiddid"
+        G = nxt.threshold_graph(cs)
+        (tgeval, tgevec) = nxt.eigenvectors(cs)
+        np.testing.assert_allclose([np.dot(lv, lv) for lv in tgevec], 1.0, rtol=1e-9)
+        lapl = nx.laplacian_matrix(G)
+
+    def test_create_using(self):
+        cs = "ddiiddid"
+        G = nxt.threshold_graph(cs)
+        pytest.raises(
+            nx.exception.NetworkXError,
+            nxt.threshold_graph,
+            cs,
+            create_using=nx.DiGraph(),
+        )
+        MG = nxt.threshold_graph(cs, create_using=nx.MultiGraph())
+        assert sorted(MG.edges()) == sorted(G.edges())
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_time_dependent.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_time_dependent.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e256f4bc69389464cfa164f209bc2db713b79ee
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_time_dependent.py
@@ -0,0 +1,431 @@
+"""Unit testing for time dependent algorithms."""
+
+from datetime import datetime, timedelta
+
+import pytest
+
+import networkx as nx
+
+_delta = timedelta(days=5 * 365)
+
+
+class TestCdIndex:
+    """Unit testing for the cd index function."""
+
+    def test_common_graph(self):
+        G = nx.DiGraph()
+        G.add_nodes_from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
+        G.add_edge(4, 2)
+        G.add_edge(4, 0)
+        G.add_edge(4, 1)
+        G.add_edge(4, 3)
+        G.add_edge(5, 2)
+        G.add_edge(6, 2)
+        G.add_edge(6, 4)
+        G.add_edge(7, 4)
+        G.add_edge(8, 4)
+        G.add_edge(9, 4)
+        G.add_edge(9, 1)
+        G.add_edge(9, 3)
+        G.add_edge(10, 4)
+
+        node_attrs = {
+            0: {"time": datetime(1992, 1, 1)},
+            1: {"time": datetime(1992, 1, 1)},
+            2: {"time": datetime(1993, 1, 1)},
+            3: {"time": datetime(1993, 1, 1)},
+            4: {"time": datetime(1995, 1, 1)},
+            5: {"time": datetime(1997, 1, 1)},
+            6: {"time": datetime(1998, 1, 1)},
+            7: {"time": datetime(1999, 1, 1)},
+            8: {"time": datetime(1999, 1, 1)},
+            9: {"time": datetime(1998, 1, 1)},
+            10: {"time": datetime(1997, 4, 1)},
+        }
+
+        nx.set_node_attributes(G, node_attrs)
+
+        assert nx.cd_index(G, 4, time_delta=_delta) == 0.17
+
+    def test_common_graph_with_given_attributes(self):
+        G = nx.DiGraph()
+        G.add_nodes_from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
+        G.add_edge(4, 2)
+        G.add_edge(4, 0)
+        G.add_edge(4, 1)
+        G.add_edge(4, 3)
+        G.add_edge(5, 2)
+        G.add_edge(6, 2)
+        G.add_edge(6, 4)
+        G.add_edge(7, 4)
+        G.add_edge(8, 4)
+        G.add_edge(9, 4)
+        G.add_edge(9, 1)
+        G.add_edge(9, 3)
+        G.add_edge(10, 4)
+
+        node_attrs = {
+            0: {"date": datetime(1992, 1, 1)},
+            1: {"date": datetime(1992, 1, 1)},
+            2: {"date": datetime(1993, 1, 1)},
+            3: {"date": datetime(1993, 1, 1)},
+            4: {"date": datetime(1995, 1, 1)},
+            5: {"date": datetime(1997, 1, 1)},
+            6: {"date": datetime(1998, 1, 1)},
+            7: {"date": datetime(1999, 1, 1)},
+            8: {"date": datetime(1999, 1, 1)},
+            9: {"date": datetime(1998, 1, 1)},
+            10: {"date": datetime(1997, 4, 1)},
+        }
+
+        nx.set_node_attributes(G, node_attrs)
+
+        assert nx.cd_index(G, 4, time_delta=_delta, time="date") == 0.17
+
+    def test_common_graph_with_int_attributes(self):
+        G = nx.DiGraph()
+        G.add_nodes_from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
+        G.add_edge(4, 2)
+        G.add_edge(4, 0)
+        G.add_edge(4, 1)
+        G.add_edge(4, 3)
+        G.add_edge(5, 2)
+        G.add_edge(6, 2)
+        G.add_edge(6, 4)
+        G.add_edge(7, 4)
+        G.add_edge(8, 4)
+        G.add_edge(9, 4)
+        G.add_edge(9, 1)
+        G.add_edge(9, 3)
+        G.add_edge(10, 4)
+
+        node_attrs = {
+            0: {"time": 20},
+            1: {"time": 20},
+            2: {"time": 30},
+            3: {"time": 30},
+            4: {"time": 50},
+            5: {"time": 70},
+            6: {"time": 80},
+            7: {"time": 90},
+            8: {"time": 90},
+            9: {"time": 80},
+            10: {"time": 74},
+        }
+
+        nx.set_node_attributes(G, node_attrs)
+
+        assert nx.cd_index(G, 4, time_delta=50) == 0.17
+
+    def test_common_graph_with_float_attributes(self):
+        G = nx.DiGraph()
+        G.add_nodes_from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
+        G.add_edge(4, 2)
+        G.add_edge(4, 0)
+        G.add_edge(4, 1)
+        G.add_edge(4, 3)
+        G.add_edge(5, 2)
+        G.add_edge(6, 2)
+        G.add_edge(6, 4)
+        G.add_edge(7, 4)
+        G.add_edge(8, 4)
+        G.add_edge(9, 4)
+        G.add_edge(9, 1)
+        G.add_edge(9, 3)
+        G.add_edge(10, 4)
+
+        node_attrs = {
+            0: {"time": 20.2},
+            1: {"time": 20.2},
+            2: {"time": 30.7},
+            3: {"time": 30.7},
+            4: {"time": 50.9},
+            5: {"time": 70.1},
+            6: {"time": 80.6},
+            7: {"time": 90.7},
+            8: {"time": 90.7},
+            9: {"time": 80.6},
+            10: {"time": 74.2},
+        }
+
+        nx.set_node_attributes(G, node_attrs)
+
+        assert nx.cd_index(G, 4, time_delta=50) == 0.17
+
+    def test_common_graph_with_weights(self):
+        G = nx.DiGraph()
+        G.add_nodes_from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
+        G.add_edge(4, 2)
+        G.add_edge(4, 0)
+        G.add_edge(4, 1)
+        G.add_edge(4, 3)
+        G.add_edge(5, 2)
+        G.add_edge(6, 2)
+        G.add_edge(6, 4)
+        G.add_edge(7, 4)
+        G.add_edge(8, 4)
+        G.add_edge(9, 4)
+        G.add_edge(9, 1)
+        G.add_edge(9, 3)
+        G.add_edge(10, 4)
+
+        node_attrs = {
+            0: {"time": datetime(1992, 1, 1)},
+            1: {"time": datetime(1992, 1, 1)},
+            2: {"time": datetime(1993, 1, 1)},
+            3: {"time": datetime(1993, 1, 1)},
+            4: {"time": datetime(1995, 1, 1)},
+            5: {"time": datetime(1997, 1, 1)},
+            6: {"time": datetime(1998, 1, 1), "weight": 5},
+            7: {"time": datetime(1999, 1, 1), "weight": 2},
+            8: {"time": datetime(1999, 1, 1), "weight": 6},
+            9: {"time": datetime(1998, 1, 1), "weight": 3},
+            10: {"time": datetime(1997, 4, 1), "weight": 10},
+        }
+
+        nx.set_node_attributes(G, node_attrs)
+        assert nx.cd_index(G, 4, time_delta=_delta, weight="weight") == 0.04
+
+    def test_node_with_no_predecessors(self):
+        G = nx.DiGraph()
+        G.add_nodes_from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
+        G.add_edge(4, 2)
+        G.add_edge(4, 0)
+        G.add_edge(4, 3)
+        G.add_edge(5, 2)
+        G.add_edge(6, 2)
+        G.add_edge(6, 4)
+        G.add_edge(7, 4)
+        G.add_edge(8, 4)
+        G.add_edge(9, 4)
+        G.add_edge(9, 1)
+        G.add_edge(9, 3)
+        G.add_edge(10, 4)
+
+        node_attrs = {
+            0: {"time": datetime(1992, 1, 1)},
+            1: {"time": datetime(1992, 1, 1)},
+            2: {"time": datetime(1993, 1, 1)},
+            3: {"time": datetime(1993, 1, 1)},
+            4: {"time": datetime(1995, 1, 1)},
+            5: {"time": datetime(2005, 1, 1)},
+            6: {"time": datetime(2010, 1, 1)},
+            7: {"time": datetime(2001, 1, 1)},
+            8: {"time": datetime(2020, 1, 1)},
+            9: {"time": datetime(2017, 1, 1)},
+            10: {"time": datetime(2004, 4, 1)},
+        }
+
+        nx.set_node_attributes(G, node_attrs)
+        assert nx.cd_index(G, 4, time_delta=_delta) == 0.0
+
+    def test_node_with_no_successors(self):
+        G = nx.DiGraph()
+        G.add_nodes_from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
+        G.add_edge(8, 2)
+        G.add_edge(6, 0)
+        G.add_edge(6, 3)
+        G.add_edge(5, 2)
+        G.add_edge(6, 2)
+        G.add_edge(6, 4)
+        G.add_edge(7, 4)
+        G.add_edge(8, 4)
+        G.add_edge(9, 4)
+        G.add_edge(9, 1)
+        G.add_edge(9, 3)
+        G.add_edge(10, 4)
+
+        node_attrs = {
+            0: {"time": datetime(1992, 1, 1)},
+            1: {"time": datetime(1992, 1, 1)},
+            2: {"time": datetime(1993, 1, 1)},
+            3: {"time": datetime(1993, 1, 1)},
+            4: {"time": datetime(1995, 1, 1)},
+            5: {"time": datetime(1997, 1, 1)},
+            6: {"time": datetime(1998, 1, 1)},
+            7: {"time": datetime(1999, 1, 1)},
+            8: {"time": datetime(1999, 1, 1)},
+            9: {"time": datetime(1998, 1, 1)},
+            10: {"time": datetime(1997, 4, 1)},
+        }
+
+        nx.set_node_attributes(G, node_attrs)
+        assert nx.cd_index(G, 4, time_delta=_delta) == 1.0
+
+    def test_n_equals_zero(self):
+        G = nx.DiGraph()
+        G.add_nodes_from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
+        G.add_edge(4, 2)
+        G.add_edge(4, 0)
+        G.add_edge(4, 3)
+        G.add_edge(6, 4)
+        G.add_edge(7, 4)
+        G.add_edge(8, 4)
+        G.add_edge(9, 4)
+        G.add_edge(9, 1)
+        G.add_edge(10, 4)
+
+        node_attrs = {
+            0: {"time": datetime(1992, 1, 1)},
+            1: {"time": datetime(1992, 1, 1)},
+            2: {"time": datetime(1993, 1, 1)},
+            3: {"time": datetime(1993, 1, 1)},
+            4: {"time": datetime(1995, 1, 1)},
+            5: {"time": datetime(2005, 1, 1)},
+            6: {"time": datetime(2010, 1, 1)},
+            7: {"time": datetime(2001, 1, 1)},
+            8: {"time": datetime(2020, 1, 1)},
+            9: {"time": datetime(2017, 1, 1)},
+            10: {"time": datetime(2004, 4, 1)},
+        }
+
+        nx.set_node_attributes(G, node_attrs)
+
+        with pytest.raises(
+            nx.NetworkXError, match="The cd index cannot be defined."
+        ) as ve:
+            nx.cd_index(G, 4, time_delta=_delta)
+
+    def test_time_timedelta_compatibility(self):
+        G = nx.DiGraph()
+        G.add_nodes_from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
+        G.add_edge(4, 2)
+        G.add_edge(4, 0)
+        G.add_edge(4, 3)
+        G.add_edge(6, 4)
+        G.add_edge(7, 4)
+        G.add_edge(8, 4)
+        G.add_edge(9, 4)
+        G.add_edge(9, 1)
+        G.add_edge(10, 4)
+
+        node_attrs = {
+            0: {"time": 20.2},
+            1: {"time": 20.2},
+            2: {"time": 30.7},
+            3: {"time": 30.7},
+            4: {"time": 50.9},
+            5: {"time": 70.1},
+            6: {"time": 80.6},
+            7: {"time": 90.7},
+            8: {"time": 90.7},
+            9: {"time": 80.6},
+            10: {"time": 74.2},
+        }
+
+        nx.set_node_attributes(G, node_attrs)
+
+        with pytest.raises(
+            nx.NetworkXError,
+            match="Addition and comparison are not supported between",
+        ) as ve:
+            nx.cd_index(G, 4, time_delta=_delta)
+
+    def test_node_with_no_time(self):
+        G = nx.DiGraph()
+        G.add_nodes_from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
+        G.add_edge(8, 2)
+        G.add_edge(6, 0)
+        G.add_edge(6, 3)
+        G.add_edge(5, 2)
+        G.add_edge(6, 2)
+        G.add_edge(6, 4)
+        G.add_edge(7, 4)
+        G.add_edge(8, 4)
+        G.add_edge(9, 4)
+        G.add_edge(9, 1)
+        G.add_edge(9, 3)
+        G.add_edge(10, 4)
+
+        node_attrs = {
+            0: {"time": datetime(1992, 1, 1)},
+            1: {"time": datetime(1992, 1, 1)},
+            2: {"time": datetime(1993, 1, 1)},
+            3: {"time": datetime(1993, 1, 1)},
+            4: {"time": datetime(1995, 1, 1)},
+            6: {"time": datetime(1998, 1, 1)},
+            7: {"time": datetime(1999, 1, 1)},
+            8: {"time": datetime(1999, 1, 1)},
+            9: {"time": datetime(1998, 1, 1)},
+            10: {"time": datetime(1997, 4, 1)},
+        }
+
+        nx.set_node_attributes(G, node_attrs)
+
+        with pytest.raises(
+            nx.NetworkXError, match="Not all nodes have a 'time' attribute."
+        ) as ve:
+            nx.cd_index(G, 4, time_delta=_delta)
+
+    def test_maximally_consolidating(self):
+        G = nx.DiGraph()
+        G.add_nodes_from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
+        G.add_edge(5, 1)
+        G.add_edge(5, 2)
+        G.add_edge(5, 3)
+        G.add_edge(5, 4)
+        G.add_edge(6, 1)
+        G.add_edge(6, 5)
+        G.add_edge(7, 1)
+        G.add_edge(7, 5)
+        G.add_edge(8, 2)
+        G.add_edge(8, 5)
+        G.add_edge(9, 5)
+        G.add_edge(9, 3)
+        G.add_edge(10, 5)
+        G.add_edge(10, 3)
+        G.add_edge(10, 4)
+        G.add_edge(11, 5)
+        G.add_edge(11, 4)
+
+        node_attrs = {
+            0: {"time": datetime(1992, 1, 1)},
+            1: {"time": datetime(1992, 1, 1)},
+            2: {"time": datetime(1993, 1, 1)},
+            3: {"time": datetime(1993, 1, 1)},
+            4: {"time": datetime(1995, 1, 1)},
+            5: {"time": datetime(1997, 1, 1)},
+            6: {"time": datetime(1998, 1, 1)},
+            7: {"time": datetime(1999, 1, 1)},
+            8: {"time": datetime(1999, 1, 1)},
+            9: {"time": datetime(1998, 1, 1)},
+            10: {"time": datetime(1997, 4, 1)},
+            11: {"time": datetime(1998, 5, 1)},
+        }
+
+        nx.set_node_attributes(G, node_attrs)
+
+        assert nx.cd_index(G, 5, time_delta=_delta) == -1
+
+    def test_maximally_destabilizing(self):
+        G = nx.DiGraph()
+        G.add_nodes_from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
+        G.add_edge(5, 1)
+        G.add_edge(5, 2)
+        G.add_edge(5, 3)
+        G.add_edge(5, 4)
+        G.add_edge(6, 5)
+        G.add_edge(7, 5)
+        G.add_edge(8, 5)
+        G.add_edge(9, 5)
+        G.add_edge(10, 5)
+        G.add_edge(11, 5)
+
+        node_attrs = {
+            0: {"time": datetime(1992, 1, 1)},
+            1: {"time": datetime(1992, 1, 1)},
+            2: {"time": datetime(1993, 1, 1)},
+            3: {"time": datetime(1993, 1, 1)},
+            4: {"time": datetime(1995, 1, 1)},
+            5: {"time": datetime(1997, 1, 1)},
+            6: {"time": datetime(1998, 1, 1)},
+            7: {"time": datetime(1999, 1, 1)},
+            8: {"time": datetime(1999, 1, 1)},
+            9: {"time": datetime(1998, 1, 1)},
+            10: {"time": datetime(1997, 4, 1)},
+            11: {"time": datetime(1998, 5, 1)},
+        }
+
+        nx.set_node_attributes(G, node_attrs)
+
+        assert nx.cd_index(G, 5, time_delta=_delta) == 1
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_tournament.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_tournament.py
new file mode 100644
index 0000000000000000000000000000000000000000..34d9b22a65a3b46b91eb1f0b6bbb9780373bbdc9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_tournament.py
@@ -0,0 +1,161 @@
+"""Unit tests for the :mod:`networkx.algorithms.tournament` module."""
+
+from itertools import combinations
+
+import pytest
+
+from networkx import DiGraph
+from networkx.algorithms.tournament import (
+    hamiltonian_path,
+    index_satisfying,
+    is_reachable,
+    is_strongly_connected,
+    is_tournament,
+    random_tournament,
+    score_sequence,
+    tournament_matrix,
+)
+
+
+def test_condition_not_satisfied():
+    iter_in = [0]
+    assert index_satisfying(iter_in, lambda x: x > 0) == 1
+
+
+def test_empty_iterable():
+    with pytest.raises(ValueError):
+        index_satisfying([], lambda x: x > 0)
+
+
+def test_is_tournament():
+    G = DiGraph()
+    G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 0), (1, 3), (0, 2)])
+    assert is_tournament(G)
+
+
+def test_self_loops():
+    """A tournament must have no self-loops."""
+    G = DiGraph()
+    G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 0), (1, 3), (0, 2)])
+    G.add_edge(0, 0)
+    assert not is_tournament(G)
+
+
+def test_missing_edges():
+    """A tournament must not have any pair of nodes without at least
+    one edge joining the pair.
+
+    """
+    G = DiGraph()
+    G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 0), (1, 3)])
+    assert not is_tournament(G)
+
+
+def test_bidirectional_edges():
+    """A tournament must not have any pair of nodes with greater
+    than one edge joining the pair.
+
+    """
+    G = DiGraph()
+    G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 0), (1, 3), (0, 2)])
+    G.add_edge(1, 0)
+    assert not is_tournament(G)
+
+
+def test_graph_is_tournament():
+    for _ in range(10):
+        G = random_tournament(5)
+        assert is_tournament(G)
+
+
+def test_graph_is_tournament_seed():
+    for _ in range(10):
+        G = random_tournament(5, seed=1)
+        assert is_tournament(G)
+
+
+def test_graph_is_tournament_one_node():
+    G = random_tournament(1)
+    assert is_tournament(G)
+
+
+def test_graph_is_tournament_zero_node():
+    G = random_tournament(0)
+    assert is_tournament(G)
+
+
+def test_hamiltonian_empty_graph():
+    path = hamiltonian_path(DiGraph())
+    assert len(path) == 0
+
+
+def test_path_is_hamiltonian():
+    G = DiGraph()
+    G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 0), (1, 3), (0, 2)])
+    path = hamiltonian_path(G)
+    assert len(path) == 4
+    assert all(v in G[u] for u, v in zip(path, path[1:]))
+
+
+def test_hamiltonian_cycle():
+    """Tests that :func:`networkx.tournament.hamiltonian_path`
+    returns a Hamiltonian cycle when provided a strongly connected
+    tournament.
+
+    """
+    G = DiGraph()
+    G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 0), (1, 3), (0, 2)])
+    path = hamiltonian_path(G)
+    assert len(path) == 4
+    assert all(v in G[u] for u, v in zip(path, path[1:]))
+    assert path[0] in G[path[-1]]
+
+
+def test_score_sequence_edge():
+    G = DiGraph([(0, 1)])
+    assert score_sequence(G) == [0, 1]
+
+
+def test_score_sequence_triangle():
+    G = DiGraph([(0, 1), (1, 2), (2, 0)])
+    assert score_sequence(G) == [1, 1, 1]
+
+
+def test_tournament_matrix():
+    np = pytest.importorskip("numpy")
+    pytest.importorskip("scipy")
+    npt = np.testing
+    G = DiGraph([(0, 1)])
+    m = tournament_matrix(G)
+    npt.assert_array_equal(m.todense(), np.array([[0, 1], [-1, 0]]))
+
+
+def test_reachable_pair():
+    """Tests for a reachable pair of nodes."""
+    G = DiGraph([(0, 1), (1, 2), (2, 0)])
+    assert is_reachable(G, 0, 2)
+
+
+def test_same_node_is_reachable():
+    """Tests that a node is always reachable from it."""
+    # G is an arbitrary tournament on ten nodes.
+    G = DiGraph(sorted(p) for p in combinations(range(10), 2))
+    assert all(is_reachable(G, v, v) for v in G)
+
+
+def test_unreachable_pair():
+    """Tests for an unreachable pair of nodes."""
+    G = DiGraph([(0, 1), (0, 2), (1, 2)])
+    assert not is_reachable(G, 1, 0)
+
+
+def test_is_strongly_connected():
+    """Tests for a strongly connected tournament."""
+    G = DiGraph([(0, 1), (1, 2), (2, 0)])
+    assert is_strongly_connected(G)
+
+
+def test_not_strongly_connected():
+    """Tests for a tournament that is not strongly connected."""
+    G = DiGraph([(0, 1), (0, 2), (1, 2)])
+    assert not is_strongly_connected(G)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_triads.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_triads.py
new file mode 100644
index 0000000000000000000000000000000000000000..cdfaf3be2de9ce9bba69bf0d5734c4c8e3716d3f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_triads.py
@@ -0,0 +1,248 @@
+"""Tests for the :mod:`networkx.algorithms.triads` module."""
+
+import itertools
+from collections import defaultdict
+from random import sample
+
+import pytest
+
+import networkx as nx
+
+
+def test_triadic_census():
+    """Tests the triadic_census function."""
+    G = nx.DiGraph()
+    G.add_edges_from(["01", "02", "03", "04", "05", "12", "16", "51", "56", "65"])
+    expected = {
+        "030T": 2,
+        "120C": 1,
+        "210": 0,
+        "120U": 0,
+        "012": 9,
+        "102": 3,
+        "021U": 0,
+        "111U": 0,
+        "003": 8,
+        "030C": 0,
+        "021D": 9,
+        "201": 0,
+        "111D": 1,
+        "300": 0,
+        "120D": 0,
+        "021C": 2,
+    }
+    actual = nx.triadic_census(G)
+    assert expected == actual
+
+
+def test_is_triad():
+    """Tests the is_triad function"""
+    G = nx.karate_club_graph()
+    G = G.to_directed()
+    for i in range(100):
+        nodes = sample(sorted(G.nodes()), 3)
+        G2 = G.subgraph(nodes)
+        assert nx.is_triad(G2)
+
+
+def test_all_triads():
+    """Tests the all_triads function."""
+    G = nx.DiGraph()
+    G.add_edges_from(["01", "02", "03", "04", "05", "12", "16", "51", "56", "65"])
+    expected = [
+        f"{i},{j},{k}"
+        for i in range(7)
+        for j in range(i + 1, 7)
+        for k in range(j + 1, 7)
+    ]
+    expected = [G.subgraph(x.split(",")) for x in expected]
+    actual = list(nx.all_triads(G))
+    assert all(any(nx.is_isomorphic(G1, G2) for G1 in expected) for G2 in actual)
+
+
+def test_triad_type():
+    """Tests the triad_type function."""
+    # 0 edges (1 type)
+    G = nx.DiGraph({0: [], 1: [], 2: []})
+    assert nx.triad_type(G) == "003"
+    # 1 edge (1 type)
+    G = nx.DiGraph({0: [1], 1: [], 2: []})
+    assert nx.triad_type(G) == "012"
+    # 2 edges (4 types)
+    G = nx.DiGraph([(0, 1), (0, 2)])
+    assert nx.triad_type(G) == "021D"
+    G = nx.DiGraph({0: [1], 1: [0], 2: []})
+    assert nx.triad_type(G) == "102"
+    G = nx.DiGraph([(0, 1), (2, 1)])
+    assert nx.triad_type(G) == "021U"
+    G = nx.DiGraph([(0, 1), (1, 2)])
+    assert nx.triad_type(G) == "021C"
+    # 3 edges (4 types)
+    G = nx.DiGraph([(0, 1), (1, 0), (2, 1)])
+    assert nx.triad_type(G) == "111D"
+    G = nx.DiGraph([(0, 1), (1, 0), (1, 2)])
+    assert nx.triad_type(G) == "111U"
+    G = nx.DiGraph([(0, 1), (1, 2), (0, 2)])
+    assert nx.triad_type(G) == "030T"
+    G = nx.DiGraph([(0, 1), (1, 2), (2, 0)])
+    assert nx.triad_type(G) == "030C"
+    # 4 edges (4 types)
+    G = nx.DiGraph([(0, 1), (1, 0), (2, 0), (0, 2)])
+    assert nx.triad_type(G) == "201"
+    G = nx.DiGraph([(0, 1), (1, 0), (2, 0), (2, 1)])
+    assert nx.triad_type(G) == "120D"
+    G = nx.DiGraph([(0, 1), (1, 0), (0, 2), (1, 2)])
+    assert nx.triad_type(G) == "120U"
+    G = nx.DiGraph([(0, 1), (1, 0), (0, 2), (2, 1)])
+    assert nx.triad_type(G) == "120C"
+    # 5 edges (1 type)
+    G = nx.DiGraph([(0, 1), (1, 0), (2, 1), (1, 2), (0, 2)])
+    assert nx.triad_type(G) == "210"
+    # 6 edges (1 type)
+    G = nx.DiGraph([(0, 1), (1, 0), (1, 2), (2, 1), (0, 2), (2, 0)])
+    assert nx.triad_type(G) == "300"
+
+
+def test_triads_by_type():
+    G = nx.DiGraph()
+    G.add_edges_from(["01", "02", "03", "04", "05", "12", "16", "51", "56", "65"])
+    all_triads = nx.all_triads(G)
+    expected = defaultdict(list)
+    for triad in all_triads:
+        name = nx.triad_type(triad)
+        expected[name].append(triad)
+    actual = nx.triads_by_type(G)
+    assert set(actual.keys()) == set(expected.keys())
+    for tri_type, actual_Gs in actual.items():
+        expected_Gs = expected[tri_type]
+        for a in actual_Gs:
+            assert any(nx.is_isomorphic(a, e) for e in expected_Gs)
+
+
+def test_triadic_census_short_path_nodelist():
+    G = nx.path_graph("abc", create_using=nx.DiGraph)
+    expected = {"021C": 1}
+    for nl in ["a", "b", "c", "ab", "ac", "bc", "abc"]:
+        triad_census = nx.triadic_census(G, nodelist=nl)
+        assert expected == {typ: cnt for typ, cnt in triad_census.items() if cnt > 0}
+
+
+def test_triadic_census_correct_nodelist_values():
+    G = nx.path_graph(5, create_using=nx.DiGraph)
+    msg = r"nodelist includes duplicate nodes or nodes not in G"
+    with pytest.raises(ValueError, match=msg):
+        nx.triadic_census(G, [1, 2, 2, 3])
+    with pytest.raises(ValueError, match=msg):
+        nx.triadic_census(G, [1, 2, "a", 3])
+
+
+def test_triadic_census_tiny_graphs():
+    tc = nx.triadic_census(nx.empty_graph(0, create_using=nx.DiGraph))
+    assert {} == {typ: cnt for typ, cnt in tc.items() if cnt > 0}
+    tc = nx.triadic_census(nx.empty_graph(1, create_using=nx.DiGraph))
+    assert {} == {typ: cnt for typ, cnt in tc.items() if cnt > 0}
+    tc = nx.triadic_census(nx.empty_graph(2, create_using=nx.DiGraph))
+    assert {} == {typ: cnt for typ, cnt in tc.items() if cnt > 0}
+    tc = nx.triadic_census(nx.DiGraph([(1, 2)]))
+    assert {} == {typ: cnt for typ, cnt in tc.items() if cnt > 0}
+
+
+def test_triadic_census_selfloops():
+    GG = nx.path_graph("abc", create_using=nx.DiGraph)
+    expected = {"021C": 1}
+    for n in GG:
+        G = GG.copy()
+        G.add_edge(n, n)
+        tc = nx.triadic_census(G)
+        assert expected == {typ: cnt for typ, cnt in tc.items() if cnt > 0}
+
+    GG = nx.path_graph("abcde", create_using=nx.DiGraph)
+    tbt = nx.triads_by_type(GG)
+    for n in GG:
+        GG.add_edge(n, n)
+    tc = nx.triadic_census(GG)
+    assert tc == {tt: len(tbt[tt]) for tt in tc}
+
+
+def test_triadic_census_four_path():
+    G = nx.path_graph("abcd", create_using=nx.DiGraph)
+    expected = {"012": 2, "021C": 2}
+    triad_census = nx.triadic_census(G)
+    assert expected == {typ: cnt for typ, cnt in triad_census.items() if cnt > 0}
+
+
+def test_triadic_census_four_path_nodelist():
+    G = nx.path_graph("abcd", create_using=nx.DiGraph)
+    expected_end = {"012": 2, "021C": 1}
+    expected_mid = {"012": 1, "021C": 2}
+    a_triad_census = nx.triadic_census(G, nodelist=["a"])
+    assert expected_end == {typ: cnt for typ, cnt in a_triad_census.items() if cnt > 0}
+    b_triad_census = nx.triadic_census(G, nodelist=["b"])
+    assert expected_mid == {typ: cnt for typ, cnt in b_triad_census.items() if cnt > 0}
+    c_triad_census = nx.triadic_census(G, nodelist=["c"])
+    assert expected_mid == {typ: cnt for typ, cnt in c_triad_census.items() if cnt > 0}
+    d_triad_census = nx.triadic_census(G, nodelist=["d"])
+    assert expected_end == {typ: cnt for typ, cnt in d_triad_census.items() if cnt > 0}
+
+
+def test_triadic_census_nodelist():
+    """Tests the triadic_census function."""
+    G = nx.DiGraph()
+    G.add_edges_from(["01", "02", "03", "04", "05", "12", "16", "51", "56", "65"])
+    expected = {
+        "030T": 2,
+        "120C": 1,
+        "210": 0,
+        "120U": 0,
+        "012": 9,
+        "102": 3,
+        "021U": 0,
+        "111U": 0,
+        "003": 8,
+        "030C": 0,
+        "021D": 9,
+        "201": 0,
+        "111D": 1,
+        "300": 0,
+        "120D": 0,
+        "021C": 2,
+    }
+    actual = {k: 0 for k in expected}
+    for node in G.nodes():
+        node_triad_census = nx.triadic_census(G, nodelist=[node])
+        for triad_key in expected:
+            actual[triad_key] += node_triad_census[triad_key]
+    # Divide all counts by 3
+    for k, v in actual.items():
+        actual[k] //= 3
+    assert expected == actual
+
+
+@pytest.mark.parametrize("N", [5, 10])
+def test_triadic_census_on_random_graph(N):
+    G = nx.binomial_graph(N, 0.3, directed=True, seed=42)
+    tc1 = nx.triadic_census(G)
+    tbt = nx.triads_by_type(G)
+    tc2 = {tt: len(tbt[tt]) for tt in tc1}
+    assert tc1 == tc2
+
+    for n in G:
+        tc1 = nx.triadic_census(G, nodelist={n})
+        tc2 = {tt: sum(1 for t in tbt.get(tt, []) if n in t) for tt in tc1}
+        assert tc1 == tc2
+
+    for ns in itertools.combinations(G, 2):
+        ns = set(ns)
+        tc1 = nx.triadic_census(G, nodelist=ns)
+        tc2 = {
+            tt: sum(1 for t in tbt.get(tt, []) if any(n in ns for n in t)) for tt in tc1
+        }
+        assert tc1 == tc2
+
+    for ns in itertools.combinations(G, 3):
+        ns = set(ns)
+        tc1 = nx.triadic_census(G, nodelist=ns)
+        tc2 = {
+            tt: sum(1 for t in tbt.get(tt, []) if any(n in ns for n in t)) for tt in tc1
+        }
+        assert tc1 == tc2
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_vitality.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_vitality.py
new file mode 100644
index 0000000000000000000000000000000000000000..248206e670fa911f62177bb6727d6a7a6df1e6b9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_vitality.py
@@ -0,0 +1,41 @@
+import networkx as nx
+
+
+class TestClosenessVitality:
+    def test_unweighted(self):
+        G = nx.cycle_graph(3)
+        vitality = nx.closeness_vitality(G)
+        assert vitality == {0: 2, 1: 2, 2: 2}
+
+    def test_weighted(self):
+        G = nx.Graph()
+        nx.add_cycle(G, [0, 1, 2], weight=2)
+        vitality = nx.closeness_vitality(G, weight="weight")
+        assert vitality == {0: 4, 1: 4, 2: 4}
+
+    def test_unweighted_digraph(self):
+        G = nx.DiGraph(nx.cycle_graph(3))
+        vitality = nx.closeness_vitality(G)
+        assert vitality == {0: 4, 1: 4, 2: 4}
+
+    def test_weighted_digraph(self):
+        G = nx.DiGraph()
+        nx.add_cycle(G, [0, 1, 2], weight=2)
+        nx.add_cycle(G, [2, 1, 0], weight=2)
+        vitality = nx.closeness_vitality(G, weight="weight")
+        assert vitality == {0: 8, 1: 8, 2: 8}
+
+    def test_weighted_multidigraph(self):
+        G = nx.MultiDiGraph()
+        nx.add_cycle(G, [0, 1, 2], weight=2)
+        nx.add_cycle(G, [2, 1, 0], weight=2)
+        vitality = nx.closeness_vitality(G, weight="weight")
+        assert vitality == {0: 8, 1: 8, 2: 8}
+
+    def test_disconnecting_graph(self):
+        """Tests that the closeness vitality of a node whose removal
+        disconnects the graph is negative infinity.
+
+        """
+        G = nx.path_graph(3)
+        assert nx.closeness_vitality(G, node=1) == -float("inf")
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_voronoi.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_voronoi.py
new file mode 100644
index 0000000000000000000000000000000000000000..3269ae62a023ff0cf9fdc55122cb6e7c8d2ba319
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_voronoi.py
@@ -0,0 +1,103 @@
+import networkx as nx
+from networkx.utils import pairwise
+
+
+class TestVoronoiCells:
+    """Unit tests for the Voronoi cells function."""
+
+    def test_isolates(self):
+        """Tests that a graph with isolated nodes has all isolates in
+        one block of the partition.
+
+        """
+        G = nx.empty_graph(5)
+        cells = nx.voronoi_cells(G, {0, 2, 4})
+        expected = {0: {0}, 2: {2}, 4: {4}, "unreachable": {1, 3}}
+        assert expected == cells
+
+    def test_undirected_unweighted(self):
+        G = nx.cycle_graph(6)
+        cells = nx.voronoi_cells(G, {0, 3})
+        expected = {0: {0, 1, 5}, 3: {2, 3, 4}}
+        assert expected == cells
+
+    def test_directed_unweighted(self):
+        # This is the singly-linked directed cycle graph on six nodes.
+        G = nx.DiGraph(pairwise(range(6), cyclic=True))
+        cells = nx.voronoi_cells(G, {0, 3})
+        expected = {0: {0, 1, 2}, 3: {3, 4, 5}}
+        assert expected == cells
+
+    def test_directed_inward(self):
+        """Tests that reversing the graph gives the "inward" Voronoi
+        partition.
+
+        """
+        # This is the singly-linked reverse directed cycle graph on six nodes.
+        G = nx.DiGraph(pairwise(range(6), cyclic=True))
+        G = G.reverse(copy=False)
+        cells = nx.voronoi_cells(G, {0, 3})
+        expected = {0: {0, 4, 5}, 3: {1, 2, 3}}
+        assert expected == cells
+
+    def test_undirected_weighted(self):
+        edges = [(0, 1, 10), (1, 2, 1), (2, 3, 1)]
+        G = nx.Graph()
+        G.add_weighted_edges_from(edges)
+        cells = nx.voronoi_cells(G, {0, 3})
+        expected = {0: {0}, 3: {1, 2, 3}}
+        assert expected == cells
+
+    def test_directed_weighted(self):
+        edges = [(0, 1, 10), (1, 2, 1), (2, 3, 1), (3, 2, 1), (2, 1, 1)]
+        G = nx.DiGraph()
+        G.add_weighted_edges_from(edges)
+        cells = nx.voronoi_cells(G, {0, 3})
+        expected = {0: {0}, 3: {1, 2, 3}}
+        assert expected == cells
+
+    def test_multigraph_unweighted(self):
+        """Tests that the Voronoi cells for a multigraph are the same as
+        for a simple graph.
+
+        """
+        edges = [(0, 1), (1, 2), (2, 3)]
+        G = nx.MultiGraph(2 * edges)
+        H = nx.Graph(G)
+        G_cells = nx.voronoi_cells(G, {0, 3})
+        H_cells = nx.voronoi_cells(H, {0, 3})
+        assert G_cells == H_cells
+
+    def test_multidigraph_unweighted(self):
+        # This is the twice-singly-linked directed cycle graph on six nodes.
+        edges = list(pairwise(range(6), cyclic=True))
+        G = nx.MultiDiGraph(2 * edges)
+        H = nx.DiGraph(G)
+        G_cells = nx.voronoi_cells(G, {0, 3})
+        H_cells = nx.voronoi_cells(H, {0, 3})
+        assert G_cells == H_cells
+
+    def test_multigraph_weighted(self):
+        edges = [(0, 1, 10), (0, 1, 10), (1, 2, 1), (1, 2, 100), (2, 3, 1), (2, 3, 100)]
+        G = nx.MultiGraph()
+        G.add_weighted_edges_from(edges)
+        cells = nx.voronoi_cells(G, {0, 3})
+        expected = {0: {0}, 3: {1, 2, 3}}
+        assert expected == cells
+
+    def test_multidigraph_weighted(self):
+        edges = [
+            (0, 1, 10),
+            (0, 1, 10),
+            (1, 2, 1),
+            (2, 3, 1),
+            (3, 2, 10),
+            (3, 2, 1),
+            (2, 1, 10),
+            (2, 1, 1),
+        ]
+        G = nx.MultiDiGraph()
+        G.add_weighted_edges_from(edges)
+        cells = nx.voronoi_cells(G, {0, 3})
+        expected = {0: {0}, 3: {1, 2, 3}}
+        assert expected == cells
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_walks.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_walks.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a6b323932988e1b9513118162df62e9613ee65b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_walks.py
@@ -0,0 +1,54 @@
+"""Unit tests for the :mod:`networkx.algorithms.walks` module."""
+
+import pytest
+
+import networkx as nx
+
+pytest.importorskip("numpy")
+pytest.importorskip("scipy")
+
+
+def test_directed():
+    G = nx.DiGraph([(0, 1), (1, 2), (2, 0)])
+    num_walks = nx.number_of_walks(G, 3)
+    expected = {0: {0: 1, 1: 0, 2: 0}, 1: {0: 0, 1: 1, 2: 0}, 2: {0: 0, 1: 0, 2: 1}}
+    assert num_walks == expected
+
+
+def test_undirected():
+    G = nx.cycle_graph(3)
+    num_walks = nx.number_of_walks(G, 3)
+    expected = {0: {0: 2, 1: 3, 2: 3}, 1: {0: 3, 1: 2, 2: 3}, 2: {0: 3, 1: 3, 2: 2}}
+    assert num_walks == expected
+
+
+def test_non_integer_nodes():
+    G = nx.DiGraph([("A", "B"), ("B", "C"), ("C", "A")])
+    num_walks = nx.number_of_walks(G, 2)
+    expected = {
+        "A": {"A": 0, "B": 0, "C": 1},
+        "B": {"A": 1, "B": 0, "C": 0},
+        "C": {"A": 0, "B": 1, "C": 0},
+    }
+    assert num_walks == expected
+
+
+def test_zero_length():
+    G = nx.cycle_graph(3)
+    num_walks = nx.number_of_walks(G, 0)
+    expected = {0: {0: 1, 1: 0, 2: 0}, 1: {0: 0, 1: 1, 2: 0}, 2: {0: 0, 1: 0, 2: 1}}
+    assert num_walks == expected
+
+
+def test_negative_length_exception():
+    G = nx.cycle_graph(3)
+    with pytest.raises(ValueError):
+        nx.number_of_walks(G, -1)
+
+
+def test_hidden_weight_attr():
+    G = nx.cycle_graph(3)
+    G.add_edge(1, 2, weight=5)
+    num_walks = nx.number_of_walks(G, 3)
+    expected = {0: {0: 2, 1: 3, 2: 3}, 1: {0: 3, 1: 2, 2: 3}, 2: {0: 3, 1: 3, 2: 2}}
+    assert num_walks == expected
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_wiener.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_wiener.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bb1f85b1d7f932a1050b43bdc1f422bc7be8aa3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tests/test_wiener.py
@@ -0,0 +1,157 @@
+import networkx as nx
+
+
+def test_wiener_index_of_disconnected_graph():
+    assert nx.wiener_index(nx.empty_graph(2)) == float("inf")
+
+
+def test_wiener_index_of_directed_graph():
+    G = nx.complete_graph(3)
+    H = nx.DiGraph(G)
+    assert (2 * nx.wiener_index(G)) == nx.wiener_index(H)
+
+
+def test_wiener_index_of_complete_graph():
+    n = 10
+    G = nx.complete_graph(n)
+    assert nx.wiener_index(G) == (n * (n - 1) / 2)
+
+
+def test_wiener_index_of_path_graph():
+    # In P_n, there are n - 1 pairs of vertices at distance one, n -
+    # 2 pairs at distance two, n - 3 at distance three, ..., 1 at
+    # distance n - 1, so the Wiener index should be
+    #
+    #     1 * (n - 1) + 2 * (n - 2) + ... + (n - 2) * 2 + (n - 1) * 1
+    #
+    # For example, in P_5,
+    #
+    #     1 * 4 + 2 * 3 + 3 * 2 + 4 * 1 = 2 (1 * 4 + 2 * 3)
+    #
+    # and in P_6,
+    #
+    #     1 * 5 + 2 * 4 + 3 * 3 + 4 * 2 + 5 * 1 = 2 (1 * 5 + 2 * 4) + 3 * 3
+    #
+    # assuming n is *odd*, this gives the formula
+    #
+    #     2 \sum_{i = 1}^{(n - 1) / 2} [i * (n - i)]
+    #
+    # assuming n is *even*, this gives the formula
+    #
+    #     2 \sum_{i = 1}^{n / 2} [i * (n - i)] - (n / 2) ** 2
+    #
+    n = 9
+    G = nx.path_graph(n)
+    expected = 2 * sum(i * (n - i) for i in range(1, (n // 2) + 1))
+    actual = nx.wiener_index(G)
+    assert expected == actual
+
+
+def test_schultz_and_gutman_index_of_disconnected_graph():
+    n = 4
+    G = nx.Graph()
+    G.add_nodes_from(list(range(1, n + 1)))
+    expected = float("inf")
+
+    G.add_edge(1, 2)
+    G.add_edge(3, 4)
+
+    actual_1 = nx.schultz_index(G)
+    actual_2 = nx.gutman_index(G)
+
+    assert expected == actual_1
+    assert expected == actual_2
+
+
+def test_schultz_and_gutman_index_of_complete_bipartite_graph_1():
+    n = 3
+    m = 3
+    cbg = nx.complete_bipartite_graph(n, m)
+
+    expected_1 = n * m * (n + m) + 2 * n * (n - 1) * m + 2 * m * (m - 1) * n
+    actual_1 = nx.schultz_index(cbg)
+
+    expected_2 = n * m * (n * m) + n * (n - 1) * m * m + m * (m - 1) * n * n
+    actual_2 = nx.gutman_index(cbg)
+
+    assert expected_1 == actual_1
+    assert expected_2 == actual_2
+
+
+def test_schultz_and_gutman_index_of_complete_bipartite_graph_2():
+    n = 2
+    m = 5
+    cbg = nx.complete_bipartite_graph(n, m)
+
+    expected_1 = n * m * (n + m) + 2 * n * (n - 1) * m + 2 * m * (m - 1) * n
+    actual_1 = nx.schultz_index(cbg)
+
+    expected_2 = n * m * (n * m) + n * (n - 1) * m * m + m * (m - 1) * n * n
+    actual_2 = nx.gutman_index(cbg)
+
+    assert expected_1 == actual_1
+    assert expected_2 == actual_2
+
+
+def test_schultz_and_gutman_index_of_complete_graph():
+    n = 5
+    cg = nx.complete_graph(n)
+
+    expected_1 = n * (n - 1) * (n - 1)
+    actual_1 = nx.schultz_index(cg)
+
+    assert expected_1 == actual_1
+
+    expected_2 = n * (n - 1) * (n - 1) * (n - 1) / 2
+    actual_2 = nx.gutman_index(cg)
+
+    assert expected_2 == actual_2
+
+
+def test_schultz_and_gutman_index_of_odd_cycle_graph():
+    k = 5
+    n = 2 * k + 1
+    ocg = nx.cycle_graph(n)
+
+    expected_1 = 2 * n * k * (k + 1)
+    actual_1 = nx.schultz_index(ocg)
+
+    expected_2 = 2 * n * k * (k + 1)
+    actual_2 = nx.gutman_index(ocg)
+
+    assert expected_1 == actual_1
+    assert expected_2 == actual_2
+
+
+def test_hyper_wiener_of_complete_graph():
+    # In a complete graph K_n, the distance is always 1.
+    # For K_n, this term is always (1 + 1^2) = 2.
+    #
+    # The number of ordered pairs is n * (n - 1).
+    # The total sum before division is (n * (n - 1)) * 2.
+    # The final result is therefore ((n * (n - 1)) * 2) / 2, which
+    # simplifies to n * (n - 1).
+    n = 5
+    G = nx.complete_graph(n)
+    assert nx.hyper_wiener_index(G) == n * (n - 1)
+
+
+def test_hyper_wiener_of_path_graph():
+    G = nx.path_graph(4)
+    assert nx.hyper_wiener_index(G) == 30.0
+
+
+def test_hyper_wiener_of_cycle_graph():
+    G = nx.cycle_graph(4)
+    assert nx.hyper_wiener_index(G) == 20.0
+
+
+def test_hyper_wiener_of_disconnected_graph():
+    G = nx.Graph([(0, 1), (2, 3)])
+    assert nx.hyper_wiener_index(G) == float("inf")
+
+
+def test_hyper_wiener_of_weighted_graph():
+    G = nx.path_graph(3)
+    G.edges[0, 1]["weight"] = 2
+    assert nx.hyper_wiener_index(G, weight="weight") == 20.0
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/threshold.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/threshold.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d08de1c45b5e49f34c75515defa48d8b1f385a9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/threshold.py
@@ -0,0 +1,981 @@
+"""
+Threshold Graphs - Creation, manipulation and identification.
+"""
+
+from math import sqrt
+
+import networkx as nx
+from networkx.utils import py_random_state
+
+__all__ = ["is_threshold_graph", "find_threshold_graph"]
+
+
+@nx._dispatchable
+def is_threshold_graph(G):
+    """
+    Returns `True` if `G` is a threshold graph.
+
+    Parameters
+    ----------
+    G : NetworkX graph instance
+        An instance of `Graph`, `DiGraph`, `MultiGraph` or `MultiDiGraph`
+
+    Returns
+    -------
+    bool
+        `True` if `G` is a threshold graph, `False` otherwise.
+
+    Examples
+    --------
+    >>> from networkx.algorithms.threshold import is_threshold_graph
+    >>> G = nx.path_graph(3)
+    >>> is_threshold_graph(G)
+    True
+    >>> G = nx.barbell_graph(3, 3)
+    >>> is_threshold_graph(G)
+    False
+
+    References
+    ----------
+    .. [1] Threshold graphs: https://en.wikipedia.org/wiki/Threshold_graph
+    """
+    return is_threshold_sequence([d for n, d in G.degree()])
+
+
+def is_threshold_sequence(degree_sequence):
+    """
+    Returns True if the sequence is a threshold degree sequence.
+
+    Uses the property that a threshold graph must be constructed by
+    adding either dominating or isolated nodes. Thus, it can be
+    deconstructed iteratively by removing a node of degree zero or a
+    node that connects to the remaining nodes.  If this deconstruction
+    fails then the sequence is not a threshold sequence.
+    """
+    ds = degree_sequence[:]  # get a copy so we don't destroy original
+    ds.sort()
+    while ds:
+        if ds[0] == 0:  # if isolated node
+            ds.pop(0)  # remove it
+            continue
+        if ds[-1] != len(ds) - 1:  # is the largest degree node dominating?
+            return False  # no, not a threshold degree sequence
+        ds.pop()  # yes, largest is the dominating node
+        ds = [d - 1 for d in ds]  # remove it and decrement all degrees
+    return True
+
+
+def creation_sequence(degree_sequence, with_labels=False, compact=False):
+    """
+    Determines the creation sequence for the given threshold degree sequence.
+
+    The creation sequence is a list of single characters 'd'
+    or 'i': 'd' for dominating or 'i' for isolated vertices.
+    Dominating vertices are connected to all vertices present when it
+    is added.  The first node added is by convention 'd'.
+    This list can be converted to a string if desired using "".join(cs)
+
+    If with_labels==True:
+    Returns a list of 2-tuples containing the vertex number
+    and a character 'd' or 'i' which describes the type of vertex.
+
+    If compact==True:
+    Returns the creation sequence in a compact form that is the number
+    of 'i's and 'd's alternating.
+    Examples:
+    [1,2,2,3] represents d,i,i,d,d,i,i,i
+    [3,1,2] represents d,d,d,i,d,d
+
+    Notice that the first number is the first vertex to be used for
+    construction and so is always 'd'.
+
+    with_labels and compact cannot both be True.
+
+    Returns None if the sequence is not a threshold sequence
+    """
+    if with_labels and compact:
+        raise ValueError("compact sequences cannot be labeled")
+
+    # make an indexed copy
+    if isinstance(degree_sequence, dict):  # labeled degree sequence
+        ds = [[degree, label] for (label, degree) in degree_sequence.items()]
+    else:
+        ds = [[d, i] for i, d in enumerate(degree_sequence)]
+    ds.sort()
+    cs = []  # creation sequence
+    while ds:
+        if ds[0][0] == 0:  # isolated node
+            (d, v) = ds.pop(0)
+            if len(ds) > 0:  # make sure we start with a d
+                cs.insert(0, (v, "i"))
+            else:
+                cs.insert(0, (v, "d"))
+            continue
+        if ds[-1][0] != len(ds) - 1:  # Not dominating node
+            return None  # not a threshold degree sequence
+        (d, v) = ds.pop()
+        cs.insert(0, (v, "d"))
+        ds = [[d[0] - 1, d[1]] for d in ds]  # decrement due to removing node
+
+    if with_labels:
+        return cs
+    if compact:
+        return make_compact(cs)
+    return [v[1] for v in cs]  # not labeled
+
+
+def make_compact(creation_sequence):
+    """
+    Returns the creation sequence in a compact form
+    that is the number of 'i's and 'd's alternating.
+
+    Examples
+    --------
+    >>> from networkx.algorithms.threshold import make_compact
+    >>> make_compact(["d", "i", "i", "d", "d", "i", "i", "i"])
+    [1, 2, 2, 3]
+    >>> make_compact(["d", "d", "d", "i", "d", "d"])
+    [3, 1, 2]
+
+    Notice that the first number is the first vertex
+    to be used for construction and so is always 'd'.
+
+    Labeled creation sequences lose their labels in the
+    compact representation.
+
+    >>> make_compact([3, 1, 2])
+    [3, 1, 2]
+    """
+    first = creation_sequence[0]
+    if isinstance(first, str):  # creation sequence
+        cs = creation_sequence[:]
+    elif isinstance(first, tuple):  # labeled creation sequence
+        cs = [s[1] for s in creation_sequence]
+    elif isinstance(first, int):  # compact creation sequence
+        return creation_sequence
+    else:
+        raise TypeError("Not a valid creation sequence type")
+
+    ccs = []
+    count = 1  # count the run lengths of d's or i's.
+    for i in range(1, len(cs)):
+        if cs[i] == cs[i - 1]:
+            count += 1
+        else:
+            ccs.append(count)
+            count = 1
+    ccs.append(count)  # don't forget the last one
+    return ccs
+
+
+def uncompact(creation_sequence):
+    """
+    Converts a compact creation sequence for a threshold
+    graph to a standard creation sequence (unlabeled).
+    If the creation_sequence is already standard, return it.
+    See creation_sequence.
+    """
+    first = creation_sequence[0]
+    if isinstance(first, str):  # creation sequence
+        return creation_sequence
+    elif isinstance(first, tuple):  # labeled creation sequence
+        return creation_sequence
+    elif isinstance(first, int):  # compact creation sequence
+        ccscopy = creation_sequence[:]
+    else:
+        raise TypeError("Not a valid creation sequence type")
+    cs = []
+    while ccscopy:
+        cs.extend(ccscopy.pop(0) * ["d"])
+        if ccscopy:
+            cs.extend(ccscopy.pop(0) * ["i"])
+    return cs
+
+
+def creation_sequence_to_weights(creation_sequence):
+    """
+    Returns a list of node weights which create the threshold
+    graph designated by the creation sequence.  The weights
+    are scaled so that the threshold is 1.0.  The order of the
+    nodes is the same as that in the creation sequence.
+    """
+    # Turn input sequence into a labeled creation sequence
+    first = creation_sequence[0]
+    if isinstance(first, str):  # creation sequence
+        if isinstance(creation_sequence, list):
+            wseq = creation_sequence[:]
+        else:
+            wseq = list(creation_sequence)  # string like 'ddidid'
+    elif isinstance(first, tuple):  # labeled creation sequence
+        wseq = [v[1] for v in creation_sequence]
+    elif isinstance(first, int):  # compact creation sequence
+        wseq = uncompact(creation_sequence)
+    else:
+        raise TypeError("Not a valid creation sequence type")
+    # pass through twice--first backwards
+    wseq.reverse()
+    w = 0
+    prev = "i"
+    for j, s in enumerate(wseq):
+        if s == "i":
+            wseq[j] = w
+            prev = s
+        elif prev == "i":
+            prev = s
+            w += 1
+    wseq.reverse()  # now pass through forwards
+    for j, s in enumerate(wseq):
+        if s == "d":
+            wseq[j] = w
+            prev = s
+        elif prev == "d":
+            prev = s
+            w += 1
+    # Now scale weights
+    if prev == "d":
+        w += 1
+    wscale = 1 / w
+    return [ww * wscale for ww in wseq]
+    # return wseq
+
+
+def weights_to_creation_sequence(
+    weights, threshold=1, with_labels=False, compact=False
+):
+    """
+    Returns a creation sequence for a threshold graph
+    determined by the weights and threshold given as input.
+    If the sum of two node weights is greater than the
+    threshold value, an edge is created between these nodes.
+
+    The creation sequence is a list of single characters 'd'
+    or 'i': 'd' for dominating or 'i' for isolated vertices.
+    Dominating vertices are connected to all vertices present
+    when it is added.  The first node added is by convention 'd'.
+
+    If with_labels==True:
+    Returns a list of 2-tuples containing the vertex number
+    and a character 'd' or 'i' which describes the type of vertex.
+
+    If compact==True:
+    Returns the creation sequence in a compact form that is the number
+    of 'i's and 'd's alternating.
+    Examples:
+    [1,2,2,3] represents d,i,i,d,d,i,i,i
+    [3,1,2] represents d,d,d,i,d,d
+
+    Notice that the first number is the first vertex to be used for
+    construction and so is always 'd'.
+
+    with_labels and compact cannot both be True.
+    """
+    if with_labels and compact:
+        raise ValueError("compact sequences cannot be labeled")
+
+    # make an indexed copy
+    if isinstance(weights, dict):  # labeled weights
+        wseq = [[w, label] for (label, w) in weights.items()]
+    else:
+        wseq = [[w, i] for i, w in enumerate(weights)]
+    wseq.sort()
+    cs = []  # creation sequence
+    cutoff = threshold - wseq[-1][0]
+    while wseq:
+        if wseq[0][0] < cutoff:  # isolated node
+            (w, label) = wseq.pop(0)
+            cs.append((label, "i"))
+        else:
+            (w, label) = wseq.pop()
+            cs.append((label, "d"))
+            cutoff = threshold - wseq[-1][0]
+        if len(wseq) == 1:  # make sure we start with a d
+            (w, label) = wseq.pop()
+            cs.append((label, "d"))
+    # put in correct order
+    cs.reverse()
+
+    if with_labels:
+        return cs
+    if compact:
+        return make_compact(cs)
+    return [v[1] for v in cs]  # not labeled
+
+
+# Manipulating NetworkX.Graphs in context of threshold graphs
+@nx._dispatchable(graphs=None, returns_graph=True)
+def threshold_graph(creation_sequence, create_using=None):
+    """
+    Create a threshold graph from the creation sequence or compact
+    creation_sequence.
+
+    The input sequence can be a
+
+    creation sequence (e.g. ['d','i','d','d','d','i'])
+    labeled creation sequence (e.g. [(0,'d'),(2,'d'),(1,'i')])
+    compact creation sequence (e.g. [2,1,1,2,0])
+
+    Use cs=creation_sequence(degree_sequence,labeled=True)
+    to convert a degree sequence to a creation sequence.
+
+    Returns None if the sequence is not valid
+    """
+    # Turn input sequence into a labeled creation sequence
+    first = creation_sequence[0]
+    if isinstance(first, str):  # creation sequence
+        ci = list(enumerate(creation_sequence))
+    elif isinstance(first, tuple):  # labeled creation sequence
+        ci = creation_sequence[:]
+    elif isinstance(first, int):  # compact creation sequence
+        cs = uncompact(creation_sequence)
+        ci = list(enumerate(cs))
+    else:
+        raise ValueError("not a valid creation sequence")
+
+    G = nx.empty_graph(0, create_using)
+    if G.is_directed():
+        raise nx.NetworkXError("Directed Graph not supported")
+
+    G.name = "Threshold Graph"
+
+    # add nodes and edges
+    # if type is 'i' just add nodea
+    # if type is a d connect to everything previous
+    while ci:
+        (v, node_type) = ci.pop(0)
+        if node_type == "d":  # dominating type, connect to all existing nodes
+            # We use `for u in list(G):` instead of
+            # `for u in G:` because we edit the graph `G` in
+            # the loop. Hence using an iterator will result in
+            # `RuntimeError: dictionary changed size during iteration`
+            for u in list(G):
+                G.add_edge(v, u)
+        G.add_node(v)
+    return G
+
+
+@nx._dispatchable
+def find_alternating_4_cycle(G):
+    """
+    Returns False if there aren't any alternating 4 cycles.
+    Otherwise returns the cycle as [a,b,c,d] where (a,b)
+    and (c,d) are edges and (a,c) and (b,d) are not.
+    """
+    for u, v in G.edges():
+        for w in G.nodes():
+            if not G.has_edge(u, w) and u != w:
+                for x in G.neighbors(w):
+                    if not G.has_edge(v, x) and v != x:
+                        return [u, v, w, x]
+    return False
+
+
+@nx._dispatchable(returns_graph=True)
+def find_threshold_graph(G, create_using=None):
+    """
+    Returns a threshold subgraph that is close to largest in `G`.
+
+    The threshold graph will contain the largest degree node in G.
+
+    Parameters
+    ----------
+    G : NetworkX graph instance
+        An instance of `Graph`, or `MultiDiGraph`
+    create_using : NetworkX graph class or `None` (default), optional
+        Type of graph to use when constructing the threshold graph.
+        If `None`, infer the appropriate graph type from the input.
+
+    Returns
+    -------
+    graph :
+        A graph instance representing the threshold graph
+
+    Examples
+    --------
+    >>> from networkx.algorithms.threshold import find_threshold_graph
+    >>> G = nx.barbell_graph(3, 3)
+    >>> T = find_threshold_graph(G)
+    >>> T.nodes  # may vary
+    NodeView((7, 8, 5, 6))
+
+    References
+    ----------
+    .. [1] Threshold graphs: https://en.wikipedia.org/wiki/Threshold_graph
+    """
+    return threshold_graph(find_creation_sequence(G), create_using)
+
+
+@nx._dispatchable
+def find_creation_sequence(G):
+    """
+    Find a threshold subgraph that is close to largest in G.
+    Returns the labeled creation sequence of that threshold graph.
+    """
+    cs = []
+    # get a local pointer to the working part of the graph
+    H = G
+    while H.order() > 0:
+        # get new degree sequence on subgraph
+        dsdict = dict(H.degree())
+        ds = [(d, v) for v, d in dsdict.items()]
+        ds.sort()
+        # Update threshold graph nodes
+        if ds[-1][0] == 0:  # all are isolated
+            cs.extend(zip(dsdict, ["i"] * (len(ds) - 1) + ["d"]))
+            break  # Done!
+        # pull off isolated nodes
+        while ds[0][0] == 0:
+            (d, iso) = ds.pop(0)
+            cs.append((iso, "i"))
+        # find new biggest node
+        (d, bigv) = ds.pop()
+        # add edges of star to t_g
+        cs.append((bigv, "d"))
+        # form subgraph of neighbors of big node
+        H = H.subgraph(H.neighbors(bigv))
+    cs.reverse()
+    return cs
+
+
+# Properties of Threshold Graphs
+def triangles(creation_sequence):
+    """
+    Compute number of triangles in the threshold graph with the
+    given creation sequence.
+    """
+    # shortcut algorithm that doesn't require computing number
+    # of triangles at each node.
+    cs = creation_sequence  # alias
+    dr = cs.count("d")  # number of d's in sequence
+    ntri = dr * (dr - 1) * (dr - 2) / 6  # number of triangles in clique of nd d's
+    # now add dr choose 2 triangles for every 'i' in sequence where
+    # dr is the number of d's to the right of the current i
+    for i, typ in enumerate(cs):
+        if typ == "i":
+            ntri += dr * (dr - 1) / 2
+        else:
+            dr -= 1
+    return ntri
+
+
+def triangle_sequence(creation_sequence):
+    """
+    Return triangle sequence for the given threshold graph creation sequence.
+
+    """
+    cs = creation_sequence
+    seq = []
+    dr = cs.count("d")  # number of d's to the right of the current pos
+    dcur = (dr - 1) * (dr - 2) // 2  # number of triangles through a node of clique dr
+    irun = 0  # number of i's in the last run
+    drun = 0  # number of d's in the last run
+    for i, sym in enumerate(cs):
+        if sym == "d":
+            drun += 1
+            tri = dcur + (dr - 1) * irun  # new triangles at this d
+        else:  # cs[i]="i":
+            if prevsym == "d":  # new string of i's
+                dcur += (dr - 1) * irun  # accumulate shared shortest paths
+                irun = 0  # reset i run counter
+                dr -= drun  # reduce number of d's to right
+                drun = 0  # reset d run counter
+            irun += 1
+            tri = dr * (dr - 1) // 2  # new triangles at this i
+        seq.append(tri)
+        prevsym = sym
+    return seq
+
+
+def cluster_sequence(creation_sequence):
+    """
+    Return cluster sequence for the given threshold graph creation sequence.
+    """
+    triseq = triangle_sequence(creation_sequence)
+    degseq = degree_sequence(creation_sequence)
+    cseq = []
+    for i, deg in enumerate(degseq):
+        tri = triseq[i]
+        if deg <= 1:  # isolated vertex or single pair gets cc 0
+            cseq.append(0)
+            continue
+        max_size = (deg * (deg - 1)) // 2
+        cseq.append(tri / max_size)
+    return cseq
+
+
+def degree_sequence(creation_sequence):
+    """
+    Return degree sequence for the threshold graph with the given
+    creation sequence
+    """
+    cs = creation_sequence  # alias
+    seq = []
+    rd = cs.count("d")  # number of d to the right
+    for i, sym in enumerate(cs):
+        if sym == "d":
+            rd -= 1
+            seq.append(rd + i)
+        else:
+            seq.append(rd)
+    return seq
+
+
+def density(creation_sequence):
+    """
+    Return the density of the graph with this creation_sequence.
+    The density is the fraction of possible edges present.
+    """
+    N = len(creation_sequence)
+    two_size = sum(degree_sequence(creation_sequence))
+    two_possible = N * (N - 1)
+    den = two_size / two_possible
+    return den
+
+
+def degree_correlation(creation_sequence):
+    """
+    Return the degree-degree correlation over all edges.
+    """
+    cs = creation_sequence
+    s1 = 0  # deg_i*deg_j
+    s2 = 0  # deg_i^2+deg_j^2
+    s3 = 0  # deg_i+deg_j
+    m = 0  # number of edges
+    rd = cs.count("d")  # number of d nodes to the right
+    rdi = [i for i, sym in enumerate(cs) if sym == "d"]  # index of "d"s
+    ds = degree_sequence(cs)
+    for i, sym in enumerate(cs):
+        if sym == "d":
+            rdi.pop(0)
+        degi = ds[i]
+        for dj in rdi:
+            degj = ds[dj]
+            s1 += degj * degi
+            s2 += degi**2 + degj**2
+            s3 += degi + degj
+            m += 1
+    denom = 2 * m * s2 - s3 * s3
+    numer = 4 * m * s1 - s3 * s3
+    if denom == 0:
+        if numer == 0:
+            return 1
+        raise ValueError(f"Zero Denominator but Numerator is {numer}")
+    return numer / denom
+
+
+def shortest_path(creation_sequence, u, v):
+    """
+    Find the shortest path between u and v in a
+    threshold graph G with the given creation_sequence.
+
+    For an unlabeled creation_sequence, the vertices
+    u and v must be integers in (0,len(sequence)) referring
+    to the position of the desired vertices in the sequence.
+
+    For a labeled creation_sequence, u and v are labels of vertices.
+
+    Use cs=creation_sequence(degree_sequence,with_labels=True)
+    to convert a degree sequence to a creation sequence.
+
+    Returns a list of vertices from u to v.
+    Example: if they are neighbors, it returns [u,v]
+    """
+    # Turn input sequence into a labeled creation sequence
+    first = creation_sequence[0]
+    if isinstance(first, str):  # creation sequence
+        cs = [(i, creation_sequence[i]) for i in range(len(creation_sequence))]
+    elif isinstance(first, tuple):  # labeled creation sequence
+        cs = creation_sequence[:]
+    elif isinstance(first, int):  # compact creation sequence
+        ci = uncompact(creation_sequence)
+        cs = [(i, ci[i]) for i in range(len(ci))]
+    else:
+        raise TypeError("Not a valid creation sequence type")
+
+    verts = [s[0] for s in cs]
+    if v not in verts:
+        raise ValueError(f"Vertex {v} not in graph from creation_sequence")
+    if u not in verts:
+        raise ValueError(f"Vertex {u} not in graph from creation_sequence")
+    # Done checking
+    if u == v:
+        return [u]
+
+    uindex = verts.index(u)
+    vindex = verts.index(v)
+    bigind = max(uindex, vindex)
+    if cs[bigind][1] == "d":
+        return [u, v]
+    # must be that cs[bigind][1]=='i'
+    cs = cs[bigind:]
+    while cs:
+        vert = cs.pop()
+        if vert[1] == "d":
+            return [u, vert[0], v]
+    # All after u are type 'i' so no connection
+    return -1
+
+
+def shortest_path_length(creation_sequence, i):
+    """
+    Return the shortest path length from indicated node to
+    every other node for the threshold graph with the given
+    creation sequence.
+    Node is indicated by index i in creation_sequence unless
+    creation_sequence is labeled in which case, i is taken to
+    be the label of the node.
+
+    Paths lengths in threshold graphs are at most 2.
+    Length to unreachable nodes is set to -1.
+    """
+    # Turn input sequence into a labeled creation sequence
+    first = creation_sequence[0]
+    if isinstance(first, str):  # creation sequence
+        if isinstance(creation_sequence, list):
+            cs = creation_sequence[:]
+        else:
+            cs = list(creation_sequence)
+    elif isinstance(first, tuple):  # labeled creation sequence
+        cs = [v[1] for v in creation_sequence]
+        i = [v[0] for v in creation_sequence].index(i)
+    elif isinstance(first, int):  # compact creation sequence
+        cs = uncompact(creation_sequence)
+    else:
+        raise TypeError("Not a valid creation sequence type")
+
+    # Compute
+    N = len(cs)
+    spl = [2] * N  # length 2 to every node
+    spl[i] = 0  # except self which is 0
+    # 1 for all d's to the right
+    for j in range(i + 1, N):
+        if cs[j] == "d":
+            spl[j] = 1
+    if cs[i] == "d":  # 1 for all nodes to the left
+        for j in range(i):
+            spl[j] = 1
+    # and -1 for any trailing i to indicate unreachable
+    for j in range(N - 1, 0, -1):
+        if cs[j] == "d":
+            break
+        spl[j] = -1
+    return spl
+
+
+def betweenness_sequence(creation_sequence, normalized=True):
+    """
+    Return betweenness for the threshold graph with the given creation
+    sequence.  The result is unscaled.  To scale the values
+    to the interval [0,1] divide by (n-1)*(n-2).
+    """
+    cs = creation_sequence
+    seq = []  # betweenness
+    lastchar = "d"  # first node is always a 'd'
+    dr = float(cs.count("d"))  # number of d's to the right of current pos
+    irun = 0  # number of i's in the last run
+    drun = 0  # number of d's in the last run
+    dlast = 0.0  # betweenness of last d
+    for i, c in enumerate(cs):
+        if c == "d":  # cs[i]=="d":
+            # betweenness = amt shared with earlier d's and i's
+            #             + new isolated nodes covered
+            #             + new paths to all previous nodes
+            b = dlast + (irun - 1) * irun / dr + 2 * irun * (i - drun - irun) / dr
+            drun += 1  # update counter
+        else:  # cs[i]="i":
+            if lastchar == "d":  # if this is a new run of i's
+                dlast = b  # accumulate betweenness
+                dr -= drun  # update number of d's to the right
+                drun = 0  # reset d counter
+                irun = 0  # reset i counter
+            b = 0  # isolated nodes have zero betweenness
+            irun += 1  # add another i to the run
+        seq.append(float(b))
+        lastchar = c
+
+    # normalize by the number of possible shortest paths
+    if normalized:
+        order = len(cs)
+        scale = 1.0 / ((order - 1) * (order - 2))
+        seq = [s * scale for s in seq]
+
+    return seq
+
+
+def eigenvectors(creation_sequence):
+    """
+    Return a 2-tuple of Laplacian eigenvalues and eigenvectors
+    for the threshold network with creation_sequence.
+    The first value is a list of eigenvalues.
+    The second value is a list of eigenvectors.
+    The lists are in the same order so corresponding eigenvectors
+    and eigenvalues are in the same position in the two lists.
+
+    Notice that the order of the eigenvalues returned by eigenvalues(cs)
+    may not correspond to the order of these eigenvectors.
+    """
+    ccs = make_compact(creation_sequence)
+    N = sum(ccs)
+    vec = [0] * N
+    val = vec[:]
+    # get number of type d nodes to the right (all for first node)
+    dr = sum(ccs[::2])
+
+    nn = ccs[0]
+    vec[0] = [1.0 / sqrt(N)] * N
+    val[0] = 0
+    e = dr
+    dr -= nn
+    type_d = True
+    i = 1
+    dd = 1
+    while dd < nn:
+        scale = 1.0 / sqrt(dd * dd + i)
+        vec[i] = i * [-scale] + [dd * scale] + [0] * (N - i - 1)
+        val[i] = e
+        i += 1
+        dd += 1
+    if len(ccs) == 1:
+        return (val, vec)
+    for nn in ccs[1:]:
+        scale = 1.0 / sqrt(nn * i * (i + nn))
+        vec[i] = i * [-nn * scale] + nn * [i * scale] + [0] * (N - i - nn)
+        # find eigenvalue
+        type_d = not type_d
+        if type_d:
+            e = i + dr
+            dr -= nn
+        else:
+            e = dr
+        val[i] = e
+        st = i
+        i += 1
+        dd = 1
+        while dd < nn:
+            scale = 1.0 / sqrt(i - st + dd * dd)
+            vec[i] = [0] * st + (i - st) * [-scale] + [dd * scale] + [0] * (N - i - 1)
+            val[i] = e
+            i += 1
+            dd += 1
+    return (val, vec)
+
+
+def spectral_projection(u, eigenpairs):
+    """
+    Returns the coefficients of each eigenvector
+    in a projection of the vector u onto the normalized
+    eigenvectors which are contained in eigenpairs.
+
+    eigenpairs should be a list of two objects.  The
+    first is a list of eigenvalues and the second a list
+    of eigenvectors.  The eigenvectors should be lists.
+
+    There's not a lot of error checking on lengths of
+    arrays, etc. so be careful.
+    """
+    coeff = []
+    evect = eigenpairs[1]
+    for ev in evect:
+        c = sum(evv * uv for (evv, uv) in zip(ev, u))
+        coeff.append(c)
+    return coeff
+
+
+def eigenvalues(creation_sequence):
+    """
+    Return sequence of eigenvalues of the Laplacian of the threshold
+    graph for the given creation_sequence.
+
+    Based on the Ferrer's diagram method.  The spectrum is integral
+    and is the conjugate of the degree sequence.
+
+    See::
+
+      @Article{degree-merris-1994,
+       author = {Russel Merris},
+       title = {Degree maximal graphs are Laplacian integral},
+       journal = {Linear Algebra Appl.},
+       year = {1994},
+       volume = {199},
+       pages = {381--389},
+      }
+
+    """
+    degseq = degree_sequence(creation_sequence)
+    degseq.sort()
+    eiglist = []  # zero is always one eigenvalue
+    eig = 0
+    row = len(degseq)
+    bigdeg = degseq.pop()
+    while row:
+        if bigdeg < row:
+            eiglist.append(eig)
+            row -= 1
+        else:
+            eig += 1
+            if degseq:
+                bigdeg = degseq.pop()
+            else:
+                bigdeg = 0
+    return eiglist
+
+
+# Threshold graph creation routines
+
+
+@py_random_state(2)
+def random_threshold_sequence(n, p, seed=None):
+    """
+    Create a random threshold sequence of size n.
+    A creation sequence is built by randomly choosing d's with
+    probability p and i's with probability 1-p.
+
+    s=nx.random_threshold_sequence(10,0.5)
+
+    returns a threshold sequence of length 10 with equal
+    probably of an i or a d at each position.
+
+    A "random" threshold graph can be built with
+
+    G=nx.threshold_graph(s)
+
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    """
+    if not (0 <= p <= 1):
+        raise ValueError("p must be in [0,1]")
+
+    cs = ["d"]  # threshold sequences always start with a d
+    for i in range(1, n):
+        if seed.random() < p:
+            cs.append("d")
+        else:
+            cs.append("i")
+    return cs
+
+
+# maybe *_d_threshold_sequence routines should
+# be (or be called from) a single routine with a more descriptive name
+# and a keyword parameter?
+def right_d_threshold_sequence(n, m):
+    """
+    Returns a "right-dominated" threshold sequence with `n` vertices and `m` edges.
+
+    Each vertex in the sequence is either dominant or isolated.
+    In the "right-dominated" version, once the basic sequence is formed,
+    isolated vertices may be flipped to dominant from the right in order
+    to reach the target number of edges.
+
+    Parameters
+    ----------
+    n : int
+        Number of vertices.
+    m : int
+        Number of edges.
+
+    Returns
+    -------
+    A list of 'd' (dominant) and 'i' (isolated) forming a right-dominated threshold sequence.
+
+    Raises
+    ------
+    ValueError
+        If `m` exceeds the maximum number of edges.
+
+    Examples
+    --------
+    >>> from networkx.algorithms.threshold import right_d_threshold_sequence
+    >>> right_d_threshold_sequence(5, 3)
+    ['d', 'i', 'i', 'd', 'i']
+    """
+
+    cs = ["d"] + ["i"] * (n - 1)  # create sequence with n insolated nodes
+
+    #  m  n * (n - 1) / 2:
+        raise ValueError("Too many edges for this many nodes.")
+
+    # connected case m >n-1
+    ind = n - 1
+    sum = n - 1
+    while sum < m:
+        cs[ind] = "d"
+        ind -= 1
+        sum += ind
+    ind = m - (sum - ind)
+    cs[ind] = "d"
+    return cs
+
+
+def left_d_threshold_sequence(n, m):
+    """
+    Returns a "left-dominated" threshold sequence with `n` vertices and `m` edges.
+
+    Each vertex in the sequence is either dominant or isolated.
+    In the "left-dominated" version, once the basic sequence is formed,
+    isolated vertices may be flipped to dominant from the left in order
+    to reach the target number of edges.
+
+    Parameters
+    ----------
+    n : int
+        Number of vertices.
+    m : int
+        Number of edges.
+
+    Returns
+    -------
+    A list of 'd' (dominant) and 'i' (isolated) forming a left-dominated threshold sequence.
+
+    Raises
+    ------
+    ValueError
+        If `m` exceeds the maximum number of edges.
+
+    Examples
+    --------
+    For certain small cases, both left and right dominated versions produce
+    the same sequence. However, for larger values of `m`, the difference in
+    flipping order becomes evident. For instance, compare the sequences for
+    ``n=6, m=8``:
+
+    >>> from networkx.algorithms.threshold import left_d_threshold_sequence
+    >>> seq = left_d_threshold_sequence(6, 8)
+    >>> seq
+    ['d', 'd', 'd', 'i', 'i', 'd']
+
+    In contrast, the right-dominated version yields:
+
+    >>> from networkx.algorithms.threshold import right_d_threshold_sequence
+    >>> right_seq = right_d_threshold_sequence(6, 8)
+    >>> right_seq
+    ['d', 'i', 'i', 'd', 'i', 'd']
+    """
+
+    cs = ["d"] + ["i"] * (n - 1)  # create sequence with n insolated nodes
+
+    #  m  n * (n - 1) / 2:
+        raise ValueError("Too many edges for this many nodes.")
+
+    # Connected case when M>N-1
+    cs[n - 1] = "d"
+    sum = n - 1
+    ind = 1
+    while sum < m:
+        cs[ind] = "d"
+        sum += ind
+        ind += 1
+    if sum > m:  # be sure not to change the first vertex
+        cs[sum - m] = "i"
+    return cs
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/time_dependent.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/time_dependent.py
new file mode 100644
index 0000000000000000000000000000000000000000..d67cdcf0b8eaecdef8497c77edd3144e96501173
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/time_dependent.py
@@ -0,0 +1,142 @@
+"""Time dependent algorithms."""
+
+import networkx as nx
+from networkx.utils import not_implemented_for
+
+__all__ = ["cd_index"]
+
+
+@not_implemented_for("undirected")
+@not_implemented_for("multigraph")
+@nx._dispatchable(node_attrs={"time": None, "weight": 1})
+def cd_index(G, node, time_delta, *, time="time", weight=None):
+    r"""Compute the CD index for `node` within the graph `G`.
+
+    Calculates the CD index for the given node of the graph,
+    considering only its predecessors who have the `time` attribute
+    smaller than or equal to the `time` attribute of the `node`
+    plus `time_delta`.
+
+    Parameters
+    ----------
+    G : graph
+       A directed networkx graph whose nodes have `time` attributes and optionally
+       `weight` attributes (if a weight is not given, it is considered 1).
+    node : node
+       The node for which the CD index is calculated.
+    time_delta : numeric or timedelta
+       Amount of time after the `time` attribute of the `node`. The value of
+       `time_delta` must support comparison with the `time` node attribute. For
+       example, if the `time` attribute of the nodes are `datetime.datetime`
+       objects, then `time_delta` should be a `datetime.timedelta` object.
+    time : string (Optional, default is "time")
+        The name of the node attribute that will be used for the calculations.
+    weight : string (Optional, default is None)
+        The name of the node attribute used as weight.
+
+    Returns
+    -------
+    float
+       The CD index calculated for the node `node` within the graph `G`.
+
+    Raises
+    ------
+    NetworkXError
+       If not all nodes have a `time` attribute or
+       `time_delta` and `time` attribute types are not compatible or
+       `n` equals 0.
+
+    NetworkXNotImplemented
+        If `G` is a non-directed graph or a multigraph.
+
+    Examples
+    --------
+    >>> from datetime import datetime, timedelta
+    >>> G = nx.DiGraph()
+    >>> nodes = {
+    ...     1: {"time": datetime(2015, 1, 1)},
+    ...     2: {"time": datetime(2012, 1, 1), "weight": 4},
+    ...     3: {"time": datetime(2010, 1, 1)},
+    ...     4: {"time": datetime(2008, 1, 1)},
+    ...     5: {"time": datetime(2014, 1, 1)},
+    ... }
+    >>> G.add_nodes_from([(n, nodes[n]) for n in nodes])
+    >>> edges = [(1, 3), (1, 4), (2, 3), (3, 4), (3, 5)]
+    >>> G.add_edges_from(edges)
+    >>> delta = timedelta(days=5 * 365)
+    >>> nx.cd_index(G, 3, time_delta=delta, time="time")
+    0.5
+    >>> nx.cd_index(G, 3, time_delta=delta, time="time", weight="weight")
+    0.12
+
+    Integers can also be used for the time values:
+    >>> node_times = {1: 2015, 2: 2012, 3: 2010, 4: 2008, 5: 2014}
+    >>> nx.set_node_attributes(G, node_times, "new_time")
+    >>> nx.cd_index(G, 3, time_delta=4, time="new_time")
+    0.5
+    >>> nx.cd_index(G, 3, time_delta=4, time="new_time", weight="weight")
+    0.12
+
+    Notes
+    -----
+    This method implements the algorithm for calculating the CD index,
+    as described in the paper by Funk and Owen-Smith [1]_. The CD index
+    is used in order to check how consolidating or destabilizing a patent
+    is, hence the nodes of the graph represent patents and the edges show
+    the citations between these patents. The mathematical model is given
+    below:
+
+    .. math::
+        CD_{t}=\frac{1}{n_{t}}\sum_{i=1}^{n}\frac{-2f_{it}b_{it}+f_{it}}{w_{it}},
+
+    where `f_{it}` equals 1 if `i` cites the focal patent else 0, `b_{it}` equals
+    1 if `i` cites any of the focal patents successors else 0, `n_{t}` is the number
+    of forward citations in `i` and `w_{it}` is a matrix of weight for patent `i`
+    at time `t`.
+
+    The `datetime.timedelta` package can lead to off-by-one issues when converting
+    from years to days. In the example above `timedelta(days=5 * 365)` looks like
+    5 years, but it isn't because of leap year days. So it gives the same result
+    as `timedelta(days=4 * 365)`. But using `timedelta(days=5 * 365 + 1)` gives
+    a 5 year delta **for this choice of years** but may not if the 5 year gap has
+    more than 1 leap year. To avoid these issues, use integers to represent years,
+    or be very careful when you convert units of time.
+
+    References
+    ----------
+    .. [1] Funk, Russell J., and Jason Owen-Smith.
+           "A dynamic network measure of technological change."
+           Management science 63, no. 3 (2017): 791-817.
+           http://russellfunk.org/cdindex/static/papers/funk_ms_2017.pdf
+
+    """
+    if not all(time in G.nodes[n] for n in G):
+        raise nx.NetworkXError("Not all nodes have a 'time' attribute.")
+
+    try:
+        # get target_date
+        target_date = G.nodes[node][time] + time_delta
+        # keep the predecessors that existed before the target date
+        pred = {i for i in G.pred[node] if G.nodes[i][time] <= target_date}
+    except:
+        raise nx.NetworkXError(
+            "Addition and comparison are not supported between 'time_delta' "
+            "and 'time' types."
+        )
+
+    # -1 if any edge between node's predecessors and node's successors, else 1
+    b = [-1 if any(j in G[i] for j in G[node]) else 1 for i in pred]
+
+    # n is size of the union of the focal node's predecessors and its successors' predecessors
+    n = len(pred.union(*(G.pred[s].keys() - {node} for s in G[node])))
+    if n == 0:
+        raise nx.NetworkXError("The cd index cannot be defined.")
+
+    # calculate cd index
+    if weight is None:
+        return round(sum(bi for bi in b) / n, 2)
+    else:
+        # If a node has the specified weight attribute, its weight is used in the calculation
+        # otherwise, a weight of 1 is assumed for that node
+        weights = [G.nodes[i].get(weight, 1) for i in pred]
+        return round(sum(bi / wt for bi, wt in zip(b, weights)) / n, 2)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tournament.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tournament.py
new file mode 100644
index 0000000000000000000000000000000000000000..bafaae226e6488c67f0022c2c1cc3808abbca5cf
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/tournament.py
@@ -0,0 +1,406 @@
+"""Functions concerning tournament graphs.
+
+A `tournament graph`_ is a complete oriented graph. In other words, it
+is a directed graph in which there is exactly one directed edge joining
+each pair of distinct nodes. For each function in this module that
+accepts a graph as input, you must provide a tournament graph. The
+responsibility is on the caller to ensure that the graph is a tournament
+graph:
+
+    >>> G = nx.DiGraph([(0, 1), (1, 2), (2, 0)])
+    >>> nx.is_tournament(G)
+    True
+
+To access the functions in this module, you must access them through the
+:mod:`networkx.tournament` module::
+
+    >>> nx.tournament.is_reachable(G, 0, 1)
+    True
+
+.. _tournament graph: https://en.wikipedia.org/wiki/Tournament_%28graph_theory%29
+
+"""
+
+from itertools import combinations
+
+import networkx as nx
+from networkx.utils import arbitrary_element, not_implemented_for, py_random_state
+
+__all__ = [
+    "hamiltonian_path",
+    "is_reachable",
+    "is_strongly_connected",
+    "is_tournament",
+    "random_tournament",
+    "score_sequence",
+    "tournament_matrix",
+]
+
+
+def index_satisfying(iterable, condition):
+    """Returns the index of the first element in `iterable` that
+    satisfies the given condition.
+
+    If no such element is found (that is, when the iterable is
+    exhausted), this returns the length of the iterable (that is, one
+    greater than the last index of the iterable).
+
+    `iterable` must not be empty. If `iterable` is empty, this
+    function raises :exc:`ValueError`.
+
+    """
+    # Pre-condition: iterable must not be empty.
+    for i, x in enumerate(iterable):
+        if condition(x):
+            return i
+    # If we reach the end of the iterable without finding an element
+    # that satisfies the condition, return the length of the iterable,
+    # which is one greater than the index of its last element. If the
+    # iterable was empty, `i` will not be defined, so we raise an
+    # exception.
+    try:
+        return i + 1
+    except NameError as err:
+        raise ValueError("iterable must be non-empty") from err
+
+
+@not_implemented_for("undirected")
+@not_implemented_for("multigraph")
+@nx._dispatchable
+def is_tournament(G):
+    """Returns True if and only if `G` is a tournament.
+
+    A tournament is a directed graph, with neither self-loops nor
+    multi-edges, in which there is exactly one directed edge joining
+    each pair of distinct nodes.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        A directed graph representing a tournament.
+
+    Returns
+    -------
+    bool
+        Whether the given graph is a tournament graph.
+
+    Examples
+    --------
+    >>> G = nx.DiGraph([(0, 1), (1, 2), (2, 0)])
+    >>> nx.is_tournament(G)
+    True
+
+    Notes
+    -----
+    Some definitions require a self-loop on each node, but that is not
+    the convention used here.
+
+    """
+    # In a tournament, there is exactly one directed edge joining each pair.
+    return (
+        all((v in G[u]) ^ (u in G[v]) for u, v in combinations(G, 2))
+        and nx.number_of_selfloops(G) == 0
+    )
+
+
+@not_implemented_for("undirected")
+@not_implemented_for("multigraph")
+@nx._dispatchable
+def hamiltonian_path(G):
+    """Returns a Hamiltonian path in the given tournament graph.
+
+    Each tournament has a Hamiltonian path. If furthermore, the
+    tournament is strongly connected, then the returned Hamiltonian path
+    is a Hamiltonian cycle (by joining the endpoints of the path).
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        A directed graph representing a tournament.
+
+    Returns
+    -------
+    path : list
+        A list of nodes which form a Hamiltonian path in `G`.
+
+    Examples
+    --------
+    >>> G = nx.DiGraph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)])
+    >>> nx.is_tournament(G)
+    True
+    >>> nx.tournament.hamiltonian_path(G)
+    [0, 1, 2, 3]
+
+    Notes
+    -----
+    This is a recursive implementation with an asymptotic running time
+    of $O(n^2)$, ignoring multiplicative polylogarithmic factors, where
+    $n$ is the number of nodes in the graph.
+
+    """
+    if len(G) == 0:
+        return []
+    if len(G) == 1:
+        return [arbitrary_element(G)]
+    v = arbitrary_element(G)
+    hampath = hamiltonian_path(G.subgraph(set(G) - {v}))
+    # Get the index of the first node in the path that does *not* have
+    # an edge to `v`, then insert `v` before that node.
+    index = index_satisfying(hampath, lambda u: v not in G[u])
+    hampath.insert(index, v)
+    return hampath
+
+
+@py_random_state(1)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def random_tournament(n, seed=None):
+    r"""Returns a random tournament graph on `n` nodes.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes in the returned graph.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    G : DiGraph
+        A tournament on `n` nodes, with exactly one directed edge joining
+        each pair of distinct nodes.
+
+    Notes
+    -----
+    This algorithm adds, for each pair of distinct nodes, an edge with
+    uniformly random orientation. In other words, `\binom{n}{2}` flips
+    of an unbiased coin decide the orientations of the edges in the
+    graph.
+
+    """
+    # Flip an unbiased coin for each pair of distinct nodes.
+    coins = (seed.random() for i in range((n * (n - 1)) // 2))
+    pairs = combinations(range(n), 2)
+    edges = ((u, v) if r < 0.5 else (v, u) for (u, v), r in zip(pairs, coins))
+    return nx.DiGraph(edges)
+
+
+@not_implemented_for("undirected")
+@not_implemented_for("multigraph")
+@nx._dispatchable
+def score_sequence(G):
+    """Returns the score sequence for the given tournament graph.
+
+    The score sequence is the sorted list of the out-degrees of the
+    nodes of the graph.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        A directed graph representing a tournament.
+
+    Returns
+    -------
+    list
+        A sorted list of the out-degrees of the nodes of `G`.
+
+    Examples
+    --------
+    >>> G = nx.DiGraph([(1, 0), (1, 3), (0, 2), (0, 3), (2, 1), (3, 2)])
+    >>> nx.is_tournament(G)
+    True
+    >>> nx.tournament.score_sequence(G)
+    [1, 1, 2, 2]
+
+    """
+    return sorted(d for v, d in G.out_degree())
+
+
+@not_implemented_for("undirected")
+@not_implemented_for("multigraph")
+@nx._dispatchable(preserve_edge_attrs={"G": {"weight": 1}})
+def tournament_matrix(G):
+    r"""Returns the tournament matrix for the given tournament graph.
+
+    This function requires SciPy.
+
+    The *tournament matrix* of a tournament graph with edge set *E* is
+    the matrix *T* defined by
+
+    .. math::
+
+       T_{i j} =
+       \begin{cases}
+       +1 & \text{if } (i, j) \in E \\
+       -1 & \text{if } (j, i) \in E \\
+       0 & \text{if } i == j.
+       \end{cases}
+
+    An equivalent definition is `T = A - A^T`, where *A* is the
+    adjacency matrix of the graph `G`.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        A directed graph representing a tournament.
+
+    Returns
+    -------
+    SciPy sparse array
+        The tournament matrix of the tournament graph `G`.
+
+    Raises
+    ------
+    ImportError
+        If SciPy is not available.
+
+    """
+    A = nx.adjacency_matrix(G)
+    return A - A.T
+
+
+@not_implemented_for("undirected")
+@not_implemented_for("multigraph")
+@nx._dispatchable
+def is_reachable(G, s, t):
+    """Decides whether there is a path from `s` to `t` in the
+    tournament.
+
+    This function is more theoretically efficient than the reachability
+    checks than the shortest path algorithms in
+    :mod:`networkx.algorithms.shortest_paths`.
+
+    The given graph **must** be a tournament, otherwise this function's
+    behavior is undefined.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        A directed graph representing a tournament.
+
+    s : node
+        A node in the graph.
+
+    t : node
+        A node in the graph.
+
+    Returns
+    -------
+    bool
+        Whether there is a path from `s` to `t` in `G`.
+
+    Examples
+    --------
+    >>> G = nx.DiGraph([(1, 0), (1, 3), (1, 2), (2, 3), (2, 0), (3, 0)])
+    >>> nx.is_tournament(G)
+    True
+    >>> nx.tournament.is_reachable(G, 1, 3)
+    True
+    >>> nx.tournament.is_reachable(G, 3, 2)
+    False
+
+    Notes
+    -----
+    Although this function is more theoretically efficient than the
+    generic shortest path functions, a speedup requires the use of
+    parallelism. Though it may in the future, the current implementation
+    does not use parallelism, thus you may not see much of a speedup.
+
+    This algorithm comes from [1].
+
+    References
+    ----------
+    .. [1] Tantau, Till.
+           "A note on the complexity of the reachability problem for
+           tournaments."
+           *Electronic Colloquium on Computational Complexity*. 2001.
+           
+    """
+
+    def two_neighborhood(G, v):
+        """Returns the set of nodes at distance at most two from `v`.
+
+        `G` must be a graph and `v` a node in that graph.
+
+        The returned set includes the nodes at distance zero (that is,
+        the node `v` itself), the nodes at distance one (that is, the
+        out-neighbors of `v`), and the nodes at distance two.
+
+        """
+        v_adj = G._adj[v]
+        return {
+            x
+            for x, x_pred in G._pred.items()
+            if x == v or x in v_adj or any(z in v_adj for z in x_pred)
+        }
+
+    def is_closed(G, S):
+        """Decides whether the given set of nodes is closed.
+
+        A set *S* of nodes is *closed* if for each node *u* in the graph
+        not in *S* and for each node *v* in *S*, there is an edge from
+        *u* to *v*.
+
+        """
+        return all(u in S or all(v in unbrs for v in S) for u, unbrs in G._adj.items())
+
+    neighborhoods = (two_neighborhood(G, v) for v in G)
+    return not any(s in S and t not in S and is_closed(G, S) for S in neighborhoods)
+
+
+@not_implemented_for("undirected")
+@not_implemented_for("multigraph")
+@nx._dispatchable(name="tournament_is_strongly_connected")
+def is_strongly_connected(G):
+    """Decides whether the given tournament is strongly connected.
+
+    This function is more theoretically efficient than the
+    :func:`~networkx.algorithms.components.is_strongly_connected`
+    function.
+
+    The given graph **must** be a tournament, otherwise this function's
+    behavior is undefined.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        A directed graph representing a tournament.
+
+    Returns
+    -------
+    bool
+        Whether the tournament is strongly connected.
+
+    Examples
+    --------
+    >>> G = nx.DiGraph([(0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (3, 0)])
+    >>> nx.is_tournament(G)
+    True
+    >>> nx.tournament.is_strongly_connected(G)
+    True
+    >>> G.remove_edge(3, 0)
+    >>> G.add_edge(0, 3)
+    >>> nx.is_tournament(G)
+    True
+    >>> nx.tournament.is_strongly_connected(G)
+    False
+
+    Notes
+    -----
+    Although this function is more theoretically efficient than the
+    generic strong connectivity function, a speedup requires the use of
+    parallelism. Though it may in the future, the current implementation
+    does not use parallelism, thus you may not see much of a speedup.
+
+    This algorithm comes from [1].
+
+    References
+    ----------
+    .. [1] Tantau, Till.
+           "A note on the complexity of the reachability problem for
+           tournaments."
+           *Electronic Colloquium on Computational Complexity*. 2001.
+           
+
+    """
+    return all(is_reachable(G, u, v) for u in G for v in G)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/traversal/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/traversal/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..93e6cdd08ca959835cc5c5f9a3e6dc353f4b217d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/traversal/__init__.py
@@ -0,0 +1,5 @@
+from .beamsearch import *
+from .breadth_first_search import *
+from .depth_first_search import *
+from .edgedfs import *
+from .edgebfs import *
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/traversal/beamsearch.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/traversal/beamsearch.py
new file mode 100644
index 0000000000000000000000000000000000000000..23fbe7bbb3f037eca4f7ede25b7edf6305356587
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/traversal/beamsearch.py
@@ -0,0 +1,90 @@
+"""Basic algorithms for breadth-first searching the nodes of a graph."""
+
+import networkx as nx
+
+__all__ = ["bfs_beam_edges"]
+
+
+@nx._dispatchable
+def bfs_beam_edges(G, source, value, width=None):
+    """Iterates over edges in a beam search.
+
+    The beam search is a generalized breadth-first search in which only
+    the "best" *w* neighbors of the current node are enqueued, where *w*
+    is the beam width and "best" is an application-specific
+    heuristic. In general, a beam search with a small beam width might
+    not visit each node in the graph.
+
+    .. note::
+
+       With the default value of ``width=None`` or `width` greater than the
+       maximum degree of the graph, this function equates to a slower
+       version of `~networkx.algorithms.traversal.breadth_first_search.bfs_edges`.
+       All nodes will be visited, though the order of the reported edges may
+       vary. In such cases, `value` has no effect - consider using `bfs_edges`
+       directly instead.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    source : node
+        Starting node for the breadth-first search; this function
+        iterates over only those edges in the component reachable from
+        this node.
+
+    value : function
+        A function that takes a node of the graph as input and returns a
+        real number indicating how "good" it is. A higher value means it
+        is more likely to be visited sooner during the search. When
+        visiting a new node, only the `width` neighbors with the highest
+        `value` are enqueued (in decreasing order of `value`).
+
+    width : int (default = None)
+        The beam width for the search. This is the number of neighbors
+        (ordered by `value`) to enqueue when visiting each new node.
+
+    Yields
+    ------
+    edge
+        Edges in the beam search starting from `source`, given as a pair
+        of nodes.
+
+    Examples
+    --------
+    To give nodes with, for example, a higher centrality precedence
+    during the search, set the `value` function to return the centrality
+    value of the node:
+
+    >>> G = nx.karate_club_graph()
+    >>> centrality = nx.eigenvector_centrality(G)
+    >>> list(nx.bfs_beam_edges(G, source=0, value=centrality.get, width=3))
+    [(0, 2), (0, 1), (0, 8), (2, 32), (1, 13), (8, 33)]
+    """
+
+    if width is None:
+        width = len(G)
+
+    def successors(v):
+        """Returns a list of the best neighbors of a node.
+
+        `v` is a node in the graph `G`.
+
+        The "best" neighbors are chosen according to the `value`
+        function (higher is better). Only the `width` best neighbors of
+        `v` are returned.
+        """
+        # TODO The Python documentation states that for small values, it
+        # is better to use `heapq.nlargest`. We should determine the
+        # threshold at which its better to use `heapq.nlargest()`
+        # instead of `sorted()[:]` and apply that optimization here.
+        #
+        # If `width` is greater than the number of neighbors of `v`, all
+        # neighbors are returned by the semantics of slicing in
+        # Python. This occurs in the special case that the user did not
+        # specify a `width`: in this case all neighbors are always
+        # returned, so this is just a (slower) implementation of
+        # `bfs_edges(G, source)` but with a sorted enqueue step.
+        return iter(sorted(G.neighbors(v), key=value, reverse=True)[:width])
+
+    yield from nx.generic_bfs_edges(G, source, successors)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/traversal/breadth_first_search.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/traversal/breadth_first_search.py
new file mode 100644
index 0000000000000000000000000000000000000000..71076ebb03c445ca842b040ff86e3a2d4e719af1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/traversal/breadth_first_search.py
@@ -0,0 +1,576 @@
+"""Basic algorithms for breadth-first searching the nodes of a graph."""
+
+from collections import deque
+
+import networkx as nx
+
+__all__ = [
+    "bfs_edges",
+    "bfs_tree",
+    "bfs_predecessors",
+    "bfs_successors",
+    "descendants_at_distance",
+    "bfs_layers",
+    "bfs_labeled_edges",
+    "generic_bfs_edges",
+]
+
+
+@nx._dispatchable
+def generic_bfs_edges(G, source, neighbors=None, depth_limit=None):
+    """Iterate over edges in a breadth-first search.
+
+    The breadth-first search begins at `source` and enqueues the
+    neighbors of newly visited nodes specified by the `neighbors`
+    function.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    source : node
+        Starting node for the breadth-first search; this function
+        iterates over only those edges in the component reachable from
+        this node.
+
+    neighbors : function
+        A function that takes a newly visited node of the graph as input
+        and returns an *iterator* (not just a list) of nodes that are
+        neighbors of that node with custom ordering. If not specified, this is
+        just the ``G.neighbors`` method, but in general it can be any function
+        that returns an iterator over some or all of the neighbors of a
+        given node, in any order.
+
+    depth_limit : int, optional(default=len(G))
+        Specify the maximum search depth.
+
+    Yields
+    ------
+    edge
+        Edges in the breadth-first search starting from `source`.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(7)
+    >>> list(nx.generic_bfs_edges(G, source=0))
+    [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
+    >>> list(nx.generic_bfs_edges(G, source=2))
+    [(2, 1), (2, 3), (1, 0), (3, 4), (4, 5), (5, 6)]
+    >>> list(nx.generic_bfs_edges(G, source=2, depth_limit=2))
+    [(2, 1), (2, 3), (1, 0), (3, 4)]
+
+    The `neighbors` param can be used to specify the visitation order of each
+    node's neighbors generically. In the following example, we modify the default
+    neighbor to return *odd* nodes first:
+
+    >>> def odd_first(n):
+    ...     return sorted(G.neighbors(n), key=lambda x: x % 2, reverse=True)
+
+    >>> G = nx.star_graph(5)
+    >>> list(nx.generic_bfs_edges(G, source=0))  # Default neighbor ordering
+    [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5)]
+    >>> list(nx.generic_bfs_edges(G, source=0, neighbors=odd_first))
+    [(0, 1), (0, 3), (0, 5), (0, 2), (0, 4)]
+
+    Notes
+    -----
+    This implementation is from `PADS`_, which was in the public domain
+    when it was first accessed in July, 2004.  The modifications
+    to allow depth limits are based on the Wikipedia article
+    "`Depth-limited-search`_".
+
+    .. _PADS: http://www.ics.uci.edu/~eppstein/PADS/BFS.py
+    .. _Depth-limited-search: https://en.wikipedia.org/wiki/Depth-limited_search
+    """
+    if neighbors is None:
+        neighbors = G.neighbors
+    if depth_limit is None:
+        depth_limit = len(G)
+
+    seen = {source}
+    n = len(G)
+    depth = 0
+    next_parents_children = [(source, neighbors(source))]
+    while next_parents_children and depth < depth_limit:
+        this_parents_children = next_parents_children
+        next_parents_children = []
+        for parent, children in this_parents_children:
+            for child in children:
+                if child not in seen:
+                    seen.add(child)
+                    next_parents_children.append((child, neighbors(child)))
+                    yield parent, child
+            if len(seen) == n:
+                return
+        depth += 1
+
+
+@nx._dispatchable
+def bfs_edges(G, source, reverse=False, depth_limit=None, sort_neighbors=None):
+    """Iterate over edges in a breadth-first-search starting at source.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    source : node
+       Specify starting node for breadth-first search; this function
+       iterates over only those edges in the component reachable from
+       this node.
+
+    reverse : bool, optional
+       If True traverse a directed graph in the reverse direction
+
+    depth_limit : int, optional(default=len(G))
+        Specify the maximum search depth
+
+    sort_neighbors : function (default=None)
+        A function that takes an iterator over nodes as the input, and
+        returns an iterable of the same nodes with a custom ordering.
+        For example, `sorted` will sort the nodes in increasing order.
+
+    Yields
+    ------
+    edge: 2-tuple of nodes
+       Yields edges resulting from the breadth-first search.
+
+    Examples
+    --------
+    To get the edges in a breadth-first search:
+
+    >>> G = nx.path_graph(3)
+    >>> list(nx.bfs_edges(G, 0))
+    [(0, 1), (1, 2)]
+    >>> list(nx.bfs_edges(G, source=0, depth_limit=1))
+    [(0, 1)]
+
+    To get the nodes in a breadth-first search order:
+
+    >>> G = nx.path_graph(3)
+    >>> root = 2
+    >>> edges = nx.bfs_edges(G, root)
+    >>> nodes = [root] + [v for u, v in edges]
+    >>> nodes
+    [2, 1, 0]
+
+    Notes
+    -----
+    The naming of this function is very similar to
+    :func:`~networkx.algorithms.traversal.edgebfs.edge_bfs`. The difference
+    is that ``edge_bfs`` yields edges even if they extend back to an already
+    explored node while this generator yields the edges of the tree that results
+    from a breadth-first-search (BFS) so no edges are reported if they extend
+    to already explored nodes. That means ``edge_bfs`` reports all edges while
+    ``bfs_edges`` only reports those traversed by a node-based BFS. Yet another
+    description is that ``bfs_edges`` reports the edges traversed during BFS
+    while ``edge_bfs`` reports all edges in the order they are explored.
+
+    Based on the breadth-first search implementation in PADS [1]_
+    by D. Eppstein, July 2004; with modifications to allow depth limits
+    as described in [2]_.
+
+    References
+    ----------
+    .. [1] http://www.ics.uci.edu/~eppstein/PADS/BFS.py.
+    .. [2] https://en.wikipedia.org/wiki/Depth-limited_search
+
+    See Also
+    --------
+    bfs_tree
+    :func:`~networkx.algorithms.traversal.depth_first_search.dfs_edges`
+    :func:`~networkx.algorithms.traversal.edgebfs.edge_bfs`
+
+    """
+    if reverse and G.is_directed():
+        successors = G.predecessors
+    else:
+        successors = G.neighbors
+
+    if sort_neighbors is not None:
+        yield from generic_bfs_edges(
+            G, source, lambda node: iter(sort_neighbors(successors(node))), depth_limit
+        )
+    else:
+        yield from generic_bfs_edges(G, source, successors, depth_limit)
+
+
+@nx._dispatchable(returns_graph=True)
+def bfs_tree(G, source, reverse=False, depth_limit=None, sort_neighbors=None):
+    """Returns an oriented tree constructed from of a breadth-first-search
+    starting at source.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    source : node
+       Specify starting node for breadth-first search
+
+    reverse : bool, optional
+       If True traverse a directed graph in the reverse direction
+
+    depth_limit : int, optional(default=len(G))
+        Specify the maximum search depth
+
+    sort_neighbors : function (default=None)
+        A function that takes an iterator over nodes as the input, and
+        returns an iterable of the same nodes with a custom ordering.
+        For example, `sorted` will sort the nodes in increasing order.
+
+    Returns
+    -------
+    T: NetworkX DiGraph
+       An oriented tree
+
+    Examples
+    --------
+    >>> G = nx.path_graph(3)
+    >>> list(nx.bfs_tree(G, 1).edges())
+    [(1, 0), (1, 2)]
+    >>> H = nx.Graph()
+    >>> nx.add_path(H, [0, 1, 2, 3, 4, 5, 6])
+    >>> nx.add_path(H, [2, 7, 8, 9, 10])
+    >>> sorted(list(nx.bfs_tree(H, source=3, depth_limit=3).edges()))
+    [(1, 0), (2, 1), (2, 7), (3, 2), (3, 4), (4, 5), (5, 6), (7, 8)]
+
+
+    Notes
+    -----
+    Based on http://www.ics.uci.edu/~eppstein/PADS/BFS.py
+    by D. Eppstein, July 2004. The modifications
+    to allow depth limits based on the Wikipedia article
+    "`Depth-limited-search`_".
+
+    .. _Depth-limited-search: https://en.wikipedia.org/wiki/Depth-limited_search
+
+    See Also
+    --------
+    dfs_tree
+    bfs_edges
+    edge_bfs
+    """
+    T = nx.DiGraph()
+    T.add_node(source)
+    edges_gen = bfs_edges(
+        G,
+        source,
+        reverse=reverse,
+        depth_limit=depth_limit,
+        sort_neighbors=sort_neighbors,
+    )
+    T.add_edges_from(edges_gen)
+    return T
+
+
+@nx._dispatchable
+def bfs_predecessors(G, source, depth_limit=None, sort_neighbors=None):
+    """Returns an iterator of predecessors in breadth-first-search from source.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    source : node
+       Specify starting node for breadth-first search
+
+    depth_limit : int, optional(default=len(G))
+        Specify the maximum search depth
+
+    sort_neighbors : function (default=None)
+        A function that takes an iterator over nodes as the input, and
+        returns an iterable of the same nodes with a custom ordering.
+        For example, `sorted` will sort the nodes in increasing order.
+
+    Returns
+    -------
+    pred: iterator
+        (node, predecessor) iterator where `predecessor` is the predecessor of
+        `node` in a breadth first search starting from `source`.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(3)
+    >>> dict(nx.bfs_predecessors(G, 0))
+    {1: 0, 2: 1}
+    >>> H = nx.Graph()
+    >>> H.add_edges_from([(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6)])
+    >>> dict(nx.bfs_predecessors(H, 0))
+    {1: 0, 2: 0, 3: 1, 4: 1, 5: 2, 6: 2}
+    >>> M = nx.Graph()
+    >>> nx.add_path(M, [0, 1, 2, 3, 4, 5, 6])
+    >>> nx.add_path(M, [2, 7, 8, 9, 10])
+    >>> sorted(nx.bfs_predecessors(M, source=1, depth_limit=3))
+    [(0, 1), (2, 1), (3, 2), (4, 3), (7, 2), (8, 7)]
+    >>> N = nx.DiGraph()
+    >>> nx.add_path(N, [0, 1, 2, 3, 4, 7])
+    >>> nx.add_path(N, [3, 5, 6, 7])
+    >>> sorted(nx.bfs_predecessors(N, source=2))
+    [(3, 2), (4, 3), (5, 3), (6, 5), (7, 4)]
+
+    Notes
+    -----
+    Based on http://www.ics.uci.edu/~eppstein/PADS/BFS.py
+    by D. Eppstein, July 2004. The modifications
+    to allow depth limits based on the Wikipedia article
+    "`Depth-limited-search`_".
+
+    .. _Depth-limited-search: https://en.wikipedia.org/wiki/Depth-limited_search
+
+    See Also
+    --------
+    bfs_tree
+    bfs_edges
+    edge_bfs
+    """
+    for s, t in bfs_edges(
+        G, source, depth_limit=depth_limit, sort_neighbors=sort_neighbors
+    ):
+        yield (t, s)
+
+
+@nx._dispatchable
+def bfs_successors(G, source, depth_limit=None, sort_neighbors=None):
+    """Returns an iterator of successors in breadth-first-search from source.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    source : node
+       Specify starting node for breadth-first search
+
+    depth_limit : int, optional(default=len(G))
+        Specify the maximum search depth
+
+    sort_neighbors : function (default=None)
+        A function that takes an iterator over nodes as the input, and
+        returns an iterable of the same nodes with a custom ordering.
+        For example, `sorted` will sort the nodes in increasing order.
+
+    Returns
+    -------
+    succ: iterator
+       (node, successors) iterator where `successors` is the non-empty list of
+       successors of `node` in a breadth first search from `source`.
+       To appear in the iterator, `node` must have successors.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(3)
+    >>> dict(nx.bfs_successors(G, 0))
+    {0: [1], 1: [2]}
+    >>> H = nx.Graph()
+    >>> H.add_edges_from([(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6)])
+    >>> dict(nx.bfs_successors(H, 0))
+    {0: [1, 2], 1: [3, 4], 2: [5, 6]}
+    >>> G = nx.Graph()
+    >>> nx.add_path(G, [0, 1, 2, 3, 4, 5, 6])
+    >>> nx.add_path(G, [2, 7, 8, 9, 10])
+    >>> dict(nx.bfs_successors(G, source=1, depth_limit=3))
+    {1: [0, 2], 2: [3, 7], 3: [4], 7: [8]}
+    >>> G = nx.DiGraph()
+    >>> nx.add_path(G, [0, 1, 2, 3, 4, 5])
+    >>> dict(nx.bfs_successors(G, source=3))
+    {3: [4], 4: [5]}
+
+    Notes
+    -----
+    Based on http://www.ics.uci.edu/~eppstein/PADS/BFS.py
+    by D. Eppstein, July 2004.The modifications
+    to allow depth limits based on the Wikipedia article
+    "`Depth-limited-search`_".
+
+    .. _Depth-limited-search: https://en.wikipedia.org/wiki/Depth-limited_search
+
+    See Also
+    --------
+    bfs_tree
+    bfs_edges
+    edge_bfs
+    """
+    parent = source
+    children = []
+    for p, c in bfs_edges(
+        G, source, depth_limit=depth_limit, sort_neighbors=sort_neighbors
+    ):
+        if p == parent:
+            children.append(c)
+            continue
+        yield (parent, children)
+        children = [c]
+        parent = p
+    yield (parent, children)
+
+
+@nx._dispatchable
+def bfs_layers(G, sources):
+    """Returns an iterator of all the layers in breadth-first search traversal.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        A graph over which to find the layers using breadth-first search.
+
+    sources : node in `G` or iterable of nodes in `G`
+        Specify starting nodes for single source or multiple sources
+        breadth-first search.
+
+    Yields
+    ------
+    layer : list of nodes
+        Yields list of nodes at the same distance from `sources`.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(5)
+    >>> dict(enumerate(nx.bfs_layers(G, [0, 4])))
+    {0: [0, 4], 1: [1, 3], 2: [2]}
+    >>> H = nx.Graph()
+    >>> H.add_edges_from([(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6)])
+    >>> dict(enumerate(nx.bfs_layers(H, [1])))
+    {0: [1], 1: [0, 3, 4], 2: [2], 3: [5, 6]}
+    >>> dict(enumerate(nx.bfs_layers(H, [1, 6])))
+    {0: [1, 6], 1: [0, 3, 4, 2], 2: [5]}
+    """
+    if sources in G:
+        sources = [sources]
+
+    visited = set(sources)
+    current_layer = list(visited)
+
+    for source in current_layer:
+        if source not in G:
+            raise nx.NetworkXError(f"The node {source} is not in the graph.")
+
+    # this is basically BFS, except that the current layer only stores the nodes at
+    # same distance from sources at each iteration
+    while current_layer:
+        yield current_layer
+        next_layer = []
+        for node in current_layer:
+            for child in G[node]:
+                if child not in visited:
+                    visited.add(child)
+                    next_layer.append(child)
+        current_layer = next_layer
+
+
+REVERSE_EDGE = "reverse"
+TREE_EDGE = "tree"
+FORWARD_EDGE = "forward"
+LEVEL_EDGE = "level"
+
+
+@nx._dispatchable
+def bfs_labeled_edges(G, sources):
+    """Iterate over edges in a breadth-first search (BFS) labeled by type.
+
+    We generate triple of the form (*u*, *v*, *d*), where (*u*, *v*) is the
+    edge being explored in the breadth-first search and *d* is one of the
+    strings 'tree', 'forward', 'level', or 'reverse'.  A 'tree' edge is one in
+    which *v* is first discovered and placed into the layer below *u*.  A
+    'forward' edge is one in which *u* is on the layer above *v* and *v* has
+    already been discovered.  A 'level' edge is one in which both *u* and *v*
+    occur on the same layer.  A 'reverse' edge is one in which *u* is on a layer
+    below *v*.
+
+    We emit each edge exactly once.  In an undirected graph, 'reverse' edges do
+    not occur, because each is discovered either as a 'tree' or 'forward' edge.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        A graph over which to find the layers using breadth-first search.
+
+    sources : node in `G` or list of nodes in `G`
+        Starting nodes for single source or multiple sources breadth-first search
+
+    Yields
+    ------
+    edges: generator
+       A generator of triples (*u*, *v*, *d*) where (*u*, *v*) is the edge being
+       explored and *d* is described above.
+
+    Examples
+    --------
+    >>> G = nx.cycle_graph(4, create_using=nx.DiGraph)
+    >>> list(nx.bfs_labeled_edges(G, 0))
+    [(0, 1, 'tree'), (1, 2, 'tree'), (2, 3, 'tree'), (3, 0, 'reverse')]
+    >>> G = nx.complete_graph(3)
+    >>> list(nx.bfs_labeled_edges(G, 0))
+    [(0, 1, 'tree'), (0, 2, 'tree'), (1, 2, 'level')]
+    >>> list(nx.bfs_labeled_edges(G, [0, 1]))
+    [(0, 1, 'level'), (0, 2, 'tree'), (1, 2, 'forward')]
+    """
+    if sources in G:
+        sources = [sources]
+
+    neighbors = G._adj
+    directed = G.is_directed()
+    visited = set()
+    visit = visited.discard if directed else visited.add
+    # We use visited in a negative sense, so the visited set stays empty for the
+    # directed case and level edges are reported on their first occurrence in
+    # the undirected case.  Note our use of visited.discard -- this is built-in
+    # thus somewhat faster than a python-defined def nop(x): pass
+    depth = {s: 0 for s in sources}
+    queue = deque(depth.items())
+    push = queue.append
+    pop = queue.popleft
+    while queue:
+        u, du = pop()
+        for v in neighbors[u]:
+            if v not in depth:
+                depth[v] = dv = du + 1
+                push((v, dv))
+                yield u, v, TREE_EDGE
+            else:
+                dv = depth[v]
+                if du == dv:
+                    if v not in visited:
+                        yield u, v, LEVEL_EDGE
+                elif du < dv:
+                    yield u, v, FORWARD_EDGE
+                elif directed:
+                    yield u, v, REVERSE_EDGE
+        visit(u)
+
+
+@nx._dispatchable
+def descendants_at_distance(G, source, distance):
+    """Returns all nodes at a fixed `distance` from `source` in `G`.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        A graph
+    source : node in `G`
+    distance : the distance of the wanted nodes from `source`
+
+    Returns
+    -------
+    set()
+        The descendants of `source` in `G` at the given `distance` from `source`
+
+    Examples
+    --------
+    >>> G = nx.path_graph(5)
+    >>> nx.descendants_at_distance(G, 2, 2)
+    {0, 4}
+    >>> H = nx.DiGraph()
+    >>> H.add_edges_from([(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6)])
+    >>> nx.descendants_at_distance(H, 0, 2)
+    {3, 4, 5, 6}
+    >>> nx.descendants_at_distance(H, 5, 0)
+    {5}
+    >>> nx.descendants_at_distance(H, 5, 1)
+    set()
+    """
+    if source not in G:
+        raise nx.NetworkXError(f"The node {source} is not in the graph.")
+
+    bfs_generator = nx.bfs_layers(G, source)
+    for i, layer in enumerate(bfs_generator):
+        if i == distance:
+            return set(layer)
+    return set()
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/traversal/depth_first_search.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/traversal/depth_first_search.py
new file mode 100644
index 0000000000000000000000000000000000000000..5bac5ecfd1cbefcba5707cac2885ef32987ee98b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/traversal/depth_first_search.py
@@ -0,0 +1,529 @@
+"""Basic algorithms for depth-first searching the nodes of a graph."""
+
+from collections import defaultdict
+
+import networkx as nx
+
+__all__ = [
+    "dfs_edges",
+    "dfs_tree",
+    "dfs_predecessors",
+    "dfs_successors",
+    "dfs_preorder_nodes",
+    "dfs_postorder_nodes",
+    "dfs_labeled_edges",
+]
+
+
+@nx._dispatchable
+def dfs_edges(G, source=None, depth_limit=None, *, sort_neighbors=None):
+    """Iterate over edges in a depth-first-search (DFS).
+
+    Perform a depth-first-search over the nodes of `G` and yield
+    the edges in order. This may not generate all edges in `G`
+    (see `~networkx.algorithms.traversal.edgedfs.edge_dfs`).
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    source : node, optional
+       Specify starting node for depth-first search and yield edges in
+       the component reachable from source.
+
+    depth_limit : int, optional (default=len(G))
+       Specify the maximum search depth.
+
+    sort_neighbors : function (default=None)
+        A function that takes an iterator over nodes as the input, and
+        returns an iterable of the same nodes with a custom ordering.
+        For example, `sorted` will sort the nodes in increasing order.
+
+    Yields
+    ------
+    edge: 2-tuple of nodes
+       Yields edges resulting from the depth-first-search.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(5)
+    >>> list(nx.dfs_edges(G, source=0))
+    [(0, 1), (1, 2), (2, 3), (3, 4)]
+    >>> list(nx.dfs_edges(G, source=0, depth_limit=2))
+    [(0, 1), (1, 2)]
+
+    Notes
+    -----
+    If a source is not specified then a source is chosen arbitrarily and
+    repeatedly until all components in the graph are searched.
+
+    The implementation of this function is adapted from David Eppstein's
+    depth-first search function in PADS [1]_, with modifications
+    to allow depth limits based on the Wikipedia article
+    "Depth-limited search" [2]_.
+
+    See Also
+    --------
+    dfs_preorder_nodes
+    dfs_postorder_nodes
+    dfs_labeled_edges
+    :func:`~networkx.algorithms.traversal.edgedfs.edge_dfs`
+    :func:`~networkx.algorithms.traversal.breadth_first_search.bfs_edges`
+
+    References
+    ----------
+    .. [1] http://www.ics.uci.edu/~eppstein/PADS
+    .. [2] https://en.wikipedia.org/wiki/Depth-limited_search
+    """
+    if source is None:
+        # edges for all components
+        nodes = G
+    else:
+        # edges for components with source
+        nodes = [source]
+    if depth_limit is None:
+        depth_limit = len(G)
+
+    get_children = (
+        G.neighbors
+        if sort_neighbors is None
+        else lambda n: iter(sort_neighbors(G.neighbors(n)))
+    )
+
+    visited = set()
+    for start in nodes:
+        if start in visited:
+            continue
+        visited.add(start)
+        stack = [(start, get_children(start))]
+        depth_now = 1
+        while stack:
+            parent, children = stack[-1]
+            for child in children:
+                if child not in visited:
+                    yield parent, child
+                    visited.add(child)
+                    if depth_now < depth_limit:
+                        stack.append((child, get_children(child)))
+                        depth_now += 1
+                        break
+            else:
+                stack.pop()
+                depth_now -= 1
+
+
+@nx._dispatchable(returns_graph=True)
+def dfs_tree(G, source=None, depth_limit=None, *, sort_neighbors=None):
+    """Returns oriented tree constructed from a depth-first-search from source.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    source : node, optional
+       Specify starting node for depth-first search.
+
+    depth_limit : int, optional (default=len(G))
+       Specify the maximum search depth.
+
+    sort_neighbors : function (default=None)
+        A function that takes an iterator over nodes as the input, and
+        returns an iterable of the same nodes with a custom ordering.
+        For example, `sorted` will sort the nodes in increasing order.
+
+    Returns
+    -------
+    T : NetworkX DiGraph
+       An oriented tree
+
+    Examples
+    --------
+    >>> G = nx.path_graph(5)
+    >>> T = nx.dfs_tree(G, source=0, depth_limit=2)
+    >>> list(T.edges())
+    [(0, 1), (1, 2)]
+    >>> T = nx.dfs_tree(G, source=0)
+    >>> list(T.edges())
+    [(0, 1), (1, 2), (2, 3), (3, 4)]
+
+    See Also
+    --------
+    dfs_preorder_nodes
+    dfs_postorder_nodes
+    dfs_labeled_edges
+    :func:`~networkx.algorithms.traversal.edgedfs.edge_dfs`
+    :func:`~networkx.algorithms.traversal.breadth_first_search.bfs_tree`
+    """
+    T = nx.DiGraph()
+    if source is None:
+        T.add_nodes_from(G)
+    else:
+        T.add_node(source)
+    T.add_edges_from(dfs_edges(G, source, depth_limit, sort_neighbors=sort_neighbors))
+    return T
+
+
+@nx._dispatchable
+def dfs_predecessors(G, source=None, depth_limit=None, *, sort_neighbors=None):
+    """Returns dictionary of predecessors in depth-first-search from source.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    source : node, optional
+       Specify starting node for depth-first search.
+       Note that you will get predecessors for all nodes in the
+       component containing `source`. This input only specifies
+       where the DFS starts.
+
+    depth_limit : int, optional (default=len(G))
+       Specify the maximum search depth.
+
+    sort_neighbors : function (default=None)
+        A function that takes an iterator over nodes as the input, and
+        returns an iterable of the same nodes with a custom ordering.
+        For example, `sorted` will sort the nodes in increasing order.
+
+    Returns
+    -------
+    pred: dict
+       A dictionary with nodes as keys and predecessor nodes as values.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> nx.dfs_predecessors(G, source=0)
+    {1: 0, 2: 1, 3: 2}
+    >>> nx.dfs_predecessors(G, source=0, depth_limit=2)
+    {1: 0, 2: 1}
+
+    Notes
+    -----
+    If a source is not specified then a source is chosen arbitrarily and
+    repeatedly until all components in the graph are searched.
+
+    The implementation of this function is adapted from David Eppstein's
+    depth-first search function in `PADS`_, with modifications
+    to allow depth limits based on the Wikipedia article
+    "`Depth-limited search`_".
+
+    .. _PADS: http://www.ics.uci.edu/~eppstein/PADS
+    .. _Depth-limited search: https://en.wikipedia.org/wiki/Depth-limited_search
+
+    See Also
+    --------
+    dfs_preorder_nodes
+    dfs_postorder_nodes
+    dfs_labeled_edges
+    :func:`~networkx.algorithms.traversal.edgedfs.edge_dfs`
+    :func:`~networkx.algorithms.traversal.breadth_first_search.bfs_tree`
+    """
+    return {
+        t: s
+        for s, t in dfs_edges(G, source, depth_limit, sort_neighbors=sort_neighbors)
+    }
+
+
+@nx._dispatchable
+def dfs_successors(G, source=None, depth_limit=None, *, sort_neighbors=None):
+    """Returns dictionary of successors in depth-first-search from source.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    source : node, optional
+       Specify starting node for depth-first search.
+       Note that you will get successors for all nodes in the
+       component containing `source`. This input only specifies
+       where the DFS starts.
+
+    depth_limit : int, optional (default=len(G))
+       Specify the maximum search depth.
+
+    sort_neighbors : function (default=None)
+        A function that takes an iterator over nodes as the input, and
+        returns an iterable of the same nodes with a custom ordering.
+        For example, `sorted` will sort the nodes in increasing order.
+
+    Returns
+    -------
+    succ: dict
+       A dictionary with nodes as keys and list of successor nodes as values.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(5)
+    >>> nx.dfs_successors(G, source=0)
+    {0: [1], 1: [2], 2: [3], 3: [4]}
+    >>> nx.dfs_successors(G, source=0, depth_limit=2)
+    {0: [1], 1: [2]}
+
+    Notes
+    -----
+    If a source is not specified then a source is chosen arbitrarily and
+    repeatedly until all components in the graph are searched.
+
+    The implementation of this function is adapted from David Eppstein's
+    depth-first search function in `PADS`_, with modifications
+    to allow depth limits based on the Wikipedia article
+    "`Depth-limited search`_".
+
+    .. _PADS: http://www.ics.uci.edu/~eppstein/PADS
+    .. _Depth-limited search: https://en.wikipedia.org/wiki/Depth-limited_search
+
+    See Also
+    --------
+    dfs_preorder_nodes
+    dfs_postorder_nodes
+    dfs_labeled_edges
+    :func:`~networkx.algorithms.traversal.edgedfs.edge_dfs`
+    :func:`~networkx.algorithms.traversal.breadth_first_search.bfs_tree`
+    """
+    d = defaultdict(list)
+    for s, t in dfs_edges(
+        G,
+        source=source,
+        depth_limit=depth_limit,
+        sort_neighbors=sort_neighbors,
+    ):
+        d[s].append(t)
+    return dict(d)
+
+
+@nx._dispatchable
+def dfs_postorder_nodes(G, source=None, depth_limit=None, *, sort_neighbors=None):
+    """Generate nodes in a depth-first-search post-ordering starting at source.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    source : node, optional
+       Specify starting node for depth-first search.
+
+    depth_limit : int, optional (default=len(G))
+       Specify the maximum search depth.
+
+    sort_neighbors : function (default=None)
+        A function that takes an iterator over nodes as the input, and
+        returns an iterable of the same nodes with a custom ordering.
+        For example, `sorted` will sort the nodes in increasing order.
+
+    Returns
+    -------
+    nodes: generator
+       A generator of nodes in a depth-first-search post-ordering.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(5)
+    >>> list(nx.dfs_postorder_nodes(G, source=0))
+    [4, 3, 2, 1, 0]
+    >>> list(nx.dfs_postorder_nodes(G, source=0, depth_limit=2))
+    [1, 0]
+
+    Notes
+    -----
+    If a source is not specified then a source is chosen arbitrarily and
+    repeatedly until all components in the graph are searched.
+
+    The implementation of this function is adapted from David Eppstein's
+    depth-first search function in `PADS`_, with modifications
+    to allow depth limits based on the Wikipedia article
+    "`Depth-limited search`_".
+
+    .. _PADS: http://www.ics.uci.edu/~eppstein/PADS
+    .. _Depth-limited search: https://en.wikipedia.org/wiki/Depth-limited_search
+
+    See Also
+    --------
+    dfs_edges
+    dfs_preorder_nodes
+    dfs_labeled_edges
+    :func:`~networkx.algorithms.traversal.edgedfs.edge_dfs`
+    :func:`~networkx.algorithms.traversal.breadth_first_search.bfs_tree`
+    """
+    edges = nx.dfs_labeled_edges(
+        G, source=source, depth_limit=depth_limit, sort_neighbors=sort_neighbors
+    )
+    return (v for u, v, d in edges if d == "reverse")
+
+
+@nx._dispatchable
+def dfs_preorder_nodes(G, source=None, depth_limit=None, *, sort_neighbors=None):
+    """Generate nodes in a depth-first-search pre-ordering starting at source.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    source : node, optional
+       Specify starting node for depth-first search and return nodes in
+       the component reachable from source.
+
+    depth_limit : int, optional (default=len(G))
+       Specify the maximum search depth.
+
+    sort_neighbors : function (default=None)
+        A function that takes an iterator over nodes as the input, and
+        returns an iterable of the same nodes with a custom ordering.
+        For example, `sorted` will sort the nodes in increasing order.
+
+    Returns
+    -------
+    nodes: generator
+       A generator of nodes in a depth-first-search pre-ordering.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(5)
+    >>> list(nx.dfs_preorder_nodes(G, source=0))
+    [0, 1, 2, 3, 4]
+    >>> list(nx.dfs_preorder_nodes(G, source=0, depth_limit=2))
+    [0, 1, 2]
+
+    Notes
+    -----
+    If a source is not specified then a source is chosen arbitrarily and
+    repeatedly until all components in the graph are searched.
+
+    The implementation of this function is adapted from David Eppstein's
+    depth-first search function in `PADS`_, with modifications
+    to allow depth limits based on the Wikipedia article
+    "`Depth-limited search`_".
+
+    .. _PADS: http://www.ics.uci.edu/~eppstein/PADS
+    .. _Depth-limited search: https://en.wikipedia.org/wiki/Depth-limited_search
+
+    See Also
+    --------
+    dfs_edges
+    dfs_postorder_nodes
+    dfs_labeled_edges
+    :func:`~networkx.algorithms.traversal.breadth_first_search.bfs_edges`
+    """
+    edges = nx.dfs_labeled_edges(
+        G, source=source, depth_limit=depth_limit, sort_neighbors=sort_neighbors
+    )
+    return (v for u, v, d in edges if d == "forward")
+
+
+@nx._dispatchable
+def dfs_labeled_edges(G, source=None, depth_limit=None, *, sort_neighbors=None):
+    """Iterate over edges in a depth-first-search (DFS) labeled by type.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    source : node, optional
+       Specify starting node for depth-first search and return edges in
+       the component reachable from source.
+
+    depth_limit : int, optional (default=len(G))
+       Specify the maximum search depth.
+
+    sort_neighbors : function (default=None)
+        A function that takes an iterator over nodes as the input, and
+        returns an iterable of the same nodes with a custom ordering.
+        For example, `sorted` will sort the nodes in increasing order.
+
+    Returns
+    -------
+    edges: generator
+       A generator of triples of the form (*u*, *v*, *d*), where (*u*,
+       *v*) is the edge being explored in the depth-first search and *d*
+       is one of the strings 'forward', 'nontree', 'reverse', or 'reverse-depth_limit'.
+       A 'forward' edge is one in which *u* has been visited but *v* has
+       not. A 'nontree' edge is one in which both *u* and *v* have been
+       visited but the edge is not in the DFS tree. A 'reverse' edge is
+       one in which both *u* and *v* have been visited and the edge is in
+       the DFS tree. When the `depth_limit` is reached via a 'forward' edge,
+       a 'reverse' edge is immediately generated rather than the subtree
+       being explored. To indicate this flavor of 'reverse' edge, the string
+       yielded is 'reverse-depth_limit'.
+
+    Examples
+    --------
+
+    The labels reveal the complete transcript of the depth-first search
+    algorithm in more detail than, for example, :func:`dfs_edges`::
+
+        >>> from pprint import pprint
+        >>>
+        >>> G = nx.DiGraph([(0, 1), (1, 2), (2, 1)])
+        >>> pprint(list(nx.dfs_labeled_edges(G, source=0)))
+        [(0, 0, 'forward'),
+         (0, 1, 'forward'),
+         (1, 2, 'forward'),
+         (2, 1, 'nontree'),
+         (1, 2, 'reverse'),
+         (0, 1, 'reverse'),
+         (0, 0, 'reverse')]
+
+    Notes
+    -----
+    If a source is not specified then a source is chosen arbitrarily and
+    repeatedly until all components in the graph are searched.
+
+    The implementation of this function is adapted from David Eppstein's
+    depth-first search function in `PADS`_, with modifications
+    to allow depth limits based on the Wikipedia article
+    "`Depth-limited search`_".
+
+    .. _PADS: http://www.ics.uci.edu/~eppstein/PADS
+    .. _Depth-limited search: https://en.wikipedia.org/wiki/Depth-limited_search
+
+    See Also
+    --------
+    dfs_edges
+    dfs_preorder_nodes
+    dfs_postorder_nodes
+    """
+    # Based on http://www.ics.uci.edu/~eppstein/PADS/DFS.py
+    # by D. Eppstein, July 2004.
+    if source is None:
+        # edges for all components
+        nodes = G
+    else:
+        # edges for components with source
+        nodes = [source]
+    if depth_limit is None:
+        depth_limit = len(G)
+
+    get_children = (
+        G.neighbors
+        if sort_neighbors is None
+        else lambda n: iter(sort_neighbors(G.neighbors(n)))
+    )
+
+    visited = set()
+    for start in nodes:
+        if start in visited:
+            continue
+        yield start, start, "forward"
+        visited.add(start)
+        stack = [(start, get_children(start))]
+        depth_now = 1
+        while stack:
+            parent, children = stack[-1]
+            for child in children:
+                if child in visited:
+                    yield parent, child, "nontree"
+                else:
+                    yield parent, child, "forward"
+                    visited.add(child)
+                    if depth_now < depth_limit:
+                        stack.append((child, iter(get_children(child))))
+                        depth_now += 1
+                        break
+                    else:
+                        yield parent, child, "reverse-depth_limit"
+            else:
+                stack.pop()
+                depth_now -= 1
+                if stack:
+                    yield stack[-1][0], parent, "reverse"
+        yield start, start, "reverse"
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/traversal/edgebfs.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/traversal/edgebfs.py
new file mode 100644
index 0000000000000000000000000000000000000000..2f468e10b3ebbf43888ac6761a473bbc2e1b106b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/traversal/edgebfs.py
@@ -0,0 +1,185 @@
+"""
+=============================
+Breadth First Search on Edges
+=============================
+
+Algorithms for a breadth-first traversal of edges in a graph.
+
+"""
+
+from collections import deque
+
+import networkx as nx
+
+FORWARD = "forward"
+REVERSE = "reverse"
+
+__all__ = ["edge_bfs"]
+
+
+@nx._dispatchable
+def edge_bfs(G, source=None, orientation=None):
+    """A directed, breadth-first-search of edges in `G`, beginning at `source`.
+
+    Yield the edges of G in a breadth-first-search order continuing until
+    all edges are generated.
+
+    Parameters
+    ----------
+    G : graph
+        A directed/undirected graph/multigraph.
+
+    source : node, list of nodes
+        The node from which the traversal begins. If None, then a source
+        is chosen arbitrarily and repeatedly until all edges from each node in
+        the graph are searched.
+
+    orientation : None | 'original' | 'reverse' | 'ignore' (default: None)
+        For directed graphs and directed multigraphs, edge traversals need not
+        respect the original orientation of the edges.
+        When set to 'reverse' every edge is traversed in the reverse direction.
+        When set to 'ignore', every edge is treated as undirected.
+        When set to 'original', every edge is treated as directed.
+        In all three cases, the yielded edge tuples add a last entry to
+        indicate the direction in which that edge was traversed.
+        If orientation is None, the yielded edge has no direction indicated.
+        The direction is respected, but not reported.
+
+    Yields
+    ------
+    edge : directed edge
+        A directed edge indicating the path taken by the breadth-first-search.
+        For graphs, `edge` is of the form `(u, v)` where `u` and `v`
+        are the tail and head of the edge as determined by the traversal.
+        For multigraphs, `edge` is of the form `(u, v, key)`, where `key` is
+        the key of the edge. When the graph is directed, then `u` and `v`
+        are always in the order of the actual directed edge.
+        If orientation is not None then the edge tuple is extended to include
+        the direction of traversal ('forward' or 'reverse') on that edge.
+
+    Examples
+    --------
+    >>> from pprint import pprint
+    >>> nodes = [0, 1, 2, 3]
+    >>> edges = [(0, 1), (1, 0), (1, 0), (2, 0), (2, 1), (3, 1)]
+
+    >>> list(nx.edge_bfs(nx.Graph(edges), nodes))
+    [(0, 1), (0, 2), (1, 2), (1, 3)]
+
+    >>> list(nx.edge_bfs(nx.DiGraph(edges), nodes))
+    [(0, 1), (1, 0), (2, 0), (2, 1), (3, 1)]
+
+    >>> list(nx.edge_bfs(nx.MultiGraph(edges), nodes))
+    [(0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 2, 0), (1, 2, 0), (1, 3, 0)]
+
+    >>> list(nx.edge_bfs(nx.MultiDiGraph(edges), nodes))
+    [(0, 1, 0), (1, 0, 0), (1, 0, 1), (2, 0, 0), (2, 1, 0), (3, 1, 0)]
+
+    >>> list(nx.edge_bfs(nx.DiGraph(edges), nodes, orientation="ignore"))
+    [(0, 1, 'forward'), (1, 0, 'reverse'), (2, 0, 'reverse'), (2, 1, 'reverse'), (3, 1, 'reverse')]
+
+    >>> elist = list(nx.edge_bfs(nx.MultiDiGraph(edges), nodes, orientation="ignore"))
+    >>> pprint(elist)
+    [(0, 1, 0, 'forward'),
+     (1, 0, 0, 'reverse'),
+     (1, 0, 1, 'reverse'),
+     (2, 0, 0, 'reverse'),
+     (2, 1, 0, 'reverse'),
+     (3, 1, 0, 'reverse')]
+
+    Notes
+    -----
+    The goal of this function is to visit edges. It differs from the more
+    familiar breadth-first-search of nodes, as provided by
+    :func:`networkx.algorithms.traversal.breadth_first_search.bfs_edges`, in
+    that it does not stop once every node has been visited. In a directed graph
+    with edges [(0, 1), (1, 2), (2, 1)], the edge (2, 1) would not be visited
+    if not for the functionality provided by this function.
+
+    The naming of this function is very similar to bfs_edges. The difference
+    is that 'edge_bfs' yields edges even if they extend back to an already
+    explored node while 'bfs_edges' yields the edges of the tree that results
+    from a breadth-first-search (BFS) so no edges are reported if they extend
+    to already explored nodes. That means 'edge_bfs' reports all edges while
+    'bfs_edges' only report those traversed by a node-based BFS. Yet another
+    description is that 'bfs_edges' reports the edges traversed during BFS
+    while 'edge_bfs' reports all edges in the order they are explored.
+
+    See Also
+    --------
+    bfs_edges
+    bfs_tree
+    edge_dfs
+
+    """
+    nodes = list(G.nbunch_iter(source))
+    if not nodes:
+        return
+
+    directed = G.is_directed()
+    kwds = {"data": False}
+    if G.is_multigraph() is True:
+        kwds["keys"] = True
+
+    # set up edge lookup
+    if orientation is None:
+
+        def edges_from(node):
+            return iter(G.edges(node, **kwds))
+
+    elif not directed or orientation == "original":
+
+        def edges_from(node):
+            for e in G.edges(node, **kwds):
+                yield e + (FORWARD,)
+
+    elif orientation == "reverse":
+
+        def edges_from(node):
+            for e in G.in_edges(node, **kwds):
+                yield e + (REVERSE,)
+
+    elif orientation == "ignore":
+
+        def edges_from(node):
+            for e in G.edges(node, **kwds):
+                yield e + (FORWARD,)
+            for e in G.in_edges(node, **kwds):
+                yield e + (REVERSE,)
+
+    else:
+        raise nx.NetworkXError("invalid orientation argument.")
+
+    if directed:
+        neighbors = G.successors
+
+        def edge_id(edge):
+            # remove direction indicator
+            return edge[:-1] if orientation is not None else edge
+
+    else:
+        neighbors = G.neighbors
+
+        def edge_id(edge):
+            return (frozenset(edge[:2]),) + edge[2:]
+
+    check_reverse = directed and orientation in ("reverse", "ignore")
+
+    # start BFS
+    visited_nodes = set(nodes)
+    visited_edges = set()
+    queue = deque([(n, edges_from(n)) for n in nodes])
+    while queue:
+        parent, children_edges = queue.popleft()
+        for edge in children_edges:
+            if check_reverse and edge[-1] == REVERSE:
+                child = edge[0]
+            else:
+                child = edge[1]
+            if child not in visited_nodes:
+                visited_nodes.add(child)
+                queue.append((child, edges_from(child)))
+            edgeid = edge_id(edge)
+            if edgeid not in visited_edges:
+                visited_edges.add(edgeid)
+                yield edge
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/traversal/edgedfs.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/traversal/edgedfs.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8173105ddb380f42accc31af87e4190b6af6ce1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/traversal/edgedfs.py
@@ -0,0 +1,182 @@
+"""
+===========================
+Depth First Search on Edges
+===========================
+
+Algorithms for a depth-first traversal of edges in a graph.
+
+"""
+
+import networkx as nx
+
+FORWARD = "forward"
+REVERSE = "reverse"
+
+__all__ = ["edge_dfs"]
+
+
+@nx._dispatchable
+def edge_dfs(G, source=None, orientation=None):
+    """A directed, depth-first-search of edges in `G`, beginning at `source`.
+
+    Yield the edges of G in a depth-first-search order continuing until
+    all edges are generated.
+
+    Parameters
+    ----------
+    G : graph
+        A directed/undirected graph/multigraph.
+
+    source : node, list of nodes
+        The node from which the traversal begins. If None, then a source
+        is chosen arbitrarily and repeatedly until all edges from each node in
+        the graph are searched.
+
+    orientation : None | 'original' | 'reverse' | 'ignore' (default: None)
+        For directed graphs and directed multigraphs, edge traversals need not
+        respect the original orientation of the edges.
+        When set to 'reverse' every edge is traversed in the reverse direction.
+        When set to 'ignore', every edge is treated as undirected.
+        When set to 'original', every edge is treated as directed.
+        In all three cases, the yielded edge tuples add a last entry to
+        indicate the direction in which that edge was traversed.
+        If orientation is None, the yielded edge has no direction indicated.
+        The direction is respected, but not reported.
+
+    Yields
+    ------
+    edge : directed edge
+        A directed edge indicating the path taken by the depth-first traversal.
+        For graphs, `edge` is of the form `(u, v)` where `u` and `v`
+        are the tail and head of the edge as determined by the traversal.
+        For multigraphs, `edge` is of the form `(u, v, key)`, where `key` is
+        the key of the edge. When the graph is directed, then `u` and `v`
+        are always in the order of the actual directed edge.
+        If orientation is not None then the edge tuple is extended to include
+        the direction of traversal ('forward' or 'reverse') on that edge.
+
+    Examples
+    --------
+    >>> from pprint import pprint
+    >>> nodes = [0, 1, 2, 3]
+    >>> edges = [(0, 1), (1, 0), (1, 0), (2, 1), (3, 1)]
+
+    >>> list(nx.edge_dfs(nx.Graph(edges), nodes))
+    [(0, 1), (1, 2), (1, 3)]
+
+    >>> list(nx.edge_dfs(nx.DiGraph(edges), nodes))
+    [(0, 1), (1, 0), (2, 1), (3, 1)]
+
+    >>> list(nx.edge_dfs(nx.MultiGraph(edges), nodes))
+    [(0, 1, 0), (1, 0, 1), (0, 1, 2), (1, 2, 0), (1, 3, 0)]
+
+    >>> list(nx.edge_dfs(nx.MultiDiGraph(edges), nodes))
+    [(0, 1, 0), (1, 0, 0), (1, 0, 1), (2, 1, 0), (3, 1, 0)]
+
+    >>> list(nx.edge_dfs(nx.DiGraph(edges), nodes, orientation="ignore"))
+    [(0, 1, 'forward'), (1, 0, 'forward'), (2, 1, 'reverse'), (3, 1, 'reverse')]
+
+    >>> elist = list(nx.edge_dfs(nx.MultiDiGraph(edges), nodes, orientation="ignore"))
+    >>> pprint(elist)
+    [(0, 1, 0, 'forward'),
+     (1, 0, 0, 'forward'),
+     (1, 0, 1, 'reverse'),
+     (2, 1, 0, 'reverse'),
+     (3, 1, 0, 'reverse')]
+
+    Notes
+    -----
+    The goal of this function is to visit edges. It differs from the more
+    familiar depth-first traversal of nodes, as provided by
+    :func:`~networkx.algorithms.traversal.depth_first_search.dfs_edges`, in
+    that it does not stop once every node has been visited. In a directed graph
+    with edges [(0, 1), (1, 2), (2, 1)], the edge (2, 1) would not be visited
+    if not for the functionality provided by this function.
+
+    See Also
+    --------
+    :func:`~networkx.algorithms.traversal.depth_first_search.dfs_edges`
+
+    """
+    nodes = list(G.nbunch_iter(source))
+    if not nodes:
+        return
+
+    directed = G.is_directed()
+    kwds = {"data": False}
+    if G.is_multigraph() is True:
+        kwds["keys"] = True
+
+    # set up edge lookup
+    if orientation is None:
+
+        def edges_from(node):
+            return iter(G.edges(node, **kwds))
+
+    elif not directed or orientation == "original":
+
+        def edges_from(node):
+            for e in G.edges(node, **kwds):
+                yield e + (FORWARD,)
+
+    elif orientation == "reverse":
+
+        def edges_from(node):
+            for e in G.in_edges(node, **kwds):
+                yield e + (REVERSE,)
+
+    elif orientation == "ignore":
+
+        def edges_from(node):
+            for e in G.edges(node, **kwds):
+                yield e + (FORWARD,)
+            for e in G.in_edges(node, **kwds):
+                yield e + (REVERSE,)
+
+    else:
+        raise nx.NetworkXError("invalid orientation argument.")
+
+    # set up formation of edge_id to easily look up if edge already returned
+    if directed:
+
+        def edge_id(edge):
+            # remove direction indicator
+            return edge[:-1] if orientation is not None else edge
+
+    else:
+
+        def edge_id(edge):
+            # single id for undirected requires frozenset on nodes
+            return (frozenset(edge[:2]),) + edge[2:]
+
+    # Basic setup
+    check_reverse = directed and orientation in ("reverse", "ignore")
+
+    visited_edges = set()
+    visited_nodes = set()
+    edges = {}
+
+    # start DFS
+    for start_node in nodes:
+        stack = [start_node]
+        while stack:
+            current_node = stack[-1]
+            if current_node not in visited_nodes:
+                edges[current_node] = edges_from(current_node)
+                visited_nodes.add(current_node)
+
+            try:
+                edge = next(edges[current_node])
+            except StopIteration:
+                # No more edges from the current node.
+                stack.pop()
+            else:
+                edgeid = edge_id(edge)
+                if edgeid not in visited_edges:
+                    visited_edges.add(edgeid)
+                    # Mark the traversed "to" node as to-be-explored.
+                    if check_reverse and edge[-1] == REVERSE:
+                        stack.append(edge[0])
+                    else:
+                        stack.append(edge[1])
+                    yield edge
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/triads.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/triads.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6d36a75cff3995b79bc189bd6b8cb7a7f186309
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/triads.py
@@ -0,0 +1,500 @@
+# See https://github.com/networkx/networkx/pull/1474
+# Copyright 2011 Reya Group 
+# Copyright 2011 Alex Levenson 
+# Copyright 2011 Diederik van Liere 
+"""Functions for analyzing triads of a graph."""
+
+from collections import defaultdict
+from itertools import combinations, permutations
+
+import networkx as nx
+from networkx.utils import not_implemented_for, py_random_state
+
+__all__ = [
+    "triadic_census",
+    "is_triad",
+    "all_triads",
+    "triads_by_type",
+    "triad_type",
+]
+
+#: The integer codes representing each type of triad.
+#:
+#: Triads that are the same up to symmetry have the same code.
+TRICODES = (
+    1,
+    2,
+    2,
+    3,
+    2,
+    4,
+    6,
+    8,
+    2,
+    6,
+    5,
+    7,
+    3,
+    8,
+    7,
+    11,
+    2,
+    6,
+    4,
+    8,
+    5,
+    9,
+    9,
+    13,
+    6,
+    10,
+    9,
+    14,
+    7,
+    14,
+    12,
+    15,
+    2,
+    5,
+    6,
+    7,
+    6,
+    9,
+    10,
+    14,
+    4,
+    9,
+    9,
+    12,
+    8,
+    13,
+    14,
+    15,
+    3,
+    7,
+    8,
+    11,
+    7,
+    12,
+    14,
+    15,
+    8,
+    14,
+    13,
+    15,
+    11,
+    15,
+    15,
+    16,
+)
+
+#: The names of each type of triad. The order of the elements is
+#: important: it corresponds to the tricodes given in :data:`TRICODES`.
+TRIAD_NAMES = (
+    "003",
+    "012",
+    "102",
+    "021D",
+    "021U",
+    "021C",
+    "111D",
+    "111U",
+    "030T",
+    "030C",
+    "201",
+    "120D",
+    "120U",
+    "120C",
+    "210",
+    "300",
+)
+
+
+#: A dictionary mapping triad code to triad name.
+TRICODE_TO_NAME = {i: TRIAD_NAMES[code - 1] for i, code in enumerate(TRICODES)}
+
+
+def _tricode(G, v, u, w):
+    """Returns the integer code of the given triad.
+
+    This is some fancy magic that comes from Batagelj and Mrvar's paper. It
+    treats each edge joining a pair of `v`, `u`, and `w` as a bit in
+    the binary representation of an integer.
+
+    """
+    combos = ((v, u, 1), (u, v, 2), (v, w, 4), (w, v, 8), (u, w, 16), (w, u, 32))
+    return sum(x for u, v, x in combos if v in G[u])
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable
+def triadic_census(G, nodelist=None):
+    """Determines the triadic census of a directed graph.
+
+    The triadic census is a count of how many of the 16 possible types of
+    triads are present in a directed graph. If a list of nodes is passed, then
+    only those triads are taken into account which have elements of nodelist in them.
+
+    Parameters
+    ----------
+    G : digraph
+       A NetworkX DiGraph
+    nodelist : list
+        List of nodes for which you want to calculate triadic census
+
+    Returns
+    -------
+    census : dict
+       Dictionary with triad type as keys and number of occurrences as values.
+
+    Examples
+    --------
+    >>> G = nx.DiGraph([(1, 2), (2, 3), (3, 1), (3, 4), (4, 1), (4, 2)])
+    >>> triadic_census = nx.triadic_census(G)
+    >>> for key, value in triadic_census.items():
+    ...     print(f"{key}: {value}")
+    003: 0
+    012: 0
+    102: 0
+    021D: 0
+    021U: 0
+    021C: 0
+    111D: 0
+    111U: 0
+    030T: 2
+    030C: 2
+    201: 0
+    120D: 0
+    120U: 0
+    120C: 0
+    210: 0
+    300: 0
+
+    Notes
+    -----
+    This algorithm has complexity $O(m)$ where $m$ is the number of edges in
+    the graph.
+
+    For undirected graphs, the triadic census can be computed by first converting
+    the graph into a directed graph using the ``G.to_directed()`` method.
+    After this conversion, only the triad types 003, 102, 201 and 300 will be
+    present in the undirected scenario.
+
+    Raises
+    ------
+    ValueError
+        If `nodelist` contains duplicate nodes or nodes not in `G`.
+        If you want to ignore this you can preprocess with `set(nodelist) & G.nodes`
+
+    See also
+    --------
+    triad_graph
+
+    References
+    ----------
+    .. [1] Vladimir Batagelj and Andrej Mrvar, A subquadratic triad census
+        algorithm for large sparse networks with small maximum degree,
+        University of Ljubljana,
+        http://vlado.fmf.uni-lj.si/pub/networks/doc/triads/triads.pdf
+
+    """
+    nodeset = set(G.nbunch_iter(nodelist))
+    if nodelist is not None and len(nodelist) != len(nodeset):
+        raise ValueError("nodelist includes duplicate nodes or nodes not in G")
+
+    N = len(G)
+    Nnot = N - len(nodeset)  # can signal special counting for subset of nodes
+
+    # create an ordering of nodes with nodeset nodes first
+    m = {n: i for i, n in enumerate(nodeset)}
+    if Nnot:
+        # add non-nodeset nodes later in the ordering
+        not_nodeset = G.nodes - nodeset
+        m.update((n, i + N) for i, n in enumerate(not_nodeset))
+
+    # build all_neighbor dicts for easy counting
+    # After Python 3.8 can leave off these keys(). Speedup also using G._pred
+    # nbrs = {n: G._pred[n].keys() | G._succ[n].keys() for n in G}
+    nbrs = {n: G.pred[n].keys() | G.succ[n].keys() for n in G}
+    dbl_nbrs = {n: G.pred[n].keys() & G.succ[n].keys() for n in G}
+
+    if Nnot:
+        sgl_nbrs = {n: G.pred[n].keys() ^ G.succ[n].keys() for n in not_nodeset}
+        # find number of edges not incident to nodes in nodeset
+        sgl = sum(1 for n in not_nodeset for nbr in sgl_nbrs[n] if nbr not in nodeset)
+        sgl_edges_outside = sgl // 2
+        dbl = sum(1 for n in not_nodeset for nbr in dbl_nbrs[n] if nbr not in nodeset)
+        dbl_edges_outside = dbl // 2
+
+    # Initialize the count for each triad to be zero.
+    census = {name: 0 for name in TRIAD_NAMES}
+    # Main loop over nodes
+    for v in nodeset:
+        vnbrs = nbrs[v]
+        dbl_vnbrs = dbl_nbrs[v]
+        if Nnot:
+            # set up counts of edges attached to v.
+            sgl_unbrs_bdy = sgl_unbrs_out = dbl_unbrs_bdy = dbl_unbrs_out = 0
+        for u in vnbrs:
+            if m[u] <= m[v]:
+                continue
+            unbrs = nbrs[u]
+            neighbors = (vnbrs | unbrs) - {u, v}
+            # Count connected triads.
+            for w in neighbors:
+                if m[u] < m[w] or (m[v] < m[w] < m[u] and v not in nbrs[w]):
+                    code = _tricode(G, v, u, w)
+                    census[TRICODE_TO_NAME[code]] += 1
+
+            # Use a formula for dyadic triads with edge incident to v
+            if u in dbl_vnbrs:
+                census["102"] += N - len(neighbors) - 2
+            else:
+                census["012"] += N - len(neighbors) - 2
+
+            # Count edges attached to v. Subtract later to get triads with v isolated
+            # _out are (u,unbr) for unbrs outside boundary of nodeset
+            # _bdy are (u,unbr) for unbrs on boundary of nodeset (get double counted)
+            if Nnot and u not in nodeset:
+                sgl_unbrs = sgl_nbrs[u]
+                sgl_unbrs_bdy += len(sgl_unbrs & vnbrs - nodeset)
+                sgl_unbrs_out += len(sgl_unbrs - vnbrs - nodeset)
+                dbl_unbrs = dbl_nbrs[u]
+                dbl_unbrs_bdy += len(dbl_unbrs & vnbrs - nodeset)
+                dbl_unbrs_out += len(dbl_unbrs - vnbrs - nodeset)
+        # if nodeset == G.nodes, skip this b/c we will find the edge later.
+        if Nnot:
+            # Count edges outside nodeset not connected with v (v isolated triads)
+            census["012"] += sgl_edges_outside - (sgl_unbrs_out + sgl_unbrs_bdy // 2)
+            census["102"] += dbl_edges_outside - (dbl_unbrs_out + dbl_unbrs_bdy // 2)
+
+    # calculate null triads: "003"
+    # null triads = total number of possible triads - all found triads
+    total_triangles = (N * (N - 1) * (N - 2)) // 6
+    triangles_without_nodeset = (Nnot * (Nnot - 1) * (Nnot - 2)) // 6
+    total_census = total_triangles - triangles_without_nodeset
+    census["003"] = total_census - sum(census.values())
+
+    return census
+
+
+@nx._dispatchable
+def is_triad(G):
+    """Returns True if the graph G is a triad, else False.
+
+    Parameters
+    ----------
+    G : graph
+       A NetworkX Graph
+
+    Returns
+    -------
+    istriad : boolean
+       Whether G is a valid triad
+
+    Examples
+    --------
+    >>> G = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
+    >>> nx.is_triad(G)
+    True
+    >>> G.add_edge(0, 1)
+    >>> nx.is_triad(G)
+    False
+    """
+    if isinstance(G, nx.Graph):
+        if G.order() == 3 and nx.is_directed(G):
+            if not any((n, n) in G.edges() for n in G.nodes()):
+                return True
+    return False
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable(returns_graph=True)
+def all_triads(G):
+    """A generator of all possible triads in G.
+
+    Parameters
+    ----------
+    G : digraph
+       A NetworkX DiGraph
+
+    Returns
+    -------
+    all_triads : generator of DiGraphs
+       Generator of triads (order-3 DiGraphs)
+
+    Examples
+    --------
+    >>> G = nx.DiGraph([(1, 2), (2, 3), (3, 1), (3, 4), (4, 1), (4, 2)])
+    >>> for triad in nx.all_triads(G):
+    ...     print(triad.edges)
+    [(1, 2), (2, 3), (3, 1)]
+    [(1, 2), (4, 1), (4, 2)]
+    [(3, 1), (3, 4), (4, 1)]
+    [(2, 3), (3, 4), (4, 2)]
+
+    """
+    triplets = combinations(G.nodes(), 3)
+    for triplet in triplets:
+        yield G.subgraph(triplet).copy()
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable
+def triads_by_type(G):
+    """Returns a list of all triads for each triad type in a directed graph.
+    There are exactly 16 different types of triads possible. Suppose 1, 2, 3 are three
+    nodes, they will be classified as a particular triad type if their connections
+    are as follows:
+
+    - 003: 1, 2, 3
+    - 012: 1 -> 2, 3
+    - 102: 1 <-> 2, 3
+    - 021D: 1 <- 2 -> 3
+    - 021U: 1 -> 2 <- 3
+    - 021C: 1 -> 2 -> 3
+    - 111D: 1 <-> 2 <- 3
+    - 111U: 1 <-> 2 -> 3
+    - 030T: 1 -> 2 -> 3, 1 -> 3
+    - 030C: 1 <- 2 <- 3, 1 -> 3
+    - 201: 1 <-> 2 <-> 3
+    - 120D: 1 <- 2 -> 3, 1 <-> 3
+    - 120U: 1 -> 2 <- 3, 1 <-> 3
+    - 120C: 1 -> 2 -> 3, 1 <-> 3
+    - 210: 1 -> 2 <-> 3, 1 <-> 3
+    - 300: 1 <-> 2 <-> 3, 1 <-> 3
+
+    Refer to the :doc:`example gallery `
+    for visual examples of the triad types.
+
+    Parameters
+    ----------
+    G : digraph
+       A NetworkX DiGraph
+
+    Returns
+    -------
+    tri_by_type : dict
+       Dictionary with triad types as keys and lists of triads as values.
+
+    Examples
+    --------
+    >>> G = nx.DiGraph([(1, 2), (1, 3), (2, 3), (3, 1), (5, 6), (5, 4), (6, 7)])
+    >>> dict = nx.triads_by_type(G)
+    >>> dict["120C"][0].edges()
+    OutEdgeView([(1, 2), (1, 3), (2, 3), (3, 1)])
+    >>> dict["012"][0].edges()
+    OutEdgeView([(1, 2)])
+
+    References
+    ----------
+    .. [1] Snijders, T. (2012). "Transitivity and triads." University of
+        Oxford.
+        https://web.archive.org/web/20170830032057/http://www.stats.ox.ac.uk/~snijders/Trans_Triads_ha.pdf
+    """
+    # num_triads = o * (o - 1) * (o - 2) // 6
+    # if num_triads > TRIAD_LIMIT: print(WARNING)
+    all_tri = all_triads(G)
+    tri_by_type = defaultdict(list)
+    for triad in all_tri:
+        name = triad_type(triad)
+        tri_by_type[name].append(triad)
+    return tri_by_type
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable
+def triad_type(G):
+    """Returns the sociological triad type for a triad.
+
+    Parameters
+    ----------
+    G : digraph
+       A NetworkX DiGraph with 3 nodes
+
+    Returns
+    -------
+    triad_type : str
+       A string identifying the triad type
+
+    Examples
+    --------
+    >>> G = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
+    >>> nx.triad_type(G)
+    '030C'
+    >>> G.add_edge(1, 3)
+    >>> nx.triad_type(G)
+    '120C'
+
+    Notes
+    -----
+    There can be 6 unique edges in a triad (order-3 DiGraph) (so 2^^6=64 unique
+    triads given 3 nodes). These 64 triads each display exactly 1 of 16
+    topologies of triads (topologies can be permuted). These topologies are
+    identified by the following notation:
+
+    {m}{a}{n}{type} (for example: 111D, 210, 102)
+
+    Here:
+
+    {m}     = number of mutual ties (takes 0, 1, 2, 3); a mutual tie is (0,1)
+              AND (1,0)
+    {a}     = number of asymmetric ties (takes 0, 1, 2, 3); an asymmetric tie
+              is (0,1) BUT NOT (1,0) or vice versa
+    {n}     = number of null ties (takes 0, 1, 2, 3); a null tie is NEITHER
+              (0,1) NOR (1,0)
+    {type}  = a letter (takes U, D, C, T) corresponding to up, down, cyclical
+              and transitive. This is only used for topologies that can have
+              more than one form (eg: 021D and 021U).
+
+    References
+    ----------
+    .. [1] Snijders, T. (2012). "Transitivity and triads." University of
+        Oxford.
+        https://web.archive.org/web/20170830032057/http://www.stats.ox.ac.uk/~snijders/Trans_Triads_ha.pdf
+    """
+    if not is_triad(G):
+        raise nx.NetworkXAlgorithmError("G is not a triad (order-3 DiGraph)")
+    num_edges = len(G.edges())
+    if num_edges == 0:
+        return "003"
+    elif num_edges == 1:
+        return "012"
+    elif num_edges == 2:
+        e1, e2 = G.edges()
+        if set(e1) == set(e2):
+            return "102"
+        elif e1[0] == e2[0]:
+            return "021D"
+        elif e1[1] == e2[1]:
+            return "021U"
+        elif e1[1] == e2[0] or e2[1] == e1[0]:
+            return "021C"
+    elif num_edges == 3:
+        for e1, e2, e3 in permutations(G.edges(), 3):
+            if set(e1) == set(e2):
+                if e3[0] in e1:
+                    return "111U"
+                # e3[1] in e1:
+                return "111D"
+            elif set(e1).symmetric_difference(set(e2)) == set(e3):
+                if {e1[0], e2[0], e3[0]} == {e1[0], e2[0], e3[0]} == set(G.nodes()):
+                    return "030C"
+                # e3 == (e1[0], e2[1]) and e2 == (e1[1], e3[1]):
+                return "030T"
+    elif num_edges == 4:
+        for e1, e2, e3, e4 in permutations(G.edges(), 4):
+            if set(e1) == set(e2):
+                # identify pair of symmetric edges (which necessarily exists)
+                if set(e3) == set(e4):
+                    return "201"
+                if {e3[0]} == {e4[0]} == set(e3).intersection(set(e4)):
+                    return "120D"
+                if {e3[1]} == {e4[1]} == set(e3).intersection(set(e4)):
+                    return "120U"
+                if e3[1] == e4[0]:
+                    return "120C"
+    elif num_edges == 5:
+        return "210"
+    elif num_edges == 6:
+        return "300"
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/vitality.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/vitality.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf4b016e78dc7429810bb48f948f40212e542eca
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/vitality.py
@@ -0,0 +1,76 @@
+"""
+Vitality measures.
+"""
+
+from functools import partial
+
+import networkx as nx
+
+__all__ = ["closeness_vitality"]
+
+
+@nx._dispatchable(edge_attrs="weight")
+def closeness_vitality(G, node=None, weight=None, wiener_index=None):
+    """Returns the closeness vitality for nodes in the graph.
+
+    The *closeness vitality* of a node, defined in Section 3.6.2 of [1],
+    is the change in the sum of distances between all node pairs when
+    excluding that node.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        A strongly-connected graph.
+
+    weight : string
+        The name of the edge attribute used as weight. This is passed
+        directly to the :func:`~networkx.wiener_index` function.
+
+    node : object
+        If specified, only the closeness vitality for this node will be
+        returned. Otherwise, a dictionary mapping each node to its
+        closeness vitality will be returned.
+
+    Other parameters
+    ----------------
+    wiener_index : number
+        If you have already computed the Wiener index of the graph
+        `G`, you can provide that value here. Otherwise, it will be
+        computed for you.
+
+    Returns
+    -------
+    dictionary or float
+        If `node` is None, this function returns a dictionary
+        with nodes as keys and closeness vitality as the
+        value. Otherwise, it returns only the closeness vitality for the
+        specified `node`.
+
+        The closeness vitality of a node may be negative infinity if
+        removing that node would disconnect the graph.
+
+    Examples
+    --------
+    >>> G = nx.cycle_graph(3)
+    >>> nx.closeness_vitality(G)
+    {0: 2.0, 1: 2.0, 2: 2.0}
+
+    See Also
+    --------
+    closeness_centrality
+
+    References
+    ----------
+    .. [1] Ulrik Brandes, Thomas Erlebach (eds.).
+           *Network Analysis: Methodological Foundations*.
+           Springer, 2005.
+           
+
+    """
+    if wiener_index is None:
+        wiener_index = nx.wiener_index(G, weight=weight)
+    if node is not None:
+        after = nx.wiener_index(G.subgraph(set(G) - {node}), weight=weight)
+        return wiener_index - after
+    vitality = partial(closeness_vitality, G, weight=weight, wiener_index=wiener_index)
+    return {v: vitality(node=v) for v in G}
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/voronoi.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/voronoi.py
new file mode 100644
index 0000000000000000000000000000000000000000..609a68deff89620e0e022020c33863107decced4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/voronoi.py
@@ -0,0 +1,86 @@
+"""Functions for computing the Voronoi cells of a graph."""
+
+import networkx as nx
+from networkx.utils import groups
+
+__all__ = ["voronoi_cells"]
+
+
+@nx._dispatchable(edge_attrs="weight")
+def voronoi_cells(G, center_nodes, weight="weight"):
+    """Returns the Voronoi cells centered at `center_nodes` with respect
+    to the shortest-path distance metric.
+
+    If $C$ is a set of nodes in the graph and $c$ is an element of $C$,
+    the *Voronoi cell* centered at a node $c$ is the set of all nodes
+    $v$ that are closer to $c$ than to any other center node in $C$ with
+    respect to the shortest-path distance metric. [1]_
+
+    For directed graphs, this will compute the "outward" Voronoi cells,
+    as defined in [1]_, in which distance is measured from the center
+    nodes to the target node. For the "inward" Voronoi cells, use the
+    :meth:`DiGraph.reverse` method to reverse the orientation of the
+    edges before invoking this function on the directed graph.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    center_nodes : set
+        A nonempty set of nodes in the graph `G` that represent the
+        center of the Voronoi cells.
+
+    weight : string or function
+        The edge attribute (or an arbitrary function) representing the
+        weight of an edge. This keyword argument is as described in the
+        documentation for :func:`~networkx.multi_source_dijkstra_path`,
+        for example.
+
+    Returns
+    -------
+    dictionary
+        A mapping from center node to set of all nodes in the graph
+        closer to that center node than to any other center node. The
+        keys of the dictionary are the element of `center_nodes`, and
+        the values of the dictionary form a partition of the nodes of
+        `G`.
+
+    Examples
+    --------
+    To get only the partition of the graph induced by the Voronoi cells,
+    take the collection of all values in the returned dictionary::
+
+        >>> G = nx.path_graph(6)
+        >>> center_nodes = {0, 3}
+        >>> cells = nx.voronoi_cells(G, center_nodes)
+        >>> partition = set(map(frozenset, cells.values()))
+        >>> sorted(map(sorted, partition))
+        [[0, 1], [2, 3, 4, 5]]
+
+    Raises
+    ------
+    ValueError
+        If `center_nodes` is empty.
+
+    References
+    ----------
+    .. [1] Erwig, Martin. (2000),"The graph Voronoi diagram with applications."
+        *Networks*, 36: 156--163.
+        https://doi.org/10.1002/1097-0037(200010)36:3<156::AID-NET2>3.0.CO;2-L
+
+    """
+    # Determine the shortest paths from any one of the center nodes to
+    # every node in the graph.
+    #
+    # This raises `ValueError` if `center_nodes` is an empty set.
+    paths = nx.multi_source_dijkstra_path(G, center_nodes, weight=weight)
+    # Determine the center node from which the shortest path originates.
+    nearest = {v: p[0] for v, p in paths.items()}
+    # Get the mapping from center node to all nodes closer to it than to
+    # any other center node.
+    cells = groups(nearest)
+    # We collect all unreachable nodes under a special key, if there are any.
+    unreachable = set(G) - set(nearest)
+    if unreachable:
+        cells["unreachable"] = unreachable
+    return cells
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/walks.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/walks.py
new file mode 100644
index 0000000000000000000000000000000000000000..97e5bb0b5b635bf5cebd5a0e1191374a6d7bd6c3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/walks.py
@@ -0,0 +1,77 @@
+"""Function for computing walks in a graph."""
+
+import networkx as nx
+
+__all__ = ["number_of_walks"]
+
+
+@nx._dispatchable
+def number_of_walks(G, walk_length):
+    """Returns the number of walks connecting each pair of nodes in `G`
+
+    A *walk* is a sequence of nodes in which each adjacent pair of nodes
+    in the sequence is adjacent in the graph. A walk can repeat the same
+    edge and go in the opposite direction just as people can walk on a
+    set of paths, but standing still is not counted as part of the walk.
+
+    This function only counts the walks with `walk_length` edges. Note that
+    the number of nodes in the walk sequence is one more than `walk_length`.
+    The number of walks can grow very quickly on a larger graph
+    and with a larger walk length.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    walk_length : int
+        A nonnegative integer representing the length of a walk.
+
+    Returns
+    -------
+    dict
+        A dictionary of dictionaries in which outer keys are source
+        nodes, inner keys are target nodes, and inner values are the
+        number of walks of length `walk_length` connecting those nodes.
+
+    Raises
+    ------
+    ValueError
+        If `walk_length` is negative
+
+    Examples
+    --------
+
+    >>> G = nx.Graph([(0, 1), (1, 2)])
+    >>> walks = nx.number_of_walks(G, 2)
+    >>> walks
+    {0: {0: 1, 1: 0, 2: 1}, 1: {0: 0, 1: 2, 2: 0}, 2: {0: 1, 1: 0, 2: 1}}
+    >>> total_walks = sum(sum(tgts.values()) for _, tgts in walks.items())
+
+    You can also get the number of walks from a specific source node using the
+    returned dictionary. For example, number of walks of length 1 from node 0
+    can be found as follows:
+
+    >>> walks = nx.number_of_walks(G, 1)
+    >>> walks[0]
+    {0: 0, 1: 1, 2: 0}
+    >>> sum(walks[0].values())  # walks from 0 of length 1
+    1
+
+    Similarly, a target node can also be specified:
+
+    >>> walks[0][1]
+    1
+
+    """
+    import scipy as sp
+
+    if walk_length < 0:
+        raise ValueError(f"`walk_length` cannot be negative: {walk_length}")
+
+    A = nx.adjacency_matrix(G, weight=None)
+    power = sp.sparse.linalg.matrix_power(A, walk_length).tocsr()
+    result = {
+        u: {v: power[u_idx, v_idx].item() for v_idx, v in enumerate(G)}
+        for u_idx, u in enumerate(G)
+    }
+    return result
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/wiener.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/wiener.py
new file mode 100644
index 0000000000000000000000000000000000000000..d097aa629088e305bdb3e221dcb6da09d69bb3dd
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/algorithms/wiener.py
@@ -0,0 +1,278 @@
+"""Functions related to the Wiener Index of a graph.
+
+The Wiener Index is a topological measure of a graph
+related to the distance between nodes and their degree.
+The Schultz Index and Gutman Index are similar measures.
+They are used categorize molecules via the network of
+atoms connected by chemical bonds. The indices are
+correlated with functional aspects of the molecules.
+
+References
+----------
+.. [1] `Wikipedia: Wiener Index `_
+.. [2] M.V. Diudeaa and I. Gutman, Wiener-Type Topological Indices,
+       Croatica Chemica Acta, 71 (1998), 21-51.
+       https://hrcak.srce.hr/132323
+"""
+
+import itertools as it
+
+import networkx as nx
+
+__all__ = ["wiener_index", "schultz_index", "gutman_index", "hyper_wiener_index"]
+
+
+@nx._dispatchable(edge_attrs="weight")
+def wiener_index(G, weight=None):
+    """Returns the Wiener index of the given graph.
+
+    The *Wiener index* of a graph is the sum of the shortest-path
+    (weighted) distances between each pair of reachable nodes.
+    For pairs of nodes in undirected graphs, only one orientation
+    of the pair is counted.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    weight : string or None, optional (default: None)
+        If None, every edge has weight 1.
+        If a string, use this edge attribute as the edge weight.
+        Any edge attribute not present defaults to 1.
+        The edge weights are used to computing shortest-path distances.
+
+    Returns
+    -------
+    number
+        The Wiener index of the graph `G`.
+
+    Raises
+    ------
+    NetworkXError
+        If the graph `G` is not connected.
+
+    Notes
+    -----
+    If a pair of nodes is not reachable, the distance is assumed to be
+    infinity. This means that for graphs that are not
+    strongly-connected, this function returns ``inf``.
+
+    The Wiener index is not usually defined for directed graphs, however
+    this function uses the natural generalization of the Wiener index to
+    directed graphs.
+
+    Examples
+    --------
+    The Wiener index of the (unweighted) complete graph on *n* nodes
+    equals the number of pairs of the *n* nodes, since each pair of
+    nodes is at distance one::
+
+        >>> n = 10
+        >>> G = nx.complete_graph(n)
+        >>> nx.wiener_index(G) == n * (n - 1) / 2
+        True
+
+    Graphs that are not strongly-connected have infinite Wiener index::
+
+        >>> G = nx.empty_graph(2)
+        >>> nx.wiener_index(G)
+        inf
+
+    References
+    ----------
+    .. [1] `Wikipedia: Wiener Index `_
+    """
+    connected = nx.is_strongly_connected(G) if G.is_directed() else nx.is_connected(G)
+    if not connected:
+        return float("inf")
+
+    spl = nx.shortest_path_length(G, weight=weight)
+    total = sum(it.chain.from_iterable(nbrs.values() for node, nbrs in spl))
+    # Need to account for double counting pairs of nodes in undirected graphs.
+    return total if G.is_directed() else total / 2
+
+
+@nx.utils.not_implemented_for("directed")
+@nx.utils.not_implemented_for("multigraph")
+@nx._dispatchable(edge_attrs="weight")
+def schultz_index(G, weight=None):
+    r"""Returns the Schultz Index (of the first kind) of `G`
+
+    The *Schultz Index* [3]_ of a graph is the sum over all node pairs of
+    distances times the sum of degrees. Consider an undirected graph `G`.
+    For each node pair ``(u, v)`` compute ``dist(u, v) * (deg(u) + deg(v)``
+    where ``dist`` is the shortest path length between two nodes and ``deg``
+    is the degree of a node.
+
+    The Schultz Index is the sum of these quantities over all (unordered)
+    pairs of nodes.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        The undirected graph of interest.
+    weight : string or None, optional (default: None)
+        If None, every edge has weight 1.
+        If a string, use this edge attribute as the edge weight.
+        Any edge attribute not present defaults to 1.
+        The edge weights are used to computing shortest-path distances.
+
+    Returns
+    -------
+    number
+        The first kind of Schultz Index of the graph `G`.
+
+    Examples
+    --------
+    The Schultz Index of the (unweighted) complete graph on *n* nodes
+    equals the number of pairs of the *n* nodes times ``2 * (n - 1)``,
+    since each pair of nodes is at distance one and the sum of degree
+    of two nodes is ``2 * (n - 1)``.
+
+    >>> n = 10
+    >>> G = nx.complete_graph(n)
+    >>> nx.schultz_index(G) == (n * (n - 1) / 2) * (2 * (n - 1))
+    True
+
+    Graph that is disconnected
+
+    >>> nx.schultz_index(nx.empty_graph(2))
+    inf
+
+    References
+    ----------
+    .. [1] I. Gutman, Selected properties of the Schultz molecular topological index,
+           J. Chem. Inf. Comput. Sci. 34 (1994), 1087–1089.
+           https://doi.org/10.1021/ci00021a009
+    .. [2] M.V. Diudeaa and I. Gutman, Wiener-Type Topological Indices,
+           Croatica Chemica Acta, 71 (1998), 21-51.
+           https://hrcak.srce.hr/132323
+    .. [3] H. P. Schultz, Topological organic chemistry. 1.
+           Graph theory and topological indices of alkanes,i
+           J. Chem. Inf. Comput. Sci. 29 (1989), 239–257.
+
+    """
+    if not nx.is_connected(G):
+        return float("inf")
+
+    spl = nx.shortest_path_length(G, weight=weight)
+    d = dict(G.degree, weight=weight)
+    return sum(dist * (d[u] + d[v]) for u, info in spl for v, dist in info.items()) / 2
+
+
+@nx.utils.not_implemented_for("directed")
+@nx.utils.not_implemented_for("multigraph")
+@nx._dispatchable(edge_attrs="weight")
+def gutman_index(G, weight=None):
+    r"""Returns the Gutman Index for the graph `G`.
+
+    The *Gutman Index* measures the topology of networks, especially for molecule
+    networks of atoms connected by bonds [1]_. It is also called the Schultz Index
+    of the second kind [2]_.
+
+    Consider an undirected graph `G` with node set ``V``.
+    The Gutman Index of a graph is the sum over all (unordered) pairs of nodes
+    of nodes ``(u, v)``, with distance ``dist(u, v)`` and degrees ``deg(u)``
+    and ``deg(v)``, of ``dist(u, v) * deg(u) * deg(v)``
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    weight : string or None, optional (default: None)
+        If None, every edge has weight 1.
+        If a string, use this edge attribute as the edge weight.
+        Any edge attribute not present defaults to 1.
+        The edge weights are used to computing shortest-path distances.
+
+    Returns
+    -------
+    number
+        The Gutman Index of the graph `G`.
+
+    Examples
+    --------
+    The Gutman Index of the (unweighted) complete graph on *n* nodes
+    equals the number of pairs of the *n* nodes times ``(n - 1) * (n - 1)``,
+    since each pair of nodes is at distance one and the product of degree of two
+    vertices is ``(n - 1) * (n - 1)``.
+
+    >>> n = 10
+    >>> G = nx.complete_graph(n)
+    >>> nx.gutman_index(G) == (n * (n - 1) / 2) * ((n - 1) * (n - 1))
+    True
+
+    Graphs that are disconnected
+
+    >>> G = nx.empty_graph(2)
+    >>> nx.gutman_index(G)
+    inf
+
+    References
+    ----------
+    .. [1] M.V. Diudeaa and I. Gutman, Wiener-Type Topological Indices,
+           Croatica Chemica Acta, 71 (1998), 21-51.
+           https://hrcak.srce.hr/132323
+    .. [2] I. Gutman, Selected properties of the Schultz molecular topological index,
+           J. Chem. Inf. Comput. Sci. 34 (1994), 1087–1089.
+           https://doi.org/10.1021/ci00021a009
+
+    """
+    if not nx.is_connected(G):
+        return float("inf")
+
+    spl = nx.shortest_path_length(G, weight=weight)
+    d = dict(G.degree, weight=weight)
+    return sum(dist * d[u] * d[v] for u, vinfo in spl for v, dist in vinfo.items()) / 2
+
+
+@nx.utils.not_implemented_for("directed")
+@nx.utils.not_implemented_for("multigraph")
+@nx._dispatchable(edge_attrs="weight")
+def hyper_wiener_index(G, weight=None):
+    r"""Returns the Hyper-Wiener index of the graph `G`.
+
+    The Hyper-Wiener index of a connected graph `G` is defined as
+
+    .. math::
+        WW(G) = \frac{1}{2} \sum_{u,v \in V(G)} (d(u,v) + d(u,v)^2)
+
+    where ``d(u, v)`` is the shortest-path distance between nodes ``u`` and ``v``.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        An undirected, connected graph.
+
+    weight : string or None, optional (default: None)
+        The edge attribute to use for calculating shortest-path distances.
+        If None, all edges are considered to have a weight of 1.
+
+    Returns
+    -------
+    float
+        The Hyper-Wiener index of the graph G.
+        Returns float("inf") if the graph is not connected.
+
+    References
+    ----------
+    .. [1] M. Randić, "Novel molecular descriptor for structure-property studies,"
+           Chemical Physics Letters, vol. 211, pp. 478-483, 1993.
+    .. [2] `Wikipedia: Hyper-Wiener Index `_
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> nx.hyper_wiener_index(G)
+    30.0
+
+    >>> G = nx.cycle_graph(4)
+    >>> nx.hyper_wiener_index(G)
+    20.0
+    """
+    if not nx.is_connected(G):
+        return float("inf")
+
+    spl = nx.shortest_path_length(G, weight=weight)
+    total = sum(dist + dist**2 for _, lengths in spl for dist in lengths.values())
+    return total / 2
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..721fa8b4767233bc2b624f6b2ce4d10533a4d66c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/__init__.py
@@ -0,0 +1,13 @@
+from .graph import Graph
+from .digraph import DiGraph
+from .multigraph import MultiGraph
+from .multidigraph import MultiDiGraph
+
+from .function import *
+from .graphviews import subgraph_view, reverse_view
+
+from networkx.classes import filters
+
+from networkx.classes import coreviews
+from networkx.classes import graphviews
+from networkx.classes import reportviews
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/coreviews.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/coreviews.py
new file mode 100644
index 0000000000000000000000000000000000000000..4769ffa71ab823c154e6f7b990f0cb07299090a6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/coreviews.py
@@ -0,0 +1,435 @@
+"""Views of core data structures such as nested Mappings (e.g. dict-of-dicts).
+These ``Views`` often restrict element access, with either the entire view or
+layers of nested mappings being read-only.
+"""
+
+from collections.abc import Mapping
+
+__all__ = [
+    "AtlasView",
+    "AdjacencyView",
+    "MultiAdjacencyView",
+    "UnionAtlas",
+    "UnionAdjacency",
+    "UnionMultiInner",
+    "UnionMultiAdjacency",
+    "FilterAtlas",
+    "FilterAdjacency",
+    "FilterMultiInner",
+    "FilterMultiAdjacency",
+]
+
+
+class AtlasView(Mapping):
+    """An AtlasView is a Read-only Mapping of Mappings.
+
+    It is a View into a dict-of-dict data structure.
+    The inner level of dict is read-write. But the
+    outer level is read-only.
+
+    See Also
+    ========
+    AdjacencyView: View into dict-of-dict-of-dict
+    MultiAdjacencyView: View into dict-of-dict-of-dict-of-dict
+    """
+
+    __slots__ = ("_atlas",)
+
+    def __getstate__(self):
+        return {"_atlas": self._atlas}
+
+    def __setstate__(self, state):
+        self._atlas = state["_atlas"]
+
+    def __init__(self, d):
+        self._atlas = d
+
+    def __len__(self):
+        return len(self._atlas)
+
+    def __iter__(self):
+        return iter(self._atlas)
+
+    def __getitem__(self, key):
+        return self._atlas[key]
+
+    def copy(self):
+        return {n: self[n].copy() for n in self._atlas}
+
+    def __str__(self):
+        return str(self._atlas)  # {nbr: self[nbr] for nbr in self})
+
+    def __repr__(self):
+        return f"{self.__class__.__name__}({self._atlas!r})"
+
+
+class AdjacencyView(AtlasView):
+    """An AdjacencyView is a Read-only Map of Maps of Maps.
+
+    It is a View into a dict-of-dict-of-dict data structure.
+    The inner level of dict is read-write. But the
+    outer levels are read-only.
+
+    See Also
+    ========
+    AtlasView: View into dict-of-dict
+    MultiAdjacencyView: View into dict-of-dict-of-dict-of-dict
+    """
+
+    __slots__ = ()  # Still uses AtlasView slots names _atlas
+
+    def __getitem__(self, name):
+        return AtlasView(self._atlas[name])
+
+    def copy(self):
+        return {n: self[n].copy() for n in self._atlas}
+
+
+class MultiAdjacencyView(AdjacencyView):
+    """An MultiAdjacencyView is a Read-only Map of Maps of Maps of Maps.
+
+    It is a View into a dict-of-dict-of-dict-of-dict data structure.
+    The inner level of dict is read-write. But the
+    outer levels are read-only.
+
+    See Also
+    ========
+    AtlasView: View into dict-of-dict
+    AdjacencyView: View into dict-of-dict-of-dict
+    """
+
+    __slots__ = ()  # Still uses AtlasView slots names _atlas
+
+    def __getitem__(self, name):
+        return AdjacencyView(self._atlas[name])
+
+    def copy(self):
+        return {n: self[n].copy() for n in self._atlas}
+
+
+class UnionAtlas(Mapping):
+    """A read-only union of two atlases (dict-of-dict).
+
+    The two dict-of-dicts represent the inner dict of
+    an Adjacency:  `G.succ[node]` and `G.pred[node]`.
+    The inner level of dict of both hold attribute key:value
+    pairs and is read-write. But the outer level is read-only.
+
+    See Also
+    ========
+    UnionAdjacency: View into dict-of-dict-of-dict
+    UnionMultiAdjacency: View into dict-of-dict-of-dict-of-dict
+    """
+
+    __slots__ = ("_succ", "_pred")
+
+    def __getstate__(self):
+        return {"_succ": self._succ, "_pred": self._pred}
+
+    def __setstate__(self, state):
+        self._succ = state["_succ"]
+        self._pred = state["_pred"]
+
+    def __init__(self, succ, pred):
+        self._succ = succ
+        self._pred = pred
+
+    def __len__(self):
+        return len(self._succ.keys() | self._pred.keys())
+
+    def __iter__(self):
+        return iter(set(self._succ.keys()) | set(self._pred.keys()))
+
+    def __getitem__(self, key):
+        try:
+            return self._succ[key]
+        except KeyError:
+            return self._pred[key]
+
+    def copy(self):
+        result = {nbr: dd.copy() for nbr, dd in self._succ.items()}
+        for nbr, dd in self._pred.items():
+            if nbr in result:
+                result[nbr].update(dd)
+            else:
+                result[nbr] = dd.copy()
+        return result
+
+    def __str__(self):
+        return str({nbr: self[nbr] for nbr in self})
+
+    def __repr__(self):
+        return f"{self.__class__.__name__}({self._succ!r}, {self._pred!r})"
+
+
+class UnionAdjacency(Mapping):
+    """A read-only union of dict Adjacencies as a Map of Maps of Maps.
+
+    The two input dict-of-dict-of-dicts represent the union of
+    `G.succ` and `G.pred`. Return values are UnionAtlas
+    The inner level of dict is read-write. But the
+    middle and outer levels are read-only.
+
+    succ : a dict-of-dict-of-dict {node: nbrdict}
+    pred : a dict-of-dict-of-dict {node: nbrdict}
+    The keys for the two dicts should be the same
+
+    See Also
+    ========
+    UnionAtlas: View into dict-of-dict
+    UnionMultiAdjacency: View into dict-of-dict-of-dict-of-dict
+    """
+
+    __slots__ = ("_succ", "_pred")
+
+    def __getstate__(self):
+        return {"_succ": self._succ, "_pred": self._pred}
+
+    def __setstate__(self, state):
+        self._succ = state["_succ"]
+        self._pred = state["_pred"]
+
+    def __init__(self, succ, pred):
+        # keys must be the same for two input dicts
+        assert len(set(succ.keys()) ^ set(pred.keys())) == 0
+        self._succ = succ
+        self._pred = pred
+
+    def __len__(self):
+        return len(self._succ)  # length of each dict should be the same
+
+    def __iter__(self):
+        return iter(self._succ)
+
+    def __getitem__(self, nbr):
+        return UnionAtlas(self._succ[nbr], self._pred[nbr])
+
+    def copy(self):
+        return {n: self[n].copy() for n in self._succ}
+
+    def __str__(self):
+        return str({nbr: self[nbr] for nbr in self})
+
+    def __repr__(self):
+        return f"{self.__class__.__name__}({self._succ!r}, {self._pred!r})"
+
+
+class UnionMultiInner(UnionAtlas):
+    """A read-only union of two inner dicts of MultiAdjacencies.
+
+    The two input dict-of-dict-of-dicts represent the union of
+    `G.succ[node]` and `G.pred[node]` for MultiDiGraphs.
+    Return values are UnionAtlas.
+    The inner level of dict is read-write. But the outer levels are read-only.
+
+    See Also
+    ========
+    UnionAtlas: View into dict-of-dict
+    UnionAdjacency:  View into dict-of-dict-of-dict
+    UnionMultiAdjacency:  View into dict-of-dict-of-dict-of-dict
+    """
+
+    __slots__ = ()  # Still uses UnionAtlas slots names _succ, _pred
+
+    def __getitem__(self, node):
+        in_succ = node in self._succ
+        in_pred = node in self._pred
+        if in_succ:
+            if in_pred:
+                return UnionAtlas(self._succ[node], self._pred[node])
+            return UnionAtlas(self._succ[node], {})
+        return UnionAtlas({}, self._pred[node])
+
+    def copy(self):
+        nodes = set(self._succ.keys()) | set(self._pred.keys())
+        return {n: self[n].copy() for n in nodes}
+
+
+class UnionMultiAdjacency(UnionAdjacency):
+    """A read-only union of two dict MultiAdjacencies.
+
+    The two input dict-of-dict-of-dict-of-dicts represent the union of
+    `G.succ` and `G.pred` for MultiDiGraphs. Return values are UnionAdjacency.
+    The inner level of dict is read-write. But the outer levels are read-only.
+
+    See Also
+    ========
+    UnionAtlas:  View into dict-of-dict
+    UnionMultiInner:  View into dict-of-dict-of-dict
+    """
+
+    __slots__ = ()  # Still uses UnionAdjacency slots names _succ, _pred
+
+    def __getitem__(self, node):
+        return UnionMultiInner(self._succ[node], self._pred[node])
+
+
+class FilterAtlas(Mapping):  # nodedict, nbrdict, keydict
+    """A read-only Mapping of Mappings with filtering criteria for nodes.
+
+    It is a view into a dict-of-dict data structure, and it selects only
+    nodes that meet the criteria defined by ``NODE_OK``.
+
+    See Also
+    ========
+    FilterAdjacency
+    FilterMultiInner
+    FilterMultiAdjacency
+    """
+
+    def __init__(self, d, NODE_OK):
+        self._atlas = d
+        self.NODE_OK = NODE_OK
+
+    def __len__(self):
+        # check whether NODE_OK stores the number of nodes as `length`
+        # or the nodes themselves as a set `nodes`. If not, count the nodes.
+        if hasattr(self.NODE_OK, "length"):
+            return self.NODE_OK.length
+        if hasattr(self.NODE_OK, "nodes"):
+            return len(self.NODE_OK.nodes & self._atlas.keys())
+        return sum(1 for n in self._atlas if self.NODE_OK(n))
+
+    def __iter__(self):
+        try:  # check that NODE_OK has attr 'nodes'
+            node_ok_shorter = 2 * len(self.NODE_OK.nodes) < len(self._atlas)
+        except AttributeError:
+            node_ok_shorter = False
+        if node_ok_shorter:
+            return (n for n in self.NODE_OK.nodes if n in self._atlas)
+        return (n for n in self._atlas if self.NODE_OK(n))
+
+    def __getitem__(self, key):
+        if key in self._atlas and self.NODE_OK(key):
+            return self._atlas[key]
+        raise KeyError(f"Key {key} not found")
+
+    def __str__(self):
+        return str({nbr: self[nbr] for nbr in self})
+
+    def __repr__(self):
+        return f"{self.__class__.__name__}({self._atlas!r}, {self.NODE_OK!r})"
+
+
+class FilterAdjacency(Mapping):  # edgedict
+    """A read-only Mapping of Mappings with filtering criteria for nodes and edges.
+
+    It is a view into a dict-of-dict-of-dict data structure, and it selects nodes
+    and edges that satisfy specific criteria defined by ``NODE_OK`` and ``EDGE_OK``,
+    respectively.
+
+    See Also
+    ========
+    FilterAtlas
+    FilterMultiInner
+    FilterMultiAdjacency
+    """
+
+    def __init__(self, d, NODE_OK, EDGE_OK):
+        self._atlas = d
+        self.NODE_OK = NODE_OK
+        self.EDGE_OK = EDGE_OK
+
+    def __len__(self):
+        # check whether NODE_OK stores the number of nodes as `length`
+        # or the nodes themselves as a set `nodes`. If not, count the nodes.
+        if hasattr(self.NODE_OK, "length"):
+            return self.NODE_OK.length
+        if hasattr(self.NODE_OK, "nodes"):
+            return len(self.NODE_OK.nodes & self._atlas.keys())
+        return sum(1 for n in self._atlas if self.NODE_OK(n))
+
+    def __iter__(self):
+        try:  # check that NODE_OK has attr 'nodes'
+            node_ok_shorter = 2 * len(self.NODE_OK.nodes) < len(self._atlas)
+        except AttributeError:
+            node_ok_shorter = False
+        if node_ok_shorter:
+            return (n for n in self.NODE_OK.nodes if n in self._atlas)
+        return (n for n in self._atlas if self.NODE_OK(n))
+
+    def __getitem__(self, node):
+        if node in self._atlas and self.NODE_OK(node):
+
+            def new_node_ok(nbr):
+                return self.NODE_OK(nbr) and self.EDGE_OK(node, nbr)
+
+            return FilterAtlas(self._atlas[node], new_node_ok)
+        raise KeyError(f"Key {node} not found")
+
+    def __str__(self):
+        return str({nbr: self[nbr] for nbr in self})
+
+    def __repr__(self):
+        name = self.__class__.__name__
+        return f"{name}({self._atlas!r}, {self.NODE_OK!r}, {self.EDGE_OK!r})"
+
+
+class FilterMultiInner(FilterAdjacency):  # muliedge_seconddict
+    """A read-only Mapping of Mappings with filtering criteria for nodes and edges.
+
+    It is a view into a dict-of-dict-of-dict-of-dict data structure, and it selects nodes
+    and edges that meet specific criteria defined by ``NODE_OK`` and ``EDGE_OK``.
+
+    See Also
+    ========
+    FilterAtlas
+    FilterAdjacency
+    FilterMultiAdjacency
+    """
+
+    def __iter__(self):
+        try:  # check that NODE_OK has attr 'nodes'
+            node_ok_shorter = 2 * len(self.NODE_OK.nodes) < len(self._atlas)
+        except AttributeError:
+            node_ok_shorter = False
+        if node_ok_shorter:
+            my_nodes = (n for n in self.NODE_OK.nodes if n in self._atlas)
+        else:
+            my_nodes = (n for n in self._atlas if self.NODE_OK(n))
+        for n in my_nodes:
+            some_keys_ok = False
+            for key in self._atlas[n]:
+                if self.EDGE_OK(n, key):
+                    some_keys_ok = True
+                    break
+            if some_keys_ok is True:
+                yield n
+
+    def __getitem__(self, nbr):
+        if (
+            nbr in self._atlas
+            and self.NODE_OK(nbr)
+            and any(self.EDGE_OK(nbr, key) for key in self._atlas[nbr])
+        ):
+
+            def new_node_ok(key):
+                return self.EDGE_OK(nbr, key)
+
+            return FilterAtlas(self._atlas[nbr], new_node_ok)
+        raise KeyError(f"Key {nbr} not found")
+
+
+class FilterMultiAdjacency(FilterAdjacency):  # multiedgedict
+    """A read-only Mapping of Mappings with filtering criteria
+    for nodes and edges.
+
+    It is a view into a dict-of-dict-of-dict-of-dict data structure,
+    and it selects nodes and edges that satisfy specific criteria
+    defined by ``NODE_OK`` and ``EDGE_OK``, respectively.
+
+    See Also
+    ========
+    FilterAtlas
+    FilterAdjacency
+    FilterMultiInner
+    """
+
+    def __getitem__(self, node):
+        if node in self._atlas and self.NODE_OK(node):
+
+            def edge_ok(nbr, key):
+                return self.NODE_OK(nbr) and self.EDGE_OK(node, nbr, key)
+
+            return FilterMultiInner(self._atlas[node], self.NODE_OK, edge_ok)
+        raise KeyError(f"Key {node} not found")
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/digraph.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/digraph.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae35128e26814315277ac4f0500abc53f36bbbb1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/digraph.py
@@ -0,0 +1,1363 @@
+"""Base class for directed graphs."""
+
+from copy import deepcopy
+from functools import cached_property
+
+import networkx as nx
+from networkx import convert
+from networkx.classes.coreviews import AdjacencyView
+from networkx.classes.graph import Graph
+from networkx.classes.reportviews import (
+    DiDegreeView,
+    InDegreeView,
+    InEdgeView,
+    OutDegreeView,
+    OutEdgeView,
+)
+from networkx.exception import NetworkXError
+
+__all__ = ["DiGraph"]
+
+
+class _CachedPropertyResetterAdjAndSucc:
+    """Data Descriptor class that syncs and resets cached properties adj and succ
+
+    The cached properties `adj` and `succ` are reset whenever `_adj` or `_succ`
+    are set to new objects. In addition, the attributes `_succ` and `_adj`
+    are synced so these two names point to the same object.
+
+    Warning: most of the time, when ``G._adj`` is set, ``G._pred`` should also
+    be set to maintain a valid data structure. They share datadicts.
+
+    This object sits on a class and ensures that any instance of that
+    class clears its cached properties "succ" and "adj" whenever the
+    underlying instance attributes "_succ" or "_adj" are set to a new object.
+    It only affects the set process of the obj._adj and obj._succ attribute.
+    All get/del operations act as they normally would.
+
+    For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
+    """
+
+    def __set__(self, obj, value):
+        od = obj.__dict__
+        od["_adj"] = value
+        od["_succ"] = value
+        # reset cached properties
+        props = [
+            "adj",
+            "succ",
+            "edges",
+            "out_edges",
+            "degree",
+            "out_degree",
+            "in_degree",
+        ]
+        for prop in props:
+            if prop in od:
+                del od[prop]
+
+
+class _CachedPropertyResetterPred:
+    """Data Descriptor class for _pred that resets ``pred`` cached_property when needed
+
+    This assumes that the ``cached_property`` ``G.pred`` should be reset whenever
+    ``G._pred`` is set to a new value.
+
+    Warning: most of the time, when ``G._pred`` is set, ``G._adj`` should also
+    be set to maintain a valid data structure. They share datadicts.
+
+    This object sits on a class and ensures that any instance of that
+    class clears its cached property "pred" whenever the underlying
+    instance attribute "_pred" is set to a new object. It only affects
+    the set process of the obj._pred attribute. All get/del operations
+    act as they normally would.
+
+    For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
+    """
+
+    def __set__(self, obj, value):
+        od = obj.__dict__
+        od["_pred"] = value
+        # reset cached properties
+        props = ["pred", "in_edges", "degree", "out_degree", "in_degree"]
+        for prop in props:
+            if prop in od:
+                del od[prop]
+
+
+class DiGraph(Graph):
+    """
+    Base class for directed graphs.
+
+    A DiGraph stores nodes and edges with optional data, or attributes.
+
+    DiGraphs hold directed edges.  Self loops are allowed but multiple
+    (parallel) edges are not.
+
+    Nodes can be arbitrary (hashable) Python objects with optional
+    key/value attributes. By convention `None` is not used as a node.
+
+    Edges are represented as links between nodes with optional
+    key/value attributes.
+
+    Parameters
+    ----------
+    incoming_graph_data : input graph (optional, default: None)
+        Data to initialize graph. If None (default) an empty
+        graph is created.  The data can be any format that is supported
+        by the to_networkx_graph() function, currently including edge list,
+        dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy
+        sparse matrix, or PyGraphviz graph.
+
+    attr : keyword arguments, optional (default= no attributes)
+        Attributes to add to graph as key=value pairs.
+
+    See Also
+    --------
+    Graph
+    MultiGraph
+    MultiDiGraph
+
+    Examples
+    --------
+    Create an empty graph structure (a "null graph") with no nodes and
+    no edges.
+
+    >>> G = nx.DiGraph()
+
+    G can be grown in several ways.
+
+    **Nodes:**
+
+    Add one node at a time:
+
+    >>> G.add_node(1)
+
+    Add the nodes from any container (a list, dict, set or
+    even the lines from a file or the nodes from another graph).
+
+    >>> G.add_nodes_from([2, 3])
+    >>> G.add_nodes_from(range(100, 110))
+    >>> H = nx.path_graph(10)
+    >>> G.add_nodes_from(H)
+
+    In addition to strings and integers any hashable Python object
+    (except None) can represent a node, e.g. a customized node object,
+    or even another Graph.
+
+    >>> G.add_node(H)
+
+    **Edges:**
+
+    G can also be grown by adding edges.
+
+    Add one edge,
+
+    >>> G.add_edge(1, 2)
+
+    a list of edges,
+
+    >>> G.add_edges_from([(1, 2), (1, 3)])
+
+    or a collection of edges,
+
+    >>> G.add_edges_from(H.edges)
+
+    If some edges connect nodes not yet in the graph, the nodes
+    are added automatically.  There are no errors when adding
+    nodes or edges that already exist.
+
+    **Attributes:**
+
+    Each graph, node, and edge can hold key/value attribute pairs
+    in an associated attribute dictionary (the keys must be hashable).
+    By default these are empty, but can be added or changed using
+    add_edge, add_node or direct manipulation of the attribute
+    dictionaries named graph, node and edge respectively.
+
+    >>> G = nx.DiGraph(day="Friday")
+    >>> G.graph
+    {'day': 'Friday'}
+
+    Add node attributes using add_node(), add_nodes_from() or G.nodes
+
+    >>> G.add_node(1, time="5pm")
+    >>> G.add_nodes_from([3], time="2pm")
+    >>> G.nodes[1]
+    {'time': '5pm'}
+    >>> G.nodes[1]["room"] = 714
+    >>> del G.nodes[1]["room"]  # remove attribute
+    >>> list(G.nodes(data=True))
+    [(1, {'time': '5pm'}), (3, {'time': '2pm'})]
+
+    Add edge attributes using add_edge(), add_edges_from(), subscript
+    notation, or G.edges.
+
+    >>> G.add_edge(1, 2, weight=4.7)
+    >>> G.add_edges_from([(3, 4), (4, 5)], color="red")
+    >>> G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
+    >>> G[1][2]["weight"] = 4.7
+    >>> G.edges[1, 2]["weight"] = 4
+
+    Warning: we protect the graph data structure by making `G.edges[1, 2]` a
+    read-only dict-like structure. However, you can assign to attributes
+    in e.g. `G.edges[1, 2]`. Thus, use 2 sets of brackets to add/change
+    data attributes: `G.edges[1, 2]['weight'] = 4`
+    (For multigraphs: `MG.edges[u, v, key][name] = value`).
+
+    **Shortcuts:**
+
+    Many common graph features allow python syntax to speed reporting.
+
+    >>> 1 in G  # check if node in graph
+    True
+    >>> [n for n in G if n < 3]  # iterate through nodes
+    [1, 2]
+    >>> len(G)  # number of nodes in graph
+    5
+
+    Often the best way to traverse all edges of a graph is via the neighbors.
+    The neighbors are reported as an adjacency-dict `G.adj` or `G.adjacency()`
+
+    >>> for n, nbrsdict in G.adjacency():
+    ...     for nbr, eattr in nbrsdict.items():
+    ...         if "weight" in eattr:
+    ...             # Do something useful with the edges
+    ...             pass
+
+    But the edges reporting object is often more convenient:
+
+    >>> for u, v, weight in G.edges(data="weight"):
+    ...     if weight is not None:
+    ...         # Do something useful with the edges
+    ...         pass
+
+    **Reporting:**
+
+    Simple graph information is obtained using object-attributes and methods.
+    Reporting usually provides views instead of containers to reduce memory
+    usage. The views update as the graph is updated similarly to dict-views.
+    The objects `nodes`, `edges` and `adj` provide access to data attributes
+    via lookup (e.g. `nodes[n]`, `edges[u, v]`, `adj[u][v]`) and iteration
+    (e.g. `nodes.items()`, `nodes.data('color')`,
+    `nodes.data('color', default='blue')` and similarly for `edges`)
+    Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
+
+    For details on these and other miscellaneous methods, see below.
+
+    **Subclasses (Advanced):**
+
+    The Graph class uses a dict-of-dict-of-dict data structure.
+    The outer dict (node_dict) holds adjacency information keyed by node.
+    The next dict (adjlist_dict) represents the adjacency information and holds
+    edge data keyed by neighbor.  The inner dict (edge_attr_dict) represents
+    the edge data and holds edge attribute values keyed by attribute names.
+
+    Each of these three dicts can be replaced in a subclass by a user defined
+    dict-like object. In general, the dict-like features should be
+    maintained but extra features can be added. To replace one of the
+    dicts create a new graph class by changing the class(!) variable
+    holding the factory for that dict-like structure. The variable names are
+    node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,
+    adjlist_outer_dict_factory, edge_attr_dict_factory and graph_attr_dict_factory.
+
+    node_dict_factory : function, (default: dict)
+        Factory function to be used to create the dict containing node
+        attributes, keyed by node id.
+        It should require no arguments and return a dict-like object
+
+    node_attr_dict_factory: function, (default: dict)
+        Factory function to be used to create the node attribute
+        dict which holds attribute values keyed by attribute name.
+        It should require no arguments and return a dict-like object
+
+    adjlist_outer_dict_factory : function, (default: dict)
+        Factory function to be used to create the outer-most dict
+        in the data structure that holds adjacency info keyed by node.
+        It should require no arguments and return a dict-like object.
+
+    adjlist_inner_dict_factory : function, optional (default: dict)
+        Factory function to be used to create the adjacency list
+        dict which holds edge data keyed by neighbor.
+        It should require no arguments and return a dict-like object
+
+    edge_attr_dict_factory : function, optional (default: dict)
+        Factory function to be used to create the edge attribute
+        dict which holds attribute values keyed by attribute name.
+        It should require no arguments and return a dict-like object.
+
+    graph_attr_dict_factory : function, (default: dict)
+        Factory function to be used to create the graph attribute
+        dict which holds attribute values keyed by attribute name.
+        It should require no arguments and return a dict-like object.
+
+    Typically, if your extension doesn't impact the data structure all
+    methods will inherited without issue except: `to_directed/to_undirected`.
+    By default these methods create a DiGraph/Graph class and you probably
+    want them to create your extension of a DiGraph/Graph. To facilitate
+    this we define two class variables that you can set in your subclass.
+
+    to_directed_class : callable, (default: DiGraph or MultiDiGraph)
+        Class to create a new graph structure in the `to_directed` method.
+        If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
+
+    to_undirected_class : callable, (default: Graph or MultiGraph)
+        Class to create a new graph structure in the `to_undirected` method.
+        If `None`, a NetworkX class (Graph or MultiGraph) is used.
+
+    **Subclassing Example**
+
+    Create a low memory graph class that effectively disallows edge
+    attributes by using a single attribute dict for all edges.
+    This reduces the memory used, but you lose edge attributes.
+
+    >>> class ThinGraph(nx.Graph):
+    ...     all_edge_dict = {"weight": 1}
+    ...
+    ...     def single_edge_dict(self):
+    ...         return self.all_edge_dict
+    ...
+    ...     edge_attr_dict_factory = single_edge_dict
+    >>> G = ThinGraph()
+    >>> G.add_edge(2, 1)
+    >>> G[2][1]
+    {'weight': 1}
+    >>> G.add_edge(2, 2)
+    >>> G[2][1] is G[2][2]
+    True
+    """
+
+    _adj = _CachedPropertyResetterAdjAndSucc()  # type: ignore[assignment]
+    _succ = _adj  # type: ignore[has-type]
+    _pred = _CachedPropertyResetterPred()
+
+    # This __new__ method just does what Python itself does automatically.
+    # We include it here as part of the dispatchable/backend interface.
+    # If your goal is to understand how the graph classes work, you can ignore
+    # this method, even when subclassing the base classes. If you are subclassing
+    # in order to provide a backend that allows class instantiation, this method
+    # can be overridden to return your own backend graph class.
+    @nx._dispatchable(name="digraph__new__", graphs=None, returns_graph=True)
+    def __new__(cls, *args, **kwargs):
+        return object.__new__(cls)
+
+    def __init__(self, incoming_graph_data=None, **attr):
+        """Initialize a graph with edges, name, or graph attributes.
+
+        Parameters
+        ----------
+        incoming_graph_data : input graph (optional, default: None)
+            Data to initialize graph.  If None (default) an empty
+            graph is created.  The data can be an edge list, or any
+            NetworkX graph object.  If the corresponding optional Python
+            packages are installed the data can also be a 2D NumPy array, a
+            SciPy sparse array, or a PyGraphviz graph.
+
+        attr : keyword arguments, optional (default= no attributes)
+            Attributes to add to graph as key=value pairs.
+
+        See Also
+        --------
+        convert
+
+        Examples
+        --------
+        >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G = nx.Graph(name="my graph")
+        >>> e = [(1, 2), (2, 3), (3, 4)]  # list of edges
+        >>> G = nx.Graph(e)
+
+        Arbitrary graph attribute pairs (key=value) may be assigned
+
+        >>> G = nx.Graph(e, day="Friday")
+        >>> G.graph
+        {'day': 'Friday'}
+
+        """
+        self.graph = self.graph_attr_dict_factory()  # dictionary for graph attributes
+        self._node = self.node_dict_factory()  # dictionary for node attr
+        # We store two adjacency lists:
+        # the predecessors of node n are stored in the dict self._pred
+        # the successors of node n are stored in the dict self._succ=self._adj
+        self._adj = self.adjlist_outer_dict_factory()  # empty adjacency dict successor
+        self._pred = self.adjlist_outer_dict_factory()  # predecessor
+        # Note: self._succ = self._adj  # successor
+
+        self.__networkx_cache__ = {}
+        # attempt to load graph with data
+        if incoming_graph_data is not None:
+            convert.to_networkx_graph(incoming_graph_data, create_using=self)
+        # load graph attributes (must be after convert)
+        attr.pop("backend", None)  # Ignore explicit `backend="networkx"`
+        self.graph.update(attr)
+
+    @cached_property
+    def adj(self):
+        """Graph adjacency object holding the neighbors of each node.
+
+        This object is a read-only dict-like structure with node keys
+        and neighbor-dict values.  The neighbor-dict is keyed by neighbor
+        to the edge-data-dict.  So `G.adj[3][2]['color'] = 'blue'` sets
+        the color of the edge `(3, 2)` to `"blue"`.
+
+        Iterating over G.adj behaves like a dict. Useful idioms include
+        `for nbr, datadict in G.adj[n].items():`.
+
+        The neighbor information is also provided by subscripting the graph.
+        So `for nbr, foovalue in G[node].data('foo', default=1):` works.
+
+        For directed graphs, `G.adj` holds outgoing (successor) info.
+        """
+        return AdjacencyView(self._succ)
+
+    @cached_property
+    def succ(self):
+        """Graph adjacency object holding the successors of each node.
+
+        This object is a read-only dict-like structure with node keys
+        and neighbor-dict values.  The neighbor-dict is keyed by neighbor
+        to the edge-data-dict.  So `G.succ[3][2]['color'] = 'blue'` sets
+        the color of the edge `(3, 2)` to `"blue"`.
+
+        Iterating over G.succ behaves like a dict. Useful idioms include
+        `for nbr, datadict in G.succ[n].items():`.  A data-view not provided
+        by dicts also exists: `for nbr, foovalue in G.succ[node].data('foo'):`
+        and a default can be set via a `default` argument to the `data` method.
+
+        The neighbor information is also provided by subscripting the graph.
+        So `for nbr, foovalue in G[node].data('foo', default=1):` works.
+
+        For directed graphs, `G.adj` is identical to `G.succ`.
+        """
+        return AdjacencyView(self._succ)
+
+    @cached_property
+    def pred(self):
+        """Graph adjacency object holding the predecessors of each node.
+
+        This object is a read-only dict-like structure with node keys
+        and neighbor-dict values.  The neighbor-dict is keyed by neighbor
+        to the edge-data-dict.  So `G.pred[2][3]['color'] = 'blue'` sets
+        the color of the edge `(3, 2)` to `"blue"`.
+
+        Iterating over G.pred behaves like a dict. Useful idioms include
+        `for nbr, datadict in G.pred[n].items():`.  A data-view not provided
+        by dicts also exists: `for nbr, foovalue in G.pred[node].data('foo'):`
+        A default can be set via a `default` argument to the `data` method.
+        """
+        return AdjacencyView(self._pred)
+
+    def add_node(self, node_for_adding, **attr):
+        """Add a single node `node_for_adding` and update node attributes.
+
+        Parameters
+        ----------
+        node_for_adding : node
+            A node can be any hashable Python object except None.
+        attr : keyword arguments, optional
+            Set or change node attributes using key=value.
+
+        See Also
+        --------
+        add_nodes_from
+
+        Examples
+        --------
+        >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.add_node(1)
+        >>> G.add_node("Hello")
+        >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
+        >>> G.add_node(K3)
+        >>> G.number_of_nodes()
+        3
+
+        Use keywords set/change node attributes:
+
+        >>> G.add_node(1, size=10)
+        >>> G.add_node(3, weight=0.4, UTM=("13S", 382871, 3972649))
+
+        Notes
+        -----
+        A hashable object is one that can be used as a key in a Python
+        dictionary. This includes strings, numbers, tuples of strings
+        and numbers, etc.
+
+        On many platforms hashable items also include mutables such as
+        NetworkX Graphs, though one should be careful that the hash
+        doesn't change on mutables.
+        """
+        if node_for_adding not in self._succ:
+            if node_for_adding is None:
+                raise ValueError("None cannot be a node")
+            self._succ[node_for_adding] = self.adjlist_inner_dict_factory()
+            self._pred[node_for_adding] = self.adjlist_inner_dict_factory()
+            attr_dict = self._node[node_for_adding] = self.node_attr_dict_factory()
+            attr_dict.update(attr)
+        else:  # update attr even if node already exists
+            self._node[node_for_adding].update(attr)
+        nx._clear_cache(self)
+
+    def add_nodes_from(self, nodes_for_adding, **attr):
+        """Add multiple nodes.
+
+        Parameters
+        ----------
+        nodes_for_adding : iterable container
+            A container of nodes (list, dict, set, etc.).
+            OR
+            A container of (node, attribute dict) tuples.
+            Node attributes are updated using the attribute dict.
+        attr : keyword arguments, optional (default= no attributes)
+            Update attributes for all nodes in nodes.
+            Node attributes specified in nodes as a tuple take
+            precedence over attributes specified via keyword arguments.
+
+        See Also
+        --------
+        add_node
+
+        Notes
+        -----
+        When adding nodes from an iterator over the graph you are changing,
+        a `RuntimeError` can be raised with message:
+        `RuntimeError: dictionary changed size during iteration`. This
+        happens when the graph's underlying dictionary is modified during
+        iteration. To avoid this error, evaluate the iterator into a separate
+        object, e.g. by using `list(iterator_of_nodes)`, and pass this
+        object to `G.add_nodes_from`.
+
+        Examples
+        --------
+        >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.add_nodes_from("Hello")
+        >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
+        >>> G.add_nodes_from(K3)
+        >>> sorted(G.nodes(), key=str)
+        [0, 1, 2, 'H', 'e', 'l', 'o']
+
+        Use keywords to update specific node attributes for every node.
+
+        >>> G.add_nodes_from([1, 2], size=10)
+        >>> G.add_nodes_from([3, 4], weight=0.4)
+
+        Use (node, attrdict) tuples to update attributes for specific nodes.
+
+        >>> G.add_nodes_from([(1, dict(size=11)), (2, {"color": "blue"})])
+        >>> G.nodes[1]["size"]
+        11
+        >>> H = nx.Graph()
+        >>> H.add_nodes_from(G.nodes(data=True))
+        >>> H.nodes[1]["size"]
+        11
+
+        Evaluate an iterator over a graph if using it to modify the same graph
+
+        >>> G = nx.DiGraph([(0, 1), (1, 2), (3, 4)])
+        >>> # wrong way - will raise RuntimeError
+        >>> # G.add_nodes_from(n + 1 for n in G.nodes)
+        >>> # correct way
+        >>> G.add_nodes_from(list(n + 1 for n in G.nodes))
+        """
+        for n in nodes_for_adding:
+            try:
+                newnode = n not in self._node
+                newdict = attr
+            except TypeError:
+                n, ndict = n
+                newnode = n not in self._node
+                newdict = attr.copy()
+                newdict.update(ndict)
+            if newnode:
+                if n is None:
+                    raise ValueError("None cannot be a node")
+                self._succ[n] = self.adjlist_inner_dict_factory()
+                self._pred[n] = self.adjlist_inner_dict_factory()
+                self._node[n] = self.node_attr_dict_factory()
+            self._node[n].update(newdict)
+        nx._clear_cache(self)
+
+    def remove_node(self, n):
+        """Remove node n.
+
+        Removes the node n and all adjacent edges.
+        Attempting to remove a nonexistent node will raise an exception.
+
+        Parameters
+        ----------
+        n : node
+           A node in the graph
+
+        Raises
+        ------
+        NetworkXError
+           If n is not in the graph.
+
+        See Also
+        --------
+        remove_nodes_from
+
+        Examples
+        --------
+        >>> G = nx.path_graph(3)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> list(G.edges)
+        [(0, 1), (1, 2)]
+        >>> G.remove_node(1)
+        >>> list(G.edges)
+        []
+
+        """
+        try:
+            nbrs = self._succ[n]
+            del self._node[n]
+        except KeyError as err:  # NetworkXError if n not in self
+            raise NetworkXError(f"The node {n} is not in the digraph.") from err
+        for u in nbrs:
+            del self._pred[u][n]  # remove all edges n-u in digraph
+        del self._succ[n]  # remove node from succ
+        for u in self._pred[n]:
+            del self._succ[u][n]  # remove all edges n-u in digraph
+        del self._pred[n]  # remove node from pred
+        nx._clear_cache(self)
+
+    def remove_nodes_from(self, nodes):
+        """Remove multiple nodes.
+
+        Parameters
+        ----------
+        nodes : iterable container
+            A container of nodes (list, dict, set, etc.).  If a node
+            in the container is not in the graph it is silently ignored.
+
+        See Also
+        --------
+        remove_node
+
+        Notes
+        -----
+        When removing nodes from an iterator over the graph you are changing,
+        a `RuntimeError` will be raised with message:
+        `RuntimeError: dictionary changed size during iteration`. This
+        happens when the graph's underlying dictionary is modified during
+        iteration. To avoid this error, evaluate the iterator into a separate
+        object, e.g. by using `list(iterator_of_nodes)`, and pass this
+        object to `G.remove_nodes_from`.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(3)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> e = list(G.nodes)
+        >>> e
+        [0, 1, 2]
+        >>> G.remove_nodes_from(e)
+        >>> list(G.nodes)
+        []
+
+        Evaluate an iterator over a graph if using it to modify the same graph
+
+        >>> G = nx.DiGraph([(0, 1), (1, 2), (3, 4)])
+        >>> # this command will fail, as the graph's dict is modified during iteration
+        >>> # G.remove_nodes_from(n for n in G.nodes if n < 2)
+        >>> # this command will work, since the dictionary underlying graph is not modified
+        >>> G.remove_nodes_from(list(n for n in G.nodes if n < 2))
+        """
+        for n in nodes:
+            try:
+                succs = self._succ[n]
+                del self._node[n]
+                for u in succs:
+                    del self._pred[u][n]  # remove all edges n-u in digraph
+                del self._succ[n]  # now remove node
+                for u in self._pred[n]:
+                    del self._succ[u][n]  # remove all edges n-u in digraph
+                del self._pred[n]  # now remove node
+            except KeyError:
+                pass  # silent failure on remove
+        nx._clear_cache(self)
+
+    def add_edge(self, u_of_edge, v_of_edge, **attr):
+        """Add an edge between u and v.
+
+        The nodes u and v will be automatically added if they are
+        not already in the graph.
+
+        Edge attributes can be specified with keywords or by directly
+        accessing the edge's attribute dictionary. See examples below.
+
+        Parameters
+        ----------
+        u_of_edge, v_of_edge : nodes
+            Nodes can be, for example, strings or numbers.
+            Nodes must be hashable (and not None) Python objects.
+        attr : keyword arguments, optional
+            Edge data (or labels or objects) can be assigned using
+            keyword arguments.
+
+        See Also
+        --------
+        add_edges_from : add a collection of edges
+
+        Notes
+        -----
+        Adding an edge that already exists updates the edge data.
+
+        Many NetworkX algorithms designed for weighted graphs use
+        an edge attribute (by default `weight`) to hold a numerical value.
+
+        Examples
+        --------
+        The following all add the edge e=(1, 2) to graph G:
+
+        >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> e = (1, 2)
+        >>> G.add_edge(1, 2)  # explicit two-node form
+        >>> G.add_edge(*e)  # single edge as tuple of two nodes
+        >>> G.add_edges_from([(1, 2)])  # add edges from iterable container
+
+        Associate data to edges using keywords:
+
+        >>> G.add_edge(1, 2, weight=3)
+        >>> G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
+
+        For non-string attribute keys, use subscript notation.
+
+        >>> G.add_edge(1, 2)
+        >>> G[1][2].update({0: 5})
+        >>> G.edges[1, 2].update({0: 5})
+        """
+        u, v = u_of_edge, v_of_edge
+        # add nodes
+        if u not in self._succ:
+            if u is None:
+                raise ValueError("None cannot be a node")
+            self._succ[u] = self.adjlist_inner_dict_factory()
+            self._pred[u] = self.adjlist_inner_dict_factory()
+            self._node[u] = self.node_attr_dict_factory()
+        if v not in self._succ:
+            if v is None:
+                raise ValueError("None cannot be a node")
+            self._succ[v] = self.adjlist_inner_dict_factory()
+            self._pred[v] = self.adjlist_inner_dict_factory()
+            self._node[v] = self.node_attr_dict_factory()
+        # add the edge
+        datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
+        datadict.update(attr)
+        self._succ[u][v] = datadict
+        self._pred[v][u] = datadict
+        nx._clear_cache(self)
+
+    def add_edges_from(self, ebunch_to_add, **attr):
+        """Add all the edges in ebunch_to_add.
+
+        Parameters
+        ----------
+        ebunch_to_add : container of edges
+            Each edge given in the container will be added to the
+            graph. The edges must be given as 2-tuples (u, v) or
+            3-tuples (u, v, d) where d is a dictionary containing edge data.
+        attr : keyword arguments, optional
+            Edge data (or labels or objects) can be assigned using
+            keyword arguments.
+
+        See Also
+        --------
+        add_edge : add a single edge
+        add_weighted_edges_from : convenient way to add weighted edges
+
+        Notes
+        -----
+        Adding the same edge twice has no effect but any edge data
+        will be updated when each duplicate edge is added.
+
+        Edge attributes specified in an ebunch take precedence over
+        attributes specified via keyword arguments.
+
+        When adding edges from an iterator over the graph you are changing,
+        a `RuntimeError` can be raised with message:
+        `RuntimeError: dictionary changed size during iteration`. This
+        happens when the graph's underlying dictionary is modified during
+        iteration. To avoid this error, evaluate the iterator into a separate
+        object, e.g. by using `list(iterator_of_edges)`, and pass this
+        object to `G.add_edges_from`.
+
+        Examples
+        --------
+        >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.add_edges_from([(0, 1), (1, 2)])  # using a list of edge tuples
+        >>> e = zip(range(0, 3), range(1, 4))
+        >>> G.add_edges_from(e)  # Add the path graph 0-1-2-3
+
+        Associate data to edges
+
+        >>> G.add_edges_from([(1, 2), (2, 3)], weight=3)
+        >>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
+
+        Evaluate an iterator over a graph if using it to modify the same graph
+
+        >>> G = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
+        >>> # Grow graph by one new node, adding edges to all existing nodes.
+        >>> # wrong way - will raise RuntimeError
+        >>> # G.add_edges_from(((5, n) for n in G.nodes))
+        >>> # right way - note that there will be no self-edge for node 5
+        >>> G.add_edges_from(list((5, n) for n in G.nodes))
+        """
+        for e in ebunch_to_add:
+            ne = len(e)
+            if ne == 3:
+                u, v, dd = e
+            elif ne == 2:
+                u, v = e
+                dd = {}
+            else:
+                raise NetworkXError(f"Edge tuple {e} must be a 2-tuple or 3-tuple.")
+            if u not in self._succ:
+                if u is None:
+                    raise ValueError("None cannot be a node")
+                self._succ[u] = self.adjlist_inner_dict_factory()
+                self._pred[u] = self.adjlist_inner_dict_factory()
+                self._node[u] = self.node_attr_dict_factory()
+            if v not in self._succ:
+                if v is None:
+                    raise ValueError("None cannot be a node")
+                self._succ[v] = self.adjlist_inner_dict_factory()
+                self._pred[v] = self.adjlist_inner_dict_factory()
+                self._node[v] = self.node_attr_dict_factory()
+            datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
+            datadict.update(attr)
+            datadict.update(dd)
+            self._succ[u][v] = datadict
+            self._pred[v][u] = datadict
+        nx._clear_cache(self)
+
+    def remove_edge(self, u, v):
+        """Remove the edge between u and v.
+
+        Parameters
+        ----------
+        u, v : nodes
+            Remove the edge between nodes u and v.
+
+        Raises
+        ------
+        NetworkXError
+            If there is not an edge between u and v.
+
+        See Also
+        --------
+        remove_edges_from : remove a collection of edges
+
+        Examples
+        --------
+        >>> G = nx.Graph()  # or DiGraph, etc
+        >>> nx.add_path(G, [0, 1, 2, 3])
+        >>> G.remove_edge(0, 1)
+        >>> e = (1, 2)
+        >>> G.remove_edge(*e)  # unpacks e from an edge tuple
+        >>> e = (2, 3, {"weight": 7})  # an edge with attribute data
+        >>> G.remove_edge(*e[:2])  # select first part of edge tuple
+        """
+        try:
+            del self._succ[u][v]
+            del self._pred[v][u]
+        except KeyError as err:
+            raise NetworkXError(f"The edge {u}-{v} not in graph.") from err
+        nx._clear_cache(self)
+
+    def remove_edges_from(self, ebunch):
+        """Remove all edges specified in ebunch.
+
+        Parameters
+        ----------
+        ebunch: list or container of edge tuples
+            Each edge given in the list or container will be removed
+            from the graph. The edges can be:
+
+                - 2-tuples (u, v) edge between u and v.
+                - 3-tuples (u, v, k) where k is ignored.
+
+        See Also
+        --------
+        remove_edge : remove a single edge
+
+        Notes
+        -----
+        Will fail silently if an edge in ebunch is not in the graph.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> ebunch = [(1, 2), (2, 3)]
+        >>> G.remove_edges_from(ebunch)
+        """
+        for e in ebunch:
+            u, v = e[:2]  # ignore edge data
+            if u in self._succ and v in self._succ[u]:
+                del self._succ[u][v]
+                del self._pred[v][u]
+        nx._clear_cache(self)
+
+    def has_successor(self, u, v):
+        """Returns True if node u has successor v.
+
+        This is true if graph has the edge u->v.
+        """
+        return u in self._succ and v in self._succ[u]
+
+    def has_predecessor(self, u, v):
+        """Returns True if node u has predecessor v.
+
+        This is true if graph has the edge u<-v.
+        """
+        return u in self._pred and v in self._pred[u]
+
+    def successors(self, n):
+        """Returns an iterator over successor nodes of n.
+
+        A successor of n is a node m such that there exists a directed
+        edge from n to m.
+
+        Parameters
+        ----------
+        n : node
+           A node in the graph
+
+        Raises
+        ------
+        NetworkXError
+           If n is not in the graph.
+
+        See Also
+        --------
+        predecessors
+
+        Notes
+        -----
+        neighbors() and successors() are the same.
+        """
+        try:
+            return iter(self._succ[n])
+        except KeyError as err:
+            raise NetworkXError(f"The node {n} is not in the digraph.") from err
+
+    # digraph definitions
+    neighbors = successors
+
+    def predecessors(self, n):
+        """Returns an iterator over predecessor nodes of n.
+
+        A predecessor of n is a node m such that there exists a directed
+        edge from m to n.
+
+        Parameters
+        ----------
+        n : node
+           A node in the graph
+
+        Raises
+        ------
+        NetworkXError
+           If n is not in the graph.
+
+        See Also
+        --------
+        successors
+        """
+        try:
+            return iter(self._pred[n])
+        except KeyError as err:
+            raise NetworkXError(f"The node {n} is not in the digraph.") from err
+
+    @cached_property
+    def edges(self):
+        """An OutEdgeView of the DiGraph as G.edges or G.edges().
+
+        edges(self, nbunch=None, data=False, default=None)
+
+        The OutEdgeView provides set-like operations on the edge-tuples
+        as well as edge attribute lookup. When called, it also provides
+        an EdgeDataView object which allows control of access to edge
+        attributes (but does not provide set-like operations).
+        Hence, `G.edges[u, v]['color']` provides the value of the color
+        attribute for edge `(u, v)` while
+        `for (u, v, c) in G.edges.data('color', default='red'):`
+        iterates through all the edges yielding the color attribute
+        with default `'red'` if no color attribute exists.
+
+        Parameters
+        ----------
+        nbunch : single node, container, or all nodes (default= all nodes)
+            The view will only report edges from these nodes.
+        data : string or bool, optional (default=False)
+            The edge attribute returned in 3-tuple (u, v, ddict[data]).
+            If True, return edge attribute dict in 3-tuple (u, v, ddict).
+            If False, return 2-tuple (u, v).
+        default : value, optional (default=None)
+            Value used for edges that don't have the requested attribute.
+            Only relevant if data is not True or False.
+
+        Returns
+        -------
+        edges : OutEdgeView
+            A view of edge attributes, usually it iterates over (u, v)
+            or (u, v, d) tuples of edges, but can also be used for
+            attribute lookup as `edges[u, v]['foo']`.
+
+        See Also
+        --------
+        in_edges, out_edges
+
+        Notes
+        -----
+        Nodes in nbunch that are not in the graph will be (quietly) ignored.
+        For directed graphs this returns the out-edges.
+
+        Examples
+        --------
+        >>> G = nx.DiGraph()  # or MultiDiGraph, etc
+        >>> nx.add_path(G, [0, 1, 2])
+        >>> G.add_edge(2, 3, weight=5)
+        >>> [e for e in G.edges]
+        [(0, 1), (1, 2), (2, 3)]
+        >>> G.edges.data()  # default data is {} (empty dict)
+        OutEdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})])
+        >>> G.edges.data("weight", default=1)
+        OutEdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)])
+        >>> G.edges([0, 2])  # only edges originating from these nodes
+        OutEdgeDataView([(0, 1), (2, 3)])
+        >>> G.edges(0)  # only edges from node 0
+        OutEdgeDataView([(0, 1)])
+
+        """
+        return OutEdgeView(self)
+
+    # alias out_edges to edges
+    @cached_property
+    def out_edges(self):
+        return OutEdgeView(self)
+
+    out_edges.__doc__ = edges.__doc__
+
+    @cached_property
+    def in_edges(self):
+        """A view of the in edges of the graph as G.in_edges or G.in_edges().
+
+        in_edges(self, nbunch=None, data=False, default=None):
+
+        Parameters
+        ----------
+        nbunch : single node, container, or all nodes (default= all nodes)
+            The view will only report edges incident to these nodes.
+        data : string or bool, optional (default=False)
+            The edge attribute returned in 3-tuple (u, v, ddict[data]).
+            If True, return edge attribute dict in 3-tuple (u, v, ddict).
+            If False, return 2-tuple (u, v).
+        default : value, optional (default=None)
+            Value used for edges that don't have the requested attribute.
+            Only relevant if data is not True or False.
+
+        Returns
+        -------
+        in_edges : InEdgeView or InEdgeDataView
+            A view of edge attributes, usually it iterates over (u, v)
+            or (u, v, d) tuples of edges, but can also be used for
+            attribute lookup as `edges[u, v]['foo']`.
+
+        Examples
+        --------
+        >>> G = nx.DiGraph()
+        >>> G.add_edge(1, 2, color="blue")
+        >>> G.in_edges()
+        InEdgeView([(1, 2)])
+        >>> G.in_edges(nbunch=2)
+        InEdgeDataView([(1, 2)])
+
+        See Also
+        --------
+        edges
+        """
+        return InEdgeView(self)
+
+    @cached_property
+    def degree(self):
+        """A DegreeView for the Graph as G.degree or G.degree().
+
+        The node degree is the number of edges adjacent to the node.
+        The weighted node degree is the sum of the edge weights for
+        edges incident to that node.
+
+        This object provides an iterator for (node, degree) as well as
+        lookup for the degree for a single node.
+
+        Parameters
+        ----------
+        nbunch : single node, container, or all nodes (default= all nodes)
+            The view will only report edges incident to these nodes.
+
+        weight : string or None, optional (default=None)
+           The name of an edge attribute that holds the numerical value used
+           as a weight.  If None, then each edge has weight 1.
+           The degree is the sum of the edge weights adjacent to the node.
+
+        Returns
+        -------
+        DiDegreeView or int
+            If multiple nodes are requested (the default), returns a `DiDegreeView`
+            mapping nodes to their degree.
+            If a single node is requested, returns the degree of the node as an integer.
+
+        See Also
+        --------
+        in_degree, out_degree
+
+        Examples
+        --------
+        >>> G = nx.DiGraph()  # or MultiDiGraph
+        >>> nx.add_path(G, [0, 1, 2, 3])
+        >>> G.degree(0)  # node 0 with degree 1
+        1
+        >>> list(G.degree([0, 1, 2]))
+        [(0, 1), (1, 2), (2, 2)]
+
+        """
+        return DiDegreeView(self)
+
+    @cached_property
+    def in_degree(self):
+        """An InDegreeView for (node, in_degree) or in_degree for single node.
+
+        The node in_degree is the number of edges pointing to the node.
+        The weighted node degree is the sum of the edge weights for
+        edges incident to that node.
+
+        This object provides an iteration over (node, in_degree) as well as
+        lookup for the degree for a single node.
+
+        Parameters
+        ----------
+        nbunch : single node, container, or all nodes (default= all nodes)
+            The view will only report edges incident to these nodes.
+
+        weight : string or None, optional (default=None)
+           The name of an edge attribute that holds the numerical value used
+           as a weight.  If None, then each edge has weight 1.
+           The degree is the sum of the edge weights adjacent to the node.
+
+        Returns
+        -------
+        If a single node is requested
+        deg : int
+            In-degree of the node
+
+        OR if multiple nodes are requested
+        nd_iter : iterator
+            The iterator returns two-tuples of (node, in-degree).
+
+        See Also
+        --------
+        degree, out_degree
+
+        Examples
+        --------
+        >>> G = nx.DiGraph()
+        >>> nx.add_path(G, [0, 1, 2, 3])
+        >>> G.in_degree(0)  # node 0 with degree 0
+        0
+        >>> list(G.in_degree([0, 1, 2]))
+        [(0, 0), (1, 1), (2, 1)]
+
+        """
+        return InDegreeView(self)
+
+    @cached_property
+    def out_degree(self):
+        """An OutDegreeView for (node, out_degree)
+
+        The node out_degree is the number of edges pointing out of the node.
+        The weighted node degree is the sum of the edge weights for
+        edges incident to that node.
+
+        This object provides an iterator over (node, out_degree) as well as
+        lookup for the degree for a single node.
+
+        Parameters
+        ----------
+        nbunch : single node, container, or all nodes (default= all nodes)
+            The view will only report edges incident to these nodes.
+
+        weight : string or None, optional (default=None)
+           The name of an edge attribute that holds the numerical value used
+           as a weight.  If None, then each edge has weight 1.
+           The degree is the sum of the edge weights adjacent to the node.
+
+        Returns
+        -------
+        If a single node is requested
+        deg : int
+            Out-degree of the node
+
+        OR if multiple nodes are requested
+        nd_iter : iterator
+            The iterator returns two-tuples of (node, out-degree).
+
+        See Also
+        --------
+        degree, in_degree
+
+        Examples
+        --------
+        >>> G = nx.DiGraph()
+        >>> nx.add_path(G, [0, 1, 2, 3])
+        >>> G.out_degree(0)  # node 0 with degree 1
+        1
+        >>> list(G.out_degree([0, 1, 2]))
+        [(0, 1), (1, 1), (2, 1)]
+
+        """
+        return OutDegreeView(self)
+
+    def clear(self):
+        """Remove all nodes and edges from the graph.
+
+        This also removes the name, and all graph, node, and edge attributes.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.clear()
+        >>> list(G.nodes)
+        []
+        >>> list(G.edges)
+        []
+
+        """
+        self._succ.clear()
+        self._pred.clear()
+        self._node.clear()
+        self.graph.clear()
+        nx._clear_cache(self)
+
+    def clear_edges(self):
+        """Remove all edges from the graph without altering nodes.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.clear_edges()
+        >>> list(G.nodes)
+        [0, 1, 2, 3]
+        >>> list(G.edges)
+        []
+
+        """
+        for predecessor_dict in self._pred.values():
+            predecessor_dict.clear()
+        for successor_dict in self._succ.values():
+            successor_dict.clear()
+        nx._clear_cache(self)
+
+    def is_multigraph(self):
+        """Returns True if graph is a multigraph, False otherwise."""
+        return False
+
+    def is_directed(self):
+        """Returns True if graph is directed, False otherwise."""
+        return True
+
+    def to_undirected(self, reciprocal=False, as_view=False):
+        """Returns an undirected representation of the digraph.
+
+        Parameters
+        ----------
+        reciprocal : bool (optional)
+          If True only keep edges that appear in both directions
+          in the original digraph.
+        as_view : bool (optional, default=False)
+          If True return an undirected view of the original directed graph.
+
+        Returns
+        -------
+        G : Graph
+            An undirected graph with the same name and nodes and
+            with edge (u, v, data) if either (u, v, data) or (v, u, data)
+            is in the digraph.  If both edges exist in digraph and
+            their edge data is different, only one edge is created
+            with an arbitrary choice of which edge data to use.
+            You must check and correct for this manually if desired.
+
+        See Also
+        --------
+        Graph, copy, add_edge, add_edges_from
+
+        Notes
+        -----
+        If edges in both directions (u, v) and (v, u) exist in the
+        graph, attributes for the new undirected edge will be a combination of
+        the attributes of the directed edges.  The edge data is updated
+        in the (arbitrary) order that the edges are encountered.  For
+        more customized control of the edge attributes use add_edge().
+
+        This returns a "deepcopy" of the edge, node, and
+        graph attributes which attempts to completely copy
+        all of the data and references.
+
+        This is in contrast to the similar G=DiGraph(D) which returns a
+        shallow copy of the data.
+
+        See the Python copy module for more information on shallow
+        and deep copies, https://docs.python.org/3/library/copy.html.
+
+        Warning: If you have subclassed DiGraph to use dict-like objects
+        in the data structure, those changes do not transfer to the
+        Graph created by this method.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(2)  # or MultiGraph, etc
+        >>> H = G.to_directed()
+        >>> list(H.edges)
+        [(0, 1), (1, 0)]
+        >>> G2 = H.to_undirected()
+        >>> list(G2.edges)
+        [(0, 1)]
+        """
+        graph_class = self.to_undirected_class()
+        if as_view is True:
+            return nx.graphviews.generic_graph_view(self, graph_class)
+        # deepcopy when not a view
+        G = graph_class()
+        G.graph.update(deepcopy(self.graph))
+        G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
+        if reciprocal is True:
+            G.add_edges_from(
+                (u, v, deepcopy(d))
+                for u, nbrs in self._adj.items()
+                for v, d in nbrs.items()
+                if v in self._pred[u]
+            )
+        else:
+            G.add_edges_from(
+                (u, v, deepcopy(d))
+                for u, nbrs in self._adj.items()
+                for v, d in nbrs.items()
+            )
+        return G
+
+    def reverse(self, copy=True):
+        """Returns the reverse of the graph.
+
+        The reverse is a graph with the same nodes and edges
+        but with the directions of the edges reversed.
+
+        Parameters
+        ----------
+        copy : bool optional (default=True)
+            If True, return a new DiGraph holding the reversed edges.
+            If False, the reverse graph is created using a view of
+            the original graph.
+        """
+        if copy:
+            H = self.__class__()
+            H.graph.update(deepcopy(self.graph))
+            H.add_nodes_from((n, deepcopy(d)) for n, d in self.nodes.items())
+            H.add_edges_from((v, u, deepcopy(d)) for u, v, d in self.edges(data=True))
+            return H
+        return nx.reverse_view(self)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/filters.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/filters.py
new file mode 100644
index 0000000000000000000000000000000000000000..e989e22bb6d7e79b6eab34103edd263d82694fd4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/filters.py
@@ -0,0 +1,95 @@
+"""Filter factories to hide or show sets of nodes and edges.
+
+These filters return the function used when creating `SubGraph`.
+"""
+
+__all__ = [
+    "no_filter",
+    "hide_nodes",
+    "hide_edges",
+    "hide_multiedges",
+    "hide_diedges",
+    "hide_multidiedges",
+    "show_nodes",
+    "show_edges",
+    "show_multiedges",
+    "show_diedges",
+    "show_multidiedges",
+]
+
+
+def no_filter(*items):
+    """Returns a filter function that always evaluates to True."""
+    return True
+
+
+def hide_nodes(nodes):
+    """Returns a filter function that hides specific nodes."""
+    nodes = set(nodes)
+    return lambda node: node not in nodes
+
+
+def hide_diedges(edges):
+    """Returns a filter function that hides specific directed edges."""
+    edges = {(u, v) for u, v in edges}
+    return lambda u, v: (u, v) not in edges
+
+
+def hide_edges(edges):
+    """Returns a filter function that hides specific undirected edges."""
+    alledges = set(edges) | {(v, u) for (u, v) in edges}
+    return lambda u, v: (u, v) not in alledges
+
+
+def hide_multidiedges(edges):
+    """Returns a filter function that hides specific multi-directed edges."""
+    edges = {(u, v, k) for u, v, k in edges}
+    return lambda u, v, k: (u, v, k) not in edges
+
+
+def hide_multiedges(edges):
+    """Returns a filter function that hides specific multi-undirected edges."""
+    alledges = set(edges) | {(v, u, k) for (u, v, k) in edges}
+    return lambda u, v, k: (u, v, k) not in alledges
+
+
+# write show_nodes as a class to make SubGraph pickleable
+class show_nodes:
+    """Filter class to show specific nodes.
+
+    Attach the set of nodes as an attribute to speed up this commonly used filter
+
+    Note that another allowed attribute for filters is to store the number of nodes
+    on the filter as attribute `length` (used in `__len__`). It is a user
+    responsibility to ensure this attribute is accurate if present.
+    """
+
+    def __init__(self, nodes):
+        self.nodes = set(nodes)
+
+    def __call__(self, node):
+        return node in self.nodes
+
+
+def show_diedges(edges):
+    """Returns a filter function that shows specific directed edges."""
+    edges = {(u, v) for u, v in edges}
+    return lambda u, v: (u, v) in edges
+
+
+def show_edges(edges):
+    """Returns a filter function that shows specific undirected edges."""
+    alledges = set(edges) | {(v, u) for (u, v) in edges}
+    return lambda u, v: (u, v) in alledges
+
+
+def show_multidiedges(edges):
+    """Returns a filter function that shows specific multi-directed edges."""
+    edges = {(u, v, k) for u, v, k in edges}
+    return lambda u, v, k: (u, v, k) in edges
+
+
+def show_multiedges(edges):
+    """Returns a filter function that shows specific multi-undirected edges."""
+    alledges = set(edges) | {(v, u, k) for (u, v, k) in edges}
+    return lambda u, v, k: (u, v, k) in alledges
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/function.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/function.py
new file mode 100644
index 0000000000000000000000000000000000000000..31f088ede87f01b2815514f1914f67e222ff66b6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/function.py
@@ -0,0 +1,1549 @@
+"""Functional interface to graph methods and assorted utilities."""
+
+from collections import Counter
+from itertools import chain
+
+import networkx as nx
+from networkx.utils import not_implemented_for, pairwise
+
+__all__ = [
+    "nodes",
+    "edges",
+    "degree",
+    "degree_histogram",
+    "neighbors",
+    "number_of_nodes",
+    "number_of_edges",
+    "density",
+    "is_directed",
+    "freeze",
+    "is_frozen",
+    "subgraph",
+    "induced_subgraph",
+    "edge_subgraph",
+    "restricted_view",
+    "to_directed",
+    "to_undirected",
+    "add_star",
+    "add_path",
+    "add_cycle",
+    "create_empty_copy",
+    "set_node_attributes",
+    "get_node_attributes",
+    "remove_node_attributes",
+    "set_edge_attributes",
+    "get_edge_attributes",
+    "remove_edge_attributes",
+    "all_neighbors",
+    "non_neighbors",
+    "non_edges",
+    "common_neighbors",
+    "is_weighted",
+    "is_negatively_weighted",
+    "is_empty",
+    "selfloop_edges",
+    "nodes_with_selfloops",
+    "number_of_selfloops",
+    "path_weight",
+    "is_path",
+    "describe",
+]
+
+
+def nodes(G):
+    """Returns a NodeView over the graph nodes.
+
+    This function wraps the :func:`G.nodes ` property.
+    """
+    return G.nodes()
+
+
+def edges(G, nbunch=None):
+    """Returns an edge view of edges incident to nodes in nbunch.
+
+    Return all edges if nbunch is unspecified or nbunch=None.
+
+    For digraphs, edges=out_edges
+
+    This function wraps the :func:`G.edges ` property.
+    """
+    return G.edges(nbunch)
+
+
+def degree(G, nbunch=None, weight=None):
+    """Returns a degree view of single node or of nbunch of nodes.
+    If nbunch is omitted, then return degrees of *all* nodes.
+
+    This function wraps the :func:`G.degree ` property.
+    """
+    return G.degree(nbunch, weight)
+
+
+def neighbors(G, n):
+    """Returns an iterator over all neighbors of node n.
+
+    This function wraps the :func:`G.neighbors ` function.
+    """
+    return G.neighbors(n)
+
+
+def number_of_nodes(G):
+    """Returns the number of nodes in the graph.
+
+    This function wraps the :func:`G.number_of_nodes ` function.
+    """
+    return G.number_of_nodes()
+
+
+def number_of_edges(G):
+    """Returns the number of edges in the graph.
+
+    This function wraps the :func:`G.number_of_edges ` function.
+    """
+    return G.number_of_edges()
+
+
+def density(G):
+    r"""Returns the density of a graph.
+
+    The density for undirected graphs is
+
+    .. math::
+
+       d = \frac{2m}{n(n-1)},
+
+    and for directed graphs is
+
+    .. math::
+
+       d = \frac{m}{n(n-1)},
+
+    where `n` is the number of nodes and `m`  is the number of edges in `G`.
+
+    Notes
+    -----
+    The density is 0 for a graph without edges and 1 for a complete graph.
+    The density of multigraphs can be higher than 1.
+
+    Self loops are counted in the total number of edges so graphs with self
+    loops can have density higher than 1.
+    """
+    n = number_of_nodes(G)
+    m = number_of_edges(G)
+    if m == 0 or n <= 1:
+        return 0
+    d = m / (n * (n - 1))
+    if not G.is_directed():
+        d *= 2
+    return d
+
+
+def degree_histogram(G):
+    """Returns a list of the frequency of each degree value.
+
+    Parameters
+    ----------
+    G : Networkx graph
+       A graph
+
+    Returns
+    -------
+    hist : list
+       A list of frequencies of degrees.
+       The degree values are the index in the list.
+
+    Notes
+    -----
+    Note: the bins are width one, hence len(list) can be large
+    (Order(number_of_edges))
+    """
+    counts = Counter(d for n, d in G.degree())
+    return [counts.get(i, 0) for i in range(max(counts) + 1 if counts else 0)]
+
+
+def is_directed(G):
+    """Return True if graph is directed."""
+    return G.is_directed()
+
+
+def frozen(*args, **kwargs):
+    """Dummy method for raising errors when trying to modify frozen graphs"""
+    raise nx.NetworkXError("Frozen graph can't be modified")
+
+
+def freeze(G):
+    """Modify graph to prevent further change by adding or removing
+    nodes or edges.
+
+    Node and edge data can still be modified.
+
+    Parameters
+    ----------
+    G : graph
+      A NetworkX graph
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> G = nx.freeze(G)
+    >>> try:
+    ...     G.add_edge(4, 5)
+    ... except nx.NetworkXError as err:
+    ...     print(str(err))
+    Frozen graph can't be modified
+
+    Notes
+    -----
+    To "unfreeze" a graph you must make a copy by creating a new graph object:
+
+    >>> graph = nx.path_graph(4)
+    >>> frozen_graph = nx.freeze(graph)
+    >>> unfrozen_graph = nx.Graph(frozen_graph)
+    >>> nx.is_frozen(unfrozen_graph)
+    False
+
+    See Also
+    --------
+    is_frozen
+    """
+    G.add_node = frozen
+    G.add_nodes_from = frozen
+    G.remove_node = frozen
+    G.remove_nodes_from = frozen
+    G.add_edge = frozen
+    G.add_edges_from = frozen
+    G.add_weighted_edges_from = frozen
+    G.remove_edge = frozen
+    G.remove_edges_from = frozen
+    G.clear = frozen
+    G.clear_edges = frozen
+    G.frozen = True
+    return G
+
+
+def is_frozen(G):
+    """Returns True if graph is frozen.
+
+    Parameters
+    ----------
+    G : graph
+      A NetworkX graph
+
+    See Also
+    --------
+    freeze
+    """
+    try:
+        return G.frozen
+    except AttributeError:
+        return False
+
+
+def add_star(G_to_add_to, nodes_for_star, **attr):
+    """Add a star to Graph G_to_add_to.
+
+    The first node in `nodes_for_star` is the middle of the star.
+    It is connected to all other nodes.
+
+    Parameters
+    ----------
+    G_to_add_to : graph
+        A NetworkX graph
+    nodes_for_star : iterable container
+        A container of nodes.
+    attr : keyword arguments, optional (default= no attributes)
+        Attributes to add to every edge in star.
+
+    See Also
+    --------
+    add_path, add_cycle
+
+    Examples
+    --------
+    >>> G = nx.Graph()
+    >>> nx.add_star(G, [0, 1, 2, 3])
+    >>> nx.add_star(G, [10, 11, 12], weight=2)
+    """
+    nlist = iter(nodes_for_star)
+    try:
+        v = next(nlist)
+    except StopIteration:
+        return
+    G_to_add_to.add_node(v)
+    edges = ((v, n) for n in nlist)
+    G_to_add_to.add_edges_from(edges, **attr)
+
+
+def add_path(G_to_add_to, nodes_for_path, **attr):
+    """Add a path to the Graph G_to_add_to.
+
+    Parameters
+    ----------
+    G_to_add_to : graph
+        A NetworkX graph
+    nodes_for_path : iterable container
+        A container of nodes.  A path will be constructed from
+        the nodes (in order) and added to the graph.
+    attr : keyword arguments, optional (default= no attributes)
+        Attributes to add to every edge in path.
+
+    See Also
+    --------
+    add_star, add_cycle
+
+    Examples
+    --------
+    >>> G = nx.Graph()
+    >>> nx.add_path(G, [0, 1, 2, 3])
+    >>> nx.add_path(G, [10, 11, 12], weight=7)
+    """
+    nlist = iter(nodes_for_path)
+    try:
+        first_node = next(nlist)
+    except StopIteration:
+        return
+    G_to_add_to.add_node(first_node)
+    G_to_add_to.add_edges_from(pairwise(chain((first_node,), nlist)), **attr)
+
+
+def add_cycle(G_to_add_to, nodes_for_cycle, **attr):
+    """Add a cycle to the Graph G_to_add_to.
+
+    Parameters
+    ----------
+    G_to_add_to : graph
+        A NetworkX graph
+    nodes_for_cycle: iterable container
+        A container of nodes.  A cycle will be constructed from
+        the nodes (in order) and added to the graph.
+    attr : keyword arguments, optional (default= no attributes)
+        Attributes to add to every edge in cycle.
+
+    See Also
+    --------
+    add_path, add_star
+
+    Examples
+    --------
+    >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+    >>> nx.add_cycle(G, [0, 1, 2, 3])
+    >>> nx.add_cycle(G, [10, 11, 12], weight=7)
+    """
+    nlist = iter(nodes_for_cycle)
+    try:
+        first_node = next(nlist)
+    except StopIteration:
+        return
+    G_to_add_to.add_node(first_node)
+    G_to_add_to.add_edges_from(
+        pairwise(chain((first_node,), nlist), cyclic=True), **attr
+    )
+
+
+def subgraph(G, nbunch):
+    """Returns the subgraph induced on nodes in nbunch.
+
+    Parameters
+    ----------
+    G : graph
+       A NetworkX graph
+
+    nbunch : list, iterable
+       A container of nodes that will be iterated through once (thus
+       it should be an iterator or be iterable).  Each element of the
+       container should be a valid node type: any hashable type except
+       None.  If nbunch is None, return all edges data in the graph.
+       Nodes in nbunch that are not in the graph will be (quietly)
+       ignored.
+
+    Notes
+    -----
+    subgraph(G) calls G.subgraph()
+    """
+    return G.subgraph(nbunch)
+
+
+def induced_subgraph(G, nbunch):
+    """Returns a SubGraph view of `G` showing only nodes in nbunch.
+
+    The induced subgraph of a graph on a set of nodes N is the
+    graph with nodes N and edges from G which have both ends in N.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+    nbunch : node, container of nodes or None (for all nodes)
+
+    Returns
+    -------
+    subgraph : SubGraph View
+        A read-only view of the subgraph in `G` induced by the nodes.
+        Changes to the graph `G` will be reflected in the view.
+
+    Notes
+    -----
+    To create a mutable subgraph with its own copies of nodes
+    edges and attributes use `subgraph.copy()` or `Graph(subgraph)`
+
+    For an inplace reduction of a graph to a subgraph you can remove nodes:
+    `G.remove_nodes_from(n in G if n not in set(nbunch))`
+
+    If you are going to compute subgraphs of your subgraphs you could
+    end up with a chain of views that can be very slow once the chain
+    has about 15 views in it. If they are all induced subgraphs, you
+    can short-cut the chain by making them all subgraphs of the original
+    graph. The graph class method `G.subgraph` does this when `G` is
+    a subgraph. In contrast, this function allows you to choose to build
+    chains or not, as you wish. The returned subgraph is a view on `G`.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+    >>> H = nx.induced_subgraph(G, [0, 1, 3])
+    >>> list(H.edges)
+    [(0, 1)]
+    >>> list(H.nodes)
+    [0, 1, 3]
+    """
+    induced_nodes = nx.filters.show_nodes(G.nbunch_iter(nbunch))
+    return nx.subgraph_view(G, filter_node=induced_nodes)
+
+
+def edge_subgraph(G, edges):
+    """Returns a view of the subgraph induced by the specified edges.
+
+    The induced subgraph contains each edge in `edges` and each
+    node incident to any of those edges.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+    edges : iterable
+        An iterable of edges. Edges not present in `G` are ignored.
+
+    Returns
+    -------
+    subgraph : SubGraph View
+        A read-only edge-induced subgraph of `G`.
+        Changes to `G` are reflected in the view.
+
+    Notes
+    -----
+    To create a mutable subgraph with its own copies of nodes
+    edges and attributes use `subgraph.copy()` or `Graph(subgraph)`
+
+    If you create a subgraph of a subgraph recursively you can end up
+    with a chain of subgraphs that becomes very slow with about 15
+    nested subgraph views. Luckily the edge_subgraph filter nests
+    nicely so you can use the original graph as G in this function
+    to avoid chains. We do not rule out chains programmatically so
+    that odd cases like an `edge_subgraph` of a `restricted_view`
+    can be created.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(5)
+    >>> H = G.edge_subgraph([(0, 1), (3, 4)])
+    >>> list(H.nodes)
+    [0, 1, 3, 4]
+    >>> list(H.edges)
+    [(0, 1), (3, 4)]
+    """
+    nxf = nx.filters
+    edges = set(edges)
+    nodes = set()
+    for e in edges:
+        nodes.update(e[:2])
+    induced_nodes = nxf.show_nodes(nodes)
+    if G.is_multigraph():
+        if G.is_directed():
+            induced_edges = nxf.show_multidiedges(edges)
+        else:
+            induced_edges = nxf.show_multiedges(edges)
+    else:
+        if G.is_directed():
+            induced_edges = nxf.show_diedges(edges)
+        else:
+            induced_edges = nxf.show_edges(edges)
+    return nx.subgraph_view(G, filter_node=induced_nodes, filter_edge=induced_edges)
+
+
+def restricted_view(G, nodes, edges):
+    """Returns a view of `G` with hidden nodes and edges.
+
+    The resulting subgraph filters out node `nodes` and edges `edges`.
+    Filtered out nodes also filter out any of their edges.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+    nodes : iterable
+        An iterable of nodes. Nodes not present in `G` are ignored.
+    edges : iterable
+        An iterable of edges. Edges not present in `G` are ignored.
+
+    Returns
+    -------
+    subgraph : SubGraph View
+        A read-only restricted view of `G` filtering out nodes and edges.
+        Changes to `G` are reflected in the view.
+
+    Notes
+    -----
+    To create a mutable subgraph with its own copies of nodes
+    edges and attributes use `subgraph.copy()` or `Graph(subgraph)`
+
+    If you create a subgraph of a subgraph recursively you may end up
+    with a chain of subgraph views. Such chains can get quite slow
+    for lengths near 15. To avoid long chains, try to make your subgraph
+    based on the original graph.  We do not rule out chains programmatically
+    so that odd cases like an `edge_subgraph` of a `restricted_view`
+    can be created.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(5)
+    >>> H = nx.restricted_view(G, [0], [(1, 2), (3, 4)])
+    >>> list(H.nodes)
+    [1, 2, 3, 4]
+    >>> list(H.edges)
+    [(2, 3)]
+    """
+    nxf = nx.filters
+    hide_nodes = nxf.hide_nodes(nodes)
+    if G.is_multigraph():
+        if G.is_directed():
+            hide_edges = nxf.hide_multidiedges(edges)
+        else:
+            hide_edges = nxf.hide_multiedges(edges)
+    else:
+        if G.is_directed():
+            hide_edges = nxf.hide_diedges(edges)
+        else:
+            hide_edges = nxf.hide_edges(edges)
+    return nx.subgraph_view(G, filter_node=hide_nodes, filter_edge=hide_edges)
+
+
+def to_directed(graph):
+    """Returns a directed view of the graph `graph`.
+
+    Identical to graph.to_directed(as_view=True)
+    Note that graph.to_directed defaults to `as_view=False`
+    while this function always provides a view.
+    """
+    return graph.to_directed(as_view=True)
+
+
+def to_undirected(graph):
+    """Returns an undirected view of the graph `graph`.
+
+    Identical to graph.to_undirected(as_view=True)
+    Note that graph.to_undirected defaults to `as_view=False`
+    while this function always provides a view.
+    """
+    return graph.to_undirected(as_view=True)
+
+
+def create_empty_copy(G, with_data=True):
+    """Returns a copy of the graph G with all of the edges removed.
+
+    Parameters
+    ----------
+    G : graph
+       A NetworkX graph
+
+    with_data :  bool (default=True)
+       Propagate Graph and Nodes data to the new graph.
+
+    See Also
+    --------
+    empty_graph
+
+    """
+    H = G.__class__()
+    H.add_nodes_from(G.nodes(data=with_data))
+    if with_data:
+        H.graph.update(G.graph)
+    return H
+
+
+@nx._dispatchable(preserve_node_attrs=True, mutates_input=True)
+def set_node_attributes(G, values, name=None):
+    """Sets node attributes from a given value or dictionary of values.
+
+    .. Warning:: The call order of arguments `values` and `name`
+        switched between v1.x & v2.x.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+
+    values : scalar value, dict-like
+        What the node attribute should be set to.  If `values` is
+        not a dictionary, then it is treated as a single attribute value
+        that is then applied to every node in `G`.  This means that if
+        you provide a mutable object, like a list, updates to that object
+        will be reflected in the node attribute for every node.
+        The attribute name will be `name`.
+
+        If `values` is a dict or a dict of dict, it should be keyed
+        by node to either an attribute value or a dict of attribute key/value
+        pairs used to update the node's attributes.
+
+    name : string (optional, default=None)
+        Name of the node attribute to set if values is a scalar.
+
+    Examples
+    --------
+    After computing some property of the nodes of a graph, you may want
+    to assign a node attribute to store the value of that property for
+    each node::
+
+        >>> G = nx.path_graph(3)
+        >>> bb = nx.betweenness_centrality(G)
+        >>> isinstance(bb, dict)
+        True
+        >>> nx.set_node_attributes(G, bb, "betweenness")
+        >>> G.nodes[1]["betweenness"]
+        1.0
+
+    If you provide a list as the second argument, updates to the list
+    will be reflected in the node attribute for each node::
+
+        >>> G = nx.path_graph(3)
+        >>> labels = []
+        >>> nx.set_node_attributes(G, labels, "labels")
+        >>> labels.append("foo")
+        >>> G.nodes[0]["labels"]
+        ['foo']
+        >>> G.nodes[1]["labels"]
+        ['foo']
+        >>> G.nodes[2]["labels"]
+        ['foo']
+
+    If you provide a dictionary of dictionaries as the second argument,
+    the outer dictionary is assumed to be keyed by node to an inner
+    dictionary of node attributes for that node::
+
+        >>> G = nx.path_graph(3)
+        >>> attrs = {0: {"attr1": 20, "attr2": "nothing"}, 1: {"attr2": 3}}
+        >>> nx.set_node_attributes(G, attrs)
+        >>> G.nodes[0]["attr1"]
+        20
+        >>> G.nodes[0]["attr2"]
+        'nothing'
+        >>> G.nodes[1]["attr2"]
+        3
+        >>> G.nodes[2]
+        {}
+
+    Note that if the dictionary contains nodes that are not in `G`, the
+    values are silently ignored::
+
+        >>> G = nx.Graph()
+        >>> G.add_node(0)
+        >>> nx.set_node_attributes(G, {0: "red", 1: "blue"}, name="color")
+        >>> G.nodes[0]["color"]
+        'red'
+        >>> 1 in G.nodes
+        False
+
+    """
+    # Set node attributes based on type of `values`
+    if name is not None:  # `values` must not be a dict of dict
+        try:  # `values` is a dict
+            for n, v in values.items():
+                try:
+                    G.nodes[n][name] = values[n]
+                except KeyError:
+                    pass
+        except AttributeError:  # `values` is a constant
+            for n in G:
+                G.nodes[n][name] = values
+    else:  # `values` must be dict of dict
+        for n, d in values.items():
+            try:
+                G.nodes[n].update(d)
+            except KeyError:
+                pass
+    nx._clear_cache(G)
+
+
+@nx._dispatchable(node_attrs={"name": "default"})
+def get_node_attributes(G, name, default=None):
+    """Get node attributes from graph
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+
+    name : string
+       Attribute name
+
+    default: object (default=None)
+       Default value of the node attribute if there is no value set for that
+       node in graph. If `None` then nodes without this attribute are not
+       included in the returned dict.
+
+    Returns
+    -------
+    Dictionary of attributes keyed by node.
+
+    Examples
+    --------
+    >>> G = nx.Graph()
+    >>> G.add_nodes_from([1, 2, 3], color="red")
+    >>> color = nx.get_node_attributes(G, "color")
+    >>> color[1]
+    'red'
+    >>> G.add_node(4)
+    >>> color = nx.get_node_attributes(G, "color", default="yellow")
+    >>> color[4]
+    'yellow'
+    """
+    if default is not None:
+        return {n: d.get(name, default) for n, d in G.nodes.items()}
+    return {n: d[name] for n, d in G.nodes.items() if name in d}
+
+
+@nx._dispatchable(preserve_node_attrs=True, mutates_input=True)
+def remove_node_attributes(G, *attr_names, nbunch=None):
+    """Remove node attributes from all nodes in the graph.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+
+    *attr_names : List of Strings
+        The attribute names to remove from the graph.
+
+    nbunch : List of Nodes
+        Remove the node attributes only from the nodes in this list.
+
+    Examples
+    --------
+    >>> G = nx.Graph()
+    >>> G.add_nodes_from([1, 2, 3], color="blue")
+    >>> nx.get_node_attributes(G, "color")
+    {1: 'blue', 2: 'blue', 3: 'blue'}
+    >>> nx.remove_node_attributes(G, "color")
+    >>> nx.get_node_attributes(G, "color")
+    {}
+    """
+
+    if nbunch is None:
+        nbunch = G.nodes()
+
+    for attr in attr_names:
+        for n, d in G.nodes(data=True):
+            if n in nbunch:
+                try:
+                    del d[attr]
+                except KeyError:
+                    pass
+
+
+@nx._dispatchable(preserve_edge_attrs=True, mutates_input=True)
+def set_edge_attributes(G, values, name=None):
+    """Sets edge attributes from a given value or dictionary of values.
+
+    .. Warning:: The call order of arguments `values` and `name`
+        switched between v1.x & v2.x.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+
+    values : scalar value, dict-like
+        What the edge attribute should be set to.  If `values` is
+        not a dictionary, then it is treated as a single attribute value
+        that is then applied to every edge in `G`.  This means that if
+        you provide a mutable object, like a list, updates to that object
+        will be reflected in the edge attribute for each edge.  The attribute
+        name will be `name`.
+
+        If `values` is a dict or a dict of dict, it should be keyed
+        by edge tuple to either an attribute value or a dict of attribute
+        key/value pairs used to update the edge's attributes.
+        For multigraphs, the edge tuples must be of the form ``(u, v, key)``,
+        where `u` and `v` are nodes and `key` is the edge key.
+        For non-multigraphs, the keys must be tuples of the form ``(u, v)``.
+
+    name : string (optional, default=None)
+        Name of the edge attribute to set if values is a scalar.
+
+    Examples
+    --------
+    After computing some property of the edges of a graph, you may want
+    to assign a edge attribute to store the value of that property for
+    each edge::
+
+        >>> G = nx.path_graph(3)
+        >>> bb = nx.edge_betweenness_centrality(G, normalized=False)
+        >>> nx.set_edge_attributes(G, bb, "betweenness")
+        >>> G.edges[1, 2]["betweenness"]
+        2.0
+
+    If you provide a list as the second argument, updates to the list
+    will be reflected in the edge attribute for each edge::
+
+        >>> labels = []
+        >>> nx.set_edge_attributes(G, labels, "labels")
+        >>> labels.append("foo")
+        >>> G.edges[0, 1]["labels"]
+        ['foo']
+        >>> G.edges[1, 2]["labels"]
+        ['foo']
+
+    If you provide a dictionary of dictionaries as the second argument,
+    the entire dictionary will be used to update edge attributes::
+
+        >>> G = nx.path_graph(3)
+        >>> attrs = {(0, 1): {"attr1": 20, "attr2": "nothing"}, (1, 2): {"attr2": 3}}
+        >>> nx.set_edge_attributes(G, attrs)
+        >>> G[0][1]["attr1"]
+        20
+        >>> G[0][1]["attr2"]
+        'nothing'
+        >>> G[1][2]["attr2"]
+        3
+
+    The attributes of one Graph can be used to set those of another.
+
+        >>> H = nx.path_graph(3)
+        >>> nx.set_edge_attributes(H, G.edges)
+
+    Note that if the dict contains edges that are not in `G`, they are
+    silently ignored::
+
+        >>> G = nx.Graph([(0, 1)])
+        >>> nx.set_edge_attributes(G, {(1, 2): {"weight": 2.0}})
+        >>> (1, 2) in G.edges()
+        False
+
+    For multigraphs, the `values` dict is expected to be keyed by 3-tuples
+    including the edge key::
+
+        >>> MG = nx.MultiGraph()
+        >>> edges = [(0, 1), (0, 1)]
+        >>> MG.add_edges_from(edges)  # Returns list of edge keys
+        [0, 1]
+        >>> attributes = {(0, 1, 0): {"cost": 21}, (0, 1, 1): {"cost": 7}}
+        >>> nx.set_edge_attributes(MG, attributes)
+        >>> MG[0][1][0]["cost"]
+        21
+        >>> MG[0][1][1]["cost"]
+        7
+
+    If MultiGraph attributes are desired for a Graph, you must convert the 3-tuple
+    multiedge to a 2-tuple edge and the last multiedge's attribute value will
+    overwrite the previous values. Continuing from the previous case we get::
+
+        >>> H = nx.path_graph([0, 1, 2])
+        >>> nx.set_edge_attributes(H, {(u, v): ed for u, v, ed in MG.edges.data()})
+        >>> nx.get_edge_attributes(H, "cost")
+        {(0, 1): 7}
+
+    """
+    if name is not None:
+        # `values` does not contain attribute names
+        try:
+            # if `values` is a dict using `.items()` => {edge: value}
+            if G.is_multigraph():
+                for (u, v, key), value in values.items():
+                    try:
+                        G._adj[u][v][key][name] = value
+                    except KeyError:
+                        pass
+            else:
+                for (u, v), value in values.items():
+                    try:
+                        G._adj[u][v][name] = value
+                    except KeyError:
+                        pass
+        except AttributeError:
+            # treat `values` as a constant
+            for u, v, data in G.edges(data=True):
+                data[name] = values
+    else:
+        # `values` consists of doct-of-dict {edge: {attr: value}} shape
+        if G.is_multigraph():
+            for (u, v, key), d in values.items():
+                try:
+                    G._adj[u][v][key].update(d)
+                except KeyError:
+                    pass
+        else:
+            for (u, v), d in values.items():
+                try:
+                    G._adj[u][v].update(d)
+                except KeyError:
+                    pass
+    nx._clear_cache(G)
+
+
+@nx._dispatchable(edge_attrs={"name": "default"})
+def get_edge_attributes(G, name, default=None):
+    """Get edge attributes from graph
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+
+    name : string
+       Attribute name
+
+    default: object (default=None)
+       Default value of the edge attribute if there is no value set for that
+       edge in graph. If `None` then edges without this attribute are not
+       included in the returned dict.
+
+    Returns
+    -------
+    Dictionary of attributes keyed by edge. For (di)graphs, the keys are
+    2-tuples of the form: (u, v). For multi(di)graphs, the keys are 3-tuples of
+    the form: (u, v, key).
+
+    Examples
+    --------
+    >>> G = nx.Graph()
+    >>> nx.add_path(G, [1, 2, 3], color="red")
+    >>> color = nx.get_edge_attributes(G, "color")
+    >>> color[(1, 2)]
+    'red'
+    >>> G.add_edge(3, 4)
+    >>> color = nx.get_edge_attributes(G, "color", default="yellow")
+    >>> color[(3, 4)]
+    'yellow'
+    """
+    if G.is_multigraph():
+        edges = G.edges(keys=True, data=True)
+    else:
+        edges = G.edges(data=True)
+    if default is not None:
+        return {x[:-1]: x[-1].get(name, default) for x in edges}
+    return {x[:-1]: x[-1][name] for x in edges if name in x[-1]}
+
+
+@nx._dispatchable(preserve_edge_attrs=True, mutates_input=True)
+def remove_edge_attributes(G, *attr_names, ebunch=None):
+    """Remove edge attributes from all edges in the graph.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+
+    *attr_names : List of Strings
+        The attribute names to remove from the graph.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(3)
+    >>> nx.set_edge_attributes(G, {(u, v): u + v for u, v in G.edges()}, name="weight")
+    >>> nx.get_edge_attributes(G, "weight")
+    {(0, 1): 1, (1, 2): 3}
+    >>> remove_edge_attributes(G, "weight")
+    >>> nx.get_edge_attributes(G, "weight")
+    {}
+    """
+    if ebunch is None:
+        ebunch = G.edges(keys=True) if G.is_multigraph() else G.edges()
+
+    for attr in attr_names:
+        edges = (
+            G.edges(keys=True, data=True) if G.is_multigraph() else G.edges(data=True)
+        )
+        for *e, d in edges:
+            if tuple(e) in ebunch:
+                try:
+                    del d[attr]
+                except KeyError:
+                    pass
+
+
+def all_neighbors(graph, node):
+    """Returns all of the neighbors of a node in the graph.
+
+    If the graph is directed returns predecessors as well as successors.
+
+    Parameters
+    ----------
+    graph : NetworkX graph
+        Graph to find neighbors.
+    node : node
+        The node whose neighbors will be returned.
+
+    Returns
+    -------
+    neighbors : iterator
+        Iterator of neighbors
+
+    Raises
+    ------
+    NetworkXError
+        If `node` is not in the graph.
+
+    Examples
+    --------
+    For undirected graphs, this function is equivalent to ``G.neighbors(node)``.
+
+    >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+    >>> list(nx.all_neighbors(G, 1))
+    [0, 2]
+
+    For directed graphs, this function returns both predecessors and successors,
+    which may include duplicates if a node is both a predecessor and successor
+    (e.g., in bidirectional edges or self-loops).
+
+    >>> DG = nx.DiGraph([(0, 1), (1, 2), (2, 1)])
+    >>> list(nx.all_neighbors(DG, 1))
+    [0, 2, 2]
+
+    Notes
+    -----
+    This function iterates over all neighbors (both predecessors and successors).
+
+    See Also
+    --------
+    Graph.neighbors : Returns successors for both Graph and DiGraph
+    DiGraph.predecessors : Returns predecessors for directed graphs only
+    DiGraph.successors : Returns successors for directed graphs only
+    """
+    if graph.is_directed():
+        values = chain(graph.predecessors(node), graph.successors(node))
+    else:
+        values = graph.neighbors(node)
+    return values
+
+
+def non_neighbors(graph, node):
+    """Returns the non-neighbors of the node in the graph.
+
+    Parameters
+    ----------
+    graph : NetworkX graph
+        Graph to find neighbors.
+
+    node : node
+        The node whose neighbors will be returned.
+
+    Returns
+    -------
+    non_neighbors : set
+        Set of nodes in the graph that are not neighbors of the node.
+    """
+    return graph._adj.keys() - graph._adj[node].keys() - {node}
+
+
+def non_edges(graph):
+    """Returns the nonexistent edges in the graph.
+
+    Parameters
+    ----------
+    graph : NetworkX graph.
+        Graph to find nonexistent edges.
+
+    Returns
+    -------
+    non_edges : iterator
+        Iterator of edges that are not in the graph.
+    """
+    if graph.is_directed():
+        for u in graph:
+            for v in non_neighbors(graph, u):
+                yield (u, v)
+    else:
+        nodes = set(graph)
+        while nodes:
+            u = nodes.pop()
+            for v in nodes - set(graph[u]):
+                yield (u, v)
+
+
+@not_implemented_for("directed")
+def common_neighbors(G, u, v):
+    """Returns the common neighbors of two nodes in a graph.
+
+    Parameters
+    ----------
+    G : graph
+        A NetworkX undirected graph.
+
+    u, v : nodes
+        Nodes in the graph.
+
+    Returns
+    -------
+    cnbors : set
+        Set of common neighbors of u and v in the graph.
+
+    Raises
+    ------
+    NetworkXError
+        If u or v is not a node in the graph.
+
+    Examples
+    --------
+    >>> G = nx.complete_graph(5)
+    >>> sorted(nx.common_neighbors(G, 0, 1))
+    [2, 3, 4]
+    """
+    if u not in G:
+        raise nx.NetworkXError("u is not in the graph.")
+    if v not in G:
+        raise nx.NetworkXError("v is not in the graph.")
+
+    return G._adj[u].keys() & G._adj[v].keys() - {u, v}
+
+
+@nx._dispatchable(preserve_edge_attrs=True)
+def is_weighted(G, edge=None, weight="weight"):
+    """Returns True if `G` has weighted edges.
+
+    Parameters
+    ----------
+    G : graph
+        A NetworkX graph.
+
+    edge : tuple, optional
+        A 2-tuple specifying the only edge in `G` that will be tested. If
+        None, then every edge in `G` is tested.
+
+    weight: string, optional
+        The attribute name used to query for edge weights.
+
+    Returns
+    -------
+    bool
+        A boolean signifying if `G`, or the specified edge, is weighted.
+
+    Raises
+    ------
+    NetworkXError
+        If the specified edge does not exist.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> nx.is_weighted(G)
+    False
+    >>> nx.is_weighted(G, (2, 3))
+    False
+
+    >>> G = nx.DiGraph()
+    >>> G.add_edge(1, 2, weight=1)
+    >>> nx.is_weighted(G)
+    True
+
+    """
+    if edge is not None:
+        data = G.get_edge_data(*edge)
+        if data is None:
+            msg = f"Edge {edge!r} does not exist."
+            raise nx.NetworkXError(msg)
+        return weight in data
+
+    if is_empty(G):
+        # Special handling required since: all([]) == True
+        return False
+
+    return all(weight in data for u, v, data in G.edges(data=True))
+
+
+@nx._dispatchable(edge_attrs="weight")
+def is_negatively_weighted(G, edge=None, weight="weight"):
+    """Returns True if `G` has negatively weighted edges.
+
+    Parameters
+    ----------
+    G : graph
+        A NetworkX graph.
+
+    edge : tuple, optional
+        A 2-tuple specifying the only edge in `G` that will be tested. If
+        None, then every edge in `G` is tested.
+
+    weight: string, optional
+        The attribute name used to query for edge weights.
+
+    Returns
+    -------
+    bool
+        A boolean signifying if `G`, or the specified edge, is negatively
+        weighted.
+
+    Raises
+    ------
+    NetworkXError
+        If the specified edge does not exist.
+
+    Examples
+    --------
+    >>> G = nx.Graph()
+    >>> G.add_edges_from([(1, 3), (2, 4), (2, 6)])
+    >>> G.add_edge(1, 2, weight=4)
+    >>> nx.is_negatively_weighted(G, (1, 2))
+    False
+    >>> G[2][4]["weight"] = -2
+    >>> nx.is_negatively_weighted(G)
+    True
+    >>> G = nx.DiGraph()
+    >>> edges = [("0", "3", 3), ("0", "1", -5), ("1", "0", -2)]
+    >>> G.add_weighted_edges_from(edges)
+    >>> nx.is_negatively_weighted(G)
+    True
+
+    """
+    if edge is not None:
+        data = G.get_edge_data(*edge)
+        if data is None:
+            msg = f"Edge {edge!r} does not exist."
+            raise nx.NetworkXError(msg)
+        return weight in data and data[weight] < 0
+
+    return any(weight in data and data[weight] < 0 for u, v, data in G.edges(data=True))
+
+
+@nx._dispatchable
+def is_empty(G):
+    """Returns True if `G` has no edges.
+
+    Parameters
+    ----------
+    G : graph
+        A NetworkX graph.
+
+    Returns
+    -------
+    bool
+        True if `G` has no edges, and False otherwise.
+
+    Notes
+    -----
+    An empty graph can have nodes but not edges. The empty graph with zero
+    nodes is known as the null graph. This is an $O(n)$ operation where n
+    is the number of nodes in the graph.
+
+    """
+    return not any(G._adj.values())
+
+
+def nodes_with_selfloops(G):
+    """Returns an iterator over nodes with self loops.
+
+    A node with a self loop has an edge with both ends adjacent
+    to that node.
+
+    Returns
+    -------
+    nodelist : iterator
+        A iterator over nodes with self loops.
+
+    See Also
+    --------
+    selfloop_edges, number_of_selfloops
+
+    Examples
+    --------
+    >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+    >>> G.add_edge(1, 1)
+    >>> G.add_edge(1, 2)
+    >>> list(nx.nodes_with_selfloops(G))
+    [1]
+
+    """
+    return (n for n, nbrs in G._adj.items() if n in nbrs)
+
+
+def selfloop_edges(G, data=False, keys=False, default=None):
+    """Returns an iterator over selfloop edges.
+
+    A selfloop edge has the same node at both ends.
+
+    Parameters
+    ----------
+    G : graph
+        A NetworkX graph.
+    data : string or bool, optional (default=False)
+        Return selfloop edges as two tuples (u, v) (data=False)
+        or three-tuples (u, v, datadict) (data=True)
+        or three-tuples (u, v, datavalue) (data='attrname')
+    keys : bool, optional (default=False)
+        If True, return edge keys with each edge.
+    default : value, optional (default=None)
+        Value used for edges that don't have the requested attribute.
+        Only relevant if data is not True or False.
+
+    Returns
+    -------
+    edgeiter : iterator over edge tuples
+        An iterator over all selfloop edges.
+
+    See Also
+    --------
+    nodes_with_selfloops, number_of_selfloops
+
+    Examples
+    --------
+    >>> G = nx.MultiGraph()  # or Graph, DiGraph, MultiDiGraph, etc
+    >>> ekey = G.add_edge(1, 1)
+    >>> ekey = G.add_edge(1, 2)
+    >>> list(nx.selfloop_edges(G))
+    [(1, 1)]
+    >>> list(nx.selfloop_edges(G, data=True))
+    [(1, 1, {})]
+    >>> list(nx.selfloop_edges(G, keys=True))
+    [(1, 1, 0)]
+    >>> list(nx.selfloop_edges(G, keys=True, data=True))
+    [(1, 1, 0, {})]
+    """
+    if data is True:
+        if G.is_multigraph():
+            if keys is True:
+                return (
+                    (n, n, k, d)
+                    for n, nbrs in G._adj.items()
+                    if n in nbrs
+                    for k, d in nbrs[n].items()
+                )
+            else:
+                return (
+                    (n, n, d)
+                    for n, nbrs in G._adj.items()
+                    if n in nbrs
+                    for d in nbrs[n].values()
+                )
+        else:
+            return ((n, n, nbrs[n]) for n, nbrs in G._adj.items() if n in nbrs)
+    elif data is not False:
+        if G.is_multigraph():
+            if keys is True:
+                return (
+                    (n, n, k, d.get(data, default))
+                    for n, nbrs in G._adj.items()
+                    if n in nbrs
+                    for k, d in nbrs[n].items()
+                )
+            else:
+                return (
+                    (n, n, d.get(data, default))
+                    for n, nbrs in G._adj.items()
+                    if n in nbrs
+                    for d in nbrs[n].values()
+                )
+        else:
+            return (
+                (n, n, nbrs[n].get(data, default))
+                for n, nbrs in G._adj.items()
+                if n in nbrs
+            )
+    else:
+        if G.is_multigraph():
+            if keys is True:
+                return (
+                    (n, n, k)
+                    for n, nbrs in G._adj.items()
+                    if n in nbrs
+                    for k in nbrs[n]
+                )
+            else:
+                return (
+                    (n, n)
+                    for n, nbrs in G._adj.items()
+                    if n in nbrs
+                    for i in range(len(nbrs[n]))  # for easy edge removal (#4068)
+                )
+        else:
+            return ((n, n) for n, nbrs in G._adj.items() if n in nbrs)
+
+
+@nx._dispatchable
+def number_of_selfloops(G):
+    """Returns the number of selfloop edges.
+
+    A selfloop edge has the same node at both ends.
+
+    Returns
+    -------
+    nloops : int
+        The number of selfloops.
+
+    See Also
+    --------
+    nodes_with_selfloops, selfloop_edges
+
+    Examples
+    --------
+    >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+    >>> G.add_edge(1, 1)
+    >>> G.add_edge(1, 2)
+    >>> nx.number_of_selfloops(G)
+    1
+    """
+    return sum(1 for _ in nx.selfloop_edges(G))
+
+
+def is_path(G, path):
+    """Returns whether or not the specified path exists.
+
+    For it to return True, every node on the path must exist and
+    each consecutive pair must be connected via one or more edges.
+
+    Parameters
+    ----------
+    G : graph
+        A NetworkX graph.
+
+    path : list
+        A list of nodes which defines the path to traverse
+
+    Returns
+    -------
+    bool
+        True if `path` is a valid path in `G`
+
+    """
+    try:
+        return all(nbr in G._adj[node] for node, nbr in nx.utils.pairwise(path))
+    except (KeyError, TypeError):
+        return False
+
+
+def path_weight(G, path, weight):
+    """Returns total cost associated with specified path and weight
+
+    Parameters
+    ----------
+    G : graph
+        A NetworkX graph.
+
+    path: list
+        A list of node labels which defines the path to traverse
+
+    weight: string
+        A string indicating which edge attribute to use for path cost
+
+    Returns
+    -------
+    cost: int or float
+        An integer or a float representing the total cost with respect to the
+        specified weight of the specified path
+
+    Raises
+    ------
+    NetworkXNoPath
+        If the specified edge does not exist.
+    """
+    multigraph = G.is_multigraph()
+    cost = 0
+
+    if not nx.is_path(G, path):
+        raise nx.NetworkXNoPath("path does not exist")
+    for node, nbr in nx.utils.pairwise(path):
+        if multigraph:
+            cost += min(v[weight] for v in G._adj[node][nbr].values())
+        else:
+            cost += G._adj[node][nbr][weight]
+    return cost
+
+
+def describe(G, describe_hook=None):
+    """Prints a description of the graph G.
+
+    By default, the description includes some basic properties of the graph.
+    You can also provide additional functions to compute and include
+    more properties in the description.
+
+    Parameters
+    ----------
+    G : graph
+        A NetworkX graph.
+
+    describe_hook: callable, optional (default=None)
+        A function that takes a graph as input and returns a
+        dictionary of additional properties to include in the description.
+        The keys of the dictionary are the property names, and the values
+        are the corresponding property values.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(5)
+    >>> nx.describe(G)
+    Number of nodes                : 5
+    Number of edges                : 4
+    Directed                       : False
+    Multigraph                     : False
+    Tree                           : True
+    Bipartite                      : True
+    Average degree (min, max)      : 1.60 (1, 2)
+    Number of connected components : 1
+
+    >>> def augment_description(G):
+    ...     return {"Average Shortest Path Length": nx.average_shortest_path_length(G)}
+    >>> nx.describe(G, describe_hook=augment_description)
+    Number of nodes                : 5
+    Number of edges                : 4
+    Directed                       : False
+    Multigraph                     : False
+    Tree                           : True
+    Bipartite                      : True
+    Average degree (min, max)      : 1.60 (1, 2)
+    Number of connected components : 1
+    Average Shortest Path Length   : 2.0
+
+    >>> G.name = "Path Graph of 5 nodes"
+    >>> nx.describe(G)
+    Name of Graph                  : Path Graph of 5 nodes
+    Number of nodes                : 5
+    Number of edges                : 4
+    Directed                       : False
+    Multigraph                     : False
+    Tree                           : True
+    Bipartite                      : True
+    Average degree (min, max)      : 1.60 (1, 2)
+    Number of connected components : 1
+
+    """
+    info_dict = _create_describe_info_dict(G)
+
+    if describe_hook is not None:
+        additional_info = describe_hook(G)
+        info_dict.update(additional_info)
+
+    max_key_len = max(len(k) for k in info_dict)
+    for key, val in info_dict.items():
+        print(f"{key:<{max_key_len}} : {val}")
+
+
+def _create_describe_info_dict(G):
+    info = {}
+    if G.name != "":
+        info["Name of Graph"] = G.name
+    info.update(
+        {
+            "Number of nodes": len(G),
+            "Number of edges": G.number_of_edges(),
+            "Directed": G.is_directed(),
+            "Multigraph": G.is_multigraph(),
+            "Tree": nx.is_tree(G),
+            "Bipartite": nx.is_bipartite(G),
+        }
+    )
+    if len(G) == 0:
+        return info
+
+    degree_values = dict(nx.degree(G)).values()
+    avg_degree = sum(degree_values) / len(G)
+    max_degree, min_degree = max(degree_values), min(degree_values)
+    info["Average degree (min, max)"] = f"{avg_degree:.2f} ({min_degree}, {max_degree})"
+
+    if G.is_directed():
+        info["Number of strongly connected components"] = (
+            nx.number_strongly_connected_components(G)
+        )
+        info["Number of weakly connected components"] = (
+            nx.number_weakly_connected_components(G)
+        )
+    else:
+        info["Number of connected components"] = nx.number_connected_components(G)
+    return info
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/graph.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/graph.py
new file mode 100644
index 0000000000000000000000000000000000000000..0eb184f4c5bfdd2a49890a480c2be08b4c0190d4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/graph.py
@@ -0,0 +1,2082 @@
+"""Base class for undirected graphs.
+
+The Graph class allows any hashable object as a node
+and can associate key/value attribute pairs with each undirected edge.
+
+Self-loops are allowed but multiple edges are not (see MultiGraph).
+
+For directed graphs see DiGraph and MultiDiGraph.
+"""
+
+from copy import deepcopy
+from functools import cached_property
+
+import networkx as nx
+from networkx import convert
+from networkx.classes.coreviews import AdjacencyView
+from networkx.classes.reportviews import DegreeView, EdgeView, NodeView
+from networkx.exception import NetworkXError
+
+__all__ = ["Graph"]
+
+
+class _CachedPropertyResetterAdj:
+    """Data Descriptor class for _adj that resets ``adj`` cached_property when needed
+
+    This assumes that the ``cached_property`` ``G.adj`` should be reset whenever
+    ``G._adj`` is set to a new value.
+
+    This object sits on a class and ensures that any instance of that
+    class clears its cached property "adj" whenever the underlying
+    instance attribute "_adj" is set to a new object. It only affects
+    the set process of the obj._adj attribute. All get/del operations
+    act as they normally would.
+
+    For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
+    """
+
+    def __set__(self, obj, value):
+        od = obj.__dict__
+        od["_adj"] = value
+        # reset cached properties
+        props = ["adj", "edges", "degree"]
+        for prop in props:
+            if prop in od:
+                del od[prop]
+
+
+class _CachedPropertyResetterNode:
+    """Data Descriptor class for _node that resets ``nodes`` cached_property when needed
+
+    This assumes that the ``cached_property`` ``G.node`` should be reset whenever
+    ``G._node`` is set to a new value.
+
+    This object sits on a class and ensures that any instance of that
+    class clears its cached property "nodes" whenever the underlying
+    instance attribute "_node" is set to a new object. It only affects
+    the set process of the obj._adj attribute. All get/del operations
+    act as they normally would.
+
+    For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
+    """
+
+    def __set__(self, obj, value):
+        od = obj.__dict__
+        od["_node"] = value
+        # reset cached properties
+        if "nodes" in od:
+            del od["nodes"]
+
+
+class Graph:
+    """
+    Base class for undirected graphs.
+
+    A Graph stores nodes and edges with optional data, or attributes.
+
+    Graphs hold undirected edges.  Self loops are allowed but multiple
+    (parallel) edges are not.
+
+    Nodes can be arbitrary (hashable) Python objects with optional
+    key/value attributes, except that `None` is not allowed as a node.
+
+    Edges are represented as links between nodes with optional
+    key/value attributes.
+
+    Parameters
+    ----------
+    incoming_graph_data : input graph (optional, default: None)
+        Data to initialize graph. If None (default) an empty
+        graph is created.  The data can be any format that is supported
+        by the to_networkx_graph() function, currently including edge list,
+        dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy
+        sparse matrix, or PyGraphviz graph.
+
+    attr : keyword arguments, optional (default= no attributes)
+        Attributes to add to graph as key=value pairs.
+
+    See Also
+    --------
+    DiGraph
+    MultiGraph
+    MultiDiGraph
+
+    Examples
+    --------
+    Create an empty graph structure (a "null graph") with no nodes and
+    no edges.
+
+    >>> G = nx.Graph()
+
+    G can be grown in several ways.
+
+    **Nodes:**
+
+    Add one node at a time:
+
+    >>> G.add_node(1)
+
+    Add the nodes from any container (a list, dict, set or
+    even the lines from a file or the nodes from another graph).
+
+    >>> G.add_nodes_from([2, 3])
+    >>> G.add_nodes_from(range(100, 110))
+    >>> H = nx.path_graph(10)
+    >>> G.add_nodes_from(H)
+
+    In addition to strings and integers any hashable Python object
+    (except None) can represent a node, e.g. a customized node object,
+    or even another Graph.
+
+    >>> G.add_node(H)
+
+    **Edges:**
+
+    G can also be grown by adding edges.
+
+    Add one edge,
+
+    >>> G.add_edge(1, 2)
+
+    a list of edges,
+
+    >>> G.add_edges_from([(1, 2), (1, 3)])
+
+    or a collection of edges,
+
+    >>> G.add_edges_from(H.edges)
+
+    If some edges connect nodes not yet in the graph, the nodes
+    are added automatically.  There are no errors when adding
+    nodes or edges that already exist.
+
+    **Attributes:**
+
+    Each graph, node, and edge can hold key/value attribute pairs
+    in an associated attribute dictionary (the keys must be hashable).
+    By default these are empty, but can be added or changed using
+    add_edge, add_node or direct manipulation of the attribute
+    dictionaries named graph, node and edge respectively.
+
+    >>> G = nx.Graph(day="Friday")
+    >>> G.graph
+    {'day': 'Friday'}
+
+    Add node attributes using add_node(), add_nodes_from() or G.nodes
+
+    >>> G.add_node(1, time="5pm")
+    >>> G.add_nodes_from([3], time="2pm")
+    >>> G.nodes[1]
+    {'time': '5pm'}
+    >>> G.nodes[1]["room"] = 714  # node must exist already to use G.nodes
+    >>> del G.nodes[1]["room"]  # remove attribute
+    >>> list(G.nodes(data=True))
+    [(1, {'time': '5pm'}), (3, {'time': '2pm'})]
+
+    Add edge attributes using add_edge(), add_edges_from(), subscript
+    notation, or G.edges.
+
+    >>> G.add_edge(1, 2, weight=4.7)
+    >>> G.add_edges_from([(3, 4), (4, 5)], color="red")
+    >>> G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
+    >>> G[1][2]["weight"] = 4.7
+    >>> G.edges[1, 2]["weight"] = 4
+
+    Warning: we protect the graph data structure by making `G.edges` a
+    read-only dict-like structure. However, you can assign to attributes
+    in e.g. `G.edges[1, 2]`. Thus, use 2 sets of brackets to add/change
+    data attributes: `G.edges[1, 2]['weight'] = 4`
+    (For multigraphs: `MG.edges[u, v, key][name] = value`).
+
+    **Shortcuts:**
+
+    Many common graph features allow python syntax to speed reporting.
+
+    >>> 1 in G  # check if node in graph
+    True
+    >>> [n for n in G if n < 3]  # iterate through nodes
+    [1, 2]
+    >>> len(G)  # number of nodes in graph
+    5
+
+    Often the best way to traverse all edges of a graph is via the neighbors.
+    The neighbors are reported as an adjacency-dict `G.adj` or `G.adjacency()`
+
+    >>> for n, nbrsdict in G.adjacency():
+    ...     for nbr, eattr in nbrsdict.items():
+    ...         if "weight" in eattr:
+    ...             # Do something useful with the edges
+    ...             pass
+
+    But the edges() method is often more convenient:
+
+    >>> for u, v, weight in G.edges.data("weight"):
+    ...     if weight is not None:
+    ...         # Do something useful with the edges
+    ...         pass
+
+    **Reporting:**
+
+    Simple graph information is obtained using object-attributes and methods.
+    Reporting typically provides views instead of containers to reduce memory
+    usage. The views update as the graph is updated similarly to dict-views.
+    The objects `nodes`, `edges` and `adj` provide access to data attributes
+    via lookup (e.g. `nodes[n]`, `edges[u, v]`, `adj[u][v]`) and iteration
+    (e.g. `nodes.items()`, `nodes.data('color')`,
+    `nodes.data('color', default='blue')` and similarly for `edges`)
+    Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
+
+    For details on these and other miscellaneous methods, see below.
+
+    **Subclasses (Advanced):**
+
+    The Graph class uses a dict-of-dict-of-dict data structure.
+    The outer dict (node_dict) holds adjacency information keyed by node.
+    The next dict (adjlist_dict) represents the adjacency information and holds
+    edge data keyed by neighbor.  The inner dict (edge_attr_dict) represents
+    the edge data and holds edge attribute values keyed by attribute names.
+
+    Each of these three dicts can be replaced in a subclass by a user defined
+    dict-like object. In general, the dict-like features should be
+    maintained but extra features can be added. To replace one of the
+    dicts create a new graph class by changing the class(!) variable
+    holding the factory for that dict-like structure.
+
+    node_dict_factory : function, (default: dict)
+        Factory function to be used to create the dict containing node
+        attributes, keyed by node id.
+        It should require no arguments and return a dict-like object
+
+    node_attr_dict_factory: function, (default: dict)
+        Factory function to be used to create the node attribute
+        dict which holds attribute values keyed by attribute name.
+        It should require no arguments and return a dict-like object
+
+    adjlist_outer_dict_factory : function, (default: dict)
+        Factory function to be used to create the outer-most dict
+        in the data structure that holds adjacency info keyed by node.
+        It should require no arguments and return a dict-like object.
+
+    adjlist_inner_dict_factory : function, (default: dict)
+        Factory function to be used to create the adjacency list
+        dict which holds edge data keyed by neighbor.
+        It should require no arguments and return a dict-like object
+
+    edge_attr_dict_factory : function, (default: dict)
+        Factory function to be used to create the edge attribute
+        dict which holds attribute values keyed by attribute name.
+        It should require no arguments and return a dict-like object.
+
+    graph_attr_dict_factory : function, (default: dict)
+        Factory function to be used to create the graph attribute
+        dict which holds attribute values keyed by attribute name.
+        It should require no arguments and return a dict-like object.
+
+    Typically, if your extension doesn't impact the data structure all
+    methods will inherit without issue except: `to_directed/to_undirected`.
+    By default these methods create a DiGraph/Graph class and you probably
+    want them to create your extension of a DiGraph/Graph. To facilitate
+    this we define two class variables that you can set in your subclass.
+
+    to_directed_class : callable, (default: DiGraph or MultiDiGraph)
+        Class to create a new graph structure in the `to_directed` method.
+        If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
+
+    to_undirected_class : callable, (default: Graph or MultiGraph)
+        Class to create a new graph structure in the `to_undirected` method.
+        If `None`, a NetworkX class (Graph or MultiGraph) is used.
+
+    **Subclassing Example**
+
+    Create a low memory graph class that effectively disallows edge
+    attributes by using a single attribute dict for all edges.
+    This reduces the memory used, but you lose edge attributes.
+
+    >>> class ThinGraph(nx.Graph):
+    ...     all_edge_dict = {"weight": 1}
+    ...
+    ...     def single_edge_dict(self):
+    ...         return self.all_edge_dict
+    ...
+    ...     edge_attr_dict_factory = single_edge_dict
+    >>> G = ThinGraph()
+    >>> G.add_edge(2, 1)
+    >>> G[2][1]
+    {'weight': 1}
+    >>> G.add_edge(2, 2)
+    >>> G[2][1] is G[2][2]
+    True
+    """
+
+    __networkx_backend__ = "networkx"
+
+    _adj = _CachedPropertyResetterAdj()
+    _node = _CachedPropertyResetterNode()
+
+    node_dict_factory = dict
+    node_attr_dict_factory = dict
+    adjlist_outer_dict_factory = dict
+    adjlist_inner_dict_factory = dict
+    edge_attr_dict_factory = dict
+    graph_attr_dict_factory = dict
+
+    def to_directed_class(self):
+        """Returns the class to use for empty directed copies.
+
+        If you subclass the base classes, use this to designate
+        what directed class to use for `to_directed()` copies.
+        """
+        return nx.DiGraph
+
+    def to_undirected_class(self):
+        """Returns the class to use for empty undirected copies.
+
+        If you subclass the base classes, use this to designate
+        what directed class to use for `to_directed()` copies.
+        """
+        return Graph
+
+    # This __new__ method just does what Python itself does automatically.
+    # We include it here as part of the dispatchable/backend interface.
+    # If your goal is to understand how the graph classes work, you can ignore
+    # this method, even when subclassing the base classes. If you are subclassing
+    # in order to provide a backend that allows class instantiation, this method
+    # can be overridden to return your own backend graph class.
+    @nx._dispatchable(name="graph__new__", graphs=None, returns_graph=True)
+    def __new__(cls, *args, **kwargs):
+        return object.__new__(cls)
+
+    def __init__(self, incoming_graph_data=None, **attr):
+        """Initialize a graph with edges, name, or graph attributes.
+
+        Parameters
+        ----------
+        incoming_graph_data : input graph (optional, default: None)
+            Data to initialize graph. If None (default) an empty
+            graph is created.  The data can be an edge list, or any
+            NetworkX graph object.  If the corresponding optional Python
+            packages are installed the data can also be a 2D NumPy array, a
+            SciPy sparse array, or a PyGraphviz graph.
+
+        attr : keyword arguments, optional (default= no attributes)
+            Attributes to add to graph as key=value pairs.
+
+        See Also
+        --------
+        convert
+
+        Examples
+        --------
+        >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G = nx.Graph(name="my graph")
+        >>> e = [(1, 2), (2, 3), (3, 4)]  # list of edges
+        >>> G = nx.Graph(e)
+
+        Arbitrary graph attribute pairs (key=value) may be assigned
+
+        >>> G = nx.Graph(e, day="Friday")
+        >>> G.graph
+        {'day': 'Friday'}
+
+        """
+        self.graph = self.graph_attr_dict_factory()  # dictionary for graph attributes
+        self._node = self.node_dict_factory()  # empty node attribute dict
+        self._adj = self.adjlist_outer_dict_factory()  # empty adjacency dict
+        self.__networkx_cache__ = {}
+        # attempt to load graph with data
+        if incoming_graph_data is not None:
+            convert.to_networkx_graph(incoming_graph_data, create_using=self)
+        # load graph attributes (must be after convert)
+        attr.pop("backend", None)  # Ignore explicit `backend="networkx"`
+        self.graph.update(attr)
+
+    @cached_property
+    def adj(self):
+        """Graph adjacency object holding the neighbors of each node.
+
+        This object is a read-only dict-like structure with node keys
+        and neighbor-dict values.  The neighbor-dict is keyed by neighbor
+        to the edge-data-dict.  So `G.adj[3][2]['color'] = 'blue'` sets
+        the color of the edge `(3, 2)` to `"blue"`.
+
+        Iterating over G.adj behaves like a dict. Useful idioms include
+        `for nbr, datadict in G.adj[n].items():`.
+
+        The neighbor information is also provided by subscripting the graph.
+        So `for nbr, foovalue in G[node].data('foo', default=1):` works.
+
+        For directed graphs, `G.adj` holds outgoing (successor) info.
+        """
+        return AdjacencyView(self._adj)
+
+    @property
+    def name(self):
+        """String identifier of the graph.
+
+        This graph attribute appears in the attribute dict G.graph
+        keyed by the string `"name"`. as well as an attribute (technically
+        a property) `G.name`. This is entirely user controlled.
+        """
+        return self.graph.get("name", "")
+
+    @name.setter
+    def name(self, s):
+        self.graph["name"] = s
+        nx._clear_cache(self)
+
+    def __str__(self):
+        """Returns a short summary of the graph.
+
+        Returns
+        -------
+        info : string
+            Graph information including the graph name (if any), graph type, and the
+            number of nodes and edges.
+
+        Examples
+        --------
+        >>> G = nx.Graph(name="foo")
+        >>> str(G)
+        "Graph named 'foo' with 0 nodes and 0 edges"
+
+        >>> G = nx.path_graph(3)
+        >>> str(G)
+        'Graph with 3 nodes and 2 edges'
+
+        """
+        return "".join(
+            [
+                type(self).__name__,
+                f" named {self.name!r}" if self.name else "",
+                f" with {self.number_of_nodes()} nodes and {self.number_of_edges()} edges",
+            ]
+        )
+
+    def __iter__(self):
+        """Iterate over the nodes. Use: 'for n in G'.
+
+        Returns
+        -------
+        niter : iterator
+            An iterator over all nodes in the graph.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> [n for n in G]
+        [0, 1, 2, 3]
+        >>> list(G)
+        [0, 1, 2, 3]
+        """
+        return iter(self._node)
+
+    def __contains__(self, n):
+        """Returns True if n is a node, False otherwise. Use: 'n in G'.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> 1 in G
+        True
+        """
+        try:
+            return n in self._node
+        except TypeError:
+            return False
+
+    def __len__(self):
+        """Returns the number of nodes in the graph. Use: 'len(G)'.
+
+        Returns
+        -------
+        nnodes : int
+            The number of nodes in the graph.
+
+        See Also
+        --------
+        number_of_nodes: identical method
+        order: identical method
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> len(G)
+        4
+
+        """
+        return len(self._node)
+
+    def __getitem__(self, n):
+        """Returns a dict of neighbors of node n.  Use: 'G[n]'.
+
+        Parameters
+        ----------
+        n : node
+           A node in the graph.
+
+        Returns
+        -------
+        adj_dict : dictionary
+           The adjacency dictionary for nodes connected to n.
+
+        Notes
+        -----
+        G[n] is the same as G.adj[n] and similar to G.neighbors(n)
+        (which is an iterator over G.adj[n])
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G[0]
+        AtlasView({1: {}})
+        """
+        return self.adj[n]
+
+    def add_node(self, node_for_adding, **attr):
+        """Add a single node `node_for_adding` and update node attributes.
+
+        Parameters
+        ----------
+        node_for_adding : node
+            A node can be any hashable Python object except None.
+        attr : keyword arguments, optional
+            Set or change node attributes using key=value.
+
+        See Also
+        --------
+        add_nodes_from
+
+        Examples
+        --------
+        >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.add_node(1)
+        >>> G.add_node("Hello")
+        >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
+        >>> G.add_node(K3)
+        >>> G.number_of_nodes()
+        3
+
+        Use keywords set/change node attributes:
+
+        >>> G.add_node(1, size=10)
+        >>> G.add_node(3, weight=0.4, UTM=("13S", 382871, 3972649))
+
+        Notes
+        -----
+        A hashable object is one that can be used as a key in a Python
+        dictionary. This includes strings, numbers, tuples of strings
+        and numbers, etc.
+
+        On many platforms hashable items also include mutables such as
+        NetworkX Graphs, though one should be careful that the hash
+        doesn't change on mutables.
+        """
+        if node_for_adding not in self._node:
+            if node_for_adding is None:
+                raise ValueError("None cannot be a node")
+            self._adj[node_for_adding] = self.adjlist_inner_dict_factory()
+            attr_dict = self._node[node_for_adding] = self.node_attr_dict_factory()
+            attr_dict.update(attr)
+        else:  # update attr even if node already exists
+            self._node[node_for_adding].update(attr)
+        nx._clear_cache(self)
+
+    def add_nodes_from(self, nodes_for_adding, **attr):
+        """Add multiple nodes.
+
+        Parameters
+        ----------
+        nodes_for_adding : iterable container
+            A container of nodes (list, dict, set, etc.).
+            OR
+            A container of (node, attribute dict) tuples.
+            Node attributes are updated using the attribute dict.
+        attr : keyword arguments, optional (default= no attributes)
+            Update attributes for all nodes in nodes.
+            Node attributes specified in nodes as a tuple take
+            precedence over attributes specified via keyword arguments.
+
+        See Also
+        --------
+        add_node
+
+        Notes
+        -----
+        When adding nodes from an iterator over the graph you are changing,
+        a `RuntimeError` can be raised with message:
+        `RuntimeError: dictionary changed size during iteration`. This
+        happens when the graph's underlying dictionary is modified during
+        iteration. To avoid this error, evaluate the iterator into a separate
+        object, e.g. by using `list(iterator_of_nodes)`, and pass this
+        object to `G.add_nodes_from`.
+
+        Examples
+        --------
+        >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.add_nodes_from("Hello")
+        >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
+        >>> G.add_nodes_from(K3)
+        >>> sorted(G.nodes(), key=str)
+        [0, 1, 2, 'H', 'e', 'l', 'o']
+
+        Use keywords to update specific node attributes for every node.
+
+        >>> G.add_nodes_from([1, 2], size=10)
+        >>> G.add_nodes_from([3, 4], weight=0.4)
+
+        Use (node, attrdict) tuples to update attributes for specific nodes.
+
+        >>> G.add_nodes_from([(1, dict(size=11)), (2, {"color": "blue"})])
+        >>> G.nodes[1]["size"]
+        11
+        >>> H = nx.Graph()
+        >>> H.add_nodes_from(G.nodes(data=True))
+        >>> H.nodes[1]["size"]
+        11
+
+        Evaluate an iterator over a graph if using it to modify the same graph
+
+        >>> G = nx.Graph([(0, 1), (1, 2), (3, 4)])
+        >>> # wrong way - will raise RuntimeError
+        >>> # G.add_nodes_from(n + 1 for n in G.nodes)
+        >>> # correct way
+        >>> G.add_nodes_from(list(n + 1 for n in G.nodes))
+        """
+        for n in nodes_for_adding:
+            try:
+                newnode = n not in self._node
+                newdict = attr
+            except TypeError:
+                n, ndict = n
+                newnode = n not in self._node
+                newdict = attr.copy()
+                newdict.update(ndict)
+            if newnode:
+                if n is None:
+                    raise ValueError("None cannot be a node")
+                self._adj[n] = self.adjlist_inner_dict_factory()
+                self._node[n] = self.node_attr_dict_factory()
+            self._node[n].update(newdict)
+        nx._clear_cache(self)
+
+    def remove_node(self, n):
+        """Remove node n.
+
+        Removes the node n and all adjacent edges.
+        Attempting to remove a nonexistent node will raise an exception.
+
+        Parameters
+        ----------
+        n : node
+           A node in the graph
+
+        Raises
+        ------
+        NetworkXError
+           If n is not in the graph.
+
+        See Also
+        --------
+        remove_nodes_from
+
+        Examples
+        --------
+        >>> G = nx.path_graph(3)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> list(G.edges)
+        [(0, 1), (1, 2)]
+        >>> G.remove_node(1)
+        >>> list(G.edges)
+        []
+
+        """
+        adj = self._adj
+        try:
+            nbrs = list(adj[n])  # list handles self-loops (allows mutation)
+            del self._node[n]
+        except KeyError as err:  # NetworkXError if n not in self
+            raise NetworkXError(f"The node {n} is not in the graph.") from err
+        for u in nbrs:
+            del adj[u][n]  # remove all edges n-u in graph
+        del adj[n]  # now remove node
+        nx._clear_cache(self)
+
+    def remove_nodes_from(self, nodes):
+        """Remove multiple nodes.
+
+        Parameters
+        ----------
+        nodes : iterable container
+            A container of nodes (list, dict, set, etc.).  If a node
+            in the container is not in the graph it is silently
+            ignored.
+
+        See Also
+        --------
+        remove_node
+
+        Notes
+        -----
+        When removing nodes from an iterator over the graph you are changing,
+        a `RuntimeError` will be raised with message:
+        `RuntimeError: dictionary changed size during iteration`. This
+        happens when the graph's underlying dictionary is modified during
+        iteration. To avoid this error, evaluate the iterator into a separate
+        object, e.g. by using `list(iterator_of_nodes)`, and pass this
+        object to `G.remove_nodes_from`.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(3)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> e = list(G.nodes)
+        >>> e
+        [0, 1, 2]
+        >>> G.remove_nodes_from(e)
+        >>> list(G.nodes)
+        []
+
+        Evaluate an iterator over a graph if using it to modify the same graph
+
+        >>> G = nx.Graph([(0, 1), (1, 2), (3, 4)])
+        >>> # this command will fail, as the graph's dict is modified during iteration
+        >>> # G.remove_nodes_from(n for n in G.nodes if n < 2)
+        >>> # this command will work, since the dictionary underlying graph is not modified
+        >>> G.remove_nodes_from(list(n for n in G.nodes if n < 2))
+        """
+        adj = self._adj
+        for n in nodes:
+            try:
+                del self._node[n]
+                for u in list(adj[n]):  # list handles self-loops
+                    del adj[u][n]  # (allows mutation of dict in loop)
+                del adj[n]
+            except KeyError:
+                pass
+        nx._clear_cache(self)
+
+    @cached_property
+    def nodes(self):
+        """A NodeView of the Graph as G.nodes or G.nodes().
+
+        Can be used as `G.nodes` for data lookup and for set-like operations.
+        Can also be used as `G.nodes(data='color', default=None)` to return a
+        NodeDataView which reports specific node data but no set operations.
+        It presents a dict-like interface as well with `G.nodes.items()`
+        iterating over `(node, nodedata)` 2-tuples and `G.nodes[3]['foo']`
+        providing the value of the `foo` attribute for node `3`. In addition,
+        a view `G.nodes.data('foo')` provides a dict-like interface to the
+        `foo` attribute of each node. `G.nodes.data('foo', default=1)`
+        provides a default for nodes that do not have attribute `foo`.
+
+        Parameters
+        ----------
+        data : string or bool, optional (default=False)
+            The node attribute returned in 2-tuple (n, ddict[data]).
+            If True, return entire node attribute dict as (n, ddict).
+            If False, return just the nodes n.
+
+        default : value, optional (default=None)
+            Value used for nodes that don't have the requested attribute.
+            Only relevant if data is not True or False.
+
+        Returns
+        -------
+        NodeView
+            Allows set-like operations over the nodes as well as node
+            attribute dict lookup and calling to get a NodeDataView.
+            A NodeDataView iterates over `(n, data)` and has no set operations.
+            A NodeView iterates over `n` and includes set operations.
+
+            When called, if data is False, an iterator over nodes.
+            Otherwise an iterator of 2-tuples (node, attribute value)
+            where the attribute is specified in `data`.
+            If data is True then the attribute becomes the
+            entire data dictionary.
+
+        Notes
+        -----
+        If your node data is not needed, it is simpler and equivalent
+        to use the expression ``for n in G``, or ``list(G)``.
+
+        Examples
+        --------
+        There are two simple ways of getting a list of all nodes in the graph:
+
+        >>> G = nx.path_graph(3)
+        >>> list(G.nodes)
+        [0, 1, 2]
+        >>> list(G)
+        [0, 1, 2]
+
+        To get the node data along with the nodes:
+
+        >>> G.add_node(1, time="5pm")
+        >>> G.nodes[0]["foo"] = "bar"
+        >>> list(G.nodes(data=True))
+        [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
+        >>> list(G.nodes.data())
+        [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
+
+        >>> list(G.nodes(data="foo"))
+        [(0, 'bar'), (1, None), (2, None)]
+        >>> list(G.nodes.data("foo"))
+        [(0, 'bar'), (1, None), (2, None)]
+
+        >>> list(G.nodes(data="time"))
+        [(0, None), (1, '5pm'), (2, None)]
+        >>> list(G.nodes.data("time"))
+        [(0, None), (1, '5pm'), (2, None)]
+
+        >>> list(G.nodes(data="time", default="Not Available"))
+        [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
+        >>> list(G.nodes.data("time", default="Not Available"))
+        [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
+
+        If some of your nodes have an attribute and the rest are assumed
+        to have a default attribute value you can create a dictionary
+        from node/attribute pairs using the `default` keyword argument
+        to guarantee the value is never None::
+
+            >>> G = nx.Graph()
+            >>> G.add_node(0)
+            >>> G.add_node(1, weight=2)
+            >>> G.add_node(2, weight=3)
+            >>> dict(G.nodes(data="weight", default=1))
+            {0: 1, 1: 2, 2: 3}
+
+        """
+        return NodeView(self)
+
+    def number_of_nodes(self):
+        """Returns the number of nodes in the graph.
+
+        Returns
+        -------
+        nnodes : int
+            The number of nodes in the graph.
+
+        See Also
+        --------
+        order: identical method
+        __len__: identical method
+
+        Examples
+        --------
+        >>> G = nx.path_graph(3)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.number_of_nodes()
+        3
+        """
+        return len(self._node)
+
+    def order(self):
+        """Returns the number of nodes in the graph.
+
+        Returns
+        -------
+        nnodes : int
+            The number of nodes in the graph.
+
+        See Also
+        --------
+        number_of_nodes: identical method
+        __len__: identical method
+
+        Examples
+        --------
+        >>> G = nx.path_graph(3)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.order()
+        3
+        """
+        return len(self._node)
+
+    def has_node(self, n):
+        """Returns True if the graph contains the node n.
+
+        Identical to `n in G`
+
+        Parameters
+        ----------
+        n : node
+
+        Examples
+        --------
+        >>> G = nx.path_graph(3)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.has_node(0)
+        True
+
+        It is more readable and simpler to use
+
+        >>> 0 in G
+        True
+
+        """
+        try:
+            return n in self._node
+        except TypeError:
+            return False
+
+    def add_edge(self, u_of_edge, v_of_edge, **attr):
+        """Add an edge between u and v.
+
+        The nodes u and v will be automatically added if they are
+        not already in the graph.
+
+        Edge attributes can be specified with keywords or by directly
+        accessing the edge's attribute dictionary. See examples below.
+
+        Parameters
+        ----------
+        u_of_edge, v_of_edge : nodes
+            Nodes can be, for example, strings or numbers.
+            Nodes must be hashable (and not None) Python objects.
+        attr : keyword arguments, optional
+            Edge data (or labels or objects) can be assigned using
+            keyword arguments.
+
+        See Also
+        --------
+        add_edges_from : add a collection of edges
+
+        Notes
+        -----
+        Adding an edge that already exists updates the edge data.
+
+        Many NetworkX algorithms designed for weighted graphs use
+        an edge attribute (by default `weight`) to hold a numerical value.
+
+        Examples
+        --------
+        The following all add the edge e=(1, 2) to graph G:
+
+        >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> e = (1, 2)
+        >>> G.add_edge(1, 2)  # explicit two-node form
+        >>> G.add_edge(*e)  # single edge as tuple of two nodes
+        >>> G.add_edges_from([(1, 2)])  # add edges from iterable container
+
+        Associate data to edges using keywords:
+
+        >>> G.add_edge(1, 2, weight=3)
+        >>> G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
+
+        For non-string attribute keys, use subscript notation.
+
+        >>> G.add_edge(1, 2)
+        >>> G[1][2].update({0: 5})
+        >>> G.edges[1, 2].update({0: 5})
+        """
+        u, v = u_of_edge, v_of_edge
+        # add nodes
+        if u not in self._node:
+            if u is None:
+                raise ValueError("None cannot be a node")
+            self._adj[u] = self.adjlist_inner_dict_factory()
+            self._node[u] = self.node_attr_dict_factory()
+        if v not in self._node:
+            if v is None:
+                raise ValueError("None cannot be a node")
+            self._adj[v] = self.adjlist_inner_dict_factory()
+            self._node[v] = self.node_attr_dict_factory()
+        # add the edge
+        datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
+        datadict.update(attr)
+        self._adj[u][v] = datadict
+        self._adj[v][u] = datadict
+        nx._clear_cache(self)
+
+    def add_edges_from(self, ebunch_to_add, **attr):
+        """Add all the edges in ebunch_to_add.
+
+        Parameters
+        ----------
+        ebunch_to_add : container of edges
+            Each edge given in the container will be added to the
+            graph. The edges must be given as 2-tuples (u, v) or
+            3-tuples (u, v, d) where d is a dictionary containing edge data.
+        attr : keyword arguments, optional
+            Edge data (or labels or objects) can be assigned using
+            keyword arguments.
+
+        See Also
+        --------
+        add_edge : add a single edge
+        add_weighted_edges_from : convenient way to add weighted edges
+
+        Notes
+        -----
+        Adding the same edge twice has no effect but any edge data
+        will be updated when each duplicate edge is added.
+
+        Edge attributes specified in an ebunch take precedence over
+        attributes specified via keyword arguments.
+
+        When adding edges from an iterator over the graph you are changing,
+        a `RuntimeError` can be raised with message:
+        `RuntimeError: dictionary changed size during iteration`. This
+        happens when the graph's underlying dictionary is modified during
+        iteration. To avoid this error, evaluate the iterator into a separate
+        object, e.g. by using `list(iterator_of_edges)`, and pass this
+        object to `G.add_edges_from`.
+
+        Examples
+        --------
+        >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.add_edges_from([(0, 1), (1, 2)])  # using a list of edge tuples
+        >>> e = zip(range(0, 3), range(1, 4))
+        >>> G.add_edges_from(e)  # Add the path graph 0-1-2-3
+
+        Associate data to edges
+
+        >>> G.add_edges_from([(1, 2), (2, 3)], weight=3)
+        >>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
+
+        Evaluate an iterator over a graph if using it to modify the same graph
+
+        >>> G = nx.Graph([(1, 2), (2, 3), (3, 4)])
+        >>> # Grow graph by one new node, adding edges to all existing nodes.
+        >>> # wrong way - will raise RuntimeError
+        >>> # G.add_edges_from(((5, n) for n in G.nodes))
+        >>> # correct way - note that there will be no self-edge for node 5
+        >>> G.add_edges_from(list((5, n) for n in G.nodes))
+        """
+        for e in ebunch_to_add:
+            ne = len(e)
+            if ne == 3:
+                u, v, dd = e
+            elif ne == 2:
+                u, v = e
+                dd = {}  # doesn't need edge_attr_dict_factory
+            else:
+                raise NetworkXError(f"Edge tuple {e} must be a 2-tuple or 3-tuple.")
+            if u not in self._node:
+                if u is None:
+                    raise ValueError("None cannot be a node")
+                self._adj[u] = self.adjlist_inner_dict_factory()
+                self._node[u] = self.node_attr_dict_factory()
+            if v not in self._node:
+                if v is None:
+                    raise ValueError("None cannot be a node")
+                self._adj[v] = self.adjlist_inner_dict_factory()
+                self._node[v] = self.node_attr_dict_factory()
+            datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
+            datadict.update(attr)
+            datadict.update(dd)
+            self._adj[u][v] = datadict
+            self._adj[v][u] = datadict
+        nx._clear_cache(self)
+
+    def add_weighted_edges_from(self, ebunch_to_add, weight="weight", **attr):
+        """Add weighted edges in `ebunch_to_add` with specified weight attr
+
+        Parameters
+        ----------
+        ebunch_to_add : container of edges
+            Each edge given in the list or container will be added
+            to the graph. The edges must be given as 3-tuples (u, v, w)
+            where w is a number.
+        weight : string, optional (default= 'weight')
+            The attribute name for the edge weights to be added.
+        attr : keyword arguments, optional (default= no attributes)
+            Edge attributes to add/update for all edges.
+
+        See Also
+        --------
+        add_edge : add a single edge
+        add_edges_from : add multiple edges
+
+        Notes
+        -----
+        Adding the same edge twice for Graph/DiGraph simply updates
+        the edge data. For MultiGraph/MultiDiGraph, duplicate edges
+        are stored.
+
+        When adding edges from an iterator over the graph you are changing,
+        a `RuntimeError` can be raised with message:
+        `RuntimeError: dictionary changed size during iteration`. This
+        happens when the graph's underlying dictionary is modified during
+        iteration. To avoid this error, evaluate the iterator into a separate
+        object, e.g. by using `list(iterator_of_edges)`, and pass this
+        object to `G.add_weighted_edges_from`.
+
+        Examples
+        --------
+        >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.add_weighted_edges_from([(0, 1, 3.0), (1, 2, 7.5)])
+
+        Evaluate an iterator over edges before passing it
+
+        >>> G = nx.Graph([(1, 2), (2, 3), (3, 4)])
+        >>> weight = 0.1
+        >>> # Grow graph by one new node, adding edges to all existing nodes.
+        >>> # wrong way - will raise RuntimeError
+        >>> # G.add_weighted_edges_from(((5, n, weight) for n in G.nodes))
+        >>> # correct way - note that there will be no self-edge for node 5
+        >>> G.add_weighted_edges_from(list((5, n, weight) for n in G.nodes))
+        """
+        self.add_edges_from(((u, v, {weight: d}) for u, v, d in ebunch_to_add), **attr)
+        nx._clear_cache(self)
+
+    def remove_edge(self, u, v):
+        """Remove the edge between u and v.
+
+        Parameters
+        ----------
+        u, v : nodes
+            Remove the edge between nodes u and v.
+
+        Raises
+        ------
+        NetworkXError
+            If there is not an edge between u and v.
+
+        See Also
+        --------
+        remove_edges_from : remove a collection of edges
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, etc
+        >>> G.remove_edge(0, 1)
+        >>> e = (1, 2)
+        >>> G.remove_edge(*e)  # unpacks e from an edge tuple
+        >>> e = (2, 3, {"weight": 7})  # an edge with attribute data
+        >>> G.remove_edge(*e[:2])  # select first part of edge tuple
+        """
+        try:
+            del self._adj[u][v]
+            if u != v:  # self-loop needs only one entry removed
+                del self._adj[v][u]
+        except KeyError as err:
+            raise NetworkXError(f"The edge {u}-{v} is not in the graph") from err
+        nx._clear_cache(self)
+
+    def remove_edges_from(self, ebunch):
+        """Remove all edges specified in ebunch.
+
+        Parameters
+        ----------
+        ebunch: list or container of edge tuples
+            Each edge given in the list or container will be removed
+            from the graph. The edges can be:
+
+                - 2-tuples (u, v) edge between u and v.
+                - 3-tuples (u, v, k) where k is ignored.
+
+        See Also
+        --------
+        remove_edge : remove a single edge
+
+        Notes
+        -----
+        Will fail silently if an edge in ebunch is not in the graph.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> ebunch = [(1, 2), (2, 3)]
+        >>> G.remove_edges_from(ebunch)
+        """
+        adj = self._adj
+        for e in ebunch:
+            u, v = e[:2]  # ignore edge data if present
+            if u in adj and v in adj[u]:
+                del adj[u][v]
+                if u != v:  # self loop needs only one entry removed
+                    del adj[v][u]
+        nx._clear_cache(self)
+
+    def update(self, edges=None, nodes=None):
+        """Update the graph using nodes/edges/graphs as input.
+
+        Like dict.update, this method takes a graph as input, adding the
+        graph's nodes and edges to this graph. It can also take two inputs:
+        edges and nodes. Finally it can take either edges or nodes.
+        To specify only nodes the keyword `nodes` must be used.
+
+        The collections of edges and nodes are treated similarly to
+        the add_edges_from/add_nodes_from methods. When iterated, they
+        should yield 2-tuples (u, v) or 3-tuples (u, v, datadict).
+
+        Parameters
+        ----------
+        edges : Graph object, collection of edges, or None
+            The first parameter can be a graph or some edges. If it has
+            attributes `nodes` and `edges`, then it is taken to be a
+            Graph-like object and those attributes are used as collections
+            of nodes and edges to be added to the graph.
+            If the first parameter does not have those attributes, it is
+            treated as a collection of edges and added to the graph.
+            If the first argument is None, no edges are added.
+        nodes : collection of nodes, or None
+            The second parameter is treated as a collection of nodes
+            to be added to the graph unless it is None.
+            If `edges is None` and `nodes is None` an exception is raised.
+            If the first parameter is a Graph, then `nodes` is ignored.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(5)
+        >>> G.update(nx.complete_graph(range(4, 10)))
+        >>> from itertools import combinations
+        >>> edges = (
+        ...     (u, v, {"power": u * v})
+        ...     for u, v in combinations(range(10, 20), 2)
+        ...     if u * v < 225
+        ... )
+        >>> nodes = [1000]  # for singleton, use a container
+        >>> G.update(edges, nodes)
+
+        Notes
+        -----
+        It you want to update the graph using an adjacency structure
+        it is straightforward to obtain the edges/nodes from adjacency.
+        The following examples provide common cases, your adjacency may
+        be slightly different and require tweaks of these examples::
+
+        >>> # dict-of-set/list/tuple
+        >>> adj = {1: {2, 3}, 2: {1, 3}, 3: {1, 2}}
+        >>> e = [(u, v) for u, nbrs in adj.items() for v in nbrs]
+        >>> G.update(edges=e, nodes=adj)
+
+        >>> DG = nx.DiGraph()
+        >>> # dict-of-dict-of-attribute
+        >>> adj = {1: {2: 1.3, 3: 0.7}, 2: {1: 1.4}, 3: {1: 0.7}}
+        >>> e = [
+        ...     (u, v, {"weight": d})
+        ...     for u, nbrs in adj.items()
+        ...     for v, d in nbrs.items()
+        ... ]
+        >>> DG.update(edges=e, nodes=adj)
+
+        >>> # dict-of-dict-of-dict
+        >>> adj = {1: {2: {"weight": 1.3}, 3: {"color": 0.7, "weight": 1.2}}}
+        >>> e = [
+        ...     (u, v, {"weight": d})
+        ...     for u, nbrs in adj.items()
+        ...     for v, d in nbrs.items()
+        ... ]
+        >>> DG.update(edges=e, nodes=adj)
+
+        >>> # predecessor adjacency (dict-of-set)
+        >>> pred = {1: {2, 3}, 2: {3}, 3: {3}}
+        >>> e = [(v, u) for u, nbrs in pred.items() for v in nbrs]
+
+        >>> # MultiGraph dict-of-dict-of-dict-of-attribute
+        >>> MDG = nx.MultiDiGraph()
+        >>> adj = {
+        ...     1: {2: {0: {"weight": 1.3}, 1: {"weight": 1.2}}},
+        ...     3: {2: {0: {"weight": 0.7}}},
+        ... }
+        >>> e = [
+        ...     (u, v, ekey, d)
+        ...     for u, nbrs in adj.items()
+        ...     for v, keydict in nbrs.items()
+        ...     for ekey, d in keydict.items()
+        ... ]
+        >>> MDG.update(edges=e)
+
+        See Also
+        --------
+        add_edges_from: add multiple edges to a graph
+        add_nodes_from: add multiple nodes to a graph
+        """
+        if edges is not None:
+            if nodes is not None:
+                self.add_nodes_from(nodes)
+                self.add_edges_from(edges)
+            else:
+                # check if edges is a Graph object
+                try:
+                    graph_nodes = edges.nodes
+                    graph_edges = edges.edges
+                except AttributeError:
+                    # edge not Graph-like
+                    self.add_edges_from(edges)
+                else:  # edges is Graph-like
+                    self.add_nodes_from(graph_nodes.data())
+                    self.add_edges_from(graph_edges.data())
+                    self.graph.update(edges.graph)
+        elif nodes is not None:
+            self.add_nodes_from(nodes)
+        else:
+            raise NetworkXError("update needs nodes or edges input")
+
+    def has_edge(self, u, v):
+        """Returns True if the edge (u, v) is in the graph.
+
+        This is the same as `v in G[u]` without KeyError exceptions.
+
+        Parameters
+        ----------
+        u, v : nodes
+            Nodes can be, for example, strings or numbers.
+            Nodes must be hashable (and not None) Python objects.
+
+        Returns
+        -------
+        edge_ind : bool
+            True if edge is in the graph, False otherwise.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.has_edge(0, 1)  # using two nodes
+        True
+        >>> e = (0, 1)
+        >>> G.has_edge(*e)  #  e is a 2-tuple (u, v)
+        True
+        >>> e = (0, 1, {"weight": 7})
+        >>> G.has_edge(*e[:2])  # e is a 3-tuple (u, v, data_dictionary)
+        True
+
+        The following syntax are equivalent:
+
+        >>> G.has_edge(0, 1)
+        True
+        >>> 1 in G[0]  # though this gives KeyError if 0 not in G
+        True
+
+        """
+        try:
+            return v in self._adj[u]
+        except KeyError:
+            return False
+
+    def neighbors(self, n):
+        """Returns an iterator over all neighbors of node n.
+
+        This is identical to `iter(G[n])`
+
+        Parameters
+        ----------
+        n : node
+           A node in the graph
+
+        Returns
+        -------
+        neighbors : iterator
+            An iterator over all neighbors of node n
+
+        Raises
+        ------
+        NetworkXError
+            If the node n is not in the graph.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> [n for n in G.neighbors(0)]
+        [1]
+
+        Notes
+        -----
+        Alternate ways to access the neighbors are ``G.adj[n]`` or ``G[n]``:
+
+        >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.add_edge("a", "b", weight=7)
+        >>> G["a"]
+        AtlasView({'b': {'weight': 7}})
+        >>> G = nx.path_graph(4)
+        >>> [n for n in G[0]]
+        [1]
+        """
+        try:
+            return iter(self._adj[n])
+        except KeyError as err:
+            raise NetworkXError(f"The node {n} is not in the graph.") from err
+
+    @cached_property
+    def edges(self):
+        """An EdgeView of the Graph as G.edges or G.edges().
+
+        edges(self, nbunch=None, data=False, default=None)
+
+        The EdgeView provides set-like operations on the edge-tuples
+        as well as edge attribute lookup. When called, it also provides
+        an EdgeDataView object which allows control of access to edge
+        attributes (but does not provide set-like operations).
+        Hence, `G.edges[u, v]['color']` provides the value of the color
+        attribute for edge `(u, v)` while
+        `for (u, v, c) in G.edges.data('color', default='red'):`
+        iterates through all the edges yielding the color attribute
+        with default `'red'` if no color attribute exists.
+
+        Parameters
+        ----------
+        nbunch : single node, container, or all nodes (default= all nodes)
+            The view will only report edges from these nodes.
+        data : string or bool, optional (default=False)
+            The edge attribute returned in 3-tuple (u, v, ddict[data]).
+            If True, return edge attribute dict in 3-tuple (u, v, ddict).
+            If False, return 2-tuple (u, v).
+        default : value, optional (default=None)
+            Value used for edges that don't have the requested attribute.
+            Only relevant if data is not True or False.
+
+        Returns
+        -------
+        edges : EdgeView
+            A view of edge attributes, usually it iterates over (u, v)
+            or (u, v, d) tuples of edges, but can also be used for
+            attribute lookup as `edges[u, v]['foo']`.
+
+        Notes
+        -----
+        Nodes in nbunch that are not in the graph will be (quietly) ignored.
+        For directed graphs this returns the out-edges.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(3)  # or MultiGraph, etc
+        >>> G.add_edge(2, 3, weight=5)
+        >>> [e for e in G.edges]
+        [(0, 1), (1, 2), (2, 3)]
+        >>> G.edges.data()  # default data is {} (empty dict)
+        EdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})])
+        >>> G.edges.data("weight", default=1)
+        EdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)])
+        >>> G.edges([0, 3])  # only edges from these nodes
+        EdgeDataView([(0, 1), (3, 2)])
+        >>> G.edges(0)  # only edges from node 0
+        EdgeDataView([(0, 1)])
+        """
+        return EdgeView(self)
+
+    def get_edge_data(self, u, v, default=None):
+        """Returns the attribute dictionary associated with edge (u, v).
+
+        This is identical to `G[u][v]` except the default is returned
+        instead of an exception if the edge doesn't exist.
+
+        Parameters
+        ----------
+        u, v : nodes
+        default:  any Python object (default=None)
+            Value to return if the edge (u, v) is not found.
+
+        Returns
+        -------
+        edge_dict : dictionary
+            The edge attribute dictionary.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G[0][1]
+        {}
+
+        Warning: Assigning to `G[u][v]` is not permitted.
+        But it is safe to assign attributes `G[u][v]['foo']`
+
+        >>> G[0][1]["weight"] = 7
+        >>> G[0][1]["weight"]
+        7
+        >>> G[1][0]["weight"]
+        7
+
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.get_edge_data(0, 1)  # default edge data is {}
+        {}
+        >>> e = (0, 1)
+        >>> G.get_edge_data(*e)  # tuple form
+        {}
+        >>> G.get_edge_data("a", "b", default=0)  # edge not in graph, return 0
+        0
+        """
+        try:
+            return self._adj[u][v]
+        except KeyError:
+            return default
+
+    def adjacency(self):
+        """Returns an iterator over (node, adjacency dict) tuples for all nodes.
+
+        For directed graphs, only outgoing neighbors/adjacencies are included.
+
+        Returns
+        -------
+        adj_iter : iterator
+           An iterator over (node, adjacency dictionary) for all nodes in
+           the graph.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> [(n, nbrdict) for n, nbrdict in G.adjacency()]
+        [(0, {1: {}}), (1, {0: {}, 2: {}}), (2, {1: {}, 3: {}}), (3, {2: {}})]
+
+        """
+        return iter(self._adj.items())
+
+    @cached_property
+    def degree(self):
+        """A DegreeView for the Graph as G.degree or G.degree().
+
+        The node degree is the number of edges adjacent to the node.
+        The weighted node degree is the sum of the edge weights for
+        edges incident to that node.
+
+        This object provides an iterator for (node, degree) as well as
+        lookup for the degree for a single node.
+
+        Parameters
+        ----------
+        nbunch : single node, container, or all nodes (default= all nodes)
+            The view will only report edges incident to these nodes.
+
+        weight : string or None, optional (default=None)
+           The name of an edge attribute that holds the numerical value used
+           as a weight.  If None, then each edge has weight 1.
+           The degree is the sum of the edge weights adjacent to the node.
+
+        Returns
+        -------
+        DegreeView or int
+            If multiple nodes are requested (the default), returns a `DegreeView`
+            mapping nodes to their degree.
+            If a single node is requested, returns the degree of the node as an integer.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.degree[0]  # node 0 has degree 1
+        1
+        >>> list(G.degree([0, 1, 2]))
+        [(0, 1), (1, 2), (2, 2)]
+        """
+        return DegreeView(self)
+
+    def clear(self):
+        """Remove all nodes and edges from the graph.
+
+        This also removes the name, and all graph, node, and edge attributes.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.clear()
+        >>> list(G.nodes)
+        []
+        >>> list(G.edges)
+        []
+
+        """
+        self._adj.clear()
+        self._node.clear()
+        self.graph.clear()
+        nx._clear_cache(self)
+
+    def clear_edges(self):
+        """Remove all edges from the graph without altering nodes.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.clear_edges()
+        >>> list(G.nodes)
+        [0, 1, 2, 3]
+        >>> list(G.edges)
+        []
+        """
+        for nbr_dict in self._adj.values():
+            nbr_dict.clear()
+        nx._clear_cache(self)
+
+    def is_multigraph(self):
+        """Returns True if graph is a multigraph, False otherwise."""
+        return False
+
+    def is_directed(self):
+        """Returns True if graph is directed, False otherwise."""
+        return False
+
+    def copy(self, as_view=False):
+        """Returns a copy of the graph.
+
+        The copy method by default returns an independent shallow copy
+        of the graph and attributes. That is, if an attribute is a
+        container, that container is shared by the original an the copy.
+        Use Python's `copy.deepcopy` for new containers.
+
+        If `as_view` is True then a view is returned instead of a copy.
+
+        Notes
+        -----
+        All copies reproduce the graph structure, but data attributes
+        may be handled in different ways. There are four types of copies
+        of a graph that people might want.
+
+        Deepcopy -- A "deepcopy" copies the graph structure as well as
+        all data attributes and any objects they might contain.
+        The entire graph object is new so that changes in the copy
+        do not affect the original object. (see Python's copy.deepcopy)
+
+        Data Reference (Shallow) -- For a shallow copy the graph structure
+        is copied but the edge, node and graph attribute dicts are
+        references to those in the original graph. This saves
+        time and memory but could cause confusion if you change an attribute
+        in one graph and it changes the attribute in the other.
+        NetworkX does not provide this level of shallow copy.
+
+        Independent Shallow -- This copy creates new independent attribute
+        dicts and then does a shallow copy of the attributes. That is, any
+        attributes that are containers are shared between the new graph
+        and the original. This is exactly what `dict.copy()` provides.
+        You can obtain this style copy using:
+
+            >>> G = nx.path_graph(5)
+            >>> H = G.copy()
+            >>> H = G.copy(as_view=False)
+            >>> H = nx.Graph(G)
+            >>> H = G.__class__(G)
+
+        Fresh Data -- For fresh data, the graph structure is copied while
+        new empty data attribute dicts are created. The resulting graph
+        is independent of the original and it has no edge, node or graph
+        attributes. Fresh copies are not enabled. Instead use:
+
+            >>> H = G.__class__()
+            >>> H.add_nodes_from(G)
+            >>> H.add_edges_from(G.edges)
+
+        View -- Inspired by dict-views, graph-views act like read-only
+        versions of the original graph, providing a copy of the original
+        structure without requiring any memory for copying the information.
+
+        See the Python copy module for more information on shallow
+        and deep copies, https://docs.python.org/3/library/copy.html.
+
+        Parameters
+        ----------
+        as_view : bool, optional (default=False)
+            If True, the returned graph-view provides a read-only view
+            of the original graph without actually copying any data.
+
+        Returns
+        -------
+        G : Graph
+            A copy of the graph.
+
+        See Also
+        --------
+        to_directed: return a directed copy of the graph.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> H = G.copy()
+
+        """
+        if as_view is True:
+            return nx.graphviews.generic_graph_view(self)
+        G = self.__class__()
+        G.graph.update(self.graph)
+        G.add_nodes_from((n, d.copy()) for n, d in self._node.items())
+        G.add_edges_from(
+            (u, v, datadict.copy())
+            for u, nbrs in self._adj.items()
+            for v, datadict in nbrs.items()
+        )
+        return G
+
+    def to_directed(self, as_view=False):
+        """Returns a directed representation of the graph.
+
+        Returns
+        -------
+        G : DiGraph
+            A directed graph with the same name, same nodes, and with
+            each edge (u, v, data) replaced by two directed edges
+            (u, v, data) and (v, u, data).
+
+        Notes
+        -----
+        This returns a "deepcopy" of the edge, node, and
+        graph attributes which attempts to completely copy
+        all of the data and references.
+
+        This is in contrast to the similar D=DiGraph(G) which returns a
+        shallow copy of the data.
+
+        See the Python copy module for more information on shallow
+        and deep copies, https://docs.python.org/3/library/copy.html.
+
+        Warning: If you have subclassed Graph to use dict-like objects
+        in the data structure, those changes do not transfer to the
+        DiGraph created by this method.
+
+        Examples
+        --------
+        >>> G = nx.Graph()  # or MultiGraph, etc
+        >>> G.add_edge(0, 1)
+        >>> H = G.to_directed()
+        >>> list(H.edges)
+        [(0, 1), (1, 0)]
+
+        If already directed, return a (deep) copy
+
+        >>> G = nx.DiGraph()  # or MultiDiGraph, etc
+        >>> G.add_edge(0, 1)
+        >>> H = G.to_directed()
+        >>> list(H.edges)
+        [(0, 1)]
+        """
+        graph_class = self.to_directed_class()
+        if as_view is True:
+            return nx.graphviews.generic_graph_view(self, graph_class)
+        # deepcopy when not a view
+        G = graph_class()
+        G.graph.update(deepcopy(self.graph))
+        G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
+        G.add_edges_from(
+            (u, v, deepcopy(data))
+            for u, nbrs in self._adj.items()
+            for v, data in nbrs.items()
+        )
+        return G
+
+    def to_undirected(self, as_view=False):
+        """Returns an undirected copy of the graph.
+
+        Parameters
+        ----------
+        as_view : bool (optional, default=False)
+          If True return a view of the original undirected graph.
+
+        Returns
+        -------
+        G : Graph/MultiGraph
+            A deepcopy of the graph.
+
+        See Also
+        --------
+        Graph, copy, add_edge, add_edges_from
+
+        Notes
+        -----
+        This returns a "deepcopy" of the edge, node, and
+        graph attributes which attempts to completely copy
+        all of the data and references.
+
+        This is in contrast to the similar `G = nx.DiGraph(D)` which returns a
+        shallow copy of the data.
+
+        See the Python copy module for more information on shallow
+        and deep copies, https://docs.python.org/3/library/copy.html.
+
+        Warning: If you have subclassed DiGraph to use dict-like objects
+        in the data structure, those changes do not transfer to the
+        Graph created by this method.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(2)  # or MultiGraph, etc
+        >>> H = G.to_directed()
+        >>> list(H.edges)
+        [(0, 1), (1, 0)]
+        >>> G2 = H.to_undirected()
+        >>> list(G2.edges)
+        [(0, 1)]
+        """
+        graph_class = self.to_undirected_class()
+        if as_view is True:
+            return nx.graphviews.generic_graph_view(self, graph_class)
+        # deepcopy when not a view
+        G = graph_class()
+        G.graph.update(deepcopy(self.graph))
+        G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
+        G.add_edges_from(
+            (u, v, deepcopy(d))
+            for u, nbrs in self._adj.items()
+            for v, d in nbrs.items()
+        )
+        return G
+
+    def subgraph(self, nodes):
+        """Returns a SubGraph view of the subgraph induced on `nodes`.
+
+        The induced subgraph of the graph contains the nodes in `nodes`
+        and the edges between those nodes.
+
+        Parameters
+        ----------
+        nodes : list, iterable
+            A container of nodes which will be iterated through once.
+
+        Returns
+        -------
+        G : SubGraph View
+            A subgraph view of the graph. The graph structure cannot be
+            changed but node/edge attributes can and are shared with the
+            original graph.
+
+        Notes
+        -----
+        The graph, edge and node attributes are shared with the original graph.
+        Changes to the graph structure is ruled out by the view, but changes
+        to attributes are reflected in the original graph.
+
+        To create a subgraph with its own copy of the edge/node attributes use:
+        G.subgraph(nodes).copy()
+
+        For an inplace reduction of a graph to a subgraph you can remove nodes:
+        G.remove_nodes_from([n for n in G if n not in set(nodes)])
+
+        Subgraph views are sometimes NOT what you want. In most cases where
+        you want to do more than simply look at the induced edges, it makes
+        more sense to just create the subgraph as its own graph with code like:
+
+        ::
+
+            # Create a subgraph SG based on a (possibly multigraph) G
+            SG = G.__class__()
+            SG.add_nodes_from((n, G.nodes[n]) for n in largest_wcc)
+            if SG.is_multigraph():
+                SG.add_edges_from(
+                    (n, nbr, key, d)
+                    for n, nbrs in G.adj.items()
+                    if n in largest_wcc
+                    for nbr, keydict in nbrs.items()
+                    if nbr in largest_wcc
+                    for key, d in keydict.items()
+                )
+            else:
+                SG.add_edges_from(
+                    (n, nbr, d)
+                    for n, nbrs in G.adj.items()
+                    if n in largest_wcc
+                    for nbr, d in nbrs.items()
+                    if nbr in largest_wcc
+                )
+            SG.graph.update(G.graph)
+
+        Subgraphs are not guaranteed to preserve the order of nodes or edges
+        as they appear in the original graph. For example:
+
+        >>> G = nx.Graph()
+        >>> G.add_nodes_from(reversed(range(10)))
+        >>> list(G)
+        [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
+        >>> list(G.subgraph([1, 3, 2]))
+        [1, 2, 3]
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> H = G.subgraph([0, 1, 2])
+        >>> list(H.edges)
+        [(0, 1), (1, 2)]
+        """
+        induced_nodes = nx.filters.show_nodes(self.nbunch_iter(nodes))
+        # if already a subgraph, don't make a chain
+        subgraph = nx.subgraph_view
+        if hasattr(self, "_NODE_OK"):
+            return subgraph(
+                self._graph, filter_node=induced_nodes, filter_edge=self._EDGE_OK
+            )
+        return subgraph(self, filter_node=induced_nodes)
+
+    def edge_subgraph(self, edges):
+        """Returns the subgraph induced by the specified edges.
+
+        The induced subgraph contains each edge in `edges` and each
+        node incident to any one of those edges.
+
+        Parameters
+        ----------
+        edges : iterable
+            An iterable of edges in this graph.
+
+        Returns
+        -------
+        G : Graph
+            An edge-induced subgraph of this graph with the same edge
+            attributes.
+
+        Notes
+        -----
+        The graph, edge, and node attributes in the returned subgraph
+        view are references to the corresponding attributes in the original
+        graph. The view is read-only.
+
+        To create a full graph version of the subgraph with its own copy
+        of the edge or node attributes, use::
+
+            G.edge_subgraph(edges).copy()
+
+        Examples
+        --------
+        >>> G = nx.path_graph(5)
+        >>> H = G.edge_subgraph([(0, 1), (3, 4)])
+        >>> list(H.nodes)
+        [0, 1, 3, 4]
+        >>> list(H.edges)
+        [(0, 1), (3, 4)]
+
+        """
+        return nx.edge_subgraph(self, edges)
+
+    def size(self, weight=None):
+        """Returns the number of edges or total of all edge weights.
+
+        Parameters
+        ----------
+        weight : string or None, optional (default=None)
+            The edge attribute that holds the numerical value used
+            as a weight. If None, then each edge has weight 1.
+
+        Returns
+        -------
+        size : numeric
+            The number of edges or
+            (if weight keyword is provided) the total weight sum.
+
+            If weight is None, returns an int. Otherwise a float
+            (or more general numeric if the weights are more general).
+
+        See Also
+        --------
+        number_of_edges
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.size()
+        3
+
+        >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.add_edge("a", "b", weight=2)
+        >>> G.add_edge("b", "c", weight=4)
+        >>> G.size()
+        2
+        >>> G.size(weight="weight")
+        6.0
+        """
+        s = sum(d for v, d in self.degree(weight=weight))
+        # If `weight` is None, the sum of the degrees is guaranteed to be
+        # even, so we can perform integer division and hence return an
+        # integer. Otherwise, the sum of the weighted degrees is not
+        # guaranteed to be an integer, so we perform "real" division.
+        return s // 2 if weight is None else s / 2
+
+    def number_of_edges(self, u=None, v=None):
+        """Returns the number of edges between two nodes.
+
+        Parameters
+        ----------
+        u, v : nodes, optional (default=all edges)
+            If u and v are specified, return the number of edges between
+            u and v. Otherwise return the total number of all edges.
+
+        Returns
+        -------
+        nedges : int
+            The number of edges in the graph.  If nodes `u` and `v` are
+            specified return the number of edges between those nodes. If
+            the graph is directed, this only returns the number of edges
+            from `u` to `v`.
+
+        See Also
+        --------
+        size
+
+        Examples
+        --------
+        For undirected graphs, this method counts the total number of
+        edges in the graph:
+
+        >>> G = nx.path_graph(4)
+        >>> G.number_of_edges()
+        3
+
+        If you specify two nodes, this counts the total number of edges
+        joining the two nodes:
+
+        >>> G.number_of_edges(0, 1)
+        1
+
+        For directed graphs, this method can count the total number of
+        directed edges from `u` to `v`:
+
+        >>> G = nx.DiGraph()
+        >>> G.add_edge(0, 1)
+        >>> G.add_edge(1, 0)
+        >>> G.number_of_edges(0, 1)
+        1
+
+        """
+        if u is None:
+            return int(self.size())
+        if v in self._adj[u]:
+            return 1
+        return 0
+
+    def nbunch_iter(self, nbunch=None):
+        """Returns an iterator over nodes contained in nbunch that are
+        also in the graph.
+
+        The nodes in an iterable nbunch are checked for membership in the graph
+        and if not are silently ignored.
+
+        Parameters
+        ----------
+        nbunch : single node, container, or all nodes (default= all nodes)
+            The view will only report edges incident to these nodes.
+
+        Returns
+        -------
+        niter : iterator
+            An iterator over nodes in nbunch that are also in the graph.
+            If nbunch is None, iterate over all nodes in the graph.
+
+        Raises
+        ------
+        NetworkXError
+            If nbunch is not a node or sequence of nodes.
+            If a node in nbunch is not hashable.
+
+        See Also
+        --------
+        Graph.__iter__
+
+        Notes
+        -----
+        When nbunch is an iterator, the returned iterator yields values
+        directly from nbunch, becoming exhausted when nbunch is exhausted.
+
+        To test whether nbunch is a single node, one can use
+        "if nbunch in self:", even after processing with this routine.
+
+        If nbunch is not a node or a (possibly empty) sequence/iterator
+        or None, a :exc:`NetworkXError` is raised.  Also, if any object in
+        nbunch is not hashable, a :exc:`NetworkXError` is raised.
+        """
+        if nbunch is None:  # include all nodes via iterator
+            bunch = iter(self._adj)
+        elif nbunch in self:  # if nbunch is a single node
+            bunch = iter([nbunch])
+        else:  # if nbunch is a sequence of nodes
+
+            def bunch_iter(nlist, adj):
+                try:
+                    for n in nlist:
+                        if n in adj:
+                            yield n
+                except TypeError as err:
+                    exc, message = err, err.args[0]
+                    # capture error for non-sequence/iterator nbunch.
+                    if "iter" in message:
+                        exc = NetworkXError(
+                            "nbunch is not a node or a sequence of nodes."
+                        )
+                    # capture single nodes that are not in the graph.
+                    if "object is not iterable" in message:
+                        exc = NetworkXError(f"Node {nbunch} is not in the graph.")
+                    # capture error for unhashable node.
+                    if "hashable" in message:
+                        exc = NetworkXError(
+                            f"Node {n} in sequence nbunch is not a valid node."
+                        )
+                    raise exc
+
+            bunch = bunch_iter(nbunch, self._adj)
+        return bunch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/graphviews.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/graphviews.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b09df649ef48fa484d27e51d86cce1e10d593a7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/graphviews.py
@@ -0,0 +1,269 @@
+"""View of Graphs as SubGraph, Reverse, Directed, Undirected.
+
+In some algorithms it is convenient to temporarily morph
+a graph to exclude some nodes or edges. It should be better
+to do that via a view than to remove and then re-add.
+In other algorithms it is convenient to temporarily morph
+a graph to reverse directed edges, or treat a directed graph
+as undirected, etc. This module provides those graph views.
+
+The resulting views are essentially read-only graphs that
+report data from the original graph object. We provide an
+attribute G._graph which points to the underlying graph object.
+
+Note: Since graphviews look like graphs, one can end up with
+view-of-view-of-view chains. Be careful with chains because
+they become very slow with about 15 nested views.
+For the common simple case of node induced subgraphs created
+from the graph class, we short-cut the chain by returning a
+subgraph of the original graph directly rather than a subgraph
+of a subgraph. We are careful not to disrupt any edge filter in
+the middle subgraph. In general, determining how to short-cut
+the chain is tricky and much harder with restricted_views than
+with induced subgraphs.
+Often it is easiest to use .copy() to avoid chains.
+"""
+
+import networkx as nx
+from networkx.classes.coreviews import (
+    FilterAdjacency,
+    FilterAtlas,
+    FilterMultiAdjacency,
+    UnionAdjacency,
+    UnionMultiAdjacency,
+)
+from networkx.classes.filters import no_filter
+from networkx.exception import NetworkXError
+from networkx.utils import not_implemented_for
+
+__all__ = ["generic_graph_view", "subgraph_view", "reverse_view"]
+
+
+def generic_graph_view(G, create_using=None):
+    """Returns a read-only view of `G`.
+
+    The graph `G` and its attributes are not copied but viewed through the new graph object
+    of the same class as `G` (or of the class specified in `create_using`).
+
+    Parameters
+    ----------
+    G : graph
+        A directed/undirected graph/multigraph.
+
+    create_using : NetworkX graph constructor, optional (default=None)
+       Graph type to create. If graph instance, then cleared before populated.
+       If `None`, then the appropriate Graph type is inferred from `G`.
+
+    Returns
+    -------
+    newG : graph
+        A view of the input graph `G` and its attributes as viewed through
+        the `create_using` class.
+
+    Raises
+    ------
+    NetworkXError
+        If `G` is a multigraph (or multidigraph) but `create_using` is not, or vice versa.
+
+    Notes
+    -----
+    The returned graph view is read-only (cannot modify the graph).
+    Yet the view reflects any changes in `G`. The intent is to mimic dict views.
+
+    Examples
+    --------
+    >>> G = nx.Graph()
+    >>> G.add_edge(1, 2, weight=0.3)
+    >>> G.add_edge(2, 3, weight=0.5)
+    >>> G.edges(data=True)
+    EdgeDataView([(1, 2, {'weight': 0.3}), (2, 3, {'weight': 0.5})])
+
+    The view exposes the attributes from the original graph.
+
+    >>> viewG = nx.graphviews.generic_graph_view(G)
+    >>> viewG.edges(data=True)
+    EdgeDataView([(1, 2, {'weight': 0.3}), (2, 3, {'weight': 0.5})])
+
+    Changes to `G` are reflected in `viewG`.
+
+    >>> G.remove_edge(2, 3)
+    >>> G.edges(data=True)
+    EdgeDataView([(1, 2, {'weight': 0.3})])
+
+    >>> viewG.edges(data=True)
+    EdgeDataView([(1, 2, {'weight': 0.3})])
+
+    We can change the graph type with the `create_using` parameter.
+
+    >>> type(G)
+    
+    >>> viewDG = nx.graphviews.generic_graph_view(G, create_using=nx.DiGraph)
+    >>> type(viewDG)
+    
+    """
+    if create_using is None:
+        newG = G.__class__()
+    else:
+        newG = nx.empty_graph(0, create_using)
+    if G.is_multigraph() != newG.is_multigraph():
+        raise NetworkXError("Multigraph for G must agree with create_using")
+    newG = nx.freeze(newG)
+
+    # create view by assigning attributes from G
+    newG._graph = G
+    newG.graph = G.graph
+
+    newG._node = G._node
+    if newG.is_directed():
+        if G.is_directed():
+            newG._succ = G._succ
+            newG._pred = G._pred
+            # newG._adj is synced with _succ
+        else:
+            newG._succ = G._adj
+            newG._pred = G._adj
+            # newG._adj is synced with _succ
+    elif G.is_directed():
+        if G.is_multigraph():
+            newG._adj = UnionMultiAdjacency(G._succ, G._pred)
+        else:
+            newG._adj = UnionAdjacency(G._succ, G._pred)
+    else:
+        newG._adj = G._adj
+    return newG
+
+
+def subgraph_view(G, *, filter_node=no_filter, filter_edge=no_filter):
+    """View of `G` applying a filter on nodes and edges.
+
+    `subgraph_view` provides a read-only view of the input graph that excludes
+    nodes and edges based on the outcome of two filter functions `filter_node`
+    and `filter_edge`.
+
+    The `filter_node` function takes one argument --- the node --- and returns
+    `True` if the node should be included in the subgraph, and `False` if it
+    should not be included.
+
+    The `filter_edge` function takes two (or three arguments if `G` is a
+    multi-graph) --- the nodes describing an edge, plus the edge-key if
+    parallel edges are possible --- and returns `True` if the edge should be
+    included in the subgraph, and `False` if it should not be included.
+
+    Both node and edge filter functions are called on graph elements as they
+    are queried, meaning there is no up-front cost to creating the view.
+
+    Parameters
+    ----------
+    G : networkx.Graph
+        A directed/undirected graph/multigraph
+
+    filter_node : callable, optional
+        A function taking a node as input, which returns `True` if the node
+        should appear in the view.
+
+    filter_edge : callable, optional
+        A function taking as input the two nodes describing an edge (plus the
+        edge-key if `G` is a multi-graph), which returns `True` if the edge
+        should appear in the view.
+
+    Returns
+    -------
+    graph : networkx.Graph
+        A read-only graph view of the input graph.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(6)
+
+    Filter functions operate on the node, and return `True` if the node should
+    appear in the view:
+
+    >>> def filter_node(n1):
+    ...     return n1 != 5
+    >>> view = nx.subgraph_view(G, filter_node=filter_node)
+    >>> view.nodes()
+    NodeView((0, 1, 2, 3, 4))
+
+    We can use a closure pattern to filter graph elements based on additional
+    data --- for example, filtering on edge data attached to the graph:
+
+    >>> G[3][4]["cross_me"] = False
+    >>> def filter_edge(n1, n2):
+    ...     return G[n1][n2].get("cross_me", True)
+    >>> view = nx.subgraph_view(G, filter_edge=filter_edge)
+    >>> view.edges()
+    EdgeView([(0, 1), (1, 2), (2, 3), (4, 5)])
+
+    >>> view = nx.subgraph_view(
+    ...     G,
+    ...     filter_node=filter_node,
+    ...     filter_edge=filter_edge,
+    ... )
+    >>> view.nodes()
+    NodeView((0, 1, 2, 3, 4))
+    >>> view.edges()
+    EdgeView([(0, 1), (1, 2), (2, 3)])
+    """
+    newG = nx.freeze(G.__class__())
+    newG._NODE_OK = filter_node
+    newG._EDGE_OK = filter_edge
+
+    # create view by assigning attributes from G
+    newG._graph = G
+    newG.graph = G.graph
+
+    newG._node = FilterAtlas(G._node, filter_node)
+    if G.is_multigraph():
+        Adj = FilterMultiAdjacency
+
+        def reverse_edge(u, v, k=None):
+            return filter_edge(v, u, k)
+
+    else:
+        Adj = FilterAdjacency
+
+        def reverse_edge(u, v, k=None):
+            return filter_edge(v, u)
+
+    if G.is_directed():
+        newG._succ = Adj(G._succ, filter_node, filter_edge)
+        newG._pred = Adj(G._pred, filter_node, reverse_edge)
+        # newG._adj is synced with _succ
+    else:
+        newG._adj = Adj(G._adj, filter_node, filter_edge)
+    return newG
+
+
+@not_implemented_for("undirected")
+def reverse_view(G):
+    """View of `G` with edge directions reversed
+
+    `reverse_view` returns a read-only view of the input graph where
+    edge directions are reversed.
+
+    Identical to digraph.reverse(copy=False)
+
+    Parameters
+    ----------
+    G : networkx.DiGraph
+
+    Returns
+    -------
+    graph : networkx.DiGraph
+
+    Examples
+    --------
+    >>> G = nx.DiGraph()
+    >>> G.add_edge(1, 2)
+    >>> G.add_edge(2, 3)
+    >>> G.edges()
+    OutEdgeView([(1, 2), (2, 3)])
+
+    >>> view = nx.reverse_view(G)
+    >>> view.edges()
+    OutEdgeView([(2, 1), (3, 2)])
+    """
+    newG = generic_graph_view(G)
+    newG._succ, newG._pred = G._pred, G._succ
+    # newG._adj is synced with _succ
+    return newG
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/multidigraph.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/multidigraph.py
new file mode 100644
index 0000000000000000000000000000000000000000..27c987037e2a47dd80045042893139f0aad226f5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/multidigraph.py
@@ -0,0 +1,977 @@
+"""Base class for MultiDiGraph."""
+
+from copy import deepcopy
+from functools import cached_property
+
+import networkx as nx
+from networkx import convert
+from networkx.classes.coreviews import MultiAdjacencyView
+from networkx.classes.digraph import DiGraph
+from networkx.classes.multigraph import MultiGraph
+from networkx.classes.reportviews import (
+    DiMultiDegreeView,
+    InMultiDegreeView,
+    InMultiEdgeView,
+    OutMultiDegreeView,
+    OutMultiEdgeView,
+)
+from networkx.exception import NetworkXError
+
+__all__ = ["MultiDiGraph"]
+
+
+class MultiDiGraph(MultiGraph, DiGraph):
+    """A directed graph class that can store multiedges.
+
+    Multiedges are multiple edges between two nodes.  Each edge
+    can hold optional data or attributes.
+
+    A MultiDiGraph holds directed edges.  Self loops are allowed.
+
+    Nodes can be arbitrary (hashable) Python objects with optional
+    key/value attributes. By convention `None` is not used as a node.
+
+    Edges are represented as links between nodes with optional
+    key/value attributes.
+
+    Parameters
+    ----------
+    incoming_graph_data : input graph (optional, default: None)
+        Data to initialize graph. If None (default) an empty
+        graph is created.  The data can be any format that is supported
+        by the to_networkx_graph() function, currently including edge list,
+        dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy
+        sparse matrix, or PyGraphviz graph.
+
+    multigraph_input : bool or None (default None)
+        Note: Only used when `incoming_graph_data` is a dict.
+        If True, `incoming_graph_data` is assumed to be a
+        dict-of-dict-of-dict-of-dict structure keyed by
+        node to neighbor to edge keys to edge data for multi-edges.
+        A NetworkXError is raised if this is not the case.
+        If False, :func:`to_networkx_graph` is used to try to determine
+        the dict's graph data structure as either a dict-of-dict-of-dict
+        keyed by node to neighbor to edge data, or a dict-of-iterable
+        keyed by node to neighbors.
+        If None, the treatment for True is tried, but if it fails,
+        the treatment for False is tried.
+
+    attr : keyword arguments, optional (default= no attributes)
+        Attributes to add to graph as key=value pairs.
+
+    See Also
+    --------
+    Graph
+    DiGraph
+    MultiGraph
+
+    Examples
+    --------
+    Create an empty graph structure (a "null graph") with no nodes and
+    no edges.
+
+    >>> G = nx.MultiDiGraph()
+
+    G can be grown in several ways.
+
+    **Nodes:**
+
+    Add one node at a time:
+
+    >>> G.add_node(1)
+
+    Add the nodes from any container (a list, dict, set or
+    even the lines from a file or the nodes from another graph).
+
+    >>> G.add_nodes_from([2, 3])
+    >>> G.add_nodes_from(range(100, 110))
+    >>> H = nx.path_graph(10)
+    >>> G.add_nodes_from(H)
+
+    In addition to strings and integers any hashable Python object
+    (except None) can represent a node, e.g. a customized node object,
+    or even another Graph.
+
+    >>> G.add_node(H)
+
+    **Edges:**
+
+    G can also be grown by adding edges.
+
+    Add one edge,
+
+    >>> key = G.add_edge(1, 2)
+
+    a list of edges,
+
+    >>> keys = G.add_edges_from([(1, 2), (1, 3)])
+
+    or a collection of edges,
+
+    >>> keys = G.add_edges_from(H.edges)
+
+    If some edges connect nodes not yet in the graph, the nodes
+    are added automatically.  If an edge already exists, an additional
+    edge is created and stored using a key to identify the edge.
+    By default the key is the lowest unused integer.
+
+    >>> keys = G.add_edges_from([(4, 5, dict(route=282)), (4, 5, dict(route=37))])
+    >>> G[4]
+    AdjacencyView({5: {0: {}, 1: {'route': 282}, 2: {'route': 37}}})
+
+    **Attributes:**
+
+    Each graph, node, and edge can hold key/value attribute pairs
+    in an associated attribute dictionary (the keys must be hashable).
+    By default these are empty, but can be added or changed using
+    add_edge, add_node or direct manipulation of the attribute
+    dictionaries named graph, node and edge respectively.
+
+    >>> G = nx.MultiDiGraph(day="Friday")
+    >>> G.graph
+    {'day': 'Friday'}
+
+    Add node attributes using add_node(), add_nodes_from() or G.nodes
+
+    >>> G.add_node(1, time="5pm")
+    >>> G.add_nodes_from([3], time="2pm")
+    >>> G.nodes[1]
+    {'time': '5pm'}
+    >>> G.nodes[1]["room"] = 714
+    >>> del G.nodes[1]["room"]  # remove attribute
+    >>> list(G.nodes(data=True))
+    [(1, {'time': '5pm'}), (3, {'time': '2pm'})]
+
+    Add edge attributes using add_edge(), add_edges_from(), subscript
+    notation, or G.edges.
+
+    >>> key = G.add_edge(1, 2, weight=4.7)
+    >>> keys = G.add_edges_from([(3, 4), (4, 5)], color="red")
+    >>> keys = G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
+    >>> G[1][2][0]["weight"] = 4.7
+    >>> G.edges[1, 2, 0]["weight"] = 4
+
+    Warning: we protect the graph data structure by making `G.edges[1,
+    2, 0]` a read-only dict-like structure. However, you can assign to
+    attributes in e.g. `G.edges[1, 2, 0]`. Thus, use 2 sets of brackets
+    to add/change data attributes: `G.edges[1, 2, 0]['weight'] = 4`
+    (for multigraphs the edge key is required: `MG.edges[u, v,
+    key][name] = value`).
+
+    **Shortcuts:**
+
+    Many common graph features allow python syntax to speed reporting.
+
+    >>> 1 in G  # check if node in graph
+    True
+    >>> [n for n in G if n < 3]  # iterate through nodes
+    [1, 2]
+    >>> len(G)  # number of nodes in graph
+    5
+    >>> G[1]  # adjacency dict-like view mapping neighbor -> edge key -> edge attributes
+    AdjacencyView({2: {0: {'weight': 4}, 1: {'color': 'blue'}}})
+
+    Often the best way to traverse all edges of a graph is via the neighbors.
+    The neighbors are available as an adjacency-view `G.adj` object or via
+    the method `G.adjacency()`.
+
+    >>> for n, nbrsdict in G.adjacency():
+    ...     for nbr, keydict in nbrsdict.items():
+    ...         for key, eattr in keydict.items():
+    ...             if "weight" in eattr:
+    ...                 # Do something useful with the edges
+    ...                 pass
+
+    But the edges() method is often more convenient:
+
+    >>> for u, v, keys, weight in G.edges(data="weight", keys=True):
+    ...     if weight is not None:
+    ...         # Do something useful with the edges
+    ...         pass
+
+    **Reporting:**
+
+    Simple graph information is obtained using methods and object-attributes.
+    Reporting usually provides views instead of containers to reduce memory
+    usage. The views update as the graph is updated similarly to dict-views.
+    The objects `nodes`, `edges` and `adj` provide access to data attributes
+    via lookup (e.g. `nodes[n]`, `edges[u, v, k]`, `adj[u][v]`) and iteration
+    (e.g. `nodes.items()`, `nodes.data('color')`,
+    `nodes.data('color', default='blue')` and similarly for `edges`)
+    Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
+
+    For details on these and other miscellaneous methods, see below.
+
+    **Subclasses (Advanced):**
+
+    The MultiDiGraph class uses a dict-of-dict-of-dict-of-dict structure.
+    The outer dict (node_dict) holds adjacency information keyed by node.
+    The next dict (adjlist_dict) represents the adjacency information
+    and holds edge_key dicts keyed by neighbor. The edge_key dict holds
+    each edge_attr dict keyed by edge key. The inner dict
+    (edge_attr_dict) represents the edge data and holds edge attribute
+    values keyed by attribute names.
+
+    Each of these four dicts in the dict-of-dict-of-dict-of-dict
+    structure can be replaced by a user defined dict-like object.
+    In general, the dict-like features should be maintained but
+    extra features can be added. To replace one of the dicts create
+    a new graph class by changing the class(!) variable holding the
+    factory for that dict-like structure. The variable names are
+    node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,
+    adjlist_outer_dict_factory, edge_key_dict_factory, edge_attr_dict_factory
+    and graph_attr_dict_factory.
+
+    node_dict_factory : function, (default: dict)
+        Factory function to be used to create the dict containing node
+        attributes, keyed by node id.
+        It should require no arguments and return a dict-like object
+
+    node_attr_dict_factory: function, (default: dict)
+        Factory function to be used to create the node attribute
+        dict which holds attribute values keyed by attribute name.
+        It should require no arguments and return a dict-like object
+
+    adjlist_outer_dict_factory : function, (default: dict)
+        Factory function to be used to create the outer-most dict
+        in the data structure that holds adjacency info keyed by node.
+        It should require no arguments and return a dict-like object.
+
+    adjlist_inner_dict_factory : function, (default: dict)
+        Factory function to be used to create the adjacency list
+        dict which holds multiedge key dicts keyed by neighbor.
+        It should require no arguments and return a dict-like object.
+
+    edge_key_dict_factory : function, (default: dict)
+        Factory function to be used to create the edge key dict
+        which holds edge data keyed by edge key.
+        It should require no arguments and return a dict-like object.
+
+    edge_attr_dict_factory : function, (default: dict)
+        Factory function to be used to create the edge attribute
+        dict which holds attribute values keyed by attribute name.
+        It should require no arguments and return a dict-like object.
+
+    graph_attr_dict_factory : function, (default: dict)
+        Factory function to be used to create the graph attribute
+        dict which holds attribute values keyed by attribute name.
+        It should require no arguments and return a dict-like object.
+
+    Typically, if your extension doesn't impact the data structure all
+    methods will inherited without issue except: `to_directed/to_undirected`.
+    By default these methods create a DiGraph/Graph class and you probably
+    want them to create your extension of a DiGraph/Graph. To facilitate
+    this we define two class variables that you can set in your subclass.
+
+    to_directed_class : callable, (default: DiGraph or MultiDiGraph)
+        Class to create a new graph structure in the `to_directed` method.
+        If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
+
+    to_undirected_class : callable, (default: Graph or MultiGraph)
+        Class to create a new graph structure in the `to_undirected` method.
+        If `None`, a NetworkX class (Graph or MultiGraph) is used.
+
+    **Subclassing Example**
+
+    Create a low memory graph class that effectively disallows edge
+    attributes by using a single attribute dict for all edges.
+    This reduces the memory used, but you lose edge attributes.
+
+    >>> class ThinGraph(nx.Graph):
+    ...     all_edge_dict = {"weight": 1}
+    ...
+    ...     def single_edge_dict(self):
+    ...         return self.all_edge_dict
+    ...
+    ...     edge_attr_dict_factory = single_edge_dict
+    >>> G = ThinGraph()
+    >>> G.add_edge(2, 1)
+    >>> G[2][1]
+    {'weight': 1}
+    >>> G.add_edge(2, 2)
+    >>> G[2][1] is G[2][2]
+    True
+    """
+
+    # node_dict_factory = dict    # already assigned in Graph
+    # adjlist_outer_dict_factory = dict
+    # adjlist_inner_dict_factory = dict
+    edge_key_dict_factory = dict
+    # edge_attr_dict_factory = dict
+
+    # This __new__ method just does what Python itself does automatically.
+    # We include it here as part of the dispatchable/backend interface.
+    # If your goal is to understand how the graph classes work, you can ignore
+    # this method, even when subclassing the base classes. If you are subclassing
+    # in order to provide a backend that allows class instantiation, this method
+    # can be overridden to return your own backend graph class.
+    @nx._dispatchable(name="multidigraph__new__", graphs=None, returns_graph=True)
+    def __new__(cls, *args, **kwargs):
+        return object.__new__(cls)
+
+    def __init__(self, incoming_graph_data=None, multigraph_input=None, **attr):
+        """Initialize a graph with edges, name, or graph attributes.
+
+        Parameters
+        ----------
+        incoming_graph_data : input graph
+            Data to initialize graph.  If incoming_graph_data=None (default)
+            an empty graph is created.  The data can be an edge list, or any
+            NetworkX graph object.  If the corresponding optional Python
+            packages are installed the data can also be a 2D NumPy array, a
+            SciPy sparse array, or a PyGraphviz graph.
+
+        multigraph_input : bool or None (default None)
+            Note: Only used when `incoming_graph_data` is a dict.
+            If True, `incoming_graph_data` is assumed to be a
+            dict-of-dict-of-dict-of-dict structure keyed by
+            node to neighbor to edge keys to edge data for multi-edges.
+            A NetworkXError is raised if this is not the case.
+            If False, :func:`to_networkx_graph` is used to try to determine
+            the dict's graph data structure as either a dict-of-dict-of-dict
+            keyed by node to neighbor to edge data, or a dict-of-iterable
+            keyed by node to neighbors.
+            If None, the treatment for True is tried, but if it fails,
+            the treatment for False is tried.
+
+        attr : keyword arguments, optional (default= no attributes)
+            Attributes to add to graph as key=value pairs.
+
+        See Also
+        --------
+        convert
+
+        Examples
+        --------
+        >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G = nx.Graph(name="my graph")
+        >>> e = [(1, 2), (2, 3), (3, 4)]  # list of edges
+        >>> G = nx.Graph(e)
+
+        Arbitrary graph attribute pairs (key=value) may be assigned
+
+        >>> G = nx.Graph(e, day="Friday")
+        >>> G.graph
+        {'day': 'Friday'}
+
+        """
+        attr.pop("backend", None)  # Ignore explicit `backend="networkx"`
+        # multigraph_input can be None/True/False. So check "is not False"
+        if isinstance(incoming_graph_data, dict) and multigraph_input is not False:
+            DiGraph.__init__(self)
+            try:
+                convert.from_dict_of_dicts(
+                    incoming_graph_data, create_using=self, multigraph_input=True
+                )
+                self.graph.update(attr)
+            except Exception as err:
+                if multigraph_input is True:
+                    raise nx.NetworkXError(
+                        f"converting multigraph_input raised:\n{type(err)}: {err}"
+                    )
+                DiGraph.__init__(self, incoming_graph_data, **attr)
+        else:
+            DiGraph.__init__(self, incoming_graph_data, **attr)
+
+    @cached_property
+    def adj(self):
+        """Graph adjacency object holding the neighbors of each node.
+
+        This object is a read-only dict-like structure with node keys
+        and neighbor-dict values.  The neighbor-dict is keyed by neighbor
+        to the edgekey-dict.  So `G.adj[3][2][0]['color'] = 'blue'` sets
+        the color of the edge `(3, 2, 0)` to `"blue"`.
+
+        Iterating over G.adj behaves like a dict. Useful idioms include
+        `for nbr, datadict in G.adj[n].items():`.
+
+        The neighbor information is also provided by subscripting the graph.
+        So `for nbr, foovalue in G[node].data('foo', default=1):` works.
+
+        For directed graphs, `G.adj` holds outgoing (successor) info.
+        """
+        return MultiAdjacencyView(self._succ)
+
+    @cached_property
+    def succ(self):
+        """Graph adjacency object holding the successors of each node.
+
+        This object is a read-only dict-like structure with node keys
+        and neighbor-dict values.  The neighbor-dict is keyed by neighbor
+        to the edgekey-dict.  So `G.adj[3][2][0]['color'] = 'blue'` sets
+        the color of the edge `(3, 2, 0)` to `"blue"`.
+
+        Iterating over G.adj behaves like a dict. Useful idioms include
+        `for nbr, datadict in G.adj[n].items():`.
+
+        The neighbor information is also provided by subscripting the graph.
+        So `for nbr, foovalue in G[node].data('foo', default=1):` works.
+
+        For directed graphs, `G.succ` is identical to `G.adj`.
+        """
+        return MultiAdjacencyView(self._succ)
+
+    @cached_property
+    def pred(self):
+        """Graph adjacency object holding the predecessors of each node.
+
+        This object is a read-only dict-like structure with node keys
+        and neighbor-dict values.  The neighbor-dict is keyed by neighbor
+        to the edgekey-dict.  So `G.adj[3][2][0]['color'] = 'blue'` sets
+        the color of the edge `(3, 2, 0)` to `"blue"`.
+
+        Iterating over G.adj behaves like a dict. Useful idioms include
+        `for nbr, datadict in G.adj[n].items():`.
+        """
+        return MultiAdjacencyView(self._pred)
+
+    def add_edge(self, u_for_edge, v_for_edge, key=None, **attr):
+        """Add an edge between u and v.
+
+        The nodes u and v will be automatically added if they are
+        not already in the graph.
+
+        Edge attributes can be specified with keywords or by directly
+        accessing the edge's attribute dictionary. See examples below.
+
+        Parameters
+        ----------
+        u_for_edge, v_for_edge : nodes
+            Nodes can be, for example, strings or numbers.
+            Nodes must be hashable (and not None) Python objects.
+        key : hashable identifier, optional (default=lowest unused integer)
+            Used to distinguish multiedges between a pair of nodes.
+        attr : keyword arguments, optional
+            Edge data (or labels or objects) can be assigned using
+            keyword arguments.
+
+        Returns
+        -------
+        The edge key assigned to the edge.
+
+        See Also
+        --------
+        add_edges_from : add a collection of edges
+
+        Notes
+        -----
+        To replace/update edge data, use the optional key argument
+        to identify a unique edge.  Otherwise a new edge will be created.
+
+        NetworkX algorithms designed for weighted graphs cannot use
+        multigraphs directly because it is not clear how to handle
+        multiedge weights.  Convert to Graph using edge attribute
+        'weight' to enable weighted graph algorithms.
+
+        Default keys are generated using the method `new_edge_key()`.
+        This method can be overridden by subclassing the base class and
+        providing a custom `new_edge_key()` method.
+
+        Examples
+        --------
+        The following all add the edge e=(1, 2) to graph G:
+
+        >>> G = nx.MultiDiGraph()
+        >>> e = (1, 2)
+        >>> key = G.add_edge(1, 2)  # explicit two-node form
+        >>> G.add_edge(*e)  # single edge as tuple of two nodes
+        1
+        >>> G.add_edges_from([(1, 2)])  # add edges from iterable container
+        [2]
+
+        Associate data to edges using keywords:
+
+        >>> key = G.add_edge(1, 2, weight=3)
+        >>> key = G.add_edge(1, 2, key=0, weight=4)  # update data for key=0
+        >>> key = G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
+
+        For non-string attribute keys, use subscript notation.
+
+        >>> ekey = G.add_edge(1, 2)
+        >>> G[1][2][0].update({0: 5})
+        >>> G.edges[1, 2, 0].update({0: 5})
+        """
+        u, v = u_for_edge, v_for_edge
+        # add nodes
+        if u not in self._succ:
+            if u is None:
+                raise ValueError("None cannot be a node")
+            self._succ[u] = self.adjlist_inner_dict_factory()
+            self._pred[u] = self.adjlist_inner_dict_factory()
+            self._node[u] = self.node_attr_dict_factory()
+        if v not in self._succ:
+            if v is None:
+                raise ValueError("None cannot be a node")
+            self._succ[v] = self.adjlist_inner_dict_factory()
+            self._pred[v] = self.adjlist_inner_dict_factory()
+            self._node[v] = self.node_attr_dict_factory()
+        if key is None:
+            key = self.new_edge_key(u, v)
+        if v in self._succ[u]:
+            keydict = self._adj[u][v]
+            datadict = keydict.get(key, self.edge_attr_dict_factory())
+            datadict.update(attr)
+            keydict[key] = datadict
+        else:
+            # selfloops work this way without special treatment
+            datadict = self.edge_attr_dict_factory()
+            datadict.update(attr)
+            keydict = self.edge_key_dict_factory()
+            keydict[key] = datadict
+            self._succ[u][v] = keydict
+            self._pred[v][u] = keydict
+        nx._clear_cache(self)
+        return key
+
+    def remove_edge(self, u, v, key=None):
+        """Remove an edge between u and v.
+
+        Parameters
+        ----------
+        u, v : nodes
+            Remove an edge between nodes u and v.
+        key : hashable identifier, optional (default=None)
+            Used to distinguish multiple edges between a pair of nodes.
+            If None, remove a single edge between u and v. If there are
+            multiple edges, removes the last edge added in terms of
+            insertion order.
+
+        Raises
+        ------
+        NetworkXError
+            If there is not an edge between u and v, or
+            if there is no edge with the specified key.
+
+        See Also
+        --------
+        remove_edges_from : remove a collection of edges
+
+        Examples
+        --------
+        >>> G = nx.MultiDiGraph()
+        >>> nx.add_path(G, [0, 1, 2, 3])
+        >>> G.remove_edge(0, 1)
+        >>> e = (1, 2)
+        >>> G.remove_edge(*e)  # unpacks e from an edge tuple
+
+        For multiple edges
+
+        >>> G = nx.MultiDiGraph()
+        >>> G.add_edges_from([(1, 2), (1, 2), (1, 2)])  # key_list returned
+        [0, 1, 2]
+
+        When ``key=None`` (the default), edges are removed in the opposite
+        order that they were added:
+
+        >>> G.remove_edge(1, 2)
+        >>> G.edges(keys=True)
+        OutMultiEdgeView([(1, 2, 0), (1, 2, 1)])
+
+        For edges with keys
+
+        >>> G = nx.MultiDiGraph()
+        >>> G.add_edge(1, 2, key="first")
+        'first'
+        >>> G.add_edge(1, 2, key="second")
+        'second'
+        >>> G.remove_edge(1, 2, key="first")
+        >>> G.edges(keys=True)
+        OutMultiEdgeView([(1, 2, 'second')])
+
+        """
+        try:
+            d = self._adj[u][v]
+        except KeyError as err:
+            raise NetworkXError(f"The edge {u}-{v} is not in the graph.") from err
+        # remove the edge with specified data
+        if key is None:
+            d.popitem()
+        else:
+            try:
+                del d[key]
+            except KeyError as err:
+                msg = f"The edge {u}-{v} with key {key} is not in the graph."
+                raise NetworkXError(msg) from err
+        if len(d) == 0:
+            # remove the key entries if last edge
+            del self._succ[u][v]
+            del self._pred[v][u]
+        nx._clear_cache(self)
+
+    @cached_property
+    def edges(self):
+        """An OutMultiEdgeView of the Graph as G.edges or G.edges().
+
+        edges(self, nbunch=None, data=False, keys=False, default=None)
+
+        The OutMultiEdgeView provides set-like operations on the edge-tuples
+        as well as edge attribute lookup. When called, it also provides
+        an EdgeDataView object which allows control of access to edge
+        attributes (but does not provide set-like operations).
+        Hence, ``G.edges[u, v, k]['color']`` provides the value of the color
+        attribute for the edge from ``u`` to ``v`` with key ``k`` while
+        ``for (u, v, k, c) in G.edges(data='color', default='red', keys=True):``
+        iterates through all the edges yielding the color attribute with
+        default `'red'` if no color attribute exists.
+
+        Edges are returned as tuples with optional data and keys
+        in the order (node, neighbor, key, data). If ``keys=True`` is not
+        provided, the tuples will just be (node, neighbor, data), but
+        multiple tuples with the same node and neighbor will be
+        generated when multiple edges between two nodes exist.
+
+        Parameters
+        ----------
+        nbunch : single node, container, or all nodes (default= all nodes)
+            The view will only report edges from these nodes.
+        data : string or bool, optional (default=False)
+            The edge attribute returned in 3-tuple (u, v, ddict[data]).
+            If True, return edge attribute dict in 3-tuple (u, v, ddict).
+            If False, return 2-tuple (u, v).
+        keys : bool, optional (default=False)
+            If True, return edge keys with each edge, creating (u, v, k,
+            d) tuples when data is also requested (the default) and (u,
+            v, k) tuples when data is not requested.
+        default : value, optional (default=None)
+            Value used for edges that don't have the requested attribute.
+            Only relevant if data is not True or False.
+
+        Returns
+        -------
+        edges : OutMultiEdgeView
+            A view of edge attributes, usually it iterates over (u, v)
+            (u, v, k) or (u, v, k, d) tuples of edges, but can also be
+            used for attribute lookup as ``edges[u, v, k]['foo']``.
+
+        Notes
+        -----
+        Nodes in nbunch that are not in the graph will be (quietly) ignored.
+        For directed graphs this returns the out-edges.
+
+        Examples
+        --------
+        >>> G = nx.MultiDiGraph()
+        >>> nx.add_path(G, [0, 1, 2])
+        >>> key = G.add_edge(2, 3, weight=5)
+        >>> key2 = G.add_edge(1, 2)  # second edge between these nodes
+        >>> [e for e in G.edges()]
+        [(0, 1), (1, 2), (1, 2), (2, 3)]
+        >>> list(G.edges(data=True))  # default data is {} (empty dict)
+        [(0, 1, {}), (1, 2, {}), (1, 2, {}), (2, 3, {'weight': 5})]
+        >>> list(G.edges(data="weight", default=1))
+        [(0, 1, 1), (1, 2, 1), (1, 2, 1), (2, 3, 5)]
+        >>> list(G.edges(keys=True))  # default keys are integers
+        [(0, 1, 0), (1, 2, 0), (1, 2, 1), (2, 3, 0)]
+        >>> list(G.edges(data=True, keys=True))
+        [(0, 1, 0, {}), (1, 2, 0, {}), (1, 2, 1, {}), (2, 3, 0, {'weight': 5})]
+        >>> list(G.edges(data="weight", default=1, keys=True))
+        [(0, 1, 0, 1), (1, 2, 0, 1), (1, 2, 1, 1), (2, 3, 0, 5)]
+        >>> list(G.edges([0, 2]))
+        [(0, 1), (2, 3)]
+        >>> list(G.edges(0))
+        [(0, 1)]
+        >>> list(G.edges(1))
+        [(1, 2), (1, 2)]
+
+        See Also
+        --------
+        in_edges, out_edges
+        """
+        return OutMultiEdgeView(self)
+
+    # alias out_edges to edges
+    @cached_property
+    def out_edges(self):
+        return OutMultiEdgeView(self)
+
+    out_edges.__doc__ = edges.__doc__
+
+    @cached_property
+    def in_edges(self):
+        """A view of the in edges of the graph as G.in_edges or G.in_edges().
+
+        in_edges(self, nbunch=None, data=False, keys=False, default=None)
+
+        Parameters
+        ----------
+        nbunch : single node, container, or all nodes (default= all nodes)
+            The view will only report edges incident to these nodes.
+        data : string or bool, optional (default=False)
+            The edge attribute returned in 3-tuple (u, v, ddict[data]).
+            If True, return edge attribute dict in 3-tuple (u, v, ddict).
+            If False, return 2-tuple (u, v).
+        keys : bool, optional (default=False)
+            If True, return edge keys with each edge, creating 3-tuples
+            (u, v, k) or with data, 4-tuples (u, v, k, d).
+        default : value, optional (default=None)
+            Value used for edges that don't have the requested attribute.
+            Only relevant if data is not True or False.
+
+        Returns
+        -------
+        in_edges : InMultiEdgeView or InMultiEdgeDataView
+            A view of edge attributes, usually it iterates over (u, v)
+            or (u, v, k) or (u, v, k, d) tuples of edges, but can also be
+            used for attribute lookup as `edges[u, v, k]['foo']`.
+
+        See Also
+        --------
+        edges
+        """
+        return InMultiEdgeView(self)
+
+    @cached_property
+    def degree(self):
+        """A DegreeView for the Graph as G.degree or G.degree().
+
+        The node degree is the number of edges adjacent to the node.
+        The weighted node degree is the sum of the edge weights for
+        edges incident to that node.
+
+        This object provides an iterator for (node, degree) as well as
+        lookup for the degree for a single node.
+
+        Parameters
+        ----------
+        nbunch : single node, container, or all nodes (default= all nodes)
+            The view will only report edges incident to these nodes.
+
+        weight : string or None, optional (default=None)
+           The name of an edge attribute that holds the numerical value used
+           as a weight.  If None, then each edge has weight 1.
+           The degree is the sum of the edge weights adjacent to the node.
+
+        Returns
+        -------
+        DiMultiDegreeView or int
+            If multiple nodes are requested (the default), returns a `DiMultiDegreeView`
+            mapping nodes to their degree.
+            If a single node is requested, returns the degree of the node as an integer.
+
+        See Also
+        --------
+        out_degree, in_degree
+
+        Examples
+        --------
+        >>> G = nx.MultiDiGraph()
+        >>> nx.add_path(G, [0, 1, 2, 3])
+        >>> G.degree(0)  # node 0 with degree 1
+        1
+        >>> list(G.degree([0, 1, 2]))
+        [(0, 1), (1, 2), (2, 2)]
+        >>> G.add_edge(0, 1)  # parallel edge
+        1
+        >>> list(G.degree([0, 1, 2]))  # parallel edges are counted
+        [(0, 2), (1, 3), (2, 2)]
+
+        """
+        return DiMultiDegreeView(self)
+
+    @cached_property
+    def in_degree(self):
+        """A DegreeView for (node, in_degree) or in_degree for single node.
+
+        The node in-degree is the number of edges pointing into the node.
+        The weighted node degree is the sum of the edge weights for
+        edges incident to that node.
+
+        This object provides an iterator for (node, degree) as well as
+        lookup for the degree for a single node.
+
+        Parameters
+        ----------
+        nbunch : single node, container, or all nodes (default= all nodes)
+            The view will only report edges incident to these nodes.
+
+        weight : string or None, optional (default=None)
+           The edge attribute that holds the numerical value used
+           as a weight.  If None, then each edge has weight 1.
+           The degree is the sum of the edge weights adjacent to the node.
+
+        Returns
+        -------
+        If a single node is requested
+        deg : int
+            Degree of the node
+
+        OR if multiple nodes are requested
+        nd_iter : iterator
+            The iterator returns two-tuples of (node, in-degree).
+
+        See Also
+        --------
+        degree, out_degree
+
+        Examples
+        --------
+        >>> G = nx.MultiDiGraph()
+        >>> nx.add_path(G, [0, 1, 2, 3])
+        >>> G.in_degree(0)  # node 0 with degree 0
+        0
+        >>> list(G.in_degree([0, 1, 2]))
+        [(0, 0), (1, 1), (2, 1)]
+        >>> G.add_edge(0, 1)  # parallel edge
+        1
+        >>> list(G.in_degree([0, 1, 2]))  # parallel edges counted
+        [(0, 0), (1, 2), (2, 1)]
+
+        """
+        return InMultiDegreeView(self)
+
+    @cached_property
+    def out_degree(self):
+        """Returns an iterator for (node, out-degree) or out-degree for single node.
+
+        out_degree(self, nbunch=None, weight=None)
+
+        The node out-degree is the number of edges pointing out of the node.
+        This function returns the out-degree for a single node or an iterator
+        for a bunch of nodes or if nothing is passed as argument.
+
+        Parameters
+        ----------
+        nbunch : single node, container, or all nodes (default= all nodes)
+            The view will only report edges incident to these nodes.
+
+        weight : string or None, optional (default=None)
+           The edge attribute that holds the numerical value used
+           as a weight.  If None, then each edge has weight 1.
+           The degree is the sum of the edge weights.
+
+        Returns
+        -------
+        If a single node is requested
+        deg : int
+            Degree of the node
+
+        OR if multiple nodes are requested
+        nd_iter : iterator
+            The iterator returns two-tuples of (node, out-degree).
+
+        See Also
+        --------
+        degree, in_degree
+
+        Examples
+        --------
+        >>> G = nx.MultiDiGraph()
+        >>> nx.add_path(G, [0, 1, 2, 3])
+        >>> G.out_degree(0)  # node 0 with degree 1
+        1
+        >>> list(G.out_degree([0, 1, 2]))
+        [(0, 1), (1, 1), (2, 1)]
+        >>> G.add_edge(0, 1)  # parallel edge
+        1
+        >>> list(G.out_degree([0, 1, 2]))  # counts parallel edges
+        [(0, 2), (1, 1), (2, 1)]
+
+        """
+        return OutMultiDegreeView(self)
+
+    def is_multigraph(self):
+        """Returns True if graph is a multigraph, False otherwise."""
+        return True
+
+    def is_directed(self):
+        """Returns True if graph is directed, False otherwise."""
+        return True
+
+    def to_undirected(self, reciprocal=False, as_view=False):
+        """Returns an undirected representation of the digraph.
+
+        Parameters
+        ----------
+        reciprocal : bool (optional)
+          If True only keep edges that appear in both directions
+          in the original digraph.
+        as_view : bool (optional, default=False)
+          If True return an undirected view of the original directed graph.
+
+        Returns
+        -------
+        G : MultiGraph
+            An undirected graph with the same name and nodes and
+            with edge (u, v, data) if either (u, v, data) or (v, u, data)
+            is in the digraph.  If both edges exist in digraph and
+            their edge data is different, only one edge is created
+            with an arbitrary choice of which edge data to use.
+            You must check and correct for this manually if desired.
+
+        See Also
+        --------
+        MultiGraph, copy, add_edge, add_edges_from
+
+        Notes
+        -----
+        This returns a "deepcopy" of the edge, node, and
+        graph attributes which attempts to completely copy
+        all of the data and references.
+
+        This is in contrast to the similar D=MultiDiGraph(G) which
+        returns a shallow copy of the data.
+
+        See the Python copy module for more information on shallow
+        and deep copies, https://docs.python.org/3/library/copy.html.
+
+        Warning: If you have subclassed MultiDiGraph to use dict-like
+        objects in the data structure, those changes do not transfer
+        to the MultiGraph created by this method.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(2)  # or MultiGraph, etc
+        >>> H = G.to_directed()
+        >>> list(H.edges)
+        [(0, 1), (1, 0)]
+        >>> G2 = H.to_undirected()
+        >>> list(G2.edges)
+        [(0, 1)]
+        """
+        graph_class = self.to_undirected_class()
+        if as_view is True:
+            return nx.graphviews.generic_graph_view(self, graph_class)
+        # deepcopy when not a view
+        G = graph_class()
+        G.graph.update(deepcopy(self.graph))
+        G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
+        if reciprocal is True:
+            G.add_edges_from(
+                (u, v, key, deepcopy(data))
+                for u, nbrs in self._adj.items()
+                for v, keydict in nbrs.items()
+                for key, data in keydict.items()
+                if v in self._pred[u] and key in self._pred[u][v]
+            )
+        else:
+            G.add_edges_from(
+                (u, v, key, deepcopy(data))
+                for u, nbrs in self._adj.items()
+                for v, keydict in nbrs.items()
+                for key, data in keydict.items()
+            )
+        return G
+
+    def reverse(self, copy=True):
+        """Returns the reverse of the graph.
+
+        The reverse is a graph with the same nodes and edges
+        but with the directions of the edges reversed.
+
+        Parameters
+        ----------
+        copy : bool optional (default=True)
+            If True, return a new DiGraph holding the reversed edges.
+            If False, the reverse graph is created using a view of
+            the original graph.
+        """
+        if copy:
+            H = self.__class__()
+            H.graph.update(deepcopy(self.graph))
+            H.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
+            H.add_edges_from(
+                (v, u, k, deepcopy(d))
+                for u, v, k, d in self.edges(keys=True, data=True)
+            )
+            return H
+        return nx.reverse_view(self)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/multigraph.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/multigraph.py
new file mode 100644
index 0000000000000000000000000000000000000000..a942f2e04ccea8a877e40d9b03cd8484844cb147
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/multigraph.py
@@ -0,0 +1,1294 @@
+"""Base class for MultiGraph."""
+
+from copy import deepcopy
+from functools import cached_property
+
+import networkx as nx
+from networkx import NetworkXError, convert
+from networkx.classes.coreviews import MultiAdjacencyView
+from networkx.classes.graph import Graph
+from networkx.classes.reportviews import MultiDegreeView, MultiEdgeView
+
+__all__ = ["MultiGraph"]
+
+
+class MultiGraph(Graph):
+    """
+    An undirected graph class that can store multiedges.
+
+    Multiedges are multiple edges between two nodes.  Each edge
+    can hold optional data or attributes.
+
+    A MultiGraph holds undirected edges.  Self loops are allowed.
+
+    Nodes can be arbitrary (hashable) Python objects with optional
+    key/value attributes. By convention `None` is not used as a node.
+
+    Edges are represented as links between nodes with optional
+    key/value attributes, in a MultiGraph each edge has a key to
+    distinguish between multiple edges that have the same source and
+    destination nodes.
+
+    Parameters
+    ----------
+    incoming_graph_data : input graph (optional, default: None)
+        Data to initialize graph. If None (default) an empty
+        graph is created.  The data can be any format that is supported
+        by the to_networkx_graph() function, currently including edge list,
+        dict of dicts, dict of lists, NetworkX graph, 2D NumPy array,
+        SciPy sparse array, or PyGraphviz graph.
+
+    multigraph_input : bool or None (default None)
+        Note: Only used when `incoming_graph_data` is a dict.
+        If True, `incoming_graph_data` is assumed to be a
+        dict-of-dict-of-dict-of-dict structure keyed by
+        node to neighbor to edge keys to edge data for multi-edges.
+        A NetworkXError is raised if this is not the case.
+        If False, :func:`to_networkx_graph` is used to try to determine
+        the dict's graph data structure as either a dict-of-dict-of-dict
+        keyed by node to neighbor to edge data, or a dict-of-iterable
+        keyed by node to neighbors.
+        If None, the treatment for True is tried, but if it fails,
+        the treatment for False is tried.
+
+    attr : keyword arguments, optional (default= no attributes)
+        Attributes to add to graph as key=value pairs.
+
+    See Also
+    --------
+    Graph
+    DiGraph
+    MultiDiGraph
+
+    Examples
+    --------
+    Create an empty graph structure (a "null graph") with no nodes and
+    no edges.
+
+    >>> G = nx.MultiGraph()
+
+    G can be grown in several ways.
+
+    **Nodes:**
+
+    Add one node at a time:
+
+    >>> G.add_node(1)
+
+    Add the nodes from any container (a list, dict, set or
+    even the lines from a file or the nodes from another graph).
+
+    >>> G.add_nodes_from([2, 3])
+    >>> G.add_nodes_from(range(100, 110))
+    >>> H = nx.path_graph(10)
+    >>> G.add_nodes_from(H)
+
+    In addition to strings and integers any hashable Python object
+    (except None) can represent a node, e.g. a customized node object,
+    or even another Graph.
+
+    >>> G.add_node(H)
+
+    **Edges:**
+
+    G can also be grown by adding edges.
+
+    Add one edge,
+
+    >>> key = G.add_edge(1, 2)
+
+    a list of edges,
+
+    >>> keys = G.add_edges_from([(1, 2), (1, 3)])
+
+    or a collection of edges,
+
+    >>> keys = G.add_edges_from(H.edges)
+
+    If some edges connect nodes not yet in the graph, the nodes
+    are added automatically.  If an edge already exists, an additional
+    edge is created and stored using a key to identify the edge.
+    By default the key is the lowest unused integer.
+
+    >>> keys = G.add_edges_from([(4, 5, {"route": 28}), (4, 5, {"route": 37})])
+    >>> G[4]
+    AdjacencyView({3: {0: {}}, 5: {0: {}, 1: {'route': 28}, 2: {'route': 37}}})
+
+    **Attributes:**
+
+    Each graph, node, and edge can hold key/value attribute pairs
+    in an associated attribute dictionary (the keys must be hashable).
+    By default these are empty, but can be added or changed using
+    add_edge, add_node or direct manipulation of the attribute
+    dictionaries named graph, node and edge respectively.
+
+    >>> G = nx.MultiGraph(day="Friday")
+    >>> G.graph
+    {'day': 'Friday'}
+
+    Add node attributes using add_node(), add_nodes_from() or G.nodes
+
+    >>> G.add_node(1, time="5pm")
+    >>> G.add_nodes_from([3], time="2pm")
+    >>> G.nodes[1]
+    {'time': '5pm'}
+    >>> G.nodes[1]["room"] = 714
+    >>> del G.nodes[1]["room"]  # remove attribute
+    >>> list(G.nodes(data=True))
+    [(1, {'time': '5pm'}), (3, {'time': '2pm'})]
+
+    Add edge attributes using add_edge(), add_edges_from(), subscript
+    notation, or G.edges.
+
+    >>> key = G.add_edge(1, 2, weight=4.7)
+    >>> keys = G.add_edges_from([(3, 4), (4, 5)], color="red")
+    >>> keys = G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
+    >>> G[1][2][0]["weight"] = 4.7
+    >>> G.edges[1, 2, 0]["weight"] = 4
+
+    Warning: we protect the graph data structure by making `G.edges[1,
+    2, 0]` a read-only dict-like structure. However, you can assign to
+    attributes in e.g. `G.edges[1, 2, 0]`. Thus, use 2 sets of brackets
+    to add/change data attributes: `G.edges[1, 2, 0]['weight'] = 4`.
+
+    **Shortcuts:**
+
+    Many common graph features allow python syntax to speed reporting.
+
+    >>> 1 in G  # check if node in graph
+    True
+    >>> [n for n in G if n < 3]  # iterate through nodes
+    [1, 2]
+    >>> len(G)  # number of nodes in graph
+    5
+    >>> G[1]  # adjacency dict-like view mapping neighbor -> edge key -> edge attributes
+    AdjacencyView({2: {0: {'weight': 4}, 1: {'color': 'blue'}}})
+
+    Often the best way to traverse all edges of a graph is via the neighbors.
+    The neighbors are reported as an adjacency-dict `G.adj` or `G.adjacency()`.
+
+    >>> for n, nbrsdict in G.adjacency():
+    ...     for nbr, keydict in nbrsdict.items():
+    ...         for key, eattr in keydict.items():
+    ...             if "weight" in eattr:
+    ...                 # Do something useful with the edges
+    ...                 pass
+
+    But the edges() method is often more convenient:
+
+    >>> for u, v, keys, weight in G.edges(data="weight", keys=True):
+    ...     if weight is not None:
+    ...         # Do something useful with the edges
+    ...         pass
+
+    **Reporting:**
+
+    Simple graph information is obtained using methods and object-attributes.
+    Reporting usually provides views instead of containers to reduce memory
+    usage. The views update as the graph is updated similarly to dict-views.
+    The objects `nodes`, `edges` and `adj` provide access to data attributes
+    via lookup (e.g. `nodes[n]`, `edges[u, v, k]`, `adj[u][v]`) and iteration
+    (e.g. `nodes.items()`, `nodes.data('color')`,
+    `nodes.data('color', default='blue')` and similarly for `edges`)
+    Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
+
+    For details on these and other miscellaneous methods, see below.
+
+    **Subclasses (Advanced):**
+
+    The MultiGraph class uses a dict-of-dict-of-dict-of-dict data structure.
+    The outer dict (node_dict) holds adjacency information keyed by node.
+    The next dict (adjlist_dict) represents the adjacency information
+    and holds edge_key dicts keyed by neighbor. The edge_key dict holds
+    each edge_attr dict keyed by edge key. The inner dict
+    (edge_attr_dict) represents the edge data and holds edge attribute
+    values keyed by attribute names.
+
+    Each of these four dicts in the dict-of-dict-of-dict-of-dict
+    structure can be replaced by a user defined dict-like object.
+    In general, the dict-like features should be maintained but
+    extra features can be added. To replace one of the dicts create
+    a new graph class by changing the class(!) variable holding the
+    factory for that dict-like structure. The variable names are
+    node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,
+    adjlist_outer_dict_factory, edge_key_dict_factory, edge_attr_dict_factory
+    and graph_attr_dict_factory.
+
+    node_dict_factory : function, (default: dict)
+        Factory function to be used to create the dict containing node
+        attributes, keyed by node id.
+        It should require no arguments and return a dict-like object
+
+    node_attr_dict_factory: function, (default: dict)
+        Factory function to be used to create the node attribute
+        dict which holds attribute values keyed by attribute name.
+        It should require no arguments and return a dict-like object
+
+    adjlist_outer_dict_factory : function, (default: dict)
+        Factory function to be used to create the outer-most dict
+        in the data structure that holds adjacency info keyed by node.
+        It should require no arguments and return a dict-like object.
+
+    adjlist_inner_dict_factory : function, (default: dict)
+        Factory function to be used to create the adjacency list
+        dict which holds multiedge key dicts keyed by neighbor.
+        It should require no arguments and return a dict-like object.
+
+    edge_key_dict_factory : function, (default: dict)
+        Factory function to be used to create the edge key dict
+        which holds edge data keyed by edge key.
+        It should require no arguments and return a dict-like object.
+
+    edge_attr_dict_factory : function, (default: dict)
+        Factory function to be used to create the edge attribute
+        dict which holds attribute values keyed by attribute name.
+        It should require no arguments and return a dict-like object.
+
+    graph_attr_dict_factory : function, (default: dict)
+        Factory function to be used to create the graph attribute
+        dict which holds attribute values keyed by attribute name.
+        It should require no arguments and return a dict-like object.
+
+    Typically, if your extension doesn't impact the data structure all
+    methods will inherited without issue except: `to_directed/to_undirected`.
+    By default these methods create a DiGraph/Graph class and you probably
+    want them to create your extension of a DiGraph/Graph. To facilitate
+    this we define two class variables that you can set in your subclass.
+
+    to_directed_class : callable, (default: DiGraph or MultiDiGraph)
+        Class to create a new graph structure in the `to_directed` method.
+        If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
+
+    to_undirected_class : callable, (default: Graph or MultiGraph)
+        Class to create a new graph structure in the `to_undirected` method.
+        If `None`, a NetworkX class (Graph or MultiGraph) is used.
+
+    **Subclassing Example**
+
+    Create a low memory graph class that effectively disallows edge
+    attributes by using a single attribute dict for all edges.
+    This reduces the memory used, but you lose edge attributes.
+
+    >>> class ThinGraph(nx.Graph):
+    ...     all_edge_dict = {"weight": 1}
+    ...
+    ...     def single_edge_dict(self):
+    ...         return self.all_edge_dict
+    ...
+    ...     edge_attr_dict_factory = single_edge_dict
+    >>> G = ThinGraph()
+    >>> G.add_edge(2, 1)
+    >>> G[2][1]
+    {'weight': 1}
+    >>> G.add_edge(2, 2)
+    >>> G[2][1] is G[2][2]
+    True
+    """
+
+    # node_dict_factory = dict    # already assigned in Graph
+    # adjlist_outer_dict_factory = dict
+    # adjlist_inner_dict_factory = dict
+    edge_key_dict_factory = dict
+    # edge_attr_dict_factory = dict
+
+    def to_directed_class(self):
+        """Returns the class to use for empty directed copies.
+
+        If you subclass the base classes, use this to designate
+        what directed class to use for `to_directed()` copies.
+        """
+        return nx.MultiDiGraph
+
+    def to_undirected_class(self):
+        """Returns the class to use for empty undirected copies.
+
+        If you subclass the base classes, use this to designate
+        what directed class to use for `to_directed()` copies.
+        """
+        return MultiGraph
+
+    # This __new__ method just does what Python itself does automatically.
+    # We include it here as part of the dispatchable/backend interface.
+    # If your goal is to understand how the graph classes work, you can ignore
+    # this method, even when subclassing the base classes. If you are subclassing
+    # in order to provide a backend that allows class instantiation, this method
+    # can be overridden to return your own backend graph class.
+    @nx._dispatchable(name="multigraph__new__", graphs=None, returns_graph=True)
+    def __new__(cls, *args, **kwargs):
+        return object.__new__(cls)
+
+    def __init__(self, incoming_graph_data=None, multigraph_input=None, **attr):
+        """Initialize a graph with edges, name, or graph attributes.
+
+        Parameters
+        ----------
+        incoming_graph_data : input graph
+            Data to initialize graph.  If incoming_graph_data=None (default)
+            an empty graph is created.  The data can be an edge list, or any
+            NetworkX graph object.  If the corresponding optional Python
+            packages are installed the data can also be a 2D NumPy array, a
+            SciPy sparse array, or a PyGraphviz graph.
+
+        multigraph_input : bool or None (default None)
+            Note: Only used when `incoming_graph_data` is a dict.
+            If True, `incoming_graph_data` is assumed to be a
+            dict-of-dict-of-dict-of-dict structure keyed by
+            node to neighbor to edge keys to edge data for multi-edges.
+            A NetworkXError is raised if this is not the case.
+            If False, :func:`to_networkx_graph` is used to try to determine
+            the dict's graph data structure as either a dict-of-dict-of-dict
+            keyed by node to neighbor to edge data, or a dict-of-iterable
+            keyed by node to neighbors.
+            If None, the treatment for True is tried, but if it fails,
+            the treatment for False is tried.
+
+        attr : keyword arguments, optional (default= no attributes)
+            Attributes to add to graph as key=value pairs.
+
+        See Also
+        --------
+        convert
+
+        Examples
+        --------
+        >>> G = nx.MultiGraph()
+        >>> G = nx.MultiGraph(name="my graph")
+        >>> e = [(1, 2), (1, 2), (2, 3), (3, 4)]  # list of edges
+        >>> G = nx.MultiGraph(e)
+
+        Arbitrary graph attribute pairs (key=value) may be assigned
+
+        >>> G = nx.MultiGraph(e, day="Friday")
+        >>> G.graph
+        {'day': 'Friday'}
+
+        """
+        attr.pop("backend", None)  # Ignore explicit `backend="networkx"`
+        # multigraph_input can be None/True/False. So check "is not False"
+        if isinstance(incoming_graph_data, dict) and multigraph_input is not False:
+            Graph.__init__(self)
+            try:
+                convert.from_dict_of_dicts(
+                    incoming_graph_data, create_using=self, multigraph_input=True
+                )
+                self.graph.update(attr)
+            except Exception as err:
+                if multigraph_input is True:
+                    raise nx.NetworkXError(
+                        f"converting multigraph_input raised:\n{type(err)}: {err}"
+                    )
+                Graph.__init__(self, incoming_graph_data, **attr)
+        else:
+            Graph.__init__(self, incoming_graph_data, **attr)
+
+    @cached_property
+    def adj(self):
+        """Graph adjacency object holding the neighbors of each node.
+
+        This object is a read-only dict-like structure with node keys
+        and neighbor-dict values.  The neighbor-dict is keyed by neighbor
+        to the edgekey-data-dict.  So `G.adj[3][2][0]['color'] = 'blue'` sets
+        the color of the edge `(3, 2, 0)` to `"blue"`.
+
+        Iterating over G.adj behaves like a dict. Useful idioms include
+        `for nbr, edgesdict in G.adj[n].items():`.
+
+        The neighbor information is also provided by subscripting the graph.
+
+        Examples
+        --------
+        >>> e = [(1, 2), (1, 2), (1, 3), (3, 4)]  # list of edges
+        >>> G = nx.MultiGraph(e)
+        >>> G.edges[1, 2, 0]["weight"] = 3
+        >>> result = set()
+        >>> for edgekey, data in G[1][2].items():
+        ...     result.add(data.get("weight", 1))
+        >>> result
+        {1, 3}
+
+        For directed graphs, `G.adj` holds outgoing (successor) info.
+        """
+        return MultiAdjacencyView(self._adj)
+
+    def new_edge_key(self, u, v):
+        """Returns an unused key for edges between nodes `u` and `v`.
+
+        The nodes `u` and `v` do not need to be already in the graph.
+
+        Notes
+        -----
+        In the standard MultiGraph class the new key is the number of existing
+        edges between `u` and `v` (increased if necessary to ensure unused).
+        The first edge will have key 0, then 1, etc. If an edge is removed
+        further new_edge_keys may not be in this order.
+
+        Parameters
+        ----------
+        u, v : nodes
+
+        Returns
+        -------
+        key : int
+        """
+        try:
+            keydict = self._adj[u][v]
+        except KeyError:
+            return 0
+        key = len(keydict)
+        while key in keydict:
+            key += 1
+        return key
+
+    def add_edge(self, u_for_edge, v_for_edge, key=None, **attr):
+        """Add an edge between u and v.
+
+        The nodes u and v will be automatically added if they are
+        not already in the graph.
+
+        Edge attributes can be specified with keywords or by directly
+        accessing the edge's attribute dictionary. See examples below.
+
+        Parameters
+        ----------
+        u_for_edge, v_for_edge : nodes
+            Nodes can be, for example, strings or numbers.
+            Nodes must be hashable (and not None) Python objects.
+        key : hashable identifier, optional (default=lowest unused integer)
+            Used to distinguish multiedges between a pair of nodes.
+        attr : keyword arguments, optional
+            Edge data (or labels or objects) can be assigned using
+            keyword arguments.
+
+        Returns
+        -------
+        The edge key assigned to the edge.
+
+        See Also
+        --------
+        add_edges_from : add a collection of edges
+
+        Notes
+        -----
+        To replace/update edge data, use the optional key argument
+        to identify a unique edge.  Otherwise a new edge will be created.
+
+        NetworkX algorithms designed for weighted graphs cannot use
+        multigraphs directly because it is not clear how to handle
+        multiedge weights.  Convert to Graph using edge attribute
+        'weight' to enable weighted graph algorithms.
+
+        Default keys are generated using the method `new_edge_key()`.
+        This method can be overridden by subclassing the base class and
+        providing a custom `new_edge_key()` method.
+
+        Examples
+        --------
+        The following each add an additional edge e=(1, 2) to graph G:
+
+        >>> G = nx.MultiGraph()
+        >>> e = (1, 2)
+        >>> ekey = G.add_edge(1, 2)  # explicit two-node form
+        >>> G.add_edge(*e)  # single edge as tuple of two nodes
+        1
+        >>> G.add_edges_from([(1, 2)])  # add edges from iterable container
+        [2]
+
+        Associate data to edges using keywords:
+
+        >>> ekey = G.add_edge(1, 2, weight=3)
+        >>> ekey = G.add_edge(1, 2, key=0, weight=4)  # update data for key=0
+        >>> ekey = G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
+
+        For non-string attribute keys, use subscript notation.
+
+        >>> ekey = G.add_edge(1, 2)
+        >>> G[1][2][0].update({0: 5})
+        >>> G.edges[1, 2, 0].update({0: 5})
+        """
+        u, v = u_for_edge, v_for_edge
+        # add nodes
+        if u not in self._adj:
+            if u is None:
+                raise ValueError("None cannot be a node")
+            self._adj[u] = self.adjlist_inner_dict_factory()
+            self._node[u] = self.node_attr_dict_factory()
+        if v not in self._adj:
+            if v is None:
+                raise ValueError("None cannot be a node")
+            self._adj[v] = self.adjlist_inner_dict_factory()
+            self._node[v] = self.node_attr_dict_factory()
+        if key is None:
+            key = self.new_edge_key(u, v)
+        if v in self._adj[u]:
+            keydict = self._adj[u][v]
+            datadict = keydict.get(key, self.edge_attr_dict_factory())
+            datadict.update(attr)
+            keydict[key] = datadict
+        else:
+            # selfloops work this way without special treatment
+            datadict = self.edge_attr_dict_factory()
+            datadict.update(attr)
+            keydict = self.edge_key_dict_factory()
+            keydict[key] = datadict
+            self._adj[u][v] = keydict
+            self._adj[v][u] = keydict
+        nx._clear_cache(self)
+        return key
+
+    def add_edges_from(self, ebunch_to_add, **attr):
+        """Add all the edges in ebunch_to_add.
+
+        Parameters
+        ----------
+        ebunch_to_add : container of edges
+            Each edge given in the container will be added to the
+            graph. The edges can be:
+
+                - 2-tuples (u, v) or
+                - 3-tuples (u, v, d) for an edge data dict d, or
+                - 3-tuples (u, v, k) for not iterable key k, or
+                - 4-tuples (u, v, k, d) for an edge with data and key k
+
+        attr : keyword arguments, optional
+            Edge data (or labels or objects) can be assigned using
+            keyword arguments.
+
+        Returns
+        -------
+        A list of edge keys assigned to the edges in `ebunch`.
+
+        See Also
+        --------
+        add_edge : add a single edge
+        add_weighted_edges_from : convenient way to add weighted edges
+
+        Notes
+        -----
+        Adding the same edge twice has no effect but any edge data
+        will be updated when each duplicate edge is added.
+
+        Edge attributes specified in an ebunch take precedence over
+        attributes specified via keyword arguments.
+
+        Default keys are generated using the method ``new_edge_key()``.
+        This method can be overridden by subclassing the base class and
+        providing a custom ``new_edge_key()`` method.
+
+        When adding edges from an iterator over the graph you are changing,
+        a `RuntimeError` can be raised with message:
+        `RuntimeError: dictionary changed size during iteration`. This
+        happens when the graph's underlying dictionary is modified during
+        iteration. To avoid this error, evaluate the iterator into a separate
+        object, e.g. by using `list(iterator_of_edges)`, and pass this
+        object to `G.add_edges_from`.
+
+        Examples
+        --------
+        >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.add_edges_from([(0, 1), (1, 2)])  # using a list of edge tuples
+        >>> e = zip(range(0, 3), range(1, 4))
+        >>> G.add_edges_from(e)  # Add the path graph 0-1-2-3
+
+        Associate data to edges
+
+        >>> G.add_edges_from([(1, 2), (2, 3)], weight=3)
+        >>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
+
+        Evaluate an iterator over a graph if using it to modify the same graph
+
+        >>> G = nx.MultiGraph([(1, 2), (2, 3), (3, 4)])
+        >>> # Grow graph by one new node, adding edges to all existing nodes.
+        >>> # wrong way - will raise RuntimeError
+        >>> # G.add_edges_from(((5, n) for n in G.nodes))
+        >>> # right way - note that there will be no self-edge for node 5
+        >>> assigned_keys = G.add_edges_from(list((5, n) for n in G.nodes))
+        """
+        keylist = []
+        for e in ebunch_to_add:
+            ne = len(e)
+            if ne == 4:
+                u, v, key, dd = e
+            elif ne == 3:
+                u, v, dd = e
+                key = None
+            elif ne == 2:
+                u, v = e
+                dd = {}
+                key = None
+            else:
+                msg = f"Edge tuple {e} must be a 2-tuple, 3-tuple or 4-tuple."
+                raise NetworkXError(msg)
+            ddd = {}
+            ddd.update(attr)
+            try:
+                ddd.update(dd)
+            except (TypeError, ValueError):
+                if ne != 3:
+                    raise
+                key = dd  # ne == 3 with 3rd value not dict, must be a key
+            key = self.add_edge(u, v, key)
+            self[u][v][key].update(ddd)
+            keylist.append(key)
+        nx._clear_cache(self)
+        return keylist
+
+    def remove_edge(self, u, v, key=None):
+        """Remove an edge between u and v.
+
+        Parameters
+        ----------
+        u, v : nodes
+            Remove an edge between nodes u and v.
+        key : hashable identifier, optional (default=None)
+            Used to distinguish multiple edges between a pair of nodes.
+            If None, remove a single edge between u and v. If there are
+            multiple edges, removes the last edge added in terms of
+            insertion order.
+
+        Raises
+        ------
+        NetworkXError
+            If there is not an edge between u and v, or
+            if there is no edge with the specified key.
+
+        See Also
+        --------
+        remove_edges_from : remove a collection of edges
+
+        Examples
+        --------
+        >>> G = nx.MultiGraph()
+        >>> nx.add_path(G, [0, 1, 2, 3])
+        >>> G.remove_edge(0, 1)
+        >>> e = (1, 2)
+        >>> G.remove_edge(*e)  # unpacks e from an edge tuple
+
+        For multiple edges
+
+        >>> G = nx.MultiGraph()  # or MultiDiGraph, etc
+        >>> G.add_edges_from([(1, 2), (1, 2), (1, 2)])  # key_list returned
+        [0, 1, 2]
+
+        When ``key=None`` (the default), edges are removed in the opposite
+        order that they were added:
+
+        >>> G.remove_edge(1, 2)
+        >>> G.edges(keys=True)
+        MultiEdgeView([(1, 2, 0), (1, 2, 1)])
+        >>> G.remove_edge(2, 1)  # edges are not directed
+        >>> G.edges(keys=True)
+        MultiEdgeView([(1, 2, 0)])
+
+        For edges with keys
+
+        >>> G = nx.MultiGraph()
+        >>> G.add_edge(1, 2, key="first")
+        'first'
+        >>> G.add_edge(1, 2, key="second")
+        'second'
+        >>> G.remove_edge(1, 2, key="first")
+        >>> G.edges(keys=True)
+        MultiEdgeView([(1, 2, 'second')])
+
+        """
+        try:
+            d = self._adj[u][v]
+        except KeyError as err:
+            raise NetworkXError(f"The edge {u}-{v} is not in the graph.") from err
+        # remove the edge with specified data
+        if key is None:
+            d.popitem()
+        else:
+            try:
+                del d[key]
+            except KeyError as err:
+                msg = f"The edge {u}-{v} with key {key} is not in the graph."
+                raise NetworkXError(msg) from err
+        if len(d) == 0:
+            # remove the key entries if last edge
+            del self._adj[u][v]
+            if u != v:  # check for selfloop
+                del self._adj[v][u]
+        nx._clear_cache(self)
+
+    def remove_edges_from(self, ebunch):
+        """Remove all edges specified in ebunch.
+
+        Parameters
+        ----------
+        ebunch: list or container of edge tuples
+            Each edge given in the list or container will be removed
+            from the graph. The edges can be:
+
+                - 2-tuples (u, v) A single edge between u and v is removed.
+                - 3-tuples (u, v, key) The edge identified by key is removed.
+                - 4-tuples (u, v, key, data) where data is ignored.
+
+        See Also
+        --------
+        remove_edge : remove a single edge
+
+        Notes
+        -----
+        Will fail silently if an edge in ebunch is not in the graph.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> ebunch = [(1, 2), (2, 3)]
+        >>> G.remove_edges_from(ebunch)
+
+        Removing multiple copies of edges
+
+        >>> G = nx.MultiGraph()
+        >>> keys = G.add_edges_from([(1, 2), (1, 2), (1, 2)])
+        >>> G.remove_edges_from([(1, 2), (2, 1)])  # edges aren't directed
+        >>> list(G.edges())
+        [(1, 2)]
+        >>> G.remove_edges_from([(1, 2), (1, 2)])  # silently ignore extra copy
+        >>> list(G.edges)  # now empty graph
+        []
+
+        When the edge is a 2-tuple ``(u, v)`` but there are multiple edges between
+        u and v in the graph, the most recent edge (in terms of insertion
+        order) is removed.
+
+        >>> G = nx.MultiGraph()
+        >>> for key in ("x", "y", "a"):
+        ...     k = G.add_edge(0, 1, key=key)
+        >>> G.edges(keys=True)
+        MultiEdgeView([(0, 1, 'x'), (0, 1, 'y'), (0, 1, 'a')])
+        >>> G.remove_edges_from([(0, 1)])
+        >>> G.edges(keys=True)
+        MultiEdgeView([(0, 1, 'x'), (0, 1, 'y')])
+
+        """
+        for e in ebunch:
+            try:
+                self.remove_edge(*e[:3])
+            except NetworkXError:
+                pass
+        nx._clear_cache(self)
+
+    def has_edge(self, u, v, key=None):
+        """Returns True if the graph has an edge between nodes u and v.
+
+        This is the same as `v in G[u] or key in G[u][v]`
+        without KeyError exceptions.
+
+        Parameters
+        ----------
+        u, v : nodes
+            Nodes can be, for example, strings or numbers.
+
+        key : hashable identifier, optional (default=None)
+            If specified return True only if the edge with
+            key is found.
+
+        Returns
+        -------
+        edge_ind : bool
+            True if edge is in the graph, False otherwise.
+
+        Examples
+        --------
+        Can be called either using two nodes u, v, an edge tuple (u, v),
+        or an edge tuple (u, v, key).
+
+        >>> G = nx.MultiGraph()  # or MultiDiGraph
+        >>> nx.add_path(G, [0, 1, 2, 3])
+        >>> G.has_edge(0, 1)  # using two nodes
+        True
+        >>> e = (0, 1)
+        >>> G.has_edge(*e)  #  e is a 2-tuple (u, v)
+        True
+        >>> G.add_edge(0, 1, key="a")
+        'a'
+        >>> G.has_edge(0, 1, key="a")  # specify key
+        True
+        >>> G.has_edge(1, 0, key="a")  # edges aren't directed
+        True
+        >>> e = (0, 1, "a")
+        >>> G.has_edge(*e)  # e is a 3-tuple (u, v, 'a')
+        True
+
+        The following syntax are equivalent:
+
+        >>> G.has_edge(0, 1)
+        True
+        >>> 1 in G[0]  # though this gives :exc:`KeyError` if 0 not in G
+        True
+        >>> 0 in G[1]  # other order; also gives :exc:`KeyError` if 0 not in G
+        True
+
+        """
+        try:
+            if key is None:
+                return v in self._adj[u]
+            else:
+                return key in self._adj[u][v]
+        except KeyError:
+            return False
+
+    @cached_property
+    def edges(self):
+        """Returns an iterator over the edges.
+
+        edges(self, nbunch=None, data=False, keys=False, default=None)
+
+        The MultiEdgeView provides set-like operations on the edge-tuples
+        as well as edge attribute lookup. When called, it also provides
+        an EdgeDataView object which allows control of access to edge
+        attributes (but does not provide set-like operations).
+        Hence, ``G.edges[u, v, k]['color']`` provides the value of the color
+        attribute for the edge from ``u`` to ``v`` with key ``k`` while
+        ``for (u, v, k, c) in G.edges(data='color', keys=True, default="red"):``
+        iterates through all the edges yielding the color attribute with
+        default `'red'` if no color attribute exists.
+
+        Edges are returned as tuples with optional data and keys
+        in the order (node, neighbor, key, data). If ``keys=True`` is not
+        provided, the tuples will just be (node, neighbor, data), but
+        multiple tuples with the same node and neighbor will be generated
+        when multiple edges exist between two nodes.
+
+        Parameters
+        ----------
+        nbunch : single node, container, or all nodes (default= all nodes)
+            The view will only report edges from these nodes.
+        data : string or bool, optional (default=False)
+            The edge attribute returned in 3-tuple (u, v, ddict[data]).
+            If True, return edge attribute dict in 3-tuple (u, v, ddict).
+            If False, return 2-tuple (u, v).
+        keys : bool, optional (default=False)
+            If True, return edge keys with each edge, creating (u, v, k)
+            tuples or (u, v, k, d) tuples if data is also requested.
+        default : value, optional (default=None)
+            Value used for edges that don't have the requested attribute.
+            Only relevant if data is not True or False.
+
+        Returns
+        -------
+        edges : MultiEdgeView
+            A view of edge attributes, usually it iterates over (u, v)
+            (u, v, k) or (u, v, k, d) tuples of edges, but can also be
+            used for attribute lookup as ``edges[u, v, k]['foo']``.
+
+        Notes
+        -----
+        Nodes in nbunch that are not in the graph will be (quietly) ignored.
+        For directed graphs this returns the out-edges.
+
+        Examples
+        --------
+        >>> G = nx.MultiGraph()
+        >>> nx.add_path(G, [0, 1, 2])
+        >>> key = G.add_edge(2, 3, weight=5)
+        >>> key2 = G.add_edge(2, 1, weight=2)  # multi-edge
+        >>> [e for e in G.edges()]
+        [(0, 1), (1, 2), (1, 2), (2, 3)]
+        >>> G.edges.data()  # default data is {} (empty dict)
+        MultiEdgeDataView([(0, 1, {}), (1, 2, {}), (1, 2, {'weight': 2}), (2, 3, {'weight': 5})])
+        >>> G.edges.data("weight", default=1)
+        MultiEdgeDataView([(0, 1, 1), (1, 2, 1), (1, 2, 2), (2, 3, 5)])
+        >>> G.edges(keys=True)  # default keys are integers
+        MultiEdgeView([(0, 1, 0), (1, 2, 0), (1, 2, 1), (2, 3, 0)])
+        >>> G.edges.data(keys=True)
+        MultiEdgeDataView([(0, 1, 0, {}), (1, 2, 0, {}), (1, 2, 1, {'weight': 2}), (2, 3, 0, {'weight': 5})])
+        >>> G.edges.data("weight", default=1, keys=True)
+        MultiEdgeDataView([(0, 1, 0, 1), (1, 2, 0, 1), (1, 2, 1, 2), (2, 3, 0, 5)])
+        >>> G.edges([0, 3])  # Note ordering of tuples from listed sources
+        MultiEdgeDataView([(0, 1), (3, 2)])
+        >>> G.edges([0, 3, 2, 1])  # Note ordering of tuples
+        MultiEdgeDataView([(0, 1), (3, 2), (2, 1), (2, 1)])
+        >>> G.edges(0)
+        MultiEdgeDataView([(0, 1)])
+        """
+        return MultiEdgeView(self)
+
+    def get_edge_data(self, u, v, key=None, default=None):
+        """Returns the attribute dictionary associated with edge (u, v,
+        key).
+
+        If a key is not provided, returns a dictionary mapping edge keys
+        to attribute dictionaries for each edge between u and v.
+
+        This is identical to `G[u][v][key]` except the default is returned
+        instead of an exception is the edge doesn't exist.
+
+        Parameters
+        ----------
+        u, v : nodes
+
+        default :  any Python object (default=None)
+            Value to return if the specific edge (u, v, key) is not
+            found, OR if there are no edges between u and v and no key
+            is specified.
+
+        key : hashable identifier, optional (default=None)
+            Return data only for the edge with specified key, as an
+            attribute dictionary (rather than a dictionary mapping keys
+            to attribute dictionaries).
+
+        Returns
+        -------
+        edge_dict : dictionary
+            The edge attribute dictionary, OR a dictionary mapping edge
+            keys to attribute dictionaries for each of those edges if no
+            specific key is provided (even if there's only one edge
+            between u and v).
+
+        Examples
+        --------
+        >>> G = nx.MultiGraph()  # or MultiDiGraph
+        >>> key = G.add_edge(0, 1, key="a", weight=7)
+        >>> G[0][1]["a"]  # key='a'
+        {'weight': 7}
+        >>> G.edges[0, 1, "a"]  # key='a'
+        {'weight': 7}
+
+        Warning: we protect the graph data structure by making
+        `G.edges` and `G[1][2]` read-only dict-like structures.
+        However, you can assign values to attributes in e.g.
+        `G.edges[1, 2, 'a']` or `G[1][2]['a']` using an additional
+        bracket as shown next. You need to specify all edge info
+        to assign to the edge data associated with an edge.
+
+        >>> G[0][1]["a"]["weight"] = 10
+        >>> G.edges[0, 1, "a"]["weight"] = 10
+        >>> G[0][1]["a"]["weight"]
+        10
+        >>> G.edges[1, 0, "a"]["weight"]
+        10
+
+        >>> G = nx.MultiGraph()  # or MultiDiGraph
+        >>> nx.add_path(G, [0, 1, 2, 3])
+        >>> G.edges[0, 1, 0]["weight"] = 5
+        >>> G.get_edge_data(0, 1)
+        {0: {'weight': 5}}
+        >>> e = (0, 1)
+        >>> G.get_edge_data(*e)  # tuple form
+        {0: {'weight': 5}}
+        >>> G.get_edge_data(3, 0)  # edge not in graph, returns None
+        >>> G.get_edge_data(3, 0, default=0)  # edge not in graph, return default
+        0
+        >>> G.get_edge_data(1, 0, 0)  # specific key gives back
+        {'weight': 5}
+        """
+        try:
+            if key is None:
+                return self._adj[u][v]
+            else:
+                return self._adj[u][v][key]
+        except KeyError:
+            return default
+
+    @cached_property
+    def degree(self):
+        """A DegreeView for the Graph as G.degree or G.degree().
+
+        The node degree is the number of edges adjacent to the node.
+        The weighted node degree is the sum of the edge weights for
+        edges incident to that node.
+
+        This object provides an iterator for (node, degree) as well as
+        lookup for the degree for a single node.
+
+        Parameters
+        ----------
+        nbunch : single node, container, or all nodes (default= all nodes)
+            The view will only report edges incident to these nodes.
+
+        weight : string or None, optional (default=None)
+           The name of an edge attribute that holds the numerical value used
+           as a weight.  If None, then each edge has weight 1.
+           The degree is the sum of the edge weights adjacent to the node.
+
+        Returns
+        -------
+        MultiDegreeView or int
+            If multiple nodes are requested (the default), returns a `MultiDegreeView`
+            mapping nodes to their degree.
+            If a single node is requested, returns the degree of the node as an integer.
+
+        Examples
+        --------
+        >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> nx.add_path(G, [0, 1, 2, 3])
+        >>> G.degree(0)  # node 0 with degree 1
+        1
+        >>> list(G.degree([0, 1]))
+        [(0, 1), (1, 2)]
+
+        """
+        return MultiDegreeView(self)
+
+    def is_multigraph(self):
+        """Returns True if graph is a multigraph, False otherwise."""
+        return True
+
+    def is_directed(self):
+        """Returns True if graph is directed, False otherwise."""
+        return False
+
+    def copy(self, as_view=False):
+        """Returns a copy of the graph.
+
+        The copy method by default returns an independent shallow copy
+        of the graph and attributes. That is, if an attribute is a
+        container, that container is shared by the original an the copy.
+        Use Python's `copy.deepcopy` for new containers.
+
+        If `as_view` is True then a view is returned instead of a copy.
+
+        Notes
+        -----
+        All copies reproduce the graph structure, but data attributes
+        may be handled in different ways. There are four types of copies
+        of a graph that people might want.
+
+        Deepcopy -- A "deepcopy" copies the graph structure as well as
+        all data attributes and any objects they might contain.
+        The entire graph object is new so that changes in the copy
+        do not affect the original object. (see Python's copy.deepcopy)
+
+        Data Reference (Shallow) -- For a shallow copy the graph structure
+        is copied but the edge, node and graph attribute dicts are
+        references to those in the original graph. This saves
+        time and memory but could cause confusion if you change an attribute
+        in one graph and it changes the attribute in the other.
+        NetworkX does not provide this level of shallow copy.
+
+        Independent Shallow -- This copy creates new independent attribute
+        dicts and then does a shallow copy of the attributes. That is, any
+        attributes that are containers are shared between the new graph
+        and the original. This is exactly what `dict.copy()` provides.
+        You can obtain this style copy using:
+
+            >>> G = nx.path_graph(5)
+            >>> H = G.copy()
+            >>> H = G.copy(as_view=False)
+            >>> H = nx.Graph(G)
+            >>> H = G.__class__(G)
+
+        Fresh Data -- For fresh data, the graph structure is copied while
+        new empty data attribute dicts are created. The resulting graph
+        is independent of the original and it has no edge, node or graph
+        attributes. Fresh copies are not enabled. Instead use:
+
+            >>> H = G.__class__()
+            >>> H.add_nodes_from(G)
+            >>> H.add_edges_from(G.edges)
+
+        View -- Inspired by dict-views, graph-views act like read-only
+        versions of the original graph, providing a copy of the original
+        structure without requiring any memory for copying the information.
+
+        See the Python copy module for more information on shallow
+        and deep copies, https://docs.python.org/3/library/copy.html.
+
+        Parameters
+        ----------
+        as_view : bool, optional (default=False)
+            If True, the returned graph-view provides a read-only view
+            of the original graph without actually copying any data.
+
+        Returns
+        -------
+        G : Graph
+            A copy of the graph.
+
+        See Also
+        --------
+        to_directed: return a directed copy of the graph.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> H = G.copy()
+
+        """
+        if as_view is True:
+            return nx.graphviews.generic_graph_view(self)
+        G = self.__class__()
+        G.graph.update(self.graph)
+        G.add_nodes_from((n, d.copy()) for n, d in self._node.items())
+        G.add_edges_from(
+            (u, v, key, datadict.copy())
+            for u, nbrs in self._adj.items()
+            for v, keydict in nbrs.items()
+            for key, datadict in keydict.items()
+        )
+        return G
+
+    def to_directed(self, as_view=False):
+        """Returns a directed representation of the graph.
+
+        Returns
+        -------
+        G : MultiDiGraph
+            A directed graph with the same name, same nodes, and with
+            each edge (u, v, k, data) replaced by two directed edges
+            (u, v, k, data) and (v, u, k, data).
+
+        Notes
+        -----
+        This returns a "deepcopy" of the edge, node, and
+        graph attributes which attempts to completely copy
+        all of the data and references.
+
+        This is in contrast to the similar D=MultiDiGraph(G) which
+        returns a shallow copy of the data.
+
+        See the Python copy module for more information on shallow
+        and deep copies, https://docs.python.org/3/library/copy.html.
+
+        Warning: If you have subclassed MultiGraph to use dict-like objects
+        in the data structure, those changes do not transfer to the
+        MultiDiGraph created by this method.
+
+        Examples
+        --------
+        >>> G = nx.MultiGraph()
+        >>> G.add_edge(0, 1)
+        0
+        >>> G.add_edge(0, 1)
+        1
+        >>> H = G.to_directed()
+        >>> list(H.edges)
+        [(0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1)]
+
+        If already directed, return a (deep) copy
+
+        >>> G = nx.MultiDiGraph()
+        >>> G.add_edge(0, 1)
+        0
+        >>> H = G.to_directed()
+        >>> list(H.edges)
+        [(0, 1, 0)]
+        """
+        graph_class = self.to_directed_class()
+        if as_view is True:
+            return nx.graphviews.generic_graph_view(self, graph_class)
+        # deepcopy when not a view
+        G = graph_class()
+        G.graph.update(deepcopy(self.graph))
+        G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
+        G.add_edges_from(
+            (u, v, key, deepcopy(datadict))
+            for u, nbrs in self.adj.items()
+            for v, keydict in nbrs.items()
+            for key, datadict in keydict.items()
+        )
+        return G
+
+    def to_undirected(self, as_view=False):
+        """Returns an undirected copy of the graph.
+
+        Returns
+        -------
+        G : Graph/MultiGraph
+            A deepcopy of the graph.
+
+        See Also
+        --------
+        copy, add_edge, add_edges_from
+
+        Notes
+        -----
+        This returns a "deepcopy" of the edge, node, and
+        graph attributes which attempts to completely copy
+        all of the data and references.
+
+        This is in contrast to the similar `G = nx.MultiGraph(D)`
+        which returns a shallow copy of the data.
+
+        See the Python copy module for more information on shallow
+        and deep copies, https://docs.python.org/3/library/copy.html.
+
+        Warning: If you have subclassed MultiGraph to use dict-like
+        objects in the data structure, those changes do not transfer
+        to the MultiGraph created by this method.
+
+        Examples
+        --------
+        >>> G = nx.MultiGraph([(0, 1), (0, 1), (1, 2)])
+        >>> H = G.to_directed()
+        >>> list(H.edges)
+        [(0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 2, 0), (2, 1, 0)]
+        >>> G2 = H.to_undirected()
+        >>> list(G2.edges)
+        [(0, 1, 0), (0, 1, 1), (1, 2, 0)]
+        """
+        graph_class = self.to_undirected_class()
+        if as_view is True:
+            return nx.graphviews.generic_graph_view(self, graph_class)
+        # deepcopy when not a view
+        G = graph_class()
+        G.graph.update(deepcopy(self.graph))
+        G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
+        G.add_edges_from(
+            (u, v, key, deepcopy(datadict))
+            for u, nbrs in self._adj.items()
+            for v, keydict in nbrs.items()
+            for key, datadict in keydict.items()
+        )
+        return G
+
+    def number_of_edges(self, u=None, v=None):
+        """Returns the number of edges between two nodes.
+
+        Parameters
+        ----------
+        u, v : nodes, optional (Default=all edges)
+            If u and v are specified, return the number of edges between
+            u and v. Otherwise return the total number of all edges.
+
+        Returns
+        -------
+        nedges : int
+            The number of edges in the graph.  If nodes `u` and `v` are
+            specified return the number of edges between those nodes. If
+            the graph is directed, this only returns the number of edges
+            from `u` to `v`.
+
+        See Also
+        --------
+        size
+
+        Examples
+        --------
+        For undirected multigraphs, this method counts the total number
+        of edges in the graph::
+
+            >>> G = nx.MultiGraph()
+            >>> G.add_edges_from([(0, 1), (0, 1), (1, 2)])
+            [0, 1, 0]
+            >>> G.number_of_edges()
+            3
+
+        If you specify two nodes, this counts the total number of edges
+        joining the two nodes::
+
+            >>> G.number_of_edges(0, 1)
+            2
+
+        For directed multigraphs, this method can count the total number
+        of directed edges from `u` to `v`::
+
+            >>> G = nx.MultiDiGraph()
+            >>> G.add_edges_from([(0, 1), (0, 1), (1, 0)])
+            [0, 1, 0]
+            >>> G.number_of_edges(0, 1)
+            2
+            >>> G.number_of_edges(1, 0)
+            1
+
+        """
+        if u is None:
+            return self.size()
+        try:
+            edgedata = self._adj[u][v]
+        except KeyError:
+            return 0  # no such edge
+        return len(edgedata)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/reportviews.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/reportviews.py
new file mode 100644
index 0000000000000000000000000000000000000000..789662de19600ec2a7922db612c525dfb75695ea
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/classes/reportviews.py
@@ -0,0 +1,1447 @@
+"""
+View Classes provide node, edge and degree "views" of a graph.
+
+Views for nodes, edges and degree are provided for all base graph classes.
+A view means a read-only object that is quick to create, automatically
+updated when the graph changes, and provides basic access like `n in V`,
+`for n in V`, `V[n]` and sometimes set operations.
+
+The views are read-only iterable containers that are updated as the
+graph is updated. As with dicts, the graph should not be updated
+while iterating through the view. Views can be iterated multiple times.
+
+Edge and Node views also allow data attribute lookup.
+The resulting attribute dict is writable as `G.edges[3, 4]['color']='red'`
+Degree views allow lookup of degree values for single nodes.
+Weighted degree is supported with the `weight` argument.
+
+NodeView
+========
+
+    `V = G.nodes` (or `V = G.nodes()`) allows `len(V)`, `n in V`, set
+    operations e.g. "G.nodes & H.nodes", and `dd = G.nodes[n]`, where
+    `dd` is the node data dict. Iteration is over the nodes by default.
+
+NodeDataView
+============
+
+    To iterate over (node, data) pairs, use arguments to `G.nodes()`
+    to create a DataView e.g. `DV = G.nodes(data='color', default='red')`.
+    The DataView iterates as `for n, color in DV` and allows
+    `(n, 'red') in DV`. Using `DV = G.nodes(data=True)`, the DataViews
+    use the full datadict in writeable form also allowing contain testing as
+    `(n, {'color': 'red'}) in VD`. DataViews allow set operations when
+    data attributes are hashable.
+
+DegreeView
+==========
+
+    `V = G.degree` allows iteration over (node, degree) pairs as well
+    as lookup: `deg=V[n]`. There are many flavors of DegreeView
+    for In/Out/Directed/Multi. For Directed Graphs, `G.degree`
+    counts both in and out going edges. `G.out_degree` and
+    `G.in_degree` count only specific directions.
+    Weighted degree using edge data attributes is provide via
+    `V = G.degree(weight='attr_name')` where any string with the
+    attribute name can be used. `weight=None` is the default.
+    No set operations are implemented for degrees, use NodeView.
+
+    The argument `nbunch` restricts iteration to nodes in nbunch.
+    The DegreeView can still lookup any node even if nbunch is specified.
+
+EdgeView
+========
+
+    `V = G.edges` or `V = G.edges()` allows iteration over edges as well as
+    `e in V`, set operations and edge data lookup `dd = G.edges[2, 3]`.
+    Iteration is over 2-tuples `(u, v)` for Graph/DiGraph. For multigraphs
+    edges 3-tuples `(u, v, key)` are the default but 2-tuples can be obtained
+    via `V = G.edges(keys=False)`.
+
+    Set operations for directed graphs treat the edges as a set of 2-tuples.
+    For undirected graphs, 2-tuples are not a unique representation of edges.
+    So long as the set being compared to contains unique representations
+    of its edges, the set operations will act as expected. If the other
+    set contains both `(0, 1)` and `(1, 0)` however, the result of set
+    operations may contain both representations of the same edge.
+
+EdgeDataView
+============
+
+    Edge data can be reported using an EdgeDataView typically created
+    by calling an EdgeView: `DV = G.edges(data='weight', default=1)`.
+    The EdgeDataView allows iteration over edge tuples, membership checking
+    but no set operations.
+
+    Iteration depends on `data` and `default` and for multigraph `keys`
+    If `data is False` (the default) then iterate over 2-tuples `(u, v)`.
+    If `data is True` iterate over 3-tuples `(u, v, datadict)`.
+    Otherwise iterate over `(u, v, datadict.get(data, default))`.
+    For Multigraphs, if `keys is True`, replace `u, v` with `u, v, key`
+    to create 3-tuples and 4-tuples.
+
+    The argument `nbunch` restricts edges to those incident to nodes in nbunch.
+"""
+
+from abc import ABC
+from collections.abc import Mapping, Set
+
+import networkx as nx
+
+__all__ = [
+    "NodeView",
+    "NodeDataView",
+    "EdgeView",
+    "OutEdgeView",
+    "InEdgeView",
+    "EdgeDataView",
+    "OutEdgeDataView",
+    "InEdgeDataView",
+    "MultiEdgeView",
+    "OutMultiEdgeView",
+    "InMultiEdgeView",
+    "MultiEdgeDataView",
+    "OutMultiEdgeDataView",
+    "InMultiEdgeDataView",
+    "DegreeView",
+    "DiDegreeView",
+    "InDegreeView",
+    "OutDegreeView",
+    "MultiDegreeView",
+    "DiMultiDegreeView",
+    "InMultiDegreeView",
+    "OutMultiDegreeView",
+]
+
+
+# NodeViews
+class NodeView(Mapping, Set):
+    """A NodeView class to act as G.nodes for a NetworkX Graph
+
+    Set operations act on the nodes without considering data.
+    Iteration is over nodes. Node data can be looked up like a dict.
+    Use NodeDataView to iterate over node data or to specify a data
+    attribute for lookup. NodeDataView is created by calling the NodeView.
+
+    Parameters
+    ----------
+    graph : NetworkX graph-like class
+
+    Examples
+    --------
+    >>> G = nx.path_graph(3)
+    >>> NV = G.nodes()
+    >>> 2 in NV
+    True
+    >>> for n in NV:
+    ...     print(n)
+    0
+    1
+    2
+    >>> assert NV & {1, 2, 3} == {1, 2}
+
+    >>> G.add_node(2, color="blue")
+    >>> NV[2]
+    {'color': 'blue'}
+    >>> G.add_node(8, color="red")
+    >>> NDV = G.nodes(data=True)
+    >>> (2, NV[2]) in NDV
+    True
+    >>> for n, dd in NDV:
+    ...     print((n, dd.get("color", "aqua")))
+    (0, 'aqua')
+    (1, 'aqua')
+    (2, 'blue')
+    (8, 'red')
+    >>> NDV[2] == NV[2]
+    True
+
+    >>> NVdata = G.nodes(data="color", default="aqua")
+    >>> (2, NVdata[2]) in NVdata
+    True
+    >>> for n, dd in NVdata:
+    ...     print((n, dd))
+    (0, 'aqua')
+    (1, 'aqua')
+    (2, 'blue')
+    (8, 'red')
+    >>> NVdata[2] == NV[2]  # NVdata gets 'color', NV gets datadict
+    False
+    """
+
+    __slots__ = ("_nodes",)
+
+    def __getstate__(self):
+        return {"_nodes": self._nodes}
+
+    def __setstate__(self, state):
+        self._nodes = state["_nodes"]
+
+    def __init__(self, graph):
+        self._nodes = graph._node
+
+    # Mapping methods
+    def __len__(self):
+        return len(self._nodes)
+
+    def __iter__(self):
+        return iter(self._nodes)
+
+    def __getitem__(self, n):
+        if isinstance(n, slice):
+            raise nx.NetworkXError(
+                f"{type(self).__name__} does not support slicing, "
+                f"try list(G.nodes)[{n.start}:{n.stop}:{n.step}]"
+            )
+        return self._nodes[n]
+
+    # Set methods
+    def __contains__(self, n):
+        return n in self._nodes
+
+    @classmethod
+    def _from_iterable(cls, it):
+        return set(it)
+
+    # DataView method
+    def __call__(self, data=False, default=None):
+        if data is False:
+            return self
+        return NodeDataView(self._nodes, data, default)
+
+    def data(self, data=True, default=None):
+        """
+        Return a read-only view of node data.
+
+        Parameters
+        ----------
+        data : bool or node data key, default=True
+            If ``data=True`` (the default), return a `NodeDataView` object that
+            maps each node to *all* of its attributes. `data` may also be an
+            arbitrary key, in which case the `NodeDataView` maps each node to
+            the value for the keyed attribute. In this case, if a node does
+            not have the `data` attribute, the `default` value is used.
+        default : object, default=None
+            The value used when a node does not have a specific attribute.
+
+        Returns
+        -------
+        NodeDataView
+            The layout of the returned NodeDataView depends on the value of the
+            `data` parameter.
+
+        Notes
+        -----
+        If ``data=False``, returns a `NodeView` object without data.
+
+        See Also
+        --------
+        NodeDataView
+
+        Examples
+        --------
+        >>> G = nx.Graph()
+        >>> G.add_nodes_from(
+        ...     [
+        ...         (0, {"color": "red", "weight": 10}),
+        ...         (1, {"color": "blue"}),
+        ...         (2, {"color": "yellow", "weight": 2}),
+        ...     ]
+        ... )
+
+        Accessing node data with ``data=True`` (the default) returns a
+        NodeDataView mapping each node to all of its attributes:
+
+        >>> G.nodes.data()
+        NodeDataView({0: {'color': 'red', 'weight': 10}, 1: {'color': 'blue'}, 2: {'color': 'yellow', 'weight': 2}})
+
+        If `data` represents  a key in the node attribute dict, a NodeDataView mapping
+        the nodes to the value for that specific key is returned:
+
+        >>> G.nodes.data("color")
+        NodeDataView({0: 'red', 1: 'blue', 2: 'yellow'}, data='color')
+
+        If a specific key is not found in an attribute dict, the value specified
+        by `default` is returned:
+
+        >>> G.nodes.data("weight", default=-999)
+        NodeDataView({0: 10, 1: -999, 2: 2}, data='weight')
+
+        Note that there is no check that the `data` key is in any of the
+        node attribute dictionaries:
+
+        >>> G.nodes.data("height")
+        NodeDataView({0: None, 1: None, 2: None}, data='height')
+        """
+        if data is False:
+            return self
+        return NodeDataView(self._nodes, data, default)
+
+    def __str__(self):
+        return str(list(self))
+
+    def __repr__(self):
+        return f"{self.__class__.__name__}({tuple(self)})"
+
+
+class NodeDataView(Set):
+    """A DataView class for nodes of a NetworkX Graph
+
+    The main use for this class is to iterate through node-data pairs.
+    The data can be the entire data-dictionary for each node, or it
+    can be a specific attribute (with default) for each node.
+    Set operations are enabled with NodeDataView, but don't work in
+    cases where the data is not hashable. Use with caution.
+    Typically, set operations on nodes use NodeView, not NodeDataView.
+    That is, they use `G.nodes` instead of `G.nodes(data='foo')`.
+
+    Parameters
+    ==========
+    graph : NetworkX graph-like class
+    data : bool or string (default=False)
+    default : object (default=None)
+    """
+
+    __slots__ = ("_nodes", "_data", "_default")
+
+    def __getstate__(self):
+        return {"_nodes": self._nodes, "_data": self._data, "_default": self._default}
+
+    def __setstate__(self, state):
+        self._nodes = state["_nodes"]
+        self._data = state["_data"]
+        self._default = state["_default"]
+
+    def __init__(self, nodedict, data=False, default=None):
+        self._nodes = nodedict
+        self._data = data
+        self._default = default
+
+    @classmethod
+    def _from_iterable(cls, it):
+        try:
+            return set(it)
+        except TypeError as err:
+            if "unhashable" in str(err):
+                msg = " : Could be b/c data=True or your values are unhashable"
+                raise TypeError(str(err) + msg) from err
+            raise
+
+    def __len__(self):
+        return len(self._nodes)
+
+    def __iter__(self):
+        data = self._data
+        if data is False:
+            return iter(self._nodes)
+        if data is True:
+            return iter(self._nodes.items())
+        return (
+            (n, dd[data] if data in dd else self._default)
+            for n, dd in self._nodes.items()
+        )
+
+    def __contains__(self, n):
+        try:
+            node_in = n in self._nodes
+        except TypeError:
+            n, d = n
+            return n in self._nodes and self[n] == d
+        if node_in is True:
+            return node_in
+        try:
+            n, d = n
+        except (TypeError, ValueError):
+            return False
+        return n in self._nodes and self[n] == d
+
+    def __getitem__(self, n):
+        if isinstance(n, slice):
+            raise nx.NetworkXError(
+                f"{type(self).__name__} does not support slicing, "
+                f"try list(G.nodes.data())[{n.start}:{n.stop}:{n.step}]"
+            )
+        ddict = self._nodes[n]
+        data = self._data
+        if data is False or data is True:
+            return ddict
+        return ddict[data] if data in ddict else self._default
+
+    def __str__(self):
+        return str(list(self))
+
+    def __repr__(self):
+        name = self.__class__.__name__
+        if self._data is False:
+            return f"{name}({tuple(self)})"
+        if self._data is True:
+            return f"{name}({dict(self)})"
+        return f"{name}({dict(self)}, data={self._data!r})"
+
+
+# DegreeViews
+class DiDegreeView:
+    """A View class for degree of nodes in a NetworkX Graph
+
+    The functionality is like dict.items() with (node, degree) pairs.
+    Additional functionality includes read-only lookup of node degree,
+    and calling with optional features nbunch (for only a subset of nodes)
+    and weight (use edge weights to compute degree).
+
+    Parameters
+    ==========
+    graph : NetworkX graph-like class
+    nbunch : node, container of nodes, or None meaning all nodes (default=None)
+    weight : bool or string (default=None)
+
+    Notes
+    -----
+    DegreeView can still lookup any node even if nbunch is specified.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(3)
+    >>> DV = G.degree()
+    >>> assert DV[2] == 1
+    >>> assert sum(deg for n, deg in DV) == 4
+
+    >>> DVweight = G.degree(weight="span")
+    >>> G.add_edge(1, 2, span=34)
+    >>> DVweight[2]
+    34
+    >>> DVweight[0]  #  default edge weight is 1
+    1
+    >>> sum(span for n, span in DVweight)  # sum weighted degrees
+    70
+
+    >>> DVnbunch = G.degree(nbunch=(1, 2))
+    >>> assert len(list(DVnbunch)) == 2  # iteration over nbunch only
+    """
+
+    def __init__(self, G, nbunch=None, weight=None):
+        self._graph = G
+        self._succ = G._succ if hasattr(G, "_succ") else G._adj
+        self._pred = G._pred if hasattr(G, "_pred") else G._adj
+        self._nodes = self._succ if nbunch is None else list(G.nbunch_iter(nbunch))
+        self._weight = weight
+
+    def __call__(self, nbunch=None, weight=None):
+        if nbunch is None:
+            if weight == self._weight:
+                return self
+            return self.__class__(self._graph, None, weight)
+        try:
+            if nbunch in self._nodes:
+                if weight == self._weight:
+                    return self[nbunch]
+                return self.__class__(self._graph, None, weight)[nbunch]
+        except TypeError:
+            pass
+        return self.__class__(self._graph, nbunch, weight)
+
+    def __getitem__(self, n):
+        weight = self._weight
+        succs = self._succ[n]
+        preds = self._pred[n]
+        if weight is None:
+            return len(succs) + len(preds)
+        return sum(dd.get(weight, 1) for dd in succs.values()) + sum(
+            dd.get(weight, 1) for dd in preds.values()
+        )
+
+    def __iter__(self):
+        weight = self._weight
+        if weight is None:
+            for n in self._nodes:
+                succs = self._succ[n]
+                preds = self._pred[n]
+                yield (n, len(succs) + len(preds))
+        else:
+            for n in self._nodes:
+                succs = self._succ[n]
+                preds = self._pred[n]
+                deg = sum(dd.get(weight, 1) for dd in succs.values()) + sum(
+                    dd.get(weight, 1) for dd in preds.values()
+                )
+                yield (n, deg)
+
+    def __len__(self):
+        return len(self._nodes)
+
+    def __str__(self):
+        return str(list(self))
+
+    def __repr__(self):
+        return f"{self.__class__.__name__}({dict(self)})"
+
+
+class DegreeView(DiDegreeView):
+    """A DegreeView class to act as G.degree for a NetworkX Graph
+
+    Typical usage focuses on iteration over `(node, degree)` pairs.
+    The degree is by default the number of edges incident to the node.
+    Optional argument `weight` enables weighted degree using the edge
+    attribute named in the `weight` argument.  Reporting and iteration
+    can also be restricted to a subset of nodes using `nbunch`.
+
+    Additional functionality include node lookup so that `G.degree[n]`
+    reported the (possibly weighted) degree of node `n`. Calling the
+    view creates a view with different arguments `nbunch` or `weight`.
+
+    Parameters
+    ==========
+    graph : NetworkX graph-like class
+    nbunch : node, container of nodes, or None meaning all nodes (default=None)
+    weight : string or None (default=None)
+
+    Notes
+    -----
+    DegreeView can still lookup any node even if nbunch is specified.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(3)
+    >>> DV = G.degree()
+    >>> assert DV[2] == 1
+    >>> assert G.degree[2] == 1
+    >>> assert sum(deg for n, deg in DV) == 4
+
+    >>> DVweight = G.degree(weight="span")
+    >>> G.add_edge(1, 2, span=34)
+    >>> DVweight[2]
+    34
+    >>> DVweight[0]  #  default edge weight is 1
+    1
+    >>> sum(span for n, span in DVweight)  # sum weighted degrees
+    70
+
+    >>> DVnbunch = G.degree(nbunch=(1, 2))
+    >>> assert len(list(DVnbunch)) == 2  # iteration over nbunch only
+    """
+
+    def __getitem__(self, n):
+        weight = self._weight
+        nbrs = self._succ[n]
+        if weight is None:
+            return len(nbrs) + (n in nbrs)
+        return sum(dd.get(weight, 1) for dd in nbrs.values()) + (
+            n in nbrs and nbrs[n].get(weight, 1)
+        )
+
+    def __iter__(self):
+        weight = self._weight
+        if weight is None:
+            for n in self._nodes:
+                nbrs = self._succ[n]
+                yield (n, len(nbrs) + (n in nbrs))
+        else:
+            for n in self._nodes:
+                nbrs = self._succ[n]
+                deg = sum(dd.get(weight, 1) for dd in nbrs.values()) + (
+                    n in nbrs and nbrs[n].get(weight, 1)
+                )
+                yield (n, deg)
+
+
+class OutDegreeView(DiDegreeView):
+    """A DegreeView class to report out_degree for a DiGraph; See DegreeView"""
+
+    def __getitem__(self, n):
+        weight = self._weight
+        nbrs = self._succ[n]
+        if self._weight is None:
+            return len(nbrs)
+        return sum(dd.get(self._weight, 1) for dd in nbrs.values())
+
+    def __iter__(self):
+        weight = self._weight
+        if weight is None:
+            for n in self._nodes:
+                succs = self._succ[n]
+                yield (n, len(succs))
+        else:
+            for n in self._nodes:
+                succs = self._succ[n]
+                deg = sum(dd.get(weight, 1) for dd in succs.values())
+                yield (n, deg)
+
+
+class InDegreeView(DiDegreeView):
+    """A DegreeView class to report in_degree for a DiGraph; See DegreeView"""
+
+    def __getitem__(self, n):
+        weight = self._weight
+        nbrs = self._pred[n]
+        if weight is None:
+            return len(nbrs)
+        return sum(dd.get(weight, 1) for dd in nbrs.values())
+
+    def __iter__(self):
+        weight = self._weight
+        if weight is None:
+            for n in self._nodes:
+                preds = self._pred[n]
+                yield (n, len(preds))
+        else:
+            for n in self._nodes:
+                preds = self._pred[n]
+                deg = sum(dd.get(weight, 1) for dd in preds.values())
+                yield (n, deg)
+
+
+class MultiDegreeView(DiDegreeView):
+    """A DegreeView class for undirected multigraphs; See DegreeView"""
+
+    def __getitem__(self, n):
+        weight = self._weight
+        nbrs = self._succ[n]
+        if weight is None:
+            return sum(len(keys) for keys in nbrs.values()) + (
+                n in nbrs and len(nbrs[n])
+            )
+        # edge weighted graph - degree is sum of nbr edge weights
+        deg = sum(
+            d.get(weight, 1) for key_dict in nbrs.values() for d in key_dict.values()
+        )
+        if n in nbrs:
+            deg += sum(d.get(weight, 1) for d in nbrs[n].values())
+        return deg
+
+    def __iter__(self):
+        weight = self._weight
+        if weight is None:
+            for n in self._nodes:
+                nbrs = self._succ[n]
+                deg = sum(len(keys) for keys in nbrs.values()) + (
+                    n in nbrs and len(nbrs[n])
+                )
+                yield (n, deg)
+        else:
+            for n in self._nodes:
+                nbrs = self._succ[n]
+                deg = sum(
+                    d.get(weight, 1)
+                    for key_dict in nbrs.values()
+                    for d in key_dict.values()
+                )
+                if n in nbrs:
+                    deg += sum(d.get(weight, 1) for d in nbrs[n].values())
+                yield (n, deg)
+
+
+class DiMultiDegreeView(DiDegreeView):
+    """A DegreeView class for MultiDiGraph; See DegreeView"""
+
+    def __getitem__(self, n):
+        weight = self._weight
+        succs = self._succ[n]
+        preds = self._pred[n]
+        if weight is None:
+            return sum(len(keys) for keys in succs.values()) + sum(
+                len(keys) for keys in preds.values()
+            )
+        # edge weighted graph - degree is sum of nbr edge weights
+        deg = sum(
+            d.get(weight, 1) for key_dict in succs.values() for d in key_dict.values()
+        ) + sum(
+            d.get(weight, 1) for key_dict in preds.values() for d in key_dict.values()
+        )
+        return deg
+
+    def __iter__(self):
+        weight = self._weight
+        if weight is None:
+            for n in self._nodes:
+                succs = self._succ[n]
+                preds = self._pred[n]
+                deg = sum(len(keys) for keys in succs.values()) + sum(
+                    len(keys) for keys in preds.values()
+                )
+                yield (n, deg)
+        else:
+            for n in self._nodes:
+                succs = self._succ[n]
+                preds = self._pred[n]
+                deg = sum(
+                    d.get(weight, 1)
+                    for key_dict in succs.values()
+                    for d in key_dict.values()
+                ) + sum(
+                    d.get(weight, 1)
+                    for key_dict in preds.values()
+                    for d in key_dict.values()
+                )
+                yield (n, deg)
+
+
+class InMultiDegreeView(DiDegreeView):
+    """A DegreeView class for inward degree of MultiDiGraph; See DegreeView"""
+
+    def __getitem__(self, n):
+        weight = self._weight
+        nbrs = self._pred[n]
+        if weight is None:
+            return sum(len(data) for data in nbrs.values())
+        # edge weighted graph - degree is sum of nbr edge weights
+        return sum(
+            d.get(weight, 1) for key_dict in nbrs.values() for d in key_dict.values()
+        )
+
+    def __iter__(self):
+        weight = self._weight
+        if weight is None:
+            for n in self._nodes:
+                nbrs = self._pred[n]
+                deg = sum(len(data) for data in nbrs.values())
+                yield (n, deg)
+        else:
+            for n in self._nodes:
+                nbrs = self._pred[n]
+                deg = sum(
+                    d.get(weight, 1)
+                    for key_dict in nbrs.values()
+                    for d in key_dict.values()
+                )
+                yield (n, deg)
+
+
+class OutMultiDegreeView(DiDegreeView):
+    """A DegreeView class for outward degree of MultiDiGraph; See DegreeView"""
+
+    def __getitem__(self, n):
+        weight = self._weight
+        nbrs = self._succ[n]
+        if weight is None:
+            return sum(len(data) for data in nbrs.values())
+        # edge weighted graph - degree is sum of nbr edge weights
+        return sum(
+            d.get(weight, 1) for key_dict in nbrs.values() for d in key_dict.values()
+        )
+
+    def __iter__(self):
+        weight = self._weight
+        if weight is None:
+            for n in self._nodes:
+                nbrs = self._succ[n]
+                deg = sum(len(data) for data in nbrs.values())
+                yield (n, deg)
+        else:
+            for n in self._nodes:
+                nbrs = self._succ[n]
+                deg = sum(
+                    d.get(weight, 1)
+                    for key_dict in nbrs.values()
+                    for d in key_dict.values()
+                )
+                yield (n, deg)
+
+
+# A base class for all edge views. Ensures all edge view and edge data view
+# objects/classes are captured by `isinstance(obj, EdgeViewABC)` and
+# `issubclass(cls, EdgeViewABC)` respectively
+class EdgeViewABC(ABC):
+    pass
+
+
+# EdgeDataViews
+class OutEdgeDataView(EdgeViewABC):
+    """EdgeDataView for outward edges of DiGraph; See EdgeDataView"""
+
+    __slots__ = (
+        "_viewer",
+        "_nbunch",
+        "_data",
+        "_default",
+        "_adjdict",
+        "_nodes_nbrs",
+        "_report",
+    )
+
+    def __getstate__(self):
+        return {
+            "viewer": self._viewer,
+            "nbunch": self._nbunch,
+            "data": self._data,
+            "default": self._default,
+        }
+
+    def __setstate__(self, state):
+        self.__init__(**state)
+
+    def __init__(self, viewer, nbunch=None, data=False, *, default=None):
+        self._viewer = viewer
+        adjdict = self._adjdict = viewer._adjdict
+        if nbunch is None:
+            self._nodes_nbrs = adjdict.items
+        else:
+            # dict retains order of nodes but acts like a set
+            nbunch = dict.fromkeys(viewer._graph.nbunch_iter(nbunch))
+            self._nodes_nbrs = lambda: [(n, adjdict[n]) for n in nbunch]
+        self._nbunch = nbunch
+        self._data = data
+        self._default = default
+        # Set _report based on data and default
+        if data is True:
+            self._report = lambda n, nbr, dd: (n, nbr, dd)
+        elif data is False:
+            self._report = lambda n, nbr, dd: (n, nbr)
+        else:  # data is attribute name
+            self._report = (
+                lambda n, nbr, dd: (n, nbr, dd[data])
+                if data in dd
+                else (n, nbr, default)
+            )
+
+    def __len__(self):
+        return sum(len(nbrs) for n, nbrs in self._nodes_nbrs())
+
+    def __iter__(self):
+        return (
+            self._report(n, nbr, dd)
+            for n, nbrs in self._nodes_nbrs()
+            for nbr, dd in nbrs.items()
+        )
+
+    def __contains__(self, e):
+        u, v = e[:2]
+        if self._nbunch is not None and u not in self._nbunch:
+            return False  # this edge doesn't start in nbunch
+        try:
+            ddict = self._adjdict[u][v]
+        except KeyError:
+            return False
+        return e == self._report(u, v, ddict)
+
+    def __str__(self):
+        return str(list(self))
+
+    def __repr__(self):
+        return f"{self.__class__.__name__}({list(self)})"
+
+
+class EdgeDataView(OutEdgeDataView):
+    """A EdgeDataView class for edges of Graph
+
+    This view is primarily used to iterate over the edges reporting
+    edges as node-tuples with edge data optionally reported. The
+    argument `nbunch` allows restriction to edges incident to nodes
+    in that container/singleton. The default (nbunch=None)
+    reports all edges. The arguments `data` and `default` control
+    what edge data is reported. The default `data is False` reports
+    only node-tuples for each edge. If `data is True` the entire edge
+    data dict is returned. Otherwise `data` is assumed to hold the name
+    of the edge attribute to report with default `default` if  that
+    edge attribute is not present.
+
+    Parameters
+    ----------
+    nbunch : container of nodes, node or None (default None)
+    data : False, True or string (default False)
+    default : default value (default None)
+
+    Examples
+    --------
+    >>> G = nx.path_graph(3)
+    >>> G.add_edge(1, 2, foo="bar")
+    >>> list(G.edges(data="foo", default="biz"))
+    [(0, 1, 'biz'), (1, 2, 'bar')]
+    >>> assert (0, 1, "biz") in G.edges(data="foo", default="biz")
+    """
+
+    __slots__ = ()
+
+    def __len__(self):
+        return sum(1 for e in self)
+
+    def __iter__(self):
+        seen = {}
+        for n, nbrs in self._nodes_nbrs():
+            for nbr, dd in nbrs.items():
+                if nbr not in seen:
+                    yield self._report(n, nbr, dd)
+            seen[n] = 1
+        del seen
+
+    def __contains__(self, e):
+        u, v = e[:2]
+        if self._nbunch is not None and u not in self._nbunch and v not in self._nbunch:
+            return False  # this edge doesn't start and it doesn't end in nbunch
+        try:
+            ddict = self._adjdict[u][v]
+        except KeyError:
+            return False
+        return e == self._report(u, v, ddict)
+
+
+class InEdgeDataView(OutEdgeDataView):
+    """An EdgeDataView class for outward edges of DiGraph; See EdgeDataView"""
+
+    __slots__ = ()
+
+    def __iter__(self):
+        return (
+            self._report(nbr, n, dd)
+            for n, nbrs in self._nodes_nbrs()
+            for nbr, dd in nbrs.items()
+        )
+
+    def __contains__(self, e):
+        u, v = e[:2]
+        if self._nbunch is not None and v not in self._nbunch:
+            return False  # this edge doesn't end in nbunch
+        try:
+            ddict = self._adjdict[v][u]
+        except KeyError:
+            return False
+        return e == self._report(u, v, ddict)
+
+
+class OutMultiEdgeDataView(OutEdgeDataView):
+    """An EdgeDataView for outward edges of MultiDiGraph; See EdgeDataView"""
+
+    __slots__ = ("keys",)
+
+    def __getstate__(self):
+        return {
+            "viewer": self._viewer,
+            "nbunch": self._nbunch,
+            "keys": self.keys,
+            "data": self._data,
+            "default": self._default,
+        }
+
+    def __setstate__(self, state):
+        self.__init__(**state)
+
+    def __init__(self, viewer, nbunch=None, data=False, *, default=None, keys=False):
+        self._viewer = viewer
+        adjdict = self._adjdict = viewer._adjdict
+        self.keys = keys
+        if nbunch is None:
+            self._nodes_nbrs = adjdict.items
+        else:
+            # dict retains order of nodes but acts like a set
+            nbunch = dict.fromkeys(viewer._graph.nbunch_iter(nbunch))
+            self._nodes_nbrs = lambda: [(n, adjdict[n]) for n in nbunch]
+        self._nbunch = nbunch
+        self._data = data
+        self._default = default
+        # Set _report based on data and default
+        if data is True:
+            if keys is True:
+                self._report = lambda n, nbr, k, dd: (n, nbr, k, dd)
+            else:
+                self._report = lambda n, nbr, k, dd: (n, nbr, dd)
+        elif data is False:
+            if keys is True:
+                self._report = lambda n, nbr, k, dd: (n, nbr, k)
+            else:
+                self._report = lambda n, nbr, k, dd: (n, nbr)
+        else:  # data is attribute name
+            if keys is True:
+                self._report = (
+                    lambda n, nbr, k, dd: (n, nbr, k, dd[data])
+                    if data in dd
+                    else (n, nbr, k, default)
+                )
+            else:
+                self._report = (
+                    lambda n, nbr, k, dd: (n, nbr, dd[data])
+                    if data in dd
+                    else (n, nbr, default)
+                )
+
+    def __len__(self):
+        return sum(1 for e in self)
+
+    def __iter__(self):
+        return (
+            self._report(n, nbr, k, dd)
+            for n, nbrs in self._nodes_nbrs()
+            for nbr, kd in nbrs.items()
+            for k, dd in kd.items()
+        )
+
+    def __contains__(self, e):
+        u, v = e[:2]
+        if self._nbunch is not None and u not in self._nbunch:
+            return False  # this edge doesn't start in nbunch
+        try:
+            kdict = self._adjdict[u][v]
+        except KeyError:
+            return False
+        if self.keys is True:
+            k = e[2]
+            try:
+                dd = kdict[k]
+            except KeyError:
+                return False
+            return e == self._report(u, v, k, dd)
+        return any(e == self._report(u, v, k, dd) for k, dd in kdict.items())
+
+
+class MultiEdgeDataView(OutMultiEdgeDataView):
+    """An EdgeDataView class for edges of MultiGraph; See EdgeDataView"""
+
+    __slots__ = ()
+
+    def __iter__(self):
+        seen = {}
+        for n, nbrs in self._nodes_nbrs():
+            for nbr, kd in nbrs.items():
+                if nbr not in seen:
+                    for k, dd in kd.items():
+                        yield self._report(n, nbr, k, dd)
+            seen[n] = 1
+        del seen
+
+    def __contains__(self, e):
+        u, v = e[:2]
+        if self._nbunch is not None and u not in self._nbunch and v not in self._nbunch:
+            return False  # this edge doesn't start and doesn't end in nbunch
+        try:
+            kdict = self._adjdict[u][v]
+        except KeyError:
+            try:
+                kdict = self._adjdict[v][u]
+            except KeyError:
+                return False
+        if self.keys is True:
+            k = e[2]
+            try:
+                dd = kdict[k]
+            except KeyError:
+                return False
+            return e == self._report(u, v, k, dd)
+        return any(e == self._report(u, v, k, dd) for k, dd in kdict.items())
+
+
+class InMultiEdgeDataView(OutMultiEdgeDataView):
+    """An EdgeDataView for inward edges of MultiDiGraph; See EdgeDataView"""
+
+    __slots__ = ()
+
+    def __iter__(self):
+        return (
+            self._report(nbr, n, k, dd)
+            for n, nbrs in self._nodes_nbrs()
+            for nbr, kd in nbrs.items()
+            for k, dd in kd.items()
+        )
+
+    def __contains__(self, e):
+        u, v = e[:2]
+        if self._nbunch is not None and v not in self._nbunch:
+            return False  # this edge doesn't end in nbunch
+        try:
+            kdict = self._adjdict[v][u]
+        except KeyError:
+            return False
+        if self.keys is True:
+            k = e[2]
+            dd = kdict[k]
+            return e == self._report(u, v, k, dd)
+        return any(e == self._report(u, v, k, dd) for k, dd in kdict.items())
+
+
+# EdgeViews    have set operations and no data reported
+class OutEdgeView(Set, Mapping, EdgeViewABC):
+    """A EdgeView class for outward edges of a DiGraph"""
+
+    __slots__ = ("_adjdict", "_graph", "_nodes_nbrs")
+
+    def __getstate__(self):
+        return {"_graph": self._graph, "_adjdict": self._adjdict}
+
+    def __setstate__(self, state):
+        self._graph = state["_graph"]
+        self._adjdict = state["_adjdict"]
+        self._nodes_nbrs = self._adjdict.items
+
+    @classmethod
+    def _from_iterable(cls, it):
+        return set(it)
+
+    dataview = OutEdgeDataView
+
+    def __init__(self, G):
+        self._graph = G
+        self._adjdict = G._succ if hasattr(G, "succ") else G._adj
+        self._nodes_nbrs = self._adjdict.items
+
+    # Set methods
+    def __len__(self):
+        return sum(len(nbrs) for n, nbrs in self._nodes_nbrs())
+
+    def __iter__(self):
+        for n, nbrs in self._nodes_nbrs():
+            for nbr in nbrs:
+                yield (n, nbr)
+
+    def __contains__(self, e):
+        try:
+            u, v = e
+            return v in self._adjdict[u]
+        except KeyError:
+            return False
+
+    # Mapping Methods
+    def __getitem__(self, e):
+        if isinstance(e, slice):
+            raise nx.NetworkXError(
+                f"{type(self).__name__} does not support slicing, "
+                f"try list(G.edges)[{e.start}:{e.stop}:{e.step}]"
+            )
+        u, v = e
+        try:
+            return self._adjdict[u][v]
+        except KeyError as ex:  # Customize msg to indicate exception origin
+            raise KeyError(f"The edge {e} is not in the graph.")
+
+    # EdgeDataView methods
+    def __call__(self, nbunch=None, data=False, *, default=None):
+        if nbunch is None and data is False:
+            return self
+        return self.dataview(self, nbunch, data, default=default)
+
+    def data(self, data=True, default=None, nbunch=None):
+        """
+        Return a read-only view of edge data.
+
+        Parameters
+        ----------
+        data : bool or edge attribute key
+            If ``data=True``, then the data view maps each edge to a dictionary
+            containing all of its attributes. If `data` is a key in the edge
+            dictionary, then the data view maps each edge to its value for
+            the keyed attribute. In this case, if the edge doesn't have the
+            attribute, the `default` value is returned.
+        default : object, default=None
+            The value used when an edge does not have a specific attribute
+        nbunch : container of nodes, optional (default=None)
+            Allows restriction to edges only involving certain nodes. All edges
+            are considered by default.
+
+        Returns
+        -------
+        dataview
+            Returns an `EdgeDataView` for undirected Graphs, `OutEdgeDataView`
+            for DiGraphs, `MultiEdgeDataView` for MultiGraphs and
+            `OutMultiEdgeDataView` for MultiDiGraphs.
+
+        Notes
+        -----
+        If ``data=False``, returns an `EdgeView` without any edge data.
+
+        See Also
+        --------
+        EdgeDataView
+        OutEdgeDataView
+        MultiEdgeDataView
+        OutMultiEdgeDataView
+
+        Examples
+        --------
+        >>> G = nx.Graph()
+        >>> G.add_edges_from(
+        ...     [
+        ...         (0, 1, {"dist": 3, "capacity": 20}),
+        ...         (1, 2, {"dist": 4}),
+        ...         (2, 0, {"dist": 5}),
+        ...     ]
+        ... )
+
+        Accessing edge data with ``data=True`` (the default) returns an
+        edge data view object listing each edge with all of its attributes:
+
+        >>> G.edges.data()
+        EdgeDataView([(0, 1, {'dist': 3, 'capacity': 20}), (0, 2, {'dist': 5}), (1, 2, {'dist': 4})])
+
+        If `data` represents a key in the edge attribute dict, a dataview listing
+        each edge with its value for that specific key is returned:
+
+        >>> G.edges.data("dist")
+        EdgeDataView([(0, 1, 3), (0, 2, 5), (1, 2, 4)])
+
+        `nbunch` can be used to limit the edges:
+
+        >>> G.edges.data("dist", nbunch=[0])
+        EdgeDataView([(0, 1, 3), (0, 2, 5)])
+
+        If a specific key is not found in an edge attribute dict, the value
+        specified by `default` is used:
+
+        >>> G.edges.data("capacity")
+        EdgeDataView([(0, 1, 20), (0, 2, None), (1, 2, None)])
+
+        Note that there is no check that the `data` key is present in any of
+        the edge attribute dictionaries:
+
+        >>> G.edges.data("speed")
+        EdgeDataView([(0, 1, None), (0, 2, None), (1, 2, None)])
+        """
+        if nbunch is None and data is False:
+            return self
+        return self.dataview(self, nbunch, data, default=default)
+
+    # String Methods
+    def __str__(self):
+        return str(list(self))
+
+    def __repr__(self):
+        return f"{self.__class__.__name__}({list(self)})"
+
+
+class EdgeView(OutEdgeView):
+    """A EdgeView class for edges of a Graph
+
+    This densely packed View allows iteration over edges, data lookup
+    like a dict and set operations on edges represented by node-tuples.
+    In addition, edge data can be controlled by calling this object
+    possibly creating an EdgeDataView. Typically edges are iterated over
+    and reported as `(u, v)` node tuples or `(u, v, key)` node/key tuples
+    for multigraphs. Those edge representations can also be using to
+    lookup the data dict for any edge. Set operations also are available
+    where those tuples are the elements of the set.
+    Calling this object with optional arguments `data`, `default` and `keys`
+    controls the form of the tuple (see EdgeDataView). Optional argument
+    `nbunch` allows restriction to edges only involving certain nodes.
+
+    If `data is False` (the default) then iterate over 2-tuples `(u, v)`.
+    If `data is True` iterate over 3-tuples `(u, v, datadict)`.
+    Otherwise iterate over `(u, v, datadict.get(data, default))`.
+    For Multigraphs, if `keys is True`, replace `u, v` with `u, v, key` above.
+
+    Parameters
+    ==========
+    graph : NetworkX graph-like class
+    nbunch : (default= all nodes in graph) only report edges with these nodes
+    keys : (only for MultiGraph. default=False) report edge key in tuple
+    data : bool or string (default=False) see above
+    default : object (default=None)
+
+    Examples
+    ========
+    >>> G = nx.path_graph(4)
+    >>> EV = G.edges()
+    >>> (2, 3) in EV
+    True
+    >>> for u, v in EV:
+    ...     print((u, v))
+    (0, 1)
+    (1, 2)
+    (2, 3)
+    >>> assert EV & {(1, 2), (3, 4)} == {(1, 2)}
+
+    >>> EVdata = G.edges(data="color", default="aqua")
+    >>> G.add_edge(2, 3, color="blue")
+    >>> assert (2, 3, "blue") in EVdata
+    >>> for u, v, c in EVdata:
+    ...     print(f"({u}, {v}) has color: {c}")
+    (0, 1) has color: aqua
+    (1, 2) has color: aqua
+    (2, 3) has color: blue
+
+    >>> EVnbunch = G.edges(nbunch=2)
+    >>> assert (2, 3) in EVnbunch
+    >>> assert (0, 1) not in EVnbunch
+    >>> for u, v in EVnbunch:
+    ...     assert u == 2 or v == 2
+
+    >>> MG = nx.path_graph(4, create_using=nx.MultiGraph)
+    >>> EVmulti = MG.edges(keys=True)
+    >>> (2, 3, 0) in EVmulti
+    True
+    >>> (2, 3) in EVmulti  # 2-tuples work even when keys is True
+    True
+    >>> key = MG.add_edge(2, 3)
+    >>> for u, v, k in EVmulti:
+    ...     print((u, v, k))
+    (0, 1, 0)
+    (1, 2, 0)
+    (2, 3, 0)
+    (2, 3, 1)
+    """
+
+    __slots__ = ()
+
+    dataview = EdgeDataView
+
+    def __len__(self):
+        num_nbrs = (len(nbrs) + (n in nbrs) for n, nbrs in self._nodes_nbrs())
+        return sum(num_nbrs) // 2
+
+    def __iter__(self):
+        seen = {}
+        for n, nbrs in self._nodes_nbrs():
+            for nbr in list(nbrs):
+                if nbr not in seen:
+                    yield (n, nbr)
+            seen[n] = 1
+        del seen
+
+    def __contains__(self, e):
+        try:
+            u, v = e[:2]
+            return v in self._adjdict[u] or u in self._adjdict[v]
+        except (KeyError, ValueError):
+            return False
+
+
+class InEdgeView(OutEdgeView):
+    """A EdgeView class for inward edges of a DiGraph"""
+
+    __slots__ = ()
+
+    def __setstate__(self, state):
+        self._graph = state["_graph"]
+        self._adjdict = state["_adjdict"]
+        self._nodes_nbrs = self._adjdict.items
+
+    dataview = InEdgeDataView
+
+    def __init__(self, G):
+        self._graph = G
+        self._adjdict = G._pred if hasattr(G, "pred") else G._adj
+        self._nodes_nbrs = self._adjdict.items
+
+    def __iter__(self):
+        for n, nbrs in self._nodes_nbrs():
+            for nbr in nbrs:
+                yield (nbr, n)
+
+    def __contains__(self, e):
+        try:
+            u, v = e
+            return u in self._adjdict[v]
+        except KeyError:
+            return False
+
+    def __getitem__(self, e):
+        if isinstance(e, slice):
+            raise nx.NetworkXError(
+                f"{type(self).__name__} does not support slicing, "
+                f"try list(G.in_edges)[{e.start}:{e.stop}:{e.step}]"
+            )
+        u, v = e
+        return self._adjdict[v][u]
+
+
+class OutMultiEdgeView(OutEdgeView):
+    """A EdgeView class for outward edges of a MultiDiGraph"""
+
+    __slots__ = ()
+
+    dataview = OutMultiEdgeDataView
+
+    def __len__(self):
+        return sum(
+            len(kdict) for n, nbrs in self._nodes_nbrs() for nbr, kdict in nbrs.items()
+        )
+
+    def __iter__(self):
+        for n, nbrs in self._nodes_nbrs():
+            for nbr, kdict in nbrs.items():
+                for key in kdict:
+                    yield (n, nbr, key)
+
+    def __contains__(self, e):
+        N = len(e)
+        if N == 3:
+            u, v, k = e
+        elif N == 2:
+            u, v = e
+            k = 0
+        else:
+            raise ValueError("MultiEdge must have length 2 or 3")
+        try:
+            return k in self._adjdict[u][v]
+        except KeyError:
+            return False
+
+    def __getitem__(self, e):
+        if isinstance(e, slice):
+            raise nx.NetworkXError(
+                f"{type(self).__name__} does not support slicing, "
+                f"try list(G.edges)[{e.start}:{e.stop}:{e.step}]"
+            )
+        u, v, k = e
+        return self._adjdict[u][v][k]
+
+    def __call__(self, nbunch=None, data=False, *, default=None, keys=False):
+        if nbunch is None and data is False and keys is True:
+            return self
+        return self.dataview(self, nbunch, data, default=default, keys=keys)
+
+    def data(self, data=True, default=None, nbunch=None, keys=False):
+        if nbunch is None and data is False and keys is True:
+            return self
+        return self.dataview(self, nbunch, data, default=default, keys=keys)
+
+
+class MultiEdgeView(OutMultiEdgeView):
+    """A EdgeView class for edges of a MultiGraph"""
+
+    __slots__ = ()
+
+    dataview = MultiEdgeDataView
+
+    def __len__(self):
+        return sum(1 for e in self)
+
+    def __iter__(self):
+        seen = {}
+        for n, nbrs in self._nodes_nbrs():
+            for nbr, kd in nbrs.items():
+                if nbr not in seen:
+                    for k, dd in kd.items():
+                        yield (n, nbr, k)
+            seen[n] = 1
+        del seen
+
+
+class InMultiEdgeView(OutMultiEdgeView):
+    """A EdgeView class for inward edges of a MultiDiGraph"""
+
+    __slots__ = ()
+
+    def __setstate__(self, state):
+        self._graph = state["_graph"]
+        self._adjdict = state["_adjdict"]
+        self._nodes_nbrs = self._adjdict.items
+
+    dataview = InMultiEdgeDataView
+
+    def __init__(self, G):
+        self._graph = G
+        self._adjdict = G._pred if hasattr(G, "pred") else G._adj
+        self._nodes_nbrs = self._adjdict.items
+
+    def __iter__(self):
+        for n, nbrs in self._nodes_nbrs():
+            for nbr, kdict in nbrs.items():
+                for key in kdict:
+                    yield (nbr, n, key)
+
+    def __contains__(self, e):
+        N = len(e)
+        if N == 3:
+            u, v, k = e
+        elif N == 2:
+            u, v = e
+            k = 0
+        else:
+            raise ValueError("MultiEdge must have length 2 or 3")
+        try:
+            return k in self._adjdict[v][u]
+        except KeyError:
+            return False
+
+    def __getitem__(self, e):
+        if isinstance(e, slice):
+            raise nx.NetworkXError(
+                f"{type(self).__name__} does not support slicing, "
+                f"try list(G.in_edges)[{e.start}:{e.stop}:{e.step}]"
+            )
+        u, v, k = e
+        return self._adjdict[v][u][k]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/drawing/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/drawing/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f53309d4da23a445bcce8cb7570a6de364452b5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/drawing/__init__.py
@@ -0,0 +1,7 @@
+# graph drawing and interface to graphviz
+
+from .layout import *
+from .nx_latex import *
+from .nx_pylab import *
+from . import nx_agraph
+from . import nx_pydot
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/drawing/layout.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/drawing/layout.py
new file mode 100644
index 0000000000000000000000000000000000000000..b46d9f77b81f27acd8f4eaef2aa5c5a3e87872ed
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/drawing/layout.py
@@ -0,0 +1,2036 @@
+"""
+******
+Layout
+******
+
+Node positioning algorithms for graph drawing.
+
+For `random_layout()` the possible resulting shape
+is a square of side [0, scale] (default: [0, 1])
+Changing `center` shifts the layout by that amount.
+
+For the other layout routines, the extent is
+[center - scale, center + scale] (default: [-1, 1]).
+
+Warning: Most layout routines have only been tested in 2-dimensions.
+
+"""
+
+import networkx as nx
+from networkx.utils import np_random_state
+
+__all__ = [
+    "bipartite_layout",
+    "circular_layout",
+    "forceatlas2_layout",
+    "kamada_kawai_layout",
+    "random_layout",
+    "rescale_layout",
+    "rescale_layout_dict",
+    "shell_layout",
+    "spring_layout",
+    "spectral_layout",
+    "planar_layout",
+    "fruchterman_reingold_layout",
+    "spiral_layout",
+    "multipartite_layout",
+    "bfs_layout",
+    "arf_layout",
+]
+
+
+def _process_params(G, center, dim):
+    # Some boilerplate code.
+    import numpy as np
+
+    if not isinstance(G, nx.Graph):
+        empty_graph = nx.Graph()
+        empty_graph.add_nodes_from(G)
+        G = empty_graph
+
+    if center is None:
+        center = np.zeros(dim)
+    else:
+        center = np.asarray(center)
+
+    if len(center) != dim:
+        msg = "length of center coordinates must match dimension of layout"
+        raise ValueError(msg)
+
+    return G, center
+
+
+@np_random_state(3)
+def random_layout(G, center=None, dim=2, seed=None, store_pos_as=None):
+    """Position nodes uniformly at random in the unit square.
+
+    For every node, a position is generated by choosing each of dim
+    coordinates uniformly at random on the interval [0.0, 1.0).
+
+    NumPy (http://scipy.org) is required for this function.
+
+    Parameters
+    ----------
+    G : NetworkX graph or list of nodes
+        A position will be assigned to every node in G.
+
+    center : array-like or None
+        Coordinate pair around which to center the layout.
+
+    dim : int
+        Dimension of layout.
+
+    seed : int, RandomState instance or None  optional (default=None)
+        Set the random state for deterministic node layouts.
+        If int, `seed` is the seed used by the random number generator,
+        if numpy.random.RandomState instance, `seed` is the random
+        number generator,
+        if None, the random number generator is the RandomState instance used
+        by numpy.random.
+
+    store_pos_as : str, default None
+        If non-None, the position of each node will be stored on the graph as
+        an attribute with this string as its name, which can be accessed with
+        ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.
+
+    Returns
+    -------
+    pos : dict
+        A dictionary of positions keyed by node
+
+    Examples
+    --------
+    >>> from pprint import pprint
+    >>> G = nx.lollipop_graph(4, 3)
+    >>> pos = nx.random_layout(G)
+    >>> # suppress the returned dict and store on the graph directly
+    >>> _ = nx.random_layout(G, seed=42, store_pos_as="pos")
+    >>> pprint(nx.get_node_attributes(G, "pos"))
+    {0: array([0.37454012, 0.9507143 ], dtype=float32),
+     1: array([0.7319939, 0.5986585], dtype=float32),
+     2: array([0.15601864, 0.15599452], dtype=float32),
+     3: array([0.05808361, 0.8661761 ], dtype=float32),
+     4: array([0.601115 , 0.7080726], dtype=float32),
+     5: array([0.02058449, 0.96990985], dtype=float32),
+     6: array([0.83244264, 0.21233912], dtype=float32)}
+    """
+    import numpy as np
+
+    G, center = _process_params(G, center, dim)
+    pos = seed.rand(len(G), dim) + center
+    pos = pos.astype(np.float32)
+    pos = dict(zip(G, pos))
+
+    if store_pos_as is not None:
+        nx.set_node_attributes(G, pos, store_pos_as)
+    return pos
+
+
+def circular_layout(G, scale=1, center=None, dim=2, store_pos_as=None):
+    # dim=2 only
+    """Position nodes on a circle.
+
+    Parameters
+    ----------
+    G : NetworkX graph or list of nodes
+        A position will be assigned to every node in G.
+
+    scale : number (default: 1)
+        Scale factor for positions.
+
+    center : array-like or None
+        Coordinate pair around which to center the layout.
+
+    dim : int
+        Dimension of layout.
+        If dim>2, the remaining dimensions are set to zero
+        in the returned positions.
+        If dim<2, a ValueError is raised.
+
+    store_pos_as : str, default None
+        If non-None, the position of each node will be stored on the graph as
+        an attribute with this string as its name, which can be accessed with
+        ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.
+
+    Returns
+    -------
+    pos : dict
+        A dictionary of positions keyed by node
+
+    Raises
+    ------
+    ValueError
+        If dim < 2
+
+    Examples
+    --------
+    >>> from pprint import pprint
+    >>> G = nx.path_graph(4)
+    >>> pos = nx.circular_layout(G)
+    >>> # suppress the returned dict and store on the graph directly
+    >>> _ = nx.circular_layout(G, store_pos_as="pos")
+    >>> pprint(nx.get_node_attributes(G, "pos"))
+    {0: array([9.99999986e-01, 2.18556937e-08]),
+     1: array([-3.57647606e-08,  1.00000000e+00]),
+     2: array([-9.9999997e-01, -6.5567081e-08]),
+     3: array([ 1.98715071e-08, -9.99999956e-01])}
+
+
+    Notes
+    -----
+    This algorithm currently only works in two dimensions and does not
+    try to minimize edge crossings.
+
+    """
+    import numpy as np
+
+    if dim < 2:
+        raise ValueError("cannot handle dimensions < 2")
+
+    G, center = _process_params(G, center, dim)
+
+    paddims = max(0, (dim - 2))
+
+    if len(G) == 0:
+        pos = {}
+    elif len(G) == 1:
+        pos = {nx.utils.arbitrary_element(G): center}
+    else:
+        # Discard the extra angle since it matches 0 radians.
+        theta = np.linspace(0, 1, len(G) + 1)[:-1] * 2 * np.pi
+        theta = theta.astype(np.float32)
+        pos = np.column_stack(
+            [np.cos(theta), np.sin(theta), np.zeros((len(G), paddims))]
+        )
+        pos = rescale_layout(pos, scale=scale) + center
+        pos = dict(zip(G, pos))
+
+    if store_pos_as is not None:
+        nx.set_node_attributes(G, pos, store_pos_as)
+
+    return pos
+
+
+def shell_layout(
+    G, nlist=None, rotate=None, scale=1, center=None, dim=2, store_pos_as=None
+):
+    """Position nodes in concentric circles.
+
+    Parameters
+    ----------
+    G : NetworkX graph or list of nodes
+        A position will be assigned to every node in G.
+
+    nlist : list of lists
+       List of node lists for each shell.
+
+    rotate : angle in radians (default=pi/len(nlist))
+       Angle by which to rotate the starting position of each shell
+       relative to the starting position of the previous shell.
+       To recreate behavior before v2.5 use rotate=0.
+
+    scale : number (default: 1)
+        Scale factor for positions.
+
+    center : array-like or None
+        Coordinate pair around which to center the layout.
+
+    dim : int
+        Dimension of layout, currently only dim=2 is supported.
+        Other dimension values result in a ValueError.
+
+    store_pos_as : str, default None
+        If non-None, the position of each node will be stored on the graph as
+        an attribute with this string as its name, which can be accessed with
+        ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.
+
+    Returns
+    -------
+    pos : dict
+        A dictionary of positions keyed by node
+
+    Raises
+    ------
+    ValueError
+        If dim != 2
+
+    Examples
+    --------
+    >>> from pprint import pprint
+    >>> G = nx.path_graph(4)
+    >>> shells = [[0], [1, 2, 3]]
+    >>> pos = nx.shell_layout(G, shells)
+    >>> # suppress the returned dict and store on the graph directly
+    >>> _ = nx.shell_layout(G, shells, store_pos_as="pos")
+    >>> pprint(nx.get_node_attributes(G, "pos"))
+    {0: array([0., 0.]),
+     1: array([-5.00000000e-01, -4.37113883e-08]),
+     2: array([ 0.24999996, -0.43301272]),
+     3: array([0.24999981, 0.43301281])}
+
+    Notes
+    -----
+    This algorithm currently only works in two dimensions and does not
+    try to minimize edge crossings.
+
+    """
+    import numpy as np
+
+    if dim != 2:
+        raise ValueError("can only handle 2 dimensions")
+
+    G, center = _process_params(G, center, dim)
+
+    if len(G) == 0:
+        return {}
+    if len(G) == 1:
+        return {nx.utils.arbitrary_element(G): center}
+
+    if nlist is None:
+        # draw the whole graph in one shell
+        nlist = [list(G)]
+
+    radius_bump = scale / len(nlist)
+
+    if len(nlist[0]) == 1:
+        # single node at center
+        radius = 0.0
+    else:
+        # else start at r=1
+        radius = radius_bump
+
+    if rotate is None:
+        rotate = np.pi / len(nlist)
+    first_theta = rotate
+    npos = {}
+    for nodes in nlist:
+        # Discard the last angle (endpoint=False) since 2*pi matches 0 radians
+        theta = (
+            np.linspace(0, 2 * np.pi, len(nodes), endpoint=False, dtype=np.float32)
+            + first_theta
+        )
+        pos = radius * np.column_stack([np.cos(theta), np.sin(theta)]) + center
+        npos.update(zip(nodes, pos))
+        radius += radius_bump
+        first_theta += rotate
+
+    if store_pos_as is not None:
+        nx.set_node_attributes(G, npos, store_pos_as)
+    return npos
+
+
+def bipartite_layout(
+    G,
+    nodes=None,
+    align="vertical",
+    scale=1,
+    center=None,
+    aspect_ratio=4 / 3,
+    store_pos_as=None,
+):
+    """Position nodes in two straight lines.
+
+    Parameters
+    ----------
+    G : NetworkX graph or list of nodes
+        A position will be assigned to every node in G.
+
+    nodes : collection of nodes
+        Nodes in one node set of the graph. This set will be placed on
+        left or top. If `None` (the default), a node set is chosen arbitrarily
+        if the graph if bipartite.
+
+    align : string (default='vertical')
+        The alignment of nodes. Vertical or horizontal.
+
+    scale : number (default: 1)
+        Scale factor for positions.
+
+    center : array-like or None
+        Coordinate pair around which to center the layout.
+
+    aspect_ratio : number (default=4/3):
+        The ratio of the width to the height of the layout.
+
+    store_pos_as : str, default None
+        If non-None, the position of each node will be stored on the graph as
+        an attribute with this string as its name, which can be accessed with
+        ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.
+
+    Returns
+    -------
+    pos : dict
+        A dictionary of positions keyed by node.
+
+    Raises
+    ------
+    NetworkXError
+        If ``nodes=None`` and `G` is not bipartite.
+
+    Examples
+    --------
+    >>> G = nx.complete_bipartite_graph(3, 3)
+    >>> pos = nx.bipartite_layout(G)
+
+    The ordering of the layout (i.e. which nodes appear on the left/top) can
+    be specified with the `nodes` parameter:
+
+    >>> top, bottom = nx.bipartite.sets(G)
+    >>> pos = nx.bipartite_layout(G, nodes=bottom)  # "bottom" set appears on the left
+
+    `store_pos_as` can be used to store the node positions for the computed layout
+    directly on the nodes:
+
+    >>> _ = nx.bipartite_layout(G, nodes=bottom, store_pos_as="pos")
+    >>> from pprint import pprint
+    >>> pprint(nx.get_node_attributes(G, "pos"))
+    {0: array([ 1.  , -0.75]),
+     1: array([1., 0.]),
+     2: array([1.  , 0.75]),
+     3: array([-1.  , -0.75]),
+     4: array([-1.,  0.]),
+     5: array([-1.  ,  0.75])}
+
+
+    The ``bipartite_layout`` function can be used with non-bipartite graphs
+    by explicitly specifying how the layout should be partitioned with `nodes`:
+
+    >>> G = nx.complete_graph(5)  # Non-bipartite
+    >>> pos = nx.bipartite_layout(G, nodes={0, 1, 2})
+
+    Notes
+    -----
+    This algorithm currently only works in two dimensions and does not
+    try to minimize edge crossings.
+
+    """
+
+    import numpy as np
+
+    if align not in ("vertical", "horizontal"):
+        msg = "align must be either vertical or horizontal."
+        raise ValueError(msg)
+
+    G, center = _process_params(G, center=center, dim=2)
+    if len(G) == 0:
+        return {}
+
+    height = 1
+    width = aspect_ratio * height
+    offset = (width / 2, height / 2)
+
+    if nodes is None:
+        top, bottom = nx.bipartite.sets(G)
+        nodes = list(G)
+    else:
+        top = set(nodes)
+        bottom = set(G) - top
+        # Preserves backward-compatible node ordering in returned pos dict
+        nodes = list(top) + list(bottom)
+
+    left_xs = np.repeat(0, len(top))
+    right_xs = np.repeat(width, len(bottom))
+    left_ys = np.linspace(0, height, len(top))
+    right_ys = np.linspace(0, height, len(bottom))
+
+    top_pos = np.column_stack([left_xs, left_ys]) - offset
+    bottom_pos = np.column_stack([right_xs, right_ys]) - offset
+
+    pos = np.concatenate([top_pos, bottom_pos])
+    pos = rescale_layout(pos, scale=scale) + center
+    if align == "horizontal":
+        pos = pos[:, ::-1]  # swap x and y coords
+    pos = dict(zip(nodes, pos))
+
+    if store_pos_as is not None:
+        nx.set_node_attributes(G, pos, store_pos_as)
+
+    return pos
+
+
+@np_random_state("seed")
+def spring_layout(
+    G,
+    k=None,
+    pos=None,
+    fixed=None,
+    iterations=50,
+    threshold=1e-4,
+    weight="weight",
+    scale=1,
+    center=None,
+    dim=2,
+    seed=None,
+    store_pos_as=None,
+    *,
+    method="auto",
+    gravity=1.0,
+):
+    """Position nodes using Fruchterman-Reingold force-directed algorithm.
+
+    The algorithm simulates a force-directed representation of the network
+    treating edges as springs holding nodes close, while treating nodes
+    as repelling objects, sometimes called an anti-gravity force.
+    Simulation continues until the positions are close to an equilibrium.
+
+    There are some hard-coded values: minimal distance between
+    nodes (0.01) and "temperature" of 0.1 to ensure nodes don't fly away.
+    During the simulation, `k` helps determine the distance between nodes,
+    though `scale` and `center` determine the size and place after
+    rescaling occurs at the end of the simulation.
+
+    Fixing some nodes doesn't allow them to move in the simulation.
+    It also turns off the rescaling feature at the simulation's end.
+    In addition, setting `scale` to `None` turns off rescaling.
+
+    Parameters
+    ----------
+    G : NetworkX graph or list of nodes
+        A position will be assigned to every node in G.
+
+    k : float (default=None)
+        Optimal distance between nodes.  If None the distance is set to
+        1/sqrt(n) where n is the number of nodes.  Increase this value
+        to move nodes farther apart.
+
+    pos : dict or None  optional (default=None)
+        Initial positions for nodes as a dictionary with node as keys
+        and values as a coordinate list or tuple.  If None, then use
+        random initial positions.
+
+    fixed : list or None  optional (default=None)
+        Nodes to keep fixed at initial position.
+        Nodes not in ``G.nodes`` are ignored.
+        ValueError raised if `fixed` specified and `pos` not.
+
+    iterations : int  optional (default=50)
+        Maximum number of iterations taken
+
+    threshold: float optional (default = 1e-4)
+        Threshold for relative error in node position changes.
+        The iteration stops if the error is below this threshold.
+
+    weight : string or None   optional (default='weight')
+        The edge attribute that holds the numerical value used for
+        the edge weight.  Larger means a stronger attractive force.
+        If None, then all edge weights are 1.
+
+    scale : number or None (default: 1)
+        Scale factor for positions. Not used unless `fixed is None`.
+        If scale is None, no rescaling is performed.
+
+    center : array-like or None
+        Coordinate pair around which to center the layout.
+        Not used unless `fixed is None`.
+
+    dim : int
+        Dimension of layout.
+
+    seed : int, RandomState instance or None  optional (default=None)
+        Used only for the initial positions in the algorithm.
+        Set the random state for deterministic node layouts.
+        If int, `seed` is the seed used by the random number generator,
+        if numpy.random.RandomState instance, `seed` is the random
+        number generator,
+        if None, the random number generator is the RandomState instance used
+        by numpy.random.
+
+    store_pos_as : str, default None
+        If non-None, the position of each node will be stored on the graph as
+        an attribute with this string as its name, which can be accessed with
+        ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.
+
+    method : str  optional (default='auto')
+        The method to compute the layout.
+        If 'force', the force-directed Fruchterman-Reingold algorithm [1]_ is used.
+        If 'energy', the energy-based optimization algorithm [2]_ is used with absolute
+        values of edge weights and gravitational forces acting on each connected component.
+        If 'auto', we use 'force' if ``len(G) < 500`` and 'energy' otherwise.
+
+    gravity: float optional (default=1.0)
+        Used only for the method='energy'.
+        The positive coefficient of gravitational forces per connected component.
+
+    Returns
+    -------
+    pos : dict
+        A dictionary of positions keyed by node
+
+    Examples
+    --------
+    >>> from pprint import pprint
+    >>> G = nx.path_graph(4)
+    >>> pos = nx.spring_layout(G)
+    >>> # suppress the returned dict and store on the graph directly
+    >>> _ = nx.spring_layout(G, seed=123, store_pos_as="pos")
+    >>> pprint(nx.get_node_attributes(G, "pos"))
+    {0: array([-0.61495802, -1.        ]),
+     1: array([-0.21789544, -0.35432583]),
+     2: array([0.21847843, 0.35527369]),
+     3: array([0.61437502, 0.99905215])}
+
+
+    # The same using longer but equivalent function name
+    >>> pos = nx.fruchterman_reingold_layout(G)
+
+    References
+    ----------
+    .. [1] Fruchterman, Thomas MJ, and Edward M. Reingold.
+           "Graph drawing by force-directed placement."
+           Software: Practice and experience 21, no. 11 (1991): 1129-1164.
+           http://dx.doi.org/10.1002/spe.4380211102
+    .. [2] Hamaguchi, Hiroki, Naoki Marumo, and Akiko Takeda.
+           "Initial Placement for Fruchterman--Reingold Force Model With Coordinate Newton Direction."
+           arXiv preprint arXiv:2412.20317 (2024).
+           https://arxiv.org/abs/2412.20317
+    """
+    import numpy as np
+
+    if method not in ("auto", "force", "energy"):
+        raise ValueError("the method must be either auto, force, or energy.")
+    if method == "auto":
+        method = "force" if len(G) < 500 else "energy"
+
+    G, center = _process_params(G, center, dim)
+
+    if fixed is not None:
+        if pos is None:
+            raise ValueError("nodes are fixed without positions given")
+        for node in fixed:
+            if node not in pos:
+                raise ValueError("nodes are fixed without positions given")
+        nfixed = {node: i for i, node in enumerate(G)}
+        fixed = np.asarray([nfixed[node] for node in fixed if node in nfixed])
+
+    if pos is not None:
+        # Determine size of existing domain to adjust initial positions
+        dom_size = max(coord for pos_tup in pos.values() for coord in pos_tup)
+        if dom_size == 0:
+            dom_size = 1
+        pos_arr = seed.rand(len(G), dim) * dom_size + center
+
+        for i, n in enumerate(G):
+            if n in pos:
+                pos_arr[i] = np.asarray(pos[n])
+    else:
+        pos_arr = None
+        dom_size = 1
+
+    if len(G) == 0:
+        return {}
+    if len(G) == 1:
+        pos = {nx.utils.arbitrary_element(G.nodes()): center}
+        if store_pos_as is not None:
+            nx.set_node_attributes(G, pos, store_pos_as)
+        return pos
+
+    # Sparse matrix
+    if len(G) >= 500 or method == "energy":
+        A = nx.to_scipy_sparse_array(G, weight=weight, dtype="f")
+        if k is None and fixed is not None:
+            # We must adjust k by domain size for layouts not near 1x1
+            nnodes, _ = A.shape
+            k = dom_size / np.sqrt(nnodes)
+        pos = _sparse_fruchterman_reingold(
+            A, k, pos_arr, fixed, iterations, threshold, dim, seed, method, gravity
+        )
+    else:
+        A = nx.to_numpy_array(G, weight=weight)
+        if k is None and fixed is not None:
+            # We must adjust k by domain size for layouts not near 1x1
+            nnodes, _ = A.shape
+            k = dom_size / np.sqrt(nnodes)
+        pos = _fruchterman_reingold(
+            A, k, pos_arr, fixed, iterations, threshold, dim, seed
+        )
+    if fixed is None and scale is not None:
+        pos = rescale_layout(pos, scale=scale) + center
+    pos = dict(zip(G, pos))
+
+    if store_pos_as is not None:
+        nx.set_node_attributes(G, pos, store_pos_as)
+
+    return pos
+
+
+fruchterman_reingold_layout = spring_layout
+
+
+@np_random_state(7)
+def _fruchterman_reingold(
+    A, k=None, pos=None, fixed=None, iterations=50, threshold=1e-4, dim=2, seed=None
+):
+    # Position nodes in adjacency matrix A using Fruchterman-Reingold
+    # Entry point for NetworkX graph is fruchterman_reingold_layout()
+    import numpy as np
+
+    try:
+        nnodes, _ = A.shape
+    except AttributeError as err:
+        msg = "fruchterman_reingold() takes an adjacency matrix as input"
+        raise nx.NetworkXError(msg) from err
+
+    if pos is None:
+        # random initial positions
+        pos = np.asarray(seed.rand(nnodes, dim), dtype=A.dtype)
+    else:
+        # make sure positions are of same type as matrix
+        pos = pos.astype(A.dtype)
+
+    # optimal distance between nodes
+    if k is None:
+        k = np.sqrt(1.0 / nnodes)
+    # the initial "temperature"  is about .1 of domain area (=1x1)
+    # this is the largest step allowed in the dynamics.
+    # We need to calculate this in case our fixed positions force our domain
+    # to be much bigger than 1x1
+    t = max(max(pos.T[0]) - min(pos.T[0]), max(pos.T[1]) - min(pos.T[1])) * 0.1
+    # simple cooling scheme.
+    # linearly step down by dt on each iteration so last iteration is size dt.
+    dt = t / (iterations + 1)
+    delta = np.zeros((pos.shape[0], pos.shape[0], pos.shape[1]), dtype=A.dtype)
+    # the inscrutable (but fast) version
+    # this is still O(V^2)
+    # could use multilevel methods to speed this up significantly
+    for iteration in range(iterations):
+        # matrix of difference between points
+        delta = pos[:, np.newaxis, :] - pos[np.newaxis, :, :]
+        # distance between points
+        distance = np.linalg.norm(delta, axis=-1)
+        # enforce minimum distance of 0.01
+        np.clip(distance, 0.01, None, out=distance)
+        # displacement "force"
+        displacement = np.einsum(
+            "ijk,ij->ik", delta, (k * k / distance**2 - A * distance / k)
+        )
+        # update positions
+        length = np.linalg.norm(displacement, axis=-1)
+        # Threshold the minimum length prior to position scaling
+        # See gh-8113 for detailed discussion of the threshold
+        length = np.clip(length, a_min=0.01, a_max=None)
+        delta_pos = np.einsum("ij,i->ij", displacement, t / length)
+        if fixed is not None:
+            # don't change positions of fixed nodes
+            delta_pos[fixed] = 0.0
+        pos += delta_pos
+        # cool temperature
+        t -= dt
+        if (np.linalg.norm(delta_pos) / nnodes) < threshold:
+            break
+    return pos
+
+
+@np_random_state(7)
+def _sparse_fruchterman_reingold(
+    A,
+    k=None,
+    pos=None,
+    fixed=None,
+    iterations=50,
+    threshold=1e-4,
+    dim=2,
+    seed=None,
+    method="energy",
+    gravity=1.0,
+):
+    # Position nodes in adjacency matrix A using Fruchterman-Reingold
+    # Entry point for NetworkX graph is fruchterman_reingold_layout()
+    # Sparse version
+    import numpy as np
+    import scipy as sp
+
+    try:
+        nnodes, _ = A.shape
+    except AttributeError as err:
+        msg = "fruchterman_reingold() takes an adjacency matrix as input"
+        raise nx.NetworkXError(msg) from err
+
+    if pos is None:
+        # random initial positions
+        pos = np.asarray(seed.rand(nnodes, dim), dtype=A.dtype)
+    else:
+        # make sure positions are of same type as matrix
+        pos = pos.astype(A.dtype)
+
+    # no fixed nodes
+    if fixed is None:
+        fixed = []
+
+    # optimal distance between nodes
+    if k is None:
+        k = np.sqrt(1.0 / nnodes)
+
+    if method == "energy":
+        return _energy_fruchterman_reingold(
+            A, nnodes, k, pos, fixed, iterations, threshold, dim, gravity
+        )
+
+    # make sure we have a LIst of Lists representation
+    try:
+        A = A.tolil()
+    except AttributeError:
+        A = (sp.sparse.coo_array(A)).tolil()
+
+    # the initial "temperature"  is about .1 of domain area (=1x1)
+    # this is the largest step allowed in the dynamics.
+    t = max(max(pos.T[0]) - min(pos.T[0]), max(pos.T[1]) - min(pos.T[1])) * 0.1
+    # simple cooling scheme.
+    # linearly step down by dt on each iteration so last iteration is size dt.
+    dt = t / (iterations + 1)
+
+    displacement = np.zeros((dim, nnodes))
+    for iteration in range(iterations):
+        displacement *= 0
+        # loop over rows
+        for i in range(A.shape[0]):
+            if i in fixed:
+                continue
+            # difference between this row's node position and all others
+            delta = (pos[i] - pos).T
+            # distance between points
+            distance = np.sqrt((delta**2).sum(axis=0))
+            # enforce minimum distance of 0.01
+            distance = np.clip(distance, a_min=0.01, a_max=None)
+            # the adjacency matrix row
+            Ai = A.getrowview(i).toarray()  # TODO: revisit w/ sparse 1D container
+            # displacement "force"
+            displacement[:, i] += (
+                delta * (k * k / distance**2 - Ai * distance / k)
+            ).sum(axis=1)
+        # update positions
+        length = np.sqrt((displacement**2).sum(axis=0))
+        # Threshold the minimum length prior to position scaling
+        # See gh-8113 for detailed discussion of the threshold
+        length = np.clip(length, a_min=0.01, a_max=None)
+        delta_pos = (displacement * t / length).T
+        pos += delta_pos
+        # cool temperature
+        t -= dt
+        if (np.linalg.norm(delta_pos) / nnodes) < threshold:
+            break
+    return pos
+
+
+def _energy_fruchterman_reingold(
+    A, nnodes, k, pos, fixed, iterations, threshold, dim, gravity
+):
+    # Entry point for NetworkX graph is fruchterman_reingold_layout()
+    # energy-based version
+    import numpy as np
+    import scipy as sp
+
+    if gravity <= 0:
+        raise ValueError(f"the gravity must be positive.")
+
+    # make sure we have a Compressed Sparse Row format
+    try:
+        A = A.tocsr()
+    except AttributeError:
+        A = sp.sparse.csr_array(A)
+
+    # Take absolute values of edge weights and symmetrize it
+    A = np.abs(A)
+    A = (A + A.T) / 2
+
+    n_components, labels = sp.sparse.csgraph.connected_components(A, directed=False)
+    bincount = np.bincount(labels)
+    batchsize = 500
+
+    def _cost_FR(x):
+        pos = x.reshape((nnodes, dim))
+        grad = np.zeros((nnodes, dim))
+        cost = 0.0
+        for l in range(0, nnodes, batchsize):
+            r = min(l + batchsize, nnodes)
+            # difference between selected node positions and all others
+            delta = pos[l:r, np.newaxis, :] - pos[np.newaxis, :, :]
+            # distance between points with a minimum distance of 1e-5
+            distance2 = np.sum(delta * delta, axis=2)
+            distance2 = np.maximum(distance2, 1e-10)
+            distance = np.sqrt(distance2)
+            # temporary variable for calculation
+            Ad = A[l:r] * distance
+            # attractive forces and repulsive forces
+            grad[l:r] = 2 * np.einsum("ij,ijk->ik", Ad / k - k**2 / distance2, delta)
+            # integrated attractive forces
+            cost += np.sum(Ad * distance2) / (3 * k)
+            # integrated repulsive forces
+            cost -= k**2 * np.sum(np.log(distance))
+        # gravitational force from the centroids of connected components to (0.5, ..., 0.5)^T
+        centers = np.zeros((n_components, dim))
+        np.add.at(centers, labels, pos)
+        delta0 = centers / bincount[:, np.newaxis] - 0.5
+        grad += gravity * delta0[labels]
+        cost += gravity * 0.5 * np.sum(bincount * np.linalg.norm(delta0, axis=1) ** 2)
+        # fix positions of fixed nodes
+        grad[fixed] = 0.0
+        return cost, grad.ravel()
+
+    # Optimization of the energy function by L-BFGS algorithm
+    options = {"maxiter": iterations, "gtol": threshold}
+    return sp.optimize.minimize(
+        _cost_FR, pos.ravel(), method="L-BFGS-B", jac=True, options=options
+    ).x.reshape((nnodes, dim))
+
+
+def kamada_kawai_layout(
+    G,
+    dist=None,
+    pos=None,
+    weight="weight",
+    scale=1,
+    center=None,
+    dim=2,
+    store_pos_as=None,
+):
+    """Position nodes using Kamada-Kawai path-length cost-function.
+
+    Parameters
+    ----------
+    G : NetworkX graph or list of nodes
+        A position will be assigned to every node in G.
+
+    dist : dict (default=None)
+        A two-level dictionary of optimal distances between nodes,
+        indexed by source and destination node.
+        If None, the distance is computed using shortest_path_length().
+
+    pos : dict or None  optional (default=None)
+        Initial positions for nodes as a dictionary with node as keys
+        and values as a coordinate list or tuple.  If None, then use
+        circular_layout() for dim >= 2 and a linear layout for dim == 1.
+
+    weight : string or None   optional (default='weight')
+        The edge attribute that holds the numerical value used for
+        the edge weight.  If None, then all edge weights are 1.
+
+    scale : number (default: 1)
+        Scale factor for positions.
+
+    center : array-like or None
+        Coordinate pair around which to center the layout.
+
+    dim : int
+        Dimension of layout.
+
+    store_pos_as : str, default None
+        If non-None, the position of each node will be stored on the graph as
+        an attribute with this string as its name, which can be accessed with
+        ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.
+
+    Returns
+    -------
+    pos : dict
+        A dictionary of positions keyed by node
+
+    Examples
+    --------
+    >>> from pprint import pprint
+    >>> G = nx.path_graph(4)
+    >>> pos = nx.kamada_kawai_layout(G)
+    >>> # suppress the returned dict and store on the graph directly
+    >>> _ = nx.kamada_kawai_layout(G, store_pos_as="pos")
+    >>> pprint(nx.get_node_attributes(G, "pos"))
+    {0: array([0.99996577, 0.99366857]),
+     1: array([0.32913544, 0.33543827]),
+     2: array([-0.33544334, -0.32910684]),
+     3: array([-0.99365787, -1.        ])}
+    """
+    import numpy as np
+
+    G, center = _process_params(G, center, dim)
+    nNodes = len(G)
+    if nNodes == 0:
+        return {}
+
+    if dist is None:
+        dist = dict(nx.shortest_path_length(G, weight=weight))
+    dist_mtx = 1e6 * np.ones((nNodes, nNodes))
+    for row, nr in enumerate(G):
+        if nr not in dist:
+            continue
+        rdist = dist[nr]
+        for col, nc in enumerate(G):
+            if nc not in rdist:
+                continue
+            dist_mtx[row][col] = rdist[nc]
+
+    if pos is None:
+        if dim >= 3:
+            pos = random_layout(G, dim=dim)
+        elif dim == 2:
+            pos = circular_layout(G, dim=dim)
+        else:
+            pos = dict(zip(G, np.linspace(0, 1, len(G))))
+    pos_arr = np.array([pos[n] for n in G])
+
+    pos = _kamada_kawai_solve(dist_mtx, pos_arr, dim)
+
+    pos = rescale_layout(pos, scale=scale) + center
+    pos = dict(zip(G, pos))
+
+    if store_pos_as is not None:
+        nx.set_node_attributes(G, pos, store_pos_as)
+
+    return pos
+
+
+def _kamada_kawai_solve(dist_mtx, pos_arr, dim):
+    # Anneal node locations based on the Kamada-Kawai cost-function,
+    # using the supplied matrix of preferred inter-node distances,
+    # and starting locations.
+
+    import numpy as np
+    import scipy as sp
+
+    meanwt = 1e-3
+    costargs = (np, 1 / (dist_mtx + np.eye(dist_mtx.shape[0]) * 1e-3), meanwt, dim)
+
+    optresult = sp.optimize.minimize(
+        _kamada_kawai_costfn,
+        pos_arr.ravel(),
+        method="L-BFGS-B",
+        args=costargs,
+        jac=True,
+    )
+
+    return optresult.x.reshape((-1, dim))
+
+
+def _kamada_kawai_costfn(pos_vec, np, invdist, meanweight, dim):
+    # Cost-function and gradient for Kamada-Kawai layout algorithm
+    nNodes = invdist.shape[0]
+    pos_arr = pos_vec.reshape((nNodes, dim))
+
+    delta = pos_arr[:, np.newaxis, :] - pos_arr[np.newaxis, :, :]
+    nodesep = np.linalg.norm(delta, axis=-1)
+    direction = np.einsum("ijk,ij->ijk", delta, 1 / (nodesep + np.eye(nNodes) * 1e-3))
+
+    offset = nodesep * invdist - 1.0
+    offset[np.diag_indices(nNodes)] = 0
+
+    cost = 0.5 * np.sum(offset**2)
+    grad = np.einsum("ij,ij,ijk->ik", invdist, offset, direction) - np.einsum(
+        "ij,ij,ijk->jk", invdist, offset, direction
+    )
+
+    # Additional parabolic term to encourage mean position to be near origin:
+    sumpos = np.sum(pos_arr, axis=0)
+    cost += 0.5 * meanweight * np.sum(sumpos**2)
+    grad += meanweight * sumpos
+
+    return (cost, grad.ravel())
+
+
+def spectral_layout(G, weight="weight", scale=1, center=None, dim=2, store_pos_as=None):
+    """Position nodes using the eigenvectors of the graph Laplacian.
+
+    Using the unnormalized Laplacian, the layout shows possible clusters of
+    nodes which are an approximation of the ratio cut. If dim is the number of
+    dimensions then the positions are the entries of the dim eigenvectors
+    corresponding to the ascending eigenvalues starting from the second one.
+
+    Parameters
+    ----------
+    G : NetworkX graph or list of nodes
+        A position will be assigned to every node in G.
+
+    weight : string or None   optional (default='weight')
+        The edge attribute that holds the numerical value used for
+        the edge weight.  If None, then all edge weights are 1.
+
+    scale : number (default: 1)
+        Scale factor for positions.
+
+    center : array-like or None
+        Coordinate pair around which to center the layout.
+
+    dim : int
+        Dimension of layout.
+
+    store_pos_as : str, default None
+        If non-None, the position of each node will be stored on the graph as
+        an attribute with this string as its name, which can be accessed with
+        ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.
+
+    Returns
+    -------
+    pos : dict
+        A dictionary of positions keyed by node
+
+    Examples
+    --------
+    >>> from pprint import pprint
+    >>> G = nx.path_graph(4)
+    >>> pos = nx.spectral_layout(G)
+    >>> # suppress the returned dict and store on the graph directly
+    >>> _ = nx.spectral_layout(G, store_pos_as="pos")
+    >>> pprint(nx.get_node_attributes(G, "pos"))
+    {0: array([-1.        ,  0.76536686]),
+     1: array([-0.41421356, -0.76536686]),
+     2: array([ 0.41421356, -0.76536686]),
+     3: array([1.        , 0.76536686])}
+
+
+    Notes
+    -----
+    Directed graphs will be considered as undirected graphs when
+    positioning the nodes.
+
+    For larger graphs (>500 nodes) this will use the SciPy sparse
+    eigenvalue solver (ARPACK).
+    """
+    # handle some special cases that break the eigensolvers
+    import numpy as np
+
+    G, center = _process_params(G, center, dim)
+
+    if len(G) <= 2:
+        if len(G) == 0:
+            pos = np.array([])
+        elif len(G) == 1:
+            pos = np.array([center])
+        else:
+            pos = np.array([np.zeros(dim), np.array(center) * 2.0])
+        return dict(zip(G, pos))
+    try:
+        # Sparse matrix
+        if len(G) < 500:  # dense solver is faster for small graphs
+            raise ValueError
+        A = nx.to_scipy_sparse_array(G, weight=weight, dtype="d")
+        # Symmetrize directed graphs
+        if G.is_directed():
+            A = A + np.transpose(A)
+        pos = _sparse_spectral(A, dim)
+    except (ImportError, ValueError):
+        # Dense matrix
+        A = nx.to_numpy_array(G, weight=weight)
+        # Symmetrize directed graphs
+        if G.is_directed():
+            A += A.T
+        pos = _spectral(A, dim)
+
+    pos = rescale_layout(pos, scale=scale) + center
+    pos = dict(zip(G, pos))
+
+    if store_pos_as is not None:
+        nx.set_node_attributes(G, pos, store_pos_as)
+
+    return pos
+
+
+def _spectral(A, dim=2):
+    # Input adjacency matrix A
+    # Uses dense eigenvalue solver from numpy
+    import numpy as np
+
+    try:
+        nnodes, _ = A.shape
+    except AttributeError as err:
+        msg = "spectral() takes an adjacency matrix as input"
+        raise nx.NetworkXError(msg) from err
+
+    # form Laplacian matrix where D is diagonal of degrees
+    D = np.identity(nnodes, dtype=A.dtype) * np.sum(A, axis=1)
+    L = D - A
+
+    eigenvalues, eigenvectors = np.linalg.eig(L)
+    # sort and keep smallest nonzero
+    index = np.argsort(eigenvalues)[1 : dim + 1]  # 0 index is zero eigenvalue
+    return np.real(eigenvectors[:, index])
+
+
+def _sparse_spectral(A, dim=2):
+    # Input adjacency matrix A
+    # Uses sparse eigenvalue solver from scipy
+    # Could use multilevel methods here, see Koren "On spectral graph drawing"
+    import numpy as np
+    import scipy as sp
+
+    try:
+        nnodes, _ = A.shape
+    except AttributeError as err:
+        msg = "sparse_spectral() takes an adjacency matrix as input"
+        raise nx.NetworkXError(msg) from err
+
+    # form Laplacian matrix
+    D = sp.sparse.dia_array((A.sum(axis=1), 0), shape=(nnodes, nnodes)).tocsr()
+    L = D - A
+
+    k = dim + 1
+    # number of Lanczos vectors for ARPACK solver.What is the right scaling?
+    ncv = max(2 * k + 1, int(np.sqrt(nnodes)))
+    # return smallest k eigenvalues and eigenvectors
+    eigenvalues, eigenvectors = sp.sparse.linalg.eigsh(L, k, which="SM", ncv=ncv)
+    index = np.argsort(eigenvalues)[1:k]  # 0 index is zero eigenvalue
+    return np.real(eigenvectors[:, index])
+
+
+def planar_layout(G, scale=1, center=None, dim=2, store_pos_as=None):
+    """Position nodes without edge intersections.
+
+    Parameters
+    ----------
+    G : NetworkX graph or list of nodes
+        A position will be assigned to every node in G. If G is of type
+        nx.PlanarEmbedding, the positions are selected accordingly.
+
+    scale : number (default: 1)
+        Scale factor for positions.
+
+    center : array-like or None
+        Coordinate pair around which to center the layout.
+
+    dim : int
+        Dimension of layout.
+
+    store_pos_as : str, default None
+        If non-None, the position of each node will be stored on the graph as
+        an attribute with this string as its name, which can be accessed with
+        ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.
+
+    Returns
+    -------
+    pos : dict
+        A dictionary of positions keyed by node
+
+    Raises
+    ------
+    NetworkXException
+        If G is not planar
+
+    Examples
+    --------
+    >>> from pprint import pprint
+    >>> G = nx.path_graph(4)
+    >>> pos = nx.planar_layout(G)
+    >>> # suppress the returned dict and store on the graph directly
+    >>> _ = nx.planar_layout(G, store_pos_as="pos")
+    >>> pprint(nx.get_node_attributes(G, "pos"))
+    {0: array([-0.77777778, -0.33333333]),
+     1: array([ 1.        , -0.33333333]),
+     2: array([0.11111111, 0.55555556]),
+     3: array([-0.33333333,  0.11111111])}
+    """
+    import numpy as np
+
+    if dim != 2:
+        raise ValueError("can only handle 2 dimensions")
+
+    G, center = _process_params(G, center, dim)
+
+    if len(G) == 0:
+        return {}
+
+    if isinstance(G, nx.PlanarEmbedding):
+        embedding = G
+    else:
+        is_planar, embedding = nx.check_planarity(G)
+        if not is_planar:
+            raise nx.NetworkXException("G is not planar.")
+    pos = nx.combinatorial_embedding_to_pos(embedding)
+    node_list = list(embedding)
+    pos = np.vstack([pos[x] for x in node_list])
+    pos = pos.astype(np.float64)
+    pos = rescale_layout(pos, scale=scale) + center
+    pos = dict(zip(node_list, pos))
+    if store_pos_as is not None:
+        nx.set_node_attributes(G, pos, store_pos_as)
+    return pos
+
+
+def spiral_layout(
+    G,
+    scale=1,
+    center=None,
+    dim=2,
+    resolution=0.35,
+    equidistant=False,
+    store_pos_as=None,
+):
+    """Position nodes in a spiral layout.
+
+    Parameters
+    ----------
+    G : NetworkX graph or list of nodes
+        A position will be assigned to every node in G.
+
+    scale : number (default: 1)
+        Scale factor for positions.
+
+    center : array-like or None
+        Coordinate pair around which to center the layout.
+
+    dim : int, default=2
+        Dimension of layout, currently only dim=2 is supported.
+        Other dimension values result in a ValueError.
+
+    resolution : float, default=0.35
+        The compactness of the spiral layout returned.
+        Lower values result in more compressed spiral layouts.
+
+    equidistant : bool, default=False
+        If True, nodes will be positioned equidistant from each other
+        by decreasing angle further from center.
+        If False, nodes will be positioned at equal angles
+        from each other by increasing separation further from center.
+
+    store_pos_as : str, default None
+        If non-None, the position of each node will be stored on the graph as
+        an attribute with this string as its name, which can be accessed with
+        ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.
+
+    Returns
+    -------
+    pos : dict
+        A dictionary of positions keyed by node
+
+    Raises
+    ------
+    ValueError
+        If dim != 2
+
+    Examples
+    --------
+    >>> from pprint import pprint
+    >>> G = nx.path_graph(4)
+    >>> pos = nx.spiral_layout(G)
+    >>> nx.draw(G, pos=pos)
+    >>> # suppress the returned dict and store on the graph directly
+    >>> _ = nx.spiral_layout(G, store_pos_as="pos")
+    >>> pprint(nx.get_node_attributes(G, "pos"))
+    {0: array([-0.64153279, -0.68555087]),
+     1: array([-0.03307913, -0.46344795]),
+     2: array([0.34927952, 0.14899882]),
+     3: array([0.32533239, 1.        ])}
+
+    Notes
+    -----
+    This algorithm currently only works in two dimensions.
+
+    """
+    import numpy as np
+
+    if dim != 2:
+        raise ValueError("can only handle 2 dimensions")
+
+    G, center = _process_params(G, center, dim)
+
+    if len(G) == 0:
+        return {}
+    if len(G) == 1:
+        pos = {nx.utils.arbitrary_element(G): center}
+        if store_pos_as is not None:
+            nx.set_node_attributes(G, pos, store_pos_as)
+        return pos
+
+    pos = []
+    if equidistant:
+        chord = 1
+        step = 0.5
+        theta = resolution
+        theta += chord / (step * theta)
+        for _ in range(len(G)):
+            r = step * theta
+            theta += chord / r
+            pos.append([np.cos(theta) * r, np.sin(theta) * r])
+
+    else:
+        dist = np.arange(len(G), dtype=float)
+        angle = resolution * dist
+        pos = np.transpose(dist * np.array([np.cos(angle), np.sin(angle)]))
+
+    pos = rescale_layout(np.array(pos), scale=scale) + center
+
+    pos = dict(zip(G, pos))
+
+    if store_pos_as is not None:
+        nx.set_node_attributes(G, pos, store_pos_as)
+
+    return pos
+
+
+def multipartite_layout(
+    G, subset_key="subset", align="vertical", scale=1, center=None, store_pos_as=None
+):
+    """Position nodes in layers of straight lines.
+
+    Parameters
+    ----------
+    G : NetworkX graph or list of nodes
+        A position will be assigned to every node in G.
+
+    subset_key : string or dict (default='subset')
+        If a string, the key of node data in G that holds the node subset.
+        If a dict, keyed by layer number to the nodes in that layer/subset.
+
+    align : string (default='vertical')
+        The alignment of nodes. Vertical or horizontal.
+
+    scale : number (default: 1)
+        Scale factor for positions.
+
+    center : array-like or None
+        Coordinate pair around which to center the layout.
+
+    store_pos_as : str, default None
+        If non-None, the position of each node will be stored on the graph as
+        an attribute with this string as its name, which can be accessed with
+        ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.
+
+    Returns
+    -------
+    pos : dict
+        A dictionary of positions keyed by node.
+
+    Examples
+    --------
+    >>> G = nx.complete_multipartite_graph(28, 16, 10)
+    >>> pos = nx.multipartite_layout(G)
+    >>> # suppress the returned dict and store on the graph directly
+    >>> G = nx.complete_multipartite_graph(28, 16, 10)
+    >>> _ = nx.multipartite_layout(G, store_pos_as="pos")
+
+    or use a dict to provide the layers of the layout
+
+    >>> G = nx.Graph([(0, 1), (1, 2), (1, 3), (3, 4)])
+    >>> layers = {"a": [0], "b": [1], "c": [2, 3], "d": [4]}
+    >>> pos = nx.multipartite_layout(G, subset_key=layers)
+
+    Notes
+    -----
+    This algorithm currently only works in two dimensions and does not
+    try to minimize edge crossings.
+
+    Network does not need to be a complete multipartite graph. As long as nodes
+    have subset_key data, they will be placed in the corresponding layers.
+
+    """
+    import numpy as np
+
+    if align not in ("vertical", "horizontal"):
+        msg = "align must be either vertical or horizontal."
+        raise ValueError(msg)
+
+    G, center = _process_params(G, center=center, dim=2)
+    if len(G) == 0:
+        return {}
+
+    try:
+        # check if subset_key is dict-like
+        if len(G) != sum(len(nodes) for nodes in subset_key.values()):
+            raise nx.NetworkXError(
+                "all nodes must be in one subset of `subset_key` dict"
+            )
+    except AttributeError:
+        # subset_key is not a dict, hence a string
+        node_to_subset = nx.get_node_attributes(G, subset_key)
+        if len(node_to_subset) != len(G):
+            raise nx.NetworkXError(
+                f"all nodes need a subset_key attribute: {subset_key}"
+            )
+        subset_key = nx.utils.groups(node_to_subset)
+
+    # Sort by layer, if possible
+    try:
+        layers = dict(sorted(subset_key.items()))
+    except TypeError:
+        layers = subset_key
+
+    pos = None
+    nodes = []
+    width = len(layers)
+    for i, layer in enumerate(layers.values()):
+        height = len(layer)
+        xs = np.repeat(i, height)
+        ys = np.arange(0, height, dtype=float)
+        offset = ((width - 1) / 2, (height - 1) / 2)
+        layer_pos = np.column_stack([xs, ys]) - offset
+        if pos is None:
+            pos = layer_pos
+        else:
+            pos = np.concatenate([pos, layer_pos])
+        nodes.extend(layer)
+    pos = rescale_layout(pos, scale=scale) + center
+    if align == "horizontal":
+        pos = pos[:, ::-1]  # swap x and y coords
+    pos = dict(zip(nodes, pos))
+
+    if store_pos_as is not None:
+        nx.set_node_attributes(G, pos, store_pos_as)
+
+    return pos
+
+
+@np_random_state("seed")
+def arf_layout(
+    G,
+    pos=None,
+    scaling=1,
+    a=1.1,
+    etol=1e-6,
+    dt=1e-3,
+    max_iter=1000,
+    *,
+    seed=None,
+    store_pos_as=None,
+):
+    """Arf layout for networkx
+
+    The attractive and repulsive forces (arf) layout [1] improves the spring
+    layout in three ways. First, it prevents congestion of highly connected nodes
+    due to strong forcing between nodes. Second, it utilizes the layout space
+    more effectively by preventing large gaps that spring layout tends to create.
+    Lastly, the arf layout represents symmetries in the layout better than the
+    default spring layout.
+
+    Parameters
+    ----------
+    G : nx.Graph or nx.DiGraph
+        Networkx graph.
+    pos : dict
+        Initial  position of  the nodes.  If set  to None  a
+        random layout will be used.
+    scaling : float
+        Scales the radius of the circular layout space.
+    a : float
+        Strength of springs between connected nodes. Should be larger than 1.
+        The greater a, the clearer the separation of unconnected sub clusters.
+    etol : float
+        Gradient sum of spring forces must be larger than `etol` before successful
+        termination.
+    dt : float
+        Time step for force differential equation simulations.
+    max_iter : int
+        Max iterations before termination of the algorithm.
+    seed : int, RandomState instance or None  optional (default=None)
+        Set the random state for deterministic node layouts.
+        If int, `seed` is the seed used by the random number generator,
+        if numpy.random.RandomState instance, `seed` is the random
+        number generator,
+        if None, the random number generator is the RandomState instance used
+        by numpy.random.
+    store_pos_as : str, default None
+        If non-None, the position of each node will be stored on the graph as
+        an attribute with this string as its name, which can be accessed with
+        ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.
+
+    Returns
+    -------
+    pos : dict
+        A dictionary of positions keyed by node.
+
+    Examples
+    --------
+    >>> G = nx.grid_graph((5, 5))
+    >>> pos = nx.arf_layout(G)
+    >>> # suppress the returned dict and store on the graph directly
+    >>> G = nx.grid_graph((5, 5))
+    >>> _ = nx.arf_layout(G, store_pos_as="pos")
+
+    References
+    ----------
+    .. [1] "Self-Organization Applied to Dynamic Network Layout", M. Geipel,
+            International Journal of Modern Physics C, 2007, Vol 18, No 10,
+            pp. 1537-1549.
+            https://doi.org/10.1142/S0129183107011558 https://arxiv.org/abs/0704.1748
+    """
+    import warnings
+
+    import numpy as np
+
+    if a <= 1:
+        msg = "The parameter a should be larger than 1"
+        raise ValueError(msg)
+
+    pos_tmp = nx.random_layout(G, seed=seed)
+    if pos is None:
+        pos = pos_tmp
+    else:
+        for node in G.nodes():
+            if node not in pos:
+                pos[node] = pos_tmp[node].copy()
+
+    # Initialize spring constant matrix
+    N = len(G)
+    # No nodes no computation
+    if N == 0:
+        return pos
+
+    # init force of springs
+    K = np.ones((N, N)) - np.eye(N)
+    node_order = {node: i for i, node in enumerate(G)}
+    for x, y in G.edges():
+        if x != y:
+            idx, jdx = (node_order[i] for i in (x, y))
+            K[idx, jdx] = a
+
+    # vectorize values
+    p = np.asarray(list(pos.values()))
+
+    # equation 10 in [1]
+    rho = scaling * np.sqrt(N)
+
+    # looping variables
+    error = etol + 1
+    n_iter = 0
+    while error > etol:
+        diff = p[:, np.newaxis] - p[np.newaxis]
+        A = np.linalg.norm(diff, axis=-1)[..., np.newaxis]
+        # attraction_force - repulsions force
+        # suppress nans due to division; caused by diagonal set to zero.
+        # Does not affect the computation due to nansum
+        with warnings.catch_warnings():
+            warnings.simplefilter("ignore")
+            change = K[..., np.newaxis] * diff - rho / A * diff
+        change = np.nansum(change, axis=0)
+        p += change * dt
+
+        error = np.linalg.norm(change, axis=-1).sum()
+        if n_iter > max_iter:
+            break
+        n_iter += 1
+
+    pos = dict(zip(G.nodes(), p))
+
+    if store_pos_as is not None:
+        nx.set_node_attributes(G, pos, store_pos_as)
+
+    return pos
+
+
+@np_random_state("seed")
+@nx._dispatchable(edge_attrs="weight", mutates_input={"store_pos_as": 15})
+def forceatlas2_layout(
+    G,
+    pos=None,
+    *,
+    max_iter=100,
+    jitter_tolerance=1.0,
+    scaling_ratio=2.0,
+    gravity=1.0,
+    distributed_action=False,
+    strong_gravity=False,
+    node_mass=None,
+    node_size=None,
+    weight=None,
+    linlog=False,
+    seed=None,
+    dim=2,
+    store_pos_as=None,
+):
+    """Position nodes using the ForceAtlas2 force-directed layout algorithm.
+
+    This function applies the ForceAtlas2 layout algorithm [1]_ to a NetworkX graph,
+    positioning the nodes in a way that visually represents the structure of the graph.
+    The algorithm uses physical simulation to minimize the energy of the system,
+    resulting in a more readable layout.
+
+    Parameters
+    ----------
+    G : nx.Graph
+        A NetworkX graph to be laid out.
+    pos : dict or None, optional
+        Initial positions of the nodes. If None, random initial positions are used.
+    max_iter : int (default: 100)
+        Number of iterations for the layout optimization.
+    jitter_tolerance : float (default: 1.0)
+        Controls the tolerance for adjusting the speed of layout generation.
+    scaling_ratio : float (default: 2.0)
+        Determines the scaling of attraction and repulsion forces.
+    gravity : float (default: 1.0)
+        Determines the amount of attraction on nodes to the center. Prevents islands
+        (i.e. weakly connected or disconnected parts of the graph)
+        from drifting away.
+    distributed_action : bool (default: False)
+        Distributes the attraction force evenly among nodes.
+    strong_gravity : bool (default: False)
+        Applies a strong gravitational pull towards the center.
+    node_mass : dict or None, optional
+        Maps nodes to their masses, influencing the attraction to other nodes.
+    node_size : dict or None, optional
+        Maps nodes to their sizes, preventing crowding by creating a halo effect.
+    weight : string or None, optional (default: None)
+        The edge attribute that holds the numerical value used for
+        the edge weight. If None, then all edge weights are 1.
+    linlog : bool (default: False)
+        Uses logarithmic attraction instead of linear.
+    seed : int, RandomState instance or None  optional (default=None)
+        Used only for the initial positions in the algorithm.
+        Set the random state for deterministic node layouts.
+        If int, `seed` is the seed used by the random number generator,
+        if numpy.random.RandomState instance, `seed` is the random
+        number generator,
+        if None, the random number generator is the RandomState instance used
+        by numpy.random.
+    dim : int (default: 2)
+        Sets the dimensions for the layout. Ignored if `pos` is provided.
+    store_pos_as : str, default None
+        If non-None, the position of each node will be stored on the graph as
+        an attribute with this string as its name, which can be accessed with
+        ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.
+
+    Examples
+    --------
+    >>> import networkx as nx
+    >>> G = nx.florentine_families_graph()
+    >>> pos = nx.forceatlas2_layout(G)
+    >>> nx.draw(G, pos=pos)
+    >>> # suppress the returned dict and store on the graph directly
+    >>> pos = nx.forceatlas2_layout(G, store_pos_as="pos")
+    >>> _ = nx.forceatlas2_layout(G, store_pos_as="pos")
+
+    References
+    ----------
+    .. [1] Jacomy, M., Venturini, T., Heymann, S., & Bastian, M. (2014).
+           ForceAtlas2, a continuous graph layout algorithm for handy network
+           visualization designed for the Gephi software. PloS one, 9(6), e98679.
+           https://doi.org/10.1371/journal.pone.0098679
+    """
+    import numpy as np
+
+    if len(G) == 0:
+        return {}
+    # parse optional pos positions
+    if pos is None:
+        pos = nx.random_layout(G, dim=dim, seed=seed)
+        pos_arr = np.array(list(pos.values()))
+    elif len(pos) == len(G):
+        pos_arr = np.array([pos[node].copy() for node in G])
+    else:
+        # set random node pos within the initial pos values
+        pos_init = np.array(list(pos.values()))
+        max_pos = pos_init.max(axis=0)
+        min_pos = pos_init.min(axis=0)
+        dim = max_pos.size
+        pos_arr = min_pos + seed.rand(len(G), dim) * (max_pos - min_pos)
+        for idx, node in enumerate(G):
+            if node in pos:
+                pos_arr[idx] = pos[node].copy()
+
+    mass = np.zeros(len(G))
+    size = np.zeros(len(G))
+
+    # Only adjust for size when the users specifies size other than default (1)
+    adjust_sizes = False
+    if node_size is None:
+        node_size = {}
+    else:
+        adjust_sizes = True
+
+    if node_mass is None:
+        node_mass = {}
+
+    for idx, node in enumerate(G):
+        mass[idx] = node_mass.get(node, G.degree(node) + 1)
+        size[idx] = node_size.get(node, 1)
+
+    n = len(G)
+    gravities = np.zeros((n, dim))
+    attraction = np.zeros((n, dim))
+    repulsion = np.zeros((n, dim))
+    A = nx.to_numpy_array(G, weight=weight)
+
+    def estimate_factor(n, swing, traction, speed, speed_efficiency, jitter_tolerance):
+        """Computes the scaling factor for the force in the ForceAtlas2 layout algorithm.
+
+        This   helper  function   adjusts   the  speed   and
+        efficiency  of the  layout generation  based on  the
+        current state of  the system, such as  the number of
+        nodes, current swing, and traction forces.
+
+        Parameters
+        ----------
+        n : int
+            Number of nodes in the graph.
+        swing : float
+            The current swing, representing the oscillation of the nodes.
+        traction : float
+            The current traction force, representing the attraction between nodes.
+        speed : float
+            The current speed of the layout generation.
+        speed_efficiency : float
+            The efficiency of the current speed, influencing how fast the layout converges.
+        jitter_tolerance : float
+            The tolerance for jitter, affecting how much speed adjustment is allowed.
+
+        Returns
+        -------
+        tuple
+            A tuple containing the updated speed and speed efficiency.
+
+        Notes
+        -----
+        This function is a part of the ForceAtlas2 layout algorithm and is used to dynamically adjust the
+        layout parameters to achieve an optimal and stable visualization.
+
+        """
+        import numpy as np
+
+        # estimate jitter
+        opt_jitter = 0.05 * np.sqrt(n)
+        min_jitter = np.sqrt(opt_jitter)
+        max_jitter = 10
+        min_speed_efficiency = 0.05
+
+        other = min(max_jitter, opt_jitter * traction / n**2)
+        jitter = jitter_tolerance * max(min_jitter, other)
+
+        if swing / traction > 2.0:
+            if speed_efficiency > min_speed_efficiency:
+                speed_efficiency *= 0.5
+            jitter = max(jitter, jitter_tolerance)
+        if swing == 0:
+            target_speed = np.inf
+        else:
+            target_speed = jitter * speed_efficiency * traction / swing
+
+        if swing > jitter * traction:
+            if speed_efficiency > min_speed_efficiency:
+                speed_efficiency *= 0.7
+        elif speed < 1000:
+            speed_efficiency *= 1.3
+
+        max_rise = 0.5
+        speed = speed + min(target_speed - speed, max_rise * speed)
+        return speed, speed_efficiency
+
+    speed = 1
+    speed_efficiency = 1
+    swing = 1
+    traction = 1
+    for _ in range(max_iter):
+        # compute pairwise difference
+        diff = pos_arr[:, None] - pos_arr[None]
+        # compute pairwise distance
+        distance = np.linalg.norm(diff, axis=-1)
+
+        # linear attraction
+        if linlog:
+            attraction = -np.log(1 + distance) / distance
+            np.fill_diagonal(attraction, 0)
+            attraction = np.einsum("ij, ij -> ij", attraction, A)
+            attraction = np.einsum("ijk, ij -> ik", diff, attraction)
+
+        else:
+            attraction = -np.einsum("ijk, ij -> ik", diff, A)
+
+        if distributed_action:
+            attraction /= mass[:, None]
+
+        # repulsion
+        tmp = mass[:, None] @ mass[None]
+        if adjust_sizes:
+            distance += -size[:, None] - size[None]
+
+        d2 = distance**2
+        # remove self-interaction
+        np.fill_diagonal(tmp, 0)
+        np.fill_diagonal(d2, 1)
+        factor = (tmp / d2) * scaling_ratio
+        repulsion = np.einsum("ijk, ij -> ik", diff, factor)
+
+        # gravity
+        pos_centered = pos_arr - np.mean(pos_arr, axis=0)
+        if strong_gravity:
+            gravities = -gravity * mass[:, None] * pos_centered
+        else:
+            # hide warnings for divide by zero. Then change nan to 0
+            with np.errstate(divide="ignore", invalid="ignore"):
+                unit_vec = pos_centered / np.linalg.norm(pos_centered, axis=-1)[:, None]
+            unit_vec = np.nan_to_num(unit_vec, nan=0)
+            gravities = -gravity * mass[:, None] * unit_vec
+
+        # total forces
+        update = attraction + repulsion + gravities
+
+        # compute total swing and traction
+        swing += (mass * np.linalg.norm(pos_arr - update, axis=-1)).sum()
+        traction += (0.5 * mass * np.linalg.norm(pos_arr + update, axis=-1)).sum()
+
+        speed, speed_efficiency = estimate_factor(
+            n,
+            swing,
+            traction,
+            speed,
+            speed_efficiency,
+            jitter_tolerance,
+        )
+
+        # update pos
+        if adjust_sizes:
+            df = np.linalg.norm(update, axis=-1)
+            swinging = mass * df
+            factor = 0.1 * speed / (1 + np.sqrt(speed * swinging))
+            factor = np.minimum(factor * df, 10.0 * np.ones(df.shape)) / df
+        else:
+            swinging = mass * np.linalg.norm(update, axis=-1)
+            factor = speed / (1 + np.sqrt(speed * swinging))
+
+        factored_update = update * factor[:, None]
+        pos_arr += factored_update
+        if abs(factored_update).sum() < 1e-10:
+            break
+
+    pos = dict(zip(G, pos_arr))
+    if store_pos_as is not None:
+        nx.set_node_attributes(G, pos, store_pos_as)
+
+    return pos
+
+
+def rescale_layout(pos, scale=1):
+    """Returns scaled position array to (-scale, scale) in all axes.
+
+    The function acts on NumPy arrays which hold position information.
+    Each position is one row of the array. The dimension of the space
+    equals the number of columns. Each coordinate in one column.
+
+    To rescale, the mean (center) is subtracted from each axis separately.
+    Then all values are scaled so that the largest magnitude value
+    from all axes equals `scale` (thus, the aspect ratio is preserved).
+    The resulting NumPy Array is returned (order of rows unchanged).
+
+    Parameters
+    ----------
+    pos : numpy array
+        positions to be scaled. Each row is a position.
+
+    scale : number (default: 1)
+        The size of the resulting extent in all directions.
+
+    attribute : str, default None
+        If non-None, the position of each node will be stored on the graph as
+        an attribute named `attribute` which can be accessed with
+        `G.nodes[...][attribute]`. The function still returns the dictionary.
+
+    Returns
+    -------
+    pos : numpy array
+        scaled positions. Each row is a position.
+
+    See Also
+    --------
+    rescale_layout_dict
+    """
+    import numpy as np
+
+    # Find max length over all dimensions
+    pos -= pos.mean(axis=0)
+    lim = np.abs(pos).max()  # max coordinate for all axes
+    # rescale to (-scale, scale) in all directions, preserves aspect
+    if lim > 0:
+        pos *= scale / lim
+    return pos
+
+
+def rescale_layout_dict(pos, scale=1):
+    """Return a dictionary of scaled positions keyed by node
+
+    Parameters
+    ----------
+    pos : A dictionary of positions keyed by node
+
+    scale : number (default: 1)
+        The size of the resulting extent in all directions.
+
+    Returns
+    -------
+    pos : A dictionary of positions keyed by node
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> pos = {0: np.array((0, 0)), 1: np.array((1, 1)), 2: np.array((0.5, 0.5))}
+    >>> nx.rescale_layout_dict(pos)
+    {0: array([-1., -1.]), 1: array([1., 1.]), 2: array([0., 0.])}
+
+    >>> pos = {0: np.array((0, 0)), 1: np.array((-1, 1)), 2: np.array((-0.5, 0.5))}
+    >>> nx.rescale_layout_dict(pos, scale=2)
+    {0: array([ 2., -2.]), 1: array([-2.,  2.]), 2: array([0., 0.])}
+
+    See Also
+    --------
+    rescale_layout
+    """
+    import numpy as np
+
+    if not pos:  # empty_graph
+        return {}
+    pos_v = np.array(list(pos.values()))
+    pos_v = rescale_layout(pos_v, scale=scale)
+    return dict(zip(pos, pos_v))
+
+
+def bfs_layout(G, start, *, align="vertical", scale=1, center=None, store_pos_as=None):
+    """Position nodes according to breadth-first search algorithm.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        A position will be assigned to every node in G.
+
+    start : node in `G`
+        Starting node for bfs
+
+    align : string (default='vertical')
+        The alignment of nodes within a layer, either `"vertical"` or
+        `"horizontal"`.
+
+    scale : number (default: 1)
+        Scale factor for positions.
+
+    center : array-like or None
+        Coordinate pair around which to center the layout.
+
+    store_pos_as : str, default None
+        If non-None, the position of each node will be stored on the graph as
+        an attribute with this string as its name, which can be accessed with
+        ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.
+
+    Returns
+    -------
+    pos : dict
+        A dictionary of positions keyed by node.
+
+    Examples
+    --------
+    >>> from pprint import pprint
+    >>> G = nx.path_graph(4)
+    >>> pos = nx.bfs_layout(G, 0)
+    >>> # suppress the returned dict and store on the graph directly
+    >>> _ = nx.bfs_layout(G, 0, store_pos_as="pos")
+    >>> pprint(nx.get_node_attributes(G, "pos"))
+    {0: array([-1.,  0.]),
+     1: array([-0.33333333,  0.        ]),
+     2: array([0.33333333, 0.        ]),
+     3: array([1., 0.])}
+
+
+
+    Notes
+    -----
+    This algorithm currently only works in two dimensions and does not
+    try to minimize edge crossings.
+
+    """
+    G, center = _process_params(G, center, 2)
+
+    # Compute layers with BFS
+    layers = dict(enumerate(nx.bfs_layers(G, start)))
+
+    if len(G) != sum(len(nodes) for nodes in layers.values()):
+        raise nx.NetworkXError(
+            "bfs_layout didn't include all nodes. Perhaps use input graph:\n"
+            "        G.subgraph(nx.node_connected_component(G, start))"
+        )
+
+    # Compute node positions with multipartite_layout
+    pos = multipartite_layout(
+        G, subset_key=layers, align=align, scale=scale, center=center
+    )
+
+    if store_pos_as is not None:
+        nx.set_node_attributes(G, pos, store_pos_as)
+
+    return pos
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/drawing/nx_agraph.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/drawing/nx_agraph.py
new file mode 100644
index 0000000000000000000000000000000000000000..897ab7f38a973bdf3ed1cbf7ac9504f4e93354f3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/drawing/nx_agraph.py
@@ -0,0 +1,470 @@
+"""
+***************
+Graphviz AGraph
+***************
+
+Interface to pygraphviz AGraph class.
+
+Examples
+--------
+>>> G = nx.complete_graph(5)
+>>> A = nx.nx_agraph.to_agraph(G)
+>>> H = nx.nx_agraph.from_agraph(A)
+
+See Also
+--------
+ - Pygraphviz: http://pygraphviz.github.io/
+ - Graphviz:      https://www.graphviz.org
+ - DOT Language:  http://www.graphviz.org/doc/info/lang.html
+"""
+
+import tempfile
+
+import networkx as nx
+
+__all__ = [
+    "from_agraph",
+    "to_agraph",
+    "write_dot",
+    "read_dot",
+    "graphviz_layout",
+    "pygraphviz_layout",
+    "view_pygraphviz",
+]
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def from_agraph(A, create_using=None):
+    """Returns a NetworkX Graph or DiGraph from a PyGraphviz graph.
+
+    Parameters
+    ----------
+    A : PyGraphviz AGraph
+      A graph created with PyGraphviz
+
+    create_using : NetworkX graph constructor, optional (default=None)
+       Graph type to create. If graph instance, then cleared before populated.
+       If `None`, then the appropriate Graph type is inferred from `A`.
+
+    Examples
+    --------
+    >>> K5 = nx.complete_graph(5)
+    >>> A = nx.nx_agraph.to_agraph(K5)
+    >>> G = nx.nx_agraph.from_agraph(A)
+
+    Notes
+    -----
+    The Graph G will have a dictionary G.graph_attr containing
+    the default graphviz attributes for graphs, nodes and edges.
+
+    Default node attributes will be in the dictionary G.node_attr
+    which is keyed by node.
+
+    Edge attributes will be returned as edge data in G.  With
+    edge_attr=False the edge data will be the Graphviz edge weight
+    attribute or the value 1 if no edge weight attribute is found.
+
+    """
+    if create_using is None:
+        if A.is_directed():
+            if A.is_strict():
+                create_using = nx.DiGraph
+            else:
+                create_using = nx.MultiDiGraph
+        else:
+            if A.is_strict():
+                create_using = nx.Graph
+            else:
+                create_using = nx.MultiGraph
+
+    # assign defaults
+    N = nx.empty_graph(0, create_using)
+    if A.name is not None:
+        N.name = A.name
+
+    # add graph attributes
+    N.graph.update(A.graph_attr)
+
+    # add nodes, attributes to N.node_attr
+    for n in A.nodes():
+        str_attr = {str(k): v for k, v in n.attr.items()}
+        N.add_node(str(n), **str_attr)
+
+    # add edges, assign edge data as dictionary of attributes
+    for e in A.edges():
+        u, v = str(e[0]), str(e[1])
+        attr = dict(e.attr)
+        str_attr = {str(k): v for k, v in attr.items()}
+        if not N.is_multigraph():
+            if e.name is not None:
+                str_attr["key"] = e.name
+            N.add_edge(u, v, **str_attr)
+        else:
+            N.add_edge(u, v, key=e.name, **str_attr)
+
+    # add default attributes for graph, nodes, and edges
+    # hang them on N.graph_attr
+    graph_default_dict = dict(A.graph_attr)
+    if graph_default_dict:
+        N.graph["graph"] = graph_default_dict
+    node_default_dict = dict(A.node_attr)
+    if node_default_dict and node_default_dict != {"label": "\\N"}:
+        N.graph["node"] = node_default_dict
+    edge_default_dict = dict(A.edge_attr)
+    if edge_default_dict:
+        N.graph["edge"] = edge_default_dict
+    return N
+
+
+def to_agraph(N):
+    """Returns a pygraphviz graph from a NetworkX graph N.
+
+    Parameters
+    ----------
+    N : NetworkX graph
+      A graph created with NetworkX
+
+    Examples
+    --------
+    >>> K5 = nx.complete_graph(5)
+    >>> A = nx.nx_agraph.to_agraph(K5)
+
+    Notes
+    -----
+    If N has an dict N.graph_attr an attempt will be made first
+    to copy properties attached to the graph (see from_agraph)
+    and then updated with the calling arguments if any.
+
+    """
+    try:
+        import pygraphviz
+    except ImportError as err:
+        raise ImportError("requires pygraphviz http://pygraphviz.github.io/") from err
+    directed = N.is_directed()
+    strict = nx.number_of_selfloops(N) == 0 and not N.is_multigraph()
+
+    A = pygraphviz.AGraph(name=N.name, strict=strict, directed=directed)
+
+    # default graph attributes
+    A.graph_attr.update(N.graph.get("graph", {}))
+    A.node_attr.update(N.graph.get("node", {}))
+    A.edge_attr.update(N.graph.get("edge", {}))
+
+    A.graph_attr.update(
+        (k, v) for k, v in N.graph.items() if k not in ("graph", "node", "edge")
+    )
+
+    # add nodes
+    for n, nodedata in N.nodes(data=True):
+        A.add_node(n)
+        # Add node data
+        a = A.get_node(n)
+        for key, val in nodedata.items():
+            if key == "pos":
+                a.attr["pos"] = f"{val[0]},{val[1]}!"
+            else:
+                a.attr[key] = str(val)
+
+    # loop over edges
+    if N.is_multigraph():
+        for u, v, key, edgedata in N.edges(data=True, keys=True):
+            str_edgedata = {k: str(v) for k, v in edgedata.items() if k != "key"}
+            A.add_edge(u, v, key=str(key))
+            # Add edge data
+            a = A.get_edge(u, v)
+            a.attr.update(str_edgedata)
+
+    else:
+        for u, v, edgedata in N.edges(data=True):
+            str_edgedata = {k: str(v) for k, v in edgedata.items()}
+            A.add_edge(u, v)
+            # Add edge data
+            a = A.get_edge(u, v)
+            a.attr.update(str_edgedata)
+
+    return A
+
+
+def write_dot(G, path):
+    """Write NetworkX graph G to Graphviz dot format on path.
+
+    Parameters
+    ----------
+    G : graph
+       A networkx graph
+    path : filename
+       Filename or file handle to write
+
+    Notes
+    -----
+    To use a specific graph layout, call ``A.layout`` prior to `write_dot`.
+    Note that some graphviz layouts are not guaranteed to be deterministic,
+    see https://gitlab.com/graphviz/graphviz/-/issues/1767 for more info.
+    """
+    A = to_agraph(G)
+    A.write(path)
+    A.clear()
+    return
+
+
+@nx._dispatchable(name="agraph_read_dot", graphs=None, returns_graph=True)
+def read_dot(path):
+    """Returns a NetworkX graph from a dot file on path.
+
+    Parameters
+    ----------
+    path : file or string
+       File name or file handle to read.
+    """
+    try:
+        import pygraphviz
+    except ImportError as err:
+        raise ImportError(
+            "read_dot() requires pygraphviz http://pygraphviz.github.io/"
+        ) from err
+    A = pygraphviz.AGraph(file=path)
+    gr = from_agraph(A)
+    A.clear()
+    return gr
+
+
+def graphviz_layout(G, prog="neato", root=None, args=""):
+    """Create node positions for G using Graphviz.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+      A graph created with NetworkX
+    prog : string
+      Name of Graphviz layout program
+    root : string, optional
+      Root node for twopi layout
+    args : string, optional
+      Extra arguments to Graphviz layout program
+
+    Returns
+    -------
+    Dictionary of x, y, positions keyed by node.
+
+    Examples
+    --------
+    >>> G = nx.petersen_graph()
+    >>> pos = nx.nx_agraph.graphviz_layout(G)
+    >>> pos = nx.nx_agraph.graphviz_layout(G, prog="dot")
+
+    Notes
+    -----
+    This is a wrapper for pygraphviz_layout.
+
+    Note that some graphviz layouts are not guaranteed to be deterministic,
+    see https://gitlab.com/graphviz/graphviz/-/issues/1767 for more info.
+    """
+    return pygraphviz_layout(G, prog=prog, root=root, args=args)
+
+
+def pygraphviz_layout(G, prog="neato", root=None, args=""):
+    """Create node positions for G using Graphviz.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+      A graph created with NetworkX
+    prog : string
+      Name of Graphviz layout program
+    root : string, optional
+      Root node for twopi layout
+    args : string, optional
+      Extra arguments to Graphviz layout program
+
+    Returns
+    -------
+    node_pos : dict
+      Dictionary of x, y, positions keyed by node.
+
+    Examples
+    --------
+    >>> G = nx.petersen_graph()
+    >>> pos = nx.nx_agraph.graphviz_layout(G)
+    >>> pos = nx.nx_agraph.graphviz_layout(G, prog="dot")
+
+    Notes
+    -----
+    If you use complex node objects, they may have the same string
+    representation and GraphViz could treat them as the same node.
+    The layout may assign both nodes a single location. See Issue #1568
+    If this occurs in your case, consider relabeling the nodes just
+    for the layout computation using something similar to::
+
+        >>> H = nx.convert_node_labels_to_integers(G, label_attribute="node_label")
+        >>> H_layout = nx.nx_agraph.pygraphviz_layout(H, prog="dot")
+        >>> G_layout = {H.nodes[n]["node_label"]: p for n, p in H_layout.items()}
+
+    Note that some graphviz layouts are not guaranteed to be deterministic,
+    see https://gitlab.com/graphviz/graphviz/-/issues/1767 for more info.
+    """
+    try:
+        import pygraphviz
+    except ImportError as err:
+        raise ImportError("requires pygraphviz http://pygraphviz.github.io/") from err
+    if root is not None:
+        args += f"-Groot={root}"
+    A = to_agraph(G)
+    A.layout(prog=prog, args=args)
+    node_pos = {}
+    for n in G:
+        node = pygraphviz.Node(A, n)
+        try:
+            xs = node.attr["pos"].split(",")
+            node_pos[n] = tuple(float(x) for x in xs)
+        except:
+            print("no position for node", n)
+            node_pos[n] = (0.0, 0.0)
+    return node_pos
+
+
+@nx.utils.open_file(5, "w+b")
+def view_pygraphviz(
+    G, edgelabel=None, prog="dot", args="", suffix="", path=None, show=True
+):
+    """Views the graph G using the specified layout algorithm.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        The machine to draw.
+    edgelabel : str, callable, None
+        If a string, then it specifies the edge attribute to be displayed
+        on the edge labels. If a callable, then it is called for each
+        edge and it should return the string to be displayed on the edges.
+        The function signature of `edgelabel` should be edgelabel(data),
+        where `data` is the edge attribute dictionary.
+    prog : string
+        Name of Graphviz layout program.
+    args : str
+        Additional arguments to pass to the Graphviz layout program.
+    suffix : str
+        If `filename` is None, we save to a temporary file.  The value of
+        `suffix` will appear at the tail end of the temporary filename.
+    path : str, None
+        The filename used to save the image.  If None, save to a temporary
+        file.  File formats are the same as those from pygraphviz.agraph.draw.
+        Filenames ending in .gz or .bz2 will be compressed.
+    show : bool, default = True
+        Whether to display the graph with :mod:`PIL.Image.show`,
+        default is `True`. If `False`, the rendered graph is still available
+        at `path`.
+
+    Returns
+    -------
+    path : str
+        The filename of the generated image.
+    A : PyGraphviz graph
+        The PyGraphviz graph instance used to generate the image.
+
+    Notes
+    -----
+    If this function is called in succession too quickly, sometimes the
+    image is not displayed. So you might consider time.sleep(.5) between
+    calls if you experience problems.
+
+    Note that some graphviz layouts are not guaranteed to be deterministic,
+    see https://gitlab.com/graphviz/graphviz/-/issues/1767 for more info.
+
+    """
+    if not len(G):
+        raise nx.NetworkXException("An empty graph cannot be drawn.")
+
+    # If we are providing default values for graphviz, these must be set
+    # before any nodes or edges are added to the PyGraphviz graph object.
+    # The reason for this is that default values only affect incoming objects.
+    # If you change the default values after the objects have been added,
+    # then they inherit no value and are set only if explicitly set.
+
+    # to_agraph() uses these values.
+    attrs = ["edge", "node", "graph"]
+    for attr in attrs:
+        if attr not in G.graph:
+            G.graph[attr] = {}
+
+    # These are the default values.
+    edge_attrs = {"fontsize": "10"}
+    node_attrs = {
+        "style": "filled",
+        "fillcolor": "#0000FF40",
+        "height": "0.75",
+        "width": "0.75",
+        "shape": "circle",
+    }
+    graph_attrs = {}
+
+    def update_attrs(which, attrs):
+        # Update graph attributes. Return list of those which were added.
+        added = []
+        for k, v in attrs.items():
+            if k not in G.graph[which]:
+                G.graph[which][k] = v
+                added.append(k)
+
+    def clean_attrs(which, added):
+        # Remove added attributes
+        for attr in added:
+            del G.graph[which][attr]
+        if not G.graph[which]:
+            del G.graph[which]
+
+    # Update all default values
+    update_attrs("edge", edge_attrs)
+    update_attrs("node", node_attrs)
+    update_attrs("graph", graph_attrs)
+
+    # Convert to agraph, so we inherit default values
+    A = to_agraph(G)
+
+    # Remove the default values we added to the original graph.
+    clean_attrs("edge", edge_attrs)
+    clean_attrs("node", node_attrs)
+    clean_attrs("graph", graph_attrs)
+
+    # If the user passed in an edgelabel, we update the labels for all edges.
+    if edgelabel is not None:
+        if not callable(edgelabel):
+
+            def func(data):
+                return "".join(["  ", str(data[edgelabel]), "  "])
+
+        else:
+            func = edgelabel
+
+        # update all the edge labels
+        if G.is_multigraph():
+            for u, v, key, data in G.edges(keys=True, data=True):
+                # PyGraphviz doesn't convert the key to a string. See #339
+                edge = A.get_edge(u, v, str(key))
+                edge.attr["label"] = str(func(data))
+        else:
+            for u, v, data in G.edges(data=True):
+                edge = A.get_edge(u, v)
+                edge.attr["label"] = str(func(data))
+
+    if path is None:
+        ext = "png"
+        if suffix:
+            suffix = f"_{suffix}.{ext}"
+        else:
+            suffix = f".{ext}"
+        path = tempfile.NamedTemporaryFile(suffix=suffix, delete=False)
+    else:
+        # Assume the decorator worked and it is a file-object.
+        pass
+
+    # Write graph to file
+    A.draw(path=path, format=None, prog=prog, args=args)
+    path.close()
+
+    # Show graph in a new window (depends on platform configuration)
+    if show:
+        from PIL import Image
+
+        Image.open(path.name).show()
+
+    return path.name, A
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/drawing/nx_latex.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/drawing/nx_latex.py
new file mode 100644
index 0000000000000000000000000000000000000000..677def8e75144afe5d73fbdea9f5643222a4ea01
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/drawing/nx_latex.py
@@ -0,0 +1,570 @@
+r"""
+*****
+LaTeX
+*****
+
+Export NetworkX graphs in LaTeX format using the TikZ library within TeX/LaTeX.
+Usually, you will want the drawing to appear in a figure environment so
+you use ``to_latex(G, caption="A caption")``. If you want the raw
+drawing commands without a figure environment use :func:`to_latex_raw`.
+And if you want to write to a file instead of just returning the latex
+code as a string, use ``write_latex(G, "filename.tex", caption="A caption")``.
+
+To construct a figure with subfigures for each graph to be shown, provide
+``to_latex`` or ``write_latex`` a list of graphs, a list of subcaptions,
+and a number of rows of subfigures inside the figure.
+
+To be able to refer to the figures or subfigures in latex using ``\\ref``,
+the keyword ``latex_label`` is available for figures and `sub_labels` for
+a list of labels, one for each subfigure.
+
+We intend to eventually provide an interface to the TikZ Graph
+features which include e.g. layout algorithms.
+
+Let us know via github what you'd like to see available, or better yet
+give us some code to do it, or even better make a github pull request
+to add the feature.
+
+The TikZ approach
+=================
+Drawing options can be stored on the graph as node/edge attributes, or
+can be provided as dicts keyed by node/edge to a string of the options
+for that node/edge. Similarly a label can be shown for each node/edge
+by specifying the labels as graph node/edge attributes or by providing
+a dict keyed by node/edge to the text to be written for that node/edge.
+
+Options for the tikzpicture environment (e.g. "[scale=2]") can be provided
+via a keyword argument. Similarly default node and edge options can be
+provided through keywords arguments. The default node options are applied
+to the single TikZ "path" that draws all nodes (and no edges). The default edge
+options are applied to a TikZ "scope" which contains a path for each edge.
+
+Examples
+========
+>>> G = nx.path_graph(3)
+>>> nx.write_latex(G, "just_my_figure.tex", as_document=True)
+>>> nx.write_latex(G, "my_figure.tex", caption="A path graph", latex_label="fig1")
+>>> latex_code = nx.to_latex(G)  # a string rather than a file
+
+You can change many features of the nodes and edges.
+
+>>> G = nx.path_graph(4, create_using=nx.DiGraph)
+>>> pos = {n: (n, n) for n in G}  # nodes set on a line
+
+>>> G.nodes[0]["style"] = "blue"
+>>> G.nodes[2]["style"] = "line width=3,draw"
+>>> G.nodes[3]["label"] = "Stop"
+>>> G.edges[(0, 1)]["label"] = "1st Step"
+>>> G.edges[(0, 1)]["label_opts"] = "near start"
+>>> G.edges[(1, 2)]["style"] = "line width=3"
+>>> G.edges[(1, 2)]["label"] = "2nd Step"
+>>> G.edges[(2, 3)]["style"] = "green"
+>>> G.edges[(2, 3)]["label"] = "3rd Step"
+>>> G.edges[(2, 3)]["label_opts"] = "near end"
+
+>>> nx.write_latex(G, "latex_graph.tex", pos=pos, as_document=True)
+
+Then compile the LaTeX using something like ``pdflatex latex_graph.tex``
+and view the pdf file created: ``latex_graph.pdf``.
+
+If you want **subfigures** each containing one graph, you can input a list of graphs.
+
+>>> H1 = nx.path_graph(4)
+>>> H2 = nx.complete_graph(4)
+>>> H3 = nx.path_graph(8)
+>>> H4 = nx.complete_graph(8)
+>>> graphs = [H1, H2, H3, H4]
+>>> caps = ["Path 4", "Complete graph 4", "Path 8", "Complete graph 8"]
+>>> lbls = ["fig2a", "fig2b", "fig2c", "fig2d"]
+>>> nx.write_latex(graphs, "subfigs.tex", n_rows=2, sub_captions=caps, sub_labels=lbls)
+>>> latex_code = nx.to_latex(graphs, n_rows=2, sub_captions=caps, sub_labels=lbls)
+
+>>> node_color = {0: "red", 1: "orange", 2: "blue", 3: "gray!90"}
+>>> edge_width = {e: "line width=1.5" for e in H3.edges}
+>>> pos = nx.circular_layout(H3)
+>>> latex_code = nx.to_latex(H3, pos, node_options=node_color, edge_options=edge_width)
+>>> print(latex_code)
+\documentclass{report}
+\usepackage{tikz}
+\usepackage{subcaption}
+
+\begin{document}
+\begin{figure}
+  \begin{tikzpicture}
+      \draw
+        (1.0, 0.0) node[red] (0){0}
+        (0.707, 0.707) node[orange] (1){1}
+        (-0.0, 1.0) node[blue] (2){2}
+        (-0.707, 0.707) node[gray!90] (3){3}
+        (-1.0, -0.0) node (4){4}
+        (-0.707, -0.707) node (5){5}
+        (0.0, -1.0) node (6){6}
+        (0.707, -0.707) node (7){7};
+      \begin{scope}[-]
+        \draw[line width=1.5] (0) to (1);
+        \draw[line width=1.5] (1) to (2);
+        \draw[line width=1.5] (2) to (3);
+        \draw[line width=1.5] (3) to (4);
+        \draw[line width=1.5] (4) to (5);
+        \draw[line width=1.5] (5) to (6);
+        \draw[line width=1.5] (6) to (7);
+      \end{scope}
+    \end{tikzpicture}
+\end{figure}
+\end{document}
+
+Notes
+-----
+If you want to change the preamble/postamble of the figure/document/subfigure
+environment, use the keyword arguments: `figure_wrapper`, `document_wrapper`,
+`subfigure_wrapper`. The default values are stored in private variables
+e.g. ``nx.nx_layout._DOCUMENT_WRAPPER``
+
+References
+----------
+TikZ:          https://tikz.dev/
+
+TikZ options details:   https://tikz.dev/tikz-actions
+"""
+
+import networkx as nx
+
+__all__ = [
+    "to_latex_raw",
+    "to_latex",
+    "write_latex",
+]
+
+
+@nx.utils.not_implemented_for("multigraph")
+def to_latex_raw(
+    G,
+    pos="pos",
+    tikz_options="",
+    default_node_options="",
+    node_options="node_options",
+    node_label="label",
+    default_edge_options="",
+    edge_options="edge_options",
+    edge_label="label",
+    edge_label_options="edge_label_options",
+):
+    """Return a string of the LaTeX/TikZ code to draw `G`
+
+    This function produces just the code for the tikzpicture
+    without any enclosing environment.
+
+    Parameters
+    ==========
+    G : NetworkX graph
+        The NetworkX graph to be drawn
+    pos : string or dict (default "pos")
+        The name of the node attribute on `G` that holds the position of each node.
+        Positions can be sequences of length 2 with numbers for (x,y) coordinates.
+        They can also be strings to denote positions in TikZ style, such as (x, y)
+        or (angle:radius).
+        If a dict, it should be keyed by node to a position.
+        If an empty dict, a circular layout is computed by TikZ.
+    tikz_options : string
+        The tikzpicture options description defining the options for the picture.
+        Often large scale options like `[scale=2]`.
+    default_node_options : string
+        The draw options for a path of nodes. Individual node options override these.
+    node_options : string or dict
+        The name of the node attribute on `G` that holds the options for each node.
+        Or a dict keyed by node to a string holding the options for that node.
+    node_label : string or dict
+        The name of the node attribute on `G` that holds the node label (text)
+        displayed for each node. If the attribute is "" or not present, the node
+        itself is drawn as a string. LaTeX processing such as ``"$A_1$"`` is allowed.
+        Or a dict keyed by node to a string holding the label for that node.
+    default_edge_options : string
+        The options for the scope drawing all edges. The default is "[-]" for
+        undirected graphs and "[->]" for directed graphs.
+    edge_options : string or dict
+        The name of the edge attribute on `G` that holds the options for each edge.
+        If the edge is a self-loop and ``"loop" not in edge_options`` the option
+        "loop," is added to the options for the self-loop edge. Hence you can
+        use "[loop above]" explicitly, but the default is "[loop]".
+        Or a dict keyed by edge to a string holding the options for that edge.
+    edge_label : string or dict
+        The name of the edge attribute on `G` that holds the edge label (text)
+        displayed for each edge. If the attribute is "" or not present, no edge
+        label is drawn.
+        Or a dict keyed by edge to a string holding the label for that edge.
+    edge_label_options : string or dict
+        The name of the edge attribute on `G` that holds the label options for
+        each edge. For example, "[sloped,above,blue]". The default is no options.
+        Or a dict keyed by edge to a string holding the label options for that edge.
+
+    Returns
+    =======
+    latex_code : string
+       The text string which draws the desired graph(s) when compiled by LaTeX.
+
+    See Also
+    ========
+    to_latex
+    write_latex
+    """
+    i4 = "\n    "
+    i8 = "\n        "
+
+    # set up position dict
+    # TODO allow pos to be None and use a nice TikZ default
+    if not isinstance(pos, dict):
+        pos = nx.get_node_attributes(G, pos)
+    if not pos:
+        # circular layout with radius 2
+        pos = {n: f"({round(360.0 * i / len(G), 3)}:2)" for i, n in enumerate(G)}
+    for node in G:
+        if node not in pos:
+            raise nx.NetworkXError(f"node {node} has no specified pos {pos}")
+        posnode = pos[node]
+        if not isinstance(posnode, str):
+            try:
+                posx, posy = posnode
+                pos[node] = f"({round(posx, 3)}, {round(posy, 3)})"
+            except (TypeError, ValueError):
+                msg = f"position pos[{node}] is not 2-tuple or a string: {posnode}"
+                raise nx.NetworkXError(msg)
+
+    # set up all the dicts
+    if not isinstance(node_options, dict):
+        node_options = nx.get_node_attributes(G, node_options)
+    if not isinstance(node_label, dict):
+        node_label = nx.get_node_attributes(G, node_label)
+    if not isinstance(edge_options, dict):
+        edge_options = nx.get_edge_attributes(G, edge_options)
+    if not isinstance(edge_label, dict):
+        edge_label = nx.get_edge_attributes(G, edge_label)
+    if not isinstance(edge_label_options, dict):
+        edge_label_options = nx.get_edge_attributes(G, edge_label_options)
+
+    # process default options (add brackets or not)
+    topts = "" if tikz_options == "" else f"[{tikz_options.strip('[]')}]"
+    defn = "" if default_node_options == "" else f"[{default_node_options.strip('[]')}]"
+    linestyle = f"{'->' if G.is_directed() else '-'}"
+    if default_edge_options == "":
+        defe = "[" + linestyle + "]"
+    elif "-" in default_edge_options:
+        defe = default_edge_options
+    else:
+        defe = f"[{linestyle},{default_edge_options.strip('[]')}]"
+
+    # Construct the string line by line
+    result = "  \\begin{tikzpicture}" + topts
+    result += i4 + "  \\draw" + defn
+    # load the nodes
+    for n in G:
+        # node options goes inside square brackets
+        nopts = f"[{node_options[n].strip('[]')}]" if n in node_options else ""
+        # node text goes inside curly brackets {}
+        ntext = f"{{{node_label[n]}}}" if n in node_label else f"{{{n}}}"
+
+        result += i8 + f"{pos[n]} node{nopts} ({n}){ntext}"
+    result += ";\n"
+
+    # load the edges
+    result += "      \\begin{scope}" + defe
+    for edge in G.edges:
+        u, v = edge[:2]
+        e_opts = f"{edge_options[edge]}".strip("[]") if edge in edge_options else ""
+        # add loop options for selfloops if not present
+        if u == v and "loop" not in e_opts:
+            e_opts = "loop," + e_opts
+        e_opts = f"[{e_opts}]" if e_opts != "" else ""
+        # TODO -- handle bending of multiedges
+
+        els = edge_label_options[edge] if edge in edge_label_options else ""
+        # edge label options goes inside square brackets []
+        els = f"[{els.strip('[]')}]"
+        # edge text is drawn using the TikZ node command inside curly brackets {}
+        e_label = f" node{els} {{{edge_label[edge]}}}" if edge in edge_label else ""
+
+        result += i8 + f"\\draw{e_opts} ({u}) to{e_label} ({v});"
+
+    result += "\n      \\end{scope}\n    \\end{tikzpicture}\n"
+    return result
+
+
+_DOC_WRAPPER_TIKZ = r"""\documentclass{{report}}
+\usepackage{{tikz}}
+\usepackage{{subcaption}}
+
+\begin{{document}}
+{content}
+\end{{document}}"""
+
+
+_FIG_WRAPPER = r"""\begin{{figure}}
+{content}{caption}{label}
+\end{{figure}}"""
+
+
+_SUBFIG_WRAPPER = r"""  \begin{{subfigure}}{{{size}\textwidth}}
+{content}{caption}{label}
+  \end{{subfigure}}"""
+
+
+def to_latex(
+    Gbunch,
+    pos="pos",
+    tikz_options="",
+    default_node_options="",
+    node_options="node_options",
+    node_label="node_label",
+    default_edge_options="",
+    edge_options="edge_options",
+    edge_label="edge_label",
+    edge_label_options="edge_label_options",
+    caption="",
+    latex_label="",
+    sub_captions=None,
+    sub_labels=None,
+    n_rows=1,
+    as_document=True,
+    document_wrapper=_DOC_WRAPPER_TIKZ,
+    figure_wrapper=_FIG_WRAPPER,
+    subfigure_wrapper=_SUBFIG_WRAPPER,
+):
+    """Return latex code to draw the graph(s) in `Gbunch`
+
+    The TikZ drawing utility in LaTeX is used to draw the graph(s).
+    If `Gbunch` is a graph, it is drawn in a figure environment.
+    If `Gbunch` is an iterable of graphs, each is drawn in a subfigure environment
+    within a single figure environment.
+
+    If `as_document` is True, the figure is wrapped inside a document environment
+    so that the resulting string is ready to be compiled by LaTeX. Otherwise,
+    the string is ready for inclusion in a larger tex document using ``\\include``
+    or ``\\input`` statements.
+
+    Parameters
+    ==========
+    Gbunch : NetworkX graph or iterable of NetworkX graphs
+        The NetworkX graph to be drawn or an iterable of graphs
+        to be drawn inside subfigures of a single figure.
+    pos : string or list of strings
+        The name of the node attribute on `G` that holds the position of each node.
+        Positions can be sequences of length 2 with numbers for (x,y) coordinates.
+        They can also be strings to denote positions in TikZ style, such as (x, y)
+        or (angle:radius).
+        If a dict, it should be keyed by node to a position.
+        If an empty dict, a circular layout is computed by TikZ.
+        If you are drawing many graphs in subfigures, use a list of position dicts.
+    tikz_options : string
+        The tikzpicture options description defining the options for the picture.
+        Often large scale options like `[scale=2]`.
+    default_node_options : string
+        The draw options for a path of nodes. Individual node options override these.
+    node_options : string or dict
+        The name of the node attribute on `G` that holds the options for each node.
+        Or a dict keyed by node to a string holding the options for that node.
+    node_label : string or dict
+        The name of the node attribute on `G` that holds the node label (text)
+        displayed for each node. If the attribute is "" or not present, the node
+        itself is drawn as a string. LaTeX processing such as ``"$A_1$"`` is allowed.
+        Or a dict keyed by node to a string holding the label for that node.
+    default_edge_options : string
+        The options for the scope drawing all edges. The default is "[-]" for
+        undirected graphs and "[->]" for directed graphs.
+    edge_options : string or dict
+        The name of the edge attribute on `G` that holds the options for each edge.
+        If the edge is a self-loop and ``"loop" not in edge_options`` the option
+        "loop," is added to the options for the self-loop edge. Hence you can
+        use "[loop above]" explicitly, but the default is "[loop]".
+        Or a dict keyed by edge to a string holding the options for that edge.
+    edge_label : string or dict
+        The name of the edge attribute on `G` that holds the edge label (text)
+        displayed for each edge. If the attribute is "" or not present, no edge
+        label is drawn.
+        Or a dict keyed by edge to a string holding the label for that edge.
+    edge_label_options : string or dict
+        The name of the edge attribute on `G` that holds the label options for
+        each edge. For example, "[sloped,above,blue]". The default is no options.
+        Or a dict keyed by edge to a string holding the label options for that edge.
+    caption : string
+        The caption string for the figure environment
+    latex_label : string
+        The latex label used for the figure for easy referral from the main text
+    sub_captions : list of strings
+        The sub_caption string for each subfigure in the figure
+    sub_latex_labels : list of strings
+        The latex label for each subfigure in the figure
+    n_rows : int
+        The number of rows of subfigures to arrange for multiple graphs
+    as_document : bool
+        Whether to wrap the latex code in a document environment for compiling
+    document_wrapper : formatted text string with variable ``content``.
+        This text is called to evaluate the content embedded in a document
+        environment with a preamble setting up TikZ.
+    figure_wrapper : formatted text string
+        This text is evaluated with variables ``content``, ``caption`` and ``label``.
+        It wraps the content and if a caption is provided, adds the latex code for
+        that caption, and if a label is provided, adds the latex code for a label.
+    subfigure_wrapper : formatted text string
+        This text evaluate variables ``size``, ``content``, ``caption`` and ``label``.
+        It wraps the content and if a caption is provided, adds the latex code for
+        that caption, and if a label is provided, adds the latex code for a label.
+        The size is the vertical size of each row of subfigures as a fraction.
+
+    Returns
+    =======
+    latex_code : string
+        The text string which draws the desired graph(s) when compiled by LaTeX.
+
+    See Also
+    ========
+    write_latex
+    to_latex_raw
+    """
+    if hasattr(Gbunch, "adj"):
+        raw = to_latex_raw(
+            Gbunch,
+            pos,
+            tikz_options,
+            default_node_options,
+            node_options,
+            node_label,
+            default_edge_options,
+            edge_options,
+            edge_label,
+            edge_label_options,
+        )
+    else:  # iterator of graphs
+        sbf = subfigure_wrapper
+        size = 1 / n_rows
+
+        N = len(Gbunch)
+        if isinstance(pos, str | dict):
+            pos = [pos] * N
+        if sub_captions is None:
+            sub_captions = [""] * N
+        if sub_labels is None:
+            sub_labels = [""] * N
+        if not (len(Gbunch) == len(pos) == len(sub_captions) == len(sub_labels)):
+            raise nx.NetworkXError(
+                "length of Gbunch, sub_captions and sub_figures must agree"
+            )
+
+        raw = ""
+        for G, pos, subcap, sublbl in zip(Gbunch, pos, sub_captions, sub_labels):
+            subraw = to_latex_raw(
+                G,
+                pos,
+                tikz_options,
+                default_node_options,
+                node_options,
+                node_label,
+                default_edge_options,
+                edge_options,
+                edge_label,
+                edge_label_options,
+            )
+            cap = f"    \\caption{{{subcap}}}" if subcap else ""
+            lbl = f"\\label{{{sublbl}}}" if sublbl else ""
+            raw += sbf.format(size=size, content=subraw, caption=cap, label=lbl)
+            raw += "\n"
+
+    # put raw latex code into a figure environment and optionally into a document
+    raw = raw[:-1]
+    cap = f"\n  \\caption{{{caption}}}" if caption else ""
+    lbl = f"\\label{{{latex_label}}}" if latex_label else ""
+    fig = figure_wrapper.format(content=raw, caption=cap, label=lbl)
+    if as_document:
+        return document_wrapper.format(content=fig)
+    return fig
+
+
+@nx.utils.open_file(1, mode="w")
+def write_latex(Gbunch, path, **options):
+    """Write the latex code to draw the graph(s) onto `path`.
+
+    This convenience function creates the latex drawing code as a string
+    and writes that to a file ready to be compiled when `as_document` is True
+    or ready to be ``import`` ed or ``include`` ed into your main LaTeX document.
+
+    The `path` argument can be a string filename or a file handle to write to.
+
+    Parameters
+    ----------
+    Gbunch : NetworkX graph or iterable of NetworkX graphs
+        If Gbunch is a graph, it is drawn in a figure environment.
+        If Gbunch is an iterable of graphs, each is drawn in a subfigure
+        environment within a single figure environment.
+    path : string or file
+        Filename or file handle to write to.
+        Filenames ending in .gz or .bz2 will be compressed.
+    options : dict
+        By default, TikZ is used with options: (others are ignored)::
+
+            pos : string or dict or list
+                The name of the node attribute on `G` that holds the position of each node.
+                Positions can be sequences of length 2 with numbers for (x,y) coordinates.
+                They can also be strings to denote positions in TikZ style, such as (x, y)
+                or (angle:radius).
+                If a dict, it should be keyed by node to a position.
+                If an empty dict, a circular layout is computed by TikZ.
+                If you are drawing many graphs in subfigures, use a list of position dicts.
+            tikz_options : string
+                The tikzpicture options description defining the options for the picture.
+                Often large scale options like `[scale=2]`.
+            default_node_options : string
+                The draw options for a path of nodes. Individual node options override these.
+            node_options : string or dict
+                The name of the node attribute on `G` that holds the options for each node.
+                Or a dict keyed by node to a string holding the options for that node.
+            node_label : string or dict
+                The name of the node attribute on `G` that holds the node label (text)
+                displayed for each node. If the attribute is "" or not present, the node
+                itself is drawn as a string. LaTeX processing such as ``"$A_1$"`` is allowed.
+                Or a dict keyed by node to a string holding the label for that node.
+            default_edge_options : string
+                The options for the scope drawing all edges. The default is "[-]" for
+                undirected graphs and "[->]" for directed graphs.
+            edge_options : string or dict
+                The name of the edge attribute on `G` that holds the options for each edge.
+                If the edge is a self-loop and ``"loop" not in edge_options`` the option
+                "loop," is added to the options for the self-loop edge. Hence you can
+                use "[loop above]" explicitly, but the default is "[loop]".
+                Or a dict keyed by edge to a string holding the options for that edge.
+            edge_label : string or dict
+                The name of the edge attribute on `G` that holds the edge label (text)
+                displayed for each edge. If the attribute is "" or not present, no edge
+                label is drawn.
+                Or a dict keyed by edge to a string holding the label for that edge.
+            edge_label_options : string or dict
+                The name of the edge attribute on `G` that holds the label options for
+                each edge. For example, "[sloped,above,blue]". The default is no options.
+                Or a dict keyed by edge to a string holding the label options for that edge.
+            caption : string
+                The caption string for the figure environment
+            latex_label : string
+                The latex label used for the figure for easy referral from the main text
+            sub_captions : list of strings
+                The sub_caption string for each subfigure in the figure
+            sub_latex_labels : list of strings
+                The latex label for each subfigure in the figure
+            n_rows : int
+                The number of rows of subfigures to arrange for multiple graphs
+            as_document : bool
+                Whether to wrap the latex code in a document environment for compiling
+            document_wrapper : formatted text string with variable ``content``.
+                This text is called to evaluate the content embedded in a document
+                environment with a preamble setting up the TikZ syntax.
+            figure_wrapper : formatted text string
+                This text is evaluated with variables ``content``, ``caption`` and ``label``.
+                It wraps the content and if a caption is provided, adds the latex code for
+                that caption, and if a label is provided, adds the latex code for a label.
+            subfigure_wrapper : formatted text string
+                This text evaluate variables ``size``, ``content``, ``caption`` and ``label``.
+                It wraps the content and if a caption is provided, adds the latex code for
+                that caption, and if a label is provided, adds the latex code for a label.
+                The size is the vertical size of each row of subfigures as a fraction.
+
+    See Also
+    ========
+    to_latex
+    """
+    path.write(to_latex(Gbunch, **options))
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/drawing/nx_pydot.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/drawing/nx_pydot.py
new file mode 100644
index 0000000000000000000000000000000000000000..0fe5ceec97c5c3c85e5e64e05b4c02eb83978c3a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/drawing/nx_pydot.py
@@ -0,0 +1,361 @@
+"""
+*****
+Pydot
+*****
+
+Import and export NetworkX graphs in Graphviz dot format using pydot.
+
+Either this module or nx_agraph can be used to interface with graphviz.
+
+Examples
+--------
+>>> G = nx.complete_graph(5)
+>>> PG = nx.nx_pydot.to_pydot(G)
+>>> H = nx.nx_pydot.from_pydot(PG)
+
+See Also
+--------
+ - pydot:         https://github.com/erocarrera/pydot
+ - Graphviz:      https://www.graphviz.org
+ - DOT Language:  http://www.graphviz.org/doc/info/lang.html
+"""
+
+from locale import getpreferredencoding
+
+import networkx as nx
+from networkx.utils import open_file
+
+__all__ = [
+    "write_dot",
+    "read_dot",
+    "graphviz_layout",
+    "pydot_layout",
+    "to_pydot",
+    "from_pydot",
+]
+
+
+@open_file(1, mode="w")
+def write_dot(G, path):
+    """Write NetworkX graph G to Graphviz dot format on path.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    path : string or file
+       Filename or file handle for data output.
+       Filenames ending in .gz or .bz2 will be compressed.
+    """
+    P = to_pydot(G)
+    path.write(P.to_string())
+    return
+
+
+@open_file(0, mode="r")
+@nx._dispatchable(name="pydot_read_dot", graphs=None, returns_graph=True)
+def read_dot(path):
+    """Returns a NetworkX :class:`MultiGraph` or :class:`MultiDiGraph` from the
+    dot file with the passed path.
+
+    If this file contains multiple graphs, only the first such graph is
+    returned. All graphs _except_ the first are silently ignored.
+
+    Parameters
+    ----------
+    path : str or file
+        Filename or file handle to read.
+        Filenames ending in .gz or .bz2 will be decompressed.
+
+    Returns
+    -------
+    G : MultiGraph or MultiDiGraph
+        A :class:`MultiGraph` or :class:`MultiDiGraph`.
+
+    Notes
+    -----
+    Use `G = nx.Graph(nx.nx_pydot.read_dot(path))` to return a :class:`Graph` instead of a
+    :class:`MultiGraph`.
+    """
+    import pydot
+
+    data = path.read()
+
+    # List of one or more "pydot.Dot" instances deserialized from this file.
+    P_list = pydot.graph_from_dot_data(data)
+
+    # Convert only the first such instance into a NetworkX graph.
+    return from_pydot(P_list[0])
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def from_pydot(P):
+    """Returns a NetworkX graph from a Pydot graph.
+
+    Parameters
+    ----------
+    P : Pydot graph
+      A graph created with Pydot
+
+    Returns
+    -------
+    G : NetworkX multigraph
+        A MultiGraph or MultiDiGraph.
+
+    Examples
+    --------
+    >>> K5 = nx.complete_graph(5)
+    >>> A = nx.nx_pydot.to_pydot(K5)
+    >>> G = nx.nx_pydot.from_pydot(A)  # return MultiGraph
+
+    # make a Graph instead of MultiGraph
+    >>> G = nx.Graph(nx.nx_pydot.from_pydot(A))
+
+    """
+    # NOTE: Pydot v3 expects a dummy argument whereas Pydot v4 doesn't
+    # Remove the try-except when Pydot v4 becomes the minimum supported version
+    try:
+        strict = P.get_strict()
+    except TypeError:
+        strict = P.get_strict(None)  # pydot bug: get_strict() shouldn't take argument
+    multiedges = not strict
+
+    if P.get_type() == "graph":  # undirected
+        if multiedges:
+            N = nx.MultiGraph()
+        else:
+            N = nx.Graph()
+    else:
+        if multiedges:
+            N = nx.MultiDiGraph()
+        else:
+            N = nx.DiGraph()
+
+    # assign defaults
+    name = P.get_name().strip('"')
+    if name != "":
+        N.name = name
+
+    # add nodes, attributes to N.node_attr
+    for p in P.get_node_list():
+        n = p.get_name().strip('"')
+        if n in ("node", "graph", "edge"):
+            continue
+        N.add_node(n, **p.get_attributes())
+
+    # add edges
+    for e in P.get_edge_list():
+        u = e.get_source()
+        v = e.get_destination()
+        attr = e.get_attributes()
+        s = []
+        d = []
+
+        if isinstance(u, str):
+            s.append(u.strip('"'))
+        else:
+            for unodes in u["nodes"]:
+                s.append(unodes.strip('"'))
+
+        if isinstance(v, str):
+            d.append(v.strip('"'))
+        else:
+            for vnodes in v["nodes"]:
+                d.append(vnodes.strip('"'))
+
+        for source_node in s:
+            for destination_node in d:
+                N.add_edge(source_node, destination_node, **attr)
+
+    # add default attributes for graph, nodes, edges
+    pattr = P.get_attributes()
+    if pattr:
+        N.graph["graph"] = pattr
+    try:
+        N.graph["node"] = P.get_node_defaults()[0]
+    except (IndexError, TypeError):
+        pass  # N.graph['node']={}
+    try:
+        N.graph["edge"] = P.get_edge_defaults()[0]
+    except (IndexError, TypeError):
+        pass  # N.graph['edge']={}
+    return N
+
+
+def to_pydot(N):
+    """Returns a pydot graph from a NetworkX graph N.
+
+    Parameters
+    ----------
+    N : NetworkX graph
+      A graph created with NetworkX
+
+    Examples
+    --------
+    >>> K5 = nx.complete_graph(5)
+    >>> P = nx.nx_pydot.to_pydot(K5)
+
+    Notes
+    -----
+
+    """
+    import pydot
+
+    # set Graphviz graph type
+    if N.is_directed():
+        graph_type = "digraph"
+    else:
+        graph_type = "graph"
+    strict = nx.number_of_selfloops(N) == 0 and not N.is_multigraph()
+
+    name = N.name
+    graph_defaults = N.graph.get("graph", {})
+    if name == "":
+        P = pydot.Dot("", graph_type=graph_type, strict=strict, **graph_defaults)
+    else:
+        P = pydot.Dot(
+            f'"{name}"', graph_type=graph_type, strict=strict, **graph_defaults
+        )
+    try:
+        P.set_node_defaults(**N.graph["node"])
+    except KeyError:
+        pass
+    try:
+        P.set_edge_defaults(**N.graph["edge"])
+    except KeyError:
+        pass
+
+    for n, nodedata in N.nodes(data=True):
+        str_nodedata = {str(k): str(v) for k, v in nodedata.items()}
+        n = str(n)
+        p = pydot.Node(n, **str_nodedata)
+        P.add_node(p)
+
+    if N.is_multigraph():
+        for u, v, key, edgedata in N.edges(data=True, keys=True):
+            str_edgedata = {str(k): str(v) for k, v in edgedata.items() if k != "key"}
+            u, v = str(u), str(v)
+            edge = pydot.Edge(u, v, key=str(key), **str_edgedata)
+            P.add_edge(edge)
+
+    else:
+        for u, v, edgedata in N.edges(data=True):
+            str_edgedata = {str(k): str(v) for k, v in edgedata.items()}
+            u, v = str(u), str(v)
+            edge = pydot.Edge(u, v, **str_edgedata)
+            P.add_edge(edge)
+    return P
+
+
+def graphviz_layout(G, prog="neato", root=None):
+    """Create node positions using Pydot and Graphviz.
+
+    Returns a dictionary of positions keyed by node.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+        The graph for which the layout is computed.
+    prog : string (default: 'neato')
+        The name of the GraphViz program to use for layout.
+        Options depend on GraphViz version but may include:
+        'dot', 'twopi', 'fdp', 'sfdp', 'circo'
+    root : Node from G or None (default: None)
+        The node of G from which to start some layout algorithms.
+
+    Returns
+    -------
+      Dictionary of (x, y) positions keyed by node.
+
+    Examples
+    --------
+    >>> G = nx.complete_graph(4)
+    >>> pos = nx.nx_pydot.graphviz_layout(G)
+    >>> pos = nx.nx_pydot.graphviz_layout(G, prog="dot")
+
+    Notes
+    -----
+    This is a wrapper for pydot_layout.
+    """
+    return pydot_layout(G=G, prog=prog, root=root)
+
+
+def pydot_layout(G, prog="neato", root=None):
+    """Create node positions using :mod:`pydot` and Graphviz.
+
+    Parameters
+    ----------
+    G : Graph
+        NetworkX graph to be laid out.
+    prog : string  (default: 'neato')
+        Name of the GraphViz command to use for layout.
+        Options depend on GraphViz version but may include:
+        'dot', 'twopi', 'fdp', 'sfdp', 'circo'
+    root : Node from G or None (default: None)
+        The node of G from which to start some layout algorithms.
+
+    Returns
+    -------
+    dict
+        Dictionary of positions keyed by node.
+
+    Examples
+    --------
+    >>> G = nx.complete_graph(4)
+    >>> pos = nx.nx_pydot.pydot_layout(G)
+    >>> pos = nx.nx_pydot.pydot_layout(G, prog="dot")
+
+    Notes
+    -----
+    If you use complex node objects, they may have the same string
+    representation and GraphViz could treat them as the same node.
+    The layout may assign both nodes a single location. See Issue #1568
+    If this occurs in your case, consider relabeling the nodes just
+    for the layout computation using something similar to::
+
+        H = nx.convert_node_labels_to_integers(G, label_attribute="node_label")
+        H_layout = nx.nx_pydot.pydot_layout(H, prog="dot")
+        G_layout = {H.nodes[n]["node_label"]: p for n, p in H_layout.items()}
+
+    """
+    import pydot
+
+    P = to_pydot(G)
+    if root is not None:
+        P.set("root", str(root))
+
+    # List of low-level bytes comprising a string in the dot language converted
+    # from the passed graph with the passed external GraphViz command.
+    D_bytes = P.create_dot(prog=prog)
+
+    # Unique string decoded from these bytes with the preferred locale encoding
+    D = str(D_bytes, encoding=getpreferredencoding())
+
+    if D == "":  # no data returned
+        print(f"Graphviz layout with {prog} failed")
+        print()
+        print("To debug what happened try:")
+        print("P = nx.nx_pydot.to_pydot(G)")
+        print('P.write_dot("file.dot")')
+        print(f"And then run {prog} on file.dot")
+        return
+
+    # List of one or more "pydot.Dot" instances deserialized from this string.
+    Q_list = pydot.graph_from_dot_data(D)
+    assert len(Q_list) == 1
+
+    # The first and only such instance, as guaranteed by the above assertion.
+    Q = Q_list[0]
+
+    node_pos = {}
+    for n in G.nodes():
+        str_n = str(n)
+        node = Q.get_node(pydot.quote_id_if_necessary(str_n))
+
+        if isinstance(node, list):
+            node = node[0]
+        pos = node.get_pos()[1:-1]  # strip leading and trailing double quotes
+        if pos is not None:
+            xx, yy = pos.split(",")
+            node_pos[n] = (float(xx), float(yy))
+    return node_pos
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/drawing/nx_pylab.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/drawing/nx_pylab.py
new file mode 100644
index 0000000000000000000000000000000000000000..143b0a7590811054dd92a1757c64e4bdeb10f320
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/drawing/nx_pylab.py
@@ -0,0 +1,2978 @@
+"""
+**********
+Matplotlib
+**********
+
+Draw networks with matplotlib.
+
+Examples
+--------
+>>> G = nx.complete_graph(5)
+>>> nx.draw(G)
+
+See Also
+--------
+ - :doc:`matplotlib `
+ - :func:`matplotlib.pyplot.scatter`
+ - :obj:`matplotlib.patches.FancyArrowPatch`
+"""
+
+import collections
+import itertools
+import math
+from numbers import Number
+
+import networkx as nx
+
+__all__ = [
+    "display",
+    "apply_matplotlib_colors",
+    "draw",
+    "draw_networkx",
+    "draw_networkx_nodes",
+    "draw_networkx_edges",
+    "draw_networkx_labels",
+    "draw_networkx_edge_labels",
+    "draw_bipartite",
+    "draw_circular",
+    "draw_kamada_kawai",
+    "draw_random",
+    "draw_spectral",
+    "draw_spring",
+    "draw_planar",
+    "draw_shell",
+    "draw_forceatlas2",
+]
+
+
+def apply_matplotlib_colors(
+    G, src_attr, dest_attr, map, vmin=None, vmax=None, nodes=True
+):
+    """
+    Apply colors from a matplotlib colormap to a graph.
+
+    Reads values from the `src_attr` and use a matplotlib colormap
+    to produce a color. Write the color to `dest_attr`.
+
+    Parameters
+    ----------
+    G : nx.Graph
+        The graph to read and compute colors for.
+
+    src_attr : str or other attribute name
+        The name of the attribute to read from the graph.
+
+    dest_attr : str or other attribute name
+        The name of the attribute to write to on the graph.
+
+    map : matplotlib.colormap
+        The matplotlib colormap to use.
+
+    vmin : float, default None
+        The minimum value for scaling the colormap. If `None`, find the
+        minimum value of `src_attr`.
+
+    vmax : float, default None
+        The maximum value for scaling the colormap. If `None`, find the
+        maximum value of `src_attr`.
+
+    nodes : bool, default True
+        Whether the attribute names are edge attributes or node attributes.
+    """
+    import matplotlib as mpl
+
+    if nodes:
+        type_iter = G.nodes()
+    elif G.is_multigraph():
+        type_iter = G.edges(keys=True)
+    else:
+        type_iter = G.edges()
+
+    if vmin is None or vmax is None:
+        vals = [type_iter[a][src_attr] for a in type_iter]
+        if vmin is None:
+            vmin = min(vals)
+        if vmax is None:
+            vmax = max(vals)
+
+    mapper = mpl.cm.ScalarMappable(cmap=map)
+    mapper.set_clim(vmin, vmax)
+
+    def do_map(x):
+        # Cast numpy scalars to float
+        return tuple(float(x) for x in mapper.to_rgba(x))
+
+    if nodes:
+        nx.set_node_attributes(
+            G, {n: do_map(G.nodes[n][src_attr]) for n in G.nodes()}, dest_attr
+        )
+    else:
+        nx.set_edge_attributes(
+            G, {e: do_map(G.edges[e][src_attr]) for e in type_iter}, dest_attr
+        )
+
+
+class CurvedArrowTextBase:
+    def __init__(
+        self,
+        arrow,
+        *args,
+        label_pos=0.5,
+        labels_horizontal=False,
+        ax=None,
+        **kwargs,
+    ):
+        # Bind to FancyArrowPatch
+        self.arrow = arrow
+        # how far along the text should be on the curve,
+        # 0 is at start, 1 is at end etc.
+        self.label_pos = label_pos
+        self.labels_horizontal = labels_horizontal
+        if ax is None:
+            ax = plt.gca()
+        self.ax = ax
+        self.x, self.y, self.angle = self._update_text_pos_angle(arrow)
+
+        # Create text object
+        super().__init__(self.x, self.y, *args, rotation=self.angle, **kwargs)
+        # Bind to axis
+        self.ax.add_artist(self)
+
+    def _get_arrow_path_disp(self, arrow):
+        """
+        This is part of FancyArrowPatch._get_path_in_displaycoord
+        It omits the second part of the method where path is converted
+            to polygon based on width
+        The transform is taken from ax, not the object, as the object
+            has not been added yet, and doesn't have transform
+        """
+        dpi_cor = arrow._dpi_cor
+        trans_data = self.ax.transData
+        if arrow._posA_posB is None:
+            raise ValueError(
+                "Can only draw labels for fancy arrows with "
+                "posA and posB inputs, not custom path"
+            )
+        posA = arrow._convert_xy_units(arrow._posA_posB[0])
+        posB = arrow._convert_xy_units(arrow._posA_posB[1])
+        (posA, posB) = trans_data.transform((posA, posB))
+        _path = arrow.get_connectionstyle()(
+            posA,
+            posB,
+            patchA=arrow.patchA,
+            patchB=arrow.patchB,
+            shrinkA=arrow.shrinkA * dpi_cor,
+            shrinkB=arrow.shrinkB * dpi_cor,
+        )
+        # Return is in display coordinates
+        return _path
+
+    def _update_text_pos_angle(self, arrow):
+        # Fractional label position
+        # Text position at a proportion t along the line in display coords
+        # default is 0.5 so text appears at the halfway point
+        import matplotlib as mpl
+        import numpy as np
+
+        t = self.label_pos
+        tt = 1 - t
+        path_disp = self._get_arrow_path_disp(arrow)
+        conn = arrow.get_connectionstyle()
+        # 1. Calculate x and y
+        points = path_disp.vertices
+        if is_curve := isinstance(
+            conn,
+            mpl.patches.ConnectionStyle.Angle3 | mpl.patches.ConnectionStyle.Arc3,
+        ):
+            # Arc3 or Angle3 type Connection Styles - Bezier curve
+            (x1, y1), (cx, cy), (x2, y2) = points
+            x = tt**2 * x1 + 2 * t * tt * cx + t**2 * x2
+            y = tt**2 * y1 + 2 * t * tt * cy + t**2 * y2
+        else:
+            if not isinstance(
+                conn,
+                mpl.patches.ConnectionStyle.Angle
+                | mpl.patches.ConnectionStyle.Arc
+                | mpl.patches.ConnectionStyle.Bar,
+            ):
+                msg = f"invalid connection style: {type(conn)}"
+                raise TypeError(msg)
+            # A. Collect lines
+            codes = path_disp.codes
+            lines = [
+                points[i - 1 : i + 1]
+                for i in range(1, len(points))
+                if codes[i] == mpl.path.Path.LINETO
+            ]
+            # B. If more than one line, find the right one and position in it
+            if (nlines := len(lines)) != 1:
+                dists = [math.dist(*line) for line in lines]
+                dist_tot = sum(dists)
+                cdist = 0
+                last_cut = 0
+                i_last = nlines - 1
+                for i, dist in enumerate(dists):
+                    cdist += dist
+                    cut = cdist / dist_tot
+                    if i == i_last or t < cut:
+                        t = (t - last_cut) / (dist / dist_tot)
+                        tt = 1 - t
+                        lines = [lines[i]]
+                        break
+                    last_cut = cut
+            [[(cx1, cy1), (cx2, cy2)]] = lines
+            x = cx1 * tt + cx2 * t
+            y = cy1 * tt + cy2 * t
+
+        # 2. Calculate Angle
+        if self.labels_horizontal:
+            # Horizontal text labels
+            angle = 0
+        else:
+            # Labels parallel to curve
+            if is_curve:
+                change_x = 2 * tt * (cx - x1) + 2 * t * (x2 - cx)
+                change_y = 2 * tt * (cy - y1) + 2 * t * (y2 - cy)
+            else:
+                change_x = (cx2 - cx1) / 2
+                change_y = (cy2 - cy1) / 2
+            angle = np.arctan2(change_y, change_x) / (2 * np.pi) * 360
+            # Text is "right way up"
+            if angle > 90:
+                angle -= 180
+            elif angle < -90:
+                angle += 180
+        (x, y) = self.ax.transData.inverted().transform((x, y))
+        return x, y, angle
+
+    def draw(self, renderer):
+        # recalculate the text position and angle
+        self.x, self.y, self.angle = self._update_text_pos_angle(self.arrow)
+        self.set_position((self.x, self.y))
+        self.set_rotation(self.angle)
+        # redraw text
+        super().draw(renderer)
+
+
+def display(
+    G,
+    canvas=None,
+    **kwargs,
+):
+    """Draw the graph G.
+
+    Draw the graph as a collection of nodes connected by edges.
+    The exact details of what the graph looks like are controlled by the below
+    attributes. All nodes and nodes at the end of visible edges must have a
+    position set, but nearly all other node and edge attributes are options and
+    nodes or edges missing the attribute will use the default listed below. A more
+    complete description of each parameter is given below this summary.
+
+    .. list-table:: Default Visualization Attributes
+        :widths: 25 25 50
+        :header-rows: 1
+
+        * - Parameter
+          - Default Attribute
+          - Default Value
+        * - node_pos
+          - `"pos"`
+          - If there is not position, a layout will be calculated with `nx.spring_layout`.
+        * - node_visible
+          - `"visible"`
+          - True
+        * - node_color
+          - `"color"`
+          - #1f78b4
+        * - node_size
+          - `"size"`
+          - 300
+        * - node_label
+          - `"label"`
+          - Dict describing the node label. Defaults create a black text with
+            the node name as the label. The dict respects these keys and defaults:
+
+            * size : 12
+            * color : black
+            * family : sans serif
+            * weight : normal
+            * alpha : 1.0
+            * h_align : center
+            * v_align : center
+            * bbox : Dict describing a `matplotlib.patches.FancyBboxPatch`.
+              Default is None.
+
+        * - node_shape
+          - `"shape"`
+          - "o"
+        * - node_alpha
+          - `"alpha"`
+          - 1.0
+        * - node_border_width
+          - `"border_width"`
+          - 1.0
+        * - node_border_color
+          - `"border_color"`
+          - Matching node_color
+        * - edge_visible
+          - `"visible"`
+          - True
+        * - edge_width
+          - `"width"`
+          - 1.0
+        * - edge_color
+          - `"color"`
+          - Black (#000000)
+        * - edge_label
+          - `"label"`
+          - Dict describing the edge label. Defaults create black text with a
+            white bounding box. The dictionary respects these keys and defaults:
+
+            * size : 12
+            * color : black
+            * family : sans serif
+            * weight : normal
+            * alpha : 1.0
+            * bbox : Dict describing a `matplotlib.patches.FancyBboxPatch`.
+              Default {"boxstyle": "round", "ec": (1.0, 1.0, 1.0), "fc": (1.0, 1.0, 1.0)}
+            * h_align : "center"
+            * v_align : "center"
+            * pos : 0.5
+            * rotate : True
+
+        * - edge_style
+          - `"style"`
+          - "-"
+        * - edge_alpha
+          - `"alpha"`
+          - 1.0
+        * - edge_arrowstyle
+          - `"arrowstyle"`
+          - ``"-|>"`` if `G` is directed else ``"-"``
+        * - edge_arrowsize
+          - `"arrowsize"`
+          - 10 if `G` is directed else 0
+        * - edge_curvature
+          - `"curvature"`
+          - arc3
+        * - edge_source_margin
+          - `"source_margin"`
+          - 0
+        * - edge_target_margin
+          - `"target_margin"`
+          - 0
+
+    Parameters
+    ----------
+    G : graph
+        A networkx graph
+
+    canvas : Matplotlib Axes object, optional
+        Draw the graph in specified Matplotlib axes
+
+    node_pos : string or function, default "pos"
+        A string naming the node attribute storing the position of nodes as a tuple.
+        Or a function to be called with input `G` which returns the layout as a dict keyed
+        by node to position tuple like the NetworkX layout functions.
+        If no nodes in the graph has the attribute, a spring layout is calculated.
+
+    node_visible : string or bool, default visible
+        A string naming the node attribute which stores if a node should be drawn.
+        If `True`, all nodes will be visible while if `False` no nodes will be visible.
+        If incomplete, nodes missing this attribute will be shown by default.
+
+    node_color : string, default "color"
+        A string naming the node attribute which stores the color of each node.
+        Visible nodes without this attribute will use '#1f78b4' as a default.
+
+    node_size : string or number, default "size"
+        A string naming the node attribute which stores the size of each node.
+        Visible nodes without this attribute will use a default size of 300.
+
+    node_label : string or bool, default "label"
+        A string naming the node attribute which stores the label of each node.
+        The attribute value can be a string, False (no label for that node),
+        True (the node is the label) or a dict keyed by node to the label.
+
+        If a dict is specified, these keys are read to further control the label:
+
+        * label : The text of the label; default: name of the node
+        * size : Font size of the label; default: 12
+        * color : Font color of the label; default: black
+        * family : Font family of the label; default: "sans-serif"
+        * weight : Font weight of the label; default: "normal"
+        * alpha : Alpha value of the label; default: 1.0
+        * h_align : The horizontal alignment of the label.
+            one of "left", "center", "right"; default: "center"
+        * v_align : The vertical alignment of the label.
+            one of "top", "center", "bottom"; default: "center"
+        * bbox : A dict of parameters for `matplotlib.patches.FancyBboxPatch`.
+
+        Visible nodes without this attribute will be treated as if the value was True.
+
+    node_shape : string, default "shape"
+        A string naming the node attribute which stores the label of each node.
+        The values of this attribute are expected to be one of the matplotlib shapes,
+        one of 'so^>v"`` for directed graphs.
+
+        See `matplotlib.patches.ArrowStyle` for more options
+
+    edge_arrowsize : string or int, default "arrowsize"
+        A string naming the edge attribute which stores the size of the arrowhead for each
+        edge. Visible edges without this attribute will use a default value of 10.
+
+    edge_curvature : string, default "curvature"
+       A string naming the edge attribute storing the curvature and connection style
+       of each edge. Visible edges without this attribute will use "arc3" as a default
+       value, resulting an a straight line between the two nodes. Curvature can be given
+       as 'arc3,rad=0.2' to specify both the style and radius of curvature.
+
+       Please see `matplotlib.patches.ConnectionStyle` and
+       `matplotlib.patches.FancyArrowPatch` for more information.
+
+    edge_source_margin : string or int, default "source_margin"
+        A string naming the edge attribute which stores the minimum margin (gap) between
+        the source node and the start of the edge. Visible edges without this attribute
+        will use a default value of 0.
+
+    edge_target_margin : string or int, default "target_margin"
+        A string naming the edge attribute which stores the minimumm margin (gap) between
+        the target node and the end of the edge. Visible edges without this attribute
+        will use a default value of 0.
+
+    hide_ticks : bool, default True
+        Weather to remove the ticks from the axes of the matplotlib object.
+
+    Raises
+    ------
+    NetworkXError
+        If a node or edge is missing a required parameter such as `pos` or
+        if `display` receives an argument not listed above.
+
+    ValueError
+        If a node or edge has an invalid color format, i.e. not a color string,
+        rgb tuple or rgba tuple.
+
+    Returns
+    -------
+    The input graph. This is potentially useful for dispatching visualization
+    functions.
+    """
+    from collections import Counter
+
+    import matplotlib as mpl
+    import matplotlib.pyplot as plt
+    import numpy as np
+
+    defaults = {
+        "node_pos": None,
+        "node_visible": True,
+        "node_color": "#1f78b4",
+        "node_size": 300,
+        "node_label": {
+            "size": 12,
+            "color": "#000000",
+            "family": "sans-serif",
+            "weight": "normal",
+            "alpha": 1.0,
+            "h_align": "center",
+            "v_align": "center",
+            "bbox": None,
+        },
+        "node_shape": "o",
+        "node_alpha": 1.0,
+        "node_border_width": 1.0,
+        "node_border_color": "face",
+        "edge_visible": True,
+        "edge_width": 1.0,
+        "edge_color": "#000000",
+        "edge_label": {
+            "size": 12,
+            "color": "#000000",
+            "family": "sans-serif",
+            "weight": "normal",
+            "alpha": 1.0,
+            "bbox": {"boxstyle": "round", "ec": (1.0, 1.0, 1.0), "fc": (1.0, 1.0, 1.0)},
+            "h_align": "center",
+            "v_align": "center",
+            "pos": 0.5,
+            "rotate": True,
+        },
+        "edge_style": "-",
+        "edge_alpha": 1.0,
+        "edge_arrowstyle": "-|>" if G.is_directed() else "-",
+        "edge_arrowsize": 10 if G.is_directed() else 0,
+        "edge_curvature": "arc3",
+        "edge_source_margin": 0,
+        "edge_target_margin": 0,
+        "hide_ticks": True,
+    }
+
+    # Check arguments
+    for kwarg in kwargs:
+        if kwarg not in defaults:
+            raise nx.NetworkXError(
+                f"Unrecognized visualization keyword argument: {kwarg}"
+            )
+
+    if canvas is None:
+        canvas = plt.gca()
+
+    if kwargs.get("hide_ticks", defaults["hide_ticks"]):
+        canvas.tick_params(
+            axis="both",
+            which="both",
+            bottom=False,
+            left=False,
+            labelbottom=False,
+            labelleft=False,
+        )
+
+    ### Helper methods and classes
+
+    def node_property_sequence(seq, attr):
+        """Return a list of attribute values for `seq`, using a default if needed"""
+
+        # All node attribute parameters start with "node_"
+        param_name = f"node_{attr}"
+        default = defaults[param_name]
+        attr = kwargs.get(param_name, attr)
+
+        if default is None:
+            # raise instead of using non-existant default value
+            for n in seq:
+                if attr not in node_subgraph.nodes[n]:
+                    raise nx.NetworkXError(f"Attribute '{attr}' missing for node {n}")
+
+        # If `attr` is not a graph attr and was explicitly passed as an argument
+        # it must be a user-default value. Allow attr=None to tell draw to skip
+        # attributes which are on the graph
+        if (
+            attr is not None
+            and nx.get_node_attributes(node_subgraph, attr) == {}
+            and any(attr == v for k, v in kwargs.items() if "node" in k)
+        ):
+            return [attr for _ in seq]
+
+        return [node_subgraph.nodes[n].get(attr, default) for n in seq]
+
+    def compute_colors(color, alpha):
+        if isinstance(color, str):
+            rgba = mpl.colors.colorConverter.to_rgba(color)
+            # Using a non-default alpha value overrides any alpha value in the color
+            if alpha != defaults["node_alpha"]:
+                return (rgba[0], rgba[1], rgba[2], alpha)
+            return rgba
+
+        if isinstance(color, tuple) and len(color) == 3:
+            return (color[0], color[1], color[2], alpha)
+
+        if isinstance(color, tuple) and len(color) == 4:
+            return color
+
+        raise ValueError(f"Invalid format for color: {color}")
+
+    # Find which edges can be plotted as a line collection
+    #
+    # Non-default values for these attributes require fancy arrow patches:
+    # - any arrow style (including the default -|> for directed graphs)
+    # - arrow size (by extension of style)
+    # - connection style
+    # - min_source_margin
+    # - min_target_margin
+
+    def collection_compatible(e):
+        return (
+            get_edge_attr(e, "arrowstyle") == "-"
+            and get_edge_attr(e, "curvature") == "arc3"
+            and get_edge_attr(e, "source_margin") == 0
+            and get_edge_attr(e, "target_margin") == 0
+            # Self-loops will use fancy arrow patches
+            and e[0] != e[1]
+        )
+
+    def edge_property_sequence(seq, attr):
+        """Return a list of attribute values for `seq`, using a default if needed"""
+
+        param_name = f"edge_{attr}"
+        default = defaults[param_name]
+        attr = kwargs.get(param_name, attr)
+
+        if default is None:
+            # raise instead of using non-existant default value
+            for e in seq:
+                if attr not in edge_subgraph.edges[e]:
+                    raise nx.NetworkXError(f"Attribute '{attr}' missing for edge {e}")
+
+        if (
+            attr is not None
+            and nx.get_edge_attributes(edge_subgraph, attr) == {}
+            and any(attr == v for k, v in kwargs.items() if "edge" in k)
+        ):
+            return [attr for _ in seq]
+
+        return [edge_subgraph.edges[e].get(attr, default) for e in seq]
+
+    def get_edge_attr(e, attr):
+        """Return the final edge attribute value, using default if not None"""
+
+        param_name = f"edge_{attr}"
+        default = defaults[param_name]
+        attr = kwargs.get(param_name, attr)
+
+        if default is None and attr not in edge_subgraph.edges[e]:
+            raise nx.NetworkXError(f"Attribute '{attr}' missing from edge {e}")
+
+        if (
+            attr is not None
+            and nx.get_edge_attributes(edge_subgraph, attr) == {}
+            and attr in kwargs.values()
+        ):
+            return attr
+
+        return edge_subgraph.edges[e].get(attr, default)
+
+    def get_node_attr(n, attr, use_edge_subgraph=True):
+        """Return the final node attribute value, using default if not None"""
+        subgraph = edge_subgraph if use_edge_subgraph else node_subgraph
+
+        param_name = f"node_{attr}"
+        default = defaults[param_name]
+        attr = kwargs.get(param_name, attr)
+
+        if default is None and attr not in subgraph.nodes[n]:
+            raise nx.NetworkXError(f"Attribute '{attr}' missing from node {n}")
+
+        if (
+            attr is not None
+            and nx.get_node_attributes(subgraph, attr) == {}
+            and attr in kwargs.values()
+        ):
+            return attr
+
+        return subgraph.nodes[n].get(attr, default)
+
+    # Taken from ConnectionStyleFactory
+    def self_loop(edge_index, node_size):
+        def self_loop_connection(posA, posB, *args, **kwargs):
+            if not np.all(posA == posB):
+                raise nx.NetworkXError(
+                    "`self_loop` connection style method"
+                    "is only to be used for self-loops"
+                )
+            # this is called with _screen space_ values
+            # so convert back to data space
+            data_loc = canvas.transData.inverted().transform(posA)
+            # Scale self loop based on the size of the base node
+            # Size of nodes are given in points ** 2 and each point is 1/72 of an inch
+            v_shift = np.sqrt(node_size) / 72
+            h_shift = v_shift * 0.5
+            # put the top of the loop first so arrow is not hidden by node
+            path = np.asarray(
+                [
+                    # 1
+                    [0, v_shift],
+                    # 4 4 4
+                    [h_shift, v_shift],
+                    [h_shift, 0],
+                    [0, 0],
+                    # 4 4 4
+                    [-h_shift, 0],
+                    [-h_shift, v_shift],
+                    [0, v_shift],
+                ]
+            )
+            # Rotate self loop 90 deg. if more than 1
+            # This will allow for maximum of 4 visible self loops
+            if edge_index % 4:
+                x, y = path.T
+                for _ in range(edge_index % 4):
+                    x, y = y, -x
+                path = np.array([x, y]).T
+            return mpl.path.Path(
+                canvas.transData.transform(data_loc + path), [1, 4, 4, 4, 4, 4, 4]
+            )
+
+        return self_loop_connection
+
+    def to_marker_edge(size, marker):
+        if marker in "s^>v 0:
+        node_shape = kwargs.get("node_shape", "shape")
+        for shape in Counter(
+            nx.get_node_attributes(
+                node_subgraph, node_shape, defaults["node_shape"]
+            ).values()
+        ):
+            # Filter position just on this shape.
+            nodes_with_shape = [
+                n
+                for n, s in node_subgraph.nodes(data=node_shape)
+                if s == shape or (s is None and shape == defaults["node_shape"])
+            ]
+            # There are two property sequences to create before hand.
+            # 1. position, since it is used for x and y parameters to scatter
+            # 2. edgecolor, since the spaeical 'face' parameter value can only be
+            #    be passed in as the sole string, not part of a list of strings.
+            position = np.asarray(node_property_sequence(nodes_with_shape, "pos"))
+            color = np.asarray(
+                [
+                    compute_colors(c, a)
+                    for c, a in zip(
+                        node_property_sequence(nodes_with_shape, "color"),
+                        node_property_sequence(nodes_with_shape, "alpha"),
+                    )
+                ]
+            )
+            border_color = np.asarray(
+                [
+                    (
+                        c
+                        if (
+                            c := get_node_attr(
+                                n,
+                                "border_color",
+                                False,
+                            )
+                        )
+                        != "face"
+                        else color[i]
+                    )
+                    for i, n in enumerate(nodes_with_shape)
+                ]
+            )
+            canvas.scatter(
+                position[:, 0],
+                position[:, 1],
+                s=node_property_sequence(nodes_with_shape, "size"),
+                c=color,
+                marker=shape,
+                linewidths=node_property_sequence(nodes_with_shape, "border_width"),
+                edgecolors=border_color,
+                zorder=2,
+            )
+
+    ### Draw node labels
+    node_label = kwargs.get("node_label", "label")
+    # Plot labels if node_label is not None and not False
+    if node_label is not None and node_label is not False:
+        default_dict = {}
+        if isinstance(node_label, dict):
+            default_dict = node_label
+            node_label = None
+
+        for n, lbl in node_subgraph.nodes(data=node_label):
+            if lbl is False:
+                continue
+
+            # We work with label dicts down here...
+            if not isinstance(lbl, dict):
+                lbl = {"label": lbl if lbl is not None else n}
+
+            lbl_text = lbl.get("label", n)
+            if not isinstance(lbl_text, str):
+                lbl_text = str(lbl_text)
+
+            lbl.update(default_dict)
+            x, y = node_subgraph.nodes[n][pos]
+            canvas.text(
+                x,
+                y,
+                lbl_text,
+                size=lbl.get("size", defaults["node_label"]["size"]),
+                color=lbl.get("color", defaults["node_label"]["color"]),
+                family=lbl.get("family", defaults["node_label"]["family"]),
+                weight=lbl.get("weight", defaults["node_label"]["weight"]),
+                horizontalalignment=lbl.get(
+                    "h_align", defaults["node_label"]["h_align"]
+                ),
+                verticalalignment=lbl.get("v_align", defaults["node_label"]["v_align"]),
+                transform=canvas.transData,
+                bbox=lbl.get("bbox", defaults["node_label"]["bbox"]),
+            )
+
+    ### Draw edges
+
+    edge_visible = kwargs.get("edge_visible", "visible")
+    if isinstance(edge_visible, bool):
+        if edge_visible:
+            visible_edges = G.edges()
+        else:
+            visible_edges = []
+    else:
+        visible_edges = [
+            e for e, v in nx.get_edge_attributes(G, edge_visible, True).items() if v
+        ]
+
+    edge_subgraph = G.edge_subgraph(visible_edges)
+    nx.set_node_attributes(
+        edge_subgraph, nx.get_node_attributes(node_subgraph, pos), name=pos
+    )
+
+    collection_edges = (
+        [e for e in edge_subgraph.edges(keys=True) if collection_compatible(e)]
+        if edge_subgraph.is_multigraph()
+        else [e for e in edge_subgraph.edges() if collection_compatible(e)]
+    )
+    non_collection_edges = (
+        [e for e in edge_subgraph.edges(keys=True) if not collection_compatible(e)]
+        if edge_subgraph.is_multigraph()
+        else [e for e in edge_subgraph.edges() if not collection_compatible(e)]
+    )
+    edge_position = np.asarray(
+        [
+            (
+                get_node_attr(u, "pos", use_edge_subgraph=True),
+                get_node_attr(v, "pos", use_edge_subgraph=True),
+            )
+            for u, v, *_ in collection_edges
+        ]
+    )
+
+    # Only plot a line collection if needed
+    if len(collection_edges) > 0:
+        edge_collection = mpl.collections.LineCollection(
+            edge_position,
+            colors=edge_property_sequence(collection_edges, "color"),
+            linewidths=edge_property_sequence(collection_edges, "width"),
+            linestyle=edge_property_sequence(collection_edges, "style"),
+            alpha=edge_property_sequence(collection_edges, "alpha"),
+            antialiaseds=(1,),
+            zorder=1,
+        )
+        canvas.add_collection(edge_collection)
+
+    fancy_arrows = {}
+    if len(non_collection_edges) > 0:
+        for e in non_collection_edges:
+            # Cache results for use in edge labels
+            fancy_arrows[e] = build_fancy_arrow(e)
+            canvas.add_patch(fancy_arrows[e])
+
+    ### Draw edge labels
+    edge_label = kwargs.get("edge_label", "label")
+    default_dict = {}
+    if isinstance(edge_label, dict):
+        default_dict = edge_label
+        # Restore the default label attribute key of 'label'
+        edge_label = "label"
+
+    # Handle multigraphs
+    edge_label_data = (
+        edge_subgraph.edges(data=edge_label, keys=True)
+        if edge_subgraph.is_multigraph()
+        else edge_subgraph.edges(data=edge_label)
+    )
+    if edge_label is not None and edge_label is not False:
+        for *e, lbl in edge_label_data:
+            e = tuple(e)
+            # I'm not sure how I want to handle None here... For now it means no label
+            if lbl is False or lbl is None:
+                continue
+
+            if not isinstance(lbl, dict):
+                lbl = {"label": lbl}
+
+            lbl.update(default_dict)
+            lbl_text = lbl.get("label")
+            if not isinstance(lbl_text, str):
+                lbl_text = str(lbl_text)
+
+            # In the old code, every non-self-loop is placed via a fancy arrow patch
+            # Only compute a new fancy arrow if needed by caching the results from
+            # edge placement.
+            try:
+                arrow = fancy_arrows[e]
+            except KeyError:
+                arrow = build_fancy_arrow(e)
+
+            if e[0] == e[1]:
+                # Taken directly from draw_networkx_edge_labels
+                connectionstyle_obj = arrow.get_connectionstyle()
+                posA = canvas.transData.transform(edge_subgraph.nodes[e[0]][pos])
+                path_disp = connectionstyle_obj(posA, posA)
+                path_data = canvas.transData.inverted().transform_path(path_disp)
+                x, y = path_data.vertices[0]
+                canvas.text(
+                    x,
+                    y,
+                    lbl_text,
+                    size=lbl.get("size", defaults["edge_label"]["size"]),
+                    color=lbl.get("color", defaults["edge_label"]["color"]),
+                    family=lbl.get("family", defaults["edge_label"]["family"]),
+                    weight=lbl.get("weight", defaults["edge_label"]["weight"]),
+                    alpha=lbl.get("alpha", defaults["edge_label"]["alpha"]),
+                    horizontalalignment=lbl.get(
+                        "h_align", defaults["edge_label"]["h_align"]
+                    ),
+                    verticalalignment=lbl.get(
+                        "v_align", defaults["edge_label"]["v_align"]
+                    ),
+                    rotation=0,
+                    transform=canvas.transData,
+                    bbox=lbl.get("bbox", defaults["edge_label"]["bbox"]),
+                    zorder=1,
+                )
+                continue
+
+            CurvedArrowText(
+                arrow,
+                lbl_text,
+                size=lbl.get("size", defaults["edge_label"]["size"]),
+                color=lbl.get("color", defaults["edge_label"]["color"]),
+                family=lbl.get("family", defaults["edge_label"]["family"]),
+                weight=lbl.get("weight", defaults["edge_label"]["weight"]),
+                alpha=lbl.get("alpha", defaults["edge_label"]["alpha"]),
+                bbox=lbl.get("bbox", defaults["edge_label"]["bbox"]),
+                horizontalalignment=lbl.get(
+                    "h_align", defaults["edge_label"]["h_align"]
+                ),
+                verticalalignment=lbl.get("v_align", defaults["edge_label"]["v_align"]),
+                label_pos=lbl.get("pos", defaults["edge_label"]["pos"]),
+                labels_horizontal=lbl.get("rotate", defaults["edge_label"]["rotate"]),
+                transform=canvas.transData,
+                zorder=1,
+                ax=canvas,
+            )
+
+    # If we had to add an attribute, remove it here
+    if pos == default_display_pos_attr:
+        nx.remove_node_attributes(G, default_display_pos_attr)
+
+    return G
+
+
+def draw(G, pos=None, ax=None, **kwds):
+    """Draw the graph G with Matplotlib.
+
+    Draw the graph as a simple representation with no node
+    labels or edge labels and using the full Matplotlib figure area
+    and no axis labels by default.  See draw_networkx() for more
+    full-featured drawing that allows title, axis labels etc.
+
+    Parameters
+    ----------
+    G : graph
+        A networkx graph
+
+    pos : dictionary, optional
+        A dictionary with nodes as keys and positions as values.
+        If not specified a spring layout positioning will be computed.
+        See :py:mod:`networkx.drawing.layout` for functions that
+        compute node positions.
+
+    ax : Matplotlib Axes object, optional
+        Draw the graph in specified Matplotlib axes.
+
+    kwds : optional keywords
+        See networkx.draw_networkx() for a description of optional keywords.
+
+    Examples
+    --------
+    >>> G = nx.dodecahedral_graph()
+    >>> nx.draw(G)
+    >>> nx.draw(G, pos=nx.spring_layout(G))  # use spring layout
+
+    See Also
+    --------
+    draw_networkx
+    draw_networkx_nodes
+    draw_networkx_edges
+    draw_networkx_labels
+    draw_networkx_edge_labels
+
+    Notes
+    -----
+    This function has the same name as pylab.draw and pyplot.draw
+    so beware when using `from networkx import *`
+
+    since you might overwrite the pylab.draw function.
+
+    With pyplot use
+
+    >>> import matplotlib.pyplot as plt
+    >>> G = nx.dodecahedral_graph()
+    >>> nx.draw(G)  # networkx draw()
+    >>> plt.draw()  # pyplot draw()
+
+    Also see the NetworkX drawing examples at
+    https://networkx.org/documentation/latest/auto_examples/index.html
+    """
+
+    import matplotlib.pyplot as plt
+
+    if ax is None:
+        cf = plt.gcf()
+    else:
+        cf = ax.get_figure()
+    cf.set_facecolor("w")
+    if ax is None:
+        if cf.axes:
+            ax = cf.gca()
+        else:
+            ax = cf.add_axes((0, 0, 1, 1))
+
+    if "with_labels" not in kwds:
+        kwds["with_labels"] = "labels" in kwds
+
+    draw_networkx(G, pos=pos, ax=ax, **kwds)
+    ax.set_axis_off()
+    plt.draw_if_interactive()
+    return
+
+
+def draw_networkx(G, pos=None, arrows=None, with_labels=True, **kwds):
+    r"""Draw the graph G using Matplotlib.
+
+    Draw the graph with Matplotlib with options for node positions,
+    labeling, titles, and many other drawing features.
+    See draw() for simple drawing without labels or axes.
+
+    Parameters
+    ----------
+    G : graph
+        A networkx graph
+
+    pos : dictionary, optional
+        A dictionary with nodes as keys and positions as values.
+        If not specified a spring layout positioning will be computed.
+        See :py:mod:`networkx.drawing.layout` for functions that
+        compute node positions.
+
+    arrows : bool or None, optional (default=None)
+        If `None`, directed graphs draw arrowheads with
+        `~matplotlib.patches.FancyArrowPatch`, while undirected graphs draw edges
+        via `~matplotlib.collections.LineCollection` for speed.
+        If `True`, draw arrowheads with FancyArrowPatches (bendable and stylish).
+        If `False`, draw edges using LineCollection (linear and fast).
+        For directed graphs, if True draw arrowheads.
+        Note: Arrows will be the same color as edges.
+
+    arrowstyle : str (default='-\|>' for directed graphs)
+        For directed graphs, choose the style of the arrowsheads.
+        For undirected graphs default to '-'
+
+        See `matplotlib.patches.ArrowStyle` for more options.
+
+    arrowsize : int or list (default=10)
+        For directed graphs, choose the size of the arrow head's length and
+        width. A list of values can be passed in to assign a different size for arrow head's length and width.
+        See `matplotlib.patches.FancyArrowPatch` for attribute `mutation_scale`
+        for more info.
+
+    with_labels :  bool (default=True)
+        Set to True to draw labels on the nodes.
+
+    ax : Matplotlib Axes object, optional
+        Draw the graph in the specified Matplotlib axes.
+
+    nodelist : list (default=list(G))
+        Draw only specified nodes
+
+    edgelist : list (default=list(G.edges()))
+        Draw only specified edges
+
+    node_size : scalar or array (default=300)
+        Size of nodes.  If an array is specified it must be the
+        same length as nodelist.
+
+    node_color : color or array of colors (default='#1f78b4')
+        Node color. Can be a single color or a sequence of colors with the same
+        length as nodelist. Color can be string or rgb (or rgba) tuple of
+        floats from 0-1. If numeric values are specified they will be
+        mapped to colors using the cmap and vmin,vmax parameters. See
+        matplotlib.scatter for more details.
+
+    node_shape :  string (default='o')
+        The shape of the node.  Specification is as matplotlib.scatter
+        marker, one of 'so^>v>> G = nx.dodecahedral_graph()
+    >>> nx.draw(G)
+    >>> nx.draw(G, pos=nx.spring_layout(G))  # use spring layout
+
+    >>> import matplotlib.pyplot as plt
+    >>> limits = plt.axis("off")  # turn off axis
+
+    Also see the NetworkX drawing examples at
+    https://networkx.org/documentation/latest/auto_examples/index.html
+
+    See Also
+    --------
+    draw
+    draw_networkx_nodes
+    draw_networkx_edges
+    draw_networkx_labels
+    draw_networkx_edge_labels
+    """
+    from inspect import signature
+
+    import matplotlib.pyplot as plt
+
+    # Get all valid keywords by inspecting the signatures of draw_networkx_nodes,
+    # draw_networkx_edges, draw_networkx_labels
+
+    valid_node_kwds = signature(draw_networkx_nodes).parameters.keys()
+    valid_edge_kwds = signature(draw_networkx_edges).parameters.keys()
+    valid_label_kwds = signature(draw_networkx_labels).parameters.keys()
+
+    # Create a set with all valid keywords across the three functions and
+    # remove the arguments of this function (draw_networkx)
+    valid_kwds = (valid_node_kwds | valid_edge_kwds | valid_label_kwds) - {
+        "G",
+        "pos",
+        "arrows",
+        "with_labels",
+    }
+
+    if any(k not in valid_kwds for k in kwds):
+        invalid_args = ", ".join([k for k in kwds if k not in valid_kwds])
+        raise ValueError(f"Received invalid argument(s): {invalid_args}")
+
+    node_kwds = {k: v for k, v in kwds.items() if k in valid_node_kwds}
+    edge_kwds = {k: v for k, v in kwds.items() if k in valid_edge_kwds}
+    label_kwds = {k: v for k, v in kwds.items() if k in valid_label_kwds}
+
+    if pos is None:
+        pos = nx.drawing.spring_layout(G)  # default to spring layout
+
+    draw_networkx_nodes(G, pos, **node_kwds)
+    draw_networkx_edges(G, pos, arrows=arrows, **edge_kwds)
+    if with_labels:
+        draw_networkx_labels(G, pos, **label_kwds)
+    plt.draw_if_interactive()
+
+
+def draw_networkx_nodes(
+    G,
+    pos,
+    nodelist=None,
+    node_size=300,
+    node_color="#1f78b4",
+    node_shape="o",
+    alpha=None,
+    cmap=None,
+    vmin=None,
+    vmax=None,
+    ax=None,
+    linewidths=None,
+    edgecolors=None,
+    label=None,
+    margins=None,
+    hide_ticks=True,
+):
+    """Draw the nodes of the graph G.
+
+    This draws only the nodes of the graph G.
+
+    Parameters
+    ----------
+    G : graph
+        A networkx graph
+
+    pos : dictionary
+        A dictionary with nodes as keys and positions as values.
+        Positions should be sequences of length 2.
+
+    ax : Matplotlib Axes object, optional
+        Draw the graph in the specified Matplotlib axes.
+
+    nodelist : list (default list(G))
+        Draw only specified nodes
+
+    node_size : scalar or array (default=300)
+        Size of nodes.  If an array it must be the same length as nodelist.
+
+    node_color : color or array of colors (default='#1f78b4')
+        Node color. Can be a single color or a sequence of colors with the same
+        length as nodelist. Color can be string or rgb (or rgba) tuple of
+        floats from 0-1. If numeric values are specified they will be
+        mapped to colors using the cmap and vmin,vmax parameters. See
+        matplotlib.scatter for more details.
+
+    node_shape :  string (default='o')
+        The shape of the node.  Specification is as matplotlib.scatter
+        marker, one of 'so^>v>> G = nx.dodecahedral_graph()
+    >>> nodes = nx.draw_networkx_nodes(G, pos=nx.spring_layout(G))
+
+    Also see the NetworkX drawing examples at
+    https://networkx.org/documentation/latest/auto_examples/index.html
+
+    See Also
+    --------
+    draw
+    draw_networkx
+    draw_networkx_edges
+    draw_networkx_labels
+    draw_networkx_edge_labels
+    """
+    from collections.abc import Iterable
+
+    import matplotlib as mpl
+    import matplotlib.collections  # call as mpl.collections
+    import matplotlib.pyplot as plt
+    import numpy as np
+
+    if ax is None:
+        ax = plt.gca()
+
+    if nodelist is None:
+        nodelist = list(G)
+
+    if len(nodelist) == 0:  # empty nodelist, no drawing
+        return mpl.collections.PathCollection(None)
+
+    try:
+        xy = np.asarray([pos[v] for v in nodelist])
+    except KeyError as err:
+        raise nx.NetworkXError(f"Node {err} has no position.") from err
+
+    if isinstance(alpha, Iterable):
+        node_color = apply_alpha(node_color, alpha, nodelist, cmap, vmin, vmax)
+        alpha = None
+
+    if not isinstance(node_shape, np.ndarray) and not isinstance(node_shape, list):
+        node_shape = np.array([node_shape for _ in range(len(nodelist))])
+    elif isinstance(node_shape, list):
+        node_shape = np.asarray(node_shape)
+
+    for shape in np.unique(node_shape):
+        node_collection = ax.scatter(
+            xy[node_shape == shape, 0],
+            xy[node_shape == shape, 1],
+            s=node_size,
+            c=node_color,
+            marker=shape,
+            cmap=cmap,
+            vmin=vmin,
+            vmax=vmax,
+            alpha=alpha,
+            linewidths=linewidths,
+            edgecolors=edgecolors,
+            label=label,
+        )
+    if hide_ticks:
+        ax.tick_params(
+            axis="both",
+            which="both",
+            bottom=False,
+            left=False,
+            labelbottom=False,
+            labelleft=False,
+        )
+
+    if margins is not None:
+        if isinstance(margins, Iterable):
+            ax.margins(*margins)
+        else:
+            ax.margins(margins)
+
+    node_collection.set_zorder(2)
+    return node_collection
+
+
+class FancyArrowFactory:
+    """Draw arrows with `matplotlib.patches.FancyarrowPatch`"""
+
+    class ConnectionStyleFactory:
+        def __init__(self, connectionstyles, selfloop_height, ax=None):
+            import matplotlib as mpl
+            import matplotlib.path  # call as mpl.path
+            import numpy as np
+
+            self.ax = ax
+            self.mpl = mpl
+            self.np = np
+            self.base_connection_styles = [
+                mpl.patches.ConnectionStyle(cs) for cs in connectionstyles
+            ]
+            self.n = len(self.base_connection_styles)
+            self.selfloop_height = selfloop_height
+
+        def curved(self, edge_index):
+            return self.base_connection_styles[edge_index % self.n]
+
+        def self_loop(self, edge_index):
+            def self_loop_connection(posA, posB, *args, **kwargs):
+                if not self.np.all(posA == posB):
+                    raise nx.NetworkXError(
+                        "`self_loop` connection style method"
+                        "is only to be used for self-loops"
+                    )
+                # this is called with _screen space_ values
+                # so convert back to data space
+                data_loc = self.ax.transData.inverted().transform(posA)
+                v_shift = 0.1 * self.selfloop_height
+                h_shift = v_shift * 0.5
+                # put the top of the loop first so arrow is not hidden by node
+                path = self.np.asarray(
+                    [
+                        # 1
+                        [0, v_shift],
+                        # 4 4 4
+                        [h_shift, v_shift],
+                        [h_shift, 0],
+                        [0, 0],
+                        # 4 4 4
+                        [-h_shift, 0],
+                        [-h_shift, v_shift],
+                        [0, v_shift],
+                    ]
+                )
+                # Rotate self loop 90 deg. if more than 1
+                # This will allow for maximum of 4 visible self loops
+                if edge_index % 4:
+                    x, y = path.T
+                    for _ in range(edge_index % 4):
+                        x, y = y, -x
+                    path = self.np.array([x, y]).T
+                return self.mpl.path.Path(
+                    self.ax.transData.transform(data_loc + path), [1, 4, 4, 4, 4, 4, 4]
+                )
+
+            return self_loop_connection
+
+    def __init__(
+        self,
+        edge_pos,
+        edgelist,
+        nodelist,
+        edge_indices,
+        node_size,
+        selfloop_height,
+        connectionstyle="arc3",
+        node_shape="o",
+        arrowstyle="-",
+        arrowsize=10,
+        edge_color="k",
+        alpha=None,
+        linewidth=1.0,
+        style="solid",
+        min_source_margin=0,
+        min_target_margin=0,
+        ax=None,
+    ):
+        import matplotlib as mpl
+        import matplotlib.patches  # call as mpl.patches
+        import matplotlib.pyplot as plt
+        import numpy as np
+
+        if isinstance(connectionstyle, str):
+            connectionstyle = [connectionstyle]
+        elif np.iterable(connectionstyle):
+            connectionstyle = list(connectionstyle)
+        else:
+            msg = "ConnectionStyleFactory arg `connectionstyle` must be str or iterable"
+            raise nx.NetworkXError(msg)
+        self.ax = ax
+        self.mpl = mpl
+        self.np = np
+        self.edge_pos = edge_pos
+        self.edgelist = edgelist
+        self.nodelist = nodelist
+        self.node_shape = node_shape
+        self.min_source_margin = min_source_margin
+        self.min_target_margin = min_target_margin
+        self.edge_indices = edge_indices
+        self.node_size = node_size
+        self.connectionstyle_factory = self.ConnectionStyleFactory(
+            connectionstyle, selfloop_height, ax
+        )
+        self.arrowstyle = arrowstyle
+        self.arrowsize = arrowsize
+        self.arrow_colors = mpl.colors.colorConverter.to_rgba_array(edge_color, alpha)
+        self.linewidth = linewidth
+        self.style = style
+        if isinstance(arrowsize, list) and len(arrowsize) != len(edge_pos):
+            raise ValueError("arrowsize should have the same length as edgelist")
+
+    def __call__(self, i):
+        (x1, y1), (x2, y2) = self.edge_pos[i]
+        shrink_source = 0  # space from source to tail
+        shrink_target = 0  # space from  head to target
+        if (
+            self.np.iterable(self.min_source_margin)
+            and not isinstance(self.min_source_margin, str)
+            and not isinstance(self.min_source_margin, tuple)
+        ):
+            min_source_margin = self.min_source_margin[i]
+        else:
+            min_source_margin = self.min_source_margin
+
+        if (
+            self.np.iterable(self.min_target_margin)
+            and not isinstance(self.min_target_margin, str)
+            and not isinstance(self.min_target_margin, tuple)
+        ):
+            min_target_margin = self.min_target_margin[i]
+        else:
+            min_target_margin = self.min_target_margin
+
+        if self.np.iterable(self.node_size):  # many node sizes
+            source, target = self.edgelist[i][:2]
+            source_node_size = self.node_size[self.nodelist.index(source)]
+            target_node_size = self.node_size[self.nodelist.index(target)]
+            shrink_source = self.to_marker_edge(source_node_size, self.node_shape)
+            shrink_target = self.to_marker_edge(target_node_size, self.node_shape)
+        else:
+            shrink_source = self.to_marker_edge(self.node_size, self.node_shape)
+            shrink_target = shrink_source
+        shrink_source = max(shrink_source, min_source_margin)
+        shrink_target = max(shrink_target, min_target_margin)
+
+        # scale factor of arrow head
+        if isinstance(self.arrowsize, list):
+            mutation_scale = self.arrowsize[i]
+        else:
+            mutation_scale = self.arrowsize
+
+        if len(self.arrow_colors) > i:
+            arrow_color = self.arrow_colors[i]
+        elif len(self.arrow_colors) == 1:
+            arrow_color = self.arrow_colors[0]
+        else:  # Cycle through colors
+            arrow_color = self.arrow_colors[i % len(self.arrow_colors)]
+
+        if self.np.iterable(self.linewidth):
+            if len(self.linewidth) > i:
+                linewidth = self.linewidth[i]
+            else:
+                linewidth = self.linewidth[i % len(self.linewidth)]
+        else:
+            linewidth = self.linewidth
+
+        if (
+            self.np.iterable(self.style)
+            and not isinstance(self.style, str)
+            and not isinstance(self.style, tuple)
+        ):
+            if len(self.style) > i:
+                linestyle = self.style[i]
+            else:  # Cycle through styles
+                linestyle = self.style[i % len(self.style)]
+        else:
+            linestyle = self.style
+
+        if x1 == x2 and y1 == y2:
+            connectionstyle = self.connectionstyle_factory.self_loop(
+                self.edge_indices[i]
+            )
+        else:
+            connectionstyle = self.connectionstyle_factory.curved(self.edge_indices[i])
+
+        if (
+            self.np.iterable(self.arrowstyle)
+            and not isinstance(self.arrowstyle, str)
+            and not isinstance(self.arrowstyle, tuple)
+        ):
+            arrowstyle = self.arrowstyle[i]
+        else:
+            arrowstyle = self.arrowstyle
+
+        return self.mpl.patches.FancyArrowPatch(
+            (x1, y1),
+            (x2, y2),
+            arrowstyle=arrowstyle,
+            shrinkA=shrink_source,
+            shrinkB=shrink_target,
+            mutation_scale=mutation_scale,
+            color=arrow_color,
+            linewidth=linewidth,
+            connectionstyle=connectionstyle,
+            linestyle=linestyle,
+            zorder=1,  # arrows go behind nodes
+        )
+
+    def to_marker_edge(self, marker_size, marker):
+        if marker in "s^>v',
+        For undirected graphs default to '-'.
+
+        See `matplotlib.patches.ArrowStyle` for more options.
+
+    arrowsize : int or list of ints(default=10)
+        For directed graphs, choose the size of the arrow head's length and
+        width. See `matplotlib.patches.FancyArrowPatch` for attribute
+        `mutation_scale` for more info.
+
+    connectionstyle : string or iterable of strings (default="arc3")
+        Pass the connectionstyle parameter to create curved arc of rounding
+        radius rad. For example, connectionstyle='arc3,rad=0.2'.
+        See `matplotlib.patches.ConnectionStyle` and
+        `matplotlib.patches.FancyArrowPatch` for more info.
+        If Iterable, index indicates i'th edge key of MultiGraph
+
+    node_size : scalar or array (default=300)
+        Size of nodes. Though the nodes are not drawn with this function, the
+        node size is used in determining edge positioning.
+
+    nodelist : list, optional (default=G.nodes())
+       This provides the node order for the `node_size` array (if it is an array).
+
+    node_shape :  string (default='o')
+        The marker used for nodes, used in determining edge positioning.
+        Specification is as a `matplotlib.markers` marker, e.g. one of 'so^>v>> G = nx.dodecahedral_graph()
+    >>> edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
+
+    >>> G = nx.DiGraph()
+    >>> G.add_edges_from([(1, 2), (1, 3), (2, 3)])
+    >>> arcs = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
+    >>> alphas = [0.3, 0.4, 0.5]
+    >>> for i, arc in enumerate(arcs):  # change alpha values of arcs
+    ...     arc.set_alpha(alphas[i])
+
+    The FancyArrowPatches corresponding to self-loops are not always
+    returned, but can always be accessed via the ``patches`` attribute of the
+    `matplotlib.Axes` object.
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots()
+    >>> G = nx.Graph([(0, 1), (0, 0)])  # Self-loop at node 0
+    >>> edge_collection = nx.draw_networkx_edges(G, pos=nx.circular_layout(G), ax=ax)
+    >>> self_loop_fap = ax.patches[0]
+
+    Also see the NetworkX drawing examples at
+    https://networkx.org/documentation/latest/auto_examples/index.html
+
+    See Also
+    --------
+    draw
+    draw_networkx
+    draw_networkx_nodes
+    draw_networkx_labels
+    draw_networkx_edge_labels
+
+    """
+    import warnings
+
+    import matplotlib as mpl
+    import matplotlib.collections  # call as mpl.collections
+    import matplotlib.colors  # call as mpl.colors
+    import matplotlib.pyplot as plt
+    import numpy as np
+
+    # The default behavior is to use LineCollection to draw edges for
+    # undirected graphs (for performance reasons) and use FancyArrowPatches
+    # for directed graphs.
+    # The `arrows` keyword can be used to override the default behavior
+    if arrows is None:
+        use_linecollection = not (G.is_directed() or G.is_multigraph())
+    else:
+        if not isinstance(arrows, bool):
+            raise TypeError("Argument `arrows` must be of type bool or None")
+        use_linecollection = not arrows
+
+    if isinstance(connectionstyle, str):
+        connectionstyle = [connectionstyle]
+    elif np.iterable(connectionstyle):
+        connectionstyle = list(connectionstyle)
+    else:
+        msg = "draw_networkx_edges arg `connectionstyle` must be str or iterable"
+        raise nx.NetworkXError(msg)
+
+    # Some kwargs only apply to FancyArrowPatches. Warn users when they use
+    # non-default values for these kwargs when LineCollection is being used
+    # instead of silently ignoring the specified option
+    if use_linecollection:
+        msg = (
+            "\n\nThe {0} keyword argument is not applicable when drawing edges\n"
+            "with LineCollection.\n\n"
+            "To make this warning go away, either specify `arrows=True` to\n"
+            "force FancyArrowPatches or use the default values.\n"
+            "Note that using FancyArrowPatches may be slow for large graphs.\n"
+        )
+        if arrowstyle is not None:
+            warnings.warn(msg.format("arrowstyle"), category=UserWarning, stacklevel=2)
+        if arrowsize != 10:
+            warnings.warn(msg.format("arrowsize"), category=UserWarning, stacklevel=2)
+        if min_source_margin != 0:
+            warnings.warn(
+                msg.format("min_source_margin"), category=UserWarning, stacklevel=2
+            )
+        if min_target_margin != 0:
+            warnings.warn(
+                msg.format("min_target_margin"), category=UserWarning, stacklevel=2
+            )
+        if any(cs != "arc3" for cs in connectionstyle):
+            warnings.warn(
+                msg.format("connectionstyle"), category=UserWarning, stacklevel=2
+            )
+
+    # NOTE: Arrowstyle modification must occur after the warnings section
+    if arrowstyle is None:
+        arrowstyle = "-|>" if G.is_directed() else "-"
+
+    if ax is None:
+        ax = plt.gca()
+
+    if edgelist is None:
+        edgelist = list(G.edges)  # (u, v, k) for multigraph (u, v) otherwise
+
+    if len(edgelist):
+        if G.is_multigraph():
+            key_count = collections.defaultdict(lambda: itertools.count(0))
+            edge_indices = [next(key_count[tuple(e[:2])]) for e in edgelist]
+        else:
+            edge_indices = [0] * len(edgelist)
+    else:  # no edges!
+        return []
+
+    if nodelist is None:
+        nodelist = list(G.nodes())
+
+    # FancyArrowPatch handles color=None different from LineCollection
+    if edge_color is None:
+        edge_color = "k"
+
+    # set edge positions
+    edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist])
+
+    # Check if edge_color is an array of floats and map to edge_cmap.
+    # This is the only case handled differently from matplotlib
+    if (
+        np.iterable(edge_color)
+        and (len(edge_color) == len(edge_pos))
+        and np.all([isinstance(c, Number) for c in edge_color])
+    ):
+        if edge_cmap is not None:
+            assert isinstance(edge_cmap, mpl.colors.Colormap)
+        else:
+            edge_cmap = plt.get_cmap()
+        if edge_vmin is None:
+            edge_vmin = min(edge_color)
+        if edge_vmax is None:
+            edge_vmax = max(edge_color)
+        color_normal = mpl.colors.Normalize(vmin=edge_vmin, vmax=edge_vmax)
+        edge_color = [edge_cmap(color_normal(e)) for e in edge_color]
+
+    # compute initial view
+    minx = np.amin(np.ravel(edge_pos[:, :, 0]))
+    maxx = np.amax(np.ravel(edge_pos[:, :, 0]))
+    miny = np.amin(np.ravel(edge_pos[:, :, 1]))
+    maxy = np.amax(np.ravel(edge_pos[:, :, 1]))
+    w = maxx - minx
+    h = maxy - miny
+
+    # Self-loops are scaled by view extent, except in cases the extent
+    # is 0, e.g. for a single node. In this case, fall back to scaling
+    # by the maximum node size
+    selfloop_height = h if h != 0 else 0.005 * np.array(node_size).max()
+    fancy_arrow_factory = FancyArrowFactory(
+        edge_pos,
+        edgelist,
+        nodelist,
+        edge_indices,
+        node_size,
+        selfloop_height,
+        connectionstyle,
+        node_shape,
+        arrowstyle,
+        arrowsize,
+        edge_color,
+        alpha,
+        width,
+        style,
+        min_source_margin,
+        min_target_margin,
+        ax=ax,
+    )
+
+    # Draw the edges
+    if use_linecollection:
+        edge_collection = mpl.collections.LineCollection(
+            edge_pos,
+            colors=edge_color,
+            linewidths=width,
+            antialiaseds=(1,),
+            linestyle=style,
+            alpha=alpha,
+        )
+        edge_collection.set_cmap(edge_cmap)
+        edge_collection.set_clim(edge_vmin, edge_vmax)
+        edge_collection.set_zorder(1)  # edges go behind nodes
+        edge_collection.set_label(label)
+        ax.add_collection(edge_collection)
+        edge_viz_obj = edge_collection
+
+        # Make sure selfloop edges are also drawn
+        # ---------------------------------------
+        selfloops_to_draw = [loop for loop in nx.selfloop_edges(G) if loop in edgelist]
+        if selfloops_to_draw:
+            edgelist_tuple = list(map(tuple, edgelist))
+            arrow_collection = []
+            for loop in selfloops_to_draw:
+                i = edgelist_tuple.index(loop)
+                arrow = fancy_arrow_factory(i)
+                arrow_collection.append(arrow)
+                ax.add_patch(arrow)
+    else:
+        edge_viz_obj = []
+        for i in range(len(edgelist)):
+            arrow = fancy_arrow_factory(i)
+            ax.add_patch(arrow)
+            edge_viz_obj.append(arrow)
+
+    # update view after drawing
+    padx, pady = 0.05 * w, 0.05 * h
+    corners = (minx - padx, miny - pady), (maxx + padx, maxy + pady)
+    ax.update_datalim(corners)
+    ax.autoscale_view()
+
+    if hide_ticks:
+        ax.tick_params(
+            axis="both",
+            which="both",
+            bottom=False,
+            left=False,
+            labelbottom=False,
+            labelleft=False,
+        )
+
+    return edge_viz_obj
+
+
+def draw_networkx_labels(
+    G,
+    pos,
+    labels=None,
+    font_size=12,
+    font_color="k",
+    font_family="sans-serif",
+    font_weight="normal",
+    alpha=None,
+    bbox=None,
+    horizontalalignment="center",
+    verticalalignment="center",
+    ax=None,
+    clip_on=True,
+    hide_ticks=True,
+):
+    """Draw node labels on the graph G.
+
+    Parameters
+    ----------
+    G : graph
+        A networkx graph
+
+    pos : dictionary
+        A dictionary with nodes as keys and positions as values.
+        Positions should be sequences of length 2.
+
+    labels : dictionary (default={n: n for n in G})
+        Node labels in a dictionary of text labels keyed by node.
+        Node-keys in labels should appear as keys in `pos`.
+        If needed use: `{n:lab for n,lab in labels.items() if n in pos}`
+
+    font_size : int or dictionary of nodes to ints (default=12)
+        Font size for text labels.
+
+    font_color : color or dictionary of nodes to colors (default='k' black)
+        Font color string. Color can be string or rgb (or rgba) tuple of
+        floats from 0-1.
+
+    font_weight : string or dictionary of nodes to strings (default='normal')
+        Font weight.
+
+    font_family : string or dictionary of nodes to strings (default='sans-serif')
+        Font family.
+
+    alpha : float or None or dictionary of nodes to floats (default=None)
+        The text transparency.
+
+    bbox : Matplotlib bbox, (default is Matplotlib's ax.text default)
+        Specify text box properties (e.g. shape, color etc.) for node labels.
+
+    horizontalalignment : string or array of strings (default='center')
+        Horizontal alignment {'center', 'right', 'left'}. If an array is
+        specified it must be the same length as `nodelist`.
+
+    verticalalignment : string (default='center')
+        Vertical alignment {'center', 'top', 'bottom', 'baseline', 'center_baseline'}.
+        If an array is specified it must be the same length as `nodelist`.
+
+    ax : Matplotlib Axes object, optional
+        Draw the graph in the specified Matplotlib axes.
+
+    clip_on : bool (default=True)
+        Turn on clipping of node labels at axis boundaries
+
+    hide_ticks : bool, optional
+        Hide ticks of axes. When `True` (the default), ticks and ticklabels
+        are removed from the axes. To set ticks and tick labels to the pyplot default,
+        use ``hide_ticks=False``.
+
+    Returns
+    -------
+    dict
+        `dict` of labels keyed on the nodes
+
+    Examples
+    --------
+    >>> G = nx.dodecahedral_graph()
+    >>> labels = nx.draw_networkx_labels(G, pos=nx.spring_layout(G))
+
+    Also see the NetworkX drawing examples at
+    https://networkx.org/documentation/latest/auto_examples/index.html
+
+    See Also
+    --------
+    draw
+    draw_networkx
+    draw_networkx_nodes
+    draw_networkx_edges
+    draw_networkx_edge_labels
+    """
+    import matplotlib.pyplot as plt
+
+    if ax is None:
+        ax = plt.gca()
+
+    if labels is None:
+        labels = {n: n for n in G.nodes()}
+
+    individual_params = set()
+
+    def check_individual_params(p_value, p_name):
+        if isinstance(p_value, dict):
+            if len(p_value) != len(labels):
+                raise ValueError(f"{p_name} must have the same length as labels.")
+            individual_params.add(p_name)
+
+    def get_param_value(node, p_value, p_name):
+        if p_name in individual_params:
+            return p_value[node]
+        return p_value
+
+    check_individual_params(font_size, "font_size")
+    check_individual_params(font_color, "font_color")
+    check_individual_params(font_weight, "font_weight")
+    check_individual_params(font_family, "font_family")
+    check_individual_params(alpha, "alpha")
+
+    text_items = {}  # there is no text collection so we'll fake one
+    for n, label in labels.items():
+        (x, y) = pos[n]
+        if not isinstance(label, str):
+            label = str(label)  # this makes "1" and 1 labeled the same
+        t = ax.text(
+            x,
+            y,
+            label,
+            size=get_param_value(n, font_size, "font_size"),
+            color=get_param_value(n, font_color, "font_color"),
+            family=get_param_value(n, font_family, "font_family"),
+            weight=get_param_value(n, font_weight, "font_weight"),
+            alpha=get_param_value(n, alpha, "alpha"),
+            horizontalalignment=horizontalalignment,
+            verticalalignment=verticalalignment,
+            transform=ax.transData,
+            bbox=bbox,
+            clip_on=clip_on,
+        )
+        text_items[n] = t
+
+    if hide_ticks:
+        ax.tick_params(
+            axis="both",
+            which="both",
+            bottom=False,
+            left=False,
+            labelbottom=False,
+            labelleft=False,
+        )
+
+    return text_items
+
+
+def draw_networkx_edge_labels(
+    G,
+    pos,
+    edge_labels=None,
+    label_pos=0.5,
+    font_size=10,
+    font_color="k",
+    font_family="sans-serif",
+    font_weight="normal",
+    alpha=None,
+    bbox=None,
+    horizontalalignment="center",
+    verticalalignment="center",
+    ax=None,
+    rotate=True,
+    clip_on=True,
+    node_size=300,
+    nodelist=None,
+    connectionstyle="arc3",
+    hide_ticks=True,
+):
+    """Draw edge labels.
+
+    Parameters
+    ----------
+    G : graph
+        A networkx graph
+
+    pos : dictionary
+        A dictionary with nodes as keys and positions as values.
+        Positions should be sequences of length 2.
+
+    edge_labels : dictionary (default=None)
+        Edge labels in a dictionary of labels keyed by edge two-tuple.
+        Only labels for the keys in the dictionary are drawn.
+
+    label_pos : float (default=0.5)
+        Position of edge label along edge (0=head, 0.5=center, 1=tail)
+
+    font_size : int (default=10)
+        Font size for text labels
+
+    font_color : color (default='k' black)
+        Font color string. Color can be string or rgb (or rgba) tuple of
+        floats from 0-1.
+
+    font_weight : string (default='normal')
+        Font weight
+
+    font_family : string (default='sans-serif')
+        Font family
+
+    alpha : float or None (default=None)
+        The text transparency
+
+    bbox : Matplotlib bbox, optional
+        Specify text box properties (e.g. shape, color etc.) for edge labels.
+        Default is {boxstyle='round', ec=(1.0, 1.0, 1.0), fc=(1.0, 1.0, 1.0)}.
+
+    horizontalalignment : string (default='center')
+        Horizontal alignment {'center', 'right', 'left'}
+
+    verticalalignment : string (default='center')
+        Vertical alignment {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
+
+    ax : Matplotlib Axes object, optional
+        Draw the graph in the specified Matplotlib axes.
+
+    rotate : bool (default=True)
+        Rotate edge labels to lie parallel to edges
+
+    clip_on : bool (default=True)
+        Turn on clipping of edge labels at axis boundaries
+
+    node_size : scalar or array (default=300)
+        Size of nodes.  If an array it must be the same length as nodelist.
+
+    nodelist : list, optional (default=G.nodes())
+       This provides the node order for the `node_size` array (if it is an array).
+
+    connectionstyle : string or iterable of strings (default="arc3")
+        Pass the connectionstyle parameter to create curved arc of rounding
+        radius rad. For example, connectionstyle='arc3,rad=0.2'.
+        See `matplotlib.patches.ConnectionStyle` and
+        `matplotlib.patches.FancyArrowPatch` for more info.
+        If Iterable, index indicates i'th edge key of MultiGraph
+
+    hide_ticks : bool, optional
+        Hide ticks of axes. When `True` (the default), ticks and ticklabels
+        are removed from the axes. To set ticks and tick labels to the pyplot default,
+        use ``hide_ticks=False``.
+
+    Returns
+    -------
+    dict
+        `dict` of labels keyed by edge
+
+    Examples
+    --------
+    >>> G = nx.dodecahedral_graph()
+    >>> edge_labels = nx.draw_networkx_edge_labels(G, pos=nx.spring_layout(G))
+
+    Also see the NetworkX drawing examples at
+    https://networkx.org/documentation/latest/auto_examples/index.html
+
+    See Also
+    --------
+    draw
+    draw_networkx
+    draw_networkx_nodes
+    draw_networkx_edges
+    draw_networkx_labels
+    """
+    import matplotlib as mpl
+    import matplotlib.pyplot as plt
+    import numpy as np
+
+    class CurvedArrowText(CurvedArrowTextBase, mpl.text.Text):
+        pass
+
+    # use default box of white with white border
+    if bbox is None:
+        bbox = {"boxstyle": "round", "ec": (1.0, 1.0, 1.0), "fc": (1.0, 1.0, 1.0)}
+
+    if isinstance(connectionstyle, str):
+        connectionstyle = [connectionstyle]
+    elif np.iterable(connectionstyle):
+        connectionstyle = list(connectionstyle)
+    else:
+        raise nx.NetworkXError(
+            "draw_networkx_edges arg `connectionstyle` must be"
+            "string or iterable of strings"
+        )
+
+    if ax is None:
+        ax = plt.gca()
+
+    if edge_labels is None:
+        kwds = {"keys": True} if G.is_multigraph() else {}
+        edge_labels = {tuple(edge): d for *edge, d in G.edges(data=True, **kwds)}
+    # NOTHING TO PLOT
+    if not edge_labels:
+        return {}
+    edgelist, labels = zip(*edge_labels.items())
+
+    if nodelist is None:
+        nodelist = list(G.nodes())
+
+    # set edge positions
+    edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist])
+
+    if G.is_multigraph():
+        key_count = collections.defaultdict(lambda: itertools.count(0))
+        edge_indices = [next(key_count[tuple(e[:2])]) for e in edgelist]
+    else:
+        edge_indices = [0] * len(edgelist)
+
+    # Used to determine self loop mid-point
+    # Note, that this will not be accurate,
+    #   if not drawing edge_labels for all edges drawn
+    h = 0
+    if edge_labels:
+        miny = np.amin(np.ravel(edge_pos[:, :, 1]))
+        maxy = np.amax(np.ravel(edge_pos[:, :, 1]))
+        h = maxy - miny
+    selfloop_height = h if h != 0 else 0.005 * np.array(node_size).max()
+    fancy_arrow_factory = FancyArrowFactory(
+        edge_pos,
+        edgelist,
+        nodelist,
+        edge_indices,
+        node_size,
+        selfloop_height,
+        connectionstyle,
+        ax=ax,
+    )
+
+    individual_params = {}
+
+    def check_individual_params(p_value, p_name):
+        # TODO should this be list or array (as in a numpy array)?
+        if isinstance(p_value, list):
+            if len(p_value) != len(edgelist):
+                raise ValueError(f"{p_name} must have the same length as edgelist.")
+            individual_params[p_name] = p_value.iter()
+
+    # Don't need to pass in an edge because these are lists, not dicts
+    def get_param_value(p_value, p_name):
+        if p_name in individual_params:
+            return next(individual_params[p_name])
+        return p_value
+
+    check_individual_params(font_size, "font_size")
+    check_individual_params(font_color, "font_color")
+    check_individual_params(font_weight, "font_weight")
+    check_individual_params(alpha, "alpha")
+    check_individual_params(horizontalalignment, "horizontalalignment")
+    check_individual_params(verticalalignment, "verticalalignment")
+    check_individual_params(rotate, "rotate")
+    check_individual_params(label_pos, "label_pos")
+
+    text_items = {}
+    for i, (edge, label) in enumerate(zip(edgelist, labels)):
+        if not isinstance(label, str):
+            label = str(label)  # this makes "1" and 1 labeled the same
+
+        n1, n2 = edge[:2]
+        arrow = fancy_arrow_factory(i)
+        if n1 == n2:
+            connectionstyle_obj = arrow.get_connectionstyle()
+            posA = ax.transData.transform(pos[n1])
+            path_disp = connectionstyle_obj(posA, posA)
+            path_data = ax.transData.inverted().transform_path(path_disp)
+            x, y = path_data.vertices[0]
+            text_items[edge] = ax.text(
+                x,
+                y,
+                label,
+                size=get_param_value(font_size, "font_size"),
+                color=get_param_value(font_color, "font_color"),
+                family=get_param_value(font_family, "font_family"),
+                weight=get_param_value(font_weight, "font_weight"),
+                alpha=get_param_value(alpha, "alpha"),
+                horizontalalignment=get_param_value(
+                    horizontalalignment, "horizontalalignment"
+                ),
+                verticalalignment=get_param_value(
+                    verticalalignment, "verticalalignment"
+                ),
+                rotation=0,
+                transform=ax.transData,
+                bbox=bbox,
+                zorder=1,
+                clip_on=clip_on,
+            )
+        else:
+            text_items[edge] = CurvedArrowText(
+                arrow,
+                label,
+                size=get_param_value(font_size, "font_size"),
+                color=get_param_value(font_color, "font_color"),
+                family=get_param_value(font_family, "font_family"),
+                weight=get_param_value(font_weight, "font_weight"),
+                alpha=get_param_value(alpha, "alpha"),
+                horizontalalignment=get_param_value(
+                    horizontalalignment, "horizontalalignment"
+                ),
+                verticalalignment=get_param_value(
+                    verticalalignment, "verticalalignment"
+                ),
+                transform=ax.transData,
+                bbox=bbox,
+                zorder=1,
+                clip_on=clip_on,
+                label_pos=get_param_value(label_pos, "label_pos"),
+                labels_horizontal=not get_param_value(rotate, "rotate"),
+                ax=ax,
+            )
+
+    if hide_ticks:
+        ax.tick_params(
+            axis="both",
+            which="both",
+            bottom=False,
+            left=False,
+            labelbottom=False,
+            labelleft=False,
+        )
+
+    return text_items
+
+
+def draw_bipartite(G, **kwargs):
+    """Draw the graph `G` with a bipartite layout.
+
+    This is a convenience function equivalent to::
+
+        nx.draw(G, pos=nx.bipartite_layout(G), **kwargs)
+
+    Parameters
+    ----------
+    G : graph
+        A networkx graph
+
+    kwargs : optional keywords
+        See `draw_networkx` for a description of optional keywords.
+
+    Raises
+    ------
+    NetworkXError :
+        If `G` is not bipartite.
+
+    Notes
+    -----
+    The layout is computed each time this function is called. For
+    repeated drawing it is much more efficient to call
+    `~networkx.drawing.layout.bipartite_layout` directly and reuse the result::
+
+        >>> G = nx.complete_bipartite_graph(3, 3)
+        >>> pos = nx.bipartite_layout(G)
+        >>> nx.draw(G, pos=pos)  # Draw the original graph
+        >>> # Draw a subgraph, reusing the same node positions
+        >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
+
+    Examples
+    --------
+    >>> G = nx.complete_bipartite_graph(2, 5)
+    >>> nx.draw_bipartite(G)
+
+    See Also
+    --------
+    :func:`~networkx.drawing.layout.bipartite_layout`
+    """
+    draw(G, pos=nx.bipartite_layout(G), **kwargs)
+
+
+def draw_circular(G, **kwargs):
+    """Draw the graph `G` with a circular layout.
+
+    This is a convenience function equivalent to::
+
+        nx.draw(G, pos=nx.circular_layout(G), **kwargs)
+
+    Parameters
+    ----------
+    G : graph
+        A networkx graph
+
+    kwargs : optional keywords
+        See `draw_networkx` for a description of optional keywords.
+
+    Notes
+    -----
+    The layout is computed each time this function is called. For
+    repeated drawing it is much more efficient to call
+    `~networkx.drawing.layout.circular_layout` directly and reuse the result::
+
+        >>> G = nx.complete_graph(5)
+        >>> pos = nx.circular_layout(G)
+        >>> nx.draw(G, pos=pos)  # Draw the original graph
+        >>> # Draw a subgraph, reusing the same node positions
+        >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
+
+    Examples
+    --------
+    >>> G = nx.path_graph(5)
+    >>> nx.draw_circular(G)
+
+    See Also
+    --------
+    :func:`~networkx.drawing.layout.circular_layout`
+    """
+    draw(G, pos=nx.circular_layout(G), **kwargs)
+
+
+def draw_kamada_kawai(G, **kwargs):
+    """Draw the graph `G` with a Kamada-Kawai force-directed layout.
+
+    This is a convenience function equivalent to::
+
+        nx.draw(G, pos=nx.kamada_kawai_layout(G), **kwargs)
+
+    Parameters
+    ----------
+    G : graph
+        A networkx graph
+
+    kwargs : optional keywords
+        See `draw_networkx` for a description of optional keywords.
+
+    Notes
+    -----
+    The layout is computed each time this function is called.
+    For repeated drawing it is much more efficient to call
+    `~networkx.drawing.layout.kamada_kawai_layout` directly and reuse the
+    result::
+
+        >>> G = nx.complete_graph(5)
+        >>> pos = nx.kamada_kawai_layout(G)
+        >>> nx.draw(G, pos=pos)  # Draw the original graph
+        >>> # Draw a subgraph, reusing the same node positions
+        >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
+
+    Examples
+    --------
+    >>> G = nx.path_graph(5)
+    >>> nx.draw_kamada_kawai(G)
+
+    See Also
+    --------
+    :func:`~networkx.drawing.layout.kamada_kawai_layout`
+    """
+    draw(G, pos=nx.kamada_kawai_layout(G), **kwargs)
+
+
+def draw_random(G, **kwargs):
+    """Draw the graph `G` with a random layout.
+
+    This is a convenience function equivalent to::
+
+        nx.draw(G, pos=nx.random_layout(G), **kwargs)
+
+    Parameters
+    ----------
+    G : graph
+        A networkx graph
+
+    kwargs : optional keywords
+        See `draw_networkx` for a description of optional keywords.
+
+    Notes
+    -----
+    The layout is computed each time this function is called.
+    For repeated drawing it is much more efficient to call
+    `~networkx.drawing.layout.random_layout` directly and reuse the result::
+
+        >>> G = nx.complete_graph(5)
+        >>> pos = nx.random_layout(G)
+        >>> nx.draw(G, pos=pos)  # Draw the original graph
+        >>> # Draw a subgraph, reusing the same node positions
+        >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
+
+    Examples
+    --------
+    >>> G = nx.lollipop_graph(4, 3)
+    >>> nx.draw_random(G)
+
+    See Also
+    --------
+    :func:`~networkx.drawing.layout.random_layout`
+    """
+    draw(G, pos=nx.random_layout(G), **kwargs)
+
+
+def draw_spectral(G, **kwargs):
+    """Draw the graph `G` with a spectral 2D layout.
+
+    This is a convenience function equivalent to::
+
+        nx.draw(G, pos=nx.spectral_layout(G), **kwargs)
+
+    For more information about how node positions are determined, see
+    `~networkx.drawing.layout.spectral_layout`.
+
+    Parameters
+    ----------
+    G : graph
+        A networkx graph
+
+    kwargs : optional keywords
+        See `draw_networkx` for a description of optional keywords.
+
+    Notes
+    -----
+    The layout is computed each time this function is called.
+    For repeated drawing it is much more efficient to call
+    `~networkx.drawing.layout.spectral_layout` directly and reuse the result::
+
+        >>> G = nx.complete_graph(5)
+        >>> pos = nx.spectral_layout(G)
+        >>> nx.draw(G, pos=pos)  # Draw the original graph
+        >>> # Draw a subgraph, reusing the same node positions
+        >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
+
+    Examples
+    --------
+    >>> G = nx.path_graph(5)
+    >>> nx.draw_spectral(G)
+
+    See Also
+    --------
+    :func:`~networkx.drawing.layout.spectral_layout`
+    """
+    draw(G, pos=nx.spectral_layout(G), **kwargs)
+
+
+def draw_spring(G, **kwargs):
+    """Draw the graph `G` with a spring layout.
+
+    This is a convenience function equivalent to::
+
+        nx.draw(G, pos=nx.spring_layout(G), **kwargs)
+
+    Parameters
+    ----------
+    G : graph
+        A networkx graph
+
+    kwargs : optional keywords
+        See `draw_networkx` for a description of optional keywords.
+
+    Notes
+    -----
+    `~networkx.drawing.layout.spring_layout` is also the default layout for
+    `draw`, so this function is equivalent to `draw`.
+
+    The layout is computed each time this function is called.
+    For repeated drawing it is much more efficient to call
+    `~networkx.drawing.layout.spring_layout` directly and reuse the result::
+
+        >>> G = nx.complete_graph(5)
+        >>> pos = nx.spring_layout(G)
+        >>> nx.draw(G, pos=pos)  # Draw the original graph
+        >>> # Draw a subgraph, reusing the same node positions
+        >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
+
+    Examples
+    --------
+    >>> G = nx.path_graph(20)
+    >>> nx.draw_spring(G)
+
+    See Also
+    --------
+    draw
+    :func:`~networkx.drawing.layout.spring_layout`
+    """
+    draw(G, pos=nx.spring_layout(G), **kwargs)
+
+
+def draw_shell(G, nlist=None, **kwargs):
+    """Draw networkx graph `G` with shell layout.
+
+    This is a convenience function equivalent to::
+
+        nx.draw(G, pos=nx.shell_layout(G, nlist=nlist), **kwargs)
+
+    Parameters
+    ----------
+    G : graph
+        A networkx graph
+
+    nlist : list of list of nodes, optional
+        A list containing lists of nodes representing the shells.
+        Default is `None`, meaning all nodes are in a single shell.
+        See `~networkx.drawing.layout.shell_layout` for details.
+
+    kwargs : optional keywords
+        See `draw_networkx` for a description of optional keywords.
+
+    Notes
+    -----
+    The layout is computed each time this function is called.
+    For repeated drawing it is much more efficient to call
+    `~networkx.drawing.layout.shell_layout` directly and reuse the result::
+
+        >>> G = nx.complete_graph(5)
+        >>> pos = nx.shell_layout(G)
+        >>> nx.draw(G, pos=pos)  # Draw the original graph
+        >>> # Draw a subgraph, reusing the same node positions
+        >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> shells = [[0], [1, 2, 3]]
+    >>> nx.draw_shell(G, nlist=shells)
+
+    See Also
+    --------
+    :func:`~networkx.drawing.layout.shell_layout`
+    """
+    draw(G, pos=nx.shell_layout(G, nlist=nlist), **kwargs)
+
+
+def draw_planar(G, **kwargs):
+    """Draw a planar networkx graph `G` with planar layout.
+
+    This is a convenience function equivalent to::
+
+        nx.draw(G, pos=nx.planar_layout(G), **kwargs)
+
+    Parameters
+    ----------
+    G : graph
+        A planar networkx graph
+
+    kwargs : optional keywords
+        See `draw_networkx` for a description of optional keywords.
+
+    Raises
+    ------
+    NetworkXException
+        When `G` is not planar
+
+    Notes
+    -----
+    The layout is computed each time this function is called.
+    For repeated drawing it is much more efficient to call
+    `~networkx.drawing.layout.planar_layout` directly and reuse the result::
+
+        >>> G = nx.path_graph(5)
+        >>> pos = nx.planar_layout(G)
+        >>> nx.draw(G, pos=pos)  # Draw the original graph
+        >>> # Draw a subgraph, reusing the same node positions
+        >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> nx.draw_planar(G)
+
+    See Also
+    --------
+    :func:`~networkx.drawing.layout.planar_layout`
+    """
+    draw(G, pos=nx.planar_layout(G), **kwargs)
+
+
+def draw_forceatlas2(G, **kwargs):
+    """Draw a networkx graph with forceatlas2 layout.
+
+    This is a convenience function equivalent to::
+
+       nx.draw(G, pos=nx.forceatlas2_layout(G), **kwargs)
+
+    Parameters
+    ----------
+    G : graph
+       A networkx graph
+
+    kwargs : optional keywords
+       See networkx.draw_networkx() for a description of optional keywords,
+       with the exception of the pos parameter which is not used by this
+       function.
+    """
+    draw(G, pos=nx.forceatlas2_layout(G), **kwargs)
+
+
+def apply_alpha(colors, alpha, elem_list, cmap=None, vmin=None, vmax=None):
+    """Apply an alpha (or list of alphas) to the colors provided.
+
+    Parameters
+    ----------
+
+    colors : color string or array of floats (default='r')
+        Color of element. Can be a single color format string,
+        or a sequence of colors with the same length as nodelist.
+        If numeric values are specified they will be mapped to
+        colors using the cmap and vmin,vmax parameters.  See
+        matplotlib.scatter for more details.
+
+    alpha : float or array of floats
+        Alpha values for elements. This can be a single alpha value, in
+        which case it will be applied to all the elements of color. Otherwise,
+        if it is an array, the elements of alpha will be applied to the colors
+        in order (cycling through alpha multiple times if necessary).
+
+    elem_list : array of networkx objects
+        The list of elements which are being colored. These could be nodes,
+        edges or labels.
+
+    cmap : matplotlib colormap
+        Color map for use if colors is a list of floats corresponding to points
+        on a color mapping.
+
+    vmin, vmax : float
+        Minimum and maximum values for normalizing colors if a colormap is used
+
+    Returns
+    -------
+
+    rgba_colors : numpy ndarray
+        Array containing RGBA format values for each of the node colours.
+
+    """
+    from itertools import cycle, islice
+
+    import matplotlib as mpl
+    import matplotlib.cm  # call as mpl.cm
+    import matplotlib.colors  # call as mpl.colors
+    import numpy as np
+
+    # If we have been provided with a list of numbers as long as elem_list,
+    # apply the color mapping.
+    if len(colors) == len(elem_list) and isinstance(colors[0], Number):
+        mapper = mpl.cm.ScalarMappable(cmap=cmap)
+        mapper.set_clim(vmin, vmax)
+        rgba_colors = mapper.to_rgba(colors)
+    # Otherwise, convert colors to matplotlib's RGB using the colorConverter
+    # object.  These are converted to numpy ndarrays to be consistent with the
+    # to_rgba method of ScalarMappable.
+    else:
+        try:
+            rgba_colors = np.array([mpl.colors.colorConverter.to_rgba(colors)])
+        except ValueError:
+            rgba_colors = np.array(
+                [mpl.colors.colorConverter.to_rgba(color) for color in colors]
+            )
+    # Set the final column of the rgba_colors to have the relevant alpha values
+    try:
+        # If alpha is longer than the number of colors, resize to the number of
+        # elements.  Also, if rgba_colors.size (the number of elements of
+        # rgba_colors) is the same as the number of elements, resize the array,
+        # to avoid it being interpreted as a colormap by scatter()
+        if len(alpha) > len(rgba_colors) or rgba_colors.size == len(elem_list):
+            rgba_colors = np.resize(rgba_colors, (len(elem_list), 4))
+            rgba_colors[1:, 0] = rgba_colors[0, 0]
+            rgba_colors[1:, 1] = rgba_colors[0, 1]
+            rgba_colors[1:, 2] = rgba_colors[0, 2]
+        rgba_colors[:, 3] = list(islice(cycle(alpha), len(rgba_colors)))
+    except TypeError:
+        rgba_colors[:, -1] = alpha
+    return rgba_colors
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ec027c2405b6f9de2e7b6a0f7c18d782ac8761c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__init__.py
@@ -0,0 +1,34 @@
+"""
+A package for generating various graphs in networkx.
+
+"""
+
+from networkx.generators.atlas import *
+from networkx.generators.classic import *
+from networkx.generators.cographs import *
+from networkx.generators.community import *
+from networkx.generators.degree_seq import *
+from networkx.generators.directed import *
+from networkx.generators.duplication import *
+from networkx.generators.ego import *
+from networkx.generators.expanders import *
+from networkx.generators.geometric import *
+from networkx.generators.harary_graph import *
+from networkx.generators.internet_as_graphs import *
+from networkx.generators.intersection import *
+from networkx.generators.interval_graph import *
+from networkx.generators.joint_degree_seq import *
+from networkx.generators.lattice import *
+from networkx.generators.line import *
+from networkx.generators.mycielski import *
+from networkx.generators.nonisomorphic_trees import *
+from networkx.generators.random_clustered import *
+from networkx.generators.random_graphs import *
+from networkx.generators.small import *
+from networkx.generators.social import *
+from networkx.generators.spectral_graph_forge import *
+from networkx.generators.stochastic import *
+from networkx.generators.sudoku import *
+from networkx.generators.time_series import *
+from networkx.generators.trees import *
+from networkx.generators.triads import *
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e3938e3110072f329da96dff697d8fd98848d1e0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/atlas.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/atlas.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1cd41c95a9762f22b22fb459307331c248766eb3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/atlas.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/classic.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/classic.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e698972c76e7ab747ff70bb68b66968596b5b4a4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/classic.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/cographs.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/cographs.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9176f8a12daf1af721fceaf8aaaca65847ab5da4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/cographs.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/community.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/community.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..81f88c2ea2da4bb9fb139f22dbfa6d5d99a4aef0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/community.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/degree_seq.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/degree_seq.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4fa7fd69ec90c1a5a9a19ae17bbac1a63caee6d7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/degree_seq.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/directed.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/directed.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a7e3e02fc044f5821bdaad845362e873c14d4fb5
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/directed.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/duplication.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/duplication.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..58a53d222abf743c5e5ddc9885244a758d5c2018
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/duplication.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/ego.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/ego.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4d1c434f55fb4162a4f7c473ec260ba916e46771
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/ego.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/expanders.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/expanders.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..32fcf4882f3c71e23c4f1aa6f7c512a3af4199f0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/expanders.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/geometric.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/geometric.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..91b0a8df98529b99b4caadff44d8360b2084b993
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/geometric.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/harary_graph.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/harary_graph.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..af3ee8b41af479e094331a16f98da093ee4adaa2
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/harary_graph.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/internet_as_graphs.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/internet_as_graphs.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ab7205d3061b1258643146af93f5452bf50f7a94
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/internet_as_graphs.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/intersection.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/intersection.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b9d6e906e3ac66cddde4389c6d4f9e3c59892a84
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/intersection.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/interval_graph.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/interval_graph.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fa31c5ec1e137f8f913ed6009c51c74b86c0db0c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/interval_graph.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/joint_degree_seq.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/joint_degree_seq.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..21c8abdb142bfe0268854ad8be093f4c38b41be4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/joint_degree_seq.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/lattice.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/lattice.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1f19f0b988903478537cf76df90372c8ec150b34
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/lattice.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/line.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/line.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..96350d258664d8e18e844b8ffa6cfb23537d495f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/line.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/mycielski.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/mycielski.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6da34d8bbdaec5a79a76064c451a06c6ea0ca877
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/mycielski.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/nonisomorphic_trees.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/nonisomorphic_trees.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..910d02393452e8a7ea61ce80ae32658e8af1df0f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/nonisomorphic_trees.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/random_clustered.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/random_clustered.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9932a51e9048a5dbe471bb1d29bd0d6af495b8d5
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/random_clustered.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/random_graphs.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/random_graphs.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d42f95a24e01b19c4f269696f7cc064c075ef528
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/random_graphs.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/small.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/small.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..06b6372723c1b5a5768ac31f6a278c6b37502857
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/small.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/social.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/social.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d2812e88742b5e1d48e18d32fc48c5bef342c2ed
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/social.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/spectral_graph_forge.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/spectral_graph_forge.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..362e6f3b617e6bb02b69f9ddb1bbc0e6364108d2
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/spectral_graph_forge.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/stochastic.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/stochastic.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d6aac6f395195e84ace50c3936ebd0a636430ef4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/stochastic.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/sudoku.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/sudoku.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4998456aebe7a5cce53b9dacc4988eb989cff40a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/sudoku.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/time_series.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/time_series.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..436d6b110c90fb8286d61102793a30f78162b8f2
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/time_series.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/trees.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/trees.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e543b62333d7e6e9591c957776724c6f619e96c1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/trees.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/triads.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/triads.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7a48e5ba3a8f8dd11d830da581c0797c87d14968
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/__pycache__/triads.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/atlas.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/atlas.py
new file mode 100644
index 0000000000000000000000000000000000000000..000d478b89210fe65f4a9bfc1a02e35dded889f3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/atlas.py
@@ -0,0 +1,227 @@
+"""
+Generators for the small graph atlas.
+"""
+
+import gzip
+import importlib.resources
+from itertools import islice
+
+import networkx as nx
+
+__all__ = ["graph_atlas", "graph_atlas_g"]
+
+#: The total number of graphs in the atlas.
+#:
+#: The graphs are labeled starting from 0 and extending to (but not
+#: including) this number.
+NUM_GRAPHS = 1253
+
+#: The path to the data file containing the graph edge lists.
+#:
+#: This is the absolute path of the gzipped text file containing the
+#: edge list for each graph in the atlas. The file contains one entry
+#: per graph in the atlas, in sequential order, starting from graph
+#: number 0 and extending through graph number 1252 (see
+#: :data:`NUM_GRAPHS`). Each entry looks like
+#:
+#: .. sourcecode:: text
+#:
+#:    GRAPH 6
+#:    NODES 3
+#:    0 1
+#:    0 2
+#:
+#: where the first two lines are the graph's index in the atlas and the
+#: number of nodes in the graph, and the remaining lines are the edge
+#: list.
+#:
+#: This file was generated from a Python list of graphs via code like
+#: the following::
+#:
+#:     import gzip
+#:     from networkx.generators.atlas import graph_atlas_g
+#:     from networkx.readwrite.edgelist import write_edgelist
+#:
+#:     with gzip.open('atlas.dat.gz', 'wb') as f:
+#:         for i, G in enumerate(graph_atlas_g()):
+#:             f.write(bytes(f'GRAPH {i}\n', encoding='utf-8'))
+#:             f.write(bytes(f'NODES {len(G)}\n', encoding='utf-8'))
+#:             write_edgelist(G, f, data=False)
+#:
+
+# Path to the atlas file
+ATLAS_FILE = importlib.resources.files("networkx.generators") / "atlas.dat.gz"
+
+
+def _generate_graphs():
+    """Sequentially read the file containing the edge list data for the
+    graphs in the atlas and generate the graphs one at a time.
+
+    This function reads the file given in :data:`.ATLAS_FILE`.
+
+    """
+    with gzip.open(ATLAS_FILE, "rb") as f:
+        line = f.readline()
+        while line and line.startswith(b"GRAPH"):
+            # The first two lines of each entry tell us the index of the
+            # graph in the list and the number of nodes in the graph.
+            # They look like this:
+            #
+            #     GRAPH 3
+            #     NODES 2
+            #
+            graph_index = int(line[6:].rstrip())
+            line = f.readline()
+            num_nodes = int(line[6:].rstrip())
+            # The remaining lines contain the edge list, until the next
+            # GRAPH line (or until the end of the file).
+            edgelist = []
+            line = f.readline()
+            while line and not line.startswith(b"GRAPH"):
+                edgelist.append(line.rstrip())
+                line = f.readline()
+            G = nx.Graph()
+            G.name = f"G{graph_index}"
+            G.add_nodes_from(range(num_nodes))
+            G.add_edges_from(tuple(map(int, e.split())) for e in edgelist)
+            yield G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def graph_atlas(i):
+    """Returns graph number `i` from the Graph Atlas.
+
+    For more information, see :func:`.graph_atlas_g`.
+
+    Parameters
+    ----------
+    i : int
+        The index of the graph from the atlas to get. The graph at index
+        0 is assumed to be the null graph.
+
+    Returns
+    -------
+    list
+        A list of :class:`~networkx.Graph` objects, the one at index *i*
+        corresponding to the graph *i* in the Graph Atlas.
+
+    See also
+    --------
+    graph_atlas_g
+
+    Notes
+    -----
+    The time required by this function increases linearly with the
+    argument `i`, since it reads a large file sequentially in order to
+    generate the graph [1]_.
+
+    References
+    ----------
+    .. [1] Ronald C. Read and Robin J. Wilson, *An Atlas of Graphs*.
+           Oxford University Press, 1998.
+
+    """
+    if not (0 <= i < NUM_GRAPHS):
+        raise ValueError(f"index must be between 0 and {NUM_GRAPHS}")
+    return next(islice(_generate_graphs(), i, None))
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def graph_atlas_g():
+    """Returns the list of all graphs with up to seven nodes named in the
+    Graph Atlas.
+
+    The graphs are listed in increasing order by
+
+    1. number of nodes,
+    2. number of edges,
+    3. degree sequence (for example 111223 < 112222),
+    4. number of automorphisms,
+
+    in that order, with three exceptions as described in the *Notes*
+    section below. This causes the list to correspond with the index of
+    the graphs in the Graph Atlas [atlas]_, with the first graph,
+    ``G[0]``, being the null graph.
+
+    Returns
+    -------
+    list
+        A list of :class:`~networkx.Graph` objects, the one at index *i*
+        corresponding to the graph *i* in the Graph Atlas.
+
+    Examples
+    --------
+    >>> from pprint import pprint
+    >>> atlas = nx.graph_atlas_g()
+
+    There are 1253 graphs in the atlas
+
+    >>> len(atlas)
+    1253
+
+    The number of graphs with *n* nodes, where *n* ranges from 0 to 7:
+
+    >>> from collections import Counter
+    >>> num_nodes_per_graph = [len(G) for G in atlas]
+    >>> Counter(num_nodes_per_graph)
+    Counter({7: 1044, 6: 156, 5: 34, 4: 11, 3: 4, 2: 2, 0: 1, 1: 1})
+
+    Since the atlas is ordered by the number of nodes in the graph, all graphs
+    with *n* nodes can be obtained by slicing the atlas. For example, all
+    graphs with 5 nodes:
+
+    >>> G5_list = atlas[19:53]
+    >>> all(len(G) == 5 for G in G5_list)
+    True
+
+    Or all graphs with at least 3 nodes but fewer than 7 nodes:
+
+    >>> G3_6_list = atlas[4:209]
+
+    More generally, the indices that partition the atlas by the number of nodes
+    per graph:
+
+    >>> import itertools
+    >>> partition_indices = [0] + list(
+    ...     itertools.accumulate(Counter(num_nodes_per_graph).values())  # cumsum
+    ... )
+    >>> partition_indices
+    [0, 1, 2, 4, 8, 19, 53, 209, 1253]
+    >>> partition_mapping = dict(enumerate(itertools.pairwise(partition_indices)))
+    >>> pprint(partition_mapping)
+    {0: (0, 1),
+     1: (1, 2),
+     2: (2, 4),
+     3: (4, 8),
+     4: (8, 19),
+     5: (19, 53),
+     6: (53, 209),
+     7: (209, 1253)}
+
+    See also
+    --------
+    graph_atlas
+
+    Notes
+    -----
+    This function may be expensive in both time and space, since it
+    reads a large file sequentially in order to populate the list.
+
+    Although the NetworkX atlas functions match the order of graphs
+    given in the "Atlas of Graphs" book, there are (at least) three
+    errors in the ordering described in the book. The following three
+    pairs of nodes violate the lexicographically nondecreasing sorted
+    degree sequence rule:
+
+    - graphs 55 and 56 with degree sequences 001111 and 000112,
+    - graphs 1007 and 1008 with degree sequences 3333444 and 3333336,
+    - graphs 1012 and 1213 with degree sequences 1244555 and 1244456.
+
+    References
+    ----------
+    .. [atlas] Ronald C. Read and Robin J. Wilson,
+               *An Atlas of Graphs*.
+               Oxford University Press, 1998.
+
+    """
+    return list(_generate_graphs())
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/classic.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/classic.py
new file mode 100644
index 0000000000000000000000000000000000000000..c7522195b95679554d22c8627c47b721572f9175
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/classic.py
@@ -0,0 +1,1091 @@
+"""Generators for some classic graphs.
+
+The typical graph builder function is called as follows:
+
+>>> G = nx.complete_graph(100)
+
+returning the complete graph on n nodes labeled 0, .., 99
+as a simple graph. Except for `empty_graph`, all the functions
+in this module return a Graph class (i.e. a simple, undirected graph).
+
+"""
+
+import itertools
+import numbers
+
+import networkx as nx
+from networkx.classes import Graph
+from networkx.exception import NetworkXError
+from networkx.utils import nodes_or_number, pairwise
+
+__all__ = [
+    "balanced_tree",
+    "barbell_graph",
+    "binomial_tree",
+    "complete_graph",
+    "complete_multipartite_graph",
+    "circular_ladder_graph",
+    "circulant_graph",
+    "cycle_graph",
+    "dorogovtsev_goltsev_mendes_graph",
+    "empty_graph",
+    "full_rary_tree",
+    "kneser_graph",
+    "ladder_graph",
+    "lollipop_graph",
+    "null_graph",
+    "path_graph",
+    "star_graph",
+    "tadpole_graph",
+    "trivial_graph",
+    "turan_graph",
+    "wheel_graph",
+]
+
+
+# -------------------------------------------------------------------
+#   Some Classic Graphs
+# -------------------------------------------------------------------
+
+
+def _tree_edges(n, r):
+    if n == 0:
+        return
+    # helper function for trees
+    # yields edges in rooted tree at 0 with n nodes and branching ratio r
+    nodes = iter(range(n))
+    parents = [next(nodes)]  # stack of max length r
+    while parents:
+        source = parents.pop(0)
+        for i in range(r):
+            try:
+                target = next(nodes)
+                parents.append(target)
+                yield source, target
+            except StopIteration:
+                break
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def full_rary_tree(r, n, create_using=None):
+    """Creates a full r-ary tree of `n` nodes.
+
+    Sometimes called a k-ary, n-ary, or m-ary tree.
+    "... all non-leaf nodes have exactly r children and all levels
+    are full except for some rightmost position of the bottom level
+    (if a leaf at the bottom level is missing, then so are all of the
+    leaves to its right." [1]_
+
+    .. plot::
+
+        >>> nx.draw(nx.full_rary_tree(2, 10))
+
+    Parameters
+    ----------
+    r : int
+        branching factor of the tree
+    n : int
+        Number of nodes in the tree
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : networkx Graph
+        An r-ary tree with n nodes
+
+    References
+    ----------
+    .. [1] An introduction to data structures and algorithms,
+           James Andrew Storer,  Birkhauser Boston 2001, (page 225).
+    """
+    G = empty_graph(n, create_using)
+    G.add_edges_from(_tree_edges(n, r))
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def kneser_graph(n, k):
+    """Returns the Kneser Graph with parameters `n` and `k`.
+
+    The Kneser Graph has nodes that are k-tuples (subsets) of the integers
+    between 0 and ``n-1``. Nodes are adjacent if their corresponding sets are disjoint.
+
+    Parameters
+    ----------
+    n: int
+        Number of integers from which to make node subsets.
+        Subsets are drawn from ``set(range(n))``.
+    k: int
+        Size of the subsets.
+
+    Returns
+    -------
+    G : NetworkX Graph
+
+    Examples
+    --------
+    >>> G = nx.kneser_graph(5, 2)
+    >>> G.number_of_nodes()
+    10
+    >>> G.number_of_edges()
+    15
+    >>> nx.is_isomorphic(G, nx.petersen_graph())
+    True
+    """
+    if n <= 0:
+        raise NetworkXError("n should be greater than zero")
+    if k <= 0 or k > n:
+        raise NetworkXError("k should be greater than zero and smaller than n")
+
+    G = nx.Graph()
+    # Create all k-subsets of [0, 1, ..., n-1]
+    subsets = list(itertools.combinations(range(n), k))
+
+    if 2 * k > n:
+        G.add_nodes_from(subsets)
+
+    universe = set(range(n))
+    comb = itertools.combinations  # only to make it all fit on one line
+    G.add_edges_from((s, t) for s in subsets for t in comb(universe - set(s), k))
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def balanced_tree(r, h, create_using=None):
+    """Returns the perfectly balanced `r`-ary tree of height `h`.
+
+    .. plot::
+
+        >>> nx.draw(nx.balanced_tree(2, 3))
+
+    Parameters
+    ----------
+    r : int
+        Branching factor of the tree; each node will have `r`
+        children.
+
+    h : int
+        Height of the tree.
+
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : NetworkX graph
+        A balanced `r`-ary tree of height `h`.
+
+    Notes
+    -----
+    This is the rooted tree where all leaves are at distance `h` from
+    the root. The root has degree `r` and all other internal nodes
+    have degree `r + 1`.
+
+    Node labels are integers, starting from zero.
+
+    A balanced tree is also known as a *complete r-ary tree*.
+
+    """
+    # The number of nodes in the balanced tree is `1 + r + ... + r^h`,
+    # which is computed by using the closed-form formula for a geometric
+    # sum with ratio `r`. In the special case that `r` is 1, the number
+    # of nodes is simply `h + 1` (since the tree is actually a path
+    # graph).
+    if r == 1:
+        n = h + 1
+    else:
+        # This must be an integer if both `r` and `h` are integers. If
+        # they are not, we force integer division anyway.
+        n = (1 - r ** (h + 1)) // (1 - r)
+    return full_rary_tree(r, n, create_using=create_using)
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def barbell_graph(m1, m2, create_using=None):
+    """Returns the Barbell Graph: two complete graphs connected by a path.
+
+    .. plot::
+
+        >>> nx.draw(nx.barbell_graph(4, 2))
+
+    Parameters
+    ----------
+    m1 : int
+        Size of the left and right barbells, must be greater than 2.
+
+    m2 : int
+        Length of the path connecting the barbells.
+
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+       Only undirected Graphs are supported.
+
+    Returns
+    -------
+    G : NetworkX graph
+        A barbell graph.
+
+    Notes
+    -----
+
+
+    Two identical complete graphs $K_{m1}$ form the left and right bells,
+    and are connected by a path $P_{m2}$.
+
+    The `2*m1+m2`  nodes are numbered
+        `0, ..., m1-1` for the left barbell,
+        `m1, ..., m1+m2-1` for the path,
+        and `m1+m2, ..., 2*m1+m2-1` for the right barbell.
+
+    The 3 subgraphs are joined via the edges `(m1-1, m1)` and
+    `(m1+m2-1, m1+m2)`. If `m2=0`, this is merely two complete
+    graphs joined together.
+
+    This graph is an extremal example in David Aldous
+    and Jim Fill's e-text on Random Walks on Graphs.
+
+    """
+    if m1 < 2:
+        raise NetworkXError("Invalid graph description, m1 should be >=2")
+    if m2 < 0:
+        raise NetworkXError("Invalid graph description, m2 should be >=0")
+
+    # left barbell
+    G = complete_graph(m1, create_using)
+    if G.is_directed():
+        raise NetworkXError("Directed Graph not supported")
+
+    # connecting path
+    G.add_nodes_from(range(m1, m1 + m2 - 1))
+    if m2 > 1:
+        G.add_edges_from(pairwise(range(m1, m1 + m2)))
+
+    # right barbell
+    G.add_edges_from(
+        (u, v) for u in range(m1 + m2, 2 * m1 + m2) for v in range(u + 1, 2 * m1 + m2)
+    )
+
+    # connect it up
+    G.add_edge(m1 - 1, m1)
+    if m2 > 0:
+        G.add_edge(m1 + m2 - 1, m1 + m2)
+
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def binomial_tree(n, create_using=None):
+    """Returns the Binomial Tree of order n.
+
+    The binomial tree of order 0 consists of a single node. A binomial tree of order k
+    is defined recursively by linking two binomial trees of order k-1: the root of one is
+    the leftmost child of the root of the other.
+
+    .. plot::
+
+        >>> nx.draw(nx.binomial_tree(3))
+
+    Parameters
+    ----------
+    n : int
+        Order of the binomial tree.
+
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : NetworkX graph
+        A binomial tree of $2^n$ nodes and $2^n - 1$ edges.
+
+    """
+    G = nx.empty_graph(1, create_using)
+
+    N = 1
+    for i in range(n):
+        # Use G.edges() to ensure 2-tuples. G.edges is 3-tuple for MultiGraph
+        edges = [(u + N, v + N) for (u, v) in G.edges()]
+        G.add_edges_from(edges)
+        G.add_edge(0, N)
+        N *= 2
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+@nodes_or_number(0)
+def complete_graph(n, create_using=None):
+    """Return the complete graph `K_n` with n nodes.
+
+    A complete graph on `n` nodes means that all pairs
+    of distinct nodes have an edge connecting them.
+
+    .. plot::
+
+        >>> nx.draw(nx.complete_graph(5))
+
+    Parameters
+    ----------
+    n : int or iterable container of nodes
+        If n is an integer, nodes are from range(n).
+        If n is a container of nodes, those nodes appear in the graph.
+        Warning: n is not checked for duplicates and if present the
+        resulting graph may not be as desired. Make sure you have no duplicates.
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Examples
+    --------
+    >>> G = nx.complete_graph(9)
+    >>> len(G)
+    9
+    >>> G.size()
+    36
+    >>> G = nx.complete_graph(range(11, 14))
+    >>> list(G.nodes())
+    [11, 12, 13]
+    >>> G = nx.complete_graph(4, nx.DiGraph())
+    >>> G.is_directed()
+    True
+
+    """
+    _, nodes = n
+    G = empty_graph(nodes, create_using)
+    if len(nodes) > 1:
+        if G.is_directed():
+            edges = itertools.permutations(nodes, 2)
+        else:
+            edges = itertools.combinations(nodes, 2)
+        G.add_edges_from(edges)
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def circular_ladder_graph(n, create_using=None):
+    """Returns the circular ladder graph $CL_n$ of length n.
+
+    $CL_n$ consists of two concentric n-cycles in which
+    each of the n pairs of concentric nodes are joined by an edge.
+
+    Node labels are the integers 0 to n-1
+
+    .. plot::
+
+        >>> nx.draw(nx.circular_ladder_graph(5))
+
+    """
+    G = ladder_graph(n, create_using)
+    G.add_edge(0, n - 1)
+    G.add_edge(n, 2 * n - 1)
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def circulant_graph(n, offsets, create_using=None):
+    r"""Returns the circulant graph $Ci_n(x_1, x_2, ..., x_m)$ with $n$ nodes.
+
+    The circulant graph $Ci_n(x_1, ..., x_m)$ consists of $n$ nodes $0, ..., n-1$
+    such that node $i$ is connected to nodes $(i + x) \mod n$ and $(i - x) \mod n$
+    for all $x$ in $x_1, ..., x_m$. Thus $Ci_n(1)$ is a cycle graph.
+
+    .. plot::
+
+        >>> nx.draw(nx.circulant_graph(10, [1]))
+
+    Parameters
+    ----------
+    n : integer
+        The number of nodes in the graph.
+    offsets : list of integers
+        A list of node offsets, $x_1$ up to $x_m$, as described above.
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    NetworkX Graph of type create_using
+
+    Examples
+    --------
+    Many well-known graph families are subfamilies of the circulant graphs;
+    for example, to create the cycle graph on n points, we connect every
+    node to nodes on either side (with offset plus or minus one). For n = 10,
+
+    >>> G = nx.circulant_graph(10, [1])
+    >>> edges = [
+    ...     (0, 9),
+    ...     (0, 1),
+    ...     (1, 2),
+    ...     (2, 3),
+    ...     (3, 4),
+    ...     (4, 5),
+    ...     (5, 6),
+    ...     (6, 7),
+    ...     (7, 8),
+    ...     (8, 9),
+    ... ]
+    >>> sorted(edges) == sorted(G.edges())
+    True
+
+    Similarly, we can create the complete graph
+    on 5 points with the set of offsets [1, 2]:
+
+    >>> G = nx.circulant_graph(5, [1, 2])
+    >>> edges = [
+    ...     (0, 1),
+    ...     (0, 2),
+    ...     (0, 3),
+    ...     (0, 4),
+    ...     (1, 2),
+    ...     (1, 3),
+    ...     (1, 4),
+    ...     (2, 3),
+    ...     (2, 4),
+    ...     (3, 4),
+    ... ]
+    >>> sorted(edges) == sorted(G.edges())
+    True
+
+    """
+    G = empty_graph(n, create_using)
+    G.add_edges_from((i, (i - j) % n) for i in range(n) for j in offsets)
+    G.add_edges_from((i, (i + j) % n) for i in range(n) for j in offsets)
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+@nodes_or_number(0)
+def cycle_graph(n, create_using=None):
+    """Returns the cycle graph $C_n$ of cyclically connected nodes.
+
+    $C_n$ is a path with its two end-nodes connected.
+
+    .. plot::
+
+        >>> nx.draw(nx.cycle_graph(5))
+
+    Parameters
+    ----------
+    n : int or iterable container of nodes
+        If n is an integer, nodes are from `range(n)`.
+        If n is a container of nodes, those nodes appear in the graph.
+        Warning: n is not checked for duplicates and if present the
+        resulting graph may not be as desired. Make sure you have no duplicates.
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Notes
+    -----
+    If create_using is directed, the direction is in increasing order.
+
+    """
+    _, nodes = n
+    G = empty_graph(nodes, create_using)
+    G.add_edges_from(pairwise(nodes, cyclic=True))
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def dorogovtsev_goltsev_mendes_graph(n, create_using=None):
+    """Returns the hierarchically constructed Dorogovtsev--Goltsev--Mendes graph.
+
+    The Dorogovtsev--Goltsev--Mendes [1]_ procedure deterministically produces a
+    scale-free graph with ``3/2 * (3**(n-1) + 1)`` nodes
+    and ``3**n`` edges for a given `n`.
+
+    Note that `n` denotes the number of times the state transition is applied,
+    starting from the base graph with ``n = 0`` (no transitions), as in [2]_.
+    This is different from the parameter ``t = n - 1`` in [1]_.
+
+    .. plot::
+
+        >>> nx.draw(nx.dorogovtsev_goltsev_mendes_graph(3))
+
+    Parameters
+    ----------
+    n : integer
+        The generation number.
+
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+        Graph type to create. Directed graphs and multigraphs are not supported.
+
+    Returns
+    -------
+    G : NetworkX `Graph`
+
+    Raises
+    ------
+    NetworkXError
+        If `n` is less than zero.
+
+        If `create_using` is a directed graph or multigraph.
+
+    Examples
+    --------
+    >>> G = nx.dorogovtsev_goltsev_mendes_graph(3)
+    >>> G.number_of_nodes()
+    15
+    >>> G.number_of_edges()
+    27
+    >>> nx.is_planar(G)
+    True
+
+    References
+    ----------
+    .. [1] S. N. Dorogovtsev, A. V. Goltsev and J. F. F. Mendes,
+        "Pseudofractal scale-free web", Physical Review E 65, 066122, 2002.
+        https://arxiv.org/pdf/cond-mat/0112143.pdf
+    .. [2] Weisstein, Eric W. "Dorogovtsev--Goltsev--Mendes Graph".
+        From MathWorld--A Wolfram Web Resource.
+        https://mathworld.wolfram.com/Dorogovtsev-Goltsev-MendesGraph.html
+    """
+    if n < 0:
+        raise NetworkXError("n must be greater than or equal to 0")
+
+    G = empty_graph(0, create_using)
+    if G.is_directed():
+        raise NetworkXError("directed graph not supported")
+    if G.is_multigraph():
+        raise NetworkXError("multigraph not supported")
+
+    G.add_edge(0, 1)
+    new_node = 2  # next node to be added
+    for _ in range(n):  # iterate over number of generations.
+        new_edges = []
+        for u, v in G.edges():
+            new_edges.append((u, new_node))
+            new_edges.append((v, new_node))
+            new_node += 1
+
+        G.add_edges_from(new_edges)
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+@nodes_or_number(0)
+def empty_graph(n=0, create_using=None, default=Graph):
+    """Returns the empty graph with n nodes and zero edges.
+
+    .. plot::
+
+        >>> nx.draw(nx.empty_graph(5))
+
+    Parameters
+    ----------
+    n : int or iterable container of nodes (default = 0)
+        If n is an integer, nodes are from `range(n)`.
+        If n is a container of nodes, those nodes appear in the graph.
+    create_using : Graph Instance, Constructor or None
+        Indicator of type of graph to return.
+        If a Graph-type instance, then clear and use it.
+        If None, use the `default` constructor.
+        If a constructor, call it to create an empty graph.
+    default : Graph constructor (optional, default = nx.Graph)
+        The constructor to use if create_using is None.
+        If None, then nx.Graph is used.
+        This is used when passing an unknown `create_using` value
+        through your home-grown function to `empty_graph` and
+        you want a default constructor other than nx.Graph.
+
+    Examples
+    --------
+    >>> G = nx.empty_graph(10)
+    >>> G.number_of_nodes()
+    10
+    >>> G.number_of_edges()
+    0
+    >>> G = nx.empty_graph("ABC")
+    >>> G.number_of_nodes()
+    3
+    >>> sorted(G)
+    ['A', 'B', 'C']
+
+    Notes
+    -----
+    The variable create_using should be a Graph Constructor or a
+    "graph"-like object. Constructors, e.g. `nx.Graph` or `nx.MultiGraph`
+    will be used to create the returned graph. "graph"-like objects
+    will be cleared (nodes and edges will be removed) and refitted as
+    an empty "graph" with nodes specified in n. This capability
+    is useful for specifying the class-nature of the resulting empty
+    "graph" (i.e. Graph, DiGraph, MyWeirdGraphClass, etc.).
+
+    The variable create_using has three main uses:
+    Firstly, the variable create_using can be used to create an
+    empty digraph, multigraph, etc.  For example,
+
+    >>> n = 10
+    >>> G = nx.empty_graph(n, create_using=nx.DiGraph)
+
+    will create an empty digraph on n nodes.
+
+    Secondly, one can pass an existing graph (digraph, multigraph,
+    etc.) via create_using. For example, if G is an existing graph
+    (resp. digraph, multigraph, etc.), then empty_graph(n, create_using=G)
+    will empty G (i.e. delete all nodes and edges using G.clear())
+    and then add n nodes and zero edges, and return the modified graph.
+
+    Thirdly, when constructing your home-grown graph creation function
+    you can use empty_graph to construct the graph by passing a user
+    defined create_using to empty_graph. In this case, if you want the
+    default constructor to be other than nx.Graph, specify `default`.
+
+    >>> def mygraph(n, create_using=None):
+    ...     G = nx.empty_graph(n, create_using, nx.MultiGraph)
+    ...     G.add_edges_from([(0, 1), (0, 1)])
+    ...     return G
+    >>> G = mygraph(3)
+    >>> G.is_multigraph()
+    True
+    >>> G = mygraph(3, nx.Graph)
+    >>> G.is_multigraph()
+    False
+
+    See also create_empty_copy(G).
+
+    """
+    if create_using is None:
+        G = default()
+    elif isinstance(create_using, type):
+        G = create_using()
+    elif not hasattr(create_using, "adj"):
+        raise TypeError("create_using is not a valid NetworkX graph type or instance")
+    else:
+        # create_using is a NetworkX style Graph
+        create_using.clear()
+        G = create_using
+
+    _, nodes = n
+    G.add_nodes_from(nodes)
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def ladder_graph(n, create_using=None):
+    """Returns the Ladder graph of length n.
+
+    This is two paths of n nodes, with
+    each pair connected by a single edge.
+
+    Node labels are the integers 0 to 2*n - 1.
+
+    .. plot::
+
+        >>> nx.draw(nx.ladder_graph(5))
+
+    """
+    G = empty_graph(2 * n, create_using)
+    if G.is_directed():
+        raise NetworkXError("Directed Graph not supported")
+    G.add_edges_from(pairwise(range(n)))
+    G.add_edges_from(pairwise(range(n, 2 * n)))
+    G.add_edges_from((v, v + n) for v in range(n))
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+@nodes_or_number([0, 1])
+def lollipop_graph(m, n, create_using=None):
+    """Returns the Lollipop Graph; ``K_m`` connected to ``P_n``.
+
+    This is the Barbell Graph without the right barbell.
+
+    .. plot::
+
+        >>> nx.draw(nx.lollipop_graph(3, 4))
+
+    Parameters
+    ----------
+    m, n : int or iterable container of nodes
+        If an integer, nodes are from ``range(m)`` and ``range(m, m+n)``.
+        If a container of nodes, those nodes appear in the graph.
+        Warning: `m` and `n` are not checked for duplicates and if present the
+        resulting graph may not be as desired. Make sure you have no duplicates.
+
+        The nodes for `m` appear in the complete graph $K_m$ and the nodes
+        for `n` appear in the path $P_n$
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    Networkx graph
+       A complete graph with `m` nodes connected to a path of length `n`.
+
+    Notes
+    -----
+    The 2 subgraphs are joined via an edge ``(m-1, m)``.
+    If ``n=0``, this is merely a complete graph.
+
+    (This graph is an extremal example in David Aldous and Jim
+    Fill's etext on Random Walks on Graphs.)
+
+    """
+    m, m_nodes = m
+    M = len(m_nodes)
+    if M < 2:
+        raise NetworkXError("Invalid description: m should indicate at least 2 nodes")
+
+    n, n_nodes = n
+    if isinstance(m, numbers.Integral) and isinstance(n, numbers.Integral):
+        n_nodes = list(range(M, M + n))
+    N = len(n_nodes)
+
+    # the ball
+    G = complete_graph(m_nodes, create_using)
+    if G.is_directed():
+        raise NetworkXError("Directed Graph not supported")
+
+    # the stick
+    G.add_nodes_from(n_nodes)
+    if N > 1:
+        G.add_edges_from(pairwise(n_nodes))
+
+    if len(G) != M + N:
+        raise NetworkXError("Nodes must be distinct in containers m and n")
+
+    # connect ball to stick
+    if M > 0 and N > 0:
+        G.add_edge(m_nodes[-1], n_nodes[0])
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def null_graph(create_using=None):
+    """Returns the Null graph with no nodes or edges.
+
+    See empty_graph for the use of create_using.
+
+    """
+    G = empty_graph(0, create_using)
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+@nodes_or_number(0)
+def path_graph(n, create_using=None):
+    """Returns the Path graph `P_n` of linearly connected nodes.
+
+    .. plot::
+
+        >>> nx.draw(nx.path_graph(5))
+
+    Parameters
+    ----------
+    n : int or iterable
+        If an integer, nodes are 0 to n - 1.
+        If an iterable of nodes, in the order they appear in the path.
+        Warning: n is not checked for duplicates and if present the
+        resulting graph may not be as desired. Make sure you have no duplicates.
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    """
+    _, nodes = n
+    G = empty_graph(nodes, create_using)
+    G.add_edges_from(pairwise(nodes))
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+@nodes_or_number(0)
+def star_graph(n, create_using=None):
+    """Return a star graph.
+
+    The star graph consists of one center node connected to `n` outer nodes.
+
+    .. plot::
+
+        >>> nx.draw(nx.star_graph(6))
+
+    Parameters
+    ----------
+    n : int or iterable
+        If an integer, node labels are ``0`` to `n`, with center ``0``.
+        If an iterable of nodes, the center is the first.
+        Warning: `n` is not checked for duplicates and if present, the
+        resulting graph may not be as desired. Make sure you have no duplicates.
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Examples
+    --------
+    A star graph with 3 spokes can be generated with
+
+    >>> G = nx.star_graph(3)
+    >>> sorted(G.edges)
+    [(0, 1), (0, 2), (0, 3)]
+
+    For directed graphs, the convention is to have edges pointing from the hub
+    to the spokes:
+
+    >>> DG1 = nx.star_graph(3, create_using=nx.DiGraph)
+    >>> sorted(DG1.edges)
+    [(0, 1), (0, 2), (0, 3)]
+
+    Other possible definitions have edges pointing from the spokes to the hub:
+
+    >>> DG2 = nx.star_graph(3, create_using=nx.DiGraph).reverse()
+    >>> sorted(DG2.edges)
+    [(1, 0), (2, 0), (3, 0)]
+
+    or have bidirectional edges:
+
+    >>> DG3 = nx.star_graph(3).to_directed()
+    >>> sorted(DG3.edges)
+    [(0, 1), (0, 2), (0, 3), (1, 0), (2, 0), (3, 0)]
+
+    Notes
+    -----
+    The graph has ``n + 1`` nodes for integer `n`.
+    So ``star_graph(3)`` is the same as ``star_graph(range(4))``.
+    """
+    n, nodes = n
+    if isinstance(n, numbers.Integral):
+        nodes.append(int(n))  # There should be n + 1 nodes.
+    G = empty_graph(nodes, create_using)
+
+    if len(nodes) > 1:
+        hub, *spokes = nodes
+        G.add_edges_from((hub, node) for node in spokes)
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+@nodes_or_number([0, 1])
+def tadpole_graph(m, n, create_using=None):
+    """Returns the (m,n)-tadpole graph; ``C_m`` connected to ``P_n``.
+
+    This graph on m+n nodes connects a cycle of size `m` to a path of length `n`.
+    It looks like a tadpole. It is also called a kite graph or a dragon graph.
+
+    .. plot::
+
+        >>> nx.draw(nx.tadpole_graph(3, 5))
+
+    Parameters
+    ----------
+    m, n : int or iterable container of nodes
+        If an integer, nodes are from ``range(m)`` and ``range(m,m+n)``.
+        If a container of nodes, those nodes appear in the graph.
+        Warning: `m` and `n` are not checked for duplicates and if present the
+        resulting graph may not be as desired.
+
+        The nodes for `m` appear in the cycle graph $C_m$ and the nodes
+        for `n` appear in the path $P_n$.
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    Networkx graph
+       A cycle of size `m` connected to a path of length `n`.
+
+    Raises
+    ------
+    NetworkXError
+        If ``m < 2``. The tadpole graph is undefined for ``m<2``.
+
+    Notes
+    -----
+    The 2 subgraphs are joined via an edge ``(m-1, m)``.
+    If ``n=0``, this is a cycle graph.
+    `m` and/or `n` can be a container of nodes instead of an integer.
+
+    """
+    m, m_nodes = m
+    M = len(m_nodes)
+    if M < 2:
+        raise NetworkXError("Invalid description: m should indicate at least 2 nodes")
+
+    n, n_nodes = n
+    if isinstance(m, numbers.Integral) and isinstance(n, numbers.Integral):
+        n_nodes = list(range(M, M + n))
+
+    # the circle
+    G = cycle_graph(m_nodes, create_using)
+    if G.is_directed():
+        raise NetworkXError("Directed Graph not supported")
+
+    # the stick
+    nx.add_path(G, [m_nodes[-1]] + list(n_nodes))
+
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def trivial_graph(create_using=None):
+    """Return the Trivial graph with one node (with label 0) and no edges.
+
+    .. plot::
+
+        >>> nx.draw(nx.trivial_graph(), with_labels=True)
+
+    """
+    G = empty_graph(1, create_using)
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def turan_graph(n, r):
+    r"""Return the Turan Graph
+
+    The Turan Graph is a complete multipartite graph on $n$ nodes
+    with $r$ disjoint subsets. That is, edges connect each node to
+    every node not in its subset.
+
+    Given $n$ and $r$, we create a complete multipartite graph with
+    $r-(n \mod r)$ partitions of size $n/r$, rounded down, and
+    $n \mod r$ partitions of size $n/r+1$, rounded down.
+
+    .. plot::
+
+        >>> nx.draw(nx.turan_graph(6, 2))
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes.
+    r : int
+        The number of partitions.
+        Must be less than or equal to n.
+
+    Notes
+    -----
+    Must satisfy $1 <= r <= n$.
+    The graph has $(r-1)(n^2)/(2r)$ edges, rounded down.
+    """
+
+    if not 1 <= r <= n:
+        raise NetworkXError("Must satisfy 1 <= r <= n")
+
+    partitions = [n // r] * (r - (n % r)) + [n // r + 1] * (n % r)
+    G = complete_multipartite_graph(*partitions)
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+@nodes_or_number(0)
+def wheel_graph(n, create_using=None):
+    """Return the wheel graph
+
+    The wheel graph consists of a hub node connected to a cycle of (n-1) nodes.
+
+    .. plot::
+
+        >>> nx.draw(nx.wheel_graph(5))
+
+    Parameters
+    ----------
+    n : int or iterable
+        If an integer, node labels are 0 to n with center 0.
+        If an iterable of nodes, the center is the first.
+        Warning: n is not checked for duplicates and if present the
+        resulting graph may not be as desired. Make sure you have no duplicates.
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Node labels are the integers 0 to n - 1.
+    """
+    _, nodes = n
+    G = empty_graph(nodes, create_using)
+    if G.is_directed():
+        raise NetworkXError("Directed Graph not supported")
+
+    if len(nodes) > 1:
+        hub, *rim = nodes
+        G.add_edges_from((hub, node) for node in rim)
+        if len(rim) > 1:
+            G.add_edges_from(pairwise(rim, cyclic=True))
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def complete_multipartite_graph(*subset_sizes):
+    """Returns the complete multipartite graph with the specified subset sizes.
+
+    .. plot::
+
+        >>> nx.draw(nx.complete_multipartite_graph(1, 2, 3))
+
+    Parameters
+    ----------
+    subset_sizes : tuple of integers or tuple of node iterables
+       The arguments can either all be integer number of nodes or they
+       can all be iterables of nodes. If integers, they represent the
+       number of nodes in each subset of the multipartite graph.
+       If iterables, each is used to create the nodes for that subset.
+       The length of subset_sizes is the number of subsets.
+
+    Returns
+    -------
+    G : NetworkX Graph
+       Returns the complete multipartite graph with the specified subsets.
+
+       For each node, the node attribute 'subset' is an integer
+       indicating which subset contains the node.
+
+    Examples
+    --------
+    Creating a complete tripartite graph, with subsets of one, two, and three
+    nodes, respectively.
+
+    >>> G = nx.complete_multipartite_graph(1, 2, 3)
+    >>> [G.nodes[u]["subset"] for u in G]
+    [0, 1, 1, 2, 2, 2]
+    >>> list(G.edges(0))
+    [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5)]
+    >>> list(G.edges(2))
+    [(2, 0), (2, 3), (2, 4), (2, 5)]
+    >>> list(G.edges(4))
+    [(4, 0), (4, 1), (4, 2)]
+
+    >>> G = nx.complete_multipartite_graph("a", "bc", "def")
+    >>> [G.nodes[u]["subset"] for u in sorted(G)]
+    [0, 1, 1, 2, 2, 2]
+
+    Notes
+    -----
+    This function generalizes several other graph builder functions.
+
+    - If no subset sizes are given, this returns the null graph.
+    - If a single subset size `n` is given, this returns the empty graph on
+      `n` nodes.
+    - If two subset sizes `m` and `n` are given, this returns the complete
+      bipartite graph on `m + n` nodes.
+    - If subset sizes `1` and `n` are given, this returns the star graph on
+      `n + 1` nodes.
+
+    See also
+    --------
+    complete_bipartite_graph
+    """
+    # The complete multipartite graph is an undirected simple graph.
+    G = Graph()
+
+    if len(subset_sizes) == 0:
+        return G
+
+    # set up subsets of nodes
+    try:
+        extents = pairwise(itertools.accumulate((0,) + subset_sizes))
+        subsets = [range(start, end) for start, end in extents]
+    except TypeError:
+        subsets = subset_sizes
+    else:
+        if any(size < 0 for size in subset_sizes):
+            raise NetworkXError(f"Negative number of nodes not valid: {subset_sizes}")
+
+    # add nodes with subset attribute
+    # while checking that ints are not mixed with iterables
+    try:
+        for i, subset in enumerate(subsets):
+            G.add_nodes_from(subset, subset=i)
+    except TypeError as err:
+        raise NetworkXError("Arguments must be all ints or all iterables") from err
+
+    # Across subsets, all nodes should be adjacent.
+    # We can use itertools.combinations() because undirected.
+    for subset1, subset2 in itertools.combinations(subsets, 2):
+        G.add_edges_from(itertools.product(subset1, subset2))
+    return G
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/cographs.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/cographs.py
new file mode 100644
index 0000000000000000000000000000000000000000..6635b32f691696c1b6f309ad0da81c3cbc43bed9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/cographs.py
@@ -0,0 +1,68 @@
+r"""Generators for cographs
+
+A cograph is a graph containing no path on four vertices.
+Cographs or $P_4$-free graphs can be obtained from a single vertex
+by disjoint union and complementation operations.
+
+References
+----------
+.. [0] D.G. Corneil, H. Lerchs, L.Stewart Burlingham,
+    "Complement reducible graphs",
+    Discrete Applied Mathematics, Volume 3, Issue 3, 1981, Pages 163-174,
+    ISSN 0166-218X.
+"""
+
+import networkx as nx
+from networkx.utils import py_random_state
+
+__all__ = ["random_cograph"]
+
+
+@py_random_state(1)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def random_cograph(n, seed=None):
+    r"""Returns a random cograph with $2 ^ n$ nodes.
+
+    A cograph is a graph containing no path on four vertices.
+    Cographs or $P_4$-free graphs can be obtained from a single vertex
+    by disjoint union and complementation operations.
+
+    This generator starts off from a single vertex and performs disjoint
+    union and full join operations on itself.
+    The decision on which operation will take place is random.
+
+    Parameters
+    ----------
+    n : int
+        The order of the cograph.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    G : A random graph containing no path on four vertices.
+
+    See Also
+    --------
+    full_join
+    union
+
+    References
+    ----------
+    .. [1] D.G. Corneil, H. Lerchs, L.Stewart Burlingham,
+       "Complement reducible graphs",
+       Discrete Applied Mathematics, Volume 3, Issue 3, 1981, Pages 163-174,
+       ISSN 0166-218X.
+    """
+    R = nx.empty_graph(1)
+
+    for i in range(n):
+        RR = nx.relabel_nodes(R.copy(), lambda x: x + len(R))
+
+        if seed.randint(0, 1) == 0:
+            R = nx.full_join(R, RR)
+        else:
+            R = nx.disjoint_union(R, RR)
+
+    return R
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/community.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/community.py
new file mode 100644
index 0000000000000000000000000000000000000000..a7f2294c5cf9137dc1fab2a50d7ffcd6c59b6dec
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/community.py
@@ -0,0 +1,1070 @@
+"""Generators for classes of graphs used in studying social networks."""
+
+import itertools
+import math
+
+import networkx as nx
+from networkx.utils import py_random_state
+
+__all__ = [
+    "caveman_graph",
+    "connected_caveman_graph",
+    "relaxed_caveman_graph",
+    "random_partition_graph",
+    "planted_partition_graph",
+    "gaussian_random_partition_graph",
+    "ring_of_cliques",
+    "windmill_graph",
+    "stochastic_block_model",
+    "LFR_benchmark_graph",
+]
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def caveman_graph(l, k):
+    """Returns a caveman graph of `l` cliques of size `k`.
+
+    Parameters
+    ----------
+    l : int
+      Number of cliques
+    k : int
+      Size of cliques
+
+    Returns
+    -------
+    G : NetworkX Graph
+      caveman graph
+
+    Notes
+    -----
+    This returns an undirected graph, it can be converted to a directed
+    graph using :func:`nx.to_directed`, or a multigraph using
+    ``nx.MultiGraph(nx.caveman_graph(l, k))``. Only the undirected version is
+    described in [1]_ and it is unclear which of the directed
+    generalizations is most useful.
+
+    Examples
+    --------
+    >>> G = nx.caveman_graph(3, 3)
+
+    See also
+    --------
+
+    connected_caveman_graph
+
+    References
+    ----------
+    .. [1] Watts, D. J. 'Networks, Dynamics, and the Small-World Phenomenon.'
+       Amer. J. Soc. 105, 493-527, 1999.
+    """
+    # l disjoint cliques of size k
+    G = nx.empty_graph(l * k)
+    if k > 1:
+        for start in range(0, l * k, k):
+            edges = itertools.combinations(range(start, start + k), 2)
+            G.add_edges_from(edges)
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def connected_caveman_graph(l, k):
+    """Returns a connected caveman graph of `l` cliques of size `k`.
+
+    The connected caveman graph is formed by creating `n` cliques of size
+    `k`, then a single edge in each clique is rewired to a node in an
+    adjacent clique.
+
+    Parameters
+    ----------
+    l : int
+      number of cliques
+    k : int
+      size of cliques (k at least 2 or NetworkXError is raised)
+
+    Returns
+    -------
+    G : NetworkX Graph
+      connected caveman graph
+
+    Raises
+    ------
+    NetworkXError
+        If the size of cliques `k` is smaller than 2.
+
+    Notes
+    -----
+    This returns an undirected graph, it can be converted to a directed
+    graph using :func:`nx.to_directed`, or a multigraph using
+    ``nx.MultiGraph(nx.caveman_graph(l, k))``. Only the undirected version is
+    described in [1]_ and it is unclear which of the directed
+    generalizations is most useful.
+
+    Examples
+    --------
+    >>> G = nx.connected_caveman_graph(3, 3)
+
+    References
+    ----------
+    .. [1] Watts, D. J. 'Networks, Dynamics, and the Small-World Phenomenon.'
+       Amer. J. Soc. 105, 493-527, 1999.
+    """
+    if k < 2:
+        raise nx.NetworkXError(
+            "The size of cliques in a connected caveman graph must be at least 2."
+        )
+
+    G = nx.caveman_graph(l, k)
+    for start in range(0, l * k, k):
+        G.remove_edge(start, start + 1)
+        G.add_edge(start, (start - 1) % (l * k))
+    return G
+
+
+@py_random_state(3)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def relaxed_caveman_graph(l, k, p, seed=None):
+    """Returns a relaxed caveman graph.
+
+    A relaxed caveman graph starts with `l` cliques of size `k`.  Edges are
+    then randomly rewired with probability `p` to link different cliques.
+
+    Parameters
+    ----------
+    l : int
+      Number of groups
+    k : int
+      Size of cliques
+    p : float
+      Probability of rewiring each edge.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    G : NetworkX Graph
+      Relaxed Caveman Graph
+
+    Raises
+    ------
+    NetworkXError
+     If p is not in [0,1]
+
+    Examples
+    --------
+    >>> G = nx.relaxed_caveman_graph(2, 3, 0.1, seed=42)
+
+    References
+    ----------
+    .. [1] Santo Fortunato, Community Detection in Graphs,
+       Physics Reports Volume 486, Issues 3-5, February 2010, Pages 75-174.
+       https://arxiv.org/abs/0906.0612
+    """
+    G = nx.caveman_graph(l, k)
+    nodes = list(G)
+    for u, v in G.edges():
+        if seed.random() < p:  # rewire the edge
+            x = seed.choice(nodes)
+            if G.has_edge(u, x):
+                continue
+            G.remove_edge(u, v)
+            G.add_edge(u, x)
+    return G
+
+
+@py_random_state(3)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def random_partition_graph(sizes, p_in, p_out, seed=None, directed=False):
+    """Returns the random partition graph with a partition of sizes.
+
+    A partition graph is a graph of communities with sizes defined by
+    s in sizes. Nodes in the same group are connected with probability
+    p_in and nodes of different groups are connected with probability
+    p_out.
+
+    Parameters
+    ----------
+    sizes : list of ints
+      Sizes of groups
+    p_in : float
+      probability of edges with in groups
+    p_out : float
+      probability of edges between groups
+    directed : boolean optional, default=False
+      Whether to create a directed graph
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    G : NetworkX Graph or DiGraph
+      random partition graph of size sum(gs)
+
+    Raises
+    ------
+    NetworkXError
+      If p_in or p_out is not in [0,1]
+
+    Examples
+    --------
+    >>> G = nx.random_partition_graph([10, 10, 10], 0.25, 0.01)
+    >>> len(G)
+    30
+    >>> partition = G.graph["partition"]
+    >>> len(partition)
+    3
+
+    Notes
+    -----
+    This is a generalization of the planted-l-partition described in
+    [1]_.  It allows for the creation of groups of any size.
+
+    The partition is store as a graph attribute 'partition'.
+
+    References
+    ----------
+    .. [1] Santo Fortunato 'Community Detection in Graphs' Physical Reports
+       Volume 486, Issue 3-5 p. 75-174. https://arxiv.org/abs/0906.0612
+    """
+    # Use geometric method for O(n+m) complexity algorithm
+    # partition = nx.community_sets(nx.get_node_attributes(G, 'affiliation'))
+    if not 0.0 <= p_in <= 1.0:
+        raise nx.NetworkXError("p_in must be in [0,1]")
+    if not 0.0 <= p_out <= 1.0:
+        raise nx.NetworkXError("p_out must be in [0,1]")
+
+    # create connection matrix
+    num_blocks = len(sizes)
+    p = [[p_out for s in range(num_blocks)] for r in range(num_blocks)]
+    for r in range(num_blocks):
+        p[r][r] = p_in
+
+    return stochastic_block_model(
+        sizes,
+        p,
+        nodelist=None,
+        seed=seed,
+        directed=directed,
+        selfloops=False,
+        sparse=True,
+    )
+
+
+@py_random_state(4)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def planted_partition_graph(l, k, p_in, p_out, seed=None, directed=False):
+    """Returns the planted l-partition graph.
+
+    This model partitions a graph with n=l*k vertices in
+    l groups with k vertices each. Vertices of the same
+    group are linked with a probability p_in, and vertices
+    of different groups are linked with probability p_out.
+
+    Parameters
+    ----------
+    l : int
+      Number of groups
+    k : int
+      Number of vertices in each group
+    p_in : float
+      probability of connecting vertices within a group
+    p_out : float
+      probability of connected vertices between groups
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    directed : bool,optional (default=False)
+      If True return a directed graph
+
+    Returns
+    -------
+    G : NetworkX Graph or DiGraph
+      planted l-partition graph
+
+    Raises
+    ------
+    NetworkXError
+      If `p_in`, `p_out` are not in `[0, 1]`
+
+    Examples
+    --------
+    >>> G = nx.planted_partition_graph(4, 3, 0.5, 0.1, seed=42)
+
+    See Also
+    --------
+    random_partition_model
+
+    References
+    ----------
+    .. [1] A. Condon, R.M. Karp, Algorithms for graph partitioning
+        on the planted partition model,
+        Random Struct. Algor. 18 (2001) 116-140.
+
+    .. [2] Santo Fortunato 'Community Detection in Graphs' Physical Reports
+       Volume 486, Issue 3-5 p. 75-174. https://arxiv.org/abs/0906.0612
+    """
+    return random_partition_graph([k] * l, p_in, p_out, seed=seed, directed=directed)
+
+
+@py_random_state(6)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def gaussian_random_partition_graph(n, s, v, p_in, p_out, directed=False, seed=None):
+    """Generate a Gaussian random partition graph.
+
+    A Gaussian random partition graph is created by creating k partitions
+    each with a size drawn from a normal distribution with mean s and variance
+    s/v. Nodes are connected within clusters with probability p_in and
+    between clusters with probability p_out[1]
+
+    Parameters
+    ----------
+    n : int
+      Number of nodes in the graph
+    s : float
+      Mean cluster size
+    v : float
+      Shape parameter. The variance of cluster size distribution is s/v.
+    p_in : float
+      Probability of intra cluster connection.
+    p_out : float
+      Probability of inter cluster connection.
+    directed : boolean, optional default=False
+      Whether to create a directed graph or not
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    G : NetworkX Graph or DiGraph
+      gaussian random partition graph
+
+    Raises
+    ------
+    NetworkXError
+      If s is > n
+      If p_in or p_out is not in [0,1]
+
+    Notes
+    -----
+    Note the number of partitions is dependent on s,v and n, and that the
+    last partition may be considerably smaller, as it is sized to simply
+    fill out the nodes [1]
+
+    See Also
+    --------
+    random_partition_graph
+
+    Examples
+    --------
+    >>> G = nx.gaussian_random_partition_graph(100, 10, 10, 0.25, 0.1)
+    >>> len(G)
+    100
+
+    References
+    ----------
+    .. [1] Ulrik Brandes, Marco Gaertler, Dorothea Wagner,
+       Experiments on Graph Clustering Algorithms,
+       In the proceedings of the 11th Europ. Symp. Algorithms, 2003.
+    """
+    if s > n:
+        raise nx.NetworkXError("s must be <= n")
+    assigned = 0
+    sizes = []
+    while True:
+        size = int(seed.gauss(s, s / v + 0.5))
+        if size < 1:  # how to handle 0 or negative sizes?
+            continue
+        if assigned + size >= n:
+            sizes.append(n - assigned)
+            break
+        assigned += size
+        sizes.append(size)
+    return random_partition_graph(sizes, p_in, p_out, seed=seed, directed=directed)
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def ring_of_cliques(num_cliques, clique_size):
+    """Defines a "ring of cliques" graph.
+
+    A ring of cliques graph is consisting of cliques, connected through single
+    links. Each clique is a complete graph.
+
+    Parameters
+    ----------
+    num_cliques : int
+        Number of cliques
+    clique_size : int
+        Size of cliques
+
+    Returns
+    -------
+    G : NetworkX Graph
+        ring of cliques graph
+
+    Raises
+    ------
+    NetworkXError
+        If the number of cliques is lower than 2 or
+        if the size of cliques is smaller than 2.
+
+    Examples
+    --------
+    >>> G = nx.ring_of_cliques(8, 4)
+
+    See Also
+    --------
+    connected_caveman_graph
+
+    Notes
+    -----
+    The `connected_caveman_graph` graph removes a link from each clique to
+    connect it with the next clique. Instead, the `ring_of_cliques` graph
+    simply adds the link without removing any link from the cliques.
+    """
+    if num_cliques < 2:
+        raise nx.NetworkXError("A ring of cliques must have at least two cliques")
+    if clique_size < 2:
+        raise nx.NetworkXError("The cliques must have at least two nodes")
+
+    G = nx.Graph()
+    for i in range(num_cliques):
+        edges = itertools.combinations(
+            range(i * clique_size, i * clique_size + clique_size), 2
+        )
+        G.add_edges_from(edges)
+        G.add_edge(
+            i * clique_size + 1, (i + 1) * clique_size % (num_cliques * clique_size)
+        )
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def windmill_graph(n, k):
+    """Generate a windmill graph.
+    A windmill graph is a graph of `n` cliques each of size `k` that are all
+    joined at one node.
+    It can be thought of as taking a disjoint union of `n` cliques of size `k`,
+    selecting one point from each, and contracting all of the selected points.
+    Alternatively, one could generate `n` cliques of size `k-1` and one node
+    that is connected to all other nodes in the graph.
+
+    Parameters
+    ----------
+    n : int
+        Number of cliques
+    k : int
+        Size of cliques
+
+    Returns
+    -------
+    G : NetworkX Graph
+        windmill graph with n cliques of size k
+
+    Raises
+    ------
+    NetworkXError
+        If the number of cliques is less than two
+        If the size of the cliques are less than two
+
+    Examples
+    --------
+    >>> G = nx.windmill_graph(4, 5)
+
+    Notes
+    -----
+    The node labeled `0` will be the node connected to all other nodes.
+    Note that windmill graphs are usually denoted `Wd(k,n)`, so the parameters
+    are in the opposite order as the parameters of this method.
+    """
+    if n < 2:
+        msg = "A windmill graph must have at least two cliques"
+        raise nx.NetworkXError(msg)
+    if k < 2:
+        raise nx.NetworkXError("The cliques must have at least two nodes")
+
+    G = nx.disjoint_union_all(
+        itertools.chain(
+            [nx.complete_graph(k)], (nx.complete_graph(k - 1) for _ in range(n - 1))
+        )
+    )
+    G.add_edges_from((0, i) for i in range(k, G.number_of_nodes()))
+    return G
+
+
+@py_random_state(3)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def stochastic_block_model(
+    sizes, p, nodelist=None, seed=None, directed=False, selfloops=False, sparse=True
+):
+    """Returns a stochastic block model graph.
+
+    This model partitions the nodes in blocks of arbitrary sizes, and places
+    edges between pairs of nodes independently, with a probability that depends
+    on the blocks.
+
+    Parameters
+    ----------
+    sizes : list of ints
+        Sizes of blocks
+    p : list of list of floats
+        Element (r,s) gives the density of edges going from the nodes
+        of group r to nodes of group s.
+        p must match the number of groups (len(sizes) == len(p)),
+        and it must be symmetric if the graph is undirected.
+    nodelist : list, optional
+        The block tags are assigned according to the node identifiers
+        in nodelist. If nodelist is None, then the ordering is the
+        range [0,sum(sizes)-1].
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    directed : boolean optional, default=False
+        Whether to create a directed graph or not.
+    selfloops : boolean optional, default=False
+        Whether to include self-loops or not.
+    sparse: boolean optional, default=True
+        Use the sparse heuristic to speed up the generator.
+
+    Returns
+    -------
+    g : NetworkX Graph or DiGraph
+        Stochastic block model graph of size sum(sizes)
+
+    Raises
+    ------
+    NetworkXError
+      If probabilities are not in [0,1].
+      If the probability matrix is not square (directed case).
+      If the probability matrix is not symmetric (undirected case).
+      If the sizes list does not match nodelist or the probability matrix.
+      If nodelist contains duplicate.
+
+    Examples
+    --------
+    >>> sizes = [75, 75, 300]
+    >>> probs = [[0.25, 0.05, 0.02], [0.05, 0.35, 0.07], [0.02, 0.07, 0.40]]
+    >>> g = nx.stochastic_block_model(sizes, probs, seed=0)
+    >>> len(g)
+    450
+    >>> H = nx.quotient_graph(g, g.graph["partition"], relabel=True)
+    >>> for v in H.nodes(data=True):
+    ...     print(round(v[1]["density"], 3))
+    0.245
+    0.348
+    0.405
+    >>> for v in H.edges(data=True):
+    ...     print(round(1.0 * v[2]["weight"] / (sizes[v[0]] * sizes[v[1]]), 3))
+    0.051
+    0.022
+    0.07
+
+    See Also
+    --------
+    random_partition_graph
+    planted_partition_graph
+    gaussian_random_partition_graph
+    gnp_random_graph
+
+    References
+    ----------
+    .. [1] Holland, P. W., Laskey, K. B., & Leinhardt, S.,
+           "Stochastic blockmodels: First steps",
+           Social networks, 5(2), 109-137, 1983.
+    """
+    # Check if dimensions match
+    if len(sizes) != len(p):
+        raise nx.NetworkXException("'sizes' and 'p' do not match.")
+    # Check for probability symmetry (undirected) and shape (directed)
+    for row in p:
+        if len(p) != len(row):
+            raise nx.NetworkXException("'p' must be a square matrix.")
+    if not directed:
+        p_transpose = [list(i) for i in zip(*p)]
+        for i in zip(p, p_transpose):
+            for j in zip(i[0], i[1]):
+                if abs(j[0] - j[1]) > 1e-08:
+                    raise nx.NetworkXException("'p' must be symmetric.")
+    # Check for probability range
+    for row in p:
+        for prob in row:
+            if prob < 0 or prob > 1:
+                raise nx.NetworkXException("Entries of 'p' not in [0,1].")
+    # Check for nodelist consistency
+    if nodelist is not None:
+        if len(nodelist) != sum(sizes):
+            raise nx.NetworkXException("'nodelist' and 'sizes' do not match.")
+        if len(nodelist) != len(set(nodelist)):
+            raise nx.NetworkXException("nodelist contains duplicate.")
+    else:
+        nodelist = range(sum(sizes))
+
+    # Setup the graph conditionally to the directed switch.
+    block_range = range(len(sizes))
+    if directed:
+        g = nx.DiGraph()
+        block_iter = itertools.product(block_range, block_range)
+    else:
+        g = nx.Graph()
+        block_iter = itertools.combinations_with_replacement(block_range, 2)
+    # Split nodelist in a partition (list of sets).
+    size_cumsum = [sum(sizes[0:x]) for x in range(len(sizes) + 1)]
+    g.graph["partition"] = [
+        set(nodelist[size_cumsum[x] : size_cumsum[x + 1]])
+        for x in range(len(size_cumsum) - 1)
+    ]
+    # Setup nodes and graph name
+    for block_id, nodes in enumerate(g.graph["partition"]):
+        for node in nodes:
+            g.add_node(node, block=block_id)
+
+    g.name = "stochastic_block_model"
+
+    # Test for edge existence
+    parts = g.graph["partition"]
+    for i, j in block_iter:
+        if i == j:
+            if directed:
+                if selfloops:
+                    edges = itertools.product(parts[i], parts[i])
+                else:
+                    edges = itertools.permutations(parts[i], 2)
+            else:
+                edges = itertools.combinations(parts[i], 2)
+                if selfloops:
+                    edges = itertools.chain(edges, zip(parts[i], parts[i]))
+            for e in edges:
+                if seed.random() < p[i][j]:
+                    g.add_edge(*e)
+        else:
+            edges = itertools.product(parts[i], parts[j])
+        if sparse:
+            if p[i][j] == 1:  # Test edges cases p_ij = 0 or 1
+                for e in edges:
+                    g.add_edge(*e)
+            elif p[i][j] > 0:
+                while True:
+                    try:
+                        logrand = math.log(seed.random())
+                        skip = math.floor(logrand / math.log(1 - p[i][j]))
+                        # consume "skip" edges
+                        next(itertools.islice(edges, skip, skip), None)
+                        e = next(edges)
+                        g.add_edge(*e)  # __safe
+                    except StopIteration:
+                        break
+        else:
+            for e in edges:
+                if seed.random() < p[i][j]:
+                    g.add_edge(*e)  # __safe
+    return g
+
+
+def _zipf_rv_below(gamma, xmin, threshold, seed):
+    """Returns a random value chosen from the bounded Zipf distribution.
+
+    Repeatedly draws values from the Zipf distribution until the
+    threshold is met, then returns that value.
+    """
+    result = nx.utils.zipf_rv(gamma, xmin, seed)
+    while result > threshold:
+        result = nx.utils.zipf_rv(gamma, xmin, seed)
+    return result
+
+
+def _powerlaw_sequence(gamma, low, high, condition, length, max_iters, seed):
+    """Returns a list of numbers obeying a constrained power law distribution.
+
+    ``gamma`` and ``low`` are the parameters for the Zipf distribution.
+
+    ``high`` is the maximum allowed value for values draw from the Zipf
+    distribution. For more information, see :func:`_zipf_rv_below`.
+
+    ``condition`` and ``length`` are Boolean-valued functions on
+    lists. While generating the list, random values are drawn and
+    appended to the list until ``length`` is satisfied by the created
+    list. Once ``condition`` is satisfied, the sequence generated in
+    this way is returned.
+
+    ``max_iters`` indicates the number of times to generate a list
+    satisfying ``length``. If the number of iterations exceeds this
+    value, :exc:`~networkx.exception.ExceededMaxIterations` is raised.
+
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    """
+    for i in range(max_iters):
+        seq = []
+        while not length(seq):
+            seq.append(_zipf_rv_below(gamma, low, high, seed))
+        if condition(seq):
+            return seq
+    raise nx.ExceededMaxIterations("Could not create power law sequence")
+
+
+def _hurwitz_zeta(x, q, tolerance):
+    """The Hurwitz zeta function, or the Riemann zeta function of two arguments.
+
+    ``x`` must be greater than one and ``q`` must be positive.
+
+    This function repeatedly computes subsequent partial sums until
+    convergence, as decided by ``tolerance``.
+    """
+    z = 0
+    z_prev = -float("inf")
+    k = 0
+    while abs(z - z_prev) > tolerance:
+        z_prev = z
+        z += 1 / ((k + q) ** x)
+        k += 1
+    return z
+
+
+def _generate_min_degree(gamma, average_degree, max_degree, tolerance, max_iters):
+    """Returns a minimum degree from the given average degree."""
+    # Defines zeta function whether or not Scipy is available
+    try:
+        from scipy.special import zeta
+    except ImportError:
+
+        def zeta(x, q):
+            return _hurwitz_zeta(x, q, tolerance)
+
+    min_deg_top = max_degree
+    min_deg_bot = 1
+    min_deg_mid = (min_deg_top - min_deg_bot) / 2 + min_deg_bot
+    itrs = 0
+    mid_avg_deg = 0
+    while abs(mid_avg_deg - average_degree) > tolerance:
+        if itrs > max_iters:
+            raise nx.ExceededMaxIterations("Could not match average_degree")
+        mid_avg_deg = 0
+        for x in range(int(min_deg_mid), max_degree + 1):
+            mid_avg_deg += (x ** (-gamma + 1)) / zeta(gamma, min_deg_mid)
+        if mid_avg_deg > average_degree:
+            min_deg_top = min_deg_mid
+            min_deg_mid = (min_deg_top - min_deg_bot) / 2 + min_deg_bot
+        else:
+            min_deg_bot = min_deg_mid
+            min_deg_mid = (min_deg_top - min_deg_bot) / 2 + min_deg_bot
+        itrs += 1
+    # return int(min_deg_mid + 0.5)
+    return round(min_deg_mid)
+
+
+def _generate_communities(degree_seq, community_sizes, mu, max_iters, seed):
+    """Returns a list of sets, each of which represents a community.
+
+    ``degree_seq`` is the degree sequence that must be met by the
+    graph.
+
+    ``community_sizes`` is the community size distribution that must be
+    met by the generated list of sets.
+
+    ``mu`` is a float in the interval [0, 1] indicating the fraction of
+    intra-community edges incident to each node.
+
+    ``max_iters`` is the number of times to try to add a node to a
+    community. This must be greater than the length of
+    ``degree_seq``, otherwise this function will always fail. If
+    the number of iterations exceeds this value,
+    :exc:`~networkx.exception.ExceededMaxIterations` is raised.
+
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    The communities returned by this are sets of integers in the set {0,
+    ..., *n* - 1}, where *n* is the length of ``degree_seq``.
+
+    """
+    # This assumes the nodes in the graph will be natural numbers.
+    result = [set() for _ in community_sizes]
+    n = len(degree_seq)
+    free = list(range(n))
+    for i in range(max_iters):
+        v = free.pop()
+        c = seed.choice(range(len(community_sizes)))
+        # s = int(degree_seq[v] * (1 - mu) + 0.5)
+        s = round(degree_seq[v] * (1 - mu))
+        # If the community is large enough, add the node to the chosen
+        # community. Otherwise, return it to the list of unaffiliated
+        # nodes.
+        if s < community_sizes[c]:
+            result[c].add(v)
+        else:
+            free.append(v)
+        # If the community is too big, remove a node from it.
+        if len(result[c]) > community_sizes[c]:
+            free.append(result[c].pop())
+        if not free:
+            return result
+    msg = "Could not assign communities; try increasing min_community"
+    raise nx.ExceededMaxIterations(msg)
+
+
+@py_random_state(11)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def LFR_benchmark_graph(
+    n,
+    tau1,
+    tau2,
+    mu,
+    average_degree=None,
+    min_degree=None,
+    max_degree=None,
+    min_community=None,
+    max_community=None,
+    tol=1.0e-7,
+    max_iters=500,
+    seed=None,
+):
+    r"""Returns the LFR benchmark graph.
+
+    This algorithm proceeds as follows:
+
+    1) Find a degree sequence with a power law distribution, and minimum
+       value ``min_degree``, which has approximate average degree
+       ``average_degree``. This is accomplished by either
+
+       a) specifying ``min_degree`` and not ``average_degree``,
+       b) specifying ``average_degree`` and not ``min_degree``, in which
+          case a suitable minimum degree will be found.
+
+       ``max_degree`` can also be specified, otherwise it will be set to
+       ``n``. Each node *u* will have $\mu \mathrm{deg}(u)$ edges
+       joining it to nodes in communities other than its own and $(1 -
+       \mu) \mathrm{deg}(u)$ edges joining it to nodes in its own
+       community.
+    2) Generate community sizes according to a power law distribution
+       with exponent ``tau2``. If ``min_community`` and
+       ``max_community`` are not specified they will be selected to be
+       ``min_degree`` and ``max_degree``, respectively.  Community sizes
+       are generated until the sum of their sizes equals ``n``.
+    3) Each node will be randomly assigned a community with the
+       condition that the community is large enough for the node's
+       intra-community degree, $(1 - \mu) \mathrm{deg}(u)$ as
+       described in step 2. If a community grows too large, a random node
+       will be selected for reassignment to a new community, until all
+       nodes have been assigned a community.
+    4) Each node *u* then adds $(1 - \mu) \mathrm{deg}(u)$
+       intra-community edges and $\mu \mathrm{deg}(u)$ inter-community
+       edges.
+
+    Parameters
+    ----------
+    n : int
+        Number of nodes in the created graph.
+
+    tau1 : float
+        Power law exponent for the degree distribution of the created
+        graph. This value must be strictly greater than one.
+
+    tau2 : float
+        Power law exponent for the community size distribution in the
+        created graph. This value must be strictly greater than one.
+
+    mu : float
+        Fraction of inter-community edges incident to each node. This
+        value must be in the interval [0, 1].
+
+    average_degree : float
+        Desired average degree of nodes in the created graph. This value
+        must be in the interval [0, *n*]. Exactly one of this and
+        ``min_degree`` must be specified, otherwise a
+        :exc:`NetworkXError` is raised.
+
+    min_degree : int
+        Minimum degree of nodes in the created graph. This value must be
+        in the interval [0, *n*]. Exactly one of this and
+        ``average_degree`` must be specified, otherwise a
+        :exc:`NetworkXError` is raised.
+
+    max_degree : int
+        Maximum degree of nodes in the created graph. If not specified,
+        this is set to ``n``, the total number of nodes in the graph.
+
+    min_community : int
+        Minimum size of communities in the graph. If not specified, this
+        is set to ``min_degree``.
+
+    max_community : int
+        Maximum size of communities in the graph. If not specified, this
+        is set to ``n``, the total number of nodes in the graph.
+
+    tol : float
+        Tolerance when comparing floats, specifically when comparing
+        average degree values.
+
+    max_iters : int
+        Maximum number of iterations to try to create the community sizes,
+        degree distribution, and community affiliations.
+
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    G : NetworkX graph
+        The LFR benchmark graph generated according to the specified
+        parameters.
+
+        Each node in the graph has a node attribute ``'community'`` that
+        stores the community (that is, the set of nodes) that includes
+        it.
+
+    Raises
+    ------
+    NetworkXError
+        If any of the parameters do not meet their upper and lower bounds:
+
+        - ``tau1`` and ``tau2`` must be strictly greater than 1.
+        - ``mu`` must be in [0, 1].
+        - ``max_degree`` must be in {1, ..., *n*}.
+        - ``min_community`` and ``max_community`` must be in {0, ...,
+          *n*}.
+
+        If not exactly one of ``average_degree`` and ``min_degree`` is
+        specified.
+
+        If ``min_degree`` is not specified and a suitable ``min_degree``
+        cannot be found.
+
+    ExceededMaxIterations
+        If a valid degree sequence cannot be created within
+        ``max_iters`` number of iterations.
+
+        If a valid set of community sizes cannot be created within
+        ``max_iters`` number of iterations.
+
+        If a valid community assignment cannot be created within ``10 *
+        n * max_iters`` number of iterations.
+
+    Examples
+    --------
+    Basic usage::
+
+        >>> from networkx.generators.community import LFR_benchmark_graph
+        >>> n = 250
+        >>> tau1 = 3
+        >>> tau2 = 1.5
+        >>> mu = 0.1
+        >>> G = LFR_benchmark_graph(
+        ...     n, tau1, tau2, mu, average_degree=5, min_community=20, seed=10
+        ... )
+
+    Continuing the example above, you can get the communities from the
+    node attributes of the graph::
+
+        >>> communities = {frozenset(G.nodes[v]["community"]) for v in G}
+
+    Notes
+    -----
+    This algorithm differs slightly from the original way it was
+    presented in [1].
+
+    1) Rather than connecting the graph via a configuration model then
+       rewiring to match the intra-community and inter-community
+       degrees, we do this wiring explicitly at the end, which should be
+       equivalent.
+    2) The code posted on the author's website [2] calculates the random
+       power law distributed variables and their average using
+       continuous approximations, whereas we use the discrete
+       distributions here as both degree and community size are
+       discrete.
+
+    Though the authors describe the algorithm as quite robust, testing
+    during development indicates that a somewhat narrower parameter set
+    is likely to successfully produce a graph. Some suggestions have
+    been provided in the event of exceptions.
+
+    References
+    ----------
+    .. [1] "Benchmark graphs for testing community detection algorithms",
+           Andrea Lancichinetti, Santo Fortunato, and Filippo Radicchi,
+           Phys. Rev. E 78, 046110 2008
+    .. [2] https://www.santofortunato.net/resources
+
+    """
+    # Perform some basic parameter validation.
+    if not tau1 > 1:
+        raise nx.NetworkXError("tau1 must be greater than one")
+    if not tau2 > 1:
+        raise nx.NetworkXError("tau2 must be greater than one")
+    if not 0 <= mu <= 1:
+        raise nx.NetworkXError("mu must be in the interval [0, 1]")
+
+    # Validate parameters for generating the degree sequence.
+    if max_degree is None:
+        max_degree = n
+    elif not 0 < max_degree <= n:
+        raise nx.NetworkXError("max_degree must be in the interval (0, n]")
+    if not ((min_degree is None) ^ (average_degree is None)):
+        raise nx.NetworkXError(
+            "Must assign exactly one of min_degree and average_degree"
+        )
+    if min_degree is None:
+        min_degree = _generate_min_degree(
+            tau1, average_degree, max_degree, tol, max_iters
+        )
+
+    # Generate a degree sequence with a power law distribution.
+    low, high = min_degree, max_degree
+
+    def condition(seq):
+        return sum(seq) % 2 == 0
+
+    def length(seq):
+        return len(seq) >= n
+
+    deg_seq = _powerlaw_sequence(tau1, low, high, condition, length, max_iters, seed)
+
+    # Validate parameters for generating the community size sequence.
+    if min_community is None:
+        min_community = min(deg_seq)
+    if max_community is None:
+        max_community = max(deg_seq)
+
+    # Generate a community size sequence with a power law distribution.
+    #
+    # TODO The original code incremented the number of iterations each
+    # time a new Zipf random value was drawn from the distribution. This
+    # differed from the way the number of iterations was incremented in
+    # `_powerlaw_degree_sequence`, so this code was changed to match
+    # that one. As a result, this code is allowed many more chances to
+    # generate a valid community size sequence.
+    low, high = min_community, max_community
+
+    def condition(seq):
+        return sum(seq) == n
+
+    def length(seq):
+        return sum(seq) >= n
+
+    comms = _powerlaw_sequence(tau2, low, high, condition, length, max_iters, seed)
+
+    # Generate the communities based on the given degree sequence and
+    # community sizes.
+    max_iters *= 10 * n
+    communities = _generate_communities(deg_seq, comms, mu, max_iters, seed)
+
+    # Finally, generate the benchmark graph based on the given
+    # communities, joining nodes according to the intra- and
+    # inter-community degrees.
+    G = nx.Graph()
+    G.add_nodes_from(range(n))
+    for c in communities:
+        for u in c:
+            while G.degree(u) < round(deg_seq[u] * (1 - mu)):
+                v = seed.choice(list(c))
+                G.add_edge(u, v)
+            while G.degree(u) < deg_seq[u]:
+                v = seed.choice(range(n))
+                if v not in c:
+                    G.add_edge(u, v)
+            G.nodes[u]["community"] = c
+    return G
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/degree_seq.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/degree_seq.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a374f47c9932fda1757163dbf8868d8c343edb6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/degree_seq.py
@@ -0,0 +1,886 @@
+"""Generate graphs with a given degree sequence or expected degree sequence."""
+
+import heapq
+import math
+from itertools import chain, combinations, zip_longest
+from operator import itemgetter
+
+import networkx as nx
+from networkx.utils import py_random_state, random_weighted_sample
+
+__all__ = [
+    "configuration_model",
+    "directed_configuration_model",
+    "expected_degree_graph",
+    "havel_hakimi_graph",
+    "directed_havel_hakimi_graph",
+    "degree_sequence_tree",
+    "random_degree_sequence_graph",
+]
+
+chaini = chain.from_iterable
+
+
+def _to_stublist(degree_sequence):
+    """Returns a list of degree-repeated node numbers.
+
+    ``degree_sequence`` is a list of nonnegative integers representing
+    the degrees of nodes in a graph.
+
+    This function returns a list of node numbers with multiplicities
+    according to the given degree sequence. For example, if the first
+    element of ``degree_sequence`` is ``3``, then the first node number,
+    ``0``, will appear at the head of the returned list three times. The
+    node numbers are assumed to be the numbers zero through
+    ``len(degree_sequence) - 1``.
+
+    Examples
+    --------
+
+    >>> degree_sequence = [1, 2, 3]
+    >>> _to_stublist(degree_sequence)
+    [0, 1, 1, 2, 2, 2]
+
+    If a zero appears in the sequence, that means the node exists but
+    has degree zero, so that number will be skipped in the returned
+    list::
+
+    >>> degree_sequence = [2, 0, 1]
+    >>> _to_stublist(degree_sequence)
+    [0, 0, 2]
+
+    """
+    return list(chaini([n] * d for n, d in enumerate(degree_sequence)))
+
+
+def _configuration_model(
+    deg_sequence, create_using, directed=False, in_deg_sequence=None, seed=None
+):
+    """Helper function for generating either undirected or directed
+    configuration model graphs.
+
+    ``deg_sequence`` is a list of nonnegative integers representing the
+    degree of the node whose label is the index of the list element.
+
+    ``create_using`` see :func:`~networkx.empty_graph`.
+
+    ``directed`` and ``in_deg_sequence`` are required if you want the
+    returned graph to be generated using the directed configuration
+    model algorithm. If ``directed`` is ``False``, then ``deg_sequence``
+    is interpreted as the degree sequence of an undirected graph and
+    ``in_deg_sequence`` is ignored. Otherwise, if ``directed`` is
+    ``True``, then ``deg_sequence`` is interpreted as the out-degree
+    sequence and ``in_deg_sequence`` as the in-degree sequence of a
+    directed graph.
+
+    .. note::
+
+       ``deg_sequence`` and ``in_deg_sequence`` need not be the same
+       length.
+
+    ``seed`` is a random.Random or numpy.random.RandomState instance
+
+    This function returns a graph, directed if and only if ``directed``
+    is ``True``, generated according to the configuration model
+    algorithm. For more information on the algorithm, see the
+    :func:`configuration_model` or :func:`directed_configuration_model`
+    functions.
+
+    """
+    n = len(deg_sequence)
+    G = nx.empty_graph(n, create_using)
+    # If empty, return the null graph immediately.
+    if n == 0:
+        return G
+    # Build a list of available degree-repeated nodes.  For example,
+    # for degree sequence [3, 2, 1, 1, 1], the "stub list" is
+    # initially [0, 0, 0, 1, 1, 2, 3, 4], that is, node 0 has degree
+    # 3 and thus is repeated 3 times, etc.
+    #
+    # Also, shuffle the stub list in order to get a random sequence of
+    # node pairs.
+    if directed:
+        pairs = zip_longest(deg_sequence, in_deg_sequence, fillvalue=0)
+        # Unzip the list of pairs into a pair of lists.
+        out_deg, in_deg = zip(*pairs)
+
+        out_stublist = _to_stublist(out_deg)
+        in_stublist = _to_stublist(in_deg)
+
+        seed.shuffle(out_stublist)
+        seed.shuffle(in_stublist)
+    else:
+        stublist = _to_stublist(deg_sequence)
+        # Choose a random balanced bipartition of the stublist, which
+        # gives a random pairing of nodes. In this implementation, we
+        # shuffle the list and then split it in half.
+        n = len(stublist)
+        half = n // 2
+        seed.shuffle(stublist)
+        out_stublist, in_stublist = stublist[:half], stublist[half:]
+    G.add_edges_from(zip(out_stublist, in_stublist))
+    return G
+
+
+@py_random_state(2)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def configuration_model(deg_sequence, create_using=None, seed=None):
+    """Returns a random graph with the given degree sequence.
+
+    The configuration model generates a random pseudograph (graph with
+    parallel edges and self loops) by randomly assigning edges to
+    match the given degree sequence.
+
+    Parameters
+    ----------
+    deg_sequence :  list of nonnegative integers
+        Each list entry corresponds to the degree of a node.
+    create_using : NetworkX graph constructor, optional (default MultiGraph)
+        Graph type to create. If graph instance, then cleared before populated.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    G : MultiGraph
+        A graph with the specified degree sequence.
+        Nodes are labeled starting at 0 with an index
+        corresponding to the position in deg_sequence.
+
+    Raises
+    ------
+    NetworkXError
+        If the degree sequence does not have an even sum.
+
+    See Also
+    --------
+    is_graphical
+
+    Notes
+    -----
+    As described by Newman [1]_.
+
+    A non-graphical degree sequence (not realizable by some simple
+    graph) is allowed since this function returns graphs with self
+    loops and parallel edges.  An exception is raised if the degree
+    sequence does not have an even sum.
+
+    This configuration model construction process can lead to
+    duplicate edges and loops.  You can remove the self-loops and
+    parallel edges (see below) which will likely result in a graph
+    that doesn't have the exact degree sequence specified.
+
+    The density of self-loops and parallel edges tends to decrease as
+    the number of nodes increases. However, typically the number of
+    self-loops will approach a Poisson distribution with a nonzero mean,
+    and similarly for the number of parallel edges.  Consider a node
+    with *k* stubs. The probability of being joined to another stub of
+    the same node is basically (*k* - *1*) / *N*, where *k* is the
+    degree and *N* is the number of nodes. So the probability of a
+    self-loop scales like *c* / *N* for some constant *c*. As *N* grows,
+    this means we expect *c* self-loops. Similarly for parallel edges.
+
+    References
+    ----------
+    .. [1] M.E.J. Newman, "The structure and function of complex networks",
+       SIAM REVIEW 45-2, pp 167-256, 2003.
+
+    Examples
+    --------
+    You can create a degree sequence following a particular distribution
+    by using the one of the distribution functions in
+    :mod:`~networkx.utils.random_sequence` (or one of your own). For
+    example, to create an undirected multigraph on one hundred nodes
+    with degree sequence chosen from the power law distribution:
+
+    >>> sequence = nx.random_powerlaw_tree_sequence(100, tries=5000)
+    >>> G = nx.configuration_model(sequence)
+    >>> len(G)
+    100
+    >>> actual_degrees = [d for v, d in G.degree()]
+    >>> actual_degrees == sequence
+    True
+
+    The returned graph is a multigraph, which may have parallel
+    edges. To remove any parallel edges from the returned graph:
+
+    >>> G = nx.Graph(G)
+
+    Similarly, to remove self-loops:
+
+    >>> G.remove_edges_from(nx.selfloop_edges(G))
+
+    """
+    if sum(deg_sequence) % 2 != 0:
+        msg = "Invalid degree sequence: sum of degrees must be even, not odd"
+        raise nx.NetworkXError(msg)
+
+    G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
+    if G.is_directed():
+        raise nx.NetworkXNotImplemented("not implemented for directed graphs")
+
+    G = _configuration_model(deg_sequence, G, seed=seed)
+
+    return G
+
+
+@py_random_state(3)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def directed_configuration_model(
+    in_degree_sequence, out_degree_sequence, create_using=None, seed=None
+):
+    """Returns a directed_random graph with the given degree sequences.
+
+    The configuration model generates a random directed pseudograph
+    (graph with parallel edges and self loops) by randomly assigning
+    edges to match the given degree sequences.
+
+    Parameters
+    ----------
+    in_degree_sequence :  list of nonnegative integers
+       Each list entry corresponds to the in-degree of a node.
+    out_degree_sequence :  list of nonnegative integers
+       Each list entry corresponds to the out-degree of a node.
+    create_using : NetworkX graph constructor, optional (default MultiDiGraph)
+        Graph type to create. If graph instance, then cleared before populated.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    G : MultiDiGraph
+        A graph with the specified degree sequences.
+        Nodes are labeled starting at 0 with an index
+        corresponding to the position in deg_sequence.
+
+    Raises
+    ------
+    NetworkXError
+        If the degree sequences do not have the same sum.
+
+    See Also
+    --------
+    configuration_model
+
+    Notes
+    -----
+    Algorithm as described by Newman [1]_.
+
+    A non-graphical degree sequence (not realizable by some simple
+    graph) is allowed since this function returns graphs with self
+    loops and parallel edges.  An exception is raised if the degree
+    sequences does not have the same sum.
+
+    This configuration model construction process can lead to
+    duplicate edges and loops.  You can remove the self-loops and
+    parallel edges (see below) which will likely result in a graph
+    that doesn't have the exact degree sequence specified.  This
+    "finite-size effect" decreases as the size of the graph increases.
+
+    References
+    ----------
+    .. [1] Newman, M. E. J. and Strogatz, S. H. and Watts, D. J.
+       Random graphs with arbitrary degree distributions and their applications
+       Phys. Rev. E, 64, 026118 (2001)
+
+    Examples
+    --------
+    One can modify the in- and out-degree sequences from an existing
+    directed graph in order to create a new directed graph. For example,
+    here we modify the directed path graph:
+
+    >>> D = nx.DiGraph([(0, 1), (1, 2), (2, 3)])
+    >>> din = list(d for n, d in D.in_degree())
+    >>> dout = list(d for n, d in D.out_degree())
+    >>> din.append(1)
+    >>> dout[0] = 2
+    >>> # We now expect an edge from node 0 to a new node, node 3.
+    ... D = nx.directed_configuration_model(din, dout)
+
+    The returned graph is a directed multigraph, which may have parallel
+    edges. To remove any parallel edges from the returned graph:
+
+    >>> D = nx.DiGraph(D)
+
+    Similarly, to remove self-loops:
+
+    >>> D.remove_edges_from(nx.selfloop_edges(D))
+
+    """
+    if sum(in_degree_sequence) != sum(out_degree_sequence):
+        msg = "Invalid degree sequences: sequences must have equal sums"
+        raise nx.NetworkXError(msg)
+
+    if create_using is None:
+        create_using = nx.MultiDiGraph
+
+    G = _configuration_model(
+        out_degree_sequence,
+        create_using,
+        directed=True,
+        in_deg_sequence=in_degree_sequence,
+        seed=seed,
+    )
+
+    name = "directed configuration_model {} nodes {} edges"
+    return G
+
+
+@py_random_state(1)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def expected_degree_graph(w, seed=None, selfloops=True):
+    r"""Returns a random graph with given expected degrees.
+
+    Given a sequence of expected degrees $W=(w_0,w_1,\ldots,w_{n-1})$
+    of length $n$ this algorithm assigns an edge between node $u$ and
+    node $v$ with probability
+
+    .. math::
+
+       p_{uv} = \frac{w_u w_v}{\sum_k w_k} .
+
+    Parameters
+    ----------
+    w : list
+        The list of expected degrees.
+    selfloops: bool (default=True)
+        Set to False to remove the possibility of self-loop edges.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    Graph
+
+    Examples
+    --------
+    >>> z = [10 for i in range(100)]
+    >>> G = nx.expected_degree_graph(z)
+
+    Notes
+    -----
+    The nodes have integer labels corresponding to index of expected degrees
+    input sequence.
+
+    The complexity of this algorithm is $\mathcal{O}(n+m)$ where $n$ is the
+    number of nodes and $m$ is the expected number of edges.
+
+    The model in [1]_ includes the possibility of self-loop edges.
+    Set selfloops=False to produce a graph without self loops.
+
+    For finite graphs this model doesn't produce exactly the given
+    expected degree sequence.  Instead the expected degrees are as
+    follows.
+
+    For the case without self loops (selfloops=False),
+
+    .. math::
+
+       E[deg(u)] = \sum_{v \ne u} p_{uv}
+                = w_u \left( 1 - \frac{w_u}{\sum_k w_k} \right) .
+
+
+    NetworkX uses the standard convention that a self-loop edge counts 2
+    in the degree of a node, so with self loops (selfloops=True),
+
+    .. math::
+
+       E[deg(u)] =  \sum_{v \ne u} p_{uv}  + 2 p_{uu}
+                = w_u \left( 1 + \frac{w_u}{\sum_k w_k} \right) .
+
+    References
+    ----------
+    .. [1] Fan Chung and L. Lu, Connected components in random graphs with
+       given expected degree sequences, Ann. Combinatorics, 6,
+       pp. 125-145, 2002.
+    .. [2] Joel Miller and Aric Hagberg,
+       Efficient generation of networks with given expected degrees,
+       in Algorithms and Models for the Web-Graph (WAW 2011),
+       Alan Frieze, Paul Horn, and Paweł Prałat (Eds), LNCS 6732,
+       pp. 115-126, 2011.
+    """
+    n = len(w)
+    G = nx.empty_graph(n)
+
+    # If there are no nodes are no edges in the graph, return the empty graph.
+    if n == 0 or max(w) == 0:
+        return G
+
+    rho = 1 / sum(w)
+    # Sort the weights in decreasing order. The original order of the
+    # weights dictates the order of the (integer) node labels, so we
+    # need to remember the permutation applied in the sorting.
+    order = sorted(enumerate(w), key=itemgetter(1), reverse=True)
+    mapping = {c: u for c, (u, v) in enumerate(order)}
+    seq = [v for u, v in order]
+    last = n
+    if not selfloops:
+        last -= 1
+    for u in range(last):
+        v = u
+        if not selfloops:
+            v += 1
+        factor = seq[u] * rho
+        p = min(seq[v] * factor, 1)
+        while v < n and p > 0:
+            if p != 1:
+                r = seed.random()
+                v += math.floor(math.log(r, 1 - p))
+            if v < n:
+                q = min(seq[v] * factor, 1)
+                if seed.random() < q / p:
+                    G.add_edge(mapping[u], mapping[v])
+                v += 1
+                p = q
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def havel_hakimi_graph(deg_sequence, create_using=None):
+    """Returns a simple graph with given degree sequence constructed
+    using the Havel-Hakimi algorithm.
+
+    Parameters
+    ----------
+    deg_sequence: list of integers
+        Each integer corresponds to the degree of a node (need not be sorted).
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+        Graph type to create. If graph instance, then cleared before populated.
+        Directed graphs are not allowed.
+
+    Raises
+    ------
+    NetworkXException
+        For a non-graphical degree sequence (i.e. one
+        not realizable by some simple graph).
+
+    Notes
+    -----
+    The Havel-Hakimi algorithm constructs a simple graph by
+    successively connecting the node of highest degree to other nodes
+    of highest degree, resorting remaining nodes by degree, and
+    repeating the process. The resulting graph has a high
+    degree-associativity.  Nodes are labeled 1,.., len(deg_sequence),
+    corresponding to their position in deg_sequence.
+
+    The basic algorithm is from Hakimi [1]_ and was generalized by
+    Kleitman and Wang [2]_.
+
+    References
+    ----------
+    .. [1] Hakimi S., On Realizability of a Set of Integers as
+       Degrees of the Vertices of a Linear Graph. I,
+       Journal of SIAM, 10(3), pp. 496-506 (1962)
+    .. [2] Kleitman D.J. and Wang D.L.
+       Algorithms for Constructing Graphs and Digraphs with Given Valences
+       and Factors  Discrete Mathematics, 6(1), pp. 79-88 (1973)
+    """
+    if not nx.is_graphical(deg_sequence):
+        raise nx.NetworkXError("Invalid degree sequence")
+
+    p = len(deg_sequence)
+    G = nx.empty_graph(p, create_using)
+    if G.is_directed():
+        raise nx.NetworkXError("Directed graphs are not supported")
+    num_degs = [[] for i in range(p)]
+    dmax, dsum, n = 0, 0, 0
+    for d in deg_sequence:
+        # Process only the non-zero integers
+        if d > 0:
+            num_degs[d].append(n)
+            dmax, dsum, n = max(dmax, d), dsum + d, n + 1
+    # Return graph if no edges
+    if n == 0:
+        return G
+
+    modstubs = [(0, 0)] * (dmax + 1)
+    # Successively reduce degree sequence by removing the maximum degree
+    while n > 0:
+        # Retrieve the maximum degree in the sequence
+        while len(num_degs[dmax]) == 0:
+            dmax -= 1
+        # If there are not enough stubs to connect to, then the sequence is
+        # not graphical
+        if dmax > n - 1:
+            raise nx.NetworkXError("Non-graphical integer sequence")
+
+        # Remove largest stub in list
+        source = num_degs[dmax].pop()
+        n -= 1
+        # Reduce the next dmax largest stubs
+        mslen = 0
+        k = dmax
+        for i in range(dmax):
+            while len(num_degs[k]) == 0:
+                k -= 1
+            target = num_degs[k].pop()
+            G.add_edge(source, target)
+            n -= 1
+            if k > 1:
+                modstubs[mslen] = (k - 1, target)
+                mslen += 1
+        # Add back to the list any nonzero stubs that were removed
+        for i in range(mslen):
+            (stubval, stubtarget) = modstubs[i]
+            num_degs[stubval].append(stubtarget)
+            n += 1
+
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def directed_havel_hakimi_graph(in_deg_sequence, out_deg_sequence, create_using=None):
+    """Returns a directed graph with the given degree sequences.
+
+    Parameters
+    ----------
+    in_deg_sequence :  list of integers
+        Each list entry corresponds to the in-degree of a node.
+    out_deg_sequence : list of integers
+        Each list entry corresponds to the out-degree of a node.
+    create_using : NetworkX graph constructor, optional (default DiGraph)
+        Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : DiGraph
+        A graph with the specified degree sequences.
+        Nodes are labeled starting at 0 with an index
+        corresponding to the position in deg_sequence
+
+    Raises
+    ------
+    NetworkXError
+        If the degree sequences are not digraphical.
+
+    See Also
+    --------
+    configuration_model
+
+    Notes
+    -----
+    Algorithm as described by Kleitman and Wang [1]_.
+
+    References
+    ----------
+    .. [1] D.J. Kleitman and D.L. Wang
+       Algorithms for Constructing Graphs and Digraphs with Given Valences
+       and Factors Discrete Mathematics, 6(1), pp. 79-88 (1973)
+    """
+    in_deg_sequence = nx.utils.make_list_of_ints(in_deg_sequence)
+    out_deg_sequence = nx.utils.make_list_of_ints(out_deg_sequence)
+
+    # Process the sequences and form two heaps to store degree pairs with
+    # either zero or nonzero out degrees
+    sumin, sumout = 0, 0
+    nin, nout = len(in_deg_sequence), len(out_deg_sequence)
+    maxn = max(nin, nout)
+    G = nx.empty_graph(maxn, create_using, default=nx.DiGraph)
+    if maxn == 0:
+        return G
+    maxin = 0
+    stubheap, zeroheap = [], []
+    for n in range(maxn):
+        in_deg, out_deg = 0, 0
+        if n < nout:
+            out_deg = out_deg_sequence[n]
+        if n < nin:
+            in_deg = in_deg_sequence[n]
+        if in_deg < 0 or out_deg < 0:
+            raise nx.NetworkXError(
+                "Invalid degree sequences. Sequence values must be positive."
+            )
+        sumin, sumout, maxin = sumin + in_deg, sumout + out_deg, max(maxin, in_deg)
+        if in_deg > 0:
+            stubheap.append((-1 * out_deg, -1 * in_deg, n))
+        elif out_deg > 0:
+            zeroheap.append((-1 * out_deg, n))
+    if sumin != sumout:
+        raise nx.NetworkXError(
+            "Invalid degree sequences. Sequences must have equal sums."
+        )
+    heapq.heapify(stubheap)
+    heapq.heapify(zeroheap)
+
+    modstubs = [(0, 0, 0)] * (maxin + 1)
+    # Successively reduce degree sequence by removing the maximum
+    while stubheap:
+        # Remove first value in the sequence with a non-zero in degree
+        (freeout, freein, target) = heapq.heappop(stubheap)
+        freein *= -1
+        if freein > len(stubheap) + len(zeroheap):
+            raise nx.NetworkXError("Non-digraphical integer sequence")
+
+        # Attach arcs from the nodes with the most stubs
+        mslen = 0
+        for i in range(freein):
+            if zeroheap and (not stubheap or stubheap[0][0] > zeroheap[0][0]):
+                (stubout, stubsource) = heapq.heappop(zeroheap)
+                stubin = 0
+            else:
+                (stubout, stubin, stubsource) = heapq.heappop(stubheap)
+            if stubout == 0:
+                raise nx.NetworkXError("Non-digraphical integer sequence")
+            G.add_edge(stubsource, target)
+            # Check if source is now totally connected
+            if stubout + 1 < 0 or stubin < 0:
+                modstubs[mslen] = (stubout + 1, stubin, stubsource)
+                mslen += 1
+
+        # Add the nodes back to the heaps that still have available stubs
+        for i in range(mslen):
+            stub = modstubs[i]
+            if stub[1] < 0:
+                heapq.heappush(stubheap, stub)
+            else:
+                heapq.heappush(zeroheap, (stub[0], stub[2]))
+        if freeout < 0:
+            heapq.heappush(zeroheap, (freeout, target))
+
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def degree_sequence_tree(deg_sequence, create_using=None):
+    """Return a tree with the given degree sequence.
+
+    Two conditions must be met for a degree sequence to be valid for a tree:
+
+    1. The number of nodes must be one more than the number of edges.
+    2. The degree sequence must be trivial or have only strictly positive
+       node degrees.
+
+    Parameters
+    ----------
+    degree_sequence : iterable
+        Iterable of node degrees.
+
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+        Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    networkx.Graph
+        A tree with the given degree sequence.
+
+    Raises
+    ------
+    NetworkXError
+        If the degree sequence is not valid for a tree.
+
+        If `create_using` is directed.
+
+    See Also
+    --------
+    random_degree_sequence_graph
+    """
+    deg_sequence = list(deg_sequence)
+    valid, reason = nx.utils.is_valid_tree_degree_sequence(deg_sequence)
+    if not valid:
+        raise nx.NetworkXError(reason)
+
+    G = nx.empty_graph(0, create_using)
+    if G.is_directed():
+        raise nx.NetworkXError("Directed Graph not supported")
+
+    if deg_sequence == [0]:
+        G.add_node(0)
+        return G
+
+    # Sort all degrees greater than 1 in decreasing order.
+    #
+    # TODO Does this need to be sorted in reverse order?
+    deg = sorted((s for s in deg_sequence if s > 1), reverse=True)
+
+    # make path graph as backbone
+    n = len(deg) + 2
+    nx.add_path(G, range(n))
+    last = n
+
+    # add the leaves
+    for source in range(1, n - 1):
+        nedges = deg.pop() - 2
+        G.add_edges_from((source, target) for target in range(last, last + nedges))
+        last += nedges
+    return G
+
+
+@py_random_state(1)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def random_degree_sequence_graph(sequence, seed=None, tries=10):
+    r"""Returns a simple random graph with the given degree sequence.
+
+    If the maximum degree $d_m$ in the sequence is $O(m^{1/4})$ then the
+    algorithm produces almost uniform random graphs in $O(m d_m)$ time
+    where $m$ is the number of edges.
+
+    Parameters
+    ----------
+    sequence :  list of integers
+        Sequence of degrees
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    tries : int, optional
+        Maximum number of tries to create a graph
+
+    Returns
+    -------
+    G : Graph
+        A graph with the specified degree sequence.
+        Nodes are labeled starting at 0 with an index
+        corresponding to the position in the sequence.
+
+    Raises
+    ------
+    NetworkXUnfeasible
+        If the degree sequence is not graphical.
+    NetworkXError
+        If a graph is not produced in specified number of tries
+
+    See Also
+    --------
+    is_graphical, configuration_model
+
+    Notes
+    -----
+    The generator algorithm [1]_ is not guaranteed to produce a graph.
+
+    References
+    ----------
+    .. [1] Moshen Bayati, Jeong Han Kim, and Amin Saberi,
+       A sequential algorithm for generating random graphs.
+       Algorithmica, Volume 58, Number 4, 860-910,
+       DOI: 10.1007/s00453-009-9340-1
+
+    Examples
+    --------
+    >>> sequence = [1, 2, 2, 3]
+    >>> G = nx.random_degree_sequence_graph(sequence, seed=42)
+    >>> sorted(d for n, d in G.degree())
+    [1, 2, 2, 3]
+    """
+    DSRG = DegreeSequenceRandomGraph(sequence, seed)
+    for try_n in range(tries):
+        try:
+            return DSRG.generate()
+        except nx.NetworkXUnfeasible:
+            pass
+    raise nx.NetworkXError(f"failed to generate graph in {tries} tries")
+
+
+class DegreeSequenceRandomGraph:
+    # class to generate random graphs with a given degree sequence
+    # use random_degree_sequence_graph()
+    def __init__(self, degree, rng):
+        self.rng = rng
+        self.degree = list(degree)
+        if not nx.is_graphical(self.degree):
+            raise nx.NetworkXUnfeasible("degree sequence is not graphical")
+        # node labels are integers 0,...,n-1
+        self.m = sum(self.degree) / 2.0  # number of edges
+        try:
+            self.dmax = max(self.degree)  # maximum degree
+        except ValueError:
+            self.dmax = 0
+
+    def generate(self):
+        # remaining_degree is mapping from int->remaining degree
+        self.remaining_degree = dict(enumerate(self.degree))
+        # add all nodes to make sure we get isolated nodes
+        self.graph = nx.Graph()
+        self.graph.add_nodes_from(self.remaining_degree)
+        # remove zero degree nodes
+        for n, d in list(self.remaining_degree.items()):
+            if d == 0:
+                del self.remaining_degree[n]
+        if len(self.remaining_degree) > 0:
+            # build graph in three phases according to how many unmatched edges
+            self.phase1()
+            self.phase2()
+            self.phase3()
+        return self.graph
+
+    def update_remaining(self, u, v, aux_graph=None):
+        # decrement remaining nodes, modify auxiliary graph if in phase3
+        if aux_graph is not None:
+            # remove edges from auxiliary graph
+            aux_graph.remove_edge(u, v)
+        if self.remaining_degree[u] == 1:
+            del self.remaining_degree[u]
+            if aux_graph is not None:
+                aux_graph.remove_node(u)
+        else:
+            self.remaining_degree[u] -= 1
+        if self.remaining_degree[v] == 1:
+            del self.remaining_degree[v]
+            if aux_graph is not None:
+                aux_graph.remove_node(v)
+        else:
+            self.remaining_degree[v] -= 1
+
+    def p(self, u, v):
+        # degree probability
+        return 1 - self.degree[u] * self.degree[v] / (4.0 * self.m)
+
+    def q(self, u, v):
+        # remaining degree probability
+        norm = max(self.remaining_degree.values()) ** 2
+        return self.remaining_degree[u] * self.remaining_degree[v] / norm
+
+    def suitable_edge(self):
+        """Returns True if and only if an arbitrary remaining node can
+        potentially be joined with some other remaining node.
+
+        """
+        nodes = iter(self.remaining_degree)
+        u = next(nodes)
+        return any(v not in self.graph[u] for v in nodes)
+
+    def phase1(self):
+        # choose node pairs from (degree) weighted distribution
+        rem_deg = self.remaining_degree
+        while sum(rem_deg.values()) >= 2 * self.dmax**2:
+            u, v = sorted(random_weighted_sample(rem_deg, 2, self.rng))
+            if self.graph.has_edge(u, v):
+                continue
+            if self.rng.random() < self.p(u, v):  # accept edge
+                self.graph.add_edge(u, v)
+                self.update_remaining(u, v)
+
+    def phase2(self):
+        # choose remaining nodes uniformly at random and use rejection sampling
+        remaining_deg = self.remaining_degree
+        rng = self.rng
+        while len(remaining_deg) >= 2 * self.dmax:
+            while True:
+                u, v = sorted(rng.sample(list(remaining_deg.keys()), 2))
+                if self.graph.has_edge(u, v):
+                    continue
+                if rng.random() < self.q(u, v):
+                    break
+            if rng.random() < self.p(u, v):  # accept edge
+                self.graph.add_edge(u, v)
+                self.update_remaining(u, v)
+
+    def phase3(self):
+        # build potential remaining edges and choose with rejection sampling
+        potential_edges = combinations(self.remaining_degree, 2)
+        # build auxiliary graph of potential edges not already in graph
+        H = nx.Graph(
+            [(u, v) for (u, v) in potential_edges if not self.graph.has_edge(u, v)]
+        )
+        rng = self.rng
+        while self.remaining_degree:
+            if not self.suitable_edge():
+                raise nx.NetworkXUnfeasible("no suitable edges left")
+            while True:
+                u, v = sorted(rng.choice(list(H.edges())))
+                if rng.random() < self.q(u, v):
+                    break
+            if rng.random() < self.p(u, v):  # accept edge
+                self.graph.add_edge(u, v)
+                self.update_remaining(u, v, aux_graph=H)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/directed.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/directed.py
new file mode 100644
index 0000000000000000000000000000000000000000..759ce2f9d9106d8dbb6c5ca001391c7be74b636a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/directed.py
@@ -0,0 +1,572 @@
+"""
+Generators for some directed graphs, including growing network (GN) graphs and
+scale-free graphs.
+
+"""
+
+import numbers
+from collections import Counter
+
+import networkx as nx
+from networkx.generators.classic import empty_graph
+from networkx.utils import (
+    discrete_sequence,
+    np_random_state,
+    py_random_state,
+    weighted_choice,
+)
+
+__all__ = [
+    "gn_graph",
+    "gnc_graph",
+    "gnr_graph",
+    "random_k_out_graph",
+    "scale_free_graph",
+]
+
+
+@py_random_state(3)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def gn_graph(n, kernel=None, create_using=None, seed=None):
+    """Returns the growing network (GN) digraph with `n` nodes.
+
+    The GN graph is built by adding nodes one at a time with a link to one
+    previously added node.  The target node for the link is chosen with
+    probability based on degree.  The default attachment kernel is a linear
+    function of the degree of a node.
+
+    The graph is always a (directed) tree.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes for the generated graph.
+    kernel : function
+        The attachment kernel.
+    create_using : NetworkX graph constructor, optional (default DiGraph)
+        Graph type to create. If graph instance, then cleared before populated.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Examples
+    --------
+    To create the undirected GN graph, use the :meth:`~DiGraph.to_directed`
+    method::
+
+    >>> D = nx.gn_graph(10)  # the GN graph
+    >>> G = D.to_undirected()  # the undirected version
+
+    To specify an attachment kernel, use the `kernel` keyword argument::
+
+    >>> D = nx.gn_graph(10, kernel=lambda x: x**1.5)  # A_k = k^1.5
+
+    References
+    ----------
+    .. [1] P. L. Krapivsky and S. Redner,
+           Organization of Growing Random Networks,
+           Phys. Rev. E, 63, 066123, 2001.
+    """
+    G = empty_graph(1, create_using, default=nx.DiGraph)
+    if not G.is_directed():
+        raise nx.NetworkXError("create_using must indicate a Directed Graph")
+
+    if kernel is None:
+
+        def kernel(x):
+            return x
+
+    if n == 1:
+        return G
+
+    G.add_edge(1, 0)  # get started
+    ds = [1, 1]  # degree sequence
+
+    for source in range(2, n):
+        # compute distribution from kernel and degree
+        dist = [kernel(d) for d in ds]
+        # choose target from discrete distribution
+        target = discrete_sequence(1, distribution=dist, seed=seed)[0]
+        G.add_edge(source, target)
+        ds.append(1)  # the source has only one link (degree one)
+        ds[target] += 1  # add one to the target link degree
+    return G
+
+
+@py_random_state(3)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def gnr_graph(n, p, create_using=None, seed=None):
+    """Returns the growing network with redirection (GNR) digraph with `n`
+    nodes and redirection probability `p`.
+
+    The GNR graph is built by adding nodes one at a time with a link to one
+    previously added node.  The previous target node is chosen uniformly at
+    random.  With probability `p` the link is instead "redirected" to the
+    successor node of the target.
+
+    The graph is always a (directed) tree.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes for the generated graph.
+    p : float
+        The redirection probability.
+    create_using : NetworkX graph constructor, optional (default DiGraph)
+        Graph type to create. If graph instance, then cleared before populated.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Examples
+    --------
+    To create the undirected GNR graph, use the :meth:`~DiGraph.to_directed`
+    method::
+
+    >>> D = nx.gnr_graph(10, 0.5)  # the GNR graph
+    >>> G = D.to_undirected()  # the undirected version
+
+    References
+    ----------
+    .. [1] P. L. Krapivsky and S. Redner,
+           Organization of Growing Random Networks,
+           Phys. Rev. E, 63, 066123, 2001.
+    """
+    G = empty_graph(1, create_using, default=nx.DiGraph)
+    if not G.is_directed():
+        raise nx.NetworkXError("create_using must indicate a Directed Graph")
+
+    if n == 1:
+        return G
+
+    for source in range(1, n):
+        target = seed.randrange(0, source)
+        if seed.random() < p and target != 0:
+            target = next(G.successors(target))
+        G.add_edge(source, target)
+    return G
+
+
+@py_random_state(2)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def gnc_graph(n, create_using=None, seed=None):
+    """Returns the growing network with copying (GNC) digraph with `n` nodes.
+
+    The GNC graph is built by adding nodes one at a time with a link to one
+    previously added node (chosen uniformly at random) and to all of that
+    node's successors.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes for the generated graph.
+    create_using : NetworkX graph constructor, optional (default DiGraph)
+        Graph type to create. If graph instance, then cleared before populated.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    References
+    ----------
+    .. [1] P. L. Krapivsky and S. Redner,
+           Network Growth by Copying,
+           Phys. Rev. E, 71, 036118, 2005k.},
+    """
+    G = empty_graph(1, create_using, default=nx.DiGraph)
+    if not G.is_directed():
+        raise nx.NetworkXError("create_using must indicate a Directed Graph")
+
+    if n == 1:
+        return G
+
+    for source in range(1, n):
+        target = seed.randrange(0, source)
+        for succ in G.successors(target):
+            G.add_edge(source, succ)
+        G.add_edge(source, target)
+    return G
+
+
+@py_random_state(6)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def scale_free_graph(
+    n,
+    alpha=0.41,
+    beta=0.54,
+    gamma=0.05,
+    delta_in=0.2,
+    delta_out=0,
+    seed=None,
+    initial_graph=None,
+):
+    """Returns a scale-free directed graph.
+
+    Parameters
+    ----------
+    n : integer
+        Number of nodes in graph
+    alpha : float
+        Probability for adding a new node connected to an existing node
+        chosen randomly according to the in-degree distribution.
+    beta : float
+        Probability for adding an edge between two existing nodes.
+        One existing node is chosen randomly according the in-degree
+        distribution and the other chosen randomly according to the out-degree
+        distribution.
+    gamma : float
+        Probability for adding a new node connected to an existing node
+        chosen randomly according to the out-degree distribution.
+    delta_in : float
+        Bias for choosing nodes from in-degree distribution.
+    delta_out : float
+        Bias for choosing nodes from out-degree distribution.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    initial_graph : MultiDiGraph instance, optional
+        Build the scale-free graph starting from this initial MultiDiGraph,
+        if provided.
+
+    Returns
+    -------
+    MultiDiGraph
+
+    Examples
+    --------
+    Create a scale-free graph on one hundred nodes::
+
+    >>> G = nx.scale_free_graph(100)
+
+    Notes
+    -----
+    The sum of `alpha`, `beta`, and `gamma` must be 1.
+
+    References
+    ----------
+    .. [1] B. Bollobás, C. Borgs, J. Chayes, and O. Riordan,
+           Directed scale-free graphs,
+           Proceedings of the fourteenth annual ACM-SIAM Symposium on
+           Discrete Algorithms, 132--139, 2003.
+    """
+
+    def _choose_node(candidates, node_list, delta):
+        if delta > 0:
+            bias_sum = len(node_list) * delta
+            p_delta = bias_sum / (bias_sum + len(candidates))
+            if seed.random() < p_delta:
+                return seed.choice(node_list)
+        return seed.choice(candidates)
+
+    if initial_graph is not None and hasattr(initial_graph, "_adj"):
+        if not isinstance(initial_graph, nx.MultiDiGraph):
+            raise nx.NetworkXError("initial_graph must be a MultiDiGraph.")
+        G = initial_graph
+    else:
+        # Start with 3-cycle
+        G = nx.MultiDiGraph([(0, 1), (1, 2), (2, 0)])
+
+    if alpha <= 0:
+        raise ValueError("alpha must be > 0.")
+    if beta <= 0:
+        raise ValueError("beta must be > 0.")
+    if gamma <= 0:
+        raise ValueError("gamma must be > 0.")
+
+    if abs(alpha + beta + gamma - 1.0) >= 1e-9:
+        raise ValueError("alpha+beta+gamma must equal 1.")
+
+    if delta_in < 0:
+        raise ValueError("delta_in must be >= 0.")
+
+    if delta_out < 0:
+        raise ValueError("delta_out must be >= 0.")
+
+    # pre-populate degree states
+    vs = sum((count * [idx] for idx, count in G.out_degree()), [])
+    ws = sum((count * [idx] for idx, count in G.in_degree()), [])
+
+    # pre-populate node state
+    node_list = list(G.nodes())
+
+    # see if there already are number-based nodes
+    numeric_nodes = [n for n in node_list if isinstance(n, numbers.Number)]
+    if len(numeric_nodes) > 0:
+        # set cursor for new nodes appropriately
+        cursor = max(int(n.real) for n in numeric_nodes) + 1
+    else:
+        # or start at zero
+        cursor = 0
+
+    while len(G) < n:
+        r = seed.random()
+
+        # random choice in alpha,beta,gamma ranges
+        if r < alpha:
+            # alpha
+            # add new node v
+            v = cursor
+            cursor += 1
+            # also add to node state
+            node_list.append(v)
+            # choose w according to in-degree and delta_in
+            w = _choose_node(ws, node_list, delta_in)
+
+        elif r < alpha + beta:
+            # beta
+            # choose v according to out-degree and delta_out
+            v = _choose_node(vs, node_list, delta_out)
+            # choose w according to in-degree and delta_in
+            w = _choose_node(ws, node_list, delta_in)
+
+        else:
+            # gamma
+            # choose v according to out-degree and delta_out
+            v = _choose_node(vs, node_list, delta_out)
+            # add new node w
+            w = cursor
+            cursor += 1
+            # also add to node state
+            node_list.append(w)
+
+        # add edge to graph
+        G.add_edge(v, w)
+
+        # update degree states
+        vs.append(v)
+        ws.append(w)
+
+    return G
+
+
+@py_random_state(4)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def random_uniform_k_out_graph(n, k, self_loops=True, with_replacement=True, seed=None):
+    """Returns a random `k`-out graph with uniform attachment.
+
+    A random `k`-out graph with uniform attachment is a multidigraph
+    generated by the following algorithm. For each node *u*, choose
+    `k` nodes *v* uniformly at random (with replacement). Add a
+    directed edge joining *u* to *v*.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes in the returned graph.
+
+    k : int
+        The out-degree of each node in the returned graph.
+
+    self_loops : bool
+        If True, self-loops are allowed when generating the graph.
+
+    with_replacement : bool
+        If True, neighbors are chosen with replacement and the
+        returned graph will be a directed multigraph. Otherwise,
+        neighbors are chosen without replacement and the returned graph
+        will be a directed graph.
+
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    NetworkX graph
+        A `k`-out-regular directed graph generated according to the
+        above algorithm. It will be a multigraph if and only if
+        `with_replacement` is True.
+
+    Raises
+    ------
+    ValueError
+        If `with_replacement` is False and `k` is greater than
+        `n`.
+
+    See also
+    --------
+    random_k_out_graph
+
+    Notes
+    -----
+    The return digraph or multidigraph may not be strongly connected, or
+    even weakly connected.
+
+    If `with_replacement` is True, this function is similar to
+    :func:`random_k_out_graph`, if that function had parameter `alpha`
+    set to positive infinity.
+
+    """
+    if with_replacement:
+        create_using = nx.MultiDiGraph()
+
+        def sample(v, nodes):
+            if not self_loops:
+                nodes = nodes - {v}
+            return (seed.choice(list(nodes)) for i in range(k))
+
+    else:
+        create_using = nx.DiGraph()
+
+        def sample(v, nodes):
+            if not self_loops:
+                nodes = nodes - {v}
+            return seed.sample(list(nodes), k)
+
+    G = nx.empty_graph(n, create_using)
+    nodes = set(G)
+    for u in G:
+        G.add_edges_from((u, v) for v in sample(u, nodes))
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def random_k_out_graph(n, k, alpha, self_loops=True, seed=None):
+    """Returns a random `k`-out graph with preferential attachment.
+
+    .. versionchanged:: 3.5
+       Different implementations will be used based on whether NumPy is
+       available. See Notes for details.
+
+    A random `k`-out graph with preferential attachment is a
+    multidigraph generated by the following algorithm.
+
+    1. Begin with an empty digraph, and initially set each node to have
+       weight `alpha`.
+    2. Choose a node `u` with out-degree less than `k` uniformly at
+       random.
+    3. Choose a node `v` from with probability proportional to its
+       weight.
+    4. Add a directed edge from `u` to `v`, and increase the weight
+       of `v` by one.
+    5. If each node has out-degree `k`, halt, otherwise repeat from
+       step 2.
+
+    For more information on this model of random graph, see [1]_.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes in the returned graph.
+
+    k : int
+        The out-degree of each node in the returned graph.
+
+    alpha : float
+        A positive :class:`float` representing the initial weight of
+        each vertex. A higher number means that in step 3 above, nodes
+        will be chosen more like a true uniformly random sample, and a
+        lower number means that nodes are more likely to be chosen as
+        their in-degree increases. If this parameter is not positive, a
+        :exc:`ValueError` is raised.
+
+    self_loops : bool
+        If True, self-loops are allowed when generating the graph.
+
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    :class:`~networkx.classes.MultiDiGraph`
+        A `k`-out-regular multidigraph generated according to the above
+        algorithm.
+
+    Raises
+    ------
+    ValueError
+        If `alpha` is not positive.
+
+    Notes
+    -----
+    The returned multidigraph may not be strongly connected, or even
+    weakly connected.
+
+    `random_k_out_graph` has two implementations: an array-based formulation that
+    uses `numpy` (``_random_k_out_graph_numpy``), and a pure-Python
+    implementation (``_random_k_out_graph_python``).
+    The NumPy implementation is more performant, especially for large `n`, and is
+    therefore used by default. If NumPy is not installed in the environment,
+    then the pure Python implementation is executed.
+    However, you can explicitly control which implementation is executed by directly
+    calling the corresponding function::
+
+        # Use numpy if available, else Python
+        nx.random_k_out_graph(1000, 5, alpha=1)
+
+        # Use the numpy-based implementation (raises ImportError if numpy not installed)
+        nx.generators.directed._random_k_out_graph_numpy(1000, 5, alpha=1)
+
+        # Use the Python-based implementation
+        nx.generators.directed._random_k_out_graph_python(1000, 5, alpha=1)
+
+    References
+    ----------
+    .. [1] Peterson, Nicholas R., and Boris Pittel.
+       "Distance between two random `k`-out digraphs, with and without preferential attachment."
+       arXiv preprint arXiv:1311.5961 (2013) .
+
+    """
+    if alpha < 0:
+        raise ValueError("alpha must be positive")
+    try:  # Use numpy if available, otherwise fall back to pure Python implementation
+        return _random_k_out_graph_numpy(n, k, alpha, self_loops, seed)
+    except ImportError:
+        return _random_k_out_graph_python(n, k, alpha, self_loops, seed)
+
+
+@np_random_state(4)
+def _random_k_out_graph_numpy(n, k, alpha, self_loops=True, seed=None):
+    import numpy as np
+
+    G = nx.empty_graph(n, create_using=nx.MultiDiGraph)
+    nodes = np.arange(n)
+    remaining_mask = np.full(n, True)
+    weights = np.full(n, alpha)
+    total_weight = n * alpha
+    out_strengths = np.zeros(n)
+
+    for i in range(k * n):
+        u = seed.choice(nodes[remaining_mask])
+
+        if self_loops:
+            v = seed.choice(nodes, p=weights / total_weight)
+        else:  # Ignore weight of u when selecting v
+            u_weight = weights[u]
+            weights[u] = 0
+            v = seed.choice(nodes, p=weights / (total_weight - u_weight))
+            weights[u] = u_weight
+
+        G.add_edge(u.item(), v.item())
+        weights[v] += 1
+        total_weight += 1
+        out_strengths[u] += 1
+        if out_strengths[u] == k:
+            remaining_mask[u] = False
+    return G
+
+
+@py_random_state(4)
+def _random_k_out_graph_python(n, k, alpha, self_loops=True, seed=None):
+    G = nx.empty_graph(n, create_using=nx.MultiDiGraph)
+    weights = Counter({v: alpha for v in G})
+    out_strengths = Counter({v: 0 for v in G})
+
+    for i in range(k * n):
+        u = seed.choice(list(out_strengths.keys()))
+        # If self-loops are not allowed, make the source node `u` have
+        # weight zero.
+        if not self_loops:
+            uweight = weights.pop(u)
+
+        v = weighted_choice(weights, seed=seed)
+
+        if not self_loops:
+            weights[u] = uweight
+
+        G.add_edge(u, v)
+        weights[v] += 1
+        out_strengths[u] += 1
+        if out_strengths[u] == k:
+            out_strengths.pop(u)
+    return G
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/duplication.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/duplication.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c3ade63f58237eeb927ff631b25f025d7d83fc1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/duplication.py
@@ -0,0 +1,174 @@
+"""Functions for generating graphs based on the "duplication" method.
+
+These graph generators start with a small initial graph then duplicate
+nodes and (partially) duplicate their edges. These functions are
+generally inspired by biological networks.
+
+"""
+
+import networkx as nx
+from networkx.exception import NetworkXError
+from networkx.utils import py_random_state
+from networkx.utils.misc import check_create_using
+
+__all__ = ["partial_duplication_graph", "duplication_divergence_graph"]
+
+
+@py_random_state(4)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def partial_duplication_graph(N, n, p, q, seed=None, *, create_using=None):
+    """Returns a random graph using the partial duplication model.
+
+    Parameters
+    ----------
+    N : int
+        The total number of nodes in the final graph.
+
+    n : int
+        The number of nodes in the initial clique.
+
+    p : float
+        The probability of joining each neighbor of a node to the
+        duplicate node. Must be a number in the between zero and one,
+        inclusive.
+
+    q : float
+        The probability of joining the source node to the duplicate
+        node. Must be a number in the between zero and one, inclusive.
+
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    create_using : Graph constructor, optional (default=nx.Graph)
+        Graph type to create. If graph instance, then cleared before populated.
+        Multigraph and directed types are not supported and raise a ``NetworkXError``.
+
+    Notes
+    -----
+    A graph of nodes is grown by creating a fully connected graph
+    of size `n`. The following procedure is then repeated until
+    a total of `N` nodes have been reached.
+
+    1. A random node, *u*, is picked and a new node, *v*, is created.
+    2. For each neighbor of *u* an edge from the neighbor to *v* is created
+       with probability `p`.
+    3. An edge from *u* to *v* is created with probability `q`.
+
+    This algorithm appears in [1].
+
+    This implementation allows the possibility of generating
+    disconnected graphs.
+
+    References
+    ----------
+    .. [1] Knudsen Michael, and Carsten Wiuf. "A Markov chain approach to
+           randomly grown graphs." Journal of Applied Mathematics 2008.
+           
+
+    """
+    create_using = check_create_using(create_using, directed=False, multigraph=False)
+    if p < 0 or p > 1 or q < 0 or q > 1:
+        msg = "partial duplication graph must have 0 <= p, q <= 1."
+        raise NetworkXError(msg)
+    if n > N:
+        raise NetworkXError("partial duplication graph must have n <= N.")
+
+    G = nx.complete_graph(n, create_using)
+    for new_node in range(n, N):
+        # Pick a random vertex, u, already in the graph.
+        src_node = seed.randint(0, new_node - 1)
+
+        # Add a new vertex, v, to the graph.
+        G.add_node(new_node)
+
+        # For each neighbor of u...
+        for nbr_node in list(nx.all_neighbors(G, src_node)):
+            # Add the neighbor to v with probability p.
+            if seed.random() < p:
+                G.add_edge(new_node, nbr_node)
+
+        # Join v and u with probability q.
+        if seed.random() < q:
+            G.add_edge(new_node, src_node)
+    return G
+
+
+@py_random_state(2)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def duplication_divergence_graph(n, p, seed=None, *, create_using=None):
+    """Returns an undirected graph using the duplication-divergence model.
+
+    A graph of `n` nodes is created by duplicating the initial nodes
+    and retaining edges incident to the original nodes with a retention
+    probability `p`.
+
+    Parameters
+    ----------
+    n : int
+        The desired number of nodes in the graph.
+    p : float
+        The probability for retaining the edge of the replicated node.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    create_using : Graph constructor, optional (default=nx.Graph)
+        Graph type to create. If graph instance, then cleared before populated.
+        Multigraph and directed types are not supported and raise a ``NetworkXError``.
+
+    Returns
+    -------
+    G : Graph
+
+    Raises
+    ------
+    NetworkXError
+        If `p` is not a valid probability.
+        If `n` is less than 2.
+
+    Notes
+    -----
+    This algorithm appears in [1].
+
+    This implementation disallows the possibility of generating
+    disconnected graphs.
+
+    References
+    ----------
+    .. [1] I. Ispolatov, P. L. Krapivsky, A. Yuryev,
+       "Duplication-divergence model of protein interaction network",
+       Phys. Rev. E, 71, 061911, 2005.
+
+    """
+    if p > 1 or p < 0:
+        msg = f"NetworkXError p={p} is not in [0,1]."
+        raise nx.NetworkXError(msg)
+    if n < 2:
+        msg = "n must be greater than or equal to 2"
+        raise nx.NetworkXError(msg)
+
+    create_using = check_create_using(create_using, directed=False, multigraph=False)
+    G = nx.empty_graph(create_using=create_using)
+
+    # Initialize the graph with two connected nodes.
+    G.add_edge(0, 1)
+    i = 2
+    while i < n:
+        # Choose a random node from current graph to duplicate.
+        random_node = seed.choice(list(G))
+        # Make the replica.
+        G.add_node(i)
+        # flag indicates whether at least one edge is connected on the replica.
+        flag = False
+        for nbr in G.neighbors(random_node):
+            if seed.random() < p:
+                # Link retention step.
+                G.add_edge(i, nbr)
+                flag = True
+        if not flag:
+            # Delete replica if no edges retained.
+            G.remove_node(i)
+        else:
+            # Successful duplication.
+            i += 1
+    return G
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/ego.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/ego.py
new file mode 100644
index 0000000000000000000000000000000000000000..91ff3e3fe8573e0764094d030a8656fafa59c929
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/ego.py
@@ -0,0 +1,66 @@
+"""
+Ego graph.
+"""
+
+__all__ = ["ego_graph"]
+
+import networkx as nx
+
+
+@nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
+def ego_graph(G, n, radius=1, center=True, undirected=False, distance=None):
+    """Returns induced subgraph of neighbors centered at node n within
+    a given radius.
+
+    Parameters
+    ----------
+    G : graph
+      A NetworkX Graph or DiGraph
+
+    n : node
+      A single node
+
+    radius : number, optional
+      Include all neighbors of distance<=radius from n.
+
+    center : bool, optional
+      If False, do not include center node in graph
+
+    undirected : bool, optional
+      If True use both in- and out-neighbors of directed graphs.
+
+    distance : key, optional
+      Use specified edge data key as distance.  For example, setting
+      distance='weight' will use the edge weight to measure the
+      distance from the node n.
+
+    Notes
+    -----
+    For directed graphs D this produces the "out" neighborhood
+    or successors.  If you want the neighborhood of predecessors
+    first reverse the graph with D.reverse().  If you want both
+    directions use the keyword argument undirected=True.
+
+    Node, edge, and graph attributes are copied to the returned subgraph.
+    """
+    if undirected:
+        if distance is not None:
+            sp, _ = nx.single_source_dijkstra(
+                G.to_undirected(), n, cutoff=radius, weight=distance
+            )
+        else:
+            sp = dict(
+                nx.single_source_shortest_path_length(
+                    G.to_undirected(), n, cutoff=radius
+                )
+            )
+    else:
+        if distance is not None:
+            sp, _ = nx.single_source_dijkstra(G, n, cutoff=radius, weight=distance)
+        else:
+            sp = nx.single_source_shortest_path_length(G, n, cutoff=radius)
+
+    H = G.subgraph(sp).copy()
+    if not center:
+        H.remove_node(n)
+    return H
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/expanders.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/expanders.py
new file mode 100644
index 0000000000000000000000000000000000000000..a7d6c21f9452f1e8d584864a010ab724cac2f048
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/expanders.py
@@ -0,0 +1,499 @@
+"""Provides explicit constructions of expander graphs."""
+
+import itertools
+
+import networkx as nx
+
+__all__ = [
+    "margulis_gabber_galil_graph",
+    "chordal_cycle_graph",
+    "paley_graph",
+    "maybe_regular_expander",
+    "maybe_regular_expander_graph",
+    "is_regular_expander",
+    "random_regular_expander_graph",
+]
+
+
+# Other discrete torus expanders can be constructed by using the following edge
+# sets. For more information, see Chapter 4, "Expander Graphs", in
+# "Pseudorandomness", by Salil Vadhan.
+#
+# For a directed expander, add edges from (x, y) to:
+#
+#     (x, y),
+#     ((x + 1) % n, y),
+#     (x, (y + 1) % n),
+#     (x, (x + y) % n),
+#     (-y % n, x)
+#
+# For an undirected expander, add the reverse edges.
+#
+# Also appearing in the paper of Gabber and Galil:
+#
+#     (x, y),
+#     (x, (x + y) % n),
+#     (x, (x + y + 1) % n),
+#     ((x + y) % n, y),
+#     ((x + y + 1) % n, y)
+#
+# and:
+#
+#     (x, y),
+#     ((x + 2*y) % n, y),
+#     ((x + (2*y + 1)) % n, y),
+#     ((x + (2*y + 2)) % n, y),
+#     (x, (y + 2*x) % n),
+#     (x, (y + (2*x + 1)) % n),
+#     (x, (y + (2*x + 2)) % n),
+#
+@nx._dispatchable(graphs=None, returns_graph=True)
+def margulis_gabber_galil_graph(n, create_using=None):
+    r"""Returns the Margulis-Gabber-Galil undirected MultiGraph on `n^2` nodes.
+
+    The undirected MultiGraph is regular with degree `8`. Nodes are integer
+    pairs. The second-largest eigenvalue of the adjacency matrix of the graph
+    is at most `5 \sqrt{2}`, regardless of `n`.
+
+    Parameters
+    ----------
+    n : int
+        Determines the number of nodes in the graph: `n^2`.
+    create_using : NetworkX graph constructor, optional (default MultiGraph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : graph
+        The constructed undirected multigraph.
+
+    Raises
+    ------
+    NetworkXError
+        If the graph is directed or not a multigraph.
+
+    """
+    G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
+    if G.is_directed() or not G.is_multigraph():
+        msg = "`create_using` must be an undirected multigraph."
+        raise nx.NetworkXError(msg)
+
+    for x, y in itertools.product(range(n), repeat=2):
+        for u, v in (
+            ((x + 2 * y) % n, y),
+            ((x + (2 * y + 1)) % n, y),
+            (x, (y + 2 * x) % n),
+            (x, (y + (2 * x + 1)) % n),
+        ):
+            G.add_edge((x, y), (u, v))
+    G.graph["name"] = f"margulis_gabber_galil_graph({n})"
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def chordal_cycle_graph(p, create_using=None):
+    """Returns the chordal cycle graph on `p` nodes.
+
+    The returned graph is a cycle graph on `p` nodes with chords joining each
+    vertex `x` to its inverse modulo `p`. This graph is a (mildly explicit)
+    3-regular expander [1]_.
+
+    `p` *must* be a prime number.
+
+    Parameters
+    ----------
+    p : a prime number
+
+        The number of vertices in the graph. This also indicates where the
+        chordal edges in the cycle will be created.
+
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : graph
+        The constructed undirected multigraph.
+
+    Raises
+    ------
+    NetworkXError
+
+        If `create_using` indicates directed or not a multigraph.
+
+    References
+    ----------
+
+    .. [1] Theorem 4.4.2 in A. Lubotzky. "Discrete groups, expanding graphs and
+           invariant measures", volume 125 of Progress in Mathematics.
+           Birkhäuser Verlag, Basel, 1994.
+
+    """
+    G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
+    if G.is_directed() or not G.is_multigraph():
+        msg = "`create_using` must be an undirected multigraph."
+        raise nx.NetworkXError(msg)
+
+    for x in range(p):
+        left = (x - 1) % p
+        right = (x + 1) % p
+        # Here we apply Fermat's Little Theorem to compute the multiplicative
+        # inverse of x in Z/pZ. By Fermat's Little Theorem,
+        #
+        #     x^p = x (mod p)
+        #
+        # Therefore,
+        #
+        #     x * x^(p - 2) = 1 (mod p)
+        #
+        # The number 0 is a special case: we just let its inverse be itself.
+        chord = pow(x, p - 2, p) if x > 0 else 0
+        for y in (left, right, chord):
+            G.add_edge(x, y)
+    G.graph["name"] = f"chordal_cycle_graph({p})"
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def paley_graph(p, create_using=None):
+    r"""Returns the Paley $\frac{(p-1)}{2}$ -regular graph on $p$ nodes.
+
+    The returned graph is a graph on $\mathbb{Z}/p\mathbb{Z}$ with edges between $x$ and $y$
+    if and only if $x-y$ is a nonzero square in $\mathbb{Z}/p\mathbb{Z}$.
+
+    If $p \equiv 1  \pmod 4$, $-1$ is a square in
+    $\mathbb{Z}/p\mathbb{Z}$ and therefore $x-y$ is a square if and
+    only if $y-x$ is also a square, i.e the edges in the Paley graph are symmetric.
+
+    If $p \equiv 3 \pmod 4$, $-1$ is not a square in $\mathbb{Z}/p\mathbb{Z}$
+    and therefore either $x-y$ or $y-x$ is a square in $\mathbb{Z}/p\mathbb{Z}$ but not both.
+
+    Note that a more general definition of Paley graphs extends this construction
+    to graphs over $q=p^n$ vertices, by using the finite field $F_q$ instead of
+    $\mathbb{Z}/p\mathbb{Z}$.
+    This construction requires to compute squares in general finite fields and is
+    not what is implemented here (i.e `paley_graph(25)` does not return the true
+    Paley graph associated with $5^2$).
+
+    Parameters
+    ----------
+    p : int, an odd prime number.
+
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : graph
+        The constructed directed graph.
+
+    Raises
+    ------
+    NetworkXError
+        If the graph is a multigraph.
+
+    References
+    ----------
+    Chapter 13 in B. Bollobas, Random Graphs. Second edition.
+    Cambridge Studies in Advanced Mathematics, 73.
+    Cambridge University Press, Cambridge (2001).
+    """
+    G = nx.empty_graph(0, create_using, default=nx.DiGraph)
+    if G.is_multigraph():
+        msg = "`create_using` cannot be a multigraph."
+        raise nx.NetworkXError(msg)
+
+    # Compute the squares in Z/pZ.
+    # Make it a set to uniquify (there are exactly (p-1)/2 squares in Z/pZ
+    # when is prime).
+    square_set = {(x**2) % p for x in range(1, p) if (x**2) % p != 0}
+
+    for x in range(p):
+        for x2 in square_set:
+            G.add_edge(x, (x + x2) % p)
+    G.graph["name"] = f"paley({p})"
+    return G
+
+
+@nx.utils.decorators.np_random_state("seed")
+@nx._dispatchable(graphs=None, returns_graph=True)
+def maybe_regular_expander_graph(n, d, *, create_using=None, max_tries=100, seed=None):
+    r"""Utility for creating a random regular expander.
+
+    Returns a random $d$-regular graph on $n$ nodes which is an expander
+    graph with very good probability.
+
+    Parameters
+    ----------
+    n : int
+      The number of nodes.
+    d : int
+      The degree of each node.
+    create_using : Graph Instance or Constructor
+      Indicator of type of graph to return.
+      If a Graph-type instance, then clear and use it.
+      If a constructor, call it to create an empty graph.
+      Use the Graph constructor by default.
+    max_tries : int. (default: 100)
+      The number of allowed loops when generating each independent cycle
+    seed : (default: None)
+      Seed used to set random number generation state. See :ref`Randomness`.
+
+    Notes
+    -----
+    The nodes are numbered from $0$ to $n - 1$.
+
+    The graph is generated by taking $d / 2$ random independent cycles.
+
+    Joel Friedman proved that in this model the resulting
+    graph is an expander with probability
+    $1 - O(n^{-\tau})$ where $\tau = \lceil (\sqrt{d - 1}) / 2 \rceil - 1$. [1]_
+
+    Examples
+    --------
+    >>> G = nx.maybe_regular_expander_graph(n=200, d=6, seed=8020)
+
+    Returns
+    -------
+    G : graph
+        The constructed undirected graph.
+
+    Raises
+    ------
+    NetworkXError
+        If $d % 2 != 0$ as the degree must be even.
+        If $n - 1$ is less than $ 2d $ as the graph is complete at most.
+        If max_tries is reached
+
+    See Also
+    --------
+    is_regular_expander
+    random_regular_expander_graph
+
+    References
+    ----------
+    .. [1] Joel Friedman,
+       A Proof of Alon's Second Eigenvalue Conjecture and Related Problems, 2004
+       https://arxiv.org/abs/cs/0405020
+
+    """
+
+    import numpy as np
+
+    if n < 1:
+        raise nx.NetworkXError("n must be a positive integer")
+
+    if not (d >= 2):
+        raise nx.NetworkXError("d must be greater than or equal to 2")
+
+    if not (d % 2 == 0):
+        raise nx.NetworkXError("d must be even")
+
+    if not (n - 1 >= d):
+        raise nx.NetworkXError(
+            f"Need n-1>= d to have room for {d // 2} independent cycles with {n} nodes"
+        )
+
+    G = nx.empty_graph(n, create_using)
+
+    if n < 2:
+        return G
+
+    cycles = []
+    edges = set()
+
+    # Create d / 2 cycles
+    for i in range(d // 2):
+        iterations = max_tries
+        # Make sure the cycles are independent to have a regular graph
+        while len(edges) != (i + 1) * n:
+            iterations -= 1
+            # Faster than random.permutation(n) since there are only
+            # (n-1)! distinct cycles against n! permutations of size n
+            cycle = seed.permutation(n - 1).tolist()
+            cycle.append(n - 1)
+
+            new_edges = {
+                (u, v)
+                for u, v in nx.utils.pairwise(cycle, cyclic=True)
+                if (u, v) not in edges and (v, u) not in edges
+            }
+            # If the new cycle has no edges in common with previous cycles
+            # then add it to the list otherwise try again
+            if len(new_edges) == n:
+                cycles.append(cycle)
+                edges.update(new_edges)
+
+            if iterations == 0:
+                msg = "Too many iterations in maybe_regular_expander_graph"
+                raise nx.NetworkXError(msg)
+
+    G.add_edges_from(edges)
+
+    return G
+
+
+def maybe_regular_expander(n, d, *, create_using=None, max_tries=100, seed=None):
+    """
+    .. deprecated:: 3.6
+       `maybe_regular_expander` is a deprecated alias
+       for `maybe_regular_expander_graph`.
+       Use `maybe_regular_expander_graph` instead.
+    """
+    import warnings
+
+    warnings.warn(
+        "maybe_regular_expander is deprecated, "
+        "use `maybe_regular_expander_graph` instead.",
+        category=DeprecationWarning,
+        stacklevel=2,
+    )
+    return maybe_regular_expander_graph(
+        n, d, create_using=create_using, max_tries=max_tries, seed=seed
+    )
+
+
+@nx.utils.not_implemented_for("directed")
+@nx.utils.not_implemented_for("multigraph")
+@nx._dispatchable(preserve_edge_attrs={"G": {"weight": 1}})
+def is_regular_expander(G, *, epsilon=0):
+    r"""Determines whether the graph G is a regular expander. [1]_
+
+    An expander graph is a sparse graph with strong connectivity properties.
+
+    More precisely, this helper checks whether the graph is a
+    regular $(n, d, \lambda)$-expander with $\lambda$ close to
+    the Alon-Boppana bound and given by
+    $\lambda = 2 \sqrt{d - 1} + \epsilon$. [2]_
+
+    In the case where $\epsilon = 0$ then if the graph successfully passes the test
+    it is a Ramanujan graph. [3]_
+
+    A Ramanujan graph has spectral gap almost as large as possible, which makes them
+    excellent expanders.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+    epsilon : int, float, default=0
+
+    Returns
+    -------
+    bool
+        Whether the given graph is a regular $(n, d, \lambda)$-expander
+        where $\lambda = 2 \sqrt{d - 1} + \epsilon$.
+
+    Examples
+    --------
+    >>> G = nx.random_regular_expander_graph(20, 4)
+    >>> nx.is_regular_expander(G)
+    True
+
+    See Also
+    --------
+    maybe_regular_expander_graph
+    random_regular_expander_graph
+
+    References
+    ----------
+    .. [1] Expander graph, https://en.wikipedia.org/wiki/Expander_graph
+    .. [2] Alon-Boppana bound, https://en.wikipedia.org/wiki/Alon%E2%80%93Boppana_bound
+    .. [3] Ramanujan graphs, https://en.wikipedia.org/wiki/Ramanujan_graph
+
+    """
+
+    import numpy as np
+    import scipy as sp
+
+    if epsilon < 0:
+        raise nx.NetworkXError("epsilon must be non negative")
+
+    if not nx.is_regular(G):
+        return False
+
+    _, d = nx.utils.arbitrary_element(G.degree)
+
+    A = nx.adjacency_matrix(G, dtype=float)
+    lams = sp.sparse.linalg.eigsh(A, which="LM", k=2, return_eigenvectors=False)
+
+    # lambda2 is the second biggest eigenvalue
+    lambda2 = min(lams)
+
+    # Use bool() to convert numpy scalar to Python Boolean
+    return bool(abs(lambda2) < 2 * np.sqrt(d - 1) + epsilon)
+
+
+@nx.utils.decorators.np_random_state("seed")
+@nx._dispatchable(graphs=None, returns_graph=True)
+def random_regular_expander_graph(
+    n, d, *, epsilon=0, create_using=None, max_tries=100, seed=None
+):
+    r"""Returns a random regular expander graph on $n$ nodes with degree $d$.
+
+    An expander graph is a sparse graph with strong connectivity properties. [1]_
+
+    More precisely the returned graph is a $(n, d, \lambda)$-expander with
+    $\lambda = 2 \sqrt{d - 1} + \epsilon$, close to the Alon-Boppana bound. [2]_
+
+    In the case where $\epsilon = 0$ it returns a Ramanujan graph.
+    A Ramanujan graph has spectral gap almost as large as possible,
+    which makes them excellent expanders. [3]_
+
+    Parameters
+    ----------
+    n : int
+      The number of nodes.
+    d : int
+      The degree of each node.
+    epsilon : int, float, default=0
+    max_tries : int, (default: 100)
+      The number of allowed loops,
+      also used in the `maybe_regular_expander_graph` utility
+    seed : (default: None)
+      Seed used to set random number generation state. See :ref`Randomness`.
+
+    Raises
+    ------
+    NetworkXError
+        If max_tries is reached
+
+    Examples
+    --------
+    >>> G = nx.random_regular_expander_graph(20, 4)
+    >>> nx.is_regular_expander(G)
+    True
+
+    Notes
+    -----
+    This loops over `maybe_regular_expander_graph` and can be slow when
+    $n$ is too big or $\epsilon$ too small.
+
+    See Also
+    --------
+    maybe_regular_expander_graph
+    is_regular_expander
+
+    References
+    ----------
+    .. [1] Expander graph, https://en.wikipedia.org/wiki/Expander_graph
+    .. [2] Alon-Boppana bound, https://en.wikipedia.org/wiki/Alon%E2%80%93Boppana_bound
+    .. [3] Ramanujan graphs, https://en.wikipedia.org/wiki/Ramanujan_graph
+
+    """
+    G = maybe_regular_expander_graph(
+        n, d, create_using=create_using, max_tries=max_tries, seed=seed
+    )
+    iterations = max_tries
+
+    while not is_regular_expander(G, epsilon=epsilon):
+        iterations -= 1
+        G = maybe_regular_expander_graph(
+            n=n, d=d, create_using=create_using, max_tries=max_tries, seed=seed
+        )
+
+        if iterations == 0:
+            raise nx.NetworkXError(
+                "Too many iterations in random_regular_expander_graph"
+            )
+
+    return G
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/geometric.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/geometric.py
new file mode 100644
index 0000000000000000000000000000000000000000..fdd4f627b46a1f0fbd2f6cd1700aecb12549516a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/geometric.py
@@ -0,0 +1,1037 @@
+"""Generators for geometric graphs."""
+
+import math
+from bisect import bisect_left
+from itertools import accumulate, combinations, product
+
+import networkx as nx
+from networkx.utils import py_random_state
+
+__all__ = [
+    "geometric_edges",
+    "geographical_threshold_graph",
+    "navigable_small_world_graph",
+    "random_geometric_graph",
+    "soft_random_geometric_graph",
+    "thresholded_random_geometric_graph",
+    "waxman_graph",
+    "geometric_soft_configuration_graph",
+]
+
+
+@nx._dispatchable(node_attrs="pos_name")
+def geometric_edges(G, radius, p=2, *, pos_name="pos"):
+    """Returns edge list of node pairs within `radius` of each other.
+
+    Parameters
+    ----------
+    G : networkx graph
+        The graph from which to generate the edge list. The nodes in `G` should
+        have an attribute ``pos`` corresponding to the node position, which is
+        used to compute the distance to other nodes.
+    radius : scalar
+        The distance threshold. Edges are included in the edge list if the
+        distance between the two nodes is less than `radius`.
+    pos_name : string, default="pos"
+        The name of the node attribute which represents the position of each
+        node in 2D coordinates. Every node in the Graph must have this attribute.
+    p : scalar, default=2
+        The `Minkowski distance metric
+        `_ used to compute
+        distances. The default value is 2, i.e. Euclidean distance.
+
+    Returns
+    -------
+    edges : list
+        List of edges whose distances are less than `radius`
+
+    Notes
+    -----
+    Radius uses Minkowski distance metric `p`.
+    If scipy is available, `scipy.spatial.cKDTree` is used to speed computation.
+
+    Examples
+    --------
+    Create a graph with nodes that have a "pos" attribute representing 2D
+    coordinates.
+
+    >>> G = nx.Graph()
+    >>> G.add_nodes_from(
+    ...     [
+    ...         (0, {"pos": (0, 0)}),
+    ...         (1, {"pos": (3, 0)}),
+    ...         (2, {"pos": (8, 0)}),
+    ...     ]
+    ... )
+    >>> nx.geometric_edges(G, radius=1)
+    []
+    >>> nx.geometric_edges(G, radius=4)
+    [(0, 1)]
+    >>> nx.geometric_edges(G, radius=6)
+    [(0, 1), (1, 2)]
+    >>> nx.geometric_edges(G, radius=9)
+    [(0, 1), (0, 2), (1, 2)]
+    """
+    # Input validation - every node must have a "pos" attribute
+    for n, pos in G.nodes(data=pos_name):
+        if pos is None:
+            raise nx.NetworkXError(
+                f"Node {n} (and all nodes) must have a '{pos_name}' attribute."
+            )
+
+    # NOTE: See _geometric_edges for the actual implementation. The reason this
+    # is split into two functions is to avoid the overhead of input validation
+    # every time the function is called internally in one of the other
+    # geometric generators
+    return _geometric_edges(G, radius, p, pos_name)
+
+
+def _geometric_edges(G, radius, p, pos_name):
+    """
+    Implements `geometric_edges` without input validation. See `geometric_edges`
+    for complete docstring.
+    """
+    nodes_pos = G.nodes(data=pos_name)
+    try:
+        import scipy as sp
+    except ImportError:
+        # no scipy KDTree so compute by for-loop
+        radius_p = radius**p
+        edges = [
+            (u, v)
+            for (u, pu), (v, pv) in combinations(nodes_pos, 2)
+            if sum(abs(a - b) ** p for a, b in zip(pu, pv)) <= radius_p
+        ]
+        return edges
+    # scipy KDTree is available
+    nodes, coords = list(zip(*nodes_pos))
+    kdtree = sp.spatial.cKDTree(coords)  # Cannot provide generator.
+    edge_indexes = kdtree.query_pairs(radius, p)
+    edges = [(nodes[u], nodes[v]) for u, v in sorted(edge_indexes)]
+    return edges
+
+
+@py_random_state(5)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def random_geometric_graph(
+    n, radius, dim=2, pos=None, p=2, seed=None, *, pos_name="pos"
+):
+    """Returns a random geometric graph in the unit cube of dimensions `dim`.
+
+    The random geometric graph model places `n` nodes uniformly at
+    random in the unit cube. Two nodes are joined by an edge if the
+    distance between the nodes is at most `radius`.
+
+    Edges are determined using a KDTree when SciPy is available.
+    This reduces the time complexity from $O(n^2)$ to $O(n)$.
+
+    Parameters
+    ----------
+    n : int or iterable
+        Number of nodes or iterable of nodes
+    radius: float
+        Distance threshold value
+    dim : int, optional
+        Dimension of graph
+    pos : dict, optional
+        A dictionary keyed by node with node positions as values.
+    p : float, optional
+        Which Minkowski distance metric to use.  `p` has to meet the condition
+        ``1 <= p <= infinity``.
+
+        If this argument is not specified, the :math:`L^2` metric
+        (the Euclidean distance metric), p = 2 is used.
+        This should not be confused with the `p` of an Erdős-Rényi random
+        graph, which represents probability.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    pos_name : string, default="pos"
+        The name of the node attribute which represents the position
+        in 2D coordinates of the node in the returned graph.
+
+    Returns
+    -------
+    Graph
+        A random geometric graph, undirected and without self-loops.
+        Each node has a node attribute ``'pos'`` that stores the
+        position of that node in Euclidean space as provided by the
+        ``pos`` keyword argument or, if ``pos`` was not provided, as
+        generated by this function.
+
+    Examples
+    --------
+    Create a random geometric graph on twenty nodes where nodes are joined by
+    an edge if their distance is at most 0.1::
+
+    >>> G = nx.random_geometric_graph(20, 0.1)
+
+    Notes
+    -----
+    This uses a *k*-d tree to build the graph.
+
+    The `pos` keyword argument can be used to specify node positions so you
+    can create an arbitrary distribution and domain for positions.
+
+    For example, to use a 2D Gaussian distribution of node positions with mean
+    (0, 0) and standard deviation 2::
+
+    >>> import random
+    >>> n = 20
+    >>> pos = {i: (random.gauss(0, 2), random.gauss(0, 2)) for i in range(n)}
+    >>> G = nx.random_geometric_graph(n, 0.2, pos=pos)
+
+    References
+    ----------
+    .. [1] Penrose, Mathew, *Random Geometric Graphs*,
+           Oxford Studies in Probability, 5, 2003.
+
+    """
+    # TODO Is this function just a special case of the geographical
+    # threshold graph?
+    #
+    #     half_radius = {v: radius / 2 for v in n}
+    #     return geographical_threshold_graph(nodes, theta=1, alpha=1,
+    #                                         weight=half_radius)
+    #
+    G = nx.empty_graph(n)
+    # If no positions are provided, choose uniformly random vectors in
+    # Euclidean space of the specified dimension.
+    if pos is None:
+        pos = {v: [seed.random() for i in range(dim)] for v in G}
+    nx.set_node_attributes(G, pos, pos_name)
+
+    G.add_edges_from(_geometric_edges(G, radius, p, pos_name))
+    return G
+
+
+@py_random_state(6)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def soft_random_geometric_graph(
+    n, radius, dim=2, pos=None, p=2, p_dist=None, seed=None, *, pos_name="pos"
+):
+    r"""Returns a soft random geometric graph in the unit cube.
+
+    The soft random geometric graph [1] model places `n` nodes uniformly at
+    random in the unit cube in dimension `dim`. Two nodes of distance, `dist`,
+    computed by the `p`-Minkowski distance metric are joined by an edge with
+    probability `p_dist` if the computed distance metric value of the nodes
+    is at most `radius`, otherwise they are not joined.
+
+    Edges within `radius` of each other are determined using a KDTree when
+    SciPy is available. This reduces the time complexity from :math:`O(n^2)`
+    to :math:`O(n)`.
+
+    Parameters
+    ----------
+    n : int or iterable
+        Number of nodes or iterable of nodes
+    radius: float
+        Distance threshold value
+    dim : int, optional
+        Dimension of graph
+    pos : dict, optional
+        A dictionary keyed by node with node positions as values.
+    p : float, optional
+        Which Minkowski distance metric to use.
+        `p` has to meet the condition ``1 <= p <= infinity``.
+
+        If this argument is not specified, the :math:`L^2` metric
+        (the Euclidean distance metric), p = 2 is used.
+
+        This should not be confused with the `p` of an Erdős-Rényi random
+        graph, which represents probability.
+    p_dist : function, optional
+        A probability density function computing the probability of
+        connecting two nodes that are of distance, dist, computed by the
+        Minkowski distance metric. The probability density function, `p_dist`,
+        must be any function that takes the metric value as input
+        and outputs a single probability value between 0-1. The `scipy.stats`
+        package has many probability distribution functions implemented and
+        tools for custom probability distribution definitions [2], and passing
+        the .pdf method of `scipy.stats` distributions can be used here.  If the
+        probability function, `p_dist`, is not supplied, the default function
+        is an exponential distribution with rate parameter :math:`\lambda=1`.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    pos_name : string, default="pos"
+        The name of the node attribute which represents the position
+        in 2D coordinates of the node in the returned graph.
+
+    Returns
+    -------
+    Graph
+        A soft random geometric graph, undirected and without self-loops.
+        Each node has a node attribute ``'pos'`` that stores the
+        position of that node in Euclidean space as provided by the
+        ``pos`` keyword argument or, if ``pos`` was not provided, as
+        generated by this function.
+
+    Notes
+    -----
+    This uses a *k*-d tree to build the graph.
+
+    References
+    ----------
+    .. [1] Penrose, Mathew D. "Connectivity of soft random geometric graphs."
+           The Annals of Applied Probability 26.2 (2016): 986-1028.
+
+    Examples
+    --------
+    Default Graph:
+
+    >>> G = nx.soft_random_geometric_graph(50, 0.2)
+
+    Custom Graph:
+
+    The `pos` keyword argument can be used to specify node positions so you
+    can create an arbitrary distribution and domain for positions.
+
+    The `scipy.stats` package can be used to define the probability distribution
+    with the ``.pdf`` method used as `p_dist`.
+
+    For example, create a soft random geometric graph on 100 nodes using a 2D
+    Gaussian distribution of node positions with mean (0, 0) and standard deviation 2,
+    where nodes are joined by an edge with probability computed from an
+    exponential distribution with rate parameter :math:`\lambda=1` if their
+    Euclidean distance is at most 0.2.
+
+    >>> import random
+    >>> from scipy.stats import expon
+    >>> n = 100
+    >>> pos = {i: (random.gauss(0, 2), random.gauss(0, 2)) for i in range(n)}
+    >>> p_dist = lambda x: expon.pdf(x, scale=1)
+    >>> G = nx.soft_random_geometric_graph(n, 0.2, pos=pos, p_dist=p_dist)
+
+    """
+    G = nx.empty_graph(n)
+    G.name = f"soft_random_geometric_graph({n}, {radius}, {dim})"
+    # If no positions are provided, choose uniformly random vectors in
+    # Euclidean space of the specified dimension.
+    if pos is None:
+        pos = {v: [seed.random() for i in range(dim)] for v in G}
+    nx.set_node_attributes(G, pos, pos_name)
+
+    # if p_dist function not supplied the default function is an exponential
+    # distribution with rate parameter :math:`\lambda=1`.
+    if p_dist is None:
+
+        def p_dist(dist):
+            return math.exp(-dist)
+
+    def should_join(edge):
+        u, v = edge
+        dist = (sum(abs(a - b) ** p for a, b in zip(pos[u], pos[v]))) ** (1 / p)
+        return seed.random() < p_dist(dist)
+
+    G.add_edges_from(filter(should_join, _geometric_edges(G, radius, p, pos_name)))
+    return G
+
+
+@py_random_state(7)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def geographical_threshold_graph(
+    n,
+    theta,
+    dim=2,
+    pos=None,
+    weight=None,
+    metric=None,
+    p_dist=None,
+    seed=None,
+    *,
+    pos_name="pos",
+    weight_name="weight",
+):
+    r"""Returns a geographical threshold graph.
+
+    The geographical threshold graph model places $n$ nodes uniformly at
+    random in a rectangular domain.  Each node $u$ is assigned a weight
+    $w_u$. Two nodes $u$ and $v$ are joined by an edge if
+
+    .. math::
+
+       (w_u + w_v)p_{dist}(r) \ge \theta
+
+    where `r` is the distance between `u` and `v`, `p_dist` is any function of
+    `r`, and :math:`\theta` as the threshold parameter. `p_dist` is used to
+    give weight to the distance between nodes when deciding whether or not
+    they should be connected. The larger `p_dist` is, the more prone nodes
+    separated by `r` are to be connected, and vice versa.
+
+    Parameters
+    ----------
+    n : int or iterable
+        Number of nodes or iterable of nodes
+    theta: float
+        Threshold value
+    dim : int, optional
+        Dimension of graph
+    pos : dict
+        Node positions as a dictionary of tuples keyed by node.
+    weight : dict
+        Node weights as a dictionary of numbers keyed by node.
+    metric : function
+        A metric on vectors of numbers (represented as lists or
+        tuples). This must be a function that accepts two lists (or
+        tuples) as input and yields a number as output. The function
+        must also satisfy the four requirements of a `metric`_.
+        Specifically, if $d$ is the function and $x$, $y$,
+        and $z$ are vectors in the graph, then $d$ must satisfy
+
+        1. $d(x, y) \ge 0$,
+        2. $d(x, y) = 0$ if and only if $x = y$,
+        3. $d(x, y) = d(y, x)$,
+        4. $d(x, z) \le d(x, y) + d(y, z)$.
+
+        If this argument is not specified, the Euclidean distance metric is
+        used.
+
+        .. _metric: https://en.wikipedia.org/wiki/Metric_%28mathematics%29
+    p_dist : function, optional
+        Any function used to give weight to the distance between nodes when
+        deciding whether or not they should be connected. `p_dist` was
+        originally conceived as a probability density function giving the
+        probability of connecting two nodes that are of metric distance `r`
+        apart. The implementation here allows for more arbitrary definitions
+        of `p_dist` that do not need to correspond to valid probability
+        density functions. The :mod:`scipy.stats` package has many
+        probability density functions implemented and tools for custom
+        probability density definitions, and passing the ``.pdf`` method of
+        `scipy.stats` distributions can be used here. If ``p_dist=None``
+        (the default), the exponential function :math:`r^{-2}` is used.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    pos_name : string, default="pos"
+        The name of the node attribute which represents the position
+        in 2D coordinates of the node in the returned graph.
+    weight_name : string, default="weight"
+        The name of the node attribute which represents the weight
+        of the node in the returned graph.
+
+    Returns
+    -------
+    Graph
+        A random geographic threshold graph, undirected and without
+        self-loops.
+
+        Each node has a node attribute ``pos`` that stores the
+        position of that node in Euclidean space as provided by the
+        ``pos`` keyword argument or, if ``pos`` was not provided, as
+        generated by this function. Similarly, each node has a node
+        attribute ``weight`` that stores the weight of that node as
+        provided or as generated.
+
+    Examples
+    --------
+    Specify an alternate distance metric using the ``metric`` keyword
+    argument. For example, to use the `taxicab metric`_ instead of the
+    default `Euclidean metric`_::
+
+        >>> dist = lambda x, y: sum(abs(a - b) for a, b in zip(x, y))
+        >>> G = nx.geographical_threshold_graph(10, 0.1, metric=dist)
+
+    .. _taxicab metric: https://en.wikipedia.org/wiki/Taxicab_geometry
+    .. _Euclidean metric: https://en.wikipedia.org/wiki/Euclidean_distance
+
+    Notes
+    -----
+    If weights are not specified they are assigned to nodes by drawing randomly
+    from the exponential distribution with rate parameter $\lambda=1$.
+    To specify weights from a different distribution, use the `weight` keyword
+    argument::
+
+    >>> import random
+    >>> n = 20
+    >>> w = {i: random.expovariate(5.0) for i in range(n)}
+    >>> G = nx.geographical_threshold_graph(20, 50, weight=w)
+
+    If node positions are not specified they are randomly assigned from the
+    uniform distribution.
+
+    References
+    ----------
+    .. [1] Masuda, N., Miwa, H., Konno, N.:
+       Geographical threshold graphs with small-world and scale-free
+       properties.
+       Physical Review E 71, 036108 (2005)
+    .. [2]  Milan Bradonjić, Aric Hagberg and Allon G. Percus,
+       Giant component and connectivity in geographical threshold graphs,
+       in Algorithms and Models for the Web-Graph (WAW 2007),
+       Antony Bonato and Fan Chung (Eds), pp. 209--216, 2007
+    """
+    G = nx.empty_graph(n)
+    # If no weights are provided, choose them from an exponential
+    # distribution.
+    if weight is None:
+        weight = {v: seed.expovariate(1) for v in G}
+    # If no positions are provided, choose uniformly random vectors in
+    # Euclidean space of the specified dimension.
+    if pos is None:
+        pos = {v: [seed.random() for i in range(dim)] for v in G}
+    # If no distance metric is provided, use Euclidean distance.
+    if metric is None:
+        metric = math.dist
+    nx.set_node_attributes(G, weight, weight_name)
+    nx.set_node_attributes(G, pos, pos_name)
+
+    # if p_dist is not supplied, use default r^-2
+    if p_dist is None:
+
+        def p_dist(r):
+            return r**-2
+
+    # Returns ``True`` if and only if the nodes whose attributes are
+    # ``du`` and ``dv`` should be joined, according to the threshold
+    # condition.
+    def should_join(pair):
+        u, v = pair
+        u_pos, v_pos = pos[u], pos[v]
+        u_weight, v_weight = weight[u], weight[v]
+        return (u_weight + v_weight) * p_dist(metric(u_pos, v_pos)) >= theta
+
+    G.add_edges_from(filter(should_join, combinations(G, 2)))
+    return G
+
+
+@py_random_state(6)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def waxman_graph(
+    n,
+    beta=0.4,
+    alpha=0.1,
+    L=None,
+    domain=(0, 0, 1, 1),
+    metric=None,
+    seed=None,
+    *,
+    pos_name="pos",
+):
+    r"""Returns a Waxman random graph.
+
+    The Waxman random graph model places `n` nodes uniformly at random
+    in a rectangular domain. Each pair of nodes at distance `d` is
+    joined by an edge with probability
+
+    .. math::
+            p = \beta \exp(-d / \alpha L).
+
+    This function implements both Waxman models, using the `L` keyword
+    argument.
+
+    * Waxman-1: if `L` is not specified, it is set to be the maximum distance
+      between any pair of nodes.
+    * Waxman-2: if `L` is specified, the distance between a pair of nodes is
+      chosen uniformly at random from the interval `[0, L]`.
+
+    Parameters
+    ----------
+    n : int or iterable
+        Number of nodes or iterable of nodes
+    beta: float
+        Model parameter
+    alpha: float
+        Model parameter
+    L : float, optional
+        Maximum distance between nodes.  If not specified, the actual distance
+        is calculated.
+    domain : four-tuple of numbers, optional
+        Domain size, given as a tuple of the form `(x_min, y_min, x_max,
+        y_max)`.
+    metric : function
+        A metric on vectors of numbers (represented as lists or
+        tuples). This must be a function that accepts two lists (or
+        tuples) as input and yields a number as output. The function
+        must also satisfy the four requirements of a `metric`_.
+        Specifically, if $d$ is the function and $x$, $y$,
+        and $z$ are vectors in the graph, then $d$ must satisfy
+
+        1. $d(x, y) \ge 0$,
+        2. $d(x, y) = 0$ if and only if $x = y$,
+        3. $d(x, y) = d(y, x)$,
+        4. $d(x, z) \le d(x, y) + d(y, z)$.
+
+        If this argument is not specified, the Euclidean distance metric is
+        used.
+
+        .. _metric: https://en.wikipedia.org/wiki/Metric_%28mathematics%29
+
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    pos_name : string, default="pos"
+        The name of the node attribute which represents the position
+        in 2D coordinates of the node in the returned graph.
+
+    Returns
+    -------
+    Graph
+        A random Waxman graph, undirected and without self-loops. Each
+        node has a node attribute ``'pos'`` that stores the position of
+        that node in Euclidean space as generated by this function.
+
+    Examples
+    --------
+    Specify an alternate distance metric using the ``metric`` keyword
+    argument. For example, to use the "`taxicab metric`_" instead of the
+    default `Euclidean metric`_::
+
+        >>> dist = lambda x, y: sum(abs(a - b) for a, b in zip(x, y))
+        >>> G = nx.waxman_graph(10, 0.5, 0.1, metric=dist)
+
+    .. _taxicab metric: https://en.wikipedia.org/wiki/Taxicab_geometry
+    .. _Euclidean metric: https://en.wikipedia.org/wiki/Euclidean_distance
+
+    Notes
+    -----
+    Starting in NetworkX 2.0 the parameters alpha and beta align with their
+    usual roles in the probability distribution. In earlier versions their
+    positions in the expression were reversed. Their position in the calling
+    sequence reversed as well to minimize backward incompatibility.
+
+    References
+    ----------
+    .. [1]  B. M. Waxman, *Routing of multipoint connections*.
+       IEEE J. Select. Areas Commun. 6(9),(1988) 1617--1622.
+    """
+    G = nx.empty_graph(n)
+    (xmin, ymin, xmax, ymax) = domain
+    # Each node gets a uniformly random position in the given rectangle.
+    pos = {v: (seed.uniform(xmin, xmax), seed.uniform(ymin, ymax)) for v in G}
+    nx.set_node_attributes(G, pos, pos_name)
+    # If no distance metric is provided, use Euclidean distance.
+    if metric is None:
+        metric = math.dist
+    # If the maximum distance L is not specified (that is, we are in the
+    # Waxman-1 model), then find the maximum distance between any pair
+    # of nodes.
+    #
+    # In the Waxman-1 model, join nodes randomly based on distance. In
+    # the Waxman-2 model, join randomly based on random l.
+    if L is None:
+        L = max(metric(x, y) for x, y in combinations(pos.values(), 2))
+
+        def dist(u, v):
+            return metric(pos[u], pos[v])
+
+    else:
+
+        def dist(u, v):
+            return seed.random() * L
+
+    # `pair` is the pair of nodes to decide whether to join.
+    def should_join(pair):
+        return seed.random() < beta * math.exp(-dist(*pair) / (alpha * L))
+
+    G.add_edges_from(filter(should_join, combinations(G, 2)))
+    return G
+
+
+@py_random_state(5)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def navigable_small_world_graph(n, p=1, q=1, r=2, dim=2, seed=None):
+    r"""Returns a navigable small-world graph.
+
+    A navigable small-world graph is a directed grid with additional long-range
+    connections that are chosen randomly.
+
+      [...] we begin with a set of nodes [...] that are identified with the set
+      of lattice points in an $n \times n$ square,
+      $\{(i, j): i \in \{1, 2, \ldots, n\}, j \in \{1, 2, \ldots, n\}\}$,
+      and we define the *lattice distance* between two nodes $(i, j)$ and
+      $(k, l)$ to be the number of "lattice steps" separating them:
+      $d((i, j), (k, l)) = |k - i| + |l - j|$.
+
+      For a universal constant $p >= 1$, the node $u$ has a directed edge to
+      every other node within lattice distance $p$---these are its *local
+      contacts*. For universal constants $q >= 0$ and $r >= 0$ we also
+      construct directed edges from $u$ to $q$ other nodes (the *long-range
+      contacts*) using independent random trials; the $i$th directed edge from
+      $u$ has endpoint $v$ with probability proportional to $[d(u,v)]^{-r}$.
+
+      -- [1]_
+
+    Parameters
+    ----------
+    n : int
+        The length of one side of the lattice; the number of nodes in
+        the graph is therefore $n^2$.
+    p : int
+        The diameter of short range connections. Each node is joined with every
+        other node within this lattice distance.
+    q : int
+        The number of long-range connections for each node.
+    r : float
+        Exponent for decaying probability of connections.  The probability of
+        connecting to a node at lattice distance $d$ is $1/d^r$.
+    dim : int
+        Dimension of grid
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    References
+    ----------
+    .. [1] J. Kleinberg. The small-world phenomenon: An algorithmic
+       perspective. Proc. 32nd ACM Symposium on Theory of Computing, 2000.
+    """
+    if p < 1:
+        raise nx.NetworkXException("p must be >= 1")
+    if q < 0:
+        raise nx.NetworkXException("q must be >= 0")
+    if r < 0:
+        raise nx.NetworkXException("r must be >= 0")
+
+    G = nx.DiGraph()
+    nodes = list(product(range(n), repeat=dim))
+    for p1 in nodes:
+        probs = [0]
+        for p2 in nodes:
+            if p1 == p2:
+                continue
+            d = sum((abs(b - a) for a, b in zip(p1, p2)))
+            if d <= p:
+                G.add_edge(p1, p2)
+            probs.append(d**-r)
+        cdf = list(accumulate(probs))
+        for _ in range(q):
+            target = nodes[bisect_left(cdf, seed.uniform(0, cdf[-1]))]
+            G.add_edge(p1, target)
+    return G
+
+
+@py_random_state(7)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def thresholded_random_geometric_graph(
+    n,
+    radius,
+    theta,
+    dim=2,
+    pos=None,
+    weight=None,
+    p=2,
+    seed=None,
+    *,
+    pos_name="pos",
+    weight_name="weight",
+):
+    r"""Returns a thresholded random geometric graph in the unit cube.
+
+    The thresholded random geometric graph [1] model places `n` nodes
+    uniformly at random in the unit cube of dimensions `dim`. Each node
+    `u` is assigned a weight :math:`w_u`. Two nodes `u` and `v` are
+    joined by an edge if they are within the maximum connection distance,
+    `radius` computed by the `p`-Minkowski distance and the summation of
+    weights :math:`w_u` + :math:`w_v` is greater than or equal
+    to the threshold parameter `theta`.
+
+    Edges within `radius` of each other are determined using a KDTree when
+    SciPy is available. This reduces the time complexity from :math:`O(n^2)`
+    to :math:`O(n)`.
+
+    Parameters
+    ----------
+    n : int or iterable
+        Number of nodes or iterable of nodes
+    radius: float
+        Distance threshold value
+    theta: float
+        Threshold value
+    dim : int, optional
+        Dimension of graph
+    pos : dict, optional
+        A dictionary keyed by node with node positions as values.
+    weight : dict, optional
+        Node weights as a dictionary of numbers keyed by node.
+    p : float, optional (default 2)
+        Which Minkowski distance metric to use.  `p` has to meet the condition
+        ``1 <= p <= infinity``.
+
+        If this argument is not specified, the :math:`L^2` metric
+        (the Euclidean distance metric), p = 2 is used.
+
+        This should not be confused with the `p` of an Erdős-Rényi random
+        graph, which represents probability.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    pos_name : string, default="pos"
+        The name of the node attribute which represents the position
+        in 2D coordinates of the node in the returned graph.
+    weight_name : string, default="weight"
+        The name of the node attribute which represents the weight
+        of the node in the returned graph.
+
+    Returns
+    -------
+    Graph
+        A thresholded random geographic graph, undirected and without
+        self-loops.
+
+        Each node has a node attribute ``'pos'`` that stores the
+        position of that node in Euclidean space as provided by the
+        ``pos`` keyword argument or, if ``pos`` was not provided, as
+        generated by this function. Similarly, each node has a nodethre
+        attribute ``'weight'`` that stores the weight of that node as
+        provided or as generated.
+
+    Notes
+    -----
+    This uses a *k*-d tree to build the graph.
+
+    References
+    ----------
+    .. [1] http://cole-maclean.github.io/blog/files/thesis.pdf
+
+    Examples
+    --------
+    Default Graph:
+
+    >>> G = nx.thresholded_random_geometric_graph(50, 0.2, 0.1)
+
+    Custom Graph:
+
+    The `pos` keyword argument can be used to specify node positions so you
+    can create an arbitrary distribution and domain for positions.
+
+    If weights are not specified they are assigned to nodes by drawing randomly
+    from the exponential distribution with rate parameter :math:`\lambda=1`.
+    To specify weights from a different distribution, use the `weight` keyword
+    argument.
+
+    For example, create a thresholded random geometric graph on 50 nodes using a 2D
+    Gaussian distribution of node positions with mean (0, 0) and standard deviation 2,
+    where nodes are joined by an edge if their sum weights drawn from
+    a exponential distribution with rate = 5 are >= theta = 0.1 and their
+    Euclidean distance is at most 0.2.
+
+    >>> import random
+    >>> n = 50
+    >>> pos = {i: (random.gauss(0, 2), random.gauss(0, 2)) for i in range(n)}
+    >>> w = {i: random.expovariate(5.0) for i in range(n)}
+    >>> G = nx.thresholded_random_geometric_graph(n, 0.2, 0.1, 2, pos, w)
+
+    """
+    G = nx.empty_graph(n)
+    G.name = f"thresholded_random_geometric_graph({n}, {radius}, {theta}, {dim})"
+    # If no weights are provided, choose them from an exponential
+    # distribution.
+    if weight is None:
+        weight = {v: seed.expovariate(1) for v in G}
+    # If no positions are provided, choose uniformly random vectors in
+    # Euclidean space of the specified dimension.
+    if pos is None:
+        pos = {v: [seed.random() for i in range(dim)] for v in G}
+    # If no distance metric is provided, use Euclidean distance.
+    nx.set_node_attributes(G, weight, weight_name)
+    nx.set_node_attributes(G, pos, pos_name)
+
+    edges = (
+        (u, v)
+        for u, v in _geometric_edges(G, radius, p, pos_name)
+        if weight[u] + weight[v] >= theta
+    )
+    G.add_edges_from(edges)
+    return G
+
+
+@py_random_state(5)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def geometric_soft_configuration_graph(
+    *, beta, n=None, gamma=None, mean_degree=None, kappas=None, seed=None
+):
+    r"""Returns a random graph from the geometric soft configuration model.
+
+    The $\mathbb{S}^1$ model [1]_ is the geometric soft configuration model
+    which is able to explain many fundamental features of real networks such as
+    small-world property, heteregenous degree distributions, high level of
+    clustering, and self-similarity.
+
+    In the geometric soft configuration model, a node $i$ is assigned two hidden
+    variables: a hidden degree $\kappa_i$, quantifying its popularity, influence,
+    or importance, and an angular position $\theta_i$ in a circle abstracting the
+    similarity space, where angular distances between nodes are a proxy for their
+    similarity. Focusing on the angular position, this model is often called
+    the $\mathbb{S}^1$ model (a one-dimensional sphere). The circle's radius is
+    adjusted to $R = N/2\pi$, where $N$ is the number of nodes, so that the density
+    is set to 1 without loss of generality.
+
+    The connection probability between any pair of nodes increases with
+    the product of their hidden degrees (i.e., their combined popularities),
+    and decreases with the angular distance between the two nodes.
+    Specifically, nodes $i$ and $j$ are connected with the probability
+
+    $p_{ij} = \frac{1}{1 + \frac{d_{ij}^\beta}{\left(\mu \kappa_i \kappa_j\right)^{\max(1, \beta)}}}$
+
+    where $d_{ij} = R\Delta\theta_{ij}$ is the arc length of the circle between
+    nodes $i$ and $j$ separated by an angular distance $\Delta\theta_{ij}$.
+    Parameters $\mu$ and $\beta$ (also called inverse temperature) control the
+    average degree and the clustering coefficient, respectively.
+
+    It can be shown [2]_ that the model undergoes a structural phase transition
+    at $\beta=1$ so that for $\beta<1$ networks are unclustered in the thermodynamic
+    limit (when $N\to \infty$) whereas for $\beta>1$ the ensemble generates
+    networks with finite clustering coefficient.
+
+    The $\mathbb{S}^1$ model can be expressed as a purely geometric model
+    $\mathbb{H}^2$ in the hyperbolic plane [3]_ by mapping the hidden degree of
+    each node into a radial coordinate as
+
+    $r_i = \hat{R} - \frac{2 \max(1, \beta)}{\beta \zeta} \ln \left(\frac{\kappa_i}{\kappa_0}\right)$
+
+    where $\hat{R}$ is the radius of the hyperbolic disk and $\zeta$ is the curvature,
+
+    $\hat{R} = \frac{2}{\zeta} \ln \left(\frac{N}{\pi}\right)
+    - \frac{2\max(1, \beta)}{\beta \zeta} \ln (\mu \kappa_0^2)$
+
+    The connection probability then reads
+
+    $p_{ij} = \frac{1}{1 + \exp\left({\frac{\beta\zeta}{2} (x_{ij} - \hat{R})}\right)}$
+
+    where
+
+    $x_{ij} = r_i + r_j + \frac{2}{\zeta} \ln \frac{\Delta\theta_{ij}}{2}$
+
+    is a good approximation of the hyperbolic distance between two nodes separated
+    by an angular distance $\Delta\theta_{ij}$ with radial coordinates $r_i$ and $r_j$.
+    For $\beta > 1$, the curvature $\zeta = 1$, for $\beta < 1$, $\zeta = \beta^{-1}$.
+
+
+    Parameters
+    ----------
+    Either `n`, `gamma`, `mean_degree` are provided or `kappas`. The values of
+    `n`, `gamma`, `mean_degree` (if provided) are used to construct a random
+    kappa-dict keyed by node with values sampled from a power-law distribution.
+
+    beta : positive number
+        Inverse temperature, controlling the clustering coefficient.
+    n : int (default: None)
+        Size of the network (number of nodes).
+        If not provided, `kappas` must be provided and holds the nodes.
+    gamma : float (default: None)
+        Exponent of the power-law distribution for hidden degrees `kappas`.
+        If not provided, `kappas` must be provided directly.
+    mean_degree : float (default: None)
+        The mean degree in the network.
+        If not provided, `kappas` must be provided directly.
+    kappas : dict (default: None)
+        A dict keyed by node to its hidden degree value.
+        If not provided, random values are computed based on a power-law
+        distribution using `n`, `gamma` and `mean_degree`.
+    seed : int, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    Graph
+        A random geometric soft configuration graph (undirected with no self-loops).
+        Each node has three node-attributes:
+
+        - ``kappa`` that represents the hidden degree.
+
+        - ``theta`` the position in the similarity space ($\mathbb{S}^1$) which is
+          also the angular position in the hyperbolic plane.
+
+        - ``radius`` the radial position in the hyperbolic plane
+          (based on the hidden degree).
+
+
+    Examples
+    --------
+    Generate a network with specified parameters:
+
+    >>> G = nx.geometric_soft_configuration_graph(
+    ...     beta=1.5, n=100, gamma=2.7, mean_degree=5
+    ... )
+
+    Create a geometric soft configuration graph with 100 nodes. The $\beta$ parameter
+    is set to 1.5 and the exponent of the powerlaw distribution of the hidden
+    degrees is 2.7 with mean value of 5.
+
+    Generate a network with predefined hidden degrees:
+
+    >>> kappas = {i: 10 for i in range(100)}
+    >>> G = nx.geometric_soft_configuration_graph(beta=2.5, kappas=kappas)
+
+    Create a geometric soft configuration graph with 100 nodes. The $\beta$ parameter
+    is set to 2.5 and all nodes with hidden degree $\kappa=10$.
+
+
+    References
+    ----------
+    .. [1] Serrano, M. Á., Krioukov, D., & Boguñá, M. (2008). Self-similarity
+       of complex networks and hidden metric spaces. Physical review letters, 100(7), 078701.
+
+    .. [2] van der Kolk, J., Serrano, M. Á., & Boguñá, M. (2022). An anomalous
+       topological phase transition in spatial random graphs. Communications Physics, 5(1), 245.
+
+    .. [3] Krioukov, D., Papadopoulos, F., Kitsak, M., Vahdat, A., & Boguná, M. (2010).
+       Hyperbolic geometry of complex networks. Physical Review E, 82(3), 036106.
+
+    """
+    if beta <= 0:
+        raise nx.NetworkXError("The parameter beta cannot be smaller or equal to 0.")
+
+    if kappas is not None:
+        if not all((n is None, gamma is None, mean_degree is None)):
+            raise nx.NetworkXError(
+                "When kappas is input, n, gamma and mean_degree must not be."
+            )
+
+        n = len(kappas)
+        mean_degree = sum(kappas) / len(kappas)
+    else:
+        if any((n is None, gamma is None, mean_degree is None)):
+            raise nx.NetworkXError(
+                "Please provide either kappas, or all 3 of: n, gamma and mean_degree."
+            )
+
+        # Generate `n` hidden degrees from a powerlaw distribution
+        # with given exponent `gamma` and mean value `mean_degree`
+        gam_ratio = (gamma - 2) / (gamma - 1)
+        kappa_0 = mean_degree * gam_ratio * (1 - 1 / n) / (1 - 1 / n**gam_ratio)
+        base = 1 - 1 / n
+        power = 1 / (1 - gamma)
+        kappas = {i: kappa_0 * (1 - seed.random() * base) ** power for i in range(n)}
+
+    G = nx.Graph()
+    R = n / (2 * math.pi)
+
+    # Approximate values for mu in the thermodynamic limit (when n -> infinity)
+    if beta > 1:
+        mu = beta * math.sin(math.pi / beta) / (2 * math.pi * mean_degree)
+    elif beta == 1:
+        mu = 1 / (2 * mean_degree * math.log(n))
+    else:
+        mu = (1 - beta) / (2**beta * mean_degree * n ** (1 - beta))
+
+    # Generate random positions on a circle
+    thetas = {k: seed.uniform(0, 2 * math.pi) for k in kappas}
+
+    for u in kappas:
+        for v in list(G):
+            angle = math.pi - math.fabs(math.pi - math.fabs(thetas[u] - thetas[v]))
+            dij = math.pow(R * angle, beta)
+            mu_kappas = math.pow(mu * kappas[u] * kappas[v], max(1, beta))
+            p_ij = 1 / (1 + dij / mu_kappas)
+
+            # Create an edge with a certain connection probability
+            if seed.random() < p_ij:
+                G.add_edge(u, v)
+        G.add_node(u)
+
+    nx.set_node_attributes(G, thetas, "theta")
+    nx.set_node_attributes(G, kappas, "kappa")
+
+    # Map hidden degrees into the radial coordinates
+    zeta = 1 if beta > 1 else 1 / beta
+    kappa_min = min(kappas.values())
+    R_c = 2 * max(1, beta) / (beta * zeta)
+    R_hat = (2 / zeta) * math.log(n / math.pi) - R_c * math.log(mu * kappa_min)
+    radii = {node: R_hat - R_c * math.log(kappa) for node, kappa in kappas.items()}
+    nx.set_node_attributes(G, radii, "radius")
+
+    return G
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/harary_graph.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/harary_graph.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5dde2e8998f25dbaf68ab8bd7a64f846cd29275
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/harary_graph.py
@@ -0,0 +1,163 @@
+"""Generators for Harary graphs
+
+This module gives two generators for the Harary graph, which was
+introduced by the famous mathematician Frank Harary in his 1962 work [H]_.
+The first generator gives the Harary graph that maximizes the node
+connectivity with given number of nodes and given number of edges.
+The second generator gives the Harary graph that minimizes
+the number of edges in the graph with given node connectivity and
+number of nodes.
+
+References
+----------
+.. [H] Harary, F. "The Maximum Connectivity of a Graph."
+       Proc. Nat. Acad. Sci. USA 48, 1142-1146, 1962.
+
+"""
+
+import networkx as nx
+from networkx.exception import NetworkXError
+
+__all__ = ["hnm_harary_graph", "hkn_harary_graph"]
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def hnm_harary_graph(n, m, create_using=None):
+    r"""Return the Harary graph with given numbers of nodes and edges.
+
+    The Harary graph $H_{n, m}$ is the graph that maximizes node connectivity
+    with $n$ nodes and $m$ edges.
+
+    This maximum node connectivity is known to be $\lfloor 2m/n \rfloor$. [1]_
+
+    Parameters
+    ----------
+    n: integer
+        The number of nodes the generated graph is to contain.
+
+    m: integer
+        The number of edges the generated graph is to contain.
+
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+        Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    NetworkX graph
+        The Harary graph $H_{n, m}$.
+
+    See Also
+    --------
+    hkn_harary_graph
+
+    Notes
+    -----
+    This algorithm runs in $O(m)$ time.
+    The implementation follows [2]_.
+
+    References
+    ----------
+    .. [1] F. T. Boesch, A. Satyanarayana, and C. L. Suffel,
+       "A Survey of Some Network Reliability Analysis and Synthesis Results,"
+       Networks, pp. 99-107, 2009.
+
+    .. [2] Harary, F. "The Maximum Connectivity of a Graph."
+       Proc. Nat. Acad. Sci. USA 48, 1142-1146, 1962.
+    """
+
+    if n < 1:
+        raise NetworkXError("The number of nodes must be >= 1!")
+    if m < n - 1:
+        raise NetworkXError("The number of edges must be >= n - 1 !")
+    if m > n * (n - 1) // 2:
+        raise NetworkXError("The number of edges must be <= n(n-1)/2")
+
+    # Get the floor of average node degree.
+    d = 2 * m // n
+
+    offset = d // 2
+    H = nx.circulant_graph(n, range(1, offset + 1), create_using=create_using)
+
+    half = n // 2
+    if (n % 2 == 0) or (d % 2 == 0):
+        # If d is odd; n must be even.
+        if d % 2 == 1:
+            # Add edges diagonally.
+            H.add_edges_from((i, i + half) for i in range(half))
+
+        r = 2 * m % n
+        # Add remaining edges at offset + 1.
+        H.add_edges_from((i, i + offset + 1) for i in range(r // 2))
+    else:
+        # Add the remaining m - n * offset edges between i and i + half.
+        H.add_edges_from((i, (i + half) % n) for i in range(m - n * offset))
+
+    return H
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def hkn_harary_graph(k, n, create_using=None):
+    r"""Return the Harary graph with given node connectivity and node number.
+
+    The Harary graph $H_{k, n}$ is the graph that minimizes the number of
+    edges needed with given node connectivity $k$ and node number $n$.
+
+    This smallest number of edges is known to be $\lceil kn/2 \rceil$ [1]_.
+
+    Parameters
+    ----------
+    k: integer
+        The node connectivity of the generated graph.
+
+    n: integer
+        The number of nodes the generated graph is to contain.
+
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+        Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    NetworkX graph
+        The Harary graph $H_{k, n}$.
+
+    See Also
+    --------
+    hnm_harary_graph
+
+    Notes
+    -----
+    This algorithm runs in $O(kn)$ time.
+    The implementation follows [2]_.
+
+    References
+    ----------
+    .. [1] Weisstein, Eric W. "Harary Graph." From MathWorld--A Wolfram Web
+     Resource. http://mathworld.wolfram.com/HararyGraph.html.
+
+    .. [2] Harary, F. "The Maximum Connectivity of a Graph."
+      Proc. Nat. Acad. Sci. USA 48, 1142-1146, 1962.
+    """
+
+    if k < 1:
+        raise NetworkXError("The node connectivity must be >= 1!")
+    if n < k + 1:
+        raise NetworkXError("The number of nodes must be >= k+1 !")
+
+    # In case of connectivity 1, simply return the path graph.
+    if k == 1:
+        return nx.path_graph(n, create_using)
+
+    offset = k // 2
+    H = nx.circulant_graph(n, range(1, offset + 1), create_using=create_using)
+
+    half = n // 2
+    if (k % 2 == 0) or (n % 2 == 0):
+        # If k is odd; n must be even.
+        if k % 2 == 1:
+            # Add edges diagonally.
+            H.add_edges_from((i, i + half) for i in range(half))
+    else:
+        # Add half + 1 edges between i and i + half.
+        H.add_edges_from((i, (i + half) % n) for i in range(half + 1))
+
+    return H
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/internet_as_graphs.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/internet_as_graphs.py
new file mode 100644
index 0000000000000000000000000000000000000000..31fbb6dd03a796aa8abc0dc5afd7c991baf5a993
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/internet_as_graphs.py
@@ -0,0 +1,443 @@
+"""Generates graphs resembling the Internet Autonomous System network"""
+
+import networkx as nx
+from networkx.utils import py_random_state
+
+__all__ = ["random_internet_as_graph"]
+
+
+def uniform_int_from_avg(a, m, seed):
+    """Pick a random integer with uniform probability.
+
+    Returns a random integer uniformly taken from a distribution with
+    minimum value 'a' and average value 'm', X~U(a,b), E[X]=m, X in N where
+    b = 2*m - a.
+
+    Notes
+    -----
+    p = (b-floor(b))/2
+    X = X1 + X2; X1~U(a,floor(b)), X2~B(p)
+    E[X] = E[X1] + E[X2] = (floor(b)+a)/2 + (b-floor(b))/2 = (b+a)/2 = m
+    """
+
+    from math import floor
+
+    assert m >= a
+    b = 2 * m - a
+    p = (b - floor(b)) / 2
+    X1 = round(seed.random() * (floor(b) - a) + a)
+    if seed.random() < p:
+        X2 = 1
+    else:
+        X2 = 0
+    return X1 + X2
+
+
+@py_random_state("seed")
+def choose_pref_attach(degs, seed):
+    """Pick a random value, with a probability given by its weight.
+
+    Returns a random choice among degs keys, each of which has a
+    probability proportional to the corresponding dictionary value.
+
+    Parameters
+    ----------
+    degs: dictionary
+        It contains the possible values (keys) and the corresponding
+        probabilities (values)
+    seed: random state
+
+    Returns
+    -------
+    v: object
+        A key of degs or None if degs is empty
+    """
+
+    if len(degs) == 0:
+        return None
+    s = sum(degs.values())
+    if s == 0:
+        return seed.choice(list(degs.keys()))
+    v = seed.random() * s
+
+    nodes = list(degs.keys())
+    i = 0
+    acc = degs[nodes[i]]
+    while v > acc:
+        i += 1
+        acc += degs[nodes[i]]
+    return nodes[i]
+
+
+class AS_graph_generator:
+    """Generates random internet AS graphs."""
+
+    @py_random_state("seed")
+    def __init__(self, n, seed):
+        """Initializes variables. Immediate numbers are taken from [1].
+
+        Parameters
+        ----------
+        n: integer
+            Number of graph nodes
+        seed: random state
+            Indicator of random number generation state.
+            See :ref:`Randomness`.
+
+        Returns
+        -------
+        GG: AS_graph_generator object
+
+        References
+        ----------
+        [1] A. Elmokashfi, A. Kvalbein and C. Dovrolis, "On the Scalability of
+        BGP: The Role of Topology Growth," in IEEE Journal on Selected Areas
+        in Communications, vol. 28, no. 8, pp. 1250-1261, October 2010.
+        """
+
+        self.seed = seed
+        self.n_t = min(n, round(self.seed.random() * 2 + 4))  # num of T nodes
+        self.n_m = round(0.15 * n)  # number of M nodes
+        self.n_cp = round(0.05 * n)  # number of CP nodes
+        self.n_c = max(0, n - self.n_t - self.n_m - self.n_cp)  # number of C nodes
+
+        self.d_m = 2 + (2.5 * n) / 10000  # average multihoming degree for M nodes
+        self.d_cp = 2 + (1.5 * n) / 10000  # avg multihoming degree for CP nodes
+        self.d_c = 1 + (5 * n) / 100000  # average multihoming degree for C nodes
+
+        self.p_m_m = 1 + (2 * n) / 10000  # avg num of peer edges between M and M
+        self.p_cp_m = 0.2 + (2 * n) / 10000  # avg num of peer edges between CP, M
+        self.p_cp_cp = 0.05 + (2 * n) / 100000  # avg num of peer edges btwn CP, CP
+
+        self.t_m = 0.375  # probability M's provider is T
+        self.t_cp = 0.375  # probability CP's provider is T
+        self.t_c = 0.125  # probability C's provider is T
+
+    def t_graph(self):
+        """Generates the core mesh network of tier one nodes of a AS graph.
+
+        Returns
+        -------
+        G: Networkx Graph
+            Core network
+        """
+
+        self.G = nx.Graph()
+        for i in range(self.n_t):
+            self.G.add_node(i, type="T")
+            for r in self.regions:
+                self.regions[r].add(i)
+            for j in self.G.nodes():
+                if i != j:
+                    self.add_edge(i, j, "peer")
+            self.customers[i] = set()
+            self.providers[i] = set()
+        return self.G
+
+    def add_edge(self, i, j, kind):
+        if kind == "transit":
+            customer = str(i)
+        else:
+            customer = "none"
+        self.G.add_edge(i, j, type=kind, customer=customer)
+
+    def choose_peer_pref_attach(self, node_list):
+        """Pick a node with a probability weighted by its peer degree.
+
+        Pick a node from node_list with preferential attachment
+        computed only on their peer degree
+        """
+
+        d = {}
+        for n in node_list:
+            d[n] = self.G.nodes[n]["peers"]
+        return choose_pref_attach(d, self.seed)
+
+    def choose_node_pref_attach(self, node_list):
+        """Pick a node with a probability weighted by its degree.
+
+        Pick a node from node_list with preferential attachment
+        computed on their degree
+        """
+
+        degs = dict(self.G.degree(node_list))
+        return choose_pref_attach(degs, self.seed)
+
+    def add_customer(self, i, j):
+        """Keep the dictionaries 'customers' and 'providers' consistent."""
+
+        self.customers[j].add(i)
+        self.providers[i].add(j)
+        for z in self.providers[j]:
+            self.customers[z].add(i)
+            self.providers[i].add(z)
+
+    def add_node(self, i, kind, reg2prob, avg_deg, t_edge_prob):
+        """Add a node and its customer transit edges to the graph.
+
+        Parameters
+        ----------
+        i: object
+            Identifier of the new node
+        kind: string
+            Type of the new node. Options are: 'M' for middle node, 'CP' for
+            content provider and 'C' for customer.
+        reg2prob: float
+            Probability the new node can be in two different regions.
+        avg_deg: float
+            Average number of transit nodes of which node i is customer.
+        t_edge_prob: float
+            Probability node i establish a customer transit edge with a tier
+            one (T) node
+
+        Returns
+        -------
+        i: object
+            Identifier of the new node
+        """
+
+        regs = 1  # regions in which node resides
+        if self.seed.random() < reg2prob:  # node is in two regions
+            regs = 2
+        node_options = set()
+
+        self.G.add_node(i, type=kind, peers=0)
+        self.customers[i] = set()
+        self.providers[i] = set()
+        self.nodes[kind].add(i)
+        for r in self.seed.sample(list(self.regions), regs):
+            node_options = node_options.union(self.regions[r])
+            self.regions[r].add(i)
+
+        edge_num = uniform_int_from_avg(1, avg_deg, self.seed)
+
+        t_options = node_options.intersection(self.nodes["T"])
+        m_options = node_options.intersection(self.nodes["M"])
+        if i in m_options:
+            m_options.remove(i)
+        d = 0
+        while d < edge_num and (len(t_options) > 0 or len(m_options) > 0):
+            if len(m_options) == 0 or (
+                len(t_options) > 0 and self.seed.random() < t_edge_prob
+            ):  # add edge to a T node
+                j = self.choose_node_pref_attach(t_options)
+                t_options.remove(j)
+            else:
+                j = self.choose_node_pref_attach(m_options)
+                m_options.remove(j)
+            self.add_edge(i, j, "transit")
+            self.add_customer(i, j)
+            d += 1
+
+        return i
+
+    def add_m_peering_link(self, m, to_kind):
+        """Add a peering link between two middle tier (M) nodes.
+
+        Target node j is drawn considering a preferential attachment based on
+        other M node peering degree.
+
+        Parameters
+        ----------
+        m: object
+            Node identifier
+        to_kind: string
+            type for target node j (must be always M)
+
+        Returns
+        -------
+        success: boolean
+        """
+
+        # candidates are of type 'M' and are not customers of m
+        node_options = self.nodes["M"].difference(self.customers[m])
+        # candidates are not providers of m
+        node_options = node_options.difference(self.providers[m])
+        # remove self
+        if m in node_options:
+            node_options.remove(m)
+
+        # remove candidates we are already connected to
+        for j in self.G.neighbors(m):
+            if j in node_options:
+                node_options.remove(j)
+
+        if len(node_options) > 0:
+            j = self.choose_peer_pref_attach(node_options)
+            self.add_edge(m, j, "peer")
+            self.G.nodes[m]["peers"] += 1
+            self.G.nodes[j]["peers"] += 1
+            return True
+        else:
+            return False
+
+    def add_cp_peering_link(self, cp, to_kind):
+        """Add a peering link to a content provider (CP) node.
+
+        Target node j can be CP or M and it is drawn uniformly among the nodes
+        belonging to the same region as cp.
+
+        Parameters
+        ----------
+        cp: object
+            Node identifier
+        to_kind: string
+            type for target node j (must be M or CP)
+
+        Returns
+        -------
+        success: boolean
+        """
+
+        node_options = set()
+        for r in self.regions:  # options include nodes in the same region(s)
+            if cp in self.regions[r]:
+                node_options = node_options.union(self.regions[r])
+
+        # options are restricted to the indicated kind ('M' or 'CP')
+        node_options = self.nodes[to_kind].intersection(node_options)
+
+        # remove self
+        if cp in node_options:
+            node_options.remove(cp)
+
+        # remove nodes that are cp's providers
+        node_options = node_options.difference(self.providers[cp])
+
+        # remove nodes we are already connected to
+        for j in self.G.neighbors(cp):
+            if j in node_options:
+                node_options.remove(j)
+
+        if len(node_options) > 0:
+            j = self.seed.sample(list(node_options), 1)[0]
+            self.add_edge(cp, j, "peer")
+            self.G.nodes[cp]["peers"] += 1
+            self.G.nodes[j]["peers"] += 1
+            return True
+        else:
+            return False
+
+    def graph_regions(self, rn):
+        """Initializes AS network regions.
+
+        Parameters
+        ----------
+        rn: integer
+            Number of regions
+        """
+
+        self.regions = {}
+        for i in range(rn):
+            self.regions["REG" + str(i)] = set()
+
+    def add_peering_links(self, from_kind, to_kind):
+        """Utility function to add peering links among node groups."""
+        peer_link_method = None
+        if from_kind == "M":
+            peer_link_method = self.add_m_peering_link
+            m = self.p_m_m
+        if from_kind == "CP":
+            peer_link_method = self.add_cp_peering_link
+            if to_kind == "M":
+                m = self.p_cp_m
+            else:
+                m = self.p_cp_cp
+
+        for i in self.nodes[from_kind]:
+            num = uniform_int_from_avg(0, m, self.seed)
+            for _ in range(num):
+                peer_link_method(i, to_kind)
+
+    def generate(self):
+        """Generates a random AS network graph as described in [1].
+
+        Returns
+        -------
+        G: Graph object
+
+        Notes
+        -----
+        The process steps are the following: first we create the core network
+        of tier one nodes, then we add the middle tier (M), the content
+        provider (CP) and the customer (C) nodes along with their transit edges
+        (link i,j means i is customer of j). Finally we add peering links
+        between M nodes, between M and CP nodes and between CP node couples.
+        For a detailed description of the algorithm, please refer to [1].
+
+        References
+        ----------
+        [1] A. Elmokashfi, A. Kvalbein and C. Dovrolis, "On the Scalability of
+        BGP: The Role of Topology Growth," in IEEE Journal on Selected Areas
+        in Communications, vol. 28, no. 8, pp. 1250-1261, October 2010.
+        """
+
+        self.graph_regions(5)
+        self.customers = {}
+        self.providers = {}
+        self.nodes = {"T": set(), "M": set(), "CP": set(), "C": set()}
+
+        self.t_graph()
+        self.nodes["T"] = set(self.G.nodes())
+
+        i = len(self.nodes["T"])
+        for _ in range(self.n_m):
+            self.nodes["M"].add(self.add_node(i, "M", 0.2, self.d_m, self.t_m))
+            i += 1
+        for _ in range(self.n_cp):
+            self.nodes["CP"].add(self.add_node(i, "CP", 0.05, self.d_cp, self.t_cp))
+            i += 1
+        for _ in range(self.n_c):
+            self.nodes["C"].add(self.add_node(i, "C", 0, self.d_c, self.t_c))
+            i += 1
+
+        self.add_peering_links("M", "M")
+        self.add_peering_links("CP", "M")
+        self.add_peering_links("CP", "CP")
+
+        return self.G
+
+
+@py_random_state(1)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def random_internet_as_graph(n, seed=None):
+    """Generates a random undirected graph resembling the Internet AS network
+
+    Parameters
+    ----------
+    n: integer in [1000, 10000]
+        Number of graph nodes
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    G: Networkx Graph object
+        A randomly generated undirected graph
+
+    Notes
+    -----
+    This algorithm returns an undirected graph resembling the Internet
+    Autonomous System (AS) network, it uses the approach by Elmokashfi et al.
+    [1]_ and it grants the properties described in the related paper [1]_.
+
+    Each node models an autonomous system, with an attribute 'type' specifying
+    its kind; tier-1 (T), mid-level (M), customer (C) or content-provider (CP).
+    Each edge models an ADV communication link (hence, bidirectional) with
+    attributes:
+
+      - type: transit|peer, the kind of commercial agreement between nodes;
+      - customer: , the identifier of the node acting as customer
+        ('none' if type is peer).
+
+    References
+    ----------
+    .. [1] A. Elmokashfi, A. Kvalbein and C. Dovrolis, "On the Scalability of
+       BGP: The Role of Topology Growth," in IEEE Journal on Selected Areas
+       in Communications, vol. 28, no. 8, pp. 1250-1261, October 2010.
+    """
+
+    GG = AS_graph_generator(n, seed)
+    G = GG.generate()
+    return G
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/intersection.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/intersection.py
new file mode 100644
index 0000000000000000000000000000000000000000..e63af5be8eed2e65b9cced2cc50827ffe6a802ba
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/intersection.py
@@ -0,0 +1,125 @@
+"""
+Generators for random intersection graphs.
+"""
+
+import networkx as nx
+from networkx.utils import py_random_state
+
+__all__ = [
+    "uniform_random_intersection_graph",
+    "k_random_intersection_graph",
+    "general_random_intersection_graph",
+]
+
+
+@py_random_state(3)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def uniform_random_intersection_graph(n, m, p, seed=None):
+    """Returns a uniform random intersection graph.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes in the first bipartite set (nodes)
+    m : int
+        The number of nodes in the second bipartite set (attributes)
+    p : float
+        Probability of connecting nodes between bipartite sets
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    See Also
+    --------
+    gnp_random_graph
+
+    References
+    ----------
+    .. [1] K.B. Singer-Cohen, Random Intersection Graphs, 1995,
+       PhD thesis, Johns Hopkins University
+    .. [2] Fill, J. A., Scheinerman, E. R., and Singer-Cohen, K. B.,
+       Random intersection graphs when m = !(n):
+       An equivalence theorem relating the evolution of the g(n, m, p)
+       and g(n, p) models. Random Struct. Algorithms 16, 2 (2000), 156–176.
+    """
+    from networkx.algorithms import bipartite
+
+    G = bipartite.random_graph(n, m, p, seed)
+    return nx.projected_graph(G, range(n))
+
+
+@py_random_state(3)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def k_random_intersection_graph(n, m, k, seed=None):
+    """Returns a intersection graph with randomly chosen attribute sets for
+    each node that are of equal size (k).
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes in the first bipartite set (nodes)
+    m : int
+        The number of nodes in the second bipartite set (attributes)
+    k : float
+        Size of attribute set to assign to each node.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    See Also
+    --------
+    gnp_random_graph, uniform_random_intersection_graph
+
+    References
+    ----------
+    .. [1] Godehardt, E., and Jaworski, J.
+       Two models of random intersection graphs and their applications.
+       Electronic Notes in Discrete Mathematics 10 (2001), 129--132.
+    """
+    G = nx.empty_graph(n + m)
+    mset = range(n, n + m)
+    for v in range(n):
+        targets = seed.sample(mset, k)
+        G.add_edges_from(zip([v] * len(targets), targets))
+    return nx.projected_graph(G, range(n))
+
+
+@py_random_state(3)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def general_random_intersection_graph(n, m, p, seed=None):
+    """Returns a random intersection graph with independent probabilities
+    for connections between node and attribute sets.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes in the first bipartite set (nodes)
+    m : int
+        The number of nodes in the second bipartite set (attributes)
+    p : list of floats of length m
+        Probabilities for connecting nodes to each attribute
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    See Also
+    --------
+    gnp_random_graph, uniform_random_intersection_graph
+
+    References
+    ----------
+    .. [1] Nikoletseas, S. E., Raptopoulos, C., and Spirakis, P. G.
+       The existence and efficient construction of large independent sets
+       in general random intersection graphs. In ICALP (2004), J. D´ıaz,
+       J. Karhum¨aki, A. Lepist¨o, and D. Sannella, Eds., vol. 3142
+       of Lecture Notes in Computer Science, Springer, pp. 1029–1040.
+    """
+    if len(p) != m:
+        raise ValueError("Probability list p must have m elements.")
+    G = nx.empty_graph(n + m)
+    mset = range(n, n + m)
+    for u in range(n):
+        for v, q in zip(mset, p):
+            if seed.random() < q:
+                G.add_edge(u, v)
+    return nx.projected_graph(G, range(n))
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/interval_graph.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/interval_graph.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a3fda45acec52af6a5f060b96d9af1067fc002b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/interval_graph.py
@@ -0,0 +1,70 @@
+"""
+Generators for interval graph.
+"""
+
+from collections.abc import Sequence
+
+import networkx as nx
+
+__all__ = ["interval_graph"]
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def interval_graph(intervals):
+    """Generates an interval graph for a list of intervals given.
+
+    In graph theory, an interval graph is an undirected graph formed from a set
+    of closed intervals on the real line, with a vertex for each interval
+    and an edge between vertices whose intervals intersect.
+    It is the intersection graph of the intervals.
+
+    More information can be found at:
+    https://en.wikipedia.org/wiki/Interval_graph
+
+    Parameters
+    ----------
+    intervals : a sequence of intervals, say (l, r) where l is the left end,
+    and r is the right end of the closed interval.
+
+    Returns
+    -------
+    G : networkx graph
+
+    Examples
+    --------
+    >>> intervals = [(-2, 3), [1, 4], (2, 3), (4, 6)]
+    >>> G = nx.interval_graph(intervals)
+    >>> sorted(G.edges)
+    [((-2, 3), (1, 4)), ((-2, 3), (2, 3)), ((1, 4), (2, 3)), ((1, 4), (4, 6))]
+
+    Raises
+    ------
+    :exc:`TypeError`
+        if `intervals` contains None or an element which is not
+        collections.abc.Sequence or not a length of 2.
+    :exc:`ValueError`
+        if `intervals` contains an interval such that min1 > max1
+        where min1,max1 = interval
+    """
+    intervals = list(intervals)
+    for interval in intervals:
+        if not (isinstance(interval, Sequence) and len(interval) == 2):
+            raise TypeError(
+                "Each interval must have length 2, and be a "
+                "collections.abc.Sequence such as tuple or list."
+            )
+        if interval[0] > interval[1]:
+            raise ValueError(f"Interval must have lower value first. Got {interval}")
+
+    graph = nx.Graph()
+
+    tupled_intervals = [tuple(interval) for interval in intervals]
+    graph.add_nodes_from(tupled_intervals)
+
+    while tupled_intervals:
+        min1, max1 = interval1 = tupled_intervals.pop()
+        for interval2 in tupled_intervals:
+            min2, max2 = interval2
+            if max1 >= min2 and max2 >= min1:
+                graph.add_edge(interval1, interval2)
+    return graph
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/joint_degree_seq.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/joint_degree_seq.py
new file mode 100644
index 0000000000000000000000000000000000000000..c426df944ad27aef4584371838a6ddb280b90dca
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/joint_degree_seq.py
@@ -0,0 +1,664 @@
+"""Generate graphs with a given joint degree and directed joint degree"""
+
+import networkx as nx
+from networkx.utils import py_random_state
+
+__all__ = [
+    "is_valid_joint_degree",
+    "is_valid_directed_joint_degree",
+    "joint_degree_graph",
+    "directed_joint_degree_graph",
+]
+
+
+@nx._dispatchable(graphs=None)
+def is_valid_joint_degree(joint_degrees):
+    """Checks whether the given joint degree dictionary is realizable.
+
+    A *joint degree dictionary* is a dictionary of dictionaries, in
+    which entry ``joint_degrees[k][l]`` is an integer representing the
+    number of edges joining nodes of degree *k* with nodes of degree
+    *l*. Such a dictionary is realizable as a simple graph if and only
+    if the following conditions are satisfied.
+
+    - each entry must be an integer,
+    - the total number of nodes of degree *k*, computed by
+      ``sum(joint_degrees[k].values()) / k``, must be an integer,
+    - the total number of edges joining nodes of degree *k* with
+      nodes of degree *l* cannot exceed the total number of possible edges,
+    - each diagonal entry ``joint_degrees[k][k]`` must be even (this is
+      a convention assumed by the :func:`joint_degree_graph` function).
+
+
+    Parameters
+    ----------
+    joint_degrees :  dictionary of dictionary of integers
+        A joint degree dictionary in which entry ``joint_degrees[k][l]``
+        is the number of edges joining nodes of degree *k* with nodes of
+        degree *l*.
+
+    Returns
+    -------
+    bool
+        Whether the given joint degree dictionary is realizable as a
+        simple graph.
+
+    References
+    ----------
+    .. [1] M. Gjoka, M. Kurant, A. Markopoulou, "2.5K Graphs: from Sampling
+       to Generation", IEEE Infocom, 2013.
+    .. [2] I. Stanton, A. Pinar, "Constructing and sampling graphs with a
+       prescribed joint degree distribution", Journal of Experimental
+       Algorithmics, 2012.
+    """
+
+    degree_count = {}
+    for k in joint_degrees:
+        if k > 0:
+            k_size = sum(joint_degrees[k].values()) / k
+            if not k_size.is_integer():
+                return False
+            degree_count[k] = k_size
+
+    for k in joint_degrees:
+        for l in joint_degrees[k]:
+            if not float(joint_degrees[k][l]).is_integer():
+                return False
+
+            if (k != l) and (joint_degrees[k][l] > degree_count[k] * degree_count[l]):
+                return False
+            elif k == l:
+                if joint_degrees[k][k] > degree_count[k] * (degree_count[k] - 1):
+                    return False
+                if joint_degrees[k][k] % 2 != 0:
+                    return False
+
+    # if all above conditions have been satisfied then the input
+    # joint degree is realizable as a simple graph.
+    return True
+
+
+def _neighbor_switch(G, w, unsat, h_node_residual, avoid_node_id=None):
+    """Releases one free stub for ``w``, while preserving joint degree in G.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        Graph in which the neighbor switch will take place.
+    w : integer
+        Node id for which we will execute this neighbor switch.
+    unsat : set of integers
+        Set of unsaturated node ids that have the same degree as w.
+    h_node_residual: dictionary of integers
+        Keeps track of the remaining stubs  for a given node.
+    avoid_node_id: integer
+        Node id to avoid when selecting w_prime.
+
+    Notes
+    -----
+    First, it selects *w_prime*, an  unsaturated node that has the same degree
+    as ``w``. Second, it selects *switch_node*, a neighbor node of ``w`` that
+    is not  connected to *w_prime*. Then it executes an edge swap i.e. removes
+    (``w``,*switch_node*) and adds (*w_prime*,*switch_node*). Gjoka et. al. [1]
+    prove that such an edge swap is always possible.
+
+    References
+    ----------
+    .. [1] M. Gjoka, B. Tillman, A. Markopoulou, "Construction of Simple
+       Graphs with a Target Joint Degree Matrix and Beyond", IEEE Infocom, '15
+    """
+
+    if (avoid_node_id is None) or (h_node_residual[avoid_node_id] > 1):
+        # select unsaturated node w_prime that has the same degree as w
+        w_prime = next(iter(unsat))
+    else:
+        # assume that the node pair (v,w) has been selected for connection. if
+        # - neighbor_switch is called for node w,
+        # - nodes v and w have the same degree,
+        # - node v=avoid_node_id has only one stub left,
+        # then prevent v=avoid_node_id from being selected as w_prime.
+
+        iter_var = iter(unsat)
+        while True:
+            w_prime = next(iter_var)
+            if w_prime != avoid_node_id:
+                break
+
+    # select switch_node, a neighbor of w, that is not connected to w_prime
+    w_prime_neighbs = G[w_prime]  # slightly faster declaring this variable
+    for v in G[w]:
+        if (v not in w_prime_neighbs) and (v != w_prime):
+            switch_node = v
+            break
+
+    # remove edge (w,switch_node), add edge (w_prime,switch_node) and update
+    # data structures
+    G.remove_edge(w, switch_node)
+    G.add_edge(w_prime, switch_node)
+    h_node_residual[w] += 1
+    h_node_residual[w_prime] -= 1
+    if h_node_residual[w_prime] == 0:
+        unsat.remove(w_prime)
+
+
+@py_random_state(1)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def joint_degree_graph(joint_degrees, seed=None):
+    """Generates a random simple graph with the given joint degree dictionary.
+
+    Parameters
+    ----------
+    joint_degrees :  dictionary of dictionary of integers
+        A joint degree dictionary in which entry ``joint_degrees[k][l]`` is the
+        number of edges joining nodes of degree *k* with nodes of degree *l*.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    G : Graph
+        A graph with the specified joint degree dictionary.
+
+    Raises
+    ------
+    NetworkXError
+        If *joint_degrees* dictionary is not realizable.
+
+    Notes
+    -----
+    In each iteration of the "while loop" the algorithm picks two disconnected
+    nodes *v* and *w*, of degree *k* and *l* correspondingly,  for which
+    ``joint_degrees[k][l]`` has not reached its target yet. It then adds
+    edge (*v*, *w*) and increases the number of edges in graph G by one.
+
+    The intelligence of the algorithm lies in the fact that  it is always
+    possible to add an edge between such disconnected nodes *v* and *w*,
+    even if one or both nodes do not have free stubs. That is made possible by
+    executing a "neighbor switch", an edge rewiring move that releases
+    a free stub while keeping the joint degree of G the same.
+
+    The algorithm continues for E (number of edges) iterations of
+    the "while loop", at the which point all entries of the given
+    ``joint_degrees[k][l]`` have reached their target values and the
+    construction is complete.
+
+    References
+    ----------
+    ..  [1] M. Gjoka, B. Tillman, A. Markopoulou, "Construction of Simple
+        Graphs with a Target Joint Degree Matrix and Beyond", IEEE Infocom, '15
+
+    Examples
+    --------
+    >>> joint_degrees = {
+    ...     1: {4: 1},
+    ...     2: {2: 2, 3: 2, 4: 2},
+    ...     3: {2: 2, 4: 1},
+    ...     4: {1: 1, 2: 2, 3: 1},
+    ... }
+    >>> G = nx.joint_degree_graph(joint_degrees)
+    >>>
+    """
+
+    if not is_valid_joint_degree(joint_degrees):
+        msg = "Input joint degree dict not realizable as a simple graph"
+        raise nx.NetworkXError(msg)
+
+    # compute degree count from joint_degrees
+    degree_count = {k: sum(l.values()) // k for k, l in joint_degrees.items() if k > 0}
+
+    # start with empty N-node graph
+    N = sum(degree_count.values())
+    G = nx.empty_graph(N)
+
+    # for a given degree group, keep the list of all node ids
+    h_degree_nodelist = {}
+
+    # for a given node, keep track of the remaining stubs
+    h_node_residual = {}
+
+    # populate h_degree_nodelist and h_node_residual
+    nodeid = 0
+    for degree, num_nodes in degree_count.items():
+        h_degree_nodelist[degree] = range(nodeid, nodeid + num_nodes)
+        for v in h_degree_nodelist[degree]:
+            h_node_residual[v] = degree
+        nodeid += int(num_nodes)
+
+    # iterate over every degree pair (k,l) and add the number of edges given
+    # for each pair
+    for k in joint_degrees:
+        for l in joint_degrees[k]:
+            # n_edges_add is the number of edges to add for the
+            # degree pair (k,l)
+            n_edges_add = joint_degrees[k][l]
+
+            if (n_edges_add > 0) and (k >= l):
+                # number of nodes with degree k and l
+                k_size = degree_count[k]
+                l_size = degree_count[l]
+
+                # k_nodes and l_nodes consist of all nodes of degree k and l
+                k_nodes = h_degree_nodelist[k]
+                l_nodes = h_degree_nodelist[l]
+
+                # k_unsat and l_unsat consist of nodes of degree k and l that
+                # are unsaturated (nodes that have at least 1 available stub)
+                k_unsat = {v for v in k_nodes if h_node_residual[v] > 0}
+
+                if k != l:
+                    l_unsat = {w for w in l_nodes if h_node_residual[w] > 0}
+                else:
+                    l_unsat = k_unsat
+                    n_edges_add = joint_degrees[k][l] // 2
+
+                while n_edges_add > 0:
+                    # randomly pick nodes v and w that have degrees k and l
+                    v = k_nodes[seed.randrange(k_size)]
+                    w = l_nodes[seed.randrange(l_size)]
+
+                    # if nodes v and w are disconnected then attempt to connect
+                    if not G.has_edge(v, w) and (v != w):
+                        # if node v has no free stubs then do neighbor switch
+                        if h_node_residual[v] == 0:
+                            _neighbor_switch(G, v, k_unsat, h_node_residual)
+
+                        # if node w has no free stubs then do neighbor switch
+                        if h_node_residual[w] == 0:
+                            if k != l:
+                                _neighbor_switch(G, w, l_unsat, h_node_residual)
+                            else:
+                                _neighbor_switch(
+                                    G, w, l_unsat, h_node_residual, avoid_node_id=v
+                                )
+
+                        # add edge (v, w) and update data structures
+                        G.add_edge(v, w)
+                        h_node_residual[v] -= 1
+                        h_node_residual[w] -= 1
+                        n_edges_add -= 1
+
+                        if h_node_residual[v] == 0:
+                            k_unsat.discard(v)
+                        if h_node_residual[w] == 0:
+                            l_unsat.discard(w)
+    return G
+
+
+@nx._dispatchable(graphs=None)
+def is_valid_directed_joint_degree(in_degrees, out_degrees, nkk):
+    """Checks whether the given directed joint degree input is realizable
+
+    Parameters
+    ----------
+    in_degrees :  list of integers
+        in degree sequence contains the in degrees of nodes.
+    out_degrees : list of integers
+        out degree sequence contains the out degrees of nodes.
+    nkk  :  dictionary of dictionary of integers
+        directed joint degree dictionary. for nodes of out degree k (first
+        level of dict) and nodes of in degree l (second level of dict)
+        describes the number of edges.
+
+    Returns
+    -------
+    boolean
+        returns true if given input is realizable, else returns false.
+
+    Notes
+    -----
+    Here is the list of conditions that the inputs (in/out degree sequences,
+    nkk) need to satisfy for simple directed graph realizability:
+
+    - Condition 0: in_degrees and out_degrees have the same length
+    - Condition 1: nkk[k][l]  is integer for all k,l
+    - Condition 2: sum(nkk[k])/k = number of nodes with partition id k, is an
+                   integer and matching degree sequence
+    - Condition 3: number of edges and non-chords between k and l cannot exceed
+                   maximum possible number of edges
+
+
+    References
+    ----------
+    [1] B. Tillman, A. Markopoulou, C. T. Butts & M. Gjoka,
+        "Construction of Directed 2K Graphs". In Proc. of KDD 2017.
+    """
+    V = {}  # number of nodes with in/out degree.
+    forbidden = {}
+    if len(in_degrees) != len(out_degrees):
+        return False
+
+    for idx in range(len(in_degrees)):
+        i = in_degrees[idx]
+        o = out_degrees[idx]
+        V[(i, 0)] = V.get((i, 0), 0) + 1
+        V[(o, 1)] = V.get((o, 1), 0) + 1
+
+        forbidden[(o, i)] = forbidden.get((o, i), 0) + 1
+
+    S = {}  # number of edges going from in/out degree nodes.
+    for k in nkk:
+        for l in nkk[k]:
+            val = nkk[k][l]
+            if not float(val).is_integer():  # condition 1
+                return False
+
+            if val > 0:
+                S[(k, 1)] = S.get((k, 1), 0) + val
+                S[(l, 0)] = S.get((l, 0), 0) + val
+                # condition 3
+                if val + forbidden.get((k, l), 0) > V[(k, 1)] * V[(l, 0)]:
+                    return False
+
+    return all(S[s] / s[0] == V[s] for s in S)
+
+
+def _directed_neighbor_switch(
+    G, w, unsat, h_node_residual_out, chords, h_partition_in, partition
+):
+    """Releases one free stub for node w, while preserving joint degree in G.
+
+    Parameters
+    ----------
+    G : networkx directed graph
+        graph within which the edge swap will take place.
+    w : integer
+        node id for which we need to perform a neighbor switch.
+    unsat: set of integers
+        set of node ids that have the same degree as w and are unsaturated.
+    h_node_residual_out: dict of integers
+        for a given node, keeps track of the remaining stubs to be added.
+    chords: set of tuples
+        keeps track of available positions to add edges.
+    h_partition_in: dict of integers
+        for a given node, keeps track of its partition id (in degree).
+    partition: integer
+        partition id to check if chords have to be updated.
+
+    Notes
+    -----
+    First, it selects node w_prime that (1) has the same degree as w and
+    (2) is unsaturated. Then, it selects node v, a neighbor of w, that is
+    not connected to w_prime and does an edge swap i.e. removes (w,v) and
+    adds (w_prime,v). If neighbor switch is not possible for w using
+    w_prime and v, then return w_prime; in [1] it's proven that
+    such unsaturated nodes can be used.
+
+    References
+    ----------
+    [1] B. Tillman, A. Markopoulou, C. T. Butts & M. Gjoka,
+        "Construction of Directed 2K Graphs". In Proc. of KDD 2017.
+    """
+    w_prime = unsat.pop()
+    unsat.add(w_prime)
+    # select node t, a neighbor of w, that is not connected to w_prime
+    w_neighbs = list(G.successors(w))
+    # slightly faster declaring this variable
+    w_prime_neighbs = list(G.successors(w_prime))
+
+    for v in w_neighbs:
+        if (v not in w_prime_neighbs) and w_prime != v:
+            # removes (w,v), add (w_prime,v)  and update data structures
+            G.remove_edge(w, v)
+            G.add_edge(w_prime, v)
+
+            if h_partition_in[v] == partition:
+                chords.add((w, v))
+                chords.discard((w_prime, v))
+
+            h_node_residual_out[w] += 1
+            h_node_residual_out[w_prime] -= 1
+            if h_node_residual_out[w_prime] == 0:
+                unsat.remove(w_prime)
+            return None
+
+    # If neighbor switch didn't work, use unsaturated node
+    return w_prime
+
+
+def _directed_neighbor_switch_rev(
+    G, w, unsat, h_node_residual_in, chords, h_partition_out, partition
+):
+    """The reverse of directed_neighbor_switch.
+
+    Parameters
+    ----------
+    G : networkx directed graph
+        graph within which the edge swap will take place.
+    w : integer
+        node id for which we need to perform a neighbor switch.
+    unsat: set of integers
+        set of node ids that have the same degree as w and are unsaturated.
+    h_node_residual_in: dict of integers
+        for a given node, keeps track of the remaining stubs to be added.
+    chords: set of tuples
+        keeps track of available positions to add edges.
+    h_partition_out: dict of integers
+        for a given node, keeps track of its partition id (out degree).
+    partition: integer
+        partition id to check if chords have to be updated.
+
+    Notes
+    -----
+    Same operation as directed_neighbor_switch except it handles this operation
+    for incoming edges instead of outgoing.
+    """
+    w_prime = unsat.pop()
+    unsat.add(w_prime)
+    # slightly faster declaring these as variables.
+    w_neighbs = list(G.predecessors(w))
+    w_prime_neighbs = list(G.predecessors(w_prime))
+    # select node v, a neighbor of w, that is not connected to w_prime.
+    for v in w_neighbs:
+        if (v not in w_prime_neighbs) and w_prime != v:
+            # removes (v,w), add (v,w_prime) and update data structures.
+            G.remove_edge(v, w)
+            G.add_edge(v, w_prime)
+            if h_partition_out[v] == partition:
+                chords.add((v, w))
+                chords.discard((v, w_prime))
+
+            h_node_residual_in[w] += 1
+            h_node_residual_in[w_prime] -= 1
+            if h_node_residual_in[w_prime] == 0:
+                unsat.remove(w_prime)
+            return None
+
+    # If neighbor switch didn't work, use the unsaturated node.
+    return w_prime
+
+
+@py_random_state(3)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def directed_joint_degree_graph(in_degrees, out_degrees, nkk, seed=None):
+    """Generates a random simple directed graph with the joint degree.
+
+    Parameters
+    ----------
+    degree_seq :  list of tuples (of size 3)
+        degree sequence contains tuples of nodes with node id, in degree and
+        out degree.
+    nkk  :  dictionary of dictionary of integers
+        directed joint degree dictionary, for nodes of out degree k (first
+        level of dict) and nodes of in degree l (second level of dict)
+        describes the number of edges.
+    seed : hashable object, optional
+        Seed for random number generator.
+
+    Returns
+    -------
+    G : Graph
+        A directed graph with the specified inputs.
+
+    Raises
+    ------
+    NetworkXError
+        If degree_seq and nkk are not realizable as a simple directed graph.
+
+
+    Notes
+    -----
+    Similarly to the undirected version:
+    In each iteration of the "while loop" the algorithm picks two disconnected
+    nodes v and w, of degree k and l correspondingly,  for which nkk[k][l] has
+    not reached its target yet i.e. (for given k,l): n_edges_add < nkk[k][l].
+    It then adds edge (v,w) and always increases the number of edges in graph G
+    by one.
+
+    The intelligence of the algorithm lies in the fact that  it is always
+    possible to add an edge between disconnected nodes v and w, for which
+    nkk[degree(v)][degree(w)] has not reached its target, even if one or both
+    nodes do not have free stubs. If either node v or w does not have a free
+    stub, we perform a "neighbor switch", an edge rewiring move that releases a
+    free stub while keeping nkk the same.
+
+    The difference for the directed version lies in the fact that neighbor
+    switches might not be able to rewire, but in these cases unsaturated nodes
+    can be reassigned to use instead, see [1] for detailed description and
+    proofs.
+
+    The algorithm continues for E (number of edges in the graph) iterations of
+    the "while loop", at which point all entries of the given nkk[k][l] have
+    reached their target values and the construction is complete.
+
+    References
+    ----------
+    [1] B. Tillman, A. Markopoulou, C. T. Butts & M. Gjoka,
+        "Construction of Directed 2K Graphs". In Proc. of KDD 2017.
+
+    Examples
+    --------
+    >>> in_degrees = [0, 1, 1, 2]
+    >>> out_degrees = [1, 1, 1, 1]
+    >>> nkk = {1: {1: 2, 2: 2}}
+    >>> G = nx.directed_joint_degree_graph(in_degrees, out_degrees, nkk)
+    >>>
+    """
+    if not is_valid_directed_joint_degree(in_degrees, out_degrees, nkk):
+        msg = "Input is not realizable as a simple graph"
+        raise nx.NetworkXError(msg)
+
+    # start with an empty directed graph.
+    G = nx.DiGraph()
+
+    # for a given group, keep the list of all node ids.
+    h_degree_nodelist_in = {}
+    h_degree_nodelist_out = {}
+    # for a given group, keep the list of all unsaturated node ids.
+    h_degree_nodelist_in_unsat = {}
+    h_degree_nodelist_out_unsat = {}
+    # for a given node, keep track of the remaining stubs to be added.
+    h_node_residual_out = {}
+    h_node_residual_in = {}
+    # for a given node, keep track of the partition id.
+    h_partition_out = {}
+    h_partition_in = {}
+    # keep track of non-chords between pairs of partition ids.
+    non_chords = {}
+
+    # populate data structures
+    for idx, i in enumerate(in_degrees):
+        idx = int(idx)
+        if i > 0:
+            h_degree_nodelist_in.setdefault(i, [])
+            h_degree_nodelist_in_unsat.setdefault(i, set())
+            h_degree_nodelist_in[i].append(idx)
+            h_degree_nodelist_in_unsat[i].add(idx)
+            h_node_residual_in[idx] = i
+            h_partition_in[idx] = i
+
+    for idx, o in enumerate(out_degrees):
+        o = out_degrees[idx]
+        non_chords[(o, in_degrees[idx])] = non_chords.get((o, in_degrees[idx]), 0) + 1
+        idx = int(idx)
+        if o > 0:
+            h_degree_nodelist_out.setdefault(o, [])
+            h_degree_nodelist_out_unsat.setdefault(o, set())
+            h_degree_nodelist_out[o].append(idx)
+            h_degree_nodelist_out_unsat[o].add(idx)
+            h_node_residual_out[idx] = o
+            h_partition_out[idx] = o
+
+        G.add_node(idx)
+
+    nk_in = {}
+    nk_out = {}
+    for p in h_degree_nodelist_in:
+        nk_in[p] = len(h_degree_nodelist_in[p])
+    for p in h_degree_nodelist_out:
+        nk_out[p] = len(h_degree_nodelist_out[p])
+
+    # iterate over every degree pair (k,l) and add the number of edges given
+    # for each pair.
+    for k in nkk:
+        for l in nkk[k]:
+            n_edges_add = nkk[k][l]
+
+            if n_edges_add > 0:
+                # chords contains a random set of potential edges.
+                chords = set()
+
+                k_len = nk_out[k]
+                l_len = nk_in[l]
+                chords_sample = seed.sample(
+                    range(k_len * l_len), n_edges_add + non_chords.get((k, l), 0)
+                )
+
+                num = 0
+                while len(chords) < n_edges_add:
+                    i = h_degree_nodelist_out[k][chords_sample[num] % k_len]
+                    j = h_degree_nodelist_in[l][chords_sample[num] // k_len]
+                    num += 1
+                    if i != j:
+                        chords.add((i, j))
+
+                # k_unsat and l_unsat consist of nodes of in/out degree k and l
+                # that are unsaturated i.e. those nodes that have at least one
+                # available stub
+                k_unsat = h_degree_nodelist_out_unsat[k]
+                l_unsat = h_degree_nodelist_in_unsat[l]
+
+                while n_edges_add > 0:
+                    v, w = chords.pop()
+                    chords.add((v, w))
+
+                    # if node v has no free stubs then do neighbor switch.
+                    if h_node_residual_out[v] == 0:
+                        _v = _directed_neighbor_switch(
+                            G,
+                            v,
+                            k_unsat,
+                            h_node_residual_out,
+                            chords,
+                            h_partition_in,
+                            l,
+                        )
+                        if _v is not None:
+                            v = _v
+
+                    # if node w has no free stubs then do neighbor switch.
+                    if h_node_residual_in[w] == 0:
+                        _w = _directed_neighbor_switch_rev(
+                            G,
+                            w,
+                            l_unsat,
+                            h_node_residual_in,
+                            chords,
+                            h_partition_out,
+                            k,
+                        )
+                        if _w is not None:
+                            w = _w
+
+                    # add edge (v,w) and update data structures.
+                    G.add_edge(v, w)
+                    h_node_residual_out[v] -= 1
+                    h_node_residual_in[w] -= 1
+                    n_edges_add -= 1
+                    chords.discard((v, w))
+
+                    if h_node_residual_out[v] == 0:
+                        k_unsat.discard(v)
+                    if h_node_residual_in[w] == 0:
+                        l_unsat.discard(w)
+    return G
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/lattice.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/lattice.py
new file mode 100644
index 0000000000000000000000000000000000000000..61721c4317995228209305de245c74d64d8095f4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/lattice.py
@@ -0,0 +1,405 @@
+"""Functions for generating grid graphs and lattices
+
+The :func:`grid_2d_graph`, :func:`triangular_lattice_graph`, and
+:func:`hexagonal_lattice_graph` functions correspond to the three
+`regular tilings of the plane`_, the square, triangular, and hexagonal
+tilings, respectively. :func:`grid_graph` and :func:`hypercube_graph`
+are similar for arbitrary dimensions. Useful relevant discussion can
+be found about `Triangular Tiling`_, and `Square, Hex and Triangle Grids`_
+
+.. _regular tilings of the plane: https://en.wikipedia.org/wiki/List_of_regular_polytopes_and_compounds#Euclidean_tilings
+.. _Square, Hex and Triangle Grids: http://www-cs-students.stanford.edu/~amitp/game-programming/grids/
+.. _Triangular Tiling: https://en.wikipedia.org/wiki/Triangular_tiling
+
+"""
+
+from itertools import repeat
+from math import sqrt
+
+import networkx as nx
+from networkx.classes import set_node_attributes
+from networkx.exception import NetworkXError
+from networkx.generators.classic import cycle_graph, empty_graph, path_graph
+from networkx.relabel import relabel_nodes
+from networkx.utils import flatten, nodes_or_number, pairwise
+
+__all__ = [
+    "grid_2d_graph",
+    "grid_graph",
+    "hypercube_graph",
+    "triangular_lattice_graph",
+    "hexagonal_lattice_graph",
+]
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+@nodes_or_number([0, 1])
+def grid_2d_graph(m, n, periodic=False, create_using=None):
+    """Returns the two-dimensional grid graph.
+
+    The grid graph has each node connected to its four nearest neighbors.
+
+    Parameters
+    ----------
+    m, n : int or iterable container of nodes
+        If an integer, nodes are from `range(n)`.
+        If a container, elements become the coordinate of the nodes.
+
+    periodic : bool or iterable
+        If `periodic` is True, both dimensions are periodic. If False, none
+        are periodic.  If `periodic` is iterable, it should yield 2 bool
+        values indicating whether the 1st and 2nd axes, respectively, are
+        periodic.
+
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+        Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    NetworkX graph
+        The (possibly periodic) grid graph of the specified dimensions.
+
+    See Also
+    --------
+    triangular_lattice_graph, hexagonal_lattice_graph :
+        Other 2D lattice graphs
+    grid_graph, hypercube_graph :
+        N-dimensional lattice graphs
+    """
+    G = empty_graph(0, create_using)
+    row_name, rows = m
+    col_name, cols = n
+    G.add_nodes_from((i, j) for i in rows for j in cols)
+    G.add_edges_from(((i, j), (pi, j)) for pi, i in pairwise(rows) for j in cols)
+    G.add_edges_from(((i, j), (i, pj)) for i in rows for pj, j in pairwise(cols))
+
+    try:
+        periodic_r, periodic_c = periodic
+    except TypeError:
+        periodic_r = periodic_c = periodic
+
+    if periodic_r and len(rows) > 2:
+        first = rows[0]
+        last = rows[-1]
+        G.add_edges_from(((first, j), (last, j)) for j in cols)
+    if periodic_c and len(cols) > 2:
+        first = cols[0]
+        last = cols[-1]
+        G.add_edges_from(((i, first), (i, last)) for i in rows)
+    # both directions for directed
+    if G.is_directed():
+        G.add_edges_from((v, u) for u, v in G.edges())
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def grid_graph(dim, periodic=False):
+    """Returns the *n*-dimensional grid graph.
+
+    The dimension *n* is the length of the list `dim` and the size in
+    each dimension is the value of the corresponding list element.
+
+    Parameters
+    ----------
+    dim : list or tuple of numbers or iterables of nodes
+        'dim' is a tuple or list with, for each dimension, either a number
+        that is the size of that dimension or an iterable of nodes for
+        that dimension. The dimension of the grid_graph is the length
+        of `dim`.
+
+    periodic : bool or iterable
+        If `periodic` is True, all dimensions are periodic. If False all
+        dimensions are not periodic. If `periodic` is iterable, it should
+        yield `dim` bool values each of which indicates whether the
+        corresponding axis is periodic.
+
+    Returns
+    -------
+    NetworkX graph
+        The (possibly periodic) grid graph of the specified dimensions.
+
+    See Also
+    --------
+    grid_2d_graph, triangular_lattice_graph, hexagonal_lattice_graph :
+        2D lattice graphs
+    hypercube_graph :
+        A special case of `grid_graph` where all elements of `dim` are identical
+
+    Examples
+    --------
+    To produce a 2 by 3 by 4 grid graph, a graph on 24 nodes:
+
+    >>> from networkx import grid_graph
+    >>> G = grid_graph(dim=(2, 3, 4))
+    >>> len(G)
+    24
+    >>> G = grid_graph(dim=(range(7, 9), range(3, 6)))
+    >>> len(G)
+    6
+    """
+    from collections.abc import Iterable
+
+    from networkx.algorithms.operators.product import cartesian_product
+
+    if not dim:
+        return empty_graph(0)
+
+    periodic = repeat(periodic) if not isinstance(periodic, Iterable) else periodic
+    func = (cycle_graph if p else path_graph for p in periodic)
+
+    G = next(func)(dim[0])
+    for current_dim in dim[1:]:
+        Gnew = next(func)(current_dim)
+        G = cartesian_product(Gnew, G)
+    # graph G is done but has labels of the form (1, (2, (3, 1))) so relabel
+    H = relabel_nodes(G, flatten)
+    return H
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def hypercube_graph(n):
+    """Returns the *n*-dimensional hypercube graph.
+
+    The *n*-dimensional hypercube graph [1]_ has ``2**n`` nodes, each represented as
+    a binary integer in the form of a tuple of 0's and 1's. Edges exist between
+    nodes that differ in exactly one bit.
+
+    Parameters
+    ----------
+    n : int
+        Dimension of the hypercube, must be a positive integer.
+
+    Returns
+    -------
+    networkx.Graph
+        The n-dimensional hypercube graph as an undirected graph.
+
+    See Also
+    --------
+    grid_2d_graph, triangular_lattice_graph, hexagonal_lattice_graph :
+        2D lattice graphs
+    grid_graph :
+        A more general N-dimensional grid
+
+    Examples
+    --------
+    >>> G = nx.hypercube_graph(3)
+    >>> list(G.neighbors((0, 0, 0)))
+    [(1, 0, 0), (0, 1, 0), (0, 0, 1)]
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Hypercube_graph
+    """
+    dim = n * [2]
+    G = grid_graph(dim)
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def triangular_lattice_graph(
+    m, n, periodic=False, with_positions=True, create_using=None
+):
+    r"""Returns the $m$ by $n$ triangular lattice graph.
+
+    The `triangular lattice graph`_ is a two-dimensional `grid graph`_ in
+    which each square unit has a diagonal edge (each grid unit has a chord).
+
+    The returned graph has $m$ rows and $n$ columns of triangles. Rows and
+    columns include both triangles pointing up and down. Rows form a strip
+    of constant height. Columns form a series of diamond shapes, staggered
+    with the columns on either side. Another way to state the size is that
+    the nodes form a grid of `m+1` rows and `(n + 1) // 2` columns.
+    The odd row nodes are shifted horizontally relative to the even rows.
+
+    Directed graph types have edges pointed up or right.
+
+    Positions of nodes are computed by default or `with_positions is True`.
+    The position of each node (embedded in a euclidean plane) is stored in
+    the graph using equilateral triangles with sidelength 1.
+    The height between rows of nodes is thus $\sqrt(3)/2$.
+    Nodes lie in the first quadrant with the node $(0, 0)$ at the origin.
+
+    .. _triangular lattice graph: http://mathworld.wolfram.com/TriangularGrid.html
+    .. _grid graph: http://www-cs-students.stanford.edu/~amitp/game-programming/grids/
+    .. _Triangular Tiling: https://en.wikipedia.org/wiki/Triangular_tiling
+
+    Parameters
+    ----------
+    m : int
+        The number of rows in the lattice.
+
+    n : int
+        The number of columns in the lattice.
+
+    periodic : bool (default: False)
+        If True, join the boundary vertices of the grid using periodic
+        boundary conditions. The join between boundaries is the final row
+        and column of triangles. This means there is one row and one column
+        fewer nodes for the periodic lattice. Periodic lattices require
+        `m >= 3`, `n >= 5` and are allowed but misaligned if `m` or `n` are odd
+
+    with_positions : bool (default: True)
+        Store the coordinates of each node in the graph node attribute 'pos'.
+        The coordinates provide a lattice with equilateral triangles.
+        Periodic positions shift the nodes vertically in a nonlinear way so
+        the edges don't overlap so much.
+
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+        Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    NetworkX graph
+        The *m* by *n* triangular lattice graph.
+
+    See Also
+    --------
+    grid_2d_graph, hexagonal_lattice_graph :
+        Other 2D lattice graphs
+    grid_graph, hypercube_graph :
+        N-dimensional lattice graphs
+    """
+    H = empty_graph(0, create_using)
+    if n == 0 or m == 0:
+        return H
+    if periodic:
+        if n < 5 or m < 3:
+            msg = f"m > 2 and n > 4 required for periodic. m={m}, n={n}"
+            raise NetworkXError(msg)
+
+    N = (n + 1) // 2  # number of nodes in row
+    rows = range(m + 1)
+    cols = range(N + 1)
+    # Make grid
+    H.add_edges_from(((i, j), (i + 1, j)) for j in rows for i in cols[:N])
+    H.add_edges_from(((i, j), (i, j + 1)) for j in rows[:m] for i in cols)
+    # add diagonals
+    H.add_edges_from(((i, j), (i + 1, j + 1)) for j in rows[1:m:2] for i in cols[:N])
+    H.add_edges_from(((i + 1, j), (i, j + 1)) for j in rows[:m:2] for i in cols[:N])
+
+    # identify boundary nodes if periodic
+    if periodic is True:
+        for i in cols:
+            H = nx.contracted_nodes(H, (i, 0), (i, m), store_contraction_as=None)
+        for j in rows[:m]:
+            H = nx.contracted_nodes(H, (0, j), (N, j), store_contraction_as=None)
+    elif n % 2:
+        # remove extra nodes
+        H.remove_nodes_from((N, j) for j in rows[1::2])
+
+    # Add position node attributes
+    if with_positions:
+        ii = (i for i in cols for j in rows)
+        jj = (j for i in cols for j in rows)
+        xx = (0.5 * (j % 2) + i for i in cols for j in rows)
+        h = sqrt(3) / 2
+        if periodic:
+            yy = (h * j + 0.01 * i * i for i in cols for j in rows)
+        else:
+            yy = (h * j for i in cols for j in rows)
+        pos = {(i, j): (x, y) for i, j, x, y in zip(ii, jj, xx, yy) if (i, j) in H}
+        set_node_attributes(H, pos, "pos")
+    return H
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def hexagonal_lattice_graph(
+    m, n, periodic=False, with_positions=True, create_using=None
+):
+    """Returns an `m` by `n` hexagonal lattice graph.
+
+    The *hexagonal lattice graph* is a graph whose nodes and edges are
+    the `hexagonal tiling`_ of the plane.
+
+    The returned graph will have `m` rows and `n` columns of hexagons.
+    `Odd numbered columns`_ are shifted up relative to even numbered columns.
+
+    Positions of nodes are computed by default or `with_positions is True`.
+    Node positions creating the standard embedding in the plane
+    with sidelength 1 and are stored in the node attribute 'pos'.
+    `pos = nx.get_node_attributes(G, 'pos')` creates a dict ready for drawing.
+
+    .. _hexagonal tiling: https://en.wikipedia.org/wiki/Hexagonal_tiling
+    .. _Odd numbered columns: http://www-cs-students.stanford.edu/~amitp/game-programming/grids/
+
+    Parameters
+    ----------
+    m : int
+        The number of rows of hexagons in the lattice.
+
+    n : int
+        The number of columns of hexagons in the lattice.
+
+    periodic : bool
+        Whether to make a periodic grid by joining the boundary vertices.
+        For this to work `n` must be even and both `n > 1` and `m > 1`.
+        The periodic connections create another row and column of hexagons
+        so these graphs have fewer nodes as boundary nodes are identified.
+
+    with_positions : bool (default: True)
+        Store the coordinates of each node in the graph node attribute 'pos'.
+        The coordinates provide a lattice with vertical columns of hexagons
+        offset to interleave and cover the plane.
+        Periodic positions shift the nodes vertically in a nonlinear way so
+        the edges don't overlap so much.
+
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+        Graph type to create. If graph instance, then cleared before populated.
+        If graph is directed, edges will point up or right.
+
+    Returns
+    -------
+    NetworkX graph
+        The *m* by *n* hexagonal lattice graph.
+
+    See Also
+    --------
+    grid_2d_graph, triangular_lattice_graph :
+        Other 2D lattice graphs
+    grid_graph, hypercube_graph :
+        N-dimensional lattice graphs
+    """
+    G = empty_graph(0, create_using)
+    if m == 0 or n == 0:
+        return G
+    if periodic and (n % 2 == 1 or m < 2 or n < 2):
+        msg = "periodic hexagonal lattice needs m > 1, n > 1 and even n"
+        raise NetworkXError(msg)
+
+    M = 2 * m  # twice as many nodes as hexagons vertically
+    rows = range(M + 2)
+    cols = range(n + 1)
+    # make lattice
+    col_edges = (((i, j), (i, j + 1)) for i in cols for j in rows[: M + 1])
+    row_edges = (((i, j), (i + 1, j)) for i in cols[:n] for j in rows if i % 2 == j % 2)
+    G.add_edges_from(col_edges)
+    G.add_edges_from(row_edges)
+    # Remove corner nodes with one edge
+    G.remove_node((0, M + 1))
+    G.remove_node((n, (M + 1) * (n % 2)))
+
+    # identify boundary nodes if periodic
+    if periodic:
+        for i in cols[:n]:
+            G = nx.contracted_nodes(G, (i, 0), (i, M), store_contraction_as=None)
+        for i in cols[1:]:
+            G = nx.contracted_nodes(G, (i, 1), (i, M + 1), store_contraction_as=None)
+        for j in rows[1:M]:
+            G = nx.contracted_nodes(G, (0, j), (n, j), store_contraction_as=None)
+        G.remove_node((n, M))
+
+    # calc position in embedded space
+    if with_positions:
+        ii = (i for i in cols for j in rows)
+        jj = (j for i in cols for j in rows)
+        xx = (0.5 + i + i // 2 + (j % 2) * ((i % 2) - 0.5) for i in cols for j in rows)
+        h = sqrt(3) / 2
+        if periodic:
+            yy = (h * j + 0.01 * i * i for i in cols for j in rows)
+        else:
+            yy = (h * j for i in cols for j in rows)
+        # exclude nodes not in G
+        pos = {(i, j): (x, y) for i, j, x, y in zip(ii, jj, xx, yy) if (i, j) in G}
+        set_node_attributes(G, pos, "pos")
+    return G
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/line.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/line.py
new file mode 100644
index 0000000000000000000000000000000000000000..90997146bde4a04b4b53c475e300c4a63b987f38
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/line.py
@@ -0,0 +1,501 @@
+"""Functions for generating line graphs."""
+
+from collections import defaultdict
+from functools import partial
+from itertools import combinations
+
+import networkx as nx
+from networkx.utils import arbitrary_element
+from networkx.utils.decorators import not_implemented_for
+
+__all__ = ["line_graph", "inverse_line_graph"]
+
+
+@nx._dispatchable(returns_graph=True)
+def line_graph(G, create_using=None):
+    r"""Returns the line graph of the graph or digraph `G`.
+
+    The line graph of a graph `G` has a node for each edge in `G` and an
+    edge joining those nodes if the two edges in `G` share a common node. For
+    directed graphs, nodes are adjacent exactly when the edges they represent
+    form a directed path of length two.
+
+    The nodes of the line graph are 2-tuples of nodes in the original graph (or
+    3-tuples for multigraphs, with the key of the edge as the third element).
+
+    For information about self-loops and more discussion, see the **Notes**
+    section below.
+
+    Parameters
+    ----------
+    G : graph
+        A NetworkX Graph, DiGraph, MultiGraph, or MultiDigraph.
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    L : graph
+        The line graph of G.
+
+    Examples
+    --------
+    >>> G = nx.star_graph(3)
+    >>> L = nx.line_graph(G)
+    >>> print(sorted(map(sorted, L.edges())))  # makes a 3-clique, K3
+    [[(0, 1), (0, 2)], [(0, 1), (0, 3)], [(0, 2), (0, 3)]]
+
+    Edge attributes from `G` are not copied over as node attributes in `L`, but
+    attributes can be copied manually:
+
+    >>> G = nx.path_graph(4)
+    >>> G.add_edges_from((u, v, {"tot": u + v}) for u, v in G.edges)
+    >>> G.edges(data=True)
+    EdgeDataView([(0, 1, {'tot': 1}), (1, 2, {'tot': 3}), (2, 3, {'tot': 5})])
+    >>> H = nx.line_graph(G)
+    >>> H.add_nodes_from((node, G.edges[node]) for node in H)
+    >>> H.nodes(data=True)
+    NodeDataView({(0, 1): {'tot': 1}, (2, 3): {'tot': 5}, (1, 2): {'tot': 3}})
+
+    Notes
+    -----
+    Graph, node, and edge data are not propagated to the new graph. For
+    undirected graphs, the nodes in G must be sortable, otherwise the
+    constructed line graph may not be correct.
+
+    *Self-loops in undirected graphs*
+
+    For an undirected graph `G` without multiple edges, each edge can be
+    written as a set `\{u, v\}`.  Its line graph `L` has the edges of `G` as
+    its nodes. If `x` and `y` are two nodes in `L`, then `\{x, y\}` is an edge
+    in `L` if and only if the intersection of `x` and `y` is nonempty. Thus,
+    the set of all edges is determined by the set of all pairwise intersections
+    of edges in `G`.
+
+    Trivially, every edge in G would have a nonzero intersection with itself,
+    and so every node in `L` should have a self-loop. This is not so
+    interesting, and the original context of line graphs was with simple
+    graphs, which had no self-loops or multiple edges. The line graph was also
+    meant to be a simple graph and thus, self-loops in `L` are not part of the
+    standard definition of a line graph. In a pairwise intersection matrix,
+    this is analogous to excluding the diagonal entries from the line graph
+    definition.
+
+    Self-loops and multiple edges in `G` add nodes to `L` in a natural way, and
+    do not require any fundamental changes to the definition. It might be
+    argued that the self-loops we excluded before should now be included.
+    However, the self-loops are still "trivial" in some sense and thus, are
+    usually excluded.
+
+    *Self-loops in directed graphs*
+
+    For a directed graph `G` without multiple edges, each edge can be written
+    as a tuple `(u, v)`. Its line graph `L` has the edges of `G` as its
+    nodes. If `x` and `y` are two nodes in `L`, then `(x, y)` is an edge in `L`
+    if and only if the tail of `x` matches the head of `y`, for example, if `x
+    = (a, b)` and `y = (b, c)` for some vertices `a`, `b`, and `c` in `G`.
+
+    Due to the directed nature of the edges, it is no longer the case that
+    every edge in `G` should have a self-loop in `L`. Now, the only time
+    self-loops arise is if a node in `G` itself has a self-loop.  So such
+    self-loops are no longer "trivial" but instead, represent essential
+    features of the topology of `G`. For this reason, the historical
+    development of line digraphs is such that self-loops are included. When the
+    graph `G` has multiple edges, once again only superficial changes are
+    required to the definition.
+
+    References
+    ----------
+    * Harary, Frank, and Norman, Robert Z., "Some properties of line digraphs",
+      Rend. Circ. Mat. Palermo, II. Ser. 9 (1960), 161--168.
+    * Hemminger, R. L.; Beineke, L. W. (1978), "Line graphs and line digraphs",
+      in Beineke, L. W.; Wilson, R. J., Selected Topics in Graph Theory,
+      Academic Press Inc., pp. 271--305.
+
+    """
+    if G.is_directed():
+        L = _lg_directed(G, create_using=create_using)
+    else:
+        L = _lg_undirected(G, selfloops=False, create_using=create_using)
+    return L
+
+
+def _lg_directed(G, create_using=None):
+    """Returns the line graph L of the (multi)digraph G.
+
+    Edges in G appear as nodes in L, represented as tuples of the form (u,v)
+    or (u,v,key) if G is a multidigraph. A node in L corresponding to the edge
+    (u,v) is connected to every node corresponding to an edge (v,w).
+
+    Parameters
+    ----------
+    G : digraph
+        A directed graph or directed multigraph.
+    create_using : NetworkX graph constructor, optional
+       Graph type to create. If graph instance, then cleared before populated.
+       Default is to use the same graph class as `G`.
+
+    """
+    L = nx.empty_graph(0, create_using, default=G.__class__)
+
+    # Create a graph specific edge function.
+    get_edges = partial(G.edges, keys=True) if G.is_multigraph() else G.edges
+
+    for from_node in get_edges():
+        # from_node is: (u,v) or (u,v,key)
+        L.add_node(from_node)
+        for to_node in get_edges(from_node[1]):
+            L.add_edge(from_node, to_node)
+
+    return L
+
+
+def _lg_undirected(G, selfloops=False, create_using=None):
+    """Returns the line graph L of the (multi)graph G.
+
+    Edges in G appear as nodes in L, represented as sorted tuples of the form
+    (u,v), or (u,v,key) if G is a multigraph. A node in L corresponding to
+    the edge {u,v} is connected to every node corresponding to an edge that
+    involves u or v.
+
+    Parameters
+    ----------
+    G : graph
+        An undirected graph or multigraph.
+    selfloops : bool
+        If `True`, then self-loops are included in the line graph. If `False`,
+        they are excluded.
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Notes
+    -----
+    The standard algorithm for line graphs of undirected graphs does not
+    produce self-loops.
+
+    """
+    L = nx.empty_graph(0, create_using, default=G.__class__)
+
+    # Graph specific functions for edges.
+    get_edges = partial(G.edges, keys=True) if G.is_multigraph() else G.edges
+
+    # Determine if we include self-loops or not.
+    shift = 0 if selfloops else 1
+
+    # Introduce numbering of nodes
+    node_index = {n: i for i, n in enumerate(G)}
+
+    # Lift canonical representation of nodes to edges in line graph
+    def edge_key_function(edge):
+        return node_index[edge[0]], node_index[edge[1]]
+
+    edges = set()
+    for u in G:
+        # Label nodes as a sorted tuple of nodes in original graph.
+        # Decide on representation of {u, v} as (u, v) or (v, u) depending on node_index.
+        # -> This ensures a canonical representation and avoids comparing values of different types.
+        nodes = [tuple(sorted(x[:2], key=node_index.get)) + x[2:] for x in get_edges(u)]
+
+        if len(nodes) == 1:
+            # Then the edge will be an isolated node in L.
+            L.add_node(nodes[0])
+
+        # Add a clique of `nodes` to graph. To prevent double adding edges,
+        # especially important for multigraphs, we store the edges in
+        # canonical form in a set.
+        for i, a in enumerate(nodes):
+            edges.update(
+                [
+                    tuple(sorted((a, b), key=edge_key_function))
+                    for b in nodes[i + shift :]
+                ]
+            )
+
+    L.add_edges_from(edges)
+    return L
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable(returns_graph=True)
+def inverse_line_graph(G):
+    """Returns the inverse line graph of graph G.
+
+    If H is a graph, and G is the line graph of H, such that G = L(H).
+    Then H is the inverse line graph of G.
+
+    Not all graphs are line graphs and these do not have an inverse line graph.
+    In these cases this function raises a NetworkXError.
+
+    Parameters
+    ----------
+    G : graph
+        A NetworkX Graph
+
+    Returns
+    -------
+    H : graph
+        The inverse line graph of G.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If G is directed or a multigraph
+
+    NetworkXError
+        If G is not a line graph
+
+    Notes
+    -----
+    This is an implementation of the Roussopoulos algorithm[1]_.
+
+    If G consists of multiple components, then the algorithm doesn't work.
+    You should invert every component separately:
+
+    >>> K5 = nx.complete_graph(5)
+    >>> P4 = nx.Graph([("a", "b"), ("b", "c"), ("c", "d")])
+    >>> G = nx.union(K5, P4)
+    >>> root_graphs = []
+    >>> for comp in nx.connected_components(G):
+    ...     root_graphs.append(nx.inverse_line_graph(G.subgraph(comp)))
+    >>> len(root_graphs)
+    2
+
+    References
+    ----------
+    .. [1] Roussopoulos, N.D. , "A max {m, n} algorithm for determining the graph H from
+       its line graph G", Information Processing Letters 2, (1973), 108--112, ISSN 0020-0190,
+       `DOI link `_
+
+    """
+    if G.number_of_nodes() == 0:
+        return nx.empty_graph(1)
+    elif G.number_of_nodes() == 1:
+        v = arbitrary_element(G)
+        a = (v, 0)
+        b = (v, 1)
+        H = nx.Graph([(a, b)])
+        return H
+    elif G.number_of_nodes() > 1 and G.number_of_edges() == 0:
+        msg = (
+            "inverse_line_graph() doesn't work on an edgeless graph. "
+            "Please use this function on each component separately."
+        )
+        raise nx.NetworkXError(msg)
+
+    if nx.number_of_selfloops(G) != 0:
+        msg = (
+            "A line graph as generated by NetworkX has no selfloops, so G has no "
+            "inverse line graph. Please remove the selfloops from G and try again."
+        )
+        raise nx.NetworkXError(msg)
+
+    starting_cell = _select_starting_cell(G)
+    P = _find_partition(G, starting_cell)
+    # count how many times each vertex appears in the partition set
+    P_count = {u: 0 for u in G.nodes}
+    for p in P:
+        for u in p:
+            P_count[u] += 1
+
+    if max(P_count.values()) > 2:
+        msg = "G is not a line graph (vertex found in more than two partition cells)"
+        raise nx.NetworkXError(msg)
+    W = tuple((u,) for u in P_count if P_count[u] == 1)
+    H = nx.Graph()
+    H.add_nodes_from(P)
+    H.add_nodes_from(W)
+    for a, b in combinations(H.nodes, 2):
+        if any(a_bit in b for a_bit in a):
+            H.add_edge(a, b)
+    return H
+
+
+def _triangles(G, e):
+    """Return list of all triangles containing edge e"""
+    u, v = e
+    if u not in G:
+        raise nx.NetworkXError(f"Vertex {u} not in graph")
+    if v not in G[u]:
+        raise nx.NetworkXError(f"Edge ({u}, {v}) not in graph")
+    triangle_list = []
+    for x in G[u]:
+        if x in G[v]:
+            triangle_list.append((u, v, x))
+    return triangle_list
+
+
+def _odd_triangle(G, T):
+    """Test whether T is an odd triangle in G
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+    T : 3-tuple of vertices forming triangle in G
+
+    Returns
+    -------
+    True is T is an odd triangle
+    False otherwise
+
+    Raises
+    ------
+    NetworkXError
+        T is not a triangle in G
+
+    Notes
+    -----
+    An odd triangle is one in which there exists another vertex in G which is
+    adjacent to either exactly one or exactly all three of the vertices in the
+    triangle.
+
+    """
+    for u in T:
+        if u not in G.nodes():
+            raise nx.NetworkXError(f"Vertex {u} not in graph")
+    for e in list(combinations(T, 2)):
+        if e[0] not in G[e[1]]:
+            raise nx.NetworkXError(f"Edge ({e[0]}, {e[1]}) not in graph")
+
+    T_nbrs = defaultdict(int)
+    for t in T:
+        for v in G[t]:
+            if v not in T:
+                T_nbrs[v] += 1
+    return any(T_nbrs[v] in [1, 3] for v in T_nbrs)
+
+
+def _find_partition(G, starting_cell):
+    """Find a partition of the vertices of G into cells of complete graphs
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+    starting_cell : tuple of vertices in G which form a cell
+
+    Returns
+    -------
+    List of tuples of vertices of G
+
+    Raises
+    ------
+    NetworkXError
+        If a cell is not a complete subgraph then G is not a line graph
+    """
+    G_partition = G.copy()
+    P = [starting_cell]  # partition set
+    G_partition.remove_edges_from(list(combinations(starting_cell, 2)))
+    # keep list of partitioned nodes which might have an edge in G_partition
+    partitioned_vertices = list(starting_cell)
+    while G_partition.number_of_edges() > 0:
+        # there are still edges left and so more cells to be made
+        u = partitioned_vertices.pop()
+        deg_u = len(G_partition[u])
+        if deg_u != 0:
+            # if u still has edges then we need to find its other cell
+            # this other cell must be a complete subgraph or else G is
+            # not a line graph
+            new_cell = [u] + list(G_partition[u])
+            for u in new_cell:
+                for v in new_cell:
+                    if (u != v) and (v not in G_partition[u]):
+                        msg = (
+                            "G is not a line graph "
+                            "(partition cell not a complete subgraph)"
+                        )
+                        raise nx.NetworkXError(msg)
+            P.append(tuple(new_cell))
+            G_partition.remove_edges_from(list(combinations(new_cell, 2)))
+            partitioned_vertices += new_cell
+    return P
+
+
+def _select_starting_cell(G, starting_edge=None):
+    """Select a cell to initiate _find_partition
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+    starting_edge: an edge to build the starting cell from
+
+    Returns
+    -------
+    Tuple of vertices in G
+
+    Raises
+    ------
+    NetworkXError
+        If it is determined that G is not a line graph
+
+    Notes
+    -----
+    If starting edge not specified then pick an arbitrary edge - doesn't
+    matter which. However, this function may call itself requiring a
+    specific starting edge. Note that the r, s notation for counting
+    triangles is the same as in the Roussopoulos paper cited above.
+    """
+    if starting_edge is None:
+        e = arbitrary_element(G.edges())
+    else:
+        e = starting_edge
+        if e[0] not in G.nodes():
+            raise nx.NetworkXError(f"Vertex {e[0]} not in graph")
+        if e[1] not in G[e[0]]:
+            msg = f"starting_edge ({e[0]}, {e[1]}) is not in the Graph"
+            raise nx.NetworkXError(msg)
+    e_triangles = _triangles(G, e)
+    r = len(e_triangles)
+    if r == 0:
+        # there are no triangles containing e, so the starting cell is just e
+        starting_cell = e
+    elif r == 1:
+        # there is exactly one triangle, T, containing e. If other 2 edges
+        # of T belong only to this triangle then T is starting cell
+        T = e_triangles[0]
+        a, b, c = T
+        # ab was original edge so check the other 2 edges
+        ac_edges = len(_triangles(G, (a, c)))
+        bc_edges = len(_triangles(G, (b, c)))
+        if ac_edges == 1:
+            if bc_edges == 1:
+                starting_cell = T
+            else:
+                return _select_starting_cell(G, starting_edge=(b, c))
+        else:
+            return _select_starting_cell(G, starting_edge=(a, c))
+    else:
+        # r >= 2 so we need to count the number of odd triangles, s
+        s = 0
+        odd_triangles = []
+        for T in e_triangles:
+            if _odd_triangle(G, T):
+                s += 1
+                odd_triangles.append(T)
+        if r == 2 and s == 0:
+            # in this case either triangle works, so just use T
+            starting_cell = T
+        elif r - 1 <= s <= r:
+            # check if odd triangles containing e form complete subgraph
+            triangle_nodes = set()
+            for T in odd_triangles:
+                for x in T:
+                    triangle_nodes.add(x)
+
+            for u in triangle_nodes:
+                for v in triangle_nodes:
+                    if u != v and (v not in G[u]):
+                        msg = (
+                            "G is not a line graph (odd triangles "
+                            "do not form complete subgraph)"
+                        )
+                        raise nx.NetworkXError(msg)
+            # otherwise then we can use this as the starting cell
+            starting_cell = tuple(triangle_nodes)
+
+        else:
+            msg = (
+                "G is not a line graph (incorrect number of "
+                "odd triangles around starting edge)"
+            )
+            raise nx.NetworkXError(msg)
+    return starting_cell
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/mycielski.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/mycielski.py
new file mode 100644
index 0000000000000000000000000000000000000000..804b903692853d3c45b3b1b20898efeee9b71a5e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/mycielski.py
@@ -0,0 +1,110 @@
+"""Functions related to the Mycielski Operation and the Mycielskian family
+of graphs.
+
+"""
+
+import networkx as nx
+from networkx.utils import not_implemented_for
+
+__all__ = ["mycielskian", "mycielski_graph"]
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable(returns_graph=True)
+def mycielskian(G, iterations=1):
+    r"""Returns the Mycielskian of a simple, undirected graph G
+
+    The Mycielskian of graph preserves a graph's triangle free
+    property while increasing the chromatic number by 1.
+
+    The Mycielski Operation on a graph, :math:`G=(V, E)`, constructs a new
+    graph with :math:`2|V| + 1` nodes and :math:`3|E| + |V|` edges.
+
+    The construction is as follows:
+
+    Let :math:`V = {0, ..., n-1}`. Construct another vertex set
+    :math:`U = {n, ..., 2n}` and a vertex, `w`.
+    Construct a new graph, `M`, with vertices :math:`U \bigcup V \bigcup w`.
+    For edges, :math:`(u, v) \in E` add edges :math:`(u, v), (u, v + n)`, and
+    :math:`(u + n, v)` to M. Finally, for all vertices :math:`u \in U`, add
+    edge :math:`(u, w)` to M.
+
+    The Mycielski Operation can be done multiple times by repeating the above
+    process iteratively.
+
+    More information can be found at https://en.wikipedia.org/wiki/Mycielskian
+
+    Parameters
+    ----------
+    G : graph
+        A simple, undirected NetworkX graph
+    iterations : int
+        The number of iterations of the Mycielski operation to
+        perform on G. Defaults to 1. Must be a non-negative integer.
+
+    Returns
+    -------
+    M : graph
+        The Mycielskian of G after the specified number of iterations.
+
+    Notes
+    -----
+    Graph, node, and edge data are not necessarily propagated to the new graph.
+
+    """
+
+    M = nx.convert_node_labels_to_integers(G)
+
+    for i in range(iterations):
+        n = M.number_of_nodes()
+        M.add_nodes_from(range(n, 2 * n))
+        old_edges = list(M.edges())
+        M.add_edges_from((u, v + n) for u, v in old_edges)
+        M.add_edges_from((u + n, v) for u, v in old_edges)
+        M.add_node(2 * n)
+        M.add_edges_from((u + n, 2 * n) for u in range(n))
+
+    return M
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def mycielski_graph(n):
+    """Generator for the n_th Mycielski Graph.
+
+    The Mycielski family of graphs is an infinite set of graphs.
+    :math:`M_1` is the singleton graph, :math:`M_2` is two vertices with an
+    edge, and, for :math:`i > 2`, :math:`M_i` is the Mycielskian of
+    :math:`M_{i-1}`.
+
+    More information can be found at
+    http://mathworld.wolfram.com/MycielskiGraph.html
+
+    Parameters
+    ----------
+    n : int
+        The desired Mycielski Graph.
+
+    Returns
+    -------
+    M : graph
+        The n_th Mycielski Graph
+
+    Notes
+    -----
+    The first graph in the Mycielski sequence is the singleton graph.
+    The Mycielskian of this graph is not the :math:`P_2` graph, but rather the
+    :math:`P_2` graph with an extra, isolated vertex. The second Mycielski
+    graph is the :math:`P_2` graph, so the first two are hard coded.
+    The remaining graphs are generated using the Mycielski operation.
+
+    """
+
+    if n < 1:
+        raise nx.NetworkXError("must satisfy n >= 1")
+
+    if n == 1:
+        return nx.empty_graph(1)
+
+    else:
+        return mycielskian(nx.path_graph(2), n - 2)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/nonisomorphic_trees.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/nonisomorphic_trees.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a0f0c996d8915b07b5f87c4e14359bc642b2929
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/nonisomorphic_trees.py
@@ -0,0 +1,259 @@
+"""
+Implementation of the Wright, Richmond, Odlyzko and McKay (WROM)
+algorithm for the enumeration of all non-isomorphic free trees of a
+given order.  Rooted trees are represented by level sequences, i.e.,
+lists in which the i-th element specifies the distance of vertex i to
+the root.
+
+"""
+
+__all__ = ["nonisomorphic_trees", "number_of_nonisomorphic_trees"]
+
+from functools import lru_cache
+
+import networkx as nx
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def nonisomorphic_trees(order):
+    """Generate nonisomorphic trees of specified `order`.
+
+    Parameters
+    ----------
+    order : int
+       order of the desired tree(s)
+
+    Yields
+    ------
+    `networkx.Graph` instances
+       A tree with `order` number of nodes that is not isomorphic to any other
+       yielded tree.
+
+    Raises
+    ------
+    ValueError
+       If `order` is negative.
+
+    Examples
+    --------
+    There are 11 unique (non-isomorphic) trees with 7 nodes.
+
+    >>> n = 7
+    >>> nit_list = list(nx.nonisomorphic_trees(n))
+    >>> len(nit_list) == nx.number_of_nonisomorphic_trees(n) == 11
+    True
+
+    All trees yielded by the generator have the specified order.
+
+    >>> all(len(G) == n for G in nx.nonisomorphic_trees(n))
+    True
+
+    Each tree is nonisomorphic to every other tree yielded by the generator.
+    >>> seen = []
+    >>> for G in nx.nonisomorphic_trees(n):
+    ...     assert not any(nx.is_isomorphic(G, H) for H in seen)
+    ...     seen.append(G)
+
+    See Also
+    --------
+    number_of_nonisomorphic_trees
+    """
+    if order < 0:
+        raise ValueError("order must be non-negative")
+    if order == 0:
+        # Idiom for empty generator, i.e. list(nonisomorphic_trees(0)) == []
+        return
+        yield
+    if order == 1:
+        yield nx.empty_graph(1)
+        return
+    # start at the path graph rooted at its center
+    layout = list(range(order // 2 + 1)) + list(range(1, (order + 1) // 2))
+
+    while layout is not None:
+        layout = _next_tree(layout)
+        if layout is not None:
+            yield _layout_to_graph(layout)
+            layout = _next_rooted_tree(layout)
+
+
+@nx._dispatchable(graphs=None)
+def number_of_nonisomorphic_trees(order):
+    """Returns the number of nonisomorphic trees of the specified `order`.
+
+    Based on an algorithm by Alois P. Heinz in
+    `OEIS entry A000055 `_. Complexity is ``O(n ** 3)``.
+
+    Parameters
+    ----------
+    order : int
+       Order of the desired tree(s).
+
+    Returns
+    -------
+    int
+       Number of nonisomorphic trees with `order` number of nodes.
+
+    Raises
+    ------
+    ValueError
+       If `order` is negative.
+
+    Examples
+    --------
+    >>> nx.number_of_nonisomorphic_trees(10)
+    106
+
+    See Also
+    --------
+    nonisomorphic_trees
+    """
+    if order < 0:
+        raise ValueError("order must be non-negative")
+    return _unlabeled_trees(order)
+
+
+@lru_cache(None)
+def _unlabeled_trees(n):
+    """Implements OEIS A000055 (number of unlabeled trees)."""
+
+    value = 0
+    for k in range(n + 1):
+        value += _rooted_trees(k) * _rooted_trees(n - k)
+    if n % 2 == 0:
+        value -= _rooted_trees(n // 2)
+    return _rooted_trees(n) - value // 2
+
+
+@lru_cache(None)
+def _rooted_trees(n):
+    """Implements OEIS A000081 (number of unlabeled rooted trees)."""
+
+    if n < 2:
+        return n
+    value = 0
+    for j in range(1, n):
+        for d in range(1, n):
+            if j % d == 0:
+                value += d * _rooted_trees(d) * _rooted_trees(n - j)
+    return value // (n - 1)
+
+
+def _next_rooted_tree(predecessor, p=None):
+    """One iteration of the Beyer-Hedetniemi algorithm."""
+
+    if p is None:
+        p = len(predecessor) - 1
+        while predecessor[p] == 1:
+            p -= 1
+    if p == 0:
+        return None
+
+    q = p - 1
+    while predecessor[q] != predecessor[p] - 1:
+        q -= 1
+    result = list(predecessor)
+    for i in range(p, len(result)):
+        result[i] = result[i - p + q]
+    return result
+
+
+def _next_tree(candidate):
+    """One iteration of the Wright, Richmond, Odlyzko and McKay
+    algorithm."""
+
+    # valid representation of a free tree if:
+    # there are at least two vertices at layer 1
+    # (this is always the case because we start at the path graph)
+    left, rest = _split_tree(candidate)
+
+    # and the left subtree of the root
+    # is less high than the tree with the left subtree removed
+    left_height = max(left)
+    rest_height = max(rest)
+    valid = rest_height >= left_height
+
+    if valid and rest_height == left_height:
+        # and, if left and rest are of the same height,
+        # if left does not encompass more vertices
+        if len(left) > len(rest):
+            valid = False
+        # and, if they have the same number or vertices,
+        # if left does not come after rest lexicographically
+        elif len(left) == len(rest) and left > rest:
+            valid = False
+
+    if valid:
+        return candidate
+    else:
+        # jump to the next valid free tree
+        p = len(left)
+        new_candidate = _next_rooted_tree(candidate, p)
+        if candidate[p] > 2:
+            new_left, new_rest = _split_tree(new_candidate)
+            new_left_height = max(new_left)
+            suffix = range(1, new_left_height + 2)
+            new_candidate[-len(suffix) :] = suffix
+        return new_candidate
+
+
+def _split_tree(layout):
+    """Returns a tuple of two layouts, one containing the left
+    subtree of the root vertex, and one containing the original tree
+    with the left subtree removed."""
+
+    one_found = False
+    m = None
+    for i in range(len(layout)):
+        if layout[i] == 1:
+            if one_found:
+                m = i
+                break
+            else:
+                one_found = True
+
+    if m is None:
+        m = len(layout)
+
+    left = [layout[i] - 1 for i in range(1, m)]
+    rest = [0] + [layout[i] for i in range(m, len(layout))]
+    return (left, rest)
+
+
+def _layout_to_matrix(layout):
+    """Create the adjacency matrix for the tree specified by the
+    given layout (level sequence)."""
+
+    result = [[0] * len(layout) for i in range(len(layout))]
+    stack = []
+    for i in range(len(layout)):
+        i_level = layout[i]
+        if stack:
+            j = stack[-1]
+            j_level = layout[j]
+            while j_level >= i_level:
+                stack.pop()
+                j = stack[-1]
+                j_level = layout[j]
+            result[i][j] = result[j][i] = 1
+        stack.append(i)
+    return result
+
+
+def _layout_to_graph(layout):
+    """Create a NetworkX Graph for the tree specified by the
+    given layout(level sequence)"""
+    G = nx.Graph()
+    stack = []
+    for i in range(len(layout)):
+        i_level = layout[i]
+        if stack:
+            j = stack[-1]
+            j_level = layout[j]
+            while j_level >= i_level:
+                stack.pop()
+                j = stack[-1]
+                j_level = layout[j]
+            G.add_edge(i, j)
+        stack.append(i)
+    return G
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/random_clustered.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/random_clustered.py
new file mode 100644
index 0000000000000000000000000000000000000000..8fbf855e672d3c50f1e74952cc2272143fbac57a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/random_clustered.py
@@ -0,0 +1,117 @@
+"""Generate graphs with given degree and triangle sequence."""
+
+import networkx as nx
+from networkx.utils import py_random_state
+
+__all__ = ["random_clustered_graph"]
+
+
+@py_random_state(2)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def random_clustered_graph(joint_degree_sequence, create_using=None, seed=None):
+    r"""Generate a random graph with the given joint independent edge degree and
+    triangle degree sequence.
+
+    This uses a configuration model-like approach to generate a random graph
+    (with parallel edges and self-loops) by randomly assigning edges to match
+    the given joint degree sequence.
+
+    The joint degree sequence is a list of pairs of integers of the form
+    $[(d_{1,i}, d_{1,t}), \dotsc, (d_{n,i}, d_{n,t})]$. According to this list,
+    vertex $u$ is a member of $d_{u,t}$ triangles and has $d_{u, i}$ other
+    edges. The number $d_{u,t}$ is the *triangle degree* of $u$ and the number
+    $d_{u,i}$ is the *independent edge degree*.
+
+    Parameters
+    ----------
+    joint_degree_sequence : list of integer pairs
+        Each list entry corresponds to the independent edge degree and
+        triangle degree of a node.
+    create_using : NetworkX graph constructor, optional (default MultiGraph)
+       Graph type to create. If graph instance, then cleared before populated.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    G : MultiGraph
+        A graph with the specified degree sequence. Nodes are labeled
+        starting at 0 with an index corresponding to the position in
+        deg_sequence.
+
+    Raises
+    ------
+    NetworkXError
+        If the independent edge degree sequence sum is not even
+        or the triangle degree sequence sum is not divisible by 3.
+
+    Notes
+    -----
+    As described by Miller [1]_ (see also Newman [2]_ for an equivalent
+    description).
+
+    A non-graphical degree sequence (not realizable by some simple
+    graph) is allowed since this function returns graphs with self
+    loops and parallel edges.  An exception is raised if the
+    independent degree sequence does not have an even sum or the
+    triangle degree sequence sum is not divisible by 3.
+
+    This configuration model-like construction process can lead to
+    duplicate edges and loops.  You can remove the self-loops and
+    parallel edges (see below) which will likely result in a graph
+    that doesn't have the exact degree sequence specified.  This
+    "finite-size effect" decreases as the size of the graph increases.
+
+    References
+    ----------
+    .. [1] Joel C. Miller. "Percolation and epidemics in random clustered
+           networks". In: Physical review. E, Statistical, nonlinear, and soft
+           matter physics 80 (2 Part 1 August 2009).
+    .. [2] M. E. J. Newman. "Random Graphs with Clustering".
+           In: Physical Review Letters 103 (5 July 2009)
+
+    Examples
+    --------
+    >>> deg = [(1, 0), (1, 0), (1, 0), (2, 0), (1, 0), (2, 1), (0, 1), (0, 1)]
+    >>> G = nx.random_clustered_graph(deg)
+
+    To remove parallel edges:
+
+    >>> G = nx.Graph(G)
+
+    To remove self loops:
+
+    >>> G.remove_edges_from(nx.selfloop_edges(G))
+
+    """
+    # In Python 3, zip() returns an iterator. Make this into a list.
+    joint_degree_sequence = list(joint_degree_sequence)
+
+    N = len(joint_degree_sequence)
+    G = nx.empty_graph(N, create_using, default=nx.MultiGraph)
+    if G.is_directed():
+        raise nx.NetworkXError("Directed Graph not supported")
+
+    ilist = []
+    tlist = []
+    for n in G:
+        degrees = joint_degree_sequence[n]
+        for icount in range(degrees[0]):
+            ilist.append(n)
+        for tcount in range(degrees[1]):
+            tlist.append(n)
+
+    if len(ilist) % 2 != 0 or len(tlist) % 3 != 0:
+        raise nx.NetworkXError("Invalid degree sequence")
+
+    seed.shuffle(ilist)
+    seed.shuffle(tlist)
+    while ilist:
+        G.add_edge(ilist.pop(), ilist.pop())
+    while tlist:
+        n1 = tlist.pop()
+        n2 = tlist.pop()
+        n3 = tlist.pop()
+        G.add_edges_from([(n1, n2), (n1, n3), (n2, n3)])
+    return G
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/random_graphs.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/random_graphs.py
new file mode 100644
index 0000000000000000000000000000000000000000..d4ab0c9813631319ff866ac585926a88e6d76550
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/random_graphs.py
@@ -0,0 +1,1416 @@
+"""
+Generators for random graphs.
+
+"""
+
+import itertools
+import math
+from collections import defaultdict
+
+import networkx as nx
+from networkx.utils import py_random_state
+
+from ..utils.misc import check_create_using
+from .classic import complete_graph, empty_graph, path_graph, star_graph
+from .degree_seq import degree_sequence_tree
+
+__all__ = [
+    "fast_gnp_random_graph",
+    "gnp_random_graph",
+    "dense_gnm_random_graph",
+    "gnm_random_graph",
+    "erdos_renyi_graph",
+    "binomial_graph",
+    "newman_watts_strogatz_graph",
+    "watts_strogatz_graph",
+    "connected_watts_strogatz_graph",
+    "random_regular_graph",
+    "barabasi_albert_graph",
+    "dual_barabasi_albert_graph",
+    "extended_barabasi_albert_graph",
+    "powerlaw_cluster_graph",
+    "random_lobster",
+    "random_lobster_graph",
+    "random_shell_graph",
+    "random_powerlaw_tree",
+    "random_powerlaw_tree_sequence",
+    "random_kernel_graph",
+]
+
+
+@py_random_state(2)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def fast_gnp_random_graph(n, p, seed=None, directed=False, *, create_using=None):
+    """Returns a $G_{n,p}$ random graph, also known as an Erdős-Rényi graph or
+    a binomial graph.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes.
+    p : float
+        Probability for edge creation.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    directed : bool, optional (default=False)
+        If True, this function returns a directed graph.
+    create_using : Graph constructor, optional (default=nx.Graph or nx.DiGraph)
+        Graph type to create. If graph instance, then cleared before populated.
+        Multigraph types are not supported and raise a ``NetworkXError``.
+        By default NetworkX Graph or DiGraph are used depending on `directed`.
+
+    Notes
+    -----
+    The $G_{n,p}$ graph algorithm chooses each of the $[n (n - 1)] / 2$
+    (undirected) or $n (n - 1)$ (directed) possible edges with probability $p$.
+
+    This algorithm [1]_ runs in $O(n + m)$ time, where `m` is the expected number of
+    edges, which equals $p n (n - 1) / 2$. This should be faster than
+    :func:`gnp_random_graph` when $p$ is small and the expected number of edges
+    is small (that is, the graph is sparse).
+
+    See Also
+    --------
+    gnp_random_graph
+
+    References
+    ----------
+    .. [1] Vladimir Batagelj and Ulrik Brandes,
+       "Efficient generation of large random networks",
+       Phys. Rev. E, 71, 036113, 2005.
+    """
+    default = nx.DiGraph if directed else nx.Graph
+    create_using = check_create_using(
+        create_using, directed=directed, multigraph=False, default=default
+    )
+    if p <= 0 or p >= 1:
+        return nx.gnp_random_graph(
+            n, p, seed=seed, directed=directed, create_using=create_using
+        )
+
+    G = empty_graph(n, create_using=create_using)
+
+    lp = math.log(1.0 - p)
+
+    if directed:
+        v = 1
+        w = -1
+        while v < n:
+            lr = math.log(1.0 - seed.random())
+            w = w + 1 + int(lr / lp)
+            while w >= v and v < n:
+                w = w - v
+                v = v + 1
+            if v < n:
+                G.add_edge(w, v)
+
+    # Nodes in graph are from 0,n-1 (start with v as the second node index).
+    v = 1
+    w = -1
+    while v < n:
+        lr = math.log(1.0 - seed.random())
+        w = w + 1 + int(lr / lp)
+        while w >= v and v < n:
+            w = w - v
+            v = v + 1
+        if v < n:
+            G.add_edge(v, w)
+    return G
+
+
+@py_random_state(2)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def gnp_random_graph(n, p, seed=None, directed=False, *, create_using=None):
+    """Returns a $G_{n,p}$ random graph, also known as an Erdős-Rényi graph
+    or a binomial graph.
+
+    The $G_{n,p}$ model chooses each of the possible edges with probability $p$.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes.
+    p : float
+        Probability for edge creation.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    directed : bool, optional (default=False)
+        If True, this function returns a directed graph.
+    create_using : Graph constructor, optional (default=nx.Graph or nx.DiGraph)
+        Graph type to create. If graph instance, then cleared before populated.
+        Multigraph types are not supported and raise a ``NetworkXError``.
+        By default NetworkX Graph or DiGraph are used depending on `directed`.
+
+    See Also
+    --------
+    fast_gnp_random_graph
+
+    Notes
+    -----
+    This algorithm [2]_ runs in $O(n^2)$ time.  For sparse graphs (that is, for
+    small values of $p$), :func:`fast_gnp_random_graph` is a faster algorithm.
+
+    :func:`binomial_graph` and :func:`erdos_renyi_graph` are
+    aliases for :func:`gnp_random_graph`.
+
+    >>> nx.binomial_graph is nx.gnp_random_graph
+    True
+    >>> nx.erdos_renyi_graph is nx.gnp_random_graph
+    True
+
+    References
+    ----------
+    .. [1] P. Erdős and A. Rényi, On Random Graphs, Publ. Math. 6, 290 (1959).
+    .. [2] E. N. Gilbert, Random Graphs, Ann. Math. Stat., 30, 1141 (1959).
+    """
+    default = nx.DiGraph if directed else nx.Graph
+    create_using = check_create_using(
+        create_using, directed=directed, multigraph=False, default=default
+    )
+    if p >= 1:
+        return complete_graph(n, create_using=create_using)
+
+    G = nx.empty_graph(n, create_using=create_using)
+    if p <= 0:
+        return G
+
+    edgetool = itertools.permutations if directed else itertools.combinations
+    for e in edgetool(range(n), 2):
+        if seed.random() < p:
+            G.add_edge(*e)
+    return G
+
+
+# add some aliases to common names
+binomial_graph = gnp_random_graph
+erdos_renyi_graph = gnp_random_graph
+
+
+@py_random_state(2)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def dense_gnm_random_graph(n, m, seed=None, *, create_using=None):
+    """Returns a $G_{n,m}$ random graph.
+
+    In the $G_{n,m}$ model, a graph is chosen uniformly at random from the set
+    of all graphs with $n$ nodes and $m$ edges.
+
+    This algorithm should be faster than :func:`gnm_random_graph` for dense
+    graphs.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes.
+    m : int
+        The number of edges.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    create_using : Graph constructor, optional (default=nx.Graph)
+        Graph type to create. If graph instance, then cleared before populated.
+        Multigraph and directed types are not supported and raise a ``NetworkXError``.
+
+    See Also
+    --------
+    gnm_random_graph
+
+    Notes
+    -----
+    Algorithm by Keith M. Briggs Mar 31, 2006.
+    Inspired by Knuth's Algorithm S (Selection sampling technique),
+    in section 3.4.2 of [1]_.
+
+    References
+    ----------
+    .. [1] Donald E. Knuth, The Art of Computer Programming,
+        Volume 2/Seminumerical algorithms, Third Edition, Addison-Wesley, 1997.
+    """
+    create_using = check_create_using(create_using, directed=False, multigraph=False)
+    mmax = n * (n - 1) // 2
+    if m >= mmax:
+        return complete_graph(n, create_using)
+    G = empty_graph(n, create_using)
+
+    if n == 1:
+        return G
+
+    u = 0
+    v = 1
+    t = 0
+    k = 0
+    while True:
+        if seed.randrange(mmax - t) < m - k:
+            G.add_edge(u, v)
+            k += 1
+            if k == m:
+                return G
+        t += 1
+        v += 1
+        if v == n:  # go to next row of adjacency matrix
+            u += 1
+            v = u + 1
+
+
+@py_random_state(2)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def gnm_random_graph(n, m, seed=None, directed=False, *, create_using=None):
+    """Returns a $G_{n,m}$ random graph.
+
+    In the $G_{n,m}$ model, a graph is chosen uniformly at random from the set
+    of all graphs with $n$ nodes and $m$ edges.
+
+    This algorithm should be faster than :func:`dense_gnm_random_graph` for
+    sparse graphs.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes.
+    m : int
+        The number of edges.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    directed : bool, optional (default=False)
+        If True return a directed graph
+    create_using : Graph constructor, optional (default=nx.Graph or nx.DiGraph)
+        Graph type to create. If graph instance, then cleared before populated.
+        Multigraph types are not supported and raise a ``NetworkXError``.
+        By default NetworkX Graph or DiGraph are used depending on `directed`.
+
+    See also
+    --------
+    dense_gnm_random_graph
+
+    """
+    default = nx.DiGraph if directed else nx.Graph
+    create_using = check_create_using(
+        create_using, directed=directed, multigraph=False, default=default
+    )
+    if n == 1:
+        return nx.empty_graph(n, create_using=create_using)
+    max_edges = n * (n - 1) if directed else n * (n - 1) / 2.0
+    if m >= max_edges:
+        return complete_graph(n, create_using=create_using)
+
+    G = nx.empty_graph(n, create_using=create_using)
+    nlist = list(G)
+    edge_count = 0
+    while edge_count < m:
+        # generate random edge,u,v
+        u = seed.choice(nlist)
+        v = seed.choice(nlist)
+        if u == v or G.has_edge(u, v):
+            continue
+        else:
+            G.add_edge(u, v)
+            edge_count = edge_count + 1
+    return G
+
+
+@py_random_state(3)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def newman_watts_strogatz_graph(n, k, p, seed=None, *, create_using=None):
+    """Returns a Newman–Watts–Strogatz small-world graph.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes.
+    k : int
+        Each node is joined with its `k` nearest neighbors in a ring
+        topology.
+    p : float
+        The probability of adding a new edge for each edge.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    create_using : Graph constructor, optional (default=nx.Graph)
+        Graph type to create. If graph instance, then cleared before populated.
+        Multigraph and directed types are not supported and raise a ``NetworkXError``.
+
+    Notes
+    -----
+    First create a ring over $n$ nodes [1]_.  Then each node in the ring is
+    connected with its $k$ nearest neighbors (or $k - 1$ neighbors if $k$
+    is odd).  Then shortcuts are created by adding new edges as follows: for
+    each edge $(u, v)$ in the underlying "$n$-ring with $k$ nearest
+    neighbors" with probability $p$ add a new edge $(u, w)$ with
+    randomly-chosen existing node $w$.  In contrast with
+    :func:`watts_strogatz_graph`, no edges are removed.
+
+    See Also
+    --------
+    watts_strogatz_graph
+
+    References
+    ----------
+    .. [1] M. E. J. Newman and D. J. Watts,
+       Renormalization group analysis of the small-world network model,
+       Physics Letters A, 263, 341, 1999.
+       https://doi.org/10.1016/S0375-9601(99)00757-4
+    """
+    create_using = check_create_using(create_using, directed=False, multigraph=False)
+    if k > n:
+        raise nx.NetworkXError("k>=n, choose smaller k or larger n")
+
+    # If k == n the graph return is a complete graph
+    if k == n:
+        return nx.complete_graph(n, create_using)
+
+    G = empty_graph(n, create_using)
+    nlist = list(G.nodes())
+    fromv = nlist
+    # connect the k/2 neighbors
+    for j in range(1, k // 2 + 1):
+        tov = fromv[j:] + fromv[0:j]  # the first j are now last
+        for i in range(len(fromv)):
+            G.add_edge(fromv[i], tov[i])
+    # for each edge u-v, with probability p, randomly select existing
+    # node w and add new edge u-w
+    e = list(G.edges())
+    for u, v in e:
+        if seed.random() < p:
+            w = seed.choice(nlist)
+            # no self-loops and reject if edge u-w exists
+            # is that the correct NWS model?
+            while w == u or G.has_edge(u, w):
+                w = seed.choice(nlist)
+                if G.degree(u) >= n - 1:
+                    break  # skip this rewiring
+            else:
+                G.add_edge(u, w)
+    return G
+
+
+@py_random_state(3)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def watts_strogatz_graph(n, k, p, seed=None, *, create_using=None):
+    """Returns a Watts–Strogatz small-world graph.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes
+    k : int
+        Each node is joined with its `k` nearest neighbors in a ring
+        topology.
+    p : float
+        The probability of rewiring each edge
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    create_using : Graph constructor, optional (default=nx.Graph)
+        Graph type to create. If graph instance, then cleared before populated.
+        Multigraph and directed types are not supported and raise a ``NetworkXError``.
+
+    See Also
+    --------
+    newman_watts_strogatz_graph
+    connected_watts_strogatz_graph
+
+    Notes
+    -----
+    First create a ring over $n$ nodes [1]_.  Then each node in the ring is joined
+    to its $k$ nearest neighbors (or $k - 1$ neighbors if $k$ is odd).
+    Then shortcuts are created by replacing some edges as follows: for each
+    edge $(u, v)$ in the underlying "$n$-ring with $k$ nearest neighbors"
+    with probability $p$ replace it with a new edge $(u, w)$ with uniformly
+    random choice of existing node $w$.
+
+    In contrast with :func:`newman_watts_strogatz_graph`, the random rewiring
+    does not increase the number of edges. The rewired graph is not guaranteed
+    to be connected as in :func:`connected_watts_strogatz_graph`.
+
+    References
+    ----------
+    .. [1] Duncan J. Watts and Steven H. Strogatz,
+       Collective dynamics of small-world networks,
+       Nature, 393, pp. 440--442, 1998.
+    """
+    create_using = check_create_using(create_using, directed=False, multigraph=False)
+    if k > n:
+        raise nx.NetworkXError("k>n, choose smaller k or larger n")
+
+    # If k == n, the graph is complete not Watts-Strogatz
+    if k == n:
+        G = nx.complete_graph(n, create_using)
+        return G
+
+    G = nx.empty_graph(n, create_using=create_using)
+    nodes = list(range(n))  # nodes are labeled 0 to n-1
+    # connect each node to k/2 neighbors
+    for j in range(1, k // 2 + 1):
+        targets = nodes[j:] + nodes[0:j]  # first j nodes are now last in list
+        G.add_edges_from(zip(nodes, targets))
+    # rewire edges from each node
+    # loop over all nodes in order (label) and neighbors in order (distance)
+    # no self loops or multiple edges allowed
+    for j in range(1, k // 2 + 1):  # outer loop is neighbors
+        targets = nodes[j:] + nodes[0:j]  # first j nodes are now last in list
+        # inner loop in node order
+        for u, v in zip(nodes, targets):
+            if seed.random() < p:
+                w = seed.choice(nodes)
+                # Enforce no self-loops or multiple edges
+                while w == u or G.has_edge(u, w):
+                    w = seed.choice(nodes)
+                    if G.degree(u) >= n - 1:
+                        break  # skip this rewiring
+                else:
+                    G.remove_edge(u, v)
+                    G.add_edge(u, w)
+    return G
+
+
+@py_random_state(4)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def connected_watts_strogatz_graph(n, k, p, tries=100, seed=None, *, create_using=None):
+    """Returns a connected Watts–Strogatz small-world graph.
+
+    Attempts to generate a connected graph by repeated generation of
+    Watts–Strogatz small-world graphs.  An exception is raised if the maximum
+    number of tries is exceeded.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes
+    k : int
+        Each node is joined with its `k` nearest neighbors in a ring
+        topology.
+    p : float
+        The probability of rewiring each edge
+    tries : int
+        Number of attempts to generate a connected graph.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    create_using : Graph constructor, optional (default=nx.Graph)
+        Graph type to create. If graph instance, then cleared before populated.
+        Multigraph and directed types are not supported and raise a ``NetworkXError``.
+
+    Notes
+    -----
+    First create a ring over $n$ nodes [1]_.  Then each node in the ring is joined
+    to its $k$ nearest neighbors (or $k - 1$ neighbors if $k$ is odd).
+    Then shortcuts are created by replacing some edges as follows: for each
+    edge $(u, v)$ in the underlying "$n$-ring with $k$ nearest neighbors"
+    with probability $p$ replace it with a new edge $(u, w)$ with uniformly
+    random choice of existing node $w$.
+    The entire process is repeated until a connected graph results.
+
+    See Also
+    --------
+    newman_watts_strogatz_graph
+    watts_strogatz_graph
+
+    References
+    ----------
+    .. [1] Duncan J. Watts and Steven H. Strogatz,
+       Collective dynamics of small-world networks,
+       Nature, 393, pp. 440--442, 1998.
+    """
+    for i in range(tries):
+        # seed is an RNG so should change sequence each call
+        G = watts_strogatz_graph(n, k, p, seed, create_using=create_using)
+        if nx.is_connected(G):
+            return G
+    raise nx.NetworkXError("Maximum number of tries exceeded")
+
+
+@py_random_state(2)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def random_regular_graph(d, n, seed=None, *, create_using=None):
+    r"""Returns a random $d$-regular graph on $n$ nodes.
+
+    A regular graph is a graph where each node has the same number of neighbors.
+
+    The resulting graph has no self-loops or parallel edges.
+
+    Parameters
+    ----------
+    d : int
+      The degree of each node.
+    n : integer
+      The number of nodes. The value of $n \times d$ must be even.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    create_using : Graph constructor, optional (default=nx.Graph)
+        Graph type to create. If graph instance, then cleared before populated.
+        Multigraph and directed types are not supported and raise a ``NetworkXError``.
+
+    Notes
+    -----
+    The nodes are numbered from $0$ to $n - 1$.
+
+    Kim and Vu's paper [2]_ shows that this algorithm samples in an
+    asymptotically uniform way from the space of random graphs when
+    $d = O(n^{1 / 3 - \epsilon})$.
+
+    Raises
+    ------
+
+    NetworkXError
+        If $n \times d$ is odd or $d$ is greater than or equal to $n$.
+
+    References
+    ----------
+    .. [1] A. Steger and N. Wormald,
+       Generating random regular graphs quickly,
+       Probability and Computing 8 (1999), 377-396, 1999.
+       https://doi.org/10.1017/S0963548399003867
+
+    .. [2] Jeong Han Kim and Van H. Vu,
+       Generating random regular graphs,
+       Proceedings of the thirty-fifth ACM symposium on Theory of computing,
+       San Diego, CA, USA, pp 213--222, 2003.
+       http://portal.acm.org/citation.cfm?id=780542.780576
+    """
+    create_using = check_create_using(create_using, directed=False, multigraph=False)
+    if (n * d) % 2 != 0:
+        raise nx.NetworkXError("n * d must be even")
+
+    if not 0 <= d < n:
+        raise nx.NetworkXError("the 0 <= d < n inequality must be satisfied")
+
+    G = nx.empty_graph(n, create_using=create_using)
+
+    if d == 0:
+        return G
+
+    def _suitable(edges, potential_edges):
+        # Helper subroutine to check if there are suitable edges remaining
+        # If False, the generation of the graph has failed
+        if not potential_edges:
+            return True
+        for s1 in potential_edges:
+            for s2 in potential_edges:
+                # Two iterators on the same dictionary are guaranteed
+                # to visit it in the same order if there are no
+                # intervening modifications.
+                if s1 == s2:
+                    # Only need to consider s1-s2 pair one time
+                    break
+                if s1 > s2:
+                    s1, s2 = s2, s1
+                if (s1, s2) not in edges:
+                    return True
+        return False
+
+    def _try_creation():
+        # Attempt to create an edge set
+
+        edges = set()
+        stubs = list(range(n)) * d
+
+        while stubs:
+            potential_edges = defaultdict(lambda: 0)
+            seed.shuffle(stubs)
+            stubiter = iter(stubs)
+            for s1, s2 in zip(stubiter, stubiter):
+                if s1 > s2:
+                    s1, s2 = s2, s1
+                if s1 != s2 and ((s1, s2) not in edges):
+                    edges.add((s1, s2))
+                else:
+                    potential_edges[s1] += 1
+                    potential_edges[s2] += 1
+
+            if not _suitable(edges, potential_edges):
+                return None  # failed to find suitable edge set
+
+            stubs = [
+                node
+                for node, potential in potential_edges.items()
+                for _ in range(potential)
+            ]
+        return edges
+
+    # Even though a suitable edge set exists,
+    # the generation of such a set is not guaranteed.
+    # Try repeatedly to find one.
+    edges = _try_creation()
+    while edges is None:
+        edges = _try_creation()
+    G.add_edges_from(edges)
+
+    return G
+
+
+def _random_subset(seq, m, rng):
+    """Return m unique elements from seq.
+
+    This differs from random.sample which can return repeated
+    elements if seq holds repeated elements.
+
+    Note: rng is a random.Random or numpy.random.RandomState instance.
+    """
+    targets = set()
+    while len(targets) < m:
+        x = rng.choice(seq)
+        targets.add(x)
+    return targets
+
+
+@py_random_state(2)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def barabasi_albert_graph(n, m, seed=None, initial_graph=None, *, create_using=None):
+    """Returns a random graph using Barabási–Albert preferential attachment
+
+    A graph of $n$ nodes is grown by attaching new nodes each with $m$
+    edges that are preferentially attached to existing nodes with high degree.
+
+    Parameters
+    ----------
+    n : int
+        Number of nodes
+    m : int
+        Number of edges to attach from a new node to existing nodes
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    initial_graph : Graph or None (default)
+        Initial network for Barabási–Albert algorithm.
+        It should be a connected graph for most use cases.
+        A copy of `initial_graph` is used.
+        If None, starts from a star graph on (m+1) nodes.
+    create_using : Graph constructor, optional (default=nx.Graph)
+        Graph type to create. If graph instance, then cleared before populated.
+        Multigraph and directed types are not supported and raise a ``NetworkXError``.
+
+    Returns
+    -------
+    G : Graph
+
+    Raises
+    ------
+    NetworkXError
+        If `m` does not satisfy ``1 <= m < n``, or
+        the initial graph number of nodes m0 does not satisfy ``m <= m0 <= n``.
+
+    References
+    ----------
+    .. [1] A. L. Barabási and R. Albert "Emergence of scaling in
+       random networks", Science 286, pp 509-512, 1999.
+    """
+    create_using = check_create_using(create_using, directed=False, multigraph=False)
+    if m < 1 or m >= n:
+        raise nx.NetworkXError(
+            f"Barabási–Albert network must have m >= 1 and m < n, m = {m}, n = {n}"
+        )
+
+    if initial_graph is None:
+        # Default initial graph : star graph on (m + 1) nodes
+        G = star_graph(m, create_using)
+    else:
+        if len(initial_graph) < m or len(initial_graph) > n:
+            raise nx.NetworkXError(
+                f"Barabási–Albert initial graph needs between m={m} and n={n} nodes"
+            )
+        G = initial_graph.copy()
+
+    # List of existing nodes, with nodes repeated once for each adjacent edge
+    repeated_nodes = [n for n, d in G.degree() for _ in range(d)]
+    # Start adding the other n - m0 nodes.
+    source = len(G)
+    while source < n:
+        # Now choose m unique nodes from the existing nodes
+        # Pick uniformly from repeated_nodes (preferential attachment)
+        targets = _random_subset(repeated_nodes, m, seed)
+        # Add edges to m nodes from the source.
+        G.add_edges_from(zip([source] * m, targets))
+        # Add one node to the list for each new edge just created.
+        repeated_nodes.extend(targets)
+        # And the new node "source" has m edges to add to the list.
+        repeated_nodes.extend([source] * m)
+
+        source += 1
+    return G
+
+
+@py_random_state(4)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def dual_barabasi_albert_graph(
+    n, m1, m2, p, seed=None, initial_graph=None, *, create_using=None
+):
+    """Returns a random graph using dual Barabási–Albert preferential attachment
+
+    A graph of $n$ nodes is grown by attaching new nodes each with either $m_1$
+    edges (with probability $p$) or $m_2$ edges (with probability $1-p$) that
+    are preferentially attached to existing nodes with high degree.
+
+    Parameters
+    ----------
+    n : int
+        Number of nodes
+    m1 : int
+        Number of edges to link each new node to existing nodes with probability $p$
+    m2 : int
+        Number of edges to link each new node to existing nodes with probability $1-p$
+    p : float
+        The probability of attaching $m_1$ edges (as opposed to $m_2$ edges)
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    initial_graph : Graph or None (default)
+        Initial network for Barabási–Albert algorithm.
+        A copy of `initial_graph` is used.
+        It should be connected for most use cases.
+        If None, starts from an star graph on max(m1, m2) + 1 nodes.
+    create_using : Graph constructor, optional (default=nx.Graph)
+        Graph type to create. If graph instance, then cleared before populated.
+        Multigraph and directed types are not supported and raise a ``NetworkXError``.
+
+    Returns
+    -------
+    G : Graph
+
+    Raises
+    ------
+    NetworkXError
+        If `m1` and `m2` do not satisfy ``1 <= m1,m2 < n``, or
+        `p` does not satisfy ``0 <= p <= 1``, or
+        the initial graph number of nodes m0 does not satisfy m1, m2 <= m0 <= n.
+
+    References
+    ----------
+    .. [1] N. Moshiri "The dual-Barabasi-Albert model", arXiv:1810.10538.
+    """
+    create_using = check_create_using(create_using, directed=False, multigraph=False)
+    if m1 < 1 or m1 >= n:
+        raise nx.NetworkXError(
+            f"Dual Barabási–Albert must have m1 >= 1 and m1 < n, m1 = {m1}, n = {n}"
+        )
+    if m2 < 1 or m2 >= n:
+        raise nx.NetworkXError(
+            f"Dual Barabási–Albert must have m2 >= 1 and m2 < n, m2 = {m2}, n = {n}"
+        )
+    if p < 0 or p > 1:
+        raise nx.NetworkXError(
+            f"Dual Barabási–Albert network must have 0 <= p <= 1, p = {p}"
+        )
+
+    # For simplicity, if p == 0 or 1, just return BA
+    if p == 1:
+        return barabasi_albert_graph(n, m1, seed, create_using=create_using)
+    elif p == 0:
+        return barabasi_albert_graph(n, m2, seed, create_using=create_using)
+
+    if initial_graph is None:
+        # Default initial graph : star graph on max(m1, m2) nodes
+        G = star_graph(max(m1, m2), create_using)
+    else:
+        if len(initial_graph) < max(m1, m2) or len(initial_graph) > n:
+            raise nx.NetworkXError(
+                f"Barabási–Albert initial graph must have between "
+                f"max(m1, m2) = {max(m1, m2)} and n = {n} nodes"
+            )
+        G = initial_graph.copy()
+
+    # Target nodes for new edges
+    targets = list(G)
+    # List of existing nodes, with nodes repeated once for each adjacent edge
+    repeated_nodes = [n for n, d in G.degree() for _ in range(d)]
+    # Start adding the remaining nodes.
+    source = len(G)
+    while source < n:
+        # Pick which m to use (m1 or m2)
+        if seed.random() < p:
+            m = m1
+        else:
+            m = m2
+        # Now choose m unique nodes from the existing nodes
+        # Pick uniformly from repeated_nodes (preferential attachment)
+        targets = _random_subset(repeated_nodes, m, seed)
+        # Add edges to m nodes from the source.
+        G.add_edges_from(zip([source] * m, targets))
+        # Add one node to the list for each new edge just created.
+        repeated_nodes.extend(targets)
+        # And the new node "source" has m edges to add to the list.
+        repeated_nodes.extend([source] * m)
+
+        source += 1
+    return G
+
+
+@py_random_state(4)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def extended_barabasi_albert_graph(n, m, p, q, seed=None, *, create_using=None):
+    """Returns an extended Barabási–Albert model graph.
+
+    An extended Barabási–Albert model graph is a random graph constructed
+    using preferential attachment. The extended model allows new edges,
+    rewired edges or new nodes. Based on the probabilities $p$ and $q$
+    with $p + q < 1$, the growing behavior of the graph is determined as:
+
+    1) With $p$ probability, $m$ new edges are added to the graph,
+    starting from randomly chosen existing nodes and attached preferentially at the
+    other end.
+
+    2) With $q$ probability, $m$ existing edges are rewired
+    by randomly choosing an edge and rewiring one end to a preferentially chosen node.
+
+    3) With $(1 - p - q)$ probability, $m$ new nodes are added to the graph
+    with edges attached preferentially.
+
+    When $p = q = 0$, the model behaves just like the Barabási–Alber model.
+
+    Parameters
+    ----------
+    n : int
+        Number of nodes
+    m : int
+        Number of edges with which a new node attaches to existing nodes
+    p : float
+        Probability value for adding an edge between existing nodes. p + q < 1
+    q : float
+        Probability value of rewiring of existing edges. p + q < 1
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    create_using : Graph constructor, optional (default=nx.Graph)
+        Graph type to create. If graph instance, then cleared before populated.
+        Multigraph and directed types are not supported and raise a ``NetworkXError``.
+
+    Returns
+    -------
+    G : Graph
+
+    Raises
+    ------
+    NetworkXError
+        If `m` does not satisfy ``1 <= m < n`` or ``1 >= p + q``
+
+    References
+    ----------
+    .. [1] Albert, R., & Barabási, A. L. (2000)
+       Topology of evolving networks: local events and universality
+       Physical review letters, 85(24), 5234.
+    """
+    create_using = check_create_using(create_using, directed=False, multigraph=False)
+    if m < 1 or m >= n:
+        msg = f"Extended Barabasi-Albert network needs m>=1 and m= 1:
+        msg = f"Extended Barabasi-Albert network needs p + q <= 1, p={p}, q={q}"
+        raise nx.NetworkXError(msg)
+
+    # Add m initial nodes (m0 in barabasi-speak)
+    G = empty_graph(m, create_using)
+
+    # List of nodes to represent the preferential attachment random selection.
+    # At the creation of the graph, all nodes are added to the list
+    # so that even nodes that are not connected have a chance to get selected,
+    # for rewiring and adding of edges.
+    # With each new edge, nodes at the ends of the edge are added to the list.
+    attachment_preference = []
+    attachment_preference.extend(range(m))
+
+    # Start adding the other n-m nodes. The first node is m.
+    new_node = m
+    while new_node < n:
+        a_probability = seed.random()
+
+        # Total number of edges of a Clique of all the nodes
+        clique_degree = len(G) - 1
+        clique_size = (len(G) * clique_degree) / 2
+
+        # Adding m new edges, if there is room to add them
+        if a_probability < p and G.size() <= clique_size - m:
+            # Select the nodes where an edge can be added
+            eligible_nodes = [nd for nd, deg in G.degree() if deg < clique_degree]
+            for i in range(m):
+                # Choosing a random source node from eligible_nodes
+                src_node = seed.choice(eligible_nodes)
+
+                # Picking a possible node that is not 'src_node' or
+                # neighbor with 'src_node', with preferential attachment
+                prohibited_nodes = list(G[src_node])
+                prohibited_nodes.append(src_node)
+                # This will raise an exception if the sequence is empty
+                dest_node = seed.choice(
+                    [nd for nd in attachment_preference if nd not in prohibited_nodes]
+                )
+                # Adding the new edge
+                G.add_edge(src_node, dest_node)
+
+                # Appending both nodes to add to their preferential attachment
+                attachment_preference.append(src_node)
+                attachment_preference.append(dest_node)
+
+                # Adjusting the eligible nodes. Degree may be saturated.
+                if G.degree(src_node) == clique_degree:
+                    eligible_nodes.remove(src_node)
+                if G.degree(dest_node) == clique_degree and dest_node in eligible_nodes:
+                    eligible_nodes.remove(dest_node)
+
+        # Rewiring m edges, if there are enough edges
+        elif p <= a_probability < (p + q) and m <= G.size() < clique_size:
+            # Selecting nodes that have at least 1 edge but that are not
+            # fully connected to ALL other nodes (center of star).
+            # These nodes are the pivot nodes of the edges to rewire
+            eligible_nodes = [nd for nd, deg in G.degree() if 0 < deg < clique_degree]
+            for i in range(m):
+                # Choosing a random source node
+                node = seed.choice(eligible_nodes)
+
+                # The available nodes do have a neighbor at least.
+                nbr_nodes = list(G[node])
+
+                # Choosing the other end that will get detached
+                src_node = seed.choice(nbr_nodes)
+
+                # Picking a target node that is not 'node' or
+                # neighbor with 'node', with preferential attachment
+                nbr_nodes.append(node)
+                dest_node = seed.choice(
+                    [nd for nd in attachment_preference if nd not in nbr_nodes]
+                )
+                # Rewire
+                G.remove_edge(node, src_node)
+                G.add_edge(node, dest_node)
+
+                # Adjusting the preferential attachment list
+                attachment_preference.remove(src_node)
+                attachment_preference.append(dest_node)
+
+                # Adjusting the eligible nodes.
+                # nodes may be saturated or isolated.
+                if G.degree(src_node) == 0 and src_node in eligible_nodes:
+                    eligible_nodes.remove(src_node)
+                if dest_node in eligible_nodes:
+                    if G.degree(dest_node) == clique_degree:
+                        eligible_nodes.remove(dest_node)
+                else:
+                    if G.degree(dest_node) == 1:
+                        eligible_nodes.append(dest_node)
+
+        # Adding new node with m edges
+        else:
+            # Select the edges' nodes by preferential attachment
+            targets = _random_subset(attachment_preference, m, seed)
+            G.add_edges_from(zip([new_node] * m, targets))
+
+            # Add one node to the list for each new edge just created.
+            attachment_preference.extend(targets)
+            # The new node has m edges to it, plus itself: m + 1
+            attachment_preference.extend([new_node] * (m + 1))
+            new_node += 1
+    return G
+
+
+@py_random_state(3)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def powerlaw_cluster_graph(n, m, p, seed=None, *, create_using=None):
+    """Holme and Kim algorithm for growing graphs with powerlaw
+    degree distribution and approximate average clustering.
+
+    Parameters
+    ----------
+    n : int
+        the number of nodes
+    m : int
+        the number of random edges to add for each new node
+    p : float,
+        Probability of adding a triangle after adding a random edge
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    create_using : Graph constructor, optional (default=nx.Graph)
+        Graph type to create. If graph instance, then cleared before populated.
+        Multigraph and directed types are not supported and raise a ``NetworkXError``.
+
+    Notes
+    -----
+    The average clustering has a hard time getting above a certain
+    cutoff that depends on `m`.  This cutoff is often quite low.  The
+    transitivity (fraction of triangles to possible triangles) seems to
+    decrease with network size.
+
+    It is essentially the Barabási–Albert (BA) growth model with an
+    extra step that each random edge is followed by a chance of
+    making an edge to one of its neighbors too (and thus a triangle).
+
+    This algorithm improves on BA in the sense that it enables a
+    higher average clustering to be attained if desired.
+
+    It seems possible to have a disconnected graph with this algorithm
+    since the initial `m` nodes may not be all linked to a new node
+    on the first iteration like the BA model.
+
+    Raises
+    ------
+    NetworkXError
+        If `m` does not satisfy ``1 <= m <= n`` or `p` does not
+        satisfy ``0 <= p <= 1``.
+
+    References
+    ----------
+    .. [1] P. Holme and B. J. Kim,
+       "Growing scale-free networks with tunable clustering",
+       Phys. Rev. E, 65, 026107, 2002.
+    """
+    create_using = check_create_using(create_using, directed=False, multigraph=False)
+    if m < 1 or n < m:
+        raise nx.NetworkXError(f"NetworkXError must have m>1 and m 1 or p < 0:
+        raise nx.NetworkXError(f"NetworkXError p must be in [0,1], p={p}")
+
+    G = empty_graph(m, create_using)  # add m initial nodes (m0 in barabasi-speak)
+    repeated_nodes = list(G)  # list of existing nodes to sample from
+    # with nodes repeated once for each adjacent edge
+    source = m  # next node is m
+    while source < n:  # Now add the other n-1 nodes
+        possible_targets = _random_subset(repeated_nodes, m, seed)
+        # do one preferential attachment for new node
+        target = possible_targets.pop()
+        G.add_edge(source, target)
+        repeated_nodes.append(target)  # add one node to list for each new link
+        count = 1
+        while count < m:  # add m-1 more new links
+            if seed.random() < p:  # clustering step: add triangle
+                neighborhood = [
+                    nbr
+                    for nbr in G.neighbors(target)
+                    if not G.has_edge(source, nbr) and nbr != source
+                ]
+                if neighborhood:  # if there is a neighbor without a link
+                    nbr = seed.choice(neighborhood)
+                    G.add_edge(source, nbr)  # add triangle
+                    repeated_nodes.append(nbr)
+                    count = count + 1
+                    continue  # go to top of while loop
+            # else do preferential attachment step if above fails
+            target = possible_targets.pop()
+            G.add_edge(source, target)
+            repeated_nodes.append(target)
+            count = count + 1
+
+        repeated_nodes.extend([source] * m)  # add source node to list m times
+        source += 1
+    return G
+
+
+@py_random_state(3)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def random_lobster_graph(n, p1, p2, seed=None, *, create_using=None):
+    """Returns a random lobster graph.
+
+    A lobster is a tree that reduces to a caterpillar when pruning all
+    leaf nodes. A caterpillar is a tree that reduces to a path graph
+    when pruning all leaf nodes; setting `p2` to zero produces a caterpillar.
+
+    This implementation iterates on the probabilities `p1` and `p2` to add
+    edges at levels 1 and 2, respectively. Graphs are therefore constructed
+    iteratively with uniform randomness at each level rather than being selected
+    uniformly at random from the set of all possible lobsters.
+
+    Parameters
+    ----------
+    n : int
+        The expected number of nodes in the backbone
+    p1 : float
+        Probability of adding an edge to the backbone
+    p2 : float
+        Probability of adding an edge one level beyond backbone
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    create_using : Graph constructor, optional (default=nx.Graph)
+        Graph type to create. If graph instance, then cleared before populated.
+        Multigraph and directed types are not supported and raise a ``NetworkXError``.
+
+    Raises
+    ------
+    NetworkXError
+        If `p1` or `p2` parameters are >= 1 because the while loops would never finish.
+    """
+    create_using = check_create_using(create_using, directed=False, multigraph=False)
+    p1, p2 = abs(p1), abs(p2)
+    if any(p >= 1 for p in [p1, p2]):
+        raise nx.NetworkXError("Probability values for `p1` and `p2` must both be < 1.")
+
+    # a necessary ingredient in any self-respecting graph library
+    llen = int(2 * seed.random() * n + 0.5)
+    L = path_graph(llen, create_using)
+    # build caterpillar: add edges to path graph with probability p1
+    current_node = llen - 1
+    for n in range(llen):
+        while seed.random() < p1:  # add fuzzy caterpillar parts
+            current_node += 1
+            L.add_edge(n, current_node)
+            cat_node = current_node
+            while seed.random() < p2:  # add crunchy lobster bits
+                current_node += 1
+                L.add_edge(cat_node, current_node)
+    return L  # voila, un lobster!
+
+
+@py_random_state(3)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def random_lobster(n, p1, p2, seed=None, *, create_using=None):
+    """
+    .. deprecated:: 3.5
+       `random_lobster` is a deprecated alias
+       for `random_lobster_graph`.
+       Use `random_lobster_graph` instead.
+    """
+    import warnings
+
+    warnings.warn(
+        "`random_lobster` is deprecated, use `random_lobster_graph` instead.",
+        category=DeprecationWarning,
+        stacklevel=2,
+    )
+    return random_lobster_graph(n, p1, p2, seed=seed, create_using=create_using)
+
+
+@py_random_state(1)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def random_shell_graph(constructor, seed=None, *, create_using=None):
+    """Returns a random shell graph for the constructor given.
+
+    Parameters
+    ----------
+    constructor : list of three-tuples
+        Represents the parameters for a shell, starting at the center
+        shell.  Each element of the list must be of the form `(n, m,
+        d)`, where `n` is the number of nodes in the shell, `m` is
+        the number of edges in the shell, and `d` is the ratio of
+        inter-shell (next) edges to intra-shell edges. If `d` is zero,
+        there will be no intra-shell edges, and if `d` is one there
+        will be all possible intra-shell edges.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    create_using : Graph constructor, optional (default=nx.Graph)
+        Graph type to create. Graph instances are not supported.
+        Multigraph and directed types are not supported and raise a ``NetworkXError``.
+
+    Examples
+    --------
+    >>> constructor = [(10, 20, 0.8), (20, 40, 0.8)]
+    >>> G = nx.random_shell_graph(constructor)
+
+    """
+    create_using = check_create_using(create_using, directed=False, multigraph=False)
+    G = empty_graph(0, create_using)
+
+    glist = []
+    intra_edges = []
+    nnodes = 0
+    # create gnm graphs for each shell
+    for n, m, d in constructor:
+        inter_edges = int(m * d)
+        intra_edges.append(m - inter_edges)
+        g = nx.convert_node_labels_to_integers(
+            gnm_random_graph(n, inter_edges, seed=seed, create_using=G.__class__),
+            first_label=nnodes,
+        )
+        glist.append(g)
+        nnodes += n
+        G = nx.operators.union(G, g)
+
+    # connect the shells randomly
+    for gi in range(len(glist) - 1):
+        nlist1 = list(glist[gi])
+        nlist2 = list(glist[gi + 1])
+        total_edges = intra_edges[gi]
+        edge_count = 0
+        while edge_count < total_edges:
+            u = seed.choice(nlist1)
+            v = seed.choice(nlist2)
+            if u == v or G.has_edge(u, v):
+                continue
+            else:
+                G.add_edge(u, v)
+                edge_count = edge_count + 1
+    return G
+
+
+@py_random_state(2)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def random_powerlaw_tree(n, gamma=3, seed=None, tries=100, *, create_using=None):
+    """Returns a tree with a power law degree distribution.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes.
+    gamma : float
+        Exponent of the power law.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    tries : int
+        Number of attempts to adjust the sequence to make it a tree.
+    create_using : Graph constructor, optional (default=nx.Graph)
+        Graph type to create. If graph instance, then cleared before populated.
+        Multigraph and directed types are not supported and raise a ``NetworkXError``.
+
+    Raises
+    ------
+    NetworkXError
+        If no valid sequence is found within the maximum number of
+        attempts.
+
+    Notes
+    -----
+    A trial power law degree sequence is chosen and then elements are
+    swapped with new elements from a powerlaw distribution until the
+    sequence makes a tree (by checking, for example, that the number of
+    edges is one smaller than the number of nodes).
+
+    """
+    create_using = check_create_using(create_using, directed=False, multigraph=False)
+    # This call may raise a NetworkXError if the number of tries is succeeded.
+    seq = random_powerlaw_tree_sequence(n, gamma=gamma, seed=seed, tries=tries)
+    G = degree_sequence_tree(seq, create_using)
+    return G
+
+
+@py_random_state(2)
+@nx._dispatchable(graphs=None)
+def random_powerlaw_tree_sequence(n, gamma=3, seed=None, tries=100):
+    """Returns a degree sequence for a tree with a power law distribution.
+
+    Parameters
+    ----------
+    n : int,
+        The number of nodes.
+    gamma : float
+        Exponent of the power law.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    tries : int
+        Number of attempts to adjust the sequence to make it a tree.
+
+    Raises
+    ------
+    NetworkXError
+        If no valid sequence is found within the maximum number of
+        attempts.
+
+    Notes
+    -----
+    A trial power law degree sequence is chosen and then elements are
+    swapped with new elements from a power law distribution until
+    the sequence makes a tree (by checking, for example, that the number of
+    edges is one smaller than the number of nodes).
+
+    """
+    # get trial sequence
+    z = nx.utils.powerlaw_sequence(n, exponent=gamma, seed=seed)
+    # round to integer values in the range [0,n]
+    zseq = [min(n, max(round(s), 0)) for s in z]
+
+    # another sequence to swap values from
+    z = nx.utils.powerlaw_sequence(tries, exponent=gamma, seed=seed)
+    # round to integer values in the range [0,n]
+    swap = [min(n, max(round(s), 0)) for s in z]
+
+    for _ in swap:
+        valid, _ = nx.utils.is_valid_tree_degree_sequence(zseq)
+        if valid:
+            return zseq
+        index = seed.randint(0, n - 1)
+        zseq[index] = swap.pop()
+
+    raise nx.NetworkXError(
+        f"Exceeded max ({tries}) attempts for a valid tree sequence."
+    )
+
+
+@py_random_state(3)
+@nx._dispatchable(graphs=None, returns_graph=True)
+def random_kernel_graph(
+    n, kernel_integral, kernel_root=None, seed=None, *, create_using=None
+):
+    r"""Returns an random graph based on the specified kernel.
+
+    The algorithm chooses each of the $[n(n-1)]/2$ possible edges with
+    probability specified by a kernel $\kappa(x,y)$ [1]_.  The kernel
+    $\kappa(x,y)$ must be a symmetric (in $x,y$), non-negative,
+    bounded function.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes
+    kernel_integral : function
+        Function that returns the definite integral of the kernel $\kappa(x,y)$,
+        $F(y,a,b) := \int_a^b \kappa(x,y)dx$
+    kernel_root: function (optional)
+        Function that returns the root $b$ of the equation $F(y,a,b) = r$.
+        If None, the root is found using :func:`scipy.optimize.brentq`
+        (this requires SciPy).
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+    create_using : Graph constructor, optional (default=nx.Graph)
+        Graph type to create. If graph instance, then cleared before populated.
+        Multigraph and directed types are not supported and raise a ``NetworkXError``.
+
+    Notes
+    -----
+    The kernel is specified through its definite integral which must be
+    provided as one of the arguments. If the integral and root of the
+    kernel integral can be found in $O(1)$ time then this algorithm runs in
+    time $O(n+m)$ where m is the expected number of edges [2]_.
+
+    The nodes are set to integers from $0$ to $n-1$.
+
+    Examples
+    --------
+    Generate an Erdős–Rényi random graph $G(n,c/n)$, with kernel
+    $\kappa(x,y)=c$ where $c$ is the mean expected degree.
+
+    >>> def integral(u, w, z):
+    ...     return c * (z - w)
+    >>> def root(u, w, r):
+    ...     return r / c + w
+    >>> c = 1
+    >>> graph = nx.random_kernel_graph(1000, integral, root)
+
+    See Also
+    --------
+    gnp_random_graph
+    expected_degree_graph
+
+    References
+    ----------
+    .. [1] Bollobás, Béla,  Janson, S. and Riordan, O.
+       "The phase transition in inhomogeneous random graphs",
+       *Random Structures Algorithms*, 31, 3--122, 2007.
+
+    .. [2] Hagberg A, Lemons N (2015),
+       "Fast Generation of Sparse Random Kernel Graphs".
+       PLoS ONE 10(9): e0135177, 2015. doi:10.1371/journal.pone.0135177
+    """
+    create_using = check_create_using(create_using, directed=False, multigraph=False)
+    if kernel_root is None:
+        import scipy as sp
+
+        def kernel_root(y, a, r):
+            def my_function(b):
+                return kernel_integral(y, a, b) - r
+
+            return sp.optimize.brentq(my_function, a, 1)
+
+    graph = nx.empty_graph(create_using=create_using)
+    graph.add_nodes_from(range(n))
+    (i, j) = (1, 1)
+    while i < n:
+        r = -math.log(1 - seed.random())  # (1-seed.random()) in (0, 1]
+        if kernel_integral(i / n, j / n, 1) <= r:
+            i, j = i + 1, i + 1
+        else:
+            j = math.ceil(n * kernel_root(i / n, j / n, r))
+            graph.add_edge(i - 1, j - 1)
+    return graph
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/small.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/small.py
new file mode 100644
index 0000000000000000000000000000000000000000..12fc2a3c99c893609ba43ce0af9af5404be19957
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/small.py
@@ -0,0 +1,1070 @@
+"""
+Various small and named graphs, together with some compact generators.
+
+"""
+
+__all__ = [
+    "LCF_graph",
+    "bull_graph",
+    "chvatal_graph",
+    "cubical_graph",
+    "desargues_graph",
+    "diamond_graph",
+    "dodecahedral_graph",
+    "frucht_graph",
+    "generalized_petersen_graph",
+    "heawood_graph",
+    "hoffman_singleton_graph",
+    "house_graph",
+    "house_x_graph",
+    "icosahedral_graph",
+    "krackhardt_kite_graph",
+    "moebius_kantor_graph",
+    "octahedral_graph",
+    "pappus_graph",
+    "petersen_graph",
+    "sedgewick_maze_graph",
+    "tetrahedral_graph",
+    "truncated_cube_graph",
+    "truncated_tetrahedron_graph",
+    "tutte_graph",
+]
+
+from functools import wraps
+
+import networkx as nx
+from networkx.exception import NetworkXError
+from networkx.generators.classic import (
+    complete_graph,
+    cycle_graph,
+    empty_graph,
+    path_graph,
+)
+
+
+def _raise_on_directed(func):
+    """
+    A decorator which inspects the `create_using` argument and raises a
+    NetworkX exception when `create_using` is a DiGraph (class or instance) for
+    graph generators that do not support directed outputs.
+
+    `create_using` may be a keyword argument or the first positional argument.
+    """
+
+    @wraps(func)
+    def wrapper(*args, **kwargs):
+        create_using = args[0] if args else kwargs.get("create_using")
+        if create_using is not None:
+            G = nx.empty_graph(create_using=create_using)
+            if G.is_directed():
+                raise NetworkXError("Directed Graph not supported in create_using")
+        return func(*args, **kwargs)
+
+    return wrapper
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def LCF_graph(n, shift_list, repeats, create_using=None):
+    """
+    Return the cubic graph specified in LCF notation.
+
+    LCF (Lederberg-Coxeter-Fruchte) notation[1]_ is a compressed
+    notation used in the generation of various cubic Hamiltonian
+    graphs of high symmetry. See, for example, `dodecahedral_graph`,
+    `desargues_graph`, `heawood_graph` and `pappus_graph`.
+
+    Nodes are drawn from ``range(n)``. Each node ``n_i`` is connected with
+    node ``n_i + shift % n`` where ``shift`` is given by cycling through
+    the input `shift_list` `repeat` s times.
+
+    Parameters
+    ----------
+    n : int
+       The starting graph is the `n`-cycle with nodes ``0, ..., n-1``.
+       The null graph is returned if `n` < 1.
+
+    shift_list : list
+       A list of integer shifts mod `n`, ``[s1, s2, .., sk]``
+
+    repeats : int
+       Integer specifying the number of times that shifts in `shift_list`
+       are successively applied to each current node in the n-cycle
+       to generate an edge between ``n_current`` and ``n_current + shift mod n``.
+
+    Returns
+    -------
+    G : Graph
+       A graph instance created from the specified LCF notation.
+
+    Examples
+    --------
+    The utility graph $K_{3,3}$
+
+    >>> G = nx.LCF_graph(6, [3, -3], 3)
+    >>> G.edges()
+    EdgeView([(0, 1), (0, 5), (0, 3), (1, 2), (1, 4), (2, 3), (2, 5), (3, 4), (4, 5)])
+
+    The Heawood graph:
+
+    >>> G = nx.LCF_graph(14, [5, -5], 7)
+    >>> nx.is_isomorphic(G, nx.heawood_graph())
+    True
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/LCF_notation
+
+    """
+    if n <= 0:
+        return empty_graph(0, create_using)
+
+    # start with the n-cycle
+    G = cycle_graph(n, create_using)
+    if G.is_directed():
+        raise NetworkXError("Directed Graph not supported")
+    G.name = "LCF_graph"
+    nodes = sorted(G)
+
+    n_extra_edges = repeats * len(shift_list)
+    # edges are added n_extra_edges times
+    # (not all of these need be new)
+    if n_extra_edges < 1:
+        return G
+
+    for i in range(n_extra_edges):
+        shift = shift_list[i % len(shift_list)]  # cycle through shift_list
+        v1 = nodes[i % n]  # cycle repeatedly through nodes
+        v2 = nodes[(i + shift) % n]
+        G.add_edge(v1, v2)
+    return G
+
+
+# -------------------------------------------------------------------------------
+#   Various small and named graphs
+# -------------------------------------------------------------------------------
+
+
+@_raise_on_directed
+@nx._dispatchable(graphs=None, returns_graph=True)
+def bull_graph(create_using=None):
+    """
+    Returns the Bull Graph
+
+    The Bull Graph has 5 nodes and 5 edges. It is a planar undirected
+    graph in the form of a triangle with two disjoint pendant edges [1]_
+    The name comes from the triangle and pendant edges representing
+    respectively the body and legs of a bull.
+
+    Parameters
+    ----------
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : networkx Graph
+        A bull graph with 5 nodes
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Bull_graph.
+
+    """
+    G = nx.from_dict_of_lists(
+        {0: [1, 2], 1: [0, 2, 3], 2: [0, 1, 4], 3: [1], 4: [2]},
+        create_using=create_using,
+    )
+    G.name = "Bull Graph"
+    return G
+
+
+@_raise_on_directed
+@nx._dispatchable(graphs=None, returns_graph=True)
+def chvatal_graph(create_using=None):
+    """
+    Returns the Chvátal Graph
+
+    The Chvátal Graph is an undirected graph with 12 nodes and 24 edges [1]_.
+    It has 370 distinct (directed) Hamiltonian cycles, giving a unique generalized
+    LCF notation of order 4, two of order 6 , and 43 of order 1 [2]_.
+
+    Parameters
+    ----------
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : networkx Graph
+        The Chvátal graph with 12 nodes and 24 edges
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Chv%C3%A1tal_graph
+    .. [2] https://mathworld.wolfram.com/ChvatalGraph.html
+
+    """
+    G = nx.from_dict_of_lists(
+        {
+            0: [1, 4, 6, 9],
+            1: [2, 5, 7],
+            2: [3, 6, 8],
+            3: [4, 7, 9],
+            4: [5, 8],
+            5: [10, 11],
+            6: [10, 11],
+            7: [8, 11],
+            8: [10],
+            9: [10, 11],
+        },
+        create_using=create_using,
+    )
+    G.name = "Chvatal Graph"
+    return G
+
+
+@_raise_on_directed
+@nx._dispatchable(graphs=None, returns_graph=True)
+def cubical_graph(create_using=None):
+    """
+    Returns the 3-regular Platonic Cubical Graph
+
+    The skeleton of the cube (the nodes and edges) form a graph, with 8
+    nodes, and 12 edges. It is a special case of the hypercube graph.
+    It is one of 5 Platonic graphs, each a skeleton of its
+    Platonic solid [1]_.
+    Such graphs arise in parallel processing in computers.
+
+    Parameters
+    ----------
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : networkx Graph
+        A cubical graph with 8 nodes and 12 edges
+
+    See Also
+    --------
+    tetrahedral_graph, octahedral_graph, dodecahedral_graph, icosahedral_graph
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Cube#Cubical_graph
+
+    """
+    G = nx.from_dict_of_lists(
+        {
+            0: [1, 3, 4],
+            1: [0, 2, 7],
+            2: [1, 3, 6],
+            3: [0, 2, 5],
+            4: [0, 5, 7],
+            5: [3, 4, 6],
+            6: [2, 5, 7],
+            7: [1, 4, 6],
+        },
+        create_using=create_using,
+    )
+    G.name = "Platonic Cubical Graph"
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def desargues_graph(create_using=None):
+    """
+    Returns the Desargues Graph
+
+    The Desargues Graph is a non-planar, distance-transitive cubic graph
+    with 20 nodes and 30 edges [1]_. It is isomorphic to the Generalized
+    Petersen Graph GP(10, 3). It is a symmetric graph. It can be represented
+    in LCF notation as [5,-5,9,-9]^5 [2]_.
+
+    Parameters
+    ----------
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : networkx Graph
+        Desargues Graph with 20 nodes and 30 edges
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Desargues_graph
+    .. [2] https://mathworld.wolfram.com/DesarguesGraph.html
+    """
+    G = LCF_graph(20, [5, -5, 9, -9], 5, create_using)
+    G.name = "Desargues Graph"
+    return G
+
+
+@_raise_on_directed
+@nx._dispatchable(graphs=None, returns_graph=True)
+def diamond_graph(create_using=None):
+    """
+    Returns the Diamond graph
+
+    The Diamond Graph is  planar undirected graph with 4 nodes and 5 edges.
+    It is also sometimes known as the double triangle graph or kite graph [1]_.
+
+    Parameters
+    ----------
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : networkx Graph
+        Diamond Graph with 4 nodes and 5 edges
+
+    References
+    ----------
+    .. [1] https://mathworld.wolfram.com/DiamondGraph.html
+    """
+    G = nx.from_dict_of_lists(
+        {0: [1, 2], 1: [0, 2, 3], 2: [0, 1, 3], 3: [1, 2]}, create_using=create_using
+    )
+    G.name = "Diamond Graph"
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def dodecahedral_graph(create_using=None):
+    """
+    Returns the Platonic Dodecahedral graph.
+
+    The dodecahedral graph has 20 nodes and 30 edges. The skeleton of the
+    dodecahedron forms a graph. It is one of 5 Platonic graphs [1]_.
+    It can be described in LCF notation as:
+    ``[10, 7, 4, -4, -7, 10, -4, 7, -7, 4]^2`` [2]_.
+
+    Parameters
+    ----------
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : networkx Graph
+        Dodecahedral Graph with 20 nodes and 30 edges
+
+    See Also
+    --------
+    tetrahedral_graph, cubical_graph, octahedral_graph, icosahedral_graph
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Regular_dodecahedron#Dodecahedral_graph
+    .. [2] https://mathworld.wolfram.com/DodecahedralGraph.html
+
+    """
+    G = LCF_graph(20, [10, 7, 4, -4, -7, 10, -4, 7, -7, 4], 2, create_using)
+    G.name = "Dodecahedral Graph"
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def frucht_graph(create_using=None):
+    """
+    Returns the Frucht Graph.
+
+    The Frucht Graph is the smallest cubical graph whose
+    automorphism group consists only of the identity element [1]_.
+    It has 12 nodes and 18 edges and no nontrivial symmetries.
+    It is planar and Hamiltonian [2]_.
+
+    Parameters
+    ----------
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : networkx Graph
+        Frucht Graph with 12 nodes and 18 edges
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Frucht_graph
+    .. [2] https://mathworld.wolfram.com/FruchtGraph.html
+
+    """
+    G = cycle_graph(7, create_using)
+    G.add_edges_from(
+        [
+            [0, 7],
+            [1, 7],
+            [2, 8],
+            [3, 9],
+            [4, 9],
+            [5, 10],
+            [6, 10],
+            [7, 11],
+            [8, 11],
+            [8, 9],
+            [10, 11],
+        ]
+    )
+
+    G.name = "Frucht Graph"
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def heawood_graph(create_using=None):
+    """
+    Returns the Heawood Graph, a (3,6) cage.
+
+    The Heawood Graph is an undirected graph with 14 nodes and 21 edges,
+    named after Percy John Heawood [1]_.
+    It is cubic symmetric, nonplanar, Hamiltonian, and can be represented
+    in LCF notation as ``[5,-5]^7`` [2]_.
+    It is the unique (3,6)-cage: the regular cubic graph of girth 6 with
+    minimal number of vertices [3]_.
+
+    Parameters
+    ----------
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : networkx Graph
+        Heawood Graph with 14 nodes and 21 edges
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Heawood_graph
+    .. [2] https://mathworld.wolfram.com/HeawoodGraph.html
+    .. [3] https://www.win.tue.nl/~aeb/graphs/Heawood.html
+
+    """
+    G = LCF_graph(14, [5, -5], 7, create_using)
+    G.name = "Heawood Graph"
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def hoffman_singleton_graph():
+    """
+    Returns the Hoffman-Singleton Graph.
+
+    The Hoffman–Singleton graph is a symmetrical undirected graph
+    with 50 nodes and 175 edges.
+    All indices lie in ``Z % 5``: that is, the integers mod 5 [1]_.
+    It is the only regular graph of vertex degree 7, diameter 2, and girth 5.
+    It is the unique (7,5)-cage graph and Moore graph, and contains many
+    copies of the Petersen Graph [2]_.
+
+    Returns
+    -------
+    G : networkx Graph
+        Hoffman–Singleton Graph with 50 nodes and 175 edges
+
+    Notes
+    -----
+    Constructed from pentagon and pentagram as follows: Take five pentagons $P_h$
+    and five pentagrams $Q_i$ . Join vertex $j$ of $P_h$ to vertex $h·i+j$ of $Q_i$ [3]_.
+
+    References
+    ----------
+    .. [1] https://blogs.ams.org/visualinsight/2016/02/01/hoffman-singleton-graph/
+    .. [2] https://mathworld.wolfram.com/Hoffman-SingletonGraph.html
+    .. [3] https://en.wikipedia.org/wiki/Hoffman%E2%80%93Singleton_graph
+
+    """
+    G = nx.Graph()
+    for i in range(5):
+        for j in range(5):
+            G.add_edge(("pentagon", i, j), ("pentagon", i, (j - 1) % 5))
+            G.add_edge(("pentagon", i, j), ("pentagon", i, (j + 1) % 5))
+            G.add_edge(("pentagram", i, j), ("pentagram", i, (j - 2) % 5))
+            G.add_edge(("pentagram", i, j), ("pentagram", i, (j + 2) % 5))
+            for k in range(5):
+                G.add_edge(("pentagon", i, j), ("pentagram", k, (i * k + j) % 5))
+    G = nx.convert_node_labels_to_integers(G)
+    G.name = "Hoffman-Singleton Graph"
+    return G
+
+
+@_raise_on_directed
+@nx._dispatchable(graphs=None, returns_graph=True)
+def house_graph(create_using=None):
+    """
+    Returns the House graph (square with triangle on top)
+
+    The house graph is a simple undirected graph with
+    5 nodes and 6 edges [1]_.
+
+    Parameters
+    ----------
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : networkx Graph
+        House graph in the form of a square with a triangle on top
+
+    References
+    ----------
+    .. [1] https://mathworld.wolfram.com/HouseGraph.html
+    """
+    G = nx.from_dict_of_lists(
+        {0: [1, 2], 1: [0, 3], 2: [0, 3, 4], 3: [1, 2, 4], 4: [2, 3]},
+        create_using=create_using,
+    )
+    G.name = "House Graph"
+    return G
+
+
+@_raise_on_directed
+@nx._dispatchable(graphs=None, returns_graph=True)
+def house_x_graph(create_using=None):
+    """
+    Returns the House graph with a cross inside the house square.
+
+    The House X-graph is the House graph plus the two edges connecting diagonally
+    opposite vertices of the square base. It is also one of the two graphs
+    obtained by removing two edges from the pentatope graph [1]_.
+
+    Parameters
+    ----------
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : networkx Graph
+        House graph with diagonal vertices connected
+
+    References
+    ----------
+    .. [1] https://mathworld.wolfram.com/HouseGraph.html
+    """
+    G = house_graph(create_using)
+    G.add_edges_from([(0, 3), (1, 2)])
+    G.name = "House-with-X-inside Graph"
+    return G
+
+
+@_raise_on_directed
+@nx._dispatchable(graphs=None, returns_graph=True)
+def icosahedral_graph(create_using=None):
+    """
+    Returns the Platonic Icosahedral graph.
+
+    The icosahedral graph has 12 nodes and 30 edges. It is a Platonic graph
+    whose nodes have the connectivity of the icosahedron. It is undirected,
+    regular and Hamiltonian [1]_.
+
+    Parameters
+    ----------
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : networkx Graph
+        Icosahedral graph with 12 nodes and 30 edges.
+
+    See Also
+    --------
+    tetrahedral_graph, cubical_graph, octahedral_graph, dodecahedral_graph
+
+    References
+    ----------
+    .. [1] https://mathworld.wolfram.com/IcosahedralGraph.html
+    """
+    G = nx.from_dict_of_lists(
+        {
+            0: [1, 5, 7, 8, 11],
+            1: [2, 5, 6, 8],
+            2: [3, 6, 8, 9],
+            3: [4, 6, 9, 10],
+            4: [5, 6, 10, 11],
+            5: [6, 11],
+            7: [8, 9, 10, 11],
+            8: [9],
+            9: [10],
+            10: [11],
+        },
+        create_using=create_using,
+    )
+    G.name = "Platonic Icosahedral Graph"
+    return G
+
+
+@_raise_on_directed
+@nx._dispatchable(graphs=None, returns_graph=True)
+def krackhardt_kite_graph(create_using=None):
+    """
+    Returns the Krackhardt Kite Social Network.
+
+    A 10 actor social network introduced by David Krackhardt
+    to illustrate different centrality measures [1]_.
+
+    Parameters
+    ----------
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : networkx Graph
+        Krackhardt Kite graph with 10 nodes and 18 edges
+
+    Notes
+    -----
+    The traditional labeling is:
+    Andre=1, Beverley=2, Carol=3, Diane=4,
+    Ed=5, Fernando=6, Garth=7, Heather=8, Ike=9, Jane=10.
+
+    References
+    ----------
+    .. [1] Krackhardt, David. "Assessing the Political Landscape: Structure,
+       Cognition, and Power in Organizations". Administrative Science Quarterly.
+       35 (2): 342–369. doi:10.2307/2393394. JSTOR 2393394. June 1990.
+
+    """
+    G = nx.from_dict_of_lists(
+        {
+            0: [1, 2, 3, 5],
+            1: [0, 3, 4, 6],
+            2: [0, 3, 5],
+            3: [0, 1, 2, 4, 5, 6],
+            4: [1, 3, 6],
+            5: [0, 2, 3, 6, 7],
+            6: [1, 3, 4, 5, 7],
+            7: [5, 6, 8],
+            8: [7, 9],
+            9: [8],
+        },
+        create_using=create_using,
+    )
+    G.name = "Krackhardt Kite Social Network"
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def moebius_kantor_graph(create_using=None):
+    """
+    Returns the Moebius-Kantor graph.
+
+    The Möbius-Kantor graph is the cubic symmetric graph on 16 nodes.
+    Its LCF notation is [5,-5]^8, and it is isomorphic to the generalized
+    Petersen Graph GP(8, 3) [1]_.
+
+    Parameters
+    ----------
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : networkx Graph
+        Moebius-Kantor graph
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/M%C3%B6bius%E2%80%93Kantor_graph
+
+    """
+    G = LCF_graph(16, [5, -5], 8, create_using)
+    G.name = "Moebius-Kantor Graph"
+    return G
+
+
+@_raise_on_directed
+@nx._dispatchable(graphs=None, returns_graph=True)
+def octahedral_graph(create_using=None):
+    """
+    Returns the Platonic Octahedral graph.
+
+    The octahedral graph is the 6-node 12-edge Platonic graph having the
+    connectivity of the octahedron [1]_. If 6 couples go to a party,
+    and each person shakes hands with every person except his or her partner,
+    then this graph describes the set of handshakes that take place;
+    for this reason it is also called the cocktail party graph [2]_.
+
+    Parameters
+    ----------
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : networkx Graph
+        Octahedral graph
+
+    See Also
+    --------
+    tetrahedral_graph, cubical_graph, dodecahedral_graph, icosahedral_graph
+
+    References
+    ----------
+    .. [1] https://mathworld.wolfram.com/OctahedralGraph.html
+    .. [2] https://en.wikipedia.org/wiki/Tur%C3%A1n_graph#Special_cases
+
+    """
+    G = nx.from_dict_of_lists(
+        {0: [1, 2, 3, 4], 1: [2, 3, 5], 2: [4, 5], 3: [4, 5], 4: [5]},
+        create_using=create_using,
+    )
+    G.name = "Platonic Octahedral Graph"
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def pappus_graph():
+    """
+    Returns the Pappus graph.
+
+    The Pappus graph is a cubic symmetric distance-regular graph with 18 nodes
+    and 27 edges. It is Hamiltonian and can be represented in LCF notation as
+    [5,7,-7,7,-7,-5]^3 [1]_.
+
+    Returns
+    -------
+    G : networkx Graph
+        Pappus graph
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Pappus_graph
+    """
+    G = LCF_graph(18, [5, 7, -7, 7, -7, -5], 3)
+    G.name = "Pappus Graph"
+    return G
+
+
+@_raise_on_directed
+@nx._dispatchable(graphs=None, returns_graph=True)
+def petersen_graph(create_using=None):
+    """
+    Returns the Petersen Graph.
+
+    The Peterson Graph is a cubic, undirected graph with 10 nodes and 15 edges [1]_.
+    Julius Petersen constructed the graph as the smallest counterexample
+    against the claim that a connected bridgeless cubic graph
+    has an edge colouring with three colours [2]_.
+
+    Parameters
+    ----------
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : networkx Graph
+        Petersen Graph
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Petersen_graph
+    .. [2] https://www.win.tue.nl/~aeb/drg/graphs/Petersen.html
+    """
+    G = nx.from_dict_of_lists(
+        {
+            0: [1, 4, 5],
+            1: [0, 2, 6],
+            2: [1, 3, 7],
+            3: [2, 4, 8],
+            4: [3, 0, 9],
+            5: [0, 7, 8],
+            6: [1, 8, 9],
+            7: [2, 5, 9],
+            8: [3, 5, 6],
+            9: [4, 6, 7],
+        },
+        create_using=create_using,
+    )
+    G.name = "Petersen Graph"
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def generalized_petersen_graph(n, k, *, create_using=None):
+    """
+    Returns the Generalized Petersen Graph GP(n,k).
+
+    The Generalized Peterson Graph consists of an outer cycle of n nodes
+    connected to an inner circulant graph of n nodes, where nodes in the
+    inner circulant are connected to their kth nearest neighbor [1]_ [2]_.
+    A Generalized Petersen Graph is cubic with 2n nodes and 3n edges.
+
+    Some well known graphs are examples of Generalized Petersen Graphs such
+    as the Petersen Graph GP(5, 2), the Desargues graph GP(10, 3), the
+    Moebius-Kantor graph GP(8, 3), and the dodecahedron graph GP(10, 2).
+
+    Parameters
+    ----------
+    n : int
+       Number of nodes in the outer cycle and inner circulant. ``n >= 3`` is required.
+
+    k : int
+       Neighbor to connect in the inner circulant. ``1 <= k <= n/2``.
+       Note that some people require ``k < n/2`` but we and others allow equality.
+       Also, ``k < n/2`` is equivalent to ``k <= floor((n-1)/2)``
+
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : networkx Graph
+        Generalized Petersen Graph n k
+
+    References
+    ----------
+    .. [1] https://mathworld.wolfram.com/GeneralizedPetersenGraph.html
+    .. [2] https://en.wikipedia.org/wiki/Generalized_Petersen_graph
+    """
+    if n <= 2:
+        raise NetworkXError(f"n >= 3 required. Got {n=}")
+    if k < 1 or k > n / 2:
+        raise NetworkXError(f" Got {n=} {k=}. Need 1 <= k <= n/2")
+
+    G = nx.cycle_graph(range(n), create_using=create_using)  # u-nodes
+    if G.is_directed():
+        raise NetworkXError("Directed Graph not supported in create_using")
+    for i in range(n):
+        G.add_edge(i, n + i)  # add v-nodes and u to v edges
+        G.add_edge(n + i, n + (i + k) % n)  # edge from v_i to v_(i+k)%n
+
+    G.name = f"Generalized Petersen Graph GP({n}, {k})"
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def sedgewick_maze_graph(create_using=None):
+    """
+    Return a small maze with a cycle.
+
+    This is the maze used in Sedgewick, 3rd Edition, Part 5, Graph
+    Algorithms, Chapter 18, e.g. Figure 18.2 and following [1]_.
+    Nodes are numbered 0,..,7
+
+    Parameters
+    ----------
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : networkx Graph
+        Small maze with a cycle
+
+    References
+    ----------
+    .. [1] Figure 18.2, Chapter 18, Graph Algorithms (3rd Ed), Sedgewick
+    """
+    G = empty_graph(0, create_using)
+    G.add_nodes_from(range(8))
+    G.add_edges_from([[0, 2], [0, 7], [0, 5]])
+    G.add_edges_from([[1, 7], [2, 6]])
+    G.add_edges_from([[3, 4], [3, 5]])
+    G.add_edges_from([[4, 5], [4, 7], [4, 6]])
+    G.name = "Sedgewick Maze"
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def tetrahedral_graph(create_using=None):
+    """
+    Returns the 3-regular Platonic Tetrahedral graph.
+
+    Tetrahedral graph has 4 nodes and 6 edges. It is a
+    special case of the complete graph, K4, and wheel graph, W4.
+    It is one of the 5 platonic graphs [1]_.
+
+    Parameters
+    ----------
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : networkx Graph
+        Tetrahedral Graph
+
+    See Also
+    --------
+    cubical_graph, octahedral_graph, dodecahedral_graph, icosahedral_graph
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Tetrahedron#Tetrahedral_graph
+
+    """
+    G = complete_graph(4, create_using)
+    G.name = "Platonic Tetrahedral Graph"
+    return G
+
+
+@_raise_on_directed
+@nx._dispatchable(graphs=None, returns_graph=True)
+def truncated_cube_graph(create_using=None):
+    """
+    Returns the skeleton of the truncated cube.
+
+    The truncated cube is an Archimedean solid with 14 regular
+    faces (6 octagonal and 8 triangular), 36 edges and 24 nodes [1]_.
+    The truncated cube is created by truncating (cutting off) the tips
+    of the cube one third of the way into each edge [2]_.
+
+    Parameters
+    ----------
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : networkx Graph
+        Skeleton of the truncated cube
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Truncated_cube
+    .. [2] https://www.coolmath.com/reference/polyhedra-truncated-cube
+
+    """
+    G = nx.from_dict_of_lists(
+        {
+            0: [1, 2, 4],
+            1: [11, 14],
+            2: [3, 4],
+            3: [6, 8],
+            4: [5],
+            5: [16, 18],
+            6: [7, 8],
+            7: [10, 12],
+            8: [9],
+            9: [17, 20],
+            10: [11, 12],
+            11: [14],
+            12: [13],
+            13: [21, 22],
+            14: [15],
+            15: [19, 23],
+            16: [17, 18],
+            17: [20],
+            18: [19],
+            19: [23],
+            20: [21],
+            21: [22],
+            22: [23],
+        },
+        create_using=create_using,
+    )
+    G.name = "Truncated Cube Graph"
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def truncated_tetrahedron_graph(create_using=None):
+    """
+    Returns the skeleton of the truncated Platonic tetrahedron.
+
+    The truncated tetrahedron is an Archimedean solid with 4 regular hexagonal faces,
+    4 equilateral triangle faces, 12 nodes and 18 edges. It can be constructed by truncating
+    all 4 vertices of a regular tetrahedron at one third of the original edge length [1]_.
+
+    Parameters
+    ----------
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : networkx Graph
+        Skeleton of the truncated tetrahedron
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Truncated_tetrahedron
+
+    """
+    G = path_graph(12, create_using)
+    G.add_edges_from([(0, 2), (0, 9), (1, 6), (3, 11), (4, 11), (5, 7), (8, 10)])
+    G.name = "Truncated Tetrahedron Graph"
+    return G
+
+
+@_raise_on_directed
+@nx._dispatchable(graphs=None, returns_graph=True)
+def tutte_graph(create_using=None):
+    """
+    Returns the Tutte graph.
+
+    The Tutte graph is a cubic polyhedral, non-Hamiltonian graph. It has
+    46 nodes and 69 edges.
+    It is a counterexample to Tait's conjecture that every 3-regular polyhedron
+    has a Hamiltonian cycle.
+    It can be realized geometrically from a tetrahedron by multiply truncating
+    three of its vertices [1]_.
+
+    Parameters
+    ----------
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    Returns
+    -------
+    G : networkx Graph
+        Tutte graph
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Tutte_graph
+    """
+    G = nx.from_dict_of_lists(
+        {
+            0: [1, 2, 3],
+            1: [4, 26],
+            2: [10, 11],
+            3: [18, 19],
+            4: [5, 33],
+            5: [6, 29],
+            6: [7, 27],
+            7: [8, 14],
+            8: [9, 38],
+            9: [10, 37],
+            10: [39],
+            11: [12, 39],
+            12: [13, 35],
+            13: [14, 15],
+            14: [34],
+            15: [16, 22],
+            16: [17, 44],
+            17: [18, 43],
+            18: [45],
+            19: [20, 45],
+            20: [21, 41],
+            21: [22, 23],
+            22: [40],
+            23: [24, 27],
+            24: [25, 32],
+            25: [26, 31],
+            26: [33],
+            27: [28],
+            28: [29, 32],
+            29: [30],
+            30: [31, 33],
+            31: [32],
+            34: [35, 38],
+            35: [36],
+            36: [37, 39],
+            37: [38],
+            40: [41, 44],
+            41: [42],
+            42: [43, 45],
+            43: [44],
+        },
+        create_using=create_using,
+    )
+    G.name = "Tutte's Graph"
+    return G
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/social.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/social.py
new file mode 100644
index 0000000000000000000000000000000000000000..d06ce00531fb840e0f2a6238aba97f7a40a3b8fc
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/social.py
@@ -0,0 +1,554 @@
+"""
+Famous social networks.
+"""
+
+import networkx as nx
+
+__all__ = [
+    "karate_club_graph",
+    "davis_southern_women_graph",
+    "florentine_families_graph",
+    "les_miserables_graph",
+]
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def karate_club_graph():
+    """Returns Zachary's Karate Club graph.
+
+    Each node in the returned graph has a node attribute 'club' that
+    indicates the name of the club to which the member represented by that node
+    belongs, either 'Mr. Hi' or 'Officer'. Each edge has a weight based on the
+    number of contexts in which that edge's incident node members interacted.
+
+    The dataset is derived from the 'Club After Split From Data' column of Table 3 in [1]_.
+    This was in turn derived from the 'Club After Fission' column of Table 1 in the
+    same paper. Note that the nodes are 0-indexed in NetworkX, but 1-indexed in the
+    paper (the 'Individual Number in Matrix C' column of Table 3 starts at 1). This
+    means, for example, that ``G.nodes[9]["club"]`` returns 'Officer', which
+    corresponds to row 10 of Table 3 in the paper.
+
+    Examples
+    --------
+    To get the name of the club to which a node belongs:
+
+    >>> G = nx.karate_club_graph()
+    >>> G.nodes[5]["club"]
+    'Mr. Hi'
+    >>> G.nodes[9]["club"]
+    'Officer'
+
+    References
+    ----------
+    .. [1] Zachary, Wayne W.
+       "An Information Flow Model for Conflict and Fission in Small Groups."
+       *Journal of Anthropological Research*, 33, 452--473, (1977).
+    """
+    # Create the set of all members, and the members of each club.
+    all_members = set(range(34))
+    club1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 16, 17, 19, 21}
+    # club2 = all_members - club1
+
+    G = nx.Graph()
+    G.add_nodes_from(all_members)
+    G.name = "Zachary's Karate Club"
+
+    zacharydat = """\
+0 4 5 3 3 3 3 2 2 0 2 3 2 3 0 0 0 2 0 2 0 2 0 0 0 0 0 0 0 0 0 2 0 0
+4 0 6 3 0 0 0 4 0 0 0 0 0 5 0 0 0 1 0 2 0 2 0 0 0 0 0 0 0 0 2 0 0 0
+5 6 0 3 0 0 0 4 5 1 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2 0 0 0 3 0
+3 3 3 0 0 0 0 3 0 0 0 0 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+3 0 0 0 0 0 2 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+3 0 0 0 0 0 5 0 0 0 3 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+3 0 0 0 2 5 0 0 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+2 4 4 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+2 0 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 0 4 3
+0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2
+2 0 0 0 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+1 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+3 5 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3
+0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 2
+0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 4
+0 0 0 0 0 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2
+2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
+0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 1
+2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0
+0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 0 4 0 2 0 0 5 4
+0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 3 0 0 0 2 0 0
+0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 2 0 0 0 0 0 0 7 0 0
+0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 2
+0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 3 0 0 0 0 0 0 0 0 4
+0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 2
+0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 0 0 4 0 0 0 0 0 3 2
+0 2 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 3
+2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 7 0 0 2 0 0 0 4 4
+0 0 2 0 0 0 0 0 3 0 0 0 0 0 3 3 0 0 1 0 3 0 2 5 0 0 0 0 0 4 3 4 0 5
+0 0 0 0 0 0 0 0 4 2 0 0 0 3 2 4 0 0 2 1 1 0 3 4 0 0 2 4 2 2 3 4 5 0"""
+
+    for row, line in enumerate(zacharydat.split("\n")):
+        thisrow = [int(b) for b in line.split()]
+        for col, entry in enumerate(thisrow):
+            if entry >= 1:
+                G.add_edge(row, col, weight=entry)
+
+    # Add the name of each member's club as a node attribute.
+    for v in G:
+        G.nodes[v]["club"] = "Mr. Hi" if v in club1 else "Officer"
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def davis_southern_women_graph():
+    """Returns Davis Southern women social network.
+
+    This is a bipartite graph.
+
+    References
+    ----------
+    .. [1] A. Davis, Gardner, B. B., Gardner, M. R., 1941. Deep South.
+        University of Chicago Press, Chicago, IL.
+    """
+    G = nx.Graph()
+    # Top nodes
+    women = [
+        "Evelyn Jefferson",
+        "Laura Mandeville",
+        "Theresa Anderson",
+        "Brenda Rogers",
+        "Charlotte McDowd",
+        "Frances Anderson",
+        "Eleanor Nye",
+        "Pearl Oglethorpe",
+        "Ruth DeSand",
+        "Verne Sanderson",
+        "Myra Liddel",
+        "Katherina Rogers",
+        "Sylvia Avondale",
+        "Nora Fayette",
+        "Helen Lloyd",
+        "Dorothy Murchison",
+        "Olivia Carleton",
+        "Flora Price",
+    ]
+    G.add_nodes_from(women, bipartite=0)
+    # Bottom nodes
+    events = [
+        "E1",
+        "E2",
+        "E3",
+        "E4",
+        "E5",
+        "E6",
+        "E7",
+        "E8",
+        "E9",
+        "E10",
+        "E11",
+        "E12",
+        "E13",
+        "E14",
+    ]
+    G.add_nodes_from(events, bipartite=1)
+
+    G.add_edges_from(
+        [
+            ("Evelyn Jefferson", "E1"),
+            ("Evelyn Jefferson", "E2"),
+            ("Evelyn Jefferson", "E3"),
+            ("Evelyn Jefferson", "E4"),
+            ("Evelyn Jefferson", "E5"),
+            ("Evelyn Jefferson", "E6"),
+            ("Evelyn Jefferson", "E8"),
+            ("Evelyn Jefferson", "E9"),
+            ("Laura Mandeville", "E1"),
+            ("Laura Mandeville", "E2"),
+            ("Laura Mandeville", "E3"),
+            ("Laura Mandeville", "E5"),
+            ("Laura Mandeville", "E6"),
+            ("Laura Mandeville", "E7"),
+            ("Laura Mandeville", "E8"),
+            ("Theresa Anderson", "E2"),
+            ("Theresa Anderson", "E3"),
+            ("Theresa Anderson", "E4"),
+            ("Theresa Anderson", "E5"),
+            ("Theresa Anderson", "E6"),
+            ("Theresa Anderson", "E7"),
+            ("Theresa Anderson", "E8"),
+            ("Theresa Anderson", "E9"),
+            ("Brenda Rogers", "E1"),
+            ("Brenda Rogers", "E3"),
+            ("Brenda Rogers", "E4"),
+            ("Brenda Rogers", "E5"),
+            ("Brenda Rogers", "E6"),
+            ("Brenda Rogers", "E7"),
+            ("Brenda Rogers", "E8"),
+            ("Charlotte McDowd", "E3"),
+            ("Charlotte McDowd", "E4"),
+            ("Charlotte McDowd", "E5"),
+            ("Charlotte McDowd", "E7"),
+            ("Frances Anderson", "E3"),
+            ("Frances Anderson", "E5"),
+            ("Frances Anderson", "E6"),
+            ("Frances Anderson", "E8"),
+            ("Eleanor Nye", "E5"),
+            ("Eleanor Nye", "E6"),
+            ("Eleanor Nye", "E7"),
+            ("Eleanor Nye", "E8"),
+            ("Pearl Oglethorpe", "E6"),
+            ("Pearl Oglethorpe", "E8"),
+            ("Pearl Oglethorpe", "E9"),
+            ("Ruth DeSand", "E5"),
+            ("Ruth DeSand", "E7"),
+            ("Ruth DeSand", "E8"),
+            ("Ruth DeSand", "E9"),
+            ("Verne Sanderson", "E7"),
+            ("Verne Sanderson", "E8"),
+            ("Verne Sanderson", "E9"),
+            ("Verne Sanderson", "E12"),
+            ("Myra Liddel", "E8"),
+            ("Myra Liddel", "E9"),
+            ("Myra Liddel", "E10"),
+            ("Myra Liddel", "E12"),
+            ("Katherina Rogers", "E8"),
+            ("Katherina Rogers", "E9"),
+            ("Katherina Rogers", "E10"),
+            ("Katherina Rogers", "E12"),
+            ("Katherina Rogers", "E13"),
+            ("Katherina Rogers", "E14"),
+            ("Sylvia Avondale", "E7"),
+            ("Sylvia Avondale", "E8"),
+            ("Sylvia Avondale", "E9"),
+            ("Sylvia Avondale", "E10"),
+            ("Sylvia Avondale", "E12"),
+            ("Sylvia Avondale", "E13"),
+            ("Sylvia Avondale", "E14"),
+            ("Nora Fayette", "E6"),
+            ("Nora Fayette", "E7"),
+            ("Nora Fayette", "E9"),
+            ("Nora Fayette", "E10"),
+            ("Nora Fayette", "E11"),
+            ("Nora Fayette", "E12"),
+            ("Nora Fayette", "E13"),
+            ("Nora Fayette", "E14"),
+            ("Helen Lloyd", "E7"),
+            ("Helen Lloyd", "E8"),
+            ("Helen Lloyd", "E10"),
+            ("Helen Lloyd", "E11"),
+            ("Helen Lloyd", "E12"),
+            ("Dorothy Murchison", "E8"),
+            ("Dorothy Murchison", "E9"),
+            ("Olivia Carleton", "E9"),
+            ("Olivia Carleton", "E11"),
+            ("Flora Price", "E9"),
+            ("Flora Price", "E11"),
+        ]
+    )
+    G.graph["top"] = women
+    G.graph["bottom"] = events
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def florentine_families_graph():
+    """Returns Florentine families graph.
+
+    References
+    ----------
+    .. [1] Ronald L. Breiger and Philippa E. Pattison
+       Cumulated social roles: The duality of persons and their algebras,1
+       Social Networks, Volume 8, Issue 3, September 1986, Pages 215-256
+    """
+    G = nx.Graph()
+    G.add_edge("Acciaiuoli", "Medici")
+    G.add_edge("Castellani", "Peruzzi")
+    G.add_edge("Castellani", "Strozzi")
+    G.add_edge("Castellani", "Barbadori")
+    G.add_edge("Medici", "Barbadori")
+    G.add_edge("Medici", "Ridolfi")
+    G.add_edge("Medici", "Tornabuoni")
+    G.add_edge("Medici", "Albizzi")
+    G.add_edge("Medici", "Salviati")
+    G.add_edge("Salviati", "Pazzi")
+    G.add_edge("Peruzzi", "Strozzi")
+    G.add_edge("Peruzzi", "Bischeri")
+    G.add_edge("Strozzi", "Ridolfi")
+    G.add_edge("Strozzi", "Bischeri")
+    G.add_edge("Ridolfi", "Tornabuoni")
+    G.add_edge("Tornabuoni", "Guadagni")
+    G.add_edge("Albizzi", "Ginori")
+    G.add_edge("Albizzi", "Guadagni")
+    G.add_edge("Bischeri", "Guadagni")
+    G.add_edge("Guadagni", "Lamberteschi")
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def les_miserables_graph():
+    """Returns coappearance network of characters in the novel Les Miserables.
+
+    References
+    ----------
+    .. [1] D. E. Knuth, 1993.
+       The Stanford GraphBase: a platform for combinatorial computing,
+       pp. 74-87. New York: AcM Press.
+    """
+    G = nx.Graph()
+    G.add_edge("Napoleon", "Myriel", weight=1)
+    G.add_edge("MlleBaptistine", "Myriel", weight=8)
+    G.add_edge("MmeMagloire", "Myriel", weight=10)
+    G.add_edge("MmeMagloire", "MlleBaptistine", weight=6)
+    G.add_edge("CountessDeLo", "Myriel", weight=1)
+    G.add_edge("Geborand", "Myriel", weight=1)
+    G.add_edge("Champtercier", "Myriel", weight=1)
+    G.add_edge("Cravatte", "Myriel", weight=1)
+    G.add_edge("Count", "Myriel", weight=2)
+    G.add_edge("OldMan", "Myriel", weight=1)
+    G.add_edge("Valjean", "Labarre", weight=1)
+    G.add_edge("Valjean", "MmeMagloire", weight=3)
+    G.add_edge("Valjean", "MlleBaptistine", weight=3)
+    G.add_edge("Valjean", "Myriel", weight=5)
+    G.add_edge("Marguerite", "Valjean", weight=1)
+    G.add_edge("MmeDeR", "Valjean", weight=1)
+    G.add_edge("Isabeau", "Valjean", weight=1)
+    G.add_edge("Gervais", "Valjean", weight=1)
+    G.add_edge("Listolier", "Tholomyes", weight=4)
+    G.add_edge("Fameuil", "Tholomyes", weight=4)
+    G.add_edge("Fameuil", "Listolier", weight=4)
+    G.add_edge("Blacheville", "Tholomyes", weight=4)
+    G.add_edge("Blacheville", "Listolier", weight=4)
+    G.add_edge("Blacheville", "Fameuil", weight=4)
+    G.add_edge("Favourite", "Tholomyes", weight=3)
+    G.add_edge("Favourite", "Listolier", weight=3)
+    G.add_edge("Favourite", "Fameuil", weight=3)
+    G.add_edge("Favourite", "Blacheville", weight=4)
+    G.add_edge("Dahlia", "Tholomyes", weight=3)
+    G.add_edge("Dahlia", "Listolier", weight=3)
+    G.add_edge("Dahlia", "Fameuil", weight=3)
+    G.add_edge("Dahlia", "Blacheville", weight=3)
+    G.add_edge("Dahlia", "Favourite", weight=5)
+    G.add_edge("Zephine", "Tholomyes", weight=3)
+    G.add_edge("Zephine", "Listolier", weight=3)
+    G.add_edge("Zephine", "Fameuil", weight=3)
+    G.add_edge("Zephine", "Blacheville", weight=3)
+    G.add_edge("Zephine", "Favourite", weight=4)
+    G.add_edge("Zephine", "Dahlia", weight=4)
+    G.add_edge("Fantine", "Tholomyes", weight=3)
+    G.add_edge("Fantine", "Listolier", weight=3)
+    G.add_edge("Fantine", "Fameuil", weight=3)
+    G.add_edge("Fantine", "Blacheville", weight=3)
+    G.add_edge("Fantine", "Favourite", weight=4)
+    G.add_edge("Fantine", "Dahlia", weight=4)
+    G.add_edge("Fantine", "Zephine", weight=4)
+    G.add_edge("Fantine", "Marguerite", weight=2)
+    G.add_edge("Fantine", "Valjean", weight=9)
+    G.add_edge("MmeThenardier", "Fantine", weight=2)
+    G.add_edge("MmeThenardier", "Valjean", weight=7)
+    G.add_edge("Thenardier", "MmeThenardier", weight=13)
+    G.add_edge("Thenardier", "Fantine", weight=1)
+    G.add_edge("Thenardier", "Valjean", weight=12)
+    G.add_edge("Cosette", "MmeThenardier", weight=4)
+    G.add_edge("Cosette", "Valjean", weight=31)
+    G.add_edge("Cosette", "Tholomyes", weight=1)
+    G.add_edge("Cosette", "Thenardier", weight=1)
+    G.add_edge("Javert", "Valjean", weight=17)
+    G.add_edge("Javert", "Fantine", weight=5)
+    G.add_edge("Javert", "Thenardier", weight=5)
+    G.add_edge("Javert", "MmeThenardier", weight=1)
+    G.add_edge("Javert", "Cosette", weight=1)
+    G.add_edge("Fauchelevent", "Valjean", weight=8)
+    G.add_edge("Fauchelevent", "Javert", weight=1)
+    G.add_edge("Bamatabois", "Fantine", weight=1)
+    G.add_edge("Bamatabois", "Javert", weight=1)
+    G.add_edge("Bamatabois", "Valjean", weight=2)
+    G.add_edge("Perpetue", "Fantine", weight=1)
+    G.add_edge("Simplice", "Perpetue", weight=2)
+    G.add_edge("Simplice", "Valjean", weight=3)
+    G.add_edge("Simplice", "Fantine", weight=2)
+    G.add_edge("Simplice", "Javert", weight=1)
+    G.add_edge("Scaufflaire", "Valjean", weight=1)
+    G.add_edge("Woman1", "Valjean", weight=2)
+    G.add_edge("Woman1", "Javert", weight=1)
+    G.add_edge("Judge", "Valjean", weight=3)
+    G.add_edge("Judge", "Bamatabois", weight=2)
+    G.add_edge("Champmathieu", "Valjean", weight=3)
+    G.add_edge("Champmathieu", "Judge", weight=3)
+    G.add_edge("Champmathieu", "Bamatabois", weight=2)
+    G.add_edge("Brevet", "Judge", weight=2)
+    G.add_edge("Brevet", "Champmathieu", weight=2)
+    G.add_edge("Brevet", "Valjean", weight=2)
+    G.add_edge("Brevet", "Bamatabois", weight=1)
+    G.add_edge("Chenildieu", "Judge", weight=2)
+    G.add_edge("Chenildieu", "Champmathieu", weight=2)
+    G.add_edge("Chenildieu", "Brevet", weight=2)
+    G.add_edge("Chenildieu", "Valjean", weight=2)
+    G.add_edge("Chenildieu", "Bamatabois", weight=1)
+    G.add_edge("Cochepaille", "Judge", weight=2)
+    G.add_edge("Cochepaille", "Champmathieu", weight=2)
+    G.add_edge("Cochepaille", "Brevet", weight=2)
+    G.add_edge("Cochepaille", "Chenildieu", weight=2)
+    G.add_edge("Cochepaille", "Valjean", weight=2)
+    G.add_edge("Cochepaille", "Bamatabois", weight=1)
+    G.add_edge("Pontmercy", "Thenardier", weight=1)
+    G.add_edge("Boulatruelle", "Thenardier", weight=1)
+    G.add_edge("Eponine", "MmeThenardier", weight=2)
+    G.add_edge("Eponine", "Thenardier", weight=3)
+    G.add_edge("Anzelma", "Eponine", weight=2)
+    G.add_edge("Anzelma", "Thenardier", weight=2)
+    G.add_edge("Anzelma", "MmeThenardier", weight=1)
+    G.add_edge("Woman2", "Valjean", weight=3)
+    G.add_edge("Woman2", "Cosette", weight=1)
+    G.add_edge("Woman2", "Javert", weight=1)
+    G.add_edge("MotherInnocent", "Fauchelevent", weight=3)
+    G.add_edge("MotherInnocent", "Valjean", weight=1)
+    G.add_edge("Gribier", "Fauchelevent", weight=2)
+    G.add_edge("MmeBurgon", "Jondrette", weight=1)
+    G.add_edge("Gavroche", "MmeBurgon", weight=2)
+    G.add_edge("Gavroche", "Thenardier", weight=1)
+    G.add_edge("Gavroche", "Javert", weight=1)
+    G.add_edge("Gavroche", "Valjean", weight=1)
+    G.add_edge("Gillenormand", "Cosette", weight=3)
+    G.add_edge("Gillenormand", "Valjean", weight=2)
+    G.add_edge("Magnon", "Gillenormand", weight=1)
+    G.add_edge("Magnon", "MmeThenardier", weight=1)
+    G.add_edge("MlleGillenormand", "Gillenormand", weight=9)
+    G.add_edge("MlleGillenormand", "Cosette", weight=2)
+    G.add_edge("MlleGillenormand", "Valjean", weight=2)
+    G.add_edge("MmePontmercy", "MlleGillenormand", weight=1)
+    G.add_edge("MmePontmercy", "Pontmercy", weight=1)
+    G.add_edge("MlleVaubois", "MlleGillenormand", weight=1)
+    G.add_edge("LtGillenormand", "MlleGillenormand", weight=2)
+    G.add_edge("LtGillenormand", "Gillenormand", weight=1)
+    G.add_edge("LtGillenormand", "Cosette", weight=1)
+    G.add_edge("Marius", "MlleGillenormand", weight=6)
+    G.add_edge("Marius", "Gillenormand", weight=12)
+    G.add_edge("Marius", "Pontmercy", weight=1)
+    G.add_edge("Marius", "LtGillenormand", weight=1)
+    G.add_edge("Marius", "Cosette", weight=21)
+    G.add_edge("Marius", "Valjean", weight=19)
+    G.add_edge("Marius", "Tholomyes", weight=1)
+    G.add_edge("Marius", "Thenardier", weight=2)
+    G.add_edge("Marius", "Eponine", weight=5)
+    G.add_edge("Marius", "Gavroche", weight=4)
+    G.add_edge("BaronessT", "Gillenormand", weight=1)
+    G.add_edge("BaronessT", "Marius", weight=1)
+    G.add_edge("Mabeuf", "Marius", weight=1)
+    G.add_edge("Mabeuf", "Eponine", weight=1)
+    G.add_edge("Mabeuf", "Gavroche", weight=1)
+    G.add_edge("Enjolras", "Marius", weight=7)
+    G.add_edge("Enjolras", "Gavroche", weight=7)
+    G.add_edge("Enjolras", "Javert", weight=6)
+    G.add_edge("Enjolras", "Mabeuf", weight=1)
+    G.add_edge("Enjolras", "Valjean", weight=4)
+    G.add_edge("Combeferre", "Enjolras", weight=15)
+    G.add_edge("Combeferre", "Marius", weight=5)
+    G.add_edge("Combeferre", "Gavroche", weight=6)
+    G.add_edge("Combeferre", "Mabeuf", weight=2)
+    G.add_edge("Prouvaire", "Gavroche", weight=1)
+    G.add_edge("Prouvaire", "Enjolras", weight=4)
+    G.add_edge("Prouvaire", "Combeferre", weight=2)
+    G.add_edge("Feuilly", "Gavroche", weight=2)
+    G.add_edge("Feuilly", "Enjolras", weight=6)
+    G.add_edge("Feuilly", "Prouvaire", weight=2)
+    G.add_edge("Feuilly", "Combeferre", weight=5)
+    G.add_edge("Feuilly", "Mabeuf", weight=1)
+    G.add_edge("Feuilly", "Marius", weight=1)
+    G.add_edge("Courfeyrac", "Marius", weight=9)
+    G.add_edge("Courfeyrac", "Enjolras", weight=17)
+    G.add_edge("Courfeyrac", "Combeferre", weight=13)
+    G.add_edge("Courfeyrac", "Gavroche", weight=7)
+    G.add_edge("Courfeyrac", "Mabeuf", weight=2)
+    G.add_edge("Courfeyrac", "Eponine", weight=1)
+    G.add_edge("Courfeyrac", "Feuilly", weight=6)
+    G.add_edge("Courfeyrac", "Prouvaire", weight=3)
+    G.add_edge("Bahorel", "Combeferre", weight=5)
+    G.add_edge("Bahorel", "Gavroche", weight=5)
+    G.add_edge("Bahorel", "Courfeyrac", weight=6)
+    G.add_edge("Bahorel", "Mabeuf", weight=2)
+    G.add_edge("Bahorel", "Enjolras", weight=4)
+    G.add_edge("Bahorel", "Feuilly", weight=3)
+    G.add_edge("Bahorel", "Prouvaire", weight=2)
+    G.add_edge("Bahorel", "Marius", weight=1)
+    G.add_edge("Bossuet", "Marius", weight=5)
+    G.add_edge("Bossuet", "Courfeyrac", weight=12)
+    G.add_edge("Bossuet", "Gavroche", weight=5)
+    G.add_edge("Bossuet", "Bahorel", weight=4)
+    G.add_edge("Bossuet", "Enjolras", weight=10)
+    G.add_edge("Bossuet", "Feuilly", weight=6)
+    G.add_edge("Bossuet", "Prouvaire", weight=2)
+    G.add_edge("Bossuet", "Combeferre", weight=9)
+    G.add_edge("Bossuet", "Mabeuf", weight=1)
+    G.add_edge("Bossuet", "Valjean", weight=1)
+    G.add_edge("Joly", "Bahorel", weight=5)
+    G.add_edge("Joly", "Bossuet", weight=7)
+    G.add_edge("Joly", "Gavroche", weight=3)
+    G.add_edge("Joly", "Courfeyrac", weight=5)
+    G.add_edge("Joly", "Enjolras", weight=5)
+    G.add_edge("Joly", "Feuilly", weight=5)
+    G.add_edge("Joly", "Prouvaire", weight=2)
+    G.add_edge("Joly", "Combeferre", weight=5)
+    G.add_edge("Joly", "Mabeuf", weight=1)
+    G.add_edge("Joly", "Marius", weight=2)
+    G.add_edge("Grantaire", "Bossuet", weight=3)
+    G.add_edge("Grantaire", "Enjolras", weight=3)
+    G.add_edge("Grantaire", "Combeferre", weight=1)
+    G.add_edge("Grantaire", "Courfeyrac", weight=2)
+    G.add_edge("Grantaire", "Joly", weight=2)
+    G.add_edge("Grantaire", "Gavroche", weight=1)
+    G.add_edge("Grantaire", "Bahorel", weight=1)
+    G.add_edge("Grantaire", "Feuilly", weight=1)
+    G.add_edge("Grantaire", "Prouvaire", weight=1)
+    G.add_edge("MotherPlutarch", "Mabeuf", weight=3)
+    G.add_edge("Gueulemer", "Thenardier", weight=5)
+    G.add_edge("Gueulemer", "Valjean", weight=1)
+    G.add_edge("Gueulemer", "MmeThenardier", weight=1)
+    G.add_edge("Gueulemer", "Javert", weight=1)
+    G.add_edge("Gueulemer", "Gavroche", weight=1)
+    G.add_edge("Gueulemer", "Eponine", weight=1)
+    G.add_edge("Babet", "Thenardier", weight=6)
+    G.add_edge("Babet", "Gueulemer", weight=6)
+    G.add_edge("Babet", "Valjean", weight=1)
+    G.add_edge("Babet", "MmeThenardier", weight=1)
+    G.add_edge("Babet", "Javert", weight=2)
+    G.add_edge("Babet", "Gavroche", weight=1)
+    G.add_edge("Babet", "Eponine", weight=1)
+    G.add_edge("Claquesous", "Thenardier", weight=4)
+    G.add_edge("Claquesous", "Babet", weight=4)
+    G.add_edge("Claquesous", "Gueulemer", weight=4)
+    G.add_edge("Claquesous", "Valjean", weight=1)
+    G.add_edge("Claquesous", "MmeThenardier", weight=1)
+    G.add_edge("Claquesous", "Javert", weight=1)
+    G.add_edge("Claquesous", "Eponine", weight=1)
+    G.add_edge("Claquesous", "Enjolras", weight=1)
+    G.add_edge("Montparnasse", "Javert", weight=1)
+    G.add_edge("Montparnasse", "Babet", weight=2)
+    G.add_edge("Montparnasse", "Gueulemer", weight=2)
+    G.add_edge("Montparnasse", "Claquesous", weight=2)
+    G.add_edge("Montparnasse", "Valjean", weight=1)
+    G.add_edge("Montparnasse", "Gavroche", weight=1)
+    G.add_edge("Montparnasse", "Eponine", weight=1)
+    G.add_edge("Montparnasse", "Thenardier", weight=1)
+    G.add_edge("Toussaint", "Cosette", weight=2)
+    G.add_edge("Toussaint", "Javert", weight=1)
+    G.add_edge("Toussaint", "Valjean", weight=1)
+    G.add_edge("Child1", "Gavroche", weight=2)
+    G.add_edge("Child2", "Gavroche", weight=2)
+    G.add_edge("Child2", "Child1", weight=3)
+    G.add_edge("Brujon", "Babet", weight=3)
+    G.add_edge("Brujon", "Gueulemer", weight=3)
+    G.add_edge("Brujon", "Thenardier", weight=3)
+    G.add_edge("Brujon", "Gavroche", weight=1)
+    G.add_edge("Brujon", "Eponine", weight=1)
+    G.add_edge("Brujon", "Claquesous", weight=1)
+    G.add_edge("Brujon", "Montparnasse", weight=1)
+    G.add_edge("MmeHucheloup", "Bossuet", weight=1)
+    G.add_edge("MmeHucheloup", "Joly", weight=1)
+    G.add_edge("MmeHucheloup", "Grantaire", weight=1)
+    G.add_edge("MmeHucheloup", "Bahorel", weight=1)
+    G.add_edge("MmeHucheloup", "Courfeyrac", weight=1)
+    G.add_edge("MmeHucheloup", "Gavroche", weight=1)
+    G.add_edge("MmeHucheloup", "Enjolras", weight=1)
+    return G
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/spectral_graph_forge.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/spectral_graph_forge.py
new file mode 100644
index 0000000000000000000000000000000000000000..aa8c9194bb31ce15434c728c607bfe0172402406
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/spectral_graph_forge.py
@@ -0,0 +1,120 @@
+"""Generates graphs with a given eigenvector structure"""
+
+import networkx as nx
+from networkx.utils import np_random_state
+
+__all__ = ["spectral_graph_forge"]
+
+
+@np_random_state(3)
+@nx._dispatchable(preserve_edge_attrs={"G": {"weight": 1}}, returns_graph=True)
+def spectral_graph_forge(G, alpha, transformation="identity", seed=None):
+    """Returns a random simple graph with spectrum resembling that of `G`
+
+    This algorithm, called Spectral Graph Forge (SGF), computes the
+    eigenvectors of a given graph adjacency matrix, filters them and
+    builds a random graph with a similar eigenstructure.
+    SGF has been proved to be particularly useful for synthesizing
+    realistic social networks and it can also be used to anonymize
+    graph sensitive data.
+
+    Parameters
+    ----------
+    G : Graph
+    alpha :  float
+        Ratio representing the percentage of eigenvectors of G to consider,
+        values in [0,1].
+    transformation : string, optional
+        Represents the intended matrix linear transformation, possible values
+        are 'identity' and 'modularity'
+    seed : integer, random_state, or None (default)
+        Indicator of numpy random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    H : Graph
+        A graph with a similar eigenvector structure of the input one.
+
+    Raises
+    ------
+    NetworkXError
+        If transformation has a value different from 'identity' or 'modularity'
+
+    Notes
+    -----
+    Spectral Graph Forge (SGF) generates a random simple graph resembling the
+    global properties of the given one.
+    It leverages the low-rank approximation of the associated adjacency matrix
+    driven by the *alpha* precision parameter.
+    SGF preserves the number of nodes of the input graph and their ordering.
+    This way, nodes of output graphs resemble the properties of the input one
+    and attributes can be directly mapped.
+
+    It considers the graph adjacency matrices which can optionally be
+    transformed to other symmetric real matrices (currently transformation
+    options include *identity* and *modularity*).
+    The *modularity* transformation, in the sense of Newman's modularity matrix
+    allows the focusing on community structure related properties of the graph.
+
+    SGF applies a low-rank approximation whose fixed rank is computed from the
+    ratio *alpha* of the input graph adjacency matrix dimension.
+    This step performs a filtering on the input eigenvectors similar to the low
+    pass filtering common in telecommunications.
+
+    The filtered values (after truncation) are used as input to a Bernoulli
+    sampling for constructing a random adjacency matrix.
+
+    References
+    ----------
+    ..  [1] L. Baldesi, C. T. Butts, A. Markopoulou, "Spectral Graph Forge:
+        Graph Generation Targeting Modularity", IEEE Infocom, '18.
+        https://arxiv.org/abs/1801.01715
+    ..  [2] M. Newman, "Networks: an introduction", Oxford university press,
+        2010
+
+    Examples
+    --------
+    >>> G = nx.karate_club_graph()
+    >>> H = nx.spectral_graph_forge(G, 0.3)
+    >>>
+    """
+    import numpy as np
+    import scipy as sp
+
+    available_transformations = ["identity", "modularity"]
+    alpha = np.clip(alpha, 0, 1)
+    A = nx.to_numpy_array(G)
+    n = A.shape[1]
+    level = round(n * alpha)
+
+    if transformation not in available_transformations:
+        msg = f"{transformation!r} is not a valid transformation. "
+        msg += f"Transformations: {available_transformations}"
+        raise nx.NetworkXError(msg)
+
+    K = np.ones((1, n)) @ A
+
+    B = A
+    if transformation == "modularity":
+        B -= K.T @ K / K.sum()
+
+    # Compute low-rank approximation of B
+    evals, evecs = np.linalg.eigh(B)
+    k = np.argsort(np.abs(evals))[::-1]  # indices of evals in descending order
+    evecs[:, k[np.arange(level, n)]] = 0  # set smallest eigenvectors to 0
+    B = evecs @ np.diag(evals) @ evecs.T
+
+    if transformation == "modularity":
+        B += K.T @ K / K.sum()
+
+    B = np.clip(B, 0, 1)
+    np.fill_diagonal(B, 0)
+
+    for i in range(n - 1):
+        B[i, i + 1 :] = sp.stats.bernoulli.rvs(B[i, i + 1 :], random_state=seed)
+        B[i + 1 :, i] = np.transpose(B[i, i + 1 :])
+
+    H = nx.from_numpy_array(B)
+
+    return H
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/stochastic.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/stochastic.py
new file mode 100644
index 0000000000000000000000000000000000000000..f53e2315470f8ffcdea0380026a933e06ddf6ea7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/stochastic.py
@@ -0,0 +1,54 @@
+"""Functions for generating stochastic graphs from a given weighted directed
+graph.
+
+"""
+
+import networkx as nx
+from networkx.classes import DiGraph, MultiDiGraph
+from networkx.utils import not_implemented_for
+
+__all__ = ["stochastic_graph"]
+
+
+@not_implemented_for("undirected")
+@nx._dispatchable(
+    edge_attrs="weight", mutates_input={"not copy": 1}, returns_graph=True
+)
+def stochastic_graph(G, copy=True, weight="weight"):
+    """Returns a right-stochastic representation of directed graph `G`.
+
+    A right-stochastic graph is a weighted digraph in which for each
+    node, the sum of the weights of all the out-edges of that node is
+    1. If the graph is already weighted (for example, via a 'weight'
+    edge attribute), the reweighting takes that into account.
+
+    Parameters
+    ----------
+    G : directed graph
+        A :class:`~networkx.DiGraph` or :class:`~networkx.MultiDiGraph`.
+
+    copy : boolean, optional
+        If this is True, then this function returns a new graph with
+        the stochastic reweighting. Otherwise, the original graph is
+        modified in-place (and also returned, for convenience).
+
+    weight : edge attribute key (optional, default='weight')
+        Edge attribute key used for reading the existing weight and
+        setting the new weight.  If no attribute with this key is found
+        for an edge, then the edge weight is assumed to be 1. If an edge
+        has a weight, it must be a positive number.
+
+    """
+    if copy:
+        G = MultiDiGraph(G) if G.is_multigraph() else DiGraph(G)
+    # There is a tradeoff here: the dictionary of node degrees may
+    # require a lot of memory, whereas making a call to `G.out_degree`
+    # inside the loop may be costly in computation time.
+    degree = dict(G.out_degree(weight=weight))
+    for u, v, d in G.edges(data=True):
+        if degree[u] == 0:
+            d[weight] = 0
+        else:
+            d[weight] = d.get(weight, 1) / degree[u]
+    nx._clear_cache(G)
+    return G
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/sudoku.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/sudoku.py
new file mode 100644
index 0000000000000000000000000000000000000000..f288ed24d1f189588de7e1e0bba61f50bbad0003
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/sudoku.py
@@ -0,0 +1,131 @@
+"""Generator for Sudoku graphs
+
+This module gives a generator for n-Sudoku graphs. It can be used to develop
+algorithms for solving or generating Sudoku puzzles.
+
+A completed Sudoku grid is a 9x9 array of integers between 1 and 9, with no
+number appearing twice in the same row, column, or 3x3 box.
+
++---------+---------+---------+
+| | 8 6 4 | | 3 7 1 | | 2 5 9 |
+| | 3 2 5 | | 8 4 9 | | 7 6 1 |
+| | 9 7 1 | | 2 6 5 | | 8 4 3 |
++---------+---------+---------+
+| | 4 3 6 | | 1 9 2 | | 5 8 7 |
+| | 1 9 8 | | 6 5 7 | | 4 3 2 |
+| | 2 5 7 | | 4 8 3 | | 9 1 6 |
++---------+---------+---------+
+| | 6 8 9 | | 7 3 4 | | 1 2 5 |
+| | 7 1 3 | | 5 2 8 | | 6 9 4 |
+| | 5 4 2 | | 9 1 6 | | 3 7 8 |
++---------+---------+---------+
+
+
+The Sudoku graph is an undirected graph with 81 vertices, corresponding to
+the cells of a Sudoku grid. It is a regular graph of degree 20. Two distinct
+vertices are adjacent if and only if the corresponding cells belong to the
+same row, column, or box. A completed Sudoku grid corresponds to a vertex
+coloring of the Sudoku graph with nine colors.
+
+More generally, the n-Sudoku graph is a graph with n^4 vertices, corresponding
+to the cells of an n^2 by n^2 grid. Two distinct vertices are adjacent if and
+only if they belong to the same row, column, or n by n box.
+
+References
+----------
+.. [1] Herzberg, A. M., & Murty, M. R. (2007). Sudoku squares and chromatic
+    polynomials. Notices of the AMS, 54(6), 708-717.
+.. [2] Sander, Torsten (2009), "Sudoku graphs are integral",
+    Electronic Journal of Combinatorics, 16 (1): Note 25, 7pp, MR 2529816
+.. [3] Wikipedia contributors. "Glossary of Sudoku." Wikipedia, The Free
+    Encyclopedia, 3 Dec. 2019. Web. 22 Dec. 2019.
+"""
+
+import networkx as nx
+from networkx.exception import NetworkXError
+
+__all__ = ["sudoku_graph"]
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def sudoku_graph(n=3):
+    """Returns the n-Sudoku graph. The default value of n is 3.
+
+    The n-Sudoku graph is a graph with n^4 vertices, corresponding to the
+    cells of an n^2 by n^2 grid. Two distinct vertices are adjacent if and
+    only if they belong to the same row, column, or n-by-n box.
+
+    Parameters
+    ----------
+    n: integer
+       The order of the Sudoku graph, equal to the square root of the
+       number of rows. The default is 3.
+
+    Returns
+    -------
+    NetworkX graph
+        The n-Sudoku graph Sud(n).
+
+    Examples
+    --------
+    >>> G = nx.sudoku_graph()
+    >>> G.number_of_nodes()
+    81
+    >>> G.number_of_edges()
+    810
+    >>> sorted(G.neighbors(42))
+    [6, 15, 24, 33, 34, 35, 36, 37, 38, 39, 40, 41, 43, 44, 51, 52, 53, 60, 69, 78]
+    >>> G = nx.sudoku_graph(2)
+    >>> G.number_of_nodes()
+    16
+    >>> G.number_of_edges()
+    56
+
+    References
+    ----------
+    .. [1] Herzberg, A. M., & Murty, M. R. (2007). Sudoku squares and chromatic
+       polynomials. Notices of the AMS, 54(6), 708-717.
+    .. [2] Sander, Torsten (2009), "Sudoku graphs are integral",
+       Electronic Journal of Combinatorics, 16 (1): Note 25, 7pp, MR 2529816
+    .. [3] Wikipedia contributors. "Glossary of Sudoku." Wikipedia, The Free
+       Encyclopedia, 3 Dec. 2019. Web. 22 Dec. 2019.
+    """
+
+    if n < 0:
+        raise NetworkXError("The order must be greater than or equal to zero.")
+
+    n2 = n * n
+    n3 = n2 * n
+    n4 = n3 * n
+
+    # Construct an empty graph with n^4 nodes
+    G = nx.empty_graph(n4)
+
+    # A Sudoku graph of order 0 or 1 has no edges
+    if n < 2:
+        return G
+
+    # Add edges for cells in the same row
+    for row_no in range(n2):
+        row_start = row_no * n2
+        for j in range(1, n2):
+            for i in range(j):
+                G.add_edge(row_start + i, row_start + j)
+
+    # Add edges for cells in the same column
+    for col_no in range(n2):
+        for j in range(col_no, n4, n2):
+            for i in range(col_no, j, n2):
+                G.add_edge(i, j)
+
+    # Add edges for cells in the same box
+    for band_no in range(n):
+        for stack_no in range(n):
+            box_start = n3 * band_no + n * stack_no
+            for j in range(1, n2):
+                for i in range(j):
+                    u = box_start + (i % n) + n2 * (i // n)
+                    v = box_start + (j % n) + n2 * (j // n)
+                    G.add_edge(u, v)
+
+    return G
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..88d858d2b3f24de0ecce5838ba1f2fd3625f74c4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_atlas.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_atlas.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3ae392e56bfd2fcfd588e12ad047e76c496c5511
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_atlas.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_classic.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_classic.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..377c7291b69a5dab3a039153d7f769223edf9619
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_classic.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_cographs.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_cographs.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c4894e4b8302b96b0428b17a81d2c04119743c2e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_cographs.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_community.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_community.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..04d5810f19a1238e613686f8c311fadd373d77e9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_community.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_degree_seq.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_degree_seq.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8fdc50e9cd83aa0b615094c57a0635551e996afc
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_degree_seq.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_directed.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_directed.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cbec17dc40b22a158b94b4a6d25fdaba9f04b660
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_directed.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_duplication.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_duplication.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..61c7dfc11d5d84d3fca85efd3cf9f1f476139bdc
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_duplication.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_ego.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_ego.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3ef5640989749c7225513ee1229978b79443e4e4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_ego.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_expanders.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_expanders.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1af7f64303bb3533fa25fbea5f22467e8ede0546
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_expanders.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_geometric.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_geometric.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f45ad40de23644161c0ba1daf72555bdb89df30d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_geometric.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_harary_graph.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_harary_graph.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..06c1943421e7fb01e05cb5d55bf1d6f34a744099
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_harary_graph.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_internet_as_graphs.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_internet_as_graphs.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aa0eb70bdfa98a3d13fa2b94438905c157c6de8d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_internet_as_graphs.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_intersection.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_intersection.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c361cb335d433e064abaa5c4ba616d64650ddc71
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_intersection.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_interval_graph.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_interval_graph.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a6e819579195252d3c6f2a30d23419b843c6ff99
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_interval_graph.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_joint_degree_seq.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_joint_degree_seq.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cf568488b1de54d19088632a43965425e7668560
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_joint_degree_seq.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_lattice.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_lattice.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..23a53f30e191a609f485322153941e15ff41050f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_lattice.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_line.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_line.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..85685bed21d03f0df79fc7174d5d060e7d07c2ed
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_line.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_mycielski.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_mycielski.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..006b92c63719f30c01a6f23a5efd8d510d80dde5
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_mycielski.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_nonisomorphic_trees.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_nonisomorphic_trees.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4f9cb77dafde818aad976b23e7a00a0b2daa3872
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_nonisomorphic_trees.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_random_clustered.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_random_clustered.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9cd16a709eb83f6ded0f466d19e6ea8d0c6ec374
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_random_clustered.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_random_graphs.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_random_graphs.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e35bb5b7aa2b7f3636b6bc74e3968fd7391994d8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_random_graphs.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_small.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_small.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7e32d1e9bbb2217e68076c732d75f2ce2a59742a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_small.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_spectral_graph_forge.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_spectral_graph_forge.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..45abe3241804863f4cc0f3dd365db139d1462489
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_spectral_graph_forge.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_stochastic.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_stochastic.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e1355bfae2c1b63e45157e3c7919d3de9189e99c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_stochastic.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_sudoku.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_sudoku.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5b8674a141af4b54ad977036d208eb058af46b77
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_sudoku.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_time_series.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_time_series.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..82c817f95c0fbe5abd7fff7d56179b5ca5e0005c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_time_series.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_trees.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_trees.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1cac5249ecf49dc147d3041dc20d266f69e341ce
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_trees.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_triads.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_triads.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5c5b58115b3db06be4d8a7c6c1a4dd1a9b539207
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/__pycache__/test_triads.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_atlas.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_atlas.py
new file mode 100644
index 0000000000000000000000000000000000000000..add4741c00e8d8aefe4fcf3a2a86815a15aab29c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_atlas.py
@@ -0,0 +1,75 @@
+from itertools import groupby
+
+import pytest
+
+import networkx as nx
+from networkx import graph_atlas, graph_atlas_g
+from networkx.generators.atlas import NUM_GRAPHS
+from networkx.utils import edges_equal, nodes_equal, pairwise
+
+
+class TestAtlasGraph:
+    """Unit tests for the :func:`~networkx.graph_atlas` function."""
+
+    def test_index_too_small(self):
+        with pytest.raises(ValueError):
+            graph_atlas(-1)
+
+    def test_index_too_large(self):
+        with pytest.raises(ValueError):
+            graph_atlas(NUM_GRAPHS)
+
+    def test_graph(self):
+        G = graph_atlas(6)
+        assert nodes_equal(G.nodes(), range(3))
+        assert edges_equal(G.edges(), [(0, 1), (0, 2)])
+
+
+class TestAtlasGraphG:
+    """Unit tests for the :func:`~networkx.graph_atlas_g` function."""
+
+    @classmethod
+    def setup_class(cls):
+        cls.GAG = graph_atlas_g()
+
+    def test_sizes(self):
+        G = self.GAG[0]
+        assert G.number_of_nodes() == 0
+        assert G.number_of_edges() == 0
+
+        G = self.GAG[7]
+        assert G.number_of_nodes() == 3
+        assert G.number_of_edges() == 3
+
+    def test_names(self):
+        for i, G in enumerate(self.GAG):
+            assert int(G.name[1:]) == i
+
+    def test_nondecreasing_nodes(self):
+        # check for nondecreasing number of nodes
+        for n1, n2 in pairwise(map(len, self.GAG)):
+            assert n2 <= n1 + 1
+
+    def test_nondecreasing_edges(self):
+        # check for nondecreasing number of edges (for fixed number of
+        # nodes)
+        for n, group in groupby(self.GAG, key=nx.number_of_nodes):
+            for m1, m2 in pairwise(map(nx.number_of_edges, group)):
+                assert m2 <= m1 + 1
+
+    def test_nondecreasing_degree_sequence(self):
+        # Check for lexicographically nondecreasing degree sequences
+        # (for fixed number of nodes and edges).
+        #
+        # There are three exceptions to this rule in the order given in
+        # the "Atlas of Graphs" book, so we need to manually exclude
+        # those.
+        exceptions = [("G55", "G56"), ("G1007", "G1008"), ("G1012", "G1013")]
+        for n, group in groupby(self.GAG, key=nx.number_of_nodes):
+            for m, group in groupby(group, key=nx.number_of_edges):
+                for G1, G2 in pairwise(group):
+                    if (G1.name, G2.name) in exceptions:
+                        continue
+                    d1 = sorted(d for v, d in G1.degree())
+                    d2 = sorted(d for v, d in G2.degree())
+                    assert d1 <= d2
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_classic.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_classic.py
new file mode 100644
index 0000000000000000000000000000000000000000..bec6e69e99141561bbb0c86dd54810c9f57c75b8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_classic.py
@@ -0,0 +1,642 @@
+"""
+====================
+Generators - Classic
+====================
+
+Unit tests for various classic graph generators in generators/classic.py
+"""
+
+import itertools
+import typing
+
+import pytest
+
+import networkx as nx
+from networkx.utils import edges_equal, nodes_equal
+
+
+class TestGeneratorClassic:
+    def test_balanced_tree(self):
+        # balanced_tree(r,h) is a tree with (r**(h+1)-1)/(r-1) edges
+        for r, h in [(2, 2), (3, 3), (6, 2)]:
+            t = nx.balanced_tree(r, h)
+            order = t.order()
+            assert order == (r ** (h + 1) - 1) / (r - 1)
+            assert nx.is_connected(t)
+            assert t.size() == order - 1
+            dh = nx.degree_histogram(t)
+            assert dh[0] == 0  # no nodes of 0
+            assert dh[1] == r**h  # nodes of degree 1 are leaves
+            assert dh[r] == 1  # root is degree r
+            assert dh[r + 1] == order - r**h - 1  # everyone else is degree r+1
+            assert len(dh) == r + 2
+
+    def test_balanced_tree_star(self):
+        # balanced_tree(r,1) is the r-star
+        t = nx.balanced_tree(r=2, h=1)
+        assert nx.could_be_isomorphic(t, nx.star_graph(2))
+        t = nx.balanced_tree(r=5, h=1)
+        assert nx.could_be_isomorphic(t, nx.star_graph(5))
+        t = nx.balanced_tree(r=10, h=1)
+        assert nx.could_be_isomorphic(t, nx.star_graph(10))
+
+    def test_balanced_tree_path(self):
+        """Tests that the balanced tree with branching factor one is the
+        path graph.
+
+        """
+        # A tree of height four has five levels.
+        T = nx.balanced_tree(1, 4)
+        P = nx.path_graph(5)
+        assert nx.could_be_isomorphic(T, P)
+
+    def test_full_rary_tree(self):
+        r = 2
+        n = 9
+        t = nx.full_rary_tree(r, n)
+        assert t.order() == n
+        assert nx.is_connected(t)
+        dh = nx.degree_histogram(t)
+        assert dh[0] == 0  # no nodes of 0
+        assert dh[1] == 5  # nodes of degree 1 are leaves
+        assert dh[r] == 1  # root is degree r
+        assert dh[r + 1] == 9 - 5 - 1  # everyone else is degree r+1
+        assert len(dh) == r + 2
+
+    def test_full_rary_tree_balanced(self):
+        t = nx.full_rary_tree(2, 15)
+        th = nx.balanced_tree(2, 3)
+        assert nx.could_be_isomorphic(t, th)
+
+    def test_full_rary_tree_path(self):
+        t = nx.full_rary_tree(1, 10)
+        assert nx.could_be_isomorphic(t, nx.path_graph(10))
+
+    def test_full_rary_tree_empty(self):
+        t = nx.full_rary_tree(0, 10)
+        assert nx.could_be_isomorphic(t, nx.empty_graph(10))
+        t = nx.full_rary_tree(3, 0)
+        assert nx.could_be_isomorphic(t, nx.empty_graph(0))
+
+    def test_full_rary_tree_3_20(self):
+        t = nx.full_rary_tree(3, 20)
+        assert t.order() == 20
+
+    def test_barbell_graph(self):
+        # number of nodes = 2*m1 + m2 (2 m1-complete graphs + m2-path + 2 edges)
+        # number of edges = 2*(nx.number_of_edges(m1-complete graph) + m2 + 1
+        m1 = 3
+        m2 = 5
+        b = nx.barbell_graph(m1, m2)
+        assert nx.number_of_nodes(b) == 2 * m1 + m2
+        assert nx.number_of_edges(b) == m1 * (m1 - 1) + m2 + 1
+
+        m1 = 4
+        m2 = 10
+        b = nx.barbell_graph(m1, m2)
+        assert nx.number_of_nodes(b) == 2 * m1 + m2
+        assert nx.number_of_edges(b) == m1 * (m1 - 1) + m2 + 1
+
+        m1 = 3
+        m2 = 20
+        b = nx.barbell_graph(m1, m2)
+        assert nx.number_of_nodes(b) == 2 * m1 + m2
+        assert nx.number_of_edges(b) == m1 * (m1 - 1) + m2 + 1
+
+        # Raise NetworkXError if m1<2
+        m1 = 1
+        m2 = 20
+        pytest.raises(nx.NetworkXError, nx.barbell_graph, m1, m2)
+
+        # Raise NetworkXError if m2<0
+        m1 = 5
+        m2 = -2
+        pytest.raises(nx.NetworkXError, nx.barbell_graph, m1, m2)
+
+        # nx.barbell_graph(2,m) = nx.path_graph(m+4)
+        m1 = 2
+        m2 = 5
+        b = nx.barbell_graph(m1, m2)
+        assert nx.could_be_isomorphic(b, nx.path_graph(m2 + 4))
+
+        m1 = 2
+        m2 = 10
+        b = nx.barbell_graph(m1, m2)
+        assert nx.could_be_isomorphic(b, nx.path_graph(m2 + 4))
+
+        m1 = 2
+        m2 = 20
+        b = nx.barbell_graph(m1, m2)
+        assert nx.could_be_isomorphic(b, nx.path_graph(m2 + 4))
+
+        pytest.raises(
+            nx.NetworkXError, nx.barbell_graph, m1, m2, create_using=nx.DiGraph()
+        )
+
+        mb = nx.barbell_graph(m1, m2, create_using=nx.MultiGraph())
+        assert edges_equal(mb.edges(), b.edges())
+
+    def test_binomial_tree(self):
+        graphs = (None, nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph)
+        for create_using in graphs:
+            for n in range(4):
+                b = nx.binomial_tree(n, create_using)
+                assert nx.number_of_nodes(b) == 2**n
+                assert nx.number_of_edges(b) == (2**n - 1)
+
+    def test_complete_graph(self):
+        # complete_graph(m) is a connected graph with
+        # m nodes and  m*(m+1)/2 edges
+        for m in [0, 1, 3, 5]:
+            g = nx.complete_graph(m)
+            assert nx.number_of_nodes(g) == m
+            assert nx.number_of_edges(g) == m * (m - 1) // 2
+
+        mg = nx.complete_graph(m, create_using=nx.MultiGraph)
+        assert edges_equal(mg.edges(), g.edges())
+
+        g = nx.complete_graph("abc")
+        assert nodes_equal(g.nodes(), ["a", "b", "c"])
+        assert g.size() == 3
+
+        # creates a self-loop... should it? 
+        g = nx.complete_graph("abcb")
+        assert nodes_equal(g.nodes(), ["a", "b", "c"])
+        assert g.size() == 4
+
+        g = nx.complete_graph("abcb", create_using=nx.MultiGraph)
+        assert nodes_equal(g.nodes(), ["a", "b", "c"])
+        assert g.size() == 6
+
+    def test_complete_digraph(self):
+        # complete_graph(m) is a connected graph with
+        # m nodes and  m*(m+1)/2 edges
+        for m in [0, 1, 3, 5]:
+            g = nx.complete_graph(m, create_using=nx.DiGraph)
+            assert nx.number_of_nodes(g) == m
+            assert nx.number_of_edges(g) == m * (m - 1)
+
+        g = nx.complete_graph("abc", create_using=nx.DiGraph)
+        assert len(g) == 3
+        assert g.size() == 6
+        assert g.is_directed()
+
+    def test_circular_ladder_graph(self):
+        G = nx.circular_ladder_graph(5)
+        pytest.raises(
+            nx.NetworkXError, nx.circular_ladder_graph, 5, create_using=nx.DiGraph
+        )
+        mG = nx.circular_ladder_graph(5, create_using=nx.MultiGraph)
+        assert edges_equal(mG.edges(), G.edges())
+
+    def test_circulant_graph(self):
+        # Ci_n(1) is the cycle graph for all n
+        Ci6_1 = nx.circulant_graph(6, [1])
+        C6 = nx.cycle_graph(6)
+        assert edges_equal(Ci6_1.edges(), C6.edges())
+
+        # Ci_n(1, 2, ..., n div 2) is the complete graph for all n
+        Ci7 = nx.circulant_graph(7, [1, 2, 3])
+        K7 = nx.complete_graph(7)
+        assert edges_equal(Ci7.edges(), K7.edges())
+
+        # Ci_6(1, 3) is K_3,3 i.e. the utility graph
+        Ci6_1_3 = nx.circulant_graph(6, [1, 3])
+        K3_3 = nx.complete_bipartite_graph(3, 3)
+        assert nx.could_be_isomorphic(Ci6_1_3, K3_3)
+
+    def test_cycle_graph(self):
+        G = nx.cycle_graph(4)
+        assert edges_equal(G.edges(), [(0, 1), (0, 3), (1, 2), (2, 3)])
+        mG = nx.cycle_graph(4, create_using=nx.MultiGraph)
+        assert edges_equal(mG.edges(), [(0, 1), (0, 3), (1, 2), (2, 3)])
+        G = nx.cycle_graph(4, create_using=nx.DiGraph)
+        assert not G.has_edge(2, 1)
+        assert G.has_edge(1, 2)
+        assert G.is_directed()
+
+        G = nx.cycle_graph("abc")
+        assert len(G) == 3
+        assert G.size() == 3
+        G = nx.cycle_graph("abcb")
+        assert len(G) == 3
+        assert G.size() == 2
+        g = nx.cycle_graph("abc", nx.DiGraph)
+        assert len(g) == 3
+        assert g.size() == 3
+        assert g.is_directed()
+        g = nx.cycle_graph("abcb", nx.DiGraph)
+        assert len(g) == 3
+        assert g.size() == 4
+
+    def test_dorogovtsev_goltsev_mendes_graph(self):
+        G = nx.dorogovtsev_goltsev_mendes_graph(0)
+        assert edges_equal(G.edges(), [(0, 1)])
+        assert nodes_equal(list(G), [0, 1])
+        G = nx.dorogovtsev_goltsev_mendes_graph(1)
+        assert edges_equal(G.edges(), [(0, 1), (0, 2), (1, 2)])
+        assert nx.average_clustering(G) == 1.0
+        assert nx.average_shortest_path_length(G) == 1.0
+        assert sorted(nx.triangles(G).values()) == [1, 1, 1]
+        assert nx.is_planar(G)
+        G = nx.dorogovtsev_goltsev_mendes_graph(2)
+        assert nx.number_of_nodes(G) == 6
+        assert nx.number_of_edges(G) == 9
+        assert nx.average_clustering(G) == 0.75
+        assert nx.average_shortest_path_length(G) == 1.4
+        assert nx.is_planar(G)
+        G = nx.dorogovtsev_goltsev_mendes_graph(10)
+        assert nx.number_of_nodes(G) == 29526
+        assert nx.number_of_edges(G) == 59049
+        assert G.degree(0) == 1024
+        assert G.degree(1) == 1024
+        assert G.degree(2) == 1024
+
+        with pytest.raises(nx.NetworkXError, match=r"n must be greater than"):
+            nx.dorogovtsev_goltsev_mendes_graph(-1)
+        with pytest.raises(nx.NetworkXError, match=r"directed graph not supported"):
+            nx.dorogovtsev_goltsev_mendes_graph(7, create_using=nx.DiGraph)
+        with pytest.raises(nx.NetworkXError, match=r"multigraph not supported"):
+            nx.dorogovtsev_goltsev_mendes_graph(7, create_using=nx.MultiGraph)
+        with pytest.raises(nx.NetworkXError):
+            nx.dorogovtsev_goltsev_mendes_graph(7, create_using=nx.MultiDiGraph)
+
+    def test_create_using(self):
+        G = nx.empty_graph()
+        assert isinstance(G, nx.Graph)
+        pytest.raises(TypeError, nx.empty_graph, create_using=0.0)
+        pytest.raises(TypeError, nx.empty_graph, create_using="Graph")
+
+        G = nx.empty_graph(create_using=nx.MultiGraph)
+        assert isinstance(G, nx.MultiGraph)
+        G = nx.empty_graph(create_using=nx.DiGraph)
+        assert isinstance(G, nx.DiGraph)
+
+        G = nx.empty_graph(create_using=nx.DiGraph, default=nx.MultiGraph)
+        assert isinstance(G, nx.DiGraph)
+        G = nx.empty_graph(create_using=None, default=nx.MultiGraph)
+        assert isinstance(G, nx.MultiGraph)
+        G = nx.empty_graph(default=nx.MultiGraph)
+        assert isinstance(G, nx.MultiGraph)
+
+        G = nx.path_graph(5)
+        H = nx.empty_graph(create_using=G)
+        assert not H.is_multigraph()
+        assert not H.is_directed()
+        assert len(H) == 0
+        assert G is H
+
+        H = nx.empty_graph(create_using=nx.MultiGraph())
+        assert H.is_multigraph()
+        assert not H.is_directed()
+        assert G is not H
+
+        # test for subclasses that also use typing.Protocol. See gh-6243
+        class Mixin(typing.Protocol):
+            pass
+
+        class MyGraph(Mixin, nx.DiGraph):
+            pass
+
+        G = nx.empty_graph(create_using=MyGraph)
+
+    def test_empty_graph(self):
+        G = nx.empty_graph()
+        assert nx.number_of_nodes(G) == 0
+        G = nx.empty_graph(42)
+        assert nx.number_of_nodes(G) == 42
+        assert nx.number_of_edges(G) == 0
+
+        G = nx.empty_graph("abc")
+        assert len(G) == 3
+        assert G.size() == 0
+
+        # create empty digraph
+        G = nx.empty_graph(42, create_using=nx.DiGraph(name="duh"))
+        assert nx.number_of_nodes(G) == 42
+        assert nx.number_of_edges(G) == 0
+        assert isinstance(G, nx.DiGraph)
+
+        # create empty multigraph
+        G = nx.empty_graph(42, create_using=nx.MultiGraph(name="duh"))
+        assert nx.number_of_nodes(G) == 42
+        assert nx.number_of_edges(G) == 0
+        assert isinstance(G, nx.MultiGraph)
+
+        # create empty graph from another
+        pete = nx.petersen_graph()
+        G = nx.empty_graph(42, create_using=pete)
+        assert nx.number_of_nodes(G) == 42
+        assert nx.number_of_edges(G) == 0
+        assert isinstance(G, nx.Graph)
+
+    def test_ladder_graph(self):
+        for i, G in [
+            (0, nx.empty_graph(0)),
+            (1, nx.path_graph(2)),
+            (2, nx.hypercube_graph(2)),
+            (10, nx.grid_graph([2, 10])),
+        ]:
+            assert nx.could_be_isomorphic(nx.ladder_graph(i), G)
+
+        pytest.raises(nx.NetworkXError, nx.ladder_graph, 2, create_using=nx.DiGraph)
+
+        g = nx.ladder_graph(2)
+        mg = nx.ladder_graph(2, create_using=nx.MultiGraph)
+        assert edges_equal(mg.edges(), g.edges())
+
+    @pytest.mark.parametrize(("m", "n"), [(3, 5), (4, 10), (3, 20)])
+    def test_lollipop_graph_right_sizes(self, m, n):
+        G = nx.lollipop_graph(m, n)
+        assert nx.number_of_nodes(G) == m + n
+        assert nx.number_of_edges(G) == m * (m - 1) / 2 + n
+
+    @pytest.mark.parametrize(("m", "n"), [("ab", ""), ("abc", "defg")])
+    def test_lollipop_graph_size_node_sequence(self, m, n):
+        G = nx.lollipop_graph(m, n)
+        assert nx.number_of_nodes(G) == len(m) + len(n)
+        assert nx.number_of_edges(G) == len(m) * (len(m) - 1) / 2 + len(n)
+
+    def test_lollipop_graph_exceptions(self):
+        # Raise NetworkXError if m<2
+        pytest.raises(nx.NetworkXError, nx.lollipop_graph, -1, 2)
+        pytest.raises(nx.NetworkXError, nx.lollipop_graph, 1, 20)
+        pytest.raises(nx.NetworkXError, nx.lollipop_graph, "", 20)
+        pytest.raises(nx.NetworkXError, nx.lollipop_graph, "a", 20)
+
+        # Raise NetworkXError if n<0
+        pytest.raises(nx.NetworkXError, nx.lollipop_graph, 5, -2)
+
+        # raise NetworkXError if create_using is directed
+        with pytest.raises(nx.NetworkXError):
+            nx.lollipop_graph(2, 20, create_using=nx.DiGraph)
+        with pytest.raises(nx.NetworkXError):
+            nx.lollipop_graph(2, 20, create_using=nx.MultiDiGraph)
+
+    @pytest.mark.parametrize(("m", "n"), [(2, 0), (2, 5), (2, 10), ("ab", 20)])
+    def test_lollipop_graph_same_as_path_when_m1_is_2(self, m, n):
+        G = nx.lollipop_graph(m, n)
+        assert nx.could_be_isomorphic(G, nx.path_graph(n + 2))
+
+    def test_lollipop_graph_for_multigraph(self):
+        G = nx.lollipop_graph(5, 20)
+        MG = nx.lollipop_graph(5, 20, create_using=nx.MultiGraph)
+        assert edges_equal(MG.edges(), G.edges())
+
+    @pytest.mark.parametrize(
+        ("m", "n"),
+        [(4, "abc"), ("abcd", 3), ([1, 2, 3, 4], "abc"), ("abcd", [1, 2, 3])],
+    )
+    def test_lollipop_graph_mixing_input_types(self, m, n):
+        expected = nx.compose(nx.complete_graph(4), nx.path_graph(range(100, 103)))
+        expected.add_edge(0, 100)  # Connect complete graph and path graph
+        assert nx.could_be_isomorphic(nx.lollipop_graph(m, n), expected)
+
+    def test_lollipop_graph_non_builtin_ints(self):
+        np = pytest.importorskip("numpy")
+        G = nx.lollipop_graph(np.int32(4), np.int64(3))
+        expected = nx.compose(nx.complete_graph(4), nx.path_graph(range(100, 103)))
+        expected.add_edge(0, 100)  # Connect complete graph and path graph
+        assert nx.could_be_isomorphic(G, expected)
+
+    def test_null_graph(self):
+        assert nx.number_of_nodes(nx.null_graph()) == 0
+
+    def test_path_graph(self):
+        p = nx.path_graph(0)
+        assert nx.could_be_isomorphic(p, nx.null_graph())
+
+        p = nx.path_graph(1)
+        assert nx.could_be_isomorphic(p, nx.empty_graph(1))
+
+        p = nx.path_graph(10)
+        assert nx.is_connected(p)
+        assert sorted(d for n, d in p.degree()) == [1, 1, 2, 2, 2, 2, 2, 2, 2, 2]
+        assert p.order() - 1 == p.size()
+
+        dp = nx.path_graph(3, create_using=nx.DiGraph)
+        assert dp.has_edge(0, 1)
+        assert not dp.has_edge(1, 0)
+
+        mp = nx.path_graph(10, create_using=nx.MultiGraph)
+        assert edges_equal(mp.edges(), p.edges())
+
+        G = nx.path_graph("abc")
+        assert len(G) == 3
+        assert G.size() == 2
+        G = nx.path_graph("abcb")
+        assert len(G) == 3
+        assert G.size() == 2
+        g = nx.path_graph("abc", nx.DiGraph)
+        assert len(g) == 3
+        assert g.size() == 2
+        assert g.is_directed()
+        g = nx.path_graph("abcb", nx.DiGraph)
+        assert len(g) == 3
+        assert g.size() == 3
+
+        G = nx.path_graph((1, 2, 3, 2, 4))
+        assert G.has_edge(2, 4)
+
+    def test_star_graph(self):
+        assert nx.could_be_isomorphic(nx.star_graph(""), nx.empty_graph(0))
+        assert nx.could_be_isomorphic(nx.star_graph([]), nx.empty_graph(0))
+        assert nx.could_be_isomorphic(nx.star_graph(0), nx.empty_graph(1))
+        assert nx.could_be_isomorphic(nx.star_graph(1), nx.path_graph(2))
+        assert nx.could_be_isomorphic(nx.star_graph(2), nx.path_graph(3))
+        assert nx.could_be_isomorphic(
+            nx.star_graph(5), nx.complete_bipartite_graph(1, 5)
+        )
+
+        s = nx.star_graph(10)
+        assert sorted(d for n, d in s.degree()) == [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10]
+
+        ms = nx.star_graph(10, create_using=nx.MultiGraph)
+        assert edges_equal(ms.edges(), s.edges())
+
+        G = nx.star_graph("abc")
+        assert len(G) == 3
+        assert G.size() == 2
+
+        G = nx.star_graph("abcb")
+        assert len(G) == 3
+        assert G.size() == 2
+        G = nx.star_graph("abcb", create_using=nx.MultiGraph)
+        assert len(G) == 3
+        assert G.size() == 3
+
+        G = nx.star_graph("abcdefg")
+        assert len(G) == 7
+        assert G.size() == 6
+
+    @pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiDiGraph))
+    def test_star_graph_directed(self, graph_type):
+        dg = nx.star_graph(3, create_using=graph_type)
+        assert sorted([(u, v) for u, v, *d in dg.edges]) == [(0, 1), (0, 2), (0, 3)]
+
+    def test_non_int_integers_for_star_graph(self):
+        np = pytest.importorskip("numpy")
+        G = nx.star_graph(np.int32(3))
+        assert len(G) == 4
+        assert G.size() == 3
+
+    @pytest.mark.parametrize(("m", "n"), [(3, 0), (3, 5), (4, 10), (3, 20)])
+    def test_tadpole_graph_right_sizes(self, m, n):
+        G = nx.tadpole_graph(m, n)
+        assert nx.number_of_nodes(G) == m + n
+        assert nx.number_of_edges(G) == m + n - (m == 2)
+
+    @pytest.mark.parametrize(("m", "n"), [("ab", ""), ("ab", "c"), ("abc", "defg")])
+    def test_tadpole_graph_size_node_sequences(self, m, n):
+        G = nx.tadpole_graph(m, n)
+        assert nx.number_of_nodes(G) == len(m) + len(n)
+        assert nx.number_of_edges(G) == len(m) + len(n) - (len(m) == 2)
+
+    def test_tadpole_graph_exceptions(self):
+        # Raise NetworkXError if m<2
+        pytest.raises(nx.NetworkXError, nx.tadpole_graph, -1, 3)
+        pytest.raises(nx.NetworkXError, nx.tadpole_graph, 0, 3)
+        pytest.raises(nx.NetworkXError, nx.tadpole_graph, 1, 3)
+
+        # Raise NetworkXError if n<0
+        pytest.raises(nx.NetworkXError, nx.tadpole_graph, 5, -2)
+
+        # Raise NetworkXError for digraphs
+        with pytest.raises(nx.NetworkXError):
+            nx.tadpole_graph(2, 20, create_using=nx.DiGraph)
+        with pytest.raises(nx.NetworkXError):
+            nx.tadpole_graph(2, 20, create_using=nx.MultiDiGraph)
+
+    @pytest.mark.parametrize(("m", "n"), [(2, 0), (2, 5), (2, 10), ("ab", 20)])
+    def test_tadpole_graph_same_as_path_when_m_is_2(self, m, n):
+        G = nx.tadpole_graph(m, n)
+        assert nx.could_be_isomorphic(G, nx.path_graph(n + 2))
+
+    @pytest.mark.parametrize("m", [4, 7])
+    def test_tadpole_graph_same_as_cycle_when_m2_is_0(self, m):
+        G = nx.tadpole_graph(m, 0)
+        assert nx.could_be_isomorphic(G, nx.cycle_graph(m))
+
+    def test_tadpole_graph_for_multigraph(self):
+        G = nx.tadpole_graph(5, 20)
+        MG = nx.tadpole_graph(5, 20, create_using=nx.MultiGraph)
+        assert edges_equal(MG.edges(), G.edges())
+
+    @pytest.mark.parametrize(
+        ("m", "n"),
+        [(4, "abc"), ("abcd", 3), ([1, 2, 3, 4], "abc"), ("abcd", [1, 2, 3])],
+    )
+    def test_tadpole_graph_mixing_input_types(self, m, n):
+        expected = nx.compose(nx.cycle_graph(4), nx.path_graph(range(100, 103)))
+        expected.add_edge(0, 100)  # Connect cycle and path
+        assert nx.could_be_isomorphic(nx.tadpole_graph(m, n), expected)
+
+    def test_tadpole_graph_non_builtin_integers(self):
+        np = pytest.importorskip("numpy")
+        G = nx.tadpole_graph(np.int32(4), np.int64(3))
+        expected = nx.compose(nx.cycle_graph(4), nx.path_graph(range(100, 103)))
+        expected.add_edge(0, 100)  # Connect cycle and path
+        assert nx.could_be_isomorphic(G, expected)
+
+    def test_trivial_graph(self):
+        assert nx.number_of_nodes(nx.trivial_graph()) == 1
+
+    def test_turan_graph(self):
+        assert nx.number_of_edges(nx.turan_graph(13, 4)) == 63
+        assert nx.could_be_isomorphic(
+            nx.turan_graph(13, 4), nx.complete_multipartite_graph(3, 4, 3, 3)
+        )
+
+    def test_wheel_graph(self):
+        for n, G in [
+            ("", nx.null_graph()),
+            (0, nx.null_graph()),
+            (1, nx.empty_graph(1)),
+            (2, nx.path_graph(2)),
+            (3, nx.complete_graph(3)),
+            (4, nx.complete_graph(4)),
+        ]:
+            g = nx.wheel_graph(n)
+            assert nx.could_be_isomorphic(g, G)
+
+        g = nx.wheel_graph(10)
+        assert sorted(d for n, d in g.degree()) == [3, 3, 3, 3, 3, 3, 3, 3, 3, 9]
+
+        pytest.raises(nx.NetworkXError, nx.wheel_graph, 10, create_using=nx.DiGraph)
+
+        mg = nx.wheel_graph(10, create_using=nx.MultiGraph())
+        assert edges_equal(mg.edges(), g.edges())
+
+        G = nx.wheel_graph("abc")
+        assert len(G) == 3
+        assert G.size() == 3
+
+        G = nx.wheel_graph("abcb")
+        assert len(G) == 3
+        assert G.size() == 4
+        G = nx.wheel_graph("abcb", nx.MultiGraph)
+        assert len(G) == 3
+        assert G.size() == 6
+
+    def test_non_int_integers_for_wheel_graph(self):
+        np = pytest.importorskip("numpy")
+        G = nx.wheel_graph(np.int32(3))
+        assert len(G) == 3
+        assert G.size() == 3
+
+    def test_complete_0_partite_graph(self):
+        """Tests that the complete 0-partite graph is the null graph."""
+        G = nx.complete_multipartite_graph()
+        H = nx.null_graph()
+        assert nodes_equal(G, H)
+        assert edges_equal(G.edges(), H.edges())
+
+    def test_complete_1_partite_graph(self):
+        """Tests that the complete 1-partite graph is the empty graph."""
+        G = nx.complete_multipartite_graph(3)
+        H = nx.empty_graph(3)
+        assert nodes_equal(G, H)
+        assert edges_equal(G.edges(), H.edges())
+
+    def test_complete_2_partite_graph(self):
+        """Tests that the complete 2-partite graph is the complete bipartite
+        graph.
+
+        """
+        G = nx.complete_multipartite_graph(2, 3)
+        H = nx.complete_bipartite_graph(2, 3)
+        assert nodes_equal(G, H)
+        assert edges_equal(G.edges(), H.edges())
+
+    def test_complete_multipartite_graph(self):
+        """Tests for generating the complete multipartite graph."""
+        G = nx.complete_multipartite_graph(2, 3, 4)
+        blocks = [(0, 1), (2, 3, 4), (5, 6, 7, 8)]
+        # Within each block, no two vertices should be adjacent.
+        for block in blocks:
+            for u, v in itertools.combinations_with_replacement(block, 2):
+                assert v not in G[u]
+                assert G.nodes[u] == G.nodes[v]
+        # Across blocks, all vertices should be adjacent.
+        for block1, block2 in itertools.combinations(blocks, 2):
+            for u, v in itertools.product(block1, block2):
+                assert v in G[u]
+                assert G.nodes[u] != G.nodes[v]
+        with pytest.raises(nx.NetworkXError, match="Negative number of nodes"):
+            nx.complete_multipartite_graph(2, -3, 4)
+
+    def test_kneser_graph(self):
+        # the petersen graph is a special case of the kneser graph when n=5 and k=2
+        assert nx.could_be_isomorphic(nx.kneser_graph(5, 2), nx.petersen_graph())
+
+        # when k is 1, the kneser graph returns a complete graph with n vertices
+        for i in range(1, 7):
+            assert nx.could_be_isomorphic(nx.kneser_graph(i, 1), nx.complete_graph(i))
+
+        # the kneser graph of n and n-1 is the empty graph with n vertices
+        for j in range(3, 7):
+            assert nx.could_be_isomorphic(nx.kneser_graph(j, j - 1), nx.empty_graph(j))
+
+        # in general the number of edges of the kneser graph is equal to
+        # (n choose k) times (n-k choose k) divided by 2
+        assert nx.number_of_edges(nx.kneser_graph(8, 3)) == 280
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_cographs.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_cographs.py
new file mode 100644
index 0000000000000000000000000000000000000000..65ac3250fd34c5972534504184839a929289e8a9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_cographs.py
@@ -0,0 +1,20 @@
+"""Unit tests for the :mod:`networkx.generators.cographs` module."""
+
+import pytest
+
+import networkx as nx
+
+
+@pytest.mark.parametrize("n", [3, 4, 5])
+@pytest.mark.parametrize("seed", [42, 43])
+def test_random_cograph(n, seed):
+    """Test the generation of random cographs.
+
+    Parametrized on `seed` to ensure we hit all code branches.
+    """
+    G = nx.random_cograph(n, seed=seed)
+
+    assert len(G) == 2**n
+
+    # Every connected subgraph of G has diameter <= 2.
+    assert all(nx.diameter(G.subgraph(c)) <= 2 for c in nx.connected_components(G))
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_community.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_community.py
new file mode 100644
index 0000000000000000000000000000000000000000..2fa107f6dde9f280123796f81b919c99f92ee20c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_community.py
@@ -0,0 +1,362 @@
+import pytest
+
+import networkx as nx
+
+
+def test_random_partition_graph():
+    G = nx.random_partition_graph([3, 3, 3], 1, 0, seed=42)
+    C = G.graph["partition"]
+    assert C == [{0, 1, 2}, {3, 4, 5}, {6, 7, 8}]
+    assert len(G) == 9
+    assert len(list(G.edges())) == 9
+
+    G = nx.random_partition_graph([3, 3, 3], 0, 1)
+    C = G.graph["partition"]
+    assert C == [{0, 1, 2}, {3, 4, 5}, {6, 7, 8}]
+    assert len(G) == 9
+    assert len(list(G.edges())) == 27
+
+    G = nx.random_partition_graph([3, 3, 3], 1, 0, directed=True)
+    C = G.graph["partition"]
+    assert C == [{0, 1, 2}, {3, 4, 5}, {6, 7, 8}]
+    assert len(G) == 9
+    assert len(list(G.edges())) == 18
+
+    G = nx.random_partition_graph([3, 3, 3], 0, 1, directed=True)
+    C = G.graph["partition"]
+    assert C == [{0, 1, 2}, {3, 4, 5}, {6, 7, 8}]
+    assert len(G) == 9
+    assert len(list(G.edges())) == 54
+
+    G = nx.random_partition_graph([1, 2, 3, 4, 5], 0.5, 0.1)
+    C = G.graph["partition"]
+    assert C == [{0}, {1, 2}, {3, 4, 5}, {6, 7, 8, 9}, {10, 11, 12, 13, 14}]
+    assert len(G) == 15
+
+    rpg = nx.random_partition_graph
+    pytest.raises(nx.NetworkXError, rpg, [1, 2, 3], 1.1, 0.1)
+    pytest.raises(nx.NetworkXError, rpg, [1, 2, 3], -0.1, 0.1)
+    pytest.raises(nx.NetworkXError, rpg, [1, 2, 3], 0.1, 1.1)
+    pytest.raises(nx.NetworkXError, rpg, [1, 2, 3], 0.1, -0.1)
+
+
+def test_planted_partition_graph():
+    G = nx.planted_partition_graph(4, 3, 1, 0, seed=42)
+    C = G.graph["partition"]
+    assert len(C) == 4
+    assert len(G) == 12
+    assert len(list(G.edges())) == 12
+
+    G = nx.planted_partition_graph(4, 3, 0, 1)
+    C = G.graph["partition"]
+    assert len(C) == 4
+    assert len(G) == 12
+    assert len(list(G.edges())) == 54
+
+    G = nx.planted_partition_graph(10, 4, 0.5, 0.1, seed=42)
+    C = G.graph["partition"]
+    assert len(C) == 10
+    assert len(G) == 40
+
+    G = nx.planted_partition_graph(4, 3, 1, 0, directed=True)
+    C = G.graph["partition"]
+    assert len(C) == 4
+    assert len(G) == 12
+    assert len(list(G.edges())) == 24
+
+    G = nx.planted_partition_graph(4, 3, 0, 1, directed=True)
+    C = G.graph["partition"]
+    assert len(C) == 4
+    assert len(G) == 12
+    assert len(list(G.edges())) == 108
+
+    G = nx.planted_partition_graph(10, 4, 0.5, 0.1, seed=42, directed=True)
+    C = G.graph["partition"]
+    assert len(C) == 10
+    assert len(G) == 40
+
+    ppg = nx.planted_partition_graph
+    pytest.raises(nx.NetworkXError, ppg, 3, 3, 1.1, 0.1)
+    pytest.raises(nx.NetworkXError, ppg, 3, 3, -0.1, 0.1)
+    pytest.raises(nx.NetworkXError, ppg, 3, 3, 0.1, 1.1)
+    pytest.raises(nx.NetworkXError, ppg, 3, 3, 0.1, -0.1)
+
+
+def test_relaxed_caveman_graph():
+    G = nx.relaxed_caveman_graph(4, 3, 0)
+    assert len(G) == 12
+    G = nx.relaxed_caveman_graph(4, 3, 1)
+    assert len(G) == 12
+    G = nx.relaxed_caveman_graph(4, 3, 0.5)
+    assert len(G) == 12
+    G = nx.relaxed_caveman_graph(4, 3, 0.5, seed=42)
+    assert len(G) == 12
+
+
+def test_connected_caveman_graph():
+    G = nx.connected_caveman_graph(4, 3)
+    assert len(G) == 12
+
+    G = nx.connected_caveman_graph(1, 5)
+    K5 = nx.complete_graph(5)
+    K5.remove_edge(3, 4)
+    assert nx.is_isomorphic(G, K5)
+
+    # need at least 2 nodes in each clique
+    pytest.raises(nx.NetworkXError, nx.connected_caveman_graph, 4, 1)
+
+
+def test_caveman_graph():
+    G = nx.caveman_graph(4, 3)
+    assert len(G) == 12
+
+    G = nx.caveman_graph(5, 1)
+    E5 = nx.empty_graph(5)
+    assert nx.is_isomorphic(G, E5)
+
+    G = nx.caveman_graph(1, 5)
+    K5 = nx.complete_graph(5)
+    assert nx.is_isomorphic(G, K5)
+
+
+def test_gaussian_random_partition_graph():
+    G = nx.gaussian_random_partition_graph(100, 10, 10, 0.3, 0.01)
+    assert len(G) == 100
+    G = nx.gaussian_random_partition_graph(100, 10, 10, 0.3, 0.01, directed=True)
+    assert len(G) == 100
+    G = nx.gaussian_random_partition_graph(
+        100, 10, 10, 0.3, 0.01, directed=False, seed=42
+    )
+    assert len(G) == 100
+    assert not isinstance(G, nx.DiGraph)
+    G = nx.gaussian_random_partition_graph(
+        100, 10, 10, 0.3, 0.01, directed=True, seed=42
+    )
+    assert len(G) == 100
+    assert isinstance(G, nx.DiGraph)
+    pytest.raises(
+        nx.NetworkXError, nx.gaussian_random_partition_graph, 100, 101, 10, 1, 0
+    )
+    # Test when clusters are likely less than 1
+    G = nx.gaussian_random_partition_graph(10, 0.5, 0.5, 0.5, 0.5, seed=1)
+    assert len(G) == 10
+
+
+def test_ring_of_cliques():
+    for i in range(2, 20, 3):
+        for j in range(2, 20, 3):
+            G = nx.ring_of_cliques(i, j)
+            assert G.number_of_nodes() == i * j
+            if i != 2 or j != 1:
+                expected_num_edges = i * (((j * (j - 1)) // 2) + 1)
+            else:
+                # the edge that already exists cannot be duplicated
+                expected_num_edges = i * (((j * (j - 1)) // 2) + 1) - 1
+            assert G.number_of_edges() == expected_num_edges
+    with pytest.raises(
+        nx.NetworkXError, match="A ring of cliques must have at least two cliques"
+    ):
+        nx.ring_of_cliques(1, 5)
+    with pytest.raises(
+        nx.NetworkXError, match="The cliques must have at least two nodes"
+    ):
+        nx.ring_of_cliques(3, 0)
+
+
+def test_windmill_graph():
+    for n in range(2, 20, 3):
+        for k in range(2, 20, 3):
+            G = nx.windmill_graph(n, k)
+            assert G.number_of_nodes() == (k - 1) * n + 1
+            assert G.number_of_edges() == n * k * (k - 1) / 2
+            assert G.degree(0) == G.number_of_nodes() - 1
+            for i in range(1, G.number_of_nodes()):
+                assert G.degree(i) == k - 1
+    with pytest.raises(
+        nx.NetworkXError, match="A windmill graph must have at least two cliques"
+    ):
+        nx.windmill_graph(1, 3)
+    with pytest.raises(
+        nx.NetworkXError, match="The cliques must have at least two nodes"
+    ):
+        nx.windmill_graph(3, 0)
+
+
+def test_stochastic_block_model():
+    sizes = [75, 75, 300]
+    probs = [[0.25, 0.05, 0.02], [0.05, 0.35, 0.07], [0.02, 0.07, 0.40]]
+    G = nx.stochastic_block_model(sizes, probs, seed=0)
+    C = G.graph["partition"]
+    assert len(C) == 3
+    assert len(G) == 450
+    assert G.size() == 22160
+
+    GG = nx.stochastic_block_model(sizes, probs, range(450), seed=0)
+    assert G.nodes == GG.nodes
+
+    # Test Exceptions
+    sbm = nx.stochastic_block_model
+    badnodelist = list(range(400))  # not enough nodes to match sizes
+    badprobs1 = [[0.25, 0.05, 1.02], [0.05, 0.35, 0.07], [0.02, 0.07, 0.40]]
+    badprobs2 = [[0.25, 0.05, 0.02], [0.05, -0.35, 0.07], [0.02, 0.07, 0.40]]
+    probs_rect1 = [[0.25, 0.05, 0.02], [0.05, -0.35, 0.07]]
+    probs_rect2 = [[0.25, 0.05], [0.05, -0.35], [0.02, 0.07]]
+    asymprobs = [[0.25, 0.05, 0.01], [0.05, -0.35, 0.07], [0.02, 0.07, 0.40]]
+    pytest.raises(nx.NetworkXException, sbm, sizes, badprobs1)
+    pytest.raises(nx.NetworkXException, sbm, sizes, badprobs2)
+    pytest.raises(nx.NetworkXException, sbm, sizes, probs_rect1, directed=True)
+    pytest.raises(nx.NetworkXException, sbm, sizes, probs_rect2, directed=True)
+    pytest.raises(nx.NetworkXException, sbm, sizes, asymprobs, directed=False)
+    pytest.raises(nx.NetworkXException, sbm, sizes, probs, badnodelist)
+    nodelist = [0] + list(range(449))  # repeated node name in nodelist
+    pytest.raises(nx.NetworkXException, sbm, sizes, probs, nodelist)
+
+    # Extra keyword arguments test
+    GG = nx.stochastic_block_model(sizes, probs, seed=0, selfloops=True)
+    assert G.nodes == GG.nodes
+    GG = nx.stochastic_block_model(sizes, probs, selfloops=True, directed=True)
+    assert G.nodes == GG.nodes
+    GG = nx.stochastic_block_model(sizes, probs, seed=0, sparse=False)
+    assert G.nodes == GG.nodes
+
+
+def test_generator():
+    n = 250
+    tau1 = 3
+    tau2 = 1.5
+    mu = 0.1
+    G = nx.LFR_benchmark_graph(
+        n, tau1, tau2, mu, average_degree=5, min_community=20, seed=10
+    )
+    assert len(G) == 250
+    C = {frozenset(G.nodes[v]["community"]) for v in G}
+    assert nx.community.is_partition(G.nodes(), C)
+
+
+def test_invalid_tau1():
+    with pytest.raises(nx.NetworkXError, match="tau2 must be greater than one"):
+        n = 100
+        tau1 = 2
+        tau2 = 1
+        mu = 0.1
+        nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2)
+
+
+def test_invalid_tau2():
+    with pytest.raises(nx.NetworkXError, match="tau1 must be greater than one"):
+        n = 100
+        tau1 = 1
+        tau2 = 2
+        mu = 0.1
+        nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2)
+
+
+def test_mu_too_large():
+    with pytest.raises(nx.NetworkXError, match="mu must be in the interval \\[0, 1\\]"):
+        n = 100
+        tau1 = 2
+        tau2 = 2
+        mu = 1.1
+        nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2)
+
+
+def test_mu_too_small():
+    with pytest.raises(nx.NetworkXError, match="mu must be in the interval \\[0, 1\\]"):
+        n = 100
+        tau1 = 2
+        tau2 = 2
+        mu = -1
+        nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2)
+
+
+def test_both_degrees_none():
+    with pytest.raises(
+        nx.NetworkXError,
+        match="Must assign exactly one of min_degree and average_degree",
+    ):
+        n = 100
+        tau1 = 2
+        tau2 = 2
+        mu = 1
+        nx.LFR_benchmark_graph(n, tau1, tau2, mu)
+
+
+def test_neither_degrees_none():
+    with pytest.raises(
+        nx.NetworkXError,
+        match="Must assign exactly one of min_degree and average_degree",
+    ):
+        n = 100
+        tau1 = 2
+        tau2 = 2
+        mu = 1
+        nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2, average_degree=5)
+
+
+def test_max_iters_exceeded():
+    with pytest.raises(
+        nx.ExceededMaxIterations,
+        match="Could not assign communities; try increasing min_community",
+    ):
+        n = 10
+        tau1 = 2
+        tau2 = 2
+        mu = 0.1
+        nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2, max_iters=10, seed=1)
+
+
+def test_max_deg_out_of_range():
+    with pytest.raises(
+        nx.NetworkXError, match="max_degree must be in the interval \\(0, n\\]"
+    ):
+        n = 10
+        tau1 = 2
+        tau2 = 2
+        mu = 0.1
+        nx.LFR_benchmark_graph(
+            n, tau1, tau2, mu, max_degree=n + 1, max_iters=10, seed=1
+        )
+
+
+def test_max_community():
+    n = 250
+    tau1 = 3
+    tau2 = 1.5
+    mu = 0.1
+    G = nx.LFR_benchmark_graph(
+        n,
+        tau1,
+        tau2,
+        mu,
+        average_degree=5,
+        max_degree=100,
+        min_community=50,
+        max_community=200,
+        seed=10,
+    )
+    assert len(G) == 250
+    C = {frozenset(G.nodes[v]["community"]) for v in G}
+    assert nx.community.is_partition(G.nodes(), C)
+
+
+def test_powerlaw_iterations_exceeded():
+    with pytest.raises(
+        nx.ExceededMaxIterations, match="Could not create power law sequence"
+    ):
+        n = 100
+        tau1 = 2
+        tau2 = 2
+        mu = 1
+        nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2, max_iters=0)
+
+
+def test_no_scipy_zeta():
+    zeta2 = 1.6449340668482264
+    assert abs(zeta2 - nx.generators.community._hurwitz_zeta(2, 1, 0.0001)) < 0.01
+
+
+def test_generate_min_degree_itr():
+    with pytest.raises(
+        nx.ExceededMaxIterations, match="Could not match average_degree"
+    ):
+        nx.generators.community._generate_min_degree(2, 2, 1, 0.01, 0)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_degree_seq.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_degree_seq.py
new file mode 100644
index 0000000000000000000000000000000000000000..c7317cd564ed30430bd267e0bb355913cc69353d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_degree_seq.py
@@ -0,0 +1,224 @@
+import pytest
+
+import networkx as nx
+
+
+class TestConfigurationModel:
+    """Unit tests for the :func:`~networkx.configuration_model`
+    function.
+
+    """
+
+    def test_empty_degree_sequence(self):
+        """Tests that an empty degree sequence yields the null graph."""
+        G = nx.configuration_model([])
+        assert len(G) == 0
+
+    def test_degree_zero(self):
+        """Tests that a degree sequence of all zeros yields the empty
+        graph.
+
+        """
+        G = nx.configuration_model([0, 0, 0])
+        assert len(G) == 3
+        assert G.number_of_edges() == 0
+
+    def test_degree_sequence(self):
+        """Tests that the degree sequence of the generated graph matches
+        the input degree sequence.
+
+        """
+        deg_seq = [5, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
+        G = nx.configuration_model(deg_seq, seed=12345678)
+        assert sorted(dict(G.degree).values()) == sorted(deg_seq)
+        assert sorted(dict(G.degree(range(len(deg_seq)))).values()) == sorted(deg_seq)
+
+    @pytest.mark.parametrize("seed", [10, 1000])
+    def test_random_seed(self, seed):
+        """Tests that each call with the same random seed generates the
+        same graph.
+
+        """
+        deg_seq = [3] * 12
+        G1 = nx.configuration_model(deg_seq, seed=seed)
+        G2 = nx.configuration_model(deg_seq, seed=seed)
+        assert nx.is_isomorphic(G1, G2)
+
+    def test_directed_disallowed(self):
+        """Tests that attempting to create a configuration model graph
+        using a directed graph yields an exception.
+
+        """
+        with pytest.raises(nx.NetworkXNotImplemented):
+            nx.configuration_model([], create_using=nx.DiGraph())
+
+    def test_odd_degree_sum(self):
+        """Tests that a degree sequence whose sum is odd yields an
+        exception.
+
+        """
+        with pytest.raises(nx.NetworkXError):
+            nx.configuration_model([1, 2])
+
+
+def test_directed_configuration_raise_unequal():
+    with pytest.raises(nx.NetworkXError):
+        zin = [5, 3, 3, 3, 3, 2, 2, 2, 1, 1]
+        zout = [5, 3, 3, 3, 3, 2, 2, 2, 1, 2]
+        nx.directed_configuration_model(zin, zout)
+
+
+def test_directed_configuration_model():
+    G = nx.directed_configuration_model([], [], seed=0)
+    assert len(G) == 0
+
+
+def test_simple_directed_configuration_model():
+    G = nx.directed_configuration_model([1, 1], [1, 1], seed=0)
+    assert len(G) == 2
+
+
+def test_expected_degree_graph_empty():
+    # empty graph has empty degree sequence
+    deg_seq = []
+    G = nx.expected_degree_graph(deg_seq)
+    assert dict(G.degree()) == {}
+
+
+@pytest.mark.parametrize("seed", [10, 42, 1000])
+@pytest.mark.parametrize("deg_seq", [[3] * 12, [2, 0], [10, 2, 2, 2, 2]])
+def test_expected_degree_graph(seed, deg_seq):
+    G1 = nx.expected_degree_graph(deg_seq, seed=seed)
+    G2 = nx.expected_degree_graph(deg_seq, seed=seed)
+    assert len(G1) == len(G2) == len(deg_seq)
+    assert nx.is_isomorphic(G1, G2)
+
+
+def test_expected_degree_graph_selfloops():
+    deg_seq = [3] * 12
+    G1 = nx.expected_degree_graph(deg_seq, seed=1000, selfloops=False)
+    G2 = nx.expected_degree_graph(deg_seq, seed=1000, selfloops=False)
+    assert len(G1) == len(G2) == len(deg_seq)
+    assert nx.is_isomorphic(G1, G2)
+    assert nx.number_of_selfloops(G1) == nx.number_of_selfloops(G2) == 0
+
+
+def test_havel_hakimi_construction():
+    G = nx.havel_hakimi_graph([])
+    assert len(G) == 0
+
+    z = [1000, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
+    pytest.raises(nx.NetworkXError, nx.havel_hakimi_graph, z)
+    z = ["A", 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
+    pytest.raises(nx.NetworkXError, nx.havel_hakimi_graph, z)
+
+    z = [5, 4, 3, 3, 3, 2, 2, 2]
+    G = nx.havel_hakimi_graph(z)
+    G = nx.configuration_model(z)
+    z = [6, 5, 4, 4, 2, 1, 1, 1]
+    pytest.raises(nx.NetworkXError, nx.havel_hakimi_graph, z)
+
+    z = [10, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2]
+
+    G = nx.havel_hakimi_graph(z)
+
+    pytest.raises(nx.NetworkXError, nx.havel_hakimi_graph, z, create_using=nx.DiGraph())
+
+
+def test_directed_havel_hakimi():
+    # Test range of valid directed degree sequences
+    n, r = 100, 10
+    p = 1.0 / r
+    for i in range(r):
+        G1 = nx.erdos_renyi_graph(n, p * (i + 1), None, True)
+        din1 = [d for n, d in G1.in_degree()]
+        dout1 = [d for n, d in G1.out_degree()]
+        G2 = nx.directed_havel_hakimi_graph(din1, dout1)
+        din2 = [d for n, d in G2.in_degree()]
+        dout2 = [d for n, d in G2.out_degree()]
+        assert sorted(din1) == sorted(din2)
+        assert sorted(dout1) == sorted(dout2)
+
+    # Test non-graphical sequence
+    dout = [1000, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
+    din = [103, 102, 102, 102, 102, 102, 102, 102, 102, 102]
+    pytest.raises(nx.exception.NetworkXError, nx.directed_havel_hakimi_graph, din, dout)
+    # Test valid sequences
+    dout = [1, 1, 1, 1, 1, 2, 2, 2, 3, 4]
+    din = [2, 2, 2, 2, 2, 2, 2, 2, 0, 2]
+    G2 = nx.directed_havel_hakimi_graph(din, dout)
+    dout2 = (d for n, d in G2.out_degree())
+    din2 = (d for n, d in G2.in_degree())
+    assert sorted(dout) == sorted(dout2)
+    assert sorted(din) == sorted(din2)
+    # Test unequal sums
+    din = [2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
+    pytest.raises(nx.exception.NetworkXError, nx.directed_havel_hakimi_graph, din, dout)
+    # Test for negative values
+    din = [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, -2]
+    pytest.raises(nx.exception.NetworkXError, nx.directed_havel_hakimi_graph, din, dout)
+
+
+@pytest.mark.parametrize(
+    "deg_seq",
+    [
+        [0],
+        [1, 1],
+        [2, 2, 2, 1, 1],
+        [3, 1, 1, 1],
+        [4, 1, 1, 1, 1],
+        [1, 1, 1, 1, 1, 2, 2, 2, 3, 4],
+    ],
+)
+def test_degree_sequence_tree(deg_seq):
+    G = nx.degree_sequence_tree(deg_seq)
+    assert sorted(dict(G.degree).values()) == sorted(deg_seq)
+    assert nx.is_tree(G)
+
+
+@pytest.mark.parametrize("graph_type", [nx.DiGraph, nx.MultiDiGraph])
+def test_degree_sequence_tree_directed(graph_type):
+    with pytest.raises(nx.NetworkXError, match="Directed Graph not supported"):
+        nx.degree_sequence_tree([1, 1], create_using=graph_type())
+
+
+@pytest.mark.parametrize(
+    "deg_seq",
+    [
+        [1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 4],
+        [],
+        [2, 0],
+        [-1, 3],
+        [1, 16, 1, 4, 0, 0, 1, 1, 0, 1, 2, 0, 1, 0, 1, 5, 1, 2, 1, 0],
+    ],
+)
+def test_degree_sequence_tree_invalid_degree_sequence(deg_seq):
+    """Test invalid degree sequences raise an error."""
+    with pytest.raises(nx.NetworkXError, match="tree must have"):
+        nx.degree_sequence_tree(deg_seq)
+
+
+def test_random_degree_sequence_graph():
+    d = [1, 2, 2, 3]
+    G = nx.random_degree_sequence_graph(d, seed=42)
+    assert d == sorted(d for n, d in G.degree())
+
+
+def test_random_degree_sequence_graph_raise():
+    z = [1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 4]
+    pytest.raises(nx.NetworkXUnfeasible, nx.random_degree_sequence_graph, z)
+
+
+def test_random_degree_sequence_large():
+    G1 = nx.fast_gnp_random_graph(100, 0.1, seed=42)
+    d1 = [d for n, d in G1.degree()]
+    G2 = nx.random_degree_sequence_graph(d1, seed=42)
+    d2 = [d for n, d in G2.degree()]
+    assert sorted(d1) == sorted(d2)
+
+
+def test_random_degree_sequence_iterator():
+    G1 = nx.fast_gnp_random_graph(100, 0.1, seed=42)
+    d1 = (d for n, d in G1.degree())
+    G2 = nx.random_degree_sequence_graph(d1, seed=42)
+    assert len(G2) > 0
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_directed.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_directed.py
new file mode 100644
index 0000000000000000000000000000000000000000..93d48acfc296901dfeaf59c6b8f72ff4e293d9fd
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_directed.py
@@ -0,0 +1,189 @@
+"""Generators - Directed Graphs
+----------------------------
+"""
+
+import pytest
+
+import networkx as nx
+from networkx.classes import Graph, MultiDiGraph
+from networkx.generators.directed import (
+    _random_k_out_graph_numpy,
+    _random_k_out_graph_python,
+    gn_graph,
+    gnc_graph,
+    gnr_graph,
+    random_k_out_graph,
+    random_uniform_k_out_graph,
+    scale_free_graph,
+)
+
+try:
+    import numpy as np
+
+    has_numpy = True
+except ImportError:
+    has_numpy = False
+
+
+class TestGeneratorsDirected:
+    def test_smoke_test_random_graphs(self):
+        gn_graph(100)
+        gnr_graph(100, 0.5)
+        gnc_graph(100)
+        scale_free_graph(100)
+
+        gn_graph(100, seed=42)
+        gnr_graph(100, 0.5, seed=42)
+        gnc_graph(100, seed=42)
+        scale_free_graph(100, seed=42)
+
+    def test_create_using_keyword_arguments(self):
+        pytest.raises(nx.NetworkXError, gn_graph, 100, create_using=Graph())
+        pytest.raises(nx.NetworkXError, gnr_graph, 100, 0.5, create_using=Graph())
+        pytest.raises(nx.NetworkXError, gnc_graph, 100, create_using=Graph())
+        G = gn_graph(100, seed=1)
+        MG = gn_graph(100, create_using=MultiDiGraph(), seed=1)
+        assert sorted(G.edges()) == sorted(MG.edges())
+        G = gnr_graph(100, 0.5, seed=1)
+        MG = gnr_graph(100, 0.5, create_using=MultiDiGraph(), seed=1)
+        assert sorted(G.edges()) == sorted(MG.edges())
+        G = gnc_graph(100, seed=1)
+        MG = gnc_graph(100, create_using=MultiDiGraph(), seed=1)
+        assert sorted(G.edges()) == sorted(MG.edges())
+
+        G = scale_free_graph(
+            100,
+            alpha=0.3,
+            beta=0.4,
+            gamma=0.3,
+            delta_in=0.3,
+            delta_out=0.1,
+            initial_graph=nx.cycle_graph(4, create_using=MultiDiGraph),
+            seed=1,
+        )
+        pytest.raises(ValueError, scale_free_graph, 100, 0.5, 0.4, 0.3)
+        pytest.raises(ValueError, scale_free_graph, 100, alpha=-0.3)
+        pytest.raises(ValueError, scale_free_graph, 100, beta=-0.3)
+        pytest.raises(ValueError, scale_free_graph, 100, gamma=-0.3)
+
+    def test_parameters(self):
+        G = nx.DiGraph()
+        G.add_node(0)
+
+        def kernel(x):
+            return x
+
+        assert nx.is_isomorphic(gn_graph(1), G)
+        assert nx.is_isomorphic(gn_graph(1, kernel=kernel), G)
+        assert nx.is_isomorphic(gnc_graph(1), G)
+        assert nx.is_isomorphic(gnr_graph(1, 0.5), G)
+
+
+def test_scale_free_graph_negative_delta():
+    with pytest.raises(ValueError, match="delta_in must be >= 0."):
+        scale_free_graph(10, delta_in=-1)
+    with pytest.raises(ValueError, match="delta_out must be >= 0."):
+        scale_free_graph(10, delta_out=-1)
+
+
+def test_non_numeric_ordering():
+    G = MultiDiGraph([("a", "b"), ("b", "c"), ("c", "a")])
+    s = scale_free_graph(3, initial_graph=G)
+    assert len(s) == 3
+    assert len(s.edges) == 3
+
+
+@pytest.mark.parametrize("ig", (nx.Graph(), nx.DiGraph([(0, 1)])))
+def test_scale_free_graph_initial_graph_kwarg(ig):
+    with pytest.raises(nx.NetworkXError):
+        scale_free_graph(100, initial_graph=ig)
+
+
+class TestRandomKOutGraph:
+    """Unit tests for the
+    :func:`~networkx.generators.directed.random_k_out_graph` function.
+
+    """
+
+    @pytest.fixture(
+        params=[
+            pytest.param(
+                _random_k_out_graph_numpy,
+                marks=pytest.mark.skipif(not has_numpy, reason="numpy not installed"),
+            ),
+            _random_k_out_graph_python,
+        ]
+    )
+    def f(self, request):
+        yield request.param
+
+    @pytest.fixture(params=[(10, 3, 1), (20, 2, 4), (5, 1, 10)])
+    def nkalpha(self, request):
+        yield request.param
+
+    def test_regularity(self, f, nkalpha):
+        """Test that the generated graph is `k`-out-regular."""
+        n, k, alpha = nkalpha
+        G = f(n, k, alpha, seed=42)
+        assert all(d == k for _, d in G.out_degree)
+
+    def test_no_self_loops(self, f, nkalpha):
+        """Test for forbidding self-loops."""
+        n, k, alpha = nkalpha
+        G = f(n, k, alpha, self_loops=False, seed=42)
+        assert nx.number_of_selfloops(G) == 0
+
+    def test_random_k_out_graph(self, nkalpha):
+        """Test that the interface function `random_k_out_graph` works correctly."""
+        n, k, alpha = nkalpha
+        G = random_k_out_graph(n, k, alpha, seed=42)
+        assert len(G) == n
+        assert all(d == k for _, d in G.out_degree)
+
+    def test_negative_alpha(self):
+        with pytest.raises(ValueError, match="alpha must be positive"):
+            random_k_out_graph(10, 3, -1)
+
+
+class TestUniformRandomKOutGraph:
+    """Unit tests for the
+    :func:`~networkx.generators.directed.random_uniform_k_out_graph`
+    function.
+
+    """
+
+    def test_regularity(self):
+        """Tests that the generated graph is `k`-out-regular."""
+        n = 10
+        k = 3
+        G = random_uniform_k_out_graph(n, k)
+        assert all(d == k for v, d in G.out_degree())
+        G = random_uniform_k_out_graph(n, k, seed=42)
+        assert all(d == k for v, d in G.out_degree())
+
+    def test_no_self_loops(self):
+        """Tests for forbidding self-loops."""
+        n = 10
+        k = 3
+        G = random_uniform_k_out_graph(n, k, self_loops=False)
+        assert nx.number_of_selfloops(G) == 0
+        assert all(d == k for v, d in G.out_degree())
+
+    def test_with_replacement(self):
+        n = 10
+        k = 3
+        G = random_uniform_k_out_graph(n, k, with_replacement=True)
+        assert G.is_multigraph()
+        assert all(d == k for v, d in G.out_degree())
+        n = 10
+        k = 9
+        G = random_uniform_k_out_graph(n, k, with_replacement=False, self_loops=False)
+        assert nx.number_of_selfloops(G) == 0
+        assert all(d == k for v, d in G.out_degree())
+
+    def test_without_replacement(self):
+        n = 10
+        k = 3
+        G = random_uniform_k_out_graph(n, k, with_replacement=False)
+        assert not G.is_multigraph()
+        assert all(d == k for v, d in G.out_degree())
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_duplication.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_duplication.py
new file mode 100644
index 0000000000000000000000000000000000000000..9b6100b78e59067b607e310f14d80e5a00c2b691
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_duplication.py
@@ -0,0 +1,103 @@
+"""Unit tests for the :mod:`networkx.generators.duplication` module."""
+
+import pytest
+
+import networkx as nx
+
+
+class TestDuplicationDivergenceGraph:
+    """Unit tests for the
+    :func:`networkx.generators.duplication.duplication_divergence_graph`
+    function.
+
+    """
+
+    def test_final_size(self):
+        G = nx.duplication_divergence_graph(3, p=1)
+        assert len(G) == 3
+        G = nx.duplication_divergence_graph(3, p=1, seed=42)
+        assert len(G) == 3
+
+    def test_probability_too_large(self):
+        with pytest.raises(nx.NetworkXError):
+            nx.duplication_divergence_graph(3, p=2)
+
+    def test_probability_too_small(self):
+        with pytest.raises(nx.NetworkXError):
+            nx.duplication_divergence_graph(3, p=-1)
+
+    def test_non_extreme_probability_value(self):
+        G = nx.duplication_divergence_graph(6, p=0.3, seed=42)
+        assert len(G) == 6
+        assert list(G.degree()) == [(0, 2), (1, 3), (2, 2), (3, 3), (4, 1), (5, 1)]
+
+    def test_minimum_desired_nodes(self):
+        with pytest.raises(
+            nx.NetworkXError, match=".*n must be greater than or equal to 2"
+        ):
+            nx.duplication_divergence_graph(1, p=1)
+
+    def test_create_using(self):
+        class DummyGraph(nx.Graph):
+            pass
+
+        class DummyDiGraph(nx.DiGraph):
+            pass
+
+        G = nx.duplication_divergence_graph(6, 0.3, seed=42, create_using=DummyGraph)
+        assert isinstance(G, DummyGraph)
+        with pytest.raises(nx.NetworkXError, match="create_using must not be directed"):
+            nx.duplication_divergence_graph(6, 0.3, seed=42, create_using=DummyDiGraph)
+
+
+class TestPartialDuplicationGraph:
+    """Unit tests for the
+    :func:`networkx.generators.duplication.partial_duplication_graph`
+    function.
+
+    """
+
+    def test_final_size(self):
+        N = 10
+        n = 5
+        p = 0.5
+        q = 0.5
+        G = nx.partial_duplication_graph(N, n, p, q)
+        assert len(G) == N
+        G = nx.partial_duplication_graph(N, n, p, q, seed=42)
+        assert len(G) == N
+
+    def test_initial_clique_size(self):
+        N = 10
+        n = 10
+        p = 0.5
+        q = 0.5
+        G = nx.partial_duplication_graph(N, n, p, q)
+        assert len(G) == n
+
+    def test_invalid_initial_size(self):
+        with pytest.raises(nx.NetworkXError):
+            N = 5
+            n = 10
+            p = 0.5
+            q = 0.5
+            G = nx.partial_duplication_graph(N, n, p, q)
+
+    def test_invalid_probabilities(self):
+        N = 1
+        n = 1
+        for p, q in [(0.5, 2), (0.5, -1), (2, 0.5), (-1, 0.5)]:
+            args = (N, n, p, q)
+            pytest.raises(nx.NetworkXError, nx.partial_duplication_graph, *args)
+
+    def test_create_using(self):
+        class DummyGraph(nx.Graph):
+            pass
+
+        class DummyDiGraph(nx.DiGraph):
+            pass
+
+        G = nx.partial_duplication_graph(10, 5, 0.5, 0.5, create_using=DummyGraph)
+        assert isinstance(G, DummyGraph)
+        with pytest.raises(nx.NetworkXError, match="create_using must not be directed"):
+            nx.partial_duplication_graph(10, 5, 0.5, 0.5, create_using=DummyDiGraph)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_ego.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_ego.py
new file mode 100644
index 0000000000000000000000000000000000000000..f6fc779548a3fd2e049679987f941b2bc211c2d0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_ego.py
@@ -0,0 +1,39 @@
+"""
+ego graph
+---------
+"""
+
+import networkx as nx
+from networkx.utils import edges_equal, nodes_equal
+
+
+class TestGeneratorEgo:
+    def test_ego(self):
+        G = nx.star_graph(3)
+        H = nx.ego_graph(G, 0)
+        assert nx.is_isomorphic(G, H)
+        G.add_edge(1, 11)
+        G.add_edge(2, 22)
+        G.add_edge(3, 33)
+        H = nx.ego_graph(G, 0)
+        assert nx.is_isomorphic(nx.star_graph(3), H)
+        G = nx.path_graph(3)
+        H = nx.ego_graph(G, 0)
+        assert edges_equal(H.edges(), [(0, 1)])
+        H = nx.ego_graph(G, 0, undirected=True)
+        assert edges_equal(H.edges(), [(0, 1)])
+        H = nx.ego_graph(G, 0, center=False)
+        assert edges_equal(H.edges(), [])
+
+    def test_ego_distance(self):
+        G = nx.Graph()
+        G.add_edge(0, 1, weight=2, distance=1)
+        G.add_edge(1, 2, weight=2, distance=2)
+        G.add_edge(2, 3, weight=2, distance=1)
+        assert nodes_equal(nx.ego_graph(G, 0, radius=3).nodes(), [0, 1, 2, 3])
+        eg = nx.ego_graph(G, 0, radius=3, distance="weight")
+        assert nodes_equal(eg.nodes(), [0, 1])
+        eg = nx.ego_graph(G, 0, radius=3, distance="weight", undirected=True)
+        assert nodes_equal(eg.nodes(), [0, 1])
+        eg = nx.ego_graph(G, 0, radius=3, distance="distance")
+        assert nodes_equal(eg.nodes(), [0, 1, 2])
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_expanders.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_expanders.py
new file mode 100644
index 0000000000000000000000000000000000000000..d742b88f3778fe718c6c53f804f9b938fdb89481
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_expanders.py
@@ -0,0 +1,182 @@
+"""Unit tests for the :mod:`networkx.generators.expanders` module."""
+
+import pytest
+
+import networkx as nx
+
+
+@pytest.mark.parametrize("n", (2, 3, 5, 6, 10))
+def test_margulis_gabber_galil_graph_properties(n):
+    g = nx.margulis_gabber_galil_graph(n)
+    assert g.number_of_nodes() == n * n
+    for node in g:
+        assert g.degree(node) == 8
+        assert len(node) == 2
+        for i in node:
+            assert int(i) == i
+            assert 0 <= i < n
+
+
+@pytest.mark.parametrize("n", (2, 3, 5, 6, 10))
+def test_margulis_gabber_galil_graph_eigvals(n):
+    np = pytest.importorskip("numpy")
+    sp = pytest.importorskip("scipy")
+
+    g = nx.margulis_gabber_galil_graph(n)
+    # Eigenvalues are already sorted using the scipy eigvalsh,
+    # but the implementation in numpy does not guarantee order.
+    w = sorted(sp.linalg.eigvalsh(nx.adjacency_matrix(g).toarray()))
+    assert w[-2] < 5 * np.sqrt(2)
+
+
+@pytest.mark.parametrize("p", (3, 5, 7, 11))  # Primes
+def test_chordal_cycle_graph(p):
+    """Test for the :func:`networkx.chordal_cycle_graph` function."""
+    G = nx.chordal_cycle_graph(p)
+    assert len(G) == p
+    # TODO The second largest eigenvalue should be smaller than a constant,
+    # independent of the number of nodes in the graph:
+    #
+    #     eigs = sorted(sp.linalg.eigvalsh(nx.adjacency_matrix(G).toarray()))
+    #     assert_less(eigs[-2], ...)
+    #
+
+
+@pytest.mark.parametrize("p", (3, 5, 7, 11, 13))  # Primes
+def test_paley_graph(p):
+    """Test for the :func:`networkx.paley_graph` function."""
+    G = nx.paley_graph(p)
+    # G has p nodes
+    assert len(G) == p
+    # G is (p-1)/2-regular
+    in_degrees = {G.in_degree(node) for node in G.nodes}
+    out_degrees = {G.out_degree(node) for node in G.nodes}
+    assert len(in_degrees) == 1 and in_degrees.pop() == (p - 1) // 2
+    assert len(out_degrees) == 1 and out_degrees.pop() == (p - 1) // 2
+
+    # If p = 1 mod 4, -1 is a square mod 4 and therefore the
+    # edge in the Paley graph are symmetric.
+    if p % 4 == 1:
+        for u, v in G.edges:
+            assert (v, u) in G.edges
+
+
+@pytest.mark.parametrize("d, n", [(2, 7), (4, 10), (4, 16)])
+def test_maybe_regular_expander_graph(d, n):
+    pytest.importorskip("numpy")
+    G = nx.maybe_regular_expander_graph(n, d, seed=1729)
+
+    assert len(G) == n, "Should have n nodes"
+    assert len(G.edges) == n * d / 2, "Should have n*d/2 edges"
+    assert nx.is_k_regular(G, d), "Should be d-regular"
+
+
+def test_maybe_regular_expander_graph_max_tries():
+    pytest.importorskip("numpy")
+    d, n = 4, 10
+    msg = "Too many iterations in maybe_regular_expander_graph"
+    with pytest.raises(nx.NetworkXError, match=msg):
+        nx.maybe_regular_expander_graph(n, d, max_tries=100, seed=6818)  # See gh-8048
+
+    nx.maybe_regular_expander_graph(n, d, max_tries=130, seed=6818)
+
+
+def test_maybe_regular_expander_deprecated():
+    pytest.importorskip("numpy")
+    d, n = 2, 7
+    with pytest.deprecated_call():
+        G = nx.maybe_regular_expander(n, d, seed=1729)
+
+    assert len(G) == n, "Should have n nodes"
+    assert len(G.edges) == n * d / 2, "Should have n*d/2 edges"
+    assert nx.is_k_regular(G, d), "Should be d-regular"
+
+
+@pytest.mark.parametrize("n", (3, 5, 6, 10))
+def test_is_regular_expander(n):
+    pytest.importorskip("numpy")
+    pytest.importorskip("scipy")
+    G = nx.complete_graph(n)
+
+    assert nx.is_regular_expander(G), "Should be a regular expander"
+
+
+@pytest.mark.parametrize("d, n", [(2, 7), (4, 10), (4, 16), (4, 2000)])
+def test_random_regular_expander(d, n):
+    pytest.importorskip("numpy")
+    pytest.importorskip("scipy")
+    G = nx.random_regular_expander_graph(n, d, seed=1729)
+
+    assert len(G) == n, "Should have n nodes"
+    assert len(G.edges) == n * d / 2, "Should have n*d/2 edges"
+    assert nx.is_k_regular(G, d), "Should be d-regular"
+    assert nx.is_regular_expander(G), "Should be a regular expander"
+
+
+def test_random_regular_expander_explicit_construction():
+    pytest.importorskip("numpy")
+    pytest.importorskip("scipy")
+    G = nx.random_regular_expander_graph(d=4, n=5, seed=1729)
+
+    assert len(G) == 5 and len(G.edges) == 10, "Should be a complete graph"
+
+
+@pytest.mark.parametrize("graph_type", (nx.Graph, nx.DiGraph, nx.MultiDiGraph))
+def test_margulis_gabber_galil_graph_badinput(graph_type):
+    with pytest.raises(
+        nx.NetworkXError, match="`create_using` must be an undirected multigraph"
+    ):
+        nx.margulis_gabber_galil_graph(3, create_using=graph_type)
+
+
+@pytest.mark.parametrize("graph_type", (nx.Graph, nx.DiGraph, nx.MultiDiGraph))
+def test_chordal_cycle_graph_badinput(graph_type):
+    with pytest.raises(
+        nx.NetworkXError, match="`create_using` must be an undirected multigraph"
+    ):
+        nx.chordal_cycle_graph(3, create_using=graph_type)
+
+
+def test_paley_graph_badinput():
+    with pytest.raises(
+        nx.NetworkXError, match="`create_using` cannot be a multigraph."
+    ):
+        nx.paley_graph(3, create_using=nx.MultiGraph)
+
+
+def test_maybe_regular_expander_graph_badinput():
+    pytest.importorskip("numpy")
+
+    with pytest.raises(nx.NetworkXError, match="n must be a positive integer"):
+        nx.maybe_regular_expander_graph(n=-1, d=2)
+
+    with pytest.raises(nx.NetworkXError, match="d must be greater than or equal to 2"):
+        nx.maybe_regular_expander_graph(n=10, d=0)
+
+    with pytest.raises(nx.NetworkXError, match="Need n-1>= d to have room"):
+        nx.maybe_regular_expander_graph(n=5, d=6)
+
+
+def test_is_regular_expander_badinput():
+    pytest.importorskip("numpy")
+    pytest.importorskip("scipy")
+
+    with pytest.raises(nx.NetworkXError, match="epsilon must be non negative"):
+        nx.is_regular_expander(nx.Graph(), epsilon=-1)
+
+
+def test_random_regular_expander_badinput():
+    pytest.importorskip("numpy")
+    pytest.importorskip("scipy")
+
+    with pytest.raises(nx.NetworkXError, match="n must be a positive integer"):
+        nx.random_regular_expander_graph(n=-1, d=2)
+
+    with pytest.raises(nx.NetworkXError, match="d must be greater than or equal to 2"):
+        nx.random_regular_expander_graph(n=10, d=0)
+
+    with pytest.raises(nx.NetworkXError, match="Need n-1>= d to have room"):
+        nx.random_regular_expander_graph(n=5, d=6)
+
+    with pytest.raises(nx.NetworkXError, match="epsilon must be non negative"):
+        nx.random_regular_expander_graph(n=4, d=2, epsilon=-1)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_geometric.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_geometric.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1c68bead51b75e7a39484164cc484cbd4e5def8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_geometric.py
@@ -0,0 +1,488 @@
+import math
+import random
+from itertools import combinations
+
+import pytest
+
+import networkx as nx
+
+
+def l1dist(x, y):
+    return sum(abs(a - b) for a, b in zip(x, y))
+
+
+class TestRandomGeometricGraph:
+    """Unit tests for :func:`~networkx.random_geometric_graph`"""
+
+    def test_number_of_nodes(self):
+        G = nx.random_geometric_graph(50, 0.25, seed=42)
+        assert len(G) == 50
+        G = nx.random_geometric_graph(range(50), 0.25, seed=42)
+        assert len(G) == 50
+
+    def test_distances(self):
+        """Tests that pairs of vertices adjacent if and only if they are
+        within the prescribed radius.
+        """
+        # Use the Euclidean metric, the default according to the
+        # documentation.
+        G = nx.random_geometric_graph(50, 0.25)
+        for u, v in combinations(G, 2):
+            # Adjacent vertices must be within the given distance.
+            if v in G[u]:
+                assert math.dist(G.nodes[u]["pos"], G.nodes[v]["pos"]) <= 0.25
+            # Nonadjacent vertices must be at greater distance.
+            else:
+                assert not math.dist(G.nodes[u]["pos"], G.nodes[v]["pos"]) <= 0.25
+
+    def test_p(self):
+        """Tests for providing an alternate distance metric to the generator."""
+        # Use the L1 metric.
+        G = nx.random_geometric_graph(50, 0.25, p=1)
+        for u, v in combinations(G, 2):
+            # Adjacent vertices must be within the given distance.
+            if v in G[u]:
+                assert l1dist(G.nodes[u]["pos"], G.nodes[v]["pos"]) <= 0.25
+            # Nonadjacent vertices must be at greater distance.
+            else:
+                assert not l1dist(G.nodes[u]["pos"], G.nodes[v]["pos"]) <= 0.25
+
+    def test_node_names(self):
+        """Tests using values other than sequential numbers as node IDs."""
+        import string
+
+        nodes = list(string.ascii_lowercase)
+        G = nx.random_geometric_graph(nodes, 0.25)
+        assert len(G) == len(nodes)
+
+        for u, v in combinations(G, 2):
+            # Adjacent vertices must be within the given distance.
+            if v in G[u]:
+                assert math.dist(G.nodes[u]["pos"], G.nodes[v]["pos"]) <= 0.25
+            # Nonadjacent vertices must be at greater distance.
+            else:
+                assert not math.dist(G.nodes[u]["pos"], G.nodes[v]["pos"]) <= 0.25
+
+    def test_pos_name(self):
+        G = nx.random_geometric_graph(50, 0.25, seed=42, pos_name="coords")
+        assert all(len(d["coords"]) == 2 for n, d in G.nodes.items())
+
+
+class TestSoftRandomGeometricGraph:
+    """Unit tests for :func:`~networkx.soft_random_geometric_graph`"""
+
+    def test_number_of_nodes(self):
+        G = nx.soft_random_geometric_graph(50, 0.25, seed=42)
+        assert len(G) == 50
+        G = nx.soft_random_geometric_graph(range(50), 0.25, seed=42)
+        assert len(G) == 50
+
+    def test_distances(self):
+        """Tests that pairs of vertices adjacent if and only if they are
+        within the prescribed radius.
+        """
+        # Use the Euclidean metric, the default according to the
+        # documentation.
+        G = nx.soft_random_geometric_graph(50, 0.25)
+        for u, v in combinations(G, 2):
+            # Adjacent vertices must be within the given distance.
+            if v in G[u]:
+                assert math.dist(G.nodes[u]["pos"], G.nodes[v]["pos"]) <= 0.25
+
+    def test_p(self):
+        """Tests for providing an alternate distance metric to the generator."""
+
+        # Use the L1 metric.
+        def dist(x, y):
+            return sum(abs(a - b) for a, b in zip(x, y))
+
+        G = nx.soft_random_geometric_graph(50, 0.25, p=1)
+        for u, v in combinations(G, 2):
+            # Adjacent vertices must be within the given distance.
+            if v in G[u]:
+                assert dist(G.nodes[u]["pos"], G.nodes[v]["pos"]) <= 0.25
+
+    def test_node_names(self):
+        """Tests using values other than sequential numbers as node IDs."""
+        import string
+
+        nodes = list(string.ascii_lowercase)
+        G = nx.soft_random_geometric_graph(nodes, 0.25)
+        assert len(G) == len(nodes)
+
+        for u, v in combinations(G, 2):
+            # Adjacent vertices must be within the given distance.
+            if v in G[u]:
+                assert math.dist(G.nodes[u]["pos"], G.nodes[v]["pos"]) <= 0.25
+
+    def test_p_dist_default(self):
+        """Tests default p_dict = 0.5 returns graph with edge count <= RGG with
+        same n, radius, dim and positions
+        """
+        nodes = 50
+        dim = 2
+        pos = {v: [random.random() for i in range(dim)] for v in range(nodes)}
+        RGG = nx.random_geometric_graph(50, 0.25, pos=pos)
+        SRGG = nx.soft_random_geometric_graph(50, 0.25, pos=pos)
+        assert len(SRGG.edges()) <= len(RGG.edges())
+
+    def test_p_dist_zero(self):
+        """Tests if p_dict = 0 returns disconnected graph with 0 edges"""
+
+        def p_dist(dist):
+            return 0
+
+        G = nx.soft_random_geometric_graph(50, 0.25, p_dist=p_dist)
+        assert len(G.edges) == 0
+
+    def test_pos_name(self):
+        G = nx.soft_random_geometric_graph(50, 0.25, seed=42, pos_name="coords")
+        assert all(len(d["coords"]) == 2 for n, d in G.nodes.items())
+
+
+def join(G, u, v, theta, alpha, metric):
+    """Returns ``True`` if and only if the nodes whose attributes are
+    ``du`` and ``dv`` should be joined, according to the threshold
+    condition for geographical threshold graphs.
+
+    ``G`` is an undirected NetworkX graph, and ``u`` and ``v`` are nodes
+    in that graph. The nodes must have node attributes ``'pos'`` and
+    ``'weight'``.
+
+    ``metric`` is a distance metric.
+    """
+    du, dv = G.nodes[u], G.nodes[v]
+    u_pos, v_pos = du["pos"], dv["pos"]
+    u_weight, v_weight = du["weight"], dv["weight"]
+    return (u_weight + v_weight) * metric(u_pos, v_pos) ** alpha >= theta
+
+
+class TestGeographicalThresholdGraph:
+    """Unit tests for :func:`~networkx.geographical_threshold_graph`"""
+
+    def test_number_of_nodes(self):
+        G = nx.geographical_threshold_graph(50, 100, seed=42)
+        assert len(G) == 50
+        G = nx.geographical_threshold_graph(range(50), 100, seed=42)
+        assert len(G) == 50
+
+    def test_distances(self):
+        """Tests that pairs of vertices adjacent if and only if their
+        distances meet the given threshold.
+        """
+        # Use the Euclidean metric and alpha = -2
+        # the default according to the documentation.
+        G = nx.geographical_threshold_graph(50, 10)
+        for u, v in combinations(G, 2):
+            # Adjacent vertices must exceed the threshold.
+            if v in G[u]:
+                assert join(G, u, v, 10, -2, math.dist)
+            # Nonadjacent vertices must not exceed the threshold.
+            else:
+                assert not join(G, u, v, 10, -2, math.dist)
+
+    def test_metric(self):
+        """Tests for providing an alternate distance metric to the generator."""
+        # Use the L1 metric.
+        G = nx.geographical_threshold_graph(50, 10, metric=l1dist)
+        for u, v in combinations(G, 2):
+            # Adjacent vertices must exceed the threshold.
+            if v in G[u]:
+                assert join(G, u, v, 10, -2, l1dist)
+            # Nonadjacent vertices must not exceed the threshold.
+            else:
+                assert not join(G, u, v, 10, -2, l1dist)
+
+    def test_p_dist_zero(self):
+        """Tests if p_dict = 0 returns disconnected graph with 0 edges"""
+
+        def p_dist(dist):
+            return 0
+
+        G = nx.geographical_threshold_graph(50, 1, p_dist=p_dist)
+        assert len(G.edges) == 0
+
+    def test_pos_weight_name(self):
+        gtg = nx.geographical_threshold_graph
+        G = gtg(50, 100, seed=42, pos_name="coords", weight_name="wt")
+        assert all(len(d["coords"]) == 2 for n, d in G.nodes.items())
+        assert all(d["wt"] > 0 for n, d in G.nodes.items())
+
+
+class TestWaxmanGraph:
+    """Unit tests for the :func:`~networkx.waxman_graph` function."""
+
+    def test_number_of_nodes_1(self):
+        G = nx.waxman_graph(50, 0.5, 0.1, seed=42)
+        assert len(G) == 50
+        G = nx.waxman_graph(range(50), 0.5, 0.1, seed=42)
+        assert len(G) == 50
+
+    def test_number_of_nodes_2(self):
+        G = nx.waxman_graph(50, 0.5, 0.1, L=1)
+        assert len(G) == 50
+        G = nx.waxman_graph(range(50), 0.5, 0.1, L=1)
+        assert len(G) == 50
+
+    def test_metric(self):
+        """Tests for providing an alternate distance metric to the generator."""
+        # Use the L1 metric.
+        G = nx.waxman_graph(50, 0.5, 0.1, metric=l1dist)
+        assert len(G) == 50
+
+    def test_pos_name(self):
+        G = nx.waxman_graph(50, 0.5, 0.1, seed=42, pos_name="coords")
+        assert all(len(d["coords"]) == 2 for n, d in G.nodes.items())
+
+
+class TestNavigableSmallWorldGraph:
+    def test_navigable_small_world(self):
+        G = nx.navigable_small_world_graph(5, p=1, q=0, seed=42)
+        gg = nx.grid_2d_graph(5, 5).to_directed()
+        assert nx.is_isomorphic(G, gg)
+
+        G = nx.navigable_small_world_graph(5, p=1, q=0, dim=3)
+        gg = nx.grid_graph([5, 5, 5]).to_directed()
+        assert nx.is_isomorphic(G, gg)
+
+        G = nx.navigable_small_world_graph(5, p=1, q=0, dim=1)
+        gg = nx.grid_graph([5]).to_directed()
+        assert nx.is_isomorphic(G, gg)
+
+    def test_invalid_diameter_value(self):
+        with pytest.raises(nx.NetworkXException, match=".*p must be >= 1"):
+            nx.navigable_small_world_graph(5, p=0, q=0, dim=1)
+
+    def test_invalid_long_range_connections_value(self):
+        with pytest.raises(nx.NetworkXException, match=".*q must be >= 0"):
+            nx.navigable_small_world_graph(5, p=1, q=-1, dim=1)
+
+    def test_invalid_exponent_for_decaying_probability_value(self):
+        with pytest.raises(nx.NetworkXException, match=".*r must be >= 0"):
+            nx.navigable_small_world_graph(5, p=1, q=0, r=-1, dim=1)
+
+    def test_r_between_0_and_1(self):
+        """Smoke test for radius in range [0, 1]"""
+        # q=0 means no long-range connections
+        G = nx.navigable_small_world_graph(3, p=1, q=0, r=0.5, dim=2, seed=42)
+        expected = nx.grid_2d_graph(3, 3, create_using=nx.DiGraph)
+        assert nx.utils.graphs_equal(G, expected)
+
+    @pytest.mark.parametrize("seed", range(2478, 2578, 10))
+    def test_r_general_scaling(self, seed):
+        """The probability of adding a long-range edge scales with `1 / dist**r`,
+        so a navigable_small_world graph created with r < 1 should generally
+        result in more edges than a navigable_small_world graph with r >= 1
+        (for 0 < q << n).
+
+        N.B. this is probabilistic, so this test may not hold for all seeds."""
+        G1 = nx.navigable_small_world_graph(7, q=3, r=0.5, seed=seed)
+        G2 = nx.navigable_small_world_graph(7, q=3, r=1, seed=seed)
+        G3 = nx.navigable_small_world_graph(7, q=3, r=2, seed=seed)
+        assert G1.number_of_edges() > G2.number_of_edges()
+        assert G2.number_of_edges() > G3.number_of_edges()
+
+
+class TestThresholdedRandomGeometricGraph:
+    """Unit tests for :func:`~networkx.thresholded_random_geometric_graph`"""
+
+    def test_number_of_nodes(self):
+        G = nx.thresholded_random_geometric_graph(50, 0.2, 0.1, seed=42)
+        assert len(G) == 50
+        G = nx.thresholded_random_geometric_graph(range(50), 0.2, 0.1, seed=42)
+        assert len(G) == 50
+
+    def test_distances(self):
+        """Tests that pairs of vertices adjacent if and only if they are
+        within the prescribed radius.
+        """
+        # Use the Euclidean metric, the default according to the
+        # documentation.
+        G = nx.thresholded_random_geometric_graph(50, 0.25, 0.1, seed=42)
+        for u, v in combinations(G, 2):
+            # Adjacent vertices must be within the given distance.
+            if v in G[u]:
+                assert math.dist(G.nodes[u]["pos"], G.nodes[v]["pos"]) <= 0.25
+
+    def test_p(self):
+        """Tests for providing an alternate distance metric to the generator."""
+
+        # Use the L1 metric.
+        def dist(x, y):
+            return sum(abs(a - b) for a, b in zip(x, y))
+
+        G = nx.thresholded_random_geometric_graph(50, 0.25, 0.1, p=1, seed=42)
+        for u, v in combinations(G, 2):
+            # Adjacent vertices must be within the given distance.
+            if v in G[u]:
+                assert dist(G.nodes[u]["pos"], G.nodes[v]["pos"]) <= 0.25
+
+    def test_node_names(self):
+        """Tests using values other than sequential numbers as node IDs."""
+        import string
+
+        nodes = list(string.ascii_lowercase)
+        G = nx.thresholded_random_geometric_graph(nodes, 0.25, 0.1, seed=42)
+        assert len(G) == len(nodes)
+
+        for u, v in combinations(G, 2):
+            # Adjacent vertices must be within the given distance.
+            if v in G[u]:
+                assert math.dist(G.nodes[u]["pos"], G.nodes[v]["pos"]) <= 0.25
+
+    def test_theta(self):
+        """Tests that pairs of vertices adjacent if and only if their sum
+        weights exceeds the threshold parameter theta.
+        """
+        G = nx.thresholded_random_geometric_graph(50, 0.25, 0.1, seed=42)
+
+        for u, v in combinations(G, 2):
+            # Adjacent vertices must be within the given distance.
+            if v in G[u]:
+                assert (G.nodes[u]["weight"] + G.nodes[v]["weight"]) >= 0.1
+
+    def test_pos_name(self):
+        trgg = nx.thresholded_random_geometric_graph
+        G = trgg(50, 0.25, 0.1, seed=42, pos_name="p", weight_name="wt")
+        assert all(len(d["p"]) == 2 for n, d in G.nodes.items())
+        assert all(d["wt"] > 0 for n, d in G.nodes.items())
+
+
+def test_geometric_edges_pos_attribute():
+    G = nx.Graph()
+    G.add_nodes_from(
+        [
+            (0, {"position": (0, 0)}),
+            (1, {"position": (0, 1)}),
+            (2, {"position": (1, 0)}),
+        ]
+    )
+    expected_edges = [(0, 1), (0, 2)]
+    assert expected_edges == nx.geometric_edges(G, radius=1, pos_name="position")
+
+
+def test_geometric_edges_raises_no_pos():
+    G = nx.path_graph(3)
+    msg = "all nodes. must have a '"
+    with pytest.raises(nx.NetworkXError, match=msg):
+        nx.geometric_edges(G, radius=1)
+
+
+def test_number_of_nodes_S1():
+    G = nx.geometric_soft_configuration_graph(
+        beta=1.5, n=100, gamma=2.7, mean_degree=10, seed=42
+    )
+    assert len(G) == 100
+
+
+def test_set_attributes_S1():
+    G = nx.geometric_soft_configuration_graph(
+        beta=1.5, n=100, gamma=2.7, mean_degree=10, seed=42
+    )
+    kappas = nx.get_node_attributes(G, "kappa")
+    assert len(kappas) == 100
+    thetas = nx.get_node_attributes(G, "theta")
+    assert len(thetas) == 100
+    radii = nx.get_node_attributes(G, "radius")
+    assert len(radii) == 100
+
+
+def test_mean_kappas_mean_degree_S1():
+    G = nx.geometric_soft_configuration_graph(
+        beta=2.5, n=50, gamma=2.7, mean_degree=10, seed=8023
+    )
+
+    kappas = nx.get_node_attributes(G, "kappa")
+    mean_kappas = sum(kappas.values()) / len(kappas)
+    assert math.fabs(mean_kappas - 10) < 0.5
+
+    degrees = dict(G.degree())
+    mean_degree = sum(degrees.values()) / len(degrees)
+    assert math.fabs(mean_degree - 10) < 1
+
+
+def test_dict_kappas_S1():
+    kappas = {i: 10 for i in range(1000)}
+    G = nx.geometric_soft_configuration_graph(beta=1, kappas=kappas)
+    assert len(G) == 1000
+    kappas = nx.get_node_attributes(G, "kappa")
+    assert all(kappa == 10 for kappa in kappas.values())
+
+
+def test_beta_clustering_S1():
+    G1 = nx.geometric_soft_configuration_graph(
+        beta=1.5, n=100, gamma=3.5, mean_degree=10, seed=42
+    )
+    G2 = nx.geometric_soft_configuration_graph(
+        beta=3.0, n=100, gamma=3.5, mean_degree=10, seed=42
+    )
+    assert nx.average_clustering(G1) < nx.average_clustering(G2)
+
+
+def test_wrong_parameters_S1():
+    with pytest.raises(
+        nx.NetworkXError,
+        match="Please provide either kappas, or all 3 of: n, gamma and mean_degree.",
+    ):
+        G = nx.geometric_soft_configuration_graph(
+            beta=1.5, gamma=3.5, mean_degree=10, seed=42
+        )
+
+    with pytest.raises(
+        nx.NetworkXError,
+        match="When kappas is input, n, gamma and mean_degree must not be.",
+    ):
+        kappas = {i: 10 for i in range(1000)}
+        G = nx.geometric_soft_configuration_graph(
+            beta=1.5, kappas=kappas, gamma=2.3, seed=42
+        )
+
+    with pytest.raises(
+        nx.NetworkXError,
+        match="Please provide either kappas, or all 3 of: n, gamma and mean_degree.",
+    ):
+        G = nx.geometric_soft_configuration_graph(beta=1.5, seed=42)
+
+
+def test_negative_beta_S1():
+    with pytest.raises(
+        nx.NetworkXError, match="The parameter beta cannot be smaller or equal to 0."
+    ):
+        G = nx.geometric_soft_configuration_graph(
+            beta=-1, n=100, gamma=2.3, mean_degree=10, seed=42
+        )
+
+
+def test_non_zero_clustering_beta_lower_one_S1():
+    G = nx.geometric_soft_configuration_graph(
+        beta=0.5, n=100, gamma=3.5, mean_degree=10, seed=42
+    )
+    assert nx.average_clustering(G) > 0
+
+
+def test_mean_degree_influence_on_connectivity_S1():
+    low_mean_degree = 2
+    high_mean_degree = 20
+    G_low = nx.geometric_soft_configuration_graph(
+        beta=1.2, n=100, gamma=2.7, mean_degree=low_mean_degree, seed=42
+    )
+    G_high = nx.geometric_soft_configuration_graph(
+        beta=1.2, n=100, gamma=2.7, mean_degree=high_mean_degree, seed=42
+    )
+    assert nx.number_connected_components(G_low) > nx.number_connected_components(
+        G_high
+    )
+
+
+def test_compare_mean_kappas_different_gammas_S1():
+    G1 = nx.geometric_soft_configuration_graph(
+        beta=1.5, n=20, gamma=2.7, mean_degree=5, seed=42
+    )
+    G2 = nx.geometric_soft_configuration_graph(
+        beta=1.5, n=20, gamma=3.5, mean_degree=5, seed=42
+    )
+    kappas1 = nx.get_node_attributes(G1, "kappa")
+    mean_kappas1 = sum(kappas1.values()) / len(kappas1)
+    kappas2 = nx.get_node_attributes(G2, "kappa")
+    mean_kappas2 = sum(kappas2.values()) / len(kappas2)
+    assert math.fabs(mean_kappas1 - mean_kappas2) < 1
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_harary_graph.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_harary_graph.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a0142df2a4340bc81d7dc25f05ea5d57e8f2d16
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_harary_graph.py
@@ -0,0 +1,133 @@
+"""Unit tests for the :mod:`networkx.generators.harary_graph` module."""
+
+import pytest
+
+import networkx as nx
+from networkx.algorithms.isomorphism.isomorph import is_isomorphic
+from networkx.generators.harary_graph import hkn_harary_graph, hnm_harary_graph
+
+
+class TestHararyGraph:
+    """
+    Suppose n nodes, m >= n-1 edges, d = 2m // n, r = 2m % n
+    """
+
+    def test_hnm_harary_graph(self):
+        # When d is even and r = 0, the hnm_harary_graph(n,m) is
+        # the circulant_graph(n, list(range(1,d/2+1)))
+        for n, m in [(5, 5), (6, 12), (7, 14)]:
+            G1 = hnm_harary_graph(n, m)
+            d = 2 * m // n
+            G2 = nx.circulant_graph(n, list(range(1, d // 2 + 1)))
+            assert is_isomorphic(G1, G2)
+
+        # When d is even and r > 0, the hnm_harary_graph(n,m) is
+        # the circulant_graph(n, list(range(1,d/2+1)))
+        # with r edges added arbitrarily
+        for n, m in [(5, 7), (6, 13), (7, 16)]:
+            G1 = hnm_harary_graph(n, m)
+            d = 2 * m // n
+            G2 = nx.circulant_graph(n, list(range(1, d // 2 + 1)))
+            assert set(G2.edges) < set(G1.edges)
+            assert G1.number_of_edges() == m
+
+        # When d is odd and n is even and r = 0, the hnm_harary_graph(n,m)
+        # is the circulant_graph(n, list(range(1,(d+1)/2) plus [n//2])
+        for n, m in [(6, 9), (8, 12), (10, 15)]:
+            G1 = hnm_harary_graph(n, m)
+            d = 2 * m // n
+            L = list(range(1, (d + 1) // 2))
+            L.append(n // 2)
+            G2 = nx.circulant_graph(n, L)
+            assert is_isomorphic(G1, G2)
+
+        # When d is odd and n is even and r > 0, the hnm_harary_graph(n,m)
+        # is the circulant_graph(n, list(range(1,(d+1)/2) plus [n//2])
+        # with r edges added arbitrarily
+        for n, m in [(6, 10), (8, 13), (10, 17)]:
+            G1 = hnm_harary_graph(n, m)
+            d = 2 * m // n
+            L = list(range(1, (d + 1) // 2))
+            L.append(n // 2)
+            G2 = nx.circulant_graph(n, L)
+            assert set(G2.edges) < set(G1.edges)
+            assert G1.number_of_edges() == m
+
+        # When d is odd and n is odd, the hnm_harary_graph(n,m) is
+        # the circulant_graph(n, list(range(1,(d+1)/2))
+        # with m - n*(d-1)/2 edges added arbitrarily
+        for n, m in [(5, 4), (7, 12), (9, 14)]:
+            G1 = hnm_harary_graph(n, m)
+            d = 2 * m // n
+            L = list(range(1, (d + 1) // 2))
+            G2 = nx.circulant_graph(n, L)
+            assert set(G2.edges) < set(G1.edges)
+            assert G1.number_of_edges() == m
+
+        # Raise NetworkXError if n<1
+        n = 0
+        m = 0
+        pytest.raises(nx.NetworkXError, hnm_harary_graph, n, m)
+
+        # Raise NetworkXError if m < n-1
+        n = 6
+        m = 4
+        pytest.raises(nx.NetworkXError, hnm_harary_graph, n, m)
+
+        # Raise NetworkXError if m > n(n-1)/2
+        n = 6
+        m = 16
+        pytest.raises(nx.NetworkXError, hnm_harary_graph, n, m)
+
+    """
+        Suppose connectivity k, number of nodes n
+    """
+
+    def test_hkn_harary_graph(self):
+        # When k == 1, the hkn_harary_graph(k,n) is
+        # the path_graph(n)
+        for k, n in [(1, 6), (1, 7)]:
+            G1 = hkn_harary_graph(k, n)
+            G2 = nx.path_graph(n)
+            assert is_isomorphic(G1, G2)
+
+        # When k is even, the hkn_harary_graph(k,n) is
+        # the circulant_graph(n, list(range(1,k/2+1)))
+        for k, n in [(2, 6), (2, 7), (4, 6), (4, 7)]:
+            G1 = hkn_harary_graph(k, n)
+            G2 = nx.circulant_graph(n, list(range(1, k // 2 + 1)))
+            assert is_isomorphic(G1, G2)
+
+        # When k is odd and n is even, the hkn_harary_graph(k,n) is
+        # the circulant_graph(n, list(range(1,(k+1)/2)) plus [n/2])
+        for k, n in [(3, 6), (5, 8), (7, 10)]:
+            G1 = hkn_harary_graph(k, n)
+            L = list(range(1, (k + 1) // 2))
+            L.append(n // 2)
+            G2 = nx.circulant_graph(n, L)
+            assert is_isomorphic(G1, G2)
+
+        # When k is odd and n is odd, the hkn_harary_graph(k,n) is
+        # the circulant_graph(n, list(range(1,(k+1)/2))) with
+        # n//2+1 edges added between node i and node i+n//2+1
+        for k, n in [(3, 5), (5, 9), (7, 11)]:
+            G1 = hkn_harary_graph(k, n)
+            G2 = nx.circulant_graph(n, list(range(1, (k + 1) // 2)))
+            eSet1 = set(G1.edges)
+            eSet2 = set(G2.edges)
+            eSet3 = set()
+            half = n // 2
+            for i in range(half + 1):
+                # add half+1 edges between i and i+half
+                eSet3.add((i, (i + half) % n))
+            assert eSet1 == eSet2 | eSet3
+
+        # Raise NetworkXError if k<1
+        k = 0
+        n = 0
+        pytest.raises(nx.NetworkXError, hkn_harary_graph, k, n)
+
+        # Raise NetworkXError if ndegree_count[1]*degree_count[4]
+    joint_degrees_3 = {
+        1: {4: 2},
+        2: {2: 2, 3: 2, 4: 2},
+        3: {2: 2, 4: 1},
+        4: {1: 2, 2: 2, 3: 1},
+    }
+    assert not is_valid_joint_degree(joint_degrees_3)
+
+    # test condition 5
+    # joint_degrees_5[1][1] not even
+    joint_degrees_5 = {1: {1: 9}}
+    assert not is_valid_joint_degree(joint_degrees_5)
+
+
+def test_joint_degree_graph(ntimes=10):
+    for _ in range(ntimes):
+        seed = int(time.time())
+
+        n, m, p = 20, 10, 1
+        # generate random graph with model powerlaw_cluster and calculate
+        # its joint degree
+        g = powerlaw_cluster_graph(n, m, p, seed=seed)
+        joint_degrees_g = degree_mixing_dict(g, normalized=False)
+
+        # generate simple undirected graph with given joint degree
+        # joint_degrees_g
+        G = joint_degree_graph(joint_degrees_g)
+        joint_degrees_G = degree_mixing_dict(G, normalized=False)
+
+        # assert that the given joint degree is equal to the generated
+        # graph's joint degree
+        assert joint_degrees_g == joint_degrees_G
+
+
+def test_is_valid_directed_joint_degree():
+    in_degrees = [0, 1, 1, 2]
+    out_degrees = [1, 1, 1, 1]
+    nkk = {1: {1: 2, 2: 2}}
+    assert is_valid_directed_joint_degree(in_degrees, out_degrees, nkk)
+
+    # not realizable, values are not integers.
+    nkk = {1: {1: 1.5, 2: 2.5}}
+    assert not is_valid_directed_joint_degree(in_degrees, out_degrees, nkk)
+
+    # not realizable, number of edges between 1-2 are insufficient.
+    nkk = {1: {1: 2, 2: 1}}
+    assert not is_valid_directed_joint_degree(in_degrees, out_degrees, nkk)
+
+    # not realizable, in/out degree sequences have different number of nodes.
+    out_degrees = [1, 1, 1]
+    nkk = {1: {1: 2, 2: 2}}
+    assert not is_valid_directed_joint_degree(in_degrees, out_degrees, nkk)
+
+    # not realizable, degree sequences have fewer than required nodes.
+    in_degrees = [0, 1, 2]
+    assert not is_valid_directed_joint_degree(in_degrees, out_degrees, nkk)
+
+
+def test_directed_joint_degree_graph(n=15, m=100, ntimes=1000):
+    for _ in range(ntimes):
+        # generate gnm random graph and calculate its joint degree.
+        g = gnm_random_graph(n, m, None, directed=True)
+
+        # in-degree sequence of g as a list of integers.
+        in_degrees = list(dict(g.in_degree()).values())
+        # out-degree sequence of g as a list of integers.
+        out_degrees = list(dict(g.out_degree()).values())
+        nkk = degree_mixing_dict(g)
+
+        # generate simple directed graph with given degree sequence and joint
+        # degree matrix.
+        G = directed_joint_degree_graph(in_degrees, out_degrees, nkk)
+
+        # assert degree sequence correctness.
+        assert in_degrees == list(dict(G.in_degree()).values())
+        assert out_degrees == list(dict(G.out_degree()).values())
+        # assert joint degree matrix correctness.
+        assert nkk == degree_mixing_dict(G)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_lattice.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_lattice.py
new file mode 100644
index 0000000000000000000000000000000000000000..10ac9fc7f0b7ed74c69859ad323b9fbe33a0a460
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_lattice.py
@@ -0,0 +1,264 @@
+"""Unit tests for the :mod:`networkx.generators.lattice` module."""
+
+from itertools import product
+
+import pytest
+
+import networkx as nx
+from networkx.utils import edges_equal
+
+
+def test_hexagonal_lattice_no_pos():
+    # Test positions are note computed/stored when with_positions=False
+    G = nx.hexagonal_lattice_graph(6, 6, with_positions=False)
+    assert all(pos is None for _, pos in G.nodes(data="pos"))
+
+
+@pytest.mark.parametrize(
+    "lattice_graph", (nx.triangular_lattice_graph, nx.hexagonal_lattice_graph)
+)
+def test_2D_lattice_no_contraction_leftovers(lattice_graph):
+    """hexagonal_lattice_graph and triangular_lattice_graph use nx.contracted_nodes
+    under-the-hood when periodic=True. Check that there are no leftover
+    "contraction" node attributes on the returned graph."""
+    G = lattice_graph(6, 6, with_positions=False, periodic=True)
+    assert all(data == {} for _, data in G.nodes(data=True))
+    assert all(data == {} for _, _, data in G.edges(data=True))
+
+
+class TestGrid2DGraph:
+    """Unit tests for :func:`networkx.generators.lattice.grid_2d_graph`"""
+
+    def test_number_of_vertices(self):
+        m, n = 5, 6
+        G = nx.grid_2d_graph(m, n)
+        assert len(G) == m * n
+
+    def test_degree_distribution(self):
+        m, n = 5, 6
+        G = nx.grid_2d_graph(m, n)
+        expected_histogram = [0, 0, 4, 2 * (m + n) - 8, (m - 2) * (n - 2)]
+        assert nx.degree_histogram(G) == expected_histogram
+
+    def test_directed(self):
+        m, n = 5, 6
+        G = nx.grid_2d_graph(m, n)
+        H = nx.grid_2d_graph(m, n, create_using=nx.DiGraph())
+        assert H.succ == G.adj
+        assert H.pred == G.adj
+
+    def test_multigraph(self):
+        m, n = 5, 6
+        G = nx.grid_2d_graph(m, n)
+        H = nx.grid_2d_graph(m, n, create_using=nx.MultiGraph())
+        assert list(H.edges()) == list(G.edges())
+
+    def test_periodic(self):
+        G = nx.grid_2d_graph(0, 0, periodic=True)
+        assert dict(G.degree()) == {}
+
+        for m, n, H in [
+            (2, 2, nx.cycle_graph(4)),
+            (1, 7, nx.cycle_graph(7)),
+            (7, 1, nx.cycle_graph(7)),
+            (2, 5, nx.circular_ladder_graph(5)),
+            (5, 2, nx.circular_ladder_graph(5)),
+            (2, 4, nx.cubical_graph()),
+            (4, 2, nx.cubical_graph()),
+        ]:
+            G = nx.grid_2d_graph(m, n, periodic=True)
+            assert nx.could_be_isomorphic(G, H)
+
+    def test_periodic_iterable(self):
+        m, n = 3, 7
+        for a, b in product([0, 1], [0, 1]):
+            G = nx.grid_2d_graph(m, n, periodic=(a, b))
+            assert G.number_of_nodes() == m * n
+            assert G.number_of_edges() == (m + a - 1) * n + (n + b - 1) * m
+
+    def test_periodic_directed(self):
+        G = nx.grid_2d_graph(4, 2, periodic=True)
+        H = nx.grid_2d_graph(4, 2, periodic=True, create_using=nx.DiGraph())
+        assert H.succ == G.adj
+        assert H.pred == G.adj
+
+    def test_periodic_multigraph(self):
+        G = nx.grid_2d_graph(4, 2, periodic=True)
+        H = nx.grid_2d_graph(4, 2, periodic=True, create_using=nx.MultiGraph())
+        assert list(G.edges()) == list(H.edges())
+
+    def test_exceptions(self):
+        pytest.raises(nx.NetworkXError, nx.grid_2d_graph, -3, 2)
+        pytest.raises(nx.NetworkXError, nx.grid_2d_graph, 3, -2)
+        pytest.raises(TypeError, nx.grid_2d_graph, 3.3, 2)
+        pytest.raises(TypeError, nx.grid_2d_graph, 3, 2.2)
+
+    def test_node_input(self):
+        G = nx.grid_2d_graph(4, 2, periodic=True)
+        H = nx.grid_2d_graph(range(4), range(2), periodic=True)
+        assert nx.is_isomorphic(H, G)
+        H = nx.grid_2d_graph("abcd", "ef", periodic=True)
+        assert nx.is_isomorphic(H, G)
+        G = nx.grid_2d_graph(5, 6)
+        H = nx.grid_2d_graph(range(5), range(6))
+        assert edges_equal(H, G)
+
+
+class TestGridGraph:
+    """Unit tests for :func:`networkx.generators.lattice.grid_graph`"""
+
+    def test_grid_graph(self):
+        """grid_graph([n,m]) is a connected simple graph with the
+        following properties:
+        number_of_nodes = n*m
+        degree_histogram = [0,0,4,2*(n+m)-8,(n-2)*(m-2)]
+        """
+        for n, m in [(3, 5), (5, 3), (4, 5), (5, 4)]:
+            dim = [n, m]
+            g = nx.grid_graph(dim)
+            assert len(g) == n * m
+            assert nx.degree_histogram(g) == [
+                0,
+                0,
+                4,
+                2 * (n + m) - 8,
+                (n - 2) * (m - 2),
+            ]
+
+        for n, m in [(1, 5), (5, 1)]:
+            dim = [n, m]
+            g = nx.grid_graph(dim)
+            assert len(g) == n * m
+            assert nx.is_isomorphic(g, nx.path_graph(5))
+
+    #        mg = nx.grid_graph([n,m], create_using=MultiGraph())
+    #        assert_equal(mg.edges(), g.edges())
+
+    def test_node_input(self):
+        G = nx.grid_graph([range(7, 9), range(3, 6)])
+        assert len(G) == 2 * 3
+        assert nx.is_isomorphic(G, nx.grid_graph([2, 3]))
+
+    def test_periodic_iterable(self):
+        m, n, k = 3, 7, 5
+        for a, b, c in product([0, 1], [0, 1], [0, 1]):
+            G = nx.grid_graph([m, n, k], periodic=(a, b, c))
+            num_e = (m + a - 1) * n * k + (n + b - 1) * m * k + (k + c - 1) * m * n
+            assert G.number_of_nodes() == m * n * k
+            assert G.number_of_edges() == num_e
+
+
+class TestHypercubeGraph:
+    """Unit tests for :func:`networkx.generators.lattice.hypercube_graph`"""
+
+    def test_special_cases(self):
+        for n, H in [
+            (0, nx.null_graph()),
+            (1, nx.path_graph(2)),
+            (2, nx.cycle_graph(4)),
+            (3, nx.cubical_graph()),
+        ]:
+            G = nx.hypercube_graph(n)
+            assert nx.could_be_isomorphic(G, H)
+
+    def test_degree_distribution(self):
+        for n in range(1, 10):
+            G = nx.hypercube_graph(n)
+            expected_histogram = [0] * n + [2**n]
+            assert nx.degree_histogram(G) == expected_histogram
+
+
+class TestTriangularLatticeGraph:
+    "Tests for :func:`networkx.generators.lattice.triangular_lattice_graph`"
+
+    def test_lattice_points(self):
+        """Tests that the graph is really a triangular lattice."""
+        for m, n in [(2, 3), (2, 2), (2, 1), (3, 3), (3, 2), (3, 4)]:
+            G = nx.triangular_lattice_graph(m, n)
+            N = (n + 1) // 2
+            assert len(G) == (m + 1) * (1 + N) - (n % 2) * ((m + 1) // 2)
+        for i, j in G.nodes():
+            nbrs = G[(i, j)]
+            if i < N:
+                assert (i + 1, j) in nbrs
+            if j < m:
+                assert (i, j + 1) in nbrs
+            if j < m and (i > 0 or j % 2) and (i < N or (j + 1) % 2):
+                assert (i + 1, j + 1) in nbrs or (i - 1, j + 1) in nbrs
+
+    def test_directed(self):
+        """Tests for creating a directed triangular lattice."""
+        G = nx.triangular_lattice_graph(3, 4, create_using=nx.Graph())
+        H = nx.triangular_lattice_graph(3, 4, create_using=nx.DiGraph())
+        assert H.is_directed()
+        for u, v in H.edges():
+            assert v[1] >= u[1]
+            if v[1] == u[1]:
+                assert v[0] > u[0]
+
+    def test_multigraph(self):
+        """Tests for creating a triangular lattice multigraph."""
+        G = nx.triangular_lattice_graph(3, 4, create_using=nx.Graph())
+        H = nx.triangular_lattice_graph(3, 4, create_using=nx.MultiGraph())
+        assert list(H.edges()) == list(G.edges())
+
+    def test_periodic(self):
+        G = nx.triangular_lattice_graph(4, 6, periodic=True)
+        assert len(G) == 12
+        assert G.size() == 36
+        # all degrees are 6
+        assert len([n for n, d in G.degree() if d != 6]) == 0
+        G = nx.triangular_lattice_graph(5, 7, periodic=True)
+        TLG = nx.triangular_lattice_graph
+        pytest.raises(nx.NetworkXError, TLG, 2, 4, periodic=True)
+        pytest.raises(nx.NetworkXError, TLG, 4, 4, periodic=True)
+        pytest.raises(nx.NetworkXError, TLG, 2, 6, periodic=True)
+
+
+class TestHexagonalLatticeGraph:
+    "Tests for :func:`networkx.generators.lattice.hexagonal_lattice_graph`"
+
+    def test_lattice_points(self):
+        """Tests that the graph is really a hexagonal lattice."""
+        for m, n in [(4, 5), (4, 4), (4, 3), (3, 2), (3, 3), (3, 5)]:
+            G = nx.hexagonal_lattice_graph(m, n)
+            assert len(G) == 2 * (m + 1) * (n + 1) - 2
+        C_6 = nx.cycle_graph(6)
+        hexagons = [
+            [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)],
+            [(0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4)],
+            [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)],
+            [(2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (3, 2)],
+            [(2, 2), (2, 3), (2, 4), (3, 2), (3, 3), (3, 4)],
+        ]
+        for hexagon in hexagons:
+            assert nx.is_isomorphic(G.subgraph(hexagon), C_6)
+
+    def test_directed(self):
+        """Tests for creating a directed hexagonal lattice."""
+        G = nx.hexagonal_lattice_graph(3, 5, create_using=nx.Graph())
+        H = nx.hexagonal_lattice_graph(3, 5, create_using=nx.DiGraph())
+        assert H.is_directed()
+        pos = nx.get_node_attributes(H, "pos")
+        for u, v in H.edges():
+            assert pos[v][1] >= pos[u][1]
+            if pos[v][1] == pos[u][1]:
+                assert pos[v][0] > pos[u][0]
+
+    def test_multigraph(self):
+        """Tests for creating a hexagonal lattice multigraph."""
+        G = nx.hexagonal_lattice_graph(3, 5, create_using=nx.Graph())
+        H = nx.hexagonal_lattice_graph(3, 5, create_using=nx.MultiGraph())
+        assert list(H.edges()) == list(G.edges())
+
+    def test_periodic(self):
+        G = nx.hexagonal_lattice_graph(4, 6, periodic=True)
+        assert len(G) == 48
+        assert G.size() == 72
+        # all degrees are 3
+        assert len([n for n, d in G.degree() if d != 3]) == 0
+        G = nx.hexagonal_lattice_graph(5, 8, periodic=True)
+        HLG = nx.hexagonal_lattice_graph
+        pytest.raises(nx.NetworkXError, HLG, 2, 7, periodic=True)
+        pytest.raises(nx.NetworkXError, HLG, 1, 4, periodic=True)
+        pytest.raises(nx.NetworkXError, HLG, 2, 1, periodic=True)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_line.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_line.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b3ff079e0a9bf7ac2233e0cac7f47d9e7d7ea04
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_line.py
@@ -0,0 +1,316 @@
+import pytest
+
+import networkx as nx
+from networkx.generators import line
+from networkx.utils import edges_equal
+
+
+class TestGeneratorLine:
+    def test_star(self):
+        G = nx.star_graph(5)
+        L = nx.line_graph(G)
+        assert nx.is_isomorphic(L, nx.complete_graph(5))
+
+    def test_path(self):
+        G = nx.path_graph(5)
+        L = nx.line_graph(G)
+        assert nx.is_isomorphic(L, nx.path_graph(4))
+
+    def test_cycle(self):
+        G = nx.cycle_graph(5)
+        L = nx.line_graph(G)
+        assert nx.is_isomorphic(L, G)
+
+    def test_digraph1(self):
+        G = nx.DiGraph([(0, 1), (0, 2), (0, 3)])
+        L = nx.line_graph(G)
+        # no edge graph, but with nodes
+        assert L.adj == {(0, 1): {}, (0, 2): {}, (0, 3): {}}
+
+    def test_multigraph1(self):
+        G = nx.MultiGraph([(0, 1), (0, 1), (1, 0), (0, 2), (2, 0), (0, 3)])
+        L = nx.line_graph(G)
+        # no edge graph, but with nodes
+        assert edges_equal(
+            L.edges(),
+            [
+                ((0, 3, 0), (0, 1, 0)),
+                ((0, 3, 0), (0, 2, 0)),
+                ((0, 3, 0), (0, 2, 1)),
+                ((0, 3, 0), (0, 1, 1)),
+                ((0, 3, 0), (0, 1, 2)),
+                ((0, 1, 0), (0, 1, 1)),
+                ((0, 1, 0), (0, 2, 0)),
+                ((0, 1, 0), (0, 1, 2)),
+                ((0, 1, 0), (0, 2, 1)),
+                ((0, 1, 1), (0, 1, 2)),
+                ((0, 1, 1), (0, 2, 0)),
+                ((0, 1, 1), (0, 2, 1)),
+                ((0, 1, 2), (0, 2, 0)),
+                ((0, 1, 2), (0, 2, 1)),
+                ((0, 2, 0), (0, 2, 1)),
+            ],
+        )
+
+    def test_multigraph2(self):
+        G = nx.MultiGraph([(1, 2), (2, 1)])
+        L = nx.line_graph(G)
+        assert edges_equal(L.edges(), [((1, 2, 0), (1, 2, 1))])
+
+    def test_multidigraph1(self):
+        G = nx.MultiDiGraph([(1, 2), (2, 1)])
+        L = nx.line_graph(G)
+        assert edges_equal(
+            L.edges(), [((1, 2, 0), (2, 1, 0)), ((2, 1, 0), (1, 2, 0))], directed=True
+        )
+
+    def test_multidigraph2(self):
+        G = nx.MultiDiGraph([(0, 1), (0, 1), (0, 1), (1, 2)])
+        L = nx.line_graph(G)
+        assert edges_equal(
+            L.edges(),
+            [((0, 1, 0), (1, 2, 0)), ((0, 1, 1), (1, 2, 0)), ((0, 1, 2), (1, 2, 0))],
+            directed=True,
+        )
+
+    def test_digraph2(self):
+        G = nx.DiGraph([(0, 1), (1, 2), (2, 3)])
+        L = nx.line_graph(G)
+        assert edges_equal(
+            L.edges(), [((0, 1), (1, 2)), ((1, 2), (2, 3))], directed=True
+        )
+
+    def test_create1(self):
+        G = nx.DiGraph([(0, 1), (1, 2), (2, 3)])
+        L = nx.line_graph(G, create_using=nx.Graph())
+        assert edges_equal(L.edges(), [((0, 1), (1, 2)), ((1, 2), (2, 3))])
+
+    def test_create2(self):
+        G = nx.Graph([(0, 1), (1, 2), (2, 3)])
+        L = nx.line_graph(G, create_using=nx.DiGraph())
+        assert edges_equal(
+            L.edges(), [((0, 1), (1, 2)), ((1, 2), (2, 3))], directed=True
+        )
+
+
+class TestGeneratorInverseLine:
+    def test_example(self):
+        G = nx.Graph()
+        G_edges = [
+            [1, 2],
+            [1, 3],
+            [1, 4],
+            [1, 5],
+            [2, 3],
+            [2, 5],
+            [2, 6],
+            [2, 7],
+            [3, 4],
+            [3, 5],
+            [6, 7],
+            [6, 8],
+            [7, 8],
+        ]
+        G.add_edges_from(G_edges)
+        H = nx.inverse_line_graph(G)
+        solution = nx.Graph()
+        solution_edges = [
+            ("a", "b"),
+            ("a", "c"),
+            ("a", "d"),
+            ("a", "e"),
+            ("c", "d"),
+            ("e", "f"),
+            ("e", "g"),
+            ("f", "g"),
+        ]
+        solution.add_edges_from(solution_edges)
+        assert nx.is_isomorphic(H, solution)
+
+    def test_example_2(self):
+        G = nx.Graph()
+        G_edges = [[1, 2], [1, 3], [2, 3], [3, 4], [3, 5], [4, 5]]
+        G.add_edges_from(G_edges)
+        H = nx.inverse_line_graph(G)
+        solution = nx.Graph()
+        solution_edges = [("a", "c"), ("b", "c"), ("c", "d"), ("d", "e"), ("d", "f")]
+        solution.add_edges_from(solution_edges)
+        assert nx.is_isomorphic(H, solution)
+
+    def test_pair(self):
+        G = nx.path_graph(2)
+        H = nx.inverse_line_graph(G)
+        solution = nx.path_graph(3)
+        assert nx.is_isomorphic(H, solution)
+
+    def test_line(self):
+        G = nx.path_graph(5)
+        solution = nx.path_graph(6)
+        H = nx.inverse_line_graph(G)
+        assert nx.is_isomorphic(H, solution)
+
+    def test_triangle_graph(self):
+        G = nx.complete_graph(3)
+        H = nx.inverse_line_graph(G)
+        alternative_solution = nx.Graph()
+        alternative_solution.add_edges_from([[0, 1], [0, 2], [0, 3]])
+        # there are two alternative inverse line graphs for this case
+        # so long as we get one of them the test should pass
+        assert nx.is_isomorphic(H, G) or nx.is_isomorphic(H, alternative_solution)
+
+    def test_cycle(self):
+        G = nx.cycle_graph(5)
+        H = nx.inverse_line_graph(G)
+        assert nx.is_isomorphic(H, G)
+
+    def test_empty(self):
+        G = nx.Graph()
+        H = nx.inverse_line_graph(G)
+        assert nx.is_isomorphic(H, nx.complete_graph(1))
+
+    def test_K1(self):
+        G = nx.complete_graph(1)
+        H = nx.inverse_line_graph(G)
+        solution = nx.path_graph(2)
+        assert nx.is_isomorphic(H, solution)
+
+    def test_edgeless_graph(self):
+        G = nx.empty_graph(5)
+        with pytest.raises(nx.NetworkXError, match="edgeless graph"):
+            nx.inverse_line_graph(G)
+
+    def test_selfloops_error(self):
+        G = nx.cycle_graph(4)
+        G.add_edge(0, 0)
+        pytest.raises(nx.NetworkXError, nx.inverse_line_graph, G)
+
+    def test_non_line_graphs(self):
+        # Tests several known non-line graphs for impossibility
+        # Adapted from L.W.Beineke, "Characterizations of derived graphs"
+
+        # claw graph
+        claw = nx.star_graph(3)
+        pytest.raises(nx.NetworkXError, nx.inverse_line_graph, claw)
+
+        # wheel graph with 6 nodes
+        wheel = nx.wheel_graph(6)
+        pytest.raises(nx.NetworkXError, nx.inverse_line_graph, wheel)
+
+        # K5 with one edge remove
+        K5m = nx.complete_graph(5)
+        K5m.remove_edge(0, 1)
+        pytest.raises(nx.NetworkXError, nx.inverse_line_graph, K5m)
+
+        # graph without any odd triangles (contains claw as induced subgraph)
+        G = nx.compose(nx.path_graph(2), nx.complete_bipartite_graph(2, 3))
+        pytest.raises(nx.NetworkXError, nx.inverse_line_graph, G)
+
+        ## Variations on a diamond graph
+
+        # Diamond + 2 edges (+ "roof")
+        G = nx.diamond_graph()
+        G.add_edges_from([(4, 0), (5, 3)])
+        pytest.raises(nx.NetworkXError, nx.inverse_line_graph, G)
+        G.add_edge(4, 5)
+        pytest.raises(nx.NetworkXError, nx.inverse_line_graph, G)
+
+        # Diamond + 2 connected edges
+        G = nx.diamond_graph()
+        G.add_edges_from([(4, 0), (4, 3)])
+        pytest.raises(nx.NetworkXError, nx.inverse_line_graph, G)
+
+        # Diamond + K3 + one edge (+ 2*K3)
+        G = nx.diamond_graph()
+        G.add_edges_from([(4, 0), (4, 1), (4, 2), (5, 3)])
+        pytest.raises(nx.NetworkXError, nx.inverse_line_graph, G)
+        G.add_edges_from([(5, 1), (5, 2)])
+        pytest.raises(nx.NetworkXError, nx.inverse_line_graph, G)
+
+        # 4 triangles
+        G = nx.diamond_graph()
+        G.add_edges_from([(4, 0), (4, 1), (5, 2), (5, 3)])
+        pytest.raises(nx.NetworkXError, nx.inverse_line_graph, G)
+
+    def test_wrong_graph_type(self):
+        G = nx.DiGraph()
+        G_edges = [[0, 1], [0, 2], [0, 3]]
+        G.add_edges_from(G_edges)
+        pytest.raises(nx.NetworkXNotImplemented, nx.inverse_line_graph, G)
+
+        G = nx.MultiGraph()
+        G_edges = [[0, 1], [0, 2], [0, 3]]
+        G.add_edges_from(G_edges)
+        pytest.raises(nx.NetworkXNotImplemented, nx.inverse_line_graph, G)
+
+    def test_line_inverse_line_complete(self):
+        G = nx.complete_graph(10)
+        H = nx.line_graph(G)
+        J = nx.inverse_line_graph(H)
+        assert nx.is_isomorphic(G, J)
+
+    def test_line_inverse_line_path(self):
+        G = nx.path_graph(10)
+        H = nx.line_graph(G)
+        J = nx.inverse_line_graph(H)
+        assert nx.is_isomorphic(G, J)
+
+    def test_line_inverse_line_hypercube(self):
+        G = nx.hypercube_graph(5)
+        H = nx.line_graph(G)
+        J = nx.inverse_line_graph(H)
+        assert nx.is_isomorphic(G, J)
+
+    def test_line_inverse_line_cycle(self):
+        G = nx.cycle_graph(10)
+        H = nx.line_graph(G)
+        J = nx.inverse_line_graph(H)
+        assert nx.is_isomorphic(G, J)
+
+    def test_line_inverse_line_star(self):
+        G = nx.star_graph(20)
+        H = nx.line_graph(G)
+        J = nx.inverse_line_graph(H)
+        assert nx.is_isomorphic(G, J)
+
+    def test_line_inverse_line_multipartite(self):
+        G = nx.complete_multipartite_graph(3, 4, 5)
+        H = nx.line_graph(G)
+        J = nx.inverse_line_graph(H)
+        assert nx.is_isomorphic(G, J)
+
+    def test_line_inverse_line_dgm(self):
+        G = nx.dorogovtsev_goltsev_mendes_graph(4)
+        H = nx.line_graph(G)
+        J = nx.inverse_line_graph(H)
+        assert nx.is_isomorphic(G, J)
+
+    def test_line_different_node_types(self):
+        G = nx.path_graph([1, 2, 3, "a", "b", "c"])
+        H = nx.line_graph(G)
+        J = nx.inverse_line_graph(H)
+        assert nx.is_isomorphic(G, J)
+
+
+class TestGeneratorPrivateFunctions:
+    def test_triangles_error(self):
+        G = nx.diamond_graph()
+        pytest.raises(nx.NetworkXError, line._triangles, G, (4, 0))
+        pytest.raises(nx.NetworkXError, line._triangles, G, (0, 3))
+
+    def test_odd_triangles_error(self):
+        G = nx.diamond_graph()
+        pytest.raises(nx.NetworkXError, line._odd_triangle, G, (0, 1, 4))
+        pytest.raises(nx.NetworkXError, line._odd_triangle, G, (0, 1, 3))
+
+    def test_select_starting_cell_error(self):
+        G = nx.diamond_graph()
+        pytest.raises(nx.NetworkXError, line._select_starting_cell, G, (4, 0))
+        pytest.raises(nx.NetworkXError, line._select_starting_cell, G, (0, 3))
+
+    def test_diamond_graph(self):
+        G = nx.diamond_graph()
+        for edge in G.edges:
+            cell = line._select_starting_cell(G, starting_edge=edge)
+            # Starting cell should always be one of the two triangles
+            assert len(cell) == 3
+            assert all(v in G[u] for u in cell for v in cell if u != v)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_mycielski.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_mycielski.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb12b1412ad4559bb500a7125c8d65e6239c5fed
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_mycielski.py
@@ -0,0 +1,30 @@
+"""Unit tests for the :mod:`networkx.generators.mycielski` module."""
+
+import pytest
+
+import networkx as nx
+
+
+class TestMycielski:
+    def test_construction(self):
+        G = nx.path_graph(2)
+        M = nx.mycielskian(G)
+        assert nx.is_isomorphic(M, nx.cycle_graph(5))
+
+    def test_size(self):
+        G = nx.path_graph(2)
+        M = nx.mycielskian(G, 2)
+        assert len(M) == 11
+        assert M.size() == 20
+
+    def test_mycielski_graph_generator(self):
+        G = nx.mycielski_graph(1)
+        assert nx.is_isomorphic(G, nx.empty_graph(1))
+        G = nx.mycielski_graph(2)
+        assert nx.is_isomorphic(G, nx.path_graph(2))
+        G = nx.mycielski_graph(3)
+        assert nx.is_isomorphic(G, nx.cycle_graph(5))
+        G = nx.mycielski_graph(4)
+        assert nx.is_isomorphic(G, nx.mycielskian(nx.cycle_graph(5)))
+        with pytest.raises(nx.NetworkXError, match="must satisfy n >= 1"):
+            nx.mycielski_graph(0)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_nonisomorphic_trees.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_nonisomorphic_trees.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c09303cc98f329084160733e8004fbe2710255f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_nonisomorphic_trees.py
@@ -0,0 +1,82 @@
+"""
+Unit tests for WROM algorithm generator in generators/nonisomorphic_trees.py
+"""
+
+import pytest
+
+import networkx as nx
+from networkx.utils import edges_equal
+
+
+def test_nonisomorphic_tree_negative_order():
+    with pytest.raises(ValueError, match="order must be non-negative"):
+        nx.number_of_nonisomorphic_trees(-1)
+    with pytest.raises(ValueError, match="order must be non-negative"):
+        next(nx.nonisomorphic_trees(-1))
+
+
+def test_nonisomorphic_tree_order_0():
+    assert nx.number_of_nonisomorphic_trees(0) == 0
+    assert list(nx.nonisomorphic_trees(0)) == []
+
+
+def test_nonisomorphic_tree_order_1():
+    assert nx.number_of_nonisomorphic_trees(1) == 1
+    nit_list = list(nx.nonisomorphic_trees(1))
+    assert len(nit_list) == 1
+    G = nit_list[0]
+    assert nx.utils.graphs_equal(G, nx.empty_graph(1))
+
+
+@pytest.mark.parametrize("n", range(5))
+def test_nonisomorphic_tree_low_order_agreement(n):
+    """Ensure all the order<2 'special cases' are consistent."""
+    assert len(list(nx.nonisomorphic_trees(n))) == nx.number_of_nonisomorphic_trees(n)
+
+
+class TestGeneratorNonIsomorphicTrees:
+    def test_tree_structure(self):
+        # test for tree structure for nx.nonisomorphic_trees()
+        def f(x):
+            return list(nx.nonisomorphic_trees(x))
+
+        for i in f(6):
+            assert nx.is_tree(i)
+        for i in f(8):
+            assert nx.is_tree(i)
+
+    def test_nonisomorphism(self):
+        # test for nonisomorphism of trees for nx.nonisomorphic_trees()
+        def f(x):
+            return list(nx.nonisomorphic_trees(x))
+
+        trees = f(6)
+        for i in range(len(trees)):
+            for j in range(i + 1, len(trees)):
+                assert not nx.is_isomorphic(trees[i], trees[j])
+        trees = f(8)
+        for i in range(len(trees)):
+            for j in range(i + 1, len(trees)):
+                assert not nx.is_isomorphic(trees[i], trees[j])
+
+    def test_number_of_nonisomorphic_trees(self):
+        # http://oeis.org/A000055
+        assert nx.number_of_nonisomorphic_trees(2) == 1
+        assert nx.number_of_nonisomorphic_trees(3) == 1
+        assert nx.number_of_nonisomorphic_trees(4) == 2
+        assert nx.number_of_nonisomorphic_trees(5) == 3
+        assert nx.number_of_nonisomorphic_trees(6) == 6
+        assert nx.number_of_nonisomorphic_trees(7) == 11
+        assert nx.number_of_nonisomorphic_trees(8) == 23
+        assert nx.number_of_nonisomorphic_trees(9) == 47
+        assert nx.number_of_nonisomorphic_trees(10) == 106
+        assert nx.number_of_nonisomorphic_trees(20) == 823065
+        assert nx.number_of_nonisomorphic_trees(30) == 14830871802
+
+    def test_nonisomorphic_trees(self):
+        def f(x):
+            return list(nx.nonisomorphic_trees(x))
+
+        assert edges_equal(f(3)[0].edges(), [(0, 1), (0, 2)])
+        assert edges_equal(f(4)[0].edges(), [(0, 1), (0, 3), (1, 2)])
+        assert edges_equal(f(4)[1].edges(), [(0, 1), (0, 2), (0, 3)])
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_random_clustered.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_random_clustered.py
new file mode 100644
index 0000000000000000000000000000000000000000..85066520ae59f1e9bec03327630276918d573fb2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_random_clustered.py
@@ -0,0 +1,33 @@
+import pytest
+
+import networkx as nx
+
+
+class TestRandomClusteredGraph:
+    def test_custom_joint_degree_sequence(self):
+        node = [1, 1, 1, 2, 1, 2, 0, 0]
+        tri = [0, 0, 0, 0, 0, 1, 1, 1]
+        joint_degree_sequence = zip(node, tri)
+        G = nx.random_clustered_graph(joint_degree_sequence)
+        assert G.number_of_nodes() == 8
+        assert G.number_of_edges() == 7
+
+    def test_tuple_joint_degree_sequence(self):
+        G = nx.random_clustered_graph([(1, 2), (2, 1), (1, 1), (1, 1), (1, 1), (2, 0)])
+        assert G.number_of_nodes() == 6
+        assert G.number_of_edges() == 10
+
+    def test_invalid_joint_degree_sequence_type(self):
+        with pytest.raises(nx.NetworkXError, match="Invalid degree sequence"):
+            nx.random_clustered_graph([[1, 1], [2, 1], [0, 1]])
+
+    def test_invalid_joint_degree_sequence_value(self):
+        with pytest.raises(nx.NetworkXError, match="Invalid degree sequence"):
+            nx.random_clustered_graph([[1, 1], [1, 2], [0, 1]])
+
+    def test_directed_graph_raises_error(self):
+        with pytest.raises(nx.NetworkXError, match="Directed Graph not supported"):
+            nx.random_clustered_graph(
+                [(1, 2), (2, 1), (1, 1), (1, 1), (1, 1), (2, 0)],
+                create_using=nx.DiGraph,
+            )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_random_graphs.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_random_graphs.py
new file mode 100644
index 0000000000000000000000000000000000000000..db8d6996fd4c501100818aa7a7a71c5d2207d3d2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_random_graphs.py
@@ -0,0 +1,495 @@
+"""Unit tests for the :mod:`networkx.generators.random_graphs` module."""
+
+import pytest
+
+import networkx as nx
+
+_gnp_generators = [
+    nx.gnp_random_graph,
+    nx.fast_gnp_random_graph,
+    nx.binomial_graph,
+    nx.erdos_renyi_graph,
+]
+
+
+@pytest.mark.parametrize("generator", _gnp_generators)
+@pytest.mark.parametrize("directed", (True, False))
+def test_gnp_generators_negative_edge_probability(generator, directed):
+    """If the edge probability `p` is <=0, the resulting graph should have no edges."""
+    G = generator(10, -1.1, directed=directed)
+    assert len(G) == 10
+    assert G.number_of_edges() == 0
+    assert G.is_directed() == directed
+
+
+@pytest.mark.parametrize("generator", _gnp_generators)
+@pytest.mark.parametrize(
+    ("directed", "expected_num_edges"),
+    [(False, 45), (True, 90)],
+)
+def test_gnp_generators_greater_than_1_edge_probability(
+    generator, directed, expected_num_edges
+):
+    """If the edge probability `p` is >=1, the resulting graph should be complete."""
+    G = generator(10, 1.1, directed=directed)
+    assert len(G) == 10
+    assert G.number_of_edges() == expected_num_edges
+    assert G.is_directed() == directed
+
+
+@pytest.mark.parametrize("generator", _gnp_generators)
+@pytest.mark.parametrize("directed", (True, False))
+def test_gnp_generators_basic(generator, directed):
+    """If the edge probability `p` is >0 and <1, test only the basic properties."""
+    G = generator(10, 0.1, directed=directed)
+    assert len(G) == 10
+    assert G.is_directed() == directed
+
+
+@pytest.mark.parametrize("generator", _gnp_generators)
+def test_gnp_generators_for_p_close_to_1(generator):
+    """If the edge probability `p` is close to 1, the resulting graph should have all edges."""
+    runs = 100
+    edges = sum(
+        generator(10, 0.99999, directed=True).number_of_edges() for _ in range(runs)
+    )
+    assert abs(edges / float(runs) - 90) <= runs * 2.0 / 100
+
+
+@pytest.mark.parametrize("generator", _gnp_generators)
+@pytest.mark.parametrize("p", (0.2, 0.8))
+@pytest.mark.parametrize("directed", (True, False))
+def test_gnp_generators_edge_probability(generator, p, directed):
+    """Test that gnp generators generate edges according to the their probability `p`."""
+    runs = 5000
+    n = 5
+    edge_counts = [[0] * n for _ in range(n)]
+    for i in range(runs):
+        G = generator(n, p, directed=directed)
+        for v, w in G.edges:
+            edge_counts[v][w] += 1
+            if not directed:
+                edge_counts[w][v] += 1
+    for v in range(n):
+        for w in range(n):
+            if v == w:
+                # There should be no loops
+                assert edge_counts[v][w] == 0
+            else:
+                # Each edge should have been generated with probability close to p
+                assert abs(edge_counts[v][w] / float(runs) - p) <= 0.03
+
+
+@pytest.mark.parametrize(
+    "generator", [nx.gnp_random_graph, nx.binomial_graph, nx.erdos_renyi_graph]
+)
+@pytest.mark.parametrize(
+    ("seed", "directed", "expected_num_edges"),
+    [(42, False, 1219), (42, True, 2454), (314, False, 1247), (314, True, 2476)],
+)
+def test_gnp_random_graph_aliases(generator, seed, directed, expected_num_edges):
+    """Test that aliases give the same result with the same seed."""
+    G = generator(100, 0.25, seed=seed, directed=directed)
+    assert len(G) == 100
+    assert G.number_of_edges() == expected_num_edges
+    assert G.is_directed() == directed
+
+
+class TestGeneratorsRandom:
+    def test_random_graph(self):
+        seed = 42
+        G = nx.gnm_random_graph(100, 20, seed)
+        G = nx.gnm_random_graph(100, 20, seed, directed=True)
+        G = nx.dense_gnm_random_graph(100, 20, seed)
+
+        G = nx.barabasi_albert_graph(100, 1, seed)
+        G = nx.barabasi_albert_graph(100, 3, seed)
+        assert G.number_of_edges() == (97 * 3)
+
+        G = nx.barabasi_albert_graph(100, 3, seed, nx.complete_graph(5))
+        assert G.number_of_edges() == (10 + 95 * 3)
+
+        G = nx.extended_barabasi_albert_graph(100, 1, 0, 0, seed)
+        assert G.number_of_edges() == 99
+        G = nx.extended_barabasi_albert_graph(100, 3, 0, 0, seed)
+        assert G.number_of_edges() == 97 * 3
+        G = nx.extended_barabasi_albert_graph(100, 1, 0, 0.5, seed)
+        assert G.number_of_edges() == 99
+        G = nx.extended_barabasi_albert_graph(100, 2, 0.5, 0, seed)
+        assert G.number_of_edges() > 100 * 3
+        assert G.number_of_edges() < 100 * 4
+
+        G = nx.extended_barabasi_albert_graph(100, 2, 0.3, 0.3, seed)
+        assert G.number_of_edges() > 100 * 2
+        assert G.number_of_edges() < 100 * 4
+
+        G = nx.powerlaw_cluster_graph(100, 1, 1.0, seed)
+        G = nx.powerlaw_cluster_graph(100, 3, 0.0, seed)
+        assert G.number_of_edges() == (97 * 3)
+
+        G = nx.random_regular_graph(10, 20, seed)
+
+        pytest.raises(nx.NetworkXError, nx.random_regular_graph, 3, 21)
+        pytest.raises(nx.NetworkXError, nx.random_regular_graph, 33, 21)
+
+        constructor = [(10, 20, 0.8), (20, 40, 0.8)]
+        G = nx.random_shell_graph(constructor, seed)
+
+        def is_caterpillar(g):
+            """
+            A tree is a caterpillar iff all nodes of degree >=3 are surrounded
+            by at most two nodes of degree two or greater.
+            ref: http://mathworld.wolfram.com/CaterpillarGraph.html
+            """
+            deg_over_3 = [n for n in g if g.degree(n) >= 3]
+            for n in deg_over_3:
+                nbh_deg_over_2 = [nbh for nbh in g.neighbors(n) if g.degree(nbh) >= 2]
+                if not len(nbh_deg_over_2) <= 2:
+                    return False
+            return True
+
+        def is_lobster(g):
+            """
+            A tree is a lobster if it has the property that the removal of leaf
+            nodes leaves a caterpillar graph (Gallian 2007)
+            ref: http://mathworld.wolfram.com/LobsterGraph.html
+            """
+            non_leafs = [n for n in g if g.degree(n) > 1]
+            return is_caterpillar(g.subgraph(non_leafs))
+
+        G = nx.random_lobster_graph(10, 0.1, 0.5, seed)
+        assert max(G.degree(n) for n in G.nodes()) > 3
+        assert is_lobster(G)
+        pytest.raises(nx.NetworkXError, nx.random_lobster_graph, 10, 0.1, 1, seed)
+        pytest.raises(nx.NetworkXError, nx.random_lobster_graph, 10, 1, 1, seed)
+        pytest.raises(nx.NetworkXError, nx.random_lobster_graph, 10, 1, 0.5, seed)
+
+        # docstring says this should be a caterpillar
+        G = nx.random_lobster_graph(10, 0.1, 0.0, seed)
+        assert is_caterpillar(G)
+
+        # difficult to find seed that requires few tries
+        seq = nx.random_powerlaw_tree_sequence(10, 3, seed=14, tries=1)
+        G = nx.random_powerlaw_tree(10, 3, seed=14, tries=1)
+
+    def test_dual_barabasi_albert(self, m1=1, m2=4, p=0.5):
+        """
+        Tests that the dual BA random graph generated behaves consistently.
+
+        Tests the exceptions are raised as expected.
+
+        The graphs generation are repeated several times to prevent lucky shots
+
+        """
+        seeds = [42, 314, 2718]
+        initial_graph = nx.complete_graph(10)
+
+        for seed in seeds:
+            # This should be BA with m = m1
+            BA1 = nx.barabasi_albert_graph(100, m1, seed)
+            DBA1 = nx.dual_barabasi_albert_graph(100, m1, m2, 1, seed)
+            assert BA1.edges() == DBA1.edges()
+
+            # This should be BA with m = m2
+            BA2 = nx.barabasi_albert_graph(100, m2, seed)
+            DBA2 = nx.dual_barabasi_albert_graph(100, m1, m2, 0, seed)
+            assert BA2.edges() == DBA2.edges()
+
+            BA3 = nx.barabasi_albert_graph(100, m1, seed)
+            DBA3 = nx.dual_barabasi_albert_graph(100, m1, m1, p, seed)
+            # We can't compare edges here since randomness is "consumed" when drawing
+            # between m1 and m2
+            assert BA3.size() == DBA3.size()
+
+            DBA = nx.dual_barabasi_albert_graph(100, m1, m2, p, seed, initial_graph)
+            BA1 = nx.barabasi_albert_graph(100, m1, seed, initial_graph)
+            BA2 = nx.barabasi_albert_graph(100, m2, seed, initial_graph)
+            assert (
+                min(BA1.size(), BA2.size()) <= DBA.size() <= max(BA1.size(), BA2.size())
+            )
+
+        # Testing exceptions
+        dbag = nx.dual_barabasi_albert_graph
+        pytest.raises(nx.NetworkXError, dbag, m1, m1, m2, 0)
+        pytest.raises(nx.NetworkXError, dbag, m2, m1, m2, 0)
+        pytest.raises(nx.NetworkXError, dbag, 100, m1, m2, -0.5)
+        pytest.raises(nx.NetworkXError, dbag, 100, m1, m2, 1.5)
+        initial = nx.complete_graph(max(m1, m2) - 1)
+        pytest.raises(nx.NetworkXError, dbag, 100, m1, m2, p, initial_graph=initial)
+
+    def test_extended_barabasi_albert(self, m=2):
+        """
+        Tests that the extended BA random graph generated behaves consistently.
+
+        Tests the exceptions are raised as expected.
+
+        The graphs generation are repeated several times to prevent lucky-shots
+
+        """
+        seeds = [42, 314, 2718]
+
+        for seed in seeds:
+            BA_model = nx.barabasi_albert_graph(100, m, seed)
+            BA_model_edges = BA_model.number_of_edges()
+
+            # This behaves just like BA, the number of edges must be the same
+            G1 = nx.extended_barabasi_albert_graph(100, m, 0, 0, seed)
+            assert G1.size() == BA_model_edges
+
+            # More than twice more edges should have been added
+            G1 = nx.extended_barabasi_albert_graph(100, m, 0.8, 0, seed)
+            assert G1.size() > BA_model_edges * 2
+
+            # Only edge rewiring, so the number of edges less than original
+            G2 = nx.extended_barabasi_albert_graph(100, m, 0, 0.8, seed)
+            assert G2.size() == BA_model_edges
+
+            # Mixed scenario: less edges than G1 and more edges than G2
+            G3 = nx.extended_barabasi_albert_graph(100, m, 0.3, 0.3, seed)
+            assert G3.size() > G2.size()
+            assert G3.size() < G1.size()
+
+        # Testing exceptions
+        ebag = nx.extended_barabasi_albert_graph
+        pytest.raises(nx.NetworkXError, ebag, m, m, 0, 0)
+        pytest.raises(nx.NetworkXError, ebag, 1, 0.5, 0, 0)
+        pytest.raises(nx.NetworkXError, ebag, 100, 2, 0.5, 0.5)
+
+    def test_random_zero_regular_graph(self):
+        """Tests that a 0-regular graph has the correct number of nodes and
+        edges.
+
+        """
+        seed = 42
+        G = nx.random_regular_graph(0, 10, seed)
+        assert len(G) == 10
+        assert G.number_of_edges() == 0
+
+    def test_gnm(self):
+        G = nx.gnm_random_graph(10, 3)
+        assert len(G) == 10
+        assert G.number_of_edges() == 3
+
+        G = nx.gnm_random_graph(10, 3, seed=42)
+        assert len(G) == 10
+        assert G.number_of_edges() == 3
+
+        G = nx.gnm_random_graph(10, 100)
+        assert len(G) == 10
+        assert G.number_of_edges() == 45
+
+        G = nx.gnm_random_graph(10, 100, directed=True)
+        assert len(G) == 10
+        assert G.number_of_edges() == 90
+
+        G = nx.gnm_random_graph(10, -1.1)
+        assert len(G) == 10
+        assert G.number_of_edges() == 0
+
+    def test_watts_strogatz_big_k(self):
+        # Test to make sure than n <= k
+        pytest.raises(nx.NetworkXError, nx.watts_strogatz_graph, 10, 11, 0.25)
+        pytest.raises(nx.NetworkXError, nx.newman_watts_strogatz_graph, 10, 11, 0.25)
+
+        # could create an infinite loop, now doesn't
+        # infinite loop used to occur when a node has degree n-1 and needs to rewire
+        nx.watts_strogatz_graph(10, 9, 0.25, seed=0)
+        nx.newman_watts_strogatz_graph(10, 9, 0.5, seed=0)
+
+        # Test k==n scenario
+        nx.watts_strogatz_graph(10, 10, 0.25, seed=0)
+        nx.newman_watts_strogatz_graph(10, 10, 0.25, seed=0)
+
+    def test_random_kernel_graph(self):
+        def integral(u, w, z):
+            return c * (z - w)
+
+        def root(u, w, r):
+            return r / c + w
+
+        c = 1
+        graph = nx.random_kernel_graph(1000, integral, root, seed=42)
+        assert len(graph) == 1000
+
+    def test_random_kernel_graph_default_root(self):
+        """When `kernel_root` is not provided, `sp.optimize.brentq` is used to
+        construct the default kernel.
+        """
+        pytest.importorskip("scipy")
+
+        def integral(u, w, z):
+            return z - w
+
+        graph = nx.random_kernel_graph(1000, integral, seed=42)
+        assert len(graph) == 1000
+
+
+@pytest.mark.parametrize(
+    ("k", "expected_num_nodes", "expected_num_edges"),
+    [
+        (2, 10, 10),
+        (4, 10, 20),
+    ],
+)
+def test_watts_strogatz(k, expected_num_nodes, expected_num_edges):
+    G = nx.watts_strogatz_graph(10, k, 0.25, seed=42)
+    assert len(G) == expected_num_nodes
+    assert G.number_of_edges() == expected_num_edges
+
+
+def test_newman_watts_strogatz_zero_probability():
+    G = nx.newman_watts_strogatz_graph(10, 2, 0.0, seed=42)
+    assert len(G) == 10
+    assert G.number_of_edges() == 10
+
+
+def test_newman_watts_strogatz_nonzero_probability():
+    G = nx.newman_watts_strogatz_graph(10, 4, 0.25, seed=42)
+    assert len(G) == 10
+    assert G.number_of_edges() >= 20
+
+
+def test_connected_watts_strogatz():
+    G = nx.connected_watts_strogatz_graph(10, 2, 0.1, tries=10, seed=42)
+    assert len(G) == 10
+    assert G.number_of_edges() == 10
+
+
+def test_connected_watts_strogatz_zero_tries():
+    with pytest.raises(nx.NetworkXError, match="Maximum number of tries exceeded"):
+        nx.connected_watts_strogatz_graph(10, 2, 0.1, tries=0)
+
+
+def test_connected_watts_strogatz_graph_disconnected():
+    """Test that `connected_watts_strogatz_graph` properly loops when disconnected."""
+    with pytest.raises(nx.NetworkXError, match="Maximum number of tries exceeded"):
+        nx.connected_watts_strogatz_graph(10, 0, 0.0)
+
+
+@pytest.mark.parametrize(
+    "generator, kwargs",
+    [
+        (nx.fast_gnp_random_graph, {"n": 20, "p": 0.2, "directed": False}),
+        (nx.fast_gnp_random_graph, {"n": 20, "p": 0.2, "directed": True}),
+        (nx.gnp_random_graph, {"n": 20, "p": 0.2, "directed": False}),
+        (nx.gnp_random_graph, {"n": 20, "p": 0.2, "directed": True}),
+        (nx.dense_gnm_random_graph, {"n": 30, "m": 4}),
+        (nx.gnm_random_graph, {"n": 30, "m": 4, "directed": False}),
+        (nx.gnm_random_graph, {"n": 30, "m": 4, "directed": True}),
+        (nx.newman_watts_strogatz_graph, {"n": 50, "k": 5, "p": 0.1}),
+        (nx.watts_strogatz_graph, {"n": 50, "k": 5, "p": 0.1}),
+        (nx.connected_watts_strogatz_graph, {"n": 50, "k": 5, "p": 0.1}),
+        (nx.random_regular_graph, {"d": 5, "n": 20}),
+        (nx.barabasi_albert_graph, {"n": 40, "m": 3}),
+        (nx.dual_barabasi_albert_graph, {"n": 40, "m1": 3, "m2": 2, "p": 0.1}),
+        (nx.extended_barabasi_albert_graph, {"n": 40, "m": 3, "p": 0.1, "q": 0.2}),
+        (nx.powerlaw_cluster_graph, {"n": 40, "m": 3, "p": 0.1}),
+        (nx.random_lobster_graph, {"n": 40, "p1": 0.1, "p2": 0.2}),
+        (nx.random_shell_graph, {"constructor": [(10, 20, 0.8), (20, 40, 0.8)]}),
+        (nx.random_powerlaw_tree, {"n": 10, "seed": 14, "tries": 1}),
+        (
+            nx.random_kernel_graph,
+            {
+                "n": 10,
+                "kernel_integral": lambda u, w, z: z - w,
+                "kernel_root": lambda u, w, r: r + w,
+            },
+        ),
+    ],
+)
+@pytest.mark.parametrize("create_using_instance", [False, True])
+def test_create_using(generator, kwargs, create_using_instance):
+    class DummyGraph(nx.Graph):
+        pass
+
+    class DummyDiGraph(nx.DiGraph):
+        pass
+
+    create_using_type = DummyDiGraph if kwargs.get("directed") else DummyGraph
+    create_using = create_using_type() if create_using_instance else create_using_type
+    graph = generator(**kwargs, create_using=create_using)
+    assert isinstance(graph, create_using_type)
+
+
+@pytest.mark.parametrize("directed", [True, False])
+@pytest.mark.parametrize("fn", (nx.fast_gnp_random_graph, nx.gnp_random_graph))
+def test_gnp_fns_disallow_multigraph(fn, directed):
+    with pytest.raises(nx.NetworkXError, match="must not be a multi-graph"):
+        fn(20, 0.2, create_using=nx.MultiGraph)
+
+
+@pytest.mark.parametrize("fn", (nx.gnm_random_graph, nx.dense_gnm_random_graph))
+@pytest.mark.parametrize("graphtype", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
+def test_gnm_fns_disallow_directed_and_multigraph(fn, graphtype):
+    with pytest.raises(nx.NetworkXError, match="must not be"):
+        fn(10, 20, create_using=graphtype)
+
+
+@pytest.mark.parametrize(
+    "fn",
+    (
+        nx.newman_watts_strogatz_graph,
+        nx.watts_strogatz_graph,
+        nx.connected_watts_strogatz_graph,
+    ),
+)
+@pytest.mark.parametrize("graphtype", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
+def test_watts_strogatz_disallow_directed_and_multigraph(fn, graphtype):
+    with pytest.raises(nx.NetworkXError, match="must not be"):
+        fn(10, 2, 0.2, create_using=graphtype)
+
+
+@pytest.mark.parametrize("graphtype", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
+def test_random_regular_graph_disallow_directed_and_multigraph(graphtype):
+    with pytest.raises(nx.NetworkXError, match="must not be"):
+        nx.random_regular_graph(2, 10, create_using=graphtype)
+
+
+@pytest.mark.parametrize("graphtype", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
+def test_barabasi_albert_disallow_directed_and_multigraph(graphtype):
+    with pytest.raises(nx.NetworkXError, match="must not be"):
+        nx.barabasi_albert_graph(10, 3, create_using=graphtype)
+
+
+@pytest.mark.parametrize("graphtype", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
+def test_dual_barabasi_albert_disallow_directed_and_multigraph(graphtype):
+    with pytest.raises(nx.NetworkXError, match="must not be"):
+        nx.dual_barabasi_albert_graph(10, 2, 1, 0.4, create_using=graphtype)
+
+
+@pytest.mark.parametrize("graphtype", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
+def test_extended_barabasi_albert_disallow_directed_and_multigraph(graphtype):
+    with pytest.raises(nx.NetworkXError, match="must not be"):
+        nx.extended_barabasi_albert_graph(10, 2, 0.2, 0.3, create_using=graphtype)
+
+
+@pytest.mark.parametrize("graphtype", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
+def test_powerlaw_cluster_disallow_directed_and_multigraph(graphtype):
+    with pytest.raises(nx.NetworkXError, match="must not be"):
+        nx.powerlaw_cluster_graph(10, 5, 0.2, create_using=graphtype)
+
+
+@pytest.mark.parametrize("graphtype", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
+def test_random_lobster_disallow_directed_and_multigraph(graphtype):
+    with pytest.raises(nx.NetworkXError, match="must not be"):
+        nx.random_lobster_graph(10, 0.1, 0.1, create_using=graphtype)
+
+
+@pytest.mark.parametrize("graphtype", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
+def test_random_shell_disallow_directed_and_multigraph(graphtype):
+    with pytest.raises(nx.NetworkXError, match="must not be"):
+        nx.random_shell_graph([(10, 20, 2), (10, 20, 5)], create_using=graphtype)
+
+
+@pytest.mark.parametrize("graphtype", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
+def test_random_powerlaw_tree_disallow_directed_and_multigraph(graphtype):
+    with pytest.raises(nx.NetworkXError, match="must not be"):
+        nx.random_powerlaw_tree(10, create_using=graphtype)
+
+
+@pytest.mark.parametrize("graphtype", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
+def test_random_kernel_disallow_directed_and_multigraph(graphtype):
+    with pytest.raises(nx.NetworkXError, match="must not be"):
+        nx.random_kernel_graph(
+            10, lambda y, a, b: a + b, lambda u, w, r: r + w, create_using=graphtype
+        )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_small.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_small.py
new file mode 100644
index 0000000000000000000000000000000000000000..2072678e473d4ec7f094b38865fc080058f94218
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_small.py
@@ -0,0 +1,220 @@
+import pytest
+
+import networkx as nx
+
+null = nx.null_graph()
+
+
+class TestGeneratorsSmall:
+    def test__LCF_graph(self):
+        # If n<=0, then return the null_graph
+        G = nx.LCF_graph(-10, [1, 2], 100)
+        assert nx.could_be_isomorphic(G, null)
+        G = nx.LCF_graph(0, [1, 2], 3)
+        assert nx.could_be_isomorphic(G, null)
+        G = nx.LCF_graph(0, [1, 2], 10)
+        assert nx.could_be_isomorphic(G, null)
+
+        # Test that LCF(n,[],0) == cycle_graph(n)
+        for a, b, c in [(5, [], 0), (10, [], 0), (5, [], 1), (10, [], 10)]:
+            G = nx.LCF_graph(a, b, c)
+            assert nx.could_be_isomorphic(G, nx.cycle_graph(a))
+
+        # Generate the utility graph K_{3,3}
+        G = nx.LCF_graph(6, [3, -3], 3)
+        utility_graph = nx.complete_bipartite_graph(3, 3)
+        assert nx.could_be_isomorphic(G, utility_graph)
+
+        with pytest.raises(nx.NetworkXError, match="Directed Graph not supported"):
+            G = nx.LCF_graph(6, [3, -3], 3, create_using=nx.DiGraph)
+
+    def test_properties_of_named_small_graphs(self):
+        G = nx.bull_graph()
+        assert sorted(G) == list(range(5))
+        assert G.number_of_edges() == 5
+        assert sorted(d for n, d in G.degree()) == [1, 1, 2, 3, 3]
+        assert nx.diameter(G) == 3
+        assert nx.radius(G) == 2
+
+        G = nx.chvatal_graph()
+        assert sorted(G) == list(range(12))
+        assert G.number_of_edges() == 24
+        assert [d for n, d in G.degree()] == 12 * [4]
+        assert nx.diameter(G) == 2
+        assert nx.radius(G) == 2
+
+        G = nx.cubical_graph()
+        assert sorted(G) == list(range(8))
+        assert G.number_of_edges() == 12
+        assert [d for n, d in G.degree()] == 8 * [3]
+        assert nx.diameter(G) == 3
+        assert nx.radius(G) == 3
+
+        G = nx.desargues_graph()
+        assert sorted(G) == list(range(20))
+        assert G.number_of_edges() == 30
+        assert [d for n, d in G.degree()] == 20 * [3]
+        assert nx.is_isomorphic(G, nx.generalized_petersen_graph(10, 3))
+
+        G = nx.diamond_graph()
+        assert sorted(G) == list(range(4))
+        assert sorted(d for n, d in G.degree()) == [2, 2, 3, 3]
+        assert nx.diameter(G) == 2
+        assert nx.radius(G) == 1
+
+        G = nx.dodecahedral_graph()
+        assert sorted(G) == list(range(20))
+        assert G.number_of_edges() == 30
+        assert [d for n, d in G.degree()] == 20 * [3]
+        assert nx.diameter(G) == 5
+        assert nx.radius(G) == 5
+        assert nx.is_isomorphic(G, nx.generalized_petersen_graph(10, 2))
+
+        G = nx.frucht_graph()
+        assert sorted(G) == list(range(12))
+        assert G.number_of_edges() == 18
+        assert [d for n, d in G.degree()] == 12 * [3]
+        assert nx.diameter(G) == 4
+        assert nx.radius(G) == 3
+
+        G = nx.generalized_petersen_graph(10, 4)
+        assert sorted(G) == list(range(20))
+        assert G.number_of_edges() == 30
+        assert [d for n, d in G.degree()] == 20 * [3]
+        assert nx.diameter(G) == 4
+        assert nx.radius(G) == 4
+
+        G = nx.heawood_graph()
+        assert sorted(G) == list(range(14))
+        assert G.number_of_edges() == 21
+        assert [d for n, d in G.degree()] == 14 * [3]
+        assert nx.diameter(G) == 3
+        assert nx.radius(G) == 3
+
+        G = nx.hoffman_singleton_graph()
+        assert sorted(G) == list(range(50))
+        assert G.number_of_edges() == 175
+        assert [d for n, d in G.degree()] == 50 * [7]
+        assert nx.diameter(G) == 2
+        assert nx.radius(G) == 2
+
+        G = nx.house_graph()
+        assert sorted(G) == list(range(5))
+        assert G.number_of_edges() == 6
+        assert sorted(d for n, d in G.degree()) == [2, 2, 2, 3, 3]
+        assert nx.diameter(G) == 2
+        assert nx.radius(G) == 2
+
+        G = nx.house_x_graph()
+        assert sorted(G) == list(range(5))
+        assert G.number_of_edges() == 8
+        assert sorted(d for n, d in G.degree()) == [2, 3, 3, 4, 4]
+        assert nx.diameter(G) == 2
+        assert nx.radius(G) == 1
+
+        G = nx.icosahedral_graph()
+        assert sorted(G) == list(range(12))
+        assert G.number_of_edges() == 30
+        assert [d for n, d in G.degree()] == [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
+        assert nx.diameter(G) == 3
+        assert nx.radius(G) == 3
+
+        G = nx.krackhardt_kite_graph()
+        assert sorted(G) == list(range(10))
+        assert G.number_of_edges() == 18
+        assert sorted(d for n, d in G.degree()) == [1, 2, 3, 3, 3, 4, 4, 5, 5, 6]
+
+        G = nx.moebius_kantor_graph()
+        assert sorted(G) == list(range(16))
+        assert G.number_of_edges() == 24
+        assert [d for n, d in G.degree()] == 16 * [3]
+        assert nx.diameter(G) == 4
+        assert nx.is_isomorphic(G, nx.generalized_petersen_graph(8, 3))
+
+        G = nx.octahedral_graph()
+        assert sorted(G) == list(range(6))
+        assert G.number_of_edges() == 12
+        assert [d for n, d in G.degree()] == 6 * [4]
+        assert nx.diameter(G) == 2
+        assert nx.radius(G) == 2
+
+        G = nx.pappus_graph()
+        assert sorted(G) == list(range(18))
+        assert G.number_of_edges() == 27
+        assert [d for n, d in G.degree()] == 18 * [3]
+        assert nx.diameter(G) == 4
+
+        G = nx.petersen_graph()
+        assert sorted(G) == list(range(10))
+        assert G.number_of_edges() == 15
+        assert [d for n, d in G.degree()] == 10 * [3]
+        assert nx.diameter(G) == 2
+        assert nx.radius(G) == 2
+        assert nx.is_isomorphic(G, nx.generalized_petersen_graph(5, 2))
+
+        G = nx.sedgewick_maze_graph()
+        assert sorted(G) == list(range(8))
+        assert G.number_of_edges() == 10
+        assert sorted(d for n, d in G.degree()) == [1, 2, 2, 2, 3, 3, 3, 4]
+
+        G = nx.tetrahedral_graph()
+        assert sorted(G) == list(range(4))
+        assert G.number_of_edges() == 6
+        assert [d for n, d in G.degree()] == [3, 3, 3, 3]
+        assert nx.diameter(G) == 1
+        assert nx.radius(G) == 1
+
+        G = nx.truncated_cube_graph()
+        assert sorted(G) == list(range(24))
+        assert G.number_of_edges() == 36
+        assert [d for n, d in G.degree()] == 24 * [3]
+
+        G = nx.truncated_tetrahedron_graph()
+        assert sorted(G) == list(range(12))
+        assert G.number_of_edges() == 18
+        assert [d for n, d in G.degree()] == 12 * [3]
+
+        G = nx.tutte_graph()
+        assert sorted(G) == list(range(46))
+        assert G.number_of_edges() == 69
+        assert [d for n, d in G.degree()] == 46 * [3]
+
+        MG = nx.tutte_graph(create_using=nx.MultiGraph)
+        assert sorted(MG.edges()) == sorted(G.edges())
+
+        # Test create_using with directed or multigraphs on small graphs
+        with pytest.raises(nx.NetworkXError, match="Directed Graph not supported "):
+            nx.generalized_petersen_graph(5, 2, create_using=nx.DiGraph)
+        with pytest.raises(nx.NetworkXError, match="Directed Graph not supported "):
+            nx.generalized_petersen_graph(5, 2, create_using=nx.MultiDiGraph)
+        G = nx.generalized_petersen_graph(5, 2)
+        MG = nx.generalized_petersen_graph(5, 2, create_using=nx.MultiGraph)
+        assert sorted(MG.edges()) == sorted(G.edges())
+
+
+@pytest.mark.parametrize(
+    "fn",
+    (
+        nx.bull_graph,
+        nx.chvatal_graph,
+        nx.cubical_graph,
+        nx.diamond_graph,
+        nx.house_graph,
+        nx.house_x_graph,
+        nx.icosahedral_graph,
+        nx.krackhardt_kite_graph,
+        nx.octahedral_graph,
+        nx.petersen_graph,
+        nx.truncated_cube_graph,
+        nx.tutte_graph,
+    ),
+)
+@pytest.mark.parametrize(
+    "create_using", (nx.DiGraph, nx.MultiDiGraph, nx.DiGraph([(0, 1)]))
+)
+def tests_raises_with_directed_create_using(fn, create_using):
+    with pytest.raises(nx.NetworkXError, match="Directed Graph not supported"):
+        fn(create_using=create_using)
+    # All these functions have `create_using` as the first positional argument too
+    with pytest.raises(nx.NetworkXError, match="Directed Graph not supported"):
+        fn(create_using)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_spectral_graph_forge.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_spectral_graph_forge.py
new file mode 100644
index 0000000000000000000000000000000000000000..b554bfd7017658c9e3ac801c4504c9702d1e03d9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_spectral_graph_forge.py
@@ -0,0 +1,49 @@
+import pytest
+
+pytest.importorskip("numpy")
+pytest.importorskip("scipy")
+
+
+from networkx import is_isomorphic
+from networkx.exception import NetworkXError
+from networkx.generators import karate_club_graph
+from networkx.generators.spectral_graph_forge import spectral_graph_forge
+from networkx.utils import nodes_equal
+
+
+def test_spectral_graph_forge():
+    G = karate_club_graph()
+
+    seed = 54321
+
+    # common cases, just checking node number preserving and difference
+    # between identity and modularity cases
+    H = spectral_graph_forge(G, 0.1, transformation="identity", seed=seed)
+    assert nodes_equal(G, H)
+
+    I = spectral_graph_forge(G, 0.1, transformation="identity", seed=seed)
+    assert nodes_equal(G, H)
+    assert is_isomorphic(I, H)
+
+    I = spectral_graph_forge(G, 0.1, transformation="modularity", seed=seed)
+    assert nodes_equal(G, I)
+
+    assert not is_isomorphic(I, H)
+
+    # with all the eigenvectors, output graph is identical to the input one
+    H = spectral_graph_forge(G, 1, transformation="modularity", seed=seed)
+    assert nodes_equal(G, H)
+    assert is_isomorphic(G, H)
+
+    # invalid alpha input value, it is silently truncated in [0,1]
+    H = spectral_graph_forge(G, -1, transformation="identity", seed=seed)
+    assert nodes_equal(G, H)
+
+    H = spectral_graph_forge(G, 10, transformation="identity", seed=seed)
+    assert nodes_equal(G, H)
+    assert is_isomorphic(G, H)
+
+    # invalid transformation mode, checking the error raising
+    pytest.raises(
+        NetworkXError, spectral_graph_forge, G, 0.1, transformation="unknown", seed=seed
+    )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_stochastic.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_stochastic.py
new file mode 100644
index 0000000000000000000000000000000000000000..0404d9d8454b36b546152c1428790441c6952fa2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_stochastic.py
@@ -0,0 +1,72 @@
+"""Unit tests for the :mod:`networkx.generators.stochastic` module."""
+
+import pytest
+
+import networkx as nx
+
+
+class TestStochasticGraph:
+    """Unit tests for the :func:`~networkx.stochastic_graph` function."""
+
+    def test_default_weights(self):
+        G = nx.DiGraph()
+        G.add_edge(0, 1)
+        G.add_edge(0, 2)
+        S = nx.stochastic_graph(G)
+        assert nx.is_isomorphic(G, S)
+        assert sorted(S.edges(data=True)) == [
+            (0, 1, {"weight": 0.5}),
+            (0, 2, {"weight": 0.5}),
+        ]
+
+    def test_in_place(self):
+        """Tests for an in-place reweighting of the edges of the graph."""
+        G = nx.DiGraph()
+        G.add_edge(0, 1, weight=1)
+        G.add_edge(0, 2, weight=1)
+        nx.stochastic_graph(G, copy=False)
+        assert sorted(G.edges(data=True)) == [
+            (0, 1, {"weight": 0.5}),
+            (0, 2, {"weight": 0.5}),
+        ]
+
+    def test_arbitrary_weights(self):
+        G = nx.DiGraph()
+        G.add_edge(0, 1, weight=1)
+        G.add_edge(0, 2, weight=1)
+        S = nx.stochastic_graph(G)
+        assert sorted(S.edges(data=True)) == [
+            (0, 1, {"weight": 0.5}),
+            (0, 2, {"weight": 0.5}),
+        ]
+
+    def test_multidigraph(self):
+        G = nx.MultiDiGraph()
+        G.add_edges_from([(0, 1), (0, 1), (0, 2), (0, 2)])
+        S = nx.stochastic_graph(G)
+        d = {"weight": 0.25}
+        assert sorted(S.edges(data=True)) == [
+            (0, 1, d),
+            (0, 1, d),
+            (0, 2, d),
+            (0, 2, d),
+        ]
+
+    def test_zero_weights(self):
+        """Smoke test: ensure ZeroDivisionError is not raised."""
+        G = nx.DiGraph()
+        G.add_edge(0, 1, weight=0)
+        G.add_edge(0, 2, weight=0)
+        S = nx.stochastic_graph(G)
+        assert sorted(S.edges(data=True)) == [
+            (0, 1, {"weight": 0}),
+            (0, 2, {"weight": 0}),
+        ]
+
+    def test_graph_disallowed(self):
+        with pytest.raises(nx.NetworkXNotImplemented):
+            nx.stochastic_graph(nx.Graph())
+
+    def test_multigraph_disallowed(self):
+        with pytest.raises(nx.NetworkXNotImplemented):
+            nx.stochastic_graph(nx.MultiGraph())
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_sudoku.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_sudoku.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c3560aa81890d0dc308219d7f0983d3950f9fd5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_sudoku.py
@@ -0,0 +1,92 @@
+"""Unit tests for the :mod:`networkx.generators.sudoku_graph` module."""
+
+import pytest
+
+import networkx as nx
+
+
+def test_sudoku_negative():
+    """Raise an error when generating a Sudoku graph of order -1."""
+    pytest.raises(nx.NetworkXError, nx.sudoku_graph, n=-1)
+
+
+@pytest.mark.parametrize("n", [0, 1, 2, 3, 4])
+def test_sudoku_generator(n):
+    """Generate Sudoku graphs of various sizes and verify their properties."""
+    G = nx.sudoku_graph(n)
+    expected_nodes = n**4
+    expected_degree = (n - 1) * (3 * n + 1)
+    expected_edges = expected_nodes * expected_degree // 2
+    assert not G.is_directed()
+    assert not G.is_multigraph()
+    assert G.number_of_nodes() == expected_nodes
+    assert G.number_of_edges() == expected_edges
+    assert all(d == expected_degree for _, d in G.degree)
+
+    if n == 2:
+        assert sorted(G.neighbors(6)) == [2, 3, 4, 5, 7, 10, 14]
+    elif n == 3:
+        assert sorted(G.neighbors(42)) == [
+            6,
+            15,
+            24,
+            33,
+            34,
+            35,
+            36,
+            37,
+            38,
+            39,
+            40,
+            41,
+            43,
+            44,
+            51,
+            52,
+            53,
+            60,
+            69,
+            78,
+        ]
+    elif n == 4:
+        assert sorted(G.neighbors(0)) == [
+            1,
+            2,
+            3,
+            4,
+            5,
+            6,
+            7,
+            8,
+            9,
+            10,
+            11,
+            12,
+            13,
+            14,
+            15,
+            16,
+            17,
+            18,
+            19,
+            32,
+            33,
+            34,
+            35,
+            48,
+            49,
+            50,
+            51,
+            64,
+            80,
+            96,
+            112,
+            128,
+            144,
+            160,
+            176,
+            192,
+            208,
+            224,
+            240,
+        ]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_time_series.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_time_series.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d0cc90a53589a46d0444be6df7c31a1f5beec06
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_time_series.py
@@ -0,0 +1,64 @@
+"""Unit tests for the :mod:`networkx.generators.time_series` module."""
+
+import itertools
+
+import networkx as nx
+
+
+def test_visibility_graph__empty_series__empty_graph():
+    null_graph = nx.visibility_graph([])  # move along nothing to see here
+    assert nx.is_empty(null_graph)
+
+
+def test_visibility_graph__single_value_ts__single_node_graph():
+    node_graph = nx.visibility_graph([10])  # So Lonely
+    assert node_graph.number_of_nodes() == 1
+    assert node_graph.number_of_edges() == 0
+
+
+def test_visibility_graph__two_values_ts__single_edge_graph():
+    edge_graph = nx.visibility_graph([10, 20])  # Two of Us
+    assert list(edge_graph.edges) == [(0, 1)]
+
+
+def test_visibility_graph__convex_series__complete_graph():
+    series = [i**2 for i in range(10)]  # no obstructions
+    expected_series_length = len(series)
+
+    actual_graph = nx.visibility_graph(series)
+
+    assert actual_graph.number_of_nodes() == expected_series_length
+    assert actual_graph.number_of_edges() == 45
+    assert nx.is_isomorphic(actual_graph, nx.complete_graph(expected_series_length))
+
+
+def test_visibility_graph__concave_series__path_graph():
+    series = [-(i**2) for i in range(10)]  # Slip Slidin' Away
+    expected_node_count = len(series)
+
+    actual_graph = nx.visibility_graph(series)
+
+    assert actual_graph.number_of_nodes() == expected_node_count
+    assert actual_graph.number_of_edges() == expected_node_count - 1
+    assert nx.is_isomorphic(actual_graph, nx.path_graph(expected_node_count))
+
+
+def test_visibility_graph__flat_series__path_graph():
+    series = [0] * 10  # living in 1D flatland
+    expected_node_count = len(series)
+
+    actual_graph = nx.visibility_graph(series)
+
+    assert actual_graph.number_of_nodes() == expected_node_count
+    assert actual_graph.number_of_edges() == expected_node_count - 1
+    assert nx.is_isomorphic(actual_graph, nx.path_graph(expected_node_count))
+
+
+def test_visibility_graph_cyclic_series():
+    series = list(itertools.islice(itertools.cycle((2, 1, 3)), 17))  # It's so bumpy!
+    expected_node_count = len(series)
+
+    actual_graph = nx.visibility_graph(series)
+
+    assert actual_graph.number_of_nodes() == expected_node_count
+    assert actual_graph.number_of_edges() == 25
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_trees.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_trees.py
new file mode 100644
index 0000000000000000000000000000000000000000..7932436bf7ad6bb5ab5124f6ff59b7523358354d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_trees.py
@@ -0,0 +1,195 @@
+import random
+
+import pytest
+
+import networkx as nx
+from networkx.utils import arbitrary_element, graphs_equal
+
+
+@pytest.mark.parametrize("prefix_tree_fn", (nx.prefix_tree, nx.prefix_tree_recursive))
+def test_basic_prefix_tree(prefix_tree_fn):
+    # This example is from the Wikipedia article "Trie"
+    # .
+    strings = ["a", "to", "tea", "ted", "ten", "i", "in", "inn"]
+    T = prefix_tree_fn(strings)
+    root, NIL = 0, -1
+
+    def source_label(v):
+        return T.nodes[v]["source"]
+
+    # First, we check that the tree has the expected
+    # structure. Recall that each node that corresponds to one of
+    # the input strings has an edge to the NIL node.
+    #
+    # Consider the three children at level 1 in the trie.
+    a, i, t = sorted(T[root], key=source_label)
+    # Check the 'a' branch.
+    assert len(T[a]) == 1
+    nil = arbitrary_element(T[a])
+    assert len(T[nil]) == 0
+    # Check the 'i' branch.
+    assert len(T[i]) == 2
+    nil, in_ = sorted(T[i], key=source_label)
+    assert len(T[nil]) == 0
+    assert len(T[in_]) == 2
+    nil, inn = sorted(T[in_], key=source_label)
+    assert len(T[nil]) == 0
+    assert len(T[inn]) == 1
+    nil = arbitrary_element(T[inn])
+    assert len(T[nil]) == 0
+    # Check the 't' branch.
+    te, to = sorted(T[t], key=source_label)
+    assert len(T[to]) == 1
+    nil = arbitrary_element(T[to])
+    assert len(T[nil]) == 0
+    tea, ted, ten = sorted(T[te], key=source_label)
+    assert len(T[tea]) == 1
+    assert len(T[ted]) == 1
+    assert len(T[ten]) == 1
+    nil = arbitrary_element(T[tea])
+    assert len(T[nil]) == 0
+    nil = arbitrary_element(T[ted])
+    assert len(T[nil]) == 0
+    nil = arbitrary_element(T[ten])
+    assert len(T[nil]) == 0
+
+    # Next, we check that the "sources" of each of the nodes is the
+    # rightmost letter in the string corresponding to the path to
+    # that node.
+    assert source_label(root) is None
+    assert source_label(a) == "a"
+    assert source_label(i) == "i"
+    assert source_label(t) == "t"
+    assert source_label(in_) == "n"
+    assert source_label(inn) == "n"
+    assert source_label(to) == "o"
+    assert source_label(te) == "e"
+    assert source_label(tea) == "a"
+    assert source_label(ted) == "d"
+    assert source_label(ten) == "n"
+    assert source_label(NIL) == "NIL"
+
+
+@pytest.mark.parametrize(
+    "strings",
+    (
+        ["a", "to", "tea", "ted", "ten", "i", "in", "inn"],
+        ["ab", "abs", "ad"],
+        ["ab", "abs", "ad", ""],
+        ["distant", "disparaging", "distant", "diamond", "ruby"],
+    ),
+)
+def test_implementations_consistent(strings):
+    """Ensure results are consistent between prefix_tree implementations."""
+    assert graphs_equal(nx.prefix_tree(strings), nx.prefix_tree_recursive(strings))
+
+
+def test_random_labeled_rooted_tree():
+    for i in range(1, 10):
+        t1 = nx.random_labeled_rooted_tree(i, seed=42)
+        t2 = nx.random_labeled_rooted_tree(i, seed=42)
+        assert nx.utils.misc.graphs_equal(t1, t2)
+        assert nx.is_tree(t1)
+        assert "root" in t1.graph
+        assert "roots" not in t1.graph
+
+
+def test_random_labeled_tree_n_zero():
+    """Tests if n = 0 then the NetworkXPointlessConcept exception is raised."""
+    with pytest.raises(nx.NetworkXPointlessConcept):
+        T = nx.random_labeled_tree(0, seed=1234)
+    with pytest.raises(nx.NetworkXPointlessConcept):
+        T = nx.random_labeled_rooted_tree(0, seed=1234)
+
+
+def test_random_labeled_rooted_forest():
+    for i in range(1, 10):
+        t1 = nx.random_labeled_rooted_forest(i, seed=42)
+        t2 = nx.random_labeled_rooted_forest(i, seed=42)
+        assert nx.utils.misc.graphs_equal(t1, t2)
+        for c in nx.connected_components(t1):
+            assert nx.is_tree(t1.subgraph(c))
+        assert "root" not in t1.graph
+        assert "roots" in t1.graph
+
+
+def test_random_labeled_rooted_forest_n_zero():
+    """Tests generation of empty labeled forests."""
+    F = nx.random_labeled_rooted_forest(0, seed=1234)
+    assert len(F) == 0
+    assert len(F.graph["roots"]) == 0
+
+
+def test_random_unlabeled_rooted_tree():
+    for i in range(1, 10):
+        t1 = nx.random_unlabeled_rooted_tree(i, seed=42)
+        t2 = nx.random_unlabeled_rooted_tree(i, seed=42)
+        assert nx.utils.misc.graphs_equal(t1, t2)
+        assert nx.is_tree(t1)
+        assert "root" in t1.graph
+        assert "roots" not in t1.graph
+    t = nx.random_unlabeled_rooted_tree(15, number_of_trees=10, seed=43)
+    random.seed(43)
+    s = nx.random_unlabeled_rooted_tree(15, number_of_trees=10, seed=random)
+    for i in range(10):
+        assert nx.utils.misc.graphs_equal(t[i], s[i])
+        assert nx.is_tree(t[i])
+        assert "root" in t[i].graph
+        assert "roots" not in t[i].graph
+
+
+def test_random_unlabeled_tree_n_zero():
+    """Tests if n = 0 then the NetworkXPointlessConcept exception is raised."""
+    with pytest.raises(nx.NetworkXPointlessConcept):
+        T = nx.random_unlabeled_tree(0, seed=1234)
+    with pytest.raises(nx.NetworkXPointlessConcept):
+        T = nx.random_unlabeled_rooted_tree(0, seed=1234)
+
+
+def test_random_unlabeled_rooted_forest():
+    with pytest.raises(ValueError):
+        nx.random_unlabeled_rooted_forest(10, q=0, seed=42)
+    for i in range(1, 10):
+        for q in range(1, i + 1):
+            t1 = nx.random_unlabeled_rooted_forest(i, q=q, seed=42)
+            t2 = nx.random_unlabeled_rooted_forest(i, q=q, seed=42)
+            assert nx.utils.misc.graphs_equal(t1, t2)
+            for c in nx.connected_components(t1):
+                assert nx.is_tree(t1.subgraph(c))
+                assert len(c) <= q
+            assert "root" not in t1.graph
+            assert "roots" in t1.graph
+    t = nx.random_unlabeled_rooted_forest(15, number_of_forests=10, seed=43)
+    random.seed(43)
+    s = nx.random_unlabeled_rooted_forest(15, number_of_forests=10, seed=random)
+    for i in range(10):
+        assert nx.utils.misc.graphs_equal(t[i], s[i])
+        for c in nx.connected_components(t[i]):
+            assert nx.is_tree(t[i].subgraph(c))
+        assert "root" not in t[i].graph
+        assert "roots" in t[i].graph
+
+
+def test_random_unlabeled_forest_n_zero():
+    """Tests generation of empty unlabeled forests."""
+    F = nx.random_unlabeled_rooted_forest(0, seed=1234)
+    assert len(F) == 0
+    assert len(F.graph["roots"]) == 0
+
+
+def test_random_unlabeled_tree():
+    for i in range(1, 10):
+        t1 = nx.random_unlabeled_tree(i, seed=42)
+        t2 = nx.random_unlabeled_tree(i, seed=42)
+        assert nx.utils.misc.graphs_equal(t1, t2)
+        assert nx.is_tree(t1)
+        assert "root" not in t1.graph
+        assert "roots" not in t1.graph
+    t = nx.random_unlabeled_tree(10, number_of_trees=10, seed=43)
+    random.seed(43)
+    s = nx.random_unlabeled_tree(10, number_of_trees=10, seed=random)
+    for i in range(10):
+        assert nx.utils.misc.graphs_equal(t[i], s[i])
+        assert nx.is_tree(t[i])
+        assert "root" not in t[i].graph
+        assert "roots" not in t[i].graph
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_triads.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_triads.py
new file mode 100644
index 0000000000000000000000000000000000000000..463844be23a07f71375873bbc71e09c402d51118
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/tests/test_triads.py
@@ -0,0 +1,15 @@
+"""Unit tests for the :mod:`networkx.generators.triads` module."""
+
+import pytest
+
+from networkx import triad_graph
+
+
+def test_triad_graph():
+    G = triad_graph("030T")
+    assert [tuple(e) for e in ("ab", "ac", "cb")] == sorted(G.edges())
+
+
+def test_invalid_name():
+    with pytest.raises(ValueError):
+        triad_graph("bogus")
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/time_series.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/time_series.py
new file mode 100644
index 0000000000000000000000000000000000000000..592d7734a408bf33e58aad20cb117be674558ad2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/time_series.py
@@ -0,0 +1,74 @@
+"""
+Time Series Graphs
+"""
+
+import itertools
+
+import networkx as nx
+
+__all__ = ["visibility_graph"]
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def visibility_graph(series):
+    """
+    Return a Visibility Graph of an input Time Series.
+
+    A visibility graph converts a time series into a graph. The constructed graph
+    uses integer nodes to indicate which event in the series the node represents.
+    Edges are formed as follows: consider a bar plot of the series and view that
+    as a side view of a landscape with a node at the top of each bar. An edge
+    means that the nodes can be connected by a straight "line-of-sight" without
+    being obscured by any bars between the nodes.
+
+    The resulting graph inherits several properties of the series in its structure.
+    Thereby, periodic series convert into regular graphs, random series convert
+    into random graphs, and fractal series convert into scale-free networks [1]_.
+
+    Parameters
+    ----------
+    series : Sequence[Number]
+       A Time Series sequence (iterable and sliceable) of numeric values
+       representing times.
+
+    Returns
+    -------
+    NetworkX Graph
+        The Visibility Graph of the input series
+
+    Examples
+    --------
+    >>> series_list = [range(10), [2, 1, 3, 2, 1, 3, 2, 1, 3, 2, 1, 3]]
+    >>> for s in series_list:
+    ...     g = nx.visibility_graph(s)
+    ...     print(g)
+    Graph with 10 nodes and 9 edges
+    Graph with 12 nodes and 18 edges
+
+    References
+    ----------
+    .. [1] Lacasa, Lucas, Bartolo Luque, Fernando Ballesteros, Jordi Luque, and Juan Carlos Nuno.
+           "From time series to complex networks: The visibility graph." Proceedings of the
+           National Academy of Sciences 105, no. 13 (2008): 4972-4975.
+           https://www.pnas.org/doi/10.1073/pnas.0709247105
+    """
+
+    # Sequential values are always connected
+    G = nx.path_graph(len(series))
+    nx.set_node_attributes(G, dict(enumerate(series)), "value")
+
+    # Check all combinations of nodes n series
+    for (n1, t1), (n2, t2) in itertools.combinations(enumerate(series), 2):
+        # check if any value between obstructs line of sight
+        slope = (t2 - t1) / (n2 - n1)
+        offset = t2 - slope * n2
+
+        obstructed = any(
+            t >= slope * n + offset
+            for n, t in enumerate(series[n1 + 1 : n2], start=n1 + 1)
+        )
+
+        if not obstructed:
+            G.add_edge(n1, n2)
+
+    return G
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/trees.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/trees.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8b24fad27c59a85daa3b31ecb2e3ddd6fe7875f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/trees.py
@@ -0,0 +1,1070 @@
+"""Functions for generating trees.
+
+The functions sampling trees at random in this module come
+in two variants: labeled and unlabeled. The labeled variants
+sample from every possible tree with the given number of nodes
+uniformly at random. The unlabeled variants sample from every
+possible *isomorphism class* of trees with the given number
+of nodes uniformly at random.
+
+To understand the difference, consider the following example.
+There are two isomorphism classes of trees with four nodes.
+One is that of the path graph, the other is that of the
+star graph. The unlabeled variant will return a line graph or
+a star graph with probability 1/2.
+
+The labeled variant will return the line graph
+with probability 3/4 and the star graph with probability 1/4,
+because there are more labeled variants of the line graph
+than of the star graph. More precisely, the line graph has
+an automorphism group of order 2, whereas the star graph has
+an automorphism group of order 6, so the line graph has three
+times as many labeled variants as the star graph, and thus
+three more chances to be drawn.
+
+Additionally, some functions in this module can sample rooted
+trees and forests uniformly at random. A rooted tree is a tree
+with a designated root node. A rooted forest is a disjoint union
+of rooted trees.
+"""
+
+from collections import Counter, defaultdict
+from math import comb, factorial
+
+import networkx as nx
+from networkx.utils import py_random_state
+
+__all__ = [
+    "prefix_tree",
+    "prefix_tree_recursive",
+    "random_labeled_tree",
+    "random_labeled_rooted_tree",
+    "random_labeled_rooted_forest",
+    "random_unlabeled_tree",
+    "random_unlabeled_rooted_tree",
+    "random_unlabeled_rooted_forest",
+]
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def prefix_tree(paths):
+    """Creates a directed prefix tree from a list of paths.
+
+    Usually the paths are described as strings or lists of integers.
+
+    A "prefix tree" represents the prefix structure of the strings.
+    Each node represents a prefix of some string. The root represents
+    the empty prefix with children for the single letter prefixes which
+    in turn have children for each double letter prefix starting with
+    the single letter corresponding to the parent node, and so on.
+
+    More generally the prefixes do not need to be strings. A prefix refers
+    to the start of a sequence. The root has children for each one element
+    prefix and they have children for each two element prefix that starts
+    with the one element sequence of the parent, and so on.
+
+    Note that this implementation uses integer nodes with an attribute.
+    Each node has an attribute "source" whose value is the original element
+    of the path to which this node corresponds. For example, suppose `paths`
+    consists of one path: "can". Then the nodes `[1, 2, 3]` which represent
+    this path have "source" values "c", "a" and "n".
+
+    All the descendants of a node have a common prefix in the sequence/path
+    associated with that node. From the returned tree, the prefix for each
+    node can be constructed by traversing the tree up to the root and
+    accumulating the "source" values along the way.
+
+    The root node is always `0` and has "source" attribute `None`.
+    The root is the only node with in-degree zero.
+    The nil node is always `-1` and has "source" attribute `"NIL"`.
+    The nil node is the only node with out-degree zero.
+
+
+    Parameters
+    ----------
+    paths: iterable of paths
+        An iterable of paths which are themselves sequences.
+        Matching prefixes among these sequences are identified with
+        nodes of the prefix tree. One leaf of the tree is associated
+        with each path. (Identical paths are associated with the same
+        leaf of the tree.)
+
+
+    Returns
+    -------
+    tree: DiGraph
+        A directed graph representing an arborescence consisting of the
+        prefix tree generated by `paths`. Nodes are directed "downward",
+        from parent to child. A special "synthetic" root node is added
+        to be the parent of the first node in each path. A special
+        "synthetic" leaf node, the "nil" node `-1`, is added to be the child
+        of all nodes representing the last element in a path. (The
+        addition of this nil node technically makes this not an
+        arborescence but a directed acyclic graph; removing the nil node
+        makes it an arborescence.)
+
+
+    Notes
+    -----
+    The prefix tree is also known as a *trie*.
+
+
+    Examples
+    --------
+    Create a prefix tree from a list of strings with common prefixes::
+
+        >>> paths = ["ab", "abs", "ad"]
+        >>> T = nx.prefix_tree(paths)
+        >>> list(T.edges)
+        [(0, 1), (1, 2), (1, 4), (2, -1), (2, 3), (3, -1), (4, -1)]
+
+    The leaf nodes can be obtained as predecessors of the nil node::
+
+        >>> root, NIL = 0, -1
+        >>> list(T.predecessors(NIL))
+        [2, 3, 4]
+
+    To recover the original paths that generated the prefix tree,
+    traverse up the tree from the node `-1` to the node `0`::
+
+        >>> recovered = []
+        >>> for v in T.predecessors(NIL):
+        ...     prefix = ""
+        ...     while v != root:
+        ...         prefix = str(T.nodes[v]["source"]) + prefix
+        ...         v = next(T.predecessors(v))  # only one predecessor
+        ...     recovered.append(prefix)
+        >>> sorted(recovered)
+        ['ab', 'abs', 'ad']
+    """
+
+    def get_children(parent, paths):
+        children = defaultdict(list)
+        # Populate dictionary with key(s) as the child/children of the root and
+        # value(s) as the remaining paths of the corresponding child/children
+        for path in paths:
+            # If path is empty, we add an edge to the NIL node.
+            if not path:
+                tree.add_edge(parent, NIL)
+                continue
+            child, *rest = path
+            # `child` may exist as the head of more than one path in `paths`.
+            children[child].append(rest)
+        return children
+
+    # Initialize the prefix tree with a root node and a nil node.
+    tree = nx.DiGraph()
+    root = 0
+    tree.add_node(root, source=None)
+    NIL = -1
+    tree.add_node(NIL, source="NIL")
+    children = get_children(root, paths)
+    stack = [(root, iter(children.items()))]
+    while stack:
+        parent, remaining_children = stack[-1]
+        try:
+            child, remaining_paths = next(remaining_children)
+        # Pop item off stack if there are no remaining children
+        except StopIteration:
+            stack.pop()
+            continue
+        # We relabel each child with an unused name.
+        new_name = len(tree) - 1
+        # The "source" node attribute stores the original node name.
+        tree.add_node(new_name, source=child)
+        tree.add_edge(parent, new_name)
+        children = get_children(new_name, remaining_paths)
+        stack.append((new_name, iter(children.items())))
+
+    return tree
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def prefix_tree_recursive(paths):
+    """Recursively creates a directed prefix tree from a list of paths.
+
+    The original recursive version of prefix_tree for comparison. It is
+    the same algorithm but the recursion is unrolled onto a stack.
+
+    Usually the paths are described as strings or lists of integers.
+
+    A "prefix tree" represents the prefix structure of the strings.
+    Each node represents a prefix of some string. The root represents
+    the empty prefix with children for the single letter prefixes which
+    in turn have children for each double letter prefix starting with
+    the single letter corresponding to the parent node, and so on.
+
+    More generally the prefixes do not need to be strings. A prefix refers
+    to the start of a sequence. The root has children for each one element
+    prefix and they have children for each two element prefix that starts
+    with the one element sequence of the parent, and so on.
+
+    Note that this implementation uses integer nodes with an attribute.
+    Each node has an attribute "source" whose value is the original element
+    of the path to which this node corresponds. For example, suppose `paths`
+    consists of one path: "can". Then the nodes `[1, 2, 3]` which represent
+    this path have "source" values "c", "a" and "n".
+
+    All the descendants of a node have a common prefix in the sequence/path
+    associated with that node. From the returned tree, ehe prefix for each
+    node can be constructed by traversing the tree up to the root and
+    accumulating the "source" values along the way.
+
+    The root node is always `0` and has "source" attribute `None`.
+    The root is the only node with in-degree zero.
+    The nil node is always `-1` and has "source" attribute `"NIL"`.
+    The nil node is the only node with out-degree zero.
+
+
+    Parameters
+    ----------
+    paths: iterable of paths
+        An iterable of paths which are themselves sequences.
+        Matching prefixes among these sequences are identified with
+        nodes of the prefix tree. One leaf of the tree is associated
+        with each path. (Identical paths are associated with the same
+        leaf of the tree.)
+
+
+    Returns
+    -------
+    tree: DiGraph
+        A directed graph representing an arborescence consisting of the
+        prefix tree generated by `paths`. Nodes are directed "downward",
+        from parent to child. A special "synthetic" root node is added
+        to be the parent of the first node in each path. A special
+        "synthetic" leaf node, the "nil" node `-1`, is added to be the child
+        of all nodes representing the last element in a path. (The
+        addition of this nil node technically makes this not an
+        arborescence but a directed acyclic graph; removing the nil node
+        makes it an arborescence.)
+
+
+    Notes
+    -----
+    The prefix tree is also known as a *trie*.
+
+
+    Examples
+    --------
+    Create a prefix tree from a list of strings with common prefixes::
+
+        >>> paths = ["ab", "abs", "ad"]
+        >>> T = nx.prefix_tree(paths)
+        >>> list(T.edges)
+        [(0, 1), (1, 2), (1, 4), (2, -1), (2, 3), (3, -1), (4, -1)]
+
+    The leaf nodes can be obtained as predecessors of the nil node.
+
+        >>> root, NIL = 0, -1
+        >>> list(T.predecessors(NIL))
+        [2, 3, 4]
+
+    To recover the original paths that generated the prefix tree,
+    traverse up the tree from the node `-1` to the node `0`::
+
+        >>> recovered = []
+        >>> for v in T.predecessors(NIL):
+        ...     prefix = ""
+        ...     while v != root:
+        ...         prefix = str(T.nodes[v]["source"]) + prefix
+        ...         v = next(T.predecessors(v))  # only one predecessor
+        ...     recovered.append(prefix)
+        >>> sorted(recovered)
+        ['ab', 'abs', 'ad']
+    """
+
+    def _helper(paths, root, tree):
+        """Recursively create a trie from the given list of paths.
+
+        `paths` is a list of paths, each of which is itself a list of
+        nodes, relative to the given `root` (but not including it). This
+        list of paths will be interpreted as a tree-like structure, in
+        which two paths that share a prefix represent two branches of
+        the tree with the same initial segment.
+
+        `root` is the parent of the node at index 0 in each path.
+
+        `tree` is the "accumulator", the :class:`networkx.DiGraph`
+        representing the branching to which the new nodes and edges will
+        be added.
+
+        """
+        # For each path, remove the first node and make it a child of root.
+        # Any remaining paths then get processed recursively.
+        children = defaultdict(list)
+        for path in paths:
+            # If path is empty, we add an edge to the NIL node.
+            if not path:
+                tree.add_edge(root, NIL)
+                continue
+            child, *rest = path
+            # `child` may exist as the head of more than one path in `paths`.
+            children[child].append(rest)
+        # Add a node for each child, connect root, recurse to remaining paths
+        for child, remaining_paths in children.items():
+            # We relabel each child with an unused name.
+            new_name = len(tree) - 1
+            # The "source" node attribute stores the original node name.
+            tree.add_node(new_name, source=child)
+            tree.add_edge(root, new_name)
+            _helper(remaining_paths, new_name, tree)
+
+    # Initialize the prefix tree with a root node and a nil node.
+    tree = nx.DiGraph()
+    root = 0
+    tree.add_node(root, source=None)
+    NIL = -1
+    tree.add_node(NIL, source="NIL")
+    # Populate the tree.
+    _helper(paths, root, tree)
+    return tree
+
+
+@py_random_state("seed")
+@nx._dispatchable(graphs=None, returns_graph=True)
+def random_labeled_tree(n, *, seed=None):
+    """Returns a labeled tree on `n` nodes chosen uniformly at random.
+
+    Generating uniformly distributed random Prüfer sequences and
+    converting them into the corresponding trees is a straightforward
+    method of generating uniformly distributed random labeled trees.
+    This function implements this method.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes, greater than zero.
+    seed : random_state
+        Indicator of random number generation state.
+        See :ref:`Randomness`
+
+    Returns
+    -------
+     :class:`networkx.Graph`
+        A `networkx.Graph` with nodes in the set {0, …, *n* - 1}.
+
+    Raises
+    ------
+    NetworkXPointlessConcept
+        If `n` is zero (because the null graph is not a tree).
+
+    Examples
+    --------
+    >>> G = nx.random_labeled_tree(5, seed=42)
+    >>> nx.is_tree(G)
+    True
+    >>> G.edges
+    EdgeView([(0, 1), (0, 3), (0, 2), (2, 4)])
+
+    A tree with *arbitrarily directed* edges can be created by assigning
+    generated edges to a ``DiGraph``:
+
+    >>> DG = nx.DiGraph()
+    >>> DG.add_edges_from(G.edges)
+    >>> nx.is_tree(DG)
+    True
+    >>> DG.edges
+    OutEdgeView([(0, 1), (0, 3), (0, 2), (2, 4)])
+    """
+    # Cannot create a Prüfer sequence unless `n` is at least two.
+    if n == 0:
+        raise nx.NetworkXPointlessConcept("the null graph is not a tree")
+    if n == 1:
+        return nx.empty_graph(1)
+    return nx.from_prufer_sequence([seed.choice(range(n)) for i in range(n - 2)])
+
+
+@py_random_state("seed")
+@nx._dispatchable(graphs=None, returns_graph=True)
+def random_labeled_rooted_tree(n, *, seed=None):
+    """Returns a labeled rooted tree with `n` nodes.
+
+    The returned tree is chosen uniformly at random from all labeled rooted trees.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    :class:`networkx.Graph`
+        A `networkx.Graph` with integer nodes 0 <= node <= `n` - 1.
+        The root of the tree is selected uniformly from the nodes.
+        The "root" graph attribute identifies the root of the tree.
+
+    Notes
+    -----
+    This function returns the result of :func:`random_labeled_tree`
+    with a randomly selected root.
+
+    Raises
+    ------
+    NetworkXPointlessConcept
+        If `n` is zero (because the null graph is not a tree).
+    """
+    t = random_labeled_tree(n, seed=seed)
+    t.graph["root"] = seed.randint(0, n - 1)
+    return t
+
+
+@py_random_state("seed")
+@nx._dispatchable(graphs=None, returns_graph=True)
+def random_labeled_rooted_forest(n, *, seed=None):
+    """Returns a labeled rooted forest with `n` nodes.
+
+    The returned forest is chosen uniformly at random using a
+    generalization of Prüfer sequences [1]_ in the form described in [2]_.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes.
+    seed : random_state
+       See :ref:`Randomness`.
+
+    Returns
+    -------
+    :class:`networkx.Graph`
+        A `networkx.Graph` with integer nodes 0 <= node <= `n` - 1.
+        The "roots" graph attribute is a set of integers containing the roots.
+
+    References
+    ----------
+    .. [1] Knuth, Donald E. "Another Enumeration of Trees."
+        Canadian Journal of Mathematics, 20 (1968): 1077-1086.
+        https://doi.org/10.4153/CJM-1968-104-8
+    .. [2] Rubey, Martin. "Counting Spanning Trees". Diplomarbeit
+        zur Erlangung des akademischen Grades Magister der
+        Naturwissenschaften an der Formal- und Naturwissenschaftlichen
+        Fakultät der Universität Wien. Wien, May 2000.
+    """
+
+    # Select the number of roots by iterating over the cumulative count of trees
+    # with at most k roots
+    def _select_k(n, seed):
+        r = seed.randint(0, (n + 1) ** (n - 1) - 1)
+        cum_sum = 0
+        for k in range(1, n):
+            cum_sum += (factorial(n - 1) * n ** (n - k)) // (
+                factorial(k - 1) * factorial(n - k)
+            )
+            if r < cum_sum:
+                return k
+
+        return n
+
+    F = nx.empty_graph(n)
+    if n == 0:
+        F.graph["roots"] = {}
+        return F
+    # Select the number of roots k
+    k = _select_k(n, seed)
+    if k == n:
+        F.graph["roots"] = set(range(n))
+        return F  # Nothing to do
+    # Select the roots
+    roots = seed.sample(range(n), k)
+    # Nonroots
+    p = set(range(n)).difference(roots)
+    # Coding sequence
+    N = [seed.randint(0, n - 1) for i in range(n - k - 1)]
+    # Multiset of elements in N also in p
+    degree = Counter([x for x in N if x in p])
+    # Iterator over the elements of p with degree zero
+    iterator = iter(x for x in p if degree[x] == 0)
+    u = last = next(iterator)
+    # This loop is identical to that for Prüfer sequences,
+    # except that we can draw nodes only from p
+    for v in N:
+        F.add_edge(u, v)
+        degree[v] -= 1
+        if v < last and degree[v] == 0:
+            u = v
+        else:
+            last = u = next(iterator)
+
+    F.add_edge(u, roots[0])
+    F.graph["roots"] = set(roots)
+    return F
+
+
+# The following functions support generation of unlabeled trees and forests.
+
+
+def _to_nx(edges, n_nodes, root=None, roots=None):
+    """
+    Converts the (edges, n_nodes) input to a :class:`networkx.Graph`.
+    The (edges, n_nodes) input is a list of even length, where each pair
+    of consecutive integers represents an edge, and an integer `n_nodes`.
+    Integers in the list are elements of `range(n_nodes)`.
+
+    Parameters
+    ----------
+    edges : list of ints
+        The flattened list of edges of the graph.
+    n_nodes : int
+        The number of nodes of the graph.
+    root: int (default=None)
+        If not None, the "root" attribute of the graph will be set to this value.
+    roots: collection of ints (default=None)
+        If not None, he "roots" attribute of the graph will be set to this value.
+
+    Returns
+    -------
+    :class:`networkx.Graph`
+        The graph with `n_nodes` nodes and edges given by `edges`.
+    """
+    G = nx.empty_graph(n_nodes)
+    G.add_edges_from(edges)
+    if root is not None:
+        G.graph["root"] = root
+    if roots is not None:
+        G.graph["roots"] = roots
+    return G
+
+
+def _num_rooted_trees(n, cache_trees):
+    """Returns the number of unlabeled rooted trees with `n` nodes.
+
+    See also https://oeis.org/A000081.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes
+    cache_trees : list of ints
+        The $i$-th element is the number of unlabeled rooted trees with $i$ nodes,
+        which is used as a cache (and is extended to length $n+1$ if needed)
+
+    Returns
+    -------
+    int
+        The number of unlabeled rooted trees with `n` nodes.
+    """
+    for n_i in range(len(cache_trees), n + 1):
+        cache_trees.append(
+            sum(
+                [
+                    d * cache_trees[n_i - j * d] * cache_trees[d]
+                    for d in range(1, n_i)
+                    for j in range(1, (n_i - 1) // d + 1)
+                ]
+            )
+            // (n_i - 1)
+        )
+    return cache_trees[n]
+
+
+def _select_jd_trees(n, cache_trees, seed):
+    """Returns a pair $(j,d)$ with a specific probability
+
+    Given $n$, returns a pair of positive integers $(j,d)$ with the probability
+    specified in formula (5) of Chapter 29 of [1]_.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes
+    cache_trees : list of ints
+        Cache for :func:`_num_rooted_trees`.
+    seed : random_state
+       See :ref:`Randomness`.
+
+    Returns
+    -------
+    (int, int)
+        A pair of positive integers $(j,d)$ satisfying formula (5) of
+        Chapter 29 of [1]_.
+
+    References
+    ----------
+    .. [1] Nijenhuis, Albert, and Wilf, Herbert S.
+        "Combinatorial algorithms: for computers and calculators."
+        Academic Press, 1978.
+        https://doi.org/10.1016/C2013-0-11243-3
+    """
+    p = seed.randint(0, _num_rooted_trees(n, cache_trees) * (n - 1) - 1)
+    cumsum = 0
+    for d in range(n - 1, 0, -1):
+        for j in range(1, (n - 1) // d + 1):
+            cumsum += (
+                d
+                * _num_rooted_trees(n - j * d, cache_trees)
+                * _num_rooted_trees(d, cache_trees)
+            )
+            if p < cumsum:
+                return (j, d)
+
+
+def _random_unlabeled_rooted_tree(n, cache_trees, seed):
+    """Returns an unlabeled rooted tree with `n` nodes.
+
+    Returns an unlabeled rooted tree with `n` nodes chosen uniformly
+    at random using the "RANRUT" algorithm from [1]_.
+    The tree is returned in the form: (list_of_edges, number_of_nodes)
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes, greater than zero.
+    cache_trees : list ints
+        Cache for :func:`_num_rooted_trees`.
+    seed : random_state
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    (list_of_edges, number_of_nodes) : list, int
+        A random unlabeled rooted tree with `n` nodes as a 2-tuple
+        ``(list_of_edges, number_of_nodes)``.
+        The root is node 0.
+
+    References
+    ----------
+    .. [1] Nijenhuis, Albert, and Wilf, Herbert S.
+        "Combinatorial algorithms: for computers and calculators."
+        Academic Press, 1978.
+        https://doi.org/10.1016/C2013-0-11243-3
+    """
+    if n == 1:
+        edges, n_nodes = [], 1
+        return edges, n_nodes
+    if n == 2:
+        edges, n_nodes = [(0, 1)], 2
+        return edges, n_nodes
+
+    j, d = _select_jd_trees(n, cache_trees, seed)
+    t1, t1_nodes = _random_unlabeled_rooted_tree(n - j * d, cache_trees, seed)
+    t2, t2_nodes = _random_unlabeled_rooted_tree(d, cache_trees, seed)
+    t12 = [(0, t2_nodes * i + t1_nodes) for i in range(j)]
+    t1.extend(t12)
+    for _ in range(j):
+        t1.extend((n1 + t1_nodes, n2 + t1_nodes) for n1, n2 in t2)
+        t1_nodes += t2_nodes
+
+    return t1, t1_nodes
+
+
+@py_random_state("seed")
+@nx._dispatchable(graphs=None, returns_graph=True)
+def random_unlabeled_rooted_tree(n, *, number_of_trees=None, seed=None):
+    """Returns a number of unlabeled rooted trees uniformly at random
+
+    Returns one or more (depending on `number_of_trees`)
+    unlabeled rooted trees with `n` nodes drawn uniformly
+    at random.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes
+    number_of_trees : int or None (default)
+        If not None, this number of trees is generated and returned.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    :class:`networkx.Graph` or list of :class:`networkx.Graph`
+        A single `networkx.Graph` (or a list thereof, if `number_of_trees`
+        is specified) with nodes in the set {0, …, *n* - 1}.
+        The "root" graph attribute identifies the root of the tree.
+
+    Notes
+    -----
+    The trees are generated using the "RANRUT" algorithm from [1]_.
+    The algorithm needs to compute some counting functions
+    that are relatively expensive: in case several trees are needed,
+    it is advisable to use the `number_of_trees` optional argument
+    to reuse the counting functions.
+
+    Raises
+    ------
+    NetworkXPointlessConcept
+        If `n` is zero (because the null graph is not a tree).
+
+    References
+    ----------
+    .. [1] Nijenhuis, Albert, and Wilf, Herbert S.
+        "Combinatorial algorithms: for computers and calculators."
+        Academic Press, 1978.
+        https://doi.org/10.1016/C2013-0-11243-3
+    """
+    if n == 0:
+        raise nx.NetworkXPointlessConcept("the null graph is not a tree")
+    cache_trees = [0, 1]  # initial cache of number of rooted trees
+    if number_of_trees is None:
+        return _to_nx(*_random_unlabeled_rooted_tree(n, cache_trees, seed), root=0)
+    return [
+        _to_nx(*_random_unlabeled_rooted_tree(n, cache_trees, seed), root=0)
+        for i in range(number_of_trees)
+    ]
+
+
+def _num_rooted_forests(n, q, cache_forests):
+    """Returns the number of unlabeled rooted forests with `n` nodes, and with
+    no more than `q` nodes per tree. A recursive formula for this is (2) in
+    [1]_. This function is implemented using dynamic programming instead of
+    recursion.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes.
+    q : int
+        The maximum number of nodes for each tree of the forest.
+    cache_forests : list of ints
+        The $i$-th element is the number of unlabeled rooted forests with
+        $i$ nodes, and with no more than `q` nodes per tree; this is used
+        as a cache (and is extended to length `n` + 1 if needed).
+
+    Returns
+    -------
+    int
+        The number of unlabeled rooted forests with `n` nodes with no more than
+        `q` nodes per tree.
+
+    References
+    ----------
+    .. [1] Wilf, Herbert S. "The uniform selection of free trees."
+        Journal of Algorithms 2.2 (1981): 204-207.
+        https://doi.org/10.1016/0196-6774(81)90021-3
+    """
+    for n_i in range(len(cache_forests), n + 1):
+        q_i = min(n_i, q)
+        cache_forests.append(
+            sum(
+                [
+                    d * cache_forests[n_i - j * d] * cache_forests[d - 1]
+                    for d in range(1, q_i + 1)
+                    for j in range(1, n_i // d + 1)
+                ]
+            )
+            // n_i
+        )
+
+    return cache_forests[n]
+
+
+def _select_jd_forests(n, q, cache_forests, seed):
+    """Given `n` and `q`, returns a pair of positive integers $(j,d)$
+    such that $j\\leq d$, with probability satisfying (F1) of [1]_.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes.
+    q : int
+        The maximum number of nodes for each tree of the forest.
+    cache_forests : list of ints
+        Cache for :func:`_num_rooted_forests`.
+    seed : random_state
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    (int, int)
+        A pair of positive integers $(j,d)$
+
+    References
+    ----------
+    .. [1] Wilf, Herbert S. "The uniform selection of free trees."
+        Journal of Algorithms 2.2 (1981): 204-207.
+        https://doi.org/10.1016/0196-6774(81)90021-3
+    """
+    p = seed.randint(0, _num_rooted_forests(n, q, cache_forests) * n - 1)
+    cumsum = 0
+    for d in range(q, 0, -1):
+        for j in range(1, n // d + 1):
+            cumsum += (
+                d
+                * _num_rooted_forests(n - j * d, q, cache_forests)
+                * _num_rooted_forests(d - 1, q, cache_forests)
+            )
+            if p < cumsum:
+                return (j, d)
+
+
+def _random_unlabeled_rooted_forest(n, q, cache_trees, cache_forests, seed):
+    """Returns an unlabeled rooted forest with `n` nodes, and with no more
+    than `q` nodes per tree, drawn uniformly at random. It is an implementation
+    of the algorithm "Forest" of [1]_.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes.
+    q : int
+        The maximum number of nodes per tree.
+    cache_trees :
+        Cache for :func:`_num_rooted_trees`.
+    cache_forests :
+        Cache for :func:`_num_rooted_forests`.
+    seed : random_state
+       See :ref:`Randomness`.
+
+    Returns
+    -------
+    (edges, n, r) : (list, int, list)
+        The forest (edges, n) and a list r of root nodes.
+
+    References
+    ----------
+    .. [1] Wilf, Herbert S. "The uniform selection of free trees."
+        Journal of Algorithms 2.2 (1981): 204-207.
+        https://doi.org/10.1016/0196-6774(81)90021-3
+    """
+    if n == 0:
+        return ([], 0, [])
+
+    j, d = _select_jd_forests(n, q, cache_forests, seed)
+    t1, t1_nodes, r1 = _random_unlabeled_rooted_forest(
+        n - j * d, q, cache_trees, cache_forests, seed
+    )
+    t2, t2_nodes = _random_unlabeled_rooted_tree(d, cache_trees, seed)
+    for _ in range(j):
+        r1.append(t1_nodes)
+        t1.extend((n1 + t1_nodes, n2 + t1_nodes) for n1, n2 in t2)
+        t1_nodes += t2_nodes
+    return t1, t1_nodes, r1
+
+
+@py_random_state("seed")
+@nx._dispatchable(graphs=None, returns_graph=True)
+def random_unlabeled_rooted_forest(n, *, q=None, number_of_forests=None, seed=None):
+    """Returns a forest or list of forests selected at random.
+
+    Returns one or more (depending on `number_of_forests`)
+    unlabeled rooted forests with `n` nodes, and with no more than
+    `q` nodes per tree, drawn uniformly at random.
+    The "roots" graph attribute identifies the roots of the forest.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes
+    q : int or None (default)
+        The maximum number of nodes per tree.
+    number_of_forests : int or None (default)
+        If not None, this number of forests is generated and returned.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    :class:`networkx.Graph` or list of :class:`networkx.Graph`
+        A single `networkx.Graph` (or a list thereof, if `number_of_forests`
+        is specified) with nodes in the set {0, …, *n* - 1}.
+        The "roots" graph attribute is a set containing the roots
+        of the trees in the forest.
+
+    Notes
+    -----
+    This function implements the algorithm "Forest" of [1]_.
+    The algorithm needs to compute some counting functions
+    that are relatively expensive: in case several trees are needed,
+    it is advisable to use the `number_of_forests` optional argument
+    to reuse the counting functions.
+
+    Raises
+    ------
+    ValueError
+        If `n` is non-zero but `q` is zero.
+
+    References
+    ----------
+    .. [1] Wilf, Herbert S. "The uniform selection of free trees."
+        Journal of Algorithms 2.2 (1981): 204-207.
+        https://doi.org/10.1016/0196-6774(81)90021-3
+    """
+    if q is None:
+        q = n
+    if q == 0 and n != 0:
+        raise ValueError("q must be a positive integer if n is positive.")
+
+    cache_trees = [0, 1]  # initial cache of number of rooted trees
+    cache_forests = [1]  # initial cache of number of rooted forests
+
+    if number_of_forests is None:
+        g, nodes, rs = _random_unlabeled_rooted_forest(
+            n, q, cache_trees, cache_forests, seed
+        )
+        return _to_nx(g, nodes, roots=set(rs))
+
+    res = []
+    for i in range(number_of_forests):
+        g, nodes, rs = _random_unlabeled_rooted_forest(
+            n, q, cache_trees, cache_forests, seed
+        )
+        res.append(_to_nx(g, nodes, roots=set(rs)))
+    return res
+
+
+def _num_trees(n, cache_trees):
+    """Returns the number of unlabeled trees with `n` nodes.
+
+    See also https://oeis.org/A000055.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes.
+    cache_trees : list of ints
+        Cache for :func:`_num_rooted_trees`.
+
+    Returns
+    -------
+    int
+        The number of unlabeled trees with `n` nodes.
+    """
+    r = _num_rooted_trees(n, cache_trees) - sum(
+        [
+            _num_rooted_trees(j, cache_trees) * _num_rooted_trees(n - j, cache_trees)
+            for j in range(1, n // 2 + 1)
+        ]
+    )
+    if n % 2 == 0:
+        r += comb(_num_rooted_trees(n // 2, cache_trees) + 1, 2)
+    return r
+
+
+def _bicenter(n, cache, seed):
+    """Returns a bi-centroidal tree on `n` nodes drawn uniformly at random.
+
+    This function implements the algorithm Bicenter of [1]_.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes (must be even).
+    cache : list of ints.
+        Cache for :func:`_num_rooted_trees`.
+    seed : random_state
+        See :ref:`Randomness`
+
+    Returns
+    -------
+    (edges, n)
+        The tree as a list of edges and number of nodes.
+
+    References
+    ----------
+    .. [1] Wilf, Herbert S. "The uniform selection of free trees."
+        Journal of Algorithms 2.2 (1981): 204-207.
+        https://doi.org/10.1016/0196-6774(81)90021-3
+    """
+    t, t_nodes = _random_unlabeled_rooted_tree(n // 2, cache, seed)
+    if seed.randint(0, _num_rooted_trees(n // 2, cache)) == 0:
+        t2, t2_nodes = t, t_nodes
+    else:
+        t2, t2_nodes = _random_unlabeled_rooted_tree(n // 2, cache, seed)
+    t.extend([(n1 + (n // 2), n2 + (n // 2)) for n1, n2 in t2])
+    t.append((0, n // 2))
+    return t, t_nodes + t2_nodes
+
+
+def _random_unlabeled_tree(n, cache_trees, cache_forests, seed):
+    """Returns a tree on `n` nodes drawn uniformly at random.
+    It implements the Wilf's algorithm "Free" of [1]_.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes, greater than zero.
+    cache_trees : list of ints
+        Cache for :func:`_num_rooted_trees`.
+    cache_forests : list of ints
+        Cache for :func:`_num_rooted_forests`.
+    seed : random_state
+        Indicator of random number generation state.
+        See :ref:`Randomness`
+
+    Returns
+    -------
+    (edges, n)
+        The tree as a list of edges and number of nodes.
+
+    References
+    ----------
+    .. [1] Wilf, Herbert S. "The uniform selection of free trees."
+        Journal of Algorithms 2.2 (1981): 204-207.
+        https://doi.org/10.1016/0196-6774(81)90021-3
+    """
+    if n % 2 == 1:
+        p = 0
+    else:
+        p = comb(_num_rooted_trees(n // 2, cache_trees) + 1, 2)
+    if seed.randint(0, _num_trees(n, cache_trees) - 1) < p:
+        return _bicenter(n, cache_trees, seed)
+    else:
+        f, n_f, r = _random_unlabeled_rooted_forest(
+            n - 1, (n - 1) // 2, cache_trees, cache_forests, seed
+        )
+        for i in r:
+            f.append((i, n_f))
+        return f, n_f + 1
+
+
+@py_random_state("seed")
+@nx._dispatchable(graphs=None, returns_graph=True)
+def random_unlabeled_tree(n, *, number_of_trees=None, seed=None):
+    """Returns a tree or list of trees chosen randomly.
+
+    Returns one or more (depending on `number_of_trees`)
+    unlabeled trees with `n` nodes drawn uniformly at random.
+
+    Parameters
+    ----------
+    n : int
+        The number of nodes
+    number_of_trees : int or None (default)
+        If not None, this number of trees is generated and returned.
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    :class:`networkx.Graph` or list of :class:`networkx.Graph`
+        A single `networkx.Graph` (or a list thereof, if
+        `number_of_trees` is specified) with nodes in the set {0, …, *n* - 1}.
+
+    Raises
+    ------
+    NetworkXPointlessConcept
+        If `n` is zero (because the null graph is not a tree).
+
+    Notes
+    -----
+    This function generates an unlabeled tree uniformly at random using
+    Wilf's algorithm "Free" of [1]_. The algorithm needs to
+    compute some counting functions that are relatively expensive:
+    in case several trees are needed, it is advisable to use the
+    `number_of_trees` optional argument to reuse the counting
+    functions.
+
+    References
+    ----------
+    .. [1] Wilf, Herbert S. "The uniform selection of free trees."
+        Journal of Algorithms 2.2 (1981): 204-207.
+        https://doi.org/10.1016/0196-6774(81)90021-3
+    """
+    if n == 0:
+        raise nx.NetworkXPointlessConcept("the null graph is not a tree")
+
+    cache_trees = [0, 1]  # initial cache of number of rooted trees
+    cache_forests = [1]  # initial cache of number of rooted forests
+    if number_of_trees is None:
+        return _to_nx(*_random_unlabeled_tree(n, cache_trees, cache_forests, seed))
+    else:
+        return [
+            _to_nx(*_random_unlabeled_tree(n, cache_trees, cache_forests, seed))
+            for i in range(number_of_trees)
+        ]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/triads.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/triads.py
new file mode 100644
index 0000000000000000000000000000000000000000..09b722dd1bd49dddae16086115d170ec989f8b06
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/generators/triads.py
@@ -0,0 +1,94 @@
+# See https://github.com/networkx/networkx/pull/1474
+# Copyright 2011 Reya Group 
+# Copyright 2011 Alex Levenson 
+# Copyright 2011 Diederik van Liere 
+"""Functions that generate the triad graphs, that is, the possible
+digraphs on three nodes.
+
+"""
+
+import networkx as nx
+from networkx.classes import DiGraph
+
+__all__ = ["triad_graph"]
+
+#: Dictionary mapping triad name to list of directed edges in the
+#: digraph representation of that triad (with nodes 'a', 'b', and 'c').
+TRIAD_EDGES = {
+    "003": [],
+    "012": ["ab"],
+    "102": ["ab", "ba"],
+    "021D": ["ba", "bc"],
+    "021U": ["ab", "cb"],
+    "021C": ["ab", "bc"],
+    "111D": ["ac", "ca", "bc"],
+    "111U": ["ac", "ca", "cb"],
+    "030T": ["ab", "cb", "ac"],
+    "030C": ["ba", "cb", "ac"],
+    "201": ["ab", "ba", "ac", "ca"],
+    "120D": ["bc", "ba", "ac", "ca"],
+    "120U": ["ab", "cb", "ac", "ca"],
+    "120C": ["ab", "bc", "ac", "ca"],
+    "210": ["ab", "bc", "cb", "ac", "ca"],
+    "300": ["ab", "ba", "bc", "cb", "ac", "ca"],
+}
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def triad_graph(triad_name):
+    """Returns the triad graph with the given name.
+
+    Each string in the following tuple is a valid triad name::
+
+        (
+            "003",
+            "012",
+            "102",
+            "021D",
+            "021U",
+            "021C",
+            "111D",
+            "111U",
+            "030T",
+            "030C",
+            "201",
+            "120D",
+            "120U",
+            "120C",
+            "210",
+            "300",
+        )
+
+    Each triad name corresponds to one of the possible valid digraph on
+    three nodes.
+
+    Parameters
+    ----------
+    triad_name : string
+        The name of a triad, as described above.
+
+    Returns
+    -------
+    :class:`~networkx.DiGraph`
+        The digraph on three nodes with the given name. The nodes of the
+        graph are the single-character strings 'a', 'b', and 'c'.
+
+    Raises
+    ------
+    ValueError
+        If `triad_name` is not the name of a triad.
+
+    See also
+    --------
+    triadic_census
+
+    """
+    if triad_name not in TRIAD_EDGES:
+        raise ValueError(
+            f'unknown triad name "{triad_name}"; use one of the triad names'
+            " in the TRIAD_NAMES constant"
+        )
+    G = DiGraph()
+    G.add_nodes_from("abc")
+    G.add_edges_from(TRIAD_EDGES[triad_name])
+    return G
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/linalg/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/linalg/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..119db185a1ae440fd2cdb6c7f531331642313c34
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/linalg/__init__.py
@@ -0,0 +1,13 @@
+from networkx.linalg.attrmatrix import *
+from networkx.linalg import attrmatrix
+from networkx.linalg.spectrum import *
+from networkx.linalg import spectrum
+from networkx.linalg.graphmatrix import *
+from networkx.linalg import graphmatrix
+from networkx.linalg.laplacianmatrix import *
+from networkx.linalg import laplacianmatrix
+from networkx.linalg.algebraicconnectivity import *
+from networkx.linalg.modularitymatrix import *
+from networkx.linalg import modularitymatrix
+from networkx.linalg.bethehessianmatrix import *
+from networkx.linalg import bethehessianmatrix
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/linalg/algebraicconnectivity.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/linalg/algebraicconnectivity.py
new file mode 100644
index 0000000000000000000000000000000000000000..c7bcf4384802c932d8cda0b579295a4fd3031951
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/linalg/algebraicconnectivity.py
@@ -0,0 +1,650 @@
+"""
+Algebraic connectivity and Fiedler vectors of undirected graphs.
+"""
+
+import networkx as nx
+from networkx.utils import (
+    not_implemented_for,
+    np_random_state,
+    reverse_cuthill_mckee_ordering,
+)
+
+__all__ = [
+    "algebraic_connectivity",
+    "fiedler_vector",
+    "spectral_ordering",
+    "spectral_bisection",
+]
+
+
+class _PCGSolver:
+    """Preconditioned conjugate gradient method.
+
+    To solve Ax = b:
+        M = A.diagonal() # or some other preconditioner
+        solver = _PCGSolver(lambda x: A * x, lambda x: M * x)
+        x = solver.solve(b)
+
+    The inputs A and M are functions which compute
+    matrix multiplication on the argument.
+    A - multiply by the matrix A in Ax=b
+    M - multiply by M, the preconditioner surrogate for A
+
+    Warning: There is no limit on number of iterations.
+    """
+
+    def __init__(self, A, M):
+        self._A = A
+        self._M = M
+
+    def solve(self, B, tol):
+        import numpy as np
+
+        # Densifying step - can this be kept sparse?
+        B = np.asarray(B)
+        X = np.ndarray(B.shape, order="F")
+        for j in range(B.shape[1]):
+            X[:, j] = self._solve(B[:, j], tol)
+        return X
+
+    def _solve(self, b, tol):
+        import numpy as np
+        import scipy as sp
+
+        A = self._A
+        M = self._M
+        tol *= sp.linalg.blas.dasum(b)
+        # Initialize.
+        x = np.zeros(b.shape)
+        r = b.copy()
+        z = M(r)
+        rz = sp.linalg.blas.ddot(r, z)
+        p = z.copy()
+        # Iterate.
+        while True:
+            Ap = A(p)
+            alpha = rz / sp.linalg.blas.ddot(p, Ap)
+            x = sp.linalg.blas.daxpy(p, x, a=alpha)
+            r = sp.linalg.blas.daxpy(Ap, r, a=-alpha)
+            if sp.linalg.blas.dasum(r) < tol:
+                return x
+            z = M(r)
+            beta = sp.linalg.blas.ddot(r, z)
+            beta, rz = beta / rz, beta
+            p = sp.linalg.blas.daxpy(p, z, a=beta)
+
+
+class _LUSolver:
+    """LU factorization.
+
+    To solve Ax = b:
+        solver = _LUSolver(A)
+        x = solver.solve(b)
+
+    optional argument `tol` on solve method is ignored but included
+    to match _PCGsolver API.
+    """
+
+    def __init__(self, A):
+        import scipy as sp
+
+        self._LU = sp.sparse.linalg.splu(
+            A,
+            permc_spec="MMD_AT_PLUS_A",
+            diag_pivot_thresh=0.0,
+            options={"Equil": True, "SymmetricMode": True},
+        )
+
+    def solve(self, B, tol=None):
+        import numpy as np
+
+        B = np.asarray(B)
+        X = np.ndarray(B.shape, order="F")
+        for j in range(B.shape[1]):
+            X[:, j] = self._LU.solve(B[:, j])
+        return X
+
+
+def _preprocess_graph(G, weight):
+    """Compute edge weights and eliminate zero-weight edges."""
+    if G.is_directed():
+        H = nx.MultiGraph()
+        H.add_nodes_from(G)
+        H.add_weighted_edges_from(
+            ((u, v, e.get(weight, 1.0)) for u, v, e in G.edges(data=True) if u != v),
+            weight=weight,
+        )
+        G = H
+    if not G.is_multigraph():
+        edges = (
+            (u, v, abs(e.get(weight, 1.0))) for u, v, e in G.edges(data=True) if u != v
+        )
+    else:
+        edges = (
+            (u, v, sum(abs(e.get(weight, 1.0)) for e in G[u][v].values()))
+            for u, v in G.edges()
+            if u != v
+        )
+    H = nx.Graph()
+    H.add_nodes_from(G)
+    H.add_weighted_edges_from((u, v, e) for u, v, e in edges if e != 0)
+    return H
+
+
+def _rcm_estimate(G, nodelist):
+    """Estimate the Fiedler vector using the reverse Cuthill-McKee ordering."""
+    import numpy as np
+
+    G = G.subgraph(nodelist)
+    order = reverse_cuthill_mckee_ordering(G)
+    n = len(nodelist)
+    index = dict(zip(nodelist, range(n)))
+    x = np.ndarray(n, dtype=float)
+    for i, u in enumerate(order):
+        x[index[u]] = i
+    x -= (n - 1) / 2.0
+    return x
+
+
+def _tracemin_fiedler(L, X, normalized, tol, method):
+    """Compute the Fiedler vector of L using the TraceMIN-Fiedler algorithm.
+
+    The Fiedler vector of a connected undirected graph is the eigenvector
+    corresponding to the second smallest eigenvalue of the Laplacian matrix
+    of the graph. This function starts with the Laplacian L, not the Graph.
+
+    Parameters
+    ----------
+    L : Laplacian of a possibly weighted or normalized, but undirected graph
+
+    X : Initial guess for a solution. Usually a matrix of random numbers.
+        This function allows more than one column in X to identify more than
+        one eigenvector if desired.
+
+    normalized : bool
+        Whether the normalized Laplacian matrix is used.
+
+    tol : float
+        Tolerance of relative residual in eigenvalue computation.
+        Warning: There is no limit on number of iterations.
+
+    method : string
+        Should be 'tracemin_pcg' or 'tracemin_lu'.
+        Otherwise exception is raised.
+
+    Returns
+    -------
+    sigma, X : Two NumPy arrays of floats.
+        The lowest eigenvalues and corresponding eigenvectors of L.
+        The size of input X determines the size of these outputs.
+        As this is for Fiedler vectors, the zero eigenvalue (and
+        constant eigenvector) are avoided.
+    """
+    import numpy as np
+    import scipy as sp
+
+    n = X.shape[0]
+
+    if normalized:
+        # Form the normalized Laplacian matrix and determine the eigenvector of
+        # its nullspace.
+        e = np.sqrt(L.diagonal())
+        D = sp.sparse.dia_array((1 / e, 0), shape=(n, n)).tocsr()
+        L = D @ L @ D
+        e *= 1.0 / np.linalg.norm(e, 2)
+
+    if normalized:
+
+        def project(X):
+            """Make X orthogonal to the nullspace of L."""
+            X = np.asarray(X)
+            for j in range(X.shape[1]):
+                X[:, j] -= (X[:, j] @ e) * e
+
+    else:
+
+        def project(X):
+            """Make X orthogonal to the nullspace of L."""
+            X = np.asarray(X)
+            for j in range(X.shape[1]):
+                X[:, j] -= X[:, j].sum() / n
+
+    if method == "tracemin_pcg":
+        D = L.diagonal().astype(float)
+        solver = _PCGSolver(lambda x: L @ x, lambda x: D * x)
+    elif method == "tracemin_lu":
+        # Convert A to CSC to suppress SparseEfficiencyWarning.
+        A = sp.sparse.csc_array(L, dtype=float, copy=True)
+        # Force A to be nonsingular. Since A is the Laplacian matrix of a
+        # connected graph, its rank deficiency is one, and thus one diagonal
+        # element needs to modified. Changing to infinity forces a zero in the
+        # corresponding element in the solution.
+        i = (A.indptr[1:] - A.indptr[:-1]).argmax()
+        A[i, i] = np.inf
+        solver = _LUSolver(A)
+    else:
+        raise nx.NetworkXError(f"Unknown linear system solver: {method}")
+
+    # Initialize.
+    Lnorm = abs(L).sum(axis=1).flatten().max()
+    project(X)
+    W = np.ndarray(X.shape, order="F")
+
+    while True:
+        # Orthonormalize X.
+        X = np.linalg.qr(X)[0]
+        # Compute iteration matrix H.
+        W[:, :] = L @ X
+        H = X.T @ W
+        sigma, Y = sp.linalg.eigh(H, overwrite_a=True)
+        # Compute the Ritz vectors.
+        X = X @ Y
+        # Test for convergence exploiting the fact that L * X == W * Y.
+        res = sp.linalg.blas.dasum(W @ Y[:, 0] - sigma[0] * X[:, 0]) / Lnorm
+        if res < tol:
+            break
+        # Compute X = L \ X / (X' * (L \ X)).
+        # L \ X can have an arbitrary projection on the nullspace of L,
+        # which will be eliminated.
+        W[:, :] = solver.solve(X, tol)
+        X = (sp.linalg.inv(W.T @ X) @ W.T).T  # Preserves Fortran storage order.
+        project(X)
+
+    return sigma, np.asarray(X)
+
+
+def _get_fiedler_func(method):
+    """Returns a function that solves the Fiedler eigenvalue problem."""
+    import numpy as np
+
+    if method == "tracemin":  # old style keyword `.
+
+    Returns
+    -------
+    algebraic_connectivity : float
+        Algebraic connectivity.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If G is directed.
+
+    NetworkXError
+        If G has less than two nodes.
+
+    Notes
+    -----
+    Edge weights are interpreted by their absolute values. For MultiGraph's,
+    weights of parallel edges are summed. Zero-weighted edges are ignored.
+
+    See Also
+    --------
+    laplacian_matrix
+
+    Examples
+    --------
+    For undirected graphs algebraic connectivity can tell us if a graph is connected or not
+    `G` is connected iff  ``algebraic_connectivity(G) > 0``:
+
+    >>> G = nx.complete_graph(5)
+    >>> nx.algebraic_connectivity(G) > 0
+    True
+    >>> G.add_node(10)  # G is no longer connected
+    >>> nx.algebraic_connectivity(G) > 0
+    False
+
+    """
+    if len(G) < 2:
+        raise nx.NetworkXError("graph has less than two nodes.")
+    G = _preprocess_graph(G, weight)
+    if not nx.is_connected(G):
+        return 0.0
+
+    L = nx.laplacian_matrix(G)
+    if L.shape[0] == 2:
+        return 2.0 * float(L[0, 0]) if not normalized else 2.0
+
+    find_fiedler = _get_fiedler_func(method)
+    x = None if method != "lobpcg" else _rcm_estimate(G, G)
+    sigma, fiedler = find_fiedler(L, x, normalized, tol, seed)
+    return float(sigma)
+
+
+@not_implemented_for("directed")
+@np_random_state(5)
+@nx._dispatchable(edge_attrs="weight")
+def fiedler_vector(
+    G, weight="weight", normalized=False, tol=1e-8, method="tracemin_pcg", seed=None
+):
+    """Returns the Fiedler vector of a connected undirected graph.
+
+    The Fiedler vector of a connected undirected graph is the eigenvector
+    corresponding to the second smallest eigenvalue of the Laplacian matrix
+    of the graph.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        An undirected graph.
+
+    weight : object, optional (default: None)
+        The data key used to determine the weight of each edge. If None, then
+        each edge has unit weight.
+
+    normalized : bool, optional (default: False)
+        Whether the normalized Laplacian matrix is used.
+
+    tol : float, optional (default: 1e-8)
+        Tolerance of relative residual in eigenvalue computation.
+
+    method : string, optional (default: 'tracemin_pcg')
+        Method of eigenvalue computation. It must be one of the tracemin
+        options shown below (TraceMIN), 'lanczos' (Lanczos iteration)
+        or 'lobpcg' (LOBPCG).
+
+        The TraceMIN algorithm uses a linear system solver. The following
+        values allow specifying the solver to be used.
+
+        =============== ========================================
+        Value           Solver
+        =============== ========================================
+        'tracemin_pcg'  Preconditioned conjugate gradient method
+        'tracemin_lu'   LU factorization
+        =============== ========================================
+
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    fiedler_vector : NumPy array of floats.
+        Fiedler vector.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If G is directed.
+
+    NetworkXError
+        If G has less than two nodes or is not connected.
+
+    Notes
+    -----
+    Edge weights are interpreted by their absolute values. For MultiGraph's,
+    weights of parallel edges are summed. Zero-weighted edges are ignored.
+
+    See Also
+    --------
+    laplacian_matrix
+
+    Examples
+    --------
+    Given a connected graph the signs of the values in the Fiedler vector can be
+    used to partition the graph into two components.
+
+    >>> G = nx.barbell_graph(5, 0)
+    >>> nx.fiedler_vector(G, normalized=True, seed=1)
+    array([-0.32864129, -0.32864129, -0.32864129, -0.32864129, -0.26072899,
+            0.26072899,  0.32864129,  0.32864129,  0.32864129,  0.32864129])
+
+    The connected components are the two 5-node cliques of the barbell graph.
+    """
+    import numpy as np
+
+    if len(G) < 2:
+        raise nx.NetworkXError("graph has less than two nodes.")
+    G = _preprocess_graph(G, weight)
+    if not nx.is_connected(G):
+        raise nx.NetworkXError("graph is not connected.")
+
+    if len(G) == 2:
+        return np.array([1.0, -1.0])
+
+    find_fiedler = _get_fiedler_func(method)
+    L = nx.laplacian_matrix(G)
+    x = None if method != "lobpcg" else _rcm_estimate(G, G)
+    sigma, fiedler = find_fiedler(L, x, normalized, tol, seed)
+    return fiedler
+
+
+@np_random_state(5)
+@nx._dispatchable(edge_attrs="weight")
+def spectral_ordering(
+    G, weight="weight", normalized=False, tol=1e-8, method="tracemin_pcg", seed=None
+):
+    """Compute the spectral_ordering of a graph.
+
+    The spectral ordering of a graph is an ordering of its nodes where nodes
+    in the same weakly connected components appear contiguous and ordered by
+    their corresponding elements in the Fiedler vector of the component.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        A graph.
+
+    weight : object, optional (default: None)
+        The data key used to determine the weight of each edge. If None, then
+        each edge has unit weight.
+
+    normalized : bool, optional (default: False)
+        Whether the normalized Laplacian matrix is used.
+
+    tol : float, optional (default: 1e-8)
+        Tolerance of relative residual in eigenvalue computation.
+
+    method : string, optional (default: 'tracemin_pcg')
+        Method of eigenvalue computation. It must be one of the tracemin
+        options shown below (TraceMIN), 'lanczos' (Lanczos iteration)
+        or 'lobpcg' (LOBPCG).
+
+        The TraceMIN algorithm uses a linear system solver. The following
+        values allow specifying the solver to be used.
+
+        =============== ========================================
+        Value           Solver
+        =============== ========================================
+        'tracemin_pcg'  Preconditioned conjugate gradient method
+        'tracemin_lu'   LU factorization
+        =============== ========================================
+
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    spectral_ordering : NumPy array of floats.
+        Spectral ordering of nodes.
+
+    Raises
+    ------
+    NetworkXError
+        If G is empty.
+
+    Notes
+    -----
+    Edge weights are interpreted by their absolute values. For MultiGraph's,
+    weights of parallel edges are summed. Zero-weighted edges are ignored.
+
+    See Also
+    --------
+    laplacian_matrix
+    """
+    if len(G) == 0:
+        raise nx.NetworkXError("graph is empty.")
+    G = _preprocess_graph(G, weight)
+
+    find_fiedler = _get_fiedler_func(method)
+    order = []
+    for component in nx.connected_components(G):
+        size = len(component)
+        if size > 2:
+            L = nx.laplacian_matrix(G, component)
+            x = None if method != "lobpcg" else _rcm_estimate(G, component)
+            sigma, fiedler = find_fiedler(L, x, normalized, tol, seed)
+            sort_info = zip(fiedler, range(size), component)
+            order.extend(u for x, c, u in sorted(sort_info))
+        else:
+            order.extend(component)
+
+    return order
+
+
+@nx._dispatchable(edge_attrs="weight")
+def spectral_bisection(
+    G, weight="weight", normalized=False, tol=1e-8, method="tracemin_pcg", seed=None
+):
+    """Bisect the graph using the Fiedler vector.
+
+    This method uses the Fiedler vector to bisect a graph.
+    The partition is defined by the nodes which are associated with
+    either positive or negative values in the vector.
+
+    Parameters
+    ----------
+    G : NetworkX Graph
+
+    weight : str, optional (default: weight)
+        The data key used to determine the weight of each edge. If None, then
+        each edge has unit weight.
+
+    normalized : bool, optional (default: False)
+        Whether the normalized Laplacian matrix is used.
+
+    tol : float, optional (default: 1e-8)
+        Tolerance of relative residual in eigenvalue computation.
+
+    method : string, optional (default: 'tracemin_pcg')
+        Method of eigenvalue computation. It must be one of the tracemin
+        options shown below (TraceMIN), 'lanczos' (Lanczos iteration)
+        or 'lobpcg' (LOBPCG).
+
+        The TraceMIN algorithm uses a linear system solver. The following
+        values allow specifying the solver to be used.
+
+        =============== ========================================
+        Value           Solver
+        =============== ========================================
+        'tracemin_pcg'  Preconditioned conjugate gradient method
+        'tracemin_lu'   LU factorization
+        =============== ========================================
+
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    bisection : tuple of sets
+        Sets with the bisection of nodes
+
+    Examples
+    --------
+    >>> G = nx.barbell_graph(3, 0)
+    >>> nx.spectral_bisection(G)
+    ({0, 1, 2}, {3, 4, 5})
+
+    References
+    ----------
+    .. [1] M. E. J Newman 'Networks: An Introduction', pages 364-370
+       Oxford University Press 2011.
+    """
+    import numpy as np
+
+    v = nx.fiedler_vector(G, weight, normalized, tol, method, seed)
+    nodes = np.array(list(G))
+    pos_vals = v >= 0
+
+    return set(nodes[~pos_vals].tolist()), set(nodes[pos_vals].tolist())
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/linalg/attrmatrix.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/linalg/attrmatrix.py
new file mode 100644
index 0000000000000000000000000000000000000000..989e8ff5798e3d778dca6c13d762b09a3dd58bd7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/linalg/attrmatrix.py
@@ -0,0 +1,466 @@
+"""
+Functions for constructing matrix-like objects from graph attributes.
+"""
+
+import networkx as nx
+
+__all__ = ["attr_matrix", "attr_sparse_matrix"]
+
+
+def _node_value(G, node_attr):
+    """Returns a function that returns a value from G.nodes[u].
+
+    We return a function expecting a node as its sole argument. Then, in the
+    simplest scenario, the returned function will return G.nodes[u][node_attr].
+    However, we also handle the case when `node_attr` is None (returns the node)
+    or when `node_attr` is a function itself.
+
+    Parameters
+    ----------
+    G : graph
+        A NetworkX graph
+
+    node_attr : {None, str, callable}
+        Specification of how the value of the node attribute should be obtained
+        from the node attribute dictionary.
+
+    Returns
+    -------
+    value : function
+        A function expecting a node as its sole argument. The function will
+        returns a value from G.nodes[u] that depends on `edge_attr`.
+
+    """
+    if node_attr is None:
+
+        def value(u):
+            return u
+
+    elif not callable(node_attr):
+        # assume it is a key for the node attribute dictionary
+        def value(u):
+            return G.nodes[u][node_attr]
+
+    else:
+        # Advanced:  Allow users to specify something else.
+        #
+        # For example,
+        #     node_attr = lambda u: G.nodes[u].get('size', .5) * 3
+        #
+        value = node_attr
+
+    return value
+
+
+def _edge_value(G, edge_attr):
+    """Returns a function that returns a value from G[u][v].
+
+    Suppose there exists an edge between u and v.  Then we return a function
+    expecting u and v as arguments.  For Graph and DiGraph, G[u][v] is
+    the edge attribute dictionary, and the function (essentially) returns
+    G[u][v][edge_attr].  However, we also handle cases when `edge_attr` is None
+    and when it is a function itself. For MultiGraph and MultiDiGraph, G[u][v]
+    is a dictionary of all edges between u and v.  In this case, the returned
+    function sums the value of `edge_attr` for every edge between u and v.
+
+    Parameters
+    ----------
+    G : graph
+       A NetworkX graph
+
+    edge_attr : {None, str, callable}
+        Specification of how the value of the edge attribute should be obtained
+        from the edge attribute dictionary, G[u][v].  For multigraphs, G[u][v]
+        is a dictionary of all the edges between u and v.  This allows for
+        special treatment of multiedges.
+
+    Returns
+    -------
+    value : function
+        A function expecting two nodes as parameters. The nodes should
+        represent the from- and to- node of an edge. The function will
+        return a value from G[u][v] that depends on `edge_attr`.
+
+    """
+
+    if edge_attr is None:
+        # topological count of edges
+
+        if G.is_multigraph():
+
+            def value(u, v):
+                return len(G[u][v])
+
+        else:
+
+            def value(u, v):
+                return 1
+
+    elif not callable(edge_attr):
+        # assume it is a key for the edge attribute dictionary
+
+        if edge_attr == "weight":
+            # provide a default value
+            if G.is_multigraph():
+
+                def value(u, v):
+                    return sum(d.get(edge_attr, 1) for d in G[u][v].values())
+
+            else:
+
+                def value(u, v):
+                    return G[u][v].get(edge_attr, 1)
+
+        else:
+            # otherwise, the edge attribute MUST exist for each edge
+            if G.is_multigraph():
+
+                def value(u, v):
+                    return sum(d[edge_attr] for d in G[u][v].values())
+
+            else:
+
+                def value(u, v):
+                    return G[u][v][edge_attr]
+
+    else:
+        # Advanced:  Allow users to specify something else.
+        #
+        # Alternative default value:
+        #     edge_attr = lambda u,v: G[u][v].get('thickness', .5)
+        #
+        # Function on an attribute:
+        #     edge_attr = lambda u,v: abs(G[u][v]['weight'])
+        #
+        # Handle Multi(Di)Graphs differently:
+        #     edge_attr = lambda u,v: numpy.prod([d['size'] for d in G[u][v].values()])
+        #
+        # Ignore multiple edges
+        #     edge_attr = lambda u,v: 1 if len(G[u][v]) else 0
+        #
+        value = edge_attr
+
+    return value
+
+
+@nx._dispatchable(edge_attrs={"edge_attr": None}, node_attrs="node_attr")
+def attr_matrix(
+    G,
+    edge_attr=None,
+    node_attr=None,
+    normalized=False,
+    rc_order=None,
+    dtype=None,
+    order=None,
+):
+    """Returns the attribute matrix using attributes from `G` as a numpy array.
+
+    If only `G` is passed in, then the adjacency matrix is constructed.
+
+    Let A be a discrete set of values for the node attribute `node_attr`. Then
+    the elements of A represent the rows and columns of the constructed matrix.
+    Now, iterate through every edge e=(u,v) in `G` and consider the value
+    of the edge attribute `edge_attr`.  If ua and va are the values of the
+    node attribute `node_attr` for u and v, respectively, then the value of
+    the edge attribute is added to the matrix element at (ua, va).
+
+    Parameters
+    ----------
+    G : graph
+        The NetworkX graph used to construct the attribute matrix.
+
+    edge_attr : str, optional (default: number of edges for each matrix element)
+        Each element of the matrix represents a running total of the
+        specified edge attribute for edges whose node attributes correspond
+        to the rows/cols of the matrix. The attribute must be present for
+        all edges in the graph. If no attribute is specified, then we
+        just count the number of edges whose node attributes correspond
+        to the matrix element.
+
+    node_attr : str, optional (default: use nodes of the graph)
+        Each row and column in the matrix represents a particular value
+        of the node attribute.  The attribute must be present for all nodes
+        in the graph. Note, the values of this attribute should be reliably
+        hashable. So, float values are not recommended. If no attribute is
+        specified, then the rows and columns will be the nodes of the graph.
+
+    normalized : bool, optional (default: False)
+        If True, then each row is normalized by the summation of its values.
+
+    rc_order : list, optional (default: order of nodes in G)
+        A list of the node attribute values. This list specifies the ordering
+        of rows and columns of the array. If no ordering is provided, then
+        the ordering will be the same as the node order in `G`.
+        When `rc_order` is `None`, the function returns a 2-tuple ``(matrix, ordering)``
+
+    Other Parameters
+    ----------------
+    dtype : NumPy data-type, optional
+        A valid NumPy dtype used to initialize the array. Keep in mind certain
+        dtypes can yield unexpected results if the array is to be normalized.
+        The parameter is passed to numpy.zeros(). If unspecified, the NumPy
+        default is used.
+
+    order : {'C', 'F'}, optional
+        Whether to store multidimensional data in C- or Fortran-contiguous
+        (row- or column-wise) order in memory. This parameter is passed to
+        numpy.zeros(). If unspecified, the NumPy default is used.
+
+    Returns
+    -------
+    M : 2D NumPy ndarray
+        The attribute matrix.
+
+    ordering : list
+        If `rc_order` was specified, then only the attribute matrix is returned.
+        However, if `rc_order` was None, then the ordering used to construct
+        the matrix is returned as well.
+
+    Examples
+    --------
+    Construct an adjacency matrix:
+
+    >>> G = nx.Graph()
+    >>> G.add_edge(0, 1, thickness=1, weight=3)
+    >>> G.add_edge(0, 2, thickness=2)
+    >>> G.add_edge(1, 2, thickness=3)
+    >>> nx.attr_matrix(G, rc_order=[0, 1, 2])
+    array([[0., 1., 1.],
+           [1., 0., 1.],
+           [1., 1., 0.]])
+
+    Alternatively, we can obtain the matrix describing edge thickness.
+
+    >>> nx.attr_matrix(G, edge_attr="thickness", rc_order=[0, 1, 2])
+    array([[0., 1., 2.],
+           [1., 0., 3.],
+           [2., 3., 0.]])
+
+    We can also color the nodes and ask for the probability distribution over
+    all edges (u,v) describing:
+
+        Pr(v has color Y | u has color X)
+
+    >>> G.nodes[0]["color"] = "red"
+    >>> G.nodes[1]["color"] = "red"
+    >>> G.nodes[2]["color"] = "blue"
+    >>> rc = ["red", "blue"]
+    >>> nx.attr_matrix(G, node_attr="color", normalized=True, rc_order=rc)
+    array([[0.33333333, 0.66666667],
+           [1.        , 0.        ]])
+
+    For example, the above tells us that for all edges (u,v):
+
+        Pr( v is red  | u is red)  = 1/3
+        Pr( v is blue | u is red)  = 2/3
+
+        Pr( v is red  | u is blue) = 1
+        Pr( v is blue | u is blue) = 0
+
+    Finally, we can obtain the total weights listed by the node colors.
+
+    >>> nx.attr_matrix(G, edge_attr="weight", node_attr="color", rc_order=rc)
+    array([[3., 2.],
+           [2., 0.]])
+
+    Thus, the total weight over all edges (u,v) with u and v having colors:
+
+        (red, red)   is 3   # the sole contribution is from edge (0,1)
+        (red, blue)  is 2   # contributions from edges (0,2) and (1,2)
+        (blue, red)  is 2   # same as (red, blue) since graph is undirected
+        (blue, blue) is 0   # there are no edges with blue endpoints
+
+    """
+    import numpy as np
+
+    edge_value = _edge_value(G, edge_attr)
+    node_value = _node_value(G, node_attr)
+
+    if rc_order is None:
+        ordering = list({node_value(n) for n in G})
+    else:
+        ordering = rc_order
+
+    N = len(ordering)
+    undirected = not G.is_directed()
+    index = dict(zip(ordering, range(N)))
+    M = np.zeros((N, N), dtype=dtype, order=order)
+
+    seen = set()
+    for u, nbrdict in G.adjacency():
+        for v in nbrdict:
+            # Obtain the node attribute values.
+            i, j = index[node_value(u)], index[node_value(v)]
+            if v not in seen:
+                M[i, j] += edge_value(u, v)
+                if undirected:
+                    M[j, i] = M[i, j]
+
+        if undirected:
+            seen.add(u)
+
+    if normalized:
+        M /= M.sum(axis=1).reshape((N, 1))
+
+    if rc_order is None:
+        return M, ordering
+    else:
+        return M
+
+
+@nx._dispatchable(edge_attrs={"edge_attr": None}, node_attrs="node_attr")
+def attr_sparse_matrix(
+    G, edge_attr=None, node_attr=None, normalized=False, rc_order=None, dtype=None
+):
+    """Returns a SciPy sparse array using attributes from G.
+
+    If only `G` is passed in, then the adjacency matrix is constructed.
+
+    Let A be a discrete set of values for the node attribute `node_attr`. Then
+    the elements of A represent the rows and columns of the constructed matrix.
+    Now, iterate through every edge e=(u,v) in `G` and consider the value
+    of the edge attribute `edge_attr`.  If ua and va are the values of the
+    node attribute `node_attr` for u and v, respectively, then the value of
+    the edge attribute is added to the matrix element at (ua, va).
+
+    Parameters
+    ----------
+    G : graph
+        The NetworkX graph used to construct the NumPy matrix.
+
+    edge_attr : str, optional (default: number of edges for each matrix element)
+        Each element of the matrix represents a running total of the
+        specified edge attribute for edges whose node attributes correspond
+        to the rows/cols of the matrix. The attribute must be present for
+        all edges in the graph. If no attribute is specified, then we
+        just count the number of edges whose node attributes correspond
+        to the matrix element.
+
+    node_attr : str, optional (default: use nodes of the graph)
+        Each row and column in the matrix represents a particular value
+        of the node attribute.  The attribute must be present for all nodes
+        in the graph. Note, the values of this attribute should be reliably
+        hashable. So, float values are not recommended. If no attribute is
+        specified, then the rows and columns will be the nodes of the graph.
+
+    normalized : bool, optional (default: False)
+        If True, then each row is normalized by the summation of its values.
+
+    rc_order : list, optional (default: order of nodes in G)
+        A list of the node attribute values. This list specifies the ordering
+        of rows and columns of the array and the return value. If no ordering
+        is provided, then the ordering will be that of nodes in `G`.
+
+    Other Parameters
+    ----------------
+    dtype : NumPy data-type, optional
+        A valid NumPy dtype used to initialize the array. Keep in mind certain
+        dtypes can yield unexpected results if the array is to be normalized.
+        The parameter is passed to numpy.zeros(). If unspecified, the NumPy
+        default is used.
+
+    Returns
+    -------
+    M : SciPy sparse array
+        The attribute matrix.
+
+    ordering : list
+        If `rc_order` was specified, then only the matrix is returned.
+        However, if `rc_order` was None, then the ordering used to construct
+        the matrix is returned as well.
+
+    Examples
+    --------
+    Construct an adjacency matrix:
+
+    >>> G = nx.Graph()
+    >>> G.add_edge(0, 1, thickness=1, weight=3)
+    >>> G.add_edge(0, 2, thickness=2)
+    >>> G.add_edge(1, 2, thickness=3)
+    >>> M = nx.attr_sparse_matrix(G, rc_order=[0, 1, 2])
+    >>> M.toarray()
+    array([[0., 1., 1.],
+           [1., 0., 1.],
+           [1., 1., 0.]])
+
+    Alternatively, we can obtain the matrix describing edge thickness.
+
+    >>> M = nx.attr_sparse_matrix(G, edge_attr="thickness", rc_order=[0, 1, 2])
+    >>> M.toarray()
+    array([[0., 1., 2.],
+           [1., 0., 3.],
+           [2., 3., 0.]])
+
+    We can also color the nodes and ask for the probability distribution over
+    all edges (u,v) describing:
+
+        Pr(v has color Y | u has color X)
+
+    >>> G.nodes[0]["color"] = "red"
+    >>> G.nodes[1]["color"] = "red"
+    >>> G.nodes[2]["color"] = "blue"
+    >>> rc = ["red", "blue"]
+    >>> M = nx.attr_sparse_matrix(G, node_attr="color", normalized=True, rc_order=rc)
+    >>> M.toarray()
+    array([[0.33333333, 0.66666667],
+           [1.        , 0.        ]])
+
+    For example, the above tells us that for all edges (u,v):
+
+        Pr( v is red  | u is red)  = 1/3
+        Pr( v is blue | u is red)  = 2/3
+
+        Pr( v is red  | u is blue) = 1
+        Pr( v is blue | u is blue) = 0
+
+    Finally, we can obtain the total weights listed by the node colors.
+
+    >>> M = nx.attr_sparse_matrix(G, edge_attr="weight", node_attr="color", rc_order=rc)
+    >>> M.toarray()
+    array([[3., 2.],
+           [2., 0.]])
+
+    Thus, the total weight over all edges (u,v) with u and v having colors:
+
+        (red, red)   is 3   # the sole contribution is from edge (0,1)
+        (red, blue)  is 2   # contributions from edges (0,2) and (1,2)
+        (blue, red)  is 2   # same as (red, blue) since graph is undirected
+        (blue, blue) is 0   # there are no edges with blue endpoints
+
+    """
+    import numpy as np
+    import scipy as sp
+
+    edge_value = _edge_value(G, edge_attr)
+    node_value = _node_value(G, node_attr)
+
+    if rc_order is None:
+        ordering = list({node_value(n) for n in G})
+    else:
+        ordering = rc_order
+
+    N = len(ordering)
+    undirected = not G.is_directed()
+    index = dict(zip(ordering, range(N)))
+    M = sp.sparse.lil_array((N, N), dtype=dtype)
+
+    seen = set()
+    for u, nbrdict in G.adjacency():
+        for v in nbrdict:
+            # Obtain the node attribute values.
+            i, j = index[node_value(u)], index[node_value(v)]
+            if v not in seen:
+                M[i, j] += edge_value(u, v)
+                if undirected:
+                    M[j, i] = M[i, j]
+
+        if undirected:
+            seen.add(u)
+
+    if normalized:
+        M *= 1 / M.sum(axis=1)[:, np.newaxis]  # in-place mult preserves sparse
+
+    if rc_order is None:
+        return M, ordering
+    else:
+        return M
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/linalg/bethehessianmatrix.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/linalg/bethehessianmatrix.py
new file mode 100644
index 0000000000000000000000000000000000000000..717e24711b37060de3eb0b42a714c95184d7b694
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/linalg/bethehessianmatrix.py
@@ -0,0 +1,77 @@
+"""Bethe Hessian or deformed Laplacian matrix of graphs."""
+
+import networkx as nx
+from networkx.utils import not_implemented_for
+
+__all__ = ["bethe_hessian_matrix"]
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable
+def bethe_hessian_matrix(G, r=None, nodelist=None):
+    r"""Returns the Bethe Hessian matrix of G.
+
+    The Bethe Hessian is a family of matrices parametrized by r, defined as
+    H(r) = (r^2 - 1) I - r A + D where A is the adjacency matrix, D is the
+    diagonal matrix of node degrees, and I is the identify matrix. It is equal
+    to the graph laplacian when the regularizer r = 1.
+
+    The default choice of regularizer should be the ratio [2]_
+
+    .. math::
+      r_m = \left(\sum k_i \right)^{-1}\left(\sum k_i^2 \right) - 1
+
+    Parameters
+    ----------
+    G : Graph
+       A NetworkX graph
+    r : float
+       Regularizer parameter
+    nodelist : list, optional
+       The rows and columns are ordered according to the nodes in nodelist.
+       If nodelist is None, then the ordering is produced by ``G.nodes()``.
+
+    Returns
+    -------
+    H : scipy.sparse.csr_array
+      The Bethe Hessian matrix of `G`, with parameter `r`.
+
+    Examples
+    --------
+    >>> k = [3, 2, 2, 1, 0]
+    >>> G = nx.havel_hakimi_graph(k)
+    >>> H = nx.bethe_hessian_matrix(G)
+    >>> H.toarray()
+    array([[ 3.5625, -1.25  , -1.25  , -1.25  ,  0.    ],
+           [-1.25  ,  2.5625, -1.25  ,  0.    ,  0.    ],
+           [-1.25  , -1.25  ,  2.5625,  0.    ,  0.    ],
+           [-1.25  ,  0.    ,  0.    ,  1.5625,  0.    ],
+           [ 0.    ,  0.    ,  0.    ,  0.    ,  0.5625]])
+
+    See Also
+    --------
+    bethe_hessian_spectrum
+    adjacency_matrix
+    laplacian_matrix
+
+    References
+    ----------
+    .. [1] A. Saade, F. Krzakala and L. Zdeborová
+       "Spectral Clustering of Graphs with the Bethe Hessian",
+       Advances in Neural Information Processing Systems, 2014.
+    .. [2] C. M. Le, E. Levina
+       "Estimating the number of communities in networks by spectral methods"
+       arXiv:1507.00827, 2015.
+    """
+    import scipy as sp
+
+    if nodelist is None:
+        nodelist = list(G)
+    if r is None:
+        r = sum(d**2 for v, d in nx.degree(G)) / sum(d for v, d in nx.degree(G)) - 1
+    A = nx.to_scipy_sparse_array(G, nodelist=nodelist, format="csr")
+    n, m = A.shape
+    D = sp.sparse.dia_array((A.sum(axis=1), 0), shape=(m, n)).tocsr()
+    I = sp.sparse.eye_array(m, n, format="csr")
+    return (r**2 - 1) * I - r * A + D
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/linalg/graphmatrix.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/linalg/graphmatrix.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f477bcccc5b6a077b8c7f1807299d71664ebede
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/linalg/graphmatrix.py
@@ -0,0 +1,168 @@
+"""
+Adjacency matrix and incidence matrix of graphs.
+"""
+
+import networkx as nx
+
+__all__ = ["incidence_matrix", "adjacency_matrix"]
+
+
+@nx._dispatchable(edge_attrs="weight")
+def incidence_matrix(
+    G, nodelist=None, edgelist=None, oriented=False, weight=None, *, dtype=None
+):
+    """Returns incidence matrix of G.
+
+    The incidence matrix assigns each row to a node and each column to an edge.
+    For a standard incidence matrix a 1 appears wherever a row's node is
+    incident on the column's edge.  For an oriented incidence matrix each
+    edge is assigned an orientation (arbitrarily for undirected and aligning to
+    direction for directed).  A -1 appears for the source (tail) of an edge and
+    1 for the destination (head) of the edge.  The elements are zero otherwise.
+
+    Parameters
+    ----------
+    G : graph
+       A NetworkX graph
+
+    nodelist : list, optional   (default= all nodes in G)
+       The rows are ordered according to the nodes in nodelist.
+       If nodelist is None, then the ordering is produced by G.nodes().
+
+    edgelist : list, optional (default= all edges in G)
+       The columns are ordered according to the edges in edgelist.
+       If edgelist is None, then the ordering is produced by G.edges().
+
+    oriented: bool, optional (default=False)
+       If True, matrix elements are +1 or -1 for the head or tail node
+       respectively of each edge.  If False, +1 occurs at both nodes.
+
+    weight : string or None, optional (default=None)
+       The edge data key used to provide each value in the matrix.
+       If None, then each edge has weight 1.  Edge weights, if used,
+       should be positive so that the orientation can provide the sign.
+
+    dtype : a NumPy dtype or None (default=None)
+        The dtype of the output sparse array. This type should be a compatible
+        type of the weight argument, eg. if weight would return a float this
+        argument should also be a float.
+        If None, then the default for SciPy is used.
+
+    Returns
+    -------
+    A : SciPy sparse array
+      The incidence matrix of G.
+
+    Notes
+    -----
+    For MultiGraph/MultiDiGraph, the edges in edgelist should be
+    (u,v,key) 3-tuples.
+
+    "Networks are the best discrete model for so many problems in
+    applied mathematics" [1]_.
+
+    References
+    ----------
+    .. [1] Gil Strang, Network applications: A = incidence matrix,
+       http://videolectures.net/mit18085f07_strang_lec03/
+    """
+    import scipy as sp
+
+    if nodelist is None:
+        nodelist = list(G)
+    if edgelist is None:
+        if G.is_multigraph():
+            edgelist = list(G.edges(keys=True))
+        else:
+            edgelist = list(G.edges())
+    A = sp.sparse.lil_array((len(nodelist), len(edgelist)), dtype=dtype)
+    node_index = {node: i for i, node in enumerate(nodelist)}
+    for ei, e in enumerate(edgelist):
+        (u, v) = e[:2]
+        if u == v:
+            continue  # self loops give zero column
+        try:
+            ui = node_index[u]
+            vi = node_index[v]
+        except KeyError as err:
+            raise nx.NetworkXError(
+                f"node {u} or {v} in edgelist but not in nodelist"
+            ) from err
+        if weight is None:
+            wt = 1
+        else:
+            if G.is_multigraph():
+                ekey = e[2]
+                wt = G[u][v][ekey].get(weight, 1)
+            else:
+                wt = G[u][v].get(weight, 1)
+        if oriented:
+            A[ui, ei] = -wt
+            A[vi, ei] = wt
+        else:
+            A[ui, ei] = wt
+            A[vi, ei] = wt
+    return A.asformat("csc")
+
+
+@nx._dispatchable(edge_attrs="weight")
+def adjacency_matrix(G, nodelist=None, dtype=None, weight="weight"):
+    """Returns adjacency matrix of `G`.
+
+    Parameters
+    ----------
+    G : graph
+       A NetworkX graph
+
+    nodelist : list, optional
+       The rows and columns are ordered according to the nodes in `nodelist`.
+       If ``nodelist=None`` (the default), then the ordering is produced by
+       ``G.nodes()``.
+
+    dtype : NumPy data-type, optional
+        The desired data-type for the array.
+        If `None`, then the NumPy default is used.
+
+    weight : string or None, optional (default='weight')
+       The edge data key used to provide each value in the matrix.
+       If None, then each edge has weight 1.
+
+    Returns
+    -------
+    A : SciPy sparse array
+      Adjacency matrix representation of G.
+
+    Notes
+    -----
+    For directed graphs, entry ``i, j`` corresponds to an edge from ``i`` to ``j``.
+
+    If you want a pure Python adjacency matrix representation try
+    :func:`~networkx.convert.to_dict_of_dicts` which will return a
+    dictionary-of-dictionaries format that can be addressed as a
+    sparse matrix.
+
+    For multigraphs with parallel edges the weights are summed.
+    See :func:`networkx.convert_matrix.to_numpy_array` for other options.
+
+    The convention used for self-loop edges in graphs is to assign the
+    diagonal matrix entry value to the edge weight attribute
+    (or the number 1 if the edge has no weight attribute).  If the
+    alternate convention of doubling the edge weight is desired the
+    resulting SciPy sparse array can be modified as follows::
+
+        >>> G = nx.Graph([(1, 1)])
+        >>> A = nx.adjacency_matrix(G)
+        >>> A.toarray()
+        array([[1]])
+        >>> A.setdiag(A.diagonal() * 2)
+        >>> A.toarray()
+        array([[2]])
+
+    See Also
+    --------
+    to_numpy_array
+    to_scipy_sparse_array
+    to_dict_of_dicts
+    adjacency_spectrum
+    """
+    return nx.to_scipy_sparse_array(G, nodelist=nodelist, dtype=dtype, weight=weight)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/linalg/laplacianmatrix.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/linalg/laplacianmatrix.py
new file mode 100644
index 0000000000000000000000000000000000000000..0453f3b2dffdf2ba8706b72d81c70849a30b8b02
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/linalg/laplacianmatrix.py
@@ -0,0 +1,512 @@
+"""Laplacian matrix of graphs.
+
+All calculations here are done using the out-degree. For Laplacians using
+in-degree, use `G.reverse(copy=False)` instead of `G` and take the transpose.
+
+The `laplacian_matrix` function provides an unnormalized matrix,
+while `normalized_laplacian_matrix`, `directed_laplacian_matrix`,
+and `directed_combinatorial_laplacian_matrix` are all normalized.
+"""
+
+import networkx as nx
+from networkx.utils import not_implemented_for
+
+__all__ = [
+    "laplacian_matrix",
+    "normalized_laplacian_matrix",
+    "directed_laplacian_matrix",
+    "directed_combinatorial_laplacian_matrix",
+]
+
+
+@nx._dispatchable(edge_attrs="weight")
+def laplacian_matrix(G, nodelist=None, weight="weight"):
+    """Returns the Laplacian matrix of G.
+
+    The graph Laplacian is the matrix L = D - A, where
+    A is the adjacency matrix and D is the diagonal matrix of node degrees.
+
+    Parameters
+    ----------
+    G : graph
+       A NetworkX graph
+
+    nodelist : list, optional
+       The rows and columns are ordered according to the nodes in nodelist.
+       If nodelist is None, then the ordering is produced by G.nodes().
+
+    weight : string or None, optional (default='weight')
+       The edge data key used to compute each value in the matrix.
+       If None, then each edge has weight 1.
+
+    Returns
+    -------
+    L : SciPy sparse array
+      The Laplacian matrix of G.
+
+    Notes
+    -----
+    For MultiGraph, the edges weights are summed.
+
+    This returns an unnormalized matrix. For a normalized output,
+    use `normalized_laplacian_matrix`, `directed_laplacian_matrix`,
+    or `directed_combinatorial_laplacian_matrix`.
+
+    This calculation uses the out-degree of the graph `G`. To use the
+    in-degree for calculations instead, use `G.reverse(copy=False)` and
+    take the transpose.
+
+    See Also
+    --------
+    :func:`~networkx.convert_matrix.to_numpy_array`
+    normalized_laplacian_matrix
+    directed_laplacian_matrix
+    directed_combinatorial_laplacian_matrix
+    :func:`~networkx.linalg.spectrum.laplacian_spectrum`
+
+    Examples
+    --------
+    For graphs with multiple connected components, L is permutation-similar
+    to a block diagonal matrix where each block is the respective Laplacian
+    matrix for each component.
+
+    >>> G = nx.Graph([(1, 2), (2, 3), (4, 5)])
+    >>> print(nx.laplacian_matrix(G).toarray())
+    [[ 1 -1  0  0  0]
+     [-1  2 -1  0  0]
+     [ 0 -1  1  0  0]
+     [ 0  0  0  1 -1]
+     [ 0  0  0 -1  1]]
+
+    >>> edges = [
+    ...     (1, 2),
+    ...     (2, 1),
+    ...     (2, 4),
+    ...     (4, 3),
+    ...     (3, 4),
+    ... ]
+    >>> DiG = nx.DiGraph(edges)
+    >>> print(nx.laplacian_matrix(DiG).toarray())
+    [[ 1 -1  0  0]
+     [-1  2 -1  0]
+     [ 0  0  1 -1]
+     [ 0  0 -1  1]]
+
+    Notice that node 4 is represented by the third column and row. This is because
+    by default the row/column order is the order of `G.nodes` (i.e. the node added
+    order -- in the edgelist, 4 first appears in (2, 4), before node 3 in edge (4, 3).)
+    To control the node order of the matrix, use the `nodelist` argument.
+
+    >>> print(nx.laplacian_matrix(DiG, nodelist=[1, 2, 3, 4]).toarray())
+    [[ 1 -1  0  0]
+     [-1  2  0 -1]
+     [ 0  0  1 -1]
+     [ 0  0 -1  1]]
+
+    This calculation uses the out-degree of the graph `G`. To use the
+    in-degree for calculations instead, use `G.reverse(copy=False)` and
+    take the transpose.
+
+    >>> print(nx.laplacian_matrix(DiG.reverse(copy=False)).toarray().T)
+    [[ 1 -1  0  0]
+     [-1  1 -1  0]
+     [ 0  0  2 -1]
+     [ 0  0 -1  1]]
+
+    References
+    ----------
+    .. [1] Langville, Amy N., and Carl D. Meyer. Google’s PageRank and Beyond:
+       The Science of Search Engine Rankings. Princeton University Press, 2006.
+
+    """
+    import scipy as sp
+
+    if nodelist is None:
+        nodelist = list(G)
+    A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, format="csr")
+    n, m = A.shape
+    D = sp.sparse.dia_array((A.sum(axis=1), 0), shape=(m, n)).tocsr()
+    return D - A
+
+
+@nx._dispatchable(edge_attrs="weight")
+def normalized_laplacian_matrix(G, nodelist=None, weight="weight"):
+    r"""Returns the normalized Laplacian matrix of G.
+
+    The normalized graph Laplacian is the matrix
+
+    .. math::
+
+        N = D^{-1/2} L D^{-1/2}
+
+    where `L` is the graph Laplacian and `D` is the diagonal matrix of
+    node degrees [1]_.
+
+    Parameters
+    ----------
+    G : graph
+       A NetworkX graph
+
+    nodelist : list, optional
+       The rows and columns are ordered according to the nodes in nodelist.
+       If nodelist is None, then the ordering is produced by G.nodes().
+
+    weight : string or None, optional (default='weight')
+       The edge data key used to compute each value in the matrix.
+       If None, then each edge has weight 1.
+
+    Returns
+    -------
+    N : SciPy sparse array
+      The normalized Laplacian matrix of G.
+
+    Notes
+    -----
+    For MultiGraph, the edges weights are summed.
+    See :func:`to_numpy_array` for other options.
+
+    If the Graph contains selfloops, D is defined as ``diag(sum(A, 1))``, where A is
+    the adjacency matrix [2]_.
+
+    This calculation uses the out-degree of the graph `G`. To use the
+    in-degree for calculations instead, use `G.reverse(copy=False)` and
+    take the transpose.
+
+    For an unnormalized output, use `laplacian_matrix`.
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> edges = [
+    ...     (1, 2),
+    ...     (2, 1),
+    ...     (2, 4),
+    ...     (4, 3),
+    ...     (3, 4),
+    ... ]
+    >>> DiG = nx.DiGraph(edges)
+    >>> print(nx.normalized_laplacian_matrix(DiG).toarray())
+    [[ 1.         -0.70710678  0.          0.        ]
+     [-0.70710678  1.         -0.70710678  0.        ]
+     [ 0.          0.          1.         -1.        ]
+     [ 0.          0.         -1.          1.        ]]
+
+    Notice that node 4 is represented by the third column and row. This is because
+    by default the row/column order is the order of `G.nodes` (i.e. the node added
+    order -- in the edgelist, 4 first appears in (2, 4), before node 3 in edge (4, 3).)
+    To control the node order of the matrix, use the `nodelist` argument.
+
+    >>> print(nx.normalized_laplacian_matrix(DiG, nodelist=[1, 2, 3, 4]).toarray())
+    [[ 1.         -0.70710678  0.          0.        ]
+     [-0.70710678  1.          0.         -0.70710678]
+     [ 0.          0.          1.         -1.        ]
+     [ 0.          0.         -1.          1.        ]]
+    >>> G = nx.Graph(edges)
+    >>> print(nx.normalized_laplacian_matrix(G).toarray())
+    [[ 1.         -0.70710678  0.          0.        ]
+     [-0.70710678  1.         -0.5         0.        ]
+     [ 0.         -0.5         1.         -0.70710678]
+     [ 0.          0.         -0.70710678  1.        ]]
+
+    See Also
+    --------
+    laplacian_matrix
+    normalized_laplacian_spectrum
+    directed_laplacian_matrix
+    directed_combinatorial_laplacian_matrix
+
+    References
+    ----------
+    .. [1] Fan Chung-Graham, Spectral Graph Theory,
+       CBMS Regional Conference Series in Mathematics, Number 92, 1997.
+    .. [2] Steve Butler, Interlacing For Weighted Graphs Using The Normalized
+       Laplacian, Electronic Journal of Linear Algebra, Volume 16, pp. 90-98,
+       March 2007.
+    .. [3] Langville, Amy N., and Carl D. Meyer. Google’s PageRank and Beyond:
+       The Science of Search Engine Rankings. Princeton University Press, 2006.
+    """
+    import numpy as np
+    import scipy as sp
+
+    if nodelist is None:
+        nodelist = list(G)
+    A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, format="csr")
+    n, _ = A.shape
+    diags = A.sum(axis=1)
+    D = sp.sparse.dia_array((diags, 0), shape=(n, n)).tocsr()
+    L = D - A
+    with np.errstate(divide="ignore"):
+        diags_sqrt = 1.0 / np.sqrt(diags)
+    diags_sqrt[np.isinf(diags_sqrt)] = 0
+    DH = sp.sparse.dia_array((diags_sqrt, 0), shape=(n, n)).tocsr()
+    return DH @ (L @ DH)
+
+
+###############################################################################
+# Code based on work from https://github.com/bjedwards
+
+
+@not_implemented_for("undirected")
+@not_implemented_for("multigraph")
+@nx._dispatchable(edge_attrs="weight")
+def directed_laplacian_matrix(
+    G, nodelist=None, weight="weight", walk_type=None, alpha=0.95
+):
+    r"""Returns the directed Laplacian matrix of G.
+
+    The graph directed Laplacian is the matrix
+
+    .. math::
+
+        L = I - \frac{1}{2} \left (\Phi^{1/2} P \Phi^{-1/2} + \Phi^{-1/2} P^T \Phi^{1/2} \right )
+
+    where `I` is the identity matrix, `P` is the transition matrix of the
+    graph, and `\Phi` a matrix with the Perron vector of `P` in the diagonal and
+    zeros elsewhere [1]_.
+
+    Depending on the value of walk_type, `P` can be the transition matrix
+    induced by a random walk, a lazy random walk, or a random walk with
+    teleportation (PageRank).
+
+    Parameters
+    ----------
+    G : DiGraph
+       A NetworkX graph
+
+    nodelist : list, optional
+       The rows and columns are ordered according to the nodes in nodelist.
+       If nodelist is None, then the ordering is produced by G.nodes().
+
+    weight : string or None, optional (default='weight')
+       The edge data key used to compute each value in the matrix.
+       If None, then each edge has weight 1.
+
+    walk_type : string or None, optional (default=None)
+       One of ``"random"``, ``"lazy"``, or ``"pagerank"``. If ``walk_type=None``
+       (the default), then a value is selected according to the properties of `G`:
+       - ``walk_type="random"`` if `G` is strongly connected and aperiodic
+       - ``walk_type="lazy"`` if `G` is strongly connected but not aperiodic
+       - ``walk_type="pagerank"`` for all other cases.
+
+    alpha : real
+       (1 - alpha) is the teleportation probability used with pagerank
+
+    Returns
+    -------
+    L : NumPy matrix
+      Normalized Laplacian of G.
+
+    Notes
+    -----
+    Only implemented for DiGraphs
+
+    The result is always a symmetric matrix.
+
+    This calculation uses the out-degree of the graph `G`. To use the
+    in-degree for calculations instead, use `G.reverse(copy=False)` and
+    take the transpose.
+
+    See Also
+    --------
+    laplacian_matrix
+    normalized_laplacian_matrix
+    directed_combinatorial_laplacian_matrix
+
+    References
+    ----------
+    .. [1] Fan Chung (2005).
+       Laplacians and the Cheeger inequality for directed graphs.
+       Annals of Combinatorics, 9(1), 2005
+    """
+    import numpy as np
+    import scipy as sp
+
+    # NOTE: P has type ndarray if walk_type=="pagerank", else csr_array
+    P = _transition_matrix(
+        G, nodelist=nodelist, weight=weight, walk_type=walk_type, alpha=alpha
+    )
+
+    n, m = P.shape
+
+    evals, evecs = sp.sparse.linalg.eigs(P.T, k=1)
+    v = evecs.flatten().real
+    p = v / v.sum()
+    # p>=0 by Perron-Frobenius Thm. Use abs() to fix roundoff across zero gh-6865
+    sqrtp = np.sqrt(np.abs(p))
+    Q = (
+        sp.sparse.dia_array((sqrtp, 0), shape=(n, n)).tocsr()
+        @ P
+        @ sp.sparse.dia_array((1.0 / sqrtp, 0), shape=(n, n)).tocsr()
+    )
+    # NOTE: This could be sparsified for the non-pagerank cases
+    I = np.identity(len(G))
+
+    return I - (Q + Q.T) / 2.0
+
+
+@not_implemented_for("undirected")
+@not_implemented_for("multigraph")
+@nx._dispatchable(edge_attrs="weight")
+def directed_combinatorial_laplacian_matrix(
+    G, nodelist=None, weight="weight", walk_type=None, alpha=0.95
+):
+    r"""Return the directed combinatorial Laplacian matrix of G.
+
+    The graph directed combinatorial Laplacian is the matrix
+
+    .. math::
+
+        L = \Phi - \frac{1}{2} \left (\Phi P + P^T \Phi \right)
+
+    where `P` is the transition matrix of the graph and `\Phi` a matrix
+    with the Perron vector of `P` in the diagonal and zeros elsewhere [1]_.
+
+    Depending on the value of walk_type, `P` can be the transition matrix
+    induced by a random walk, a lazy random walk, or a random walk with
+    teleportation (PageRank).
+
+    Parameters
+    ----------
+    G : DiGraph
+       A NetworkX graph
+
+    nodelist : list, optional
+       The rows and columns are ordered according to the nodes in nodelist.
+       If nodelist is None, then the ordering is produced by G.nodes().
+
+    weight : string or None, optional (default='weight')
+       The edge data key used to compute each value in the matrix.
+       If None, then each edge has weight 1.
+
+    walk_type : string or None, optional (default=None)
+        One of ``"random"``, ``"lazy"``, or ``"pagerank"``. If ``walk_type=None``
+        (the default), then a value is selected according to the properties of `G`:
+        - ``walk_type="random"`` if `G` is strongly connected and aperiodic
+        - ``walk_type="lazy"`` if `G` is strongly connected but not aperiodic
+        - ``walk_type="pagerank"`` for all other cases.
+
+    alpha : real
+       (1 - alpha) is the teleportation probability used with pagerank
+
+    Returns
+    -------
+    L : NumPy matrix
+      Combinatorial Laplacian of G.
+
+    Notes
+    -----
+    Only implemented for DiGraphs
+
+    The result is always a symmetric matrix.
+
+    This calculation uses the out-degree of the graph `G`. To use the
+    in-degree for calculations instead, use `G.reverse(copy=False)` and
+    take the transpose.
+
+    See Also
+    --------
+    laplacian_matrix
+    normalized_laplacian_matrix
+    directed_laplacian_matrix
+
+    References
+    ----------
+    .. [1] Fan Chung (2005).
+       Laplacians and the Cheeger inequality for directed graphs.
+       Annals of Combinatorics, 9(1), 2005
+    """
+    import scipy as sp
+
+    P = _transition_matrix(
+        G, nodelist=nodelist, weight=weight, walk_type=walk_type, alpha=alpha
+    )
+
+    n, m = P.shape
+
+    evals, evecs = sp.sparse.linalg.eigs(P.T, k=1)
+    v = evecs.flatten().real
+    p = v / v.sum()
+    # NOTE: could be improved by not densifying
+    Phi = sp.sparse.dia_array((p, 0), shape=(n, n)).toarray()
+
+    return Phi - (Phi @ P + P.T @ Phi) / 2.0
+
+
+def _transition_matrix(G, nodelist=None, weight="weight", walk_type=None, alpha=0.95):
+    """Returns the transition matrix of G.
+
+    This is a row stochastic giving the transition probabilities while
+    performing a random walk on the graph. Depending on the value of walk_type,
+    P can be the transition matrix induced by a random walk, a lazy random walk,
+    or a random walk with teleportation (PageRank).
+
+    Parameters
+    ----------
+    G : DiGraph
+       A NetworkX graph
+
+    nodelist : list, optional
+       The rows and columns are ordered according to the nodes in nodelist.
+       If nodelist is None, then the ordering is produced by G.nodes().
+
+    weight : string or None, optional (default='weight')
+       The edge data key used to compute each value in the matrix.
+       If None, then each edge has weight 1.
+
+    walk_type : string or None, optional (default=None)
+       One of ``"random"``, ``"lazy"``, or ``"pagerank"``. If ``walk_type=None``
+       (the default), then a value is selected according to the properties of `G`:
+        - ``walk_type="random"`` if `G` is strongly connected and aperiodic
+        - ``walk_type="lazy"`` if `G` is strongly connected but not aperiodic
+        - ``walk_type="pagerank"`` for all other cases.
+
+    alpha : real
+       (1 - alpha) is the teleportation probability used with pagerank
+
+    Returns
+    -------
+    P : numpy.ndarray
+      transition matrix of G.
+
+    Raises
+    ------
+    NetworkXError
+        If walk_type not specified or alpha not in valid range
+    """
+    import numpy as np
+    import scipy as sp
+
+    if walk_type is None:
+        if nx.is_strongly_connected(G):
+            if nx.is_aperiodic(G):
+                walk_type = "random"
+            else:
+                walk_type = "lazy"
+        else:
+            walk_type = "pagerank"
+
+    A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, dtype=float)
+    n, m = A.shape
+    if walk_type in ["random", "lazy"]:
+        DI = sp.sparse.dia_array((1.0 / A.sum(axis=1), 0), shape=(n, n)).tocsr()
+        if walk_type == "random":
+            P = DI @ A
+        else:
+            I = sp.sparse.eye_array(n, format="csr")
+            P = (I + DI @ A) / 2.0
+
+    elif walk_type == "pagerank":
+        if not (0 < alpha < 1):
+            raise nx.NetworkXError("alpha must be between 0 and 1")
+        # this is using a dense representation. NOTE: This should be sparsified!
+        A = A.toarray()
+        # add constant to dangling nodes' row
+        A[A.sum(axis=1) == 0, :] = 1 / n
+        # normalize
+        A = A / A.sum(axis=1)[np.newaxis, :].T
+        P = alpha * A + (1 - alpha) / n
+    else:
+        raise nx.NetworkXError("walk_type must be random, lazy, or pagerank")
+
+    return P
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/linalg/modularitymatrix.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/linalg/modularitymatrix.py
new file mode 100644
index 0000000000000000000000000000000000000000..0287910bdccc61263afa4d6adfa2b0d78afc4daa
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/linalg/modularitymatrix.py
@@ -0,0 +1,166 @@
+"""Modularity matrix of graphs."""
+
+import networkx as nx
+from networkx.utils import not_implemented_for
+
+__all__ = ["modularity_matrix", "directed_modularity_matrix"]
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable(edge_attrs="weight")
+def modularity_matrix(G, nodelist=None, weight=None):
+    r"""Returns the modularity matrix of G.
+
+    The modularity matrix is the matrix B = A - , where A is the adjacency
+    matrix and  is the average adjacency matrix, assuming that the graph
+    is described by the configuration model.
+
+    More specifically, the element B_ij of B is defined as
+
+    .. math::
+        A_{ij} - {k_i k_j \over 2 m}
+
+    where k_i is the degree of node i, and where m is the number of edges
+    in the graph. When weight is set to a name of an attribute edge, Aij, k_i,
+    k_j and m are computed using its value.
+
+    Parameters
+    ----------
+    G : Graph
+       A NetworkX graph
+
+    nodelist : list, optional
+       The rows and columns are ordered according to the nodes in nodelist.
+       If nodelist is None, then the ordering is produced by G.nodes().
+
+    weight : string or None, optional (default=None)
+       The edge attribute that holds the numerical value used for
+       the edge weight.  If None then all edge weights are 1.
+
+    Returns
+    -------
+    B : Numpy array
+      The modularity matrix of G.
+
+    Examples
+    --------
+    >>> k = [3, 2, 2, 1, 0]
+    >>> G = nx.havel_hakimi_graph(k)
+    >>> B = nx.modularity_matrix(G)
+
+
+    See Also
+    --------
+    to_numpy_array
+    modularity_spectrum
+    adjacency_matrix
+    directed_modularity_matrix
+
+    References
+    ----------
+    .. [1] M. E. J. Newman, "Modularity and community structure in networks",
+           Proc. Natl. Acad. Sci. USA, vol. 103, pp. 8577-8582, 2006.
+    """
+    import numpy as np
+
+    if nodelist is None:
+        nodelist = list(G)
+    A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, format="csr")
+    k = A.sum(axis=1)
+    m = k.sum() * 0.5
+    # Expected adjacency matrix
+    X = np.outer(k, k) / (2 * m)
+
+    return A - X
+
+
+@not_implemented_for("undirected")
+@not_implemented_for("multigraph")
+@nx._dispatchable(edge_attrs="weight")
+def directed_modularity_matrix(G, nodelist=None, weight=None):
+    """Returns the directed modularity matrix of G.
+
+    The modularity matrix is the matrix B = A - , where A is the adjacency
+    matrix and  is the expected adjacency matrix, assuming that the graph
+    is described by the configuration model.
+
+    More specifically, the element B_ij of B is defined as
+
+    .. math::
+        B_{ij} = A_{ij} - k_i^{out} k_j^{in} / m
+
+    where :math:`k_i^{in}` is the in degree of node i, and :math:`k_j^{out}` is the out degree
+    of node j, with m the number of edges in the graph. When weight is set
+    to a name of an attribute edge, Aij, k_i, k_j and m are computed using
+    its value.
+
+    Parameters
+    ----------
+    G : DiGraph
+       A NetworkX DiGraph
+
+    nodelist : list, optional
+       The rows and columns are ordered according to the nodes in nodelist.
+       If nodelist is None, then the ordering is produced by G.nodes().
+
+    weight : string or None, optional (default=None)
+       The edge attribute that holds the numerical value used for
+       the edge weight.  If None then all edge weights are 1.
+
+    Returns
+    -------
+    B : Numpy array
+      The modularity matrix of G.
+
+    Examples
+    --------
+    >>> G = nx.DiGraph()
+    >>> G.add_edges_from(
+    ...     (
+    ...         (1, 2),
+    ...         (1, 3),
+    ...         (3, 1),
+    ...         (3, 2),
+    ...         (3, 5),
+    ...         (4, 5),
+    ...         (4, 6),
+    ...         (5, 4),
+    ...         (5, 6),
+    ...         (6, 4),
+    ...     )
+    ... )
+    >>> B = nx.directed_modularity_matrix(G)
+
+
+    Notes
+    -----
+    NetworkX defines the element A_ij of the adjacency matrix as 1 if there
+    is a link going from node i to node j. Leicht and Newman use the opposite
+    definition. This explains the different expression for B_ij.
+
+    See Also
+    --------
+    to_numpy_array
+    modularity_spectrum
+    adjacency_matrix
+    modularity_matrix
+
+    References
+    ----------
+    .. [1] E. A. Leicht, M. E. J. Newman,
+        "Community structure in directed networks",
+        Phys. Rev Lett., vol. 100, no. 11, p. 118703, 2008.
+    """
+    import numpy as np
+
+    if nodelist is None:
+        nodelist = list(G)
+    A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, format="csr")
+    k_in = A.sum(axis=0)
+    k_out = A.sum(axis=1)
+    m = k_in.sum()
+    # Expected adjacency matrix
+    X = np.outer(k_out, k_in) / m
+
+    return A - X
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/linalg/spectrum.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/linalg/spectrum.py
new file mode 100644
index 0000000000000000000000000000000000000000..079b18550ca5b1478ec3f4b12ee40e5451627355
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/linalg/spectrum.py
@@ -0,0 +1,186 @@
+"""
+Eigenvalue spectrum of graphs.
+"""
+
+import networkx as nx
+
+__all__ = [
+    "laplacian_spectrum",
+    "adjacency_spectrum",
+    "modularity_spectrum",
+    "normalized_laplacian_spectrum",
+    "bethe_hessian_spectrum",
+]
+
+
+@nx._dispatchable(edge_attrs="weight")
+def laplacian_spectrum(G, weight="weight"):
+    """Returns eigenvalues of the Laplacian of G
+
+    Parameters
+    ----------
+    G : graph
+       A NetworkX graph
+
+    weight : string or None, optional (default='weight')
+       The edge data key used to compute each value in the matrix.
+       If None, then each edge has weight 1.
+
+    Returns
+    -------
+    evals : NumPy array
+      Eigenvalues
+
+    Notes
+    -----
+    For MultiGraph/MultiDiGraph, the edges weights are summed.
+    See :func:`~networkx.convert_matrix.to_numpy_array` for other options.
+
+    See Also
+    --------
+    laplacian_matrix
+
+    Examples
+    --------
+    The multiplicity of 0 as an eigenvalue of the laplacian matrix is equal
+    to the number of connected components of G.
+
+    >>> G = nx.Graph()  # Create a graph with 5 nodes and 3 connected components
+    >>> G.add_nodes_from(range(5))
+    >>> G.add_edges_from([(0, 2), (3, 4)])
+    >>> nx.laplacian_spectrum(G)
+    array([0., 0., 0., 2., 2.])
+
+    """
+    import scipy as sp
+
+    return sp.linalg.eigvalsh(nx.laplacian_matrix(G, weight=weight).todense())
+
+
+@nx._dispatchable(edge_attrs="weight")
+def normalized_laplacian_spectrum(G, weight="weight"):
+    """Return eigenvalues of the normalized Laplacian of G
+
+    Parameters
+    ----------
+    G : graph
+       A NetworkX graph
+
+    weight : string or None, optional (default='weight')
+       The edge data key used to compute each value in the matrix.
+       If None, then each edge has weight 1.
+
+    Returns
+    -------
+    evals : NumPy array
+      Eigenvalues
+
+    Notes
+    -----
+    For MultiGraph/MultiDiGraph, the edges weights are summed.
+    See to_numpy_array for other options.
+
+    See Also
+    --------
+    normalized_laplacian_matrix
+    """
+    import scipy as sp
+
+    return sp.linalg.eigvalsh(
+        nx.normalized_laplacian_matrix(G, weight=weight).todense()
+    )
+
+
+@nx._dispatchable(edge_attrs="weight")
+def adjacency_spectrum(G, weight="weight"):
+    """Returns eigenvalues of the adjacency matrix of G.
+
+    Parameters
+    ----------
+    G : graph
+       A NetworkX graph
+
+    weight : string or None, optional (default='weight')
+       The edge data key used to compute each value in the matrix.
+       If None, then each edge has weight 1.
+
+    Returns
+    -------
+    evals : NumPy array
+      Eigenvalues
+
+    Notes
+    -----
+    For MultiGraph/MultiDiGraph, the edges weights are summed.
+    See to_numpy_array for other options.
+
+    See Also
+    --------
+    adjacency_matrix
+    """
+    import scipy as sp
+
+    return sp.linalg.eigvals(nx.adjacency_matrix(G, weight=weight).todense())
+
+
+@nx._dispatchable
+def modularity_spectrum(G):
+    """Returns eigenvalues of the modularity matrix of G.
+
+    Parameters
+    ----------
+    G : Graph
+       A NetworkX Graph or DiGraph
+
+    Returns
+    -------
+    evals : NumPy array
+      Eigenvalues
+
+    See Also
+    --------
+    modularity_matrix
+
+    References
+    ----------
+    .. [1] M. E. J. Newman, "Modularity and community structure in networks",
+       Proc. Natl. Acad. Sci. USA, vol. 103, pp. 8577-8582, 2006.
+    """
+    import scipy as sp
+
+    if G.is_directed():
+        return sp.linalg.eigvals(nx.directed_modularity_matrix(G))
+    else:
+        return sp.linalg.eigvals(nx.modularity_matrix(G))
+
+
+@nx._dispatchable
+def bethe_hessian_spectrum(G, r=None):
+    """Returns eigenvalues of the Bethe Hessian matrix of G.
+
+    Parameters
+    ----------
+    G : Graph
+       A NetworkX Graph or DiGraph
+
+    r : float
+       Regularizer parameter
+
+    Returns
+    -------
+    evals : NumPy array
+      Eigenvalues
+
+    See Also
+    --------
+    bethe_hessian_matrix
+
+    References
+    ----------
+    .. [1] A. Saade, F. Krzakala and L. Zdeborová
+       "Spectral clustering of graphs with the bethe hessian",
+       Advances in Neural Information Processing Systems. 2014.
+    """
+    import scipy as sp
+
+    return sp.linalg.eigvalsh(nx.bethe_hessian_matrix(G, r).todense())
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a805c50a7b18bc818f7bb0a8978ee1e7e90277b5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/__init__.py
@@ -0,0 +1,17 @@
+"""
+A package for reading and writing graphs in various formats.
+
+"""
+
+from networkx.readwrite.adjlist import *
+from networkx.readwrite.multiline_adjlist import *
+from networkx.readwrite.edgelist import *
+from networkx.readwrite.pajek import *
+from networkx.readwrite.leda import *
+from networkx.readwrite.sparse6 import *
+from networkx.readwrite.graph6 import *
+from networkx.readwrite.gml import *
+from networkx.readwrite.graphml import *
+from networkx.readwrite.gexf import *
+from networkx.readwrite.json_graph import *
+from networkx.readwrite.text import *
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/adjlist.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/adjlist.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba3b6e5addff8f39ae5f89610e675304d580787c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/adjlist.py
@@ -0,0 +1,330 @@
+"""
+**************
+Adjacency List
+**************
+Read and write NetworkX graphs as adjacency lists.
+
+Adjacency list format is useful for graphs without data associated
+with nodes or edges and for nodes that can be meaningfully represented
+as strings.
+
+Format
+------
+The adjacency list format consists of lines with node labels.  The
+first label in a line is the source node.  Further labels in the line
+are considered target nodes and are added to the graph along with an edge
+between the source node and target node.
+
+The graph with edges a-b, a-c, d-e can be represented as the following
+adjacency list (anything following the # in a line is a comment)::
+
+     a b c # source target target
+     d e
+"""
+
+__all__ = ["generate_adjlist", "write_adjlist", "parse_adjlist", "read_adjlist"]
+
+import networkx as nx
+from networkx.utils import open_file
+
+
+def generate_adjlist(G, delimiter=" "):
+    """Generate lines representing a graph in adjacency list format.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    delimiter : str, default=" "
+        Separator for node labels.
+
+    Yields
+    ------
+    str
+        Adjacency list for a node in `G`. The first item is the node label,
+        followed by the labels of its neighbors.
+
+    Examples
+    --------
+    >>> G = nx.lollipop_graph(4, 3)
+    >>> for line in nx.generate_adjlist(G):
+    ...     print(line)
+    0 1 2 3
+    1 2 3
+    2 3
+    3 4
+    4 5
+    5 6
+    6
+
+    When `G` is undirected, each edge is only listed once. For directed graphs,
+    edges appear once for each direction.
+
+    >>> G = nx.complete_graph(3, create_using=nx.DiGraph)
+    >>> for line in nx.generate_adjlist(G):
+    ...     print(line)
+    0 1 2
+    1 0 2
+    2 0 1
+
+    Node labels are shown multiple times for multiedges, but edge data (including keys)
+    are not included in the output.
+
+    >>> G = nx.MultiGraph([(0, 1, {"weight": 1}), (0, 1, {"weight": 2})])
+    >>> for line in nx.generate_adjlist(G):
+    ...     print(line)
+    0 1 1
+    1
+
+    See Also
+    --------
+    write_adjlist, read_adjlist
+
+    Notes
+    -----
+    The default `delimiter=" "` will result in unexpected results if node names contain
+    whitespace characters. To avoid this problem, specify an alternate delimiter when spaces are
+    valid in node names.
+
+    NB: This option is not available for data that isn't user-generated.
+
+    """
+    seen = set()
+    directed = G.is_directed()
+    multigraph = G.is_multigraph()
+    for s, nbrs in G.adjacency():
+        nodes = [str(s)]
+        for t, data in nbrs.items():
+            if t in seen:
+                continue
+            if multigraph and len(data) > 1:
+                nodes.extend((str(t),) * len(data))
+            else:
+                nodes.append(str(t))
+        if not directed:
+            seen.add(s)
+        yield delimiter.join(nodes)
+
+
+@open_file(1, mode="wb")
+def write_adjlist(G, path, comments="#", delimiter=" ", encoding="utf-8"):
+    """Write graph G in single-line adjacency-list format to path.
+
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    path : string or file
+       Filename or file handle for data output.
+       Filenames ending in .gz or .bz2 will be compressed.
+
+    comments : string, optional
+       Marker for comment lines
+
+    delimiter : string, optional
+       Separator for node labels
+
+    encoding : string, optional
+       Text encoding.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> nx.write_adjlist(G, "path4.adjlist")
+
+    The path can be a filehandle or a string with the name of the file. If a
+    filehandle is provided, it has to be opened in 'wb' mode.
+
+    >>> fh = open("path4.adjlist2", "wb")
+    >>> nx.write_adjlist(G, fh)
+
+    Notes
+    -----
+    The default `delimiter=" "` will result in unexpected results if node names contain
+    whitespace characters. To avoid this problem, specify an alternate delimiter when spaces are
+    valid in node names.
+    NB: This option is not available for data that isn't user-generated.
+
+    This format does not store graph, node, or edge data.
+
+    See Also
+    --------
+    read_adjlist, generate_adjlist
+    """
+    import sys
+    import time
+
+    pargs = comments + " ".join(sys.argv) + "\n"
+    header = (
+        pargs
+        + comments
+        + f" GMT {time.asctime(time.gmtime())}\n"
+        + comments
+        + f" {G.name}\n"
+    )
+    path.write(header.encode(encoding))
+
+    for line in generate_adjlist(G, delimiter):
+        line += "\n"
+        path.write(line.encode(encoding))
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def parse_adjlist(
+    lines, comments="#", delimiter=None, create_using=None, nodetype=None
+):
+    """Parse lines of a graph adjacency list representation.
+
+    Parameters
+    ----------
+    lines : list or iterator of strings
+        Input data in adjlist format
+
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    nodetype : Python type, optional
+       Convert nodes to this type.
+
+    comments : string, optional
+       Marker for comment lines
+
+    delimiter : string, optional
+       Separator for node labels.  The default is whitespace.
+
+    Returns
+    -------
+    G: NetworkX graph
+        The graph corresponding to the lines in adjacency list format.
+
+    Examples
+    --------
+    >>> lines = ["1 2 5", "2 3 4", "3 5", "4", "5"]
+    >>> G = nx.parse_adjlist(lines, nodetype=int)
+    >>> nodes = [1, 2, 3, 4, 5]
+    >>> all(node in G for node in nodes)
+    True
+    >>> edges = [(1, 2), (1, 5), (2, 3), (2, 4), (3, 5)]
+    >>> all((u, v) in G.edges() or (v, u) in G.edges() for (u, v) in edges)
+    True
+
+    See Also
+    --------
+    read_adjlist
+
+    """
+    G = nx.empty_graph(0, create_using)
+    for line in lines:
+        p = line.find(comments)
+        if p >= 0:
+            line = line[:p]
+        if not len(line):
+            continue
+        vlist = line.rstrip("\n").split(delimiter)
+        u = vlist.pop(0)
+        # convert types
+        if nodetype is not None:
+            try:
+                u = nodetype(u)
+            except BaseException as err:
+                raise TypeError(
+                    f"Failed to convert node ({u}) to type {nodetype}"
+                ) from err
+        G.add_node(u)
+        if nodetype is not None:
+            try:
+                vlist = list(map(nodetype, vlist))
+            except BaseException as err:
+                raise TypeError(
+                    f"Failed to convert nodes ({','.join(vlist)}) to type {nodetype}"
+                ) from err
+        G.add_edges_from([(u, v) for v in vlist])
+    return G
+
+
+@open_file(0, mode="rb")
+@nx._dispatchable(graphs=None, returns_graph=True)
+def read_adjlist(
+    path,
+    comments="#",
+    delimiter=None,
+    create_using=None,
+    nodetype=None,
+    encoding="utf-8",
+):
+    """Read graph in adjacency list format from path.
+
+    Parameters
+    ----------
+    path : string or file
+       Filename or file handle to read.
+       Filenames ending in .gz or .bz2 will be decompressed.
+
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    nodetype : Python type, optional
+       Convert nodes to this type.
+
+    comments : string, optional
+       Marker for comment lines
+
+    delimiter : string, optional
+       Separator for node labels.  The default is whitespace.
+
+    Returns
+    -------
+    G: NetworkX graph
+        The graph corresponding to the lines in adjacency list format.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> nx.write_adjlist(G, "test.adjlist")
+    >>> G = nx.read_adjlist("test.adjlist")
+
+    The path can be a filehandle or a string with the name of the file. If a
+    filehandle is provided, it has to be opened in 'rb' mode.
+
+    >>> fh = open("test.adjlist", "rb")
+    >>> G = nx.read_adjlist(fh)
+
+    Filenames ending in .gz or .bz2 will be compressed.
+
+    >>> nx.write_adjlist(G, "test.adjlist.gz")
+    >>> G = nx.read_adjlist("test.adjlist.gz")
+
+    The optional nodetype is a function to convert node strings to nodetype.
+
+    For example
+
+    >>> G = nx.read_adjlist("test.adjlist", nodetype=int)
+
+    will attempt to convert all nodes to integer type.
+
+    Since nodes must be hashable, the function nodetype must return hashable
+    types (e.g. int, float, str, frozenset - or tuples of those, etc.)
+
+    The optional create_using parameter indicates the type of NetworkX graph
+    created.  The default is `nx.Graph`, an undirected graph.
+    To read the data as a directed graph use
+
+    >>> G = nx.read_adjlist("test.adjlist", create_using=nx.DiGraph)
+
+    Notes
+    -----
+    This format does not store graph or node data.
+
+    See Also
+    --------
+    write_adjlist
+    """
+    lines = (line.decode(encoding) for line in path)
+    return parse_adjlist(
+        lines,
+        comments=comments,
+        delimiter=delimiter,
+        create_using=create_using,
+        nodetype=nodetype,
+    )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/edgelist.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/edgelist.py
new file mode 100644
index 0000000000000000000000000000000000000000..afdb175e8cf4dfb5d8ddb81b136259d2471ad13e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/edgelist.py
@@ -0,0 +1,489 @@
+"""
+**********
+Edge Lists
+**********
+Read and write NetworkX graphs as edge lists.
+
+The multi-line adjacency list format is useful for graphs with nodes
+that can be meaningfully represented as strings.  With the edgelist
+format simple edge data can be stored but node or graph data is not.
+There is no way of representing isolated nodes unless the node has a
+self-loop edge.
+
+Format
+------
+You can read or write three formats of edge lists with these functions.
+
+Node pairs with no data::
+
+ 1 2
+
+Python dictionary as data::
+
+ 1 2 {'weight':7, 'color':'green'}
+
+Arbitrary data::
+
+ 1 2 7 green
+"""
+
+__all__ = [
+    "generate_edgelist",
+    "write_edgelist",
+    "parse_edgelist",
+    "read_edgelist",
+    "read_weighted_edgelist",
+    "write_weighted_edgelist",
+]
+
+import networkx as nx
+from networkx.utils import open_file
+
+
+def generate_edgelist(G, delimiter=" ", data=True):
+    """Generate a single line of the graph G in edge list format.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    delimiter : string, optional
+       Separator for node labels
+
+    data : bool or list of keys
+       If False generate no edge data.  If True use a dictionary
+       representation of edge data.  If a list of keys use a list of data
+       values corresponding to the keys.
+
+    Returns
+    -------
+    lines : string
+        Lines of data in adjlist format.
+
+    Examples
+    --------
+    >>> G = nx.lollipop_graph(4, 3)
+    >>> G[1][2]["weight"] = 3
+    >>> G[3][4]["capacity"] = 12
+    >>> for line in nx.generate_edgelist(G, data=False):
+    ...     print(line)
+    0 1
+    0 2
+    0 3
+    1 2
+    1 3
+    2 3
+    3 4
+    4 5
+    5 6
+
+    >>> for line in nx.generate_edgelist(G):
+    ...     print(line)
+    0 1 {}
+    0 2 {}
+    0 3 {}
+    1 2 {'weight': 3}
+    1 3 {}
+    2 3 {}
+    3 4 {'capacity': 12}
+    4 5 {}
+    5 6 {}
+
+    >>> for line in nx.generate_edgelist(G, data=["weight"]):
+    ...     print(line)
+    0 1
+    0 2
+    0 3
+    1 2 3
+    1 3
+    2 3
+    3 4
+    4 5
+    5 6
+
+    See Also
+    --------
+    write_adjlist, read_adjlist
+    """
+    if data is True:
+        for u, v, d in G.edges(data=True):
+            e = u, v, dict(d)
+            yield delimiter.join(map(str, e))
+    elif data is False:
+        for u, v in G.edges(data=False):
+            e = u, v
+            yield delimiter.join(map(str, e))
+    else:
+        for u, v, d in G.edges(data=True):
+            e = [u, v]
+            try:
+                e.extend(d[k] for k in data)
+            except KeyError:
+                pass  # missing data for this edge, should warn?
+            yield delimiter.join(map(str, e))
+
+
+@open_file(1, mode="wb")
+def write_edgelist(G, path, comments="#", delimiter=" ", data=True, encoding="utf-8"):
+    """Write graph as a list of edges.
+
+    Parameters
+    ----------
+    G : graph
+       A NetworkX graph
+    path : file or string
+       File or filename to write. If a file is provided, it must be
+       opened in 'wb' mode. Filenames ending in .gz or .bz2 will be compressed.
+    comments : string, optional
+       The character used to indicate the start of a comment
+    delimiter : string, optional
+       The string used to separate values.  The default is whitespace.
+    data : bool or list, optional
+       If False write no edge data.
+       If True write a string representation of the edge data dictionary..
+       If a list (or other iterable) is provided, write the  keys specified
+       in the list.
+    encoding: string, optional
+       Specify which encoding to use when writing file.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> nx.write_edgelist(G, "test.edgelist")
+    >>> G = nx.path_graph(4)
+    >>> fh = open("test.edgelist", "wb")
+    >>> nx.write_edgelist(G, fh)
+    >>> nx.write_edgelist(G, "test.edgelist.gz")
+    >>> nx.write_edgelist(G, "test.edgelist_nodata.gz", data=False)
+
+    >>> G = nx.Graph()
+    >>> G.add_edge(1, 2, weight=7, color="red")
+    >>> nx.write_edgelist(G, "test.edgelist_bigger_nodata", data=False)
+    >>> nx.write_edgelist(G, "test.edgelist_color", data=["color"])
+    >>> nx.write_edgelist(G, "test.edgelist_color_weight", data=["color", "weight"])
+
+    See Also
+    --------
+    read_edgelist
+    write_weighted_edgelist
+    """
+
+    for line in generate_edgelist(G, delimiter, data):
+        line += "\n"
+        path.write(line.encode(encoding))
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def parse_edgelist(
+    lines, comments="#", delimiter=None, create_using=None, nodetype=None, data=True
+):
+    """Parse lines of an edge list representation of a graph.
+
+    Parameters
+    ----------
+    lines : list or iterator of strings
+        Input data in edgelist format
+    comments : string, optional
+       Marker for comment lines. Default is `'#'`. To specify that no character
+       should be treated as a comment, use ``comments=None``.
+    delimiter : string, optional
+       Separator for node labels. Default is `None`, meaning any whitespace.
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+    nodetype : Python type, optional
+       Convert nodes to this type. Default is `None`, meaning no conversion is
+       performed.
+    data : bool or list of (label,type) tuples
+       If `False` generate no edge data or if `True` use a dictionary
+       representation of edge data or a list tuples specifying dictionary
+       key names and types for edge data.
+
+    Returns
+    -------
+    G: NetworkX Graph
+        The graph corresponding to lines
+
+    Examples
+    --------
+    Edgelist with no data:
+
+    >>> lines = ["1 2", "2 3", "3 4"]
+    >>> G = nx.parse_edgelist(lines, nodetype=int)
+    >>> list(G)
+    [1, 2, 3, 4]
+    >>> list(G.edges())
+    [(1, 2), (2, 3), (3, 4)]
+
+    Edgelist with data in Python dictionary representation:
+
+    >>> lines = ["1 2 {'weight': 3}", "2 3 {'weight': 27}", "3 4 {'weight': 3.0}"]
+    >>> G = nx.parse_edgelist(lines, nodetype=int)
+    >>> list(G)
+    [1, 2, 3, 4]
+    >>> list(G.edges(data=True))
+    [(1, 2, {'weight': 3}), (2, 3, {'weight': 27}), (3, 4, {'weight': 3.0})]
+
+    Edgelist with data in a list:
+
+    >>> lines = ["1 2 3", "2 3 27", "3 4 3.0"]
+    >>> G = nx.parse_edgelist(lines, nodetype=int, data=(("weight", float),))
+    >>> list(G)
+    [1, 2, 3, 4]
+    >>> list(G.edges(data=True))
+    [(1, 2, {'weight': 3.0}), (2, 3, {'weight': 27.0}), (3, 4, {'weight': 3.0})]
+
+    See Also
+    --------
+    read_weighted_edgelist
+    """
+    from ast import literal_eval
+
+    G = nx.empty_graph(0, create_using)
+    for line in lines:
+        if comments is not None:
+            p = line.find(comments)
+            if p >= 0:
+                line = line[:p]
+            if not line:
+                continue
+        # split line, should have 2 or more
+        s = line.rstrip("\n").split(delimiter)
+        if len(s) < 2:
+            continue
+        u = s.pop(0)
+        v = s.pop(0)
+        d = s
+        if nodetype is not None:
+            try:
+                u = nodetype(u)
+                v = nodetype(v)
+            except Exception as err:
+                raise TypeError(
+                    f"Failed to convert nodes {u},{v} to type {nodetype}."
+                ) from err
+
+        if len(d) == 0 or data is False:
+            # no data or data type specified
+            edgedata = {}
+        elif data is True:
+            # no edge types specified
+            try:  # try to evaluate as dictionary
+                if delimiter == ",":
+                    edgedata_str = ",".join(d)
+                else:
+                    edgedata_str = " ".join(d)
+                edgedata = dict(literal_eval(edgedata_str.strip()))
+            except Exception as err:
+                raise TypeError(
+                    f"Failed to convert edge data ({d}) to dictionary."
+                ) from err
+        else:
+            # convert edge data to dictionary with specified keys and type
+            if len(d) != len(data):
+                raise IndexError(
+                    f"Edge data {d} and data_keys {data} are not the same length"
+                )
+            edgedata = {}
+            for (edge_key, edge_type), edge_value in zip(data, d):
+                try:
+                    edge_value = edge_type(edge_value)
+                except Exception as err:
+                    raise TypeError(
+                        f"Failed to convert {edge_key} data {edge_value} "
+                        f"to type {edge_type}."
+                    ) from err
+                edgedata.update({edge_key: edge_value})
+        G.add_edge(u, v, **edgedata)
+    return G
+
+
+@open_file(0, mode="rb")
+@nx._dispatchable(graphs=None, returns_graph=True)
+def read_edgelist(
+    path,
+    comments="#",
+    delimiter=None,
+    create_using=None,
+    nodetype=None,
+    data=True,
+    edgetype=None,
+    encoding="utf-8",
+):
+    """Read a graph from a list of edges.
+
+    Parameters
+    ----------
+    path : file or string
+       File or filename to read. If a file is provided, it must be
+       opened in 'rb' mode.
+       Filenames ending in .gz or .bz2 will be decompressed.
+    comments : string, optional
+       The character used to indicate the start of a comment. To specify that
+       no character should be treated as a comment, use ``comments=None``.
+    delimiter : string, optional
+       The string used to separate values.  The default is whitespace.
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+    nodetype : int, float, str, Python type, optional
+       Convert node data from strings to specified type
+    data : bool or list of (label,type) tuples
+       Tuples specifying dictionary key names and types for edge data
+    edgetype : int, float, str, Python type, optional OBSOLETE
+       Convert edge data from strings to specified type and use as 'weight'
+    encoding: string, optional
+       Specify which encoding to use when reading file.
+
+    Returns
+    -------
+    G : graph
+       A networkx Graph or other type specified with create_using
+
+    Examples
+    --------
+    >>> nx.write_edgelist(nx.path_graph(4), "test.edgelist_P4")
+    >>> G = nx.read_edgelist("test.edgelist_P4")
+
+    >>> fh = open("test.edgelist_P4", "rb")
+    >>> G = nx.read_edgelist(fh)
+    >>> fh.close()
+
+    >>> G = nx.read_edgelist("test.edgelist_P4", nodetype=int)
+    >>> G = nx.read_edgelist("test.edgelist_P4", create_using=nx.DiGraph)
+
+    Edgelist with data in a list:
+
+    >>> textline = "1 2 3"
+    >>> fh = open("test.textline", "w")
+    >>> d = fh.write(textline)
+    >>> fh.close()
+    >>> G = nx.read_edgelist("test.textline", nodetype=int, data=(("weight", float),))
+    >>> list(G)
+    [1, 2]
+    >>> list(G.edges(data=True))
+    [(1, 2, {'weight': 3.0})]
+
+    See parse_edgelist() for more examples of formatting.
+
+    See Also
+    --------
+    parse_edgelist
+    write_edgelist
+
+    Notes
+    -----
+    Since nodes must be hashable, the function nodetype must return hashable
+    types (e.g. int, float, str, frozenset - or tuples of those, etc.)
+    """
+    lines = (line if isinstance(line, str) else line.decode(encoding) for line in path)
+    return parse_edgelist(
+        lines,
+        comments=comments,
+        delimiter=delimiter,
+        create_using=create_using,
+        nodetype=nodetype,
+        data=data,
+    )
+
+
+def write_weighted_edgelist(G, path, comments="#", delimiter=" ", encoding="utf-8"):
+    """Write graph G as a list of edges with numeric weights.
+
+    Parameters
+    ----------
+    G : graph
+       A NetworkX graph
+    path : file or string
+       File or filename to write. If a file is provided, it must be
+       opened in 'wb' mode.
+       Filenames ending in .gz or .bz2 will be compressed.
+    comments : string, optional
+       The character used to indicate the start of a comment
+    delimiter : string, optional
+       The string used to separate values.  The default is whitespace.
+    encoding: string, optional
+       Specify which encoding to use when writing file.
+
+    Examples
+    --------
+    >>> G = nx.Graph()
+    >>> G.add_edge(1, 2, weight=7)
+    >>> nx.write_weighted_edgelist(G, "test.weighted.edgelist")
+
+    See Also
+    --------
+    read_edgelist
+    write_edgelist
+    read_weighted_edgelist
+    """
+    write_edgelist(
+        G,
+        path,
+        comments=comments,
+        delimiter=delimiter,
+        data=("weight",),
+        encoding=encoding,
+    )
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def read_weighted_edgelist(
+    path,
+    comments="#",
+    delimiter=None,
+    create_using=None,
+    nodetype=None,
+    encoding="utf-8",
+):
+    """Read a graph as list of edges with numeric weights.
+
+    Parameters
+    ----------
+    path : file or string
+       File or filename to read. If a file is provided, it must be
+       opened in 'rb' mode.
+       Filenames ending in .gz or .bz2 will be decompressed.
+    comments : string, optional
+       The character used to indicate the start of a comment.
+    delimiter : string, optional
+       The string used to separate values.  The default is whitespace.
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+    nodetype : int, float, str, Python type, optional
+       Convert node data from strings to specified type
+    encoding: string, optional
+       Specify which encoding to use when reading file.
+
+    Returns
+    -------
+    G : graph
+       A networkx Graph or other type specified with create_using
+
+    Notes
+    -----
+    Since nodes must be hashable, the function nodetype must return hashable
+    types (e.g. int, float, str, frozenset - or tuples of those, etc.)
+
+    Example edgelist file format.
+
+    With numeric edge data::
+
+     # read with
+     # >>> G=nx.read_weighted_edgelist(fh)
+     # source target data
+     a b 1
+     a c 3.14159
+     d e 42
+
+    See Also
+    --------
+    write_weighted_edgelist
+    """
+    return read_edgelist(
+        path,
+        comments=comments,
+        delimiter=delimiter,
+        create_using=create_using,
+        nodetype=nodetype,
+        data=(("weight", float),),
+        encoding=encoding,
+    )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/gexf.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/gexf.py
new file mode 100644
index 0000000000000000000000000000000000000000..56bc71f0e3c05ea053a10d68425168ddef23f04d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/gexf.py
@@ -0,0 +1,1084 @@
+"""Read and write graphs in GEXF format.
+
+.. warning::
+    This parser uses the standard xml library present in Python, which is
+    insecure - see :external+python:mod:`xml` for additional information.
+    Only parse GEFX files you trust.
+
+GEXF (Graph Exchange XML Format) is a language for describing complex
+network structures, their associated data and dynamics.
+
+This implementation does not support mixed graphs (directed and
+undirected edges together).
+
+Format
+------
+GEXF is an XML format.  See http://gexf.net/schema.html for the
+specification and http://gexf.net/basic.html for examples.
+"""
+
+import itertools
+import time
+from xml.etree.ElementTree import (
+    Element,
+    ElementTree,
+    SubElement,
+    register_namespace,
+    tostring,
+)
+
+import networkx as nx
+from networkx.utils import open_file
+
+__all__ = ["write_gexf", "read_gexf", "relabel_gexf_graph", "generate_gexf"]
+
+
+@open_file(1, mode="wb")
+def write_gexf(G, path, encoding="utf-8", prettyprint=True, version="1.2draft"):
+    """Write G in GEXF format to path.
+
+    "GEXF (Graph Exchange XML Format) is a language for describing
+    complex networks structures, their associated data and dynamics" [1]_.
+
+    Node attributes are checked according to the version of the GEXF
+    schemas used for parameters which are not user defined,
+    e.g. visualization 'viz' [2]_. See example for usage.
+
+    .. warning::
+
+       The `GEXF specification `_ reserves some
+       keywords (e.g. ``id``, ``pid``, ``label``, etc.) for specifying node/edge
+       metadata in the file format. Ensure NetworkX node/edge attribute names
+       do not use these special keywords to guarantee all attributes are preserved
+       as expected when roundtripping to/from GEXF format.
+
+    Parameters
+    ----------
+    G : graph
+       A NetworkX graph
+    path : file or string
+       File or file name to write.
+       File names ending in .gz or .bz2 will be compressed.
+    encoding : string (optional, default: 'utf-8')
+       Encoding for text data.
+    prettyprint : bool (optional, default: True)
+       If True use line breaks and indenting in output XML.
+    version: string (optional, default: '1.2draft')
+       The version of GEXF to be used for nodes attributes checking
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> nx.write_gexf(G, "test.gexf")
+
+    # visualization data
+    >>> G.nodes[0]["viz"] = {"size": 54}
+    >>> G.nodes[0]["viz"]["position"] = {"x": 0, "y": 1}
+    >>> G.nodes[0]["viz"]["color"] = {"r": 0, "g": 0, "b": 256}
+
+
+    Notes
+    -----
+    This implementation does not support mixed graphs (directed and undirected
+    edges together).
+
+    The node id attribute is set to be the string of the node label.
+    If you want to specify an id use set it as node data, e.g.
+    node['a']['id']=1 to set the id of node 'a' to 1.
+
+    References
+    ----------
+    .. [1] GEXF File Format, http://gexf.net/
+    .. [2] GEXF schema, http://gexf.net/schema.html
+    """
+    writer = GEXFWriter(encoding=encoding, prettyprint=prettyprint, version=version)
+    writer.add_graph(G)
+    writer.write(path)
+
+
+def generate_gexf(G, encoding="utf-8", prettyprint=True, version="1.2draft"):
+    """Generate lines of GEXF format representation of G.
+
+    "GEXF (Graph Exchange XML Format) is a language for describing
+    complex networks structures, their associated data and dynamics" [1]_.
+
+    Parameters
+    ----------
+    G : graph
+    A NetworkX graph
+    encoding : string (optional, default: 'utf-8')
+    Encoding for text data.
+    prettyprint : bool (optional, default: True)
+    If True use line breaks and indenting in output XML.
+    version : string (default: 1.2draft)
+    Version of GEFX File Format (see http://gexf.net/schema.html)
+    Supported values: "1.1draft", "1.2draft"
+
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> linefeed = chr(10)  # linefeed=\n
+    >>> s = linefeed.join(nx.generate_gexf(G))
+    >>> for line in nx.generate_gexf(G):  # doctest: +SKIP
+    ...     print(line)
+
+    Notes
+    -----
+    This implementation does not support mixed graphs (directed and undirected
+    edges together).
+
+    The node id attribute is set to be the string of the node label.
+    If you want to specify an id use set it as node data, e.g.
+    node['a']['id']=1 to set the id of node 'a' to 1.
+
+    References
+    ----------
+    .. [1] GEXF File Format, https://gephi.org/gexf/format/
+    """
+    writer = GEXFWriter(encoding=encoding, prettyprint=prettyprint, version=version)
+    writer.add_graph(G)
+    yield from str(writer).splitlines()
+
+
+@open_file(0, mode="rb")
+@nx._dispatchable(graphs=None, returns_graph=True)
+def read_gexf(path, node_type=None, relabel=False, version="1.2draft"):
+    """Read graph in GEXF format from path.
+
+    "GEXF (Graph Exchange XML Format) is a language for describing
+    complex networks structures, their associated data and dynamics" [1]_.
+
+    Parameters
+    ----------
+    path : file or string
+       Filename or file handle to read.
+       Filenames ending in .gz or .bz2 will be decompressed.
+    node_type: Python type (default: None)
+       Convert node ids to this type if not None.
+    relabel : bool (default: False)
+       If True relabel the nodes to use the GEXF node "label" attribute
+       instead of the node "id" attribute as the NetworkX node label.
+    version : string (default: 1.2draft)
+    Version of GEFX File Format (see http://gexf.net/schema.html)
+       Supported values: "1.1draft", "1.2draft"
+
+    Returns
+    -------
+    graph: NetworkX graph
+        If no parallel edges are found a Graph or DiGraph is returned.
+        Otherwise a MultiGraph or MultiDiGraph is returned.
+
+    Notes
+    -----
+    This implementation does not support mixed graphs (directed and undirected
+    edges together).
+
+    References
+    ----------
+    .. [1] GEXF File Format, http://gexf.net/
+    """
+    reader = GEXFReader(node_type=node_type, version=version)
+    if relabel:
+        G = relabel_gexf_graph(reader(path))
+    else:
+        G = reader(path)
+    return G
+
+
+class GEXF:
+    versions = {
+        "1.1draft": {
+            "NS_GEXF": "http://www.gexf.net/1.1draft",
+            "NS_VIZ": "http://www.gexf.net/1.1draft/viz",
+            "NS_XSI": "http://www.w3.org/2001/XMLSchema-instance",
+            "SCHEMALOCATION": " ".join(
+                [
+                    "http://www.gexf.net/1.1draft",
+                    "http://www.gexf.net/1.1draft/gexf.xsd",
+                ]
+            ),
+            "VERSION": "1.1",
+        },
+        "1.2draft": {
+            "NS_GEXF": "http://www.gexf.net/1.2draft",
+            "NS_VIZ": "http://www.gexf.net/1.2draft/viz",
+            "NS_XSI": "http://www.w3.org/2001/XMLSchema-instance",
+            "SCHEMALOCATION": " ".join(
+                [
+                    "http://www.gexf.net/1.2draft",
+                    "http://www.gexf.net/1.2draft/gexf.xsd",
+                ]
+            ),
+            "VERSION": "1.2",
+        },
+        "1.3": {
+            "NS_GEXF": "http://gexf.net/1.3",
+            "NS_VIZ": "http://gexf.net/1.3/viz",
+            "NS_XSI": "http://w3.org/2001/XMLSchema-instance",
+            "SCHEMALOCATION": " ".join(
+                [
+                    "http://gexf.net/1.3",
+                    "http://gexf.net/1.3/gexf.xsd",
+                ]
+            ),
+            "VERSION": "1.3",
+        },
+    }
+
+    def construct_types(self):
+        types = [
+            (int, "integer"),
+            (float, "float"),
+            (float, "double"),
+            (bool, "boolean"),
+            (list, "string"),
+            (dict, "string"),
+            (int, "long"),
+            (str, "liststring"),
+            (str, "anyURI"),
+            (str, "string"),
+        ]
+
+        # These additions to types allow writing numpy types
+        try:
+            import numpy as np
+        except ImportError:
+            pass
+        else:
+            # prepend so that python types are created upon read (last entry wins)
+            types = [
+                (np.float64, "float"),
+                (np.float32, "float"),
+                (np.float16, "float"),
+                (np.int_, "int"),
+                (np.int8, "int"),
+                (np.int16, "int"),
+                (np.int32, "int"),
+                (np.int64, "int"),
+                (np.uint8, "int"),
+                (np.uint16, "int"),
+                (np.uint32, "int"),
+                (np.uint64, "int"),
+                (np.int_, "int"),
+                (np.intc, "int"),
+                (np.intp, "int"),
+            ] + types
+
+        self.xml_type = dict(types)
+        self.python_type = dict(reversed(a) for a in types)
+
+    # http://www.w3.org/TR/xmlschema-2/#boolean
+    convert_bool = {
+        "true": True,
+        "false": False,
+        "True": True,
+        "False": False,
+        "0": False,
+        0: False,
+        "1": True,
+        1: True,
+    }
+
+    def set_version(self, version):
+        d = self.versions.get(version)
+        if d is None:
+            raise nx.NetworkXError(f"Unknown GEXF version {version}.")
+        self.NS_GEXF = d["NS_GEXF"]
+        self.NS_VIZ = d["NS_VIZ"]
+        self.NS_XSI = d["NS_XSI"]
+        self.SCHEMALOCATION = d["SCHEMALOCATION"]
+        self.VERSION = d["VERSION"]
+        self.version = version
+
+
+class GEXFWriter(GEXF):
+    # class for writing GEXF format files
+    # use write_gexf() function
+    def __init__(
+        self, graph=None, encoding="utf-8", prettyprint=True, version="1.2draft"
+    ):
+        self.construct_types()
+        self.prettyprint = prettyprint
+        self.encoding = encoding
+        self.set_version(version)
+        self.xml = Element(
+            "gexf",
+            {
+                "xmlns": self.NS_GEXF,
+                "xmlns:xsi": self.NS_XSI,
+                "xsi:schemaLocation": self.SCHEMALOCATION,
+                "version": self.VERSION,
+            },
+        )
+
+        # Make meta element a non-graph element
+        # Also add lastmodifieddate as attribute, not tag
+        meta_element = Element("meta")
+        subelement_text = f"NetworkX {nx.__version__}"
+        SubElement(meta_element, "creator").text = subelement_text
+        meta_element.set("lastmodifieddate", time.strftime("%Y-%m-%d"))
+        self.xml.append(meta_element)
+
+        register_namespace("viz", self.NS_VIZ)
+
+        # counters for edge and attribute identifiers
+        self.edge_id = itertools.count()
+        self.attr_id = itertools.count()
+        self.all_edge_ids = set()
+        # default attributes are stored in dictionaries
+        self.attr = {}
+        self.attr["node"] = {}
+        self.attr["edge"] = {}
+        self.attr["node"]["dynamic"] = {}
+        self.attr["node"]["static"] = {}
+        self.attr["edge"]["dynamic"] = {}
+        self.attr["edge"]["static"] = {}
+
+        if graph is not None:
+            self.add_graph(graph)
+
+    def __str__(self):
+        if self.prettyprint:
+            self.indent(self.xml)
+        s = tostring(self.xml).decode(self.encoding)
+        return s
+
+    def add_graph(self, G):
+        # first pass through G collecting edge ids
+        for u, v, dd in G.edges(data=True):
+            eid = dd.get("id")
+            if eid is not None:
+                self.all_edge_ids.add(str(eid))
+        # set graph attributes
+        if G.graph.get("mode") == "dynamic":
+            mode = "dynamic"
+        else:
+            mode = "static"
+        # Add a graph element to the XML
+        if G.is_directed():
+            default = "directed"
+        else:
+            default = "undirected"
+        name = G.graph.get("name", "")
+        graph_element = Element("graph", defaultedgetype=default, mode=mode, name=name)
+        self.graph_element = graph_element
+        self.add_nodes(G, graph_element)
+        self.add_edges(G, graph_element)
+        self.xml.append(graph_element)
+
+    def add_nodes(self, G, graph_element):
+        nodes_element = Element("nodes")
+        for node, data in G.nodes(data=True):
+            node_data = data.copy()
+            node_id = str(node_data.pop("id", node))
+            kw = {"id": node_id}
+            label = str(node_data.pop("label", node))
+            kw["label"] = label
+            try:
+                pid = node_data.pop("pid")
+                kw["pid"] = str(pid)
+            except KeyError:
+                pass
+            try:
+                start = node_data.pop("start")
+                kw["start"] = str(start)
+                self.alter_graph_mode_timeformat(start)
+            except KeyError:
+                pass
+            try:
+                end = node_data.pop("end")
+                kw["end"] = str(end)
+                self.alter_graph_mode_timeformat(end)
+            except KeyError:
+                pass
+            # add node element with attributes
+            node_element = Element("node", **kw)
+            # add node element and attr subelements
+            default = G.graph.get("node_default", {})
+            node_data = self.add_parents(node_element, node_data)
+            if self.VERSION == "1.1":
+                node_data = self.add_slices(node_element, node_data)
+            else:
+                node_data = self.add_spells(node_element, node_data)
+            node_data = self.add_viz(node_element, node_data)
+            node_data = self.add_attributes("node", node_element, node_data, default)
+            nodes_element.append(node_element)
+        graph_element.append(nodes_element)
+
+    def add_edges(self, G, graph_element):
+        def edge_key_data(G):
+            # helper function to unify multigraph and graph edge iterator
+            if G.is_multigraph():
+                for u, v, key, data in G.edges(data=True, keys=True):
+                    edge_data = data.copy()
+                    edge_data.update(key=key)
+                    edge_id = edge_data.pop("id", None)
+                    if edge_id is None:
+                        edge_id = next(self.edge_id)
+                        while str(edge_id) in self.all_edge_ids:
+                            edge_id = next(self.edge_id)
+                        self.all_edge_ids.add(str(edge_id))
+                    yield u, v, edge_id, edge_data
+            else:
+                for u, v, data in G.edges(data=True):
+                    edge_data = data.copy()
+                    edge_id = edge_data.pop("id", None)
+                    if edge_id is None:
+                        edge_id = next(self.edge_id)
+                        while str(edge_id) in self.all_edge_ids:
+                            edge_id = next(self.edge_id)
+                        self.all_edge_ids.add(str(edge_id))
+                    yield u, v, edge_id, edge_data
+
+        edges_element = Element("edges")
+        for u, v, key, edge_data in edge_key_data(G):
+            kw = {"id": str(key)}
+            try:
+                edge_label = edge_data.pop("label")
+                kw["label"] = str(edge_label)
+            except KeyError:
+                pass
+            try:
+                edge_weight = edge_data.pop("weight")
+                kw["weight"] = str(edge_weight)
+            except KeyError:
+                pass
+            try:
+                edge_type = edge_data.pop("type")
+                kw["type"] = str(edge_type)
+            except KeyError:
+                pass
+            try:
+                start = edge_data.pop("start")
+                kw["start"] = str(start)
+                self.alter_graph_mode_timeformat(start)
+            except KeyError:
+                pass
+            try:
+                end = edge_data.pop("end")
+                kw["end"] = str(end)
+                self.alter_graph_mode_timeformat(end)
+            except KeyError:
+                pass
+            source_id = str(G.nodes[u].get("id", u))
+            target_id = str(G.nodes[v].get("id", v))
+            edge_element = Element("edge", source=source_id, target=target_id, **kw)
+            default = G.graph.get("edge_default", {})
+            if self.VERSION == "1.1":
+                edge_data = self.add_slices(edge_element, edge_data)
+            else:
+                edge_data = self.add_spells(edge_element, edge_data)
+            edge_data = self.add_viz(edge_element, edge_data)
+            edge_data = self.add_attributes("edge", edge_element, edge_data, default)
+            edges_element.append(edge_element)
+        graph_element.append(edges_element)
+
+    def add_attributes(self, node_or_edge, xml_obj, data, default):
+        # Add attrvalues to node or edge
+        attvalues = Element("attvalues")
+        if len(data) == 0:
+            return data
+        mode = "static"
+        for k, v in data.items():
+            # rename generic multigraph key to avoid any name conflict
+            if k == "key":
+                k = "networkx_key"
+            val_type = type(v)
+            if val_type not in self.xml_type:
+                raise TypeError(f"attribute value type is not allowed: {val_type}")
+            if isinstance(v, list):
+                # dynamic data
+                for val, start, end in v:
+                    val_type = type(val)
+                    if start is not None or end is not None:
+                        mode = "dynamic"
+                        self.alter_graph_mode_timeformat(start)
+                        self.alter_graph_mode_timeformat(end)
+                        break
+                attr_id = self.get_attr_id(
+                    str(k), self.xml_type[val_type], node_or_edge, default, mode
+                )
+                for val, start, end in v:
+                    e = Element("attvalue")
+                    e.attrib["for"] = attr_id
+                    e.attrib["value"] = str(val)
+                    # Handle nan, inf, -inf differently
+                    if val_type is float:
+                        if e.attrib["value"] == "inf":
+                            e.attrib["value"] = "INF"
+                        elif e.attrib["value"] == "nan":
+                            e.attrib["value"] = "NaN"
+                        elif e.attrib["value"] == "-inf":
+                            e.attrib["value"] = "-INF"
+                    if start is not None:
+                        e.attrib["start"] = str(start)
+                    if end is not None:
+                        e.attrib["end"] = str(end)
+                    attvalues.append(e)
+            else:
+                # static data
+                mode = "static"
+                attr_id = self.get_attr_id(
+                    str(k), self.xml_type[val_type], node_or_edge, default, mode
+                )
+                e = Element("attvalue")
+                e.attrib["for"] = attr_id
+                if isinstance(v, bool):
+                    e.attrib["value"] = str(v).lower()
+                else:
+                    e.attrib["value"] = str(v)
+                    # Handle float nan, inf, -inf differently
+                    if val_type is float:
+                        if e.attrib["value"] == "inf":
+                            e.attrib["value"] = "INF"
+                        elif e.attrib["value"] == "nan":
+                            e.attrib["value"] = "NaN"
+                        elif e.attrib["value"] == "-inf":
+                            e.attrib["value"] = "-INF"
+                attvalues.append(e)
+        xml_obj.append(attvalues)
+        return data
+
+    def get_attr_id(self, title, attr_type, edge_or_node, default, mode):
+        # find the id of the attribute or generate a new id
+        try:
+            return self.attr[edge_or_node][mode][title]
+        except KeyError:
+            # generate new id
+            new_id = str(next(self.attr_id))
+            self.attr[edge_or_node][mode][title] = new_id
+            attr_kwargs = {"id": new_id, "title": title, "type": attr_type}
+            attribute = Element("attribute", **attr_kwargs)
+            # add subelement for data default value if present
+            default_title = default.get(title)
+            if default_title is not None:
+                default_element = Element("default")
+                default_element.text = str(default_title)
+                attribute.append(default_element)
+            # new insert it into the XML
+            attributes_element = None
+            for a in self.graph_element.findall("attributes"):
+                # find existing attributes element by class and mode
+                a_class = a.get("class")
+                a_mode = a.get("mode", "static")
+                if a_class == edge_or_node and a_mode == mode:
+                    attributes_element = a
+            if attributes_element is None:
+                # create new attributes element
+                attr_kwargs = {"mode": mode, "class": edge_or_node}
+                attributes_element = Element("attributes", **attr_kwargs)
+                self.graph_element.insert(0, attributes_element)
+            attributes_element.append(attribute)
+        return new_id
+
+    def add_viz(self, element, node_data):
+        viz = node_data.pop("viz", False)
+        if viz:
+            color = viz.get("color")
+            if color is not None:
+                if self.VERSION == "1.1":
+                    e = Element(
+                        f"{{{self.NS_VIZ}}}color",
+                        r=str(color.get("r")),
+                        g=str(color.get("g")),
+                        b=str(color.get("b")),
+                    )
+                else:
+                    e = Element(
+                        f"{{{self.NS_VIZ}}}color",
+                        r=str(color.get("r")),
+                        g=str(color.get("g")),
+                        b=str(color.get("b")),
+                        a=str(color.get("a", 1.0)),
+                    )
+                element.append(e)
+
+            size = viz.get("size")
+            if size is not None:
+                e = Element(f"{{{self.NS_VIZ}}}size", value=str(size))
+                element.append(e)
+
+            thickness = viz.get("thickness")
+            if thickness is not None:
+                e = Element(f"{{{self.NS_VIZ}}}thickness", value=str(thickness))
+                element.append(e)
+
+            shape = viz.get("shape")
+            if shape is not None:
+                if shape.startswith("http"):
+                    e = Element(
+                        f"{{{self.NS_VIZ}}}shape", value="image", uri=str(shape)
+                    )
+                else:
+                    e = Element(f"{{{self.NS_VIZ}}}shape", value=str(shape))
+                element.append(e)
+
+            position = viz.get("position")
+            if position is not None:
+                e = Element(
+                    f"{{{self.NS_VIZ}}}position",
+                    x=str(position.get("x")),
+                    y=str(position.get("y")),
+                    z=str(position.get("z")),
+                )
+                element.append(e)
+        return node_data
+
+    def add_parents(self, node_element, node_data):
+        parents = node_data.pop("parents", False)
+        if parents:
+            parents_element = Element("parents")
+            for p in parents:
+                e = Element("parent")
+                e.attrib["for"] = str(p)
+                parents_element.append(e)
+            node_element.append(parents_element)
+        return node_data
+
+    def add_slices(self, node_or_edge_element, node_or_edge_data):
+        slices = node_or_edge_data.pop("slices", False)
+        if slices:
+            slices_element = Element("slices")
+            for start, end in slices:
+                e = Element("slice", start=str(start), end=str(end))
+                slices_element.append(e)
+            node_or_edge_element.append(slices_element)
+        return node_or_edge_data
+
+    def add_spells(self, node_or_edge_element, node_or_edge_data):
+        spells = node_or_edge_data.pop("spells", False)
+        if spells:
+            spells_element = Element("spells")
+            for start, end in spells:
+                e = Element("spell")
+                if start is not None:
+                    e.attrib["start"] = str(start)
+                    self.alter_graph_mode_timeformat(start)
+                if end is not None:
+                    e.attrib["end"] = str(end)
+                    self.alter_graph_mode_timeformat(end)
+                spells_element.append(e)
+            node_or_edge_element.append(spells_element)
+        return node_or_edge_data
+
+    def alter_graph_mode_timeformat(self, start_or_end):
+        # If 'start' or 'end' appears, set timeformat
+        if start_or_end is not None:
+            if isinstance(start_or_end, str):
+                timeformat = "date"
+            elif isinstance(start_or_end, float):
+                timeformat = "double"
+            elif isinstance(start_or_end, int):
+                timeformat = "long"
+            else:
+                raise nx.NetworkXError(
+                    "timeformat should be of the type int, float or str"
+                )
+            self.graph_element.set("timeformat", timeformat)
+            # If Graph mode is static, alter to dynamic
+            if self.graph_element.get("mode") == "static":
+                self.graph_element.set("mode", "dynamic")
+
+    def write(self, fh):
+        # Serialize graph G in GEXF to the open fh
+        if self.prettyprint:
+            self.indent(self.xml)
+        document = ElementTree(self.xml)
+        document.write(fh, encoding=self.encoding, xml_declaration=True)
+
+    def indent(self, elem, level=0):
+        # in-place prettyprint formatter
+        i = "\n" + "  " * level
+        if len(elem):
+            if not elem.text or not elem.text.strip():
+                elem.text = i + "  "
+            if not elem.tail or not elem.tail.strip():
+                elem.tail = i
+            for elem in elem:
+                self.indent(elem, level + 1)
+            if not elem.tail or not elem.tail.strip():
+                elem.tail = i
+        else:
+            if level and (not elem.tail or not elem.tail.strip()):
+                elem.tail = i
+
+
+class GEXFReader(GEXF):
+    # Class to read GEXF format files
+    # use read_gexf() function
+    def __init__(self, node_type=None, version="1.2draft"):
+        self.construct_types()
+        self.node_type = node_type
+        # assume simple graph and test for multigraph on read
+        self.simple_graph = True
+        self.set_version(version)
+
+    def __call__(self, stream):
+        self.xml = ElementTree(file=stream)
+        g = self.xml.find(f"{{{self.NS_GEXF}}}graph")
+        if g is not None:
+            return self.make_graph(g)
+        # try all the versions
+        for version in self.versions:
+            self.set_version(version)
+            g = self.xml.find(f"{{{self.NS_GEXF}}}graph")
+            if g is not None:
+                return self.make_graph(g)
+        raise nx.NetworkXError("No  element in GEXF file.")
+
+    def make_graph(self, graph_xml):
+        # start with empty DiGraph or MultiDiGraph
+        edgedefault = graph_xml.get("defaultedgetype", None)
+        if edgedefault == "directed":
+            G = nx.MultiDiGraph()
+        else:
+            G = nx.MultiGraph()
+
+        # graph attributes
+        graph_name = graph_xml.get("name", "")
+        if graph_name != "":
+            G.graph["name"] = graph_name
+        graph_start = graph_xml.get("start")
+        if graph_start is not None:
+            G.graph["start"] = graph_start
+        graph_end = graph_xml.get("end")
+        if graph_end is not None:
+            G.graph["end"] = graph_end
+        graph_mode = graph_xml.get("mode", "")
+        if graph_mode == "dynamic":
+            G.graph["mode"] = "dynamic"
+        else:
+            G.graph["mode"] = "static"
+
+        # timeformat
+        self.timeformat = graph_xml.get("timeformat")
+        if self.timeformat == "date":
+            self.timeformat = "string"
+
+        # node and edge attributes
+        attributes_elements = graph_xml.findall(f"{{{self.NS_GEXF}}}attributes")
+        # dictionaries to hold attributes and attribute defaults
+        node_attr = {}
+        node_default = {}
+        edge_attr = {}
+        edge_default = {}
+        for a in attributes_elements:
+            attr_class = a.get("class")
+            if attr_class == "node":
+                na, nd = self.find_gexf_attributes(a)
+                node_attr.update(na)
+                node_default.update(nd)
+                G.graph["node_default"] = node_default
+            elif attr_class == "edge":
+                ea, ed = self.find_gexf_attributes(a)
+                edge_attr.update(ea)
+                edge_default.update(ed)
+                G.graph["edge_default"] = edge_default
+            else:
+                raise  # unknown attribute class
+
+        # Hack to handle Gephi0.7beta bug
+        # add weight attribute
+        ea = {"weight": {"type": "double", "mode": "static", "title": "weight"}}
+        ed = {}
+        edge_attr.update(ea)
+        edge_default.update(ed)
+        G.graph["edge_default"] = edge_default
+
+        # add nodes
+        nodes_element = graph_xml.find(f"{{{self.NS_GEXF}}}nodes")
+        if nodes_element is not None:
+            for node_xml in nodes_element.findall(f"{{{self.NS_GEXF}}}node"):
+                self.add_node(G, node_xml, node_attr)
+
+        # add edges
+        edges_element = graph_xml.find(f"{{{self.NS_GEXF}}}edges")
+        if edges_element is not None:
+            for edge_xml in edges_element.findall(f"{{{self.NS_GEXF}}}edge"):
+                self.add_edge(G, edge_xml, edge_attr)
+
+        # switch to Graph or DiGraph if no parallel edges were found.
+        if self.simple_graph:
+            if G.is_directed():
+                G = nx.DiGraph(G)
+            else:
+                G = nx.Graph(G)
+        return G
+
+    def add_node(self, G, node_xml, node_attr, node_pid=None):
+        # add a single node with attributes to the graph
+
+        # get attributes and subattributues for node
+        data = self.decode_attr_elements(node_attr, node_xml)
+        data = self.add_parents(data, node_xml)  # add any parents
+        if self.VERSION == "1.1":
+            data = self.add_slices(data, node_xml)  # add slices
+        else:
+            data = self.add_spells(data, node_xml)  # add spells
+        data = self.add_viz(data, node_xml)  # add viz
+        data = self.add_start_end(data, node_xml)  # add start/end
+
+        # find the node id and cast it to the appropriate type
+        node_id = node_xml.get("id")
+        if self.node_type is not None:
+            node_id = self.node_type(node_id)
+
+        # every node should have a label
+        node_label = node_xml.get("label")
+        data["label"] = node_label
+
+        # parent node id
+        node_pid = node_xml.get("pid", node_pid)
+        if node_pid is not None:
+            data["pid"] = node_pid
+
+        # check for subnodes, recursive
+        subnodes = node_xml.find(f"{{{self.NS_GEXF}}}nodes")
+        if subnodes is not None:
+            for node_xml in subnodes.findall(f"{{{self.NS_GEXF}}}node"):
+                self.add_node(G, node_xml, node_attr, node_pid=node_id)
+
+        G.add_node(node_id, **data)
+
+    def add_start_end(self, data, xml):
+        # start and end times
+        ttype = self.timeformat
+        node_start = xml.get("start")
+        if node_start is not None:
+            data["start"] = self.python_type[ttype](node_start)
+        node_end = xml.get("end")
+        if node_end is not None:
+            data["end"] = self.python_type[ttype](node_end)
+        return data
+
+    def add_viz(self, data, node_xml):
+        # add viz element for node
+        viz = {}
+        color = node_xml.find(f"{{{self.NS_VIZ}}}color")
+        if color is not None:
+            if self.VERSION == "1.1":
+                viz["color"] = {
+                    "r": int(color.get("r")),
+                    "g": int(color.get("g")),
+                    "b": int(color.get("b")),
+                }
+            else:
+                viz["color"] = {
+                    "r": int(color.get("r")),
+                    "g": int(color.get("g")),
+                    "b": int(color.get("b")),
+                    "a": float(color.get("a", 1)),
+                }
+
+        size = node_xml.find(f"{{{self.NS_VIZ}}}size")
+        if size is not None:
+            viz["size"] = float(size.get("value"))
+
+        thickness = node_xml.find(f"{{{self.NS_VIZ}}}thickness")
+        if thickness is not None:
+            viz["thickness"] = float(thickness.get("value"))
+
+        shape = node_xml.find(f"{{{self.NS_VIZ}}}shape")
+        if shape is not None:
+            viz["shape"] = shape.get("shape")
+            if viz["shape"] == "image":
+                viz["shape"] = shape.get("uri")
+
+        position = node_xml.find(f"{{{self.NS_VIZ}}}position")
+        if position is not None:
+            viz["position"] = {
+                "x": float(position.get("x", 0)),
+                "y": float(position.get("y", 0)),
+                "z": float(position.get("z", 0)),
+            }
+
+        if len(viz) > 0:
+            data["viz"] = viz
+        return data
+
+    def add_parents(self, data, node_xml):
+        parents_element = node_xml.find(f"{{{self.NS_GEXF}}}parents")
+        if parents_element is not None:
+            data["parents"] = []
+            for p in parents_element.findall(f"{{{self.NS_GEXF}}}parent"):
+                parent = p.get("for")
+                data["parents"].append(parent)
+        return data
+
+    def add_slices(self, data, node_or_edge_xml):
+        slices_element = node_or_edge_xml.find(f"{{{self.NS_GEXF}}}slices")
+        if slices_element is not None:
+            data["slices"] = []
+            for s in slices_element.findall(f"{{{self.NS_GEXF}}}slice"):
+                start = s.get("start")
+                end = s.get("end")
+                data["slices"].append((start, end))
+        return data
+
+    def add_spells(self, data, node_or_edge_xml):
+        spells_element = node_or_edge_xml.find(f"{{{self.NS_GEXF}}}spells")
+        if spells_element is not None:
+            data["spells"] = []
+            ttype = self.timeformat
+            for s in spells_element.findall(f"{{{self.NS_GEXF}}}spell"):
+                start = self.python_type[ttype](s.get("start"))
+                end = self.python_type[ttype](s.get("end"))
+                data["spells"].append((start, end))
+        return data
+
+    def add_edge(self, G, edge_element, edge_attr):
+        # add an edge to the graph
+
+        # raise error if we find mixed directed and undirected edges
+        edge_direction = edge_element.get("type")
+        if G.is_directed() and edge_direction == "undirected":
+            raise nx.NetworkXError("Undirected edge found in directed graph.")
+        if (not G.is_directed()) and edge_direction == "directed":
+            raise nx.NetworkXError("Directed edge found in undirected graph.")
+
+        # Get source and target and recast type if required
+        source = edge_element.get("source")
+        target = edge_element.get("target")
+        if self.node_type is not None:
+            source = self.node_type(source)
+            target = self.node_type(target)
+
+        data = self.decode_attr_elements(edge_attr, edge_element)
+        data = self.add_start_end(data, edge_element)
+
+        if self.VERSION == "1.1":
+            data = self.add_slices(data, edge_element)  # add slices
+        else:
+            data = self.add_spells(data, edge_element)  # add spells
+
+        # GEXF stores edge ids as an attribute
+        # NetworkX uses them as keys in multigraphs
+        # if networkx_key is not specified as an attribute
+        edge_id = edge_element.get("id")
+        if edge_id is not None:
+            data["id"] = edge_id
+
+        # check if there is a 'multigraph_key' and use that as edge_id
+        multigraph_key = data.pop("networkx_key", None)
+        if multigraph_key is not None:
+            edge_id = multigraph_key
+
+        weight = edge_element.get("weight")
+        if weight is not None:
+            data["weight"] = float(weight)
+
+        edge_label = edge_element.get("label")
+        if edge_label is not None:
+            data["label"] = edge_label
+
+        if G.has_edge(source, target):
+            # seen this edge before - this is a multigraph
+            self.simple_graph = False
+        G.add_edge(source, target, key=edge_id, **data)
+        if edge_direction == "mutual":
+            G.add_edge(target, source, key=edge_id, **data)
+
+    def decode_attr_elements(self, gexf_keys, obj_xml):
+        # Use the key information to decode the attr XML
+        attr = {}
+        # look for outer '' element
+        attr_element = obj_xml.find(f"{{{self.NS_GEXF}}}attvalues")
+        if attr_element is not None:
+            # loop over  elements
+            for a in attr_element.findall(f"{{{self.NS_GEXF}}}attvalue"):
+                key = a.get("for")  # for is required
+                try:  # should be in our gexf_keys dictionary
+                    title = gexf_keys[key]["title"]
+                except KeyError as err:
+                    raise nx.NetworkXError(f"No attribute defined for={key}.") from err
+                atype = gexf_keys[key]["type"]
+                value = a.get("value")
+                if atype == "boolean":
+                    value = self.convert_bool[value]
+                else:
+                    value = self.python_type[atype](value)
+                if gexf_keys[key]["mode"] == "dynamic":
+                    # for dynamic graphs use list of three-tuples
+                    # [(value1,start1,end1), (value2,start2,end2), etc]
+                    ttype = self.timeformat
+                    start = self.python_type[ttype](a.get("start"))
+                    end = self.python_type[ttype](a.get("end"))
+                    if title in attr:
+                        attr[title].append((value, start, end))
+                    else:
+                        attr[title] = [(value, start, end)]
+                else:
+                    # for static graphs just assign the value
+                    attr[title] = value
+        return attr
+
+    def find_gexf_attributes(self, attributes_element):
+        # Extract all the attributes and defaults
+        attrs = {}
+        defaults = {}
+        mode = attributes_element.get("mode")
+        for k in attributes_element.findall(f"{{{self.NS_GEXF}}}attribute"):
+            attr_id = k.get("id")
+            title = k.get("title")
+            atype = k.get("type")
+            attrs[attr_id] = {"title": title, "type": atype, "mode": mode}
+            # check for the 'default' subelement of key element and add
+            default = k.find(f"{{{self.NS_GEXF}}}default")
+            if default is not None:
+                if atype == "boolean":
+                    value = self.convert_bool[default.text]
+                else:
+                    value = self.python_type[atype](default.text)
+                defaults[title] = value
+        return attrs, defaults
+
+
+def relabel_gexf_graph(G):
+    """Relabel graph using "label" node keyword for node label.
+
+    Parameters
+    ----------
+    G : graph
+       A NetworkX graph read from GEXF data
+
+    Returns
+    -------
+    H : graph
+      A NetworkX graph with relabeled nodes
+
+    Raises
+    ------
+    NetworkXError
+        If node labels are missing or not unique while relabel=True.
+
+    Notes
+    -----
+    This function relabels the nodes in a NetworkX graph with the
+    "label" attribute.  It also handles relabeling the specific GEXF
+    node attributes "parents", and "pid".
+    """
+    # build mapping of node labels, do some error checking
+    try:
+        mapping = [(u, G.nodes[u]["label"]) for u in G]
+    except KeyError as err:
+        raise nx.NetworkXError(
+            "Failed to relabel nodes: missing node labels found. Use relabel=False."
+        ) from err
+    x, y = zip(*mapping)
+    if len(set(y)) != len(G):
+        raise nx.NetworkXError(
+            "Failed to relabel nodes: duplicate node labels found. Use relabel=False."
+        )
+    mapping = dict(mapping)
+    H = nx.relabel_nodes(G, mapping)
+    # relabel attributes
+    for n in G:
+        m = mapping[n]
+        H.nodes[m]["id"] = n
+        H.nodes[m].pop("label")
+        if "pid" in H.nodes[m]:
+            H.nodes[m]["pid"] = mapping[G.nodes[n]["pid"]]
+        if "parents" in H.nodes[m]:
+            H.nodes[m]["parents"] = [mapping[p] for p in G.nodes[n]["parents"]]
+    return H
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/gml.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/gml.py
new file mode 100644
index 0000000000000000000000000000000000000000..c53496c3e7fd2797ce2f786e665d0ad069d8184c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/gml.py
@@ -0,0 +1,879 @@
+"""
+Read graphs in GML format.
+
+"GML, the Graph Modelling Language, is our proposal for a portable
+file format for graphs. GML's key features are portability, simple
+syntax, extensibility and flexibility. A GML file consists of a
+hierarchical key-value lists. Graphs can be annotated with arbitrary
+data structures. The idea for a common file format was born at the
+GD'95; this proposal is the outcome of many discussions. GML is the
+standard file format in the Graphlet graph editor system. It has been
+overtaken and adapted by several other systems for drawing graphs."
+
+GML files are stored using a 7-bit ASCII encoding with any extended
+ASCII characters (iso8859-1) appearing as HTML character entities.
+You will need to give some thought into how the exported data should
+interact with different languages and even different Python versions.
+Re-importing from gml is also a concern.
+
+Without specifying a `stringizer`/`destringizer`, the code is capable of
+writing `int`/`float`/`str`/`dict`/`list` data as required by the GML
+specification.  For writing other data types, and for reading data other
+than `str` you need to explicitly supply a `stringizer`/`destringizer`.
+
+For additional documentation on the GML file format, please see the
+`GML website `_.
+
+Several example graphs in GML format may be found on Mark Newman's
+`Network data page `_.
+"""
+
+import html.entities as htmlentitydefs
+import re
+from ast import literal_eval
+from collections import defaultdict
+from enum import Enum
+from io import StringIO
+from typing import Any, NamedTuple
+
+import networkx as nx
+from networkx.exception import NetworkXError
+from networkx.utils import open_file
+
+__all__ = ["read_gml", "parse_gml", "generate_gml", "write_gml"]
+
+
+def escape(text):
+    """Use XML character references to escape characters.
+
+    Use XML character references for unprintable or non-ASCII
+    characters, double quotes and ampersands in a string
+    """
+
+    def fixup(m):
+        ch = m.group(0)
+        return "&#" + str(ord(ch)) + ";"
+
+    text = re.sub('[^ -~]|[&"]', fixup, text)
+    return text if isinstance(text, str) else str(text)
+
+
+def unescape(text):
+    """Replace XML character references with the referenced characters"""
+
+    def fixup(m):
+        text = m.group(0)
+        if text[1] == "#":
+            # Character reference
+            if text[2] == "x":
+                code = int(text[3:-1], 16)
+            else:
+                code = int(text[2:-1])
+        else:
+            # Named entity
+            try:
+                code = htmlentitydefs.name2codepoint[text[1:-1]]
+            except KeyError:
+                return text  # leave unchanged
+        try:
+            return chr(code)
+        except (ValueError, OverflowError):
+            return text  # leave unchanged
+
+    return re.sub("&(?:[0-9A-Za-z]+|#(?:[0-9]+|x[0-9A-Fa-f]+));", fixup, text)
+
+
+def literal_destringizer(rep):
+    """Convert a Python literal to the value it represents.
+
+    Parameters
+    ----------
+    rep : string
+        A Python literal.
+
+    Returns
+    -------
+    value : object
+        The value of the Python literal.
+
+    Raises
+    ------
+    ValueError
+        If `rep` is not a Python literal.
+    """
+    if isinstance(rep, str):
+        orig_rep = rep
+        try:
+            return literal_eval(rep)
+        except SyntaxError as err:
+            raise ValueError(f"{orig_rep!r} is not a valid Python literal") from err
+    else:
+        raise ValueError(f"{rep!r} is not a string")
+
+
+@open_file(0, mode="rb")
+@nx._dispatchable(graphs=None, returns_graph=True)
+def read_gml(path, label="label", destringizer=None):
+    """Read graph in GML format from `path`.
+
+    Parameters
+    ----------
+    path : file or string
+        Filename or file handle to read.
+        Filenames ending in .gz or .bz2 will be decompressed.
+
+    label : string, optional
+        If not None, the parsed nodes will be renamed according to node
+        attributes indicated by `label`. Default value: 'label'.
+
+    destringizer : callable, optional
+        A `destringizer` that recovers values stored as strings in GML. If it
+        cannot convert a string to a value, a `ValueError` is raised. Default
+        value : None.
+
+    Returns
+    -------
+    G : NetworkX graph
+        The parsed graph.
+
+    Raises
+    ------
+    NetworkXError
+        If the input cannot be parsed.
+
+    See Also
+    --------
+    write_gml, parse_gml
+    literal_destringizer
+
+    Notes
+    -----
+    GML files are stored using a 7-bit ASCII encoding with any extended
+    ASCII characters (iso8859-1) appearing as HTML character entities.
+    Without specifying a `stringizer`/`destringizer`, the code is capable of
+    writing `int`/`float`/`str`/`dict`/`list` data as required by the GML
+    specification.  For writing other data types, and for reading data other
+    than `str` you need to explicitly supply a `stringizer`/`destringizer`.
+
+    For additional documentation on the GML file format, please see the
+    `GML url `_.
+
+    See the module docstring :mod:`networkx.readwrite.gml` for more details.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> nx.write_gml(G, "test_path4.gml")
+
+    GML values are interpreted as strings by default:
+
+    >>> H = nx.read_gml("test_path4.gml")
+    >>> H.nodes
+    NodeView(('0', '1', '2', '3'))
+
+    When a `destringizer` is provided, GML values are converted to the provided type.
+    For example, integer nodes can be recovered as shown below:
+
+    >>> J = nx.read_gml("test_path4.gml", destringizer=int)
+    >>> J.nodes
+    NodeView((0, 1, 2, 3))
+
+    """
+
+    def filter_lines(lines):
+        for line in lines:
+            try:
+                line = line.decode("ascii")
+            except UnicodeDecodeError as err:
+                raise NetworkXError("input is not ASCII-encoded") from err
+            if not isinstance(line, str):
+                lines = str(lines)
+            if line and line[-1] == "\n":
+                line = line[:-1]
+            yield line
+
+    G = parse_gml_lines(filter_lines(path), label, destringizer)
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def parse_gml(lines, label="label", destringizer=None):
+    """Parse GML graph from a string or iterable.
+
+    Parameters
+    ----------
+    lines : string or iterable of strings
+       Data in GML format.
+
+    label : string, optional
+        If not None, the parsed nodes will be renamed according to node
+        attributes indicated by `label`. Default value: 'label'.
+
+    destringizer : callable, optional
+        A `destringizer` that recovers values stored as strings in GML. If it
+        cannot convert a string to a value, a `ValueError` is raised. Default
+        value : None.
+
+    Returns
+    -------
+    G : NetworkX graph
+        The parsed graph.
+
+    Raises
+    ------
+    NetworkXError
+        If the input cannot be parsed.
+
+    See Also
+    --------
+    write_gml, read_gml
+
+    Notes
+    -----
+    This stores nested GML attributes as dictionaries in the NetworkX graph,
+    node, and edge attribute structures.
+
+    GML files are stored using a 7-bit ASCII encoding with any extended
+    ASCII characters (iso8859-1) appearing as HTML character entities.
+    Without specifying a `stringizer`/`destringizer`, the code is capable of
+    writing `int`/`float`/`str`/`dict`/`list` data as required by the GML
+    specification.  For writing other data types, and for reading data other
+    than `str` you need to explicitly supply a `stringizer`/`destringizer`.
+
+    For additional documentation on the GML file format, please see the
+    `GML url `_.
+
+    See the module docstring :mod:`networkx.readwrite.gml` for more details.
+    """
+
+    def decode_line(line):
+        if isinstance(line, bytes):
+            try:
+                line.decode("ascii")
+            except UnicodeDecodeError as err:
+                raise NetworkXError("input is not ASCII-encoded") from err
+        if not isinstance(line, str):
+            line = str(line)
+        return line
+
+    def filter_lines(lines):
+        if isinstance(lines, str):
+            lines = decode_line(lines)
+            lines = lines.splitlines()
+            yield from lines
+        else:
+            for line in lines:
+                line = decode_line(line)
+                if line and line[-1] == "\n":
+                    line = line[:-1]
+                if line.find("\n") != -1:
+                    raise NetworkXError("input line contains newline")
+                yield line
+
+    G = parse_gml_lines(filter_lines(lines), label, destringizer)
+    return G
+
+
+class Pattern(Enum):
+    """encodes the index of each token-matching pattern in `tokenize`."""
+
+    KEYS = 0
+    REALS = 1
+    INTS = 2
+    STRINGS = 3
+    DICT_START = 4
+    DICT_END = 5
+    COMMENT_WHITESPACE = 6
+
+
+class Token(NamedTuple):
+    category: Pattern
+    value: Any
+    line: int
+    position: int
+
+
+LIST_START_VALUE = "_networkx_list_start"
+
+
+def parse_gml_lines(lines, label, destringizer):
+    """Parse GML `lines` into a graph."""
+
+    def tokenize():
+        patterns = [
+            r"[A-Za-z][0-9A-Za-z_]*\b",  # keys
+            # reals
+            r"[+-]?(?:[0-9]*\.[0-9]+|[0-9]+\.[0-9]*|INF)(?:[Ee][+-]?[0-9]+)?",
+            r"[+-]?[0-9]+",  # ints
+            r'".*?"',  # strings
+            r"\[",  # dict start
+            r"\]",  # dict end
+            r"#.*$|\s+",  # comments and whitespaces
+        ]
+        tokens = re.compile("|".join(f"({pattern})" for pattern in patterns))
+        lineno = 0
+        multilines = []  # entries spread across multiple lines
+        for line in lines:
+            pos = 0
+
+            # deal with entries spread across multiple lines
+            #
+            # should we actually have to deal with escaped "s then do it here
+            if multilines:
+                multilines.append(line.strip())
+                if line[-1] == '"':  # closing multiline entry
+                    # multiline entries will be joined by space. cannot
+                    # reintroduce newlines as this will break the tokenizer
+                    line = " ".join(multilines)
+                    multilines = []
+                else:  # continued multiline entry
+                    lineno += 1
+                    continue
+            else:
+                if line.count('"') == 1:  # opening multiline entry
+                    if line.strip()[0] != '"' and line.strip()[-1] != '"':
+                        # since we expect something like key "value", the " should not be found at ends
+                        # otherwise tokenizer will pick up the formatting mistake.
+                        multilines = [line.rstrip()]
+                        lineno += 1
+                        continue
+
+            length = len(line)
+
+            while pos < length:
+                match = tokens.match(line, pos)
+                if match is None:
+                    m = f"cannot tokenize {line[pos:]} at ({lineno + 1}, {pos + 1})"
+                    raise NetworkXError(m)
+                for i in range(len(patterns)):
+                    group = match.group(i + 1)
+                    if group is not None:
+                        if i == 0:  # keys
+                            value = group.rstrip()
+                        elif i == 1:  # reals
+                            value = float(group)
+                        elif i == 2:  # ints
+                            value = int(group)
+                        else:
+                            value = group
+                        if i != 6:  # comments and whitespaces
+                            yield Token(Pattern(i), value, lineno + 1, pos + 1)
+                        pos += len(group)
+                        break
+            lineno += 1
+        yield Token(None, None, lineno + 1, 1)  # EOF
+
+    def unexpected(curr_token, expected):
+        category, value, lineno, pos = curr_token
+        value = repr(value) if value is not None else "EOF"
+        raise NetworkXError(f"expected {expected}, found {value} at ({lineno}, {pos})")
+
+    def consume(curr_token, category, expected):
+        if curr_token.category == category:
+            return next(tokens)
+        unexpected(curr_token, expected)
+
+    def parse_kv(curr_token):
+        dct = defaultdict(list)
+        while curr_token.category == Pattern.KEYS:
+            key = curr_token.value
+            curr_token = next(tokens)
+            category = curr_token.category
+            if category == Pattern.REALS or category == Pattern.INTS:
+                value = curr_token.value
+                curr_token = next(tokens)
+            elif category == Pattern.STRINGS:
+                value = unescape(curr_token.value[1:-1])
+                if destringizer:
+                    try:
+                        value = destringizer(value)
+                    except ValueError:
+                        pass
+                # Special handling for empty lists and tuples
+                if value == "()":
+                    value = ()
+                if value == "[]":
+                    value = []
+                curr_token = next(tokens)
+            elif category == Pattern.DICT_START:
+                curr_token, value = parse_dict(curr_token)
+            else:
+                # Allow for string convertible id and label values
+                if key in ("id", "label", "source", "target"):
+                    try:
+                        # String convert the token value
+                        value = unescape(str(curr_token.value))
+                        if destringizer:
+                            try:
+                                value = destringizer(value)
+                            except ValueError:
+                                pass
+                        curr_token = next(tokens)
+                    except Exception:
+                        msg = (
+                            "an int, float, string, '[' or string"
+                            + " convertible ASCII value for node id or label"
+                        )
+                        unexpected(curr_token, msg)
+                # Special handling for nan and infinity.  Since the gml language
+                # defines unquoted strings as keys, the numeric and string branches
+                # are skipped and we end up in this special branch, so we need to
+                # convert the current token value to a float for NAN and plain INF.
+                # +/-INF are handled in the pattern for 'reals' in tokenize().  This
+                # allows labels and values to be nan or infinity, but not keys.
+                elif curr_token.value in {"NAN", "INF"}:
+                    value = float(curr_token.value)
+                    curr_token = next(tokens)
+                else:  # Otherwise error out
+                    unexpected(curr_token, "an int, float, string or '['")
+            dct[key].append(value)
+
+        def clean_dict_value(value):
+            if not isinstance(value, list):
+                return value
+            if len(value) == 1:
+                return value[0]
+            if value[0] == LIST_START_VALUE:
+                return value[1:]
+            return value
+
+        dct = {key: clean_dict_value(value) for key, value in dct.items()}
+        return curr_token, dct
+
+    def parse_dict(curr_token):
+        # dict start
+        curr_token = consume(curr_token, Pattern.DICT_START, "'['")
+        # dict contents
+        curr_token, dct = parse_kv(curr_token)
+        # dict end
+        curr_token = consume(curr_token, Pattern.DICT_END, "']'")
+        return curr_token, dct
+
+    def parse_graph():
+        curr_token, dct = parse_kv(next(tokens))
+        if curr_token.category is not None:  # EOF
+            unexpected(curr_token, "EOF")
+        if "graph" not in dct:
+            raise NetworkXError("input contains no graph")
+        graph = dct["graph"]
+        if isinstance(graph, list):
+            raise NetworkXError("input contains more than one graph")
+        return graph
+
+    tokens = tokenize()
+    graph = parse_graph()
+
+    directed = graph.pop("directed", False)
+    multigraph = graph.pop("multigraph", False)
+    if not multigraph:
+        G = nx.DiGraph() if directed else nx.Graph()
+    else:
+        G = nx.MultiDiGraph() if directed else nx.MultiGraph()
+    graph_attr = {k: v for k, v in graph.items() if k not in ("node", "edge")}
+    G.graph.update(graph_attr)
+
+    def pop_attr(dct, category, attr, i):
+        try:
+            return dct.pop(attr)
+        except KeyError as err:
+            raise NetworkXError(f"{category} #{i} has no {attr!r} attribute") from err
+
+    nodes = graph.get("node", [])
+    mapping = {}
+    node_labels = set()
+    for i, node in enumerate(nodes if isinstance(nodes, list) else [nodes]):
+        id = pop_attr(node, "node", "id", i)
+        if id in G:
+            raise NetworkXError(f"node id {id!r} is duplicated")
+        if label is not None and label != "id":
+            node_label = pop_attr(node, "node", label, i)
+            if node_label in node_labels:
+                raise NetworkXError(f"node label {node_label!r} is duplicated")
+            node_labels.add(node_label)
+            mapping[id] = node_label
+        G.add_node(id, **node)
+
+    edges = graph.get("edge", [])
+    for i, edge in enumerate(edges if isinstance(edges, list) else [edges]):
+        source = pop_attr(edge, "edge", "source", i)
+        target = pop_attr(edge, "edge", "target", i)
+        if source not in G:
+            raise NetworkXError(f"edge #{i} has undefined source {source!r}")
+        if target not in G:
+            raise NetworkXError(f"edge #{i} has undefined target {target!r}")
+        if not multigraph:
+            if not G.has_edge(source, target):
+                G.add_edge(source, target, **edge)
+            else:
+                arrow = "->" if directed else "--"
+                msg = f"edge #{i} ({source!r}{arrow}{target!r}) is duplicated"
+                raise nx.NetworkXError(msg)
+        else:
+            key = edge.pop("key", None)
+            if key is not None and G.has_edge(source, target, key):
+                arrow = "->" if directed else "--"
+                msg = f"edge #{i} ({source!r}{arrow}{target!r}, {key!r})"
+                msg2 = 'Hint: If multigraph add "multigraph 1" to file header.'
+                raise nx.NetworkXError(msg + " is duplicated\n" + msg2)
+            G.add_edge(source, target, key, **edge)
+
+    if label is not None and label != "id":
+        G = nx.relabel_nodes(G, mapping)
+    return G
+
+
+def literal_stringizer(value):
+    """Convert a `value` to a Python literal in GML representation.
+
+    Parameters
+    ----------
+    value : object
+        The `value` to be converted to GML representation.
+
+    Returns
+    -------
+    rep : string
+        A double-quoted Python literal representing value. Unprintable
+        characters are replaced by XML character references.
+
+    Raises
+    ------
+    ValueError
+        If `value` cannot be converted to GML.
+
+    Notes
+    -----
+    The original value can be recovered using the
+    :func:`networkx.readwrite.gml.literal_destringizer` function.
+    """
+
+    def stringize(value):
+        if isinstance(value, int | bool) or value is None:
+            if value is True:  # GML uses 1/0 for boolean values.
+                buf.write(str(1))
+            elif value is False:
+                buf.write(str(0))
+            else:
+                buf.write(str(value))
+        elif isinstance(value, str):
+            text = repr(value)
+            if text[0] != "u":
+                try:
+                    value.encode("latin1")
+                except UnicodeEncodeError:
+                    text = "u" + text
+            buf.write(text)
+        elif isinstance(value, float | complex | str | bytes):
+            buf.write(repr(value))
+        elif isinstance(value, list):
+            buf.write("[")
+            first = True
+            for item in value:
+                if not first:
+                    buf.write(",")
+                else:
+                    first = False
+                stringize(item)
+            buf.write("]")
+        elif isinstance(value, tuple):
+            if len(value) > 1:
+                buf.write("(")
+                first = True
+                for item in value:
+                    if not first:
+                        buf.write(",")
+                    else:
+                        first = False
+                    stringize(item)
+                buf.write(")")
+            elif value:
+                buf.write("(")
+                stringize(value[0])
+                buf.write(",)")
+            else:
+                buf.write("()")
+        elif isinstance(value, dict):
+            buf.write("{")
+            first = True
+            for key, value in value.items():
+                if not first:
+                    buf.write(",")
+                else:
+                    first = False
+                stringize(key)
+                buf.write(":")
+                stringize(value)
+            buf.write("}")
+        elif isinstance(value, set):
+            buf.write("{")
+            first = True
+            for item in value:
+                if not first:
+                    buf.write(",")
+                else:
+                    first = False
+                stringize(item)
+            buf.write("}")
+        else:
+            msg = f"{value!r} cannot be converted into a Python literal"
+            raise ValueError(msg)
+
+    buf = StringIO()
+    stringize(value)
+    return buf.getvalue()
+
+
+def generate_gml(G, stringizer=None):
+    r"""Generate a single entry of the graph `G` in GML format.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        The graph to be converted to GML.
+
+    stringizer : callable, optional
+        A `stringizer` which converts non-int/non-float/non-dict values into
+        strings. If it cannot convert a value into a string, it should raise a
+        `ValueError` to indicate that. Default value: None.
+
+    Returns
+    -------
+    lines: generator of strings
+        Lines of GML data. Newlines are not appended.
+
+    Raises
+    ------
+    NetworkXError
+        If `stringizer` cannot convert a value into a string, or the value to
+        convert is not a string while `stringizer` is None.
+
+    See Also
+    --------
+    literal_stringizer
+
+    Notes
+    -----
+    Graph attributes named 'directed', 'multigraph', 'node' or
+    'edge', node attributes named 'id' or 'label', edge attributes
+    named 'source' or 'target' (or 'key' if `G` is a multigraph)
+    are ignored because these attribute names are used to encode the graph
+    structure.
+
+    GML files are stored using a 7-bit ASCII encoding with any extended
+    ASCII characters (iso8859-1) appearing as HTML character entities.
+    Without specifying a `stringizer`/`destringizer`, the code is capable of
+    writing `int`/`float`/`str`/`dict`/`list` data as required by the GML
+    specification.  For writing other data types, and for reading data other
+    than `str` you need to explicitly supply a `stringizer`/`destringizer`.
+
+    For additional documentation on the GML file format, please see the
+    `GML url `_.
+
+    See the module docstring :mod:`networkx.readwrite.gml` for more details.
+
+    Examples
+    --------
+    >>> G = nx.Graph()
+    >>> G.add_node("1")
+    >>> print("\n".join(nx.generate_gml(G)))
+    graph [
+      node [
+        id 0
+        label "1"
+      ]
+    ]
+    >>> G = nx.MultiGraph([("a", "b"), ("a", "b")])
+    >>> print("\n".join(nx.generate_gml(G)))
+    graph [
+      multigraph 1
+      node [
+        id 0
+        label "a"
+      ]
+      node [
+        id 1
+        label "b"
+      ]
+      edge [
+        source 0
+        target 1
+        key 0
+      ]
+      edge [
+        source 0
+        target 1
+        key 1
+      ]
+    ]
+    """
+    valid_keys = re.compile("^[A-Za-z][0-9A-Za-z_]*$")
+
+    def stringize(key, value, ignored_keys, indent, in_list=False):
+        if not isinstance(key, str):
+            raise NetworkXError(f"{key!r} is not a string")
+        if not valid_keys.match(key):
+            raise NetworkXError(f"{key!r} is not a valid key")
+        if not isinstance(key, str):
+            key = str(key)
+        if key not in ignored_keys:
+            if isinstance(value, int | bool):
+                if key == "label":
+                    yield indent + key + ' "' + str(value) + '"'
+                elif value is True:
+                    # python bool is an instance of int
+                    yield indent + key + " 1"
+                elif value is False:
+                    yield indent + key + " 0"
+                # GML only supports signed 32-bit integers
+                elif value < -(2**31) or value >= 2**31:
+                    yield indent + key + ' "' + str(value) + '"'
+                else:
+                    yield indent + key + " " + str(value)
+            elif isinstance(value, float):
+                text = repr(value).upper()
+                # GML matches INF to keys, so prepend + to INF. Use repr(float(*))
+                # instead of string literal to future proof against changes to repr.
+                if text == repr(float("inf")).upper():
+                    text = "+" + text
+                else:
+                    # GML requires that a real literal contain a decimal point, but
+                    # repr may not output a decimal point when the mantissa is
+                    # integral and hence needs fixing.
+                    epos = text.rfind("E")
+                    if epos != -1 and text.find(".", 0, epos) == -1:
+                        text = text[:epos] + "." + text[epos:]
+                if key == "label":
+                    yield indent + key + ' "' + text + '"'
+                else:
+                    yield indent + key + " " + text
+            elif isinstance(value, dict):
+                yield indent + key + " ["
+                next_indent = indent + "  "
+                for key, value in value.items():
+                    yield from stringize(key, value, (), next_indent)
+                yield indent + "]"
+            elif isinstance(value, tuple) and key == "label":
+                yield indent + key + f' "({",".join(repr(v) for v in value)})"'
+            elif isinstance(value, list | tuple) and key != "label" and not in_list:
+                if len(value) == 0:
+                    yield indent + key + " " + f'"{value!r}"'
+                if len(value) == 1:
+                    yield indent + key + " " + f'"{LIST_START_VALUE}"'
+                for val in value:
+                    yield from stringize(key, val, (), indent, True)
+            else:
+                if stringizer:
+                    try:
+                        value = stringizer(value)
+                    except ValueError as err:
+                        raise NetworkXError(
+                            f"{value!r} cannot be converted into a string"
+                        ) from err
+                if not isinstance(value, str):
+                    raise NetworkXError(f"{value!r} is not a string")
+                yield indent + key + ' "' + escape(value) + '"'
+
+    multigraph = G.is_multigraph()
+    yield "graph ["
+
+    # Output graph attributes
+    if G.is_directed():
+        yield "  directed 1"
+    if multigraph:
+        yield "  multigraph 1"
+    ignored_keys = {"directed", "multigraph", "node", "edge"}
+    for attr, value in G.graph.items():
+        yield from stringize(attr, value, ignored_keys, "  ")
+
+    # Output node data
+    node_id = dict(zip(G, range(len(G))))
+    ignored_keys = {"id", "label"}
+    for node, attrs in G.nodes.items():
+        yield "  node ["
+        yield "    id " + str(node_id[node])
+        yield from stringize("label", node, (), "    ")
+        for attr, value in attrs.items():
+            yield from stringize(attr, value, ignored_keys, "    ")
+        yield "  ]"
+
+    # Output edge data
+    ignored_keys = {"source", "target"}
+    kwargs = {"data": True}
+    if multigraph:
+        ignored_keys.add("key")
+        kwargs["keys"] = True
+    for e in G.edges(**kwargs):
+        yield "  edge ["
+        yield "    source " + str(node_id[e[0]])
+        yield "    target " + str(node_id[e[1]])
+        if multigraph:
+            yield from stringize("key", e[2], (), "    ")
+        for attr, value in e[-1].items():
+            yield from stringize(attr, value, ignored_keys, "    ")
+        yield "  ]"
+    yield "]"
+
+
+@open_file(1, mode="wb")
+def write_gml(G, path, stringizer=None):
+    """Write a graph `G` in GML format to the file or file handle `path`.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+        The graph to be converted to GML.
+
+    path : string or file
+        Filename or file handle to write to.
+        Filenames ending in .gz or .bz2 will be compressed.
+
+    stringizer : callable, optional
+        A `stringizer` which converts non-int/non-float/non-dict values into
+        strings. If it cannot convert a value into a string, it should raise a
+        `ValueError` to indicate that. Default value: None.
+
+    Raises
+    ------
+    NetworkXError
+        If `stringizer` cannot convert a value into a string, or the value to
+        convert is not a string while `stringizer` is None.
+
+    See Also
+    --------
+    read_gml, generate_gml
+    literal_stringizer
+
+    Notes
+    -----
+    Graph attributes named 'directed', 'multigraph', 'node' or
+    'edge', node attributes named 'id' or 'label', edge attributes
+    named 'source' or 'target' (or 'key' if `G` is a multigraph)
+    are ignored because these attribute names are used to encode the graph
+    structure.
+
+    GML files are stored using a 7-bit ASCII encoding with any extended
+    ASCII characters (iso8859-1) appearing as HTML character entities.
+    Without specifying a `stringizer`/`destringizer`, the code is capable of
+    writing `int`/`float`/`str`/`dict`/`list` data as required by the GML
+    specification.  For writing other data types, and for reading data other
+    than `str` you need to explicitly supply a `stringizer`/`destringizer`.
+
+    Note that while we allow non-standard GML to be read from a file, we make
+    sure to write GML format. In particular, underscores are not allowed in
+    attribute names.
+    For additional documentation on the GML file format, please see the
+    `GML url `_.
+
+    See the module docstring :mod:`networkx.readwrite.gml` for more details.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(5)
+    >>> nx.write_gml(G, "test_path5.gml")
+
+    Filenames ending in .gz or .bz2 will be compressed.
+
+    >>> nx.write_gml(G, "test_path5.gml.gz")
+    """
+    for line in generate_gml(G, stringizer):
+        path.write((line + "\n").encode("ascii"))
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/graph6.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/graph6.py
new file mode 100644
index 0000000000000000000000000000000000000000..cdc2925e5fb264a3d3e3235571682e38530d7f69
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/graph6.py
@@ -0,0 +1,427 @@
+# Original author: D. Eppstein, UC Irvine, August 12, 2003.
+# The original code at http://www.ics.uci.edu/~eppstein/PADS/ is public domain.
+"""Functions for reading and writing graphs in the *graph6* format.
+
+The *graph6* file format is suitable for small graphs or large dense
+graphs. For large sparse graphs, use the *sparse6* format.
+
+For more information, see the `graph6`_ homepage.
+
+.. _graph6: http://users.cecs.anu.edu.au/~bdm/data/formats.html
+
+"""
+
+from itertools import islice
+
+import networkx as nx
+from networkx.exception import NetworkXError
+from networkx.utils import not_implemented_for, open_file
+
+__all__ = ["from_graph6_bytes", "read_graph6", "to_graph6_bytes", "write_graph6"]
+
+
+def _generate_graph6_bytes(G, nodes, header):
+    """Yield bytes in the graph6 encoding of a graph.
+
+    `G` is an undirected simple graph. `nodes` is the list of nodes for
+    which the node-induced subgraph will be encoded; if `nodes` is the
+    list of all nodes in the graph, the entire graph will be
+    encoded. `header` is a Boolean that specifies whether to generate
+    the header ``b'>>graph6<<'`` before the remaining data.
+
+    This function generates `bytes` objects in the following order:
+
+    1. the header (if requested),
+    2. the encoding of the number of nodes,
+    3. each character, one-at-a-time, in the encoding of the requested
+       node-induced subgraph,
+    4. a newline character.
+
+    This function raises :exc:`ValueError` if the graph is too large for
+    the graph6 format (that is, greater than ``2 ** 36`` nodes).
+
+    """
+    n = len(G)
+    if n >= 2**36:
+        raise ValueError(
+            "graph6 is only defined if number of nodes is less than 2 ** 36"
+        )
+    if header:
+        yield b">>graph6<<"
+    for d in n_to_data(n):
+        yield str.encode(chr(d + 63))
+    # This generates the same as `(v in G[u] for u, v in combinations(G, 2))`,
+    # but in "column-major" order instead of "row-major" order.
+    bits = (nodes[j] in G[nodes[i]] for j in range(1, n) for i in range(j))
+    chunk = list(islice(bits, 6))
+    while chunk:
+        d = sum(b << 5 - i for i, b in enumerate(chunk))
+        yield str.encode(chr(d + 63))
+        chunk = list(islice(bits, 6))
+    yield b"\n"
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def from_graph6_bytes(bytes_in):
+    """Read a simple undirected graph in graph6 format from bytes.
+
+    Parameters
+    ----------
+    bytes_in : bytes
+       Data in graph6 format
+
+    Returns
+    -------
+    G : Graph
+
+    Raises
+    ------
+    NetworkXError
+        If `bytes_in` is unable to be parsed in graph6 format
+
+    ValueError
+        If any character ``c`` in bytes_in does not satisfy
+        ``63 <= ord(c) < 127``.
+
+    Examples
+    --------
+    >>> G = nx.from_graph6_bytes(b"A_")
+    >>> sorted(G.edges())
+    [(0, 1)]
+
+    Notes
+    -----
+    Per the graph6 spec, the header (e.g. ``b'>>graph6<<'``) must not be
+    followed by a newline character.
+
+    See Also
+    --------
+    read_graph6, write_graph6
+
+    References
+    ----------
+    .. [1] Graph6 specification
+           
+
+    """
+
+    def bits():
+        """Returns sequence of individual bits from 6-bit-per-value
+        list of data values."""
+        for d in data:
+            for i in [5, 4, 3, 2, 1, 0]:
+                yield (d >> i) & 1
+
+    # Ignore trailing newline
+    bytes_in = bytes_in.rstrip(b"\n")
+
+    if bytes_in.startswith(b">>graph6<<"):
+        bytes_in = bytes_in[10:]
+
+    data = [c - 63 for c in bytes_in]
+    if any(c > 63 for c in data):
+        raise ValueError("each input character must be in range(63, 127)")
+
+    n, data = data_to_n(data)
+    nd = (n * (n - 1) // 2 + 5) // 6
+    if len(data) != nd:
+        raise NetworkXError(
+            f"Expected {n * (n - 1) // 2} bits but got {len(data) * 6} in graph6"
+        )
+
+    G = nx.Graph()
+    G.add_nodes_from(range(n))
+    for (i, j), b in zip(((i, j) for j in range(1, n) for i in range(j)), bits()):
+        if b:
+            G.add_edge(i, j)
+
+    return G
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+def to_graph6_bytes(G, nodes=None, header=True):
+    """Convert a simple undirected graph to bytes in graph6 format.
+
+    Parameters
+    ----------
+    G : Graph (undirected)
+
+    nodes: list or iterable
+       Nodes are labeled 0...n-1 in the order provided.  If None the ordering
+       given by ``G.nodes()`` is used.
+
+    header: bool
+       If True add '>>graph6<<' bytes to head of data.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If the graph is directed or is a multigraph.
+
+    ValueError
+        If the graph has at least ``2 ** 36`` nodes; the graph6 format
+        is only defined for graphs of order less than ``2 ** 36``.
+
+    Examples
+    --------
+    >>> nx.to_graph6_bytes(nx.path_graph(2))
+    b'>>graph6<
+
+    """
+    if nodes is not None:
+        G = G.subgraph(nodes)
+    H = nx.convert_node_labels_to_integers(G)
+    nodes = sorted(H.nodes())
+    return b"".join(_generate_graph6_bytes(H, nodes, header))
+
+
+@open_file(0, mode="rb")
+@nx._dispatchable(graphs=None, returns_graph=True)
+def read_graph6(path):
+    """Read simple undirected graphs in graph6 format from path.
+
+    Parameters
+    ----------
+    path : file or string
+       Filename or file handle to read.
+       Filenames ending in .gz or .bz2 will be decompressed.
+
+    Returns
+    -------
+    G : Graph or list of Graphs
+       If the file contains multiple lines then a list of graphs is returned
+
+    Raises
+    ------
+    NetworkXError
+        If the string is unable to be parsed in graph6 format
+
+    Examples
+    --------
+    You can read a graph6 file by giving the path to the file::
+
+        >>> import tempfile
+        >>> with tempfile.NamedTemporaryFile(delete=False) as f:
+        ...     _ = f.write(b">>graph6<>> list(G.edges())
+        [(0, 1)]
+
+    You can also read a graph6 file by giving an open file-like object::
+
+        >>> import tempfile
+        >>> with tempfile.NamedTemporaryFile() as f:
+        ...     _ = f.write(b">>graph6<>> list(G.edges())
+        [(0, 1)]
+
+    See Also
+    --------
+    from_graph6_bytes, write_graph6
+
+    References
+    ----------
+    .. [1] Graph6 specification
+           
+
+    """
+    glist = []
+    for line in path:
+        line = line.strip()
+        if not len(line):
+            continue
+        glist.append(from_graph6_bytes(line))
+    if len(glist) == 1:
+        return glist[0]
+    else:
+        return glist
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@open_file(1, mode="wb")
+def write_graph6(G, path, nodes=None, header=True):
+    """Write a simple undirected graph to a path in graph6 format.
+
+    Parameters
+    ----------
+    G : Graph (undirected)
+
+    path : file or string
+       File or filename to write.
+       Filenames ending in .gz or .bz2 will be compressed.
+
+    nodes: list or iterable
+       Nodes are labeled 0...n-1 in the order provided.  If None the ordering
+       given by ``G.nodes()`` is used.
+
+    header: bool
+       If True add '>>graph6<<' string to head of data
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If the graph is directed or is a multigraph.
+
+    ValueError
+        If the graph has at least ``2 ** 36`` nodes; the graph6 format
+        is only defined for graphs of order less than ``2 ** 36``.
+
+    Examples
+    --------
+    You can write a graph6 file by giving the path to a file::
+
+        >>> import tempfile
+        >>> with tempfile.NamedTemporaryFile(delete=False) as f:
+        ...     nx.write_graph6(nx.path_graph(2), f.name)
+        ...     _ = f.seek(0)
+        ...     print(f.read())
+        b'>>graph6<
+
+    """
+    return write_graph6_file(G, path, nodes=nodes, header=header)
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+def write_graph6_file(G, f, nodes=None, header=True):
+    """Write a simple undirected graph to a file-like object in graph6 format.
+
+    Parameters
+    ----------
+    G : Graph (undirected)
+
+    f : file-like object
+       The file to write.
+
+    nodes: list or iterable
+       Nodes are labeled 0...n-1 in the order provided.  If None the ordering
+       given by ``G.nodes()`` is used.
+
+    header: bool
+       If True add '>>graph6<<' string to head of data
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If the graph is directed or is a multigraph.
+
+    ValueError
+        If the graph has at least ``2 ** 36`` nodes; the graph6 format
+        is only defined for graphs of order less than ``2 ** 36``.
+
+    Examples
+    --------
+    You can write a graph6 file by giving an open file-like object::
+
+        >>> import tempfile
+        >>> with tempfile.NamedTemporaryFile() as f:
+        ...     nx.write_graph6(nx.path_graph(2), f)
+        ...     _ = f.seek(0)
+        ...     print(f.read())
+        b'>>graph6<
+
+    """
+    if nodes is not None:
+        G = G.subgraph(nodes)
+    H = nx.convert_node_labels_to_integers(G)
+    nodes = sorted(H.nodes())
+    for b in _generate_graph6_bytes(H, nodes, header):
+        f.write(b)
+
+
+def data_to_n(data):
+    """Read initial one-, four- or eight-unit value from graph6
+    integer sequence.
+
+    Return (value, rest of seq.)"""
+    if data[0] <= 62:
+        return data[0], data[1:]
+    if data[1] <= 62:
+        return (data[1] << 12) + (data[2] << 6) + data[3], data[4:]
+    return (
+        (data[2] << 30)
+        + (data[3] << 24)
+        + (data[4] << 18)
+        + (data[5] << 12)
+        + (data[6] << 6)
+        + data[7],
+        data[8:],
+    )
+
+
+def n_to_data(n):
+    """Convert an integer to one-, four- or eight-unit graph6 sequence.
+
+    This function is undefined if `n` is not in ``range(2 ** 36)``.
+
+    """
+    if n <= 62:
+        return [n]
+    elif n <= 258047:
+        return [63, (n >> 12) & 0x3F, (n >> 6) & 0x3F, n & 0x3F]
+    else:  # if n <= 68719476735:
+        return [
+            63,
+            63,
+            (n >> 30) & 0x3F,
+            (n >> 24) & 0x3F,
+            (n >> 18) & 0x3F,
+            (n >> 12) & 0x3F,
+            (n >> 6) & 0x3F,
+            n & 0x3F,
+        ]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/graphml.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/graphml.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ca1741452c963d99ffb8bfad2fb09eab8badd6b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/graphml.py
@@ -0,0 +1,1053 @@
+"""
+*******
+GraphML
+*******
+Read and write graphs in GraphML format.
+
+.. warning::
+
+    This parser uses the standard xml library present in Python, which is
+    insecure - see :external+python:mod:`xml` for additional information.
+    Only parse GraphML files you trust.
+
+This implementation does not support mixed graphs (directed and unidirected
+edges together), hyperedges, nested graphs, or ports.
+
+"GraphML is a comprehensive and easy-to-use file format for graphs. It
+consists of a language core to describe the structural properties of a
+graph and a flexible extension mechanism to add application-specific
+data. Its main features include support of
+
+    * directed, undirected, and mixed graphs,
+    * hypergraphs,
+    * hierarchical graphs,
+    * graphical representations,
+    * references to external data,
+    * application-specific attribute data, and
+    * light-weight parsers.
+
+Unlike many other file formats for graphs, GraphML does not use a
+custom syntax. Instead, it is based on XML and hence ideally suited as
+a common denominator for all kinds of services generating, archiving,
+or processing graphs."
+
+http://graphml.graphdrawing.org/
+
+Format
+------
+GraphML is an XML format.  See
+http://graphml.graphdrawing.org/specification.html for the specification and
+http://graphml.graphdrawing.org/primer/graphml-primer.html
+for examples.
+"""
+
+import warnings
+from collections import defaultdict
+
+import networkx as nx
+from networkx.utils import open_file
+
+__all__ = [
+    "write_graphml",
+    "read_graphml",
+    "generate_graphml",
+    "write_graphml_xml",
+    "write_graphml_lxml",
+    "parse_graphml",
+    "GraphMLWriter",
+    "GraphMLReader",
+]
+
+
+@open_file(1, mode="wb")
+def write_graphml_xml(
+    G,
+    path,
+    encoding="utf-8",
+    prettyprint=True,
+    infer_numeric_types=False,
+    named_key_ids=False,
+    edge_id_from_attribute=None,
+):
+    """Write G in GraphML XML format to path
+
+    Parameters
+    ----------
+    G : graph
+       A networkx graph
+    path : file or string
+       File or filename to write.
+       Filenames ending in .gz or .bz2 will be compressed.
+    encoding : string (optional)
+       Encoding for text data.
+    prettyprint : bool (optional)
+       If True use line breaks and indenting in output XML.
+    infer_numeric_types : boolean
+       Determine if numeric types should be generalized.
+       For example, if edges have both int and float 'weight' attributes,
+       we infer in GraphML that both are floats.
+    named_key_ids : bool (optional)
+       If True use attr.name as value for key elements' id attribute.
+    edge_id_from_attribute : dict key (optional)
+        If provided, the graphml edge id is set by looking up the corresponding
+        edge data attribute keyed by this parameter. If `None` or the key does not exist in edge data,
+        the edge id is set by the edge key if `G` is a MultiGraph, else the edge id is left unset.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> nx.write_graphml(G, "test.graphml")
+
+    Notes
+    -----
+    This implementation does not support mixed graphs (directed
+    and unidirected edges together) hyperedges, nested graphs, or ports.
+    """
+    writer = GraphMLWriter(
+        encoding=encoding,
+        prettyprint=prettyprint,
+        infer_numeric_types=infer_numeric_types,
+        named_key_ids=named_key_ids,
+        edge_id_from_attribute=edge_id_from_attribute,
+    )
+    writer.add_graph_element(G)
+    writer.dump(path)
+
+
+@open_file(1, mode="wb")
+def write_graphml_lxml(
+    G,
+    path,
+    encoding="utf-8",
+    prettyprint=True,
+    infer_numeric_types=False,
+    named_key_ids=False,
+    edge_id_from_attribute=None,
+):
+    """Write G in GraphML XML format to path
+
+    This function uses the LXML framework and should be faster than
+    the version using the xml library.
+
+    Parameters
+    ----------
+    G : graph
+       A networkx graph
+    path : file or string
+       File or filename to write.
+       Filenames ending in .gz or .bz2 will be compressed.
+    encoding : string (optional)
+       Encoding for text data.
+    prettyprint : bool (optional)
+       If True use line breaks and indenting in output XML.
+    infer_numeric_types : boolean
+       Determine if numeric types should be generalized.
+       For example, if edges have both int and float 'weight' attributes,
+       we infer in GraphML that both are floats.
+    named_key_ids : bool (optional)
+       If True use attr.name as value for key elements' id attribute.
+    edge_id_from_attribute : dict key (optional)
+        If provided, the graphml edge id is set by looking up the corresponding
+        edge data attribute keyed by this parameter. If `None` or the key does not exist in edge data,
+        the edge id is set by the edge key if `G` is a MultiGraph, else the edge id is left unset.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> nx.write_graphml_lxml(G, "fourpath.graphml")
+
+    Notes
+    -----
+    This implementation does not support mixed graphs (directed
+    and unidirected edges together) hyperedges, nested graphs, or ports.
+    """
+    try:
+        import lxml.etree as lxmletree
+    except ImportError:
+        return write_graphml_xml(
+            G,
+            path,
+            encoding,
+            prettyprint,
+            infer_numeric_types,
+            named_key_ids,
+            edge_id_from_attribute,
+        )
+
+    writer = GraphMLWriterLxml(
+        path,
+        graph=G,
+        encoding=encoding,
+        prettyprint=prettyprint,
+        infer_numeric_types=infer_numeric_types,
+        named_key_ids=named_key_ids,
+        edge_id_from_attribute=edge_id_from_attribute,
+    )
+    writer.dump()
+
+
+def generate_graphml(
+    G,
+    encoding="utf-8",
+    prettyprint=True,
+    named_key_ids=False,
+    edge_id_from_attribute=None,
+):
+    """Generate GraphML lines for G
+
+    Parameters
+    ----------
+    G : graph
+       A networkx graph
+    encoding : string (optional)
+       Encoding for text data.
+    prettyprint : bool (optional)
+       If True use line breaks and indenting in output XML.
+    named_key_ids : bool (optional)
+       If True use attr.name as value for key elements' id attribute.
+    edge_id_from_attribute : dict key (optional)
+        If provided, the graphml edge id is set by looking up the corresponding
+        edge data attribute keyed by this parameter. If `None` or the key does not exist in edge data,
+        the edge id is set by the edge key if `G` is a MultiGraph, else the edge id is left unset.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> linefeed = chr(10)  # linefeed = \n
+    >>> s = linefeed.join(nx.generate_graphml(G))
+    >>> for line in nx.generate_graphml(G):  # doctest: +SKIP
+    ...     print(line)
+
+    Notes
+    -----
+    This implementation does not support mixed graphs (directed and unidirected
+    edges together) hyperedges, nested graphs, or ports.
+    """
+    writer = GraphMLWriter(
+        encoding=encoding,
+        prettyprint=prettyprint,
+        named_key_ids=named_key_ids,
+        edge_id_from_attribute=edge_id_from_attribute,
+    )
+    writer.add_graph_element(G)
+    yield from str(writer).splitlines()
+
+
+@open_file(0, mode="rb")
+@nx._dispatchable(graphs=None, returns_graph=True)
+def read_graphml(path, node_type=str, edge_key_type=int, force_multigraph=False):
+    """Read graph in GraphML format from path.
+
+    Parameters
+    ----------
+    path : file or string
+       Filename or file handle to read.
+       Filenames ending in .gz or .bz2 will be decompressed.
+
+    node_type: Python type (default: str)
+       Convert node ids to this type
+
+    edge_key_type: Python type (default: int)
+       Convert graphml edge ids to this type. Multigraphs use id as edge key.
+       Non-multigraphs add to edge attribute dict with name "id".
+
+    force_multigraph : bool (default: False)
+       If True, return a multigraph with edge keys. If False (the default)
+       return a multigraph when multiedges are in the graph.
+
+    Returns
+    -------
+    graph: NetworkX graph
+        If parallel edges are present or `force_multigraph=True` then
+        a MultiGraph or MultiDiGraph is returned. Otherwise a Graph/DiGraph.
+        The returned graph is directed if the file indicates it should be.
+
+    Notes
+    -----
+    Default node and edge attributes are not propagated to each node and edge.
+    They can be obtained from `G.graph` and applied to node and edge attributes
+    if desired using something like this:
+
+    >>> default_color = G.graph["node_default"]["color"]  # doctest: +SKIP
+    >>> for node, data in G.nodes(data=True):  # doctest: +SKIP
+    ...     if "color" not in data:
+    ...         data["color"] = default_color
+    >>> default_color = G.graph["edge_default"]["color"]  # doctest: +SKIP
+    >>> for u, v, data in G.edges(data=True):  # doctest: +SKIP
+    ...     if "color" not in data:
+    ...         data["color"] = default_color
+
+    This implementation does not support mixed graphs (directed and unidirected
+    edges together), hypergraphs, nested graphs, or ports.
+
+    For multigraphs the GraphML edge "id" will be used as the edge
+    key.  If not specified then they "key" attribute will be used.  If
+    there is no "key" attribute a default NetworkX multigraph edge key
+    will be provided.
+
+    Files with the yEd "yfiles" extension can be read. The type of the node's
+    shape is preserved in the `shape_type` node attribute.
+
+    yEd compressed files ("file.graphmlz" extension) can be read by renaming
+    the file to "file.graphml.gz".
+
+    """
+    reader = GraphMLReader(node_type, edge_key_type, force_multigraph)
+    # need to check for multiple graphs
+    glist = list(reader(path=path))
+    if len(glist) == 0:
+        # If no graph comes back, try looking for an incomplete header
+        header = b''
+        path.seek(0)
+        old_bytes = path.read()
+        new_bytes = old_bytes.replace(b"", header)
+        glist = list(reader(string=new_bytes))
+        if len(glist) == 0:
+            raise nx.NetworkXError("file not successfully read as graphml")
+    return glist[0]
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def parse_graphml(
+    graphml_string, node_type=str, edge_key_type=int, force_multigraph=False
+):
+    """Read graph in GraphML format from string.
+
+    Parameters
+    ----------
+    graphml_string : string
+       String containing graphml information
+       (e.g., contents of a graphml file).
+
+    node_type: Python type (default: str)
+       Convert node ids to this type
+
+    edge_key_type: Python type (default: int)
+       Convert graphml edge ids to this type. Multigraphs use id as edge key.
+       Non-multigraphs add to edge attribute dict with name "id".
+
+    force_multigraph : bool (default: False)
+       If True, return a multigraph with edge keys. If False (the default)
+       return a multigraph when multiedges are in the graph.
+
+
+    Returns
+    -------
+    graph: NetworkX graph
+        If no parallel edges are found a Graph or DiGraph is returned.
+        Otherwise a MultiGraph or MultiDiGraph is returned.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> linefeed = chr(10)  # linefeed = \n
+    >>> s = linefeed.join(nx.generate_graphml(G))
+    >>> H = nx.parse_graphml(s)
+
+    Notes
+    -----
+    Default node and edge attributes are not propagated to each node and edge.
+    They can be obtained from `G.graph` and applied to node and edge attributes
+    if desired using something like this:
+
+    >>> default_color = G.graph["node_default"]["color"]  # doctest: +SKIP
+    >>> for node, data in G.nodes(data=True):  # doctest: +SKIP
+    ...     if "color" not in data:
+    ...         data["color"] = default_color
+    >>> default_color = G.graph["edge_default"]["color"]  # doctest: +SKIP
+    >>> for u, v, data in G.edges(data=True):  # doctest: +SKIP
+    ...     if "color" not in data:
+    ...         data["color"] = default_color
+
+    This implementation does not support mixed graphs (directed and unidirected
+    edges together), hypergraphs, nested graphs, or ports.
+
+    For multigraphs the GraphML edge "id" will be used as the edge
+    key.  If not specified then they "key" attribute will be used.  If
+    there is no "key" attribute a default NetworkX multigraph edge key
+    will be provided.
+
+    """
+    reader = GraphMLReader(node_type, edge_key_type, force_multigraph)
+    # need to check for multiple graphs
+    glist = list(reader(string=graphml_string))
+    if len(glist) == 0:
+        # If no graph comes back, try looking for an incomplete header
+        header = ''
+        new_string = graphml_string.replace("", header)
+        glist = list(reader(string=new_string))
+        if len(glist) == 0:
+            raise nx.NetworkXError("file not successfully read as graphml")
+    return glist[0]
+
+
+class GraphML:
+    NS_GRAPHML = "http://graphml.graphdrawing.org/xmlns"
+    NS_XSI = "http://www.w3.org/2001/XMLSchema-instance"
+    # xmlns:y="http://www.yworks.com/xml/graphml"
+    NS_Y = "http://www.yworks.com/xml/graphml"
+    SCHEMALOCATION = " ".join(
+        [
+            "http://graphml.graphdrawing.org/xmlns",
+            "http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd",
+        ]
+    )
+
+    def construct_types(self):
+        types = [
+            (int, "integer"),  # for Gephi GraphML bug
+            (str, "yfiles"),
+            (str, "string"),
+            (int, "int"),
+            (int, "long"),
+            (float, "float"),
+            (float, "double"),
+            (bool, "boolean"),
+        ]
+
+        # These additions to types allow writing numpy types
+        try:
+            import numpy as np
+        except:
+            pass
+        else:
+            # prepend so that python types are created upon read (last entry wins)
+            types = [
+                (np.float64, "float"),
+                (np.float32, "float"),
+                (np.float16, "float"),
+                (np.int_, "int"),
+                (np.int8, "int"),
+                (np.int16, "int"),
+                (np.int32, "int"),
+                (np.int64, "int"),
+                (np.uint8, "int"),
+                (np.uint16, "int"),
+                (np.uint32, "int"),
+                (np.uint64, "int"),
+                (np.int_, "int"),
+                (np.intc, "int"),
+                (np.intp, "int"),
+            ] + types
+
+        self.xml_type = dict(types)
+        self.python_type = dict(reversed(a) for a in types)
+
+    # This page says that data types in GraphML follow Java(TM).
+    #  http://graphml.graphdrawing.org/primer/graphml-primer.html#AttributesDefinition
+    # true and false are the only boolean literals:
+    #  http://en.wikibooks.org/wiki/Java_Programming/Literals#Boolean_Literals
+    convert_bool = {
+        # We use data.lower() in actual use.
+        "true": True,
+        "false": False,
+        # Include integer strings for convenience.
+        "0": False,
+        0: False,
+        "1": True,
+        1: True,
+    }
+
+    def get_xml_type(self, key):
+        """Wrapper around the xml_type dict that raises a more informative
+        exception message when a user attempts to use data of a type not
+        supported by GraphML."""
+        try:
+            return self.xml_type[key]
+        except KeyError as err:
+            raise TypeError(
+                f"GraphML does not support type {key} as data values."
+            ) from err
+
+
+class GraphMLWriter(GraphML):
+    def __init__(
+        self,
+        graph=None,
+        encoding="utf-8",
+        prettyprint=True,
+        infer_numeric_types=False,
+        named_key_ids=False,
+        edge_id_from_attribute=None,
+    ):
+        self.construct_types()
+        from xml.etree.ElementTree import Element
+
+        self.myElement = Element
+
+        self.infer_numeric_types = infer_numeric_types
+        self.prettyprint = prettyprint
+        self.named_key_ids = named_key_ids
+        self.edge_id_from_attribute = edge_id_from_attribute
+        self.encoding = encoding
+        self.xml = self.myElement(
+            "graphml",
+            {
+                "xmlns": self.NS_GRAPHML,
+                "xmlns:xsi": self.NS_XSI,
+                "xsi:schemaLocation": self.SCHEMALOCATION,
+            },
+        )
+        self.keys = {}
+        self.attributes = defaultdict(list)
+        self.attribute_types = defaultdict(set)
+
+        if graph is not None:
+            self.add_graph_element(graph)
+
+    def __str__(self):
+        from xml.etree.ElementTree import tostring
+
+        if self.prettyprint:
+            self.indent(self.xml)
+        s = tostring(self.xml).decode(self.encoding)
+        return s
+
+    def attr_type(self, name, scope, value):
+        """Infer the attribute type of data named name. Currently this only
+        supports inference of numeric types.
+
+        If self.infer_numeric_types is false, type is used. Otherwise, pick the
+        most general of types found across all values with name and scope. This
+        means edges with data named 'weight' are treated separately from nodes
+        with data named 'weight'.
+        """
+        if self.infer_numeric_types:
+            types = self.attribute_types[(name, scope)]
+
+            if len(types) > 1:
+                types = {self.get_xml_type(t) for t in types}
+                if "string" in types:
+                    return str
+                elif "float" in types or "double" in types:
+                    return float
+                else:
+                    return int
+            else:
+                return list(types)[0]
+        else:
+            return type(value)
+
+    def get_key(self, name, attr_type, scope, default):
+        keys_key = (name, attr_type, scope)
+        try:
+            return self.keys[keys_key]
+        except KeyError:
+            if self.named_key_ids:
+                new_id = name
+            else:
+                new_id = f"d{len(list(self.keys))}"
+
+            self.keys[keys_key] = new_id
+            key_kwargs = {
+                "id": new_id,
+                "for": scope,
+                "attr.name": name,
+                "attr.type": attr_type,
+            }
+            key_element = self.myElement("key", **key_kwargs)
+            # add subelement for data default value if present
+            if default is not None:
+                default_element = self.myElement("default")
+                default_element.text = str(default)
+                key_element.append(default_element)
+            self.xml.insert(0, key_element)
+        return new_id
+
+    def add_data(self, name, element_type, value, scope="all", default=None):
+        """
+        Make a data element for an edge or a node. Keep a log of the
+        type in the keys table.
+        """
+        if element_type not in self.xml_type:
+            raise nx.NetworkXError(
+                f"GraphML writer does not support {element_type} as data values."
+            )
+        keyid = self.get_key(name, self.get_xml_type(element_type), scope, default)
+        data_element = self.myElement("data", key=keyid)
+        data_element.text = str(value)
+        return data_element
+
+    def add_attributes(self, scope, xml_obj, data, default):
+        """Appends attribute data to edges or nodes, and stores type information
+        to be added later. See add_graph_element.
+        """
+        for k, v in data.items():
+            self.attribute_types[(str(k), scope)].add(type(v))
+            self.attributes[xml_obj].append([k, v, scope, default.get(k)])
+
+    def add_nodes(self, G, graph_element):
+        default = G.graph.get("node_default", {})
+        for node, data in G.nodes(data=True):
+            node_element = self.myElement("node", id=str(node))
+            self.add_attributes("node", node_element, data, default)
+            graph_element.append(node_element)
+
+    def add_edges(self, G, graph_element):
+        if G.is_multigraph():
+            for u, v, key, data in G.edges(data=True, keys=True):
+                edge_element = self.myElement(
+                    "edge",
+                    source=str(u),
+                    target=str(v),
+                    id=str(data.get(self.edge_id_from_attribute))
+                    if self.edge_id_from_attribute
+                    and self.edge_id_from_attribute in data
+                    else str(key),
+                )
+                default = G.graph.get("edge_default", {})
+                self.add_attributes("edge", edge_element, data, default)
+                graph_element.append(edge_element)
+        else:
+            for u, v, data in G.edges(data=True):
+                if self.edge_id_from_attribute and self.edge_id_from_attribute in data:
+                    # select attribute to be edge id
+                    edge_element = self.myElement(
+                        "edge",
+                        source=str(u),
+                        target=str(v),
+                        id=str(data.get(self.edge_id_from_attribute)),
+                    )
+                else:
+                    # default: no edge id
+                    edge_element = self.myElement("edge", source=str(u), target=str(v))
+                default = G.graph.get("edge_default", {})
+                self.add_attributes("edge", edge_element, data, default)
+                graph_element.append(edge_element)
+
+    def add_graph_element(self, G):
+        """
+        Serialize graph G in GraphML to the stream.
+        """
+        if G.is_directed():
+            default_edge_type = "directed"
+        else:
+            default_edge_type = "undirected"
+
+        graphid = G.graph.pop("id", None)
+        if graphid is None:
+            graph_element = self.myElement("graph", edgedefault=default_edge_type)
+        else:
+            graph_element = self.myElement(
+                "graph", edgedefault=default_edge_type, id=graphid
+            )
+        default = {}
+        data = {
+            k: v
+            for (k, v) in G.graph.items()
+            if k not in ["node_default", "edge_default"]
+        }
+        self.add_attributes("graph", graph_element, data, default)
+        self.add_nodes(G, graph_element)
+        self.add_edges(G, graph_element)
+
+        # self.attributes contains a mapping from XML Objects to a list of
+        # data that needs to be added to them.
+        # We postpone processing in order to do type inference/generalization.
+        # See self.attr_type
+        for xml_obj, data in self.attributes.items():
+            for k, v, scope, default in data:
+                xml_obj.append(
+                    self.add_data(
+                        str(k), self.attr_type(k, scope, v), str(v), scope, default
+                    )
+                )
+        self.xml.append(graph_element)
+
+    def add_graphs(self, graph_list):
+        """Add many graphs to this GraphML document."""
+        for G in graph_list:
+            self.add_graph_element(G)
+
+    def dump(self, stream):
+        from xml.etree.ElementTree import ElementTree
+
+        if self.prettyprint:
+            self.indent(self.xml)
+        document = ElementTree(self.xml)
+        document.write(stream, encoding=self.encoding, xml_declaration=True)
+
+    def indent(self, elem, level=0):
+        # in-place prettyprint formatter
+        i = "\n" + level * "  "
+        if len(elem):
+            if not elem.text or not elem.text.strip():
+                elem.text = i + "  "
+            if not elem.tail or not elem.tail.strip():
+                elem.tail = i
+            for elem in elem:
+                self.indent(elem, level + 1)
+            if not elem.tail or not elem.tail.strip():
+                elem.tail = i
+        else:
+            if level and (not elem.tail or not elem.tail.strip()):
+                elem.tail = i
+
+
+class IncrementalElement:
+    """Wrapper for _IncrementalWriter providing an Element like interface.
+
+    This wrapper does not intend to be a complete implementation but rather to
+    deal with those calls used in GraphMLWriter.
+    """
+
+    def __init__(self, xml, prettyprint):
+        self.xml = xml
+        self.prettyprint = prettyprint
+
+    def append(self, element):
+        self.xml.write(element, pretty_print=self.prettyprint)
+
+
+class GraphMLWriterLxml(GraphMLWriter):
+    def __init__(
+        self,
+        path,
+        graph=None,
+        encoding="utf-8",
+        prettyprint=True,
+        infer_numeric_types=False,
+        named_key_ids=False,
+        edge_id_from_attribute=None,
+    ):
+        self.construct_types()
+        import lxml.etree as lxmletree
+
+        self.myElement = lxmletree.Element
+
+        self._encoding = encoding
+        self._prettyprint = prettyprint
+        self.named_key_ids = named_key_ids
+        self.edge_id_from_attribute = edge_id_from_attribute
+        self.infer_numeric_types = infer_numeric_types
+
+        self._xml_base = lxmletree.xmlfile(path, encoding=encoding)
+        self._xml = self._xml_base.__enter__()
+        self._xml.write_declaration()
+
+        # We need to have a xml variable that support insertion. This call is
+        # used for adding the keys to the document.
+        # We will store those keys in a plain list, and then after the graph
+        # element is closed we will add them to the main graphml element.
+        self.xml = []
+        self._keys = self.xml
+        self._graphml = self._xml.element(
+            "graphml",
+            {
+                "xmlns": self.NS_GRAPHML,
+                "xmlns:xsi": self.NS_XSI,
+                "xsi:schemaLocation": self.SCHEMALOCATION,
+            },
+        )
+        self._graphml.__enter__()
+        self.keys = {}
+        self.attribute_types = defaultdict(set)
+
+        if graph is not None:
+            self.add_graph_element(graph)
+
+    def add_graph_element(self, G):
+        """
+        Serialize graph G in GraphML to the stream.
+        """
+        if G.is_directed():
+            default_edge_type = "directed"
+        else:
+            default_edge_type = "undirected"
+
+        graphid = G.graph.pop("id", None)
+        if graphid is None:
+            graph_element = self._xml.element("graph", edgedefault=default_edge_type)
+        else:
+            graph_element = self._xml.element(
+                "graph", edgedefault=default_edge_type, id=graphid
+            )
+
+        # gather attributes types for the whole graph
+        # to find the most general numeric format needed.
+        # Then pass through attributes to create key_id for each.
+        graphdata = {
+            k: v
+            for k, v in G.graph.items()
+            if k not in ("node_default", "edge_default")
+        }
+        node_default = G.graph.get("node_default", {})
+        edge_default = G.graph.get("edge_default", {})
+        # Graph attributes
+        for k, v in graphdata.items():
+            self.attribute_types[(str(k), "graph")].add(type(v))
+        for k, v in graphdata.items():
+            element_type = self.get_xml_type(self.attr_type(k, "graph", v))
+            self.get_key(str(k), element_type, "graph", None)
+        # Nodes and data
+        for node, d in G.nodes(data=True):
+            for k, v in d.items():
+                self.attribute_types[(str(k), "node")].add(type(v))
+        for node, d in G.nodes(data=True):
+            for k, v in d.items():
+                T = self.get_xml_type(self.attr_type(k, "node", v))
+                self.get_key(str(k), T, "node", node_default.get(k))
+        # Edges and data
+        if G.is_multigraph():
+            for u, v, ekey, d in G.edges(keys=True, data=True):
+                for k, v in d.items():
+                    self.attribute_types[(str(k), "edge")].add(type(v))
+            for u, v, ekey, d in G.edges(keys=True, data=True):
+                for k, v in d.items():
+                    T = self.get_xml_type(self.attr_type(k, "edge", v))
+                    self.get_key(str(k), T, "edge", edge_default.get(k))
+        else:
+            for u, v, d in G.edges(data=True):
+                for k, v in d.items():
+                    self.attribute_types[(str(k), "edge")].add(type(v))
+            for u, v, d in G.edges(data=True):
+                for k, v in d.items():
+                    T = self.get_xml_type(self.attr_type(k, "edge", v))
+                    self.get_key(str(k), T, "edge", edge_default.get(k))
+
+        # Now add attribute keys to the xml file
+        for key in self.xml:
+            self._xml.write(key, pretty_print=self._prettyprint)
+
+        # The incremental_writer writes each node/edge as it is created
+        incremental_writer = IncrementalElement(self._xml, self._prettyprint)
+        with graph_element:
+            self.add_attributes("graph", incremental_writer, graphdata, {})
+            self.add_nodes(G, incremental_writer)  # adds attributes too
+            self.add_edges(G, incremental_writer)  # adds attributes too
+
+    def add_attributes(self, scope, xml_obj, data, default):
+        """Appends attribute data."""
+        for k, v in data.items():
+            data_element = self.add_data(
+                str(k), self.attr_type(str(k), scope, v), str(v), scope, default.get(k)
+            )
+            xml_obj.append(data_element)
+
+    def __str__(self):
+        return object.__str__(self)
+
+    def dump(self, stream=None):
+        self._graphml.__exit__(None, None, None)
+        self._xml_base.__exit__(None, None, None)
+
+
+# default is lxml is present.
+write_graphml = write_graphml_lxml
+
+
+class GraphMLReader(GraphML):
+    """Read a GraphML document.  Produces NetworkX graph objects."""
+
+    def __init__(self, node_type=str, edge_key_type=int, force_multigraph=False):
+        self.construct_types()
+        self.node_type = node_type
+        self.edge_key_type = edge_key_type
+        self.multigraph = force_multigraph  # If False, test for multiedges
+        self.edge_ids = {}  # dict mapping (u,v) tuples to edge id attributes
+
+    def __call__(self, path=None, string=None):
+        from xml.etree.ElementTree import ElementTree, fromstring
+
+        if path is not None:
+            self.xml = ElementTree(file=path)
+        elif string is not None:
+            self.xml = fromstring(string)
+        else:
+            raise ValueError("Must specify either 'path' or 'string' as kwarg")
+        (keys, defaults) = self.find_graphml_keys(self.xml)
+        for g in self.xml.findall(f"{{{self.NS_GRAPHML}}}graph"):
+            yield self.make_graph(g, keys, defaults)
+
+    def make_graph(self, graph_xml, graphml_keys, defaults, G=None):
+        # set default graph type
+        edgedefault = graph_xml.get("edgedefault", None)
+        if G is None:
+            if edgedefault == "directed":
+                G = nx.MultiDiGraph()
+            else:
+                G = nx.MultiGraph()
+        # set defaults for graph attributes
+        G.graph["node_default"] = {}
+        G.graph["edge_default"] = {}
+        for key_id, value in defaults.items():
+            key_for = graphml_keys[key_id]["for"]
+            name = graphml_keys[key_id]["name"]
+            python_type = graphml_keys[key_id]["type"]
+            if key_for == "node":
+                G.graph["node_default"].update({name: python_type(value)})
+            if key_for == "edge":
+                G.graph["edge_default"].update({name: python_type(value)})
+        # hyperedges are not supported
+        hyperedge = graph_xml.find(f"{{{self.NS_GRAPHML}}}hyperedge")
+        if hyperedge is not None:
+            raise nx.NetworkXError("GraphML reader doesn't support hyperedges")
+        # add nodes
+        for node_xml in graph_xml.findall(f"{{{self.NS_GRAPHML}}}node"):
+            self.add_node(G, node_xml, graphml_keys, defaults)
+        # add edges
+        for edge_xml in graph_xml.findall(f"{{{self.NS_GRAPHML}}}edge"):
+            self.add_edge(G, edge_xml, graphml_keys)
+        # add graph data
+        data = self.decode_data_elements(graphml_keys, graph_xml)
+        G.graph.update(data)
+
+        # switch to Graph or DiGraph if no parallel edges were found
+        if self.multigraph:
+            return G
+
+        G = nx.DiGraph(G) if G.is_directed() else nx.Graph(G)
+        # add explicit edge "id" from file as attribute in NX graph.
+        nx.set_edge_attributes(G, values=self.edge_ids, name="id")
+        return G
+
+    def add_node(self, G, node_xml, graphml_keys, defaults):
+        """Add a node to the graph."""
+        # warn on finding unsupported ports tag
+        ports = node_xml.find(f"{{{self.NS_GRAPHML}}}port")
+        if ports is not None:
+            warnings.warn("GraphML port tag not supported.")
+        # find the node by id and cast it to the appropriate type
+        node_id = self.node_type(node_xml.get("id"))
+        # get data/attributes for node
+        data = self.decode_data_elements(graphml_keys, node_xml)
+        G.add_node(node_id, **data)
+        # get child nodes
+        if node_xml.attrib.get("yfiles.foldertype") == "group":
+            graph_xml = node_xml.find(f"{{{self.NS_GRAPHML}}}graph")
+            self.make_graph(graph_xml, graphml_keys, defaults, G)
+
+    def add_edge(self, G, edge_element, graphml_keys):
+        """Add an edge to the graph."""
+        # warn on finding unsupported ports tag
+        ports = edge_element.find(f"{{{self.NS_GRAPHML}}}port")
+        if ports is not None:
+            warnings.warn("GraphML port tag not supported.")
+
+        # raise error if we find mixed directed and undirected edges
+        directed = edge_element.get("directed")
+        if G.is_directed() and directed == "false":
+            msg = "directed=false edge found in directed graph."
+            raise nx.NetworkXError(msg)
+        if (not G.is_directed()) and directed == "true":
+            msg = "directed=true edge found in undirected graph."
+            raise nx.NetworkXError(msg)
+
+        source = self.node_type(edge_element.get("source"))
+        target = self.node_type(edge_element.get("target"))
+        data = self.decode_data_elements(graphml_keys, edge_element)
+        # GraphML stores edge ids as an attribute
+        # NetworkX uses them as keys in multigraphs too if no key
+        # attribute is specified
+        edge_id = edge_element.get("id")
+        if edge_id:
+            # self.edge_ids is used by `make_graph` method for non-multigraphs
+            self.edge_ids[source, target] = edge_id
+            try:
+                edge_id = self.edge_key_type(edge_id)
+            except ValueError:  # Could not convert.
+                pass
+        else:
+            edge_id = data.get("key")
+
+        if G.has_edge(source, target):
+            # mark this as a multigraph
+            self.multigraph = True
+
+        # Use add_edges_from to avoid error with add_edge when `'key' in data`
+        # Note there is only one edge here...
+        G.add_edges_from([(source, target, edge_id, data)])
+
+    def decode_data_elements(self, graphml_keys, obj_xml):
+        """Use the key information to decode the data XML if present."""
+        data = {}
+        for data_element in obj_xml.findall(f"{{{self.NS_GRAPHML}}}data"):
+            key = data_element.get("key")
+            try:
+                data_name = graphml_keys[key]["name"]
+                data_type = graphml_keys[key]["type"]
+            except KeyError as err:
+                raise nx.NetworkXError(f"Bad GraphML data: no key {key}") from err
+            text = data_element.text
+            # assume anything with subelements is a yfiles extension
+            if text is not None and len(list(data_element)) == 0:
+                if data_type is bool:
+                    # Ignore cases.
+                    # http://docs.oracle.com/javase/6/docs/api/java/lang/
+                    # Boolean.html#parseBoolean%28java.lang.String%29
+                    data[data_name] = self.convert_bool[text.lower()]
+                else:
+                    data[data_name] = data_type(text)
+            elif len(list(data_element)) > 0:
+                # Assume yfiles as subelements, try to extract node_label
+                node_label = None
+                # set GenericNode's configuration as shape type
+                gn = data_element.find(f"{{{self.NS_Y}}}GenericNode")
+                if gn is not None:
+                    data["shape_type"] = gn.get("configuration")
+                for node_type in ["GenericNode", "ShapeNode", "SVGNode", "ImageNode"]:
+                    pref = f"{{{self.NS_Y}}}{node_type}/{{{self.NS_Y}}}"
+                    geometry = data_element.find(f"{pref}Geometry")
+                    if geometry is not None:
+                        data["x"] = geometry.get("x")
+                        data["y"] = geometry.get("y")
+                    if node_label is None:
+                        node_label = data_element.find(f"{pref}NodeLabel")
+                    shape = data_element.find(f"{pref}Shape")
+                    if shape is not None:
+                        data["shape_type"] = shape.get("type")
+                if node_label is not None:
+                    data["label"] = node_label.text
+
+                # check all the different types of edges available in yEd.
+                for edge_type in [
+                    "PolyLineEdge",
+                    "SplineEdge",
+                    "QuadCurveEdge",
+                    "BezierEdge",
+                    "ArcEdge",
+                ]:
+                    pref = f"{{{self.NS_Y}}}{edge_type}/{{{self.NS_Y}}}"
+                    edge_label = data_element.find(f"{pref}EdgeLabel")
+                    if edge_label is not None:
+                        break
+                if edge_label is not None:
+                    data["label"] = edge_label.text
+            elif text is None:
+                data[data_name] = ""
+        return data
+
+    def find_graphml_keys(self, graph_element):
+        """Extracts all the keys and key defaults from the xml."""
+        graphml_keys = {}
+        graphml_key_defaults = {}
+        for k in graph_element.findall(f"{{{self.NS_GRAPHML}}}key"):
+            attr_id = k.get("id")
+            attr_type = k.get("attr.type")
+            attr_name = k.get("attr.name")
+            yfiles_type = k.get("yfiles.type")
+            if yfiles_type is not None:
+                attr_name = yfiles_type
+                attr_type = "yfiles"
+            if attr_type is None:
+                attr_type = "string"
+                warnings.warn(f"No key type for id {attr_id}. Using string")
+            if attr_name is None:
+                raise nx.NetworkXError(f"Unknown key for id {attr_id}.")
+            graphml_keys[attr_id] = {
+                "name": attr_name,
+                "type": self.python_type[attr_type],
+                "for": k.get("for"),
+            }
+            # check for "default" sub-element of key element
+            default = k.find(f"{{{self.NS_GRAPHML}}}default")
+            if default is not None:
+                # Handle default values identically to data element values
+                python_type = graphml_keys[attr_id]["type"]
+                if python_type is bool:
+                    graphml_key_defaults[attr_id] = self.convert_bool[
+                        default.text.lower()
+                    ]
+                else:
+                    graphml_key_defaults[attr_id] = python_type(default.text)
+        return graphml_keys, graphml_key_defaults
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/leda.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/leda.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d88a67d39d7ff27bf4af36895c52c9546cca329
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/leda.py
@@ -0,0 +1,108 @@
+"""
+Read graphs in LEDA format.
+
+LEDA is a C++ class library for efficient data types and algorithms.
+
+Format
+------
+See http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html
+
+"""
+# Original author: D. Eppstein, UC Irvine, August 12, 2003.
+# The original code at http://www.ics.uci.edu/~eppstein/PADS/ is public domain.
+
+__all__ = ["read_leda", "parse_leda"]
+
+import networkx as nx
+from networkx.exception import NetworkXError
+from networkx.utils import open_file
+
+
+@open_file(0, mode="rb")
+@nx._dispatchable(graphs=None, returns_graph=True)
+def read_leda(path, encoding="UTF-8"):
+    """Read graph in LEDA format from path.
+
+    Parameters
+    ----------
+    path : file or string
+       Filename or file handle to read.
+       Filenames ending in .gz or .bz2 will be decompressed.
+
+    Returns
+    -------
+    G : NetworkX graph
+
+    Examples
+    --------
+    >>> G = nx.read_leda("file.leda")  # doctest: +SKIP
+
+    References
+    ----------
+    .. [1] http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html
+    """
+    lines = (line.decode(encoding) for line in path)
+    G = parse_leda(lines)
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def parse_leda(lines):
+    """Read graph in LEDA format from string or iterable.
+
+    Parameters
+    ----------
+    lines : string or iterable
+       Data in LEDA format.
+
+    Returns
+    -------
+    G : NetworkX graph
+
+    Examples
+    --------
+    >>> G = nx.parse_leda(string)  # doctest: +SKIP
+
+    References
+    ----------
+    .. [1] http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html
+    """
+    if isinstance(lines, str):
+        lines = iter(lines.split("\n"))
+    lines = iter(
+        [
+            line.rstrip("\n")
+            for line in lines
+            if not (line.startswith(("#", "\n")) or line == "")
+        ]
+    )
+    for i in range(3):
+        next(lines)
+    # Graph
+    du = int(next(lines))  # -1=directed, -2=undirected
+    if du == -1:
+        G = nx.DiGraph()
+    else:
+        G = nx.Graph()
+
+    # Nodes
+    n = int(next(lines))  # number of nodes
+    node = {}
+    for i in range(1, n + 1):  # LEDA counts from 1 to n
+        symbol = next(lines).rstrip().strip("|{}|  ")
+        if symbol == "":
+            symbol = str(i)  # use int if no label - could be trouble
+        node[i] = symbol
+
+    G.add_nodes_from([s for i, s in node.items()])
+
+    # Edges
+    m = int(next(lines))  # number of edges
+    for i in range(m):
+        try:
+            s, t, reversal, label = next(lines).split()
+        except BaseException as err:
+            raise NetworkXError(f"Too few fields in LEDA.GRAPH edge {i + 1}") from err
+        # BEWARE: no handling of reversal edges
+        G.add_edge(node[int(s)], node[int(t)], label=label[2:-2])
+    return G
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/multiline_adjlist.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/multiline_adjlist.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5b0b1c153b2f55f22f0fb0e8db9df8bdc0da18d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/multiline_adjlist.py
@@ -0,0 +1,393 @@
+"""
+*************************
+Multi-line Adjacency List
+*************************
+Read and write NetworkX graphs as multi-line adjacency lists.
+
+The multi-line adjacency list format is useful for graphs with
+nodes that can be meaningfully represented as strings.  With this format
+simple edge data can be stored but node or graph data is not.
+
+Format
+------
+The first label in a line is the source node label followed by the node degree
+d.  The next d lines are target node labels and optional edge data.
+That pattern repeats for all nodes in the graph.
+
+The graph with edges a-b, a-c, d-e can be represented as the following
+adjacency list (anything following the # in a line is a comment)::
+
+     # example.multiline-adjlist
+     a 2
+     b
+     c
+     d 1
+     e
+"""
+
+__all__ = [
+    "generate_multiline_adjlist",
+    "write_multiline_adjlist",
+    "parse_multiline_adjlist",
+    "read_multiline_adjlist",
+]
+
+import networkx as nx
+from networkx.utils import open_file
+
+
+def generate_multiline_adjlist(G, delimiter=" "):
+    """Generate a single line of the graph G in multiline adjacency list format.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    delimiter : string, optional
+       Separator for node labels
+
+    Returns
+    -------
+    lines : string
+        Lines of data in multiline adjlist format.
+
+    Examples
+    --------
+    >>> G = nx.lollipop_graph(4, 3)
+    >>> for line in nx.generate_multiline_adjlist(G):
+    ...     print(line)
+    0 3
+    1 {}
+    2 {}
+    3 {}
+    1 2
+    2 {}
+    3 {}
+    2 1
+    3 {}
+    3 1
+    4 {}
+    4 1
+    5 {}
+    5 1
+    6 {}
+    6 0
+
+    See Also
+    --------
+    write_multiline_adjlist, read_multiline_adjlist
+    """
+    if G.is_directed():
+        if G.is_multigraph():
+            for s, nbrs in G.adjacency():
+                nbr_edges = [
+                    (u, data)
+                    for u, datadict in nbrs.items()
+                    for key, data in datadict.items()
+                ]
+                deg = len(nbr_edges)
+                yield str(s) + delimiter + str(deg)
+                for u, d in nbr_edges:
+                    if d is None:
+                        yield str(u)
+                    else:
+                        yield str(u) + delimiter + str(d)
+        else:  # directed single edges
+            for s, nbrs in G.adjacency():
+                deg = len(nbrs)
+                yield str(s) + delimiter + str(deg)
+                for u, d in nbrs.items():
+                    if d is None:
+                        yield str(u)
+                    else:
+                        yield str(u) + delimiter + str(d)
+    else:  # undirected
+        if G.is_multigraph():
+            seen = set()  # helper dict used to avoid duplicate edges
+            for s, nbrs in G.adjacency():
+                nbr_edges = [
+                    (u, data)
+                    for u, datadict in nbrs.items()
+                    if u not in seen
+                    for key, data in datadict.items()
+                ]
+                deg = len(nbr_edges)
+                yield str(s) + delimiter + str(deg)
+                for u, d in nbr_edges:
+                    if d is None:
+                        yield str(u)
+                    else:
+                        yield str(u) + delimiter + str(d)
+                seen.add(s)
+        else:  # undirected single edges
+            seen = set()  # helper dict used to avoid duplicate edges
+            for s, nbrs in G.adjacency():
+                nbr_edges = [(u, d) for u, d in nbrs.items() if u not in seen]
+                deg = len(nbr_edges)
+                yield str(s) + delimiter + str(deg)
+                for u, d in nbr_edges:
+                    if d is None:
+                        yield str(u)
+                    else:
+                        yield str(u) + delimiter + str(d)
+                seen.add(s)
+
+
+@open_file(1, mode="wb")
+def write_multiline_adjlist(G, path, delimiter=" ", comments="#", encoding="utf-8"):
+    """Write the graph G in multiline adjacency list format to path
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    path : string or file
+       Filename or file handle to write to.
+       Filenames ending in .gz or .bz2 will be compressed.
+
+    comments : string, optional
+       Marker for comment lines
+
+    delimiter : string, optional
+       Separator for node labels
+
+    encoding : string, optional
+       Text encoding.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> nx.write_multiline_adjlist(G, "test.multi_adjlist")
+
+    The path can be a file handle or a string with the name of the file. If a
+    file handle is provided, it has to be opened in 'wb' mode.
+
+    >>> fh = open("test.multi_adjlist2", "wb")
+    >>> nx.write_multiline_adjlist(G, fh)
+
+    Filenames ending in .gz or .bz2 will be compressed.
+
+    >>> nx.write_multiline_adjlist(G, "test.multi_adjlist.gz")
+
+    See Also
+    --------
+    read_multiline_adjlist
+    """
+    import sys
+    import time
+
+    pargs = comments + " ".join(sys.argv)
+    header = (
+        f"{pargs}\n"
+        + comments
+        + f" GMT {time.asctime(time.gmtime())}\n"
+        + comments
+        + f" {G.name}\n"
+    )
+    path.write(header.encode(encoding))
+
+    for multiline in generate_multiline_adjlist(G, delimiter):
+        multiline += "\n"
+        path.write(multiline.encode(encoding))
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def parse_multiline_adjlist(
+    lines, comments="#", delimiter=None, create_using=None, nodetype=None, edgetype=None
+):
+    """Parse lines of a multiline adjacency list representation of a graph.
+
+    Parameters
+    ----------
+    lines : list or iterator of strings
+        Input data in multiline adjlist format
+
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    nodetype : Python type, optional
+       Convert nodes to this type.
+
+    edgetype : Python type, optional
+       Convert edges to this type.
+
+    comments : string, optional
+       Marker for comment lines
+
+    delimiter : string, optional
+       Separator for node labels.  The default is whitespace.
+
+    Returns
+    -------
+    G: NetworkX graph
+        The graph corresponding to the lines in multiline adjacency list format.
+
+    Examples
+    --------
+    >>> lines = [
+    ...     "1 2",
+    ...     "2 {'weight':3, 'name': 'Frodo'}",
+    ...     "3 {}",
+    ...     "2 1",
+    ...     "5 {'weight':6, 'name': 'Saruman'}",
+    ... ]
+    >>> G = nx.parse_multiline_adjlist(iter(lines), nodetype=int)
+    >>> list(G)
+    [1, 2, 3, 5]
+
+    """
+    from ast import literal_eval
+
+    G = nx.empty_graph(0, create_using)
+    for line in lines:
+        p = line.find(comments)
+        if p >= 0:
+            line = line[:p]
+        if not line:
+            continue
+        try:
+            (u, deg) = line.rstrip("\n").split(delimiter)
+            deg = int(deg)
+        except BaseException as err:
+            raise TypeError(f"Failed to read node and degree on line ({line})") from err
+        if nodetype is not None:
+            try:
+                u = nodetype(u)
+            except BaseException as err:
+                raise TypeError(
+                    f"Failed to convert node ({u}) to type {nodetype}"
+                ) from err
+        G.add_node(u)
+        for i in range(deg):
+            while True:
+                try:
+                    line = next(lines)
+                except StopIteration as err:
+                    msg = f"Failed to find neighbor for node ({u})"
+                    raise TypeError(msg) from err
+                p = line.find(comments)
+                if p >= 0:
+                    line = line[:p]
+                if line:
+                    break
+            vlist = line.rstrip("\n").split(delimiter)
+            numb = len(vlist)
+            if numb < 1:
+                continue  # isolated node
+            v = vlist.pop(0)
+            data = "".join(vlist)
+            if nodetype is not None:
+                try:
+                    v = nodetype(v)
+                except BaseException as err:
+                    raise TypeError(
+                        f"Failed to convert node ({v}) to type {nodetype}"
+                    ) from err
+            if edgetype is not None:
+                try:
+                    edgedata = {"weight": edgetype(data)}
+                except BaseException as err:
+                    raise TypeError(
+                        f"Failed to convert edge data ({data}) to type {edgetype}"
+                    ) from err
+            else:
+                try:  # try to evaluate
+                    edgedata = literal_eval(data)
+                except:
+                    edgedata = {}
+            G.add_edge(u, v, **edgedata)
+
+    return G
+
+
+@open_file(0, mode="rb")
+@nx._dispatchable(graphs=None, returns_graph=True)
+def read_multiline_adjlist(
+    path,
+    comments="#",
+    delimiter=None,
+    create_using=None,
+    nodetype=None,
+    edgetype=None,
+    encoding="utf-8",
+):
+    """Read graph in multi-line adjacency list format from path.
+
+    Parameters
+    ----------
+    path : string or file
+       Filename or file handle to read.
+       Filenames ending in .gz or .bz2 will be decompressed.
+
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
+    nodetype : Python type, optional
+       Convert nodes to this type.
+
+    edgetype : Python type, optional
+       Convert edge data to this type.
+
+    comments : string, optional
+       Marker for comment lines
+
+    delimiter : string, optional
+       Separator for node labels.  The default is whitespace.
+
+    Returns
+    -------
+    G: NetworkX graph
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> nx.write_multiline_adjlist(G, "test.multi_adjlistP4")
+    >>> G = nx.read_multiline_adjlist("test.multi_adjlistP4")
+
+    The path can be a file or a string with the name of the file. If a
+    file s provided, it has to be opened in 'rb' mode.
+
+    >>> fh = open("test.multi_adjlistP4", "rb")
+    >>> G = nx.read_multiline_adjlist(fh)
+
+    Filenames ending in .gz or .bz2 will be compressed.
+
+    >>> nx.write_multiline_adjlist(G, "test.multi_adjlistP4.gz")
+    >>> G = nx.read_multiline_adjlist("test.multi_adjlistP4.gz")
+
+    The optional nodetype is a function to convert node strings to nodetype.
+
+    For example
+
+    >>> G = nx.read_multiline_adjlist("test.multi_adjlistP4", nodetype=int)
+
+    will attempt to convert all nodes to integer type.
+
+    The optional edgetype is a function to convert edge data strings to
+    edgetype.
+
+    >>> G = nx.read_multiline_adjlist("test.multi_adjlistP4")
+
+    The optional create_using parameter is a NetworkX graph container.
+    The default is Graph(), an undirected graph.  To read the data as
+    a directed graph use
+
+    >>> G = nx.read_multiline_adjlist("test.multi_adjlistP4", create_using=nx.DiGraph)
+
+    Notes
+    -----
+    This format does not store graph, node, or edge data.
+
+    See Also
+    --------
+    write_multiline_adjlist
+    """
+    lines = (line.decode(encoding) for line in path)
+    return parse_multiline_adjlist(
+        lines,
+        comments=comments,
+        delimiter=delimiter,
+        create_using=create_using,
+        nodetype=nodetype,
+        edgetype=edgetype,
+    )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/p2g.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/p2g.py
new file mode 100644
index 0000000000000000000000000000000000000000..4bde362ea8d511e603ce3b8d95a6206d74091663
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/p2g.py
@@ -0,0 +1,113 @@
+"""
+This module provides the following: read and write of p2g format
+used in metabolic pathway studies.
+
+See:
+
+for a description.
+
+The summary is included here:
+
+A file that describes a uniquely labeled graph (with extension ".gr")
+format looks like the following:
+
+
+name
+3 4
+a
+1 2
+b
+
+c
+0 2
+
+"name" is simply a description of what the graph corresponds to. The
+second line displays the number of nodes and number of edges,
+respectively. This sample graph contains three nodes labeled "a", "b",
+and "c". The rest of the graph contains two lines for each node. The
+first line for a node contains the node label. After the declaration
+of the node label, the out-edges of that node in the graph are
+provided. For instance, "a" is linked to nodes 1 and 2, which are
+labeled "b" and "c", while the node labeled "b" has no outgoing
+edges. Observe that node labeled "c" has an outgoing edge to
+itself. Indeed, self-loops are allowed. Node index starts from 0.
+
+"""
+
+import networkx as nx
+from networkx.utils import open_file
+
+
+@open_file(1, mode="w")
+def write_p2g(G, path, encoding="utf-8"):
+    """Write NetworkX graph in p2g format.
+
+    Notes
+    -----
+    This format is meant to be used with directed graphs with
+    possible self loops.
+    """
+    path.write((f"{G.name}\n").encode(encoding))
+    path.write((f"{G.order()} {G.size()}\n").encode(encoding))
+    nodes = list(G)
+    # make dictionary mapping nodes to integers
+    nodenumber = dict(zip(nodes, range(len(nodes))))
+    for n in nodes:
+        path.write((f"{n}\n").encode(encoding))
+        for nbr in G.neighbors(n):
+            path.write((f"{nodenumber[nbr]} ").encode(encoding))
+        path.write("\n".encode(encoding))
+
+
+@open_file(0, mode="r")
+@nx._dispatchable(graphs=None, returns_graph=True)
+def read_p2g(path, encoding="utf-8"):
+    """Read graph in p2g format from path.
+
+    Parameters
+    ----------
+    path : string or file
+       Filename or file handle to read.
+       Filenames ending in .gz or .bz2 will be decompressed.
+
+    Returns
+    -------
+    MultiDiGraph
+
+    Notes
+    -----
+    If you want a DiGraph (with no self loops allowed and no edge data)
+    use D=nx.DiGraph(read_p2g(path))
+    """
+    lines = (line.decode(encoding) for line in path)
+    G = parse_p2g(lines)
+    return G
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def parse_p2g(lines):
+    """Parse p2g format graph from string or iterable.
+
+    Returns
+    -------
+    MultiDiGraph
+    """
+    description = next(lines).strip()
+    # are multiedges (parallel edges) allowed?
+    G = nx.MultiDiGraph(name=description, selfloops=True)
+    nnodes, nedges = map(int, next(lines).split())
+    nodelabel = {}
+    nbrs = {}
+    # loop over the nodes keeping track of node labels and out neighbors
+    # defer adding edges until all node labels are known
+    for i in range(nnodes):
+        n = next(lines).strip()
+        nodelabel[i] = n
+        G.add_node(n)
+        nbrs[n] = map(int, next(lines).split())
+    # now we know all of the node labels so we can add the edges
+    # with the correct labels
+    for n in G:
+        for nbr in nbrs[n]:
+            G.add_edge(n, nodelabel[nbr])
+    return G
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/pajek.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/pajek.py
new file mode 100644
index 0000000000000000000000000000000000000000..2cab6b9ae68ba9c9869f0452394838925ff2a7db
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/pajek.py
@@ -0,0 +1,286 @@
+"""
+*****
+Pajek
+*****
+Read graphs in Pajek format.
+
+This implementation handles directed and undirected graphs including
+those with self loops and parallel edges.
+
+Format
+------
+See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
+for format information.
+
+"""
+
+import warnings
+
+import networkx as nx
+from networkx.utils import open_file
+
+__all__ = ["read_pajek", "parse_pajek", "generate_pajek", "write_pajek"]
+
+
+def generate_pajek(G):
+    """Generate lines in Pajek graph format.
+
+    Parameters
+    ----------
+    G : graph
+       A Networkx graph
+
+    References
+    ----------
+    See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
+    for format information.
+    """
+    if G.name == "":
+        name = "NetworkX"
+    else:
+        name = G.name
+    # Apparently many Pajek format readers can't process this line
+    # So we'll leave it out for now.
+    # yield '*network %s'%name
+
+    # write nodes with attributes
+    yield f"*vertices {G.order()}"
+    nodes = list(G)
+    # make dictionary mapping nodes to integers
+    nodenumber = dict(zip(nodes, range(1, len(nodes) + 1)))
+    for n in nodes:
+        # copy node attributes and pop mandatory attributes
+        # to avoid duplication.
+        na = G.nodes.get(n, {}).copy()
+        x = na.pop("x", 0.0)
+        y = na.pop("y", 0.0)
+        try:
+            id = int(na.pop("id", nodenumber[n]))
+        except ValueError as err:
+            err.args += (
+                (
+                    "Pajek format requires 'id' to be an int()."
+                    " Refer to the 'Relabeling nodes' section."
+                ),
+            )
+            raise
+        nodenumber[n] = id
+        shape = na.pop("shape", "ellipse")
+        s = " ".join(map(make_qstr, (id, n, x, y, shape)))
+        # only optional attributes are left in na.
+        for k, v in na.items():
+            if isinstance(v, str) and v.strip() != "":
+                s += f" {make_qstr(k)} {make_qstr(v)}"
+            else:
+                warnings.warn(
+                    f"Node attribute {k} is not processed. {('Empty attribute' if isinstance(v, str) else 'Non-string attribute')}."
+                )
+        yield s
+
+    # write edges with attributes
+    if G.is_directed():
+        yield "*arcs"
+    else:
+        yield "*edges"
+    for u, v, edgedata in G.edges(data=True):
+        d = edgedata.copy()
+        value = d.pop("weight", 1.0)  # use 1 as default edge value
+        s = " ".join(map(make_qstr, (nodenumber[u], nodenumber[v], value)))
+        for k, v in d.items():
+            if isinstance(v, str) and v.strip() != "":
+                s += f" {make_qstr(k)} {make_qstr(v)}"
+            else:
+                warnings.warn(
+                    f"Edge attribute {k} is not processed. {('Empty attribute' if isinstance(v, str) else 'Non-string attribute')}."
+                )
+        yield s
+
+
+@open_file(1, mode="wb")
+def write_pajek(G, path, encoding="UTF-8"):
+    """Write graph in Pajek format to path.
+
+    Parameters
+    ----------
+    G : graph
+       A Networkx graph
+    path : file or string
+       File or filename to write.
+       Filenames ending in .gz or .bz2 will be compressed.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> nx.write_pajek(G, "test.netP4")
+
+    Warnings
+    --------
+    Optional node attributes and edge attributes must be non-empty strings.
+    Otherwise it will not be written into the file. You will need to
+    convert those attributes to strings if you want to keep them.
+
+    References
+    ----------
+    See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
+    for format information.
+    """
+    for line in generate_pajek(G):
+        line += "\n"
+        path.write(line.encode(encoding))
+
+
+@open_file(0, mode="rb")
+@nx._dispatchable(graphs=None, returns_graph=True)
+def read_pajek(path, encoding="UTF-8"):
+    """Read graph in Pajek format from path.
+
+    Parameters
+    ----------
+    path : file or string
+       Filename or file handle to read.
+       Filenames ending in .gz or .bz2 will be decompressed.
+
+    Returns
+    -------
+    G : NetworkX MultiGraph or MultiDiGraph.
+
+    Examples
+    --------
+    >>> G = nx.path_graph(4)
+    >>> nx.write_pajek(G, "test.net")
+    >>> G = nx.read_pajek("test.net")
+
+    To create a Graph instead of a MultiGraph use
+
+    >>> G1 = nx.Graph(G)
+
+    References
+    ----------
+    See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
+    for format information.
+    """
+    lines = (line.decode(encoding) for line in path)
+    return parse_pajek(lines)
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def parse_pajek(lines):
+    """Parse Pajek format graph from string or iterable.
+
+    Parameters
+    ----------
+    lines : string or iterable
+       Data in Pajek format.
+
+    Returns
+    -------
+    G : NetworkX graph
+
+    See Also
+    --------
+    read_pajek
+
+    """
+    import shlex
+
+    # multigraph=False
+    if isinstance(lines, str):
+        lines = iter(lines.split("\n"))
+    lines = iter([line.rstrip("\n") for line in lines])
+    G = nx.MultiDiGraph()  # are multiedges allowed in Pajek? assume yes
+    labels = []  # in the order of the file, needed for matrix
+    while lines:
+        try:
+            l = next(lines)
+        except:  # EOF
+            break
+        if l.lower().startswith("*network"):
+            try:
+                label, name = l.split(None, 1)
+            except ValueError:
+                # Line was not of the form:  *network NAME
+                pass
+            else:
+                G.graph["name"] = name
+        elif l.lower().startswith("*vertices"):
+            nodelabels = {}
+            l, nnodes = l.split()
+            for i in range(int(nnodes)):
+                l = next(lines)
+                try:
+                    splitline = [
+                        x.decode("utf-8") for x in shlex.split(str(l).encode("utf-8"))
+                    ]
+                except AttributeError:
+                    splitline = shlex.split(str(l))
+                id, label = splitline[0:2]
+                labels.append(label)
+                G.add_node(label)
+                nodelabels[id] = label
+                G.nodes[label]["id"] = id
+                try:
+                    x, y, shape = splitline[2:5]
+                    G.nodes[label].update(
+                        {"x": float(x), "y": float(y), "shape": shape}
+                    )
+                except:
+                    pass
+                extra_attr = zip(splitline[5::2], splitline[6::2])
+                G.nodes[label].update(extra_attr)
+        elif l.lower().startswith("*edges") or l.lower().startswith("*arcs"):
+            if l.lower().startswith("*edge"):
+                # switch from multidigraph to multigraph
+                G = nx.MultiGraph(G)
+            if l.lower().startswith("*arcs"):
+                # switch to directed with multiple arcs for each existing edge
+                G = G.to_directed()
+            for l in lines:
+                try:
+                    splitline = [
+                        x.decode("utf-8") for x in shlex.split(str(l).encode("utf-8"))
+                    ]
+                except AttributeError:
+                    splitline = shlex.split(str(l))
+
+                if len(splitline) < 2:
+                    continue
+                ui, vi = splitline[0:2]
+                u = nodelabels.get(ui, ui)
+                v = nodelabels.get(vi, vi)
+                # parse the data attached to this edge and put in a dictionary
+                edge_data = {}
+                try:
+                    # there should always be a single value on the edge?
+                    w = splitline[2:3]
+                    edge_data.update({"weight": float(w[0])})
+                except:
+                    pass
+                    # if there isn't, just assign a 1
+                #                    edge_data.update({'value':1})
+                extra_attr = zip(splitline[3::2], splitline[4::2])
+                edge_data.update(extra_attr)
+                # if G.has_edge(u,v):
+                #     multigraph=True
+                G.add_edge(u, v, **edge_data)
+        elif l.lower().startswith("*matrix"):
+            G = nx.DiGraph(G)
+            adj_list = (
+                (labels[row], labels[col], {"weight": int(data)})
+                for (row, line) in enumerate(lines)
+                for (col, data) in enumerate(line.split())
+                if int(data) != 0
+            )
+            G.add_edges_from(adj_list)
+
+    return G
+
+
+def make_qstr(t):
+    """Returns the string representation of t.
+    Add outer double-quotes if the string has a space.
+    """
+    if not isinstance(t, str):
+        t = str(t)
+    if " " in t:
+        t = f'"{t}"'
+    return t
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/sparse6.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/sparse6.py
new file mode 100644
index 0000000000000000000000000000000000000000..b82ae5c34d30e1a1e72f0e94e6845072d18296f9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/sparse6.py
@@ -0,0 +1,379 @@
+# Original author: D. Eppstein, UC Irvine, August 12, 2003.
+# The original code at https://www.ics.uci.edu/~eppstein/PADS/ is public domain.
+"""Functions for reading and writing graphs in the *sparse6* format.
+
+The *sparse6* file format is a space-efficient format for large sparse
+graphs. For small graphs or large dense graphs, use the *graph6* file
+format.
+
+For more information, see the `sparse6`_ homepage.
+
+.. _sparse6: https://users.cecs.anu.edu.au/~bdm/data/formats.html
+
+"""
+
+import networkx as nx
+from networkx.exception import NetworkXError
+from networkx.readwrite.graph6 import data_to_n, n_to_data
+from networkx.utils import not_implemented_for, open_file
+
+__all__ = ["from_sparse6_bytes", "read_sparse6", "to_sparse6_bytes", "write_sparse6"]
+
+
+def _generate_sparse6_bytes(G, nodes, header):
+    """Yield bytes in the sparse6 encoding of a graph.
+
+    `G` is an undirected simple graph. `nodes` is the list of nodes for
+    which the node-induced subgraph will be encoded; if `nodes` is the
+    list of all nodes in the graph, the entire graph will be
+    encoded. `header` is a Boolean that specifies whether to generate
+    the header ``b'>>sparse6<<'`` before the remaining data.
+
+    This function generates `bytes` objects in the following order:
+
+    1. the header (if requested),
+    2. the encoding of the number of nodes,
+    3. each character, one-at-a-time, in the encoding of the requested
+       node-induced subgraph,
+    4. a newline character.
+
+    This function raises :exc:`ValueError` if the graph is too large for
+    the graph6 format (that is, greater than ``2 ** 36`` nodes).
+
+    """
+    n = len(G)
+    if n >= 2**36:
+        raise ValueError(
+            "sparse6 is only defined if number of nodes is less than 2 ** 36"
+        )
+    if header:
+        yield b">>sparse6<<"
+    yield b":"
+    for d in n_to_data(n):
+        yield str.encode(chr(d + 63))
+
+    k = 1
+    while 1 << k < n:
+        k += 1
+
+    def enc(x):
+        """Big endian k-bit encoding of x"""
+        return [1 if (x & 1 << (k - 1 - i)) else 0 for i in range(k)]
+
+    edges = sorted((max(u, v), min(u, v)) for u, v in G.edges())
+    bits = []
+    curv = 0
+    for v, u in edges:
+        if v == curv:  # current vertex edge
+            bits.append(0)
+            bits.extend(enc(u))
+        elif v == curv + 1:  # next vertex edge
+            curv += 1
+            bits.append(1)
+            bits.extend(enc(u))
+        else:  # skip to vertex v and then add edge to u
+            curv = v
+            bits.append(1)
+            bits.extend(enc(v))
+            bits.append(0)
+            bits.extend(enc(u))
+    if k < 6 and n == (1 << k) and ((-len(bits)) % 6) >= k and curv < (n - 1):
+        # Padding special case: small k, n=2^k,
+        # more than k bits of padding needed,
+        # current vertex is not (n-1) --
+        # appending 1111... would add a loop on (n-1)
+        bits.append(0)
+        bits.extend([1] * ((-len(bits)) % 6))
+    else:
+        bits.extend([1] * ((-len(bits)) % 6))
+
+    data = [
+        (bits[i + 0] << 5)
+        + (bits[i + 1] << 4)
+        + (bits[i + 2] << 3)
+        + (bits[i + 3] << 2)
+        + (bits[i + 4] << 1)
+        + (bits[i + 5] << 0)
+        for i in range(0, len(bits), 6)
+    ]
+
+    for d in data:
+        yield str.encode(chr(d + 63))
+    yield b"\n"
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def from_sparse6_bytes(string):
+    """Read an undirected graph in sparse6 format from string.
+
+    Parameters
+    ----------
+    string : string
+       Data in sparse6 format
+
+    Returns
+    -------
+    G : Graph
+
+    Raises
+    ------
+    NetworkXError
+        If the string is unable to be parsed in sparse6 format
+
+    Examples
+    --------
+    >>> G = nx.from_sparse6_bytes(b":A_")
+    >>> sorted(G.edges())
+    [(0, 1), (0, 1), (0, 1)]
+
+    See Also
+    --------
+    read_sparse6, write_sparse6
+
+    References
+    ----------
+    .. [1] Sparse6 specification
+           
+
+    """
+    if string.startswith(b">>sparse6<<"):
+        string = string[11:]
+    if not string.startswith(b":"):
+        raise NetworkXError("Expected leading colon in sparse6")
+
+    chars = [c - 63 for c in string[1:]]
+    n, data = data_to_n(chars)
+    k = 1
+    while 1 << k < n:
+        k += 1
+
+    def parseData():
+        """Returns stream of pairs b[i], x[i] for sparse6 format."""
+        chunks = iter(data)
+        d = None  # partial data word
+        dLen = 0  # how many unparsed bits are left in d
+
+        while 1:
+            if dLen < 1:
+                try:
+                    d = next(chunks)
+                except StopIteration:
+                    return
+                dLen = 6
+            dLen -= 1
+            b = (d >> dLen) & 1  # grab top remaining bit
+
+            x = d & ((1 << dLen) - 1)  # partially built up value of x
+            xLen = dLen  # how many bits included so far in x
+            while xLen < k:  # now grab full chunks until we have enough
+                try:
+                    d = next(chunks)
+                except StopIteration:
+                    return
+                dLen = 6
+                x = (x << 6) + d
+                xLen += 6
+            x = x >> (xLen - k)  # shift back the extra bits
+            dLen = xLen - k
+            yield b, x
+
+    v = 0
+
+    G = nx.MultiGraph()
+    G.add_nodes_from(range(n))
+
+    multigraph = False
+    for b, x in parseData():
+        if b == 1:
+            v += 1
+        # padding with ones can cause overlarge number here
+        if x >= n or v >= n:
+            break
+        elif x > v:
+            v = x
+        else:
+            if G.has_edge(x, v):
+                multigraph = True
+            G.add_edge(x, v)
+    if not multigraph:
+        G = nx.Graph(G)
+    return G
+
+
+def to_sparse6_bytes(G, nodes=None, header=True):
+    """Convert an undirected graph to bytes in sparse6 format.
+
+    Parameters
+    ----------
+    G : Graph (undirected)
+
+    nodes: list or iterable
+       Nodes are labeled 0...n-1 in the order provided.  If None the ordering
+       given by ``G.nodes()`` is used.
+
+    header: bool
+       If True add '>>sparse6<<' bytes to head of data.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+        If the graph is directed.
+
+    ValueError
+        If the graph has at least ``2 ** 36`` nodes; the sparse6 format
+        is only defined for graphs of order less than ``2 ** 36``.
+
+    Examples
+    --------
+    >>> nx.to_sparse6_bytes(nx.path_graph(2))
+    b'>>sparse6<<:An\\n'
+
+    See Also
+    --------
+    to_sparse6_bytes, read_sparse6, write_sparse6_bytes
+
+    Notes
+    -----
+    The returned bytes end with a newline character.
+
+    The format does not support edge or node labels.
+
+    References
+    ----------
+    .. [1] Graph6 specification
+           
+
+    """
+    if nodes is not None:
+        G = G.subgraph(nodes)
+    G = nx.convert_node_labels_to_integers(G, ordering="sorted")
+    return b"".join(_generate_sparse6_bytes(G, nodes, header))
+
+
+@open_file(0, mode="rb")
+@nx._dispatchable(graphs=None, returns_graph=True)
+def read_sparse6(path):
+    """Read an undirected graph in sparse6 format from path.
+
+    Parameters
+    ----------
+    path : file or string
+       Filename or file handle to read.
+       Filenames ending in .gz or .bz2 will be decompressed.
+
+    Returns
+    -------
+    G : Graph/Multigraph or list of Graphs/MultiGraphs
+       If the file contains multiple lines then a list of graphs is returned
+
+    Raises
+    ------
+    NetworkXError
+        If the string is unable to be parsed in sparse6 format
+
+    Examples
+    --------
+    You can read a sparse6 file by giving the path to the file::
+
+        >>> import tempfile
+        >>> with tempfile.NamedTemporaryFile(delete=False) as f:
+        ...     _ = f.write(b">>sparse6<<:An\\n")
+        ...     _ = f.seek(0)
+        ...     G = nx.read_sparse6(f.name)
+        >>> list(G.edges())
+        [(0, 1)]
+
+    You can also read a sparse6 file by giving an open file-like object::
+
+        >>> import tempfile
+        >>> with tempfile.NamedTemporaryFile() as f:
+        ...     _ = f.write(b">>sparse6<<:An\\n")
+        ...     _ = f.seek(0)
+        ...     G = nx.read_sparse6(f)
+        >>> list(G.edges())
+        [(0, 1)]
+
+    See Also
+    --------
+    read_sparse6, from_sparse6_bytes
+
+    References
+    ----------
+    .. [1] Sparse6 specification
+           
+
+    """
+    glist = []
+    for line in path:
+        line = line.strip()
+        if not len(line):
+            continue
+        glist.append(from_sparse6_bytes(line))
+    if len(glist) == 1:
+        return glist[0]
+    else:
+        return glist
+
+
+@not_implemented_for("directed")
+@open_file(1, mode="wb")
+def write_sparse6(G, path, nodes=None, header=True):
+    """Write graph G to given path in sparse6 format.
+
+    Parameters
+    ----------
+    G : Graph (undirected)
+
+    path : file or string
+       File or filename to write.
+       Filenames ending in .gz or .bz2 will be compressed.
+
+    nodes: list or iterable
+       Nodes are labeled 0...n-1 in the order provided.  If None the ordering
+       given by G.nodes() is used.
+
+    header: bool
+       If True add '>>sparse6<<' string to head of data
+
+    Raises
+    ------
+    NetworkXError
+        If the graph is directed
+
+    Examples
+    --------
+    You can write a sparse6 file by giving the path to the file::
+
+        >>> import tempfile
+        >>> with tempfile.NamedTemporaryFile(delete=False) as f:
+        ...     nx.write_sparse6(nx.path_graph(2), f.name)
+        ...     print(f.read())
+        b'>>sparse6<<:An\\n'
+
+    You can also write a sparse6 file by giving an open file-like object::
+
+        >>> with tempfile.NamedTemporaryFile() as f:
+        ...     nx.write_sparse6(nx.path_graph(2), f)
+        ...     _ = f.seek(0)
+        ...     print(f.read())
+        b'>>sparse6<<:An\\n'
+
+    See Also
+    --------
+    read_sparse6, from_sparse6_bytes
+
+    Notes
+    -----
+    The format does not support edge or node labels.
+
+    References
+    ----------
+    .. [1] Sparse6 specification
+           
+
+    """
+    if nodes is not None:
+        G = G.subgraph(nodes)
+    G = nx.convert_node_labels_to_integers(G, ordering="sorted")
+    for b in _generate_sparse6_bytes(G, nodes, header):
+        path.write(b)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/text.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/text.py
new file mode 100644
index 0000000000000000000000000000000000000000..6fce220764d0e3aab0dff0200f3d7b601d03d007
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/readwrite/text.py
@@ -0,0 +1,851 @@
+"""
+Text-based visual representations of graphs
+"""
+
+import sys
+from collections import defaultdict
+
+import networkx as nx
+from networkx.utils import open_file
+
+__all__ = ["generate_network_text", "write_network_text"]
+
+
+class BaseGlyphs:
+    @classmethod
+    def as_dict(cls):
+        return {
+            a: getattr(cls, a)
+            for a in dir(cls)
+            if not a.startswith("_") and a != "as_dict"
+        }
+
+
+class AsciiBaseGlyphs(BaseGlyphs):
+    empty: str = "+"
+    newtree_last: str = "+-- "
+    newtree_mid: str = "+-- "
+    endof_forest: str = "    "
+    within_forest: str = ":   "
+    within_tree: str = "|   "
+
+
+class AsciiDirectedGlyphs(AsciiBaseGlyphs):
+    last: str = "L-> "
+    mid: str = "|-> "
+    backedge: str = "<-"
+    vertical_edge: str = "!"
+
+
+class AsciiUndirectedGlyphs(AsciiBaseGlyphs):
+    last: str = "L-- "
+    mid: str = "|-- "
+    backedge: str = "-"
+    vertical_edge: str = "|"
+
+
+class UtfBaseGlyphs(BaseGlyphs):
+    # Notes on available box and arrow characters
+    # https://en.wikipedia.org/wiki/Box-drawing_character
+    # https://stackoverflow.com/questions/2701192/triangle-arrow
+    empty: str = "╙"
+    newtree_last: str = "╙── "
+    newtree_mid: str = "╟── "
+    endof_forest: str = "    "
+    within_forest: str = "╎   "
+    within_tree: str = "│   "
+
+
+class UtfDirectedGlyphs(UtfBaseGlyphs):
+    last: str = "└─╼ "
+    mid: str = "├─╼ "
+    backedge: str = "╾"
+    vertical_edge: str = "╽"
+
+
+class UtfUndirectedGlyphs(UtfBaseGlyphs):
+    last: str = "└── "
+    mid: str = "├── "
+    backedge: str = "─"
+    vertical_edge: str = "│"
+
+
+def generate_network_text(
+    graph,
+    with_labels=True,
+    sources=None,
+    max_depth=None,
+    ascii_only=False,
+    vertical_chains=False,
+):
+    """Generate lines in the "network text" format
+
+    This works via a depth-first traversal of the graph and writing a line for
+    each unique node encountered. Non-tree edges are written to the right of
+    each node, and connection to a non-tree edge is indicated with an ellipsis.
+    This representation works best when the input graph is a forest, but any
+    graph can be represented.
+
+    This notation is original to networkx, although it is simple enough that it
+    may be known in existing literature. See #5602 for details. The procedure
+    is summarized as follows:
+
+    1. Given a set of source nodes (which can be specified, or automatically
+    discovered via finding the (strongly) connected components and choosing one
+    node with minimum degree from each), we traverse the graph in depth first
+    order.
+
+    2. Each reachable node will be printed exactly once on it's own line.
+
+    3. Edges are indicated in one of four ways:
+
+        a. a parent "L-style" connection on the upper left. This corresponds to
+        a traversal in the directed DFS tree.
+
+        b. a backref "<-style" connection shown directly on the right. For
+        directed graphs, these are drawn for any incoming edges to a node that
+        is not a parent edge. For undirected graphs, these are drawn for only
+        the non-parent edges that have already been represented (The edges that
+        have not been represented will be handled in the recursive case).
+
+        c. a child "L-style" connection on the lower right. Drawing of the
+        children are handled recursively.
+
+        d. if ``vertical_chains`` is true, and a parent node only has one child
+        a "vertical-style" edge is drawn between them.
+
+    4. The children of each node (wrt the directed DFS tree) are drawn
+    underneath and to the right of it. In the case that a child node has already
+    been drawn the connection is replaced with an ellipsis ("...") to indicate
+    that there is one or more connections represented elsewhere.
+
+    5. If a maximum depth is specified, an edge to nodes past this maximum
+    depth will be represented by an ellipsis.
+
+    6. If a node has a truthy "collapse" value, then we do not traverse past
+    that node.
+
+    Parameters
+    ----------
+    graph : nx.DiGraph | nx.Graph
+        Graph to represent
+
+    with_labels : bool | str
+        If True will use the "label" attribute of a node to display if it
+        exists otherwise it will use the node value itself. If given as a
+        string, then that attribute name will be used instead of "label".
+        Defaults to True.
+
+    sources : List
+        Specifies which nodes to start traversal from. Note: nodes that are not
+        reachable from one of these sources may not be shown. If unspecified,
+        the minimal set of nodes needed to reach all others will be used.
+
+    max_depth : int | None
+        The maximum depth to traverse before stopping. Defaults to None.
+
+    ascii_only : Boolean
+        If True only ASCII characters are used to construct the visualization
+
+    vertical_chains : Boolean
+        If True, chains of nodes will be drawn vertically when possible.
+
+    Yields
+    ------
+    str : a line of generated text
+
+    Examples
+    --------
+    >>> graph = nx.path_graph(10)
+    >>> graph.add_node("A")
+    >>> graph.add_node("B")
+    >>> graph.add_node("C")
+    >>> graph.add_node("D")
+    >>> graph.add_edge(9, "A")
+    >>> graph.add_edge(9, "B")
+    >>> graph.add_edge(9, "C")
+    >>> graph.add_edge("C", "D")
+    >>> graph.add_edge("C", "E")
+    >>> graph.add_edge("C", "F")
+    >>> nx.write_network_text(graph)
+    ╙── 0
+        └── 1
+            └── 2
+                └── 3
+                    └── 4
+                        └── 5
+                            └── 6
+                                └── 7
+                                    └── 8
+                                        └── 9
+                                            ├── A
+                                            ├── B
+                                            └── C
+                                                ├── D
+                                                ├── E
+                                                └── F
+    >>> nx.write_network_text(graph, vertical_chains=True)
+    ╙── 0
+        │
+        1
+        │
+        2
+        │
+        3
+        │
+        4
+        │
+        5
+        │
+        6
+        │
+        7
+        │
+        8
+        │
+        9
+        ├── A
+        ├── B
+        └── C
+            ├── D
+            ├── E
+            └── F
+    """
+    from typing import Any, NamedTuple
+
+    class StackFrame(NamedTuple):
+        parent: Any
+        node: Any
+        indents: list
+        this_islast: bool
+        this_vertical: bool
+
+    collapse_attr = "collapse"
+
+    is_directed = graph.is_directed()
+
+    if is_directed:
+        glyphs = AsciiDirectedGlyphs if ascii_only else UtfDirectedGlyphs
+        succ = graph.succ
+        pred = graph.pred
+    else:
+        glyphs = AsciiUndirectedGlyphs if ascii_only else UtfUndirectedGlyphs
+        succ = graph.adj
+        pred = graph.adj
+
+    if isinstance(with_labels, str):
+        label_attr = with_labels
+    elif with_labels:
+        label_attr = "label"
+    else:
+        label_attr = None
+
+    if max_depth == 0:
+        yield glyphs.empty + " ..."
+    elif len(graph.nodes) == 0:
+        yield glyphs.empty
+    else:
+        # If the nodes to traverse are unspecified, find the minimal set of
+        # nodes that will reach the entire graph
+        if sources is None:
+            sources = _find_sources(graph)
+
+        # Populate the stack with each:
+        # 1. parent node in the DFS tree (or None for root nodes),
+        # 2. the current node in the DFS tree
+        # 2. a list of indentations indicating depth
+        # 3. a flag indicating if the node is the final one to be written.
+        # Reverse the stack so sources are popped in the correct order.
+        last_idx = len(sources) - 1
+        stack = [
+            StackFrame(None, node, [], (idx == last_idx), False)
+            for idx, node in enumerate(sources)
+        ][::-1]
+
+        num_skipped_children = defaultdict(lambda: 0)
+        seen_nodes = set()
+        while stack:
+            parent, node, indents, this_islast, this_vertical = stack.pop()
+
+            if node is not Ellipsis:
+                skip = node in seen_nodes
+                if skip:
+                    # Mark that we skipped a parent's child
+                    num_skipped_children[parent] += 1
+
+                if this_islast:
+                    # If we reached the last child of a parent, and we skipped
+                    # any of that parents children, then we should emit an
+                    # ellipsis at the end after this.
+                    if num_skipped_children[parent] and parent is not None:
+                        # Append the ellipsis to be emitted last
+                        next_islast = True
+                        try_frame = StackFrame(
+                            node, Ellipsis, indents, next_islast, False
+                        )
+                        stack.append(try_frame)
+
+                        # Redo this frame, but not as a last object
+                        next_islast = False
+                        try_frame = StackFrame(
+                            parent, node, indents, next_islast, this_vertical
+                        )
+                        stack.append(try_frame)
+                        continue
+
+                if skip:
+                    continue
+                seen_nodes.add(node)
+
+            if not indents:
+                # Top level items (i.e. trees in the forest) get different
+                # glyphs to indicate they are not actually connected
+                if this_islast:
+                    this_vertical = False
+                    this_prefix = indents + [glyphs.newtree_last]
+                    next_prefix = indents + [glyphs.endof_forest]
+                else:
+                    this_prefix = indents + [glyphs.newtree_mid]
+                    next_prefix = indents + [glyphs.within_forest]
+
+            else:
+                # Non-top-level items
+                if this_vertical:
+                    this_prefix = indents
+                    next_prefix = indents
+                else:
+                    if this_islast:
+                        this_prefix = indents + [glyphs.last]
+                        next_prefix = indents + [glyphs.endof_forest]
+                    else:
+                        this_prefix = indents + [glyphs.mid]
+                        next_prefix = indents + [glyphs.within_tree]
+
+            if node is Ellipsis:
+                label = " ..."
+                suffix = ""
+                children = []
+            else:
+                if label_attr is not None:
+                    label = str(graph.nodes[node].get(label_attr, node))
+                else:
+                    label = str(node)
+
+                # Determine if we want to show the children of this node.
+                if collapse_attr is not None:
+                    collapse = graph.nodes[node].get(collapse_attr, False)
+                else:
+                    collapse = False
+
+                # Determine:
+                # (1) children to traverse into after showing this node.
+                # (2) parents to immediately show to the right of this node.
+                if is_directed:
+                    # In the directed case we must show every successor node
+                    # note: it may be skipped later, but we don't have that
+                    # information here.
+                    children = list(succ[node])
+                    # In the directed case we must show every predecessor
+                    # except for parent we directly traversed from.
+                    handled_parents = {parent}
+                else:
+                    # Showing only the unseen children results in a more
+                    # concise representation for the undirected case.
+                    children = [
+                        child for child in succ[node] if child not in seen_nodes
+                    ]
+
+                    # In the undirected case, parents are also children, so we
+                    # only need to immediately show the ones we can no longer
+                    # traverse
+                    handled_parents = {*children, parent}
+
+                if max_depth is not None and len(indents) == max_depth - 1:
+                    # Use ellipsis to indicate we have reached maximum depth
+                    if children:
+                        children = [Ellipsis]
+                    handled_parents = {parent}
+
+                if collapse:
+                    # Collapsing a node is the same as reaching maximum depth
+                    if children:
+                        children = [Ellipsis]
+                    handled_parents = {parent}
+
+                # The other parents are other predecessors of this node that
+                # are not handled elsewhere.
+                other_parents = [p for p in pred[node] if p not in handled_parents]
+                if other_parents:
+                    if label_attr is not None:
+                        other_parents_labels = ", ".join(
+                            [
+                                str(graph.nodes[p].get(label_attr, p))
+                                for p in other_parents
+                            ]
+                        )
+                    else:
+                        other_parents_labels = ", ".join(
+                            [str(p) for p in other_parents]
+                        )
+                    suffix = " ".join(["", glyphs.backedge, other_parents_labels])
+                else:
+                    suffix = ""
+
+            # Emit the line for this node, this will be called for each node
+            # exactly once.
+            if this_vertical:
+                yield "".join(this_prefix + [glyphs.vertical_edge])
+
+            yield "".join(this_prefix + [label, suffix])
+
+            if vertical_chains:
+                if is_directed:
+                    num_children = len(set(children))
+                else:
+                    num_children = len(set(children) - {parent})
+                # The next node can be drawn vertically if it is the only
+                # remaining child of this node.
+                next_is_vertical = num_children == 1
+            else:
+                next_is_vertical = False
+
+            # Push children on the stack in reverse order so they are popped in
+            # the original order.
+            for idx, child in enumerate(children[::-1]):
+                next_islast = idx == 0
+                try_frame = StackFrame(
+                    node, child, next_prefix, next_islast, next_is_vertical
+                )
+                stack.append(try_frame)
+
+
+@open_file(1, "w")
+def write_network_text(
+    graph,
+    path=None,
+    with_labels=True,
+    sources=None,
+    max_depth=None,
+    ascii_only=False,
+    end="\n",
+    vertical_chains=False,
+):
+    """Creates a nice text representation of a graph
+
+    This works via a depth-first traversal of the graph and writing a line for
+    each unique node encountered. Non-tree edges are written to the right of
+    each node, and connection to a non-tree edge is indicated with an ellipsis.
+    This representation works best when the input graph is a forest, but any
+    graph can be represented.
+
+    Parameters
+    ----------
+    graph : nx.DiGraph | nx.Graph
+        Graph to represent
+
+    path : string or file or callable or None
+       Filename or file handle for data output.
+       if a function, then it will be called for each generated line.
+       if None, this will default to "sys.stdout.write"
+
+    with_labels : bool | str
+        If True will use the "label" attribute of a node to display if it
+        exists otherwise it will use the node value itself. If given as a
+        string, then that attribute name will be used instead of "label".
+        Defaults to True.
+
+    sources : List
+        Specifies which nodes to start traversal from. Note: nodes that are not
+        reachable from one of these sources may not be shown. If unspecified,
+        the minimal set of nodes needed to reach all others will be used.
+
+    max_depth : int | None
+        The maximum depth to traverse before stopping. Defaults to None.
+
+    ascii_only : Boolean
+        If True only ASCII characters are used to construct the visualization
+
+    end : string
+        The line ending character
+
+    vertical_chains : Boolean
+        If True, chains of nodes will be drawn vertically when possible.
+
+    Examples
+    --------
+    >>> graph = nx.balanced_tree(r=2, h=2, create_using=nx.DiGraph)
+    >>> nx.write_network_text(graph)
+    ╙── 0
+        ├─╼ 1
+        │   ├─╼ 3
+        │   └─╼ 4
+        └─╼ 2
+            ├─╼ 5
+            └─╼ 6
+
+    >>> # A near tree with one non-tree edge
+    >>> graph.add_edge(5, 1)
+    >>> nx.write_network_text(graph)
+    ╙── 0
+        ├─╼ 1 ╾ 5
+        │   ├─╼ 3
+        │   └─╼ 4
+        └─╼ 2
+            ├─╼ 5
+            │   └─╼  ...
+            └─╼ 6
+
+    >>> graph = nx.cycle_graph(5)
+    >>> nx.write_network_text(graph)
+    ╙── 0
+        ├── 1
+        │   └── 2
+        │       └── 3
+        │           └── 4 ─ 0
+        └──  ...
+
+    >>> graph = nx.cycle_graph(5, nx.DiGraph)
+    >>> nx.write_network_text(graph, vertical_chains=True)
+    ╙── 0 ╾ 4
+        ╽
+        1
+        ╽
+        2
+        ╽
+        3
+        ╽
+        4
+        └─╼  ...
+
+    >>> nx.write_network_text(graph, vertical_chains=True, ascii_only=True)
+    +-- 0 <- 4
+        !
+        1
+        !
+        2
+        !
+        3
+        !
+        4
+        L->  ...
+
+    >>> graph = nx.generators.barbell_graph(4, 2)
+    >>> nx.write_network_text(graph, vertical_chains=False)
+    ╙── 4
+        ├── 5
+        │   └── 6
+        │       ├── 7
+        │       │   ├── 8 ─ 6
+        │       │   │   └── 9 ─ 6, 7
+        │       │   └──  ...
+        │       └──  ...
+        └── 3
+            ├── 0
+            │   ├── 1 ─ 3
+            │   │   └── 2 ─ 0, 3
+            │   └──  ...
+            └──  ...
+    >>> nx.write_network_text(graph, vertical_chains=True)
+    ╙── 4
+        ├── 5
+        │   │
+        │   6
+        │   ├── 7
+        │   │   ├── 8 ─ 6
+        │   │   │   │
+        │   │   │   9 ─ 6, 7
+        │   │   └──  ...
+        │   └──  ...
+        └── 3
+            ├── 0
+            │   ├── 1 ─ 3
+            │   │   │
+            │   │   2 ─ 0, 3
+            │   └──  ...
+            └──  ...
+
+    >>> graph = nx.complete_graph(5, create_using=nx.Graph)
+    >>> nx.write_network_text(graph)
+    ╙── 0
+        ├── 1
+        │   ├── 2 ─ 0
+        │   │   ├── 3 ─ 0, 1
+        │   │   │   └── 4 ─ 0, 1, 2
+        │   │   └──  ...
+        │   └──  ...
+        └──  ...
+
+    >>> graph = nx.complete_graph(3, create_using=nx.DiGraph)
+    >>> nx.write_network_text(graph)
+    ╙── 0 ╾ 1, 2
+        ├─╼ 1 ╾ 2
+        │   ├─╼ 2 ╾ 0
+        │   │   └─╼  ...
+        │   └─╼  ...
+        └─╼  ...
+    """
+    if path is None:
+        # The path is unspecified, write to stdout
+        _write = sys.stdout.write
+    elif hasattr(path, "write"):
+        # The path is already an open file
+        _write = path.write
+    elif callable(path):
+        # The path is a custom callable
+        _write = path
+    else:
+        raise TypeError(type(path))
+
+    for line in generate_network_text(
+        graph,
+        with_labels=with_labels,
+        sources=sources,
+        max_depth=max_depth,
+        ascii_only=ascii_only,
+        vertical_chains=vertical_chains,
+    ):
+        _write(line + end)
+
+
+def _find_sources(graph):
+    """
+    Determine a minimal set of nodes such that the entire graph is reachable
+    """
+    # For each connected part of the graph, choose at least
+    # one node as a starting point, preferably without a parent
+    if graph.is_directed():
+        # Choose one node from each SCC with minimum in_degree
+        sccs = list(nx.strongly_connected_components(graph))
+        # condensing the SCCs forms a dag, the nodes in this graph with
+        # 0 in-degree correspond to the SCCs from which the minimum set
+        # of nodes from which all other nodes can be reached.
+        scc_graph = nx.condensation(graph, sccs)
+        supernode_to_nodes = {sn: [] for sn in scc_graph.nodes()}
+        # Note: the order of mapping differs between pypy and cpython
+        # so we have to loop over graph nodes for consistency
+        mapping = scc_graph.graph["mapping"]
+        for n in graph.nodes:
+            sn = mapping[n]
+            supernode_to_nodes[sn].append(n)
+        sources = []
+        for sn in scc_graph.nodes():
+            if scc_graph.in_degree[sn] == 0:
+                scc = supernode_to_nodes[sn]
+                node = min(scc, key=lambda n: graph.in_degree[n])
+                sources.append(node)
+    else:
+        # For undirected graph, the entire graph will be reachable as
+        # long as we consider one node from every connected component
+        sources = [
+            min(cc, key=lambda n: graph.degree[n])
+            for cc in nx.connected_components(graph)
+        ]
+        sources = sorted(sources, key=lambda n: graph.degree[n])
+    return sources
+
+
+def _parse_network_text(lines):
+    """Reconstructs a graph from a network text representation.
+
+    This is mainly used for testing.  Network text is for display, not
+    serialization, as such this cannot parse all network text representations
+    because node labels can be ambiguous with the glyphs and indentation used
+    to represent edge structure. Additionally, there is no way to determine if
+    disconnected graphs were originally directed or undirected.
+
+    Parameters
+    ----------
+    lines : list or iterator of strings
+        Input data in network text format
+
+    Returns
+    -------
+    G: NetworkX graph
+        The graph corresponding to the lines in network text format.
+    """
+    from itertools import chain
+    from typing import Any, NamedTuple
+
+    class ParseStackFrame(NamedTuple):
+        node: Any
+        indent: int
+        has_vertical_child: int | None
+
+    initial_line_iter = iter(lines)
+
+    is_ascii = None
+    is_directed = None
+
+    ##############
+    # Initial Pass
+    ##############
+
+    # Do an initial pass over the lines to determine what type of graph it is.
+    # Remember what these lines were, so we can reiterate over them in the
+    # parsing pass.
+    initial_lines = []
+    try:
+        first_line = next(initial_line_iter)
+    except StopIteration:
+        ...
+    else:
+        initial_lines.append(first_line)
+        # The first character indicates if it is an ASCII or UTF graph
+        first_char = first_line[0]
+        if first_char in {
+            UtfBaseGlyphs.empty,
+            UtfBaseGlyphs.newtree_mid[0],
+            UtfBaseGlyphs.newtree_last[0],
+        }:
+            is_ascii = False
+        elif first_char in {
+            AsciiBaseGlyphs.empty,
+            AsciiBaseGlyphs.newtree_mid[0],
+            AsciiBaseGlyphs.newtree_last[0],
+        }:
+            is_ascii = True
+        else:
+            raise AssertionError(f"Unexpected first character: {first_char}")
+
+    if is_ascii:
+        directed_glyphs = AsciiDirectedGlyphs.as_dict()
+        undirected_glyphs = AsciiUndirectedGlyphs.as_dict()
+    else:
+        directed_glyphs = UtfDirectedGlyphs.as_dict()
+        undirected_glyphs = UtfUndirectedGlyphs.as_dict()
+
+    # For both directed / undirected glyphs, determine which glyphs never
+    # appear as substrings in the other undirected / directed glyphs.  Glyphs
+    # with this property unambiguously indicates if a graph is directed /
+    # undirected.
+    directed_items = set(directed_glyphs.values())
+    undirected_items = set(undirected_glyphs.values())
+    unambiguous_directed_items = []
+    for item in directed_items:
+        other_items = undirected_items
+        other_supersets = [other for other in other_items if item in other]
+        if not other_supersets:
+            unambiguous_directed_items.append(item)
+    unambiguous_undirected_items = []
+    for item in undirected_items:
+        other_items = directed_items
+        other_supersets = [other for other in other_items if item in other]
+        if not other_supersets:
+            unambiguous_undirected_items.append(item)
+
+    for line in initial_line_iter:
+        initial_lines.append(line)
+        if any(item in line for item in unambiguous_undirected_items):
+            is_directed = False
+            break
+        elif any(item in line for item in unambiguous_directed_items):
+            is_directed = True
+            break
+
+    if is_directed is None:
+        # Not enough information to determine, choose undirected by default
+        is_directed = False
+
+    glyphs = directed_glyphs if is_directed else undirected_glyphs
+
+    # the backedge symbol by itself can be ambiguous, but with spaces around it
+    # becomes unambiguous.
+    backedge_symbol = " " + glyphs["backedge"] + " "
+
+    # Reconstruct an iterator over all of the lines.
+    parsing_line_iter = chain(initial_lines, initial_line_iter)
+
+    ##############
+    # Parsing Pass
+    ##############
+
+    edges = []
+    nodes = []
+    is_empty = None
+
+    noparent = object()  # sentinel value
+
+    # keep a stack of previous nodes that could be parents of subsequent nodes
+    stack = [ParseStackFrame(noparent, -1, None)]
+
+    for line in parsing_line_iter:
+        if line == glyphs["empty"]:
+            # If the line is the empty glyph, we are done.
+            # There shouldn't be anything else after this.
+            is_empty = True
+            continue
+
+        if backedge_symbol in line:
+            # This line has one or more backedges, separate those out
+            node_part, backedge_part = line.split(backedge_symbol)
+            backedge_nodes = [u.strip() for u in backedge_part.split(", ")]
+            # Now the node can be parsed
+            node_part = node_part.rstrip()
+            prefix, node = node_part.rsplit(" ", 1)
+            node = node.strip()
+            # Add the backedges to the edge list
+            edges.extend([(u, node) for u in backedge_nodes])
+        else:
+            # No backedge, the tail of this line is the node
+            prefix, node = line.rsplit(" ", 1)
+            node = node.strip()
+
+        prev = stack.pop()
+
+        if node in glyphs["vertical_edge"]:
+            # Previous node is still the previous node, but we know it will
+            # have exactly one child, which will need to have its nesting level
+            # adjusted.
+            modified_prev = ParseStackFrame(
+                prev.node,
+                prev.indent,
+                True,
+            )
+            stack.append(modified_prev)
+            continue
+
+        # The length of the string before the node characters give us a hint
+        # about our nesting level. The only case where this doesn't work is
+        # when there are vertical chains, which is handled explicitly.
+        indent = len(prefix)
+        curr = ParseStackFrame(node, indent, None)
+
+        if prev.has_vertical_child:
+            # In this case we know prev must be the parent of our current line,
+            # so we don't have to search the stack. (which is good because the
+            # indentation check wouldn't work in this case).
+            ...
+        else:
+            # If the previous node nesting-level is greater than the current
+            # nodes nesting-level than the previous node was the end of a path,
+            # and is not our parent. We can safely pop nodes off the stack
+            # until we find one with a comparable nesting-level, which is our
+            # parent.
+            while curr.indent <= prev.indent:
+                prev = stack.pop()
+
+        if node == "...":
+            # The current previous node is no longer a valid parent,
+            # keep it popped from the stack.
+            stack.append(prev)
+        else:
+            # The previous and current nodes may still be parents, so add them
+            # back onto the stack.
+            stack.append(prev)
+            stack.append(curr)
+
+            # Add the node and the edge to its parent to the node / edge lists.
+            nodes.append(curr.node)
+            if prev.node is not noparent:
+                edges.append((prev.node, curr.node))
+
+    if is_empty:
+        # Sanity check
+        assert len(nodes) == 0
+
+    # Reconstruct the graph
+    cls = nx.DiGraph if is_directed else nx.Graph
+    new = cls()
+    new.add_nodes_from(nodes)
+    new.add_edges_from(edges)
+    return new
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..25cba24b1580e95dc4f9ea3a449954f1e4d8eb58
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_all_random_functions.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_all_random_functions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..641eaf0b55f1f29fecc78549ca64670bafb6905f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_all_random_functions.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_convert.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_convert.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9a8d1303f0c627488b26f9ea02128fe731e7ed9a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_convert.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_convert_numpy.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_convert_numpy.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b52e4160c0b4988233da2d1debfe07936ccdeb55
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_convert_numpy.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_convert_pandas.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_convert_pandas.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e88f0872ab0be99dcf2b9c4fcb29b8d2c84babf0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_convert_pandas.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_convert_scipy.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_convert_scipy.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d6ba67afca8992335a785b583f9f6821ed5cd955
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_convert_scipy.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_exceptions.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_exceptions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..806d6426d29532c11c21cc176c981fd4b1f56cbf
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_exceptions.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_import.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_import.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c6e1ecac75e7d26d3af88f0316fd10de04c0a55c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_import.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_lazy_imports.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_lazy_imports.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..528c615ddec9f5f9f349176978c523167df2417c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_lazy_imports.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_relabel.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_relabel.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..269ede3016df53718924fc3c65f1d16a63d4de52
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_relabel.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_removed_functions_exception_messages.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_removed_functions_exception_messages.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..12d3e7c3ac7c53d786538d2db49bef68ea71a8f3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/__pycache__/test_removed_functions_exception_messages.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_all_random_functions.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_all_random_functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb3a73d0666b01bd1a90a4759670f912590aaf6b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_all_random_functions.py
@@ -0,0 +1,248 @@
+import random
+
+import pytest
+
+import networkx as nx
+from networkx.algorithms import approximation as approx
+from networkx.algorithms import threshold
+
+np = pytest.importorskip("numpy")
+
+progress = 0
+
+# store the random numbers after setting a global seed
+np.random.seed(42)
+np_rv = np.random.rand()
+random.seed(42)
+py_rv = random.random()
+
+
+def t(f, *args, **kwds):
+    """call one function and check if global RNG changed"""
+    global progress
+    progress += 1
+    print(progress, ",", end="")
+
+    f(*args, **kwds)
+
+    after_np_rv = np.random.rand()
+    # if np_rv != after_np_rv:
+    #    print(np_rv, after_np_rv, "don't match np!")
+    assert np_rv == after_np_rv
+    np.random.seed(42)
+
+    after_py_rv = random.random()
+    # if py_rv != after_py_rv:
+    #    print(py_rv, after_py_rv, "don't match py!")
+    assert py_rv == after_py_rv
+    random.seed(42)
+
+
+def run_all_random_functions(seed):
+    n = 20
+    m = 10
+    k = l = 2
+    s = v = 10
+    p = q = p1 = p2 = p_in = p_out = 0.4
+    alpha = radius = theta = 0.75
+    sizes = (20, 20, 10)
+    colors = [1, 2, 3]
+    G = nx.barbell_graph(12, 20)
+    H = nx.cycle_graph(3)
+    H.add_weighted_edges_from((u, v, 0.2) for u, v in H.edges)
+    deg_sequence = [3, 2, 1, 3, 2, 1, 3, 2, 1, 2, 1, 2, 1]
+    in_degree_sequence = w = sequence = aseq = bseq = deg_sequence
+
+    # print("starting...")
+    t(nx.maximal_independent_set, G, seed=seed)
+    t(nx.rich_club_coefficient, G, seed=seed, normalized=False)
+    t(nx.random_reference, G, seed=seed)
+    t(nx.lattice_reference, G, seed=seed)
+    t(nx.sigma, G, 1, 2, seed=seed)
+    t(nx.omega, G, 1, 2, seed=seed)
+    # print("out of smallworld.py")
+    t(nx.double_edge_swap, G, seed=seed)
+    # print("starting connected_double_edge_swap")
+    t(nx.connected_double_edge_swap, nx.complete_graph(9), seed=seed)
+    # print("ending connected_double_edge_swap")
+    t(nx.random_layout, G, seed=seed)
+    t(nx.fruchterman_reingold_layout, G, seed=seed)
+    t(nx.algebraic_connectivity, G, seed=seed)
+    t(nx.fiedler_vector, G, seed=seed)
+    t(nx.spectral_ordering, G, seed=seed)
+    # print('starting average_clustering')
+    t(approx.average_clustering, G, seed=seed)
+    t(approx.simulated_annealing_tsp, H, "greedy", source=1, seed=seed)
+    t(approx.threshold_accepting_tsp, H, "greedy", source=1, seed=seed)
+    t(
+        approx.traveling_salesman_problem,
+        H,
+        method=lambda G, weight: approx.simulated_annealing_tsp(
+            G, "greedy", weight, seed=seed
+        ),
+    )
+    t(
+        approx.traveling_salesman_problem,
+        H,
+        method=lambda G, weight: approx.threshold_accepting_tsp(
+            G, "greedy", weight, seed=seed
+        ),
+    )
+    t(nx.betweenness_centrality, G, seed=seed)
+    t(nx.edge_betweenness_centrality, G, seed=seed)
+    t(nx.approximate_current_flow_betweenness_centrality, G, seed=seed)
+    # print("kernighan")
+    t(nx.algorithms.community.kernighan_lin_bisection, G, seed=seed)
+    # nx.algorithms.community.asyn_lpa_communities(G, seed=seed)
+    t(nx.algorithms.tree.greedy_branching, G, seed=seed)
+    # print('done with graph argument functions')
+
+    t(nx.spectral_graph_forge, G, alpha, seed=seed)
+    t(nx.algorithms.community.asyn_fluidc, G, k, max_iter=1, seed=seed)
+    t(
+        nx.algorithms.connectivity.edge_augmentation.greedy_k_edge_augmentation,
+        G,
+        k,
+        seed=seed,
+    )
+    t(nx.algorithms.coloring.strategy_random_sequential, G, colors, seed=seed)
+
+    t(nx.configuration_model, deg_sequence, seed=seed)
+    t(
+        nx.directed_configuration_model,
+        in_degree_sequence,
+        in_degree_sequence,
+        seed=seed,
+    )
+    t(nx.expected_degree_graph, w, seed=seed)
+    t(nx.random_degree_sequence_graph, sequence, seed=seed)
+    joint_degrees = {
+        1: {4: 1},
+        2: {2: 2, 3: 2, 4: 2},
+        3: {2: 2, 4: 1},
+        4: {1: 1, 2: 2, 3: 1},
+    }
+    t(nx.joint_degree_graph, joint_degrees, seed=seed)
+    joint_degree_sequence = [
+        (1, 0),
+        (1, 0),
+        (1, 0),
+        (2, 0),
+        (1, 0),
+        (2, 1),
+        (0, 1),
+        (0, 1),
+    ]
+    t(nx.random_clustered_graph, joint_degree_sequence, seed=seed)
+    constructor = [(3, 3, 0.5), (10, 10, 0.7)]
+    t(nx.random_shell_graph, constructor, seed=seed)
+    mapping = {1: 0.4, 2: 0.3, 3: 0.3}
+    t(nx.utils.random_weighted_sample, mapping, k, seed=seed)
+    t(nx.utils.weighted_choice, mapping, seed=seed)
+    t(nx.algorithms.bipartite.configuration_model, aseq, bseq, seed=seed)
+    t(nx.algorithms.bipartite.preferential_attachment_graph, aseq, p, seed=seed)
+
+    def kernel_integral(u, w, z):
+        return z - w
+
+    t(nx.random_kernel_graph, n, kernel_integral, seed=seed)
+
+    sizes = [75, 75, 300]
+    probs = [[0.25, 0.05, 0.02], [0.05, 0.35, 0.07], [0.02, 0.07, 0.40]]
+    t(nx.stochastic_block_model, sizes, probs, seed=seed)
+    t(nx.random_partition_graph, sizes, p_in, p_out, seed=seed)
+
+    # print("starting generator functions")
+    t(threshold.random_threshold_sequence, n, p, seed=seed)
+    t(nx.tournament.random_tournament, n, seed=seed)
+    t(nx.relaxed_caveman_graph, l, k, p, seed=seed)
+    t(nx.planted_partition_graph, l, k, p_in, p_out, seed=seed)
+    t(nx.gaussian_random_partition_graph, n, s, v, p_in, p_out, seed=seed)
+    t(nx.gn_graph, n, seed=seed)
+    t(nx.gnr_graph, n, p, seed=seed)
+    t(nx.gnc_graph, n, seed=seed)
+    t(nx.scale_free_graph, n, seed=seed)
+    t(nx.directed.random_uniform_k_out_graph, n, k, seed=seed)
+    t(nx.random_k_out_graph, n, k, alpha, seed=seed)
+    N = 1000
+    t(nx.partial_duplication_graph, N, n, p, q, seed=seed)
+    t(nx.duplication_divergence_graph, n, p, seed=seed)
+    t(nx.random_geometric_graph, n, radius, seed=seed)
+    t(nx.soft_random_geometric_graph, n, radius, seed=seed)
+    t(nx.geographical_threshold_graph, n, theta, seed=seed)
+    t(nx.waxman_graph, n, seed=seed)
+    t(nx.navigable_small_world_graph, n, seed=seed)
+    t(nx.thresholded_random_geometric_graph, n, radius, theta, seed=seed)
+    t(nx.uniform_random_intersection_graph, n, m, p, seed=seed)
+    t(nx.k_random_intersection_graph, n, m, k, seed=seed)
+
+    t(nx.general_random_intersection_graph, n, 2, [0.1, 0.5], seed=seed)
+    t(nx.fast_gnp_random_graph, n, p, seed=seed)
+    t(nx.gnp_random_graph, n, p, seed=seed)
+    t(nx.dense_gnm_random_graph, n, m, seed=seed)
+    t(nx.gnm_random_graph, n, m, seed=seed)
+    t(nx.newman_watts_strogatz_graph, n, k, p, seed=seed)
+    t(nx.watts_strogatz_graph, n, k, p, seed=seed)
+    t(nx.connected_watts_strogatz_graph, n, k, p, seed=seed)
+    t(nx.random_regular_graph, 3, n, seed=seed)
+    t(nx.barabasi_albert_graph, n, m, seed=seed)
+    t(nx.extended_barabasi_albert_graph, n, m, p, q, seed=seed)
+    t(nx.powerlaw_cluster_graph, n, m, p, seed=seed)
+    t(nx.random_lobster_graph, n, p1, p2, seed=seed)
+    t(nx.random_powerlaw_tree, 5, seed=seed, tries=5000)
+    t(nx.random_powerlaw_tree_sequence, 5, seed=seed, tries=5000)
+    t(nx.random_labeled_tree, n, seed=seed)
+    t(nx.utils.powerlaw_sequence, n, seed=seed)
+    t(nx.utils.zipf_rv, 2.3, seed=seed)
+    cdist = [0.2, 0.4, 0.5, 0.7, 0.9, 1.0]
+    t(nx.utils.discrete_sequence, n, cdistribution=cdist, seed=seed)
+    t(nx.algorithms.bipartite.random_graph, n, m, p, seed=seed)
+    t(nx.algorithms.bipartite.gnmk_random_graph, n, m, k, seed=seed)
+    LFR = nx.generators.LFR_benchmark_graph
+    t(
+        LFR,
+        25,
+        3,
+        1.5,
+        0.1,
+        average_degree=3,
+        min_community=10,
+        seed=seed,
+        max_community=20,
+    )
+    t(nx.random_internet_as_graph, n, seed=seed)
+    # print("done")
+
+
+# choose to test an integer seed, or whether a single RNG can be everywhere
+# np_rng = np.random.RandomState(14)
+# seed = np_rng
+# seed = 14
+
+
+@pytest.mark.slow
+# print("NetworkX Version:", nx.__version__)
+def test_rng_interface():
+    global progress
+
+    # try different kinds of seeds
+    for seed in [14, np.random.RandomState(14)]:
+        np.random.seed(42)
+        random.seed(42)
+        run_all_random_functions(seed)
+        progress = 0
+
+        # check that both global RNGs are unaffected
+        after_np_rv = np.random.rand()
+        #        if np_rv != after_np_rv:
+        #            print(np_rv, after_np_rv, "don't match np!")
+        assert np_rv == after_np_rv
+        after_py_rv = random.random()
+        #        if py_rv != after_py_rv:
+        #            print(py_rv, after_py_rv, "don't match py!")
+        assert py_rv == after_py_rv
+
+
+#        print("\nDone testing seed:", seed)
+
+# test_rng_interface()
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_convert.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_convert.py
new file mode 100644
index 0000000000000000000000000000000000000000..44bed9438945a39bb5eb85477301f58cfcd70cf0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_convert.py
@@ -0,0 +1,321 @@
+import pytest
+
+import networkx as nx
+from networkx.convert import (
+    from_dict_of_dicts,
+    from_dict_of_lists,
+    to_dict_of_dicts,
+    to_dict_of_lists,
+    to_networkx_graph,
+)
+from networkx.generators.classic import barbell_graph, cycle_graph
+from networkx.utils import edges_equal, graphs_equal, nodes_equal
+
+
+class TestConvert:
+    def edgelists_equal(self, e1, e2):
+        return sorted(sorted(e) for e in e1) == sorted(sorted(e) for e in e2)
+
+    def test_simple_graphs(self):
+        for dest, source in [
+            (to_dict_of_dicts, from_dict_of_dicts),
+            (to_dict_of_lists, from_dict_of_lists),
+        ]:
+            G = barbell_graph(10, 3)
+            G.graph = {}
+            dod = dest(G)
+
+            # Dict of [dicts, lists]
+            GG = source(dod)
+            assert graphs_equal(G, GG)
+            GW = to_networkx_graph(dod)
+            assert graphs_equal(G, GW)
+            GI = nx.Graph(dod)
+            assert graphs_equal(G, GI)
+
+            # With nodelist keyword
+            P4 = nx.path_graph(4)
+            P3 = nx.path_graph(3)
+            P4.graph = {}
+            P3.graph = {}
+            dod = dest(P4, nodelist=[0, 1, 2])
+            Gdod = nx.Graph(dod)
+            assert graphs_equal(Gdod, P3)
+
+    def test_exceptions(self):
+        # NX graph
+        class G:
+            adj = None
+
+        pytest.raises(nx.NetworkXError, to_networkx_graph, G)
+
+        # pygraphviz  agraph
+        class G:
+            is_strict = None
+
+        pytest.raises(nx.NetworkXError, to_networkx_graph, G)
+
+        # Dict of [dicts, lists]
+        G = {"a": 0}
+        pytest.raises(TypeError, to_networkx_graph, G)
+
+        # list or generator of edges
+        class G:
+            next = None
+
+        pytest.raises(nx.NetworkXError, to_networkx_graph, G)
+
+        # no match
+        pytest.raises(nx.NetworkXError, to_networkx_graph, "a")
+
+    def test_digraphs(self):
+        for dest, source in [
+            (to_dict_of_dicts, from_dict_of_dicts),
+            (to_dict_of_lists, from_dict_of_lists),
+        ]:
+            G = cycle_graph(10)
+
+            # Dict of [dicts, lists]
+            dod = dest(G)
+            GG = source(dod)
+            assert nodes_equal(sorted(G.nodes()), sorted(GG.nodes()))
+            assert edges_equal(sorted(G.edges()), sorted(GG.edges()))
+            GW = to_networkx_graph(dod)
+            assert nodes_equal(sorted(G.nodes()), sorted(GW.nodes()))
+            assert edges_equal(sorted(G.edges()), sorted(GW.edges()))
+            GI = nx.Graph(dod)
+            assert nodes_equal(sorted(G.nodes()), sorted(GI.nodes()))
+            assert edges_equal(sorted(G.edges()), sorted(GI.edges()))
+
+            G = cycle_graph(10, create_using=nx.DiGraph)
+            dod = dest(G)
+            GG = source(dod, create_using=nx.DiGraph)
+            assert sorted(G.nodes()) == sorted(GG.nodes())
+            assert sorted(G.edges()) == sorted(GG.edges())
+            GW = to_networkx_graph(dod, create_using=nx.DiGraph)
+            assert sorted(G.nodes()) == sorted(GW.nodes())
+            assert sorted(G.edges()) == sorted(GW.edges())
+            GI = nx.DiGraph(dod)
+            assert sorted(G.nodes()) == sorted(GI.nodes())
+            assert sorted(G.edges()) == sorted(GI.edges())
+
+    def test_graph(self):
+        g = nx.cycle_graph(10)
+        G = nx.Graph()
+        G.add_nodes_from(g)
+        G.add_weighted_edges_from((u, v, u) for u, v in g.edges())
+
+        # Dict of dicts
+        dod = to_dict_of_dicts(G)
+        GG = from_dict_of_dicts(dod, create_using=nx.Graph)
+        assert nodes_equal(sorted(G.nodes()), sorted(GG.nodes()))
+        assert edges_equal(sorted(G.edges()), sorted(GG.edges()))
+        GW = to_networkx_graph(dod, create_using=nx.Graph)
+        assert nodes_equal(sorted(G.nodes()), sorted(GW.nodes()))
+        assert edges_equal(sorted(G.edges()), sorted(GW.edges()))
+        GI = nx.Graph(dod)
+        assert sorted(G.nodes()) == sorted(GI.nodes())
+        assert sorted(G.edges()) == sorted(GI.edges())
+
+        # Dict of lists
+        dol = to_dict_of_lists(G)
+        GG = from_dict_of_lists(dol, create_using=nx.Graph)
+        # dict of lists throws away edge data so set it to none
+        enone = [(u, v, {}) for (u, v, d) in G.edges(data=True)]
+        assert nodes_equal(sorted(G.nodes()), sorted(GG.nodes()))
+        assert edges_equal(enone, sorted(GG.edges(data=True)))
+        GW = to_networkx_graph(dol, create_using=nx.Graph)
+        assert nodes_equal(sorted(G.nodes()), sorted(GW.nodes()))
+        assert edges_equal(enone, sorted(GW.edges(data=True)))
+        GI = nx.Graph(dol)
+        assert nodes_equal(sorted(G.nodes()), sorted(GI.nodes()))
+        assert edges_equal(enone, sorted(GI.edges(data=True)))
+
+    def test_with_multiedges_self_loops(self):
+        G = cycle_graph(10)
+        XG = nx.Graph()
+        XG.add_nodes_from(G)
+        XG.add_weighted_edges_from((u, v, u) for u, v in G.edges())
+        XGM = nx.MultiGraph()
+        XGM.add_nodes_from(G)
+        XGM.add_weighted_edges_from((u, v, u) for u, v in G.edges())
+        XGM.add_edge(0, 1, weight=2)  # multiedge
+        XGS = nx.Graph()
+        XGS.add_nodes_from(G)
+        XGS.add_weighted_edges_from((u, v, u) for u, v in G.edges())
+        XGS.add_edge(0, 0, weight=100)  # self loop
+
+        # Dict of dicts
+        # with self loops, OK
+        dod = to_dict_of_dicts(XGS)
+        GG = from_dict_of_dicts(dod, create_using=nx.Graph)
+        assert nodes_equal(XGS.nodes(), GG.nodes())
+        assert edges_equal(XGS.edges(), GG.edges())
+        GW = to_networkx_graph(dod, create_using=nx.Graph)
+        assert nodes_equal(XGS.nodes(), GW.nodes())
+        assert edges_equal(XGS.edges(), GW.edges())
+        GI = nx.Graph(dod)
+        assert nodes_equal(XGS.nodes(), GI.nodes())
+        assert edges_equal(XGS.edges(), GI.edges())
+
+        # Dict of lists
+        # with self loops, OK
+        dol = to_dict_of_lists(XGS)
+        GG = from_dict_of_lists(dol, create_using=nx.Graph)
+        # dict of lists throws away edge data so set it to none
+        enone = [(u, v, {}) for (u, v, d) in XGS.edges(data=True)]
+        assert nodes_equal(sorted(XGS.nodes()), sorted(GG.nodes()))
+        assert edges_equal(enone, sorted(GG.edges(data=True)))
+        GW = to_networkx_graph(dol, create_using=nx.Graph)
+        assert nodes_equal(sorted(XGS.nodes()), sorted(GW.nodes()))
+        assert edges_equal(enone, sorted(GW.edges(data=True)))
+        GI = nx.Graph(dol)
+        assert nodes_equal(sorted(XGS.nodes()), sorted(GI.nodes()))
+        assert edges_equal(enone, sorted(GI.edges(data=True)))
+
+        # Dict of dicts
+        # with multiedges, OK
+        dod = to_dict_of_dicts(XGM)
+        GG = from_dict_of_dicts(dod, create_using=nx.MultiGraph, multigraph_input=True)
+        assert nodes_equal(sorted(XGM.nodes()), sorted(GG.nodes()))
+        assert edges_equal(sorted(XGM.edges()), sorted(GG.edges()))
+        GW = to_networkx_graph(dod, create_using=nx.MultiGraph, multigraph_input=True)
+        assert nodes_equal(sorted(XGM.nodes()), sorted(GW.nodes()))
+        assert edges_equal(sorted(XGM.edges()), sorted(GW.edges()))
+        GI = nx.MultiGraph(dod)
+        assert nodes_equal(sorted(XGM.nodes()), sorted(GI.nodes()))
+        assert sorted(XGM.edges()) == sorted(GI.edges())
+        GE = from_dict_of_dicts(dod, create_using=nx.MultiGraph, multigraph_input=False)
+        assert nodes_equal(sorted(XGM.nodes()), sorted(GE.nodes()))
+        assert sorted(XGM.edges()) != sorted(GE.edges())
+        GI = nx.MultiGraph(XGM)
+        assert nodes_equal(sorted(XGM.nodes()), sorted(GI.nodes()))
+        assert edges_equal(sorted(XGM.edges()), sorted(GI.edges()))
+        GM = nx.MultiGraph(G)
+        assert nodes_equal(sorted(GM.nodes()), sorted(G.nodes()))
+        assert edges_equal(sorted(GM.edges()), sorted(G.edges()))
+
+        # Dict of lists
+        # with multiedges, OK, but better write as DiGraph else you'll
+        # get double edges
+        dol = to_dict_of_lists(G)
+        GG = from_dict_of_lists(dol, create_using=nx.MultiGraph)
+        assert nodes_equal(sorted(G.nodes()), sorted(GG.nodes()))
+        assert edges_equal(sorted(G.edges()), sorted(GG.edges()))
+        GW = to_networkx_graph(dol, create_using=nx.MultiGraph)
+        assert nodes_equal(sorted(G.nodes()), sorted(GW.nodes()))
+        assert edges_equal(sorted(G.edges()), sorted(GW.edges()))
+        GI = nx.MultiGraph(dol)
+        assert nodes_equal(sorted(G.nodes()), sorted(GI.nodes()))
+        assert edges_equal(sorted(G.edges()), sorted(GI.edges()))
+
+    def test_edgelists(self):
+        P = nx.path_graph(4)
+        e = [(0, 1), (1, 2), (2, 3)]
+        G = nx.Graph(e)
+        assert nodes_equal(sorted(G.nodes()), sorted(P.nodes()))
+        assert edges_equal(sorted(G.edges()), sorted(P.edges()))
+        assert edges_equal(sorted(G.edges(data=True)), sorted(P.edges(data=True)))
+
+        e = [(0, 1, {}), (1, 2, {}), (2, 3, {})]
+        G = nx.Graph(e)
+        assert nodes_equal(sorted(G.nodes()), sorted(P.nodes()))
+        assert edges_equal(sorted(G.edges()), sorted(P.edges()))
+        assert edges_equal(sorted(G.edges(data=True)), sorted(P.edges(data=True)))
+
+        e = ((n, n + 1) for n in range(3))
+        G = nx.Graph(e)
+        assert nodes_equal(sorted(G.nodes()), sorted(P.nodes()))
+        assert edges_equal(sorted(G.edges()), sorted(P.edges()))
+        assert edges_equal(sorted(G.edges(data=True)), sorted(P.edges(data=True)))
+
+    def test_directed_to_undirected(self):
+        edges1 = [(0, 1), (1, 2), (2, 0)]
+        edges2 = [(0, 1), (1, 2), (0, 2)]
+        assert self.edgelists_equal(nx.Graph(nx.DiGraph(edges1)).edges(), edges1)
+        assert self.edgelists_equal(nx.Graph(nx.DiGraph(edges2)).edges(), edges1)
+        assert self.edgelists_equal(nx.MultiGraph(nx.DiGraph(edges1)).edges(), edges1)
+        assert self.edgelists_equal(nx.MultiGraph(nx.DiGraph(edges2)).edges(), edges1)
+
+        assert self.edgelists_equal(
+            nx.MultiGraph(nx.MultiDiGraph(edges1)).edges(), edges1
+        )
+        assert self.edgelists_equal(
+            nx.MultiGraph(nx.MultiDiGraph(edges2)).edges(), edges1
+        )
+
+        assert self.edgelists_equal(nx.Graph(nx.MultiDiGraph(edges1)).edges(), edges1)
+        assert self.edgelists_equal(nx.Graph(nx.MultiDiGraph(edges2)).edges(), edges1)
+
+    def test_attribute_dict_integrity(self):
+        # we must not replace dict-like graph data structures with dicts
+        G = nx.Graph()
+        G.add_nodes_from("abc")
+        H = to_networkx_graph(G, create_using=nx.Graph)
+        assert list(H.nodes) == list(G.nodes)
+        H = nx.DiGraph(G)
+        assert list(H.nodes) == list(G.nodes)
+
+    def test_to_edgelist(self):
+        G = nx.Graph([(1, 1)])
+        elist = nx.to_edgelist(G, nodelist=list(G))
+        assert edges_equal(G.edges(data=True), elist)
+
+    def test_custom_node_attr_dict_safekeeping(self):
+        class custom_dict(dict):
+            pass
+
+        class Custom(nx.Graph):
+            node_attr_dict_factory = custom_dict
+
+        g = nx.Graph()
+        g.add_node(1, weight=1)
+
+        h = Custom(g)
+        assert isinstance(g._node[1], dict)
+        assert isinstance(h._node[1], custom_dict)
+
+        # this raise exception
+        # h._node.update((n, dd.copy()) for n, dd in g.nodes.items())
+        # assert isinstance(h._node[1], custom_dict)
+
+
+@pytest.mark.parametrize(
+    "edgelist",
+    (
+        # Graph with no edge data
+        [(0, 1), (1, 2)],
+        # Graph with edge data
+        [(0, 1, {"weight": 1.0}), (1, 2, {"weight": 2.0})],
+    ),
+)
+def test_to_dict_of_dicts_with_edgedata_param(edgelist):
+    G = nx.Graph()
+    G.add_edges_from(edgelist)
+    # Innermost dict value == edge_data when edge_data != None.
+    # In the case when G has edge data, it is overwritten
+    expected = {0: {1: 10}, 1: {0: 10, 2: 10}, 2: {1: 10}}
+    assert nx.to_dict_of_dicts(G, edge_data=10) == expected
+
+
+def test_to_dict_of_dicts_with_edgedata_and_nodelist():
+    G = nx.path_graph(5)
+    nodelist = [2, 3, 4]
+    expected = {2: {3: 10}, 3: {2: 10, 4: 10}, 4: {3: 10}}
+    assert nx.to_dict_of_dicts(G, nodelist=nodelist, edge_data=10) == expected
+
+
+def test_to_dict_of_dicts_with_edgedata_multigraph():
+    """Multi edge data overwritten when edge_data != None"""
+    G = nx.MultiGraph()
+    G.add_edge(0, 1, key="a")
+    G.add_edge(0, 1, key="b")
+    # Multi edge data lost when edge_data is not None
+    expected = {0: {1: 10}, 1: {0: 10}}
+    assert nx.to_dict_of_dicts(G, edge_data=10) == expected
+
+
+def test_to_networkx_graph_non_edgelist():
+    invalid_edgelist = [1, 2, 3]
+    with pytest.raises(nx.NetworkXError, match="Input is not a valid edge list"):
+        nx.to_networkx_graph(invalid_edgelist)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_convert_numpy.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_convert_numpy.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a554fd4b2d5e00e69a0537fbd04e877a95b6593
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_convert_numpy.py
@@ -0,0 +1,531 @@
+import itertools
+
+import pytest
+
+import networkx as nx
+from networkx.utils import graphs_equal
+
+np = pytest.importorskip("numpy")
+npt = pytest.importorskip("numpy.testing")
+
+
+class TestConvertNumpyArray:
+    def setup_method(self):
+        self.G1 = nx.barbell_graph(10, 3)
+        self.G2 = nx.cycle_graph(10, create_using=nx.DiGraph)
+        self.G3 = self.create_weighted(nx.Graph())
+        self.G4 = self.create_weighted(nx.DiGraph())
+
+    def create_weighted(self, G):
+        g = nx.cycle_graph(4)
+        G.add_nodes_from(g)
+        G.add_weighted_edges_from((u, v, 10 + u) for u, v in g.edges())
+        return G
+
+    def assert_equal(self, G1, G2):
+        assert sorted(G1.nodes()) == sorted(G2.nodes())
+        assert sorted(G1.edges()) == sorted(G2.edges())
+
+    def identity_conversion(self, G, A, create_using):
+        assert A.sum() > 0
+        GG = nx.from_numpy_array(A, create_using=create_using)
+        self.assert_equal(G, GG)
+        GW = nx.to_networkx_graph(A, create_using=create_using)
+        self.assert_equal(G, GW)
+        GI = nx.empty_graph(0, create_using).__class__(A)
+        self.assert_equal(G, GI)
+
+    def test_shape(self):
+        "Conversion from non-square array."
+        A = np.array([[1, 2, 3], [4, 5, 6]])
+        pytest.raises(nx.NetworkXError, nx.from_numpy_array, A)
+
+    def test_identity_graph_array(self):
+        "Conversion from graph to array to graph."
+        A = nx.to_numpy_array(self.G1)
+        self.identity_conversion(self.G1, A, nx.Graph())
+
+    def test_identity_digraph_array(self):
+        """Conversion from digraph to array to digraph."""
+        A = nx.to_numpy_array(self.G2)
+        self.identity_conversion(self.G2, A, nx.DiGraph())
+
+    def test_identity_weighted_graph_array(self):
+        """Conversion from weighted graph to array to weighted graph."""
+        A = nx.to_numpy_array(self.G3)
+        self.identity_conversion(self.G3, A, nx.Graph())
+
+    def test_identity_weighted_digraph_array(self):
+        """Conversion from weighted digraph to array to weighted digraph."""
+        A = nx.to_numpy_array(self.G4)
+        self.identity_conversion(self.G4, A, nx.DiGraph())
+
+    def test_nodelist(self):
+        """Conversion from graph to array to graph with nodelist."""
+        P4 = nx.path_graph(4)
+        P3 = nx.path_graph(3)
+        nodelist = list(P3)
+        A = nx.to_numpy_array(P4, nodelist=nodelist)
+        GA = nx.Graph(A)
+        self.assert_equal(GA, P3)
+
+        # Make nodelist ambiguous by containing duplicates.
+        nodelist += [nodelist[0]]
+        pytest.raises(nx.NetworkXError, nx.to_numpy_array, P3, nodelist=nodelist)
+
+        # Make nodelist invalid by including nonexistent nodes
+        nodelist = [-1, 0, 1]
+        with pytest.raises(
+            nx.NetworkXError,
+            match=f"Nodes {nodelist - P3.nodes} in nodelist is not in G",
+        ):
+            nx.to_numpy_array(P3, nodelist=nodelist)
+
+    def test_weight_keyword(self):
+        WP4 = nx.Graph()
+        WP4.add_edges_from((n, n + 1, {"weight": 0.5, "other": 0.3}) for n in range(3))
+        P4 = nx.path_graph(4)
+        A = nx.to_numpy_array(P4)
+        np.testing.assert_equal(A, nx.to_numpy_array(WP4, weight=None))
+        np.testing.assert_equal(0.5 * A, nx.to_numpy_array(WP4))
+        np.testing.assert_equal(0.3 * A, nx.to_numpy_array(WP4, weight="other"))
+
+    def test_from_numpy_array_type(self):
+        A = np.array([[1]])
+        G = nx.from_numpy_array(A)
+        assert isinstance(G[0][0]["weight"], int)
+
+        A = np.array([[1]]).astype(float)
+        G = nx.from_numpy_array(A)
+        assert isinstance(G[0][0]["weight"], float)
+
+        A = np.array([[1]]).astype(str)
+        G = nx.from_numpy_array(A)
+        assert isinstance(G[0][0]["weight"], str)
+
+        A = np.array([[1]]).astype(bool)
+        G = nx.from_numpy_array(A)
+        assert isinstance(G[0][0]["weight"], bool)
+
+        A = np.array([[1]]).astype(complex)
+        G = nx.from_numpy_array(A)
+        assert isinstance(G[0][0]["weight"], complex)
+
+        A = np.array([[1]]).astype(object)
+        pytest.raises(TypeError, nx.from_numpy_array, A)
+
+        A = np.array([[[1, 1, 1], [1, 1, 1]], [[1, 1, 1], [1, 1, 1]]])
+        with pytest.raises(
+            nx.NetworkXError, match=f"Input array must be 2D, not {A.ndim}"
+        ):
+            g = nx.from_numpy_array(A)
+
+    def test_from_numpy_array_dtype(self):
+        dt = [("weight", float), ("cost", int)]
+        A = np.array([[(1.0, 2)]], dtype=dt)
+        G = nx.from_numpy_array(A)
+        assert isinstance(G[0][0]["weight"], float)
+        assert isinstance(G[0][0]["cost"], int)
+        assert G[0][0]["cost"] == 2
+        assert G[0][0]["weight"] == 1.0
+
+    def test_from_numpy_array_parallel_edges(self):
+        """Tests that the :func:`networkx.from_numpy_array` function
+        interprets integer weights as the number of parallel edges when
+        creating a multigraph.
+
+        """
+        A = np.array([[1, 1], [1, 2]])
+        # First, with a simple graph, each integer entry in the adjacency
+        # matrix is interpreted as the weight of a single edge in the graph.
+        expected = nx.DiGraph()
+        edges = [(0, 0), (0, 1), (1, 0)]
+        expected.add_weighted_edges_from([(u, v, 1) for (u, v) in edges])
+        expected.add_edge(1, 1, weight=2)
+        actual = nx.from_numpy_array(A, parallel_edges=True, create_using=nx.DiGraph)
+        assert graphs_equal(actual, expected)
+        actual = nx.from_numpy_array(A, parallel_edges=False, create_using=nx.DiGraph)
+        assert graphs_equal(actual, expected)
+        # Now each integer entry in the adjacency matrix is interpreted as the
+        # number of parallel edges in the graph if the appropriate keyword
+        # argument is specified.
+        edges = [(0, 0), (0, 1), (1, 0), (1, 1), (1, 1)]
+        expected = nx.MultiDiGraph()
+        expected.add_weighted_edges_from([(u, v, 1) for (u, v) in edges])
+        actual = nx.from_numpy_array(
+            A, parallel_edges=True, create_using=nx.MultiDiGraph
+        )
+        assert graphs_equal(actual, expected)
+        expected = nx.MultiDiGraph()
+        expected.add_edges_from(set(edges), weight=1)
+        # The sole self-loop (edge 0) on vertex 1 should have weight 2.
+        expected[1][1][0]["weight"] = 2
+        actual = nx.from_numpy_array(
+            A, parallel_edges=False, create_using=nx.MultiDiGraph
+        )
+        assert graphs_equal(actual, expected)
+
+    @pytest.mark.parametrize(
+        "dt",
+        (
+            None,  # default
+            int,  # integer dtype
+            np.dtype(
+                [("weight", "f8"), ("color", "i1")]
+            ),  # Structured dtype with named fields
+        ),
+    )
+    def test_from_numpy_array_no_edge_attr(self, dt):
+        A = np.array([[0, 1], [1, 0]], dtype=dt)
+        G = nx.from_numpy_array(A, edge_attr=None)
+        assert "weight" not in G.edges[0, 1]
+        assert len(G.edges[0, 1]) == 0
+
+    def test_from_numpy_array_multiedge_no_edge_attr(self):
+        A = np.array([[0, 2], [2, 0]])
+        G = nx.from_numpy_array(A, create_using=nx.MultiDiGraph, edge_attr=None)
+        assert all("weight" not in e for _, e in G[0][1].items())
+        assert len(G[0][1][0]) == 0
+
+    def test_from_numpy_array_custom_edge_attr(self):
+        A = np.array([[0, 2], [3, 0]])
+        G = nx.from_numpy_array(A, edge_attr="cost")
+        assert "weight" not in G.edges[0, 1]
+        assert G.edges[0, 1]["cost"] == 3
+
+    def test_symmetric(self):
+        """Tests that a symmetric array has edges added only once to an
+        undirected multigraph when using :func:`networkx.from_numpy_array`.
+
+        """
+        A = np.array([[0, 1], [1, 0]])
+        G = nx.from_numpy_array(A, create_using=nx.MultiGraph)
+        expected = nx.MultiGraph()
+        expected.add_edge(0, 1, weight=1)
+        assert graphs_equal(G, expected)
+
+    def test_dtype_int_graph(self):
+        """Test that setting dtype int actually gives an integer array.
+
+        For more information, see GitHub pull request #1363.
+
+        """
+        G = nx.complete_graph(3)
+        A = nx.to_numpy_array(G, dtype=int)
+        assert A.dtype == int
+
+    def test_dtype_int_multigraph(self):
+        """Test that setting dtype int actually gives an integer array.
+
+        For more information, see GitHub pull request #1363.
+
+        """
+        G = nx.MultiGraph(nx.complete_graph(3))
+        A = nx.to_numpy_array(G, dtype=int)
+        assert A.dtype == int
+
+
+@pytest.fixture
+def multigraph_test_graph():
+    G = nx.MultiGraph()
+    G.add_edge(1, 2, weight=7)
+    G.add_edge(1, 2, weight=70)
+    return G
+
+
+@pytest.mark.parametrize(("operator", "expected"), ((sum, 77), (min, 7), (max, 70)))
+def test_numpy_multigraph(multigraph_test_graph, operator, expected):
+    A = nx.to_numpy_array(multigraph_test_graph, multigraph_weight=operator)
+    assert A[1, 0] == expected
+
+
+def test_to_numpy_array_multigraph_nodelist(multigraph_test_graph):
+    G = multigraph_test_graph
+    G.add_edge(0, 1, weight=3)
+    A = nx.to_numpy_array(G, nodelist=[1, 2])
+    assert A.shape == (2, 2)
+    assert A[1, 0] == 77
+
+
+@pytest.mark.parametrize(
+    "G, expected",
+    [
+        (nx.Graph(), np.array([[0, 1 + 2j], [1 + 2j, 0]], dtype=complex)),
+        (nx.DiGraph(), np.array([[0, 1 + 2j], [0, 0]], dtype=complex)),
+    ],
+)
+def test_to_numpy_array_complex_weights(G, expected):
+    G.add_edge(0, 1, weight=1 + 2j)
+    A = nx.to_numpy_array(G, dtype=complex)
+    npt.assert_array_equal(A, expected)
+
+
+def test_to_numpy_array_arbitrary_weights():
+    G = nx.DiGraph()
+    w = 922337203685477580102  # Out of range for int64
+    G.add_edge(0, 1, weight=922337203685477580102)  # val not representable by int64
+    A = nx.to_numpy_array(G, dtype=object)
+    expected = np.array([[0, w], [0, 0]], dtype=object)
+    npt.assert_array_equal(A, expected)
+
+    # Undirected
+    A = nx.to_numpy_array(G.to_undirected(), dtype=object)
+    expected = np.array([[0, w], [w, 0]], dtype=object)
+    npt.assert_array_equal(A, expected)
+
+
+@pytest.mark.parametrize(
+    "func, expected",
+    ((min, -1), (max, 10), (sum, 11), (np.mean, 11 / 3), (np.median, 2)),
+)
+def test_to_numpy_array_multiweight_reduction(func, expected):
+    """Test various functions for reducing multiedge weights."""
+    G = nx.MultiDiGraph()
+    weights = [-1, 2, 10.0]
+    for w in weights:
+        G.add_edge(0, 1, weight=w)
+    A = nx.to_numpy_array(G, multigraph_weight=func, dtype=float)
+    assert np.allclose(A, [[0, expected], [0, 0]])
+
+    # Undirected case
+    A = nx.to_numpy_array(G.to_undirected(), multigraph_weight=func, dtype=float)
+    assert np.allclose(A, [[0, expected], [expected, 0]])
+
+
+@pytest.mark.parametrize(
+    ("G, expected"),
+    [
+        (nx.Graph(), [[(0, 0), (10, 5)], [(10, 5), (0, 0)]]),
+        (nx.DiGraph(), [[(0, 0), (10, 5)], [(0, 0), (0, 0)]]),
+    ],
+)
+def test_to_numpy_array_structured_dtype_attrs_from_fields(G, expected):
+    """When `dtype` is structured (i.e. has names) and `weight` is None, use
+    the named fields of the dtype to look up edge attributes."""
+    G.add_edge(0, 1, weight=10, cost=5.0)
+    dtype = np.dtype([("weight", int), ("cost", int)])
+    A = nx.to_numpy_array(G, dtype=dtype, weight=None)
+    expected = np.asarray(expected, dtype=dtype)
+    npt.assert_array_equal(A, expected)
+
+
+def test_to_numpy_array_structured_dtype_single_attr_default():
+    G = nx.path_graph(3)
+    dtype = np.dtype([("weight", float)])  # A single named field
+    A = nx.to_numpy_array(G, dtype=dtype, weight=None)
+    expected = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]], dtype=float)
+    npt.assert_array_equal(A["weight"], expected)
+
+
+@pytest.mark.parametrize(
+    ("field_name", "expected_attr_val"),
+    [
+        ("weight", 1),
+        ("cost", 3),
+    ],
+)
+def test_to_numpy_array_structured_dtype_single_attr(field_name, expected_attr_val):
+    G = nx.Graph()
+    G.add_edge(0, 1, cost=3)
+    dtype = np.dtype([(field_name, float)])
+    A = nx.to_numpy_array(G, dtype=dtype, weight=None)
+    expected = np.array([[0, expected_attr_val], [expected_attr_val, 0]], dtype=float)
+    npt.assert_array_equal(A[field_name], expected)
+
+
+@pytest.mark.parametrize("graph_type", (nx.Graph, nx.DiGraph))
+@pytest.mark.parametrize(
+    "edge",
+    [
+        (0, 1),  # No edge attributes
+        (0, 1, {"weight": 10}),  # One edge attr
+        (0, 1, {"weight": 5, "flow": -4}),  # Multiple but not all edge attrs
+        (0, 1, {"weight": 2.0, "cost": 10, "flow": -45}),  # All attrs
+    ],
+)
+def test_to_numpy_array_structured_dtype_multiple_fields(graph_type, edge):
+    G = graph_type([edge])
+    dtype = np.dtype([("weight", float), ("cost", float), ("flow", float)])
+    A = nx.to_numpy_array(G, dtype=dtype, weight=None)
+    for attr in dtype.names:
+        expected = nx.to_numpy_array(G, dtype=float, weight=attr)
+        npt.assert_array_equal(A[attr], expected)
+
+
+@pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph()))
+def test_to_numpy_array_structured_dtype_scalar_nonedge(G):
+    G.add_edge(0, 1, weight=10)
+    dtype = np.dtype([("weight", float), ("cost", float)])
+    A = nx.to_numpy_array(G, dtype=dtype, weight=None, nonedge=np.nan)
+    for attr in dtype.names:
+        expected = nx.to_numpy_array(G, dtype=float, weight=attr, nonedge=np.nan)
+        npt.assert_array_equal(A[attr], expected)
+
+
+@pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph()))
+def test_to_numpy_array_structured_dtype_nonedge_ary(G):
+    """Similar to the scalar case, except has a different non-edge value for
+    each named field."""
+    G.add_edge(0, 1, weight=10)
+    dtype = np.dtype([("weight", float), ("cost", float)])
+    nonedges = np.array([(0, np.inf)], dtype=dtype)
+    A = nx.to_numpy_array(G, dtype=dtype, weight=None, nonedge=nonedges)
+    for attr in dtype.names:
+        nonedge = nonedges[attr]
+        expected = nx.to_numpy_array(G, dtype=float, weight=attr, nonedge=nonedge)
+        npt.assert_array_equal(A[attr], expected)
+
+
+def test_to_numpy_array_structured_dtype_with_weight_raises():
+    """Using both a structured dtype (with named fields) and specifying a `weight`
+    parameter is ambiguous."""
+    G = nx.path_graph(3)
+    dtype = np.dtype([("weight", int), ("cost", int)])
+    exception_msg = "Specifying `weight` not supported for structured dtypes"
+    with pytest.raises(ValueError, match=exception_msg):
+        nx.to_numpy_array(G, dtype=dtype)  # Default is weight="weight"
+    with pytest.raises(ValueError, match=exception_msg):
+        nx.to_numpy_array(G, dtype=dtype, weight="cost")
+
+
+@pytest.mark.parametrize("graph_type", (nx.MultiGraph, nx.MultiDiGraph))
+def test_to_numpy_array_structured_multigraph_raises(graph_type):
+    G = nx.path_graph(3, create_using=graph_type)
+    dtype = np.dtype([("weight", int), ("cost", int)])
+    with pytest.raises(nx.NetworkXError, match="Structured arrays are not supported"):
+        nx.to_numpy_array(G, dtype=dtype, weight=None)
+
+
+def test_from_numpy_array_nodelist_bad_size():
+    """An exception is raised when `len(nodelist) != A.shape[0]`."""
+    n = 5  # Number of nodes
+    A = np.diag(np.ones(n - 1), k=1)  # Adj. matrix for P_n
+    expected = nx.path_graph(n)
+
+    assert graphs_equal(nx.from_numpy_array(A, edge_attr=None), expected)
+    nodes = list(range(n))
+    assert graphs_equal(
+        nx.from_numpy_array(A, edge_attr=None, nodelist=nodes), expected
+    )
+
+    # Too many node labels
+    nodes = list(range(n + 1))
+    with pytest.raises(ValueError, match="nodelist must have the same length as A"):
+        nx.from_numpy_array(A, nodelist=nodes)
+
+    # Too few node labels
+    nodes = list(range(n - 1))
+    with pytest.raises(ValueError, match="nodelist must have the same length as A"):
+        nx.from_numpy_array(A, nodelist=nodes)
+
+
+@pytest.mark.parametrize(
+    "nodes",
+    (
+        [4, 3, 2, 1, 0],
+        [9, 7, 1, 2, 8],
+        ["a", "b", "c", "d", "e"],
+        [(0, 0), (1, 1), (2, 3), (0, 2), (3, 1)],
+        ["A", 2, 7, "spam", (1, 3)],
+    ),
+)
+def test_from_numpy_array_nodelist(nodes):
+    A = np.diag(np.ones(4), k=1)
+    # Without edge attributes
+    expected = nx.relabel_nodes(
+        nx.path_graph(5), mapping=dict(enumerate(nodes)), copy=True
+    )
+    G = nx.from_numpy_array(A, edge_attr=None, nodelist=nodes)
+    assert graphs_equal(G, expected)
+
+    # With edge attributes
+    nx.set_edge_attributes(expected, 1.0, name="weight")
+    G = nx.from_numpy_array(A, nodelist=nodes)
+    assert graphs_equal(G, expected)
+
+
+@pytest.mark.parametrize(
+    "nodes",
+    (
+        [4, 3, 2, 1, 0],
+        [9, 7, 1, 2, 8],
+        ["a", "b", "c", "d", "e"],
+        [(0, 0), (1, 1), (2, 3), (0, 2), (3, 1)],
+        ["A", 2, 7, "spam", (1, 3)],
+    ),
+)
+def test_from_numpy_array_nodelist_directed(nodes):
+    A = np.diag(np.ones(4), k=1)
+    # Without edge attributes
+    H = nx.DiGraph([(0, 1), (1, 2), (2, 3), (3, 4)])
+    expected = nx.relabel_nodes(H, mapping=dict(enumerate(nodes)), copy=True)
+    G = nx.from_numpy_array(A, create_using=nx.DiGraph, edge_attr=None, nodelist=nodes)
+    assert graphs_equal(G, expected)
+
+    # With edge attributes
+    nx.set_edge_attributes(expected, 1.0, name="weight")
+    G = nx.from_numpy_array(A, create_using=nx.DiGraph, nodelist=nodes)
+    assert graphs_equal(G, expected)
+
+
+@pytest.mark.parametrize(
+    "nodes",
+    (
+        [4, 3, 2, 1, 0],
+        [9, 7, 1, 2, 8],
+        ["a", "b", "c", "d", "e"],
+        [(0, 0), (1, 1), (2, 3), (0, 2), (3, 1)],
+        ["A", 2, 7, "spam", (1, 3)],
+    ),
+)
+def test_from_numpy_array_nodelist_multigraph(nodes):
+    A = np.array(
+        [
+            [0, 1, 0, 0, 0],
+            [1, 0, 2, 0, 0],
+            [0, 2, 0, 3, 0],
+            [0, 0, 3, 0, 4],
+            [0, 0, 0, 4, 0],
+        ]
+    )
+
+    H = nx.MultiGraph()
+    for i, edge in enumerate(((0, 1), (1, 2), (2, 3), (3, 4))):
+        H.add_edges_from(itertools.repeat(edge, i + 1))
+    expected = nx.relabel_nodes(H, mapping=dict(enumerate(nodes)), copy=True)
+
+    G = nx.from_numpy_array(
+        A,
+        parallel_edges=True,
+        create_using=nx.MultiGraph,
+        edge_attr=None,
+        nodelist=nodes,
+    )
+    assert graphs_equal(G, expected)
+
+
+@pytest.mark.parametrize(
+    "nodes",
+    (
+        [4, 3, 2, 1, 0],
+        [9, 7, 1, 2, 8],
+        ["a", "b", "c", "d", "e"],
+        [(0, 0), (1, 1), (2, 3), (0, 2), (3, 1)],
+        ["A", 2, 7, "spam", (1, 3)],
+    ),
+)
+@pytest.mark.parametrize("graph", (nx.complete_graph, nx.cycle_graph, nx.wheel_graph))
+def test_from_numpy_array_nodelist_rountrip(graph, nodes):
+    G = graph(5)
+    A = nx.to_numpy_array(G)
+    expected = nx.relabel_nodes(G, mapping=dict(enumerate(nodes)), copy=True)
+    H = nx.from_numpy_array(A, edge_attr=None, nodelist=nodes)
+    assert graphs_equal(H, expected)
+
+    # With an isolated node
+    G = graph(4)
+    G.add_node("foo")
+    A = nx.to_numpy_array(G)
+    expected = nx.relabel_nodes(G, mapping=dict(zip(G.nodes, nodes)), copy=True)
+    H = nx.from_numpy_array(A, edge_attr=None, nodelist=nodes)
+    assert graphs_equal(H, expected)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_convert_pandas.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_convert_pandas.py
new file mode 100644
index 0000000000000000000000000000000000000000..eaa8d695f868dbb551d3a3819cedd590a25492f8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_convert_pandas.py
@@ -0,0 +1,349 @@
+import pytest
+
+import networkx as nx
+from networkx.utils import edges_equal, graphs_equal, nodes_equal
+
+np = pytest.importorskip("numpy")
+pd = pytest.importorskip("pandas")
+
+
+class TestConvertPandas:
+    def setup_method(self):
+        self.rng = np.random.RandomState(seed=5)
+        ints = self.rng.randint(1, 11, size=(3, 2))
+        a = ["A", "B", "C"]
+        b = ["D", "A", "E"]
+        df = pd.DataFrame(ints, columns=["weight", "cost"])
+        df[0] = a  # Column label 0 (int)
+        df["b"] = b  # Column label 'b' (str)
+        self.df = df
+
+        mdf = pd.DataFrame([[4, 16, "A", "D"]], columns=["weight", "cost", 0, "b"])
+        self.mdf = pd.concat([df, mdf])
+
+    def test_exceptions(self):
+        G = pd.DataFrame(["a"])  # adj
+        pytest.raises(nx.NetworkXError, nx.to_networkx_graph, G)
+        G = pd.DataFrame(["a", 0.0])  # elist
+        pytest.raises(nx.NetworkXError, nx.to_networkx_graph, G)
+        df = pd.DataFrame([[1, 1], [1, 0]], dtype=int, index=[1, 2], columns=["a", "b"])
+        pytest.raises(nx.NetworkXError, nx.from_pandas_adjacency, df)
+
+    def test_from_edgelist_all_attr(self):
+        Gtrue = nx.Graph(
+            [
+                ("E", "C", {"cost": 9, "weight": 10}),
+                ("B", "A", {"cost": 1, "weight": 7}),
+                ("A", "D", {"cost": 7, "weight": 4}),
+            ]
+        )
+        G = nx.from_pandas_edgelist(self.df, 0, "b", True)
+        assert graphs_equal(G, Gtrue)
+        # MultiGraph
+        MGtrue = nx.MultiGraph(Gtrue)
+        MGtrue.add_edge("A", "D", cost=16, weight=4)
+        MG = nx.from_pandas_edgelist(self.mdf, 0, "b", True, nx.MultiGraph())
+        assert graphs_equal(MG, MGtrue)
+
+    def test_from_edgelist_multi_attr(self):
+        Gtrue = nx.Graph(
+            [
+                ("E", "C", {"cost": 9, "weight": 10}),
+                ("B", "A", {"cost": 1, "weight": 7}),
+                ("A", "D", {"cost": 7, "weight": 4}),
+            ]
+        )
+        G = nx.from_pandas_edgelist(self.df, 0, "b", ["weight", "cost"])
+        assert graphs_equal(G, Gtrue)
+
+    def test_from_edgelist_multi_attr_incl_target(self):
+        Gtrue = nx.Graph(
+            [
+                ("E", "C", {0: "C", "b": "E", "weight": 10}),
+                ("B", "A", {0: "B", "b": "A", "weight": 7}),
+                ("A", "D", {0: "A", "b": "D", "weight": 4}),
+            ]
+        )
+        G = nx.from_pandas_edgelist(self.df, 0, "b", [0, "b", "weight"])
+        assert graphs_equal(G, Gtrue)
+
+    def test_from_edgelist_multidigraph_and_edge_attr(self):
+        # example from issue #2374
+        edges = [
+            ("X1", "X4", {"Co": "zA", "Mi": 0, "St": "X1"}),
+            ("X1", "X4", {"Co": "zB", "Mi": 54, "St": "X2"}),
+            ("X1", "X4", {"Co": "zB", "Mi": 49, "St": "X3"}),
+            ("X1", "X4", {"Co": "zB", "Mi": 44, "St": "X4"}),
+            ("Y1", "Y3", {"Co": "zC", "Mi": 0, "St": "Y1"}),
+            ("Y1", "Y3", {"Co": "zC", "Mi": 34, "St": "Y2"}),
+            ("Y1", "Y3", {"Co": "zC", "Mi": 29, "St": "X2"}),
+            ("Y1", "Y3", {"Co": "zC", "Mi": 24, "St": "Y3"}),
+            ("Z1", "Z3", {"Co": "zD", "Mi": 0, "St": "Z1"}),
+            ("Z1", "Z3", {"Co": "zD", "Mi": 14, "St": "X3"}),
+        ]
+        Gtrue = nx.MultiDiGraph(edges)
+        data = {
+            "O": ["X1", "X1", "X1", "X1", "Y1", "Y1", "Y1", "Y1", "Z1", "Z1"],
+            "D": ["X4", "X4", "X4", "X4", "Y3", "Y3", "Y3", "Y3", "Z3", "Z3"],
+            "St": ["X1", "X2", "X3", "X4", "Y1", "Y2", "X2", "Y3", "Z1", "X3"],
+            "Co": ["zA", "zB", "zB", "zB", "zC", "zC", "zC", "zC", "zD", "zD"],
+            "Mi": [0, 54, 49, 44, 0, 34, 29, 24, 0, 14],
+        }
+        df = pd.DataFrame.from_dict(data)
+        G1 = nx.from_pandas_edgelist(
+            df, source="O", target="D", edge_attr=True, create_using=nx.MultiDiGraph
+        )
+        G2 = nx.from_pandas_edgelist(
+            df,
+            source="O",
+            target="D",
+            edge_attr=["St", "Co", "Mi"],
+            create_using=nx.MultiDiGraph,
+        )
+        assert graphs_equal(G1, Gtrue)
+        assert graphs_equal(G2, Gtrue)
+
+    def test_from_edgelist_one_attr(self):
+        Gtrue = nx.Graph(
+            [
+                ("E", "C", {"weight": 10}),
+                ("B", "A", {"weight": 7}),
+                ("A", "D", {"weight": 4}),
+            ]
+        )
+        G = nx.from_pandas_edgelist(self.df, 0, "b", "weight")
+        assert graphs_equal(G, Gtrue)
+
+    def test_from_edgelist_int_attr_name(self):
+        # note: this also tests that edge_attr can be `source`
+        Gtrue = nx.Graph(
+            [("E", "C", {0: "C"}), ("B", "A", {0: "B"}), ("A", "D", {0: "A"})]
+        )
+        G = nx.from_pandas_edgelist(self.df, 0, "b", 0)
+        assert graphs_equal(G, Gtrue)
+
+    def test_from_edgelist_invalid_attr(self):
+        pytest.raises(
+            nx.NetworkXError, nx.from_pandas_edgelist, self.df, 0, "b", "misspell"
+        )
+        pytest.raises(nx.NetworkXError, nx.from_pandas_edgelist, self.df, 0, "b", 1)
+        # see Issue #3562
+        edgeframe = pd.DataFrame([[0, 1], [1, 2], [2, 0]], columns=["s", "t"])
+        pytest.raises(
+            nx.NetworkXError, nx.from_pandas_edgelist, edgeframe, "s", "t", True
+        )
+        pytest.raises(
+            nx.NetworkXError, nx.from_pandas_edgelist, edgeframe, "s", "t", "weight"
+        )
+        pytest.raises(
+            nx.NetworkXError,
+            nx.from_pandas_edgelist,
+            edgeframe,
+            "s",
+            "t",
+            ["weight", "size"],
+        )
+
+    def test_from_edgelist_no_attr(self):
+        Gtrue = nx.Graph([("E", "C", {}), ("B", "A", {}), ("A", "D", {})])
+        G = nx.from_pandas_edgelist(self.df, 0, "b")
+        assert graphs_equal(G, Gtrue)
+
+    def test_from_edgelist(self):
+        # Pandas DataFrame
+        G = nx.cycle_graph(10)
+        G.add_weighted_edges_from((u, v, u) for u, v in list(G.edges))
+
+        edgelist = nx.to_edgelist(G)
+        source = [s for s, t, d in edgelist]
+        target = [t for s, t, d in edgelist]
+        weight = [d["weight"] for s, t, d in edgelist]
+        edges = pd.DataFrame({"source": source, "target": target, "weight": weight})
+
+        GG = nx.from_pandas_edgelist(edges, edge_attr="weight")
+        assert nodes_equal(G.nodes(), GG.nodes())
+        assert edges_equal(G.edges(), GG.edges())
+        GW = nx.to_networkx_graph(edges, create_using=nx.Graph)
+        assert nodes_equal(G.nodes(), GW.nodes())
+        assert edges_equal(G.edges(), GW.edges())
+
+    def test_to_edgelist_default_source_or_target_col_exists(self):
+        G = nx.path_graph(10)
+        G.add_weighted_edges_from((u, v, u) for u, v in list(G.edges))
+        nx.set_edge_attributes(G, 0, name="source")
+        pytest.raises(nx.NetworkXError, nx.to_pandas_edgelist, G)
+
+        # drop source column to test an exception raised for the target column
+        for u, v, d in G.edges(data=True):
+            d.pop("source", None)
+
+        nx.set_edge_attributes(G, 0, name="target")
+        pytest.raises(nx.NetworkXError, nx.to_pandas_edgelist, G)
+
+    def test_to_edgelist_custom_source_or_target_col_exists(self):
+        G = nx.path_graph(10)
+        G.add_weighted_edges_from((u, v, u) for u, v in list(G.edges))
+        nx.set_edge_attributes(G, 0, name="source_col_name")
+        pytest.raises(
+            nx.NetworkXError, nx.to_pandas_edgelist, G, source="source_col_name"
+        )
+
+        # drop source column to test an exception raised for the target column
+        for u, v, d in G.edges(data=True):
+            d.pop("source_col_name", None)
+
+        nx.set_edge_attributes(G, 0, name="target_col_name")
+        pytest.raises(
+            nx.NetworkXError, nx.to_pandas_edgelist, G, target="target_col_name"
+        )
+
+    def test_to_edgelist_edge_key_col_exists(self):
+        G = nx.path_graph(10, create_using=nx.MultiGraph)
+        G.add_weighted_edges_from((u, v, u) for u, v in list(G.edges()))
+        nx.set_edge_attributes(G, 0, name="edge_key_name")
+        pytest.raises(
+            nx.NetworkXError, nx.to_pandas_edgelist, G, edge_key="edge_key_name"
+        )
+
+    def test_from_adjacency(self):
+        nodelist = [1, 2]
+        dftrue = pd.DataFrame(
+            [[1, 1], [1, 0]], dtype=int, index=nodelist, columns=nodelist
+        )
+        G = nx.Graph([(1, 1), (1, 2)])
+        df = nx.to_pandas_adjacency(G, dtype=int)
+        pd.testing.assert_frame_equal(df, dftrue)
+
+    @pytest.mark.parametrize("graph", [nx.Graph, nx.MultiGraph])
+    def test_roundtrip(self, graph):
+        # edgelist
+        Gtrue = graph([(1, 1), (1, 2)])
+        df = nx.to_pandas_edgelist(Gtrue)
+        G = nx.from_pandas_edgelist(df, create_using=graph)
+        assert graphs_equal(Gtrue, G)
+        # adjacency
+        adj = {1: {1: {"weight": 1}, 2: {"weight": 1}}, 2: {1: {"weight": 1}}}
+        Gtrue = graph(adj)
+        df = nx.to_pandas_adjacency(Gtrue, dtype=int)
+        G = nx.from_pandas_adjacency(df, create_using=graph)
+        assert graphs_equal(Gtrue, G)
+
+    def test_from_adjacency_named(self):
+        # example from issue #3105
+        data = {
+            "A": {"A": 0, "B": 0, "C": 0},
+            "B": {"A": 1, "B": 0, "C": 0},
+            "C": {"A": 0, "B": 1, "C": 0},
+        }
+        dftrue = pd.DataFrame(data, dtype=np.intp)
+        df = dftrue[["A", "C", "B"]]
+        G = nx.from_pandas_adjacency(df, create_using=nx.DiGraph())
+        df = nx.to_pandas_adjacency(G, dtype=np.intp)
+        pd.testing.assert_frame_equal(df, dftrue)
+
+    @pytest.mark.parametrize("edge_attr", [["attr2", "attr3"], True])
+    def test_edgekey_with_multigraph(self, edge_attr):
+        df = pd.DataFrame(
+            {
+                "source": {"A": "N1", "B": "N2", "C": "N1", "D": "N1"},
+                "target": {"A": "N2", "B": "N3", "C": "N1", "D": "N2"},
+                "attr1": {"A": "F1", "B": "F2", "C": "F3", "D": "F4"},
+                "attr2": {"A": 1, "B": 0, "C": 0, "D": 0},
+                "attr3": {"A": 0, "B": 1, "C": 0, "D": 1},
+            }
+        )
+        Gtrue = nx.MultiGraph(
+            [
+                ("N1", "N2", "F1", {"attr2": 1, "attr3": 0}),
+                ("N2", "N3", "F2", {"attr2": 0, "attr3": 1}),
+                ("N1", "N1", "F3", {"attr2": 0, "attr3": 0}),
+                ("N1", "N2", "F4", {"attr2": 0, "attr3": 1}),
+            ]
+        )
+        # example from issue #4065
+        G = nx.from_pandas_edgelist(
+            df,
+            source="source",
+            target="target",
+            edge_attr=edge_attr,
+            edge_key="attr1",
+            create_using=nx.MultiGraph(),
+        )
+        assert graphs_equal(G, Gtrue)
+
+        df_roundtrip = nx.to_pandas_edgelist(G, edge_key="attr1")
+        df_roundtrip = df_roundtrip.sort_values("attr1")
+        df_roundtrip.index = ["A", "B", "C", "D"]
+        pd.testing.assert_frame_equal(
+            df, df_roundtrip[["source", "target", "attr1", "attr2", "attr3"]]
+        )
+
+    def test_edgekey_with_normal_graph_no_action(self):
+        Gtrue = nx.Graph(
+            [
+                ("E", "C", {"cost": 9, "weight": 10}),
+                ("B", "A", {"cost": 1, "weight": 7}),
+                ("A", "D", {"cost": 7, "weight": 4}),
+            ]
+        )
+        G = nx.from_pandas_edgelist(self.df, 0, "b", True, edge_key="weight")
+        assert graphs_equal(G, Gtrue)
+
+    def test_nonexisting_edgekey_raises(self):
+        with pytest.raises(nx.exception.NetworkXError):
+            nx.from_pandas_edgelist(
+                self.df,
+                source="source",
+                target="target",
+                edge_key="Not_real",
+                edge_attr=True,
+                create_using=nx.MultiGraph(),
+            )
+
+    def test_multigraph_with_edgekey_no_edgeattrs(self):
+        Gtrue = nx.MultiGraph()
+        Gtrue.add_edge(0, 1, key=0)
+        Gtrue.add_edge(0, 1, key=3)
+        df = nx.to_pandas_edgelist(Gtrue, edge_key="key")
+        expected = pd.DataFrame({"source": [0, 0], "target": [1, 1], "key": [0, 3]})
+        pd.testing.assert_frame_equal(expected, df)
+        G = nx.from_pandas_edgelist(df, edge_key="key", create_using=nx.MultiGraph)
+        assert graphs_equal(Gtrue, G)
+
+
+def test_to_pandas_adjacency_with_nodelist():
+    G = nx.complete_graph(5)
+    nodelist = [1, 4]
+    expected = pd.DataFrame(
+        [[0, 1], [1, 0]], dtype=int, index=nodelist, columns=nodelist
+    )
+    pd.testing.assert_frame_equal(
+        expected, nx.to_pandas_adjacency(G, nodelist, dtype=int)
+    )
+
+
+def test_to_pandas_edgelist_with_nodelist():
+    G = nx.Graph()
+    G.add_edges_from([(0, 1), (1, 2), (1, 3)], weight=2.0)
+    G.add_edge(0, 5, weight=100)
+    df = nx.to_pandas_edgelist(G, nodelist=[1, 2])
+    assert 0 not in df["source"].to_numpy()
+    assert 100 not in df["weight"].to_numpy()
+
+
+def test_from_pandas_adjacency_with_index_collisions():
+    """See gh-7407"""
+    df = pd.DataFrame(
+        [
+            [0, 1, 0, 0],
+            [0, 0, 1, 0],
+            [0, 0, 0, 1],
+            [0, 0, 0, 0],
+        ],
+        index=[1010001, 2, 1, 1010002],
+        columns=[1010001, 2, 1, 1010002],
+    )
+    G = nx.from_pandas_adjacency(df, create_using=nx.DiGraph)
+    expected = nx.DiGraph([(1010001, 2), (2, 1), (1, 1010002)])
+    assert nodes_equal(G.nodes, expected.nodes)
+    assert edges_equal(G.edges, expected.edges, directed=True)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_convert_scipy.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_convert_scipy.py
new file mode 100644
index 0000000000000000000000000000000000000000..2575027046c61612c1be3c36a5b7877c28e71d92
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_convert_scipy.py
@@ -0,0 +1,281 @@
+import pytest
+
+import networkx as nx
+from networkx.utils import graphs_equal
+
+np = pytest.importorskip("numpy")
+sp = pytest.importorskip("scipy")
+
+
+class TestConvertScipy:
+    def setup_method(self):
+        self.G1 = nx.barbell_graph(10, 3)
+        self.G2 = nx.cycle_graph(10, create_using=nx.DiGraph)
+
+        self.G3 = self.create_weighted(nx.Graph())
+        self.G4 = self.create_weighted(nx.DiGraph())
+
+    def test_exceptions(self):
+        class G:
+            format = None
+
+        pytest.raises(nx.NetworkXError, nx.to_networkx_graph, G)
+
+    def create_weighted(self, G):
+        g = nx.cycle_graph(4)
+        e = list(g.edges())
+        source = [u for u, v in e]
+        dest = [v for u, v in e]
+        weight = [s + 10 for s in source]
+        ex = zip(source, dest, weight)
+        G.add_weighted_edges_from(ex)
+        return G
+
+    def identity_conversion(self, G, A, create_using):
+        GG = nx.from_scipy_sparse_array(A, create_using=create_using)
+        assert nx.is_isomorphic(G, GG)
+
+        GW = nx.to_networkx_graph(A, create_using=create_using)
+        assert nx.is_isomorphic(G, GW)
+
+        GI = nx.empty_graph(0, create_using).__class__(A)
+        assert nx.is_isomorphic(G, GI)
+
+        ACSR = A.tocsr()
+        GI = nx.empty_graph(0, create_using).__class__(ACSR)
+        assert nx.is_isomorphic(G, GI)
+
+        ACOO = A.tocoo()
+        GI = nx.empty_graph(0, create_using).__class__(ACOO)
+        assert nx.is_isomorphic(G, GI)
+
+        ACSC = A.tocsc()
+        GI = nx.empty_graph(0, create_using).__class__(ACSC)
+        assert nx.is_isomorphic(G, GI)
+
+        AD = A.todense()
+        GI = nx.empty_graph(0, create_using).__class__(AD)
+        assert nx.is_isomorphic(G, GI)
+
+        AA = A.toarray()
+        GI = nx.empty_graph(0, create_using).__class__(AA)
+        assert nx.is_isomorphic(G, GI)
+
+    def test_shape(self):
+        "Conversion from non-square sparse array."
+        A = sp.sparse.lil_array([[1, 2, 3], [4, 5, 6]])
+        pytest.raises(nx.NetworkXError, nx.from_scipy_sparse_array, A)
+
+    def test_identity_graph_matrix(self):
+        "Conversion from graph to sparse matrix to graph."
+        A = nx.to_scipy_sparse_array(self.G1)
+        self.identity_conversion(self.G1, A, nx.Graph())
+
+    def test_identity_digraph_matrix(self):
+        "Conversion from digraph to sparse matrix to digraph."
+        A = nx.to_scipy_sparse_array(self.G2)
+        self.identity_conversion(self.G2, A, nx.DiGraph())
+
+    def test_identity_weighted_graph_matrix(self):
+        """Conversion from weighted graph to sparse matrix to weighted graph."""
+        A = nx.to_scipy_sparse_array(self.G3)
+        self.identity_conversion(self.G3, A, nx.Graph())
+
+    def test_identity_weighted_digraph_matrix(self):
+        """Conversion from weighted digraph to sparse matrix to weighted digraph."""
+        A = nx.to_scipy_sparse_array(self.G4)
+        self.identity_conversion(self.G4, A, nx.DiGraph())
+
+    def test_nodelist(self):
+        """Conversion from graph to sparse matrix to graph with nodelist."""
+        P4 = nx.path_graph(4)
+        P3 = nx.path_graph(3)
+        nodelist = list(P3.nodes())
+        A = nx.to_scipy_sparse_array(P4, nodelist=nodelist)
+        GA = nx.Graph(A)
+        assert nx.is_isomorphic(GA, P3)
+
+        pytest.raises(nx.NetworkXError, nx.to_scipy_sparse_array, P3, nodelist=[])
+        # Test nodelist duplicates.
+        long_nl = nodelist + [0]
+        pytest.raises(nx.NetworkXError, nx.to_scipy_sparse_array, P3, nodelist=long_nl)
+
+        # Test nodelist contains non-nodes
+        non_nl = [-1, 0, 1, 2]
+        pytest.raises(nx.NetworkXError, nx.to_scipy_sparse_array, P3, nodelist=non_nl)
+
+    def test_weight_keyword(self):
+        WP4 = nx.Graph()
+        WP4.add_edges_from((n, n + 1, {"weight": 0.5, "other": 0.3}) for n in range(3))
+        P4 = nx.path_graph(4)
+        A = nx.to_scipy_sparse_array(P4)
+        np.testing.assert_equal(
+            A.todense(), nx.to_scipy_sparse_array(WP4, weight=None).todense()
+        )
+        np.testing.assert_equal(
+            0.5 * A.todense(), nx.to_scipy_sparse_array(WP4).todense()
+        )
+        np.testing.assert_equal(
+            0.3 * A.todense(), nx.to_scipy_sparse_array(WP4, weight="other").todense()
+        )
+
+    def test_format_keyword(self):
+        WP4 = nx.Graph()
+        WP4.add_edges_from((n, n + 1, {"weight": 0.5, "other": 0.3}) for n in range(3))
+        P4 = nx.path_graph(4)
+        A = nx.to_scipy_sparse_array(P4, format="csr")
+        np.testing.assert_equal(
+            A.todense(), nx.to_scipy_sparse_array(WP4, weight=None).todense()
+        )
+
+        A = nx.to_scipy_sparse_array(P4, format="csc")
+        np.testing.assert_equal(
+            A.todense(), nx.to_scipy_sparse_array(WP4, weight=None).todense()
+        )
+
+        A = nx.to_scipy_sparse_array(P4, format="coo")
+        np.testing.assert_equal(
+            A.todense(), nx.to_scipy_sparse_array(WP4, weight=None).todense()
+        )
+
+        A = nx.to_scipy_sparse_array(P4, format="bsr")
+        np.testing.assert_equal(
+            A.todense(), nx.to_scipy_sparse_array(WP4, weight=None).todense()
+        )
+
+        A = nx.to_scipy_sparse_array(P4, format="lil")
+        np.testing.assert_equal(
+            A.todense(), nx.to_scipy_sparse_array(WP4, weight=None).todense()
+        )
+
+        A = nx.to_scipy_sparse_array(P4, format="dia")
+        np.testing.assert_equal(
+            A.todense(), nx.to_scipy_sparse_array(WP4, weight=None).todense()
+        )
+
+        A = nx.to_scipy_sparse_array(P4, format="dok")
+        np.testing.assert_equal(
+            A.todense(), nx.to_scipy_sparse_array(WP4, weight=None).todense()
+        )
+
+    def test_format_keyword_raise(self):
+        with pytest.raises(nx.NetworkXError):
+            WP4 = nx.Graph()
+            WP4.add_edges_from(
+                (n, n + 1, {"weight": 0.5, "other": 0.3}) for n in range(3)
+            )
+            P4 = nx.path_graph(4)
+            nx.to_scipy_sparse_array(P4, format="any_other")
+
+    def test_null_raise(self):
+        with pytest.raises(nx.NetworkXError):
+            nx.to_scipy_sparse_array(nx.Graph())
+
+    def test_empty(self):
+        G = nx.Graph()
+        G.add_node(1)
+        M = nx.to_scipy_sparse_array(G)
+        np.testing.assert_equal(M.toarray(), np.array([[0]]))
+
+    def test_ordering(self):
+        G = nx.DiGraph()
+        G.add_edge(1, 2)
+        G.add_edge(2, 3)
+        G.add_edge(3, 1)
+        M = nx.to_scipy_sparse_array(G, nodelist=[3, 2, 1])
+        np.testing.assert_equal(
+            M.toarray(), np.array([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
+        )
+
+    def test_selfloop_graph(self):
+        G = nx.Graph([(1, 1)])
+        M = nx.to_scipy_sparse_array(G)
+        np.testing.assert_equal(M.toarray(), np.array([[1]]))
+
+        G.add_edges_from([(2, 3), (3, 4)])
+        M = nx.to_scipy_sparse_array(G, nodelist=[2, 3, 4])
+        np.testing.assert_equal(
+            M.toarray(), np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]])
+        )
+
+    def test_selfloop_digraph(self):
+        G = nx.DiGraph([(1, 1)])
+        M = nx.to_scipy_sparse_array(G)
+        np.testing.assert_equal(M.toarray(), np.array([[1]]))
+
+        G.add_edges_from([(2, 3), (3, 4)])
+        M = nx.to_scipy_sparse_array(G, nodelist=[2, 3, 4])
+        np.testing.assert_equal(
+            M.toarray(), np.array([[0, 1, 0], [0, 0, 1], [0, 0, 0]])
+        )
+
+    def test_from_scipy_sparse_array_parallel_edges(self):
+        """Tests that the :func:`networkx.from_scipy_sparse_array` function
+        interprets integer weights as the number of parallel edges when
+        creating a multigraph.
+
+        """
+        A = sp.sparse.csr_array([[1, 1], [1, 2]])
+        # First, with a simple graph, each integer entry in the adjacency
+        # matrix is interpreted as the weight of a single edge in the graph.
+        expected = nx.DiGraph()
+        edges = [(0, 0), (0, 1), (1, 0)]
+        expected.add_weighted_edges_from([(u, v, 1) for (u, v) in edges])
+        expected.add_edge(1, 1, weight=2)
+        actual = nx.from_scipy_sparse_array(
+            A, parallel_edges=True, create_using=nx.DiGraph
+        )
+        assert graphs_equal(actual, expected)
+        actual = nx.from_scipy_sparse_array(
+            A, parallel_edges=False, create_using=nx.DiGraph
+        )
+        assert graphs_equal(actual, expected)
+        # Now each integer entry in the adjacency matrix is interpreted as the
+        # number of parallel edges in the graph if the appropriate keyword
+        # argument is specified.
+        edges = [(0, 0), (0, 1), (1, 0), (1, 1), (1, 1)]
+        expected = nx.MultiDiGraph()
+        expected.add_weighted_edges_from([(u, v, 1) for (u, v) in edges])
+        actual = nx.from_scipy_sparse_array(
+            A, parallel_edges=True, create_using=nx.MultiDiGraph
+        )
+        assert graphs_equal(actual, expected)
+        expected = nx.MultiDiGraph()
+        expected.add_edges_from(set(edges), weight=1)
+        # The sole self-loop (edge 0) on vertex 1 should have weight 2.
+        expected[1][1][0]["weight"] = 2
+        actual = nx.from_scipy_sparse_array(
+            A, parallel_edges=False, create_using=nx.MultiDiGraph
+        )
+        assert graphs_equal(actual, expected)
+
+    def test_symmetric(self):
+        """Tests that a symmetric matrix has edges added only once to an
+        undirected multigraph when using
+        :func:`networkx.from_scipy_sparse_array`.
+
+        """
+        A = sp.sparse.csr_array([[0, 1], [1, 0]])
+        G = nx.from_scipy_sparse_array(A, create_using=nx.MultiGraph)
+        expected = nx.MultiGraph()
+        expected.add_edge(0, 1, weight=1)
+        assert graphs_equal(G, expected)
+
+
+@pytest.mark.parametrize("sparse_format", ("csr", "csc", "dok"))
+def test_from_scipy_sparse_array_formats(sparse_format):
+    """Test all formats supported by _generate_weighted_edges."""
+    # trinode complete graph with non-uniform edge weights
+    expected = nx.Graph()
+    expected.add_edges_from(
+        [
+            (0, 1, {"weight": 3}),
+            (0, 2, {"weight": 2}),
+            (1, 0, {"weight": 3}),
+            (1, 2, {"weight": 1}),
+            (2, 0, {"weight": 2}),
+            (2, 1, {"weight": 1}),
+        ]
+    )
+    A = sp.sparse.coo_array([[0, 3, 2], [3, 0, 1], [2, 1, 0]]).asformat(sparse_format)
+    assert graphs_equal(expected, nx.from_scipy_sparse_array(A))
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_exceptions.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf59983cb8d12a119f5744ebc8b11e7cb9075366
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_exceptions.py
@@ -0,0 +1,40 @@
+import pytest
+
+import networkx as nx
+
+# smoke tests for exceptions
+
+
+def test_raises_networkxexception():
+    with pytest.raises(nx.NetworkXException):
+        raise nx.NetworkXException
+
+
+def test_raises_networkxerr():
+    with pytest.raises(nx.NetworkXError):
+        raise nx.NetworkXError
+
+
+def test_raises_networkx_pointless_concept():
+    with pytest.raises(nx.NetworkXPointlessConcept):
+        raise nx.NetworkXPointlessConcept
+
+
+def test_raises_networkxalgorithmerr():
+    with pytest.raises(nx.NetworkXAlgorithmError):
+        raise nx.NetworkXAlgorithmError
+
+
+def test_raises_networkx_unfeasible():
+    with pytest.raises(nx.NetworkXUnfeasible):
+        raise nx.NetworkXUnfeasible
+
+
+def test_raises_networkx_no_path():
+    with pytest.raises(nx.NetworkXNoPath):
+        raise nx.NetworkXNoPath
+
+
+def test_raises_networkx_unbounded():
+    with pytest.raises(nx.NetworkXUnbounded):
+        raise nx.NetworkXUnbounded
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_import.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_import.py
new file mode 100644
index 0000000000000000000000000000000000000000..32aafdf2a4dafc85cee088138590b84f4c627b5e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_import.py
@@ -0,0 +1,11 @@
+import pytest
+
+
+def test_namespace_alias():
+    with pytest.raises(ImportError):
+        from networkx import nx
+
+
+def test_namespace_nesting():
+    with pytest.raises(ImportError):
+        from networkx import networkx
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_lazy_imports.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_lazy_imports.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec09ac2fcda5c9ce8b1f9c6f1d0fba58eb54742e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_lazy_imports.py
@@ -0,0 +1,96 @@
+import sys
+import types
+
+import pytest
+
+import networkx.lazy_imports as lazy
+
+
+def test_lazy_import_basics():
+    math = lazy._lazy_import("math")
+    anything_not_real = lazy._lazy_import("anything_not_real")
+
+    # Now test that accessing attributes does what it should
+    assert math.sin(math.pi) == pytest.approx(0, 1e-6)
+    # poor-mans pytest.raises for testing errors on attribute access
+    try:
+        anything_not_real.pi
+        assert False  # Should not get here
+    except ModuleNotFoundError:
+        pass
+    assert isinstance(anything_not_real, lazy.DelayedImportErrorModule)
+    # see if it changes for second access
+    try:
+        anything_not_real.pi
+        assert False  # Should not get here
+    except ModuleNotFoundError:
+        pass
+
+
+def test_lazy_import_impact_on_sys_modules():
+    math = lazy._lazy_import("math")
+    anything_not_real = lazy._lazy_import("anything_not_real")
+
+    assert isinstance(math, types.ModuleType)
+    assert "math" in sys.modules
+    assert type(anything_not_real) is lazy.DelayedImportErrorModule
+    assert "anything_not_real" not in sys.modules
+
+    # only do this if numpy is installed
+    np_test = pytest.importorskip("numpy")
+    np = lazy._lazy_import("numpy")
+    assert isinstance(np, types.ModuleType)
+    assert "numpy" in sys.modules
+
+    np.pi  # trigger load of numpy
+
+    assert isinstance(np, types.ModuleType)
+    assert "numpy" in sys.modules
+
+
+def test_lazy_import_nonbuiltins():
+    sp = lazy._lazy_import("scipy")
+    np = lazy._lazy_import("numpy")
+    if isinstance(sp, lazy.DelayedImportErrorModule):
+        try:
+            sp.special.erf
+            assert False
+        except ModuleNotFoundError:
+            pass
+    elif isinstance(np, lazy.DelayedImportErrorModule):
+        try:
+            np.sin(np.pi)
+            assert False
+        except ModuleNotFoundError:
+            pass
+    else:
+        assert sp.special.erf(np.pi) == pytest.approx(1, 1e-4)
+
+
+def test_lazy_attach():
+    name = "mymod"
+    submods = ["mysubmodule", "anothersubmodule"]
+    myall = {"not_real_submod": ["some_var_or_func"]}
+
+    locls = {
+        "attach": lazy.attach,
+        "name": name,
+        "submods": submods,
+        "myall": myall,
+    }
+    s = "__getattr__, __lazy_dir__, __all__ = attach(name, submods, myall)"
+
+    exec(s, {}, locls)
+    expected = {
+        "attach": lazy.attach,
+        "name": name,
+        "submods": submods,
+        "myall": myall,
+        "__getattr__": None,
+        "__lazy_dir__": None,
+        "__all__": None,
+    }
+    assert locls.keys() == expected.keys()
+    for k, v in expected.items():
+        if v is not None:
+            assert locls[k] == v
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_relabel.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_relabel.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a70ec11e6a4b2ed3e7371e1adaee90ece46f2c7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_relabel.py
@@ -0,0 +1,349 @@
+import pytest
+
+import networkx as nx
+from networkx.generators.classic import empty_graph
+from networkx.utils import edges_equal, nodes_equal
+
+
+class TestRelabel:
+    def test_convert_node_labels_to_integers(self):
+        # test that empty graph converts fine for all options
+        G = empty_graph()
+        H = nx.convert_node_labels_to_integers(G, 100)
+        assert list(H.nodes()) == []
+        assert list(H.edges()) == []
+
+        for opt in ["default", "sorted", "increasing degree", "decreasing degree"]:
+            G = empty_graph()
+            H = nx.convert_node_labels_to_integers(G, 100, ordering=opt)
+            assert list(H.nodes()) == []
+            assert list(H.edges()) == []
+
+        G = empty_graph()
+        G.add_edges_from([("A", "B"), ("A", "C"), ("B", "C"), ("C", "D")])
+        H = nx.convert_node_labels_to_integers(G)
+        degH = (d for n, d in H.degree())
+        degG = (d for n, d in G.degree())
+        assert sorted(degH) == sorted(degG)
+
+        H = nx.convert_node_labels_to_integers(G, 1000)
+        degH = (d for n, d in H.degree())
+        degG = (d for n, d in G.degree())
+        assert sorted(degH) == sorted(degG)
+        assert nodes_equal(H.nodes(), [1000, 1001, 1002, 1003])
+
+        H = nx.convert_node_labels_to_integers(G, ordering="increasing degree")
+        degH = (d for n, d in H.degree())
+        degG = (d for n, d in G.degree())
+        assert sorted(degH) == sorted(degG)
+        assert H.degree(0) == 1
+        assert H.degree(1) == 2
+        assert H.degree(2) == 2
+        assert H.degree(3) == 3
+
+        H = nx.convert_node_labels_to_integers(G, ordering="decreasing degree")
+        degH = (d for n, d in H.degree())
+        degG = (d for n, d in G.degree())
+        assert sorted(degH) == sorted(degG)
+        assert H.degree(0) == 3
+        assert H.degree(1) == 2
+        assert H.degree(2) == 2
+        assert H.degree(3) == 1
+
+        H = nx.convert_node_labels_to_integers(
+            G, ordering="increasing degree", label_attribute="label"
+        )
+        degH = (d for n, d in H.degree())
+        degG = (d for n, d in G.degree())
+        assert sorted(degH) == sorted(degG)
+        assert H.degree(0) == 1
+        assert H.degree(1) == 2
+        assert H.degree(2) == 2
+        assert H.degree(3) == 3
+
+        # check mapping
+        assert H.nodes[3]["label"] == "C"
+        assert H.nodes[0]["label"] == "D"
+        assert H.nodes[1]["label"] == "A" or H.nodes[2]["label"] == "A"
+        assert H.nodes[1]["label"] == "B" or H.nodes[2]["label"] == "B"
+
+    def test_convert_to_integers2(self):
+        G = empty_graph()
+        G.add_edges_from([("C", "D"), ("A", "B"), ("A", "C"), ("B", "C")])
+        H = nx.convert_node_labels_to_integers(G, ordering="sorted")
+        degH = (d for n, d in H.degree())
+        degG = (d for n, d in G.degree())
+        assert sorted(degH) == sorted(degG)
+
+        H = nx.convert_node_labels_to_integers(
+            G, ordering="sorted", label_attribute="label"
+        )
+        assert H.nodes[0]["label"] == "A"
+        assert H.nodes[1]["label"] == "B"
+        assert H.nodes[2]["label"] == "C"
+        assert H.nodes[3]["label"] == "D"
+
+    def test_convert_to_integers_raise(self):
+        with pytest.raises(nx.NetworkXError):
+            G = nx.Graph()
+            H = nx.convert_node_labels_to_integers(G, ordering="increasing age")
+
+    def test_relabel_nodes_copy(self):
+        G = nx.empty_graph()
+        G.add_edges_from([("A", "B"), ("A", "C"), ("B", "C"), ("C", "D")])
+        mapping = {"A": "aardvark", "B": "bear", "C": "cat", "D": "dog"}
+        H = nx.relabel_nodes(G, mapping)
+        assert nodes_equal(H.nodes(), ["aardvark", "bear", "cat", "dog"])
+
+    def test_relabel_nodes_function(self):
+        G = nx.empty_graph()
+        G.add_edges_from([("A", "B"), ("A", "C"), ("B", "C"), ("C", "D")])
+        # function mapping no longer encouraged but works
+
+        def mapping(n):
+            return ord(n)
+
+        H = nx.relabel_nodes(G, mapping)
+        assert nodes_equal(H.nodes(), [65, 66, 67, 68])
+
+    def test_relabel_nodes_callable_type(self):
+        G = nx.path_graph(4)
+        H = nx.relabel_nodes(G, str)
+        assert nodes_equal(H.nodes, ["0", "1", "2", "3"])
+
+    @pytest.mark.parametrize("non_mc", ("0123", ["0", "1", "2", "3"]))
+    def test_relabel_nodes_non_mapping_or_callable(self, non_mc):
+        """If `mapping` is neither a Callable or a Mapping, an exception
+        should be raised."""
+        G = nx.path_graph(4)
+        with pytest.raises(AttributeError):
+            nx.relabel_nodes(G, non_mc)
+
+    def test_relabel_nodes_graph(self):
+        G = nx.Graph([("A", "B"), ("A", "C"), ("B", "C"), ("C", "D")])
+        mapping = {"A": "aardvark", "B": "bear", "C": "cat", "D": "dog"}
+        H = nx.relabel_nodes(G, mapping)
+        assert nodes_equal(H.nodes(), ["aardvark", "bear", "cat", "dog"])
+
+    def test_relabel_nodes_orderedgraph(self):
+        G = nx.Graph()
+        G.add_nodes_from([1, 2, 3])
+        G.add_edges_from([(1, 3), (2, 3)])
+        mapping = {1: "a", 2: "b", 3: "c"}
+        H = nx.relabel_nodes(G, mapping)
+        assert list(H.nodes) == ["a", "b", "c"]
+
+    def test_relabel_nodes_digraph(self):
+        G = nx.DiGraph([("A", "B"), ("A", "C"), ("B", "C"), ("C", "D")])
+        mapping = {"A": "aardvark", "B": "bear", "C": "cat", "D": "dog"}
+        H = nx.relabel_nodes(G, mapping, copy=False)
+        assert nodes_equal(H.nodes(), ["aardvark", "bear", "cat", "dog"])
+
+    def test_relabel_nodes_multigraph(self):
+        G = nx.MultiGraph([("a", "b"), ("a", "b")])
+        mapping = {"a": "aardvark", "b": "bear"}
+        G = nx.relabel_nodes(G, mapping, copy=False)
+        assert nodes_equal(G.nodes(), ["aardvark", "bear"])
+        assert edges_equal(G.edges(), [("aardvark", "bear"), ("aardvark", "bear")])
+
+    def test_relabel_nodes_multidigraph(self):
+        G = nx.MultiDiGraph([("a", "b"), ("a", "b")])
+        mapping = {"a": "aardvark", "b": "bear"}
+        G = nx.relabel_nodes(G, mapping, copy=False)
+        assert nodes_equal(G.nodes(), ["aardvark", "bear"])
+        assert edges_equal(
+            G.edges(), [("aardvark", "bear"), ("aardvark", "bear")], directed=True
+        )
+
+    def test_relabel_isolated_nodes_to_same(self):
+        G = nx.Graph()
+        G.add_nodes_from(range(4))
+        mapping = {1: 1}
+        H = nx.relabel_nodes(G, mapping, copy=False)
+        assert nodes_equal(H.nodes(), list(range(4)))
+
+    def test_relabel_nodes_missing(self):
+        G = nx.Graph([("A", "B"), ("A", "C"), ("B", "C"), ("C", "D")])
+        mapping = {0: "aardvark"}
+        # copy=True
+        H = nx.relabel_nodes(G, mapping, copy=True)
+        assert nodes_equal(H.nodes, G.nodes)
+        # copy=False
+        GG = G.copy()
+        nx.relabel_nodes(G, mapping, copy=False)
+        assert nodes_equal(G.nodes, GG.nodes)
+
+    def test_relabel_copy_name(self):
+        G = nx.Graph()
+        H = nx.relabel_nodes(G, {}, copy=True)
+        assert H.graph == G.graph
+        H = nx.relabel_nodes(G, {}, copy=False)
+        assert H.graph == G.graph
+        G.name = "first"
+        H = nx.relabel_nodes(G, {}, copy=True)
+        assert H.graph == G.graph
+        H = nx.relabel_nodes(G, {}, copy=False)
+        assert H.graph == G.graph
+
+    def test_relabel_toposort(self):
+        K5 = nx.complete_graph(4)
+        G = nx.complete_graph(4)
+        G = nx.relabel_nodes(G, {i: i + 1 for i in range(4)}, copy=False)
+        assert nx.is_isomorphic(K5, G)
+        G = nx.complete_graph(4)
+        G = nx.relabel_nodes(G, {i: i - 1 for i in range(4)}, copy=False)
+        assert nx.is_isomorphic(K5, G)
+
+    def test_relabel_selfloop(self):
+        G = nx.DiGraph([(1, 1), (1, 2), (2, 3)])
+        G = nx.relabel_nodes(G, {1: "One", 2: "Two", 3: "Three"}, copy=False)
+        assert nodes_equal(G.nodes(), ["One", "Three", "Two"])
+        G = nx.MultiDiGraph([(1, 1), (1, 2), (2, 3)])
+        G = nx.relabel_nodes(G, {1: "One", 2: "Two", 3: "Three"}, copy=False)
+        assert nodes_equal(G.nodes(), ["One", "Three", "Two"])
+        G = nx.MultiDiGraph([(1, 1)])
+        G = nx.relabel_nodes(G, {1: 0}, copy=False)
+        assert nodes_equal(G.nodes(), [0])
+
+    def test_relabel_multidigraph_inout_merge_nodes(self):
+        for MG in (nx.MultiGraph, nx.MultiDiGraph):
+            for cc in (True, False):
+                G = MG([(0, 4), (1, 4), (4, 2), (4, 3)])
+                G[0][4][0]["value"] = "a"
+                G[1][4][0]["value"] = "b"
+                G[4][2][0]["value"] = "c"
+                G[4][3][0]["value"] = "d"
+                G.add_edge(0, 4, key="x", value="e")
+                G.add_edge(4, 3, key="x", value="f")
+                mapping = {0: 9, 1: 9, 2: 9, 3: 9}
+                H = nx.relabel_nodes(G, mapping, copy=cc)
+                # No ordering on keys enforced
+                assert {"value": "a"} in H[9][4].values()
+                assert {"value": "b"} in H[9][4].values()
+                assert {"value": "c"} in H[4][9].values()
+                assert len(H[4][9]) == 3 if G.is_directed() else 6
+                assert {"value": "d"} in H[4][9].values()
+                assert {"value": "e"} in H[9][4].values()
+                assert {"value": "f"} in H[4][9].values()
+                assert len(H[9][4]) == 3 if G.is_directed() else 6
+
+    def test_relabel_multigraph_merge_inplace(self):
+        G = nx.MultiGraph([(0, 1), (0, 2), (0, 3), (0, 1), (0, 2), (0, 3)])
+        G[0][1][0]["value"] = "a"
+        G[0][2][0]["value"] = "b"
+        G[0][3][0]["value"] = "c"
+        mapping = {1: 4, 2: 4, 3: 4}
+        nx.relabel_nodes(G, mapping, copy=False)
+        # No ordering on keys enforced
+        assert {"value": "a"} in G[0][4].values()
+        assert {"value": "b"} in G[0][4].values()
+        assert {"value": "c"} in G[0][4].values()
+
+    def test_relabel_multidigraph_merge_inplace(self):
+        G = nx.MultiDiGraph([(0, 1), (0, 2), (0, 3)])
+        G[0][1][0]["value"] = "a"
+        G[0][2][0]["value"] = "b"
+        G[0][3][0]["value"] = "c"
+        mapping = {1: 4, 2: 4, 3: 4}
+        nx.relabel_nodes(G, mapping, copy=False)
+        # No ordering on keys enforced
+        assert {"value": "a"} in G[0][4].values()
+        assert {"value": "b"} in G[0][4].values()
+        assert {"value": "c"} in G[0][4].values()
+
+    def test_relabel_multidigraph_inout_copy(self):
+        G = nx.MultiDiGraph([(0, 4), (1, 4), (4, 2), (4, 3)])
+        G[0][4][0]["value"] = "a"
+        G[1][4][0]["value"] = "b"
+        G[4][2][0]["value"] = "c"
+        G[4][3][0]["value"] = "d"
+        G.add_edge(0, 4, key="x", value="e")
+        G.add_edge(4, 3, key="x", value="f")
+        mapping = {0: 9, 1: 9, 2: 9, 3: 9}
+        H = nx.relabel_nodes(G, mapping, copy=True)
+        # No ordering on keys enforced
+        assert {"value": "a"} in H[9][4].values()
+        assert {"value": "b"} in H[9][4].values()
+        assert {"value": "c"} in H[4][9].values()
+        assert len(H[4][9]) == 3
+        assert {"value": "d"} in H[4][9].values()
+        assert {"value": "e"} in H[9][4].values()
+        assert {"value": "f"} in H[4][9].values()
+        assert len(H[9][4]) == 3
+
+    def test_relabel_multigraph_merge_copy(self):
+        G = nx.MultiGraph([(0, 1), (0, 2), (0, 3)])
+        G[0][1][0]["value"] = "a"
+        G[0][2][0]["value"] = "b"
+        G[0][3][0]["value"] = "c"
+        mapping = {1: 4, 2: 4, 3: 4}
+        H = nx.relabel_nodes(G, mapping, copy=True)
+        assert {"value": "a"} in H[0][4].values()
+        assert {"value": "b"} in H[0][4].values()
+        assert {"value": "c"} in H[0][4].values()
+
+    def test_relabel_multidigraph_merge_copy(self):
+        G = nx.MultiDiGraph([(0, 1), (0, 2), (0, 3)])
+        G[0][1][0]["value"] = "a"
+        G[0][2][0]["value"] = "b"
+        G[0][3][0]["value"] = "c"
+        mapping = {1: 4, 2: 4, 3: 4}
+        H = nx.relabel_nodes(G, mapping, copy=True)
+        assert {"value": "a"} in H[0][4].values()
+        assert {"value": "b"} in H[0][4].values()
+        assert {"value": "c"} in H[0][4].values()
+
+    def test_relabel_multigraph_nonnumeric_key(self):
+        for MG in (nx.MultiGraph, nx.MultiDiGraph):
+            for cc in (True, False):
+                G = nx.MultiGraph()
+                G.add_edge(0, 1, key="I", value="a")
+                G.add_edge(0, 2, key="II", value="b")
+                G.add_edge(0, 3, key="II", value="c")
+                mapping = {1: 4, 2: 4, 3: 4}
+                nx.relabel_nodes(G, mapping, copy=False)
+                assert {"value": "a"} in G[0][4].values()
+                assert {"value": "b"} in G[0][4].values()
+                assert {"value": "c"} in G[0][4].values()
+                assert 0 in G[0][4]
+                assert "I" in G[0][4]
+                assert "II" in G[0][4]
+
+    def test_relabel_circular(self):
+        G = nx.path_graph(3)
+        mapping = {0: 1, 1: 0}
+        H = nx.relabel_nodes(G, mapping, copy=True)
+        with pytest.raises(nx.NetworkXUnfeasible):
+            H = nx.relabel_nodes(G, mapping, copy=False)
+
+    def test_relabel_preserve_node_order_full_mapping_with_copy_true(self):
+        G = nx.path_graph(3)
+        original_order = list(G.nodes())
+        mapping = {2: "a", 1: "b", 0: "c"}  # dictionary keys out of order on purpose
+        H = nx.relabel_nodes(G, mapping, copy=True)
+        new_order = list(H.nodes())
+        assert [mapping.get(i, i) for i in original_order] == new_order
+
+    def test_relabel_preserve_node_order_full_mapping_with_copy_false(self):
+        G = nx.path_graph(3)
+        original_order = list(G)
+        mapping = {2: "a", 1: "b", 0: "c"}  # dictionary keys out of order on purpose
+        H = nx.relabel_nodes(G, mapping, copy=False)
+        new_order = list(H)
+        assert [mapping.get(i, i) for i in original_order] == new_order
+
+    def test_relabel_preserve_node_order_partial_mapping_with_copy_true(self):
+        G = nx.path_graph(3)
+        original_order = list(G)
+        mapping = {1: "a", 0: "b"}  # partial mapping and keys out of order on purpose
+        H = nx.relabel_nodes(G, mapping, copy=True)
+        new_order = list(H)
+        assert [mapping.get(i, i) for i in original_order] == new_order
+
+    def test_relabel_preserve_node_order_partial_mapping_with_copy_false(self):
+        G = nx.path_graph(3)
+        original_order = list(G)
+        mapping = {1: "a", 0: "b"}  # partial mapping and keys out of order on purpose
+        H = nx.relabel_nodes(G, mapping, copy=False)
+        new_order = list(H)
+        assert [mapping.get(i, i) for i in original_order] != new_order
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_removed_functions_exception_messages.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_removed_functions_exception_messages.py
new file mode 100644
index 0000000000000000000000000000000000000000..4746345627689ef18d39660f51204622dec5dbdb
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/tests/test_removed_functions_exception_messages.py
@@ -0,0 +1,8 @@
+import pytest
+
+import networkx as nx
+
+
+def test_random_tree():
+    with pytest.raises(AttributeError, match=".*Use `nx.random_labeled_tree` instead"):
+        nx.random_tree(3)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6abb178e4fd014bcec4c781fe98b8917d3ec876
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/__init__.py
@@ -0,0 +1,8 @@
+from networkx.utils.misc import *
+from networkx.utils.decorators import *
+from networkx.utils.random_sequence import *
+from networkx.utils.union_find import *
+from networkx.utils.rcm import *
+from networkx.utils.heaps import *
+from networkx.utils.configs import *
+from networkx.utils.backends import *
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/backends.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/backends.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7c99b5955957225cfc39d3868120e79b4f5af42
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/backends.py
@@ -0,0 +1,2171 @@
+# Notes about NetworkX namespace objects set up here:
+#
+# nx.utils.backends.backends:
+#   dict keyed by backend name to the backend entry point object.
+#   Filled using ``_get_backends("networkx.backends")`` during import of this module.
+#
+# nx.utils.backends.backend_info:
+#   dict keyed by backend name to the metadata returned by the function indicated
+#   by the "networkx.backend_info" entry point.
+#   Created as an empty dict while importing this module, but later filled using
+#   ``_set_configs_from_environment()`` at end of importing ``networkx/__init__.py``.
+#
+# nx.config:
+#   Config object for NetworkX config setting. Created using
+#   ``_set_configs_from_environment()`` at end of importing ``networkx/__init__.py``.
+#
+# private dicts:
+#   nx.utils.backends._loaded_backends:
+#       dict used to memoize loaded backends. Keyed by backend name to loaded backends.
+#
+#   nx.utils.backends._registered_algorithms:
+#       dict of all the dispatchable functions in networkx, keyed by _dispatchable
+#       function name to the wrapped function object.
+
+import inspect
+import itertools
+import logging
+import os
+import typing
+import warnings
+from functools import partial
+from importlib.metadata import entry_points
+
+import networkx as nx
+
+from .configs import BackendPriorities, Config, NetworkXConfig
+from .decorators import argmap
+
+__all__ = ["_dispatchable"]
+
+_logger = logging.getLogger(__name__)
+FAILED_TO_CONVERT = "FAILED_TO_CONVERT"
+
+
+def _get_backends(group, *, load_and_call=False):
+    """
+    Retrieve NetworkX ``backends`` and ``backend_info`` from the entry points.
+
+    Parameters
+    -----------
+    group : str
+        The entry_point to be retrieved.
+    load_and_call : bool, optional
+        If True, load and call the backend. Defaults to False.
+
+    Returns
+    --------
+    dict
+        A dictionary mapping backend names to their respective backend objects.
+
+    Notes
+    ------
+    If a backend is defined more than once, a warning is issued.
+    If a backend name is not a valid Python identifier, the backend is
+    ignored and a warning is issued.
+    The "nx_loopback" backend is removed if it exists, as it is only available during testing.
+    A warning is displayed if an error occurs while loading a backend.
+    """
+    items = entry_points(group=group)
+    rv = {}
+    for ep in items:
+        if not ep.name.isidentifier():
+            warnings.warn(
+                f"networkx backend name is not a valid identifier: {ep.name!r}. Ignoring.",
+                RuntimeWarning,
+                stacklevel=2,
+            )
+        elif ep.name in rv:
+            warnings.warn(
+                f"networkx backend defined more than once: {ep.name}",
+                RuntimeWarning,
+                stacklevel=2,
+            )
+        elif load_and_call:
+            try:
+                rv[ep.name] = ep.load()()
+            except Exception as exc:
+                warnings.warn(
+                    f"Error encountered when loading info for backend {ep.name}: {exc}",
+                    RuntimeWarning,
+                    stacklevel=2,
+                )
+        else:
+            rv[ep.name] = ep
+    rv.pop("nx_loopback", None)
+    return rv
+
+
+# Note: "networkx" is in `backend_info` but ignored in `backends` and `config.backends`.
+# It is valid to use "networkx" as a backend argument and in `config.backend_priority`.
+# If we make "networkx" a "proper" backend, put it in `backends` and `config.backends`.
+backends = _get_backends("networkx.backends")
+
+# Use _set_configs_from_environment() below to fill backend_info dict as
+# the last step in importing networkx
+backend_info = {}
+
+# Load and cache backends on-demand
+_loaded_backends = {}  # type: ignore[var-annotated]
+_registered_algorithms = {}
+
+
+# Get default configuration from environment variables at import time
+def _comma_sep_to_list(string):
+    return [x_strip for x in string.strip().split(",") if (x_strip := x.strip())]
+
+
+def _set_configs_from_environment():
+    """Initialize ``config.backend_priority``, load backend_info and config.
+
+    This gets default values from environment variables (see ``nx.config`` for details).
+    This function is run at the very end of importing networkx. It is run at this time
+    to avoid loading backend_info before the rest of networkx is imported in case a
+    backend uses networkx for its backend_info (e.g. subclassing the Config class.)
+    """
+    # backend_info is defined above as empty dict. Fill it after import finishes.
+    backend_info.update(_get_backends("networkx.backend_info", load_and_call=True))
+    backend_info.update(
+        (backend, {}) for backend in backends.keys() - backend_info.keys()
+    )
+
+    # set up config based on backend_info and environment
+    backend_config = {}
+    for backend, info in backend_info.items():
+        if "default_config" not in info:
+            cfg = Config()
+        else:
+            cfg = info["default_config"]
+            if not isinstance(cfg, Config):
+                cfg = Config(**cfg)
+        backend_config[backend] = cfg
+    backend_config = Config(**backend_config)
+    # Setting doc of backends_config type is not setting doc of Config
+    # Config has __new__ method that returns instance with a unique type!
+    type(backend_config).__doc__ = "All installed NetworkX backends and their configs."
+
+    backend_priority = BackendPriorities(algos=[], generators=[], classes=[])
+
+    config = NetworkXConfig(
+        backend_priority=backend_priority,
+        backends=backend_config,
+        cache_converted_graphs=bool(
+            os.environ.get("NETWORKX_CACHE_CONVERTED_GRAPHS", True)
+        ),
+        fallback_to_nx=bool(os.environ.get("NETWORKX_FALLBACK_TO_NX", False)),
+        warnings_to_ignore=set(
+            _comma_sep_to_list(os.environ.get("NETWORKX_WARNINGS_TO_IGNORE", ""))
+        ),
+    )
+
+    # Add "networkx" item to backend_info now b/c backend_config is set up
+    backend_info["networkx"] = {}
+
+    # NETWORKX_BACKEND_PRIORITY is the same as NETWORKX_BACKEND_PRIORITY_ALGOS
+    priorities = {
+        key[26:].lower(): val
+        for key, val in os.environ.items()
+        if key.startswith("NETWORKX_BACKEND_PRIORITY_")
+    }
+    backend_priority = config.backend_priority
+    backend_priority.algos = (
+        _comma_sep_to_list(priorities.pop("algos"))
+        if "algos" in priorities
+        else _comma_sep_to_list(
+            os.environ.get(
+                "NETWORKX_BACKEND_PRIORITY",
+                os.environ.get("NETWORKX_AUTOMATIC_BACKENDS", ""),
+            )
+        )
+    )
+    backend_priority.generators = _comma_sep_to_list(priorities.pop("generators", ""))
+    for key in sorted(priorities):
+        backend_priority[key] = _comma_sep_to_list(priorities[key])
+
+    return config
+
+
+def _do_nothing():
+    """This does nothing at all, yet it helps turn ``_dispatchable`` into functions.
+
+    Use this with the ``argmap`` decorator to turn ``self`` into a function. It results
+    in some small additional overhead compared to calling ``_dispatchable`` directly,
+    but ``argmap`` has the property that it can stack with other ``argmap``
+    decorators "for free". Being a function is better for REPRs and type-checkers.
+    """
+
+
+def _always_run(name, args, kwargs):
+    return True
+
+
+def _load_backend(backend_name):
+    if backend_name in _loaded_backends:
+        return _loaded_backends[backend_name]
+    if backend_name not in backends:
+        raise ImportError(f"'{backend_name}' backend is not installed")
+    rv = _loaded_backends[backend_name] = backends[backend_name].load()
+    if not hasattr(rv, "can_run"):
+        rv.can_run = _always_run
+    if not hasattr(rv, "should_run"):
+        rv.should_run = _always_run
+    return rv
+
+
+class _dispatchable:
+    _is_testing = False
+
+    def __new__(
+        cls,
+        func=None,
+        *,
+        name=None,
+        graphs="G",
+        edge_attrs=None,
+        node_attrs=None,
+        preserve_edge_attrs=False,
+        preserve_node_attrs=False,
+        preserve_graph_attrs=False,
+        preserve_all_attrs=False,
+        mutates_input=False,
+        returns_graph=False,
+        implemented_by_nx=True,
+    ):
+        """A decorator function that is used to redirect the execution of ``func``
+        function to its backend implementation.
+
+        This decorator allows the function to dispatch to different backend
+        implementations based on the input graph types, and also manages the
+        extra keywords ``backend`` and ``**backend_kwargs``.
+        Usage can be any of the following decorator forms:
+
+        - ``@_dispatchable``
+        - ``@_dispatchable()``
+        - ``@_dispatchable(name="override_name")``
+        - ``@_dispatchable(graphs="graph_var_name")``
+        - ``@_dispatchable(edge_attrs="weight")``
+        - ``@_dispatchable(graphs={"G": 0, "H": 1}, edge_attrs={"weight": "default"})``
+            with 0 and 1 giving the position in the signature function for graph
+            objects. When ``edge_attrs`` is a dict, keys are keyword names and values
+            are defaults.
+
+        Parameters
+        ----------
+        func : callable, optional (default: None)
+            The function to be decorated. If None, ``_dispatchable`` returns a
+            partial object that can be used to decorate a function later. If ``func``
+            is a callable, returns a new callable object that dispatches to a backend
+            function based on input graph types.
+
+        name : str, optional (default: name of `func`)
+            The dispatch name for the function. It defaults to the name of `func`,
+            but can be set manually to avoid conflicts in the global dispatch
+            namespace. A common pattern is to prefix the function name with its
+            module or submodule to make it unique. For example:
+
+                - ``@_dispatchable(name="tournament_is_strongly_connected")``
+                  resolves conflict between ``nx.tournament.is_strongly_connected``
+                  and ``nx.is_strongly_connected``.
+                - ``@_dispatchable(name="approximate_node_connectivity")``
+                  resolves conflict between ``nx.approximation.node_connectivity``
+                  and ``nx.connectivity.node_connectivity``.
+
+        graphs : str or dict or None, optional (default: "G")
+            If a string, the parameter name of the graph, which must be the first
+            argument of the wrapped function. If more than one graph is required
+            for the function (or if the graph is not the first argument), provide
+            a dict keyed by graph parameter name to the value parameter position.
+            A question mark in the name indicates an optional argument.
+            For example, ``@_dispatchable(graphs={"G": 0, "auxiliary?": 4})``
+            indicates the 0th parameter ``G`` of the function is a required graph,
+            and the 4th parameter ``auxiliary?`` is an optional graph.
+            To indicate that an argument is a list of graphs, do ``"[graphs]"``.
+            Use ``graphs=None``, if *no* arguments are NetworkX graphs such as for
+            graph generators, readers, and conversion functions.
+
+        edge_attrs : str or dict, optional (default: None)
+            ``edge_attrs`` holds information about edge attribute arguments
+            and default values for those edge attributes.
+            If a string, ``edge_attrs`` holds the function argument name that
+            indicates a single edge attribute to include in the converted graph.
+            The default value for this attribute is 1. To indicate that an argument
+            is a list of attributes (all with default value 1), use e.g. ``"[attrs]"``.
+            If a dict, ``edge_attrs`` holds a dict keyed by argument names, with
+            values that are either the default value or, if a string, the argument
+            name that indicates the default value.
+            If None, function does not use edge attributes.
+
+        node_attrs : str or dict, optional
+            Like ``edge_attrs``, but for node attributes.
+
+        preserve_edge_attrs : bool or str or dict, optional (default: False)
+            If bool, whether to preserve all edge attributes.
+            If a string, the parameter name that may indicate (with ``True`` or a
+            callable argument) whether all edge attributes should be preserved
+            when converting graphs to a backend graph type.
+            If a dict of form ``{graph_name: {attr: default}}``, indicate
+            pre-determined edge attributes (and defaults) to preserve for the
+            indicated input graph.
+
+        preserve_node_attrs : bool or str or dict, optional (default: False)
+            Like ``preserve_edge_attrs``, but for node attributes.
+
+        preserve_graph_attrs : bool or set, optional (default: False)
+            If bool, whether to preserve all graph attributes.
+            If set, which input graph arguments to preserve graph attributes.
+
+        preserve_all_attrs : bool, optional (default: False)
+            Whether to preserve all edge, node and graph attributes.
+            If True, this overrides all the other preserve_*_attrs.
+
+        mutates_input : bool or dict, optional (default: False)
+            If bool, whether the function mutates an input graph argument.
+            If dict of ``{arg_name: arg_pos}``, name and position of bool arguments
+            that indicate whether an input graph will be mutated, and ``arg_name``
+            may begin with ``"not "`` to negate the logic (for example, ``"not copy"``
+            means we mutate the input graph when the ``copy`` argument is False).
+            By default, dispatching doesn't convert input graphs to a different
+            backend for functions that mutate input graphs.
+
+        returns_graph : bool, optional (default: False)
+            Whether the function can return or yield a graph object. By default,
+            dispatching doesn't convert input graphs to a different backend for
+            functions that return graphs.
+
+        implemented_by_nx : bool, optional (default: True)
+            Whether the function is implemented by NetworkX. If it is not, then the
+            function is included in NetworkX only as an API to dispatch to backends.
+            Default is True.
+        """
+        if func is None:
+            return partial(
+                _dispatchable,
+                name=name,
+                graphs=graphs,
+                edge_attrs=edge_attrs,
+                node_attrs=node_attrs,
+                preserve_edge_attrs=preserve_edge_attrs,
+                preserve_node_attrs=preserve_node_attrs,
+                preserve_graph_attrs=preserve_graph_attrs,
+                preserve_all_attrs=preserve_all_attrs,
+                mutates_input=mutates_input,
+                returns_graph=returns_graph,
+                implemented_by_nx=implemented_by_nx,
+            )
+        if isinstance(func, str):
+            raise TypeError("'name' and 'graphs' must be passed by keyword") from None
+        # If name not provided, use the name of the function
+        if name is None:
+            name = func.__name__
+
+        self = object.__new__(cls)
+
+        # standard function-wrapping stuff
+        # __annotations__ not used
+        self.__name__ = func.__name__
+        # self.__doc__ = func.__doc__  # __doc__ handled as cached property
+        self.__defaults__ = func.__defaults__
+        # Add `backend=` keyword argument to allow backend choice at call-time
+        if func.__kwdefaults__:
+            self.__kwdefaults__ = {**func.__kwdefaults__, "backend": None}
+        else:
+            self.__kwdefaults__ = {"backend": None}
+        self.__module__ = func.__module__
+        self.__qualname__ = func.__qualname__
+        self.__dict__.update(func.__dict__)
+        self.__wrapped__ = func
+
+        # Supplement docstring with backend info; compute and cache when needed
+        self._orig_doc = func.__doc__
+        self._cached_doc = None
+
+        self.orig_func = func
+        self.name = name
+        self.edge_attrs = edge_attrs
+        self.node_attrs = node_attrs
+        self.preserve_edge_attrs = preserve_edge_attrs or preserve_all_attrs
+        self.preserve_node_attrs = preserve_node_attrs or preserve_all_attrs
+        self.preserve_graph_attrs = preserve_graph_attrs or preserve_all_attrs
+        self.mutates_input = mutates_input
+        # Keep `returns_graph` private for now, b/c we may extend info on return types
+        self._returns_graph = returns_graph
+
+        if edge_attrs is not None and not isinstance(edge_attrs, str | dict):
+            raise TypeError(
+                f"Bad type for edge_attrs: {type(edge_attrs)}. Expected str or dict."
+            ) from None
+        if node_attrs is not None and not isinstance(node_attrs, str | dict):
+            raise TypeError(
+                f"Bad type for node_attrs: {type(node_attrs)}. Expected str or dict."
+            ) from None
+        if not isinstance(self.preserve_edge_attrs, bool | str | dict):
+            raise TypeError(
+                f"Bad type for preserve_edge_attrs: {type(self.preserve_edge_attrs)}."
+                " Expected bool, str, or dict."
+            ) from None
+        if not isinstance(self.preserve_node_attrs, bool | str | dict):
+            raise TypeError(
+                f"Bad type for preserve_node_attrs: {type(self.preserve_node_attrs)}."
+                " Expected bool, str, or dict."
+            ) from None
+        if not isinstance(self.preserve_graph_attrs, bool | set):
+            raise TypeError(
+                f"Bad type for preserve_graph_attrs: {type(self.preserve_graph_attrs)}."
+                " Expected bool or set."
+            ) from None
+        if not isinstance(self.mutates_input, bool | dict):
+            raise TypeError(
+                f"Bad type for mutates_input: {type(self.mutates_input)}."
+                " Expected bool or dict."
+            ) from None
+        if not isinstance(self._returns_graph, bool):
+            raise TypeError(
+                f"Bad type for returns_graph: {type(self._returns_graph)}."
+                " Expected bool."
+            ) from None
+
+        if isinstance(graphs, str):
+            graphs = {graphs: 0}
+        elif graphs is None:
+            pass
+        elif not isinstance(graphs, dict):
+            raise TypeError(
+                f"Bad type for graphs: {type(graphs)}. Expected str or dict."
+            ) from None
+        elif len(graphs) == 0:
+            raise KeyError("'graphs' must contain at least one variable name") from None
+
+        # This dict comprehension is complicated for better performance; equivalent shown below.
+        self.optional_graphs = set()
+        self.list_graphs = set()
+        if graphs is None:
+            self.graphs = {}
+        else:
+            self.graphs = {
+                self.optional_graphs.add(val := k[:-1]) or val
+                if (last := k[-1]) == "?"
+                else self.list_graphs.add(val := k[1:-1]) or val
+                if last == "]"
+                else k: v
+                for k, v in graphs.items()
+            }
+        # The above is equivalent to:
+        # self.optional_graphs = {k[:-1] for k in graphs if k[-1] == "?"}
+        # self.list_graphs = {k[1:-1] for k in graphs if k[-1] == "]"}
+        # self.graphs = {k[:-1] if k[-1] == "?" else k: v for k, v in graphs.items()}
+
+        # Compute and cache the signature on-demand
+        self._sig = None
+
+        # Which backends implement this function?
+        self.backends = {
+            backend
+            for backend, info in backend_info.items()
+            if "functions" in info and name in info["functions"]
+        }
+        if implemented_by_nx:
+            self.backends.add("networkx")
+
+        if name in _registered_algorithms:
+            raise KeyError(
+                f"Algorithm already exists in dispatch namespace: {name}. "
+                "Fix by assigning a unique `name=` in the `@_dispatchable` decorator."
+            ) from None
+        # Use the `argmap` decorator to turn `self` into a function. This does result
+        # in small additional overhead compared to calling `_dispatchable` directly,
+        # but `argmap` has the property that it can stack with other `argmap`
+        # decorators "for free". Being a function is better for REPRs and type-checkers.
+        # It also allows `_dispatchable` to be used on class methods, since functions
+        # define `__get__`. Without using `argmap`, we would need to define `__get__`.
+        self = argmap(_do_nothing)(self)
+        _registered_algorithms[name] = self
+        return self
+
+    @property
+    def __doc__(self):
+        """If the cached documentation exists, it is returned.
+        Otherwise, the documentation is generated using _make_doc() method,
+        cached, and then returned."""
+
+        rv = self._cached_doc
+        if rv is None:
+            rv = self._cached_doc = self._make_doc()
+        return rv
+
+    @__doc__.setter
+    def __doc__(self, val):
+        """Sets the original documentation to the given value and resets the
+        cached documentation."""
+
+        self._orig_doc = val
+        self._cached_doc = None
+
+    @property
+    def __signature__(self):
+        """Return the signature of the original function, with the addition of
+        the `backend` and `backend_kwargs` parameters."""
+
+        if self._sig is None:
+            sig = inspect.signature(self.orig_func)
+            # `backend` is now a reserved argument used by dispatching.
+            # assert "backend" not in sig.parameters
+            if not any(
+                p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values()
+            ):
+                sig = sig.replace(
+                    parameters=[
+                        *sig.parameters.values(),
+                        inspect.Parameter(
+                            "backend", inspect.Parameter.KEYWORD_ONLY, default=None
+                        ),
+                        inspect.Parameter(
+                            "backend_kwargs", inspect.Parameter.VAR_KEYWORD
+                        ),
+                    ]
+                )
+            else:
+                *parameters, var_keyword = sig.parameters.values()
+                sig = sig.replace(
+                    parameters=[
+                        *parameters,
+                        inspect.Parameter(
+                            "backend", inspect.Parameter.KEYWORD_ONLY, default=None
+                        ),
+                        var_keyword,
+                    ]
+                )
+            self._sig = sig
+        return self._sig
+
+    # Fast, simple path if no backends are installed
+    def _call_if_no_backends_installed(self, /, *args, backend=None, **kwargs):
+        """Returns the result of the original function (no backends installed)."""
+        if backend is not None and backend != "networkx":
+            raise ImportError(f"'{backend}' backend is not installed")
+        if "networkx" not in self.backends:
+            raise NotImplementedError(
+                f"'{self.name}' is not implemented by 'networkx' backend. "
+                "This function is included in NetworkX as an API to dispatch to "
+                "other backends."
+            )
+        return self.orig_func(*args, **kwargs)
+
+    # Dispatch to backends based on inputs, `backend=` arg, or configuration
+    def _call_if_any_backends_installed(self, /, *args, backend=None, **kwargs):
+        """Returns the result of the original function, or the backend function if
+        the backend is specified and that backend implements `func`."""
+        # Use `backend_name` in this function instead of `backend`.
+        # This is purely for aesthetics and to make it easier to search for this
+        # variable since "backend" is used in many comments and log/error messages.
+        backend_name = backend
+        if backend_name is not None and backend_name not in backend_info:
+            raise ImportError(f"'{backend_name}' backend is not installed")
+
+        graphs_resolved = {}
+        for gname, pos in self.graphs.items():
+            if pos < len(args):
+                if gname in kwargs:
+                    raise TypeError(f"{self.name}() got multiple values for {gname!r}")
+                graph = args[pos]
+            elif gname in kwargs:
+                graph = kwargs[gname]
+            elif gname not in self.optional_graphs:
+                raise TypeError(
+                    f"{self.name}() missing required graph argument: {gname}"
+                )
+            else:
+                continue
+            if graph is None:
+                if gname not in self.optional_graphs:
+                    raise TypeError(
+                        f"{self.name}() required graph argument {gname!r} is None; must be a graph"
+                    )
+            else:
+                graphs_resolved[gname] = graph
+
+        # Alternative to the above that does not check duplicated args or missing required graphs.
+        # graphs_resolved = {
+        #     gname: graph
+        #     for gname, pos in self.graphs.items()
+        #     if (graph := args[pos] if pos < len(args) else kwargs.get(gname)) is not None
+        # }
+
+        # Check if any graph comes from a backend
+        if self.list_graphs:
+            # Make sure we don't lose values by consuming an iterator
+            args = list(args)
+            for gname in self.list_graphs & graphs_resolved.keys():
+                list_of_graphs = list(graphs_resolved[gname])
+                graphs_resolved[gname] = list_of_graphs
+                if gname in kwargs:
+                    kwargs[gname] = list_of_graphs
+                else:
+                    args[self.graphs[gname]] = list_of_graphs
+
+            graph_backend_names = {
+                getattr(g, "__networkx_backend__", None)
+                for gname, g in graphs_resolved.items()
+                if gname not in self.list_graphs
+            }
+            for gname in self.list_graphs & graphs_resolved.keys():
+                graph_backend_names.update(
+                    getattr(g, "__networkx_backend__", None)
+                    for g in graphs_resolved[gname]
+                )
+        else:
+            graph_backend_names = {
+                getattr(g, "__networkx_backend__", None)
+                for g in graphs_resolved.values()
+            }
+
+        backend_priority = nx.config.backend_priority.get(
+            self.name,
+            nx.config.backend_priority.classes
+            if self.name.endswith("__new__")
+            else nx.config.backend_priority.generators
+            if self._returns_graph
+            else nx.config.backend_priority.algos,
+        )
+        fallback_to_nx = nx.config.fallback_to_nx and "networkx" in self.backends
+        if self._is_testing and backend_priority and backend_name is None:
+            # Special path if we are running networkx tests with a backend.
+            # This even runs for (and handles) functions that mutate input graphs.
+            return self._convert_and_call_for_tests(
+                backend_priority[0],
+                args,
+                kwargs,
+                fallback_to_nx=fallback_to_nx,
+            )
+
+        graph_backend_names.discard(None)
+        if backend_name is not None:
+            # Must run with the given backend.
+            # `can_run` only used for better log and error messages.
+            # Check `mutates_input` for logging, not behavior.
+            backend_kwarg_msg = (
+                "No other backends will be attempted, because the backend was "
+                f"specified with the `backend='{backend_name}'` keyword argument."
+            )
+            extra_message = (
+                f"'{backend_name}' backend raised NotImplementedError when calling "
+                f"'{self.name}'. {backend_kwarg_msg}"
+            )
+            if not graph_backend_names or graph_backend_names == {backend_name}:
+                # All graphs are backend graphs--no need to convert!
+                if self._can_backend_run(backend_name, args, kwargs):
+                    return self._call_with_backend(
+                        backend_name, args, kwargs, extra_message=extra_message
+                    )
+                if self._does_backend_have(backend_name):
+                    extra = " for the given arguments"
+                else:
+                    extra = ""
+                raise NotImplementedError(
+                    f"'{self.name}' is not implemented by '{backend_name}' backend"
+                    f"{extra}. {backend_kwarg_msg}"
+                )
+            if self._can_convert(backend_name, graph_backend_names):
+                if self._can_backend_run(backend_name, args, kwargs):
+                    if self._will_call_mutate_input(args, kwargs):
+                        _logger.debug(
+                            "'%s' will mutate an input graph. This prevents automatic conversion "
+                            "to, and use of, backends listed in `nx.config.backend_priority`. "
+                            "Using backend specified by the "
+                            "`backend='%s'` keyword argument. This may change behavior by not "
+                            "mutating inputs.",
+                            self.name,
+                            backend_name,
+                        )
+                        mutations = []
+                    else:
+                        mutations = None
+                    rv = self._convert_and_call(
+                        backend_name,
+                        graph_backend_names,
+                        args,
+                        kwargs,
+                        extra_message=extra_message,
+                        mutations=mutations,
+                    )
+                    if mutations:
+                        for cache, key in mutations:
+                            # If the call mutates inputs, then remove all inputs gotten
+                            # from cache. We do this after all conversions (and call) so
+                            # that a graph can be gotten from a cache multiple times.
+                            cache.pop(key, None)
+                    return rv
+                if self._does_backend_have(backend_name):
+                    extra = " for the given arguments"
+                else:
+                    extra = ""
+                raise NotImplementedError(
+                    f"'{self.name}' is not implemented by '{backend_name}' backend"
+                    f"{extra}. {backend_kwarg_msg}"
+                )
+            if len(graph_backend_names) == 1:
+                maybe_s = ""
+                graph_backend_names = f"'{next(iter(graph_backend_names))}'"
+            else:
+                maybe_s = "s"
+            raise TypeError(
+                f"'{self.name}' is unable to convert graph from backend{maybe_s} "
+                f"{graph_backend_names} to '{backend_name}' backend, which was "
+                f"specified with the `backend='{backend_name}'` keyword argument. "
+                f"{backend_kwarg_msg}"
+            )
+
+        if self._will_call_mutate_input(args, kwargs):
+            # The current behavior for functions that mutate input graphs:
+            #
+            # 1. If backend is specified by `backend=` keyword, use it (done above).
+            # 2. If inputs are from one backend, try to use it.
+            # 3. If all input graphs are instances of `nx.Graph`, then run with the
+            #    default "networkx" implementation.
+            #
+            # Do not automatically convert if a call will mutate inputs, because doing
+            # so would change behavior. Hence, we should fail if there are multiple input
+            # backends or if the input backend does not implement the function. However,
+            # we offer a way for backends to circumvent this if they do not implement
+            # this function: we will fall back to the default "networkx" implementation
+            # without using conversions if all input graphs are subclasses of `nx.Graph`.
+            mutate_msg = (
+                "conversions between backends (if configured) will not be attempted "
+                "because the original input graph would not be mutated. Using the "
+                "backend keyword e.g. `backend='some_backend'` will force conversions "
+                "and not mutate the original input graph."
+            )
+            fallback_msg = (
+                "This call will mutate inputs, so fall back to 'networkx' "
+                "backend (without converting) since all input graphs are "
+                "instances of nx.Graph and are hopefully compatible."
+            )
+            if len(graph_backend_names) == 1:
+                [backend_name] = graph_backend_names
+                msg_template = (
+                    f"Backend '{backend_name}' does not implement '{self.name}'%s. "
+                    f"This call will mutate an input, so automatic {mutate_msg}"
+                )
+                # `can_run` is only used for better log and error messages
+                try:
+                    if self._can_backend_run(backend_name, args, kwargs):
+                        return self._call_with_backend(
+                            backend_name,
+                            args,
+                            kwargs,
+                            extra_message=msg_template % " with these arguments",
+                        )
+                except NotImplementedError as exc:
+                    if all(isinstance(g, nx.Graph) for g in graphs_resolved.values()):
+                        _logger.debug(
+                            "Backend '%s' raised when calling '%s': %s. %s",
+                            backend_name,
+                            self.name,
+                            exc,
+                            fallback_msg,
+                        )
+                    else:
+                        raise
+                else:
+                    if fallback_to_nx and all(
+                        # Consider dropping the `isinstance` check here to allow
+                        # duck-type graphs, but let's wait for a backend to ask us.
+                        isinstance(g, nx.Graph)
+                        for g in graphs_resolved.values()
+                    ):
+                        # Log that we are falling back to networkx
+                        _logger.debug(
+                            "Backend '%s' can't run '%s'. %s",
+                            backend_name,
+                            self.name,
+                            fallback_msg,
+                        )
+                    else:
+                        if self._does_backend_have(backend_name):
+                            extra = " with these arguments"
+                        else:
+                            extra = ""
+                        raise NotImplementedError(msg_template % extra)
+            elif fallback_to_nx and all(
+                # Consider dropping the `isinstance` check here to allow
+                # duck-type graphs, but let's wait for a backend to ask us.
+                isinstance(g, nx.Graph)
+                for g in graphs_resolved.values()
+            ):
+                # Log that we are falling back to networkx
+                _logger.debug(
+                    "'%s' was called with inputs from multiple backends: %s. %s",
+                    self.name,
+                    graph_backend_names,
+                    fallback_msg,
+                )
+            else:
+                raise RuntimeError(
+                    f"'{self.name}' will mutate an input, but it was called with "
+                    f"inputs from multiple backends: {graph_backend_names}. "
+                    f"Automatic {mutate_msg}"
+                )
+            # At this point, no backends are available to handle the call with
+            # the input graph types, but if the input graphs are compatible
+            # nx.Graph instances, fall back to networkx without converting.
+            return self.orig_func(*args, **kwargs)
+
+        # We may generalize fallback configuration as e.g. `nx.config.backend_fallback`
+        if fallback_to_nx or not graph_backend_names:
+            # Use "networkx" by default if there are no inputs from backends.
+            # For example, graph generators should probably return NetworkX graphs
+            # instead of raising NotImplementedError.
+            backend_fallback = ["networkx"]
+        else:
+            backend_fallback = []
+
+        # ##########################
+        # # How this behaves today #
+        # ##########################
+        #
+        # The prose below describes the implementation and a *possible* way to
+        # generalize "networkx" as "just another backend". The code is structured
+        # to perhaps someday support backend-to-backend conversions (including
+        # simply passing objects from one backend directly to another backend;
+        # the dispatch machinery does not necessarily need to perform conversions),
+        # but since backend-to-backend matching is not yet supported, the following
+        # code is merely a convenient way to implement dispatch behaviors that have
+        # been carefully developed since NetworkX 3.0 and to include falling back
+        # to the default NetworkX implementation.
+        #
+        # The current behavior for functions that don't mutate input graphs:
+        #
+        # 1. If backend is specified by `backend=` keyword, use it (done above).
+        # 2. If input is from a backend other than "networkx", try to use it.
+        #    - Note: if present, "networkx" graphs will be converted to the backend.
+        # 3. If input is from "networkx" (or no backend), try to use backends from
+        #    `backend_priority` before running with the default "networkx" implementation.
+        # 4. If configured, "fall back" and run with the default "networkx" implementation.
+        #
+        # ################################################
+        # # How this is implemented and may work someday #
+        # ################################################
+        #
+        # Let's determine the order of backends we should try according
+        # to `backend_priority`, `backend_fallback`, and input backends.
+        # There are two† dimensions of priorities to consider:
+        #   backend_priority > unspecified > backend_fallback
+        # and
+        #   backend of an input > not a backend of an input
+        # These are combined to form five groups of priorities as such:
+        #
+        #                    input   ~input
+        #                  +-------+-------+
+        # backend_priority |   1   |   2   |
+        #      unspecified |   3   |  N/A  | (if only 1)
+        # backend_fallback |   4   |   5   |
+        #                  +-------+-------+
+        #
+        # This matches the behaviors we developed in versions 3.0 to 3.2, it
+        # ought to cover virtually all use cases we expect, and I (@eriknw) don't
+        # think it can be done any simpler (although it can be generalized further
+        # and made to be more complicated to capture 100% of *possible* use cases).
+        # Some observations:
+        #
+        #   1. If an input is in `backend_priority`, it will be used before trying a
+        #      backend that is higher priority in `backend_priority` and not an input.
+        #   2. To prioritize converting from one backend to another even if both implement
+        #      a function, list one in `backend_priority` and one in `backend_fallback`.
+        #   3. To disable conversions, set `backend_priority` and `backend_fallback` to [].
+        #
+        # †: There is actually a third dimension of priorities:
+        #        should_run == True > should_run == False
+        #    Backends with `can_run == True` and `should_run == False` are tried last.
+        #
+        seen = set()
+        group1 = []  # In backend_priority, and an input
+        group2 = []  # In backend_priority, but not an input
+        for name in backend_priority:
+            if name in seen:
+                continue
+            seen.add(name)
+            if name in graph_backend_names:
+                group1.append(name)
+            else:
+                group2.append(name)
+        group4 = []  # In backend_fallback, and an input
+        group5 = []  # In backend_fallback, but not an input
+        for name in backend_fallback:
+            if name in seen:
+                continue
+            seen.add(name)
+            if name in graph_backend_names:
+                group4.append(name)
+            else:
+                group5.append(name)
+        # An input, but not in backend_priority or backend_fallback.
+        group3 = graph_backend_names - seen
+        if len(group3) > 1:
+            # `group3` backends are not configured for automatic conversion or fallback.
+            # There are at least two issues if this group contains multiple backends:
+            #
+            #   1. How should we prioritize them? We have no good way to break ties.
+            #      Although we could arbitrarily choose alphabetical or left-most,
+            #      let's follow the Zen of Python and refuse the temptation to guess.
+            #   2. We probably shouldn't automatically convert to these backends,
+            #      because we are not configured to do so.
+            #
+            # (2) is important to allow disabling all conversions by setting both
+            # `nx.config.backend_priority` and `nx.config.backend_fallback` to [].
+            #
+            # If there is a single backend in `group3`, then giving it priority over
+            # the fallback backends is what is generally expected. For example, this
+            # allows input graphs of `backend_fallback` backends (such as "networkx")
+            # to be converted to, and run with, the unspecified backend.
+            _logger.debug(
+                "Call to '%s' has inputs from multiple backends, %s, that "
+                "have no priority set in `nx.config.backend_priority`, "
+                "so automatic conversions to "
+                "these backends will not be attempted.",
+                self.name,
+                group3,
+            )
+            group3 = ()
+
+        try_order = list(itertools.chain(group1, group2, group3, group4, group5))
+        if len(try_order) > 1:
+            # Should we consider adding an option for more verbose logging?
+            # For example, we could explain the order of `try_order` in detail.
+            _logger.debug(
+                "Call to '%s' has inputs from %s backends, and will try to use "
+                "backends in the following order: %s",
+                self.name,
+                graph_backend_names or "no",
+                try_order,
+            )
+        backends_to_try_again = []
+        for is_not_first, backend_name in enumerate(try_order):
+            if is_not_first:
+                _logger.debug("Trying next backend: '%s'", backend_name)
+            try:
+                if not graph_backend_names or graph_backend_names == {backend_name}:
+                    if self._can_backend_run(backend_name, args, kwargs):
+                        return self._call_with_backend(backend_name, args, kwargs)
+                elif self._can_convert(
+                    backend_name, graph_backend_names
+                ) and self._can_backend_run(backend_name, args, kwargs):
+                    if self._should_backend_run(backend_name, args, kwargs):
+                        rv = self._convert_and_call(
+                            backend_name, graph_backend_names, args, kwargs
+                        )
+                        if (
+                            self._returns_graph
+                            and graph_backend_names
+                            and backend_name not in graph_backend_names
+                        ):
+                            # If the function has graph inputs and graph output, we try
+                            # to make it so the backend of the return type will match the
+                            # backend of the input types. In case this is not possible,
+                            # let's tell the user that the backend of the return graph
+                            # has changed. Perhaps we could try to convert back, but
+                            # "fallback" backends for graph generators should typically
+                            # be compatible with NetworkX graphs.
+                            _logger.debug(
+                                "Call to '%s' is returning a graph from a different "
+                                "backend! It has inputs from %s backends, but ran with "
+                                "'%s' backend and is returning graph from '%s' backend",
+                                self.name,
+                                graph_backend_names,
+                                backend_name,
+                                backend_name,
+                            )
+                        return rv
+                    # `should_run` is False, but `can_run` is True, so try again later
+                    backends_to_try_again.append(backend_name)
+            except NotImplementedError as exc:
+                _logger.debug(
+                    "Backend '%s' raised when calling '%s': %s",
+                    backend_name,
+                    self.name,
+                    exc,
+                )
+
+        # We are about to fail. Let's try backends with can_run=True and should_run=False.
+        # This is unlikely to help today since we try to run with "networkx" before this.
+        for backend_name in backends_to_try_again:
+            _logger.debug(
+                "Trying backend: '%s' (ignoring `should_run=False`)", backend_name
+            )
+            try:
+                rv = self._convert_and_call(
+                    backend_name, graph_backend_names, args, kwargs
+                )
+                if (
+                    self._returns_graph
+                    and graph_backend_names
+                    and backend_name not in graph_backend_names
+                ):
+                    _logger.debug(
+                        "Call to '%s' is returning a graph from a different "
+                        "backend! It has inputs from %s backends, but ran with "
+                        "'%s' backend and is returning graph from '%s' backend",
+                        self.name,
+                        graph_backend_names,
+                        backend_name,
+                        backend_name,
+                    )
+                return rv
+            except NotImplementedError as exc:
+                _logger.debug(
+                    "Backend '%s' raised when calling '%s': %s",
+                    backend_name,
+                    self.name,
+                    exc,
+                )
+        # As a final effort, we could try to convert and run with `group3` backends
+        # that we discarded when `len(group3) > 1`, but let's not consider doing
+        # so until there is a reasonable request for it.
+
+        if len(unspecified_backends := graph_backend_names - seen) > 1:
+            raise TypeError(
+                f"Unable to convert inputs from {graph_backend_names} backends and "
+                f"run '{self.name}'. NetworkX is configured to automatically convert "
+                f"to {try_order} backends. To remedy this, you may enable automatic "
+                f"conversion to {unspecified_backends} backends by adding them to "
+                "`nx.config.backend_priority`, or you "
+                "may specify a backend to use with the `backend=` keyword argument."
+            )
+        if "networkx" not in self.backends:
+            extra = (
+                " This function is included in NetworkX as an API to dispatch to "
+                "other backends."
+            )
+        else:
+            extra = ""
+        raise NotImplementedError(
+            f"'{self.name}' is not implemented by {try_order} backends. To remedy "
+            "this, you may enable automatic conversion to more backends (including "
+            "'networkx') by adding them to `nx.config.backend_priority`, "
+            "or you may specify a backend to use with "
+            f"the `backend=` keyword argument.{extra}"
+        )
+
+    # Dispatch only if there exist any installed backend(s)
+    __call__: typing.Callable = (
+        _call_if_any_backends_installed if backends else _call_if_no_backends_installed
+    )
+
+    def _will_call_mutate_input(self, args, kwargs):
+        # Fairly few nx functions mutate the input graph. Most that do, always do.
+        # So a boolean input indicates "always" or "never".
+        if isinstance((mutates_input := self.mutates_input), bool):
+            return mutates_input
+
+        # The ~10 other nx functions either use "copy=True" to control mutation or
+        # an arg naming an edge/node attribute to mutate (None means no mutation).
+        # Now `mutates_input` is a dict keyed by arg_name to its func-sig position.
+        # The `copy=` args are keyed as "not copy" to mean "negate the copy argument".
+        # Keys w/o "not " mean the call mutates only when the arg value `is not None`.
+        #
+        # This section might need different code if new functions mutate in new ways.
+        #
+        # NetworkX doesn't have any `mutates_input` dicts with more than 1 item.
+        # But we treat it like it might have more than 1 item for generality.
+        n = len(args)
+        return any(
+            (args[arg_pos] if n > arg_pos else kwargs.get(arg_name)) is not None
+            if not arg_name.startswith("not ")
+            # This assumes that e.g. `copy=True` is the default
+            else not (args[arg_pos] if n > arg_pos else kwargs.get(arg_name[4:], True))
+            for arg_name, arg_pos in mutates_input.items()
+        )
+
+    def _can_convert(self, backend_name, graph_backend_names):
+        # Backend-to-backend conversion not supported yet.
+        # We can only convert to and from networkx.
+        rv = backend_name == "networkx" or graph_backend_names.issubset(
+            {"networkx", backend_name}
+        )
+        if not rv:
+            _logger.debug(
+                "Unable to convert from %s backends to '%s' backend",
+                graph_backend_names,
+                backend_name,
+            )
+        return rv
+
+    def _does_backend_have(self, backend_name):
+        """Does the specified backend have this algorithm?"""
+        if backend_name == "networkx":
+            return "networkx" in self.backends
+        # Inspect the backend; don't trust metadata used to create `self.backends`
+        backend = _load_backend(backend_name)
+        return hasattr(backend, self.name)
+
+    def _can_backend_run(self, backend_name, args, kwargs):
+        """Can the specified backend run this algorithm with these arguments?"""
+        if backend_name == "networkx":
+            return "networkx" in self.backends
+        backend = _load_backend(backend_name)
+        # `backend.can_run` and `backend.should_run` may return strings that describe
+        # why they can't or shouldn't be run.
+        if not hasattr(backend, self.name):
+            _logger.debug(
+                "Backend '%s' does not implement '%s'", backend_name, self.name
+            )
+            return False
+        can_run = backend.can_run(self.name, args, kwargs)
+        if isinstance(can_run, str) or not can_run:
+            reason = f", because: {can_run}" if isinstance(can_run, str) else ""
+            _logger.debug(
+                "Backend '%s' can't run `%s` with arguments: %s%s",
+                backend_name,
+                self.name,
+                _LazyArgsRepr(self, args, kwargs),
+                reason,
+            )
+            return False
+        return True
+
+    def _should_backend_run(self, backend_name, args, kwargs):
+        """Should the specified backend run this algorithm with these arguments?
+
+        Note that this does not check ``backend.can_run``.
+        """
+        # `backend.can_run` and `backend.should_run` may return strings that describe
+        # why they can't or shouldn't be run.
+        # `_should_backend_run` may assume that `_can_backend_run` returned True.
+        if backend_name == "networkx":
+            return True
+        backend = _load_backend(backend_name)
+        should_run = backend.should_run(self.name, args, kwargs)
+        if isinstance(should_run, str) or not should_run:
+            reason = f", because: {should_run}" if isinstance(should_run, str) else ""
+            _logger.debug(
+                "Backend '%s' shouldn't run `%s` with arguments: %s%s",
+                backend_name,
+                self.name,
+                _LazyArgsRepr(self, args, kwargs),
+                reason,
+            )
+            return False
+        return True
+
+    def _convert_arguments(self, backend_name, args, kwargs, *, use_cache, mutations):
+        """Convert graph arguments to the specified backend.
+
+        Returns
+        -------
+        args tuple and kwargs dict
+        """
+        bound = self.__signature__.bind(*args, **kwargs)
+        bound.apply_defaults()
+        if not self.graphs:
+            bound_kwargs = bound.kwargs
+            del bound_kwargs["backend"]
+            return bound.args, bound_kwargs
+        if backend_name == "networkx":
+            # `backend_interface.convert_from_nx` preserves everything
+            preserve_edge_attrs = preserve_node_attrs = preserve_graph_attrs = True
+        else:
+            preserve_edge_attrs = self.preserve_edge_attrs
+            preserve_node_attrs = self.preserve_node_attrs
+            preserve_graph_attrs = self.preserve_graph_attrs
+            edge_attrs = self.edge_attrs
+            node_attrs = self.node_attrs
+        # Convert graphs into backend graph-like object
+        # Include the edge and/or node labels if provided to the algorithm
+        if preserve_edge_attrs is False:
+            # e.g. `preserve_edge_attrs=False`
+            pass
+        elif preserve_edge_attrs is True:
+            # e.g. `preserve_edge_attrs=True`
+            edge_attrs = None
+        elif isinstance(preserve_edge_attrs, str):
+            if bound.arguments[preserve_edge_attrs] is True or callable(
+                bound.arguments[preserve_edge_attrs]
+            ):
+                # e.g. `preserve_edge_attrs="attr"` and `func(attr=True)`
+                # e.g. `preserve_edge_attrs="attr"` and `func(attr=myfunc)`
+                preserve_edge_attrs = True
+                edge_attrs = None
+            elif bound.arguments[preserve_edge_attrs] is False and (
+                isinstance(edge_attrs, str)
+                and edge_attrs == preserve_edge_attrs
+                or isinstance(edge_attrs, dict)
+                and preserve_edge_attrs in edge_attrs
+            ):
+                # e.g. `preserve_edge_attrs="attr"` and `func(attr=False)`
+                # Treat `False` argument as meaning "preserve_edge_data=False"
+                # and not `False` as the edge attribute to use.
+                preserve_edge_attrs = False
+                edge_attrs = None
+            else:
+                # e.g. `preserve_edge_attrs="attr"` and `func(attr="weight")`
+                preserve_edge_attrs = False
+        # Else: e.g. `preserve_edge_attrs={"G": {"weight": 1}}`
+
+        if edge_attrs is None:
+            # May have been set to None above b/c all attributes are preserved
+            pass
+        elif isinstance(edge_attrs, str):
+            if edge_attrs[0] == "[":
+                # e.g. `edge_attrs="[edge_attributes]"` (argument of list of attributes)
+                # e.g. `func(edge_attributes=["foo", "bar"])`
+                edge_attrs = {
+                    edge_attr: 1 for edge_attr in bound.arguments[edge_attrs[1:-1]]
+                }
+            elif callable(bound.arguments[edge_attrs]):
+                # e.g. `edge_attrs="weight"` and `func(weight=myfunc)`
+                preserve_edge_attrs = True
+                edge_attrs = None
+            elif bound.arguments[edge_attrs] is not None:
+                # e.g. `edge_attrs="weight"` and `func(weight="foo")` (default of 1)
+                edge_attrs = {bound.arguments[edge_attrs]: 1}
+            elif self.name == "to_numpy_array" and hasattr(
+                bound.arguments["dtype"], "names"
+            ):
+                # Custom handling: attributes may be obtained from `dtype`
+                edge_attrs = {
+                    edge_attr: 1 for edge_attr in bound.arguments["dtype"].names
+                }
+            else:
+                # e.g. `edge_attrs="weight"` and `func(weight=None)`
+                edge_attrs = None
+        else:
+            # e.g. `edge_attrs={"attr": "default"}` and `func(attr="foo", default=7)`
+            # e.g. `edge_attrs={"attr": 0}` and `func(attr="foo")`
+            edge_attrs = {
+                edge_attr: bound.arguments.get(val, 1) if isinstance(val, str) else val
+                for key, val in edge_attrs.items()
+                if (edge_attr := bound.arguments[key]) is not None
+            }
+
+        if preserve_node_attrs is False:
+            # e.g. `preserve_node_attrs=False`
+            pass
+        elif preserve_node_attrs is True:
+            # e.g. `preserve_node_attrs=True`
+            node_attrs = None
+        elif isinstance(preserve_node_attrs, str):
+            if bound.arguments[preserve_node_attrs] is True or callable(
+                bound.arguments[preserve_node_attrs]
+            ):
+                # e.g. `preserve_node_attrs="attr"` and `func(attr=True)`
+                # e.g. `preserve_node_attrs="attr"` and `func(attr=myfunc)`
+                preserve_node_attrs = True
+                node_attrs = None
+            elif bound.arguments[preserve_node_attrs] is False and (
+                isinstance(node_attrs, str)
+                and node_attrs == preserve_node_attrs
+                or isinstance(node_attrs, dict)
+                and preserve_node_attrs in node_attrs
+            ):
+                # e.g. `preserve_node_attrs="attr"` and `func(attr=False)`
+                # Treat `False` argument as meaning "preserve_node_data=False"
+                # and not `False` as the node attribute to use. Is this used?
+                preserve_node_attrs = False
+                node_attrs = None
+            else:
+                # e.g. `preserve_node_attrs="attr"` and `func(attr="weight")`
+                preserve_node_attrs = False
+        # Else: e.g. `preserve_node_attrs={"G": {"pos": None}}`
+
+        if node_attrs is None:
+            # May have been set to None above b/c all attributes are preserved
+            pass
+        elif isinstance(node_attrs, str):
+            if node_attrs[0] == "[":
+                # e.g. `node_attrs="[node_attributes]"` (argument of list of attributes)
+                # e.g. `func(node_attributes=["foo", "bar"])`
+                node_attrs = {
+                    node_attr: None for node_attr in bound.arguments[node_attrs[1:-1]]
+                }
+            elif callable(bound.arguments[node_attrs]):
+                # e.g. `node_attrs="weight"` and `func(weight=myfunc)`
+                preserve_node_attrs = True
+                node_attrs = None
+            elif bound.arguments[node_attrs] is not None:
+                # e.g. `node_attrs="weight"` and `func(weight="foo")`
+                node_attrs = {bound.arguments[node_attrs]: None}
+            else:
+                # e.g. `node_attrs="weight"` and `func(weight=None)`
+                node_attrs = None
+        else:
+            # e.g. `node_attrs={"attr": "default"}` and `func(attr="foo", default=7)`
+            # e.g. `node_attrs={"attr": 0}` and `func(attr="foo")`
+            node_attrs = {
+                node_attr: bound.arguments.get(val) if isinstance(val, str) else val
+                for key, val in node_attrs.items()
+                if (node_attr := bound.arguments[key]) is not None
+            }
+
+        # It should be safe to assume that we either have networkx graphs or backend graphs.
+        # Future work: allow conversions between backends.
+        for gname in self.graphs:
+            if gname in self.list_graphs:
+                bound.arguments[gname] = [
+                    self._convert_graph(
+                        backend_name,
+                        g,
+                        edge_attrs=edge_attrs,
+                        node_attrs=node_attrs,
+                        preserve_edge_attrs=preserve_edge_attrs,
+                        preserve_node_attrs=preserve_node_attrs,
+                        preserve_graph_attrs=preserve_graph_attrs,
+                        graph_name=gname,
+                        use_cache=use_cache,
+                        mutations=mutations,
+                    )
+                    if getattr(g, "__networkx_backend__", "networkx") != backend_name
+                    else g
+                    for g in bound.arguments[gname]
+                ]
+            else:
+                graph = bound.arguments[gname]
+                if graph is None:
+                    if gname in self.optional_graphs:
+                        continue
+                    raise TypeError(
+                        f"Missing required graph argument `{gname}` in {self.name} function"
+                    )
+                if isinstance(preserve_edge_attrs, dict):
+                    preserve_edges = False
+                    edges = preserve_edge_attrs.get(gname, edge_attrs)
+                else:
+                    preserve_edges = preserve_edge_attrs
+                    edges = edge_attrs
+                if isinstance(preserve_node_attrs, dict):
+                    preserve_nodes = False
+                    nodes = preserve_node_attrs.get(gname, node_attrs)
+                else:
+                    preserve_nodes = preserve_node_attrs
+                    nodes = node_attrs
+                if isinstance(preserve_graph_attrs, set):
+                    preserve_graph = gname in preserve_graph_attrs
+                else:
+                    preserve_graph = preserve_graph_attrs
+                if getattr(graph, "__networkx_backend__", "networkx") != backend_name:
+                    bound.arguments[gname] = self._convert_graph(
+                        backend_name,
+                        graph,
+                        edge_attrs=edges,
+                        node_attrs=nodes,
+                        preserve_edge_attrs=preserve_edges,
+                        preserve_node_attrs=preserve_nodes,
+                        preserve_graph_attrs=preserve_graph,
+                        graph_name=gname,
+                        use_cache=use_cache,
+                        mutations=mutations,
+                    )
+        bound_kwargs = bound.kwargs
+        del bound_kwargs["backend"]
+        return bound.args, bound_kwargs
+
+    def _convert_graph(
+        self,
+        backend_name,
+        graph,
+        *,
+        edge_attrs,
+        node_attrs,
+        preserve_edge_attrs,
+        preserve_node_attrs,
+        preserve_graph_attrs,
+        graph_name,
+        use_cache,
+        mutations,
+    ):
+        nx_cache = getattr(graph, "__networkx_cache__", None) if use_cache else None
+        if nx_cache is not None:
+            cache = nx_cache.setdefault("backends", {}).setdefault(backend_name, {})
+            key = _get_cache_key(
+                edge_attrs=edge_attrs,
+                node_attrs=node_attrs,
+                preserve_edge_attrs=preserve_edge_attrs,
+                preserve_node_attrs=preserve_node_attrs,
+                preserve_graph_attrs=preserve_graph_attrs,
+            )
+            compat_key, rv = _get_from_cache(cache, key, mutations=mutations)
+            if rv is not None:
+                if "cache" not in nx.config.warnings_to_ignore:
+                    warnings.warn(
+                        "Note: conversions to backend graphs are saved to cache "
+                        "(`G.__networkx_cache__` on the original graph) by default."
+                        "\n\nThis warning means the cached graph is being used "
+                        f"for the {backend_name!r} backend in the "
+                        f"call to {self.name}.\n\nFor the cache to be consistent "
+                        "(i.e., correct), the input graph must not have been "
+                        "manually mutated since the cached graph was created. "
+                        "Examples of manually mutating the graph data structures "
+                        "resulting in an inconsistent cache include:\n\n"
+                        "    >>> G[u][v][key] = val\n\n"
+                        "and\n\n"
+                        "    >>> for u, v, d in G.edges(data=True):\n"
+                        "    ...     d[key] = val\n\n"
+                        "Using methods such as `G.add_edge(u, v, weight=val)` "
+                        "will correctly clear the cache to keep it consistent. "
+                        "You may also use `G.__networkx_cache__.clear()` to "
+                        "manually clear the cache, or set `G.__networkx_cache__` "
+                        "to None to disable caching for G. Enable or disable caching "
+                        "globally via `nx.config.cache_converted_graphs` config.\n\n"
+                        "To disable this warning:\n\n"
+                        '    >>> nx.config.warnings_to_ignore.add("cache")\n'
+                    )
+                if rv == FAILED_TO_CONVERT:
+                    # NotImplementedError is reasonable to use since the backend doesn't
+                    # implement this conversion. However, this will be different than
+                    # the original exception that the backend raised when it failed.
+                    # Using NotImplementedError allows the next backend to be attempted.
+                    raise NotImplementedError(
+                        "Graph conversion aborted: unable to convert graph to "
+                        f"'{backend_name}' backend in call to `{self.name}', "
+                        "because this conversion has previously failed."
+                    )
+                _logger.debug(
+                    "Using cached converted graph (from '%s' to '%s' backend) "
+                    "in call to '%s' for '%s' argument",
+                    getattr(graph, "__networkx_backend__", None),
+                    backend_name,
+                    self.name,
+                    graph_name,
+                )
+                return rv
+
+        if backend_name == "networkx":
+            # Perhaps we should check that "__networkx_backend__" attribute exists
+            # and return the original object if not.
+            if not hasattr(graph, "__networkx_backend__"):
+                _logger.debug(
+                    "Unable to convert input to 'networkx' backend in call to '%s' for "
+                    "'%s argument, because it is not from a backend (i.e., it does not "
+                    "have `G.__networkx_backend__` attribute). Using the original "
+                    "object: %s",
+                    self.name,
+                    graph_name,
+                    graph,
+                )
+                # This may fail, but let it fail in the networkx function
+                return graph
+            backend = _load_backend(graph.__networkx_backend__)
+            try:
+                rv = backend.convert_to_nx(graph)
+            except Exception:
+                if nx_cache is not None:
+                    _set_to_cache(cache, key, FAILED_TO_CONVERT)
+                raise
+        else:
+            backend = _load_backend(backend_name)
+            try:
+                rv = backend.convert_from_nx(
+                    graph,
+                    edge_attrs=edge_attrs,
+                    node_attrs=node_attrs,
+                    preserve_edge_attrs=preserve_edge_attrs,
+                    preserve_node_attrs=preserve_node_attrs,
+                    # Always preserve graph attrs when we are caching b/c this should be
+                    # cheap and may help prevent extra (unnecessary) conversions. Because
+                    # we do this, we don't need `preserve_graph_attrs` in the cache key.
+                    preserve_graph_attrs=preserve_graph_attrs or nx_cache is not None,
+                    name=self.name,
+                    graph_name=graph_name,
+                )
+            except Exception:
+                if nx_cache is not None:
+                    _set_to_cache(cache, key, FAILED_TO_CONVERT)
+                raise
+        if nx_cache is not None:
+            _set_to_cache(cache, key, rv)
+            _logger.debug(
+                "Caching converted graph (from '%s' to '%s' backend) "
+                "in call to '%s' for '%s' argument",
+                getattr(graph, "__networkx_backend__", None),
+                backend_name,
+                self.name,
+                graph_name,
+            )
+
+        return rv
+
+    def _call_with_backend(self, backend_name, args, kwargs, *, extra_message=None):
+        """Call this dispatchable function with a backend without converting inputs."""
+        if backend_name == "networkx":
+            return self.orig_func(*args, **kwargs)
+        backend = _load_backend(backend_name)
+        _logger.debug(
+            "Using backend '%s' for call to '%s' with arguments: %s",
+            backend_name,
+            self.name,
+            _LazyArgsRepr(self, args, kwargs),
+        )
+        try:
+            return getattr(backend, self.name)(*args, **kwargs)
+        except NotImplementedError as exc:
+            if extra_message is not None:
+                _logger.debug(
+                    "Backend '%s' raised when calling '%s': %s",
+                    backend_name,
+                    self.name,
+                    exc,
+                )
+                raise NotImplementedError(extra_message) from exc
+            raise
+
+    def _convert_and_call(
+        self,
+        backend_name,
+        input_backend_names,
+        args,
+        kwargs,
+        *,
+        extra_message=None,
+        mutations=None,
+    ):
+        """Call this dispatchable function with a backend after converting inputs.
+
+        Parameters
+        ----------
+        backend_name : str
+        input_backend_names : set[str]
+        args : arguments tuple
+        kwargs : keywords dict
+        extra_message : str, optional
+            Additional message to log if NotImplementedError is raised by backend.
+        mutations : list, optional
+            Used to clear objects gotten from cache if inputs will be mutated.
+        """
+        if backend_name == "networkx":
+            func = self.orig_func
+        else:
+            backend = _load_backend(backend_name)
+            func = getattr(backend, self.name)
+        other_backend_names = input_backend_names - {backend_name}
+        _logger.debug(
+            "Converting input graphs from %s backend%s to '%s' backend for call to '%s'",
+            other_backend_names
+            if len(other_backend_names) > 1
+            else f"'{next(iter(other_backend_names))}'",
+            "s" if len(other_backend_names) > 1 else "",
+            backend_name,
+            self.name,
+        )
+        try:
+            converted_args, converted_kwargs = self._convert_arguments(
+                backend_name,
+                args,
+                kwargs,
+                use_cache=nx.config.cache_converted_graphs,
+                mutations=mutations,
+            )
+        except NotImplementedError as exc:
+            # Only log the exception if we are adding an extra message
+            # because we don't want to lose any information.
+            _logger.debug(
+                "Failed to convert graphs from %s to '%s' backend for call to '%s'"
+                + ("" if extra_message is None else ": %s"),
+                input_backend_names,
+                backend_name,
+                self.name,
+                *(() if extra_message is None else (exc,)),
+            )
+            if extra_message is not None:
+                raise NotImplementedError(extra_message) from exc
+            raise
+        if backend_name != "networkx":
+            _logger.debug(
+                "Using backend '%s' for call to '%s' with arguments: %s",
+                backend_name,
+                self.name,
+                _LazyArgsRepr(self, converted_args, converted_kwargs),
+            )
+        try:
+            return func(*converted_args, **converted_kwargs)
+        except NotImplementedError as exc:
+            if extra_message is not None:
+                _logger.debug(
+                    "Backend '%s' raised when calling '%s': %s",
+                    backend_name,
+                    self.name,
+                    exc,
+                )
+                raise NotImplementedError(extra_message) from exc
+            raise
+
+    def _convert_and_call_for_tests(
+        self, backend_name, args, kwargs, *, fallback_to_nx=False
+    ):
+        """Call this dispatchable function with a backend; for use with testing."""
+        backend = _load_backend(backend_name)
+        if not self._can_backend_run(backend_name, args, kwargs):
+            if fallback_to_nx or not self.graphs:
+                if fallback_to_nx:
+                    _logger.debug(
+                        "Falling back to use 'networkx' instead of '%s' backend "
+                        "for call to '%s' with arguments: %s",
+                        backend_name,
+                        self.name,
+                        _LazyArgsRepr(self, args, kwargs),
+                    )
+                return self.orig_func(*args, **kwargs)
+
+            import pytest
+
+            msg = f"'{self.name}' not implemented by {backend_name}"
+            if hasattr(backend, self.name):
+                msg += " with the given arguments"
+            pytest.xfail(msg)
+
+        from collections.abc import Iterable, Iterator, Mapping
+        from copy import copy, deepcopy
+        from io import BufferedReader, BytesIO, StringIO, TextIOWrapper
+        from itertools import tee
+        from random import Random
+
+        import numpy as np
+        from numpy.random import Generator, RandomState
+        from scipy.sparse import sparray
+
+        # We sometimes compare the backend result (or input graphs) to the
+        # original result (or input graphs), so we need two sets of arguments.
+        compare_result_to_nx = (
+            self._returns_graph
+            and "networkx" in self.backends
+            and self.name
+            not in {
+                # Has graphs as node values (unable to compare)
+                "quotient_graph",
+                # We don't handle tempfile.NamedTemporaryFile arguments
+                "read_gml",
+                "read_graph6",
+                "read_sparse6",
+                # We don't handle io.BufferedReader or io.TextIOWrapper arguments
+                "bipartite_read_edgelist",
+                "read_adjlist",
+                "read_edgelist",
+                "read_graphml",
+                "read_multiline_adjlist",
+                "read_pajek",
+                "from_pydot",
+                "pydot_read_dot",
+                "agraph_read_dot",
+                # graph comparison fails b/c of nan values
+                "read_gexf",
+            }
+        )
+        compare_inputs_to_nx = (
+            "networkx" in self.backends and self._will_call_mutate_input(args, kwargs)
+        )
+
+        # Tee iterators and copy random state so that they may be used twice.
+        if not args or not compare_result_to_nx and not compare_inputs_to_nx:
+            args_to_convert = args_nx = args
+        else:
+            args_to_convert, args_nx = zip(
+                *(
+                    (arg, deepcopy(arg))
+                    if isinstance(arg, RandomState)
+                    else (arg, copy(arg))
+                    if isinstance(arg, BytesIO | StringIO | Random | Generator)
+                    else tee(arg)
+                    if isinstance(arg, Iterator)
+                    and not isinstance(arg, BufferedReader | TextIOWrapper)
+                    else (arg, arg)
+                    for arg in args
+                )
+            )
+        if not kwargs or not compare_result_to_nx and not compare_inputs_to_nx:
+            kwargs_to_convert = kwargs_nx = kwargs
+        else:
+            kwargs_to_convert, kwargs_nx = zip(
+                *(
+                    ((k, v), (k, deepcopy(v)))
+                    if isinstance(v, RandomState)
+                    else ((k, v), (k, copy(v)))
+                    if isinstance(v, BytesIO | StringIO | Random | Generator)
+                    else ((k, (teed := tee(v))[0]), (k, teed[1]))
+                    if isinstance(v, Iterator)
+                    and not isinstance(v, BufferedReader | TextIOWrapper)
+                    else ((k, v), (k, v))
+                    for k, v in kwargs.items()
+                )
+            )
+            kwargs_to_convert = dict(kwargs_to_convert)
+            kwargs_nx = dict(kwargs_nx)
+
+        try:
+            converted_args, converted_kwargs = self._convert_arguments(
+                backend_name,
+                args_to_convert,
+                kwargs_to_convert,
+                use_cache=False,
+                mutations=None,
+            )
+        except NotImplementedError as exc:
+            if fallback_to_nx:
+                _logger.debug(
+                    "Graph conversion failed; falling back to use 'networkx' instead "
+                    "of '%s' backend for call to '%s'",
+                    backend_name,
+                    self.name,
+                )
+                return self.orig_func(*args_nx, **kwargs_nx)
+            import pytest
+
+            pytest.xfail(
+                exc.args[0] if exc.args else f"{self.name} raised {type(exc).__name__}"
+            )
+
+        if compare_inputs_to_nx:
+            # Ensure input graphs are different if the function mutates an input graph.
+            bound_backend = self.__signature__.bind(*converted_args, **converted_kwargs)
+            bound_backend.apply_defaults()
+            bound_nx = self.__signature__.bind(*args_nx, **kwargs_nx)
+            bound_nx.apply_defaults()
+            for gname in self.graphs:
+                graph_nx = bound_nx.arguments[gname]
+                if bound_backend.arguments[gname] is graph_nx is not None:
+                    bound_nx.arguments[gname] = graph_nx.copy()
+            args_nx = bound_nx.args
+            kwargs_nx = bound_nx.kwargs
+            kwargs_nx.pop("backend", None)
+
+        _logger.debug(
+            "Using backend '%s' for call to '%s' with arguments: %s",
+            backend_name,
+            self.name,
+            _LazyArgsRepr(self, converted_args, converted_kwargs),
+        )
+        try:
+            result = getattr(backend, self.name)(*converted_args, **converted_kwargs)
+        except NotImplementedError as exc:
+            if fallback_to_nx:
+                _logger.debug(
+                    "Backend '%s' raised when calling '%s': %s; "
+                    "falling back to use 'networkx' instead.",
+                    backend_name,
+                    self.name,
+                    exc,
+                )
+                return self.orig_func(*args_nx, **kwargs_nx)
+            import pytest
+
+            pytest.xfail(
+                exc.args[0] if exc.args else f"{self.name} raised {type(exc).__name__}"
+            )
+
+        # Verify that `self._returns_graph` is correct. This compares the return type
+        # to the type expected from `self._returns_graph`. This handles tuple and list
+        # return types, but *does not* catch functions that yield graphs.
+        if (
+            self._returns_graph
+            != (
+                isinstance(result, nx.Graph)
+                or hasattr(result, "__networkx_backend__")
+                or isinstance(result, tuple | list)
+                and any(
+                    isinstance(x, nx.Graph) or hasattr(x, "__networkx_backend__")
+                    for x in result
+                )
+            )
+            and not (
+                # May return Graph or None
+                self.name in {"check_planarity", "check_planarity_recursive"}
+                and any(x is None for x in result)
+            )
+            and not (
+                # May return Graph or dict
+                self.name in {"held_karp_ascent"}
+                and any(isinstance(x, dict) for x in result)
+            )
+            and self.name
+            not in {
+                # yields graphs
+                "all_triads",
+                "general_k_edge_subgraphs",
+                # yields graphs or arrays
+                "nonisomorphic_trees",
+            }
+        ):
+            raise RuntimeError(f"`returns_graph` is incorrect for {self.name}")
+
+        def check_result(val, depth=0):
+            if isinstance(val, np.number):
+                raise RuntimeError(
+                    f"{self.name} returned a numpy scalar {val} ({type(val)}, depth={depth})"
+                )
+            if isinstance(val, np.ndarray | sparray):
+                return
+            if isinstance(val, nx.Graph):
+                check_result(val._node, depth=depth + 1)
+                check_result(val._adj, depth=depth + 1)
+                return
+            if isinstance(val, Iterator):
+                raise NotImplementedError
+            if isinstance(val, Iterable) and not isinstance(val, str):
+                for x in val:
+                    check_result(x, depth=depth + 1)
+            if isinstance(val, Mapping):
+                for x in val.values():
+                    check_result(x, depth=depth + 1)
+
+        def check_iterator(it):
+            for val in it:
+                try:
+                    check_result(val)
+                except RuntimeError as exc:
+                    raise RuntimeError(
+                        f"{self.name} returned a numpy scalar {val} ({type(val)})"
+                    ) from exc
+                yield val
+
+        if self.name in {"from_edgelist"}:
+            # numpy scalars are explicitly given as values in some tests
+            pass
+        elif isinstance(result, Iterator):
+            result = check_iterator(result)
+        else:
+            try:
+                check_result(result)
+            except RuntimeError as exc:
+                raise RuntimeError(
+                    f"{self.name} returned a numpy scalar {result} ({type(result)})"
+                ) from exc
+            check_result(result)
+
+        if self.name.endswith("__new__"):
+            # Graph is not yet done initializing; no sense doing more here
+            return result
+
+        def assert_graphs_equal(G1, G2, strict=True):
+            assert G1.number_of_nodes() == G2.number_of_nodes()
+            assert G1.number_of_edges() == G2.number_of_edges()
+            assert G1.is_directed() is G2.is_directed()
+            assert G1.is_multigraph() is G2.is_multigraph()
+            if strict:
+                assert G1.graph == G2.graph
+                assert G1._node == G2._node
+                assert G1._adj == G2._adj
+            else:
+                assert set(G1) == set(G2)
+                assert set(G1.edges) == set(G2.edges)
+
+        if compare_inputs_to_nx:
+            # Special-case algorithms that mutate input graphs
+            result_nx = self.orig_func(*args_nx, **kwargs_nx)
+            for gname in self.graphs:
+                G0 = bound_backend.arguments[gname]
+                G1 = bound_nx.arguments[gname]
+                if G0 is not None or G1 is not None:
+                    G1 = backend.convert_to_nx(G1)
+                    assert_graphs_equal(G0, G1, strict=False)
+
+        converted_result = backend.convert_to_nx(result)
+        if compare_result_to_nx and isinstance(converted_result, nx.Graph):
+            # For graph return types (e.g. generators), we compare that results are
+            # the same between the backend and networkx, then return the original
+            # networkx result so the iteration order will be consistent in tests.
+            if compare_inputs_to_nx:
+                G = result_nx
+            else:
+                G = self.orig_func(*args_nx, **kwargs_nx)
+            assert_graphs_equal(G, converted_result)
+            return G
+
+        return converted_result
+
+    def _make_doc(self):
+        """Generate the backends section at the end for functions having an alternate
+        backend implementation(s) using the `backend_info` entry-point."""
+
+        if self.backends == {"networkx"}:
+            return self._orig_doc
+        # Add "Backends" section to the bottom of the docstring (if there are backends)
+        lines = [
+            "Backends",
+            "--------",
+        ]
+        for backend in sorted(self.backends - {"networkx"}):
+            info = backend_info[backend]
+            if "short_summary" in info:
+                lines.append(f"{backend} : {info['short_summary']}")
+            else:
+                lines.append(backend)
+            if "functions" not in info or self.name not in info["functions"]:
+                lines.append("")
+                continue
+
+            func_info = info["functions"][self.name]
+
+            # Renaming extra_docstring to additional_docs
+            if func_docs := (
+                func_info.get("additional_docs") or func_info.get("extra_docstring")
+            ):
+                lines.extend(
+                    f"  {line}" if line else line for line in func_docs.split("\n")
+                )
+                add_gap = True
+            else:
+                add_gap = False
+
+            # Renaming extra_parameters to additional_parameters
+            if extra_parameters := (
+                func_info.get("extra_parameters")
+                or func_info.get("additional_parameters")
+            ):
+                if add_gap:
+                    lines.append("")
+                lines.append("  Additional parameters:")
+                for param in sorted(extra_parameters):
+                    lines.append(f"    {param}")
+                    if desc := extra_parameters[param]:
+                        lines.append(f"      {desc}")
+                    lines.append("")
+            else:
+                lines.append("")
+
+            if func_url := func_info.get("url"):
+                lines.append(f"[`Source <{func_url}>`_]")
+                lines.append("")
+
+        # We assume the docstrings are indented by four spaces (true for now)
+        new_doc = self._orig_doc or ""
+        if not new_doc.rstrip():
+            new_doc = f"The original docstring for {self.name} was empty."
+        if self.backends:
+            lines.pop()  # Remove last empty line
+            to_add = "\n    ".join(lines)
+            new_doc = f"{new_doc.rstrip()}\n\n    {to_add}"
+
+        # For backend-only funcs, add "Attention" admonishment after the one line summary
+        if "networkx" not in self.backends:
+            lines = new_doc.split("\n")
+            index = 0
+            while not lines[index].strip():
+                index += 1
+            while index < len(lines) and lines[index].strip():
+                index += 1
+            backends = sorted(self.backends)
+            if len(backends) == 0:
+                example = ""
+            elif len(backends) == 1:
+                example = f' such as "{backends[0]}"'
+            elif len(backends) == 2:
+                example = f' such as "{backends[0]} or "{backends[1]}"'
+            else:
+                example = (
+                    " such as "
+                    + ", ".join(f'"{x}"' for x in backends[:-1])
+                    + f', or "{backends[-1]}"'  # Oxford comma
+                )
+            to_add = (
+                "\n    .. attention:: This function does not have a default NetworkX implementation.\n"
+                "        It may only be run with an installable :doc:`backend ` that\n"
+                f"        supports it{example}.\n\n"
+                "        Hint: use ``backend=...`` keyword argument to specify a backend or add\n"
+                "        backends to ``nx.config.backend_priority``."
+            )
+            lines.insert(index, to_add)
+            new_doc = "\n".join(lines)
+        return new_doc
+
+    def __reduce__(self):
+        """Allow this object to be serialized with pickle.
+
+        This uses the global registry `_registered_algorithms` to deserialize.
+        """
+        return _restore_dispatchable, (self.name,)
+
+
+def _restore_dispatchable(name):
+    return _registered_algorithms[name].__wrapped__
+
+
+def _get_cache_key(
+    *,
+    edge_attrs,
+    node_attrs,
+    preserve_edge_attrs,
+    preserve_node_attrs,
+    preserve_graph_attrs,
+):
+    """Return key used by networkx caching given arguments for ``convert_from_nx``."""
+    # edge_attrs: dict | None
+    # node_attrs: dict | None
+    # preserve_edge_attrs: bool (False if edge_attrs is not None)
+    # preserve_node_attrs: bool (False if node_attrs is not None)
+    return (
+        frozenset(edge_attrs.items())
+        if edge_attrs is not None
+        else preserve_edge_attrs,
+        frozenset(node_attrs.items())
+        if node_attrs is not None
+        else preserve_node_attrs,
+    )
+
+
+def _get_from_cache(cache, key, *, backend_name=None, mutations=None):
+    """Search the networkx cache for a graph that is compatible with ``key``.
+
+    Parameters
+    ----------
+    cache : dict
+        If ``backend_name`` is given, then this is treated as ``G.__networkx_cache__``,
+        but if ``backend_name`` is None, then this is treated as the resolved inner
+        cache such as ``G.__networkx_cache__["backends"][backend_name]``.
+    key : tuple
+        Cache key from ``_get_cache_key``.
+    backend_name : str, optional
+        Name of the backend to control how ``cache`` is interpreted.
+    mutations : list, optional
+        Used internally to clear objects gotten from cache if inputs will be mutated.
+
+    Returns
+    -------
+    tuple or None
+        The key of the compatible graph found in the cache.
+    graph or "FAILED_TO_CONVERT" or None
+        A compatible graph if possible. "FAILED_TO_CONVERT" indicates that a previous
+        conversion attempt failed for this cache key.
+    """
+    if backend_name is not None:
+        cache = cache.get("backends", {}).get(backend_name, {})
+    if not cache:
+        return None, None
+
+    # Do a simple search for a cached graph with compatible data.
+    # For example, if we need a single attribute, then it's okay
+    # to use a cached graph that preserved all attributes.
+    # This looks for an exact match first.
+    edge_key, node_key = key
+    for compat_key in itertools.product(
+        (edge_key, True) if edge_key is not True else (True,),
+        (node_key, True) if node_key is not True else (True,),
+    ):
+        if (rv := cache.get(compat_key)) is not None and (
+            rv != FAILED_TO_CONVERT or key == compat_key
+        ):
+            if mutations is not None:
+                # Remove this item from the cache (after all conversions) if
+                # the call to this dispatchable function will mutate an input.
+                mutations.append((cache, compat_key))
+            return compat_key, rv
+
+    # Iterate over the items in `cache` to see if any are compatible.
+    # For example, if no edge attributes are needed, then a graph
+    # with any edge attribute will suffice. We use the same logic
+    # below (but switched) to clear unnecessary items from the cache.
+    # Use `list(cache.items())` to be thread-safe.
+    for (ekey, nkey), graph in list(cache.items()):
+        if graph == FAILED_TO_CONVERT:
+            # Return FAILED_TO_CONVERT if any cache key that requires a subset
+            # of the edge/node attributes of the given cache key has previously
+            # failed to convert. This logic is similar to `_set_to_cache`.
+            if ekey is False or edge_key is True:
+                pass
+            elif ekey is True or edge_key is False or not ekey.issubset(edge_key):
+                continue
+            if nkey is False or node_key is True:  # or nkey == node_key:
+                pass
+            elif nkey is True or node_key is False or not nkey.issubset(node_key):
+                continue
+            # Save to cache for faster subsequent lookups
+            cache[key] = FAILED_TO_CONVERT
+        elif edge_key is False or ekey is True:
+            pass  # Cache works for edge data!
+        elif edge_key is True or ekey is False or not edge_key.issubset(ekey):
+            continue  # Cache missing required edge data; does not work
+        if node_key is False or nkey is True:
+            pass  # Cache works for node data!
+        elif node_key is True or nkey is False or not node_key.issubset(nkey):
+            continue  # Cache missing required node data; does not work
+        if mutations is not None:
+            # Remove this item from the cache (after all conversions) if
+            # the call to this dispatchable function will mutate an input.
+            mutations.append((cache, (ekey, nkey)))
+        return (ekey, nkey), graph
+
+    return None, None
+
+
+def _set_to_cache(cache, key, graph, *, backend_name=None):
+    """Set a backend graph to the cache, and remove unnecessary cached items.
+
+    Parameters
+    ----------
+    cache : dict
+        If ``backend_name`` is given, then this is treated as ``G.__networkx_cache__``,
+        but if ``backend_name`` is None, then this is treated as the resolved inner
+        cache such as ``G.__networkx_cache__["backends"][backend_name]``.
+    key : tuple
+        Cache key from ``_get_cache_key``.
+    graph : graph or "FAILED_TO_CONVERT"
+        Setting value to "FAILED_TO_CONVERT" prevents this conversion from being
+        attempted in future calls.
+    backend_name : str, optional
+        Name of the backend to control how ``cache`` is interpreted.
+
+    Returns
+    -------
+    dict
+        The items that were removed from the cache.
+    """
+    if backend_name is not None:
+        cache = cache.setdefault("backends", {}).setdefault(backend_name, {})
+    # Remove old cached items that are no longer necessary since they
+    # are dominated/subsumed/outdated by what was just calculated.
+    # This uses the same logic as above, but with keys switched.
+    # Also, don't update the cache here if the call will mutate an input.
+    removed = {}
+    edge_key, node_key = key
+    cache[key] = graph  # Set at beginning to be thread-safe
+    if graph == FAILED_TO_CONVERT:
+        return removed
+    for cur_key in list(cache):
+        if cur_key == key:
+            continue
+        ekey, nkey = cur_key
+        if ekey is False or edge_key is True:
+            pass
+        elif ekey is True or edge_key is False or not ekey.issubset(edge_key):
+            continue
+        if nkey is False or node_key is True:
+            pass
+        elif nkey is True or node_key is False or not nkey.issubset(node_key):
+            continue
+        # Use pop instead of del to try to be thread-safe
+        if (graph := cache.pop(cur_key, None)) is not None:
+            removed[cur_key] = graph
+    return removed
+
+
+class _LazyArgsRepr:
+    """Simple wrapper to display arguments of dispatchable functions in logging calls."""
+
+    def __init__(self, func, args, kwargs):
+        self.func = func
+        self.args = args
+        self.kwargs = kwargs
+        self.value = None
+
+    def __repr__(self):
+        if self.value is None:
+            bound = self.func.__signature__.bind_partial(*self.args, **self.kwargs)
+            inner = ", ".join(f"{key}={val!r}" for key, val in bound.arguments.items())
+            self.value = f"({inner})"
+        return self.value
+
+
+if os.environ.get("_NETWORKX_BUILDING_DOCS_"):
+    # When building docs with Sphinx, use the original function with the
+    # dispatched __doc__, b/c Sphinx renders normal Python functions better.
+    # This doesn't show e.g. `*, backend=None, **backend_kwargs` in the
+    # signatures, which is probably okay. It does allow the docstring to be
+    # updated based on the installed backends.
+    _orig_dispatchable = _dispatchable
+
+    def _dispatchable(func=None, **kwargs):  # type: ignore[no-redef]
+        if func is None:
+            return partial(_dispatchable, **kwargs)
+        dispatched_func = _orig_dispatchable(func, **kwargs)
+        func.__doc__ = dispatched_func.__doc__
+        return func
+
+    _dispatchable.__doc__ = _orig_dispatchable.__new__.__doc__  # type: ignore[method-assign,assignment]
+    _sig = inspect.signature(_orig_dispatchable.__new__)
+    _dispatchable.__signature__ = _sig.replace(  # type: ignore[method-assign,assignment]
+        parameters=[v for k, v in _sig.parameters.items() if k != "cls"]
+    )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/configs.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/configs.py
new file mode 100644
index 0000000000000000000000000000000000000000..5da4bdc083e1948a353342004a0925c6bd02ae45
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/configs.py
@@ -0,0 +1,396 @@
+import collections
+import typing
+from dataclasses import dataclass
+
+__all__ = ["Config"]
+
+
+@dataclass(init=False, eq=False, slots=True, kw_only=True, match_args=False)
+class Config:
+    """The base class for NetworkX configuration.
+
+    There are two ways to use this to create configurations. The recommended way
+    is to subclass ``Config`` with docs and annotations.
+
+    >>> class MyConfig(Config):
+    ...     '''Breakfast!'''
+    ...
+    ...     eggs: int
+    ...     spam: int
+    ...
+    ...     def _on_setattr(self, key, value):
+    ...         assert isinstance(value, int) and value >= 0
+    ...         return value
+    >>> cfg = MyConfig(eggs=1, spam=5)
+
+    Another way is to simply pass the initial configuration as keyword arguments to
+    the ``Config`` instance:
+
+    >>> cfg1 = Config(eggs=1, spam=5)
+    >>> cfg1
+    Config(eggs=1, spam=5)
+
+    Once defined, config items may be modified, but can't be added or deleted by default.
+    ``Config`` is a ``Mapping``, and can get and set configs via attributes or brackets:
+
+    >>> cfg.eggs = 2
+    >>> cfg.eggs
+    2
+    >>> cfg["spam"] = 42
+    >>> cfg["spam"]
+    42
+
+    For convenience, it can also set configs within a context with the "with" statement:
+
+    >>> with cfg(spam=3):
+    ...     print("spam (in context):", cfg.spam)
+    spam (in context): 3
+    >>> print("spam (after context):", cfg.spam)
+    spam (after context): 42
+
+    Subclasses may also define ``_on_setattr`` (as done in the example above)
+    to ensure the value being assigned is valid:
+
+    >>> cfg.spam = -1
+    Traceback (most recent call last):
+        ...
+    AssertionError
+
+    If a more flexible configuration object is needed that allows adding and deleting
+    configurations, then pass ``strict=False`` when defining the subclass:
+
+    >>> class FlexibleConfig(Config, strict=False):
+    ...     default_greeting: str = "Hello"
+    >>> flexcfg = FlexibleConfig()
+    >>> flexcfg.name = "Mr. Anderson"
+    >>> flexcfg
+    FlexibleConfig(default_greeting='Hello', name='Mr. Anderson')
+    """
+
+    def __init_subclass__(cls, strict=True):
+        cls._strict = strict
+
+    def __new__(cls, **kwargs):
+        orig_class = cls
+        if cls is Config:
+            # Enable the "simple" case of accepting config definition as keywords
+            cls = type(
+                cls.__name__,
+                (cls,),
+                {"__annotations__": {key: typing.Any for key in kwargs}},
+            )
+        cls = dataclass(
+            eq=False,
+            repr=cls._strict,
+            slots=cls._strict,
+            kw_only=True,
+            match_args=False,
+        )(cls)
+        if not cls._strict:
+            cls.__repr__ = _flexible_repr
+        cls._orig_class = orig_class  # Save original class so we can pickle
+        cls._prev = None  # Stage previous configs to enable use as context manager
+        cls._context_stack = []  # Stack of previous configs when used as context
+        instance = object.__new__(cls)
+        instance.__init__(**kwargs)
+        return instance
+
+    def _on_setattr(self, key, value):
+        """Process config value and check whether it is valid. Useful for subclasses."""
+        return value
+
+    def _on_delattr(self, key):
+        """Callback for when a config item is being deleted. Useful for subclasses."""
+
+    # Control behavior of attributes
+    def __dir__(self):
+        return self.__dataclass_fields__.keys()
+
+    def __setattr__(self, key, value):
+        if self._strict and key not in self.__dataclass_fields__:
+            raise AttributeError(f"Invalid config name: {key!r}")
+        value = self._on_setattr(key, value)
+        object.__setattr__(self, key, value)
+        self.__class__._prev = None
+
+    def __delattr__(self, key):
+        if self._strict:
+            raise TypeError(
+                f"Configuration items can't be deleted (can't delete {key!r})."
+            )
+        self._on_delattr(key)
+        object.__delattr__(self, key)
+        self.__class__._prev = None
+
+    # Be a `collection.abc.Collection`
+    def __contains__(self, key):
+        return (
+            key in self.__dataclass_fields__ if self._strict else key in self.__dict__
+        )
+
+    def __iter__(self):
+        return iter(self.__dataclass_fields__ if self._strict else self.__dict__)
+
+    def __len__(self):
+        return len(self.__dataclass_fields__ if self._strict else self.__dict__)
+
+    def __reversed__(self):
+        return reversed(self.__dataclass_fields__ if self._strict else self.__dict__)
+
+    # Add dunder methods for `collections.abc.Mapping`
+    def __getitem__(self, key):
+        try:
+            return getattr(self, key)
+        except AttributeError as err:
+            raise KeyError(*err.args) from None
+
+    def __setitem__(self, key, value):
+        try:
+            self.__setattr__(key, value)
+        except AttributeError as err:
+            raise KeyError(*err.args) from None
+
+    def __delitem__(self, key):
+        try:
+            self.__delattr__(key)
+        except AttributeError as err:
+            raise KeyError(*err.args) from None
+
+    _ipython_key_completions_ = __dir__  # config["
+
+    # Go ahead and make it a `collections.abc.Mapping`
+    def get(self, key, default=None):
+        return getattr(self, key, default)
+
+    def items(self):
+        return collections.abc.ItemsView(self)
+
+    def keys(self):
+        return collections.abc.KeysView(self)
+
+    def values(self):
+        return collections.abc.ValuesView(self)
+
+    # dataclass can define __eq__ for us, but do it here so it works after pickling
+    def __eq__(self, other):
+        if not isinstance(other, Config):
+            return NotImplemented
+        return self._orig_class == other._orig_class and self.items() == other.items()
+
+    # Make pickle work
+    def __reduce__(self):
+        return self._deserialize, (self._orig_class, dict(self))
+
+    @staticmethod
+    def _deserialize(cls, kwargs):
+        return cls(**kwargs)
+
+    # Allow to be used as context manager
+    def __call__(self, **kwargs):
+        kwargs = {key: self._on_setattr(key, val) for key, val in kwargs.items()}
+        prev = dict(self)
+        for key, val in kwargs.items():
+            setattr(self, key, val)
+        self.__class__._prev = prev
+        return self
+
+    def __enter__(self):
+        if self.__class__._prev is None:
+            raise RuntimeError(
+                "Config being used as a context manager without config items being set. "
+                "Set config items via keyword arguments when calling the config object. "
+                "For example, using config as a context manager should be like:\n\n"
+                '    >>> with cfg(breakfast="spam"):\n'
+                "    ...     ...  # Do stuff\n"
+            )
+        self.__class__._context_stack.append(self.__class__._prev)
+        self.__class__._prev = None
+        return self
+
+    def __exit__(self, exc_type, exc_value, traceback):
+        prev = self.__class__._context_stack.pop()
+        for key, val in prev.items():
+            setattr(self, key, val)
+
+
+def _flexible_repr(self):
+    return (
+        f"{self.__class__.__qualname__}("
+        + ", ".join(f"{key}={val!r}" for key, val in self.__dict__.items())
+        + ")"
+    )
+
+
+# Register, b/c `Mapping.__subclasshook__` returns `NotImplemented`
+collections.abc.Mapping.register(Config)
+
+
+class BackendPriorities(Config, strict=False):
+    """Configuration to control automatic conversion to and calling of backends.
+
+    Priority is given to backends listed earlier.
+
+    Parameters
+    ----------
+    algos : list of backend names
+        This controls "algorithms" such as ``nx.pagerank`` that don't return a graph.
+    generators : list of backend names
+        This controls "generators" such as ``nx.from_pandas_edgelist`` that return a graph.
+    classes : list of backend names
+        This controls graph classes such as ``nx.Graph()``.
+    kwargs : variadic keyword arguments of function name to list of backend names
+        This allows each function to be configured separately and will override the config
+        in ``algos`` or ``generators`` if present. The dispatchable function name may be
+        gotten from the ``.name`` attribute such as ``nx.pagerank.name`` (it's typically
+        the same as the name of the function).
+    """
+
+    algos: list[str]
+    generators: list[str]
+    classes: list[str]
+
+    def _on_setattr(self, key, value):
+        from .backends import _registered_algorithms, backend_info
+
+        if key in {"algos", "generators", "classes"}:
+            pass
+        elif key not in _registered_algorithms:
+            raise AttributeError(
+                f"Invalid config name: {key!r}. Expected 'algos', 'generators', "
+                "'classes', or a name of a dispatchable function "
+                "(e.g. `.name` attribute of the function)."
+            )
+        if not (isinstance(value, list) and all(isinstance(x, str) for x in value)):
+            raise TypeError(
+                f"{key!r} config must be a list of backend names; got {value!r}"
+            )
+        if missing := {x for x in value if x not in backend_info}:
+            missing = ", ".join(map(repr, sorted(missing)))
+            raise ValueError(f"Unknown backend when setting {key!r}: {missing}")
+        return value
+
+    def _on_delattr(self, key):
+        if key in {"algos", "generators", "classes"}:
+            raise TypeError(f"{key!r} configuration item can't be deleted.")
+
+
+class NetworkXConfig(Config):
+    """Configuration for NetworkX that controls behaviors such as how to use backends.
+
+    Attribute and bracket notation are supported for getting and setting configurations::
+
+        >>> nx.config.backend_priority == nx.config["backend_priority"]
+        True
+
+    Parameters
+    ----------
+    backend_priority : list of backend names or dict or BackendPriorities
+        Enable automatic conversion of graphs to backend graphs for functions
+        implemented by the backend. Priority is given to backends listed earlier.
+        This is a nested configuration with keys ``algos``, ``generators``,
+        ``classes``, and, optionally, function names. Setting this value to a
+        list of backend names will set ``nx.config.backend_priority.algos``.
+        For more information, see ``help(nx.config.backend_priority)``.
+        Default is empty list.
+
+    backends : Config mapping of backend names to backend Config
+        The keys of the Config mapping are names of all installed NetworkX backends,
+        and the values are their configurations as Config mappings.
+
+    cache_converted_graphs : bool
+        If True, then save converted graphs to the cache of the input graph. Graph
+        conversion may occur when automatically using a backend from `backend_priority`
+        or when using the `backend=` keyword argument to a function call. Caching can
+        improve performance by avoiding repeated conversions, but it uses more memory.
+        Care should be taken to not manually mutate a graph that has cached graphs; for
+        example, ``G[u][v][k] = val`` changes the graph, but does not clear the cache.
+        Using methods such as ``G.add_edge(u, v, weight=val)`` will clear the cache to
+        keep it consistent. ``G.__networkx_cache__.clear()`` manually clears the cache.
+        Default is True.
+
+    fallback_to_nx : bool
+        If True, then "fall back" and run with the default "networkx" implementation
+        for dispatchable functions not implemented by backends of input graphs. When a
+        backend graph is passed to a dispatchable function, the default behavior is to
+        use the implementation from that backend if possible and raise if not. Enabling
+        ``fallback_to_nx`` makes the networkx implementation the fallback to use instead
+        of raising, and will convert the backend graph to a networkx-compatible graph.
+        Default is False.
+
+    warnings_to_ignore : set of strings
+        Control which warnings from NetworkX are not emitted. Valid elements:
+
+        - `"cache"`: when a cached value is used from ``G.__networkx_cache__``.
+
+    Notes
+    -----
+    Environment variables may be used to control some default configurations:
+
+    - ``NETWORKX_BACKEND_PRIORITY``: set ``backend_priority.algos`` from comma-separated names.
+    - ``NETWORKX_CACHE_CONVERTED_GRAPHS``: set ``cache_converted_graphs`` to True if nonempty.
+    - ``NETWORKX_FALLBACK_TO_NX``: set ``fallback_to_nx`` to True if nonempty.
+    - ``NETWORKX_WARNINGS_TO_IGNORE``: set `warnings_to_ignore` from comma-separated names.
+
+    and can be used for finer control of ``backend_priority`` such as:
+
+    - ``NETWORKX_BACKEND_PRIORITY_ALGOS``: same as ``NETWORKX_BACKEND_PRIORITY``
+      to set ``backend_priority.algos``.
+
+    This is a global configuration. Use with caution when using from multiple threads.
+    """
+
+    backend_priority: BackendPriorities
+    backends: Config
+    cache_converted_graphs: bool
+    fallback_to_nx: bool
+    warnings_to_ignore: set[str]
+
+    def _on_setattr(self, key, value):
+        from .backends import backend_info
+
+        if key == "backend_priority":
+            if isinstance(value, list):
+                # `config.backend_priority = [backend]` sets `backend_priority.algos`
+                value = BackendPriorities(
+                    **dict(
+                        self.backend_priority,
+                        algos=self.backend_priority._on_setattr("algos", value),
+                    )
+                )
+            elif isinstance(value, dict):
+                kwargs = value
+                value = BackendPriorities(algos=[], generators=[], classes=[])
+                for key, val in kwargs.items():
+                    setattr(value, key, val)
+            elif not isinstance(value, BackendPriorities):
+                raise TypeError(
+                    f"{key!r} config must be a dict of lists of backend names; got {value!r}"
+                )
+        elif key == "backends":
+            if not (
+                isinstance(value, Config)
+                and all(isinstance(key, str) for key in value)
+                and all(isinstance(val, Config) for val in value.values())
+            ):
+                raise TypeError(
+                    f"{key!r} config must be a Config of backend configs; got {value!r}"
+                )
+            if missing := {x for x in value if x not in backend_info}:
+                missing = ", ".join(map(repr, sorted(missing)))
+                raise ValueError(f"Unknown backend when setting {key!r}: {missing}")
+        elif key in {"cache_converted_graphs", "fallback_to_nx"}:
+            if not isinstance(value, bool):
+                raise TypeError(f"{key!r} config must be True or False; got {value!r}")
+        elif key == "warnings_to_ignore":
+            if not (isinstance(value, set) and all(isinstance(x, str) for x in value)):
+                raise TypeError(
+                    f"{key!r} config must be a set of warning names; got {value!r}"
+                )
+            known_warnings = {"cache"}
+            if missing := {x for x in value if x not in known_warnings}:
+                missing = ", ".join(map(repr, sorted(missing)))
+                raise ValueError(
+                    f"Unknown warning when setting {key!r}: {missing}. Valid entries: "
+                    + ", ".join(sorted(known_warnings))
+                )
+        return value
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/decorators.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/decorators.py
new file mode 100644
index 0000000000000000000000000000000000000000..f222744fb939454dc504bf31078fc58b3cfe0da8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/decorators.py
@@ -0,0 +1,1233 @@
+import bz2
+import collections
+import gzip
+import inspect
+import itertools
+import re
+from collections import defaultdict
+from os.path import splitext
+from pathlib import Path
+
+import networkx as nx
+from networkx.utils import create_py_random_state, create_random_state
+
+__all__ = [
+    "not_implemented_for",
+    "open_file",
+    "nodes_or_number",
+    "np_random_state",
+    "py_random_state",
+    "argmap",
+]
+
+
+def not_implemented_for(*graph_types):
+    """Decorator to mark algorithms as not implemented
+
+    Parameters
+    ----------
+    graph_types : container of strings
+        Entries must be one of "directed", "undirected", "multigraph", or "graph".
+
+    Returns
+    -------
+    _require : function
+        The decorated function.
+
+    Raises
+    ------
+    NetworkXNotImplemented
+    If any of the packages cannot be imported
+
+    Notes
+    -----
+    Multiple types are joined logically with "and".
+    For "or" use multiple @not_implemented_for() lines.
+
+    Examples
+    --------
+    Decorate functions like this::
+
+       @not_implemented_for("directed")
+       def sp_function(G):
+           pass
+
+
+       # rule out MultiDiGraph
+       @not_implemented_for("directed", "multigraph")
+       def sp_np_function(G):
+           pass
+
+
+       # rule out all except DiGraph
+       @not_implemented_for("undirected")
+       @not_implemented_for("multigraph")
+       def sp_np_function(G):
+           pass
+    """
+    if ("directed" in graph_types) and ("undirected" in graph_types):
+        raise ValueError("Function not implemented on directed AND undirected graphs?")
+    if ("multigraph" in graph_types) and ("graph" in graph_types):
+        raise ValueError("Function not implemented on graph AND multigraphs?")
+    if not set(graph_types) < {"directed", "undirected", "multigraph", "graph"}:
+        raise KeyError(
+            "use one or more of directed, undirected, multigraph, graph.  "
+            f"You used {graph_types}"
+        )
+
+    # 3-way logic: True if "directed" input, False if "undirected" input, else None
+    dval = ("directed" in graph_types) or "undirected" not in graph_types and None
+    mval = ("multigraph" in graph_types) or "graph" not in graph_types and None
+    errmsg = f"not implemented for {' '.join(graph_types)} type"
+
+    def _not_implemented_for(g):
+        if (mval is None or mval == g.is_multigraph()) and (
+            dval is None or dval == g.is_directed()
+        ):
+            raise nx.NetworkXNotImplemented(errmsg)
+
+        return g
+
+    return argmap(_not_implemented_for, 0)
+
+
+# To handle new extensions, define a function accepting a `path` and `mode`.
+# Then add the extension to _dispatch_dict.
+fopeners = {
+    ".gz": gzip.open,
+    ".gzip": gzip.open,
+    ".bz2": bz2.BZ2File,
+}
+_dispatch_dict = defaultdict(lambda: open, **fopeners)
+
+
+def open_file(path_arg, mode="r"):
+    """Decorator to ensure clean opening and closing of files.
+
+    Parameters
+    ----------
+    path_arg : string or int
+        Name or index of the argument that is a path.
+
+    mode : str
+        String for opening mode.
+
+    Returns
+    -------
+    _open_file : function
+        Function which cleanly executes the io.
+
+    Examples
+    --------
+    Decorate functions like this::
+
+       @open_file(0, "r")
+       def read_function(pathname):
+           pass
+
+
+       @open_file(1, "w")
+       def write_function(G, pathname):
+           pass
+
+
+       @open_file(1, "w")
+       def write_function(G, pathname="graph.dot"):
+           pass
+
+
+       @open_file("pathname", "w")
+       def write_function(G, pathname="graph.dot"):
+           pass
+
+
+       @open_file("path", "w+")
+       def another_function(arg, **kwargs):
+           path = kwargs["path"]
+           pass
+
+    Notes
+    -----
+    Note that this decorator solves the problem when a path argument is
+    specified as a string, but it does not handle the situation when the
+    function wants to accept a default of None (and then handle it).
+
+    Here is an example of how to handle this case::
+
+      @open_file("path")
+      def some_function(arg1, arg2, path=None):
+          if path is None:
+              fobj = tempfile.NamedTemporaryFile(delete=False)
+          else:
+              # `path` could have been a string or file object or something
+              # similar. In any event, the decorator has given us a file object
+              # and it will close it for us, if it should.
+              fobj = path
+
+          try:
+              fobj.write("blah")
+          finally:
+              if path is None:
+                  fobj.close()
+
+    Normally, we'd want to use "with" to ensure that fobj gets closed.
+    However, the decorator will make `path` a file object for us,
+    and using "with" would undesirably close that file object.
+    Instead, we use a try block, as shown above.
+    When we exit the function, fobj will be closed, if it should be, by the decorator.
+    """
+
+    def _open_file(path):
+        # Now we have the path_arg. There are two types of input to consider:
+        #   1) string representing a path that should be opened
+        #   2) an already opened file object
+        if isinstance(path, str):
+            ext = splitext(path)[1]
+        elif isinstance(path, Path):
+            # path is a pathlib reference to a filename
+            ext = path.suffix
+            path = str(path)
+        else:
+            # could be None, or a file handle, in which case the algorithm will deal with it
+            return path, lambda: None
+
+        fobj = _dispatch_dict[ext](path, mode=mode)
+        return fobj, lambda: fobj.close()
+
+    return argmap(_open_file, path_arg, try_finally=True)
+
+
+def nodes_or_number(which_args):
+    """Decorator to allow number of nodes or container of nodes.
+
+    With this decorator, the specified argument can be either a number or a container
+    of nodes. If it is a number, the nodes used are `range(n)`.
+    This allows `nx.complete_graph(50)` in place of `nx.complete_graph(list(range(50)))`.
+    And it also allows `nx.complete_graph(any_list_of_nodes)`.
+
+    Parameters
+    ----------
+    which_args : string or int or sequence of strings or ints
+        If string, the name of the argument to be treated.
+        If int, the index of the argument to be treated.
+        If more than one node argument is allowed, can be a list of locations.
+
+    Returns
+    -------
+    _nodes_or_numbers : function
+        Function which replaces int args with ranges.
+
+    Examples
+    --------
+    Decorate functions like this::
+
+       @nodes_or_number("nodes")
+       def empty_graph(nodes):
+           # nodes is converted to a list of nodes
+
+       @nodes_or_number(0)
+       def empty_graph(nodes):
+           # nodes is converted to a list of nodes
+
+       @nodes_or_number(["m1", "m2"])
+       def grid_2d_graph(m1, m2, periodic=False):
+           # m1 and m2 are each converted to a list of nodes
+
+       @nodes_or_number([0, 1])
+       def grid_2d_graph(m1, m2, periodic=False):
+           # m1 and m2 are each converted to a list of nodes
+
+       @nodes_or_number(1)
+       def full_rary_tree(r, n)
+           # presumably r is a number. It is not handled by this decorator.
+           # n is converted to a list of nodes
+    """
+
+    def _nodes_or_number(n):
+        try:
+            nodes = list(range(n))
+        except TypeError:
+            nodes = tuple(n)
+        else:
+            if n < 0:
+                raise nx.NetworkXError(f"Negative number of nodes not valid: {n}")
+        return (n, nodes)
+
+    try:
+        iter_wa = iter(which_args)
+    except TypeError:
+        iter_wa = (which_args,)
+
+    return argmap(_nodes_or_number, *iter_wa)
+
+
+def np_random_state(random_state_argument):
+    """Decorator to generate a numpy RandomState or Generator instance.
+
+    The decorator processes the argument indicated by `random_state_argument`
+    using :func:`nx.utils.create_random_state`.
+    The argument value can be a seed (integer), or a `numpy.random.RandomState`
+    or `numpy.random.RandomState` instance or (`None` or `numpy.random`).
+    The latter two options use the global random number generator for `numpy.random`.
+
+    The returned instance is a `numpy.random.RandomState` or `numpy.random.Generator`.
+
+    Parameters
+    ----------
+    random_state_argument : string or int
+        The name or index of the argument to be converted
+        to a `numpy.random.RandomState` instance.
+
+    Returns
+    -------
+    _random_state : function
+        Function whose random_state keyword argument is a RandomState instance.
+
+    Examples
+    --------
+    Decorate functions like this::
+
+       @np_random_state("seed")
+       def random_float(seed=None):
+           return seed.rand()
+
+
+       @np_random_state(0)
+       def random_float(rng=None):
+           return rng.rand()
+
+
+       @np_random_state(1)
+       def random_array(dims, random_state=1):
+           return random_state.rand(*dims)
+
+    See Also
+    --------
+    py_random_state
+    """
+    return argmap(create_random_state, random_state_argument)
+
+
+def py_random_state(random_state_argument):
+    """Decorator to generate a random.Random instance (or equiv).
+
+    This decorator processes `random_state_argument` using
+    :func:`nx.utils.create_py_random_state`.
+    The input value can be a seed (integer), or a random number generator::
+
+        If int, return a random.Random instance set with seed=int.
+        If random.Random instance, return it.
+        If None or the `random` package, return the global random number
+        generator used by `random`.
+        If np.random package, or the default numpy RandomState instance,
+        return the default numpy random number generator wrapped in a
+        `PythonRandomViaNumpyBits`  class.
+        If np.random.Generator instance, return it wrapped in a
+        `PythonRandomViaNumpyBits`  class.
+
+        # Legacy options
+        If np.random.RandomState instance, return it wrapped in a
+        `PythonRandomInterface` class.
+        If a `PythonRandomInterface` instance, return it
+
+    Parameters
+    ----------
+    random_state_argument : string or int
+        The name of the argument or the index of the argument in args that is
+        to be converted to the random.Random instance or numpy.random.RandomState
+        instance that mimics basic methods of random.Random.
+
+    Returns
+    -------
+    _random_state : function
+        Function whose random_state_argument is converted to a Random instance.
+
+    Examples
+    --------
+    Decorate functions like this::
+
+       @py_random_state("random_state")
+       def random_float(random_state=None):
+           return random_state.rand()
+
+
+       @py_random_state(0)
+       def random_float(rng=None):
+           return rng.rand()
+
+
+       @py_random_state(1)
+       def random_array(dims, seed=12345):
+           return seed.rand(*dims)
+
+    See Also
+    --------
+    np_random_state
+    """
+
+    return argmap(create_py_random_state, random_state_argument)
+
+
+class argmap:
+    """A decorator to apply a map to arguments before calling the function
+
+    This class provides a decorator that maps (transforms) arguments of the function
+    before the function is called. Thus for example, we have similar code
+    in many functions to determine whether an argument is the number of nodes
+    to be created, or a list of nodes to be handled. The decorator provides
+    the code to accept either -- transforming the indicated argument into a
+    list of nodes before the actual function is called.
+
+    This decorator class allows us to process single or multiple arguments.
+    The arguments to be processed can be specified by string, naming the argument,
+    or by index, specifying the item in the args list.
+
+    Parameters
+    ----------
+    func : callable
+        The function to apply to arguments
+
+    *args : iterable of (int, str or tuple)
+        A list of parameters, specified either as strings (their names), ints
+        (numerical indices) or tuples, which may contain ints, strings, and
+        (recursively) tuples. Each indicates which parameters the decorator
+        should map. Tuples indicate that the map function takes (and returns)
+        multiple parameters in the same order and nested structure as indicated
+        here.
+
+    try_finally : bool (default: False)
+        When True, wrap the function call in a try-finally block with code
+        for the finally block created by `func`. This is used when the map
+        function constructs an object (like a file handle) that requires
+        post-processing (like closing).
+
+        Note: try_finally decorators cannot be used to decorate generator
+        functions.
+
+    Examples
+    --------
+    Most of these examples use `@argmap(...)` to apply the decorator to
+    the function defined on the next line.
+    In the NetworkX codebase however, `argmap` is used within a function to
+    construct a decorator. That is, the decorator defines a mapping function
+    and then uses `argmap` to build and return a decorated function.
+    A simple example is a decorator that specifies which currency to report money.
+    The decorator (named `convert_to`) would be used like::
+
+        @convert_to("US_Dollars", "income")
+        def show_me_the_money(name, income):
+            print(f"{name} : {income}")
+
+    And the code to create the decorator might be::
+
+        def convert_to(currency, which_arg):
+            def _convert(amount):
+                if amount.currency != currency:
+                    amount = amount.to_currency(currency)
+                return amount
+
+            return argmap(_convert, which_arg)
+
+    Despite this common idiom for argmap, most of the following examples
+    use the `@argmap(...)` idiom to save space.
+
+    Here's an example use of argmap to sum the elements of two of the functions
+    arguments. The decorated function::
+
+        @argmap(sum, "xlist", "zlist")
+        def foo(xlist, y, zlist):
+            return xlist - y + zlist
+
+    is syntactic sugar for::
+
+        def foo(xlist, y, zlist):
+            x = sum(xlist)
+            z = sum(zlist)
+            return x - y + z
+
+    and is equivalent to (using argument indexes)::
+
+        @argmap(sum, "xlist", 2)
+        def foo(xlist, y, zlist):
+            return xlist - y + zlist
+
+    or::
+
+        @argmap(sum, "zlist", 0)
+        def foo(xlist, y, zlist):
+            return xlist - y + zlist
+
+    Transforming functions can be applied to multiple arguments, such as::
+
+        def swap(x, y):
+            return y, x
+
+        # the 2-tuple tells argmap that the map `swap` has 2 inputs/outputs.
+        @argmap(swap, ("a", "b")):
+        def foo(a, b, c):
+            return a / b * c
+
+    is equivalent to::
+
+        def foo(a, b, c):
+            a, b = swap(a, b)
+            return a / b * c
+
+    More generally, the applied arguments can be nested tuples of strings or ints.
+    The syntax `@argmap(some_func, ("a", ("b", "c")))` would expect `some_func` to
+    accept 2 inputs with the second expected to be a 2-tuple. It should then return
+    2 outputs with the second a 2-tuple. The returns values would replace input "a"
+    "b" and "c" respectively. Similarly for `@argmap(some_func, (0, ("b", 2)))`.
+
+    Also, note that an index larger than the number of named parameters is allowed
+    for variadic functions. For example::
+
+        def double(a):
+            return 2 * a
+
+
+        @argmap(double, 3)
+        def overflow(a, *args):
+            return a, args
+
+
+        print(overflow(1, 2, 3, 4, 5, 6))  # output is 1, (2, 3, 8, 5, 6)
+
+    **Try Finally**
+
+    Additionally, this `argmap` class can be used to create a decorator that
+    initiates a try...finally block. The decorator must be written to return
+    both the transformed argument and a closing function.
+    This feature was included to enable the `open_file` decorator which might
+    need to close the file or not depending on whether it had to open that file.
+    This feature uses the keyword-only `try_finally` argument to `@argmap`.
+
+    For example this map opens a file and then makes sure it is closed::
+
+        def open_file(fn):
+            f = open(fn)
+            return f, lambda: f.close()
+
+    The decorator applies that to the function `foo`::
+
+        @argmap(open_file, "file", try_finally=True)
+        def foo(file):
+            print(file.read())
+
+    is syntactic sugar for::
+
+        def foo(file):
+            file, close_file = open_file(file)
+            try:
+                print(file.read())
+            finally:
+                close_file()
+
+    and is equivalent to (using indexes)::
+
+        @argmap(open_file, 0, try_finally=True)
+        def foo(file):
+            print(file.read())
+
+    Here's an example of the try_finally feature used to create a decorator::
+
+        def my_closing_decorator(which_arg):
+            def _opener(path):
+                if path is None:
+                    path = open(path)
+                    fclose = path.close
+                else:
+                    # assume `path` handles the closing
+                    fclose = lambda: None
+                return path, fclose
+
+            return argmap(_opener, which_arg, try_finally=True)
+
+    which can then be used as::
+
+        @my_closing_decorator("file")
+        def fancy_reader(file=None):
+            # this code doesn't need to worry about closing the file
+            print(file.read())
+
+    Decorators with try_finally = True cannot be used with generator functions,
+    because the `finally` block is evaluated before the generator is exhausted::
+
+        @argmap(open_file, "file", try_finally=True)
+        def file_to_lines(file):
+            for line in file.readlines():
+                yield line
+
+    is equivalent to::
+
+        def file_to_lines_wrapped(file):
+            for line in file.readlines():
+                yield line
+
+
+        def file_to_lines_wrapper(file):
+            try:
+                file = open_file(file)
+                return file_to_lines_wrapped(file)
+            finally:
+                file.close()
+
+    which behaves similarly to::
+
+        def file_to_lines_whoops(file):
+            file = open_file(file)
+            file.close()
+            for line in file.readlines():
+                yield line
+
+    because the `finally` block of `file_to_lines_wrapper` is executed before
+    the caller has a chance to exhaust the iterator.
+
+    Notes
+    -----
+    An object of this class is callable and intended to be used when
+    defining a decorator. Generally, a decorator takes a function as input
+    and constructs a function as output. Specifically, an `argmap` object
+    returns the input function decorated/wrapped so that specified arguments
+    are mapped (transformed) to new values before the decorated function is called.
+
+    As an overview, the argmap object returns a new function with all the
+    dunder values of the original function (like `__doc__`, `__name__`, etc).
+    Code for this decorated function is built based on the original function's
+    signature. It starts by mapping the input arguments to potentially new
+    values. Then it calls the decorated function with these new values in place
+    of the indicated arguments that have been mapped. The return value of the
+    original function is then returned. This new function is the function that
+    is actually called by the user.
+
+    Three additional features are provided.
+        1) The code is lazily compiled. That is, the new function is returned
+        as an object without the code compiled, but with all information
+        needed so it can be compiled upon it's first invocation. This saves
+        time on import at the cost of additional time on the first call of
+        the function. Subsequent calls are then just as fast as normal.
+
+        2) If the "try_finally" keyword-only argument is True, a try block
+        follows each mapped argument, matched on the other side of the wrapped
+        call, by a finally block closing that mapping.  We expect func to return
+        a 2-tuple: the mapped value and a function to be called in the finally
+        clause.  This feature was included so the `open_file` decorator could
+        provide a file handle to the decorated function and close the file handle
+        after the function call. It even keeps track of whether to close the file
+        handle or not based on whether it had to open the file or the input was
+        already open. So, the decorated function does not need to include any
+        code to open or close files.
+
+        3) The maps applied can process multiple arguments. For example,
+        you could swap two arguments using a mapping, or transform
+        them to their sum and their difference. This was included to allow
+        a decorator in the `quality.py` module that checks that an input
+        `partition` is a valid partition of the nodes of the input graph `G`.
+        In this example, the map has inputs `(G, partition)`. After checking
+        for a valid partition, the map either raises an exception or leaves
+        the inputs unchanged. Thus many functions that make this check can
+        use the decorator rather than copy the checking code into each function.
+        More complicated nested argument structures are described below.
+
+    The remaining notes describe the code structure and methods for this
+    class in broad terms to aid in understanding how to use it.
+
+    Instantiating an `argmap` object simply stores the mapping function and
+    the input identifiers of which arguments to map. The resulting decorator
+    is ready to use this map to decorate any function. Calling that object
+    (`argmap.__call__`, but usually done via `@my_decorator`) a lazily
+    compiled thin wrapper of the decorated function is constructed,
+    wrapped with the necessary function dunder attributes like `__doc__`
+    and `__name__`. That thinly wrapped function is returned as the
+    decorated function. When that decorated function is called, the thin
+    wrapper of code calls `argmap._lazy_compile` which compiles the decorated
+    function (using `argmap.compile`) and replaces the code of the thin
+    wrapper with the newly compiled code. This saves the compilation step
+    every import of networkx, at the cost of compiling upon the first call
+    to the decorated function.
+
+    When the decorated function is compiled, the code is recursively assembled
+    using the `argmap.assemble` method. The recursive nature is needed in
+    case of nested decorators. The result of the assembly is a number of
+    useful objects.
+
+      sig : the function signature of the original decorated function as
+          constructed by :func:`argmap.signature`. This is constructed
+          using `inspect.signature` but enhanced with attribute
+          strings `sig_def` and `sig_call`, and other information
+          specific to mapping arguments of this function.
+          This information is used to construct a string of code defining
+          the new decorated function.
+
+      wrapped_name : a unique internally used name constructed by argmap
+          for the decorated function.
+
+      functions : a dict of the functions used inside the code of this
+          decorated function, to be used as `globals` in `exec`.
+          This dict is recursively updated to allow for nested decorating.
+
+      mapblock : code (as a list of strings) to map the incoming argument
+          values to their mapped values.
+
+      finallys : code (as a list of strings) to provide the possibly nested
+          set of finally clauses if needed.
+
+      mutable_args : a bool indicating whether the `sig.args` tuple should be
+          converted to a list so mutation can occur.
+
+    After this recursive assembly process, the `argmap.compile` method
+    constructs code (as strings) to convert the tuple `sig.args` to a list
+    if needed. It joins the defining code with appropriate indents and
+    compiles the result.  Finally, this code is evaluated and the original
+    wrapper's implementation is replaced with the compiled version (see
+    `argmap._lazy_compile` for more details).
+
+    Other `argmap` methods include `_name` and `_count` which allow internally
+    generated names to be unique within a python session.
+    The methods `_flatten` and `_indent` process the nested lists of strings
+    into properly indented python code ready to be compiled.
+
+    More complicated nested tuples of arguments also allowed though
+    usually not used. For the simple 2 argument case, the argmap
+    input ("a", "b") implies the mapping function will take 2 arguments
+    and return a 2-tuple of mapped values. A more complicated example
+    with argmap input `("a", ("b", "c"))` requires the mapping function
+    take 2 inputs, with the second being a 2-tuple. It then must output
+    the 3 mapped values in the same nested structure `(newa, (newb, newc))`.
+    This level of generality is not often needed, but was convenient
+    to implement when handling the multiple arguments.
+
+    See Also
+    --------
+    not_implemented_for
+    open_file
+    nodes_or_number
+    py_random_state
+    networkx.algorithms.community.quality.require_partition
+
+    """
+
+    def __init__(self, func, *args, try_finally=False):
+        self._func = func
+        self._args = args
+        self._finally = try_finally
+
+    @staticmethod
+    def _lazy_compile(func):
+        """Compile the source of a wrapped function
+
+        Assemble and compile the decorated function, and intrusively replace its
+        code with the compiled version's.  The thinly wrapped function becomes
+        the decorated function.
+
+        Parameters
+        ----------
+        func : callable
+            A function returned by argmap.__call__ which is in the process
+            of being called for the first time.
+
+        Returns
+        -------
+        func : callable
+            The same function, with a new __code__ object.
+
+        Notes
+        -----
+        It was observed in NetworkX issue #4732 [1] that the import time of
+        NetworkX was significantly bloated by the use of decorators: over half
+        of the import time was being spent decorating functions.  This was
+        somewhat improved by a change made to the `decorator` library, at the
+        cost of a relatively heavy-weight call to `inspect.Signature.bind`
+        for each call to the decorated function.
+
+        The workaround we arrived at is to do minimal work at the time of
+        decoration.  When the decorated function is called for the first time,
+        we compile a function with the same function signature as the wrapped
+        function.  The resulting decorated function is faster than one made by
+        the `decorator` library, so that the overhead of the first call is
+        'paid off' after a small number of calls.
+
+        References
+        ----------
+
+        [1] https://github.com/networkx/networkx/issues/4732
+
+        """
+        real_func = func.__argmap__.compile(func.__wrapped__)
+        func.__code__ = real_func.__code__
+        func.__globals__.update(real_func.__globals__)
+        func.__dict__.update(real_func.__dict__)
+        return func
+
+    def __call__(self, f):
+        """Construct a lazily decorated wrapper of f.
+
+        The decorated function will be compiled when it is called for the first time,
+        and it will replace its own __code__ object so subsequent calls are fast.
+
+        Parameters
+        ----------
+        f : callable
+            A function to be decorated.
+
+        Returns
+        -------
+        func : callable
+            The decorated function.
+
+        See Also
+        --------
+        argmap._lazy_compile
+        """
+
+        def func(*args, __wrapper=None, **kwargs):
+            return argmap._lazy_compile(__wrapper)(*args, **kwargs)
+
+        # standard function-wrapping stuff
+        func.__name__ = f.__name__
+        func.__doc__ = f.__doc__
+        func.__defaults__ = f.__defaults__
+        func.__kwdefaults__.update(f.__kwdefaults__ or {})
+        func.__module__ = f.__module__
+        func.__qualname__ = f.__qualname__
+        func.__dict__.update(f.__dict__)
+        func.__wrapped__ = f
+
+        # now that we've wrapped f, we may have picked up some __dict__ or
+        # __kwdefaults__ items that were set by a previous argmap.  Thus, we set
+        # these values after those update() calls.
+
+        # If we attempt to access func from within itself, that happens through
+        # a closure -- which trips an error when we replace func.__code__.  The
+        # standard workaround for functions which can't see themselves is to use
+        # a Y-combinator, as we do here.
+        func.__kwdefaults__["_argmap__wrapper"] = func
+
+        # this self-reference is here because functools.wraps preserves
+        # everything in __dict__, and we don't want to mistake a non-argmap
+        # wrapper for an argmap wrapper
+        func.__self__ = func
+
+        # this is used to variously call self.assemble and self.compile
+        func.__argmap__ = self
+
+        if hasattr(f, "__argmap__"):
+            func.__is_generator = f.__is_generator
+        else:
+            func.__is_generator = inspect.isgeneratorfunction(f)
+
+        if self._finally and func.__is_generator:
+            raise nx.NetworkXError("argmap cannot decorate generators with try_finally")
+
+        return func
+
+    __count = 0
+
+    @classmethod
+    def _count(cls):
+        """Maintain a globally-unique identifier for function names and "file" names
+
+        Note that this counter is a class method reporting a class variable
+        so the count is unique within a Python session. It could differ from
+        session to session for a specific decorator depending on the order
+        that the decorators are created. But that doesn't disrupt `argmap`.
+
+        This is used in two places: to construct unique variable names
+        in the `_name` method and to construct unique fictitious filenames
+        in the `_compile` method.
+
+        Returns
+        -------
+        count : int
+            An integer unique to this Python session (simply counts from zero)
+        """
+        cls.__count += 1
+        return cls.__count
+
+    _bad_chars = re.compile("[^a-zA-Z0-9_]")
+
+    @classmethod
+    def _name(cls, f):
+        """Mangle the name of a function to be unique but somewhat human-readable
+
+        The names are unique within a Python session and set using `_count`.
+
+        Parameters
+        ----------
+        f : str or object
+
+        Returns
+        -------
+        name : str
+            The mangled version of `f.__name__` (if `f.__name__` exists) or `f`
+
+        """
+        f = f.__name__ if hasattr(f, "__name__") else f
+        fname = re.sub(cls._bad_chars, "_", f)
+        return f"argmap_{fname}_{cls._count()}"
+
+    def compile(self, f):
+        """Compile the decorated function.
+
+        Called once for a given decorated function -- collects the code from all
+        argmap decorators in the stack, and compiles the decorated function.
+
+        Much of the work done here uses the `assemble` method to allow recursive
+        treatment of multiple argmap decorators on a single decorated function.
+        That flattens the argmap decorators, collects the source code to construct
+        a single decorated function, then compiles/executes/returns that function.
+
+        The source code for the decorated function is stored as an attribute
+        `_code` on the function object itself.
+
+        Note that Python's `compile` function requires a filename, but this
+        code is constructed without a file, so a fictitious filename is used
+        to describe where the function comes from. The name is something like:
+        "argmap compilation 4".
+
+        Parameters
+        ----------
+        f : callable
+            The function to be decorated
+
+        Returns
+        -------
+        func : callable
+            The decorated file
+
+        """
+        sig, wrapped_name, functions, mapblock, finallys, mutable_args = self.assemble(
+            f
+        )
+
+        call = f"{sig.call_sig.format(wrapped_name)}#"
+        mut_args = f"{sig.args} = list({sig.args})" if mutable_args else ""
+        body = argmap._indent(sig.def_sig, mut_args, mapblock, call, finallys)
+        code = "\n".join(body)
+
+        locl = {}
+        globl = dict(functions.values())
+        filename = f"{self.__class__} compilation {self._count()}"
+        compiled = compile(code, filename, "exec")
+        exec(compiled, globl, locl)
+        func = locl[sig.name]
+        func._code = code
+        return func
+
+    def assemble(self, f):
+        """Collects components of the source for the decorated function wrapping f.
+
+        If `f` has multiple argmap decorators, we recursively assemble the stack of
+        decorators into a single flattened function.
+
+        This method is part of the `compile` method's process yet separated
+        from that method to allow recursive processing. The outputs are
+        strings, dictionaries and lists that collect needed info to
+        flatten any nested argmap-decoration.
+
+        Parameters
+        ----------
+        f : callable
+            The function to be decorated.  If f is argmapped, we assemble it.
+
+        Returns
+        -------
+        sig : argmap.Signature
+            The function signature as an `argmap.Signature` object.
+        wrapped_name : str
+            The mangled name used to represent the wrapped function in the code
+            being assembled.
+        functions : dict
+            A dictionary mapping id(g) -> (mangled_name(g), g) for functions g
+            referred to in the code being assembled. These need to be present
+            in the ``globals`` scope of ``exec`` when defining the decorated
+            function.
+        mapblock : list of lists and/or strings
+            Code that implements mapping of parameters including any try blocks
+            if needed. This code will precede the decorated function call.
+        finallys : list of lists and/or strings
+            Code that implements the finally blocks to post-process the
+            arguments (usually close any files if needed) after the
+            decorated function is called.
+        mutable_args : bool
+            True if the decorator needs to modify positional arguments
+            via their indices. The compile method then turns the argument
+            tuple into a list so that the arguments can be modified.
+        """
+
+        # first, we check if f is already argmapped -- if that's the case,
+        # build up the function recursively.
+        # > mapblock is generally a list of function calls of the sort
+        #     arg = func(arg)
+        # in addition to some try-blocks if needed.
+        # > finallys is a recursive list of finally blocks of the sort
+        #         finally:
+        #             close_func_1()
+        #     finally:
+        #         close_func_2()
+        # > functions is a dict of functions used in the scope of our decorated
+        # function. It will be used to construct globals used in compilation.
+        # We make functions[id(f)] = name_of_f, f to ensure that a given
+        # function is stored and named exactly once even if called by
+        # nested decorators.
+        if hasattr(f, "__argmap__") and f.__self__ is f:
+            (
+                sig,
+                wrapped_name,
+                functions,
+                mapblock,
+                finallys,
+                mutable_args,
+            ) = f.__argmap__.assemble(f.__wrapped__)
+            functions = dict(functions)  # shallow-copy just in case
+        else:
+            sig = self.signature(f)
+            wrapped_name = self._name(f)
+            mapblock, finallys = [], []
+            functions = {id(f): (wrapped_name, f)}
+            mutable_args = False
+
+        if id(self._func) in functions:
+            fname, _ = functions[id(self._func)]
+        else:
+            fname, _ = functions[id(self._func)] = self._name(self._func), self._func
+
+        # this is a bit complicated -- we can call functions with a variety of
+        # nested arguments, so long as their input and output are tuples with
+        # the same nested structure. e.g. ("a", "b") maps arguments a and b.
+        # A more complicated nesting like (0, (3, 4)) maps arguments 0, 3, 4
+        # expecting the mapping to output new values in the same nested shape.
+        # The ability to argmap multiple arguments was necessary for
+        # the decorator `nx.algorithms.community.quality.require_partition`, and
+        # while we're not taking full advantage of the ability to handle
+        # multiply-nested tuples, it was convenient to implement this in
+        # generality because the recursive call to `get_name` is necessary in
+        # any case.
+        applied = set()
+
+        def get_name(arg, first=True):
+            nonlocal mutable_args
+            if isinstance(arg, tuple):
+                name = ", ".join(get_name(x, False) for x in arg)
+                return name if first else f"({name})"
+            if arg in applied:
+                raise nx.NetworkXError(f"argument {arg} is specified multiple times")
+            applied.add(arg)
+            if arg in sig.names:
+                return sig.names[arg]
+            elif isinstance(arg, str):
+                if sig.kwargs is None:
+                    raise nx.NetworkXError(
+                        f"name {arg} is not a named parameter and this function doesn't have kwargs"
+                    )
+                return f"{sig.kwargs}[{arg!r}]"
+            else:
+                if sig.args is None:
+                    raise nx.NetworkXError(
+                        f"index {arg} not a parameter index and this function doesn't have args"
+                    )
+                mutable_args = True
+                return f"{sig.args}[{arg - sig.n_positional}]"
+
+        if self._finally:
+            # here's where we handle try_finally decorators.  Such a decorator
+            # returns a mapped argument and a function to be called in a
+            # finally block.  This feature was required by the open_file
+            # decorator.  The below generates the code
+            #
+            # name, final = func(name)                   #<--append to mapblock
+            # try:                                       #<--append to mapblock
+            #     ... more argmapping and try blocks
+            #     return WRAPPED_FUNCTION(...)
+            #     ... more finally blocks
+            # finally:                                   #<--prepend to finallys
+            #     final()                                #<--prepend to finallys
+            #
+            for a in self._args:
+                name = get_name(a)
+                final = self._name(name)
+                mapblock.append(f"{name}, {final} = {fname}({name})")
+                mapblock.append("try:")
+                finallys = ["finally:", f"{final}()#", "#", finallys]
+        else:
+            mapblock.extend(
+                f"{name} = {fname}({name})" for name in map(get_name, self._args)
+            )
+
+        return sig, wrapped_name, functions, mapblock, finallys, mutable_args
+
+    @classmethod
+    def signature(cls, f):
+        r"""Construct a Signature object describing `f`
+
+        Compute a Signature so that we can write a function wrapping f with
+        the same signature and call-type.
+
+        Parameters
+        ----------
+        f : callable
+            A function to be decorated
+
+        Returns
+        -------
+        sig : argmap.Signature
+            The Signature of f
+
+        Notes
+        -----
+        The Signature is a namedtuple with names:
+
+            name : a unique version of the name of the decorated function
+            signature : the inspect.signature of the decorated function
+            def_sig : a string used as code to define the new function
+            call_sig : a string used as code to call the decorated function
+            names : a dict keyed by argument name and index to the argument's name
+            n_positional : the number of positional arguments in the signature
+            args : the name of the VAR_POSITIONAL argument if any, i.e. \*theseargs
+            kwargs : the name of the VAR_KEYWORDS argument if any, i.e. \*\*kwargs
+
+        These named attributes of the signature are used in `assemble` and `compile`
+        to construct a string of source code for the decorated function.
+
+        """
+        sig = inspect.signature(f, follow_wrapped=False)
+        def_sig = []
+        call_sig = []
+        names = {}
+
+        kind = None
+        args = None
+        kwargs = None
+        npos = 0
+        for i, param in enumerate(sig.parameters.values()):
+            # parameters can be position-only, keyword-or-position, keyword-only
+            # in any combination, but only in the order as above.  we do edge
+            # detection to add the appropriate punctuation
+            prev = kind
+            kind = param.kind
+            if prev == param.POSITIONAL_ONLY != kind:
+                # the last token was position-only, but this one isn't
+                def_sig.append("/")
+            if (
+                param.VAR_POSITIONAL
+                != prev
+                != param.KEYWORD_ONLY
+                == kind
+                != param.VAR_POSITIONAL
+            ):
+                # param is the first keyword-only arg and isn't starred
+                def_sig.append("*")
+
+            # star arguments as appropriate
+            if kind == param.VAR_POSITIONAL:
+                name = "*" + param.name
+                args = param.name
+                count = 0
+            elif kind == param.VAR_KEYWORD:
+                name = "**" + param.name
+                kwargs = param.name
+                count = 0
+            else:
+                names[i] = names[param.name] = param.name
+                name = param.name
+                count = 1
+
+            # assign to keyword-only args in the function call
+            if kind == param.KEYWORD_ONLY:
+                call_sig.append(f"{name} = {name}")
+            else:
+                npos += count
+                call_sig.append(name)
+
+            def_sig.append(name)
+
+        fname = cls._name(f)
+        def_sig = f"def {fname}({', '.join(def_sig)}):"
+
+        call_sig = f"return {{}}({', '.join(call_sig)})"
+
+        return cls.Signature(fname, sig, def_sig, call_sig, names, npos, args, kwargs)
+
+    Signature = collections.namedtuple(
+        "Signature",
+        [
+            "name",
+            "signature",
+            "def_sig",
+            "call_sig",
+            "names",
+            "n_positional",
+            "args",
+            "kwargs",
+        ],
+    )
+
+    @staticmethod
+    def _flatten(nestlist, visited):
+        """flattens a recursive list of lists that doesn't have cyclic references
+
+        Parameters
+        ----------
+        nestlist : iterable
+            A recursive list of objects to be flattened into a single iterable
+
+        visited : set
+            A set of object ids which have been walked -- initialize with an
+            empty set
+
+        Yields
+        ------
+        Non-list objects contained in nestlist
+
+        """
+        for thing in nestlist:
+            if isinstance(thing, list):
+                if id(thing) in visited:
+                    raise ValueError("A cycle was found in nestlist.  Be a tree.")
+                else:
+                    visited.add(id(thing))
+                yield from argmap._flatten(thing, visited)
+            else:
+                yield thing
+
+    _tabs = " " * 64
+
+    @staticmethod
+    def _indent(*lines):
+        """Indent list of code lines to make executable Python code
+
+        Indents a tree-recursive list of strings, following the rule that one
+        space is added to the tab after a line that ends in a colon, and one is
+        removed after a line that ends in an hashmark.
+
+        Parameters
+        ----------
+        *lines : lists and/or strings
+            A recursive list of strings to be assembled into properly indented
+            code.
+
+        Returns
+        -------
+        code : str
+
+        Examples
+        --------
+
+            argmap._indent(*["try:", "try:", "pass#", "finally:", "pass#", "#",
+                             "finally:", "pass#"])
+
+        renders to
+
+            '''try:
+             try:
+              pass#
+             finally:
+              pass#
+             #
+            finally:
+             pass#'''
+        """
+        depth = 0
+        for line in argmap._flatten(lines, set()):
+            yield f"{argmap._tabs[:depth]}{line}"
+            depth += (line[-1:] == ":") - (line[-1:] == "#")
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/heaps.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/heaps.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d67dfd3ff381d51e2ece51aae7ea27ee3091acb
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/heaps.py
@@ -0,0 +1,338 @@
+"""
+Min-heaps.
+"""
+
+from heapq import heappop, heappush
+from itertools import count
+
+import networkx as nx
+
+__all__ = ["MinHeap", "PairingHeap", "BinaryHeap"]
+
+
+class MinHeap:
+    """Base class for min-heaps.
+
+    A MinHeap stores a collection of key-value pairs ordered by their values.
+    It supports querying the minimum pair, inserting a new pair, decreasing the
+    value in an existing pair and deleting the minimum pair.
+    """
+
+    class _Item:
+        """Used by subclassess to represent a key-value pair."""
+
+        __slots__ = ("key", "value")
+
+        def __init__(self, key, value):
+            self.key = key
+            self.value = value
+
+        def __repr__(self):
+            return repr((self.key, self.value))
+
+    def __init__(self):
+        """Initialize a new min-heap."""
+        self._dict = {}
+
+    def min(self):
+        """Query the minimum key-value pair.
+
+        Returns
+        -------
+        key, value : tuple
+            The key-value pair with the minimum value in the heap.
+
+        Raises
+        ------
+        NetworkXError
+            If the heap is empty.
+        """
+        raise NotImplementedError
+
+    def pop(self):
+        """Delete the minimum pair in the heap.
+
+        Returns
+        -------
+        key, value : tuple
+            The key-value pair with the minimum value in the heap.
+
+        Raises
+        ------
+        NetworkXError
+            If the heap is empty.
+        """
+        raise NotImplementedError
+
+    def get(self, key, default=None):
+        """Returns the value associated with a key.
+
+        Parameters
+        ----------
+        key : hashable object
+            The key to be looked up.
+
+        default : object
+            Default value to return if the key is not present in the heap.
+            Default value: None.
+
+        Returns
+        -------
+        value : object.
+            The value associated with the key.
+        """
+        raise NotImplementedError
+
+    def insert(self, key, value, allow_increase=False):
+        """Insert a new key-value pair or modify the value in an existing
+        pair.
+
+        Parameters
+        ----------
+        key : hashable object
+            The key.
+
+        value : object comparable with existing values.
+            The value.
+
+        allow_increase : bool
+            Whether the value is allowed to increase. If False, attempts to
+            increase an existing value have no effect. Default value: False.
+
+        Returns
+        -------
+        decreased : bool
+            True if a pair is inserted or the existing value is decreased.
+        """
+        raise NotImplementedError
+
+    def __nonzero__(self):
+        """Returns whether the heap if empty."""
+        return bool(self._dict)
+
+    def __bool__(self):
+        """Returns whether the heap if empty."""
+        return bool(self._dict)
+
+    def __len__(self):
+        """Returns the number of key-value pairs in the heap."""
+        return len(self._dict)
+
+    def __contains__(self, key):
+        """Returns whether a key exists in the heap.
+
+        Parameters
+        ----------
+        key : any hashable object.
+            The key to be looked up.
+        """
+        return key in self._dict
+
+
+class PairingHeap(MinHeap):
+    """A pairing heap."""
+
+    class _Node(MinHeap._Item):
+        """A node in a pairing heap.
+
+        A tree in a pairing heap is stored using the left-child, right-sibling
+        representation.
+        """
+
+        __slots__ = ("left", "next", "prev", "parent")
+
+        def __init__(self, key, value):
+            super().__init__(key, value)
+            # The leftmost child.
+            self.left = None
+            # The next sibling.
+            self.next = None
+            # The previous sibling.
+            self.prev = None
+            # The parent.
+            self.parent = None
+
+    def __init__(self):
+        """Initialize a pairing heap."""
+        super().__init__()
+        self._root = None
+
+    def min(self):
+        if self._root is None:
+            raise nx.NetworkXError("heap is empty.")
+        return (self._root.key, self._root.value)
+
+    def pop(self):
+        if self._root is None:
+            raise nx.NetworkXError("heap is empty.")
+        min_node = self._root
+        self._root = self._merge_children(self._root)
+        del self._dict[min_node.key]
+        return (min_node.key, min_node.value)
+
+    def get(self, key, default=None):
+        node = self._dict.get(key)
+        return node.value if node is not None else default
+
+    def insert(self, key, value, allow_increase=False):
+        node = self._dict.get(key)
+        root = self._root
+        if node is not None:
+            if value < node.value:
+                node.value = value
+                if node is not root and value < node.parent.value:
+                    self._cut(node)
+                    self._root = self._link(root, node)
+                return True
+            elif allow_increase and value > node.value:
+                node.value = value
+                child = self._merge_children(node)
+                # Nonstandard step: Link the merged subtree with the root. See
+                # below for the standard step.
+                if child is not None:
+                    self._root = self._link(self._root, child)
+                # Standard step: Perform a decrease followed by a pop as if the
+                # value were the smallest in the heap. Then insert the new
+                # value into the heap.
+                # if node is not root:
+                #     self._cut(node)
+                #     if child is not None:
+                #         root = self._link(root, child)
+                #     self._root = self._link(root, node)
+                # else:
+                #     self._root = (self._link(node, child)
+                #                   if child is not None else node)
+            return False
+        else:
+            # Insert a new key.
+            node = self._Node(key, value)
+            self._dict[key] = node
+            self._root = self._link(root, node) if root is not None else node
+            return True
+
+    def _link(self, root, other):
+        """Link two nodes, making the one with the smaller value the parent of
+        the other.
+        """
+        if other.value < root.value:
+            root, other = other, root
+        next = root.left
+        other.next = next
+        if next is not None:
+            next.prev = other
+        other.prev = None
+        root.left = other
+        other.parent = root
+        return root
+
+    def _merge_children(self, root):
+        """Merge the subtrees of the root using the standard two-pass method.
+        The resulting subtree is detached from the root.
+        """
+        node = root.left
+        root.left = None
+        if node is not None:
+            link = self._link
+            # Pass 1: Merge pairs of consecutive subtrees from left to right.
+            # At the end of the pass, only the prev pointers of the resulting
+            # subtrees have meaningful values. The other pointers will be fixed
+            # in pass 2.
+            prev = None
+            while True:
+                next = node.next
+                if next is None:
+                    node.prev = prev
+                    break
+                next_next = next.next
+                node = link(node, next)
+                node.prev = prev
+                prev = node
+                if next_next is None:
+                    break
+                node = next_next
+            # Pass 2: Successively merge the subtrees produced by pass 1 from
+            # right to left with the rightmost one.
+            prev = node.prev
+            while prev is not None:
+                prev_prev = prev.prev
+                node = link(prev, node)
+                prev = prev_prev
+            # Now node can become the new root. Its has no parent nor siblings.
+            node.prev = None
+            node.next = None
+            node.parent = None
+        return node
+
+    def _cut(self, node):
+        """Cut a node from its parent."""
+        prev = node.prev
+        next = node.next
+        if prev is not None:
+            prev.next = next
+        else:
+            node.parent.left = next
+        node.prev = None
+        if next is not None:
+            next.prev = prev
+            node.next = None
+        node.parent = None
+
+
+class BinaryHeap(MinHeap):
+    """A binary heap."""
+
+    def __init__(self):
+        """Initialize a binary heap."""
+        super().__init__()
+        self._heap = []
+        self._count = count()
+
+    def min(self):
+        dict = self._dict
+        if not dict:
+            raise nx.NetworkXError("heap is empty")
+        heap = self._heap
+        # Repeatedly remove stale key-value pairs until a up-to-date one is
+        # met.
+        while True:
+            value, _, key = heap[0]
+            if key in dict and value == dict[key]:
+                break
+            heappop(heap)
+        return (key, value)
+
+    def pop(self):
+        dict = self._dict
+        if not dict:
+            raise nx.NetworkXError("heap is empty")
+        heap = self._heap
+        # Repeatedly remove stale key-value pairs until a up-to-date one is
+        # met.
+        while True:
+            value, _, key = heap[0]
+            heappop(heap)
+            if key in dict and value == dict[key]:
+                break
+        del dict[key]
+        return (key, value)
+
+    def get(self, key, default=None):
+        return self._dict.get(key, default)
+
+    def insert(self, key, value, allow_increase=False):
+        dict = self._dict
+        if key in dict:
+            old_value = dict[key]
+            if value < old_value or (allow_increase and value > old_value):
+                # Since there is no way to efficiently obtain the location of a
+                # key-value pair in the heap, insert a new pair even if ones
+                # with the same key may already be present. Deem the old ones
+                # as stale and skip them when the minimum pair is queried.
+                dict[key] = value
+                heappush(self._heap, (value, next(self._count), key))
+                return value < old_value
+            return False
+        else:
+            dict[key] = value
+            heappush(self._heap, (value, next(self._count), key))
+            return True
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/mapped_queue.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/mapped_queue.py
new file mode 100644
index 0000000000000000000000000000000000000000..0dcea368a93873fd72195fc8d388891c129942e0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/mapped_queue.py
@@ -0,0 +1,297 @@
+"""Priority queue class with updatable priorities."""
+
+import heapq
+
+__all__ = ["MappedQueue"]
+
+
+class _HeapElement:
+    """This proxy class separates the heap element from its priority.
+
+    The idea is that using a 2-tuple (priority, element) works
+    for sorting, but not for dict lookup because priorities are
+    often floating point values so round-off can mess up equality.
+
+    So, we need inequalities to look at the priority (for sorting)
+    and equality (and hash) to look at the element to enable
+    updates to the priority.
+
+    Unfortunately, this class can be tricky to work with if you forget that
+    `__lt__` compares the priority while `__eq__` compares the element.
+    In `greedy_modularity_communities()` the following code is
+    used to check that two _HeapElements differ in either element or priority:
+
+        if d_oldmax != row_max or d_oldmax.priority != row_max.priority:
+
+    If the priorities are the same, this implementation uses the element
+    as a tiebreaker. This provides compatibility with older systems that
+    use tuples to combine priority and elements.
+    """
+
+    __slots__ = ["priority", "element", "_hash"]
+
+    def __init__(self, priority, element):
+        self.priority = priority
+        self.element = element
+        self._hash = hash(element)
+
+    def __lt__(self, other):
+        try:
+            other_priority = other.priority
+        except AttributeError:
+            return self.priority < other
+        # assume comparing to another _HeapElement
+        if self.priority == other_priority:
+            try:
+                return self.element < other.element
+            except TypeError as err:
+                raise TypeError(
+                    "Consider using a tuple, with a priority value that can be compared."
+                )
+        return self.priority < other_priority
+
+    def __gt__(self, other):
+        try:
+            other_priority = other.priority
+        except AttributeError:
+            return self.priority > other
+        # assume comparing to another _HeapElement
+        if self.priority == other_priority:
+            try:
+                return self.element > other.element
+            except TypeError as err:
+                raise TypeError(
+                    "Consider using a tuple, with a priority value that can be compared."
+                )
+        return self.priority > other_priority
+
+    def __eq__(self, other):
+        try:
+            return self.element == other.element
+        except AttributeError:
+            return self.element == other
+
+    def __hash__(self):
+        return self._hash
+
+    def __getitem__(self, indx):
+        return self.priority if indx == 0 else self.element[indx - 1]
+
+    def __iter__(self):
+        yield self.priority
+        try:
+            yield from self.element
+        except TypeError:
+            yield self.element
+
+    def __repr__(self):
+        return f"_HeapElement({self.priority}, {self.element})"
+
+
+class MappedQueue:
+    """The MappedQueue class implements a min-heap with removal and update-priority.
+
+    The min heap uses heapq as well as custom written _siftup and _siftdown
+    methods to allow the heap positions to be tracked by an additional dict
+    keyed by element to position. The smallest element can be popped in O(1) time,
+    new elements can be pushed in O(log n) time, and any element can be removed
+    or updated in O(log n) time. The queue cannot contain duplicate elements
+    and an attempt to push an element already in the queue will have no effect.
+
+    MappedQueue complements the heapq package from the python standard
+    library. While MappedQueue is designed for maximum compatibility with
+    heapq, it adds element removal, lookup, and priority update.
+
+    Parameters
+    ----------
+    data : dict or iterable
+
+    Examples
+    --------
+
+    A `MappedQueue` can be created empty, or optionally, given a dictionary
+    of initial elements and priorities.  The methods `push`, `pop`,
+    `remove`, and `update` operate on the queue.
+
+    >>> colors_nm = {"red": 665, "blue": 470, "green": 550}
+    >>> q = MappedQueue(colors_nm)
+    >>> q.remove("red")
+    >>> q.update("green", "violet", 400)
+    >>> q.push("indigo", 425)
+    True
+    >>> [q.pop().element for i in range(len(q.heap))]
+    ['violet', 'indigo', 'blue']
+
+    A `MappedQueue` can also be initialized with a list or other iterable. The priority is assumed
+    to be the sort order of the items in the list.
+
+    >>> q = MappedQueue([916, 50, 4609, 493, 237])
+    >>> q.remove(493)
+    >>> q.update(237, 1117)
+    >>> [q.pop() for i in range(len(q.heap))]
+    [50, 916, 1117, 4609]
+
+    An exception is raised if the elements are not comparable.
+
+    >>> q = MappedQueue([100, "a"])
+    Traceback (most recent call last):
+    ...
+    TypeError: '<' not supported between instances of 'int' and 'str'
+
+    To avoid the exception, use a dictionary to assign priorities to the elements.
+
+    >>> q = MappedQueue({100: 0, "a": 1})
+
+    References
+    ----------
+    .. [1] Cormen, T. H., Leiserson, C. E., Rivest, R. L., & Stein, C. (2001).
+       Introduction to algorithms second edition.
+    .. [2] Knuth, D. E. (1997). The art of computer programming (Vol. 3).
+       Pearson Education.
+    """
+
+    def __init__(self, data=None):
+        """Priority queue class with updatable priorities."""
+        if data is None:
+            self.heap = []
+        elif isinstance(data, dict):
+            self.heap = [_HeapElement(v, k) for k, v in data.items()]
+        else:
+            self.heap = list(data)
+        self.position = {}
+        self._heapify()
+
+    def _heapify(self):
+        """Restore heap invariant and recalculate map."""
+        heapq.heapify(self.heap)
+        self.position = {elt: pos for pos, elt in enumerate(self.heap)}
+        if len(self.heap) != len(self.position):
+            raise AssertionError("Heap contains duplicate elements")
+
+    def __len__(self):
+        return len(self.heap)
+
+    def push(self, elt, priority=None):
+        """Add an element to the queue."""
+        if priority is not None:
+            elt = _HeapElement(priority, elt)
+        # If element is already in queue, do nothing
+        if elt in self.position:
+            return False
+        # Add element to heap and dict
+        pos = len(self.heap)
+        self.heap.append(elt)
+        self.position[elt] = pos
+        # Restore invariant by sifting down
+        self._siftdown(0, pos)
+        return True
+
+    def pop(self):
+        """Remove and return the smallest element in the queue."""
+        # Remove smallest element
+        elt = self.heap[0]
+        del self.position[elt]
+        # If elt is last item, remove and return
+        if len(self.heap) == 1:
+            self.heap.pop()
+            return elt
+        # Replace root with last element
+        last = self.heap.pop()
+        self.heap[0] = last
+        self.position[last] = 0
+        # Restore invariant by sifting up
+        self._siftup(0)
+        # Return smallest element
+        return elt
+
+    def update(self, elt, new, priority=None):
+        """Replace an element in the queue with a new one."""
+        if priority is not None:
+            new = _HeapElement(priority, new)
+        # Replace
+        pos = self.position[elt]
+        self.heap[pos] = new
+        del self.position[elt]
+        self.position[new] = pos
+        # Restore invariant by sifting up
+        self._siftup(pos)
+
+    def remove(self, elt):
+        """Remove an element from the queue."""
+        # Find and remove element
+        try:
+            pos = self.position[elt]
+            del self.position[elt]
+        except KeyError:
+            # Not in queue
+            raise
+        # If elt is last item, remove and return
+        if pos == len(self.heap) - 1:
+            self.heap.pop()
+            return
+        # Replace elt with last element
+        last = self.heap.pop()
+        self.heap[pos] = last
+        self.position[last] = pos
+        # Restore invariant by sifting up
+        self._siftup(pos)
+
+    def _siftup(self, pos):
+        """Move smaller child up until hitting a leaf.
+
+        Built to mimic code for heapq._siftup
+        only updating position dict too.
+        """
+        heap, position = self.heap, self.position
+        end_pos = len(heap)
+        startpos = pos
+        newitem = heap[pos]
+        # Shift up the smaller child until hitting a leaf
+        child_pos = (pos << 1) + 1  # start with leftmost child position
+        while child_pos < end_pos:
+            # Set child_pos to index of smaller child.
+            child = heap[child_pos]
+            right_pos = child_pos + 1
+            if right_pos < end_pos:
+                right = heap[right_pos]
+                if not child < right:
+                    child = right
+                    child_pos = right_pos
+            # Move the smaller child up.
+            heap[pos] = child
+            position[child] = pos
+            pos = child_pos
+            child_pos = (pos << 1) + 1
+        # pos is a leaf position. Put newitem there, and bubble it up
+        # to its final resting place (by sifting its parents down).
+        while pos > 0:
+            parent_pos = (pos - 1) >> 1
+            parent = heap[parent_pos]
+            if not newitem < parent:
+                break
+            heap[pos] = parent
+            position[parent] = pos
+            pos = parent_pos
+        heap[pos] = newitem
+        position[newitem] = pos
+
+    def _siftdown(self, start_pos, pos):
+        """Restore invariant. keep swapping with parent until smaller.
+
+        Built to mimic code for heapq._siftdown
+        only updating position dict too.
+        """
+        heap, position = self.heap, self.position
+        newitem = heap[pos]
+        # Follow the path to the root, moving parents down until finding a place
+        # newitem fits.
+        while pos > start_pos:
+            parent_pos = (pos - 1) >> 1
+            parent = heap[parent_pos]
+            if not newitem < parent:
+                break
+            heap[pos] = parent
+            position[parent] = pos
+            pos = parent_pos
+        heap[pos] = newitem
+        position[newitem] = pos
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/misc.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/misc.py
new file mode 100644
index 0000000000000000000000000000000000000000..f848113f4c5a7a2aeb09504e71f4e4b6da0061c3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/misc.py
@@ -0,0 +1,703 @@
+"""
+Miscellaneous Helpers for NetworkX.
+
+These are not imported into the base networkx namespace but
+can be accessed, for example, as
+
+>>> import networkx as nx
+>>> nx.utils.make_list_of_ints({1, 2, 3})
+[1, 2, 3]
+>>> nx.utils.arbitrary_element({5, 1, 7})  # doctest: +SKIP
+1
+"""
+
+import itertools
+import random
+import warnings
+from collections import defaultdict
+from collections.abc import Iterable, Iterator, Sized
+from itertools import chain, tee, zip_longest
+
+import networkx as nx
+
+__all__ = [
+    "flatten",
+    "make_list_of_ints",
+    "dict_to_numpy_array",
+    "arbitrary_element",
+    "pairwise",
+    "groups",
+    "create_random_state",
+    "create_py_random_state",
+    "PythonRandomInterface",
+    "PythonRandomViaNumpyBits",
+    "nodes_equal",
+    "edges_equal",
+    "graphs_equal",
+    "_clear_cache",
+]
+
+
+# some cookbook stuff
+# used in deciding whether something is a bunch of nodes, edges, etc.
+# see G.add_nodes and others in Graph Class in networkx/base.py
+
+
+def flatten(obj, result=None):
+    """Return flattened version of (possibly nested) iterable object."""
+    if not isinstance(obj, Iterable | Sized) or isinstance(obj, str):
+        return obj
+    if result is None:
+        result = []
+    for item in obj:
+        if not isinstance(item, Iterable | Sized) or isinstance(item, str):
+            result.append(item)
+        else:
+            flatten(item, result)
+    return tuple(result)
+
+
+def make_list_of_ints(sequence):
+    """Return list of ints from sequence of integral numbers.
+
+    All elements of the sequence must satisfy int(element) == element
+    or a ValueError is raised. Sequence is iterated through once.
+
+    If sequence is a list, the non-int values are replaced with ints.
+    So, no new list is created
+    """
+    if not isinstance(sequence, list):
+        result = []
+        for i in sequence:
+            errmsg = f"sequence is not all integers: {i}"
+            try:
+                ii = int(i)
+            except ValueError:
+                raise nx.NetworkXError(errmsg) from None
+            if ii != i:
+                raise nx.NetworkXError(errmsg)
+            result.append(ii)
+        return result
+    # original sequence is a list... in-place conversion to ints
+    for indx, i in enumerate(sequence):
+        errmsg = f"sequence is not all integers: {i}"
+        if isinstance(i, int):
+            continue
+        try:
+            ii = int(i)
+        except ValueError:
+            raise nx.NetworkXError(errmsg) from None
+        if ii != i:
+            raise nx.NetworkXError(errmsg)
+        sequence[indx] = ii
+    return sequence
+
+
+def dict_to_numpy_array(d, mapping=None):
+    """Convert a dictionary of dictionaries to a numpy array
+    with optional mapping."""
+    try:
+        return _dict_to_numpy_array2(d, mapping)
+    except (AttributeError, TypeError):
+        # AttributeError is when no mapping was provided and v.keys() fails.
+        # TypeError is when a mapping was provided and d[k1][k2] fails.
+        return _dict_to_numpy_array1(d, mapping)
+
+
+def _dict_to_numpy_array2(d, mapping=None):
+    """Convert a dictionary of dictionaries to a 2d numpy array
+    with optional mapping.
+
+    """
+    import numpy as np
+
+    if mapping is None:
+        s = set(d.keys())
+        for k, v in d.items():
+            s.update(v.keys())
+        mapping = dict(zip(s, range(len(s))))
+    n = len(mapping)
+    a = np.zeros((n, n))
+    for k1, i in mapping.items():
+        for k2, j in mapping.items():
+            try:
+                a[i, j] = d[k1][k2]
+            except KeyError:
+                pass
+    return a
+
+
+def _dict_to_numpy_array1(d, mapping=None):
+    """Convert a dictionary of numbers to a 1d numpy array with optional mapping."""
+    import numpy as np
+
+    if mapping is None:
+        s = set(d.keys())
+        mapping = dict(zip(s, range(len(s))))
+    n = len(mapping)
+    a = np.zeros(n)
+    for k1, i in mapping.items():
+        i = mapping[k1]
+        a[i] = d[k1]
+    return a
+
+
+def arbitrary_element(iterable):
+    """Returns an arbitrary element of `iterable` without removing it.
+
+    This is most useful for "peeking" at an arbitrary element of a set,
+    but can be used for any list, dictionary, etc., as well.
+
+    Parameters
+    ----------
+    iterable : `abc.collections.Iterable` instance
+        Any object that implements ``__iter__``, e.g. set, dict, list, tuple,
+        etc.
+
+    Returns
+    -------
+    The object that results from ``next(iter(iterable))``
+
+    Raises
+    ------
+    ValueError
+        If `iterable` is an iterator (because the current implementation of
+        this function would consume an element from the iterator).
+
+    Examples
+    --------
+    Arbitrary elements from common Iterable objects:
+
+    >>> nx.utils.arbitrary_element([1, 2, 3])  # list
+    1
+    >>> nx.utils.arbitrary_element((1, 2, 3))  # tuple
+    1
+    >>> nx.utils.arbitrary_element({1, 2, 3})  # set
+    1
+    >>> d = {k: v for k, v in zip([1, 2, 3], [3, 2, 1])}
+    >>> nx.utils.arbitrary_element(d)  # dict_keys
+    1
+    >>> nx.utils.arbitrary_element(d.values())  # dict values
+    3
+
+    `str` is also an Iterable:
+
+    >>> nx.utils.arbitrary_element("hello")
+    'h'
+
+    :exc:`ValueError` is raised if `iterable` is an iterator:
+
+    >>> iterator = iter([1, 2, 3])  # Iterator, *not* Iterable
+    >>> nx.utils.arbitrary_element(iterator)
+    Traceback (most recent call last):
+        ...
+    ValueError: cannot return an arbitrary item from an iterator
+
+    Notes
+    -----
+    This function does not return a *random* element. If `iterable` is
+    ordered, sequential calls will return the same value::
+
+        >>> l = [1, 2, 3]
+        >>> nx.utils.arbitrary_element(l)
+        1
+        >>> nx.utils.arbitrary_element(l)
+        1
+
+    """
+    if isinstance(iterable, Iterator):
+        raise ValueError("cannot return an arbitrary item from an iterator")
+    # Another possible implementation is ``for x in iterable: return x``.
+    return next(iter(iterable))
+
+
+def pairwise(iterable, cyclic=False):
+    """Return successive overlapping pairs taken from an input iterable.
+
+    Parameters
+    ----------
+    iterable : iterable
+        An iterable from which to generate pairs.
+
+    cyclic : bool, optional (default=False)
+        If `True`, a pair with the last and first items is included at the end.
+
+    Returns
+    -------
+    iterator
+        An iterator over successive overlapping pairs from the `iterable`.
+
+    See Also
+    --------
+    itertools.pairwise
+
+    Examples
+    --------
+    >>> list(nx.utils.pairwise([1, 2, 3, 4]))
+    [(1, 2), (2, 3), (3, 4)]
+
+    >>> list(nx.utils.pairwise([1, 2, 3, 4], cyclic=True))
+    [(1, 2), (2, 3), (3, 4), (4, 1)]
+    """
+    if not cyclic:
+        return itertools.pairwise(iterable)
+    a, b = tee(iterable)
+    first = next(b, None)
+    return zip(a, chain(b, (first,)))
+
+
+def groups(many_to_one):
+    """Converts a many-to-one mapping into a one-to-many mapping.
+
+    `many_to_one` must be a dictionary whose keys and values are all
+    :term:`hashable`.
+
+    The return value is a dictionary mapping values from `many_to_one`
+    to sets of keys from `many_to_one` that have that value.
+
+    Examples
+    --------
+    >>> from networkx.utils import groups
+    >>> many_to_one = {"a": 1, "b": 1, "c": 2, "d": 3, "e": 3}
+    >>> groups(many_to_one)  # doctest: +SKIP
+    {1: {'a', 'b'}, 2: {'c'}, 3: {'e', 'd'}}
+    """
+    one_to_many = defaultdict(set)
+    for v, k in many_to_one.items():
+        one_to_many[k].add(v)
+    return dict(one_to_many)
+
+
+def create_random_state(random_state=None):
+    """Returns a numpy.random.RandomState or numpy.random.Generator instance
+    depending on input.
+
+    Parameters
+    ----------
+    random_state : int or NumPy RandomState or Generator instance, optional (default=None)
+        If int, return a numpy.random.RandomState instance set with seed=int.
+        if `numpy.random.RandomState` instance, return it.
+        if `numpy.random.Generator` instance, return it.
+        if None or numpy.random, return the global random number generator used
+        by numpy.random.
+    """
+    import numpy as np
+
+    if random_state is None or random_state is np.random:
+        return np.random.mtrand._rand
+    if isinstance(random_state, np.random.RandomState):
+        return random_state
+    if isinstance(random_state, int):
+        return np.random.RandomState(random_state)
+    if isinstance(random_state, np.random.Generator):
+        return random_state
+    msg = (
+        f"{random_state} cannot be used to create a numpy.random.RandomState or\n"
+        "numpy.random.Generator instance"
+    )
+    raise ValueError(msg)
+
+
+class PythonRandomViaNumpyBits(random.Random):
+    """Provide the random.random algorithms using a numpy.random bit generator
+
+    The intent is to allow people to contribute code that uses Python's random
+    library, but still allow users to provide a single easily controlled random
+    bit-stream for all work with NetworkX. This implementation is based on helpful
+    comments and code from Robert Kern on NumPy's GitHub Issue #24458.
+
+    This implementation supersedes that of `PythonRandomInterface` which rewrote
+    methods to account for subtle differences in API between `random` and
+    `numpy.random`. Instead this subclasses `random.Random` and overwrites
+    the methods `random`, `getrandbits`, `getstate`, `setstate` and `seed`.
+    It makes them use the rng values from an input numpy `RandomState` or `Generator`.
+    Those few methods allow the rest of the `random.Random` methods to provide
+    the API interface of `random.random` while using randomness generated by
+    a numpy generator.
+    """
+
+    def __init__(self, rng=None):
+        try:
+            import numpy as np
+        except ImportError:
+            msg = "numpy not found, only random.random available."
+            warnings.warn(msg, ImportWarning)
+
+        if rng is None:
+            self._rng = np.random.mtrand._rand
+        else:
+            self._rng = rng
+
+        # Not necessary, given our overriding of gauss() below, but it's
+        # in the superclass and nominally public, so initialize it here.
+        self.gauss_next = None
+
+    def random(self):
+        """Get the next random number in the range 0.0 <= X < 1.0."""
+        return self._rng.random()
+
+    def getrandbits(self, k):
+        """getrandbits(k) -> x.  Generates an int with k random bits."""
+        if k < 0:
+            raise ValueError("number of bits must be non-negative")
+        numbytes = (k + 7) // 8  # bits / 8 and rounded up
+        x = int.from_bytes(self._rng.bytes(numbytes), "big")
+        return x >> (numbytes * 8 - k)  # trim excess bits
+
+    def getstate(self):
+        return self._rng.__getstate__()
+
+    def setstate(self, state):
+        self._rng.__setstate__(state)
+
+    def seed(self, *args, **kwds):
+        "Do nothing override method."
+        raise NotImplementedError("seed() not implemented in PythonRandomViaNumpyBits")
+
+
+##################################################################
+class PythonRandomInterface:
+    """PythonRandomInterface is included for backward compatibility
+    New code should use PythonRandomViaNumpyBits instead.
+    """
+
+    def __init__(self, rng=None):
+        try:
+            import numpy as np
+        except ImportError:
+            msg = "numpy not found, only random.random available."
+            warnings.warn(msg, ImportWarning)
+
+        if rng is None:
+            self._rng = np.random.mtrand._rand
+        else:
+            self._rng = rng
+
+    def random(self):
+        return self._rng.random()
+
+    def uniform(self, a, b):
+        return a + (b - a) * self._rng.random()
+
+    def randrange(self, a, b=None):
+        import numpy as np
+
+        if b is None:
+            a, b = 0, a
+        if b > 9223372036854775807:  # from np.iinfo(np.int64).max
+            tmp_rng = PythonRandomViaNumpyBits(self._rng)
+            return tmp_rng.randrange(a, b)
+
+        if isinstance(self._rng, np.random.Generator):
+            return self._rng.integers(a, b)
+        return self._rng.randint(a, b)
+
+    # NOTE: the numpy implementations of `choice` don't support strings, so
+    # this cannot be replaced with self._rng.choice
+    def choice(self, seq):
+        import numpy as np
+
+        if isinstance(self._rng, np.random.Generator):
+            idx = self._rng.integers(0, len(seq))
+        else:
+            idx = self._rng.randint(0, len(seq))
+        return seq[idx]
+
+    def gauss(self, mu, sigma):
+        return self._rng.normal(mu, sigma)
+
+    def shuffle(self, seq):
+        return self._rng.shuffle(seq)
+
+    #    Some methods don't match API for numpy RandomState.
+    #    Commented out versions are not used by NetworkX
+
+    def sample(self, seq, k):
+        return self._rng.choice(list(seq), size=(k,), replace=False)
+
+    def randint(self, a, b):
+        import numpy as np
+
+        if b > 9223372036854775807:  # from np.iinfo(np.int64).max
+            tmp_rng = PythonRandomViaNumpyBits(self._rng)
+            return tmp_rng.randint(a, b)
+
+        if isinstance(self._rng, np.random.Generator):
+            return self._rng.integers(a, b + 1)
+        return self._rng.randint(a, b + 1)
+
+    #    exponential as expovariate with 1/argument,
+    def expovariate(self, scale):
+        return self._rng.exponential(1 / scale)
+
+    #    pareto as paretovariate with argument,
+    def paretovariate(self, shape):
+        return self._rng.pareto(shape)
+
+
+#    weibull as weibullvariate multiplied by beta,
+#    def weibullvariate(self, alpha, beta):
+#        return self._rng.weibull(alpha) * beta
+#
+#    def triangular(self, low, high, mode):
+#        return self._rng.triangular(low, mode, high)
+#
+#    def choices(self, seq, weights=None, cum_weights=None, k=1):
+#        return self._rng.choice(seq
+
+
+def create_py_random_state(random_state=None):
+    """Returns a random.Random instance depending on input.
+
+    Parameters
+    ----------
+    random_state : int or random number generator or None (default=None)
+        - If int, return a `random.Random` instance set with seed=int.
+        - If `random.Random` instance, return it.
+        - If None or the `np.random` package, return the global random number
+          generator used by `np.random`.
+        - If an `np.random.Generator` instance, or the `np.random` package, or
+          the global numpy random number generator, then return it.
+          wrapped in a `PythonRandomViaNumpyBits` class.
+        - If a `PythonRandomViaNumpyBits` instance, return it.
+        - If a `PythonRandomInterface` instance, return it.
+        - If a `np.random.RandomState` instance and not the global numpy default,
+          return it wrapped in `PythonRandomInterface` for backward bit-stream
+          matching with legacy code.
+
+    Notes
+    -----
+    - A diagram intending to illustrate the relationships behind our support
+      for numpy random numbers is called
+      `NetworkX Numpy Random Numbers `_.
+    - More discussion about this support also appears in
+      `gh-6869#comment `_.
+    - Wrappers of numpy.random number generators allow them to mimic the Python random
+      number generation algorithms. For example, Python can create arbitrarily large
+      random ints, and the wrappers use Numpy bit-streams with CPython's random module
+      to choose arbitrarily large random integers too.
+    - We provide two wrapper classes:
+      `PythonRandomViaNumpyBits` is usually what you want and is always used for
+      `np.Generator` instances. But for users who need to recreate random numbers
+      produced in NetworkX 3.2 or earlier, we maintain the `PythonRandomInterface`
+      wrapper as well. We use it only used if passed a (non-default) `np.RandomState`
+      instance pre-initialized from a seed. Otherwise the newer wrapper is used.
+    """
+    if random_state is None or random_state is random:
+        return random._inst
+    if isinstance(random_state, random.Random):
+        return random_state
+    if isinstance(random_state, int):
+        return random.Random(random_state)
+
+    try:
+        import numpy as np
+    except ImportError:
+        pass
+    else:
+        if isinstance(random_state, PythonRandomInterface | PythonRandomViaNumpyBits):
+            return random_state
+        if isinstance(random_state, np.random.Generator):
+            return PythonRandomViaNumpyBits(random_state)
+        if random_state is np.random:
+            return PythonRandomViaNumpyBits(np.random.mtrand._rand)
+
+        if isinstance(random_state, np.random.RandomState):
+            if random_state is np.random.mtrand._rand:
+                return PythonRandomViaNumpyBits(random_state)
+            # Only need older interface if specially constructed RandomState used
+            return PythonRandomInterface(random_state)
+
+    msg = f"{random_state} cannot be used to generate a random.Random instance"
+    raise ValueError(msg)
+
+
+def nodes_equal(nodes1, nodes2):
+    """Check if nodes are equal.
+
+    Equality here means equal as Python objects.
+    Node data must match if included.
+    The order of nodes is not relevant.
+
+    Parameters
+    ----------
+    nodes1, nodes2 : iterables of nodes, or (node, datadict) tuples
+
+    Returns
+    -------
+    bool
+        True if nodes are equal, False otherwise.
+    """
+    nlist1 = list(nodes1)
+    nlist2 = list(nodes2)
+    try:
+        d1 = dict(nlist1)
+        d2 = dict(nlist2)
+    except (ValueError, TypeError):
+        d1 = dict.fromkeys(nlist1)
+        d2 = dict.fromkeys(nlist2)
+    return d1 == d2
+
+
+def edges_equal(edges1, edges2, *, directed=False):
+    """Return whether edgelists are equal.
+
+    Equality here means equal as Python objects. Edge data must match
+    if included. Ordering of edges in an edgelist is not relevant;
+    ordering of nodes in an edge is only relevant if ``directed == True``.
+
+    Parameters
+    ----------
+    edges1, edges2 : iterables of tuples
+        Each tuple can be
+        an edge tuple ``(u, v)``, or
+        an edge tuple with data `dict` s ``(u, v, d)``, or
+        an edge tuple with keys and data `dict` s ``(u, v, k, d)``.
+
+    directed : bool, optional (default=False)
+        If `True`, edgelists are treated as coming from directed
+        graphs.
+
+    Returns
+    -------
+    bool
+        `True` if edgelists are equal, `False` otherwise.
+
+    Examples
+    --------
+    >>> G1 = nx.complete_graph(3)
+    >>> G2 = nx.cycle_graph(3)
+    >>> edges_equal(G1.edges, G2.edges)
+    True
+
+    Edge order is not taken into account:
+
+    >>> G1 = nx.Graph([(0, 1), (1, 2)])
+    >>> G2 = nx.Graph([(1, 2), (0, 1)])
+    >>> edges_equal(G1.edges, G2.edges)
+    True
+
+    The `directed` parameter controls whether edges are treated as
+    coming from directed graphs.
+
+    >>> DG1 = nx.DiGraph([(0, 1)])
+    >>> DG2 = nx.DiGraph([(1, 0)])
+    >>> edges_equal(DG1.edges, DG2.edges, directed=False)  # Not recommended.
+    True
+    >>> edges_equal(DG1.edges, DG2.edges, directed=True)
+    False
+
+    This function is meant to be used on edgelists (i.e. the output of a
+    ``G.edges()`` call), and can give unexpected results on unprocessed
+    lists of edges:
+
+    >>> l1 = [(0, 1)]
+    >>> l2 = [(0, 1), (1, 0)]
+    >>> edges_equal(l1, l2)  # Not recommended.
+    False
+    >>> G1 = nx.Graph(l1)
+    >>> G2 = nx.Graph(l2)
+    >>> edges_equal(G1.edges, G2.edges)
+    True
+    >>> DG1 = nx.DiGraph(l1)
+    >>> DG2 = nx.DiGraph(l2)
+    >>> edges_equal(DG1.edges, DG2.edges, directed=True)
+    False
+    """
+    d1 = defaultdict(list)
+    d2 = defaultdict(list)
+
+    for e1, e2 in zip_longest(edges1, edges2, fillvalue=None):
+        if e1 is None or e2 is None:
+            return False  # One is longer.
+        for e, d in [(e1, d1), (e2, d2)]:
+            u, v, *data = e
+            d[u, v].append(data)
+            if not directed:
+                d[v, u].append(data)
+
+    # Can check one direction because lengths are the same.
+    return all(d1[e].count(data) == d2[e].count(data) for e in d1 for data in d1[e])
+
+
+def graphs_equal(graph1, graph2):
+    """Check if graphs are equal.
+
+    Equality here means equal as Python objects (not isomorphism).
+    Node, edge and graph data must match.
+
+    Parameters
+    ----------
+    graph1, graph2 : graph
+
+    Returns
+    -------
+    bool
+        True if graphs are equal, False otherwise.
+    """
+    return (
+        graph1.adj == graph2.adj
+        and graph1.nodes == graph2.nodes
+        and graph1.graph == graph2.graph
+    )
+
+
+def _clear_cache(G):
+    """Clear the cache of a graph (currently stores converted graphs).
+
+    Caching is controlled via ``nx.config.cache_converted_graphs`` configuration.
+    """
+    if cache := getattr(G, "__networkx_cache__", None):
+        cache.clear()
+
+
+def check_create_using(create_using, *, directed=None, multigraph=None, default=None):
+    """Assert that create_using has good properties
+
+    This checks for desired directedness and multi-edge properties.
+    It returns `create_using` unless that is `None` when it returns
+    the optionally specified default value.
+
+    Parameters
+    ----------
+    create_using : None, graph class or instance
+        The input value of create_using for a function.
+    directed : None or bool
+        Whether to check `create_using.is_directed() == directed`.
+        If None, do not assert directedness.
+    multigraph : None or bool
+        Whether to check `create_using.is_multigraph() == multigraph`.
+        If None, do not assert multi-edge property.
+    default : None or graph class
+        The graph class to return if create_using is None.
+
+    Returns
+    -------
+    create_using : graph class or instance
+        The provided graph class or instance, or if None, the `default` value.
+
+    Raises
+    ------
+    NetworkXError
+        When `create_using` doesn't match the properties specified by `directed`
+        or `multigraph` parameters.
+    """
+    if default is None:
+        default = nx.Graph
+    G = create_using if create_using is not None else default
+
+    G_directed = G.is_directed(None) if isinstance(G, type) else G.is_directed()
+    G_multigraph = G.is_multigraph(None) if isinstance(G, type) else G.is_multigraph()
+
+    if directed is not None:
+        if directed and not G_directed:
+            raise nx.NetworkXError("create_using must be directed")
+        if not directed and G_directed:
+            raise nx.NetworkXError("create_using must not be directed")
+
+    if multigraph is not None:
+        if multigraph and not G_multigraph:
+            raise nx.NetworkXError("create_using must be a multi-graph")
+        if not multigraph and G_multigraph:
+            raise nx.NetworkXError("create_using must not be a multi-graph")
+    return G
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/random_sequence.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/random_sequence.py
new file mode 100644
index 0000000000000000000000000000000000000000..f4513034d15034f0783982b8361d2290d30bd1ac
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/random_sequence.py
@@ -0,0 +1,198 @@
+"""
+Utilities for generating random numbers, random sequences, and
+random selections.
+"""
+
+import networkx as nx
+from networkx.utils import py_random_state
+
+__all__ = [
+    "powerlaw_sequence",
+    "is_valid_tree_degree_sequence",
+    "zipf_rv",
+    "cumulative_distribution",
+    "discrete_sequence",
+    "random_weighted_sample",
+    "weighted_choice",
+]
+
+
+# The same helpers for choosing random sequences from distributions
+# uses Python's random module
+# https://docs.python.org/3/library/random.html
+
+
+@py_random_state(2)
+def powerlaw_sequence(n, exponent=2.0, seed=None):
+    """
+    Return sample sequence of length n from a power law distribution.
+    """
+    return [seed.paretovariate(exponent - 1) for i in range(n)]
+
+
+def is_valid_tree_degree_sequence(degree_sequence):
+    """Check if a degree sequence is valid for a tree.
+
+    Two conditions must be met for a degree sequence to be valid for a tree:
+
+    1. The number of nodes must be one more than the number of edges.
+    2. The degree sequence must be trivial or have only strictly positive
+       node degrees.
+
+    Parameters
+    ----------
+    degree_sequence : iterable
+        Iterable of node degrees.
+
+    Returns
+    -------
+    bool
+        Whether the degree sequence is valid for a tree.
+    str
+        Reason for invalidity, or dummy string if valid.
+    """
+    seq = list(degree_sequence)
+    number_of_nodes = len(seq)
+    twice_number_of_edges = sum(seq)
+
+    if 2 * number_of_nodes - twice_number_of_edges != 2:
+        return False, "tree must have one more node than number of edges"
+    elif seq != [0] and any(d <= 0 for d in seq):
+        return False, "nontrivial tree must have strictly positive node degrees"
+    return True, ""
+
+
+@py_random_state(2)
+def zipf_rv(alpha, xmin=1, seed=None):
+    r"""Returns a random value chosen from the Zipf distribution.
+
+    The return value is an integer drawn from the probability distribution
+
+    .. math::
+
+        p(x)=\frac{x^{-\alpha}}{\zeta(\alpha, x_{\min})},
+
+    where $\zeta(\alpha, x_{\min})$ is the Hurwitz zeta function.
+
+    Parameters
+    ----------
+    alpha : float
+      Exponent value of the distribution
+    xmin : int
+      Minimum value
+    seed : integer, random_state, or None (default)
+        Indicator of random number generation state.
+        See :ref:`Randomness`.
+
+    Returns
+    -------
+    x : int
+      Random value from Zipf distribution
+
+    Raises
+    ------
+    ValueError:
+      If xmin < 1 or
+      If alpha <= 1
+
+    Notes
+    -----
+    The rejection algorithm generates random values for a the power-law
+    distribution in uniformly bounded expected time dependent on
+    parameters.  See [1]_ for details on its operation.
+
+    Examples
+    --------
+    >>> nx.utils.zipf_rv(alpha=2, xmin=3, seed=42)
+    8
+
+    References
+    ----------
+    .. [1] Luc Devroye, Non-Uniform Random Variate Generation,
+       Springer-Verlag, New York, 1986.
+    """
+    if xmin < 1:
+        raise ValueError("xmin < 1")
+    if alpha <= 1:
+        raise ValueError("a <= 1.0")
+    a1 = alpha - 1.0
+    b = 2**a1
+    while True:
+        u = 1.0 - seed.random()  # u in (0,1]
+        v = seed.random()  # v in [0,1)
+        x = int(xmin * u ** -(1.0 / a1))
+        t = (1.0 + (1.0 / x)) ** a1
+        if v * x * (t - 1.0) / (b - 1.0) <= t / b:
+            break
+    return x
+
+
+def cumulative_distribution(distribution):
+    """Returns normalized cumulative distribution from discrete distribution."""
+
+    cdf = [0.0]
+    cumulative = 0.0
+    for element in distribution:
+        cumulative += element
+        cdf.append(cumulative)
+    return [element / cumulative for element in cdf]
+
+
+@py_random_state(3)
+def discrete_sequence(n, distribution=None, cdistribution=None, seed=None):
+    """
+    Return sample sequence of length n from a given discrete distribution
+    or discrete cumulative distribution.
+
+    One of the following must be specified.
+
+    distribution = histogram of values, will be normalized
+
+    cdistribution = normalized discrete cumulative distribution
+
+    """
+    import bisect
+
+    if cdistribution is not None:
+        cdf = cdistribution
+    elif distribution is not None:
+        cdf = cumulative_distribution(distribution)
+    else:
+        raise nx.NetworkXError(
+            "discrete_sequence: distribution or cdistribution missing"
+        )
+
+    # get a uniform random number
+    inputseq = [seed.random() for i in range(n)]
+
+    # choose from CDF
+    seq = [bisect.bisect_left(cdf, s) - 1 for s in inputseq]
+    return seq
+
+
+@py_random_state(2)
+def random_weighted_sample(mapping, k, seed=None):
+    """Returns k items without replacement from a weighted sample.
+
+    The input is a dictionary of items with weights as values.
+    """
+    if k > len(mapping):
+        raise ValueError("sample larger than population")
+    sample = set()
+    while len(sample) < k:
+        sample.add(weighted_choice(mapping, seed))
+    return list(sample)
+
+
+@py_random_state(1)
+def weighted_choice(mapping, seed=None):
+    """Returns a single element from a weighted sample.
+
+    The input is a dictionary of items with weights as values.
+    """
+    # use roulette method
+    rnd = seed.random() * sum(mapping.values())
+    for k, w in mapping.items():
+        rnd -= w
+        if rnd < 0:
+            return k
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/rcm.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/rcm.py
new file mode 100644
index 0000000000000000000000000000000000000000..7465c50d5af49095e421c509e36b33f2476ae157
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/rcm.py
@@ -0,0 +1,159 @@
+"""
+Cuthill-McKee ordering of graph nodes to produce sparse matrices
+"""
+
+from collections import deque
+from operator import itemgetter
+
+import networkx as nx
+
+from ..utils import arbitrary_element
+
+__all__ = ["cuthill_mckee_ordering", "reverse_cuthill_mckee_ordering"]
+
+
+def cuthill_mckee_ordering(G, heuristic=None):
+    """Generate an ordering (permutation) of the graph nodes to make
+    a sparse matrix.
+
+    Uses the Cuthill-McKee heuristic (based on breadth-first search) [1]_.
+
+    Parameters
+    ----------
+    G : graph
+      A NetworkX graph
+
+    heuristic : function, optional
+      Function to choose starting node for RCM algorithm.  If None
+      a node from a pseudo-peripheral pair is used.  A user-defined function
+      can be supplied that takes a graph object and returns a single node.
+
+    Returns
+    -------
+    nodes : generator
+       Generator of nodes in Cuthill-McKee ordering.
+
+    Examples
+    --------
+    >>> from networkx.utils import cuthill_mckee_ordering
+    >>> G = nx.path_graph(4)
+    >>> rcm = list(cuthill_mckee_ordering(G))
+    >>> A = nx.adjacency_matrix(G, nodelist=rcm)
+
+    Smallest degree node as heuristic function:
+
+    >>> def smallest_degree(G):
+    ...     return min(G, key=G.degree)
+    >>> rcm = list(cuthill_mckee_ordering(G, heuristic=smallest_degree))
+
+
+    See Also
+    --------
+    reverse_cuthill_mckee_ordering
+
+    Notes
+    -----
+    The optimal solution the bandwidth reduction is NP-complete [2]_.
+
+
+    References
+    ----------
+    .. [1] E. Cuthill and J. McKee.
+       Reducing the bandwidth of sparse symmetric matrices,
+       In Proc. 24th Nat. Conf. ACM, pages 157-172, 1969.
+       http://doi.acm.org/10.1145/800195.805928
+    .. [2]  Steven S. Skiena. 1997. The Algorithm Design Manual.
+       Springer-Verlag New York, Inc., New York, NY, USA.
+    """
+    for c in nx.connected_components(G):
+        yield from connected_cuthill_mckee_ordering(G.subgraph(c), heuristic)
+
+
+def reverse_cuthill_mckee_ordering(G, heuristic=None):
+    """Generate an ordering (permutation) of the graph nodes to make
+    a sparse matrix.
+
+    Uses the reverse Cuthill-McKee heuristic (based on breadth-first search)
+    [1]_.
+
+    Parameters
+    ----------
+    G : graph
+      A NetworkX graph
+
+    heuristic : function, optional
+      Function to choose starting node for RCM algorithm.  If None
+      a node from a pseudo-peripheral pair is used.  A user-defined function
+      can be supplied that takes a graph object and returns a single node.
+
+    Returns
+    -------
+    nodes : generator
+       Generator of nodes in reverse Cuthill-McKee ordering.
+
+    Examples
+    --------
+    >>> from networkx.utils import reverse_cuthill_mckee_ordering
+    >>> G = nx.path_graph(4)
+    >>> rcm = list(reverse_cuthill_mckee_ordering(G))
+    >>> A = nx.adjacency_matrix(G, nodelist=rcm)
+
+    Smallest degree node as heuristic function:
+
+    >>> def smallest_degree(G):
+    ...     return min(G, key=G.degree)
+    >>> rcm = list(reverse_cuthill_mckee_ordering(G, heuristic=smallest_degree))
+
+
+    See Also
+    --------
+    cuthill_mckee_ordering
+
+    Notes
+    -----
+    The optimal solution the bandwidth reduction is NP-complete [2]_.
+
+    References
+    ----------
+    .. [1] E. Cuthill and J. McKee.
+       Reducing the bandwidth of sparse symmetric matrices,
+       In Proc. 24th Nat. Conf. ACM, pages 157-72, 1969.
+       http://doi.acm.org/10.1145/800195.805928
+    .. [2]  Steven S. Skiena. 1997. The Algorithm Design Manual.
+       Springer-Verlag New York, Inc., New York, NY, USA.
+    """
+    return reversed(list(cuthill_mckee_ordering(G, heuristic=heuristic)))
+
+
+def connected_cuthill_mckee_ordering(G, heuristic=None):
+    # the cuthill mckee algorithm for connected graphs
+    if heuristic is None:
+        start = pseudo_peripheral_node(G)
+    else:
+        start = heuristic(G)
+    visited = {start}
+    queue = deque([start])
+    while queue:
+        parent = queue.popleft()
+        yield parent
+        nd = sorted(G.degree(set(G[parent]) - visited), key=itemgetter(1))
+        children = [n for n, d in nd]
+        visited.update(children)
+        queue.extend(children)
+
+
+def pseudo_peripheral_node(G):
+    # helper for cuthill-mckee to find a node in a "pseudo peripheral pair"
+    # to use as good starting node
+    u = arbitrary_element(G)
+    lp = 0
+    v = u
+    while True:
+        spl = nx.shortest_path_length(G, v)
+        l = max(spl.values())
+        if l <= lp:
+            break
+        lp = l
+        farthest = (n for n, dist in spl.items() if dist == l)
+        v, deg = min(G.degree(farthest), key=itemgetter(1))
+    return v
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/union_find.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/union_find.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a07129f5427cd8a3caf30095efee125bc3d853b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/networkx/utils/union_find.py
@@ -0,0 +1,106 @@
+"""
+Union-find data structure.
+"""
+
+from networkx.utils import groups
+
+
+class UnionFind:
+    """Union-find data structure.
+
+    Each unionFind instance X maintains a family of disjoint sets of
+    hashable objects, supporting the following two methods:
+
+    - X[item] returns a name for the set containing the given item.
+      Each set is named by an arbitrarily-chosen one of its members; as
+      long as the set remains unchanged it will keep the same name. If
+      the item is not yet part of a set in X, a new singleton set is
+      created for it.
+
+    - X.union(item1, item2, ...) merges the sets containing each item
+      into a single larger set.  If any item is not yet part of a set
+      in X, it is added to X as one of the members of the merged set.
+
+      Union-find data structure. Based on Josiah Carlson's code,
+      https://code.activestate.com/recipes/215912/
+      with significant additional changes by D. Eppstein.
+      http://www.ics.uci.edu/~eppstein/PADS/UnionFind.py
+
+    """
+
+    def __init__(self, elements=None):
+        """Create a new empty union-find structure.
+
+        If *elements* is an iterable, this structure will be initialized
+        with the discrete partition on the given set of elements.
+
+        """
+        if elements is None:
+            elements = ()
+        self.parents = {}
+        self.weights = {}
+        for x in elements:
+            self.weights[x] = 1
+            self.parents[x] = x
+
+    def __getitem__(self, object):
+        """Find and return the name of the set containing the object."""
+
+        # check for previously unknown object
+        if object not in self.parents:
+            self.parents[object] = object
+            self.weights[object] = 1
+            return object
+
+        # find path of objects leading to the root
+        path = []
+        root = self.parents[object]
+        while root != object:
+            path.append(object)
+            object = root
+            root = self.parents[object]
+
+        # compress the path and return
+        for ancestor in path:
+            self.parents[ancestor] = root
+        return root
+
+    def __iter__(self):
+        """Iterate through all items ever found or unioned by this structure."""
+        return iter(self.parents)
+
+    def to_sets(self):
+        """Iterates over the sets stored in this structure.
+
+        For example::
+
+            >>> partition = UnionFind("xyz")
+            >>> sorted(map(sorted, partition.to_sets()))
+            [['x'], ['y'], ['z']]
+            >>> partition.union("x", "y")
+            >>> sorted(map(sorted, partition.to_sets()))
+            [['x', 'y'], ['z']]
+
+        """
+        # Ensure fully pruned paths
+        for x in self.parents:
+            _ = self[x]  # Evaluated for side-effect only
+
+        yield from groups(self.parents).values()
+
+    def union(self, *objects):
+        """Find the sets containing the objects and merge them all."""
+        # Find the heaviest root according to its weight.
+        roots = iter(
+            sorted(
+                {self[x] for x in objects}, key=lambda r: self.weights[r], reverse=True
+            )
+        )
+        try:
+            root = next(roots)
+        except StopIteration:
+            return
+
+        for r in roots:
+            self.weights[root] += self.weights[r]
+            self.parents[r] = root
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/semver/__pycache__/__about__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/semver/__pycache__/__about__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..561836b5ce57c7f14bd062c64ff3ecaa6d31179b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/semver/__pycache__/__about__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/semver/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/semver/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dc861c8a9aa42b39f72a2a16f442d9840a1de2f0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/semver/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/semver/__pycache__/__main__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/semver/__pycache__/__main__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ac4ccb567fde018a9754bfa82e543df716535ead
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/semver/__pycache__/__main__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/semver/__pycache__/_deprecated.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/semver/__pycache__/_deprecated.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..47591a205804c0368557b7a7490b82736149c1ce
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/semver/__pycache__/_deprecated.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/semver/__pycache__/_types.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/semver/__pycache__/_types.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..afe198a019d06b821f1d957db4bc7745ddd575d6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/semver/__pycache__/_types.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/semver/__pycache__/cli.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/semver/__pycache__/cli.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d86d1436d0452ac548e617be0d03986486fb1a43
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/semver/__pycache__/cli.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/semver/__pycache__/version.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/semver/__pycache__/version.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..87e181b37e87b981c9b1450120d88c7a38c60892
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/semver/__pycache__/version.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/cpu/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/cpu/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6d291d2a604a791627960ff377b60fdc0162c038
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/cpu/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/cpu/amp/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/cpu/amp/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e72eb3b92a7f84ee0f0559d8969b81de1f529c2b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/cpu/amp/__init__.py
@@ -0,0 +1,2 @@
+from .autocast_mode import autocast
+from .grad_scaler import GradScaler
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/cpu/amp/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/cpu/amp/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8feb0ea8151c52d2b4f5068a2680e6bfb16f4abc
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/cpu/amp/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/cpu/amp/__pycache__/autocast_mode.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/cpu/amp/__pycache__/autocast_mode.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3a1feed7c884756796b51fed952aa77a958b117b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/cpu/amp/__pycache__/autocast_mode.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/cpu/amp/__pycache__/grad_scaler.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/cpu/amp/__pycache__/grad_scaler.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5e6de4c2b369f255fd822608423142a429f2e215
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/cpu/amp/__pycache__/grad_scaler.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/cpu/amp/autocast_mode.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/cpu/amp/autocast_mode.py
new file mode 100644
index 0000000000000000000000000000000000000000..630fe9e58a4694c5bcb3409301a34fec69bfc199
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/cpu/amp/autocast_mode.py
@@ -0,0 +1,51 @@
+# mypy: allow-untyped-defs
+from typing import Any
+from typing_extensions import deprecated
+
+import torch
+
+
+__all__ = ["autocast"]
+
+
+class autocast(torch.amp.autocast_mode.autocast):
+    r"""
+    See :class:`torch.autocast`.
+    ``torch.cpu.amp.autocast(args...)`` is deprecated. Please use ``torch.amp.autocast("cpu", args...)`` instead.
+    """
+
+    @deprecated(
+        "`torch.cpu.amp.autocast(args...)` is deprecated. "
+        "Please use `torch.amp.autocast('cpu', args...)` instead.",
+        category=FutureWarning,
+    )
+    def __init__(
+        self,
+        enabled: bool = True,
+        dtype: torch.dtype = torch.bfloat16,
+        cache_enabled: bool = True,
+    ):
+        if torch._jit_internal.is_scripting():
+            self._enabled = enabled
+            self.device = "cpu"
+            self.fast_dtype = dtype
+            return
+        super().__init__(
+            "cpu", enabled=enabled, dtype=dtype, cache_enabled=cache_enabled
+        )
+
+    def __enter__(self):
+        if torch._jit_internal.is_scripting():
+            return self
+        return super().__enter__()
+
+    # TODO: discuss a unified TorchScript-friendly API for autocast
+    def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any):  # type: ignore[override]
+        if torch._jit_internal.is_scripting():
+            return
+        return super().__exit__(exc_type, exc_val, exc_tb)
+
+    def __call__(self, func):
+        if torch._jit_internal.is_scripting():
+            return func
+        return super().__call__(func)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/cpu/amp/grad_scaler.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/cpu/amp/grad_scaler.py
new file mode 100644
index 0000000000000000000000000000000000000000..aefaa1c323f5ff9089fc69c7a7aabbb380cc7233
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/cpu/amp/grad_scaler.py
@@ -0,0 +1,35 @@
+from typing_extensions import deprecated
+
+import torch
+
+
+__all__ = ["GradScaler"]
+
+
+class GradScaler(torch.amp.GradScaler):
+    r"""
+    See :class:`torch.amp.GradScaler`.
+    ``torch.cpu.amp.GradScaler(args...)`` is deprecated. Please use ``torch.amp.GradScaler("cpu", args...)`` instead.
+    """
+
+    @deprecated(
+        "`torch.cpu.amp.GradScaler(args...)` is deprecated. "
+        "Please use `torch.amp.GradScaler('cpu', args...)` instead.",
+        category=FutureWarning,
+    )
+    def __init__(
+        self,
+        init_scale: float = 2.0**16,
+        growth_factor: float = 2.0,
+        backoff_factor: float = 0.5,
+        growth_interval: int = 2000,
+        enabled: bool = True,
+    ) -> None:
+        super().__init__(
+            "cpu",
+            init_scale=init_scale,
+            growth_factor=growth_factor,
+            backoff_factor=backoff_factor,
+            growth_interval=growth_interval,
+            enabled=enabled,
+        )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2d12ef5350d1fa9bec8885f3e4202b1175a17d67
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/_checkpointable.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/_checkpointable.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..60254e39c8447e956ede6fba351ad939d284f99e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/_checkpointable.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/_composable_state.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/_composable_state.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8cd244215d85e831e96a6469e6f4c1bcf6ec04a4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/_composable_state.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/_functional_collectives.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/_functional_collectives.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..206792acf420d565549f8af0697ad3ff65a42083
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/_functional_collectives.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/_functional_collectives_impl.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/_functional_collectives_impl.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..85924dd22476bbdb4639a01645ef74ba083d1fa5
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/_functional_collectives_impl.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/_state_dict_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/_state_dict_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..da7d8512ddb9c0e7da96a14edc758f28658e146c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/_state_dict_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/argparse_util.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/argparse_util.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4d18551fa33ab5be35f51094b85d42af03146ed9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/argparse_util.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/c10d_logger.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/c10d_logger.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6f13b160a00bf8d4422fa34e14631fde21b392ff
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/c10d_logger.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/collective_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/collective_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..19c771aace6d5684a0b639f787fb1d65a703b950
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/collective_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/constants.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/constants.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3329a8220fd54960a7f73250e4137bd3fcf0790f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/constants.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/device_mesh.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/device_mesh.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..08ac6bc426a96fc963283c53f5c40cd4ef8dccb1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/device_mesh.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/launch.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/launch.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9fca41e66108ac2ac0298d1ffaf8d872c3d12144
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/launch.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/logging_handlers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/logging_handlers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cc0bb2cffd8c71d53125169a343d854d0845a17a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/logging_handlers.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/remote_device.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/remote_device.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..503d09b3c27f30dabb743192071d41d06d7a14cb
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/remote_device.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/rendezvous.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/rendezvous.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dea8a8f8b2366171ad9a9e5dfcf8786637393d32
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/rendezvous.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/run.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/run.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2b3d43864f89d1fd76a048bf7b0db663e7266c19
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/run.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c5668021e0ad3ed6ecfeb8858fe11c772902dd11
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/__pycache__/utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f6f9ccfa27ee04f0138daa65df48470fe24d770
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/__init__.py
@@ -0,0 +1,4 @@
+from .checkpoint_activation import checkpoint
+from .contract import _get_registry, contract
+from .fully_shard import fully_shard
+from .replicate import replicate
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..56dbdae99ace7535e20d9618e3dc82ccaa090e0b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/__pycache__/checkpoint_activation.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/__pycache__/checkpoint_activation.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8de29fa005ade7b9bdbd8a182071e3d26dee765b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/__pycache__/checkpoint_activation.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/__pycache__/contract.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/__pycache__/contract.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2f77c6ec012a9f8fc5050851981a7bbcb89c4da8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/__pycache__/contract.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/__pycache__/fully_shard.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/__pycache__/fully_shard.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cf37a3c72ceebab88440298baaae2be447861b97
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/__pycache__/fully_shard.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/__pycache__/replicate.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/__pycache__/replicate.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3e32285c64c9bb160b7bd9b0453b273463ce35d6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/__pycache__/replicate.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/checkpoint_activation.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/checkpoint_activation.py
new file mode 100644
index 0000000000000000000000000000000000000000..88253abb4b9cbb6f31e5eb9cc25003d654d82ee1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/checkpoint_activation.py
@@ -0,0 +1,126 @@
+# mypy: allow-untyped-decorators
+# mypy: allow-untyped-defs
+from contextlib import contextmanager, nullcontext
+from typing import Any, ContextManager, Dict, Optional, Tuple
+
+import torch
+import torch.nn as nn
+from torch.utils.checkpoint import (
+    _checkpoint_without_reentrant_generator,
+    _DEFAULT_DETERMINISM_MODE,
+)
+
+from .contract import contract
+
+
+@contextmanager
+def _no_hook(module: nn.Module, user_ctx: Optional[ContextManager] = None):
+    r"""
+    Disable hooks installed by checkpoint to avoid unintentional recursion
+    during backward recomputation.
+    """
+
+    with user_ctx if user_ctx else nullcontext():
+        orig_enable_hook = checkpoint.state(module).enable_hook
+        checkpoint.state(module).enable_hook = False
+        try:
+            yield
+        finally:
+            checkpoint.state(module).enable_hook = orig_enable_hook
+
+
+@contract()
+def checkpoint(module: nn.Module, **kwargs) -> nn.Module:
+    r"""
+    This is a composable activation checkpointing API. Unlike functional
+    activation checkpointing APIs, this one does not require changing model
+    source code. Unlike ``nn.Module`` wrapper activation checkpointing APIs,
+    this one does not modify model structure or fully-qualified names either.
+    Under the hood, it registers activation checkpointing logic as pre- and
+    post-forward hooks. Hence, this API can be easily applied to any model or
+    sub-modules in the model.
+
+    Args:
+        module (nn.Module): the target model or sub-module to apply activation
+            checkpointing.
+
+    Example::
+        >>> # xdoctest: +SKIP
+        >>> import torch.nn as nn
+        >>>
+        >>> class MyModel(nn.Module):
+        >>>     def __init__(self) -> None:
+        >>>         super().__init__()
+        >>>         self.l1 = nn.Linear(10, 10)
+        >>>         self.l2 = nn.Linear(10, 10)
+        >>>
+        >>>     def forward(self, x):
+        >>>         return self.l2(self.l1(x))
+        >>>
+        >>> model = MyModel()
+        >>> checkpoint(model.l1)  # apply activation checkpointing only to l1
+        >>> model(torch.zeros(2, 10)).sum().backward()
+
+    """
+    torch._C._log_api_usage_once("torch.distributed.checkpoint")
+
+    use_reentrant = kwargs.pop("use_reentrant", False)
+    if use_reentrant:
+        raise NotImplementedError(
+            "use_reentrant=True is not supported in composable checkpoint. "
+            "Please use torch.utils.checkpoint.checkpoint instead."
+        )
+    preserve_rng_state = kwargs.pop("preserve_rng_state", True)
+    user_context_fns = kwargs.pop("context_fn", None)
+    determinism_check = kwargs.pop("determinism_check", _DEFAULT_DETERMINISM_MODE)
+    debug = kwargs.pop("debug", False)
+
+    if kwargs:
+        raise ValueError(
+            "Unexpected keyword arguments: " + ",".join(arg for arg in kwargs)
+        )
+
+    def forward_pre_hook(
+        module: nn.Module, args: Tuple[Any, ...], kwargs: Dict[str, Any]
+    ) -> None:
+        if checkpoint.state(module).enable_hook:
+
+            def context_fns():
+                if user_context_fns is not None:
+                    ctx1, ctx2 = user_context_fns()
+                    return ctx1, _no_hook(module, ctx2)
+                else:
+                    return nullcontext(), _no_hook(module)
+
+            checkpoint.state(
+                module
+            )._ac_generator = _checkpoint_without_reentrant_generator(
+                module,
+                preserve_rng_state,
+                context_fns,
+                determinism_check,
+                debug,
+                *args,
+                **kwargs,
+            )
+            next(checkpoint.state(module)._ac_generator)
+
+    def forward_hook(module: nn.Module, inputs: Tuple[Any, ...], output: Any) -> Any:
+        if checkpoint.state(module).enable_hook:
+            try:
+                next(checkpoint.state(module)._ac_generator)
+            except StopIteration:
+                pass
+            else:
+                raise RuntimeError(
+                    "Expected non-reentrant activation checkpoint generator to be exhausted, but it was not!"
+                )
+
+        #  Ensure that we no longer hold on to the generator. always_call=True helps ensure we
+        # clear this even in the case of exception in fwd pass.
+        checkpoint.state(module)._ac_generator = None
+
+    checkpoint.state(module).enable_hook = True
+    module.register_forward_pre_hook(forward_pre_hook, with_kwargs=True)
+    module.register_forward_hook(forward_hook, prepend=True, always_call=True)
+    return module
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/contract.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/contract.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7cd1713fae4c2eef3677242180ca719566ffe7f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/contract.py
@@ -0,0 +1,224 @@
+# mypy: allow-untyped-defs
+import uuid
+from collections import OrderedDict
+from functools import wraps
+from typing import Callable, Dict, List, Optional, Sequence, Type, Union
+
+import torch
+import torch.nn as nn
+from torch.distributed._composable_state import _State
+from torch.distributed.utils import _get_root_modules
+
+
+def generate_state_key(string="__composable_api_state_key"):
+    return f"{string}_{str(uuid.uuid4())}"
+
+
+STATE_KEY = generate_state_key()
+REGISTRY_KEY = generate_state_key()
+
+
+# TODO: we can add additional info to RegistryItem to share across APIs. E.g.,
+# we can add args and kwargs here, and then we can detect whether fully_shard
+# is combined with reentrant activation checkpointing and error out with a clear
+# message.
+class RegistryItem:
+    pass
+
+
+def contract(state_cls: Type[_State] = _State):
+    r"""
+    Decorate a function as a composable distributed API, where the first
+    argument of the function must be an :class:`nn.Module` instance or sequence
+    of :class:`nn.Module` instances.
+
+    The decorator verifies that the decorated function does not modify
+    fully-qualified names (FQNs) for parameters, buffers, or modules. The
+    decorated function can return different module instances than the input
+    modules; the FQN invariant will be enforced following the input order.
+
+    When a function ``func`` is decorated by ``@contract()``, a
+    ``.state(module: nn.Module)`` method will be installed to the decorated
+    function. Then you can retrieve and modify the state on a module by calling
+    ``func.state(module)``.
+
+    Example::
+        >>> # xdoctest: +SKIP
+        >>> import torch.nn as nn
+        >>>
+        >>> class MyModel(nn.Module):
+        >>>     def __init__(self) -> None:
+        >>>         super().__init__()
+        >>>         self.l1 = nn.Linear(10, 10)
+        >>>         self.l2 = nn.Linear(10, 10)
+        >>>
+        >>>     def forward(self, x):
+        >>>         return self.l2(self.l1(x))
+        >>>
+        >>> @contract()
+        >>> def my_feature(module: nn.Module) -> nn.Module:
+        >>>     my_feature.state(module).some_state = "any value"
+        >>>     return module
+        >>>
+        >>> model = MyModel()
+        >>> my_feature(model.l1)
+        >>> assert my_feature.state(model.l1).some_state == "any value"
+        >>> my_feature(model.l2)
+        >>> model(torch.randn(2, 10)).sum().backward()
+    """
+
+    # wraps will make functions decorated with contract() pickleable - needed for integration with torch.package
+    @wraps(state_cls)
+    def inner(func):
+        @wraps(func)
+        def wrapper(
+            module: Union[nn.Module, Sequence[nn.Module]], *args, **kwargs
+        ) -> Optional[nn.Module]:
+            inp_module = module
+            if isinstance(module, nn.Module):
+                modules = [module]
+            else:
+                # If the user passes a sequence of modules, then we assume that
+                # we only need to insert the state object on the root modules
+                # (i.e. those without a parent) among the passed-in modules.
+                modules = _get_root_modules(list(module))
+            state = state_cls()  # shared across all modules
+            registry_item = RegistryItem()  # shared across all modules
+
+            # `func` is allowed to return different module instances than the
+            # input modules as long as FQNs are preserved following the input
+            # module order
+            all_orig_named_params: List[Dict[str, nn.Parameter]] = []
+            all_orig_named_buffers: List[Dict[str, torch.Tensor]] = []
+            all_orig_named_modules: List[Dict[str, nn.Module]] = []
+
+            for module in modules:
+                default_all_state: Dict[Callable, _State] = OrderedDict()
+                default_registry: Dict[str, RegistryItem] = OrderedDict()
+                all_state: Dict[Callable, _State] = module.__dict__.setdefault(  # type: ignore[call-overload]
+                    STATE_KEY, default_all_state
+                )
+                if not isinstance(all_state, dict):
+                    raise AssertionError(
+                        f"Distributed composable API states corrupted: {all_state}"
+                    )
+                registry: Dict[str, RegistryItem] = module.__dict__.setdefault(  # type: ignore[call-overload]
+                    REGISTRY_KEY, default_registry
+                )
+                if not isinstance(registry, dict):
+                    raise AssertionError(
+                        f"Distributed composable API registry corrupted: {registry}"
+                    )
+                if func in all_state or func.__name__ in registry:
+                    raise AssertionError(
+                        "Each distinct composable distributed API can only be applied to a "
+                        f"module once. {func.__name__} has already been applied to the "
+                        f"following module:\n{module}"
+                    )
+                all_state.setdefault(func, state)
+                registry.setdefault(func.__name__, registry_item)
+
+                all_orig_named_params.append(OrderedDict(module.named_parameters()))
+                all_orig_named_buffers.append(OrderedDict(module.named_buffers()))
+                all_orig_named_modules.append(OrderedDict(module.named_modules()))
+
+            updated = func(inp_module, *args, **kwargs)
+            if updated is None:
+                updated = inp_module
+            if isinstance(updated, nn.Module):
+                updated_modules = [updated]
+            else:
+                updated_modules = _get_root_modules(list(inp_module))
+
+            all_new_named_params: List[Dict[str, nn.Parameter]] = []
+            all_new_named_buffers: List[Dict[str, torch.Tensor]] = []
+            all_new_named_modules: List[Dict[str, nn.Module]] = []
+            for module in updated_modules:
+                all_new_named_params.append(OrderedDict(module.named_parameters()))
+                all_new_named_buffers.append(OrderedDict(module.named_buffers()))
+                all_new_named_modules.append(OrderedDict(module.named_modules()))
+
+            num_orig_modules = len(all_orig_named_modules)
+            num_new_modules = len(all_new_named_modules)
+            if num_orig_modules != num_new_modules:
+                raise AssertionError(
+                    f"{func.__name__} should return the same number of modules as input modules"
+                    f"Inputs: {num_orig_modules} modules\n"
+                    f"Outputs: {num_new_modules} modules"
+                )
+
+            def check_fqn(orig_fqns: List[str], new_fqns: List[str], check_key: str):
+                if orig_fqns == new_fqns:
+                    return
+
+                orig_fqn_set, new_fqn_set = set(orig_fqns), set(new_fqns)
+                orig_only = orig_fqn_set - new_fqn_set
+                new_only = new_fqn_set - orig_fqn_set
+                if len(orig_only) or len(new_only):
+                    raise RuntimeError(
+                        f"{check_key}"
+                        "Composable distributed API implementations cannot modify FQNs.\n"
+                        f"FQNs only in original: {orig_only}\n"
+                        f"FQNs only in new: {new_only}"
+                    )
+                else:
+                    raise RuntimeError(
+                        f"{check_key}"
+                        "Composable distributed API implementations cannot modify "
+                        "the order of FQNs.\n"
+                        f"Original FQNs: {orig_only}\n"
+                        f"New FQNs: {new_only}"
+                    )
+
+            for orig_named_params, new_named_params in zip(
+                all_orig_named_params, all_new_named_params
+            ):
+                check_fqn(
+                    list(orig_named_params.keys()),
+                    list(new_named_params.keys()),
+                    "Checking parameters: ",
+                )
+            for orig_named_buffers, new_named_buffers in zip(
+                all_orig_named_buffers, all_new_named_buffers
+            ):
+                check_fqn(
+                    list(orig_named_buffers.keys()),
+                    list(new_named_buffers.keys()),
+                    "Checking buffers: ",
+                )
+            for orig_named_modules, new_named_modules in zip(
+                all_orig_named_modules, all_new_named_modules
+            ):
+                check_fqn(
+                    list(orig_named_modules.keys()),
+                    list(new_named_modules.keys()),
+                    "Checking modules: ",
+                )
+
+            # TODO: verify that installed distributed paradigms are compatible with
+            # each other.
+
+            return updated
+
+        def get_state(module: nn.Module) -> Optional[_State]:
+            return module.__dict__.setdefault(  # type: ignore[call-overload]
+                STATE_KEY,
+                {},  # TODO(@yhcharles): this is a temporary fix, need a better way
+            ).get(
+                func
+            )  # type: ignore[call-overload]
+
+        wrapper.state = get_state  # type: ignore[attr-defined]
+
+        return wrapper
+
+    return inner
+
+
+def _get_registry(module: nn.Module) -> Optional[Dict[str, RegistryItem]]:
+    r"""
+    Get an ``OrderedDict`` of composable APIs that have been applied to the
+    ``module``, indexed by the API name. If no API has been applied, then this
+    returns ``None``.
+    """
+    return getattr(module, REGISTRY_KEY, None)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..191a836632085e2f3b22d9330b84fc46f0475a09
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__init__.py
@@ -0,0 +1,2 @@
+from ._fsdp_api import CPUOffloadPolicy, MixedPrecisionPolicy, OffloadPolicy
+from .fully_shard import FSDPModule, fully_shard, register_fsdp_forward_method
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1f9eb227cd33a6152fa4bed35fdf1d22be420899
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_api.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_api.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2151fe065143a21d1d49a90d28c318c1f576bb3e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_api.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_collectives.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_collectives.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..04cfd592f50839000a602bee85857474354e62d1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_collectives.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_common.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_common.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..803837d3c98bc279c0979c2ee8b0d5f2de0cf4d1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_common.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_init.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_init.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..21616a9f5753cef8edf3401e7cd247b2992b3c8d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_init.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_param.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_param.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b118d8c5819378b67347e213d265b586c3398d13
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_param.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_param_group.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_param_group.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2a228b7dcb76bf7dc48ef2e754b964e793a0cd58
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_param_group.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_state.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_state.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b7a801aa14c82987021658c99b305398cc3fcf9e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_state.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/fully_shard.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/fully_shard.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b528ce641523f717ec2546196ed29bec6dc3e2d3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/__pycache__/fully_shard.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/_fsdp_api.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/_fsdp_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..aa6b5e803b80b3e263cb6820cc281d8cda24c546
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/_fsdp_api.py
@@ -0,0 +1,80 @@
+# mypy: allow-untyped-defs
+from dataclasses import dataclass
+from typing import Optional
+
+import torch
+
+
+@dataclass(frozen=True)
+class MixedPrecisionPolicy:
+    """
+    This configures FSDP's mixed precision. Unlike autocast, this applies mixed
+    precision at the module level, not op level, which means low-precision
+    activations are saved for backward and high-to-low-precision casts are
+    incurred only at module boundaries.
+
+    FSDP works well with module-level mixed precision since it keeps the
+    high-precision sharded parameters in memory anyway. In other words, FSDP
+    does not require any extra memory to keep a high-precision copy of the
+    parameters for the optimizer step.
+
+    Attributes:
+        param_dtype (Optional[torch.dtype]): This specifies the dtype for
+            the unsharded parameter and hence the dtype for forward/backward
+            computation and the parameter all-gather. If this is ``None``, then
+            the unsharded parameter uses the original dtype. The optimizer step
+            uses the sharded parameter in the original dtype. (Default:
+            ``None``)
+        reduce_dtype (Optional[torch.dtype]): This specifies the dtype for
+            gradient reduction (i.e. reduce-scatter or all-reduce). If this is
+            ``None`` but ``param_dtype`` is not ``None``, then the reduction
+            uses the compute dtype. This can be used to run gradient reduction
+            in full precision while using low precision for compute. If also
+            gradient reduction is disabled via :meth:`set_requires_gradient_sync`,
+            then FSDP will accumulate gradients using ``reduce_dtype``.
+            (Default: ``None``)
+        output_dtype (Optional[torch.dtype]): This specifies the dtype for
+            casting floating-point forward outputs. This can be used to
+            help implement cases where different modules have different mixed
+            precision policies. (Default: ``None``)
+        cast_forward_inputs (bool): This specifies whether FSDP should cast the
+            forward's floating-point input tensors to ``param_dtype`` or not.
+    """
+
+    param_dtype: Optional[torch.dtype] = None
+    reduce_dtype: Optional[torch.dtype] = None
+    output_dtype: Optional[torch.dtype] = None
+    cast_forward_inputs: bool = True
+
+    def __post_init__(self):
+        # Clamp `reduce_dtype` to `None` if no casting is required: since
+        # gradients are computed in `param_dtype`, if `reduce_dtype` matches,
+        # then we do not need extra casting
+        if self.param_dtype == self.reduce_dtype:
+            # Bypass the frozen dataclass checks
+            object.__setattr__(self, "reduce_dtype", None)
+
+
+@dataclass
+class OffloadPolicy:
+    """This base class represents the policy of no offloading."""
+
+
+@dataclass
+class CPUOffloadPolicy(OffloadPolicy):
+    """
+    This offload policy offloads parameters, gradients, and optimizer states to
+    CPU. Sharded parameters are copied host-to-device before all-gather. The
+    all-gathered parameters are freed according to ``reshard_after_forward``.
+    Sharded gradients are copied device-to-host in backward, and the optimizer
+    step runs on CPU with CPU optimizer states.
+
+    Attributes:
+        pin_memory (bool): Whether to pin sharded parameter and gradient
+            memory. Pinning memory allows H2D/D2H copying without blocking the
+            CPU and in turn, overlap with compute, but pinned memory cannot be
+            used by other processes. Set this to ``False`` if you have
+            insufficient CPU memory. (Default: ``True``)
+    """
+
+    pin_memory: bool = True
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/_fsdp_collectives.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/_fsdp_collectives.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e10f4594c152935eecefb1d3247aa29e6a80983
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/_fsdp_collectives.py
@@ -0,0 +1,477 @@
+# mypy: allow-untyped-decorators
+from typing import cast, List, NamedTuple, Optional, Tuple, Union
+
+import torch
+import torch._dynamo.compiled_autograd as ca
+import torch.distributed as dist
+from torch.distributed.distributed_c10d import ReduceOp
+from torch.distributed.tensor import DTensor
+
+from ._fsdp_common import (
+    _get_dim0_padded_size,
+    _raise_assert_with_print,
+    _to_dtype_if_needed,
+)
+from ._fsdp_param import FSDPParam, ShardedState
+
+
+class AllGatherResult(NamedTuple):
+    all_gather_output: torch.Tensor
+    all_gather_event: Optional[torch.cuda.Event]
+    all_gather_work: Optional[dist.distributed_c10d.Work]
+    # For each parameter, the all-gather input dtype for each input
+    param_all_gather_input_dtypes: List[List[torch.dtype]]
+    # For each parameter, the all-gather input numel for each input
+    param_all_gather_input_numels: List[List[int]]
+    # 1D flattened version of `param_all_gather_input_numels` saved to avoid
+    # CPU overhead from recomputing
+    all_gather_input_split_sizes: List[int]
+
+
+lib = torch.library.Library("fsdp", "FRAGMENT")  # noqa: TOR901
+
+lib.define(
+    """
+    all_gather_copy_in(
+        Tensor[] all_gather_inputs,
+        SymInt[] inp_split_sizes,
+        SymInt all_gather_input_numel,
+        SymInt world_size,
+        SymInt rank,
+        ScalarType dtype,
+        Device device
+    ) -> (Tensor, Tensor)
+    """
+)
+
+
+@torch.library.impl(lib, "all_gather_copy_in", "Meta")
+def all_gather_copy_in_meta(
+    all_gather_inputs: List[torch.Tensor],
+    inp_split_sizes: List[int],
+    all_gather_input_numel: int,
+    world_size: int,
+    rank: int,
+    dtype: torch.dtype,
+    device: torch.device,
+) -> Tuple[torch.Tensor, torch.Tensor]:
+    all_gather_output = torch.empty(
+        (all_gather_input_numel * world_size,), dtype=dtype, device="meta"
+    )
+    all_gather_input = all_gather_output.narrow(
+        0, all_gather_input_numel * rank, all_gather_input_numel
+    )
+    return all_gather_input, all_gather_output
+
+
+@torch.library.impl(lib, "all_gather_copy_in", "CUDA")
+@torch.library.impl(lib, "all_gather_copy_in", "CPU")
+def all_gather_copy_in_cuda(
+    all_gather_inputs: List[torch.Tensor],
+    inp_split_sizes: List[int],
+    all_gather_input_numel: int,
+    world_size: int,
+    rank: int,
+    dtype: torch.dtype,
+    device: torch.device,
+) -> Tuple[torch.Tensor, torch.Tensor]:
+    all_gather_output = torch.empty(
+        (all_gather_input_numel * world_size,), dtype=dtype, device=device
+    )
+    all_gather_input = all_gather_output.narrow(
+        0, all_gather_input_numel * rank, all_gather_input_numel
+    )
+    foreach_copy_dsts = torch.split(all_gather_input, inp_split_sizes)
+    with torch.no_grad():
+        torch._foreach_copy_(foreach_copy_dsts, all_gather_inputs)
+    return all_gather_input, all_gather_output
+
+
+lib.define(
+    "split_with_sizes_copy(Tensor all_gather_output, SymInt[] all_gather_input_split_sizes, int dim=0, *, Tensor(a!)[] out) -> ()"
+)
+
+
+@torch.library.impl(lib, "split_with_sizes_copy", "Meta")
+@torch.library.impl(lib, "split_with_sizes_copy", "CUDA")
+@torch.library.impl(lib, "split_with_sizes_copy", "CPU")
+def split_with_sizes_copy(
+    all_gather_output: torch.Tensor,
+    all_gather_input_split_sizes: List[int],
+    dim: int,
+    out: List[torch.Tensor],
+) -> None:
+    torch.split_with_sizes_copy(
+        all_gather_output, all_gather_input_split_sizes, dim=dim, out=out
+    )
+
+
+lib.define(
+    "chunk_cat(Tensor[] tensors, int dim, int num_chunks, *, Tensor(a!) out) -> ()"
+)
+
+
+@torch.library.impl(lib, "chunk_cat", "Meta")
+@torch.library.impl(lib, "chunk_cat", "CUDA")
+@torch.library.impl(lib, "chunk_cat", "CPU")
+def chunk_cat(
+    tensors: List[torch.Tensor],
+    dim: int,
+    num_chunks: int,
+    out: torch.Tensor,
+) -> None:
+    torch._chunk_cat(tensors, dim, num_chunks, out=out)
+
+
+@torch.no_grad()
+def foreach_all_gather(
+    fsdp_params: List[FSDPParam],
+    group: dist.ProcessGroup,
+    async_op: bool,
+    all_gather_copy_in_stream: torch.cuda.Stream,
+    all_gather_stream: torch.cuda.Stream,
+    device: torch.device,
+) -> Optional[AllGatherResult]:
+    world_size, rank = group.size(), group.rank()
+    with torch.cuda.stream(all_gather_copy_in_stream):
+        param_all_gather_inputs = _get_param_all_gather_inputs(fsdp_params)
+        (
+            param_all_gather_input_dtypes,
+            param_all_gather_input_numels,
+            dtype,
+        ) = _get_all_gather_input_metadatas(param_all_gather_inputs)
+        if dtype == torch.uint8:
+            all_gather_inputs = [
+                t.view(torch.uint8) for ts in param_all_gather_inputs for t in ts
+            ]
+        else:
+            all_gather_inputs = [t for ts in param_all_gather_inputs for t in ts]
+        inp_split_sizes = [t.numel() for t in all_gather_inputs]
+        all_gather_input_numel = sum(inp_split_sizes)
+        all_gather_input, all_gather_output = torch.ops.fsdp.all_gather_copy_in(
+            all_gather_inputs,
+            inp_split_sizes,
+            all_gather_input_numel,
+            world_size,
+            rank,
+            dtype,
+            device,
+        )
+        del param_all_gather_inputs
+    all_gather_stream.wait_stream(all_gather_copy_in_stream)
+    with torch.cuda.stream(all_gather_stream):
+        all_gather_work = dist.all_gather_into_tensor(
+            output_tensor=all_gather_output,
+            input_tensor=all_gather_input,
+            group=group,
+            async_op=async_op,
+        )
+        all_gather_event = all_gather_stream.record_event()
+        return AllGatherResult(
+            all_gather_output,
+            all_gather_event,
+            all_gather_work,
+            param_all_gather_input_dtypes,
+            param_all_gather_input_numels,
+            inp_split_sizes,
+        )
+
+
+@torch.no_grad()
+def _get_param_all_gather_inputs(
+    fsdp_params: List[FSDPParam],
+) -> List[List[torch.Tensor]]:
+    if ca.compiled_autograd_enabled:
+        return [fsdp_param.all_gather_inputs for fsdp_param in fsdp_params]
+
+    # Intentionally try to run a fast-path that bypasses abstractions for the
+    # common FSDP case of bf16/fp32 mixed precision in order to use foreach
+    # copy for lower CPU overhead and more efficient copying in eager
+    def use_foreach_copy(fsdp_param: FSDPParam) -> bool:
+        return (
+            fsdp_param.param_dtype is not None
+            and not fsdp_param.offload_to_cpu
+            and not hasattr(fsdp_param._sharded_local_tensor, "fsdp_pre_all_gather")
+        )
+
+    param_all_gather_inputs: List[List[torch.Tensor]] = [[] for _ in fsdp_params]
+    foreach_copy_indices: List[int] = []
+    foreach_copy_inputs: List[torch.Tensor] = []
+    foreach_copy_input_numels: List[int] = []
+
+    # 1st pass: for foreach-copy parameters, get inputs and metadata for the
+    # foreach copy, and for the others, actually get their all-gather inputs
+    for i, fsdp_param in enumerate(fsdp_params):
+        if use_foreach_copy(fsdp_param):
+            foreach_copy_indices.append(i)
+            all_gather_input = (
+                fsdp_param._sharded_param_data
+                if fsdp_param.sharded_state == ShardedState.SHARDED
+                else cast(torch.Tensor, fsdp_param._sharded_post_forward_param_data)
+            )
+            foreach_copy_inputs.append(all_gather_input)
+            foreach_copy_input_numels.append(all_gather_input.numel())
+        else:
+            param_all_gather_inputs[i] = fsdp_param.all_gather_inputs
+
+    # 2nd pass: use foreach copy to compute the remaining all-gather inputs
+    if foreach_copy_inputs:
+        fsdp_param_0 = fsdp_params[foreach_copy_indices[0]]
+        param_dtype, device = fsdp_param_0.param_dtype, fsdp_param_0.device
+        flat_foreach_copy_input = torch.empty(
+            (sum(foreach_copy_input_numels),), device=device, dtype=param_dtype
+        )
+        splits = torch.split(flat_foreach_copy_input, foreach_copy_input_numels)
+        torch._foreach_copy_(splits, foreach_copy_inputs)
+        for i, split in zip(foreach_copy_indices, splits):
+            param_all_gather_inputs[i] = [split]
+
+    return param_all_gather_inputs
+
+
+@torch.no_grad()
+def foreach_all_gather_copy_out(
+    all_gather_result: AllGatherResult,
+    fsdp_params: List[FSDPParam],
+    group: dist.ProcessGroup,
+) -> None:
+    (
+        all_gather_output,
+        all_gather_event,
+        all_gather_work,
+        param_all_gather_input_dtypes,
+        param_all_gather_input_numels,
+        all_gather_input_split_sizes,
+    ) = all_gather_result
+    if all_gather_event is not None:  # sync op
+        torch.cuda.current_stream().wait_event(all_gather_event)
+    if isinstance(all_gather_work, dist.distributed_c10d.Work):  # async op
+        all_gather_work.wait()
+    world_size, device = group.size(), all_gather_output.device
+    for all_gather_input_numels, all_gather_input_dtypes, fsdp_param in zip(
+        param_all_gather_input_numels, param_all_gather_input_dtypes, fsdp_params
+    ):
+        if ca.compiled_autograd_enabled:
+            fsdp_param.init_all_gather_outputs(
+                all_gather_input_numels,
+                all_gather_input_dtypes,
+                world_size,
+                device,
+                # NOTE: Under compile, make sure we always recreate all_gather_outputs
+                # per AllGather. See [Note: Invariants for torch.compile Traceable FSDP2].
+                force_recreate=True,
+            )
+        else:
+            fsdp_param.init_all_gather_outputs(
+                all_gather_input_numels, all_gather_input_dtypes, world_size, device
+            )  # no-op after 1st call
+            fsdp_param.alloc_all_gather_outputs()
+    all_gather_output = all_gather_output.view(world_size, -1)
+    gen = (t for fsdp_param in fsdp_params for t in fsdp_param.all_gather_outputs)
+    if all_gather_output.dtype == torch.uint8:
+        out = [t.view(world_size, -1).view(torch.uint8) for t in gen]
+    else:
+        out = [t.view(world_size, -1) for t in gen]
+    torch.ops.fsdp.split_with_sizes_copy(
+        all_gather_output, all_gather_input_split_sizes, dim=1, out=out
+    )
+
+
+@torch.no_grad()
+def foreach_reduce(
+    fsdp_params: List[FSDPParam],
+    unsharded_grads: List[torch.Tensor],
+    reduce_scatter_group: dist.ProcessGroup,
+    reduce_scatter_stream: torch.cuda.Stream,
+    orig_dtype: torch.dtype,
+    reduce_dtype: Optional[torch.dtype],
+    device: torch.device,
+    reduce_scatter_reduce_op: Optional[Union[dist.ReduceOp, dist.ReduceOp.RedOpType]],
+    all_reduce_group: Optional[dist.ProcessGroup],  # not `None` iff HSDP
+    all_reduce_stream: torch.cuda.Stream,
+    all_reduce_grads: bool,
+    partial_reduce_output: Optional[torch.Tensor],  # only used for HSDP
+) -> Tuple[torch.Tensor, torch.cuda.Event, torch.cuda.Event, Optional[torch.Tensor]]:
+    """
+    ``unsharded_grads`` owns the references to the gradients computed by
+    autograd, so clearing the list frees the gradients.
+    """
+    grad_dtypes = {grad.dtype for grad in unsharded_grads}
+    if len(grad_dtypes) != 1:
+        # Check this at runtime since it could be a real runtime error if e.g.
+        # fp8 weights do not produce the correct higher precision gradients
+        _raise_assert_with_print(
+            f"FSDP reduce-scatter expects uniform gradient dtype but got {grad_dtypes}"
+        )
+    grad_dtype = unsharded_grads[0].dtype
+    reduce_dtype = reduce_dtype or grad_dtype
+    predivide_factor, postdivide_factor = _get_gradient_divide_factors(
+        reduce_scatter_group, all_reduce_group, reduce_dtype
+    )
+    world_size = reduce_scatter_group.size()
+    padded_unsharded_sizes = tuple(
+        _get_dim0_padded_size(grad.size(), world_size) for grad in unsharded_grads
+    )
+    reduce_scatter_input_numel = sum(s.numel() for s in padded_unsharded_sizes)
+    reduce_scatter_output_numel = reduce_scatter_input_numel // world_size
+    reduce_scatter_input = torch.empty(
+        (reduce_scatter_input_numel,), dtype=reduce_dtype, device=device
+    )
+    foreach_reduce_scatter_copy_in(unsharded_grads, reduce_scatter_input, world_size)
+    current_stream = torch.cuda.current_stream()
+    # Only after the copy-in finishes can we free the gradients
+    unsharded_grads.clear()
+    reduce_scatter_stream.wait_stream(current_stream)
+    with torch.cuda.stream(reduce_scatter_stream):
+        reduce_output = reduce_scatter_input.new_empty((reduce_scatter_output_numel,))
+        _div_if_needed(reduce_scatter_input, predivide_factor)
+        if reduce_scatter_reduce_op is None:
+            if predivide_factor is None:
+                reduce_scatter_reduce_op = ReduceOp.AVG
+            else:
+                reduce_scatter_reduce_op = ReduceOp.SUM
+        dist.reduce_scatter_tensor(
+            output=reduce_output,
+            input=reduce_scatter_input,
+            group=reduce_scatter_group,
+            op=reduce_scatter_reduce_op,
+        )
+        reduce_scatter_event = reduce_scatter_stream.record_event()
+        post_reduce_stream = reduce_scatter_stream
+        if all_reduce_group is not None:  # HSDP
+            # Accumulations must run in the reduce-scatter stream
+            if not all_reduce_grads:
+                if partial_reduce_output is not None:
+                    partial_reduce_output += reduce_output
+                else:
+                    partial_reduce_output = reduce_output
+                return (
+                    reduce_scatter_input,
+                    reduce_scatter_event,
+                    post_reduce_stream.record_event(),
+                    partial_reduce_output,
+                )
+            if partial_reduce_output is not None:
+                reduce_output += partial_reduce_output
+            post_reduce_stream = all_reduce_stream
+            all_reduce_stream.wait_stream(reduce_scatter_stream)
+            with torch.cuda.stream(all_reduce_stream):
+                dist.all_reduce(
+                    reduce_output,
+                    group=all_reduce_group,
+                    op=ReduceOp.AVG if predivide_factor is None else ReduceOp.SUM,
+                )
+    with torch.cuda.stream(post_reduce_stream):
+        _div_if_needed(reduce_output, postdivide_factor)
+        reduce_output = _to_dtype_if_needed(reduce_output, orig_dtype)
+        # View out and accumulate sharded gradients
+        flat_grad_offset = 0  # [0, reduce_scatter_output_numel - 1]
+        for padded_unsharded_size, fsdp_param in zip(
+            padded_unsharded_sizes, fsdp_params
+        ):
+            new_sharded_grad = torch.as_strided(
+                reduce_output,
+                size=fsdp_param.sharded_size,
+                stride=fsdp_param.contiguous_sharded_stride,
+                storage_offset=flat_grad_offset,
+            )
+            to_accumulate_grad = fsdp_param.sharded_param.grad is not None
+            if fsdp_param.offload_to_cpu:
+                # Only overlap the D2H copy (copying to pinned memory) if not
+                # accumulating gradients since the CPU add kernel depends on
+                # the copy result and we cannot run the add as a callback
+                non_blocking = fsdp_param.pin_memory and not to_accumulate_grad
+                # Since the GPU sharded gradient is allocated in the RS stream,
+                # we can free it here by not keeping a ref without waiting for
+                # the D2H copy since future RS-stream ops run after the copy
+                new_sharded_grad = new_sharded_grad.to(
+                    torch.device("cpu"), non_blocking=non_blocking
+                )
+                if non_blocking:
+                    # Record an event on which to block the CPU thread to
+                    # ensure that the D2H copy finishes before the optimizer
+                    fsdp_param.grad_offload_event = reduce_scatter_stream.record_event()
+            if to_accumulate_grad:
+                assert isinstance(fsdp_param.sharded_param.grad, DTensor)
+                fsdp_param.sharded_param.grad._local_tensor += new_sharded_grad
+            else:
+                new_sharded_dtensor_grad = fsdp_param.to_sharded_dtensor(
+                    new_sharded_grad
+                )
+                fsdp_param.sharded_param.grad = new_sharded_dtensor_grad
+            if not ca.compiled_autograd_enabled:
+                for hook in (
+                    getattr(fsdp_param.sharded_param, "_post_accumulate_grad_hooks", {})
+                    or {}
+                ).values():
+                    hook(fsdp_param.sharded_param)
+            padded_sharded_numel = padded_unsharded_size.numel() // world_size
+            flat_grad_offset += padded_sharded_numel
+        post_reduce_event = post_reduce_stream.record_event()
+    # The RS output is allocated in the RS stream and used in the default
+    # stream (for optimizer). To ensure its memory is not reused for later
+    # RSs, we do not need extra synchronization since the sharded parameters
+    # hold refs through the end of backward.
+    return reduce_scatter_input, reduce_scatter_event, post_reduce_event, None
+
+
+def foreach_reduce_scatter_copy_in(
+    unsharded_grads: List[torch.Tensor],
+    reduce_scatter_input: torch.Tensor,
+    world_size: int,
+) -> None:
+    reduce_scatter_input = reduce_scatter_input.view(world_size, -1)
+    torch.ops.fsdp.chunk_cat(
+        unsharded_grads, dim=0, num_chunks=world_size, out=reduce_scatter_input
+    )
+
+
+def _get_all_gather_input_metadatas(
+    param_all_gather_inputs: List[List[torch.Tensor]],
+) -> Tuple[List[List[torch.dtype]], List[List[int]], torch.dtype]:
+    param_all_gather_input_dtypes: List[List[torch.dtype]] = []
+    param_all_gather_input_numels: List[List[int]] = []
+    all_gather_dtype = param_all_gather_inputs[0][0].dtype
+    for all_gather_inputs in param_all_gather_inputs:
+        input_dtypes: List[torch.dtype] = []
+        input_numels: List[int] = []
+        for all_gather_input in all_gather_inputs:
+            if all_gather_input.dtype != all_gather_dtype:
+                all_gather_dtype = torch.uint8
+            input_dtypes.append(all_gather_input.dtype)
+            input_numels.append(all_gather_input.numel())
+        param_all_gather_input_dtypes.append(input_dtypes)
+        param_all_gather_input_numels.append(input_numels)
+    return (
+        param_all_gather_input_dtypes,
+        param_all_gather_input_numels,
+        all_gather_dtype,
+    )
+
+
+def _get_gradient_divide_factors(
+    reduce_scatter_group: dist.ProcessGroup,
+    all_reduce_group: Optional[dist.ProcessGroup],
+    reduce_dtype: torch.dtype,
+) -> Union[Tuple[None, None], Tuple[float, float]]:
+    # For fp32/bf16, we do not need to worry about overflow/underflow, so we
+    # use NCCL's built-in division to avoid separate div kernels
+    if reduce_dtype in (torch.float32, torch.bfloat16):
+        return None, None
+    data_parallel_size = reduce_scatter_group.size()
+    if all_reduce_group is not None:
+        data_parallel_size *= all_reduce_group.size()
+    # Since fp16 has smaller dynamic range than fp32/bf16, we want to avoid
+    # overflow/underflow. For N data parallel workers, each worker computes
+    # g_i, and they collectively reduce (g_1 + ... + g_N) / N. To avoid
+    # overflow/underflow, we divide by ~sqrt(N) before/after the reduction.
+    factor: int = 1
+    while data_parallel_size % factor == 0 and data_parallel_size / factor > factor:
+        factor *= 2
+    factor = float(factor)
+    return (factor, data_parallel_size / factor)
+
+
+def _div_if_needed(tensor: torch.Tensor, div_factor: Optional[float]) -> None:
+    if div_factor is not None and div_factor > 1:
+        tensor.div_(div_factor)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/_fsdp_common.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/_fsdp_common.py
new file mode 100644
index 0000000000000000000000000000000000000000..31b74079aaa8be31ef27ddcccf6ead55a56ac2f2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/_fsdp_common.py
@@ -0,0 +1,152 @@
+# mypy: allow-untyped-defs
+import math
+import traceback
+from dataclasses import dataclass
+from enum import auto, Enum
+from typing import Any, cast, List, Optional
+
+import torch
+import torch._dynamo.compiled_autograd as ca
+import torch.distributed as dist
+import torch.nn as nn
+from torch.distributed._composable.contract import _get_registry
+from torch.distributed.tensor import DeviceMesh, DTensor
+from torch.distributed.tensor._dtensor_spec import DTensorSpec
+
+
+@dataclass
+class DataParallelMeshInfo:
+    mesh: DeviceMesh
+    shard_mesh_dim: Optional[int] = None
+    replicate_mesh_dim: Optional[int] = None
+
+    def __post_init__(self):
+        if self.shard_mesh_dim is None and self.replicate_mesh_dim is None:
+            raise AssertionError(
+                "At least one of shard_mesh_dim and replicate_mesh_dim must not be None"
+            )
+
+
+@dataclass
+class FSDPMeshInfo(DataParallelMeshInfo):
+    def __post_init__(self):
+        super().__post_init__()
+        if self.shard_mesh_dim is None:
+            raise AssertionError("Expects non-None shard_mesh_dim")
+        self.shard_mesh_size: int = self.mesh.size(self.shard_mesh_dim)
+        self.shard_process_group = self.mesh.get_group(self.shard_mesh_dim)
+        self.shard_mesh_rank: int = self.shard_process_group.rank()
+
+
+@dataclass
+class DDPMeshInfo(DataParallelMeshInfo):
+    def __post_init__(self):
+        super().__post_init__()
+        if self.replicate_mesh_dim is None:
+            raise AssertionError("Expects non-None replicate_mesh_dim")
+        self.replicate_mesh_size: int = self.mesh.size(self.replicate_mesh_dim)
+        self.replicate_process_group = self.mesh.get_group(self.replicate_mesh_dim)
+        self.replicate_mesh_rank: int = self.replicate_process_group.rank()
+
+
+@dataclass
+class HSDPMeshInfo(FSDPMeshInfo, DDPMeshInfo):
+    def __post_init__(self):
+        # Calls `FSDPMeshInfo` -> `DDPMeshInfo` -> `DataParallelMeshInfo`
+        super().__post_init__()
+
+
+class TrainingState(Enum):
+    """Describes the training state of one FSDP state / parameter group."""
+
+    # Transition to forward starting pre-forward until post-forward
+    FORWARD = auto()
+    # Transition to pre-backward when unsharding in backward
+    PRE_BACKWARD = auto()
+    # Transition to post-backward when resharding and reducing gradients
+    POST_BACKWARD = auto()
+    # Idle before/after forward or before pre-backward/after post-backward
+    IDLE = auto()
+
+
+def _raise_assert_with_print(*args: Any, **kwargs: Any):
+    print(f"[Rank {dist.get_rank()}] ", end="")
+    print(*args, **kwargs)
+    traceback.print_stack()
+    raise AssertionError(*args, **kwargs)
+
+
+def _is_composable_with_fsdp(module: nn.Module) -> bool:
+    registry = _get_registry(module)
+    if registry is None:
+        return True
+    # Registry keys by function name
+    return "replicate" not in registry
+
+
+def _get_dim0_padded_size(tensor_size: torch.Size, dim0_factor: int) -> torch.Size:
+    padded_dim0 = math.ceil(tensor_size[0] / dim0_factor) * dim0_factor
+    return cast(torch.Size, torch.Size([padded_dim0]) + tensor_size[1:])
+
+
+def _chunk_with_empty(
+    tensor: torch.Tensor, num_chunks: int, dim: int
+) -> List[torch.Tensor]:
+    chunks = list(torch.chunk(tensor, num_chunks, dim=dim))
+    while len(chunks) < num_chunks:
+        chunks.append(chunks[0].new_empty(0))
+    return chunks
+
+
+def _get_dim0_chunked_size(
+    chunk: torch.Tensor, unchunked_size: torch.Size
+) -> torch.Size:
+    if chunk.numel() > 0:
+        return chunk.size()
+    # For 0 numel, we need to preserve trailing dims for DTensor APIs
+    return cast(torch.Size, torch.Size([0]) + unchunked_size[1:])
+
+
+def _from_local_no_grad(
+    local_tensor: torch.Tensor,
+    sharding_spec: DTensorSpec,
+) -> DTensor:
+    """
+    This method is similar to ``DTensor.from_local()`` except that in eager mode
+    it avoids some CPU overhead by avoiding default args and not being differentiable.
+    """
+
+    if not ca.compiled_autograd_enabled:
+        return DTensor(
+            # Use the local tensor directly instead of constructing a new tensor
+            # variable, e.g. with `view_as()`, since this is not differentiable
+            local_tensor,
+            sharding_spec,
+            requires_grad=local_tensor.requires_grad,
+        )
+    else:
+        return DTensor.from_local(
+            local_tensor,
+            sharding_spec.mesh,
+            sharding_spec.placements,
+            shape=sharding_spec.shape,
+            stride=sharding_spec.stride,
+        )
+
+
+def _to_dtype_if_needed(
+    tensor: torch.Tensor, dtype: Optional[torch.dtype]
+) -> torch.Tensor:
+    if dtype is not None and tensor.dtype != dtype:
+        return tensor.to(dtype)
+    return tensor
+
+
+def _cast_fp_tensor(dtype: torch.dtype, x: torch.Tensor) -> torch.Tensor:
+    if (
+        not isinstance(x, torch.Tensor)
+        or not torch.is_floating_point(x)
+        or x.dtype == dtype
+    ):
+        return x
+    return x.to(dtype)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/_fsdp_init.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/_fsdp_init.py
new file mode 100644
index 0000000000000000000000000000000000000000..c07e323449f30c265a8606cf5f7b456a914be291
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/_fsdp_init.py
@@ -0,0 +1,168 @@
+import itertools
+from typing import List, Optional, Set, Tuple, Union
+
+import torch
+import torch.distributed as dist
+import torch.nn as nn
+from torch.distributed.device_mesh import _get_device_handle
+from torch.distributed.tensor import DeviceMesh, DTensor, init_device_mesh
+from torch.utils._python_dispatch import is_traceable_wrapper_subclass
+
+from ._fsdp_common import _is_composable_with_fsdp, FSDPMeshInfo, HSDPMeshInfo
+from ._fsdp_state import _get_module_fsdp_state
+
+
+def _get_post_forward_mesh_info(
+    reshard_after_forward: Union[bool, int], mesh_info: FSDPMeshInfo
+) -> Optional[FSDPMeshInfo]:
+    shard_mesh_size = mesh_info.shard_mesh_size
+    if not isinstance(reshard_after_forward, (bool, int)):
+        raise ValueError(
+            "reshard_after_forward should be a bool or an int representing the "
+            f"group size to reshard to, not {reshard_after_forward}"
+        )
+    # NOTE: `isinstance(False, int)` returns `True`.
+    if not isinstance(reshard_after_forward, bool) and isinstance(
+        reshard_after_forward, int
+    ):
+        if (
+            reshard_after_forward < 1
+            or reshard_after_forward > shard_mesh_size
+            or shard_mesh_size % reshard_after_forward != 0
+        ):
+            raise ValueError(
+                "If passing reshard_after_forward as an int, it should be a "
+                f"factor of {shard_mesh_size}, not {reshard_after_forward}"
+            )
+        elif reshard_after_forward == 1:
+            reshard_after_forward = False
+        elif reshard_after_forward == shard_mesh_size:
+            reshard_after_forward = True
+    post_forward_mesh_info = None
+    if reshard_after_forward is True:
+        post_forward_mesh_info = mesh_info
+    elif reshard_after_forward is not False:  # int case
+        # For HSDP, we can flatten the two replicate dims into the 0th dim
+        post_forward_mesh_tensor = mesh_info.mesh.mesh.view(-1, reshard_after_forward)
+        post_forward_mesh = DeviceMesh(
+            mesh_info.mesh.device_type, post_forward_mesh_tensor
+        )
+        post_forward_mesh_info = HSDPMeshInfo(
+            post_forward_mesh, shard_mesh_dim=1, replicate_mesh_dim=0
+        )
+    return post_forward_mesh_info
+
+
+def _init_default_fully_shard_mesh() -> DeviceMesh:
+    """Default to global CUDA mesh if possible else global CPU mesh."""
+    if not dist.distributed_c10d.is_initialized():
+        dist.distributed_c10d.init_process_group()
+    default_pg = dist.distributed_c10d._get_default_group()
+    device_type = "cuda" if torch.cuda.is_available() else "cpu"
+    mesh = init_device_mesh(device_type, mesh_shape=(default_pg.size(),))
+    return mesh
+
+
+def _get_device_from_mesh(mesh: DeviceMesh) -> torch.device:
+    if mesh.device_type == "cpu":
+        return torch.device("cpu")
+    device_handle = _get_device_handle(mesh.device_type)
+    return torch.device(mesh.device_type, device_handle.current_device())
+
+
+def _get_managed_modules(root_modules: Tuple[nn.Module, ...]) -> List[nn.Module]:
+    modules: List[nn.Module] = []
+    root_modules_set = set(root_modules)
+    # Track visisted modules to avoid visiting shared modules multiple times
+    visited_modules: Set[nn.Module] = set()
+
+    def dfs(module: nn.Module) -> None:
+        """
+        Runs a DFS to collect managed modules, not recursing into modules with
+        a non-composable API or ``fully_shard`` already applied.
+        """
+        if not _is_composable_with_fsdp(module):
+            return
+        elif (
+            module not in root_modules_set
+            and _get_module_fsdp_state(module) is not None
+        ):
+            return  # nested `fully_shard` module
+        visited_modules.add(module)
+        for submodule in module.children():
+            if submodule not in visited_modules:
+                dfs(submodule)
+        modules.append(module)
+
+    for root_module in root_modules:
+        dfs(root_module)
+    return modules
+
+
+def _verify_managed_param(name: str, param: nn.Parameter) -> None:
+    """
+    Verify if the parameter is accepted by fully_shard. The only restriction now
+    is that the parameter cannot be a scalar tensor (param.numel == 0) since we
+    need at least one dim to shard.
+    """
+    if len(param.shape) == 0:
+        raise ValueError(
+            "fully_shard doesn't support salar parameters. "
+            f"Change {name} to a 1D tensor with numel equal to 1."
+        )
+
+
+def _get_managed_states(
+    modules: List[nn.Module],
+) -> Tuple[List[nn.Parameter], List[torch.Tensor]]:
+    params: List[nn.Parameter] = []
+    buffers: List[torch.Tensor] = []
+    # Track visited parameters/buffers to avoid visiting shared parameters and
+    # buffers multiple times
+    visited_params: Set[nn.Parameter] = set()
+    visited_buffers: Set[torch.Tensor] = set()
+    for module in modules:
+        for name, param in module.named_parameters(recurse=False):
+            if param not in visited_params:
+                _verify_managed_param(name, param)
+                params.append(param)
+                visited_params.add(param)
+        for buffer in module.buffers(recurse=False):
+            if buffer not in visited_buffers:
+                buffers.append(buffer)
+                visited_buffers.add(buffer)
+    return params, buffers
+
+
+def _move_states_to_device(
+    params: List[nn.Parameter],
+    buffers: List[torch.Tensor],
+    device: torch.device,
+) -> None:
+    """
+    We have FSDP move states to device for simpler and faster initialization
+    since FSDP almost always uses CUDA for training. We move parameters/buffers
+    rather than modules since modules to support ignoring parameters/buffers in
+    the future.
+    """
+    # Follow the logic in `nn.Module._apply`
+    for tensor in itertools.chain(params, buffers):
+        if tensor.device == device or tensor.device.type == "meta":
+            # Keep meta-device tensors on meta device for deferred init
+            continue
+        if isinstance(tensor, DTensor):
+            if (dtensor_mesh_type := tensor.device_mesh.device_type) != device.type:
+                raise ValueError(
+                    "Requires DTensor to have mesh of the same type as the FSDP mesh "
+                    f"but got {dtensor_mesh_type} for DTensor and {device.type} for FSDP"
+                )
+            raise AssertionError(
+                f"Expects DTensor to be moved to {dtensor_mesh_type} but got {tensor.device}"
+            )
+        tensor_ = tensor
+        if is_traceable_wrapper_subclass(tensor_):
+            with torch.no_grad():  # avoid autograd increasing C++ refcount by 1
+                tensor_on_device = nn.Parameter(tensor.to(device))
+            torch.utils.swap_tensors(tensor, tensor_on_device)
+        else:
+            tensor.data = tensor.to(device)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/_fsdp_param.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/_fsdp_param.py
new file mode 100644
index 0000000000000000000000000000000000000000..f6fc631ec8ac46f5494c93c471d93ef5f2a58722
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/_fsdp_param.py
@@ -0,0 +1,754 @@
+# mypy: allow-untyped-defs
+import itertools
+from dataclasses import dataclass, field
+from enum import auto, Enum
+from typing import Any, cast, List, Optional, Sequence, Tuple
+
+import torch
+import torch._dynamo.compiled_autograd as ca
+import torch.nn as nn
+from torch._prims_common import make_contiguous_strides_for
+from torch.distributed._functional_collectives import AsyncCollectiveTensor
+from torch.distributed.tensor import DTensor, Replicate, Shard
+from torch.distributed.tensor._dtensor_spec import DTensorSpec, TensorMeta
+from torch.distributed.tensor.device_mesh import _mesh_resources
+from torch.distributed.tensor.placement_types import _StridedShard, Placement
+
+from ._fsdp_api import CPUOffloadPolicy, MixedPrecisionPolicy, OffloadPolicy
+from ._fsdp_common import (
+    _chunk_with_empty,
+    _from_local_no_grad,
+    _get_dim0_chunked_size,
+    _raise_assert_with_print,
+    _to_dtype_if_needed,
+    FSDPMeshInfo,
+    HSDPMeshInfo,
+)
+
+
+"""
+[Note: FSDP tensors]
+FSDP considers the following tensors:
+- Original parameter: parameter passed to :class:`FSDPParam`, i.e. the one
+  on the module when applying FSDP
+- Sharded parameter: sharding the original parameter on dim-0 as a DTensor
+  over the main mesh
+- All-gather inputs: the ``torch.Tensor`` or ``Tensor`` s passed to all-gather,
+  derived from the sharded parameter
+- All-gather output: the ``torch.Tensor`` or ``Tensor`` s resulting from
+  all-gathering the all-gather inputs
+- Unsharded parameter: parameter used for forward/backward computation, derived
+  from the all-gather output; autograd leaf
+
+We define these tensors to describe the general framework that can accomodate
+extensions, where:
+- all-gather-inputs = pre-all-gather-transform(sharded-parameter)
+- unsharded-parameter = post-all-gather-transform(all-gather-outputs)
+
+For the default ``torch.Tensor`` case, there is only one all-gather input, and
+it shares the same underlying tensor data as the sharded parameter, meaning
+that they can be thought of as the same tensors. The same applies for the
+all-gather output and unsharded parameter. For non-``torch.Tensor`` extensions,
+these equivalences may no longer hold due to the pre/post-all-gather
+transforms, and some may have multiple all-gather inputs/outputs (e.g.
+quantized data and scales).
+
+[Note: FSDP and autograd]
+FSDP dynamically frees and allocates the unsharded parameter. Since autograd
+can pack a reference to it or a view to save for backward, we use storage
+resizing to implement the freeing/allocation since that preserves the aliasing.
+This implies that we construct the unsharded parameter object once and write to
+it in-place thereafter. For the default ``torch.Tensor` original parameter
+case, the all-gather output and unsharded parameter share the same
+data, so we use storage resizing on the all-gather output.
+"""
+
+lib = torch.library.Library("fsdp", "FRAGMENT")  # noqa: TOR901
+
+lib.define("set_(Tensor(a!) tensor, Tensor data) -> ()")
+
+
+@torch.library.impl(lib, "set_", "Meta")
+@torch.library.impl(lib, "set_", "CUDA")
+@torch.library.impl(lib, "set_", "CPU")
+def set_(tensor, data):
+    tensor.set_(data)
+
+
+"""
+[Note: Avoiding functionalization for fsdp.set_ and inductor.resize_storage_bytes_(0)]
+
+Currently we don't functionalize `fsdp.set_` op or `inductor.resize_storage_bytes_(0)` op
+(i.e. they show up as a mutation op in the middle of the AOT joint graph).
+
+Reason:
+Traceable FSDP2 compiled autograd BWD graph have the following traits:
+(1) Two inputs of the graph were aliased to each other (one from hook closed-over tensors, one from FWD saved tensors).
+(2) One of them is mutated (set_ and resize_(0) to handle the all-gathered param).
+(3) They are both subclasses.
+The combination of these traits is not supported by AOTAutograd (it's difficult to reason about subclass aliasing).
+So this doesn't work at all for Traceable FSDP2.
+
+The compromise we use is to avoid functionalization for the FSDP2 set_ and resize_(0) ops.
+This avoids the problem above, because from AOTAutograd point-of-view there are no mutations
+that functionalization needs to handle. (Although we need to be careful not to DCE those mutable ops.)
+
+We can avoid this functionalization because:
+(1) The nn.Parameter is never used before its .set_() is called in eager code (i.e. no alias of it is created),
+so it's safe to call .set_() in the middle of the graph to swap out its storage and start using the nn.Parameter downstream.
+(2) We always re-allocate the buffer for nn.Parameter to store the AllGather output and to be used in downstream user ops.
+So calling resize-to-0 in the middle of the graph to free nn.Parameter memory after use should always be okay
+(since we always allocate anew next time we need it, we strictly don't need to keep the old tensor storage around anymore).
+
+Q: But doesn't the torch.compile stack have the "functional graph" assumption in many places?
+A: Yes - this is WIP but we will try to get back to functional graph as early as possible in the lowering process.
+Specifically, we believe we can move both .set_ and .resize_(0) ops to end of graph in AOT joint graph before partitioner
+(i.e. effectively "re-functionalizing" those ops). Put it in another way, we avoid functionalization for those two ops just to
+make AOTAutograd alias analysis happy, and as soon as we are past that point, we "re-functionalize" the graph.
+This requires a custom FX pass but we believe it's not hard to write and maintain.
+
+Q: What's the importance of partitioner not saving views of nn.Parameter as FWD saved tensors?
+A: This is critical: we do want to save FWD nn.Parameter graph input (instead of its view) for BWD use,
+so that downstream ops in BWD graph uses the post-`.set_` nn.Parameter instead of any of its saved views as input.
+This is because .set_ will not update any of the nn.Parameter's views, so BWD downstream ops must use the original
+nn.Parameter in order to see the result of .set_.
+"""
+
+
+@torch.library.impl(lib, "set_", "Functionalize")
+def set__functionalize(tensor, data):
+    torch._sync(tensor)
+    torch._sync(data)
+    # AOTDispatcher needs to know if any inputs had their storages mutated.
+    # (Why? It sometimes detaches inputs before sending them into the graph,
+    #  when it sees that they do not need to have any gradients computed)
+    torch._functionalize_set_storage_changed(tensor)
+    tensor_inner = torch._from_functional_tensor(tensor)
+    data_inner = torch._from_functional_tensor(data)
+    with torch._C._ExcludeDispatchKeyGuard(
+        torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize)
+    ):
+        torch.ops.fsdp.set_.default(tensor_inner, data_inner)
+
+
+torch.fx.node.has_side_effect(torch.ops.fsdp.set_.default)
+
+
+class ShardedState(Enum):
+    """
+    - ``SHARDED``: The sharded parameter is registered to the module. It is the
+      only contributor to parameter memory.
+    - ``SHARDED_POST_FORWARD``: The unsharded parameter is resharded to a
+      smaller world size. Since this data should not be used for computation,
+      we do not register it to the module. Users should reshard the module
+      before any in-place modifications. Both it and the sharded parameter
+      contribute to parameter memory.
+    - ``UNSHARDED``: The unsharded parameter is registered to the module. Both
+      it and the sharded parameter contribute to parameter memory.
+    """
+
+    SHARDED = auto()
+    SHARDED_POST_FORWARD = auto()
+    UNSHARDED = auto()
+
+
+@dataclass
+class ParamModuleInfo:
+    """
+    For a parameter, this stores the module and the parameter name to be able
+    to do a parameter swap via ``setattr(module, param_name, ...)`` or to get
+    the parameter via ``getattr(module, param_name)``. We additionally save
+    shared modules and shared parameter names to update them accordingly.
+    """
+
+    # Parameter names are unprefixed, e.g. "weight", not "lin.weight"
+    module: nn.Module
+    param_name: str
+    shared_modules: List[nn.Module] = field(default_factory=list)
+    shared_param_names: List[str] = field(default_factory=list)
+
+
+@dataclass
+class ExtensionsData:
+    # User-defined metadata passed from pre to post-all-gather
+    all_gather_metadata: Optional[Any] = None
+    # Save the all-gather input sizes to unflatten the all-gather outputs to ND
+    all_gather_input_sizes: Sequence[torch.Size] = ()  # ND
+
+    def clear(self):
+        self.all_gather_metadata = None
+        self.all_gather_input_sizes = ()
+
+
+class FSDPParam:
+    """
+    This class manages a parameter with FSDP or FSDP variants applied,
+    implementing dim-0 per-parameter sharding.
+    """
+
+    orig_dtype: torch.dtype
+    param_dtype: Optional[torch.dtype]
+    reduce_dtype: Optional[torch.dtype]
+    _orig_size: torch.Size  # ND
+    sharded_size: torch.Size  # ND
+    contiguous_sharded_stride: Tuple[int, ...]
+    padded_sharded_param_size: torch.Size  # ND
+    sharded_post_forward_size: torch.Size  # ND
+    contiguous_sharded_post_forward_stride: Tuple[int, ...]
+    _sharded_param_data: torch.Tensor  # 1D
+    sharded_param: nn.Parameter  # ND
+    _sharded_post_forward_param_data: Optional[torch.Tensor]  # 1D
+    _sharded_post_forward_param: Optional[nn.Parameter]  # ND
+    _unsharded_param: nn.Parameter  # ND
+    unsharded_accumulated_grad: Optional[torch.Tensor]  # ND
+    _sharding_spec: DTensorSpec
+    # DTensor attributes (only defined for DTensor `param`):
+    _tp_spec: DTensorSpec
+    all_gather_outputs: List[torch.Tensor]  # 1D
+    # All-gather extension attributes
+    _extensions_data: ExtensionsData
+    _unsharded_inner_tensors: List[torch.Tensor]
+
+    def __init__(
+        self,
+        param: nn.Parameter,
+        module_info: ParamModuleInfo,
+        mesh_info: FSDPMeshInfo,
+        post_forward_mesh_info: Optional[FSDPMeshInfo],
+        device: torch.device,
+        mp_policy: MixedPrecisionPolicy,
+        offload_policy: OffloadPolicy,
+    ):
+        self._module_info: ParamModuleInfo = module_info
+        self.mesh_info = mesh_info
+        self.post_forward_mesh_info = post_forward_mesh_info
+        self.device = device
+        self.offload_to_cpu: bool = isinstance(offload_policy, CPUOffloadPolicy)
+        self.pin_memory = (
+            self.offload_to_cpu and cast(CPUOffloadPolicy, offload_policy).pin_memory
+        )
+        self.grad_offload_event: Optional[torch.cuda.Event] = None
+        self._init_sharded_param(param, device)
+        if self.post_forward_mesh_info:
+            self._init_sharded_post_forward_param_metadata(param)
+        self._init_extensions()
+        self.all_gather_outputs: List[torch.Tensor] = []
+        self.unsharded_accumulated_grad = None
+        self._param_fqn: Optional[str] = None  # prefixed from root module
+        # TODO: Remove this padding logic once DTensor pads the local tensor:
+        # https://github.com/pytorch/pytorch/issues/113045
+        self._post_load_hook_handle = (
+            module_info.module.register_load_state_dict_post_hook(
+                lambda *args, **kwargs: self.reset_sharded_param()
+            )
+        )
+
+    @torch.no_grad()
+    def _init_sharded_param(self, param: nn.Parameter, device: torch.device):
+        if param.device != device and param.device.type != "meta":
+            raise AssertionError(
+                f"Expects the parameter to already be moved to device {device} but got {param.device}"
+            )
+        # TODO: Replace the sharded DTensor parameter construction logic with
+        # `distribute_tensor` after https://github.com/pytorch/pytorch/issues/116101
+        # TODO: Simplify the following sharded parameter padding logic after
+        # https://github.com/pytorch/pytorch/issues/113045
+        self.is_dtensor = isinstance(param, DTensor)
+        if self.is_dtensor:
+            self._tp_spec = cast(DTensor, param)._spec
+            dp_mesh, tp_mesh = (self.mesh_info.mesh, self._tp_spec.mesh)
+            dp_global_mesh = _mesh_resources.get_root_mesh(dp_mesh)
+            tp_global_mesh = _mesh_resources.get_root_mesh(tp_mesh)
+            if dp_global_mesh != tp_global_mesh or (
+                dp_global_mesh is None or tp_global_mesh is None
+            ):
+                raise AssertionError(
+                    "FSDP requires the DP and TP mesh to have the same parent mesh but got: \n"
+                    f"DP's global mesh: {dp_global_mesh}\nTP's global mesh: {tp_global_mesh}"
+                )
+
+            name_dims_error = "FSDP requires named DeviceMesh dims for ND parallelism"
+            assert dp_mesh.mesh_dim_names is not None, name_dims_error
+            assert tp_mesh.mesh_dim_names is not None, name_dims_error
+            submesh_names = dp_mesh.mesh_dim_names + tp_mesh.mesh_dim_names
+            self._spmd_mesh = dp_global_mesh[submesh_names]
+            if len(self._tp_spec.placements) != 1:
+                raise NotImplementedError(
+                    f"FSDP only supports 1D TP, not {self._tp_spec.placements}"
+                )
+            split_factor = self._tp_spec.num_shards_map[0]
+            assert (
+                2 <= self._spmd_mesh.ndim <= 3
+            ), f"_spmd_mesh.ndim can only be 2 or 3 but got {self._spmd_mesh.ndim}."
+            self._spmd_placements: Tuple[Placement, ...]
+            dp_shard_tp_placement = (
+                (
+                    _StridedShard(0, split_factor=split_factor)
+                    if split_factor > 1
+                    else Shard(0)
+                ),
+                self._tp_spec.placements[0],
+            )
+            if self._spmd_mesh.ndim == 2:
+                self._spmd_placements = dp_shard_tp_placement
+            else:
+                assert self.mesh_info.replicate_mesh_dim == 0
+                self._spmd_placements = (Replicate(),) + dp_shard_tp_placement
+            self._sharding_spec = DTensorSpec(
+                self._spmd_mesh,
+                self._spmd_placements,
+                tensor_meta=self._tp_spec.tensor_meta,
+            )
+            # NOTE: FSDP+TP does not support uneven sharding for now
+            # TODO: enable uneven sharding for FSDP+TP
+            if split_factor > 1:  # FSDP has strided sharding on tensor dim 0
+                num_shards = self._sharding_spec.num_shards_map[0]
+                tensor_size_dim_0 = self._sharding_spec.shape[0]
+                if tensor_size_dim_0 % num_shards != 0:
+                    raise NotImplementedError(
+                        "FSDP+TP sharding does not support uneven sharding for now: "
+                        f"tensor dim 0 has size {tensor_size_dim_0} which cannot be "
+                        f"evenly sharded into {num_shards} shards."
+                    )
+
+            param_data = cast(DTensor, param)._local_tensor
+        else:
+            self._spmd_mesh = self.mesh_info.mesh
+            if isinstance(self.mesh_info, HSDPMeshInfo):
+                self._spmd_placements = (Replicate(), Shard(0))
+            else:
+                self._spmd_placements = (Shard(0),)
+            self._sharding_spec = DTensorSpec(
+                self._spmd_mesh,
+                self._spmd_placements,
+                tensor_meta=TensorMeta(
+                    param.size(),
+                    param.stride(),
+                    param.dtype,
+                ),
+            )
+            param_data = param
+        self._orig_size = param_data.size()
+        self._contiguous_orig_stride = make_contiguous_strides_for(self._orig_size)
+        shard_rank = self.mesh_info.shard_mesh_rank
+        shard_world_size = self.mesh_info.shard_mesh_size
+        chunks = _chunk_with_empty(param_data, shard_world_size, dim=0)
+        sharded_param = chunks[shard_rank]
+        self.sharded_size = _get_dim0_chunked_size(sharded_param, param_data.size())
+        self.contiguous_sharded_stride = make_contiguous_strides_for(self.sharded_size)
+        padded_sharded_size = chunks[0].size()  # 0th always padded
+        padded_sharded_param = param_data.new_zeros(padded_sharded_size)
+        self.padded_sharded_param_size = padded_sharded_param.size()
+        if sharded_param.numel() > 0:
+            padded_sharded_param[: sharded_param.size(0)].copy_(sharded_param)
+        if self.offload_to_cpu and not padded_sharded_param.is_meta:
+            padded_sharded_param = padded_sharded_param.cpu()
+            if self.pin_memory:
+                padded_sharded_param = padded_sharded_param.pin_memory()
+        self._sharded_param_data = padded_sharded_param.view(-1)
+        self.sharded_param = nn.Parameter(
+            self.to_sharded_dtensor(padded_sharded_param[: sharded_param.size(0)])
+        )
+        self.sharded_param.requires_grad_(param.requires_grad)
+        # Let `param_data` be freed normally when its ref count reaches 0 when
+        # the `fully_shard` call returns to allow provided parameters to alias
+        self._setattr_on_modules(self.sharded_param)
+        self.sharded_state = ShardedState.SHARDED
+
+    def _init_sharded_post_forward_param_metadata(self, param: torch.Tensor) -> None:
+        mesh_info = self.post_forward_mesh_info
+        assert mesh_info is not None  # mypy
+        param_data = param._local_tensor if isinstance(param, DTensor) else param
+        chunks = _chunk_with_empty(param_data, mesh_info.shard_mesh_size, dim=0)
+        self.sharded_post_forward_size = _get_dim0_chunked_size(
+            chunks[mesh_info.shard_mesh_rank], param_data.size()
+        )
+        self.contiguous_sharded_post_forward_stride = make_contiguous_strides_for(
+            self.sharded_post_forward_size
+        )
+
+    def init_dtype_attrs(self, mp_policy: MixedPrecisionPolicy):
+        param_dtype, reduce_dtype = (mp_policy.param_dtype, mp_policy.reduce_dtype)
+        self.orig_dtype = self.sharded_param.dtype
+        # Clamp `param_dtype` to `None` if no casting is required
+        if param_dtype == self.orig_dtype:
+            param_dtype = None
+        self.param_dtype = param_dtype
+        self.reduce_dtype = reduce_dtype
+        # None indicates that the mixed precision is not enabled
+
+    def _init_extensions(self) -> None:
+        inner_tensor = self._sharded_local_tensor
+        has_fsdp_pre_all_gather = hasattr(inner_tensor, "fsdp_pre_all_gather")
+        has_fsdp_post_all_gather = hasattr(inner_tensor, "fsdp_post_all_gather")
+        if has_fsdp_pre_all_gather != has_fsdp_post_all_gather:
+            raise AssertionError(
+                "Both fsdp_pre_all_gather and fsdp_post_all_gather should be defined "
+                f"if using all-gather extensions: {inner_tensor}"
+            )
+        if has_fsdp_pre_all_gather:
+            if self.padded_sharded_param_size != self._sharded_local_tensor.size():
+                raise NotImplementedError(
+                    "FSDP all-gather extensions require even sharding on dim-0.\n"
+                    f"{self._orig_size} is not divisible by FSDP world size {self.mesh_info.mesh.size()}."
+                )
+            self._extensions_data = ExtensionsData()
+        self._unsharded_inner_tensors: List[torch.Tensor] = []
+
+    def init_all_gather_outputs(
+        self,
+        all_gather_input_numels: List[int],
+        all_gather_input_dtypes: List[torch.dtype],
+        world_size: int,
+        device: torch.device,
+        force_recreate: bool = False,
+    ):
+        if not force_recreate and len(self.all_gather_outputs) > 0:
+            return  # already initialized
+        self.all_gather_outputs = [
+            torch.empty(torch.Size([numel * world_size]), dtype=dtype, device=device)
+            for numel, dtype in zip(all_gather_input_numels, all_gather_input_dtypes)
+        ]
+
+    def init_unsharded_param(self):
+        """
+        [Note: Invariants for torch.compile Traceable FSDP2]
+        1. Under compile, we always re-populate the content of `self._unsharded_param`
+           per AllGather using the slow path.
+        2. Under compile, we always recreate `self.all_gather_outputs` per AllGather.
+           This is to ensure the buffer creation is internal to the graph and
+           avoid `self.all_gather_outputs` being captured as a graph input.
+        3. Under compile, at the end of `free_unsharded_param()`, we always clean up
+           `self.all_gather_outputs` and `self._unsharded_inner_tensors`,
+           to avoid them being captured as graph output.
+
+        With these invariants, only these tensors will be inputs to the graph:
+        - Sharded parameters
+        - Placeholders for the `self._unsharded_param` nn.Parameter
+        """
+        if not ca.compiled_autograd_enabled and hasattr(
+            self, "_unsharded_param"
+        ):  # after the 1st all-gather
+            inner_tensor = self._sharded_local_tensor
+            if not hasattr(inner_tensor, "fsdp_post_all_gather"):
+                return  # already initialized
+            for tensor in self._unsharded_inner_tensors:
+                alloc_storage(tensor)
+            all_gather_outputs = self._unflatten_all_gather_outputs()
+            inner_tensor.fsdp_post_all_gather(
+                all_gather_outputs,
+                self._extensions_data.all_gather_metadata,
+                self.param_dtype or self.orig_dtype,
+                out=self._unsharded_param,
+            )
+            self._extensions_data.clear()
+            return
+        inner_tensor = self._sharded_local_tensor
+        if not ca.compiled_autograd_enabled and hasattr(
+            inner_tensor, "fsdp_post_all_gather"
+        ):
+            all_gather_outputs = self._unflatten_all_gather_outputs()
+            (
+                unsharded_tensor,
+                self._unsharded_inner_tensors,
+            ) = inner_tensor.fsdp_post_all_gather(
+                all_gather_outputs,
+                self._extensions_data.all_gather_metadata,
+                self.param_dtype or self.orig_dtype,
+            )
+            self._extensions_data.clear()
+        else:
+            # For the default path (no post-all-gather), the all-gather output
+            # gives the unsharded parameter data directly
+            assert len(self.all_gather_outputs) == 1, f"{len(self.all_gather_outputs)}"
+            unsharded_tensor = self.all_gather_outputs[0]
+        unsharded_param = torch.as_strided(
+            unsharded_tensor,
+            self._orig_size,
+            self._contiguous_orig_stride,
+            storage_offset=0,
+        )
+        if self.is_dtensor:
+            unsharded_param = _from_local_no_grad(unsharded_param, self._tp_spec)
+        if hasattr(self, "_unsharded_param"):
+            assert ca.compiled_autograd_enabled
+            with torch.no_grad(), torch.autograd._unsafe_preserve_version_counter(
+                self._unsharded_param
+            ):
+                torch.ops.fsdp.set_.default(self._unsharded_param, unsharded_param)
+        else:
+            self._unsharded_param = nn.Parameter(
+                unsharded_param, requires_grad=self.sharded_param.requires_grad
+            )
+
+    def _unflatten_all_gather_outputs(self) -> Tuple[torch.Tensor, ...]:
+        return tuple(
+            t.view(-1, *s[1:])
+            for t, s in zip(
+                self.all_gather_outputs, self._extensions_data.all_gather_input_sizes
+            )
+        )
+
+    def to_sharded(self) -> None:
+        self._setattr_on_modules(self.sharded_param)
+        self.free_unsharded_param()
+        self.sharded_state = ShardedState.SHARDED
+
+    def to_sharded_post_forward(self) -> None:
+        if self.is_dtensor:
+            raise NotImplementedError(
+                "Resharding to smaller mesh with TP is not supported yet"
+            )
+        self._assert_in_states(ShardedState.UNSHARDED)
+        assert self.post_forward_mesh_info is not None  # mypy
+        assert len(self.all_gather_outputs) == 1
+        shard_world_size = self.post_forward_mesh_info.shard_mesh_size
+        if (numel := self.all_gather_outputs[0].numel()) % shard_world_size != 0:
+            _raise_assert_with_print(
+                f"All-gather output size ({numel}) must be divisible by the shard "
+                f"world size ({shard_world_size})"
+            )
+        shard_rank = self.post_forward_mesh_info.shard_mesh_rank
+        sharded_numel = numel // shard_world_size
+        self._sharded_post_forward_param_data = (
+            self.all_gather_outputs[0].narrow(
+                0, sharded_numel * shard_rank, sharded_numel
+            )
+        ).clone()  # clone to be able to free all-gather output
+        sharded_post_forward_tensor = torch.as_strided(
+            self._sharded_post_forward_param_data,
+            size=self.sharded_post_forward_size,
+            stride=self.contiguous_sharded_post_forward_stride,
+            storage_offset=0,
+        )
+        self._sharded_post_forward_param = nn.Parameter(
+            self.to_sharded_post_forward_dtensor(sharded_post_forward_tensor)
+        )
+        self._setattr_on_modules(self._sharded_post_forward_param)
+        self.free_unsharded_param()
+        self.sharded_state = ShardedState.SHARDED_POST_FORWARD
+
+    def to_unsharded(self) -> None:
+        # Assume that the data has been allocated and all-gathered
+        set_requires_grad_if_needed(self.sharded_param, self._unsharded_param)
+        self._setattr_on_modules(self._unsharded_param)
+        if self.sharded_state == ShardedState.SHARDED_POST_FORWARD:
+            # The data is allocated in the default stream via the post-forward
+            # reshard and must be kept alive for the next all-gather copy-in.
+            # Since we call this method after the copy-out, the data's lifetime
+            # is ensured without further synchronization.
+            self._sharded_post_forward_param = None
+            self._sharded_post_forward_param_data = None  # free
+        self.sharded_state = ShardedState.UNSHARDED
+
+    def _setattr_on_modules(self, param: nn.Parameter) -> None:
+        unsafe_setattr_param(
+            self._module_info.module, self._module_info.param_name, param
+        )
+        for shared_module, shared_param_name in zip(
+            self._module_info.shared_modules, self._module_info.shared_param_names
+        ):
+            unsafe_setattr_param(shared_module, shared_param_name, param)
+
+    def to_sharded_dtensor(self, tensor: torch.Tensor) -> DTensor:
+        """
+        Converts a local tensor representing either the sharded parameter or
+        sharded gradient to DTensor.
+        """
+        if tensor.shape != self.sharded_size:
+            _raise_assert_with_print(
+                f"Expects size {self.sharded_size} but got {tensor.shape}"
+            )
+        return _from_local_no_grad(
+            tensor,
+            self._sharding_spec,
+        )
+
+    def to_sharded_post_forward_dtensor(self, tensor: torch.Tensor) -> DTensor:
+        if tensor.shape != self.sharded_post_forward_size:
+            _raise_assert_with_print(
+                f"Expects size {self.sharded_post_forward_size} but got {tensor.shape}"
+            )
+        assert isinstance(self.post_forward_mesh_info, HSDPMeshInfo)
+        # TODO: Prefer this DTensor to be read-only and generalize the
+        # placement once we support TP.
+        post_forward_sharding_spec = DTensorSpec(
+            self.post_forward_mesh_info.mesh,
+            (Replicate(), Shard(0)),
+            tensor_meta=self._sharding_spec.tensor_meta,
+        )
+        return _from_local_no_grad(tensor, post_forward_sharding_spec)
+
+    def to_accumulated_grad_if_needed(self) -> None:
+        # Access `_unsharded_param` to bypass the sharded state check since we
+        # prefer to reshard before upcasting the gradient to save memory
+        if (
+            self.reduce_dtype is None
+            or self._unsharded_param.grad is None
+            or self._unsharded_param.grad.dtype == self.reduce_dtype
+        ):
+            return
+        unsharded_grad = self._unsharded_param.grad
+        self._unsharded_param.grad = None
+        self.unsharded_accumulated_grad = unsharded_grad.to(self.reduce_dtype)
+
+    def accumulate_unsharded_grad_if_needed(self) -> None:
+        if (
+            self.unsharded_accumulated_grad is not None
+            and self.unsharded_param.grad is not None
+        ):
+            self.unsharded_accumulated_grad += self.unsharded_param.grad
+            self.unsharded_param.grad = None
+
+    def alloc_all_gather_outputs(self) -> None:
+        for tensor in self.all_gather_outputs:
+            alloc_storage(tensor)
+
+    def free_unsharded_param(self) -> None:
+        for tensor in itertools.chain(
+            self.all_gather_outputs, self._unsharded_inner_tensors
+        ):
+            free_storage(tensor)
+        if ca.compiled_autograd_enabled:
+            self.all_gather_outputs = []
+            self._unsharded_inner_tensors = []
+
+    @property
+    def all_gather_inputs(self) -> List[torch.Tensor]:  # 1D
+        self._assert_in_states(ShardedState.SHARDED, ShardedState.SHARDED_POST_FORWARD)
+        if self.sharded_state == ShardedState.SHARDED:
+            if not ca.compiled_autograd_enabled and hasattr(
+                self._sharded_local_tensor, "fsdp_pre_all_gather"
+            ):
+                sharded_local_tensor = self._sharded_local_tensor
+                if self.offload_to_cpu:
+                    sharded_local_tensor = sharded_local_tensor.to(
+                        self.device, non_blocking=True
+                    )
+                (
+                    all_gather_inputs,
+                    self._extensions_data.all_gather_metadata,
+                ) = sharded_local_tensor.fsdp_pre_all_gather(self.mesh_info.mesh)
+                self._extensions_data.all_gather_input_sizes = [
+                    t.size() for t in all_gather_inputs
+                ]
+                return [t.view(-1) for t in all_gather_inputs]
+            sharded_param_data = self._sharded_param_data
+            if self.offload_to_cpu:
+                sharded_param_data = sharded_param_data.to(
+                    self.device, non_blocking=True
+                )
+            return [_to_dtype_if_needed(sharded_param_data, self.param_dtype)]
+        elif self.sharded_state == ShardedState.SHARDED_POST_FORWARD:
+            if not ca.compiled_autograd_enabled and hasattr(
+                self._sharded_local_tensor, "fsdp_pre_all_gather"
+            ):
+                raise NotImplementedError
+            all_gather_input = _to_dtype_if_needed(
+                cast(torch.Tensor, self._sharded_post_forward_param_data),
+                self.param_dtype,
+            )
+            return [all_gather_input]
+        return [torch.empty(0)]  # mypy
+
+    @property
+    def unsharded_param(self) -> nn.Parameter:  # ND
+        self._assert_in_states(ShardedState.UNSHARDED)
+        return self._unsharded_param
+
+    @property
+    def unsharded_grad_data(self) -> torch.Tensor:
+        grad = self.unsharded_param.grad
+        assert grad is not None, "Expects unsharded_param.grad to not be None"
+        return self._get_grad_inner_tensor(grad)
+
+    @property
+    def unsharded_accumulated_grad_data(self) -> torch.Tensor:
+        grad = self.unsharded_accumulated_grad
+        assert grad is not None, "Expects unsharded_accumulated_grad to not be None"
+        return self._get_grad_inner_tensor(grad)
+
+    def _get_grad_inner_tensor(self, grad: torch.Tensor) -> torch.Tensor:
+        if self.is_dtensor:
+            if isinstance(grad, AsyncCollectiveTensor):
+                grad = grad.wait()
+            assert isinstance(grad, DTensor), f"{type(grad)}"
+            if any(pl.is_partial() for pl in grad.placements):
+                placements = [
+                    Replicate() if pl.is_partial() else pl for pl in grad.placements
+                ]
+                grad = grad.redistribute(placements=placements)
+            grad = grad._local_tensor
+        return grad
+
+    @property
+    def _sharded_local_tensor(self) -> torch.Tensor:
+        return cast(DTensor, self.sharded_param)._local_tensor
+
+    def _assert_in_states(self, *states: ShardedState) -> None:
+        if self.sharded_state not in states:
+            _raise_assert_with_print(
+                f"Expects to be in one of {states}, not {self.sharded_state}"
+            )
+
+    def reset_sharded_param(self):
+        # For ops like `nn.Module._apply` or `load_state_dict(assign=True)`
+        # that change the sharded parameter tensor, we may need to re-pad the
+        # sharded local tensor and re-save the reference.
+        module_info = self._module_info
+        new_param = getattr(module_info.module, module_info.param_name)
+        if new_param is not self.sharded_param:
+            if torch.__future__.get_swap_module_params_on_conversion():
+                raise AssertionError(
+                    f"Expects swap_tensors to preserve object but got {new_param} "
+                    f"instead of {self.sharded_param}"
+                )
+            self.sharded_param = new_param
+        local_tensor = new_param._local_tensor
+        if local_tensor.is_meta:
+            return
+        padded_sharded_size = self.padded_sharded_param_size
+        if local_tensor.size() != padded_sharded_size:
+            padded_local_tensor = local_tensor.new_zeros(padded_sharded_size)
+            padded_local_tensor[: local_tensor.size(0)].copy_(local_tensor)
+            local_tensor = padded_local_tensor
+        if self.pin_memory and not local_tensor.is_pinned():
+            local_tensor = local_tensor.cpu().pin_memory()
+        self._sharded_param_data = local_tensor.view(-1)
+        assert isinstance(self.sharded_param, DTensor)  # mypy
+        self.sharded_param._local_tensor = local_tensor[: self.sharded_size[0]]
+
+    def __repr__(self):
+        return f"FSDPParam(fqn={self._param_fqn}, orig_size={self._orig_size})"
+
+
+def alloc_storage(tensor: torch.Tensor) -> None:
+    size = tensor.numel() * tensor.itemsize
+    if (storage := tensor.untyped_storage()).size() != size:
+        storage.resize_(size)
+
+
+def free_storage(tensor: torch.Tensor) -> None:
+    if (storage := tensor.untyped_storage()).size() != 0:
+        storage.resize_(0)
+
+
+# NOTE: These bypass `nn.Module.__setattr__` checks, which incur non-trivial
+# CPU overhead, if the module did not override it. For FSDP, we know we do not
+# need those checks when transitioning between sharded/unsharded parameters.
+def unsafe_setattr_param(
+    module: nn.Module, param_name: str, param: nn.Parameter
+) -> None:
+    if getattr(module.__setattr__, "__func__", None) is nn.Module.__setattr__:
+        module._parameters[param_name] = param
+    else:  # slow path
+        setattr(module, param_name, param)
+
+
+def set_requires_grad_if_needed(
+    src_tensor: torch.Tensor, dst_tensor: torch.Tensor
+) -> None:
+    # Only call `requires_grad_` if needed to avoid the Python <> C++ context
+    # switch overhead
+    if src_tensor.requires_grad != dst_tensor.requires_grad:
+        dst_tensor.requires_grad_(src_tensor.requires_grad)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/_fsdp_param_group.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/_fsdp_param_group.py
new file mode 100644
index 0000000000000000000000000000000000000000..3cb4a31c28d2f3acd7f19babe88274c5e4811e25
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/_fsdp_param_group.py
@@ -0,0 +1,614 @@
+# mypy: allow-untyped-defs
+import contextlib
+import logging
+from typing import Any, cast, Dict, List, NamedTuple, Optional, Set, Tuple
+
+import torch
+import torch._dynamo.compiled_autograd as ca
+import torch.distributed as dist
+import torch.nn as nn
+from torch.distributed.fsdp._common_utils import _named_parameters_with_duplicates
+from torch.profiler import record_function
+from torch.utils._pytree import tree_flatten, tree_unflatten
+from torch.utils.hooks import RemovableHandle
+
+from ._fsdp_api import MixedPrecisionPolicy, OffloadPolicy
+from ._fsdp_collectives import (
+    AllGatherResult,
+    foreach_all_gather,
+    foreach_all_gather_copy_out,
+    foreach_reduce,
+)
+from ._fsdp_common import FSDPMeshInfo, HSDPMeshInfo, TrainingState
+from ._fsdp_param import FSDPParam, ParamModuleInfo, ShardedState
+
+
+logger = logging.getLogger("torch.distributed._composable.fsdp")
+
+_ModuleToHandleDict = Dict[nn.Module, RemovableHandle]  # for state dict
+
+
+"""
+[Note: Overlapping all-gather copy-in and all-gather]
+For implicit forward prefetching, we want to overlap the next copy-in with the
+current all-gather. We do so using a separate copy-in stream. However, since
+we have the all-gather input as a view into the output, we must make sure to
+copy into different memory from the current all-gather's output. Thus, we keep
+a reference to the current all-gather's output and have the next FSDP parameter
+group free it after its copy-in. Finally, we have the last FSDP state flush the
+reference to avoid holding onto memory after forward.
+"""
+
+
+class FSDPCommContext:
+    """This has the communication state shared across FSDP states/parameter groups."""
+
+    def lazy_init(self):
+        if not torch.cuda.is_available():
+            raise RuntimeError("FSDP requires CUDA for streams")
+        # Setting the all-gather/reduce-scatter streams to be higher priority
+        # can help avoid some issues where their copies in/out are delayed and
+        # block computation (this is different from high-pri NCCL streams)
+        high_priority = -1
+        # All-gather state and copy-in stream allow overlapping the next
+        # copy-in with the current all-gather in forward; copy-in overlaps with
+        # reduce-scatter in backward without the separate copy-in stream
+        self.all_gather_copy_in_stream = torch.cuda.Stream(priority=high_priority)
+        # All-gather stream allows overlapping next all-gather with current
+        # forward compute
+        self.all_gather_stream = torch.cuda.Stream(priority=high_priority)
+        # Reduce-scatter stream gives separate execution "thread" for post-
+        # backward logic like pre/post-gradient division and reduce-scatter
+        self.reduce_scatter_stream = torch.cuda.Stream(priority=high_priority)
+        # Run the HSDP all-reduces concurrently with all-gather/reduce-scatter
+        # since collectives use different network resources and can overlap
+        # in the typical intra-node sharding / inter-node replication case
+        self.all_reduce_stream = torch.cuda.Stream()
+        # All-gather/reduce-scatter states keep references to collective
+        # tensors produced in one stream and used in another and accompanying
+        # CUDA events for synchronization
+        self.all_gather_state: Optional[AllGatherState] = None
+        self.reduce_scatter_state: Optional[ReduceScatterState] = None
+        # Post-forward order for explicit backward prefetching
+        self.post_forward_order: List[FSDPParamGroup] = []  # will cause ref cycles
+
+    def get_all_gather_streams(
+        self, training_state: TrainingState
+    ) -> Tuple[torch.cuda.Stream, torch.cuda.Stream]:
+        if training_state in (TrainingState.FORWARD, TrainingState.PRE_BACKWARD):
+            # Use separate streams for implicit prefetching
+            return self.all_gather_copy_in_stream, self.all_gather_stream
+        current_stream = torch.cuda.current_stream()
+        return current_stream, current_stream
+
+
+# See [Note: Overlapping all-gather copy-in and all-gather]
+class AllGatherState(NamedTuple):
+    all_gather_result: AllGatherResult
+    event: torch.cuda.Event  # all-gather copy-out
+
+
+class ReduceScatterState(NamedTuple):
+    reduce_scatter_input: torch.Tensor
+    event: torch.cuda.Event  # reduce-scatter event
+
+
+class FSDPParamGroup:
+    """This class represents a parameter group to communicate together."""
+
+    _orig_dtype: torch.dtype
+    _reduce_dtype: Optional[torch.dtype]
+
+    def __init__(
+        self,
+        params: List[nn.Parameter],
+        modules: Tuple[nn.Module, ...],
+        mesh_info: FSDPMeshInfo,
+        post_forward_mesh_info: Optional[FSDPMeshInfo],
+        device: torch.device,
+        mp_policy: MixedPrecisionPolicy,
+        offload_policy: OffloadPolicy,
+    ):
+        self.modules = modules  # permit ref cycle because 1:1 lifetime
+        param_module_infos = _get_param_module_infos(params, modules)
+        self.fsdp_params = [
+            FSDPParam(
+                param,
+                module_info,
+                mesh_info,
+                post_forward_mesh_info,
+                device,
+                mp_policy,
+                offload_policy,
+            )
+            for param, module_info in zip(params, param_module_infos)
+        ]
+        self.mesh_info = mesh_info
+        self.post_forward_mesh_info = post_forward_mesh_info
+        self.device = device
+        self.mp_policy = mp_policy
+        self._training_state = TrainingState.IDLE
+        # Group's sharded state always matches its parameters' sharded states
+        self._sharded_state = ShardedState.SHARDED
+        self._module_fqn: Optional[str] = None  # prefixed from root module
+        # Only consider resetting sharded parameters once in lazy init since it
+        # can incur nontrivial overhead to reset them
+        self._reset_sharded_params: bool = False
+
+        # - Hook state
+        self._module_to_pre_save_state_dict_hook_handle: _ModuleToHandleDict = {}
+        self._module_to_pre_load_state_dict_hook_handle: _ModuleToHandleDict = {}
+
+        # - Communication and communication/computation overlap
+        self.comm_ctx = FSDPCommContext()
+        # Group's indices in the shared post-forward order
+        self._post_forward_indices: List[int] = []
+        # Whether to reduce gradients at all (whether for FSDP or HSDP)
+        self.reduce_grads: bool = True
+        # Whether to all-reduce gradients for HSDP; only used if
+        # `self.reduce_grads` is true, in which case setting this to false
+        # means reduce-scatter but no all-reduce
+        self.all_reduce_grads: bool = True
+        # Whether to reshard parameters after backward (only useful for
+        # gradient accumulation)
+        self.reshard_after_backward: bool = True
+        # Optional custom reduce-scatter reduce op (e.g. to divide by a
+        # factor other than the shard world size)
+        self.reduce_scatter_reduce_op: Optional[dist.ReduceOp] = None
+
+        # - CUDA events for stream synchronization
+        # Holds the all-gather output buffer, sync objects, and metadata
+        self._all_gather_result: Optional[AllGatherResult] = None
+        # Holds the reduce-scatter/all-reduce view-out CUDA event that marks the end of
+        # the group's post-backward (e.g. reduce-scatter, all-reduce and div), which
+        # should be waited on at the end of backward
+        self._post_reduce_event: Optional[torch.cuda.Event] = None
+        # Holds the reshard-after-forward CUDA event when resharding to a
+        # different world size, which should be waited on in the next unshard
+        self._reshard_after_forward_event: Optional[torch.cuda.Event] = None
+
+        # Only for HSDP, if accumulating gradients without all-reduce, save the
+        # partial reduce output (only reduce-scattered but not all-reduced)
+        self._partial_reduce_output: Optional[torch.Tensor] = None
+
+    # Initialization #
+    def _init_mp_dtypes(self) -> None:
+        for fsdp_param in self.fsdp_params:
+            fsdp_param.init_dtype_attrs(self.mp_policy)
+        orig_dtypes = {fsdp_param.orig_dtype for fsdp_param in self.fsdp_params}
+        if len(orig_dtypes) != 1:
+            # This can be relaxed if we copy-out for the reduce-scatter
+            raise AssertionError(
+                f"FSDP expects uniform original parameter dtype but got {orig_dtypes}"
+            )
+        self._orig_dtype = next(iter(orig_dtypes))
+        reduce_dtypes = {fsdp_param.reduce_dtype for fsdp_param in self.fsdp_params}
+        if len(reduce_dtypes) != 1:
+            # This can be relaxed if we issue one reduce-scatter per reduce
+            # dtype (but we would need a way for users to specify multiple
+            # reduce dtypes)
+            raise AssertionError(
+                f"FSDP expects uniform reduce dtype but got {reduce_dtypes}"
+            )
+        self._reduce_dtype = next(iter(reduce_dtypes))
+
+    def lazy_init(self):
+        # Lazy init should be idempotent
+        # Users may change or register parameters after construction time.
+        # For example, DoRA (https://arxiv.org/abs/2402.09353) initializes linear magnitudes based on
+        # other parameters (e.g. loaded from the state dict).
+        if self.is_sharded and not self._reset_sharded_params:
+            for fsdp_param in self.fsdp_params:
+                fsdp_param.reset_sharded_param()
+            self._reset_sharded_params = True
+        param_names_on_meta = [
+            fsdp_param._param_fqn
+            for fsdp_param in self.fsdp_params
+            if fsdp_param.sharded_param.device.type == "meta"
+        ]
+        if param_names_on_meta:
+            raise RuntimeError(
+                "FSDP parameters should be materialized from meta device before training, "
+                f"but the following were still on meta device: {param_names_on_meta}\n"
+                "For example, call module.to_empty(device) to materialize to device and "
+                "call module.reset_parameters() on each module to initialize values."
+            )
+        # Initialize mixed precision attributes lazily in case the user changes
+        # the parameter dtypes after construction time but before forward
+        self._init_mp_dtypes()
+        self._register_state_dict_hooks()
+
+    # Runtime #
+    def unshard(self, async_op: bool = False):
+        if self._all_gather_result is not None:  # already called, pending wait
+            return
+        if self.is_unsharded:
+            return  # no-op
+        if self._reshard_after_forward_event is not None:
+            # Resharded parameter data is allocated in the default stream and
+            # used in the all-gather streams
+            self._wait_all_gather_streams_on_event(self._reshard_after_forward_event)
+            self._reshard_after_forward_event = None
+        with record_function(self._with_fqn("FSDP::all_gather")):
+            self._all_gather_result = foreach_all_gather(
+                self.fsdp_params,
+                self._all_gather_process_group,
+                async_op,
+                *self.comm_ctx.get_all_gather_streams(self._training_state),
+                self.device,
+            )
+
+    def wait_for_unshard(self):
+        """
+        1. In forward with implict prefetching, to overlap the current copy-out
+        with the next all-gather, we save a reference to the current all-gather
+        result to free after the next copy-out.
+        2. Otherwise (explicit prefetching or in backward), we free the
+        all-gather result immediately after the current copy-out since we can
+        already overlap the current copy-out with the previous reduce-scatter.
+        """
+        if not self._all_gather_result:
+            return  # no preceding unshard
+        if self._training_state == TrainingState.FORWARD:  # implicit prefetch
+            if prev_all_gather_state := self.comm_ctx.all_gather_state:
+                self._wait_all_gather_streams_on_event(prev_all_gather_state.event)
+                self.comm_ctx.all_gather_state = None  # free the all-gather result
+        with record_function(self._with_fqn("FSDP::all_gather_copy_out")):
+            foreach_all_gather_copy_out(
+                self._all_gather_result,
+                self.fsdp_params,
+                self._all_gather_process_group,
+            )
+        for fsdp_param in self.fsdp_params:
+            fsdp_param.init_unsharded_param()
+        self._to_unsharded()
+        all_gather_copy_out_event = torch.cuda.Event()
+        all_gather_copy_out_event.record()
+        if self._training_state == TrainingState.FORWARD:
+            self.comm_ctx.all_gather_state = AllGatherState(
+                self._all_gather_result, all_gather_copy_out_event
+            )
+        else:
+            self._wait_all_gather_streams_on_event(all_gather_copy_out_event)
+        self._all_gather_result = None  # free unless saved in `all_gather_state`
+
+    def _wait_all_gather_streams_on_event(self, event: torch.cuda.Event):
+        # Calling `unshard` before lazy init means streams are not initialized
+        if hasattr(self.comm_ctx, "all_gather_copy_in_stream"):
+            self.comm_ctx.all_gather_copy_in_stream.wait_event(event)
+        if hasattr(self.comm_ctx, "all_gather_stream"):
+            self.comm_ctx.all_gather_stream.wait_event(event)
+
+    def reshard(self):
+        if self._training_state == TrainingState.FORWARD:
+            if not self._reshard_after_forward:
+                return
+            if self._use_post_forward_mesh:
+                self._to_sharded_post_forward()
+                self._reshard_after_forward_event = torch.cuda.Event()
+                self._reshard_after_forward_event.record()
+                return
+        self._to_sharded()
+
+    def pre_forward(
+        self, module: nn.Module, args: Tuple[Any, ...], kwargs: Dict[str, Any]
+    ) -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
+        if not ca.compiled_autograd_enabled:
+            logger.debug("%s", self._with_fqn("FSDP::pre_forward"))
+        with record_function(self._with_fqn("FSDP::pre_forward")):
+            self._training_state = TrainingState.FORWARD
+            self.unshard()
+            self.wait_for_unshard()
+            args, kwargs = self._register_post_backward_hook(args, kwargs)
+            return args, kwargs
+
+    def post_forward(self, module: nn.Module, input: Any, output: Any):
+        if not ca.compiled_autograd_enabled:
+            logger.debug("%s", self._with_fqn("FSDP::post_forward"))
+        with record_function(self._with_fqn("FSDP::post_forward")):
+            self.reshard()
+            self._record_post_forward()
+            self._training_state = TrainingState.IDLE
+            return output
+
+    def _record_post_forward(self) -> None:
+        # Since a group has one pre-backward unshard for each forward call
+        # before the backward, we record each usage (with multiplicity)
+        post_forward_index = len(self.comm_ctx.post_forward_order)
+        self.comm_ctx.post_forward_order.append(self)
+        self._post_forward_indices.append(post_forward_index)
+
+    def pre_backward(self, default_prefetch: bool, *unused: Any):
+        if self._training_state == TrainingState.PRE_BACKWARD:
+            return
+        if not ca.compiled_autograd_enabled:
+            logger.debug("%s", self._with_fqn("FSDP::pre_backward"))
+        with record_function(self._with_fqn("FSDP::pre_backward")):
+            self._training_state = TrainingState.PRE_BACKWARD
+            self.unshard()  # no-op if prefetched
+            self.wait_for_unshard()
+            if default_prefetch and not ca.compiled_autograd_enabled:
+                self._backward_prefetch()
+
+    def post_backward(self, *unused: Any):
+        if not ca.compiled_autograd_enabled:
+            logger.debug("%s", self._with_fqn("FSDP::post_backward"))
+        self._training_state = TrainingState.POST_BACKWARD
+        with record_function(self._with_fqn("FSDP::post_backward_accumulate")):
+            for fsdp_param in self.fsdp_params:
+                fsdp_param.accumulate_unsharded_grad_if_needed()
+        with record_function(self._with_fqn("FSDP::post_backward_reshard")):
+            if not self.reduce_grads:
+                if self.reshard_after_backward:
+                    self.reshard()
+                for fsdp_param in self.fsdp_params:
+                    fsdp_param.to_accumulated_grad_if_needed()
+                return
+            # Save the autograd-computed gradients before resharding to only
+            # access the unsharded parameters when their data is present
+            fsdp_params_with_grad: List[FSDPParam] = []
+            unsharded_grads: List[torch.Tensor] = []
+            for fsdp_param in self.fsdp_params:
+                # May have an accumulated gradient of the reduce dtype if the
+                # previous backward did not reduce-scatter
+                if fsdp_param.unsharded_accumulated_grad is not None:
+                    fsdp_params_with_grad.append(fsdp_param)
+                    unsharded_grads.append(fsdp_param.unsharded_accumulated_grad_data)
+                    fsdp_param.unsharded_accumulated_grad = None
+                elif fsdp_param.unsharded_param.grad is not None:
+                    fsdp_params_with_grad.append(fsdp_param)
+                    unsharded_grads.append(fsdp_param.unsharded_grad_data)
+                    fsdp_param.unsharded_param.grad = None
+            if self.reshard_after_backward:
+                self.reshard()
+        if len(fsdp_params_with_grad) == 0:
+            return
+        with record_function(self._with_fqn("FSDP::post_backward_reduce")):
+            if self.comm_ctx.reduce_scatter_state is not None:
+                torch.cuda.current_stream().wait_event(
+                    self.comm_ctx.reduce_scatter_state.event
+                )
+                self.comm_ctx.reduce_scatter_state = None
+            (
+                reduce_scatter_input,
+                reduce_scatter_event,
+                self._post_reduce_event,
+                self._partial_reduce_output,
+            ) = foreach_reduce(
+                fsdp_params_with_grad,
+                unsharded_grads,
+                self._reduce_scatter_process_group,
+                self.comm_ctx.reduce_scatter_stream,
+                self._orig_dtype,
+                self._reduce_dtype,
+                self.device,
+                self.reduce_scatter_reduce_op,
+                self._all_reduce_process_group if self._is_hsdp else None,
+                self.comm_ctx.all_reduce_stream,
+                self.all_reduce_grads,
+                self._partial_reduce_output,
+            )
+            self.comm_ctx.reduce_scatter_state = ReduceScatterState(
+                reduce_scatter_input, reduce_scatter_event
+            )
+
+    def finalize_backward(self):
+        if self._post_reduce_event is not None:
+            torch.cuda.current_stream().wait_event(self._post_reduce_event)
+            self._post_reduce_event = None
+        for fsdp_param in self.fsdp_params:
+            if fsdp_param.grad_offload_event is not None:
+                fsdp_param.grad_offload_event.synchronize()
+                fsdp_param.grad_offload_event = None
+        self._post_forward_indices.clear()
+
+    def _backward_prefetch(self) -> None:
+        if self._training_state == TrainingState.PRE_BACKWARD:
+            if not self._post_forward_indices:
+                # Can be cleared if running multiple `backward`s
+                return
+            curr_index = self._post_forward_indices.pop()
+            if (target_index := curr_index - 1) < 0:
+                return
+            # Prefetch naively using the reverse post-forward order, which may
+            # have mistargeted prefetches if not all modules used in forward
+            # are used in this backward
+            target_fsdp_param_group = self.comm_ctx.post_forward_order[target_index]
+            self._prefetch_unshard(target_fsdp_param_group, "backward")
+
+    @staticmethod
+    def _prefetch_unshard(
+        target_fsdp_param_group: "FSDPParamGroup", pass_type: str
+    ) -> None:
+        if pass_type == "backward":
+            training_state = TrainingState.PRE_BACKWARD
+        elif pass_type == "forward":
+            training_state = TrainingState.FORWARD
+        else:
+            raise ValueError(f"Unknown pass type: {pass_type}")
+        target_fqn = target_fsdp_param_group._module_fqn
+        with record_function(
+            f"FSDP::{pass_type}_prefetch for {target_fqn}"
+        ), target_fsdp_param_group.use_training_state(training_state):
+            target_fsdp_param_group.unshard()
+
+    # Utilities #
+    def _to_sharded(self):
+        if not self.is_sharded:
+            for fsdp_param in self.fsdp_params:
+                fsdp_param.to_sharded()
+            self._sharded_state = ShardedState.SHARDED
+
+    def _to_sharded_post_forward(self):
+        if not self.is_sharded_post_forward:
+            for fsdp_param in self.fsdp_params:
+                fsdp_param.to_sharded_post_forward()
+            self._sharded_state = ShardedState.SHARDED_POST_FORWARD
+
+    def _to_unsharded(self):
+        if not self.is_unsharded:
+            for fsdp_param in self.fsdp_params:
+                fsdp_param.to_unsharded()
+            self._sharded_state = ShardedState.UNSHARDED
+
+    @property
+    def is_sharded(self) -> bool:
+        return self._sharded_state == ShardedState.SHARDED
+
+    @property
+    def is_sharded_post_forward(self) -> bool:
+        return self._sharded_state == ShardedState.SHARDED_POST_FORWARD
+
+    @property
+    def is_unsharded(self) -> bool:
+        return self._sharded_state == ShardedState.UNSHARDED
+
+    @contextlib.contextmanager
+    def use_training_state(self, training_state: TrainingState):
+        old_training_state = self._training_state
+        self._training_state = training_state
+        try:
+            yield
+        finally:
+            self._training_state = old_training_state
+
+    # Hook Registration #
+    def _register_post_backward_hook(
+        self, args: Tuple[Any, ...], kwargs: Dict[str, Any]
+    ) -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
+        # Compile relies on `root_post_backward_callback` to call each
+        # `FSDPParamGroup.post_backward`
+        if ca.compiled_autograd_enabled:
+            return args, kwargs
+        if not torch.is_grad_enabled():
+            return args, kwargs
+        args_list, args_spec = tree_flatten(args)
+        kwargs_list, kwargs_spec = tree_flatten(kwargs)
+        args_kwargs_list = list(args_list) + list(kwargs_list)
+        inp_tensor_indices: List[int] = []
+        inp_tensors: List[torch.Tensor] = []
+        for i, obj in enumerate(args_kwargs_list):
+            if torch.is_tensor(obj) and obj.requires_grad:
+                inp_tensor_indices.append(i)
+                inp_tensors.append(obj)
+        if len(inp_tensors) == 0:
+            return args, kwargs  # no tensors that require gradients
+        inp_tensors = RegisterPostBackwardFunction.apply(self, *inp_tensors)
+        for inp_tensor_idx, inp_tensor in zip(inp_tensor_indices, inp_tensors):
+            args_kwargs_list[inp_tensor_idx] = inp_tensor
+        args_list = args_kwargs_list[: len(args_list)]
+        kwargs_list = args_kwargs_list[len(args_list) :]
+        args = tree_unflatten(args_list, args_spec)
+        kwargs = tree_unflatten(kwargs_list, kwargs_spec)
+        return args, kwargs
+
+    def _register_state_dict_hooks(self) -> None:
+        num_pre_save_hooks = len(self._module_to_pre_save_state_dict_hook_handle)
+        num_pre_load_hooks = len(self._module_to_pre_load_state_dict_hook_handle)
+        assert (
+            num_pre_save_hooks == num_pre_load_hooks
+        ), f"Pre-save: {num_pre_save_hooks} pre-load: {num_pre_load_hooks}"
+        if num_pre_save_hooks > 0:
+            return  # already registered
+        modules_with_fsdp_params: Set[nn.Module] = {
+            fsdp_param._module_info.module for fsdp_param in self.fsdp_params
+        }
+
+        def to_sharded_hook(*args: Any, **kwargs: Any) -> None:
+            self._to_sharded()
+
+        for module in modules_with_fsdp_params:
+            self._module_to_pre_save_state_dict_hook_handle[
+                module
+            ] = module.register_state_dict_pre_hook(to_sharded_hook)
+            self._module_to_pre_load_state_dict_hook_handle[
+                module
+            ] = module._register_load_state_dict_pre_hook(to_sharded_hook)
+
+    # Properties #
+    @property
+    def _reshard_after_forward(self) -> bool:
+        return self.post_forward_mesh_info is not None
+
+    @property
+    def _use_post_forward_mesh(self) -> bool:
+        return (
+            self._reshard_after_forward
+            and self.mesh_info != self.post_forward_mesh_info
+        )
+
+    @property
+    def _is_hsdp(self) -> bool:
+        return isinstance(self.mesh_info, HSDPMeshInfo)
+
+    @property
+    def _all_gather_process_group(self) -> dist.ProcessGroup:
+        mesh_info = (
+            cast(FSDPMeshInfo, self.post_forward_mesh_info)
+            if self.is_sharded_post_forward
+            else self.mesh_info
+        )
+        assert isinstance(mesh_info, FSDPMeshInfo)
+        return mesh_info.shard_process_group
+
+    @property
+    def _reduce_scatter_process_group(self) -> dist.ProcessGroup:
+        assert isinstance(self.mesh_info, FSDPMeshInfo)
+        return self.mesh_info.shard_process_group
+
+    @property
+    def _all_reduce_process_group(self) -> dist.ProcessGroup:
+        assert isinstance(self.mesh_info, HSDPMeshInfo)
+        return self.mesh_info.replicate_process_group
+
+    def _with_fqn(self, label: str) -> str:
+        if self._module_fqn:
+            return f"{label} ({self._module_fqn})"
+        return label
+
+    def __repr__(self):
+        return f"FSDPParamGroup(fqn={self._module_fqn})"
+
+
+def _get_param_module_infos(
+    params: List[nn.Parameter], modules: Tuple[nn.Module, ...]
+) -> List[ParamModuleInfo]:
+    """
+    Shared parameter: lin1.weight = lin2.weight
+    Shared module: mlp.lin1 = mlp.lin2
+    We do not remove duplicates when traversing both modules and parameters to
+    find shared modules' parameters and shared parameters within a module.
+    """
+    params_set = set(params)
+    param_to_module_info: Dict[nn.Parameter, ParamModuleInfo] = {}
+    for module in modules:
+        for _, submodule in module.named_modules(remove_duplicate=False):
+            for param_name, param in _named_parameters_with_duplicates(
+                submodule, recurse=False
+            ):
+                if param in params_set:
+                    if param not in param_to_module_info:
+                        param_to_module_info[param] = ParamModuleInfo(
+                            submodule, param_name
+                        )
+                    else:
+                        param_to_module_info[param].shared_modules.append(submodule)
+                        param_to_module_info[param].shared_param_names.append(
+                            param_name
+                        )
+    if len(param_to_module_info) != len(params):
+        raise AssertionError(f"Some parameters are not in the module tree of {module}")
+    return [param_to_module_info[param] for param in params]
+
+
+class RegisterPostBackwardFunction(torch.autograd.Function):
+    @staticmethod
+    def forward(ctx, param_group: FSDPParamGroup, *inputs: torch.Tensor):
+        # All tensors in `inputs` should require gradient
+        ctx.param_group = param_group
+        return inputs
+
+    @staticmethod
+    def backward(ctx, *grads: torch.Tensor):
+        ctx.param_group.post_backward()
+        return (None,) + grads
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/_fsdp_state.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/_fsdp_state.py
new file mode 100644
index 0000000000000000000000000000000000000000..ceb480fd23939f27510614d05486e8eef537fcfa
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/_fsdp_state.py
@@ -0,0 +1,383 @@
+# mypy: allow-untyped-decorators
+# mypy: allow-untyped-defs
+import functools
+import logging
+from typing import (
+    Any,
+    Callable,
+    Dict,
+    List,
+    Optional,
+    Sequence,
+    Set,
+    Tuple,
+    TYPE_CHECKING,
+)
+
+import torch
+import torch._dynamo.compiled_autograd as ca
+import torch.nn as nn
+from torch._logging import warning_once
+from torch.autograd import Variable
+from torch.autograd.graph import _MultiHandle
+from torch.distributed._composable_state import (
+    _get_module_state,
+    _insert_module_state,
+    _State,
+)
+from torch.distributed.utils import _to_kwargs
+from torch.utils._pytree import tree_flatten, tree_map
+
+from ._fsdp_api import MixedPrecisionPolicy
+from ._fsdp_common import _cast_fp_tensor, TrainingState
+from ._fsdp_param_group import FSDPCommContext, FSDPParamGroup
+
+
+if TYPE_CHECKING:
+    from ._fsdp_param import FSDPParam
+
+
+logger = logging.getLogger("torch.distributed._composable.fsdp")
+
+
+class FSDPStateContext:
+    """This has state shared across FSDP states."""
+
+    def __init__(self) -> None:
+        # All FSDP states in the root state's module tree
+        self.all_states: List[FSDPState] = []
+        # Iteration's forward root runs the once-per-forward logic; this root
+        # may not be the overall root set by lazy initialization in cases where
+        # only a submodule runs forward (e.g. encoder-only for eval)
+        self.iter_forward_root: Optional[FSDPState] = None
+        # Final callback should only be queued once per backward
+        self.post_backward_final_callback_queued: bool = False
+        # Whether to finalize backward in this backward's final callback
+        self.is_last_backward: bool = True
+        # Optional user-provided event recorded after optimizer for the
+        # all-gather streams to wait on in the root pre-forward
+        self.post_optim_event: Optional[torch.cuda.Event] = None
+
+
+def disable_if_config_true(func):
+    @functools.wraps(func)
+    def fsdp_hook_wrapper(*args, **kwargs):
+        if torch._dynamo.config.skip_fsdp_hooks:
+            return torch._dynamo.disable(func, recursive=True)(*args, **kwargs)
+        else:
+            return func(*args, **kwargs)
+
+    return fsdp_hook_wrapper
+
+
+class FSDPState(_State):
+    def __init__(self) -> None:
+        super().__init__()
+        self._fsdp_param_group: Optional[FSDPParamGroup] = None
+        self._is_root: Optional[bool] = None  # root set during lazy init
+        self._state_ctx = FSDPStateContext()
+        self._comm_ctx = FSDPCommContext()
+        self._training_state: TrainingState = TrainingState.IDLE
+        self._states_to_forward_prefetch: List[FSDPState] = []
+        self._states_to_backward_prefetch: List[FSDPState] = []
+        self._modules_to_run_forward: Set[nn.Module] = set()
+
+    # Define a separate init since `__init__` is called in the contract
+    def init(
+        self,
+        modules: Tuple[nn.Module, ...],
+        device: torch.device,
+        mp_policy: MixedPrecisionPolicy,
+    ) -> None:
+        for module in modules:
+            _insert_module_state(module, self)
+        self._modules = modules
+        self._device = device
+        self._mp_policy = mp_policy
+        if len(modules) == 1:
+            self._pre_forward_hook_handle = modules[0].register_forward_pre_hook(
+                self._pre_forward, prepend=True, with_kwargs=True
+            )
+            self._post_forward_hook_handle = modules[0].register_forward_hook(
+                self._post_forward, prepend=False
+            )
+        else:
+            hook_handle = _register_group_forward_hooks(
+                modules,
+                self._pre_forward,
+                self._post_forward,
+                self._modules_to_run_forward,
+            )
+            self._pre_forward_hook_handle = hook_handle
+            self._post_forward_hook_handle = hook_handle
+
+    def _root_pre_forward(
+        self, module: nn.Module, args: Tuple[Any, ...], kwargs: Dict[str, Any]
+    ) -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
+        self._lazy_init()
+        if self._state_ctx.iter_forward_root is not None:
+            return args, kwargs
+        if not ca.compiled_autograd_enabled:
+            logger.debug("FSDP::root_pre_forward")
+        self._state_ctx.iter_forward_root = self
+        with torch.profiler.record_function("FSDP::root_pre_forward"):
+            # Wait for optimizer before implicitly prefetched all-gathers
+            if (event := self._state_ctx.post_optim_event) is not None:
+                self._comm_ctx.all_gather_copy_in_stream.wait_event(event)
+                self._comm_ctx.all_gather_stream.wait_event(event)
+                self._state_ctx.post_optim_event = None
+            else:
+                current_stream = torch.cuda.current_stream()
+                self._comm_ctx.all_gather_copy_in_stream.wait_stream(current_stream)
+                self._comm_ctx.all_gather_stream.wait_stream(current_stream)
+            if self._device.type == "cuda":
+                with torch.profiler.record_function("FSDP::inputs_to_device"):
+                    args_tuple, kwargs_tuple = _to_kwargs(
+                        args, kwargs, self._device, False
+                    )  # same as DDP
+                args, kwargs = args_tuple[0], kwargs_tuple[0]
+        return args, kwargs
+
+    def _lazy_init(self) -> None:
+        """
+        Lazy initialization represents when all modules' parallelisms have
+        finalized (e.g. FSDP has been applied to all desired modules). This
+        means that we can determine which state is the root, and we do so by
+        the 1st state to run forward.
+        """
+        if self._is_root is not None:
+            return  # no-op: already initialized
+        self._is_root = True
+        if len(self._modules) > 1:
+            raise RuntimeError(
+                f"FSDP requires a single root module but got {self._modules}"
+            )
+        root_module = self._modules[0]
+        visited_states: Set[FSDPState] = set()
+        for module_name, module in root_module.named_modules():
+            if (state := _get_module_fsdp_state(module)) is None:
+                continue
+            if module is not root_module:
+                if state not in visited_states and state._is_root is not None:
+                    raise RuntimeError(
+                        "FSDP state has already been lazily initialized for "
+                        f"{module_name}\nFSDP requires running forward through "
+                        "the root module first"
+                    )
+                state._is_root = False
+            self._state_ctx.all_states.append(state)
+            visited_states.add(state)
+        if self._fsdp_param_group:
+            # For the root, do not reshard after forward since for training,
+            # the parameters would be freed and all-gathered immediately
+            self._fsdp_param_group.post_forward_mesh_info = None
+        self._init_fqns()
+        self._init_shared_state()
+        # Run parameter group lazy inits after initializing FQNs for improved
+        # error messages
+        for state in self._state_ctx.all_states:
+            if state._fsdp_param_group:
+                state._fsdp_param_group.lazy_init()
+
+    def _init_shared_state(self) -> None:
+        self._comm_ctx.lazy_init()
+        for state in self._state_ctx.all_states:
+            state._state_ctx = self._state_ctx
+            state._comm_ctx = self._comm_ctx
+            if fsdp_param_group := state._fsdp_param_group:
+                fsdp_param_group.comm_ctx = self._comm_ctx
+
+    def _init_fqns(self) -> None:
+        """Sets module and parameter FQN attributes for debugging."""
+        assert self._is_root
+        root_module = self._modules[0]
+        param_to_fsdp_param: Dict[nn.Parameter, FSDPParam] = {}
+        module_to_fsdp_param_group: Dict[nn.Module, FSDPParamGroup] = {}
+        for state in self._state_ctx.all_states:
+            if fsdp_param_group := state._fsdp_param_group:
+                for fsdp_param in fsdp_param_group.fsdp_params:
+                    param_to_fsdp_param[fsdp_param.sharded_param] = fsdp_param
+                for module in fsdp_param_group.modules:
+                    module_to_fsdp_param_group[module] = fsdp_param_group
+        for param_name, param in root_module.named_parameters():
+            if param in param_to_fsdp_param:
+                param_to_fsdp_param[param]._param_fqn = param_name
+        for module_name, module in root_module.named_modules():
+            if module in module_to_fsdp_param_group:
+                module_fqn = module_to_fsdp_param_group[module]._module_fqn
+                if module_fqn is None:
+                    module_to_fsdp_param_group[module]._module_fqn = module_name
+                else:
+                    assert isinstance(module_fqn, str), f"{module_fqn}"
+                    module_fqn += f", {module_name}"
+                    module_to_fsdp_param_group[module]._module_fqn = module_fqn
+
+    @disable_if_config_true
+    def _pre_forward(
+        self, module: nn.Module, args: Tuple[Any, ...], kwargs: Dict[str, Any]
+    ) -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
+        # When composing with module-hook-based activation checkpointing, the
+        # the pre-backward hook is responsible for the unshard
+        if self._training_state == TrainingState.PRE_BACKWARD:
+            return args, kwargs
+        self._training_state = TrainingState.FORWARD
+        args, kwargs = self._root_pre_forward(module, args, kwargs)
+        if self._mp_policy.cast_forward_inputs and self._mp_policy.param_dtype:
+            with torch.profiler.record_function("FSDP::cast_forward_inputs"):
+                cast_fn = functools.partial(
+                    _cast_fp_tensor, self._mp_policy.param_dtype
+                )
+                args, kwargs = tree_map(cast_fn, args), tree_map(cast_fn, kwargs)
+        if self._fsdp_param_group:
+            args, kwargs = self._fsdp_param_group.pre_forward(module, args, kwargs)
+        for fsdp_state in self._states_to_forward_prefetch:
+            if (target_param_group := fsdp_state._fsdp_param_group) is not None:
+                FSDPParamGroup._prefetch_unshard(target_param_group, "forward")
+        return args, kwargs
+
+    @disable_if_config_true
+    def _post_forward(self, module: nn.Module, input: Any, output: Any) -> Any:
+        # When composing with module-hook-based activation checkpointing, the
+        # post-backward hook is responsible for the reshard
+        if self._training_state == TrainingState.PRE_BACKWARD:
+            return output
+        if self._fsdp_param_group:
+            output = self._fsdp_param_group.post_forward(module, input, output)
+        output = self._register_pre_backward_hook(output)
+        self._training_state = TrainingState.IDLE
+        if self._state_ctx.iter_forward_root is self:
+            if all_gather_state := self._comm_ctx.all_gather_state:
+                # Free the last all-gather result if needed; refer to
+                # [Note: Overlapping all-gather copy-in and all-gather]
+                self._comm_ctx.all_gather_copy_in_stream.wait_event(
+                    all_gather_state.event
+                )
+                self._comm_ctx.all_gather_stream.wait_event(all_gather_state.event)
+                self._comm_ctx.all_gather_state = None  # free the all-gather result
+            self._state_ctx.iter_forward_root = None
+        if self._mp_policy.output_dtype is not None:
+            with torch.profiler.record_function("FSDP::cast_forward_outputs"):
+                output = tree_map(
+                    functools.partial(_cast_fp_tensor, self._mp_policy.output_dtype),
+                    output,
+                )
+        return output
+
+    def _pre_backward(self, grad: torch.Tensor) -> torch.Tensor:
+        self._training_state = TrainingState.PRE_BACKWARD
+        self._register_root_post_backward_final_callback()
+        if self._fsdp_param_group:
+            default_prefetch = len(self._states_to_backward_prefetch) == 0
+            self._fsdp_param_group.pre_backward(default_prefetch)
+        for fsdp_state in self._states_to_backward_prefetch:
+            if (target_param_group := fsdp_state._fsdp_param_group) is not None:
+                FSDPParamGroup._prefetch_unshard(target_param_group, "backward")
+        return grad
+
+    def _root_post_backward_final_callback(self) -> None:
+        if not ca.compiled_autograd_enabled:
+            logger.debug("FSDP::root_post_backward")
+        with torch.profiler.record_function("FSDP::root_post_backward_callback"):
+            for state in self._state_ctx.all_states:
+                if state._fsdp_param_group and state._fsdp_param_group.is_unsharded:
+                    # Run post-backward in case forward inputs did not require
+                    # gradient so the autograd backward did not run
+                    state._fsdp_param_group.post_backward()
+                state._training_state = TrainingState.IDLE
+                if state._fsdp_param_group:
+                    state._fsdp_param_group._training_state = TrainingState.IDLE
+                if self._state_ctx.is_last_backward:
+                    state._finalize_backward()
+            if self._state_ctx.is_last_backward:
+                self._comm_ctx.post_forward_order.clear()
+                if self._comm_ctx.reduce_scatter_state is not None:
+                    torch.cuda.current_stream().wait_event(
+                        self._comm_ctx.reduce_scatter_state.event
+                    )
+                    self._comm_ctx.reduce_scatter_state = None
+            self._state_ctx.post_backward_final_callback_queued = False
+
+    def _finalize_backward(self) -> None:
+        if self._modules_to_run_forward:
+            msg = (
+                f"{len(self._modules_to_run_forward)} of the {len(self._modules)} "
+                f"modules passed to fully_shard did not run forward before backward, "
+                "which is error-prone since FSDP post-forward/pre-backward logic "
+                "will not run for these modules. We recommend passing only modules "
+                "that run forward together. Modules that did not run forward: "
+                f"{list(self._modules_to_run_forward)}"
+            )
+            warning_once(logger, msg, stacklevel=2)
+            # Clear since we want the next forward to run
+            self._modules_to_run_forward.clear()
+        if self._fsdp_param_group:
+            self._fsdp_param_group.finalize_backward()
+
+    def _register_pre_backward_hook(self, output: Any) -> Any:
+        if not torch.is_grad_enabled():
+            return output
+        flat_outputs, _ = tree_flatten(output)
+        for t in flat_outputs:
+            if torch.is_tensor(t) and t.requires_grad:
+                t.register_hook(self._pre_backward)
+        return output
+
+    def _register_root_post_backward_final_callback(self):
+        if self._state_ctx.post_backward_final_callback_queued:
+            return
+        self._state_ctx.post_backward_final_callback_queued = True
+        Variable._execution_engine.queue_callback(
+            self._root_post_backward_final_callback
+        )
+
+
+def _get_module_fsdp_state(module: nn.Module) -> Optional[FSDPState]:
+    state = _get_module_state(module)
+    if isinstance(state, FSDPState):
+        return state
+    return None
+
+
+def _register_group_forward_hooks(
+    modules: Sequence[nn.Module],
+    pre_hook: Callable,
+    post_hook: Callable,
+    modules_to_run: Set[nn.Module],
+):
+    """
+    Registers group forward pre and post-hooks. The pre-hook runs upon the
+    first module pre-forward, and the post-hook runs upon the last. If at least
+    one module does not run forward, then the post-hook does not run.
+    """
+    modules_set = set(modules)
+
+    @disable_if_config_true
+    @functools.wraps(pre_hook)
+    def wrapped_pre_hook(*args: Any, **kwargs: Any):
+        if len(modules_to_run) == 0:  # first to run
+            modules_to_run.update(modules_set)
+            return pre_hook(*args, **kwargs)
+
+    @disable_if_config_true
+    def get_wrapped_post_hook(module: nn.Module):
+        @functools.wraps(post_hook)
+        def wrapped_post_hook(*args: Any, **kwargs: Any):
+            modules_to_run.discard(module)
+            if len(modules_to_run) == 0:
+                return post_hook(*args, **kwargs)
+
+        return wrapped_post_hook
+
+    pre_handles = [
+        module.register_forward_pre_hook(
+            wrapped_pre_hook, prepend=True, with_kwargs=True
+        )
+        for module in modules
+    ]
+    post_handles = [
+        module.register_forward_hook(
+            get_wrapped_post_hook(module), prepend=False, always_call=True
+        )
+        for module in modules
+    ]
+    return _MultiHandle(tuple(pre_handles + post_handles))
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/fully_shard.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/fully_shard.py
new file mode 100644
index 0000000000000000000000000000000000000000..5da4f83f9e5594a4b4d5efa12e1ec5bb2ca1d640
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fsdp/fully_shard.py
@@ -0,0 +1,446 @@
+# mypy: allow-untyped-decorators
+# mypy: allow-untyped-defs
+import functools
+from typing import Any, cast, Dict, Iterable, List, NoReturn, Optional, Type, Union
+
+import torch
+import torch.nn as nn
+from torch.distributed._composable import contract
+from torch.distributed.tensor import DeviceMesh
+from torch.distributed.utils import _get_root_modules
+
+from ._fsdp_api import MixedPrecisionPolicy, OffloadPolicy
+from ._fsdp_common import FSDPMeshInfo, HSDPMeshInfo
+from ._fsdp_init import (
+    _get_device_from_mesh,
+    _get_managed_modules,
+    _get_managed_states,
+    _get_post_forward_mesh_info,
+    _init_default_fully_shard_mesh,
+    _move_states_to_device,
+)
+from ._fsdp_param_group import FSDPParamGroup
+from ._fsdp_state import _get_module_fsdp_state, FSDPState
+
+
+cls_to_fsdp_cls: Dict[Type, Type] = {}
+
+
+# The decorator adds a state object to `module` that can be accessed via
+# `fully_shard.state(module)`. The state object and module are 1:1.
+@contract(state_cls=FSDPState)  # type: ignore[operator]
+def fully_shard(
+    module: Union[nn.Module, List[nn.Module]],
+    *,
+    mesh: Optional[DeviceMesh] = None,
+    reshard_after_forward: Union[bool, int] = True,
+    mp_policy: MixedPrecisionPolicy = MixedPrecisionPolicy(),
+    offload_policy: OffloadPolicy = OffloadPolicy(),
+):
+    """
+    Shard module parameters across data parallel workers.
+
+    This function applies fully sharded data parallelism (FSDP) or a variant to
+    ``module``, a technique for memory savings at the cost of communication.
+    Parameters are sharded across ``mesh``, and in turn, so are their gradients
+    and optimizer states.
+
+    The sharded parameters are all-gathered to construct the unsharded
+    parameters for forward or backward computation. The unsharded parameters
+    are freed after computation to save memory. The gradients are reduced
+    across the mesh and divided by the mesh size for data parallelism. The
+    optimizer step runs on the sharded parameters.
+
+    Each call to ``fully_shard`` constructs one communication group that
+    includes the parameters in ``module.parameters()`` except those already
+    assigned to a group from a nested call. Each group's parameters and its
+    gradients are communicated together in one collective, respectively.
+    Constructing multiple groups across the model (e.g. "layer by layer")
+    allows for peak memory savings and communication/computation overlap.
+
+    Implementation-wise, the sharded parameters are represented as
+    :class:`DTensor` s, sharded on dim-0, and the unsharded parameters are
+    represented as :class:`Tensor` s. A module forward pre-hook all-gathers the
+    parameters, and a module forward hook frees them. Similar backward hooks
+    gather parameters and later free parameters/reduce gradients.
+
+    Args:
+        module (Union[nn.Module, List[nn.Module]): The module or modules to
+            shard with FSDP and group together for communication.
+        mesh (Optional[DeviceMesh]): This data parallel mesh defines the
+            sharding and device. If 1D, then parameters are fully sharded
+            across the 1D mesh (FSDP). If 2D, then parameters are sharded
+            across the 0th dim and replicated across the 1st dim (HSDP). The
+            mesh's device type gives the device type used for communication;
+            if a CUDA or CUDA-like device type, then we use the current device.
+        reshard_after_forward (Union[bool, int]): This controls the parameter
+            behavior after forward and can trade off memory and communication:
+            - If ``True``, then this reshards parameters after forward and
+            all-gathers in backward.
+            - If ``False``, then this keeps the unsharded parameters in memory
+            after forward and avoids the all-gather in backward.
+            - If an ``int``, then this represents the world size to reshard to
+            after forward. It should be a non-trivial divisor of the ``mesh``
+            shard dim size (i.e. excluding 1 and the dim size itself). A choice
+            may be the intra-node size (e.g. ``torch.cuda.device_count()``).
+            This allows the all-gather in backward to be over a smaller world
+            size at the cost of higher memory usage than setting to ``True``.
+            - The root FSDP state has its value specially set to ``False`` as a
+            heuristic since its parameters would typically be immediately
+            all-gathered for backward.
+            - After forward, the parameters registered to the module depend on
+            to this: The registered parameters are the sharded parameters if
+            ``True``; unsharded parameters if ``False``; and the paramters
+            resharded to the smaller mesh otherwise. To modify the parameters
+            between forward and backward, the registered parameters must be the
+            sharded parameters. For ``False`` or an ``int``, this can be done
+            by manually resharding via :meth:`reshard`.
+        mp_policy (MixedPrecisionPolicy): This controls the mixed precision
+            policy, which offers parameter/reduction mixed precision for this
+            module. See :class:`MixedPrecisionPolicy` for details.
+        offload_policy (OffloadPolicy): This controls the offloading policy,
+            which offers parameter/gradient/optimizer state offloading. See
+            :class:`OffloadPolicy` and its subclasses for details.
+    """
+    if isinstance(module, (nn.ModuleList, nn.ModuleDict)):
+        raise ValueError(
+            f"fully_shard does not support containers that do not implement forward: {module}"
+        )
+    mesh = mesh or _init_default_fully_shard_mesh()
+    if mesh.ndim not in (1, 2):
+        raise ValueError(f"fully_shard expects a 1D or 2D DeviceMesh but got {mesh}")
+    elif mesh.ndim == 1:
+        mesh_info = FSDPMeshInfo(mesh, shard_mesh_dim=0)
+    else:
+        mesh_info = HSDPMeshInfo(mesh, shard_mesh_dim=1, replicate_mesh_dim=0)
+    device = _get_device_from_mesh(mesh)
+    post_forward_mesh_info = _get_post_forward_mesh_info(
+        reshard_after_forward, mesh_info
+    )
+
+    arg_module = module
+    modules = (
+        (module,) if isinstance(module, nn.Module) else tuple(_get_root_modules(module))
+    )
+    state = fully_shard.state(modules[0])
+    state.init(modules, device, mp_policy)
+
+    managed_modules = _get_managed_modules(modules)
+    params, buffers = _get_managed_states(managed_modules)
+    _move_states_to_device(params, buffers, device)
+    if params:
+        state._fsdp_param_group = FSDPParamGroup(
+            params,
+            modules,
+            mesh_info,
+            post_forward_mesh_info,
+            device,
+            mp_policy,
+            offload_policy,
+        )
+
+    # For Dynamo
+    for managed_module in managed_modules:
+        managed_module._is_fsdp_managed_module = True  # type: ignore[assignment]
+        managed_module._fsdp_use_orig_params = True  # type: ignore[assignment]
+
+    # Place FSDP leftmost for highest priority in the method resolution order
+    for module in modules:
+        cls = module.__class__
+        new_cls = cls_to_fsdp_cls.get(cls, None)
+        if not new_cls:
+            dct = {"__deepcopy__": unimplemented_deepcopy}
+            new_cls = type(f"FSDP{cls.__name__}", (FSDPModule, cls), dct)
+            cls_to_fsdp_cls[cls] = new_cls
+        module.__class__ = new_cls
+    return arg_module
+
+
+def unimplemented_deepcopy(*args: Any, **kwargs: Any) -> NoReturn:
+    raise AssertionError(
+        "FSDP does not support deepcopy. Please use state dict for serialization."
+    )
+
+
+class FSDPModule:
+    def __new__(cls, *args, **kwargs):
+        """
+        Override ``__new__`` to remove the FSDP class and directly construct
+        the original class for cases like indexing into a container module.
+        """
+        # Use index 2 since 0 is the dynamically constructed `FSDP<...>` class
+        # and index 1 is the `FSDPModule` class itself
+        orig_cls = cls.__mro__[2]
+        self = orig_cls.__new__(orig_cls, *args, **kwargs)
+        self.__init__(*args, **kwargs)
+        return self
+
+    def reshard(self) -> None:
+        """
+        Reshards the module's parameters, registering the sharded parameters
+        to the module and freeing the unsharded parameters if needed. This
+        method is *not* recursive.
+        """
+        state = self._get_fsdp_state()
+        if fsdp_param_group := state._fsdp_param_group:
+            fsdp_param_group.reshard()
+
+    def unshard(self, async_op: bool = False) -> Optional["UnshardHandle"]:
+        """
+        Unshards the module's parameters by allocating memory and all-gathering
+        the parameters. This method is *not* recursive.
+
+        Args:
+            async_op (bool): If ``True``, then returns a :class:`UnshardHandle`
+                that has a :meth:`wait` method to wait on the unshard op. If
+                ``False``, then returns ``None`` and waits on the handle inside
+                this function.
+
+        .. warning:: This method is experimental and subject to change.
+
+        .. note:: If ``async_op=True``, then the user does not have to call
+            :meth:`wait` on the returned handle if waiting on the unshard op
+            in the module's pre-forward is tolerable. FSDP will wait on the
+            pending unshard op in the pre-forward automatically.
+        """
+        state = self._get_fsdp_state()
+        fsdp_param_group = state._fsdp_param_group
+        if fsdp_param_group is not None:
+            fsdp_param_group.lazy_init()
+            fsdp_param_group.unshard(async_op=async_op)
+        handle = UnshardHandle(fsdp_param_group)
+        if async_op:
+            return handle
+        handle.wait()
+        return None
+
+    def set_is_last_backward(self, is_last_backward: bool) -> None:
+        """
+        Sets whether the next backward is the last one, meaning that FSDP
+        should wait for gradient reduction to finish and clear internal data
+        structures used for explicit prefetching.
+        """
+        state = self._get_fsdp_state()
+        state._state_ctx.is_last_backward = is_last_backward
+
+    def set_requires_gradient_sync(
+        self, requires_gradient_sync: bool, *, recurse: bool = True
+    ) -> None:
+        """
+        Sets if the module should sync gradients. This can be used to implement
+        gradient accumulation without communication. For HSDP, this controls
+        both reduce-scatter and all-reduce together.
+
+        Args:
+            requires_gradient_sync (bool): Whether to reduce gradients for the
+                module's parameters.
+            recurse (bool): Whether to set for all submodules or just the
+                passed-in module.
+        """
+        self_module = cast(nn.Module, self)
+        modules = list(self_module.modules()) if recurse else [self_module]
+        for module in modules:
+            if isinstance(module, FSDPModule):
+                state = module._get_fsdp_state()
+                if fsdp_param_group := state._fsdp_param_group:
+                    fsdp_param_group.reduce_grads = requires_gradient_sync
+                    fsdp_param_group.all_reduce_grads = requires_gradient_sync
+
+    def set_requires_all_reduce(
+        self, requires_all_reduce: bool, *, recurse: bool = True
+    ) -> None:
+        """
+        Sets if the module should all-reduce gradients. This can be used to
+        implement gradient accumulation with only reduce-scatter but not
+        all-reduce for HSDP.
+        """
+        self_module = cast(nn.Module, self)
+        modules = list(self_module.modules()) if recurse else [self_module]
+        for module in modules:
+            if isinstance(module, FSDPModule):
+                state = module._get_fsdp_state()
+                if fsdp_param_group := state._fsdp_param_group:
+                    fsdp_param_group.all_reduce_grads = requires_all_reduce
+
+    def set_reshard_after_backward(
+        self, reshard_after_backward: bool, *, recurse: bool = True
+    ) -> None:
+        """
+        Sets if the module should reshard parameters after backward. This can
+        be used during gradient accumulation to trade off higher memory for
+        reduced communication.
+
+        Args:
+            reshard_after_backward (bool): Whether to reshard parameters after
+                backward.
+            recurse (bool): Whether to set for all submodules or just the
+                passed-in module.
+        """
+        self_module = cast(nn.Module, self)
+        modules = list(self_module.modules()) if recurse else [self_module]
+        for module in modules:
+            if isinstance(module, FSDPModule):
+                state = module._get_fsdp_state()
+                if fsdp_param_group := state._fsdp_param_group:
+                    fsdp_param_group.reshard_after_backward = reshard_after_backward
+
+    def set_modules_to_forward_prefetch(self, modules: List["FSDPModule"]) -> None:
+        """
+        Sets the FSDP modules for which this FSDP module should explicitly
+        prefetch all-gathers in forward. The prefetching runs after this
+        module's all-gather copy-out.
+
+        Passing a singleton list containing the next FSDP module gives the same
+        all-gather overlap behavior as the default overlap behavior, except the
+        prefetched all-gather is issued earlier from the CPU. Passing a list
+        with at least length two is required for more aggressive overlap and
+        will use more reserved memory.
+
+        Args:
+            modules (List[FSDPModule]): FSDP modules to prefetch.
+        """
+        _assert_all_fsdp_modules(modules)
+        self._get_fsdp_state()._states_to_forward_prefetch = [
+            module._get_fsdp_state() for module in modules
+        ]
+
+    def set_modules_to_backward_prefetch(self, modules: List["FSDPModule"]) -> None:
+        """
+        Sets the FSDP modules for which this FSDP module should explicitly
+        prefetch all-gathers in backward. This overrides the default backward
+        pretching implementation that prefetches the next FSDP module based on
+        the reverse post-forward order.
+
+        Passing a singleton list containing the previous FSDP module gives the
+        same all-gather overlap behavior as the default overlap behavior.
+        Passing a list with at least length two is required for more aggressive
+        overlap and will use more reserved memory.
+
+        Args:
+            modules (List[FSDPModule]): FSDP modules to prefetch.
+        """
+        _assert_all_fsdp_modules(modules)
+        self._get_fsdp_state()._states_to_backward_prefetch = [
+            module._get_fsdp_state() for module in modules
+        ]
+
+    def set_post_optim_event(self, event: torch.cuda.Event) -> None:
+        """
+        Sets a post-optimizer-step event for the root FSDP module to wait the
+        all-gather streams on.
+
+        By default, the root FSDP module waits the all-gather streams on the
+        current stream to ensure that the optimizer step has finished before
+        all-gathering. However, this may introduce false dependencies if
+        there is unrelated computation after the optimizer step. This API
+        allows the user to provide their own event to wait on. After the root
+        waits on the event, the event is discarded, so this API should be
+        called with a new event each iteration.
+
+        Args:
+            event (torch.cuda.Event): Event recorded after the optimizer step
+                to wait all-gather streams on.
+        """
+        self._get_fsdp_state()._state_ctx.post_optim_event = event
+
+    def set_reduce_scatter_divide_factor(self, factor: float) -> None:
+        """
+        Sets a custom divide factor for the reduce-scatter. This becomes a
+        custom reduce op using NCCL's PreMulSum, which allows multiplying by
+        the factor before reduction.
+
+        Args:
+            factor (float): Custom divide factor.
+        """
+        state = self._get_fsdp_state()
+        if (fsdp_param_group := state._fsdp_param_group) is not None:
+            mul_factor = 1.0 / float(factor)
+            reduce_op = torch.distributed._make_nccl_premul_sum(mul_factor)
+            fsdp_param_group.reduce_scatter_reduce_op = reduce_op
+
+    def _get_fsdp_state(self) -> FSDPState:
+        if (state := _get_module_fsdp_state(cast(nn.Module, self))) is None:
+            raise AssertionError(f"No FSDP state found on {self}")
+        return state
+
+    def _apply(self, *args: Any, **kwargs: Any) -> Any:
+        # Reshard to ensure that sharded parameters are registered
+        self.reshard()
+        ret = super()._apply(*args, **kwargs)  # type: ignore[misc]
+        state = self._get_fsdp_state()
+        if not (fsdp_param_group := state._fsdp_param_group):
+            return ret
+        # TODO: Remove this padding logic once DTensor pads the local tensor:
+        # https://github.com/pytorch/pytorch/issues/113045
+        with torch.no_grad():
+            for fsdp_param in fsdp_param_group.fsdp_params:
+                fsdp_param.reset_sharded_param()
+        return ret
+
+
+class UnshardHandle:
+    """
+    A handle to wait on the unshard op.
+
+    Args:
+        fsdp_param_group (FSDPParamGroup, optional): FSDP parameter group to
+            unshard. This should be ``None`` iff the FSDP module does not
+            manage any parameters, meaning the unshard is a no-op.
+    """
+
+    def __init__(self, fsdp_param_group: Optional[FSDPParamGroup]):
+        self._fsdp_param_group = fsdp_param_group
+
+    def wait(self):
+        """
+        Waits on the unshard op.
+
+        This ensures that the current stream can use the unsharded parameters,
+        which are now registered to the module.
+        """
+        if self._fsdp_param_group is not None:
+            self._fsdp_param_group.wait_for_unshard()
+            # Avoid keeping a reference
+            self._fsdp_param_group = None
+
+
+def register_fsdp_forward_method(module: nn.Module, method_name: str) -> None:
+    """
+    Registers a method on ``module`` to be a forward method for FSDP.
+
+    FSDP only knows to run its pre-forward and post-forward hooks on the
+    default :meth:`nn.Module.forward` method. This function patches a user
+    specified method to run the pre/post-forward hooks before/after the method,
+    respectively. If ``module`` is not an :class:`FSDPModule`, then this is a
+    no-op.
+
+    Args:
+        module (nn.Module): Module to register the forward method on.
+        method_name (str): Name of the forward method.
+    """
+    if not isinstance(module, FSDPModule):
+        # Make no-op to allow including both when using/not using FSDP
+        return
+    if not hasattr(module, method_name):
+        raise ValueError(f"{type(module)} does not have a method {method_name}")
+    orig_method = getattr(module, method_name)
+
+    @functools.wraps(orig_method)
+    def wrapped_method(self, *args, **kwargs):
+        fsdp_state = self._get_fsdp_state()
+        args, kwargs = fsdp_state._pre_forward(self, args, kwargs)
+        out = orig_method(*args, **kwargs)
+        return fsdp_state._post_forward(self, args, out)
+
+    # Use `__get__` to make `wrapped_method` an instance method
+    setattr(
+        module,
+        method_name,
+        wrapped_method.__get__(module, type(module)),  # type:ignore[attr-defined]
+    )
+
+
+def _assert_all_fsdp_modules(modules: Iterable[Any]) -> None:
+    for module in modules:
+        if not isinstance(module, FSDPModule):
+            raise ValueError(f"Expects FSDPModule but got {type(module)}: {module}")
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fully_shard.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fully_shard.py
new file mode 100644
index 0000000000000000000000000000000000000000..4afa0f431075f7499b5808161fb42925494f1185
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/fully_shard.py
@@ -0,0 +1,131 @@
+# mypy: allow-untyped-decorators
+from typing import Callable, Iterable, Optional, Union
+from typing_extensions import deprecated
+
+import torch
+import torch.distributed as dist
+import torch.nn as nn
+from torch.distributed._composable.contract import contract
+from torch.distributed._composable_state import _get_module_state, _insert_module_state
+from torch.distributed.fsdp._common_utils import _FSDPState
+from torch.distributed.fsdp._dynamo_utils import _annotate_modules_for_dynamo
+from torch.distributed.fsdp._init_utils import (
+    _init_buffer_state,
+    _init_core_state,
+    _init_device_handle,
+    _init_ignored_module_states,
+    _init_param_handle_from_module,
+    _init_prefetching_state,
+    _init_process_group_state,
+    _init_runtime_state,
+    _init_state_dict_state,
+    HYBRID_SHARDING_STRATEGIES,
+)
+from torch.distributed.fsdp._runtime_utils import (
+    _register_post_forward_hook,
+    _register_pre_forward_hook,
+    _register_root_pre_forward_hook,
+)
+from torch.distributed.fsdp._state_dict_utils import _register_all_state_dict_hooks
+from torch.distributed.fsdp._wrap_utils import _auto_wrap
+from torch.distributed.fsdp.api import (
+    BackwardPrefetch,
+    CPUOffload,
+    MixedPrecision,
+    ShardingStrategy,
+)
+from torch.distributed.fsdp.wrap import _Policy
+
+
+@contract(state_cls=_FSDPState)
+@deprecated(
+    "`torch.distributed._composable.fully_shard` is being deprecated. "
+    "You can continue to use the wrapper based FSDP. "
+    "See usage in: https://github.com/pytorch/pytorch/blob/main/torch/distributed/fsdp/fully_sharded_data_parallel.py. "
+    "`torch.distributed._composable.fully_shard` will be removed after PyTorch 2.5.",
+    category=FutureWarning,
+)
+def fully_shard(
+    module: nn.Module,
+    *,
+    process_group: Optional[dist.ProcessGroup] = None,
+    policy: Optional[_Policy] = None,
+    strategy: Optional[ShardingStrategy] = None,
+    mixed_precision: Optional[MixedPrecision] = None,
+    cpu_offload: Optional[CPUOffload] = None,
+    ignored_modules: Optional[Iterable[torch.nn.Module]] = None,
+    device_id: Optional[Union[int, torch.device]] = None,
+    param_init_fn: Optional[Callable[[nn.Module], None]] = None,
+    sync_module_states: bool = False,
+    forward_prefetch: bool = False,
+    ignored_states: Union[
+        Optional[Iterable[torch.nn.Parameter]], Optional[Iterable[torch.nn.Module]]
+    ] = None,
+) -> nn.Module:
+    """Applies ``FullyShardedDataParallel`` (FSDP) semantics to ``module``."""
+    torch._C._log_api_usage_once("torch.distributed.fully_shard")
+    # Enforce the new auto wrap policy
+    if policy is not None and not isinstance(policy, _Policy):
+        raise ValueError(f"Expects a `_Policy` but got {policy}")
+    state = fully_shard.state(module)
+    state = _init_ignored_module_states(state, module, ignored_modules, ignored_states)
+    state = _init_device_handle(state, module, state._ignored_params, device_id)
+    _annotate_modules_for_dynamo(module, state._ignored_modules, True)
+    state = _init_process_group_state(state, process_group, strategy, policy)
+    if policy is not None:
+        root_kwargs = {
+            "process_group": process_group,
+            "strategy": strategy,
+            "mixed_precision": mixed_precision,
+            "cpu_offload": cpu_offload,
+            "ignored_modules": ignored_modules,
+            "device_id": device_id,
+            "param_init_fn": param_init_fn,
+            "sync_module_states": sync_module_states,
+            "forward_prefetch": forward_prefetch,
+            "ignored_states": ignored_states,
+        }
+        if strategy in HYBRID_SHARDING_STRATEGIES:
+            root_kwargs["process_group"] = (state.process_group, state._inter_node_pg)
+        _auto_wrap(
+            module,
+            policy,
+            state._ignored_modules,
+            state._ignored_params,
+            root_kwargs,
+            fully_shard,
+        )
+    state = _init_core_state(
+        state,
+        strategy or ShardingStrategy.FULL_SHARD,
+        mixed_precision,
+        cpu_offload,
+        limit_all_gathers=True,
+        use_orig_params=True,
+        backward_prefetch_limit=1,
+        forward_prefetch_limit=1,
+    )
+    state = _init_runtime_state(state)
+    state = _init_prefetching_state(
+        state, BackwardPrefetch.BACKWARD_PRE, forward_prefetch=forward_prefetch
+    )
+    state = _init_buffer_state(state, module)
+    state = _init_param_handle_from_module(
+        state, module, device_id, param_init_fn, sync_module_states
+    )
+    state = _init_state_dict_state(state)
+    _register_all_state_dict_hooks(state)
+    _register_pre_forward_hook(state, module)
+    _register_post_forward_hook(state, module)
+    _register_root_pre_forward_hook(state, module)  # prepend last
+    # Always insert the state for the passed-in module even if it has no
+    # managed parameters, in which case it has no handles and does not appear
+    # in `_fully_sharded_module_to_handles`
+    _insert_module_state(module, state)
+    for submodule in module.modules():
+        if (
+            submodule in state._fully_sharded_module_to_handle
+            and _get_module_state(submodule) is None
+        ):
+            _insert_module_state(submodule, state)
+    return module
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/replicate.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/replicate.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac1956ce0962cf262390077bd4e97e9bca57fbe9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_composable/replicate.py
@@ -0,0 +1,256 @@
+# mypy: allow-untyped-decorators
+# mypy: allow-untyped-defs
+import weakref
+from typing import Any, cast, Dict, Iterable, List, NoReturn, Optional, Set, Tuple
+
+import torch
+import torch.nn as nn
+from torch.distributed._composable_state import _State
+from torch.nn.parallel import DistributedDataParallel
+
+from .contract import _get_registry, contract
+
+
+_ROOT_MODULE_PREFIX = ""
+
+
+class _ReplicateState(_State):
+    def __init__(self) -> None:
+        super().__init__()
+        self.module: nn.Module = nn.ParameterList()
+        self.has_initialized: bool = False
+        self._param_list: nn.ParameterList = nn.ParameterList()
+        # TODO(@fegin): this variable is originally create for testing, we
+        # should remove this if possible.
+        self._orig_module = self.module
+        self._param_names: List[str] = []
+        self._no_sync: bool = False
+        self._init_args: Optional[Tuple[Any, ...]] = None
+        self._init_kwargs: Dict[str, Any] = {}
+        self._comm_hook_args: List[Any] = []
+
+    def _collect_params(
+        self,
+        module: nn.Module,
+        ignored_modules: Set[nn.Module],
+        ignored_params: Set[nn.Parameter],
+        prefix: str = _ROOT_MODULE_PREFIX,
+    ) -> None:
+        # skip if managed by fully_sharded API
+        if _is_fully_sharded(module):
+            return
+
+        # if a module is ignored, all descendants of the module are ignored.
+        if module in ignored_modules:
+            return
+
+        recurse_prefix = (
+            f"{prefix}." if prefix != _ROOT_MODULE_PREFIX else _ROOT_MODULE_PREFIX
+        )
+
+        for n, p in module.named_parameters(recurse=False):
+            if p not in ignored_params:
+                self._param_list.append(p)
+                self._param_names.append(f"{recurse_prefix}{n}")
+
+        for name, child_module in module.named_children():
+            self._collect_params(
+                child_module,
+                ignored_modules,
+                ignored_params,
+                prefix=f"{recurse_prefix}{name}",
+            )
+
+    def lazy_init(self) -> None:
+        @torch._disable_dynamo(recursive=True)
+        def _lazy_init():
+            assert self._init_args is not None
+            self.init(*self._init_args, **self._init_kwargs)
+            self.register_comm_hook()
+            self._init_args = ()
+            self._init_kwargs = {}
+
+        _lazy_init()
+
+    def init(
+        self,
+        module: nn.Module,
+        ignored_modules: Set[nn.Module],
+        **kwargs,
+    ) -> None:
+        if self.has_initialized:
+            return
+
+        self.has_initialized = True
+
+        device_mesh = kwargs.get("device_mesh", None)
+        self.module = module
+        ignored_params = {p for m in ignored_modules for p in m.parameters()}
+        for submodule in module.modules():
+            if _is_fully_sharded(submodule):
+                ignored_params.update(submodule.parameters())
+        from torch.distributed.tensor.parallel.ddp import _localize_dtensor
+
+        _localize_dtensor(module, ignored_params=ignored_params)
+        self._collect_params(module, ignored_modules, ignored_params)
+
+        if "device_id" in kwargs:
+            # replicate() supports a small usability enhancement where
+            # user can pass in device_id as a Union[int, torch.device] even for
+            # CPU devices so users don't have to change code for CPU/GPU runs.
+            # We derive the right device_ids to feed into DDP to support this.
+            if kwargs["device_id"] is not None:
+                device_id = kwargs["device_id"]
+                # Convert to device_ids that DDP expects.
+                if isinstance(device_id, torch.device) and device_id.type == "cpu":
+                    # CPU modules receive device_ids None
+                    kwargs["device_ids"] = None
+                else:
+                    # GPU modules expect device_ids=[cuda_device]
+                    kwargs["device_ids"] = [device_id]
+            else:
+                kwargs["device_ids"] = None
+            kwargs.pop("device_id")
+
+        self._ddp = DistributedDataParallel(self._param_list, **kwargs)
+        # Weakref to the DDP instance is currently only used for testing.
+        replicate.state(self.module)._ddp_weakref = weakref.ref(self._ddp)
+
+    def register_comm_hook(self) -> None:
+        for comm_args, comm_kwargs in self._comm_hook_args:
+            self._ddp.register_comm_hook(*comm_args, **comm_kwargs)
+        self._comm_hook_args.clear()
+
+    def record_init_args(self, *args, **kwargs) -> None:
+        self._init_args = args
+        self._init_kwargs = kwargs
+
+    def forward_pre_hook(
+        self, module: nn.Module, args: Tuple[Any, ...], kwargs: Dict[str, Any]
+    ) -> Any:
+        if self._init_args or self._init_kwargs:
+            self.lazy_init()
+        self._ddp.require_backward_grad_sync = not self._no_sync
+        return self._ddp._pre_forward(*args, **kwargs)
+
+    def forward_post_hook(
+        self,
+        module: nn.Module,
+        input: Tuple[torch.Tensor],
+        output: torch.Tensor,
+    ) -> torch.Tensor:
+        return self._ddp._post_forward(output)
+
+
+def unimplemented_deepcopy(*args: Any, **kwargs: Any) -> NoReturn:
+    raise AssertionError(
+        "DDP does not support deepcopy. Please use state dict for serialization."
+    )
+
+
+# Follow the same pattern as FSDP/fully_shard
+class DDP:
+    def __new__(cls, *args, **kwargs):
+        """
+        Override ``__new__`` to remove the DDP class and directly construct
+        the original class for cases like indexing into a container module.
+        """
+        # Use index 2 since 0 is the dynamically constructed `DDP<...>` class
+        # and index 1 is the `DDP` class itself
+        orig_cls = cls.__mro__[2]
+        return orig_cls.__new__(orig_cls, *args, **kwargs)
+
+    def set_requires_gradient_sync(self, requires_gradient_sync: bool) -> None:
+        """
+        Sets if the module should sync gradients. This can be used to implement
+        gradient accumulation without communication.
+
+        Args:
+            requires_gradient_sync (bool): Whether to reduce gradients for the
+                module's parameters.
+        """
+        replicate.state(self)._no_sync = not requires_gradient_sync
+
+    def register_comm_hook(self, *args, **kwargs) -> None:
+        replicate.state(self)._comm_hook_args.append((args, kwargs))
+
+
+@contract(state_cls=_ReplicateState)
+def replicate(
+    module: nn.Module,
+    ignored_modules: Optional[Iterable[torch.nn.Module]] = None,
+    **kwargs,
+) -> nn.Module:
+    r"""Replicates a module
+
+    Args:
+        module (torch.nn.Module): module to replicate
+
+    Example::
+        >>> # xdoctest: +REQUIRES(module:torch._C._distributed_c10d)
+        >>> module = nn.Linear(3, 3)
+        >>> replicate(module)
+    """
+    torch._C._log_api_usage_once("torch.distributed.replicate")
+
+    # TODO(fegin): using kwargs is not a good idea if we would like to make
+    # replicate a formal API to replace DDP.
+    if "device_id" in kwargs:
+        if not isinstance(kwargs["device_id"], (int, torch.device)):
+            raise RuntimeError(
+                "Expected device_id to be int or torch.device, "
+                f"but got {type(kwargs['device_id'])}"
+            )
+
+    if _is_fully_sharded(module):
+        raise RuntimeError(
+            "Cannot apply `replicate()` on a Module already managed by `fully_shard`"
+        )
+
+    if ignored_modules is None:
+        ignored_modules = {}
+    else:
+        ignored_modules = set(ignored_modules)
+
+    state = cast(_ReplicateState, replicate.state(module))
+    module.register_forward_pre_hook(state.forward_pre_hook, with_kwargs=True)
+    device_mesh = kwargs.get("device_mesh", None)
+    if device_mesh is not None:
+        from torch.distributed.device_mesh import _mesh_resources
+
+        root_mesh = _mesh_resources.get_root_mesh(device_mesh)
+        # if a root mesh is not the same as device_mesh,
+        # meaning the device_mesh is sliced out from the root mesh.
+        if root_mesh != device_mesh:
+            # TODO: This is a temporary work around to enable DDP + TP.
+            # We should do the logic in DDP so that the 2D implementation is
+            # sound and the state_dict works out of the box.
+            #
+            # This won't conflict with what is done in DDP class as the module
+            # replicate is going to pass is NOT the original module.
+            from torch.distributed.tensor.parallel.ddp import (
+                _localize_dtensor,
+                _reconstruct_dtensor,
+            )
+
+            module.register_forward_pre_hook(_reconstruct_dtensor)
+            module.register_forward_hook(_localize_dtensor)
+
+    module.register_forward_hook(state.forward_post_hook)  # type: ignore[arg-type]
+
+    state.record_init_args(module, ignored_modules, **kwargs)
+
+    # Place DDP leftmost for highest priority in the method resolution order
+    cls = module.__class__
+    dct = {"__deepcopy__": unimplemented_deepcopy}
+    new_cls = type(f"DDP{cls.__name__}", (DDP, cls), dct)
+    module.__class__ = new_cls
+    return module
+
+
+def _is_fully_sharded(module: nn.Module) -> bool:
+    r"""Check if module is marked with fully_shard."""
+    registry = _get_registry(module)
+    if registry is None:
+        return False
+    return "fully_shard" in registry
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..85a313c779e7aa87726f425146048fcd37efd261
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/__init__.py
@@ -0,0 +1 @@
+from .api import _shard_tensor, load_with_process_group, shard_module, shard_parameter
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c1ababe155d763b8e3870e7e58957be8fe5bfc59
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/__pycache__/_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/__pycache__/_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c0975e43398d0e9ab3ccac64fbfbe936e0165f64
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/__pycache__/_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/__pycache__/api.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/__pycache__/api.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0aad87afdfb391739a1ec8da480eb6290168b82e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/__pycache__/api.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/__pycache__/common_op_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/__pycache__/common_op_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..62dea27086a6f632308a4fb4b6ad05052b3c2915
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/__pycache__/common_op_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/__pycache__/metadata.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/__pycache__/metadata.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6404d6955af412fb18ca89756d6aa738aca9900f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/__pycache__/metadata.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/__pycache__/op_registry_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/__pycache__/op_registry_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3f75cc7a1324ff62bb0fe42eedacbe47d839e03d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/__pycache__/op_registry_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/__pycache__/sharder.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/__pycache__/sharder.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a8e8b1429d3f7fdbfc39ac7c0df40ae8ec175b94
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/__pycache__/sharder.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..d06fc4dc961447dc974d2d79d7a4e418a7938541
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/_utils.py
@@ -0,0 +1,32 @@
+from typing import Sequence
+
+import torch
+from torch.distributed._shard.metadata import ShardMetadata
+
+
+DEPRECATE_MSG = "Please use DTensor instead and we are deprecating ShardedTensor."
+
+
+def narrow_tensor_by_index(
+    tensor: torch.Tensor,
+    offsets: Sequence[int],
+    sizes: Sequence[int],
+) -> torch.Tensor:
+    """
+    Narrow the tensor according to ``offsets`` and ``sizes``.
+    """
+    narrowed_tensor = tensor
+    for idx, (offset, size) in enumerate(zip(offsets, sizes)):
+        if size < tensor.size(idx):
+            # Reshape to get shard for this rank and we don't want autograd
+            # recording here for the narrow op and 'local_shard' should be a
+            # leaf variable in the autograd graph.
+            narrowed_tensor = narrowed_tensor.narrow(idx, offset, size)
+    return narrowed_tensor
+
+
+def narrow_tensor(tensor: torch.Tensor, metadata: ShardMetadata) -> torch.Tensor:
+    """
+    Narrow the tensor according to the metadata
+    """
+    return narrow_tensor_by_index(tensor, metadata.shard_offsets, metadata.shard_sizes)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/api.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a5f0c552cbedce234c6e14c0b252650a4498b27
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/api.py
@@ -0,0 +1,306 @@
+# mypy: allow-untyped-defs
+from contextlib import contextmanager
+from typing import Optional
+
+import torch
+import torch.distributed as dist
+import torch.nn as nn
+from torch.distributed import distributed_c10d
+from torch.distributed._shard.sharded_tensor import ShardedTensor
+
+from .sharder import Sharder
+from .sharding_plan import ShardingPlan
+from .sharding_spec import ChunkShardingSpec, ShardingSpec
+
+
+def _shard_tensor(
+    tensor: torch.Tensor, sharding_spec: ShardingSpec, src_rank=0, process_group=None
+) -> ShardedTensor:
+    """
+    Given a :class:`torch.Tensor`, it shards that tensor according to the provided
+    ``sharding_spec``. ``src_rank`` denotes the source rank which would be
+    used as the ground truth of the data which would be scattered as shards
+    across the rest of the ranks.
+
+    Args:
+        tensor (:class:`torch.Tensor`): Tensor needs to be sharded.
+        sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification
+            describing how to shard the Tensor.
+
+    Keyword args:
+        src_rank (int, optional): The source rank which is used as the ground truth of
+            the data for the parameter that would be sharded and scattered
+            across the rest of the ranks.
+            Default: 0.
+        process_group (ProcessGroup, optional): The process group to work on. If None,
+            the default process group will be used.
+
+    Returns:
+        A :class:`ShardedTensor` sharded from the given tensor.
+
+    .. warning::
+        Only :class:`torch.distributed._shard.sharding_spec.ChunkShardingSpec` is
+        currently supported as the ``sharding_spec``.
+    """
+    if not tensor.is_contiguous():
+        raise ValueError("input tensor is not a contiguous Tensor")
+
+    pg = (
+        process_group
+        if process_group is not None
+        else distributed_c10d._get_default_group()
+    )
+    world_size = dist.get_world_size(pg)
+    current_rank = dist.get_rank(pg)
+
+    # Validate src_rank and sharding_spec are same across all ranks.
+    gathered_list = [None] * world_size
+    dist.all_gather_object(gathered_list, (src_rank, sharding_spec), group=pg)
+
+    for idx, entry in enumerate(gathered_list):
+        if src_rank != entry[0]:  # type: ignore[index]
+            raise ValueError(
+                f"src_rank={src_rank} on rank: {current_rank} does not "  # type: ignore[index]
+                f"match with src_rank={entry[0]} on rank: {idx}"  # type: ignore[index]
+            )
+        if sharding_spec != entry[1]:  # type: ignore[index]
+            raise ValueError(
+                f"sharding_spec={sharding_spec} on rank: {current_rank} does not "  # type: ignore[index]
+                f"match with sharding_spec={entry[1]} on rank: {idx}"  # type: ignore[index]
+            )
+
+    st = sharding_spec.shard(tensor, src_rank=src_rank, process_group=pg)
+
+    return st
+
+
+def shard_parameter(
+    module: torch.nn.Module,
+    param_name: str,
+    sharding_spec: ShardingSpec,
+    src_rank=0,
+    process_group=None,
+):
+    """
+    Given a :class:`torch.nn.Module`, a ``param_name`` for a parameter in that
+    module, it shards that parameter according to the provided
+    ``sharding_spec``. ``src_rank`` denotes the source rank which would be
+    used as the ground truth of the data which would be scattered as shards
+    across the rest of the ranks.
+
+    This method replaces ``module.param_name`` with a
+    :class:`torch.distributed._sharded_tensor.ShardedTensor`
+
+    Args:
+        module (:class:`torch.nn.Module`): Module whose parameter needs to be sharded.
+        param_name (str): Name of the parameter of ``module`` that needs to be sharded.
+        sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification
+            describing how to shard the Tensor.
+
+    Keyword args:
+        src_rank (int, optional): The source rank which is used as the ground truth of
+            the data for the parameter that would be sharded and scattered
+            across the rest of the ranks.
+            Default: 0.
+        process_group (ProcessGroup, optional): The process group to work on. If None,
+            the default process group will be used.
+
+    .. warning::
+        Only :class:`torch.distributed._shard.sharding_spec.ChunkShardingSpec` is
+        currently supported as the ``sharding_spec``.
+    """
+    # Perform some validation first.
+    if not hasattr(module, param_name):
+        raise AttributeError(f"{module._get_name()} has no attribute `{param_name}`")
+
+    tensor = getattr(module, param_name)
+    if not isinstance(tensor, torch.Tensor):
+        raise ValueError(
+            f"Expected {type(module).__name__}.{param_name} to be a Tensor, but found {type(tensor).__name__}"
+        )
+
+    if not tensor.is_contiguous():
+        raise ValueError(f"param: {param_name} is not a contiguous Tensor")
+
+    st = _shard_tensor(tensor, sharding_spec, src_rank, process_group)
+
+    # Replace param with ShardedTensor.
+    module.register_parameter(param_name, nn.Parameter(st))
+
+
+# Tracks the current process group in the load context manager.
+_CURRENT_PROCESS_GROUP: Optional[dist.ProcessGroup] = None
+
+
+@contextmanager
+def load_with_process_group(process_group):
+    """
+    Context manager to set the process group with which to load a ShardedTensor.
+    """
+    global _CURRENT_PROCESS_GROUP
+    if _CURRENT_PROCESS_GROUP is not None:
+        raise RuntimeError(
+            'ProcessGroup already set by previous "load_with_process_group" '
+            "context manager"
+        )
+    _CURRENT_PROCESS_GROUP = process_group
+    try:
+        yield process_group
+    finally:
+        _CURRENT_PROCESS_GROUP = None
+
+
+def _get_current_process_group():
+    """
+    Retrieves the current process group set by ``load_with_process_group``.
+    If not set, it just returns the default group.
+    """
+    global _CURRENT_PROCESS_GROUP
+    if _CURRENT_PROCESS_GROUP is None:
+        return distributed_c10d._get_default_group()
+    else:
+        return _CURRENT_PROCESS_GROUP
+
+
+def _reshard_output(
+    module: torch.nn.Module, resharding_spec: ShardingSpec
+) -> torch.nn.Module:
+    """
+    Hook a module with output resharding in the forward pass according
+    to the given ``resharding_spec``.
+
+    Args:
+        module (:class:`torch.nn.Module`): Module whose output needs to be resharded.
+        resharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`):
+            The specification describing how the output of the module will be resharded.
+
+    Returns:
+        A :class:`torch.nn.Module` object with reshard API hooked.
+    """
+
+    def hook_func(_module, _input, output):
+        if isinstance(output, ShardedTensor):
+            return output.reshard(resharding_spec)
+        return output
+
+    module.register_forward_hook(hook_func)
+    return module
+
+
+def _collect_local_shard(module: torch.nn.Module) -> torch.nn.Module:
+    """
+    Hook a module with local shards collection in the forward pass.
+
+    This API is typically used to convert a sharded representation back to data parallel
+    representation. In particular, it returns the local tensor for this Shard. If the
+    size along the sharding dimension for the local tensor is 1, this dimension is removed
+    from the final result. For example a [4, 16] ShardedTensor across 4 ranks is typically
+    a local Tensor of size [16] across each rank and not [1, 16] across each rank.
+
+    Args:
+        module (:class:`torch.nn.Module`): Module whose output is ShardedTensor and the
+            local tensor value needs to be returned.
+
+    Returns:
+        A :class:`torch.nn.Module` object with collection API hooked.
+    """
+
+    def hook_func(_module, _input, output):
+        if isinstance(output, ShardedTensor):
+            local_tensor = output.local_tensor()
+            # Squeeze the # of dimensions manually, only applicable to ChunkShardingSpec
+            sharding_spec = output._sharding_spec
+            if (
+                isinstance(sharding_spec, ChunkShardingSpec)
+                and local_tensor.size(sharding_spec.dim) == 1  # type: ignore[attr-defined, arg-type]
+            ):
+                local_tensor = local_tensor.squeeze(
+                    output._sharding_spec.dim  # type: ignore[attr-defined]
+                )
+            return local_tensor
+
+    module.register_forward_hook(hook_func)
+    return module
+
+
+def shard_module(module: nn.Module, plan: ShardingPlan, src_rank=0, process_group=None):
+    """
+    Shards a given module according to the provided sharding `plan`. This method
+    first shards all the parameters according to the given sharding `plan`. Then if
+    `output_plan` and `return_local_tensor` are specified in the sharding `plan`, it
+    will tag the output of modules according `output_plan`, convert the module's
+    output back to data parallel according to `return_local_tensor`.
+
+    Needs to be called on all ranks in an SPMD fashion.
+
+    Args:
+        module (:class:`torch.nn.Module`): The module to apply sharding to
+        plan (:class:`torch.distributed._shard.sharding_plan.ShardingPlan`):
+            The ShardingPlan which specified param name to ShardingSpec to apply to
+            each parameter.
+
+    Keyword args:
+         src_rank (int, optional): The source rank which is used as the ground truth of
+            the data for the module that would be sharded and scattered across the rest
+            of the ranks.
+            Default: 0.
+        process_group (ProcessGroup, optional): The process group to work on. If None,
+            the default process group will be used.
+    """
+    # record Sharder paths for sanity check on the plan to ensure items in the plan
+    # does not conflict with the submodule tree that the Sharder is working with
+    sharder_paths = []
+    for name, spec in plan.plan.items():
+        if isinstance(spec, Sharder):
+            sharder_paths.append(name)
+
+    # shard the parameter according to the ShardingPlan
+    for name, spec in plan.plan.items():
+        if isinstance(spec, ShardingSpec):
+            # if found a sharding spec, try to shard the parameter
+            module_path, _, param_name = name.rpartition(".")
+
+            for sharder_path in sharder_paths:
+                if module_path.startswith(sharder_path):
+                    raise RuntimeError(
+                        f"ShardingPlan is in-valid, trying to shard a parameter: {name},"
+                        f" but there's already a Sharder entry for module {sharder_path},"
+                        f" parameter sharding should not conflict with the submodule tree"
+                        f" that a Sharder is working with!"
+                    )
+
+            mod = module.get_submodule(module_path)
+            shard_parameter(
+                mod, param_name, spec, src_rank=src_rank, process_group=process_group
+            )
+        elif isinstance(spec, Sharder):
+            parent_mod_path, _, mod_name = name.rpartition(".")
+            if name == "":
+                raise KeyError("Module path must not be empty for custom sharder!")
+            mod = module.get_submodule(name)
+            parent_mod = module.get_submodule(parent_mod_path)
+            sharded_mod = spec.shard(mod)
+            # swap this submodule with the sharded module
+            parent_mod.mod_name = sharded_mod
+        else:
+            raise TypeError(
+                f"Only `ShardingSpec` and `Sharder` are supported to shard '{name}'"
+            )
+
+    # reshard output if there's an entry in `reshard_output` for this module
+    if plan.output_plan is not None:
+        for module_path, output_spec in plan.output_plan.items():
+            if isinstance(output_spec, ShardingSpec):
+                mod = module.get_submodule(module_path)
+                _reshard_output(mod, output_spec)
+            else:
+                raise TypeError(
+                    f"Only `ShardingSpec` is supported as output_plan for '{module_path}'"
+                )
+    # convert the output back to data parallel for the modules appears in
+    # `return_local_tensor` of the plan, we will call `_collect_local_shard`
+    # to collect the local tensor for output of modules
+    if plan.return_local_tensor is not None:
+        for module_path in plan.return_local_tensor:
+            mod = module.get_submodule(module_path)
+            _collect_local_shard(mod)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/checkpoint/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/checkpoint/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..85915636a014640d8fff5a29db602c4a114f1b1d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/checkpoint/__init__.py
@@ -0,0 +1,19 @@
+# Keep old package for BC purposes, this file should be removed once
+# everything moves to the `torch.distributed.checkpoint` package.
+import sys
+import warnings
+
+import torch
+from torch.distributed.checkpoint import *  # noqa: F403
+
+
+with warnings.catch_warnings():
+    warnings.simplefilter("always")
+    warnings.warn(
+        "`torch.distributed._shard.checkpoint` will be deprecated, "
+        "use `torch.distributed.checkpoint` instead",
+        DeprecationWarning,
+        stacklevel=2,
+    )
+
+sys.modules["torch.distributed._shard.checkpoint"] = torch.distributed.checkpoint
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/checkpoint/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/checkpoint/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d45fcfae2f438779a87d622b4b5a9d390a6886c0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/checkpoint/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/common_op_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/common_op_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2573998712b5f0f73805d89566ef035abac52d7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/common_op_utils.py
@@ -0,0 +1,65 @@
+# mypy: allow-untyped-defs
+from typing import Optional
+
+import torch
+from torch.utils import _pytree as pytree
+
+
+def _basic_validation(op, args=(), kwargs=None):
+    """
+    Common validation across all ops go in here.
+    """
+    from torch.distributed._shard.sharded_tensor import ShardedTensor
+
+    if len(args) == 0 and (kwargs is None or len(kwargs) == 0):
+        raise ValueError(f" No input for '{op.__name__}'!")
+
+    # Validate types
+    has_distributed_tensor = False
+
+    def is_distributed_tensor(e):
+        nonlocal has_distributed_tensor
+        if isinstance(e, ShardedTensor):
+            has_distributed_tensor = True
+
+    pytree.tree_map_(is_distributed_tensor, args)
+    pytree.tree_map_(is_distributed_tensor, kwargs)
+
+    if not has_distributed_tensor:
+        raise TypeError(
+            f"torch function '{op.__name__}', with args: {args} and "
+            f"kwargs: {kwargs} are called without any distributed tensor!"
+        )
+
+    # Validate all distributed tensors use the same PG.
+    cur_pg: Optional[torch.distributed.ProcessGroup] = None
+
+    def validate_pg(e):
+        nonlocal cur_pg
+        if isinstance(e, ShardedTensor):
+            if cur_pg is not None and e._process_group is not cur_pg:
+                raise RuntimeError(
+                    "All distributed tensors should use the "
+                    "same ProcessGroup if used together in an op."
+                )
+            cur_pg = e._process_group
+
+    pytree.tree_map_(validate_pg, args)
+    pytree.tree_map_(validate_pg, kwargs)
+
+
+def _register_default_op(op, decorator):
+    @decorator(op)
+    def tensor_default_op(types, args=(), kwargs=None, pg=None):
+        """
+        Handles ``__torch_function__`` dispatch for the default tensor ops that
+        behave the same as ``torch.Tensor`` such as ``torch.Tensor.shape`` or
+        ``torch.Tensor.dtype``. We simply lower to the real op call with
+        DisableTorchFunctionSubclass context like ``torch.Tensor.__torch_function__``
+        to avoid recursions.
+        """
+        if kwargs is None:
+            kwargs = {}
+
+        with torch._C.DisableTorchFunctionSubclass():
+            return op(*args, **kwargs)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/metadata.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/metadata.py
new file mode 100644
index 0000000000000000000000000000000000000000..2611d13ef3aafec39973cc619bf76b3fff9f41b0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/metadata.py
@@ -0,0 +1,64 @@
+# mypy: allow-untyped-defs
+from dataclasses import dataclass
+from functools import reduce
+from typing import List, Optional, Union
+
+from torch.distributed.remote_device import _remote_device
+
+
+@dataclass
+class ShardMetadata:
+    """
+    Represents a shard of the overall Tensor including its
+    offsets, lengths and device placement.
+
+    Args:
+        shard_offsets(List[int]): Offsets in the original tensor indicating
+            the start offsets for this shard. Should have the same rank as
+            the original tensor.
+        shard_sizes(List[int]): Integers indicating the size of each
+            dimension for this shard. Should have the same rank as the
+            original tensor.
+        placement(:class:`torch.distributed._remote_device`):
+            Specifies the placement of this shard.
+    """
+
+    __slots__ = ["shard_offsets", "shard_sizes", "placement"]
+
+    shard_offsets: List[int]
+    shard_sizes: List[int]
+    placement: Optional[_remote_device]
+
+    def __init__(
+        self,
+        shard_offsets: List[int],
+        shard_sizes: List[int],
+        placement: Optional[Union[str, _remote_device]] = None,
+    ):
+        self.shard_offsets = shard_offsets
+        self.shard_sizes = shard_sizes
+        if isinstance(placement, str):
+            self.placement = _remote_device(placement)
+        else:
+            self.placement = placement
+        if len(self.shard_offsets) != len(self.shard_sizes):
+            raise ValueError(
+                f"shard_offsets and shard_sizes should have "
+                f"the same number of elements, found {len(self.shard_offsets)} "
+                f"and {self.shard_sizes} respectively"
+            )
+
+        for i in range(len(self.shard_offsets)):
+            if self.shard_offsets[i] < 0:
+                raise ValueError("shard_offsets should be >=0")
+            if self.shard_sizes[i] < 0:
+                raise ValueError("shard_sizes should be >= 0")
+
+    def __hash__(self):
+        def _hash_reduce(a, b):
+            return (a << 8) + hash(b)
+
+        res = reduce(_hash_reduce, self.shard_offsets, 37)
+        res = reduce(_hash_reduce, self.shard_sizes, res)
+        res = _hash_reduce(res, self.placement)
+        return res
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/op_registry_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/op_registry_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..12e0b1895e2f053e6c4a975cb6d3c0118baf50bb
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/op_registry_utils.py
@@ -0,0 +1,41 @@
+# mypy: allow-untyped-defs
+import functools
+from inspect import signature
+
+from .common_op_utils import _basic_validation
+
+
+"""
+Common utilities to register ops on ShardedTensor
+and PartialTensor.
+"""
+
+
+def _register_op(op, func, op_table):
+    """
+    Performs basic validation and registers the provided op in the given
+    op_table.
+    """
+    if len(signature(func).parameters) != 4:
+        raise TypeError(
+            f"Custom sharded op function expects signature: "
+            f"(types, args, kwargs, process_group), but received "
+            f"signature: {signature(func)}"
+        )
+
+    op_table[op] = func
+
+
+def _decorator_func(wrapped_func, op, op_table):
+    """
+    Decorator function to register the given ``op`` in the provided
+    ``op_table``
+    """
+
+    @functools.wraps(wrapped_func)
+    def wrapper(types, args, kwargs, process_group):
+        _basic_validation(op, args, kwargs)
+        return wrapped_func(types, args, kwargs, process_group)
+
+    _register_op(op, wrapper, op_table)
+    return wrapper
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_optim/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_optim/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1508208c169070bf12fb866e27e3acaab9a2eec
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_optim/__init__.py
@@ -0,0 +1,52 @@
+from typing import Iterator, Tuple, Union
+
+import torch.nn as nn
+from torch.distributed._shard.sharded_tensor import ShardedTensor
+
+from .api import ShardedOptimizer
+
+
+def named_params_with_sharded_tensor(
+    module: nn.Module,
+    prefix: str = "",
+    recurse: bool = True,
+) -> Iterator[Tuple[str, Union[nn.Parameter, ShardedTensor]]]:
+    r"""Returns an iterator over module parameters (together with the
+    ShardedTensor parameters), yielding both the name of the parameter
+    as well as the parameter itself. This is typically passed to a
+    :class:torch.distributed._shard.sharded_optim.ShardedOptimizer
+
+    Args:
+        prefix (str): prefix to prepend to all parameter names.
+        recurse (bool): if True, then yields parameters of this module
+            and all submodules. Otherwise, yields only parameters that
+            are direct members of this module.
+
+    Yields:
+        (str, Union[Tensor, ShardedTensor]): Tuple containing
+            the name and parameter (or ShardedTensor parameter)
+
+    Example::
+
+        >>> # xdoctest: +SKIP
+        >>> model = torch.nn.Linear(*linear_size)
+        >>> shard_parameter(model, "weight", spec)
+        >>> for name, param in named_params_with_sharded_tensor(model):
+        >>>    if name in ['weight']:
+        >>>        print(param.size())
+
+    """
+    modules = module.named_modules(prefix=prefix) if recurse else [(prefix, module)]
+
+    memo = set()
+    for mod_prefix, mod in modules:
+        # find all sharded tensor params
+        for name, val in vars(mod).items():
+            if isinstance(val, ShardedTensor) and val not in memo:
+                memo.add(val)
+                name = mod_prefix + ("." if mod_prefix else "") + name
+                yield name, val
+
+    # find all nn.Parameters
+    for name, val in module.named_parameters():
+        yield name, val
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_optim/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_optim/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0b705799c8f516754db9bef2bcec7286da42bd9f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_optim/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_optim/__pycache__/api.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_optim/__pycache__/api.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ca4bd00cf44a78dd5b64a795e2518446cf5e53c4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_optim/__pycache__/api.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_optim/api.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_optim/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c7c632f22b59abee746e7b4cb6d0771d91e3605
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_optim/api.py
@@ -0,0 +1,100 @@
+# mypy: allow-untyped-defs
+from typing import Any, Dict, List, Mapping, Union
+
+import torch.optim as optim
+from torch import Tensor
+from torch.distributed._shard.sharded_tensor import ShardedTensor
+
+
+class ShardedOptimizer(optim.Optimizer):
+    def __init__(
+        self,
+        named_params: Mapping[str, Union[Tensor, ShardedTensor]],
+        optimizer_class,
+        *optimizer_args,
+        **optimizer_kwargs,
+    ):
+        """
+        ShardedOptimizer collects all tensors and local shard tensors of
+        ShardedTensor, then use these tensors as ``params`` for optimizers
+
+        Args:
+            named_params (Dict[str, Union[Tensor, ShardedTensor]]) : a Dict
+                of parameters, where key is the parameter key, value is either
+                Tensor or ShardedTensor parameter.
+            optimizer_class (torch.optim.Optimizer): the Optimizer to use
+                locally, i.e. torch.optim.SGD, torch.optim.Adagrad, etc.
+            *optimizer_args: the arguments to initialize the optimizer.
+            **optimizer_kwargs: the key-word arguments to initialize the optimizer.
+
+        """
+        tensors: List[Tensor] = []
+        for value in named_params.values():
+            if isinstance(value, ShardedTensor):
+                for local_shard in value.local_shards():
+                    tensors.append(local_shard.tensor)
+            else:
+                tensors.append(value)
+
+        self.named_params = named_params
+        self._optim = optimizer_class(tensors, *optimizer_args, **optimizer_kwargs)
+        self.param_groups = self._optim.param_groups
+        self.state = self._optim.state
+
+    def zero_grad(self, set_to_none: bool = True):  # type: ignore[override]
+        r"""Resets the gradients of all optimized :class:`torch.Tensor` s.
+
+        Args:
+            set_to_none (bool): instead of setting to zero, set the grads to None.
+                This will in general have lower memory footprint, and can modestly improve performance.
+                However, it changes certain behaviors. For example:
+                1. When the user tries to access a gradient and perform manual ops on it,
+                a None attribute or a Tensor full of 0s will behave differently.
+                2. If the user requests ``zero_grad(set_to_none=True)`` followed by a backward pass, ``.grad``\ s
+                are guaranteed to be None for params that did not receive a gradient.
+                3. ``torch.optim`` optimizers have a different behavior if the gradient is 0 or None
+                (in one case it does the step with a gradient of 0 and in the other it skips
+                the step altogether).
+        """
+        self._optim.zero_grad(set_to_none)
+
+    def step(self, closure=None):
+        r"""Performs a single optimization step (parameter update).
+
+        Args:
+            closure (Callable): A closure that reevaluates the model and
+                returns the loss. Optional for most optimizers.
+
+        .. note::
+            Unless otherwise specified, this function should not modify the
+            ``.grad`` field of the parameters.
+        """
+        self._optim.step(closure)
+
+    def state_dict(self) -> Dict[str, Any]:
+        """
+        Returned state and param_groups will contain parameter keys
+        instead of parameter indices like torch.optim.Optimizer.
+        This allows for advanced functionality like optimizer re-sharding to be implemented.
+        """
+        # TODO: implement state_dict
+        raise NotImplementedError("ShardedOptimizer state_dict not implemented yet!")
+
+    def load_state_dict(self, state_dict: Mapping[str, Any]):
+        r"""Loads the ShardedOptimizer state.
+
+        Args:
+            state_dict (dict): ShardedOptimizer state. Should be an object returned
+                from a call to :meth:`state_dict`.
+        """
+        # TODO: implement load_state_dict
+        raise NotImplementedError(
+            "ShardedOptimizer load_state_dict not implemented yet!"
+        )
+
+    def add_param_group(self, param_group: Any):
+        r"""Add a new param group"""
+        # TODO: implement add_param_group
+        raise NotImplementedError(
+            "ShardedOptimizer add_param_group not implemented yet!"
+        )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..db7090820ea0a960446ef80fabd50085013e5dc4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__init__.py
@@ -0,0 +1,490 @@
+# mypy: allow-untyped-defs
+import functools
+from typing import List, TYPE_CHECKING
+
+import torch
+from torch.distributed._shard.op_registry_utils import _decorator_func
+
+from .api import (
+    _CUSTOM_SHARDED_OPS,
+    _SHARDED_OPS,
+    Shard,
+    ShardedTensor,
+    ShardedTensorBase,
+    ShardedTensorMetadata,
+    TensorProperties,
+)
+from .metadata import ShardMetadata  # noqa: F401
+
+
+if TYPE_CHECKING:
+    from torch.distributed._shard.sharding_spec import ShardingSpec
+else:
+    ShardingSpec = "ShardingSpec"
+
+
+def empty(
+    sharding_spec: ShardingSpec,
+    *size,
+    dtype=None,
+    layout=torch.strided,
+    requires_grad=False,
+    pin_memory=False,
+    memory_format=torch.contiguous_format,
+    process_group=None,
+    init_rrefs=False,
+) -> ShardedTensor:
+    """
+    Returns a :class:`ShardedTensor` filled with uninitialized data.
+        Needs to be called on all ranks in an SPMD fashion.
+
+    Args:
+        sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification
+            describing how to shard the Tensor.
+        size (int...): a sequence of integers defining the shape of the output
+            tensor. Can be a variable number of arguments or a collection like a list or tuple.
+
+    Keyword args:
+        dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
+            Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).
+        layout (:class:`torch.layout`, optional): the desired layout of returned Tensor.
+            Default: ``torch.strided``.
+        requires_grad (bool, optional): If autograd should record operations on the
+            returned tensor. Default: ``False``.
+        pin_memory (bool, optional): If set, returned tensor would be allocated in
+            the pinned memory. Works only for CPU tensors. Default: ``False``.
+        memory_format (:class:`torch.memory_format`, optional): the desired memory format of
+            returned Tensor. Default: ``torch.contiguous_format``.
+        process_group (ProcessGroup, optional): The process group to work on. If None,
+            the default process group will be used.
+        init_rrefs (bool, optional): Whether or not to initialize
+            :class:`torch.distributed.rpc.RRef`s pointing to remote shards.
+            Need to initialize the RPC Framework if specified as ``True``.
+            Default: ``False``.
+
+    Returns:
+        A :class:`ShardedTensor` object on each rank
+    """
+    return ShardedTensor(
+        sharding_spec,
+        *size,
+        dtype=dtype,
+        layout=layout,
+        requires_grad=requires_grad,
+        pin_memory=pin_memory,
+        memory_format=memory_format,
+        process_group=process_group,
+        init_rrefs=init_rrefs,
+    )
+
+
+def ones(
+    sharding_spec: ShardingSpec,
+    *size,
+    dtype=None,
+    layout=torch.strided,
+    requires_grad=False,
+    pin_memory=False,
+    memory_format=torch.contiguous_format,
+    process_group=None,
+    init_rrefs=False,
+) -> ShardedTensor:
+    """
+    Returns a :class:`ShardedTensor` with the scalar value 1.
+        Needs to be called on all ranks in an SPMD fashion.
+
+    Args:
+        sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification
+            describing how to shard the Tensor.
+        size (int...): a sequence of integers defining the shape of the output
+            tensor. Can be a variable number of arguments or a collection like a list or tuple.
+
+    Keyword args:
+        dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
+            Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).
+        layout (:class:`torch.layout`, optional): the desired layout of returned Tensor.
+            Default: ``torch.strided``.
+        requires_grad (bool, optional): If autograd should record operations on the
+            returned tensor. Default: ``False``.
+        pin_memory (bool, optional): If set, returned tensor would be allocated in
+            the pinned memory. Works only for CPU tensors. Default: ``False``.
+        process_group (ProcessGroup, optional): The process group to work on. If None,
+            the default process group will be used.
+        init_rrefs (bool, optional): Whether or not to initialize
+            :class:`torch.distributed.rpc.RRef`s pointing to remote shards.
+            Need to initialize the RPC Framework if specified as ``True``.
+            Default: ``False``.
+
+    Returns:
+        A :class:`ShardedTensor` object on each rank
+    """
+    return full(
+        sharding_spec,
+        size,
+        fill_value=1,
+        dtype=dtype,
+        layout=layout,
+        requires_grad=requires_grad,
+        pin_memory=pin_memory,
+        memory_format=memory_format,
+        process_group=process_group,
+        init_rrefs=init_rrefs,
+    )
+
+
+def zeros(
+    sharding_spec: ShardingSpec,
+    *size,
+    dtype=None,
+    layout=torch.strided,
+    requires_grad=False,
+    pin_memory=False,
+    memory_format=torch.contiguous_format,
+    process_group=None,
+    init_rrefs=False,
+) -> ShardedTensor:
+    """
+    Returns a :class:`ShardedTensor` filled with the scalar value 0.
+        Needs to be called on all ranks in an SPMD fashion.
+
+    Args:
+        sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification
+            describing how to shard the Tensor.
+        size (int...): a sequence of integers defining the shape of the output
+            tensor. Can be a variable number of arguments or a collection like a list or tuple.
+
+    Keyword args:
+        dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
+            Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).
+        layout (:class:`torch.layout`, optional): the desired layout of returned Tensor.
+            Default: ``torch.strided``.
+        requires_grad (bool, optional): If autograd should record operations on the
+            returned tensor. Default: ``False``.
+        pin_memory (bool, optional): If set, returned tensor would be allocated in
+            the pinned memory. Works only for CPU tensors. Default: ``False``.
+        process_group (ProcessGroup, optional): The process group to work on. If None,
+            the default process group will be used.
+        init_rrefs (bool, optional): Whether or not to initialize
+            :class:`torch.distributed.rpc.RRef`s pointing to remote shards.
+            Need to initialize the RPC Framework if specified as ``True``.
+            Default: ``False``.
+
+    Returns:
+        A :class:`ShardedTensor` object on each rank
+    """
+    return full(
+        sharding_spec,
+        size,
+        fill_value=0,
+        dtype=dtype,
+        layout=layout,
+        requires_grad=requires_grad,
+        pin_memory=pin_memory,
+        memory_format=memory_format,
+        process_group=process_group,
+        init_rrefs=init_rrefs,
+    )
+
+
+def full(
+    sharding_spec: ShardingSpec,
+    size,
+    fill_value,
+    *,
+    dtype=None,
+    layout=torch.strided,
+    requires_grad=False,
+    pin_memory=False,
+    memory_format=torch.contiguous_format,
+    process_group=None,
+    init_rrefs=False,
+) -> ShardedTensor:
+    """
+    Creates a :class:`ShardedTensor` filled with fill_value. The tensor's dtype
+        is inferred from fill_value. If dtype is specified, it will override the
+        inferred type from fill_value. Needs to be called on all ranks in an SPMD fashion.
+    Args:
+        sharding_spec (:class:`torch.distributed._sharding_spec.ShardingSpec`): The specification
+            describing how to shard the Tensor.
+        size (int...):  a list, tuple, or `torch.Size` of integers defining the shape of the
+            output tensor.
+        fill_value (Scalar) - the value to fill the output tensor with.
+    Keyword args:
+        dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
+            Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).
+        layout (:class:`torch.layout`, optional): the desired layout of returned Tensor.
+            Default: ``torch.strided``.
+        requires_grad (bool, optional): If autograd should record operations on the
+            returned tensor. Default: ``False``.
+        pin_memory (bool, optional): If set, returned tensor would be allocated in
+            the pinned memory. Works only for CPU tensors. Default: ``False``.
+        process_group (ProcessGroup, optional): The process group to work on. If None,
+            the default process group will be used.
+        init_rrefs (bool, optional): Whether or not to initialize
+            :class:`torch.distributed.rpc.RRef`s pointing to remote shards.
+            Need to initialize the RPC Framework if specified as ``True``.
+            Default: ``False``.
+    Returns:
+        A :class:`ShardedTensor` object on each rank
+    """
+    sharded_tensor = ShardedTensor(
+        sharding_spec,
+        *size,
+        dtype=dtype,
+        layout=layout,
+        requires_grad=requires_grad,
+        pin_memory=pin_memory,
+        memory_format=memory_format,
+        process_group=process_group,
+        init_rrefs=init_rrefs,
+    )
+    torch.nn.init.constant_(sharded_tensor, fill_value)  # type: ignore[arg-type]
+    return sharded_tensor
+
+
+def rand(
+    sharding_spec: ShardingSpec,
+    *size,
+    dtype=None,
+    layout=torch.strided,
+    requires_grad=False,
+    pin_memory=False,
+    memory_format=torch.contiguous_format,
+    process_group=None,
+    init_rrefs=False,
+) -> ShardedTensor:
+    """
+    Creates a :class:`ShardedTensor` filled with random numbers from a uniform distribution
+        on the interval :math:`[0, 1)`. The shape of the tensor is defined by the
+        variable argument `size`. Needs to be called on all ranks in an SPMD fashion.
+
+    Args:
+        sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification
+            describing how to shard the Tensor.
+        size (int...):  a list, tuple, or `torch.Size` of integers defining the shape of the
+            output tensor.
+
+    Keyword args:
+        dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
+            Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).
+        layout (:class:`torch.layout`, optional): the desired layout of returned Tensor.
+            Default: ``torch.strided``.
+        requires_grad (bool, optional): If autograd should record operations on the
+            returned tensor. Default: ``False``.
+        pin_memory (bool, optional): If set, returned tensor would be allocated in
+            the pinned memory. Works only for CPU tensors. Default: ``False``.
+        process_group (ProcessGroup, optional): The process group to work on. If None,
+            the default process group will be used.
+        init_rrefs (bool, optional): Whether or not to initialize
+            :class:`torch.distributed.rpc.RRef`s pointing to remote shards.
+            Need to initialize the RPC Framework if specified as ``True``.
+            Default: ``False``.
+
+    Returns:
+        A :class:`ShardedTensor` object on each rank
+    """
+    sharded_tensor = ShardedTensor(
+        sharding_spec,
+        *size,
+        dtype=dtype,
+        layout=layout,
+        requires_grad=requires_grad,
+        pin_memory=pin_memory,
+        memory_format=memory_format,
+        process_group=process_group,
+        init_rrefs=init_rrefs,
+    )
+    torch.nn.init.uniform_(sharded_tensor, 0, 1)  # type: ignore[arg-type]
+    return sharded_tensor
+
+
+def randn(
+    sharding_spec: ShardingSpec,
+    *size,
+    dtype=None,
+    layout=torch.strided,
+    requires_grad=False,
+    pin_memory=False,
+    memory_format=torch.contiguous_format,
+    process_group=None,
+    init_rrefs=False,
+) -> ShardedTensor:
+    """
+    Creates a :class:`ShardedTensor` filled with random numbers from a uniform distribution
+        with mean `0` and variance `1` (also called standard normal distribution). The shape
+        of the tensor is defined by the variable argument `size`. Needs to be called on all ranks
+        in an SPMD fashion.
+
+    Args:
+        sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification
+            describing how to shard the Tensor.
+        size (int...):  a list, tuple, or `torch.Size` of integers defining the shape of the
+            output tensor.
+
+    Keyword args:
+        dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
+            Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).
+        layout (:class:`torch.layout`, optional): the desired layout of returned Tensor.
+            Default: ``torch.strided``.
+        requires_grad (bool, optional): If autograd should record operations on the
+            returned tensor. Default: ``False``.
+        pin_memory (bool, optional): If set, returned tensor would be allocated in
+            the pinned memory. Works only for CPU tensors. Default: ``False``.
+        process_group (ProcessGroup, optional): The process group to work on. If None,
+            the default process group will be used.
+        init_rrefs (bool, optional): Whether or not to initialize
+            :class:`torch.distributed.rpc.RRef`s pointing to remote shards.
+            Need to initialize the RPC Framework if specified as ``True``.
+            Default: ``False``.
+
+    Returns:
+        A :class:`ShardedTensor` object on each rank
+    """
+    sharded_tensor = ShardedTensor(
+        sharding_spec,
+        *size,
+        dtype=dtype,
+        layout=layout,
+        requires_grad=requires_grad,
+        pin_memory=pin_memory,
+        memory_format=memory_format,
+        process_group=process_group,
+        init_rrefs=init_rrefs,
+    )
+    torch.nn.init.normal_(sharded_tensor, 0, 1)  # type: ignore[arg-type]
+    return sharded_tensor
+
+
+def init_from_local_shards(
+    local_shards: List[Shard], *global_size, process_group=None, init_rrefs=False
+) -> ShardedTensor:
+    """
+    Creates an :class:`ShardedTensor` from local shards and the global metadata.
+    Needs to be called on all ranks in an SPMD fashion.
+
+    Args:
+        local_shards (List[:class `torch.distributed._shard.sharded_tensor.Shard`]): A list
+            of shards that represent the local shards on this rank.
+        global_size (int...):  a list, tuple, or `torch.Size` of integers defining the
+            shape of the overall sharded tensor.
+
+    Keyword args:
+        process_group (ProcessGroup, optional): The process group to work on. If None,
+            the default process group will be used.
+        init_rrefs (bool, optional): Whether or not to initialize
+            :class:`torch.distributed.rpc.RRef`s pointing to remote shards.
+            Need to initialize the RPC Framework if specified as ``True``.
+            Default: ``False``.
+
+    Returns:
+        A :class:`ShardedTensor` object handle on this rank
+
+
+    Examples:
+        Suppose we want construct a sharded tensor on two ranks, global size = (10, 5),
+        each shard have a (5, 5) local tensor, we can do it like below:
+
+        on rank 0:
+        >>> # xdoctest: +SKIP("not distributed")
+        >>> local_shard_metadata = ShardMetadata(
+        >>>     shard_offsets=[0, 0],
+        >>>     shard_lengths=[5, 5],
+        >>>     placement="rank:0/cuda:0"
+        >>> )
+        >>> local_shards = [Shard(torch.randn(5, 5), local_shard_metadata)]
+        >>> sharded_tensor = init_from_local_shards(local_shards, [10, 5])
+
+        on rank 1:
+        >>> # xdoctest: +SKIP("not distributed")
+        >>> local_shard_metadata = ShardMetadata(
+        >>>     shard_offsets=[5, 0],
+        >>>     shard_lengths=[5, 5],
+        >>>     placement="rank:1/cuda:1"
+        >>> )
+        >>> local_shards = [Shard(torch.randn(5, 5), local_shard_metadata)]
+        >>> sharded_tensor = init_from_local_shards(local_shards, [10, 5])
+    """
+    return ShardedTensor._init_from_local_shards(
+        local_shards, *global_size, process_group=process_group, init_rrefs=init_rrefs
+    )
+
+
+def state_dict_hook(module, destination, prefix, local_metadata):
+    """
+    Hook to add ShardedTensor to Module's ``state_dict``. Needs to be
+    registered to the Module using
+    :meth:`torch.nn.Module._register_state_dict_hook`.
+    """
+    for submodule_name, submodule in module.named_modules():
+        for attr_name, attr in submodule.__dict__.items():
+            if isinstance(attr, ShardedTensor):
+                mod_prefix = prefix + submodule_name
+                key = mod_prefix + ("." if mod_prefix else "") + attr_name
+                destination[key] = attr
+
+
+def pre_load_state_dict_hook(
+    module,
+    state_dict,
+    prefix,
+    local_metadata,
+    strict,
+    missing_keys,
+    unexpected_keys,
+    error_msgs,
+):
+    """
+    Pre-load state dict hook to add ShardedTensor to the module.
+    """
+    for submodule_name, submodule in module.named_modules():
+        for attr_name in submodule.__dict__.keys():
+            mod_prefix = prefix + submodule_name
+            key = mod_prefix + ("." if mod_prefix else "") + attr_name
+            if key in state_dict:
+                if isinstance(state_dict[key], ShardedTensor):
+                    setattr(submodule, attr_name, state_dict[key])
+
+
+def custom_sharded_op_impl(func):
+    """
+    Provides a way for users to write their own custom sharded operator. This
+    can be used to override existing ShardedTensor operators or write a new
+    one not supported by ShardedTensor. If the operator in question is covered
+    by ``__torch_function__`` dispatch and has a ShardedTensor as any of its
+    parameters, the function provided will be invoked for that operator.
+
+    Example::
+        >>> # xdoctest: +SKIP
+        >>> @custom_sharded_op_impl(torch.nn.functional.linear)
+        >>> def my_custom_sharded_linear(types, args, kwargs, process_group):
+        >>>     ...
+        >>> # xdoctest: +SKIP("Undefined variables")
+        >>> input = torch.rand(10, 32)
+        >>> weight = sharded_tensor.rand(32, 16)
+        >>> bias = torch.rand(16)
+        >>> # This will call 'my_custom_sharded_linear'
+        >>> torch.nn.functional.linear(input, weight, bias)
+
+    The types, args and kwargs parameters are the same parameters that are
+    passed to ``__torch_function__`` dispatch API
+    (https://pytorch.org/docs/stable/notes/extending.html#extending-torch).
+    There is an additional ``process_group`` parameter which is the
+    process_group used for the ShardedTensor and can be used by
+    implementations for communications within a sharded implementation.
+
+    Args:
+        func(Callable): Torch function for which we want to provide a sharded
+            implementation (ex: torch.nn.functional.linear)
+    """
+    return functools.partial(_decorator_func, op=func, op_table=_CUSTOM_SHARDED_OPS)
+
+
+def _sharded_op_impl(func):
+    """
+    Decorator to register a default sharded op.
+    """
+    return functools.partial(_decorator_func, op=func, op_table=_SHARDED_OPS)
+
+
+# Import all builtin sharded ops
+from ._ops import *  # noqa: F403
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..42929b3ebea07377edf1a15dc5316eec99ecdaae
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__pycache__/api.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__pycache__/api.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4544c636cfd5f456e6d23f585b43eadc2162af1f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__pycache__/api.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__pycache__/logger.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__pycache__/logger.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f2e73ba1ec66fce2c3ba4117aa4d1bfe21f50322
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__pycache__/logger.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__pycache__/logging_handlers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__pycache__/logging_handlers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9d75d0b6e6120bdb1c76dd723e8aa07e8d17fde6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__pycache__/logging_handlers.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__pycache__/metadata.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__pycache__/metadata.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..16b462a7955b8c74a2bc4706b0be222e4e3c709b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__pycache__/metadata.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__pycache__/reshard.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__pycache__/reshard.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..671e3f77662641987fc0bcc3db64638803274568
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__pycache__/reshard.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__pycache__/shard.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__pycache__/shard.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a6d10aed85c6fd75cd830d0091d5681106938dfb
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__pycache__/shard.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__pycache__/utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__pycache__/utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..84b6e9bcf5319139a48b3a3c45b73a562665cd18
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/__pycache__/utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..be6d01fc8e54ee214fafa847c9261db375d8b87e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/__init__.py
@@ -0,0 +1,13 @@
+import torch.distributed._shard.sharded_tensor._ops.misc_ops
+import torch.distributed._shard.sharded_tensor._ops.tensor_ops
+
+# Import all ChunkShardingSpec ops
+from torch.distributed._shard.sharding_spec.chunk_sharding_spec_ops.embedding import (
+    sharded_embedding,
+)
+from torch.distributed._shard.sharding_spec.chunk_sharding_spec_ops.embedding_bag import (
+    sharded_embedding_bag,
+)
+
+from .binary_cmp import allclose, equal
+from .init import constant_, kaiming_uniform_, normal_, uniform_
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f0a9fa5307057c2721fad2b396dc8cbaa19f9c03
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/__pycache__/_common.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/__pycache__/_common.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..44a0e9512f8043a5d09b430fa5141d160f02f7ff
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/__pycache__/_common.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/__pycache__/binary_cmp.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/__pycache__/binary_cmp.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bd335357ef633b49208b99380b03ec5ba0087ab0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/__pycache__/binary_cmp.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/__pycache__/init.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/__pycache__/init.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3de1febe4638ec676467dbb0955f1f634349219c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/__pycache__/init.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/__pycache__/misc_ops.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/__pycache__/misc_ops.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..899c917b3fdcac2cf77fbd45c8a5a2d5a347e381
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/__pycache__/misc_ops.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/__pycache__/tensor_ops.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/__pycache__/tensor_ops.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..29a68a8d99c0e5458e64429cc909f5a160d99a90
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/__pycache__/tensor_ops.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/_common.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/_common.py
new file mode 100644
index 0000000000000000000000000000000000000000..502e0ac9a8552dae35c3fa45f52d73d1c2e82067
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/_common.py
@@ -0,0 +1,113 @@
+# mypy: allow-untyped-defs
+import functools
+
+from torch.distributed._shard.common_op_utils import _basic_validation
+from torch.distributed._shard.sharded_tensor import (
+    _sharded_op_impl,
+    Shard,
+    ShardedTensor,
+)
+
+
+def _sharded_op_common(op, early_stop_func, extra_check):
+    """
+    Inject sharded tensor op registration with common logics executed before
+    different behaviors are done on either local shards or a local tensor.
+
+    Example::
+        >>> # xdoctest: +SKIP("Undefined variables")
+        >>> op = torch.transpose
+        >>> @_sharded_op_impl(op)
+        >>> @_sharded_op_common(op, early_stop_func, extra_check)
+        >>> def sharded_tensor_op(types, args, kwargs, process_group):
+        >>>   ...
+        >>>
+        >>> st = sharded_tensor.rand(32, 16)
+        >>> st.transpose(1, 2)
+        >>> # This will call '_sharded_op_common'
+
+    Args:
+        op: The op to be registered and applied to all shards of the st.
+        early_stop_func (Callable, optional): the func for early stop.
+            Default: if ``None``, no early stop.
+        extra_check (Callable, optional): the func for extra condition check.
+            Default: if ``None``, no extra check.
+
+    Return:
+        func (Callable): Torch function for which we want to provide a sharded
+            implementation (ex: torch.transpose)
+    """
+
+    def decorator_sharded_func(wrapped_func):
+        @functools.wraps(wrapped_func)
+        def wrapper(types, args=(), kwargs=None, pg=None):
+            _basic_validation(op, args, kwargs)
+
+            st = args[0]
+            if kwargs is None:
+                kwargs = {}
+            if extra_check:
+                extra_check(*args, **kwargs)
+            if early_stop_func:
+                early_stop = early_stop_func(*args, **kwargs)
+                if early_stop:
+                    return st
+            return wrapped_func(types, args, kwargs, pg)
+
+        return wrapper
+
+    return decorator_sharded_func
+
+
+def _register_sharded_op_on_local_shards(
+    op, early_stop_func=None, extra_check=None, customized_func=None
+):
+    """
+    Handles ``__torch_function__`` dispatch for ops which are performed on
+    each shard of the sharded tensor such as elementwise op like
+    ``torch.nn.functional.gelu`` or ``torch.nn.functional.relu``.
+
+    For more complicated ops, a customized func can be used to generate
+    the new shards and sharded tensor size.
+
+    This function expects that the original ShardingSpec for the ShardedTensor
+    is preserved irrespective of whether or not a customized function is used.
+
+    Args:
+        op: The op to be registered and applied to all shards of the st.
+        early_stop_func (Callable, optional): the func for early stop.
+            Default: if ``None``, no early stop.
+        extra_check (Callable, optional): the func for extra condition check.
+            Default: if ``None``, no extra check.
+        customized_func (Callable, optional): the func for customized logic
+            to generate new shards and sharded tensor size.
+            Default: if ``None``, we simply lower to the real op call with
+                all local shards of the st.
+
+    Return:
+        func (Callable): registered implementation for sharded op for
+        ``__torch_function__`` dispatch.
+    """
+
+    @_sharded_op_impl(op)
+    @_sharded_op_common(op, early_stop_func, extra_check)
+    def sharded_tensor_op_on_local_shards(types, args=(), kwargs=None, pg=None):
+        st = args[0]
+        st_metadata = st.metadata()
+        local_shards = st.local_shards()
+        local_shards_new = []
+        if customized_func:
+            local_shards_new, st_metadata = customized_func(args, kwargs, pg)
+        else:
+            for local_shard in local_shards:
+                args = (local_shard.tensor, *args[1:])
+                local_shards_new.append(
+                    Shard(op(*args, **kwargs), local_shard.metadata)
+                )
+        return ShardedTensor._init_from_local_shards_and_global_metadata(
+            local_shards_new,
+            st_metadata,
+            process_group=pg,
+            init_rrefs=st._init_rrefs,
+            sharding_spec=st.sharding_spec(),
+        )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/binary_cmp.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/binary_cmp.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8db8b6ebe96fda7c184bb7746fc5abedfefdad3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/binary_cmp.py
@@ -0,0 +1,79 @@
+# mypy: allow-untyped-defs
+import torch
+import torch.distributed as dist
+import torch.distributed.distributed_c10d as distributed_c10d
+from torch.distributed._shard.sharded_tensor import _sharded_op_impl, ShardedTensor
+
+
+def _communicate_result(result, pg):
+    # Gather results from all ranks.
+    if result:
+        result_tensor = torch.ones(1, device=torch.device(torch.cuda.current_device()))
+    else:
+        result_tensor = torch.zeros(1, device=torch.device(torch.cuda.current_device()))
+
+    dist.all_reduce(result_tensor, group=pg)
+
+    expected_result = torch.ones(
+        1, device=torch.device(torch.cuda.current_device())
+    ) * dist.get_world_size(pg)
+
+    return torch.equal(result_tensor, expected_result)
+
+
+def binary_cmp(cmp_fun, types, args, kwargs=None, process_group=None):
+    if len(args) != 2:
+        raise ValueError(f"Expected two arguments for torch.{cmp_fun.__name__}")
+
+    result = True
+    st1 = args[0]
+    st2 = args[1]
+    if not (isinstance(st1, ShardedTensor) and isinstance(st2, ShardedTensor)):
+        raise TypeError(
+            f"Both arguments to torch.{cmp_fun.__name__} need to be of type ShardedTensor"
+        )
+
+    # Verify same PG
+    if st1._process_group != st2._process_group:
+        return False
+
+    if distributed_c10d._rank_not_in_group(
+        st1._process_group
+    ) or distributed_c10d._rank_not_in_group(st2._process_group):
+        return distributed_c10d._rank_not_in_group(
+            st1._process_group
+        ) == distributed_c10d._rank_not_in_group(st2._process_group)
+
+    # Verify metadata
+    if st1.metadata() != st2.metadata():
+        return _communicate_result(False, st1._process_group)
+
+    # Verify number of local shards
+    st1_local_shards = st1.local_shards()
+    st2_local_shards = st2.local_shards()
+    if len(st1_local_shards) != len(st2_local_shards):
+        return _communicate_result(False, st1._process_group)
+
+    # kwargs must be dict-like
+    if kwargs is None:
+        kwargs = {}
+    # Verify each local shard
+    for idx in range(len(st1_local_shards)):
+        if st1_local_shards[idx].metadata != st2_local_shards[idx].metadata:
+            return _communicate_result(False, st1._process_group)
+        if not cmp_fun(
+            st1_local_shards[idx].tensor, st2_local_shards[idx].tensor, **kwargs
+        ):
+            return _communicate_result(False, st1._process_group)
+
+    return _communicate_result(True, st1._process_group)
+
+
+@_sharded_op_impl(torch.equal)
+def equal(types, args, kwargs, process_group):
+    return binary_cmp(torch.equal, types, args, kwargs, process_group)
+
+
+@_sharded_op_impl(torch.allclose)
+def allclose(types, args, kwargs, process_group):
+    return binary_cmp(torch.allclose, types, args, kwargs, process_group)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/init.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/init.py
new file mode 100644
index 0000000000000000000000000000000000000000..71a9c20b45352cd1526ab00f3b4463bdaefe982a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/init.py
@@ -0,0 +1,151 @@
+# mypy: allow-untyped-defs
+import torch
+import torch.distributed._shard.sharded_tensor as sharded_tensor
+from torch.distributed._shard.sharded_tensor import _sharded_op_impl
+
+
+def validate_param(param, param_name):
+    if param is None:
+        raise ValueError(f"param: {param_name} shouldn't be None!")
+
+
+@_sharded_op_impl(torch.nn.init.uniform_)
+def uniform_(types, args=(), kwargs=None, pg=None):
+    r"""
+    Fills the Tensor in tensor.local_shards with values drawn from the uniform
+    distribution :math:`\mathcal{U}(a, b)`.
+    Args:
+        tensor: tensor sharded across devices
+        a: the lower bound of the uniform distribution
+        b: the upper bound of the uniform distribution
+    """
+    validate_param(kwargs, "kwargs")
+    sharded_tensor = kwargs["tensor"]
+    validate_param(sharded_tensor, "tensor")
+    a = kwargs["a"]
+    validate_param(a, "a")
+    b = kwargs["b"]
+    validate_param(b, "b")
+
+    for shard in sharded_tensor.local_shards():
+        torch.nn.init.uniform_(shard.tensor, a=a, b=b)
+    return sharded_tensor
+
+
+@_sharded_op_impl(torch.nn.init.normal_)
+def normal_(types, args=(), kwargs=None, pg=None):
+    r"""
+    Fills the Tensors in tensor.local_shards with values drawn from the normal
+    distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)`.
+    Args:
+        tensor: tensor sharded across devices
+        mean: the mean of the normal distribution
+        std: the standard deviation of the normal distribution
+    """
+    validate_param(kwargs, "kwargs")
+    sharded_tensor = kwargs["tensor"]
+    validate_param(sharded_tensor, "tensor")
+    mean = kwargs["mean"]
+    validate_param(mean, "mean")
+    std = kwargs["std"]
+    validate_param(std, "std")
+
+    for shard in sharded_tensor.local_shards():
+        torch.nn.init.normal_(shard.tensor, mean=mean, std=std)
+    return sharded_tensor
+
+
+@_sharded_op_impl(torch.nn.init.kaiming_uniform_)
+def kaiming_uniform_(types, args=(), kwargs=None, pg=None):
+    r"""
+    Fills the Tensors in tensor.local_shards with values according to the method
+    described in `Delving deep into rectifiers: Surpassing human-level
+    performance on ImageNet classification` - He, K. et al. (2015), using a
+    uniform distribution. The resulting tensor will have values sampled from
+    :math:`\mathcal{U}(-\text{bound}, \text{bound})` where
+    .. math::
+        \text{bound} = \text{gain} \times \sqrt{\frac{3}{\text{fan\_mode}}}
+    Also known as He initialization.
+    Args:
+        tensor: tensor sharded across devices
+        a: the negative slope of the rectifier used after this layer (only
+            used with ``'leaky_relu'``)
+        mode: either ``'fan_in'`` (default) or ``'fan_out'``. Choosing ``'fan_in'``
+            preserves the magnitude of the variance of the weights in the
+            forward pass. Choosing ``'fan_out'`` preserves the magnitudes in the
+            backwards pass.
+        nonlinearity: the non-linear function (`nn.functional` name),
+            recommended to use only with ``'relu'`` or ``'leaky_relu'`` (default).
+    """
+    validate_param(kwargs, "kwargs")
+    sharded_tensor = kwargs["tensor"]
+    validate_param(sharded_tensor, "tensor")
+    a = kwargs["a"]
+    validate_param(a, "a")
+    mode = kwargs["mode"]
+    validate_param(mode, "mode")
+    nonlinearity = kwargs["nonlinearity"]
+    validate_param(nonlinearity, "nonlinearity")
+
+    for shard in sharded_tensor.local_shards():
+        torch.nn.init.kaiming_uniform_(
+            shard.tensor, a=a, mode=mode, nonlinearity=nonlinearity
+        )
+    return sharded_tensor
+
+
+@_sharded_op_impl(torch.nn.init.constant_)
+def constant_(types, args=(), kwargs=None, pg=None):
+    r"""
+    Fills the input ShardedTensor with the value \text{val}val.
+    Args:
+        tensor: tensor sharded across devices
+        val: the value to fill the tensor with
+    """
+    validate_param(kwargs, "kwargs")
+    sharded_tensor = kwargs["tensor"]
+    validate_param(sharded_tensor, "tensor")
+    val = kwargs["val"]
+    validate_param(val, "val")
+    for shard in sharded_tensor.local_shards():
+        torch.nn.init.constant_(shard.tensor, val=val)
+    return sharded_tensor
+
+
+tensor_like_creation_op_map = {
+    torch.full_like: sharded_tensor.full,
+    torch.empty_like: sharded_tensor.empty,
+    torch.zeros_like: sharded_tensor.zeros,
+    torch.ones_like: sharded_tensor.ones,
+    torch.rand_like: sharded_tensor.rand,
+    torch.randn_like: sharded_tensor.randn,
+}
+
+
+# tensor ops that behave the same as the default tensor
+def register_tensor_creation_op(op):
+    @_sharded_op_impl(op)
+    def tensor_creation_op(types, args=(), kwargs=None, pg=None):
+        """
+        Handles ``__torch_function__`` dispatch for tensor creation ops that
+        takes a ShardedTensor as argument, such as ``torch.zeros_like`` or
+        ``torch.full_like``.
+        """
+        creation_op = tensor_like_creation_op_map.get(op, None)
+        if creation_op is None:
+            raise RuntimeError(f"Tensor creation {op} not supported!")
+        if kwargs is None:
+            kwargs = {}
+
+        st = args[0]
+
+        new_st = creation_op(st.sharding_spec(), st.size(), *args[1:], **kwargs)  # type: ignore[operator]
+        return new_st
+
+
+register_tensor_creation_op(torch.full_like)
+register_tensor_creation_op(torch.empty_like)
+register_tensor_creation_op(torch.zeros_like)
+register_tensor_creation_op(torch.ones_like)
+register_tensor_creation_op(torch.rand_like)
+register_tensor_creation_op(torch.randn_like)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/misc_ops.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/misc_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b84c1684c32456989e3998b3d4c30c34cb5dbf4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/misc_ops.py
@@ -0,0 +1,12 @@
+# mypy: allow-untyped-defs
+import torch
+from torch.distributed._shard.sharded_tensor import _sharded_op_impl
+
+
+# This is used by `_apply()` within module.py to set new
+# parameters after apply a certain method, we should follow
+# the future behavior of overwriting the existing tensor
+# instead of doing in-place change using `.data = `.
+@_sharded_op_impl(torch._has_compatible_shallow_copy_type)
+def tensor_has_compatible_shallow_copy_type(types, args=(), kwargs=None, pg=None):
+    return False
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/tensor_ops.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/tensor_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..93902d6f314c51a6010dc06390bb6149c14291c8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/_ops/tensor_ops.py
@@ -0,0 +1,218 @@
+# mypy: allow-untyped-defs
+import copy
+
+import torch
+from torch.distributed._shard.common_op_utils import _register_default_op
+from torch.distributed._shard.sharded_tensor import (
+    _sharded_op_impl,
+    Shard,
+    ShardedTensor,
+)
+
+from ._common import _register_sharded_op_on_local_shards
+
+
+# Tensor properties access
+_register_default_op(torch.Tensor.shape.__get__, _sharded_op_impl)  # type: ignore[attr-defined]
+_register_default_op(torch.Tensor.dtype.__get__, _sharded_op_impl)  # type: ignore[attr-defined]
+_register_default_op(torch.Tensor.layout.__get__, _sharded_op_impl)  # type: ignore[attr-defined]
+_register_default_op(torch.Tensor.size, _sharded_op_impl)
+_register_default_op(torch.Tensor.dim, _sharded_op_impl)
+_register_default_op(torch.Tensor.ndim.__get__, _sharded_op_impl)  # type: ignore[attr-defined]
+_register_default_op(torch.Tensor.is_contiguous, _sharded_op_impl)
+_register_default_op(torch.Tensor.contiguous, _sharded_op_impl)
+_register_default_op(torch.Tensor.is_floating_point, _sharded_op_impl)
+
+# __reduce_ex__ to dispatch to get_state/set_state
+_register_default_op(torch.Tensor.__reduce_ex__, _sharded_op_impl)
+
+# autograd related properties
+_register_default_op(torch.Tensor.requires_grad.__get__, _sharded_op_impl)  # type: ignore[attr-defined]
+# TODO: set grad with a ShardedTensor that consists of all local grads
+_register_default_op(torch.Tensor.grad.__get__, _sharded_op_impl)  # type: ignore[union-attr]
+_register_default_op(torch.Tensor.grad_fn.__get__, _sharded_op_impl)  # type: ignore[union-attr]
+_register_default_op(torch.Tensor.is_leaf.__get__, _sharded_op_impl)  # type: ignore[attr-defined]
+
+
+# device property is ambiguous as from a global prospective,
+# ShardedTensor.device consists of multiple devices (might even across hosts)
+# We choose to return the current device of the local tensor to represent
+# the device property on each rank
+@_sharded_op_impl(torch.Tensor.device.__get__)
+def tensor_device(types, args=(), kwargs=None, pg=None):
+    self_st = args[0]
+    # Validate types
+    if not isinstance(self_st, ShardedTensor):
+        raise TypeError("input needs to be a ShardedTensor")
+    dev: torch.device
+    if self_st._local_shards:
+        dev = self_st._local_shards[0].tensor.device
+    elif pg and pg._get_backend_name() == "gloo":
+        dev = torch.device("cpu")
+    else:
+        dev = torch.device(torch.cuda.current_device())
+    return dev
+
+
+@_sharded_op_impl(torch.Tensor.is_meta.__get__)  # type: ignore[attr-defined]
+def st_is_meta(types, args=(), kwargs=None, pg=None):
+    return args[0].local_tensor().is_meta
+
+
+def sharded_type_as_check(*args, **kwargs):
+    """
+    Perform extra checks for the sharded_type_as op such as the input needs to
+    be either a Tensor or ShardedTensor.
+
+    Args: same as ``torch.Tensor.type_as``.
+
+    Return: None
+    """
+    if len(args) < 2:
+        raise ValueError("Needs to give a tensor to cast type as!")
+    if not isinstance(args[1], torch.Tensor) and not isinstance(args[1], ShardedTensor):
+        raise ValueError("Needs to give a Tensor or ShardedTensor to cast type as!")
+
+
+def same_dtype(*args, **kwargs):
+    """
+    When the dtype is the same, return the original ShardedTensor.
+
+    Args: same as ``torch.Tensor.type_as``.
+
+    Return (bool): Whether to return early or not.
+    """
+    return args[0].dtype == args[1].dtype
+
+
+def sharded_type_as(args, kwargs, pg):
+    """
+    Handles ``__torch_function__`` dispatch for the ``torch.Tensor.type_as`` op.
+
+    Args: same as ``torch.Tensor.type_as``.
+
+    Return:
+        new_local_shards (List[Shard]): Local shards for the new sharded tensor.
+        st_meta (ShardedTensorMetadata): Metadata of the new sharded tensor.
+    """
+    st = args[0]
+    tensor = args[1]
+    if isinstance(tensor, ShardedTensor):
+        tensor = tensor.local_tensor()
+    new_local_shards = []
+    for shard in st.local_shards():
+        new_local_shards.append(Shard(shard.tensor.type_as(tensor), shard.metadata))
+    st_meta = copy.deepcopy(st._metadata)
+    st_meta.tensor_properties.dtype = tensor.dtype
+    return new_local_shards, st_meta
+
+
+_register_sharded_op_on_local_shards(
+    torch.Tensor.type_as,
+    early_stop_func=same_dtype,
+    extra_check=sharded_type_as_check,
+    customized_func=sharded_type_as,
+)
+
+
+def sharded_deepcopy(args, kwargs, pg):
+    # NOTE: we directly implement deepcopy magic method
+    # instead of using the default tensor.__deepcopy__
+    # and implement clone(). This is because the default
+    # tensor deepcopy copies every attribute, but the
+    # process_group in ShardedTensor cannot be deep copied.
+    self_st = args[0]
+    new_local_shards = copy.deepcopy(self_st.local_shards())
+    new_metadata = copy.deepcopy(self_st.metadata())
+    return new_local_shards, new_metadata
+
+
+_register_sharded_op_on_local_shards(
+    torch.Tensor.__deepcopy__,
+    customized_func=sharded_deepcopy,
+)
+
+
+@_sharded_op_impl(torch.Tensor.copy_)
+def sharded_inplace_copy(types, args, kwargs, pg):
+    # NOTE: inplace op don't need to rewrap
+    kwargs = {} if kwargs is None else kwargs
+    self_st = args[0]
+    new_st = args[1]
+    nonblocking = kwargs.get("non_blocking", False)
+    for local_shard, new_shard in zip(self_st.local_shards(), new_st.local_shards()):
+        if local_shard.metadata != new_shard.metadata:
+            raise RuntimeError(
+                "inplace copy can only happen between two ShardedTensor with same metadata!"
+            )
+    for local_shard, new_shard in zip(self_st.local_shards(), new_st.local_shards()):
+        local_shard.tensor.copy_(new_shard.tensor, nonblocking)
+
+    return self_st
+
+
+def sharded_clone(args, kwargs, pg):
+    self_st = args[0]
+    desire_memory_format = kwargs.get("memory_format", None)
+    if desire_memory_format and desire_memory_format != torch.preserve_format:
+        raise RuntimeError("Only support torch.preserve_format for ShardedTensor!")
+    cloned_local_shards = [
+        Shard(
+            local_shard.tensor.clone(memory_format=desire_memory_format),
+            metadata=copy.deepcopy(local_shard.metadata),
+        )
+        for local_shard in self_st.local_shards()
+    ]
+    new_metadata = copy.deepcopy(self_st.metadata())
+    return cloned_local_shards, new_metadata
+
+
+_register_sharded_op_on_local_shards(
+    torch.Tensor.clone,
+    customized_func=sharded_clone,
+)
+
+
+def sharded_detach(args, kwargs, pg):
+    self_st = args[0]
+    detached_local_shards = [
+        Shard(
+            local_shard.tensor.detach(),
+            metadata=copy.deepcopy(local_shard.metadata),
+        )
+        for local_shard in self_st.local_shards()
+    ]
+    new_metadata = copy.deepcopy(self_st.metadata())
+    new_metadata.tensor_properties.requires_grad = False
+    return detached_local_shards, new_metadata
+
+
+_register_sharded_op_on_local_shards(
+    torch.Tensor.detach,
+    customized_func=sharded_detach,
+)
+
+
+@_sharded_op_impl(torch.Tensor.requires_grad_)
+def tensor_requires_grad_set(types, args=(), kwargs=None, pg=None):
+    self_st = args[0]
+    # Validate types
+    if not isinstance(self_st, ShardedTensor):
+        raise TypeError("input needs to be a ShardedTensor")
+
+    if kwargs is None:
+        kwargs = {}
+
+    requires_grad = args[1] if len(args) > 1 else kwargs.get("requires_grad", True)
+    if requires_grad == self_st.requires_grad:
+        return self_st
+
+    for local_shard in self_st.local_shards():
+        local_shard.tensor.requires_grad_(requires_grad)
+
+        # update the wrapper class property
+    with torch._C.DisableTorchFunctionSubclass():
+        self_st.requires_grad_(requires_grad)
+    # update the metadata in the meanwhile
+    self_st._metadata.tensor_properties.requires_grad = requires_grad
+    return self_st
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/api.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..68df582cd5145e12e217847d6937fa95bccf67be
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/api.py
@@ -0,0 +1,1304 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations  # type: ignore[attr-defined]
+
+import copy
+import operator
+import threading
+import warnings
+import weakref
+from dataclasses import dataclass
+from functools import reduce
+from typing import Callable, cast, Dict, List, Optional, Sequence, Tuple, TYPE_CHECKING
+from typing_extensions import deprecated
+
+import torch
+import torch.distributed as dist
+import torch.distributed._shard.sharding_spec as shard_spec
+from torch.distributed import distributed_c10d, rpc
+from torch.distributed._shard._utils import DEPRECATE_MSG
+from torch.distributed._shard.sharding_spec._internals import (
+    check_tensor,
+    validate_non_overlapping_shards_metadata,
+)
+from torch.distributed._shard.sharding_spec.api import (
+    _dispatch_custom_op,
+    _has_custom_op,
+)
+from torch.distributed.remote_device import _remote_device
+from torch.utils import _pytree as pytree
+
+from .metadata import ShardedTensorMetadata, TensorProperties
+from .reshard import reshard_local_shard, reshuffle_local_shard
+from .shard import Shard
+from .utils import (
+    _flatten_tensor_size,
+    _parse_and_validate_remote_device,
+    _validate_output_tensor_for_gather,
+    build_global_metadata,
+    build_metadata_from_local_shards,
+)
+
+
+if TYPE_CHECKING:
+    from torch.distributed._shard.metadata import ShardMetadata
+
+
+# Tracking for sharded tensor objects.
+_sharded_tensor_lock = threading.Lock()
+_sharded_tensor_current_id = 0
+_sharded_tensor_map: Dict[int, weakref.ReferenceType[ShardedTensor]] = {}
+
+# Default sharded ops
+_SHARDED_OPS: Dict[Callable, Callable] = {}
+
+# Customized user ops
+_CUSTOM_SHARDED_OPS: Dict[Callable, Callable] = {}
+
+
+def _register_remote_shards(
+    sharded_tensor_id: int, rrefs: List[rpc.RRef[Shard]], rpc_rank: int
+):
+    with _sharded_tensor_lock:
+        if sharded_tensor_id not in _sharded_tensor_map:
+            raise RuntimeError(
+                f"Could not find sharded_tensor_id: {sharded_tensor_id} in map: {_sharded_tensor_map.keys()}"
+            )
+
+        sharded_tensor = _sharded_tensor_map[sharded_tensor_id]()
+        if sharded_tensor is None:
+            raise RuntimeError("ShardedTensor weakref has been deallocated")
+        else:
+            sharded_tensor._register_remote_shards(rrefs, rpc_rank)
+
+
+class ShardedTensorBase(torch.Tensor):
+    _sharding_spec: shard_spec.ShardingSpec
+    _metadata: ShardedTensorMetadata
+    _local_shards: List[Shard]
+
+    def __new__(cls, sharding_spec: shard_spec.ShardingSpec, *size, **kwargs):
+        # Use __new__ to construct a wrapper tensor, for recording tensor
+        # properties and logging purposes.
+        torch._C._log_api_usage_once("torch.distributed._shard.sharded_tensor")
+
+        # check sharding spec and build sharded tensor metadata
+        if not isinstance(sharding_spec, shard_spec.ShardingSpec):
+            raise ValueError(f"Expecting ShardingSpec but got: {type(sharding_spec)}")
+
+        sizes = _flatten_tensor_size(size)
+        dtype = kwargs["dtype"]
+        layout = kwargs["layout"]
+        pin_memory = kwargs["pin_memory"]
+        requires_grad = kwargs["requires_grad"]
+
+        if dtype is None:
+            dtype = torch.get_default_dtype()
+
+        tensor_properties = TensorProperties(
+            dtype, layout, requires_grad, pin_memory=pin_memory
+        )
+        sharded_tensor_metadata = sharding_spec.build_metadata(
+            sizes, tensor_properties=tensor_properties
+        )
+
+        r = torch.Tensor._make_wrapper_subclass(  # type: ignore[attr-defined]
+            cls,
+            sizes,
+            dtype=dtype,
+            layout=layout,
+            pin_memory=pin_memory,
+            requires_grad=requires_grad,
+        )
+        # set sharding spec
+        r._sharding_spec = sharding_spec
+        # set metadata
+        r._metadata = sharded_tensor_metadata
+        # set local shards
+        r._local_shards = []
+        return r
+
+    def metadata(self) -> ShardedTensorMetadata:
+        """
+        Returns a :class:`ShardedTensorMetadata` object corresponding to the
+        metadata for the entire tensor.
+        """
+        return self._metadata
+
+    def local_shards(self) -> List[Shard]:
+        """
+        Returns a list of :class:`Shard' corresponding to the
+        local shards for this rank. Returns an empty list if the current rank
+        does not host any shards for this Tensor.
+        """
+        return self._local_shards
+
+    @classmethod
+    def _init_from_local_shards_and_global_metadata(
+        cls,
+        local_shards: List[Shard],
+        sharded_tensor_metadata: ShardedTensorMetadata,
+        sharding_spec=None,
+    ) -> ShardedTensorBase:
+        """
+        Initialize a ShardedTensorBase with local shards and a global
+        ShardedTensorMetadata built on each rank.
+        Warning: This API is experimental and subject to change. It does
+                 not do cross rank validations, and fully rely on the user
+                 for the correctness of sharded_tensor_metadata on each rank
+        """
+        shards_metadata = sharded_tensor_metadata.shards_metadata
+        tensor_properties = sharded_tensor_metadata.tensor_properties
+
+        if len(shards_metadata) == 0:
+            raise ValueError("shards_metadata must not be empty!")
+
+        if tensor_properties.layout != torch.strided:
+            raise ValueError("Only torch.strided layout is currently supported")
+
+        if sharding_spec is None:
+            spec = shard_spec._infer_sharding_spec_from_shards_metadata(shards_metadata)
+        else:
+            spec = sharding_spec
+
+        sharded_tensor_base = ShardedTensorBase.__new__(
+            ShardedTensor,
+            spec,
+            sharded_tensor_metadata.size,
+            dtype=tensor_properties.dtype,
+            layout=tensor_properties.layout,
+            pin_memory=tensor_properties.pin_memory,
+            requires_grad=tensor_properties.requires_grad,
+        )
+
+        # check if shards_metadata have overlap shards
+        validate_non_overlapping_shards_metadata(shards_metadata)
+
+        # check if the shards_metadata is compatible with overall size of the sharded tensor.
+        check_tensor(shards_metadata, list(sharded_tensor_metadata.size))
+
+        # done validation, add local_shards
+        sharded_tensor_base._local_shards = local_shards
+        return sharded_tensor_base
+
+    @classmethod
+    def __torch_dispatch__(cls, func, types, args=(), kwargs=None):
+        raise RuntimeError(
+            f"A {cls.__name__} object is being used from c++ while calling {func.__module__}.{func.__name__} "
+            "but the there is no custom __torch_dispatch__ implementation for it."
+        )
+
+
+class ShardedTensor(ShardedTensorBase):
+    """
+    ShardedTensor is an torch.Tensor subclass to represent Tensors that are sharded
+    across multiple devices and multiple processes.
+
+    ShardedTensor is initialized in an SPMD like fashion where each rank
+    initializes the ShardedTensor. The ShardedTensor object on each rank
+    then only stores the local shard for the Tensor and provides global
+    metadata for all the shards.
+
+    ShardedTensor doesn't provide any Tensor like operations but is a wrapper
+    providing the Tensor representing the local shard and the global metadata.
+    Using these, users can build their custom distributed._sharded computations
+    on top of this primitive. The local shards are all initialized using the
+    create_op specified by tensor_init_params.create_op, e.g., torch.ones, or
+    torch.empty
+
+    Args:
+        sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification
+            describing how to shard the Tensor.
+        size (int...): a sequence of integers defining the shape of the output
+            tensor. Can be a variable number of arguments or a collection like a list or tuple.
+
+    Keyword args:
+        dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
+                Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).
+        layout (:class:`torch.layout`, optional): the desired layout of returned Tensor.
+            Default: ``torch.strided``.
+        requires_grad (bool, optional): If autograd should record operations on the
+            returned tensor. Default: ``False``.
+        pin_memory (bool, optional): If set, returned tensor would be allocated in
+            the pinned memory. Works only for CPU tensors. Default: ``False``.
+        memory_format (:class:`torch.memory_format`, optional): the desired memory format of
+            returned Tensor. Default: ``torch.contiguous_format``.
+        init_rrefs (bool, optional): Whether or not to initialize
+            :class:`torch.distributed.rpc.RRef`s pointing to remote shards.
+            Need to initialize the RPC Framework if specified as ``True``.
+            Default: ``False``.
+
+    .. note:: ShardedTensor uses collectives to do various operations, i.e. it
+        uses all_gather to do cross rank validations. For NCCL-based process
+        groups, internal tensor representations of objects must be moved to the
+        GPU device before communication takes place. In this case, the device
+        used is given by ``torch.cuda.current_device()`` and it is the user's
+        responsibility to ensure that this is set so that each rank has an
+        individual GPU, via ``torch.cuda.set_device()``
+
+    """
+
+    def __new__(cls, sharding_spec: shard_spec.ShardingSpec, *size, **kwargs):
+        self = super().__new__(cls, sharding_spec, *size, **kwargs)
+        return self
+
+    def __init__(
+        self,
+        sharding_spec: shard_spec.ShardingSpec,
+        *size,
+        dtype=None,
+        layout=torch.strided,
+        requires_grad=False,
+        pin_memory=False,
+        memory_format=torch.contiguous_format,
+        process_group=None,
+        init_rrefs=False,
+    ):
+        # prepare initialization, initialize fields like
+        # _process_group, _local_shards, etc.
+        self._prepare_init(process_group=process_group, init_rrefs=init_rrefs)
+
+        if layout != torch.strided:
+            raise ValueError("Only torch.strided layout is currently supported")
+
+        if memory_format != torch.contiguous_format:
+            raise ValueError(
+                "Only torch.contiguous_format memory_format is currently supported"
+            )
+
+        self._metadata.tensor_properties.memory_format = memory_format
+
+        current_rank = dist.get_rank()  # global rank
+
+        for shard_metadata in self._metadata.shards_metadata:
+            rank, device = _parse_and_validate_remote_device(
+                self._process_group, shard_metadata.placement
+            )
+            if rank == current_rank:
+                local_tensor = _create_tensor_from_params(
+                    shard_metadata.shard_sizes,
+                    local_device=device,
+                    tensor_properties=self._metadata.tensor_properties,
+                )
+                self._local_shards.append(Shard(local_tensor, shard_metadata))
+
+        # do post initialization (i.e. register sharded_tensor_id, initialize_rpc)
+        self._post_init()
+
+    def _prepare_init(self, process_group=None, init_rrefs=False):
+        self._init_rrefs = init_rrefs
+        self._sharded_tensor_id = None
+
+        self._process_group = self._normalize_pg(process_group)
+        self._remote_shards: Dict[int, List[rpc.RRef[Shard]]] = {}
+
+    def _post_init(self):
+        # Initialize RPC if available.
+        if self._init_rrefs:
+            with _sharded_tensor_lock:
+                global _sharded_tensor_current_id, _sharded_tensor_map
+                self._sharded_tensor_id = _sharded_tensor_current_id
+                _sharded_tensor_map[self._sharded_tensor_id] = weakref.ref(self)
+                _sharded_tensor_current_id += 1
+
+            if not rpc._is_current_rpc_agent_set():
+                raise RuntimeError(
+                    "RPC Framework needs to be initialized using"
+                    " torch.distributed.rpc.init_rpc if init_rrefs is set to True"
+                )
+            self._init_rpc()
+
+    def __del__(self):
+        # Clean up the global map.
+        with _sharded_tensor_lock:
+            global _sharded_tensor_current_id, _sharded_tensor_map
+            if (
+                hasattr(self, "_sharded_tensor_id")
+                and self._sharded_tensor_id in _sharded_tensor_map
+            ):
+                _sharded_tensor_map.pop(self._sharded_tensor_id)  # type: ignore[call-overload]
+
+    def _init_rpc(self):
+        # Validate PG and RPC ranks match.
+        pg_rank = dist.get_rank()
+        rpc_rank = rpc.get_worker_info().id
+        if pg_rank != rpc_rank:
+            raise ValueError(
+                f"Default ProcessGroup and RPC ranks must be "
+                f"the same for ShardedTensor, found process group rank: "
+                f"{pg_rank} and RPC rank: {rpc_rank}"
+            )
+
+        self._remote_shards = {}
+
+        # Gather all the sharded tensor ids.
+        worker_infos = rpc._get_current_rpc_agent().get_worker_infos()
+        rank_to_name = {}
+        name_to_rank = {}
+
+        for worker_info in worker_infos:
+            rank_to_name[worker_info.id] = worker_info.name
+            name_to_rank[worker_info.name] = worker_info.id
+
+        all_tensor_ids = rpc.api._all_gather(self._sharded_tensor_id)
+
+        # Share the local shards to the entire world.
+        futs = []
+        rpc_rank = rpc.get_worker_info().id
+        for rank in range(dist.get_world_size()):
+            # Skip self.
+            if rank == dist.get_rank():
+                continue
+
+            if len(self.local_shards()) != 0:
+                rrefs: List[rpc.RRef[Shard]] = [
+                    rpc.RRef(shard) for shard in self.local_shards()
+                ]
+                fut = rpc.rpc_async(
+                    rank,
+                    _register_remote_shards,
+                    args=(all_tensor_ids[rank_to_name[rank]], rrefs, rpc_rank),
+                )
+                futs.append(fut)
+
+        torch.futures.wait_all(futs)
+
+        # Barrier for all RPCs to finish on all ranks.
+        rpc.api._all_gather(None)
+
+    def _get_preferred_device(self) -> torch.device:
+        """
+        Return the preferred device to be used when creating tensors for collectives.
+        This method takes into account the associated process group
+        """
+        if dist.get_backend(self._process_group) == dist.Backend.NCCL:
+            return torch.device(torch.cuda.current_device())
+        return torch.device("cpu")
+
+    def gather(  # type: ignore[override]
+        self,
+        dst: int = 0,
+        out: Optional[torch.Tensor] = None,
+        enforce_dtype: bool = False,
+        dtype: Optional[torch.dtype] = None,
+    ) -> None:
+        """
+        Creates a full :class:`Tensor` on rank ``dst`` by gathering all shards of the
+        sharded tensor.
+
+        The API needs to be called on all ranks in SPMD fashion. All ranks should have
+        the same ``dst``. ``out`` should be a tensor of the same size as the overall
+        size of the sharded tensor on ``dst`` and ``None`` on all other ranks.
+
+        Args:
+            dst(int): The rank where full tensor is constructed.
+                Default: 0
+            out (:class `torch.Tensor`, optional): The output full tensor.
+                Must to be provided ONLY on ``dst`` rank.
+                Default: ``None``
+            enforce_dtype (bool): Deprecated, please use dtype instead.  Force the
+                gathered tensors to be the same type as input and output.
+            dtype (torch.dtype): Force the gathered tensors to be this dtype.
+                Default: ``None``
+        """
+
+        def shard_size(shard_md):
+            return reduce(operator.mul, shard_md.shard_sizes)  # type: ignore[attr-defined]
+
+        if enforce_dtype:
+            warnings.warn(
+                "`enforce_dtype` is deprecated. Please use `dtype` instead.",
+                FutureWarning,
+                stacklevel=2,
+            )
+
+        rank = dist.get_rank(self._process_group)
+        full_size = self.metadata().size
+        _validate_output_tensor_for_gather(rank, dst, full_size, out)
+
+        local_shards = self.local_shards()
+        world_size = dist.get_world_size(self._process_group)
+        rank_sizes = [0 for _ in range(world_size)]
+        max_rank_size = 0
+        shard_placement: Dict[ShardMetadata, Tuple[int, int]] = {}
+        # collect sizes
+        for shard_md in self.metadata().shards_metadata:
+            shard_rank = cast(_remote_device, shard_md.placement).rank()
+            assert shard_rank is not None
+
+            shard_placement[shard_md] = (shard_rank, rank_sizes[shard_rank])
+            rank_sizes[shard_rank] += shard_size(shard_md)
+            max_rank_size = max(max_rank_size, rank_sizes[shard_rank])
+
+        gather_list: Optional[List[torch.Tensor]]
+        if rank == dst:
+            assert out is not None
+            if enforce_dtype:
+                # enforce_dtype is deprecated.  Do it for backward compatibility.
+                dtype = out.dtype
+            # TODO make it as a view of out tensor
+            gather_list = [
+                torch.empty((max_rank_size,), device=out.device, dtype=dtype)
+                for _ in range(world_size)
+            ]
+        else:
+            gather_list = None
+
+        with torch.no_grad():
+            if enforce_dtype and len(local_shards) > 0:
+                # enforce_dtype is deprecated.  Do it for backward compatibility.
+                dtype = local_shards[0].tensor.dtype
+            data = torch.empty(
+                max_rank_size, device=self._get_preferred_device(), dtype=dtype
+            )
+
+            for shard in local_shards:
+                src = shard.tensor.flatten()
+                if src.nelement() == 0:
+                    warnings.warn(
+                        "Gathering a tensor with zero elements on rank " + str(rank)
+                    )
+                    return
+                shard_offset = shard_placement[shard.metadata][1]
+                data[shard_offset : shard_offset + src.numel()].copy_(src)
+
+        dist.gather(
+            tensor=data,
+            gather_list=gather_list,
+            dst=dst,
+            group=self._process_group,
+        )
+        if rank != dst:
+            return
+        # In _validate_output_tensor_for_gather, we raise if out == None and rank == dst
+        out = cast(torch.Tensor, out)
+        assert gather_list is not None
+
+        full_size = self.metadata().size
+        dims = len(full_size)
+        for shard_md in self.metadata().shards_metadata:
+            rank, rank_offset = shard_placement[shard_md]
+            tensor = gather_list[rank]
+            tensor = tensor[rank_offset : rank_offset + shard_size(shard_md)]
+            tensor = tensor.view(shard_md.shard_sizes)
+
+            out_narrow_view = out
+            for dim in range(dims):
+                out_narrow_view = out_narrow_view.narrow(
+                    dim,
+                    shard_md.shard_offsets[dim],
+                    shard_md.shard_sizes[dim],
+                )
+
+            out_narrow_view.copy_(tensor)
+
+    def cpu(
+        self, memory_format=torch.preserve_format, process_group=None
+    ) -> ShardedTensor:
+        """
+        Returns a copy of this object in CPU memory.
+
+        If this ShardedTensor is already on CPU memory, then no copy is
+        performed and original object is returned.
+
+        .. note:: When moving a ShardedTensor from GPU to CPU, the ShardedTensor might
+            need to be managed by a different type of ProcessGroup(i.e. ProcessGroupGloo),
+            it is the user's responsiblity to explicitly pass in a new process_group that
+            is compatible with CPU.
+        """
+        # TODO: make this a __torch_function__ op once ShardedTensor becomes a
+        # torch.Tensor subclass, see https://github.com/pytorch/pytorch/issues/75402
+        if (
+            memory_format != torch.preserve_format
+            and memory_format != torch.contiguous_format
+        ):
+            raise RuntimeError(
+                "Only `torch.contiguous_format` or "
+                "`torch.preserve_format` is supported!"
+            )
+        all_on_cpu = True
+        for meta in self.metadata().shards_metadata:
+            all_on_cpu &= meta.placement.device().type == "cpu"  # type: ignore[union-attr]
+
+        # if every shard is already on CPU, return the original object
+        if all_on_cpu:
+            return self
+
+        # if not, returns a copy of this object on CPU
+        list_shards: List[Shard] = []
+        # move all local shards to cpu, and change metadata
+        for shard in self._local_shards:
+            cpu_tensor = shard.tensor.cpu(memory_format=memory_format)  # type: ignore[call-arg]
+            metadata = copy.deepcopy(shard.metadata)
+            metadata.placement._device = torch.device("cpu")  # type: ignore[union-attr]
+            list_shards.append(Shard(cpu_tensor, metadata))
+
+        st_meta = copy.deepcopy(self.metadata())
+        for meta in st_meta.shards_metadata:
+            if meta.placement.device().type != "cpu":  # type: ignore[union-attr]
+                meta.placement._device = torch.device("cpu")  # type: ignore[union-attr]
+
+        pg = self._process_group if process_group is None else process_group
+        st_cpu = ShardedTensor._init_from_local_shards_and_global_metadata(
+            list_shards,
+            sharded_tensor_metadata=st_meta,
+            process_group=pg,
+            init_rrefs=self._init_rrefs,
+        )
+        return st_cpu
+
+    def cuda(
+        self,
+        device=None,
+        non_blocking=False,
+        memory_format=torch.preserve_format,
+        process_group=None,
+    ) -> ShardedTensor:
+        """
+        Returns a copy of this object in CUDA memory, if the original ShardedTensor
+        is on CPU, we will move the local shard to the current GPU device of each
+        process in a SPMD fashion.
+        If this ShardedTensor is already on CUDA memory and local shards on each rank are
+        already on current device, we still returns a new ShardedTensor object with new
+        metadata, but no underlying data movements are performed.
+        .. note:: When moving a ShardedTensor from CPU to GPU, the ShardedTensor might
+            need to be managed by a different type of ProcessGroup(i.e. ProcessGroupNCCL),
+            it is the user's responsiblity to explicitly pass in a new process_group that
+            is compatible with GPU.
+        """
+        if (
+            memory_format != torch.preserve_format
+            and memory_format != torch.contiguous_format
+        ):
+            raise RuntimeError(
+                "Only `torch.contiguous_format` or "
+                "`torch.preserve_format` is supported!"
+            )
+
+        if device is not None:
+            device = torch.device(device) if isinstance(device, str) else device
+            assert (
+                isinstance(device, torch.device)
+                and device.index == torch.cuda.current_device()
+            ), """Only device without device id (e.g. "cpu" or "cuda") is expected for ShardedTensor!"""
+
+        current_device = torch.device(torch.cuda.current_device())
+        # returns a copy of ShardedTensor on CUDA current device
+        list_shards: List[Shard] = []
+        # move all local shards to current device, and change metadata
+        # if local shards already on the current device, there's no
+        # real data movement, only the metadata are copied.
+        for shard in self._local_shards:
+            cuda_tensor = shard.tensor.cuda(
+                device=current_device,
+                non_blocking=non_blocking,
+                memory_format=memory_format,
+            )  # type: ignore[call-arg]
+            metadata = copy.deepcopy(shard.metadata)
+            metadata.placement._device = current_device  # type: ignore[union-attr]
+
+            list_shards.append(Shard(cuda_tensor, metadata))
+
+        st_meta = copy.deepcopy(self.metadata())
+        for meta in st_meta.shards_metadata:
+            if meta.placement.device().type != "cuda":  # type: ignore[union-attr]
+                meta.placement._device = current_device  # type: ignore[union-attr]
+
+        pg = self._process_group if process_group is None else process_group
+        # we need to use `init_from_local_shards` to communicate between ranks
+        # and update the sharding spec/shards metadata.
+        st_cuda = ShardedTensor._init_from_local_shards_and_global_metadata(
+            list_shards,
+            sharded_tensor_metadata=st_meta,
+            process_group=pg,
+            init_rrefs=self._init_rrefs,
+        )
+        return st_cuda
+
+    def to(self, *args, **kwargs) -> ShardedTensor:
+        current_device: torch.device
+        if self._local_shards:
+            current_device = self._local_shards[0].tensor.device
+        elif self._process_group._get_backend_name() == "gloo":
+            current_device = torch.device("cpu")
+        else:
+            current_device = torch.device(torch.cuda.current_device())
+        current_dtype = self.dtype
+        device_to = current_device
+        dtype_to = current_dtype
+        if len(args) == 1:
+            if isinstance(args[0], torch.dtype):
+                dtype_to = args[0]
+            elif isinstance(args[0], torch.device):
+                device_to = args[0]
+            elif isinstance(args[0], (str, int)):
+                device_to = torch.device(args[0])
+            elif isinstance(args[0], torch.Tensor):
+                dtype_to = args[0].dtype
+                device_to = args[0].device
+            else:
+                raise RuntimeError(f"ShardedTensor.to() have wrong arguments: {args}")
+        elif len(args) == 2:
+            device_to, dtype_to = args
+        else:
+            dtype_to = kwargs.get("dtype", current_dtype)
+            device_to = kwargs.get("device", current_device)
+
+        device_to = (
+            torch.device(device_to) if isinstance(device_to, (str, int)) else device_to
+        )
+
+        if device_to.type == "cuda":
+            # if device_to set to cuda, set to current device even
+            # if user specify the device index.
+            current_idx = torch.cuda.current_device()
+            if device_to.index != current_idx:
+                warnings.warn(
+                    "ShardedTensor.to only move tensor to its current device"
+                    "If you want to put to different device, use `reshard` instead."
+                )
+            device_to = torch.device(current_idx)
+
+        copy_tensor = kwargs.get("copy", False)
+        non_blocking = kwargs.get("non_blocking", False)
+        memory_format = kwargs.get("memory_format", torch.preserve_format)
+        process_group = kwargs.get("process_group", None)
+
+        if (
+            not copy_tensor
+            and dtype_to == current_dtype
+            and device_to == current_device
+        ):
+            # already have correct dtype and device, return itself
+            return self
+
+        # returns a copy of ShardedTensor on CUDA current device
+        list_shards: List[Shard] = []
+
+        for shard in self._local_shards:
+            new_tensor = shard.tensor.to(  # type: ignore[call-overload]
+                device=device_to,
+                dtype=dtype_to,
+                non_blocking=non_blocking,
+                copy=copy_tensor,
+                memory_format=memory_format,
+            )
+            metadata = copy.deepcopy(shard.metadata)
+            if metadata.placement is not None:
+                metadata.placement._device = device_to
+            list_shards.append(Shard(new_tensor, metadata))
+
+        # update metadata
+        st_meta = copy.deepcopy(self.metadata())
+        st_meta.tensor_properties.dtype = dtype_to
+        for meta in st_meta.shards_metadata:
+            meta.placement._device = device_to  # type: ignore[union-attr]
+
+        pg = self._process_group if process_group is None else process_group
+        # we need to use `init_from_local_shards` to communicate between ranks
+        # and update the sharding spec/shards metadata.
+        st_to = ShardedTensor._init_from_local_shards_and_global_metadata(
+            list_shards,
+            sharded_tensor_metadata=st_meta,
+            process_group=pg,
+            init_rrefs=self._init_rrefs,
+        )
+        return st_to
+
+    @classmethod
+    def _normalize_pg(
+        cls, process_group: Optional[dist.ProcessGroup]
+    ) -> dist.ProcessGroup:
+        if process_group is not None:
+            return process_group
+        return distributed_c10d._get_default_group()
+
+    @classmethod
+    def _init_from_local_shards(
+        cls,
+        local_shards: List[Shard],
+        *global_size,
+        process_group=None,
+        init_rrefs=False,
+    ):
+        # STEP 1: Validate the Shardmetadatas locally
+        process_group = cls._normalize_pg(process_group)
+        current_rank = dist.get_rank()  # intentional to get global rank
+        world_size = dist.get_world_size(process_group)
+
+        local_sharded_tensor_metadata: Optional[ShardedTensorMetadata] = None
+        global_tensor_size = _flatten_tensor_size(global_size)
+
+        if len(local_shards) > 0:
+            local_sharded_tensor_metadata = build_metadata_from_local_shards(
+                local_shards, global_tensor_size, current_rank, process_group
+            )
+
+        # STEP 2. Validate metadata across ranks, and build a global sharded tensor
+        # metadata by gathering local ShardedTensorMetadata
+        gathered_metadatas: List[Optional[ShardedTensorMetadata]] = []
+        if world_size > 1:
+            gathered_metadatas = [None for _ in range(world_size)]
+
+            dist.all_gather_object(
+                gathered_metadatas, local_sharded_tensor_metadata, group=process_group
+            )
+        else:
+            gathered_metadatas = [local_sharded_tensor_metadata]
+
+        global_sharded_tensor_metadata = build_global_metadata(gathered_metadatas)
+        tensor_properties = global_sharded_tensor_metadata.tensor_properties
+
+        # STEP 3: Validation done, create the actual ShardedTensor and populate fields
+        # prepare initialization
+        spec = shard_spec._infer_sharding_spec_from_shards_metadata(
+            global_sharded_tensor_metadata.shards_metadata
+        )
+        sharded_tensor = cls.__new__(
+            cls,
+            spec,
+            global_sharded_tensor_metadata.size,
+            dtype=tensor_properties.dtype,
+            layout=tensor_properties.layout,
+            pin_memory=tensor_properties.pin_memory,
+            requires_grad=tensor_properties.requires_grad,
+        )
+        sharded_tensor._prepare_init(process_group=process_group, init_rrefs=init_rrefs)
+
+        # attach local_shards to the ShardedTensor created
+        sharded_tensor._local_shards = local_shards
+
+        # run post initialization, i.e. map registration, rpc initialization
+        sharded_tensor._post_init()
+        return sharded_tensor
+
+    @classmethod
+    @deprecated(DEPRECATE_MSG, category=FutureWarning)
+    def _init_from_local_tensor(
+        cls,
+        local_tensor: torch.Tensor,
+        sharding_spec: shard_spec.ShardingSpec,
+        *global_size: Sequence[int],
+        process_group: Optional[dist.ProcessGroup] = None,
+        init_rrefs=False,
+    ) -> ShardedTensor:
+        """
+        Initialize a ShardedTensor given only one local tensor, global sharded tensor
+        size and sharding spec on each rank.
+
+        Args:
+            local_tensor (Tensor): Single tensor of local shard stored in each rank.
+            sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`):
+                The specification describing how to shard the Tensor.
+            global_size (Sequence[int]): Size of the sharded tensor.
+            process_group (ProcessGroup, optional): The process group to aggregate on.
+                Default: None
+            init_rrefs (bool, optional): Whether or not to initialize
+                :class:`torch.distributed.rpc.RRef`s pointing to remote shards.
+                Need to initialize the RPC Framework if specified as ``True``.
+                Default: ``False``.
+
+        Returns:
+            A :class:`ShardedTensor` sharded based on the given sharding_spec with local
+                tensor stored in the current rank.
+
+        Examples:
+            >>> # xdoctest: +SKIP
+            >>> # All tensors below are of torch.int64 type.
+            >>> # We have 2 process groups, 2 ranks.
+            >>> tensor = torch.arange(2, dtype=torch.int64) + 1 + 2 * rank
+            >>> local_tensor = torch.unsqueeze(torch.cat([tensor, tensor + 2]))
+            >>> local_tensor
+            tensor([[1, 2, 3, 4]]) # Rank 0
+            tensor([[3, 4, 5, 6]]) # Rank 1
+            >>> sharding_dim = 0
+            >>> sharding_spec = ChunkShardingSpec(
+                    dim=sharding_dim,
+                    placements=[
+                        "rank:0/cuda:0",
+                        "rank:1/cuda:1",
+                    ],
+                )
+            >>> st = ShardedTensor._init_from_local_tensor(local_tensor, sharding_spec, [2, 4])
+            >>> st
+            ShardedTensor(
+                ShardedTensorMetadata(
+                    shards_metadata=[
+                        ShardMetadata(shard_offsets=[0, 0], shard_sizes=[1, 4], placement=rank:0/cuda:0),
+                        ShardMetadata(shard_offsets=[1, 0], shard_sizes=[1, 4], placement=rank:1/cuda:1),
+                    ],
+                    size=torch.Size([2, 4])
+            )
+            >>> st.local_tensor()
+            tensor([1, 2, 3, 4]) # Rank 0
+            tensor([3, 4, 5, 6]) # Rank 1
+
+        Warning: This API is experimental and subject to change. It lacks of a fully across
+                 rank validations, and we only validate the local shard on the current rank.
+                 We fully rely on the user to ensure local tensor is sharded based on the
+                 sharding spec.
+        """
+        if not local_tensor.is_contiguous():
+            raise ValueError("local_tensor is not a contiguous Tensor.")
+
+        global_tensor_size = _flatten_tensor_size(global_size)
+        tensor_properties = TensorProperties(
+            dtype=local_tensor.dtype,
+            layout=local_tensor.layout,
+            requires_grad=local_tensor.requires_grad,
+            memory_format=torch.contiguous_format,
+            pin_memory=local_tensor.is_pinned(),
+        )
+        sharded_tensor_metadata = sharding_spec.build_metadata(
+            global_tensor_size, tensor_properties
+        )
+
+        process_group = cls._normalize_pg(process_group)
+        current_rank = dist.get_rank()  # intentional to get global rank
+
+        local_shards: List[Shard] = []
+        for shard_metadata in sharded_tensor_metadata.shards_metadata:
+            rank, device = _parse_and_validate_remote_device(
+                process_group, shard_metadata.placement
+            )
+            if rank == current_rank:
+                local_shards.append(Shard(local_tensor, shard_metadata))
+
+        # TODO: figure out what the API should behave when some rank have no shard
+        # see https://github.com/pytorch/pytorch/issues/7313
+        return ShardedTensor._init_from_local_shards_and_global_metadata(
+            local_shards,
+            sharded_tensor_metadata,
+            process_group=process_group,
+            init_rrefs=init_rrefs,
+            sharding_spec=sharding_spec,
+        )
+
+    @classmethod
+    def _init_from_local_shards_and_global_metadata(  # type: ignore[override]
+        cls,
+        local_shards: List[Shard],
+        sharded_tensor_metadata: ShardedTensorMetadata,
+        process_group=None,
+        init_rrefs=False,
+        sharding_spec=None,
+    ) -> ShardedTensor:
+        """
+        Initialize a ShardedTensor with local shards and a global
+        ShardedTensorMetadata built on each rank.
+
+        Warning: This API is experimental and subject to change. It does
+                 not do cross rank validations, and fully rely on the user
+                 for the correctness of sharded_tensor_metadata on each rank
+        """
+        process_group = cls._normalize_pg(process_group)
+        current_rank = dist.get_rank()  # intentional to get global rank
+
+        shards_metadata = sharded_tensor_metadata.shards_metadata
+
+        local_shard_metadatas = []
+
+        # collect local shard metadatas from the global sharded_tensor_metadata
+        for shard_metadata in shards_metadata:  # type: ignore[attr-defined]
+            rank, local_device = _parse_and_validate_remote_device(
+                process_group, shard_metadata.placement
+            )
+
+            if current_rank == rank:
+                local_shard_metadatas.append(shard_metadata)
+
+        if len(local_shards) != len(local_shard_metadatas):
+            raise RuntimeError(
+                f"Number of local shards ({len(local_shards)}) does not match number of local "
+                f"shards metadata in sharded_tensor_metadata ({len(local_shard_metadatas)}) "
+                f"on rank ({current_rank}) "
+            )
+
+        shards_metadata = sharded_tensor_metadata.shards_metadata
+        tensor_properties = sharded_tensor_metadata.tensor_properties
+
+        if len(shards_metadata) == 0:
+            raise ValueError("shards_metadata must not be empty!")
+
+        if tensor_properties.layout != torch.strided:
+            raise ValueError("Only torch.strided layout is currently supported")
+
+        if sharding_spec is None:
+            spec = shard_spec._infer_sharding_spec_from_shards_metadata(shards_metadata)
+        else:
+            spec = sharding_spec
+
+        sharded_tensor = ShardedTensor.__new__(
+            ShardedTensor,
+            spec,
+            sharded_tensor_metadata.size,
+            dtype=tensor_properties.dtype,
+            layout=tensor_properties.layout,
+            pin_memory=tensor_properties.pin_memory,
+            requires_grad=tensor_properties.requires_grad,
+        )
+
+        def _raise_if_mismatch(expected, actual, prop_name, rank, is_property=False):
+            tensor_property_or_metadata = (
+                "tensor property" if is_property else "local ShardMetadata"
+            )
+            if expected != actual:
+                raise ValueError(
+                    f"Local shards' tensor {prop_name} property is incompatible with "
+                    f"{tensor_property_or_metadata} on rank {rank}: "
+                    f"{tensor_property_or_metadata} {prop_name}={expected}, "
+                    f"local shard tensor {prop_name}={actual}."
+                )
+
+        for shard in local_shards:
+            shard_meta = shard.metadata
+            local_shard_tensor = shard.tensor
+            placement = shard_meta.placement
+            assert placement is not None, "Must specify placement for `Shard`!"
+            rank = placement.rank()
+            local_device = placement.device()
+
+            _raise_if_mismatch(
+                tensor_properties.layout,
+                local_shard_tensor.layout,
+                "layout",
+                rank,
+                True,
+            )
+            if not local_shard_tensor.is_contiguous():
+                raise ValueError(
+                    "Only torch.contiguous_format memory_format is currently supported"
+                )
+
+            _raise_if_mismatch(
+                shard_meta.shard_sizes,
+                list(local_shard_tensor.size()),
+                "size",
+                rank,
+            )
+            _raise_if_mismatch(
+                tensor_properties.pin_memory,
+                local_shard_tensor.is_pinned(),
+                "pin_memory",
+                rank,
+                True,
+            )
+            _raise_if_mismatch(local_device, local_shard_tensor.device, "device", rank)
+            _raise_if_mismatch(
+                tensor_properties.dtype,
+                local_shard_tensor.dtype,
+                "dtype",
+                rank,
+                True,
+            )
+            _raise_if_mismatch(
+                tensor_properties.requires_grad,
+                local_shard_tensor.requires_grad,
+                "requires_grad",
+                rank,
+                True,
+            )
+
+        # check if shards_metadata have overlap shards
+        validate_non_overlapping_shards_metadata(shards_metadata)
+
+        # check if the shards_metadata is compatible with overall size of the sharded tensor.
+        check_tensor(shards_metadata, list(sharded_tensor_metadata.size))
+
+        # done validation, add local_shards
+        sharded_tensor._local_shards = local_shards
+        sharded_tensor._prepare_init(process_group=process_group, init_rrefs=init_rrefs)
+
+        # run post initialization, i.e. map registration, rpc initialization
+        sharded_tensor._post_init()
+        return sharded_tensor
+
+    def sharding_spec(self) -> shard_spec.ShardingSpec:
+        """
+        Returns the ShardingSpec for the tensor.
+        """
+        return self._sharding_spec
+
+    @deprecated(DEPRECATE_MSG, category=FutureWarning)
+    def reshard(self, resharding_spec: shard_spec.ShardingSpec) -> ShardedTensor:
+        """
+        Reshard a sharded tensor given the ``resharding_spec``. For now, we only support
+        single local shard.
+
+        If ``resharding_spec`` is same as the original one, this becomes a no-op.
+        If only ``resharding_spec`` shares the same sharding dim with the original one,
+        we swap local shards directly.
+        For more generic cases, we merge different shards across different ranks and split
+        the local shards based on the ``resharding_spec`` via `all_to_all` collective API.
+
+        Args:
+            resharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The
+                specification describing how the tensor is sharded.
+
+        Returns:
+            A :class:`ShardedTensor` object whose local shards are resharded.
+
+        Examples:
+            >>> # xdoctest: +SKIP
+            >>> # We have 2 process groups, 2 ranks.
+            >>> tensor = torch.arange(4, dtype=torch.int64) + 1 + 2 * rank
+            >>> tensor = torch.stack([tensor, tensor])
+            >>> tensor
+            tensor([[1, 2, 3, 4], [1, 2, 3, 4]]) # Rank 0
+            tensor([[3, 4, 5, 6], [3, 4, 5, 6]]) # Rank 1
+            tensor([[5, 6, 7, 8], [5, 6, 7, 8]]) # Rank 2
+            tensor([[7, 8, 9, 10], [7, 8, 9, 10]]) # Rank 3
+            >>> sharding_dim = 0
+            >>> spec = ChunkShardingSpec(
+                    dim=sharding_dim,
+                    placements=[
+                        "rank:0/cuda:0",
+                        "rank:1/cuda:1",
+                        "rank:2/cuda:2",
+                        "rank:3/cuda:3",
+                    ],
+                )
+            >>> current_offsets = [0] * 2
+            >>> current_offsets[0] = rank * 2
+            >>> shard_metadata = ShardMetadata(
+                    shard_offsets=copy.deepcopy(current_offsets),
+                    shard_sizes=tensor.size(),
+                    placement=spec.placements[rank],
+                )
+            >>> local_shards = [
+                    Shard(
+                        tensor=tensor,
+                        metadata=shard_metadata,
+                    )
+                ]
+            >>> st = ShardedTensor._init_from_local_shards(local_shards, tensor.size())
+            >>> sharding_dim = 1
+            >>> resharding_spec = ChunkShardingSpec(
+                    dim=sharding_dim,
+                    placements=[
+                        "rank:0/cuda:0",
+                        "rank:1/cuda:1",
+                        "rank:2/cuda:2",
+                        "rank:3/cuda:3",
+                    ],
+                )
+            >>> st.reshard(resharding_spec)
+            >>> tensor = st.local_shards()[0].tensor
+            >>> tensor
+            tensor([[1], [1], [3], [3], [5], [5], [7], [7]]) # Rank 0
+            tensor([[2], [2], [4], [4], [6], [6], [8], [8]]) # Rank 1
+            tensor([[3], [3], [5], [5], [7], [7], [9], [9]]) # Rank 2
+            tensor([[4], [4], [6], [6], [8], [8], [10], [10]]) # Rank 3
+        """
+        if not isinstance(
+            resharding_spec, shard_spec.ChunkShardingSpec
+        ) or not isinstance(self._sharding_spec, shard_spec.ChunkShardingSpec):
+            raise NotImplementedError("Only ChunkShardingSpec supported for reshard.")
+        if len(self.local_shards()) != 1:
+            raise NotImplementedError("Only single local shard supported for reshard.")
+
+        if self._sharding_spec.dim == resharding_spec.dim:  # type: ignore[attr-defined]
+            if self._sharding_spec.placements == resharding_spec.placements:  # type: ignore[attr-defined]
+                return self
+            else:
+                local_shards, shards_metadata = reshuffle_local_shard(
+                    self.local_tensor(),
+                    self.size(),  # type: ignore[arg-type]
+                    self._sharding_spec,
+                    resharding_spec,
+                    self._process_group,
+                )
+        else:
+            local_shards, shards_metadata = reshard_local_shard(
+                self.local_tensor(),
+                self.size(),  # type: ignore[arg-type]
+                self._sharding_spec,
+                resharding_spec,
+                self._process_group,
+            )
+        self._local_shards = local_shards
+        self._metadata.shards_metadata = shards_metadata
+        self._sharding_spec = resharding_spec
+        return self
+
+    def local_tensor(self) -> torch.Tensor:
+        """
+        Return local tensor for a sharded_tensor. For now we only support single local shard.
+
+        Returns:
+            A :class:`torch.Tensor` of the local shard.
+        """
+        if len(self.local_shards()) != 1:
+            raise NotImplementedError("Only single local shard is supported.")
+        return self.local_shards()[0].tensor
+
+    @classmethod
+    @deprecated(DEPRECATE_MSG, category=FutureWarning)
+    def __torch_function__(cls, func, types, args=(), kwargs=None):
+        def dispatch(st: ShardedTensor, func: Callable):
+            # Dispatch to custom user provided op first if it exists.
+            if func in _CUSTOM_SHARDED_OPS:
+                return _CUSTOM_SHARDED_OPS[func](types, args, kwargs, st._process_group)
+
+            # Dispatch to custom sharding spec op if it has one.
+            if _has_custom_op(st._sharding_spec, func):
+                return _dispatch_custom_op(
+                    st._sharding_spec, func, types, args, kwargs, st._process_group
+                )
+
+            if func in _SHARDED_OPS:
+                return _SHARDED_OPS[func](types, args, kwargs, st._process_group)
+
+            raise RuntimeError(
+                f"torch function '{func.__name__}', with args: {args} and "
+                f"kwargs: {kwargs} not supported for ShardedTensor!"
+            )
+
+        # Find ShardedTensor instance to get process_group and sharding_spec.
+        st_instance = None
+
+        def find_sharded_tensor(e):
+            nonlocal st_instance
+            if st_instance is None and isinstance(e, ShardedTensor):
+                st_instance = e
+
+        pytree.tree_map_(find_sharded_tensor, args)
+        pytree.tree_map_(find_sharded_tensor, kwargs)
+
+        if st_instance is not None:
+            return dispatch(st_instance, func)
+
+        raise RuntimeError(
+            f"torch function '{func.__name__}', with args: {args} and "
+            f"kwargs: {kwargs} not supported for ShardedTensor!"
+        )
+
+    def is_pinned(self) -> bool:  # type: ignore[override]
+        """
+        Returns True if the sharded tensor (each local shard) resides in pinned memory.
+        """
+        return self._metadata.tensor_properties.pin_memory
+
+    def _register_remote_shards(
+        self, remote_shards: List[rpc.RRef[Shard]], rpc_rank: int
+    ):
+        self._remote_shards[rpc_rank] = remote_shards
+
+    def remote_shards(self) -> Dict[int, List[rpc.RRef[Shard]]]:
+        """
+        Returns a Dict[int, RRef] with keys being the RPC rank and values
+        being RRefs to shards on that rank. Need to initialize the
+        RPC framework for this functionality.
+
+        Raises an exception if ShardedTensor was created with ``init_rrefs=False``
+        """
+        if not self._init_rrefs:
+            raise RuntimeError(
+                "ShardedTensor created with init_rrefs=False, no RRefs to remote shards available"
+            )
+        return self._remote_shards
+
+    def __hash__(self):
+        return id(self)
+
+    def __repr__(self):
+        return f"ShardedTensor({self._metadata})"
+
+    @dataclass
+    class ProcessGroupState:
+        """
+        State for ser-de of process group
+        """
+
+        local_rank: int
+        global_rank: int
+        local_world_size: int
+        global_world_size: int
+
+    def __getstate__(self):
+        pg_state = ShardedTensor.ProcessGroupState(
+            distributed_c10d.get_rank(self._process_group),
+            distributed_c10d.get_rank(),
+            distributed_c10d.get_world_size(self._process_group),
+            distributed_c10d.get_world_size(),
+        )
+
+        return (
+            self._local_shards,
+            self._metadata,
+            pg_state,
+            self._sharding_spec,
+            self._init_rrefs,
+        )
+
+    def __setstate__(self, state):
+        self._sharded_tensor_id = None
+        if not distributed_c10d.is_initialized():
+            raise RuntimeError(
+                "Need to initialize default process group using "
+                '"init_process_group" before loading ShardedTensor'
+            )
+
+        (
+            self._local_shards,
+            self._metadata,
+            pg_state,
+            self._sharding_spec,
+            self._init_rrefs,
+        ) = state
+
+        # Setup process group
+        from torch.distributed._shard.api import _get_current_process_group
+
+        self._process_group = _get_current_process_group()
+
+        # Validate process group.
+        local_rank = distributed_c10d.get_rank(self._process_group)
+        if pg_state.local_rank != local_rank:
+            raise RuntimeError(
+                f"Local rank at save time was {pg_state.local_rank}, but at "
+                f"load time was {local_rank}"
+            )
+
+        global_rank = distributed_c10d.get_rank()
+        if pg_state.global_rank != global_rank:
+            raise RuntimeError(
+                f"Global rank at save time was {pg_state.global_rank}, but at "
+                f"load time was {global_rank}"
+            )
+
+        local_world_size = distributed_c10d.get_world_size(self._process_group)
+        if pg_state.local_world_size != local_world_size:
+            raise RuntimeError(
+                f"Local world size at save time was {pg_state.local_world_size}, "
+                f"but at load time was {local_world_size}"
+            )
+
+        global_world_size = distributed_c10d.get_world_size()
+        if pg_state.global_world_size != global_world_size:
+            raise RuntimeError(
+                f"Global world size at save time was {pg_state.global_world_size}, "
+                f"but at load time was {global_world_size}"
+            )
+
+        self._post_init()
+
+
+def _create_tensor_from_params(
+    *size, local_device, tensor_properties: TensorProperties
+):
+    """Helper to construct tensor from size, device and common params."""
+    dtype = tensor_properties.dtype
+    layout = tensor_properties.layout
+    requires_grad = tensor_properties.requires_grad
+    memory_format = tensor_properties.memory_format
+    pin_memory = tensor_properties.pin_memory
+
+    return torch.empty(
+        *size,
+        dtype=dtype,
+        layout=layout,
+        device=local_device,
+        requires_grad=requires_grad,
+        memory_format=memory_format,
+        pin_memory=pin_memory,
+    )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/logger.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/logger.py
new file mode 100644
index 0000000000000000000000000000000000000000..ebb749dc7d5c7315028d6edd4ee6552360b48594
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/logger.py
@@ -0,0 +1,36 @@
+#!/usr/bin/env python3
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+import logging
+from typing import List, Tuple
+
+from torch.distributed._shard.sharded_tensor.logging_handlers import _log_handlers
+
+
+__all__: List[str] = []
+
+
+def _get_or_create_logger() -> logging.Logger:
+    logging_handler, log_handler_name = _get_logging_handler()
+    logger = logging.getLogger(f"sharding-spec-{log_handler_name}")
+    logger.setLevel(logging.DEBUG)
+    formatter = logging.Formatter(
+        "%(asctime)s %(filename)s:%(lineno)s %(levelname)s p:%(processName)s t:%(threadName)s: %(message)s"
+    )
+    logging_handler.setFormatter(formatter)
+    logger.propagate = False
+    logger.addHandler(logging_handler)
+    return logger
+
+
+def _get_logging_handler(
+    destination: str = "default",
+) -> Tuple[logging.Handler, str]:
+    log_handler = _log_handlers[destination]
+    log_handler_name = type(log_handler).__name__
+    return (log_handler, log_handler_name)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/logging_handlers.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/logging_handlers.py
new file mode 100644
index 0000000000000000000000000000000000000000..021ad100f06a89fa944d7e6dba18f1a9558d88f5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/logging_handlers.py
@@ -0,0 +1,17 @@
+#!/usr/bin/env python3
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+import logging
+from typing import Dict, List
+
+
+__all__: List[str] = []
+
+_log_handlers: Dict[str, logging.Handler] = {
+    "default": logging.NullHandler(),
+}
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/metadata.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/metadata.py
new file mode 100644
index 0000000000000000000000000000000000000000..e53ac25fa55d9c2a73dce027cf8e0785b8cba930
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/metadata.py
@@ -0,0 +1,95 @@
+# mypy: allow-untyped-defs
+from dataclasses import dataclass, field
+from enum import Enum
+from typing import List
+
+import torch
+from torch.distributed._shard.metadata import ShardMetadata
+
+
+class MEM_FORMAT_ENCODING(Enum):
+    TORCH_CONTIGUOUS_FORMAT = 0
+    TORCH_CHANNELS_LAST = 1
+    TORCH_PRESERVE_FORMAT = 2
+
+
+@dataclass
+class TensorProperties:
+    """Properties used to create :class:`Tensor`"""
+
+    # Regular tensor fields
+    dtype: torch.dtype = field(default=torch.get_default_dtype())
+    layout: torch.layout = field(default=torch.strided)
+    requires_grad: bool = False
+    memory_format: torch.memory_format = field(default=torch.contiguous_format)
+    pin_memory: bool = False
+
+    def __getstate__(self):
+        # Since torch.memory_format cannot be pickled!
+        memory_format = self.memory_format
+        if memory_format == torch.contiguous_format:
+            mem_format_encoding = MEM_FORMAT_ENCODING.TORCH_CONTIGUOUS_FORMAT
+        elif memory_format == torch.channels_last:
+            mem_format_encoding = MEM_FORMAT_ENCODING.TORCH_CHANNELS_LAST
+        elif memory_format == torch.preserve_format:
+            mem_format_encoding = MEM_FORMAT_ENCODING.TORCH_PRESERVE_FORMAT
+        else:
+            raise RuntimeError(f"Invalid torch.memory_format: {memory_format}")
+
+        return (
+            self.dtype,
+            self.layout,
+            self.requires_grad,
+            mem_format_encoding,
+            self.pin_memory,
+        )
+
+    def __setstate__(
+        self,
+        state,
+    ):
+        (
+            self.dtype,
+            self.layout,
+            self.requires_grad,
+            mem_format_encoding,
+            self.pin_memory,
+        ) = state
+
+        if mem_format_encoding == MEM_FORMAT_ENCODING.TORCH_CONTIGUOUS_FORMAT:
+            memory_format = torch.contiguous_format
+        elif mem_format_encoding == MEM_FORMAT_ENCODING.TORCH_CHANNELS_LAST:
+            memory_format = torch.channels_last
+        elif mem_format_encoding == MEM_FORMAT_ENCODING.TORCH_PRESERVE_FORMAT:
+            memory_format = torch.preserve_format
+        else:
+            raise RuntimeError(
+                f"Invalid torch.memory_format encoding: {mem_format_encoding}"
+            )
+
+        self.memory_format = memory_format
+
+    @staticmethod
+    def create_from_tensor(tensor: torch.Tensor) -> "TensorProperties":
+        return TensorProperties(
+            dtype=tensor.dtype,
+            layout=tensor.layout,
+            requires_grad=tensor.requires_grad,
+            memory_format=torch.contiguous_format,
+            pin_memory=tensor.is_pinned(),
+        )
+
+
+@dataclass
+class ShardedTensorMetadata:
+    """
+    Represents metadata for :class:`ShardedTensor`
+    """
+
+    # Metadata about each shard of the Tensor
+    shards_metadata: List[ShardMetadata] = field(default_factory=list)
+
+    # Size of each dim of the overall Tensor.
+    size: torch.Size = field(default=torch.Size([]))
+
+    tensor_properties: TensorProperties = field(default_factory=TensorProperties)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/reshard.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/reshard.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a82012d59cd3f276e7aacafaa690989bc3378f3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/reshard.py
@@ -0,0 +1,246 @@
+# mypy: allow-untyped-defs
+import copy
+from typing import List, Tuple
+
+import torch
+import torch.distributed as dist
+import torch.distributed._shard.sharding_spec as shard_spec
+from torch._C._distributed_c10d import ProcessGroup
+from torch.distributed._shard.metadata import ShardMetadata
+from torch.distributed._shard.sharding_spec._internals import (
+    get_chunked_dim_size,
+    get_split_size,
+)
+from torch.distributed.nn.functional import all_to_all, all_to_all_single
+
+from .shard import Shard
+
+
+def get_idx_from_placements(placements, current_rank) -> int:
+    """
+    Return the position of the current rank in the given placements.
+
+    Args:
+        placements(List[Union[_remote_device, str]]):
+            Specifies the placement of each shard of the Tensor. The size of
+            the list represents the number of shards to be created. This could
+            be a list of
+            :class:`torch.distributed._remote_device`'s. This list
+            could also contain a string which represents remote
+            device as accepted by
+            :class:`torch.distributed._remote_device`
+        current_rank (int): number of current device.
+
+    Returns:
+        A int which contains the position of current device in the placement list.
+    """
+    for idx, placement in enumerate(placements):  # type: ignore[attr-defined]
+        if current_rank == placement.rank():  # type: ignore[union-attr]
+            return idx
+    raise RuntimeError("current_rank not in the placement.")
+
+
+def build_reshard_metadata(
+    st_size: torch.Size,
+    sharding_spec: shard_spec.ShardingSpec,
+    world_size: int,
+) -> Tuple[List[ShardMetadata], List[int]]:
+    """
+    Based the given sharding spec, we calculate the offset and local shard size.
+    We then build a ShardMetadata on top of the calculation result.
+
+    Args:
+        st_size (torch.Size): The size of the sharded tensor.
+        sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The
+            specification describing how the tensor is sharded.
+        world_size (int): number of ranks.
+
+    Returns:
+        A Tuple of the followings:
+            A List[`ShardMetadata`] which contains the metadata for the shard, including
+                offsets, lengths and device placement.
+            A List[int] which contains the ranks in the order of placement.
+    """
+    shard_dim = int(sharding_spec.dim)  # type: ignore[attr-defined]
+    shards_metadata = [None] * world_size
+    ranks = []
+    offsets = [0] * len(st_size)
+    split_size = get_split_size(st_size[shard_dim], world_size)
+    for idx, placement in enumerate(sharding_spec.placements):  # type: ignore[attr-defined]
+        ranks.append(placement.rank())
+        sharded_dim_size = get_chunked_dim_size(st_size[shard_dim], split_size, idx)
+        local_tensor_size = list(st_size)
+        local_tensor_size[shard_dim] = sharded_dim_size
+        shards_metadata[placement.rank()] = ShardMetadata(  # type: ignore[call-overload]
+            shard_offsets=copy.deepcopy(offsets),
+            shard_sizes=local_tensor_size,
+            placement=placement,
+        )
+        offsets[shard_dim] += sharded_dim_size
+    return shards_metadata, ranks  # type: ignore[return-value]
+
+
+def reshuffle_local_shard(
+    local_shard: torch.Tensor,
+    st_size: torch.Size,
+    sharding_spec: shard_spec.ShardingSpec,
+    resharding_spec: shard_spec.ShardingSpec,
+    pg: ProcessGroup,
+) -> Tuple[List[Shard], List[ShardMetadata]]:
+    """
+    Reshuffle the local shard directly when the reshard dim is same as the original
+    sharding dim. Logically we do this in two step:
+    1. To collect all shards based on original sharding spec.
+    2. Reshard the tensor based on the given resharding spec.
+
+    In reality, we consolidate the two steps into one by sending the local tensor to
+    the new shard directly based on the resharding spec.
+
+    Args:
+        local_shard (Tensor): Local tensor stored in the current rank.
+        st_size (torch.Size): The size of the sharded tensor.
+        sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The
+            specification describing how the tensor is sharded originally.
+        resharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The
+            specification describing how the tensor will be resharded.
+        pg (ProcessGroup): The process group to aggregate on.
+
+    Returns:
+        A Tuple of the followings:
+            A List[`Shard`] which contains the local tensor and its metadata.
+            A List[`ShardMetadata`] which contains the metadata for the shard, including
+                offsets, lengths and device placement.
+    """
+    current_rank = dist.get_rank(pg)
+    world_size = dist.get_world_size(pg)
+    # Build shards_metadata first.
+    shards_metadata, ranks = build_reshard_metadata(
+        st_size, resharding_spec, world_size
+    )
+    # Get input split size for all2all.
+    reshard_dim = int(resharding_spec.dim)  # type: ignore[attr-defined]
+    split_size = get_split_size(st_size[reshard_dim], world_size)
+    input_split_sizes = [0] * world_size
+    idx = get_idx_from_placements(sharding_spec.placements, current_rank)  # type: ignore[attr-defined]
+    new_rank = resharding_spec.placements[idx].rank()  # type: ignore[union-attr, attr-defined]
+    input_split_sizes[new_rank] = local_shard.size(reshard_dim)
+    # Get output split size for all2all.
+    output_split_sizes = [0] * world_size
+    new_idx = ranks.index(current_rank)
+    sharded_dim_size = get_chunked_dim_size(st_size[reshard_dim], split_size, new_idx)
+    output_split_sizes[new_rank] = sharded_dim_size
+    # Get gathered_input for all2all.
+    local_shard = local_shard.transpose(0, reshard_dim).contiguous()
+    gathered_input_size = list(local_shard.size())
+    gathered_input_size[0] = sharded_dim_size
+    gathered_input = torch.empty(
+        gathered_input_size, device=local_shard.device, dtype=local_shard.dtype
+    )
+    # all2all.
+    local_shard = all_to_all_single(
+        gathered_input,
+        local_shard,
+        input_split_sizes=input_split_sizes,
+        output_split_sizes=output_split_sizes,
+        group=pg,
+    )
+    local_tensor = local_shard.transpose(0, reshard_dim).contiguous()
+    local_shards = [Shard(local_tensor, shards_metadata[current_rank])]
+    return local_shards, shards_metadata
+
+
+def reshard_local_shard(
+    local_tensor: torch.Tensor,
+    st_size: torch.Size,
+    sharding_spec: shard_spec.ShardingSpec,
+    resharding_spec: shard_spec.ShardingSpec,
+    pg: ProcessGroup,
+) -> Tuple[List[Shard], List[ShardMetadata]]:
+    """
+    Reshard a sharded tensor given the ``resharding_spec``. When the reshard dim is
+    different from the original sharding dim, we need to do two steps logically:
+    1. To collect all shards based on original sharding spec.
+    2. Reshard the tensor based on the given resharding spec.
+
+    In reality, we consolidate the two steps into one by sending each rank the new
+    shard based on the resharding spec.
+
+    Args:
+        local_tensor (Tensor): Local tensor stored in the current rank.
+        st_size (torch.Size): The size of the sharded tensor.
+        sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The
+            specification describing how the tensor is sharded originally.
+        resharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The
+            specification describing how the tensor will be resharded.
+        pg (ProcessGroup): The process group to aggregate on.
+
+    Returns:
+        A Tuple of the followings:
+            A List[`Shard`] which contains the local tensor and its metadata.
+            A List[`ShardMetadata`] which contains the metadata for the shard, including
+                offsets, lengths and device placement.
+    """
+    current_rank = dist.get_rank(pg)
+    world_size = dist.get_world_size(pg)
+    current_sharding_dim = int(sharding_spec.dim)  # type: ignore[attr-defined]
+    reshard_dim = int(resharding_spec.dim)  # type: ignore[attr-defined]
+
+    # Build shards_metadata first.
+    shards_metadata, ranks = build_reshard_metadata(
+        st_size, resharding_spec, world_size
+    )
+
+    # Compute expected size
+    input_split_sizes = []
+    for metadata in shards_metadata:
+        input_split_sizes.append(metadata.shard_sizes[reshard_dim])
+    rearrange_input = any(ranks[i] > ranks[i + 1] for i in range(len(ranks) - 1))
+
+    if rearrange_input:
+        # Need to re-arrange reshard_dim of local_tensor before all2all.
+        indices: List[int] = []
+        for metadata in shards_metadata:
+            offset_start_idx = metadata.shard_offsets[reshard_dim]
+            split_size = metadata.shard_sizes[reshard_dim]
+            indices += range(offset_start_idx, offset_start_idx + split_size)
+        local_tensor = local_tensor.index_select(
+            reshard_dim, torch.tensor(indices, device=local_tensor.device)
+        )
+
+    # Because reshard_dim != original shard_dim. We need to compute the
+    # size of tensor from each rank.
+    output_tensor_list = [torch.tensor(1)] * world_size
+    split_size = get_split_size(st_size[current_sharding_dim], world_size)
+    rearrange_output_list = False
+    indices = []
+    for idx, placement in enumerate(sharding_spec.placements):  # type: ignore[attr-defined]
+        sharded_dim_size = get_chunked_dim_size(
+            st_size[current_sharding_dim], split_size, idx
+        )
+        output_tensor_size = list(st_size)
+        output_tensor_size[current_sharding_dim] = sharded_dim_size
+        output_tensor_size[reshard_dim] = input_split_sizes[current_rank]
+        output_tensor_list[
+            placement.rank()
+        ] = torch.empty(  # type: ignore[union-attr, index]
+            output_tensor_size, device=local_tensor.device, dtype=local_tensor.dtype
+        )
+        indices.append(placement.rank())  # type: ignore[union-attr, index, arg-type]
+        if idx != placement.rank():  # type: ignore[union-attr]
+            rearrange_output_list = True
+
+    # Perform autograd enabled all2all.
+    input_tensor_tuple = torch.split(local_tensor, input_split_sizes, dim=reshard_dim)
+    input_tensor_list = [tensor.contiguous() for tensor in input_tensor_tuple]
+    output_tensor_list = all_to_all(
+        output_tensor_list,
+        input_tensor_list,
+        group=pg,
+    )
+
+    if rearrange_output_list:
+        # Need to re-arrange original shard_dim of output_tensor_list.
+        output_tensor_list = [output_tensor_list[idx] for idx in indices]  # type: ignore[call-overload]
+    local_tensor = torch.cat(output_tensor_list, dim=current_sharding_dim)
+    local_shards = [Shard(local_tensor, shards_metadata[current_rank])]
+    return local_shards, shards_metadata
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/shard.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/shard.py
new file mode 100644
index 0000000000000000000000000000000000000000..dcb6b3b5d626748911c8aa8ce00605ce0a6d319c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/shard.py
@@ -0,0 +1,63 @@
+# mypy: allow-untyped-defs
+from dataclasses import dataclass
+from typing import List
+
+import torch
+from torch.distributed._shard.metadata import ShardMetadata
+from torch.distributed.remote_device import _remote_device
+
+
+@dataclass
+class Shard:
+    """
+    Container which holds the data for a shard as a Tensor and also
+    the associated metadata for that shard.
+
+    Args:
+        tensor(torch.Tensor): Local tensor for the shard.
+        metadata(:class `torch.distributed._shard.sharded_tensor.ShardMetadata`):
+            The metadata for the shard, including offsets, lengths and device placement.
+    """
+
+    __slots__ = ["tensor", "metadata"]
+    tensor: torch.Tensor
+    metadata: ShardMetadata
+
+    def __post_init__(self):
+        # verification between local tensor and metadata
+        if list(self.tensor.size()) != self.metadata.shard_sizes:
+            raise ValueError(
+                "Shard tensor size does not match with metadata.shard_lengths! "
+                f"Found shard tensor size: {list(self.tensor.size())}, "
+                f"metadata.shard_lengths: {self.metadata.shard_sizes}, "
+            )
+        placement_device = self.metadata.placement
+        if (
+            placement_device is not None
+            and placement_device.device() != self.tensor.device
+        ):
+            raise ValueError(
+                f"Local shard tensor device does not match with local Shard's placement! "
+                f"Found local shard tensor device: {self.tensor.device}, "
+                f"local shard metadata placement device: {placement_device.device()}"
+            )
+
+    @classmethod
+    def from_tensor_and_offsets(
+        cls, tensor: torch.Tensor, shard_offsets: List[int], rank: int
+    ):
+        """
+        Creates a Shard of a ShardedTensor from a local torch.Tensor, shard_offsets and rank.
+
+        Args:
+            tensor(torch.Tensor): Local tensor for the shard.
+            shard_offsets(List[int]): List of integers specify the offset
+                of the shard on each dimension.
+            rank(int): Specify the rank for the shard.
+        """
+        shard_sizes = list(tensor.size())
+        placement = _remote_device(f"rank:{rank}/{str(tensor.device)}")
+        shard_meta = ShardMetadata(
+            shard_offsets=shard_offsets, shard_sizes=shard_sizes, placement=placement
+        )
+        return Shard(tensor, shard_meta)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6954813f82b27a8850dde4dc5d64ef257f9a5bc
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharded_tensor/utils.py
@@ -0,0 +1,267 @@
+# mypy: allow-untyped-defs
+import collections.abc
+import copy
+from typing import List, Optional, Sequence, TYPE_CHECKING
+
+import torch
+from torch.distributed import distributed_c10d as c10d, rpc
+from torch.distributed._shard.sharding_spec._internals import (
+    check_tensor,
+    validate_non_overlapping_shards_metadata,
+)
+
+from .metadata import ShardedTensorMetadata, TensorProperties
+from .shard import Shard
+
+
+if TYPE_CHECKING:
+    from torch.distributed._shard.metadata import ShardMetadata
+
+
+def _parse_and_validate_remote_device(pg, remote_device):
+    if remote_device is None:
+        raise ValueError("remote device is None")
+
+    worker_name = remote_device.worker_name()
+    rank = remote_device.rank()
+    device = remote_device.device()
+
+    # Validate rank, skip validation if rank is not part of process group.
+    if rank is not None and not c10d._rank_not_in_group(pg):
+        pg_global_ranks = c10d.get_process_group_ranks(pg)
+        if rank not in pg_global_ranks:
+            raise ValueError(
+                f"Global rank {rank} does not exist in input process group: {pg_global_ranks}"
+            )
+
+    if worker_name is not None:
+        if not rpc._is_current_rpc_agent_set():
+            raise RuntimeError(
+                f"RPC framework needs to be initialized for using worker names: {worker_name}"
+            )
+
+        workers = rpc._get_current_rpc_agent().get_worker_infos()
+        for worker in workers:
+            if worker.name == worker_name:
+                return worker.id, device
+
+        raise ValueError(f"Invalid worker name: {worker_name}")
+
+    return rank, device
+
+
+def _validate_output_tensor_for_gather(
+    my_rank: int,
+    dst_rank: int,
+    size: torch.Size,
+    dst_tensor: Optional[torch.Tensor],
+) -> None:
+    if dst_rank == my_rank:
+        if dst_tensor is None:
+            raise ValueError(
+                f"Argument ``dst_tensor`` must be specified on destination rank {dst_rank}"
+            )
+        if tuple(size) != (dst_tensor.size()):
+            raise ValueError(
+                f"Argument ``dst_tensor`` have size {tuple(dst_tensor.size())},"
+                f"but should be {tuple(size)}"
+            )
+    elif dst_tensor:
+        raise ValueError(
+            "Argument ``dst_tensor`` must NOT be specified " "on non-destination ranks."
+        )
+
+
+def _flatten_tensor_size(size) -> torch.Size:
+    """
+    Checks if tensor size is valid, then flatten/return a torch.Size object.
+    """
+    if len(size) == 1 and isinstance(size[0], collections.abc.Sequence):
+        dims = list(*size)
+    else:
+        dims = list(size)
+
+    for dim in dims:
+        if not isinstance(dim, int):
+            raise TypeError(f"size has to be a sequence of ints, found: {dims}")
+
+    return torch.Size(dims)
+
+
+def _raise_if_mismatch(expected, actual, prop_name, ranks, is_local=True):
+    if is_local:
+        assert isinstance(ranks, int)
+        if expected != actual:
+            raise ValueError(
+                f"Local shards' tensor {prop_name} property need to be the same on rank:{ranks}! "
+                f"Found one local shard tensor {prop_name}={expected}, "
+                f"the other local shard tensor {prop_name}={actual}."
+            )
+    else:
+        # compare failure check across ranks, ranks list should have two rank
+        assert len(ranks) == 2
+        if expected != actual:
+            raise ValueError(
+                f"ShardedTensor {prop_name} property does not match from different ranks! "
+                f"Found {prop_name}={expected} on rank:{ranks[0]}, "
+                f"and {prop_name}={actual} on rank:{ranks[1]}."
+            )
+
+
+def build_metadata_from_local_shards(
+    local_shards: List[Shard],
+    global_size: torch.Size,
+    current_rank: int,
+    pg: c10d.ProcessGroup,
+) -> ShardedTensorMetadata:
+    assert len(local_shards) > 0, "must have local shards!"
+    local_shard_metadatas: List[ShardMetadata] = []
+
+    first_shard_dtype = local_shards[0].tensor.dtype
+    first_shard_layout = local_shards[0].tensor.layout
+    first_shard_requires_grad = local_shards[0].tensor.requires_grad
+    first_shard_is_pinned = local_shards[0].tensor.is_pinned()
+
+    # 1). Validate local tensors and associated metadatas
+    for local_shard in local_shards:
+        local_shard_tensor = local_shard.tensor
+        local_shard_meta = local_shard.metadata
+        local_shard_metadatas.append(local_shard_meta)
+        rank, local_device = _parse_and_validate_remote_device(
+            pg, local_shard_meta.placement
+        )
+
+        if (
+            local_shard_tensor.layout != torch.strided
+            or local_shard_tensor.layout != first_shard_layout
+        ):
+            raise ValueError(
+                f"Only torch.strided layout is currently supported, but found "
+                f"{local_shard_tensor.layout} on rank:{current_rank}!"
+            )
+
+        if not local_shard_tensor.is_contiguous():
+            raise ValueError(
+                "Only torch.contiguous_format memory_format is currently supported!"
+            )
+
+        if rank != current_rank:
+            raise ValueError(
+                f"Local shard metadata's rank does not match with the rank in its process group! "
+                f"Found current rank in the process group: {current_rank}, "
+                f"local ShardMetadata placement's rank: {rank}"
+            )
+        if local_shard_tensor.device != local_device:
+            raise ValueError(
+                f"Local shard tensor device does not match with local Shard's placement! "
+                f"Found local shard tensor device: {local_shard_tensor.device}, "
+                f"local shard metadata placement device: {local_device}"
+            )
+
+        _raise_if_mismatch(
+            local_shard_meta.shard_sizes,
+            list(local_shard_tensor.size()),
+            "size",
+            current_rank,
+        )
+        _raise_if_mismatch(
+            local_shard_tensor.is_pinned(),
+            first_shard_is_pinned,
+            "pin_memory",
+            current_rank,
+        )
+        _raise_if_mismatch(
+            local_shard_tensor.dtype, first_shard_dtype, "dtype", current_rank
+        )
+        _raise_if_mismatch(
+            local_shard_tensor.requires_grad,
+            first_shard_requires_grad,
+            "requires_grad",
+            current_rank,
+        )
+
+    # 2). Build a "local" ShardedTensorMetadata with all local shards on this rank, then
+    #    do all_gather to collect local_sharded_tensor_metadata from all ranks
+    local_tensor_properties = TensorProperties(
+        dtype=first_shard_dtype,
+        layout=first_shard_layout,
+        requires_grad=first_shard_requires_grad,
+        memory_format=torch.contiguous_format,
+        pin_memory=first_shard_is_pinned,
+    )
+
+    local_sharded_tensor_metadata = ShardedTensorMetadata(
+        shards_metadata=local_shard_metadatas,
+        size=global_size,
+        tensor_properties=local_tensor_properties,
+    )
+
+    return local_sharded_tensor_metadata
+
+
+def build_global_metadata(
+    gathered_metadatas: Sequence[Optional[ShardedTensorMetadata]],
+):
+    global_sharded_tensor_metadata = None
+    global_metadata_rank = 0
+
+    for rank, rank_metadata in enumerate(gathered_metadatas):
+        if rank_metadata is None:
+            continue
+
+        if global_sharded_tensor_metadata is None:
+            global_sharded_tensor_metadata = copy.deepcopy(rank_metadata)
+            global_metadata_rank = rank
+        else:
+            _raise_if_mismatch(
+                global_sharded_tensor_metadata.size,
+                rank_metadata.size,
+                "global_size",
+                [global_metadata_rank, rank],
+                is_local=False,
+            )
+
+            # don't need to check layout and memory format as we already checked in local shards validation stage
+            _raise_if_mismatch(
+                global_sharded_tensor_metadata.tensor_properties.dtype,
+                rank_metadata.tensor_properties.dtype,
+                "dtype",
+                [global_metadata_rank, rank],
+                is_local=False,
+            )
+
+            _raise_if_mismatch(
+                global_sharded_tensor_metadata.tensor_properties.requires_grad,
+                rank_metadata.tensor_properties.requires_grad,
+                "requires_grad",
+                [global_metadata_rank, rank],
+                is_local=False,
+            )
+
+            _raise_if_mismatch(
+                global_sharded_tensor_metadata.tensor_properties.pin_memory,
+                rank_metadata.tensor_properties.pin_memory,
+                "pin_memory",
+                [global_metadata_rank, rank],
+                is_local=False,
+            )
+            # pass all validations, extend shards metadata
+            global_sharded_tensor_metadata.shards_metadata.extend(
+                rank_metadata.shards_metadata
+            )
+
+    if global_sharded_tensor_metadata is not None:
+        # check if shards_metadata have overlap shards
+        validate_non_overlapping_shards_metadata(
+            global_sharded_tensor_metadata.shards_metadata
+        )
+
+        # check if the shards_metadata is compatible with global size of the sharded tensor.
+        check_tensor(
+            global_sharded_tensor_metadata.shards_metadata,
+            global_sharded_tensor_metadata.size,
+        )
+    else:
+        raise ValueError("ShardedTensor have no local shards on all ranks!")
+
+    return global_sharded_tensor_metadata
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharder.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharder.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d91ec15775bea870b81c4b10fb1443a3fba0977
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharder.py
@@ -0,0 +1,29 @@
+import abc
+
+import torch.nn as nn
+
+
+class Sharder(abc.ABC):
+    """
+    This is an interface which allows user to create more advanced
+    sharding strategies that are not easily be composed by the
+    `ShardingSpec`.
+
+    :class:`torch.distributed._shard.sharding_plan.ShardingPlan` could
+    take an object of the `Sharder` and call `shard` to shard the module,
+    then replace the original module with sharded module returned.
+    """
+
+    @abc.abstractmethod
+    def shard(self, module: nn.Module) -> nn.Module:
+        """
+        Shard a module base on the implementation of this method, and
+        return the sharded version of the module.
+
+        Args:
+            module (:class:`torch.nn.Module`):
+                The module to apply sharding to.
+        Returns:
+            A :class:`torch.nn.Module` object that represents a module
+            that's already been sharded.
+        """
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_plan/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_plan/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..325f7d7eb47b96a79fdc10cc2d1f072cdec9b4ce
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_plan/__init__.py
@@ -0,0 +1 @@
+from .api import ShardingPlan, ShardingPlanner
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_plan/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_plan/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1e7eff2aca63de6f2644f47016096418bef63c5c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_plan/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_plan/__pycache__/api.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_plan/__pycache__/api.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..754e39bb50ff427e00bc83fa8b2add304abfb90b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_plan/__pycache__/api.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_plan/api.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_plan/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..217ef8dab1e90fa7683ad2f5267cba6592985afe
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_plan/api.py
@@ -0,0 +1,87 @@
+import abc
+from dataclasses import dataclass
+from typing import Dict, List, Optional, Union
+
+import torch.nn as nn
+from torch.distributed._shard.sharder import Sharder
+from torch.distributed._shard.sharding_spec import ShardingSpec
+
+
+@dataclass
+class ShardingPlan:
+    """
+    Representation of a sharding plan, describes how to shard a module
+    across hosts. `plan` is used to shard module parameters according to the spec provided,
+    `output_plan` and `return_local_tensor` are optional, they are used to specify the output
+    layout of a module with a spec, and when to convert back to data parallel fashion.
+
+    Args:
+        plan (Dict[str, Union[:class:`torch.distributed._shard.sharding_spec.ShardingSpec`,
+              :class:`torch.distributed._shard.sharder.Sharder`]):
+            a dict describes how to shard a module, there're currently two ways to shard a module:
+                1. directly shard a module parameter by a `ShardingSpec`, keyed by the name of
+                   a parameter to a `ShardingSpec`.
+                2. shard a submodule by applying a `Sharder` on it, keyed by the name of a module
+                   to a `Sharder` object.
+        output_plan (Dict[str, :class:`torch.distributed._shard.sharding_spec.ShardingSpec`), optional):
+            a dict specifies the layout of a module's output which produces a ShardedTensor,
+            keyed by the name of module to ShardingSpec("" in key means the root module).
+            Default: `None`
+        return_local_tensor (List[str], optional): a list of string, each element enables
+            a module's sharded output to be returned as a Tensor from its local shards to
+            ensure further processing in a data parallel fashion. ("" in list means the
+            root module).
+            Default: None
+    Example:
+      Suppose we want to shard a module with two linear layers and then run it with DDP, we also
+      want to convert the output of the second linear layer back to DDP, we can do it as follows:
+
+        >>> # xdoctest: +REQUIRES(module:torch._C._distributed_c10d)
+        >>> class MyModule(nn.Module):
+        >>>     def __init__(self) -> None:
+        >>>        super().__init__()
+        >>>        self.fc1 = nn.Linear()
+        >>>        self.gelu = nn.GELU()
+        >>>        self.fc2 = nn.Linear()
+        >>>        self.relu = nn.Linear()
+        >>>
+        >>>     def forward(self, input):
+        >>>         return self.relu(self.fc2(self.gelu(self.fc1(input))))
+
+
+        >>> # xdoctest: +SKIP("Undefined spec1, spec2)
+        >>> sharding_plan = ShardingPlan(
+        >>>    plan={
+        >>>        "fc1.weight": spec1,
+        >>>        "fc2.weight": spec2
+        >>>    },
+        >>>    output_plan={
+        >>>        "fc2": output_spec
+        >>>    },
+        >>>    return_local_tensor=["fc2"]
+        >>> )
+    """
+
+    plan: Dict[str, Union[ShardingSpec, Sharder]]
+    output_plan: Optional[Dict[str, ShardingSpec]] = None
+    return_local_tensor: Optional[List[str]] = None
+
+
+class ShardingPlanner(abc.ABC):
+    """
+    Default ShardingPlanner interface, can be extended and
+    implement advanced sharding strategies.
+    """
+
+    @abc.abstractmethod
+    def build_plan(self, module: nn.Module) -> ShardingPlan:
+        """
+        Given a nn.Module, define how to shard the module across
+        ranks, return a ShardingPlan
+        Args:
+            module (:class:`torch.nn.Module`):
+                The module to apply sharding to.
+        Returns:
+            A :class:`torch.distributed._shard.sharding_plan.ShardingPlan` object that
+            represents how to shard the module.
+        """
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..bfd3f0a7581e8c4352eba843af6d3751bee7f387
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/__init__.py
@@ -0,0 +1,10 @@
+from torch.distributed._shard.metadata import ShardMetadata
+
+from .api import (
+    _infer_sharding_spec_from_shards_metadata,
+    DevicePlacementSpec,
+    EnumerableShardingSpec,
+    PlacementSpec,
+    ShardingSpec,
+)
+from .chunk_sharding_spec import ChunkShardingSpec as ChunkShardingSpec
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c8f0e8dd97acd4c30d2a6b1065deed1f344568b3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/__pycache__/_internals.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/__pycache__/_internals.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3c96a505aed3c6aba63311bf080471ba92149370
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/__pycache__/_internals.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/__pycache__/api.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/__pycache__/api.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..195ff606f87188586a4f55f2a1234ae084f650d6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/__pycache__/api.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/__pycache__/chunk_sharding_spec.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/__pycache__/chunk_sharding_spec.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c2637c13ffbdba2695428a187ed40f48b11e6bc9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/__pycache__/chunk_sharding_spec.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/_internals.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/_internals.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a439c447eff077dbb5bf0c0fff254062d346879
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/_internals.py
@@ -0,0 +1,217 @@
+# mypy: allow-untyped-defs
+from typing import List, Optional, Tuple
+
+from torch.distributed._shard.metadata import ShardMetadata
+
+
+def _check_shard_metadata_pair_overlap(shard1: ShardMetadata, shard2: ShardMetadata):
+    """
+    Checks if two shards overlap.
+    """
+
+    # For each dim of each shard, check if one shard resides on the other
+    # end of second shard with respect to that dim. As an example for a 2D
+    # shard, we would check if one shard is above or on the left of the
+    # other shard.
+    ndims = len(shard1.shard_offsets)
+    for i in range(ndims):
+        if shard1.shard_offsets[i] >= shard2.shard_offsets[i] + shard2.shard_sizes[i]:
+            return False
+        if shard2.shard_offsets[i] >= shard1.shard_offsets[i] + shard1.shard_sizes[i]:
+            return False
+
+    return True
+
+
+def _find_nd_overlapping_shards(
+    shards: List[ShardMetadata], sharded_dims: List[int]
+) -> Optional[Tuple[int, int]]:
+    # Each rank has len(sharded_dims) tuples. Each tuple represent the
+    # [begin, end] (inclusive) pair of that dimension.
+    shard_intervals = [
+        [
+            (s.shard_offsets[dim], s.shard_offsets[dim] + s.shard_sizes[dim] - 1)
+            for dim in sharded_dims
+        ]
+        for s in shards
+    ]
+
+    for i in range(len(shards)):
+        shard_i = shard_intervals[i]
+        for j in range(i + 1, len(shards)):
+            shard_j = shard_intervals[j]
+            # For each dim of each shard, check if one shard resides on the other
+            # end of second shard with respect to that dim. As an example for a 2D
+            # shard, we would check if one shard is above or on the left of the
+            # other shard.
+            overlap = True
+            for interval_i, interval_j in zip(shard_i, shard_j):
+                if interval_i[0] > interval_j[1] or interval_j[0] > interval_i[1]:
+                    overlap = False
+                    break
+            if overlap:
+                return (i, j)
+    return None
+
+
+def _find_1d_overlapping_shards(
+    shards: List[ShardMetadata], dim: int
+) -> Optional[Tuple[int, int]]:
+    # (begin, end, index_in_shards). Begin and end are inclusive.
+    intervals = [
+        (s.shard_offsets[dim], s.shard_offsets[dim] + s.shard_sizes[dim] - 1, i)
+        for i, s in enumerate(shards)
+    ]
+    intervals.sort()
+    for i in range(len(shards) - 1):
+        if intervals[i][1] >= intervals[i + 1][0]:
+            return (intervals[i][2], intervals[i + 1][2])
+    return None
+
+
+def validate_non_overlapping_shards_metadata(shards: List[ShardMetadata]):
+    """
+    Ensures none of the shards overlap with each other.
+
+    Args:
+        shards(List[ShardMetadata]): List of :class:`ShardMetadata` objects representing
+            each shard.
+    Raises:
+        ``ValueError`` if there's overlap in any two shards.
+    """
+    if not shards or len(shards) == 1:
+        return
+
+    sharded_dims: List[int] = []
+    for dim in range(len(shards[0].shard_offsets)):
+        for i in range(1, len(shards)):
+            if (
+                shards[i].shard_offsets[dim] != shards[0].shard_offsets[dim]
+                or shards[i].shard_sizes[dim] != shards[0].shard_sizes[dim]
+            ):
+                sharded_dims.append(dim)
+                break
+
+    pair: Optional[Tuple[int, int]] = None
+    if len(sharded_dims) == 0:
+        # All shards are the same, all dims are not partitioned. Choose any 2.
+        pair = (0, 1)
+    elif len(sharded_dims) == 1:
+        # Shards are partitioned over only one dimension. Overlap can be found
+        # using a O(nlogn) overlapping interval algorithm.
+        pair = _find_1d_overlapping_shards(shards, sharded_dims[0])
+    else:
+        # Shards are partitioned over more than one dimension. Fall back to
+        # pair-wise check. Even though O(nlogn) algorithms (line sweep) exist
+        # for 2D overlap, the implementation is not trivial and may not justify
+        # the time saving in most cases.
+        pair = _find_nd_overlapping_shards(shards, sharded_dims)
+
+    if pair:
+        raise ValueError(f"Shards {shards[pair[0]]} and {shards[pair[1]]} overlap")
+
+
+def check_tensor(shards_metadata, tensor_dims) -> None:
+    """
+    Checks if the shards_metadata is compatible with the provided tensor dims.
+
+    Args:
+        shards_metadata(List[ShardMetadata]): List of :class:`ShardMetadata`
+            objects representing each shard of the tensor.
+        tensor_dims(Sequence of int): Dimensions of tensor to verify
+    Raises:
+        ``ValueError`` if not compatible.
+    """
+
+    # If the tensor's volume matches the total volume of all shards and
+    # all shard boundaries are within tensor dims, we have a compatible
+    # sharding spec for this tensor. Note that we have already verified
+    # we don't have overlapping shards.
+    tensor_rank = len(tensor_dims)
+    shards_rank = len(shards_metadata[0].shard_offsets)
+    if tensor_rank != shards_rank:
+        raise ValueError(
+            f"Rank of tensor is {tensor_rank}, but shards rank is {shards_rank}"
+        )
+
+    total_shard_volume = 0
+    for shard in shards_metadata:
+        shard_volume = 1
+        for i, shard_length in enumerate(shard.shard_sizes):
+            shard_volume *= shard_length
+            if shard.shard_offsets[i] + shard.shard_sizes[i] > tensor_dims[i]:
+                raise ValueError(
+                    f"Shard offset {shard.shard_offsets[i]} and length "
+                    f"{shard.shard_sizes[i]} exceeds tensor dim: {tensor_dims[i]} for shard {shard}"
+                )
+        total_shard_volume += shard_volume
+
+    tensor_volume = 1
+    for size in tensor_dims:
+        tensor_volume *= size
+
+    if total_shard_volume != tensor_volume:
+        # TODO: Can we improve this error message to point out the gaps?
+        raise ValueError(
+            f"Total volume of shards: {total_shard_volume} "
+            f"does not match tensor volume: {tensor_volume}, in other words "
+            f"all the individual shards do not cover the entire tensor"
+        )
+
+
+def get_split_size(dim_size, chunks):
+    """
+    Computes the split size inline with ``torch.chunk``
+
+    Args:
+        dim_size(int): Size of the dimension being chunked.
+        chunks(int): Number of chunks to create for ``dim_size``.
+
+    Returns:
+        An int indicating the split size to use.
+    """
+    return (dim_size + chunks - 1) // chunks
+
+
+def get_chunked_dim_size(dim_size, split_size, idx):
+    """
+    Computes the dim size of the chunk for provided ``idx`` given ``dim_size``
+    and ``split_size``.
+
+    Args:
+        dim_size(int): Size of the dimension being chunked.
+        split_size(int): The chunk size for each chunk of ``dim_size``.
+        idx(int): The index of chunk whose dim size is being requested.
+
+    Returns:
+        An int indicating the dim size of the chunk.
+    """
+    return max(min(dim_size, split_size * (idx + 1)) - split_size * idx, 0)
+
+
+def get_chunk_sharding_params(sharding_dim_size, world_size, spec, rank):
+    """
+    Generate the start pos and offset length for the current rank for
+    chunk sharding.
+
+    Args:
+        sharding_dim_size(int): The dimension length which we shard on.
+        world_size(int): number of ranks.
+        spec (:class:`torch.distributed._shard.sharding_spec.ChunkShardingSpec`):
+            sharding spec.
+        rank(int): # of cuda process.
+
+    Returns:
+        start_pos(int): start position of sharded tensor on the given rank.
+        chunk_size(int): chunk size of sharded tensor on the given rank.
+    """
+    split_size = get_split_size(sharding_dim_size, world_size)
+    current_offsets = 0
+    start_pos = current_offsets
+    for idx, placement in enumerate(spec.placements):
+        chunk_size = get_chunked_dim_size(sharding_dim_size, split_size, idx)
+        if rank == placement.rank():
+            start_pos = current_offsets
+            break
+        current_offsets += chunk_size
+    return start_pos, chunk_size  # type: ignore[possibly-undefined]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/api.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..91355e356c33eee8ad841408d6cc695a9e791d18
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/api.py
@@ -0,0 +1,263 @@
+# mypy: allow-untyped-defs
+import functools
+import operator
+from abc import ABC, abstractmethod
+from dataclasses import dataclass
+from typing import Callable, Dict, List, TYPE_CHECKING
+
+import torch
+import torch.distributed._shard.sharded_tensor.metadata as sharded_tensor_meta
+from torch.distributed._shard.metadata import ShardMetadata
+from torch.distributed._shard.op_registry_utils import _decorator_func
+
+from ._internals import (
+    check_tensor,
+    get_chunked_dim_size,
+    get_split_size,
+    validate_non_overlapping_shards_metadata,
+)
+
+
+if TYPE_CHECKING:
+    # Only include ShardedTensor when do type checking, exclude it
+    # from run-time to resolve circular dependency.
+    from torch.distributed._shard.sharded_tensor import ShardedTensor
+
+
+class PlacementSpec(ABC):  # noqa: B024
+    """
+    Base class representing the placement of an entity. Subclasses of this
+    class can be used to specify customized placements which might not be
+    covered by existing APIs.
+    """
+
+
+@dataclass
+class DevicePlacementSpec(PlacementSpec):
+    """
+    Associates placement of an entity with a single device.
+
+    Args:
+        device(:class:`torch.distributed._remote_device`): The device to place the entity on.
+    """
+
+    device: torch.distributed._remote_device
+
+    def __post_init__(self):
+        if not isinstance(self.device, torch.distributed._remote_device):
+            self.device = torch.distributed._remote_device(self.device)
+
+
+class ShardingSpec(ABC):
+    """
+    Base class representing sharding specifications.
+    """
+
+    @abstractmethod
+    def build_metadata(
+        self,
+        tensor_sizes: torch.Size,
+        tensor_properties: sharded_tensor_meta.TensorProperties,
+    ) -> sharded_tensor_meta.ShardedTensorMetadata:
+        """
+        Given a global tensor size, define how to shard a tensor like this shape
+        across ranks, return ShardedTensorMetadata
+        Args:
+            tensor_sizes (:class:`torch.Size`):
+                The tensor shape to shard on, a `torch.Size` object that represents the
+                tensor shape to be sharded according to the ShardingSpec.
+            tensor_properties(:class:`torch.distributed._shard.sharded_tensor.TensorProperties):
+                Tensor properties used to create a ShardedTensor.
+        Returns:
+            A :class:`ShardedTensorMetadata` object that encodes the information about
+            the layout of the ShardedTensor and its properties.
+        """
+
+    @abstractmethod
+    def shard(
+        self, tensor: torch.Tensor, src_rank: int = 0, process_group=None
+    ) -> "ShardedTensor":
+        """
+        Given a global tensor on src_rank, shard this tensor
+        across ranks within the process group, return a ShardedTensor.
+        Args:
+            tensor (:class:`torch.Tensor`): Tensor needs to be sharded.
+        Keyword args:
+            src_rank (int, optional): The source rank which is used as the ground truth of
+                the data for the parameter that would be sharded and scattered
+                across the rest of the ranks.
+                Default: 0.
+            process_group (ProcessGroup, optional): The process group to work on. If None,
+                the default process group will be used.
+        Returns:
+            A :class:`ShardedTensor` sharded from the given tensor.
+        """
+
+
+# Ops customized for a particular ShardingSpec.
+_CUSTOM_SHARDING_SPEC_OPS: Dict[str, Dict[Callable, Callable]] = {}
+
+
+def _has_custom_op(sharding_spec, op):
+    """
+    Returns whether or not the ShardingSpec has a custom op implementation.
+    """
+    class_name = type(sharding_spec).__qualname__
+    return (
+        class_name in _CUSTOM_SHARDING_SPEC_OPS
+        and op in _CUSTOM_SHARDING_SPEC_OPS[class_name]
+    )
+
+
+def _dispatch_custom_op(
+    sharding_spec, op: Callable, types, args, kwargs, process_group
+):
+    """
+    Calls the custom op for this ShardingSpec if it exists.
+    """
+    class_name = type(sharding_spec).__qualname__
+    if not _has_custom_op(sharding_spec, op):
+        raise RuntimeError(f"Custom op: {op} not registered for {class_name}")
+    func = _CUSTOM_SHARDING_SPEC_OPS[class_name][op]
+    return func(types, args, kwargs, process_group)
+
+
+def custom_sharding_spec_op(sharding_spec_class, func):
+    """
+    Decorator to allow custom registration of ops.
+    Args:
+        sharding_spec_class(type): The ShardingSpec for which we need to add this custom op.
+        func(Callable): The op to override (ex: torch.bmm)
+    """
+    class_name = sharding_spec_class.__qualname__
+    if class_name not in _CUSTOM_SHARDING_SPEC_OPS:
+        _CUSTOM_SHARDING_SPEC_OPS[class_name] = {}
+    return functools.partial(
+        _decorator_func, op=func, op_table=_CUSTOM_SHARDING_SPEC_OPS[class_name]
+    )
+
+
+@dataclass
+class EnumerableShardingSpec(ShardingSpec):
+    """
+    This is a type of PlacementSpec that allows users to specify a generic
+    sharding scheme by enumerating exactly how each shard is laid out.
+
+    Args:
+        shards(List[ShardMetadata]): List of :class:`ShardMetadata` objects representing
+            each shard. Note that none of the shards should overlap.
+    """
+
+    shards: List[ShardMetadata]
+
+    def __post_init__(self):
+        if len(self.shards) == 0:
+            raise ValueError(f"Empty shard list provided: {self.shards}")
+
+        # Validate each shard has same rank.
+        rank = -1
+        for shard in self.shards:
+            if rank != -1 and rank != len(shard.shard_offsets):
+                raise ValueError(
+                    f"Found inconsistent ranks for shards: {rank} and {len(shard.shard_offsets)}"
+                )
+            rank = len(shard.shard_offsets)
+
+        validate_non_overlapping_shards_metadata(self.shards)
+
+    def build_metadata(
+        self,
+        tensor_sizes: torch.Size,
+        tensor_properties: sharded_tensor_meta.TensorProperties,
+    ) -> sharded_tensor_meta.ShardedTensorMetadata:
+        # check if shards form a valid tensor
+        check_tensor(self.shards, tensor_sizes)
+        return sharded_tensor_meta.ShardedTensorMetadata(
+            self.shards, tensor_sizes, tensor_properties
+        )
+
+    def shard(
+        self, tensor: torch.Tensor, src_rank: int = 0, process_group=None
+    ) -> "ShardedTensor":
+        # TODO: figure out a generic and efficient way to scatter the shards for EnumerableShardingSpec
+        raise NotImplementedError("EnumerableShardingSpec.shard not implemented yet!")
+
+
+def _infer_sharding_spec_from_shards_metadata(shards_metadata):
+    """
+    Infer the sharding spec from the metadata of each shard of a ShardedTensor.
+    If the tensor is sharded only on one dimension, we can then verify whether it's
+    a ChunkShardingSpec or not. The way to verify it is to first get the total length
+    and perform a chunk sharding with the given placements to see if we can have the
+    same chunk size as the given shards_metadata. If not, we assume it's enum sharded.
+
+    Args:
+        shards_metadata (List[ShardMetadata]): List of Metadata of local shards.
+
+    Returns:
+        A :class:`torch.distributed._shard.sharding_spec.ShardingSpec` object of sharding
+            spec for one sharded tensor.
+    """
+    placements = []
+    chunk_sharding_dim = None
+    chunk_offset_list = []
+    shard_size_list = []
+    shard_offset_list = []
+    # collect local shard metadatas from the global sharded_tensor_metadata
+    for shard_metadata in shards_metadata:  # type: ignore[attr-defined]
+        placements.append(shard_metadata.placement)
+        local_offsets = shard_metadata.shard_offsets
+        chunk_offset_list.append(sum(local_offsets))
+        shard_size_list.append(shard_metadata.shard_sizes)
+        shard_offset_list.append(shard_metadata.shard_offsets)
+        shard_dims = [idx for idx, e in enumerate(local_offsets) if e != 0]
+        # If the offset is [0, 0, ..., 0] (all zeros),
+        # we cannot decide whether how the tensor is sharded.
+        if len(shard_dims) == 0:
+            continue
+        # If the offset is [0, N, .,0, M, 0, .., 0],
+        # we are sure it's sharded by more than one dimension.
+        if len(shard_dims) != 1:
+            chunk_sharding_dim = None
+            break
+        # If the offset is [0, 0, .,0, M, 0, .., 0], aka, it's sharded by just
+        # one dimension, we need to make sure all ranks share the same dimension.
+        if not chunk_sharding_dim:
+            chunk_sharding_dim = shard_dims[0]
+        elif chunk_sharding_dim != shard_dims[0]:
+            chunk_sharding_dim = None
+            break
+
+    if chunk_sharding_dim is not None:
+        # Ensure we infer the correct placement order from offsets
+        placements = [
+            x
+            for _, x in sorted(
+                zip(chunk_offset_list, placements), key=operator.itemgetter(0)
+            )
+        ]
+
+        from .chunk_sharding_spec import ChunkShardingSpec
+
+        chunk_spec = ChunkShardingSpec(
+            dim=chunk_sharding_dim,
+            placements=placements,
+        )
+
+        shard_sizes = sorted([x[chunk_sharding_dim] for x in shard_size_list])
+        shard_total_length = sum(shard_sizes)
+        shard_offsets = sorted([x[chunk_sharding_dim] for x in shard_offset_list])
+
+        chunks = len(placements)
+        split_size = get_split_size(shard_total_length, chunks)
+        chunk_shard_sizes = sorted(
+            [
+                get_chunked_dim_size(shard_total_length, split_size, idx)
+                for idx in range(chunks)
+            ]
+        )
+        # Should match ChunkShardingSpec offsets calculation
+        chunk_shard_offsets = [split_size * idx for idx in range(chunks)]
+        if shard_sizes == chunk_shard_sizes and shard_offsets == chunk_shard_offsets:
+            return chunk_spec
+    return EnumerableShardingSpec(shards_metadata)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/chunk_sharding_spec.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/chunk_sharding_spec.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd0e354dfc25cc6dec83084dc447870572ef7074
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/chunk_sharding_spec.py
@@ -0,0 +1,218 @@
+# mypy: allow-untyped-defs
+from dataclasses import dataclass
+from typing import cast, List, Optional, TYPE_CHECKING, Union
+
+import torch
+import torch.distributed as dist
+import torch.distributed._shard.sharded_tensor.metadata as sharded_tensor_meta
+import torch.distributed.distributed_c10d as distributed_c10d
+from torch.distributed._shard._utils import narrow_tensor
+from torch.distributed._shard.metadata import ShardMetadata
+from torch.distributed._shard.sharded_tensor.shard import Shard
+from torch.distributed._shard.sharded_tensor.utils import (
+    _parse_and_validate_remote_device,
+)
+
+from ._internals import get_chunked_dim_size, get_split_size
+from .api import ShardingSpec
+
+
+if TYPE_CHECKING:
+    # Only include ShardedTensor when do type checking, exclude it
+    # from run-time to resolve circular dependency.
+    from torch.distributed._shard.sharded_tensor import ShardedTensor
+
+
+@dataclass
+class ChunkShardingSpec(ShardingSpec):
+    """
+    This is a type of PlacementSpec that defines the placement as being sharded
+    across multiple devices. In particular, it represents sharding a Tensor
+    along a single dimension into equal chunks (similar to :meth:`torch.chunk`).
+
+    The semantics of how a tensor is partitioned is inline with
+    :meth:`torch.chunk`, where ``dim`` in torch.chunk corresponds to the
+    specified ``dim`` and ``chunks`` in torch.chunk is the number of elements
+    in the placement specified.
+
+    Args:
+        dim (int or str):
+            The dimension to shard on, could be an integer representing the
+            dimension or a string in case of named tensors where dimensions are
+            named. Note that named tensor support is not added yet.
+        placement(List[Union[_remote_device, str]]):
+            Specifies the placement of each shard of the Tensor. The size of
+            the list represents the number of shards to be created. This could
+            be a list of
+            :class:`torch.distributed._remote_device`'s. This list
+            could also contain a string which represents remote
+            device as accepted by
+            :class:`torch.distributed._remote_device`
+    """
+
+    ShardingDim = Union[int, str]
+
+    dim: ShardingDim
+    placements: List[Union[torch.distributed._remote_device, str]]
+
+    def __post_init__(self):
+        self._verify_dim(self.dim)
+        for i, remote_device in enumerate(self.placements):
+            if not isinstance(remote_device, torch.distributed._remote_device):
+                self.placements[i] = torch.distributed._remote_device(remote_device)
+
+    @staticmethod
+    def _verify_dim(dim):
+        # Validate the sharding spec.
+        # TODO: support named dimension
+        if isinstance(dim, str):
+            raise NotImplementedError(
+                "ChunkShardingSpec does not support named dimension yet!"
+            )
+
+        if not isinstance(dim, int):
+            raise ValueError(f"Sharding dim needs to be an integer, found: {dim}")
+
+    def build_metadata(
+        self,
+        tensor_sizes: torch.Size,
+        tensor_properties: sharded_tensor_meta.TensorProperties,
+    ) -> sharded_tensor_meta.ShardedTensorMetadata:
+        tensor_num_dim = len(tensor_sizes)
+
+        self._verify_dim(self.dim)
+        if self.dim >= tensor_num_dim or self.dim < -tensor_num_dim:  # type: ignore[operator]
+            raise ValueError(f"Invalid sharding dim: {self.dim}")
+
+        shards_metadata = []
+        sharding_dim_size = tensor_sizes[self.dim]  # type: ignore[index]
+        chunks = len(self.placements)
+        split_size = get_split_size(sharding_dim_size, chunks)
+        for idx, placement in enumerate(self.placements):
+            # generate ShardMetadata for each placement device
+            chunked_dim_size = get_chunked_dim_size(sharding_dim_size, split_size, idx)
+            shard_size = list(tensor_sizes)
+            current_offsets = [0] * tensor_num_dim
+            current_offsets[self.dim] = split_size * idx  # type: ignore[index]
+            shard_size[self.dim] = chunked_dim_size  # type: ignore[index]
+
+            shard_metadata = ShardMetadata(
+                shard_offsets=current_offsets,
+                shard_sizes=shard_size,
+                placement=placement,
+            )
+            shards_metadata.append(shard_metadata)
+
+        return sharded_tensor_meta.ShardedTensorMetadata(
+            shards_metadata, tensor_sizes, tensor_properties
+        )
+
+    def shard(
+        self, tensor: torch.Tensor, src_rank: int = 0, process_group=None
+    ) -> "ShardedTensor":
+        """
+        Args:
+            src_rank: group rank relative to ``process_group``
+
+            N.B. If ``process_group`` is None, ``src_rank`` is a global rank.
+        """
+        # relative imports to avoid circular dependency
+        from torch.distributed._shard.sharded_tensor import ShardedTensor
+
+        tensor_properties = sharded_tensor_meta.TensorProperties(
+            dtype=tensor.dtype,
+            layout=tensor.layout,
+            requires_grad=tensor.requires_grad,
+            memory_format=torch.contiguous_format,
+            pin_memory=tensor.is_pinned(),
+        )
+        current_rank = dist.get_rank(process_group)
+        current_global_rank = dist.get_rank()
+        tensor_meta = self.build_metadata(tensor.size(), tensor_properties)
+        local_shards = []
+        local_tensor = None
+        local_metadata = None
+        tensors_to_scatter = cast(
+            List[Optional[torch.Tensor]],
+            [None] * dist.get_world_size(process_group),
+        )
+
+        sharding_dim_size = tensor.size()[self.dim]  # type: ignore[index]
+        chunks = len(self.placements)
+        split_size = get_split_size(sharding_dim_size, chunks)
+        scatter_shape = list(tensor.size())
+        scatter_shape[self.dim] = split_size  # type: ignore[index]
+
+        for shard_meta in tensor_meta.shards_metadata:
+            remote_global_rank, device = _parse_and_validate_remote_device(
+                process_group, shard_meta.placement
+            )
+            if current_rank == src_rank:
+                # Reshape to get shard for this rank and we don't want autograd
+                # recording here for the narrow op and 'local_shard' should be a
+                # leaf variable in the autograd graph.
+                narrowed_tensor = narrow_tensor(tensor, shard_meta)
+                if shard_meta.shard_sizes[self.dim] < split_size:  # type: ignore[index]
+                    # for the last shard that might be smaller to other shards
+                    # resize the narrowed tensor to the same size and use it for
+                    # the scatter collective as dist.scatter requires same size
+                    # inputs on every rank
+                    tensor_to_scatter = (
+                        narrowed_tensor.detach().clone().resize_(scatter_shape)
+                    )
+                else:
+                    tensor_to_scatter = narrowed_tensor.detach().clone().contiguous()
+
+                tensors_to_scatter[
+                    dist.get_group_rank(process_group, remote_global_rank)
+                ] = tensor_to_scatter
+
+            if current_global_rank == remote_global_rank:
+                local_tensor = torch.empty(
+                    scatter_shape,
+                    dtype=tensor.dtype,
+                    layout=tensor.layout,
+                    device=device,
+                )
+                local_metadata = shard_meta
+
+        # each rank should have local_tensor and local_metadata initialized if we build
+        # the metadata list in a correct way.
+        assert local_tensor is not None
+        assert local_metadata is not None
+
+        # Scatter the shards to all ranks in the pg
+        # scatter takes the global rank as ``src``
+        src_for_scatter = src_rank
+        if (
+            process_group is not None
+            and process_group is not distributed_c10d._get_default_group()
+        ):
+            src_for_scatter = distributed_c10d.get_global_rank(
+                process_group, src_for_scatter
+            )
+
+        dist.scatter(
+            local_tensor,
+            scatter_list=tensors_to_scatter if current_rank == src_rank else None,
+            src=src_for_scatter,
+            group=process_group,
+        )
+
+        if list(local_tensor.size()) != local_metadata.shard_sizes:
+            # detach again after receiving to ensure local shards remain a leaf node
+            local_tensor = local_tensor.resize_(local_metadata.shard_sizes).detach()
+
+        # Sync requires_grad to local_shard.
+        local_tensor.requires_grad = tensor.requires_grad
+
+        local_shards.append(Shard(tensor=local_tensor, metadata=local_metadata))
+
+        st = ShardedTensor._init_from_local_shards_and_global_metadata(
+            local_shards, tensor_meta, process_group=process_group
+        )
+
+        # Manually set sharding_spec
+        st._sharding_spec = self
+
+        return st
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..33a09bf97d4898aefcf7f6a9c7fef16f10610d8d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/__pycache__/_common.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/__pycache__/_common.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2948abfb827090da125cd44d2cc4c4f6e4a9d6b1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/__pycache__/_common.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/__pycache__/embedding.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/__pycache__/embedding.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..93640ee554bd485c8a1c57e763e181e0cb8427ad
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/__pycache__/embedding.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/__pycache__/embedding_bag.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/__pycache__/embedding_bag.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f659badda1bbdee8e90b861044460363bea4878e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/__pycache__/embedding_bag.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/_common.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/_common.py
new file mode 100644
index 0000000000000000000000000000000000000000..83d3371c7f904d3a6f0e72e0cf5c10ce22b6a8b4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/_common.py
@@ -0,0 +1,348 @@
+# mypy: allow-untyped-defs
+
+import torch
+import torch.distributed as dist
+from torch.distributed._shard.sharded_tensor import ShardedTensor
+from torch.distributed._shard.sharded_tensor._ops._common import _sharded_op_common
+from torch.distributed._shard.sharding_spec import ChunkShardingSpec
+from torch.distributed._shard.sharding_spec._internals import (
+    get_chunk_sharding_params,
+    get_chunked_dim_size,
+    get_split_size,
+)
+from torch.distributed._shard.sharding_spec.api import custom_sharding_spec_op
+from torch.distributed.nn.functional import (
+    _all_gather_base,
+    all_reduce,
+    all_to_all_single,
+)
+
+
+def _chunk_sharding_spec_check(spec, op):
+    """
+    For the given op implementation check if the sharding spec is ChunkShardingSpec.
+    """
+    if not isinstance(spec, ChunkShardingSpec):
+        raise NotImplementedError(
+            f"Only ChunkShardingSpec supported for '{op.__name__}'."
+        )
+
+
+def _register_sharded_op_on_local_tensor(
+    op, early_stop_func=None, extra_check=None, customized_func=None
+):
+    """
+    Handles ``__torch_function__`` dispatch for ops which are performed on
+    the single local tensor of the sharded tensor such as op like
+    ``torch.nn.functional.softmax`` or ``torch.Tensor.view``.
+
+    For more complicated ops, a customized func can be used to generate
+    the new local tensor, sharding spec and sharded tensor size.
+
+    Args:
+        op: The op to be registered and applied to all shards of the st.
+        early_stop_func (Callable, optional): the func for early stop.
+            Default: if ``None``, no early stop.
+        extra_check (Callable, optional): the func for extra condition check.
+            Default: if ``None``, no extra check.
+        customized_func (Callable, optional): the func for customized logic
+            to generate the new local tensor, sharding spec and sharded tensor size.
+            Default: if ``None``, we simply lower to the real op call with
+                the single local tensor of the st.
+
+    Return:
+        func (Callable): registered implementation for sharded op for
+        ``__torch_function__`` dispatch.
+    """
+
+    @custom_sharding_spec_op(ChunkShardingSpec, op)
+    @_sharded_op_common(op, early_stop_func, extra_check)
+    def sharded_tensor_op_on_local_tensor(types, args=(), kwargs=None, pg=None):
+        st = args[0]
+        sharding_spec = st.sharding_spec()
+        if len(st.local_shards()) != 1:
+            raise TypeError(
+                f"torch function '{op.__name__}', with args: {args} and "
+                f"kwargs: {kwargs} only supported for single local tensor!"
+            )
+        st_size = st.size()
+        if customized_func:
+            local_tensor, sharding_spec, st_size = customized_func(args, kwargs, pg)
+        else:
+            args = (st.local_tensor(), *args[1:])
+            local_tensor = op(*args, **kwargs)
+        return ShardedTensor._init_from_local_tensor(
+            local_tensor.contiguous(),
+            sharding_spec,
+            st_size,  # type: ignore[arg-type]
+            process_group=pg,
+            init_rrefs=st._init_rrefs,
+        )
+
+
+def _handle_col_wise_sharding_base(
+    op_func,
+    col_dim,
+    input,
+    world_size,
+    weight,
+    local_shard,
+    pg,
+    gathered_inputs,
+    mode=None,
+    gathered_per_sample_weights=None,
+    gathered_offsets=None,
+    padding_idx=None,
+):
+    """
+    For col-wise sharding of weight, lots of logic are common.
+    So we extract the common logic and put in this function:
+    Step 1. To get input from each rank and
+    Step 2. To perform the op on the concatenated tensor.
+    Step 3. To distribute results to each rank with col rearrangement.
+    Step 4. To concatenate all results from all ranks.
+
+    Args:
+        op_func: operator which is applied to the input tensor.
+        col_dim: dim of result tensor after the operation.
+        input: tensor to be applied op on.
+        world_size: number of ranks.
+        weight: sharded weight tensor.
+        local_shard: col-wise sharded weight tensor.
+        pg: process group.
+        gathered_inputs: list of inputs from all ranks. If specified, we
+            don't need to communicate with each rank any more.
+        mode: aggregation mode of EmbeddingBag.
+        gathered_per_sample_weights: per_sample_weights across all ranks.
+        gathered_offsets: offsets across all ranks.
+        padding_idx: If specified, the entries at padding_idx do
+            not contribute to the gradient; therefore, the embedding
+            vector at padding_idx is not updated during training,
+            i.e. it remains as a fixed "pad".
+            Note that the embedding vector at padding_idx is
+            excluded from the reduction.
+
+    Return: final result of input being applied with the op.
+    """
+    # run the operator's function for all the inputs.
+    results = []
+    for i, inp in enumerate(gathered_inputs):
+        if op_func == torch.nn.functional.embedding_bag:
+            result = op_func(
+                inp,
+                local_shard,
+                offsets=gathered_offsets[i] if gathered_offsets is not None else None,
+                mode=mode,
+                per_sample_weights=gathered_per_sample_weights[i]
+                if gathered_per_sample_weights is not None
+                else None,
+                padding_idx=padding_idx,
+            )
+        elif op_func == torch.nn.functional.embedding:
+            result = op_func(
+                inp,
+                local_shard,
+                padding_idx=padding_idx,
+            )
+        else:
+            result = op_func(inp, local_shard)
+        results.append(torch.transpose(result, 0, col_dim))
+
+    # Distribute results to each rank with col rearrangement.
+    output = _result_distribute_with_col_rearrange(
+        results, input, world_size, weight, pg
+    )
+
+    # transpose the output and return result.
+    return torch.transpose(output, 0, col_dim)
+
+
+def _result_distribute_with_col_rearrange(results, input, world_size, weight, pg):
+    """
+    For col-wise sharding of weight, we need to distribute
+    results to each rank. We do them in this function.
+    Note that, if the index in the Sharding Spec is not equal to
+    the rank number, we need to do the rearrangement based on the
+    order given by the Sharding Spec (placement).
+
+    Args:
+        results: results from ops applied to inputs from all ranks.
+            We need to distribute them back to their original ranks.
+        input: tensor to be applied op to.
+        world_size: number of ranks.
+        weight: sharded weight tensor.
+        pg: process group.
+
+    Return: column rearranged result.
+    """
+    # Process results and outputs for all2all.
+    sharding_dim = weight._sharding_spec.dim
+    sharding_dim_size = weight.size(sharding_dim)
+    dims = list(results[0].size())
+    dims[0] = sharding_dim_size
+    combined_results = torch.cat(results)
+    output = torch.empty(
+        *dims, device=combined_results.device, dtype=combined_results.dtype
+    )
+
+    # Compute output splits
+    split_size = get_split_size(sharding_dim_size, world_size)
+    output_split_sizes = [0] * world_size
+    for idx, placement in enumerate(weight._sharding_spec.placements):
+        output_split_sizes[placement.rank()] = get_chunked_dim_size(
+            sharding_dim_size, split_size, idx
+        )
+
+    # distribute the outputs using all2all.
+    output = all_to_all_single(
+        output, combined_results, output_split_sizes=output_split_sizes, group=pg
+    )
+
+    # Check if we need to rearrange columns appropriately for output.
+    rearrange_columns = any(
+        idx != placement.rank()
+        for idx, placement in enumerate(weight._sharding_spec.placements)
+    )
+    if not rearrange_columns:
+        return output
+
+    indices = []
+    for placement in weight._sharding_spec.placements:
+        dim_size = output_split_sizes[placement.rank()]
+        start = sum(
+            split_size if i < placement.rank() else 0
+            for i, split_size in enumerate(output_split_sizes)
+        )
+        indices += list(range(start, start + dim_size))
+
+    return output.index_select(0, torch.tensor(indices, device=output.device))
+
+
+def _handle_max_norm_col_wise(
+    max_norm,
+    norm_type,
+    local_shard,
+    input,
+    world_size,
+    gathered_inputs,
+    pg,
+):
+    """
+    For col-wise sharding of weight, we need to aggregate the
+    norm across all ranks before we can perform the proper re-norm.
+    Note that, the max_norm logic is only applied to the embedding
+    indices that are looked up and not the whole shard.
+
+    Args:
+        max_norm: If given, each embedding vector with norm larger
+            than max_norm is renormalized to have norm max_norm.
+            Note: this will modify weight in-place.
+        norm_type: The p in the p-norm to compute for the max_norm option.
+        local_shard: col-wise shared local weight used for lookup.
+        input: tensor to be applied op to.
+        world_size: number of ranks.
+        gathered_inputs: list of inputs from all ranks.
+        pg: process group.
+
+    Return:
+        local_shard_norm_renormed: local_shard re-normed to max_norm if the norm is larger
+            than it.
+
+    """
+    norm_type = norm_type if norm_type is not None else 2.0
+    unique_inp = torch.unique(torch.cat(gathered_inputs))
+    local_shard_sum = torch.sum(
+        torch.pow(torch.abs(local_shard), norm_type), dim=1, dtype=local_shard.dtype
+    )
+    # For col-wise sharding, we need to first aggregate the powered sum
+    # from each rank first and then calculate the norm.
+    local_shard_sum = all_reduce(local_shard_sum, group=pg)
+    local_shard_norm = torch.pow(local_shard_sum, 1.0 / norm_type)
+    max_norm_tensor = torch.full(
+        (local_shard.size(0),),
+        float("inf"),
+        dtype=local_shard.dtype,
+        device=input.device,
+    )
+    max_norm_tensor[unique_inp] = max_norm
+    local_shard_t = local_shard.t().contiguous()
+    normalized_tensor = torch.where(
+        local_shard_norm > max_norm_tensor, max_norm_tensor, local_shard_norm
+    )
+    # Make sure divisor is not zero.
+    local_shard_norm[local_shard_norm == 0.0] = 1.0
+    local_shard_norm_renormed = (
+        torch.div(torch.mul(local_shard_t, normalized_tensor), local_shard_norm)
+        .t()
+        .contiguous()
+    )
+    return local_shard_norm_renormed
+
+
+def _all_gather_base_input(input, pg):
+    """
+    Use _all_gather_base to get a concatenated input from each rank.
+
+    Args:
+        input: tensor to be applied op on.
+        pg: process group.
+
+    Returns:
+        gathered_inputs: input gathered from each rank and concat by dim 0.
+    """
+    # allgather the inputs first.
+    gather_inp_size = list(input.size())
+    gather_inp_size[0] = input.size(0) * dist.get_world_size(pg)
+    gather_inp = torch.empty(gather_inp_size, device=input.device, dtype=input.dtype)
+    return _all_gather_base(gather_inp, input, group=pg)
+
+
+def _handle_row_wise_mask(gather_inp, padding_idx, weight, world_size, rank):
+    """
+    Mask the input for embedding look-up for IDs which are not stored
+    on the current rank. This function also adjust the ``padding_idx``
+    so that it is only used on the rank where the corresponding row is
+    stored.
+
+    Note that, with ``max_norm`` flag on, only weights of rows being
+    looked up will be re-normed. So we need an extra row for masked ID
+    so that it does not affect the final result and ``max_norm``.
+
+    Args:
+        gather_inp: tensor to be applied op on gathered from all ranks.
+        padding_idx: If specified, the entries at padding_idx do
+            not contribute to the gradient; therefore, the embedding
+            vector at padding_idx is not updated during training,
+            i.e. it remains as a fixed "pad".
+            Note that the embedding vector at padding_idx is
+            excluded from the reduction.
+        weight: weight tensor of Embedding look-up table.
+        world_size: number of ranks.
+        rank: # of cuda process.
+
+    Returns:
+        lookup_input: Tensor of masked input.
+        padding_idx: adjusted padding_idx.
+        padding_row: The extra row we used during lookup so that
+            looking up does not affect ``max_norm``.
+    """
+    (start_pos, chunk_size) = get_chunk_sharding_params(
+        weight.size(0), world_size, weight._sharding_spec, rank
+    )
+    mask = (gather_inp < start_pos) | (gather_inp >= start_pos + chunk_size)
+    lookup_input = gather_inp.clone() - start_pos
+    lookup_input[mask] = chunk_size
+    if (
+        padding_idx is not None
+        and padding_idx >= start_pos
+        and padding_idx < (start_pos + chunk_size)
+    ):
+        padding_idx = padding_idx - start_pos
+    else:
+        padding_idx = None
+
+    # When max_norm is set, it will only re-norm the row being looked up.
+    padding_row = torch.zeros(
+        1, weight.size(1), device=gather_inp.device, dtype=weight.dtype
+    )
+    return lookup_input, padding_idx, padding_row
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/embedding.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/embedding.py
new file mode 100644
index 0000000000000000000000000000000000000000..117aed79520d9ad78c10bdd2310fb6b032c2a024
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/embedding.py
@@ -0,0 +1,294 @@
+# mypy: allow-untyped-defs
+
+import torch
+import torch.distributed as dist
+from torch.distributed._shard.sharded_tensor import ShardedTensor
+from torch.distributed._shard.sharding_spec import ChunkShardingSpec
+from torch.distributed._shard.sharding_spec.api import custom_sharding_spec_op
+from torch.distributed.nn.functional import all_gather, reduce_scatter
+
+from ._common import (
+    _all_gather_base_input,
+    _handle_col_wise_sharding_base,
+    _handle_max_norm_col_wise,
+    _handle_row_wise_mask,
+)
+
+
+@custom_sharding_spec_op(ChunkShardingSpec, torch.nn.functional.embedding)
+def sharded_embedding(types, args, kwargs, pg):
+    """
+    Handles ``__torch_function__`` dispatch for ``torch.nn.functional.embedding``.
+    This method computes a sharded embedding lookup and has the following limitations:
+
+    1. Supports only sharding of ``weight``.
+    2. Supports only ``ChunkShardingSpec``.
+    3. Supports only a single local shard per rank.
+    4. Supports all specs except for scale_grad_by_freq, sparse, etc.
+
+    Based on the dimension that the weight is sharded on, there are two
+    algorithms:
+
+    ROWWISE SHARDING
+    ================
+    For row-wise sharding the weight is sharded on dimension 0.
+
+    The overall algorithm can be best explained with an example. Let's assume
+    the dims for input are (4 x 6) and W are (10 x 17) and W is sharded across
+    4 GPUs creating 3 shard of (3 x 17) and 1 shard of (1 x 17).
+    The algorithm is as follows:
+
+    1. First the input is all gathered to all ranks, since this is SPMD and
+       input is actually sharded across all ranks. The inputs then become a
+       4 (4 x 6) tensor on each rank. For example if the given input is
+       tensor([[6, 5, 2, 9, 6, 3],
+               [3, 1, 2, 4, 7, 6],
+               [4, 0, 4, 9, 8, 9],
+               [8, 6, 6, 4, 6, 1]])
+       on rank 0.
+       Then on every rank, we will have this tensor.
+       If input itself is already replicated, no all-gather will be done.
+    2. Next, we mask the ID which are not stored on that rank.
+       For example on rank 0, we store ID [0, 1, 2]. We only keep the ID
+       inside the set of numbers. The rest of them will be masked to an extra row.
+       The masked matrix will be used for embedding look up and is like:
+       tensor([[4, 4, 2, 4, 4, 4],
+               [4, 1, 2, 4, 4, 4],
+               [4, 0, 4, 4, 4, 4],
+               [4, 4, 4, 4, 4, 1]])
+       The reason of having an extra row (aka, number 4 in the example) is
+       because when max_norm is specified only weight which has looked will
+       be re-normed so mask IDs whose embeddings are not stored in current
+       rank will to an extra row will ensure max_norm still works as expected.
+    3. If max_norm is specified, the extra row guarantees that the mask ID will
+       not affect the behavior of weigh re-norm.
+
+    COLWISE SHARDING
+    ================
+    For col-wise sharding the weight is sharded on dimension 1.
+
+    The overall algorithm can be best explained with an example. Let's assume
+    the dims for input are (4 x 6) and W are (16 x 17) and W is sharded across
+    4 GPUs creating 3 shards of (16 x 5) and 1 shard of (16 x 2).
+    The algorithm is as follows:
+
+    1. First the input is broadcasted to all ranks, since this is SPMD we
+       actually do an all_gather for all the inputs resulting in 4 (4 x 6)
+       inputs on each rank.
+    2. Next we perform local embedding lookup operation by apply each
+       input (4 x 6) with the local shard (16 x 5) ((16 x 2) for the last).
+       This results in 4 (5 x 6 x 4) ((2 x 6 x 4) for the last) matrices
+       on each rank. We transpose dim 0 and dim 2.
+    3. Next, we concat these 4 matrices and perform an all2all to share the
+       appropriate (5 x 6 x 4) or (2 x 6 x 4) matrices to each rank.
+    4. Now, each rank receives a (17 x 6 x 4) matrix which is basically the
+       size of the result we need.
+    5. If placements are not in order any appropriate rearrangement of columns
+       are done for the (17 x 6 x 4) matrix and finally we transpose the
+       dim 0 and dim 2 again.
+    6. If max_norm is specified, we manually sum up the norm and renorm. Because
+       the renorm must be in place, we need to override the local_shard to mimic
+       this behavior.
+    """
+    # Validate input params
+    _validate_embedding_param(args, kwargs)
+
+    input = args[0]
+    weight = args[1]
+    max_norm = kwargs.get("max_norm")
+    norm_type = kwargs.get("norm_type")
+    padding_idx = kwargs.get("padding_idx")
+
+    local_shard = weight.local_tensor().contiguous()
+    sharding_dim = weight._sharding_spec.dim
+    world_size = dist.get_world_size(pg)
+    rank = dist.get_rank(pg)
+
+    if sharding_dim == 1:
+        output, local_shard = _handle_col_wise_sharding(
+            input, world_size, weight, local_shard, max_norm, norm_type, padding_idx, pg
+        )
+        weight.local_shards()[0].tensor = local_shard
+        return output
+    elif sharding_dim == 0:
+        return _handle_row_wise_sharding(
+            input,
+            world_size,
+            weight,
+            local_shard,
+            max_norm,
+            norm_type,
+            padding_idx,
+            rank,
+            pg,
+        )
+    else:
+        raise RuntimeError(
+            f"nn.Embedding weight sharded on dim {sharding_dim} not supported!"
+        )
+
+
+def _validate_embedding_param(args, kwargs):
+    """
+    Validate input params of sharded embedding op.
+
+    Args:
+        input: list of ID used for lookup.
+        weight: sharded weight tensor.
+        kwargs: same as normal Embedding.
+
+    Return: None.
+    """
+
+    input = args[0]
+    weight = args[1]
+    max_norm = kwargs.get("max_norm")
+    scale_grad_by_freq = kwargs.get("scale_grad_by_freq")
+    sparse = kwargs.get("sparse")
+
+    # Validate types
+    if not isinstance(input, torch.Tensor):
+        raise TypeError("input need to be torch.Tensor")
+    if not isinstance(weight, ShardedTensor):
+        raise TypeError("weight needs to be ShardedTensor")
+    weight_size = weight.size()
+    if len(weight_size) != 2:
+        raise ValueError("Weight needs to have exactly 2 dims")
+    if int(torch.min(input).item()) < 0:
+        raise ValueError(
+            "Index out of range in Input %d %d",
+            int(torch.min(input).item()),
+            weight_size[1],
+        )
+    if int(torch.max(input).item()) >= weight_size[0]:
+        raise ValueError(
+            "Index out of range in Input %d %d",
+            int(torch.max(input).item()),
+            weight_size[1],
+        )
+    if scale_grad_by_freq:
+        raise RuntimeError(
+            'nn.Embedding weight sharded with flag on "scale_grad_by_freq" not supported!'
+        )
+    if sparse:
+        raise RuntimeError(
+            'nn.Embedding weight sharded with flag on "sparse" not supported!'
+        )
+    if max_norm and max_norm <= 0.0:
+        raise ValueError('"max_norm" must be larger than zero!')
+
+    if not isinstance(weight._sharding_spec, ChunkShardingSpec):
+        raise ValueError("Only ChunkShardingSpec supported for ShardedTensor ops!")
+    if len(weight.local_shards()) != 1:
+        raise ValueError("Only one local shard supported!")
+
+
+def _handle_col_wise_sharding(
+    input, world_size, weight, local_shard, max_norm, norm_type, padding_idx, pg
+):
+    """
+    Entry-point function to handle the logic of col-wise sharding of weight
+    for embedding. (Detailed explanations of the logic can be found in
+    the comment for sharded_embedding.)
+
+    Args:
+        input: list of ID used for lookup and aggregation.
+        world_size: number of ranks.
+        weight: sharded weight tensor.
+        local_shard: col-wise shared local weight used for lookup.
+        max_norm: If given, each embedding vector with norm larger
+            than max_norm is renormalized to have norm max_norm.
+            Note: this will modify weight in-place.
+        norm_type: The p in the p-norm to compute for the max_norm option.
+        padding_idx: If specified, the entries at padding_idx do
+            not contribute to the gradient; therefore, the embedding
+            vector at padding_idx is not updated during training,
+            i.e. it remains as a fixed "pad".
+        pg: process group.
+
+    Returns: final result of lookup.
+    """
+    # allgather the inputs first for non Replicated Tensor.
+    gathered_inputs = all_gather(input, group=pg)
+
+    if max_norm is not None:
+        # max_norm changes the weight in-place
+        local_shard = _handle_max_norm_col_wise(
+            max_norm, norm_type, local_shard, input, world_size, gathered_inputs, pg
+        )
+
+    output = _handle_col_wise_sharding_base(
+        torch.nn.functional.embedding,
+        len(input.size()),
+        input,
+        world_size,
+        weight,
+        local_shard,
+        pg,
+        gathered_inputs,
+        padding_idx=padding_idx,
+    )
+    return (output, local_shard)
+
+
+def _handle_row_wise_sharding(
+    input, world_size, weight, local_shard, max_norm, norm_type, padding_idx, rank, pg
+):
+    """
+    Entry-point function to handle the logic of row-wise sharding of weight
+    for embedding. (Detailed explanations of the logic can be found in
+    the comment for sharded_embedding.)
+
+    Args:
+        input: list of ID used for lookup and aggregation.
+        world_size: number of ranks.
+        weight: sharded weight tensor.
+        local_shard: row-wise shared local weight used for lookup.
+        max_norm: If given, each embedding vector with norm larger
+            than max_norm is renormalized to have norm max_norm.
+            Note: this will modify weight in-place.
+        norm_type: The p in the p-norm to compute for the max_norm option.
+        padding_idx: If specified, the entries at padding_idx do
+            not contribute to the gradient; therefore, the embedding
+            vector at padding_idx is not updated during training,
+            i.e. it remains as a fixed "pad".
+        rank: # of cuda process.
+        pg: process group.
+
+    Returns: final result of lookup.
+    """
+    # allgather the inputs first for non Replicated Tensor.
+    gather_inp = _all_gather_base_input(input, pg)
+
+    # Mask the input according to sharding spec.
+    lookup_input, padding_idx, padding_row = _handle_row_wise_mask(
+        gather_inp, padding_idx, weight, world_size, rank
+    )
+
+    # When input is a large tensor, the value of weight is changed.
+    # This is a walk-around for now. GH issue: #81717
+    if max_norm is not None:
+        torch.nn.functional.embedding(
+            torch.unique(lookup_input)[:-1],
+            local_shard,
+            padding_idx=padding_idx,
+            max_norm=max_norm,
+            norm_type=norm_type,
+        )
+        max_norm = None
+
+    local_input_embeddings = torch.nn.functional.embedding(
+        lookup_input,
+        torch.cat([local_shard, padding_row]),
+        padding_idx=padding_idx,
+        max_norm=max_norm,
+        norm_type=norm_type,
+    )
+
+    # TODO: Make the result a PartialTensor.
+    local_shards = local_input_embeddings.chunk(pg.size())
+    return reduce_scatter(
+        torch.empty_like(local_shards[0]),
+        list(local_shards),
+        group=pg,
+    )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/embedding_bag.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/embedding_bag.py
new file mode 100644
index 0000000000000000000000000000000000000000..01a148b5a9a93c184b7d7dda7b80f9eb49f32e7d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/embedding_bag.py
@@ -0,0 +1,477 @@
+# mypy: allow-untyped-defs
+
+from typing import cast, List
+
+import torch
+import torch.distributed as dist
+from torch._C._distributed_c10d import ReduceOp
+from torch.distributed._shard.sharded_tensor import ShardedTensor
+from torch.distributed._shard.sharding_spec import ChunkShardingSpec
+from torch.distributed._shard.sharding_spec.api import custom_sharding_spec_op
+from torch.distributed.nn.functional import all_gather, reduce_scatter
+
+from ._common import (
+    _all_gather_base_input,
+    _handle_col_wise_sharding_base,
+    _handle_max_norm_col_wise,
+    _handle_row_wise_mask,
+)
+
+
+@custom_sharding_spec_op(ChunkShardingSpec, torch.nn.functional.embedding_bag)
+def sharded_embedding_bag(types, args, kwargs, pg):
+    """
+    Handles ``__torch_function__`` dispatch for ``torch.nn.functional.embedding_bag``.
+    This method computes a sharded embedding bag aggregation and has the following limitations:
+
+    1. Supports only sharding of ``weight``.
+    2. Supports only ``ChunkShardingSpec``.
+    3. Supports only a single local shard per rank.
+    4. Supports all specs except for scale_grad_by_freq, sparse, etc.
+
+    Based on the dimension that the weight is sharded on, there are two
+    algorithms:
+
+    ROWWISE SHARDING
+    ================
+    For row-wise sharding the weight is sharded on dimension 0.
+
+    The overall algorithm can be best explained with an example. Let's assume
+    the dims for input are (4 x 6) and W are (16 x 17) and W is sharded across
+    4 GPUs creating 4 shard of (4 x 17).
+    The algorithm is as follows:
+
+    1. First the input is all gathered to all ranks, since this is SPMD and
+       input is actually sharded across all ranks. The inputs then become a
+       4 (4 x 6) tensor on each rank. For example if the given input is
+       tensor([[6, 5, 2, 9, 6, 3],
+               [3, 1, 2, 4, 7, 6],
+               [4, 0, 4, 9, 8, 9],
+               [8, 6, 6, 4, 6, 1]])
+       on rank 0.
+       Then on every rank, we will have this tensor.
+       If input itself is already replicated, no all-gather will be done.
+    2. Next, we mask the ID which are not stored on that rank.
+       For example on rank 0, we store ID [0, 1, 2]. We only keep the ID
+       inside the set of numbers. The rest of them will be masked to an extra row.
+       The masked matrix will be used for embedding look up and is like:
+       tensor([[4, 4, 2, 4, 4, 4],
+               [4, 1, 2, 4, 4, 4],
+               [4, 0, 4, 4, 4, 4],
+               [4, 4, 4, 4, 4, 1]])
+    3. If ``max_norm`` is specified, the extra row guarantees that the mask ID will
+       not affect the behavior of weigh re-norm.
+    4. The example above only happens in one rank and each rank does a very similar thing.
+       For "Mean" mode we need to divide by either column size (2D) or the interval length
+       defined by the offset (excluding the row specified in ``padding_idx``).
+       We also need to mask the unexisting row to neg Inf so that negative value does not
+       gets wiped out in the "Max" mode.
+
+    COLWISE SHARDING
+    ================
+    For col-wise sharding the weight is sharded on dimension 1.
+
+    The overall algorithm can be best explained with an example. Let's assume
+    the dims for input are (4 x 6) and W are (16 x 17) and W is sharded across
+    4 GPUs creating 3 shards of (16 x 5) and 1 shard of (16 x 2).
+    The algorithm is as follows:
+
+    1. First the input is broadcasted to all ranks, since this is SPMD we
+       actually do an all_gather for all the inputs resulting in 4 (4 x 6)
+       inputs on each rank.
+    2. Next we perform local embedding bag operation under the given mode by
+       apply each input (4 x 6) with the local shard (16 x 5) ((16 x 2) for the last).
+       This results in 4 (5 x 4) ((2 x 4) for the last) matrices on each rank.
+       We transpose the aggregation result.
+    3. Next, we concatenate these 4 matrices and perform an all2all to share the
+       appropriate (5 x 4) or (2 x 4) matrices to each rank.
+    4. Now, each rank receives a (17 x 4) matrix which is basically the
+       size of the result we need.
+    5. If placements are not in order any appropriate rearrangement of columns
+       are done for the (17 x 4) matrix and finally we transpose the output again.
+    6. If max_norm is specified, we manually sum up the norm and renorm. Because
+       the renorm must be in place, we need to override the local_shard to mimic
+       this behavior.
+    """
+    # Validate input params
+    _validate_embedding_bag_param(args, kwargs)
+
+    input = args[0]
+    weight = args[1]
+    offsets = kwargs.get("offsets")
+    per_sample_weights = kwargs.get("per_sample_weights")
+    mode = kwargs.get("mode")
+    max_norm = kwargs.get("max_norm")
+    norm_type = kwargs.get("norm_type")
+    include_last_offset = kwargs.get("include_last_offset")
+    padding_idx = kwargs.get("padding_idx")
+
+    local_shard = weight.local_tensor().contiguous()
+    sharding_dim = weight._sharding_spec.dim
+    world_size = dist.get_world_size(pg)
+    rank = dist.get_rank(pg)
+    if include_last_offset:
+        offsets = offsets[:-1]
+
+    if sharding_dim == 1:
+        output, local_shard = _handle_col_wise_sharding(
+            input,
+            world_size,
+            weight,
+            local_shard,
+            offsets,
+            per_sample_weights,
+            mode,
+            max_norm,
+            norm_type,
+            padding_idx,
+            pg,
+        )
+        weight.local_shards()[0].tensor = local_shard
+        return output
+    elif sharding_dim == 0:
+        return _handle_row_wise_sharding(
+            input,
+            world_size,
+            weight,
+            local_shard,
+            offsets,
+            per_sample_weights,
+            mode,
+            max_norm,
+            norm_type,
+            padding_idx,
+            rank,
+            pg,
+        )
+    else:
+        raise RuntimeError(
+            f"nn.EmbeddingBag weight sharded on dim {sharding_dim} not supported!"
+        )
+
+
+def _validate_embedding_bag_param(args, kwargs):
+    """
+    Validate input params of sharded embeddingBag op.
+
+    Args:
+        input: list of ID used for lookup and aggregation.
+        weight: sharded weight tensor.
+        kwargs: same as normal EmbeddingBag.
+
+    Return: None.
+    """
+
+    input = args[0]
+    weight = args[1]
+    offsets = kwargs.get("offsets")
+    per_sample_weights = kwargs.get("per_sample_weights")
+    mode = kwargs.get("mode")
+    max_norm = kwargs.get("max_norm")
+    scale_grad_by_freq = kwargs.get("scale_grad_by_freq")
+    sparse = kwargs.get("sparse")
+    include_last_offset = kwargs.get("include_last_offset")
+
+    # Validate types
+    if not isinstance(input, torch.Tensor):
+        raise TypeError("input need to be torch.Tensor")
+    if offsets is not None and not isinstance(offsets, torch.Tensor):
+        raise TypeError("offsets need to be torch.Tensor")
+    if per_sample_weights is not None and not isinstance(
+        per_sample_weights, torch.Tensor
+    ):
+        raise TypeError("per_sample_weights need to be torch.Tensor")
+    if not isinstance(weight, ShardedTensor):
+        raise TypeError("weight needs to be ShardedTensor")
+    if len(input.size()) > 2:
+        raise ValueError("Input more than 2 dims not supported")
+    weight_size = weight.size()
+    if len(weight_size) != 2:
+        raise ValueError("Weight needs to have exactly 2 dims")
+    if int(torch.min(input).item()) < 0:
+        raise ValueError(
+            "Index out of range in Input %d %d",
+            int(torch.min(input).item()),
+            weight_size[1],
+        )
+    if int(torch.max(input).item()) >= weight_size[0]:
+        raise ValueError(
+            "Index out of range in Input %d %d",
+            int(torch.max(input).item()),
+            weight_size[1],
+        )
+    if offsets is not None and len(input.size()) != 1:
+        raise ValueError("Input dimension needs to be exactly 1 dim")
+    if len(input.size()) == 1 and offsets is None:
+        raise ValueError("offsets is required for 1D input")
+    if per_sample_weights is not None and per_sample_weights.size() != input.size():
+        raise ValueError(
+            f"per_sample_weights size {per_sample_weights.size()} not equal to input size {input.size()}"
+        )
+    if mode is None:
+        mode = "mean"
+    if mode not in ["sum", "mean", "max"]:
+        raise ValueError(f"mode '{mode}' is not supported")
+    if scale_grad_by_freq:
+        raise RuntimeError(
+            'nn.Embedding weight sharded with flag on "scale_grad_by_freq" not supported!'
+        )
+    if sparse:
+        raise RuntimeError(
+            'nn.Embedding weight sharded with flag on "sparse" not supported!'
+        )
+    if include_last_offset and offsets is None:
+        raise ValueError('offsets is required for flag "include_last_offset"!')
+    if include_last_offset and cast(List[int], offsets)[-1] != input.size(0):
+        raise ValueError(
+            'offsets need to have the input size in the end when the flag "include_last_offset" is on!'
+        )
+
+    if max_norm and max_norm <= 0.0:
+        raise ValueError('"max_norm" must be larger than zero!')
+
+    if not isinstance(weight._sharding_spec, ChunkShardingSpec):
+        raise ValueError("Only ChunkShardingSpec supported for ShardedTensor ops!")
+    if len(weight.local_shards()) != 1:
+        raise ValueError("Only one local shard supported!")
+
+
+def _handle_col_wise_sharding(
+    input,
+    world_size,
+    weight,
+    local_shard,
+    offsets,
+    per_sample_weights,
+    mode,
+    max_norm,
+    norm_type,
+    padding_idx,
+    pg,
+):
+    """
+    Entry-point function to handle the logic of col-wise sharding of weight
+    for embeddingBag. (Detailed explanations of the logic can be found in
+    the comment for sharded_embedding_bag.)
+
+    Args:
+        input: list of ID used for lookup and aggregation.
+        world_size: number of ranks.
+        weight: sharded weight tensor.
+        local_shard: col-wise shared local weight used for lookup.
+        offsets: list of start positions of each bag for 1D input.
+        per_sample_weights: weights for weighted sum mode.
+        mode: aggregation method of each bag.
+        max_norm: If given, each embedding vector with norm larger
+            than max_norm is renormalized to have norm max_norm.
+            Note: this will modify weight in-place.
+        norm_type: The p in the p-norm to compute for the max_norm option.
+        padding_idx: If specified, the entries at padding_idx do
+            not contribute to the gradient; therefore, the embedding
+            vector at padding_idx is not updated during training,
+            i.e. it remains as a fixed "pad".
+            Note that the embedding vector at padding_idx is
+            excluded from the reduction.
+        pg: process group.
+
+    Return:
+        output: final result of lookup and aggregation.
+        local_shard: col-wise shared local weight used for lookup.
+            If max_norm, this will be the renormed weight.
+    """
+    # allgather the special input of embedding bag first.
+    (
+        gathered_inputs,
+        gathered_per_sample_weights,
+        gathered_offsets,
+    ) = _all_gather_embedding_bag_input(input, per_sample_weights, offsets, pg)
+
+    if max_norm is not None:
+        # max_norm changes the weight in-place
+        local_shard = _handle_max_norm_col_wise(
+            max_norm, norm_type, local_shard, input, world_size, gathered_inputs, pg
+        )
+
+    output = _handle_col_wise_sharding_base(
+        torch.nn.functional.embedding_bag,
+        1,
+        input,
+        world_size,
+        weight,
+        local_shard,
+        pg,
+        gathered_inputs,
+        mode=mode,
+        gathered_per_sample_weights=gathered_per_sample_weights,
+        gathered_offsets=gathered_offsets,
+        padding_idx=padding_idx,
+    )
+    return (output, local_shard)
+
+
+def _handle_row_wise_sharding(
+    input,
+    world_size,
+    weight,
+    local_shard,
+    offsets,
+    per_sample_weights,
+    mode,
+    max_norm,
+    norm_type,
+    padding_idx,
+    rank,
+    pg,
+):
+    """
+    Entry-point function to handle the logic of row-wise sharding of weight
+    for embeddingBag. (Detailed explanations of the logic can be found in
+    the comment for sharded_embedding_bag.)
+
+    Args:
+        input: list of ID used for lookup and aggregation.
+        world_size: number of ranks.
+        weight: sharded weight tensor.
+        local_shard: row-wise shared local weight used for lookup.
+        offsets: list of start positions of each bag for 1D input.
+        per_sample_weights: weights for weighted sum mode.
+        mode: aggregation method of each bag.
+        max_norm: If given, each embedding vector with norm larger
+            than max_norm is renormalized to have norm max_norm.
+            Note: this will modify weight in-place.
+        norm_type: The p in the p-norm to compute for the max_norm option.
+        padding_idx: If specified, the entries at padding_idx do
+            not contribute to the gradient; therefore, the embedding
+            vector at padding_idx is not updated during training,
+            i.e. it remains as a fixed "pad".
+            Note that the embedding vector at padding_idx is
+            excluded from the reduction.
+        rank: # of cuda process.
+        pg: process group.
+
+    Returns:
+        gathered_output: final result of lookup and aggregation.
+    """
+    if input.dim() > 1 and per_sample_weights is None:
+        # allgather the inputs first for non Replicated Tensor.
+        gather_inp = _all_gather_base_input(input, pg)
+    else:
+        (
+            gathered_inputs,
+            gathered_per_sample_weights,
+            gathered_offsets,
+        ) = _all_gather_embedding_bag_input(input, per_sample_weights, offsets, pg)
+        cat_dim = 0 if input.dim() != 1 else -1
+        gather_inp = torch.cat(gathered_inputs, dim=cat_dim)
+        if per_sample_weights is not None:
+            per_sample_weights = torch.cat(gathered_per_sample_weights, dim=cat_dim)
+        offset_add = 0 if input.dim() > 1 else input.size(0)
+        if offsets is not None:
+            offsets_list = torch.cat(
+                [gathered_offsets[i] + (offset_add * i) for i in range(pg.size())],
+                dim=cat_dim,
+            )
+
+    # Mask the input according to sharding spec.
+    lookup_input, padding_local, padding_row = _handle_row_wise_mask(
+        gather_inp, padding_idx, weight, world_size, rank
+    )
+    if mode == "max":
+        padding_row[:] = -float("Inf")
+
+    # When input is a large tensor, the value of weight is changed.
+    # This is a walk-around for now. GH issue: #81717.
+    if max_norm is not None:
+        torch.nn.functional.embedding_bag(
+            torch.unique(lookup_input)[:-1],
+            local_shard,
+            offsets=torch.tensor([0], device=local_shard.device, dtype=torch.long),
+            mode=mode,
+            per_sample_weights=None,
+            max_norm=max_norm,
+            norm_type=norm_type,
+            padding_idx=padding_local,
+        )
+        max_norm = None
+    result = torch.nn.functional.embedding_bag(
+        lookup_input,
+        torch.cat([local_shard, padding_row]),
+        offsets=offsets_list if offsets is not None else offsets,  # type: ignore[possibly-undefined]
+        mode=mode if mode != "mean" else "sum",
+        per_sample_weights=per_sample_weights,
+        max_norm=max_norm,
+        norm_type=norm_type,
+        padding_idx=padding_local,
+    )
+
+    op = ReduceOp.SUM if mode != "max" else ReduceOp.MAX
+    # TODO: Make the result a PartialTensor and move the logic below there.
+    local_shards = result.chunk(pg.size())
+    result = reduce_scatter(
+        torch.empty_like(local_shards[0]),
+        list(local_shards),
+        op=op,
+        group=pg,
+    )
+
+    # For Mean, we cannot do the division until very end because the sum of means
+    # not equal to the mean of sum. (Divisor is different)
+    if mode == "mean":
+        if input.dim() > 1:
+            padding_idx = padding_idx if padding_idx is not None else -1
+            split_sizes = torch.sum(
+                torch.ne(input, padding_idx), dim=-1, dtype=local_shard.dtype
+            )
+        else:
+            split_sizes = torch.cat(
+                (
+                    offsets[1 : offsets.size(0)] - offsets[0:-1],
+                    (input.size(0) - offsets[-1]).unsqueeze(0),
+                ),
+                dim=-1,
+            )
+        return torch.div(result, split_sizes.unsqueeze(1))
+
+    # Return the appropriate local result.
+    return result
+
+
+def _all_gather_embedding_bag_input(input, per_sample_weights, offsets, pg):
+    """
+    In case we need to gather input and all other parameters of embeddingBag
+    ops, we need to stack all input together to perform ``all_gather``
+    collective communication just once.
+
+    Note that since offsets does not share the same size as input and
+    is always smaller than input, we resize it during the communication.
+
+    Args:
+        input: tensor to be applied op on.
+        per_sample_weights: weights for weighted sum mode.
+        offsets: when input is 1D. offsets determines the starting
+            index position of each bag (sequence) in input.
+        pg: process group.
+
+    Returns:
+        gathered_inputs: list of input tensor gathered from each rank.
+        gathered_per_sample_weights: list of per_sample_weights from each rank.
+        gathered_offsets: list of offsets from each rank.
+    """
+    input_to_gather = [input]
+    if per_sample_weights is not None:
+        input_to_gather.append(per_sample_weights)
+    if offsets is not None:
+        input_to_gather.append(offsets.clone().resize_(input.size()))
+    gathered_inputs = all_gather(torch.stack(input_to_gather), group=pg)
+
+    gathered_per_sample_weights = None
+    if per_sample_weights is not None:
+        gathered_per_sample_weights = [t[1] for t in gathered_inputs]
+    gathered_offsets = None
+    if offsets is not None:
+        idx = 2 if per_sample_weights is not None else 1
+        gathered_offsets = [
+            t[idx].resize_(offsets.size()).to(offsets.dtype) for t in gathered_inputs
+        ]
+    gathered_inputs = [t[0].to(input.dtype) for t in gathered_inputs]
+    return gathered_inputs, gathered_per_sample_weights, gathered_offsets
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_sharded_tensor/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_sharded_tensor/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e6f4d2a1a6ec4114948399e0e882111786cf3e4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_sharded_tensor/__init__.py
@@ -0,0 +1,21 @@
+# Keep old package for BC purposes, this file should be removed once
+# everything moves to the `torch.distributed._shard` package.
+import sys
+import warnings
+
+import torch
+from torch.distributed._shard.sharded_tensor import *  # noqa: F403
+
+
+with warnings.catch_warnings():
+    warnings.simplefilter("always")
+    warnings.warn(
+        "`torch.distributed._sharded_tensor` will be deprecated, "
+        "use `torch.distributed._shard.sharded_tensor` instead",
+        DeprecationWarning,
+        stacklevel=2,
+    )
+
+sys.modules[
+    "torch.distributed._sharded_tensor"
+] = torch.distributed._shard.sharded_tensor
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_sharded_tensor/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_sharded_tensor/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b47becec44576bf6ce77fe8e7af78dc9c6574d79
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_sharded_tensor/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_sharding_spec/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_sharding_spec/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c74dd3633e0f5e8436b844fd2d14f3bdb00635b7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_sharding_spec/__init__.py
@@ -0,0 +1,22 @@
+# Keep old package for BC purposes, this file should be removed once
+# everything moves to the `torch.distributed._shard` package.
+import sys
+import warnings
+
+import torch
+from torch.distributed._shard.sharding_spec import *  # noqa: F403
+
+
+with warnings.catch_warnings():
+    warnings.simplefilter("always")
+    warnings.warn(
+        "`torch.distributed._sharding_spec` will be deprecated, "
+        "use `torch.distributed._shard.sharding_spec` instead",
+        DeprecationWarning,
+        stacklevel=2,
+    )
+
+import torch.distributed._shard.sharding_spec as _sharding_spec
+
+
+sys.modules["torch.distributed._sharding_spec"] = _sharding_spec
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_sharding_spec/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_sharding_spec/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bba0a3ce76e412101a14e67c6be81de03cadb2bc
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_sharding_spec/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_symmetric_memory/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_symmetric_memory/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4773bbb930d85d46d74cf3763d7241f7ef976ad7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_symmetric_memory/__init__.py
@@ -0,0 +1,1008 @@
+# mypy: allow-untyped-decorators
+import socket
+import uuid
+from contextlib import contextmanager
+from datetime import timedelta
+from functools import partial
+from typing import Any, Callable, Dict, Generator, List, Optional, Tuple
+
+import torch
+import torch.distributed._functional_collectives as funcol
+import torch.distributed.distributed_c10d as c10d
+from torch._C._distributed_c10d import _SymmetricMemory, Work as _Work
+
+
+_group_name_to_store: Dict[str, c10d.Store] = {}
+
+
+def enable_symm_mem_for_group(group_name: str) -> None:
+    """
+    Enables symmetric memory for a process group.
+
+    Args:
+        group_name (str): the name of the process group.
+    """
+    if group_name in _group_name_to_store:
+        return
+
+    group = c10d._resolve_process_group(group_name)
+    global_ranks = sorted(c10d._world.pg_group_ranks[group].keys())
+    # Different subgroups with the same name should use different stores
+    global_ranks_str = "_".join(map(str, global_ranks))
+    store = c10d.PrefixStore(
+        f"symmetric_memory-{global_ranks_str}",
+        c10d._get_process_group_store(group),
+    )
+    # Use one store-based broadcast to bootstrap a file store from the process
+    # and simultaneously verify that all ranks are on the same host.
+    hostname = socket.gethostname()
+    if group.rank() == 0:
+        uid = str(uuid.uuid4())
+        msg = f"{hostname}/{uid}"
+        store.set("init", msg)
+    else:
+        msg = store.get("init").decode("utf-8")
+        tokens = msg.split("/")
+        assert len(tokens) == 2, tokens
+        rank_0_hostname, uid = tokens
+        if hostname != rank_0_hostname:
+            raise RuntimeError(
+                "init_symmetric_memory_for_process_group() failed for "
+                f'group "{group_name}". Rank 0 and rank {group.rank()} '
+                f"are on different hosts ({rank_0_hostname} and {hostname})"
+            )
+    store = torch._C._distributed_c10d.FileStore(f"/tmp/{uid}", group.size())
+    # TODO: check device connectiivity
+    _group_name_to_store[group_name] = store
+    _SymmetricMemory.set_group_info(
+        group_name,
+        group.rank(),
+        group.size(),
+        store,
+    )
+
+
+_is_test_mode: bool = False
+
+
+@contextmanager
+def _test_mode() -> Generator[None, None, None]:
+    """
+    Forces ``is_symm_mem_enabled_for_group()`` to return ``True`` and the ops
+    defined in the ``symm_mem`` namespace to use fallback implementations.
+
+    The context manager is not thread safe.
+    """
+    global _is_test_mode
+    prev = _is_test_mode
+    try:
+        _is_test_mode = True
+        yield
+    finally:
+        _is_test_mode = prev
+
+
+def is_symm_mem_enabled_for_group(group_name: str) -> bool:
+    """
+    Check if symmetric memory is enabled for a process group.
+
+    Args:
+        group_name (str): the name of the process group.
+    """
+    return _is_test_mode or group_name in _group_name_to_store
+
+
+_group_name_to_workspace_tensor: Dict[str, Optional[torch.Tensor]] = {}
+
+
+def get_symm_mem_workspace(group_name: str, min_size: int) -> _SymmetricMemory:
+    """
+    Get the symmetric memory workspace associated with the process group. If
+    ``min_size`` is greater than the workspace associated with ``group_name``,
+    the workspace will be re-allocated and re-rendezvous'd.
+
+    Args:
+        group_name (str): the name of the process group.
+        min_size (int): the size requirement for the workspace in bytes.
+
+    Returns:
+        _SymmetricMemory: the symmetric memory workspace associated with the
+        group.
+    """
+    tensor = _group_name_to_workspace_tensor.get(group_name)
+    size = tensor.numel() * tensor.element_size() if tensor is not None else 0
+    if tensor is None or size < min_size:
+        tensor = _SymmetricMemory.empty_strided_p2p(
+            (max(size, min_size),),
+            [1],
+            torch.uint8,
+            torch.device(f"cuda:{torch.cuda.current_device()}"),
+            group_name,
+        )
+        _group_name_to_workspace_tensor[group_name] = tensor
+    return _SymmetricMemory.rendezvous(tensor)
+
+
+_backend_stream: Optional[torch.cuda.Stream] = None
+
+
+def _get_backend_stream() -> torch.cuda.Stream:
+    global _backend_stream
+    if _backend_stream is None:
+        _backend_stream = torch.cuda.Stream()
+    return _backend_stream
+
+
+def _pipelined_all_gather_and_consume(
+    shard: torch.Tensor,
+    shard_consumer: Callable[[torch.Tensor, int], None],
+    ag_out: torch.Tensor,
+    group_name: str,
+) -> None:
+    """
+    Perform the following logic with micro-pipelined computation and
+    communication:
+
+        tensor = all_gather_tensor(shard, gather_dim=1, group=group)
+        chunks = tensor.chunk(group.size())
+        for src_rank, chunk in enumerate(chunks):
+            shard_consumer(chunk, src_rank)
+
+    NOTE:
+    - The shard passed to shard consumer will always be contiguous.
+    """
+    p2p_workspace_size_req = shard.numel() * shard.element_size()
+    symm_mem = get_symm_mem_workspace(group_name, min_size=p2p_workspace_size_req)
+    group_size = symm_mem.world_size
+    rank = symm_mem.rank
+
+    backend_stream = _get_backend_stream()
+    backend_stream.wait_stream(torch.cuda.current_stream())
+    local_p2p_buf = symm_mem.get_buffer(rank, shard.shape, shard.dtype)
+
+    chunks = ag_out.chunk(group_size)
+
+    # While consuming local shard, copy it to the local p2p buffer
+    # in another stream.
+    shard_consumer(shard, rank)
+    chunks[rank].copy_(shard)
+
+    with torch.cuda.stream(backend_stream):
+        local_p2p_buf.copy_(shard)
+        symm_mem.barrier(channel=0)
+    torch.cuda.current_stream().wait_stream(backend_stream)
+
+    # At this point, all ranks have copied their local shard to
+    # their local p2p buffer. Each rank can now copy and consume
+    # remote shards.
+    for step in range(1, group_size):
+        if step % 2 == 0:
+            stream = torch.cuda.current_stream()
+        else:
+            stream = backend_stream
+        remote_rank = (step + rank) % group_size
+        remote_p2p_buf = symm_mem.get_buffer(remote_rank, shard.shape, shard.dtype)
+        with torch.cuda.stream(stream):
+            chunks[remote_rank].copy_(remote_p2p_buf)
+            shard_consumer(chunks[remote_rank], remote_rank)
+
+    with torch.cuda.stream(backend_stream):
+        symm_mem.barrier(channel=group_size % 2)
+    torch.cuda.current_stream().wait_stream(backend_stream)
+
+
+def _pipelined_produce_and_all2all(
+    chunk_producer: Callable[[int, torch.Tensor], None],
+    output: torch.Tensor,
+    group_name: str,
+) -> None:
+    """
+    Perform the following logic with micro-pipelined computation and
+    communication:
+
+        chunks = [
+            chunk_producer(dst_rank, chunks[dst_rank])
+            for dst_rank in range(group_size):
+        ]
+        dist.all_to_all_single(output=output, input=torch.cat(chunks))
+    """
+    out_chunks = output.chunk(c10d._get_group_size_by_name(group_name))
+    p2p_workspace_size_req = out_chunks[0].numel() * out_chunks[0].element_size() * 2
+    symm_mem = get_symm_mem_workspace(group_name, min_size=p2p_workspace_size_req)
+    group_size = symm_mem.world_size
+    rank = symm_mem.rank
+
+    backend_stream = _get_backend_stream()
+    backend_stream.wait_stream(torch.cuda.current_stream())
+
+    def get_p2p_buf(rank: int, idx: int) -> torch.Tensor:
+        assert idx in (0, 1)
+        offset = 0 if idx == 0 else out_chunks[0].numel()
+        return symm_mem.get_buffer(
+            rank, out_chunks[0].shape, out_chunks[0].dtype, offset
+        )
+
+    # Prepare two local p2p buffers, so that a remote rank can pull the result
+    # of step [i] in one p2p buffer while the local rank can compute the
+    # result of step [i+1] and write it directly the other p2p buffer.
+    local_p2p_buf_0 = get_p2p_buf(rank, 0)
+    local_p2p_buf_1 = get_p2p_buf(rank, 1)
+
+    for step in range(1, group_size):
+        remote_rank = (rank - step) % group_size
+        if step % 2 == 0:
+            stream = torch.cuda.current_stream()
+            other_stream = backend_stream
+            p2p_buf = local_p2p_buf_1
+            remote_p2p_buf = get_p2p_buf(remote_rank, 1)
+        else:
+            stream = backend_stream
+            other_stream = torch.cuda.current_stream()
+            p2p_buf = local_p2p_buf_0
+            remote_p2p_buf = get_p2p_buf(remote_rank, 0)
+        with torch.cuda.stream(stream):
+            chunk_producer((rank + step) % group_size, p2p_buf)
+            symm_mem.barrier(channel=step % 2)
+            # Make the other stream to wait for the barrier on the current
+            # stream to finish before chunk_producer to avoid the compute
+            # delaying the barrier.
+            other_stream.wait_stream(stream)
+            out_chunks[remote_rank].copy_(remote_p2p_buf)
+
+    chunk_producer(rank, out_chunks[rank])
+    torch.cuda.current_stream().wait_stream(backend_stream)
+
+
+lib = torch.library.Library("symm_mem", "DEF")  # noqa: TOR901
+lib.define(
+    "fused_all_gather_matmul(Tensor A, Tensor[] Bs, int gather_dim, str group_name) -> (Tensor, Tensor[])"
+)
+lib.define(
+    "fused_all_gather_scaled_matmul("
+    "Tensor A, Tensor[] Bs, Tensor A_scale, Tensor[] B_scales, "
+    "int gather_dim, str group_name, "
+    "Tensor?[] biases, "
+    "Tensor?[] result_scales, "
+    "ScalarType?[] out_dtypes, "
+    "bool[] use_fast_accum) -> (Tensor, Tensor[])"
+)
+lib.define(
+    "fused_matmul_reduce_scatter(Tensor A, Tensor B, str reduce_op, int scatter_dim, str group_name) -> Tensor"
+)
+lib.define(
+    "fused_scaled_matmul_reduce_scatter("
+    "Tensor A, Tensor B, Tensor A_scale, Tensor B_scale, "
+    "str reduce_op, int scatter_dim, str group_name, "
+    "Tensor? bias = None, "
+    "Tensor? result_scale = None, "
+    "ScalarType? out_dtype = None, "
+    "bool use_fast_accum = False) -> Tensor"
+)
+lib.define("_low_contention_all_gather(Tensor tensor, str group_name) -> Tensor")
+lib.define(
+    "_low_contention_reduce_scatter(Tensor tensor, str reduce_op, str group_name) -> Tensor"
+)
+
+
+def _fused_all_gather_matmul_impl(
+    mm_out_op: torch._ops.OpOverload,
+    A_shard: torch.Tensor,
+    Bs: List[torch.Tensor],
+    kwargs_list: List[Dict[str, Any]],
+    out_dtypes: List[Optional[torch.dtype]],
+    gather_dim: int,
+    group_name: str,
+) -> Tuple[torch.Tensor, List[torch.Tensor]]:
+    if A_shard.dim() < 2:
+        raise ValueError("A_shard must be a matrix")
+    for B in Bs:
+        if B.dim() != 2:
+            raise ValueError("B must be a matrix")
+    if len(out_dtypes) != len(Bs):
+        raise ValueError("len(out_types) must be the same as len(Bs)")
+    if len(kwargs_list) != len(Bs):
+        raise ValueError("len(kwargs_list) must be the same as len(Bs)")
+    if gather_dim < 0 or gather_dim >= A_shard.dim():
+        raise ValueError("Invalid gather_dim")
+
+    group = c10d._resolve_process_group(group_name)
+
+    # Move the gather_dim to the front and flatten the tensor into a 2D matrix.
+    # The flattened tensor doesn't need to be contiguous (for computation
+    # efficiency), as _pipelined_all_gather_and_consume guarantees that shards
+    # passed to shard_consumer are contiguous.
+    x = A_shard.movedim(gather_dim, 0)
+    leading_dims = [group.size()] + list(x.shape[:-1])
+    x = x.flatten(0, -2)
+
+    # Helper function for reverting the above transformation
+    def unflatten(t: torch.Tensor) -> torch.Tensor:
+        return t.view(*leading_dims, -1).flatten(0, 1).movedim(0, gather_dim)
+
+    ag_out = x.new_empty(
+        x.shape[0] * group.size(),
+        x.shape[1],
+    )
+    outputs = [
+        x.new_empty(x.shape[0] * group.size(), B.shape[1], dtype=out_dtype or B.dtype)
+        for B, out_dtype in zip(Bs, out_dtypes)
+    ]
+    output_shards = [output.chunk(group.size()) for output in outputs]
+
+    # Computing block-wise matmul along the first dim of A
+    def shard_consumer(shard: torch.Tensor, rank: int) -> None:
+        for idx, (B, kwargs) in enumerate(zip(Bs, kwargs_list)):
+            mm_out_op(shard, B, **kwargs, out=output_shards[idx][rank])
+
+    _pipelined_all_gather_and_consume(
+        x,
+        shard_consumer,
+        ag_out,
+        group_name,
+    )
+    return unflatten(ag_out), [unflatten(output) for output in outputs]
+
+
+@torch.library.impl(lib, "fused_all_gather_matmul", "Meta")
+def _fused_all_gather_matmul_fallback(
+    A_shard: torch.Tensor,
+    Bs: List[torch.Tensor],
+    gather_dim: int,
+    group_name: str,
+) -> Tuple[torch.Tensor, List[torch.Tensor]]:
+    group_size = c10d._get_group_size_by_name(group_name)
+    A = torch.ops._c10d_functional.all_gather_into_tensor(
+        A_shard.contiguous(), group_size, group_name
+    )
+    A = torch.ops._c10d_functional.wait_tensor(A)
+    A = A.view(group_size, *A_shard.shape).movedim(gather_dim + 1, 1).flatten(0, 1)
+    return A.movedim(0, gather_dim), [
+        torch.matmul(A, B).movedim(0, gather_dim) for B in Bs
+    ]
+
+
+@torch.library.impl(lib, "fused_all_gather_matmul", "CUDA")
+def _fused_all_gather_matmul(
+    A_shard: torch.Tensor,
+    Bs: List[torch.Tensor],
+    gather_dim: int,
+    group_name: str,
+) -> Tuple[torch.Tensor, List[torch.Tensor]]:
+    """
+    Perform the following logic with micro-pipelined computation and
+    communication:
+
+        all_gather_tensor(A_shard, gather_dim, group_name) @ B
+
+    Optimal stride order for A_shard - if A_shard.movedim(gather_dim, 0) is
+    contiguous, no extra copy is required for input layout transformation.
+    Otherwise A_shard needs to be copied once.
+    """
+    if _is_test_mode:
+        return _fused_all_gather_matmul_fallback(A_shard, Bs, gather_dim, group_name)
+
+    with torch.profiler.record_function("fused_all_gather_matmul"):
+        return _fused_all_gather_matmul_impl(
+            torch.ops.aten.mm.out,
+            A_shard,
+            Bs,
+            [{} for B in Bs],
+            [B.dtype for B in Bs],
+            gather_dim,
+            group_name,
+        )
+
+
+@torch.library.impl(lib, "fused_all_gather_scaled_matmul", "Meta")
+def _fused_all_gather_scaled_matmul_fallback(
+    A_shard: torch.Tensor,
+    Bs: List[torch.Tensor],
+    A_scale: torch.Tensor,
+    B_scales: List[torch.Tensor],
+    gather_dim: int,
+    group_name: str,
+    biases: List[Optional[torch.Tensor]],
+    result_scales: List[Optional[torch.Tensor]],
+    out_dtypes: List[Optional[torch.dtype]],
+    use_fast_accum: List[bool],
+) -> Tuple[torch.Tensor, List[torch.Tensor]]:
+    out_dtypes = _maybe_convert_scalar_types_to_dtypes(out_dtypes)
+
+    group_size = c10d._get_group_size_by_name(group_name)
+    A = torch.ops._c10d_functional.all_gather_into_tensor(
+        A_shard.contiguous(), group_size, group_name
+    )
+    A = torch.ops._c10d_functional.wait_tensor(A)
+    A = A.view(group_size, *A_shard.shape).movedim(gather_dim + 1, 1).flatten(0, 1)
+
+    def scaled_matmul(
+        A: torch.Tensor,
+        B: torch.Tensor,
+        A_scale: torch.Tensor,
+        B_scale: torch.Tensor,
+        bias: Optional[torch.Tensor],
+        result_scale: Optional[torch.Tensor],
+        out_dtype: Optional[torch.dtype],
+        use_fast_accum: bool,
+    ) -> torch.Tensor:
+        leading_dims = A.shape[:-1]
+        res = torch.ops.aten._scaled_mm(
+            A.flatten(0, -2), B, A_scale, B_scale, out_dtype=out_dtype
+        )
+        return res.unflatten(0, leading_dims)
+
+    return A.movedim(0, gather_dim), [
+        scaled_matmul(
+            A, B, A_scale, B_scale, bias, result_scale, out_dtype, fast_accum
+        ).movedim(0, gather_dim)
+        for B, B_scale, bias, result_scale, out_dtype, fast_accum in zip(
+            Bs, B_scales, biases, result_scales, out_dtypes, use_fast_accum
+        )
+    ]
+
+
+@torch.library.impl(lib, "fused_all_gather_scaled_matmul", "CUDA")
+def _fused_all_gather_scaled_matmul(
+    A_shard: torch.Tensor,
+    Bs: List[torch.Tensor],
+    A_scale: torch.Tensor,
+    B_scales: List[torch.Tensor],
+    gather_dim: int,
+    group_name: str,
+    biases: List[Optional[torch.Tensor]],
+    result_scales: List[Optional[torch.Tensor]],
+    out_dtypes: List[Optional[torch.dtype]],
+    use_fast_accum: List[bool],
+) -> Tuple[torch.Tensor, List[torch.Tensor]]:
+    """
+    Perform the following logic with micro-pipelined computation and
+    communication:
+
+        A = all_gather_tensor(A_shard, gather_dim, group_name)
+        leading_dims = A.shape[:-1]
+        res = torch.ops.aten._scaled_mm(A.flatten(0, -2), B, A_scale, B_scale)
+        res = res.unflatten(0, leading_dims)
+
+    Optimal stride order for A_shard - if A_shard.movedim(gather_dim, 0) is
+    contiguous, no extra copy is required for input layout transformation.
+    Otherwise A_shard needs to be copied once.
+    """
+    out_dtypes = _maybe_convert_scalar_types_to_dtypes(out_dtypes)
+
+    if len(biases) != len(Bs):
+        raise ValueError("len(biases) must be the same as len(Bs)")
+    if len(result_scales) != len(Bs):
+        raise ValueError("len(result_scales) must be the same as len(Bs)")
+    if len(out_dtypes) != len(Bs):
+        raise ValueError("len(out_dtypes) must be the same as len(Bs)")
+    if len(use_fast_accum) != len(Bs):
+        raise ValueError("len(use_gast_accum_list) must be the same as len(Bs)")
+
+    if _is_test_mode:
+        return _fused_all_gather_scaled_matmul_fallback(
+            A_shard,
+            Bs,
+            A_scale,
+            B_scales,
+            gather_dim,
+            group_name,
+            biases,
+            result_scales,
+            out_dtypes,
+            use_fast_accum,
+        )
+
+    with torch.profiler.record_function("fused_all_gather_scaled_matmul"):
+        return _fused_all_gather_matmul_impl(
+            torch.ops.aten._scaled_mm.out,
+            A_shard,
+            Bs,
+            [
+                {
+                    "scale_a": A_scale,
+                    "scale_b": B_scale,
+                    "bias": bias,
+                    "scale_result": result_scale,
+                    "out_dtype": out_dtype,
+                    "use_fast_accum": fast_accum,
+                }
+                for B_scale, bias, result_scale, out_dtype, fast_accum in zip(
+                    B_scales, biases, result_scales, out_dtypes, use_fast_accum
+                )
+            ],
+            out_dtypes,
+            gather_dim,
+            group_name,
+        )
+
+
+def make_contiguous_for_perm(
+    t: torch.Tensor,
+    perm: List[int],
+) -> torch.Tensor:
+    """
+    Restride `t` such that `t.permute(perm)` is contiguous.
+    """
+    inv_perm = [0] * len(perm)
+    for i, p in enumerate(perm):
+        inv_perm[p] = i
+    return t.permute(perm).contiguous().permute(inv_perm)
+
+
+def restride_A_shard_for_fused_all_gather_matmul(
+    t: torch.Tensor,
+    gather_dim: int,
+) -> torch.Tensor:
+    """
+    Restride the `A_shard` arg of `fused_all_gather_matmul` for optimal perf.
+    See the doc for `fused_all_gather_matmul` for detail.
+    """
+    perm = list(range(len(t.shape)))
+    perm.insert(0, perm.pop(gather_dim))
+    return make_contiguous_for_perm(t, perm)
+
+
+def _fused_matmul_reduce_scatter_impl(
+    mm_out_op: torch._ops.OpOverload,
+    A: torch.Tensor,
+    B: torch.Tensor,
+    kwargs: Dict[str, Any],
+    out_dtype: Optional[torch.dtype],
+    reduce_op: str,
+    scatter_dim: int,
+    group_name: str,
+) -> torch.Tensor:
+    if A.dim() < 2:
+        raise ValueError("A_shard must be a matrix")
+    if scatter_dim < 0 or scatter_dim >= A.dim():
+        raise ValueError("Invalid gather_dim")
+    if B.dim() != 2:
+        raise ValueError("B must be a matrix")
+    if reduce_op == "sum":
+        reduce_fn = partial(torch.sum, dim=0)
+    elif reduce_op == "avg":
+        reduce_fn = partial(torch.mean, dim=0)
+    else:
+        raise ValueError("reduce_op must be sum or avg")
+
+    group = c10d._resolve_process_group(group_name)
+    out_shape = [*A.shape[:-1], B.shape[1]]
+    out_shape[scatter_dim] //= group.size()
+
+    # Move the gather_dim to the front and flatten the tensor into a 2D matrix
+    x = A.movedim(scatter_dim, 0)
+    leading_dims = [group.size()] + list(x.shape[:-1])
+    leading_dims[1] //= group.size()
+    x = x.flatten(0, -2)
+    shards = x.chunk(group.size())
+
+    # Computing block-wise matmul along the first dim of A
+    def chunk_producer(rank: int, out: torch.Tensor) -> None:
+        mm_out_op(shards[rank], B, **kwargs, out=out)
+
+    stacked_partials = x.new_empty(x.shape[0], B.shape[1], dtype=out_dtype or A.dtype)
+
+    _pipelined_produce_and_all2all(
+        chunk_producer,
+        stacked_partials,
+        group_name,
+    )
+    # Ensures that the transpose and reduction produce contiguous result
+    # in a single reduction kernel.
+    return reduce_fn(
+        stacked_partials.view(*leading_dims, -1)
+        .movedim(1, scatter_dim + 1)
+        .movedim(0, scatter_dim),
+        dim=scatter_dim,
+    )
+
+
+@torch.library.impl(lib, "fused_matmul_reduce_scatter", "Meta")
+def _fused_matmul_reduce_scatter_fallback(
+    A: torch.Tensor,
+    B: torch.Tensor,
+    reduce_op: str,
+    scatter_dim: int,
+    group_name: str,
+) -> torch.Tensor:
+    res = funcol.reduce_scatter_tensor(A @ B, reduce_op, scatter_dim, group_name)
+    res = funcol.wait_tensor(res)
+    return res
+
+
+@torch.library.impl(lib, "fused_matmul_reduce_scatter", "CUDA")
+def _fused_matmul_reduce_scatter(
+    A: torch.Tensor,
+    B: torch.Tensor,
+    reduce_op: str,
+    scatter_dim: int,
+    group_name: str,
+) -> torch.Tensor:
+    """
+    Perform the following logic with micro-pipelined computation and
+    communication:
+
+        reduce_scatter_tensor(A @ B, reduce_op, scatter_dim, group_name)
+
+    Optimal stride order for A - if A.movedim(scatter_dim, 0) is contiguous, no
+    extra copy is required for input layout transformation. Otherwise A needs
+    to be copied once.
+    """
+    if _is_test_mode:
+        return _fused_matmul_reduce_scatter_fallback(
+            A, B, reduce_op, scatter_dim, group_name
+        )
+
+    with torch.profiler.record_function("fused_matmul_reduce_scatter"):
+        return _fused_matmul_reduce_scatter_impl(
+            mm_out_op=torch.ops.aten.mm.out,
+            A=A,
+            B=B,
+            kwargs={},
+            out_dtype=A.dtype,
+            reduce_op=reduce_op,
+            scatter_dim=scatter_dim,
+            group_name=group_name,
+        )
+
+
+@torch.library.impl(lib, "fused_scaled_matmul_reduce_scatter", "Meta")
+def _fused_scaled_matmul_reduce_scatter_fallback(
+    A: torch.Tensor,
+    B: torch.Tensor,
+    A_scale: torch.Tensor,
+    B_scale: torch.Tensor,
+    reduce_op: str,
+    scatter_dim: int,
+    group_name: str,
+    bias: Optional[torch.Tensor] = None,
+    result_scale: Optional[torch.Tensor] = None,
+    out_dtype: Optional[torch.dtype] = None,
+    use_fast_accum: bool = False,
+) -> torch.Tensor:
+    C = torch._scaled_mm(
+        A.flatten(0, -2).contiguous(),
+        B,
+        A_scale,
+        B_scale,
+        bias,
+        result_scale,
+        out_dtype,
+        use_fast_accum,
+    )
+    C = C.view(*A.shape[:-1], B.shape[1])
+    res = funcol.reduce_scatter_tensor(
+        C,
+        reduce_op,
+        scatter_dim,
+        group_name,
+    )
+    res = funcol.wait_tensor(res)
+    return res
+
+
+@torch.library.impl(lib, "fused_scaled_matmul_reduce_scatter", "CUDA")
+def _fused_scaled_matmul_reduce_scatter(
+    A: torch.Tensor,
+    B: torch.Tensor,
+    A_scale: torch.Tensor,
+    B_scale: torch.Tensor,
+    reduce_op: str,
+    scatter_dim: int,
+    group_name: str,
+    bias: Optional[torch.Tensor] = None,
+    result_scale: Optional[torch.Tensor] = None,
+    out_dtype: Optional[torch.dtype] = None,
+    use_fast_accum: bool = False,
+) -> torch.Tensor:
+    if _is_test_mode:
+        return _fused_scaled_matmul_reduce_scatter_fallback(
+            A,
+            B,
+            A_scale,
+            B_scale,
+            reduce_op,
+            scatter_dim,
+            group_name,
+            bias,
+            result_scale,
+            out_dtype,
+            use_fast_accum,
+        )
+    with torch.profiler.record_function("fused_matmul_reduce_scatter"):
+        return _fused_matmul_reduce_scatter_impl(
+            mm_out_op=torch.ops.aten._scaled_mm.out,
+            A=A,
+            B=B,
+            kwargs={
+                "scale_a": A_scale,
+                "scale_b": B_scale,
+                "bias": bias,
+                "scale_result": result_scale,
+                "out_dtype": out_dtype,
+                "use_fast_accum": use_fast_accum,
+            },
+            out_dtype=out_dtype,
+            reduce_op=reduce_op,
+            scatter_dim=scatter_dim,
+            group_name=group_name,
+        )
+
+
+def restride_A_for_fused_matmul_reduce_scatter(
+    t: torch.Tensor,
+    gather_dim: int,
+) -> torch.Tensor:
+    """
+    Restride the `A_shard` arg of `fused_matmul_reduce_scatter` for optimal
+    perf. See the doc for `fused_matmul_reduce_scatter` for detail.
+    """
+    perm = list(range(len(t.shape)))
+    perm.insert(0, perm.pop(gather_dim))
+    return make_contiguous_for_perm(t, perm)
+
+
+def _maybe_convert_scalar_types_to_dtypes(
+    scalar_types: List[Any],
+) -> List[Optional[torch.dtype]]:
+    """
+    When a list of `torch.dtype`s is passed through the dispatcher as
+    `ScalarType[]`, it is converted to a list of scalar type enum values. This
+    function converts it back to a list of `torch.dtype`s.
+    """
+    # Order defined in https://github.com/pytorch/pytorch/blob/344defc9733a45fee8d0c4d3f5530f631e823196/c10/core/ScalarType.h
+    _SCALAR_TYPE_TO_DTYPE = {
+        0: torch.uint8,
+        1: torch.int8,
+        2: torch.short,
+        3: torch.int,
+        4: torch.int64,
+        5: torch.half,
+        6: torch.float,
+        7: torch.double,
+        8: torch.complex32,
+        9: torch.complex64,
+        10: torch.complex128,
+        11: torch.bool,
+        12: torch.qint8,
+        13: torch.quint8,
+        14: torch.qint32,
+        15: torch.bfloat16,
+        16: torch.float8_e5m2,
+        17: torch.float8_e4m3fn,
+        18: torch.float8_e5m2fnuz,
+        19: torch.float8_e4m3fnuz,
+    }
+    if any(not isinstance(x, (type(None), int)) for x in scalar_types):
+        return scalar_types
+
+    dtypes: List[Optional[torch.dtype]] = []
+    for scalar_type in scalar_types:
+        if scalar_type is None:
+            dtypes.append(scalar_type)
+        elif scalar_type not in _SCALAR_TYPE_TO_DTYPE:
+            raise ValueError("Unrecognized scalar type {scalar_type}")
+        else:
+            dtypes.append(_SCALAR_TYPE_TO_DTYPE[scalar_type])
+    return dtypes
+
+
+class Work(_Work):
+    def __init__(self) -> None:
+        super().__init__()
+        self.event = torch.cuda.Event()
+        self.event.record()
+
+    def wait(self, timeout: timedelta = timedelta(seconds=0)) -> bool:
+        self.event.wait()
+        return True
+
+
+"""
+NOTE [low-contention collectives]
+When a collective is overlapped with abundant compute, it makes sense to
+prioritize reducing the contention between the collective and the overlapped
+compute, even at the cost of a slightly slower collective.
+
+Common collective implementations (e.g., NCCL without user buffer
+registration) optimize for throughput with no ambient compute. However, such
+implementations may not be optimal when they are overlapped with compute:
+- These implementations typically fuse the entire collective into a single
+kernel and reserve SM resources based on the most demanding portion of the
+collective, even when a large portion of the collective does not require this
+much resource.
+- These implementations often use SM-based P2P copy as opposed to copy
+engine-based P2P copy. Copy engine-based P2P copy may not have a significant
+advantage when there's no ambient compute. However, it may significantly
+improve overall resource utilization in the presence of ambient compute.
+
+When overlapped with intensive compute (e.g., persistent matmul kernels), the
+SM-usage of a collective can lead to inefficient overlapping.
+
+Low-contention collectives achieve their goals with the following strategies:
+- Use copy engine-based copy whenever possible.
+- Break down portions of a collective with different resource requirements
+into multiple kernels. This improves the overlapping efficiency at the cost
+of additional launching overhead.
+"""
+
+
+@torch.library.impl(lib, "_low_contention_all_gather", "Meta")
+def _low_contention_all_gather_meta(
+    tensor: torch.Tensor,
+    group_name: str,
+) -> torch.Tensor:
+    group_size = c10d._get_group_size_by_name(group_name)
+    return tensor.new_empty(tensor.shape[0] * group_size, *tensor.shape[1:])
+
+
+@torch.library.impl(lib, "_low_contention_all_gather", "CUDA")
+def _low_contention_all_gather(
+    tensor: torch.Tensor,
+    group_name: str,
+) -> torch.Tensor:
+    """
+    Performs all-gather with symmetric memory in a low-contention fashion.
+
+    When `tensor` is already in symmetric memory:
+        - The collective is carried out without using SMs.
+        - No symmetric memory workspace is required.
+
+    When `tensor` is not in symmetric memory:
+        - An extra SM-based copy is performed to copy the input data into the
+          symmetric memory workspace.
+        - Symmetric memory workspace size requirement: the size of `tensor`.
+    """
+    symm_mem = _SymmetricMemory.rendezvous(tensor)
+    if symm_mem is not None:
+        input_is_symm_mem = True
+    else:
+        symm_mem = get_symm_mem_workspace(
+            group_name, tensor.numel() * tensor.element_size()
+        )
+        input_is_symm_mem = False
+
+    rank = symm_mem.rank
+    world_size = symm_mem.world_size
+
+    output = tensor.new_empty(tensor.shape[0] * world_size, *tensor.shape[1:])
+    chunks = output.chunk(world_size)
+
+    _get_backend_stream().wait_stream(torch.cuda.current_stream())
+    with torch.cuda.stream(_get_backend_stream()):
+        if not input_is_symm_mem:
+            local_buf = symm_mem.get_buffer(rank, tensor.shape, tensor.dtype)
+            local_buf.copy_(tensor)
+        # pull
+        symm_mem.barrier()
+        for step in range(0, world_size):
+            remote_rank = (rank - step) % world_size
+            src_buf = symm_mem.get_buffer(remote_rank, tensor.shape, tensor.dtype)
+            chunks[remote_rank].copy_(src_buf)
+        symm_mem.barrier()
+        torch._C._distributed_c10d._register_work(output, Work())
+        return output
+
+
+@torch.library.impl(lib, "_low_contention_reduce_scatter", "Meta")
+def _low_contention_reduce_scatter_meta(
+    tensor: torch.Tensor,
+    reduce_op: str,
+    group_name: str,
+) -> torch.Tensor:
+    group_size = c10d._get_group_size_by_name(group_name)
+    return tensor.unflatten(0, (group_size, -1)).mean(dim=0)
+
+
+def _low_contention_reduce_scatter_with_symm_mem_input(
+    tensor: torch.Tensor,
+    reduce_op: str,
+    symm_mem: _SymmetricMemory,
+) -> torch.Tensor:
+    rank = symm_mem.rank
+    world_size = symm_mem.world_size
+
+    assert tensor.shape[0] % world_size == 0
+    a2a_res = torch.empty_like(tensor)
+    chunks = a2a_res.chunk(world_size)
+
+    _get_backend_stream().wait_stream(torch.cuda.current_stream())
+    with torch.cuda.stream(_get_backend_stream()):
+        # pull + offline reduction
+        symm_mem.barrier()
+        for step in range(0, world_size):
+            remote_rank = (rank - step) % world_size
+            src_buf = symm_mem.get_buffer(
+                remote_rank,
+                chunks[0].shape,
+                chunks[0].dtype,
+                chunks[0].numel() * rank,
+            )
+            chunks[remote_rank].copy_(src_buf)
+        symm_mem.barrier()
+
+        ret = a2a_res.unflatten(0, (world_size, -1))
+        if reduce_op == "sum":
+            ret = ret.sum(dim=0)
+        elif reduce_op == "avg":
+            ret = ret.mean(dim=0)
+        else:
+            raise ValueError(f"reduce_op ({reduce_op}) is not supported")
+        torch._C._distributed_c10d._register_work(ret, Work())
+        return ret
+
+
+def _low_contention_reduce_scatter_with_workspace(
+    tensor: torch.Tensor,
+    reduce_op: str,
+    workspace: _SymmetricMemory,
+) -> torch.Tensor:
+    rank = workspace.rank
+    world_size = workspace.world_size
+
+    assert tensor.shape[0] % world_size == 0
+    chunks = tensor.chunk(world_size)
+
+    _get_backend_stream().wait_stream(torch.cuda.current_stream())
+    with torch.cuda.stream(_get_backend_stream()):
+        # push + offline reduction
+        workspace.barrier()
+        for step in range(0, world_size):
+            remote_rank = (rank - step) % world_size
+            dst_buf = workspace.get_buffer(
+                remote_rank, chunks[0].shape, chunks[0].dtype, chunks[0].numel() * rank
+            )
+            dst_buf.copy_(chunks[remote_rank])
+        workspace.barrier()
+
+        buf = workspace.get_buffer(rank, tensor.shape, tensor.dtype)
+        ret = buf.unflatten(0, (world_size, -1))
+        if reduce_op == "sum":
+            ret = ret.sum(dim=0)
+        elif reduce_op == "avg":
+            ret = ret.mean(dim=0)
+        else:
+            raise ValueError(f"reduce_op ({reduce_op}) is not supported")
+        torch._C._distributed_c10d._register_work(ret, Work())
+        return ret
+
+
+@torch.library.impl(lib, "_low_contention_reduce_scatter", "CUDA")
+def _low_contention_reduce_scatter(
+    tensor: torch.Tensor,
+    reduce_op: str,
+    group_name: str,
+) -> torch.Tensor:
+    """
+    Performs reduce-scatter with symmetric memory in a low-contention fashion.
+
+    This implementation performs a P2P-based all-to-all followed by an offline
+    reduction.
+
+    When `tensor` is already in symmetric memory:
+        - Pull-based all-to-all is used.
+        - No symmetric memory workspace is required.
+
+    When `tensor` is not in symmetric memory:
+        - Push-based all-to-all is used.
+        - Symmetric memory workspace size requirement: the size of `tensor`.
+
+    SM-usage:
+        - SM-based copy of the rank's own chunk for the all-to-all.
+        - Reduction on the all-to-all result.
+
+    TODO(yifu): the SM-based copy can be avoided with a list-based reduction
+    kernel.
+    """
+    symm_mem = _SymmetricMemory.rendezvous(tensor)
+    if symm_mem is not None:
+        return _low_contention_reduce_scatter_with_symm_mem_input(
+            tensor, reduce_op, symm_mem
+        )
+    else:
+        workspace = get_symm_mem_workspace(
+            group_name, tensor.numel() * tensor.element_size()
+        )
+        return _low_contention_reduce_scatter_with_workspace(
+            tensor, reduce_op, workspace
+        )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_symmetric_memory/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_symmetric_memory/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..13e45d7daddc09ea89c014bdc27fbc73c966ead7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_symmetric_memory/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tensor/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tensor/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..40f9727015d7644916167e8fdaee10ac37593f34
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tensor/__init__.py
@@ -0,0 +1,44 @@
+"""
+NOTICE: DTensor has moved to torch.distributed.tensor
+
+This file is a shim to redirect to the new location, and
+we keep the old import path starts with `_tensor` for
+backward compatibility. We will remove this folder once
+we resolve all the BC issues.
+"""
+import sys
+from importlib import import_module
+
+
+submodules = [
+    # TODO: _shards_wrapper/_utils here mainly for checkpoint BC, remove them
+    "_shards_wrapper",
+    "_utils",
+    "experimental",
+    "device_mesh",
+]
+
+# Redirect imports
+for submodule in submodules:
+    full_module_name = f"torch.distributed.tensor.{submodule}"
+    sys.modules[f"torch.distributed._tensor.{submodule}"] = import_module(
+        full_module_name
+    )
+
+from torch.distributed.tensor import (  # noqa: F401
+    DeviceMesh,
+    distribute_module,
+    distribute_tensor,
+    DTensor,
+    empty,
+    full,
+    init_device_mesh,
+    ones,
+    Partial,
+    Placement,
+    rand,
+    randn,
+    Replicate,
+    Shard,
+    zeros,
+)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tensor/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tensor/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5172901b76af98cfac01c9a8660cb2dda037a67b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tensor/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tensor/__pycache__/api.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tensor/__pycache__/api.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6c4ebbd933a7f35bda4fe46744564bb54f3b8e59
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tensor/__pycache__/api.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tensor/__pycache__/placement_types.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tensor/__pycache__/placement_types.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3e61926496aaddd427f2687370aa2cf1b4b3d3d8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tensor/__pycache__/placement_types.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tensor/api.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tensor/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e5742156a86ca511619360038a9028b0efeeaef
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tensor/api.py
@@ -0,0 +1,9 @@
+"""
+NOTE: torch.distributed._tensor has been moved to torch.distributed.tensor.
+The imports here are purely for backward compatibility. We will remove these
+imports in a few releases
+
+TODO: throw warnings when this module imported
+"""
+
+from torch.distributed.tensor._api import *  # noqa: F401, F403
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tensor/placement_types.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tensor/placement_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a4e70dbba455471feef2326cae8ba28b32d0304
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tensor/placement_types.py
@@ -0,0 +1,10 @@
+"""
+NOTE: torch.distributed._tensor has been moved to torch.distributed.tensor.
+The imports here are purely for backward compatibility. We will remove these
+imports in a few releases
+
+TODO: throw warnings when this module imported
+"""
+
+from torch.distributed.tensor._dtensor_spec import *  # noqa: F401, F403
+from torch.distributed.tensor.placement_types import *  # noqa: F401, F403
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd57eedba375177d76d0b0587af3cc2bdfb5f484
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/__init__.py
@@ -0,0 +1,5 @@
+from .fsdp2_mem_tracker import FSDPMemTracker
+from .mem_tracker import MemTracker
+from .memory_tracker import MemoryTracker
+from .mod_tracker import ModTracker
+from .runtime_estimator import RuntimeEstimator
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..47b56c3ede3a6c00708417c3ac103f27d2a8d44e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/__pycache__/fsdp2_mem_tracker.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/__pycache__/fsdp2_mem_tracker.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9971f37ffde63f58e764651592e45818f3ae35e7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/__pycache__/fsdp2_mem_tracker.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/__pycache__/mem_tracker.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/__pycache__/mem_tracker.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f29bdb262fa877e43ba882ea6ca03d6476be27f1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/__pycache__/mem_tracker.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/__pycache__/memory_tracker.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/__pycache__/memory_tracker.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c89ef4b63cb85cd4bc4ce6cc30cf5945c4dd1b2e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/__pycache__/memory_tracker.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/__pycache__/mod_tracker.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/__pycache__/mod_tracker.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aa463840230c09d3f567d73113c308e2e5f95b93
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/__pycache__/mod_tracker.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/__pycache__/runtime_estimator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/__pycache__/runtime_estimator.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7b6b121c69f8ec28745948a2a9c203bcc4b2ccc9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/__pycache__/runtime_estimator.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/fsdp2_mem_tracker.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/fsdp2_mem_tracker.py
new file mode 100644
index 0000000000000000000000000000000000000000..56fae2f038f61c475f8b4fe22ce913093f0b532c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/fsdp2_mem_tracker.py
@@ -0,0 +1,610 @@
+from copy import deepcopy
+from datetime import timedelta
+from functools import partial, wraps
+from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, Type, Union
+
+import torch
+import torch.distributed as dist
+from torch import nn, optim
+from torch._guards import active_fake_mode
+from torch.distributed._composable.fsdp import FSDPModule
+from torch.distributed._composable.fsdp._fsdp_param_group import FSDPParamGroup
+from torch.distributed._tools.mem_tracker import _RefType, _State, MemTracker
+from torch.distributed.distributed_c10d import (
+    _IllegalWork,
+    ProcessGroup,
+    ReduceOp,
+    Work,
+)
+from torch.futures import Future
+from torch.utils._python_dispatch import TorchDispatchMode
+from torch.utils._pytree import tree_map_only
+from torch.utils.weak import WeakIdKeyDictionary, weakref
+
+
+_TOTAL_KEY = "Total"
+
+__all__ = ["FSDPMemTracker"]
+
+
+class _FSDPRefType(_RefType):
+    """
+    Enumerates categories of memory usage in FSDP modules, including parameters, gradients, activations,
+    and optimizer states.
+
+    Attributes:
+        SHARDED_PARAM (str): Memory usage of sharded parameters.
+        UNSHARDED_PARAM (str): Memory usage of unsharded parameters.
+        SHARDED_GRAD (str): Memory usage of sharded gradients corresponding to the sharded parameters.
+        UNSHARDED_GRAD (str): Memory usage of unsharded gradients corresponding to the unsharded parameters.
+        ACT (str): Memory usage of activations and tensors from forward and AC recomputation.
+        TEMP (str): Memory usage of temporary tensors during the backward pass including gradients of activations.
+        ALL_GATHER (str): Memory usage of all_gather output tensor.
+        REDUCE_SCATTER (str): Memory usage of reduce_scatter input tensor.
+        OPT (str): Memory usage of tensors storing optimizer states.
+        INP (str): Memory usage of input tensors.
+    """
+
+    SHARDED_PARAM = "Sharded Param"
+    UNSHARDED_PARAM = "Unsharded Param"
+    BUFFER = "Buffer"
+    SHARDED_GRAD = "Sharded Grad"
+    UNSHARDED_GRAD = "Unsharded Grad"
+    ACT = "Activation"
+    TEMP = "Temp"
+    ALL_GATHER = "All Gather"
+    REDUCE_SCATTER = "Reduce Scatter"
+    OPT = "OptState"
+    INP = "Inputs"
+
+
+class _SavedFSDPMethods(NamedTuple):
+    pre_backward: Callable
+    post_backward: Callable
+
+
+class _SavedCollectives(NamedTuple):
+    all_gather_into_tensor: Callable
+    reduce_scatter_tensor: Callable
+    all_reduce: Callable
+    barrier: Callable
+
+
+class _FSDPModState(_State):
+    """
+    Enumerates the states of FSDP modules during the forward and backward passes.
+    """
+
+    BEF_PRE_FW = "Before Pre-Forward"
+    AFT_PRE_FW = "After Pre-Forward"
+    BEF_POST_FW = "Before Post-Forward"
+    AFT_POST_FW = "After Post-Forward"
+    BEF_PRE_BW = "Before Pre-Backward"
+    AFT_PRE_BW = "After Pre-Backward"
+    BEF_POST_BW = "Before Post-Backward"
+    AFT_POST_BW = "After Post-Backward"
+    PRE_FW_AC = "Pre-Forward AC"
+    POST_FW_AC = "Post-Forward AC"
+    PEAK_FW = "Peak Forward"
+    PEAK_BW = "Peak Backward"
+
+
+class _FSDPModMemStats:
+    """
+    A class to store the memory statistics of an FSDP module.
+
+    Args:
+        mod_fqn (str): The fully qualified name of the FSDP module.
+
+    Attributes:
+        snapshots (Dict[_FSDPModState, Dict[torch.device, Dict[str, int]]]): A dictionary of memory snapshots
+        of the module at different states as defined by ``_FSDPModState``. Each key is a device, and
+        each value is another dictionary with keys as memory reference types defined by ``_FSDPRefType`` and
+        values as the memory consumed in bytes.
+
+    """
+
+    def __init__(self, mod_fqn: str) -> None:
+        self.mod_fqn = mod_fqn
+        self.local_peak: Dict[torch.device, int] = {}
+        self.snapshots: Dict[
+            _FSDPModState, List[Dict[torch.device, Dict[str, int]]]
+        ] = {}
+
+
+class FSDPMemTracker(MemTracker):
+    """
+    A ``TorchDispatchMode`` based context manager that extends ``torch.distributed._tools.mem_tracker.MemTracker`` to track
+    and categorize the peak memory and module-wise memory usage of FSDP modules.
+
+    It tracks the peak memory usage across all the devices of all the FSDP modules in the module tree and categorizes
+    the tensor memory usage as defined by ``_FSDPRefType``. Further, it captures memory `snapshots` at different stages of
+    the module execution defined by ``_FSDPModState``.
+
+    Attributes:
+        memory_tracking: A weakref key dictionary to store the memory statistics of each module. Each key is a reference
+        to a module, and each value is a ``_FSDPModMemStats`` object that stores the memory statistics of the module.
+
+    Args:
+        mod (torch.nn.Module): The root FSDP module to be tracked.
+        optm (torch.optim.Optimizer, optional): The optimizer to be tracked.
+
+    Note: Please refer to ``torch.distributed._tools.mem_tracker.MemTracker`` to learn about the limitations.
+
+    Example usage
+
+    .. code-block:: python
+
+        module = ...
+        optimizer = ...
+        inp = ...
+        fmt = FSDPMemTracker(module, optimizer)
+        fmt.track_inputs((inp,))
+        with fmt:
+            optimizer.zero_grad()
+            loss = module(inp)
+            print("After Forward:")
+            fmt.display_snapshot("current")
+            loss.backward()
+            optimizer.step()
+        fmt.display_snapshot("peak")
+        fmt.display_modulewise_snapshots(depth = 3, units = "MB")
+
+    """
+
+    def __init__(
+        self,
+        mod: torch.nn.Module,
+        optm: Optional[torch.optim.Optimizer] = None,
+    ) -> None:
+        super().__init__()
+        assert isinstance(mod, FSDPModule), "FSDPMemTracker only supports FSDP modules"
+        self._root_mod = mod
+        self._optm = optm
+        self._in_fake_mode: bool = False
+        self._fsdp_mod_to_saved_methods: WeakIdKeyDictionary = WeakIdKeyDictionary()
+        self._saved_collectives: _SavedCollectives
+        self._ref_class: Type[_RefType] = _FSDPRefType
+
+    def _instrument_fsdp_sharded_params_grads(
+        self, fsdp_param_group: FSDPParamGroup
+    ) -> None:
+        # Track sharded params and grads after initilization
+        for fsdp_param in fsdp_param_group.fsdp_params:
+            self._update_and_maybe_create_winfos(
+                fsdp_param.sharded_param,
+                _FSDPRefType.SHARDED_PARAM,
+            )
+            sharded_grad = fsdp_param.sharded_param.grad
+            if sharded_grad is not None:
+                self._update_and_maybe_create_winfos(
+                    sharded_grad,
+                    _FSDPRefType.SHARDED_GRAD,
+                )
+
+    def _fsdp_state_pre_forward(
+        self,
+        fsdp_mod: FSDPModule,
+        orig_fsdp_state_pre_fw: Callable,
+    ) -> Callable:
+        # We capture memory snapshots before and after ``FSDPState._pre_forward`` to attribute the `unsharded` params
+        # and `all_gather` buffers.  There are three cases:
+        # Case 1: If the module is not in the ``memory_tracking`` dictionary, create a new ``_FSDPModMemStats``
+        #         instance for the module and add it to the ``memory_tracking`` dictionary.
+        # Case 2: If the module is already in the ``memory_tracking`` dictionary and we are in backward, this means
+        #         we are in the AC region. We check if this is the top most module in the AC region. If it is,
+        #         we store a weak reference and set the flag ``_in_ac`` to True.
+        # Case 3: If the module is already in the ``memory_tracking`` dictionary and we are in forward, this means
+        #         this module is called for the second time. If it is a root module, that means we are in the next
+        #         iteration and we error out. If it is not a root module, that means it's a submodule that is being
+        #         used multiple times in the same iteration, which we allow and track.
+        # For Case 1 and 3, we also initialiaze the ``local_peak`` and ``PEAK_FW`` snapshot for the module.
+        # For Case 2 we only capture 1 snapshot after ``FSDPState._pre_forward`` runs because it is a no-op.
+        @wraps(orig_fsdp_state_pre_fw)
+        def inner(*args: Any, **kwargs: Any) -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
+            mod_fqn = self._mod_tracker.get_known_fqn(fsdp_mod)
+            assert mod_fqn is not None
+            if fsdp_mod not in self.memory_tracking:
+                mod_stat = _FSDPModMemStats(mod_fqn)
+                self.memory_tracking[fsdp_mod] = mod_stat
+                snapshot = self.get_tracker_snapshot()
+                mod_stat.local_peak = {
+                    dev: dev_snap[_TOTAL_KEY] for dev, dev_snap in snapshot.items()
+                }
+                mod_stat.snapshots.setdefault(_FSDPModState.PEAK_FW, []).append(
+                    snapshot
+                )
+                mod_stat.snapshots.setdefault(_FSDPModState.BEF_PRE_FW, []).append(
+                    deepcopy(snapshot)
+                )
+            elif not self._mod_tracker.is_bw:
+                parents = self._mod_tracker.parents - {mod_fqn}
+                if len(parents) == 1 and "Global" in parents:
+                    raise NotImplementedError(
+                        "FSDPMemTracker does not support memory tracking for multiple iterative calls."
+                        " Either use ``reset_mod_stats`` to clear module memory stats for the previous iteration"
+                        " or file a github issue if you need this feature."
+                    )
+
+            args, kwargs = orig_fsdp_state_pre_fw(*args, **kwargs)
+
+            fsdp_state = fsdp_mod._get_fsdp_state()
+            if fsdp_param_group := fsdp_state._fsdp_param_group:
+                for fsdp_param in fsdp_param_group.fsdp_params:
+                    self._update_and_maybe_create_winfos(
+                        fsdp_param.unsharded_param,
+                        _FSDPRefType.UNSHARDED_PARAM,
+                    )
+            mod_stat = self.memory_tracking[fsdp_mod]
+            if self._mod_tracker.is_bw:
+                state = _FSDPModState.PRE_FW_AC
+                if self._ac_mod is None:
+                    self._ac_mod = weakref.ref(fsdp_mod)
+                    self._in_ac = True
+            else:
+                state = _FSDPModState.AFT_PRE_FW
+            mod_stat.snapshots.setdefault(state, []).append(self.get_tracker_snapshot())
+            return args, kwargs
+
+        return inner
+
+    def _fsdp_state_post_forward(
+        self,
+        fsdp_mod: FSDPModule,
+        orig_fsdp_state_post_fw: Callable,
+    ) -> Callable:
+        # We capture memory snapshots before and after ``FSDPState._post_forward`` to capture the resharded state
+        # if ``reshard_after_forward`` is not ``False``. There are two cases:
+        # Case 1: This is called in backward, which means we are in the AC region. If this is the top most module
+        #         in the AC region, we set the flag ``_in_ac`` to False.
+        # Case 2: This is called in forward.
+        @wraps(orig_fsdp_state_post_fw)
+        def inner(*args: Any, **kwargs: Any) -> Any:
+            mod_stat = self.memory_tracking[fsdp_mod]
+            if self._mod_tracker.is_bw:
+                state = _FSDPModState.POST_FW_AC
+                if self._ac_mod is not None and self._ac_mod() is fsdp_mod:
+                    self._ac_mod = None
+                    self._in_ac = False
+            else:
+                state = _FSDPModState.BEF_POST_FW
+            mod_stat.snapshots.setdefault(state, []).append(self.get_tracker_snapshot())
+
+            output = orig_fsdp_state_post_fw(*args, **kwargs)
+
+            if not self._mod_tracker.is_bw:
+                mod_stat.snapshots.setdefault(_FSDPModState.AFT_POST_FW, []).append(
+                    self.get_tracker_snapshot()
+                )
+            return output
+
+        return inner
+
+    def _fsdp_param_group_pre_backward(
+        self,
+        fsdp_mod: FSDPModule,
+        orig_fsdp_param_group_pre_backward: Callable,
+    ) -> Callable:
+        # We capture memory snapshots before and after ``FSDPParamGroup.pre_backward`` to capture the pre-fetching
+        # and unsharding of params. We also initialize ``local_peak`` and ``PEAK_BW`` snapshot for the module.
+        @wraps(orig_fsdp_param_group_pre_backward)
+        def inner(*args: Any, **kwargs: Any) -> None:
+            mod_stat = self.memory_tracking[fsdp_mod]
+            snapshot = self.get_tracker_snapshot()
+            mod_stat.local_peak = {
+                dev: dev_snap[_TOTAL_KEY] for dev, dev_snap in snapshot.items()
+            }
+            mod_stat.snapshots.setdefault(_FSDPModState.PEAK_BW, []).append(snapshot)
+            mod_stat.snapshots.setdefault(_FSDPModState.BEF_PRE_BW, []).append(
+                deepcopy(snapshot)
+            )
+            orig_fsdp_param_group_pre_backward(*args, **kwargs)
+
+            mod_stat.snapshots.setdefault(_FSDPModState.AFT_PRE_BW, []).append(
+                self.get_tracker_snapshot()
+            )
+
+        return inner
+
+    def _fsdp_param_group_post_backward(
+        self,
+        fsdp_mod: FSDPModule,
+        orig_fsdp_param_group_post_backward: Callable,
+    ) -> Callable:
+        # We capture the memory snapshots before and after ``FSDPParamGroup.post_backward`` to track and attribute
+        # the `unsharded` grads before the post backward and then `sharded` grads and `reduce_scatter`  buffers
+        # after the post backward.
+        @wraps(orig_fsdp_param_group_post_backward)
+        def inner(*args: Any, **kwargs: Any) -> None:
+            fsdp_state = fsdp_mod._get_fsdp_state()
+            if fsdp_param_group := fsdp_state._fsdp_param_group:
+                for fsdp_param in fsdp_param_group.fsdp_params:
+                    unsharded_grad = fsdp_param._unsharded_param.grad
+                    if unsharded_grad is not None:
+                        self._update_and_maybe_create_winfos(
+                            unsharded_grad,
+                            _FSDPRefType.UNSHARDED_GRAD,
+                            update_existing=True,
+                        )
+
+            mod_stat = self.memory_tracking[fsdp_mod]
+            mod_stat.snapshots.setdefault(_FSDPModState.BEF_POST_BW, []).append(
+                self.get_tracker_snapshot()
+            )
+
+            orig_fsdp_param_group_post_backward(*args, **kwargs)
+
+            if fsdp_param_group := fsdp_state._fsdp_param_group:
+                for fsdp_param in fsdp_param_group.fsdp_params:
+                    sharded_grad = fsdp_param.sharded_param.grad
+                    if sharded_grad is not None:
+                        self._update_and_maybe_create_winfos(
+                            sharded_grad,
+                            _FSDPRefType.SHARDED_GRAD,
+                        )
+
+            mod_stat.snapshots.setdefault(_FSDPModState.AFT_POST_BW, []).append(
+                self.get_tracker_snapshot()
+            )
+
+        return inner
+
+    def _instrument_fsdp_module(self) -> None:
+        # We uninstall the existing `FSDPState._pre_forward` and `FSDPState._post_forward` hooks and install
+        # our own hooks that wrap them. We choose this over monkey-patching `FSDPParamGroup.pre_forward` and
+        # `FSDPParamGroup.post_forward` because during AC these won't be called.
+        # TODO(@sanketpurandare): This will need to be modified after this PR (https://github.com/pytorch/pytorch/pull/127786)
+        # lands. For backward we monkey-patch the `FSDPParamGroup.pre_backward` and `FSDPParamGroup.post_backward`.
+        for module in self._root_mod.modules():
+            if isinstance(module, FSDPModule):
+                fsdp_state = module._get_fsdp_state()
+                if fsdp_param_group := fsdp_state._fsdp_param_group:
+                    self._instrument_fsdp_sharded_params_grads(fsdp_param_group)
+                    fsdp_state._pre_forward_hook_handle.remove()
+                    fsdp_state._post_forward_hook_handle.remove()
+                    fsdp_state._pre_forward_hook_handle = (
+                        module.register_forward_pre_hook(
+                            self._fsdp_state_pre_forward(
+                                module, fsdp_state._pre_forward
+                            ),
+                            prepend=True,
+                            with_kwargs=True,
+                        )
+                    )
+                    fsdp_state._post_forward_hook_handle = module.register_forward_hook(
+                        self._fsdp_state_post_forward(module, fsdp_state._post_forward),
+                        prepend=False,
+                        always_call=True,
+                    )
+                    self._fsdp_mod_to_saved_methods[module] = _SavedFSDPMethods(
+                        fsdp_param_group.pre_backward,
+                        fsdp_param_group.post_backward,
+                    )
+                    fsdp_param_group.pre_backward = self._fsdp_param_group_pre_backward(  # type: ignore[assignment]
+                        module, fsdp_param_group.pre_backward
+                    )
+                    fsdp_param_group.post_backward = (  # type: ignore[assignment]
+                        self._fsdp_param_group_post_backward(
+                            module, fsdp_param_group.post_backward
+                        )
+                    )
+
+        for buffer in self._root_mod.buffers():
+            self._update_and_maybe_create_winfos(
+                buffer,
+                _FSDPRefType.BUFFER,
+            )
+
+    def _instrument_optimizer(self) -> None:
+        # Register a hook on the optimizer step to track the optimizer states.
+        # The pre-hook is to set the flag ``_in_opt`` to True. The post-hook unsets the flag,
+        # and also tracks any optimizer states that are created during the optimizer step.
+        if self._optm is not None:
+            self._track_optimizer_states(_FSDPRefType.OPT, self._optm)
+
+            def _opt_step_pre_hook(
+                optimizer: optim.Optimizer, args: Any, kwargs: Any
+            ) -> None:
+                self._in_opt = True
+
+            def _opt_step_post_hook(
+                optimizer: optim.Optimizer, args: Any, kwargs: Any
+            ) -> None:
+                self._track_optimizer_states(_FSDPRefType.OPT, optimizer)
+                self._in_opt = False
+
+            self._optimizer_hook_handles = (
+                self._optm.register_step_pre_hook(_opt_step_pre_hook),
+                self._optm.register_step_post_hook(_opt_step_post_hook),
+            )
+
+    def _register_module_and_optimizer_hooks(self) -> None:
+        self._instrument_fsdp_module()
+        self._instrument_optimizer()
+
+    def _deregister_module_and_optimizer_hooks(self) -> None:
+        for (
+            fsdp_mod,
+            saved_methods,
+        ) in self._fsdp_mod_to_saved_methods.items():
+            fsdp_state = fsdp_mod._get_fsdp_state()
+            fsdp_state._pre_forward_hook_handle.remove()
+            fsdp_state._post_forward_hook_handle.remove()
+            fsdp_state._pre_forward_hook_handle = fsdp_mod.register_forward_pre_hook(
+                fsdp_state._pre_forward, prepend=True, with_kwargs=True
+            )
+            fsdp_state._post_forward_hook_handle = fsdp_mod.register_forward_hook(
+                fsdp_state._post_forward, prepend=False
+            )
+            if fsdp_param_group := fsdp_state._fsdp_param_group:
+                fsdp_param_group.pre_backward = saved_methods.pre_backward
+                fsdp_param_group.post_backward = saved_methods.post_backward
+        self._fsdp_mod_to_saved_methods.clear()
+
+        if self._optimizer_hook_handles is not None:
+            for handle in self._optimizer_hook_handles:
+                handle.remove()
+            self._optimizer_hook_handles = None
+
+    def _instrument_and_maybe_bypass_collectives(self) -> None:
+        # Monkey-patching collectives is required because they do not work with `FakeTensorMode`
+        # It's also easier to track `all_gather` and `reduce_scatter` buffers faithfully.
+        self._saved_collectives = _SavedCollectives(
+            dist.all_gather_into_tensor,
+            dist.reduce_scatter_tensor,
+            dist.all_reduce,
+            dist.barrier,
+        )
+
+        class FakeWork(Work):
+            def __init__(self) -> None:
+                super().__init__()
+
+            def get_future(self) -> Future:
+                future: Future = Future()
+                future.set_result(None)
+                return future
+
+            def wait(self, timeout: Optional[timedelta] = None) -> bool:
+                return True
+
+        @wraps(dist.all_gather_into_tensor)
+        def all_gather_into_tensor(
+            output_tensor: torch.Tensor,
+            input_tensor: torch.Tensor,
+            group: Union[ProcessGroup, None] = None,
+            async_op: bool = False,
+        ) -> Union[Work, _IllegalWork, None]:
+            self._update_and_maybe_create_winfos(
+                output_tensor,
+                _FSDPRefType.ALL_GATHER,
+                update_existing=True,
+            )
+
+            if self._in_fake_mode:
+                if async_op:
+                    return FakeWork()
+                return None
+            else:
+                return self._saved_collectives.all_gather_into_tensor(
+                    output_tensor, input_tensor, group, async_op
+                )
+
+        @wraps(dist.reduce_scatter_tensor)
+        def reduce_scatter_tensor(
+            output: torch.Tensor,
+            input: torch.Tensor,
+            op: ReduceOp.RedOpType = dist.ReduceOp.SUM,
+            group: Union[ProcessGroup, None] = None,
+            async_op: bool = False,
+        ) -> Union[Work, _IllegalWork, None]:
+            self._update_and_maybe_create_winfos(
+                input,
+                _FSDPRefType.REDUCE_SCATTER,
+                update_existing=True,
+            )
+
+            if self._in_fake_mode:
+                if async_op:
+                    return FakeWork()
+                return None
+            else:
+                return self._saved_collectives.reduce_scatter_tensor(
+                    output, input, op, group, async_op
+                )
+
+        @wraps(dist.all_reduce)
+        def all_reduce(
+            tensor: torch.Tensor,
+            op: ReduceOp.RedOpType = dist.ReduceOp.SUM,
+            group: Union[ProcessGroup, None] = None,
+            async_op: bool = False,
+        ) -> Union[Work, _IllegalWork, None]:
+            if self._in_fake_mode:
+                if async_op:
+                    return FakeWork()
+                return None
+            else:
+                return self._saved_collectives.all_reduce(tensor, op, group, async_op)
+
+        @wraps(dist.barrier)
+        def barrier(
+            group: Union[ProcessGroup, None] = dist.GroupMember.WORLD,
+            async_op: bool = False,
+            device_ids: Union[List[int], None] = None,
+        ) -> Union[Work, None]:
+            if self._in_fake_mode:
+                return None
+            else:
+                return self._saved_collectives.barrier(group, async_op, device_ids)
+
+        dist.all_gather_into_tensor = all_gather_into_tensor
+        dist.reduce_scatter_tensor = reduce_scatter_tensor
+        dist.all_reduce = all_reduce
+        dist.barrier = barrier
+
+    def _restore_collectives(self) -> None:
+        dist.all_gather_into_tensor = self._saved_collectives.all_gather_into_tensor
+        dist.reduce_scatter_tensor = self._saved_collectives.reduce_scatter_tensor
+        dist.all_reduce = self._saved_collectives.all_reduce
+        dist.barrier = self._saved_collectives.barrier
+        del self._saved_collectives
+
+    def track_inputs(self, inputs: Tuple[Any, ...]) -> None:
+        """
+        This is used to track the input tensors to the model and annotate them as ``Inputs``.
+        Args:
+            inputs (Tuple[Any]): A tuple containing the input data. This can include tensors
+                        as well as other data types. Only tensors will be tracked.
+        """
+
+        def _track_inputs(t: torch.Tensor) -> None:
+            self._update_and_maybe_create_winfos(
+                t,
+                _FSDPRefType.INP,
+            )
+
+        tree_map_only(torch.Tensor, _track_inputs, inputs)
+
+    def track_external(
+        self, *external: Union[nn.Module, optim.Optimizer, torch.Tensor]
+    ) -> None:
+        """This is no-op for ``FSDPMemTracker``"""
+
+    def __enter__(self) -> "FSDPMemTracker":
+        self._in_fake_mode = True if active_fake_mode() else False
+        self._register_module_and_optimizer_hooks()
+        self._instrument_and_maybe_bypass_collectives()
+        self._track_resize()
+        self._peak_mem_snap = self.get_tracker_snapshot()
+        self._peak_mem = {
+            dev: dev_snap[_TOTAL_KEY] for dev, dev_snap in self._peak_mem_snap.items()
+        }
+        self._mod_tracker.__enter__()
+        TorchDispatchMode.__enter__(self)
+        return self
+
+    def __exit__(self, *args: Any) -> None:
+        self._deregister_module_and_optimizer_hooks()
+        self._restore_collectives()
+        self._restore_resize()
+        TorchDispatchMode.__exit__(self, *args)
+        self._mod_tracker.__exit__(*args)
+
+    def __torch_dispatch__(self, func, types, args=..., kwargs=None):  # type: ignore[no-untyped-def]
+        res = func(*args, **kwargs or {})
+        # If we are tracking an optimizer state, we use the optimizer reference type.
+        # If we are in backward region and not in AC region, we use the backward reference type.
+        # Else we use the forward reference type.
+        if self._in_opt:
+            reftype = _FSDPRefType.OPT
+        elif self._mod_tracker.is_bw and not self._in_ac:
+            reftype = _FSDPRefType.TEMP
+        else:
+            reftype = _FSDPRefType.ACT
+        tree_map_only(torch.Tensor, partial(self._track, reftype), res)
+        peak_state = (
+            _FSDPModState.PEAK_BW if self._mod_tracker.is_bw else _FSDPModState.PEAK_FW
+        )
+        self._update_peak_stats(peak_state)
+        return res
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/mem_tracker.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/mem_tracker.py
new file mode 100644
index 0000000000000000000000000000000000000000..86fc561241e8ee54927b137bfe5c452cac52f30d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/mem_tracker.py
@@ -0,0 +1,943 @@
+import math
+import os
+import re
+import warnings
+from copy import deepcopy
+from enum import auto, Enum
+from functools import partial, wraps
+from typing import (
+    Any,
+    Callable,
+    Dict,
+    List,
+    Optional,
+    Set,
+    Tuple,
+    Type,
+    TYPE_CHECKING,
+    Union,
+)
+from typing_extensions import Self
+
+import torch
+from torch import nn, optim
+from torch.distributed._tools.mod_tracker import ModTracker
+from torch.optim.optimizer import (
+    register_optimizer_step_post_hook,
+    register_optimizer_step_pre_hook,
+)
+from torch.utils._python_dispatch import (
+    is_traceable_wrapper_subclass,
+    TorchDispatchMode,
+)
+from torch.utils._pytree import tree_flatten, tree_map_only
+from torch.utils.weak import WeakIdKeyDictionary, weakref
+
+
+if TYPE_CHECKING:
+    from torch.utils.hooks import RemovableHandle
+
+# This value is hard-coded here:
+# https://github.com/pytorch/pytorch/blob/5fba5d83f0703ff8077ab65448a998e9ad6598fd/c10/cuda/CUDACachingAllocator.cpp#L117
+_PYTORCH_MIN_ALLOCATE = (
+    2**9 if int(os.environ.get("PYTORCH_NO_CUDA_MEMORY_CACHING", 0)) == 0 else 1
+)
+_TOTAL_KEY = "Total"
+
+__all__ = ["MemTracker"]
+
+
+class _RefType(str, Enum):
+    """Base Class for defining memory reference types, categorizing tensors based on their usage within a model."""
+
+
+class _State(str, Enum):
+    """Base Class for defining module state to capture snapshots ."""
+
+
+class _MemRefType(_RefType):
+    """
+    An enum to define memory reference types, categorizing tensors based on their usage within a model.
+
+        - PARAM: Tensors registered as nn.Parameter within modules.
+        - BUFFER: Tensors registered as nn.Buffer within modules.
+        - GRAD: Gradients associated with parameters.
+        - ACT: Tensors produced during the forward pass and recomputation in activation checkpointing.
+        - TMP: Temporary memory used during the backward pass, including gradients of activations.
+        - OPT: Tensors holding optimizer states.
+        - OTH: Tensors registered via `track_external` that do not fit the above categories.
+    """
+
+    PARAM = "Parameter"
+    BUFFER = "Buffer"
+    GRAD = "Gradient"
+    ACT = "Activation"
+    TEMP = "Temp"
+    OPT = "Optstate"
+    OTH = "Other"
+
+
+class _ModState(_State):
+    """
+    An enum to define the state of a module.
+
+        - PRE_FW: The module is about to run the forward pass.
+        - POST_FW: The module has finished running the forward pass.
+        - PEAK_FW: The module has reached the peak memory usage during the forward pass.
+        - PRE_BW: The module is about to run the backward pass.
+        - PRE_FW_AC: The module is about to run the forward pass with activation checkpointing.
+        - POST_FW_AC: The module has finished running the forward pass with activation checkpointing.
+        - POST_BW: The module has finished running the backward pass.
+        - PEAK_BW: The module has reached the peak memory usage during the backward pass.
+    """
+
+    PRE_FW = "Pre-Forward"
+    POST_FW = "Post-Forward"
+    PEAK_FW = "Peak-Forward"
+    PRE_BW = "Pre-Backward"
+    PRE_FW_AC = "Pre-Forward-AC"
+    POST_FW_AC = "Post-Forward-AC"
+    POST_BW = "Post-Backward"
+    PEAK_BW = "Peak-Backward"
+
+
+class _ModMemStats:
+    """
+    A class to store the memory statistics of a module.
+
+    Args:
+        mod_fqn (str): The fully qualified name of the module.
+    Attributes:
+        mod_fqn (str): The fully qualified name of the module.
+        parameter_mem (int): The memory usage of the parameters of the module.
+        buffer_mem (int): The memory usage of the buffers of the module.
+        input_mem (int): The memory usage of the inputs to the module.
+        output_mem (int): The memory usage of the outputs from the module.
+        snapshots (Dict[_ModState, Dict[torch.device, Dict[str, int]]]): A dictionary of memory snapshots
+        of the module at different states defined by ``_ModState``.
+    Note:
+        The memory snapshot is stored as a dictionary - Dict[torch.device, Dict[str, int]], where each key is a device,
+         and each value is another dictionary with keys as memory reference types defined by `_MemRefType` and
+         values as the memory consumed in bytes.
+    """
+
+    def __init__(self, mod_fqn: str):
+        self.mod_fqn = mod_fqn
+        self.parameter_mem: int
+        self.buffer_mem: int
+        self.input_mem: int
+        self.output_mem: int
+        self.local_peak: Dict[torch.device, int] = {}
+        self.snapshots: Dict[_ModState, List[Dict[torch.device, Dict[str, int]]]] = {}
+
+
+class _WeakRefInfo:
+    """
+    Manages memory statistics and device attributes for tensor storages.
+    """
+
+    def __init__(
+        self, size: int, element_size: int, device: torch.device, reftype: _RefType
+    ) -> None:
+        """
+        Initializes the ``_WeakRefInfo`` object with tensor storage properties.
+
+        Args:
+            size (int): The number of elements in the tensor storage.
+            element_size (int): The size of each element in the tensor storage.
+            device (torch.device): The device on which the tensor is allocated.
+            reftype (_RefType): The reference type of the tensor.
+        """
+        self.size = size
+        self.element_size = element_size
+        self.reftype = reftype
+        self.device = device
+        self.mem_consumed = self._calculate_mem_consumed()
+
+    def _calculate_mem_consumed(self) -> int:
+        """
+        Calculates the memory consumed by the tensor storage, considering device-specific allocation rules.
+
+        Returns:
+            int: The memory consumed in bytes.
+        """
+        mem = self.size * self.element_size
+        if self.device.type == "cuda":
+            return math.ceil((mem) / _PYTORCH_MIN_ALLOCATE) * _PYTORCH_MIN_ALLOCATE
+        return mem
+
+    def update_mem_consumed(self, st: torch.UntypedStorage) -> int:
+        """
+        Updates and returns the memory consumed if the storage size has changed.
+
+        Args:
+            st (torch.UntypedStorage): The tensor storage to check for size updates.
+
+        Returns:
+            int: The updated memory consumed in bytes.
+        """
+        if st.size() != self.size:
+            self.size = st.size()
+            self.mem_consumed = self._calculate_mem_consumed()
+        return self.mem_consumed
+
+    @staticmethod
+    def get_untyped_storages(t: torch.Tensor) -> Set[torch.UntypedStorage]:
+        """
+        Recursively extracts untyped storages from a tensor or its subclasses.
+
+        Args:
+            t (torch.Tensor): The tensor to extract storages from.
+
+        Returns:
+            Set[torch.UntypedStorage]: A set of untyped storages.
+        """
+        unflattened_tensors = [t]
+        flattened_tensor_storages = set()
+        while len(unflattened_tensors) > 0:
+            obj = unflattened_tensors.pop()
+            if is_traceable_wrapper_subclass(obj):
+                attrs, _ = obj.__tensor_flatten__()  # type: ignore[attr-defined]
+                unflattened_tensors.extend([getattr(obj, attr) for attr in attrs])
+            else:
+                if not hasattr(obj, "untyped_storage"):
+                    warnings.warn(
+                        f"Expected a tensor or a traceable wrapper-subclass of tensor, but got {type(obj)}",
+                        category=UserWarning,
+                        stacklevel=2,
+                    )
+                else:
+                    flattened_tensor_storages.add(obj.untyped_storage())
+        return flattened_tensor_storages
+
+    @classmethod
+    def create_winfo(
+        cls,
+        st: torch.UntypedStorage,
+        device: torch.device,
+        reftype: _RefType,
+        callback: Optional[Callable[[Self, weakref.ref], Any]] = None,
+    ) -> Tuple[Self, weakref.ref]:
+        """
+        Creates a new ``_WeakRefInfo`` instance and a weak reference to a ``torch.UntypedStorage`` object,
+        optionally attaching a callback to the weak reference.
+
+        Args:
+            st (torch.UntypedStorage): The storage object for which to create the weak reference info.
+            device (torch.device): The device associated with the storage object.
+            reftype (_RefType): The type of reference, used to categorize the storage.
+            callback (Optional[Callable[[Self, weakref.ref]]]): A callback function that is called when
+                the storage object is about to be finalized (garbage collected). The callback function
+                should accept two arguments: the ``_WeakRefInfo`` instance and the weak reference to the storage.
+        Returns:
+            Tuple[Self, weakref.ref]: A tuple containing the newly created ``_WeakRefInfo`` instance and the
+            weak reference to the storage object. The weak reference may have an attached callback if provided.
+        """
+
+        winfo = cls(st.size(), st.element_size(), device, reftype)
+        w_st = weakref.ref(st, partial(callback, winfo) if callback else None)
+        return winfo, w_st
+
+
+def _get_mem_divisor(units: str) -> int:
+    unit_dict = {"B": 1, "KiB": 2**10, "MiB": 2**20, "GiB": 2**30}
+    if units in unit_dict:
+        return unit_dict[units]
+    else:
+        raise ValueError(
+            f"Unsupported unit: {units}. Supported units are: {', '.join(unit_dict.keys())}"
+        )
+
+
+def _rounding_fn(value: int, divisor: int, precision: int) -> Union[float, int]:
+    return value if divisor == 1 else round(value / divisor, precision)
+
+
+def _print_snapshot(snapshot: Dict[torch.device, Dict[str, int]], units: str) -> None:
+    if len(snapshot) == 0:
+        print("No memory tracked.")
+        return
+    divisor = _get_mem_divisor(units)
+    for dev, dev_snap in snapshot.items():
+        if _rounding_fn(dev_snap[_TOTAL_KEY], divisor, 2) <= 0:
+            continue
+        print(
+            f"Device: {dev}",
+            *(
+                f"\t{k}: {_rounding_fn(v, divisor, 2)} {units}"
+                for k, v in dev_snap.items()
+            ),
+            sep="\n",
+        )
+
+
+def _print_snapshot_tabular(
+    snapshot: Dict[torch.device, Dict[str, int]], units: str
+) -> None:
+    if len(snapshot) == 0:
+        print("No memory tracked.")
+        return
+    try:
+        from tabulate import tabulate
+    except ImportError as err:
+        raise ImportError(
+            "Please install tabulate to use the tabulate option."
+        ) from err
+    divisor = _get_mem_divisor(units)
+    table_data = []
+    key_list = list(next(iter(snapshot.values())).keys())
+    headers = ["Device"] + [f"{key}" for key in key_list]
+
+    for dev, dev_snap in snapshot.items():
+        if _rounding_fn(dev_snap[_TOTAL_KEY], divisor, 2) <= 0:
+            continue
+        row = [str(dev)]
+        row.extend(f"{_rounding_fn(v, divisor, 2)} {units}" for v in dev_snap.values())
+        table_data.append(row)
+    print(tabulate(table_data, headers=headers, tablefmt="rst"))
+
+
+def _print_state_snapshots(
+    snapshots: Dict[_State, List[Dict[torch.device, Dict[str, int]]]], units: str
+) -> None:
+    for state, snapshot_list in snapshots.items():
+        print(f"{state}")
+        for i, snapshot in enumerate(snapshot_list):
+            print(f"# {i + 1}:")
+            _print_snapshot(snapshot, units)
+    print()
+
+
+def _print_state_snapshots_tabular(
+    snapshots: Dict[_State, List[Dict[torch.device, Dict[str, int]]]], units: str
+) -> None:
+    try:
+        from tabulate import tabulate
+    except ImportError as err:
+        raise ImportError(
+            "Please install tabulate to use the tabulate option."
+        ) from err
+
+    table_data = []
+    last_state_call = None
+    divisor = _get_mem_divisor(units)
+    for state, snapshot_list in snapshots.items():
+        for i, snapshot in enumerate(snapshot_list):
+            state_call = f"{state} # {i + 1}"
+            for dev, dev_snap in snapshot.items():
+                if _rounding_fn(dev_snap[_TOTAL_KEY], divisor, 2) <= 0:
+                    continue
+                row = {
+                    "State & Call": (
+                        state_call if state_call != last_state_call else ""
+                    ),
+                    "Device": str(dev),
+                }
+                last_state_call = state_call
+                for k, v in dev_snap.items():
+                    row[f"{k}"] = f"{_rounding_fn(v, divisor, 2)} {units}"
+                table_data.append(row)
+    print(tabulate(table_data, headers="keys", tablefmt="rst"))
+
+
+class _UpdateType(Enum):
+    # These are used for tracking updates to the continuouly maintained memory snapshot.
+    # ADD - When a new tensor storage is tracked
+    # DEL - When a tensor storage is about to be finalized (garbage collected).
+    # REF - When a tensor reference is updated, for instance, the gradients are marked as
+    #       generic backward reference types until the grad_hook categorizes them as gradients.
+    # SIZE - When a tensor's storage is resized.
+    ADD = auto()
+    DEL = auto()
+    REF = auto()
+    SIZE = auto()
+
+
+class MemTracker(TorchDispatchMode):
+    """
+    A TorchDispatchMode to track, categorize and attribute the tensor memory created or accessed within its context.
+
+    It categorizes the tracked tensors as parameters, buffers, activations, gradients, temporary memory and optimizer states
+    as defined by ``_MemRefType`` within its context. It captures memory `snapshots` for the modules, called within its context,
+    at various states defined by ``_ModState``.
+
+    Attributes:
+        memory_tracking: A weakref key dictionary to store the memory statistics of each module. Each key
+        is a reference to a module, and each value is a ``_ModMemStats`` object that stores the memory
+        statistics of the module.
+
+    Note:
+        The MemTracker should be used as a context manager. The modules, optimizers, and any other tensors created within
+        the context of MemTracker will be tracked by default. Any tensors or stateful objects such as modules, optimizers etc.
+        that need to be tracked but are created outside the MemTracker should be registered using the `track_external` method.
+        The `track_external` method should be called before the MemTracker is used. Any tensors created outside the ``MemTracker``
+        and not supplied to the `track_external` method will not be tracked by the ``MemTracker``.
+
+    Example usage:
+
+        .. code-block:: python
+
+            module = ...
+            optimizer = ...
+            inp = ...
+            mem_tracker = MemTracker()
+            mem_tracker.track_external(module, optimizer, inp)
+            with mem_tracker as mt:
+                loss = module(inp)
+                print("After Forward:")
+                mt.display_snapshot("current")
+                loss.backward()
+                optimizer.step()
+                optimizer.zero_grad()
+            mt.display_snapshot("peak")
+            mt.display_modulewise_snapshots(depth = 3, units = "MiB")
+
+    Known Limitations:
+        - The ``MemTracker`` does not track memory for tensors that bypass the ``TorchDispatchMode`` ex. under ``no_dispatch``.
+        - Resizing tensor storages directly by using non-Tensor methods other than using ``torch.Untyped_Storage.resize_``
+          is not tracked. File a Github issue if you have use-cases for this.
+        - If the tensors are not traceable or wrappable subclasses of ``torch.Tensor``, then the tracker does not know how to
+            track their storages. File a Github issue if you have use-cases for this.
+        - During AC in the backward pass there might be misattribution between activation and temp memory, but the peak memory
+          will be tracked accurately. This will be fixed in the next update by hooking intricately with ``torch.uitls.checkpoint``.
+    """
+
+    def __init__(self) -> None:
+        self.memory_tracking = WeakIdKeyDictionary()
+        self._curr_mem_snap: Dict[torch.device, Dict[str, int]] = {}
+        self._peak_mem: Dict[torch.device, int] = {}
+        self._peak_mem_snap: Dict[torch.device, Dict[str, int]] = {}
+        self._param_to_grad_hook_handles = WeakIdKeyDictionary()
+        self._optimizer_hook_handles: Optional[
+            Tuple[RemovableHandle, RemovableHandle]
+        ] = None
+        # Dictionary to store the ``_WeakRefInfo`` instances corresponding to each tensor's storage.
+        self._WINFO = WeakIdKeyDictionary()
+        self._mod_tracker = ModTracker()
+        # This is a general memory tracker which can be used with any ``_RefType`` subclass
+        self._ref_class: Type[_RefType] = _MemRefType
+        # Flags to track if we are in the AC region or optimizer step region
+        self._in_opt: bool = False
+        self._in_ac: bool = False
+        # Weak references to the topmost AC module currently active
+        self._ac_mod: Optional[weakref.ref] = None
+        self._orig_resize = torch.UntypedStorage.resize_
+
+    def _update_snap(
+        self,
+        u_type: _UpdateType,
+        winfo: _WeakRefInfo,
+        old_mem_consumed: Optional[int] = None,
+        old_reftype: Optional[_RefType] = None,
+    ) -> None:
+        # Initialize a flag to track if the total memory might drop to zero after updates.
+        maybe_zero = False
+        # Ensure the device entry exists in the current memory snapshot, initializing if necessary.
+        dev_snap = self._curr_mem_snap.setdefault(
+            winfo.device, dict.fromkeys(self._ref_class, 0)
+        )
+        dev_snap.setdefault(_TOTAL_KEY, 0)
+        # Handle different types of updates based on the update type (`u_type`).
+        if u_type == _UpdateType.ADD:
+            # Increase the memory consumed for the specific reference type and update the total.
+            dev_snap[winfo.reftype] += winfo.mem_consumed
+            dev_snap[_TOTAL_KEY] += winfo.mem_consumed
+        elif u_type == _UpdateType.DEL:
+            # Decrease the memory consumed for the specific reference type and reduce the total.
+            dev_snap[winfo.reftype] -= winfo.mem_consumed
+            dev_snap[_TOTAL_KEY] -= winfo.mem_consumed
+            maybe_zero = True
+        elif u_type == _UpdateType.REF:
+            assert old_reftype is not None
+            # Adjust memory consumption between two reference types within the same device.
+            dev_snap[old_reftype] -= winfo.mem_consumed
+            dev_snap[winfo.reftype] += winfo.mem_consumed
+        elif u_type == _UpdateType.SIZE:
+            assert old_mem_consumed is not None
+            # Adjust the memory consumed for a reference type due to a change in size.
+            change = winfo.mem_consumed - old_mem_consumed
+            dev_snap[winfo.reftype] += change
+            dev_snap[_TOTAL_KEY] += change
+            maybe_zero = True
+        else:
+            raise ValueError(f"Invalid update type: {u_type}")
+        # Check if the total memory for the device has dropped to zero.
+        if maybe_zero:
+            if self._curr_mem_snap[winfo.device][_TOTAL_KEY] == 0:
+                # Remove the device entry from the memory snapshot if the total memory is zero.
+                del self._curr_mem_snap[winfo.device]
+
+    def _update_and_maybe_create_winfos(
+        self,
+        t: torch.Tensor,
+        reftype: _RefType,
+        update_existing: bool = False,
+    ) -> Set[_WeakRefInfo]:
+        sts = _WeakRefInfo.get_untyped_storages(t)
+        winfos = set()
+        for st in sts:
+            # Attempt to retrieve existing ``_WeakRefInfo`` and its weak reference from the tracking dictionary.
+            winfo, _ = self._WINFO.get(st, (None, None))
+            if winfo is not None:
+                # If ``_WeakRefInfo`` exists, check if the reference type needs to be updated.
+                old_reftype = winfo.reftype
+                if old_reftype != reftype:
+                    # Update the reference type and apply changes via ``_update_snap``.
+                    winfo.reftype = reftype
+                    self._update_snap(_UpdateType.REF, winfo, old_reftype=old_reftype)
+                winfos.add(winfo)
+            elif update_existing:
+                # If no existing ``_WeakRefInfo`` is found and update_existing is True, raise an error.
+                raise KeyError("No existing winfo found")
+            else:
+                # If no existing _WeakRefInfo is found and update_existing is False, create a new ``_WeakRefInfo``.
+                winfo, w_st = _WeakRefInfo.create_winfo(
+                    st, t.device, reftype, self._delete_callback
+                )
+                # Store the new ``_WeakRefInfo`` and its weak reference in the tracking dictionary.
+                self._WINFO[st] = (winfo, w_st)
+                # Update the snapshot for the newly added ``_WeakRefInfo``.
+                if winfo.mem_consumed > 0:
+                    self._update_snap(_UpdateType.ADD, winfo)
+                winfos.add(winfo)
+        return winfos
+
+    def _delete_callback(self, winfo: _WeakRefInfo, w_st: weakref.ref) -> None:
+        # Callback to be called when the storage object corresponding to the  ``_WeakRefInfo``
+        # instance is about to be finalized.
+        if winfo.mem_consumed > 0:
+            self._update_snap(_UpdateType.DEL, winfo)
+
+    def _track_resize(self) -> None:
+        # Need to monkey-patch this because ``torch.UntypedStorage.resize_`` is not captured
+        # by ``TorchDispatchMode``.
+        @wraps(self._orig_resize)
+        def resize_(st: torch.UntypedStorage, size: int) -> None:
+            self._orig_resize(st, size)
+            winfo, _ = self._WINFO.get(st, (None, None))
+            if winfo is not None and winfo.size != st.size():
+                old_mem_consumed = winfo.mem_consumed
+                winfo.update_mem_consumed(st)
+                self._update_snap(
+                    _UpdateType.SIZE, winfo, old_mem_consumed=old_mem_consumed
+                )
+
+        torch.UntypedStorage.resize_ = resize_  # type: ignore[method-assign, assignment]
+
+    def _restore_resize(self) -> None:
+        torch.UntypedStorage.resize_ = self._orig_resize  # type: ignore[method-assign]
+
+    def _update_peak_stats(self, peak_state: _State) -> None:
+        # We first capture the current memory snapshot of the current tracker state then,
+        # We step through each of the modules we have tracked so far in ``memory_tracking``
+        #  and check if it is currently active by querying ``_mod_tracker.parents``
+        # If it is active, we update the per device peak memory usage for the module
+        #  corresponding to the ``_State`` which can be ``PEAK_FW`` or ``PEAK_BW``.
+        curr_snap = self._curr_mem_snap
+
+        for mod_stats in self.memory_tracking.values():
+            if mod_stats.mod_fqn in self._mod_tracker.parents:
+                if peak_state in mod_stats.snapshots:
+                    for dev, dev_snap in curr_snap.items():
+                        if mod_stats.local_peak.get(dev, 0) < dev_snap[_TOTAL_KEY]:
+                            mod_stats.local_peak[dev] = dev_snap[_TOTAL_KEY]
+                            mod_stats.snapshots[peak_state][-1][dev] = deepcopy(
+                                dev_snap
+                            )
+
+        for dev, dev_snap in curr_snap.items():
+            if self._peak_mem.get(dev, 0) < dev_snap[_TOTAL_KEY]:
+                self._peak_mem[dev] = dev_snap[_TOTAL_KEY]
+                self._peak_mem_snap[dev] = deepcopy(dev_snap)
+
+    def _track(self, reftype: _RefType, t: torch.Tensor) -> None:
+        # Get the storages of the tensor and check if we have already tracked them.
+        # If yes, then check if the storage size has changed and update the current snapshot.
+        # Else create a new ``_WeakRefInfo`` instance and add it to the dictionary.
+        sts = _WeakRefInfo.get_untyped_storages(t)
+        for st in sts:
+            winfo, _ = self._WINFO.get(st, (None, None))
+            if winfo is not None:
+                if winfo.size != st.size():
+                    old_mem_consumed = winfo.mem_consumed
+                    winfo.update_mem_consumed(st)
+                    self._update_snap(
+                        _UpdateType.SIZE, winfo, old_mem_consumed=old_mem_consumed
+                    )
+                return
+            else:
+                winfo, w_st = _WeakRefInfo.create_winfo(
+                    st, t.device, reftype, self._delete_callback
+                )
+                self._WINFO[st] = (winfo, w_st)
+                # Update the current snapshot for the newly added ``_WeakRefInfo``.
+                if winfo.mem_consumed > 0:
+                    self._update_snap(_UpdateType.ADD, winfo)
+
+    def get_tracker_snapshot(
+        self, type: str = "current"
+    ) -> Dict[torch.device, Dict[str, int]]:
+        """
+        Capture a snapshot of the memory usage breakdown per device, based on the specified type.
+
+        Args:
+            type (str): The type of snapshot to capture. Can be "current" for the current memory usage or "peak" for the
+                        peak memory usage. Defaults to "current".
+        Returns:
+            Dict[torch.device, Dict[str, int]]: A dictionary where each key is a torch.device, and each value is another
+                                                dictionary. This inner dictionary has keys representing memory reference
+                                                types as defined in ``_MemRefType`` and values representing the amount of
+                                                memory consumed in bytes.
+        Raises:
+            ValueError: If an invalid type is specified.
+        """
+        if type == "current":
+            return deepcopy(self._curr_mem_snap)
+        elif type == "peak":
+            return deepcopy(self._peak_mem_snap)
+        else:
+            raise ValueError(f"Invalid type {type}")
+
+    def _track_module_params_and_buffers(
+        self, module: nn.Module, install_grad_hooks: bool = True
+    ) -> Tuple[int, int]:
+        # Track the parameters and buffers of the module if not already tracked.
+        # If the parameters have gradients, track the gradients as well.
+        # If install_grad_hooks is True, install a gradient hook on the parameters
+        #  to track the gradients, if it has not already been installed.
+        # Return the total memory consumed by the parameters and buffers.
+        def _grad_hook(grad: torch.Tensor) -> None:
+            self._update_and_maybe_create_winfos(
+                grad,
+                _MemRefType.GRAD,
+            )
+
+        param_memory = 0
+        for param in module.parameters():
+            winfos = self._update_and_maybe_create_winfos(
+                param,
+                _MemRefType.PARAM,
+            )
+            param_memory += sum(winfo.mem_consumed for winfo in winfos)
+            if param.grad is not None:
+                self._update_and_maybe_create_winfos(
+                    param.grad,
+                    _MemRefType.GRAD,
+                )
+            if (
+                self._param_to_grad_hook_handles.get(param, None) is None
+                and install_grad_hooks
+            ):
+                grad_hook_handle = param.register_hook(_grad_hook)
+                post_acc_grad_hook_handle = param.register_post_accumulate_grad_hook(
+                    lambda p: (_grad_hook(p.grad))
+                )
+                self._param_to_grad_hook_handles[param] = (
+                    grad_hook_handle,
+                    post_acc_grad_hook_handle,
+                )
+        buffer_memory = 0
+        for buffer in module.buffers():
+            winfos = self._update_and_maybe_create_winfos(
+                buffer,
+                _MemRefType.BUFFER,
+            )
+            buffer_memory += sum(winfo.mem_consumed for winfo in winfos)
+        return (param_memory, buffer_memory)
+
+    def _track_inputs_or_outputs(self, args: Any) -> int:
+        # Calculate the memory consumed by the inputs or outputs of the module.
+        input_or_output_memory = 0
+
+        def add_inps_or_outs(t: torch.Tensor) -> None:
+            nonlocal input_or_output_memory
+            sts = _WeakRefInfo.get_untyped_storages(t)
+            for st in sts:
+                winfo, _ = self._WINFO.get(st, (None, None))
+                if winfo is not None:
+                    input_or_output_memory += winfo.mem_consumed
+
+        tree_map_only(torch.Tensor, add_inps_or_outs, args)
+        return input_or_output_memory
+
+    def _pre_fw_hook(self, module: nn.Module, inputs: Any) -> None:
+        # This is installed as a pre-fwd user hook with ``ModTracker.`` Based on the following cases we
+        # set the state and capture the memory snapshot for the module.
+        # Case 1: If the module is not in the ``memory_tracking`` dictionary, we track the parameters, buffers,
+        #         input and output memory of the module. Create a new ``_ModMemStats`` instance for the module
+        #         and add it to the ``memory_tracking`` dictionary.
+        # Case 2: If the module is already in the ``memory_tracking`` dictionary and we are in backward, this means
+        #         we are in the AC region. We check if this is the top most module in the AC region. If it is,
+        #         we store a weak reference and set the flag ``_in_ac`` to True.
+        # Case 3: If the module is already in the ``memory_tracking`` dictionary and we are in forward, this means
+        #         this module is called for the second time. If it is a root module, that means we are in the next
+        #         iteration and we error out. If it is not a root module, that means it's a submodule that is being
+        #         used multiple times in the same iteration, which we allow and track.
+        # For Case 1 and 3, we also initialiaze the ``local_peak`` and ``PEAK_FW`` snapshot for the module.
+        mod_name = self._mod_tracker.get_known_fqn(module)
+        assert mod_name is not None
+        if module not in self.memory_tracking:
+            mod_stats = _ModMemStats(mod_name)
+            param_mem, buffer_mem = self._track_module_params_and_buffers(
+                module, install_grad_hooks=True
+            )
+            input_mem = self._track_inputs_or_outputs(inputs)
+            mod_stats.parameter_mem = param_mem
+            mod_stats.buffer_mem = buffer_mem
+            mod_stats.input_mem = input_mem
+            self.memory_tracking[module] = mod_stats
+            state = _ModState.PRE_FW
+
+        elif self._mod_tracker.is_bw:
+            mod_stats = self.memory_tracking[module]
+            state = _ModState.PRE_FW_AC
+            if self._ac_mod is None:
+                self._ac_mod = weakref.ref(module)
+                self._in_ac = True
+        else:
+            parents = set(self._mod_tracker.parents) - {mod_name}
+            if len(parents) == 1 and "Global" in parents:
+                raise NotImplementedError(
+                    "MemTracker does not support memory tracking for multiple iterative calls."
+                    " Either use ``reset_mod_stats`` to clear module memory stats for the previous iteration"
+                    " or file a github issue if you need this feature."
+                )
+            mod_stats = self.memory_tracking[module]
+            state = _ModState.PRE_FW
+            input_mem = self._track_inputs_or_outputs(inputs)
+            mod_stats.input_mem = input_mem
+
+        mem_snapshot = self.get_tracker_snapshot()
+        if state == _ModState.PRE_FW:
+            mod_stats.local_peak = {
+                dev: dev_snap[_TOTAL_KEY] for dev, dev_snap in mem_snapshot.items()
+            }
+            mod_stats.snapshots.setdefault(_ModState.PEAK_FW, []).append(mem_snapshot)
+        mod_stats.snapshots.setdefault(state, []).append(deepcopy(mem_snapshot))
+
+    def _post_fw_hook(self, module: nn.Module, inputs: Any, outputs: Any) -> None:
+        # This is installed as a post-fwd user hook with ``ModTracker``. Based on the following cases we
+        # set the state and capture the memory snapshot for the module.
+        # Case 1: This is called in backward, which means we are in the AC region. If this is the top most module
+        #         in the AC region, we set the flag ``_in_ac`` to False.
+        # Case 2: This is called in forward so we calculate the output memory
+        #         of the module and update its mod_stats.
+        mod_stats = self.memory_tracking[module]
+        if self._mod_tracker.is_bw:
+            state = _ModState.POST_FW_AC
+            if self._ac_mod is not None and self._ac_mod() is module:
+                self._ac_mod = None
+                self._in_ac = False
+        else:
+            state = _ModState.POST_FW
+            output_mem = self._track_inputs_or_outputs(outputs)
+            mod_stats.output_mem = output_mem
+        mod_stats.snapshots.setdefault(state, []).append(self.get_tracker_snapshot())
+
+    def _pre_bw_hook(self, module: nn.Module, args: Any) -> None:
+        # This is installed as a pre-bwd user hook with ``ModTracker``. We set the state and capture the
+        # snapshot for the module. We also initialize the ``local_peak`` and ``PEAK_BW`` snapshot for it.
+        # If the module is None, we skip the hook.
+        # This can happen since this installed inside a multi-grad hook on the module's output tensors
+        # and the module itself may not be alive during backward.
+        if module is None:
+            warnings.warn("Module is None. Skipping PRE_BW hook.", stacklevel=2)
+            return
+        mod_stats = self.memory_tracking[module]
+        mem_snapshot = self.get_tracker_snapshot()
+        mod_stats.local_peak = {
+            dev: dev_snap[_TOTAL_KEY] for dev, dev_snap in mem_snapshot.items()
+        }
+        mod_stats.snapshots.setdefault(_ModState.PEAK_BW, []).append(mem_snapshot)
+        mod_stats.snapshots.setdefault(_ModState.PRE_BW, []).append(
+            deepcopy(mem_snapshot)
+        )
+
+    def _post_bw_hook(self, module: nn.Module, args: Any) -> None:
+        # This is installed as a post-bwd user hook with ``ModTracker``. We set the state and capture the
+        # snapshot for the module if it is not None.
+        # This can happen since this installed inside a multi-grad hook on the module's input tensors
+        # and the module itself may not be alive during backward.
+        if module is None:
+            warnings.warn("Module is None. Skipping POST_BW hook.", stacklevel=2)
+            return
+        mod_stats = self.memory_tracking[module]
+        mod_stats.snapshots.setdefault(_ModState.POST_BW, []).append(
+            self.get_tracker_snapshot()
+        )
+
+    def _track_optimizer_states(
+        self, reftype: _RefType, optimizer: optim.Optimizer
+    ) -> None:
+        for states in optimizer.state.values():
+            for val in states.values():
+                if isinstance(val, torch.Tensor):
+                    self._update_and_maybe_create_winfos(
+                        val,
+                        reftype,
+                    )
+
+    def _register_global_optimizer_hook(self) -> None:
+        # Register a hook on the optimizer step to track the optimizer states.
+        # The pre-hook is to set the flag ``_in_opt`` to True. The post-hook unsets the flag,
+        # and also tracks any optimizer states that are created during the optimizer step.
+        def _opt_step_pre_hook(
+            optimizer: optim.Optimizer, args: Any, kwargs: Any
+        ) -> None:
+            self._in_opt = True
+
+        def _opt_step_post_hook(
+            optimizer: optim.Optimizer, args: Any, kwargs: Any
+        ) -> None:
+            self._track_optimizer_states(_MemRefType.OPT, optimizer)
+            self._in_opt = False
+
+        self._optimizer_hook_handles = (
+            register_optimizer_step_pre_hook(_opt_step_pre_hook),
+            register_optimizer_step_post_hook(_opt_step_post_hook),
+        )
+
+    def _deregister_param_and_optimizer_hooks(self) -> None:
+        for (
+            grad_hook_handle,
+            post_acc_grad_hook_handle,
+        ) in self._param_to_grad_hook_handles.values():
+            grad_hook_handle.remove()
+            post_acc_grad_hook_handle.remove()
+        self._param_to_grad_hook_handles.clear()
+
+        if self._optimizer_hook_handles is not None:
+            for handle in self._optimizer_hook_handles:
+                handle.remove()
+            self._optimizer_hook_handles = None
+
+    def track_external(
+        self, *external: Union[nn.Module, optim.Optimizer, torch.Tensor]
+    ) -> None:
+        """
+        Track tensors and stateful objects like modules, optimizers etc. that are created outside the MemTracker.
+
+        This method should be called before the ``MemTracker`` is used. Any tensors that are not module parameters, buffers,
+        gradients activations, or optimizer states will be categorized as ``Other``. If you want them categorized with a
+        custom name, please file a GitHub issue. Any tensors created outside the MemTracker and not supplied to this
+        method will not be be tracked by ``MemTracker``.
+
+        Args:
+            *external (Union[nn.Module, optim.Optimizer, torch.Tensor]): The external modules, optimizers, and
+                                                                         tensors to be tracked.
+        """
+        flat_external, _ = tree_flatten(external)
+        for obj in flat_external:
+            if isinstance(obj, torch.Tensor):
+                self._update_and_maybe_create_winfos(
+                    obj,
+                    _MemRefType.OTH,
+                )
+            elif isinstance(obj, torch.nn.Module):
+                self._track_module_params_and_buffers(obj, install_grad_hooks=False)
+            elif isinstance(obj, optim.Optimizer):
+                self._track_optimizer_states(_MemRefType.OPT, obj)
+            else:
+                raise TypeError(
+                    f"Object of type {type(obj)} is not supported for tracking. "
+                    f"Only stateful objects like modules, optimizers, and tensors are supported."
+                )
+
+    def display_snapshot(
+        self, type: str = "current", units: str = "B", tabulate: bool = False
+    ) -> None:
+        """
+        Display the memory usage breakdown snapshot of the tracker based on the specified type and units.
+
+        Keyword args:
+            type (str): The type of snapshot to display. Can be "current" for the current memory usage or "peak" for the
+                        peak memory usage. Defaults to "current".
+            units (str): The units to use for displaying memory usage. Defaults to "B". Supports ["B", "KiB", "MiB", "GiB"].
+            tabulate (bool): Whether to display the snapshot in a tabular format. Defaults to False.
+        """
+        snapshot = self.get_tracker_snapshot(type)
+        if tabulate:
+            _print_snapshot_tabular(snapshot, units)
+        else:
+            _print_snapshot(snapshot, units)
+
+    def display_modulewise_snapshots(
+        self, depth: int = 2, units: str = "B", tabulate: bool = False
+    ) -> None:
+        """
+        Print per device memory breakdown snapshot for each module called within MemTracker.
+
+        Snapshots are displayed for the states defined by ``_ModState``.
+        The module hierarchy is displayed up to the specified depth.
+
+        Keyword Args:
+            depth (int, optional): The depth of the module hierarchy to display. Defaults to 2.
+            units (str, optional): The units to use for memory tracking. Defaults to "B". Supports ["B", "KiB", "MiB", "GiB"].
+            tabulate (bool, optional): Whether to display the snapshot in a tabular format. Defaults to False.
+        """
+
+        def natural_sort_key(s: str) -> List[Union[int, str]]:
+            return [
+                int(text) if text.isdigit() else text.lower()
+                for text in re.split("([0-9]+)", s)
+            ]
+
+        for mod_stats in sorted(
+            self.memory_tracking.values(),
+            key=lambda m_stats: natural_sort_key(m_stats.mod_fqn),
+        ):
+            mod_fqn = mod_stats.mod_fqn
+            mod_depth = mod_fqn.count(".") + 1
+            if mod_depth > depth:
+                continue
+            print(f"Module:  {mod_fqn}")
+            if tabulate:
+                _print_state_snapshots_tabular(mod_stats.snapshots, units)
+            else:
+                _print_state_snapshots(mod_stats.snapshots, units)
+
+    def reset_mod_stats(self) -> None:
+        """
+        Reset all the module memory stats. Clears ``memory_tracking`` dictionary.
+        """
+        self.memory_tracking.clear()
+
+    def __enter__(self) -> "MemTracker":
+        self._register_global_optimizer_hook()
+        self._mod_tracker.register_user_hooks(
+            self._pre_fw_hook,
+            self._post_fw_hook,
+            self._pre_bw_hook,
+            self._post_bw_hook,
+        )
+        self._track_resize()
+        self._peak_mem_snap = self.get_tracker_snapshot()
+        self._peak_mem = {
+            dev: dev_snap[_TOTAL_KEY] for dev, dev_snap in self._peak_mem_snap.items()
+        }
+        self._mod_tracker.__enter__()
+        super().__enter__()
+        return self
+
+    def __exit__(self, *args: Any) -> None:
+        self._deregister_param_and_optimizer_hooks()
+        self._mod_tracker.clear_user_hooks()
+        self._restore_resize()
+        super().__exit__(*args)
+        self._mod_tracker.__exit__(*args)
+
+    def __torch_dispatch__(self, func, types, args=(), kwargs=None):  # type: ignore[no-untyped-def]
+        res = func(*args, **kwargs or {})
+        # If we are tracking an optimizer state, we use the optimizer reference type.
+        # If we are in backward region and not in AC region, we use the backward reference type.
+        # Else we use the forward reference type.
+        if self._in_opt:
+            reftype = _MemRefType.OPT
+        elif self._mod_tracker.is_bw and not self._in_ac:
+            reftype = _MemRefType.TEMP
+        else:
+            reftype = _MemRefType.ACT
+        tree_map_only(torch.Tensor, partial(self._track, reftype), res)
+        peak_state = _ModState.PEAK_BW if self._mod_tracker.is_bw else _ModState.PEAK_FW
+        self._update_peak_stats(peak_state)
+        return res
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/memory_tracker.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/memory_tracker.py
new file mode 100644
index 0000000000000000000000000000000000000000..e4d8aa6e762b8f4ec8b00ba86bf77de39afb20be
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/memory_tracker.py
@@ -0,0 +1,295 @@
+# mypy: allow-untyped-defs
+import operator
+import pickle
+from collections import defaultdict
+from itertools import chain
+from typing import Any, Callable, Dict, List, no_type_check, Sequence, TYPE_CHECKING
+
+import torch
+import torch.nn as nn
+from torch.utils._python_dispatch import TorchDispatchMode
+
+
+if TYPE_CHECKING:
+    from torch.utils.hooks import RemovableHandle
+
+
+BYTES_PER_MB = 1024 * 1024.0
+
+
+class MemoryProfileDispatchMode(TorchDispatchMode):
+    """Run in ``TorchDispatchMode`` to get memory stats at operator level."""
+
+    def __init__(self, memory_tracker) -> None:
+        self.memory_tracker = memory_tracker
+
+    def __torch_dispatch__(self, func, types, args=..., kwargs=None):
+        rs = func(*args, **kwargs)
+        if func == torch.ops.aten.detach.default:
+            return rs
+        func_name: str = (
+            self.memory_tracker._cur_module_name
+            + "."
+            + func.__name__
+            + "_"
+            + str(self.memory_tracker._operator_names[func.__name__])
+        )
+        self.memory_tracker._operator_names[func.__name__] = (
+            self.memory_tracker._operator_names[func.__name__] + 1
+        )
+        self.memory_tracker._record_memory_stats(func_name)
+
+        return rs
+
+
+class MemoryTracker:
+    """
+    Collect and plot the memory stats at operator level.
+
+    Includes ``memories_allocated``, ``memories_active`` and ``memories_reserved``.
+    It also prints a summary for the top 20 operators that generate the most memories.
+
+    Example usage:
+
+        >>> # xdoctest: +SKIP(failing)
+        >>> net.cuda()
+        >>> input = input.cuda()
+
+        >>> mem_tracker = MemoryTracker()
+        >>> mem_tracker.start_monitor(net)
+
+        >>> net.zero_grad(True)
+        >>> loss = net(input)
+        >>> if isinstance(loss, dict):
+        >>>    loss = loss['out']
+        >>> loss.sum().backward()
+        >>> net.zero_grad(set_to_none=True)
+
+        >>> mem_tracker.stop()
+        >>> mem_tracker.summary()
+        >>> mem_tracker.show_traces()
+    """
+
+    def __init__(self) -> None:
+        torch._C._log_api_usage_once("torch.distributed.memory_tracker")
+        self._hooks: List[RemovableHandle] = []
+        self._operator_names: Dict[str, int] = defaultdict(int)
+        self.memories_allocated: Dict[int, Dict[str, float]] = defaultdict()
+        self.memories_active: Dict[int, Dict[str, float]] = defaultdict()
+        self.memories_reserved: Dict[int, Dict[str, float]] = defaultdict()
+        self._markers: Dict[str, int] = defaultdict(int)
+        self._cur_module_name: str = ""
+        self._op_index: int = 0
+        self._num_cuda_retries: int = 0
+
+    @no_type_check
+    def start_monitor(self, root_module: nn.Module) -> None:
+        """
+        Register module hooks and entering ``MemoryProfileDispatchMode``.
+
+        This enables operator level memory stats can be tracked during module runtime.
+        """
+        self._clear_state()
+        root_module.__setattr__("_memory_tracker_is_root", True)
+        for name, m in root_module.named_modules():
+            if m is not root_module:
+                m.__setattr__("_memory_tracker_is_root", False)
+            # fused_proxy_group does not support hooks
+            if ".fused_proxy_grouped_embedding_bag" in name:
+                continue
+            # hook ordering with other hooks added by users is not managed, so
+            # the memory stats tracked here may not completely accurate.
+            h1 = m.register_forward_pre_hook(self._create_pre_forward_hook(name))
+            h2 = m.register_forward_hook(self._create_post_forward_hook(name))
+            # it does not work well with jagged tensor somehow, the root cause is not
+            # clear and remove it for now as it does not really capture important info.
+            # h3 = m.register_backward_hook(self._create_backward_hook(name))
+            self._hooks.extend([h1, h2])
+        torch.cuda.empty_cache()
+        assert getattr(self, "profile_mode", None) is None
+        self.profile_mode = MemoryProfileDispatchMode(self)
+        self.profile_mode.__enter__()
+
+    @no_type_check
+    def stop(self) -> None:
+        """
+        Remove module hooks and exit ``MemoryProfileDispatchMode`` to stop tracking memory stats at operator level.
+
+        Get some aggregated stats when the memory_tracker() is enabled, like cuda ``num_alloc_retries``.
+        """
+        self._num_cuda_retries = torch.cuda.memory_stats().get("num_alloc_retries", 0)
+
+        for h in self._hooks:
+            h.remove()
+        self._hooks.clear()
+        assert getattr(self, "profile_mode", None) is not None
+        self.profile_mode.__exit__(None, None, None)
+        self.profile_mode = None
+
+    @no_type_check
+    def summary(self, top: int = 20) -> None:
+        """
+        Print out the top operators that generate the most memories.
+
+        The number of the top operators can be configured.
+        """
+        op_diff: Dict[str, float] = defaultdict(float)
+        op_name, previous_allocated_memory = self.memories_allocated[0]
+        for i in range(1, self._op_index):
+            op_name, current_allocated_memory = self.memories_allocated[i]
+            op_diff[op_name] = current_allocated_memory - previous_allocated_memory
+            previous_allocated_memory = current_allocated_memory
+
+        print("------------------------------------------------")
+        print(f"The number of cuda retries are: {self._num_cuda_retries}")
+        print(f"Top {top} ops that generates memory are:")
+        for k, v in sorted(op_diff.items(), key=operator.itemgetter(1), reverse=True)[
+            :top
+        ]:
+            print(f"{k}: {v}MB")
+        print("------------------------------------------------")
+
+    @no_type_check
+    def show_traces(self, path: str = "") -> None:
+        import matplotlib.pyplot as plt
+
+        def _plot_figure(x, y_values, labels):
+            min_val = min(list(chain(*y_values))) * 0.999
+            max_val = max(list(chain(*y_values))) * 1.001
+            plt.figure()
+            for y, label in zip(y_values, labels):
+                plt.plot(x, y, label=label)
+            plt.xlabel("# Operator Calls")
+            plt.ylabel("Memory (MB)")
+            plt.legend()
+            for marker_name, marker in self._markers.items():
+                if marker_name == "fw_bw_boundary":
+                    plt.plot(
+                        [marker, marker],
+                        [min_val, max_val],
+                        "r",
+                        lw=2,
+                        label=marker_name,
+                    )
+                else:
+                    plt.plot(
+                        [marker, marker],
+                        [min_val, max_val],
+                        "k-",
+                        lw=2,
+                        label=marker_name,
+                    )
+
+        if path != "":
+            self.load(path)
+
+        y_1 = [gb for (name, gb) in self.memories_allocated.values()]
+        y_2 = [gb for (name, gb) in self.memories_active.values()]
+        y_3 = [gb for (name, gb) in self.memories_reserved.values()]
+        x = list(range(len(y_1)))
+        # Split figures when there is big difference between
+        # "reserved_memory" and "allocated_memory" or "active_memory".
+        _plot_figure(
+            x,
+            [list(y_1), list(y_2), list(y_3)],
+            ["allocated_memory", "active_memory", "reserved_memory"],
+        )
+        _plot_figure(x, [list(y_1)], ["allocated_memory"])
+        _plot_figure(x, [list(y_2)], ["active_memory"])
+        _plot_figure(x, [list(y_3)], ["reserved_memory"])
+
+    def save_stats(self, path: str) -> None:
+        """Save the stats using pickle during runtime if users want to plot the traces in other places like notebook."""
+        stats = {
+            "memories_allocated": self.memories_allocated,
+            "memories_active": self.memories_active,
+            "memories_reserved": self.memories_reserved,
+            "markers": self._markers,
+            "num_alloc_retries": self._num_cuda_retries,
+        }
+
+        with open(path, "wb") as f:
+            pickle.dump(stats, f, pickle.HIGHEST_PROTOCOL)
+
+    def load(self, path: str) -> None:
+        """Load the pickled memory stats to plot the traces or print the summary."""
+        with open(path, "rb") as f:
+            stats = pickle.load(f)
+
+        self.memories_allocated = stats["memories_allocated"]
+        self.memories_active = stats["memories_active"]
+        self.memories_reserved = stats["memories_reserved"]
+        self._markers = stats["markers"]
+        self._num_cuda_retries = stats["num_alloc_retries"]
+
+    def _create_pre_forward_hook(self, name: str) -> Callable:
+        """Prefix operator name with current module and 'forward', and insert 'fw_start' marker at forward pass start."""
+
+        def _pre_forward_hook(module: nn.Module, inputs: Any) -> None:
+            self._cur_module_name = f"{name}.forward"
+            if (
+                hasattr(module, "_memory_tracker_is_root")
+                and module._memory_tracker_is_root
+            ):
+                self._add_marker("fw_start")
+
+        return _pre_forward_hook
+
+    def _create_post_forward_hook(self, name: str) -> Callable:
+        """Insert the marker 'fw_bw_boundary' at the boundary of forward and backward pass."""
+
+        def _post_forward_hook(
+            module: nn.Module,
+            inputs: Sequence[torch.Tensor],
+            outputs: Sequence[torch.Tensor],
+        ) -> None:
+            if (
+                hasattr(module, "_memory_tracker_is_root")
+                and module._memory_tracker_is_root
+            ):
+                self._add_marker("fw_bw_boundary")
+
+        return _post_forward_hook
+
+    def _create_backward_hook(self, name: str) -> Callable:
+        """Insert the current module name with backward prefix for the operator name."""
+
+        def _backward_hook(
+            module: nn.Module, grad_input: torch.Tensor, grad_output: torch.Tensor
+        ) -> None:
+            self._cur_module_name = f"{name}.backward"
+
+        return _backward_hook
+
+    @no_type_check
+    def _record_memory_stats(self, fn_name: str) -> None:
+        """
+        Record current memory allocated, current memory active and current memory reserved.
+
+        The memory stats dict is indexed with ``self._op_index``.
+        """
+        memory_allocated: float = torch.cuda.memory_allocated() / BYTES_PER_MB
+        memory_reserved: float = torch.cuda.memory_reserved() / BYTES_PER_MB
+        memory_active: float = (
+            torch.cuda.memory_stats().get("active_bytes.all.current", 0) / BYTES_PER_MB
+        )
+        self.memories_allocated[self._op_index] = (fn_name, memory_allocated)
+        self.memories_reserved[self._op_index] = (fn_name, memory_reserved)
+        self.memories_active[self._op_index] = (fn_name, memory_active)
+        self._op_index += 1
+
+    def _add_marker(self, marker_name: str) -> None:
+        """Set the marker's x-axis value."""
+        marker_val = len(self.memories_allocated.values())
+        self._markers[marker_name] = marker_val
+
+    def _clear_state(self) -> None:
+        """Clear states when start_monitor() is called."""
+        self._operator_names.clear()
+        self.memories_allocated.clear()
+        self.memories_active.clear()
+        self.memories_reserved.clear()
+        self._markers.clear()
+        self._cur_module_name = ""
+        self._op_index = 0
+        self._num_cuda_retries = 0
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/mod_tracker.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/mod_tracker.py
new file mode 100644
index 0000000000000000000000000000000000000000..3525ae3f95bfa0017c9943e4612a500d76000a23
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/mod_tracker.py
@@ -0,0 +1,238 @@
+# mypy: allow-untyped-defs
+import warnings
+import weakref
+from typing import Callable, Optional, Set
+
+import torch
+from torch.autograd.graph import register_multi_grad_hook
+from torch.nn.modules.module import (
+    register_module_forward_hook,
+    register_module_forward_pre_hook,
+)
+from torch.utils._pytree import tree_flatten
+
+
+__all__ = ["ModTracker"]
+
+
+class ModTracker:
+    """
+    ``ModTracker`` is a context manager that tracks the nn.Module hierarchy during execution
+    so that other system can query which Module is currently being executed (or its backward is being
+    executed).
+
+    You can access the ``parents`` attribute on this context manager to get the set of all the
+    Modules currently being executed via their fqn (fully qualified name, also used as the key within
+    the state_dict).
+    You can access the ``is_bw`` attribute to know if you are currently running in backward or not.
+
+    Note that ``parents`` is never empty and always contains the "Global" key. The ``is_bw`` flag
+    will remain ``True`` after the forward until another Module is executed. If you need it to be
+    more accurate, please submit an issue requesting this. Adding a map from fqn to the module instance
+    is possible but not done yet, please submit an issue requesting this if you need it.
+
+    Example usage
+
+    .. code-block:: python
+
+        mod = torch.nn.Linear(2, 2)
+
+        with ModTracker() as tracker:
+            # Access anything during the forward pass
+            def my_linear(m1, m2, bias):
+                print(f"Current modules: {tracker.parents}")
+                return torch.mm(m1, m2.t()) + bias
+            torch.nn.functional.linear = my_linear
+
+            mod(torch.rand(2, 2))
+
+    """
+
+    parents: Set[str]
+    """
+    A Set containing the fqn for each module currently running their forward
+    """
+
+    def __init__(self):
+        self.parents = {"Global"}
+        self._active_module_cnt = {}
+        self._known_modules: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary()
+        self._seen_modules: weakref.WeakSet = weakref.WeakSet()
+        self._has_callback = False
+        self._user_pre_fw_hook = None
+        self._user_post_fw_hook = None
+        self._user_pre_bw_hook = None
+        self._user_post_bw_hook = None
+
+    def _maybe_set_engine_callback(self):
+        # This assumes no concurrent calls to backward
+        if self._has_callback:
+            return
+
+        def callback():
+            self.parents = {"Global"}
+            self._has_callback = False
+
+        torch.autograd.Variable._execution_engine.queue_callback(callback)
+        self._has_callback = True
+
+    @property
+    def is_bw(self):
+        """
+        A boolean marking if this is currently running during the backward pass or not
+        """
+        return torch._C._current_graph_task_id() != -1
+
+    def get_known_fqn(self, mod):
+        """
+        Return the fqn for the given module if it is known to the ``ModTracker``, otherwise ``None``.
+        """
+        return self._known_modules.get(mod, None)
+
+    def register_user_hooks(
+        self,
+        pre_fw_hook: Optional[Callable] = None,
+        post_fw_hook: Optional[Callable] = None,
+        pre_bw_hook: Optional[Callable] = None,
+        post_bw_hook: Optional[Callable] = None,
+    ):
+        """
+        Registers user-specified hooks to be called before/after the forward/backward pass for each
+        module tracked by the ``ModTracker``. One or more can be ``None``.
+        Args:
+            pre_fw_hook (Callable, optional): A hook to be called before the forward pass for the
+                module. It should have the following signature:
+                pre_fw_hook (module, input) -> None
+            post_fw_hook (Callable, optional): A hook to be called after the forward pass for the
+                module. It should have the following signature:
+                post_fw_hook (module, input, output) -> None
+            pre_bw_hook (Callable, optional): A multi-grad hook to be called on all the outputs of
+                the module that require gradients. It should have the following signature:
+                pre_bw_hook (module, grad_output) -> None
+            post_bw_hook (Callable, optional): A multi-grad hook to be called on all the inputs of
+                the module that require gradients. It should have the following signature:
+                post_bw_hook (module, grad_input) -> None
+        Raises:
+            AssertionError: If a new hook is provided when one is already registered.
+        Note:
+            If the module is not alive during the backward pass, the pre_bw_hook and post_bw_hook will
+            will receive None as the module argument.
+            The module fqn will be present in the ``parents`` attribute when each of the hooks is called.
+            Hooks are intended to be used as markers only not to modify the inputs/outputs.
+        """
+
+        def set_hook(hook, user_hook, hook_name):
+            if hook is not None and user_hook is not None:
+                raise AssertionError(
+                    f"Only one {hook_name} can be registered at a time"
+                    f" Clear the existing hook by calling ``clear_user_hooks`` before registering a new one"
+                )
+            return hook
+
+        self._user_pre_fw_hook = set_hook(
+            pre_fw_hook, self._user_pre_fw_hook, "pre_fw_hook"
+        )
+        self._user_post_fw_hook = set_hook(
+            post_fw_hook, self._user_post_fw_hook, "post_fw_hook"
+        )
+        self._user_pre_bw_hook = set_hook(
+            pre_bw_hook, self._user_pre_bw_hook, "pre_bw_hook"
+        )
+        self._user_post_bw_hook = set_hook(
+            post_bw_hook, self._user_post_bw_hook, "post_bw_hook"
+        )
+
+    def clear_user_hooks(self):
+        """
+        Clears the user specified hooks registered with ``register_user_hooks``
+        """
+        self._user_pre_fw_hook = None
+        self._user_post_fw_hook = None
+        self._user_pre_bw_hook = None
+        self._user_post_bw_hook = None
+
+    def _get_mod_name(self, mod):
+        if mod not in self._known_modules:
+            self._known_modules[mod] = type(mod).__name__
+        mod_name = self._known_modules[mod]
+        if mod not in self._seen_modules:
+            for name, submod in mod.named_children():
+                self._known_modules[submod] = f"{mod_name}.{name}"
+                self._get_mod_name(submod)
+            self._seen_modules.add(mod)
+        return mod_name
+
+    def _get_append_fn(self, w_mod, name, is_bw):
+        def fn(*args):
+            if is_bw:
+                self._maybe_set_engine_callback()
+            if name in self.parents and not self.is_bw:
+
+                def custom_formatwarning(msg, category, filename, lineno, line=None):
+                    return f"{filename}:{lineno}: {category.__name__}: {msg} \n"
+
+                warnings.formatwarning = custom_formatwarning
+                warnings.warn(
+                    "The module hierarchy tracking maybe be messed up."
+                    " Please file a bug to PyTorch, if it is the case."
+                )
+            if name not in self.parents:
+                self._active_module_cnt[name] = 1
+                self.parents.add(name)
+            else:
+                self._active_module_cnt[name] += 1
+
+            if self._user_pre_bw_hook is not None and is_bw:
+                self._user_pre_bw_hook(w_mod(), args)
+
+        return fn
+
+    def _get_pop_fn(self, w_mod, name, is_bw):
+        def fn(*args):
+            if self._user_post_bw_hook is not None and is_bw:
+                self._user_post_bw_hook(w_mod(), args)
+            if name in self.parents:
+                self._active_module_cnt[name] -= 1
+                if self._active_module_cnt[name] == 0:
+                    self.parents.remove(name)
+            elif not self.is_bw:
+                # Due to some input/output not requiring gradients, we cannot enforce
+                # proper nesting in backward
+                raise RuntimeError(
+                    "The Module hierarchy tracking is wrong. Report a bug to PyTorch"
+                )
+
+        return fn
+
+    def _fw_pre_hook(self, mod, input):
+        name = self._get_mod_name(mod)
+        w_mod = weakref.ref(mod)
+        self._get_append_fn(w_mod, name, False)()
+        if self._user_pre_fw_hook is not None:
+            self._user_pre_fw_hook(mod, input)
+        args, _ = tree_flatten(input)
+        tensors = [a for a in args if isinstance(a, torch.Tensor) and a.requires_grad]
+        if not self.is_bw and tensors:
+            register_multi_grad_hook(tensors, self._get_pop_fn(w_mod, name, True))
+
+    def _fw_post_hook(self, mod, input, output):
+        name = self._get_mod_name(mod)
+        w_mod = weakref.ref(mod)
+        if self._user_post_fw_hook is not None:
+            self._user_post_fw_hook(mod, input, output)
+        self._get_pop_fn(w_mod, name, False)()
+        args, _ = tree_flatten(output)
+        tensors = [a for a in args if isinstance(a, torch.Tensor) and a.requires_grad]
+        if not self.is_bw and tensors:
+            register_multi_grad_hook(tensors, self._get_append_fn(w_mod, name, True))
+
+    def __enter__(self):
+        self._fw_pre_handle = register_module_forward_pre_hook(self._fw_pre_hook)
+        self._fw_post_handle = register_module_forward_hook(
+            self._fw_post_hook, always_call=True
+        )
+        return self
+
+    def __exit__(self, *args):
+        self._fw_pre_handle.remove()
+        self._fw_post_handle.remove()
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/runtime_estimator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/runtime_estimator.py
new file mode 100644
index 0000000000000000000000000000000000000000..87f4d3f36b60e09e47e013018690359e6cc72140
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/_tools/runtime_estimator.py
@@ -0,0 +1,527 @@
+# Owner(s): ["module: unknown"]
+import math
+import os
+from collections import defaultdict
+from typing import Any, Callable, Dict, List, Set, Tuple
+from typing_extensions import Self
+
+import torch
+import torch.utils._pytree as pytree
+from torch._guards import active_fake_mode
+from torch._inductor.utils import get_device_tflops, get_gpu_dram_gbps
+from torch._subclasses.fake_tensor import FakeTensorMode
+from torch.distributed._tools.mod_tracker import ModTracker
+from torch.utils._mode_utils import no_dispatch
+from torch.utils._python_dispatch import TorchDispatchMode
+from torch.utils.flop_counter import flop_registry
+
+
+aten = torch.ops.aten
+
+# This value is hard-coded here:
+# https://github.com/pytorch/pytorch/blob/5fba5d83f0703ff8077ab65448a998e9ad6598fd/c10/cuda/CUDACachingAllocator.cpp#L117
+_PYTORCH_MIN_ALLOCATE = (
+    2**9 if int(os.environ.get("PYTORCH_NO_CUDA_MEMORY_CACHING", 0)) == 0 else 1
+)
+
+# No fall-back kernel needed/exists for view ops
+_VIEW_OPS = {
+    aten.lift_fresh,
+    aten.t,
+    aten.transpose,
+    aten.view,
+    aten.detach,
+    aten._unsafe_view,
+    aten.split,
+    aten.adjoint,
+    aten.as_strided,
+    aten.diagonal,
+    aten.expand,
+    aten.expand_as,
+    aten.movedim,
+    aten.permute,
+    aten.select,
+    aten.squeeze,
+    aten.mT,
+    aten.mH,
+    aten.real,
+    aten.imag,
+    aten.view_as,
+    aten.unflatten,
+    aten.unfold,
+    aten.unbind,
+    aten.unsqueeze,
+    aten.vsplit,
+    aten.hsplit,
+    aten.split_with_sizes,
+    aten.swapaxes,
+    aten.swapdims,
+    aten.chunk,
+}
+# We can ignore benchmarking tensor create ops
+_CREATE_OPS = {
+    aten.randint,
+    aten.randn,
+    aten.rand,
+    aten.randn_like,
+    aten.rand_like,
+    aten.randint_like,
+    aten.arange,
+    aten.ones_like,
+    aten.zeros_like,
+}
+
+_IGNORE_OPS = _VIEW_OPS | _CREATE_OPS
+
+__all__ = ["RuntimeEstimator"]
+
+
+class RuntimeEstimator(TorchDispatchMode):
+    """
+    Estimates the GPU runtime in milliseconds using various estimation methods under the ``FakeTensorMode``.
+
+    This class provides a ``TorchDispatchMode`` based context manager that can be used to estimate the eager
+    runtime of PyTorch functions. It supports two estimation modes, benchmarking (`operator-level-benchmark`) and
+    roofline cost modeling (`operator-level-cost-model`).
+    For modules executed under this context manager, it agggregates the forward and backward operation runtimes
+    and also records their execution orders.
+
+    Attributes:
+        mod_runtimes (Dict[str, Dict[str, float]]): A dictionary of module runtimes. The key to the outer dictionary
+            is the fully qualified name (FQN) of the module. For each module the forward and backward runtimes of the
+            operations are aggregated in the inner dictionary keyed by 'fw' and 'bw'.
+        mod_fw_pre_order (List[str]): List of module FQNs in pre-forward execution order.
+        mod_bw_pre_order (List[str]): List of module FQNs in pre-backward execution order.
+        mod_fw_post_order (List[str]): List of module FQNs in post-forward execution order.
+        mod_bw_post_order (List[str]): List of module FQNs in post-backward execution order.
+        total_runtime (float): The total estimated runtime in milliseconds.
+
+    Note:
+        1) The benchmarking estimate mode will execute kernels on GPU and assumes that every operation can run in
+            isolation without causing an OOM error. It is also designed to be used only under ``FakeTensorMode``.
+        2) Currently wrapper tensor sub-classes such as ``DTensor`` won't produce correct estimates. We plan to support
+            them in future PRs.
+        3) We only estimate the compute time, if your code has communication, it will not be considered. Again, we will
+            support this in future PRs.
+
+    Example usage:
+
+        .. code-block:: python
+
+            runtime_estimator = RuntimeEstimator()
+            with FakeTensorMode():
+                module = ...
+                optimizer = ...
+                inp = ...
+                with runtime_estimator(estimate_mode_type="operator-level-cost-model"):
+                    loss = module(inp)
+                    loss.backward()
+                    optimizer.step()
+                    optimizer.zero_grad()
+                runtime_estimator.display_modulewise_stats()
+    """
+
+    _float_types: Set[torch.dtype] = {
+        torch.float16,
+        torch.bfloat16,
+        torch.float32,
+        torch.float64,
+    }
+    _no_fallback_kernel: Set[torch._ops._OpNamespace] = set()
+    fake_mode: FakeTensorMode
+
+    def __init__(self) -> None:
+        super().__init__()
+        self._estimate: Callable
+        self._estimate_mode_type: str
+        self._mod_tracker = ModTracker()
+        self.mod_runtimes: Dict[str, Dict[str, float]] = defaultdict(
+            lambda: defaultdict(lambda: 0.0)
+        )
+        self.mod_fw_pre_order: List[str] = []
+        self.mod_bw_pre_order: List[str] = []
+        self.mod_fw_post_order: List[str] = []
+        self.mod_bw_post_order: List[str] = []
+        self.total_runtime: float = 0.0
+
+    # Adapted from: https://github.com/pytorch/pytorch/blob/9b902b3ee3bd608a19543362b66bf06c373dd374/torch/_subclasses/fake_tensor.py#L1969  # noqa: PGH004,B950
+    # NB: returns fake tensors
+    @classmethod
+    def _maybe_run_and_benchmark_fallback_kernel(  # type: ignore[no-untyped-def]
+        cls,
+        func,
+        args,
+        kwargs,
+        orig_not_implemented_exception,
+    ):
+        """
+        Runs and benchmarks a fallback kernel for a given function.
+
+        Args:
+            func (Callable): The function to benchmark.
+            args (Tuple): The arguments to pass to the function.
+            kwargs (Dict[str, Any]): The keyword arguments to pass to the function.
+            orig_not_implemented_exception (Exception): The original exception to raise if the fallback kernel
+                is not implemented.
+
+        Returns:
+            Tuple[Any, float]: A tuple containing the result of the function and
+                the mean operation time in milliseconds.
+        """
+        # these should all be supported, just to be safe
+        # avoid fallback for operators which inplace modify metadata
+        # because the input fake tensors would be umodified
+        if torch.Tag.inplace_view in func.tags:  # type: ignore[attr-defined]
+            raise orig_not_implemented_exception
+
+        inp_impls = {}
+        flat_args, args_spec = pytree.tree_flatten((args, kwargs))
+        # Don't use in_kernel_invocation_manager(fake_mode) as we want to do
+        # REAL compute (not with meta device)
+        with no_dispatch():
+
+            def to_real_tensor(e):  # type: ignore[no-untyped-def]
+                if cls.fake_mode.is_our_fake(e):
+                    if e.dtype in cls._float_types:
+                        out = torch.rand_like(e, device=e.fake_device)
+                    else:
+                        out = torch.ones_like(e, device=e.fake_device)
+                    if e.is_sparse:
+                        out._coalesced_(e.is_coalesced())
+                    inp_impls[id(out)] = e
+                    return out
+                return e
+
+            flat_args = [to_real_tensor(a) for a in flat_args]
+            args, kwargs = pytree.tree_unflatten(flat_args, args_spec)
+            r = func(*args, **kwargs)
+            warmup_iters, actual_iters = 2, 3
+            for _ in range(warmup_iters):
+                func(*args, **kwargs)
+            start_event = torch.cuda.Event(enable_timing=True)
+            end_event = torch.cuda.Event(enable_timing=True)
+            start_event.record(torch.cuda.current_stream())
+            for _ in range(actual_iters):
+                func(*args, **kwargs)
+            end_event.record(torch.cuda.current_stream())
+            torch.cuda.synchronize()
+            cuda_time = start_event.elapsed_time(end_event)
+            mean_op_time = cuda_time / actual_iters
+
+        storages = set()
+
+        for e in flat_args:
+            if isinstance(e, torch.Tensor):
+                if not e.is_sparse:
+                    storages.add(e._typed_storage()._cdata)
+
+        # TODO: also check metadata change on inputs
+        # proper aliasing/metadata relationship between outputs and inputs will
+        # not be set up, bc of conversion to device, unless we can reuse an
+        # input impl
+
+        def map_out(e):  # type: ignore[no-untyped-def]
+            if id(e) not in inp_impls and (
+                isinstance(e, torch.Tensor)
+                and not e.is_sparse
+                and e._typed_storage()._cdata in storages
+            ):
+                raise orig_not_implemented_exception
+
+            if isinstance(e, torch.Tensor):
+                if id(e) in inp_impls:
+                    return inp_impls[id(e)]
+                else:
+                    return cls.fake_mode.fake_tensor_converter.from_real_tensor(
+                        cls.fake_mode, e
+                    )
+            else:
+                return e
+
+        return (pytree.tree_map(map_out, r), mean_op_time)
+
+    @classmethod
+    def _benchmark_estimate(cls, func, args, kwargs) -> Tuple[Any, float]:  # type: ignore[no-untyped-def]
+        """
+        Estimates the runtime of a function using benchmarking.
+
+        Args:
+            func: The function to estimate.
+            args: The arguments to pass to the function.
+            kwargs: The keyword arguments to pass to the function.
+            res: The result of the function.
+
+        Returns:
+            Tuple[Any, float]: A tuple containing the result of the function and
+                the mean operation time in milliseconds.
+        """
+        assert isinstance(
+            cls.fake_mode, FakeTensorMode
+        ), "Initialize/Assign FakeTensorMode before using this function"
+        mean_op_time = 0.0
+        if func._overloadpacket not in _VIEW_OPS:
+            try:
+                res, mean_op_time = cls._maybe_run_and_benchmark_fallback_kernel(
+                    func,
+                    args,
+                    kwargs,
+                    NotImplementedError,
+                )
+                return (res, mean_op_time)
+            except NotImplementedError:
+                cls._no_fallback_kernel.add(func._overloadpacket)
+        res = func(*args, **kwargs or {})
+        return (res, mean_op_time)
+
+    # Adapted from: https://github.com/pytorch/pytorch/blob/9b902b3ee3bd608a19543362b66bf06c373dd374/torch/_inductor/scheduler.py#L589  # noqa: PGH004,B950
+    @classmethod
+    def _roofline_estimate(cls, func, args, kwargs) -> Tuple[Any, float]:  # type: ignore[no-untyped-def]
+        """
+        Estimates the runtime of a function using a roofline cost model.
+
+        Args:
+            func: The function to estimate.
+            args: The arguments to pass to the function.
+            kwargs: The keyword arguments to pass to the function.
+            out: The output of the function.
+
+        Returns:
+            Tuple[Any, float]: A tuple containing the result of the function and
+                the mean operation time in milliseconds.
+        """
+        assert (
+            torch.cuda.is_available()
+        ), "Roofline estimation needs to access CUDA capabilities to make estimations"
+
+        def get_num_bytes(t: torch.Tensor) -> int:
+            """
+            Calculates the memory consumption of a tensor.
+
+            Args:
+                t (torch.Tensor): The input tensor.
+
+            Returns:
+                int: The memory consumption of the tensor in bytes.
+            """
+            num_bytes = t.untyped_storage().nbytes()
+            mem_consumed = (
+                math.ceil(num_bytes / _PYTORCH_MIN_ALLOCATE) * _PYTORCH_MIN_ALLOCATE
+            )
+            return mem_consumed
+
+        def get_compute_time(func_packet, args, kwargs, out, out_dtypes) -> float:  # type: ignore[no-untyped-def]
+            """
+            Estimates the compute time of an aten operator.
+
+            Args:
+                func_packet: The operator overload packet.
+                args: The arguments to the operator.
+                kwargs: The keyword arguments to the operator.
+                out: The output of the operator.
+                out_dtypes: The output data types.
+
+            Returns:
+                float: The estimated compute time in nanoseconds.
+            """
+            if func_packet in flop_registry:
+                assert (
+                    len(out_dtypes) == 1
+                ), f"Only support single out dtype got {out_dtypes} for {func_packet}"
+                dtype = out_dtypes.pop()
+                # This actually gives peta-FLOPs/s hence multiply by 1e15 to get the FLOPs/s
+                peak_gpu_flops = get_device_tflops(dtype) * 1e15
+                # We can expect to achieve 75% of theoretical peak flops
+                factor = 0.75
+                peak_empirical_flops = factor * peak_gpu_flops
+                flop_count_func = flop_registry[func_packet]
+                # We divide by a factor of 2 to get the MACs (multiply and accumulate)
+                flop_count = flop_count_func(*args, **kwargs, out_val=out) / 2
+                # We multiply by 1e9 to get the time in nano seconds
+                compute_time = (flop_count / peak_empirical_flops) * 1e9
+                return compute_time
+            return 0.0
+
+        def get_transfer_time(flat_args_kwargs, flat_outs) -> float:  # type: ignore[no-untyped-def]
+            """
+            Estimates the memory transfer time of input and output tensors.
+
+            Args:
+                flat_args_kwargs (List[torch.Tensor]): The flat list of arguments and keyword arguments.
+                flat_outs (List[torch.Tensor]): The flat list of outputs.
+
+            Returns:
+                float: The estimated memory transfer time in nanoseconds.
+            """
+            gpu_memory_bandwidth = get_gpu_dram_gbps()
+            read_bytes = sum(
+                get_num_bytes(t)
+                for t in flat_args_kwargs
+                if isinstance(t, torch.Tensor)
+            )
+            write_bytes = sum(
+                get_num_bytes(t) for t in flat_outs if isinstance(t, torch.Tensor)
+            )
+            counted_bytes = read_bytes + write_bytes
+            # The GPU memory bandwidth is in GB/s so the transfer time is in nanoseconds
+            transfer_time = counted_bytes / gpu_memory_bandwidth
+            return transfer_time
+
+        # Roofline Cost Model Explanation
+
+        # The roofline cost model estimates the execution time of an operator based on
+        # the device's empirical maximum FLOPs/sec (pi) and device DRAM bandwidth (beta).
+
+        # Variables:
+        # - pi: Maximum empirical FLOPs/sec of the device
+        # - beta: Maximum empirical device DRAM bandwidth (bytes/sec) of the device
+        # - I: Arithmetic intensity of the operator (FLOPs/bytes)
+        # - op_flops: FLOPs required by the operator
+        # - op_bytes: Bytes transferred to and from DRAM for the operator
+
+        # Calculation Steps:
+        # 1. Calculate arithmetic intensity: I = op_flops / op_bytes
+        # 2. Calculate estimated FLOPs/sec: est_flops_sec = min(pi, beta * I)
+        # 3. Calculate estimated operator time: estimated_op_time = op_flops / est_flops_sec
+        #    This simplifies to: estimated_op_time = max(op_flops / pi, op_flops / (beta * I))
+        #    Further simplifying: estimated_op_time = max(op_flops / pi, op_bytes / beta)
+
+        # Simplified Formulas:
+        # - compute_time = op_flops / pi
+        # - transfer_time = op_bytes / beta
+        # - estimated_op_time = max(compute_time, transfer_time)
+
+        kwargs = kwargs if kwargs else {}
+        out = func(*args, **kwargs)
+        op_time = 0.0
+        func_packet = func._overloadpacket
+        if func_packet not in _IGNORE_OPS:
+            flat_args_kwargs, args_spec = pytree.tree_flatten((args, kwargs))
+            flat_outs, out_spec = pytree.tree_flatten(out)
+            transfer_time = get_transfer_time(flat_args_kwargs, flat_outs)
+
+            out_dtypes = {
+                t.dtype
+                for t in flat_outs
+                if isinstance(t, torch.Tensor) and t.dtype in cls._float_types
+            }
+
+            args, kwargs = pytree.tree_unflatten(flat_args_kwargs, args_spec)
+            out = pytree.tree_unflatten(flat_outs, out_spec)
+
+            compute_time = get_compute_time(func_packet, args, kwargs, out, out_dtypes)
+            # We get the estimated time as the max of the transfer time and
+            # compute time. We divide by 1e6 to get the time in ms
+            op_time = max(transfer_time, compute_time) / 1e6
+
+        return (out, op_time)
+
+    def display_modulewise_stats(self, depth: int = 2) -> None:
+        """
+        Displays module-wise statistics collected by ``RuntimeEstimator``.
+
+        Prints the pre-forward and pre-backward execution orders.
+        Displays the module-wise forward and backward runtimes in milliseconds.
+
+        Args:
+            depth (int): The maximum depth of module hierarchy to display (default to 2).
+        """
+        print("Pre-Forward Execution Order: ")
+        for mod_fqn in self.mod_fw_pre_order:
+            mod_depth = mod_fqn.count(".") + 1
+            if mod_depth > depth:
+                continue
+            print(mod_fqn)
+        print("Pre-Backward Execution Order: ")
+        for mod_fqn in self.mod_bw_pre_order:
+            mod_depth = mod_fqn.count(".") + 1
+            if mod_depth > depth:
+                continue
+            print(mod_fqn)
+        for mod_fqn, runtimes in self.mod_runtimes.items():
+            mod_depth = mod_fqn.count(".") + 1
+            if mod_depth > depth:
+                continue
+            print(
+                f"{mod_fqn} fw: {runtimes.get('fw', 0.0):.3f}ms bw: {runtimes.get('bw', 0.0):.3f}ms"
+            )
+
+    def __torch_dispatch__(self, func, types, args=..., kwargs=None):  # type: ignore[no-untyped-def]
+        # TODO: @sanketpurandare: Flatten tensors by desugaring the tensor subclasses
+        # TODO: @sanketpurandare: Add logic for incorporating communication time
+        res, op_time = self._estimate(func, args, kwargs)
+        for par in self._mod_tracker.parents:
+            if self._mod_tracker.is_bw:
+                self.mod_runtimes[par]["bw"] += op_time
+            else:
+                self.mod_runtimes[par]["fw"] += op_time
+        self.total_runtime += op_time
+        return res
+
+    def __call__(self, estimate_mode_type: str) -> Self:
+        """
+        Sets the estimate mode type.
+
+        Currently supported modes:
+            - "operator-level-benchmark": Estimates runtime using operator benchmarking.
+            - "operator-level-cost-model": Estimates runtime using roofline cost model.
+
+        Args:
+            estimate_mode_type (str): The type of estimate mode to use.
+
+        Returns:
+            RuntimeEstimator: The runtime estimator instance.
+
+        Raises:
+            NotImplementedError: If the estimate mode type is not supported.
+        """
+        if estimate_mode_type == "operator-level-benchmark":
+            self._estimate = RuntimeEstimator._benchmark_estimate
+        elif estimate_mode_type == "operator-level-cost-model":
+            self._estimate = RuntimeEstimator._roofline_estimate
+        else:
+            raise NotImplementedError(
+                f"estimate_mode_type {estimate_mode_type} not supported"
+            )
+        self._estimate_mode_type = estimate_mode_type
+        return self
+
+    def __enter__(self) -> Self:
+        fake_mode = active_fake_mode()
+        assert isinstance(
+            fake_mode, FakeTensorMode
+        ), "No FakeTensorMode found, designed to used under FakeTensorMode"
+        RuntimeEstimator.fake_mode = fake_mode
+        self.total_runtime = 0.0
+        self.mod_runtimes = defaultdict(lambda: defaultdict(lambda: 0.0))
+        self.mod_fw_pre_order.clear()
+        self.mod_bw_pre_order.clear()
+        self.mod_fw_post_order.clear()
+        self.mod_bw_post_order.clear()
+        self._mod_tracker.register_user_hooks(
+            pre_fw_hook=lambda mod, inp: self.mod_fw_pre_order.append(
+                self._mod_tracker.get_known_fqn(mod)
+            ),
+            pre_bw_hook=lambda mod, g_out: self.mod_bw_pre_order.append(
+                self._mod_tracker.get_known_fqn(mod)
+            ),
+            post_fw_hook=lambda mod, inp, out: self.mod_fw_post_order.append(
+                self._mod_tracker.get_known_fqn(mod)
+            ),
+            post_bw_hook=lambda mod, g_inp: self.mod_bw_post_order.append(
+                self._mod_tracker.get_known_fqn(mod)
+            ),
+        )
+        self._mod_tracker.__enter__()
+        super().__enter__()
+        return self
+
+    def __exit__(self, *args: Any) -> None:
+        print(
+            f"Estimated ({self._estimate_mode_type})"
+            f"total_time: {self.total_runtime:.3f} ms"
+        )
+        if len(self._no_fallback_kernel) > 0:
+            print("no_fallback_kernel: ", list(self._no_fallback_kernel))
+        super().__exit__(*args)
+        self._mod_tracker.clear_user_hooks()
+        self._mod_tracker.__exit__()
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..06c814295699405de9a8f8cf7f6a861b07b63a05
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/__init__.py
@@ -0,0 +1 @@
+from .join import Join, Joinable, JoinHook
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e91ec50430b6c9b3b6ee9cca187d1bfc9d8f0110
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/__pycache__/join.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/__pycache__/join.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fb01f1732b73b3cfa406d3b11ed0929a26daf6df
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/__pycache__/join.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_checkpoint/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_checkpoint/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_checkpoint/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_checkpoint/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..67029764f370a3940639d654edac4ace17d9b4ae
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_checkpoint/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_checkpoint/__pycache__/checkpoint_wrapper.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_checkpoint/__pycache__/checkpoint_wrapper.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..35d673f3309f4c56f44a4bd47cd45f27486cf501
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_checkpoint/__pycache__/checkpoint_wrapper.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_checkpoint/checkpoint_wrapper.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_checkpoint/checkpoint_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..af550d7bf150b1da219d68a7fc1a1073c118e027
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_checkpoint/checkpoint_wrapper.py
@@ -0,0 +1,323 @@
+# mypy: allow-untyped-defs
+import warnings
+from abc import ABC, abstractmethod
+from enum import auto, Enum
+from functools import partial
+from typing import Any, Callable, Dict, Iterator, Optional, Tuple
+
+import torch
+import torch.nn as nn
+from torch.autograd.graph import save_on_cpu
+from torch.distributed.utils import _pack_kwargs, _replace_by_prefix, _unpack_kwargs
+from torch.utils.checkpoint import checkpoint as torch_utils_checkpoint
+
+
+_CHECKPOINT_WRAPPED_MODULE = "_checkpoint_wrapped_module"
+_CHECKPOINT_PREFIX = _CHECKPOINT_WRAPPED_MODULE + "."
+
+
+class CheckpointImpl(Enum):
+    REENTRANT = auto()
+    NO_REENTRANT = auto()
+
+
+class ActivationWrapper(torch.nn.Module, ABC):
+    """
+    Base class for Activation Checkpoint and Activation Offload.
+
+    Not meant to be instantiated directly.
+    """
+
+    def __init__(self, mod):
+        super().__init__()
+        self._checkpoint_wrapped_module = mod
+        # state_dict post hook to remove prefix to allow loading into a
+        # non-checkpoint wrapped module.
+        self._register_state_dict_hook(self._post_state_dict_hook)
+        # load_state_dict pre-hook to allow loading back into
+        # checkpoint-wrapped module.
+        self.register_load_state_dict_pre_hook(self._pre_load_state_dict_hook)
+
+    @abstractmethod
+    def forward(self, *args, **kwargs):
+        raise ValueError("Subclasses should implement forward().")
+
+    def __getattr__(self, name: str) -> Any:
+        """Forward missing attributes to wrapped module."""
+        try:
+            return super().__getattr__(name)  # defer to nn.Module's logic
+        except AttributeError:
+            return getattr(self._checkpoint_wrapped_module, name)
+
+    def __getitem__(self, key: int) -> Any:
+        """Forward indexing calls in case the module is a nn.Sequential."""
+        return self._checkpoint_wrapped_module.__getitem__(key)  # type: ignore[operator]
+
+    def named_parameters(
+        self,
+        *args,
+        **kwargs,
+    ) -> Iterator[Tuple[str, torch.nn.Parameter]]:
+        """
+        Override :meth:`named_parameters()` to intercept parameter names.
+
+        remove all occurrences of ``_CHECKPOINT_PREFIX``.
+        """
+        for param_name, param in super().named_parameters(*args, **kwargs):
+            yield param_name.replace(_CHECKPOINT_PREFIX, ""), param
+
+    @staticmethod
+    def _post_state_dict_hook(
+        module: nn.Module,
+        state_dict: Dict[str, Any],
+        prefix: str,
+        *args: Any,
+    ) -> Dict[str, Any]:
+        """
+        _post_state_dict_hook() is called after the state_dict() of this FSDP module is executed.
+
+        For ``checkpoint_wrapper``, it will strip checkpoint-wrapped module prefix,
+        so that this module can be loaded into non-checkpointed modules.
+        It would still be able to be loaded into checkpoint-wrapped modules as this class,
+        adds the prefix back before loading the state_dict.
+        """
+        _replace_by_prefix(state_dict, f"{prefix}{_CHECKPOINT_PREFIX}", prefix)
+        return state_dict
+
+    @staticmethod
+    def _pre_load_state_dict_hook(
+        module: nn.Module,
+        state_dict: Dict[str, Any],
+        prefix: str,
+        *args: Any,
+    ) -> None:
+        """
+        ``_pre_state_dict_hook` is called before ``self._load_from_state_dict()`` is called.
+
+        For ``checkpoint_wrapper``, it will add back the module
+        prefix so that non-checkpointed modules can be loaded into
+        checkpoint_wrapper modules properly.
+        """
+        _replace_by_prefix(state_dict, prefix, prefix + f"{_CHECKPOINT_PREFIX}")
+
+
+class OffloadWrapper(ActivationWrapper):
+    def __init__(self, mod):
+        super().__init__(mod)
+
+    def forward(self, *args, **kwargs):
+        with save_on_cpu(pin_memory=True):
+            return self._checkpoint_wrapped_module(*args, **kwargs)
+
+
+class CheckpointWrapper(ActivationWrapper):
+    """
+    An ``nn.Module`` that wraps another ``nn.Module`` with checkpointing.
+
+    Note that this module is not meant to be used directly but instead,
+    it is to be used through the ``checkpoint_wrapper`` function.
+    """
+
+    def __init__(
+        self,
+        mod: torch.nn.Module,
+        checkpoint_impl: CheckpointImpl = CheckpointImpl.NO_REENTRANT,
+        checkpoint_fn=None,
+        **checkpoint_fn_kwargs,
+    ):
+        super().__init__(mod)
+        self.checkpoint_impl = checkpoint_impl
+        if checkpoint_fn is None:
+            # use torch.utils.checkpoint
+            self.checkpoint_fn = partial(
+                torch_utils_checkpoint,
+                use_reentrant=(self.checkpoint_impl == CheckpointImpl.REENTRANT),
+                **checkpoint_fn_kwargs,
+            )
+        else:
+            # Construct user-specified checkpoint function.
+            self.checkpoint_fn = partial(
+                checkpoint_fn,
+                **checkpoint_fn_kwargs,
+            )
+
+    def forward(self, *args, **kwargs):
+        # Support keyword arguments for reentrant checkpoint. Note that this
+        # only works if user has specified self.checkpoint_impl and is not
+        # using their own custom checkpoint_fn.
+        if self.checkpoint_impl == CheckpointImpl.REENTRANT and kwargs != {}:
+            # Pack the args and kwargs
+            flat_args, kwarg_keys = _pack_kwargs(*args, **kwargs)
+
+            # Function that only takes (packed) args, but can unpack them
+            # into the original args and kwargs for the checkpointed
+            # function, and runs that function.
+            def my_function(*inputs):
+                # unpack back into args and kwargs
+                unpacked_args, unpacked_kwargs = _unpack_kwargs(inputs, kwarg_keys)
+                # run original module
+                return self._checkpoint_wrapped_module(
+                    *unpacked_args, **unpacked_kwargs
+                )
+
+            # Pass the function that only takes packed args into reentrant
+            # checkpoint API.
+            return self.checkpoint_fn(  # type: ignore[misc]
+                my_function,
+                *flat_args,
+            )
+        else:
+            return self.checkpoint_fn(  # type: ignore[misc]
+                self._checkpoint_wrapped_module, *args, **kwargs
+            )
+
+
+def offload_wrapper(module: torch.nn.Module) -> torch.nn.Module:
+    """
+    Wrap a module for activation offloading to CPU.
+
+    Offloads intermediate activations to the CPU for modules wrapped with this function.
+    Wrappers with activation offload can be composed with ones that do recomputation-based
+    checkpoint to trade off increased compute versus increased CPU
+    memory usage and additional H2D transfers.
+
+    Usage::
+        offloaded_module = offload_wrapper(module)
+        outputs = checkpointed_module(inputs)
+    Args:
+        module (nn.Module):
+            The module to be wrapped
+    Returns:
+        (nn.Module):
+            Wrapped module
+    """
+    return OffloadWrapper(module)
+
+
+def checkpoint_wrapper(
+    module: torch.nn.Module,
+    checkpoint_impl: CheckpointImpl = CheckpointImpl.NO_REENTRANT,
+    checkpoint_fn=None,
+    **checkpoint_fn_kwargs,
+) -> torch.nn.Module:
+    """
+    Wrap a module for activation checkpointing.
+
+    If the module is wrapped with this function, all subsequent calls to the module will,
+    automatically perform checkpointing without the user having to explicitly call ``checkpoint`` function.
+
+    Usage::
+        checkpointed_module = checkpoint_wrapper(module)
+        outputs = checkpointed_module(inputs)
+    Args:
+        module (nn.Module):
+            The module to be wrapped
+        checkpoint_impl (Optional[CheckpointImpl]):
+            The checkpointing implementation to use. Note that this will only
+            be passed into the ``torch.utils.checkpoint.checkpoint``
+            implementation, and is ignored if a custom ``checkpoint_fn`` is
+            specified. Note that for implementations using reentrant checkpoint
+            from ``torch.utils.checkpoint``, keyword arguments will only be
+            supported if ``checkpoint_impl`` is passed as ``CheckpointImpl.REENTRANT`.
+        checkpoint_fn (Optional[Callable]):
+            Functional checkpoint implementation to use. If this is specified,
+            it will be used over the default ``torch.utils.checkpoint.checkpoint``
+            implementation and the `checkpoint_impl` argument will be ignored.
+        **checkpoint_fn_kwargs: (Dict[str, Any]): Keyword arguments to pass into `checkpoint_fn`.
+
+    Returns:
+        (nn.Module):
+            Wrapped module
+    """
+
+    if checkpoint_impl == CheckpointImpl.REENTRANT:
+        warnings.warn(
+            f"Please specify {CheckpointImpl.NO_REENTRANT} as "
+            f"{CheckpointImpl.REENTRANT} will soon be removed as "
+            "the default and eventually deprecated.",
+            FutureWarning,
+            stacklevel=2,
+        )
+    return CheckpointWrapper(
+        module,
+        checkpoint_impl,
+        checkpoint_fn,
+        **checkpoint_fn_kwargs,
+    )
+
+
+def apply_activation_checkpointing(
+    model,
+    checkpoint_wrapper_fn=checkpoint_wrapper,
+    check_fn=lambda _: True,
+    auto_wrap_policy: Optional[Callable[[nn.Module, bool, int], bool]] = None,
+):
+    """
+    Apply :func:`checkpoint_wrapper` to modules within `model` based on a user-defined configuration.
+
+    For each module within `model`, the `check_fn` is used to decide
+    whether `module` should be wrapped with :func:`checkpoint_wrapper` or not.
+
+    Note::
+        This function modifies `model` in place and replaces appropriate layers with
+        their checkpoint-wrapped modules.
+    Note::
+        This function will not wrap the overall root module. If this is needed, please directly use
+        :func:`checkpoint_wrapper` or :func:`offload_wrapper`.
+    Usage::
+        model = nn.Sequential(
+            nn.Linear(10, 10), nn.Linear(10, 10), nn.Linear(10, 10)
+        )
+        check_fn = lambda l: isinstance(l, nn.Linear)
+        # checkpoint activations
+        apply_activation_checkpointing(model, checkpoint_wrapper_fn=checkpoint_wrapper, check_fn=check_fn)
+        # Or offload activations to CPU
+        apply_activation_checkpointing(model, checkpoint_wrapper_fn=offload_wrapper, check_fn=check_fn)
+    Args:
+        model (nn.Module):
+            The model whose submodules should be wrapped with activation checkpointing.
+        checkpoint_wrapper_fn (Optional[Callable[nn.Module]])
+            A ``Callable`` which will wrap modules
+        check_fn (Optional[Callable[nn.Module, nn.Module]])
+            A lambda function which will be passed each child submodule of ``model`` and returns
+            ``True`` or ``False`` depending on whether the submodule should be wrapped.
+        auto_wrap_policy (Optional[Callable[[nn.Module, bool, int], bool]]): A policy to wrap model's
+            submodules with AC. Note that if this is specified, it takes precedence over ``check_fn``.
+    Returns: None (`model` is modified inplace)
+    """
+    # TODO: Importing inside function to avoid circular import issue between FSDP and
+    # checkpoint_wrapper. This can be resolved once wrap() APIs are decoupled from FSDP code.
+    from torch.distributed.fsdp._wrap_utils import _construct_wrap_fn, _post_order_apply
+    from torch.distributed.fsdp.wrap import (
+        _Policy,
+        _recursive_wrap,
+        lambda_auto_wrap_policy,
+    )
+
+    policy = (
+        auto_wrap_policy
+        if auto_wrap_policy is not None
+        else partial(lambda_auto_wrap_policy, lambda_fn=check_fn)
+    )
+    if not callable(policy):
+        if not isinstance(policy, _Policy):
+            raise ValueError(
+                f"Expected {policy} to be callable or be a pre-defined wrap policy"
+            )
+        target_module_to_kwargs = policy._run_policy(
+            model, ignored_modules=set(), root_kwargs={}
+        )
+        wrap_fn = _construct_wrap_fn(
+            model, target_module_to_kwargs, checkpoint_wrapper_fn
+        )
+        _post_order_apply(model, wrap_fn)
+        return
+
+    _recursive_wrap(
+        module=model,
+        auto_wrap_policy=policy,  # type: ignore[arg-type]
+        wrapper_cls=checkpoint_wrapper_fn,
+        ignored_modules=set(),
+        ignored_params=set(),
+        only_wrap_children=True,
+    )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_comm_hooks/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_comm_hooks/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b57a075ad729d0ae3004dc15585250b04810f43
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_comm_hooks/__init__.py
@@ -0,0 +1,7 @@
+from . import default_hooks as default
+
+
+LOW_PRECISION_HOOKS = [
+    default.fp16_compress_hook,
+    default.bf16_compress_hook,
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_comm_hooks/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_comm_hooks/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4d2dd17c0b637d2bce97d2448d733b4a3f2edf98
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_comm_hooks/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_comm_hooks/__pycache__/default_hooks.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_comm_hooks/__pycache__/default_hooks.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9034f59c0204c3abd09776dd06d5626d3a63f83a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_comm_hooks/__pycache__/default_hooks.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_comm_hooks/default_hooks.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_comm_hooks/default_hooks.py
new file mode 100644
index 0000000000000000000000000000000000000000..0acafd6868d3bb68addba53995eda6334dbcad1a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_comm_hooks/default_hooks.py
@@ -0,0 +1,192 @@
+# mypy: allow-untyped-defs
+import functools
+from typing import Optional
+
+import torch
+import torch.distributed as dist
+
+
+class DefaultState:
+    r"""
+    Stores state needed to perform the default communication algorithm within a communication hook.
+
+    Args:
+        process_group (ProcessGroup): The process group to be used.
+    """
+
+    __slots__ = [
+        "process_group",
+        "world_size",
+        "gradient_predivide_factor",
+        "gradient_postdivide_factor",
+    ]
+
+    def __init__(self, process_group: dist.ProcessGroup):
+        if process_group is None:
+            raise ValueError(f"Expected to pass in an explicit ProcessGroup to {self}.")
+        self.process_group = process_group
+        self.world_size = dist.get_world_size(process_group)
+        # Setting two factors `self.gradient_predivide_factor`
+        # and `self.gradient_postdivide_factor` to avoid underflow and overflow
+        self.gradient_predivide_factor = self._get_gradient_predivide_factor(
+            self.world_size
+        )
+        self.gradient_postdivide_factor = (
+            self.world_size / self.gradient_predivide_factor
+        )
+
+    @staticmethod
+    def _get_gradient_predivide_factor(world_size: int) -> float:
+        factor: int = 1
+        while world_size % factor == 0 and world_size / factor > factor:
+            factor *= 2
+        return float(factor)
+
+
+class LowPrecisionState(DefaultState):
+    r"""
+    Stores state needed to perform gradient communication in a lower precision within a communication hook.
+
+    Communication hook will cast gradients back to the original
+    parameter precision specified by ``parameter_type`` (default: torch.float32).
+    Builds on top of the :class:`DefaultState`.
+
+    Args:
+        parameter_type (torch.dtype): The precision of model's parameters.
+        Required for a hook to cast gradients back to a parameter's precision.
+    """
+
+    __slots__ = [
+        "parameter_type",
+    ]
+
+    def __init__(
+        self,
+        process_group,
+        parameter_type=torch.float32,
+    ):
+        super().__init__(process_group)
+        self.parameter_type = parameter_type
+
+
+def _decompress(state: LowPrecisionState, grad: torch.Tensor):
+    """
+    Casts gradients back to full parameter precision so that further computation happens in full precision.
+    """
+    orig_grad_data = grad.data
+    grad.data = grad.data.to(state.parameter_type)
+    device_type = ""
+    try:
+        if grad.device.type == "privateuse1":
+            device_type = torch._C._get_privateuse1_backend_name()
+        else:
+            device_type = grad.device.type
+        backend = getattr(torch, device_type)
+    except AttributeError as e:
+        raise AttributeError(
+            f"Device {grad.device}  does not have a \
+                corresponding backend registered as 'torch.device_type'."
+        ) from e
+
+    # Don't let this memory get reused until after the transfer.
+    orig_grad_data.record_stream(backend.current_stream())  # type: ignore[arg-type]
+
+
+def allreduce_hook(state: DefaultState, grad: torch.Tensor):
+    r"""
+    Implement the  FSDP communication hook for ``all_reduce`` algorithm and a necessary pre- and post-division of gradients.
+
+    Args:
+        state (DefaultState): State information, configures pre- and post-division factors.
+        grad (torch.Tensor): A gradient for the local batch that needs to be communicated across ranks.
+    """
+    # Average grad by pre-division factor. Together pre- and post-division factors
+    # lead to an overall averaging by world_size, required for consistency with PyTorch DDP.
+    # This is a two-step process to avoid potential underflow and overflow.
+    if state.gradient_predivide_factor > 1:
+        grad.div_(state.gradient_predivide_factor)
+    dist.all_reduce(grad, group=state.process_group)
+    # Average grad by post-division factor.
+    if state.gradient_postdivide_factor > 1:
+        grad.div_(state.gradient_postdivide_factor)
+
+
+def reduce_scatter_hook(state: DefaultState, grad: torch.Tensor, output: torch.Tensor):
+    r"""
+    Implement the  FSDP communication hook for ``reduce_scatter`` algorithm.
+
+    For sharded FSDP strategies and a necessary pre- and post-division of gradients.
+
+    Args:
+        state (DefaultState): State information, configures pre- and post-division factors.
+        grad (torch.Tensor): An unsharded gradient for the local batch that needs to be
+        communicated across ranks.
+        output (torch.Tensor): Stores a single shard of the gradient after ``reduce_scatter``.
+    """
+    # Average grad by pre-division factor.
+    if state.gradient_predivide_factor > 1:
+        grad.div_(state.gradient_predivide_factor)
+    dist.reduce_scatter_tensor(output, grad, group=state.process_group)
+    # Average grad's shard by post-division factor.
+    if state.gradient_postdivide_factor > 1:
+        output.div_(state.gradient_postdivide_factor)
+
+
+def _low_precision_hook(
+    prec: torch.dtype,
+    state: LowPrecisionState,
+    grad: torch.Tensor,
+    output: torch.Tensor,
+):
+    if grad.dtype != prec:
+        grad.data = grad.data.to(prec)
+    if output is not None:
+        if output.dtype != prec:
+            output.data = output.data.to(prec)
+        reduce_scatter_hook(state, grad, output)
+        _decompress(state, output)
+    else:
+        allreduce_hook(state, grad)
+        _decompress(state, grad)
+
+
+def fp16_compress_hook(
+    state: LowPrecisionState, grad: torch.Tensor, output: Optional[torch.Tensor] = None
+):
+    r"""
+    Implement FSDP communication hook for a simple gradient compression approach.
+    Casts ``grad`` to half-precision floating-point format (``torch.float16``).
+
+    It also averages gradients by ``world_size`` in two steps: first it pre-divides gradients by a
+    ``state.gradient_predivide_factor``, and after a communication step (``all_reduce`` or ``reduce_scatter``)
+    gradients are averaged by a ``state.gradient_postdivide_factor``.
+    Once post-division is done, compressed gradients are casted back to parameters' precision.
+
+    Args:
+        state (LowPrecisionState): State information, configures pre- and post-division factors, parameters' precision.
+        grad (torch.Tensor): A gradient for the local batch that needs to be communicated across ranks in a lower precision.
+        output (torch.Tensor): Stores a single shard of the gradient after ``reduce_scatter``.
+    """
+    fp16_hook = functools.partial(_low_precision_hook, torch.float16)
+    return fp16_hook(state, grad, output)
+
+
+def bf16_compress_hook(
+    state: LowPrecisionState, grad: torch.Tensor, output: Optional[torch.Tensor] = None
+):
+    r"""
+    Implement FSDP communication hook for a simple gradient compression approach .
+    Casts ``grad`` to half-precision floating-point format.
+
+    It also averages gradients by ``world_size`` in two steps: first it pre-divides gradients by a
+    ``state.gradient_predivide_factor``, and after a communication step (``all_reduce`` or ``reduce_scatter``)
+    gradients are averaged by a ``state.gradient_postdivide_factor``.
+    Once post-division is done, compressed gradients are casted back to parameters' precision.
+
+    Args:
+        state (LowPrecisionState): State information, configures pre- and post-division factors, parameters' precision.
+        grad (torch.Tensor): A gradient for the local batch that needs to be communicated across ranks in a lower precision.
+        output (torch.Tensor): Stores a single shard of the gradient after ``reduce_scatter``.
+    """
+    bf16_hook = functools.partial(_low_precision_hook, torch.bfloat16)
+    return bf16_hook(state, grad, output)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_optimizer_overlap/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_optimizer_overlap/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba62bfb68f42a136dcfa27bcf378d3892cf6751a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_optimizer_overlap/__init__.py
@@ -0,0 +1 @@
+from .optimizer_overlap import _as_overlapped_optim
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_optimizer_overlap/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_optimizer_overlap/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5fad06883b07c407b10802cf9a2d8dc238c6b908
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_optimizer_overlap/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_optimizer_overlap/__pycache__/optimizer_overlap.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_optimizer_overlap/__pycache__/optimizer_overlap.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..952b7534876600f66586f912f9f41e1e57e73f62
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_optimizer_overlap/__pycache__/optimizer_overlap.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_optimizer_overlap/optimizer_overlap.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_optimizer_overlap/optimizer_overlap.py
new file mode 100644
index 0000000000000000000000000000000000000000..ada39ca24d9705f7aa1018fd83d43ed11ebe9bd9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_optimizer_overlap/optimizer_overlap.py
@@ -0,0 +1,97 @@
+# mypy: allow-untyped-defs
+import inspect
+from abc import ABC, abstractmethod
+from typing import Dict, Type
+
+from torch.distributed.algorithms.ddp_comm_hooks.default_hooks import allreduce_hook
+from torch.distributed.algorithms.ddp_comm_hooks.optimizer_overlap_hooks import (
+    _hook_then_optimizer,
+    _OptimizerHookState,
+)
+from torch.distributed.fsdp import FullyShardedDataParallel
+from torch.distributed.optim import as_functional_optim
+from torch.nn.parallel import DistributedDataParallel
+from torch.optim import Optimizer
+
+
+# Contains the mappings between the regular and overlapped optimizer types.
+_registered_overlapped_optims: Dict[Type, Type] = {}
+
+
+def register_overlapped(optim_cls):
+    def decorator(target_overlapped_optim_cls):
+        if target_overlapped_optim_cls in _registered_overlapped_optims:
+            raise ValueError(
+                f"{target_overlapped_optim_cls} already registered with optim_cls "
+                f"{_registered_overlapped_optims[optim_cls]} {optim_cls}, trying to"
+                f"re-register it for {optim_cls} is not supported."
+            )
+        _registered_overlapped_optims[optim_cls] = target_overlapped_optim_cls
+        return target_overlapped_optim_cls
+
+    return decorator
+
+
+class OverlappedOptimizer(ABC):
+    def __init__(self, optim_cls: Type) -> None:
+        """
+        Initialize the OverlappedOptimizer.
+
+        Overlappedoptimizer is a base class that child classes can implement to
+        specify how different optimizers will register themselves with DDP.
+        """
+        self.optim_cls = optim_cls
+
+    @abstractmethod
+    def register_ddp(self, ddp: DistributedDataParallel) -> None:
+        """Registers the overlapped optimizer with DDP."""
+        raise NotImplementedError(
+            f"{self.__class__.__name__} does not support overlapped DDP."
+        )
+
+    @abstractmethod
+    def register_fsdp(self, fsdp: FullyShardedDataParallel) -> None:
+        """Registers the overlapped optimizer with FSDP."""
+        raise NotImplementedError(
+            f"{self.__class__.__name__} does not support overlapped FSDP."
+        )
+
+
+@register_overlapped(Optimizer)
+class _OverlappedStandardOptimizer(OverlappedOptimizer):
+    """Overlaps a regular ``Optimizer``."""
+
+    def __init__(self, optim_cls: Type, params, *optim_args, **optim_kwargs) -> None:
+        super().__init__(optim_cls)
+        f_optim = as_functional_optim(self.optim_cls, *optim_args, **optim_kwargs)
+        self._opt_hook_state = _OptimizerHookState(f_optim, params)
+
+    def register_ddp(self, ddp_inst: DistributedDataParallel):
+        # NOTE: using a custom communication hook and fused optimizer is not
+        # yet supported.
+        ddp_inst.register_comm_hook(  # type: ignore[operator]
+            None,  # wrapped hook state
+            _hook_then_optimizer(allreduce_hook, self._opt_hook_state),
+        )
+
+    # TODO: register_fsdp once FSDP supports communication hook.
+    def register_fsdp(self, fsdp: FullyShardedDataParallel) -> None:
+        """Register the overlapped optimizer with FSDP."""
+        raise NotImplementedError(
+            f"{self.__class__.__name__} does not support overlapped FSDP."
+        )
+
+
+def _as_overlapped_optim(optim_cls: Type, params, *args, **kwargs):
+    """Return a new ``OverlappedOptimizer`` instance that supports ``optim_cls``."""
+    for clz in inspect.getmro(optim_cls):
+        try:
+            return _registered_overlapped_optims[clz](
+                optim_cls, params, *args, **kwargs
+            )
+        except KeyError:
+            pass
+
+    # Fallback to standard overlapped optimizer, which will raise errors if user
+    # is attempting to use an unsupported optimizer.
+    return _OverlappedStandardOptimizer(optim_cls, params, *args, **kwargs)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_quantization/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_quantization/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_quantization/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_quantization/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..73fa7c9b6de10a7085788757b3f7ac5902360cb0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_quantization/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_quantization/__pycache__/quantization.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_quantization/__pycache__/quantization.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..003b9180f86bc94aa296acee1de44fa02a7faaf8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_quantization/__pycache__/quantization.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_quantization/quantization.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_quantization/quantization.py
new file mode 100644
index 0000000000000000000000000000000000000000..a579a0a02feae930c3e0528dee1f951fb63b1d21
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/_quantization/quantization.py
@@ -0,0 +1,150 @@
+# mypy: allow-untyped-defs
+import functools
+from enum import Enum
+
+import torch
+import torch.distributed as dist
+
+
+TORCH_HALF_MIN = torch.finfo(torch.float16).min
+TORCH_HALF_MAX = torch.finfo(torch.float16).max
+
+
+class DQuantType(Enum):
+    """
+    Different quantization methods for auto_quantize API are identified here.
+
+    auto_quantize API currently supports fp16 and bfp16 methods.
+    """
+
+    FP16 = ("fp16",)
+    BFP16 = "bfp16"
+
+    def __str__(self) -> str:
+        return self.value
+
+
+def _fp32_to_fp16_with_clamp(tensor: torch.Tensor) -> torch.Tensor:
+    return torch.clamp(tensor, TORCH_HALF_MIN, TORCH_HALF_MAX).half()
+
+
+def _quantize_tensor(tensor, qtype):
+    if not isinstance(tensor, torch.Tensor):
+        raise RuntimeError(
+            f"_quantize_tensor expecting torch.Tensor as input but found {type(tensor)}"
+        )
+    if qtype == DQuantType.FP16:
+        return _fp32_to_fp16_with_clamp(tensor)
+    elif qtype == DQuantType.BFP16:
+        return torch.ops.quantization._FloatToBfloat16Quantized(tensor)
+    else:
+        raise RuntimeError(f"Quantization type {qtype} is not supported")
+
+
+def _quantize_tensor_list(tensor_list, qtype):
+    if not isinstance(tensor_list, list) or not all(
+        isinstance(p, torch.Tensor) for p in tensor_list
+    ):
+        raise RuntimeError(
+            f"_quantize_tensor_list expecting list of torch.Tensor as input but found {type(tensor_list)}"
+        )
+    quantized_tensor_list = [_quantize_tensor(t, qtype) for t in tensor_list]
+    return quantized_tensor_list
+
+
+def _dequantize_tensor(tensor, qtype, quant_loss=None):
+    if not isinstance(tensor, torch.Tensor):
+        raise RuntimeError(
+            f"_dequantize_tensor expecting torch.Tensor as input but found {type(tensor)}"
+        )
+    if qtype == DQuantType.FP16:
+        if tensor.dtype != torch.float16:
+            raise RuntimeError(
+                f"tensor dtype is {tensor.dtype} while expected to be FP16."
+            )
+        elif tensor.dtype == torch.float16 and quant_loss is None:
+            return tensor.float()
+        else:
+            return tensor.float() / quant_loss
+    elif qtype == DQuantType.BFP16:
+        if tensor.dtype != torch.float16:
+            raise RuntimeError(
+                f"tensor dtype is {tensor.dtype} while expected to be FP16."
+            )
+        else:
+            return torch.ops.quantization._Bfloat16QuantizedToFloat(tensor)
+    else:
+        raise RuntimeError(f"Quantization type {qtype} is not supported")
+
+
+def _dequantize_tensor_list(tensor_list, qtype, quant_loss=None):
+    if not isinstance(tensor_list, list) or not all(
+        isinstance(p, torch.Tensor) for p in tensor_list
+    ):
+        raise RuntimeError(
+            f"_dequantize_tensor_list expecting list of torch.Tensor as input but found {type(tensor_list)}"
+        )
+    dequantized_tensor_list = [_dequantize_tensor(t, qtype) for t in tensor_list]
+    return dequantized_tensor_list
+
+
+def auto_quantize(func, qtype, quant_loss=None):
+    """
+    Quantize the input tensors, choose the precision types, and pass other necessary arguments and then dequantizes the output.
+
+    Currently it only supports:
+        . FP16 and BFP16 quantization method supported for gloo and nccl backends
+        . all_gather, all_to_all collective ops
+    Note: BFP16 only supports 2D tensors.
+    Args:
+        func (Callable): A function representing collective operations.
+        qtype (QuantType): Quantization method
+        quant_loss (float, optional): This can be used to improve accuracy in the dequantization.
+    Returns:
+        (Callable): the same collective as func but enables automatic quantization/dequantization.
+    """
+
+    @functools.wraps(func)
+    def wrapper(*args, **kwargs):
+        group = kwargs.get("group", None)
+        async_op = kwargs.get("async_op", False)
+        if async_op is True:
+            raise RuntimeError("The async_op=True mode is not supported yet.")
+        if func == dist.all_gather:
+            tensors = args[0]
+            input_tensors = _quantize_tensor(args[1], qtype)
+            out_tensors = _quantize_tensor_list(tensors, qtype)
+            dist.all_gather(out_tensors, input_tensors, group=group, async_op=async_op)
+            for i, t in enumerate(
+                _dequantize_tensor_list(out_tensors, qtype, quant_loss=quant_loss)
+            ):
+                tensors[i] = t
+
+        elif func == dist.all_to_all:
+            tensors = args[0]
+            input_tensors = _quantize_tensor_list(args[1], qtype)
+            out_tensors = _quantize_tensor_list(tensors, qtype)
+            dist.all_to_all(out_tensors, input_tensors, group=group, async_op=async_op)
+            for i, t in enumerate(
+                _dequantize_tensor_list(out_tensors, qtype, quant_loss=quant_loss)
+            ):
+                tensors[i] = t
+
+        elif func == dist.all_to_all_single:
+            tensors = args[0]
+            out_splits = kwargs.get("out_splits", None)
+            in_splits = kwargs.get("in_splits", None)
+            # Quantizing the input/output tensor
+            input_tensors = _quantize_tensor(args[1], qtype)
+            out_tensors = _quantize_tensor(tensors, qtype)
+            dist.all_to_all_single(
+                out_tensors, input_tensors, out_splits, in_splits, group=group
+            )
+            for i, t in enumerate(
+                _dequantize_tensor(out_tensors, qtype, quant_loss=quant_loss)
+            ):
+                tensors[i] = t
+        else:
+            raise RuntimeError(f"The collective op {func} is not supported yet")
+
+    return wrapper
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1d1ffd2fc8771ce346556f988dfd764683ce94a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__init__.py
@@ -0,0 +1,110 @@
+# mypy: allow-untyped-defs
+from enum import Enum
+from functools import partial
+
+import torch.distributed as dist
+
+from . import (
+    debugging_hooks as debugging,
+    default_hooks as default,
+    optimizer_overlap_hooks as optimizer_overlap,
+    powerSGD_hook as powerSGD,
+    quantization_hooks as quantization,
+)
+
+
+__all__ = ["DDPCommHookType", "register_ddp_comm_hook"]
+
+
+def _ddp_comm_hook_wrapper(comm_hook, model, state):
+    model.register_comm_hook(state, comm_hook)
+
+
+def _powerSGD_comm_hook_wrapper(
+    comm_hook,
+    model,
+    state,
+    matrix_approximation_rank,
+    start_powerSGD_iter=1_000,
+):
+    """
+    Wrap PowerSGD communication hook.
+
+    To be consistent with the wrappers of other DDP comm hooks, the input state only needs to be a process group,
+    which will be wrapped up with other state info.
+    """
+    powerSGD_state = powerSGD.PowerSGDState(
+        process_group=state,
+        matrix_approximation_rank=matrix_approximation_rank,
+        start_powerSGD_iter=start_powerSGD_iter,
+    )
+    model.register_comm_hook(powerSGD_state, comm_hook)
+
+
+class DDPCommHookType(Enum):
+    """
+    Enumerate ``ddp_comm_hooks`` and ``ddp_comm_hook_wrapper`` communucation hook types.
+
+    DDPCommHookType enumerates the hooks of ``torch.distributed.algorithms.ddp_comm_hooks``
+    as names and ``ddp_comm_hook_wrapper`` partials with hook specified. As an example,
+    you can register allreduce hook by
+    ``DDPCommHookType.ALLREDUCE.value(model=model, state=process_group)``.
+    """
+
+    ALLREDUCE = partial(_ddp_comm_hook_wrapper, comm_hook=default.allreduce_hook)
+    FP16_COMPRESS = partial(
+        _ddp_comm_hook_wrapper, comm_hook=default.fp16_compress_hook
+    )
+    BF16_COMPRESS = partial(
+        _ddp_comm_hook_wrapper, comm_hook=default.bf16_compress_hook
+    )
+    QUANTIZE_PER_TENSOR = partial(
+        _ddp_comm_hook_wrapper, comm_hook=quantization.quantization_pertensor_hook
+    )
+    QUANTIZE_PER_CHANNEL = partial(
+        _ddp_comm_hook_wrapper, comm_hook=quantization.quantization_perchannel_hook
+    )
+    POWER_SGD = partial(
+        _powerSGD_comm_hook_wrapper,
+        comm_hook=powerSGD.powerSGD_hook,
+        matrix_approximation_rank=1,
+    )
+    # Rank-2 PowerSGD can give a higher accuracy than the default rank-1 version,
+    # but it runs slower and consumes more memory.
+    POWER_SGD_RANK2 = partial(
+        _powerSGD_comm_hook_wrapper,
+        comm_hook=powerSGD.powerSGD_hook,
+        matrix_approximation_rank=2,
+    )
+    # Batching can lead to a faster training at the cost of accuracy.
+    BATCHED_POWER_SGD = partial(
+        _powerSGD_comm_hook_wrapper,
+        comm_hook=powerSGD.batched_powerSGD_hook,
+        matrix_approximation_rank=1,
+    )
+    BATCHED_POWER_SGD_RANK2 = partial(
+        _powerSGD_comm_hook_wrapper,
+        comm_hook=powerSGD.batched_powerSGD_hook,
+        matrix_approximation_rank=2,
+    )
+    NOOP = partial(
+        _ddp_comm_hook_wrapper,
+        comm_hook=debugging.noop_hook,
+    )
+
+
+def register_ddp_comm_hook(comm_hook_type: DDPCommHookType, model, state=None):
+    """
+    Register ``ddp_comm_hooks`` to DDP model.
+
+    Registers the hooks of ``torch.distributed.algorithms.ddp_comm_hooks``
+    to the DDP model. User can specify the type of hook as an enum
+    ``DDPCommHookType`` type using ``comm_hook_type`` input. State input will
+    be passed to the model.
+    Uses Python comm hook implementations.
+
+    Example::
+        >>> # xdoctest: +SKIP
+        >>> register_ddp_comm_hook(DDPCommHookType.FP16_COMPRESS, model, state)
+    """
+    comm_hook_type.value(model=model, state=state)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a5d16d40a7b2b11e56751d32ddf3905fb1a381b6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/ddp_zero_hook.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/ddp_zero_hook.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..de63168c264ed3c636e8a21e6ac7cc94a1bae3b0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/ddp_zero_hook.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/debugging_hooks.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/debugging_hooks.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..def7f09bbc029de915b03f6750c9feb3967d56fc
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/debugging_hooks.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/default_hooks.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/default_hooks.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ea798372dee205f8a98ecc90e0d53cfb3523c609
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/default_hooks.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/mixed_precision_hooks.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/mixed_precision_hooks.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b0596305ffdd74a74fb19010d8bd26bc65fda5d6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/mixed_precision_hooks.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/optimizer_overlap_hooks.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/optimizer_overlap_hooks.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ca17dae0302fc260a24410b3b36cba263b1f6263
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/optimizer_overlap_hooks.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/post_localSGD_hook.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/post_localSGD_hook.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5fc67ab4c46c8acf159c3edeced8ace1db2823fe
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/post_localSGD_hook.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/powerSGD_hook.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/powerSGD_hook.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3fe4806aa004fa0a574f85d7881e0d416e521bbe
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/powerSGD_hook.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/quantization_hooks.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/quantization_hooks.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..39688a5c9d4cc8221f0f8503e010cc683fd37293
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/__pycache__/quantization_hooks.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/ddp_zero_hook.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/ddp_zero_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..6db6d1831b1fdef770aa32a73fa7699c2ee5458e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/ddp_zero_hook.py
@@ -0,0 +1,458 @@
+# mypy: allow-untyped-defs
+import weakref
+from typing import Any, Callable, List, Optional
+
+import torch
+import torch.distributed as dist
+from torch.distributed.optim import ZeroRedundancyOptimizer
+from torch.distributed.optim.zero_redundancy_optimizer import _OverlapStatus
+from torch.nn.parallel.distributed import DistributedDataParallel
+
+
+__all__ = ["hook_with_zero_step", "hook_with_zero_step_interleaved"]
+
+# Functional optimizers require passing a list of gradients to their `step()`
+# method, and ZeRO requires a functional optimizer to overlap with DDP
+# Passing a `None` instead of an actual gradient indicates to the optimizer
+# to not update the corresponding parameter
+_NO_PARAM_UPDATE: None = None
+
+
+def _perform_local_step(
+    bucket: dist.GradBucket,
+    zero: ZeroRedundancyOptimizer,
+    rank: int,
+):
+    r"""
+    Perform a local optimizer step using the gradients provided by ``bucket``.
+
+    Arguments:
+        bucket (dist.GradBucket): the bucket providing the gradients.
+        zero (ZeroRedundancyOptimizer): the :class:`ZeroRedundancyOptimizer`
+            instance to perform the :meth:`_local_step`.
+        rank (int): the calling process's rank.
+
+    .. warning::
+        This function assumes that appropriate synchronization has taken place
+        so that the bucket's gradients can be used.
+    """
+    overlap_info = zero._overlap_info
+    bucket_index = bucket.index()
+    assert (
+        len(zero.optim.param_groups) == 1
+    ), "Overlapping DDP with ZeRO only supports a single parameter group"
+
+    # Construct the `gradients` input for the local optimizer step, which
+    # expects `None` in a list position to indicate that the corresponding
+    # parameter should not be updated
+    num_local_optim_params = len(zero.optim.param_groups[0]["params"])
+    gradients: List[Optional[torch.Tensor]] = [
+        _NO_PARAM_UPDATE for _ in range(num_local_optim_params)
+    ]
+    assert (
+        bucket_index in overlap_info.offsets
+    ), f"Bucket index {bucket_index} was not assigned to rank {rank}"
+    gradients_offset = overlap_info.offsets[bucket_index]
+    bucket_assignment = zero._bucket_assignments_per_rank[rank][bucket_index]
+    bucket_offset = bucket_assignment.offset
+    length = len(bucket_assignment.parameters)
+    bucket_gradients = bucket.gradients()[bucket_offset : bucket_offset + length]
+    for i, grad in enumerate(bucket_gradients):
+        gradients[gradients_offset + i] = grad
+
+    zero._local_step(gradients)
+
+
+def _broadcast_bucket(
+    bucket_index: int,
+    zero: ZeroRedundancyOptimizer,
+):
+    r"""
+    Broadcasts a bucket's parameters.
+
+    Arguments:
+        bucket_index (int): the index of the bucket corresponding to the
+            parameters to broadcast.
+        zero (ZeroRedundancyOptimizer): the calling process's
+            :class:`ZeroRedundancyOptimizer` instance.
+    """
+    overlap_info = zero._overlap_info
+    assert (
+        len(overlap_info.assigned_ranks_per_bucket) > bucket_index
+    ), "`assigned_ranks_per_bucket` is not fully constructed"
+    # Sort to ensure the same ordering across ranks
+    assigned_ranks = sorted(overlap_info.assigned_ranks_per_bucket[bucket_index])
+    assert len(assigned_ranks) > 0, (
+        f"Bucket {bucket_index} should be " "assigned to at least one rank"
+    )
+    for assigned_rank in assigned_ranks:
+        bucket_assignments = zero._bucket_assignments_per_rank[assigned_rank]
+        if bucket_index in bucket_assignments:
+            overlap_info.broadcast_handles.append(
+                dist.broadcast(
+                    bucket_assignments[bucket_index].tensor,
+                    src=dist.get_global_rank(zero.process_group, assigned_rank),
+                    group=zero.process_group,
+                    async_op=True,
+                )
+            )
+
+
+def _save_ddp_bucket_info(
+    bucket: dist.GradBucket,
+    zero: ZeroRedundancyOptimizer,
+):
+    r"""
+    Save :class:`DistributedDataParallel` gradient bucket information for :class:`ZeroRedundancyOptimizer` instance ``zero``.
+
+    In particular, this function is meant to be called upon seeing each
+    gradient bucket to use when overlapping, meaning it does not save or compute any global
+    information.
+
+    Arguments:
+        bucket (dist.GradBucket): the current gradient bucket.
+        zero (ZeroRedundancyOptimizer): the calling process's
+            :class:`ZeroRedundancyOptimizer` instance.
+    """
+    overlap_info = zero._overlap_info
+    bucket_params = bucket.parameters()
+    assert len(bucket_params) > 0, "Empty bucket"
+
+    # Save the parameters in the bucket
+    overlap_info.params_per_bucket.append(bucket_params)
+    if overlap_info.shard_buckets:
+        # Additionally save the bucket size for the assignment heuristic to use
+        bucket_size = 0
+        for param in bucket_params:
+            bucket_size += param.numel()
+        assert overlap_info.total_size is not None
+        overlap_info.total_size += bucket_size
+
+
+def _hook_with_zero_step_setup(
+    ddp_ref: weakref.ReferenceType,
+    zero: ZeroRedundancyOptimizer,
+    bucket: dist.GradBucket,
+):
+    r"""
+    Encapsulate the setup logic for :func:`hook_with_zero_step` and :func:`hook_with_zero_step_interleaved`.
+
+    This means the logic to run in the
+    hook before the backward pass and optimizer step can actually be
+    overlapped. This is factored out since it is common to both
+    :func:`hook_with_zero_step` and :func:`hook_with_zero_step_interleaved`.
+
+    Arguments:
+        ddp_ref (weakref.ReferenceType): weak reference to the process's
+            :class:`DistributedDataParallel` instance.
+        zero (ZeroRedundancyOptimizer): the calling process's
+            :class:`ZeroRedundancyOptimizer` instance.
+        bucket (dist.GradBucket): the current gradient bucket.
+    """
+    # Proceed as normal until the DDP buckets have been rebuilt
+    if not ddp_ref()._has_rebuilt_buckets:  # type: ignore[union-attr]
+        assert zero._overlap_info.status == _OverlapStatus.UNINITIALIZED
+        return
+
+    bucket_index = bucket.index()
+    overlap_info = zero._overlap_info
+    if overlap_info.status == _OverlapStatus.UNINITIALIZED:
+        overlap_info.status = _OverlapStatus.DDP_HAS_REBUILT_BUCKETS
+
+    if overlap_info.status == _OverlapStatus.DDP_HAS_REBUILT_BUCKETS:
+        if bucket_index == 0 and len(overlap_info.params_per_bucket) > 0:
+            # This corresponds to the first bucket of the backward pass
+            # immediately after all information has been saved, so we
+            # can perform the delayed ZeRO initialization
+            zero._init_zero_for_overlap()
+        else:
+            # Once DDP buckets have been rebuilt but ZeRO has not been
+            # properly initialized yet, save the information needed
+            _save_ddp_bucket_info(bucket, zero)
+
+
+def hook_with_zero_step(
+    hook: Callable[[Any, dist.GradBucket], torch.futures.Future],
+    ddp: DistributedDataParallel,
+    zero: ZeroRedundancyOptimizer,
+    shard_buckets: bool = False,
+) -> Callable[[Any, dist.GradBucket], torch.futures.Future[torch.Tensor]]:
+    r"""
+    Modify ``hook`` to overlap :class:`ZeroRedundancyOptimizer` optimizer step with :class:`DistributedDataParallel` backward pass.
+
+    This approach overlaps the optimizer computation and communication with the
+    backward communication. In particular, the backward computation proceeds
+    contiguously, and the optimizer computation follows, overlapping with
+    outstanding backward communication (i.e. all-reduces) and possibly other
+    optimizer communication (i.e. broadcasts).
+    The optimizer step computation begins after the last gradient bucket computation has finished.
+
+    This approach may be preferred over :meth:`hook_with_zero_step_interleaved`
+    if communication is relatively slow compared to computation.
+
+    Arguments:
+        hook (Callable[[Any, dist.GradBucket], torch.futures.Future]): the hook
+            to modify.
+        ddp (DistributedDataParallel): the :class:`DistributedDataParallel`
+            instance to use.
+        zero (ZeroRedundancyOptimizer): the :class:`ZeroRedundancyOptimizer`
+            instance to use.
+        shard_buckets (bool): if ``True``, then the assignment of each
+            :class:`DistributedDataParallel` bucket is partitioned across
+            possibly multiple :class:`ZeroRedundancyOptimizer` instances (i.e.
+            across possibly multiple ranks) to approximate uniformity; if
+            ``False``, then each bucket is wholly assigned to a single
+            :class:`ZeroRedundancyOptimizer` instance (i.e. to a single rank).
+
+    Returns:
+        The modified hook.
+
+    Raises:
+        ValueError: if ``zero`` was constructed with ``overlap_with_ddp=False``.
+        RuntimeError: if using any backend other than NCCL/HCCL since currently
+            Gloo may hang.
+
+    .. warning::
+        Given the way that overlapping :class:`DistributedDataParallel` with
+        :class:`ZeroRedundancyOptimizer` is currently implemented, the first
+        two or three training iterations do not perform parameter updates in
+        the optimizer step, depending on if ``static_graph=False`` or
+        ``static_graph=True``, respectively. This is because it needs
+        information about the gradient bucketing strategy used by
+        :class:`DistributedDataParallel`, which is not finalized until the
+        second forward pass if ``static_graph=False`` or until the third
+        forward pass if ``static_graph=True``.
+    """
+    if not zero._overlap_with_ddp:
+        raise ValueError(
+            "ZeroRedundancyOptimizer must be constructed with "
+            "`overlap_with_ddp=True` to use this hook properly"
+        )
+    ddp_ref = weakref.ref(ddp)
+
+    # NOTE: Gloo may hang with this overlapping approach, so we require
+    # NCCL/HCCL backend for now; see https://github.com/pytorch/pytorch/issues/62300
+    pg = dist.get_backend(ddp_ref().process_group)  # type: ignore[union-attr]
+    if (pg != dist.Backend.NCCL) and (pg != "hccl"):
+        raise RuntimeError(
+            "Overlapping DDP with ZeRO using this approach currently requires "
+            "NCCL/HCCL backend to avoid hangs"
+        )
+
+    if shard_buckets:
+        zero._overlap_info.shard_buckets = True
+        zero._overlap_info.total_size = 0
+
+    def hook_with_zero_fn(
+        state: Any,
+        bucket: dist.GradBucket,
+    ) -> torch.futures.Future[torch.Tensor]:
+        r"""
+        Return :class:`Future` that runs the optimizer step if this corresponds to the last gradient bucket.
+
+        Perform equivalent of :class:`ZeroRedundancyOptimizer` :meth:`step` if ``bucket`` is last gradient bucket.
+        The function gives a gradient bucket tensor and
+        performs additional computation on the iteration that
+        the :class:`DistributedDataParallel` buckets are rebuilt to collect
+        information used to implement the modified hook.
+
+        Arguments:
+            state (Any): any state for the hook.
+            bucket (dist.GradBucket): the :class:`DistributedDataParallel`
+                gradient bucket.
+        """
+        fut = hook(state, bucket)
+        _hook_with_zero_step_setup(ddp_ref, zero, bucket)
+        if zero._overlap_info.status != _OverlapStatus.INITIALIZED:
+            return fut
+
+        overlap_info = zero._overlap_info
+        bucket_index = bucket.index()
+        rank = zero.global_rank
+
+        assert overlap_info.status == _OverlapStatus.INITIALIZED
+        assert (
+            len(overlap_info.assigned_ranks_per_bucket) > bucket_index
+        ), "`assigned_ranks_per_bucket` is not fully constructed"
+        assigned_to_bucket = (
+            rank in overlap_info.assigned_ranks_per_bucket[bucket_index]
+        )
+
+        # Save the bucket reference and all-reduce future for the final bucket
+        if assigned_to_bucket:
+            overlap_info.bucket_index_to_bucket[bucket_index] = bucket
+            overlap_info.bucket_index_to_future[bucket_index] = fut
+
+        # Check that buckets are indexed incrementally starting from 0 in the
+        # order of their autograd hooks firing
+        if len(overlap_info.bucket_indices_seen) > 0:
+            assert (
+                overlap_info.bucket_indices_seen[-1] == bucket_index - 1
+            ), "Bucket indices are not in incremental order"
+        else:
+            assert bucket_index == 0, "Bucket indices do not start from 0"
+        overlap_info.bucket_indices_seen.append(bucket_index)
+
+        # Directly return the future without any optimizer computation if this
+        # is not the last bucket
+        num_buckets = len(overlap_info.params_per_bucket)
+        is_last_bucket = bucket_index == num_buckets - 1
+        if not is_last_bucket:
+            return fut
+
+        # Perform partial optimizer step on all buckets after the final
+        # bucket has been computed
+        # NOTE: This should not be chained as a callback to the last bucket's
+        # all-reduce future since that would add synchronization that delays
+        # all optimizer computation to wait for that last all-reduce
+        for bucket_index in range(num_buckets):
+            assigned_ranks = overlap_info.assigned_ranks_per_bucket[bucket_index]
+            if rank in assigned_ranks:
+                # Wait on the bucket's all-reduce future to ensure correct
+                # gradients
+                assert bucket_index in overlap_info.bucket_index_to_future, (
+                    f"All-reduce future for bucket {bucket_index} not saved "
+                    f"on rank {rank}"
+                )
+                allreduce_future = overlap_info.bucket_index_to_future[bucket_index]
+                allreduce_future.wait()
+
+                # Perform the partial optimizer step
+                curr_bucket = overlap_info.bucket_index_to_bucket[bucket_index]
+                _perform_local_step(curr_bucket, zero, rank)
+
+            _broadcast_bucket(bucket_index, zero)
+
+        # Ensure that all parameter updates are finished before the
+        # next forward pass
+        overlap_info.wait_for_broadcasts()
+        overlap_info.clear_per_iter_info()
+
+        return fut
+
+    return hook_with_zero_fn
+
+
+def hook_with_zero_step_interleaved(
+    hook: Callable[[Any, dist.GradBucket], torch.futures.Future],
+    ddp: DistributedDataParallel,
+    zero: ZeroRedundancyOptimizer,
+    shard_buckets: bool = False,
+) -> Callable[[Any, dist.GradBucket], torch.futures.Future[torch.Tensor]]:
+    r"""
+    Modify ``hook`` to overlap :class:`ZeroRedundancyOptimizer` optimizer step with :class:`DistributedDataParallel` backward pass
+
+    This approach overlaps the optimizer computation and communication with the
+    backward computation and communication. In particular, once a bucket's
+    gradients have been computed, the optimizer computation using those
+    gradients is launched (though the actual computation must wait for the
+    bucket's all-reduce to complete). This yields an interleaving of all-
+    reduces and broadcasts in the communication stream.
+
+    This approach may be preferred over :meth:`hook_with_zero_step` if
+    communication is relatively fast compared to computation.
+
+    Arguments:
+        hook (Any * dist.GradBucket -> torch.futures.Future): the hook to
+            modify.
+        ddp (DistributedDataParallel): the :class:`DistributedDataParallel`
+            instance to use.
+        zero (ZeroRedundancyOptimizer): the :class:`ZeroRedundancyOptimizer`
+            instance to use.
+        shard_buckets (bool): if ``True``, then the assignment of each
+            :class:`DistributedDataParallel` bucket is partitioned across
+            possibly multiple :class:`ZeroRedundancyOptimizer` instances (i.e.
+            across possibly multiple ranks) to approximate uniformity; if
+            ``False``, then each bucket is wholly assigned to a single
+            :class:`ZeroRedundancyOptimizer` instance (i.e. to a single rank).
+
+    Returns:
+        The modified hook.
+
+    Raises:
+        ValueError: if ``zero`` was constructed with ``overlap_with_ddp=False``.
+        RuntimeError: if using any backend other than NCCL since currently
+            Gloo may hang.
+
+    .. warning::
+        Given the way that overlapping :class:`DistributedDataParallel` with
+        :class:`ZeroRedundancyOptimizer` is currently implemented, the first
+        two or three training iterations do not perform parameter updates in
+        the optimizer step, depending on if ``static_graph=False`` or
+        ``static_graph=True``, respectively. This is because it needs
+        information about the gradient bucketing strategy used by
+        :class:`DistributedDataParallel`, which is not finalized until the
+        second forward pass if ``static_graph=False`` or until the third
+        forward pass if ``static_graph=True``.
+    """
+    if not zero._overlap_with_ddp:
+        raise ValueError(
+            "ZeroRedundancyOptimizer must be constructed with "
+            "`overlap_with_ddp=True` to use this hook properly"
+        )
+    ddp_ref = weakref.ref(ddp)
+
+    # NOTE: Gloo may hang with this overlapping approach, so we require
+    # NCCL/HCCL backend for now; see https://github.com/pytorch/pytorch/issues/62300
+    pg = dist.get_backend(ddp_ref().process_group)  # type: ignore[union-attr]
+    if (pg != dist.Backend.NCCL) and (pg != "hccl"):
+        raise RuntimeError(
+            "Overlapping DDP with ZeRO using this approach currently requires "
+            "NCCL/HCCL backend to avoid hangs"
+        )
+
+    if shard_buckets:
+        zero._overlap_info.shard_buckets = True
+        zero._overlap_info.total_size = 0
+
+    def hook_with_zero_interleaved_fn(
+        state,
+        bucket: dist.GradBucket,
+    ) -> torch.futures.Future[torch.Tensor]:
+        r"""
+        Return :class:`Future` that gives gradient bucket tensor and performs partial :class:`ZeroRedundancyOptimizer` :meth:`step`.
+
+        This function uses the gradients in gradient in given bucket to perform a partial
+        :class:`ZeroRedundancyOptimizer` :meth:`step`
+
+        Arguments:
+            state: any state for the hook.
+            bucket (dist.GradBucket): the :class:`DistributedDataParallel`
+                gradient bucket.
+        """
+        fut = hook(state, bucket)
+        _hook_with_zero_step_setup(ddp_ref, zero, bucket)
+        if zero._overlap_info.status != _OverlapStatus.INITIALIZED:
+            return fut
+
+        def zero_step(fut: torch.futures.Future) -> torch.Tensor:
+            r"""
+            Perform partial :class:`ZeroRedundancyOptimizer` :meth:`step` using gradients in the :class:`DistributedDataParallel`.
+
+            Returns:
+                A :class:`torch.Tensor` representing the contents of the
+                gradient bucket.
+            """
+            overlap_info = zero._overlap_info
+            bucket_index = bucket.index()
+            rank = zero.global_rank
+
+            assigned_ranks = overlap_info.assigned_ranks_per_bucket[bucket_index]
+            overlap_info.bucket_indices_seen.append(bucket_index)
+            if rank in assigned_ranks:
+                _perform_local_step(bucket, zero, rank)
+
+            _broadcast_bucket(bucket_index, zero)
+
+            num_buckets = len(overlap_info.params_per_bucket)
+            if len(overlap_info.bucket_indices_seen) == num_buckets:
+                # Ensure that all parameter updates are finished before the
+                # next forward pass
+                overlap_info.wait_for_broadcasts()
+                overlap_info.clear_per_iter_info()
+
+            return bucket.buffer()
+
+        return fut.then(zero_step)
+
+    return hook_with_zero_interleaved_fn
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/debugging_hooks.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/debugging_hooks.py
new file mode 100644
index 0000000000000000000000000000000000000000..53a184839a06f4787471f14f48137f4aa344fd91
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/debugging_hooks.py
@@ -0,0 +1,29 @@
+from typing import Any
+
+import torch
+from torch.distributed import GradBucket
+
+
+__all__ = ["noop_hook"]
+
+
+def noop_hook(_: Any, bucket: GradBucket) -> torch.futures.Future[torch.Tensor]:
+    """
+    Return a future that wraps the input, so it is a no-op that does not incur any communication overheads.
+
+    This hook should **only** be used for headroom analysis of allreduce optimization,
+    instead of the normal gradient synchronization.
+    For example, if only less than 10% speedup of training time can be observed after this hook is registered,
+    it usually implies that allreduce is not a performance bottleneck for this case.
+    Such instrumentation can be particularly useful
+    if GPU traces cannot be easily retrieved or the trace analysis is complicated
+    some factors such as the overlap between allreduce and computation or the desynchronization across ranks.
+
+    Example::
+        >>> # xdoctest: +SKIP
+        >>> ddp_model.register_comm_hook(None, noop_hook)
+    """
+    fut: torch.futures.Future[torch.Tensor] = torch.futures.Future()
+    fut.set_result(bucket.buffer())
+
+    return fut
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/default_hooks.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/default_hooks.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1296ae712f0c0046128884b64a1eb7661c8d74f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/default_hooks.py
@@ -0,0 +1,225 @@
+# mypy: allow-untyped-defs
+from typing import Any, Callable, cast, Tuple
+
+import torch
+import torch.distributed as dist
+
+
+__all__ = [
+    "allreduce_hook",
+    "fp16_compress_hook",
+    "bf16_compress_hook",
+    "fp16_compress_wrapper",
+    "bf16_compress_wrapper",
+]
+
+
+def _allreduce_fut(
+    process_group: dist.ProcessGroup, tensor: torch.Tensor
+) -> torch.futures.Future[torch.Tensor]:
+    """Average the input gradient tensor by allreduce and returns a future."""
+    group_to_use = process_group if process_group is not None else dist.group.WORLD
+
+    # Apply the division first to avoid overflow, especially for FP16.
+    tensor.div_(group_to_use.size())
+
+    return (
+        dist.all_reduce(tensor, group=group_to_use, async_op=True)
+        .get_future()
+        .then(lambda fut: fut.value()[0])
+    )
+
+
+def allreduce_hook(
+    process_group: dist.ProcessGroup, bucket: dist.GradBucket
+) -> torch.futures.Future[torch.Tensor]:
+    """
+    Call ``allreduce`` using ``GradBucket`` tensors.
+
+    Once gradient tensors are aggregated across all workers, its ``then``
+    callback takes the mean and returns the result.
+
+    If user registers this DDP communication hook,
+    DDP results is expected to be same as the case where no hook was registered.
+    Hence, this won't change behavior of DDP and user can use this as a reference
+    or modify this hook to log useful information or any other purposes while
+    unaffecting DDP behavior.
+
+    Example::
+        >>> # xdoctest: +SKIP
+        >>> ddp_model.register_comm_hook(process_group, allreduce_hook)
+    """
+    return _allreduce_fut(process_group, bucket.buffer())
+
+
+def fp16_compress_hook(
+    process_group: dist.ProcessGroup,
+    bucket: dist.GradBucket,
+) -> torch.futures.Future[torch.Tensor]:
+    """
+    Compress by casting ``GradBucket`` to ``torch.float16`` divided by process group size.
+
+    This DDP communication hook implements a simple gradient compression
+    approach that casts ``GradBucket`` tensor to half-precision floating-point format (``torch.float16``)
+    and then divides it by the process group size.
+    It allreduces those ``float16`` gradient tensors. Once compressed gradient
+    tensors are allreduced, the chained callback ``decompress`` casts it back to the input data type (such as ``float32``).
+
+    Example::
+        >>> # xdoctest: +SKIP
+        >>> ddp_model.register_comm_hook(process_group, fp16_compress_hook)
+    """
+    group_to_use = process_group if process_group is not None else dist.group.WORLD
+    world_size = group_to_use.size()
+
+    buffer = (
+        cast(Tuple[torch.Tensor, ...], bucket)[0]
+        if isinstance(bucket, tuple)
+        else bucket.buffer()
+    )
+    compressed_tensor = buffer.to(torch.float16).div_(world_size)
+
+    def decompress(fut):
+        decompressed_tensor = buffer
+        # Decompress in place to reduce the peak memory.
+        # See: https://github.com/pytorch/pytorch/issues/45968
+        value = fut if isinstance(fut, torch.Tensor) else fut.value()[0]
+        decompressed_tensor.copy_(value)
+        return decompressed_tensor
+
+    if torch._utils.is_compiling():
+        grad = dist._functional_collectives.all_reduce(
+            compressed_tensor, "sum", group_to_use
+        )
+        return decompress(grad)
+    else:
+        fut = dist.all_reduce(
+            compressed_tensor, group=group_to_use, async_op=True
+        ).get_future()
+        return fut.then(decompress)
+
+
+# TODO: create an internal helper function and extract the duplicate code in FP16_compress and BF16_compress.
+def bf16_compress_hook(
+    process_group: dist.ProcessGroup,
+    bucket: dist.GradBucket,
+) -> torch.futures.Future[torch.Tensor]:
+    """
+    Warning: This API is experimental, and it requires NCCL version later than 2.9.6.
+
+    This DDP communication hook implements a simple gradient compression
+    approach that casts ``GradBucket`` tensor to half-precision
+    `Brain floating point format `_ (``torch.bfloat16``)
+    and then divides it by the process group size.
+    It allreduces those ``bfloat16`` gradient tensors. Once compressed gradient
+    tensors are allreduced, the chained callback ``decompress`` casts it back to the input data type (such as ``float32``).
+
+    Example::
+        >>> # xdoctest: +SKIP
+        >>> ddp_model.register_comm_hook(process_group, bf16_compress_hook)
+    """
+    group_to_use = process_group if process_group is not None else dist.group.WORLD
+    world_size = group_to_use.size()
+
+    buffer = (
+        cast(Tuple[torch.Tensor, ...], bucket)[0]
+        if isinstance(bucket, tuple)
+        else bucket.buffer()
+    )
+    compressed_tensor = buffer.to(torch.bfloat16).div_(world_size)
+
+    def decompress(fut):
+        decompressed_tensor = buffer
+        # Decompress in place to reduce the peak memory.
+        # See: https://github.com/pytorch/pytorch/issues/45968
+        value = fut if isinstance(fut, torch.Tensor) else fut.value()[0]
+        decompressed_tensor.copy_(value)
+        return decompressed_tensor
+
+    if torch._utils.is_compiling():
+        grad = dist._functional_collectives.all_reduce(
+            compressed_tensor, "sum", group_to_use
+        )
+        return decompress(grad)
+    else:
+        fut = dist.all_reduce(
+            compressed_tensor, group=group_to_use, async_op=True
+        ).get_future()
+        return fut.then(decompress)
+
+
+def fp16_compress_wrapper(
+    hook: Callable[[Any, dist.GradBucket], torch.futures.Future[torch.Tensor]]
+) -> Callable[[Any, dist.GradBucket], torch.futures.Future[torch.Tensor]]:
+    """
+    Cast input tensor to ``torch.float16``, cast result of hook back to input dtype.
+
+    This wrapper casts the input gradient tensor of a given DDP communication hook to half-precision
+    floating point format (``torch.float16``), and casts the resulting tensor of the given hook back to
+    the input data type, such as ``float32``.
+    Therefore, ``fp16_compress_hook`` is equivalent to ``fp16_compress_wrapper(allreduce_hook)``.
+
+    Example::
+        >>> # xdoctest: +SKIP
+        >>> state = PowerSGDState(process_group=process_group, matrix_approximation_rank=1, start_powerSGD_iter=10)
+        >>> ddp_model.register_comm_hook(state, fp16_compress_wrapper(powerSGD_hook))
+    """
+
+    def fp16_compress_wrapper_hook(
+        hook_state, bucket: dist.GradBucket
+    ) -> torch.futures.Future[torch.Tensor]:
+        # Cast bucket tensor to FP16.
+        bucket.set_buffer(bucket.buffer().to(torch.float16))
+
+        fut = hook(hook_state, bucket)
+
+        def decompress(fut):
+            decompressed_tensor = bucket.buffer()
+            # Decompress in place to reduce the peak memory.
+            # See: https://github.com/pytorch/pytorch/issues/45968
+            decompressed_tensor.copy_(fut.value())
+            return decompressed_tensor
+
+        # Decompress after hook has run.
+        return fut.then(decompress)
+
+    return fp16_compress_wrapper_hook
+
+
+def bf16_compress_wrapper(
+    hook: Callable[[Any, dist.GradBucket], torch.futures.Future[torch.Tensor]]
+) -> Callable[[Any, dist.GradBucket], torch.futures.Future[torch.Tensor]]:
+    """
+    Warning: This API is experimental, and it requires NCCL version later than 2.9.6.
+
+    This wrapper casts the input gradient tensor of a given DDP communication hook to half-precision
+    `Brain floating point format  `_  (``torch.bfloat16``),
+    and casts the resulting tensor of the given hook back to the input data type, such as ``float32``.
+
+    Therefore, ``bf16_compress_hook`` is equivalent to ``bf16_compress_wrapper(allreduce_hook)``.
+
+    Example::
+        >>> # xdoctest: +SKIP
+        >>> state = PowerSGDState(process_group=process_group, matrix_approximation_rank=1, start_powerSGD_iter=10)
+        >>> ddp_model.register_comm_hook(state, bf16_compress_wrapper(powerSGD_hook))
+    """
+
+    def bf16_compress_wrapper_hook(
+        hook_state, bucket: dist.GradBucket
+    ) -> torch.futures.Future[torch.Tensor]:
+        # Cast bucket tensor to BF16.
+        bucket.set_buffer(bucket.buffer().to(torch.bfloat16))
+
+        fut = hook(hook_state, bucket)
+
+        def decompress(fut):
+            decompressed_tensor = bucket.buffer()
+            # Decompress in place to reduce the peak memory.
+            # See: https://github.com/pytorch/pytorch/issues/45968
+            decompressed_tensor.copy_(fut.value())
+            return decompressed_tensor
+
+        # Decompress after hook has run.
+        return fut.then(decompress)
+
+    return bf16_compress_wrapper_hook
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/mixed_precision_hooks.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/mixed_precision_hooks.py
new file mode 100644
index 0000000000000000000000000000000000000000..4727bbf9d45e66f5983f441cd8d72224e62069f8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/mixed_precision_hooks.py
@@ -0,0 +1,88 @@
+from dataclasses import dataclass
+from typing import Any, no_type_check
+
+import torch
+import torch.distributed as dist
+from torch.autograd import Variable
+from torch.distributed.utils import _free_storage
+
+
+@dataclass
+class _AllreduceUpcastHookState:
+    """
+    State to manage DDP mixed precision in backward / gradient communication.
+
+    This contains a weakref to the DDP module for access to reducer and process
+    group, and a stream to run parameter and gradient upcasts.
+    """
+
+    ddp_weakref: Any
+    upcast_stream: torch.cuda.Stream
+    wait_for_stream_enqueued: bool = False
+
+
+@no_type_check
+def _reducer_allreduce_and_upcast_hook(
+    hook_state: _AllreduceUpcastHookState, bucket: dist.GradBucket
+) -> torch.futures.Future[torch.Tensor]:
+    """
+    Perform allreduce in precision ``reduce_dtype``, upcast to prepare for optimizer.
+
+    Performs allreduce in the reduced precision given by DDP's mixed precision
+    reduce_dtype, and upcasts parameters and gradients to fp32 in preparation
+    to run the optimizer.
+    """
+    ddp_weakref = hook_state.ddp_weakref
+    reducer, process_group = ddp_weakref().reducer, ddp_weakref().process_group
+    gradient_is_bucket_view = ddp_weakref().gradient_as_bucket_view
+    # Cast bucket if different than param_dtype.
+    if (
+        ddp_weakref().mixed_precision.param_dtype
+        != ddp_weakref().mixed_precision.reduce_dtype
+    ):
+        # Cast bucket tensor to reduce_dtype
+        bucket.set_buffer(
+            bucket.buffer().to(ddp_weakref().mixed_precision.reduce_dtype)
+        )
+    fut = reducer._run_allreduce_hook(bucket)
+    ret_fut = torch.futures.Future()
+    stream = hook_state.upcast_stream
+    with torch.cuda.stream(stream):
+        fut.wait()
+        bucket.buffer().div_(process_group.size())
+        ret_fut.set_result(bucket.buffer())
+
+        # Upcast parameters and gradients so optimizer step can run in fp32.
+        params, grads = bucket.parameters(), bucket.gradients()
+        for p, g in zip(params, grads):
+            p.data = p._fp_param
+            # free storage for mp param as it will be allocated again in next
+            # forward pass.
+            _free_storage(p._mp_param)
+            p.grad.data = p.grad.to(p.data.dtype)
+
+    # enqueue a callback to wait for this stream at end of backward
+    def wait_for_stream_cb():
+        torch.cuda.current_stream().wait_stream(stream)
+        # Remove post-backward hooks since they are re-installed in next
+        # iteration, similar to FSDP.
+        # Parameters that don't require grad still needed to be casted since
+        # they may participate in computation. However, they would not be recast
+        # by hook above as they don't have a grad hook installed, so cast them
+        # back here.
+        for n, p in ddp_weakref().module.named_parameters():
+            if hasattr(p, "_ddp_mp_hook_state"):
+                p._ddp_mp_hook_state[1].remove()
+                delattr(p, "_ddp_mp_hook_state")
+            if not p.requires_grad and not hasattr(p, "_ddp_ignored"):
+                p.data = p._fp_param
+
+        # reset for next backward pass
+        hook_state.wait_for_stream_enqueued = False
+
+    if not hook_state.wait_for_stream_enqueued:
+        Variable._execution_engine.queue_callback(wait_for_stream_cb)
+        # mark that the callback is enqueued
+        hook_state.wait_for_stream_enqueued = True
+
+    return ret_fut
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/optimizer_overlap_hooks.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/optimizer_overlap_hooks.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ae242b04a9c537a6fbad357b9cd0e96376bb8eb
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/optimizer_overlap_hooks.py
@@ -0,0 +1,160 @@
+# mypy: allow-untyped-defs
+from dataclasses import dataclass
+from functools import partial
+from typing import Any, Callable, List, no_type_check
+
+import torch
+import torch.distributed as dist
+from torch.autograd import Variable
+
+
+__all__: List[str] = []
+
+_FUNCTIONAL_OPTIM_STEP_METHOD_NAME = "step_param"
+
+
+class _OptimizerHookState:
+    """
+    Holds state for running optimizer in-line after DDP communication hook.
+
+    Currently contains only optimizer class which must have a method `step_param`.
+    """
+
+    __slots__ = ["functional_optimizer", "params_to_optimize"]
+
+    def __init__(self, functional_optim, params=None):
+        self.functional_optimizer = functional_optim
+        self._check_valid_functional_optim()
+        self._set_params_to_optimize(params)
+
+    def _set_params_to_optimize(self, params):
+        if params is not None:
+            self.params_to_optimize = set(params)
+
+    def _check_valid_functional_optim(self):
+        if not hasattr(self.functional_optimizer, _FUNCTIONAL_OPTIM_STEP_METHOD_NAME):
+            raise ValueError(
+                f"Class {type(self.functional_optimizer)} must implement method "
+                f"{_FUNCTIONAL_OPTIM_STEP_METHOD_NAME}."
+            )
+
+
+@dataclass
+class _OptimInBackwardHookState:
+    optim_stream: torch.cuda.Stream
+    wait_for_optim_stream_enqueued: bool
+
+
+@no_type_check
+def _apply_optim_in_backward_hook(
+    gradient_is_bucket_view: bool,
+) -> Callable[[Any, dist.GradBucket], torch.futures.Future[torch.Tensor]]:
+    r"""
+    Register hook to apply the optimizer in backward.
+
+    If torch.distributed.optim._apply_optimizer_in_backward is used to overlap
+    optimizer with backward pass, DDP will run the below hook to run optimizer
+    step for parameters after gradient communication has taken place.
+    """
+    optim_in_bwd_state = _OptimInBackwardHookState(
+        optim_stream=torch.cuda.Stream(),
+        wait_for_optim_stream_enqueued=False,
+    )
+
+    def apply_optim_in_backward_hook(
+        hook_state: Any,
+        bucket: dist.GradBucket,
+        optim_stream_state,
+    ) -> torch.futures.Future[torch.Tensor]:
+        # Run original hook
+        ddp_weakref = hook_state
+        ddp_inst = ddp_weakref()
+        reducer, process_group = ddp_inst.reducer, ddp_inst.process_group
+        fut = reducer._run_allreduce_hook(bucket)
+        optimizer_stream = optim_stream_state.optim_stream
+        with torch.cuda.stream(optimizer_stream):
+            fut.wait()
+            # Apply gradient division since C++ side only allreduces and does
+            # not average. TODO: (rohan-varma) the div factor may be different
+            # when running with join hook
+            bucket.buffer().div_(process_group.size())
+            model_params = bucket.parameters()
+            grads = bucket.gradients()
+            # TODO (rohan-varma): upcast as needed for DDP mixed precision,
+            # once optimizer in backward + DDP mixed precision is supported.
+            for p, g in zip(model_params, grads):
+                if hasattr(p, "_in_backward_optimizers"):
+                    # Note: need to set grad to the bucket's grad, because
+                    # running allreduce results in the bucket's grad being
+                    # reduced, but not grad field.
+                    if not gradient_is_bucket_view:
+                        p.grad = g
+                    for optim in p._in_backward_optimizers:
+                        optim.step()
+
+        # Need to return a Future[Tensor] to obey comm hook API contract.
+        ret_fut = torch.futures.Future()
+        ret_fut.set_result(bucket.buffer())
+
+        # enqueue a callback to wait for this optimizer stream at the end of
+        # backward and set all DDP managed grads to None.
+        def wait_for_optim_stream_callback():
+            torch.cuda.current_stream().wait_stream(optim_stream_state.optim_stream)
+            # Set DDP managed grads to None
+            for param in ddp_inst._get_data_parallel_params(ddp_inst.module):
+                if hasattr(param, "_in_backward_optimizers"):
+                    param.grad = None
+
+            # reset for the next backwards pass
+            optim_stream_state.wait_for_optim_stream_enqueued = False
+
+        if not optim_stream_state.wait_for_optim_stream_enqueued:
+            Variable._execution_engine.queue_callback(wait_for_optim_stream_callback)
+            # mark that the callback is enqueued
+            optim_stream_state.wait_for_optim_stream_enqueued = True
+
+        return ret_fut
+
+    comm_hook = partial(
+        apply_optim_in_backward_hook, optim_stream_state=optim_in_bwd_state
+    )
+    # These are needed for DDP's logging of comm hooks
+    comm_hook.__name__ = apply_optim_in_backward_hook.__name__
+    comm_hook.__qualname__ = apply_optim_in_backward_hook.__qualname__
+
+    return comm_hook
+
+
+def _hook_then_optimizer(
+    hook: Callable[[Any, dist.GradBucket], torch.futures.Future[torch.Tensor]],
+    optimizer_state: _OptimizerHookState,
+) -> Callable[[Any, dist.GradBucket], torch.futures.Future[torch.Tensor]]:
+    r"""Run optimizer in a functional fashion after DDP communication hook."""
+    has_set_params = (
+        hasattr(optimizer_state, "params_to_optimize")
+        and optimizer_state.params_to_optimize is not None
+    )
+
+    def hook_then_optimizer_wrapper(
+        hook_state, bucket: dist.GradBucket
+    ) -> torch.futures.Future[torch.Tensor]:
+        # Run original hook
+        fut = hook(hook_state, bucket)
+
+        def optimizer_step(fut):
+            gradient_tensors = bucket.gradients()
+            model_params = bucket.parameters()
+            for grad_tensor, model_param in zip(gradient_tensors, model_params):
+                if (
+                    not has_set_params
+                    or model_param in optimizer_state.params_to_optimize
+                ):
+                    optimizer_state.functional_optimizer.step_param(
+                        model_param,
+                        grad_tensor,
+                    )
+            return bucket.buffer()
+
+        return fut.then(optimizer_step)
+
+    return hook_then_optimizer_wrapper
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/post_localSGD_hook.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/post_localSGD_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..d8da01e6e1fe2e242956aab780c88a2f6041552e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/post_localSGD_hook.py
@@ -0,0 +1,124 @@
+# mypy: allow-untyped-defs
+import logging
+
+import torch
+import torch.distributed as dist
+
+from . import default_hooks as default
+
+
+logger = logging.getLogger(__name__)
+
+
+class PostLocalSGDState:
+    r"""
+    Store state for all-reducing gradients globally until given step, then locally after.
+
+    Stores the state for all-reducing gradients globally using ``process_group`` until step ``start_localSGD_iter``,
+    and all-reducing gradients locally using ``subgroup`` afterwards.
+
+    If ``process_group`` is ``None``, the global process group will be used.
+    If ``subgroup`` is ``None``, the intra-node process group on each machine will be used.
+
+    Additionally, ``post_local_gradient_allreduce`` may be worth tuning,
+    because both true and false may give a faster convergence.
+    """
+
+    __slots__ = [
+        "process_group",
+        "subgroup",
+        "start_localSGD_iter",
+        "post_local_gradient_allreduce",
+        "iter",
+    ]
+
+    def __init__(
+        self,
+        process_group,
+        subgroup,
+        start_localSGD_iter,
+        post_local_gradient_allreduce=True,
+    ):
+        """Initialize state object with given parameters and log when localSGD start."""
+        logger.info(
+            "Local SGD will be started after %s iterations", start_localSGD_iter
+        )
+
+        # The group used for all-reducing gradients globally.
+        self.process_group = process_group
+        # The group used for all-reducing gradients locally.
+        self.subgroup = subgroup
+        self.start_localSGD_iter = start_localSGD_iter
+        # Allreduce gradients locally since iteration `start_localSGD_iter`.
+        # This may help with the convergence efficiency at the cost of relatively cheap intra-subgroup communication.
+        self.post_local_gradient_allreduce = post_local_gradient_allreduce
+        # Iteration/step in the training loop.
+        self.iter = 0
+
+    def maybe_increase_iter(self, bucket):
+        """Track iterations and trigger log message at start of local SGD."""
+        # Since bucket 0 is the last bucket to allreduce in an iteration.
+        # Only increase `iter` when bucket 0 is processed.
+        if bucket.is_last():
+            self.iter += 1
+
+        if self.iter == self.start_localSGD_iter:
+            logger.info("Start to apply local SGD after %s iterations.", self.iter)
+
+
+def post_localSGD_hook(
+    state: PostLocalSGDState, bucket: dist.GradBucket
+) -> torch.futures.Future[torch.Tensor]:
+    """
+    Run post-localSGD algorithm.
+
+    This DDP communication hook is used for running post-localSGD algorithm,
+    by combining with a model averaging component (e.g.,
+    :class:`~torch.distributed.algorithms.model_averaging.averagers.PeriodicModelAverager`)
+    that runs after the optimizer step.
+
+    Args:
+        state (PostLocalSGDState): State information to run post-localSGD.
+            Users mainly need to tune ``start_localSGD_iter`` to determine when to start local SGD.
+        bucket (dist.GradBucket): Bucket that stores a 1D flattened gradient tensor that batches multiple per-variable tensors.
+            Note that since DDP comm hook only supports single process single device mode,
+            only exactly one tensor is stored in this bucket.
+
+    Returns:
+        Future handler of the communication, which updates the gradients in place.
+
+    Example::
+        >>> # xdoctest: +SKIP
+        >>> state = PostLocalSGDState(process_group=process_group, subgroup=subgroup,
+                                  start_localSGD_iter=10)
+        >>> ddp_model.register_comm_hook(state, post_localSGD_hook)
+        >>> # Also need to establish a model averaging module and run model averaging after ``optimizer.step()``.
+        >>> # Please refer to the examples in ``torch.distributed.algorithms.model_averaging.averagers`` module.
+    """
+    global_group_to_use = (
+        state.process_group if state.process_group is not None else dist.group.WORLD
+    )
+
+    # The input tensor is a flattened 1D tensor.
+    input_tensor = bucket.buffer()
+
+    # Run allreduce using `global_group_to_use` in the first `start_localSGD_iter` iterations.
+    if state.iter < state.start_localSGD_iter:
+        state.maybe_increase_iter(bucket)
+        return default._allreduce_fut(global_group_to_use, input_tensor)
+
+    # If `post_local_gradient_allreduce` is not set,
+    # then no gradient synchronization after the first `start_localSGD_iter` iterations.
+    if not state.post_local_gradient_allreduce:
+        fut: torch.futures.Future[torch.Tensor] = torch.futures.Future()
+        fut.set_result(input_tensor)
+        return fut
+
+    # Run allreduce using `subgroup` after the first `start_localSGD_iter` iterations.
+    # Note that by default, a separate subgroup for each node is created which
+    # causes an intra-node allreduce to be done at each training step.
+    # From this moment, model averaging should run after the optimizer step,
+    # to globally allreduce all the parameters.
+    if state.subgroup is None:
+        state.subgroup, _ = dist.new_subgroups()
+    return default._allreduce_fut(state.subgroup, input_tensor)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/powerSGD_hook.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/powerSGD_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..96b3b888511ae0d314b7dfb5de0112128b6895d2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/powerSGD_hook.py
@@ -0,0 +1,856 @@
+# mypy: allow-untyped-defs
+import logging
+import math
+from collections import defaultdict
+from typing import Dict
+
+import torch
+import torch.distributed as dist
+from torch.distributed import distributed_c10d
+
+from . import default_hooks as default
+
+
+__all__ = ["PowerSGDState", "powerSGD_hook", "batched_powerSGD_hook"]
+
+logger = logging.getLogger(__name__)
+
+
+def _orthogonalize(matrices, epsilon=0):
+    """
+    Decide between Gram-Schmidt or QR factorization to orthogonalize a batch of matrices.
+
+    QR factorization doesn't work with half-precision, but it is usually faster with a rank > 2.
+    """
+    assert len(matrices.shape) == 3 and matrices.shape[2] <= matrices.shape[1]
+
+    num_matrices = matrices.shape[0]
+    rank = matrices.shape[2]
+    dtype = matrices.dtype
+    if rank <= 2 or dtype in [torch.float16, torch.bfloat16]:
+        _orthogonalize_gram_schmidt(matrices, epsilon=epsilon)
+    else:
+        torch.linalg.qr(
+            matrices,
+            out=(
+                matrices,
+                torch.empty(
+                    num_matrices, rank, rank, device=matrices.device, dtype=dtype
+                ),
+            ),
+        )
+
+
+def _orthogonalize_gram_schmidt(matrices, epsilon=0):
+    """
+    Apply Gram-Schmidt procedure to orthogonalize a batch of matrices.
+
+    If epsilon is 0, this is equivalent to `torch.qr(matrices, out=(matrices, _))`,
+    """
+    num_cols = matrices.shape[2]
+    for i in range(num_cols):
+        # Normalize the i'th column.
+        col = matrices[:, :, i : i + 1]
+        # If no epsilon is added here, division by zero may be caused by vanishing gradients.
+        # This epsilon is not needed if the input batch of matrices covers the gradients of at least one entire layer
+        # in the neural network.
+        if epsilon == 0:
+            # Note that col ** 2 can underflow/overflow if we use FP16.
+            # May need to consider multiplying a scaling factor and dividing it later, or using bfloat16 instead.
+            try:
+                col /= torch.norm(col, dim=1, keepdim=True)
+            except ZeroDivisionError:
+                logger.error(
+                    "The matrices to be orthogonalized has at least a column of all 0s. Please set a small value such as 1e-8 "
+                    "as `orthogonalization_epsilon` in PowerSGD state."
+                )
+                # Recover the values from NaNs to 0s.
+                col.fill_(0.0)
+        else:
+            col /= torch.norm(col, dim=1, keepdim=True) + epsilon
+        # Project it on the rest and remove it.
+        if i + 1 < num_cols:
+            rest = matrices[:, :, i + 1 :]
+            rest -= torch.sum(col * rest, dim=1, keepdim=True) * col
+
+
+def _should_compress(
+    num_rows, num_cols, matrix_approximation_rank, min_compression_rate
+):
+    """
+    Recommend if tensor given is worth compressing.
+
+    Returns a recommendation as to whether the 2D tensor described by the arguments is worth compressing,
+    including statistics describing the expected savings from compression.  We consider a tensor worth
+    compressing when ``min_compression_rate`` < uncompressed size / compressed size, where
+    uncompressed size = ``num_rows`` * ``num_cols``,
+    and compressed size = (``num_rows`` + ``num_cols``) * ``matrix_approximation_rank``.
+
+    The result of this function is a tuple of the form (compression_recommendation, uncompressed_el_count, compressed_el_count), where:
+
+    compression_recommendation is true if the tensor is worth compressing, and false otherwise (see above);
+
+    uncompressed_el_count is the uncompressed element count, i.e. ``num_rows`` * ``num_cols``; and,
+
+    compress_el_count is the element count after compression, i.e. (``num_rows`` + ``num_cols``) * ``matrix_approximation_rank``.
+    """  # noqa: B950
+    uncompressed_size = num_rows * num_cols
+    compressed_size = (num_rows + num_cols) * matrix_approximation_rank
+    return (
+        compressed_size * min_compression_rate < uncompressed_size,
+        uncompressed_size,
+        compressed_size,
+    )
+
+
+def _report_compression_stats(bucket, state):
+    """Report compression stats at frequency of ``compression_stats_logging_frequency`` specified in PowerSGD state."""
+    if bucket.is_last() and state.iter >= state.next_stats_report:
+        stats = state.compression_stats()
+        logger.info(
+            "Compression stats: iter %s, total before compression %s, total after compression %s, "
+            "rate %s",
+            state.iter,
+            stats[1],
+            stats[2],
+            stats[0],
+        )
+        state.next_stats_report = state.iter + state.compression_stats_logging_frequency
+
+
+class PowerSGDState:
+    r"""
+    Store both the algorithm's hyperparameters and internal state for all gradients during training.
+
+    Particularly, ``matrix_approximation_rank`` and ``start_powerSGD_iter`` are the main hyperparameters that should be tuned by the user.
+    For performance, we suggest to keep binary hyperparameters ``use_error_feedback`` and ``warm_start`` on.
+
+    1. ``matrix_approximation_rank`` controls the size of compressed low-rank tensors, which determines the compression rate. The lower the rank, the stronger the compression.
+
+        1.1. If ``matrix_approximation_rank`` is too low, the full model quality will need more training steps to reach or will never reach and yield loss in accuracy.
+
+        1.2. The increase of ``matrix_approximation_rank`` can substantially increase the computation costs of the compression, and the accuracy may not be further improved beyond a certain ``matrix_approximation_rank`` threshold.
+
+    To tune ``matrix_approximation_rank``, we suggest to start from 1 and increase by factors of 2 (like an exponential grid search, 1, 2, 4, ...), until a satisfactory accuracy is reached. Typically only a small value 1-4 is used. For some NLP tasks (as shown in Appendix D of the original paper), this value has been increased to 32.
+
+    2. ``start_powerSGD_iter`` defers PowerSGD compression until step ``start_powerSGD_iter``, and vanilla allreduce runs prior to step ``start_powerSGD_iter``. This hybrid scheme of **vanilla allreduce + PowerSGD** can effectively improve the accuracy, even a relatively small ``matrix_approximation_rank`` is used. This is because that, the beginning of training phase is usually very sensitive to inaccurate gradients, and compressing gradients too early may make the training quickly take a suboptimal trajectory, which can result in an irrecoverable impact on the accuracy.
+
+    To tune ``start_powerSGD_iter``, we suggest to start with 10% of total training steps, and increase it until a satisfactory accuracy is reached. If there is a warm-up stage in the training, ``start_powerSGD_iter`` typically should be no less than the number of warm-up steps.
+
+    3. ``min_compression_rate`` is the minimum compression rate required when a layer is compressed. Due to the computation overheads incurred by the compression, a tensor is worth compressing only if there can be sufficient saving in bandwidth, where ``(num_rows + num_cols) * matrix_approximation_rank * min_compression_rate < num_rows * num_cols``. If the specified compression rate threshold cannot be satisfied, the tensor will be directly allreduced without compression.
+
+    Compression statistics are logged every ``compression_stats_logging_frequency`` iterations once PowerSGD compression starts.
+
+    4. ``orthogonalization_epsilon`` can be a very small value (e.g., 1e-8) added to every normalized matrix column in orthogonalization step, to prevent div-by-zero error if any column has all 0s. If this can already be prevented (e.g., by batch normalization), an epsilon of 0 is recommended for accuracy.
+
+    5. ``batch_tensors_with_same_shape`` controls whether to compress and decompress tensors with same shape in a batched operation to achieve higher parallelism. Note that you should also increase the bucket size (i.e., ``bucket_cap_mb`` arg in DDP constructor) to make more same-shaped tensors appear in the same bucket, however this may reduce the overlap between computation and communication, and increase the memory footprint due to stacking the tensors of the same shape. Set to ``True`` if the compression / decompression computation is a bottleneck.
+
+    .. warning ::
+        If error feedback or warm-up is enabled, the minimum value of ``start_powerSGD_iter`` allowed in DDP is 2.
+        This is because there is another internal optimization that rebuilds buckets at iteration 1 in DDP,
+        and this can conflict with any tensor memorized before the rebuild process.
+    """  # noqa: B950
+
+    __slots__ = [
+        "process_group",
+        # The fields below are the hyperparameters that often need to be tuned by the user.
+        "matrix_approximation_rank",
+        "start_powerSGD_iter",
+        # The fields below are the hyperparameters that seldom need be tuned by the user.
+        "min_compression_rate",
+        "orthogonalization_epsilon",
+        # The fields below are the binary hyperparameters recommended to be turned on for performance and accuracy.
+        "use_error_feedback",
+        "warm_start",
+        "batch_tensors_with_same_shape",
+        # The fields below are internal state.
+        "rng",
+        "error_dict",
+        "p_memory_dict",
+        "q_memory_dict",
+        "iter",
+        # The fields below are for recording compression stats.
+        "total_numel_before_compression",
+        "total_numel_after_compression",
+        "compression_stats_logging_frequency",
+        "next_stats_report",
+    ]
+
+    def __init__(
+        self,
+        process_group,
+        matrix_approximation_rank=1,
+        start_powerSGD_iter=1_000,
+        min_compression_rate=2,
+        use_error_feedback=True,
+        warm_start=True,
+        orthogonalization_epsilon=0,
+        random_seed=0,
+        compression_stats_logging_frequency=10_000,
+        batch_tensors_with_same_shape: bool = False,
+    ):
+        logger.info(
+            "PowerSGD config: matrix_approximation_rank = %s; start_powerSGD_iter = %s; "
+            "min_compression_rate = %s; orthogonalization_epsilon = %s; use_error_feedback = %s; warm_start = %s; "
+            "random_seed = %s; compression_stats_logging_frequency = %s; batch_tensors_with_same_shape = %s",
+            matrix_approximation_rank,
+            start_powerSGD_iter,
+            min_compression_rate,
+            orthogonalization_epsilon,
+            use_error_feedback,
+            warm_start,
+            random_seed,
+            compression_stats_logging_frequency,
+            batch_tensors_with_same_shape,
+        )
+
+        self.process_group = process_group
+        self.matrix_approximation_rank = matrix_approximation_rank
+        # Deferring PowerSGD compression util step 'start_powerSGD_iter' can have two advantages:
+        # 1) It turns out that PowerSGD may lead to a non-trivial accuracy loss,
+        # even if the matrix approximation rank is increased to a large value.
+        # To mitigate the accuracy loss, a simple yet effective way is mixing vanilla allreduce
+        # (or a more conservative compression such as FP16 compression) with PowerSGD.
+        # 2) There is an internal optimization of rebuilding buckets process in DDP,
+        # in order to save the memory space.
+        # This step takes place after the first iteration.
+        # However, this means that the shape of input bucketized tensors is subject to change,
+        # which will complicate the implementations of error feedback and warm-up.
+        # Running vanilla allreduce in the first few iterations can avoid this complexity.
+        if (use_error_feedback or warm_start) and start_powerSGD_iter <= 1:
+            raise ValueError(
+                "Expect `start_powerSGD_iter` > 1 if `use_error_feedback` or `warm_start` is enabled, "
+                "because PowerSGD can only be applied after the first two iterations in DDP."
+            )
+        self.start_powerSGD_iter = start_powerSGD_iter
+        self.min_compression_rate = min_compression_rate
+        # Error feedback is usually crucial for both for convergence and generalization,
+        # because PowerSGD is a biased compressor,
+        # i.e., compressing and decompressing a random gradient does not yield the original in expectation.
+        # This mechanism requires a temporary copy of the input gradients,
+        # so it increases the peak memory consumption by the size of the gradient tensor.
+        # However, if the target matrices are known to be exactly low-ranked (instead of just low stable rank),
+        # sometimes it is possible to converge to the optima without error feedback.
+        # See: http://proceedings.mlr.press/v54/yurtsever17a/yurtsever17a.pdf
+        self.use_error_feedback = use_error_feedback
+        # Warm-start reuses P(s) and Q(s) from the previous iteration.
+        # This can improve the approximation quality and hence improve the accuracy.
+        # Additionally, by avoiding the initialization of these low-rank tensors at every step,
+        # this can also accelerate training.
+        # However, this is at the cost of extra memory.
+        self.warm_start = warm_start
+        # Can use a very small value to prevent div-by-zero error caused by orthogonalization of vanishing gradients.
+        self.orthogonalization_epsilon = orthogonalization_epsilon
+        # The purpose of this RNG is to generate different random seeds for initializing Q across iterations,
+        # but in the same order for all the DDP replicas.
+        # Different random seeds across iterations indicate different 'projections' of the gradients at different SGD steps.
+        # If the same random projection is used,
+        # there will be differences between the gradients that are never synchronized.
+        import numpy as np
+
+        self.rng = np.random.RandomState(random_seed)
+        # Since there is only a single state instance for all the input buckets,
+        # need to maintain a dictionary that maps each bucket index to the local error.
+        self.error_dict: Dict[int, torch.Tensor] = {}
+        self.p_memory_dict: Dict[int, torch.Tensor] = {}
+        self.q_memory_dict: Dict[int, torch.Tensor] = {}
+        # Iteration/step in the training loop.
+        self.iter = 0
+        # Compression stats accumulators
+        self.total_numel_before_compression = 0
+        self.total_numel_after_compression = 0
+        # We'll report compression stats every 'compression_stats_logging_frequency' iterations
+        # Note that we always report compression stats at least once.
+        self.compression_stats_logging_frequency = max(
+            1, compression_stats_logging_frequency
+        )
+        self.next_stats_report = 0
+        # Batching tensors with same shape can increase parallelism in compression / decompression computation.
+        # This requires a larger bucket size to make more same-shaped tensor to appear in one bucket, however
+        # this may reduce the overlap between computation and communication, and increase the memory footprint
+        # due to stacking tensors.
+        # Turn on if compression / decompression computation is a bottleneck.
+        self.batch_tensors_with_same_shape = batch_tensors_with_same_shape
+
+    def __getstate__(self):
+        r"""
+        Return a ``Dict[str, Any]`` which will be pickled and saved.
+
+        ``process_group`` is not serializable and excluded from
+        a returned state.
+        """
+        logger.warning(
+            "NOTE: Process group is not serializable and excluded from a saved state."
+        )
+        return {
+            slot: getattr(self, slot)
+            for slot in self.__slots__
+            if slot != "process_group"
+        }
+
+    def __setstate__(self, state):
+        r"""
+        Take a provided ``state`` and set to this ``PowerSGDState`` instance.
+
+        ``process_group`` is set to default.
+        """
+        self.process_group = distributed_c10d._get_default_group()
+        logger.warning(
+            "NOTE: Process group will be set to a default group (i.e. the world size).\
+                If a different group is desired, please set `self.process_group` after PowerSGD state is loaded."
+        )
+        for slot, value in state.items():
+            setattr(self, slot, value)
+
+    def maybe_increase_iter(self, bucket):
+        """Track iterations and trigger log message at start of local SGD."""
+        # Since bucket 0 is the last bucket to allreduce in an iteration.
+        # Only increase `iter` when bucket 0 is processed.
+        if bucket.is_last():
+            self.iter += 1
+
+        if self.iter == self.start_powerSGD_iter:
+            logger.info("Start to apply PowerSGD after %s iterations.", self.iter)
+
+    def compression_stats(self):
+        r"""
+        Return latest compression statistics as tuple.
+
+        Returns tuple of form (compress_rate, numel_before_compression, numel_after_compression) where:
+
+        compress_rate is the effective compression rate i.e. (number of elements before compression) / (number of elements after compression);
+
+        numel_before_compression is the total number of elements before compression was applied; and,
+
+        numel_after_compression is the total number of elements after compression was applied.
+        """  # noqa: B950
+        compress_rate = (
+            self.total_numel_before_compression / self.total_numel_after_compression
+            if self.total_numel_after_compression > 0
+            else 0
+        )
+        return (
+            compress_rate,
+            self.total_numel_before_compression,
+            self.total_numel_after_compression,
+        )
+
+
+def powerSGD_hook(
+    state: PowerSGDState, bucket: dist.GradBucket
+) -> torch.futures.Future[torch.Tensor]:
+    r"""
+    Implement PowerSGD algorithm.
+
+    This DDP communication hook implements PowerSGD gradient compression
+    algorithm described in the `paper `_.
+    Once gradient tensors are aggregated across all workers, this hook applies
+    compression as follows:
+
+    1. Views the input flattened 1D gradient tensor as a list of per-parameter tensors, and divides all the tensors into two groups:
+
+        1.1 The tensors that should be compressed before allreduce, because the compression can give enough saving in bandwidth.
+
+        1.2 Rest of the tensors will be directly allreduced without compression, including all the vector tensors (for biases).
+
+    2. Handles uncompressed tensors:
+
+        2.1. Allocate contiguous memory for those uncompressed tensors, and allreduces all the uncompressed tensors as a batch, without compression;
+
+        2.2. Copies the individual uncompressed tensors from the contiguous memory back to the input tensor.
+
+    3. Handles the tensors that should be compressed by PowerSGD compression:
+
+        3.1. For each tensor M, creates two low-rank tensors P and Q for decomposing M,
+        such that M = PQ^T, where Q is initialized from a standard normal distribution and orthogonalized;
+
+        3.2. Computes each P in Ps, which is equal to MQ;
+
+        3.3. Allreduces Ps as a batch;
+
+        3.4. Orthogonalizes each P in Ps;
+
+        3.5. Computes each Q in Qs, which is approximately equal to M^TP;
+
+        3.6. Allreduces Qs as a batch;
+
+        3.7. Computes each M among all the compressed tensors, which is approximately equal to PQ^T.
+
+    Note that this communication hook enforces vanilla allreduce for the first ``state.start_powerSGD_iter`` iterations.
+    This not only gives the user more control over the tradeoff between speedup and accuracy,
+    but also helps abstract away some complexity of the internal optimization of DDP for future communication hook developers.
+
+    Args:
+        state (PowerSGDState): State information to configure the compression rate and support error feedback, warm start, etc.
+            To tune the compression configs, mainly need to tune ``matrix_approximation_rank``, ``start_powerSGD_iter``
+            and ``min_compression_rate``.
+        bucket (dist.GradBucket): Bucket that stores a 1D flattened gradient tensor that batches multiple per-variable tensors.
+            Note that since DDP comm hook only supports single process single device mode,
+            only exactly one tensor is stored in this bucket.
+
+    Returns:
+        Future handler of the communication, which updates the gradients in place.
+
+    Example::
+        >>> # xdoctest: +SKIP
+        >>> state = PowerSGDState(process_group=process_group, matrix_approximation_rank=1,
+                                  start_powerSGD_iter=10, min_compression_rate=0.5)
+        >>> ddp_model.register_comm_hook(state, powerSGD_hook)
+    """  # noqa: B950
+    process_group = state.process_group
+    group_to_use = process_group if process_group is not None else dist.group.WORLD
+    world_size = group_to_use.size()
+
+    # The input tensor is a flattened 1D tensor.
+    input_tensor = bucket.buffer()
+
+    # Run vanilla allreduce in the first `start_powerSGD_iter` iterations.
+    if state.iter < state.start_powerSGD_iter:
+        state.maybe_increase_iter(bucket)
+        return default._allreduce_fut(group_to_use, input_tensor)
+
+    # Apply PowerSGD after `start_powerSGD_iter` iterations.
+    device = input_tensor.device
+    dtype = input_tensor.dtype
+
+    # Incorporate the error from the previous state into the gradients.
+    bucket_index = bucket.index()
+    input_tensor_cp = None
+    total_length = input_tensor.shape[0]
+    if state.use_error_feedback:
+        if bucket_index in state.error_dict:
+            input_tensor.add_(state.error_dict[bucket_index])
+        else:
+            logger.info(
+                "A zero tensor of length %s that represents local error is created.",
+                total_length,
+            )
+            state.error_dict[bucket_index] = torch.zeros(
+                total_length, device=device, dtype=dtype
+            )
+
+        # Keep a copy of the input tensor,
+        # so that we can compute the local error caused by compression later,
+        # by comparing this copy and the input tensor updated after decompression.
+        input_tensor_cp = torch.clone(input_tensor).detach()
+
+    # Unflatten the input tensor into per-parameter tensors, for layer-wise compression.
+    tensors = bucket.gradients()
+
+    # Step I: Divide all the tensors into two groups,
+    # one will be compressed before allreduce and the other will be directly allreduced without compression.
+    tensors_to_compress, uncompressed_tensors = [], []
+    total_Ps_size = 0
+    total_Qs_size = 0
+    for tensor in tensors:
+        matrix = tensor.view(tensor.shape[0], -1)
+        n, m = matrix.shape
+        matrix_approximation_rank = min(n, m, state.matrix_approximation_rank)
+        compress_test = _should_compress(
+            n, m, matrix_approximation_rank, state.min_compression_rate
+        )
+        state.total_numel_before_compression += compress_test[1]
+        if compress_test[0]:
+            tensors_to_compress.append(matrix)
+            total_Ps_size += n * matrix_approximation_rank
+            total_Qs_size += m * matrix_approximation_rank
+            state.total_numel_after_compression += compress_test[2]
+        else:
+            uncompressed_tensors.append(tensor)
+            state.total_numel_after_compression += compress_test[1]
+
+    _report_compression_stats(bucket, state)
+
+    # Step II: Handle uncompressed tensors.
+    # Allocate contiguous memory for these tensors to allreduce efficiently.
+    uncompressed_tensors_memory = (
+        torch.cat([tensor.view(-1) for tensor in uncompressed_tensors])
+        if uncompressed_tensors
+        else torch.tensor([], device=device, dtype=dtype)
+    )
+
+    # Step III: Handle the tensors that should be compressed.
+    # Allocate contiguous memory for Ps and Qs to allreduce efficiently.
+    # If warm-start is enabled, reuse Ps and Qs from the previous iteration if possible.
+    # The memory spaces of Ps and Qs need to be allocated in the first iteration when PowerSGD is applied.
+    need_randomize_qs = False
+    if not state.warm_start or bucket_index not in state.p_memory_dict:
+        need_randomize_qs = True
+        # If warm-start is disabled, low-rank tensors will be initialized at every step.
+        # Only log this if warm-start to avoid spamming.
+        if state.warm_start:
+            logger.info(
+                "Allocating contiguous memory of length %s for Ps, and of length %s for Qs, respectively.",
+                total_Ps_size,
+                total_Qs_size,
+            )
+        state.p_memory_dict[bucket_index] = torch.empty(
+            total_Ps_size, device=device, dtype=dtype
+        )
+        state.q_memory_dict[bucket_index] = torch.empty(
+            total_Qs_size, device=device, dtype=dtype
+        )
+
+    # Batch tensors to compress by shape.
+    shape_to_tensors = defaultdict(list)
+    for tensor in tensors_to_compress:
+        shape_to_tensors[tensor.shape].append(tensor)
+
+    # This function decides whether to batch tensors with same shape or not according to the argument,
+    # so the following process could share the same code.
+    def maybe_batched_tensors_to_compress():
+        for tensors in shape_to_tensors.values():
+            if state.batch_tensors_with_same_shape:
+                batch_size = len(tensors)
+                if batch_size == 1:
+                    # Use the original tensor to avoid copy.
+                    yield tensors[0].unsqueeze(0)
+                else:
+                    yield torch.stack(tensors)
+            else:
+                for tensor in tensors:
+                    yield tensor.unsqueeze(0)
+
+    # Create Ps and Qs that point to the allocated memory.
+    tensors_to_compress = []
+    ps = []
+    qs = []
+    p_idx = 0
+    q_idx = 0
+    for tensor in maybe_batched_tensors_to_compress():
+        batch_size, n, m = tensor.shape
+        matrix_approximation_rank = min(n, m, state.matrix_approximation_rank)
+        tensors_to_compress.append(tensor)
+        ps.append(
+            state.p_memory_dict[bucket_index][
+                p_idx : p_idx + batch_size * n * matrix_approximation_rank
+            ].view(batch_size, n, matrix_approximation_rank)
+        )
+        qs.append(
+            state.q_memory_dict[bucket_index][
+                q_idx : q_idx + batch_size * m * matrix_approximation_rank
+            ].view(batch_size, m, matrix_approximation_rank)
+        )
+        p_idx += batch_size * n * matrix_approximation_rank
+        q_idx += batch_size * m * matrix_approximation_rank
+
+    # If warm-start is enabled, reuse Qs from the previous iteration if possible and skip filling random values.
+    # The exception is the first iteration when PowerSGD is applied.
+    if not need_randomize_qs:
+        for q in qs:
+            _orthogonalize(q, state.orthogonalization_epsilon)
+    else:
+        with torch.random.fork_rng(devices=[]):
+            # Fork this RNG to avoid changing the seed globally and affecting the random sampling anywhere else in the training.
+            # The seed makes sure that the initial random values are the same across all the DDP replicas.
+            # This seed should differ at every step.
+            # Since it is very slow to fork RNG state across all the CUDA devices,
+            # only fork on CPU and then move the generated tensor to the CUDA device (by overwriting q).
+            torch.manual_seed(state.rng.randint(1_000_000_000))
+            for q in qs:
+                q.copy_(
+                    torch.randn(
+                        *q.shape,
+                        device="cpu",
+                        dtype=dtype,
+                    )
+                )
+                _orthogonalize(q, state.orthogonalization_epsilon)
+
+    # Compute Ps.
+    for tensor, q, p in zip(tensors_to_compress, qs, ps):
+        torch.bmm(tensor, q, out=p)
+
+    # This allreduce is only applied to uncompressed tensors,
+    # so it should have been kicked off before the above computation on the compressed tensors to hide more communication costs.
+    # However, this somehow requires a separate future chain at this time.
+    allreduce_contiguous_uncompressed_tensors_fut = dist.all_reduce(
+        uncompressed_tensors_memory, group=group_to_use, async_op=True
+    ).get_future()
+
+    def unpack_uncompressed_tensors_and_allreduce_ps(fut):
+        uncompressed_tensors_memory = fut.value()[0].div_(world_size)
+        idx = 0
+        for tensor in uncompressed_tensors:
+            tensor.copy_(
+                uncompressed_tensors_memory[idx : idx + tensor.numel()].view_as(tensor)
+            )
+            idx += tensor.numel()
+
+        # Since these Ps will be orthogonalized later, no need to divide them by world size.
+        return (
+            dist.all_reduce(
+                state.p_memory_dict[bucket_index], group=group_to_use, async_op=True
+            )
+            .get_future()
+            .wait()[0]
+        )
+
+    def compute_qs(fut):
+        state.p_memory_dict[bucket_index] = fut.value()
+        for p in ps:
+            _orthogonalize(p, state.orthogonalization_epsilon)
+
+        # Compute Qs.
+        for tensor, p, q in zip(tensors_to_compress, ps, qs):
+            torch.bmm(tensor.transpose(1, 2), p, out=q)
+
+        # TODO: The above procedure does two matmul+allreduce steps per iteration --
+        # one left multiplication and one right multiplication.
+        # For warm-start, can take one such step at a time, and alternate between them.
+
+        # Allreduce Qs.
+        return (
+            dist.all_reduce(
+                state.q_memory_dict[bucket_index], group=group_to_use, async_op=True
+            )
+            .get_future()
+            .wait()[0]
+        )
+
+    def decompress(fut):
+        state.q_memory_dict[bucket_index] = fut.value().div_(world_size)
+
+        for p, q, tensor in zip(ps, qs, tensors_to_compress):
+            torch.bmm(p, q.transpose(1, 2), out=tensor)
+
+        # Copy batched tensors back to original buffer.
+        if state.batch_tensors_with_same_shape:
+            for tensor in tensors_to_compress:
+                if tensor.shape[0] == 1:
+                    # Skip tensor with batch_size == 1 since itself is the original tensor.
+                    continue
+                original_tensors = shape_to_tensors[tensor.shape[1:]]
+                for i, original_tensor in enumerate(original_tensors):
+                    original_tensor.copy_(tensor[i])
+
+        if torch.cuda.is_available():
+            torch.cuda.synchronize(device)
+
+        if state.use_error_feedback:
+            # Memorize the local errors.
+            state.error_dict[bucket_index] = input_tensor_cp - input_tensor
+        if not state.warm_start:
+            state.p_memory_dict.clear()
+            state.q_memory_dict.clear()
+
+        state.maybe_increase_iter(bucket)
+
+        return input_tensor
+
+    return (
+        allreduce_contiguous_uncompressed_tensors_fut.then(
+            unpack_uncompressed_tensors_and_allreduce_ps
+        )
+        .then(compute_qs)
+        .then(decompress)
+    )
+
+
+def batched_powerSGD_hook(
+    state: PowerSGDState, bucket: dist.GradBucket
+) -> torch.futures.Future[torch.Tensor]:
+    r"""
+    Implement simplified PowerSGD algorithm.
+
+    This DDP communication hook implements a simplified PowerSGD gradient compression
+    algorithm described in the `paper `_.
+    This variant does not compress the gradients layer by layer,
+    but instead compresses the flattened input tensor that batches all the gradients.
+    Therefore, it is **faster** than :meth:`powerSGD_hook`,
+    but usually results in a **much lower accuracy**, unless ``matrix_approximation_rank`` is 1.
+
+    .. warning ::
+        Increasing ``matrix_approximation_rank`` here may not necessarily increase the accuracy,
+        because batching per-parameter tensors without column/row alignment can destroy low-rank structure.
+        Therefore, the user should always consider :meth:`powerSGD_hook` first,
+        and only consider this variant when a satisfactory accuracy can be achieved when ``matrix_approximation_rank`` is 1.
+
+    Once gradient tensors are aggregated across all workers, this hook applies
+    compression as follows:
+
+    1. Views the input flattened 1D gradient tensor as a square-shaped tensor M with 0 paddings;
+
+    2. Creates two low-rank tensors P and Q for decomposing M, such that M = PQ^T, where Q is initialized from a standard normal distribution and orthogonalized;
+
+    3. Computes P, which is equal to MQ;
+
+    4. Allreduces P;
+
+    5. Orthogonalizes P;
+
+    6. Computes Q, which is approximately equal to M^TP;
+
+    7. Allreduces Q;
+
+    8. Computes M, which is approximately equal to PQ^T.
+
+    9. Truncates the input tensor to the original length.
+
+    Note that this communication hook enforces vanilla allreduce for the first ``state.start_powerSGD_iter`` iterations.
+    This not only gives the user more control over the tradeoff between speedup and accuracy,
+    but also helps abstract away some complexity of the internal optimization of DDP for future communication hook developers.
+
+    Args:
+        state (PowerSGDState): State information to configure the compression rate and support error feedback, warm start, etc.
+            To tune the compression configs, mainly need to tune ``matrix_approximation_rank`` and ``start_powerSGD_iter``.
+        bucket (dist.GradBucket): Bucket that stores a 1D flattened gradient tensor that batches multiple per-variable tensors.
+            Note that since DDP comm hook only supports single process single device mode,
+            only exactly one tensor is stored in this bucket.
+
+    Returns:
+        Future handler of the communication, which updates the gradients in place.
+
+    Example::
+        >>> # xdoctest: +SKIP
+        >>> state = PowerSGDState(process_group=process_group, matrix_approximation_rank=1)
+        >>> ddp_model.register_comm_hook(state, batched_powerSGD_hook)
+    """  # noqa: B950
+    process_group = state.process_group
+    group_to_use = process_group if process_group is not None else dist.group.WORLD
+    world_size = group_to_use.size()
+
+    # The input tensor is a flattened 1D tensor.
+    input_tensor = bucket.buffer()
+
+    # Run vanilla allreduce in the first `start_powerSGD_iter` iterations.
+    if state.iter < state.start_powerSGD_iter:
+        state.maybe_increase_iter(bucket)
+        return default._allreduce_fut(group_to_use, input_tensor)
+
+    # Apply PowerSGD after `start_powerSGD_iter` iterations.
+    device = input_tensor.device
+    total_length = input_tensor.shape[0]
+    state.total_numel_before_compression += total_length
+
+    # View the input tensor as a 2D square-shape tensor, and pad 0s if necessary.
+    square_side_length = math.ceil(math.sqrt(total_length))
+    state.total_numel_after_compression += (
+        square_side_length * state.matrix_approximation_rank * 2
+    )
+    padded_total_length = square_side_length**2
+    input_tensor.resize_(padded_total_length)
+    input_tensor[total_length:padded_total_length].fill_(0)
+
+    _report_compression_stats(bucket, state)
+
+    # Incorporate the error from the previous state into the gradients.
+    bucket_index = bucket.index()
+    input_tensor_cp = None
+    if state.use_error_feedback:
+        if bucket_index in state.error_dict:
+            input_tensor.add_(state.error_dict[bucket_index])
+        else:
+            logger.info(
+                "A zero tensor of length %s that represents local error is created.",
+                padded_total_length,
+            )
+            state.error_dict[bucket_index] = torch.zeros(
+                padded_total_length, device=device, dtype=input_tensor.dtype
+            )
+
+        # Keep a copy of the input tensor,
+        # so that we can compute the local error caused by compression later,
+        # by comparing this copy and the input tensor updated after decompression.
+        input_tensor_cp = torch.clone(input_tensor).detach()
+    matrix = input_tensor.view(square_side_length, square_side_length)
+
+    # Reuse P and Q from the previous iteration if possible.
+    # The memory spaces of P and Q need to be allocated in the first iteration when PowerSGD is applied.
+    if not state.warm_start or bucket_index not in state.p_memory_dict:
+        # If warm-start is disabled, low-rank tensors will be initialized at every step.
+        # Only log this if warm-start to avoid spamming.
+        if state.warm_start:
+            logger.info(
+                "Initializing low-rank tensors P and Q, each of which has a shape of %s x %s.",
+                square_side_length,
+                state.matrix_approximation_rank,
+            )
+
+        def create_low_rank_tensor(fill_random_values, rng):
+            """Return a low-rank 2D tensor of square_side_length * matrix_approximation_rank."""
+            if fill_random_values:
+                with torch.random.fork_rng(devices=[]):
+                    # Fork this RNG to avoid changing the seed globally and affecting the random sampling
+                    # anywhere else in the training.
+                    # The seed makes sure that the initial random values are the same across all the DDP replicas.
+                    # This seed should differ at every step.
+                    # Since it is very slow to fork RNG state across all the CUDA devices,
+                    # only fork on CPU and then move the generated tensor to the CUDA device.
+                    torch.manual_seed(rng.randint(1_000_000_000))
+                    return torch.randn(
+                        square_side_length,
+                        state.matrix_approximation_rank,
+                        device="cpu",
+                        dtype=input_tensor.dtype,
+                    ).to(device)
+            else:
+                return torch.empty(
+                    square_side_length,
+                    state.matrix_approximation_rank,
+                    device=device,
+                    dtype=input_tensor.dtype,
+                )
+
+        state.p_memory_dict[bucket_index] = create_low_rank_tensor(
+            fill_random_values=False, rng=state.rng
+        )
+        state.q_memory_dict[bucket_index] = create_low_rank_tensor(
+            fill_random_values=True, rng=state.rng
+        )
+    _orthogonalize(state.q_memory_dict[bucket_index])
+
+    torch.matmul(
+        matrix, state.q_memory_dict[bucket_index], out=state.p_memory_dict[bucket_index]
+    )
+    allreduce_p_fut = dist.all_reduce(
+        state.p_memory_dict[bucket_index], group=group_to_use, async_op=True
+    ).get_future()
+
+    def compute_q(fut):
+        state.p_memory_dict[bucket_index] = fut.value()[0]
+        _orthogonalize(state.p_memory_dict[bucket_index])
+
+        torch.matmul(
+            matrix.t(),
+            state.p_memory_dict[bucket_index],
+            out=state.q_memory_dict[bucket_index],
+        )
+
+        # TODO: The above procedure does two matmul+allreduce steps per iteration --
+        # one left multiplication and one right multiplication.
+        # For warm-start, can take one such step at a time, and alternate between them.
+
+        return (
+            dist.all_reduce(
+                state.q_memory_dict[bucket_index], group=group_to_use, async_op=True
+            )
+            .get_future()
+            .wait()[0]
+        )
+
+    def decompress(fut):
+        state.q_memory_dict[bucket_index] = fut.value().div_(world_size)
+        torch.matmul(
+            state.p_memory_dict[bucket_index],
+            state.q_memory_dict[bucket_index].t(),
+            out=matrix,
+        )
+
+        if state.use_error_feedback:
+            # Memorize the local errors.
+            state.error_dict[bucket_index] = input_tensor_cp - input_tensor
+        # Removing this seemingly unnecessary sync somehow may cause failures.
+        # See: https://github.com/pytorch/pytorch/pull/54838
+        if torch.cuda.is_available():
+            torch.cuda.synchronize(device)
+        if not state.warm_start:
+            state.p_memory_dict.clear()
+            state.q_memory_dict.clear()
+        ret = input_tensor.resize_(total_length)
+
+        state.maybe_increase_iter(bucket)
+
+        return ret
+
+    return allreduce_p_fut.then(compute_q).then(decompress)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/quantization_hooks.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/quantization_hooks.py
new file mode 100644
index 0000000000000000000000000000000000000000..cbc1290e76e4e1d2e4d5d191b9ff41b643ff4cd7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/ddp_comm_hooks/quantization_hooks.py
@@ -0,0 +1,218 @@
+# mypy: allow-untyped-defs
+import torch
+import torch.distributed as dist
+from torch import nn
+
+
+def _quantize_per_tensor_cuda(x, scale, zero_point):
+    y = torch.round(x / scale) + zero_point
+    y = torch.clamp(y, 0, 255).to(torch.uint8)
+    return y
+
+
+def _dequantize_per_tensor_cuda(y, scale, zero_point):
+    x = scale * (y.to(torch.float32) - zero_point)
+    return x
+
+
+def _quantize_per_channel_cuda(x, scale, zero_point):
+    y = torch.zeros(x.size(), device=x.device)
+    for i in range(x.size()[0]):
+        y[i, :] = torch.round(x[i, :] / scale[i]) + zero_point[i]
+    y = torch.clamp(y, 0, 255).to(torch.uint8)
+    return y
+
+
+def _dequantize_per_channel_cuda(y, scale, zero_point):
+    y = y.to(torch.float32).cuda(y.device)
+    x = torch.zeros_like(y, device=y.device)
+    for i in range(x.size()[0]):
+        x[i, :] = scale[i] * (y[i, :] - zero_point[i])
+    return x
+
+
+def _get_allgather_out_list(all_gather_in_list, world_size):
+    out_list = [
+        torch.zeros_like(
+            all_gather_in_list,
+            device=all_gather_in_list.device,
+            dtype=all_gather_in_list.dtype,
+        )
+        for _ in range(world_size)
+    ]
+    return out_list
+
+
+def quantization_pertensor_hook(
+    process_group: dist.ProcessGroup, bucket: dist.GradBucket
+) -> torch.futures.Future[torch.Tensor]:
+    """
+    Apply ``torch.quantize_per_tensor`` logic to DDP using ``allgather`` protocol.
+
+    Workers first allgather the scale and zero point of their own
+    ``GradBucket`` prior to the quantization. After all workers have that information,
+    the first ``then`` callback called ``quantize_and_allgather`` quantizes worker's
+    own gradient tensor, and uses ``allgather`` to communicate these across all workers.
+    The final ``then`` callback called ``dequantize_and_aggregate``, dequantizes and
+    aggregates each quantized gradient tensor locally and returns the mean.
+
+    .. warning ::
+        This is experimental, and uses ``allgather`` protocol which is considerably slower than
+        ``allreduce`` protocol. It works only with flattened grads.
+
+    Example::
+        >>> # xdoctest: +SKIP
+        >>> ddp_model.register_comm_hook(process_group, quantization_pertensor_hook)
+    """
+    group_to_use = process_group if process_group is not None else dist.group.WORLD
+    rank = process_group.rank() if process_group is not None else dist.get_rank()
+    world_size = group_to_use.size()
+
+    tensor = bucket.buffer()
+
+    myObserver = torch.ao.quantization.MinMaxObserver().cuda(tensor.device)
+    myObserver(tensor)
+
+    s, z = myObserver.calculate_qparams()
+    s_and_z = torch.FloatTensor([s, z]).cuda(tensor.device)
+
+    all_ranks_s_and_z = _get_allgather_out_list(s_and_z, world_size)
+
+    # First, allgather scale and zeros.
+    fut = dist.all_gather(
+        all_ranks_s_and_z, s_and_z, group=group_to_use, async_op=True
+    ).get_future()
+
+    def quantize_and_allgather(fut):
+        # Store scale and zeros across all workers.
+        all_ranks_s_and_z = fut.wait()[0]
+        # All workers quantize their own ``GradBucket`` tensors.
+        quantized_tensor = _quantize_per_tensor_cuda(
+            tensor, all_ranks_s_and_z[rank][0], all_ranks_s_and_z[rank][1]
+        )
+        # Allgather quantized tensors.
+        fut = dist.all_gather(
+            _get_allgather_out_list(quantized_tensor, world_size),
+            quantized_tensor,
+            group=group_to_use,
+            async_op=True,
+        ).get_future()
+
+        return fut.wait()
+
+    def dequantize_and_aggregate(fut):
+        all_ranks_quantized_tensor = fut.wait()[0]
+
+        aggregated_dequantized_tensor = torch.zeros_like(
+            all_ranks_quantized_tensor[0], device=tensor.device, dtype=torch.float32
+        )
+        # Using previously allgathered scales and zeros, dequantize gradient tensors
+        # locally and then aggregate them.
+        for r, quantized_tensor in enumerate(all_ranks_quantized_tensor):
+            aggregated_dequantized_tensor += _dequantize_per_tensor_cuda(
+                quantized_tensor, all_ranks_s_and_z[r][0], all_ranks_s_and_z[r][1]
+            )
+
+        return aggregated_dequantized_tensor / world_size
+
+    return fut.then(quantize_and_allgather).then(dequantize_and_aggregate)
+
+
+def quantization_perchannel_hook(
+    process_group: dist.ProcessGroup, bucket: dist.GradBucket, bucket_size=512
+) -> torch.futures.Future[torch.Tensor]:
+    """
+    Apply``torch.quantize_per_channel`` logic to DDP using ``allgather`` protocol.
+
+    Compared to per-tensor, the main motivation of per-channel is
+    for considerably large tensors such as a tensor that contains 6 million
+    elements quantizing per a bucket size of 512 (or 128) elements may significantly
+    increase the resolution.
+
+    It first splits ``GradBucket`` tensor into multiple chunks (channels) of ``bucket_size``
+    elements. Then, workers allgather the scales and zero points of their own
+    ``GradBucket`` prior to the quantization. After all workers have that information,
+    the first ``then`` callback called ``quantize_and_allgather`` quantizes worker's
+    own gradient tensor, and uses ``allgather`` to communicate these across all workers.
+    The final ``then`` callback called ``dequantize_and_aggregate``, dequantizes, flattens, and
+    aggregates each quantized gradient tensor locally and returns the mean.
+
+    .. warning ::
+        This is experimental, and uses ``allgather`` protocol which is considerably slower than
+        ``allreduce`` protocol. It works only with flattened grads.
+
+    Example::
+        >>> # xdoctest: +SKIP
+        >>> ddp_model.register_comm_hook(process_group, quantization_perchannel_hook)
+    """
+    group_to_use = process_group if process_group is not None else dist.group.WORLD
+    rank = process_group.rank() if process_group is not None else dist.get_rank()
+    world_size = group_to_use.size()
+
+    tensor = bucket.buffer()
+
+    tensor_in_channels = (
+        nn.functional.pad(
+            input=tensor,
+            pad=(0, bucket_size - len(tensor) % bucket_size),
+            mode="constant",
+            value=0,
+        )
+        .view(-1, bucket_size)
+        .cuda(tensor.device)
+    )
+
+    myPerChannelObserver = torch.ao.quantization.PerChannelMinMaxObserver().cuda(
+        tensor.device
+    )
+    myPerChannelObserver(tensor_in_channels)
+
+    s_ch, z_ch = myPerChannelObserver.calculate_qparams()
+    s_and_z = torch.stack((s_ch, z_ch)).cuda(tensor.device)
+
+    all_ranks_s_and_z = _get_allgather_out_list(s_and_z, world_size)
+    # First, allgather scale and zeros.
+    fut = dist.all_gather(
+        all_ranks_s_and_z, s_and_z, group=group_to_use, async_op=True
+    ).get_future()
+
+    def quantize_and_allgather(fut):
+        # Store scale and zeros across all workers.
+        all_ranks_s_and_z = fut.wait()[0]
+        # All workers quantize their corresponding ``GradBucket`` tensors.
+        quantized_tensor = _quantize_per_channel_cuda(
+            tensor_in_channels,
+            all_ranks_s_and_z[rank, 0, :],
+            all_ranks_s_and_z[rank, 1, :],
+        )
+        # Allgather quantized tensors.
+        fut = dist.all_gather(
+            _get_allgather_out_list(quantized_tensor, world_size),
+            quantized_tensor,
+            group=group_to_use,
+            async_op=True,
+        ).get_future()
+
+        return fut.wait()
+
+    def dequantize_and_aggregate(fut):
+        all_ranks_quantized_tensor = fut.wait()[0]
+
+        aggregated_dequantized_tensor = torch.zeros_like(
+            all_ranks_quantized_tensor[0], device=tensor.device, dtype=torch.float32
+        )
+        # Using previously allgathered scales and zeros, dequantize gradient tensors
+        # locally and then aggregate them.
+        for r, quantized_tensor in enumerate(all_ranks_quantized_tensor):
+            aggregated_dequantized_tensor += _dequantize_per_channel_cuda(
+                quantized_tensor, all_ranks_s_and_z[r][0], all_ranks_s_and_z[r][1]
+            )
+
+        return (
+            torch.flatten(aggregated_dequantized_tensor).cuda(tensor.device)[
+                : tensor.size()[0]
+            ]
+            / world_size
+        )
+
+    return fut.then(quantize_and_allgather).then(dequantize_and_aggregate)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/join.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/join.py
new file mode 100644
index 0000000000000000000000000000000000000000..90c679e2c2f2a4ddb80130ac623f20d6d5e25691
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/join.py
@@ -0,0 +1,349 @@
+# mypy: allow-untyped-defs
+import warnings
+from abc import ABC, abstractmethod
+from types import TracebackType
+from typing import Any, List, NamedTuple, Optional, Type
+
+import torch
+import torch.distributed as dist
+
+
+__all__ = ["JoinHook", "Joinable", "Join"]
+
+
+class JoinHook:
+    r"""
+    This defines a join hook, which provides two entry points in the join context manager.
+
+    Entry points : a main hook, which is called repeatedly while there exists a non-joined
+    process, and a post-hook, which is called once all processes have joined.
+
+    To implement a join hook for the generic join context manager, define a
+    class that inherits from :class:`JoinHook` and override ``main_hook()`` and
+    ``post_hook()`` as appropriate.
+    """
+
+    def main_hook(self) -> None:
+        r"""Call this hook while there exists a non-joined process to shadow collective communications in a training iteration.
+
+        Training iteration i.e., in one forward pass, backward pass, and optimizer step.
+        """
+
+    def post_hook(self, is_last_joiner: bool) -> None:
+        r"""
+        Call hook after all processes have joined.
+
+        It is passed an additional ``bool`` argument ``is_last_joiner``, which indicates if the rank is one of the last to join.
+
+        Arguments:
+            is_last_joiner (bool): ``True`` if the rank is one of the last to
+                join; ``False`` otherwise.
+        """
+
+
+class Joinable(ABC):
+    r"""
+    This defines an abstract base class for joinable classes.
+
+    A joinable class
+    (inheriting from :class:`Joinable`) should implement :meth:`join_hook`,
+    which returns a :class:`JoinHook` instance, in addition to
+    :meth:`join_device` and :meth:`join_process_group` that return device and
+    process group information, respectively.
+    """
+
+    @abstractmethod
+    def __init__(self) -> None:
+        super().__init__()
+        self._join_config = _JoinConfig.construct_disabled_join_config()
+
+    @abstractmethod
+    def join_hook(self, **kwargs) -> JoinHook:
+        r"""
+        Return a :class:`JoinHook` instance for the given :class:`Joinable`.
+
+        Arguments:
+            kwargs (dict): a :class:`dict` containing any keyword arguments
+                to modify the behavior of the join hook at run time; all
+                :class:`Joinable` instances sharing the same join context
+                manager are forwarded the same value for ``kwargs``.
+        """
+        ...
+
+    @property
+    @abstractmethod
+    def join_device(self) -> torch.device:
+        r"""Return the device from which to perform collective communications needed by the join context manager."""
+        ...
+
+    @property
+    @abstractmethod
+    def join_process_group(self) -> Any:
+        r"""Returns the process group for the collective communications needed by the join context manager itself."""
+        ...
+
+
+class _JoinConfig(NamedTuple):
+    r"""This includes all fields needed from a :class:`Joinable` instance for the join context manager side."""
+
+    enable: bool
+    throw_on_early_termination: bool
+    is_first_joinable: bool
+
+    @staticmethod
+    def construct_disabled_join_config():
+        r"""Return a :class:`_JoinConfig` instance indicating that join-related logic should be disabled.
+
+        e.g. if the caller is not in a join context manager.
+        """
+        return _JoinConfig(
+            enable=False, throw_on_early_termination=False, is_first_joinable=False
+        )
+
+
+class Join:
+    r"""
+    This class defines the generic join context manager, which allows custom hooks to be called after a process joins.
+
+    These hooks should shadow the
+    collective communications of non-joined processes to prevent hanging and
+    erroring and to ensure algorithmic correctness. Refer to :class:`JoinHook`
+    for details about the hook definition.
+
+    .. warning::
+        The context manager requires each participating :class:`Joinable` to
+        call the method :meth:`notify_join_context()` before its own per-
+        iteration collective communications to ensure correctness.
+
+    .. warning::
+        The context manager requires that all ``process_group`` attributes in
+        the :class:`JoinHook` objects are the same. If there are multiple
+        :class:`JoinHook` objects, then the ``device`` of the first is used.
+        The process group and device information is used for checking for non-
+        joined processes and for notifying processes to throw an exception if
+        ``throw_on_early_termination`` is enabled, both of which using an all-
+        reduce.
+
+    Arguments:
+        joinables (List[Joinable]): a list of the participating
+            :class:`Joinable` s; their hooks are iterated over in the given
+            order.
+
+        enable (bool): a flag enabling uneven input detection; setting to
+            ``False`` disables the context manager's functionality and should
+            only be set when the user knows the inputs will not be uneven
+            (default: ``True``).
+
+        throw_on_early_termination (bool): a flag controlling whether to throw an
+            exception upon detecting uneven inputs (default: ``False``).
+
+    Example::
+
+        >>> import os
+        >>> import torch
+        >>> import torch.distributed as dist
+        >>> import torch.multiprocessing as mp
+        >>> # xdoctest: +SKIP
+        >>> import torch.nn.parallel.DistributedDataParallel as DDP
+        >>> import torch.distributed.optim.ZeroRedundancyOptimizer as ZeRO
+        >>> from torch.distributed.algorithms.join import Join
+        >>>
+        >>> # On each spawned worker
+        >>> def worker(rank):
+        >>>     dist.init_process_group("nccl", rank=rank, world_size=2)
+        >>>     model = DDP(torch.nn.Linear(1, 1).to(rank), device_ids=[rank])
+        >>>     optim = ZeRO(model.parameters(), torch.optim.Adam, lr=0.01)
+        >>>     # Rank 1 gets one more input than rank 0
+        >>>     inputs = [torch.tensor([1.]).to(rank) for _ in range(10 + rank)]
+        >>>     with Join([model, optim]):
+        >>>         for input in inputs:
+        >>>             loss = model(input).sum()
+        >>>             loss.backward()
+        >>>             optim.step()
+        >>>     # All ranks reach here without hanging/erroring
+    """
+
+    def __init__(
+        self,
+        joinables: List[Joinable],
+        enable: bool = True,
+        throw_on_early_termination: bool = False,
+        **kwargs,
+    ):
+        if len(joinables) == 0:
+            raise ValueError("The join context manager requires at least one joinable")
+        self._joinables = joinables
+        self._join_hooks = [
+            joinable.join_hook(**kwargs) for joinable in self._joinables
+        ]
+        self._enable = enable
+        self._throw_on_early_termination = throw_on_early_termination
+        self._set_joinable_configs()
+        self._extract_dist_info()
+
+    def _set_joinable_configs(self) -> None:
+        r"""Set the :class:`_JoinConfig` of each participating :class:`Joinable`."""
+        assert len(self._joinables) > 0
+        is_first_joinable = True
+        for joinable in self._joinables:
+            joinable._join_config = _JoinConfig(
+                enable=self._enable,
+                throw_on_early_termination=self._throw_on_early_termination,
+                is_first_joinable=is_first_joinable,
+            )
+            is_first_joinable = False
+
+    def _extract_dist_info(self) -> None:
+        r"""
+        Extract the process group and device information from the joinables.
+
+        If there are multiple joinables, then the context manager uses the
+        first specified device.
+
+        Preconditions:
+            ``self._joinables`` is not ``None`` and is non-empty.
+
+        Raises:
+            ValueError
+                If there are multiple conflicting ``process_group`` attributes
+                among the ``Joinable`` objects.
+        """
+        process_group = None
+        device = None
+        for joinable in self._joinables:
+            if process_group is None:
+                process_group = joinable.join_process_group
+            elif process_group != joinable.join_process_group:
+                raise ValueError(
+                    "Using join context manager with multiple process groups"
+                )
+            if device is None:
+                device = joinable.join_device
+        self._process_group = process_group
+        self._rank = dist.get_rank(self._process_group)
+        self._device = device
+
+    def __enter__(self):
+        ...
+
+    def __exit__(
+        self,
+        type: Optional[Type[BaseException]],
+        value: Optional[BaseException],
+        traceback: Optional[TracebackType],
+    ):
+        r"""
+        Repeatedly runs the main hooks until all processes join; then, runs the post-hooks.
+
+        Raises:
+            RuntimeError
+                If ``throw_on_early_termination=True``.
+        """
+        if not self._enable or type:
+            return  # propagate the exception directly if one was raised
+
+        all_procs_joined = False
+        is_last_joiner = True
+
+        i = 0
+        WARN_THRESHOLD = 1000
+        warnings.simplefilter("once")
+
+        while not all_procs_joined:
+            if i > WARN_THRESHOLD:
+                warnings.warn(
+                    "Detected uneven input skew of greater than "
+                    f"{WARN_THRESHOLD}. This means that rank "
+                    f"{self._rank} has at least {WARN_THRESHOLD} "
+                    f"fewer inputs than other currently-active ranks. "
+                    "This level of skew could lead to performance "
+                    "degradation during training."
+                )
+            # Shadow the all-reduce in non-joined processes
+            num_nonjoined_procs = self._get_num_nonjoined_procs()
+            if num_nonjoined_procs == 0:
+                all_procs_joined = True
+            else:
+                if self._throw_on_early_termination:
+                    self._notify_procs_to_terminate()
+
+                # Run main hooks
+                for join_hook in self._join_hooks:
+                    join_hook.main_hook()
+
+                is_last_joiner = False
+                i += 1
+
+        # Run post-hooks
+        for join_hook in self._join_hooks:
+            join_hook.post_hook(is_last_joiner)
+
+    def _get_num_nonjoined_procs(self):
+        r"""Return the number of non-joined processes by shadowing an all-reduce in the non-joined processes."""
+        num_nonjoined_procs = torch.zeros(1, device=self._device)
+        dist.all_reduce(num_nonjoined_procs, group=self._process_group)
+        return num_nonjoined_procs.item()
+
+    def _notify_procs_to_terminate(self):
+        r"""Schedule an all-reduce to notify non-joined processes to terminate.
+
+        Also raise a ``RuntimeError`` indicating that the current process has exhausted its inputs.
+        """
+        ones = torch.ones(1, device=self._device)
+        dist.all_reduce(ones, group=self._process_group)
+        raise RuntimeError(f"Rank {self._rank} exhausted all inputs.")
+
+    @staticmethod
+    def notify_join_context(joinable: Joinable):
+        r"""
+        Notifies the join context manager that the calling process has not yet joined.
+
+        Then, if ``throw_on_early_termination=True``, checks if uneven inputs have been detected
+        (i.e. if one process has already joined) and throws an exception if so.
+
+        This method should be called from a :class:`Joinable` object before
+        its per-iteration collective communications. For example, this should
+        be called at the beginning of the forward pass in
+        :class:`DistributedDataParallel`.
+
+        Only the first :class:`Joinable` object passed into the context
+        manager performs the collective communications in this method, and
+        for the others, this method is vacuous.
+
+        Arguments:
+            joinable (Joinable): the :class:`Joinable` object calling this
+                method.
+
+        Returns:
+            An async work handle for the all-reduce meant to notify the context
+            manager that the process has not yet joined if ``joinable`` is the
+            first one passed into the context manager; ``None`` otherwise.
+        """
+        assert hasattr(joinable, "_join_config"), (
+            f"Check that the {type(joinable)} constructor calls the "
+            "``Joinable`` constructor"
+        )
+
+        join_config = joinable._join_config
+        # First joinable is responsible for the collective communications
+        if not join_config.is_first_joinable or not join_config.enable:
+            return None
+
+        device = joinable.join_device
+        process_group = joinable.join_process_group
+
+        # Schedule an all-reduce to indicate that the caller has not yet joined
+        ones = torch.ones(1, device=device)
+        work = dist.all_reduce(ones, group=process_group, async_op=True)
+
+        if join_config.throw_on_early_termination:
+            # Check if uneven inputs have been detected
+            zeros = torch.zeros(1, device=device)
+            dist.all_reduce(zeros, group=process_group)
+            should_throw = zeros.item()
+            if should_throw:
+                raise RuntimeError(
+                    "Detected at least one rank that exhausted inputs. "
+                    "Throwing across all ranks."
+                )
+        return work
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/model_averaging/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/model_averaging/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/model_averaging/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/model_averaging/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..861cbc1b9a521a1f7be469d6f6f8566ea48f99c6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/model_averaging/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/model_averaging/__pycache__/averagers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/model_averaging/__pycache__/averagers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..383eae54d8d2492e1d33a8a1e764de0a7151718d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/model_averaging/__pycache__/averagers.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/model_averaging/__pycache__/hierarchical_model_averager.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/model_averaging/__pycache__/hierarchical_model_averager.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0a0f681fcb8c844fcfc0cce3a455559cdaa8791e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/model_averaging/__pycache__/hierarchical_model_averager.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/model_averaging/__pycache__/utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/model_averaging/__pycache__/utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ec53dc9103bca2eec0abe2bcac4043f036f429ad
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/model_averaging/__pycache__/utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/model_averaging/averagers.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/model_averaging/averagers.py
new file mode 100644
index 0000000000000000000000000000000000000000..e15154e3f8578f2f70e2b215bd14906ef54a7437
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/model_averaging/averagers.py
@@ -0,0 +1,124 @@
+# mypy: allow-untyped-defs
+import warnings
+from abc import ABC, abstractmethod
+from typing import Dict, Iterable, Union
+
+import torch
+import torch.distributed as dist
+import torch.distributed.algorithms.model_averaging.utils as utils
+
+
+__all__ = ["ModelAverager", "PeriodicModelAverager"]
+
+
+class ModelAverager(ABC):
+    r"""Base class for all model averagers.
+
+    Args:
+        process_group: The process group to be used for all-reduce.
+                       If ``None``, the default process group, which
+                       is created by :func:`torch.distributed.init_process_group`,
+                       will be used. (default: ``None``)
+    """
+
+    def __init__(self, process_group=None):
+        self.process_group = (
+            process_group if process_group is not None else dist.group.WORLD
+        )
+        self.step = 0
+
+    @abstractmethod
+    def average_parameters(self, params):
+        raise NotImplementedError
+
+
+class PeriodicModelAverager(ModelAverager):
+    r"""
+    Averages parameters periodically after the warm-up stage.
+
+    This can be used for running `post-local SGD `_,
+    by running :class:`~torch.nn.DistributedDataParallel` (DDP)
+    using the subgroups created by :meth:`~torch.distributed.new_subgroups`.
+
+    Args:
+        period (int): The number of steps per model averaging.
+                      Usually the period should be greater than ``1`` to reduce the communication cost.
+                      Otherwise, only DDP needs to be used.
+        warmup_steps (int): The number of warm-up steps. During this stage,
+                            model averaging is skipped.
+        process_group: The process group to be used for all-reduce.
+                       If ``None``, the default process group, which
+                       is created by :func:`torch.distributed.init_process_group`,
+                       will be used. (default: ``None``)
+
+    Example::
+
+        >>> # xdoctest: +SKIP("undefined variables")
+        >>> import torch
+        >>> import torch.distributed as dist
+        >>> import torch.distributed.algorithms.ddp_comm_hooks.post_localSGD_hook as post_localSGD
+        >>> import torch.distributed.algorithms.model_averaging.averagers as averagers
+        >>> import torch.nn as nn
+        >>>
+        >>> dist.init_process_group("nccl", rank=rank, world_size=16)
+        >>> torch.cuda.set_device(rank)
+        >>> module = nn.Linear(1, 1, bias=False).cuda()
+        >>> model = nn.parallel.DistributedDataParallel(
+        >>>    module, device_ids=[rank], output_device=rank
+        >>> )
+        >>> # Register a post-localSGD communication hook.
+        >>> state = PostLocalSGDState(process_group=None, subgroup=None, start_localSGD_iter=100)
+        >>> model.register_comm_hook(state, post_localSGD_hook)
+        >>>
+        >>> # In the first 100 steps, run global gradient averaging like normal DDP at every step.
+        >>> # After 100 steps, run model averaging every 4 steps.
+        >>> # Note that ``warmup_steps`` must be the same as ``start_localSGD_iter`` used in ``PostLocalSGDState``.
+        >>> averager = averagers.PeriodicModelAverager(period=4, warmup_steps=100)
+        >>> for step in range(0, 200):
+        >>>    optimizer.zero_grad()
+        >>>    loss = loss_fn(output, labels)
+        >>>    loss.backward()
+        >>>    optimizer.step()
+        >>>    # Will average model parameters globally every 4 steps. Thus,
+        >>>    # inter-node communication only occurs every 4 iterations after
+        >>>    # the initial ``warmup_steps`` period.
+        >>>    averager.average_parameters(model.parameters())
+    """
+
+    def __init__(self, period, warmup_steps=0, process_group=None):
+        super().__init__(process_group)
+        if warmup_steps < 0:
+            raise ValueError("Arg ``warmup_steps`` must be a non-negative number.")
+        self.warmup_steps = warmup_steps
+        if period < 1:
+            raise ValueError("Arg ``period`` must be a positive value.")
+        elif period == 1:
+            warnings.warn(
+                "When period is 1, no need to use model averaging because the communication cost "
+                "of all-reducing parameters will be no less than the cost of all-reducing gradients "
+                "by DistributedDataParallel in the backward pass. Therefore, only "
+                "DistributedDataParallel should be used for this case."
+            )
+        self.period = period
+
+    def average_parameters(
+        self,
+        params: Union[
+            Iterable[torch.nn.Parameter], Iterable[Dict[str, torch.nn.Parameter]]
+        ],
+    ):
+        """
+        Averages parameters or parameter groups of an optimizer if ``step`` is no less than ``warmup_steps``.
+
+        Can be divided by ``period``, where ``step`` is increased by 1
+        at each iteration in the training loop.
+        Args:
+            params: The parameters of a model or parameter groups of an optimizer.
+
+        """
+        if (
+            self.step >= self.warmup_steps
+            and (self.step - self.warmup_steps) % self.period == 0
+        ):
+            utils.average_parameters_or_parameter_groups(params, self.process_group)
+        self.step += 1
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/model_averaging/hierarchical_model_averager.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/model_averaging/hierarchical_model_averager.py
new file mode 100644
index 0000000000000000000000000000000000000000..a27f3b762a9e3ae5017c1c1c02e0b1734d7d25f1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/model_averaging/hierarchical_model_averager.py
@@ -0,0 +1,180 @@
+# mypy: allow-untyped-defs
+# Copyright 2022 Cruise LLC
+import logging
+import warnings
+from collections import OrderedDict
+from typing import Dict, Iterable, Union
+
+import torch
+import torch.distributed as dist
+import torch.distributed.algorithms.model_averaging.averagers as averagers
+import torch.distributed.algorithms.model_averaging.utils as utils
+
+
+logger = logging.getLogger(__name__)
+
+
+class HierarchicalModelAverager(averagers.ModelAverager):
+    r"""
+    Runs hierarchical model averaging (`hierarchical SGD `_).
+
+    Process groups of different sizes are organized in a hierarchy, and they average parameters
+    by using different periods concurrently after the warm-up stage.
+    This is an extension of :class:`~torch.distributed.algorithms.model_averaging.averagers.PeriodicModelAverager`
+    that supports `post-local SGD `_, which essentially only supports
+    a two-level hierarchy: the intra-machine level and the global level, where the intra-machine
+    level is usually embedded in :meth:`~torch.distributed.algorithms.ddp_comm_hooks.post_localSGD_hook`.
+    Similarly, the process groups within this class do not have such an intra-machine process
+    subgroup, which should be embedded by the post-local SGD communication hook instead.
+
+    Args:
+        period_group_size_dict: An ordered dict mapping keys of model averaging period to
+                                process group size, used for initializing process groups of
+                                different sizes in a hierarchy to average parameters concurrently.
+                                Particularly, at each iteration, there will be at most a single
+                                process group that runs averaging -- the period of such group should
+                                have the largest period which the current step can be divided by.
+                                For example, if the dict has three keys: 2, 4, and 8,
+                                then this means totally three process groups will be created to
+                                average parameters every 2, 4, and 8 iterations, respectively.
+                                At the 4th iteration, only the second process group will run
+                                averaging, because the first process group should be a
+                                subset of the second process group, and no need to execute the first
+                                process group redundantly.
+                                On the other hand, the third process group can only be triggered
+                                every 8 iterations, so it will not be triggered at the 4th iteration.
+        warmup_steps (int): The number of warm-up steps. During this stage, model averaging is skipped.
+        process_group (ProcessGroup, optional): The overall process group containing all the processes that runs model averaging.
+                                                If ``None``, the default process group, which is created
+                                                by :func:`torch.distributed.init_process_group`, will be used.
+                                                (default: ``None``)
+
+    Example::
+        >>> # xdoctest: +SKIP('undefined rank')
+        >>> from collections import OrderedDict
+        >>> import torch
+        >>> import torch.distributed as dist
+        >>> from torch.distributed.algorithms.ddp_comm_hooks.post_localSGD_hook import (
+        >>>     PostLocalSGDState,
+        >>>     post_localSGD_hook,
+        >>> )
+        >>> import torch.distributed.algorithms.model_averaging.hierarchical_model_averager as hierarchicalSGD
+        >>> import torch.nn as nn
+        >>>
+        >>> dist.init_process_group("nccl", rank=rank, world_size=16)
+        >>> torch.cuda.set_device(rank)
+        >>> module = nn.Linear(1, 1, bias=False).to(rank)
+        >>> model = nn.parallel.DistributedDataParallel(
+        >>>    module, device_ids=[rank], output_device=rank
+        >>> )
+        >>> # Register a post-localSGD communication hook.
+        >>> # Assume that each machine has 4 GPUs, then each intra-machine subgroup has a size of 4.
+        >>> subgroup, _ = dist.new_subgroups()
+        >>> state = PostLocalSGDState(process_group=None, subgroup=subgroup, start_localSGD_iter=100)
+        >>> model.register_comm_hook(state, post_localSGD_hook)
+        >>>
+        >>> # Average parameters among each group of 8 processes every 4 iterations, and among all
+        >>> # the 16 processes every 16 iterations.
+        >>> averager = hierarchicalSGD.HierarchicalModelAverager(
+        >>>     period_group_size_dict=OrderedDict([(4, 8), (16, 16)]), warmup_steps=100)
+        >>> # Note that ``warmup_steps`` must be the same as ``start_localSGD_iter`` used in ``PostLocalSGDState``.
+        >>> # In the first 100 steps, run global gradient averaging like normal DDP at every step.
+        >>> # After 100 steps, run model averaging at two levels.
+        >>> for step in range(0, 200):
+        >>>    optimizer.zero_grad()
+        >>>    loss = loss_fn(output, labels)
+        >>>    loss.backward()
+        >>>    optimizer.step()
+        >>>    # Average parameters after ``optimizer.step()``.
+        >>>    # Thus, the inter-node communication only occurs periodically after ``warmup_steps``.
+        >>>    averager.average_parameters(model.parameters())
+
+    .. warning ::
+        The last group size in the dict must be the size of the provided ``process_group``,
+        which indicates model averaging at the highest level of the hierarchy.
+        If ``process_group`` is not provided, then the last group size should be equal to the world size.
+
+    .. warning ::
+        `HierarchicalModelAverager` is experimental and subject to change.
+    """
+
+    def __init__(self, period_group_size_dict=None, warmup_steps=0, process_group=None):
+        super().__init__(process_group)
+        if not period_group_size_dict:
+            raise ValueError("Arg ``period_group_size_dict`` must not be empty.")
+        self._periods = list(period_group_size_dict.keys())
+        if self._periods[0] <= 0:
+            raise ValueError(
+                "The minimum period in arg ``period_group_size_dict`` must be a positive value."
+            )
+        elif self._periods[-1] == 1:
+            warnings.warn(
+                "When the maximum period in arg ``period_group_size_dict`` is 1, "
+                "no need to use model averaging because the communication cost "
+                "of all-reducing parameters will be no less than the cost of all-reducing gradients "
+                "by DistributedDataParallel in the backward pass. Therefore, only "
+                "DistributedDataParallel should be used for this case."
+            )
+        overall_group_size = dist.get_world_size(group=self.process_group)
+        if list(period_group_size_dict.values())[-1] != overall_group_size:
+            raise ValueError(
+                f"The last value in arg ``period_process_group_dict`` {list(period_group_size_dict.values())[-1]} "
+                f"must be equal to the size of arg ``process_group`` {overall_group_size}."
+            )
+
+        self.period_process_group_dict = OrderedDict()
+        logger.info("Model averaging hierarchy:")
+        for period, group_size in period_group_size_dict.items():
+            logger.info(
+                "\tEach group that has %s processes average parameters every %s iterations, "
+                "if no higher-level averaging.",
+                group_size,
+                period,
+            )
+            if group_size != overall_group_size:
+                self.period_process_group_dict[period], _ = dist.new_subgroups(
+                    group_size=group_size, group=self.process_group
+                )
+            else:
+                self.period_process_group_dict[period] = self.process_group
+
+        if warmup_steps < 0:
+            raise ValueError("Arg ``warmup_steps`` must be a non-negative number.")
+        self.warmup_steps = warmup_steps
+
+    def _find_process_group(self):
+        """
+        Return a process group as the value of an ``period_process_group_dict`` entry.
+
+        If ``step`` can be divided by multiple periods in the keys of ``period_process_group_dict``,
+        then the returned process group is the one corresponding to the largest period,
+        since this process group will be used for averaging parameters at this ``step``.
+        Returns ``None`` if not found.
+        """
+        for period in reversed(self._periods):
+            if self.step % period == 0:
+                return self.period_process_group_dict[period]
+        return None
+
+    def average_parameters(
+        self,
+        params: Union[
+            Iterable[torch.nn.Parameter], Iterable[Dict[str, torch.nn.Parameter]]
+        ],
+    ):
+        """
+        Averages parameters or parameter groups of an optimizer.
+
+        Averaging only occurs if ``step`` is no less than ``warmup_steps``
+        and it can be divided by a period in the keys of ``period_process_group_dict``,
+        where ``step`` is increased by 1 at each iteration in the training loop.
+        If ``step`` can be divided by multiple periods in the keys of ``period_process_group_dict``,
+        only the largest period is used, and the corresponding process group is used for averaging parameters.
+        Args:
+            params: The parameters of a model or parameter groups of an optimizer.
+        """
+        if self.step >= self.warmup_steps:
+            group = self._find_process_group()
+            if group is not None:
+                utils.average_parameters_or_parameter_groups(params, group)
+        self.step += 1
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/model_averaging/utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/model_averaging/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..20f75152f0b876acf2b174177edf75db89c37fa2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/algorithms/model_averaging/utils.py
@@ -0,0 +1,89 @@
+# mypy: allow-untyped-defs
+# flake8: noqa C101
+import itertools
+from typing import Dict, Iterable, Iterator, Union
+
+import torch
+import torch.distributed as dist
+
+# The two imports below are not always available depending on the
+# USE_DISTRIBUTED compile flag. Make sure they raise import error
+# if we're trying to use them.
+from torch.distributed import group, ProcessGroup
+
+
+__all__ = [
+    "average_parameters",
+    "get_params_to_average",
+    "average_parameters_or_parameter_groups",
+]
+
+
+def average_parameters(
+    params: Iterator[torch.nn.Parameter], process_group: ProcessGroup
+):
+    """
+    Averages all the given parameters.
+
+    For allreduce efficiency, all the parameters are flattened into a contiguous buffer.
+    Thus, it requires extra memory of the same size as the given parameters.
+    """
+    group_to_use = process_group if process_group is not None else group.WORLD
+    # Do not update any parameter if not in the process group.
+    if dist._rank_not_in_group(group_to_use):
+        return
+
+    params_it1, params_it2 = itertools.tee(params)
+    # If the input parameters have different data types,
+    # packing these parameters will trigger an implicit type up-casting.
+    # The original parameter data types will be restored during the subsequent unpacking.
+    flat_params = torch.cat([p.data.reshape(-1) for p in params_it1])
+    flat_params /= dist.get_world_size(group_to_use)
+    # Make sure the allreduce will not conflict with any other ongoing process group.
+    if torch.cuda.is_available():
+        torch.cuda.synchronize()
+    dist.all_reduce(flat_params, group=group_to_use)
+
+    offset = 0
+    for p in params_it2:
+        p.data = flat_params[offset : offset + p.numel()].view_as(p).type_as(p)
+        offset += p.numel()
+
+
+def get_params_to_average(
+    params: Union[Iterable[torch.nn.Parameter], Iterable[Dict[str, torch.nn.Parameter]]]
+):
+    """
+    Return a list of parameters that need to average.
+
+    This filters out the parameters that do not contain any gradients.
+    Args:
+        params: The parameters of a model or parameter groups of an optimizer.
+    """
+    filtered_params = []
+    for param in params:
+        if isinstance(param, torch.nn.Parameter):
+            # model.parameters() input
+            param_data = param
+            if param_data.grad is not None:
+                filtered_params.append(param_data)
+        elif isinstance(param, dict):
+            # optimizer.param_groups input
+            for param_data in param["params"]:
+                if param_data.grad is not None:
+                    filtered_params.append(param_data)
+        else:
+            raise NotImplementedError(
+                f"Parameter input of type {type(param)} is not supported"
+            )
+    return filtered_params
+
+
+def average_parameters_or_parameter_groups(
+    params: Union[
+        Iterable[torch.nn.Parameter], Iterable[Dict[str, torch.nn.Parameter]]
+    ],
+    process_group: ProcessGroup,
+):
+    """Averages parameters of a model or parameter groups of an optimizer."""
+    average_parameters(iter(get_params_to_average(params)), process_group)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/autograd/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/autograd/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1cf0aec6140f8c61e36ca90de5165399447b290
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/autograd/__init__.py
@@ -0,0 +1,53 @@
+# mypy: allow-untyped-defs
+
+import torch
+
+
+def is_available():
+    return hasattr(torch._C, "_dist_autograd_init")
+
+
+if is_available() and not torch._C._dist_autograd_init():
+    raise RuntimeError("Failed to initialize torch.distributed.autograd")
+
+if is_available():
+    from torch._C._distributed_autograd import (
+        _current_context,
+        _get_debug_info,
+        _get_max_id,
+        _init,
+        _is_valid_context,
+        _new_context,
+        _release_context,
+        _retrieve_context,
+        backward,
+        DistAutogradContext,
+        get_gradients,
+    )
+
+
+class context:
+    """
+    Context object to wrap forward and backward passes when using
+    distributed autograd. The ``context_id`` generated in the ``with``
+    statement  is required to uniquely identify a distributed backward pass
+    on all workers. Each worker stores metadata associated with this
+    ``context_id``, which is required to correctly execute a distributed
+    autograd pass.
+
+    Example::
+        >>> # xdoctest: +SKIP
+        >>> import torch.distributed.autograd as dist_autograd
+        >>> with dist_autograd.context() as context_id:
+        >>>     t1 = torch.rand((3, 3), requires_grad=True)
+        >>>     t2 = torch.rand((3, 3), requires_grad=True)
+        >>>     loss = rpc.rpc_sync("worker1", torch.add, args=(t1, t2)).sum()
+        >>>     dist_autograd.backward(context_id, [loss])
+    """
+
+    def __enter__(self):
+        self.autograd_context = _new_context()
+        return self.autograd_context._context_id()
+
+    def __exit__(self, type, value, traceback):
+        _release_context(self.autograd_context._context_id())
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/autograd/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/autograd/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f7ca74f73e33f5c7b631547e7aaf6d77ca1e065e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/autograd/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3262acccac1a6d4c1c157233ef6ac519b3629e93
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__init__.py
@@ -0,0 +1,14 @@
+from .api import CheckpointException
+from .default_planner import DefaultLoadPlanner, DefaultSavePlanner
+from .filesystem import FileSystemReader, FileSystemWriter
+from .metadata import (
+    BytesStorageMetadata,
+    ChunkStorageMetadata,
+    Metadata,
+    TensorStorageMetadata,
+)
+from .optimizer import load_sharded_optimizer_state_dict
+from .planner import LoadPlan, LoadPlanner, ReadItem, SavePlan, SavePlanner, WriteItem
+from .state_dict_loader import load, load_state_dict
+from .state_dict_saver import async_save, save, save_state_dict
+from .storage import StorageReader, StorageWriter
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3381df195ea119077f5b221193ba54a9d8145c8f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_checkpointer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_checkpointer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c848441f926e9aeecc1f1e02b31d554b192dbe10
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_checkpointer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_dedup_save_plans.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_dedup_save_plans.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..428f61fbdbf12847faf4d1ab7d1548b309d1c073
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_dedup_save_plans.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_dedup_tensors.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_dedup_tensors.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d7ec1a7ef8f18b0fe614a1c438aa6748865f200f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_dedup_tensors.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_fsspec_filesystem.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_fsspec_filesystem.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1273325885a5213d1a8abcb17264571fa116be84
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_fsspec_filesystem.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_nested_dict.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_nested_dict.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dc8f45ecfd92bbf3256266d5292918297c3f0ee4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_nested_dict.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_sharded_tensor_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_sharded_tensor_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..595cf062d69557db8b2f6b273ac82bb90aa7fd5b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_sharded_tensor_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_storage_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_storage_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..40e82c4be398e016a51d52264531f95788e112ae
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_storage_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_traverse.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_traverse.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4a4f59ff0a0d2f1760603a02a31446d186dcc7d7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_traverse.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_version.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_version.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f46010c5a885f2812df3c4cf6823141e70f7405e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/_version.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/api.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/api.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..09d28a9bf96bd9409ed8486b377631b22327978e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/api.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/default_planner.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/default_planner.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..06f9e4c3dcf5baa8666416ae0e18350636707f4a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/default_planner.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/filesystem.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/filesystem.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..da6ada00a3c4b4f2d8a3e33eb354b0d350faca1e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/filesystem.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/format_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/format_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3831ca153f0a66ffeebf7440b4aa4123d60977e2
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/format_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/logger.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/logger.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cc43cf6018963c5ef9e00e83d9c5ea4fe97e6b0f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/logger.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/logging_handlers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/logging_handlers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e2961e717d38a76281bdc3ff571007b98a2c8a8a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/logging_handlers.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/metadata.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/metadata.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a5832698fcac579199e6cfeae837d03d03e094dd
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/metadata.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/optimizer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/optimizer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d36e929a4646d46d0d850f3064536ad6a2eb0406
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/optimizer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/planner.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/planner.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..98d27f04bdf240b8a77e4f9933c2d4c7688efb14
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/planner.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/planner_helpers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/planner_helpers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0081a4ce1a9e328c92f3c293a63ddf22f0eeae5d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/planner_helpers.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/resharding.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/resharding.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dfdc8f54042224e967d597f7f576f4a389699c97
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/resharding.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/staging.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/staging.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5f5a56ec4223dbdfbbbd156ffc4afce93452659d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/staging.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/state_dict.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/state_dict.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7ecae7830692e46d93526048761497350b474995
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/state_dict.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/state_dict_loader.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/state_dict_loader.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..310b8a6e2231a023e815a68f70af9dd4931b3839
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/state_dict_loader.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/state_dict_saver.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/state_dict_saver.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..78d24e50a2dfaa14370bb495b88383cb00d1d221
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/state_dict_saver.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/stateful.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/stateful.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..748f125fb2ce769560496796712ee9b80d67158b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/stateful.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/storage.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/storage.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ff4586e8994a8f97feed97ddfe2ce9fbee31193a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/storage.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5c102b8cbe51af962064057aae20b3a5ca567cd7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/__pycache__/utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_checkpointer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_checkpointer.py
new file mode 100644
index 0000000000000000000000000000000000000000..a93fe8197dea66e5e331133f94c0067ff8ecb90f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_checkpointer.py
@@ -0,0 +1,100 @@
+from concurrent.futures import Future
+from typing import Any, Dict, List, Optional
+
+import torch.distributed as dist
+import torch.distributed.checkpoint.state_dict_loader as loader
+import torch.distributed.checkpoint.state_dict_saver as saver
+from torch.distributed.checkpoint.metadata import Metadata, STATE_DICT_TYPE
+from torch.distributed.checkpoint.storage import (
+    LoadPlanner,
+    SavePlanner,
+    StorageReader,
+    StorageWriter,
+)
+
+
+__all__: List[str] = []
+
+
+class _Checkpointer:
+    """This base class specefies a high level API for saving and loading
+    distributed `state_dict` 's. It provides an abstraction over the low-level APIs
+    provided by :py:mod:`torch.distributed.checkpoint.storage`, essentially calling
+    :py:meth: `torch.distributed.state_dict_saver.save` and
+    :py:meth: `torch.distributed.state_dict_loader.load` with the provided storage
+    readers and writers.
+
+    .. warning::
+        This feature is experimental and subject to removal/change.
+
+    """
+
+    def __init__(
+        self,
+        storage_writer: StorageWriter,
+        storage_reader: StorageReader,
+        *,
+        process_group: Optional[dist.ProcessGroup] = None,
+        coordinator_rank: int = 0,
+        no_dist: bool = False,
+        load_planner: Optional[LoadPlanner] = None,
+        save_planner: Optional[SavePlanner] = None,
+    ):
+        """Initializes the Checkpointer instance.
+
+        Args:
+            storage_writer: Instance of StorageWrite use to perform writes.
+            storage_reader: StorageReader used to load data from.
+            process_group: ProcessGroup to be used for cross-rank synchronization.
+            coordinator_rank: Rank to use to coordinate the checkpoint. rank0 is used by default.
+            no_dist: If ``True``, distributed checkpoint will not load in SPMD style. (Default: ``False``)
+            loader_planner: Instance of LoadPlanner to use when loading.
+            save_planner: Instance of SavePlanner to use when saving.
+        """
+        self.storage_writer = storage_writer
+        self.storage_reader = storage_reader
+        self.process_group = process_group
+        self.coordinator_rank = coordinator_rank
+        self.no_dist = no_dist
+        self.load_planner = load_planner
+        self.save_planner = save_planner
+
+    def save(
+        self,
+        state_dict: STATE_DICT_TYPE,
+    ) -> Metadata:
+        """Calls :py:meth: `torch.distributed.state_dict_saver.save`. Utilizing values passed during initialization."""
+        return saver.save(
+            state_dict,
+            self.storage_writer,
+            process_group=self.process_group,
+            coordinator_rank=self.coordinator_rank,
+            no_dist=self.no_dist,
+            planner=self.save_planner,
+        )
+
+    def async_save(
+        self,
+        state_dict: STATE_DICT_TYPE,
+    ) -> Future:
+        """
+        Calls :py:meth: `torch.distributed.state_dict_saver._async_save`. Utilizing values passed during initialization.
+
+        Returns:
+            Future: A future holding the resultant Metadata object from `save`.
+        """
+        return saver.async_save(
+            state_dict,
+            storage_writer=self.storage_writer,
+            process_group=self.process_group,
+            planner=self.save_planner,
+        )
+
+    def load(self, state_dict: Dict[str, Any]) -> None:
+        """Calls :py:meth: `torch.distributed.state_dict_loader.load`. Utilizing values passed during initialization."""
+        loader.load(
+            state_dict,
+            storage_reader=self.storage_reader,
+            process_group=self.process_group,
+            planner=self.load_planner,
+        )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_dedup_save_plans.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_dedup_save_plans.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd37634a0aa64bb5e849375a4fcedb39617b998e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_dedup_save_plans.py
@@ -0,0 +1,60 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates
+import dataclasses
+from collections import defaultdict
+from typing import Dict, List, Set, TYPE_CHECKING
+
+from torch.distributed.checkpoint.planner import SavePlan, WriteItem
+
+
+if TYPE_CHECKING:
+    from torch.distributed.checkpoint.metadata import MetadataIndex
+
+__all__ = ["dedup_save_plans"]
+
+
+def dedup_save_plans(
+    all_plans: List[SavePlan],
+    save_to_lowest_rank: bool = False,
+) -> List[SavePlan]:
+    """
+    Removes duplicate entries from appearing on multiple SavePlans. For each duplicate across
+    a set of SavePlans, only the smallest SavePlan in terms of planned storage keeps the entry.
+    """
+
+    write_item_to_plan_indices: Dict[MetadataIndex, Set[int]] = defaultdict(set)
+    write_item_idx_to_write_item: Dict[MetadataIndex, WriteItem] = {}
+    for plan_idx, plan in enumerate(all_plans):
+        for write_item in plan.items:
+            # map each write item to its plan
+            write_item_to_plan_indices[write_item.index].add(plan_idx)
+            write_item_idx_to_write_item[write_item.index] = write_item
+
+    # put item in the plan with the smallest size and remove it from the other plan_indices
+    to_remove: List[Set] = [set() for _ in range(len(all_plans))]
+    plan_to_size = [0] * len(all_plans)
+    for write_item_idx, plan_indices in write_item_to_plan_indices.items():
+        if save_to_lowest_rank:
+            select_plan_idx = min(plan_indices)
+        else:
+            select_plan_idx = min(
+                plan_indices, key=lambda plan_idx: plan_to_size[plan_idx]
+            )
+
+        write_item = write_item_idx_to_write_item[write_item_idx]
+        # essentially ignores the storage size of anything that is not a tensor, since
+        # we don't know how much storage they represent
+        plan_to_size[select_plan_idx] += write_item.tensor_storage_size() or 1
+
+        plan_indices.remove(select_plan_idx)
+        for plan_idx in plan_indices:
+            to_remove[plan_idx].add(write_item_idx)
+
+    for plan_idx, remove_set in enumerate(to_remove):
+        new_items = [
+            write_item
+            for write_item in all_plans[plan_idx].items
+            if write_item.index not in remove_set
+        ]
+        all_plans[plan_idx] = dataclasses.replace(all_plans[plan_idx], items=new_items)
+
+    return all_plans
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_dedup_tensors.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_dedup_tensors.py
new file mode 100644
index 0000000000000000000000000000000000000000..687afb287b3c74a4454085561528c31df3a5f702
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_dedup_tensors.py
@@ -0,0 +1,62 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates
+import dataclasses
+import logging
+from typing import Dict, List, TYPE_CHECKING
+
+from torch.distributed.checkpoint.planner import SavePlan
+
+
+if TYPE_CHECKING:
+    from torch.distributed.checkpoint.metadata import MetadataIndex
+
+__all__ = ["dedup_tensors"]
+
+
+def init_logger() -> logging.Logger:
+    logger = logging.getLogger(__name__)
+    level = logging.INFO
+    logger.setLevel(level)
+    console = logging.StreamHandler()
+    formatter = logging.Formatter(
+        "%(asctime)s %(filename)s:%(lineno)s %(levelname)s p:%(processName)s t:%(threadName)s: %(message)s"
+    )
+    console.setFormatter(formatter)
+    console.setLevel(level)
+    logger.addHandler(console)
+    logger.propagate = False
+    return logger
+
+
+logger = init_logger()
+
+
+# TODO add docstring for dedup_tensors
+def dedup_tensors(all_plans: List[SavePlan]) -> List[SavePlan]:
+    all_plans = list(all_plans)
+    key_to_plan: Dict[MetadataIndex, List[int]] = {}
+    for plan_idx, plan in enumerate(all_plans):
+        for write_item in plan.items:
+            key_to_plan.setdefault(write_item.index, []).append(plan_idx)
+
+    replicated_items = {k: v for k, v in key_to_plan.items() if len(v) > 1}
+
+    # Remove duplicates by always keeping the first entry.
+    # Compute the per-rank remove set.
+    plan_to_keys: Dict[int, List[MetadataIndex]] = {}
+    for key, plans in replicated_items.items():
+        for plan_idx in plans[1:]:
+            plan_to_keys.setdefault(plan_idx, []).append(key)
+    if len(plan_to_keys) > 0:
+        logger.info("Duplicate keys to remove: %s", plan_to_keys)
+
+    for plan_idx, keys in plan_to_keys.items():
+        key_set = set(keys)
+        # rewrite items and remove elements
+        new_items = [
+            write_item
+            for write_item in all_plans[plan_idx].items
+            if write_item.index not in key_set
+        ]
+        all_plans[plan_idx] = dataclasses.replace(all_plans[plan_idx], items=new_items)
+
+    return all_plans
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_fsspec_filesystem.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_fsspec_filesystem.py
new file mode 100644
index 0000000000000000000000000000000000000000..b57df9c3456ca6bcd70ef65594a7e1e15eb95268
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_fsspec_filesystem.py
@@ -0,0 +1,137 @@
+# Mypy will not try inferring the types of any 3rd party libraries installed.
+# mypy: ignore-errors
+
+import io
+import os
+from contextlib import contextmanager
+from pathlib import Path
+from typing import Generator, Optional, Union
+
+import fsspec
+from fsspec import AbstractFileSystem
+from fsspec.core import url_to_fs
+
+from torch.distributed.checkpoint.filesystem import (
+    FileSystemBase,
+    FileSystemReader,
+    FileSystemWriter,
+)
+
+
+__all__ = [
+    "FsspecWriter",
+    "FsspecReader",
+]
+
+
+class FileSystem(FileSystemBase):
+    def __init__(self) -> None:
+        self.fs: Optional[AbstractFileSystem] = None
+
+    @contextmanager
+    def create_stream(
+        self, path: Union[str, os.PathLike], mode: str
+    ) -> Generator[io.IOBase, None, None]:
+        assert self.fs is not None
+        with self.fs.transaction:
+            with fsspec.open(str(path), mode) as stream:
+                yield stream
+
+    def concat_path(
+        self, path: Union[str, os.PathLike], suffix: str
+    ) -> Union[str, os.PathLike]:
+        return os.path.join(path, suffix)
+
+    def init_path(self, path: Union[str, os.PathLike]) -> Union[str, os.PathLike]:
+        self.fs, _ = url_to_fs(path)
+        return path
+
+    def rename(
+        self, path: Union[str, os.PathLike], new_path: Union[str, os.PathLike]
+    ) -> None:
+        self.fs.rename(path, new_path)
+
+    def mkdir(self, path: [str, os.PathLike]) -> None:
+        self.fs.makedirs(path, exist_ok=True)
+
+    @classmethod
+    def validate_checkpoint_id(cls, checkpoint_id: Union[str, os.PathLike]) -> bool:
+        if isinstance(checkpoint_id, Path):
+            return False
+
+        try:
+            url_to_fs(checkpoint_id)
+        except ValueError:
+            return False
+
+        return True
+
+    def exists(self, path: Union[str, os.PathLike]) -> bool:
+        return self.fs.exists(path)
+
+    def rm_file(self, path: Union[str, os.PathLike]) -> None:
+        self.fs.rm(path)
+
+
+# TODO: add the dcp.async_save mixin
+class FsspecWriter(FileSystemWriter):
+    """
+    Basic implementation of StorageWriter using FFspec.
+
+    This implementation makes the following assumptions and simplifications:
+
+    * The checkpoint path is an empty or non-existing directory.
+    * File creation is atomic
+
+    The checkpoint consist of one file per write request plus
+    a `.metadata` file with the serialized metadata.
+
+    """
+
+    def __init__(
+        self,
+        path: Union[str, os.PathLike],
+        single_file_per_rank: bool = True,
+        sync_files: bool = True,
+        thread_count: int = 1,
+        per_thread_copy_ahead: int = 10_000_000,
+        overwrite: bool = True,
+    ) -> None:
+        """
+        Initialize the writer pointing to `path`.
+
+        Args:
+            path: directory where the checkpoint will be written to.
+            single_file_per_rank: Produce one file per rank instead of one file per tensor/blob. Default to True.
+            sync_files : force files to be synced to permanent storage. Default to True.
+            thread_count: Number of IO threads to use to write. Default to 1.
+            per_thread_copy_ahead: How many bytes to copy from the GPU ahead of saving then. Default 10Mb.
+            overwrite: Whether to allow overwriting existing checkpoints. Defaults to True.
+
+        N. B. If sync_files is disabled, there's no guarantee that the checkpoint will be consistent in the case of a failure.
+        """
+        super().__init__(
+            path,
+            single_file_per_rank,
+            sync_files,
+            thread_count,
+            per_thread_copy_ahead,
+            overwrite=overwrite,
+        )
+        self.fs = FileSystem()
+        self.path = self.fs.init_path(path)
+
+    @classmethod
+    def validate_checkpoint_id(cls, checkpoint_id: Union[str, os.PathLike]) -> bool:
+        return FileSystem.validate_checkpoint_id(checkpoint_id)
+
+
+class FsspecReader(FileSystemReader):
+    def __init__(self, path: Union[str, os.PathLike]) -> None:
+        super().__init__(path)
+        self.fs = FileSystem()
+        self.path = self.fs.init_path(path)
+
+    @classmethod
+    def validate_checkpoint_id(cls, checkpoint_id: Union[str, os.PathLike]) -> bool:
+        return FileSystem.validate_checkpoint_id(checkpoint_id)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_nested_dict.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_nested_dict.py
new file mode 100644
index 0000000000000000000000000000000000000000..b846a1d47d843433e1c3de295c86d318b7157a1e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_nested_dict.py
@@ -0,0 +1,70 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates
+from typing import Dict, Tuple
+
+from torch.distributed.checkpoint.metadata import STATE_DICT_TYPE
+
+from . import _version
+from ._traverse import (
+    OBJ_PATH,
+    set_element,
+    STATE_DICT_ITEM,
+    traverse_state_dict,
+    traverse_state_dict_v_2_3,
+)
+
+
+"""
+TODO:
+Need to add ability to handle tuple, OrderedDict, NamedTuple.
+Update mappings from dict to a class.
+Change set_element to recreate the right type for tuple, OrderedDict, and NamedTuple.
+"""
+
+
+FLATTEN_MAPPING = Dict[str, OBJ_PATH]
+
+
+# TODO: Update Docstring for nested_dict.py
+def flatten_state_dict(
+    state_dict: STATE_DICT_TYPE,
+) -> Tuple[STATE_DICT_TYPE, FLATTEN_MAPPING]:
+    """
+    Flatten ``state_dict`` made of nested dicts and lists into a top level dictionary.
+
+    Use ``unflatten_state_dict`` to revert this process.
+    Returns:
+        A tuple with the flatten state_dict and a mapping from original to new state_dict.
+    N.B. The new keys are derived from the object paths, joined by dot.
+        For example: ``{ 'a': {'b':...}}`` results in the key `a.b`.
+    """
+    flattened: STATE_DICT_TYPE = {}
+    mappings: FLATTEN_MAPPING = {}
+
+    def flat_copy(path: OBJ_PATH, value: STATE_DICT_ITEM) -> None:
+        new_fqn = ".".join(map(str, path))
+        if new_fqn in flattened:
+            raise ValueError(f"duplicated flatten key {new_fqn}")
+        flattened[new_fqn] = value
+        mappings[new_fqn] = path
+
+    # We started to flatten dictionary since v2.4. But in order to not break
+    # the checkpoints that were saved before v2.4, we need to keep the old
+    # traversal so that we can reconstruct those checkpoints.
+    use_v_2_3 = (
+        _version._derived_version is not None and _version._derived_version == "2_3"
+    )
+    if use_v_2_3:
+        traverse_state_dict_v_2_3(state_dict, flat_copy)
+    else:
+        traverse_state_dict(state_dict, flat_copy)
+    return flattened, mappings
+
+
+def unflatten_state_dict(
+    state_dict: STATE_DICT_TYPE, mapping: FLATTEN_MAPPING
+) -> STATE_DICT_TYPE:
+    """Restore the original nested state_dict according to ``mapping`` and the flattened ``state_dict``."""
+    nested: STATE_DICT_TYPE = {}
+    for key, value in state_dict.items():
+        set_element(nested, mapping[key], value)
+    return nested
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_sharded_tensor_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_sharded_tensor_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..a68bcddeb7f9d9ffe6f89056dfe1ccc30cc12eb5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_sharded_tensor_utils.py
@@ -0,0 +1,107 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates
+
+import copy
+from typing import TYPE_CHECKING
+
+import torch.distributed as dist
+from torch.distributed._shard.sharded_tensor import Shard, ShardedTensor, ShardMetadata
+from torch.distributed.checkpoint.metadata import STATE_DICT_TYPE
+from torch.distributed.remote_device import _remote_device
+
+from ._traverse import OBJ_PATH, set_element, STATE_DICT_ITEM, traverse_state_dict
+from .utils import _element_wise_add, _normalize_device_info
+
+
+if TYPE_CHECKING:
+    from torch.distributed._shard.sharded_tensor.metadata import ShardedTensorMetadata
+
+
+# TODO: We need to refactor this code.
+def _flatten_sharded_tensors(state_dict: STATE_DICT_TYPE) -> STATE_DICT_TYPE:
+    r"""
+    Transform ``state_dict`` by flattening all nested ShardedTensor instances found.
+
+    The resulting ShardedTensor instances are only correct regarding the local shard and
+    MUST not be used for any other purpose but checkpointing, as no operator will work with them.
+
+    This function should be used in conjunction with a state_dict produced by FSDP's
+    StateDictType.SHARDED_STATE_DICT methods.
+    """
+    new_state_dict: STATE_DICT_TYPE = {}
+
+    def rewrite_dict(path: OBJ_PATH, value: STATE_DICT_ITEM) -> None:
+        if not isinstance(value, ShardedTensor):
+            set_element(new_state_dict, path, value)
+            return
+        shards = value.local_shards()
+
+        if len(shards) == 0:
+            return
+        if len(shards) != 1:
+            set_element(new_state_dict, path, value)
+            return
+
+        outer_shard = shards[0]
+
+        inner_st = outer_shard.tensor
+        if not isinstance(inner_st, ShardedTensor):
+            set_element(new_state_dict, path, value)
+            return
+
+        if len(inner_st.local_shards()) != 1:
+            raise ValueError("Cannot handle inner tensor with more than 1 shard")
+        inner_shard = inner_st.local_shards()[0]
+
+        local_shards = [
+            Shard(
+                tensor=inner_shard.tensor,
+                metadata=ShardMetadata(
+                    shard_offsets=_element_wise_add(
+                        outer_shard.metadata.shard_offsets,
+                        inner_shard.metadata.shard_offsets,
+                    ),
+                    shard_sizes=inner_shard.metadata.shard_sizes,
+                    placement=f"rank:{dist.get_rank()}/{inner_shard.tensor.device}",
+                ),
+            )
+        ]
+
+        st_meta: ShardedTensorMetadata = copy.deepcopy(value.metadata())
+        other_rank = 0 if dist.get_rank() > 0 else 1
+        device_info = _normalize_device_info(inner_shard.tensor.device.type, 0)
+
+        # Remove the outer ST shard the inner ST covers
+        for i, shard_md in enumerate(st_meta.shards_metadata):
+            if shard_md.shard_offsets == outer_shard.metadata.shard_offsets:
+                st_meta.shards_metadata.pop(i)
+                break
+
+        # Attribute other rank for the other shards
+        for shard_md in st_meta.shards_metadata:
+            shard_md.placement = _remote_device(f"rank:{other_rank}/{device_info}")
+
+        # Add other inner shards from the inner tensor
+        for inner_md in inner_st.metadata().shards_metadata:
+            if inner_md.shard_offsets != inner_shard.metadata.shard_offsets:
+                st_meta.shards_metadata.append(
+                    ShardMetadata(
+                        shard_offsets=_element_wise_add(
+                            outer_shard.metadata.shard_offsets,
+                            inner_md.shard_offsets,
+                        ),
+                        shard_sizes=inner_md.shard_sizes,
+                        placement=f"rank:{other_rank}/{device_info}",
+                    )
+                )
+
+        # Finally add this shard
+        st_meta.shards_metadata.append(local_shards[0].metadata)
+
+        st = ShardedTensor._init_from_local_shards_and_global_metadata(
+            local_shards=local_shards,
+            sharded_tensor_metadata=st_meta,
+        )
+        set_element(new_state_dict, path, st)
+
+    traverse_state_dict(state_dict, rewrite_dict)
+    return new_state_dict
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_storage_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_storage_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..194c9c8c4b9b15eb1b2909cfd8a9e8e01e46f54d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_storage_utils.py
@@ -0,0 +1,49 @@
+import os
+from typing import List, Type, Union
+
+from .filesystem import FileSystemReader, FileSystemWriter
+from .storage import StorageReader, StorageWriter
+
+
+def _storage_setup(
+    storage: Union[StorageReader, StorageWriter, None],
+    checkpoint_id: Union[str, os.PathLike, None],
+    reader: bool = False,
+) -> Union[None, StorageReader, StorageWriter]:
+    if storage:
+        if checkpoint_id is not None:
+            storage.reset(checkpoint_id)
+        return storage
+
+    if not checkpoint_id:
+        raise RuntimeError(
+            "`checkpoint_id` must be specificed if "
+            "storage_reader/storage_writer is None."
+        )
+
+    targets: List[Type[Union[StorageReader, StorageWriter]]] = []
+    if reader:
+        targets = [
+            FileSystemReader,
+        ]
+    else:
+        targets = [
+            FileSystemWriter,
+        ]
+    try:
+        from ._fsspec_filesystem import FsspecReader, FsspecWriter
+
+        targets.append(FsspecReader if reader else FsspecWriter)
+    except Exception:
+        pass
+
+    for target in targets:
+        if target.validate_checkpoint_id(checkpoint_id):
+            storage = target(checkpoint_id)  # type: ignore[call-arg]
+            storage.reset(checkpoint_id)
+            return storage
+
+    raise RuntimeError(
+        "Cannot detect which StorageReader or StorageWriter to use. "
+        "Please specify the storage_reader/storage_writer."
+    )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_traverse.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_traverse.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c79013abeb2692a7359e77df0ede0237125bdb4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_traverse.py
@@ -0,0 +1,208 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates
+from typing import (
+    Callable,
+    cast,
+    Collection,
+    List,
+    Mapping,
+    MutableMapping,
+    Optional,
+    Tuple,
+    TypeVar,
+    Union,
+)
+
+import torch
+from torch.distributed._shard.sharded_tensor.api import ShardedTensor
+from torch.distributed.checkpoint.metadata import STATE_DICT_TYPE
+from torch.distributed.tensor import DTensor
+
+
+PATH_ITEM = Union[str, int]
+OBJ_PATH = Tuple[PATH_ITEM, ...]
+T = TypeVar("T")
+
+STATE_DICT_ITEM = object
+CONTAINER_TYPE = MutableMapping[PATH_ITEM, STATE_DICT_ITEM]
+
+__all__ = ["traverse_state_dict", "set_element", "get_element", "print_tensor"]
+
+
+def _keep_visiting_tensors(value: STATE_DICT_ITEM) -> bool:
+    return isinstance(value, torch.Tensor)
+
+
+# TODO: update docstring for traverse.py
+def traverse_state_dict(
+    state_dict: STATE_DICT_TYPE,
+    visitor: Callable[[OBJ_PATH, STATE_DICT_ITEM], None],
+    keep_traversing: Callable[[STATE_DICT_ITEM], bool] = _keep_visiting_tensors,
+) -> None:
+    """
+    Invoke ``visitor`` for each value recursively in ``state_dict``.
+    Mapping will be traversed and ``visitor`` will be applied to the leaf elements.
+    ``visitor`` will only be applied to elements in a list or a tuple, if the
+    container contains tensors or mappings.
+    """
+
+    def _is_terminal(value: STATE_DICT_ITEM) -> bool:
+        values: Collection[STATE_DICT_ITEM]
+        if isinstance(value, Mapping):
+            return False
+        elif isinstance(value, list):
+            values = value
+        else:
+            return True
+
+        for entry in values:
+            if isinstance(entry, (Mapping, list)) and not _is_terminal(entry):
+                return False
+            if keep_traversing is not None and keep_traversing(entry):
+                return False
+        return True
+
+    def _traverse_obj(path: OBJ_PATH, value: STATE_DICT_ITEM) -> None:
+        if isinstance(value, Mapping):
+            for k, v in value.items():
+                _traverse_obj(path + (str(k),), v)
+        elif _is_terminal(value):
+            visitor(path, value)
+        elif isinstance(value, (list, tuple)):
+            for i, v in enumerate(value):
+                _traverse_obj(path + (i,), v)
+
+    for key, value in state_dict.items():
+        _traverse_obj((str(key),), value)
+
+
+def traverse_state_dict_v_2_3(
+    state_dict: STATE_DICT_TYPE,
+    visitor: Callable[[OBJ_PATH, STATE_DICT_ITEM], None],
+    keep_traversing: Callable[[STATE_DICT_ITEM], bool] = _keep_visiting_tensors,
+) -> None:
+    """
+    Traversal is short-circuited when if finds a collection for which ``keep_visiting_tensors`` evaluates
+    to false for all elements.
+    By default, all collections with at least one ``torch.Tensor`` element are traversed.
+    Visitor takes a path argument that is a tuple of the keys used to reach it.
+    """
+
+    # a value is terminal if it has no other containers values inside it
+    def _is_terminal(value: STATE_DICT_ITEM) -> bool:
+        values: Collection[STATE_DICT_ITEM]
+        if isinstance(value, Mapping):
+            values = value.values()
+        elif isinstance(value, list):
+            values = value
+        else:
+            return True
+
+        for entry in values:
+            if isinstance(entry, (Mapping, list)) and not _is_terminal(entry):
+                return False
+            if keep_traversing is not None and keep_traversing(entry):
+                return False
+        return True
+
+    def _traverse_obj(path: OBJ_PATH, value: STATE_DICT_ITEM) -> None:
+        if _is_terminal(value):
+            visitor(path, value)
+        elif isinstance(value, Mapping):
+            for k, v in value.items():
+                _traverse_obj(path + (str(k),), v)
+        elif isinstance(value, list):
+            for i, v in enumerate(value):
+                _traverse_obj(path + (i,), v)
+
+    for key, value in state_dict.items():
+        _traverse_obj((str(key),), value)
+
+
+def set_element(
+    root_dict: STATE_DICT_TYPE, path: OBJ_PATH, value: STATE_DICT_ITEM
+) -> None:
+    """Set ``value`` in ``root_dict`` along the ``path`` object path."""
+    cur_container = cast(CONTAINER_TYPE, root_dict)
+
+    def extend_list(lst: List[STATE_DICT_ITEM], idx: int) -> None:
+        while len(lst) <= idx:
+            lst.append(None)
+
+    for i in range(1, len(path)):
+        prev_key = path[i - 1]
+        key = path[i]
+        def_val = cast(STATE_DICT_ITEM, {} if type(key) == str else [])
+
+        if isinstance(cur_container, Mapping):
+            cur_container = cast(
+                CONTAINER_TYPE, cur_container.setdefault(prev_key, def_val)
+            )
+        else:
+            extend_list(cur_container, prev_key)
+            if cur_container[prev_key] is None:
+                cur_container[prev_key] = def_val
+            cur_container = cur_container[prev_key]
+
+    key = path[-1]
+    if type(key) == int:
+        extend_list(cast(List[STATE_DICT_ITEM], cur_container), key)
+
+    cur_container[key] = value
+
+
+def get_element(
+    root_dict: STATE_DICT_TYPE,
+    path: OBJ_PATH,
+    default_value: Optional[T] = None,
+) -> Optional[T]:
+    """Retrieve the value at ``path``from ``root_dict``, returning ``default_value`` if not found."""
+    cur_value = cast(CONTAINER_TYPE, root_dict)
+    for part in path:
+        if type(part) is int:
+            if not isinstance(cur_value, list) or len(cur_value) < part:
+                return default_value
+        elif not isinstance(cur_value, Mapping) or part not in cur_value:
+            return default_value
+
+        cur_value = cast(CONTAINER_TYPE, cur_value[part])
+    return cast(Optional[T], cur_value)
+
+
+def _print_nested(
+    value: STATE_DICT_ITEM,
+    prefix: str = "",
+    print_fun: Callable[[str], None] = print,
+) -> None:
+    if type(value) is ShardedTensor:
+        print_fun(f"{prefix} ShardedTensor size: {value.size()}")
+        for shard in value.local_shards():
+            _print_nested(
+                shard.tensor,
+                f"{shard.metadata.shard_offsets} ",
+                print_fun=print_fun,
+            )
+    elif type(value) is (DTensor):
+        print_fun(f"{prefix} DistributedTensor size: {value.size()}")
+        # TODO: add local offset for _local_tensor in print_nested.
+        _print_nested(
+            value._local_tensor,
+            print_fun=print_fun,
+        )
+    elif isinstance(value, torch.Tensor):
+        print_fun(f"{prefix} Tensor size: {value.size()}")
+    else:
+        print_fun(f"{prefix} Type: {type(value)}")
+
+
+def print_tensor(
+    path: OBJ_PATH,
+    value: STATE_DICT_ITEM,
+    print_fun: Callable[[str], None] = print,
+) -> None:
+    """
+    Use this callback with traverse_state_dict to print its content.
+
+    By default the content is printed using the builtin ``print`` but this can
+    be change by passing a different ``print_fun` callable.
+    """
+    _print_nested(value, prefix=str(path), print_fun=print_fun)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_version.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_version.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3065bdfd6a2c141a959ef0ffe30aeafdc2dc54f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/_version.py
@@ -0,0 +1,6 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates
+
+from typing import Optional
+
+
+_derived_version: Optional[str] = None
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/api.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..e587580617a1bff43f4d50861dd554595b371c3e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/api.py
@@ -0,0 +1,43 @@
+# mypy: allow-untyped-defs
+import traceback as tb
+from typing import Any, Dict, Tuple
+
+
+WRAPPED_EXCEPTION = Tuple[BaseException, tb.StackSummary]
+
+__all__ = ["CheckpointException"]
+
+
+def _wrap_exception(exc: BaseException) -> WRAPPED_EXCEPTION:
+    return (exc, tb.extract_tb(exc.__traceback__))
+
+
+def _is_wrapped_exception(obj: Any) -> bool:
+    if not isinstance(obj, tuple):
+        return False
+    if len(obj) != 2:
+        return False
+    return isinstance(obj[0], BaseException) and isinstance(obj[1], tb.StackSummary)
+
+
+class CheckpointException(BaseException):
+    """Exception raised if failure was detected as part of a checkpoint load or save."""
+
+    def __init__(self, msg: str, failures: Dict[int, WRAPPED_EXCEPTION]):
+        super().__init__(msg, failures)
+        self._failures = failures
+
+    @property
+    def failures(self) -> Dict[int, WRAPPED_EXCEPTION]:
+        """Return a dictionary mapping node ranks to their associated exceptions in case of failure."""
+        return self._failures
+
+    def __str__(self):
+        str = f"CheckpointException ranks:{self._failures.keys()}\n"
+        for rank, exc_pair in self._failures.items():
+            exc, trace = exc_pair
+            str += f"Traceback (most recent call last): (RANK {rank})\n"
+            if trace is not None:
+                str += "".join(tb.format_list(trace))
+            str += "".join(tb.format_exception_only(type(exc), value=exc))
+        return str
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/default_planner.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/default_planner.py
new file mode 100644
index 0000000000000000000000000000000000000000..67f3c73bca51daf1b1d54c34bb575185e021ebf9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/default_planner.py
@@ -0,0 +1,546 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and affiliates
+
+import dataclasses
+import io
+import logging
+import operator
+from collections import ChainMap
+from functools import reduce
+from typing import Any, cast, Dict, List, Optional, Tuple, Union
+
+import torch
+from torch.distributed._shard._utils import narrow_tensor_by_index
+from torch.distributed.checkpoint._dedup_save_plans import dedup_save_plans
+from torch.distributed.checkpoint._nested_dict import (
+    FLATTEN_MAPPING,
+    flatten_state_dict,
+)
+from torch.distributed.checkpoint._sharded_tensor_utils import _flatten_sharded_tensors
+from torch.distributed.checkpoint._traverse import set_element
+from torch.distributed.checkpoint.metadata import (
+    BytesStorageMetadata,
+    ChunkStorageMetadata,
+    Metadata,
+    MetadataIndex,
+    STATE_DICT_TYPE,
+    STORAGE_TYPES,
+    StorageMeta,
+    TensorStorageMetadata,
+)
+from torch.distributed.checkpoint.planner import (
+    LoadPlan,
+    LoadPlanner,
+    ReadItem,
+    SavePlan,
+    SavePlanner,
+    WriteItem,
+    WriteItemType,
+)
+from torch.distributed.checkpoint.planner_helpers import (
+    _create_default_metadata_only_plan,
+    _create_read_items,
+    _create_write_items,
+    _init_state_dict,
+)
+from torch.distributed.checkpoint.utils import find_state_dict_object
+from torch.distributed.tensor import DTensor
+
+from . import _version
+
+
+logger: logging.Logger = logging.getLogger(__name__)
+
+
+__all__ = [
+    "DefaultSavePlanner",
+    "DefaultLoadPlanner",
+    "create_default_local_load_plan",
+    "create_default_global_load_plan",
+    "create_default_local_save_plan",
+    "create_default_global_save_plan",
+]
+
+
+# TODO: Update docstrings for default_planner.py
+class DefaultSavePlanner(SavePlanner):
+    mappings: FLATTEN_MAPPING
+
+    def __init__(
+        self,
+        flatten_state_dict: bool = True,
+        flatten_sharded_tensors: bool = True,
+        dedup_replicated_tensors: Optional[bool] = None,
+        dedup_save_to_lowest_rank: bool = False,
+    ) -> None:
+        self.flatten_state_dict = flatten_state_dict
+        self.flatten_sharded_tensors = flatten_sharded_tensors
+        self.mappings = {}
+        self.dedup_save_to_lowest_rank = dedup_save_to_lowest_rank
+        if dedup_replicated_tensors is not None:
+            logger.warning(
+                "DefaultSavePlanner's `dedup_replicated_tensors` argument is being "
+                "deprecated, and no longer has any effect. Please remove this argument "
+                "from your call."
+            )
+
+    def set_up_planner(
+        self,
+        state_dict: STATE_DICT_TYPE,
+        storage_meta: Optional[StorageMeta] = None,
+        is_coordinator: bool = False,
+    ) -> None:
+        if self.flatten_state_dict:
+            state_dict, self.mappings = flatten_state_dict(state_dict)
+        if self.flatten_sharded_tensors:
+            state_dict = _flatten_sharded_tensors(state_dict)
+        self.state_dict = state_dict
+        self.is_coordinator = is_coordinator
+
+    def create_local_plan(self) -> SavePlan:
+        plan = create_default_local_save_plan(self.state_dict, self.is_coordinator)
+        if self.flatten_state_dict:
+            plan = dataclasses.replace(plan, planner_data=self.mappings)
+        self.plan = plan
+
+        return self.plan
+
+    def create_global_plan(
+        self, all_plans: List[SavePlan]
+    ) -> Tuple[List[SavePlan], Metadata]:
+        all_plans = dedup_save_plans(all_plans, self.dedup_save_to_lowest_rank)
+
+        global_plan, metadata = create_default_global_save_plan(all_plans)
+
+        if self.flatten_state_dict:
+            # | does not work for Python 3.8 or older version.
+            # merged_mappings = reduce(
+            #     lambda x, y: x | y, (p.planner_data for p in global_plan)
+            # )
+            planner_data_dict = [p.planner_data for p in global_plan]
+            merged_mappings = dict(ChainMap(*planner_data_dict))
+            metadata = dataclasses.replace(metadata, planner_data=merged_mappings)
+
+        if not _validate_global_plan(global_plan, metadata):
+            raise ValueError("Failed to validate global plan")
+
+        self.global_plan = global_plan
+        self.metadata = metadata
+
+        return self.global_plan, self.metadata
+
+    def finish_plan(self, new_plan: SavePlan) -> SavePlan:
+        self.plan = new_plan
+        return new_plan
+
+    def resolve_data(self, write_item: WriteItem) -> Union[torch.Tensor, io.BytesIO]:
+        object = self.lookup_object(write_item.index)
+        return self.transform_object(write_item, object)
+
+    def lookup_object(self, index: MetadataIndex) -> Any:
+        """Extension from the planner interface to make it easy to extend the default planner."""
+        return find_state_dict_object(self.state_dict, index)
+
+    def transform_object(self, write_item: WriteItem, object: Any):
+        """Extension from the planner interface to make it easy to extend the default planner."""
+        if write_item.type == WriteItemType.BYTE_IO:
+            bytes = io.BytesIO()
+            torch.save(object, bytes)
+            object = bytes
+        return object
+
+
+class DefaultLoadPlanner(LoadPlanner):
+    """
+    DefaultLoadPlanner that adds multiple features on top of LoadPlanner.
+
+    In particular it adds the following:
+
+    flatten_state_dict: Handle state_dict with nested dicts
+    flatten_sharded_tensors: For FSDP in 2D parallel mode
+    allow_partial_load: If False, will raise a runtime error if a key is present in state_dict, but not in the checkpoint.
+    """
+
+    original_state_dict: STATE_DICT_TYPE
+    mappings: FLATTEN_MAPPING
+
+    def __init__(
+        self,
+        flatten_state_dict: bool = True,
+        flatten_sharded_tensors: bool = True,
+        allow_partial_load: bool = False,
+    ) -> None:
+        self.flatten_state_dict = flatten_state_dict
+        self.flatten_sharded_tensors = flatten_sharded_tensors
+        self.original_state_dict = {}
+        self.mappings = {}
+        self.allow_partial_load = allow_partial_load
+
+    def set_up_planner(
+        self,
+        state_dict: STATE_DICT_TYPE,
+        metadata: Optional[Metadata] = None,
+        is_coordinator: bool = False,
+    ) -> None:
+        _init_state_dict(state_dict)
+        self.original_state_dict = state_dict
+
+        if self.flatten_sharded_tensors:
+            state_dict = _flatten_sharded_tensors(state_dict)
+
+        if self.flatten_state_dict:
+            state_dict, self.mappings = flatten_state_dict(state_dict)
+
+        self.state_dict = state_dict
+        self.metadata = metadata
+        self.is_coordinator = is_coordinator
+
+    def create_local_plan(self) -> LoadPlan:
+        assert self.metadata is not None
+        if self.flatten_state_dict:
+            # To support checkpoints that are saved before v2.4, we have to
+            # differentiate if the missing keys are due to old checkpoints.
+            # The contracts are:
+            # 1. There are 3 cases when we found a missing key.
+            #    1.1 Actual missing key, but allow_partial_load is False
+            #    1.2 Actual missing key, but allow_partial load is True
+            #    1.3 Old checkpoint, but allow_partial_load is False
+            #    1.4 Old checkpoint, but allow_partial_load is True
+            # 2. If we found a missing key, we first convert the keys back to
+            #    the key format of v2.3
+            # 3. If the previous missing keys are in the v2.3 keys, we assume
+            #    this is a old checkpoint.
+            # 4. Pass the state_dict to `create_default_local_load_plan()`,
+            #    which has the logic to check missing for allow_partial_load.
+            # So for 1.2 and 1.4 cases, we delegate allow_partial_load check to
+            # `create_default_local_load_plan()`. The logic here is to determine
+            # whether the checkpoint belong to 2.3 (or before) or 2.4 (or after).
+            current_keys = set(self.state_dict.keys())
+            load_keys = set(self.metadata.state_dict_metadata.keys())
+            missing_keys = load_keys - current_keys
+            if missing_keys:
+                _version._derived_version = "2_3"
+                old_state_dict, old_mappings = flatten_state_dict(
+                    self.original_state_dict
+                )
+                old_keys = set(old_state_dict.keys())
+                if old_keys & missing_keys:
+                    self.state_dict, self.mappings = old_state_dict, old_mappings
+                # _derived_version is only used by flatten_state_dict now.
+                # Set it back to None so that later we can save to a new version.
+                _version._derived_version = None
+
+        return create_default_local_load_plan(
+            self.state_dict, self.metadata, not self.allow_partial_load
+        )
+
+    def create_global_plan(self, global_plan: List[LoadPlan]) -> List[LoadPlan]:
+        return create_default_global_load_plan(global_plan)
+
+    def finish_plan(self, new_plan: LoadPlan) -> LoadPlan:
+        return new_plan
+
+    def load_bytes(self, read_item: ReadItem, value: io.BytesIO) -> None:
+        if self.flatten_state_dict:
+            set_element(
+                self.original_state_dict,
+                self.mappings[read_item.dest_index.fqn],
+                torch.load(value, weights_only=False),
+            )
+        else:
+            self.state_dict[read_item.dest_index.fqn] = torch.load(
+                value, weights_only=False
+            )
+
+    def resolve_tensor(self, read_item: ReadItem):
+        tensor = self.lookup_tensor(read_item.dest_index)
+        return self.transform_tensor(read_item, tensor)
+
+    def commit_tensor(self, read_item: ReadItem, tensor: torch.Tensor) -> None:
+        pass
+
+    def lookup_tensor(self, index: MetadataIndex) -> torch.Tensor:
+        """Extension from the planner interface to make it easy to extend the default planner."""
+        return find_state_dict_object(self.state_dict, index)
+
+    def transform_tensor(self, read_item: ReadItem, tensor: torch.Tensor):
+        """Extension from the planner interface to make it easy to extend the default planner."""
+        return narrow_tensor_by_index(tensor, read_item.dest_offsets, read_item.lengths)
+
+
+class _EmptyStateDictLoadPlanner(DefaultLoadPlanner):
+    """
+    Extension of DefaultLoadPlanner, which rebuilds state_dict from the saved metadata.
+    Useful for loading in state_dict without first initializing a model, such as
+    when converting a DCP checkpoint into a Torch save file.
+
+    . N.B. `state_dict` must be an empty dictionary when used with this LoadPlanner
+
+    .. warning::
+        Because the entire state dict is initialized, It's recommended to only utilize
+        this LoadPlanner on a single rank or process to avoid OOM.
+
+    """
+
+    def __init__(self, keys=None, *args, **kwargs):
+        self.keys = keys
+        super().__init__(*args, **kwargs)
+
+    def _should_include_key(self, key: str, metadata: Metadata) -> bool:
+        if self.keys is None:
+            return True
+
+        if key in self.keys:
+            True
+
+        unflattened_keys: List[str] = []
+        planner_data = metadata.planner_data.get(key)
+        for unflattened_key in planner_data:
+            if unflattened_keys:
+                unflattened_keys.append(
+                    ".".join([unflattened_keys[-1], str(unflattened_key)])
+                )
+
+            else:
+                unflattened_keys.append(unflattened_key)
+
+        if any(unflattened_key in self.keys for unflattened_key in unflattened_keys):
+            return True
+
+        return False
+
+    def set_up_planner(
+        self,
+        state_dict: STATE_DICT_TYPE,
+        metadata: Optional[Metadata] = None,
+        is_coordinator: bool = False,
+    ) -> None:
+        assert not state_dict
+        assert metadata is not None
+
+        # rebuild the state dict from the metadata
+        for k, v in metadata.state_dict_metadata.items():
+            if not self._should_include_key(k, metadata):
+                continue
+
+            if isinstance(v, TensorStorageMetadata):
+                v = torch.empty(v.size, dtype=v.properties.dtype)  # type: ignore[assignment]
+            if k in metadata.planner_data:
+                set_element(state_dict, metadata.planner_data[k], v)
+            else:
+                state_dict[k] = v
+
+        super().set_up_planner(state_dict, metadata, is_coordinator)
+
+
+def create_default_local_load_plan(
+    state_dict: Dict[str, Any], metadata: Metadata, strict: bool = True
+) -> LoadPlan:
+    requests = []
+    """
+    Create the ``LoadPlan`` used by DefaultLoadPlanner.
+
+    It produces one read item per value in ``state_dict`` using the metadata in ``metadata``.
+
+    The default behavior is to match key exactly between state_dict and metadata.
+    It handles resharding by issuing multiple read requests against storage in order to match
+    load requirements.
+    """
+
+    for fqn, obj in state_dict.items():
+        # ignore state_dict keys which do not exist in `state_dict` if strict=False
+        if fqn not in metadata.state_dict_metadata:
+            if strict:
+                raise RuntimeError(f"Missing key in checkpoint state_dict: {fqn}.")
+            else:
+                continue
+
+        md = metadata.state_dict_metadata[fqn]
+        # Since DTensor supports submesh, adding extra check to ensure _create_read_items()
+        # gets called only when the current rank is part of the mesh for the corresponding DTensor.
+        if isinstance(obj, DTensor):
+            if obj.device_mesh.get_coordinate() is not None:
+                requests += _create_read_items(fqn, md, obj)
+        else:
+            requests += _create_read_items(fqn, md, obj)
+
+    return LoadPlan(requests)
+
+
+def create_default_global_load_plan(
+    all_plans: List[LoadPlan],
+) -> List[LoadPlan]:
+    """
+    Create global load plan used by DefaultLoadPlanner.
+
+    The default load behavior involved no global coordination and this function
+    currently doesn't change the local plans.
+    """
+    return all_plans
+
+
+def create_default_local_save_plan(
+    state_dict: Dict[str, Any], is_coordinator: bool
+) -> SavePlan:
+    """
+    Create the ``SavePlan`` used by DefaultSavePlanner.
+
+    On non-coordinator ranks, this function ignores tensors and non-tensor objects,
+    only producing writes for ShardedTensor objects.
+
+    On the coordinator rank, produce writes for all values.
+    """
+    requests = []
+    for fqn, obj in state_dict.items():
+        # Since DTensor supports submesh, adding extra check to ensure _create_write_items()
+        # gets called only when the current rank is part of the mesh for the corresponding DTensor.
+        if isinstance(obj, DTensor):
+            if obj.device_mesh.get_coordinate() is not None:
+                requests += _create_write_items(fqn, obj)
+        else:
+            # For the plain tensor and non-tensor values, add the request for all
+            # the ranks. Coordinator will decides whether to deduplicate the
+            # values based on the keys.
+            requests += _create_write_items(fqn, obj)
+
+    return SavePlan(requests)
+
+
+def create_default_global_save_plan(
+    all_plans: List[SavePlan],
+    rewrite_index_hints: bool = True,
+) -> Tuple[List[SavePlan], Metadata]:
+    """
+    Create the global plan and metadata used by DefaultSavePlanner.
+
+    Metadata is produced by concatenating the metadata of all ``WriteItem`` from the supplied plans.
+
+    The only global planning change is to update index hints in all ``MetadataIndex`` objects if
+    ``rewrite_index_hints`` is True.
+    """
+    md: Dict[str, STORAGE_TYPES] = {}
+    new_plans = []
+    for plan in all_plans:
+        new_items = []
+        for item in plan.items:
+            if not item.type == WriteItemType.SHARD:
+                assert item.index.fqn not in md
+
+            if item.type == WriteItemType.BYTE_IO:
+                md[item.index.fqn] = BytesStorageMetadata()
+                new_items.append(item)
+            else:
+                assert item.tensor_data is not None
+                tensor_md = cast(
+                    TensorStorageMetadata,
+                    md.setdefault(
+                        item.index.fqn,
+                        TensorStorageMetadata(
+                            properties=item.tensor_data.properties,
+                            size=item.tensor_data.size,
+                            chunks=[],
+                        ),
+                    ),
+                )
+                new_item = item
+                if rewrite_index_hints:
+                    new_index = dataclasses.replace(
+                        item.index, index=len(tensor_md.chunks)
+                    )
+                    new_item = dataclasses.replace(item, index=new_index)
+                new_items.append(new_item)
+
+                assert (
+                    item.tensor_data.chunk is not None
+                ), f"""
+                    Cannot create MD for tensor without bounds.
+                    FQN: {item.index.fqn}
+                """
+                tensor_md.chunks.append(item.tensor_data.chunk)
+        new_plans.append(dataclasses.replace(plan, items=new_items))
+    return (new_plans, Metadata(md))
+
+
+def _create_default_local_metadata(state_dict: STATE_DICT_TYPE) -> Metadata:
+    """Return the ``Metadata`` if DefaultSavePlanner was used to checkpoint ``state_dict``."""
+    plan = _create_default_metadata_only_plan(state_dict)
+    _, md = create_default_global_save_plan([plan])
+    return md
+
+
+def _check_box_overlap(box0: ChunkStorageMetadata, box1: ChunkStorageMetadata) -> bool:
+    """Check if two boxes overlap. Tuples are (offset, lengths)."""
+    # For each dim of each shard, check if one shard resides on the other
+    # end of second shard with respect to that dim. As an example for a 2D
+    # shard, we would check if one shard is above or on the left of the
+    # other shard.
+    ndims = len(box0.offsets)
+    for i in range(ndims):
+        if box0.offsets[i] >= box1.offsets[i] + box1.sizes[i]:
+            return False
+        if box1.offsets[i] >= box0.offsets[i] + box0.sizes[i]:
+            return False
+
+    return True
+
+
+def _check_box_bounds(
+    outer_box_size: torch.Size, inner_box: ChunkStorageMetadata
+) -> bool:
+    for i in range(len(outer_box_size)):
+        if inner_box.offsets[i] < 0:
+            return False
+        if inner_box.sizes[i] < 0:
+            return False
+        if inner_box.offsets[i] + inner_box.sizes[i] > outer_box_size[i]:
+            return False
+
+    return True
+
+
+def _validate_global_plan(global_plan: List[SavePlan], metadata: Metadata) -> bool:
+    all_good = True
+    for key, value in metadata.state_dict_metadata.items():
+        if isinstance(value, BytesStorageMetadata):
+            continue
+        if len(value.size) == 0:
+            continue
+        chunks_volume = 0
+        for chunk_idx, chunk0 in enumerate(value.chunks):
+            # Compute the volume
+            if not _check_box_bounds(value.size, chunk0):
+                logger.warning(
+                    """
+                        key:%s has out of bounds chunk:
+                        tensor-size:%s chunk: %s
+                    """,
+                    key,
+                    value.size,
+                    chunk0,
+                )
+                all_good = False
+            chunks_volume += reduce(operator.mul, chunk0.sizes, 1)
+
+            # Check for overlap
+            for chunk1 in value.chunks[chunk_idx + 1 :]:
+                if _check_box_overlap(chunk0, chunk1):
+                    logger.warning(
+                        "key:%s has overlapping chunks: %s %s", key, chunk0, chunk1
+                    )
+                    all_good = False
+
+        # Check whether combined chunk cover the whole tensor
+        tensor_volume = reduce(operator.mul, value.size, 1)
+        if chunks_volume != tensor_volume:
+            logger.warning(
+                """
+                    key:%s invalid fill tensor-volume:
+                    %s chunks-volume: %s
+                """,
+                key,
+                tensor_volume,
+                chunks_volume,
+            )
+            all_good = False
+
+    return all_good
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/filesystem.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/filesystem.py
new file mode 100644
index 0000000000000000000000000000000000000000..3faee96b238dc761e760e0d3c0e2faf21ca6db03
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/filesystem.py
@@ -0,0 +1,765 @@
+# mypy: allow-untyped-defs
+import collections
+import dataclasses
+import io
+import operator
+import os
+import pickle
+import queue
+import threading
+import uuid
+import warnings
+from abc import ABC, abstractmethod
+from contextlib import contextmanager
+from dataclasses import dataclass
+from pathlib import Path
+from typing import (
+    Any,
+    Callable,
+    cast,
+    Dict,
+    Generator,
+    IO,
+    Iterable,
+    Iterator,
+    List,
+    Optional,
+    Tuple,
+    Union,
+)
+
+import torch
+from torch import Tensor
+from torch._utils import _get_available_device_type, _get_device_module
+from torch.distributed._shard._utils import narrow_tensor_by_index
+from torch.distributed.checkpoint.metadata import (
+    Metadata,
+    MetadataIndex,
+    STATE_DICT_TYPE,
+    StorageMeta,
+)
+from torch.distributed.checkpoint.planner import (
+    LoadItemType,
+    LoadPlan,
+    LoadPlanner,
+    ReadItem,
+    SavePlan,
+    SavePlanner,
+    WriteItem,
+    WriteItemType,
+)
+from torch.distributed.checkpoint.staging import BlockingAsyncStager
+from torch.distributed.checkpoint.storage import (
+    StorageReader,
+    StorageWriter,
+    WriteResult,
+)
+from torch.distributed.checkpoint.utils import _create_file_view
+from torch.futures import Future
+
+
+__all__ = ["FileSystemWriter", "FileSystemReader", "FileSystem", "FileSystemBase"]
+
+_metadata_fn: str = ".metadata"
+
+
+@dataclass
+class _StorageInfo:
+    """This is the per entry storage info."""
+
+    relative_path: str
+    offset: int
+    length: int
+
+
+@dataclass
+class _StoragePrefix:
+    prefix: str
+
+
+DEFAULT_SUFFIX = ".distcp"
+
+
+def _generate_uuid() -> str:
+    return str(uuid.uuid4())
+
+
+class _TensorLoader(ABC):
+    @abstractmethod
+    def add(self, size: int, obj: object) -> None:
+        pass
+
+    @abstractmethod
+    def start_loading(self) -> None:
+        pass
+
+    @abstractmethod
+    def values(self) -> Iterator[Tuple[torch.Tensor, object]]:
+        pass
+
+
+class _SerialCpuLoader(_TensorLoader):
+    def __init__(self, resolve_fun: Callable) -> None:
+        self.resolve_fun = resolve_fun
+        self.items: List[Tuple[int, object]] = []
+
+    def add(self, size: int, obj: object) -> None:
+        self.items.append((size, obj))
+
+    def start_loading(self) -> None:
+        pass
+
+    def values(self) -> Iterator[Tuple[torch.Tensor, object]]:
+        for _, obj in self.items:
+            tensor = self.resolve_fun(obj).detach()
+            tensor = tensor.cpu()
+            if tensor.storage().size() != tensor.numel():
+                tensor = tensor.clone()
+            yield (
+                tensor,
+                obj,
+            )
+
+
+class _OverlappingCpuLoader(_TensorLoader):
+    def __init__(
+        self,
+        resolve_fun: Callable,
+        stream: Optional[torch.Stream] = None,
+        inflight_threshhold: int = 1_000_000,
+    ) -> None:
+        self.resolve_fun = resolve_fun
+        self.items: List[Tuple[int, object]] = []
+        self.inflight_threshhold = inflight_threshhold
+        self.in_flight_data = 0
+        self.current_items: collections.deque = collections.deque()
+        self.idx = 0
+        self.started = False
+        self.device_type = (
+            stream.device_type if stream else _get_available_device_type()
+        )
+        self.device_module = _get_device_module(self.device_type)
+        self.stream = cast(
+            torch.cuda.Stream, stream or self.device_module.current_stream()
+        )
+        if self.stream != self.device_module.current_stream():
+            self.stream.wait_stream(self.device_module.current_stream())
+
+    @property
+    def _done(self) -> bool:
+        return self.idx >= len(self.items)
+
+    def _drain(self) -> List[Tuple[torch.Tensor, object]]:
+        drained = []
+        if self.in_flight_data >= self.inflight_threshhold:
+            self.stream.synchronize()
+        while self.in_flight_data >= self.inflight_threshhold:
+            val = self.current_items.popleft()
+            self.in_flight_data -= val[0].numel() * val[0].element_size()
+            drained.append(val)
+        return drained
+
+    def _refill(self) -> None:
+        with self.device_module.stream(self.stream):
+            while not self._done and self.in_flight_data < self.inflight_threshhold:
+                _, obj = self.items[self.idx]
+                self.idx += 1
+                tensor = self.resolve_fun(obj).detach()
+                if tensor.device.type == self.device_type:
+                    tensor = tensor.to(device="cpu", non_blocking=True)
+                elif tensor.device == torch.device("cpu"):
+                    if (
+                        tensor.untyped_storage().size()
+                        != tensor.numel() * tensor.itemsize
+                    ):
+                        # this forces the tensor to be both contiguous and with minimal storage
+                        tensor = tensor.clone()
+
+                self.current_items.append(
+                    (
+                        tensor,
+                        obj,
+                    )
+                )
+                self.in_flight_data += tensor.numel() * tensor.element_size()
+
+    def _finish(self) -> Iterable[Tuple[torch.Tensor, object]]:
+        assert self._done
+        if len(self.current_items) > 0:
+            self.stream.synchronize()
+        return self.current_items
+
+    def add(self, size: int, obj: object) -> None:
+        if self.started:
+            raise RuntimeError("cannot add items after loading started")
+        self.items.append((size, obj))
+
+    def start_loading(self) -> None:
+        if self.started:
+            return
+        self.started = True
+        self.items.sort(key=operator.itemgetter(0))
+        self._refill()
+
+    def values(self) -> Iterator[Tuple[torch.Tensor, object]]:
+        self.start_loading()
+        while not self._done:
+            drained = self._drain()
+            self._refill()
+            yield from drained
+
+        yield from self._finish()
+
+
+def _item_size(item: WriteItem) -> int:
+    size = 1
+    assert item.tensor_data is not None
+    # can't use math.prod as PT needs to support older python
+    for s in item.tensor_data.size:
+        size *= s
+
+    dtype = item.tensor_data.properties.dtype
+    return size * torch._utils._element_size(dtype)
+
+
+def _split_by_size_and_type(bins: int, items: List[WriteItem]) -> List[List[WriteItem]]:
+    if bins == 1:
+        return [items]
+
+    bytes_w = [wi for wi in items if wi.type == WriteItemType.BYTE_IO]
+    tensor_w = [wi for wi in items if wi.type != WriteItemType.BYTE_IO]
+
+    buckets: List[List[WriteItem]] = [[] for _ in range(bins)]
+    bucket_sizes = [0 for _ in range(bins)]
+
+    tensor_w.sort(key=_item_size, reverse=True)
+
+    for i, wi in enumerate(bytes_w):
+        buckets[i % bins].append(wi)
+
+    for wi in tensor_w:
+        # TODO replace with headq
+        idx = min(enumerate(bucket_sizes), key=operator.itemgetter(1))[0]
+        buckets[idx].append(wi)
+        bucket_sizes[idx] += _item_size(wi)
+
+    return buckets
+
+
+def _write_item(
+    stream: io.IOBase,
+    data: Union[io.BytesIO, torch.Tensor],
+    write_item: WriteItem,
+    storage_key: str,
+) -> WriteResult:
+    offset = stream.tell()
+
+    if write_item.type == WriteItemType.BYTE_IO:
+        assert isinstance(data, io.BytesIO)
+        stream.write(data.getbuffer())
+    else:
+        assert isinstance(data, torch.Tensor)
+        assert data.device == torch.device("cpu")
+        torch.save(data, cast(IO[bytes], stream))
+    length = stream.tell() - offset
+
+    return WriteResult(
+        index=write_item.index,
+        size_in_bytes=length,
+        storage_data=_StorageInfo(storage_key, offset, length),
+    )
+
+
+def _write_files_from_queue(
+    create_stream: Callable,
+    file_queue: queue.Queue,
+    result_queue: queue.Queue,
+    planner: SavePlanner,
+    inflight_threshhold: int,
+    use_fsync: bool,
+    thread_count: int,
+) -> None:
+    try:
+        while True:
+            file_name, storage_key, write_items = file_queue.get_nowait()
+            loader: _TensorLoader
+
+            custom_backend_name = torch._C._get_privateuse1_backend_name()
+            custom_device_mod = getattr(torch, custom_backend_name, None)
+
+            # TODO: Using the OverlappingCpuLoader with multiple threads creates significant
+            # performance degredation, observed as being related to cuda stream syncs. We
+            # should try to fix this and use _OverlappingCpuLoader for all threaded cases
+            if (
+                thread_count == 1
+                and (
+                    torch.cuda.is_available()
+                    or (custom_device_mod and custom_device_mod.is_available())
+                )
+                and inflight_threshhold > 0
+            ):
+                loader = _OverlappingCpuLoader(
+                    planner.resolve_data,
+                    inflight_threshhold=inflight_threshhold,
+                )
+            else:
+                loader = _SerialCpuLoader(
+                    planner.resolve_data,
+                )
+
+            tensor_w = [wi for wi in write_items if wi.type != WriteItemType.BYTE_IO]
+            for write_item in tensor_w:
+                loader.add(_item_size(write_item), write_item)
+            loader.start_loading()
+
+            bytes_w = [wi for wi in write_items if wi.type == WriteItemType.BYTE_IO]
+            write_results = []
+
+            with create_stream(file_name, "wb") as stream:
+                for write_item in bytes_w:
+                    data = planner.resolve_data(write_item)
+                    write_results.append(
+                        _write_item(stream, data, write_item, storage_key)
+                    )
+
+                for tensor, write_item in loader.values():
+                    assert tensor.is_cpu
+                    write_results.append(
+                        _write_item(stream, tensor, write_item, storage_key)
+                    )
+
+                if use_fsync:
+                    try:
+                        os.fsync(stream.fileno())
+                    except AttributeError:
+                        os.sync()
+            result_queue.put(write_results)
+    except queue.Empty:
+        pass
+
+
+class FileSystemBase(ABC):
+    @contextmanager
+    @abstractmethod
+    def create_stream(
+        self, path: Union[str, os.PathLike], mode: str
+    ) -> Generator[io.IOBase, None, None]:
+        ...
+
+    @abstractmethod
+    def concat_path(
+        self, path: Union[str, os.PathLike], suffix: str
+    ) -> Union[str, os.PathLike]:
+        ...
+
+    @abstractmethod
+    def rename(
+        self, path: Union[str, os.PathLike], new_path: Union[str, os.PathLike]
+    ) -> None:
+        ...
+
+    @abstractmethod
+    def init_path(self, path: Union[str, os.PathLike]) -> Union[str, os.PathLike]:
+        ...
+
+    @abstractmethod
+    def mkdir(self, path: Union[str, os.PathLike]) -> None:
+        ...
+
+    @classmethod
+    @abstractmethod
+    def validate_checkpoint_id(cls, checkpoint_id: Union[str, os.PathLike]) -> bool:
+        ...
+
+    @abstractmethod
+    def exists(self, path: Union[str, os.PathLike]) -> bool:
+        ...
+
+    @abstractmethod
+    def rm_file(self, path: Union[str, os.PathLike]) -> None:
+        ...
+
+
+class FileSystem(FileSystemBase):
+    @contextmanager
+    def create_stream(
+        self, path: Union[str, os.PathLike], mode: str
+    ) -> Generator[io.IOBase, None, None]:
+        with cast(Path, path).open(mode) as stream:
+            yield cast(io.IOBase, stream)
+
+    def concat_path(
+        self, path: Union[str, os.PathLike], suffix: str
+    ) -> Union[str, os.PathLike]:
+        return cast(Path, path) / suffix
+
+    def init_path(self, path: Union[str, os.PathLike]) -> Union[str, os.PathLike]:
+        if not isinstance(path, Path):
+            path = Path(path)
+        return path
+
+    def rename(
+        self, path: Union[str, os.PathLike], new_path: Union[str, os.PathLike]
+    ) -> None:
+        cast(Path, path).rename(cast(Path, new_path))
+
+    def mkdir(self, path: Union[str, os.PathLike]) -> None:
+        cast(Path, path).mkdir(parents=True, exist_ok=True)
+
+    @classmethod
+    def validate_checkpoint_id(cls, checkpoint_id: Union[str, os.PathLike]) -> bool:
+        if isinstance(checkpoint_id, Path):
+            return True
+
+        if "://" in str(checkpoint_id):
+            return False
+
+        for p in Path(checkpoint_id).parents:
+            if p.exists() and os.access(str(p), os.W_OK):
+                return True
+
+        return False
+
+    def exists(self, path: Union[str, os.PathLike]) -> bool:
+        return cast(Path, path).exists()
+
+    def rm_file(self, path: Union[str, os.PathLike]) -> None:
+        cast(Path, path).unlink()
+
+
+class _FileSystemWriter(StorageWriter):
+    """
+    Basic implementation of StorageWriter using file IO.
+
+    This implementation makes the following assumptions and simplifications:
+
+    * The checkpoint path is an empty or non-existing directory.
+    * File creation is atomic
+
+    The checkpoint consist of one file per write request plus
+    a `.metadata` file with the serialized metadata.
+
+    """
+
+    def __init__(
+        self,
+        path: Union[str, os.PathLike],
+        single_file_per_rank: bool = True,
+        sync_files: bool = True,
+        thread_count: int = 1,
+        per_thread_copy_ahead: int = 10_000_000,
+        overwrite: bool = True,
+        *args: Any,
+        **kwargs: Any,
+    ) -> None:
+        """
+        Initialize the writer pointing to `path`.
+
+        Args:
+            path: directory where the checkpoint will be written to.
+            single_file_per_rank: Produce one file per rank instead of one file per tensor/blob. Default to True.
+            sync_files : force files to be synced to permanent storage. Default to True.
+            thread_count: Number of IO threads to use to write. Default to 1.
+            per_thread_copy_ahead: How many bytes to copy from the GPU ahead of saving then. Default 10Mb.
+            overwrite: Whether to allow overwriting existing checkpoints. Defaults to True.
+
+        N. B. If sync_files is disabled, there's no guarantee that the checkpoint will be consistent in the case of a failure.
+        """
+        super().__init__()
+        self.fs = FileSystem()
+        self.path = self.fs.init_path(path)
+        self.single_file_per_rank = single_file_per_rank
+        self.sync_files = sync_files
+        self.thread_count = thread_count
+        self.per_thread_copy_ahead = per_thread_copy_ahead
+        self.save_id = _generate_uuid()
+        self.overwrite = overwrite
+
+    def reset(self, checkpoint_id: Union[str, os.PathLike, None] = None) -> None:
+        if checkpoint_id:
+            self.path = self.fs.init_path(checkpoint_id)
+        self.save_id = _generate_uuid()
+
+    def set_up_storage_writer(self, is_coordinator: bool) -> None:
+        pass
+
+    def prepare_local_plan(self, plan: SavePlan) -> SavePlan:
+        self.fs.mkdir(self.path)
+        if self.fs.exists(self.metadata_path):
+            if self.overwrite:
+                warnings.warn(
+                    f"Detected an existing checkpoint in {self.metadata_path}, overwriting since {self.overwrite=}."
+                    " Past version 2.5 of PyTorch, `overwrite` will default to False. Set this variable to True to"
+                    " maintain this functionality or False to raise when an existing checkpoint is found."
+                )
+            else:
+                raise RuntimeError(f"Checkpoint already exists and {self.overwrite=}.")
+
+        return plan
+
+    def prepare_global_plan(self, plans: List[SavePlan]) -> List[SavePlan]:
+        new_plans = [
+            dataclasses.replace(plan, storage_data=_StoragePrefix(f"__{i}_"))
+            for i, plan in enumerate(plans)
+        ]
+        return new_plans
+
+    def write_data(
+        self,
+        plan: SavePlan,
+        planner: SavePlanner,
+    ) -> Future[List[WriteResult]]:
+        storage_plan: _StoragePrefix = plan.storage_data
+        file_count = 0
+
+        def gen_file():
+            nonlocal file_count
+            file_name = f"{storage_plan.prefix}{file_count}{DEFAULT_SUFFIX}"
+            file_count += 1
+            return file_name
+
+        file_queue: queue.Queue = queue.Queue()
+        if self.single_file_per_rank:
+            for bucket in _split_by_size_and_type(self.thread_count, plan.items):
+                file_name = gen_file()
+                path = self.fs.concat_path(self.path, file_name)
+                file_queue.put((path, file_name, bucket))
+        else:
+            for item in plan.items:
+                file_name = gen_file()
+                path = self.fs.concat_path(self.path, file_name)
+                file_queue.put((path, file_name, [item]))
+
+        result_queue: queue.Queue = queue.Queue()
+
+        threads = []
+        for _ in range(1, self.thread_count):
+            t = threading.Thread(
+                target=_write_files_from_queue,
+                args=(
+                    self.fs.create_stream,
+                    file_queue,
+                    result_queue,
+                    planner,
+                    self.per_thread_copy_ahead,
+                    self.sync_files,
+                    self.thread_count,
+                ),
+            )
+            t.start()
+            threads.append(t)
+
+        _write_files_from_queue(
+            create_stream=self.fs.create_stream,
+            file_queue=file_queue,
+            result_queue=result_queue,
+            planner=planner,
+            inflight_threshhold=self.per_thread_copy_ahead,
+            use_fsync=self.sync_files,
+            thread_count=self.thread_count,
+        )
+
+        for t in threads:
+            t.join()
+
+        res = []
+        try:
+            while True:
+                res += result_queue.get_nowait()
+        except queue.Empty:
+            fut: Future[List[WriteResult]] = Future()
+            fut.set_result(res)
+            return fut
+
+    def finish(self, metadata: Metadata, results: List[List[WriteResult]]) -> None:
+        storage_md = {}
+        for wr_list in results:
+            storage_md.update({wr.index: wr.storage_data for wr in wr_list})
+        metadata.storage_data = storage_md
+
+        metadata.storage_meta = self.storage_meta()
+
+        tmp_path = cast(Path, self.fs.concat_path(self.path, f"{_metadata_fn}.tmp"))
+        with self.fs.create_stream(tmp_path, "wb") as metadata_file:
+            pickle.dump(metadata, metadata_file)
+            if self.sync_files:
+                try:
+                    os.fsync(metadata_file.fileno())
+                except AttributeError:
+                    os.sync()
+
+        # delete in-case other checkpoints were present.
+        if self.fs.exists(self.metadata_path):
+            self.fs.rm_file(self.metadata_path)
+
+        self.fs.rename(tmp_path, self.metadata_path)
+
+    def storage_meta(self) -> Optional[StorageMeta]:
+        return StorageMeta(checkpoint_id=self.checkpoint_id, save_id=self.save_id)
+
+    @property
+    def metadata_path(self) -> Union[str, os.PathLike]:
+        return cast(Path, self.fs.concat_path(self.path, _metadata_fn))
+
+    @property
+    def checkpoint_id(self) -> Union[str, os.PathLike]:
+        """
+        return the checkpoint_id that will be used to save the checkpoint.
+        """
+        return self.path
+
+    @classmethod
+    def validate_checkpoint_id(cls, checkpoint_id: Union[str, os.PathLike]) -> bool:
+        return FileSystem.validate_checkpoint_id(checkpoint_id)
+
+
+class FileSystemReader(StorageReader):
+    def __init__(self, path: Union[str, os.PathLike]) -> None:
+        super().__init__()
+        self.fs = FileSystem()
+        self.path = self.fs.init_path(path)
+        self.storage_data: Dict[MetadataIndex, _StorageInfo] = {}
+        self.load_id = _generate_uuid()
+
+    def _slice_file(self, file, sinfo: _StorageInfo) -> io.IOBase:
+        return _create_file_view(file, sinfo.offset, sinfo.length)
+
+    def reset(self, checkpoint_id: Union[str, os.PathLike, None] = None) -> None:
+        self.storage_data = {}
+        if checkpoint_id:
+            self.path = self.fs.init_path(checkpoint_id)
+        self.load_id = _generate_uuid()
+
+    def read_data(self, plan: LoadPlan, planner: LoadPlanner) -> Future[None]:
+        # group requests by file
+        per_file: Dict[str, List[ReadItem]] = {}
+        for read_item in plan.items:
+            item_md = self.storage_data[read_item.storage_index]
+            path = item_md.relative_path
+            per_file.setdefault(path, []).append(read_item)
+
+        for relative_path, reqs in per_file.items():
+            new_path = self.fs.concat_path(self.path, relative_path)
+            with self.fs.create_stream(new_path, "rb") as stream:
+                # TODO sort by offset and cache the reading
+                for req in reqs:
+                    item_md = self.storage_data[req.storage_index]
+                    file_slice = self._slice_file(stream, item_md)
+                    if req.type == LoadItemType.BYTE_IO:
+                        read_bytes = io.BytesIO(file_slice.read(item_md.length))
+                        read_bytes.seek(0)
+                        planner.load_bytes(req, read_bytes)
+                    else:
+                        tensor = cast(
+                            Tensor,
+                            torch.load(
+                                cast(IO[bytes], file_slice),
+                                map_location="cpu",
+                                weights_only=True,
+                            ),
+                        )
+                        tensor = narrow_tensor_by_index(
+                            tensor, req.storage_offsets, req.lengths
+                        )
+                        target_tensor = planner.resolve_tensor(req).detach()
+
+                        assert (
+                            target_tensor.size() == tensor.size()
+                        ), f"req {req.storage_index} mismatch sizes {target_tensor.size()} vs {tensor.size()}"
+                        target_tensor.copy_(tensor)
+                        planner.commit_tensor(req, target_tensor)
+
+        fut: Future = Future()
+        fut.set_result(None)
+        return fut
+
+    # Implementing the abstract function in StorageReader
+    def read_metadata(self) -> Metadata:
+        path = self.fs.concat_path(self.path, ".metadata")
+        with self.fs.create_stream(path, "rb") as metadata_file:
+            metadata = pickle.load(metadata_file)
+
+        if getattr(metadata, "storage_meta", None) is None:
+            metadata.storage_meta = StorageMeta()
+        metadata.storage_meta.load_id = self.load_id
+
+        return metadata
+
+    def set_up_storage_reader(self, metadata: Metadata, is_coordinator: bool) -> None:
+        self.storage_data = metadata.storage_data
+        assert self.storage_data is not None
+
+    def prepare_local_plan(self, plan: LoadPlan) -> LoadPlan:
+        return plan
+
+    def prepare_global_plan(self, plans: List[LoadPlan]) -> List[LoadPlan]:
+        return plans
+
+    @property
+    def checkpoint_id(self) -> Union[str, os.PathLike]:
+        """
+        return the checkpoint_id that will be used to load the checkpoint.
+        """
+        return self.path
+
+    @classmethod
+    def validate_checkpoint_id(cls, checkpoint_id: Union[str, os.PathLike]) -> bool:
+        return FileSystem.validate_checkpoint_id(checkpoint_id)
+
+
+class FileSystemWriter(_FileSystemWriter, BlockingAsyncStager):
+    """
+    Basic implementation of StorageWriter using file IO.
+
+    This implementation makes the following assumptions and simplifications:
+
+    * The checkpoint path is an empty or non-existing directory.
+    * File creation is atomic
+
+    The checkpoint consist of one file per write request plus
+    a `.metadata` file with the serialized metadata.
+
+    """
+
+    def __init__(
+        self,
+        path: Union[str, os.PathLike],
+        single_file_per_rank: bool = True,
+        sync_files: bool = True,
+        thread_count: int = 1,
+        per_thread_copy_ahead: int = 10_000_000,
+        cache_staged_state_dict: bool = False,
+        overwrite: bool = True,
+    ) -> None:
+        """
+        Initialize the writer pointing to `path`.
+
+        Args:
+            path: directory where the checkpoint will be written to.
+            single_file_per_rank: Produce one file per rank instead of one file per tensor/blob. Default to True.
+            sync_files : force files to be synced to permanent storage. Default to True.
+            thread_count: Number of IO threads to use to write. Default to 1.
+            per_thread_copy_ahead: How many bytes to copy from the GPU ahead of saving then. Default 10Mb.
+            cache_staged_state_dict: Whether to cache the staged state_dict. This option decreases staging latency
+                at the cost of increases memory usage. Additionally, if this parameter is set to True, it's the expectation
+                that the stager is maintained and re-used for multiple dcp.async_save calls. Default to False.
+            overwrite: Whether to allow overwriting existing checkpoints. Defaults to True.
+
+        N. B. If sync_files is disabled, there's no guarantee that the checkpoint will be consistent in the case of a failure.
+        """
+        super().__init__(
+            path=path,
+            single_file_per_rank=single_file_per_rank,
+            sync_files=sync_files,
+            thread_count=thread_count,
+            per_thread_copy_ahead=per_thread_copy_ahead,
+            cache_staged_state_dict=cache_staged_state_dict,
+            overwrite=overwrite,
+        )
+
+    def stage(self, state_dict: STATE_DICT_TYPE) -> STATE_DICT_TYPE:
+        """Override of AsyncStager.stage"""
+        # in the async case, the state dict is already on CPU, so maintaining this
+        # buffer makes no sense
+        self.per_thread_copy_ahead = 0
+        return super().stage(state_dict)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/format_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/format_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec97504e79b58f10771654eff0c04d7f9690cd46
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/format_utils.py
@@ -0,0 +1,280 @@
+# mypy: allow-untyped-defs
+import argparse
+import os
+from enum import Enum
+from typing import cast, Dict, List, Optional, Union
+
+import torch
+import torch.distributed as dist
+from torch.distributed._shard._utils import narrow_tensor_by_index
+from torch.distributed.checkpoint import FileSystemReader, FileSystemWriter
+from torch.distributed.checkpoint._nested_dict import flatten_state_dict
+from torch.distributed.checkpoint.default_planner import (
+    _EmptyStateDictLoadPlanner,
+    DefaultLoadPlanner,
+)
+from torch.distributed.checkpoint.metadata import (
+    Metadata,
+    STATE_DICT_TYPE,
+    STORAGE_TYPES,
+    TensorProperties,
+    TensorStorageMetadata,
+)
+from torch.distributed.checkpoint.planner import LoadItemType, LoadPlan, LoadPlanner
+from torch.distributed.checkpoint.planner_helpers import _create_chunk_list
+from torch.distributed.checkpoint.state_dict_loader import _load_state_dict
+from torch.distributed.checkpoint.state_dict_saver import _save_state_dict
+from torch.distributed.checkpoint.storage import StorageReader
+from torch.futures import Future
+
+
+__all__ = [
+    "dcp_to_torch_save",
+    "torch_save_to_dcp",
+    "BroadcastingTorchSaveReader",
+    "DynamicMetaLoadPlanner",
+]
+
+
+class BroadcastingTorchSaveReader(StorageReader):
+    """
+    StorageReader for reading a Torch Save file. This reader will read the entire checkpoint
+    on the coordinator rank, and then broadcast and shard each tensor to all ranks.
+
+    . N.B. Intended to be used with DynamicMetaLoadPlanner
+
+    .. warning::
+        Current implementation only supports loading Tensors.
+
+    >>> # xdoctest: +SKIP("undefined vars")
+    >>> sd = {"mode": model}
+    >>> dcp.load(
+    >>>    sd,
+    >>>    storage_reader=BroadcastingTorchSaveReader(),
+    >>>    planner=DynamicMetaLoadPlanner(),
+    >>>    checkpoint_id="path_to_model.pt"
+    >>> )
+    """
+
+    def __init__(
+        self,
+        checkpoint_id: Optional[Union[str, os.PathLike]] = None,
+        coordinator_rank: int = 0,
+    ) -> None:
+        self.checkpoint_id = checkpoint_id
+        self.coordinator_rank = coordinator_rank
+
+    def read_metadata(self) -> Metadata:
+        """Extends the default StorageReader to support building the metadata file"""
+        # Metadata is built in planner.set_up_planner, since we are not actually reading metadata from
+        # the disk
+        return Metadata(state_dict_metadata={})
+
+    def read_data(self, plan: LoadPlan, planner: LoadPlanner) -> Future[None]:
+        """
+        Reads torch save data on the coordinator rank, and broadcast afterwards
+        this incurrs a communication cost, but avoids having to load
+        the entire checkpoint on each rank, hopefully preventing OOM issues
+        """
+        planner = cast(DefaultLoadPlanner, planner)
+
+        # data is read in on the coordinator rank, and broadcast afterwards
+        # this incurrs a communication cost, but it avoids having to load
+        # the entire checkpoint on each rank, hopefully preventing OOM issues
+        # TODO: read on each host, instead of only the coordinator
+        if self.is_coordinator:
+            assert self.checkpoint_id is not None
+            torch_state_dict = torch.load(
+                self.checkpoint_id, map_location="cpu", weights_only=False
+            )
+            if planner.flatten_state_dict:
+                torch_state_dict, _ = flatten_state_dict(torch_state_dict)
+        else:
+            torch_state_dict = None
+
+        for req in plan.items:
+            if req.type == LoadItemType.BYTE_IO:
+                raise RuntimeError(
+                    f"Non-tensor value identified at {req.storage_index.fqn}. "
+                    f"At this time {type(self).__name__} only supports loading Tensors."
+                )
+
+            #  Broadcast the tensor from the coordinator rank
+            if self.is_coordinator:
+                pg_device = dist.distributed_c10d._get_pg_default_device()
+                tensor = torch_state_dict[req.storage_index.fqn].to(pg_device)
+            else:
+                tensor = torch.empty_like(planner.state_dict[req.storage_index.fqn])
+
+            dist.broadcast(tensor, src=self.coordinator_rank, async_op=False)
+
+            tensor = narrow_tensor_by_index(tensor, req.storage_offsets, req.lengths)
+            target_tensor = planner.resolve_tensor(req).detach()
+            assert target_tensor.size() == tensor.size(), (
+                f"req {req.storage_index} mismatch sizes, "
+                f"{target_tensor.size()} vs {tensor.size()}"
+            )
+            target_tensor.copy_(tensor)
+            planner.commit_tensor(req, target_tensor)
+
+        fut: Future = Future()
+        fut.set_result(None)
+        return fut
+
+    def set_up_storage_reader(self, metadata: Metadata, is_coordinator: bool) -> None:
+        """Implementation of the StorageReader method"""
+        self.is_coordinator = is_coordinator
+        if self.is_coordinator:
+            assert dist.get_rank() == self.coordinator_rank
+
+        assert self.checkpoint_id is not None
+
+    def prepare_local_plan(self, plan: LoadPlan) -> LoadPlan:
+        """Implementation of the StorageReader method"""
+        return plan
+
+    def prepare_global_plan(self, global_plan: List[LoadPlan]) -> List[LoadPlan]:
+        """Implementation of the StorageReader method"""
+        return global_plan
+
+    def reset(self, checkpoint_id: Union[str, os.PathLike, None] = None) -> None:
+        """Implementation of the StorageReader method"""
+        self.checkpoint_id = checkpoint_id
+
+    @classmethod
+    def validate_checkpoint_id(cls, checkpoint_id: Union[str, os.PathLike]) -> bool:
+        """Implementation of the StorageReader method"""
+        return os.path.isfile(checkpoint_id)
+
+
+class DynamicMetaLoadPlanner(DefaultLoadPlanner):
+    """
+    Extension of DefaultLoadPlanner, which creates a new Metadata object based on the passed in state dict,
+    avoiding the need to read metadata from disk. This is useful when reading formats which don't have a
+    metadata file, like Torch Save files.
+
+    . N.B. Intended to be used with BroadcastingTorchSaveReader
+
+    .. warning::
+        Current implementation only supports loading Tensors.
+
+    >>> # xdoctest: +SKIP("undefined vars")
+    >>> sd = {"mode": model}
+    >>> dcp.load(
+    >>>    sd,
+    >>>    storage_reader=BroadcastingTorchSaveReader(),
+    >>>    planner=DynamicMetaLoadPlanner(),
+    >>>    checkpoint_id="path_to_model.pt"
+    >>> )
+    """
+
+    def set_up_planner(
+        self,
+        state_dict: STATE_DICT_TYPE,
+        metadata: Optional[Metadata] = None,
+        is_coordinator: bool = False,
+    ) -> None:
+        """Setups of the planner, extnding default behavior by creating the Metadata object from the state dict"""
+        super().set_up_planner(state_dict, metadata, is_coordinator)
+
+        state_dict_metadata: Dict[str, STORAGE_TYPES] = {}
+        for key, tensor in self.state_dict.items():
+            if not torch.is_tensor(tensor):
+                raise RuntimeError(
+                    f"Non-tensor value identified at {key}. "
+                    f"At this time {type(self).__name__} only supports loading Tensors."
+                )
+
+            state_dict_metadata[key] = TensorStorageMetadata(
+                TensorProperties(dtype=tensor.dtype),
+                tensor.size(),
+                _create_chunk_list(tensor),
+            )
+        self.metadata = Metadata(state_dict_metadata=state_dict_metadata)
+
+
+def dcp_to_torch_save(
+    dcp_checkpoint_dir: Union[str, os.PathLike],
+    torch_save_path: Union[str, os.PathLike],
+):
+    """
+    Given a directory containing a DCP checkpoint, this function will convert it into a
+    Torch save file.
+
+    Args:
+        dcp_checkpoint_dir: Directory containing the DCP checkpoint.
+        torch_save_path: Filename to store the converted Torch save file.
+
+    .. warning::
+        To avoid OOM, it's recommended to only run this function on a single rank.
+    """
+    sd: STATE_DICT_TYPE = {}
+    _load_state_dict(
+        sd,
+        storage_reader=FileSystemReader(dcp_checkpoint_dir),
+        planner=_EmptyStateDictLoadPlanner(),
+        no_dist=True,
+    )
+    torch.save(sd, torch_save_path)
+
+
+def torch_save_to_dcp(
+    torch_save_path: Union[str, os.PathLike],
+    dcp_checkpoint_dir: Union[str, os.PathLike],
+):
+    """
+    Given the location of a torch save file, converts it into a DCP checkpoint.
+
+    Args:
+        torch_save_path: Filename of the Torch save file.
+        dcp_checkpoint_dir: Directory to store the DCP checkpoint.
+
+    .. warning::
+        To avoid OOM, it's recommended to only run this function on a single rank.
+    """
+
+    state_dict = torch.load(torch_save_path, weights_only=False)
+    # we don't need stateful behavior here because the expectation is anything loaded by
+    # torch.load would not contain stateful objects.
+    _save_state_dict(
+        state_dict, storage_writer=FileSystemWriter(dcp_checkpoint_dir), no_dist=True
+    )
+
+
+if __name__ == "__main__":
+
+    class FormatMode(Enum):
+        TORCH_TO_DCP = "torch_to_dcp"
+        DCP_TO_TORCH = "dcp_to_torch"
+
+    # Parse command-line arguments
+    parser = argparse.ArgumentParser()
+    parser.add_argument(
+        "mode",
+        type=str,
+        help="Conversion mode",
+        choices=[m.value for m in FormatMode],
+        default=FormatMode.TORCH_TO_DCP,
+    )
+    parser.add_argument("src", type=str, help="Path to the source model")
+    parser.add_argument("dst", type=str, help="Path to the destination model")
+    args = parser.parse_args()
+
+    print(
+        f"Converting checkpoint from {args.src} to {args.dst} using method: '{args.mode}'"
+    )
+    checkpoint_missing_warning = (
+        f"No checkpoint found at {args.src}. Skipping conversion."
+    )
+    if args.mode == FormatMode.TORCH_TO_DCP.value:
+        if os.path.isfile(args.src):
+            torch_save_to_dcp(args.src, args.dst)
+        else:
+            print(checkpoint_missing_warning)
+    elif args.mode == FormatMode.DCP_TO_TORCH.value:
+        if os.path.isdir(args.src):
+            dcp_to_torch_save(args.src, args.dst)
+        else:
+            print(checkpoint_missing_warning)
+    else:
+        raise ValueError(f"Unknown conversion mode: {args.mode}")
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/logger.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/logger.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee7ae4d9a5b94983c3bceb3bbdc64f897419ebb6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/logger.py
@@ -0,0 +1,103 @@
+# mypy: allow-untyped-defs
+import functools
+import time
+from typing import Any, Callable, Dict, List, TypeVar
+from typing_extensions import ParamSpec
+from uuid import uuid4
+
+import torch.distributed.c10d_logger as c10d_logger
+from torch.distributed.checkpoint.logging_handlers import DCP_LOGGER_NAME
+
+
+__all__: List[str] = []
+
+global _dcp_logger
+_dcp_logger = c10d_logger._get_or_create_logger(DCP_LOGGER_NAME)
+
+_T = TypeVar("_T")
+_P = ParamSpec("_P")
+
+
+def _msg_dict_from_dcp_method_args(*args, **kwargs) -> Dict[str, Any]:
+    """
+    Extracts log data from dcp method args
+    """
+    msg_dict = {}
+
+    # checkpoint ID can be passed in through the serializer or through the checkpoint id directly
+    storage_writer = kwargs.get("storage_writer", None)
+    storage_reader = kwargs.get("storage_reader", None)
+    planner = kwargs.get("planner", None)
+
+    checkpoint_id = kwargs.get("checkpoint_id", None)
+    if not checkpoint_id and (serializer := storage_writer or storage_reader):
+        checkpoint_id = getattr(serializer, "checkpoint_id", None)
+
+    msg_dict["checkpoint_id"] = (
+        str(checkpoint_id) if checkpoint_id is not None else checkpoint_id
+    )
+
+    # Uniquely identify a _dcp_method_logger wrapped function call.
+    msg_dict["uuid"] = str(uuid4().int)
+
+    if storage_writer:
+        msg_dict["storage_writer"] = storage_writer.__class__.__name__
+
+    if storage_reader:
+        msg_dict["storage_reader"] = storage_reader.__class__.__name__
+
+    if planner:
+        msg_dict["planner"] = planner.__class__.__name__
+
+    return msg_dict
+
+
+def _get_msg_dict(func_name, *args, **kwargs) -> Dict[str, Any]:
+    msg_dict = _msg_dict_from_dcp_method_args(*args, **kwargs)
+    msg_dict.update(c10d_logger._get_msg_dict(func_name, **msg_dict))
+
+    return msg_dict
+
+
+def _dcp_method_logger(
+    log_exceptions: bool = False, **wrapper_kwargs: Any
+) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]:  # pyre-ignore
+    """This method decorator logs the start, end, and exception of wrapped events."""
+
+    def decorator(func: Callable[_P, _T]):
+        @functools.wraps(func)
+        def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _T:
+            msg_dict = _get_msg_dict(
+                func.__name__, *args, **{**wrapper_kwargs, **kwargs}
+            )
+
+            # log start event
+            msg_dict["event"] = "start"
+            t0 = time.time_ns()
+            msg_dict["time"] = t0
+            msg_dict["log_exceptions"] = log_exceptions
+            _dcp_logger.debug(msg_dict)
+
+            # exceptions
+            try:
+                result = func(*args, **kwargs)
+            except BaseException as error:
+                if log_exceptions:
+                    msg_dict["event"] = "exception"
+                    msg_dict["error"] = f"{error}"
+                    msg_dict["time"] = time.time_ns()
+                    _dcp_logger.error(msg_dict)
+                raise
+
+            # end event
+            msg_dict["event"] = "end"
+            t1 = time.time_ns()
+            msg_dict["time"] = time.time_ns()
+            msg_dict["times_spent"] = t1 - t0
+            _dcp_logger.debug(msg_dict)
+
+            return result
+
+        return wrapper
+
+    return decorator
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/logging_handlers.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/logging_handlers.py
new file mode 100644
index 0000000000000000000000000000000000000000..119dd52b7679750180c6ce1a1b0182762bc3f9e3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/logging_handlers.py
@@ -0,0 +1,15 @@
+import logging
+from typing import List
+
+from torch.distributed.logging_handlers import _log_handlers
+
+
+__all__: List[str] = []
+
+DCP_LOGGER_NAME = "dcp_logger"
+
+_log_handlers.update(
+    {
+        DCP_LOGGER_NAME: logging.NullHandler(),
+    }
+)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/metadata.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/metadata.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1f87e2d9cba8a1b5e8c78f795eb7a6a2c10d2c6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/metadata.py
@@ -0,0 +1,182 @@
+# mypy: allow-untyped-defs
+import os
+from dataclasses import dataclass, field
+from enum import Enum
+from typing import Any, Dict, List, Optional, Sequence, Union
+
+import torch
+from torch.distributed.checkpoint.stateful import StatefulT
+
+
+__all__ = [
+    "ChunkStorageMetadata",
+    "TensorStorageMetadata",
+    "BytesStorageMetadata",
+    "Metadata",
+    "MetadataIndex",
+    "TensorProperties",
+    "StorageMeta",
+]
+
+
+@dataclass
+class ChunkStorageMetadata:
+    """
+    Each chunk is expected to have the same properties of the TensorStorageMetadata
+    that includes it.
+    """
+
+    offsets: torch.Size
+    sizes: torch.Size
+
+
+class _MEM_FORMAT_ENCODING(Enum):
+    """Describe the memory format of a tensor."""
+
+    TORCH_CONTIGUOUS_FORMAT = 0
+    TORCH_CHANNELS_LAST = 1
+    TORCH_PRESERVE_FORMAT = 2
+
+
+@dataclass
+class TensorProperties:
+    """Properties used to create :class:`Tensor`"""
+
+    # Regular tensor fields
+    dtype: torch.dtype = field(default_factory=torch.get_default_dtype)
+    # This field is deprecated.
+    layout: torch.layout = field(default=torch.strided)
+    # This field is deprecated.
+    requires_grad: bool = False
+    # This field is deprecated.
+    memory_format: torch.memory_format = field(default=torch.contiguous_format)
+    # This field is deprecated.
+    pin_memory: bool = False
+
+    def __getstate__(self):
+        # Since torch.memory_format cannot be pickled!
+        memory_format = self.memory_format
+        if memory_format == torch.contiguous_format:
+            mem_format_encoding = _MEM_FORMAT_ENCODING.TORCH_CONTIGUOUS_FORMAT
+        elif memory_format == torch.channels_last:
+            mem_format_encoding = _MEM_FORMAT_ENCODING.TORCH_CHANNELS_LAST
+        elif memory_format == torch.preserve_format:
+            mem_format_encoding = _MEM_FORMAT_ENCODING.TORCH_PRESERVE_FORMAT
+        else:
+            raise RuntimeError(f"Invalid torch.memory_format: {memory_format}")
+
+        return (
+            self.dtype,
+            self.layout,
+            self.requires_grad,
+            mem_format_encoding,
+            self.pin_memory,
+        )
+
+    def __setstate__(
+        self,
+        state,
+    ):
+        (
+            self.dtype,
+            self.layout,
+            self.requires_grad,
+            mem_format_encoding,
+            self.pin_memory,
+        ) = state
+
+        if mem_format_encoding == _MEM_FORMAT_ENCODING.TORCH_CONTIGUOUS_FORMAT:
+            memory_format = torch.contiguous_format
+        elif mem_format_encoding == _MEM_FORMAT_ENCODING.TORCH_CHANNELS_LAST:
+            memory_format = torch.channels_last
+        elif mem_format_encoding == _MEM_FORMAT_ENCODING.TORCH_PRESERVE_FORMAT:
+            memory_format = torch.preserve_format
+        else:
+            raise RuntimeError(
+                f"Invalid torch.memory_format encoding: {mem_format_encoding}"
+            )
+
+        self.memory_format = memory_format
+
+    @staticmethod
+    def create_from_tensor(tensor: torch.Tensor) -> "TensorProperties":
+        return TensorProperties(
+            dtype=tensor.dtype,
+            layout=tensor.layout,
+            requires_grad=tensor.requires_grad,
+            memory_format=torch.contiguous_format,
+            pin_memory=tensor.is_pinned(),
+        )
+
+
+@dataclass
+class TensorStorageMetadata:
+    properties: TensorProperties
+    size: torch.Size
+    chunks: List[ChunkStorageMetadata]
+
+
+@dataclass
+class BytesStorageMetadata:
+    pass
+
+
+STORAGE_TYPES = Union[TensorStorageMetadata, BytesStorageMetadata]
+STATE_DICT_TYPE = Dict[str, Union[StatefulT, Any]]
+
+
+@dataclass
+class StorageMeta:
+    checkpoint_id: Union[str, os.PathLike, None] = None
+    save_id: Optional[str] = None
+    load_id: Optional[str] = None
+
+
+@dataclass
+class Metadata:
+    """This class represents the metadata of the checkpoint."""
+
+    # Keys are the same from the `state_dict` used.
+    state_dict_metadata: Dict[str, STORAGE_TYPES]
+    # It is the responsibility of the planner and storage plugins to ensure
+    # backward compatibility of the planner_data and storage_data. DCP will
+    # also ensure the backward compatibility of the metadata in this file and
+    # the metadata of the built-in planner and storage plugins.
+    planner_data: Any = None
+    storage_data: Any = None
+    storage_meta: Optional[StorageMeta] = None
+
+
+@dataclass(frozen=True)
+class MetadataIndex:
+    """This class represents a lookup key for items in a state dict or Metadata."""
+
+    fqn: str
+    """Fully Qualified Name of the object"""
+
+    offset: Optional[torch.Size] = None
+    """If the object is a tensor, offset into the tensor we're looking for"""
+
+    index: Optional[int] = field(hash=False, compare=False, default=None)
+    """
+    Index hint when searching for tensor chunk to speedup lookups (optional)
+
+    A common representation of a sharded tensor is as a list of chunks so to
+    find the index in such a list you need to linear search it.
+
+    When constructing an instance of MetadataIndex that points to that list,
+    one can provide the index as a hint and it will be probed first before
+    the linear search and thus making it significantly faster.
+    """
+
+    def __init__(
+        self,
+        fqn: str,
+        offset: Optional[Sequence[int]] = None,
+        index: Optional[int] = None,
+    ):
+        # We must use object.__setattr__ due to frozen=True
+        object.__setattr__(self, "fqn", fqn)
+        object.__setattr__(self, "index", index)
+        if offset is not None:
+            object.__setattr__(self, "offset", torch.Size(offset))
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/optimizer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/optimizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ad170768db9294e63e09b2c99da8f0d6b93241d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/optimizer.py
@@ -0,0 +1,356 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates
+
+import dataclasses
+from typing import cast, Dict, List, Optional, Sequence, Tuple, Union
+
+import torch
+import torch.distributed as dist
+from torch._utils import _get_device_module
+from torch.distributed._shard.sharded_tensor.api import ShardedTensor
+from torch.distributed._shard.sharded_tensor.metadata import (
+    TensorProperties as ShardTensorProperties,
+)
+from torch.distributed._shard.sharded_tensor.shard import Shard
+from torch.distributed._shard.sharding_spec.chunk_sharding_spec import ChunkShardingSpec
+from torch.distributed.checkpoint._nested_dict import unflatten_state_dict
+from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner
+from torch.distributed.checkpoint.metadata import (
+    BytesStorageMetadata,
+    ChunkStorageMetadata,
+    Metadata,
+    MetadataIndex,
+    STATE_DICT_TYPE,
+    TensorProperties,
+    TensorStorageMetadata,
+)
+from torch.distributed.checkpoint.planner import LoadPlan, LoadPlanner
+from torch.distributed.checkpoint.planner_helpers import (
+    _create_read_items,
+    create_read_items_for_chunk_list,
+)
+from torch.distributed.checkpoint.state_dict_loader import load_state_dict
+from torch.distributed.checkpoint.storage import StorageReader
+from torch.distributed.checkpoint.utils import (
+    _element_wise_add,
+    _element_wise_sub,
+    _normalize_device_info,
+)
+from torch.distributed.distributed_c10d import _get_default_group
+from torch.distributed.fsdp._shard_utils import _create_chunk_sharded_tensor
+from torch.distributed.remote_device import _remote_device
+from torch.distributed.tensor import DTensor
+
+
+STATE_DICT_2D_LAYOUT = Dict[str, Tuple[Optional[Sequence[int]], Sequence[int]]]
+
+
+# TODO: Update docstrings for optimizer.py
+__all__ = [
+    "load_sharded_optimizer_state_dict",
+]
+
+
+def _gen_rank_device(global_rank: int, device_type: str = "cuda") -> str:
+    if device_type == "cpu":
+        return "cpu"
+    device_module = _get_device_module(device_type)
+    if device_module.is_available():
+        return _normalize_device_info(
+            device_type, global_rank % device_module.device_count()
+        )
+    return "cpu"
+
+
+def _create_colwise_spec(
+    pg: Optional[dist.ProcessGroup] = None,
+) -> ChunkShardingSpec:
+    pg_device_type = dist.distributed_c10d._get_pg_default_device(pg).type
+    if pg is None:
+        placements = [
+            f"rank:{idx}/{_gen_rank_device(idx, pg_device_type)}"
+            for idx in range(dist.get_world_size())
+        ]
+    else:
+        placements = [
+            f"rank:{idx}/{_gen_rank_device(dist.get_global_rank(pg, idx), pg_device_type)}"
+            for idx in range(pg.size())
+        ]
+    return ChunkShardingSpec(
+        dim=0,
+        placements=cast(List[Union[_remote_device, str]], placements),
+    )
+
+
+def _is_nested_tensor(val: torch.Tensor) -> bool:
+    if type(val) is ShardedTensor:
+        if len(val.local_shards()) == 0:
+            return False
+        if type(val.local_shards()[0].tensor) is ShardedTensor:
+            return True
+        if type(val.local_shards()[0].tensor) is DTensor:
+            raise ValueError("Cannot handle DTensor nested insided ShardedTensor")
+    elif type(val) is DTensor and (
+        type(val._local_tensor) is DTensor or type(val._local_tensor) is ShardedTensor
+    ):
+        raise ValueError("Cannot handle nested DTensor")
+    return False
+
+
+def _alloc_tensor(
+    props: TensorProperties, size: Sequence[int], device_type: str = "cuda"
+) -> torch.Tensor:
+    if device_type == "cpu":
+        device = cast(torch.device, _get_device_module(device_type).current_device())
+    else:
+        device = torch.device(
+            device_type, _get_device_module(device_type).current_device()
+        )
+
+    return torch.empty(
+        size=size,
+        dtype=props.dtype,
+        layout=props.layout,
+        requires_grad=props.requires_grad,
+        pin_memory=props.pin_memory,
+        device=device,
+    )
+
+
+def _get_state_dict_2d_layout(
+    state_dict: STATE_DICT_TYPE,
+) -> Tuple[STATE_DICT_2D_LAYOUT, Optional[dist.ProcessGroup]]:
+    """
+    Load the right TP slice of the optimizer state.
+
+    This is not easy since the per-tensor slicing can't be inferred from checkpoint metadata.
+    We take advantage of the model state_dict producing a sliced ST to figure out what we need to load.
+    This is pretty fragile and it might be easier for FSDP to compute this info for us.
+    Returns a dictionary where keys are the same of the state_dict and the value is a tuple of
+    (offset, size) for the current rank TP slice.
+    N.B. The state_dict *MUST* come from FSDP.sharded_state_dict.
+    """
+    specs: STATE_DICT_2D_LAYOUT = {}
+    dp_pg: Optional[dist.ProcessGroup] = None
+    for key, value in state_dict.items():
+        specs[key] = (None, value.size())
+        if _is_nested_tensor(value):
+            assert (
+                len(value.local_shards()) == 1
+            ), "Cannot handle ST with multiple shards"
+            assert isinstance(
+                value, ShardedTensor
+            ), "Can only handle nested ShardedTensor"
+            shard = value.local_shards()[0]
+            specs[key] = (
+                shard.metadata.shard_offsets,
+                shard.metadata.shard_sizes,
+            )
+            dp_pg = shard.tensor._process_group  # type: ignore[attr-defined]
+
+    return (
+        specs,
+        dp_pg,
+    )
+
+
+class _ReaderWithOffset(DefaultLoadPlanner):
+    translation: Dict[MetadataIndex, MetadataIndex]
+    state_dict: STATE_DICT_TYPE
+    metadata: Metadata
+
+    def __init__(self, fqn_to_offset: Dict[str, Sequence[int]]) -> None:
+        super().__init__()
+        self.fqn_to_offset = fqn_to_offset
+        self.metadata = Metadata({})
+        self.state_dict = {}
+        self.translation = {}
+
+    def create_local_plan(self) -> LoadPlan:
+        requests = []
+        self.translation = {}
+        for fqn, obj in self.state_dict.items():
+            md = self.metadata.state_dict_metadata[fqn]
+            if not isinstance(obj, ShardedTensor):
+                requests += _create_read_items(fqn, md, obj)
+                continue
+
+            if fqn not in self.fqn_to_offset:
+                requests += _create_read_items(fqn, md, obj)
+                continue
+
+            offset = self.fqn_to_offset[fqn]
+
+            assert len(obj.local_shards()) == 1
+            original_shard = obj.local_shards()[0]
+            local_chunks = [
+                ChunkStorageMetadata(
+                    offsets=torch.Size(
+                        _element_wise_add(original_shard.metadata.shard_offsets, offset)
+                    ),
+                    sizes=torch.Size(original_shard.metadata.shard_sizes),
+                )
+            ]
+
+            reqs = create_read_items_for_chunk_list(
+                fqn, cast(TensorStorageMetadata, md), local_chunks
+            )
+            # TODO: The ReadItems will have a displaced MetadataIndex, fix it.
+            # TODO: we should change _create_sharded_read_items to have more ergonomic API
+            for ri in reqs:
+                assert ri.dest_index.offset is not None
+                original_offset = _element_wise_sub(ri.dest_index.offset, offset)
+                original_index = dataclasses.replace(
+                    ri.dest_index, offset=torch.Size(original_offset)
+                )
+                self.translation[ri.dest_index] = original_index
+
+            requests += reqs
+        return LoadPlan(requests)
+
+    def lookup_tensor(self, index: MetadataIndex) -> torch.Tensor:
+        return super().lookup_tensor(self.translation.get(index, index))
+
+
+def load_sharded_optimizer_state_dict(
+    model_state_dict: STATE_DICT_TYPE,
+    optimizer_key: str,
+    storage_reader: StorageReader,
+    planner: Optional[LoadPlanner] = None,
+) -> STATE_DICT_TYPE:
+    """
+    Load a state_dict in conjunction with FSDP sharded optimizer state.
+
+    This is the current recommended way to checkpoint FSDP.
+    >>> # xdoctest: +SKIP
+    >>> import torch.distributed.checkpoint as dist_cp
+    >>> # Save
+    >>> model: torch.nn.Model
+    >>> optim_params = model.parameters()
+    >>> optim = torch.optim.SGD(optim_params, lr=0.01)
+    >>> # Save
+    >>> with FSDP.state_dict_type(model, StateDictType.SHARDED_STATE_DICT):
+    >>>     state_dict = {
+    >>>         "optimizer": FSDP.optim_state_dict(model, optim),
+    >>>         "model": model.state_dict()
+    >>>     }
+    >>>     dist_cp.save_state_dict(
+    >>>         state_dict=optim_state,
+    >>>         storage_writer=dist_cp.FileSystemWriter("checkpoint"),
+    >>>         planner=dist_cp.DefaultSavePlanner(),
+    >>>     )
+    >>>
+    >>> # Load
+    >>> with FSDP.state_dict_type(model_tp, StateDictType.SHARDED_STATE_DICT):
+    >>>     model_state_dict = model_tp.state_dict()
+    >>>     checkpoint = {
+    >>>         "model": model_state_dict
+    >>>     }
+    >>>     dist_cp.load_state_dict(
+    >>>         state_dict=checkpoint,
+    >>>         storage_reader=dist_cp.FileSystemReader(checkpoint_file),
+    >>>         planner=dist_cp.DefaultLoadPlanner(),
+    >>>     )
+    >>>     model.load_state_dict(checkpoint["model_state"])
+    >>>
+    >>>     optim_state = dist_cp.load_sharded_optimizer_state_dict(
+    >>>         model_state_dict,
+    >>>         optimizer_key="optimizer",
+    >>>         storage_reader=dist_cp.FileSystemReader("checkpoint"),
+    >>>     )
+    >>>
+    >>>     flattened_osd = FSDP.optim_state_dict_to_load(
+    >>>        model, optim, optim_state["optimizer"]
+    >>>     )
+    >>>
+    >>>     optim.load_state_dict(flattened_osd)
+    """
+    metadata = storage_reader.read_metadata()
+
+    layout_specs, dp_pg = _get_state_dict_2d_layout(model_state_dict)
+    dp_pg_device_type = dist.distributed_c10d._get_pg_default_device(dp_pg).type
+    device_module = _get_device_module(dp_pg_device_type)
+
+    if dp_pg is None:
+        placements = []
+        for i in range(dist.get_world_size()):
+            device_info = _normalize_device_info(
+                dp_pg_device_type, i % device_module.device_count()
+            )
+            placements.append(f"rank:{i}/{device_info}")
+        sharding_spec = ChunkShardingSpec(dim=0, placements=placements)  # type: ignore[arg-type]
+    else:
+        sharding_spec = _create_colwise_spec(dp_pg)
+
+    # Create a state_dict for optimizer state
+    state_dict: STATE_DICT_TYPE = {}
+
+    fqn_to_offset: Dict[str, Sequence[int]] = {}
+    for key, value in metadata.state_dict_metadata.items():
+        key_path = metadata.planner_data[key]
+        if key_path[0] != optimizer_key:
+            continue
+
+        if isinstance(value, BytesStorageMetadata):
+            state_dict[key] = ""
+            continue
+
+        # value: TensorStorageMetadata
+        if value.size.numel() == 1:
+            state_dict[key] = _alloc_tensor(
+                value.properties, value.size, dp_pg_device_type
+            )
+        elif dp_pg is None:
+            state_dict[key] = _create_chunk_sharded_tensor(
+                _alloc_tensor(value.properties, value.size, dp_pg_device_type),
+                rank=dist.get_rank(),
+                world_size=dist.get_world_size(),
+                num_devices_per_node=device_module.device_count(),
+                pg=_get_default_group(),
+            )
+        else:
+            spec_key = key_path[2]
+            alloc_size = layout_specs.get(spec_key, (None, value.size))[1]
+
+            properties = ShardTensorProperties(
+                dtype=value.properties.dtype,
+                layout=value.properties.layout,
+                requires_grad=value.properties.requires_grad,
+                memory_format=value.properties.memory_format,
+                pin_memory=value.properties.pin_memory,
+            )
+
+            st_md = sharding_spec.build_metadata(torch.Size(alloc_size), properties)
+            local_shards = []
+            current_rank = dist.get_rank(dp_pg)
+            for shard_md in st_md.shards_metadata:
+                if cast(_remote_device, shard_md.placement).rank() != current_rank:
+                    continue
+                local_shards.append(
+                    Shard(
+                        tensor=_alloc_tensor(
+                            value.properties, shard_md.shard_sizes, dp_pg_device_type
+                        ),
+                        metadata=shard_md,
+                    )
+                )
+
+            st = ShardedTensor._init_from_local_shards_and_global_metadata(
+                local_shards, st_md, process_group=dp_pg
+            )
+
+            if spec_key in layout_specs and layout_specs[spec_key][0] is not None:
+                fqn_to_offset[key] = cast(Sequence[int], layout_specs[spec_key][0])
+
+            state_dict[key] = st
+
+    # Whether we unflatten before or after doesn't matter
+    load_state_dict(
+        state_dict=state_dict,
+        storage_reader=storage_reader,
+        # FIXME the type of planner is wrong in load_state_dict
+        planner=_ReaderWithOffset(fqn_to_offset) if dp_pg is not None else planner,
+    )
+
+    state_dict = unflatten_state_dict(state_dict, metadata.planner_data)
+
+    return state_dict
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/planner.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/planner.py
new file mode 100644
index 0000000000000000000000000000000000000000..75619b627356ad3c0c63fa7cedae4733d9771491
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/planner.py
@@ -0,0 +1,417 @@
+import abc
+import io
+import operator
+from dataclasses import dataclass
+from enum import auto, Enum
+from functools import reduce
+from typing import Any, List, Optional, Tuple, Union
+
+import torch
+from torch.distributed.checkpoint.metadata import (
+    ChunkStorageMetadata,
+    Metadata,
+    MetadataIndex,
+    STATE_DICT_TYPE,
+    StorageMeta,
+    TensorProperties,
+)
+
+
+__all__ = [
+    "WriteItemType",
+    "LoadItemType",
+    "TensorWriteData",
+    "WriteItem",
+    "ReadItem",
+    "SavePlan",
+    "LoadPlan",
+    "SavePlanner",
+    "LoadPlanner",
+]
+
+
+class WriteItemType(Enum):
+    TENSOR = auto()
+    SHARD = auto()
+    BYTE_IO = auto()
+
+
+class LoadItemType(Enum):
+    TENSOR = auto()
+    BYTE_IO = auto()
+
+
+@dataclass(frozen=True)
+class TensorWriteData:
+    chunk: ChunkStorageMetadata
+    properties: TensorProperties
+    size: torch.Size
+
+
+@dataclass(frozen=True)
+class WriteItem:
+    """Dataclass which holds information about what needs to be written to storage."""
+
+    index: MetadataIndex
+    type: WriteItemType
+
+    # Value present if it's a tensor write
+    tensor_data: Optional[TensorWriteData] = None
+
+    def tensor_storage_size(self) -> Optional[int]:
+        """
+        Calculates the storage size of the underlying tensor, or None if this is not a tensor write.
+
+        Returns:
+            Optional[int] storage size, in bytes of underlying tensor if any.
+        """
+        if self.tensor_data is None:
+            return None
+
+        numels = reduce(operator.mul, self.tensor_data.size, 1)
+        dtype_size = torch._utils._element_size(self.tensor_data.properties.dtype)
+        return numels * dtype_size
+
+
+@dataclass(frozen=True)
+class ReadItem:
+    # Read Item
+    type: LoadItemType
+
+    # Index into the state_dict
+    dest_index: MetadataIndex
+    # Offsets into destination tensor
+    dest_offsets: torch.Size
+
+    # Index into the checkpoint
+    storage_index: MetadataIndex
+    # Offset into the checkpoint data
+    storage_offsets: torch.Size
+
+    # Size of the hypercube to copy
+    lengths: torch.Size
+
+
+@dataclass(frozen=True)
+class SavePlan:
+    items: List[WriteItem]
+    storage_data: Any = None
+    planner_data: Any = None
+
+
+@dataclass
+class LoadPlan:
+    items: List[ReadItem]
+    storage_data: Any = None
+    planner_data: Any = None
+
+
+class SavePlanner(abc.ABC):
+    """
+    Abstract class defining the protocol used by save_state_dict to plan the save process.
+
+    SavePlanners are stateful objects that can be used to customize the whole save process.
+
+    SavePlanner acts as an access proxy to the state_dict, so any transformation done to it
+    will be visible to the whole process.
+
+    A planner subclass can expect the following sequence of calls during save_state_dict:
+
+    1) set_up_planner - called on all ranks.
+        Signals the start of a checkpoint save.
+
+    2) create_local_plan - called on all ranks.
+        Process the state_dict and produces a `SavePlan` that will be sent for global planning.
+
+    3) create_global_plan - called on the coordinator rank only.
+        Takes the SavePlan from all ranks and make any global decision.
+
+    4) finish_plan - called on all ranks.
+        This gives each rank a chance to adjust to global planning decisions.
+
+    5) resolve_data - called multiple times on each rank
+        Lookups a value on the `state_dict` for the storage layer to write.
+
+    Users are recommended to extend DefaultSavePlanner instead of this interface directly as
+    most changes can be expressed by changes in a single method.
+
+    There are 3 usual patterns of extension:
+
+    Rewriting state_dict. This is the simplest way to extend the save process as it
+    doesn't requite understanding the intrincacies of how SavePlan works:
+
+    >>> # xdoctest: +SKIP("undefined vars")
+    >>> class RenamePlanner(DefaultSavePlanner):
+    >>>     def set_up_planner(
+    >>>         self,
+    >>>         state_dict: STATE_DICT_TYPE,
+    >>>         storage_meta: Optional[StorageMeta],
+    >>>         is_coordinator: bool,
+    >>>     ) -> None:
+    >>>         # prefix all keys with `foo_``
+    >>>         super().set_up_planner({"foo_" + k: v for k, v in state_dict.items()}, storage_meta, is_coordinator)
+
+    Modifying local plan and lookup in tandem. This is useful when fine control of how data is persisted
+
+    >>> # xdoctest: +SKIP("undefined vars")
+    >>> class FP16Planner(DefaultSavePlanner):
+    >>>     def create_local_plan(self):
+    >>>         plan = super().create_local_plan()
+    >>>         for p in plan:
+    >>>             if p.tensor_data is not None:
+    >>>                 p.tensor_data.properties.dtype = torch.float16
+    >>>         return plan
+    >>>
+    >>>     def resolve_data(self, write_item):
+    >>>         item = super().resolve_data(write_item)
+    >>>         return item if write_item.type == WriteItemType.BYTE_IO else item.to(torch.float16)
+
+    Using the global planning step to make central decisions that can't be made individually by each rank
+
+    >>> # xdoctest: +SKIP("undefined vars")
+    >>> from itertools import zip_longest
+    >>> from dataclasses import replace
+    >>> class DDPLoadBalancingPlanner(DefaultSavePlanner):
+    >>>     # This uses the default local plan behavior of having all non-sharded writes in rank 0
+    >>>     # This sample doesn't handle ShardedTensors
+    >>>     def create_global_plan(self, all_plans):
+    >>>         iters = [iter(all_plans[0].items)] * len(all_plans)
+    >>>         items_per_rank = [
+    >>>             [item for item in items if item is not None]
+    >>>             for items in zip(*zip_longest(*iters), strict=True)
+    >>>         ]
+    >>>         all_plans = [
+    >>>             replace(plan, items=items)
+    >>>             for plan, items in zip(all_plans, items_per_rank, strict=True)
+    >>>         ]
+    >>>         return super().create_global_plan(all_plans)
+
+    Finally, some planners need to save additional metadata in the checkpoint, this is
+    accomplished by having each rank contribute their data items in the local plan and
+    the global planner aggregate them:
+
+    >>> # xdoctest: +SKIP("undefined vars")
+    >>> class SaveExtraDataPlanner(DefaultSavePlanner):
+    >>>     def create_local_plan(self) -> SavePlan:
+    >>>         plan = super().create_local_plan()
+    >>>         return replace(plan, planner_data="per-rank-data")
+    >>>
+    >>>     def create_global_plan(self, all_plans: List[SavePlan]) -> Tuple[List[SavePlan], Metadata]:
+    >>>         global_plan, metadata = super().create_global_plan(all_plans)
+    >>>         merged_data = [p.planner_data for p in global_plan]
+    >>>         metadata = replace(metadata, planner_data=merged_data)
+    >>>         return global_plan, metadata
+    """
+
+    @abc.abstractmethod
+    def set_up_planner(
+        self,
+        state_dict: STATE_DICT_TYPE,
+        storage_meta: Optional[StorageMeta] = None,
+        is_coordinator: bool = False,
+    ) -> None:
+        """
+        Initialize this planner to save ``state_dict``.
+
+        Implementations should save those values as they won't be provided lated in the save process.
+
+        This is called on all ranks.
+        """
+
+    @abc.abstractmethod
+    def create_local_plan(self) -> SavePlan:
+        """
+        Compute the save plan for the current rank.
+
+        This will be aggregated and passed to create_global_plan.
+        Planner specific data can be passed through SavePlan::planner_data.
+
+        This is called on all ranks.
+        """
+
+    @abc.abstractmethod
+    def create_global_plan(
+        self, all_plans: List[SavePlan]
+    ) -> Tuple[List[SavePlan], Metadata]:
+        """
+        Compute the global checkpoint plan and return the local plan of each rank.
+
+        This is called on the coordinator rank only.
+        """
+
+    @abc.abstractmethod
+    def finish_plan(self, new_plan: SavePlan) -> SavePlan:
+        """
+        Merge the plan created by `create_local_plan` and the result of `create_global_plan`.
+
+        This is called on all ranks.
+        """
+
+    @abc.abstractmethod
+    def resolve_data(self, write_item: WriteItem) -> Union[torch.Tensor, io.BytesIO]:
+        """
+        Transform and prepare ``write_item`` from ``state_dict`` for storage, ensuring idempotency and thread-safety.
+
+        Lookup the object associated with ``write_item`` in ``state_dict`` and apply any
+        transformation (such as serialization) prior to the storage layer consuming it.
+
+        Called on each rank multiple times, at least once per WriteItem in the final SavePlan.
+
+        This method should be idempotent and thread-save. StorageWriter implementations
+        are free to call it as frequently as they need.
+
+        Any transformation that allocates memory should be lazily done when his method
+        is called in order to reduce peak memory required by checkpointing.
+
+        When returning tensors, they can be on any device or format, they can be views too.
+        It's the storage layer responsibility to figure out how to save them.
+        """
+
+
+class LoadPlanner:
+    """
+    Abstract class defining the protocol used by load_state_dict to plan the load process.
+
+    LoadPlanner are stateful objects that can be used to customize the whole load process.
+
+    LoadPlanner acts as an access proxy to the state_dict, so any transformation done to it
+    will be visible to the whole process.
+
+    A planner subclass can expect the following sequence of calls during load_state_dict:
+
+    1) set_up_planner - called on all ranks.
+        Signals the start of loading a checkpoint.
+
+    2) create_local_plan - called on all ranks.
+        Process the state_dict and produces a `LoadPlan` that will be sent for global planning.
+
+    3) create_global_plan - called on the coordinator rank only.
+        Takes the LoadPlan from all ranks and make any global decision.
+
+    4) load_bytes - called multiple times on each rank
+        This is called once per non-tensor value in state_dict.
+
+    5) resolve_tensor and commit_tensor - called multiple times on each rank
+        They are called in pair for each Tensor value in state_dict.
+
+    Users are recommended to extend DefaultLoadPlanner instead of this interface directly as
+    most changes can be expressed by changes in a single method.
+
+    There are two usual patterns of extension:
+
+    Rewriting state_dict. This is the simplest way to extend the load process as it
+    doesn't requite understanding the intrincacies of how LoadPlan works. We need
+    to keep a reference to the original state_dict as load happens in place so
+    we need to be able to perform it in place
+
+    >>> # xdoctest: +SKIP("undefined vars")
+    >>> class RenamePlanner(DefaultLoadPlanner):
+    >>>     def set_up_planner(
+    >>>         self,
+    >>>         state_dict: STATE_DICT_TYPE,
+    >>>         metadata: Metadata,
+    >>>         is_coordinator: bool,
+    >>>     ) -> None:
+    >>>         self.original_state_dict = state_dict
+    >>>         state_dict = {"foo_" + k: v for k, v in state_dict.items()}
+    >>>
+    >>>         if self.flatten_sharded_tensors:
+    >>>             state_dict = _flatten_sharded_tensors(state_dict)
+    >>>
+    >>>         if self.flatten_state_dict:
+    >>>             state_dict, self.mappings = flatten_state_dict(state_dict)
+    >>>
+    >>>         self.state_dict = state_dict
+    >>>         self.metadata = metadata
+    >>>         self.is_coordinator = is_coordinator
+    >>>
+    >>>     def load_bytes(self, read_item, value):
+    >>>         # Remove the "foo_" prefix
+    >>>         self.original_state_dict[read_item.dest_index.fqn[4:]] = torch.load(value, weights_only=False)
+
+
+    Modifying resolve_tensor and commit_tensor to handle load time transformation.
+
+    >>> # xdoctest: +SKIP("undefined vars")
+    >>> class MetaModelMaterialize(DefaultSavePlanner):
+    >>>     def resolve_tensor(self, read_item):
+    >>>         tensor = super().resolve_tensor(read_item)
+    >>>         return torch.empty_like(tensor, device="cpu")
+    >>>
+    >>>     def commit_tensor(self, read_item, tensor):
+    >>>         self.state_dict[read_item.dest_index.fqn] = tensor
+    """
+
+    @abc.abstractmethod
+    def set_up_planner(
+        self,
+        state_dict: STATE_DICT_TYPE,
+        metadata: Optional[Metadata] = None,
+        is_coordinator: bool = False,
+    ) -> None:
+        """
+        Initialize this instance to load data into ``state_dict``.
+
+        . N.B. This is called on every rank.
+        """
+
+    @abc.abstractmethod
+    def create_local_plan(self) -> LoadPlan:
+        """
+        Create a LoadPlan based on state_dict and metadata provided by set_up_planner.
+
+        . N.B. This is called on every rank.
+        """
+
+    @abc.abstractmethod
+    def create_global_plan(self, global_plan: List[LoadPlan]) -> List[LoadPlan]:
+        """
+        Compute the global load plan and return plans for each rank.
+
+        . N.B. This is called on the coordinator rank only
+        """
+
+    @abc.abstractmethod
+    def finish_plan(self, central_plan: LoadPlan) -> LoadPlan:
+        """Accept the plan from coordinator and return final LoadPlan."""
+
+    @abc.abstractmethod
+    def load_bytes(self, read_item: ReadItem, value: io.BytesIO) -> None:
+        """
+        Load the item described by ``read_item``and ``value``.
+
+        This method is expected to modify in-place the underlying state_dict.
+
+        The contents of ``value`` are defined by the SavePlanner used to produce
+        the checkpoint being loaded.
+        """
+
+    def resolve_bytes(self, read_item: ReadItem) -> io.BytesIO:
+        """
+        Return the BytesIO to be used by the StorageReader to load `read_item`.
+
+        The BytesIO should alias with one on the underlying state_dict as StorageReader will replace its contents.
+        """
+        raise NotImplementedError("LoadPlanner.resolve_bytes is not implemented")
+
+    @abc.abstractmethod
+    def resolve_tensor(self, read_item: ReadItem) -> torch.Tensor:
+        """
+        Return the tensor described by ``read_item`` to be used by the StorageReader to load `read_item`.
+
+        The tensor should alias with one on the underlying state_dict as StorageReader will replace its contents.
+        If, for any reason, that's not possible, the planner can use the ``commit_tensor`` method to copy the data
+        back to the one in state_dict.
+        """
+
+    @abc.abstractmethod
+    def commit_tensor(self, read_item: ReadItem, tensor: torch.Tensor) -> None:
+        """
+        Call once the StorageReader finished loading data into ``tensor``.
+
+        The provided tensor is the same one returned by the call to ``resolve_tensor``.
+        This method is only needed if this LoadPlanner needs to post process ``tensor`` prior to
+        copying it back to the one in the state_dict.
+
+        The contents of tensor will follow its device synchronization model.
+        """
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/planner_helpers.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/planner_helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..d715c651e024ba31ccfc818d0d66d68e1b0008de
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/planner_helpers.py
@@ -0,0 +1,386 @@
+# mypy: allow-untyped-defs
+import io
+from typing import Any, Callable, cast, Dict, List
+
+import torch
+import torch.distributed as dist
+from torch._utils import _get_device_module
+from torch.distributed._shard.metadata import ShardMetadata
+from torch.distributed._shard.sharded_tensor import ShardedTensor
+from torch.distributed.tensor import DTensor
+from torch.distributed.tensor._utils import compute_local_shape_and_global_offset
+
+from .metadata import (
+    BytesStorageMetadata,
+    ChunkStorageMetadata,
+    MetadataIndex,
+    STATE_DICT_TYPE,
+    STORAGE_TYPES,
+    TensorProperties,
+    TensorStorageMetadata,
+)
+from .planner import (
+    LoadItemType,
+    ReadItem,
+    SavePlan,
+    TensorWriteData,
+    WriteItem,
+    WriteItemType,
+)
+from .resharding import (
+    _check_shard_metadata_pair_overlap,
+    _shards_get_overlap_region_wrt_saved_tensor,
+)
+
+
+__all__: List[str] = ["create_read_items_for_chunk_list"]
+
+
+def _create_chunk_from_tensor(tensor: torch.Tensor) -> ChunkStorageMetadata:
+    return ChunkStorageMetadata(
+        offsets=torch.Size([0] * len(tensor.size())), sizes=tensor.size()
+    )
+
+
+def _chunk_for_shard(shard_md: ShardMetadata) -> ChunkStorageMetadata:
+    return ChunkStorageMetadata(
+        offsets=torch.Size(shard_md.shard_offsets),
+        sizes=torch.Size(shard_md.shard_sizes),
+    )
+
+
+def _sharded_tensor_metadata(
+    sharded_tensor: ShardedTensor, shard_md: ShardMetadata
+) -> TensorWriteData:
+    shard_properties = sharded_tensor.metadata().tensor_properties
+
+    properties = TensorProperties(
+        dtype=shard_properties.dtype,
+        layout=shard_properties.layout,
+        requires_grad=shard_properties.requires_grad,
+        memory_format=shard_properties.memory_format,
+        pin_memory=shard_properties.pin_memory,
+    )
+
+    return TensorWriteData(
+        chunk=_chunk_for_shard(shard_md),
+        properties=properties,
+        size=sharded_tensor.metadata().size,
+    )
+
+
+def _create_write_items_for_dtensor(fqn: str, tensor: DTensor) -> WriteItem:
+    sizes, offsets = compute_local_shape_and_global_offset(
+        tensor.shape, tensor.device_mesh, tensor.placements
+    )
+    sizes, offsets = torch.Size(sizes), torch.Size(offsets)
+
+    return WriteItem(
+        index=MetadataIndex(fqn, offsets),
+        type=WriteItemType.SHARD,
+        tensor_data=TensorWriteData(
+            chunk=ChunkStorageMetadata(
+                offsets=offsets,
+                sizes=sizes,
+            ),
+            properties=TensorProperties.create_from_tensor(tensor.to_local()),
+            size=tensor.size(),
+        ),
+    )
+
+
+def _create_write_item_for_shard(
+    fqn: str, sharded_tensor: ShardedTensor, shard_md: ShardMetadata
+) -> WriteItem:
+    offsets = torch.Size(shard_md.shard_offsets)
+    return WriteItem(
+        index=MetadataIndex(fqn, offsets),
+        type=WriteItemType.SHARD,
+        tensor_data=_sharded_tensor_metadata(sharded_tensor, shard_md),
+    )
+
+
+def _create_write_item_for_tensor(fqn: str, tensor: torch.Tensor) -> WriteItem:
+    offsets = torch.Size([0] * len(tensor.size()))
+    return WriteItem(
+        index=MetadataIndex(fqn, offsets),
+        type=WriteItemType.TENSOR,
+        tensor_data=TensorWriteData(
+            chunk=ChunkStorageMetadata(offsets=offsets, sizes=tensor.size()),
+            properties=TensorProperties.create_from_tensor(tensor),
+            size=tensor.size(),
+        ),
+    )
+
+
+def _create_write_item_for_bytesio(fqn: str, bytes: Any):
+    return WriteItem(
+        index=MetadataIndex(fqn),
+        type=WriteItemType.BYTE_IO,
+    )
+
+
+def _create_read_item_for_byteio(
+    dest_index, dest_offset, storage_index, storage_offset, length
+):
+    return ReadItem(
+        type=LoadItemType.BYTE_IO,
+        dest_index=dest_index,
+        dest_offsets=torch.Size((dest_offset,)),
+        storage_index=storage_index,
+        storage_offsets=torch.Size((storage_offset,)),
+        lengths=torch.Size((length,)),
+    )
+
+
+def _create_read_item_for_tensor(
+    dest_index, dest_offsets, storage_index, storage_offsets, lengths
+):
+    return ReadItem(
+        type=LoadItemType.TENSOR,
+        dest_index=dest_index,
+        dest_offsets=torch.Size(dest_offsets),
+        storage_index=storage_index,
+        storage_offsets=torch.Size(storage_offsets),
+        lengths=torch.Size(lengths),
+    )
+
+
+def create_read_items_for_chunk_list(
+    fqn: str,
+    checkpoint_md: TensorStorageMetadata,
+    local_chunks: List[ChunkStorageMetadata],
+) -> List[ReadItem]:
+    """
+    Create a list of ``ReadItem`` based on the checkpoint and local chunks.
+
+    This applies the resharding algorithm and computes the reads needed
+    to satisfy ``local_chunks`` with a checkpoint described by ``checkpoint_md``.
+
+    Args:
+        fqn (str) : The state_dict FQN to pass to ``ReadItem``.
+        checkpoint_md (TensorStorageMetadata): metadata for a given tensor
+            from a checkpoint.
+        local_chunks (List[ChunkStorageMetadata]): Local chunks that needs to be
+            loaded.
+
+    Returns:
+        A list of ``ReadItem`` that will satisfy all input chunks.
+    """
+    read_items = []
+    # this is a naive quadratic algo that can be optimized later
+    for idx, shard in enumerate(local_chunks):
+        for storage_idx, storage_md in enumerate(checkpoint_md.chunks):
+            if not _check_shard_metadata_pair_overlap(shard, storage_md):
+                continue
+
+            storage_offsets = []
+            dest_offsets = []
+            lengths = []
+            for (
+                dim,
+                offset_for_saved_tensor,
+                offset_for_current_tensor,
+                length,
+            ) in _shards_get_overlap_region_wrt_saved_tensor(
+                saved_shard=storage_md, current_shard=shard
+            ):
+                storage_offsets.append(offset_for_saved_tensor)
+                dest_offsets.append(offset_for_current_tensor)
+                lengths.append(length)
+
+            read_items.append(
+                _create_read_item_for_tensor(
+                    dest_index=MetadataIndex(fqn, shard.offsets, idx),
+                    dest_offsets=dest_offsets,
+                    storage_index=MetadataIndex(fqn, storage_md.offsets, storage_idx),
+                    storage_offsets=storage_offsets,
+                    lengths=lengths,
+                )
+            )
+    return read_items
+
+
+def _create_default_metadata_only_plan(state_dict: STATE_DICT_TYPE) -> SavePlan:
+    requests = []
+    for fqn, obj in state_dict.items():
+        if isinstance(obj, DTensor):
+            requests.append(_create_write_items_for_dtensor(fqn, obj))
+        elif isinstance(obj, ShardedTensor):
+            for shard_md in obj.metadata().shards_metadata:
+                requests.append(_create_write_item_for_shard(fqn, obj, shard_md))
+        elif isinstance(obj, torch.Tensor):
+            requests.append(_create_write_item_for_tensor(fqn, obj))
+        else:
+            requests.append(_create_write_item_for_bytesio(fqn, obj))
+    return SavePlan(requests)
+
+
+def _create_write_items(fqn: str, object: Any) -> List[WriteItem]:
+    if hasattr(object, "__create_write_items__"):
+        # DTensor implements _Checkpointable
+        return object.__create_write_items__(fqn, object)
+    elif isinstance(object, ShardedTensor):
+        return [
+            _create_write_item_for_shard(fqn, object, shard.metadata)
+            for shard in object.local_shards()
+        ]
+    elif isinstance(object, torch.Tensor):
+        return [_create_write_item_for_tensor(fqn, object)]
+    else:
+        return [_create_write_item_for_bytesio(fqn, object)]
+
+
+def _create_chunk_from_dtensor(tensor: DTensor) -> ChunkStorageMetadata:
+    sizes, offsets = compute_local_shape_and_global_offset(
+        tensor.shape, tensor.device_mesh, tensor.placements
+    )
+    sizes, offsets = torch.Size(sizes), torch.Size(offsets)
+    return ChunkStorageMetadata(
+        offsets=offsets,
+        sizes=sizes,
+    )
+
+
+def _create_chunk_list(tensor: torch.Tensor) -> List[ChunkStorageMetadata]:
+    if hasattr(tensor, "__create_chunk_list__"):
+        # DTensor implements _Checkpointable
+        local_chunks = tensor.__create_chunk_list__()  # type: ignore[attr-defined]
+    elif isinstance(tensor, ShardedTensor):
+        local_chunks = [
+            _chunk_for_shard(shard.metadata) for shard in tensor.local_shards()
+        ]
+    elif isinstance(tensor, torch.Tensor):
+        local_chunks = [_create_chunk_from_tensor(tensor)]
+    else:
+        raise ValueError(
+            "Unsupported Type, expecting one of [Tensor, DTensor, ShardedTensor] "
+            f",but got {type(tensor)}"
+        )
+
+    return local_chunks
+
+
+def _create_read_items(fqn: str, md: STORAGE_TYPES, obj: Any) -> List[ReadItem]:
+    if not isinstance(md, BytesStorageMetadata):
+        try:
+            local_chunks = _create_chunk_list(obj)
+        except ValueError as ex:
+            raise ValueError(
+                f"Invalid checkpoint metadata for {fqn}, "
+                + f"expected BytesStorageMetadata but found {type(md)}",
+            ) from ex
+
+        return create_read_items_for_chunk_list(fqn, md, local_chunks)
+    else:
+        return [
+            _create_read_item_for_byteio(
+                dest_index=MetadataIndex(fqn),
+                dest_offset=0,
+                storage_index=MetadataIndex(fqn),
+                storage_offset=0,
+                length=0,
+            )
+        ]
+
+
+def _init_state_dict(state_dict: Dict[str, Any]) -> Any:
+    """
+    Initializes meta tensor if the meta tensor is DTensor or torch.Tensor.
+    """
+
+    def dtensor_func(value: DTensor):
+        device = getattr(value, "device", None)
+        if device == torch.device("meta"):
+            device_type = dist.distributed_c10d._get_pg_default_device().type
+            device = cast(
+                torch.device, _get_device_module(device_type).current_device()
+            )
+            new_local_tensor = torch.empty_like(value.to_local(), device=device)
+            # We need to pass shape and stride explicitly, since DTensor might be
+            # sharded unevenly.
+            dtensor = DTensor.from_local(
+                new_local_tensor,
+                device_mesh=value.device_mesh,
+                placements=value.placements,
+                shape=value.size(),
+                stride=value.stride(),
+            )
+            return dtensor
+        else:
+            return value
+
+    def sharded_tensor_func(value: Any):
+        device = getattr(value, "device", None)
+        if device == torch.device("meta"):
+            raise RuntimeError(
+                f"Found unsupported type {type(value)} for meta device loading."
+            )
+        else:
+            return value
+
+    def tensor_func(value: torch.Tensor):
+        device = getattr(value, "device", None)
+        if device == torch.device("meta"):
+            device_type = dist.distributed_c10d._get_pg_default_device().type
+            device = cast(
+                torch.device, _get_device_module(device_type).current_device()
+            )
+            tensor = torch.empty_like(value, device=device)
+            return tensor
+        else:
+            return value
+
+    _iterate_state_dict(
+        state_dict,
+        dtensor_func,
+        sharded_tensor_func,
+        tensor_func,
+    )
+
+
+def _iterate_state_dict(
+    iter_object: Any,
+    dtensor_func: Callable,
+    sharded_tensor_func: Callable,
+    tensor_func: Callable,
+):
+    """
+    Iterate through the state dict, applying the given functions to each tensor type
+    and update the state dict in place.
+
+    Args:
+        iter_object (Any): the target state_dict.
+        sharded_tensor_func (Callable): the function to apply to ShardedTensor
+        dtensor_func (Callable): the function to apply to DTensor
+        tensor_func (Callable): the function to apply to Tensor
+
+    # TODO: let state_dict_util._iterate_state_dict() to support in place option
+    so we don't need to have two versions of _iterate_state_dict.
+    """
+
+    if isinstance(iter_object, DTensor):
+        return dtensor_func(iter_object)
+    elif isinstance(iter_object, ShardedTensor):
+        return sharded_tensor_func(iter_object)
+    elif isinstance(iter_object, torch.Tensor):
+        return tensor_func(iter_object)
+    elif (
+        isinstance(iter_object, (int, float, str, bytes, io.BytesIO))
+        or iter_object is None
+    ):
+        return iter_object
+    elif isinstance(iter_object, dict):
+        for key, value in iter_object.items():
+            iter_object[key] = _iterate_state_dict(
+                value, dtensor_func, sharded_tensor_func, tensor_func
+            )
+        return iter_object
+    elif isinstance(iter_object, (list, tuple)):
+        ret = [
+            _iterate_state_dict(v, dtensor_func, sharded_tensor_func, tensor_func)
+            for v in iter_object
+        ]
+        if isinstance(iter_object, tuple):
+            ret = tuple(ret)  # type: ignore[assignment]
+        return ret
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/resharding.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/resharding.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e5153df8da0adbe58b2c525c233ce805cf8b1c1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/resharding.py
@@ -0,0 +1,72 @@
+# mypy: allow-untyped-defs
+from typing import List, Tuple
+
+from torch.distributed.checkpoint.metadata import ChunkStorageMetadata
+
+
+__all__: List[str] = []
+
+
+def _check_shard_metadata_pair_overlap(
+    shard1: ChunkStorageMetadata, shard2: ChunkStorageMetadata
+):
+    """Check if two shards overlap."""
+    # For each dim of each shard, check if one shard resides on the other
+    # end of second shard with respect to that dim. As an example for a 2D
+    # shard, we would check if one shard is above or on the left of the
+    # other shard.
+    ndims = len(shard1.offsets)
+    for i in range(ndims):
+        if shard1.offsets[i] >= shard2.offsets[i] + shard2.sizes[i]:
+            return False
+        if shard2.offsets[i] >= shard1.offsets[i] + shard1.sizes[i]:
+            return False
+
+    return True
+
+
+def _shards_get_overlap_region_wrt_saved_tensor(
+    saved_shard: ChunkStorageMetadata, current_shard: ChunkStorageMetadata
+) -> List[Tuple[int, int, int, int]]:
+    """
+    Return the overlapping region between saved_shard and current_shard.
+
+    There returned list has the same number of elements as the tensor's dimension.
+    For each element, we produce a tuple with the following contents:
+        (dimension, `saved_shard` offset, `current_shard` offset, length)
+
+    Offsets are relative to each shard.
+    """
+    narrows = []
+    for dim, (
+        saved_shard_offset,
+        current_shard_offset,
+        saved_shard_size,
+        current_shard_size,
+    ) in enumerate(
+        zip(
+            saved_shard.offsets,
+            current_shard.offsets,
+            saved_shard.sizes,
+            current_shard.sizes,
+        )
+    ):
+        min_range_end = min(
+            saved_shard_offset + saved_shard_size,
+            current_shard_offset + current_shard_size,
+        )
+
+        length = min_range_end - max(current_shard_offset, saved_shard_offset)
+
+        if saved_shard_offset > current_shard_offset:
+            offset_for_saved_tensor = 0
+            offset_for_current_tensor = saved_shard_offset - current_shard_offset
+        else:
+            offset_for_saved_tensor = current_shard_offset - saved_shard_offset
+            offset_for_current_tensor = 0
+
+        narrows.append(
+            (dim, offset_for_saved_tensor, offset_for_current_tensor, length)
+        )
+
+    return narrows
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/staging.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/staging.py
new file mode 100644
index 0000000000000000000000000000000000000000..22eed63c1cc517bc18f777d8943045115b440f06
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/staging.py
@@ -0,0 +1,117 @@
+from typing import Optional, runtime_checkable
+from typing_extensions import Protocol
+
+from torch.distributed._state_dict_utils import (
+    _copy_state_dict,
+    _create_cpu_state_dict,
+    _offload_state_dict_to_cpu,
+)
+from torch.distributed.checkpoint.metadata import STATE_DICT_TYPE
+
+
+__all__ = ["AsyncStager", "BlockingAsyncStager"]
+
+
+@runtime_checkable
+class AsyncStager(Protocol):
+    """
+    This protocol is meant to provide customization and extensibility for dcp.async_save, allowing users
+    to customize how data is staged previous to executing the usual dcp.save path in parallel.
+    The expected order of operations (concretely defined in `torch.distributed.state_dict_saver.async_save`)
+    is the following:
+
+    1. AsyncStager.stage_data(state_dict):
+        This call gives the AsyncStager the opportunity to 'stage'
+        the state_dict. The expectation and purpose of staging in this context is to create a "training-safe"
+        representation of the state dict, meaning that any updates to module data after staging is complete
+        should not be reflected in the state dict returned from this method. For example, in the default
+        case a copy of the entire state dict is created on CPU RAM and returned here, allowing users
+        to continue training without risking changes to data which is being serialized.
+
+    2. dcp.save is called on the state_dict returned from stage in parallel. This call is responsible
+        for serializing the state_dict and writing it to storage.
+
+    3. If AsyncStager.should_synchronize_after_execute is True, this method will be called immediately after
+        the serialization thread starts and before returning from dcp.async_save. If this is set to False,
+        the assumption is the user has defined a custom synchronization point for the the purpose of further
+        optimizing save latency in the training loop (for example, by overlapping staging with the
+        forward/backward pass), and it is the respondsibility of the user to call `AsyncStager.synchronize_staging`
+        at the appropriate time.
+
+    """
+
+    # default to True since the common case is to stage synchronously
+    _synchronize_after_execute: bool = True
+
+    @property
+    def should_synchronize_after_execute(self) -> bool:
+        """
+        Whether to synchronize after executing the stage.
+        """
+
+        return self._synchronize_after_execute
+
+    def stage(self, state_dict: STATE_DICT_TYPE) -> STATE_DICT_TYPE:
+        """
+        Returns a "staged" copy of `state_dict`. The expectation of the staged copy is that it is
+        innoculated from any updates incurred after the stage call is complete.
+        """
+        raise NotImplementedError(
+            f"{self.__class__.__name__} must implement stage method"
+        )
+
+    def synchronize_staging(self) -> None:
+        """
+        In the case `stage` is async in some way, this method should be called to ensure staging
+        is complete and it is safe to begin modifying the original `state_dict`
+        """
+
+
+class BlockingAsyncStager(AsyncStager):
+    """
+    An implementation of AsyncStager which stages the state_dict on CPU RAM and blocks until the copy is complete.
+    This implementation also provides an option to optimize stage latency using pinned memory.
+
+    N.B. synchronize_staging is a no-op in this case.
+
+
+    """
+
+    # default to True since the common case is to stage synchronously
+    _synchronize_after_execute: bool = False
+
+    def __init__(
+        self,
+        cache_staged_state_dict: bool = False,
+        type_check: bool = False,
+    ):
+        """
+        Initializes the BlockingAsyncStager.
+
+        Args:
+            cache_staged_state_dict: Whether to cache the staged state_dict. This option decreases staging latency
+                at the cost of increases memory usage. Additionally, if this parameter is set to True, it's the expectation
+                that the stager is maintained and re-used for multiple dcp.async_save calls. Default to False.
+            type_check: Whether to perform a type check during cpu_offload. Defaults to False.
+
+        """
+        self.cache_staged_state_dict = cache_staged_state_dict
+        self.type_check = type_check
+        self.state_dict_cache: Optional[STATE_DICT_TYPE] = None
+
+    def stage(self, state_dict: STATE_DICT_TYPE) -> STATE_DICT_TYPE:
+        """
+        Returns a copy of `state_dict` on the CPU.
+        """
+
+        if not self.cache_staged_state_dict:
+            return _offload_state_dict_to_cpu(state_dict, type_check=self.type_check)
+
+        if self.state_dict_cache is None:
+            self.state_dict_cache = _create_cpu_state_dict(state_dict, pin_memory=True)
+        return _copy_state_dict(state_dict, self.state_dict_cache)
+
+    def synchronize_staging(self) -> None:
+        """
+        No-op function, since staging is blocking.
+        """
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/state_dict.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/state_dict.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef90b32eb2042f6e87f860b86d21a82ac1771323
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/state_dict.py
@@ -0,0 +1,1422 @@
+# mypy: allow-untyped-defs
+import contextlib
+import functools
+import gc
+import warnings
+from dataclasses import asdict, dataclass, field
+from itertools import chain
+from typing import (
+    Any,
+    Callable,
+    cast,
+    Dict,
+    Generator,
+    Iterable,
+    List,
+    no_type_check,
+    Optional,
+    Set,
+    Tuple,
+    Union,
+)
+
+import torch
+import torch.distributed as dist
+import torch.nn as nn
+from torch.distributed._shard.sharded_tensor import ShardedTensor
+from torch.distributed._state_dict_utils import (
+    _broadcast_state_dict,
+    _distribute_state_dict,
+    _flatten_state_dict,
+    _gather_state_dict,
+    _offload_state_dict_to_cpu,
+    _unflatten_state_dict,
+)
+from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import (
+    _CHECKPOINT_PREFIX,
+)
+from torch.distributed.fsdp import (
+    FullOptimStateDictConfig,
+    FullStateDictConfig,
+    FullyShardedDataParallel as FSDP,
+    OptimStateDictConfig,
+    ShardedOptimStateDictConfig,
+    ShardedStateDictConfig,
+    StateDictConfig,
+    StateDictType,
+)
+from torch.distributed.fsdp._common_utils import (
+    _get_module_fsdp_state_if_fully_sharded_module,
+    FSDP_WRAPPED_MODULE,
+)
+from torch.distributed.tensor import DTensor
+from torch.nn.modules.module import _IncompatibleKeys
+from torch.nn.parallel import DistributedDataParallel as DDP
+from torch.utils._pytree import tree_map_only
+
+
+__all__ = [
+    "FQNS_T",
+    "PrimitiveType",
+    "ValueType",
+    "DictValueType",
+    "ListDictValueType",
+    "OptimizerStateType",
+    "StateDictOptions",
+    "get_model_state_dict",
+    "get_optimizer_state_dict",
+    "get_state_dict",
+    "set_model_state_dict",
+    "set_optimizer_state_dict",
+    "set_state_dict",
+]
+
+
+_FLAT_PARAM = "_flat_param"
+_PG = "param_groups"
+_PARAMS = "params"
+_STATE = "state"
+
+FQNS_T = Set[str]
+PrimitiveType = Union[DTensor, ShardedTensor, torch.Tensor, int, float, str]
+ValueType = Union[
+    PrimitiveType, List[PrimitiveType], Tuple[PrimitiveType], Dict[str, "ValueType"]
+]
+DictValueType = Dict[str, ValueType]
+ListDictValueType = List[DictValueType]
+OptimizerStateType = Dict[str, Union[DictValueType, ListDictValueType]]
+
+
+_patched_state_dict: Set[Callable] = set()
+
+
+@contextlib.contextmanager
+def _gc_context():
+    is_enabled = gc.isenabled()
+    gc.disable()
+    try:
+        yield
+    finally:
+        if is_enabled:
+            gc.enable()
+
+
+@dataclass
+class StateDictOptions:
+    """
+    This dataclass specifies how get_state_dict/set_state_dict will work.
+
+    - ``full_state_dict``: if this is set to True, all the tensors in the
+      returned state_dict will be gathered. No ShardedTensor and DTensor
+      will be in the returned state_dict.
+
+    - ``cpu_offload``: offload all the tensors to cpu. To prevent CPU OOM, if
+      ``full_state_dict`` is also true, then only the rank0 will get the
+      state_dict and all other ranks will get empty state_dict.
+
+    - ``ignore_frozen_params``: if the value is True, the returned state_dict
+      won't contain any frozen parameters -- the ``requires_grad`` is False.
+      The default value is False.
+
+    - ``keep_submodule_prefixes`` (deprecated): when ``submodules`` is not None, this option
+      indicates whether to keep the submodule prefixes from the state_dict keys.
+      or example, if the submodule is ``module.pretrain`` and the full FQN of
+      the parameter is ``pretrain.layer1.weight`` of the param. When this option
+      is True, the parameter's key in the returned state_dict will be
+      ``pretrain.layer1.weight``. If the options is False, the key will be
+      ``layer1.weight``.
+      Note that if ``keep_submodule_prefixes`` is False, there may be conflicted
+      FQNs, hence there should be only one submodule in ``submodules``.
+
+    - ``strict``: the ``strict`` option when ``set_state_dict`` calls
+      model.load_state_dict().
+
+    - ``broadcast_from_rank0``: when the option is True, rank0 should receive a
+       full state_dict and will broadcast the tensors in the state_dict/
+       optim_state_dict one by one to other ranks. Other ranks will receive
+       the tensors and shard according to the local shards in the model and
+       optimizer. ``full_state_dict`` must be set to True when using this option.
+       This option currently only supports DTensor, not the legacy ShardedTensor.
+    """
+
+    full_state_dict: bool = False
+    cpu_offload: bool = False
+    ignore_frozen_params: bool = False
+    keep_submodule_prefixes: bool = True
+    strict: bool = True
+    broadcast_from_rank0: bool = False
+    flatten_optimizer_state_dict: bool = False
+
+
+@dataclass
+class _StateDictInfo(StateDictOptions):
+    fqn_param_mapping: Dict[
+        Union[str, torch.Tensor], Union[FQNS_T, torch.Tensor]
+    ] = field(default_factory=dict)
+    shared_params_mapping: Dict[
+        Union[str, torch.Tensor], Union[FQNS_T, torch.Tensor]
+    ] = field(default_factory=dict)
+    submodule_prefixes: Set[str] = field(default_factory=set)
+    handle_model: bool = True
+    handle_optim: bool = True
+    fsdp_context: Callable = contextlib.nullcontext
+    fsdp_modules: List[nn.Module] = field(default_factory=list)
+
+
+@functools.lru_cache(maxsize=None)
+def _get_fqns(
+    model: nn.Module,
+    name: str,
+    skip_ddp_prefix: bool = True,
+    skip_compiler_prefix: bool = True,
+) -> FQNS_T:
+    """
+    This API is used to convert the name of a parameter to the FQNs. For FSDP
+    without `use_orig_params`, the name of FlatParameter can be mapped to
+    multiple original parameters. As a result, the return type of this function
+    is `Set[str]`.
+
+    Args:
+        module (nn.Module): the root model.
+        name (str): the name
+        skip_ddp_prefix (bool): whether to skip DDP's `module` prefix
+
+    Returns:
+        The canonical FQNs based on the model traversal.
+    """
+
+    # Remove the checkpoint prefix, if it exists.
+    name = name.replace(_CHECKPOINT_PREFIX, "")
+    if "." not in name:
+        return {name}
+
+    obj_names = name.split(".")
+    fqn_obj_names = []
+    curr_obj = model
+    for i, curr_obj_name in enumerate(obj_names):
+        if isinstance(curr_obj, DDP):
+            assert curr_obj_name == "module"
+            curr_obj = curr_obj.module
+            if not skip_ddp_prefix:
+                fqn_obj_names.append(curr_obj_name)
+        elif isinstance(curr_obj, FSDP):
+            if i < len(obj_names) - 1 and obj_names[i + 1] == _FLAT_PARAM:
+                prefix = ".".join(fqn_obj_names)
+                flat_param = getattr(curr_obj, _FLAT_PARAM)
+                if prefix:
+                    prefix = f"{prefix}."
+                return {f"{prefix}{fqn}" for fqn in flat_param._fqns}
+            curr_obj = getattr(curr_obj, FSDP_WRAPPED_MODULE)
+            if curr_obj_name != FSDP_WRAPPED_MODULE:
+                fqn_obj_names.append(curr_obj_name)
+                curr_obj = getattr(curr_obj, curr_obj_name)
+        elif isinstance(curr_obj, torch._dynamo.eval_frame.OptimizedModule):
+            assert curr_obj_name == "_orig_mod"
+            curr_obj = curr_obj._orig_mod
+            if not skip_compiler_prefix:
+                fqn_obj_names.append(curr_obj_name)
+        else:
+            fqn_obj_names.append(curr_obj_name)
+            if curr_obj_name == nn.modules.module._EXTRA_STATE_KEY_SUFFIX:
+                if i != len(obj_names) - 1:
+                    raise RuntimeError("Expect `_extra_state` to be the last obj name")
+            else:
+                curr_obj = getattr(curr_obj, curr_obj_name)
+
+    return {".".join(fqn_obj_names).replace(_CHECKPOINT_PREFIX, "")}
+
+
+class _EXTRA_STATE:
+    pass
+
+
+def _iterate_valid_model_state(model):
+    visited_modules: Set[nn.Module] = set()
+
+    def recurse(module: nn.Module, curr_fqn: str) -> Generator:
+        visited_modules.add(module)
+
+        curr_fqn = f"{curr_fqn}." if curr_fqn else ""
+        for name, submodule in module.named_children():
+            if submodule in visited_modules:
+                continue
+            new_fqn = f"{curr_fqn}{name}"
+            yield from recurse(submodule, new_fqn)
+
+        for name, obj in chain(
+            module.named_buffers(recurse=False), module.named_parameters(recurse=False)
+        ):
+            if name in module._non_persistent_buffers_set:
+                continue
+            new_fqn = f"{curr_fqn}{name}"
+            yield new_fqn, obj
+
+        if (
+            getattr(module.__class__, "get_extra_state", nn.Module.get_extra_state)
+            != nn.Module.get_extra_state
+        ):
+            new_fqn = f"{curr_fqn}{nn.modules.module._EXTRA_STATE_KEY_SUFFIX}"
+            yield new_fqn, _EXTRA_STATE()
+
+    yield from recurse(model, "")
+
+
+def _verify_options(
+    model: nn.Module,
+    optims: Tuple[torch.optim.Optimizer, ...],
+    optim_only: bool,
+    *,
+    submodules: Optional[Set[nn.Module]] = None,
+    options: Optional[StateDictOptions] = None,
+) -> _StateDictInfo:
+    """
+    Verify the model and options passed by the user and generates _StateDictInfo.
+    """
+    if submodules:
+        warnings.warn(
+            "Getting submodules only model/optim state_dict is deprecated and "
+            "will be removed in 2.5. This feature can be achieved by manually "
+            "filtering out the state_dict returned from get_state_dict.",
+            FutureWarning,
+        )
+    if optim_only and not optims:
+        raise RuntimeError(
+            "Optimizers are not passed in but optim_only is set to True."
+        )
+
+    options = options or StateDictOptions()
+
+    fqn_param_mapping: Dict[
+        Union[str, torch.Tensor], Union[Set[str], torch.Tensor]
+    ] = {}
+    shared_params_mapping: Dict[
+        Union[str, torch.Tensor], Union[Set[str], torch.Tensor]
+    ] = {}
+    for name, param in _iterate_valid_model_state(model):
+        if isinstance(param, _EXTRA_STATE):
+            continue
+
+        fqns = _get_fqns(model, name)
+        fqn = fqn_param_mapping.get(param, None)
+        if fqn is not None:
+            cast(Set[str], fqn_param_mapping[param]).update(fqns)
+            shared_params_mapping[param] = fqn_param_mapping[param]
+        else:
+            # We need to do copy as _get_fqns is lru_cached
+            fqn_param_mapping[param] = fqns.copy()
+        for fqn in fqns:
+            if not isinstance(param, _EXTRA_STATE):
+                fqn_param_mapping[fqn] = param
+
+    for param_, fqns_ in list(shared_params_mapping.items()):
+        for fqn in fqns_:
+            shared_params_mapping[fqn] = cast(torch.Tensor, param_)
+
+    submodule_prefixes: Set[str] = set()
+    if submodules:
+        submodules = set(submodules)
+        for name, module in model.named_modules():
+            if module not in submodules:
+                continue
+            fqns = _get_fqns(model, name)
+            assert len(fqns) == 1, "Submodule FQN should only have 1 instance"
+            submodule_prefixes.update(f"{fqn}." for fqn in fqns)
+
+    if options.broadcast_from_rank0 and not options.full_state_dict:
+        raise ValueError(
+            "full_state_dict must be True when broadcast_from_rank0 is True."
+        )
+    fsdp_modules = FSDP.fsdp_modules(model)
+    state_dict_config: StateDictConfig
+    optim_state_dict_config: OptimStateDictConfig
+    fsdp_context: Callable
+    if fsdp_modules:
+        # FSDP API only work if at least one FSDP instance exists.
+        if options.full_state_dict:
+            state_dict_config = FullStateDictConfig(
+                offload_to_cpu=options.cpu_offload, rank0_only=options.cpu_offload
+            )
+            optim_state_dict_config = FullOptimStateDictConfig(
+                offload_to_cpu=options.cpu_offload,
+                rank0_only=(options.cpu_offload or options.broadcast_from_rank0),
+            )
+            state_dict_type = StateDictType.FULL_STATE_DICT
+        else:
+            state_dict_config = ShardedStateDictConfig(
+                offload_to_cpu=options.cpu_offload,
+            )
+            optim_state_dict_config = ShardedOptimStateDictConfig(
+                offload_to_cpu=options.cpu_offload,
+            )
+            state_dict_type = StateDictType.SHARDED_STATE_DICT
+
+        @contextlib.contextmanager
+        def fsdp_state_dict_type_without_warning(
+            module,
+            state_dict_type,
+            state_dict_config,
+            optim_state_dict_config,
+        ):
+            with warnings.catch_warnings():
+                warnings.filterwarnings(
+                    "ignore", message="FSDP.state_dict_type", category=FutureWarning
+                )
+                with FSDP.state_dict_type(
+                    module=module,
+                    state_dict_type=state_dict_type,
+                    state_dict_config=state_dict_config,
+                    optim_state_dict_config=optim_state_dict_config,
+                ):
+                    yield
+
+        fsdp_context = functools.partial(
+            fsdp_state_dict_type_without_warning,
+            module=model,
+            state_dict_type=state_dict_type,
+            state_dict_config=state_dict_config,
+            optim_state_dict_config=optim_state_dict_config,
+        )
+    else:
+        fsdp_context = contextlib.nullcontext
+
+    return _StateDictInfo(
+        **asdict(options),
+        fqn_param_mapping=fqn_param_mapping,
+        shared_params_mapping=shared_params_mapping,
+        submodule_prefixes=submodule_prefixes,
+        fsdp_context=fsdp_context,
+        fsdp_modules=cast(List[nn.Module], fsdp_modules),
+        handle_model=not optim_only,
+        handle_optim=(len(optims) > 0),
+    )
+
+
+def _verify_state_dict(
+    model_state_dict: Dict[str, ValueType],
+    optim_state_dict: OptimizerStateType,
+    info: _StateDictInfo,
+) -> None:
+    for module in info.fsdp_modules:
+        fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module)
+        assert fsdp_state is not None, "Expected a fsdp_state with a fsdp module."
+
+    # Verify if the model_state_dict and optim_state_dict are valid. This API
+    # should give the users an explicit error message to debug or report.
+    if (
+        info.handle_model
+        and not model_state_dict
+        and not info.submodule_prefixes
+        and not info.ignore_frozen_params
+        and not (info.cpu_offload and info.full_state_dict)
+        and info.strict
+        and not info.broadcast_from_rank0
+    ):
+        raise RuntimeError(
+            "The option indicates that model state_dict is required to save "
+            "or load, but model state_dict is empty."
+            f"rank = {dist.get_rank()=}."
+        )
+
+    if info.handle_optim:
+        if (
+            not optim_state_dict
+            and not (info.cpu_offload and info.full_state_dict)
+            and (not info.broadcast_from_rank0)
+        ):
+            raise RuntimeError(
+                "The option indicates that model state_dict is required to save, "
+                f"or load but optim state_dict is empty. {optim_state_dict}"
+            )
+
+    for key in model_state_dict.keys():
+        if _FLAT_PARAM in key:
+            raise RuntimeError(
+                f"{key} contains {_FLAT_PARAM}. This can happen if the model "
+                "is not the root module."
+            )
+
+
+def _state_dict_fn(obj: Union[nn.Module, torch.optim.Optimizer], api: str) -> Callable:
+    call = getattr(obj, api)
+    if call in _patched_state_dict:
+        call = functools.partial(getattr(obj.__class__, api), self=obj)
+    return call
+
+
+def _maybe_full_or_cpu_state_dict(
+    state_dict: Dict[str, Any], info: _StateDictInfo
+) -> Dict[str, Any]:
+    if info.full_state_dict:
+        ranks_only = (
+            ()
+            if (not info.cpu_offload or not torch.distributed.is_initialized())
+            else (0,)
+        )
+        return _gather_state_dict(
+            state_dict, cpu_offload=info.cpu_offload, ranks_only=ranks_only
+        )
+    elif info.cpu_offload:
+        return _offload_state_dict_to_cpu(state_dict)
+    else:
+        return state_dict
+
+
+@torch.no_grad()
+def _get_model_state_dict(
+    model: nn.Module, info: _StateDictInfo
+) -> Dict[str, ValueType]:
+    if not info.handle_model:
+        return {}
+
+    with info.fsdp_context():
+        state_dict = _state_dict_fn(model, "state_dict")()
+
+    for key in list(state_dict.keys()):
+        fqns = _get_fqns(model, key)
+        assert len(fqns) == 1, (key, fqns)
+        fqn = next(iter(fqns))
+        if fqn != key:
+            # As we only support FSDP, DDP, and TP, the only cases are
+            # wrapper-based DDP and compiler. Verify if the assumption
+            # is correct.
+            def verify(key, fqn) -> bool:
+                if len(fqn) >= len(key):
+                    return False
+                fqn_split = fqn.split(".")
+                key_split = key.split(".")
+                fqn_idx = 0
+                for key_idx, key_name in enumerate(key_split):
+                    if key_name == fqn_split[fqn_idx]:
+                        fqn_idx += 1
+                        if fqn_idx == len(fqn_split):
+                            return key_idx == len(key_split) - 1
+                    elif key_name in ("module", "_orig_mod"):
+                        continue
+                    else:
+                        return False
+                return True
+
+            if not verify(key, fqn):
+                raise RuntimeError(f"An unexpected key, {key}, exists. FQN is {fqn}")
+            state_dict[fqn] = state_dict.pop(key)
+
+    if info.submodule_prefixes:
+        new_state_dict: Dict[str, ValueType] = {}
+        # TODO: make this faster.
+        for fqn in state_dict.keys():
+            for prefix in info.submodule_prefixes:
+                if not fqn.startswith(prefix):
+                    continue
+                if info.keep_submodule_prefixes:
+                    new_state_dict[fqn] = state_dict[fqn]
+                else:
+                    new_fqn = fqn[len(prefix) :]
+                    new_state_dict[new_fqn] = state_dict[fqn]
+        state_dict = new_state_dict
+
+    if info.ignore_frozen_params:
+        for key, param in model.named_parameters():
+            if param.requires_grad:
+                continue
+            fqns = _get_fqns(model, key)
+            for fqn in fqns:
+                state_dict.pop(fqn)
+
+    for key, p in list(state_dict.items()):
+        if torch.is_tensor(p) and p.is_meta:
+            state_dict.pop(key)
+
+    return _maybe_full_or_cpu_state_dict(state_dict, info)
+
+
+@torch.no_grad()
+def _load_model_state_dict(
+    model: nn.Module,
+    state_dict: Dict[str, ValueType],
+    info: _StateDictInfo,
+) -> _IncompatibleKeys:
+    if not info.handle_model or (not state_dict and not info.broadcast_from_rank0):
+        return _IncompatibleKeys({}, {})
+
+    local_state_dict = {}
+    for key, value in _iterate_valid_model_state(model):
+        fqns = _get_fqns(model, key)
+        fqns_with_prefix = _get_fqns(
+            model, key, skip_ddp_prefix=False, skip_compiler_prefix=False
+        )
+
+        for fqn, fqn_with_prefix in zip(fqns, fqns_with_prefix):
+            if (
+                not info.broadcast_from_rank0 or dist.get_rank() == 0
+            ) and fqn != fqn_with_prefix:
+                state_dict[fqn_with_prefix] = state_dict.pop(fqn)
+            local_state_dict[fqn_with_prefix] = value
+
+    assign = False
+    if info.broadcast_from_rank0 or info.full_state_dict:
+        device = None
+        for key, value in local_state_dict.items():
+            if torch.is_tensor(value) and value.dim() > 0:
+                if device is None:
+                    device = value.device
+                else:
+                    assert device == value.device
+        assert device is not None
+        if device == torch.device("meta"):
+            device = dist.distributed_c10d._get_pg_default_device()
+            assign = True
+        if info.broadcast_from_rank0:
+            _broadcast_state_dict(
+                state_dict, local_state_dict, device=device, strict=info.strict
+            )
+        elif info.full_state_dict:
+            _distribute_state_dict(state_dict, local_state_dict, device=device)
+        for fqn, local_state in local_state_dict.items():
+            state_dict[fqn] = local_state
+
+    with info.fsdp_context():
+        return cast(
+            _IncompatibleKeys,
+            _state_dict_fn(model, "load_state_dict")(
+                state_dict=state_dict, strict=info.strict, assign=assign
+            ),
+        )
+
+
+def _init_optim_state(optim: torch.optim.Optimizer) -> None:
+    """
+    Initialize optim states by calling the step() with zero grads.
+    """
+    if optim.state:
+        # The optimizer state is initialized.
+        return
+
+    # There are some stateless optimizers like SGD. These optimizer will
+    # not return in the above condition. So if gradients exist, we should also
+    # return. If gradients do not exist, the following initialization should
+    # not disturb SGD because the gradients and lr are both zero.
+    for param_group in optim.param_groups:
+        for param in param_group[_PARAMS]:
+            if param.grad is not None:
+                return
+
+    for param_group in optim.param_groups:
+        for param in param_group[_PARAMS]:
+            if param.requires_grad:
+                param.grad = torch.zeros_like(param)
+
+    # Some optimizers will update parameters regardless of grads due to lr, so
+    # make lr to zero when calling `step()`.
+    lrs = []
+    for param_group in optim.param_groups:
+        if "lr" in param_group:
+            lrs.append(param_group["lr"])
+            param_group["lr"] = 0.0
+    optim.step(closure=None)
+    # Whether to recover the "lr" should not matter too much as we will
+    # restore checkpointing later.
+    for param_group in optim.param_groups:
+        if "lr" in param_group:
+            param_group["lr"] = lrs.pop(0)
+    optim.zero_grad(set_to_none=True)
+
+
+def _flatten_optim_state_dict(state_dict: OptimizerStateType) -> Dict[str, ValueType]:
+    """
+    This API flattens the optimizer state_dict to support optimizer resharding for
+    MPMD, e.g., pipeline parallelism.
+
+    Without the API, the original optimizer state_dict looks like:
+    {
+        "state": {
+            "layer1.weight": {
+                "step": 10, "exp_avg": SomeTensor, "exp_avg_sq": SomeTensor
+            },
+            "layer2.weight": {
+                "step": 10, "exp_avg": SomeTensor, "exp_avg_sq": SomeTensor
+            },
+        },
+        "param_group": [
+            {
+                "lr": 0.0,
+                "betas": (0.9, 0.95), ...,
+                "params": ["layer1.weight", "layer2.weight"]
+            }
+        ]
+    }
+
+    With this API, the optimizer state_dict looks like:
+    {
+        "state.layer1.weight.step": 10,
+        "state.layer2.weight.step": 10,
+        "state.layer1.weight.exp_avg": SomeTensor,
+        "state.layer2.weight.exp_avg": SomeTensor,
+        "state.layer1.weight.exp_avg_sq": SomeTensor,
+        "state.layer2.weight.exp_avg_sq": SomeTensor,
+        "param_group.layer1.weight.lr" : 0.1,
+        "param_group.layer2.weight.lr" : 0.1,
+        "param_group.layer1.weight.betas" : (0.9, 0.95),
+        "param_group.layer2.weight.betas" : (0.9, 0.95),
+    }
+
+    Note that if any of the value is a container, like the betas in the example,
+    this API won't flattent it.
+    """
+
+    def _raise_if_type_not_supported(v):
+        if not isinstance(v, (torch.Tensor, int, float)):
+            raise NotImplementedError(
+                "Flattening optimizer state_dict only supports "
+                "tensor, int, float states now. "
+                f"Type is {type(v)}."
+            )
+
+    ret: Dict[str, ValueType] = {}
+    for fqn, state in cast(DictValueType, state_dict[_STATE]).items():
+        for k, v in cast(DictValueType, state).items():
+            _raise_if_type_not_supported(v)
+            ret[f"{_STATE}.{fqn}.{k}"] = v
+
+    for param_group in cast(ListDictValueType, state_dict[_PG]):
+        fqns = param_group.pop(_PARAMS)
+        for fqn in cast(List[str], fqns):
+            for k, v in param_group.items():
+                ret[f"{_PG}.{fqn}.{k}"] = v
+    return ret
+
+
+def _unflatten_optim_state_dict(
+    optim: torch.optim.Optimizer,
+    state_dict: Dict[str, ValueType],
+    info: _StateDictInfo,
+) -> OptimizerStateType:
+    """
+    This API unflattens the state_dict generated by _flatten_optim_state_dict().
+    See the docstring of _flatten_optim_state_dict() for more detail.
+    """
+    state: DictValueType = {}
+    pg_state: ListDictValueType = []
+    return_osd: OptimizerStateType = {_STATE: state, _PG: pg_state}
+
+    for param_group in optim.param_groups:
+        pg_state.append({_PARAMS: []})
+        for param in param_group[_PARAMS]:
+            for fqn in info.fqn_param_mapping[param]:
+                params = pg_state[-1][_PARAMS]
+                assert isinstance(params, list)  # typing
+                params.append(fqn)
+                if not param.requires_grad:
+                    continue
+                state[fqn] = {}
+                for state_name in optim.state[param].keys():
+                    cast(DictValueType, state[fqn])[state_name] = state_dict[
+                        f"{_STATE}.{fqn}.{state_name}"
+                    ]
+
+        first_param_fqn = cast(List[str], pg_state[-1][_PARAMS])[0]
+        for k in param_group.keys():
+            if k == _PARAMS:
+                continue
+            value = state_dict[f"{_PG}.{first_param_fqn}.{k}"]
+            if k not in pg_state[-1]:
+                pg_state[-1][k] = value
+            elif pg_state[-1][k] != value:
+                raise RuntimeError(
+                    "All the parameters in the same parameter group should have "
+                    f"the same saved param_group value. But {first_param_fqn}.{k} "
+                    f"is {value} while other(s) is {pg_state[-1][k]}."
+                )
+
+    return return_osd
+
+
+@torch.no_grad()
+def _get_optim_state_dict(
+    model: nn.Module,
+    optimizers: Tuple[torch.optim.Optimizer, ...],
+    info: _StateDictInfo,
+) -> OptimizerStateType:
+    if not info.handle_optim:
+        return {}
+
+    optim_state_dict: OptimizerStateType = {_STATE: {}, _PG: []}
+    for optim in optimizers:
+        _init_optim_state(optim)
+        osd = _state_dict_fn(optim, "state_dict")()
+        if info.fsdp_modules:
+            with info.fsdp_context():
+                osd = FSDP.optim_state_dict(model, optim, osd)
+
+            # We need to specially handle FlatParameter FSDP as
+            # FlatParameter FSDP converts the FQNs.
+            # There are no easy ways to do this conversion systematically.
+            # We can only use a string replacment without correctness check.
+            if not osd:
+                continue
+            for k in list(osd[_STATE].keys()):
+                if "_orig_mod" in k:
+                    osd[_STATE][k.replace("_orig_mod.", "")] = osd[_STATE].pop(k)
+            for g in osd[_PG]:
+                params = [k.replace("_orig_mod.", "") for k in g[_PARAMS]]
+                g[_PARAMS] = params
+        else:
+            params = list(chain.from_iterable(g[_PARAMS] for g in optim.param_groups))
+            param_pid_mapping = dict(zip(params, range(len(params))))
+            fqn_pid_mapping = {}
+            for key, param in model.named_parameters():
+                fqns = _get_fqns(model, key)
+                assert len(fqns) == 1
+                fqn = next(iter(fqns))
+                if param not in param_pid_mapping:
+                    continue
+                pid = param_pid_mapping[param]
+                fqn_pid_mapping[fqn] = pid
+                fqn_pid_mapping[pid] = fqn
+
+            for key in list(osd[_STATE].keys()):
+                fqn = fqn_pid_mapping[key]
+                osd[_STATE][fqn] = osd[_STATE].pop(key)
+
+            for group in osd[_PG]:
+                group[_PARAMS] = [fqn_pid_mapping[pid] for pid in group[_PARAMS]]
+
+        if not osd:
+            continue
+
+        cast(DictValueType, optim_state_dict[_STATE]).update(osd[_STATE])
+        cast(ListDictValueType, optim_state_dict[_PG]).extend(osd[_PG])
+
+    if info.flatten_optimizer_state_dict:
+        optim_state_dict = cast(
+            OptimizerStateType, _flatten_optim_state_dict(optim_state_dict)
+        )
+
+    return _maybe_full_or_cpu_state_dict(optim_state_dict, info)
+
+
+def _split_optim_state_dict(
+    model: nn.Module,
+    optim: torch.optim.Optimizer,
+    optim_state_dict: OptimizerStateType,
+    info: _StateDictInfo,
+) -> OptimizerStateType:
+    """
+    Extract the corresponding optim state_dict from ``optim_state_dict`` for
+    ``optim`` and return the result optim state_dict.
+
+    Args:
+        model (nn.Module): the root model.
+        optim (torch.optim.Optimizer): the optimizer.
+        optim_state_dict (Dict[str, ValueType]): the superset optim state_dict that
+            contains the optim state_dict of ``optim``.
+        info (_StateDictInfo): state dict information.
+
+    Returns:
+        The optim state_dict of ``optim``.
+    """
+
+    state: DictValueType = {}
+    pg_state: ListDictValueType = []
+    return_osd: OptimizerStateType = {_STATE: state, _PG: pg_state}
+    pg_mapping: Dict[int, int] = {}
+
+    if all(
+        isinstance(k, int) for k in cast(DictValueType, optim_state_dict[_STATE]).keys()
+    ):
+        return optim_state_dict
+
+    for param_group in optim.param_groups:
+        pg_state.append({_PARAMS: []})
+        for param in param_group[_PARAMS]:
+            for fqn in info.fqn_param_mapping[param]:
+                if fqn in info.shared_params_mapping:
+                    in_params = False
+                    for loaded_param_group in cast(
+                        ListDictValueType, optim_state_dict[_PG]
+                    ):
+                        if fqn in cast(List[str], loaded_param_group[_PARAMS]):
+                            in_params = True
+                            break
+                else:
+                    in_params = True
+                if not in_params:
+                    continue
+
+                params = pg_state[-1][_PARAMS]
+                assert isinstance(params, list)
+                params.append(fqn)
+                if param.requires_grad:
+                    state[fqn] = cast(DictValueType, optim_state_dict[_STATE])[fqn]
+                for loaded_param_group in cast(
+                    ListDictValueType, optim_state_dict[_PG]
+                ):
+                    if fqn in cast(List[str], loaded_param_group[_PARAMS]):
+                        pg_mapping[id(loaded_param_group)] = len(return_osd[_PG]) - 1
+
+    for param_group in cast(ListDictValueType, optim_state_dict[_PG]):
+        idx = pg_mapping.get(id(param_group), -1)
+        if idx == -1:
+            continue
+        for key, value in param_group.items():
+            if key == _PARAMS:
+                continue
+            # TODO: check if value is the same if exists.
+            pg_state[idx][key] = value
+
+    return return_osd
+
+
+@torch.no_grad()
+def _load_optim_state_dict(
+    model: nn.Module,
+    optimizers: Tuple[torch.optim.Optimizer, ...],
+    state_dict: OptimizerStateType,
+    info: _StateDictInfo,
+) -> None:
+    if not info.handle_optim:
+        return
+
+    for optim in optimizers:
+        _init_optim_state(optim)
+        if state_dict:
+            if _STATE in state_dict:
+                optim_state_dict = _split_optim_state_dict(
+                    model, optim, state_dict, info
+                )
+            else:
+                optim_state_dict = _unflatten_optim_state_dict(
+                    optim, cast(Dict[str, ValueType], state_dict), info
+                )
+        else:
+            optim_state_dict = {}
+        if info.fsdp_modules:
+            # We need to specially handle FlatParameter FSDP as
+            # FlatParameter FSDP converts the FQNs.
+            for original_fqn, _ in model.named_parameters():
+                fqns = _get_fqns(model, original_fqn)
+                fqns_with_compiler = _get_fqns(
+                    model, original_fqn, skip_compiler_prefix=False
+                )
+                if fqns == fqns_with_compiler:
+                    continue
+
+                assert len(fqns) == 1
+                fqn = fqns.pop()
+                fqn_with_compiler = fqns_with_compiler.pop()
+                for g in optim_state_dict[_PG]:
+                    val = cast(Dict[str, Any], g)
+                    params = [
+                        key.replace(fqn, fqn_with_compiler) for key in val[_PARAMS]
+                    ]
+                    val[_PARAMS] = params
+                osd_state = cast(DictValueType, optim_state_dict[_STATE])
+                for k in list(osd_state.keys()):
+                    if fqn in k:
+                        osd_state[k.replace(fqn, fqn_with_compiler)] = osd_state.pop(k)
+
+            with info.fsdp_context():
+                optim_state_dict = FSDP.optim_state_dict_to_load(
+                    model, optim, optim_state_dict
+                )
+        elif info.full_state_dict:
+            info.full_state_dict = False
+            local_state_dict = _get_optim_state_dict(model, (optim,), info)
+            info.full_state_dict = True
+            device = None
+
+            def _device(t):
+                if t.dim() > 0:
+                    nonlocal device
+                    if device is None:
+                        device = t.device
+                    elif device != t.device:
+                        raise ValueError("Device mismatch")
+                return t
+
+            _ = tree_map_only(torch.Tensor, _device, local_state_dict)
+            assert device is not None
+            flatten_osd, osd_mapping = _flatten_state_dict(optim_state_dict)
+            flatten_local_osd, local_osd_mapping = _flatten_state_dict(local_state_dict)
+            if info.broadcast_from_rank0:
+                _broadcast_state_dict(flatten_osd, flatten_local_osd, device=device)
+            else:
+                _distribute_state_dict(flatten_osd, flatten_local_osd, device=device)
+            # The modifications listed seek to address the problem where optim might possess
+            # dissimilar parameters in comparison to optim_state_dict. This is achieved by
+            # incorporating differential parameters within local, which may result in optim
+            # having additional parameters ultimately.
+            for optim_key in flatten_osd.keys():
+                if optim_key not in flatten_local_osd:
+                    assert optim_key in osd_mapping
+                    flatten_local_osd[optim_key] = flatten_osd[optim_key]
+                    local_osd_mapping[optim_key] = osd_mapping[optim_key]
+            optim_state_dict = _unflatten_state_dict(
+                flatten_local_osd, local_osd_mapping
+            )
+
+        # Note that we do not have to convert the FQN back to param id here if
+        # order in optim.param_groups[idx][_PARAMS] is the same as the one in
+        # optim_state_dict[_PG][idx][_PARAMS].
+        _state_dict_fn(optim, "load_state_dict")(state_dict=optim_state_dict)
+
+
+def get_model_state_dict(
+    model: nn.Module,
+    *,
+    submodules: Optional[Set[nn.Module]] = None,
+    options: Optional[StateDictOptions] = None,
+) -> Dict[str, ValueType]:
+    """
+    Return the model state_dict of ``model``.
+
+    See ``get_state_dict`` for the detail usage.
+
+    Args:
+        model (nn.Module): the nn.Module to the model.
+        submodules (deprecated): Optional[Set[nn.Module]]: only return the model parameters
+            that belong to the submodules.
+        options (StateDictOptions): the options to control how
+            model state_dict and optimizer state_dict should be returned. See
+            `StateDictOptions` for the details.
+
+    Returns:
+        The state_dict for ``model``.
+
+    :rtype: typing.Dict[str, ValueType]
+    """
+    with _gc_context():
+        info = _verify_options(
+            model,
+            (),
+            optim_only=False,
+            submodules=submodules,
+            options=options,
+        )
+        model_state_dict = _get_model_state_dict(model, info)
+        _verify_state_dict(model_state_dict, {}, info)
+        return model_state_dict
+
+
+def get_optimizer_state_dict(
+    model: nn.Module,
+    optimizers: Union[torch.optim.Optimizer, Iterable[torch.optim.Optimizer]],
+    *,
+    submodules: Optional[Set[nn.Module]] = None,
+    options: Optional[StateDictOptions] = None,
+) -> OptimizerStateType:
+    """
+    Return the combined state_dict for optimizers.
+
+    See ``get_state_dict`` for the detail usage.
+
+    Args:
+        model (nn.Module): the nn.Module to the model.
+        optimizers (Union[None, Optimizer, Iterable[Optimizer]]):
+            The optimizers that are used to optimize ``model``.
+        submodules (deprecated): Optional[Set[nn.Module]]: only return the model parameters
+            that belong to the submodules.
+        options (StateDictOptions): the options to control how
+            model state_dict and optimizer state_dict should be returned. See
+            `StateDictOptions` for the details.
+
+    Returns:
+        The state_dict for ``optimizers``.
+
+    :rtype: OptimizerStateType
+    """
+    with _gc_context():
+        optimizers = (
+            (optimizers,)
+            if isinstance(optimizers, torch.optim.Optimizer)
+            else tuple(optimizers)
+        )
+        info = _verify_options(
+            model,
+            optimizers,
+            optim_only=True,
+            submodules=submodules,
+            options=options,
+        )
+        optim_state_dict = _get_optim_state_dict(model, optimizers, info)
+        _verify_state_dict({}, optim_state_dict, info)
+        return optim_state_dict
+
+
+def get_state_dict(
+    model: nn.Module,
+    optimizers: Union[torch.optim.Optimizer, Iterable[torch.optim.Optimizer]],
+    *,
+    submodules: Optional[Set[nn.Module]] = None,
+    options: Optional[StateDictOptions] = None,
+) -> Tuple[Dict[str, ValueType], OptimizerStateType]:
+    """
+    Return the model state_dict and optimizers state_dict.
+
+    ``get_state_dict`` can process any module that is parallelized by PyTorch
+    FSDP/fully_shard, DDP/replicate, tensor_parallel/parallelize_module, and any
+    combination of these parallelisms. The main functions of ``get_state_dict``
+    are: 1.) returning a model and optimizer state_dict that can be resharded
+    with a different number of trainers and/or different parallelisms.
+    2.) hiding the parallelism-specific state_dict APIs. Users don't have to call
+    these APIs.
+    3.) sanity checking the result state_dict.
+
+    The keys of the result state dictionary are the canonical FQNs (Fully
+    Qualified Names).  A canonical FQN refers to the FQN based on a parameter's
+    position in an nn.Module hierarchy. More specifically, a canonical FQN to a
+    parameter is the FQN returned by ``module.named_parameters()`` or
+    ``module.named_buffers()`` when the module is not distributed by any
+    parallelisms. Since the optimizer internally uses parameter IDs to represent
+    a parameter, there will be a conversion from the parameter IDs to the
+    canonical FQNs when calling this API.
+
+    ``get_state_dict`` can also process a module that is not parallelized. In
+    such a case, ``get_state_dict`` only performs one function -- converting the
+    optimizer parameter IDs to the canonical FQNs.
+
+    Example:
+        >>> # xdoctest: +SKIP
+        >>> import torch
+        >>> from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
+        >>> from torch.nn.parallel import DistributedDataParallel as DDP
+        >>> from torch.distributed.checkpoint.state_dict import get_state_dict
+
+        >>> fsdp_model = FSDP(copy.deepcopy(model))
+        >>> fsdp_optim = torch.optim.Adam(model.parameters(), lr=1e-3)
+        >>> ddp_model = DDP(copy.deepcopy(model))
+        >>> ddp_optim = torch.optim.Adam(model.parameters(), lr=1e-3)
+
+
+        >>> ddp_state_dict, ddp_optim_state_dict = get_state_dict(ddp_model, ddp_optim)
+        >>> fsdp_state_dict, fsdp_optim_state_dict = get_state_dict(fsdp_model, fsdp_optim)
+
+        >>> # if we simply call ddp_model.state_dict() and fsdp_model.state_dict(),
+        >>> # the asserts will fail.
+        >>> assert ddp_state_dict == fsdp_state_dict
+        >>> assert ddp_optim_state == fsdp_optim_state_dict
+
+
+    Args:
+        model (nn.Module): the nn.Module to the model.
+        optimizers (Union[None, Optimizer, Iterable[Optimizer]]):
+            The optimizers that are used to optimize ``model``.
+        submodules (deprecated): Optional[Set[nn.Module]]: only return the model parameters
+            that belong to the submodules.
+        options (StateDictOptions): the options to control how
+            model state_dict and optimizer state_dict should be returned. See
+            `StateDictOptions` for the details.
+
+    Returns:
+        ``Tuple`` that contain model state_dict and optimizer state_dict.
+
+    :rtype: typing.Tuple[typing.Dict[str, ValueType], OptimizerStateType]
+    """
+
+    with _gc_context():
+        optimizers = (
+            (optimizers,)
+            if isinstance(optimizers, torch.optim.Optimizer)
+            else tuple(optimizers)
+        )
+        info = _verify_options(
+            model,
+            optimizers,
+            optim_only=False,
+            submodules=submodules,
+            options=options,
+        )
+        model_state_dict = _get_model_state_dict(model, info)
+        optim_state_dict = _get_optim_state_dict(model, optimizers, info)
+        _verify_state_dict(model_state_dict, optim_state_dict, info)
+        return model_state_dict, optim_state_dict
+
+
+def _unflatten_model_state_dict(
+    model: nn.Module,
+    state_dict: Union[Dict[nn.Module, Dict[str, ValueType]], Dict[str, ValueType]],
+) -> Dict[str, ValueType]:
+    if not state_dict:
+        return {}
+
+    if isinstance(next(iter(state_dict.keys())), nn.Module):
+        warnings.warn(
+            "Passing model_state_dict as a ``Dict[nn.Module, Dict[str, Any]]``"
+            "is deprecated and will be removed in 2.5. If you need this "
+            "feature, please preprocessing the model_state_dict to achieve the "
+            "same functionality.",
+            FutureWarning,
+        )
+        cast_state_dict = cast(Dict[nn.Module, Dict[str, ValueType]], state_dict)
+        new_state_dict: Dict[str, ValueType] = {}
+        for submodule, sub_state_dict in cast_state_dict.items():
+            for name, m in model.named_modules():
+                if m != submodule:
+                    continue
+
+                fqns = _get_fqns(model, name)
+                assert len(fqns) == 1, "FQNs for a submodule should only have 1 element"
+                prefix = f"{next(iter(fqns))}."
+                new_state_dict.update(
+                    {prefix + subfqn: value for subfqn, value in sub_state_dict.items()}
+                )
+        return new_state_dict
+    else:
+        return cast(Dict[str, ValueType], state_dict)
+
+
+def set_model_state_dict(
+    model: nn.Module,
+    model_state_dict: Dict[str, ValueType],
+    *,
+    options: Optional[StateDictOptions] = None,
+) -> _IncompatibleKeys:
+    """Load the model state_dict.
+
+    The counterpart of ``get_model_state_dict`` to set the state_dict to the
+    model. See ``set_state_dict`` for the detail usage.
+
+    Args:
+        model (nn.Module): the nn.Module to the model.
+        model_state_dict: (Dict[str, ValueType]):
+           the model state_dict to load. If the key of the ``model_state_dict``
+           is nn.Module, the key is a submodule of ``model`` and the value should
+           be the state_dict of the submodule. When loading the state_dict,
+           the prefix of the submodule will be append to the state_dict.
+        options (StateDictOptions): the options to control how
+            model state_dict and optimizer state_dict should be loaded. See
+            `StateDictOptions` for the details.
+
+    Returns:
+        ``NamedTuple`` with ``missing_keys`` and ``unexpected_keys`` fields:
+            * **missing_keys** is a list of str containing the missing keys
+            * **unexpected_keys** is a list of str containing the unexpected keys
+
+    :type model_state_dict: typing.Dict[str, ValueType]
+    """
+    model_state_dict: Dict[str, ValueType] = _unflatten_model_state_dict(
+        model, model_state_dict
+    )
+    with _gc_context():
+        info = _verify_options(model, (), optim_only=False, options=options)
+
+        _verify_state_dict(model_state_dict, {}, info)
+        return _load_model_state_dict(model, model_state_dict, info)
+
+
+def set_optimizer_state_dict(
+    model: nn.Module,
+    optimizers: Union[torch.optim.Optimizer, Iterable[torch.optim.Optimizer]],
+    optim_state_dict: OptimizerStateType,
+    *,
+    options: Optional[StateDictOptions] = None,
+) -> None:
+    """Load the optimizers state_dict.
+
+    The counterpart of ``get_optimizer_state_dict`` to set the state_dict to the
+    optimizers. See ``set_state_dict`` for the detail usage.
+
+    Args:
+        model (nn.Module): the nn.Module to the model.
+        optimizers (Union[Optimizer, Iterable[Optimizer]]):
+            The optimizers that are used to optimize ``model``.
+        optim_state_dict: OptimizerStateType:
+            the optimizer state_dict to load.
+        options (StateDictOptions): the options to control how
+            model state_dict and optimizer state_dict should be loaded. See
+            `StateDictOptions` for the details.
+
+    Returns:
+        None
+
+    :type optim_state_dict: typing.OptimizerStateType
+    """
+    with _gc_context():
+        optimizers = (
+            (optimizers,)
+            if isinstance(optimizers, torch.optim.Optimizer)
+            else tuple(optimizers)
+        )
+        info = _verify_options(model, optimizers, optim_only=True, options=options)
+
+        _verify_state_dict({}, optim_state_dict, info)
+        _load_optim_state_dict(model, optimizers, optim_state_dict, info)
+
+
+def set_state_dict(
+    model: nn.Module,
+    optimizers: Union[torch.optim.Optimizer, Iterable[torch.optim.Optimizer]],
+    *,
+    model_state_dict: Dict[str, ValueType],
+    optim_state_dict: OptimizerStateType,
+    options: Optional[StateDictOptions] = None,
+) -> _IncompatibleKeys:
+    """Load the model state_dict and optimizers state_dict.
+
+    The counterpart of ``get_state_dict`` to set the state_dict to the model and
+    optimizers.  The given ``model_state_dict`` and ``optim_state_dict`` do not
+    have to be returned by ``get_state_dict`` but must meet the following
+    requirements: 1) all FQNs are canonical FQNs as defined in ``get_state_dict``,
+    2) if a tensor is sharded, it must be either a ShardedTensor or DTensor,
+    3) optimizer state_dict cannot contain the parameter IDs; the keys should be
+    the canonical FQNs.
+
+    Args:
+        model (nn.Module): the nn.Module to the model.
+        optimizers (Union[Optimizer, Iterable[Optimizer]]):
+            The optimizers that are used to optimize ``model``.
+        model_state_dict: (Union[Dict[nn.Module, Dict[str, ValueType]], Dict[str, ValueType]]):
+           the model state_dict to load. If the key of the ``model_state_dict``
+           is nn.Module, the key is a submodule of ``model`` and the value should
+           be the state_dict of the submodule. When loading the state_dict,
+           the prefix of the submodule will be append to the state_dict.
+        optim_state_dict: OptimizerStateType:
+            the optimizer state_dict to load.
+        options (StateDictOptions): the options to control how
+            model state_dict and optimizer state_dict should be loaded. See
+            `StateDictOptions` for the details.
+
+    Returns:
+        ``NamedTuple`` with ``missing_keys`` and ``unexpected_keys`` fields:
+            * **missing_keys** is a list of str containing the missing keys of the model state_dict.
+            * **unexpected_keys** is a list of str containing the unexpected keys of the model state_dict.
+
+    :type model_state_dict: typing.Dict[str, ValueType]
+    :type optim_state_dict: typing.OptimizerStateType
+    """
+
+    model_state_dict: Dict[str, ValueType] = _unflatten_model_state_dict(
+        model, model_state_dict
+    )
+    with _gc_context():
+        optimizers = (
+            (optimizers,)
+            if isinstance(optimizers, torch.optim.Optimizer)
+            else tuple(optimizers)
+        )
+        info = _verify_options(
+            model, optimizers, optim_only=not model_state_dict, options=options
+        )
+
+        _verify_state_dict(model_state_dict, optim_state_dict, info)
+        _load_optim_state_dict(model, optimizers, optim_state_dict, info)
+        return _load_model_state_dict(model, model_state_dict, info)
+
+
+# TODO: correct the state_dict function signature.
+# TODO: this API is not yet fully tested. Make it private
+@no_type_check
+def _patch_model_state_dict(
+    model: nn.Module,
+    *,
+    options: Optional[StateDictOptions] = None,
+) -> None:
+    """Patch the ``state_dict`` and ``load_state_dict`` attributes of ``model``.
+
+    Patch the ``state_dict`` and ``load_state_dict`` attributes of ``model`` to
+    be a partial function to call ``get_state_dict`` and ``set_state_dict``.
+
+    Example:
+        from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
+        from torch.distributed.checkpoint.state_dict import patch_model_state_dict
+
+        model = fsdp(model)
+        patch_model_state_dict(model)
+
+    Args:
+        model (nn.Module): the nn.Module to the model.
+        options (StateDictOptions): the options to control how
+            model state_dict and optimizer state_dict should be loaded. See
+            `StateDictOptions` for the details.
+    Returns:
+        None
+    """
+
+    _state_dict_call = functools.partial(
+        get_model_state_dict,
+        model=model,
+        options=options,
+    )
+
+    def state_dict_call():
+        return _state_dict_call()
+
+    model.state_dict = state_dict_call
+
+    _load_state_dict_call = functools.partial(
+        set_model_state_dict,
+        model=model,
+        options=options,
+    )
+
+    def load_state_dict_call(state_dict: Dict[str, Any]):
+        _load_state_dict_call(model_state_dict=state_dict)
+
+    model.load_state_dict = load_state_dict_call
+
+    _patched_state_dict.add(state_dict_call)
+    _patched_state_dict.add(load_state_dict_call)
+
+
+# TODO: correct the load_state_dict function signature.
+# TODO: this API is not yet fully tested. Make it private
+@no_type_check
+def _patch_optimizer_state_dict(
+    model: nn.Module,
+    *,
+    optimizers: Tuple[torch.optim.Optimizer, ...],
+    options: Optional[StateDictOptions] = None,
+) -> None:
+    """Patch the ``state_dict`` and ``load_state_dict`` attributes of ``optimizers``.
+
+    Patch the ``state_dict`` and ``load_state_dict`` attributes of ``optimizers`` to
+    be a partial function to call ``get_state_dict`` and ``set_state_dict``.
+
+    Note that if there are multiple optimizers, all of the optimizers will be patched.
+    So users only need to call one of the state_dict() to get the full result.
+
+    Example:
+        from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
+        from torch.distributed.checkpoint.state_dict import patch_model_state_dict
+
+        model = fsdp(model)
+        patch_model_state_dict(model)
+
+    Args:
+        model (nn.Module): the nn.Module to the model.
+        options (StateDictOptions): the options to control how
+            model state_dict and optimizer state_dict should be loaded. See
+            `StateDictOptions` for the details.
+    Returns:
+        None
+    """
+
+    _state_dict_call = functools.partial(
+        get_optimizer_state_dict,
+        model=model,
+        optimizers=optimizers,
+        options=options,
+    )
+
+    def state_dict_call():
+        return _state_dict_call()
+
+    _load_state_dict_call = functools.partial(
+        set_optimizer_state_dict,
+        model=model,
+        optimizers=optimizers,
+        options=options,
+    )
+
+    def load_state_dict_call(state_dict: Dict[str, Any]):
+        _load_state_dict_call(optim_state_dict=state_dict)
+
+    _patched_state_dict.add(state_dict_call)
+    _patched_state_dict.add(load_state_dict_call)
+    optimizers = (
+        (optimizers,)
+        if isinstance(optimizers, torch.optim.Optimizer)
+        else tuple(optimizers)
+    )
+    for optim in optimizers:
+        optim.state_dict = state_dict_call
+        optim.load_state_dict = load_state_dict_call
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/state_dict_loader.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/state_dict_loader.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d92327e9e4761c4331a80876406101b9eef4868
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/state_dict_loader.py
@@ -0,0 +1,316 @@
+# mypy: allow-untyped-decorators
+# mypy: allow-untyped-defs
+import os
+import warnings
+from typing import Any, cast, Dict, Optional, Set, Union
+from typing_extensions import deprecated
+
+import torch
+import torch.distributed as dist
+from torch.distributed.checkpoint.default_planner import _EmptyStateDictLoadPlanner
+from torch.distributed.checkpoint.logger import _dcp_method_logger
+from torch.distributed.checkpoint.stateful import Stateful
+
+from ._storage_utils import _storage_setup
+from .default_planner import DefaultLoadPlanner
+from .planner import LoadPlan, LoadPlanner
+from .storage import StorageReader
+from .utils import _all_gather_keys, _api_bc_check, _DistWrapper, _profile
+
+
+__all__ = ["load_state_dict", "load"]
+
+
+@deprecated(
+    "`load_state_dict` is deprecated and will be removed in future versions. "
+    "Please use `load` instead.",
+    category=FutureWarning,
+)
+def load_state_dict(
+    state_dict: Dict[str, Any],
+    storage_reader: StorageReader,
+    process_group: Optional[dist.ProcessGroup] = None,
+    coordinator_rank: int = 0,
+    no_dist: bool = False,
+    planner: Optional[LoadPlanner] = None,
+) -> None:
+    """This method is deprecated. Please switch to 'load'."""
+    storage_reader.reset()
+    with _profile():
+        # TODO: test returning `load` here instead.
+        return _load_state_dict(
+            state_dict,
+            storage_reader,
+            process_group,
+            coordinator_rank,
+            no_dist,
+            planner,
+        )
+
+
+@_dcp_method_logger(log_exceptions=True)
+@_api_bc_check
+def load(
+    state_dict: Dict[str, Any],
+    *,
+    checkpoint_id: Union[str, os.PathLike, None] = None,
+    storage_reader: Optional[StorageReader] = None,
+    planner: Optional[LoadPlanner] = None,
+    process_group: Optional[dist.ProcessGroup] = None,
+) -> None:
+    """
+    Load a distributed ``state_dict`` in SPMD style.
+
+    Each rank will try to read the least amount of data necessary
+    to fullfill the requested `state_dict`. When loading :class:`ShardedTensor`
+    or :class:`DTensor` instances, each rank only reads data for their local shards.
+
+    For each ``Stateful`` object (having both a ``state_dict`` and a ``load_state_dict``),
+    load will first call ``state_dict`` before attempting deserialization, followed by
+    ``load_state_dict`` once the deserialization is complete.
+
+    .. warning::
+        All tensors in ``state_dict`` must be allocated on their
+        destination device *prior to* calling this function.
+
+        All non-tensor data is loaded using `torch.load()` and modified in place
+        on state_dict.
+
+    .. warning::
+        Users must call `load_state_dict` on the root module to ensure load
+        pos-processing and non-tensor data properly propagates.
+
+    .. note:
+        If no process group is initialized, this function will assume the intent
+        is to load a checkpoint into the local process. This can be useful in the
+        case of local inference, and when using regular Tensors (as opposed to DTensor
+         or ShardedTensor)
+
+    .. note:
+        Rank 0 is assumed to be the coordinator rank.
+
+    Args:
+        state_dict (Dict[str, Any]): The state_dict to save.
+        checkpoint_id (Union[str, os.PathLike, None]):
+            The ID of this checkpoint instance. The meaning of the checkpoint_id
+            depends on the storage. It can be a path to a folder or to a file.
+            It can also be a key if the storage is a key-value store.
+            (Default: ``None``)
+        storage_reader (Optional[StorageReader]):
+            Instance of StorageWriter used to perform reads. If this is not
+            specified, DCP will automatically infer the reader based on the
+            checkpoint_id. If checkpoint_id is also None, an exception will
+            be raised. (Default: ``None``)
+        planner (Optional[LoadPlanner]):
+            Instance of LoadPlanner. If this is not specificed, the default
+            planner will be used. (Default: ``None``)
+        process_group (Optional[ProcessGroup]):
+            ProcessGroup to be used for cross-rank synchronization.
+            (Default: ``None``)
+
+    Returns:
+        None.
+
+    Examples
+        >>> # xdoctest: +SKIP
+        >>> my_model = MyModule()
+        >>> optimizer = Adagrad(my_model.parameters())
+        >>> model_state_dict = my_model.state_dict()
+        >>> fs_storage_reader = torch.distributed.checkpoint.FileSystemReader("/checkpoint/1")
+
+        >>> torch.distributed.checkpoint.load_state_dict(
+        >>>     state_dict=model_state_dict,
+        >>>     storage_reader=fs_storage_reader,
+        >>> )
+
+        >>> # module.load_state_dict() function might have customized steps
+        >>> # to flush the state_dict, must call it to
+        >>> # ensure correct behavior.
+        >>> my_model.load_state_dict(model_state_dict)
+
+    .. note::
+        load_state_dict uses collectives to coordinate reads across ranks.
+        For NCCL-based process groups, internal tensor representations of
+        objects must be moved to the GPU device before communication takes place.
+        In this case, the device used is given by ``torch.cuda.current_device()``
+        and it is the user's responsibility to ensure that this is set so that each
+        rank has an individual GPU, via ``torch.cuda.set_device()``.
+    """
+
+    no_dist = not (dist.is_available() and dist.is_initialized())
+    if no_dist:
+        warnings.warn(
+            "torch.distributed is unavailable or uninitialized, assuming the intent is to load in a single process."
+        )
+
+    with _profile():
+        storage_reader = cast(
+            StorageReader, _storage_setup(storage_reader, checkpoint_id, reader=True)
+        )
+
+        if no_dist:
+            keys = list(state_dict.keys())
+        else:
+            keys = _all_gather_keys(state_dict, process_group)
+            if keys != sorted(state_dict.keys()):
+                warnings.warn(
+                    "Detected mismatched keys in state dict after all gather!"
+                    " This behavior is unsupported and may cause errors may cause errors."
+                )
+
+        statetful_sd = {}
+        for key in keys:
+            if key not in state_dict:
+                continue
+            elem = state_dict[key]
+            statetful_sd[key] = (
+                elem.state_dict() if isinstance(elem, Stateful) else elem
+            )
+
+        _load_state_dict(
+            state_dict=statetful_sd,
+            storage_reader=storage_reader,
+            process_group=process_group,
+            no_dist=no_dist,
+            planner=planner,
+        )
+        for key in keys:
+            if key not in state_dict:
+                continue
+            elem = state_dict[key]
+            if isinstance(elem, Stateful):
+                elem.load_state_dict(statetful_sd[key])
+            state_dict[key] = statetful_sd[key]
+
+
+def _load_state_dict(
+    state_dict: Dict[str, Any],
+    storage_reader: StorageReader,
+    process_group: Optional[dist.ProcessGroup] = None,
+    coordinator_rank: int = 0,
+    no_dist: bool = False,
+    planner: Optional[LoadPlanner] = None,
+) -> None:
+    torch._C._log_api_usage_once("torch.distributed.checkpoint.load_state_dict")
+
+    distW = _DistWrapper(process_group, not no_dist, coordinator_rank)
+    if planner is None:
+        planner = DefaultLoadPlanner()
+
+    ckpt_kwargs = {}
+    if (ckpt_id := getattr(storage_reader, "checkpoint_id", None)) is not None:
+        ckpt_kwargs["checkpoint_id"] = ckpt_id
+
+    @_dcp_method_logger(**ckpt_kwargs)
+    def local_step():
+        assert planner is not None
+        metadata = storage_reader.read_metadata()
+        planner.set_up_planner(state_dict, metadata, distW.is_coordinator)
+        storage_reader.set_up_storage_reader(metadata, distW.is_coordinator)
+
+        local_plan = planner.create_local_plan()
+        local_plan = storage_reader.prepare_local_plan(local_plan)
+        return local_plan
+
+    @_dcp_method_logger(**ckpt_kwargs)
+    def global_step(all_local_plans):
+        assert planner is not None
+        all_local_plans = planner.create_global_plan(all_local_plans)
+        all_local_plans = storage_reader.prepare_global_plan(all_local_plans)
+        return all_local_plans
+
+    central_plan: LoadPlan = distW.reduce_scatter("plan", local_step, global_step)
+
+    @_dcp_method_logger(**ckpt_kwargs)
+    def read_data():
+        assert planner is not None
+        final_local_plan = planner.finish_plan(central_plan)
+        all_reads = storage_reader.read_data(final_local_plan, planner)
+
+        all_reads.wait()
+        return None
+
+    _ = distW.all_gather("read", read_data)
+
+
+def _load_state_dict_from_keys(
+    keys: Optional[Union[Set[str], str]] = None,
+    *,
+    checkpoint_id: Union[str, os.PathLike, None] = None,
+    storage_reader: Optional[StorageReader] = None,
+    process_group: Optional[dist.ProcessGroup] = None,
+) -> Dict[str, Any]:
+    """
+    Load only the specified keys from the checkpoint, if no keys are specified, the entire
+    checkpoint will be loaded. Note, this method completely loads the checkpoint into the
+    current process and is not distributed.
+
+    .. warning::
+
+
+    .. warning::
+
+        All non-tensor data is loaded using `torch.load()`
+
+    .. note:
+        As opposed to the usual pattern, this function does not take a state dict as input
+        and does not load inplace. Instead, a new state dict is directly initialized and read
+        from file.
+
+    .. note:
+        If no process group is initialized, this function will assume the intent
+        is to load a checkpoint into the local process. This can be useful in the
+        case of local inference, and when using regular Tensors (as opposed to DTensor
+         or ShardedTensor)
+
+    .. note:
+        Rank 0 is assumed to be the coordinator rank.
+
+    Args:
+        keys (Optional[Union[Set[str], str]]):
+            Loads any key specified in this set. If no keys are specified, the entire checkpoint
+            is loaded.
+        checkpoint_id (Union[str, os.PathLike, None]):
+            The ID of this checkpoint instance. The meaning of the checkpoint_id
+            depends on the storage. It can be a path to a folder or to a file.
+            It can also be a key if the storage is a key-value store.
+            (Default: ``None``)
+        storage_reader (Optional[StorageReader]):
+            Instance of StorageWriter used to perform reads. If this is not
+            specified, DCP will automatically infer the reader based on the
+            checkpoint_id. If checkpoint_id is also None, an exception will
+            be raised. (Default: ``None``)
+        process_group (Optional[ProcessGroup]):
+            ProcessGroup to be used for cross-rank synchronization.
+            (Default: ``None``)
+
+    Returns:
+        State dict from specified keys
+    """
+    torch._C._log_api_usage_once(
+        "torch.distributed.checkpoint._load_state_dict_from_keys"
+    )
+
+    no_dist = not (dist.is_available() and dist.is_initialized())
+    if no_dist:
+        warnings.warn(
+            "torch.distributed is unavailable or uninitialized, assuming the intent is to load in a single process."
+        )
+
+    storage_reader = cast(
+        StorageReader, _storage_setup(storage_reader, checkpoint_id, reader=True)
+    )
+
+    if isinstance(keys, str):
+        keys = {keys}
+
+    sd: Dict[str, Any] = {}
+    _load_state_dict(
+        state_dict=sd,
+        storage_reader=storage_reader,
+        process_group=process_group,
+        no_dist=no_dist,
+        planner=_EmptyStateDictLoadPlanner(keys=keys or set()),
+    )
+
+    return sd
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/state_dict_saver.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/state_dict_saver.py
new file mode 100644
index 0000000000000000000000000000000000000000..307c6d8d4a96052372d6627695709ffbbef47f06
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/state_dict_saver.py
@@ -0,0 +1,333 @@
+# mypy: allow-untyped-decorators
+# mypy: allow-untyped-defs
+import inspect
+import os
+import warnings
+from concurrent.futures import Future, ThreadPoolExecutor
+from typing import cast, Optional, Union
+from typing_extensions import deprecated
+
+import torch
+import torch.distributed as dist
+from torch.distributed._state_dict_utils import _offload_state_dict_to_cpu
+from torch.distributed.checkpoint._storage_utils import _storage_setup
+from torch.distributed.checkpoint.default_planner import DefaultSavePlanner
+from torch.distributed.checkpoint.logger import _dcp_method_logger
+from torch.distributed.checkpoint.metadata import Metadata, STATE_DICT_TYPE
+from torch.distributed.checkpoint.planner import SavePlan, SavePlanner
+from torch.distributed.checkpoint.staging import AsyncStager
+from torch.distributed.checkpoint.stateful import Stateful
+from torch.distributed.checkpoint.storage import StorageWriter
+from torch.distributed.distributed_c10d import _get_default_group
+
+from .utils import _api_bc_check, _DistWrapper, _profile
+
+
+__all__ = ["save_state_dict", "save", "async_save"]
+
+
+@deprecated(
+    "`save_state_dict` is deprecated and will be removed in future versions."
+    "Please use `save` instead.",
+    category=FutureWarning,
+)
+def save_state_dict(
+    state_dict: STATE_DICT_TYPE,
+    storage_writer: StorageWriter,
+    process_group: Optional[dist.ProcessGroup] = None,
+    coordinator_rank: int = 0,
+    no_dist: bool = False,
+    planner: Optional[SavePlanner] = None,
+) -> Metadata:
+    """This method is deprecated. Please switch to 'save'."""
+    storage_writer.reset()
+
+    # TODO: test returning `save` here instead.
+    with _profile():
+        return _save_state_dict(
+            state_dict,
+            storage_writer,
+            process_group,
+            coordinator_rank,
+            no_dist,
+            planner,
+        )
+
+
+@_dcp_method_logger(log_exceptions=True)  # type: ignore[arg-type]
+@_api_bc_check
+def save(
+    state_dict: STATE_DICT_TYPE,
+    *,
+    checkpoint_id: Union[str, os.PathLike, None] = None,
+    storage_writer: Optional[StorageWriter] = None,
+    planner: Optional[SavePlanner] = None,
+    process_group: Optional[dist.ProcessGroup] = None,
+) -> Metadata:
+    """
+    Save a distributed model in SPMD style.
+
+    This function is different from ``torch.save()`` as it handles
+    ``ShardedTensor`` , and ``DTensor`` by having each rank only save their local shards.
+
+    For each ``Stateful`` object (having both a ``state_dict`` and a ``load_state_dict``),
+    save will call ``state_dict`` before serialization.
+
+    .. warning::
+        There is no guarantees of Backwards Compatibility across PyTorch versions
+        for saved state_dicts.
+
+    .. warning::
+        If using the `process_group` argument, make sure that only its ranks
+        call `save_state_dict` and that all data in state_dict belong to it.
+
+    .. note::
+        When saving checkpoint for FSDP's `ShardingStrategy.HYBRID_SHARD`, only one of
+        the shard_group should be calling `save_state_dict` and the corresponding process
+        group needs to be passed in.
+
+    .. note::
+        If no process group is available, this function assumes the intention is to save the
+         state_dict in the local process.
+
+    .. note:
+        Rank 0 is assumed to be the coordinator rank.
+
+
+    Args:
+        state_dict (Dict[str, Any]): The state_dict to save.
+        checkpoint_id (Union[str, os.PathLike, None]):
+            The ID of this checkpoint instance. The meaning of the checkpoint_id
+            depends on the storage. It can be a path to a folder or to a file.
+            It can also be a key if the storage is a key-value store.
+            (Default: ``None``)
+        storage_writer (Optional[StorageWriter]):
+            Instance of StorageWriter used to perform writes. If this is not
+            specified, DCP will automatically infer the writer based on the
+            checkpoint_id. If checkpoint_id is also None, an exception will
+            be raised. (Default: ``None``)
+        planner (Optional[SavePlanner]):
+            Instance of SavePlanner. If this is not specificed, the default
+            planner will be used. (Default: ``None``)
+        process_group (Optional[ProcessGroup]):
+            ProcessGroup to be used for cross-rank synchronization.
+            (Default: ``None``)
+
+    Returns:
+        Metadata: Metadata object for the saved checkpoint.
+
+    Example:
+        >>> # xdoctest: +SKIP
+        >>> my_model = MyModule()
+
+        >>> state_dict = {"model": my_model}
+
+        >>> fs_storage_writer = torch.distributed.checkpoint.FileSystemWriter("/checkpoint/1")
+        >>> torch.distributed.checkpoint.save(
+        >>>     state_dict=state_dict,
+        >>>     storage_writer=fs_storage_writer,
+        >>> )
+
+    .. note::
+        save_state_dict uses collectives to coordinate writes across ranks.
+        For NCCL-based process groups, internal tensor representations of
+        objects must be moved to the GPU device before communication takes place.
+        In this case, the device used is given by ``torch.cuda.current_device()``
+        and it is the user's responsibility to ensure that this is set so that
+        each rank has an individual GPU, via ``torch.cuda.set_device()``.
+    """
+    torch._C._log_api_usage_once("torch.distributed.checkpoint.save")
+
+    no_dist = not (dist.is_available() and dist.is_initialized())
+    if no_dist:
+        warnings.warn(
+            "torch.distributed is unavailable or uninitialized, assuming the intent is to save in a single process."
+        )
+
+    with _profile():
+        storage_writer = cast(
+            StorageWriter, _storage_setup(storage_writer, checkpoint_id, reader=False)
+        )
+
+        return _save_state_dict(
+            state_dict=_stateful_to_state_dict(state_dict),
+            storage_writer=storage_writer,
+            process_group=process_group,
+            no_dist=no_dist,
+            planner=planner,
+        )
+
+
+@_dcp_method_logger(log_exceptions=True)
+def async_save(
+    state_dict: STATE_DICT_TYPE,
+    *,
+    checkpoint_id: Union[str, os.PathLike, None] = None,
+    storage_writer: Optional[StorageWriter] = None,
+    planner: Optional[SavePlanner] = None,
+    process_group: Optional[dist.ProcessGroup] = None,
+) -> Future:
+    """Asynchronous version of ``save``. This code first de-stages the state_dict on to the
+    staging storage (defaults to CPU memory), and then calls the `save` in a separate thread.
+
+    .. warning::
+        This feature is experimental and subject to change.
+
+    Args:
+        state_dict (Dict[str, Any]): The state_dict to save.
+        checkpoint_id (Union[str, os.PathLike, None]):
+            The ID of this checkpoint instance. The meaning of the checkpoint_id
+            depends on the storage. It can be a path to a folder or to a file.
+            It can also be a key if the storage is a key-value store.
+            (Default: ``None``)
+        storage_writer (Optional[StorageWriter]):
+            Instance of StorageWriter used to perform 'stage' and  'save'. If
+            this is not specified, DCP will automatically infer the writer based on the
+            checkpoint_id. If checkpoint_id is also None, an exception will
+            be raised. (Default: ``None``)
+        planner (Optional[SavePlanner]):
+            Instance of SavePlanner. If this is not specificed, the default
+            planner will be used. (Default: ``None``)
+        process_group (Optional[ProcessGroup]):
+            ProcessGroup to be used for cross-rank synchronization.
+            (Default: ``None``)
+
+    Returns:
+        Future: A future holding the resultant Metadata object from `save`.
+
+    Example:
+        >>> # xdoctest: +SKIP
+        >>> my_model = MyModule()
+
+        >>> state_dict = {"model": my_model}
+
+        >>> fs_storage_writer = torch.distributed.checkpoint.FileSystemWriter("/checkpoint/1")
+        >>> checkpoint_future = torch.distributed.checkpoint.async_save(
+        >>>     state_dict=state_dict,
+        >>>     storage_writer=fs_storage_writer,
+        >>> )
+        >>>
+        >>> # ... do some work ...
+        >>>
+        >>> checkpoint_future.result()
+
+    """
+    torch._C._log_api_usage_once("torch.distributed.checkpoint.async_save")
+
+    if dist.is_available() and dist.is_initialized():
+        pg = process_group or _get_default_group()
+        assert (
+            torch.device("cpu") in pg._device_types  # type: ignore[attr-defined]
+        ), "A CPU backend must be enabled for async save; try initializing process group with 'cpu:gloo,cuda:nccl'"
+
+    storage_writer = cast(
+        StorageWriter, _storage_setup(storage_writer, checkpoint_id, reader=False)
+    )
+
+    state_dict = _stateful_to_state_dict(state_dict)
+    if isinstance(storage_writer, AsyncStager):
+        staged_state_dict = storage_writer.stage(state_dict)
+    else:  # provides bwc for storage_writers not implementing AsyncStager
+        staged_state_dict = _offload_state_dict_to_cpu(state_dict, type_check=False)
+
+    executor = ThreadPoolExecutor(max_workers=1)
+    f: Future = executor.submit(
+        save,
+        staged_state_dict,
+        checkpoint_id=checkpoint_id,
+        storage_writer=storage_writer,
+        planner=planner,
+        process_group=process_group,
+    )
+    f.add_done_callback(lambda f: executor.shutdown(wait=False))
+
+    if (
+        isinstance(storage_writer, AsyncStager)
+        and storage_writer.should_synchronize_after_execute
+    ):
+        storage_writer.synchronize_staging()
+
+    return f
+
+
+def _stateful_to_state_dict(state_dict: STATE_DICT_TYPE) -> STATE_DICT_TYPE:
+    """Creates a shallow copy of `state_dict` where `state_dict` is called for each Stateful object."""
+    stateful_state_dict = {}
+    for key, elem in state_dict.items():
+        stateful_state_dict[key] = (
+            elem.state_dict() if isinstance(elem, Stateful) else elem
+        )
+    return stateful_state_dict
+
+
+def _save_state_dict(
+    state_dict: STATE_DICT_TYPE,
+    storage_writer: StorageWriter,
+    process_group: Optional[dist.ProcessGroup] = None,
+    coordinator_rank: int = 0,
+    no_dist: bool = False,
+    planner: Optional[SavePlanner] = None,
+) -> Metadata:
+    torch._C._log_api_usage_once("torch.distributed.checkpoint.save_state_dict")
+
+    distW = _DistWrapper(process_group, not no_dist, coordinator_rank)
+    if planner is None:
+        planner = DefaultSavePlanner()
+    assert planner is not None
+
+    global_metadata = None
+
+    ckpt_kwargs = {}
+    if (ckpt_id := getattr(storage_writer, "checkpoint_id", None)) is not None:
+        ckpt_kwargs["checkpoint_id"] = ckpt_id
+
+    @_dcp_method_logger(**ckpt_kwargs)
+    def local_step():
+        assert planner is not None
+        storage_meta = storage_writer.storage_meta()
+        if "storage_meta" not in inspect.signature(planner.set_up_planner).parameters:
+            warnings.warn(
+                "The function definition for SavePlanner.set_up_planner has been updated"
+                " to include the storage_meta argument. Please update your implementation"
+                " to include this parameter."
+            )
+            planner.set_up_planner(state_dict, distW.is_coordinator)  # type: ignore[call-arg, arg-type]
+        else:
+            planner.set_up_planner(
+                state_dict=state_dict,
+                storage_meta=storage_meta,
+                is_coordinator=distW.is_coordinator,
+            )
+        storage_writer.set_up_storage_writer(distW.is_coordinator)
+
+        local_plan = planner.create_local_plan()
+        local_plan = storage_writer.prepare_local_plan(local_plan)
+        return local_plan
+
+    @_dcp_method_logger(**ckpt_kwargs)
+    def global_step(all_local_plans):
+        nonlocal global_metadata
+
+        assert planner is not None
+        all_local_plans, global_metadata = planner.create_global_plan(all_local_plans)
+        all_local_plans = storage_writer.prepare_global_plan(all_local_plans)
+        return all_local_plans
+
+    central_plan: SavePlan = distW.reduce_scatter("plan", local_step, global_step)
+
+    @_dcp_method_logger(**ckpt_kwargs)
+    def write_data():
+        assert planner is not None
+        final_local_plan = planner.finish_plan(central_plan)
+        all_writes = storage_writer.write_data(final_local_plan, planner)
+
+        all_writes.wait()
+        return all_writes.value()
+
+    @_dcp_method_logger(**ckpt_kwargs)
+    def finish_checkpoint(all_results):
+        assert global_metadata is not None
+        storage_writer.finish(metadata=global_metadata, results=all_results)
+        return global_metadata
+
+    return distW.all_reduce("write", write_data, finish_checkpoint)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/stateful.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/stateful.py
new file mode 100644
index 0000000000000000000000000000000000000000..97d83ddbdf15d564b4724f59fdd97ac3368de0b1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/stateful.py
@@ -0,0 +1,42 @@
+from typing import Any, Dict, runtime_checkable, TypeVar
+from typing_extensions import Protocol
+
+
+__all__ = ["Stateful", "StatefulT"]
+
+
+@runtime_checkable
+class Stateful(Protocol):
+    """
+    Stateful protocol for objects that can be checkpointed and restored.
+    """
+
+    def state_dict(self) -> Dict[str, Any]:
+        """
+        Objects should return their state_dict representation as a dictionary.
+        The output of this function will be checkpointed, and later restored in
+        `load_state_dict()`.
+
+        .. warning::
+            Because of the inplace nature of restoring a checkpoint, this function
+            is also called during `torch.distributed.checkpoint.load`.
+
+
+        Returns:
+            Dict: The objects state dict
+        """
+
+        ...
+
+    def load_state_dict(self, state_dict: Dict[str, Any]) -> None:
+        """
+        Restore the object's state from the provided state_dict.
+
+        Args:
+            state_dict: The state dict to restore from
+        """
+
+        ...
+
+
+StatefulT = TypeVar("StatefulT", bound=Stateful)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/storage.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/storage.py
new file mode 100644
index 0000000000000000000000000000000000000000..985e91df9e739d1033725ce6173e35ea25296907
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/storage.py
@@ -0,0 +1,284 @@
+import abc
+import os
+from dataclasses import dataclass
+from typing import Any, List, Optional, Union
+
+from torch.distributed.checkpoint.metadata import Metadata, MetadataIndex, StorageMeta
+from torch.distributed.checkpoint.planner import (
+    LoadPlan,
+    LoadPlanner,
+    SavePlan,
+    SavePlanner,
+)
+from torch.futures import Future
+
+
+__all__ = ["WriteResult", "StorageWriter", "StorageReader"]
+
+
+@dataclass(frozen=True)
+class WriteResult:
+    index: MetadataIndex
+
+    size_in_bytes: int
+    storage_data: Any
+
+
+class StorageWriter(abc.ABC):
+    """
+    Interface used by ``save_state_dict`` to write to storage.
+
+    One StorageWriter instance acts as both the coordinator and the follower
+    in a distributed checkpoint. As part of initialization, each instance
+    is told its role.
+
+    A subclass should expect the following sequence of calls.
+
+    0) (all ranks) set checkpoint_id if users pass a valid checkpoint_id.
+    1) (all ranks) set_up_storage_writer()
+    2) (all ranks) prepare_local_plan()
+    3) (coordinator) prepare_global_plan()
+    4) (all ranks) write_data()
+    5) (coordinator) finish()
+    """
+
+    @abc.abstractmethod
+    def reset(self, checkpoint_id: Union[str, os.PathLike, None] = None) -> None:
+        """
+        Calls to indicates a brand new checkpoint write is going to happen.
+        A checkpoint_id may be present if users set the checkpoint_id for
+        this checkpoint write. The meaning of the checkpiont_id is
+        storage-dependent. It can be a path to a folder/file or a key for
+        a key-value storage.
+
+        Args:
+            checkpoint_id (Union[str, os.PathLike, None]):
+                The ID of this checkpoint instance. The meaning of the checkpoint_id
+                depends on the storage. It can be a path to a folder or to a file.
+                It can also be a key if the storage is a key-value store.
+                (Default: ``None``)
+        """
+        ...
+
+    @abc.abstractmethod
+    def set_up_storage_writer(self, is_coordinator: bool) -> None:
+        """
+        Initialize this instance.
+
+        Args:
+            is_coordinator (bool): Whether this instance is responsible for coordinating
+              the checkpoint.
+        """
+
+    @abc.abstractmethod
+    def prepare_local_plan(self, plan: SavePlan) -> SavePlan:
+        """
+        Perform storage-specific local planning.
+
+        While this method can produce a completely different plan, the recommended
+        way is to store storage specific data in SavePlan::storage_data.
+
+        Args:
+            plan (SavePlan): The local plan from the ``SavePlanner`` in use.
+
+        Returns:
+            A transformed ``SavePlan`` after storage local planning
+        """
+
+    @abc.abstractmethod
+    def prepare_global_plan(self, plans: List[SavePlan]) -> List[SavePlan]:
+        """
+        Perform centralized planning of storage.
+
+        This method is only called on the coordinator instance.
+
+        While this method can produce a completely different plan, the preferred
+        way is to store storage specific data in SavePlan::storage_data.
+
+        Args:
+            plans: A list of ``SavePlan`` instances, one for each rank.
+
+        Returns:
+            A list of transformed ``SavePlan`` after storage global planning
+        """
+
+    @abc.abstractmethod
+    def write_data(
+        self, plan: SavePlan, planner: SavePlanner
+    ) -> Future[List[WriteResult]]:
+        """
+        Write all items from ``plan`` using ``planner`` to resolve the data.
+
+        A subclass should call ``SavePlanner::resolve_data`` on each item
+        from the plan to get access to the underlying object to write.
+
+        Subclasses should lazily call `resolve_data` as it can allocate memory.
+        In case of tensors, make following assumptions:
+
+        - They might be on any device, including not matching the one on ``WriteItem::tensor_data``
+        - They might be views or not contiguous. Only the projection needs to be saved.
+
+        Args:
+            plan (SavePlan): The save plan to execute.
+            planner (SavePlanner): Planner object to be used to resolve items to data.
+
+        Returns:
+            A future that completes to a list of WriteResult
+        """
+
+    @abc.abstractmethod
+    def finish(self, metadata: Metadata, results: List[List[WriteResult]]) -> None:
+        """
+        Write the metadata and marks the current checkpoint as successful.
+
+        The actual format/schema used for serializing `metadata` is an
+        implementation detail. The only requirement is that it's recoverable
+        in to the same object graph.
+
+        Args:
+            metadata (Metadata): metadata for the new checkpoint
+            results: A list of WriteResults from all ranks.
+
+        Returns:
+            None
+        """
+
+    @classmethod
+    @abc.abstractmethod
+    def validate_checkpoint_id(cls, checkpoint_id: Union[str, os.PathLike]) -> bool:
+        """
+        Check if the given checkpoint_id is supported by the stroage. This allow
+        us to enable automatic storage selection.
+        """
+        ...
+
+    def storage_meta(self) -> Optional[StorageMeta]:
+        """
+        Return the storage-specific metadata. This is used to store additional information
+        in a checkpoint that can be useful for providing request-level observability. StorageMeta
+        is passed to the ``SavePlanner`` during save calls. Returns None by default.
+
+        TODO: provide an example
+        """
+        return None
+
+
+class StorageReader(abc.ABC):
+    """
+    Interface used by ``load_state_dict`` to read from storage.
+
+    One StorageReader instance acts as both the coordinator and the follower
+    in a distributed checkpoint. As part of initialization, each instance
+    is told its role.
+
+    A subclass should expected the following sequence of calls by ``load_state_dict``:
+
+    0) (all ranks) set checkpoint_id if users pass a valid checkpoint_id.
+    1) (all ranks) read_metadata()
+    2) (all ranks) set_up_storage_reader()
+    3) (all ranks) prepare_local_plan()
+    4) (coordinator) prepare_global_plan()
+    5) (all ranks) read_data()
+    """
+
+    @abc.abstractmethod
+    def reset(self, checkpoint_id: Union[str, os.PathLike, None] = None) -> None:
+        """
+        Calls to indicates a brand new checkpoint read is going to happen.
+        A checkpoint_id may be present if users set the checkpoint_id for
+        this checkpoint read. The meaning of the checkpiont_id is
+        storage-dependent. It can be a path to a folder/file or a key for
+        a key-value storage.
+
+        Args:
+            checkpoint_id (Union[str, os.PathLike, None]):
+                The ID of this checkpoint instance. The meaning of the checkpoint_id
+                depends on the storage. It can be a path to a folder or to a file.
+                It can also be a key if the storage is more like a key-value store.
+                (Default: ``None``)
+        """
+        ...
+
+    @abc.abstractmethod
+    def read_metadata(self) -> Metadata:
+        """
+        Read the checkpoint metadata.
+
+        Returns:
+            The metadata object associated with the checkpoint being loaded.
+
+        """
+
+    @abc.abstractmethod
+    def set_up_storage_reader(self, metadata: Metadata, is_coordinator: bool) -> None:
+        """
+        Initialize this instance.
+
+        Args:
+            metadata (Metadata): The metadata schema to use.
+            is_coordinator (bool): Whether this instance is responsible for coordinating
+              the checkpoint.
+        """
+
+    @abc.abstractmethod
+    def prepare_local_plan(self, plan: LoadPlan) -> LoadPlan:
+        """
+        Perform storage-specific local planning.
+
+        While this method can produce a completely different plan, the recommended
+        way is to store storage specific data in LoadPlan::storage_data.
+
+        Args:
+            plan (LoadPlan): The local plan from the ``LoadPlan`` in use.
+
+        Returns:
+            A transformed ``LoadPlan`` after storage local planning
+        """
+
+    @abc.abstractmethod
+    def prepare_global_plan(self, plans: List[LoadPlan]) -> List[LoadPlan]:
+        """
+        Perform centralized planning of storage loading.
+
+        This method is only called on the coordinator instance.
+
+        While this method can produce a completely different plan, the preferred
+        way is to store storage specific data in LoadPlan::storage_data.
+
+        Args:
+            plans: A list of ``LoadPlan`` instances, one for each rank.
+
+        Returns:
+            A list of transformed ``LoadPlan`` after storage global planning
+        """
+
+    @abc.abstractmethod
+    def read_data(self, plan: LoadPlan, planner: LoadPlanner) -> Future[None]:
+        """
+        Read all items from ``plan`` using ``planner`` to resolve the data.
+
+        A subclass should call ``LoadPlanner::load_bytes`` to deserialize a BytesIO
+        object into the right place.
+
+        A subclass should call ``LoadPlanner::resolve_tensor`` to get access to the
+        tensors that in should load data into.
+
+        It's the StorageLayer responsibility to properly schedule any cross device copies
+        required.
+
+        Args:
+            plan (LoadPlan): The local plan to execute on
+            planner (LoadPlanner): The planner object to use to resolve items.
+
+        Returns:
+            A future that completes once all reads are finished.
+        """
+
+    @classmethod
+    @abc.abstractmethod
+    def validate_checkpoint_id(cls, checkpoint_id: Union[str, os.PathLike]) -> bool:
+        """
+        Check if the given checkpoint_id is supported by the stroage. This allow
+        us to enable automatic storage selection.
+        """
+        ...
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb90dd119121593f5df5bf355f30df98361f5764
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/checkpoint/utils.py
@@ -0,0 +1,431 @@
+# mypy: allow-untyped-defs
+import cProfile
+import inspect
+import io
+import itertools
+import os
+import warnings
+from contextlib import contextmanager
+from functools import wraps
+from pstats import Stats
+from typing import Any, Callable, cast, Dict, List, Optional, Sequence, TypeVar, Union
+
+import torch
+import torch.distributed as dist
+from torch.distributed._shard.sharded_tensor import ShardedTensor
+from torch.distributed._shard.sharded_tensor.shard import Shard
+
+from .api import (
+    _is_wrapped_exception,
+    _wrap_exception,
+    CheckpointException,
+    WRAPPED_EXCEPTION,
+)
+from .metadata import MetadataIndex, STATE_DICT_TYPE
+
+
+__all__ = ["find_tensor_shard", "find_state_dict_object"]
+
+T = TypeVar("T")
+R = TypeVar("R")
+
+
+def _get_failure_dict(
+    results: List[Union[T, WRAPPED_EXCEPTION]]
+) -> Dict[int, WRAPPED_EXCEPTION]:
+    return cast(
+        Dict[int, WRAPPED_EXCEPTION],
+        {i: err for i, err in enumerate(results) if _is_wrapped_exception(err)},
+    )
+
+
+def _all_gather_keys(
+    local_dict: Dict[Any, Any], group: Optional[dist.ProcessGroup] = None
+) -> List[Any]:
+    """Gathers all keys, and returns them sorted."""
+    keys = list(local_dict.keys())
+    gathered_keys: List[List[Any]] = [None] * dist.get_world_size(group)  # type: ignore[list-item]
+
+    dist.all_gather_object(gathered_keys, keys, group=group)
+    return sorted(set(itertools.chain.from_iterable(gathered_keys)))
+
+
+class _DistWrapper:
+    """
+    This is a wrapper around PG that provides a series of features around object collectives.
+
+    It works without distributed initialized, where most collectives turns into nops.
+
+    All variants that take functions are exception robust, meaning that if one or more
+    ranks raise errors, all ranks will observe those.
+    """
+
+    def __init__(
+        self,
+        group: Optional[dist.ProcessGroup],
+        use_dist: bool,
+        coordinator_rank: int,
+    ):
+        self.group = group
+        self.use_dist = use_dist
+        self.coordinator_rank = coordinator_rank
+        if self.use_dist:
+            self.rank = dist.get_rank(group)
+            self.is_coordinator = self.rank == coordinator_rank
+        else:
+            self.rank = 0
+            self.is_coordinator = True
+
+    def get_rank(self) -> int:
+        return self.rank
+
+    def get_world_size(self) -> int:
+        if self.use_dist:
+            return dist.get_world_size(self.group)
+        return 1
+
+    def broadcast_object(self, object: Optional[T]) -> T:
+        """Implement functionality similar to c10d::broadcast_object_list but without distributed enabled."""
+        object_list = [object]
+        if self.use_dist:
+            dist.broadcast_object_list(
+                object_list=object_list,
+                group=self.group,
+                src=self.coordinator_rank,
+            )
+        return cast(T, object_list[0])
+
+    def gather_object(self, object: T) -> Optional[List[T]]:
+        """Implement functionality similar to c10d::gather_object but without distributed enabled."""
+        if self.use_dist:
+            gather_objs = (
+                cast(List[T], [None] * dist.get_world_size(self.group))
+                if self.is_coordinator
+                else None
+            )
+
+            dist.gather_object(
+                obj=object,
+                object_gather_list=gather_objs if self.is_coordinator else None,
+                dst=self.coordinator_rank,
+                group=self.group,
+            )
+            result = gather_objs
+        else:
+            result = [object]
+        return result
+
+    def all_gather_object(self, object: T) -> List[T]:
+        """Implement functionality similar to c10d::all_gather_object but without distributed enabled."""
+        if self.use_dist:
+            gather_objs = cast(List[T], [None] * dist.get_world_size(self.group))
+
+            dist.all_gather_object(
+                object_list=gather_objs, obj=object, group=self.group
+            )
+        else:
+            gather_objs = [object]
+        return gather_objs
+
+    def scatter_object(self, object_list: Optional[List[T]]) -> T:
+        """Implement functionality similar to c10d::scatter_object but without distributed enabled."""
+        if self.use_dist:
+            gather_result = cast(List[T], [None])
+            dist.scatter_object_list(
+                scatter_object_output_list=gather_result,
+                scatter_object_input_list=object_list if self.is_coordinator else None,
+                src=self.coordinator_rank,
+                group=self.group,
+            )
+
+            local_reply = gather_result[0]
+        else:
+            assert object_list is not None
+            local_reply = object_list[0]
+        return local_reply
+
+    def reduce_scatter(
+        self,
+        step: str,
+        map_fun: Callable[[], T],
+        reduce_fun: Callable[[List[T]], List[R]],
+    ) -> R:
+        """
+        Compute a value on each rank, then do centralized reduce on a single rank, followed by a scatter.
+
+        This method operates in the following way:
+            Run ``map_fun`` on all ranks
+            Gather results on rank 0
+            Call ``reduce_fun`` on all those values
+            Scatter to each rank part of the result.
+        """
+        local_data: Union[WRAPPED_EXCEPTION, T]
+        try:
+            local_data = map_fun()
+        except BaseException as e:
+            local_data = _wrap_exception(e)
+
+        all_data = self.gather_object(local_data)
+        all_results: Optional[List[Union[R, CheckpointException]]] = None
+        if self.is_coordinator:
+            assert all_data is not None
+            node_failures = _get_failure_dict(all_data)
+
+            if len(node_failures) == 0:
+                try:
+                    # N.B. why can't mypy cast List[R] to List[Union[R, WRAPPED_EXCEPTION]]?
+                    all_results = cast(
+                        List[Union[R, CheckpointException]],
+                        reduce_fun(cast(List[T], all_data)),
+                    )
+                except BaseException as e:
+                    node_failures[self.rank] = _wrap_exception(e)
+
+            if len(node_failures) > 0:
+                all_results = [
+                    CheckpointException(step, node_failures)
+                ] * self.get_world_size()
+
+        result = self.scatter_object(all_results)
+        if isinstance(result, CheckpointException):
+            raise result
+        return result
+
+    def all_reduce(
+        self,
+        step: str,
+        map_fun: Callable[[], T],
+        reduce_fun: Callable[[List[T]], R],
+    ) -> R:
+        """
+        Compute a value on each rank, then do centralized reduce on a single rank, followed by a broadcast.
+
+        This method operates in the following way:
+            Run ``map_fun`` on all ranks
+            Gather results on rank 0
+            Call ``reduce_fun`` on all those values
+            Broadcast the reduced value to all ranks.
+        """
+        local_data: Union[T, WRAPPED_EXCEPTION]
+        try:
+            local_data = map_fun()
+        except BaseException as e:
+            local_data = _wrap_exception(e)
+
+        all_data = self.gather_object(local_data)
+        result: Optional[Union[R, CheckpointException]] = None
+        if self.is_coordinator:
+            assert all_data is not None
+            node_failures = _get_failure_dict(all_data)
+            if len(node_failures) == 0:
+                try:
+                    result = reduce_fun(cast(List[T], all_data))
+                except BaseException as e:
+                    node_failures[self.rank] = _wrap_exception(e)
+
+            if len(node_failures) > 0:
+                result = CheckpointException(step, node_failures)
+
+        final_result = self.broadcast_object(result)
+        if isinstance(final_result, CheckpointException):
+            raise final_result
+        return cast(R, final_result)
+
+    def all_gather(
+        self,
+        step: str,
+        map_fun: Callable[[], T],
+    ) -> List[T]:
+        """
+        Compute a value on each rank, then all_gather them.
+
+        This method operates in the following way:
+            Run ``map_cp`` on all ranks
+            all_gather the values to all ranks
+        """
+        result: Union[T, WRAPPED_EXCEPTION]
+        try:
+            result = map_fun()
+        except BaseException as e:
+            result = _wrap_exception(e)
+
+        all_results = self.all_gather_object(result)
+
+        node_failures = _get_failure_dict(all_results)
+        if len(node_failures) > 0:
+            raise CheckpointException(step, node_failures)
+        return cast(List[T], all_results)
+
+    def broadcast(
+        self,
+        step: str,
+        map_fun: Callable[[], T],
+    ) -> T:
+        """
+        Compute a value on rank 0 and broadcast it.
+
+        This method operates in the following way:
+            Run ``map_cp`` on rank 0
+            broadcast the value
+        """
+        result: Optional[Union[T, CheckpointException]] = None
+        if self.is_coordinator:
+            try:
+                result = map_fun()
+            except BaseException as e:
+                result = CheckpointException(step, {self.rank: _wrap_exception(e)})
+        final_result = self.broadcast_object(result)
+        if isinstance(final_result, CheckpointException):
+            raise final_result
+        return cast(T, final_result)
+
+
+def _find_shard(tensor: ShardedTensor, index: MetadataIndex) -> Shard:
+    if index.offset is None:
+        raise ValueError(
+            f"Cannot lookup {index.fqn} since its a ShardedTensor and no offset was provided"
+        )
+
+    shards = tensor.local_shards()
+    # index fast path
+    if index.index is not None:
+        if (
+            len(shards) > index.index
+            and torch.Size(shards[index.index].metadata.shard_offsets) == index.offset
+        ):
+            return shards[index.index]
+
+    for shard in shards:
+        if torch.Size(shard.metadata.shard_offsets) == index.offset:
+            return shard
+    raise ValueError(f"Could not find shard at '{index.offset}' for FQN: '{index.fqn}'")
+
+
+def find_tensor_shard(tensor: torch.Tensor, index: MetadataIndex) -> torch.Tensor:
+    if hasattr(tensor, "__get_tensor_shard__"):
+        # DTensor implements _Checkpointable
+        return tensor.__get_tensor_shard__(index)  # type: ignore[attr-defined]
+    if isinstance(tensor, ShardedTensor):
+        return _find_shard(tensor, index).tensor
+    if index.offset is not None:
+        # special case looking up a tensor by origin
+        if index.offset == torch.Size([0] * len(tensor.size())):
+            return tensor
+        raise ValueError(
+            f"FQN: '{index.fqn}' is not a ShardedTensor, can't find by offset: '{index.offset}'"
+        )
+    return tensor
+
+
+def find_state_dict_object(state_dict: STATE_DICT_TYPE, index: MetadataIndex) -> Any:
+    if index.fqn not in state_dict:
+        raise ValueError(f"Could not find FQN: '{index.fqn}'")
+    obj = state_dict[index.fqn]
+
+    if isinstance(obj, torch.Tensor):
+        return find_tensor_shard(obj, index)
+    elif index.offset is not None:
+        raise ValueError(
+            f"FQN: '{index.fqn}' is not a ShardedTensor, can't find by offset: '{index.offset}'"
+        )
+    return obj
+
+
+def _element_wise_add(a: Sequence[int], b: Sequence[int]) -> List[int]:
+    return [i_a + i_b for i_a, i_b in zip(a, b)]
+
+
+def _element_wise_sub(a: Sequence[int], b: Sequence[int]) -> List[int]:
+    return [i_a - i_b for i_a, i_b in zip(a, b)]
+
+
+class _ReaderView(io.IOBase):
+    def __init__(self, base_stream: io.IOBase, offset: int, len: int):
+        super().__init__()
+        self.offset = offset
+        self.len = len
+        self.base_stream = base_stream
+        self.seek(0)
+
+    def seek(self, __offset: int, __whence: int = os.SEEK_SET) -> int:
+        if __whence == os.SEEK_SET:
+            __offset = self.offset + __offset
+        elif __whence == os.SEEK_END:
+            __whence = os.SEEK_SET
+            __offset = (self.offset + self.len) - __offset
+        return self.base_stream.seek(__offset, __whence)
+
+    def tell(self) -> int:
+        return self.base_stream.tell() - self.offset
+
+    def readable(self) -> bool:
+        return self.base_stream.readable()
+
+    def seekable(self) -> bool:
+        return self.base_stream.seekable()
+
+    def readinto(self, b):
+        return self.base_stream.readinto(b)  # type: ignore[attr-defined]
+
+    def read(self, size=-1):
+        return self.base_stream.read(size)
+
+
+def _create_file_view(file: io.IOBase, offset: int, length: int) -> io.IOBase:
+    # FIXME (kumpera) torch.load fails if we wrap with io.BufferedReader
+    return _ReaderView(file, offset, length)
+
+
+def _normalize_device_info(device_type: str, device_id: int) -> str:
+    """Device info normalization."""
+    if device_type == "cpu":
+        return "cpu"
+    return f"{device_type}:{device_id}"
+
+
+# TODO: integrate with distributed logging flag
+ENABLE_PROFILE = False
+
+
+@contextmanager
+def _profile():
+    # Only log the profiling when it is enable and is on rank0  or dist is not
+    # avaiable.
+    if ENABLE_PROFILE and (not dist.is_available() or dist.get_rank() == 0):
+        profiler = cProfile.Profile()
+        profiler.enable()
+        try:
+            yield
+        finally:
+            profiler.disable()
+            stats = Stats(profiler)
+            stats.sort_stats("time").print_stats(10)
+    else:
+        yield
+
+
+def _api_bc_check(func):
+    @wraps(func)
+    def inner_func(*args, **kwargs) -> Any:
+        if len(args) == 2:
+            warnings.warn(
+                f"The argument order of {func.__name__} has been changed. "
+                "Please check the document to avoid future breakages."
+            )
+            sig = inspect.signature(func)
+            kwonlyargs = [
+                p.name for p in sig.parameters.values() if p.kind == p.KEYWORD_ONLY
+            ]
+            if "storage_writer" in kwonlyargs:
+                assert "storage_writer" not in kwargs, (args, kwargs)
+                kwargs["storage_writer"] = args[1]
+            elif "storage_reader" in kwonlyargs:
+                assert "storage_reader" not in kwargs, (args, kwargs)
+                kwargs["storage_reader"] = args[1]
+            else:
+                raise RuntimeError(f"Unexpected kwonlyargs = {kwonlyargs}")
+            return func(args[0], **kwargs)
+        else:
+            return func(*args, **kwargs)
+
+    return inner_func
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a7c9b29a750593a812907ce2cf4c800d7d1435bb
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/__init__.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env/python3
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+"""
+
+Torchelastic agent and user worker failover contract:
+
+**TL;DR;**:
+
+* TE(torchelastic) expects user workers to finish with the 5 minutes drift
+* It is better to design DDP app to fail for all workers, rather than a single one.
+* TE does not synchronize number of restarts between agents
+* TE re-rendezvous does not trigger restart decrease
+* When a single agent finishes its job(successfully or not), it will close rendezvous.
+  If other agents still have workers in progress, they will be terminated.
+* Based on above, scale down does not work if at least single agent finishes the job.
+* When Scale up is detected by agents, it will not decrease ``max_restarts``
+
+
+In general TE(torchelastic) can launch arbitrary user code, but there is some
+clarifications need to be done around what failover mechanism torchelastic
+provides and what failover mechanism it expects from user workers.
+
+Torchelastic currently supports DDP style applications.  That means that
+TE expects *ALL* workers finish approximately at the same time. In practice,
+it is nearly to impossible to guarantee that all workers in arbitrary
+DDP application finish at the time, so TE provides a finalization barrier
+that waits for TIMEOUT(5 minutes) for worker finalization.
+
+**Worker Failure**
+
+When worker fails, TE will check the number of restarts
+available, if there is more than 0 restarts, TE will start a new rendezvous
+round and restart the worker process. New rendezvous round will other
+TE agents to terminate their workers.
+
+.. note:: The TE agent does not synchronize restarts between themselves.
+          When a single agent performs restart, it will trigger a local ``max_restarts``
+          decrease, other agent will not decrease their ``max_restarts``.
+          the user to run the distributed application locally on a dev host.
+
+A single worker failure can cause the whole cluster to fail:
+If a single worker is constantly failing, it will cause the TE agent
+``max_restarts``  to go to zero. This will cause an agent to finish its
+work and close rendezvous. If there are any other workers on different
+agents, they will be terminated.
+
+
+**Re-Rendezvous**
+
+Re-rendezvous occurs when TE agents detect a new node
+trying to joint a cluster. TE will not decrease ``max_restarts``. TE agents
+will terminate its workers and start a new rendezvous round.
+
+Note about DynamicRendezvous(etcd-v2, c10d-experimental): If the rendezvous
+has already max_nodes, the new node won't be added to the wait list right
+away since there is no need to tear down a rendezvous that is already fully
+utilized. The new node will wait until its timeout (600 secs by default)
+and periodically check the number of participants. If the number becomes
+less than max_nodes, it will be added to the wait list; otherwise, it will time out after 600 secs.
+
+*Scale up event*. When scale up event happens, torchelastic rendezvous
+will detect that there are new nodes trying to join. Torchelastic agent
+will stop all workers and perform re-rendezvous. Note: when scale up event
+happens, *``max_restarts``* will *not* decrease.
+
+*Scale down event*. When scale down event happens, rendezvous will not
+notify the torchelastic agent about it. If TE agent launched with ``max_restarts=0`` ,
+it relies on the underlying scheduler to handle job restart. If the ``max_restarts>0`` ,
+TE agent will terminate workers and start a new rdzv round, which is a *Scale up event*.
+
+"""
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e2501df8dda74c3bf9ad30bfe752af4a3b2cde20
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/__pycache__/control_plane.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/__pycache__/control_plane.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a69796b419e146662fc41b63ea709e60c22b5def
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/__pycache__/control_plane.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..50d637eae6b999994de359581a3693945b04d220
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/server/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/server/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c0d76131fe40d70945ffa8ff97431954151d50e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/server/__init__.py
@@ -0,0 +1,41 @@
+#!/usr/bin/env python3
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+"""
+The elastic agent is the control plane of torchelastic.
+
+It is a process that launches and manages underlying worker processes.
+The agent is responsible for:
+
+1. Working with distributed torch: the workers are started with all the
+   necessary information to successfully and trivially call
+   ``torch.distributed.init_process_group()``.
+
+2. Fault tolerance: monitors workers and upon detecting worker failures
+   or unhealthiness, tears down all workers and restarts everyone.
+
+3. Elasticity: Reacts to membership changes and restarts workers with the new
+   members.
+
+The simplest agents are deployed per node and works with local processes.
+A more advanced agent can launch and manage workers remotely. Agents can
+be completely decentralized, making decisions based on the workers it manages.
+Or can be coordinated, communicating to other agents (that manage workers
+in the same job) to make a collective decision.
+"""
+
+from .api import (  # noqa: F401
+    ElasticAgent,
+    RunResult,
+    SimpleElasticAgent,
+    Worker,
+    WorkerGroup,
+    WorkerSpec,
+    WorkerState,
+)
+from .local_elastic_agent import TORCHELASTIC_ENABLE_FILE_TIMER, TORCHELASTIC_TIMER_FILE
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/server/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/server/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..14f75d42cd82692941a71179c1e4ee1444d6c238
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/server/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/server/__pycache__/api.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/server/__pycache__/api.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a7242a6e86878be8a8772c11d02f762b766a2722
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/server/__pycache__/api.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/server/__pycache__/health_check_server.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/server/__pycache__/health_check_server.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..371fe5d190e073f6d4ecebbe1c7e26e850875ba2
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/server/__pycache__/health_check_server.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/server/__pycache__/local_elastic_agent.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/server/__pycache__/local_elastic_agent.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d73b5d4acf9743f8092ea55bd24c0bbaa763301e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/server/__pycache__/local_elastic_agent.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/server/api.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/server/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..50c69b8e962740426fc6d763b4c72260757165e9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/server/api.py
@@ -0,0 +1,942 @@
+# mypy: ignore-errors
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+import abc
+import json
+import os
+import signal
+import socket
+import time
+import traceback
+import warnings
+from collections import defaultdict
+from contextlib import contextmanager
+from dataclasses import dataclass, field
+from enum import Enum
+from typing import Any, Callable, Dict, List, Optional, Tuple, Union
+
+import torch.distributed.elastic.rendezvous as rdzv
+import torch.distributed.elastic.utils.store as store_util
+from torch.distributed.elastic.events import Event, EventSource, record
+from torch.distributed.elastic.metrics import prof, put_metric
+from torch.distributed.elastic.multiprocessing import ProcessFailure, SignalException
+from torch.distributed.elastic.rendezvous import RendezvousGracefulExitError
+from torch.distributed.elastic.utils.logging import get_logger
+
+
+__all__ = [
+    "WorkerSpec",
+    "Worker",
+    "WorkerState",
+    "WorkerGroup",
+    "RunResult",
+    "ElasticAgent",
+    "SimpleElasticAgent",
+]
+_TERMINAL_STATE_SYNC_ID = "torchelastic/agent/terminal_state"
+
+DEFAULT_ROLE = "default"
+logger = get_logger(__name__)
+
+
+@dataclass
+class WorkerSpec:
+    """Blueprint information about a particular type of worker.
+
+    For a given role, there must only exist a single worker spec.
+    Worker spec is expected to be homogeneous across all nodes (machine),
+    that is each node runs the same number of workers for a particular spec.
+
+    Args:
+        role: user-defined role for the workers with this spec
+        local_world_size: number local workers to run
+        fn: (deprecated use entrypoint instead)
+        entrypoint: worker function or command
+        args: arguments to pass to ``entrypoint``
+        rdzv_handler: handles rdzv for this set of workers
+        max_restarts: number of max retries for the workers
+        monitor_interval: monitor status of workers every ``n`` seconds
+        master_port: fixed port to run the c10d store on rank 0
+                     if not specified then will chose a random free port
+        master_addr: fixed master_addr to run the c10d store on rank 0
+                     if not specified then will chose hostname on agent rank 0
+        redirects: redirect std streams to a file,
+                   selectively redirect for a particular
+                   local rank by passing a map
+        tee: tees the specified std stream(s) to console + file,
+             selectively tee for a particular local rank by passing a map,
+             takes precedence over ``redirects`` settings.
+
+    """
+
+    role: str
+    local_world_size: int
+    rdzv_handler: rdzv.RendezvousHandler
+    fn: Optional[Callable] = None
+    # TODO @kiuk - make entrypoint a required field
+    entrypoint: Union[Callable, str, None] = None
+    args: Tuple = ()
+    max_restarts: int = 3
+    monitor_interval: float = 0.1
+    master_port: Optional[int] = None
+    master_addr: Optional[str] = None
+    local_addr: Optional[str] = None
+
+    def __post_init__(self):
+        assert self.local_world_size > 0
+        assert self.monitor_interval > 0
+
+        if self.fn:
+            warnings.warn(
+                "WorkerSpec.fn will be deprecated,"
+                " please use WorkerSpec.entrypoint instead",
+                category=DeprecationWarning,
+            )
+            self.entrypoint = self.fn
+        assert self.entrypoint
+
+    def get_entrypoint_name(self):
+        """Get the entry point name.
+
+        If the entrypoint is a function (e.g. ``Callable``) returns its ``__qualname__``
+        else if the entrypoint is a binary (e.g. ``str``), returns the binary name.
+        """
+        if isinstance(self.entrypoint, str):
+            return os.path.basename(self.entrypoint)
+        else:
+            assert self.entrypoint is not None
+            return self.entrypoint.__qualname__
+
+
+class Worker:
+    """A worker instance.
+
+    Contrast this with ``WorkerSpec`` that represents the specifications of a
+    worker. A ``Worker`` is created from a ``WorkerSpec``. A ``Worker`` is to
+    a ``WorkerSpec`` as an object is to a class.
+
+    The ``id`` of the worker is interpreted
+    by the specific implementation of ``ElasticAgent``. For a local
+    agent, it could be the ``pid (int)`` of the worker, for a remote
+    agent it could be encoded as ``host:port (string)``.
+
+    Args:
+        id (Any): uniquely identifies a worker (interpreted by the agent)
+        local_rank (int): local rank of the worker
+        global_rank (int): global rank of the worker
+        role_rank (int): rank of the worker across all workers that have the same role
+        world_size (int): number of workers (globally)
+        role_world_size (int): number of workers that have the same role
+    """
+
+    __slots__ = [
+        "id",
+        "local_rank",
+        "global_rank",
+        "role_rank",
+        "world_size",
+        "role_world_size",
+    ]
+
+    def __init__(
+        self,
+        local_rank: int,
+        global_rank: int = -1,
+        role_rank: int = -1,
+        world_size: int = -1,
+        role_world_size: int = -1,
+    ):
+        # unique identifier for this worker
+        self.id: Any = None
+
+        # rank of the worker among workers with the same role being monitored
+        # by the same ``agent`` instance.
+        self.local_rank: int = local_rank
+
+        #  rank of the worker among all the workers across all roles
+        #  across all ``agent`` instances.
+        #  Global rank is not stable between re-rendezvous.
+        self.global_rank: int = global_rank
+
+        #  rank of the worker among all the workers with the same role
+        #  across all ``agent`` instances.
+        #  Role rank is not stable between re-rendezvous.
+        self.role_rank: int = role_rank
+
+        # total number of workers (globally). Due to elasticity
+        # the world size may change between re-rendezvous.
+        self.world_size: int = world_size
+
+        # total number of workers that share the same role. Due to elasticity
+        # the role world size may change between re-rendezvous.
+        self.role_world_size: int = role_world_size
+
+    def __str__(self):
+        return (
+            f"local_rank={self.local_rank},global_rank={self.global_rank}"
+            f",role_rank={self.role_rank},world_size={self.world_size}"
+            f",role_world_size={self.role_world_size}"
+        )
+
+    def __repr__(self):
+        return str(self)
+
+
+class WorkerState(str, Enum):
+    """A state of the ``WorkerGroup``.
+
+    Workers in a worker group change state as a unit. If a single worker
+    in a worker group fails the entire set is considered failed::
+
+      UNKNOWN - agent lost track of worker group state, unrecoverable
+      INIT - worker group object created not yet started
+      HEALTHY - workers running and healthy
+      UNHEALTHY - workers running and unhealthy
+      STOPPED - workers stopped (interrupted) by the agent
+      SUCCEEDED - workers finished running (exit 0)
+      FAILED - workers failed to successfully finish (exit !0)
+
+
+    A worker group starts from an initial ``INIT`` state,
+    then progresses to ``HEALTHY`` or ``UNHEALTHY`` states,
+    and finally reaches a terminal ``SUCCEEDED`` or ``FAILED`` state.
+
+    Worker groups can be interrupted and temporarily put into ``STOPPED`` state
+    by the agent. Workers in ``STOPPED`` state are scheduled to be restarted
+    in the near future by the agent. Some examples of workers being put into
+    ``STOPPED`` state are:
+
+    1. Worker group failure|unhealthy observed
+    2. Membership change detected
+
+    When actions (start, stop, rdzv, retry, etc) on worker group fails
+    and results in the action being partially applied to the worker group
+    the state will be ``UNKNOWN``. Typically this happens on uncaught/unhandled
+    exceptions during state change events on the agent. The agent is not
+    expected to recover worker groups in ``UNKNOWN`` state and is better off
+    self terminating and allowing the job manager to retry the node.
+    """
+
+    UNKNOWN = "UNKNOWN"
+    INIT = "INIT"
+    HEALTHY = "HEALTHY"
+    UNHEALTHY = "UNHEALTHY"
+    STOPPED = "STOPPED"
+    SUCCEEDED = "SUCCEEDED"
+    FAILED = "FAILED"
+
+    @staticmethod
+    def is_running(state: "WorkerState") -> bool:
+        """Return the state of the Worker.
+
+        Returns:
+             True if the worker state represents workers still running
+             (e.g. that the process exists but not necessarily healthy).
+        """
+        return state in {WorkerState.HEALTHY, WorkerState.UNHEALTHY}
+
+
+class WorkerGroup:
+    """A set of ``Worker`` instances.
+
+    The class defines a set of ``Worker`` instances for the given ``WorkerSpec`` managed by ``ElasticAgent``. Whether the worker
+    group contains cross instance workers or not depends on the implementation of the agent.
+    """
+
+    __slots__ = [
+        "spec",
+        "workers",
+        "store",
+        "group_rank",
+        "group_world_size",
+        "state",
+        "master_addr",
+        "master_port",
+    ]
+
+    def __init__(self, spec: WorkerSpec):
+        self.spec = spec
+        self.workers = [Worker(local_rank=i) for i in range(self.spec.local_world_size)]
+
+        # assigned after rdzv
+        self.store = None
+        self.group_rank = None
+        self.group_world_size = None
+        self.master_addr = None
+        self.master_port = None
+
+        self.state = WorkerState.INIT
+
+
+class _RoleInstanceInfo:
+    """The class is used by the agent to exchange the information with other agents.
+
+    The information is used to determine the rank of the workers that agent
+    manages in heterogeneous environments, where different agents can have
+    different number of workers.
+    """
+
+    __slots__ = ["role", "rank", "local_world_size"]
+
+    def __init__(self, role: str, rank: int, local_world_size: int):
+        r"""Initialize the agent class instance.
+
+        Args:
+            role (str): user-defined role for the workers with this spec
+            rank (int): the rank of the agent
+            local_world_size (int): number of local workers to run
+        """
+        self.role = role
+        self.rank = rank
+        self.local_world_size = local_world_size
+
+    def serialize(self) -> bytes:
+        dict_data = {
+            "role": self.role,
+            "rank": self.rank,
+            "local_world_size": self.local_world_size,
+        }
+        return json.dumps(dict_data).encode(encoding="UTF-8")
+
+    @staticmethod
+    def deserialize(data: bytes):
+        dict_data = json.loads(data.decode(encoding="UTF-8"))
+        return _RoleInstanceInfo(
+            dict_data["role"], dict_data["rank"], dict_data["local_world_size"]
+        )
+
+    @staticmethod
+    def compare(obj1, obj2) -> int:
+        if obj1.role == obj2.role:
+            return obj1.rank - obj2.rank
+        elif obj1.role > obj2.role:
+            return 1
+        else:
+            return -1
+
+    @staticmethod
+    def find_role_boundaries(roles_infos: List, role: str) -> Tuple[int, int]:
+        start_idx, end_idx = -1, -1
+        for idx, role_info in enumerate(roles_infos):
+            if role_info.role == role:
+                if start_idx == -1:
+                    start_idx = idx
+                end_idx = idx
+        return (start_idx, end_idx)
+
+
+@dataclass
+class RunResult:
+    """Return results of the worker executions.
+
+    Run results follow an "all-or-nothing" policy where the run is successful if and
+    only if ALL local workers managed by this agent complete successfully.
+
+    If the result is successful (e.g. ``is_failed() = False``) then the ``return_values``
+    field contains the outputs (return values) of the workers managed by THIS agent mapped
+    by their GLOBAL ranks. That is ``result.return_values[0]`` is the return value of
+    global rank 0.
+
+    .. note:: ``return_values`` are only meaningful for when the worker entrypoint
+              is a function. Workers specified as a binary entrypoint do not canonically
+              have a return value and the ``return_values`` field is meaningless and
+              may be empty.
+
+    If ``is_failed()`` returns ``True`` then the ``failures`` field contains the
+    failure information, again, mapped by the GLOBAL rank of the worker that failed.
+
+    The keys in ``return_values`` and ``failures`` are mutually exclusive, that is,
+    a worker's final state can only be one of: succeeded, failed. Workers intentionally
+    terminated by the agent according to the agent's restart policy, are not represented
+    in either ``return_values`` nor ``failures``.
+    """
+
+    state: WorkerState
+    return_values: Dict[int, Any] = field(default_factory=dict)
+    failures: Dict[int, ProcessFailure] = field(default_factory=dict)
+
+    def is_failed(self) -> bool:
+        return self.state == WorkerState.FAILED
+
+
+def _get_fq_hostname() -> str:
+    return socket.getfqdn(socket.gethostname())
+
+
+class ElasticAgent(abc.ABC):
+    """An agent process responsible for managing one or more worker processes.
+
+    The worker processes are assumed to be regular distributed PyTorch scripts.
+    When the worker process is created by the agent, the agent provides the
+    necessary information for the worker processes to properly initialize
+    a torch process group.
+
+    The exact deployment topology and ratio of agent-to-worker is dependent
+    on the specific implementation of the agent and the user's job placement
+    preferences. For instance, to run a distributed training job on GPU with
+    8 trainers (one per GPU) one can:
+
+    1. Use 8 x single GPU instances, place an agent per instance, managing
+       1 worker per agent.
+    2. Use 4 x double GPU instances, place an agent per instance, managing
+       2 workers per agent.
+    3. Use 2 x quad GPU instances, place an agent per instance, managing
+       4 workers per agent.
+    4. Use 1 x 8 GPU instance, place an agent per instance, managing
+       8 workers per agent.
+
+    Usage
+    ::
+
+     group_result = agent.run()
+      if group_result.is_failed():
+        # workers failed
+        failure = group_result.failures[0]
+        logger.exception("worker 0 failed with exit code : %s", failure.exit_code)
+      else:
+        return group_result.return_values[0] # return rank 0's results
+
+    """
+
+    @abc.abstractmethod
+    def run(self, role: str = DEFAULT_ROLE) -> RunResult:
+        """Run the agent.
+
+        Supports retrying the worker group on failures up to ``max_restarts``.
+
+        Returns:
+            The result of the execution, containing the return values or
+            failure details for each worker mapped by the worker's global rank.
+
+        Raises:
+            Exception - any other failures NOT related to worker process
+        """
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def get_worker_group(self, role: str = DEFAULT_ROLE) -> WorkerGroup:
+        """Return the ``WorkerGroup`` for the given ``role``.
+
+        Note that the worker group is a mutable object and hence in a
+        multi-threaded/process environment it may change state.
+        Implementors are encouraged (but not required) to return
+        a defensive read-only copy.
+        """
+        raise NotImplementedError
+
+
+class SimpleElasticAgent(ElasticAgent):
+    """An ``ElasticAgent`` that manages one particular type of worker role.
+
+    An ``ElasticAgent`` that manages workers (``WorkerGroup``) for a single ``WorkerSpec``
+    such as one particular type of worker role.
+    """
+
+    def __init__(self, spec: WorkerSpec, exit_barrier_timeout: float = 300):
+        self._worker_group = WorkerGroup(spec)
+        self._remaining_restarts = self._worker_group.spec.max_restarts
+        self._store = None
+        self._exit_barrier_timeout = exit_barrier_timeout
+        self._total_execution_time = 0
+
+    def get_worker_group(self, role: str = DEFAULT_ROLE) -> WorkerGroup:
+        return self._worker_group
+
+    @abc.abstractmethod
+    def _start_workers(self, worker_group: WorkerGroup) -> Dict[int, Any]:
+        r"""Start ``worker_group.spec.local_world_size`` number of workers.
+
+        This is according to worker spec for the worker group .
+        Returns a map of ``local_rank`` to worker ``id``.
+        """
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def _stop_workers(
+        self, worker_group: WorkerGroup, is_restart: bool = False
+    ) -> None:
+        r"""Stop all workers in the given worker group.
+
+        Implementors must deal with workers in all states defined by
+        ``WorkerState``. That is, it must gracefully handle stopping
+        non-existent workers, unhealthy (stuck) workers, etc.
+        """
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def _monitor_workers(self, worker_group: WorkerGroup) -> RunResult:
+        r"""Check on the workers for the ``worker_group``.
+
+        This function also returns the new state of the worker group.
+        """
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def _shutdown(
+        self, death_sig: signal.Signals = signal.SIGTERM, is_restart: bool = False
+    ) -> None:
+        """Clean up any resources that were allocated during the agent's work.
+
+        Args:
+            death_sig: Signal to send to the child process, SIGTERM is default
+        """
+        raise NotImplementedError
+
+    @prof
+    def _rendezvous(self, worker_group: WorkerGroup) -> None:
+        r"""Run rendezvous for the workers specified by the worker spec.
+
+        Assigns workers a new global rank and world size.
+        Updates the rendezvous store for the worker group.
+        """
+        spec = worker_group.spec
+
+        with self.record_duration("RENDEZVOUS"):
+            rdzv_info = spec.rdzv_handler.next_rendezvous()
+        store = rdzv_info.store
+        group_rank = rdzv_info.rank
+        group_world_size = rdzv_info.world_size
+
+        # master_addr/master_port could be explicitly overriden
+        # TODO: BC - specific to static rdzv and can be simplifed further
+        master_addr = spec.master_addr or rdzv_info.bootstrap_store_info.master_addr
+        master_port = spec.master_port or rdzv_info.bootstrap_store_info.master_port
+
+        self._store = store
+
+        with self.record_duration("ASSIGN_WORKER_RANKS"):
+            workers = self._assign_worker_ranks(
+                store, group_rank, group_world_size, spec
+            )
+        worker_group.workers = workers
+        worker_group.store = store
+        worker_group.group_rank = group_rank
+        worker_group.group_world_size = group_world_size
+        worker_group.master_addr = master_addr
+        worker_group.master_port = master_port
+
+        restart_count = spec.max_restarts - self._remaining_restarts
+
+        logger.info(
+            "[%(role)s] Rendezvous complete for workers. Result:\n"
+            "  restart_count=%(restart_count)s\n"
+            "  master_addr=%(master_addr)s\n"
+            "  master_port=%(master_port)s\n"
+            "  group_rank=%(group_rank)s\n"
+            "  group_world_size=%(group_world_size)s\n"
+            "  local_ranks=%(local_ranks)s\n"
+            "  role_ranks=%(role_ranks)s\n"
+            "  global_ranks=%(global_ranks)s\n"
+            "  role_world_sizes=%(role_world_sizes)s\n"
+            "  global_world_sizes=%(global_world_sizes)s\n",
+            {
+                "role": spec.role,
+                "restart_count": restart_count,
+                "master_addr": master_addr,
+                "master_port": master_port,
+                "group_rank": group_rank,
+                "group_world_size": group_world_size,
+                "local_ranks": [worker.local_rank for worker in workers],
+                "role_ranks": [worker.role_rank for worker in workers],
+                "global_ranks": [worker.global_rank for worker in workers],
+                "role_world_sizes": [worker.role_world_size for worker in workers],
+                "global_world_sizes": [worker.world_size for worker in workers],
+            },
+        )
+
+    # pyre-fixme[56]: Pyre was not able to infer the type of the decorator
+    #  `torch.distributed.elastic.metrics.prof`.
+    @prof
+    def _assign_worker_ranks(
+        self, store, group_rank: int, group_world_size: int, spec: WorkerSpec
+    ) -> List[Worker]:
+        """Determine proper ranks for worker processes.
+
+        The rank assignment is done according to the following algorithm:
+
+        1. Each agent writes its configuration(group_rank, group_world_size
+           , num_workers) to the common store.
+        2. The rank 0 agent reads all the role_info from the store and
+           determines each agents worker ranks.
+        3. Determine the global rank: the global rank of the workers is computed
+           by cumulative sum of the local_world_size for all workers in front of it.
+           For efficiency reasons each worker is assigned a base global rank
+           such that it's workers are in the range [base_global_rank,
+           base_global_rank + local_world_size).
+        4. Determine the role rank: The role rank is determined using the algorithms
+           in the point 3 with the exception that the ranks are calculated with
+           respect to the role name.
+        5. The rank 0 agent writes the assigned ranks to the store.
+        6. Each agent reads the assigned ranks from the store.
+
+        Time complexity: each worker O(1), rank0 O(n), overall O(n)
+        """
+
+        ROLE_INFO_PREFIX = "torchelastic/role_info/"
+        ASSIGNED_RANKS_PREFIX = "torchelastic/assigned_ranks/"
+
+        agent_role_info = _RoleInstanceInfo(
+            spec.role, group_rank, spec.local_world_size
+        )
+        store.set(f"{ROLE_INFO_PREFIX}{group_rank}", agent_role_info.serialize())
+
+        # tcp store is collocated with rank 0 so we can use it to do extra compute to reduce overall # of operations.
+        if group_rank == 0:
+            role_infos_bytes = store.multi_get(
+                [f"torchelastic/role_info/{i}" for i in range(group_world_size)]
+            )
+            role_infos = [
+                _RoleInstanceInfo.deserialize(info_bytes)
+                for info_bytes in role_infos_bytes
+            ]
+
+            role_sizes = defaultdict(lambda: 0)
+            global_size = 0
+            for role_info in role_infos:
+                role_sizes[role_info.role] += role_info.local_world_size
+                global_size += role_info.local_world_size
+
+            base_global_rank = 0
+            role_ranks = defaultdict(lambda: 0)
+
+            keys = []
+            values = []
+            for i, role_info in enumerate(role_infos):
+                keys.append(f"{ASSIGNED_RANKS_PREFIX}{i}")
+                values.append(
+                    json.dumps(
+                        [
+                            base_global_rank,
+                            global_size,
+                            role_ranks[role_info.role],
+                            role_sizes[role_info.role],
+                        ]
+                    )
+                )
+
+                base_global_rank += role_info.local_world_size
+                role_ranks[role_info.role] += role_info.local_world_size
+
+            store.multi_set(keys, values)
+
+        # get will block until the data is available in the store.
+        (
+            base_global_rank,
+            global_world_size,
+            base_role_rank,
+            role_world_size,
+        ) = json.loads(store.get(f"{ASSIGNED_RANKS_PREFIX}{group_rank}"))
+
+        workers = []
+        for local_rank in range(spec.local_world_size):
+            worker = Worker(
+                local_rank=local_rank,
+                global_rank=base_global_rank + local_rank,
+                role_rank=base_role_rank + local_rank,
+                world_size=global_world_size,
+                role_world_size=role_world_size,
+            )
+            workers.append(worker)
+        return workers
+
+    # pyre-fixme[56]: Pyre was not able to infer the type of the decorator
+    #  `torch.distributed.elastic.metrics.prof`.
+    @prof
+    def _initialize_workers(self, worker_group: WorkerGroup) -> None:
+        r"""Start a fresh set of workers for the worker_group.
+
+        Essentially, a rendezvous followed by a ``start_workers``.
+        The caller should first call ``_stop_workers()`` to stop running workers
+        prior to calling this method.
+
+        Optimistically sets the state of the worker group that
+        just started as ``HEALTHY`` and delegates the actual monitoring
+        of state to ``_monitor_workers()`` method
+        """
+        role = worker_group.spec.role
+        logger.info("[%s] Rendezvous'ing worker group", role)
+
+        # TODO after stopping workers, wait at least monitor_interval*2 for
+        # workers on different nodes to fail on a collective op before waiting
+        # on the rdzv barrier, this way we ensure that nodes enter rdzv
+        # at around the same time and reduce false positive rdzv timeout errors
+        self._rendezvous(worker_group)
+
+        logger.info("[%s] Starting worker group", role)
+        worker_ids = self._start_workers(worker_group)
+        for local_rank, w_id in worker_ids.items():
+            worker = worker_group.workers[local_rank]
+            worker.id = w_id
+
+        worker_group.state = WorkerState.HEALTHY
+
+    # pyre-fixme[56]: Pyre was not able to infer the type of the decorator
+    #  `torch.distributed.elastic.metrics.prof`.
+    @prof
+    def _restart_workers(self, worker_group: WorkerGroup) -> None:
+        """Restart (stops, rendezvous, starts) all local workers in the group."""
+        role = worker_group.spec.role
+        logger.info("[%s] Stopping worker group", role)
+        self._stop_workers(worker_group, is_restart=True)
+        worker_group.state = WorkerState.STOPPED
+        self._initialize_workers(worker_group)
+
+    # pyre-fixme[56]: Pyre was not able to infer the type of the decorator
+    #  `torch.distributed.elastic.metrics.prof`.
+    @prof
+    def run(self, role: str = DEFAULT_ROLE) -> RunResult:
+        start_time = time.monotonic()
+        shutdown_called: bool = False
+        try:
+            result = self._invoke_run(role)
+            self._total_execution_time = int(time.monotonic() - start_time)
+            self._record_metrics(result)
+            self._record_worker_events(result)
+            return result
+        except RendezvousGracefulExitError as e:
+            logger.info("Rendezvous gracefully exited: %s", e)
+        except SignalException as e:
+            logger.warning("Received %s death signal, shutting down workers", e.sigval)
+            self._shutdown(e.sigval)
+            shutdown_called = True
+            raise
+        finally:
+            if not shutdown_called:
+                self._shutdown()
+            # record the execution time in case there were any exceptions during run.
+            self._total_execution_time = int(time.monotonic() - start_time)
+
+    def get_event_failed(self) -> Event:
+        return self._construct_event(
+            state="FAILED",
+            source=EventSource.AGENT,
+            raw_error=traceback.format_exc(),
+        )
+
+    def get_event_succeeded(self) -> Event:
+        return self._construct_event(
+            state="SUCCEEDED",
+            source=EventSource.AGENT,
+        )
+
+    def _record_worker_events(self, result: RunResult) -> None:
+        for worker in self._worker_group.workers:
+            failure = result.failures.get(worker.global_rank)
+            state: str = self._get_worker_state(worker, result)
+            raw_error = json.dumps(failure.error_file_data) if failure else None
+            record(self._construct_event(state, EventSource.WORKER, worker, raw_error))
+
+    def _get_worker_state(self, worker: Worker, result: RunResult) -> str:
+        failure = result.failures.get(worker.global_rank)
+        if result.state in {WorkerState.UNHEALTHY, WorkerState.FAILED} and not failure:
+            # The worker got terminated by the torchelastic agent via SIGTERM signal
+            return "TERMINATED"
+        elif failure or worker.global_rank in result.return_values:
+            return result.state.value
+        else:
+            raise ValueError(f"Unknown worker: {worker.global_rank}")
+
+    @contextmanager
+    def record_duration(self, state: str):
+        start_time = time.perf_counter()
+        try:
+            yield
+        finally:
+            end_time = time.perf_counter()
+            duration_ms = (end_time - start_time) * 1000
+            record(
+                self._construct_event(
+                    state=state, source=EventSource.AGENT, duration_ms=duration_ms
+                )
+            )
+
+    def _construct_event(
+        self,
+        state: str,
+        source: EventSource,
+        worker: Optional[Worker] = None,
+        raw_error: Optional[str] = None,
+        duration_ms: Optional[float] = None,
+    ) -> Event:
+        wg = self._worker_group
+        spec = wg.spec
+        md = {
+            "group_world_size": wg.group_world_size,
+            "entry_point": spec.get_entrypoint_name(),
+        }
+        if worker:
+            md["local_rank"] = (worker.local_rank,)
+            md["role_rank"] = (worker.role_rank,)
+            md["role_world_size"] = (worker.role_world_size,)
+            global_rank = worker.global_rank
+            worker_id = str(worker.id)
+        else:
+            global_rank = None
+            worker_id = None
+        md_str = json.dumps(md)
+        metadata = {
+            "run_id": spec.rdzv_handler.get_run_id(),
+            "global_rank": global_rank,
+            "group_rank": wg.group_rank,
+            "worker_id": worker_id,
+            "role": spec.role,
+            "hostname": _get_fq_hostname(),
+            "state": state,
+            "total_run_time": self._total_execution_time,
+            "rdzv_backend": spec.rdzv_handler.get_backend(),
+            "raw_error": raw_error,
+            "metadata": md_str,
+            "agent_restarts": spec.max_restarts - self._remaining_restarts,
+            "duration_ms": duration_ms,
+        }
+        return Event(
+            f"torchelastic.worker.status.{state}", source=source, metadata=metadata
+        )
+
+    def _record_metrics(self, group_results: RunResult):
+        is_failed = group_results.is_failed()
+        self._record_flakiness_metric(is_failed)
+        spec = self._worker_group.spec
+        restarts_happened = self._remaining_restarts != spec.max_restarts
+        put_metric(f"workers.{spec.role}.run_total", 1)
+        self._record_metric_with_condition(
+            "run_success_with_retries", not is_failed and restarts_happened
+        )
+        self._record_metric_with_condition(
+            "run_success_no_retries", not is_failed and not restarts_happened
+        )
+        self._record_metric_with_condition(
+            "run_failed_with_retries", is_failed and restarts_happened
+        )
+        self._record_metric_with_condition(
+            "run_failed_no_retries", is_failed and not restarts_happened
+        )
+
+    def _record_metric_with_condition(self, metric_name, condition):
+        spec = self._worker_group.spec
+        if condition:
+            put_metric(f"workers.{spec.role}.{metric_name}", 1)
+        else:
+            put_metric(f"workers.{spec.role}.{metric_name}", 0)
+
+    def _record_flakiness_metric(self, is_failed: bool = False):
+        if is_failed:
+            flakiness = 100.0
+        else:
+            spec = self._worker_group.spec
+            flakiness = 100.0 - 100.0 * (self._remaining_restarts + 1) / (
+                spec.max_restarts + 1
+            )
+        spec = self._worker_group.spec
+
+        put_metric(f"workers.{spec.role}.flakiness", int(flakiness))
+
+    def _invoke_run(self, role: str = DEFAULT_ROLE) -> RunResult:
+        # NOTE: currently only works for a single role
+
+        spec = self._worker_group.spec
+        role = spec.role
+
+        logger.info(
+            "[%s] starting workers for entrypoint: %s", role, spec.get_entrypoint_name()
+        )
+
+        self._initialize_workers(self._worker_group)
+        monitor_interval = spec.monitor_interval
+        rdzv_handler = spec.rdzv_handler
+
+        while True:
+            assert self._worker_group.state != WorkerState.INIT
+            time.sleep(monitor_interval)
+            run_result = self._monitor_workers(self._worker_group)
+            state = run_result.state
+            self._worker_group.state = state
+
+            put_metric(f"workers.{role}.remaining_restarts", self._remaining_restarts)
+            put_metric(f"workers.{role}.{state.name.lower()}", 1)
+
+            if state == WorkerState.SUCCEEDED:
+                logger.info(
+                    "[%s] worker group successfully finished."
+                    " Waiting %s seconds for other agents to finish.",
+                    role,
+                    self._exit_barrier_timeout,
+                )
+                self._exit_barrier()
+                return run_result
+            elif state in {WorkerState.UNHEALTHY, WorkerState.FAILED}:
+                if self._remaining_restarts > 0:
+                    logger.info(
+                        "[%s] Worker group %s. "
+                        "%s/%s attempts left;"
+                        " will restart worker group",
+                        role,
+                        state.name,
+                        self._remaining_restarts,
+                        spec.max_restarts,
+                    )
+                    self._remaining_restarts -= 1
+                    self._restart_workers(self._worker_group)
+                else:
+                    self._stop_workers(self._worker_group)
+                    self._worker_group.state = WorkerState.FAILED
+                    return run_result
+            elif state == WorkerState.HEALTHY:
+                # membership changes do not count as retries
+                num_nodes_waiting = rdzv_handler.num_nodes_waiting()
+                group_rank = self._worker_group.group_rank
+                if num_nodes_waiting > 0:
+                    logger.info(
+                        "[%s] Detected %s "
+                        "new nodes from group_rank=%s; "
+                        "will restart worker group",
+                        role,
+                        num_nodes_waiting,
+                        group_rank,
+                    )
+                    self._restart_workers(self._worker_group)
+            else:
+                raise Exception(  # noqa: TRY002
+                    f"[{role}] Worker group in {state.name} state"
+                )
+
+    def _exit_barrier(self):
+        """
+        Define a barrier that keeps the agent process alive until all workers finish.
+
+        Wait for ``exit_barrier_timeout`` seconds for all agents to finish
+        executing their local workers (either successfully or not). This
+        acts as a safety guard against user scripts that terminate at different
+        times.
+        """
+        logger.info(
+            "Local worker group finished (%s). "
+            "Waiting %s seconds for other agents to finish",
+            self._worker_group.state,
+            self._exit_barrier_timeout,
+        )
+        start = time.time()
+        try:
+            store_util.barrier(
+                store=self._store,
+                world_size=self._worker_group.group_world_size,
+                key_prefix=_TERMINAL_STATE_SYNC_ID,
+                barrier_timeout=self._exit_barrier_timeout,
+            )
+            logger.info(
+                "Done waiting for other agents. Elapsed: %s seconds",
+                time.time() - start,
+            )
+        except SignalException as e:
+            logger.warning("Got termination signal: %s", e.sigval)
+            raise
+        except Exception:
+            logger.exception(
+                "Error waiting on exit barrier. Elapsed: %s seconds",
+                time.time() - start,
+            )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/server/health_check_server.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/server/health_check_server.py
new file mode 100644
index 0000000000000000000000000000000000000000..d54915f7461685b9a49f87ea6dfa69a0c7d5e4c9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/server/health_check_server.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env python3
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+from typing import Callable
+
+from torch.distributed.elastic.utils.logging import get_logger
+
+
+log = get_logger(__name__)
+
+__all__ = ["HealthCheckServer", "create_healthcheck_server"]
+
+
+class HealthCheckServer:
+    """
+    Interface for health check monitoring server, which can be extended
+    by starting tcp/http server on the specified port.
+
+    Args:
+
+        alive_callback: Callable[[], int], callback to last progress time of agent
+
+        port: int, port number to start tcp/http server
+
+        timeout: int, timeout seconds to decide agent is alive/dead
+    """
+
+    _alive_callback: Callable[[], int]
+    _port: int
+    _timeout: int
+
+    def __init__(
+        self, alive_callback: Callable[[], int], port: int, timeout: int
+    ) -> None:
+        self._alive_callback = alive_callback
+        self._port = port
+        self._timeout = timeout
+
+    def start(self) -> None:
+        """
+        Unsupported functionality for Pytorch, doesn't start any health check server
+        """
+        log.warning("No health check server started")
+
+    def stop(self) -> None:
+        """
+        Function to stop health check server
+        """
+        log.info("Stopping noop health check server.")
+
+
+def create_healthcheck_server(
+    alive_callback: Callable[[], int],
+    port: int,
+    timeout: int,
+) -> HealthCheckServer:
+    """
+    creates health check server object
+    """
+    return HealthCheckServer(alive_callback, port, timeout)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/server/local_elastic_agent.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/server/local_elastic_agent.py
new file mode 100644
index 0000000000000000000000000000000000000000..f6a389ad61ec42cbf5e7a4c9d02ced629c0be90d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/agent/server/local_elastic_agent.py
@@ -0,0 +1,410 @@
+#!/usr/bin/env python3
+# mypy: allow-untyped-defs
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+
+import json
+import os
+import signal
+import socket
+import time
+import uuid
+from string import Template
+from typing import Any, Dict, Optional, Tuple, TYPE_CHECKING
+
+import torch.distributed.elastic.timer as timer
+from torch.distributed.elastic import events
+from torch.distributed.elastic.agent.server.api import (
+    RunResult,
+    SimpleElasticAgent,
+    WorkerGroup,
+    WorkerSpec,
+    WorkerState,
+)
+from torch.distributed.elastic.agent.server.health_check_server import (
+    create_healthcheck_server,
+    HealthCheckServer,
+)
+from torch.distributed.elastic.metrics.api import prof
+from torch.distributed.elastic.multiprocessing import (
+    LogsSpecs,
+    PContext,
+    start_processes,
+)
+from torch.distributed.elastic.utils import macros
+from torch.distributed.elastic.utils.logging import get_logger
+
+
+if TYPE_CHECKING:
+    from torch.distributed.elastic.events.api import EventMetadataValue
+
+logger = get_logger(__name__)
+
+__all__ = [
+    "LocalElasticAgent",
+    "TORCHELASTIC_ENABLE_FILE_TIMER",
+    "TORCHELASTIC_TIMER_FILE",
+    "TORCHELASTIC_HEALTH_CHECK_PORT",
+]
+
+TORCHELASTIC_ENABLE_FILE_TIMER = "TORCHELASTIC_ENABLE_FILE_TIMER"
+TORCHELASTIC_HEALTH_CHECK_PORT = "TORCHELASTIC_HEALTH_CHECK_PORT"
+TORCHELASTIC_TIMER_FILE = "TORCHELASTIC_TIMER_FILE"
+
+
+class LocalElasticAgent(SimpleElasticAgent):
+    """An implementation of :py:class:`torchelastic.agent.server.ElasticAgent` that handles host-local workers.
+
+    This agent is deployed per host and is configured to spawn ``n`` workers.
+    When using GPUs, ``n`` maps to the number of GPUs available on the host.
+
+    The local agent does not communicate to other local agents deployed on
+    other hosts, even if the workers may communicate inter-host. The worker id
+    is interpreted to be a local process. The agent starts and stops all worker
+    processes as a single unit.
+
+
+    The worker function and argument passed to the worker function must be
+    python multiprocessing compatible. To pass multiprocessing data structures
+    to the workers you may create the data structure in the same multiprocessing
+    context as the specified ``start_method`` and pass it as a function argument.
+
+    The ``exit_barrier_timeout`` specifies the amount of time (in seconds) to wait
+    for other agents to finish. This acts as a safety net to handle cases where
+    workers finish at different times, to prevent agents from viewing workers
+    that finished early as a scale-down event. It is strongly advised that the
+    user code deal with ensuring that workers are terminated in a synchronous
+    manner rather than relying on the exit_barrier_timeout.
+
+    A named pipe based watchdog can be enabled in ```LocalElasticAgent``` if an
+    environment variable ``TORCHELASTIC_ENABLE_FILE_TIMER`` with value 1 has
+    been defined in the ```LocalElasticAgent``` process.
+    Optionally, another environment variable ```TORCHELASTIC_TIMER_FILE```
+    can be set with a unique file name for the named pipe. If the environment
+    variable ```TORCHELASTIC_TIMER_FILE``` is not set, ```LocalElasticAgent```
+    will internally create a unique file name and set it to the environment
+    variable ```TORCHELASTIC_TIMER_FILE```, and this environment variable will
+    be propagated to the worker processes to allow them to connect to the same
+    named pipe that ```LocalElasticAgent``` uses.
+
+    Logs are written to the specified log directory. Each log line will be by default
+    prefixed by ``[${role_name}${local_rank}]:`` (e.g. ``[trainer0]: foobar``).
+    Log prefixes can be customized by passing a `template string
+    `_ as the
+    ``log_line_prefix_template`` argument.
+    The following macros (identifiers) are substituted at runtime:
+    ``${role_name}, ${local_rank}, ${rank}``. For example, to prefix each log line with
+    global rank instead of the local rank, set ``log_line_prefix_template = "[${rank}]:``.
+
+
+    Example launching function
+
+    ::
+
+        def trainer(args) -> str:
+            return "do train"
+
+        def main():
+            start_method="spawn"
+            shared_queue= multiprocessing.get_context(start_method).Queue()
+            spec = WorkerSpec(
+                        role="trainer",
+                        local_world_size=nproc_per_process,
+                        entrypoint=trainer,
+                        args=("foobar",),
+                        ...)
+            agent = LocalElasticAgent(spec, start_method)
+            results = agent.run()
+
+            if results.is_failed():
+                print("trainer failed")
+            else:
+                print(f"rank 0 return value: {results.return_values[0]}")
+                # prints -> rank 0 return value: do train
+
+    Example launching binary
+
+    ::
+
+        def main():
+            spec = WorkerSpec(
+                        role="trainer",
+                        local_world_size=nproc_per_process,
+                        entrypoint="/usr/local/bin/trainer",
+                        args=("--trainer-args", "foobar"),
+                        ...)
+            agent = LocalElasticAgent(spec)
+            results = agent.run()
+
+            if not results.is_failed():
+                print("binary launches do not have return values")
+
+    """
+
+    def __init__(
+        self,
+        spec: WorkerSpec,
+        logs_specs: LogsSpecs,
+        start_method="spawn",
+        exit_barrier_timeout: float = 300,
+        log_line_prefix_template: Optional[str] = None,
+    ):
+        super().__init__(spec, exit_barrier_timeout)
+        self._start_method = start_method
+        self._pcontext: Optional[PContext] = None
+        self._rdzv_handler = spec.rdzv_handler
+        self._log_line_prefix_template = log_line_prefix_template
+        self._worker_watchdog: Optional[timer.FileTimerServer] = None
+        self._logs_specs = logs_specs
+        self._health_check_server: Optional[HealthCheckServer] = None
+
+    def _setup_local_watchdog(self, envs: Dict[int, Dict[str, str]]) -> None:
+        enable_watchdog_env_name = TORCHELASTIC_ENABLE_FILE_TIMER
+        watchdog_enabled = os.getenv(enable_watchdog_env_name)
+        watchdog_file_env_name = TORCHELASTIC_TIMER_FILE
+        watchdog_file_path = os.getenv(watchdog_file_env_name)
+        if watchdog_enabled is not None and str(watchdog_enabled) == "1":
+            if watchdog_file_path is None:
+                watchdog_file_path = "/tmp/watchdog_timer_" + str(uuid.uuid4())
+            logger.info("Starting a FileTimerServer with %s ...", watchdog_file_path)
+            if not envs:
+                logger.warning(
+                    "Empty envs variables, using empty run_id for FileTimerServer"
+                )
+                run_id = ""
+            else:
+                run_id = envs[0]["TORCHELASTIC_RUN_ID"]
+            self._worker_watchdog = timer.FileTimerServer(
+                file_path=watchdog_file_path,
+                run_id=run_id,
+                max_interval=0.1,
+                daemon=True,
+                log_event=self._log_watchdog_event,
+            )
+            self._worker_watchdog.start()
+            logger.info("FileTimerServer started")
+        else:
+            logger.info(
+                "Environment variable '%s' not found. Do not start FileTimerServer.",
+                enable_watchdog_env_name,
+            )
+        # Propagate the watchdog file env to worker processes
+        if watchdog_file_path is not None:
+            for worker_env in envs.values():
+                worker_env[watchdog_file_env_name] = watchdog_file_path
+
+    @staticmethod
+    def _get_current_time_secs() -> int:
+        return int(time.time())
+
+    def _setup_healthcheck(self) -> None:
+        healthcheck_port_env_name = TORCHELASTIC_HEALTH_CHECK_PORT
+        healthcheck_port = os.getenv(healthcheck_port_env_name)
+        if healthcheck_port is not None:
+            logger.info(
+                "Found healthcheck port %s: %s",
+                healthcheck_port_env_name,
+                healthcheck_port,
+            )
+            if self._worker_watchdog is None:
+                logger.info(
+                    "FileTimerServer doesn't exist, using current time as dummy callback"
+                )
+                alive_callback = LocalElasticAgent._get_current_time_secs
+            else:
+                alive_callback = self._worker_watchdog.get_last_progress_time
+
+            self._health_check_server = create_healthcheck_server(
+                alive_callback=alive_callback,
+                port=int(healthcheck_port),
+                timeout=60,
+            )
+            self._health_check_server.start()
+        else:
+            logger.info(
+                "Environment variable '%s' not found. Do not start health check.",
+                healthcheck_port_env_name,
+            )
+
+    def _get_fq_hostname(self) -> str:
+        return socket.getfqdn(socket.gethostname())
+
+    def _log_watchdog_event(
+        self,
+        name: str,
+        request: Optional[timer.FileTimerRequest],
+    ) -> None:
+        wg = self._worker_group
+        spec = wg.spec
+        md = {"watchdog_event": name}
+        if request is not None:
+            md["worker_pid"] = str(request.worker_pid)
+            md["scope_id"] = request.scope_id
+            md["expiration_time"] = str(request.expiration_time)
+            md["signal"] = str(request.signal)
+        md_str = json.dumps(md)
+        state = "RUNNING"
+        metadata: Dict[str, EventMetadataValue] = {
+            "run_id": spec.rdzv_handler.get_run_id(),
+            "global_rank": None,
+            "group_rank": wg.group_rank,
+            "worker_id": None,
+            "role": spec.role,
+            "hostname": self._get_fq_hostname(),
+            "state": state,
+            "total_run_time": self._total_execution_time,
+            "rdzv_backend": spec.rdzv_handler.get_backend(),
+            "raw_error": None,
+            "metadata": md_str,
+            "agent_restarts": spec.max_restarts - self._remaining_restarts,
+        }
+        # Note: The 'metadata' field of the Event is converted to a TorchelasticStatusLogEntry later.
+        #       The 'name' field of the Event is NOT used in the TorchelasticStatusLogEntry.
+        event = events.Event(
+            name=name, source=events.EventSource.AGENT, metadata=metadata
+        )
+        events.record(event)
+
+    # pyre-fixme[56]: Pyre was not able to infer the type of the decorator
+    #  `torch.distributed.elastic.metrics.prof`.
+    @prof
+    def _stop_workers(
+        self, worker_group: WorkerGroup, is_restart: bool = False
+    ) -> None:
+        self._shutdown(is_restart=is_restart)
+
+    # pyre-fixme[56]: Pyre was not able to infer the type of the decorator
+    #  `torch.distributed.elastic.metrics.prof`.
+    @prof
+    def _start_workers(self, worker_group: WorkerGroup) -> Dict[int, Any]:
+        spec = worker_group.spec
+        store = worker_group.store
+        assert store is not None
+        restart_count = spec.max_restarts - self._remaining_restarts
+
+        use_agent_store: bool = spec.rdzv_handler.use_agent_store
+        logger.info("use_agent_store: %s", use_agent_store)
+
+        args: Dict[int, Tuple] = {}
+        envs: Dict[int, Dict[str, str]] = {}
+        log_line_prefixes: Optional[Dict[int, str]] = (
+            {} if self._log_line_prefix_template else None
+        )
+        for worker in worker_group.workers:
+            local_rank = worker.local_rank
+            worker_env = {
+                "LOCAL_RANK": str(local_rank),
+                "RANK": str(worker.global_rank),
+                "GROUP_RANK": str(worker_group.group_rank),
+                "ROLE_RANK": str(worker.role_rank),
+                "ROLE_NAME": spec.role,
+                "LOCAL_WORLD_SIZE": str(spec.local_world_size),
+                "WORLD_SIZE": str(worker.world_size),
+                "GROUP_WORLD_SIZE": str(worker_group.group_world_size),
+                "ROLE_WORLD_SIZE": str(worker.role_world_size),
+                "MASTER_ADDR": worker_group.master_addr,
+                "MASTER_PORT": str(worker_group.master_port),
+                "TORCHELASTIC_RESTART_COUNT": str(restart_count),
+                "TORCHELASTIC_MAX_RESTARTS": str(spec.max_restarts),
+                "TORCHELASTIC_RUN_ID": spec.rdzv_handler.get_run_id(),
+                "TORCHELASTIC_USE_AGENT_STORE": str(use_agent_store),
+                "TORCH_NCCL_ASYNC_ERROR_HANDLING": os.getenv(
+                    "TORCH_NCCL_ASYNC_ERROR_HANDLING", str(1)
+                ),
+            }
+            if "OMP_NUM_THREADS" in os.environ:
+                worker_env["OMP_NUM_THREADS"] = os.environ["OMP_NUM_THREADS"]
+
+            if self._log_line_prefix_template:
+                log_line_prefix = Template(
+                    self._log_line_prefix_template
+                ).safe_substitute(
+                    role_name=spec.role,
+                    rank=worker.global_rank,
+                    local_rank=local_rank,
+                )
+                log_line_prefixes[local_rank] = log_line_prefix
+
+            envs[local_rank] = worker_env
+            worker_args = list(spec.args)
+            worker_args = macros.substitute(worker_args, str(local_rank))
+            args[local_rank] = tuple(worker_args)
+
+        self._setup_local_watchdog(envs=envs)
+        self._setup_healthcheck()
+
+        assert spec.entrypoint is not None
+        assert self._logs_specs is not None
+        self._pcontext = start_processes(
+            name=spec.role,
+            entrypoint=spec.entrypoint,
+            args=args,
+            envs=envs,
+            logs_specs=self._logs_specs,
+            log_line_prefixes=log_line_prefixes,
+            start_method=self._start_method,
+        )
+
+        return self._pcontext.pids()
+
+    def _shutdown(
+        self, death_sig: signal.Signals = signal.SIGTERM, is_restart: bool = False
+    ) -> None:
+        if self._worker_watchdog is not None:
+            self._worker_watchdog.stop()
+            self._worker_watchdog = None
+        if self._health_check_server is not None:
+            self._health_check_server.stop()
+            self._health_check_server = None
+        if self._pcontext:
+            self._pcontext.close(death_sig)
+        if not is_restart and self._rdzv_handler:
+            self._rdzv_handler.shutdown()
+
+    # pyre-fixme[56]: Pyre was not able to infer the type of the decorator
+    #  `torch.distributed.elastic.metrics.prof`.
+    @prof
+    def _monitor_workers(self, worker_group: WorkerGroup) -> RunResult:
+        role = worker_group.spec.role
+        worker_pids = {w.id for w in worker_group.workers}
+        assert self._pcontext is not None
+        pc_pids = set(self._pcontext.pids().values())
+        if worker_pids != pc_pids:
+            logger.error(
+                "[%s] worker pids do not match process_context pids."
+                " Expected: %s, actual: %s",
+                role,
+                worker_pids,
+                pc_pids,
+            )
+            return RunResult(state=WorkerState.UNKNOWN)
+
+        result = self._pcontext.wait(0)
+        if result:
+            if result.is_failed():
+                # map local rank failure to global rank
+                worker_failures = {}
+                for local_rank, failure in result.failures.items():
+                    worker = worker_group.workers[local_rank]
+                    worker_failures[worker.global_rank] = failure
+                return RunResult(
+                    state=WorkerState.FAILED,
+                    failures=worker_failures,
+                )
+            else:
+                # copy ret_val_queue into a map with a global ranks
+                workers_ret_vals = {}
+                for local_rank, ret_val in result.return_values.items():
+                    worker = worker_group.workers[local_rank]
+                    workers_ret_vals[worker.global_rank] = ret_val
+                return RunResult(
+                    state=WorkerState.SUCCEEDED,
+                    return_values=workers_ret_vals,
+                )
+        else:
+            return RunResult(state=WorkerState.HEALTHY)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/control_plane.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/control_plane.py
new file mode 100644
index 0000000000000000000000000000000000000000..e778c0868384771e02e3b9df9e04a738a9e04043
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/control_plane.py
@@ -0,0 +1,52 @@
+import os
+from contextlib import contextmanager, ExitStack
+from typing import Generator
+
+from torch.distributed.elastic.multiprocessing.errors import record
+
+
+__all__ = [
+    "worker_main",
+]
+
+TORCH_WORKER_SERVER_SOCKET = "TORCH_WORKER_SERVER_SOCKET"
+
+
+@contextmanager
+def _worker_server(socket_path: str) -> Generator[None, None, None]:
+    from torch._C._distributed_c10d import _WorkerServer
+
+    server = _WorkerServer(socket_path)
+    try:
+        yield
+    finally:
+        server.shutdown()
+
+
+@contextmanager
+@record
+def worker_main() -> Generator[None, None, None]:
+    """
+    This is a context manager that wraps your main entry function. This combines
+    the existing ``errors.record`` logic as well as a new ``_WorkerServer`` that
+    exposes handlers via a unix socket specified by
+    ``Torch_WORKER_SERVER_SOCKET``.
+
+    Example
+
+    ::
+
+     @worker_main()
+     def main():
+         pass
+
+     if __name__=="__main__":
+        main()
+
+    """
+    with ExitStack() as stack:
+        socket_path = os.environ.get(TORCH_WORKER_SERVER_SOCKET)
+        if socket_path is not None:
+            stack.enter_context(_worker_server(socket_path))
+
+        yield
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/events/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/events/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e4a0a6f236918966cd19de32031a3947012b5eb
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/events/__init__.py
@@ -0,0 +1,170 @@
+#!/usr/bin/env/python3
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+"""
+Module contains events processing mechanisms that are integrated with the standard python logging.
+
+Example of usage:
+
+::
+
+  from torch.distributed.elastic import events
+  event = events.Event(name="test_event", source=events.EventSource.WORKER, metadata={...})
+  events.get_logging_handler(destination="console").info(event)
+
+"""
+
+import inspect
+import logging
+import os
+import socket
+import traceback
+from typing import Dict, Optional
+
+from torch.distributed.elastic.events.handlers import get_logging_handler
+
+from .api import (  # noqa: F401
+    Event,
+    EventMetadataValue,
+    EventSource,
+    NodeState,
+    RdzvEvent,
+)
+
+
+_events_loggers: Dict[str, logging.Logger] = {}
+
+
+def _get_or_create_logger(destination: str = "null") -> logging.Logger:
+    """
+    Construct python logger based on the destination type or extends if provided.
+
+    Available destination could be found in ``handlers.py`` file.
+    The constructed logger does not propagate messages to the upper level loggers,
+    e.g. root logger. This makes sure that a single event can be processed once.
+
+    Args:
+        destination: The string representation of the event handler.
+            Available handlers found in ``handlers`` module
+    """
+    global _events_loggers
+
+    if destination not in _events_loggers:
+        _events_logger = logging.getLogger(f"torchelastic-events-{destination}")
+        _events_logger.setLevel(os.environ.get("LOGLEVEL", "INFO"))
+        # Do not propagate message to the root logger
+        _events_logger.propagate = False
+
+        logging_handler = get_logging_handler(destination)
+        _events_logger.addHandler(logging_handler)
+
+        # Add the logger to the global dictionary
+        _events_loggers[destination] = _events_logger
+
+    return _events_loggers[destination]
+
+
+def record(event: Event, destination: str = "null") -> None:
+    _get_or_create_logger(destination).info(event.serialize())
+
+
+def record_rdzv_event(event: RdzvEvent) -> None:
+    _get_or_create_logger("dynamic_rendezvous").info(event.serialize())
+
+
+def construct_and_record_rdzv_event(
+    run_id: str,
+    message: str,
+    node_state: NodeState,
+    name: str = "",
+    hostname: str = "",
+    pid: Optional[int] = None,
+    master_endpoint: str = "",
+    local_id: Optional[int] = None,
+    rank: Optional[int] = None,
+) -> None:
+    """
+    Initialize rendezvous event object and record its operations.
+
+    Args:
+        run_id (str): The run id of the rendezvous.
+        message (str): The message describing the event.
+        node_state (NodeState): The state of the node (INIT, RUNNING, SUCCEEDED, FAILED).
+        name (str): Event name. (E.g. Current action being performed).
+        hostname (str): Hostname of the node.
+        pid (Optional[int]): The process id of the node.
+        master_endpoint (str): The master endpoint for the rendezvous store, if known.
+        local_id (Optional[int]):  The local_id of the node, if defined in dynamic_rendezvous.py
+        rank (Optional[int]): The rank of the node, if known.
+    Returns:
+        None
+    Example:
+        >>> # See DynamicRendezvousHandler class
+        >>> def _record(
+        ...     self,
+        ...     message: str,
+        ...     node_state: NodeState = NodeState.RUNNING,
+        ...     rank: Optional[int] = None,
+        ... ) -> None:
+        ...     construct_and_record_rdzv_event(
+        ...         name=f"{self.__class__.__name__}.{get_method_name()}",
+        ...         run_id=self._settings.run_id,
+        ...         message=message,
+        ...         node_state=node_state,
+        ...         hostname=self._this_node.addr,
+        ...         pid=self._this_node.pid,
+        ...         local_id=self._this_node.local_id,
+        ...         rank=rank,
+        ...     )
+    """
+    # We don't want to perform an extra computation if not needed.
+    if isinstance(get_logging_handler("dynamic_rendezvous"), logging.NullHandler):
+        return
+
+    # Set up parameters.
+    if not hostname:
+        hostname = socket.getfqdn()
+    if not pid:
+        pid = os.getpid()
+
+    # Determines which file called this function.
+    callstack = inspect.stack()
+    filename = "no_file"
+    if len(callstack) > 1:
+        stack_depth_1 = callstack[1]
+        filename = os.path.basename(stack_depth_1.filename)
+        if not name:
+            name = stack_depth_1.function
+
+    # Delete the callstack variable. If kept, this can mess with python's
+    # garbage collector as we are holding on to stack frame information in
+    # the inspect module.
+    del callstack
+
+    # Set up error trace if this is an exception
+    if node_state == NodeState.FAILED:
+        error_trace = traceback.format_exc()
+    else:
+        error_trace = ""
+
+    # Initialize event object
+    event = RdzvEvent(
+        name=f"{filename}:{name}",
+        run_id=run_id,
+        message=message,
+        hostname=hostname,
+        pid=pid,
+        node_state=node_state,
+        master_endpoint=master_endpoint,
+        rank=rank,
+        local_id=local_id,
+        error_trace=error_trace,
+    )
+
+    # Finally, record the event.
+    record_rdzv_event(event)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/events/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/events/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f645b5c4cfd0f53cb44ca7e15b7897595b21b0cf
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/events/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/events/__pycache__/api.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/events/__pycache__/api.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e9b6d6175ed6d69eefa2872bc0d25f4fa7f2009d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/events/__pycache__/api.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/events/__pycache__/handlers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/events/__pycache__/handlers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b0b702a394862b28ad0ca3c7acdc6899513e6001
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/events/__pycache__/handlers.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/events/api.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/events/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..c610cfd4cb3540e1bddfb363676c1408efd72e17
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/events/api.py
@@ -0,0 +1,114 @@
+#!/usr/bin/env python3
+# mypy: allow-untyped-defs
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+import json
+from dataclasses import asdict, dataclass, field
+from enum import Enum
+from typing import Dict, Optional, Union
+
+
+__all__ = ["EventSource", "Event", "NodeState", "RdzvEvent"]
+
+EventMetadataValue = Union[str, int, float, bool, None]
+
+
+class EventSource(str, Enum):
+    """Known identifiers of the event producers."""
+
+    AGENT = "AGENT"
+    WORKER = "WORKER"
+
+
+@dataclass
+class Event:
+    """
+    The class represents the generic event that occurs during the torchelastic job execution.
+
+    The event can be any kind of meaningful action.
+
+    Args:
+        name: event name.
+        source: the event producer, e.g. agent or worker
+        timestamp: timestamp in milliseconds when event occurred.
+        metadata: additional data that is associated with the event.
+    """
+
+    name: str
+    source: EventSource
+    timestamp: int = 0
+    metadata: Dict[str, EventMetadataValue] = field(default_factory=dict)
+
+    def __str__(self):
+        return self.serialize()
+
+    @staticmethod
+    def deserialize(data: Union[str, "Event"]) -> "Event":
+        if isinstance(data, Event):
+            return data
+        if isinstance(data, str):
+            data_dict = json.loads(data)
+        data_dict["source"] = EventSource[data_dict["source"]]  # type: ignore[possibly-undefined]
+        return Event(**data_dict)
+
+    def serialize(self) -> str:
+        return json.dumps(asdict(self))
+
+
+class NodeState(str, Enum):
+    """The states that a node can be in rendezvous."""
+
+    INIT = "INIT"
+    RUNNING = "RUNNING"
+    SUCCEEDED = "SUCCEEDED"
+    FAILED = "FAILED"
+
+
+@dataclass
+class RdzvEvent:
+    """
+    Dataclass to represent any rendezvous event.
+
+    Args:
+        name: Event name. (E.g. Current action being performed)
+        run_id: The run id of the rendezvous
+        message: The message describing the event
+        hostname: Hostname of the node
+        pid: The process id of the node
+        node_state: The state of the node (INIT, RUNNING, SUCCEEDED, FAILED)
+        master_endpoint: The master endpoint for the rendezvous store, if known
+        rank: The rank of the node, if known
+        local_id: The local_id of the node, if defined in dynamic_rendezvous.py
+        error_trace: Error stack trace, if this is an error event.
+    """
+
+    name: str
+    run_id: str
+    message: str
+    hostname: str
+    pid: int
+    node_state: NodeState
+    master_endpoint: str = ""
+    rank: Optional[int] = None
+    local_id: Optional[int] = None
+    error_trace: str = ""
+
+    def __str__(self):
+        return self.serialize()
+
+    @staticmethod
+    def deserialize(data: Union[str, "RdzvEvent"]) -> "RdzvEvent":
+        if isinstance(data, RdzvEvent):
+            return data
+        if isinstance(data, str):
+            data_dict = json.loads(data)
+        data_dict["node_state"] = NodeState[data_dict["node_state"]]  # type: ignore[possibly-undefined]
+        return RdzvEvent(**data_dict)
+
+    def serialize(self) -> str:
+        return json.dumps(asdict(self))
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/events/handlers.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/events/handlers.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a7c16e3fd808db47d257158cedb4aad185d41e6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/events/handlers.py
@@ -0,0 +1,22 @@
+#!/usr/bin/env python3
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+import logging
+from typing import Dict
+
+
+_log_handlers: Dict[str, logging.Handler] = {
+    "console": logging.StreamHandler(),
+    "dynamic_rendezvous": logging.NullHandler(),
+    "null": logging.NullHandler(),
+}
+
+
+def get_logging_handler(destination: str = "null") -> logging.Handler:
+    global _log_handlers
+    return _log_handlers[destination]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/metrics/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/metrics/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b72dcd7c6020de322ae4f20a7ca8076acb5a381
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/metrics/__init__.py
@@ -0,0 +1,164 @@
+#!/usr/bin/env/python3
+# mypy: allow-untyped-defs
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+"""Metrics API.
+
+**Overview**:
+
+The metrics API in torchelastic is used to publish telemetry metrics.
+It is designed to be used by torchelastic's internal modules to
+publish metrics for the end user with the goal of increasing visibility
+and helping with debugging. However you may use the same API in your
+jobs to publish metrics to the same metrics ``sink``.
+
+A ``metric`` can be thought of as timeseries data
+and is uniquely identified by the string-valued tuple
+``(metric_group, metric_name)``.
+
+torchelastic makes no assumptions about what a ``metric_group`` is
+and what relationship it has with ``metric_name``. It is totally up
+to the user to use these two fields to uniquely identify a metric.
+
+.. note:: The metric group ``torchelastic`` is reserved by torchelastic for
+          platform level metrics that it produces.
+          For instance torchelastic may output the latency (in milliseconds)
+          of a re-rendezvous operation from the agent as
+          ``(torchelastic, agent.rendezvous.duration.ms)``
+
+A sensible way to use metric groups is to map them to a stage or module
+in your job. You may also encode certain high level properties
+the job such as the region or stage (dev vs prod).
+
+**Publish Metrics**:
+
+Using torchelastic's metrics API is similar to using python's logging
+framework. You first have to configure a metrics handler before
+trying to add metric data.
+
+The example below measures the latency for the ``calculate()`` function.
+
+::
+
+  import time
+  import torch.distributed.elastic.metrics as metrics
+
+  # makes all metrics other than the one from "my_module" to go /dev/null
+  metrics.configure(metrics.NullMetricsHandler())
+  metrics.configure(metrics.ConsoleMetricsHandler(), "my_module")
+
+  def my_method():
+    start = time.time()
+    calculate()
+    end = time.time()
+    metrics.put_metric("calculate_latency", int(end-start), "my_module")
+
+You may also use the torch.distributed.elastic.metrics.prof` decorator
+to conveniently and succinctly profile functions
+
+::
+
+  # -- in module examples.foobar --
+
+  import torch.distributed.elastic.metrics as metrics
+
+  metrics.configure(metrics.ConsoleMetricsHandler(), "foobar")
+  metrics.configure(metrics.ConsoleMetricsHandler(), "Bar")
+
+  @metrics.prof
+  def foo():
+    pass
+
+  class Bar():
+
+    @metrics.prof
+    def baz():
+        pass
+
+``@metrics.prof`` will publish the following metrics
+::
+
+  .success - 1 if the function finished successfully
+  .failure - 1 if the function threw an exception
+  .duration.ms - function duration in milliseconds
+
+**Configuring Metrics Handler**:
+
+`torch.distributed.elastic.metrics.MetricHandler` is responsible for emitting
+the added metric values to a particular destination. Metric groups can be
+configured with different metric handlers.
+
+By default torchelastic emits all metrics to ``/dev/null``.
+By adding the following configuration metrics,
+``torchelastic`` and ``my_app`` metric groups will be printed out to
+console.
+
+::
+
+  import torch.distributed.elastic.metrics as metrics
+
+  metrics.configure(metrics.ConsoleMetricHandler(), group = "torchelastic")
+  metrics.configure(metrics.ConsoleMetricHandler(), group = "my_app")
+
+**Writing a Custom Metric Handler**:
+
+If you want your metrics to be emitted to a custom location, implement
+the `torch.distributed.elastic.metrics.MetricHandler` interface
+and configure your job to use your custom metric handler.
+
+Below is a toy example that prints the metrics to ``stdout``
+
+::
+
+  import torch.distributed.elastic.metrics as metrics
+
+  class StdoutMetricHandler(metrics.MetricHandler):
+     def emit(self, metric_data):
+         ts = metric_data.timestamp
+         group = metric_data.group_name
+         name = metric_data.name
+         value = metric_data.value
+         print(f"[{ts}][{group}]: {name}={value}")
+
+  metrics.configure(StdoutMetricHandler(), group="my_app")
+
+Now all metrics in the group ``my_app`` will be printed to stdout as:
+
+::
+
+  [1574213883.4182858][my_app]: my_metric=
+  [1574213940.5237644][my_app]: my_metric=
+
+"""
+
+from typing import Optional
+
+from .api import (  # noqa: F401
+    configure,
+    ConsoleMetricHandler,
+    get_elapsed_time_ms,
+    getStream,
+    MetricData,
+    MetricHandler,
+    MetricsConfig,
+    NullMetricHandler,
+    prof,
+    profile,
+    publish_metric,
+    put_metric,
+)
+
+
+def initialize_metrics(cfg: Optional[MetricsConfig] = None):
+    pass
+
+
+try:
+    from torch.distributed.elastic.metrics.static_init import *  # type: ignore[import] # noqa: F401 F403
+except ModuleNotFoundError:
+    pass
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/metrics/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/metrics/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..93110b76ec1bf9eceaa76dae61417bedff09a46d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/metrics/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/metrics/__pycache__/api.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/metrics/__pycache__/api.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0360361410060958c9e26ff8f45b2fa061fcea47
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/metrics/__pycache__/api.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/metrics/api.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/metrics/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c07d3b5c47bbd50acd203bb9c326dcb325eea2e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/metrics/api.py
@@ -0,0 +1,216 @@
+#!/usr/bin/env python3
+# mypy: allow-untyped-defs
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+import abc
+import time
+from collections import namedtuple
+from functools import wraps
+from typing import Dict, Optional
+from typing_extensions import deprecated
+
+
+__all__ = [
+    "MetricsConfig",
+    "MetricHandler",
+    "ConsoleMetricHandler",
+    "NullMetricHandler",
+    "MetricStream",
+    "configure",
+    "getStream",
+    "prof",
+    "profile",
+    "put_metric",
+    "publish_metric",
+    "get_elapsed_time_ms",
+    "MetricData",
+]
+
+MetricData = namedtuple("MetricData", ["timestamp", "group_name", "name", "value"])
+
+
+class MetricsConfig:
+    __slots__ = ["params"]
+
+    def __init__(self, params: Optional[Dict[str, str]] = None):
+        self.params = params
+        if self.params is None:
+            self.params = {}
+
+
+class MetricHandler(abc.ABC):
+    @abc.abstractmethod
+    def emit(self, metric_data: MetricData):
+        pass
+
+
+class ConsoleMetricHandler(MetricHandler):
+    def emit(self, metric_data: MetricData):
+        print(
+            f"[{metric_data.timestamp}][{metric_data.group_name}]: {metric_data.name}={metric_data.value}"
+        )
+
+
+class NullMetricHandler(MetricHandler):
+    def emit(self, metric_data: MetricData):
+        pass
+
+
+class MetricStream:
+    def __init__(self, group_name: str, handler: MetricHandler):
+        self.group_name = group_name
+        self.handler = handler
+
+    def add_value(self, metric_name: str, metric_value: int):
+        self.handler.emit(
+            MetricData(time.time(), self.group_name, metric_name, metric_value)
+        )
+
+
+_metrics_map: Dict[str, MetricHandler] = {}
+_default_metrics_handler: MetricHandler = NullMetricHandler()
+
+
+# pyre-fixme[9]: group has type `str`; used as `None`.
+def configure(handler: MetricHandler, group: Optional[str] = None):
+    if group is None:
+        global _default_metrics_handler
+        # pyre-fixme[9]: _default_metrics_handler has type `NullMetricHandler`; used
+        #  as `MetricHandler`.
+        _default_metrics_handler = handler
+    else:
+        _metrics_map[group] = handler
+
+
+def getStream(group: str):
+    if group in _metrics_map:
+        handler = _metrics_map[group]
+    else:
+        handler = _default_metrics_handler
+    return MetricStream(group, handler)
+
+
+def _get_metric_name(fn):
+    qualname = fn.__qualname__
+    split = qualname.split(".")
+    if len(split) == 1:
+        module = fn.__module__
+        if module:
+            return module.split(".")[-1] + "." + split[0]
+        else:
+            return split[0]
+    else:
+        return qualname
+
+
+def prof(fn=None, group: str = "torchelastic"):
+    r"""
+    @profile decorator publishes duration.ms, count, success, failure metrics for the function that it decorates.
+
+    The metric name defaults to the qualified name (``class_name.def_name``) of the function.
+    If the function does not belong to a class, it uses the leaf module name instead.
+
+    Usage
+
+    ::
+
+     @metrics.prof
+     def x():
+         pass
+
+     @metrics.prof(group="agent")
+     def y():
+         pass
+    """
+
+    def wrap(f):
+        @wraps(f)
+        def wrapper(*args, **kwargs):
+            key = _get_metric_name(f)
+            try:
+                start = time.time()
+                result = f(*args, **kwargs)
+                put_metric(f"{key}.success", 1, group)
+            except Exception:
+                put_metric(f"{key}.failure", 1, group)
+                raise
+            finally:
+                put_metric(f"{key}.duration.ms", get_elapsed_time_ms(start), group)  # type: ignore[possibly-undefined]
+            return result
+
+        return wrapper
+
+    if fn:
+        return wrap(fn)
+    else:
+        return wrap
+
+
+@deprecated("Deprecated, use `@prof` instead", category=FutureWarning)
+def profile(group=None):
+    """
+    @profile decorator adds latency and success/failure metrics to any given function.
+
+    Usage
+
+    ::
+
+     @metrics.profile("my_metric_group")
+     def some_function():
+    """
+
+    def wrap(func):
+        @wraps(func)
+        def wrapper(*args, **kwargs):
+            try:
+                start_time = time.time()
+                result = func(*args, **kwargs)
+                publish_metric(group, f"{func.__name__}.success", 1)
+            except Exception:
+                publish_metric(group, f"{func.__name__}.failure", 1)
+                raise
+            finally:
+                publish_metric(
+                    group,
+                    f"{func.__name__}.duration.ms",
+                    get_elapsed_time_ms(start_time),  # type: ignore[possibly-undefined]
+                )
+            return result
+
+        return wrapper
+
+    return wrap
+
+
+def put_metric(metric_name: str, metric_value: int, metric_group: str = "torchelastic"):
+    """
+    Publish a metric data point.
+
+    Usage
+
+    ::
+
+     put_metric("metric_name", 1)
+     put_metric("metric_name", 1, "metric_group_name")
+    """
+    getStream(metric_group).add_value(metric_name, metric_value)
+
+
+@deprecated(
+    "Deprecated, use `put_metric(metric_group)(metric_name, metric_value)` instead",
+    category=FutureWarning,
+)
+def publish_metric(metric_group: str, metric_name: str, metric_value: int):
+    metric_stream = getStream(metric_group)
+    metric_stream.add_value(metric_name, metric_value)
+
+
+def get_elapsed_time_ms(start_time_in_seconds: float):
+    """Return the elapsed time in millis from the given start time."""
+    end_time = time.time()
+    return int((end_time - start_time_in_seconds) * 1000)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..21cb5e47d4419216212c6c609a515643593e95b7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/__init__.py
@@ -0,0 +1,233 @@
+#!/usr/bin/env python3
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+"""
+Library that launches and manages ``n`` copies of worker subprocesses either specified by a function or a binary.
+
+For functions, it uses ``torch.multiprocessing`` (and therefore python
+``multiprocessing``) to spawn/fork worker processes. For binaries it uses python
+``subprocessing.Popen`` to create worker processes.
+
+
+Usage 1: Launching two trainers as a function
+
+::
+
+ from torch.distributed.elastic.multiprocessing import Std, start_processes
+
+ def trainer(a, b, c):
+     pass # train
+
+
+ # runs two trainers
+ # LOCAL_RANK=0 trainer(1,2,3)
+ # LOCAL_RANK=1 trainer(4,5,6)
+ ctx = start_processes(
+         name="trainer",
+         entrypoint=trainer,
+         args={0: (1,2,3), 1: (4,5,6)},
+         envs={0: {"LOCAL_RANK": 0}, 1: {"LOCAL_RANK": 1}},
+         log_dir="/tmp/foobar",
+         redirects=Std.ALL, # write all worker stdout/stderr to a log file
+         tee={0: Std.ERR}, # tee only local rank 0's stderr to console
+       )
+
+ # waits for all copies of trainer to finish
+ ctx.wait()
+
+Usage 2: Launching 2 echo workers as a binary
+
+::
+
+ # same as invoking
+ # echo hello
+ # echo world > stdout.log
+ ctx = start_processes(
+         name="echo"
+         entrypoint="echo",
+         log_dir="/tmp/foobar",
+         args={0: "hello", 1: "world"},
+         redirects={1: Std.OUT},
+        )
+
+Just like ``torch.multiprocessing``, the return value of the function
+:func:`start_processes` is a process context (:class:`api.PContext`). If a function
+was launched, a :class:`api.MultiprocessContext` is returned and if a binary
+was launched a :class:`api.SubprocessContext` is returned. Both are specific
+implementations of the parent :class:`api.PContext` class.
+"""
+
+from typing import Callable, Dict, Optional, Tuple, Union
+
+from torch.distributed.elastic.multiprocessing.api import (  # noqa: F401
+    _validate_full_rank,
+    DefaultLogsSpecs,
+    LogsDest,
+    LogsSpecs,
+    MultiprocessContext,
+    PContext,
+    ProcessFailure,
+    RunProcsResult,
+    SignalException,
+    Std,
+    SubprocessContext,
+    to_map,
+)
+from torch.distributed.elastic.utils.logging import get_logger
+
+
+__all__ = [
+    "start_processes",
+    "MultiprocessContext",
+    "PContext",
+    "ProcessFailure",
+    "RunProcsResult",
+    "SignalException",
+    "Std",
+    "LogsDest",
+    "LogsSpecs",
+    "DefaultLogsSpecs",
+    "SubprocessContext",
+    "to_map",
+]
+
+
+def start_processes(
+    name: str,
+    entrypoint: Union[Callable, str],
+    args: Dict[int, Tuple],
+    envs: Dict[int, Dict[str, str]],
+    logs_specs: LogsSpecs,
+    log_line_prefixes: Optional[Dict[int, str]] = None,
+    start_method: str = "spawn",
+) -> PContext:
+    """
+    Start ``n`` copies of ``entrypoint`` processes with the provided options.
+
+    ``entrypoint`` is either a ``Callable`` (function) or a ``str`` (binary).
+    The number of copies is determined by the number of entries for ``args`` and
+    ``envs`` arguments, which need to have the same key set.
+
+    ``args`` and ``env`` parameters are the arguments and environment variables
+    to pass down to the entrypoint mapped by the replica index (local rank).
+    All local ranks must be accounted for.
+    That is, the keyset should be ``{0,1,...,(nprocs-1)}``.
+
+    .. note:: When the ``entrypoint`` is a binary (``str``), ``args`` can only be strings.
+              If any other type is given, then it is casted to a string representation
+              (e.g. ``str(arg1)``). Furthermore, a binary failure will only write
+              an ``error.json`` error file if the main function is annotated with
+              ``torch.distributed.elastic.multiprocessing.errors.record``. For function launches,
+              this is done by default and there is no need to manually annotate
+              with the ``@record`` annotation.
+
+    ``redirects`` and ``tee`` are bitmasks specifying which std stream(s) to redirect
+    to a log file in the ``log_dir``. Valid mask values are defined in ``Std``.
+    To redirect/tee only certain local ranks, pass ``redirects`` as a map with the key as
+    the local rank to specify the redirect behavior for.
+    Any missing local ranks will default to ``Std.NONE``.
+
+    ``tee`` acts like the unix "tee" command in that it redirects + prints to console.
+    To avoid worker stdout/stderr from printing to console, use the ``redirects`` parameter.
+
+    For each process, the ``log_dir`` will contain:
+
+    #. ``{local_rank}/error.json``: if the process failed, a file with the error info
+    #. ``{local_rank}/stdout.json``: if ``redirect & STDOUT == STDOUT``
+    #. ``{local_rank}/stderr.json``: if ``redirect & STDERR == STDERR``
+
+    .. note:: It is expected that the ``log_dir`` exists, is empty, and is a directory.
+
+    Example:
+    ::
+
+     log_dir = "/tmp/test"
+
+     # ok; two copies of foo: foo("bar0"), foo("bar1")
+     start_processes(
+        name="trainer",
+        entrypoint=foo,
+        args:{0:("bar0",), 1:("bar1",),
+        envs:{0:{}, 1:{}},
+        log_dir=log_dir
+     )
+
+     # invalid; envs missing for local rank 1
+     start_processes(
+        name="trainer",
+        entrypoint=foo,
+        args:{0:("bar0",), 1:("bar1",),
+        envs:{0:{}},
+        log_dir=log_dir
+     )
+
+     # ok; two copies of /usr/bin/touch: touch file1, touch file2
+     start_processes(
+        name="trainer",
+        entrypoint="/usr/bin/touch",
+        args:{0:("file1",), 1:("file2",),
+        envs:{0:{}, 1:{}},
+        log_dir=log_dir
+      )
+
+     # caution; arguments casted to string, runs:
+     # echo "1" "2" "3" and echo "[1, 2, 3]"
+     start_processes(
+        name="trainer",
+        entrypoint="/usr/bin/echo",
+        args:{0:(1,2,3), 1:([1,2,3],),
+        envs:{0:{}, 1:{}},
+        log_dir=log_dir
+      )
+
+    Args:
+        name: a human readable short name that describes what the processes are
+              (used as header when tee'ing stdout/stderr outputs)
+        entrypoint: either a ``Callable`` (function) or ``cmd`` (binary)
+        args: arguments to each replica
+        envs: env vars to each replica
+        log_dir: directory used to write log files
+        start_method: multiprocessing start method (spawn, fork, forkserver)
+                      ignored for binaries
+        redirects: which std streams to redirect to a log file
+        tee: which std streams to redirect + print to console
+        local_ranks_filter: which ranks' logs to print to console
+
+    """
+
+    nprocs = len(args)
+    _validate_full_rank(args, nprocs, "args")
+    _validate_full_rank(envs, nprocs, "envs")
+
+    context: PContext
+    if isinstance(entrypoint, str):
+        context = SubprocessContext(
+            name=name,
+            entrypoint=entrypoint,
+            args=args,
+            envs=envs,
+            logs_specs=logs_specs,
+            log_line_prefixes=log_line_prefixes,
+        )
+    else:
+        context = MultiprocessContext(
+            name=name,
+            entrypoint=entrypoint,
+            args=args,
+            envs=envs,
+            log_line_prefixes=log_line_prefixes,
+            start_method=start_method,
+            logs_specs=logs_specs,
+        )
+
+    try:
+        context.start()
+        return context
+    except Exception:
+        context.close()
+        raise
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..654113dc35078fa0474db0e32044b8cc2813c627
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/__pycache__/api.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/__pycache__/api.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a138195b3d3c125530faa017c20cba42e8112054
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/__pycache__/api.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/__pycache__/redirects.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/__pycache__/redirects.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9cee00d01a52108457a2b0a14ecf596ff573bb5f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/__pycache__/redirects.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/__pycache__/tail_log.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/__pycache__/tail_log.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..49641b0f9aaadd2b9a674f5f66f1a40360bcfbee
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/__pycache__/tail_log.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/api.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..5befbffe49573db01280a9c7c8999aed67ad4365
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/api.py
@@ -0,0 +1,923 @@
+#!/usr/bin/env python3
+# mypy: allow-untyped-defs
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+import abc
+import logging
+import os
+import re
+import shutil
+import signal
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+from abc import ABC, abstractmethod
+from contextlib import nullcontext
+from dataclasses import dataclass, field
+from enum import IntFlag
+from multiprocessing import synchronize
+from types import FrameType
+from typing import Any, Callable, Dict, Optional, Set, Tuple, Union
+
+import torch.multiprocessing as mp
+from torch.distributed.elastic.multiprocessing.errors import ProcessFailure, record
+from torch.distributed.elastic.multiprocessing.redirects import (
+    redirect_stderr,
+    redirect_stdout,
+)
+from torch.distributed.elastic.multiprocessing.subprocess_handler import (
+    get_subprocess_handler,
+    SubprocessHandler,
+)
+from torch.distributed.elastic.multiprocessing.tail_log import TailLog
+
+
+IS_WINDOWS = sys.platform == "win32"
+IS_MACOS = sys.platform == "darwin"
+
+
+logger = logging.getLogger(__name__)
+
+__all__ = [
+    "DefaultLogsSpecs",
+    "SignalException",
+    "Std",
+    "to_map",
+    "RunProcsResult",
+    "PContext",
+    "get_std_cm",
+    "MultiprocessContext",
+    "SubprocessContext",
+    "LogsDest",
+    "LogsSpecs",
+]
+
+
+class SignalException(Exception):
+    """
+    Exception is raised inside the torchelastic agent process by the termination handler
+    if the death signal got received by the process.
+    """
+
+    def __init__(self, msg: str, sigval: signal.Signals) -> None:
+        super().__init__(msg)
+        self.sigval = sigval
+
+
+def _terminate_process_handler(signum: int, frame: Optional[FrameType]) -> None:
+    """Termination handler that raises exceptions on the main process.
+
+    When the process receives death signal(SIGTERM, SIGINT), this termination handler will
+    be invoked. It raises the ``SignalException`` exception that should be processed by the
+    user code. Python does not terminate process after the termination handler is finished,
+    so the exception should not be silently ignored, otherwise the process will never
+    be terminated.
+    """
+    sigval = signal.Signals(signum)
+    raise SignalException(f"Process {os.getpid()} got signal: {sigval}", sigval=sigval)
+
+
+def _get_kill_signal() -> signal.Signals:
+    """Get the kill signal. SIGKILL for unix, CTRL_C_EVENT for windows."""
+    if IS_WINDOWS:
+        return signal.CTRL_C_EVENT  # type: ignore[attr-defined] # noqa: F821
+    else:
+        return signal.SIGKILL
+
+
+def _get_default_signal() -> signal.Signals:
+    """Get the default termination signal. SIGTERM for unix, CTRL_C_EVENT for windows."""
+    if IS_WINDOWS:
+        return signal.CTRL_C_EVENT  # type: ignore[attr-defined] # noqa: F821
+    else:
+        return signal.SIGTERM
+
+
+def _validate_full_rank(d: Dict[int, Any], nprocs: int, what: str):
+    actual_keys = set(d.keys())
+    expected_keys = set(range(nprocs))
+
+    if actual_keys != expected_keys:
+        raise RuntimeError(
+            f"{what}, local rank mapping mismatch,"
+            f" expected: {expected_keys}, actual: {actual_keys}"
+        )
+
+
+_MAPPING_REGEX = r"^(\d:[0123],)*(\d:[0123])$"
+_VALUE_REGEX = r"^[0123]$"
+
+
+class Std(IntFlag):
+    NONE = 0
+    OUT = 1
+    ERR = 2
+    ALL = OUT | ERR
+
+    @classmethod
+    def from_str(cls, vm: str) -> Union["Std", Dict[int, "Std"]]:
+        """
+        Example:
+        ::
+
+         from_str("0") -> Std.NONE
+         from_str("1") -> Std.OUT
+         from_str("0:3,1:0,2:1,3:2") -> {0: Std.ALL, 1: Std.NONE, 2: Std.OUT, 3: Std.ERR}
+
+        Any other input raises an exception
+        """
+
+        def to_std(v: str) -> Std:  # type: ignore[return]
+            s = Std(int(v))
+            if s in Std:
+                return s
+            # return None -> should NEVER reach here since we regex check input
+
+        if re.match(_VALUE_REGEX, vm):  # vm is a number (e.g. 0)
+            return to_std(vm)
+        elif re.match(_MAPPING_REGEX, vm):  # vm is a mapping (e.g. 0:1,1:2)
+            d: Dict[int, Std] = {}
+            for m in vm.split(","):
+                i, v = m.split(":")
+                d[int(i)] = to_std(v)
+            return d
+        else:
+            raise ValueError(
+                f"{vm} does not match: <{_VALUE_REGEX}> or <{_MAPPING_REGEX}>"
+            )
+
+
+def to_map(
+    val_or_map: Union[Std, Dict[int, Std]], local_world_size: int
+) -> Dict[int, Std]:
+    """
+    Certain APIs take redirect settings either as a single value (e.g. apply to all
+    local ranks) or as an explicit user-provided mapping. This method is a convenience
+    method that converts a value or mapping into a mapping.
+
+    Example:
+    ::
+
+     to_map(Std.OUT, local_world_size=2) # returns: {0: Std.OUT, 1: Std.OUT}
+     to_map({1: Std.OUT}, local_world_size=2) # returns: {0: Std.NONE, 1: Std.OUT}
+     to_map({0: Std.OUT, 1: Std.OUT}, local_world_size=2) # returns: {0: Std.OUT, 1: Std.OUT}
+    """
+    if isinstance(val_or_map, Std):
+        return dict.fromkeys(range(local_world_size), val_or_map)
+    else:
+        map = {}
+        for i in range(local_world_size):
+            map[i] = val_or_map.get(i, Std.NONE)
+        return map
+
+
+@dataclass
+class LogsDest:
+    """
+    For each log type, holds mapping of local rank ids to file paths.
+    """
+
+    stdouts: Dict[int, str] = field(default_factory=dict)
+    stderrs: Dict[int, str] = field(default_factory=dict)
+    tee_stdouts: Dict[int, str] = field(default_factory=dict)
+    tee_stderrs: Dict[int, str] = field(default_factory=dict)
+    error_files: Dict[int, str] = field(default_factory=dict)
+
+
+class LogsSpecs(ABC):
+    """
+    Defines logs processing and redirection for each worker process.
+
+    Args:
+        log_dir:
+            Base directory where logs will be written.
+        redirects:
+            Streams to redirect to files. Pass a single ``Std``
+            enum to redirect for all workers, or a mapping keyed
+            by local_rank to selectively redirect.
+        tee:
+            Streams to duplicate to stdout/stderr.
+            Pass a single ``Std`` enum to duplicate streams for all workers,
+            or a mapping keyed by local_rank to selectively duplicate.
+    """
+
+    def __init__(
+        self,
+        log_dir: Optional[str] = None,
+        redirects: Union[Std, Dict[int, Std]] = Std.NONE,
+        tee: Union[Std, Dict[int, Std]] = Std.NONE,
+        local_ranks_filter: Optional[Set[int]] = None,
+    ) -> None:
+        self._root_log_dir = log_dir
+        self._redirects = redirects
+        self._tee = tee
+        self._local_ranks_filter = local_ranks_filter
+
+    @abstractmethod
+    def reify(
+        self,
+        envs: Dict[int, Dict[str, str]],
+    ) -> LogsDest:
+        """
+        Given the environment variables, builds destination of log files for each of the local ranks.
+
+        Envs parameter contains env variables dict for each of the local ranks, where entries are defined in:
+        :func:`~torchelastic.distributed.elastic.agent.server.local_elastic_agent.LocalElasticAgent._start_workers`.
+        """
+
+    @property
+    @abstractmethod
+    def root_log_dir(self) -> str:
+        pass
+
+
+class DefaultLogsSpecs(LogsSpecs):
+    """
+    Default LogsSpecs implementation:
+
+    - `log_dir` will be created if it doesn't exist
+    - Generates nested folders for each attempt and rank.
+    """
+
+    def __init__(
+        self,
+        log_dir: Optional[str] = None,
+        redirects: Union[Std, Dict[int, Std]] = Std.NONE,
+        tee: Union[Std, Dict[int, Std]] = Std.NONE,
+        local_ranks_filter: Optional[Set[int]] = None,
+    ) -> None:
+        if log_dir != os.devnull:
+            if not log_dir:
+                log_dir = tempfile.mkdtemp(prefix="torchelastic_")
+            elif not os.path.exists(log_dir):
+                os.makedirs(log_dir, exist_ok=True)
+            else:
+                if os.path.isfile(log_dir):
+                    raise NotADirectoryError(f"log_dir: {log_dir} is a file")
+        super().__init__(log_dir, redirects, tee, local_ranks_filter)
+        # initialized only once
+        self._run_log_dir = None
+
+    @property
+    def root_log_dir(self) -> str:
+        return str(self._root_log_dir)
+
+    def _make_log_dir(self, log_dir: Optional[str], rdzv_run_id: str):
+        base_log_dir = log_dir or tempfile.mkdtemp(prefix="torchelastic_")
+        os.makedirs(base_log_dir, exist_ok=True)
+        dir = tempfile.mkdtemp(prefix=f"{rdzv_run_id}_", dir=base_log_dir)
+        logger.info("log directory set to: %s", dir)
+        return dir
+
+    def reify(
+        self,
+        envs: Dict[int, Dict[str, str]],
+    ) -> LogsDest:
+        """
+        Uses following scheme to build log destination paths:
+
+        - `//attempt_//stdout.log`
+        - `//attempt_//stderr.log`
+        - `//attempt_//error.json`
+        """
+        nprocs = len(envs)
+        global_env = {}  # use only to query properies that are not dependent on a rank
+        if nprocs > 0:
+            global_env = envs[0]
+        else:
+            logger.warning(
+                "Empty envs map provided when defining logging destinations."
+            )
+        # Keys are always defined, but values can be missing in unit tests
+        run_id = global_env.get("TORCHELASTIC_RUN_ID", "test_run_id")
+        restart_count = global_env.get("TORCHELASTIC_RESTART_COUNT", "0")
+
+        attempt_log_dir: str = ""
+        if self._root_log_dir != os.devnull:
+            if not self._run_log_dir:
+                self._run_log_dir = self._make_log_dir(self._root_log_dir, run_id)
+
+            attempt_log_dir = os.path.join(self._run_log_dir, f"attempt_{restart_count}")  # type: ignore[call-overload]
+            shutil.rmtree(attempt_log_dir, ignore_errors=True)
+            os.makedirs(attempt_log_dir)
+
+        if self._root_log_dir == os.devnull:
+            attempt_log_dir = os.devnull
+
+        # create subdirs for each local rank in the logs_dir
+        # logs_dir
+        #       |- 0
+        #          |- error.json
+        #          |- stdout.log
+        #          |- stderr.log
+        #       |- ...
+        #       |- (nprocs-1)
+        redirs = to_map(self._redirects, nprocs)
+        ts = to_map(self._tee, nprocs)
+
+        # to tee stdout/stderr we first redirect into a file
+        # then tail -f stdout.log/stderr.log so add tee settings to redirects
+        for local_rank, tee_std in ts.items():
+            redirect_std = redirs[local_rank]
+            redirs[local_rank] = redirect_std | tee_std
+
+        SYS_STREAM = ""  # special case to indicate to output to console
+        stdouts = dict.fromkeys(range(nprocs), SYS_STREAM)
+        stderrs = dict.fromkeys(range(nprocs), SYS_STREAM)
+        tee_stdouts: Dict[int, str] = {}
+        tee_stderrs: Dict[int, str] = {}
+        error_files = {}
+
+        for local_rank in range(nprocs):
+            if attempt_log_dir == os.devnull:
+                tee_stdouts[local_rank] = os.devnull
+                tee_stderrs[local_rank] = os.devnull
+                error_files[local_rank] = os.devnull
+                envs[local_rank]["TORCHELASTIC_ERROR_FILE"] = ""
+            else:
+                clogdir = os.path.join(attempt_log_dir, str(local_rank))
+                os.mkdir(clogdir)
+
+                rd = redirs[local_rank]
+                if (rd & Std.OUT) == Std.OUT:
+                    stdouts[local_rank] = os.path.join(clogdir, "stdout.log")
+                if (rd & Std.ERR) == Std.ERR:
+                    stderrs[local_rank] = os.path.join(clogdir, "stderr.log")
+
+                t = ts[local_rank]
+                if t & Std.OUT == Std.OUT:
+                    tee_stdouts[local_rank] = stdouts[local_rank]
+                if t & Std.ERR == Std.ERR:
+                    tee_stderrs[local_rank] = stderrs[local_rank]
+
+                if (
+                    self._local_ranks_filter
+                    and local_rank not in self._local_ranks_filter
+                ):
+                    # If stream is tee'd, only write to file, but don't tail
+                    if local_rank in tee_stdouts:
+                        tee_stdouts.pop(local_rank, None)
+                    if local_rank in tee_stderrs:
+                        tee_stderrs.pop(local_rank, None)
+
+                    # If stream is not redirected, don't print
+                    if stdouts[local_rank] == SYS_STREAM:
+                        stdouts[local_rank] = os.devnull
+                    if stderrs[local_rank] == SYS_STREAM:
+                        stderrs[local_rank] = os.devnull
+
+                error_file = os.path.join(clogdir, "error.json")
+                error_files[local_rank] = error_file
+                logger.info(
+                    "Setting worker%s reply file to: %s", local_rank, error_file
+                )
+                envs[local_rank]["TORCHELASTIC_ERROR_FILE"] = error_file
+
+        return LogsDest(stdouts, stderrs, tee_stdouts, tee_stderrs, error_files)
+
+    def __repr__(self) -> str:
+        return (
+            f"DefaultLogsSpecs(root_log_dir={self._root_log_dir}, redirects={self._redirects}, "
+            f"tee={self._tee}, local_ranks_filter={self._local_ranks_filter})"
+        )
+
+    def __eq__(self, other: object) -> bool:
+        if not isinstance(other, DefaultLogsSpecs):
+            return False
+
+        return (
+            self._root_log_dir == other._root_log_dir
+            and self._redirects == other._redirects
+            and self._tee == other._tee
+            and self._local_ranks_filter == other._local_ranks_filter
+        )
+
+
+@dataclass
+class RunProcsResult:
+    """
+    Results of a completed run of processes started with ``start_processes()``. Returned by ``PContext``.
+
+    Note the following:
+
+    1. All fields are mapped by local rank
+    2. ``return_values`` - only populated for functions (not the binaries).
+    3. ``stdouts`` - path to stdout.log (empty string if no redirect)
+    4. ``stderrs`` - path to stderr.log (empty string if no redirect)
+
+    """
+
+    return_values: Dict[int, Any] = field(default_factory=dict)
+    failures: Dict[int, ProcessFailure] = field(default_factory=dict)
+    stdouts: Dict[int, str] = field(default_factory=dict)
+    stderrs: Dict[int, str] = field(default_factory=dict)
+
+    def is_failed(self) -> bool:
+        return len(self.failures) > 0
+
+
+class PContext(abc.ABC):
+    """
+    The base class that standardizes operations over a set of processes that are launched via different mechanisms.
+
+    The name ``PContext`` is intentional to disambiguate with ``torch.multiprocessing.ProcessContext``.
+
+    .. warning:: stdouts and stderrs should ALWAYS be a superset of
+                 tee_stdouts and tee_stderrs (respectively) this is b/c
+                 tee is implemented as a redirect + tail -f 
+    """
+
+    def __init__(
+        self,
+        name: str,
+        entrypoint: Union[Callable, str],
+        args: Dict[int, Tuple],
+        envs: Dict[int, Dict[str, str]],
+        logs_specs: LogsSpecs,
+        log_line_prefixes: Optional[Dict[int, str]] = None,
+    ):
+        self.name = name
+        # validate that all mappings have the same number of keys and
+        # all local ranks are accounted for
+        nprocs = len(args)
+
+        # TODO log_line_prefixes can be exanded too
+        logs_dest = logs_specs.reify(envs)
+
+        _validate_full_rank(logs_dest.stdouts, nprocs, "stdouts")
+        _validate_full_rank(logs_dest.stderrs, nprocs, "stderrs")
+
+        self.entrypoint = entrypoint
+        self.args = args
+        self.envs = envs
+        self.stdouts = logs_dest.stdouts
+        self.stderrs = logs_dest.stderrs
+        self.error_files = logs_dest.error_files
+        self.nprocs = nprocs
+
+        self._stdout_tail = TailLog(
+            name, logs_dest.tee_stdouts, sys.stdout, log_line_prefixes
+        )
+        self._stderr_tail = TailLog(
+            name, logs_dest.tee_stderrs, sys.stderr, log_line_prefixes
+        )
+
+    def start(self) -> None:
+        """Start processes using parameters defined in the constructor."""
+        if threading.current_thread() is threading.main_thread():
+            signal.signal(signal.SIGTERM, _terminate_process_handler)
+            signal.signal(signal.SIGINT, _terminate_process_handler)
+            if not IS_WINDOWS:
+                signal.signal(signal.SIGHUP, _terminate_process_handler)
+                signal.signal(signal.SIGQUIT, _terminate_process_handler)
+        else:
+            logger.warning(
+                "Failed to register signal handlers since torchelastic is running on a child thread. "
+                "This could lead to orphaned worker processes if the torchrun is terminated."
+            )
+        self._start()
+        self._stdout_tail.start()
+        self._stderr_tail.start()
+
+    @abc.abstractmethod
+    def _start(self) -> None:
+        """Start processes using strategy defined in a particular context."""
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def _poll(self) -> Optional[RunProcsResult]:
+        """
+        Poll the run status of the processes running under this context.
+        This method follows an "all-or-nothing" policy and returns
+        a ``RunProcessResults`` object if either all processes complete
+        successfully or any process fails. Returns ``None`` if
+        all processes are still running.
+        """
+        raise NotImplementedError
+
+    def wait(self, timeout: float = -1, period: float = 1) -> Optional[RunProcsResult]:
+        """
+        Wait for the specified ``timeout`` seconds, polling every ``period`` seconds
+        for the processes to be done. Returns ``None`` if the processes are still running
+        on timeout expiry. Negative timeout values are interpreted as "wait-forever".
+        A timeout value of zero simply queries the status of the processes (e.g. equivalent
+        to a poll).
+
+        ..note: Multiprocessing library registers SIGTERM and SIGINT signal handlers that raise
+                ``SignalException`` when the signals received. It is up to the consumer of the code
+                to properly handle the exception. It is important not to swallow the exception otherwise
+                the process would not terminate. Example of the typical workflow can be:
+
+        .. code-block:: python
+            pc = start_processes(...)
+            try:
+                pc.wait(1)
+                .. do some other work
+            except SignalException as e:
+                pc.shutdown(e.sigval, timeout=30)
+
+        If SIGTERM or SIGINT occurs, the code above will try to shutdown child processes by propagating
+        received signal. If child processes will not terminate in the timeout time, the process will send
+        the SIGKILL.
+        """
+        if timeout == 0:
+            return self._poll()
+
+        if timeout < 0:
+            timeout = sys.maxsize
+
+        expiry = time.time() + timeout
+        while time.time() < expiry:
+            pr = self._poll()
+            if pr:
+                return pr
+            time.sleep(period)
+
+        return None
+
+    @abc.abstractmethod
+    def pids(self) -> Dict[int, int]:
+        """Return pids of processes mapped by their respective local_ranks."""
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def _close(self, death_sig: signal.Signals, timeout: int = 30) -> None:
+        r"""
+        Terminates all processes managed by this context and cleans up any
+        meta resources (e.g. redirect, error_file files).
+        """
+        raise NotImplementedError
+
+    def close(
+        self, death_sig: Optional[signal.Signals] = None, timeout: int = 30
+    ) -> None:
+        r"""
+        Terminates all processes managed by this context and cleans up any
+        meta resources (e.g. redirect, error_file files).
+
+        Args:
+            death_sig: Death signal to terminate processes.
+            timeout: Time to wait for processes to finish, if process is
+                still alive after this time, it will be terminated via SIGKILL.
+        """
+        if not death_sig:
+            death_sig = _get_default_signal()
+        self._close(death_sig=death_sig, timeout=timeout)
+        if self._stdout_tail:
+            self._stdout_tail.stop()
+        if self._stderr_tail:
+            self._stderr_tail.stop()
+
+
+def get_std_cm(std_rd: str, redirect_fn):
+    if IS_WINDOWS or IS_MACOS or not std_rd:
+        return nullcontext()
+    else:
+        return redirect_fn(std_rd)
+
+
+def _wrap(
+    local_rank: int,
+    fn: Callable,
+    args: Dict[int, Tuple],
+    envs: Dict[int, Dict[str, str]],
+    stdout_redirects: Dict[int, str],  # redirect file for stdout (to console if None)
+    stderr_redirects: Dict[int, str],  # redirect file for stderr (to console if None)
+    ret_vals: Dict[int, mp.SimpleQueue],
+    queue_finished_reading_event: synchronize.Event,
+) -> None:
+    # get the per-rank params up front so we fail fast if no mapping is found
+    args_ = args[local_rank]
+    env_ = envs[local_rank]
+    ret_val_ = ret_vals[local_rank]
+
+    stdout_rd = stdout_redirects[local_rank]
+    stderr_rd = stderr_redirects[local_rank]
+
+    stdout_cm = get_std_cm(stdout_rd, redirect_stdout)
+    stderr_cm = get_std_cm(stderr_rd, redirect_stderr)
+
+    for k, v in env_.items():
+        os.environ[k] = v
+
+    with stdout_cm, stderr_cm:
+        ret = record(fn)(*args_)
+    ret_val_.put(ret)
+    queue_finished_reading_event.wait()
+
+
+class MultiprocessContext(PContext):
+    """``PContext`` holding worker processes invoked as a function."""
+
+    def __init__(
+        self,
+        name: str,
+        entrypoint: Callable,
+        args: Dict[int, Tuple],
+        envs: Dict[int, Dict[str, str]],
+        start_method: str,
+        logs_specs: LogsSpecs,
+        log_line_prefixes: Optional[Dict[int, str]] = None,
+    ):
+        super().__init__(
+            name,
+            entrypoint,
+            args,
+            envs,
+            logs_specs,
+            log_line_prefixes,
+        )
+
+        self.start_method = start_method
+        # each ret_val queue will always contain a single element.
+        self._ret_vals = {
+            local_rank: mp.get_context(self.start_method).SimpleQueue()
+            for local_rank in range(self.nprocs)
+        }
+
+        # see comments in ``join()`` for what this is
+        self._return_values: Dict[int, Any] = {}
+        self._pc: Optional[mp.ProcessContext] = None
+        # Note: set method should ONLY be invoked for the use case when all processes finished
+        # successfully. If any process died on event.wait() calling set() method will deadlock.
+        self._worker_finished_event = mp.get_context(self.start_method).Event()
+
+    def _start(self):
+        if self._pc:
+            raise ValueError(
+                "The process context already initialized."
+                " Most likely the start method got called twice."
+            )
+        self._pc = mp.start_processes(
+            fn=_wrap,
+            args=(
+                self.entrypoint,
+                self.args,
+                self.envs,
+                self.stdouts,
+                self.stderrs,
+                self._ret_vals,
+                self._worker_finished_event,
+            ),
+            nprocs=self.nprocs,
+            join=False,
+            daemon=False,
+            start_method=self.start_method,
+        )
+
+    def _is_done(self) -> bool:
+        return len(self._return_values) == self.nprocs
+
+    def _poll(self) -> Optional[RunProcsResult]:
+        assert self._pc is not None  # assertion for mypy type checker
+
+        try:
+            # torch.mp.ProcessContext Throws an Exception if some/all of
+            # worker processes failed
+            # timeout < 0 checks worker status and return immediately
+            # Join will never return success since we use synchronize.Event to wait
+            # for all processes to finish.
+            self._pc.join(-1)
+
+            # IMPORTANT: we use multiprocessing.Queue to carry worker return values
+            # back to the parent, the worker process will wait before terminating
+            # until all the buffered items are fed by the feeder thread to the underlying
+            # pipe. Hence to prevent deadlocks on large return values,
+            # we opportunistically try queue.get on each join call
+            # See: https://docs.python.org/2/library/multiprocessing.html#all-platforms
+            for local_rank in range(0, self.nprocs):
+                return_queue = self._ret_vals[local_rank]
+                if not return_queue.empty():
+                    # save the return values temporarily into a member var
+                    self._return_values[local_rank] = return_queue.get()
+
+            if self._is_done():
+                # we should ALWAYS have ALL the return values when all the processes are done
+                self._worker_finished_event.set()
+
+                # At this point workers finished running the user function
+                # But the child process might still have not exited. Wait for them.
+                # pc.join() blocks [forever] until "a" proc exits. Loop until all of them exits.
+                while not self._pc.join():
+                    logger.debug(
+                        "entrypoint fn finished, waiting for all child procs to exit..."
+                    )
+
+                _validate_full_rank(
+                    self._return_values, self.nprocs, "return_value queue"
+                )
+                self.close()
+                return RunProcsResult(
+                    return_values=self._return_values,
+                    stdouts=self.stdouts,
+                    stderrs=self.stderrs,
+                )
+            else:
+                return None
+        except (mp.ProcessRaisedException, mp.ProcessExitedException) as e:
+            failed_local_rank = e.error_index
+
+            # entrypoint for MultiprocessContext will always be a Callable
+            fn_name = self.entrypoint.__qualname__  # type: ignore[union-attr]
+            failed_proc = self._pc.processes[failed_local_rank]
+            error_filepath = self.error_files[failed_local_rank]
+
+            logger.exception(
+                "failed (exitcode: %s)"
+                " local_rank: %s (pid: %s)"
+                " of fn: %s (start_method: %s)",
+                failed_proc.exitcode,
+                failed_local_rank,
+                e.pid,
+                fn_name,
+                self.start_method,
+            )
+
+            self.close()
+            return RunProcsResult(
+                failures={
+                    failed_local_rank: ProcessFailure(
+                        local_rank=failed_local_rank,
+                        pid=e.pid,
+                        exitcode=failed_proc.exitcode,
+                        error_file=error_filepath,
+                    )
+                },
+                stdouts=self.stdouts,
+                stderrs=self.stderrs,
+            )
+
+    def pids(self) -> Dict[int, int]:
+        assert self._pc is not None  # assertion for mypy type checking
+        return dict(enumerate(self._pc.pids()))
+
+    def _close(self, death_sig: signal.Signals, timeout: int = 30) -> None:
+        if not self._pc:
+            return
+        for proc in self._pc.processes:
+            if proc.is_alive():
+                logger.warning(
+                    "Closing process %s via signal %s", proc.pid, death_sig.name
+                )
+                try:
+                    os.kill(proc.pid, death_sig)
+                except ProcessLookupError:
+                    # If the process exited because of some reason,
+                    # `ProcessLookupError` will be raised, it is safe to ignore it.
+                    pass
+        end = time.monotonic() + timeout
+        for proc in self._pc.processes:
+            time_to_wait = end - time.monotonic()
+            if time_to_wait <= 0:
+                break
+            proc.join(time_to_wait)
+        for proc in self._pc.processes:
+            if proc.is_alive():
+                logger.warning(
+                    "Unable to shutdown process %s via %s, forcefully exiting via %s",
+                    proc.pid,
+                    death_sig,
+                    _get_kill_signal(),
+                )
+                try:
+                    os.kill(proc.pid, _get_kill_signal())
+                except ProcessLookupError:
+                    # If the process exited because of some reason,
+                    # `ProcessLookupError` will be raised, it is safe to ignore it.
+                    pass
+            proc.join()
+
+
+class SubprocessContext(PContext):
+    """``PContext`` holding worker processes invoked as a binary."""
+
+    def __init__(
+        self,
+        name: str,
+        entrypoint: str,
+        args: Dict[int, Tuple],
+        envs: Dict[int, Dict[str, str]],
+        logs_specs: LogsSpecs,
+        log_line_prefixes: Optional[Dict[int, str]] = None,
+    ):
+        super().__init__(
+            name,
+            entrypoint,
+            args,
+            envs,
+            logs_specs,
+            log_line_prefixes,
+        )
+
+        # state vector; _vdone[local_rank] -> is local_rank finished or not
+        self._running_local_ranks: Set[int] = set(range(self.nprocs))
+        self._failures: Dict[int, ProcessFailure] = {}
+        self.subprocess_handlers: Dict[int, SubprocessHandler] = {}
+
+    def _start(self):
+        if self.subprocess_handlers:
+            raise ValueError(
+                "The subprocess handlers already initialized. Most likely the start method got called twice."
+            )
+        self.subprocess_handlers = {
+            local_rank: get_subprocess_handler(
+                entrypoint=self.entrypoint,  # type: ignore[arg-type] # entrypoint is always a str
+                args=self.args[local_rank],
+                env=self.envs[local_rank],
+                stdout=self.stdouts[local_rank],
+                stderr=self.stderrs[local_rank],
+                local_rank_id=local_rank,
+            )
+            for local_rank in range(self.nprocs)
+        }
+
+    def _poll(self) -> Optional[RunProcsResult]:
+        done_local_ranks = set()
+        for local_rank in self._running_local_ranks:
+            handler = self.subprocess_handlers[local_rank]
+            exitcode = handler.proc.poll()
+            if exitcode is not None:
+                done_local_ranks.add(local_rank)
+                if exitcode != 0:  # failed or signaled
+                    self._failures[local_rank] = ProcessFailure(
+                        local_rank=local_rank,
+                        pid=handler.proc.pid,
+                        exitcode=exitcode,
+                        error_file=self.error_files[local_rank],
+                    )
+                # else: --> succeeded; nothing to do
+
+        self._running_local_ranks.difference_update(done_local_ranks)
+
+        # if ALL procs are finished or ANY have failed
+        if not self._running_local_ranks or self._failures:
+            self.close()  # terminate all running procs
+            result = RunProcsResult(
+                failures=self._failures,
+                stdouts=self.stdouts,
+                stderrs=self.stderrs,
+            )
+            if result.is_failed():
+                first_failure = min(result.failures.values(), key=lambda f: f.timestamp)
+                logger.error(
+                    "failed (exitcode: %s)"
+                    " local_rank: %s (pid: %s)"
+                    " of binary: %s",
+                    first_failure.exitcode,
+                    first_failure.local_rank,
+                    first_failure.pid,
+                    self.entrypoint,
+                )
+            else:
+                # Populate return with dummy values. This provides consistency with MultiprocessingHandler
+                result.return_values = dict.fromkeys(range(self.nprocs))
+
+            return result
+        else:  # there are no failures and procs still running
+            return None
+
+    def pids(self) -> Dict[int, int]:
+        return {
+            local_rank: sh.proc.pid
+            for local_rank, sh in self.subprocess_handlers.items()
+        }
+
+    def _close(self, death_sig: signal.Signals, timeout: int = 30) -> None:
+        if not self.subprocess_handlers:
+            return
+        for handler in self.subprocess_handlers.values():
+            if handler.proc.poll() is None:
+                logger.warning(
+                    "Sending process %s closing signal %s",
+                    handler.proc.pid,
+                    death_sig.name,
+                )
+                handler.close(death_sig=death_sig)
+        end = time.monotonic() + timeout
+        for handler in self.subprocess_handlers.values():
+            time_to_wait = end - time.monotonic()
+            if time_to_wait <= 0:
+                break
+            try:
+                handler.proc.wait(time_to_wait)
+            except subprocess.TimeoutExpired:
+                # Ignore the timeout expired exception, since
+                # the child process will be forcefully terminated via SIGKILL
+                pass
+        for handler in self.subprocess_handlers.values():
+            if handler.proc.poll() is None:
+                logger.warning(
+                    "Unable to shutdown process %s via %s, forcefully exiting via %s",
+                    handler.proc.pid,
+                    death_sig,
+                    _get_kill_signal(),
+                )
+                handler.close(death_sig=_get_kill_signal())
+                handler.proc.wait()
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/errors/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/errors/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2f5ed2d1ab0b81dbcf635245fbd49acc7ed02f79
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/errors/__init__.py
@@ -0,0 +1,383 @@
+#!/usr/bin/env python3
+# mypy: allow-untyped-defs
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+"""
+Each host in a distributed PyTorch job runs with a single TorchElastic agent,
+and multiple workers (as children processes of the TorchElastic agent).
+Since the workers are user-provided (your PyTorch script/job), TorchElastic
+has a way to propagate errors on the trainers through the agent and up to the
+scheduler, which ultimately informs the end-user about the state of the job
+and applies any retry policies.
+
+TorchElastic categorizes errors into 3 categories:
+
++----------------+----------------+--------------------------------------------------------------+
+| Category       | Sub-Category   |  Description                                                 |
++================+================+==============================================================+
+| User Error     | Input Error    | invalid inputs to TorchElastic APIs (e.g. min > max nodes)   |
+|                +----------------+--------------------------------------------------------------+
+|                | Worker Failure | any failures on the worker child process                     |
++----------------+----------------+--------------------------------------------------------------+
+| Platform Error |      n/a       | failures caused by the agent                                 |
++----------------+----------------+--------------------------------------------------------------+
+| Infra Error    |      n/a       | failures outside the domain of the agent and workers         |
+|                |                | (e.g. host failures)                                         |
++----------------+----------------+--------------------------------------------------------------+
+
+All errors other than "Worker Failure" are either raised canonically from the
+agent process or implicitly or explicitly crash the agent process. So the
+standard language (python) provided exception handling strategies apply.
+
+Worker Failures are special because the exception/failure originates on a different
+process from the agent so the error needs to be propagated inter-process
+(e.g. the agent cannot simply ``try-catch`` an exception raised on the worker process).
+
+TorchElastic agents use :func:`torch.distributed.elastic.multiprocessing.start_processes`
+to launch the workers which has a simple file based inter-process error propagation
+built-in.
+
+Any function or binary entrypoint decorated with :func:`record`
+will write uncaught exceptions (with the trace information) to a file specified by the
+environment variable ``TORCHELASTIC_ERROR_FILE``. The parent process (e.g. agent)
+sets this env var on each child it launches, then aggregates the error files for all
+children, and propagates the one with the **smallest** timestamp (e.g. the **first** error).
+"""
+
+import json
+import os
+import signal
+import socket
+import time
+import warnings
+from dataclasses import dataclass, field
+from datetime import datetime
+from functools import wraps
+from string import Template
+from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar
+
+from torch.distributed.elastic.utils.logging import get_logger
+
+from .error_handler import ErrorHandler  # noqa: F401
+from .handlers import get_error_handler  # noqa: F401
+
+
+__all__ = [
+    "ProcessFailure",
+    "ChildFailedError",
+    "record",
+    "ErrorHandler",
+    "get_error_handler",
+]
+
+logger = get_logger(__name__)
+
+
+JSON = Dict
+
+_EMPTY_ERROR_DATA = {"message": ""}
+_NOT_AVAILABLE = ""
+
+T = TypeVar("T")
+
+
+@dataclass
+class ProcessFailure:
+    """
+    Represent the failed process result. When the worker process fails, it may record failure root cause into the file.
+
+    Tries to read the failure timestamp from the provided ``error_file``,
+    if the ``error_file`` does not exist, the timestamp is the current
+    timestamp (seconds since epoch).
+
+    The ``message`` field is a concise explanation of the failure. If
+    the error file exists then the message is obtained from the error file.
+    Otherwise one is generated based on the failure signature.
+
+    .. note:: It is assumed that the ``error_file`` is written by
+              ``torch.distributed.elastic.multiprocessing.errors.error_handler.ErrorHandler``.
+              Otherwise the behavior is undefined.
+
+    """
+
+    local_rank: int
+    pid: int
+    exitcode: int
+    error_file: str
+    error_file_data: JSON = field(init=False)
+    message: str = field(init=False)
+    timestamp: int = field(init=False)
+
+    def __post_init__(self):
+        self.error_file_data = _EMPTY_ERROR_DATA
+        if os.path.isfile(self.error_file):
+            try:
+                with open(self.error_file) as fp:
+                    self.error_file_data = json.load(fp)
+                    logger.debug(
+                        "User process failed with error data: %s",
+                        json.dumps(self.error_file_data, indent=2),
+                    )
+                    self.message, self.timestamp = self._get_error_data(
+                        self.error_file_data
+                    )
+            except Exception:
+                logger.exception("Failed to parse reply file: %s", self.error_file)
+                raise
+        else:
+            self._set_no_reply_file()
+
+        # make up an informative message if not already present
+        if not self.message:
+            # signals typically do not generate an error file message
+            if self.exitcode < 0:
+                self.message = (
+                    f"Signal {-self.exitcode} ({self.signal_name()})"
+                    f" received by PID {self.pid}"
+                )
+            else:
+                self.message = "To enable traceback see: https://pytorch.org/docs/stable/elastic/errors.html"
+
+    def _get_error_data(self, error_file_data: Dict[str, Any]) -> Tuple[str, int]:
+        message = error_file_data["message"]
+        if isinstance(message, str):
+            timestamp = int(error_file_data.get("timestamp", 0))
+        else:
+            timestamp = int(message["extraInfo"]["timestamp"])
+        return (message, timestamp)
+
+    def _set_no_reply_file(self):
+        self.error_file = _NOT_AVAILABLE
+        self.error_file_data = _EMPTY_ERROR_DATA
+        self.message = ""
+        self.timestamp = int(time.time())
+
+    def signal_name(self) -> str:
+        if self.exitcode < 0:
+            # We don't want to kill the parent process trying to find the signal name.
+            # if the signal doesn't map to a known name, use not available.
+            try:
+                return signal.Signals(-self.exitcode).name
+            except Exception:
+                return _NOT_AVAILABLE
+        else:
+            return _NOT_AVAILABLE
+
+    def timestamp_isoformat(self):
+        """Return timestamp in ISO format (YYYY-MM-DD_HH:MM:SS)."""
+        return datetime.fromtimestamp(self.timestamp).isoformat(sep="_")
+
+
+GlobalRank = int
+
+_FAILURE_FORMAT_TEMPLATE = """[${idx}]:
+  time      : ${time}
+  host      : ${hostname}
+  rank      : ${rank} (local_rank: ${local_rank})
+  exitcode  : ${exitcode} (pid: ${pid})
+  error_file: ${error_file}
+  traceback : ${message}"""
+
+# extra new lines before and after are intentional
+_MSG_FORMAT_TEMPLATE = """
+${boarder}
+${title}
+${section}
+Failures:
+${other_failures}
+${section}
+Root Cause (first observed failure):
+${root_failure}
+${boarder}"""
+
+
+class ChildFailedError(Exception):
+    """
+    Special exception type that can be raised from a function annotated with the
+    ``@record`` decorator to have the child process' (root exception) propagate
+    up the stack as-is (e.g. without being wrapped in the parent's traceback).
+
+    Useful in cases where the parent is a simple nanny process
+    and the child (worker) processes are actually doing meaningful compute.
+    In this case, errors typically occur on the child process as the parent
+    is not doing anything non-trivial, and child errors should be propagated
+    to the scheduler for accurate root cause diagnostics.
+
+    .. note:: The propagation relies on error files rather than exception handling to
+              support both function and binary launches.
+
+    Example:
+    ::
+
+     # process tree on a host (container)
+     0: scheduler-init-process:
+                |- 1: torchelastic_agent:
+                         |- 2: trainer_0 (ok)
+                         |- 3: trainer_1 (fail) -> error.json
+                         |- ...
+                         |- n+2: trainer_n (ok)
+                |- n+3: other processes
+                |- ...
+
+    In the example above, trainer 1's failure (written into error.json) is
+    the root cause and should be reported to the scheduler's init process.
+    The torchelastic agent raises a ``ChildFailedError("trainer", {1: "trainer_1/error.json"})``
+    upon detecting trainer 1's failure which would propagate the contents
+    of trainer 1's error file to the scheduler's init process.
+    """
+
+    def __init__(self, name: str, failures: Dict[GlobalRank, ProcessFailure]):
+        self.name = name
+        self.failures = failures
+        assert (
+            self.failures
+        )  # does not make sense to create a ChildFaileError with no failures
+        super().__init__(self.format_msg())
+
+    def get_first_failure(self) -> Tuple[GlobalRank, ProcessFailure]:
+        rank = min(self.failures.keys(), key=lambda r: self.failures[r].timestamp)
+        return rank, self.failures[rank]
+
+    def format_msg(self, boarder_delim="=", section_delim="-"):
+        title = f"{self.name} FAILED"
+        root_rank, root_failure = self.get_first_failure()
+
+        root_failure_fmt: str = ""
+        other_failures_fmt: List[str] = []
+        width = len(title)
+        for idx, (rank, failure) in enumerate(self.failures.items()):
+            fmt, w = self._format_failure(idx, rank, failure)
+            width = max(width, w)
+            if rank == root_rank:
+                root_failure_fmt = fmt
+            else:
+                other_failures_fmt.append(fmt)
+
+        # upper boundary on width
+        width = min(width, 60)
+
+        return Template(_MSG_FORMAT_TEMPLATE).substitute(
+            boarder=boarder_delim * width,
+            title=title,
+            section=section_delim * width,
+            root_failure=root_failure_fmt,
+            other_failures="\n".join(other_failures_fmt or ["  "]),
+        )
+
+    def _format_failure(
+        self, idx: int, rank: int, failure: ProcessFailure
+    ) -> Tuple[str, int]:
+        # failure.message is either a str (when the failure does not generate a traceback - e.g. signals)
+        # or a dict (json) of the form
+        # {"message": $ERROR_MSG, "extraInfo": {"py_callstack": $TRACEBACK, timestamp: $TS}}
+        # so the display logic is:
+        # 1. if failure.message is not a dict (it is a str) just show it as is
+        # 2. else try to get the traceback (py_callstack)
+        # 3.      if the traceback is not there, use the message
+        # 4.      if the message  is not there show 
+        msg = failure.message
+        if isinstance(failure.message, dict):
+            msg = (
+                failure.message.get("extraInfo", {})
+                .get("py_callstack", failure.message.get("message", ""))
+                .replace("\n", "\n  ")  # to properly indent the traceback
+            )
+
+        fmt = Template(_FAILURE_FORMAT_TEMPLATE).substitute(
+            idx=idx,
+            time=failure.timestamp_isoformat(),
+            hostname=socket.getfqdn(),
+            rank=rank,
+            local_rank=failure.local_rank,
+            exitcode=failure.exitcode,
+            pid=failure.pid,
+            error_file=failure.error_file,
+            message=msg,
+        )
+        width = 0
+        for line in fmt.split("\n"):
+            width = max(width, len(line))
+        return fmt, width
+
+
+def record(
+    fn: Callable[..., T], error_handler: Optional[ErrorHandler] = None
+) -> Callable[..., T]:
+    """
+    Syntactic sugar to record errors/exceptions that happened in the decorated
+    function using the provided ``error_handler``.
+
+    Using this decorator is equivalent to:
+
+    ::
+
+     error_handler = get_error_handler()
+     error_handler.initialize()
+     try:
+        foobar()
+     except ChildFailedError as e:
+        _, failure = e.get_first_failure()
+        error_handler.dump_error_file(failure.error_file, failure.exitcode)
+        raise
+     except Exception as e:
+        error_handler.record(e)
+        raise
+
+    .. important:: use this decorator once per process at the top level method,
+                   typically this is the main method.
+
+    Example
+
+    ::
+
+     @record
+     def main():
+         pass
+
+     if __name__=="__main__":
+        main()
+
+    """
+    if not error_handler:
+        error_handler = get_error_handler()
+
+    def wrap(f):
+        @wraps(f)
+        def wrapper(*args, **kwargs):
+            assert error_handler is not None  # assertion for mypy type checker
+            error_handler.initialize()
+            try:
+                return f(*args, **kwargs)
+            except SystemExit as se:
+                # For run_path based entrypoints, SystemExit with code = 0 will never exit.
+                # Handling it here by returning a value:
+                if se.code == 0:
+                    return None
+                else:
+                    raise
+            except ChildFailedError as e:
+                rank, failure = e.get_first_failure()
+                if failure.error_file != _NOT_AVAILABLE:
+                    error_handler.dump_error_file(failure.error_file, failure.exitcode)
+                else:
+                    logger.info(
+                        (
+                            "local_rank %s FAILED with no error file."
+                            " Decorate your entrypoint fn with @record for traceback info."
+                            " See: https://pytorch.org/docs/stable/elastic/errors.html",
+                            rank,
+                        )
+                    )
+                raise
+            except Exception as e:
+                error_handler.record_exception(e)
+                raise
+
+        return wrapper
+
+    return wrap(fn)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/errors/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/errors/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..45cf2f9131a4520fa49a7cf743ee16968de25afa
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/errors/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/errors/__pycache__/error_handler.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/errors/__pycache__/error_handler.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..850dcb47f40b8b5bcf0dd2da69743d82904e6dd1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/errors/__pycache__/error_handler.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/errors/__pycache__/handlers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/errors/__pycache__/handlers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6ab3efac02780aaa53540211ba78284e9da40612
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/errors/__pycache__/handlers.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/errors/error_handler.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/errors/error_handler.py
new file mode 100644
index 0000000000000000000000000000000000000000..89e7fffdd5c7dc664dd4ee096a0338a3004a6dfa
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/errors/error_handler.py
@@ -0,0 +1,166 @@
+#!/usr/bin/env python3
+# mypy: allow-untyped-defs
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+import faulthandler
+import json
+import logging
+import os
+import time
+import traceback
+import warnings
+from typing import Any, Dict, Optional
+
+
+__all__ = ["ErrorHandler"]
+
+logger = logging.getLogger(__name__)
+
+
+class ErrorHandler:
+    """
+    Write the provided exception object along with some other metadata about
+    the error in a structured way in JSON format to an error file specified by the
+    environment variable: ``TORCHELASTIC_ERROR_FILE``. If this environment
+    variable is not set, then simply logs the contents of what would have been
+    written to the error file.
+
+    This handler may be subclassed to customize the handling of the error.
+    Subclasses should override ``initialize()`` and ``record_exception()``.
+    """
+
+    def _get_error_file_path(self) -> Optional[str]:
+        """
+        Return the error file path.
+
+        May return ``None`` to have the structured error be logged only.
+        """
+        return os.environ.get("TORCHELASTIC_ERROR_FILE", None)
+
+    def initialize(self) -> None:
+        """
+        Call prior to running code that we wish to capture errors/exceptions.
+
+        Typically registers signal/fault handlers. Users can override this
+        function to add custom initialization/registrations that aid in
+        propagation/information of errors/signals/exceptions/faults.
+        """
+        try:
+            faulthandler.enable(all_threads=True)
+        except Exception as e:
+            warnings.warn(f"Unable to enable fault handler. {type(e).__name__}: {e}")
+
+    def _write_error_file(self, file_path: str, error_msg: str) -> None:
+        """Write error message to the file."""
+        try:
+            with open(file_path, "w") as fp:
+                fp.write(error_msg)
+        except Exception as e:
+            warnings.warn(f"Unable to write error to file. {type(e).__name__}: {e}")
+
+    def record_exception(self, e: BaseException) -> None:
+        """
+        Write a structured information about the exception into an error file in JSON format.
+
+        If the error file cannot be determined, then logs the content
+        that would have been written to the error file.
+        """
+        file = self._get_error_file_path()
+        if file:
+            data = {
+                "message": {
+                    "message": f"{type(e).__name__}: {e}",
+                    "extraInfo": {
+                        "py_callstack": traceback.format_exc(),
+                        "timestamp": str(int(time.time())),
+                    },
+                }
+            }
+            with open(file, "w") as fp:
+                json.dump(data, fp)
+
+    def override_error_code_in_rootcause_data(
+        self,
+        rootcause_error_file: str,
+        rootcause_error: Dict[str, Any],
+        error_code: int = 0,
+    ):
+        """Modify the rootcause_error read from the file, to correctly set the exit code."""
+        if "message" not in rootcause_error:
+            logger.warning(
+                "child error file (%s) does not have field `message`. \n"
+                "cannot override error code: %s",
+                rootcause_error_file,
+                error_code,
+            )
+        elif isinstance(rootcause_error["message"], str):
+            logger.warning(
+                "child error file (%s) has a new message format. \n"
+                "skipping error code override",
+                rootcause_error_file,
+            )
+        else:
+            rootcause_error["message"]["errorCode"] = error_code
+
+    def dump_error_file(self, rootcause_error_file: str, error_code: int = 0):
+        """Dump parent error file from child process's root cause error and error code."""
+        with open(rootcause_error_file) as fp:
+            rootcause_error = json.load(fp)
+            # Override error code since the child process cannot capture the error code if it
+            # is terminated by signals like SIGSEGV.
+            if error_code:
+                self.override_error_code_in_rootcause_data(
+                    rootcause_error_file, rootcause_error, error_code
+                )
+            logger.debug(
+                "child error file (%s) contents:\n" "%s",
+                rootcause_error_file,
+                json.dumps(rootcause_error, indent=2),
+            )
+
+        my_error_file = self._get_error_file_path()
+        if my_error_file:
+            # Guard against existing error files
+            # This can happen when the child is created using multiprocessing
+            # and the same env var (TORCHELASTIC_ERROR_FILE) is used on the
+            # parent and child to specify the error files (respectively)
+            # because the env vars on the child is set in the wrapper function
+            # and by default the child inherits the parent's env vars, if the child
+            # process receives a signal before the wrapper function kicks in
+            # and the signal handler writes to the error file, then the child
+            # will write to the parent's error file. In this case just log the
+            # original error file contents and overwrite the error file.
+            self._rm(my_error_file)
+            self._write_error_file(my_error_file, json.dumps(rootcause_error))
+            logger.info("dumped error file to parent's %s", my_error_file)
+        else:
+            logger.error(
+                "no error file defined for parent, to copy child error file (%s)",
+                rootcause_error_file,
+            )
+
+    def _rm(self, my_error_file):
+        if os.path.isfile(my_error_file):
+            # Log the contents of the original file.
+            with open(my_error_file) as fp:
+                try:
+                    original = json.dumps(json.load(fp), indent=2)
+                    logger.warning(
+                        "%s already exists"
+                        " and will be overwritten."
+                        " Original contents:\n%s",
+                        my_error_file,
+                        original,
+                    )
+                except json.decoder.JSONDecodeError:
+                    logger.warning(
+                        "%s already exists"
+                        " and will be overwritten."
+                        " Unable to load original contents:\n",
+                        my_error_file,
+                    )
+            os.remove(my_error_file)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/errors/handlers.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/errors/handlers.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8a78e73702fd10a7a69b0b9c599b9128e3d12d2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/errors/handlers.py
@@ -0,0 +1,19 @@
+#!/usr/bin/env python3
+# mypy: allow-untyped-defs
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+# Multiprocessing error-reporting module
+
+
+from torch.distributed.elastic.multiprocessing.errors.error_handler import ErrorHandler
+
+
+__all__ = ["get_error_handler"]
+
+
+def get_error_handler():
+    return ErrorHandler()
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/redirects.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/redirects.py
new file mode 100644
index 0000000000000000000000000000000000000000..057013fbb9e5b8a2aeca69b41d7679cbe75c0e28
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/redirects.py
@@ -0,0 +1,104 @@
+# mypy: allow-untyped-defs
+# !/usr/bin/env python3
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+# Taken and modified from original source:
+# https://eli.thegreenplace.net/2015/redirecting-all-kinds-of-stdout-in-python/
+import ctypes
+import logging
+import os
+import sys
+from contextlib import contextmanager
+from functools import partial
+
+
+IS_WINDOWS = sys.platform == "win32"
+IS_MACOS = sys.platform == "darwin"
+
+
+logger = logging.getLogger(__name__)
+
+
+def get_libc():
+    if IS_WINDOWS or IS_MACOS:
+        logger.warning(
+            "NOTE: Redirects are currently not supported in Windows or MacOs."
+        )
+        return None
+    else:
+        return ctypes.CDLL("libc.so.6")
+
+
+libc = get_libc()
+
+
+def _c_std(stream: str):
+    return ctypes.c_void_p.in_dll(libc, stream)
+
+
+def _python_std(stream: str):
+    return {"stdout": sys.stdout, "stderr": sys.stderr}[stream]
+
+
+_VALID_STD = {"stdout", "stderr"}
+
+
+@contextmanager
+def redirect(std: str, to_file: str):
+    """
+    Redirect ``std`` (one of ``"stdout"`` or ``"stderr"``) to a file in the path specified by ``to_file``.
+
+    This method redirects the underlying std file descriptor (not just python's ``sys.stdout|stderr``).
+    See usage for details.
+
+    Directory of ``dst_filename`` is assumed to exist and the destination file
+    is overwritten if it already exists.
+
+    .. note:: Due to buffering cross source writes are not guaranteed to
+              appear in wall-clock order. For instance in the example below
+              it is possible for the C-outputs to appear before the python
+              outputs in the log file.
+
+    Usage:
+
+    ::
+
+     # syntactic-sugar for redirect("stdout", "tmp/stdout.log")
+     with redirect_stdout("/tmp/stdout.log"):
+        print("python stdouts are redirected")
+        libc = ctypes.CDLL("libc.so.6")
+        libc.printf(b"c stdouts are also redirected"
+        os.system("echo system stdouts are also redirected")
+
+     print("stdout restored")
+
+    """
+    if std not in _VALID_STD:
+        raise ValueError(
+            f"unknown standard stream <{std}>, must be one of {_VALID_STD}"
+        )
+
+    c_std = _c_std(std)
+    python_std = _python_std(std)
+    std_fd = python_std.fileno()
+
+    def _redirect(dst):
+        libc.fflush(c_std)
+        python_std.flush()
+        os.dup2(dst.fileno(), std_fd)
+
+    with os.fdopen(os.dup(std_fd)) as orig_std, open(to_file, mode="w+b") as dst:
+        _redirect(dst)
+        try:
+            yield
+        finally:
+            _redirect(orig_std)
+
+
+redirect_stdout = partial(redirect, "stdout")
+redirect_stderr = partial(redirect, "stderr")
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f56d423ce080fd7c331dc9b43eda58e5370678fc
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/__init__.py
@@ -0,0 +1,16 @@
+#!/usr/bin/env python3
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+from torch.distributed.elastic.multiprocessing.subprocess_handler.handlers import (
+    get_subprocess_handler,
+)
+from torch.distributed.elastic.multiprocessing.subprocess_handler.subprocess_handler import (
+    SubprocessHandler,
+)
+
+
+__all__ = ["SubprocessHandler", "get_subprocess_handler"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a5cd7da7c86aa253d5f6c771ae0bcf42517cb94a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/__pycache__/handlers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/__pycache__/handlers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a7a1aab69c2cc0067de9a6c6a4d36e02ef5d3b6b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/__pycache__/handlers.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/__pycache__/subprocess_handler.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/__pycache__/subprocess_handler.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..73bd8ffe342dd5eed731e52d08b0ae147b1db37f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/__pycache__/subprocess_handler.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/handlers.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/handlers.py
new file mode 100644
index 0000000000000000000000000000000000000000..2660be5af399a4969edd64589757f918686c3f4e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/handlers.py
@@ -0,0 +1,34 @@
+#!/usr/bin/env python3
+# mypy: allow-untyped-defs
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+from typing import Dict, Tuple
+
+from torch.distributed.elastic.multiprocessing.subprocess_handler.subprocess_handler import (
+    SubprocessHandler,
+)
+
+
+__all__ = ["get_subprocess_handler"]
+
+
+def get_subprocess_handler(
+    entrypoint: str,
+    args: Tuple,
+    env: Dict[str, str],
+    stdout: str,
+    stderr: str,
+    local_rank_id: int,
+):
+    return SubprocessHandler(
+        entrypoint=entrypoint,
+        args=args,
+        env=env,
+        stdout=stdout,
+        stderr=stderr,
+        local_rank_id=local_rank_id,
+    )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/subprocess_handler.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/subprocess_handler.py
new file mode 100644
index 0000000000000000000000000000000000000000..f4b8d582f1c8161f88821b438e4e94052180f2f2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/subprocess_handler/subprocess_handler.py
@@ -0,0 +1,78 @@
+#!/usr/bin/env python3
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+import os
+import signal
+import subprocess
+import sys
+from typing import Any, Dict, Optional, Tuple
+
+
+__all__ = ["SubprocessHandler"]
+
+IS_WINDOWS = sys.platform == "win32"
+
+
+def _get_default_signal() -> signal.Signals:
+    """Get the default termination signal. SIGTERM for unix, CTRL_C_EVENT for windows."""
+    if IS_WINDOWS:
+        return signal.CTRL_C_EVENT  # type: ignore[attr-defined] # noqa: F821
+    else:
+        return signal.SIGTERM
+
+
+class SubprocessHandler:
+    """
+    Convenience wrapper around python's ``subprocess.Popen``. Keeps track of
+    meta-objects associated to the process (e.g. stdout and stderr redirect fds).
+    """
+
+    def __init__(
+        self,
+        entrypoint: str,
+        args: Tuple,
+        env: Dict[str, str],
+        stdout: Optional[str],
+        stderr: Optional[str],
+        local_rank_id: int,
+    ):
+        self._stdout = open(stdout, "w") if stdout else None
+        self._stderr = open(stderr, "w") if stderr else None
+        # inherit parent environment vars
+        env_vars = os.environ.copy()
+        env_vars.update(env)
+
+        args_str = (entrypoint, *[str(e) for e in args])
+        self.local_rank_id = local_rank_id
+        self.proc: subprocess.Popen = self._popen(args_str, env_vars)
+
+    def _popen(self, args: Tuple, env: Dict[str, str]) -> subprocess.Popen:
+        kwargs: Dict[str, Any] = {}
+        if not IS_WINDOWS:
+            kwargs["start_new_session"] = True
+        return subprocess.Popen(
+            # pyre-fixme[6]: Expected `Union[typing.Sequence[Union[_PathLike[bytes],
+            #  _PathLike[str], bytes, str]], bytes, str]` for 1st param but got
+            #  `Tuple[str, *Tuple[Any, ...]]`.
+            args=args,
+            env=env,
+            stdout=self._stdout,
+            stderr=self._stderr,
+            **kwargs,
+        )
+
+    def close(self, death_sig: Optional[signal.Signals] = None) -> None:
+        if not death_sig:
+            death_sig = _get_default_signal()
+        if IS_WINDOWS:
+            self.proc.send_signal(death_sig)
+        else:
+            os.killpg(self.proc.pid, death_sig)
+        if self._stdout:
+            self._stdout.close()
+        if self._stderr:
+            self._stderr.close()
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/tail_log.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/tail_log.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c814ffb7be9980333bb3b6500aeaff349e52716
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/multiprocessing/tail_log.py
@@ -0,0 +1,158 @@
+#!/usr/bin/env python3
+# mypy: allow-untyped-defs
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+import logging
+import os
+import time
+from concurrent.futures.thread import ThreadPoolExecutor
+from threading import Event
+from typing import Dict, List, Optional, TextIO, TYPE_CHECKING
+
+
+if TYPE_CHECKING:
+    from concurrent.futures._base import Future
+
+__all__ = ["tail_logfile", "TailLog"]
+
+logger = logging.getLogger(__name__)
+
+
+def tail_logfile(
+    header: str, file: str, dst: TextIO, finished: Event, interval_sec: float
+):
+    while not os.path.exists(file):
+        if finished.is_set():
+            return
+        time.sleep(interval_sec)
+
+    with open(file, errors="replace") as fp:
+        while True:
+            line = fp.readline()
+
+            if line:
+                dst.write(f"{header}{line}")
+            else:  # reached EOF
+                if finished.is_set():
+                    # log line producer is finished
+                    break
+                else:
+                    # log line producer is still going
+                    # wait for a bit before looping again
+                    time.sleep(interval_sec)
+
+
+class TailLog:
+    """
+    Tail the given log files.
+
+    The log files do not have to exist when the ``start()`` method is called. The tail-er will gracefully wait until
+    the log files are created by the producer and will tail the contents of the
+    log files until the ``stop()`` method is called.
+
+    .. warning:: ``TailLog`` will wait indefinitely for the log file to be created!
+
+    Each log file's line will be suffixed with a header of the form: ``[{name}{idx}]:``,
+    where the ``name`` is user-provided and ``idx`` is the index of the log file
+    in the ``log_files`` mapping. ``log_line_prefixes`` can be used to override the
+    header for each log file.
+
+    Usage:
+
+    ::
+
+     log_files = {0: "/tmp/0_stdout.log", 1: "/tmp/1_stdout.log"}
+     tailer = TailLog("trainer", log_files, sys.stdout).start()
+     # actually run the trainers to produce 0_stdout.log and 1_stdout.log
+     run_trainers()
+     tailer.stop()
+
+     # once run_trainers() start writing the ##_stdout.log files
+     # the tailer will print to sys.stdout:
+     # >>> [trainer0]:log_line1
+     # >>> [trainer1]:log_line1
+     # >>> [trainer0]:log_line2
+     # >>> [trainer0]:log_line3
+     # >>> [trainer1]:log_line2
+
+    .. note:: Due to buffering log lines between files may not necessarily
+              be printed out in order. You should configure your application's
+              logger to suffix each log line with a proper timestamp.
+
+    """
+
+    def __init__(
+        self,
+        name: str,
+        log_files: Dict[int, str],
+        dst: TextIO,
+        log_line_prefixes: Optional[Dict[int, str]] = None,
+        interval_sec: float = 0.1,
+    ):
+        n = len(log_files)
+        self._threadpool = None
+        if n > 0:
+            self._threadpool = ThreadPoolExecutor(
+                max_workers=n,
+                thread_name_prefix=f"{self.__class__.__qualname__}_{name}",
+            )
+
+        self._name = name
+        self._dst = dst
+        self._log_files = log_files
+        self._log_line_prefixes = log_line_prefixes
+        self._finished_events: Dict[int, Event] = {
+            local_rank: Event() for local_rank in log_files.keys()
+        }
+        self._futs: List[Future] = []
+        self._interval_sec = interval_sec
+        self._stopped = False
+
+    def start(self) -> "TailLog":
+        if not self._threadpool:
+            return self
+
+        for local_rank, file in self._log_files.items():
+            header = f"[{self._name}{local_rank}]:"
+            if self._log_line_prefixes and local_rank in self._log_line_prefixes:
+                header = self._log_line_prefixes[local_rank]
+            self._futs.append(
+                self._threadpool.submit(
+                    tail_logfile,
+                    header=header,
+                    file=file,
+                    dst=self._dst,
+                    finished=self._finished_events[local_rank],
+                    interval_sec=self._interval_sec,
+                )
+            )
+        return self
+
+    def stop(self) -> None:
+        for finished in self._finished_events.values():
+            finished.set()
+
+        for local_rank, f in enumerate(self._futs):
+            try:
+                f.result()
+            except Exception as e:
+                logger.error(
+                    "error in log tailor for %s%s. %s: %s",
+                    self._name,
+                    local_rank,
+                    e.__class__.__qualname__,
+                    e,
+                )
+
+        if self._threadpool:
+            self._threadpool.shutdown(wait=True)
+
+        self._stopped = True
+
+    def stopped(self) -> bool:
+        return self._stopped
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..62a31adab27b01e830de13113d8dd16f6bf54b81
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__init__.py
@@ -0,0 +1,166 @@
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+"""
+In the context of Torch Distributed Elastic we use the term *rendezvous* to
+refer to a particular functionality that combines a **distributed
+synchronization** primitive with **peer discovery**.
+
+It is used by Torch Distributed Elastic to gather participants of a training
+job (i.e. nodes) such that they all agree on the same list of participants and
+everyone's roles, as well as make a consistent collective decision on when
+training can begin/resume.
+
+Torch Distributed Elastic rendezvous provides the following critical
+functionalities:
+
+**Barrier**:
+
+Nodes performing rendezvous will all block until the rendezvous is considered
+complete - this happens when at least ``min`` total number of nodes have joined
+the rendezvous barrier (for the same job). This also implies the barrier is not
+necessarily of fixed size.
+
+There's an additional small waiting time after reaching ``min`` number of
+nodes - this is used to ensure the rendezvous is not completed "too quickly"
+(which could potentially exclude additional nodes attempting to join at
+approximately the same time).
+
+If ``max`` number of nodes is gathered at the barrier, the rendezvous is
+completed immediately.
+
+There's also an overall timeout which causes the rendezvous to fail if ``min``
+number of nodes is never reached - this is meant to be a simple fail-safe to
+help release partially allocated job resources, in case there's a problem with
+the resource manager, and is meant to be interpreted as non-retryable.
+
+**Exclusivity**:
+
+A simple distributed barrier would not be sufficient, as we also need to ensure
+that only one group of nodes exists at any given time (for a given job). In
+other words, new nodes (i.e. joining late) should not be able to form a parallel
+independent group of workers for the same job.
+
+Torch Distributed Elastic rendezvous ensures that if a group of nodes has
+already completed a rendezvous (and hence might already be training), then
+additional "late" nodes attempting to rendezvous will only announce themselves
+as waiting, and will have to wait until the (previously completed) existing
+rendezvous is destroyed first.
+
+**Consistency**:
+
+When a rendezvous is completed, all its members will agree on the job membership
+and everyone's role in it. This role is represented using an integer, called
+rank, that is between between 0 and world size.
+
+Note that ranks are *not stable*, in the sense that the same node can be
+assigned a different rank in the next (re-)rendezvous.
+
+**Fault-tolerance**:
+
+Torch Distributed Elastic rendezvous is designed to tolerate node failures
+during the rendezvous process. Should a process crash (or lose network
+connectivity, etc), between joining the rendezvous and it being completed, then
+a re-rendezvous with remaining healthy nodes will happen automatically.
+
+A node can also fail *after* it has completed (or *has been observered* by other
+nodes to have completed) the rendezvous - this scenario will be handled by the
+Torch Distributed Elastic ``train_loop`` instead (where it will also trigger a
+re-rendezvous).
+
+**Shared key-value store**:
+
+When the rendezvous is completed, a shared key-value store is created and
+returned. This store implements a ``torch.distributed.Store`` API (see
+`distributed communication docs
+`__).
+
+This store is only shared by the members of the completed rendezvous. It
+is intended to be used by Torch Distributed Elastic to exchange information
+necessary to initialize job control and data-planes.
+
+**Waiting workers and rendezvous closing**:
+
+Torch Distributed Elastic rendezvous handler object provides additional
+functionalities, which are technically not part of the rendezvous process:
+
+1. Querying how many workers arrived late at the barrier, who can participate in
+   *next* rendezvous.
+
+2. Setting the rendezvous *closed* to signal all nodes not to participate in
+   next rendezvous.
+
+**DynamicRendezvousHandler**:
+
+Torch Distributed Elastic comes with the :py:class:`.DynamicRendezvousHandler`
+class that implements the rendezvous mechanism described above. It is a backend-
+agnostic type that expects a particular :py:class:`.RendezvousBackend` instance
+to be specified during construction.
+
+Torch distributed users can either implement their own backend type or use one
+of the following implementations that come with PyTorch:
+
+- :py:class:`.C10dRendezvousBackend`: Uses a C10d store (by default
+  ``TCPStore``) as the rendezvous backend. The main advantage of using a C10d
+  store is that it requires no 3rd-party dependency (such as etcd) to establish
+  a rendezvous.
+- :py:class:`.EtcdRendezvousBackend`: Supersedes the legacy
+  :py:class:`.EtcdRendezvousHandler` class. Passing an
+  :py:class:`.EtcdRendezvousBackend` instance to
+  :py:class:`.DynamicRendezvousHandler` is functionally equivalent to
+  instantiating an :py:class:`.EtcdRendezvousHandler`.
+
+  ::
+
+     store = TCPStore("localhost")
+
+     backend = C10dRendezvousBackend(store, "my_run_id")
+
+     rdzv_handler = DynamicRendezvousHandler.from_backend(
+         run_id="my_run_id",
+         store=store,
+         backend=backend,
+         min_nodes=2,
+         max_nodes=4
+     )
+"""
+
+from .api import (
+    rendezvous_handler_registry,
+    RendezvousClosedError,
+    RendezvousConnectionError,
+    RendezvousError,
+    RendezvousGracefulExitError,
+    RendezvousHandler,
+    RendezvousHandlerCreator,
+    RendezvousHandlerRegistry,
+    RendezvousInfo,
+    RendezvousParameters,
+    RendezvousStateError,
+    RendezvousStoreInfo,
+    RendezvousTimeoutError,
+)
+from .registry import _register_default_handlers
+
+
+_register_default_handlers()
+
+
+__all__ = [
+    "RendezvousClosedError",
+    "RendezvousConnectionError",
+    "RendezvousError",
+    "RendezvousGracefulExitError",
+    "RendezvousHandler",
+    "RendezvousHandlerCreator",
+    "RendezvousHandlerRegistry",
+    "RendezvousInfo",
+    "RendezvousParameters",
+    "RendezvousStateError",
+    "RendezvousStoreInfo",
+    "RendezvousTimeoutError",
+    "rendezvous_handler_registry",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..648021f746fca6871a9db6921816fb901445f58c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/api.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/api.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..009e8675030a7744bc2b380253bc3f1511cac16c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/api.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/c10d_rendezvous_backend.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/c10d_rendezvous_backend.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..56364bf8f1fd246c0e471497e24cc57bde0ca077
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/c10d_rendezvous_backend.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/dynamic_rendezvous.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/dynamic_rendezvous.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..080abac02fbd3e5351d35d71a305fa9a326139e4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/dynamic_rendezvous.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/etcd_rendezvous.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/etcd_rendezvous.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5ebd7a47bd9ca7fbb606bd469a5352161f940407
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/etcd_rendezvous.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/etcd_rendezvous_backend.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/etcd_rendezvous_backend.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..11cfe1b3c2fa2ac622ae612e0aa399e3049f0d01
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/etcd_rendezvous_backend.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/etcd_server.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/etcd_server.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3d2d5503d7c7747a38826b0773b1fa848ab429c9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/etcd_server.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/etcd_store.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/etcd_store.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..662e356ba2838073432a9284b9655828a7f258b7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/etcd_store.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/registry.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/registry.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..29ccffc09aaea7ca134d2c89eecee643d010b3dc
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/registry.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/static_tcp_rendezvous.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/static_tcp_rendezvous.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a7c30a1fdb61361b3ed93906e414966b47ae72ce
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/static_tcp_rendezvous.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..59e2d0c1a50f6757887c57aa62111244fae54b23
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/__pycache__/utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/api.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..cbfc5532c76a6a1d132324e61842d9f16a4d3fb1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/api.py
@@ -0,0 +1,379 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+import socket
+from abc import ABC, abstractmethod
+from dataclasses import dataclass
+from typing import Any, Callable, ClassVar, Dict, Optional
+
+from torch.distributed import Store
+from torch.distributed.elastic.utils.distributed import get_free_port as _get_free_port
+
+
+__all__ = [
+    "RendezvousClosedError",
+    "RendezvousConnectionError",
+    "RendezvousError",
+    "RendezvousGracefulExitError",
+    "RendezvousHandler",
+    "RendezvousHandlerCreator",
+    "RendezvousHandlerRegistry",
+    "RendezvousInfo",
+    "RendezvousParameters",
+    "RendezvousStateError",
+    "RendezvousStoreInfo",
+    "RendezvousTimeoutError",
+    "rendezvous_handler_registry",
+]
+
+
+class RendezvousError(Exception):
+    """Represents the base type for rendezvous errors."""
+
+
+class RendezvousClosedError(RendezvousError):
+    """Raised when a rendezvous is closed."""
+
+
+class RendezvousTimeoutError(RendezvousError):
+    """Raised when a rendezvous did not complete on time."""
+
+
+class RendezvousConnectionError(RendezvousError):
+    """Raised when the connection to a rendezvous backend has failed."""
+
+
+class RendezvousStateError(RendezvousError):
+    """Raised when the state of a rendezvous is corrupt."""
+
+
+class RendezvousGracefulExitError(RendezvousError):
+    """Raised when node wasn't not included in rendezvous and gracefully exits.
+
+    Exception is a mechanism to exit the stack, however does not mean a failure.
+    """
+
+
+@dataclass
+class RendezvousStoreInfo:
+    """Store address and port that can be used to bootstrap trainer distributed comms"""
+
+    MASTER_ADDR_KEY: ClassVar[str] = "MASTER_ADDR"
+    MASTER_PORT_KEY: ClassVar[str] = "MASTER_PORT"
+    master_addr: str
+    master_port: int
+
+    @staticmethod
+    def build(
+        rank: int, store: Store, local_addr: Optional[str]
+    ) -> "RendezvousStoreInfo":
+        """Factory method, finds unused new port on rank0 host and addr/port info with all ranks.
+
+        If master_addr/master_port is knowns (useful when sharing existing tcp store server) use the constructor.
+
+        Args:
+            rank: rank of the current node
+            store: store to use for rendezvous
+            local_addr: address of the current node, if not provided will be resolved from hostname
+        """
+        # TODO swap to collectives comms API
+        if rank == 0:
+            addr = local_addr or socket.getfqdn()
+            port = _get_free_port()
+            store.set(RendezvousStoreInfo.MASTER_ADDR_KEY, addr.encode(encoding="UTF-8"))  # type: ignore[arg-type]
+            store.set(RendezvousStoreInfo.MASTER_PORT_KEY, str(port).encode(encoding="UTF-8"))  # type: ignore[arg-type]
+
+        addr = store.get(RendezvousStoreInfo.MASTER_ADDR_KEY).decode(encoding="UTF-8")
+        port = int(
+            store.get(RendezvousStoreInfo.MASTER_PORT_KEY).decode(encoding="UTF-8")
+        )
+        return RendezvousStoreInfo(master_addr=addr, master_port=port)
+
+
+class RendezvousInfo:
+    """Holds the information about the rendezvous."""
+
+    def __init__(
+        self,
+        store: Store,
+        rank: int,
+        world_size: int,
+        bootstrap_store_info: RendezvousStoreInfo,
+    ):
+        self._store = store
+        self._rank = rank
+        self._world_size = world_size
+        self._bootstrap_store_info = bootstrap_store_info
+
+    @property
+    def store(self) -> Store:
+        """Store used by torchelastic control plane"""
+        return self._store
+
+    @property
+    def rank(self) -> int:
+        """Rank within a group"""
+        return self._rank
+
+    @property
+    def world_size(self) -> int:
+        """Global group size"""
+        return self._world_size
+
+    @property
+    def bootstrap_store_info(self) -> Optional[RendezvousStoreInfo]:
+        """Store information that can used by trainer code to bootstrap distributed comms."""
+        return self._bootstrap_store_info
+
+
+class RendezvousHandler(ABC):
+    """Main rendezvous interface.
+
+    Note:
+        Distributed Torch users normally **do not** need to implement their own
+        ``RendezvousHandler``. An implementation based on C10d Store is already
+        provided, and is recommended for most users.
+    """
+
+    @abstractmethod
+    def get_backend(self) -> str:
+        """Return the name of the rendezvous backend."""
+
+    @property
+    def use_agent_store(self) -> bool:
+        """Indicates that store reference returned by :py:meth:`next_rendezvous` can be shared with user
+        applications and will be available during application lifecyle.
+
+        Rendezous handler impl will share store details as instance of :py:class:`RendezvousStoreInfo`.
+        Applications as a convention use `MASTER_ADDR`/`MASTER_PORT` env variables to lookup the store.
+        """
+        return False
+
+    @abstractmethod
+    def next_rendezvous(self) -> RendezvousInfo:
+        """Main entry-point into the rendezvous barrier.
+
+        Blocks until the rendezvous is complete and the current process is
+        included in the formed worker group, or a timeout occurs, or the
+        rendezvous was marked closed.
+
+        Returns:
+            Instance of :py:class:`RendezvousInfo`.
+
+        Raises:
+            RendezvousClosedError:
+                The rendezvous is closed.
+            RendezvousConnectionError:
+                The connection to the rendezvous backend has failed.
+            RendezvousStateError:
+                The rendezvous state is corrupt.
+            RendezvousTimeoutError:
+                The rendezvous did not complete on time.
+        """
+
+    @abstractmethod
+    def is_closed(self) -> bool:
+        """Check whether the rendezvous has been closed.
+
+        A closed rendezvous means all future attempts to re-rendezvous within
+        same job will fail.
+
+        ``is_closed()`` and :py:meth:`set_closed` have semantics of eventual
+        propagation and should not be used for synchronization. The intention is
+        that if at least one node decides the job is finished, it will close the
+        rendezvous, and other nodes will soon observe this and stop running as
+        well.
+        """
+
+    @abstractmethod
+    def set_closed(self):
+        """Mark the rendezvous as closed."""
+
+    @abstractmethod
+    def num_nodes_waiting(self) -> int:
+        """Return the number of nodes who arrived late at the rendezvous
+        barrier, hence were not included in the current worker group.
+
+        Callers should periodically call this method to check whether new
+        nodes are waiting to join the job and if so admit them by calling
+        :py:meth:`next_rendezvous()` (re-rendezvous).
+        """
+
+    @abstractmethod
+    def get_run_id(self) -> str:
+        """Return the run id of the rendezvous.
+
+        The run id is a user-defined id that uniquely identifies an instance of
+        a distributed application. It typically maps to a job id and is used to
+        allow nodes to join the correct distributed application.
+        """
+
+    @abstractmethod
+    def shutdown(self) -> bool:
+        """Close all resources that were open for the rendezvous.
+
+        Example::
+
+            rdzv_handler = ...
+            try:
+                store, rank, world_size = rdzv_handler.next_rendezvous()
+            finally:
+                rdzv_handler.shutdown()
+        """
+
+
+class RendezvousParameters:
+    """Hold the parameters to construct a :py:class:`RendezvousHandler`.
+
+    Args:
+        backend:
+            The name of the backend to use to handle the rendezvous.
+        endpoint:
+            The endpoint of the rendezvous, usually in form [:].
+        run_id:
+            The id of the rendezvous.
+        min_nodes:
+            The minimum number of nodes to admit to the rendezvous.
+        max_nodes:
+            The maximum number of nodes to admit to the rendezvous.
+        local_addr:
+            The address of the local node.
+        **kwargs:
+            Additional parameters for the specified backend.
+    """
+
+    def __init__(
+        self,
+        backend: str,
+        endpoint: str,
+        run_id: str,
+        min_nodes: int,
+        max_nodes: int,
+        local_addr: Optional[str] = None,
+        **kwargs,
+    ):
+        if not backend:
+            raise ValueError("The rendezvous backend name must be a non-empty string.")
+
+        if min_nodes < 1:
+            raise ValueError(
+                f"The minimum number of rendezvous nodes ({min_nodes}) must be greater than zero."
+            )
+        if max_nodes < min_nodes:
+            raise ValueError(
+                f"The maximum number of rendezvous nodes ({max_nodes}) must be greater than or "
+                f"equal to the minimum number of rendezvous nodes ({min_nodes})."
+            )
+
+        self.backend = backend
+        self.endpoint = endpoint
+        self.run_id = run_id
+        self.min_nodes = min_nodes
+        self.max_nodes = max_nodes
+        self.config = kwargs
+        self.local_addr = local_addr
+
+    def get(self, key: str, default: Any = None) -> Any:
+        """Return the value for ``key`` if ``key`` exists, else ``default``."""
+        return self.config.get(key, default)
+
+    def get_as_bool(self, key: str, default: Optional[bool] = None) -> Optional[bool]:
+        """Return the value for ``key`` as a ``bool``."""
+        value = self.get(key, default)
+        if value is None or isinstance(value, bool):
+            return value
+        if isinstance(value, int):
+            if value == 1:
+                return True
+            if value == 0:
+                return False
+        elif isinstance(value, str):
+            if value.lower() in ["1", "true", "t", "yes", "y"]:
+                return True
+            if value.lower() in ["0", "false", "f", "no", "n"]:
+                return False
+        raise ValueError(
+            f"The rendezvous configuration option '{key}' does not represent a valid boolean value."
+        )
+
+    def get_as_int(self, key: str, default: Optional[int] = None) -> Optional[int]:
+        """Return the value for ``key`` as an ``int``."""
+        value = self.get(key, default)
+        if value is None:
+            return value
+        try:
+            return int(value)
+        except ValueError as e:
+            raise ValueError(
+                f"The rendezvous configuration option '{key}' does not represent a valid integer "
+                "value."
+            ) from e
+
+
+RendezvousHandlerCreator = Callable[[RendezvousParameters], RendezvousHandler]
+
+
+class RendezvousHandlerRegistry:
+    """Represent a registry of :py:class:`RendezvousHandler` backends."""
+
+    _registry: Dict[str, RendezvousHandlerCreator]
+
+    def __init__(self) -> None:
+        self._registry = {}
+
+    def register(self, backend: str, creator: RendezvousHandlerCreator) -> None:
+        """Register a new rendezvous backend.
+
+        Args:
+            backend:
+                The name of the backend.
+            creator:
+                The callback to invoke to construct the
+                :py:class:`RendezvousHandler`.
+        """
+        if not backend:
+            raise ValueError("The rendezvous backend name must be a non-empty string.")
+
+        current_creator: Optional[RendezvousHandlerCreator]
+        try:
+            current_creator = self._registry[backend]
+        except KeyError:
+            current_creator = None
+
+        if current_creator is not None and current_creator != creator:
+            raise ValueError(
+                f"The rendezvous backend '{backend}' cannot be registered with '{creator}' as it "
+                f"is already registered with '{current_creator}'."
+            )
+
+        self._registry[backend] = creator
+
+    def create_handler(self, params: RendezvousParameters) -> RendezvousHandler:
+        """Create a new :py:class:`RendezvousHandler`."""
+        try:
+            creator = self._registry[params.backend]
+        except KeyError as e:
+            raise ValueError(
+                f"The rendezvous backend '{params.backend}' is not registered. Did you forget "
+                f"to call `{self.register.__name__}`?"
+            ) from e
+
+        handler = creator(params)
+
+        # Do some sanity check.
+        if handler.get_backend() != params.backend:
+            raise RuntimeError(
+                f"The rendezvous backend '{handler.get_backend()}' does not match the requested "
+                f"backend '{params.backend}'."
+            )
+
+        return handler
+
+
+# The default global registry instance used by launcher scripts to instantiate
+# rendezvous handlers.
+rendezvous_handler_registry = RendezvousHandlerRegistry()
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/c10d_rendezvous_backend.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/c10d_rendezvous_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..427a53bc3276dd0e6e9c074f3e48e572ee7a8cbd
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/c10d_rendezvous_backend.py
@@ -0,0 +1,273 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+import binascii
+import logging
+import os
+import tempfile
+from base64 import b64decode, b64encode
+from datetime import timedelta
+from typing import Any, cast, Optional, Tuple
+
+from torch.distributed import FileStore, Store, TCPStore
+from torch.distributed.elastic.events import construct_and_record_rdzv_event, NodeState
+
+from .api import (
+    RendezvousConnectionError,
+    RendezvousError,
+    RendezvousParameters,
+    RendezvousStateError,
+)
+from .dynamic_rendezvous import RendezvousBackend, Token
+from .utils import _matches_machine_hostname, parse_rendezvous_endpoint
+
+
+logger = logging.getLogger(__name__)
+
+# default port for the TCP store
+DEFAULT_PORT = 29400
+
+
+class C10dRendezvousBackend(RendezvousBackend):
+    """Represents a C10d-backed rendezvous backend.
+
+    Args:
+        store:
+            The :py:class:`torch.distributed.Store` instance to use to
+            communicate with the C10d store.
+        run_id:
+            The run id of the rendezvous.
+    """
+
+    # See the explanation in the __init__ method.
+    _NULL_SENTINEL = "Y2FuaW1hZGFt"
+
+    _store: Store
+    _key: str
+
+    def __init__(self, store: Store, run_id: str) -> None:
+        if not run_id:
+            raise ValueError("The run id must be a non-empty string.")
+
+        self._store = store
+
+        self._key = "torch.rendezvous." + run_id
+
+        # The read operation of a store blocks the caller until the specified
+        # key becomes available. This behavior makes it tricky to use a store
+        # as a regular key-value dictionary.
+        #
+        # As a workaround we initially set a sentinel value as the rendezvous
+        # state. Whenever this value gets returned we treat it as a None.
+        self._call_store("compare_set", self._key, "", self._NULL_SENTINEL)
+
+    @property
+    def name(self) -> str:
+        """See base class."""
+        return "c10d"
+
+    def get_state(self) -> Optional[Tuple[bytes, Token]]:
+        """See base class."""
+        base64_state: bytes = self._call_store("get", self._key)
+
+        return self._decode_state(base64_state)
+
+    def set_state(
+        self, state: bytes, token: Optional[Token] = None
+    ) -> Optional[Tuple[bytes, Token, bool]]:
+        """See base class."""
+        base64_state_str: str = b64encode(state).decode()
+
+        if token:
+            # Shortcut if we know for sure that the token is not valid.
+            if not isinstance(token, bytes):
+                result = self.get_state()
+                if result is not None:
+                    tmp = *result, False
+                    # Python 3.6 does not support tuple unpacking in return
+                    # statements.
+                    return tmp
+                return None
+
+            token = token.decode()
+        else:
+            token = self._NULL_SENTINEL
+
+        base64_state: bytes = self._call_store(
+            "compare_set", self._key, token, base64_state_str
+        )
+
+        state_token_pair = self._decode_state(base64_state)
+        if state_token_pair is None:
+            return None
+
+        new_state, new_token = state_token_pair
+
+        # C10d Store's compare_set method does not offer an easy way to find out
+        # whether our write attempt was successful. As a brute-force solution we
+        # perform a bitwise comparison of our local state and the remote state.
+        return new_state, new_token, new_state == state
+
+    def _call_store(self, store_op: str, *args, **kwargs) -> Any:
+        try:
+            return getattr(self._store, store_op)(*args, **kwargs)
+        except (ValueError, RuntimeError, TimeoutError) as exc:
+            raise RendezvousConnectionError(
+                "The connection to the C10d store has failed. See inner exception for details."
+            ) from exc
+
+    def _decode_state(self, base64_state: bytes) -> Optional[Tuple[bytes, Token]]:
+        if base64_state == self._NULL_SENTINEL.encode():
+            return None
+
+        try:
+            state = b64decode(base64_state)
+        except binascii.Error as exc:
+            raise RendezvousStateError(
+                "The state object is corrupt. See inner exception for details."
+            ) from exc
+
+        return state, base64_state
+
+
+def _create_tcp_store(params: RendezvousParameters) -> TCPStore:
+    host, port = parse_rendezvous_endpoint(params.endpoint, default_port=DEFAULT_PORT)
+
+    cfg_is_host = params.get_as_bool("is_host")
+    # If the user has explicitly specified whether our process should host the
+    # the store, respect it.
+    if cfg_is_host is not None:
+        is_host = cfg_is_host
+    # Otherwise try to determine whether we are the host based on our hostname
+    # and IP address.
+    else:
+        is_host = _matches_machine_hostname(host)
+
+    # The timeout
+    read_timeout = cast(int, params.get_as_int("read_timeout", 60))
+    if read_timeout <= 0:
+        raise ValueError("The read timeout must be a positive integer.")
+
+    # In specific cases we attempt to instantiate the store twice. For details
+    # see the explanation in the except clause below.
+    for is_server in [is_host, False]:
+        try:
+            store = TCPStore(
+                host,
+                port,
+                is_master=is_server,
+                multi_tenant=True,
+                timeout=timedelta(seconds=read_timeout),
+            )
+
+            if is_server:
+                msg = f"Process {os.getpid()} hosts the TCP store for the C10d rendezvous backend."
+                construct_and_record_rdzv_event(
+                    run_id=params.run_id, message=msg, node_state=NodeState.INIT
+                )
+                logger.info(msg)
+
+            break
+        except (ValueError, RuntimeError, TimeoutError) as exc:
+            # If we heuristically inferred the value of is_host as True and our
+            # first attempt to instantiate the TCP store has failed, try it one
+            # more time with is_host set to False. As an edge case there can be
+            # more than one process that is part of the same rendezvous on this
+            # machine and only one of them will eventually host the store.
+
+            if not is_server or cfg_is_host is not None:
+                raise RendezvousConnectionError(
+                    "The connection to the C10d store has failed. See inner exception for details."
+                ) from exc
+
+    return store  # type: ignore[possibly-undefined]
+
+
+def _create_file_store(params: RendezvousParameters) -> FileStore:
+    # If a user specifies an endpoint, we treat it as a path to a file.
+    if params.endpoint:
+        path = params.endpoint
+    else:
+        try:
+            # The temporary file is readable and writable only by the user of
+            # this process.
+            _, path = tempfile.mkstemp()
+        except OSError as exc:
+            raise RendezvousError(
+                "The file creation for C10d store has failed. See inner exception for details."
+            ) from exc
+
+    try:
+        store = FileStore(path)
+    except (ValueError, RuntimeError) as exc:
+        raise RendezvousConnectionError(
+            "The connection to the C10d store has failed. See inner exception for details."
+        ) from exc
+
+    return store
+
+
+def create_backend(params: RendezvousParameters) -> Tuple[C10dRendezvousBackend, Store]:
+    """Create a new :py:class:`C10dRendezvousBackend` from the specified parameters.
+
+    +--------------+-----------------------------------------------------------+
+    | Parameter    | Description                                               |
+    +==============+===========================================================+
+    | store_type   | The type of the C10d store. The currently supported types |
+    |              | are "tcp" and "file" which correspond to                  |
+    |              | :py:class:`torch.distributed.TCPStore` and                |
+    |              | :py:class:`torch.distributed.FileStore`, respectively.    |
+    |              | Defaults to "tcp".                                        |
+    +--------------+-----------------------------------------------------------+
+    | read_timeout | The read timeout, in seconds, for store operations.       |
+    |              | Defaults to 60 seconds.                                   |
+    |              |                                                           |
+    |              | Note this only applies to                                 |
+    |              | :py:class:`torch.distributed.TCPStore`. It is not relevant|
+    |              | to :py:class:`torch.distributed.FileStore` which does not |
+    |              | take in timeout as a parameter.                           |
+    +--------------+-----------------------------------------------------------+
+    | is_host      | A boolean value indicating whether this backend instance  |
+    |              | will host the C10d store. If not specified it will be     |
+    |              | inferred heuristically by matching the hostname or the IP |
+    |              | address of this machine against the specified rendezvous  |
+    |              | endpoint. Defaults to ``None``.                           |
+    |              |                                                           |
+    |              | Note that this configuration option only applies to       |
+    |              | :py:class:`torch.distributed.TCPStore`. In normal         |
+    |              | circumstances you can safely skip it; the only time when  |
+    |              | it is needed is if its value cannot be correctly          |
+    |              | determined (e.g. the rendezvous endpoint has a CNAME as   |
+    |              | the hostname or does not match the FQDN of the machine).  |
+    +--------------+-----------------------------------------------------------+
+    """
+    # As of today we only support TCPStore and FileStore. Other store types do
+    # not have the required functionality (e.g. compare_set) yet.
+    store_type = params.get("store_type", "tcp").strip().lower()
+    store: Store
+
+    try:
+        if store_type == "file":
+            store = _create_file_store(params)
+        elif store_type == "tcp":
+            store = _create_tcp_store(params)
+        else:
+            raise ValueError(
+                "Invalid store type given. Currently only supports file and tcp."
+            )
+
+        backend = C10dRendezvousBackend(store, params.run_id)
+
+    except Exception as e:
+        construct_and_record_rdzv_event(
+            message=f"{type(e).__name__}: {str(e)}",
+            run_id=params.run_id,
+            node_state=NodeState.FAILED,
+        )
+        raise
+
+    return backend, store
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/dynamic_rendezvous.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/dynamic_rendezvous.py
new file mode 100644
index 0000000000000000000000000000000000000000..c8e294604501db855c426618bc927180f7c61d9e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/dynamic_rendezvous.py
@@ -0,0 +1,1429 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+import inspect
+import logging
+import os
+import pickle
+import socket
+import threading
+import time
+import weakref
+from abc import ABC, abstractmethod
+from dataclasses import dataclass
+from datetime import datetime, timedelta
+from enum import Enum
+from typing import Any, Callable, cast, Dict, List, Optional, Set, Tuple
+
+import torch.distributed as dist
+from torch.distributed import Store
+from torch.distributed.elastic.events import construct_and_record_rdzv_event, NodeState
+
+from .api import (
+    RendezvousClosedError,
+    RendezvousError,
+    RendezvousGracefulExitError,
+    RendezvousHandler,
+    RendezvousInfo,
+    RendezvousParameters,
+    RendezvousStateError,
+    RendezvousStoreInfo,
+    RendezvousTimeoutError,
+)
+from .utils import _delay, _PeriodicTimer
+
+
+__all__ = [
+    "RendezvousBackend",
+    "RendezvousTimeout",
+    "RendezvousSettings",
+    "DynamicRendezvousHandler",
+    "create_handler",
+]
+
+logger = logging.getLogger(__name__)
+
+
+def get_method_name(depth=2):
+    if len(inspect.stack()) > depth:
+        return inspect.stack()[depth].function
+    return "no_method_name"
+
+
+Token = Any
+"""Represent an opaque fencing token used by the rendezvous backend."""
+
+
+class RendezvousBackend(ABC):
+    """Represent a backend that holds the rendezvous state."""
+
+    @property
+    @abstractmethod
+    def name(self) -> str:
+        """Get the name of the backend."""
+
+    @abstractmethod
+    def get_state(self) -> Optional[Tuple[bytes, Token]]:
+        """Get the rendezvous state.
+
+        Returns:
+            A tuple of the encoded rendezvous state and its fencing token or
+            ``None`` if no state is found in the backend.
+
+        Raises:
+            RendezvousConnectionError:
+                The connection to the backend has failed.
+            RendezvousStateError:
+                The rendezvous state is corrupt.
+        """
+
+    @abstractmethod
+    def set_state(
+        self, state: bytes, token: Optional[Token] = None
+    ) -> Optional[Tuple[bytes, Token, bool]]:
+        """Set the rendezvous state.
+
+        The new rendezvous state is set conditionally:
+
+          - If the specified ``token`` matches the fencing token stored in the
+            backend, the state will be updated. The new state will be returned
+            to the caller along with its fencing token.
+          - If the specified ``token`` does not match the fencing token stored
+            in the backend, the state won't be updated; instead the existing
+            state along with its fencing token will be returned to the caller.
+          - If the specified ``token`` is ``None``, the new state will be set
+            only if there is no existing state in the backend. Either the new
+            state or the existing state along with its fencing token will be
+            returned to the caller.
+
+        Args:
+            state:
+                The encoded rendezvous state.
+            token:
+                An optional fencing token that was retrieved by a previous call
+                to :py:meth:`get_state` or ``set_state()``.
+
+        Returns:
+            A tuple of the serialized rendezvous state, its fencing token, and
+            a boolean value indicating whether our set attempt succeeded.
+
+        Raises:
+            RendezvousConnectionError:
+                The connection to the backend has failed.
+            RendezvousStateError:
+                The rendezvous state is corrupt.
+        """
+
+
+class RendezvousTimeout:
+    """Hold the timeout configuration of a rendezvous.
+
+    Args:
+        join:
+            The time within which the rendezvous is expected to complete.
+        last_call:
+            An additional wait amount before completing the rendezvous once the
+            rendezvous has the minimum number of required participants.
+        close:
+            The time within which the rendezvous is expected to close after a
+            call to :py:meth:`RendezvousHandler.set_closed` or
+            :py:meth:`RendezvousHandler.shutdown`.
+        keep_alive:
+            The time within which a keep-alive heartbeat is expected to
+            complete.
+    """
+
+    _ZERO = timedelta(0)
+
+    _DEFAULT_TIMEOUTS = {
+        "join": timedelta(seconds=600),
+        "last_call": timedelta(seconds=30),
+        "close": timedelta(seconds=30),
+        "heartbeat": timedelta(seconds=5),
+    }
+
+    _join: timedelta
+    _last_call: timedelta
+    _close: timedelta
+    _heartbeat: timedelta
+
+    def __init__(
+        self,
+        join: Optional[timedelta] = None,
+        last_call: Optional[timedelta] = None,
+        close: Optional[timedelta] = None,
+        heartbeat: Optional[timedelta] = None,
+    ) -> None:
+        self._set_timeouts(
+            join=join, last_call=last_call, close=close, heartbeat=heartbeat
+        )
+
+    @property
+    def join(self) -> timedelta:
+        """Get the join timeout."""
+        return self._join
+
+    @property
+    def last_call(self) -> timedelta:
+        """Get the last call timeout."""
+        return self._last_call
+
+    @property
+    def close(self) -> timedelta:
+        """Get the close timeout."""
+        return self._close
+
+    @property
+    def heartbeat(self) -> timedelta:
+        """Get the keep-alive heartbeat timeout."""
+        return self._heartbeat
+
+    def _set_timeouts(self, **timeouts: Optional[timedelta]):
+        for name, timeout in timeouts.items():
+            if timeout is None:
+                timeout = self._DEFAULT_TIMEOUTS[name]
+            if timeout <= self._ZERO:
+                raise ValueError(f"The {name} timeout ({timeout}) must be positive.")
+            setattr(self, "_" + name, timeout)
+
+
+@dataclass(repr=False, eq=False, frozen=True)
+class RendezvousSettings:
+    """Hold the settings of the rendezvous.
+
+    Attributes:
+        run_id:
+            The run id of the rendezvous.
+        min_nodes:
+            The minimum number of nodes to admit to the rendezvous.
+        max_nodes:
+            The maximum number of nodes to admit to the rendezvous.
+        timeout:
+            The timeout configuration of the rendezvous.
+        keep_alive_interval:
+            The amount of time a node waits before sending a heartbeat to keep
+            it alive in the rendezvous.
+        keep_alive_max_attempt:
+            The maximum number of failed heartbeat attempts after which a node
+            is considered dead.
+    """
+
+    run_id: str
+    min_nodes: int
+    max_nodes: int
+    timeout: RendezvousTimeout
+    keep_alive_interval: timedelta
+    keep_alive_max_attempt: int
+
+
+@dataclass(eq=True, order=True, frozen=True)
+class _NodeDesc:
+    """Describe a node in the rendezvous.
+
+    Attributes:
+        addr:
+            The FQDN of the node or user specified local node address.
+        pid:
+            The id of the process in which the rendezvous handler runs.
+        local_id:
+            A process-wide unique id.
+    """
+
+    addr: str
+    pid: int
+    local_id: int
+
+    def __repr__(self) -> str:
+        return f"{self.addr}_{self.pid}_{self.local_id}"
+
+
+class _NodeDescGenerator:
+    """Generate node descriptors.
+
+    A node descriptor is a combination of an FQDN, a process id, and an auto-
+    incremented integer that uniquely identifies a node in the rendezvous.
+    """
+
+    _lock: threading.Lock
+    _local_id: int
+
+    def __init__(self) -> None:
+        self._lock = threading.Lock()
+
+        # An integer that is incremented with each call to generate().
+        self._local_id = 0
+
+    def generate(self, local_addr: Optional[str] = None) -> _NodeDesc:
+        # This method can be called by multiple threads concurrently; therefore,
+        # we must increment the integer atomically.
+        with self._lock:
+            local_id = self._local_id
+
+            self._local_id += 1
+
+        return _NodeDesc(local_addr or socket.getfqdn(), os.getpid(), local_id)
+
+
+class _RendezvousState:
+    """Hold the state of a rendezvous.
+
+    Attributes:
+        round:
+            The current round of the rendezvous.
+        complete:
+            A boolean value indicating whether the current round of the
+            rendezvous is complete.
+        deadline:
+            The time at which the current round of the rendezvous will be
+            considered complete if it is still waiting for nodes to join.
+        closed:
+            A boolean value indicating whether the rendezvous is closed.
+        participants:
+            A dictionary of the participants and their corresponding ranks.
+        wait_list:
+            A set of nodes that are waiting to participate in the next round of
+            the rendezvous.
+        redundancy_list:
+            A set of nodes that are redundant in the current round and can join
+            the next rendezvous without triggering re-rendezvous.
+        last_heartbeats:
+            A dictionary containing each node's last heartbeat time.
+    """
+
+    round: int
+    complete: bool
+    deadline: Optional[datetime]
+    closed: bool
+    participants: Dict[_NodeDesc, int]
+    wait_list: Set[_NodeDesc]
+    redundancy_list: Set[_NodeDesc]
+    last_heartbeats: Dict[_NodeDesc, datetime]
+
+    def __init__(self) -> None:
+        self.round = 0
+        self.complete = False
+        self.deadline = None
+        self.closed = False
+        self.participants = {}
+        self.wait_list = set()
+        self.redundancy_list = set()
+        self.last_heartbeats = {}
+
+
+def _remove_participant_epilogue(
+    state: _RendezvousState, settings: RendezvousSettings
+) -> None:
+    if state.complete:
+        # If we do not have any participants left, move to the next round.
+        if not state.participants:
+            msg = "No participants left in the rendezvous, marking rendezvous as incomplete"
+            logger.debug(msg)
+            state.complete = False
+
+            state.round += 1
+    else:
+        if len(state.participants) < settings.min_nodes:
+            msg = (
+                f"Number of participants {len(state.participants)}) less than"
+                f"min_nodes {settings.min_nodes}, clearning deadline in state"
+            )
+            logger.debug(msg)
+            state.deadline = None
+
+
+class _RendezvousStateHolder(ABC):
+    """Hold the shared rendezvous state synced with other nodes."""
+
+    @property
+    @abstractmethod
+    def state(self) -> _RendezvousState:
+        """Get the local state."""
+
+    @abstractmethod
+    def sync(self) -> Optional[bool]:
+        """Read or writes the latest state.
+
+        Returns:
+            A boolean value indicating whether the local state, in case marked
+            as dirty, was successfully synced with other nodes.
+        """
+
+    @abstractmethod
+    def mark_dirty(self) -> None:
+        """Mark the local state as dirty."""
+
+
+class _BackendRendezvousStateHolder(_RendezvousStateHolder):
+    """Hold the rendezvous state synced with other nodes via a backend.
+
+    Args:
+        backend:
+            The rendezvous backend to use.
+        settings:
+            The rendezvous settings.
+        cache_duration:
+            The amount of time, in seconds, to cache the last rendezvous state
+            before requesting it from the backend again.
+    """
+
+    _backend: RendezvousBackend
+    _state: _RendezvousState
+    _settings: RendezvousSettings
+    _cache_duration: int
+    _token: Token
+    _dirty: bool
+    _last_sync_time: float
+    _dead_nodes: List[_NodeDesc]
+
+    def __init__(
+        self,
+        backend: RendezvousBackend,
+        settings: RendezvousSettings,
+        cache_duration: int = 1,
+    ) -> None:
+        self._backend = backend
+        self._state = _RendezvousState()
+        self._settings = settings
+        self._cache_duration = cache_duration
+        self._token = None
+        self._dirty = False
+        self._last_sync_time = -1
+        self._dead_nodes = []
+
+    def _record(self, message: str, node_state: NodeState = NodeState.RUNNING):
+        construct_and_record_rdzv_event(
+            name=f"{self.__class__.__name__}.{get_method_name()}",
+            run_id=self._settings.run_id,
+            message=message,
+            node_state=node_state,
+        )
+
+    @property
+    def state(self) -> _RendezvousState:
+        """See base class."""
+        return self._state
+
+    def sync(self) -> Optional[bool]:
+        """See base class."""
+        state_bits: Optional[bytes] = None
+
+        token = None
+
+        has_set: Optional[bool]
+
+        if self._dirty:
+            has_set = False
+
+            state_bits = pickle.dumps(self._state)
+
+            set_response = self._backend.set_state(state_bits, self._token)
+            if set_response is not None:
+                state_bits, token, has_set = set_response
+        else:
+            has_set = None
+
+            if self._cache_duration > 0:
+                # Avoid overloading the backend if we are asked to retrieve the
+                # state repeatedly. Try to serve the cached state.
+                if self._last_sync_time >= max(
+                    time.monotonic() - self._cache_duration, 0
+                ):
+                    return None
+
+            get_response = self._backend.get_state()
+            if get_response is not None:
+                state_bits, token = get_response
+
+        if state_bits is not None:
+            try:
+                self._state = pickle.loads(state_bits)
+            except pickle.PickleError as exc:
+                raise RendezvousStateError(
+                    "The rendezvous state is corrupt. See inner exception for details."
+                ) from exc
+        else:
+            self._state = _RendezvousState()
+
+        if has_set and self._dead_nodes and logger.isEnabledFor(logging.DEBUG):
+            node_list = ", ".join(f"'{dead_node}'" for dead_node in self._dead_nodes)
+
+            msg = (
+                f"As part of the sync operation the node(s) {node_list} have been removed from the "
+                f"rendezvous '{self._settings.run_id}' since they had no heartbeat."
+            )
+            self._record(message=msg)
+            logger.debug(msg)
+
+        self._token = token
+
+        self._dirty = False
+
+        self._last_sync_time = time.monotonic()
+
+        self._sanitize()
+
+        return has_set
+
+    def _sanitize(self) -> None:
+        state = self._state
+
+        expire_time = datetime.utcnow() - (
+            self._settings.keep_alive_interval * self._settings.keep_alive_max_attempt
+        )
+
+        # Filter out the dead nodes.
+        self._dead_nodes = [
+            node
+            for node, last_heartbeat in state.last_heartbeats.items()
+            if last_heartbeat < expire_time
+        ]
+
+        participant_removed = False
+
+        for dead_node in self._dead_nodes:
+            msg = f"Detected dead node '{dead_node}', removing it from the rendezvous"
+            logger.debug(msg)
+            del state.last_heartbeats[dead_node]
+
+            try:
+                del state.participants[dead_node]
+
+                participant_removed = True
+            except KeyError:
+                pass
+
+            try:
+                state.wait_list.remove(dead_node)
+            except KeyError:
+                pass
+
+            try:
+                state.redundancy_list.remove(dead_node)
+            except KeyError:
+                pass
+
+        if participant_removed:
+            # Common epilogue shared with the _remove_from_participants()
+            # function of _DistributedRendezvousOpExecutor.
+            _remove_participant_epilogue(state, self._settings)
+
+    def mark_dirty(self) -> None:
+        """See base class.
+
+        If the local rendezvous state is dirty, the next sync call will try to
+        write the changes back to the backend. However this attempt might fail
+        if another node, which had the same state, also made changes and wrote
+        them before us.
+        """
+        self._dirty = True
+
+
+class _Action(Enum):
+    """Specifies the possible actions based on the state of the rendezvous."""
+
+    KEEP_ALIVE = 1
+    ADD_TO_PARTICIPANTS = 2
+    ADD_TO_WAIT_LIST = 3
+    ADD_TO_REDUNDANCY_LIST = 4
+    REMOVE_FROM_PARTICIPANTS = 5
+    REMOVE_FROM_WAIT_LIST = 6
+    REMOVE_FROM_REDUNDANCY_LIST = 7
+    MARK_RENDEZVOUS_COMPLETE = 8
+    MARK_RENDEZVOUS_CLOSED = 9
+    SYNC = 10
+    ERROR_CLOSED = 11
+    ERROR_TIMEOUT = 12
+    FINISH = 13
+
+
+class _RendezvousContext:
+    """Holds the context of the rendezvous.
+
+    Attributes:
+        node:
+            The node descriptor associated with the current rendezvous handler
+            instance.
+        state:
+            The current state of the rendezvous.
+        settings:
+            The rendezvous settings.
+    """
+
+    node: _NodeDesc
+    state: _RendezvousState
+    settings: RendezvousSettings
+
+    def __init__(
+        self, node: _NodeDesc, state: _RendezvousState, settings: RendezvousSettings
+    ) -> None:
+        self.node = node
+        self.state = state
+        self.settings = settings
+
+
+class _RendezvousOpExecutor(ABC):
+    """Execute rendezvous operations."""
+
+    @abstractmethod
+    def run(
+        self,
+        state_handler: Callable[[_RendezvousContext, float], _Action],
+        deadline: float,
+        update_deadline: Optional[Callable[[timedelta], float]] = None,
+    ) -> None:
+        """Execute a rendezvous operation.
+
+        An operation is run inside a state machine and is expected to transition
+        the rendezvous from one state to another.
+
+        Args:
+            state_handler:
+                A callable that is expected to return the next state transition
+                action based on the current state of the rendezvous.
+            deadline:
+                The time, in seconds, at which the operation will be considered
+                timed-out.
+            update_deadline:
+                Function to generate a new operation deadline if the current
+                node may participate in the next rendezvous.
+        """
+
+
+class _DistributedRendezvousOpExecutor(_RendezvousOpExecutor):
+    """Execute rendezvous operations using a shared state.
+
+    Args:
+        node:
+            The node descriptor associated with the current rendezvous handler
+            instance.
+        state_holder:
+            The ``RendezvousStateHolder`` to use to sync the rendezvous state
+            with other nodes.
+        settings:
+            The rendezvous settings.
+    """
+
+    _node: _NodeDesc
+    _state: _RendezvousState
+    _state_holder: _RendezvousStateHolder
+    _settings: RendezvousSettings
+
+    def __init__(
+        self,
+        node: _NodeDesc,
+        state_holder: _RendezvousStateHolder,
+        settings: RendezvousSettings,
+    ) -> None:
+        self._node = node
+        self._state_holder = state_holder
+        self._settings = settings
+
+    def _record(self, message: str, node_state: NodeState = NodeState.RUNNING) -> None:
+        construct_and_record_rdzv_event(
+            name=f"{self.__class__.__name__}.{get_method_name()}",
+            run_id=self._settings.run_id,
+            message=message,
+            node_state=node_state,
+            hostname=self._node.addr,
+            pid=self._node.pid,
+            local_id=self._node.local_id,
+        )
+
+    def run(
+        self,
+        state_handler: Callable[[_RendezvousContext, float], _Action],
+        deadline: float,
+        update_deadline: Optional[Callable[[timedelta], float]] = None,
+    ) -> None:
+        """See base class."""
+        action = None
+        while action != _Action.FINISH:
+            # Reads or writes the latest rendezvous state shared by all nodes in
+            # the rendezvous. Note that our local changes might get overridden
+            # by another node if that node synced its changes before us.
+            has_set = self._state_holder.sync()
+            if has_set is not None:
+                if has_set:
+                    msg = (
+                        f"The node '{self._node}' has successfully synced its local changes with "
+                        f"other nodes in the rendezvous '{self._settings.run_id}'."
+                    )
+                else:
+                    msg = (
+                        f"The node '{self._node}' has a stale state and failed to sync its local "
+                        f"changes with other nodes in the rendezvous '{self._settings.run_id}'."
+                    )
+
+                self._record(message=msg)
+                logger.debug(msg)
+
+            self._state = self._state_holder.state
+
+            ctx = _RendezvousContext(self._node, self._state, self._settings)
+
+            # Determine the next action to take based on the current state of
+            # the rendezvous.
+            action = state_handler(ctx, deadline)
+
+            if action == _Action.FINISH:
+                continue
+
+            if action == _Action.ERROR_CLOSED:
+                raise RendezvousClosedError
+
+            if action == _Action.ERROR_TIMEOUT:
+                raise RendezvousTimeoutError
+
+            if action == _Action.SYNC:
+                # Delay the execution by one second to avoid overloading the
+                # backend if we are asked to poll for state changes.
+                _delay(seconds=1)
+            else:
+                if action == _Action.KEEP_ALIVE:
+                    self._keep_alive()
+                elif action == _Action.ADD_TO_PARTICIPANTS:
+                    self._add_to_participants()
+                elif action == _Action.ADD_TO_WAIT_LIST:
+                    self._add_to_wait_list()
+                elif action == _Action.ADD_TO_REDUNDANCY_LIST:
+                    self._add_to_redundancy_list()
+                elif action == _Action.REMOVE_FROM_PARTICIPANTS:
+                    self._remove_from_participants()
+                elif action == _Action.REMOVE_FROM_WAIT_LIST:
+                    self._remove_from_wait_list()
+                elif action == _Action.REMOVE_FROM_REDUNDANCY_LIST:
+                    self._remove_from_redundancy_list()
+                    # update deadline since the node may participate in rendezvous process
+                    if update_deadline:
+                        deadline = update_deadline(self._settings.timeout.join)
+                elif action == _Action.MARK_RENDEZVOUS_COMPLETE:
+                    self._mark_rendezvous_complete()
+                elif action == _Action.MARK_RENDEZVOUS_CLOSED:
+                    self._mark_rendezvous_closed()
+
+                # Attempt to sync our changes back to other nodes.
+                self._state_holder.mark_dirty()
+
+    def _keep_alive(self) -> None:
+        msg = (
+            f"The node '{self._node}' updated its keep-alive heartbeat time for the rendezvous "
+            f"'{self._settings.run_id}'. Pending sync."
+        )
+        self._record(message=msg)
+        logger.debug(msg)
+
+        self._state.last_heartbeats[self._node] = datetime.utcnow()
+
+    def _add_to_participants(self) -> None:
+        msg = (
+            f"The node '{self._node}' added itself to the participants of round "
+            f"{self._state.round} of the rendezvous '{self._settings.run_id}'. Pending sync."
+        )
+        self._record(message=msg)
+        logger.debug(msg)
+
+        state = self._state
+
+        try:
+            state.wait_list.remove(self._node)
+        except KeyError:
+            pass
+
+        # The ranks of the participants will be set once the rendezvous is
+        # complete.
+        state.participants[self._node] = 0
+
+        self._keep_alive()
+
+        if len(state.participants) == self._settings.min_nodes:
+            state.deadline = datetime.utcnow() + self._settings.timeout.last_call
+
+        if len(state.participants) == self._settings.max_nodes:
+            self._mark_rendezvous_complete()
+
+    def _add_to_wait_list(self) -> None:
+        msg = (
+            f"The node '{self._node}' added itself to the wait list of round "
+            f"{self._state.round + 1} of the rendezvous '{self._settings.run_id}'. Pending sync."
+        )
+        self._record(message=msg)
+        logger.debug(msg)
+
+        if self._node in self._state.redundancy_list:
+            self._state.redundancy_list.remove(self._node)
+        self._state.wait_list.add(self._node)
+
+        self._keep_alive()
+
+    def _add_to_redundancy_list(self) -> None:
+        msg = (
+            f"The node '{self._node}' added itself to the redundancy list of round "
+            f"{self._state.round + 1} of the rendezvous '{self._settings.run_id}'. Pending sync."
+        )
+        self._record(message=msg)
+        logger.debug(msg)
+
+        self._state.redundancy_list.add(self._node)
+
+        self._keep_alive()
+
+    def _remove_from_participants(self) -> None:
+        msg = (
+            f"The node '{self._node}' removed itself from the participants of round "
+            f"{self._state.round} of the rendezvous '{self._settings.run_id}'. Pending sync."
+        )
+        self._record(message=msg)
+        logger.debug(msg)
+
+        state = self._state
+
+        del state.participants[self._node]
+
+        del state.last_heartbeats[self._node]
+
+        # Common epilogue shared with the sanitizer() function of
+        # _BackendRendezvousStateHolder.
+        _remove_participant_epilogue(state, self._settings)
+
+    def _remove_from_wait_list(self) -> None:
+        msg = (
+            f"The node '{self._node}' removed itself from the wait list of round "
+            f"{self._state.round + 1} of the rendezvous '{self._settings.run_id}'. Pending sync."
+        )
+        self._record(message=msg)
+        logger.debug(msg)
+
+        self._state.wait_list.remove(self._node)
+
+        del self._state.last_heartbeats[self._node]
+
+    def _remove_from_redundancy_list(self) -> None:
+        msg = (
+            f"The node '{self._node}' removed itself from the redunant list of round "
+            f"{self._state.round + 1} of the rendezvous '{self._settings.run_id}'. Pending sync."
+        )
+        self._record(message=msg)
+        logger.debug(msg)
+
+        self._state.redundancy_list.remove(self._node)
+
+        del self._state.last_heartbeats[self._node]
+
+    def _mark_rendezvous_complete(self) -> None:
+        msg = (
+            f"The node '{self._node}' marked round {self._state.round} of the rendezvous "
+            f"'{self._settings.run_id}' as complete. Pending sync."
+        )
+        self._record(message=msg, node_state=NodeState.SUCCEEDED)
+        logger.debug(msg)
+
+        state = self._state
+
+        state.complete = True
+        state.deadline = None
+
+        # Assign the ranks.
+        for rank, node in enumerate(sorted(state.participants)):
+            state.participants[node] = rank
+
+    def _mark_rendezvous_closed(self) -> None:
+        msg = (
+            f"The node '{self._node}' marked the rendezvous '{self._settings.run_id}' as closed. "
+            "Pending sync."
+        )
+        self._record(message=msg, node_state=NodeState.SUCCEEDED)
+        logger.debug(msg)
+
+        self._state.closed = True
+
+
+def _should_keep_alive(ctx: _RendezvousContext) -> bool:
+    """Determine whether a keep-alive heartbeat should be sent."""
+    try:
+        last_heartbeat = ctx.state.last_heartbeats[ctx.node]
+    except KeyError:
+        return False
+
+    return last_heartbeat <= datetime.utcnow() - ctx.settings.keep_alive_interval
+
+
+class _RendezvousExitOp:
+    """Represent a rendezvous exit operation."""
+
+    def __call__(self, ctx: _RendezvousContext, deadline: float) -> _Action:
+        if ctx.node in ctx.state.participants:
+            if time.monotonic() > deadline:
+                return _Action.ERROR_TIMEOUT
+            return _Action.REMOVE_FROM_PARTICIPANTS
+        return _Action.FINISH
+
+
+class _RendezvousJoinOp:
+    """Represent a rendezvous join operation."""
+
+    def __call__(self, ctx: _RendezvousContext, deadline: float) -> _Action:
+        state = ctx.state
+
+        # A closed rendezvous means that it no longer accepts new nodes.
+        if state.closed:
+            if ctx.node in state.redundancy_list:
+                msg = f"The rendezvous '{ctx.settings.run_id}' is closed, terminating pending rendezvous."
+                raise RendezvousGracefulExitError(msg)
+            return _Action.ERROR_CLOSED
+
+        if ctx.node in state.redundancy_list:
+            msg = f"The node {ctx.node} is in redunancy list"
+            logger.debug(msg)
+            # don't apply the timeout logic here, since we want to allow the node to rejoin
+            if len(state.participants) == ctx.settings.max_nodes:
+                if _should_keep_alive(ctx):
+                    return _Action.KEEP_ALIVE
+                else:
+                    return _Action.SYNC
+            else:
+                # transition to waiting state that will respect timeouts.
+                msg = f"The node {ctx.node} is removed from redunancy list"
+                logger.debug(msg)
+                return _Action.REMOVE_FROM_REDUNDANCY_LIST
+
+        is_participant = ctx.node in state.participants
+
+        # If we are part of the rendezvous and it is already complete there is
+        # no further action to take.
+        if state.complete and is_participant:
+            return _Action.FINISH
+
+        now = time.monotonic()
+        if now > deadline:
+            rollback_period = 5  # 5 seconds
+
+            # If we still have time to rollback (a short period on top of the
+            # operation deadline), try to remove ourself from the rendezvous.
+            # It is okay if we can't though as our keep-alive will eventually
+            # expire.
+            if now <= deadline + rollback_period:
+                # If we are part of the rendezvous, it means we couldn't find
+                # enough participants to complete it on time.
+                if is_participant:
+                    return _Action.REMOVE_FROM_PARTICIPANTS
+                # If we are in the wait list, it means we couldn't wait till the
+                # next round of the rendezvous.
+                if ctx.node in state.wait_list:
+                    return _Action.REMOVE_FROM_WAIT_LIST
+            return _Action.ERROR_TIMEOUT
+
+        if state.complete:
+            # If we are here, it means we are not part of the rendezvous. In
+            # case the rendezvous has capacity for additional participants add
+            # ourself to the wait list for the next round.
+            if len(state.participants) < ctx.settings.max_nodes:
+                if ctx.node not in state.wait_list:
+                    return _Action.ADD_TO_WAIT_LIST
+            elif len(state.participants) >= ctx.settings.max_nodes:
+                if (
+                    ctx.node not in state.redundancy_list
+                    and ctx.node not in state.wait_list
+                ):
+                    return _Action.ADD_TO_REDUNDANCY_LIST
+        elif is_participant:
+            # If the rendezvous has enough number of participants including us,
+            # check whether we have passed the rendezvous deadline. If yes,
+            # complete it.
+            if (
+                len(state.participants) >= ctx.settings.min_nodes
+                and len(state.participants) <= ctx.settings.max_nodes
+            ):
+                if cast(datetime, state.deadline) < datetime.utcnow():
+                    msg = (
+                        f"The node '{ctx.node}' marking the rendezvous complete, "
+                        f"quorum established within deadline"
+                    )
+                    logger.debug(msg)
+                    return _Action.MARK_RENDEZVOUS_COMPLETE
+                else:
+                    msg = f"The node '{ctx.node}' can't complete rendezvous: deadline reached"
+                    logger.debug(msg)
+            else:
+                msg = f"The node '{ctx.node}' can't complete rendezvous: not enough participants"
+                logger.debug(msg)
+        else:
+            # The rendezvous is not complete yet and we are not part of it. Try
+            # to join.
+            return _Action.ADD_TO_PARTICIPANTS
+
+        if _should_keep_alive(ctx):
+            return _Action.KEEP_ALIVE
+
+        # At this point either the rendezvous is not complete, but we are part
+        # of it, which means we have to wait for other participants to join; or
+        # the rendezvous is complete, but we are not part of it, which means we
+        # have to wait for the next round.
+        return _Action.SYNC
+
+
+class _RendezvousCloseOp:
+    """Represent a rendezvous close operation."""
+
+    def __call__(self, ctx: _RendezvousContext, deadline: float) -> _Action:
+        if ctx.state.closed:
+            return _Action.FINISH
+        if time.monotonic() > deadline:
+            return _Action.ERROR_TIMEOUT
+        return _Action.MARK_RENDEZVOUS_CLOSED
+
+
+class _RendezvousKeepAliveOp:
+    """Represent a rendezvous keep-alive update operation."""
+
+    def __call__(self, ctx: _RendezvousContext, deadline: float) -> _Action:
+        if _should_keep_alive(ctx):
+            if time.monotonic() > deadline:
+                return _Action.ERROR_TIMEOUT
+            return _Action.KEEP_ALIVE
+        return _Action.FINISH
+
+
+class DynamicRendezvousHandler(RendezvousHandler):
+    """Represent a handler that sets up a rendezvous among a set of nodes."""
+
+    # Static
+    _node_desc_generator = _NodeDescGenerator()
+
+    _this_node: _NodeDesc
+    _settings: RendezvousSettings
+    _backend_name: str
+    _store: Store
+    _state_holder: _RendezvousStateHolder
+    _op_executor: _RendezvousOpExecutor
+    _heartbeat_lock: threading.Lock
+    _keep_alive_timer: Optional[_PeriodicTimer]
+
+    @classmethod
+    def from_backend(
+        cls,
+        run_id: str,
+        store: Store,
+        backend: RendezvousBackend,
+        min_nodes: int,
+        max_nodes: int,
+        local_addr: Optional[str] = None,
+        timeout: Optional[RendezvousTimeout] = None,
+    ):
+        """Create a new :py:class:`DynamicRendezvousHandler`.
+
+        Args:
+            run_id:
+                The run id of the rendezvous.
+            store:
+                The C10d store to return as part of the rendezvous.
+            backend:
+                The backend to use to hold the rendezvous state.
+            min_nodes:
+                The minimum number of nodes to admit to the rendezvous.
+            max_nodes:
+                The maximum number of nodes to admit to the rendezvous.
+            local_addr:
+                The local node address.
+            timeout:
+                The timeout configuration of the rendezvous.
+        """
+        # We associate each handler instance with a unique node descriptor.
+        node = cls._node_desc_generator.generate(local_addr)
+
+        settings = RendezvousSettings(
+            run_id,
+            min_nodes,
+            max_nodes,
+            timeout or RendezvousTimeout(),
+            keep_alive_interval=timedelta(seconds=5),
+            keep_alive_max_attempt=3,
+        )
+
+        state_holder = _BackendRendezvousStateHolder(backend, settings)
+
+        return cls(node, settings, backend.name, store, state_holder)
+
+    def __init__(
+        self,
+        node: _NodeDesc,
+        settings: RendezvousSettings,
+        backend_name: str,
+        store: Store,
+        state_holder: _RendezvousStateHolder,
+    ) -> None:
+        if not settings.run_id:
+            raise ValueError("The run id must be a non-empty string.")
+
+        if settings.min_nodes < 1:
+            raise ValueError(
+                f"The minimum number of nodes ({settings.min_nodes}) must be greater than zero."
+            )
+
+        if settings.max_nodes < settings.min_nodes:
+            raise ValueError(
+                f"The maximum number of nodes ({settings.max_nodes}) must be greater than or equal "
+                f"to the minimum number of nodes ({settings.min_nodes})."
+            )
+
+        self._this_node = node
+
+        self._settings = settings
+
+        self._backend_name = backend_name
+
+        self._store = store
+
+        self._state_holder = state_holder
+
+        self._op_executor = _DistributedRendezvousOpExecutor(
+            self._this_node, self._state_holder, self._settings
+        )
+
+        self._heartbeat_lock = threading.Lock()
+
+        self._keep_alive_timer = None
+
+        # Cached shared store server reference
+        self._shared_tcp_store_server: Optional[dist.Store] = None
+
+        self._bootstrap_store_info: Optional[RendezvousStoreInfo] = None
+
+    def _record(
+        self,
+        message: str,
+        node_state: NodeState = NodeState.RUNNING,
+        rank: Optional[int] = None,
+    ) -> None:
+        construct_and_record_rdzv_event(
+            name=f"{self.__class__.__name__}.{get_method_name()}",
+            run_id=self._settings.run_id,
+            message=message,
+            node_state=node_state,
+            hostname=self._this_node.addr,
+            pid=self._this_node.pid,
+            local_id=self._this_node.local_id,
+            rank=rank,
+        )
+
+    def _create_tcp_store_server(self, bootstrap_store_info) -> dist.TCPStore:
+        return dist.TCPStore(
+            bootstrap_store_info.master_addr,
+            bootstrap_store_info.master_port,
+            is_master=True,
+            multi_tenant=True,
+        )
+
+    @property
+    def settings(self) -> RendezvousSettings:
+        """Get the settings of the rendezvous."""
+        return self._settings
+
+    def get_backend(self) -> str:
+        """See base class."""
+        return self._backend_name
+
+    @property
+    def use_agent_store(self) -> bool:
+        """See base class."""
+        return os.getenv("TORCH_DISABLE_SHARE_RDZV_TCP_STORE", "0") != "1"
+
+    def next_rendezvous(self) -> RendezvousInfo:
+        """See base class."""
+        msg = (
+            f"The node '{self._this_node}' attempts to join the next round of the rendezvous "
+            f"'{self._settings.run_id}'."
+        )
+        self._record(message=msg)
+        logger.info(msg)
+
+        try:
+            self._stop_heartbeats()
+
+            # Delay the execution for a small random amount of time if this is our
+            # first run. This will slightly skew the rendezvous attempts across the
+            # nodes and reduce the load on the backend.
+            if self._state_holder.state.round == 0:
+                _delay(seconds=(0, 0.3))
+
+            exit_op = _RendezvousExitOp()
+            join_op = _RendezvousJoinOp()
+
+            deadline = self._get_deadline(self._settings.timeout.join)
+            self._op_executor.run(exit_op, deadline)
+            self._op_executor.run(join_op, deadline, self._get_deadline)
+
+            self._start_heartbeats()
+
+            rank, world_size = self._get_world()
+            store = self._get_store()
+
+        except Exception as e:
+            self._record(
+                message=f"{type(e).__name__}: {str(e)}",
+                node_state=NodeState.FAILED,
+            )
+            raise
+
+        msg = (
+            f"The node '{self._this_node}' has joined round {self._state_holder.state.round} of "
+            f"the rendezvous '{self._settings.run_id}' as rank {rank} in a world of size "
+            f"{world_size}."
+        )
+        self._record(message=msg, rank=rank)
+        logger.info(msg)
+
+        # opt-out option of TCP store sharing
+        if os.getenv("TORCH_DISABLE_SHARE_RDZV_TCP_STORE", "0") == "1":
+            bootstrap_store_info = RendezvousStoreInfo.build(
+                rank, store, local_addr=self._this_node.addr
+            )
+            return RendezvousInfo(
+                store,
+                rank,
+                world_size,
+                bootstrap_store_info,
+            )
+
+        if self._bootstrap_store_info is None:
+            if isinstance(self._store, dist.TCPStore):
+                addr = self._store.host
+                port = self._store.port
+                self._bootstrap_store_info = RendezvousStoreInfo(
+                    master_addr=addr, master_port=port
+                )
+                if rank == 0:
+                    self._shared_tcp_store_server = self._store
+            else:
+                # If the store is not type of TCPStore start TCPStore server, which requries
+                # bootstrapping info across ranks
+                self._bootstrap_store_info = RendezvousStoreInfo.build(
+                    rank, store, local_addr=self._this_node.addr
+                )
+                if rank == 0:
+                    self._shared_tcp_store_server = self._create_tcp_store_server(
+                        self._bootstrap_store_info
+                    )
+
+        assert self._bootstrap_store_info is not None
+        if rank == 0:
+            assert self._shared_tcp_store_server is not None
+
+        return RendezvousInfo(
+            store,
+            rank,
+            world_size,
+            self._bootstrap_store_info,  # type: ignore[assignment]
+        )
+
+    def is_closed(self) -> bool:
+        """See base class."""
+        try:
+            with self._heartbeat_lock:
+                self._state_holder.sync()
+
+                return self._state_holder.state.closed
+
+        except Exception as e:
+            self._record(
+                message=f"{type(e).__name__}: {str(e)}",
+                node_state=NodeState.FAILED,
+            )
+            raise
+
+    def set_closed(self) -> None:
+        """See base class."""
+        try:
+            with self._heartbeat_lock:
+                self._close()
+        except Exception as e:
+            self._record(
+                message=f"{type(e).__name__}: {str(e)}",
+                node_state=NodeState.FAILED,
+            )
+            raise
+
+    def num_nodes_waiting(self) -> int:
+        """See base class."""
+        try:
+            with self._heartbeat_lock:
+                self._state_holder.sync()
+
+                return len(self._state_holder.state.wait_list)
+
+        except Exception as e:
+            self._record(
+                message=f"{type(e).__name__}: {str(e)}",
+                node_state=NodeState.FAILED,
+            )
+            raise
+
+    def get_run_id(self) -> str:
+        """See base class."""
+        return self._settings.run_id
+
+    def shutdown(self) -> bool:
+        """See base class."""
+        self._stop_heartbeats()
+
+        try:
+            self._close()
+
+            return True
+        except RendezvousError as ex:
+            msg = (
+                f"The node '{self._this_node}' has failed to shutdown the rendezvous "
+                f"'{self._settings.run_id}' due to an error of type {type(ex).__name__}."
+            )
+            self._record(message=msg, node_state=NodeState.FAILED)
+            logger.warning(msg)
+
+            return False
+        except Exception as e:
+            self._record(
+                message=f"{type(e).__name__}: {str(e)}",
+                node_state=NodeState.FAILED,
+            )
+            raise
+
+    def _close(self) -> None:
+        op = _RendezvousCloseOp()
+
+        deadline = self._get_deadline(self._settings.timeout.close)
+
+        self._op_executor.run(op, deadline)
+
+        msg = f"The node '{self._this_node}' has closed the rendezvous '{self._settings.run_id}'."
+        self._record(message=msg, node_state=NodeState.SUCCEEDED)
+        logger.info(msg)
+
+    @staticmethod
+    def _keep_alive_weak(weak_self) -> None:
+        self = weak_self()
+        if self is not None:
+            self._keep_alive()
+
+    def _keep_alive(self) -> None:
+        self._heartbeat_lock.acquire()
+
+        op = _RendezvousKeepAliveOp()
+
+        deadline = self._get_deadline(self._settings.timeout.heartbeat)
+
+        try:
+            self._op_executor.run(op, deadline)
+
+            msg = (
+                f"The node '{self._this_node}' has sent a keep-alive heartbeat to the rendezvous "
+                f"'{self._settings.run_id}'."
+            )
+            self._record(message=msg)
+            logger.debug(msg)
+        except RendezvousError as ex:
+            msg = (
+                f"The node '{self._this_node}' has failed to send a keep-alive heartbeat to the "
+                f"rendezvous '{self._settings.run_id}' due to an error of type {type(ex).__name__}."
+            )
+            self._record(message=msg, node_state=NodeState.FAILED)
+            logger.warning(msg)
+        finally:
+            self._heartbeat_lock.release()
+
+    def _start_heartbeats(self) -> None:
+        self._keep_alive_timer = _PeriodicTimer(
+            self._settings.keep_alive_interval, self._keep_alive_weak, weakref.ref(self)
+        )
+
+        self._keep_alive_timer.set_name(
+            f"RendezvousKeepAliveTimer_{self._this_node.local_id}"
+        )
+
+        self._keep_alive_timer.start()
+
+    def _stop_heartbeats(self) -> None:
+        if self._keep_alive_timer is None:
+            return
+
+        self._keep_alive_timer.cancel()
+
+    def _get_world(self) -> Tuple[int, int]:
+        state = self._state_holder.state
+
+        return state.participants[self._this_node], len(state.participants)
+
+    def _wrap_store(self, store: Store) -> Store:
+        key_prefix = (
+            f"torch.rendezvous.{self._settings.run_id}.{self._state_holder.state.round}"
+        )
+
+        return dist.PrefixStore(key_prefix, store)
+
+    def _get_store(self) -> Store:
+        return self._wrap_store(self._store)
+
+    def _get_deadline(self, timeout: timedelta) -> float:
+        return time.monotonic() + timeout.total_seconds()
+
+
+def _get_timeout(params: RendezvousParameters, key: str) -> Optional[timedelta]:
+    timeout = params.get_as_int(key + "_timeout")
+    if timeout is None:
+        return None
+    return timedelta(seconds=timeout)
+
+
+def create_handler(
+    store: Store, backend: RendezvousBackend, params: RendezvousParameters
+) -> DynamicRendezvousHandler:
+    """Create a new :py:class:`DynamicRendezvousHandler` from the specified parameters.
+
+    Args:
+        store:
+            The C10d store to return as part of the rendezvous.
+        backend:
+            The backend to use to hold the rendezvous state.
+
+    +-------------------+------------------------------------------------------+
+    | Parameter         | Description                                          |
+    +===================+======================================================+
+    | join_timeout      | The total time, in seconds, within which the         |
+    |                   | rendezvous is expected to complete. Defaults to 600  |
+    |                   | seconds.                                             |
+    +-------------------+------------------------------------------------------+
+    | last_call_timeout | An additional wait amount, in seconds, before        |
+    |                   | completing the rendezvous once the minimum number of |
+    |                   | nodes has been reached. Defaults to 30 seconds.      |
+    +-------------------+------------------------------------------------------+
+    | close_timeout     | The time, in seconds, within which the rendezvous is |
+    |                   | expected to close after a call to                    |
+    |                   | :py:meth:`RendezvousHandler.set_closed` or           |
+    |                   | :py:meth:`RendezvousHandler.shutdown`. Defaults to   |
+    |                   | 30 seconds.                                          |
+    +-------------------+------------------------------------------------------+
+    """
+    try:
+        timeout = RendezvousTimeout(
+            _get_timeout(params, "join"),
+            _get_timeout(params, "last_call"),
+            _get_timeout(params, "close"),
+        )
+
+        return DynamicRendezvousHandler.from_backend(
+            params.run_id,
+            store,
+            backend,
+            params.min_nodes,
+            params.max_nodes,
+            params.local_addr,
+            timeout,
+        )
+    except Exception as e:
+        construct_and_record_rdzv_event(
+            message=f"{type(e).__name__}: {str(e)}",
+            run_id=params.run_id,
+            node_state=NodeState.FAILED,
+        )
+        raise
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/etcd_rendezvous.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/etcd_rendezvous.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0aa3c8d8887d854f29374d4bdb5921ab9d4d156
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/etcd_rendezvous.py
@@ -0,0 +1,1077 @@
+#!/usr/bin/env python3
+# mypy: allow-untyped-defs
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+import json
+import logging
+import sys
+import threading
+import time
+from typing import Optional
+
+import etcd  # type: ignore[import]
+
+from torch.distributed.elastic.rendezvous import (
+    RendezvousClosedError,
+    RendezvousError,
+    RendezvousHandler,
+    RendezvousInfo,
+    RendezvousParameters,
+    RendezvousStoreInfo,
+    RendezvousTimeoutError,
+)
+
+from .etcd_store import cas_delay, EtcdStore
+from .utils import parse_rendezvous_endpoint
+
+
+__all__ = [
+    "EtcdRendezvousRetryableFailure",
+    "EtcdRendezvousRetryImmediately",
+    "EtcdRendezvousHandler",
+    "EtcdRendezvous",
+    "create_rdzv_handler",
+]
+
+_log_fmt = logging.Formatter("%(levelname)s %(asctime)s %(message)s")
+_log_handler = logging.StreamHandler(sys.stderr)
+_log_handler.setFormatter(_log_fmt)
+
+logger = logging.getLogger(__name__)
+logger.propagate = False
+logger.setLevel(logging.INFO)
+logger.addHandler(_log_handler)
+
+
+# Retryable failure exception means the we were too late to make
+# a desired state transition (e.g. because of a race condition),
+# and should now restart from the beginning.
+# A small delay is recommended to avoid spamming Etcd.
+class EtcdRendezvousRetryableFailure(Exception):
+    pass
+
+
+# Similar to retryable failure, but the new state we observed suggests we
+# can re-try immediately, i.e. without a need for "safety delay".
+class EtcdRendezvousRetryImmediately(Exception):
+    pass
+
+
+# Default timeout for the rendezvous.
+_DEFAULT_TIMEOUT: int = 600  # 10 minutes
+
+# Additional waiting time after reaching the minimum number of nodes
+# in case the rendezvous is elastic (min != max).
+_DEFAULT_LAST_CALL_TIMEOUT: int = 30  # 30 seconds
+
+# Various constants used internally in EtcdRendezvous
+CONST_ETCD_SETUP_TTL = 5
+CONST_ETCD_FROZEN_TTL = 10
+CONST_ETCD_JOINABLE_EPHEMERAL_TTL = 10
+
+# Ephemeral node TTL for worker's keep-alive key:
+CONST_WORKER_KEEPALIVE_TTL = 10
+
+# TTL for the ephemeral run_id-specific directory. All rendezvous state data
+# for a specific run_id (job instance) is contained within directory.
+# Its only role is to clean-up rendezvous data from old runs (for the case when
+# etcd server is persistent), and has no affect on correctness, but should be
+# larger than any timeouts that a worker process is expected to survive:
+CONST_RUNID_SUBROOT_TTL = 7200  # 2 hours
+
+
+class EtcdRendezvousHandler(RendezvousHandler):
+    """
+    Implements a
+    :py:class:`torch.distributed.elastic.rendezvous.RendezvousHandler` interface
+    backed by
+    :py:class:`torch.distributed.elastic.rendezvous.etcd_rendezvous.EtcdRendezvous`.
+    ``EtcdRendezvousHandler`` uses a URL to configure the type of rendezvous to
+    use and to pass implementation specific configurations to the rendezvous
+    module. The basic etcd rendezvous configuration URL looks like the following
+    ::
+
+     etcd://:/?min_workers=&max_workers=  # noqa: W605
+
+     -- example --
+
+     etcd://localhost:2379/1234?min_workers=1&max_workers=3
+
+    The URL above is interpreted as follows:
+
+    1. Use the rendezvous handler that is registered with the ``etcd``
+       scheme
+    2. The ``etcd`` endpoint to use is ``localhost:2379``
+    3. ``job_id == 1234`` is used as the prefix in etcd (this allows one to
+       share a common etcd server for multiple jobs so long as the
+       ``job_ids`` are guaranteed to be unique). Note that the job id can be
+       any string (e.g. does not need to be a number) as long as it is
+       unique.
+    4. ``min_workers=1`` and ``max_workers=3`` specifies a range for
+       membership size - Torch Distributed Elastic starts running the job as
+       long as the cluster size is greater than or equal to ``min_workers``
+       and admits up to ``max_workers`` into the cluster.
+
+    Below are a full list of the parameters that can be passed to etcd
+    rendezvous:
+
+    +--------------------------------------------+--------------------------+
+    | Parameter                                  | Description              |
+    +============================================+==========================+
+    | min_workers                                | minimum number of        |
+    |                                            | workers for the          |
+    |                                            | rendezvous to be valid   |
+    +--------------------------------------------+--------------------------+
+    | max_workers                                | maximum number of        |
+    |                                            | workers to admit         |
+    +--------------------------------------------+--------------------------+
+    | timeout                                    | total timeout within     |
+    |                                            | which next_rendezvous is |
+    |                                            | expected to succeed      |
+    |                                            | (default 600s)           |
+    +--------------------------------------------+--------------------------+
+    | last_call_timeout                          | additional wait amount   |
+    |                                            | ("last call") after min  |
+    |                                            | number of workers has    |
+    |                                            | been reached (defaults   |
+    |                                            | to 30s)                  |
+    +--------------------------------------------+--------------------------+
+    | etcd_prefix                                | path prefix (from etcd   |
+    |                                            | root), inside which all  |
+    |                                            | etcd nodes will be       |
+    |                                            | created (defaults to     |
+    |                                            | ``/torchelastic/p2p``)   |
+    +--------------------------------------------+--------------------------+
+    """
+
+    def __init__(self, rdzv_impl: "EtcdRendezvous", local_addr: Optional[str]):
+        """
+        Args:
+            rdzv_impl: the implementation of the rendezvous
+            local_addr: the local address of the current node
+        """
+
+        self._rdzv_impl = rdzv_impl
+        self._local_addr = local_addr
+
+    def __del__(self):
+        # TODO: look into using weakref here instead.
+        del self._rdzv_impl
+
+    def get_backend(self) -> str:
+        return "etcd"
+
+    def next_rendezvous(self):
+        rdzv_version, rank, world_size = self._rdzv_impl.rendezvous_barrier()
+
+        logger.info("Creating EtcdStore as the c10d::Store implementation")
+        store = self._rdzv_impl.setup_kv_store(rdzv_version)
+
+        bootstrap_store_info = RendezvousStoreInfo.build(
+            rank, store, local_addr=self._local_addr
+        )
+        return RendezvousInfo(store, rank, world_size, bootstrap_store_info)
+
+    def is_closed(self):
+        try:
+            _, state = self._rdzv_impl.get_rdzv_state()
+            return state["status"] == "closed"
+        except etcd.EtcdKeyNotFound:
+            # No rendezvous state, so it cannot be closed.
+            return False
+
+    def set_closed(self):
+        self._rdzv_impl.set_closed()
+
+    def num_nodes_waiting(self):
+        try:
+            _, state = self._rdzv_impl.get_rdzv_state()
+            if state["status"] == "final":
+                return state["num_workers_waiting"]
+        except etcd.EtcdKeyNotFound:
+            pass
+        return 0
+
+    def get_run_id(self) -> str:
+        return self._rdzv_impl._run_id
+
+    def shutdown(self) -> bool:
+        try:
+            self.set_closed()
+            return True
+        except BaseException as e:
+            logger.warning("Shutdown failed. Error occurred: %s", str(e))
+            return False
+
+
+# TODO: we should probably handle a few additional errors,
+# like EtcdLeaderElectionInProgress and EtcdWatcherCleared. These are
+# only relevant for multi-node Etcd ensemble. A simple retry would work,
+# but is verbose to add everywhere. Consider wrapping the client calls
+# into auto-retry for these errors?
+#
+class EtcdRendezvous:
+    """A rendezvous implementation that uses `etcd `__ as the backend store."""
+
+    def __init__(
+        self,
+        client,
+        prefix,
+        run_id,
+        num_min_workers,
+        num_max_workers,
+        timeout,
+        last_call_timeout,
+    ):
+        self.client = client
+        logger.info("Etcd machines: %s", self.client.machines)
+
+        self._prefix = prefix
+        self._run_id = run_id
+        self._num_min_workers = num_min_workers
+        self._num_max_workers = num_max_workers
+        self._timeout = timeout
+        self._last_call_timeout = last_call_timeout
+
+        # For cleaning up TTL refresher threads (for ephemeral keys)
+        self._lease_run_id_stop = None
+        self._lease_this_rank_stop = None
+
+        if not self._prefix.endswith("/"):
+            self._prefix += "/"
+
+        # Setup a permanent prefix dir, if didn't exist
+        if self._prefix != "/":
+            self.create_path_if_not_exists(self._prefix)
+
+        # Lease a "sub-root" node specific to this job instance (run_id)
+        self.create_path_if_not_exists(self.get_path(""), ttl=CONST_RUNID_SUBROOT_TTL)
+        self._lease_run_id_stop = self.setup_lease_renewal(
+            self.get_path(""), ttl=CONST_RUNID_SUBROOT_TTL
+        )
+
+        # Subdir for all rendezvous work
+        self.create_path_if_not_exists(self.get_path("/rdzv"))
+
+        # Create a rendezvous version counter, if doesn't exist
+        try:
+            self.client.write(
+                key=self.get_path("/rdzv/version_counter"), value="0", prevExist=False
+            )
+        except etcd.EtcdAlreadyExist:
+            pass
+
+    def __del__(self):
+        # TODO: look into using weakref here instead.
+        if self._lease_run_id_stop is not None:
+            self._lease_run_id_stop.set()
+
+        if self._lease_this_rank_stop is not None:
+            self._lease_this_rank_stop.set()
+
+    def rendezvous_barrier(self):
+        """
+        Main entry point for next rendezvous.
+
+        This method is blocking until rendezvous succeeds or a timeout occurs.
+
+        Returns:
+             ``(rdzv_version, rank, world_size)``
+
+        Raises:
+            RendezvousTimeoutError - timeout waiting for rendezvous
+            RendezvousClosedError - rendezvous is or was closed while waiting
+            RendezvousError - other persistent errors that
+             render the rendezvous non-retryable
+        """
+        self._rendezvous_deadline = time.time() + self._timeout
+        while True:
+            if time.time() > self._rendezvous_deadline:
+                raise RendezvousTimeoutError
+
+            logger.info("Attempting to join next rendezvous")
+            try:
+                # Dis-own our lease in the previous rendezvous, if exists
+                if self._lease_this_rank_stop is not None:
+                    self._lease_this_rank_stop.set()
+
+                return self.init_phase()
+
+            except EtcdRendezvousRetryImmediately:
+                # The type of failure suggests we can retry without delay
+                pass
+
+            except EtcdRendezvousRetryableFailure:
+                # In case of retryable failure, wait a small delay
+                # to avoid spamming etcd
+                time.sleep(1)
+
+            except RendezvousTimeoutError:
+                logger.info("Rendezvous timeout occurred in EtcdRendezvousHandler")
+                raise
+
+            except RendezvousClosedError:
+                logger.info(
+                    "Rendezvous for run_id=%s was observed to be closed", self._run_id
+                )
+                raise
+
+            except RendezvousError:
+                raise
+
+            except Exception as e:
+                # In case of a general exception, wait a small delay
+                # to avoid spamming etcd
+                # FIXME: there are a few things that fall under this like
+                # etcd.EtcdKeyNotFound, etc, which could be handled more explicitly.
+                logger.info("Rendezvous attempt failed, will retry. Reason: %s", e)
+                time.sleep(1)
+
+    def init_phase(self):
+        """
+        Initially, the rendezvous state is expected to be one of:
+
+        1. empty (non-existent) - in this case we try to create a new one.
+        2. joinable - we try to join it.
+        3. final - we announce ourselves as waiting, and go into monitoring mode
+
+        Any other state is considered transitional, and will be retried after
+        a short delay.
+
+        Returns:
+            ``(rdzv_version, rank, world_size)``
+
+        Raises:
+            RendezvousClosedError - current rendezvous was/is closed
+            EtcdRendezvousRetryableFailure - observed some intermediate
+             state, which is best handled by retrying later
+        """
+        try:
+            active_version = self.try_create_rendezvous()
+            state = json.loads(active_version.value)
+            logger.info("New rendezvous state created: %s", state)
+        except etcd.EtcdAlreadyExist:
+            active_version, state = self.get_rdzv_state()
+            # Note: it is possible for above query to fail (etcd.EtcdKeyNotFound),
+            # but this is ok for us - just means we'll restart from beginning.
+            logger.info("Observed existing rendezvous state: %s", state)
+
+        if state["status"] == "closed":
+            raise RendezvousClosedError
+
+        if state["status"] == "joinable":
+            return self.join_phase(state["version"])
+
+        if state["status"] == "final":
+            self.handle_existing_rendezvous(state["version"])
+            raise EtcdRendezvousRetryImmediately
+
+        self.try_wait_for_state_change(etcd_index=active_version.etcd_index + 1)
+        raise EtcdRendezvousRetryableFailure
+
+    def join_phase(self, expected_version):
+        """
+        We observed a rendezvous state in 'joinable' state, and attempt to join this
+        particular version, and then wait for all other peers to join.
+        """
+        # Failure to join will propagate an exception, causing a re-entry.
+        active_version, this_rank = self.join_rendezvous(expected_version)
+        state = json.loads(active_version.value)
+        logger.info(
+            "Joined rendezvous version %s as rank %s. Full state: %s",
+            state["version"],
+            this_rank,
+            state,
+        )
+
+        # If this worker was first to reach num_min_workers requirement,
+        # and rendezvous is still joinable (therefore it is elastic),
+        # then this worker will be responsible for waiting out the "last call"
+        # timeout and closing (i.e. transitioning to 'frozen') the rendezvous
+        # afterwards.
+        # As a safety against a potential failure of this worker (during the
+        # last call timeout), the rendezvous state is made ephemeral
+        # when min_num_workers is reached.
+
+        if this_rank == self._num_min_workers - 1 and state["status"] == "joinable":
+            logger.info("Rank %s is responsible for join last call.", this_rank)
+            last_call_deadline = time.time() + self._last_call_timeout
+            self.handle_join_last_call(expected_version, last_call_deadline)
+            logger.info("Rank %s finished join last call.", this_rank)
+
+        # Wait for rendezvous state to be frozen, which means a fixed set of peers
+        logger.info("Waiting for remaining peers.")
+        active_version = self.wait_for_peers(expected_version)
+        state = json.loads(active_version.value)
+
+        assert (
+            state["version"] == expected_version
+        ), "Logic error: failed to observe version mismatch"
+
+        return self.confirm_phase(expected_version, this_rank)
+
+    def confirm_phase(self, expected_version, this_rank):
+        """
+        Once the rendezvous state transitions from 'joinable' to 'frozen',
+        we have every participant confirm their membership and setup per-member
+        keep-alive TTL keys, and then wait for all other participants to confirm,
+        which would then successfully conclude this rendezvous.
+        """
+        logger.info("All peers arrived. Confirming membership.")
+        self.confirm_membership(expected_version, this_rank)
+
+        logger.info("Waiting for confirmations from all peers.")
+        active_version = self.wait_for_final(expected_version)
+        state = json.loads(active_version.value)
+
+        logger.info(
+            "Rendezvous version %s is complete. Final state: %s",
+            state["version"],
+            state,
+        )
+
+        # Rendezvous version number; our rank in it; world size
+        return state["version"], this_rank, len(state["participants"])
+
+    def handle_existing_rendezvous(self, expected_version):
+        """
+        Handle the case when there's an existing (state 'final) rendezvous already
+        in place, and we have to announce ourselves waiting, and wait until
+        the next rendezvous opportunity.
+        """
+        # If state is 'final' -> increment num_workers_waiting
+        # Then, observe state changes:
+        #   1. if it's no longer final -> bail out and re-try
+        #   2. if keep alives are missing, destroy it and bail out.
+        active_state = self.announce_self_waiting(expected_version)
+        logger.info(
+            "Added self to waiting list. Rendezvous full state: %s", active_state.value
+        )
+
+        self.wait_for_rendezvous_to_free(expected_version)
+        logger.info(
+            "Previously existing rendezvous state changed. Will re-try joining."
+        )
+
+    def try_create_rendezvous(self):
+        """
+        Create new rendezvous state or raise an exception that indicates an unexpected state (e.g. already exists).
+
+        Raises:
+             RendezvousError - on unexpected state
+        """
+        # Initially active_version is ephemeral - this is to handle the
+        # possibility that might fail to complete the setup transaction,
+        # i.e. the transition "setup" -> "joinable".
+        active_version = self.client.write(
+            key=self.get_path("/rdzv/active_version"),
+            value=json.dumps({"status": "setup"}),
+            prevExist=False,
+            ttl=CONST_ETCD_SETUP_TTL,
+        )
+
+        try:
+            version_counter = self.client.get(self.get_path("/rdzv/version_counter"))
+            version_counter.value = str(int(version_counter.value) + 1)
+            self.client.update(version_counter)
+        except (etcd.EtcdKeyNotFound, etcd.EtcdCompareFailed) as e:
+            raise RendezvousError(
+                "Unexpected state of EtcdRendezvousHandler, worker needs to die."
+            ) from e
+
+        # Any failure below results in declaring a retryable rendezvous failure.
+        # The ephemeral /rdzv/active_version will expire and someone can then
+        # re-try the setup process.
+
+        # Create directory node for participant data
+        self.client.write(
+            key=self.get_path(f"/rdzv/v_{version_counter.value}"),
+            value=None,
+            dir=True,
+            prevExist=False,
+        )
+
+        # Publish rendezvous version and signal it is ready-to-be-joined.
+        # If rendezvous was set closed just before this, a retry will happen,
+        # where the closed condition will be handled.
+        return self.client.test_and_set(
+            key=self.get_path("/rdzv/active_version"),
+            value=json.dumps(
+                {
+                    "status": "joinable",
+                    "version": version_counter.value,
+                    "participants": [],
+                }
+            ),
+            prev_value=active_version.value,
+        )
+
+    def join_rendezvous(self, expected_version):
+        """Helper method for the join phase."""
+        # Use compare-and-swap to add self to rendezvous state:
+        while True:
+            cas_delay()
+            active_version, state = self.get_rdzv_state()
+
+            if state["status"] != "joinable":
+                raise EtcdRendezvousRetryableFailure(
+                    "Rendezvous state became non-joinable before we could join. "
+                    "Must join next one."
+                )
+
+            if state["version"] != expected_version:
+                raise EtcdRendezvousRetryImmediately(
+                    "Rendezvous version changed. Must try join the new one."
+                )
+
+            assert (
+                len(state["participants"]) < self._num_max_workers
+            ), "Logic error: joinable rendezvous should always have space left"
+
+            this_rank = len(state["participants"])
+            state["participants"].append(this_rank)
+
+            # When reaching min workers, or changing state to frozen, we'll set
+            # the active_version node to be ephemeral.
+            set_ttl: Optional[int] = None
+            if len(state["participants"]) == self._num_max_workers:
+                state["status"] = "frozen"
+                state["keep_alives"] = []
+                set_ttl = CONST_ETCD_FROZEN_TTL
+            elif len(state["participants"]) >= self._num_min_workers:
+                set_ttl = CONST_ETCD_JOINABLE_EPHEMERAL_TTL
+
+            try:
+                # Compare-and-swap.
+                active_version = self.client.test_and_set(
+                    key=self.get_path("/rdzv/active_version"),
+                    value=json.dumps(state),
+                    prev_value=active_version.value,
+                    ttl=set_ttl,
+                )
+                # We succeeded joining.
+                return active_version, this_rank
+
+            except etcd.EtcdCompareFailed:
+                logger.info("Join rendezvous CAS unsuccessful, retrying")
+
+    def wait_for_peers(self, expected_version):
+        """Helper method for the join phase."""
+        active_version, state = self.get_rdzv_state()
+        while True:
+            if state["status"] == "frozen" and state["version"] == expected_version:
+                # Success, all peers arrived.
+                return active_version
+
+            elif state["status"] == "joinable" and state["version"] == expected_version:
+                # Continue waiting for any interesting events.
+                active_version, state = self.try_wait_for_state_change(
+                    etcd_index=active_version.etcd_index + 1
+                )
+
+            else:
+                # No valid transition possible at this point
+                raise EtcdRendezvousRetryableFailure(
+                    "Rendezvous state transition no longer possible. Must re-enter."
+                )
+
+    def confirm_membership(self, expected_version, this_rank):
+        """Helper method for the confirm phase."""
+        # Compare-and-swap loop
+        while True:
+            cas_delay()
+            active_version, state = self.get_rdzv_state()
+
+            if state["status"] != "frozen":
+                raise EtcdRendezvousRetryImmediately(
+                    "Rendezvous no longer frozen, before we confirmed. "
+                    "Must join next one"
+                )
+            if state["version"] != expected_version:
+                raise EtcdRendezvousRetryImmediately(
+                    "Rendezvous version changed. Must try join the new one."
+                )
+
+            this_lease_key = self.get_path(
+                f"/rdzv/v_{expected_version}/rank_{this_rank}"
+            )
+            self.client.set(this_lease_key, value=None, ttl=CONST_WORKER_KEEPALIVE_TTL)
+
+            state["keep_alives"].append(this_lease_key)
+            if len(state["keep_alives"]) == len(state["participants"]):
+                # Everyone confirmed (this rank is last to do so)
+                state["status"] = "final"
+                state["num_workers_waiting"] = 0
+                finalize = True
+            else:
+                finalize = False
+
+            try:
+                # Compare-and-swap. If new state is still frozen, keep it ephemeral.
+                active_version = self.client.test_and_set(
+                    key=self.get_path("/rdzv/active_version"),
+                    value=json.dumps(state),
+                    prev_value=active_version.value,
+                    ttl=None if finalize else CONST_ETCD_FROZEN_TTL,
+                )
+
+                self._lease_this_rank_stop = self.setup_lease_renewal(
+                    this_lease_key, ttl=CONST_WORKER_KEEPALIVE_TTL
+                )
+                return active_version
+
+            except etcd.EtcdCompareFailed:
+                logger.info("Confirm membership CAS unsuccessful, retrying")
+
+    def wait_for_final(self, expected_version):
+        """Helper method for the confirm phase."""
+        active_version, state = self.get_rdzv_state()
+        while True:
+            if state["status"] == "final" and state["version"] == expected_version:
+                # Success. This rendezvous is final, and we accept it.
+                return active_version
+
+            elif state["status"] == "frozen" and state["version"] == expected_version:
+                # Continue waiting for any interesting events.
+                active_version, state = self.try_wait_for_state_change(
+                    etcd_index=active_version.etcd_index + 1
+                )
+
+            else:
+                # No valid transition possible at this point
+                raise EtcdRendezvousRetryableFailure(
+                    "Rendezvous state transition no longer possible. Must re-enter."
+                )
+
+    def announce_self_waiting(self, expected_version):
+        """
+        Announce this worker is waiting (via num_workers_waiting counter) to join next
+        rendezvous, but only if state and version match.
+        """
+        while True:
+            cas_delay()
+            active_version, state = self.get_rdzv_state()
+
+            if state["status"] != "final" or state["version"] != expected_version:
+                raise EtcdRendezvousRetryImmediately
+
+            # Increment counter to signal an additional waiting worker.
+            state["num_workers_waiting"] += 1
+
+            try:
+                active_version = self.client.test_and_set(
+                    key=self.get_path("/rdzv/active_version"),
+                    value=json.dumps(state),
+                    prev_value=active_version.value,
+                )
+                return active_version
+
+            except etcd.EtcdCompareFailed:
+                logger.info("Announce self as waiting CAS unsuccessful, retrying")
+
+    def wait_for_rendezvous_to_free(self, expected_version):
+        """
+        When there's an existing valid rendezvous in state 'final', we have to wait until the next opportunity to join.
+
+        Such opportunity may come from:
+
+        1. rendezvous state changed by someone else, in which case we unblock and retry.
+        2. rendezvous becomes invalid because at least one member failed to renew their
+           leased keep_alive node. We detect this, and destroy the rendezvous.
+        """
+        active_version, state = self.get_rdzv_state()
+        while True:
+            if state["status"] != "final" or state["version"] != expected_version:
+                return
+
+            # Check if current rendezvous state is valid, in the sense that all
+            # its members are alive (renewing their lease).
+            # If not, try destroy this rendezvous, so a new one can be created.
+            alive_members = self.client.get(
+                self.get_path(f"/rdzv/v_{expected_version}")
+            )
+            keep_alive_keys = [ch.key for ch in alive_members.children]
+
+            for key in state["keep_alives"]:
+                if key not in keep_alive_keys:
+                    # This participant didn't renew their lease. We'll declare this
+                    # rendezvous version as dead (but only if it hadn't changed)
+                    logger.info("Keep-alive key %s is not renewed.", key)
+                    logger.info(
+                        "Rendezvous version %s is incomplete. ", expected_version
+                    )
+                    logger.info("Attempting to destroy it.")
+
+                    # Compare-and-delete operation. Throws if compare failed,
+                    # which means rendezvous was already destroyed/re-created/closed,
+                    # and we can try to re-enter the barrier.
+                    self.client.delete(
+                        key=self.get_path("/rdzv/active_version"),
+                        prevValue=active_version.value,
+                    )
+
+                    logger.info(
+                        "Destroyed rendezvous version %s successfully.",
+                        expected_version,
+                    )
+
+                    # We can return (and retry) immediately
+                    return
+
+            # Existing rendezvous seems valid, no reason to destroy it.
+            # We just have to wait until something changes and re-check.
+            try:
+                overall_timeout = (
+                    max(self._rendezvous_deadline - time.time(), 0.0) + 1.0
+                )
+                self.client.watch(
+                    key=self.get_path("/rdzv"),
+                    index=active_version.etcd_index + 1,
+                    recursive=True,
+                    timeout=overall_timeout,
+                )
+            except (etcd.EtcdEventIndexCleared, etcd.EtcdWatchTimedOut):
+                pass
+
+            if time.time() > self._rendezvous_deadline:
+                raise RendezvousTimeoutError
+            active_version, state = self.get_rdzv_state()
+
+    def handle_join_last_call(self, expected_version, deadline):
+        """
+        After we reach min number of workers, one particular worker takes on the
+        responsibility of waiting an additional timeout before closing the join window.
+        If the worker responsible for this fails, the rendezvous will be destroyed due
+        to expiring TTL, and the other participants will re-rendezvous.
+
+        Here we expect to see state 
+        Exit gracefully if either:
+
+        1. state becomes 
+        2. timeout happens (reaching deadline), in which case
+           we try the transition to 
+
+        Exit with exception otherwise.
+        """
+        active_version, state = self.get_rdzv_state()
+        while True:
+            if state["status"] == "frozen" and state["version"] == expected_version:
+                # Worker set became frozen before last-call timeout. This is possible
+                # when num_max_workers is reached before the timeout.
+                return
+
+            if state["status"] != "joinable" or state["version"] != expected_version:
+                raise EtcdRendezvousRetryableFailure(
+                    "Rendezvous state transition no longer possible. Must re-enter."
+                )
+
+            # If timeout occurred, attempt a state transition (joinable -> frozen)
+            if time.time() >= deadline:
+                state["status"] = "frozen"
+                state["keep_alives"] = []
+                try:
+                    active_version = self.client.test_and_set(
+                        key=self.get_path("/rdzv/active_version"),
+                        value=json.dumps(state),
+                        prev_value=active_version.value,
+                        ttl=CONST_ETCD_FROZEN_TTL,
+                    )
+                    # We successfully made this rendezvous frozen.
+                    return
+                except etcd.EtcdCompareFailed:
+                    logger.info(
+                        "Join last-call transition CAS unsuccessful. Will retry"
+                    )
+                    cas_delay()
+                    active_version, state = self.get_rdzv_state()
+                    continue
+
+            # Timeout did not occur, so we must refresh TTL, and wait for
+            # further changes. Note: we only want TTL to be refreshed if
+            # state is still joinable, hence we use CAS for that here,
+            # even though we don't change any of the data.
+            try:
+                active_version = self.client.test_and_set(
+                    key=self.get_path("/rdzv/active_version"),
+                    value=active_version.value,
+                    prev_value=active_version.value,
+                    ttl=CONST_ETCD_JOINABLE_EPHEMERAL_TTL,
+                )
+
+                # Minimize "oversleeping":
+                timeout = min(
+                    CONST_ETCD_JOINABLE_EPHEMERAL_TTL / 2,
+                    deadline - time.time() + 1.0,  # Oversleeping by 1s is ok.
+                )
+                active_version, state = self.try_wait_for_state_change(
+                    etcd_index=active_version.etcd_index + 1, timeout=timeout
+                )
+            except etcd.EtcdCompareFailed:
+                logger.info("Join last-call TTL refresh CAS unsuccessful, will retry")
+                cas_delay()
+                active_version, state = self.get_rdzv_state()
+
+    def set_closed(self):
+        """
+        Mark rendezvous 'closed' for current run_id, which is used to signal other
+        participants to not attempt to perform (re-)rendezvous. This is useful
+        when one of the workers decides the job is complete.
+        """
+        while True:
+            active_version, state = self.get_rdzv_state()
+
+            if state["status"] == "closed":
+                # Already closed by someone else.
+                return
+
+            state["status"] = "closed"
+            try:
+                self.client.test_and_set(
+                    key=self.get_path("/rdzv/active_version"),
+                    value=json.dumps(state),
+                    prev_value=active_version.value,
+                )
+                return
+
+            except etcd.EtcdCompareFailed:
+                logger.info("Set closed CAS unsuccessful, retrying")
+                cas_delay()
+
+    def get_rdzv_state(self):
+        active_version = self.client.get(key=self.get_path("/rdzv/active_version"))
+        return active_version, json.loads(active_version.value)
+
+    def try_wait_for_state_change(self, etcd_index, timeout=None):
+        # Don't sleep past the overall deadline (at least more than by 1s)
+        overall_timeout = max(self._rendezvous_deadline - time.time(), 0.0) + 1.0
+        timeout = overall_timeout if timeout is None else min(timeout, overall_timeout)
+
+        try:
+            self.client.watch(
+                self.get_path("/rdzv/active_version"), index=etcd_index, timeout=timeout
+            )
+        except (etcd.EtcdEventIndexCleared, etcd.EtcdWatchTimedOut):
+            pass
+
+        if time.time() > self._rendezvous_deadline:
+            raise RendezvousTimeoutError
+
+        # Unfortunately, we have to do another fetch in order to get last etcd_index.
+        return self.get_rdzv_state()
+
+    def get_path(self, path):
+        if not path.startswith("/"):
+            path = "/" + path
+
+        return f"{self._prefix}run_{self._run_id}{path}"
+
+    def create_path_if_not_exists(self, full_path, ttl=None):
+        try:
+            self.client.write(
+                key=full_path, value=None, dir=True, prevExist=False, ttl=ttl
+            )
+        except etcd.EtcdAlreadyExist:
+            pass
+
+    def setup_lease_renewal(self, full_path, ttl):
+        # NOTE: For ephemeral key TTL renewal (~lease) to work correctly,
+        # make sure you don't call any long-blocking methods that do not
+        # release the Python's GIL! An example of this is calling a pybind11
+        # extension function that is blocking / long-running, but is not
+        # doing a scoped release of the GIL.
+        def lease_worker(client, path, ttl, stop_event):
+            while True:
+                try:
+                    client.refresh(path, ttl=ttl)
+                except etcd.EtcdKeyNotFound:
+                    break
+                except ConnectionRefusedError:
+                    # This error usually occurs during test when the server already got terminated but the
+                    # python garbage collector have not yet invoked the __del__ method.
+                    break
+
+                if stop_event.wait(timeout=ttl / 2):
+                    break
+
+        lease_stop_event = threading.Event()
+        lease_thread = threading.Thread(
+            target=lease_worker, args=(self.client, full_path, ttl, lease_stop_event)
+        )
+
+        lease_thread.daemon = True
+        lease_thread.start()
+
+        return lease_stop_event
+
+    def store_extra_data(self, rdzv_version, key, value):
+        node = self.get_path(f"/rdzv/v_{rdzv_version}/extra_data")
+        try:
+            # If first time we are storing anything:
+            extra_data = self.client.write(
+                key=node, value=json.dumps({key: value}), prevExist=False
+            )
+            return
+        except etcd.EtcdAlreadyExist:
+            pass
+
+        # CAS loop, to make sure we don't lose concurrent stores.
+        while True:
+            # We never delete extra_data. Failure here should be fatal, no special handling.
+            extra_data = self.client.get(node)
+
+            new_extra_data_value = json.loads(extra_data.value)
+            new_extra_data_value[key] = value
+
+            try:
+                extra_data = self.client.test_and_set(
+                    key=node,
+                    value=json.dumps(new_extra_data_value),
+                    prev_value=extra_data.value,
+                )
+                return
+            except etcd.EtcdCompareFailed:
+                logger.info("Store extra_data CAS unsuccessful, retrying")
+                time.sleep(0.1)
+
+    def load_extra_data(self, rdzv_version, key, timeout=None):
+        # 'extra_data' node itself, and the directory it is located in:
+        node = self.get_path(f"/rdzv/v_{rdzv_version}/extra_data")
+        node_dir = self.get_path(f"/rdzv/v_{rdzv_version}")
+
+        # TODO: implement timeout
+        # https://github.com/pytorch/elastic/issues/12
+        while True:
+            # Combined wait for the node itself, and the key inside it.
+            root = self.client.get(node_dir)
+
+            # Find the extra_data node, if it exists
+            extra_data = [n for n in root.children if n.key == node]
+            assert len(extra_data) <= 1
+
+            # Node for extra_data exists, check the desired key inside it.
+            if len(extra_data) == 1:
+                extra_data_dict = json.loads(extra_data[0].value)
+                if key in extra_data_dict:
+                    return extra_data_dict[key]
+
+            # The 'extra_data' node doesn't exist, or they key isn't published yet.
+            # Wait for interesting events on the extra_data node and retry.
+            try:
+                self.client.watch(node, index=root.etcd_index + 1)
+            except (etcd.EtcdEventIndexCleared, etcd.EtcdWatchTimedOut):
+                pass
+
+    def setup_kv_store(self, rdzv_version):
+        store_path = self.get_path(f"/rdzv/v_{rdzv_version}/kv")
+        self.create_path_if_not_exists(store_path)
+        return EtcdStore(etcd_client=self.client, etcd_store_prefix=store_path)
+
+
+def _create_etcd_client(params: RendezvousParameters) -> etcd.Client:
+    """Create a new ``etcd.Client`` from the specified ``RendezvousParameters``."""
+    hostname, port = parse_rendezvous_endpoint(params.endpoint, 2379)
+
+    # The communication protocol
+    protocol = params.config.get("protocol")
+    if protocol is None:
+        protocol = "http"
+    else:
+        if protocol != "http" and protocol != "https":
+            raise ValueError("The etcd protocol must be HTTP or HTTPS.")
+
+    # The SSL client certificate
+    ssl_cert = params.config.get("cert")
+    if ssl_cert is not None:
+        cert_key = params.config.get("key")
+        if cert_key is not None:
+            # The etcd client expects the certificate key as the second element
+            # of the `cert` tuple.
+            ssl_cert = (ssl_cert, cert_key)
+
+    # The root certificate
+    ca_cert = params.config.get("cacert")
+
+    return etcd.Client(
+        hostname,
+        port,
+        protocol=protocol,
+        cert=ssl_cert,
+        ca_cert=ca_cert,
+        allow_reconnect=True,
+    )
+
+
+# Handler for torch.distributed "static" registration
+def create_rdzv_handler(params: RendezvousParameters) -> RendezvousHandler:
+    """
+    Usage:
+
+    ::
+
+    rdzv_params = RendezvousParameters(
+                        backend="etcd",
+                        endpoint="192.168.0.42:2379",
+                        run_id="123",
+                        min_nodes=4,
+                        max_nodes=8,
+                        timeout=300,
+                        last_call_timeout=30,
+                        etcd_prefix="custom_prefix",
+                        protocol="https",
+                        cacert="/etc/kubernetes/certs/ca.crt",
+                        cert="/etc/kubernetes/certs/client.crt",
+                        key="/etc/kubernetes/certs/client.key")
+    # -- or --
+    rdzv_params = RendezvousParameters(
+                        backend="etcd",
+                        endpoint="192.168.0.42:2379",
+                        run_id="123",
+                        min_nodes=4,
+                        max_nodes=8)
+
+    etcd_rdzv_handler = create_etcd_rendezvous_handler(rdzv_params)
+
+
+    Where:
+        run_id - unique id for this training job instance,
+        min_nodes - min number of workers expected to join the rendezvous,
+        max_nodes - max number of workers allowed to join the rendezvous,
+                        defaults to min_workers is not specified.
+        timeout - total timeout within which next_rendezvous is expected to
+                      succeed; a RendezvousTimeoutError is raised otherwise;
+                      Defaults is 600 (10 minutes).
+        last_call_timeout - additional wait amount ("last call") after
+                            min number of workers has been reached.
+                            Defaults to 30 seconds.
+        etcd_prefix - path prefix (from etcd root), inside which all
+                      etcd nodes will be created.
+                      Default is "/torchelastic/p2p".
+        protocol - http (default) or https to access etcd.
+        cacert - CA cert to access etcd, only makes sense with https.
+        cert - client cert to access etcd, only makes sense with https.
+        key - client key to access etcd, only makes sense with https.
+    """
+    client = _create_etcd_client(params)
+
+    etcd_prefix = params.get("etcd_prefix", "/torchelastic/p2p")
+
+    rdzv = EtcdRendezvous(
+        client=client,
+        prefix=etcd_prefix,
+        run_id=params.run_id,
+        num_min_workers=params.min_nodes,
+        num_max_workers=params.max_nodes,
+        timeout=params.get_as_int("timeout", _DEFAULT_TIMEOUT),
+        last_call_timeout=params.get_as_int(
+            "last_call_timeout", _DEFAULT_LAST_CALL_TIMEOUT
+        ),
+    )
+    return EtcdRendezvousHandler(
+        rdzv_impl=rdzv,
+        local_addr=params.local_addr,
+    )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/etcd_rendezvous_backend.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/etcd_rendezvous_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..75ae347293c8fbc8ace6802ca39ef906921097a1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/etcd_rendezvous_backend.py
@@ -0,0 +1,217 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+import binascii
+from base64 import b64decode, b64encode
+from typing import cast, Optional, Tuple
+
+import urllib3.exceptions  # type: ignore[import]
+from etcd import (  # type: ignore[import]
+    Client as EtcdClient,
+    EtcdAlreadyExist,
+    EtcdCompareFailed,
+    EtcdException,
+    EtcdKeyNotFound,
+    EtcdResult,
+)
+
+from torch.distributed import Store
+
+from .api import RendezvousConnectionError, RendezvousParameters, RendezvousStateError
+from .dynamic_rendezvous import RendezvousBackend, Token
+from .etcd_store import EtcdStore
+from .utils import parse_rendezvous_endpoint
+
+
+class EtcdRendezvousBackend(RendezvousBackend):
+    """Represents an etcd-based rendezvous backend.
+
+    Args:
+        client:
+            The ``etcd.Client`` instance to use to communicate with etcd.
+        run_id:
+            The run id of the rendezvous.
+        key_prefix:
+            The path under which to store the rendezvous state in etcd.
+        ttl:
+            The TTL of the rendezvous state. If not specified, defaults to two hours.
+    """
+
+    _DEFAULT_TTL = 7200  # 2 hours
+
+    _client: EtcdClient
+    _key: str
+    _ttl: int
+
+    def __init__(
+        self,
+        client: EtcdClient,
+        run_id: str,
+        key_prefix: Optional[str] = None,
+        ttl: Optional[int] = None,
+    ) -> None:
+        if not run_id:
+            raise ValueError("The run id must be a non-empty string.")
+
+        self._client = client
+
+        if key_prefix:
+            self._key = key_prefix + "/" + run_id
+        else:
+            self._key = run_id
+
+        if ttl and ttl > 0:
+            self._ttl = ttl
+        else:
+            self._ttl = self._DEFAULT_TTL
+
+    @property
+    def name(self) -> str:
+        """See base class."""
+        return "etcd-v2"
+
+    def get_state(self) -> Optional[Tuple[bytes, Token]]:
+        """See base class."""
+        try:
+            result = self._client.read(self._key)
+        except EtcdKeyNotFound:
+            return None
+        except (EtcdException, urllib3.exceptions.TimeoutError) as exc:
+            raise RendezvousConnectionError(
+                "The connection to etcd has failed. See inner exception for details."
+            ) from exc
+
+        return self._decode_state(result)
+
+    def set_state(
+        self, state: bytes, token: Optional[Token] = None
+    ) -> Optional[Tuple[bytes, Token, bool]]:
+        """See base class."""
+        base64_state = b64encode(state).decode()
+
+        kwargs = {}
+
+        def get_state():
+            result = self.get_state()
+            if result is not None:
+                tmp = *result, False
+                # Python 3.6 does not support tuple unpacking in return
+                # statements.
+                return tmp
+            return None
+
+        if token:
+            try:
+                token = int(token)
+            except ValueError:
+                return get_state()
+
+        if token:
+            kwargs["prevIndex"] = token
+        else:
+            kwargs["prevExist"] = False
+
+        try:
+            result = self._client.write(self._key, base64_state, self._ttl, **kwargs)
+        except (EtcdAlreadyExist, EtcdCompareFailed):
+            result = None
+        except (EtcdException, urllib3.exceptions.TimeoutError) as exc:
+            raise RendezvousConnectionError(
+                "The connection to etcd has failed. See inner exception for details."
+            ) from exc
+
+        if result is None:
+            return get_state()
+
+        tmp = *self._decode_state(result), True
+        return tmp
+
+    def _decode_state(self, result: EtcdResult) -> Tuple[bytes, Token]:
+        base64_state = result.value.encode()
+
+        try:
+            state = b64decode(base64_state)
+        except binascii.Error as exc:
+            raise RendezvousStateError(
+                "The state object is corrupt. See inner exception for details."
+            ) from exc
+
+        return state, result.modifiedIndex
+
+
+def _create_etcd_client(params: RendezvousParameters) -> EtcdClient:
+    host, port = parse_rendezvous_endpoint(params.endpoint, default_port=2379)
+
+    # The timeout
+    read_timeout = cast(int, params.get_as_int("read_timeout", 60))
+    if read_timeout <= 0:
+        raise ValueError("The read timeout must be a positive integer.")
+
+    # The communication protocol
+    protocol = params.get("protocol", "http").strip().lower()
+    if protocol != "http" and protocol != "https":
+        raise ValueError("The protocol must be HTTP or HTTPS.")
+
+    # The SSL client certificate
+    ssl_cert = params.get("ssl_cert")
+    if ssl_cert:
+        ssl_cert_key = params.get("ssl_cert_key")
+        if ssl_cert_key:
+            # The etcd client expects the certificate key as the second element
+            # of the `cert` tuple.
+            ssl_cert = (ssl_cert, ssl_cert_key)
+
+    # The root certificate
+    ca_cert = params.get("ca_cert")
+
+    try:
+        return EtcdClient(
+            host,
+            port,
+            read_timeout=read_timeout,
+            protocol=protocol,
+            cert=ssl_cert,
+            ca_cert=ca_cert,
+            allow_reconnect=True,
+        )
+    except (EtcdException, urllib3.exceptions.TimeoutError) as exc:
+        raise RendezvousConnectionError(
+            "The connection to etcd has failed. See inner exception for details."
+        ) from exc
+
+
+def create_backend(params: RendezvousParameters) -> Tuple[EtcdRendezvousBackend, Store]:
+    """Create a new :py:class:`EtcdRendezvousBackend` from the specified parameters.
+
+    +--------------+-----------------------------------------------------------+
+    | Parameter    | Description                                               |
+    +==============+===========================================================+
+    | read_timeout | The read timeout, in seconds, for etcd operations.        |
+    |              | Defaults to 60 seconds.                                   |
+    +--------------+-----------------------------------------------------------+
+    | protocol     | The protocol to use to communicate with etcd. Valid       |
+    |              | values are "http" and "https". Defaults to "http".        |
+    +--------------+-----------------------------------------------------------+
+    | ssl_cert     | The path to the SSL client certificate to use along with  |
+    |              | HTTPS. Defaults to ``None``.                              |
+    +--------------+-----------------------------------------------------------+
+    | ssl_cert_key | The path to the private key of the SSL client certificate |
+    |              | to use along with HTTPS. Defaults to ``None``.            |
+    +--------------+-----------------------------------------------------------+
+    | ca_cert      | The path to the rool SSL authority certificate. Defaults  |
+    |              | to ``None``.                                              |
+    +--------------+-----------------------------------------------------------+
+    """
+    client = _create_etcd_client(params)
+
+    backend = EtcdRendezvousBackend(
+        client, params.run_id, key_prefix="/torch/elastic/rendezvous"
+    )
+
+    store = EtcdStore(client, "/torch/elastic/store")
+
+    return backend, store
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/etcd_server.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/etcd_server.py
new file mode 100644
index 0000000000000000000000000000000000000000..8af8c01c028ae04801b41b5dd6b883ea34159fb8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/etcd_server.py
@@ -0,0 +1,248 @@
+#!/usr/bin/env python3
+# mypy: allow-untyped-defs
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+import atexit
+import logging
+import os
+import shlex
+import shutil
+import socket
+import subprocess
+import tempfile
+import time
+from typing import Optional, TextIO, Union
+
+
+try:
+    import etcd  # type: ignore[import]
+except ModuleNotFoundError:
+    pass
+
+
+logger = logging.getLogger(__name__)
+
+
+def find_free_port():
+    """
+    Find a free port and binds a temporary socket to it so that the port can be "reserved" until used.
+
+    .. note:: the returned socket must be closed before using the port,
+              otherwise a ``address already in use`` error will happen.
+              The socket should be held and closed as close to the
+              consumer of the port as possible since otherwise, there
+              is a greater chance of race-condition where a different
+              process may see the port as being free and take it.
+
+    Returns: a socket binded to the reserved free port
+
+    Usage::
+
+    sock = find_free_port()
+    port = sock.getsockname()[1]
+    sock.close()
+    use_port(port)
+    """
+    addrs = socket.getaddrinfo(
+        host="localhost", port=None, family=socket.AF_UNSPEC, type=socket.SOCK_STREAM
+    )
+
+    for addr in addrs:
+        family, type, proto, _, _ = addr
+        try:
+            s = socket.socket(family, type, proto)
+            s.bind(("localhost", 0))
+            s.listen(0)
+            return s
+        except OSError as e:
+            s.close()  # type: ignore[possibly-undefined]
+            print(f"Socket creation attempt failed: {e}")
+    raise RuntimeError("Failed to create a socket")
+
+
+def stop_etcd(subprocess, data_dir: Optional[str] = None):
+    if subprocess and subprocess.poll() is None:
+        logger.info("stopping etcd server")
+        subprocess.terminate()
+        subprocess.wait()
+
+    if data_dir:
+        logger.info("deleting etcd data dir: %s", data_dir)
+        shutil.rmtree(data_dir, ignore_errors=True)
+
+
+class EtcdServer:
+    """
+    .. note:: tested on etcd server v3.4.3.
+
+    Starts and stops a local standalone etcd server on a random free
+    port. Useful for single node, multi-worker launches or testing,
+    where a sidecar etcd server is more convenient than having to
+    separately setup an etcd server.
+
+    This class registers a termination handler to shutdown the etcd
+    subprocess on exit. This termination handler is NOT a substitute for
+    calling the ``stop()`` method.
+
+    The following fallback mechanism is used to find the etcd binary:
+
+    1. Uses env var TORCHELASTIC_ETCD_BINARY_PATH
+    2. Uses ``/bin/etcd`` if one exists
+    3. Uses ``etcd`` from ``PATH``
+
+    Usage
+    ::
+
+     server = EtcdServer("/usr/bin/etcd", 2379, "/tmp/default.etcd")
+     server.start()
+     client = server.get_client()
+     # use client
+     server.stop()
+
+    Args:
+        etcd_binary_path: path of etcd server binary (see above for fallback path)
+    """
+
+    def __init__(self, data_dir: Optional[str] = None):
+        self._port = -1
+        self._host = "localhost"
+
+        root = os.path.dirname(__file__)
+        default_etcd_bin = os.path.join(root, "bin/etcd")
+        self._etcd_binary_path = os.environ.get(
+            "TORCHELASTIC_ETCD_BINARY_PATH", default_etcd_bin
+        )
+        if not os.path.isfile(self._etcd_binary_path):
+            self._etcd_binary_path = "etcd"
+
+        self._base_data_dir = (
+            data_dir if data_dir else tempfile.mkdtemp(prefix="torchelastic_etcd_data")
+        )
+        self._etcd_cmd = None
+        self._etcd_proc: Optional[subprocess.Popen] = None
+
+    def _get_etcd_server_process(self) -> subprocess.Popen:
+        if not self._etcd_proc:
+            raise RuntimeError(
+                "No etcd server process started. Call etcd_server.start() first"
+            )
+        else:
+            return self._etcd_proc
+
+    def get_port(self) -> int:
+        """Return the port the server is running on."""
+        return self._port
+
+    def get_host(self) -> str:
+        """Return the host the server is running on."""
+        return self._host
+
+    def get_endpoint(self) -> str:
+        """Return the etcd server endpoint (host:port)."""
+        return f"{self._host}:{self._port}"
+
+    def start(
+        self,
+        timeout: int = 60,
+        num_retries: int = 3,
+        stderr: Union[int, TextIO, None] = None,
+    ) -> None:
+        """
+        Start the server, and waits for it to be ready. When this function returns the sever is ready to take requests.
+
+        Args:
+            timeout: time (in seconds) to wait for the server to be ready
+                before giving up.
+            num_retries: number of retries to start the server. Each retry
+                will wait for max ``timeout`` before considering it as failed.
+            stderr: the standard error file handle. Valid values are
+                `subprocess.PIPE`, `subprocess.DEVNULL`, an existing file
+                descriptor (a positive integer), an existing file object, and
+                `None`.
+
+        Raises:
+            TimeoutError: if the server is not ready within the specified timeout
+        """
+        curr_retries = 0
+        while True:
+            try:
+                data_dir = os.path.join(self._base_data_dir, str(curr_retries))
+                os.makedirs(data_dir, exist_ok=True)
+                return self._start(data_dir, timeout, stderr)
+            except Exception as e:
+                curr_retries += 1
+                stop_etcd(self._etcd_proc)
+                logger.warning(
+                    "Failed to start etcd server, got error: %s, retrying", str(e)
+                )
+                if curr_retries >= num_retries:
+                    shutil.rmtree(self._base_data_dir, ignore_errors=True)
+                    raise
+        atexit.register(stop_etcd, self._etcd_proc, self._base_data_dir)
+
+    def _start(
+        self, data_dir: str, timeout: int = 60, stderr: Union[int, TextIO, None] = None
+    ) -> None:
+        sock = find_free_port()
+        sock_peer = find_free_port()
+        self._port = sock.getsockname()[1]
+        peer_port = sock_peer.getsockname()[1]
+
+        etcd_cmd = shlex.split(
+            " ".join(
+                [
+                    self._etcd_binary_path,
+                    "--enable-v2",
+                    "--data-dir",
+                    data_dir,
+                    "--listen-client-urls",
+                    f"http://{self._host}:{self._port}",
+                    "--advertise-client-urls",
+                    f"http://{self._host}:{self._port}",
+                    "--listen-peer-urls",
+                    f"http://{self._host}:{peer_port}",
+                ]
+            )
+        )
+
+        logger.info("Starting etcd server: [%s]", etcd_cmd)
+
+        sock.close()
+        sock_peer.close()
+        self._etcd_proc = subprocess.Popen(etcd_cmd, close_fds=True, stderr=stderr)
+        self._wait_for_ready(timeout)
+
+    def get_client(self):
+        """Return an etcd client object that can be used to make requests to this server."""
+        return etcd.Client(
+            host=self._host, port=self._port, version_prefix="/v2", read_timeout=10
+        )
+
+    def _wait_for_ready(self, timeout: int = 60) -> None:
+        client = etcd.Client(
+            host=f"{self._host}", port=self._port, version_prefix="/v2", read_timeout=5
+        )
+        max_time = time.time() + timeout
+
+        while time.time() < max_time:
+            if self._get_etcd_server_process().poll() is not None:
+                # etcd server process finished
+                exitcode = self._get_etcd_server_process().returncode
+                raise RuntimeError(
+                    f"Etcd server process exited with the code: {exitcode}"
+                )
+            try:
+                logger.info("etcd server ready. version: %s", client.version)
+                return
+            except Exception:
+                time.sleep(1)
+        raise TimeoutError("Timed out waiting for etcd server to be ready!")
+
+    def stop(self) -> None:
+        """Stop the server and cleans up auto generated resources (e.g. data dir)."""
+        logger.info("EtcdServer stop method called")
+        stop_etcd(self._etcd_proc, self._base_data_dir)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/etcd_store.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/etcd_store.py
new file mode 100644
index 0000000000000000000000000000000000000000..4fa1bef06857d44c9092362dad29f016a472752f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/etcd_store.py
@@ -0,0 +1,207 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+import datetime
+import random
+import time
+from base64 import b64decode, b64encode
+from typing import Optional
+
+import etcd  # type: ignore[import]
+
+# pyre-ignore[21]: Could not find name `Store` in `torch.distributed`.
+from torch.distributed import Store
+
+
+# Delay (sleep) for a small random amount to reduce CAS failures.
+# This does not affect correctness, but will reduce requests to etcd server.
+def cas_delay():
+    time.sleep(random.uniform(0, 0.1))
+
+
+# pyre-fixme[11]: Annotation `Store` is not defined as a type.
+class EtcdStore(Store):
+    """
+    Implement a c10 Store interface by piggybacking on the rendezvous etcd instance.
+
+    This is the store object returned by ``EtcdRendezvous``.
+    """
+
+    def __init__(
+        self,
+        etcd_client,
+        etcd_store_prefix,
+        # Default timeout same as in c10d/Store.hpp
+        timeout: Optional[datetime.timedelta] = None,
+    ):
+        super().__init__()  # required for pybind trampoline.
+
+        self.client = etcd_client
+        self.prefix = etcd_store_prefix
+
+        if timeout is not None:
+            self.set_timeout(timeout)
+
+        if not self.prefix.endswith("/"):
+            self.prefix += "/"
+
+    def set(self, key, value):
+        """
+        Write a key/value pair into ``EtcdStore``.
+
+        Both key and value may be either Python ``str`` or ``bytes``.
+        """
+        self.client.set(key=self.prefix + self._encode(key), value=self._encode(value))
+
+    def get(self, key) -> bytes:
+        """
+        Get a value by key, possibly doing a blocking wait.
+
+        If key is not immediately present, will do a blocking wait
+        for at most ``timeout`` duration or until the key is published.
+
+
+        Returns:
+            value ``(bytes)``
+
+        Raises:
+            LookupError - If key still not published after timeout
+        """
+        b64_key = self.prefix + self._encode(key)
+        kvs = self._try_wait_get([b64_key])
+
+        if kvs is None:
+            raise LookupError(f"Key {key} not found in EtcdStore")
+
+        return self._decode(kvs[b64_key])
+
+    def add(self, key, num: int) -> int:
+        """
+        Atomically increment a value by an integer amount.
+
+        The integer is represented as a string using base 10. If key is not present,
+        a default value of ``0`` will be assumed.
+
+        Returns:
+             the new (incremented) value
+
+
+        """
+        b64_key = self._encode(key)
+        # c10d Store assumes value is an integer represented as a decimal string
+        try:
+            # Assume default value "0", if this key didn't yet:
+            node = self.client.write(
+                key=self.prefix + b64_key,
+                value=self._encode(str(num)),  # i.e. 0 + num
+                prevExist=False,
+            )
+            return int(self._decode(node.value))
+        except etcd.EtcdAlreadyExist:
+            pass
+
+        while True:
+            # Note: c10d Store does not have a method to delete keys, so we
+            # can be sure it's still there.
+            node = self.client.get(key=self.prefix + b64_key)
+            new_value = self._encode(str(int(self._decode(node.value)) + num))
+            try:
+                node = self.client.test_and_set(
+                    key=node.key, value=new_value, prev_value=node.value
+                )
+                return int(self._decode(node.value))
+            except etcd.EtcdCompareFailed:
+                cas_delay()
+
+    def wait(self, keys, override_timeout: Optional[datetime.timedelta] = None):
+        """
+        Wait until all of the keys are published, or until timeout.
+
+        Raises:
+            LookupError - if timeout occurs
+        """
+        b64_keys = [self.prefix + self._encode(key) for key in keys]
+        kvs = self._try_wait_get(b64_keys, override_timeout)
+        if kvs is None:
+            raise LookupError("Timeout while waiting for keys in EtcdStore")
+        # No return value on success
+
+    def check(self, keys) -> bool:
+        """Check if all of the keys are immediately present (without waiting)."""
+        b64_keys = [self.prefix + self._encode(key) for key in keys]
+        kvs = self._try_wait_get(
+            b64_keys,
+            override_timeout=datetime.timedelta(microseconds=1),  # as if no wait
+        )
+        return kvs is not None
+
+    #
+    # Encode key/value data in base64, so we can store arbitrary binary data
+    # in EtcdStore. Input can be `str` or `bytes`.
+    # In case of `str`, utf-8 encoding is assumed.
+    #
+    def _encode(self, value) -> str:
+        if type(value) == bytes:
+            return b64encode(value).decode()
+        elif type(value) == str:
+            return b64encode(value.encode()).decode()
+        raise ValueError("Value must be of type str or bytes")
+
+    #
+    # Decode a base64 string (of type `str` or `bytes`).
+    # Return type is `bytes`, which is more convenient with the Store interface.
+    #
+    def _decode(self, value) -> bytes:
+        if type(value) == bytes:
+            return b64decode(value)
+        elif type(value) == str:
+            return b64decode(value.encode())
+        raise ValueError("Value must be of type str or bytes")
+
+    #
+    # Get all of the (base64-encoded) etcd keys at once, or wait until all the keys
+    # are published or timeout occurs.
+    # This is a helper method for the public interface methods.
+    #
+    # On success, a dictionary of {etcd key -> etcd value} is returned.
+    # On timeout, None is returned.
+    #
+    def _try_wait_get(self, b64_keys, override_timeout=None):
+        timeout = self.timeout if override_timeout is None else override_timeout  # type: ignore[attr-defined]
+        deadline = time.time() + timeout.total_seconds()
+
+        while True:
+            # Read whole directory (of keys), filter only the ones waited for
+            all_nodes = self.client.get(key=self.prefix)
+            req_nodes = {
+                node.key: node.value
+                for node in all_nodes.children
+                if node.key in b64_keys
+            }
+
+            if len(req_nodes) == len(b64_keys):
+                # All keys are available
+                return req_nodes
+
+            watch_timeout = deadline - time.time()
+            if watch_timeout <= 0:
+                return None
+
+            try:
+                self.client.watch(
+                    key=self.prefix,
+                    recursive=True,
+                    timeout=watch_timeout,
+                    index=all_nodes.etcd_index + 1,
+                )
+            except etcd.EtcdWatchTimedOut:
+                if time.time() >= deadline:
+                    return None
+                else:
+                    continue
+            except etcd.EtcdEventIndexCleared:
+                continue
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/registry.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a91d0a8ff794666f51c30fba78ce02779ac5f19
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/registry.py
@@ -0,0 +1,71 @@
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+from .api import (
+    rendezvous_handler_registry as handler_registry,
+    RendezvousHandler,
+    RendezvousParameters,
+)
+from .dynamic_rendezvous import create_handler
+
+
+__all__ = ["get_rendezvous_handler"]
+
+
+def _create_static_handler(params: RendezvousParameters) -> RendezvousHandler:
+    from . import static_tcp_rendezvous
+
+    return static_tcp_rendezvous.create_rdzv_handler(params)
+
+
+def _create_etcd_handler(params: RendezvousParameters) -> RendezvousHandler:
+    from . import etcd_rendezvous
+
+    return etcd_rendezvous.create_rdzv_handler(params)
+
+
+def _create_etcd_v2_handler(params: RendezvousParameters) -> RendezvousHandler:
+    from .etcd_rendezvous_backend import create_backend
+
+    backend, store = create_backend(params)
+
+    return create_handler(store, backend, params)
+
+
+def _create_c10d_handler(params: RendezvousParameters) -> RendezvousHandler:
+    from .c10d_rendezvous_backend import create_backend
+
+    backend, store = create_backend(params)
+
+    return create_handler(store, backend, params)
+
+
+def _register_default_handlers() -> None:
+    handler_registry.register("etcd", _create_etcd_handler)
+    handler_registry.register("etcd-v2", _create_etcd_v2_handler)
+    handler_registry.register("c10d", _create_c10d_handler)
+    handler_registry.register("static", _create_static_handler)
+
+
+def get_rendezvous_handler(params: RendezvousParameters) -> RendezvousHandler:
+    """
+    Obtain a reference to a :py:class`RendezvousHandler`.
+
+    Custom rendezvous handlers can be registered by
+
+    ::
+
+      from torch.distributed.elastic.rendezvous import rendezvous_handler_registry
+      from torch.distributed.elastic.rendezvous.registry import get_rendezvous_handler
+
+      def create_my_rdzv(params: RendezvousParameters):
+        return MyCustomRdzv(params)
+
+      rendezvous_handler_registry.register("my_rdzv_backend_name", create_my_rdzv)
+
+      my_rdzv_handler = get_rendezvous_handler("my_rdzv_backend_name", RendezvousParameters)
+    """
+    return handler_registry.create_handler(params)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/static_tcp_rendezvous.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/static_tcp_rendezvous.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6395b70be2b432130e35f4b0fe702bfb5301542
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/static_tcp_rendezvous.py
@@ -0,0 +1,128 @@
+#!/usr/bin/env python3
+# mypy: allow-untyped-defs
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+import datetime
+import logging
+from typing import cast, Optional
+
+from torch.distributed import PrefixStore, Store, TCPStore
+from torch.distributed.elastic.rendezvous import (
+    RendezvousHandler,
+    RendezvousInfo,
+    RendezvousParameters,
+    RendezvousStoreInfo,
+)
+from torch.distributed.elastic.rendezvous.utils import parse_rendezvous_endpoint
+
+
+__all__ = ["StaticTCPRendezvous", "create_rdzv_handler"]
+
+logger = logging.getLogger(__name__)
+
+_default_timeout_seconds = 600
+
+
+class StaticTCPRendezvous(RendezvousHandler):
+    """
+    Static rendezvous that is a wrapper around the TCPStore.
+
+    Creates TCPStore based on the input parameters with the
+    listener on the agent with group_rank=0
+    """
+
+    def __init__(
+        self,
+        master_addr: str,
+        master_port: int,
+        rank: int,
+        world_size: int,
+        run_id: str,
+        timeout: int,
+    ):
+        self.master_addr = master_addr
+        self.master_port = master_port
+        self.rank = rank
+        self.world_size = world_size
+        self.run_id = run_id
+        self.timeout = datetime.timedelta(seconds=timeout)
+        self._store: Optional[Store] = None
+
+    def get_backend(self) -> str:
+        return "static"
+
+    @property
+    def use_agent_store(self) -> bool:
+        return True
+
+    def next_rendezvous(self) -> RendezvousInfo:
+        logger.info("Creating TCPStore as the c10d::Store implementation")
+        is_master = self.rank == 0
+        if not self._store:
+            self._store = TCPStore(  # type: ignore[call-arg]
+                self.master_addr,
+                self.master_port,
+                self.world_size,
+                is_master,
+                self.timeout,
+                multi_tenant=True,
+            )
+        store = PrefixStore(self.run_id, self._store)
+        # TCPStore server instance is used by trainer code
+        bootstrap_store_info = RendezvousStoreInfo(self.master_addr, self.master_port)
+        return RendezvousInfo(
+            store,
+            self.rank,
+            self.world_size,
+            bootstrap_store_info,
+        )
+
+    def is_closed(self):
+        return False
+
+    def set_closed(self):
+        pass
+
+    def num_nodes_waiting(self):
+        return 0
+
+    def get_run_id(self) -> str:
+        return self.run_id
+
+    def shutdown(self) -> bool:
+        return True
+
+
+def create_rdzv_handler(params: RendezvousParameters) -> RendezvousHandler:
+    if "rank" not in params.config:
+        raise ValueError(
+            "rank is absent in RendezvousParameters."
+            "Try add --node-rank to the cmd request"
+        )
+    endpoint = params.endpoint.strip()
+    if not endpoint:
+        raise ValueError(
+            "endpoint is absent in RendezvousParameters"
+            "Try add --master-port and --master-addr to the cmd request"
+        )
+    master_addr, master_port = parse_rendezvous_endpoint(endpoint, -1)
+    if master_port == -1:
+        raise ValueError(
+            f"Port is absent in endpoint: {endpoint}. Try launching with --master-port"
+        )
+    world_size = params.max_nodes
+    rank = cast(int, params.config.get("rank"))
+    run_id = params.run_id
+    if "timeout" in params.config:
+        timeout = int(params.config["timeout"])
+    else:
+        timeout = _default_timeout_seconds
+
+    return StaticTCPRendezvous(
+        master_addr, master_port, rank, world_size, run_id, timeout
+    )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..a93c9c39e58635bc91fc8f6b3a0a0451fab4ef34
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/rendezvous/utils.py
@@ -0,0 +1,284 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+import ipaddress
+import random
+import re
+import socket
+import time
+import weakref
+from datetime import timedelta
+from threading import Event, Thread
+from typing import Any, Callable, Dict, Optional, Tuple, Union
+
+
+__all__ = ["parse_rendezvous_endpoint"]
+
+
+def _parse_rendezvous_config(config_str: str) -> Dict[str, str]:
+    """Extract key-value pairs from a rendezvous configuration string.
+
+    Args:
+        config_str:
+            A string in format =,...,=.
+    """
+    config: Dict[str, str] = {}
+
+    config_str = config_str.strip()
+    if not config_str:
+        return config
+
+    key_values = config_str.split(",")
+    for kv in key_values:
+        key, *values = kv.split("=", 1)
+
+        key = key.strip()
+        if not key:
+            raise ValueError(
+                "The rendezvous configuration string must be in format "
+                "=,...,=."
+            )
+
+        value: Optional[str]
+        if values:
+            value = values[0].strip()
+        else:
+            value = None
+        if not value:
+            raise ValueError(
+                f"The rendezvous configuration option '{key}' must have a value specified."
+            )
+
+        config[key] = value
+    return config
+
+
+def _try_parse_port(port_str: str) -> Optional[int]:
+    """Try to extract the port number from ``port_str``."""
+    if port_str and re.match(r"^[0-9]{1,5}$", port_str):
+        return int(port_str)
+    return None
+
+
+def parse_rendezvous_endpoint(
+    endpoint: Optional[str], default_port: int
+) -> Tuple[str, int]:
+    """Extract the hostname and the port number from a rendezvous endpoint.
+
+    Args:
+        endpoint:
+            A string in format [:].
+        default_port:
+            The port number to use if the endpoint does not include one.
+
+    Returns:
+        A tuple of hostname and port number.
+    """
+    if endpoint is not None:
+        endpoint = endpoint.strip()
+
+    if not endpoint:
+        return ("localhost", default_port)
+
+    # An endpoint that starts and ends with brackets represents an IPv6 address.
+    if endpoint[0] == "[" and endpoint[-1] == "]":
+        host, *rest = endpoint, *[]
+    else:
+        host, *rest = endpoint.rsplit(":", 1)
+
+    # Sanitize the IPv6 address.
+    if len(host) > 1 and host[0] == "[" and host[-1] == "]":
+        host = host[1:-1]
+
+    if len(rest) == 1:
+        port = _try_parse_port(rest[0])
+        if port is None or port >= 2**16:
+            raise ValueError(
+                f"The port number of the rendezvous endpoint '{endpoint}' must be an integer "
+                "between 0 and 65536."
+            )
+    else:
+        port = default_port
+
+    if not re.match(r"^[\w\.:-]+$", host):
+        raise ValueError(
+            f"The hostname of the rendezvous endpoint '{endpoint}' must be a dot-separated list of "
+            "labels, an IPv4 address, or an IPv6 address."
+        )
+
+    return host, port
+
+
+def _matches_machine_hostname(host: str) -> bool:
+    """Indicate whether ``host`` matches the hostname of this machine.
+
+    This function compares ``host`` to the hostname as well as to the IP
+    addresses of this machine. Note that it may return a false negative if this
+    machine has CNAME records beyond its FQDN or IP addresses assigned to
+    secondary NICs.
+    """
+    if host == "localhost":
+        return True
+
+    try:
+        addr = ipaddress.ip_address(host)
+    except ValueError:
+        addr = None
+
+    if addr and addr.is_loopback:
+        return True
+
+    try:
+        host_addr_list = socket.getaddrinfo(
+            host, None, proto=socket.IPPROTO_TCP, flags=socket.AI_CANONNAME
+        )
+    except (ValueError, socket.gaierror) as _:
+        host_addr_list = []
+
+    host_ip_list = [host_addr_info[4][0] for host_addr_info in host_addr_list]
+
+    this_host = socket.gethostname()
+    if host == this_host:
+        return True
+
+    addr_list = socket.getaddrinfo(
+        this_host, None, proto=socket.IPPROTO_TCP, flags=socket.AI_CANONNAME
+    )
+    for addr_info in addr_list:
+        # If we have an FQDN in the addr_info, compare it to `host`.
+        if addr_info[3] and addr_info[3] == host:
+            return True
+
+        # Otherwise if `host` represents an IP address, compare it to our IP
+        # address.
+        if addr and addr_info[4][0] == str(addr):
+            return True
+
+        # If the IP address matches one of the provided host's IP addresses
+        if addr_info[4][0] in host_ip_list:
+            return True
+
+    return False
+
+
+def _delay(seconds: Union[float, Tuple[float, float]]) -> None:
+    """Suspend the current thread for ``seconds``.
+
+    Args:
+        seconds:
+            Either the delay, in seconds, or a tuple of a lower and an upper
+            bound within which a random delay will be picked.
+    """
+    if isinstance(seconds, tuple):
+        seconds = random.uniform(*seconds)
+    # Ignore delay requests that are less than 10 milliseconds.
+    if seconds >= 0.01:
+        time.sleep(seconds)
+
+
+class _PeriodicTimer:
+    """Represent a timer that periodically runs a specified function.
+
+    Args:
+        interval:
+            The interval, in seconds, between each run.
+        function:
+            The function to run.
+    """
+
+    # The state of the timer is hold in a separate context object to avoid a
+    # reference cycle between the timer and the background thread.
+    class _Context:
+        interval: float
+        function: Callable[..., None]
+        args: Tuple[Any, ...]
+        kwargs: Dict[str, Any]
+        stop_event: Event
+
+    _name: Optional[str]
+    _thread: Optional[Thread]
+    _finalizer: Optional[weakref.finalize]
+
+    # The context that is shared between the timer and the background thread.
+    _ctx: _Context
+
+    def __init__(
+        self,
+        interval: timedelta,
+        function: Callable[..., None],
+        *args: Any,
+        **kwargs: Any,
+    ) -> None:
+        self._name = None
+
+        self._ctx = self._Context()
+        self._ctx.interval = interval.total_seconds()
+        self._ctx.function = function  # type: ignore[assignment]
+        self._ctx.args = args or ()
+        self._ctx.kwargs = kwargs or {}
+        self._ctx.stop_event = Event()
+
+        self._thread = None
+        self._finalizer = None
+
+    @property
+    def name(self) -> Optional[str]:
+        """Get the name of the timer."""
+        return self._name
+
+    def set_name(self, name: str) -> None:
+        """Set the name of the timer.
+
+        The specified name will be assigned to the background thread and serves
+        for debugging and troubleshooting purposes.
+        """
+        if self._thread:
+            raise RuntimeError("The timer has already started.")
+
+        self._name = name
+
+    def start(self) -> None:
+        """Start the timer."""
+        if self._thread:
+            raise RuntimeError("The timer has already started.")
+
+        self._thread = Thread(
+            target=self._run,
+            name=self._name or "PeriodicTimer",
+            args=(self._ctx,),
+            daemon=True,
+        )
+
+        # We avoid using a regular finalizer (a.k.a. __del__) for stopping the
+        # timer as joining a daemon thread during the interpreter shutdown can
+        # cause deadlocks. The weakref.finalize is a superior alternative that
+        # provides a consistent behavior regardless of the GC implementation.
+        self._finalizer = weakref.finalize(
+            self, self._stop_thread, self._thread, self._ctx.stop_event
+        )
+
+        # We do not attempt to stop our background thread during the interpreter
+        # shutdown. At that point we do not even know whether it still exists.
+        self._finalizer.atexit = False
+
+        self._thread.start()
+
+    def cancel(self) -> None:
+        """Stop the timer at the next opportunity."""
+        if self._finalizer:
+            self._finalizer()
+
+    @staticmethod
+    def _run(ctx) -> None:
+        while not ctx.stop_event.wait(ctx.interval):
+            ctx.function(*ctx.args, **ctx.kwargs)
+
+    @staticmethod
+    def _stop_thread(thread, stop_event):
+        stop_event.set()
+
+        thread.join()
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b9c2ea349cc67ff7175d5ef17ec63aecddbf52a7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/__init__.py
@@ -0,0 +1,54 @@
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+"""
+Expiration timers are set up on the same process as the agent and
+used from your script to deal with stuck workers. When you go into
+a code-block that has the potential to get stuck you can acquire
+an expiration timer, which instructs the timer server to kill the
+process if it does not release the timer by the self-imposed expiration
+deadline.
+
+Usage::
+
+    import torchelastic.timer as timer
+    import torchelastic.agent.server as agent
+
+    def main():
+        start_method = "spawn"
+        message_queue = mp.get_context(start_method).Queue()
+        server = timer.LocalTimerServer(message, max_interval=0.01)
+        server.start() # non-blocking
+
+        spec = WorkerSpec(
+                    fn=trainer_func,
+                    args=(message_queue,),
+                    ...)
+        agent = agent.LocalElasticAgent(spec, start_method)
+        agent.run()
+
+    def trainer_func(message_queue):
+        timer.configure(timer.LocalTimerClient(message_queue))
+        with timer.expires(after=60): # 60 second expiry
+            # do some work
+
+In the example above if ``trainer_func`` takes more than 60 seconds to
+complete, then the worker process is killed and the agent retries the worker group.
+"""
+
+from .api import (  # noqa: F401
+    configure,
+    expires,
+    TimerClient,
+    TimerRequest,
+    TimerServer,
+)
+from .file_based_local_timer import (  # noqa: F401
+    FileTimerClient,
+    FileTimerRequest,
+    FileTimerServer,
+)
+from .local_timer import LocalTimerClient, LocalTimerServer  # noqa: F401
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e98503f56f5b4776898d4c02ec3586cc4d9d7120
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/__pycache__/api.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/__pycache__/api.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6fba976ca0547f6b3c2c07da804698fefd962992
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/__pycache__/api.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/__pycache__/debug_info_logging.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/__pycache__/debug_info_logging.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cd90001f2efe967201a0d9057afa8d54d8f80a75
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/__pycache__/debug_info_logging.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/__pycache__/file_based_local_timer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/__pycache__/file_based_local_timer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..83e3620d0c565d403d2e461031af03146d31d431
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/__pycache__/file_based_local_timer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/__pycache__/local_timer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/__pycache__/local_timer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bd5cd499673d27db4b88e9a32894a4a5fb5e973c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/__pycache__/local_timer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/api.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..e627bff5b9bd29eff9b4d317be113b625da0e33d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/api.py
@@ -0,0 +1,283 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+import abc
+import logging
+import threading
+import time
+from contextlib import contextmanager
+from inspect import getframeinfo, stack
+from typing import Any, Dict, List, Optional, Set
+
+
+__all__ = [
+    "TimerRequest",
+    "TimerClient",
+    "RequestQueue",
+    "TimerServer",
+    "configure",
+    "expires",
+]
+
+logger = logging.getLogger(__name__)
+
+
+class TimerRequest:
+    """
+    Data object representing a countdown timer acquisition and release
+    that is used between the ``TimerClient`` and ``TimerServer``.
+    A negative ``expiration_time`` should be interpreted as a "release"
+    request.
+
+    .. note:: the type of ``worker_id`` is implementation specific.
+              It is whatever the TimerServer and TimerClient implementations
+              have on to uniquely identify a worker.
+    """
+
+    __slots__ = ["worker_id", "scope_id", "expiration_time"]
+
+    def __init__(self, worker_id: Any, scope_id: str, expiration_time: float):
+        self.worker_id = worker_id
+        self.scope_id = scope_id
+        self.expiration_time = expiration_time
+
+    def __eq__(self, other):
+        if isinstance(other, TimerRequest):
+            return (
+                self.worker_id == other.worker_id
+                and self.scope_id == other.scope_id
+                and self.expiration_time == other.expiration_time
+            )
+        return False
+
+
+class TimerClient(abc.ABC):
+    """
+    Client library to acquire and release countdown timers by communicating
+    with the TimerServer.
+    """
+
+    @abc.abstractmethod
+    def acquire(self, scope_id: str, expiration_time: float) -> None:
+        """
+        Acquires a timer for the worker that holds this client object
+        given the scope_id and expiration_time. Typically registers
+        the timer with the TimerServer.
+        """
+
+    @abc.abstractmethod
+    def release(self, scope_id: str):
+        """
+        Releases the timer for the ``scope_id`` on the worker this
+        client represents. After this method is
+        called, the countdown timer on the scope is no longer in effect.
+        """
+
+
+class RequestQueue(abc.ABC):
+    """
+    Consumer queue holding timer acquisition/release requests
+    """
+
+    @abc.abstractmethod
+    def size(self) -> int:
+        """
+        Returns the size of the queue at the time this method is called.
+        Note that by the time ``get`` is called the size of the queue
+        may have increased. The size of the queue should not decrease
+        until the ``get`` method is called. That is, the following assertion
+        should hold:
+
+        size = q.size()
+        res = q.get(size, timeout=0)
+        assert size == len(res)
+
+        -- or --
+
+        size = q.size()
+        res = q.get(size * 2, timeout=1)
+        assert size <= len(res) <= size * 2
+        """
+
+    @abc.abstractmethod
+    def get(self, size: int, timeout: float) -> List[TimerRequest]:
+        """
+        Gets up to ``size`` number of timer requests in a blocking fashion
+        (no more than ``timeout`` seconds).
+        """
+
+
+class TimerServer(abc.ABC):
+    """
+    Entity that monitors active timers and expires them
+    in a timely fashion. This server is responsible for
+    reaping workers that have expired timers.
+    """
+
+    def __init__(
+        self, request_queue: RequestQueue, max_interval: float, daemon: bool = True
+    ):
+        """
+        :param request_queue: Consumer ``RequestQueue``
+        :param max_interval: max time (in seconds) to wait
+                             for an item in the request_queue
+        :param daemon: whether to run the watchdog thread as a daemon
+        """
+        super().__init__()
+        self._request_queue = request_queue
+        self._max_interval = max_interval
+        self._daemon = daemon
+        self._watchdog_thread: Optional[threading.Thread] = None
+        self._stop_signaled = False
+
+    @abc.abstractmethod
+    def register_timers(self, timer_requests: List[TimerRequest]) -> None:
+        """
+        Processes the incoming timer requests and registers them with the server.
+        The timer request can either be a acquire-timer or release-timer request.
+        Timer requests with a negative expiration_time should be interpreted
+        as a release-timer request.
+        """
+
+    @abc.abstractmethod
+    def clear_timers(self, worker_ids: Set[Any]) -> None:
+        """
+        Clears all timers for the given ``worker_ids``.
+        """
+
+    @abc.abstractmethod
+    def get_expired_timers(self, deadline: float) -> Dict[str, List[TimerRequest]]:
+        """
+        Returns all expired timers for each worker_id. An expired timer
+        is a timer for which the expiration_time is less than or equal to
+        the provided deadline.
+        """
+
+    @abc.abstractmethod
+    def _reap_worker(self, worker_id: Any) -> bool:
+        """
+        Reaps the given worker. Returns True if the worker has been
+        successfully reaped, False otherwise. If any uncaught exception
+        is thrown from this method, the worker is considered reaped
+        and all associated timers will be removed.
+        """
+
+    def _reap_worker_no_throw(self, worker_id: Any) -> bool:
+        """
+        Wraps ``_reap_worker(worker_id)``, if an uncaught exception is
+        thrown, then it considers the worker as reaped.
+        """
+        try:
+            return self._reap_worker(worker_id)
+        except Exception:
+            logger.exception(
+                "Uncaught exception thrown from _reap_worker(), "
+                "check that the implementation correctly catches exceptions",
+            )
+            return True
+
+    def _watchdog_loop(self):
+        while not self._stop_signaled:
+            try:
+                self._run_watchdog()
+            except Exception:
+                logger.exception("Error running watchdog")
+
+    def _run_watchdog(self):
+        batch_size = max(1, self._request_queue.size())
+        timer_requests = self._request_queue.get(batch_size, self._max_interval)
+        self.register_timers(timer_requests)
+        now = time.time()
+        reaped_worker_ids = set()
+        for worker_id, expired_timers in self.get_expired_timers(now).items():
+            logger.info(
+                "Reaping worker_id=[%s]." " Expired timers: %s",
+                worker_id,
+                self._get_scopes(expired_timers),
+            )
+            if self._reap_worker_no_throw(worker_id):
+                logger.info("Successfully reaped worker=[%s]", worker_id)
+                reaped_worker_ids.add(worker_id)
+            else:
+                logger.error(
+                    "Error reaping worker=[%s]. Will retry on next watchdog.", worker_id
+                )
+        self.clear_timers(reaped_worker_ids)
+
+    def _get_scopes(self, timer_requests):
+        return [r.scope_id for r in timer_requests]
+
+    def start(self) -> None:
+        logger.info(
+            "Starting %s..." " max_interval=%s," " daemon=%s",
+            type(self).__name__,
+            self._max_interval,
+            self._daemon,
+        )
+        self._watchdog_thread = threading.Thread(
+            target=self._watchdog_loop, daemon=self._daemon
+        )
+        logger.info("Starting watchdog thread...")
+        self._watchdog_thread.start()
+
+    def stop(self) -> None:
+        logger.info("Stopping %s", type(self).__name__)
+        self._stop_signaled = True
+        if self._watchdog_thread:
+            logger.info("Stopping watchdog thread...")
+            self._watchdog_thread.join(self._max_interval)
+            self._watchdog_thread = None
+        else:
+            logger.info("No watchdog thread running, doing nothing")
+
+
+_timer_client: Optional[TimerClient] = None
+
+
+def configure(timer_client: TimerClient):
+    """
+    Configures a timer client. Must be called before using ``expires``.
+    """
+    global _timer_client
+    _timer_client = timer_client
+    logger.info("Timer client configured to: %s", type(_timer_client).__name__)
+
+
+@contextmanager
+def expires(
+    after: float, scope: Optional[str] = None, client: Optional[TimerClient] = None
+):
+    """
+    Acquires a countdown timer that expires in ``after`` seconds from now,
+    unless the code-block that it wraps is finished within the timeframe.
+    When the timer expires, this worker is eligible to be reaped. The
+    exact meaning of "reaped" depends on the client implementation. In
+    most cases, reaping means to terminate the worker process.
+    Note that the worker is NOT guaranteed to be reaped at exactly
+    ``time.now() + after``, but rather the worker is "eligible" for being
+    reaped and the ``TimerServer`` that the client talks to will ultimately
+    make the decision when and how to reap the workers with expired timers.
+
+    Usage::
+
+        torch.distributed.elastic.timer.configure(LocalTimerClient())
+        with expires(after=10):
+            torch.distributed.all_reduce(...)
+    """
+    if client is None:
+        if _timer_client is None:
+            raise RuntimeError("Configure timer client before using countdown timers.")
+        client = _timer_client
+    if scope is None:
+        # grab the caller file + lineno
+        caller = getframeinfo(stack()[1][0])
+        scope = f"{caller.filename}#{caller.lineno}"
+    expiration = time.time() + after
+    client.acquire(scope, expiration)
+    try:
+        yield
+    finally:
+        client.release(scope)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/debug_info_logging.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/debug_info_logging.py
new file mode 100644
index 0000000000000000000000000000000000000000..3dce543220d83d97d9043766892490fda8b8a01b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/debug_info_logging.py
@@ -0,0 +1,25 @@
+#!/usr/bin/env python3
+# mypy: allow-untyped-defs
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+from typing import Dict, List
+
+from torch.distributed.elastic.utils.logging import get_logger
+
+
+logger = get_logger(__name__)
+
+__all__ = ["log_debug_info_for_expired_timers"]
+
+
+def log_debug_info_for_expired_timers(
+    run_id: str,
+    expired_timers: Dict[int, List[str]],
+):
+    if expired_timers:
+        logger.info("Timers expired for run:[%s] [%s].", run_id, expired_timers)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/file_based_local_timer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/file_based_local_timer.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c6d0d9a33064a3021f65bb8e6021ea373eefc24
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/file_based_local_timer.py
@@ -0,0 +1,393 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+import io
+import json
+import os
+import select
+import signal
+import sys
+import threading
+import time
+from typing import Callable, Dict, List, Optional, Set, Tuple
+
+from torch.distributed.elastic.timer.api import TimerClient, TimerRequest
+from torch.distributed.elastic.timer.debug_info_logging import (
+    log_debug_info_for_expired_timers,
+)
+from torch.distributed.elastic.utils.logging import get_logger
+
+
+__all__ = ["FileTimerClient", "FileTimerRequest", "FileTimerServer"]
+
+logger = get_logger(__name__)
+
+
+class FileTimerRequest(TimerRequest):
+    """
+    Data object representing a countdown timer acquisition and release
+    that is used between the ``FileTimerClient`` and ``FileTimerServer``.
+    A negative ``expiration_time`` should be interpreted as a "release"
+    request.
+    ``signal`` is the signal to reap the worker process from the server
+    process.
+    """
+
+    __slots__ = ["version", "worker_pid", "scope_id", "expiration_time", "signal"]
+
+    def __init__(
+        self, worker_pid: int, scope_id: str, expiration_time: float, signal: int = 0
+    ) -> None:
+        self.version = 1
+        self.worker_pid = worker_pid
+        self.scope_id = scope_id
+        self.expiration_time = expiration_time
+        self.signal = signal
+
+    def __eq__(self, other) -> bool:
+        if isinstance(other, FileTimerRequest):
+            return (
+                self.version == other.version
+                and self.worker_pid == other.worker_pid
+                and self.scope_id == other.scope_id
+                and self.expiration_time == other.expiration_time
+                and self.signal == other.signal
+            )
+        return False
+
+    def to_json(self) -> str:
+        return json.dumps(
+            {
+                "version": self.version,
+                "pid": self.worker_pid,
+                "scope_id": self.scope_id,
+                "expiration_time": self.expiration_time,
+                "signal": self.signal,
+            },
+        )
+
+
+class FileTimerClient(TimerClient):
+    """
+    Client side of ``FileTimerServer``. This client is meant to be used
+    on the same host that the ``FileTimerServer`` is running on and uses
+    pid to uniquely identify a worker.
+    This client uses a named_pipe to send timer requests to the
+    ``FileTimerServer``. This client is a producer while the
+    ``FileTimerServer`` is a consumer. Multiple clients can work with
+    the same ``FileTimerServer``.
+
+    Args:
+
+        file_path: str, the path of a FIFO special file. ``FileTimerServer``
+                        must have created it by calling os.mkfifo().
+
+        signal: signal, the signal to use to kill the process. Using a
+                        negative or zero signal will not kill the process.
+    """
+
+    def __init__(
+        self,
+        file_path: str,
+        signal=(signal.SIGKILL if sys.platform != "win32" else signal.CTRL_C_EVENT),  # type: ignore[attr-defined]
+    ) -> None:
+        super().__init__()
+        self._file_path = file_path
+        self.signal = signal
+
+    def _open_non_blocking(self) -> Optional[io.TextIOWrapper]:
+        try:
+            fd = os.open(self._file_path, os.O_WRONLY | os.O_NONBLOCK)
+            return os.fdopen(fd, "wt")
+        except Exception:
+            return None
+
+    def _send_request(self, request: FileTimerRequest) -> None:
+        # The server may have crashed or may haven't started yet.
+        # In such case, calling open() in blocking model blocks the client.
+        # To avoid such issue, open it in non-blocking mode, and an OSError will
+        # be raised if the server is not there.
+        file = self._open_non_blocking()
+        if file is None:
+            raise BrokenPipeError(
+                "Could not send the FileTimerRequest because FileTimerServer is not available."
+            )
+        with file:
+            json_request = request.to_json()
+            # Write request with no greater than select.PIPE_BUF is guarantee to be atomic.
+            if len(json_request) > select.PIPE_BUF:
+                raise RuntimeError(
+                    f"FileTimerRequest larger than {select.PIPE_BUF} bytes "
+                    f"is not supported: {json_request}"
+                )
+            file.write(json_request + "\n")
+
+    def acquire(self, scope_id: str, expiration_time: float) -> None:
+        self._send_request(
+            request=FileTimerRequest(
+                worker_pid=os.getpid(),
+                scope_id=scope_id,
+                expiration_time=expiration_time,
+                signal=self.signal,
+            ),
+        )
+
+    def release(self, scope_id: str) -> None:
+        self._send_request(
+            request=FileTimerRequest(
+                worker_pid=os.getpid(), scope_id=scope_id, expiration_time=-1, signal=0
+            ),
+        )
+
+
+class FileTimerServer:
+    """
+    Server that works with ``FileTimerClient``. Clients are expected to be
+    running on the same host as the process that is running this server.
+    Each host in the job is expected to start its own timer server locally
+    and each server instance manages timers for local workers (running on
+    processes on the same host).
+
+    Args:
+
+        file_path: str, the path of a FIFO special file to be created.
+
+        max_interval: float, max interval in seconds for each watchdog loop.
+
+        daemon: bool, running the watchdog thread in daemon mode or not.
+                      A daemon thread will not block a process to stop.
+        log_event: Callable[[Dict[str, str]], None], an optional callback for
+                logging the events in JSON format.
+    """
+
+    def __init__(
+        self,
+        file_path: str,
+        run_id: str,
+        max_interval: float = 10,
+        daemon: bool = True,
+        log_event: Optional[Callable[[str, Optional[FileTimerRequest]], None]] = None,
+    ) -> None:
+        self._file_path = file_path
+        self._run_id = run_id
+        self._max_interval = max_interval
+        self._daemon = daemon
+        self._timers: Dict[Tuple[int, str], FileTimerRequest] = {}
+        self._stop_signaled = False
+        self._watchdog_thread: Optional[threading.Thread] = None
+        if os.path.exists(self._file_path):
+            os.remove(self._file_path)
+        os.mkfifo(self._file_path)
+        # For test only. Count the number of requests received.
+        self._request_count = 0
+        # For test only. Process all requests and stop the server.
+        self._run_once = False
+        self._log_event = (
+            log_event if log_event is not None else lambda name, request: None
+        )
+        self._last_progress_time = int(time.time())
+
+    def start(self) -> None:
+        logger.info(
+            "Starting %s... max_interval=%s, daemon=%s, file_path=%s",
+            type(self).__name__,
+            self._max_interval,
+            self._daemon,
+            self._file_path,
+        )
+        self._watchdog_thread = threading.Thread(
+            target=self._watchdog_loop, daemon=self._daemon
+        )
+        logger.info("Starting watchdog thread...")
+        self._watchdog_thread.start()
+        self._log_event("watchdog started", None)
+
+    def stop(self) -> None:
+        logger.info("Stopping %s", type(self).__name__)
+        self._stop_signaled = True
+        if self._watchdog_thread:
+            logger.info("Stopping watchdog thread...")
+            self._watchdog_thread.join(self._max_interval)
+            self._watchdog_thread = None
+        else:
+            logger.info("No watchdog thread running, doing nothing")
+        if os.path.exists(self._file_path):
+            os.remove(self._file_path)
+        self._log_event("watchdog stopped", None)
+
+    def run_once(self) -> None:
+        self._run_once = True
+        if self._watchdog_thread:
+            logger.info("Stopping watchdog thread...")
+            self._watchdog_thread.join()
+            self._watchdog_thread = None
+        else:
+            logger.info("No watchdog thread running, doing nothing")
+        if os.path.exists(self._file_path):
+            os.remove(self._file_path)
+
+    @staticmethod
+    def is_process_running(pid: int):
+        """
+        function to check process is running or not
+        """
+        try:
+            # Check if the process exists and we can send signals to it
+            os.kill(pid, 0)
+            return True
+        except OSError:
+            return False
+
+    def _watchdog_loop(self) -> None:
+        # Open the pipe in blocking mode blocks the server thread.
+        # This is fine for the following reasons:
+        #  1. No client case usually does not happen.
+        #  2. We are running the watchdog loop in a separate daemon
+        #     thread, which will not block the process to stop.
+        with open(self._file_path) as fd:
+            while not self._stop_signaled:
+                try:
+                    run_once = self._run_once
+                    self._run_watchdog(fd)
+                    if run_once:
+                        break
+                    self._last_progress_time = int(time.time())
+                except Exception:
+                    logger.exception("Error running watchdog")
+
+    def _run_watchdog(self, fd: io.TextIOWrapper) -> None:
+        timer_requests = self._get_requests(fd, self._max_interval)
+        self.register_timers(timer_requests)
+        now = time.time()
+        reaped_worker_pids = set()
+
+        all_expired_timers = self.get_expired_timers(now)
+        log_debug_info_for_expired_timers(
+            self._run_id,
+            {
+                pid: self._get_scopes(expired_timers)
+                for pid, expired_timers in all_expired_timers.items()
+            },
+        )
+
+        for worker_pid, expired_timers in all_expired_timers.items():
+            logger.info(
+                "Reaping worker_pid=[%s]. Expired timers: %s",
+                worker_pid,
+                self._get_scopes(expired_timers),
+            )
+            reaped_worker_pids.add(worker_pid)
+            # In case we have multiple expired timers, we find the first timer
+            # with a valid signal (>0) in the expiration time order.
+            expired_timers.sort(key=lambda timer: timer.expiration_time)
+            signal = 0
+            expired_timer = None
+            for timer in expired_timers:
+                self._log_event("timer expired", timer)
+                if timer.signal > 0:
+                    signal = timer.signal
+                    expired_timer = timer
+                    break
+            if signal <= 0:
+                logger.info(
+                    "No signal specified with worker=[%s]. Do not reap it.", worker_pid
+                )
+                continue
+            if self._reap_worker(worker_pid, signal):
+                logger.info(
+                    "Successfully reaped worker=[%s] with signal=%s", worker_pid, signal
+                )
+                self._log_event("kill worker process", expired_timer)
+            else:
+                logger.error(
+                    "Error reaping worker=[%s]. Will retry on next watchdog.",
+                    worker_pid,
+                )
+        self.clear_timers(reaped_worker_pids)
+
+    def _get_scopes(self, timer_requests: List[FileTimerRequest]) -> List[str]:
+        return [r.scope_id for r in timer_requests]
+
+    def _get_requests(
+        self, fd: io.TextIOWrapper, max_interval: float
+    ) -> List[FileTimerRequest]:
+        start = time.time()
+        requests = []
+        while not self._stop_signaled or self._run_once:
+            # For named pipe, readline() is blocking when at least one writer opens.
+            # It returns only when flush() is called at the writer side.
+            # Note that flush() is automatically called inside close().
+            # After the last writer closes, readline() is not blocking.
+            # It will return an empty string when it's at end-of-file.
+            # Since the client side always opens the pipe, writes a message and closes
+            # the pipe immediately, the readline() call below is not blocking for long.
+            json_request = fd.readline()
+            if len(json_request) == 0:
+                if self._run_once:
+                    break
+                time.sleep(min(max_interval, 1))
+            else:
+                request = json.loads(json_request)
+                pid = request["pid"]
+                scope_id = request["scope_id"]
+                expiration_time = request["expiration_time"]
+                signal = request["signal"]
+                requests.append(
+                    FileTimerRequest(
+                        worker_pid=pid,
+                        scope_id=scope_id,
+                        expiration_time=expiration_time,
+                        signal=signal,
+                    )
+                )
+            now = time.time()
+            if now - start > max_interval:
+                break
+        return requests
+
+    def register_timers(self, timer_requests: List[FileTimerRequest]) -> None:
+        for request in timer_requests:
+            pid = request.worker_pid
+            scope_id = request.scope_id
+            expiration_time = request.expiration_time
+            self._request_count += 1
+
+            key = (pid, scope_id)
+            # negative expiration is a proxy for a release call
+            if expiration_time < 0:
+                if key in self._timers:
+                    del self._timers[key]
+            else:
+                self._timers[key] = request
+
+    def clear_timers(self, worker_pids: Set[int]) -> None:
+        for pid, scope_id in list(self._timers.keys()):
+            if pid in worker_pids or not FileTimerServer.is_process_running(pid):
+                del self._timers[(pid, scope_id)]
+
+    def get_expired_timers(self, deadline: float) -> Dict[int, List[FileTimerRequest]]:
+        # pid -> [timer_requests...]
+        expired_timers: Dict[int, List[FileTimerRequest]] = {}
+        for request in self._timers.values():
+            if request.expiration_time <= deadline:
+                expired_scopes = expired_timers.setdefault(request.worker_pid, [])
+                expired_scopes.append(request)
+        return expired_timers
+
+    def _reap_worker(self, worker_pid: int, signal: int) -> bool:
+        try:
+            os.kill(worker_pid, signal)
+            return True
+        except ProcessLookupError:
+            logger.info("Process with pid=%s does not exist. Skipping", worker_pid)
+            return True
+        except Exception:
+            logger.exception("Error terminating pid=%s", worker_pid)
+        return False
+
+    def get_last_progress_time(self) -> int:
+        return self._last_progress_time
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/local_timer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/local_timer.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe784b7de46d2740b8376d812db6c43f5247269e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/timer/local_timer.py
@@ -0,0 +1,128 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+import logging
+import multiprocessing as mp
+import os
+import signal
+import time
+from queue import Empty
+from typing import Any, Dict, List, Set, Tuple
+
+from .api import RequestQueue, TimerClient, TimerRequest, TimerServer
+
+
+__all__ = ["LocalTimerClient", "MultiprocessingRequestQueue", "LocalTimerServer"]
+
+logger = logging.getLogger(__name__)
+
+
+class LocalTimerClient(TimerClient):
+    """
+    Client side of ``LocalTimerServer``. This client is meant to be used
+    on the same host that the ``LocalTimerServer`` is running on and uses
+    pid to uniquely identify a worker. This is particularly useful in situations
+    where one spawns a subprocess (trainer) per GPU on a host with multiple
+    GPU devices.
+    """
+
+    def __init__(self, mp_queue):
+        super().__init__()
+        self._mp_queue = mp_queue
+
+    def acquire(self, scope_id, expiration_time):
+        pid = os.getpid()
+        acquire_request = TimerRequest(pid, scope_id, expiration_time)
+        self._mp_queue.put(acquire_request)
+
+    def release(self, scope_id):
+        pid = os.getpid()
+        release_request = TimerRequest(pid, scope_id, -1)
+        self._mp_queue.put(release_request)
+
+
+class MultiprocessingRequestQueue(RequestQueue):
+    """
+    A ``RequestQueue`` backed by python ``multiprocessing.Queue``
+    """
+
+    def __init__(self, mp_queue: mp.Queue):
+        super().__init__()
+        self._mp_queue = mp_queue
+
+    def size(self) -> int:
+        return self._mp_queue.qsize()
+
+    def get(self, size, timeout: float) -> List[TimerRequest]:
+        requests = []
+        wait = timeout
+        for _ in range(0, size):
+            start = time.time()
+
+            try:
+                r = self._mp_queue.get(block=True, timeout=wait)
+            except Empty:
+                break
+
+            requests.append(r)
+            wait = wait - (time.time() - start)
+            if wait <= 0:
+                break
+
+        return requests
+
+
+class LocalTimerServer(TimerServer):
+    """
+    Server that works with ``LocalTimerClient``. Clients are expected to be
+    subprocesses to the parent process that is running this server. Each host
+    in the job is expected to start its own timer server locally and each
+    server instance manages timers for local workers (running on processes
+    on the same host).
+    """
+
+    def __init__(
+        self, mp_queue: mp.Queue, max_interval: float = 60, daemon: bool = True
+    ):
+        super().__init__(MultiprocessingRequestQueue(mp_queue), max_interval, daemon)
+        self._timers: Dict[Tuple[Any, str], TimerRequest] = {}
+
+    def register_timers(self, timer_requests: List[TimerRequest]) -> None:
+        for request in timer_requests:
+            pid = request.worker_id
+            scope_id = request.scope_id
+            expiration_time = request.expiration_time
+
+            # negative expiration is a proxy for a release call
+            if expiration_time < 0:
+                self._timers.pop((pid, scope_id), None)
+            else:
+                self._timers[(pid, scope_id)] = request
+
+    def clear_timers(self, worker_ids: Set[int]) -> None:
+        for pid, scope_id in list(self._timers.keys()):
+            if pid in worker_ids:
+                self._timers.pop((pid, scope_id))
+
+    def get_expired_timers(self, deadline: float) -> Dict[Any, List[TimerRequest]]:
+        # pid -> [timer_requests...]
+        expired_timers: Dict[Any, List[TimerRequest]] = {}
+        for request in self._timers.values():
+            if request.expiration_time <= deadline:
+                expired_scopes = expired_timers.setdefault(request.worker_id, [])
+                expired_scopes.append(request)
+        return expired_timers
+
+    def _reap_worker(self, worker_id: int) -> bool:
+        try:
+            os.kill(worker_id, signal.SIGKILL)
+            return True
+        except ProcessLookupError:
+            logger.info("Process with pid=%s does not exist. Skipping", worker_id)
+            return True
+        except Exception:
+            logger.exception("Error terminating pid=%s", worker_id)
+        return False
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce2bbf5bbe2348bb0eaa411a034710dd14f7648e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/__init__.py
@@ -0,0 +1,9 @@
+#!/usr/bin/env python3
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+from .api import get_env_variable_or_raise, get_socket_with_port, macros  # noqa: F401
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d1edf265b1b6bd20227ec56f212e98a62a9d678a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/__pycache__/api.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/__pycache__/api.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..845de3f96e0c78ac71dd9b4fb3ebe1ea4e6ab313
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/__pycache__/api.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/__pycache__/distributed.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/__pycache__/distributed.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d23f0101b101e35a6e2eba4d0678978de2763fb7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/__pycache__/distributed.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/__pycache__/log_level.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/__pycache__/log_level.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dfdb7eb435b2a0b2a110b087477f9a54b8e375de
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/__pycache__/log_level.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/__pycache__/logging.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/__pycache__/logging.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..85548076a0123f2fe9da22c01d8f783b79c6cfae
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/__pycache__/logging.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/__pycache__/store.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/__pycache__/store.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e7f53e02a28ef53aea77105ad4738154883e5921
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/__pycache__/store.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/api.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..bdb8f02e0176fdffa931c71d80c889acc40a5077
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/api.py
@@ -0,0 +1,62 @@
+#!/usr/bin/env python3
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+import os
+import socket
+from string import Template
+from typing import Any, List
+
+
+def get_env_variable_or_raise(env_name: str) -> str:
+    r"""
+    Tries to retrieve environment variable. Raises ``ValueError``
+    if no environment variable found.
+
+    Args:
+        env_name (str): Name of the env variable
+    """
+    value = os.environ.get(env_name, None)
+    if value is None:
+        msg = f"Environment variable {env_name} expected, but not set"
+        raise ValueError(msg)
+    return value
+
+
+def get_socket_with_port() -> socket.socket:
+    addrs = socket.getaddrinfo(
+        host="localhost", port=None, family=socket.AF_UNSPEC, type=socket.SOCK_STREAM
+    )
+    for addr in addrs:
+        family, type, proto, _, _ = addr
+        s = socket.socket(family, type, proto)
+        try:
+            s.bind(("localhost", 0))
+            s.listen(0)
+            return s
+        except OSError as e:
+            s.close()
+    raise RuntimeError("Failed to create a socket")
+
+
+class macros:
+    """
+    Defines simple macros for caffe2.distributed.launch cmd args substitution
+    """
+
+    local_rank = "${local_rank}"
+
+    @staticmethod
+    def substitute(args: List[Any], local_rank: str) -> List[str]:
+        args_sub = []
+        for arg in args:
+            if isinstance(arg, str):
+                sub = Template(arg).safe_substitute(local_rank=local_rank)
+                args_sub.append(sub)
+            else:
+                args_sub.append(arg)
+        return args_sub
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c39bca6f3c8a31f5f2d7115ad12c1fc4925fe1d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/__init__.py
@@ -0,0 +1,10 @@
+#!/usr/bin/env python3
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+from .cycling_iterator import CyclingIterator  # noqa: F401
+from .elastic_distributed_sampler import ElasticDistributedSampler  # noqa: F401
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..30b22ba8d87c16d2641e7e9859d54ca5d9de2f59
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/__pycache__/cycling_iterator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/__pycache__/cycling_iterator.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..31dead488590e871fbc9115d2b7a2754ad2c59e8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/__pycache__/cycling_iterator.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/__pycache__/elastic_distributed_sampler.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/__pycache__/elastic_distributed_sampler.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c22b4de723f3bea190461f75441c17e0e36df230
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/__pycache__/elastic_distributed_sampler.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/cycling_iterator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/cycling_iterator.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5dadb96bda49d0e5c6af36ae22d24fc64ef6b85
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/cycling_iterator.py
@@ -0,0 +1,44 @@
+#!/usr/bin/env python3
+# mypy: allow-untyped-defs
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+
+class CyclingIterator:
+    """
+    An iterator decorator that cycles through the
+    underlying iterator "n" times. Useful to "unroll"
+    the dataset across multiple training epochs.
+
+    The generator function is called as ``generator_fn(epoch)``
+    to obtain the underlying iterator, where ``epoch`` is a
+    number less than or equal to ``n`` representing the ``k``th cycle
+
+    For example if ``generator_fn`` always returns ``[1,2,3]``
+    then ``CyclingIterator(n=2, generator_fn)`` will iterate through
+    ``[1,2,3,1,2,3]``
+    """
+
+    def __init__(self, n: int, generator_fn, start_epoch=0):
+        self._n = n
+        self._epoch = start_epoch
+        self._generator_fn = generator_fn
+        self._iter = generator_fn(self._epoch)
+
+    def __iter__(self):
+        return self
+
+    def __next__(self):
+        try:
+            return next(self._iter)
+        except StopIteration as eod:  # eod == end of data
+            if self._epoch < self._n - 1:
+                self._epoch += 1
+                self._iter = self._generator_fn(self._epoch)
+                return self.__next__()
+            else:
+                raise eod
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/elastic_distributed_sampler.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/elastic_distributed_sampler.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e378c6a1be1a435f6fa8afacf554f50a926d089
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/elastic_distributed_sampler.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python3
+# mypy: allow-untyped-defs
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+import math
+
+import torch
+from torch.utils.data.distributed import DistributedSampler
+
+
+class ElasticDistributedSampler(DistributedSampler):
+    """
+    Sampler that restricts data loading to a subset of
+    the dataset for elastic training.
+
+    It is especially useful in conjunction with
+    :class:`torch.nn.parallel.DistributedDataParallel`. In such case, each
+    process can pass a DistributedSampler instance as a DataLoader sampler,
+    and load a subset of the original dataset that is exclusive to it.
+
+    .. note::
+        Dataset is assumed to be of constant size.
+
+    Args:
+        dataset: Dataset used for sampling.
+        num_replicas (optional): Number of processes participating in
+            distributed training.
+        rank (optional): Rank of the current process within num_replicas.
+        start_index (optional):  Which index of the dataset to start sampling from
+    """
+
+    def __init__(self, dataset, num_replicas=None, rank=None, start_index=0):
+        super().__init__(dataset=dataset, num_replicas=num_replicas, rank=rank)
+        if start_index >= len(dataset):
+            raise ValueError(
+                f"Start index {start_index} should be less than dataset size {len(dataset)}"
+            )
+
+        self.start_index = start_index
+        self.num_samples = int(
+            math.ceil(float(len(self.dataset) - self.start_index) / self.num_replicas)  # type: ignore[arg-type]
+        )
+        self.total_size = self.num_samples * self.num_replicas
+
+    def __iter__(self):
+        # deterministically shuffle based on epoch
+        g = torch.Generator()
+        g.manual_seed(self.epoch)
+        indices = (
+            torch.randperm(len(self.dataset) - self.start_index, generator=g)  # type: ignore[arg-type]
+            .add(self.start_index)
+            .tolist()
+        )
+
+        # add extra samples to make it evenly divisible
+        indices += indices[: (self.total_size - len(indices))]
+        assert len(indices) == self.total_size
+
+        # subsample
+        indices = indices[self.rank : self.total_size : self.num_replicas]
+        assert len(indices) == self.num_samples
+
+        return iter(indices)
+
+    def __len__(self):
+        return self.num_samples
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/distributed.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/distributed.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e216da72c25470dc2c39bda030e1c8d278d366c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/distributed.py
@@ -0,0 +1,184 @@
+#!/usr/bin/env python3
+# mypy: allow-untyped-defs
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+import datetime
+import os
+import socket
+from contextlib import closing
+from typing import Optional
+
+import torch.distributed as dist
+from torch.distributed.elastic.utils.logging import get_logger
+from torch.distributed.elastic.utils.store import barrier
+
+
+__all__ = ["create_c10d_store", "get_free_port", "get_socket_with_port"]
+
+logger = get_logger(__name__)
+
+_ADDRESS_IN_USE = "Address already in use"
+_SOCKET_TIMEOUT = "Socket Timeout"
+
+_TCP_STORE_INIT = "_tcp_store/num_members"
+
+
+def create_c10d_store(
+    is_server: bool,
+    server_addr: str,
+    server_port: int = -1,
+    world_size: int = 1,
+    timeout: float = (60 * 10),  # 10 min
+    wait_for_workers: bool = True,
+    retries=3,
+    use_libuv: Optional[bool] = None,
+):
+    if use_libuv is not None:
+        logger.warning(
+            "argument use_libuv is deprecated and ignored. Set USE_LIBUV environment "
+            'variable to "0" to disable libuv, or "1" to enable it. If the env var '
+            "is not set, libuv will be used by default."
+        )
+
+    # check os.environ for use_libuv
+    use_libuv = os.environ.get("USE_LIBUV", "1") == "1"  # libuv is the default option
+
+    if server_port == -1 and world_size > 1:
+        raise ValueError(
+            f"server_port must be specified when world_size > 1, got server_port={server_port}, world_size={world_size}"
+        )
+
+    if server_port != -1:
+        logger.info("sever_port: %s, specified, ignoring retries", server_port)
+
+    # only retry when server_port is NOT static
+    attempt = retries if server_port == -1 else 1
+    while True:
+        if server_port != -1:
+            port = server_port
+        else:
+            port = get_free_port()
+
+        logger.info(
+            "Creating c10d store on %s:%s\n"
+            "  world_size  : %s\n"
+            "  is_server   : %s\n"
+            "  timeout(sec): %s\n"
+            "  use_libuv   : %s\n",
+            server_addr,
+            port,
+            world_size,
+            is_server,
+            timeout,
+            use_libuv,
+        )
+
+        try:
+            store = dist.TCPStore(
+                host_name=server_addr,
+                port=port,
+                world_size=world_size,
+                is_master=is_server,
+                timeout=datetime.timedelta(seconds=timeout),
+                wait_for_workers=wait_for_workers,
+                use_libuv=use_libuv,
+            )
+            # skips full rank check when we don't have to wait for all workers
+            if wait_for_workers:
+                _check_full_rank(store, world_size, timeout=timeout)
+            logger.info("Successfully created c10d store")
+            return store
+        except RuntimeError as e:
+            # this is brittle, but the underlying exception type is not properly pybinded
+            # so we parse the error msg for now, interestingly this is how torch itself
+            # detects timeouts and port conflicts in their own unittests
+            # see - caffe2/torch/testing/_internal/common_utils.py
+            # TODO properly map the exceptions in pybind (c10d/init.cpp)
+            if str(e) == _ADDRESS_IN_USE:  # this will only happen on the server
+                if attempt < retries:
+                    logger.warning(
+                        "port: %s already in use, attempt: [%s/%s]",
+                        port,
+                        attempt,
+                        retries,
+                    )
+                    attempt += 1
+                else:
+                    raise RuntimeError(
+                        f"on {server_addr}, port: {port} already in use"
+                    ) from e
+            else:
+                raise
+
+
+def _check_full_rank(store, world_size, timeout):
+    try:
+        barrier(store, world_size, key_prefix=_TCP_STORE_INIT, barrier_timeout=timeout)
+    except RuntimeError as e:
+        if str(e) == _SOCKET_TIMEOUT:
+            raise TimeoutError(
+                f"timed out waiting for all {world_size} members to join"
+            ) from e
+        else:
+            raise
+
+
+def get_free_port():
+    """
+    Returns an unused port on localhost.
+
+    This function finds an unused port on localhost by opening to socket to bind
+    to a port and then closing it.
+
+    Returns:
+        int: an unused port on localhost
+
+    Example:
+        >>> # xdoctest: +SKIP("Nondeterministic")
+        >>> get_free_port()
+        63976
+
+    ..note:
+        The port returned by :func:`get_free_port` is not reserved and may be
+        taken by another process after this function returns.
+    """
+    sock = get_socket_with_port()
+    with closing(sock):
+        return sock.getsockname()[1]
+
+
+def get_socket_with_port() -> socket.socket:
+    """
+    Returns a free port on localhost that is "reserved" by binding a temporary
+    socket on it. Close the socket before passing the port to the entity
+    that requires it. Usage example
+
+    ::
+
+    sock = _get_socket_with_port()
+    with closing(sock):
+        port = sock.getsockname()[1]
+        sock.close()
+        # there is still a race-condition that some other process
+        # may grab this port before func() runs
+        func(port)
+    """
+
+    addrs = socket.getaddrinfo(
+        host="localhost", port=None, family=socket.AF_UNSPEC, type=socket.SOCK_STREAM
+    )
+    for addr in addrs:
+        family, type, proto, _, _ = addr
+        s = socket.socket(family, type, proto)
+        try:
+            s.bind(("localhost", 0))
+            s.listen(0)
+            return s
+        except OSError as e:
+            s.close()
+            logger.warning("Socket creation attempt failed.", exc_info=e)
+    raise RuntimeError("Failed to create a socket")
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/log_level.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/log_level.py
new file mode 100644
index 0000000000000000000000000000000000000000..87ea0f7d64182488b40fd7fed6965ce57ec475a0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/log_level.py
@@ -0,0 +1,14 @@
+#!/usr/bin/env python3
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+
+def get_log_level() -> str:
+    """
+    Return default log level for pytorch.
+    """
+    return "WARNING"
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/logging.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/logging.py
new file mode 100644
index 0000000000000000000000000000000000000000..d87504d255d6f79aaf05606776e20db690cf23da
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/logging.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python3
+# mypy: allow-untyped-defs
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+import inspect
+import logging
+import os
+import warnings
+from typing import Optional
+
+from torch.distributed.elastic.utils.log_level import get_log_level
+
+
+def get_logger(name: Optional[str] = None):
+    """
+    Util function to set up a simple logger that writes
+    into stderr. The loglevel is fetched from the LOGLEVEL
+    env. variable or WARNING as default. The function will use the
+    module name of the caller if no name is provided.
+
+    Args:
+        name: Name of the logger. If no name provided, the name will
+              be derived from the call stack.
+    """
+
+    # Derive the name of the caller, if none provided
+    # Use depth=2 since this function takes up one level in the call stack
+    return _setup_logger(name or _derive_module_name(depth=2))
+
+
+def _setup_logger(name: Optional[str] = None):
+    logger = logging.getLogger(name)
+    logger.setLevel(os.environ.get("LOGLEVEL", get_log_level()))
+    return logger
+
+
+def _derive_module_name(depth: int = 1) -> Optional[str]:
+    """
+    Derives the name of the caller module from the stack frames.
+
+    Args:
+        depth: The position of the frame in the stack.
+    """
+    try:
+        stack = inspect.stack()
+        assert depth < len(stack)
+        # FrameInfo is just a named tuple: (frame, filename, lineno, function, code_context, index)
+        frame_info = stack[depth]
+
+        module = inspect.getmodule(frame_info[0])
+        if module:
+            module_name = module.__name__
+        else:
+            # inspect.getmodule(frame_info[0]) does NOT work (returns None) in
+            # binaries built with @mode/opt
+            # return the filename (minus the .py extension) as modulename
+            filename = frame_info[1]
+            module_name = os.path.splitext(os.path.basename(filename))[0]
+        return module_name
+    except Exception as e:
+        warnings.warn(
+            f"Error deriving logger module name, using . Exception: {e}",
+            RuntimeWarning,
+        )
+        return None
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/store.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/store.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a1351d4cf5e160f9554b815eeed2df8ff22ffa6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/elastic/utils/store.py
@@ -0,0 +1,225 @@
+#!/usr/bin/env python3
+# mypy: allow-untyped-defs
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+from contextlib import contextmanager
+from datetime import timedelta
+from typing import Callable, Iterable, List, Optional
+
+import torch
+
+
+DistStoreError = torch._C._DistStoreError
+
+_NUM_MEMBERS = "/num_members"
+_LAST_MEMBER_CHECKIN = "/last_member"
+_TRACE = "/TRACE"
+_TRACING_GATE = "/TRACING_GATE"
+_MAX_TRACE_MISSING_RANKS = 16
+
+
+__all__ = ["store_timeout", "get_all", "synchronize", "barrier"]
+
+
+@contextmanager
+def store_timeout(store, timeout: float):
+    """
+    This sets the timeout and then restores the old timeout when the context
+    manager exits.
+
+    Args:
+        store: the store to set the timeout on
+        timeout: the timeout to set
+    """
+
+    old_timeout = store.timeout
+    store.set_timeout(timedelta(seconds=timeout))
+    yield
+    store.set_timeout(old_timeout)
+
+
+def get_all(store, rank: int, prefix: str, world_size: int):
+    r"""
+    Given a store and a prefix, the method goes through the array of keys
+    of the following format: ``{prefix}{idx}``, where idx is in a range
+    from 0 to size, and tries to retrieve the data.
+
+    The Rank0 process waits at the end to make sure all other processes
+    finished the procedure before exiting.
+
+    Usage
+
+    ::
+
+     values = get_all(store, 'torchelastic/data', 3)
+     value1 = values[0] # retrieves the data for key torchelastic/data0
+     value2 = values[1] # retrieves the data for key torchelastic/data1
+     value3 = values[2] # retrieves the data for key torchelastic/data2
+
+    """
+    data_arr = store.multi_get([f"{prefix}{idx}" for idx in range(world_size)])
+
+    barrier_key = _barrier_nonblocking(
+        store=store,
+        world_size=world_size,
+        key_prefix=f"{prefix}/finished",
+    )
+    if rank == 0:
+        # Rank0 runs the TCPStore daemon, as a result it needs to exit last.
+        # Otherwise, the barrier may timeout if rank0 process finished the work
+        # before other processes finished `get_all` method
+        store.wait([barrier_key])
+
+    return data_arr
+
+
+def synchronize(
+    store,
+    data: bytes,
+    rank: int,
+    world_size: int,
+    key_prefix: str,
+    timeout: float = 300,
+) -> List[bytes]:
+    """
+    Synchronizes ``world_size`` agents between each other using the underlying c10d store.
+    The ``data`` will be available on each of the agents.
+
+    Note: The data on the path is not deleted, as a result there can be stale data if
+        you use the same key_prefix twice.
+
+    Time complexity: O(N) per worker, O(N^2) globally.
+    """
+    with store_timeout(store, timeout):
+        store.set(f"{key_prefix}{rank}", data)
+        agent_data = get_all(store, rank, key_prefix, world_size)
+        return agent_data
+
+
+def _try_detecting_missing_ranks(
+    store,
+    world_size: int,
+    key_prefix: str,
+    rank: int,
+    rank_decoder: Callable[[int], str],
+    trace_timeout: float,
+) -> Optional[Iterable[str]]:
+    store.set(f"{key_prefix}{rank}{_TRACE}", "")
+
+    def _find_missing_ranks():
+        missing_rank_info = set()
+        ranks_missing = 0
+        for i in range(1, world_size):
+            # reduce noise, assuming in general 8 ranks per node
+            # It is valuable to know that 1 or >1 nodes have timed-out.
+            if ranks_missing >= _MAX_TRACE_MISSING_RANKS:
+                break
+            try:
+                if ranks_missing == 0:
+                    store.wait(
+                        [f"{key_prefix}{i}{_TRACE}"], timedelta(seconds=trace_timeout)
+                    )
+                else:
+                    # use a shortest timeout, some ranks have failed to check-in
+                    store.wait([f"{key_prefix}{i}{_TRACE}"], timedelta(milliseconds=1))
+            except DistStoreError:
+                ranks_missing += 1
+                missing_rank_info.add(rank_decoder(i))
+        return missing_rank_info
+
+    def _checkin():
+        try:
+            store.wait([f"{key_prefix}{_TRACING_GATE}"])
+            return [f"[]"]
+        except DistStoreError:
+            # in case rank0 is the source of the timeout, original exception will be raised
+            return None
+
+    if rank == 0:
+        missing_rank_info = _find_missing_ranks()
+        store.set(f"{key_prefix}{_TRACING_GATE}", "")
+        return missing_rank_info
+    else:
+        return _checkin()
+
+
+def _barrier_nonblocking(store, world_size: int, key_prefix: str) -> str:
+    """
+    Does all the non-blocking operations for a barrier and returns the final key
+    that can be waited on.
+    """
+    num_members_key = key_prefix + _NUM_MEMBERS
+    last_member_key = key_prefix + _LAST_MEMBER_CHECKIN
+
+    idx = store.add(num_members_key, 1)
+    if idx == world_size:
+        store.set(last_member_key, "")
+
+    return last_member_key
+
+
+def barrier(
+    store,
+    world_size: int,
+    key_prefix: str,
+    barrier_timeout: float = 300,
+    rank: Optional[int] = None,
+    rank_tracing_decoder: Optional[Callable[[int], str]] = None,
+    trace_timeout: float = 10,
+) -> None:
+    """
+    A global lock between agents. This will pause all workers until at least
+    ``world_size`` workers respond.
+
+    This uses a fast incrementing index to assign waiting ranks and a success
+    flag set by the last worker.
+
+    Time complexity: O(1) per worker, O(N) globally.
+
+    Optionally, passing rank will enable tracing of missing ranks on timeouts.
+    `rank_tracing_decoder` lambda arg can be used to convert rank data
+    into a more meaninful information at an app level (e.g. hostname).
+
+    Note: Since the data is not removed from the store, the barrier can be used
+        once per unique ``key_prefix``.
+    """
+
+    if rank is None:
+        assert rank_tracing_decoder is None, "Tracing requires rank information"
+
+    with store_timeout(store, barrier_timeout):
+        last_member_key = _barrier_nonblocking(
+            store=store, world_size=world_size, key_prefix=key_prefix
+        )
+        try:
+            store.wait([last_member_key])
+        except DistStoreError as e:
+            if rank is None:
+                raise e
+            else:
+                missing_ranks = _try_detecting_missing_ranks(
+                    store,
+                    world_size,
+                    key_prefix,
+                    rank,
+                    rank_tracing_decoder or (lambda x: str(x)),
+                    trace_timeout,
+                )
+                if missing_ranks is not None:
+                    raise DistStoreError(
+                        "Timed out waiting on barrier on "
+                        "rank {}, for key prefix: {} (world_size={}, missing_ranks={}, timeout={})".format(
+                            rank,
+                            key_prefix,
+                            world_size,
+                            f"[{', '.join(missing_ranks)}]",
+                            barrier_timeout,
+                        )
+                    ) from None
+                else:
+                    raise e
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6180dbb3df299e7454bd7b37e064334b159782bc
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__init__.py
@@ -0,0 +1,39 @@
+from ._flat_param import FlatParameter as FlatParameter
+from .fully_sharded_data_parallel import (
+    BackwardPrefetch,
+    CPUOffload,
+    FullOptimStateDictConfig,
+    FullStateDictConfig,
+    FullyShardedDataParallel,
+    LocalOptimStateDictConfig,
+    LocalStateDictConfig,
+    MixedPrecision,
+    OptimStateDictConfig,
+    OptimStateKeyType,
+    ShardedOptimStateDictConfig,
+    ShardedStateDictConfig,
+    ShardingStrategy,
+    StateDictConfig,
+    StateDictSettings,
+    StateDictType,
+)
+
+
+__all__ = [
+    "BackwardPrefetch",
+    "CPUOffload",
+    "FullOptimStateDictConfig",
+    "FullStateDictConfig",
+    "FullyShardedDataParallel",
+    "LocalOptimStateDictConfig",
+    "LocalStateDictConfig",
+    "MixedPrecision",
+    "OptimStateDictConfig",
+    "OptimStateKeyType",
+    "ShardedOptimStateDictConfig",
+    "ShardedStateDictConfig",
+    "ShardingStrategy",
+    "StateDictConfig",
+    "StateDictSettings",
+    "StateDictType",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5129598622a7b63c63ac04c8349c17c8e582230c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_common_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_common_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..68b027affe82fdea832dcf128740ccff81a6ed1c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_common_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_debug_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_debug_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6f37dae9a317ccbd334275d93137c0328d4d5f4e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_debug_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_dynamo_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_dynamo_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b27091e715a7c8938a9057dc9a771853da4b34c7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_dynamo_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_exec_order_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_exec_order_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5e8e17f5af66111be24be3329dd66d964583c4ac
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_exec_order_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_fsdp_extensions.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_fsdp_extensions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d0e6bbf1b9cbeab8b23fdcb18e600be7478a5be1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_fsdp_extensions.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_init_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_init_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..93b6aab0b1b4bcf32808c2574f8363a0378dadc8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_init_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_limiter_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_limiter_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7a79664cfa2c11e326ae26fb4b8bb833ab0da933
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_limiter_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_optim_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_optim_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7e3276255a08a1042cfec6c065b210803e697d3e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_optim_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_runtime_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_runtime_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dc7d39533909def05d1c5bd15ae4f75fa70b0e16
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_runtime_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_shard_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_shard_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..190b30cfb6cef45dd26fdea944d37f15327dc14e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_shard_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_state_dict_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_state_dict_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4a14a63f05f489e9e40bd37f3f9718af5c22090d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_state_dict_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_trace_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_trace_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..60e79bddcd00b710706fc9503e731dcad22a9b58
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_trace_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_traversal_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_traversal_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fe90eae8436be96ac772a363ee1b9e69f8cefa4c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_traversal_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_unshard_param_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_unshard_param_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e147ab81a2f930da1ed0ba198d96be59bf3224f9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_unshard_param_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_wrap_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_wrap_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e1348935f4338d0b392a844feae370d6da4de65f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_wrap_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/api.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/api.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d3b246774de5da0ac0dc6c6c7778ff9178be787d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/api.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/sharded_grad_scaler.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/sharded_grad_scaler.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e617987da14d7edc0728c9cc63dcdd2b3f123235
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/sharded_grad_scaler.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/wrap.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/wrap.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e58a44dc466a056801a50b087675ea3229264321
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/wrap.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_common_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_common_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..396f058c45a1aef3bba5e3c8b8b3f4b6dfbe1bd3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_common_utils.py
@@ -0,0 +1,558 @@
+# mypy: allow-untyped-defs
+"""
+This file includes private common utilities for FSDP.
+"""
+import logging
+import traceback
+import warnings
+import weakref
+from enum import auto, Enum
+from functools import partial
+from typing import (
+    Any,
+    Callable,
+    cast,
+    Dict,
+    Generator,
+    Iterable,
+    List,
+    no_type_check,
+    Optional,
+    Set,
+    Tuple,
+    Type,
+    TYPE_CHECKING,
+)
+
+import torch
+import torch.distributed as dist
+import torch.distributed.fsdp._flat_param as flat_param_file
+import torch.nn as nn
+from torch.distributed._composable_state import _get_module_state, _State
+from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import (
+    _CHECKPOINT_PREFIX,
+)
+from torch.distributed.utils import _apply_to_tensors
+from torch.utils._mode_utils import no_dispatch
+
+from .api import (
+    FullOptimStateDictConfig,
+    FullStateDictConfig,
+    OptimStateDictConfig,
+    ShardingStrategy,
+    StateDictConfig,
+    StateDictType,
+)
+
+
+if TYPE_CHECKING:
+    from torch.distributed.device_mesh import DeviceMesh
+    from torch.distributed.fsdp._fsdp_extensions import FSDPExtensions
+
+    from ._flat_param import FlatParamHandle
+
+FSDP_WRAPPED_MODULE = "_fsdp_wrapped_module"
+FSDP_PREFIX = FSDP_WRAPPED_MODULE + "."
+FSDP_FLATTENED = "_fsdp_flattened"
+
+# Save a global mapping from module to its input tensor dtype to be populated
+# during the forward pre-hook and consumed in the forward post-hook when
+# overriding a module's mixed precision
+# NOTE: We currently take the last input tensor's dtype in the case of multiple
+# floating-point input tensors, which may be incorrect. However, since there is
+# not a 1:1 correspondence between input and output tensors, we must use *some*
+# heuristic like this to predict the desired output dtype.
+_MODULE_TO_INP_DTYPE: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary()
+
+
+class _FSDPDeviceHandle:
+    """
+    This is a simple abstraction for FSDP computing devices,
+    which enables custom backends that implement CUDA-like
+    semantics to be integrated with FSDP.
+    """
+
+    def __init__(self, device: torch.device, backend: Any = None):
+        if backend is None:
+            try:
+                self.__backend = getattr(torch, device.type)
+                self.__device = device
+            except AttributeError as exc:
+                raise AttributeError(
+                    f"Device '{device}' does not have a corresponding backend registered as 'torch.{device.type}'."
+                ) from exc
+        else:
+            self.__backend = backend
+
+    @classmethod
+    def from_device(cls, device: torch.device) -> "_FSDPDeviceHandle":
+        """
+        Return a device handle corresponding to the device, and through this handle,
+        operations with the same semantics as CUDA can be performed on the device.
+        Just return torch.cuda if the device is cuda to make attribute-access faster.
+        Custom backend must first register a module with the same name with {device.type} on torch.
+        """
+        if device.type == "cuda":
+            return cast(_FSDPDeviceHandle, torch.cuda)
+        elif device.type == "mtia":
+            return cast(_FSDPDeviceHandle, torch.mtia)
+        return cls(device)
+
+    def __getattr__(self, __name: str) -> Any:
+        try:
+            return getattr(self.__backend, __name)
+        except AttributeError as exc:
+            raise AttributeError(
+                f"Custom backend '{self.__device.type}' not implement 'torch.{self.__device.type}.{__name}'"
+            ) from exc
+
+
+class _UninitializedDeviceHandle(_FSDPDeviceHandle):
+    def __init__(self) -> None:
+        pass
+
+    def __getattribute__(self, __name: str) -> Any:
+        raise RuntimeError("Trying to use an uninitialized device handle.")
+
+
+class _FSDPState(_State):
+    def __init__(self) -> None:
+        # TODO: Move all the attributes to this class to enable typing for
+        # FSDP/fully_shard.
+        self._ignored_modules: Set[nn.Module] = set()
+        self._ignored_params: Set[nn.Parameter] = set()
+        # Buffer names are cleaned (without wrapper prefixes)
+        self._ignored_buffer_names: Set[str] = set()
+        self.process_group: Optional[dist.ProcessGroup] = None
+        self.rank: int = -1
+        self.world_size: int = -1
+        self._device_mesh: Optional[DeviceMesh] = None
+        self.sharding_strategy = ShardingStrategy.FULL_SHARD
+        self._use_orig_params: bool = False
+        self.training_state = TrainingState.IDLE
+        self._unshard_params_ctx: Dict[nn.Module, Generator] = {}
+        self._state_dict_type: StateDictType = StateDictType.FULL_STATE_DICT
+        self._state_dict_config: StateDictConfig = FullStateDictConfig()
+        self._optim_state_dict_config: OptimStateDictConfig = FullOptimStateDictConfig()
+        self._is_root: Optional[bool] = None
+        self._handle: Optional[flat_param_file.FlatParamHandle] = None
+        self._fully_sharded_module_to_handle: Dict[
+            nn.Module, Optional[flat_param_file.FlatParamHandle]
+        ] = {}
+        self.compute_device: Optional[torch.device] = None
+        self._gradient_predivide_factor: int = 0
+        self._gradient_postdivide_factor: int = 0
+        self._comm_hook: Optional[Callable] = None
+        self._comm_hook_state: Optional[Any] = None
+        self._unshard_event: Optional[torch.Event] = None
+        # Abstract device handle for fsdp compute device. For now,
+        # the compute device must implement cuda semantics used by fsdp
+        self._device_handle: _FSDPDeviceHandle = _UninitializedDeviceHandle()
+        # All following attributes should only be used for root states:
+        # Save these static lists to avoid the repeated tree traversals
+        self._all_fsdp_states: List[_FSDPState] = []
+        self._all_handles: List[flat_param_file.FlatParamHandle] = []
+        self._fsdp_extension: Optional[FSDPExtensions] = None
+
+
+def _get_module_fsdp_state(module: nn.Module) -> Optional[_FSDPState]:
+    state = _get_module_state(module)
+    if state is None or not isinstance(state, _FSDPState):
+        return None
+    return state
+
+
+def _get_module_fsdp_state_if_fully_sharded_module(
+    module: nn.Module,
+) -> Optional[_FSDPState]:
+    state = _get_module_fsdp_state(module)
+    if state is None:
+        return None
+    if state == module:  # FullyShardedDataParallel module case.
+        return state
+    if module in state._fully_sharded_module_to_handle:  # fully_shard case.
+        return state
+    return None
+
+
+class TrainingState(Enum):
+    """
+    An enum that indicates the state of a ``FullyShardedDataParallel` instance.
+    """
+
+    IDLE = auto()
+    FORWARD_BACKWARD = auto()
+    SUMMON_FULL_PARAMS = auto()
+
+
+class HandleTrainingState(Enum):
+    """
+    An enum that indicates the state of a ``FlatParamHandle`.
+    """
+
+    IDLE = auto()
+    FORWARD = auto()
+    BACKWARD_PRE = auto()
+    BACKWARD_POST = auto()
+    SUMMON_FULL_PARAMS = auto()
+
+
+def _is_composable(state: _FSDPState):
+    # TODO: This is a temporary hack for differentiate between code paths.
+    return not isinstance(state, nn.Module)
+
+
+@no_type_check
+def _module_handle(state: _FSDPState, module: nn.Module) -> Optional["FlatParamHandle"]:
+    """
+    Returns the ``FlatParamHandle`` s corresponding to ``module``. This is
+    the handle that contains some parameter in ``module``.
+    """
+    if _is_composable(state):
+        # A valid FSDP state may have no managed parameters and hence no
+        # handles, meaning no entry in `_fully_sharded_module_to_handles`
+        if state._handle is None:
+            return None
+        assert (
+            module in state._fully_sharded_module_to_handle
+        ), f"Expects a fully sharded module but got {module} on rank {state.rank}"
+        return state._fully_sharded_module_to_handle[module]
+    else:
+        # NOTE: This assumes `module` is a `FullyShardedDataParallel` instance.
+        return module._handle
+
+
+@no_type_check
+def _has_fsdp_params(state: _FSDPState, module: nn.Module) -> bool:
+    """Returns if ``module`` has parameters managed by FSDP."""
+    return _module_handle(state, module) is not None
+
+
+def _get_sharding_strategy(handle):
+    """
+    Returns the sharding strategy of the handle.
+    """
+    return handle._sharding_strategy if handle else None
+
+
+def clean_tensor_name(tensor_name: str) -> str:
+    """
+    Cleans the parameter or buffer name by removing any module wrapper
+    prefixes.
+    """
+    tensor_name = tensor_name.replace(FSDP_PREFIX, "")
+    # TODO: Explicitly replacing the checkpoint wrapper prefix is not ideal as
+    # it couples `CheckpointWrapper` and FSDP and also does not scale for more
+    # module wrappers.
+    tensor_name = tensor_name.replace(_CHECKPOINT_PREFIX, "")
+    return tensor_name
+
+
+def _set_fsdp_flattened(tensor: torch.Tensor) -> None:
+    """
+    Sets an attribute on ``tensor`` to mark it as flattened by FSDP. This is to
+    avoid re-flattening it during nested construction.
+    """
+    setattr(tensor, FSDP_FLATTENED, True)
+
+
+def _is_fsdp_flattened(tensor: torch.Tensor) -> bool:
+    """Returns if ``tensor`` has been marked as flattened by FSDP."""
+    return getattr(tensor, FSDP_FLATTENED, False)
+
+
+def _named_parameters_with_duplicates(
+    module: nn.Module, **kwargs: Any
+) -> List[Tuple[str, nn.Parameter]]:
+    """
+    This API is required as some modules overwrite `named_parameters()` but do not support
+    `remove_duplicate`.
+    """
+    assert (
+        "remove_duplicate" not in kwargs
+    ), "_named_parameters_with_duplicates cannot be used with `remove_duplicate` argument."
+    kwargs["remove_duplicate"] = False
+    try:
+        ret = list(module.named_parameters(**kwargs))
+    except AssertionError as e:
+        kwargs.pop("remove_duplicate")
+        ret = list(module.named_parameters(**kwargs))
+    return ret
+
+
+def _get_param_to_fqns(
+    model: torch.nn.Module,
+    dedup_shared_params: bool = True,
+) -> Dict[nn.Parameter, List[str]]:
+    """
+    Constructs a mapping from parameter to a list of its \"canonical\" FQNs. Here,
+    we use canonical to mean the fully-qualified name assigned to the parameter
+    based on its position in the original nn.Module hierarchy before any wrapper
+    or parallelism has been applied to it. This is in contrast to FQNs that may be
+    generated after parallelisms or wrappers have been applied to the model.
+
+    Each normal parameter maps to a singleton list containing its FQN, while each
+    ``FlatParameter`` maps to a list of its original parameter FQNs, which may
+    have length greater than one.  All FQNs are prefixed starting from ``model``.
+
+    In the case where FSDP was applied with ``use_orig_params=True``, there should be no
+    ``FlatParameter`` s registered to the model's modules and this mapping will only
+    contain mappings from ``nn.Parameter`` s to singleton FQN lists.
+
+    It is only in the case where FSDP was applied with ``use_orig_params=False`` where
+    a ``FlatParameter`` will be registered in place of the original parameters and there
+    will be mappings from each ``FlatParameter`` to lists of FQNs corresponding to the
+    original parameters.
+
+    Args:
+        model (torch.nn.Module): Root module (which may or may not be a
+            :class:`FullyShardedDataParallel` instance).
+        dedup_shared_params (bool): For shared parameters, if ``True``, only
+            includes the FQNs corresponding to the first encounter of the
+            shared parameter in the module traversal; if ``False``, then
+            includes the FQNs across all encounters. (Default: ``True``)
+    """
+
+    def module_fn(module, prefix, tree_level, param_to_fqns):
+        for param_name, param in _named_parameters_with_duplicates(
+            module, recurse=False
+        ):
+            local_fqns = (
+                param._fqns
+                if isinstance(param, flat_param_file.FlatParameter)
+                else [param_name]
+            )  # prefixed from `module`
+            global_fqns = [
+                clean_tensor_name(prefix + name) for name in local_fqns
+            ]  # prefixed from the top level `model` (i.e. including `prefix`)
+            is_shared_param = param in param_to_fqns
+            if not is_shared_param:
+                param_to_fqns[param] = global_fqns
+            else:
+                if isinstance(param, flat_param_file.FlatParameter):
+                    # DMP overwrites `named_parameters` and skip (advance to
+                    # the next child module) the wrapped_module (e.g.,
+                    # _dmp_wrapped_module and _fsdp_wrapped_module). When a user
+                    # calls `named_child` to traverse the module recursively and
+                    # calls `named_parameters` with `recurse=False`, parameters
+                    # will be traversed more than once.
+                    # This hack is specified designed for DMP + FSDP. We
+                    # overwrite the flat_parameters traversal result to only obtain
+                    # the last one, which happens to be the correct one.
+                    #
+                    # TODO: Remove this hack once DMP + FSDP is not supported.
+                    warnings.warn(
+                        "FlatParameter is being traversed more than once. "
+                        "This case should only happen when using "
+                        "DistributedModelParallel with FullyShardedDataParallel."
+                    )
+                    param_to_fqns[param] = global_fqns
+                elif not dedup_shared_params:
+                    param_to_fqns[param].extend(global_fqns)
+
+    def return_fn(param_to_fqns):
+        return param_to_fqns
+
+    param_to_unflat_param_names: Dict[torch.nn.Parameter, List[str]] = {}
+    return _apply_to_modules(
+        model,
+        module_fn,
+        return_fn,
+        [key for key, _ in _named_parameters_with_duplicates(model)],
+        param_to_unflat_param_names,
+    )
+
+
+@no_type_check
+def _log_post_backward_hook(
+    state: _FSDPState, handle: "FlatParamHandle", logger: logging.Logger
+) -> None:
+    # Under TORCH_DISTRIBUTED_DEBUG=INFO, log the module names this hook fires for.
+    # Below logging of module names this post-bwd hook fires for can help debug certain
+    # cases where hooks don't fire, such as under certain activation checkpoint configs.
+    if state._use_orig_params and handle._debug_level == dist.DebugLevel.INFO:
+        param_fqns = _get_handle_fqns_from_root(state, handle)
+        logger.warning("FSDP firing post-backward hooks for parameters %s", param_fqns)
+
+
+@no_type_check
+def _get_handle_fqns_from_root(
+    state: _FSDPState, handle: "FlatParamHandle"
+) -> Optional[List[str]]:
+    if handle is None:
+        return None
+    param_to_fqn = state._exec_order_data.param_to_fqn
+    handle_params = handle.flat_param._params  # only populated for use_orig_params
+    param_fqns = [
+        fqn for fqn_list in [param_to_fqn[p] for p in handle_params] for fqn in fqn_list
+    ]
+    return param_fqns
+
+
+def _apply_to_modules(
+    root_module: torch.nn.Module,
+    module_fn: Callable,
+    return_fn: Callable,
+    filter_fqns: Optional[List[str]] = None,
+    *args,
+    **kwargs,
+):
+    """
+    Performs a pre-order traversal of the modules in the hierarchy rooted at
+    ``root_module``, applying ``module_fn`` at each module and finally
+    returning a value using ``return_fn``. The traversal constructs the full
+    module prefix name (e.g. "module.submodule." just like in model state dict)
+    and makes that available to ``module_fn``.
+
+    ``filter_fqns`` is used because some module may have its own prefix similar
+    to ``FullyShardedDataParallel`` and the ``named_parameters()`` is overwritten
+    to remove the prefix.
+    """
+
+    def f(module: torch.nn.Module, prefix: str, tree_level: int, *args, **kwargs):
+        # Call the module function before recursing over children (pre-order)
+        module_fn(module, prefix, tree_level, *args, **kwargs)
+        for submodule_name, submodule in module.named_children():
+            if submodule is None:
+                continue
+            new_prefix = prefix + submodule_name + "."
+            new_tree_level = tree_level + 1
+            if filter_fqns is not None:
+                for fqn in filter_fqns:
+                    if fqn.startswith(new_prefix):
+                        break
+                else:
+                    # DMP's named_parameter() will mess up the traversal with
+                    # ``named_children`` + `named_parameter(recurse=False)``.
+                    # This hack is a must to make the traversal work.
+                    # TODO: Remove this hack once DMP + FSDP is not supported.
+                    # It turns out that recursive wrapping may trigger this as
+                    # well.
+                    if (
+                        submodule_name == "_fsdp_wrapped_module"
+                        or submodule_name == "_dmp_wrapped_module"
+                    ):
+                        new_prefix = prefix
+                    elif submodule_name == "module":
+                        new_prefix = prefix
+            f(submodule, new_prefix, new_tree_level, *args, **kwargs)
+
+    f(root_module, "", 0, *args, **kwargs)
+    return return_fn(*args, **kwargs)
+
+
+@no_type_check
+def _assert_in_training_states(
+    state: _FSDPState,
+    training_states: List[TrainingState],
+) -> None:
+    """Asserts that FSDP is in the states ``_training_states``."""
+    # Raise a `ValueError` instead of using `assert` to ensure that these
+    # logical assertions run even if `assert`s are disabled
+    if state.training_state not in training_states:
+        msg = (
+            f"expected to be in states {training_states} but current state is "
+            f"{state.training_state}"
+        )
+        # Print the error on rank 0 in case this is called in the backward pass
+        if state.rank == 0:
+            if isinstance(state, nn.Module):
+                print(f"Asserting FSDP instance is: {state}")
+            print(f"ERROR: {msg}")
+            traceback.print_stack()
+        raise ValueError(msg)
+
+
+def _get_root_modules(modules: Set[nn.Module]) -> Set[nn.Module]:
+    """
+    Returns:
+        Set[nn.Module]: The subset of ``modules`` that are root modules (i.e.
+        parent-less) with respect to the modules in the set itself. In other
+        words, these are the modules in ``modules`` that are not the child of
+        any other module in ``modules``.
+    """
+    root_modules: Set[nn.Module] = set()
+    module_to_submodules = {module: set(module.modules()) for module in modules}
+    for candidate_module in modules:
+        is_root_module = True
+        for module, submodules in module_to_submodules.items():
+            is_child_module = (
+                candidate_module is not module and candidate_module in submodules
+            )
+            if is_child_module:
+                is_root_module = False
+                break
+        if is_root_module:
+            root_modules.add(candidate_module)
+    return root_modules
+
+
+def _override_module_mixed_precision(
+    root: torch.nn.Module,
+    module_classes_to_override: Iterable[Type[nn.Module]],
+    wrap_override_dict: Dict[str, Any] = {"mixed_precision": None},  # noqa: B006
+) -> Set[Type[nn.Module]]:
+    module_classes_to_override = tuple(set(module_classes_to_override))
+    # Return a set of the actually overridden module classes
+    overridden_module_classes: Set[Type[nn.Module]] = set()
+    for mod in root.modules():
+        if isinstance(mod, module_classes_to_override):
+            overridden_module_classes.add(type(mod))
+            mod._wrap_overrides = wrap_override_dict  # type: ignore[assignment]
+            # TODO: We need to run this mixed precision ignored module in fp32,
+            # but ensure subsequent modules, that may possibly be running with
+            # mixed precision, still receive the appropriate precision inputs
+            # without user having to adjust mixed precision config too much.
+            # As a result, we attach pre and post forward hooks to up / down
+            # cast. We should revisit this design.
+
+            def cast_fn(
+                dtype: torch.dtype, module: nn.Module, x: torch.Tensor
+            ) -> torch.Tensor:
+                if not torch.is_floating_point(x) or x.dtype == dtype:
+                    return x
+                _MODULE_TO_INP_DTYPE[module] = x.dtype
+                return x.to(dtype)
+
+            def forward_pre_hook(module, args):
+                return _apply_to_tensors(partial(cast_fn, torch.float32, module), args)
+
+            def forward_post_hook(module, args, output):
+                # NOTE: If the forward did not have any floating-point tensors,
+                # then the dtype will not be set for this module, and we do not
+                # upcast the dtype.
+                if module in _MODULE_TO_INP_DTYPE:
+                    old_dtype = _MODULE_TO_INP_DTYPE[module]
+                    return _apply_to_tensors(
+                        partial(cast_fn, old_dtype, module), output
+                    )
+
+            # We intentionally append both of these hooks so that they run after
+            # all other hooks.
+            mod.register_forward_pre_hook(forward_pre_hook, prepend=False)
+            mod.register_forward_hook(forward_post_hook, prepend=False)
+    return overridden_module_classes
+
+
+def _no_dispatch_record_stream(tensor: torch.Tensor, stream: torch.Stream) -> None:
+    # FIXME record_stream doesn't work with non-cuda/mtia tensors
+    if tensor.device.type not in [
+        "cuda",
+        "mtia",
+        torch._C._get_privateuse1_backend_name(),
+    ]:
+        return
+
+    if torch.distributed._functional_collectives.is_torchdynamo_compiling():
+        return
+        # from @ezyang:
+        # The no_dispatch was added in https://github.com/pytorch/pytorch/pull/88014 cc @fegin
+        # Looking over the PR, it looks like this is because we don't actually support Stream arguments
+        # in torch dispatch, so it just chokes.
+        # If Dynamo is able to answer "are there any torch dispatch modes" active (it should answer False),
+        # a better version of this would just be to check if there are any modes before disabling dispatch.
+        # TODO(voz): Extend a dynamo util to answer the above, unify the codepaths here.
+        tensor.record_stream(stream)
+    else:
+        with no_dispatch():
+            tensor.record_stream(stream)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_debug_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_debug_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..163d9a045b68eaf612ec93b74526f8ee2c06486a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_debug_utils.py
@@ -0,0 +1,157 @@
+# mypy: allow-untyped-defs
+import logging
+import time
+from collections import defaultdict
+from contextlib import contextmanager
+from enum import Enum
+from typing import Dict, Iterator, List, Set, Tuple
+
+import torch
+import torch.distributed as dist
+import torch.distributed.fsdp._flat_param as flat_param_file
+from torch.distributed.fsdp._common_utils import (
+    _apply_to_modules,
+    _get_module_fsdp_state,
+    clean_tensor_name,
+)
+
+
+logger = logging.getLogger(__name__)
+
+
+class SimpleProfiler:
+    class Type(str, Enum):
+        ALL = "all"
+        ALLGATHER = "all_gather"
+        ALLGATHER_OBJ = "all_gather_object"
+        RESHARDING = "resharding"
+        H2D = "H2D"
+        D2H = "D2H"
+
+    results: Dict[str, float] = defaultdict(float)
+    profiling: Set[str] = set()
+
+    @classmethod
+    def reset(cls) -> None:
+        cls.results.clear()
+        cls.profiling.clear()
+
+    @classmethod
+    @contextmanager
+    def profile(cls, profile_type: str) -> Iterator[None]:
+        assert profile_type not in cls.profiling, (
+            f"{profile_type} is already being profiled. "
+            "SimpleProfiler does not support profiling multiple instances at "
+            "the same time. "
+        )
+
+        cls.profiling.add(profile_type)
+        begin = time.monotonic()
+        try:
+            yield
+        finally:
+            end = time.monotonic()
+            cls.results[profile_type] += end - begin
+            cls.profiling.remove(profile_type)
+
+    @classmethod
+    def dump_and_reset(cls, msg: str) -> None:
+        # This cannot be combined with DETAIL distributed log
+        # as the profiling will be very incorrect.
+        if dist.get_rank() == 0 and dist.get_debug_level() == dist.DebugLevel.INFO:
+            logger.info("%s %s", msg, cls.results)
+        cls.reset()
+
+
+def _get_sharded_module_tree_with_module_name_to_fqns(
+    model: torch.nn.Module,
+) -> Tuple[str, Dict[str, List[str]]]:
+    """
+    It is used for composable fully_shard() code path, it returns
+      1. sharded module tree info: each line reprents a submodule name that contats the
+    submodule's FQN and its submodule class name, if the submodule is sharded by `fully_shard`,
+    the submodule name will add a postfix with ' FULLY SHARDED'. Each increased tree
+    level adds 4 spaces before the printed name. A printed sharded module tree info for a toy model
+    is like this:
+        [CompositeModel] FULLY SHARDED
+            l1[Linear]
+            u1[UnitModule] FULLY SHARDED
+                u1.l1[Linear]
+                u1.seq[Sequential]
+                    u1.seq.0[ReLU]
+                    u1.seq.1[Linear]
+                    u1.seq.2[ReLU]
+                u1.l2[Linear]
+            u2[UnitModule] FULLY SHARDED
+                u2.l1[Linear]
+                u2.seq[Sequential]
+                    u2.seq.0[ReLU]
+                    u2.seq.1[Linear]
+                    u2.seq.2[ReLU]
+                u2.l2[Linear]
+            l2[Linear]
+      2. a dict mapping from the concated module FQN and class name to a list of its managed
+    original parameters' FQNs. An example of the dict for the above toy sharded model is like this:
+            {'[CompositeModel]': ['l1.weight', 'l1.bias', 'l2.weight', 'l2.bias'],
+             'u1[UnitModule]': ['u1.l1.weight', 'u1.l1.bias', 'u1.seq.1.weight', 'u1.seq.1.bias', 'u1.l2.weight', 'u1.l2.bias'],
+             'u2[UnitModule]': ['u2.l1.weight', 'u2.l1.bias', 'u2.seq.1.weight', 'u2.seq.1.bias', 'u2.l2.weight', 'u2.l2.bias']
+            }
+    All FQNs are prefixed starting from ``model``.
+
+    Args:
+        model (torch.nn.Module): Root module (which may or may not be passed to
+                                 composable `fully_shard()`).
+    """
+
+    def module_fn(
+        module, prefix, tree_level, sharded_tree_info, sharded_module_name_to_fqns
+    ):
+        num_spaces = tree_level * 4
+        trimed_prefix = (
+            prefix[:-1] if (len(prefix) > 0 and prefix[-1] == ".") else prefix
+        )
+        prefixed_module_name = trimed_prefix + "[" + module.__class__.__name__ + "]"
+        printed_prefixed_module_name = " " * num_spaces + prefixed_module_name
+
+        state = _get_module_fsdp_state(module)
+        if state is None:
+            sharded_tree_info[0] += printed_prefixed_module_name + "\n"
+            return
+
+        handle = state._fully_sharded_module_to_handle.get(module, None)
+
+        if handle:
+            sharded_tree_info[0] += (
+                printed_prefixed_module_name + " FULLY SHARDED" + "\n"
+            )
+        else:
+            sharded_tree_info[0] += printed_prefixed_module_name + "\n"
+
+        if handle:
+            param = handle.flat_param
+            assert isinstance(param, flat_param_file.FlatParameter)
+            global_fqns = [
+                clean_tensor_name(prefix + name) for name in param._fqns
+            ]  # prefixed from the top level `model` (i.e. including `prefix`)
+
+            if prefixed_module_name in sharded_module_name_to_fqns:
+                sharded_module_name_to_fqns[prefixed_module_name].extend(global_fqns)
+            else:
+                sharded_module_name_to_fqns[prefixed_module_name] = global_fqns
+
+    def return_fn(sharded_tree_info, sharded_module_name_to_fqns):
+        return sharded_tree_info[0], sharded_module_name_to_fqns
+
+    # Use List to mutate its value in place while running the recursive functions
+    sharded_tree_info: List[str] = [
+        "",
+    ]
+    sharded_module_name_to_fqns: Dict[str, List[str]] = {}
+    return _apply_to_modules(
+        model,
+        module_fn,
+        return_fn,
+        [key for key, _ in model.named_parameters()],
+        sharded_tree_info,
+        sharded_module_name_to_fqns,
+    )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_dynamo_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_dynamo_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..e58c91a5807b9e3d1807d095b7a6409cf818f737
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_dynamo_utils.py
@@ -0,0 +1,46 @@
+# mypy: allow-untyped-defs
+from typing import Set
+
+import torch.nn as nn
+
+
+def _annotate_modules_for_dynamo(
+    module: nn.Module,
+    ignored_modules: Set[nn.Module],
+    use_orig_params: bool,
+):
+    """
+    Annotates the submodules in ``module`` 's tree, except those in
+    ``ignored_modules``, indicating that the submodules are FSDP-managed and
+    saving the ``use_orig_params`` setting passed to the FSDP constructor.
+    """
+    for submodule in module.modules():
+        if submodule not in ignored_modules:
+            """[note: Dynamo treats FSDP wrapped modules as UnspecializedNNModule]
+
+            Dynamo doesn't get to see this instance (FullyShardedDataParallel) during tracing, since
+            it skips tracing all the torch.distributed.fsdp code.
+                - Why? Running the FSDP code eagerly avoids lots of issues trying to trace complex hooks, and also
+                gets us graph-breaks on FSDP module boundaries which we want anyway for comm ops.
+                - However, we _also_ want dynamo to treat the wrapped module inside FSDP 'unspecially' (*),
+                and we need a way to indicate to dynamo which modules are wrapped by FSDP.
+
+            (*) UnspecializedNNModules in dynamo are traced-through without any assumptions, and with thorough
+            guards.  NNModules otherwise are 'specialized', meaning there is less overhead due to assuming
+            their code is well-behaved.
+
+            One particular issue with specialized NNModules for FSDP is that the
+            views created for orig_params are captured into the compiled graph on the first iteration, and while
+            they are always going to point to the correct flatparameter and give correct results, their order
+            of creation influences the order of backward execution, preventing overlap of comm and computation
+            during backward.  We need to _use_ the new parameter views created on each forward iteration, in
+            order for backward to interleave hooks with compute per layer.  UnspecializedNNModule lets us achieve
+            this by capturing the module code more 'functionally' and passing parameters in as inputs each time.
+            """
+            submodule._is_fsdp_managed_module = True  # type: ignore[assignment]
+
+            # Dynamo only supports FSDP with use_orig_params=True.
+            # This is hacky, but I could not think of another way to add an assertion to dynamo
+            # for this, since Dynamo skips all the FSDP code frames and thus can't inspect the
+            # FSDP module directly
+            submodule._fsdp_use_orig_params = use_orig_params  # type: ignore[assignment]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_exec_order_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_exec_order_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad5fdc1fde5f09d4ffec06ba222b155744dcd3dd
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_exec_order_utils.py
@@ -0,0 +1,365 @@
+# mypy: allow-untyped-defs
+import itertools
+import warnings
+from enum import auto, Enum
+from typing import Dict, List, Optional, Tuple, Union
+
+import torch
+import torch.distributed as dist
+import torch.distributed.fsdp._traversal_utils as traversal_utils
+import torch.nn as nn
+from torch.distributed.fsdp._common_utils import _FSDPState, _get_param_to_fqns
+from torch.distributed.fsdp._flat_param import FlatParamHandle
+
+
+class _ExecOrderWarnStatus(Enum):
+    """Used internally for execution order validation."""
+
+    NONE = auto()  # no deviation yet
+    WARNING = auto()  # deviated this iteration; currently issuing warnings
+    WARNED = auto()  # deviated in a previous iteration
+
+
+class _ExecOrderData:
+    """
+    This contains the data structures to track the execution order. We track
+    the pre-forward order on the *first* iteration for forward prefetching
+    (which thus assumes static graph) and the post-forward order on *every*
+    iteration for backward prefetching (which thus does not assume static
+    graph but may be provide an incorrect order).
+    """
+
+    def __init__(
+        self,
+        debug_level: dist.DebugLevel,
+        backward_prefetch_limit: int,
+        forward_prefetch_limit: int,
+    ) -> None:
+        # Tracks the (static) pre-forward order for execution order validation
+        # and forward prefetching
+        self.handles_pre_forward_order: List[FlatParamHandle] = []
+        # Tracks the post-forward order for pre-backward prefetching
+        self.handles_post_forward_order: List[Optional[FlatParamHandle]] = []
+        self._iter = 0
+
+        # Gives the max number of backward/forward prefetched all-gathers by a
+        # single module
+        self._backward_prefetch_limit = backward_prefetch_limit
+        self._forward_prefetch_limit = forward_prefetch_limit
+
+        # Data structures for execution order validation
+        self._checking_order: bool = debug_level == dist.DebugLevel.DETAIL
+        self.process_group: Optional[dist.ProcessGroup] = None
+        self.world_size: Optional[int] = None
+        self.all_handles: List[FlatParamHandle] = []
+        # Names are prefixed from the root module
+        self.param_to_fqn: Dict[nn.Parameter, List[str]] = {}
+        # Current index in the pre-forward execution order
+        self.current_order_index = 0
+        self.warn_status = _ExecOrderWarnStatus.NONE
+
+    def init(
+        self,
+        state: _FSDPState,
+        root_module: nn.Module,
+        process_group: dist.ProcessGroup,
+    ) -> None:
+        """
+        Initializes the data structures needed for checking the forward order.
+        This should be called after a root FSDP instance has been set during
+        lazy initialization.
+        """
+        self.process_group = process_group
+        self.rank = process_group.rank()
+        self.world_size = process_group.size()
+        # Fix an order over the handles, which should be the same across ranks
+        for handle in traversal_utils._get_fsdp_handles(root_module):
+            index = len(self.all_handles)
+            self.all_handles.append(handle)
+            handle._handle_index = index
+        self.param_to_fqn = _get_param_to_fqns(root_module)
+        # TODO (awgu): We can broadcast the metadata of rank 0's `all_handles`
+        # to check that all ranks have the same handles in the same order.
+        # https://github.com/pytorch/pytorch/issues/79620
+
+    @property
+    def is_first_iter(self) -> bool:
+        return self._iter == 0
+
+    def get_handle_to_backward_prefetch(
+        self,
+        current_handle: FlatParamHandle,
+    ) -> Optional[FlatParamHandle]:
+        """
+        Returns a :class:`list` of the handles keys of the handles to backward
+        prefetch given the current handles key. If there are no valid handles
+        keys to prefetch, then this returns an empty :class:`list`.
+        """
+        current_index = current_handle._post_forward_index
+        if current_index is None:
+            return None
+        target_index = current_index - 1
+        target_handle: Optional[FlatParamHandle] = None
+        for _ in range(self._backward_prefetch_limit):
+            if target_index < 0:
+                break
+            target_handle = self.handles_post_forward_order[target_index]
+            target_index -= 1
+        return target_handle
+
+    def get_handle_to_forward_prefetch(
+        self,
+        current_handle: FlatParamHandle,
+    ) -> Optional[FlatParamHandle]:
+        """
+        Returns a :class:`list` of the handles keys of the handles to forward
+        prefetch given the current handles key. If there are no valid handles
+        keys to prefetch, then this returns an empty :class:`list`.
+        """
+        current_index = current_handle._pre_forward_order_index
+        if current_index is None:
+            return None
+        target_index = current_index + 1
+        target_handle: Optional[FlatParamHandle] = None
+        for _ in range(self._forward_prefetch_limit):
+            if target_index >= len(self.handles_pre_forward_order):
+                break
+            target_handle = self.handles_pre_forward_order[target_index]
+            target_index += 1
+        return target_handle
+
+    def record_post_forward(self, handle: Optional[FlatParamHandle]) -> None:
+        """
+        Records ``handles`` in the post-forward order, where ``handles`` should
+        be a group of handles used in the same module's forward. If ``handles``
+        is empty, then it is omitted.
+
+        Unlike :meth:`record_pre_forward`, this records the order *every*
+        iteration with the expectation that the recorded order is reset in
+        :meth:`next_iter`.
+        """
+        if not handle:
+            return
+        # Only record the first usage of a handles key
+        if handle._post_forward_index:
+            self.handles_post_forward_order.append(handle)
+            return
+        index = len(self.handles_post_forward_order)
+        handle._post_forward_index = index
+        self.handles_post_forward_order.append(handle)
+
+    def record_pre_forward(
+        self, handle: Optional[FlatParamHandle], is_training: bool
+    ) -> None:
+        """
+        Records ``handles`` in the pre-forward order, where ``handles`` should
+        be a group of handles used in the same module's forward. If ``handles``
+        is empty, then it is omitted.
+
+        On the first iteration, this checks the execution order across ranks.
+        See :meth:`_check_order` for details.
+        """
+        if not handle:
+            return
+        self._check_order(handle, is_training)
+        # Fix the order after the first iteration and only record the first
+        # usage of a handles key
+        if not self.is_first_iter or handle._pre_forward_order_index is not None:
+            return
+        index = len(self.handles_pre_forward_order)
+        handle._pre_forward_order_index = index
+        self.handles_pre_forward_order.append(handle)
+
+    def _check_order(self, handle: FlatParamHandle, is_training: bool) -> None:
+        """
+        Checks the forward execution order as long as ``is_training`` is
+        ``True`` since checking in eval mode is not supported. This only checks
+        if the distributed debug level is DETAIL.
+
+        - On the first iteration, this uses all-gathers to check that all ranks
+        are all-gathering the same handles and hence ``FlatParameter`` s,
+        raising an error if not.
+        - On subsequent iterations, this checks that each rank is locally
+        consistent with its own forward order from the first iteration, issuing
+        a warning if not. This issues a warning on the first deviating
+        iteration and stops warning thereafter.
+        """
+        # Do not check order in eval mode since the post-backward callback does
+        # not run so it cannot be used to mark the end of an iteration
+        if not is_training or not self._checking_order:
+            return
+        if self.is_first_iter:
+            msg_prefix = "Forward order differs across ranks:"
+            optional_local_indices: Tuple[
+                Optional[int], ...
+            ] = self._get_handle_indices(handle)
+            device = handle.device  # guaranteed to be non-CPU
+            num_valid_indices = sum(
+                (index is not None) for index in optional_local_indices
+            )
+            tensor_kwargs: Dict[str, Union[torch.dtype, torch.device]] = {
+                "dtype": torch.int32,
+                "device": device,
+            }
+            world_num_valid_indices = torch.zeros(self.world_size, **tensor_kwargs)  # type: ignore[arg-type, call-overload]
+            local_num_valid_indices = torch.tensor([num_valid_indices], **tensor_kwargs)  # type: ignore[arg-type, call-overload]
+            dist.all_gather_into_tensor(
+                world_num_valid_indices,
+                local_num_valid_indices,
+                group=self.process_group,
+            )
+            # Copy entire tensor from D2H once to avoid per element D2H copies
+            world_num_valid_indices = world_num_valid_indices.cpu()
+            # Check that all ranks plan to all-gather the same number of
+            # parameters
+            # TODO (awgu): Since every module has at most one handle in the
+            # current implementation, this should never raise the error.
+            assert self.world_size is not None  # mypy
+            if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
+                # TODO(voz): Don't graph break on this - dynamo hates the n1 != n2
+                # tensor comparison control flow.
+                # https://github.com/pytorch/pytorch/issues/107055
+                for (r1, n1), (r2, n2) in itertools.combinations(
+                    (
+                        (rank, world_num_valid_indices[rank])
+                        for rank in range(self.world_size)
+                    ),
+                    2,
+                ):
+                    if n1 != n2:
+                        raise RuntimeError(
+                            f"{msg_prefix} rank {r1} is all-gathering {n1} parameters "
+                            f"while rank {r2} is all-gathering {n2} parameters"
+                        )
+            world_indices = torch.zeros(  # type: ignore[call-overload]
+                self.world_size * num_valid_indices, **tensor_kwargs
+            )
+            local_indices = torch.tensor(optional_local_indices, **tensor_kwargs)  # type: ignore[arg-type]
+            dist.all_gather_into_tensor(
+                world_indices, local_indices, group=self.process_group
+            )
+            # Copy entire tensor from D2H once to avoid per element D2H copies
+            world_indices = world_indices.cpu()
+            # Check that all ranks plan to all-gather the same index parameters
+            if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
+                # TODO(voz): Don't graph break on this - dynamo hates the i1 != i2
+                # tensor comparison control flow.
+                # https://github.com/pytorch/pytorch/issues/107055
+                for (r1, i1), (r2, i2) in itertools.combinations(
+                    (
+                        (
+                            rank,
+                            world_indices[
+                                rank
+                                * num_valid_indices : (rank + 1)
+                                * num_valid_indices
+                            ],
+                        )
+                        for rank in range(self.world_size)
+                    ),
+                    2,
+                ):
+                    if i1 != i2:
+                        r1_param_names = self._get_names_from_handle_indices(i1)
+                        r2_param_names = self._get_names_from_handle_indices(i2)
+                        raise RuntimeError(
+                            f"{msg_prefix} rank {r1} is all-gathering parameters "
+                            f"for {r1_param_names} while rank {r2} is all-gathering "
+                            f"parameters for {r2_param_names}"
+                        )
+        else:
+            # Only issue warnings on the first deviating iteration and stop
+            # checking thereafter to avoid flooding the console
+            if self.warn_status == _ExecOrderWarnStatus.WARNED:
+                return
+            msg_prefix = None  # non-`None` means we should warn
+            if self.current_order_index >= len(self.handles_pre_forward_order):
+                # This iteration sees extra all-gather(s) compared to the first
+                msg_prefix = (
+                    "Expected to not all-gather any more parameters in the "
+                    "forward but trying to all-gather parameters for "
+                )
+            else:
+                expected_handle = self.handles_pre_forward_order[
+                    self.current_order_index
+                ]
+                if expected_handle != handle:
+                    expected_param_names = self._get_names_from_handles(expected_handle)
+                    msg_prefix = (
+                        f"Expected to all-gather for {expected_param_names} "
+                        "but trying to all-gather parameters for "
+                    )
+            if msg_prefix is not None:
+                param_names = self._get_names_from_handles(handle)
+                msg_suffix = (
+                    f"{param_names}"
+                    if param_names
+                    else "a newly-added parameter since construction time"
+                )
+                warnings.warn(
+                    "Forward order differs from that of the first iteration "
+                    f"on rank {self.rank}. Collectives are unchecked and may "
+                    f"give incorrect results or hang.\n{msg_prefix}{msg_suffix}"
+                )
+                self.warn_status = _ExecOrderWarnStatus.WARNING
+            self.current_order_index += 1
+
+    def _get_handle_indices(
+        self,
+        handle: FlatParamHandle,
+    ) -> Tuple[Optional[int], ...]:
+        """
+        Returns the handle indices (i.e. indices into ``self.all_handles``)
+        corresponding to the handles in ``handle``. An entry in the
+        returned tuple is ``None`` if the handle is invalid.
+        """
+        indices: List[Optional[int]] = []
+        if handle:
+            indices.append(handle._handle_index)
+        return tuple(indices)
+
+    def _get_names_from_handle_indices(
+        self,
+        handle_indices: Tuple[int, ...],
+    ) -> List[List[str]]:
+        """
+        Returns a list of FQNs for each handle in ``handle_indices``. If a
+        handle index is invalid, then its FQNs are omitted from the returned
+        list.
+        """
+        fqns: List[List[str]] = []
+        for index in handle_indices:
+            if index is None or index < 0 or index >= len(self.all_handles):
+                continue
+            handle = self.all_handles[index]
+            flat_param = handle.flat_param
+            fqns.append(self.param_to_fqn[flat_param])
+        return fqns
+
+    def _get_names_from_handles(
+        self,
+        handle: FlatParamHandle,
+    ) -> List[List[str]]:
+        """
+        Returns a list of FQNs for each handle in ``handles_key``. If a handle
+        is invalid, then its FQNs are omitted from the returned list.
+        """
+        fqns: List[List[str]] = []
+        if handle:
+            flat_param = handle.flat_param
+            if flat_param in self.param_to_fqn:
+                fqns.append(self.param_to_fqn[flat_param])
+        return fqns
+
+    def next_iter(self):
+        """
+        Advances the internal data structures per iteration. This should be
+        called in the post-backward callback since that marks the true end of
+        an iteration.
+        """
+        self._iter += 1
+        self.handles_post_forward_order.clear()
+        if self._checking_order:
+            self.current_order_index = 0
+            if self.warn_status == _ExecOrderWarnStatus.WARNING:
+                self.warn_status = _ExecOrderWarnStatus.WARNED
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_flat_param.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_flat_param.py
new file mode 100644
index 0000000000000000000000000000000000000000..ede7d06ec9a1de076aa3aab3017aa80738f7579d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_flat_param.py
@@ -0,0 +1,2735 @@
+# mypy: allow-untyped-defs
+import contextlib
+import functools
+import logging
+import os
+import warnings
+from enum import auto, Enum
+from itertools import accumulate, chain
+from typing import (
+    Any,
+    Callable,
+    cast,
+    Dict,
+    Generator,
+    Iterator,
+    List,
+    NamedTuple,
+    no_type_check,
+    Optional,
+    Sequence,
+    Set,
+    Tuple,
+    Union,
+)
+
+import torch
+import torch.distributed as dist
+import torch.nn as nn
+import torch.nn.functional as F
+from torch import Tensor
+from torch.distributed.fsdp._common_utils import (
+    _FSDPDeviceHandle,
+    _named_parameters_with_duplicates,
+    _no_dispatch_record_stream,
+    _set_fsdp_flattened,
+    HandleTrainingState,
+)
+from torch.distributed.utils import (
+    _alloc_storage,
+    _data_ptr_allocated,
+    _free_storage,
+    _p_assert,
+)
+from torch.nn.parameter import _ParameterMeta  # type: ignore[attr-defined]
+from torch.testing._internal.distributed.fake_pg import FakeProcessGroup
+
+from ._fsdp_extensions import (
+    _ext_post_unflatten_transform,
+    _ext_pre_flatten_transform,
+    FSDPExtensions,
+)
+
+
+__all__ = [
+    "FlatParameter",
+    "FlatParamHandle",
+    "FlatParamShardMetadata",
+    "ParamInfo",
+    "SharedParamInfo",
+    "HandleShardingStrategy",
+]
+
+logger = logging.getLogger(__name__)
+
+
+"""
+[Note: Fully Sharded Module]
+We define the "fully sharded module" to be the original ``nn.Module`` that owns
+a ``FlatParamHandle``. It is the *single* module logically responsible for the
+*single* unshard/reshard pair for the handle's ``FlatParameter`` for a given
+forward or backward pass. The fully sharded module should be passed to the
+``FlatParamHandle`` constructor.
+
+For the wrapper code path:
+- The ``FullyShardedDataParallel`` module wrapping the fully sharded module
+runs the unshard/reshard on behalf of the fully sharded module by overriding
+``nn.Module.forward``.
+- The fully sharded module is exactly the module passed to the
+``FullyShardedDataParallel`` constructor's ``module`` argument.
+
+For the non-wrapper code path:
+- Hooks registered on the fully sharded module run the unshard/reshard.
+- The fully sharded module may either be the direct argument to ``fully_shard``
+or a submodule chosen by the provided wrapping policy.
+"""
+
+# Environment variable toggling whether to use unsafe `setattr()` for view
+# setting in `_use_sharded_views()` and `_use_unsharded_views()`
+# We should use 'safe' by default since it respects method overrides, but for
+# special cases such as for high CPU overhead or for intentionally bypassing
+# checks in the overrides, we may use 'unsafe'.
+_FSDP_USE_UNSAFE_SETATTR = "FSDP_USE_UNSAFE_SETATTR"
+
+# Environment variable toggling whether to check for parameter/gradient
+# writeback in case their storages change after FSDP initialization
+# We should check by default since it prevents silent correctness errors, but
+# since such changes are atypical, we may want to skip the check to save CPU
+# overhead, especially since the check happens in the pre-forward and
+# pre-backward each iteration.
+_FSDP_SKIP_WRITEBACK_CHECK = "FSDP_SKIP_WRITEBACK_CHECK"
+
+# Env var toggling whether when model is in .eval() mode, should we run in fp32
+# or the reduced precision.
+_FSDP_USE_FULL_PREC_IN_EVAL = "FSDP_USE_FULL_PREC_IN_EVAL"
+
+# Some value to set padding in tensors to for debuggability
+_FLAT_PARAM_PADDING_VALUE = 42
+
+# Environment variables for disabling the all-gather and reduce-scatter
+# communication ops for ablation studies. Note that without these communication
+# ops the training won't converge, and you probably need to disable correctness
+# checks in your model.
+_FSDP_USE_FAKE_ALL_GATHER = "FSDP_USE_FAKE_ALL_GATHER"
+_FSDP_USE_FAKE_REDUCE = "FSDP_USE_FAKE_REDUCE"
+
+
+# TODO: Define this for now to avoid circular imports. See if we can remove.
+class HandleShardingStrategy(Enum):
+    FULL_SHARD = auto()
+    SHARD_GRAD_OP = auto()
+    NO_SHARD = auto()
+    HYBRID_SHARD = auto()
+    _HYBRID_SHARD_ZERO2 = auto()
+
+
+RESHARD_AFTER_FORWARD_HANDLE_STRATEGIES = (
+    HandleShardingStrategy.FULL_SHARD,
+    HandleShardingStrategy.HYBRID_SHARD,
+)
+NO_RESHARD_AFTER_FORWARD_HANDLE_STRATEGIES = (
+    HandleShardingStrategy.SHARD_GRAD_OP,
+    HandleShardingStrategy._HYBRID_SHARD_ZERO2,
+)
+
+
+class ParamInfo(NamedTuple):
+    """Information for an original parameter."""
+
+    param_name: str  # unprefixed
+    module: nn.Module
+    module_name: str
+
+
+class SharedParamInfo(NamedTuple):
+    """
+    Additional information for a shared parameter.
+
+    For each shared parameter, we designate one module and its parameter
+    variable to be the primary owner, determined as the first one encountered
+    in the parameter walk. These are prefixed with "prim". The primary module
+    and parameter do not have their own :class:`SharedParamInfo` instance.
+    """
+
+    param_name: str  # unprefixed
+    module: nn.Module
+    module_name: str
+    prim_param_name: str  # unprefixed
+    prim_module: nn.Module
+    prim_module_name: str
+
+
+class _ShardParamInfo(NamedTuple):
+    """Shard-related information for an original parameter."""
+
+    in_shard: bool
+    # Use to index into the sharded flat parameter, e.g.
+    # `flat_param[offset_in_shard : offset_in_shard + numel_in_shard]`
+    offset_in_shard: Optional[int]
+    numel_in_shard: Optional[int]
+    # Use to get part of the parameter in the local shard from a flattened
+    # version of the unsharded parameter, e.g.
+    # `param.flatten()[intra_param_start_idx : intra_param_end_idx + 1]`
+    intra_param_start_idx: Optional[int]
+    intra_param_end_idx: Optional[int]  # inclusive
+
+
+class FlatParamShardMetadata(NamedTuple):
+    """
+    This holds metadata specific to this rank's shard of the flat parameter.
+
+    Attributes:
+        param_names (Tuple[str, ...]): Prefixed parameter names of this rank's
+            shard of the parameters; see :class:`FlatParameter`.
+        param_shapes (Tuple[torch.Size, ...]): Parameter shapes of this rank's
+            shard of the parameters; see :class:`FlatParameter`.
+        param_numels (Tuple[int, ...]): Parameter numels of this rank's shard
+            of the parameters; see :class:`FlatParameter`.
+        param_offsets (Tuple[Tuple[int, int], ...]): [start, end] offsets (in
+            units of numels) giving this rank's part of each flattened
+            original parameter.
+    """
+
+    param_names: Tuple[str, ...]
+    param_shapes: Tuple[torch.Size, ...]
+    param_numels: Tuple[int, ...]
+    param_offsets: Tuple[Tuple[int, int], ...]
+
+
+class _FlatParameterMeta(_ParameterMeta):
+    # Make `isinstance(t, FlatParameter)` return True for custom tensor
+    # instances that have the _is_flat_param flag for BC
+    def __instancecheck__(self, instance):
+        # NB: do NOT test the super implementation
+        return isinstance(instance, torch.Tensor) and getattr(
+            instance, "_is_flat_param", False
+        )
+
+
+class FlatParameter(nn.Parameter, metaclass=_FlatParameterMeta):
+    """
+    This is the flat parameter used by :class:`FullyShardedDataParallel`.
+
+    It is comprised of one or more original parameters, which are flattened and
+    concatenated to construct the flat parameter.
+
+    Under the current design, this parameter logically represents both the
+    unsharded and sharded flat parameter, and its data changes storages
+    dynamically.
+        - In the :class:`FullyShardedDataParallel` constructor, the parameter
+        is initialized as unsharded and then sharded in-place.
+        - At runtime, the parameter is lazily (re)-initialized. The sharded
+        parameter data is saved in ``self._local_shard``, and a new ``Tensor``
+        ``self._full_param_padded`` is created, which is the all-gather
+        destination and owns the unsharded parameter storage thereafter. (See
+        :meth:`FlatParamHandle.init_flat_param_attributes`.)
+        - Throughout runtime, the parameter data changes storages as needed,
+        e.g. to the sharded flat parameter, low precision sharded flat
+        parameter, or the unsharded flat parameter.
+
+    NOTE: Since ``use_orig_params=True`` supports intra-``FlatParameter``
+    padding, we have two versions of the per-parameter numels, one that
+    includes the padding (``_numels_with_padding``) and one that does not
+    (``_numels``). The former may have length longer than the other data
+    structures, while the latter has the same length as the number of actual
+    original parameters like the other per-parameter data structures.
+
+    NOTE: This is not a real class; instead, you will always get a Parameter
+    back out if you try to create one of these.  This is similar to the trick
+    we implemented for Parameter to get it to work with subclasses; this
+    is primarily so that FlatParameter supports combination with FakeTensor.
+
+    Attributes:
+        _unpadded_unsharded_size (torch.Size): Unsharded flat parameter's size
+            without right-hand-side padding for divisibility by the world size.
+            For ``use_orig_params=True``, this includes alignment padding.
+        _padded_unsharded_size (torch.Size): Unsharded flat parameter's size
+            with right-hand-side padding for divisibility by the world size.
+            For ``use_orig_params=True``, this includes alignment padding. This
+            is only set for sharded strategies since they require padding for
+            the all-gather.
+        _sharded_size (torch.Size): Sharded flat parameter's size with padding.
+            This is also set for ``NO_SHARD``, in which case it is the same as
+            the unsharded sizes. (We omit "padded" because there is no
+            analogous unpadded one.)
+
+        _num_params (int): Number of original parameters flattened into this
+            flat parameter. This is the length of the per-parameter data
+            structures.
+        _param_infos (Tuple[ParamInfo, ...]): Each parameter's parameter info
+            entry; see :class:`ParamInfo` for details.
+        _shapes (Tuple[torch.Size, ...]): Each parameter's original shape.
+        _fqns (Tuple[str, ...]): Each parameter's fully-qualified name (FQN)
+            prefixed from the ``_fully_sharded_module``. The names are
+            guaranteed to be unique in the subtree rooted at that module.
+        _param_extensions (Tuple[Optional[Any], ...]): Each parameter's
+            extension (i.e. some per-parameter state) used to customize
+            pre-flatten and post-unflatten behavior or ``None``. This is
+            experimental, and users should not depend on its existence in the
+            future.
+        _numels_with_padding (Tuple[int, ...]): Each parameter's numel
+            including entries for the padding. This is used to construct views
+            into the flat parameter via ``torch.split()``. This may have length
+            longer than ``_num_params``.
+        _numels (Tuple[int, ...]): Each parameter's numel excluding entries for
+            padding. This has length equal to ``_num_params``.
+        _shard_param_infos (Tuple[_ShardParamInfo, ...]): Each parameter's
+            shard parameter info; see :class:`_ShardParamInfo` for details.
+        _shared_param_infos (Tuple[SharedParamInfo, ...]): Shared parameter
+            info entries; see :class:`SharedParamInfo` for details.
+        _modules (Set[nn.Module]): Modules that contain some original parameter
+            that is flattened into the flat parameter.
+
+        _shard_numel_padded (int): Numel padded for this rank's sharded flat
+            parameter.
+        _local_shard (Tensor): Sharded flat parameter with padding if using a
+            sharded strategy. If using ``NO_SHARD``, then this is the unpadded
+            unsharded flat parameter, and there is no notion of a sharded flat
+            parameter or padded unsharded flat parameter.
+        _full_param_padded (Tensor): Unsharded flat parameter with padding.
+            This is not defined for ``NO_SHARD``. When using mixed precision
+            for parameters, this has the low precision.
+        _full_prec_full_param_padded (Tensor): Full precision unsharded flat
+            parameter with padding. This is used for unsharding outside of
+            computation when using mixed precision for parameters. This is
+            never defined for ``NO_SHARD``.
+        _post_backward_hook_handle (RemovableHandle):
+            Flat parameter's post-backward hook handle. (Compile only)
+        _post_backward_hook_state (Tuple[AccumulateGrad, RemovableHandle]):
+            Flat parameter's :class:`AccumulateGrad` object and post-backward
+            hook handle. (Eager only)
+        _mp_shard (Tensor): Low precision sharded flat parameter with padding.
+            This is only defined when parameter mixed precision is enabled. For
+            ``NO_SHARD``, this is used for computation.
+        _cpu_grad (Tensor): Sharded gradient with padding stored on CPU.
+            This is only defined when offloading parameters is enabled.
+        _saved_grad_shard (Tensor): Sharded gradient with padding from previous
+            iterations for gradient accumulation without :meth:`no_sync`.
+
+        _params (Optional[List[nn.Parameter]]): If ``use_orig_params=True``,
+            then each original parameter variable; otherwise, ``None``. This
+            does not include any padding tensors.
+        _shared_params (Optional[List[nn.Parameter]]): The original shared
+            parameter variables if ``use_orig_params=True`` and ``None``
+            otherwise.
+        _tensors (Optional[List[Optional[Tensor]]]): This saves the ``Tensor``
+            views created in the forward and tracked by autograd when
+            ``use_orig_params=True`` and is ``None`` otherwise. This is to
+            preserve those ``Tensor`` variables for the backward to ensure that
+            the ``FlatParameter`` 's ``AccumulateGrad`` object does not change
+            in which case the post-backward hook does not run. This is relevant
+            for cases like reentrant activation checkpointing.
+        _is_grad_none_mask (Optional[List[bool]]): If ``use_orig_params=True``,
+            a mask over the original parameters' gradients indicating if it is
+            logically ``None`` or not; otherwise, ``None``. This does not
+            include entries for padding. This mask is needed because only some
+            of the parameters may have ``None`` gradient, in which case the
+            flat gradient must be non-``None`` and must use zeros to
+            approximate those original ``None`` gradients. This mask informs
+            FSDP to set the original parameter gradients to ``None`` (instead
+            of zeros) as needed.
+    """
+
+    _unpadded_unsharded_size: torch.Size
+    _padded_unsharded_size: torch.Size
+    _sharded_size: torch.Size
+    _num_params: int
+    _param_infos: Tuple[ParamInfo, ...]
+    _shapes: Tuple[torch.Size, ...]
+    _fqns: Tuple[str, ...]
+    _param_extensions: Tuple[Optional[Any], ...]
+    _numels_with_padding: Tuple[int, ...]
+    _numels: Tuple[int, ...]
+    _shard_param_infos: Tuple[_ShardParamInfo, ...]
+    _shared_param_infos: Tuple[SharedParamInfo, ...]
+    _modules: Set[nn.Module]
+    _shard_numel_padded: int
+    _local_shard: Tensor
+    _full_param_padded: Tensor
+    _full_prec_full_param_padded: Tensor
+    # Eager only
+    _post_backward_hook_state: Tuple[Any, Any]
+    # Compile only
+    _post_backward_hook_handle: Any
+    _mp_shard: Tensor
+    _cpu_grad: Tensor
+    _saved_grad_shard: Tensor
+    _params: Optional[List[nn.Parameter]]
+    _shared_params: Optional[List[nn.Parameter]]
+    _tensors: Optional[List[Optional[Tensor]]]
+    _is_grad_none_mask: Optional[List[bool]]
+
+    _is_padding_mask: List[bool]
+
+    def __new__(cls, data=None, requires_grad=True):
+        assert cls is FlatParameter, "subclasses FlatParameter not supported"
+        r = nn.Parameter.__new__(nn.Parameter, data, requires_grad)  # type: ignore[call-arg]
+        r._is_flat_param = True  # type: ignore[attr-defined]
+        return r
+
+    # NB: This is not a regular method, because FlatParameters are not actually
+    # instances of this class (see __new__ above).  So you must indirectly
+    # call this directly through the classmethod.
+    @classmethod
+    def _init_metadata(
+        cls,
+        self,
+        param_infos: List[ParamInfo],
+        numels: List[int],
+        shapes: List[torch.Size],
+        fqns: List[str],
+        shared_param_infos: List[SharedParamInfo],
+        param_extensions: List[Optional[Any]],
+        params: Optional[List[nn.Parameter]],
+        shared_params: Optional[List[nn.Parameter]],
+        is_padding_mask: List[bool],
+    ) -> None:
+        """
+        Initialize attributes holding metadata about the original parameters comprising the flat parameter.
+
+        We expose this method separate from the constructor to keep the
+        constructor only responsible for the flat parameter's tensor data. This
+        method should only be called once per model, while the constructor may
+        be called multiple times, e.g. when reloading from a checkpoint, in
+        which case only the tensor data needs to be passed to the constructor.
+        Since :meth:`load_state_dict` is implemented via :meth:`copy_`, the
+        metadata is correctly assumed to be unchanged.
+
+        Args:
+            See the Attributes in the class docstring.
+        """
+        assert len(param_infos) == len(shapes)
+        assert len(param_infos) == len(fqns)
+        assert len(param_infos) == len(param_extensions)
+        self._num_params = len(param_infos)
+        self._param_infos = param_infos
+        self._shapes = shapes
+        self._fqns = fqns
+        self._param_extensions = param_extensions
+        self._is_padding_mask = is_padding_mask
+
+        numels_without_padding: List[int] = []
+        for numel, is_padding in zip(numels, is_padding_mask):
+            if not is_padding:
+                numels_without_padding.append(numel)
+        self._numels = tuple(numels_without_padding)
+        self._numels_with_padding = tuple(numels)
+        assert len(self._numels) == self._num_params
+
+        self._shared_param_infos = tuple(shared_param_infos)
+        self._modules = {pi.module for pi in self._param_infos}.union(
+            {spi.module for spi in self._shared_param_infos}
+        )
+        assert (params is None) == (shared_params is None)
+        if params is not None:
+            assert shared_params is not None and len(shared_params) == len(
+                shared_param_infos
+            )
+            self._params = []
+            for param, is_padding in zip(params, is_padding_mask):
+                if not is_padding:
+                    self._params.append(param)
+            self._shared_params = shared_params
+            # Mark the original parameters to avoid flattening them into
+            # another `FlatParameter` during recursive construction
+            for param in chain(self._params, self._shared_params):
+                _set_fsdp_flattened(param)
+            self._is_grad_none_mask = [False for _ in range(self._num_params)]
+            self._tensors = [None for _ in range(self._num_params)]
+        else:
+            self._params = None
+            self._shared_params = None
+            self._is_grad_none_mask = None
+            self._tensors = None
+        self._unpadded_unsharded_size = self.size()
+        _set_fsdp_flattened(self)
+        # Tracks whether the `FlatParameter`'s post-backward hook has been
+        # called to modify the behavior of the post-backward callback
+        self._post_backward_called = False
+
+
+class FlatParamHandle:
+    """
+    A handle that manages a flat parameter (:class:`FlatParameter`).
+
+    This includes sharding and view management.
+
+    Args:
+        params (Sequence[nn.Parameter]): The parameters to flatten into the
+            flat parameter.
+        fully_sharded_module (nn.Module): See [Note: Fully Sharded Module].
+        device (torch.device): The compute and communication device, which
+            should be a non-CPU device. We refer to it as the compute device.
+        sharding_strategy (ShardingStrategy): Sharding strategy to apply to
+            this handle's ``FlatParameter``.
+        offload_params (bool): Whether to offload the handle's
+            ``FlatParameter`` to CPU.
+        mp_param_dtype (Optional[torch.dtype]): Parameter mixed precision
+            setting passed to the FSDP constructor.
+        mp_reduce_dtype (Optional[torch.dtype]): Gradient reduction mixed
+            precision setting passed to the FSDP constructor.
+        keep_low_precision_grads (bool): Whether to keep gradients in low
+            precision.
+        use_orig_params (bool): If ``True``, then FSDP preserves the original
+            parameter variables and returns them from ``named_parameters()``
+            (e.g. to support different optimizer hyperparameters within one
+            :class:`FlatParameter`). If ``False``, then FSDP reconstructs the
+            parameters every iteration and returns the :class:`FlatParameter` s
+            from ``named_parameters()``.
+    """
+
+    ##################
+    # INITIALIZATION #
+    ##################
+    def __init__(
+        self,
+        params: Sequence[Union[nn.Parameter, Tensor]],
+        fully_sharded_module: nn.Module,
+        device: torch.device,
+        sharding_strategy: HandleShardingStrategy,
+        offload_params: bool,
+        mp_param_dtype: Optional[torch.dtype],
+        mp_reduce_dtype: Optional[torch.dtype],
+        keep_low_precision_grads: bool,
+        process_group: dist.ProcessGroup,
+        use_orig_params: bool,
+        *,
+        fsdp_extension: Optional[FSDPExtensions] = None,
+    ):
+        super().__init__()
+        params = list(params)
+        if len(params) == 0:
+            raise ValueError(
+                f"Cannot construct a {self.__class__.__name__} with an empty parameter list"
+            )
+        self._init_setattr_fns()
+        self._skip_writeback_check = (
+            os.environ.get(_FSDP_SKIP_WRITEBACK_CHECK, "") == "1"
+        )
+        self._use_full_prec_in_eval = (
+            os.environ.get(_FSDP_USE_FULL_PREC_IN_EVAL, "") == "1"
+        )
+        self._use_fake_all_gather = os.environ.get(_FSDP_USE_FAKE_ALL_GATHER, "") == "1"
+        self._use_fake_reduce = os.environ.get(_FSDP_USE_FAKE_REDUCE, "") == "1"
+        if self._skip_writeback_check:
+            _warn_skip_writeback_check(
+                logger,
+                f"Since {_FSDP_SKIP_WRITEBACK_CHECK}=1, FSDP will not check "
+                "for parameter or gradient writeback. Changing parameter or "
+                "gradient storages may lead to silent correctness errors.",
+            )
+        if self._use_fake_all_gather:
+            _warn_use_fake_all_gather(
+                logger,
+                f"Since {_FSDP_USE_FAKE_ALL_GATHER}=1, FSDP will not execute "
+                "all-gather ops. Your training will be incorrect, but "
+                "can reveal how much time spent on all-gather ops.",
+            )
+        if self._use_fake_reduce:
+            _warn_use_fake_reduce(
+                logger,
+                f"Since {_FSDP_USE_FAKE_REDUCE}=1, FSDP will not execute "
+                "reduce-scatter ops. Your training will be incorrect, but "
+                "can reveal how much time spent on reduce-scatter ops.",
+            )
+        # Only align addresses for `use_orig_params=True` (for now)
+        align_addresses = use_orig_params
+        self._init_get_unflat_views_fn(align_addresses)
+        self.device = device
+        self._device_handle = _FSDPDeviceHandle.from_device(self.device)
+        self.process_group = process_group
+        if self._use_fake_all_gather or self._use_fake_reduce:
+            self._fake_process_group = FakeProcessGroup(
+                rank=process_group.rank(), world_size=process_group.size()
+            )
+        self.rank = process_group.rank()
+        self.world_size = process_group.size()
+        self._sharding_strategy = sharding_strategy
+        self._offload_params = offload_params
+        self._use_orig_params = use_orig_params
+        self._keep_low_precision_grads = keep_low_precision_grads
+        self._training_state = HandleTrainingState.IDLE
+        self._debug_level = dist.get_debug_level()
+        self._fully_sharded_module = fully_sharded_module
+        # For strategies that do not free after forward, we skip using sharded
+        # views after forward since the unsharded data exists. We still switch
+        # `self.flat_param` to point to the sharded flat parameter since what
+        # it points to parameterizes behavior. We use the following attribute
+        # to track which tensor data the parameters are unsharded views into.
+        self._unsharded_flat_param_for_skipped_views: Optional[Tensor] = None
+        # The index in the state's `all_handles`, which must be the
+        # same across ranks for the execution order validation to work
+        self._handle_index: Optional[int] = None
+        # Index in handles_to_pre_forward_order
+        self._pre_forward_order_index: Optional[int] = None
+        # Index in `handles_post_forward_order`
+        self._post_forward_index: Optional[int] = None
+        # Used for guarding against mistargeted forward prefetches
+        self._needs_pre_forward_unshard = False
+        # Used for guarding against mistargeted backward prefetches
+        self._needs_pre_backward_unshard = False
+        # Was the handle prefetched? Set on successful _prefetch_handle and unshard
+        self._prefetched = False
+        # Optimistically assume a valid input `params` and set dtype attributes
+        # before `_init_flat_param()`, which performs the actual validation
+        self._orig_param_dtype = params[0].dtype
+        self._init_param_reduce_dtypes(mp_param_dtype, mp_reduce_dtype)
+        assert self._fwd_bwd_param_dtype is not None  # mypy
+        self._aligned_numel = (
+            _get_aligned_numel(unsharded_dtype=self._fwd_bwd_param_dtype)
+            if align_addresses
+            else 0
+        )
+        self._fsdp_extension = fsdp_extension
+        self._init_flat_param_and_metadata(
+            params, fully_sharded_module, self._aligned_numel, use_orig_params  # type: ignore[arg-type]
+        )
+        self._use_unsharded_views(as_params=False)
+
+    def _init_setattr_fns(self):
+        use_unsafe_setattr = os.environ.get(_FSDP_USE_UNSAFE_SETATTR, "") == "1"
+        self._setattr_tensor: Callable[[nn.Module, str, Tensor], None]
+        self._setattr_param: Callable[[nn.Module, str, nn.Parameter], None]
+        if use_unsafe_setattr:
+            self._setattr_tensor = _unsafe_setattr_tensor
+            self._setattr_param = _unsafe_setattr_param
+        else:
+            self._setattr_tensor = _safe_setattr_tensor_or_param
+            self._setattr_param = _safe_setattr_tensor_or_param
+
+    def _init_get_unflat_views_fn(self, align_addresses: bool):
+        self._get_unflat_views = (
+            self._get_unflat_views_aligned
+            if align_addresses
+            else self._get_unflat_views_unaligned
+        )
+
+    def _init_flat_param_and_metadata(
+        self,
+        params: List[Union[Tensor, nn.Parameter]],
+        module: nn.Module,
+        aligned_numel: int,
+        use_orig_params: bool,
+    ) -> None:
+        """
+        Initialize the ``FlatParameter`` and its metadata.
+
+        NOTE: This should only be called once at construction time, after which
+        the ``FlatParameter`` metadata is assumed to be static.
+
+        NOTE: The elements of ``params`` should only be ``Tensor`` s when
+        composing with ``DTensor`` -based tensor parallelism, in which case the
+        elements may be ``DTensor`` local shards.
+        """
+        if len(params) == 0:
+            raise ValueError("Expects non-empty `params`")
+        if aligned_numel < 0:
+            raise ValueError(
+                f"Expects non-negative `aligned_numel` but got {aligned_numel}"
+            )
+        (
+            dtype,
+            flat_param_requires_grad,
+            device,
+        ) = self._validate_tensors_to_flatten(params)
+        params_set = set(params)
+        # For alignment padding, only `numels` gets strictly non-`None`
+        # elements, and all other lists get `None` elements for padding.
+        param_infos: List[ParamInfo] = []
+        numels: List[int] = []
+        shapes: List[torch.Size] = []
+        fqns: List[str] = []
+        shared_param_infos: List[SharedParamInfo] = []
+        shared_param_memo: Dict[
+            Union[Tensor, nn.Parameter], Tuple[nn.Module, str, str]
+        ] = {}
+        params_to_flatten: List[Union[Tensor, nn.Parameter]] = []
+        shared_params: List[Union[Tensor, nn.Parameter]] = []
+        param_extensions: List[Any] = []
+        is_padding_mask: List[bool] = []
+        total_numel = total_numel_without_padding = 0
+        for submodule_name, submodule in module.named_modules(remove_duplicate=False):
+            for param_name, param in _named_parameters_with_duplicates(
+                submodule, recurse=False
+            ):
+                if param not in params_set:
+                    continue
+                if param in shared_param_memo:  # shared reference
+                    prim_module, prim_module_name, prim_param_name = shared_param_memo[
+                        param
+                    ]
+                    shared_params.append(param)
+                    shared_param_infos.append(
+                        SharedParamInfo(
+                            param_name,
+                            submodule,
+                            submodule_name,
+                            prim_param_name,
+                            prim_module,
+                            prim_module_name,
+                        )
+                    )
+                else:
+                    if aligned_numel > 0:
+                        numel_to_pad = aligned_numel - (total_numel % aligned_numel)
+                        if numel_to_pad > 0 and numel_to_pad < aligned_numel:
+                            padding_tensor = _construct_padding_tensor(
+                                numel_to_pad, dtype, False, device
+                            )
+                            params_to_flatten.append(padding_tensor)
+                            is_padding_mask.append(True)
+                            numels.append(numel_to_pad)
+                            total_numel += numel_to_pad
+                    transform_t, extension = _ext_pre_flatten_transform(
+                        param,
+                        self._fsdp_extension,
+                    )
+                    param = cast(nn.Parameter, transform_t)
+                    param_extensions.append(extension)
+                    shared_param_memo[param] = (submodule, submodule_name, param_name)
+                    params_to_flatten.append(param)
+                    is_padding_mask.append(False)
+                    param_infos.append(ParamInfo(param_name, submodule, submodule_name))
+                    numels.append(param.numel())
+                    shapes.append(param.shape)
+                    fqn = (
+                        submodule_name + "." + param_name
+                        if submodule_name
+                        else param_name
+                    )
+                    fqns.append(fqn)
+                    total_numel += param.numel()
+                    total_numel_without_padding += param.numel()
+        if len(params_to_flatten) == 0:
+            raise ValueError(
+                f"`params` were not found in `module`'s tree"
+                f"params: {params}\nmodule: {module}"
+            )
+        if (
+            self.rank == 0
+            and aligned_numel > 0
+            and total_numel != total_numel_without_padding
+        ):
+            logger.debug(
+                "FSDP FlatParameter address alignment created "
+                "%s numel of padding (%s vs. %s)",
+                total_numel - total_numel_without_padding,
+                total_numel,
+                total_numel_without_padding,
+            )
+        if aligned_numel > 0:
+            # Pad to be divisible by world size to avoid a copy for the
+            # post-backward reduce-scatter
+            numel_to_pad = self.world_size - (total_numel % self.world_size)
+            if numel_to_pad > 0 and numel_to_pad < self.world_size:
+                if self.rank == 0:
+                    logger.info(
+                        "FSDP FlatParameter world size divisibility created "
+                        "%s numel of padding",
+                        numel_to_pad,
+                    )
+                padding_tensor = _construct_padding_tensor(
+                    numel_to_pad, dtype, False, device
+                )
+                params_to_flatten.append(padding_tensor)
+                is_padding_mask.append(True)
+                numels.append(numel_to_pad)
+                total_numel += numel_to_pad
+        # Pass `aligned_numel=0` since we already included padding tensors
+        self.flat_param: FlatParameter = self.flatten_tensors_into_flat_param(
+            params_to_flatten,
+            aligned_numel=0,
+            requires_grad=flat_param_requires_grad,
+        )
+        FlatParameter._init_metadata(
+            self.flat_param,
+            param_infos,
+            numels,
+            shapes,
+            fqns,
+            shared_param_infos,
+            param_extensions,
+            _convert_to_params(params_to_flatten) if use_orig_params else None,
+            _convert_to_params(shared_params) if use_orig_params else None,
+            is_padding_mask,
+        )
+
+    def _validate_tensors_to_flatten(
+        self, tensors: List[Union[Tensor, nn.Parameter]]
+    ) -> Tuple:
+        """Validate the tensors to flatten and returns any necessary metadata."""
+        dtype: Optional[torch.dtype] = None
+        # Return as the logical OR over each tensor's value
+        flat_param_requires_grad: Optional[bool] = None
+        device: Optional[torch.device] = None
+        # For `use_orig_params=True`, permit non-uniform `requires_grad`
+        for tensor in tensors:
+            if isinstance(tensor, FlatParameter):
+                raise ValueError("Cannot flatten a `FlatParameter`")
+            if dtype is None and not tensor.is_floating_point():
+                raise ValueError("Cannot flatten integer dtype tensors")
+            if dtype is not None and tensor.dtype != dtype:
+                raise ValueError(
+                    f"Must flatten tensors with uniform dtype but got {dtype} "
+                    f"and {tensor.dtype}"
+                )
+            if (
+                not self._use_orig_params
+                and flat_param_requires_grad is not None
+                and tensor.requires_grad != flat_param_requires_grad
+            ):
+                raise ValueError(
+                    "Must flatten tensors with uniform `requires_grad` when "
+                    "`use_orig_params=False`"
+                )
+            if device is not None and tensor.device != device:
+                raise ValueError(
+                    "Must flatten tensors on the same device but got both "
+                    f"{device} and {tensor.device}"
+                )
+            dtype = tensor.dtype
+            flat_param_requires_grad = flat_param_requires_grad or tensor.requires_grad
+            device = tensor.device
+        assert flat_param_requires_grad is not None, "Requires non-empty `tensors` list"
+        return dtype, flat_param_requires_grad, device
+
+    def flatten_tensors(
+        self,
+        tensors: List[Tensor],
+        aligned_numel: int,
+    ) -> Tensor:
+        """
+        Flatten ``tensors`` into a single flat tensor.
+
+        The flattening optionally includes
+        padding if ``aligned_numel`` is greater than 0, where ``aligned_numel``
+        gives the numel required to have address alignment.
+
+        NOTE: The padding alignment algorithm must be kept in sync with
+        :meth:`_init_flat_param_metadata`. We separate the two methods because
+        the initialization happens once, whereas this method may be called
+        multiple times throughout training (e.g. for checkpointing).
+        """
+        if len(tensors) == 0:
+            raise ValueError("Expects non-empty `tensors`")
+        if aligned_numel < 0:
+            raise ValueError(
+                f"Expects non-negative `aligned_numel` but got {aligned_numel}"
+            )
+        dtype, _, device = self._validate_tensors_to_flatten(tensors)
+        flat_tensors: List[Tensor] = []
+        if aligned_numel > 0:
+            total_numel = 0
+            for tensor in tensors:
+                numel_to_pad = aligned_numel - (total_numel % aligned_numel)
+                if numel_to_pad > 0 and numel_to_pad < aligned_numel:
+                    padding_tensor = _construct_padding_tensor(
+                        numel_to_pad, dtype, False, device
+                    )
+                    flat_tensors.append(padding_tensor)
+                    total_numel += numel_to_pad
+                flat_tensors.append(torch.flatten(_detach_if_needed(tensor)))
+                total_numel += tensor.numel()
+            numel_to_pad = self.world_size - (total_numel % self.world_size)
+            if numel_to_pad > 0 and numel_to_pad < self.world_size:
+                padding_tensor = _construct_padding_tensor(
+                    numel_to_pad, dtype, False, device
+                )
+                flat_tensors.append(padding_tensor)
+                total_numel += numel_to_pad
+        else:
+            flat_tensors = [
+                torch.flatten(_detach_if_needed(tensor)) for tensor in tensors
+            ]
+        return torch.cat(flat_tensors, dim=0)
+
+    def flatten_tensors_into_flat_param(
+        self,
+        tensors: List[Tensor],
+        aligned_numel: int,
+        requires_grad: bool,
+    ) -> FlatParameter:
+        flat_param_data = self.flatten_tensors(tensors, aligned_numel)
+        return FlatParameter(flat_param_data, requires_grad=requires_grad)
+
+    def _init_param_reduce_dtypes(
+        self,
+        mp_param_dtype: Optional[torch.dtype],
+        mp_reduce_dtype: Optional[torch.dtype],
+    ) -> None:
+        """
+        Initialize param and reduce dtypes.
+
+        Precondition: ``self.flat_param`` is set. This ensures that this
+        handle's parameters have a single dtype.
+
+        Postcondition: This sets ``self._fwd_bwd_param_dtype`` and
+        ``self._reduce_dtype``. If ``mp_param_dtype`` or ``mp_reduce_dtype``
+        is ``None``, then we assume the original parameter dtype. One special
+        case is if ``mp_param_dtype`` is not ``None`` and ``mp_reduce_dtype``
+        is ``None``, in which case we assume the gradient reduction dtype
+        matches the forward/backward parameter dtype.
+        """
+        # Save whether these dtypes were specified so that we permit the
+        # parameter dtype to change up until the lazy initialization
+        self._low_prec_param_dtype_specified = mp_param_dtype is not None
+        self._low_prec_reduce_dtype_specified = mp_reduce_dtype is not None
+        if (
+            self._low_prec_param_dtype_specified
+            and not self._low_prec_reduce_dtype_specified
+        ):
+            # Special case: infer gradient reduction mixed precision
+            self._fwd_bwd_param_dtype = mp_param_dtype
+            self._reduce_dtype = self._fwd_bwd_param_dtype
+        else:
+            self._fwd_bwd_param_dtype = mp_param_dtype or self._orig_param_dtype
+            self._reduce_dtype = mp_reduce_dtype or self._orig_param_dtype
+        assert self._fwd_bwd_param_dtype is not None
+        assert self._reduce_dtype is not None
+
+    ###################################
+    # SHARD INITIALIZATION & METADATA #
+    ###################################
+    @torch.no_grad()
+    def shard(self):
+        """
+        Shard the handle's ``FlatParameter``.
+
+        This allocates new memory for
+        the sharded flat parameter and frees the unsharded flat parameter's
+        storage.
+
+        Postcondition: ``self.flat_param`` is the sharded flat parameter. Shard
+        metadata attributes are set for all sharding strategies.
+        """
+        flat_param = self.flat_param
+        if not self.uses_sharded_strategy:
+            self._init_shard_metadata(0, 0, flat_param.numel() - 1)
+        else:
+            _p_assert(
+                flat_param.storage_offset() == 0,
+                "The `FlatParameter` is not the sole occupant of its storage",
+            )
+            sharded_flat_param, numel_padded = FlatParamHandle._get_shard(
+                flat_param, self.rank, self.world_size
+            )
+            if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
+                allocated = flat_param._typed_storage()._size() > 0
+                if allocated:
+                    flat_param._typed_storage()._resize_(0)
+            flat_param.set_(sharded_flat_param)  # type: ignore[call-overload]
+            start_idx = sharded_flat_param.numel() * self.rank
+            end_idx = sharded_flat_param.numel() * (self.rank + 1) - 1  # inclusive
+            self._init_shard_metadata(numel_padded, start_idx, end_idx)
+        if self._use_orig_params:
+            self._use_sharded_views()
+
+    def _init_shard_metadata(
+        self,
+        numel_padded: int,
+        unsharded_start_idx: int,
+        unsharded_end_idx: int,
+    ) -> None:
+        """
+        Initialize shard-related metadata for this rank's shard of the flat parameter.
+
+        This includes ``_sharded_size``, ``_shard_param_infos``, and ``_shard_numel_padded``.
+
+        Args:
+            numel_padded (int): Numel padded for this rank's sharded flat
+                parameter.
+            unsharded_start_idx (int): Start index in the unsharded flat
+            parameter assigned to this rank.
+            unsharded_end_idx (int): End index (inclusive) in the unsharded
+                flat parameter assigned to this rank.
+
+        Precondition: ``self.flat_param`` 's data is the sharded flat
+        parameter.
+        """
+        flat_param = self.flat_param
+        flat_param._sharded_size = flat_param.size()  # type: ignore[attr-defined]
+        sharded_flat_param_numel = flat_param.numel()  # includes `numel_padded`
+        _p_assert(
+            unsharded_start_idx >= 0 and unsharded_start_idx <= unsharded_end_idx,
+            f"unsharded_start_idx: {unsharded_start_idx} unsharded_end_idx: {unsharded_end_idx}",
+        )
+        _p_assert(
+            numel_padded <= sharded_flat_param_numel,
+            f"numel_padded: {numel_padded} "
+            f"sharded_flat_param_numel: {sharded_flat_param_numel}",
+        )
+        shard_param_infos = self._get_shard_metadata(
+            unsharded_start_idx, unsharded_end_idx
+        )
+        assert (
+            len(shard_param_infos) == flat_param._num_params
+        ), f"Expects length {flat_param._num_params} but got {len(shard_param_infos)}"
+        flat_param._shard_param_infos = shard_param_infos  # type: ignore[attr-defined]
+        flat_param._shard_numel_padded = numel_padded  # type: ignore[attr-defined]
+
+    def _get_shard_metadata(
+        self,
+        unsharded_start_idx: int,
+        unsharded_end_idx: int,
+    ) -> Tuple[_ShardParamInfo, ...]:
+        """
+        Compute the shard metadata based on ``unsharded_start_idx`` and ``unsharded_end_idx`` (inclusive).
+
+        ``unsharded_start_idx`` and ``unsharded_end_idx`` give the interval of the
+        unsharded flat parameter specifying the shard.
+        """
+        flat_param_offsets = self._get_flat_param_offsets()
+        assert len(flat_param_offsets) == len(
+            self.flat_param._numels_with_padding
+        ), f"Expected {len(self.flat_param._numels_with_padding)} but got {len(flat_param_offsets)}"
+        shard_param_infos: List[_ShardParamInfo] = []
+        sharded_flat_param_numel = unsharded_end_idx - unsharded_start_idx + 1
+        # `unsharded_param_start_idx` and `unsharded_param_end_idx` are indices
+        # into the unsharded flat parameter (inclusive) of the given parameter
+        for i, (
+            (unsharded_param_start_idx, unsharded_param_end_idx),
+            is_padding,
+        ) in enumerate(zip(flat_param_offsets, self.flat_param._is_padding_mask)):
+            if is_padding:
+                continue
+            in_sharded_flat_param = (
+                unsharded_start_idx <= unsharded_param_end_idx
+                and unsharded_end_idx >= unsharded_param_start_idx
+            )
+            if not in_sharded_flat_param:
+                shard_param_info = _ShardParamInfo(False, None, None, None, None)
+            else:
+                if unsharded_start_idx <= unsharded_param_start_idx:
+                    # This branch can only happen once since the rank's
+                    # unsharded start index can only intersect one parameter
+                    intra_param_start_idx = 0
+                    offset_in_shard = unsharded_param_start_idx - unsharded_start_idx
+                else:
+                    intra_param_start_idx = (
+                        unsharded_start_idx - unsharded_param_start_idx
+                    )
+                    offset_in_shard = 0
+                assert (
+                    offset_in_shard >= 0 and offset_in_shard < sharded_flat_param_numel
+                ), (
+                    f"Invalid `offset_in_shard` of {offset_in_shard} for "
+                    f"sharded flat parameter with {sharded_flat_param_numel} numel"
+                )
+                intra_param_end_idx = (
+                    min(unsharded_param_end_idx, unsharded_end_idx)
+                    - unsharded_param_start_idx
+                )
+                numel_in_shard = intra_param_end_idx - intra_param_start_idx + 1
+                shard_param_info = _ShardParamInfo(
+                    True,
+                    offset_in_shard,
+                    numel_in_shard,
+                    intra_param_start_idx,
+                    intra_param_end_idx,
+                )
+            shard_param_infos.append(shard_param_info)
+        return tuple(shard_param_infos)
+
+    @staticmethod
+    def _get_unpadded_shard(
+        tensor: Tensor,
+        rank: int,
+        world_size: int,
+    ) -> Tuple[Tensor, int]:
+        """
+        Return the unpadded shard of ``tensor`` for the given ``rank`` and ``world_size``.
+
+        The returned value is a tuple of the shard of ``tensor`` without any
+        padding and the numel to pad for that shard.
+
+        If ``tensor`` is already flattened or may be viewed in the flattened
+        shape (which is true in the expected usage), then this method does not
+        allocate any new tensor memory.
+        """
+        chunks = torch.flatten(tensor).chunk(world_size)
+        if len(chunks) < (rank + 1):
+            # This rank gets an empty chunk fully padded with zeros since there
+            # are not enough chunks across ranks
+            chunk = chunks[0].new_empty(0)
+        else:
+            chunk = chunks[rank]
+        numel_to_pad = chunks[0].numel() - chunk.numel()
+        assert (
+            numel_to_pad >= 0
+        ), "Chunk's size should be at most the first chunk's size"
+        return chunk, numel_to_pad
+
+    @staticmethod
+    def _get_shard(
+        tensor: Tensor,
+        rank: int,
+        world_size: int,
+    ) -> Tuple[Tensor, int]:
+        """
+        Return the shard of ``tensor`` with padding for the given ``rank`` and ``world_size`` and the numel padded for that shard.
+
+        This method allocates new memory (via :meth:`clone`) since the
+        unsharded ``tensor`` may be deallocated after this method returns.
+        """
+        chunk, numel_to_pad = FlatParamHandle._get_unpadded_shard(
+            tensor, rank, world_size
+        )
+        shard = chunk.clone()
+        if numel_to_pad > 0:
+            shard = F.pad(shard, [0, numel_to_pad])
+        return shard, numel_to_pad
+
+    @staticmethod
+    def _get_sharded_size(tensor: Tensor, rank: int, world_size: int) -> torch.Size:
+        """
+        Return the shape of ``tensor`` after sharding including padding.
+
+        This requires ``tensor`` to have 1D shape and ensures that the returned
+        shape is 1D.
+        """
+        assert len(tensor.shape) == 1, f"{tensor.shape}"
+        unpadded_sharded_tensor, numel_to_pad = FlatParamHandle._get_unpadded_shard(
+            tensor, rank, world_size
+        )
+        unpadded_sharded_size = unpadded_sharded_tensor.size()
+        assert len(unpadded_sharded_size) == 1, f"{unpadded_sharded_size}"
+        return torch.Size([unpadded_sharded_size[0] + numel_to_pad])
+
+    def _get_flat_param_offsets(self) -> List[Tuple[int, int]]:
+        """
+        Return [start, end] offsets of each original parameter's flattened data in the unsharded flat parameter (without padding).
+
+        NOTE: The returned list includes elements for alignment padding.
+        """
+        cumulative_sum = list(accumulate(self.flat_param._numels_with_padding))
+        starts = [0] + cumulative_sum[:-1]
+        ends = [end - 1 for end in cumulative_sum]  # inclusive
+        param_offsets = list(zip(starts, ends))
+        return param_offsets
+
+    @no_type_check
+    def shard_metadata(
+        self,
+    ) -> FlatParamShardMetadata:
+        """
+        Return the shard-related metadata specific to this rank's shard of the flat parameter.
+
+        NOTE: The returned tuple does not include elements for alignment
+        padding but does account for the padding.
+        """
+        fqns_list = []
+        shapes_list = []
+        numels_list = []
+        shard_param_offsets = []
+        for fqn, shape, numel, shard_param_info in zip(
+            self.flat_param._fqns,
+            self.flat_param._shapes,
+            self.flat_param._numels,
+            self.flat_param._shard_param_infos,
+        ):
+            if not shard_param_info.in_shard:
+                continue
+            fqns_list.append(fqn)
+            shapes_list.append(shape)
+            numels_list.append(numel)
+            shard_param_offsets.append(
+                (
+                    shard_param_info.intra_param_start_idx,
+                    shard_param_info.intra_param_end_idx,
+                )
+            )
+        return FlatParamShardMetadata(
+            tuple(fqns_list),
+            tuple(shapes_list),
+            tuple(numels_list),
+            tuple(shard_param_offsets),
+        )
+
+    @no_type_check
+    @torch.no_grad()
+    def init_flat_param_attributes(self) -> None:
+        """
+        This initializes some attributes on the handle's ``FlatParameter``.
+        This should be called during lazy initialization since it requires the
+        parameter to be on the compute device if not offloading to CPU and we
+        want to give users the chance to move the parameter appropriately after
+        the FSDP constructor.
+
+        For each tensor attribute on the ``FlatParameter``, see the unshard and
+        reshard methods in this class for the allocation and free pattern.
+        """
+        flat_param = self.flat_param
+        if flat_param.dtype != self._orig_param_dtype:
+            # Entering this branch means that the user changed the parameter
+            # dtype after FSDP initialization, in which case we may need to
+            # refresh some saved dtype attributes (dtypes specified as a part
+            # of mixed precision take precedence).
+            if not self._low_prec_param_dtype_specified:
+                self._fwd_bwd_param_dtype = flat_param.dtype
+            # For `reduce_dtype`, require `param_dtype` was not specified since
+            # then we infer the `reduce_dtype` from the specified `param_dtype`
+            if (
+                not self._low_prec_reduce_dtype_specified
+                and not self._low_prec_param_dtype_specified
+            ):
+                self._reduce_dtype = flat_param.dtype
+            self._orig_param_dtype = flat_param.dtype
+        cpu_device = torch.device("cpu")
+        if self._offload_params:
+            _p_assert(
+                flat_param.device == cpu_device,
+                f"Expects the `FlatParameter` to be on CPU when parameter CPU "
+                f"offloading is enabled, not {flat_param.device}",
+            )
+        else:
+            self._check_on_compute_device(self.flat_param)
+        flat_param._local_shard = flat_param.data
+        if self._offload_params:
+            # Pin the memory for faster H2D transfer
+            flat_param._local_shard = flat_param._local_shard.pin_memory(
+                device=self.device
+            )
+            # Pre-allocate the sharded gradient on CPU to enable non-blocking
+            # D2H transfer during the backward pass
+            flat_param._cpu_grad = torch.zeros_like(
+                flat_param._local_shard, device=cpu_device
+            ).pin_memory(device=self.device)
+        if self._uses_param_mixed_precision:
+            # For parameter mixed precision, we maintain a low precision
+            # sharded tensor on the compute device to be all-gathered (for
+            # sharded strategies) or directly used (for `NO_SHARD`) for
+            # computation.
+            flat_param._mp_shard = torch.empty_like(
+                flat_param._local_shard,
+                device=self.device,
+                dtype=self._fwd_bwd_param_dtype,
+            )
+            _free_storage(flat_param._mp_shard)
+        if self.uses_sharded_strategy:
+            # We maintain a padded unsharded tensor that serves as the
+            # all-gather destination and owns the original parameter storages.
+            unsharded_param_dtype = (
+                self._fwd_bwd_param_dtype
+                if self._uses_param_mixed_precision
+                else flat_param.dtype
+            )  # use low precision if parameter mixed precision is enabled
+            padded_unsharded_numel = flat_param.numel() * self.world_size
+            flat_param._full_param_padded = torch.empty(
+                padded_unsharded_numel,
+                device=self.device,
+                dtype=unsharded_param_dtype,
+            )
+            flat_param._padded_unsharded_size = flat_param._full_param_padded.size()
+            _free_storage(flat_param._full_param_padded)
+
+            if self._uses_param_mixed_precision:
+                # For parameter mixed precision, we maintain a full precision
+                # padded unsharded tensor for when we force full precision.
+                flat_param._full_prec_full_param_padded = torch.empty(
+                    padded_unsharded_numel,
+                    device=self.device,
+                    dtype=flat_param.dtype,  # full precision
+                )
+                _free_storage(flat_param._full_prec_full_param_padded)
+
+    ###################
+    # UNSHARD/RESHARD #
+    ###################
+    def pre_unshard(self) -> bool:
+        """
+        Return ``False`` if this is a no-op and ``True`` otherwise.
+
+        Postcondition: ``self.flat_param`` 's data is on the device for
+        communication and is what should be all-gathered. This means that it
+        matches the dtype of the expected unsharded parameter.
+        """
+        if (
+            self._training_state == HandleTrainingState.SUMMON_FULL_PARAMS
+            and self._skipped_use_sharded_views
+        ):
+            # Since this path imposes special semantics for the unsharded flat
+            # parameter (e.g. forcing full precision), use sharded views to
+            # reuse the existing logic for that special handling
+            self._use_sharded_views()
+        ret = False
+        if self._use_orig_params and not self._skip_writeback_check:
+            ret = self._writeback_orig_params()
+        if (
+            self.uses_sharded_strategy
+            and not self._offload_params
+            and not self.needs_unshard()
+        ):
+            pass  # no-op
+        elif self._uses_param_mixed_precision and not self._force_full_precision:
+            self._use_low_precision_shard()
+            ret = True
+        elif self._offload_params and self.flat_param.device != self.device:
+            # NOTE: This creates a new tensor distinct from any attributes.
+            self.flat_param_to(self.device, non_blocking=True)
+            ret = True
+        self._check_on_compute_device(self.flat_param)
+        return ret
+
+    def _use_low_precision_shard(self):
+        """Allocate on the compute device and switch to using the low precision sharded flat parameter."""
+        self._check_low_precision_shard()
+        flat_param = self.flat_param
+        _alloc_storage(
+            flat_param._mp_shard, flat_param._local_shard.size()  # type: ignore[attr-defined]
+        )
+        # `copy_()` implicitly casts to the low precision
+        flat_param._mp_shard.copy_(  # type: ignore[attr-defined]
+            flat_param._local_shard.to(  # type: ignore[attr-defined]
+                self.device, non_blocking=True
+            )
+        )
+        # Invariant: `_mp_shard` is always on the compute device.
+        flat_param.data = flat_param._mp_shard  # type: ignore[attr-defined]
+
+    def unshard(self):
+        """
+        Run the unshard logic.
+
+        This includes all-gathering the flat parameter
+        and switching to using the unsharded flat parameter. If the handle does
+        not need unsharding, then this only switches to using the unsharded
+        flat parameter. For ``NO_SHARD``, this is a no-op.
+
+        If FSDP is in :meth:`summon_full_params` and the handle uses parameter
+        mixed precision, then the parameter is forced to full precision.
+        """
+        if not self.needs_unshard():
+            # Even when not needing an unshard, we should switch to using
+            # the unsharded flat parameter
+            unsharded_flat_param = (
+                self._get_padded_unsharded_flat_param()
+                if self.uses_sharded_strategy
+                else self.flat_param
+            )
+            self._use_unsharded_flat_param(unsharded_flat_param)
+            return
+        unsharded_flat_param = self._alloc_padded_unsharded_flat_param()
+        padded_unsharded_flat_param = self._all_gather_flat_param(unsharded_flat_param)
+        self._use_unsharded_flat_param(padded_unsharded_flat_param)
+
+    def needs_unshard(self) -> bool:
+        """Return if the handle's flat parameter needs to be unsharded."""
+        if not self.uses_sharded_strategy:
+            return False
+        unsharded_flat_param = self._get_padded_unsharded_flat_param()
+        already_unsharded = _same_storage_size(
+            unsharded_flat_param, unsharded_flat_param.numel()
+        )
+        return not already_unsharded
+
+    def _alloc_padded_unsharded_flat_param(self):
+        """
+        Allocate the *padded* unsharded flat parameter.
+
+        The unpadded unsharded
+        flat parameter is always a view into the padded one. This padded
+        parameter is saved to a different attribute on the ``FlatParameter``
+        depending on if we force full precision.
+        """
+        self._check_sharded_strategy()
+        flat_param = self.flat_param
+        unsharded_flat_param = self._get_padded_unsharded_flat_param()
+        self._check_storage_freed(unsharded_flat_param)
+        _alloc_storage(unsharded_flat_param, flat_param._padded_unsharded_size)  # type: ignore[attr-defined]
+        return unsharded_flat_param
+
+    def _get_padded_unsharded_flat_param(self) -> torch.Tensor:
+        """
+        Return a reference to the padded unsharded flat parameter depending on the calling context.
+
+        This should only be called if using a sharded strategy.
+        """
+        self._check_sharded_strategy()
+        flat_param = self.flat_param
+        if self._force_full_precision and self._uses_param_mixed_precision:
+            # When parameter mixed precision is enabled, we use a different
+            # tensor as the all-gather destination to preserve the invariant
+            # that  `_full_param_padded` is in the low precision
+            unsharded_flat_param = flat_param._full_prec_full_param_padded  # type: ignore[attr-defined]
+            _p_assert(
+                unsharded_flat_param.dtype != self._fwd_bwd_param_dtype,
+                f"Expects full precision but got {self._fwd_bwd_param_dtype}",
+            )
+            # For no-reshard-after-forward strategies, `_full_param_padded` may
+            # still be allocated from a previous forward. As we are forcing
+            # full precision here, the full-precision unsharded copy may be
+            # modified, invalidating the existing low-precision unsharded copy,
+            # so we should free it here to ensure a new all-gather for the next
+            # forward/backward computation to persist the modifications.
+            if flat_param._full_param_padded.untyped_storage().size() > 0:
+                _free_storage(flat_param._full_param_padded)
+        else:
+            unsharded_flat_param = flat_param._full_param_padded  # type: ignore[attr-defined]
+        return unsharded_flat_param
+
+    def _all_gather_flat_param(
+        self,
+        padded_unsharded_flat_param: Tensor,
+    ) -> Tensor:
+        """
+        All-gather the handle's flat parameter to the destination ``padded_unsharded_flat_param``.
+
+        Then switch to use the all-gathered tensor.
+        """
+        _p_assert(
+            hasattr(self, "process_group") and hasattr(self, "world_size"),
+            "Expects a process group and world size to have been set via `shard()`",
+        )
+        sharded_flat_param = self.flat_param.data
+        expected_numel = sharded_flat_param.numel() * self.world_size
+        _p_assert(
+            padded_unsharded_flat_param.numel() == expected_numel,
+            f"Expects {expected_numel} numel but got {padded_unsharded_flat_param.numel()}",
+        )
+
+        pg = (
+            self._fake_process_group
+            if self._use_fake_all_gather
+            else self.process_group
+        )
+
+        # HACK this should be handled by C10D
+        if sharded_flat_param.is_cpu:  # type: ignore[attr-defined]
+            tensor_list = list(
+                torch.chunk(padded_unsharded_flat_param, dist.get_world_size(pg))
+            )
+            dist.all_gather(tensor_list, sharded_flat_param, group=pg)
+        else:
+            dist.all_gather_into_tensor(
+                padded_unsharded_flat_param,
+                sharded_flat_param,
+                pg,
+            )
+
+        if self._offload_params:
+            # In case of offloading, `flat_param.data` (i.e. sharded param) is
+            # created on the pre-unshard stream. We need to hand it over to the
+            # unshard stream for all-gather
+            _no_dispatch_record_stream(
+                sharded_flat_param,
+                self._device_handle.current_stream(),  # unshard_stream
+            )
+        return padded_unsharded_flat_param
+
+    def _use_unsharded_flat_param(
+        self,
+        padded_unsharded_flat_param: torch.Tensor,
+    ) -> None:
+        """
+        Switch to use the *unpadded* unsharded flat parameter.
+
+        This is a view into the *padded* unsharded flat parameter.
+        """
+        unsharded_size = self.flat_param._unpadded_unsharded_size
+        flat_param_part = padded_unsharded_flat_param[: unsharded_size.numel()]
+        # slicing [:] is not visible to autograd because of .data
+        self.flat_param.data = flat_param_part
+        in_forward = self._training_state == HandleTrainingState.FORWARD
+        in_pre_backward = self._training_state == HandleTrainingState.BACKWARD_PRE
+        if self._use_orig_params:
+            if self._skipped_use_sharded_views and in_pre_backward:
+                # This call corresponds to the complementary pre-backward
+                # `_use_unsharded_views()` to the skipped pre-forward
+                # `_use_sharded_views()`, so we should skip this one too.
+                return
+            # We use `Tensor` views in the forward so that they are tracked by
+            # autograd. We use them in the pre-backward as well to support
+            # reentrant activation checkpointing, which needs the views to be
+            # tracked by autograd in the backward pass's recomputed forward.
+            self._use_unsharded_views(
+                as_params=(not in_forward and not in_pre_backward)
+            )
+        elif in_forward:
+            self._use_unsharded_views(as_params=False)
+
+    def post_unshard(self):
+        """
+        Run the post-unshard logic.
+
+        This includes freeing the low precision shard if needed.
+        """
+        if self._uses_param_mixed_precision and self.uses_sharded_strategy:
+            self._free_low_precision_sharded_param()
+        self._check_on_compute_device(self.flat_param)
+
+    def _free_low_precision_sharded_param(self):
+        """Frees the low precision sharded flat parameter."""
+        self._check_low_precision_shard()
+        # `_mp_shard` is allocated in the pre-unshard stream, consumed in the
+        # unshard stream for sharded strategies, and consumed in both the
+        # unshard and default streams for `NO_SHARD`. For sharded strategies,
+        # the current stream here is the unshard stream, and for `NO_SHARD`,
+        # it is the default stream. For `NO_SHARD`, only recording for the
+        # default stream suffices since the default stream waits for the
+        # unshard stream.
+        _no_dispatch_record_stream(
+            self.flat_param._mp_shard, self._device_handle.current_stream()  # type: ignore[attr-defined]
+        )
+        _free_storage(self.flat_param._mp_shard)  # type: ignore[attr-defined]
+
+    @torch.no_grad()
+    def unshard_grad(self):
+        """
+        Unshard the handle's ``FlatParameter``'s gradient.
+
+        If all ranks have
+        ``None`` gradient, then all original parameters will as well. This
+        method performs an all-reduce and an all-gather. The additional
+        all-reduce is tolerable since this method is not meant to be used on
+        the computation critical path.
+
+        Postcondition: ``_saved_grad_shard`` is defined and contains the value
+        to set ``flat_param.grad`` after gradients are resharded.
+        """
+        if not self.uses_sharded_strategy:
+            self._use_unsharded_grad_views()
+            return
+        flat_param = self.flat_param
+        self._check_unsharded(flat_param)
+
+        # Check if all ranks have a `None` gradient
+        num_grad_none = torch.zeros(1, dtype=torch.int32, device=self.device)
+        num_grad_none[0] = flat_param.grad is None
+        dist.all_reduce(num_grad_none, group=self.process_group)
+        if num_grad_none[0] == self.world_size:
+            flat_param._saved_grad_shard = None  # type: ignore[assignment]
+            self._use_unsharded_grad_views()
+            return
+
+        if flat_param.grad is None:
+            # In the case that only some ranks have `None` gradient, we use
+            # zeros to approximate as a best effort attempt
+            if self._debug_level == dist.DebugLevel.INFO:
+                warnings.warn(
+                    f"[Rank {self.rank}] Only some but not all ranks have a "
+                    "`None` `FlatParameter` gradient, so FSDP is using zeros to "
+                    "approximate those ranks' sharded gradients being `None`"
+                )
+            flat_param._saved_grad_shard = None  # type: ignore[assignment]
+            sharded_grad = torch.zeros(flat_param._sharded_size, device=self.device)  # type: ignore[attr-defined]
+        else:
+            self._check_sharded(flat_param.grad)
+            flat_param._saved_grad_shard = flat_param.grad  # type: ignore[attr-defined]
+            sharded_grad = flat_param._saved_grad_shard  # type: ignore[attr-defined]
+        padded_unsharded_grad = torch.empty(
+            flat_param._padded_unsharded_size,  # type: ignore[attr-defined]
+            device=self.device,
+            dtype=sharded_grad.dtype,
+        )
+        dist.all_gather_into_tensor(
+            padded_unsharded_grad, sharded_grad, self.process_group
+        )
+        unsharded_size = self.flat_param._unpadded_unsharded_size
+        flat_param.grad = padded_unsharded_grad[: unsharded_size.numel()].view(
+            unsharded_size
+        )
+        self._use_unsharded_grad_views()
+
+    def reshard_grad(self):
+        if self._use_orig_params:
+            self._use_sharded_grad_views()
+        if not self.uses_sharded_strategy:
+            return
+        self.flat_param.grad = self.flat_param._saved_grad_shard  # type: ignore[attr-defined]
+        delattr(self.flat_param, "_saved_grad_shard")
+
+    def prepare_gradient_for_backward(self):
+        """
+        Prepare the gradient for the backward computation.
+
+        This is done by saving and clearing any existing sharded gradient
+        in ``.grad`` to enable computing a new unsharded gradient.
+        """
+        _p_assert(
+            self._training_state
+            in (HandleTrainingState.BACKWARD_PRE, HandleTrainingState.IDLE),
+            "Expects to be in `BACKWARD_PRE` or `IDLE` (if prefetching)",
+        )
+        flat_param = self.flat_param
+        if flat_param.grad is not None and (
+            flat_param.grad.size() != flat_param._unpadded_unsharded_size
+            or flat_param.grad.device != flat_param.device  # grad on CPU
+        ):
+            self._check_on_compute_device(self.flat_param)
+            grad_offloaded = flat_param.grad.device != self.device
+            _p_assert(
+                not grad_offloaded or self._offload_params,
+                f"Expects the sharded gradient to be on {self.device} "
+                f"but got {flat_param.grad.device}",
+            )
+            prev_iter_synced_gradients = (
+                flat_param.grad.size()
+                == flat_param._local_shard.size()  # type: ignore[attr-defined]
+            )
+            if prev_iter_synced_gradients:
+                # TODO (awgu): Gradient accumulation outside `no_sync()`
+                # does not work with CPU offloading. The issue should be
+                # that, in the post-backward hook, we cannot do an addition
+                # between a CPU tensor (the existing sharded gradient) and
+                # a GPU tensor (the new sharded gradient).
+                if not grad_offloaded:
+                    flat_param._saved_grad_shard = flat_param.grad.data  # type: ignore[attr-defined]
+                    sharded_grad = flat_param._saved_grad_shard  # type: ignore[attr-defined]
+                else:
+                    _p_assert(
+                        hasattr(flat_param, "_cpu_grad"),
+                        "`_cpu_grad` should be defined if the gradient is on CPU",
+                    )
+                    sharded_grad = flat_param._cpu_grad  # type: ignore[attr-defined]
+                # If user specified to keep the gradient in low precision, then
+                # the gradient may still be of the low precision dtype if the
+                # user did not set the gradient to `None` after the previous
+                # backward, in which case FSDP should cast back to the full
+                # precision dtype so that FSDP can accumulate in that dtype in
+                # the post-backward hook and assign to `.grad` in that dtype in
+                # the post-backward callback.
+                local_shard_dtype = flat_param._local_shard.dtype  # type: ignore[attr-defined]
+                if (
+                    self._keep_low_precision_grads
+                    and sharded_grad.dtype != local_shard_dtype
+                ):
+                    sharded_grad.data = sharded_grad.to(local_shard_dtype)
+            else:
+                padded_unsharded_size = flat_param._padded_unsharded_size  # type: ignore[attr-defined]
+                _p_assert(
+                    flat_param.grad.size() == padded_unsharded_size,
+                    "Expects `.grad` to be the unsharded gradient in "
+                    f"`no_sync()` with size {padded_unsharded_size} "
+                    f"but got size {flat_param.grad.size()}",
+                )
+            flat_param.grad = None
+
+    def prepare_gradient_for_optim(self):
+        """Prepare the gradient for optimizer computation by moving the sharded gradient to the ``.grad`` attribute."""
+
+        def cast_grad_to_param_dtype_if_needed(flat_param):
+            # TODO (rohan-varma): test for full precision with keep_low_precision_grads
+            if not self._force_full_precision and self._keep_low_precision_grads:
+                _p_assert(flat_param.grad is not None, "Unexpected None grad!")
+                if flat_param.grad.dtype != self._fwd_bwd_param_dtype:
+                    flat_param.grad.data = flat_param.grad.to(self._fwd_bwd_param_dtype)
+                    if self._use_orig_params:
+                        self._use_sharded_grad_views()
+
+        flat_param = self.flat_param
+        # TODO (awgu): We should replace these conditional checks to encode
+        # the logical intention more directly.
+        if hasattr(flat_param, "_cpu_grad"):
+            # NOTE: This branch includes `NO_SHARD`.
+            self._check_sharded(flat_param)
+            self._check_on_cpu(flat_param)
+            flat_param.grad = flat_param._cpu_grad  # type: ignore[attr-defined]
+            cast_grad_to_param_dtype_if_needed(flat_param)
+        elif hasattr(flat_param, "_saved_grad_shard"):
+            self._check_sharded(flat_param)
+            self._check_on_compute_device(flat_param)
+            if flat_param._saved_grad_shard is not None:
+                self._check_on_compute_device(flat_param._saved_grad_shard)  # type: ignore[attr-defined]
+            # If no sharded gradient was computed this iteration, then there is
+            # no need to forward `_saved_grad_shard` to `grad`
+            if flat_param._post_backward_called:  # type: ignore[attr-defined]
+                flat_param.grad = flat_param._saved_grad_shard  # type: ignore[attr-defined]
+                if flat_param.grad is not None:
+                    cast_grad_to_param_dtype_if_needed(flat_param)
+        else:
+            _p_assert(
+                not self.uses_sharded_strategy
+                or not flat_param._post_backward_called,  # type: ignore[attr-defined]
+                "All sharded parameters that received a gradient in the "
+                "post-backward should use `_saved_grad_shard`",
+            )
+        # Delete `_saved_grad_shard` since its existence indicates a previous
+        # gradient to accumulate with in the post-backward hook
+        if hasattr(flat_param, "_saved_grad_shard"):
+            delattr(flat_param, "_saved_grad_shard")
+
+    @contextlib.contextmanager
+    def to_cpu(self):
+        """
+        Move the unpadded unsharded flat parameter to CPU while in the context and moves it back to the previous device upon exit.
+
+        For now, this assumes the ``FlatParameter`` is the unpadded unsharded flat parameter
+        since (1) there is no reason to include the padding in the copy and (2)
+        there is no use case for the sharded flat parameter.
+
+        Precondition: ``self.flat_param`` 's data is the unpadded unsharded
+        flat parameter on the compute device, and the handle uses a sharded
+        strategy.
+        Postcondition: Same as the precondition.
+        """
+        self._check_sharded_strategy()
+        _p_assert(
+            self.flat_param.size() == self.flat_param._unpadded_unsharded_size,
+            f"Expects size {self.flat_param._unpadded_unsharded_size} but got {self.flat_param.size()}",
+        )
+        self._check_on_compute_device(self.flat_param)
+        # Check that the unpadded unsharded flat parameter is a view into the
+        # padded unsharded flat parameter as expected
+        # NOTE: This check is not strictly needed for correctness but is a
+        # useful sanity check since the tensor should only be used internally.
+        _p_assert(
+            _same_storage(self.flat_param, self._get_padded_unsharded_flat_param()),
+            "Expects the unpadded parameter to be a view into the padded parameter",
+        )
+        self.flat_param_to(torch.device("cpu"))
+        self._free_unsharded_flat_param()
+        try:
+            yield
+        finally:
+            _p_assert(
+                self.flat_param.size() == self.flat_param._unpadded_unsharded_size,
+                f"Expects size {self.flat_param._unpadded_unsharded_size} but got {self.flat_param.size()}",
+            )
+            padded_unsharded_flat_param = self._alloc_padded_unsharded_flat_param()
+            # Copy from CPU to the compute device
+            padded_unsharded_flat_param[: self.flat_param.numel()].copy_(
+                self.flat_param
+            )
+            self._use_unsharded_flat_param(padded_unsharded_flat_param)
+
+    def reshard(self, free_unsharded_flat_param: bool):
+        """
+        Run the reshard logic.
+
+        This includes freeing the unsharded flat
+        parameter if ``free_unsharded_flat_param`` and switching to using the
+        sharded flat parameter. Note that this also implicitly offloads
+        the sharded flat parameter (if CPU offload is enabled) by pointing
+        it to the ``_local_shard`` attribute which resides on CPU.
+        """
+        # Switch to the sharded `FlatParameter` before freeing to prevent
+        # "use-after-free"-type bugs with external profiling tools, where for
+        # `use_orig_params=True`, the `param` does not point to valid memory
+        # when setting `param.data = ...` in `_use_sharded_views()`.
+        self._use_sharded_flat_param()
+        if free_unsharded_flat_param:
+            self._free_unsharded_flat_param()
+
+    def post_reshard(self):
+        """
+        Run the post-reshard logic.
+
+        This includes freeing any memory that
+        can now be freed given that the ``FlatParameter`` points to the full
+        precision sharded flat parameter.
+
+        Precondition: ``self.flat_param`` 's data points to the full precision
+        sharded flat parameter.
+        """
+        # For `NO_SHARD`, `_mp_shard` is not freed in the post-unshard since it
+        # is also the low precision *unsharded* flat parameter. Hence, we delay
+        # the free until the reshard.
+        if (
+            self._uses_param_mixed_precision
+            and not self.uses_sharded_strategy
+            and not self._force_full_precision  # did not use the low precision shard
+        ):
+            self._free_low_precision_sharded_param()
+
+    def _free_unsharded_flat_param(self):
+        """
+        Free the padded unsharded flat parameter. We allow this
+        function to be called even when storage is not allocated
+
+        The tensor to free depends
+        on the calling context since the unshard may have forced full
+        precision, in which case a different tensor is used.
+        """
+        self._check_sharded_strategy()
+        unsharded_flat_param = self._get_padded_unsharded_flat_param()
+        self._check_on_compute_device(unsharded_flat_param)
+        # Do not free the memory until all ops in the current stream finish
+        _no_dispatch_record_stream(
+            unsharded_flat_param, self._device_handle.current_stream()
+        )
+        _free_storage(unsharded_flat_param)
+
+    def _use_sharded_flat_param(self) -> None:
+        """Switches to using the sharded flat parameter."""
+        flat_param = self.flat_param
+        if self._use_orig_params:
+            in_forward = self._training_state == HandleTrainingState.FORWARD
+            skip_use_sharded_views = (
+                torch.is_grad_enabled()
+                and in_forward
+                and self._sharding_strategy
+                in NO_RESHARD_AFTER_FORWARD_HANDLE_STRATEGIES
+            )
+            # Only incur the extra `.data` call if needed
+            if skip_use_sharded_views:
+                unsharded_flat_param = flat_param.data
+        if self._offload_params:
+            device = flat_param._local_shard.device  # type: ignore[attr-defined]
+            _p_assert(
+                device == torch.device("cpu"),
+                f"Expects the local shard to be on CPU but got {device}",
+            )
+        flat_param.data = flat_param._local_shard  # type: ignore[attr-defined]
+        if self._use_orig_params:
+            if skip_use_sharded_views:  # type: ignore[possibly-undefined]
+                self._unsharded_flat_param_for_skipped_views = unsharded_flat_param  # type: ignore[possibly-undefined]
+            else:
+                self._use_sharded_views()
+            # For the post-forward reshard, we may try to use sharded gradient
+            # views (or unsharded gradient views if a gradient was accumulated
+            # in `no_sync()`), but for the post-backward reshard, we delay the
+            # call to after the reduce-scatter.
+            if (
+                in_forward  # type: ignore[possibly-undefined]
+                # Skip using gradient views if skipped using sharded views
+                # since exposing unsharded parameters with sharded gradients
+                # may be confusing to the user
+                and not self._skipped_use_sharded_views
+            ):
+                # TODO: Change `_unpadded_unsharded_size` if we change the
+                # gradient to be computed directly with padding.
+                accumulated_grad_in_no_sync = (
+                    flat_param.grad is not None
+                    and self.uses_sharded_strategy
+                    and flat_param.grad.shape == flat_param._unpadded_unsharded_size
+                )
+                if accumulated_grad_in_no_sync:
+                    self._use_unsharded_grad_views()
+                else:
+                    self._use_sharded_grad_views()
+
+    #########
+    # VIEWS #
+    #########
+    @no_type_check
+    def _get_unflat_views_unaligned(
+        self,
+        tensor: Optional[torch.Tensor] = None,
+    ) -> Iterator[Tensor]:
+        """
+        Return unflattened ``Tensor`` views into ``tensor``.
+
+        If `tensor`` is ``None``,  ``flat_param`` is used. The unflattening is based
+        on ``flat_param`` 's metadata.
+
+        Examples for ``tensor`` include ``flat_param.grad`` or unsharded
+        tensor optimizer state.
+        """
+        flat_param = self.flat_param
+        if tensor is None:
+            tensor = flat_param
+        views = (
+            _ext_post_unflatten_transform(
+                subtensor.view(shape),
+                param_extension,
+                self._fsdp_extension,
+            )
+            for (subtensor, shape, param_extension) in zip(
+                torch.split(tensor, flat_param._numels, dim=0),
+                flat_param._shapes,
+                flat_param._param_extensions,
+            )
+        )
+        return views
+
+    @no_type_check
+    def _get_unflat_views_aligned(
+        self,
+        tensor: Optional[Tensor] = None,
+    ) -> List[Tensor]:
+        """
+        Return unflattened ``Tensor`` views into ``tensor`` with handling for padding.
+
+        This method has the same contract as :meth:`_get_unflat_views_unaligned`
+        except it checks for ``None`` placeholders representing padding for
+        alignment, which may incur slightly more CPU overhead.
+        """
+        flat_param = self.flat_param
+        if tensor is None:
+            tensor = flat_param
+        splits: List[Tensor] = torch.split(
+            tensor, flat_param._numels_with_padding, dim=0
+        )
+        idx = 0
+        views: List[Tensor] = []
+        for split, is_padding in zip(splits, flat_param._is_padding_mask):
+            if is_padding:
+                continue
+            views.append(
+                _ext_post_unflatten_transform(
+                    split.view(flat_param._shapes[idx]),
+                    flat_param._param_extensions[idx],
+                    self._fsdp_extension,
+                )
+            )
+            idx += 1
+        return views
+
+    @no_type_check
+    @torch.enable_grad()
+    def _use_unsharded_views(self, as_params: bool) -> None:
+        """
+        Unflatten the unsharded flat parameter by setting the original parameter variables to be views into it.
+
+        Args:
+            as_params (bool): If ``True``, then registers the original
+                parameters as ``nn.Parameter`` s; if ``False``, then registers
+                the original parameters only as ``Tensor`` s. ``False`` should
+                be used during forward/backward computation and when hiding the
+                original parameters from :meth:`nn.Module.named_parameters`.
+
+        Note:
+            when prefetching for next forward, current forward may be
+            annotated with `@torch.no_grad()`
+            `@torch.enable_grad()` ensures non-empty `view.grad_fn`
+            otherwise `_post_backward_hook` will not get called
+        """
+        flat_param = self.flat_param
+        self._check_unsharded(flat_param)
+        views = self._get_unflat_views()
+        from torch.distributed.tensor import DTensor
+
+        for i, (view, (param_name, module, _)) in enumerate(
+            zip(views, flat_param._param_infos)
+        ):
+            if self._use_orig_params and as_params:
+                if type(view) is DTensor:
+                    # A `DTensor` `view` is not compatible with assigning
+                    # `param.data = view`, so we cannot preserve the parameter
+                    # variable.
+                    self._setattr_param(
+                        module,
+                        param_name,
+                        nn.Parameter(view, requires_grad=flat_param.requires_grad),
+                    )
+                    continue
+                param = self.flat_param._params[i]
+                self._setattr_param(module, param_name, param)
+                param.data = view
+            elif as_params:
+                self._setattr_param(
+                    module,
+                    param_name,
+                    nn.Parameter(view, requires_grad=flat_param.requires_grad),
+                )
+            else:  # `as_params=False`
+                param_var: Tensor = view
+                if self._use_orig_params:
+                    if self._training_state == HandleTrainingState.FORWARD:
+                        # Save the `Tensor` for the pre-backward
+                        self.flat_param._tensors[i] = view  # save for pre-backward
+                    elif self._training_state == HandleTrainingState.BACKWARD_PRE:
+                        # Use the saved `Tensor` variable from the forward to
+                        # preserve the autograd graph so that the post-backward
+                        # hook fires (e.g. for reentrant AC)
+                        tensor = self.flat_param._tensors[i]
+                        tensor.data = view
+                        param_var = tensor
+                self._setattr_tensor(module, param_name, param_var)
+                if (
+                    self._use_orig_params
+                    and self._training_state == HandleTrainingState.FORWARD
+                ):
+                    module._parameters[param_name] = param_var
+        for i, (
+            param_name,
+            module,
+            _,
+            prim_param_name,
+            prim_module,
+            _,
+        ) in enumerate(self.flat_param._shared_param_infos):
+            prim_param: Union[Tensor, nn.Parameter] = getattr(
+                prim_module, prim_param_name
+            )
+            _p_assert(
+                not as_params or isinstance(prim_param, nn.Parameter),
+                f"as_params={as_params} type(prim_param)={type(prim_param)}",
+            )
+            if self._use_orig_params and as_params:
+                shared_param = self.flat_param._shared_params[i]
+                self._setattr_param(module, param_name, shared_param)
+                shared_param.data = prim_param
+            elif as_params:
+                self._setattr_param(module, param_name, prim_param)
+            else:
+                self._setattr_tensor(module, param_name, prim_param)
+                if (
+                    self._use_orig_params
+                    and self._training_state == HandleTrainingState.FORWARD
+                ):
+                    module._parameters[param_name] = prim_param
+
+    @no_type_check
+    def _use_unsharded_grad_views(self) -> None:
+        """
+        Unflatten the unsharded flat parameter's gradient.
+
+        The original parameter variables' gradients are set to be views into
+        the unsharded flat parameter's gradient.
+        """
+        # Expects the gradient to be in `flat_param.grad`
+        if self.flat_param.grad is None:
+            for param in chain(self.flat_param._params, self.flat_param._shared_params):
+                param.grad = None
+            return
+        self._check_unsharded(self.flat_param.grad)
+        views = self._get_unflat_views(self.flat_param.grad)
+        for i, (view, (param_name, module, _)) in enumerate(
+            zip(views, self.flat_param._param_infos)
+        ):
+            _p_assert(
+                hasattr(module, param_name),
+                f"{self.flat_param._fqns[i]} is missing",
+            )
+            param = getattr(module, param_name)
+            if (
+                param.shape != view.shape
+                or param.dtype != view.dtype
+                or param.device != view.device
+            ):
+                # NOTE: This is a hack using `.data` to side step the check
+                # that parameter/gradient sizes/dtypes/devices match. From
+                # calling `reshard()`, `param` has the sharded size, has the
+                # full precision dtype, and if CPU offloading is enabled, is on
+                # CPU. Thus, one or more of the following cases can hold when
+                # in `no_sync()`, where `view` is the original parameter's
+                # gradient:
+                # 1. `view` can have the unsharded size.
+                # 2. `view` can have the parameter low precision dtype.
+                # 3. `view` can be on GPU.
+                if param.grad is None:
+                    param.grad = torch.empty_like(param)
+                param.grad.data = view
+            else:
+                param.grad = view
+        for i, (
+            param_name,
+            module,
+            module_name,
+            prim_param_name,
+            prim_module,
+            _,
+        ) in enumerate(self.flat_param._shared_param_infos):
+            _p_assert(
+                hasattr(module, param_name),
+                f"{module_name + '.' + param_name if module_name else param_name} is missing",
+            )  # did not save FQN info in `_shared_param_infos`
+            param = getattr(module, param_name)
+            prim_param = getattr(prim_module, prim_param_name)
+            if (
+                param.shape != prim_param.grad.shape
+                or param.dtype != prim_param.grad.dtype
+                or param.device != prim_param.grad.device
+            ):
+                # NOTE: This is the same hack to use `.data` to side step the
+                # size check.
+                if param.grad is None:
+                    param.grad = torch.empty_like(param)
+                param.grad.data = prim_param.grad
+            else:
+                param.grad = prim_param.grad
+
+    @contextlib.contextmanager
+    def unflatten_as_params(self) -> Generator:
+        """
+        Unflatten the original parameters.
+
+        The function assumes that the flat parameter is unsharded. When in the context,
+        unflattens the original parameters as ``nn.Parameter`` views into the
+        flat parameter, and after the context, restores the original parameters
+        as ``Tensor`` views into the flat parameter.
+        """
+        self._use_unsharded_views(as_params=True)
+        try:
+            yield
+        finally:
+            self._use_unsharded_views(as_params=False)
+
+    @no_type_check
+    @torch.no_grad()
+    def _use_sharded_views(self) -> None:
+        """
+        Set the original parameter variables' data to be flattened views into the sharded flat parameter.
+
+        The views are kept as flattened to simplify the case where a parameter
+        is sharded across ranks. Parameters whose data is not present in the
+        sharded flat parameter have their data set to a size-0 empty tensor. We
+        do not delete them to ensure to preserve expected behaviors like model
+        printability. Parameters whose data is present must preserve their
+        variables to be passable to an optimizer.
+        """
+        self._unsharded_flat_param_for_skipped_views = None
+        if not self.uses_sharded_strategy:
+            # For `NO_SHARD`, use the *unflattened* unsharded views since we
+            # have the unsharded parameter
+            self._use_unsharded_views(as_params=True)
+            return
+        flat_param = self.flat_param
+        self._check_sharded(flat_param)
+        # Construct once and reuse for all parameters not in the local shard
+        size_0_empty_tensor = torch.empty(
+            0,
+            dtype=self.flat_param.dtype,  # in case `flat_param` changed dtype
+            device=self.flat_param.device,
+            requires_grad=False,
+        )
+        for param, shard_param_info, (param_name, module, _) in zip(
+            flat_param._params, flat_param._shard_param_infos, flat_param._param_infos
+        ):
+            self._setattr_param(module, param_name, param)
+            if not shard_param_info.in_shard:
+                # Allow the original data to be freed via garbage collection
+                param.data = size_0_empty_tensor
+            else:
+                offset = shard_param_info.offset_in_shard
+                numel_in_shard = shard_param_info.numel_in_shard
+                param.data = flat_param[offset : offset + numel_in_shard]
+        assert self.flat_param._shared_params is not None
+        for i, (
+            param,
+            (param_name, module, _, prim_param_name, prim_module, _),
+        ) in enumerate(
+            zip(self.flat_param._shared_params, self.flat_param._shared_param_infos)
+        ):
+            self._setattr_param(module, param_name, param)
+            prim_param = getattr(prim_module, prim_param_name)
+            param.data = prim_param  # could be both empty and non-empty
+        if self._training_state == HandleTrainingState.BACKWARD_POST:
+            # Clear the saved `Tensor`s since they are unneeded now
+            for i in range(len(self.flat_param._tensors)):
+                self.flat_param._tensors[i] = None
+
+    @no_type_check
+    @torch.no_grad()
+    def _use_sharded_grad_views(self) -> None:
+        """
+        Set the original parameter variables' gradients to be flattened views into the sharded flat parameter's gradient.
+
+        This is a no-op if there is no gradient.
+
+        Parameters whose data is not present in the sharded flat parameter and
+        parameters with ``requires_grad=False`` have their gradients set to
+        ``None``. Since the gradient variables do not need to be preserved,
+        this method does not manipulate existing ``Tensor`` data directly and
+        creates new ``Tensor`` variables instead.
+        """
+        flat_param = self.flat_param
+        self._check_sharded(flat_param)
+        grad = self.sharded_grad
+        if grad is None:
+            for param in chain(flat_param._params, flat_param._shared_params):
+                param.grad = None
+            return
+        self._check_sharded(grad)
+        for param, shard_param_info, is_grad_none in zip(
+            flat_param._params,
+            flat_param._shard_param_infos,
+            flat_param._is_grad_none_mask,
+        ):
+            if not shard_param_info.in_shard:
+                param.grad = None
+            else:
+                numel_in_shard = shard_param_info.numel_in_shard
+                if param.requires_grad and not is_grad_none:
+                    offset = shard_param_info.offset_in_shard
+                    if self._keep_low_precision_grads or param.dtype != grad.dtype:
+                        # NOTE: This is a hack using `.data` to side step the
+                        # check that parameter/gradient dtypes match. Here,
+                        # `param` has full precision; `grad` has low precision.
+                        if param.grad is None:
+                            # `.grad` must have the same shape as `param`
+                            param.grad = torch.empty_like(param)
+                        param.grad.data = grad[
+                            offset : offset + numel_in_shard
+                        ].reshape(param.shape)
+                    else:
+                        param.grad = grad[offset : offset + numel_in_shard].reshape(
+                            param.shape
+                        )
+                else:
+                    param.grad = None
+        assert flat_param._shared_params is not None
+        for i, (param, (_, _, _, prim_param_name, prim_module, _)) in enumerate(
+            zip(flat_param._shared_params, flat_param._shared_param_infos)
+        ):
+            in_sharded_flat_param = hasattr(prim_module, prim_param_name)
+            if in_sharded_flat_param and param.requires_grad:
+                prim_param = getattr(prim_module, prim_param_name)
+                param.grad = prim_param.grad  # share the same reference
+            else:
+                param.grad = None
+
+    @no_type_check
+    @torch.no_grad()
+    def _writeback_orig_params(self) -> bool:
+        """
+        Write back any parameters that changed storage to the handle's ``FlatParameter``.
+
+        Iterates over the original parameters and writes back any parameters
+        that changed storages (due to a non-inplace operator) to the handle's
+        ``FlatParameter``. This method preserves the ``FlatParameter` 's
+        device even if an original parameter's device changes.
+
+        Raises:
+            RuntimeError: If an original parameter or gradient changes storages
+            but no longer has the expected flattened shape.
+        Returns: ``True`` if some writeback happened, and ``False`` otherwise.
+        """
+        if (
+            self.uses_sharded_strategy
+            and not self.is_sharded(self.flat_param)
+            and not self._skipped_use_sharded_views
+        ):
+            # For `NO_SHARD`, we may still need to writeback
+            return False
+        flat_param = self.flat_param
+        wroteback = False
+        if self._skipped_use_sharded_views and self.uses_sharded_strategy:
+            # NOTE: We must use the unsharded flat parameter from which the
+            # unsharded views were computed, not the one from the current
+            # calling context (`_get_padded_unsharded_flat_param()`) since that
+            # may be different (e.g. the model changed from train to eval).
+            flat_param_tensor = self._unsharded_flat_param_for_skipped_views
+            _p_assert(
+                _data_ptr_allocated(flat_param_tensor),
+                "If skipped using sharded views, the unsharded flat parameter "
+                "should be allocated",
+            )
+        else:
+            flat_param_tensor = flat_param
+        # NOTE: Since this method is called in the pre-unshard, which is only
+        # called during computation in the pre-forward or pre-backward, the
+        # sharded gradient should be guaranteed to be in `.grad`, not in
+        # `._saved_grad_shard`.
+        flat_param_grad = (
+            flat_param.grad
+            if self.uses_sharded_strategy or not self._offload_params
+            else flat_param._cpu_grad
+        )
+        for i, (
+            param,
+            (in_shard, offset_in_shard, numel_in_shard, _, _),
+            (param_name, module, _),
+        ) in enumerate(
+            zip(
+                flat_param._params,
+                flat_param._shard_param_infos,
+                flat_param._param_infos,
+            )
+        ):
+            if not in_shard:
+                continue
+            if not hasattr(module, param_name):
+                # Do not writeback if original parameters are deregistered
+                # (e.g. during model checkpointing)
+                continue
+
+            # Check for parameter writeback
+            if self._skipped_use_sharded_views:
+                param = flat_param._tensors[i]
+                _p_assert(
+                    param is not None,
+                    f"Expects to have saved tensor for {flat_param._fqns[i]}",
+                )
+            param_changed = getattr(module, param_name) is not param
+            needs_param_writeback = (
+                param_changed  # changed parameter variable itself
+                or not _same_storage(param, flat_param_tensor)
+            )
+            if self._skipped_use_sharded_views and (
+                param_changed or needs_param_writeback
+            ):
+                raise AssertionError(
+                    "FSDP does not support changing the parameters between "
+                    f"forward and backward for {self._sharding_strategy}"
+                )
+            if param_changed:
+                # NOTE: The gradient is not preserved after a parameter change.
+                param = getattr(module, param_name)
+                flat_param._params[i] = param
+            if needs_param_writeback:
+                expected_shape = torch.Size([numel_in_shard])
+                self._writeback_tensor(
+                    param, flat_param, i, expected_shape, offset_in_shard, True
+                )
+                wroteback = True
+
+            # Check for gradient writeback
+            if self._skipped_use_sharded_views:
+                # Skip the writeback check because we do not expose gradients
+                # when we skipped using sharded views
+                continue
+            if param.grad is None and flat_param.grad is not None:
+                expected_shape = torch.Size([numel_in_shard])
+                self._writeback_tensor(
+                    None, flat_param.grad, i, expected_shape, offset_in_shard, False
+                )
+            elif param.grad is not None:
+                # For `NO_SHARD` + CPU offloading, `_cpu_grad` is always in
+                # memory and owns the gradient storage, so it will never
+                # require gradient writeback.
+                if not self.uses_sharded_strategy and self._offload_params:
+                    # Explicitly continue to handle the case of `no_sync()`,
+                    # where `param.grad` is a view into the GPU gradient
+                    # referenced by `flat_param.grad`, while `flat_param_grad`
+                    # is `flat_param._cpu_grad`, which is on CPU
+                    continue
+
+                needs_grad_writeback = flat_param_grad is None or not _same_storage(
+                    param.grad, flat_param_grad
+                )
+                if needs_grad_writeback:
+                    if flat_param_grad is None:
+                        flat_param_grad = torch.zeros_like(flat_param)
+                    expected_shape = torch.Size([numel_in_shard])
+                    self._writeback_tensor(
+                        param.grad,
+                        flat_param_grad,
+                        i,
+                        expected_shape,
+                        offset_in_shard,
+                        False,
+                    )
+                    flat_param.grad = flat_param_grad
+                    flat_param_grad = flat_param.grad
+
+        # TODO: If we want to handle shared parameters, we need to re-generate
+        # the shared parameter data structures in case sharedness changed.
+        for i, (
+            param_name,
+            module,
+            _,
+            prim_param_name,
+            prim_module,
+            _,
+        ) in enumerate(flat_param._shared_param_infos):
+            if getattr(module, param_name) is not getattr(prim_module, prim_param_name):
+                raise NotImplementedError(
+                    "Changing shared parameters is not supported yet"
+                )
+        return wroteback
+
+    def _writeback_tensor(
+        self,
+        src_tensor: Optional[Tensor],
+        dst_tensor: Tensor,
+        tensor_index: int,
+        expected_shape: torch.Size,
+        offset: int,
+        is_param: bool,  # else gradient
+    ) -> None:
+        """
+        Write back ``src_tensor`` to ``dst_tensor`` at offset ``offset``, where ``src_tensor`` should have shape ``expected_shape``.
+
+        ``is_param`` indicates if the tensor is the parameter (if ``True``) or gradient (if
+        ``False``). If ``src_tensor`` is ``None``, then the effect is zeroing
+        instead of copying. ``tensor_index`` gives the index of ``src_tensor``
+        in the metadata structures.
+
+        Raises:
+            RuntimeError: If the ``src_tensor`` does not have the expected
+            shape.
+        """
+        _p_assert(
+            len(expected_shape) == 1,
+            f"Expects a 1D expected shape but got {expected_shape}",
+        )
+        if self._debug_level == dist.DebugLevel.INFO:
+            rank = self.rank if hasattr(self, "rank") else dist.get_rank()
+            src_shape = src_tensor.shape if src_tensor is not None else None
+            src_device = src_tensor.device if src_tensor is not None else None
+            warnings.warn(
+                f"[Rank {rank}] {'Parameter' if is_param else 'Gradient'} needs "
+                f"writeback in {self._training_state}\n"
+                f"expected shape={expected_shape} shape={src_shape} "
+                f"expected device={dst_tensor.device} device={src_device}"
+            )
+        if src_tensor is not None and src_tensor.shape != expected_shape:
+            # NOTE: Gradient shape mismatch is not possible in practice since
+            # the gradient shape is enforced to match that of the parameter and
+            # we already check for parameter shape mismatch.
+            raise RuntimeError(
+                f"Cannot writeback when the {'parameter' if is_param else 'gradient'} "
+                f"shape changes\nExpects {expected_shape} but got {src_tensor.shape}"
+            )
+        if src_tensor is not None:
+            dst_tensor[offset : offset + expected_shape.numel()].copy_(src_tensor)
+        else:
+            dst_tensor[offset : offset + expected_shape.numel()].zero_()
+            assert self.flat_param._is_grad_none_mask is not None
+            self.flat_param._is_grad_none_mask[tensor_index] = True
+
+    def _reset_flat_param_grad_info_if_needed(self):
+        """
+        Reset ``flat_param.grad`` if needed.
+
+        When ``use_orig_params=True``:
+        (1) sets the underlying ``flat_param.grad`` to ``None`` if *all* of the
+        original parameters' ``.grad`` are ``None``, and
+        (2) sets ``flat_param.requires_grad=False`` if *none* of the original
+        parameters require gradient.
+        For (1), this is targeting ``optim.zero_grad(set_to_none=True)``, in
+        which case we want to free the gradients as soon after the
+        ``zero_grad()`` call as possible.
+        """
+        if not self._use_orig_params:
+            return
+        flat_param = self.flat_param
+        assert flat_param._params is not None  # mypy
+        all_grad_none = True
+        requires_grad = False
+        for param in flat_param._params:
+            all_grad_none &= param.grad is None
+            requires_grad |= param.requires_grad
+        if all_grad_none:
+            flat_param.grad = None
+        # As long as one parameter requires gradient, then the flat parameter
+        # must require gradient
+        flat_param.requires_grad = requires_grad
+
+    def _deregister_orig_params(self):
+        for param_info in self.flat_param._param_infos:
+            param_name, module, _ = param_info
+            if hasattr(module, param_name):
+                delattr(module, param_name)
+        for param_name, module, _, _, _, _ in self.flat_param._shared_param_infos:
+            if hasattr(module, param_name):
+                delattr(module, param_name)
+
+    ###########
+    # HELPERS #
+    ###########
+    def flat_param_to(self, *args, **kwargs):
+        """Wrap an in-place call to ``.to()`` for ``self.flat_param``."""
+        self.flat_param.data = self.flat_param.to(*args, **kwargs)
+        if self._use_orig_params:
+            # Refresh the views because their storage may have changed
+            if self.is_sharded(self.flat_param):
+                self._use_sharded_views()
+            else:
+                self._use_unsharded_views(as_params=True)
+
+    def _get_modules(self) -> Set[nn.Module]:
+        """Return a :class:`set` of the modules whose parameters are included in this handle's flat parameter."""
+        return {pi.module for pi in self.flat_param._param_infos}.union(
+            {spi.module for spi in self.flat_param._shared_param_infos}
+        )
+
+    def is_sharded(self, tensor: Tensor) -> bool:
+        """
+        Return whether ``tensor`` is *currently* sharded.
+
+        For ``NO_SHARD``, we choose to have this always return ``False`` for clarity.
+        """
+        if (
+            not hasattr(self.flat_param, "_sharded_size")
+            or not self.uses_sharded_strategy
+        ):
+            # `_sharded_size` is defined iff `handle.shard()` has been called
+            return False
+        sharded_size = self.flat_param._sharded_size  # type: ignore[attr-defined]
+        return tensor.size() == sharded_size
+
+    def param_module_names(self) -> Iterator[Tuple[str, str]]:
+        shared_param_infos = [
+            ParamInfo(param_name, module, module_name)
+            for (
+                param_name,
+                module,
+                module_name,
+                _,
+                _,
+                _,
+            ) in self.flat_param._shared_param_infos
+        ]
+        for param_info in chain(self.flat_param._param_infos, shared_param_infos):
+            param_name, _, module_name = param_info  # type: ignore[misc]
+            yield (param_name, module_name)
+
+    def shared_param_module_names(self) -> Iterator[Tuple[str, str]]:
+        for param_name, _, module_name in [
+            ParamInfo(param_name, module, module_name)
+            for (
+                param_name,
+                module,
+                module_name,
+                _,
+                _,
+                _,
+            ) in self.flat_param._shared_param_infos
+        ]:
+            yield (param_name, module_name)
+
+    @property
+    def _fqns_in_shard(self) -> List[str]:
+        """Return the FQNs of the parameters present in this rank's shard."""
+        fqns_in_shard: List[str] = []
+        for fqn, shard_param_info in zip(
+            self.flat_param._fqns, self.flat_param._shard_param_infos  # type: ignore[attr-defined]
+        ):
+            if shard_param_info.in_shard:
+                fqns_in_shard.append(fqn)
+        return fqns_in_shard
+
+    @property
+    def sharded_grad(self) -> Optional[Tensor]:
+        """Return the handle's sharded gradient."""
+        flat_param = self.flat_param
+        # Priority for non-`None`: `_cpu_grad` > `_saved_grad_shard` > `grad`
+        # - CPU offloading: `_cpu_grad`
+        # - No CPU offloading + sharded strategies: `_saved_grad_shard`
+        # - No CPU offloading + `NO_SHARD`: `grad`
+        grad: Optional[Tensor]
+        if hasattr(flat_param, "_cpu_grad"):
+            grad = flat_param._cpu_grad  # type: ignore[attr-defined]
+        elif hasattr(flat_param, "_saved_grad_shard"):
+            # In the post-backward hook, the sharded gradient is still in
+            # `_saved_grad_shard`.
+            grad = flat_param._saved_grad_shard  # type: ignore[attr-defined]
+        else:
+            # If in IDLE or in FORWARD states, then there may be an
+            # (accumulated) gradient. If accessed in IDLE, then this should
+            # be due to re-registering the original parameters (e.g. in state
+            # dict load).
+            _p_assert(
+                flat_param.grad is None
+                or not self.uses_sharded_strategy
+                or self._training_state
+                in (HandleTrainingState.FORWARD, HandleTrainingState.IDLE),
+                "Sharded strategies should use `_cpu_grad` or `_saved_grad_shard` "
+                "unless in IDLE or FORWARD",
+            )
+            grad = flat_param.grad
+        return grad
+
+    def _reset_is_grad_none(self) -> None:
+        """
+        Reset ``_is_grad_none_mask`` as needed.
+
+        This method should only be
+        called in the post-backward after gradient computation, in which case
+        if a parameter requires gradient, then it will surely receive a
+        gradient and we may reset its mask entry to ``False``.
+        """
+        if not self._use_orig_params:
+            return
+        _p_assert(
+            self._training_state == HandleTrainingState.BACKWARD_POST,
+            "Expects to only be called in the post-backward after gradient computation",
+        )
+        flat_param = self.flat_param
+        assert flat_param._params is not None  # mypy
+        for i, param in enumerate(flat_param._params):  # type: ignore[arg-type]
+            # As long as the parameter requires gradient, it should receive a
+            # meaningful gradient (even if the gradient happens to be zeros)
+            if param.requires_grad:
+                assert flat_param._is_grad_none_mask is not None  # mypy
+                flat_param._is_grad_none_mask[i] = False
+
+    #######################
+    # CHECKS & INVARIANTS #
+    #######################
+    def _check_sharded_strategy(self):
+        _p_assert(self.uses_sharded_strategy, "Expects sharded strategy")
+
+    def _check_on_compute_device(self, tensor: Tensor):
+        _p_assert(
+            tensor.device == self.device,
+            f"Expects tensor to be on the compute device {self.device}, was on {tensor.device}",
+        )
+
+    def _check_on_cpu(self, tensor: Tensor):
+        _p_assert(
+            tensor.device == torch.device("cpu"),
+            f"Expects tensor to be on CPU but got {tensor.device}",
+        )
+
+    @staticmethod
+    def _check_storage_freed(tensor: Tensor):
+        # Compile does not resize during trace
+        if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
+            _p_assert(
+                _same_storage_size(tensor, 0),
+                "Expects storage to be freed but got storage with size > 0",
+            )
+
+    @staticmethod
+    def _check_storage_allocated(tensor: Tensor):
+        _p_assert(_storage_size_allocated(tensor), "Expects storage to be allocated")
+
+    def _check_low_precision_shard(self):
+        _p_assert(
+            self._uses_param_mixed_precision,
+            "Not using low precision for parameters",
+        )
+        _p_assert(
+            getattr(self.flat_param, "_mp_shard", None) is not None,
+            "Expects `_mp_shard` to exist",
+        )
+        device = self.flat_param._mp_shard.device  # type: ignore[attr-defined]
+        _p_assert(
+            device == self.device,
+            f"Expects the low precision shard to be on {self.device} but got {device}",
+        )
+
+    def _check_unsharded(self, tensor: Tensor):
+        msg_prefix = "Expects tensor to be unsharded "
+        _p_assert(tensor is not None, msg_prefix + "but got `None`")
+        unsharded_size = self.flat_param._unpadded_unsharded_size
+        _p_assert(
+            tensor.size() == unsharded_size,
+            msg_prefix + f"with size {unsharded_size} but got {tensor.size()}",
+        )
+
+    def _check_sharded(self, tensor: Tensor):
+        msg_prefix = "Expects tensor to be sharded "
+        _p_assert(tensor is not None, msg_prefix + "but got `None`")
+        sharded_size = self.flat_param._sharded_size  # type: ignore[attr-defined]
+        _p_assert(
+            tensor.size() == sharded_size,
+            msg_prefix + f"with size {sharded_size} but got {tensor.size()}",
+        )
+
+    ##############
+    # PROPERTIES #
+    ##############
+    @property
+    def uses_sharded_strategy(self) -> bool:
+        return self._sharding_strategy != HandleShardingStrategy.NO_SHARD
+
+    @property
+    def _uses_param_mixed_precision(self) -> bool:
+        return self._fwd_bwd_param_dtype != self._orig_param_dtype
+
+    @property
+    def _uses_reduce_mixed_precision(self) -> bool:
+        return self._reduce_dtype != self._orig_param_dtype
+
+    @property
+    def _force_full_precision(self) -> bool:
+        return (
+            self._uses_param_mixed_precision or self._uses_reduce_mixed_precision
+        ) and (
+            self._training_state == HandleTrainingState.SUMMON_FULL_PARAMS
+            or
+            # Also disable mixed precision in model eval mode, if configured
+            (not self._fully_sharded_module.training and self._use_full_prec_in_eval)
+        )
+
+    @property
+    def _skipped_use_sharded_views(self) -> bool:
+        """
+        This property is used for sharding strategies that do not free after forward with ``use_orig_params=True``.
+
+        This returns if this handle is
+        currently in a state where it has skipped using sharded views, in which
+        case it can restore view invariants via ``_use_sharded_views()``.
+        """
+        return self._unsharded_flat_param_for_skipped_views is not None
+
+
+# NOTE: These are hacks to bypass `nn.Module.__setattr__` checks.
+def _unsafe_setattr_param(
+    module: nn.Module, param_name: str, param: nn.Parameter
+) -> None:
+    module._parameters[param_name] = param
+    # This bypasses any overrides in case `module` is an instance of an
+    # `nn.Module` subclass
+    super(nn.Module, module).__setattr__(param_name, param)
+
+
+def _unsafe_setattr_tensor(module: nn.Module, param_name: str, tensor: Tensor) -> None:
+    module._parameters.pop(param_name, None)
+    # This bypasses any overrides in case `module` is an instance of an
+    # `nn.Module` subclass
+    super(nn.Module, module).__setattr__(param_name, tensor)
+
+
+def _safe_setattr_tensor_or_param(
+    module: nn.Module, param_name: str, tensor_or_param: Union[Tensor, nn.Parameter]
+):
+    # Call `delattr()` and `setattr()` to go through `nn.Module` checks
+    if hasattr(module, param_name):
+        delattr(module, param_name)
+    setattr(module, param_name, tensor_or_param)
+
+
+def _convert_to_params(
+    tensors: List[Union[torch.Tensor, nn.Parameter]]
+) -> List[nn.Parameter]:
+    return [t if isinstance(t, nn.Parameter) else nn.Parameter(t) for t in tensors]
+
+
+def _detach_if_needed(param_or_tensor: Union[nn.Parameter, Tensor]) -> Tensor:
+    return (
+        param_or_tensor.detach()
+        if isinstance(param_or_tensor, nn.Parameter)
+        else param_or_tensor
+    )
+
+
+def _get_aligned_numel(unsharded_dtype: torch.dtype):
+    # NOTE: This alignment constraint comes from TorchInductor.
+    ALIGNMENT = 16  # bytes
+    unsharded_dtype_size = _get_dtype_size(unsharded_dtype)
+    aligned_numel = ALIGNMENT // unsharded_dtype_size
+    return aligned_numel
+
+
+@functools.lru_cache(8)
+def _get_dtype_size(dtype):
+    return torch.empty((), dtype=dtype).element_size()
+
+
+def _construct_padding_tensor(
+    padding_numel: int, dtype: torch.dtype, requires_grad: bool, device: torch.device
+):
+    # NOTE: Set the padding value as a magic number for debuggability. The
+    # value itself should never be used in any user-facing computation.
+    return (
+        torch.ones(
+            (padding_numel,), dtype=dtype, requires_grad=requires_grad, device=device
+        )
+        * _FLAT_PARAM_PADDING_VALUE
+    )
+
+
+# Use `lru_cache(1)` to only log the warning once (assuming the fixed warning
+# messasge is passed in)
+@functools.lru_cache(1)
+def _warn_skip_writeback_check(log: logging.Logger, warning: str):
+    logger.warning(warning)
+
+
+# Use `lru_cache(1)` to only log the warning once
+@functools.lru_cache(1)
+def _warn_use_fake_all_gather(log: logging.Logger, warning: str):
+    logger.warning(warning)
+
+
+# Use `lru_cache(1)` to only log the warning once
+@functools.lru_cache(1)
+def _warn_use_fake_reduce(log: logging.Logger, warning: str):
+    logger.warning(warning)
+
+
+def _same_storage(a, b):
+    # Params are DTensors in backward
+    # with SHARD_GRAD_OP + TP
+    from torch.distributed.tensor import DTensor
+
+    if isinstance(a, DTensor):
+        a = a._local_tensor
+    if isinstance(b, DTensor):
+        b = b._local_tensor
+    return a.untyped_storage().data_ptr() == b.untyped_storage().data_ptr()
+
+
+def _same_storage_size(a: torch.Tensor, b: int):
+    return a.untyped_storage().size() // a.element_size() == b
+
+
+def _storage_size_allocated(tensor: Tensor):
+    storage_size: int = tensor.untyped_storage().size()
+    return storage_size > 0
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_fsdp_extensions.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_fsdp_extensions.py
new file mode 100644
index 0000000000000000000000000000000000000000..d96fa99a236571708139c454f3433cc0cd5e21b6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_fsdp_extensions.py
@@ -0,0 +1,179 @@
+from abc import ABC, abstractmethod
+from typing import Any, List, Optional, Tuple
+
+import torch
+import torch.distributed as dist
+from torch.distributed._shard.sharded_tensor.api import ShardedTensor
+from torch.distributed._shard.sharded_tensor.shard import Shard
+from torch.distributed.fsdp._shard_utils import (
+    _all_gather_dtensor,
+    _create_chunk_dtensor,
+    _create_chunk_sharded_tensor,
+)
+from torch.distributed.tensor import DeviceMesh, DTensor
+
+
+class FSDPExtensions(ABC):
+    """
+    This enables some customizable hooks to enable composability with tensor
+    parallelism. To activate these hooks, use :func:`_set_fsdp_extensions` to
+    set a custom :class:`FSDPExtensions` that implements the hooks.
+    """
+
+    @abstractmethod
+    def pre_flatten_transform(
+        self,
+        tensor: torch.Tensor,
+    ) -> Tuple[torch.Tensor, Optional[Any]]:
+        """E.g. converting ``DistributedTensor`` to local tensor."""
+        ...
+
+    @abstractmethod
+    def post_unflatten_transform(
+        self,
+        tensor: torch.Tensor,
+        param_extension: Any,
+    ) -> torch.Tensor:
+        """E.g. converting local tensor to ``DistributedTensor``."""
+        ...
+
+    @abstractmethod
+    def chunk_tensor(
+        self,
+        tensor: torch.Tensor,
+        rank: int,
+        world_size: int,
+        num_devices_per_node: int,
+        pg: dist.ProcessGroup,
+        device: Optional[torch.device] = None,
+    ) -> torch.Tensor:
+        """Shards a tensor to chunks and returns the local chunk."""
+        ...
+
+    @abstractmethod
+    def chunk_dtensor(
+        self,
+        tensor: torch.Tensor,
+        rank: int,
+        device_mesh: DeviceMesh,
+    ) -> torch.Tensor:
+        """Shards a tensor/DTensor to DTensor and returns the local DTensor."""
+        ...
+
+    @abstractmethod
+    def pre_load_state_dict_transform(
+        self,
+        tensor: torch.Tensor,
+    ) -> Tuple[torch.Tensor, List[Shard]]:
+        """
+        This is to be called before loading a *sharded* model state dict and
+        should return the tensor and list of shards from which to load data.
+        """
+        ...
+
+    @abstractmethod
+    def all_gather_dtensor(
+        self,
+        tensor: DTensor,
+        parent_mesh: Optional[DeviceMesh],
+    ) -> torch.Tensor:
+        """
+        This is to be called before loading a *sharded* DTensor state dict.
+        This gathers tensor in FSDP dimension and returns local tensor of
+        TP DTensor.
+        """
+        ...
+
+
+_extensions: Optional[FSDPExtensions] = None
+
+
+def _set_fsdp_extensions(flattener: FSDPExtensions) -> None:
+    global _extensions
+    _extensions = flattener
+
+
+def _ext_pre_flatten_transform(
+    tensor: torch.Tensor,
+    fsdp_extension: Optional[FSDPExtensions] = None,
+) -> Tuple[torch.Tensor, Optional[Any]]:
+    if fsdp_extension is not None:
+        new_tensor, param_extension = fsdp_extension.pre_flatten_transform(tensor)
+        if param_extension is not None:
+            return new_tensor, param_extension
+    return tensor, None
+
+
+def _ext_post_unflatten_transform(
+    tensor: torch.Tensor,
+    param_extension: Any,
+    fsdp_extension: Optional[FSDPExtensions] = None,
+) -> torch.Tensor:
+    if fsdp_extension is not None and param_extension is not None:
+        return fsdp_extension.post_unflatten_transform(tensor, param_extension)
+    return tensor
+
+
+def _ext_chunk_tensor(
+    tensor: torch.Tensor,
+    rank: int,
+    world_size: int,
+    num_devices_per_node: int,
+    pg: dist.ProcessGroup,
+    fsdp_extension: Optional[FSDPExtensions] = None,
+) -> torch.Tensor:
+    chunk_tensor_fn = (
+        fsdp_extension.chunk_tensor
+        if fsdp_extension is not None
+        else _create_chunk_sharded_tensor
+    )
+    return chunk_tensor_fn(
+        tensor,
+        rank,
+        world_size,
+        num_devices_per_node,
+        pg,
+    )
+
+
+def _ext_chunk_dtensor(
+    tensor: torch.Tensor,
+    rank: int,
+    device_mesh: DeviceMesh,
+    fsdp_extension: Optional[FSDPExtensions] = None,
+) -> torch.Tensor:
+    chunk_dtensor_fn = (
+        fsdp_extension.chunk_dtensor
+        if fsdp_extension is not None
+        else _create_chunk_dtensor
+    )
+    return chunk_dtensor_fn(
+        tensor,
+        rank,
+        device_mesh,
+    )
+
+
+def _ext_pre_load_state_dict_transform(
+    tensor: torch.Tensor,
+    fsdp_extension: Optional[FSDPExtensions] = None,
+) -> Tuple[torch.Tensor, List[Shard]]:
+    if fsdp_extension is not None:
+        return fsdp_extension.pre_load_state_dict_transform(tensor)
+
+    assert type(tensor) is ShardedTensor
+    shards = tensor.local_shards()
+    return (tensor, shards)
+
+
+def _ext_all_gather_dtensor(
+    tensor: DTensor,
+    parent_mesh: Optional[DeviceMesh],
+    fsdp_extension: Optional[FSDPExtensions] = None,
+) -> torch.Tensor:
+    all_gather_dtensor_fn = (
+        fsdp_extension.all_gather_dtensor
+        if fsdp_extension is not None
+        else _all_gather_dtensor
+    )
+    return all_gather_dtensor_fn(tensor, parent_mesh)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_init_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_init_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..3166f4b1430d767a8e4c5c30da3590aafadab04a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_init_utils.py
@@ -0,0 +1,1200 @@
+# mypy: allow-untyped-defs
+import collections
+import itertools
+import os
+import warnings
+from typing import (
+    Any,
+    Callable,
+    Deque,
+    Dict,
+    Generator,
+    Iterable,
+    Iterator,
+    List,
+    no_type_check,
+    Optional,
+    Set,
+    Tuple,
+    TYPE_CHECKING,
+    Union,
+)
+
+import torch
+import torch.distributed as dist
+import torch.distributed.fsdp._exec_order_utils as exec_order_utils
+import torch.distributed.fsdp._traversal_utils as traversal_utils
+import torch.distributed.fsdp.fully_sharded_data_parallel as fsdp_file
+import torch.nn as nn
+from torch.distributed.algorithms._comm_hooks import default_hooks
+from torch.distributed.device_mesh import _mesh_resources, DeviceMesh
+from torch.distributed.distributed_c10d import _get_default_group
+from torch.distributed.fsdp._common_utils import (
+    _FSDPDeviceHandle,
+    _FSDPState,
+    _get_module_fsdp_state,
+    _is_fsdp_flattened,
+    _named_parameters_with_duplicates,
+    clean_tensor_name,
+    TrainingState,
+)
+from torch.distributed.fsdp._flat_param import (
+    _FSDP_USE_FULL_PREC_IN_EVAL,
+    FlatParameter,
+    FlatParamHandle,
+    HandleShardingStrategy,
+)
+from torch.distributed.fsdp._limiter_utils import _FreeEventQueue
+from torch.distributed.fsdp.api import (
+    BackwardPrefetch,
+    CPUOffload,
+    FullOptimStateDictConfig,
+    FullStateDictConfig,
+    MixedPrecision,
+    ShardingStrategy,
+    StateDictConfig,
+    StateDictType,
+)
+from torch.distributed.fsdp.wrap import _Policy
+from torch.distributed.tensor.parallel.fsdp import DTensorExtensions
+from torch.distributed.utils import _sync_params_and_buffers
+from torch.utils._python_dispatch import is_traceable_wrapper_subclass
+
+
+if TYPE_CHECKING:
+    from torch.utils.hooks import RemovableHandle
+
+_TORCHDISTX_AVAIL = True
+try:
+    from torchdistx import deferred_init, fake  # type: ignore[import]
+except ImportError:
+    _TORCHDISTX_AVAIL = False
+
+PARAM_BROADCAST_BUCKET_SIZE = int(250 * 1024 * 1024)
+FSDP_SYNCED = "_fsdp_synced"
+# Specification of process groups for hybrid sharding strategies.
+HybridShardProcessGroupType = Tuple[dist.ProcessGroup, dist.ProcessGroup]
+# Overall specification of process group.
+ProcessGroupType = Optional[Union[dist.ProcessGroup, HybridShardProcessGroupType]]
+
+
+# TODO (awgu): Refactor this later
+SHARDING_STRATEGY_MAP = {
+    ShardingStrategy.NO_SHARD: HandleShardingStrategy.NO_SHARD,
+    ShardingStrategy.FULL_SHARD: HandleShardingStrategy.FULL_SHARD,
+    ShardingStrategy.SHARD_GRAD_OP: HandleShardingStrategy.SHARD_GRAD_OP,
+    ShardingStrategy.HYBRID_SHARD: HandleShardingStrategy.HYBRID_SHARD,
+    ShardingStrategy._HYBRID_SHARD_ZERO2: HandleShardingStrategy._HYBRID_SHARD_ZERO2,
+}
+HYBRID_SHARDING_STRATEGIES = [
+    ShardingStrategy.HYBRID_SHARD,
+    ShardingStrategy._HYBRID_SHARD_ZERO2,
+]
+NO_RESHARD_AFTER_FORWARD_STRATEGIES = (
+    ShardingStrategy.SHARD_GRAD_OP,
+    ShardingStrategy._HYBRID_SHARD_ZERO2,
+)
+
+
+# NOTE: Since non-self attributes cannot be type annotated, several attributes
+# on `state` are defined first as local variables before being assigned.
+
+
+@no_type_check
+def _init_process_group_state(
+    state: _FSDPState,
+    process_group: ProcessGroupType,
+    sharding_strategy: ShardingStrategy,
+    policy: Optional[_Policy],
+    device_mesh: Optional[DeviceMesh] = None,
+) -> _FSDPState:
+    if process_group is not None and device_mesh is not None:
+        raise ValueError(
+            "Cannot pass both process_group and device_mesh at the "
+            "same time. Please just pass only one of them."
+        )
+    is_hybrid_strategy = sharding_strategy in HYBRID_SHARDING_STRATEGIES
+    if is_hybrid_strategy:
+        if process_group is None and policy is None and device_mesh is None:
+            # Raise an error here, since this is manual wrapping with no process group
+            # passed in, there is no way to ensure all wrapped FSDP instances use the same
+            # process groups.
+            raise ValueError(
+                f"Manual wrapping with {sharding_strategy} "
+                "requires explicit specification of process group or device_mesh."
+            )
+        else:
+            state = _init_process_group_state_for_hybrid_shard(
+                state, process_group, device_mesh
+            )
+    else:
+        if device_mesh:
+            state._device_mesh = device_mesh
+            state.process_group = device_mesh.get_group(mesh_dim=0)
+        else:
+            state.process_group = (
+                process_group if process_group is not None else _get_default_group()
+            )
+
+    state.rank = state.process_group.rank()
+    state.world_size = state.process_group.size()
+    data_parallel_world_size = state.world_size
+    if is_hybrid_strategy:
+        data_parallel_world_size *= state._inter_node_pg.size()
+    state._gradient_predivide_factor = (
+        default_hooks.DefaultState._get_gradient_predivide_factor(
+            data_parallel_world_size
+        )
+    )
+    state._gradient_postdivide_factor = (
+        data_parallel_world_size / state._gradient_predivide_factor
+    )
+    return state
+
+
+@no_type_check
+def _init_process_group_state_for_hybrid_shard(
+    state: _FSDPState,
+    process_group: ProcessGroupType,
+    device_mesh: DeviceMesh,
+) -> _FSDPState:
+    if device_mesh:
+        if _is_valid_hybrid_shard_device_mesh(device_mesh):
+            state._device_mesh = device_mesh
+            # We currently only allow _inter_node_pg to be the outermost dimension, and the
+            # process_group(intra_node) to be the innermost dimension.
+            state._inter_node_pg = device_mesh.get_group(mesh_dim=0)
+            state.process_group = device_mesh.get_group(mesh_dim=1)
+        else:
+            raise ValueError(
+                f"Expected device_mesh to have ndim=2 but got {device_mesh.ndim}"
+            )
+    elif process_group is None:
+        default_group = _get_default_group()
+        intra_node_group, inter_node_group = _init_intra_and_inter_node_groups(
+            default_group, state._device_handle.device_count()
+        )
+        # we shard across intra-node
+        state.process_group = intra_node_group
+        # save _inter_node_pg to allreduce across.
+        state._inter_node_pg = inter_node_group
+    else:
+        # Check type and assign state.process_group and state._inter_node_pg.
+        if _is_valid_hybrid_shard_pg_type(process_group):
+            # Assuming that user passed in as intra node group and inter node group
+            # as documented.
+            state.process_group, state._inter_node_pg = process_group
+        else:
+            raise ValueError(
+                "Expected process_group to be passed in as either None or "
+                f"Tuple[dist.ProcessGroup, dist.ProcessGroup] but got {type(process_group)}"
+            )
+    # Create state for allreduce
+    state._inter_node_state = _get_default_comm_hook_state(
+        process_group=state._inter_node_pg,
+    )
+    return state
+
+
+@no_type_check
+def _is_valid_hybrid_shard_pg_type(process_group: Any) -> bool:
+    return (
+        isinstance(process_group, tuple)
+        and len(process_group) == 2
+        and all(isinstance(pg, dist.ProcessGroup) for pg in process_group)
+    )
+
+
+@no_type_check
+def _is_valid_hybrid_shard_device_mesh(device_mesh: DeviceMesh) -> bool:
+    return isinstance(device_mesh, DeviceMesh) and device_mesh.ndim == 2
+
+
+@no_type_check
+def _init_intra_node_process_group(num_devices_per_node: int) -> dist.ProcessGroup:
+    """
+    Return a process group across the current node.
+
+    For example, given each row is a distinct node:
+    0  1  2  3  4  5  6  7
+    8  9 10 11 12 13 14 15
+    This API would return an intra-node subgroup across
+    [0, 1, ..., 7] or [8, 9, ..., 15] depending on the process's rank.
+    For example, rank 3 would get [0, 1, ..., 7].
+    """
+    intra_node_subgroup, _ = dist.new_subgroups(num_devices_per_node)
+    return intra_node_subgroup
+
+
+@no_type_check
+def _init_inter_node_process_group(
+    global_process_group: dist.ProcessGroup,
+    num_devices_per_node: int,
+) -> dist.ProcessGroup:
+    """
+    Return an inter-node process group where each contained rank has the same local rank.
+
+    For example, given each row is a distinct node:
+    0  1  2  3  4  5  6  7
+    8  9 10 11 12 13 14 15
+    This API would return inter-node process group [0, 8], [1, 9], [2, 10], and so forth
+    depending on the process's rank. For example, rank 1 would get [1, 9], rank 5
+    would get [5, 13].
+    """
+    # the inter-node pg that is returned
+    inter_node_pg = None
+    sharding_backend = dist.get_backend(global_process_group)
+    world_size = dist.get_world_size(global_process_group)
+    # Assuming fully homogeneous setup
+    num_nodes = world_size // num_devices_per_node
+    my_local_rank = dist.get_rank(global_process_group) % num_devices_per_node
+    for local_rank in range(num_devices_per_node):
+        ranks_for_inter_group = [
+            local_rank + (i * num_devices_per_node) for i in range(num_nodes)
+        ]
+        # every rank always needs to call dist.new_group
+        grp = dist.new_group(ranks=ranks_for_inter_group, backend=sharding_backend)
+        if local_rank == my_local_rank:
+            inter_node_pg = grp
+
+    assert (
+        inter_node_pg is not None
+    ), f"{my_local_rank} expected to assign inter-node pg, but did not"
+    return inter_node_pg
+
+
+def _init_intra_and_inter_node_groups(
+    global_process_group: dist.ProcessGroup,
+    num_devices_per_node: int,
+) -> Tuple[dist.ProcessGroup, dist.ProcessGroup]:
+    """
+    Initialize intra and inter-node process groups and return the ones corresponding to this process's rank.
+
+    This function can be used to initialize process groups for ``HYBRID_SHARD`` or
+    ``_HYBRID_SHARD_ZERO2`` in FSDP.
+    This function assumes each node has an equal number of CUDA-enabled devices.
+    Returns:
+        Tuple[dist.ProcessGroup, dist.ProcessGroup]: Intra and inter-node process group.
+    """
+    return (
+        _init_intra_node_process_group(num_devices_per_node),
+        _init_inter_node_process_group(global_process_group, num_devices_per_node),
+    )
+
+
+@no_type_check
+def _init_ignored_module_states(
+    state: _FSDPState,
+    module: nn.Module,
+    ignored_modules: Optional[Iterable[torch.nn.Module]],
+    ignored_states: Union[
+        Optional[Iterable[torch.nn.Parameter]], Optional[Iterable[torch.nn.Module]]
+    ] = None,
+) -> _FSDPState:
+    if ignored_modules is not None and ignored_states is not None:
+        raise ValueError(
+            "Cannot pass both ignored_modules and ignored_states at the "
+            "same time. Please just pass ignored_states."
+        )
+    ignored_parameters = None
+    passed_as_ignored_states = ignored_states is not None
+    if passed_as_ignored_states:
+        ignored_states_list = list(ignored_states)
+        _check_ignored_states(ignored_states_list, True)
+    else:
+        ignored_states_list = []
+        _check_ignored_states(
+            list(ignored_modules) if ignored_modules is not None else [], False
+        )
+    if len(ignored_states_list) > 0:
+        if isinstance(ignored_states_list[0], nn.Parameter):
+            ignored_parameters = ignored_states_list
+        else:
+            ignored_modules = ignored_states_list
+    state._ignored_modules = _get_ignored_modules(module, ignored_modules)
+    state._ignored_params = _get_ignored_params(
+        module,
+        state._ignored_modules,
+        ignored_parameters,
+    )
+    state._ignored_buffer_names = _get_ignored_buffer_names(
+        module,
+        state._ignored_modules,
+    )
+    # TODO: FSDP's contract for buffers is not well-defined. They are
+    # implicitly ignored for most functionality since they are not sharded;
+    # however, FSDP still imposes some semantics on buffers (e.g. buffer mixed
+    # precision). We should formalize this contract and decide if we need to
+    # compute and store `_ignored_buffers`.
+    return state
+
+
+def _check_ignored_states(
+    ignored_states: List[Any], passed_as_ignored_states: bool
+) -> None:
+    """
+    Check that the ignored states are uniformly parameters or uniformly modules.
+
+    We may remove this check in the future if we permit mixing.
+    """
+    if len(ignored_states) == 0:
+        return
+    if passed_as_ignored_states:
+        all_params = all(isinstance(state, nn.Parameter) for state in ignored_states)
+        all_modules = all(isinstance(state, nn.Module) for state in ignored_states)
+        if not all_params and not all_modules:
+            # Sort for consistent ordering for unit test regex matching
+            sorted_types = sorted({type(state) for state in ignored_states}, key=repr)
+            raise ValueError(
+                "ignored_states expects all nn.Parameter or all nn.Module list "
+                f"elements but got types {sorted_types}"
+            )
+    else:
+        if not all(isinstance(state, nn.Module) for state in ignored_states):
+            sorted_types = sorted({type(state) for state in ignored_states}, key=repr)
+            raise ValueError(
+                "ignored_modules expects nn.Module list elements but got "
+                f"types {sorted_types}"
+            )
+
+
+@no_type_check
+def _init_device_handle(
+    state: _FSDPState,
+    module: nn.Module,
+    ignored_params: Set[nn.Parameter],
+    device_id: Optional[Union[int, torch.device]],
+) -> _FSDPState:
+    """
+    Determine device handle used for initializing FSDP.
+
+    If a device is specified by ``device_id``,
+    then returns device handle corresponds to that device type. Otherwise, If the
+    module is already on a non-CPU device, then the device type is that non-CPU device type.
+    If the module is on CPU or meta, then the device type is the current accelerator device.
+    See the :ref:`Accelerators` for details.
+
+
+    This method will be called once ignored paramters was determined, as the device handle maybe needed
+    for other initialization.
+    """
+    determined_device = None
+    if device_id is not None:
+        determined_device = (
+            device_id
+            if isinstance(device_id, torch.device)
+            else torch.device(device_id)
+        )
+    if determined_device is None:
+        for param in _get_orig_params(module, ignored_params):
+            if param.device.type in {"cpu", "meta"}:
+                continue
+            if determined_device is None:
+                determined_device = param.device
+            else:
+                if param.device.type != determined_device.type:
+                    raise RuntimeError(
+                        f"FSDP does not support modules with different device types "
+                        f"but got params on {determined_device.type} and {param.device.type}"
+                    )
+        determined_device = determined_device or torch._C._get_accelerator()
+        if determined_device.type == "cpu":
+            raise RuntimeError(
+                "FSDP needs a non-CPU accelerator device, but no accelerator device is detected."
+            )
+
+    state._device_handle = _FSDPDeviceHandle.from_device(determined_device)
+    return state
+
+
+@no_type_check
+def _init_buffer_state(
+    state: _FSDPState,
+    module: nn.Module,
+) -> _FSDPState:
+    state._buffer_names = _get_buffer_names(module)
+    # Save a mapping from clean fully-qualified buffer name (starting from
+    # `module`) to its original dtype for restoring that dtype during model
+    # checkpointing when buffer mixed precision is enabled. The names should
+    # be clean since the casting happens in a `summon_full_params()` context.
+    _buffer_name_to_orig_dtype: Dict[str, torch.dtype] = {}
+    for buffer_name, buffer in module.named_buffers():
+        buffer_name = clean_tensor_name(buffer_name)
+        _buffer_name_to_orig_dtype[buffer_name] = buffer.dtype
+    state._buffer_name_to_orig_dtype = _buffer_name_to_orig_dtype
+    return state
+
+
+@no_type_check
+def _init_core_state(
+    state: _FSDPState,
+    sharding_strategy: Optional[ShardingStrategy],
+    mixed_precision: Optional[MixedPrecision],
+    cpu_offload: Optional[CPUOffload],
+    limit_all_gathers: bool,
+    use_orig_params: bool,
+    backward_prefetch_limit: int,
+    forward_prefetch_limit: int,
+) -> _FSDPState:
+    # We clamp the strategy to `NO_SHARD` for world size of 1 since they are
+    # currently functionally equivalent. This may change if/when we integrate
+    # FSDP with MoE.
+    if state.world_size == 1:
+        if sharding_strategy != ShardingStrategy.NO_SHARD:
+            warnings.warn(
+                "FSDP is switching to use `NO_SHARD` instead of "
+                f"{sharding_strategy or ShardingStrategy.FULL_SHARD} since "
+                "the world size is 1."
+            )
+        sharding_strategy = ShardingStrategy.NO_SHARD
+    elif sharding_strategy == ShardingStrategy.NO_SHARD:
+        warnings.warn(
+            "The `NO_SHARD` sharding strategy is deprecated. If having issues, "
+            "please use `DistributedDataParallel` instead.",
+            FutureWarning,
+            # Level 1 is here, level 2 is from `FullyShardedDataParallel`, and
+            # level 3 is from the true caller
+            stacklevel=3,
+        )
+    state.sharding_strategy = sharding_strategy or ShardingStrategy.FULL_SHARD
+    state.mixed_precision = mixed_precision or MixedPrecision()
+    if mixed_precision is not None:
+        torch._C._log_api_usage_once(
+            f"torch.distributed.fsdp.mixed_precision.{str(state.mixed_precision)}"
+        )
+    state._use_full_prec_in_eval = (
+        os.environ.get(_FSDP_USE_FULL_PREC_IN_EVAL, "") == "1"
+    )
+    state.cpu_offload = cpu_offload or CPUOffload()
+    state.limit_all_gathers = limit_all_gathers
+    state._use_orig_params = use_orig_params
+    state.training_state = TrainingState.IDLE
+    state._is_root = None
+    state._free_event_queue = _FreeEventQueue()
+    state._debug_level = dist.get_debug_level()
+    state._exec_order_data = exec_order_utils._ExecOrderData(
+        state._debug_level,
+        backward_prefetch_limit,
+        forward_prefetch_limit,
+    )
+    state._unshard_event = None
+    # Mapping from fully sharded module to the handles it is responsible to
+    # unshard and reshard (see [Note: Fully Sharded Module])
+    _fully_sharded_module_to_handle: Dict[nn.Module, FlatParamHandle] = {}
+    state._fully_sharded_module_to_handle = _fully_sharded_module_to_handle
+    # Invariant: `state.params` contains exactly the `FlatParameter`s of the
+    # handles in `state._handle`
+    _handle: Optional[FlatParamHandle] = None
+    state._handle = _handle
+    params: List[FlatParameter] = []
+    state.params = params
+    return state
+
+
+@no_type_check
+def _init_runtime_state(
+    state: _FSDPState,
+) -> _FSDPState:
+    _root_pre_forward_handles: List[RemovableHandle] = []
+    state._root_pre_forward_handles = _root_pre_forward_handles
+    _pre_forward_handles: List[RemovableHandle] = []
+    state._pre_forward_handles = _pre_forward_handles
+    _post_forward_handles: List[RemovableHandle] = []
+    state._post_forward_handles = _post_forward_handles
+    state._sync_gradients = True
+    state._comm_hook = None
+    state._comm_hook_state = None
+    # Used to prevent running the pre-backward hook multiple times
+    return state
+
+
+@no_type_check
+def _init_prefetching_state(
+    state: _FSDPState,
+    backward_prefetch: BackwardPrefetch,
+    forward_prefetch: bool,
+) -> _FSDPState:
+    state.backward_prefetch = backward_prefetch
+    state.forward_prefetch = forward_prefetch
+    # The data structures use tuples of handles to generalize over the case
+    # where a module's forward involves multiple handles.
+    return state
+
+
+@no_type_check
+def _init_extension(state: _FSDPState, device_mesh: DeviceMesh = None) -> _FSDPState:
+    # TODO: we need to add additional check once we support FSDP + PiPPy.
+    # This check is currently sufficient, since we only support FSDP + TP.
+    root_mesh = _mesh_resources.get_root_mesh(device_mesh)
+    # if a root mesh is not the same as device_mesh,
+    # meaning the device_mesh is sliced out from the root mesh.
+    if device_mesh and root_mesh != state._device_mesh:
+        state._fsdp_extension = DTensorExtensions(state._device_handle)
+    else:
+        # We need to explicilty set _fsdp_extension to None.
+        # Otherwise, we will run into an infinite recursion when getting the attribute.
+        state._fsdp_extension = None
+    return state
+
+
+@no_type_check
+def _init_state_dict_state(state: _FSDPState) -> _FSDPState:
+    state._state_dict_type = StateDictType.FULL_STATE_DICT
+    state_dict_config: StateDictConfig = FullStateDictConfig()
+    state._optim_state_dict_config = FullOptimStateDictConfig()
+    state._state_dict_config = state_dict_config
+    unshard_params_ctx: Dict[nn.Module, Generator] = {}
+    state._unshard_params_ctx = unshard_params_ctx
+
+    return state
+
+
+def _verify_managed_params(module: nn.Module, params: List[nn.Parameter]) -> None:
+    """
+    Verify if the parameters are accepted by FSDP. The only restriction now
+    is that the parameter cannot be a scalar tensor (param.shape == []).
+    """
+    for param in params:
+        if len(param.shape) == 0:
+            param_name = ""
+            for name, param_ in module.named_parameters():
+                if param is param_:
+                    param_name = name
+                    break
+            assert param_name
+            raise ValueError(
+                "FSDP doesn't support salar parameters. "
+                f"Change {param_name} to a 1D tensor with numel equal to 1."
+            )
+
+
+@no_type_check
+def _init_param_handle_from_module(
+    state: _FSDPState,
+    fully_sharded_module: nn.Module,
+    device_id: Optional[Union[int, torch.device]],
+    param_init_fn: Optional[Callable[[nn.Module], None]],
+    sync_module_states: bool,
+) -> _FSDPState:
+    """Initialize a ``FlatParamHandle`` from a module ``fully_sharded_module``."""
+    _check_single_device_module(fully_sharded_module, state._ignored_params, device_id)
+    device_from_device_id = _get_device_from_device_id(
+        device_id, state.rank, state._device_handle
+    )
+    is_meta_module, is_torchdistX_deferred_init = _need_to_materialize_module(
+        fully_sharded_module, state._ignored_params, state._ignored_modules
+    )
+    # Materialize the module if needed
+    if (is_meta_module or is_torchdistX_deferred_init) and param_init_fn is not None:
+        _materialize_with_param_init_fn(
+            fully_sharded_module, param_init_fn, state._ignored_modules
+        )
+    elif is_meta_module:
+        _materialize_meta_module(
+            fully_sharded_module,
+            device_id,
+            state._ignored_modules,
+            state._device_handle,
+        )
+    elif is_torchdistX_deferred_init:
+        deferred_init.materialize_module(
+            fully_sharded_module,
+            check_fn=lambda submodule: _get_module_fsdp_state(submodule) is None
+            and submodule not in state._ignored_modules,
+        )
+
+    ignored_buffers = {
+        buffer
+        for ignored_module in state._ignored_modules
+        for buffer in ignored_module.buffers()
+    }
+
+    _move_module_to_device(
+        fully_sharded_module,
+        state._ignored_params,
+        ignored_buffers,
+        device_from_device_id,
+    )
+    state.compute_device = _get_compute_device(
+        fully_sharded_module,
+        state._ignored_params,
+        device_from_device_id,
+        state.rank,
+        state._device_handle,
+    )
+
+    managed_params = list(_get_orig_params(fully_sharded_module, state._ignored_params))
+    _verify_managed_params(fully_sharded_module, managed_params)
+    if sync_module_states:
+        _sync_module_params_and_buffers(
+            fully_sharded_module, managed_params, state.process_group
+        )
+        if state.sharding_strategy in HYBRID_SHARDING_STRATEGIES:
+            _sync_module_params_and_buffers(
+                fully_sharded_module, managed_params, state._inter_node_pg
+            )
+    _init_param_handle_from_params(state, managed_params, fully_sharded_module)
+    return state
+
+
+@no_type_check
+def _init_param_handle_from_params(
+    state: _FSDPState,
+    params: List[nn.Parameter],
+    fully_sharded_module: nn.Module,
+):
+    if len(params) == 0:
+        return
+    handle = FlatParamHandle(
+        params,
+        fully_sharded_module,
+        state.compute_device,
+        SHARDING_STRATEGY_MAP[state.sharding_strategy],
+        state.cpu_offload.offload_params,
+        state.mixed_precision.param_dtype,
+        state.mixed_precision.reduce_dtype,
+        state.mixed_precision.keep_low_precision_grads,
+        state.process_group,
+        state._use_orig_params,
+        fsdp_extension=state._fsdp_extension,
+    )
+    handle.shard()
+    assert not state._handle
+    state.params.append(handle.flat_param)
+    state._handle = handle
+    state._fully_sharded_module_to_handle[handle._fully_sharded_module] = handle
+    cpu_device = torch.device("cpu")
+    if state.cpu_offload.offload_params and handle.flat_param.device != cpu_device:
+        handle.flat_param_to(cpu_device)
+
+
+def _get_ignored_modules(
+    root_module: nn.Module,
+    _ignored_modules: Optional[Iterable[torch.nn.Module]],
+) -> Set[nn.Module]:
+    """
+    Check that ``_ignored_modules`` is an iterable of ``nn.Module`` s without any FSDP instances.
+
+    Return the modules contained in their module
+    subtrees as a :class:`set`. Nested FSDP instances are excluded, but their
+    already-computed ignored modules are included.
+
+    ``_ignored_modules`` represents the argument passed by the user to FSDP.
+    """
+    msg_prefix = "`ignored_modules` should be an iterable of `torch.nn.Module`s "
+    try:
+        ignored_root_modules = (
+            set(_ignored_modules) if _ignored_modules is not None else set()
+        )
+    except TypeError as e:
+        raise TypeError(msg_prefix + f"but got {type(_ignored_modules)}") from e
+    for module in ignored_root_modules:
+        if not isinstance(module, torch.nn.Module):
+            raise TypeError(msg_prefix + f"but got an iterable with {type(module)}")
+        if _get_module_fsdp_state(module):
+            # TODO: We may relax this by taking the FSDP instance's wrapped
+            # module to provide more flexibility to the user.
+            raise ValueError("`ignored_modules` should not include FSDP modules")
+    # Treat modules that cannot compose with `fully_shard` as ignored modules,
+    # meaning that their subtrees are ignored
+    for module in root_module.modules():
+        if not traversal_utils._composable(module):
+            ignored_root_modules.add(module)
+    # NOTE: Even if `ignored_root_modules` is empty, do not return early so
+    # that this FSDP instance can get any ignored modules from its children.
+
+    # Include child modules and exclude nested FSDP modules themselves
+    ignored_modules = {
+        child
+        for module in ignored_root_modules
+        for child in module.modules()
+        if not isinstance(child, fsdp_file.FullyShardedDataParallel)
+    }
+    if root_module in ignored_modules:
+        warnings.warn(
+            "Trying to ignore the top-level module passed into the FSDP "
+            "constructor itself will result in all parameters being "
+            f"ignored and is not well-supported: {module}"
+        )
+    # Include nested FSDP modules' ignored modules
+    for submodule in root_module.modules():
+        optional_fsdp_state = _get_module_fsdp_state(submodule)
+        if optional_fsdp_state is not None:
+            assert hasattr(optional_fsdp_state, "_ignored_modules")
+            ignored_modules.update(optional_fsdp_state._ignored_modules)
+    return ignored_modules
+
+
+def _get_ignored_params(
+    root_module: torch.nn.Module,
+    ignored_modules: Set[torch.nn.Module],
+    ignored_parameters: Optional[Iterable[torch.nn.Parameter]] = None,
+) -> Set[torch.nn.Parameter]:
+    """
+    Return the parameters of the modules in ``ignored_modules`` and the parameters in ``ignored_parameters``.
+
+    :class:`FlatParameter` s are excluded from the result.
+    """
+    all_ignored_params: Set[torch.nn.Parameter] = set()
+
+    params_in_ignored_modules = {
+        p for m in ignored_modules for p in m.parameters() if not _is_fsdp_flattened(p)
+    }
+
+    all_ignored_params.update(params_in_ignored_modules)
+
+    if ignored_parameters is not None:
+        params_in_ignored_parameters = {
+            p for p in ignored_parameters if not _is_fsdp_flattened(p)
+        }
+        all_ignored_params.update(params_in_ignored_parameters)
+
+    # Always include nested FSDP modules' ignored parameters
+    for submodule in root_module.modules():
+        optional_fsdp_state = _get_module_fsdp_state(submodule)
+        if optional_fsdp_state is not None:
+            assert hasattr(optional_fsdp_state, "_ignored_params")
+            all_ignored_params.update(optional_fsdp_state._ignored_params)
+
+    return all_ignored_params
+
+
+def _get_ignored_buffer_names(
+    root_module: torch.nn.Module,
+    ignored_modules: Set[torch.nn.Module],
+) -> Set[str]:
+    """Return the cleaned buffer FQNs in ``ignored_modules``."""
+    all_ignored_buffer_names: Set[str] = set()
+
+    buffers_in_ignored_modules = {
+        buffer for m in ignored_modules for buffer in m.buffers()
+    }
+
+    all_ignored_buffer_names.update(
+        {
+            clean_tensor_name(buffer_name)
+            for buffer_name, buffer in root_module.named_buffers()
+            if buffer in buffers_in_ignored_modules
+        }
+    )
+
+    # Always include nested FSDP modules' ignored buffer names
+    for submodule in root_module.modules():
+        optional_fsdp_state = _get_module_fsdp_state(submodule)
+        if optional_fsdp_state is not None:
+            assert hasattr(optional_fsdp_state, "_ignored_buffer_names")
+            all_ignored_buffer_names.update(optional_fsdp_state._ignored_buffer_names)
+
+    return all_ignored_buffer_names
+
+
+def _get_buffer_names(root_module: nn.Module) -> Set[str]:
+    """Return the fully prefixed names of all buffers in the module hierarchy rooted at ``root_module`` as a class:`set`."""
+    return {
+        clean_tensor_name(buffer_name) for buffer_name, _ in root_module.named_buffers()
+    }
+
+
+def _check_single_device_module(
+    module: nn.Module,
+    ignored_params: Set[nn.Parameter],
+    device_id: Optional[Union[int, torch.device]],
+) -> None:
+    """
+    Raise an error if ``module`` has original parameters on multiple devices, ignoring the parameters in ``ignored_params``.
+
+    Thus, after this method, the
+    module must be either fully on the CPU or fully on a non-CPU device.
+    """
+    devices = {param.device for param in _get_orig_params(module, ignored_params)}
+    # We allow module to be partially on CPU and partially on GPU if device_id is not
+    # None, since the device_id arg will result in the CPU portion being moved to
+    # GPU. This is useful in cases where part of the module may be parallelized
+    # by another algorithm and may already be on GPU. We'd like to enforce device_id
+    # to not be None, otherwise we'd flatten parameters in a mixed module which is
+    # not supported.
+    if len(devices) == 2 and torch.device("cpu") in devices:
+        if device_id is None:
+            raise RuntimeError(
+                "To support a module with both CPU and GPU params, "
+                "please pass in device_id argument."
+            )
+    elif len(devices) > 1:
+        raise RuntimeError(
+            f"FSDP only supports single device modules but got params on {devices}"
+        )
+
+
+def _get_device_from_device_id(
+    device_id: Optional[Union[int, torch.device]],
+    rank: int,
+    device_handle: _FSDPDeviceHandle,
+) -> Optional[torch.device]:
+    """
+    Return a ``torch.device`` for the specified ``device_id``.
+
+    Processes ``device_id`` and returns either the corresponding device or
+    ``None`` if ``device_id`` is ``None``.
+    """
+    if device_id is None:
+        return None
+    device = (
+        device_id if isinstance(device_id, torch.device) else torch.device(device_id)
+    )
+    if device.type != "cpu" and device.index is None:
+        warnings.warn(
+            f"FSDP got the argument `device_id` {device_id} on rank "
+            f"{rank}, which does not have an explicit index. "
+            f"FSDP will use the current device {device_handle.current_device()}. "
+            f"If this is incorrect, please explicitly call `torch.{device.type}.set_device()` "
+            "before FSDP initialization or pass in the explicit device "
+            "index as the `device_id` argument."
+        )
+        device = torch.device(device_handle.current_device())
+    return device
+
+
+def _need_to_materialize_module(
+    module: nn.Module,
+    ignored_params: Set[nn.Parameter],
+    ignored_modules: Set[nn.Module],
+) -> Tuple[bool, bool]:
+    """
+    Return if ``module`` has parameters on meta device and if ``module`` is using torchdistX deferred initialization.
+
+    At most of the returned bools can
+    be ``True``. If either is ``True``, then ``module`` needs to be
+    materialized.
+    """
+    managed_params = list(_get_orig_params(module, ignored_params))
+    is_meta_module = any(param.is_meta for param in managed_params)
+    # TODO: We need to establish a contract for FSDP and buffers. For now, we
+    # skip checking for meta buffers from ignored modules. We should consider
+    # refactoring the initialization holistically to avoid so many traversals.
+    for submodule in module.modules():
+        if submodule in ignored_modules:
+            continue
+        for buf in submodule.buffers(recurse=False):
+            is_meta_module |= buf.is_meta
+    is_torchdistX_deferred_init = (
+        not is_meta_module
+        and _TORCHDISTX_AVAIL
+        and any(fake.is_fake(param) for param in managed_params)
+    )
+    return is_meta_module, is_torchdistX_deferred_init
+
+
+def _materialize_with_param_init_fn(
+    root_module: nn.Module,
+    param_init_fn: Callable[[nn.Module], None],
+    ignored_modules: Set[nn.Module],
+) -> None:
+    if not callable(param_init_fn):
+        raise ValueError(
+            f"Expected {param_init_fn} to be callable but got {type(param_init_fn)}"
+        )
+    modules_to_materialize = _get_modules_to_materialize(root_module, ignored_modules)
+    for module in modules_to_materialize:
+        param_init_fn(module)
+
+
+def _materialize_meta_module(
+    root_module: nn.Module,
+    device_from_device_id: Optional[torch.device],
+    ignored_modules: Set[nn.Module],
+    device_handle: _FSDPDeviceHandle,
+):
+    # Run default meta device initialization
+    materialization_device = device_from_device_id or torch.device(
+        device_handle.current_device()
+    )
+    modules_to_materialize = _get_modules_to_materialize(root_module, ignored_modules)
+    module = None
+    try:
+        # Assume that each module's `reset_parameters()` only initializes its
+        # own parameters and not those of its children
+        with torch.no_grad():
+            for module in modules_to_materialize:
+                # As a contract to the user, only call `reset_parameters()` if
+                # the module has directly managed parameters/buffers
+                module_state_iter = itertools.chain(
+                    module.parameters(recurse=False), module.buffers(recurse=False)
+                )
+                has_module_states = len(list(module_state_iter)) > 0
+                if has_module_states:
+                    module.to_empty(device=materialization_device, recurse=False)
+                    module.reset_parameters()  # type: ignore[operator]
+    except BaseException as e:
+        warnings.warn(
+            "Unable to call `reset_parameters()` for module on meta "
+            f"device with error {str(e)}. Please ensure that your module of"
+            f"type {type(module)} implements a `reset_parameters()` method."  # type: ignore[possibly-undefined]
+        )
+        raise e
+
+
+def _get_modules_to_materialize(
+    root_module: nn.Module, ignored_modules: Set[nn.Module]
+) -> List[nn.Module]:
+    # Run BFS to collect the modules to materialize via `reset_parameters()`,
+    # stopping at any module with FSDP already applied or at ignored modules.
+    modules_to_materialize: List[nn.Module] = []
+    queue = collections.deque([root_module])
+    visited_modules: Set[nn.Module] = {root_module}
+    while queue:
+        module = queue.popleft()
+        modules_to_materialize.append(module)
+        for child_module in module.children():
+            if (
+                child_module not in visited_modules
+                and _get_module_fsdp_state(child_module) is None
+                and child_module not in ignored_modules
+            ):
+                visited_modules.add(child_module)
+                queue.append(child_module)
+    return modules_to_materialize
+
+
+def _move_module_to_device(
+    module: nn.Module,
+    ignored_params: Set[nn.Parameter],
+    ignored_buffers: Set[torch.Tensor],
+    device_from_device_id: Optional[torch.device],
+) -> None:
+    """
+    Move ``module`` depending on ``device_from_device_id`` and its current device.
+
+    This includes moving ignored modules' parameters.
+
+    - If ``device_from_device_id`` is not ``None``, then this moves
+    ``module`` to the device.
+    - If ``device_from_device_id`` is ``None``, then this does not move
+    ``module`` but warns the user if it is on CPU.
+
+    Precondition: ``_check_single_device_module()``.
+    """
+    cpu_device = torch.device("cpu")
+    if device_from_device_id is not None:
+        # BFS from `module` without traversing any nested FSDP instances to
+        # collect the parameters/buffers that have not yet been managed
+        queue: Deque[nn.Module] = collections.deque()
+        queue.append(module)
+        params: List[nn.Parameter] = []
+        buffers: List[torch.Tensor] = []
+        while queue:
+            curr_module = queue.popleft()
+            # NOTE: We include a check to only move parameters/buffers that are
+            # on CPU device. If they are on a CUDA device different from the
+            # one specified by `device_id`, then this does NOT move them. This
+            # is so that we can raise an error in `_get_compute_device()`.
+            params.extend(
+                param
+                for param in curr_module.parameters(recurse=False)
+                if param.device == cpu_device
+            )
+            buffers.extend(
+                buffer
+                for buffer in curr_module.buffers(recurse=False)
+                if buffer.device == cpu_device
+            )
+            for submodule in curr_module.children():
+                if not isinstance(submodule, fsdp_file.FullyShardedDataParallel):
+                    queue.append(submodule)
+        params_to_move = [p for p in params if p not in ignored_params]
+        bufs_to_move = [p for p in buffers if p not in ignored_buffers]
+        _move_states_to_device(params_to_move, bufs_to_move, device_from_device_id)
+        return
+    param = next(_get_orig_params(module, ignored_params), None)
+    if param is not None and param.device == cpu_device:
+        _warn_cpu_init()
+
+
+def _move_states_to_device(
+    params: List[nn.Parameter],
+    buffers: List[torch.Tensor],
+    device_from_device_id: Optional[torch.device],
+) -> None:
+    """
+    Move states to the specified device.
+
+    Precondition: ``_check_single_device_module()`` and module's parameters and
+    buffers have been materialized if needed.
+    """
+    if len(params) == 0 and len(buffers) == 0:
+        return
+    if len(params) > 0:
+        current_device = params[0].device
+    elif len(buffers) > 0:
+        current_device = buffers[0].device
+    cpu_device = torch.device("cpu")
+    if device_from_device_id is not None:
+        # Move the parameters and buffers like the `.data` code path in
+        # `nn.Module._apply()`, which underlies `nn.Module.to()`
+        for param in params:
+            with torch.no_grad():
+                param.data = param.to(device_from_device_id)
+                if param.grad is not None:
+                    param.grad.data = param.grad.to(device_from_device_id)
+        for buffer in buffers:
+            buffer.data = buffer.to(device_from_device_id)
+    elif current_device == cpu_device:  # type: ignore[possibly-undefined]
+        _warn_cpu_init()
+
+
+def _warn_cpu_init():
+    warnings.warn(
+        "The passed-in `module` is on CPU and will thus have FSDP's sharding "
+        "initialization run on CPU, which may be slower than on GPU. We "
+        "recommend passing in the `device_id` argument for FSDP to move "
+        "`module` to GPU for the sharding initialization. `module` must also "
+        "be on GPU device to work with the `sync_module_states=True` flag "
+        "since that requires GPU communication."
+    )
+
+
+def _get_compute_device(
+    module: nn.Module,
+    ignored_params: Set[nn.Parameter],
+    device_from_device_id: Optional[torch.device],
+    rank: int,
+    device_handle: _FSDPDeviceHandle,
+) -> torch.device:
+    """
+    Determine and return this FSDP instance's compute device.
+
+    If the module is already on a non-CPU device, then the compute device is that non-CPU
+    device. If the module is on CPU, then the compute device is the current
+    device.
+
+    Since this method should be called after materializing the module, any
+    non-CPU device should not be meta device. For now, the compute device is
+    always a CUDA or CUDA-like device with its explicit index.
+
+    Precondition: ``_check_single_device_module()`` and
+    ``_move_module_to_device()``.
+    """
+    param = next(_get_orig_params(module, ignored_params), None)
+    if param is not None and param.device.type != "cpu":
+        compute_device = param.device  # Determined by model param placement
+    else:
+        compute_device = torch.device(device_handle.current_device())
+    if device_from_device_id is not None and compute_device != device_from_device_id:
+        raise ValueError(
+            f"Inconsistent compute device and `device_id` on rank {rank}: "
+            f"{compute_device} vs {device_from_device_id}"
+        )
+    return compute_device
+
+
+# TODO: See how to deprecate!
+def _sync_module_params_and_buffers(
+    module: nn.Module,
+    params: List[nn.Parameter],
+    process_group: dist.ProcessGroup,
+) -> None:
+    """
+    Synchronize module states (i.e. parameters ``params`` and all not-yet-synced buffers) by broadcasting from rank 0 to all ranks.
+
+    Precondition: ``sync_module_states == True`` and ``self.process_group`` has
+    been set.
+    """
+    module_states: List[torch.Tensor] = []
+    for buffer in module.buffers():
+        # Avoid re-synchronizing buffers in case of nested wrapping
+        if not getattr(buffer, FSDP_SYNCED, False):
+            setattr(buffer, FSDP_SYNCED, True)
+            detached_buffer = buffer.detach()
+            if is_traceable_wrapper_subclass(detached_buffer):
+                # NOTE: Here we assume no nested subclasses, at most one level of subclass
+                # in both model's buffers and params
+                attrs, _ = detached_buffer.__tensor_flatten__()  # type: ignore[attr-defined]
+                inner_buffers = [getattr(detached_buffer, attr) for attr in attrs]
+                module_states.extend(inner_buffers)
+            else:
+                module_states.append(detached_buffer)
+
+    for param in params:
+        detached_param = param.detach()
+        if is_traceable_wrapper_subclass(detached_param):
+            attrs, _ = detached_param.__tensor_flatten__()  # type: ignore[attr-defined]
+            inner_params = [getattr(detached_param, attr) for attr in attrs]
+            module_states.extend(inner_params)
+        else:
+            module_states.append(detached_param)
+
+    _check_module_states_for_sync_module_states(module_states)
+    _sync_params_and_buffers(
+        process_group,
+        module_states,
+        PARAM_BROADCAST_BUCKET_SIZE,
+        src=0,
+    )
+
+
+def _check_module_states_for_sync_module_states(
+    module_states: List[torch.Tensor],
+) -> None:
+    if module_states and any(
+        tensor.device == torch.device("cpu") for tensor in module_states
+    ):
+        raise ValueError(
+            "The module has CPU parameters or buffers when `sync_module_states=True`, "
+            "which requires them to be on GPU. Please specify the `device_id` argument "
+            "or move the module to GPU before passing it to FSDP."
+        )
+
+
+def _get_orig_params(
+    module: nn.Module,
+    ignored_params: Set[nn.Parameter],
+) -> Iterator[nn.Parameter]:
+    """
+    Return an iterator over the original parameters in ``module``.
+
+    The iterator does not return
+    the parameters in ``ignored_params``, any ``FlatParameter`` s (which may be
+    present due to nested FSDP wrapping), or any original parameters already
+    flattened (only relevant when ``use_orig_params=True``).
+    """
+    param_gen = module.parameters()
+    try:
+        while True:
+            param = next(param_gen)
+            if param not in ignored_params and not _is_fsdp_flattened(param):
+                yield param
+    except StopIteration:
+        pass
+
+
+def _check_orig_params_flattened(
+    fsdp_module,
+    ignored_params: Set[nn.Parameter],
+) -> None:
+    """
+    Check that original parameters in ``fsdp_module`` have been flattened.
+
+    The flattened parameters are made
+    invisible to ``named_parameters()`` for the module hierarchy rooted at
+    ``fsdp_module``. This should be called as a sanity check after flattening
+    the wrapped module's parameters.
+    """
+    for param_name, param in _named_parameters_with_duplicates(fsdp_module):
+        if param not in ignored_params and not _is_fsdp_flattened(param):
+            raise RuntimeError(
+                f"Found an unflattened parameter: {param_name}; "
+                f"{param.size()} {param.__class__}"
+            )
+
+
+def _get_default_comm_hook(sharding_strategy: ShardingStrategy):
+    return (
+        default_hooks.allreduce_hook
+        if sharding_strategy == ShardingStrategy.NO_SHARD
+        else default_hooks.reduce_scatter_hook
+    )
+
+
+def _get_default_comm_hook_state(
+    process_group: dist.ProcessGroup,
+) -> default_hooks.DefaultState:
+    return default_hooks.DefaultState(process_group=process_group)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_limiter_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_limiter_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..5cc56b29f84d4a92dfa0debc2229d8105e378c99
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_limiter_utils.py
@@ -0,0 +1,33 @@
+import collections
+from typing import Deque, Optional
+
+import torch
+
+
+class _FreeEventQueue:
+    """
+    This tracks all pending frees corresponding to inflight all-gathers. The
+    queueing pattern is iterative enqueues with a single dequeue per iteration
+    once the limit ``_max_num_inflight_all_gathers`` is reached.
+    """
+
+    def __init__(self) -> None:
+        self._queue: Deque[torch.Event] = collections.deque()
+        self._max_num_inflight_all_gathers = 2  # empirically chosen
+
+    def enqueue(self, free_event: torch.Event) -> None:
+        """Enqueues a free event."""
+        self._queue.append(free_event)
+
+    def dequeue_if_needed(self) -> Optional[torch.Event]:
+        """Dequeues a single event if the limit is reached."""
+        if len(self._queue) >= self._max_num_inflight_all_gathers:
+            return self._dequeue()
+        return None
+
+    def _dequeue(self) -> Optional[torch.Event]:
+        """Dequeues a free event if possible."""
+        if self._queue:
+            event = self._queue.popleft()
+            return event
+        return None
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_optim_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_optim_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..35beee36ef583900a512d8f2665806645662c6f5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_optim_utils.py
@@ -0,0 +1,2091 @@
+# mypy: allow-untyped-defs
+import copy
+import functools
+import logging
+import warnings
+from contextlib import ExitStack
+from dataclasses import dataclass, field
+from typing import (
+    Any,
+    cast,
+    Dict,
+    Iterable,
+    Iterator,
+    List,
+    NamedTuple,
+    no_type_check,
+    Optional,
+    Sequence,
+    Set,
+    Tuple,
+    TYPE_CHECKING,
+    Union,
+)
+
+import torch
+import torch.distributed as dist
+import torch.distributed.fsdp._traversal_utils as traversal_utils
+import torch.nn as nn
+from torch.distributed._state_dict_utils import _gather_state_dict
+from torch.distributed.distributed_c10d import _get_pg_default_device
+from torch.distributed.fsdp._common_utils import (
+    _apply_to_modules,
+    _FSDPState,
+    _get_module_fsdp_state_if_fully_sharded_module,
+    _get_param_to_fqns,
+    _module_handle,
+    _named_parameters_with_duplicates,
+    clean_tensor_name,
+)
+from torch.distributed.fsdp._debug_utils import SimpleProfiler
+from torch.distributed.fsdp._flat_param import FlatParameter, FlatParamHandle
+from torch.distributed.fsdp._fsdp_extensions import (
+    _ext_chunk_dtensor,
+    _ext_chunk_tensor,
+)
+from torch.distributed.fsdp._runtime_utils import (
+    _lazy_init,
+    _reset_flat_param_grad_info_if_needed,
+)
+from torch.distributed.fsdp.api import (
+    ShardingStrategy,
+    StateDictSettings,
+    StateDictType,
+)
+from torch.distributed.tensor import DTensor, Replicate
+from torch.utils._pytree import tree_map_only
+
+
+if TYPE_CHECKING:
+    from torch.distributed._shard.sharded_tensor import ShardedTensor
+
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class FSDPParamInfo:
+    state: _FSDPState
+    handle: FlatParamHandle
+    param_indices: Dict[str, int]
+    param_requires_grad: List[bool]
+
+
+def sorted_items(dictionary: Dict[str, Any]) -> Iterator[Tuple[str, Any]]:
+    keys = sorted(dictionary.keys())
+    for k in keys:
+        yield k, dictionary[k]
+
+
+@dataclass
+class _ConsolidatedOptimState:
+    """
+    This holds the consolidated optimizer state on the target rank. Positive-
+    dimension tensor state is communicated across ranks, while zero-dimension
+    tensor state and non-tensor state is taken directly from the target rank.
+
+    PyTorch version 1.12 moved to using zero-dimension tensors for scalar
+    values, but user implemented optimizers may still use float (i.e. a
+    non-tensor). Thus, we support both and handle them identically.
+
+    Attributes:
+        tensor_state (Dict[str, torch.Tensor]): Mapping from positive-dimension
+            tensor state name to the unsharded flat tensor representing the
+            state.
+        zero_dim_tensor_state (Dict[str, torch.Tensor]): Mapping from zero-
+            dimension tensor state name to its value.
+        non_tensor_state (Dict[str, Any]): Mapping from non-tensor state
+            name to its value.
+    """
+
+    tensor_state: Dict[str, torch.Tensor] = field(default_factory=dict)
+    zero_dim_tensor_state: Dict[str, torch.Tensor] = field(default_factory=dict)
+    non_tensor_state: Dict[str, Any] = field(default_factory=dict)
+
+
+class _PosDimTensorInfo(NamedTuple):
+    """
+    Meatadata for positive-dimension tensors used internally for
+    :meth:`scatter_full_optim_state_dict`.
+
+    Attributes:
+        shape (torch.Size): Sharded tensor shape (which is equal to the
+            unsharded tensor shape if the tensor is optimizer state for a
+            non-FSDP parameter and is hence not sharded).
+        dtype (torch.dtype): Data type of the tensor.
+    """
+
+    shape: torch.Size
+    dtype: torch.dtype
+
+
+class _OptimStateKey(NamedTuple):
+    """
+    This represents an optimizer state key that may be used commonly across
+    ranks. It is based on the unflattened parameter names rather than parameter
+    IDs to make it independent of each rank's own optimizer construction.
+    """
+
+    unflat_param_names: Tuple[str, ...]
+    is_fsdp_managed: bool
+
+
+def _unflatten_optim_state(
+    fsdp_param_info: FSDPParamInfo,
+    flat_param_state: Dict[str, Any],
+    to_save: bool,
+    shard_state: bool,
+    cpu_offload: bool,
+) -> List[Dict[str, Any]]:
+    """
+    Unflattens the optimizer state, consisting of the "state" part and the
+    "param_groups" part. Unflattening the "state" part involves consolidating
+    the state on the target rank and remapping from flattened to unflattened
+    parameter IDs, and the "param_groups" part only involves remapping from
+    flattened to unflattened parameter IDs.
+
+    Args:
+        fsdp_param_info (FSDPParamInfo): The FSDP state, the handle, and a
+            mapping from FQN to original parameter index.
+        flat_param_state (Dict[str, Any]): Entry for the flat parameter in the
+            "state" part of the optimizer state dict.
+        to_save (bool): Whether to save the state on this rank.
+
+    Returns:
+        List[Dict[str, Any]]: A :class:`list` holding the entries in the
+        "state" part of the optimizer state dict corresponding to the
+        unflattened parameters comprising the flat parameter if on the target
+        rank or an empty :class:`list` otherwise. The final optimizer state
+        dict will need to map these entries using the proper unflattened
+        parameter IDs.
+    """
+    assert (
+        not shard_state or to_save
+    ), "If ``shard_state`` is True, ``to_save`` has to be True."
+    consolidated_state = _communicate_optim_state(
+        fsdp_param_info,
+        flat_param_state,
+    )
+    if to_save:
+        unflat_param_state = _unflatten_communicated_optim_state(
+            fsdp_param_info,
+            consolidated_state,
+            shard_state,
+        )
+        for optim_state in unflat_param_state:
+            # We can't use .items() below cuz we'd run into a concurrent modification error
+            if cpu_offload:
+                for key in list(optim_state.keys()):
+                    state = optim_state[key]
+                    if not isinstance(state, torch.Tensor):
+                        continue
+                    optim_state[key] = state.cpu()
+        return unflat_param_state
+    else:
+        return []
+
+
+def _is_zero_dim_tensor(x: Any) -> bool:
+    return torch.is_tensor(x) and x.dim() == 0
+
+
+def _communicate_optim_state(
+    fsdp_param_info: FSDPParamInfo,
+    flat_param_state: Dict[str, Any],
+) -> _ConsolidatedOptimState:
+    """
+    Communicates the optimizer state for a flat parameter across ranks. All
+    ranks will hold the entire non-sharded optimizer state on GPU.
+
+    If ``N`` is the number of tensor optimizer states in the optimizer state
+    dict, then the communication complexity is 0 if ``N = 0`` and ``N + 1``
+    otherwise (where the plus 1 comes from all-gathering the padding per rank).
+
+    Args:
+        fsdp_param_info (FSDPParamInfo): The FSDP state, the handle, and a
+            mapping from FQN to original parameter index.
+        flat_param_state (Dict[str, Any]): The entry in the "state" part of the
+            optimizer state dict corresponding to the flat parameter.
+
+    Returns:
+        ConsolidatedOptimState: Consolidated optimizer state for the target
+        flat parameter.
+    """
+    fsdp_state = fsdp_param_info.state
+    flat_param = fsdp_param_info.handle.flat_param
+    state = _ConsolidatedOptimState()
+    tensor_state, zero_dim_tensor_state, non_tensor_state = (
+        state.tensor_state,
+        state.zero_dim_tensor_state,
+        state.non_tensor_state,
+    )
+
+    for state_name, value in sorted_items(flat_param_state):
+        # Positive-dimension tensor state: communicate across ranks
+        if torch.is_tensor(value) and value.dim() > 0:
+            # If the parameter is not sharded, then neither is the
+            # positive-dimension tensor state, so no need to communicate it --
+            # we take the target rank's value
+            if (
+                fsdp_state.world_size == 1
+                or fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD
+            ):
+                tensor_state[state_name] = value
+                continue
+            assert (
+                fsdp_state.compute_device is not None
+            ), "compute_device has not been initialized"
+            if value.device.type != fsdp_state.compute_device.type:
+                value = value.to(fsdp_state.compute_device)
+            # Assume that positive-dimension tensor optimizer state
+            # has the same shape as the sharded flat parameter
+            buffer_size = flat_param._full_param_padded.size()  # type: ignore[attr-defined]
+            tensor_buffer = value.new_zeros(*buffer_size)
+            dist.all_gather_into_tensor(
+                tensor_buffer, value, group=fsdp_state.process_group
+            )
+            fsdp_state._device_handle.synchronize()
+            unpadded_numel = cast(
+                nn.Parameter, flat_param._unpadded_unsharded_size
+            ).numel()
+            tensor_state[state_name] = tensor_buffer[:unpadded_numel]
+        # Zero-dimension tensor state and non-tensor state: take this rank's
+        # value directly
+        else:
+            if _is_zero_dim_tensor(value):
+                zero_dim_tensor_state[state_name] = value.detach().clone()
+            else:
+                non_tensor_state[state_name] = value
+    return state
+
+
+def _unflatten_communicated_optim_state(
+    fsdp_param_info: FSDPParamInfo,
+    state: _ConsolidatedOptimState,
+    shard_state: bool,
+) -> List[Dict[str, Any]]:
+    """
+    Unflattens the communicated optimizer state (given by ``tensor_state``,
+    ``non_tensor_state``, and ``zero_dim_tensor_state``) for a single flat
+    parameter. This should only be called on the target rank.
+
+    Args:
+        fsdp_param_info (FSDPParamInfo): The FSDP state, the handle, and a
+            mapping from FQN to original parameter index.
+        state (_ConsolidatedOptimState): Consolidated optimizer state.
+
+    Returns:
+        List[Dict[str, Any]]: A :class:`list` holding the entries in the
+        "state" part of the optimizer state dict corresponding to the
+        unflattened parameters comprising the flat parameter. The final
+        optimizer state dict will need to map these entries using the proper
+        unflattened parameter IDs.
+    """
+    fsdp_state = fsdp_param_info.state
+    handle = fsdp_param_info.handle
+    flat_param = handle.flat_param
+    unflat_param_state: List[Dict[str, Any]] = []
+    flat_param_views: Dict[str, Iterator] = {}
+    num_unflat_params = flat_param._num_params
+    tensor_state, zero_dim_tensor_state, non_tensor_state = (
+        state.tensor_state,
+        state.zero_dim_tensor_state,
+        state.non_tensor_state,
+    )
+
+    for _ in range(num_unflat_params):
+        unflat_state_param = {}
+        # Add positive-dimension tensor state: unflatten with views
+        for state_name, flat_tensor in sorted_items(tensor_state):
+            views_generated = state_name in flat_param_views
+            if not views_generated:
+                views = handle._get_unflat_views(flat_tensor)
+                flat_param_views[state_name] = views
+            else:
+                views = flat_param_views[state_name]
+            optim_state: Union[torch.Tensor, ShardedTensor, DTensor] = next(views)
+            if shard_state:
+                osd_config = fsdp_state._optim_state_dict_config
+                if getattr(osd_config, "_use_dtensor", False):
+                    assert fsdp_state._device_mesh is not None
+                    optim_state = _ext_chunk_dtensor(
+                        optim_state,
+                        fsdp_state.rank,
+                        fsdp_state._device_mesh,
+                        fsdp_state._fsdp_extension,
+                    )
+                else:
+                    assert fsdp_state.process_group is not None
+                    optim_state = _ext_chunk_tensor(
+                        optim_state,
+                        fsdp_state.rank,
+                        fsdp_state.world_size,
+                        fsdp_state._device_handle.device_count(),
+                        fsdp_state.process_group,
+                        fsdp_state._fsdp_extension,
+                    )
+            unflat_state_param[state_name] = optim_state
+
+        # Add zero-dimension tensor state: take the target rank's value
+        for state_name, zero_dim_tensor in sorted_items(zero_dim_tensor_state):
+            unflat_state_param[state_name] = zero_dim_tensor
+        # Add non-tensor state: take the target rank's value
+        for state_name, non_tensor in sorted_items(non_tensor_state):
+            unflat_state_param[state_name] = non_tensor
+        unflat_param_state.append(unflat_state_param)
+    return unflat_param_state
+
+
+def _broadcast_processed_state(
+    fsdp_state: _FSDPState,
+    optim_state: Dict[str, Any],
+    group: Optional[dist.ProcessGroup],
+) -> Dict[str, Any]:
+    objects: List[Any] = [None]
+    if dist.get_rank(group) == 0:
+        objects[0] = tree_map_only(
+            torch.Tensor,
+            lambda v: v.cpu() if v.dim() == 0 else _PosDimTensorInfo(v.shape, v.dtype),  # type: ignore[union-attr]
+            optim_state,
+        )
+    dist.broadcast_object_list(objects, src=0, group=group)
+    if dist.get_rank(group) == 0:
+        return optim_state
+    else:
+        return objects[0]
+
+
+def _broadcast_state(
+    fsdp_state: _FSDPState, state: Any, group: Optional[dist.ProcessGroup]
+) -> Any:
+    if dist.get_rank(group) == 0:
+        if not isinstance(state, torch.Tensor) or state.dim() == 0:
+            return state
+        tensor = state.to(fsdp_state.compute_device)
+    else:
+        if isinstance(state, torch.Tensor):
+            assert state.dim() == 0, (
+                "For non-zero ranks, a tensor state should have zero dimension, "
+                "but got the state with shape {state.shape()}."
+            )
+            return state
+        elif not isinstance(state, _PosDimTensorInfo):
+            return state
+        tensor = torch.zeros(
+            state.shape, dtype=state.dtype, device=fsdp_state.compute_device
+        )
+    dist.broadcast(tensor, src=0, group=group)
+    return tensor
+
+
+def _shard_orig_param_state(
+    fsdp_param_info: FSDPParamInfo,
+    fqn: str,
+    optim_state: Dict[str, Any],
+) -> Dict[str, Any]:
+    """
+    Shard the optimizer state for the original parameter with the name ``fqn``.
+    This API should only be used when ``use_orig_params`` is True.
+    """
+    if not optim_state:
+        return {}
+    fsdp_state = fsdp_param_info.state
+    flat_param = fsdp_param_info.handle.flat_param
+    param_idx = fsdp_param_info.param_indices[fqn]
+    shard_param_info = flat_param._shard_param_infos[param_idx]  # type: ignore[attr-defined]
+    optim_state = _gather_state_dict(
+        optim_state, pg=fsdp_state.process_group, device=fsdp_state.compute_device
+    )
+    if not shard_param_info.in_shard:
+        return {}
+    # Flatten and shard the state.
+    new_optim_state: Dict[str, Any] = {}
+    intra_param_start_idx = shard_param_info.intra_param_start_idx
+    intra_param_end_idx = shard_param_info.intra_param_end_idx
+    for state_name, value in optim_state.items():
+        if (
+            torch.is_tensor(value)
+            and value.dim() > 0
+            and fsdp_state.sharding_strategy != ShardingStrategy.NO_SHARD
+        ):
+            value = value.flatten()[intra_param_start_idx : intra_param_end_idx + 1].clone()  # type: ignore[operator]
+        new_optim_state[state_name] = value
+    return new_optim_state
+
+
+def _flatten_optim_state_dict(
+    optim_state_dict: Dict[str, Any],
+    model: nn.Module,
+    use_orig_params: bool = False,
+    optim: Optional[torch.optim.Optimizer] = None,
+    rank0_only: bool = False,
+    group: Optional[dist.ProcessGroup] = None,
+) -> Dict[str, Any]:
+    """
+    Flattens the full optimizer state dict, still keying by unflattened parameter
+    names.
+
+    If ``use_orig_params`` is True, each rank will have all FSDP-managed
+    parameters but some of these parameters may be empty due to the sharding.
+    For a regular optim.Optimizer, states for those empty parameters will
+    not be initialized. So, when aggregating the FQNs across ranks, no assert
+    will be raised on a rank even if it does not have all the states -- it is
+    valid and FSDP know how to aggregate them. However, FSDP has to ignore
+    handling those parameters that are not managed by FSDP and do not exist on
+    the local rank -- it is managed by other parallelism and FSDP does not
+    know ho to handle/aggregate them.
+
+    Note that ``_flatten_tensor_optim_state`` does not need ``optim`` to
+    flatten/shard the state. However, NamedOptimizer and KeyedOptimizer require
+    all the states even if the corresponding parameters are empty. To this end,
+    ``optim`` will be used to to get the initial state of the empty parameters.
+    ``optim`` should only be non-None if the ``optim` is KeyedOptimizer or
+    NamedOptimizer.
+
+    Returns:
+        Dict[str, Any]: The flattened optimizer state dict.
+    """
+    SimpleProfiler.reset()
+
+    unflat_osd = optim_state_dict
+    if "state" not in unflat_osd and not rank0_only:
+        raise ValueError(
+            '`optim_state_dict` must have the keys "state"'
+            "to be a valid optimizer state dict"
+        )
+    param_to_fqns = _get_param_to_fqns(model)
+    fqn_to_fsdp_param_info = _get_fqn_to_fsdp_param_info(model)
+    fsdp_state = next(iter(fqn_to_fsdp_param_info.values())).state
+
+    # Broadcast unflat_osd without non-scalar tensor if rank0_only is True.
+    if rank0_only:
+        unflat_osd = _broadcast_processed_state(fsdp_state, unflat_osd, group=group)
+
+    # Construct the "state" part
+    flat_osd_state: Dict[Union[_OptimStateKey, str], Any] = {}
+    unflat_osd_state = unflat_osd["state"]
+    all_state_keys = set(unflat_osd_state.keys())
+
+    for param, fqns in param_to_fqns.items():
+        fqn = fqns[0]
+        if fqn not in unflat_osd_state:
+            continue
+        all_state_keys.difference_update(fqns)
+
+        if rank0_only:
+            for fqn in fqns:
+                if not unflat_osd_state[fqn]:
+                    continue
+                for state_name in unflat_osd_state[fqn].keys():
+                    unflat_osd_state[fqn][state_name] = _broadcast_state(
+                        fsdp_state, unflat_osd_state[fqn][state_name], group=group
+                    )
+            fqn = fqns[0]
+        if fqn in fqn_to_fsdp_param_info:
+            fsdp_param_info = fqn_to_fsdp_param_info[fqn]
+            if use_orig_params:
+                with SimpleProfiler.profile(SimpleProfiler.Type.RESHARDING):
+                    flat_state = _shard_orig_param_state(
+                        fsdp_param_info,
+                        fqn,
+                        unflat_osd_state[fqn],
+                    )
+            else:
+                flat_state = _flatten_optim_state(
+                    fsdp_param_info,
+                    unflat_osd_state,
+                    fqns,
+                )
+            key = _OptimStateKey(tuple(fqns), True)
+            # Only include non-empty states since as expected by
+            # `torch.optim.Optimizer` s unless the optimizer is KeyedOptimizer
+            # or NamedOptimizer.
+            if flat_state:
+                flat_osd_state[key] = flat_state
+            elif use_orig_params:
+                assert (
+                    len(fqns) == 1
+                ), f"use_orig_params is True but there are multiple FQNs, {fqns}."
+                if optim is not None:  # NamedOptimizer or KeyedOptimizer case.
+                    state = optim.state.get(param, None)  # type: ignore[call-overload]
+                    if state is not None:
+                        flat_osd_state[key] = copy.deepcopy(state)
+                    else:
+                        warnings.warn(
+                            f"optim_state[{key}] is not on rank{fsdp_state.rank}."
+                        )
+
+            else:
+                raise RuntimeError(
+                    f"The state of {key} is empty. This should happen when "
+                    "use_orig_params=True."
+                )
+        else:  # do not flatten non-FSDP parameters' states
+            assert len(fqns) == 1
+            key = _OptimStateKey(tuple(fqns), False)
+            flat_osd_state[key] = copy.copy(unflat_osd_state[fqn])
+
+        if rank0_only:
+            for fqn in fqns:
+                if not unflat_osd_state[fqn]:
+                    continue
+                for state_name, param_state in list(unflat_osd_state[fqn].items()):
+                    if fsdp_state.rank > 0:
+                        # Deference the tensor so that PyTorch can collect the memory.
+                        del unflat_osd_state[fqn][state_name]
+                    else:
+                        # Move the tensor in the original osd back to CPU to make the
+                        # original osd unaffected.
+                        unflat_osd_state[fqn][state_name] = unflat_osd_state[fqn][
+                            state_name
+                        ].cpu()
+
+    # Handle user-defined state, states that are not associated with parameters.
+    for key in all_state_keys:
+        user_state = unflat_osd_state[key]
+        if isinstance(user_state, torch.Tensor) and rank0_only and use_orig_params:
+            user_state = _broadcast_state(fsdp_state, user_state, group=group)
+        flat_osd_state[key] = copy.copy(user_state)
+
+    SimpleProfiler.dump_and_reset("FSDP _flatten_optim_state_dict() profiling: ")
+    # Construct the "param_groups" part -- copy as is since it will be
+    # rekeyed later according to the target rank's optimizer
+    # Only copy param_groups if it exists in unflat_osd
+    if "param_groups" in unflat_osd:
+        flat_osd_param_groups = copy.deepcopy(unflat_osd["param_groups"])
+        return {"state": flat_osd_state, "param_groups": flat_osd_param_groups}
+    else:
+        return {"state": flat_osd_state}
+
+
+def _flatten_optim_state(
+    fsdp_param_info: FSDPParamInfo,
+    unflat_osd_state: Dict[str, Dict[str, Any]],
+    unflat_param_names: List[str],
+) -> Dict[str, Any]:
+    """
+    Flattens the optimizer state in ``full_optim_state_dict`` for a single
+    flat parameter in ``fsdp_param_info`` corresponding to the unflattened
+    parameter names in ``unflat_param_names``.
+
+    Args:
+        fsdp_param_info (FSDPParamInfo): The FSDP state, the handle, and a
+            mapping from FQN to original parameter index.
+        unflat_osd_state (Dict[str, Dict[str, Any]]): The "state" part of the
+            optimizer state dict corresponding to the unflattened parameters.
+        unflat_param_names (List[str]): A :class:`list` of unflattened
+            parameter names corresponding to the flat parameter ``flat_param``.
+
+    Returns:
+        Dict[str, Any]: A :class:`dict` mapping state names to their values for
+        a particular flat parameter. The sharded optimizer state dict's "state"
+        part will map a key to this returned value.
+    """
+    fsdp_state = fsdp_param_info.state
+    handle = fsdp_param_info.handle
+    flat_param = handle.flat_param
+    num_unflat_params = len(unflat_param_names)
+    assert num_unflat_params > 0, (
+        "Expects at least one unflattened parameter corresponding to the "
+        "flat parameter"
+    )
+    unflat_param_shapes = flat_param._shapes
+    num_unflat_param_shapes = len(unflat_param_shapes)
+    assert (
+        num_unflat_params == num_unflat_param_shapes
+    ), f"Expects {num_unflat_params} shapes but got {num_unflat_param_shapes}"
+
+    # Check if these unflattened parameters have any optimizer state
+    has_state = [
+        bool(unflat_param_name in unflat_osd_state)
+        for unflat_param_name in unflat_param_names
+    ]
+    # If none of the unflattened parameters comprising this flat parameter have
+    # any state, then we do not want an entry in the optimizer state dict
+    if not any(has_state):
+        return {}  # no need to flatten any state
+    # There may still be some unflattened parameters with state and some
+    # without
+    unflat_param_states = [
+        _gather_state_dict(
+            unflat_osd_state[unflat_param_name],
+            pg=fsdp_state.process_group,
+            device=fsdp_state.compute_device,
+        )
+        if unflat_param_name in unflat_osd_state
+        else None
+        for unflat_param_name in unflat_param_names
+    ]
+    # Check that the unflattened parameters have the same state names
+    state_names = None
+    for unflat_param_state in unflat_param_states:
+        if unflat_param_state is None:
+            continue
+        if state_names is None:
+            state_names = set(unflat_param_state.keys())
+        else:
+            if state_names != set(unflat_param_state.keys()):
+                raise ValueError(
+                    "Differing optimizer state names for the unflattened "
+                    f"parameters: {unflat_param_names}"
+                )
+    assert state_names is not None
+
+    # Flatten the state
+    flat_state: Dict[str, Any] = {}
+    for state_name in state_names:
+        state_values = [
+            unflat_param_state[state_name] if unflat_param_state is not None else None
+            for unflat_param_state in unflat_param_states
+        ]
+        non_none_state_values = [v for v in state_values if v is not None]
+        # If all ranks have None, this is a None value
+        if not non_none_state_values:
+            flat_state[state_name] = None
+            continue
+        are_pos_dim_tensors = are_zero_dim_tensors = are_non_tensors = True
+        for v in non_none_state_values:
+            are_pos_dim_tensors &= torch.is_tensor(v) and v.dim() > 0
+            are_zero_dim_tensors &= _is_zero_dim_tensor(v)
+            are_non_tensors &= not torch.is_tensor(v)
+        types = {type(v) for v in non_none_state_values}
+        if len(types) != 1 or not (
+            are_pos_dim_tensors or are_zero_dim_tensors or are_non_tensors
+        ):
+            raise ValueError(
+                f"Differing optimizer state types for state {state_name}, "
+                f"values {non_none_state_values}, and unflattened parameter "
+                f"names {unflat_param_names}"
+            )
+        if are_pos_dim_tensors:
+            flat_tensor = _flatten_tensor_optim_state(
+                state_name,
+                state_values,
+                unflat_param_names,
+                unflat_param_shapes,
+                handle,
+            )
+            # Shard the flattened tensor immediately to minimize max memory
+            # usage
+            if (
+                fsdp_state.world_size != 1
+                and fsdp_state.sharding_strategy != ShardingStrategy.NO_SHARD
+            ):
+                sharded_flat_tensor, _ = FlatParamHandle._get_shard(
+                    flat_tensor,
+                    fsdp_state.rank,
+                    fsdp_state.world_size,
+                )
+            else:
+                sharded_flat_tensor = flat_tensor
+            flat_state[state_name] = sharded_flat_tensor
+        elif are_zero_dim_tensors:
+            flat_state[state_name] = _flatten_zero_dim_tensor_optim_state(
+                state_name,
+                state_values,
+                unflat_param_names,
+            )
+        else:
+            assert are_non_tensors
+            flat_state[state_name] = _flatten_non_tensor_optim_state(
+                state_name,
+                state_values,
+                unflat_param_names,
+            )
+
+    return flat_state
+
+
+def _flatten_tensor_optim_state(
+    state_name: str,
+    pos_dim_tensors: List[torch.Tensor],
+    unflat_param_names: List[str],
+    unflat_param_shapes: Sequence[torch.Size],
+    handle: FlatParamHandle,
+) -> torch.Tensor:
+    """
+    Flattens the positive-dimension tensor optimizer state given by the values
+    ``tensors`` for the state ``state_name`` for a single flat parameter
+    from ``handle`` corresponding to the unflattened parameter names
+    ``unflat_param_names`` and unflatted parameter shapes
+    ``unflat_param_shapes``. This flattens each unflattened parameter's tensor
+    state into one tensor.
+
+    NOTE: We use zero tensors for any unflattened parameters without state
+    since some value is required to fill those entries. This assumes that the
+    zero tensor is mathematically equivalent to having no state, which is true
+    for Adam's "exp_avg" and "exp_avg_sq" but may not be true for all
+    optimizers.
+
+    Args:
+        state_name (str): Optimizer state name.
+        pos_dim_tensors (List[torch.Tensor]): Positive-dimension tensor
+            optimizer state values for the unflattened parameters corresponding
+            to the single flat parameter.
+        unflat_param_names (List[str]): A :class:`list` of unflattened
+            parameter names corresponding to the single flat parameter.
+        unflat_param_shapes (List[torch.Size]): Unflattened parameter shapes
+            corresponding to the single flat parameter.
+        handle (FlatParamHandle): The flat parameter's handle.
+
+    Returns:
+        torch.Tensor: A flat tensor containing the optimizer state
+        corresponding to ``state_name`` constructed by concatenating the
+        unflattened parameter tensor states in ``pos_dim_tensors`` (using zero
+        tensors for any unflattened parameters without the state).
+    """
+    flat_param = handle.flat_param
+    non_none_tensors = [t for t in pos_dim_tensors if t is not None]
+    # Check that all are tensors with the same dtype
+    dtypes = {t.dtype for t in non_none_tensors}
+    if len(dtypes) != 1:
+        raise ValueError(
+            "All unflattened parameters comprising a single flat "
+            "parameter must have positive-dimension tensor state with the "
+            f"same dtype but got dtypes {dtypes} for state {state_name} and "
+            f"unflattened parameter names {unflat_param_names}"
+        )
+    dtype = next(iter(dtypes))
+    # Check that each tensor state matches its parameter's shape
+    for tensor, shape in zip(pos_dim_tensors, unflat_param_shapes):
+        if tensor is None and len(shape) == 0:
+            raise ValueError("Flattening a zero-dimension parameter is not supported")
+        elif tensor is not None and tensor.shape != shape:
+            raise ValueError(
+                "Tensor optimizer state does not have same shape as its "
+                f"parameter: {tensor.shape} {shape}"
+            )
+    # Flatten the tensor states: we do not need to add any right-hand-side
+    # padding since the flat optimizer state tensor is sharded via
+    # `_get_shard()`, which pads the shard as needed (just like for the flat
+    # parameter)
+    cpu_device = torch.device("cpu")
+    tensors_to_flatten = [
+        torch.flatten(state_value.to(cpu_device))
+        if state_value is not None
+        else torch.flatten(
+            torch.zeros(
+                size=shape,
+                dtype=dtype,
+                device=cpu_device,
+            )
+        )
+        for state_value, shape in zip(pos_dim_tensors, unflat_param_shapes)
+    ]
+    flat_tensor = handle.flatten_tensors(tensors_to_flatten, handle._aligned_numel)
+    flat_param_shape = flat_param._unpadded_unsharded_size  # type: ignore[attr-defined]
+    assert flat_tensor.shape == flat_param_shape, (
+        f"tensor optim state: {flat_tensor.shape} "
+        f"flat parameter: {flat_param_shape}"
+    )
+    return flat_tensor
+
+
+def _flatten_zero_dim_tensor_optim_state(
+    state_name: str,
+    zero_dim_tensors: List[torch.Tensor],
+    unflat_param_names: List[str],
+) -> torch.Tensor:
+    """
+    Flattens the zero-dimension tensor optimizer state given by the values
+    ``zero_dim_tensors`` for the state ``state_name`` for a single flat
+    parameter corresponding to the unflattened parameter names
+    ``unflat_param_names`` by enforcing that all tensors are the same and using
+    that common value.
+
+    NOTE: The requirement that the tensors are the same across all unflattened
+    parameters comprising the flat parameter is needed to maintain the
+    invariant that FSDP performs the same computation as its non-sharded
+    equivalent. This means that none of the unflattened parameters can be
+    missing this state since imposing a value may differ from having no value.
+    For example, for Adam's "step", no value means maximum bias correction,
+    while having some positive value means less bias correction.
+
+    Args:
+        state_name (str): Optimizer state name.
+        zero_dim_tensors (List[torch.Tensor]): Zero-dimension optimizer state
+            for the unflattened parameters corresponding to the single
+            flat parameter.
+        unflat_param_names (List[str]): A :class:`list` of unflattened
+            parameter names corresponding to the single flat parameter.
+
+    Returns:
+        torch.Tensor: A zero-dimensional tensor giving the value of the state
+        ``state_name`` for all unflattened parameters corresponding to the
+        names ``unflat_param_names``.
+    """
+    non_none_tensors = [t for t in zero_dim_tensors if t is not None]
+    # Enforce that all have the same value and dtype
+    values_set = {t.item() if t is not None else None for t in zero_dim_tensors}
+    dtypes = {t.dtype if t is not None else None for t in zero_dim_tensors}
+    if (
+        len(non_none_tensors) != len(zero_dim_tensors)
+        or len(values_set) != 1
+        or len(dtypes) != 1
+    ):
+        raise ValueError(
+            "All unflattened parameters comprising a single flat "
+            "parameter must have scalar state with the same value and dtype "
+            f"but got values {values_set} and dtypes {dtypes} for state "
+            f"{state_name} and unflattened parameter names "
+            f"{unflat_param_names}"
+        )
+    value = next(iter(values_set))
+    dtype = next(iter(dtypes))
+    return torch.tensor(value, dtype=dtype, device=torch.device("cpu"))
+
+
+def _flatten_non_tensor_optim_state(
+    state_name: str,
+    non_tensors: List[Any],
+    unflat_param_names: List[str],
+) -> Any:
+    """
+    Flattens the non-tensor optimizer state given by the values ``non_tensors``
+    for the state ``state_name`` for a single flat parameter corresponding
+    to the unflattened parameter names ``unflat_param_names`` by enforcing that
+    all values are the same and using that common value.
+
+    See the note in :func:`_flatten_zero_dim_tensor_optim_state`.
+
+    Args:
+        state_name (str): Optimizer state name.
+        non_tensors (List[Any]): Non-tensor optimizer state for the unflattened
+            parameters corresponding to the single flat parameter.
+        unflat_param_names (List[str]): A :class:`list` of unflattened
+            parameter names corresponding to the single flat parameter.
+
+    Returns:
+        Any: A non-tensor giving the value of the state ``state_name`` for all
+        unflattened parameters corresponding to the names
+        ``unflat_param_names``.
+    """
+    non_none_non_tensors = [nt for nt in non_tensors if nt is not None]
+    # Enforce that all have the same value (same type already checked)
+    non_tensor_set = set(non_tensors)
+    if len(non_none_non_tensors) != len(non_tensors) or len(non_tensor_set) != 1:
+        raise ValueError(
+            "All unflattened parameters comprising a single flat "
+            "parameter must have scalar state with the same value and dtype "
+            f"but got values {non_tensor_set} for state {state_name} and  "
+            f"unflattened parameter names {unflat_param_names}"
+        )
+    non_tensor = next(iter(non_tensor_set))
+    return non_tensor
+
+
+def _rekey_sharded_optim_state_dict(
+    sharded_osd: Dict[str, Any],
+    model: nn.Module,
+    optim: torch.optim.Optimizer,
+    optim_input: Optional[
+        Union[
+            List[Dict[str, Any]],
+            Iterable[nn.Parameter],
+        ]
+    ],
+    using_optim_input: bool,
+    is_named_optimizer: bool = False,
+) -> Dict[str, Any]:
+    """
+    Rekeys the optimizer state dict from unflattened parameter names to flat
+    parameter IDs according to the calling rank's ``optim``, which may be
+    different across ranks. In particular, the unflattened parameter names are
+    represented as :class:`_OptimStateKey` s.
+    """
+    param_to_fqns = _get_param_to_fqns(model)
+    flat_param_to_fqn = _get_flat_param_to_fqn(model)
+    param_to_param_key: Dict[nn.Parameter, Union[int, str]] = cast(
+        Dict[nn.Parameter, Union[int, str]],
+        (
+            _get_param_to_param_id_from_optim_input(model, optim_input)
+            if using_optim_input
+            else _get_param_to_param_key(
+                optim, model, is_named_optimizer, param_to_fqns, flat_param_to_fqn
+            )
+        ),
+    )
+    # All parameter keys in `param_to_param_key` should be in
+    # `param_to_fqns` -- strict inequality follows when not all parameters are
+    # passed to the optimizer
+    assert len(param_to_param_key) <= len(param_to_fqns)
+
+    unflat_param_names_to_flat_param_key: Dict[
+        Tuple[str, ...], Union[int, str]
+    ] = {}  # for "state"
+    unflat_param_name_to_flat_param_key: Dict[
+        str, Union[int, str]
+    ] = {}  # for "param_groups"
+    for param, unflat_param_names in param_to_fqns.items():
+        if param not in param_to_param_key:
+            # This parameter was not passed to the optimizer
+            continue
+        flat_param_key = param_to_param_key[param]
+        unflat_param_names_to_flat_param_key[tuple(unflat_param_names)] = flat_param_key
+        for unflat_param_name in unflat_param_names:
+            unflat_param_name_to_flat_param_key[unflat_param_name] = flat_param_key
+
+    sharded_osd_state = sharded_osd["state"]
+    rekeyed_osd_state: Dict[Union[str, int], Any] = {}
+    for key, param_state in sharded_osd_state.items():
+        if isinstance(key, str):
+            rekeyed_osd_state[key] = param_state
+            continue
+        flat_param_key = unflat_param_names_to_flat_param_key.get(
+            key.unflat_param_names, key.unflat_param_names
+        )
+        rekeyed_osd_state[flat_param_key] = param_state
+
+    # Only process param_groups if it exists in sharded_osd
+    if "param_groups" in sharded_osd:
+        rekeyed_osd_param_groups: List[Dict[str, Any]] = []
+        for unflat_param_group in sharded_osd["param_groups"]:
+            flat_param_group = copy.deepcopy(unflat_param_group)
+            flat_param_keys = sorted(
+                {
+                    unflat_param_name_to_flat_param_key[unflat_param_name]
+                    for unflat_param_name in unflat_param_group["params"]
+                }
+            )
+            flat_param_group["params"] = flat_param_keys
+            rekeyed_osd_param_groups.append(flat_param_group)
+        return {"state": rekeyed_osd_state, "param_groups": rekeyed_osd_param_groups}
+    else:
+        return {"state": rekeyed_osd_state}
+
+
+def _get_param_id_to_param_from_optim_input(
+    model: nn.Module,
+    optim_input: Optional[
+        Union[
+            List[Dict[str, Any]],
+            Iterable[nn.Parameter],
+        ]
+    ] = None,
+) -> Dict[int, nn.Parameter]:
+    """
+    Constructs a mapping from parameter IDs to parameters. This may be used
+    both for models with ``FlatParameter`` s and without.
+
+    NOTE: This method is only preserved for backward compatibility. The method
+    :meth:`_get_param_key_to_param` is the preferred code path that does not
+    rely on ``optim_input``.
+
+    NOTE: We critically assume that, whether the optimizer input is a list of
+    parameters or a list of parameter groups, :class:`torch.optim.Optimizer`
+    enumerates the parameter IDs in order. In other words, for a parameter list
+    input, the parameter IDs should be in that list order, and for a parameter
+    groups input, the parameter IDs should be in order within each parameter
+    group and in order across parameter groups.
+
+    Args:
+        model (nn.Module): Model whose parameters are passed into the
+            optimizer.
+        optim_input (Optional[Union[List[Dict[str, Any]],
+        Iterable[nn.Parameter]]]): Input passed into the optimizer
+            representing either a :class:`list` of parameter groups or an
+            iterable of parameters; if ``None``, then this method assumes the
+            input was ``model.parameters()``. (Default: ``None``)
+
+    Returns:
+        List[nn.Parameter]: Mapping from parameter IDs to parameters,
+        where the parameter ID is implicitly the index in the :class:`list`.
+    """
+    # Assume the standard case of passing `model.parameters()` to the optimizer
+    # if `optim_input` is not specified
+    if optim_input is None:
+        return dict(enumerate(model.parameters()))
+    try:
+        params = cast(List[nn.Parameter], list(optim_input))
+    except TypeError as e:
+        raise TypeError(
+            "Optimizer input should be an iterable of Tensors or dicts, "
+            f"but got {optim_input}"
+        ) from e
+    if len(params) == 0:
+        raise ValueError("Optimizer input should not be empty")
+
+    # Check if the optimizer input represents tensors or parameter groups
+    all_tensors = True
+    all_dicts = True
+    for param in params:
+        all_tensors &= isinstance(param, torch.Tensor)
+        all_dicts &= isinstance(param, dict)
+    if not all_tensors and not all_dicts:
+        raise TypeError("Optimizer input should be an iterable of Tensors or dicts")
+    if all_tensors:
+        return dict(enumerate(params))
+    assert all_dicts
+    param_id_to_param: List[nn.Parameter] = []
+    for param_group in params:
+        has_params_key = "params" in param_group  # type: ignore[operator]
+        assert has_params_key, (
+            'A parameter group should map "params" to a list of the '
+            "parameters in the group"
+        )
+        # Implicitly map `flat_param_id` (current length of the list) to
+        # `param`
+        param_id_to_param.extend(param_group["params"])  # type: ignore[index]
+    return dict(enumerate(param_id_to_param))
+
+
+def _get_flat_param_to_fqn(model: torch.nn.Module) -> Dict[FlatParameter, str]:
+    """
+    Constructs a mapping from ``FlatParameter`` to a cleaned (devoid of prefixes
+    from wrappers) fully qualified name (FQN). Note that this FQN is "non-canonical"
+    because ``FlatParameter``  s do not come from the original module but are
+    registered only after FSDP has been applied. This function returns the FSDP-given
+    name for the ``FlatParameter`` (usually module._flat_param) as opposed to the
+    canonical FQNs returned for ``FlatParameter`` s in ``_common_utils._get_param_to_fqns(...)``).
+
+    Consequently, this function will only return a non-empty mapping if FSDP was
+    applied with ``use_orig_params=False`` as, otherwise, the original parameters
+    are used within the module and there would be no ``FlatParameter`` s in the module.
+
+    """
+
+    def module_fn(module, prefix, tree_level, flat_param_to_fqn):
+        for param_name, param in _named_parameters_with_duplicates(
+            module, recurse=False
+        ):
+            if not isinstance(param, FlatParameter):
+                continue
+            fqn = clean_tensor_name(prefix + param_name)
+            flat_param_to_fqn[param] = fqn
+
+    def return_fn(flat_param_to_fqn):
+        return flat_param_to_fqn
+
+    flat_param_to_fqn_ret: Dict[FlatParameter, str] = {}
+    return _apply_to_modules(
+        model,
+        module_fn,
+        return_fn,
+        [fqn for fqn, _ in _named_parameters_with_duplicates(model)],
+        flat_param_to_fqn_ret,
+    )
+
+
+def _get_param_key_to_param(
+    optim: torch.optim.Optimizer,
+    model: Optional[nn.Module] = None,
+    is_named_optimizer: bool = False,
+    param_to_fqns: Optional[Dict[nn.Parameter, List[str]]] = None,
+    flat_param_to_fqn: Optional[Dict[FlatParameter, str]] = None,
+) -> Dict[Union[int, str], nn.Parameter]:
+    """
+    Constructs a mapping from parameter keys to parameters. For the regular
+    optimizers, the keys are parameter IDs. For NamedOptimizer, the keys
+    are FQNs. This API may be used both for models with ``FlatParameter`` s and
+    without.
+    """
+    clean_fqn_to_curr_fqn: Dict[str, str] = {}
+    if is_named_optimizer:
+        assert (
+            param_to_fqns is not None and flat_param_to_fqn is not None
+        ), "The optimizer is a NamedOptimizer, `param_to_fqns` must not be None."
+        assert model is not None
+        for key, _ in _named_parameters_with_duplicates(model):
+            clean_fqn_to_curr_fqn[clean_tensor_name(key)] = key
+
+    param_key_to_param: Dict[Union[str, int], nn.Parameter] = {}
+    pid = 0
+    for param_group in optim.param_groups:
+        if is_named_optimizer:
+            for param in param_group["params"]:
+                assert flat_param_to_fqn is not None
+                if param in flat_param_to_fqn:
+                    # FlatParameter case
+                    key = flat_param_to_fqn[param]
+                else:
+                    assert param_to_fqns is not None
+                    # use_orig_params case
+                    assert len(param_to_fqns[param]) == 1
+                    key = param_to_fqns[param][0]
+                try:
+                    key = clean_fqn_to_curr_fqn[key]
+                except KeyError as e:
+                    raise KeyError(
+                        f"Can't find {key} from {list(clean_fqn_to_curr_fqn.keys())}."
+                    ) from e
+                param_key_to_param[key] = param
+        else:
+            for param in param_group["params"]:
+                param_key_to_param[pid] = param
+                pid += 1
+
+    return param_key_to_param
+
+
+def _get_param_to_param_key(
+    optim: torch.optim.Optimizer,
+    model: Optional[nn.Module] = None,
+    is_named_optimizer: bool = False,
+    param_to_fqns: Optional[Dict[nn.Parameter, List[str]]] = None,
+    flat_param_to_fqn: Optional[Dict[FlatParameter, str]] = None,
+) -> Dict[nn.Parameter, Union[int, str]]:
+    """
+    Constructs the inverse mapping of :func:`_get_param_key_to_param`. This API
+    only supports the case where `optim` is a regular optimizer, not NamedOptimizer.
+    So the parameter keys will be parameter ids.
+    """
+    param_id_to_param = _get_param_key_to_param(
+        optim, model, is_named_optimizer, param_to_fqns, flat_param_to_fqn
+    )
+    return {param: param_id for param_id, param in param_id_to_param.items()}
+
+
+def _get_param_to_param_id_from_optim_input(
+    model: nn.Module,
+    optim_input: Optional[
+        Union[
+            List[Dict[str, Any]],
+            Iterable[nn.Parameter],
+        ]
+    ] = None,
+) -> Dict[nn.Parameter, int]:
+    """Constructs the inverse mapping of :func:`_get_param_id_to_param_from_optim_input`."""
+    param_id_to_param = _get_param_id_to_param_from_optim_input(model, optim_input)
+    return {param: param_id for param_id, param in param_id_to_param.items()}
+
+
+def _check_missing_keys_on_rank(
+    r0_optim_state_keys: List[_OptimStateKey],
+    optim_state_key_to_param_key: Dict[_OptimStateKey, Union[str, int]],
+    param_key_to_param: Dict[Union[str, int], nn.Parameter],
+    group: Optional[dist.ProcessGroup],
+) -> None:
+    # Ensure that all ranks have at least the optimizer states needed by
+    # rank 0's optimizer
+    missing_keys: List[_OptimStateKey] = []
+    for r0_optim_state_key in r0_optim_state_keys:
+        if r0_optim_state_key not in optim_state_key_to_param_key:
+            # A parameter from rank 0's optimizer does not exist for this
+            # rank's optimizer
+            missing_keys.append(r0_optim_state_key)
+            continue
+        param_key = optim_state_key_to_param_key[r0_optim_state_key]
+        if isinstance(param_key, int):
+            assert param_key >= 0 and param_key < len(
+                param_key_to_param
+            ), "Check the `param_key_to_param` construction"
+    # We cannot use FSDPState.compute_device as this API is a global view.
+    device = _get_pg_default_device(group)
+    num_missing = torch.tensor([len(missing_keys)], dtype=torch.int32, device=device)
+    dist.all_reduce(num_missing, group=group)
+    if num_missing.item() > 0:
+        obj_list = [None for _ in range(dist.get_world_size(group))]
+        dist.all_gather_object(obj_list, missing_keys, group=group)
+        error_msg = (
+            "FSDP currently requires each rank to have at least the "
+            "optimizer states needed by rank 0's optimizer but some ranks "
+            "are missing some of those states"
+        )
+        for rank, keys in enumerate(obj_list):
+            keys = cast(List[_OptimStateKey], keys)
+            if len(keys) > 0:
+                error_msg += (
+                    f"\nRank {rank} is missing states for the parameters: "
+                    f"{[key.unflat_param_names for key in keys]}"
+                )
+        raise RuntimeError(error_msg)
+
+
+def _map_param_key_to_optim_keys(
+    optim_state_dict: Dict[str, Any],
+    group: Optional[dist.ProcessGroup],
+    param_key_to_param: Dict[Union[int, str], nn.Parameter],
+    param_to_fqns: Dict[nn.Parameter, List[str]],
+    fqn_to_fsdp_param_info: Dict[str, FSDPParamInfo],
+    merge_keys: bool = False,
+) -> Tuple[List[_OptimStateKey], Dict[_OptimStateKey, Union[int, str]]]:
+    """
+    Construct the local mapping between the ``_OptimStateKey`` and parameter keys
+    and all the ``_OptimStateKey`` across ranks. If ``merge_keys`` is False, rank0
+    must contain all the ``_OptimStateKey``, an exception will be raised otherwise.
+    Note that ``merge_keys`` should equal to ``use_orig_params``.
+    """
+    rank = dist.get_rank(group)
+    optim_state_key_to_param_key: Dict[_OptimStateKey, Union[int, str]] = {}  # local
+    all_optim_state_keys: List[_OptimStateKey] = []
+
+    for param_key, param in param_key_to_param.items():
+        # Do not include parameters without state to avoid empty mappings
+        # just like in normal `torch.optim.Optimizer.state_dict()`
+        if param_key not in optim_state_dict["state"]:
+            continue
+        fqns = param_to_fqns[param]
+        is_fsdp_managed = isinstance(param, FlatParameter)
+        if is_fsdp_managed:
+            assert fqns[0] in fqn_to_fsdp_param_info, (
+                fqns[0],
+                list(fqn_to_fsdp_param_info.keys()),
+            )
+        is_fsdp_managed = fqns[0] in fqn_to_fsdp_param_info
+        optim_state_key = _OptimStateKey(
+            unflat_param_names=tuple(fqns),
+            is_fsdp_managed=is_fsdp_managed,
+        )
+        if rank == 0 or merge_keys:
+            all_optim_state_keys.append(optim_state_key)
+        optim_state_key_to_param_key[optim_state_key] = param_key
+
+    if merge_keys:
+        all_keys: List[List[_OptimStateKey]] = [
+            [] for _ in range(dist.get_world_size(group))
+        ]
+        dist.all_gather_object(all_keys, all_optim_state_keys, group=group)
+        merge_all_optim_state_keys = [
+            key for local_keys in all_keys for key in local_keys
+        ]
+        all_optim_state_keys = sorted(set(merge_all_optim_state_keys))
+    else:
+        key_obj_list: List[Optional[List[_OptimStateKey]]] = (
+            [all_optim_state_keys] if rank == 0 else [None]
+        )
+        dist.broadcast_object_list(key_obj_list, src=0, group=group)
+        assert key_obj_list[0] is not None
+        all_optim_state_keys = key_obj_list[0]
+        _check_missing_keys_on_rank(
+            all_optim_state_keys,
+            optim_state_key_to_param_key,
+            param_key_to_param,
+            group,
+        )
+
+    return all_optim_state_keys, optim_state_key_to_param_key
+
+
+def _unflatten_param_groups(
+    state_dict: Dict[str, Any],
+    param_key_to_param: Dict[Union[int, str], nn.Parameter],
+    param_to_fqns: Dict[nn.Parameter, List[str]],
+) -> List[Dict[str, Any]]:
+    param_groups: List[Dict[str, Any]] = []
+    for flat_param_group in state_dict["param_groups"]:
+        unflat_param_group = copy.deepcopy(flat_param_group)
+        param_group_params = [
+            param_key_to_param[flat_param_key]
+            for flat_param_key in flat_param_group["params"]
+        ]
+        nested_unflat_param_names = [
+            param_to_fqns[param] for param in param_group_params
+        ]
+        unflat_param_group["params"] = [
+            unflat_param_name
+            for unflat_param_names in nested_unflat_param_names
+            for unflat_param_name in unflat_param_names
+        ]  # flatten the list of lists
+        param_groups.append(unflat_param_group)
+    return param_groups
+
+
+def _is_named_optimizer(optim_state_dict: Dict[str, Any]) -> bool:
+    """
+    Returns whether the state_dict is from a NamedOptimizer.
+    This function checks that the keys in the state_dict['state'] are strings
+    (which usually are FQNs) versus integers (which usually refer to param_ids
+    from a vanilla torch.optim.Optimizer).
+    """
+    state = optim_state_dict.get("state", None)
+    if not state:
+        # If we cannot find a state, assume it is not NamedOptimizer as
+        # NamedOptimizer has eager initialization.
+        return False
+    try:
+        key = next(iter(state.keys()))
+    except Exception as e:
+        raise Exception(optim_state_dict) from e  # noqa: TRY002
+    return isinstance(key, str)
+
+
+@dataclass
+class StateInfo:
+    # The key of these dictionaries are the state name, e.g., `exp_avg`.
+    tensors: Dict[str, _PosDimTensorInfo]
+    scalar_tensors: Dict[str, torch.Tensor]
+    non_tensors: Dict[str, Any]
+
+
+def _allgather_state_info(
+    fsdp_state: _FSDPState,
+    input_states: Dict[str, Any],
+) -> List[Dict[str, StateInfo]]:
+    """
+    Given the ``input_states``, allgather StateInfo for each state. The function
+    uses all_gather_object to gather StateInfo so no GPU tensors are sent.
+    """
+
+    processed_state_dict: Dict[str, StateInfo] = {}
+    gathered_state_info: List[Dict[str, StateInfo]] = [
+        {} for _ in range(fsdp_state.world_size)
+    ]
+
+    for fqn, optim_state in input_states.items():
+        # Allgather the scalar tensor state, non-tensor states and tensors metadata.
+        processed_state = StateInfo({}, {}, {})
+        for state_name, value in sorted_items(optim_state):
+            if torch.is_tensor(value):
+                if value.dim() == 0:
+                    # Ensure that `step` is on CPU.
+                    processed_state.scalar_tensors[state_name] = value.cpu()
+                else:
+                    processed_state.tensors[state_name] = _PosDimTensorInfo(
+                        value.shape, value.dtype
+                    )
+            else:
+                processed_state.non_tensors[state_name] = value
+        processed_state_dict[fqn] = processed_state
+    dist.all_gather_object(
+        gathered_state_info,
+        processed_state_dict,
+        group=fsdp_state.process_group,
+    )
+    return gathered_state_info
+
+
+def _convert_all_state_info(
+    fsdp_param_info: FSDPParamInfo,
+    gathered_state_info: List[Dict[str, StateInfo]],
+    input_states: Dict[str, Any],
+    output_states: Dict[str, Dict[str, Any]],
+) -> Tuple[Optional[torch.dtype], Dict[str, List[Optional[torch.Tensor]]]]:
+    """
+    Given the ``gathered_state_info`` and ``input_states``, the API converted
+    the StateInfo into the original state if the state is not a non-scalar
+    tensor. For a multi-dimensional tensor, the local state will be stored in
+    ``state_buffer`` in a correct order for later allgather purpose.
+    """
+
+    state_buffers: Dict[str, List[Optional[torch.Tensor]]] = {}
+
+    for fqn, gathered_state in output_states.items():
+        state_info = [s[fqn] for s in gathered_state_info]
+        all_tensor_states = sorted(
+            {n for state in state_info for n in state.tensors.keys()}
+        )
+        empty_ranks: Set[int] = set()
+        dtype: Optional[torch.dtype] = None
+        # First check all the non-scalar states and get the information of
+        # states on each rank.
+        for state_name in all_tensor_states:
+            numels = []
+            _empty_ranks: Set[int] = set()
+            for rank, object_state in enumerate(state_info):
+                numels.append(0)
+                info = object_state.tensors.get(state_name, None)
+                if info is not None:
+                    numels[-1] = info.shape.numel()
+                    if not dtype:
+                        dtype = info.dtype
+                    else:
+                        assert dtype == info.dtype
+                if numels[-1] == 0:
+                    _empty_ranks.add(rank)
+
+            assert not empty_ranks or empty_ranks == _empty_ranks
+            empty_ranks = _empty_ranks
+            if state_name not in state_buffers:
+                state_buffers[state_name] = [
+                    None for _ in fsdp_param_info.param_indices
+                ]
+            local_state = input_states[fqn].get(state_name, None)
+            # N.B. We need to move the state to compute_device. The reason is
+            # not yet clear and we need to figure out why the state may be on a
+            # different device.
+            if local_state is not None:
+                local_state = local_state.to(fsdp_param_info.state.compute_device)
+            state_buffers[state_name][fsdp_param_info.param_indices[fqn]] = local_state
+
+        # Restoring the scalar and non-tensor states. If the corresponding
+        # non-scalar states do not exist on the rank, we also skip the scalar
+        # non-tensor states on that rank.
+        for rank, object_state in enumerate(state_info):
+            if rank in empty_ranks:
+                continue
+            for name, non_tensor_value in object_state.non_tensors.items():
+                curr_non_tensor_value = gathered_state.get(name, None)
+                assert (
+                    curr_non_tensor_value is None
+                    or curr_non_tensor_value == non_tensor_value
+                ), (
+                    f"Rank {rank} has different values for {name}: {non_tensor_value}."
+                    + f" Other ranks: {curr_non_tensor_value}"
+                )
+                gathered_state[name] = non_tensor_value
+
+            for name, scalar_tensor_value in object_state.scalar_tensors.items():
+                curr_scalar_tensor_value = gathered_state.get(name, None)
+                assert curr_scalar_tensor_value is None or torch.equal(
+                    scalar_tensor_value, curr_scalar_tensor_value
+                ), (
+                    f"Rank {rank} has different values for {name}: {scalar_tensor_value}."
+                    + f" Other ranks: {curr_scalar_tensor_value}"
+                )
+                gathered_state[name] = scalar_tensor_value
+
+    return dtype, state_buffers  # type: ignore[possibly-undefined]
+
+
+def _unflatten_orig_param_states(
+    fsdp_param_info: FSDPParamInfo,
+    output_states: Dict[str, Dict[str, Any]],
+    state_name: str,
+    shard_state: bool,
+    to_save: bool,
+    cpu_offload: bool,
+) -> None:
+    """
+    Given a output state dict, ``output_states``, which the keys are FQNs to the
+    original parameters (not FlatParameters nor parmeter ID), and the values
+    are gathered states, unflatten the states to the original dimensions.
+
+    This function performs the unflattening process in-place.
+    """
+    if not to_save:
+        return
+    flat_param = fsdp_param_info.handle.flat_param
+    fsdp_state = fsdp_param_info.state
+    for fqn, gathered_state in output_states.items():
+        value = gathered_state[state_name]
+        param_idx = fsdp_param_info.param_indices[fqn]
+
+        # TODO: This solution is not general and only apply to PTD TP solution.
+        if isinstance(value, DTensor):
+            placement = value.placements[0]
+            # If gathered state is a DTensor and its TP placement is not Replicate(), we need to
+            # gather the tensor on its TP dimension before chunking them into DTensor again.
+            if placement != Replicate():
+                placement_dim = placement.dim  # type: ignore[attr-defined]
+                value_local = value.redistribute(placements=(Replicate(),))
+                reshape_size = list(flat_param._shapes[param_idx])
+                reshape_size[placement_dim] *= value.device_mesh.size(0)
+                reshape_size = torch.Size(reshape_size)
+                value = value.reshape(reshape_size)
+            # If gathered state is a replicate DTensor, we directly reshape it.
+            else:
+                value = value.reshape(flat_param._shapes[param_idx])
+        else:
+            # If gathered state is a tensor, we directly reshape it into unflatten state.
+            value = value.reshape(flat_param._shapes[param_idx])
+
+        if shard_state:
+            osd_config = fsdp_state._optim_state_dict_config
+            if getattr(osd_config, "_use_dtensor", False):
+                assert fsdp_state._device_mesh is not None
+                value = _ext_chunk_dtensor(
+                    value,
+                    fsdp_state.rank,
+                    fsdp_state._device_mesh,
+                    fsdp_state._fsdp_extension,
+                )
+            else:
+                assert fsdp_state.process_group is not None
+                value = _ext_chunk_tensor(
+                    value,
+                    fsdp_state.rank,
+                    fsdp_state.world_size,
+                    fsdp_state._device_handle.device_count(),
+                    fsdp_state.process_group,
+                    fsdp_state._fsdp_extension,
+                )
+        elif not cpu_offload:
+            with SimpleProfiler.profile("clone"):
+                value = value.detach().clone()
+
+        if cpu_offload:
+            with SimpleProfiler.profile(SimpleProfiler.Type.D2H):
+                value = value.cpu()
+        gathered_state[state_name] = value
+
+
+def _allgather_orig_param_states(
+    fsdp_param_info: FSDPParamInfo,
+    gathered_state_info: List[Dict[str, StateInfo]],
+    input_states: Dict[str, Any],
+    shard_state: bool,
+    to_save: bool,
+    cpu_offload: bool,
+) -> Dict[str, Dict[str, Any]]:
+    """
+    Given the ``gathered_state_info`` and ``input_states``, the API allgathers
+    all tensor states and restore non-tensor states from ``gathered_state_info``.
+    """
+    fsdp_state = fsdp_param_info.state
+    if fsdp_state.rank == 0 and dist.get_debug_level() == dist.DebugLevel.DETAIL:
+        logger.info(
+            "Memory Summary before calling to _allgather_orig_param_states %s",
+            fsdp_state._device_handle.memory_summary(),
+        )
+
+    output_states: Dict[str, Dict[str, Any]] = {fqn: {} for fqn in input_states.keys()}
+
+    dtype, state_buffers = _convert_all_state_info(
+        fsdp_param_info, gathered_state_info, input_states, output_states
+    )
+
+    if len(state_buffers) == 0:
+        return output_states
+
+    has_state_params: List[bool] = [
+        True if fqn in output_states else False
+        for fqn, idx in fsdp_param_info.param_indices.items()
+    ]
+
+    # Loop through the ``state_buffers`` and construct the flattened, concatenated,
+    # sharded states. The size of the constructed state will be the same size as
+    # flat_param (also sharded).
+    # Then we perform an allgather_into_tensor to get the full flat_param state.
+    # The full flat_param state is the result of concatenation of multiple states
+    # the order of of flat_param._fqns.
+    # The final step is to split the flat_param state into original param states
+    # and return the result.
+    flat_param = fsdp_param_info.handle.flat_param
+    empty_func = functools.partial(
+        torch.empty, dtype=dtype, device=fsdp_state.compute_device
+    )
+    gathered_tensor = empty_func(flat_param._padded_unsharded_size)
+    # Synchronize can be slow but this will be easier for us to debug.
+    fsdp_state._device_handle.synchronize()
+    for state_name, buffers in state_buffers.items():
+        local_buffers: List[torch.Tensor] = []
+        begin = fsdp_state.rank * flat_param._sharded_size.numel()
+        # End is inclusive.
+        end = begin + flat_param._sharded_size.numel() - 1
+        # param_idx corresponds to the parameter index in the FlatParameter.
+        mem_offset, param_idx = 0, 0
+        for numel, is_padding in zip(
+            flat_param._numels_with_padding, flat_param._is_padding_mask
+        ):
+            frozen_and_no_state = not is_padding and (
+                not fsdp_param_info.param_requires_grad[param_idx]
+                and not has_state_params[param_idx]
+            )
+
+            if is_padding or frozen_and_no_state:
+                # This memory range is a padding or the param is frozen and does
+                # not require gradient. For the later case, we treat it as a
+                # padding and add empty values to the local_buffers.
+
+                padding_begin, padding_end = mem_offset, mem_offset + numel - 1
+                if padding_begin <= begin <= padding_end:
+                    # The range is an align padding before the first parameter in
+                    # the shard. The shard includes parts of this align padding.
+                    padding_len = (
+                        padding_end - begin + 1
+                        if end >= padding_end
+                        else end - begin + 1
+                    )
+                elif padding_begin <= end <= padding_end:
+                    # The range is an align padding after the last parameter in
+                    # the shard. The shard includes parts of this align padding.
+                    padding_len = (
+                        end - padding_begin + 1
+                        if begin <= padding_begin
+                        else end - begin + 1
+                    )
+                elif begin < padding_begin <= padding_end < end:
+                    # The range is an align padding that is completely in the
+                    # shard.
+                    padding_len = numel
+                else:
+                    padding_len = 0
+                if padding_len:
+                    local_buffers.append(empty_func(padding_len))
+
+            if not is_padding:
+                # This memory range is a parameter in FlatParameter. So there
+                # should be an corresponding state in the optimizer unless the
+                # parameter is frozen, which we treat it as a padding above.
+
+                # We need to check if this rank owns the buffer. If this is None:
+                # 1.) the rank does not own any part of the original parameter.
+                #     As a result, there is no corresponding optimizer state on
+                #     the rank as well.
+                # 2.) the parameter is frozen AND no optimizer state for the
+                #     parameter. If a parameter is frozen, there can still be
+                #     optimizer state if the parameter is not frozen in the
+                #     previous steps.
+                if buffers[param_idx] is not None:
+                    local_buffers.append(cast(torch.Tensor, buffers[param_idx]))
+                param_idx += 1
+
+            mem_offset += numel
+
+        shard_numel_padded = flat_param._sharded_size.numel() - (
+            sum(t.numel() for t in local_buffers)
+        )
+
+        assert flat_param._shard_numel_padded == shard_numel_padded, (
+            "Manually calculated _sharded_numel_padded is incorrect. "
+            f"_shard_numel_padded={flat_param._shard_numel_padded}, "
+            f"shard_numel_padded={shard_numel_padded}, "
+            f"_sharded_size.numel={flat_param._sharded_size.numel()}, "
+            f"_numels_with_padding={flat_param._numels_with_padding}, "
+            f"begin={begin}, end={end},"
+        )
+        if shard_numel_padded > 0:
+            # Add right-handed padding.
+            local_buffers.append(empty_func(shard_numel_padded))
+        local_shard = torch.cat(local_buffers)
+        assert local_shard.numel() * fsdp_state.world_size == gathered_tensor.numel(), (
+            "The size of local shard times the world size should equal to the "
+            "gathered tensor size. The inconsistency may be from a bug of "
+            "FlatParameter's metadata or the reconstruction logic in optimizer "
+            "state dict."
+        )
+        fsdp_state._device_handle.synchronize()
+        with SimpleProfiler.profile(SimpleProfiler.Type.ALLGATHER):
+            dist.all_gather_into_tensor(
+                gathered_tensor, local_shard, group=fsdp_state.process_group
+            )
+            # Synchronize can be slow but this will be easier for us to debug.
+            fsdp_state._device_handle.synchronize()
+
+        unpadded_tensor = gathered_tensor[: flat_param._unpadded_unsharded_size.numel()]
+        flat_param_handle = fsdp_param_info.handle
+        orig_states = flat_param_handle._get_unflat_views_aligned(unpadded_tensor)
+        assert len(orig_states) == len(fsdp_param_info.param_indices), (
+            "The number of parameters from FlatParameter is not consistent to "
+            "the number of states used by optimizer state dict reconstruction "
+            "logic."
+        )
+        for fqn, idx in fsdp_param_info.param_indices.items():
+            if fsdp_param_info.param_requires_grad[idx] or fqn in output_states:
+                output_states[fqn][state_name] = orig_states[idx]
+
+        _unflatten_orig_param_states(
+            fsdp_param_info,
+            output_states,
+            state_name,
+            shard_state,
+            to_save,
+            cpu_offload,
+        )
+
+    del gathered_tensor
+    return output_states
+
+
+def _gather_all_orig_param_state(
+    fsdp_param_info: FSDPParamInfo,
+    input_states: Dict[str, Any],
+    shard_state: bool,
+    to_save: bool,
+    cpu_offload: bool,
+) -> Dict[str, Any]:
+    """
+    Given a optimizer state dict, ``input_states``, which the keys are FQNs to the
+    original parameters (not FlatParameters nor parmeter ID), gather all the
+    states and unflatten them to the original dimensions. Note that all the
+    params referred by the ``input_states`` must be managed by FSDP.
+    """
+    fsdp_state = fsdp_param_info.state
+    if (
+        fsdp_state.world_size == 1
+        or fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD
+    ):
+        return input_states if to_save else {}
+
+    with SimpleProfiler.profile(SimpleProfiler.Type.RESHARDING):
+        with SimpleProfiler.profile(SimpleProfiler.Type.ALLGATHER_OBJ):
+            gathered_state_info = _allgather_state_info(fsdp_state, input_states)
+        output_states = _allgather_orig_param_states(
+            fsdp_param_info,
+            gathered_state_info,
+            input_states,
+            shard_state,
+            to_save,
+            cpu_offload,
+        )
+    if to_save:
+        for key, idx in fsdp_param_info.param_indices.items():
+            if key in output_states:
+                continue
+            if not fsdp_param_info.param_requires_grad[idx]:
+                continue
+
+            raise RuntimeError(
+                f"{key} is not in the output state. "
+                "The FSDPParamInfo has the param keys "
+                f"{sorted(fsdp_param_info.param_indices.keys())} while "
+                "the output_states has the param keys "
+                f"{sorted(output_states.keys())}."
+            )
+        return output_states
+    else:
+        return {}
+
+
+def _convert_state_with_orig_params(
+    all_optim_state_keys: List[_OptimStateKey],
+    optim_state_key_to_param_key: Dict[_OptimStateKey, Union[int, str]],
+    fqn_to_fsdp_param_info: Dict[str, FSDPParamInfo],
+    optim_state_dict: Dict[Union[str, int], Any],
+    to_save: bool,
+    shard_state: bool,
+    cpu_offload: bool = True,
+) -> Dict[str, Any]:
+    fsdp_osd_state: Dict[str, Any] = {}
+    # This variable is used to deduplicate the FSDPParamInfo as one FSDPParamInfo
+    # usually corresponds to multiple parameters. We could not use FSDPParamInfo
+    # as the key because FSDPParamInfo is not hashable. As a result, we fall back
+    # to `id(FSDPParamInfo)`, which the type is an integer.
+    all_states: Dict[int, Dict[str, Any]] = {}
+    # Iterate in rank 0's flat parameter ID order to ensure aligned all-gathers
+    # across ranks
+    for optim_state_key in all_optim_state_keys:
+        param_key: Union[str, int, None] = optim_state_key_to_param_key.get(
+            optim_state_key, None
+        )
+
+        if param_key is None and not optim_state_key.is_fsdp_managed:
+            continue
+
+        if optim_state_key.is_fsdp_managed:
+            fqn = optim_state_key.unflat_param_names[0]
+            fsdp_param_info = fqn_to_fsdp_param_info.get(fqn, None)
+            if fsdp_param_info is None:
+                # This can happen if the not all FSDP instances have all the
+                # parameters. This can happen with FSDP + some MPMD style
+                # parallelism.
+
+                # TODO: it is unclear if we need to do the same check with
+                # non-FSDP managed keys.
+                continue
+            state = {} if param_key is None else optim_state_dict[param_key]
+            if id(fsdp_param_info) not in all_states:
+                all_states[id(fsdp_param_info)] = {}
+            all_states[id(fsdp_param_info)][fqn] = state
+
+        elif to_save:
+            assert len(optim_state_key.unflat_param_names) == 1
+            unflat_param_name = optim_state_key.unflat_param_names[0]
+            with SimpleProfiler.profile("none_fsdp_managed_copy"):
+                param_key = cast(Union[str, int], param_key)
+                fsdp_osd_state[unflat_param_name] = copy.copy(
+                    optim_state_dict[param_key]
+                )
+                if cpu_offload:
+                    for state_name, value in sorted_items(
+                        fsdp_osd_state[unflat_param_name]
+                    ):
+                        if not torch.is_tensor(value):
+                            continue
+                        fsdp_osd_state[unflat_param_name][state_name] = value.cpu()
+
+    # Instead of gathering the state of each parameter individually, we perform
+    # the gathering  all at once to speed up the process.
+    for _all_states in all_states.values():
+        fqn = next(iter(_all_states.keys()))
+        fsdp_param_info = fqn_to_fsdp_param_info[fqn]
+        assert len(fsdp_param_info.param_requires_grad) > 0, (
+            "With use_orig_params, FSDPParamInfo should have requires_grad "
+            "information. However, the length is zero."
+        )
+        for key, idx in fsdp_param_info.param_indices.items():
+            if key in _all_states:
+                continue
+            if not fsdp_param_info.param_requires_grad[idx]:
+                continue
+            raise RuntimeError(
+                f"{key} is not in the optimizer state. "
+                "The FSDPParamInfo has the param keys "
+                f"{sorted(fsdp_param_info.param_indices.keys())} while "
+                "the optimizer has the param keys "
+                f"{sorted(_all_states.keys())}."
+            )
+        fsdp_osd_state.update(
+            _gather_all_orig_param_state(
+                fsdp_param_info,
+                _all_states,
+                shard_state,
+                to_save,
+                cpu_offload,
+            )
+        )
+
+    return fsdp_osd_state
+
+
+def _convert_state_with_flat_params(
+    all_optim_state_keys: List[_OptimStateKey],
+    optim_state_key_to_param_key: Dict[_OptimStateKey, Union[int, str]],
+    fqn_to_fsdp_param_info: Dict[str, FSDPParamInfo],
+    optim_state_dict: Dict[Union[str, int], Any],
+    to_save: bool,
+    shard_state: bool,
+    cpu_offload: bool = True,
+) -> Dict[str, Any]:
+    fsdp_osd_state: Dict[str, Any] = {}
+    # Iterate in rank 0's flat parameter ID order to ensure aligned all-gathers
+    # across ranks
+    for optim_state_key in all_optim_state_keys:
+        param_key: Union[str, int, None] = optim_state_key_to_param_key.get(
+            optim_state_key, None
+        )
+
+        assert param_key is not None, (
+            "If use_orig_params is False, we must be able to find the "
+            f"corresponding param id. {optim_state_key} {param_key}"
+        )
+
+        if optim_state_key.is_fsdp_managed:
+            # If there are multiple unflat_param_names (not use_orig_params),
+            # they share the same FSDPParamInfo. So the first unflat_param_name
+            # is sufficient to fetch the FSDPParamInfo.
+            fqn = optim_state_key.unflat_param_names[0]
+            fsdp_param_info = fqn_to_fsdp_param_info[fqn]
+            unflat_state = _unflatten_optim_state(
+                fsdp_param_info,
+                optim_state_dict[param_key],
+                to_save,
+                shard_state,
+                cpu_offload,
+            )
+            if to_save:
+                assert len(unflat_state) == len(optim_state_key.unflat_param_names)
+                for unflat_param_name, unflat_param_state in zip(
+                    optim_state_key.unflat_param_names,
+                    unflat_state,
+                ):
+                    fsdp_osd_state[unflat_param_name] = unflat_param_state
+        elif to_save:
+            assert len(optim_state_key.unflat_param_names) == 1
+            unflat_param_name = optim_state_key.unflat_param_names[0]
+            fsdp_osd_state[unflat_param_name] = copy.copy(optim_state_dict[param_key])
+            if cpu_offload:
+                for state_name, value in sorted_items(
+                    fsdp_osd_state[unflat_param_name]
+                ):
+                    if not torch.is_tensor(value):
+                        continue
+                    fsdp_osd_state[unflat_param_name][state_name] = value.cpu()
+
+    return fsdp_osd_state
+
+
+@torch.no_grad()
+def _optim_state_dict(
+    model: nn.Module,
+    optim: torch.optim.Optimizer,
+    optim_state_dict: Dict[str, Any],
+    optim_input: Optional[
+        Union[
+            List[Dict[str, Any]],
+            Iterable[nn.Parameter],
+        ]
+    ],
+    rank0_only: bool,
+    shard_state: bool,
+    group: Optional[dist.ProcessGroup],
+    using_optim_input: bool,
+    use_orig_params: bool = False,
+    cpu_offload: bool = True,
+) -> Dict[str, Any]:
+    """
+    Consolidates the optimizer state and returns it as a :class:`dict`
+    following the convention of :meth:`torch.optim.Optimizer.state_dict`,
+    i.e. with keys ``"state"`` and ``"param_groups"``.
+    The flat parameters in ``FSDP`` modules contained in ``model`` are mapped
+    back to their unflattened parameters.
+
+    Parameter keys are not well-defined. For a regular optimizer, the optimizer
+    state_dict contains a mapping from parameter IDs to parameter states.
+    Parameter IDs are the order of parameters in ``optim.param_groups()`` across
+    all the groups. This API also allows user to pass ``optim_input`` for the
+    mapping between parameters and parameter IDs. Using ``optim_input`` is being
+    deprecated.
+
+    If the optimizer is a ``NamedOptimizer``, the optimizer state_dict does not
+    contain parameter IDs mapping but a mapping from parameter FQNs to parameter
+    states. This API finds the mapping from FQNs to parameters if the optimizer
+    is a ``NamedOptimizer``.
+
+    If ``use_orig_params`` is True, each rank will have all FSDP-managed
+    parameters but some of these parameters may be empty due to the sharding.
+    For a regular optim.Optimizer, states for those empty parameters will
+    not be initialized. So, when aggregating the FQNs across ranks, no assert
+    will be raised on a rank even if it does not have all the states -- it is
+    valid and FSDP knows how to aggregate them. However, FSDP has to ignore
+    handling those parameters that are not managed by FSDP and do not exist on
+    the local rank -- those are managed by other parallelisms and FSDP does not
+    know how to handle/aggregate them.
+
+    Args:
+        model (nn.Module): Root module (which may or may not be a
+            :class:`FullyShardedDataParallel` instance) whose parameters
+            were passed into the optimizer ``optim``.
+        optim (torch.optim.Optimizer): Optimizer for ``model`` 's
+            parameters.
+        rank0_only (bool): If ``True``, saves the populated :class:`dict`
+            only on rank 0; if ``False``, saves it on all ranks. (Default:
+            ``True``)
+        shard_state (bool): If ``True``, shard and distribute all
+            non-zero-dimension states.
+
+    Returns:
+        Dict[str, Any]: A :class:`dict` containing the optimizer state for
+        ``model`` 's original unflattened parameters and including keys
+        "state" and "param_groups" following the convention of
+        :meth:`torch.optim.Optimizer.state_dict`. If ``rank0_only=False``,
+        then nonzero ranks return an empty :class:`dict`.
+    """
+    SimpleProfiler.reset()
+    cm = ExitStack()
+    cm.enter_context(SimpleProfiler.profile(SimpleProfiler.Type.ALL))
+    _reset_flat_param_grad_info_if_needed(traversal_utils._get_fsdp_handles(model))
+    to_save = not rank0_only or dist.get_rank(group) == 0 or shard_state
+
+    with SimpleProfiler.profile("preprocessing"):
+        param_to_fqns = _get_param_to_fqns(model)
+        flat_param_to_fqn = _get_flat_param_to_fqn(model)
+        is_named_optimizer = _is_named_optimizer(optim_state_dict)
+
+        param_key_to_param = cast(
+            Dict[Union[int, str], nn.Parameter],
+            (
+                _get_param_id_to_param_from_optim_input(model, optim_input)
+                if using_optim_input
+                else _get_param_key_to_param(
+                    optim, model, is_named_optimizer, param_to_fqns, flat_param_to_fqn
+                )
+            ),
+        )
+        fqn_to_fsdp_param_info = _get_fqn_to_fsdp_param_info(model)
+
+    with SimpleProfiler.profile("preprocessing_with_comm"):
+        (
+            all_optim_state_keys,
+            optim_state_key_to_param_key,
+        ) = _map_param_key_to_optim_keys(
+            optim_state_dict,
+            group,
+            param_key_to_param,
+            param_to_fqns,
+            fqn_to_fsdp_param_info,
+            merge_keys=use_orig_params,
+        )
+
+    with SimpleProfiler.profile("state_converting"):
+        convert_fn = (
+            _convert_state_with_orig_params
+            if use_orig_params
+            else _convert_state_with_flat_params
+        )
+        fsdp_osd_state = convert_fn(
+            all_optim_state_keys,
+            optim_state_key_to_param_key,
+            fqn_to_fsdp_param_info,
+            optim_state_dict["state"],
+            to_save,
+            shard_state,
+            cpu_offload,
+        )
+
+    # At this point, communication is complete and ranks can return early if nothing
+    # will be saved on that rank.
+    if not to_save:
+        return {}
+
+    fsdp_osd: Dict[str, Any] = {"state": fsdp_osd_state}
+
+    flat_param_fqns = set(flat_param_to_fqn.values())
+    for key, value in optim_state_dict["state"].items():
+        if key in fsdp_osd_state:
+            continue
+        if key in flat_param_fqns:
+            continue
+        if key in param_key_to_param:
+            continue
+        # This key is not recognized by FSDP. It may be a user-defined state
+        # or some parameters state that FSDP is unable to map from
+        # ``optim.param_groups``.
+        warnings.warn(
+            f"Found a optim state, {key}, that FSDP cannot process. FSDP "
+            "will directly copy everything to the returned state_dict. In "
+            "most cases, this is a user-defined state that is not "
+            "associated with any particular parameter. Another possible "
+            "case is this state is managed by TorchRec. Otherwise, there may "
+            " be a mismatched assumption of optim_state_dict of this mode."
+        )
+        fsdp_osd_state[key] = value
+
+    if "param_groups" in optim_state_dict:
+        fsdp_osd["param_groups"] = _unflatten_param_groups(
+            optim_state_dict, param_key_to_param, param_to_fqns
+        )
+
+    cm.close()
+    SimpleProfiler.dump_and_reset("FSDP _optim_state_dict() profiling: ")
+
+    return fsdp_osd
+
+
+def _get_fqn_to_fsdp_param_info(model: nn.Module) -> Dict[str, FSDPParamInfo]:
+    """
+    Construct the mapping from a param's fqn to its corresponding ``FSDPParamInfo``
+    if the param is managed by FSDP. Shared parameters, or original parameters that
+    are shared across multiple nn.Modules, are required to belong to one and only
+    one FSDP instance and thus correspond to one ``FlatParameter``. Within the one
+    ``FlatParameter``, ``FlatParameter._fqns`` only stores the first FQN of a shared
+    parameter. Thus, the keys in the mapping are guaranteed to map to unique parameters.
+    """
+
+    def module_fn(module, prefix, tree_level, fqn_to_param_info):
+        fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module)
+        if fsdp_state is None:
+            return
+        _lazy_init(fsdp_state, module)
+        handle = _module_handle(fsdp_state, module)
+        if not handle:
+            return
+        flat_param = handle.flat_param
+        fsdp_param_info = FSDPParamInfo(fsdp_state, handle, {}, [])
+        # NOTE: `idx` indexes into the data structures *without* padding
+        # elements
+        for idx, local_fqn in enumerate(flat_param._fqns):
+            fqn = clean_tensor_name(prefix + local_fqn)
+            if fqn in fqn_to_param_info:
+                assert fqn_to_param_info[fqn].handle.flat_param is flat_param, fqn
+            fqn_to_param_info[fqn] = fsdp_param_info
+            fsdp_param_info.param_indices[fqn] = idx
+            if flat_param._params is not None:
+                fsdp_param_info.param_requires_grad.append(
+                    flat_param._params[idx].requires_grad
+                )
+
+    def return_fn(fqn_to_param_info):
+        return fqn_to_param_info
+
+    fqn_to_param_info: Dict[str, FSDPParamInfo] = {}
+    # FlatParameter._fqns stores the local fqn, starting from the root of the
+    # FSDP. Using _apply_to_modules() with model (may not be the FSDP root
+    # module) allows us to construct the global fqn.
+    return _apply_to_modules(
+        model,
+        module_fn,
+        return_fn,
+        [fqn for fqn, _ in _named_parameters_with_duplicates(model)],
+        fqn_to_param_info,
+    )
+
+
+@no_type_check
+def _set_optim_use_dtensor(
+    fsdp_state: _FSDPState,
+    state_dict_settings: StateDictSettings,
+) -> None:
+    # If device_mesh is passed in when initalizing FSDP, we automatically turn the
+    # _use_dtensor flag to be true for ShardedOptimStateDictConfig() if state_dict_type
+    # has to be set to SHARDED_STATE_DICT.
+    if getattr(fsdp_state, "_device_mesh", None):
+        state_dict_type = state_dict_settings.state_dict_type
+        if state_dict_type == StateDictType.LOCAL_STATE_DICT:
+            raise RuntimeError(
+                "Found state_dict_type LOCAL_STATE_DICT.",
+                "DeviceMesh is not compatible with LOCAL_STATE_DICT.",
+                "Please set state_dict_type to SHARDED_STATE_DICT to get DTensor state_dict.",
+            )
+        else:
+            state_dict_settings.optim_state_dict_config._use_dtensor = True
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_runtime_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_runtime_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..1dcea4f325e0b817fdef10ca173dd7727f696171
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_runtime_utils.py
@@ -0,0 +1,1638 @@
+# mypy: allow-untyped-defs
+import functools
+import logging
+from enum import auto, Enum
+from typing import Any, Callable, Dict, List, no_type_check, Optional, Set, Tuple
+
+import torch
+import torch.distributed as dist
+import torch.distributed.fsdp._traversal_utils as traversal_utils
+import torch.nn as nn
+import torch.nn.functional as F
+from torch.autograd import Variable
+from torch.autograd.graph import register_multi_grad_hook
+from torch.distributed.algorithms._comm_hooks import LOW_PRECISION_HOOKS
+from torch.distributed.fsdp._common_utils import (
+    _assert_in_training_states,
+    _FSDPState,
+    _get_module_fsdp_state,
+    _is_composable,
+    _log_post_backward_hook,
+    _no_dispatch_record_stream,
+    clean_tensor_name,
+    TrainingState,
+)
+from torch.distributed.fsdp._flat_param import (
+    FlatParameter,
+    FlatParamHandle,
+    HandleShardingStrategy,
+    HandleTrainingState,
+    RESHARD_AFTER_FORWARD_HANDLE_STRATEGIES,
+)
+from torch.distributed.fsdp._init_utils import HYBRID_SHARDING_STRATEGIES
+from torch.distributed.fsdp.api import BackwardPrefetch
+from torch.distributed.utils import (
+    _apply_to_tensors,
+    _cast_forward_inputs,
+    _p_assert,
+    _to_kwargs,
+)
+from torch.utils import _pytree as pytree
+
+
+logger = logging.getLogger(__name__)
+
+# Do not include "process_group" to enable hybrid shard and MoE cases
+HOMOGENEOUS_ATTR_NAMES = (
+    "_use_orig_params",
+    "limit_all_gathers",
+    "_use_full_prec_in_eval",
+)
+
+
+class _PrefetchMode(Enum):
+    BACKWARD = auto()
+    FORWARD = auto()
+
+
+def _get_fsdp_root_states_with_modules(
+    module: nn.Module,
+) -> Tuple[List[_FSDPState], List[nn.Module]]:
+    """
+    Returns a tuple containing:
+    1. A list of the root ``_FSDPState`` instances in the module tree rooted at
+    ``module`` without any duplicates and following the ``module.modules()``
+    traversal order (which is assumed to be depth-first).
+    2. A corresponding list of the root modules owning the states in the first
+    list.
+
+    This is similar to :func:`_get_fsdp_states_with_modules` except that we
+    must call :func:`_is_fsdp_root` to force a lazy initialization to determine
+    the FSDP root in case lazy initialization has not yet happened.
+    """
+    fsdp_root_states: List[_FSDPState] = []
+    fsdp_root_modules: List[nn.Module] = []
+    visited_fsdp_states: Set[_FSDPState] = set()
+    # NOTE: This function assumes that `module.modules()` proceeds top-down.
+    for submodule in module.modules():
+        optional_state = _get_module_fsdp_state(submodule)
+        if (
+            optional_state is not None
+            and optional_state not in visited_fsdp_states
+            and _is_fsdp_root(optional_state, submodule)
+        ):
+            visited_fsdp_states.add(optional_state)
+            fsdp_root_states.append(optional_state)
+            fsdp_root_modules.append(submodule)
+    return fsdp_root_states, fsdp_root_modules
+
+
+def _get_fsdp_root_states(module: nn.Module) -> List[_FSDPState]:
+    """See :func:`_get_fsdp_root_states_with_modules`."""
+    fsdp_root_states, _ = _get_fsdp_root_states_with_modules(module)
+    return fsdp_root_states
+
+
+def _is_fsdp_root(state: _FSDPState, module: nn.Module) -> bool:
+    """
+    Returns if ``state`` corresponds to that of an FSDP root.
+
+    For the wrapper code path, ``state`` and ``module`` should be the same. For
+    the non-wrapper code path, ``state`` should be ``module`` 's state.
+    """
+    # Force a lazy initialization to determine the FSDP root
+    _lazy_init(state, module)
+    assert state._is_root is not None  # mypy
+    return state._is_root
+
+
+@no_type_check
+def _lazy_init(
+    state: _FSDPState,
+    root_module: nn.Module,
+) -> _FSDPState:
+    """
+    Performs initialization lazily, typically right before the first forward
+    pass. The laziness is needed to ensure that the parameter device/dtype and
+    the FSDP hierarchy have finalized. This method's actual logic only runs on
+    the root FSDP instance, which performs initialization for all non-root FSDP
+    instances to avoid partial initialization.
+
+    For the non-composable code path, ``state`` and ``root_module`` should be
+    the same, namely the FSDP instance itself.
+    """
+    if state._is_root is not None:
+        return  # no-op: already lazily initialized
+    if not state._device_handle.is_available():
+        # Allow the FSDP constructor to run even without CUDA but check this
+        # once we start real execution
+        raise RuntimeError("FSDP does not support CPU only execution")
+    # The following logic is only run on the root FSDP instance since it will
+    # set `_is_root=False` for the non-root instances
+    state._is_root = True
+    _assert_in_training_states(state, [TrainingState.IDLE])
+    _check_flat_params_on_expected_device(state, root_module)
+    state._all_fsdp_states = traversal_utils._get_fsdp_states(root_module)
+    _init_streams(state)
+    buffers, buffer_dtypes = _get_buffers_and_dtypes_for_computation(state, root_module)
+    _cast_buffers_to_dtype_and_device(buffers, buffer_dtypes, state.compute_device)
+    state._exec_order_data.init(state, root_module, state.process_group)
+    _share_state_and_init_handle_attrs(state, root_module)
+    return state
+
+
+def _check_flat_params_on_expected_device(state: _FSDPState, module: nn.Module):
+    """
+    Checks that all ``FlatParameter``s in ``module`` 's tree managed by
+    ``state`` are on the expected device for *lazy initialization*.
+    """
+    cpu_device = torch.device("cpu")
+    for handle in traversal_utils._get_fsdp_handles(module):
+        if (
+            not handle._offload_params
+            and handle.flat_param.device != state.compute_device
+        ):
+            raise RuntimeError(
+                "An FSDP-managed module unexpectedly has parameters on "
+                f"{handle.flat_param.device}. Make sure to move the module to "
+                f"{state.compute_device} before training."
+            )
+        elif handle._offload_params and handle.flat_param.device != cpu_device:
+            raise RuntimeError(
+                "An FSDP-managed module with parameter CPU offloading enabled "
+                f"has parameters on {handle.flat_param.device}. Make sure to "
+                f"not move the module from CPU when offloading parameters."
+            )
+
+
+@no_type_check
+def _share_state_and_init_handle_attrs(
+    root_state: _FSDPState,
+    root_module: nn.Module,
+) -> None:
+    """
+    Shares data structure state from the ``root_state`` to all FSDP states in
+    ``root_module`` 's module tree, and initializes handle attributes. These
+    are done together to require a single loop over the states.
+    """
+    handle = root_state._handle
+    if handle:
+        handle.init_flat_param_attributes()
+    attr_name_to_values: Dict[str, Set[Any]] = {}
+    for attr_name in HOMOGENEOUS_ATTR_NAMES:
+        attr_name_to_values[attr_name] = set()
+    root_state._all_handles = root_state._exec_order_data.all_handles  # share reference
+    # Update _has_optim_in_backward for each handle.
+    for handle in root_state._all_handles:
+        flat_param = handle.flat_param
+        if hasattr(flat_param, "_in_backward_optimizers"):
+            raise RuntimeError(
+                "FSDP optimizer in backward only supported with use_orig_params=True!"
+            )
+        handle._has_optim_in_backward = flat_param._params is not None and any(
+            hasattr(param, "_in_backward_optimizers") for param in flat_param._params
+        )
+        if handle._has_optim_in_backward:
+            torch._C._log_api_usage_once("fsdp.optimizer_in_backward")
+    for fsdp_state in root_state._all_fsdp_states:
+        for attr_name in HOMOGENEOUS_ATTR_NAMES:
+            _p_assert(
+                hasattr(fsdp_state, attr_name),
+                f"FSDP state missing attribute {attr_name}",
+            )
+            attr_name_to_values[attr_name].add(getattr(fsdp_state, attr_name))
+        if fsdp_state is root_state:
+            continue
+        # Relax the assert for non-root FSDP instances in case the nested
+        # initialized module is wrapped again in FSDP later (e.g. after
+        # training to run inference)
+        _p_assert(
+            fsdp_state._is_root is None or not fsdp_state._is_root,
+            "Non-root FSDP instance's `_is_root` should not have been "
+            "set yet or should have been set to `False`",
+        )
+        fsdp_state._is_root = False
+        fsdp_state._unshard_stream = root_state._unshard_stream
+        fsdp_state._post_backward_stream = root_state._post_backward_stream
+        fsdp_state._pre_unshard_stream = root_state._pre_unshard_stream
+        fsdp_state._all_reduce_stream = root_state._all_reduce_stream
+        fsdp_state._default_stream = root_state._default_stream
+        fsdp_state._exec_order_data = root_state._exec_order_data
+        fsdp_state._free_event_queue = root_state._free_event_queue
+        if fsdp_state._fsdp_extension is not None:
+            fsdp_state._fsdp_extension.compute_stream = root_state._default_stream
+        handle = fsdp_state._handle
+        if handle:
+            handle.init_flat_param_attributes()
+    for attr_name, attr_values in attr_name_to_values.items():
+        if len(attr_values) != 1:
+            raise ValueError(
+                f"Expects one homogeneous value for {attr_name} but got {attr_values}"
+            )
+
+
+@no_type_check
+def _init_streams(
+    state: _FSDPState,
+) -> None:
+    """
+    Initializes CUDA streams for overlapping communication, computation, and
+    data transfers. The streams should be shared across FSDP instances.
+    """
+    assert state._is_root
+    assert state._device_handle.is_available()
+    uses_hybrid_sharding = any(
+        fsdp_state.sharding_strategy in HYBRID_SHARDING_STRATEGIES
+        for fsdp_state in state._all_fsdp_states
+    )
+    # Prioritize all-gathers/reduce-scatters over async all-reduce for HSDP and
+    # preserve the default priority of 0 otherwise
+    high_priority = -1 if state.limit_all_gathers and uses_hybrid_sharding else 0
+    # Default stream for computation
+    state._default_stream = state._device_handle.current_stream()
+    if state._fsdp_extension is not None:
+        # set the compute stream to the FSDP extension
+        state._fsdp_extension.compute_stream = state._default_stream
+
+    # Stream for unshard logic, including allocating the all-gather destination
+    # tensors and the all-gathers themselves
+    state._unshard_stream = state._device_handle.Stream(priority=high_priority)
+    # Stream for overlapping gradient reduction with the backward pass gradient
+    # computation
+    state._post_backward_stream = state._device_handle.Stream(priority=high_priority)
+    # Stream for pre-unshard logic, namely allocations and writes for CPU
+    # offloading (H2D copy) and mixed precision (low precision cast)
+    state._pre_unshard_stream = state._device_handle.Stream(priority=high_priority)
+    # Stream to run HSDP's all-reduce as async (if using HSDP)
+    state._all_reduce_stream = (
+        state._device_handle.Stream() if uses_hybrid_sharding else state._default_stream
+    )
+
+
+@no_type_check
+def _unshard(
+    state: _FSDPState,
+    handle: FlatParamHandle,
+    unshard_stream: torch.Stream,
+    pre_unshard_stream: torch.Stream,
+) -> None:
+    """
+    Unshards the handles in ``handles``. If the handles are in
+    :meth:`summon_full_params` and are using mixed precision, then they are
+    forced to full precision.
+
+    Postcondition: handle's ``FlatParameter`` 's data is the padded
+    unsharded flat parameter on the compute device.
+    """
+    if not handle:
+        return
+    with state._device_handle.stream(pre_unshard_stream):
+        ran_pre_unshard = handle.pre_unshard()
+    if ran_pre_unshard:
+        unshard_stream.wait_stream(pre_unshard_stream)
+    if state.limit_all_gathers:
+        event = state._free_event_queue.dequeue_if_needed()
+        if event:
+            with torch.profiler.record_function(
+                "FullyShardedDataParallel.rate_limiter"
+            ):
+                event.synchronize()
+    with state._device_handle.stream(unshard_stream):
+        handle.unshard()
+        handle.post_unshard()
+
+
+@no_type_check
+def _reshard(
+    state: _FSDPState,
+    handle: FlatParamHandle,
+    free_unsharded_flat_param: bool,
+):
+    """
+    Reshards the handle. ``free_unsharded_flat_param`` indicates whether to
+    free the handle's padded unsharded flat parameter.
+    """
+    handle.reshard(free_unsharded_flat_param)
+    if state.limit_all_gathers and free_unsharded_flat_param:
+        if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
+            # We don't run a even queue for freeing under torch compile atm
+            # But maybe we need to? TODO(voz): Look into this
+            free_event = state._device_handle.Event()
+            free_event.record()
+            state._free_event_queue.enqueue(free_event)
+    handle.post_reshard()
+    # Flat parameter freed or not, we always have to "unshard" the parameter
+    # upon next access to get its shape correct.
+    handle._prefetched = False
+
+
+def _unshard_grads(
+    handle: Optional[FlatParamHandle],
+) -> None:
+    if handle:
+        handle.unshard_grad()
+
+
+def _reshard_grads(
+    handle: Optional[FlatParamHandle],
+) -> None:
+    if handle:
+        handle.reshard_grad()
+
+
+@no_type_check
+def _pre_forward(
+    state: _FSDPState,
+    handle: Optional[FlatParamHandle],
+    unshard_fn: Callable,
+    module: nn.Module,
+    args: Tuple[Any, ...],
+    kwargs: Dict[str, Any],
+) -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
+    """
+    Runs the pre-forward logic. This includes an opportunity to unshard
+    currently sharded parameters such as those for the current forward and
+    registering post-backward hooks for these current parameters. This function
+    also converts forward ``args`` and ``kwargs`` to the given precision.
+
+    Args:
+        handles (List[FlatParamHandle]): Handles giving the parameters used in
+            the current forward.
+        unshard_fn (Optional[Callable]): A callable to unshard any currently
+            sharded parameters or ``None`` to not do any unsharding.
+        module (nn.Module): Module whose forward this method runs right before;
+            expected by the hook signature.
+        args (Tuple[Any, ...]): Module forward ``args``.
+        kwargs (Dict[str, Any]): Module forward ``kwargs``.
+    """
+    with torch.profiler.record_function("FullyShardedDataParallel._pre_forward"):
+        # For `fully_shard` + `checkpoint`, skip pre-forward logic in the
+        # recomputed forward
+        if handle and handle._training_state == HandleTrainingState.BACKWARD_PRE:
+            # For both checkpoint implementations, we do not need to re-cast
+            # inputs here since they will be checkpointed in the low precision
+            # either by AC or normally by autograd as long as the AC region is
+            # nested within FSDP
+            return args, kwargs
+        state.training_state = TrainingState.FORWARD_BACKWARD
+        state._exec_order_data.record_pre_forward(handle, module.training)
+        if handle:
+            handle._training_state = HandleTrainingState.FORWARD
+        if unshard_fn is not None:
+            unshard_fn(state, handle)
+        # Register post-backward hooks to reshard the parameters and reduce-scatter
+        # their gradients. They must be re-registered every forward pass in case
+        # the `grad_fn` is mutated.
+        _register_post_backward_hook(state, handle)
+        # We have to reallocate the _cpu_grad if optimizer overlap
+        # set the grad to None in the backward pass.
+        if handle and handle._offload_params and handle.flat_param._cpu_grad is None:
+            handle.flat_param._cpu_grad = torch.zeros_like(
+                handle.flat_param._local_shard, device=torch.device("cpu")
+            ).pin_memory(device=state.compute_device)
+
+        should_cast_forward_inputs = (
+            state._handle and not state._handle._force_full_precision
+        )
+
+        if should_cast_forward_inputs and state.mixed_precision.cast_forward_inputs:
+            # Recursively convert args and kwargs to specified precision.
+            input_dtype: Optional[torch.dtype] = state.mixed_precision.param_dtype
+            args, kwargs = _cast_forward_inputs(input_dtype, *args, **kwargs)
+        _register_post_backward_reshard_only_hook(state, handle, args, kwargs)
+        return args, kwargs
+
+
+@no_type_check
+def _pre_forward_unshard(
+    state: _FSDPState,
+    handle: Optional[FlatParamHandle],
+) -> None:
+    """Unshards parameters in the pre-forward."""
+    if not handle:
+        return
+    # If the handles have been prefetched, then there is no need to call
+    # `_unshard()` again
+    if not handle._prefetched:
+        _unshard(state, handle, state._unshard_stream, state._pre_unshard_stream)
+    handle._needs_pre_forward_unshard = False
+    # Don't wait during trace
+    if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
+        current_stream = state._device_handle.current_stream()
+        if state._unshard_event is not None:
+            current_stream.wait_event(state._unshard_event)
+            state._unshard_event = None
+        else:
+            current_stream.wait_stream(state._unshard_stream)
+    with torch.profiler.record_function(
+        "FullyShardedDataParallel._pre_forward_prefetch"
+    ):
+        _prefetch_handle(state, handle, _PrefetchMode.FORWARD)
+
+
+@no_type_check
+def _post_forward(
+    state: _FSDPState,
+    handle: Optional[FlatParamHandle],
+    reshard_fn: Callable,
+    module: nn.Module,
+    input: Any,
+    output: Any,
+) -> Any:
+    """
+    Runs the post-forward logic. This includes an opportunity to reshard
+    currently unsharded parameters such as those used in the current forward
+    and registering pre-backward hooks on the forward outputs.
+
+    Args:
+        handles (List[FlatParamHandle]): Handles giving the parameters used in
+            the current forward.
+        reshard_fn (Optional[Callable]): A callable to reshard any currently
+            unsharded parameters (e.g. from the current forward) or ``None`` to
+            not do any resharding.
+        module (nn.Module): Module whose forward just ran, which should be a
+            fully sharded module (see [Note: Fully Sharded Module]); expected
+            by the hook signature.
+        input (Any): Unused; expected by the hook signature.
+        output (Any): Forward pass output; pre-backward hooks are registered on
+            the tensors that require gradients in this output.
+
+    Postcondition: Each ``FlatParameter`` 's data points to the sharded flat
+    parameter.
+    """
+    with torch.profiler.record_function("FullyShardedDataParallel._post_forward"):
+        # For `fully_shard` + `checkpoint`, skip post-forward logic in the
+        # recomputed forward
+        if handle and handle._training_state == HandleTrainingState.BACKWARD_PRE:
+            return output
+
+        state._exec_order_data.record_post_forward(handle)
+        if reshard_fn is not None:
+            reshard_fn(state, handle)
+        # Register pre-backward hooks to unshard the flat parameters for the
+        # gradient computation (if needed)
+        output = _register_pre_backward_hooks(state, module, output, handle)
+        state.training_state = TrainingState.IDLE
+        if handle:
+            handle._training_state = HandleTrainingState.IDLE
+        return output
+
+
+@no_type_check
+def _post_forward_reshard(
+    state: _FSDPState,
+    handle: FlatParamHandle,
+) -> None:
+    """Reshards parameters in the post-forward."""
+    if not handle:
+        return
+    # Do not free the root's parameters in the post-forward for `FULL_SHARD`
+    # with the intention that they are immediately used for backward
+    # computation (though this may not be true)
+    free_unsharded_flat_param = (
+        not state._is_root
+        and handle._sharding_strategy in RESHARD_AFTER_FORWARD_HANDLE_STRATEGIES
+    )
+    _reshard(state, handle, free_unsharded_flat_param)
+
+
+@no_type_check
+def _root_pre_forward(
+    state: _FSDPState,
+    module: nn.Module,
+    args,
+    kwargs,
+) -> None:
+    """
+    Runs pre-forward logic specific to the root FSDP instance, which should run
+    before any individual module's pre-forward. This starts with an attempt at
+    lazy initialization (which only runs non-vacuously once). Otherwise, if
+    this is called on a non-root FSDP instance, then it returns directly.
+
+    Args:
+        module (nn.Module): Module for which this logic tries to run. It may or
+            may not be the root. If not, then this method does not do anything.
+    """
+    with torch.profiler.record_function("FullyShardedDataParallel._root_pre_forward"):
+        _lazy_init(state, module)
+        _p_assert(state._is_root is not None, "Expects a root FSDP to have been set")
+        if not state._is_root:
+            # Always cast forward inputs in the root of this local FSDP unit for mixed
+            # precision, as this is where mixed precision could be configed.
+            # This is more useful for auto wrapping that is recommended in composable path.
+            # For manual wrapping, cast forward inputs on each local FSDP unit root will
+            # increase some overhead, so not turned on for model wrapper path right now where
+            # manual wrapping is more broadly used.
+            if _is_composable(state):
+                return _root_cast_forward_input(state, module, args, kwargs)
+            return args, kwargs
+
+        # We cast buffers back to full precision if we're forcing full precision. Disjointly, we check if buffers
+        # are in full precision and if we should cast them back to lower precision, which happens when
+        # exiting eval() mode.
+        handle = state._handle
+        if handle:
+            should_cast_buffers_to_full_prec = handle._force_full_precision
+        else:
+            should_cast_buffers_to_full_prec = True
+
+        if should_cast_buffers_to_full_prec:
+            _cast_buffers_to_dtype_and_device(
+                buffers=dict(module.named_buffers()).values(),
+                buffer_dtypes=list(state._buffer_name_to_orig_dtype.values()),
+                device=state.compute_device,
+            )
+            # This flag is only set when we cast buffers to full precision, to avoid the
+            # CPU overhead that can stem from retrieving all buffers and their types in the
+            # following else branch.
+            state._needs_buffer_dtype_restore_check = True
+        elif getattr(state, "_needs_buffer_dtype_restore_check", False):
+            # Check if buffers are in full precision and we need to cast them
+            # back down.
+            (
+                buffers,
+                buffer_dtypes_for_computation,
+            ) = _get_buffers_and_dtypes_for_computation(state, module)
+            if len(buffers) > 0 and len(buffer_dtypes_for_computation) > 0:
+                if any(
+                    buffer.dtype != buffer_dtype_for_computation
+                    for buffer, buffer_dtype_for_computation in zip(
+                        buffers, buffer_dtypes_for_computation
+                    )
+                ):
+                    # Assume we have to cast everything if there is one mismatch
+                    _cast_buffers_to_dtype_and_device(
+                        buffers, buffer_dtypes_for_computation, state.compute_device
+                    )
+            # We don't have to check this again until we cast buffers to full precision again.
+            state._needs_buffer_dtype_restore_check = False
+
+        if state.forward_prefetch:
+            handles = []
+            for fsdp_state in state._all_fsdp_states:
+                if fsdp_state._handle:
+                    handles.append(fsdp_state._handle)
+            for handle in handles:
+                handle._needs_pre_forward_unshard = True
+                handle._prefetched = False
+        _wait_for_computation_stream(
+            state._device_handle.current_stream(),
+            state._unshard_stream,
+            state._pre_unshard_stream,
+        )
+        _reset_flat_param_grad_info_if_needed(state._all_handles)
+
+        # Prepares the forward inputs by moving them to ``compute_device``
+        # TODO: Do not use the side stream for tensor copies for now; investigate
+        # the perf with/without it.
+        with torch.profiler.record_function("FullyShardedDataParallel._to_kwargs"):
+            args_tuple, kwargs_tuple = _to_kwargs(
+                args, kwargs, state.compute_device, False
+            )
+        args = args_tuple[0]
+        kwargs = kwargs_tuple[0]
+
+        return _root_cast_forward_input(state, module, args, kwargs)
+
+
+@no_type_check
+def _root_cast_forward_input(
+    state: _FSDPState, module: torch.nn.Module, args, kwargs
+) -> Tuple[Any, Any]:
+    if state._handle:
+        force_full_precision = not state._handle._force_full_precision
+    else:
+        force_full_precision = True
+
+    should_cast_forward_inputs = (
+        (module.training or not state._use_full_prec_in_eval) and force_full_precision
+    ) and state.mixed_precision.cast_root_forward_inputs
+
+    if should_cast_forward_inputs:
+        input_dtype: Optional[torch.dtype] = state.mixed_precision.param_dtype
+        args, kwargs = _cast_forward_inputs(input_dtype, *args, **kwargs)
+
+    return args, kwargs
+
+
+@no_type_check
+def _pre_backward_hook(
+    state: _FSDPState,
+    module: nn.Module,
+    handle: FlatParamHandle,
+    grad,
+    *unused: Any,
+) -> Any:
+    """
+    Prepares ``_handle`` 's ``FlatParameter`` s for gradient computation.
+
+    Args:
+        module (nn.Module): Fully sharded module (see [Note: Fully Sharded
+            Module]).
+    """
+    # Only run the pre-backward hook once per group of handles involved in the
+    # same module forward computation
+    if (
+        handle
+        and hasattr(handle, "_ran_pre_backward_hook")
+        and handle._ran_pre_backward_hook
+    ):
+        return grad
+
+    with torch.profiler.record_function("FullyShardedDataParallel._pre_backward_hook"):
+        # Queue the post-backward callback once for the root FSDP instance to
+        # attach it to the outermost backward graph task so that it is called
+        # after all backward calls complete
+        if state._is_root and not state._post_backward_callback_queued:
+            _register_post_backward_final_callback(state, module)
+            _reset_flat_param_grad_info_if_needed(state._all_handles)
+        elif handle:
+            allowed_states = [TrainingState.IDLE]
+            if _is_composable(state):
+                allowed_states.append(TrainingState.FORWARD_BACKWARD)
+            _assert_in_training_states(state, allowed_states)
+        state.training_state = TrainingState.FORWARD_BACKWARD
+        # Queueing the post-backward callback is the only logic that is not
+        # per-handle in the pre-backward hook, so we can return early here if
+        # there are no handles.
+        if not handle:
+            return grad
+        handle._training_state = HandleTrainingState.BACKWARD_PRE
+
+        if handle._needs_pre_backward_unshard:
+            # If the handles have been prefetched, then there is no need to
+            # call `_unshard()` again
+            if not handle._prefetched:
+                _unshard(
+                    state,
+                    handle,
+                    state._unshard_stream,
+                    state._pre_unshard_stream,
+                )
+            # Don't wait during trace
+            if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
+                state._device_handle.current_stream().wait_stream(state._unshard_stream)
+
+        # Set this to `False` to ensure that a mistargeted prefetch does not
+        # actually unshard these handles
+        handle._needs_pre_backward_unshard = False
+        with torch.profiler.record_function(
+            "FullyShardedDataParallel._pre_backward_prefetch"
+        ):
+            _prefetch_handle(state, handle, _PrefetchMode.BACKWARD)
+        handle.prepare_gradient_for_backward()
+        handle._ran_pre_backward_hook = True
+        return grad
+
+
+@no_type_check
+@torch.no_grad()
+def _post_backward_hook(
+    state: _FSDPState,
+    handle: FlatParamHandle,
+    flat_param,
+    *unused: Any,
+):
+    """
+    Reduce-scatters the gradient of ``handle`` 's ``FlatParameter``.
+
+    Precondition: The ``FlatParameter`` 's ``.grad`` attribute contains the
+    unsharded gradient for the local batch.
+
+    Postcondition:
+    - If using ``NO_SHARD``, then the ``.grad`` attribute is the reduced
+    unsharded gradient.
+    - Otherwise, the ``_saved_grad_shard`` attribute is the reduced sharded
+    gradient (accumulating with any existing gradient).
+    """
+    _log_post_backward_hook(state, handle, logger)
+    flat_param = handle.flat_param
+    flat_param._post_backward_called = True
+    with torch.autograd.profiler.record_function(
+        "FullyShardedDataParallel._post_backward_hook"
+    ):
+        _assert_in_training_states(state, [TrainingState.FORWARD_BACKWARD])
+        # For multiple applications of reentrant AC across submodules sharing
+        # the same `FlatParameter`, the post-backward hook may run multiple
+        # times in one backward, in which case we permit the state to already
+        # be in `BACKWARD_POST`.
+        _p_assert(
+            handle._training_state
+            in (HandleTrainingState.BACKWARD_PRE, HandleTrainingState.BACKWARD_POST),
+            f"Expects `BACKWARD_PRE` or `BACKWARD_POST` state but got {handle._training_state}",
+        )
+        handle._training_state = HandleTrainingState.BACKWARD_POST
+
+        if flat_param.grad is None:
+            return
+        if flat_param.grad.requires_grad:
+            raise RuntimeError("FSDP does not support gradients of gradients")
+
+        _post_backward_reshard(state, handle)
+        if not state._sync_gradients:
+            if handle._use_orig_params:
+                handle._use_unsharded_grad_views()
+            return
+
+        # Wait for all ops in the current stream (e.g. gradient computation) to
+        # finish before reduce-scattering the gradient
+        if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
+            state._post_backward_stream.wait_stream(
+                state._device_handle.current_stream()
+            )
+
+        with state._device_handle.stream(state._post_backward_stream):
+            autograd_computed_grad = flat_param.grad.data
+            if (
+                not _low_precision_hook_enabled(state)
+                and flat_param.grad.dtype != handle._reduce_dtype
+                # If we are forcing full precision but communicating grads
+                # (i.e. model.eval() + full precision in eval was configured), don't downcast gradient.
+                and not handle._force_full_precision
+            ):
+                flat_param.grad.data = flat_param.grad.to(handle._reduce_dtype)
+            if handle.uses_sharded_strategy:
+                _reduce_grad(state, handle)
+            else:
+                _reduce_grad_no_shard(state, handle)
+            # Since the unsharded gradient is produced in the computation
+            # stream and consumed in the post-backward stream, inform the
+            # caching allocator (before it goes out of scope)
+            _no_dispatch_record_stream(
+                autograd_computed_grad, state._post_backward_stream
+            )
+
+
+def _post_backward_reshard_only_hook(
+    state: _FSDPState,
+    handle: FlatParamHandle,
+    *unused: Any,
+) -> None:
+    with torch.profiler.record_function(
+        "FullyShardedDataParallel._post_backward_hook_reshard_only"
+    ):
+        # `_pre_backward_hook` may not get executed
+        # if forward output does not require grad
+        # overwrite IDLE state for post-backward prefetching
+        state.training_state = TrainingState.FORWARD_BACKWARD
+        handle._training_state = HandleTrainingState.BACKWARD_POST
+        _post_backward_reshard(state, handle)
+
+
+def _post_backward_reshard(
+    state: _FSDPState,
+    handle: FlatParamHandle,
+    *unused: Any,
+) -> None:
+    free_unsharded_flat_param = _should_free_in_backward(state, handle)
+    _reshard(state, handle, free_unsharded_flat_param)
+
+    # TODO: Post-backward prefetching does not support the multiple handles
+    # per module case since the post-backward hook runs per handle, not per
+    # group of handles.
+    with torch.profiler.record_function(
+        "FullyShardedDataParallel._post_backward_prefetch"
+    ):
+        _prefetch_handle(state, handle, _PrefetchMode.BACKWARD)
+
+
+@no_type_check
+def _should_free_in_backward(
+    state: _FSDPState,
+    handle: FlatParamHandle,
+) -> bool:
+    """
+    Returns whether FSDP should free the unsharded flat parameter in the
+    post-backward or not.
+    """
+    if not handle.uses_sharded_strategy:
+        return False
+    # If not syncing gradients, then we do not free for strategies that do not
+    # reshard after forward as a *heuristic* to tradeoff higher memory for
+    # higher throughput.
+    return (
+        state._sync_gradients
+        or handle._sharding_strategy in RESHARD_AFTER_FORWARD_HANDLE_STRATEGIES
+    )
+
+
+@no_type_check
+def _reduce_grad(state: _FSDPState, handle: FlatParamHandle) -> None:
+    """
+    For sharded strategies, this runs gradient reduction, sharded gradient
+    accumulation if needed, and the post-reduction callback.
+    """
+    flat_param = handle.flat_param
+    uses_hybrid_sharded_strategy = handle._sharding_strategy in (
+        HandleShardingStrategy.HYBRID_SHARD,
+        HandleShardingStrategy._HYBRID_SHARD_ZERO2,
+    )
+    # We clear `.grad` to permit multiple backwards. This avoids a race where
+    # the second backward pass computation precedes ahead of the first backward
+    # pass reduction, which is possible since the reduction is issued in a
+    # separate stream and is async and would result in reducing the wrong
+    # gradient.
+    unsharded_grad = flat_param.grad.data
+    flat_param.grad = None
+    padded_unsharded_grad, new_sharded_grad = _get_reduce_scatter_tensors(
+        state, unsharded_grad
+    )
+    if state._comm_hook is None:  # default path
+        _div_if_needed(padded_unsharded_grad, state._gradient_predivide_factor)
+        pg = (
+            handle._fake_process_group
+            if handle._use_fake_reduce
+            else state.process_group
+        )
+        dist.reduce_scatter_tensor(
+            new_sharded_grad,
+            padded_unsharded_grad,
+            group=pg,
+        )
+        if uses_hybrid_sharded_strategy:
+            # Don't wait during trace
+            if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
+                state._all_reduce_stream.wait_stream(state._post_backward_stream)
+            with state._device_handle.stream(state._all_reduce_stream):
+                # Since the new sharded gradient is produced in the post-
+                # backward stream and consumed in the all-reduce stream,
+                # inform the caching allocator
+                _no_dispatch_record_stream(new_sharded_grad, state._all_reduce_stream)
+                dist.all_reduce(new_sharded_grad, group=state._inter_node_pg)
+                _div_if_needed(new_sharded_grad, state._gradient_postdivide_factor)
+                grad_to_offload = _accumulate_sharded_grad(
+                    state, handle, new_sharded_grad
+                )
+                _post_reduce_grad_callback(state, handle, grad_to_offload)
+                return
+        _div_if_needed(new_sharded_grad, state._gradient_postdivide_factor)
+    else:
+        state._comm_hook(
+            state._comm_hook_state, padded_unsharded_grad, new_sharded_grad
+        )
+        # NOTE: HSDP variants do not support communication hook.
+    grad_to_offload = _accumulate_sharded_grad(state, handle, new_sharded_grad)
+    _post_reduce_grad_callback(state, handle, grad_to_offload)
+
+
+@no_type_check
+def _get_reduce_scatter_tensors(
+    state: _FSDPState, unsharded_grad: torch.Tensor
+) -> Tuple[torch.Tensor, torch.Tensor]:
+    """
+    Returns the input and output tensors to reduce-scatter, respectively.
+    """
+    chunks = list(unsharded_grad.chunk(state.world_size))
+    numel_to_pad = state.world_size * chunks[0].numel() - unsharded_grad.numel()
+    padded_unsharded_grad = (
+        F.pad(unsharded_grad, [0, numel_to_pad]) if numel_to_pad > 0 else unsharded_grad
+    )
+    new_sharded_grad = torch.empty_like(chunks[0])  # padded
+    return padded_unsharded_grad, new_sharded_grad
+
+
+@no_type_check
+def _accumulate_sharded_grad(
+    state: _FSDPState,
+    handle: FlatParamHandle,
+    sharded_grad: torch.Tensor,
+) -> torch.Tensor:
+    """
+    Accumulates the reduce-scattered sharded gradient with any existing sharded
+    gradient if needed, returning the gradient to offload (if CPU offloading is
+    enabled).
+    """
+    flat_param = handle.flat_param
+    _cast_grad_to_param_dtype(state, sharded_grad, flat_param)
+    # Save the sharded gradient in `_saved_grad_shard` to support gradient
+    # accumulation -- for multiple backwards, the gradient reductions may
+    # happen in arbitrary order
+    accumulate_grad = hasattr(flat_param, "_saved_grad_shard")
+    if accumulate_grad:
+        _check_grad_to_accumulate(sharded_grad, flat_param._saved_grad_shard)
+        flat_param._saved_grad_shard += sharded_grad
+    else:
+        flat_param._saved_grad_shard = sharded_grad
+    grad_to_offload = flat_param._saved_grad_shard
+    return grad_to_offload
+
+
+@no_type_check
+def _reduce_grad_no_shard(state: _FSDPState, handle: FlatParamHandle) -> None:
+    """
+    For no-shard, this runs gradient reduction (which directly covers any
+    gradient accumulation implicitly) and the post-reduction callback.
+    """
+    flat_param = handle.flat_param
+    if state._comm_hook is None:  # default path
+        _div_if_needed(flat_param.grad, state._gradient_predivide_factor)
+        dist.all_reduce(flat_param.grad, group=state.process_group)
+        _div_if_needed(flat_param.grad, state._gradient_postdivide_factor)
+    else:
+        state._comm_hook(state._comm_hook_state, flat_param.grad)
+    # For `NO_SHARD`, we can keep the low precision gradients by simply
+    # omitting the cast altogether
+    if not handle._keep_low_precision_grads:
+        _cast_grad_to_param_dtype(state, flat_param.grad, flat_param)
+    grad_to_offload = flat_param.grad.data
+    _post_reduce_grad_callback(state, handle, grad_to_offload)
+
+
+@no_type_check
+def _post_reduce_grad_callback(
+    state: _FSDPState,
+    handle: FlatParamHandle,
+    # Additional arguments needed for the callback logic
+    grad_to_offload: torch.Tensor,
+):
+    """
+    This callback captures any logic to run after the gradient reduction
+    finishes. Currently, this offloads the gradient to CPU if CPU offloading is
+    enabled and uses sharded gradient views if ``use_orig_params=True``.
+    """
+    _offload_grad(state, handle, grad_to_offload)
+    _post_backward_use_sharded_grad_views(handle)
+
+
+@no_type_check
+def _offload_grad(
+    state: _FSDPState,
+    handle: FlatParamHandle,
+    grad_to_offload: torch.Tensor,
+):
+    if not handle._offload_params:
+        return
+    # Offload the gradient to CPU to ensure parameters and gradients are on the
+    # same device as required by the optimizer
+    # TODO: Investigate why `NO_SHARD` breaks correctness when using
+    # `non_blocking=True` here.
+    # TODO (rohan-varma): When CPU offload and optimizer overlap,
+    # non_blocking=True won't work since the copy may have not finished before
+    # the optimizer step executes on CPU. If we want to use non-blocking=True
+    # here, we'll have to synchronize before using result on CPU.
+    non_blocking = handle.uses_sharded_strategy and not handle._has_optim_in_backward
+    handle.flat_param._cpu_grad.copy_(
+        grad_to_offload.detach(), non_blocking=non_blocking
+    )  # synchronized in the post-backward callback
+    # Since the gradient being offloaded may have been produced in the
+    # computation stream and is being consumed here in the post-backward
+    # stream, inform the caching allocator
+    _no_dispatch_record_stream(grad_to_offload.data, state._post_backward_stream)
+
+
+@no_type_check
+def _post_backward_use_sharded_grad_views(handle: FlatParamHandle):
+    if not handle._use_orig_params:
+        return
+    # Since the handle's `FlatParameter` completed its gradient computation, we
+    # should reset the gradient noneness mask
+    handle._reset_is_grad_none()
+    # Delay using sharded gradient views until after the reduce-scatter instead
+    # of immediately after resharding
+    handle._use_sharded_grad_views()
+    if handle._has_optim_in_backward:
+        handle.prepare_gradient_for_optim()
+        for orig_param in handle.flat_param._params:
+            # Check for `None` gradient to filter parameters not in the rank
+            if orig_param.grad is not None and hasattr(
+                orig_param, "_in_backward_optimizers"
+            ):
+                # TODO (rohan-varma): For CPU offload, this unfortunately
+                # operates on CPU because the parameters and gradients have
+                # already been offloaded. We should run this on GPU after
+                # refactoring.
+                for optim in orig_param._in_backward_optimizers:
+                    optim.step()
+
+                optim.zero_grad(set_to_none=True)
+        handle._reset_flat_param_grad_info_if_needed()
+        if handle._offload_params:
+            handle.flat_param._cpu_grad = None
+
+
+def _div_if_needed(tensor: torch.Tensor, div_factor: float) -> None:
+    if div_factor > 1:
+        tensor.div_(div_factor)
+
+
+@no_type_check
+def _cast_grad_to_param_dtype(
+    state: _FSDPState,
+    sharded_grad: torch.Tensor,
+    param: FlatParameter,
+):
+    """
+    Casts ``sharded_grad`` back to the full parameter dtype so that the
+    optimizer step runs with that dtype. This performs an actual cast if
+    1. parameters were in reduced precision during the forward since then
+    gradients would be in that reduced precision, or
+    2. parameters were not in reduced precision but gradients were in
+    reduced precision for communication.
+    However, if a low precision communication hook is registered, then this
+    dtype cast happens in the hook instead.
+    """
+    _assert_in_training_states(state, [TrainingState.FORWARD_BACKWARD])
+    if not _low_precision_hook_enabled(state) and sharded_grad.dtype != param.dtype:
+        low_prec_grad_data = sharded_grad.data
+        sharded_grad.data = sharded_grad.data.to(dtype=param.dtype)
+        # Since for `NO_SHARD`, the gradient is produced in the computation
+        # stream and consumed here in the post-backward stream, inform the
+        # caching allocator; for the sharded strategies, the gradient is
+        # produced in the post-backward stream, so this `record_stream()`
+        # should be a no-op
+        _no_dispatch_record_stream(
+            low_prec_grad_data, state._device_handle.current_stream()
+        )
+
+
+def _check_grad_to_accumulate(
+    new_sharded_grad: torch.Tensor,
+    accumulated_grad: torch.Tensor,
+) -> None:
+    _p_assert(
+        accumulated_grad.shape == new_sharded_grad.shape,
+        "Shape mismatch when accumulating gradients: "
+        f"existing gradient shape={accumulated_grad.shape} "
+        f"new gradient shape={new_sharded_grad.shape}",
+    )
+    _p_assert(
+        accumulated_grad.device == new_sharded_grad.device,
+        "Device mismatch when accumulating gradients: "
+        f"existing gradient device={accumulated_grad.device} "
+        f"new gradient device={new_sharded_grad.device}",
+    )
+
+
+@no_type_check
+def _low_precision_hook_enabled(state: _FSDPState) -> bool:
+    return state._comm_hook in LOW_PRECISION_HOOKS
+
+
+@no_type_check
+@torch.no_grad()
+def _post_backward_final_callback(
+    state: _FSDPState,
+    module: nn.Module,
+):
+    """
+    This waits for the post-backward to finish and performs some final cleanup.
+    This runs at the end of the entire backward pass and should only be called
+    on the root FSDP instance.
+    """
+    _p_assert(
+        state._is_root,
+        "The post-backward callback should only be called on the root FSDP instance",
+    )
+    root_state = state
+
+    if root_state._sync_gradients:
+        current_stream = state._device_handle.current_stream()
+        # TODO (rohan-varma): this also waits for the overlapped optimizer step to finish
+        # since it currently runs in the post-backward stream. That can be
+        # pushed to the next forward if run in a different stream
+        current_stream.wait_stream(root_state._post_backward_stream)
+        if root_state._all_reduce_stream is not current_stream:  # uses HSDP
+            current_stream.wait_stream(root_state._all_reduce_stream)
+        if root_state.cpu_offload.offload_params:
+            # Wait for non-blocking GPU -> CPU sharded gradient copies from the
+            # post-backward hooks to finish explicitly since CPU gradients do
+            # not automatically synchronize with the GPU
+            state._device_handle.current_stream().synchronize()
+    root_state._exec_order_data.next_iter()
+
+    for fsdp_state in state._all_fsdp_states:
+        _catch_all_reshard(fsdp_state)
+        _finalize_params(fsdp_state)
+        fsdp_state.training_state = TrainingState.IDLE
+        handle = fsdp_state._handle
+        if handle:
+            handle._ran_pre_backward_hook = False
+            handle._needs_pre_backward_unshard = False
+            handle._post_forward_index = None
+            handle._training_state = HandleTrainingState.IDLE
+            handle._prefetched = False
+    # Reset for cases like one forward and multiple backwards
+    root_state._post_backward_callback_queued = False
+
+
+@no_type_check
+def _catch_all_reshard(
+    state: _FSDPState,
+) -> None:
+    """
+    Reshards the parameters that may not have been resharded in the
+    post-backward hook. This can happen when a module's output is used in the
+    forward pass, meaning that its pre-backward hook runs (unsharding the
+    parameter), but the post-backward hook does not run because the output was
+    not jused in the loss computation corresponding to this backward pass.
+    """
+    # Wrap with a try-except to provide a more informative traceback if an
+    # error is raised
+    try:
+        if state._handle:
+            # TODO: This already-resharded check is brittle:
+            # https://github.com/pytorch/pytorch/issues/83956
+            already_resharded = (
+                state._handle.flat_param.data_ptr()
+                == state._handle.flat_param._local_shard.data_ptr()
+                # If FSDP skipped using sharded views, then the flat parameter
+                # still points to the sharded data, so we need to reshard to
+                # use sharded views
+                and not state._handle._skipped_use_sharded_views
+            )
+            if already_resharded:
+                return
+            free_unsharded_flat_param = _should_free_in_backward(state, state._handle)
+            _reshard(state, state._handle, free_unsharded_flat_param)
+    except Exception as e:
+        _p_assert(
+            False,
+            f"Got exception in the catch-all reshard for {state}: {str(e)}",
+            raise_assertion_error=False,
+        )
+        raise e
+
+
+@no_type_check
+def _finalize_params(
+    state: _FSDPState,
+) -> None:
+    """Finalizes the parameters before the next iteration."""
+    handle = state._handle
+    if not handle:
+        return
+    flat_param = handle.flat_param
+    if torch.distributed._functional_collectives.is_torchdynamo_compiling():
+        if hasattr(flat_param, "_post_backward_hook_handle"):
+            pbhs_handle = flat_param._post_backward_hook_handle
+            pbhs_handle.remove()
+            del flat_param._post_backward_hook_handle
+    else:
+        if hasattr(flat_param, "_post_backward_hook_state"):
+            post_backward_hook_state_len = len(flat_param._post_backward_hook_state)
+            expected_post_backward_hook_state_len = int(flat_param.requires_grad) + 1
+            _p_assert(
+                post_backward_hook_state_len == expected_post_backward_hook_state_len,
+                f"Invalid: ``_post_backward_hook_state``: {flat_param._post_backward_hook_state}",
+            )
+            flat_param._post_backward_hook_state[-1].remove()
+            delattr(flat_param, "_post_backward_hook_state")
+    if flat_param.requires_grad:
+        if not state._sync_gradients:
+            # Preserve the gradient accumulation state if not synchronizing
+            # gradients: `.grad` remains the unsharded gradient  from prior
+            # `no_sync()` iterations, and `_saved_grad_shard` remains the
+            # sharded gradient from the last synchronized iteration
+            return
+        if not handle._has_optim_in_backward:
+            handle.prepare_gradient_for_optim()
+        _p_assert(
+            hasattr(flat_param, "_post_backward_called"),
+            "Expects `_post_backward_called` to be set on the `FlatParameter`",
+        )
+        flat_param._post_backward_called = False
+
+
+@no_type_check
+def _prefetch_handle(
+    state: _FSDPState,
+    current_handle: Optional[FlatParamHandle],
+    prefetch_mode: _PrefetchMode,
+) -> None:
+    """
+    Prefetches the next handles if needed (without synchronization). An empty
+    handles key cannot prefetch.
+    """
+    if not current_handle:
+        return
+    handle = _get_handle_to_prefetch(state, current_handle)
+    if not handle:
+        return
+    # Temporarily emulate the training state while calling `_unshard` to
+    # ensure the correct `as_params` for `_use_unsharded_views()`
+    prev_training_state = handle._training_state
+    if prefetch_mode == _PrefetchMode.BACKWARD:
+        handle._training_state = HandleTrainingState.BACKWARD_PRE
+    elif prefetch_mode == _PrefetchMode.FORWARD:
+        handle._training_state = HandleTrainingState.FORWARD
+    else:
+        raise ValueError(f"Invalid prefetch mode on rank {state.rank}: {prefetch_mode}")
+    # Prefetch the next set of handles without synchronizing to allow
+    # the sync to happen as late as possible to maximize overlap
+    _unshard(state, handle, state._unshard_stream, state._pre_unshard_stream)
+    handle._training_state = prev_training_state
+    handle._prefetched = True
+
+
+@no_type_check
+def _get_handle_to_prefetch(
+    state: _FSDPState,
+    current_handle: FlatParamHandle,
+) -> FlatParamHandle:
+    """
+    Returns a :class:`list` of the handles keys to prefetch for the next
+    module(s), where ``current_handle`` represents the current module.
+
+    "Prefetching" refers to running the unshard logic early (without
+    synchronization), and the "next" modules depend on the recorded execution
+    order and the current training state.
+    """
+    training_state = _get_training_state(current_handle)
+    valid_training_states = (
+        HandleTrainingState.BACKWARD_PRE,
+        HandleTrainingState.BACKWARD_POST,
+        HandleTrainingState.FORWARD,
+    )
+    _p_assert(
+        training_state in valid_training_states,
+        f"Prefetching is only supported in {valid_training_states} but "
+        f"currently in {training_state}",
+    )
+    eod = state._exec_order_data
+    target_handle: Optional[FlatParamHandle] = None
+    if (
+        training_state == HandleTrainingState.BACKWARD_PRE
+        and state.backward_prefetch == BackwardPrefetch.BACKWARD_PRE
+    ) or (
+        training_state == HandleTrainingState.BACKWARD_POST
+        and state.backward_prefetch == BackwardPrefetch.BACKWARD_POST
+    ):
+        target_handle_candidate = eod.get_handle_to_backward_prefetch(current_handle)
+        if (
+            target_handle_candidate
+            and target_handle_candidate._needs_pre_backward_unshard
+            and not target_handle_candidate._prefetched
+        ):
+            target_handle = target_handle_candidate
+        else:
+            target_handle = None
+    elif training_state == HandleTrainingState.FORWARD and state.forward_prefetch:
+        target_handle_candidate = eod.get_handle_to_forward_prefetch(current_handle)
+        if (
+            target_handle_candidate
+            and target_handle_candidate._needs_pre_forward_unshard
+            and not target_handle_candidate._prefetched
+        ):
+            target_handle = target_handle_candidate
+        else:
+            target_handle = None
+
+    return target_handle
+
+
+def _get_training_state(
+    handle: FlatParamHandle,
+) -> HandleTrainingState:
+    """Returns the training state of the handles in ``handle``."""
+    _p_assert(handle, "Expects a non-empty handle")
+    return handle._training_state
+
+
+@no_type_check
+def _register_pre_forward_hook(
+    state: _FSDPState,
+    module: nn.Module,
+) -> None:
+    """
+    Registers a pre-forward hook on ``module``.
+    """
+    for forward_handle in state._pre_forward_handles:
+        forward_handle.remove()
+    state._pre_forward_handles.clear()
+    module_param_handle = state._fully_sharded_module_to_handle.get(module, None)
+    hook = functools.partial(
+        _pre_forward, state, module_param_handle, _pre_forward_unshard
+    )
+    state._pre_forward_handles.append(
+        module.register_forward_pre_hook(hook, prepend=True, with_kwargs=True)
+    )
+
+
+@no_type_check
+def _register_post_forward_hook(
+    state: _FSDPState,
+    module: nn.Module,
+) -> None:
+    """
+    Registers a post-forward hook on ``module``. Even if the module has no
+    handles, we should register the hook since it will register the module's
+    pre-backward hook.
+    """
+    for forward_handle in state._post_forward_handles:
+        forward_handle.remove()
+    state._post_forward_handles.clear()
+    module_param_handle = state._fully_sharded_module_to_handle.get(module, None)
+    hook = functools.partial(
+        _post_forward,
+        state,
+        module_param_handle,
+        _post_forward_reshard,
+    )
+    state._post_forward_handles.append(module.register_forward_hook(hook))
+
+
+@no_type_check
+def _register_root_pre_forward_hook(
+    state: _FSDPState,
+    module: nn.Module,
+):
+    """
+    Registers root pre-forward hook on ``module``, which should be the local
+    FSDP root.
+
+    NOTE: For the current composable FSDP design, we have each application of
+    ``fully_shard()`` to a module to indicate that that module is the local
+    FSDP root. We may remove this assumption in the future, in which case we
+    will need to register this root pre-forward hook on any candidate module
+    that may be the local FSDP root.
+    """
+    for forward_handle in state._root_pre_forward_handles:
+        forward_handle.remove()
+    state._root_pre_forward_handles.clear()
+    hook = functools.partial(_root_pre_forward, state)
+    state._root_pre_forward_handles.append(
+        module.register_forward_pre_hook(hook, prepend=True, with_kwargs=True)
+    )
+
+
+@no_type_check
+def _register_pre_backward_hooks(
+    state: _FSDPState,
+    module: nn.Module,
+    outputs: Any,
+    handle: FlatParamHandle,
+) -> None:
+    """
+    Registers pre-backward hooks on the tensors that require gradients in the
+    forward pass outputs ``outputs``, which were computed using the
+    ``FlatParameter`` s of ``handles``.
+
+    Args:
+        module (nn.Module): Fully sharded module (see [Note: Fully Sharded
+            Module]).
+
+    Returns:
+        Forward pass outputs with pre-backward hooks registered to tensors that
+        require gradients.
+    """
+    # If there is no gradient computation, then there is no need for
+    # pre-backward logic
+    if not torch.is_grad_enabled():
+        return outputs
+    if state._is_root:
+        state._post_backward_callback_queued = False  # only defined on the root
+
+    if handle:
+        handle._needs_pre_backward_unshard = False
+        # Since these handles' `FlatParameter`s participated in a forward, we
+        # conservatively assume that they will be used in the backward
+        handle._ran_pre_backward_hook = False
+
+    def _register_hook(t: torch.Tensor) -> torch.Tensor:
+        if t.requires_grad:
+            t.register_hook(
+                torch.utils.hooks.unserializable_hook(
+                    functools.partial(_pre_backward_hook, state, module, handle)
+                )
+            )
+            if handle:
+                handle._needs_pre_backward_unshard = True
+        return t
+
+    return _apply_to_tensors(_register_hook, outputs)
+
+
+def _register_post_backward_hook(
+    state: _FSDPState,
+    handle: Optional[FlatParamHandle],
+) -> None:
+    """
+    Registers post-backward hooks on the ``FlatParameter`` s'
+    ``AccumulateGrad`` objects to reshard and to reduce-scatter gradients.
+
+    The ``AccumulateGrad`` object represents the last function that finalizes
+    the ``FlatParameter`` 's gradient, so it only runs after its entire
+    gradient computation has finished.
+
+    We register the post-backward hook only once in the *first* forward that a
+    ``FlatParameter`` participates in. This relies on the ``AccumulateGrad``
+    object being preserved through multiple forwards.
+
+    NOTE: We follow this heuristic to prefer the *first* forward to target the
+    parameter mixed precision case, where there are *separate*
+    ``AccumulateGrad`` objects across the different forwards. (Without
+    parameter mixed precision, the ``AccumulateGrad`` objects are the same.) If
+    we instead prefer the *last* forward, then the hook runs early.
+    """
+    # If there is no gradient computation, then there is no need for
+    # post-backward logic
+    if not torch.is_grad_enabled():
+        return
+    if not handle:
+        return
+    flat_param = handle.flat_param
+
+    if torch.distributed._functional_collectives.is_torchdynamo_compiling():
+        already_registered = hasattr(flat_param, "_post_backward_hook_handle")
+        if already_registered or not flat_param.requires_grad:
+            return
+        hook = functools.partial(_post_backward_hook, state, handle)
+        hook_handle = flat_param.register_post_accumulate_grad_hook(hook)
+        flat_param._post_backward_hook_handle = hook_handle  # type: ignore[attr-defined]
+    else:
+        already_registered = hasattr(flat_param, "_post_backward_hook_state")
+        if already_registered or not flat_param.requires_grad:
+            return
+        # Get the `AccumulateGrad` object
+        temp_flat_param = flat_param.expand_as(flat_param)
+        _p_assert(
+            temp_flat_param.grad_fn is not None,
+            "The `grad_fn` is needed to access the `AccumulateGrad` and "
+            "register the post-backward hook",
+        )
+        acc_grad = temp_flat_param.grad_fn.next_functions[0][0]  # type: ignore[union-attr]
+        assert acc_grad is not None
+        hook_handle = acc_grad.register_hook(
+            functools.partial(_post_backward_hook, state, handle)
+        )
+        flat_param._post_backward_hook_state = (acc_grad, hook_handle)  # type: ignore[attr-defined]
+
+
+def _register_post_backward_reshard_only_hook(
+    state: _FSDPState,
+    handle: Optional[FlatParamHandle],
+    args: Tuple[Any, ...],
+    kwargs: Dict[str, Any],
+) -> None:
+    """
+    Registers post-backward hooks to reshard flat parameters that do not
+    require gradient. We register these using multi-post-grad hooks on the
+    input activations to ensure that all gradients that may depend on the
+    parameters have been computed before resharding.
+    """
+    # If there is no gradient computation, then there is no need for
+    # post-backward logic
+    if not torch.is_grad_enabled():
+        return
+    # Construct `inp_tensors` lazily to avoid CPU overhead in typical case
+    # where each flat parameter requires gradient
+    inp_tensors: Optional[List[torch.Tensor]] = None
+    if not handle:
+        return
+    flat_param = handle.flat_param
+
+    if torch.distributed._functional_collectives.is_torchdynamo_compiling():
+        already_registered = hasattr(flat_param, "_post_backward_hook_handle")
+    else:
+        already_registered = hasattr(flat_param, "_post_backward_hook_state")
+
+    if already_registered or flat_param.requires_grad:
+        return
+    if inp_tensors is None:
+        args_flat = pytree.arg_tree_leaves(*args, **kwargs)
+        inp_tensors = [
+            obj for obj in args_flat if torch.is_tensor(obj) and obj.requires_grad
+        ]
+    assert inp_tensors is not None  # mypy
+    hook_handle = register_multi_grad_hook(
+        inp_tensors, functools.partial(_post_backward_reshard_only_hook, state, handle)
+    )
+    if torch.distributed._functional_collectives.is_torchdynamo_compiling():
+        flat_param._post_backward_hook_handle = hook_handle  # type: ignore[attr-defined, assignment]
+    else:
+        flat_param._post_backward_hook_state = (hook_handle,)  # type: ignore[attr-defined, assignment]
+
+
+@no_type_check
+def _register_post_backward_final_callback(
+    state: _FSDPState, module: nn.Module
+) -> None:
+    """
+    Registers the post-backward final callback that runs at the end of the
+    backward pass. This should be called from the root FSDP instance at the
+    beginning of the pre-backward.
+    """
+    _p_assert(
+        state._is_root,
+        "Only the root FSDP instance should register the post-backward callback",
+    )
+    if state._post_backward_callback_queued:
+        return
+    _assert_in_training_states(state, [TrainingState.IDLE])
+    # Trace does not need this callback
+    if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
+        state._post_backward_callback_queued = True
+        Variable._execution_engine.queue_callback(
+            functools.partial(_post_backward_final_callback, state, module)
+        )
+
+
+def _wait_for_computation_stream(
+    computation_stream: torch.Stream,
+    unshard_stream: torch.Stream,
+    pre_unshard_stream: torch.Stream,
+):
+    """
+    Has the unshard and pre-unshard streams wait for the computation stream.
+    For example, this should be called in the FSDP root's pre-forward to
+    respect optimizer step computation.
+    """
+    # Tracing does not need to wait
+    if torch.distributed._functional_collectives.is_torchdynamo_compiling():
+        return
+    unshard_stream.wait_stream(computation_stream)  # type: ignore[attr-defined]
+    # Having the pre-all-gather stream wait for the current stream even if we
+    # do not leverage the pre-all-gather stream is tolerable since this only
+    # runs once per iteration
+    pre_unshard_stream.wait_stream(computation_stream)  # type: ignore[attr-defined]
+
+
+def _reset_flat_param_grad_info_if_needed(
+    handles: List[FlatParamHandle],
+):
+    """
+    Clears the original parameters' gradients if needed. This method's CPU
+    overhead is minimal, so we may call it throughout FSDP methods, which serve
+    as callsites to free the gradient memory earlier.
+    """
+    if not isinstance(handles, list):
+        handles = [handles]
+    for handle in handles:
+        if handle._use_orig_params:
+            handle._reset_flat_param_grad_info_if_needed()
+
+
+@no_type_check
+def _get_buffers_and_dtypes_for_computation(
+    state: _FSDPState,
+    root_module: nn.Module,
+) -> Tuple[List[torch.Tensor], List[Optional[torch.dtype]]]:
+    """
+    Returns all buffers in the module tree rooted at ``root_module`` and a
+    corresponding list of the buffer dtypes for computation. Each buffer dtype
+    is either ``None`` if buffer mixed precision is not enabled or the buffer
+    low precision dtype otherwise.
+    """
+    _p_assert(state._is_root, "Expects the root to cast buffers")
+    buffers: List[torch.Tensor] = []
+    buffer_dtypes: List[Optional[torch.dtype]] = []
+    visited_buffers: Set[torch.Tensor] = set()
+    # Traverse the FSDP states bottom-up so that we prefer the owning FSDP
+    # instance's mixed precision setting for each buffer
+    fsdp_states, fsdp_modules = traversal_utils._get_fsdp_states_with_modules(
+        root_module
+    )
+    for fsdp_state, fsdp_module in zip(reversed(fsdp_states), reversed(fsdp_modules)):
+        for buffer_name, buffer in fsdp_module.named_buffers():
+            if buffer in visited_buffers:
+                continue
+            visited_buffers.add(buffer)
+            if clean_tensor_name(buffer_name) in fsdp_state._ignored_buffer_names:
+                continue
+            buffers.append(buffer)
+            buffer_dtypes.append(fsdp_state.mixed_precision.buffer_dtype)
+    assert len(buffers) == len(buffer_dtypes), f"{len(buffers)} {len(buffer_dtypes)}"
+    return buffers, buffer_dtypes
+
+
+@no_type_check
+def _get_orig_buffer_dtypes(
+    state: _FSDPState,
+    buffer_names: List[str],
+) -> List[torch.dtype]:
+    """
+    Returns the original buffer types of the given buffer names.
+    """
+    buffer_dtypes: List[torch.dtype] = []
+    for buffer_name in buffer_names:
+        _p_assert(
+            buffer_name in state._buffer_name_to_orig_dtype,
+            f"{buffer_name} is missing from pre-computed dict on rank "
+            f"{state.rank}, which only has keys "
+            f"{state._buffer_name_to_orig_dtype.keys()}",
+        )
+        buffer_dtypes.append(state._buffer_name_to_orig_dtype[buffer_name])
+    return buffer_dtypes
+
+
+def _cast_buffers_to_dtype_and_device(
+    buffers: List[torch.Tensor],
+    buffer_dtypes: List[Optional[torch.dtype]],
+    device: torch.device,
+) -> None:
+    """
+    Casts ``buffers`` to the dtypes given by ``buffer_dtypes`` and moves them
+    to ``device``. If an element in ``buffer_dtypes`` is ``None``, then the
+    corresponding buffer is only moved to ``device``.
+    """
+    _p_assert(
+        buffer_dtypes is None or len(buffers) == len(buffer_dtypes),
+        f"Expects `buffers` and `buffer_dtypes` to have the same length if "
+        f"`buffer_dtypes` is specified but got {len(buffers)} and "
+        f"{len(buffer_dtypes)}",
+    )
+    for buffer, buffer_dtype in zip(buffers, buffer_dtypes):
+        if not torch.is_floating_point(buffer) or buffer_dtype is None:
+            buffer.data = buffer.to(device=device)
+        else:
+            buffer.data = buffer.to(device=device, dtype=buffer_dtype)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_shard_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_shard_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..9769d5296d4efb9d7ca4adf87427d7a4974dc3cc
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_shard_utils.py
@@ -0,0 +1,137 @@
+# mypy: allow-untyped-defs
+import copy
+import itertools
+import math
+from typing import Optional
+
+import torch
+import torch.distributed as dist
+from torch._utils import _get_device_module
+from torch.distributed import distributed_c10d
+from torch.distributed._shard.sharded_tensor import (
+    Shard,
+    ShardedTensor,
+    ShardedTensorMetadata,
+    TensorProperties,
+)
+from torch.distributed._shard.sharding_spec import ShardMetadata
+from torch.distributed.tensor import DeviceMesh, DTensor, Replicate, Shard as DShard
+
+
+def _get_remote_device_str(rank, device_type, num_devices_per_node):
+    if device_type.lower() == "cpu":
+        return f"rank:{rank}/{device_type}"
+    elif device_type.lower() == "hpu":
+        return f"rank:{rank}/{device_type}:{_get_device_module(device_type).current_device()}"
+    else:
+        return f"rank:{rank}/{device_type}:{rank % num_devices_per_node}"
+
+
+def _create_chunk_sharded_tensor(
+    tensor: torch.Tensor,
+    rank: int,
+    world_size: int,
+    num_devices_per_node: int,
+    pg: dist.ProcessGroup,
+    device: Optional[torch.device] = None,
+) -> ShardedTensor:
+    """
+    Shard a tensor to chunks along the first dimension. The local rank will gets its
+    corresponding chunk as the local shard to create a ShardedTensor.
+    """
+    chunks = tensor.chunk(world_size, dim=0)
+    if len(chunks) > rank:
+        local_shard = chunks[rank].clone()
+        offsets = [0 for _ in tensor.size()]
+        offsets[0] = math.ceil(tensor.size()[0] / world_size) * rank
+        local_shards = [Shard.from_tensor_and_offsets(local_shard, offsets, rank)]
+    else:
+        local_shards = []
+
+    # Create a ShardedTensor without invoking communication.
+    chunk_sizes = [list(chunk.size()) for chunk in chunks]
+    dim0_offsets = [0] + list(
+        itertools.accumulate([chunk_size[0] for chunk_size in chunk_sizes])
+    )[:-1]
+    offsets = [0] * (len(chunk_sizes[0]) - 1)
+    chunk_offsets = [[d0] + offsets for d0 in dim0_offsets]
+    device_type = (
+        distributed_c10d._get_pg_default_device(pg).type
+        if device is None
+        else device.type
+    )
+    placements = [
+        _get_remote_device_str(
+            dist.get_global_rank(pg, r),
+            device_type,
+            num_devices_per_node,
+        )
+        for r in range(len(chunk_sizes))
+    ]
+    assert len(chunk_sizes) == len(chunk_offsets) == len(placements)
+    shard_metadata = [
+        ShardMetadata(offset, size, placement)
+        for offset, size, placement in zip(chunk_offsets, chunk_sizes, placements)
+    ]
+    sharded_tensor_metadata = ShardedTensorMetadata(
+        shards_metadata=shard_metadata,
+        size=tensor.size(),
+        tensor_properties=TensorProperties(
+            dtype=tensor.dtype,
+            layout=tensor.layout,
+            requires_grad=False,
+            memory_format=torch.contiguous_format,
+            pin_memory=tensor.is_pinned(),
+        ),
+    )
+    return ShardedTensor._init_from_local_shards_and_global_metadata(
+        local_shards, sharded_tensor_metadata=sharded_tensor_metadata, process_group=pg
+    )
+
+
+def _create_chunk_dtensor(
+    tensor: torch.Tensor,
+    rank: int,
+    device_mesh: DeviceMesh,
+) -> DTensor:
+    """
+    Shard a tensor to chunks along the first dimension. The local rank will gets its
+    corresponding chunk as the local tensor to create a DTensor.
+    """
+    # We need to explicitly call .detach() to return a new tensor detached from the current graph.
+    tensor = tensor.clone().detach()
+
+    # FSDP placements: [Shard(0)]
+    # HSDP placements: [Replicate(), Shard(0)]
+    replicate_placements = [Replicate() for _ in range(device_mesh.ndim)]
+    shard_placements = [Replicate() for _ in range(device_mesh.ndim)]
+    shard_placements[-1] = DShard(0)  # type: ignore[call-overload]
+
+    return DTensor.from_local(
+        tensor, device_mesh, replicate_placements, run_check=False
+    ).redistribute(
+        placements=shard_placements,
+    )
+
+
+def _all_gather_dtensor(
+    tensor: DTensor,
+    root_mesh: Optional[DeviceMesh],
+) -> torch.Tensor:
+    """
+    All gather a DTensor in its sharded dimension and return the local tensor.
+    """
+    assert (
+        root_mesh == tensor.device_mesh
+    ), "The device mesh of a tensor should be a root mesh."
+
+    placements = list(copy.deepcopy(tensor.placements))
+    # FSDP placements: [Shard(0)] -> [Replicate()]
+    # HSDP placements: [Replicate(), Shard(0)] -> [Replicate(), Replicate()]
+    placements[-1] = Replicate()
+    tensor = tensor.redistribute(
+        device_mesh=tensor.device_mesh,
+        placements=placements,
+    )
+
+    return tensor.to_local()
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_state_dict_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_state_dict_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..06dfb00d71e8980364aeab308e904a777ad08614
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_state_dict_utils.py
@@ -0,0 +1,924 @@
+# mypy: allow-untyped-defs
+import contextlib
+import logging
+import math
+import warnings
+from typing import (
+    Any,
+    Callable,
+    cast,
+    Dict,
+    Generator,
+    Iterator,
+    List,
+    no_type_check,
+    Tuple,
+)
+
+import torch
+import torch.distributed as dist
+import torch.distributed.algorithms._checkpoint.checkpoint_wrapper as checkpoint_wrapper
+import torch.nn as nn
+import torch.nn.functional as F
+from torch.distributed._shard.sharded_tensor import (
+    init_from_local_shards,
+    Shard,
+    ShardedTensor,
+)
+from torch.distributed.device_mesh import _mesh_resources
+from torch.distributed.fsdp._common_utils import (
+    _FSDPState,
+    _get_module_fsdp_state_if_fully_sharded_module,
+    _has_fsdp_params,
+    _is_composable,
+    _module_handle,
+    clean_tensor_name,
+    FSDP_PREFIX,
+    FSDP_WRAPPED_MODULE,
+)
+from torch.distributed.fsdp._debug_utils import SimpleProfiler
+from torch.distributed.fsdp._runtime_utils import (
+    _cast_buffers_to_dtype_and_device,
+    _get_orig_buffer_dtypes,
+    _lazy_init,
+    _reset_flat_param_grad_info_if_needed,
+)
+from torch.distributed.fsdp.api import (
+    FullStateDictConfig,
+    ShardingStrategy,
+    StateDictType,
+)
+from torch.distributed.tensor import DTensor
+from torch.distributed.utils import _replace_by_prefix
+
+from ._fsdp_extensions import (
+    _ext_all_gather_dtensor,
+    _ext_chunk_dtensor,
+    _ext_chunk_tensor,
+    _ext_post_unflatten_transform,
+    _ext_pre_load_state_dict_transform,
+)
+from ._unshard_param_utils import _unshard_fsdp_state_params, FLAT_PARAM
+
+
+logger = logging.getLogger(__name__)
+
+
+def _should_unshard_params(fsdp_state: _FSDPState) -> bool:
+    return not (
+        fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD
+        and (_is_composable(fsdp_state) or fsdp_state._use_orig_params)
+    )
+
+
+def _convert_to_wrapped_module_name(module_name: str) -> str:
+    module_name = module_name.replace(f"{FSDP_PREFIX}", "")
+    module_name = module_name.replace(f"{FSDP_WRAPPED_MODULE}", "")
+    if module_name:
+        module_name = f"{module_name}."
+    # `CheckpointWrapper` adds a prefix that has to be removed as well.
+    module_name = module_name.replace(checkpoint_wrapper._CHECKPOINT_PREFIX, "")
+    return module_name
+
+
+def _param_name_infos(
+    module: nn.Module, fsdp_state: _FSDPState
+) -> Iterator[Tuple[str, str, str]]:
+    if not _has_fsdp_params(fsdp_state, module):
+        return
+    for param_name, module_name in _module_handle(
+        fsdp_state, module
+    ).param_module_names():
+        module_name = _convert_to_wrapped_module_name(module_name)
+        fqn = f"{module_name}{param_name}"
+        yield fqn, param_name, module_name
+
+
+def _shared_param_name_infos(
+    module: nn.Module, fsdp_state
+) -> Iterator[Tuple[str, str, str]]:
+    for param_name, module_name in _module_handle(
+        fsdp_state, module
+    ).shared_param_module_names():
+        module_name = _convert_to_wrapped_module_name(module_name)
+        fqn = f"{module_name}{param_name}"
+        yield fqn, param_name, module_name
+
+
+@no_type_check
+def _enter_unshard_params_ctx(
+    module: nn.Module,
+    fsdp_state: _FSDPState,
+    writeback: bool = False,
+    rank0_only: bool = False,
+    offload_to_cpu: bool = False,
+    with_grads: bool = False,
+) -> None:
+    """
+    state_dict hooks cannot use the pure context call as the checkpoint flow
+    requires to enter the context in the pre-hook but leave the context in the
+    post-hook. This API enters the context of ``_unshard_fsdp_state_params``.
+    """
+    assert module not in fsdp_state._unshard_params_ctx, (
+        "Entering the ``_unshard_fsdp_state_params`` context but _unshard_params_ctx[module] "
+        "is not None."
+    )
+    fsdp_state._unshard_params_ctx[module] = _unshard_fsdp_state_params(
+        module,
+        fsdp_state,
+        writeback=writeback,
+        rank0_only=rank0_only,
+        offload_to_cpu=offload_to_cpu,
+        with_grads=with_grads,
+    )
+    fsdp_state._unshard_params_ctx[module].__enter__()
+
+
+@no_type_check
+def _exit_unshard_params_ctx(module: nn.Module, fsdp_state: _FSDPState) -> None:
+    """A helper function to exit ``_unshard_fsdp_state_params`` context."""
+    fsdp_state._unshard_params_ctx[module].__exit__(None, None, None)
+    fsdp_state._unshard_params_ctx.pop(module)
+
+
+def _common_pre_state_dict_hook(
+    module: nn.Module,
+    fsdp_state: _FSDPState,
+) -> None:
+    """Performs the pre-state_dict tasks shared by all state_dict types."""
+    if fsdp_state._device_handle.is_available():
+        fsdp_state._device_handle.synchronize()
+    # TODO: need to check if this is always correct for composable FSDP.
+    _lazy_init(fsdp_state, module)
+    if fsdp_state._is_root:
+        _reset_flat_param_grad_info_if_needed(fsdp_state._all_handles)
+
+
+def _common_unshard_pre_state_dict_hook(
+    module: nn.Module,
+    fsdp_state: _FSDPState,
+    offload_to_cpu: bool,
+    rank0_only: bool,
+) -> None:
+    """
+    Performs the pre-state_dict tasks shared by all state_dict types that require
+    ``_unshard_fsdp_state_params()``. FULL_STATE_DICT and SHARDED_STATE_DICT use this hook.
+    """
+    # For composable `fully_shard`, it does not need to unshard parameters for `NO_SHARD` cases.
+    if not _should_unshard_params(fsdp_state):
+        return
+    _enter_unshard_params_ctx(
+        module,
+        fsdp_state,
+        writeback=False,
+        offload_to_cpu=offload_to_cpu,
+        rank0_only=rank0_only,
+    )
+
+
+@no_type_check
+def _common_unshard_post_state_dict_hook(
+    module: nn.Module,
+    fsdp_state: _FSDPState,
+    state_dict: Dict[str, Any],
+    prefix: str,
+    param_hook: Callable,
+) -> Dict[str, Any]:
+    """
+    The post-state_dict flow that shared by all state_dict types that require
+    ``_unshard_fsdp_state_params()``. FULL_STATE_DICT and SHARDED_STATE_DICT use this
+    hook.
+    """
+    _replace_by_prefix(state_dict, prefix + f"{FSDP_PREFIX}", prefix)
+    # Return early for trivial cases
+    if not state_dict or not _has_fsdp_params(fsdp_state, module):
+        if _should_unshard_params(fsdp_state):
+            _exit_unshard_params_ctx(module, fsdp_state)
+        return state_dict
+
+    # If a rank does not have unsharded parameters(when `rank0_only=True`
+    # and `rank != 0`), then the rank only needed to participate in the
+    # all-gather and does not need to save the # state dict. We simply check
+    # rank0_only to ensure this issue.
+    rank0_only = (
+        fsdp_state._state_dict_type == StateDictType.FULL_STATE_DICT
+        and cast(FullStateDictConfig, fsdp_state._state_dict_config).rank0_only
+    )
+    # no_fsdp_return means the state_dict returned by this rank should contain
+    # only non-FSDP controlled parameters and buffers.
+    no_fsdp_return = rank0_only and fsdp_state.rank != 0
+    if no_fsdp_return and not fsdp_state._use_orig_params:
+        for clean_key in fsdp_state._buffer_names:
+            # This is a hack to support activation checkpoint.
+            clean_key = clean_key.replace(
+                f"{checkpoint_wrapper._CHECKPOINT_PREFIX}.", ""
+            )
+            state_dict.pop(f"{prefix}{clean_key}", None)
+        # Non-zero ranks have flat_param key when rank0_only=True, because rank0_only=True is
+        # passed in to unshard context, but nonzero ranks reshard early, causing this flat_param
+        # to appear in state_dict.
+        state_dict.pop(f"{prefix}{FLAT_PARAM}")
+        _exit_unshard_params_ctx(module, fsdp_state)
+        return state_dict
+
+    # Loop only the parameters saved in this instance's wrapped module to
+    # avoid processing buffers.
+    for fqn, param_name, module_name in _param_name_infos(module, fsdp_state):
+        fqn = f"{prefix}{fqn}"
+        if no_fsdp_return:
+            state_dict.pop(fqn)
+            continue
+        assert fqn in state_dict, (
+            f"FSDP assumes {fqn} is in the state_dict but the state_dict only "
+            f"has {state_dict.keys()}. "
+            f"prefix={prefix}, module_name={module_name}, "
+            f"param_name={param_name} rank={fsdp_state.rank}."
+        )
+
+        param_hook(state_dict, prefix, fqn)
+
+    if _should_unshard_params(fsdp_state):
+        _exit_unshard_params_ctx(module, fsdp_state)
+
+    cpu_device = torch.device("cpu")
+    buffer_clean_fqns = []
+    buffers = []
+    for clean_key in fsdp_state._buffer_names:
+        # This is a hack to support activation checkpoint.
+        clean_key = clean_tensor_name(clean_key)
+        fqn = f"{prefix}{clean_key}"
+        if fqn not in state_dict:
+            # A buffer can be registered as non-persistent.
+            continue
+        if no_fsdp_return:
+            state_dict.pop(fqn)
+        else:
+            buffer = state_dict[fqn]
+            if (
+                fsdp_state._state_dict_config.offload_to_cpu
+                and buffer.device != cpu_device
+            ):
+                state_dict[fqn] = buffer.to(cpu_device)
+            # skip upcasting for ignored buffers
+            if clean_key not in fsdp_state._ignored_buffer_names:
+                buffer_clean_fqns.append(clean_key)
+                buffers.append(state_dict[fqn])
+
+    if buffers:
+        mixed_precision_enabled_for_buffers = (
+            fsdp_state._mixed_precision_enabled_for_buffers()
+            if not _is_composable(fsdp_state)
+            else (fsdp_state.mixed_precision.buffer_dtype is not None)
+        )
+        if mixed_precision_enabled_for_buffers:
+            buffer_dtypes = _get_orig_buffer_dtypes(fsdp_state, buffer_clean_fqns)
+            _cast_buffers_to_dtype_and_device(
+                buffers, buffer_dtypes, fsdp_state.compute_device
+            )
+            for buffer, clean_fqn in zip(buffers, buffer_clean_fqns):
+                fqn = f"{prefix}{clean_fqn}"
+                logger.info("FSDP is casting the dtype of %s to %s", fqn, buffer.dtype)
+                state_dict[fqn] = buffer.clone()
+    return state_dict
+
+
+@no_type_check
+def _full_pre_state_dict_hook(
+    fsdp_state: _FSDPState,
+    module: nn.Module,
+    *args,
+    **kwargs,
+) -> None:
+    """
+    Hook that runs before model.state_dict() is called. pre-state_dict hook is
+    not actually supported by ``nn.Module``. As a result, this API is called
+    from ``_full_post_state_dict_hook()`` to simulate the case. Once pre-state_dict
+    is supported in ``nn.Module``, this hook will be registered as a hook in
+    ``nn.Module``.
+    """
+    if getattr(fsdp_state, "_device_mesh", False):
+        root_mesh = _mesh_resources.get_root_mesh(fsdp_state._device_mesh)
+
+    _common_pre_state_dict_hook(module, fsdp_state)
+    _common_unshard_pre_state_dict_hook(
+        module,
+        fsdp_state,
+        offload_to_cpu=fsdp_state._state_dict_config.offload_to_cpu,
+        rank0_only=cast(FullStateDictConfig, fsdp_state._state_dict_config).rank0_only,
+    )
+
+
+@no_type_check
+def _full_post_state_dict_hook(
+    module: nn.Module,
+    fsdp_state: _FSDPState,
+    state_dict: Dict[str, Any],
+    prefix: str,
+) -> Dict[str, Any]:
+    """
+    Hook that runs after model.state_dict() is called before returning result to
+    user. For FSDP, we may have to clone the tensors in state_dict as params go
+    back to sharded version after _unshard_fsdp_state_params ends, and also remove
+    the ``FSDP_WRAPPED_MODULE`` prefix.
+    """
+
+    def param_hook(
+        state_dict: Dict[str, Any],
+        prefix: str,
+        fqn: str,
+    ) -> None:
+        clean_key = fqn
+        clean_prefix = clean_tensor_name(prefix)
+        # Strip prefix out of key if needed as buffer names and param names
+        # do not have prefix considered as they are not computed in `state_dict`
+        # call.
+        if clean_key.startswith(clean_prefix):
+            clean_key = clean_key[len(clean_prefix) :]
+
+        # Clone parameters before exiting the `_unshard_fsdp_state_params()` context.
+        if not getattr(state_dict[fqn], "_has_been_cloned", False):
+            try:
+                state_dict[fqn] = state_dict[fqn].clone().detach()
+                state_dict[fqn]._has_been_cloned = True  # type: ignore[attr-defined]
+            except BaseException as e:
+                warnings.warn(
+                    f"Failed to clone() tensor with name {fqn} on rank {fsdp_state.rank}. "
+                    "This may mean that this state_dict entry could point to invalid "
+                    "memory regions after returning from state_dict() call if this "
+                    "parameter is managed by FSDP. Please check clone "
+                    f"implementation of {fqn}. Error: {str(e)}"
+                )
+
+    return _common_unshard_post_state_dict_hook(
+        module, fsdp_state, state_dict, prefix, param_hook
+    )
+
+
+def _full_pre_load_state_dict_hook(
+    module: nn.Module,
+    fsdp_state: _FSDPState,
+    state_dict: Dict[str, Any],
+    prefix: str,
+) -> None:
+    _lazy_init(fsdp_state, module)
+    if _should_unshard_params(fsdp_state):
+        with SimpleProfiler.profile("_enter_unshard_params_ctx"):
+            _enter_unshard_params_ctx(module, fsdp_state, writeback=True)
+    # Add FSDP_PREFIX only for wrapper-based FSDP.
+    if not _is_composable(fsdp_state):
+        _replace_by_prefix(state_dict, prefix, prefix + f"{FSDP_PREFIX}")
+
+
+def _full_post_load_state_dict_hook(
+    module: nn.Module, fsdp_state: _FSDPState, *args, **kwargs
+) -> None:
+    if _should_unshard_params(fsdp_state):
+        with SimpleProfiler.profile("_exit_unshard_params_ctx"):
+            _exit_unshard_params_ctx(module, fsdp_state)
+
+
+def _local_pre_state_dict_hook(
+    fsdp_state: _FSDPState,
+    module: nn.Module,
+    *args,
+    **kwargs,
+) -> None:
+    """
+    Hook that runs before model.state_dict() is called. Right now, pre-state_dict
+    hook is not supported by the PyTorch core. So this API is called from
+    `_local_post_state_dict_hook()` to simulate the case.
+    """
+    if (
+        _has_fsdp_params(fsdp_state, module)
+        and not _module_handle(fsdp_state, module).uses_sharded_strategy
+    ):
+        raise RuntimeError(
+            "``local_state_dict`` can only be used when parameters are flatten "
+            "and sharded."
+        )
+    _common_pre_state_dict_hook(module, fsdp_state)
+
+
+@no_type_check
+def _local_post_state_dict_hook(
+    module: nn.Module,
+    fsdp_state: _FSDPState,
+    state_dict: Dict[str, Any],
+    prefix: str,
+) -> Dict[str, Any]:
+    """
+    This hook create a ShardedTensor from the local flat_param and replace
+    the state_dict[f"{prefix}{FLAT_PARAM}] with the ShardedTensor. No copy
+    will happen. The underlying storage is the same.
+    """
+
+    _replace_by_prefix(state_dict, f"{prefix}{FSDP_PREFIX}", prefix)
+    if not _has_fsdp_params(fsdp_state, module):
+        return state_dict
+
+    # state_dict[f"{prefix}{FLAT_PARAM}"] exists and has the same tensor
+    # value as the flat_param but it is a pure Tensor because
+    # nn.Module.state_dict() will detach the parameter. Therefore, we need
+    # to get flat_param to get the metadata.
+    assert _module_handle(fsdp_state, module), "Should have returned early"
+    flat_param = _module_handle(fsdp_state, module).flat_param
+    # Constructs a ShardedTensor from the flat_param "without" padding.
+    # Removing the padding allows users to change the number of ranks
+    # when loading the local_state_dict.
+    full_numel = flat_param._unpadded_unsharded_size.numel()  # type: ignore[attr-defined]
+    shard_offset = flat_param.numel() * fsdp_state.rank
+    valid_data_size = flat_param.numel() - flat_param._shard_numel_padded
+    if valid_data_size > 0:
+        # If FlatParameter is returned, FlatParameter._local_shard cause a
+        # pickling issue (can be torch.save but not torch.load). Since there
+        # is no benefit for state_dict to return the actual FlatParameter class,
+        # a view (which is a tensor) of the FlatParameter will be returned.
+        flat_param = flat_param[:valid_data_size].view(valid_data_size)
+        local_shards = [
+            Shard.from_tensor_and_offsets(flat_param, [shard_offset], fsdp_state.rank)
+        ]
+    else:
+        local_shards = []
+    sharded_tensor = init_from_local_shards(
+        local_shards, full_numel, process_group=fsdp_state.process_group
+    )  # type: ignore[assignment]
+    # TODO: Add DTensor state_dict support for LOCAL_STATE_DICT.
+    if fsdp_state._state_dict_config.offload_to_cpu:
+        sharded_tensor = sharded_tensor.cpu()
+    state_dict[f"{prefix}{FLAT_PARAM}"] = sharded_tensor
+    return state_dict
+
+
+def _local_post_load_state_dict_hook(
+    module: nn.Module, fsdp_state: _FSDPState, *args, **kwargs
+) -> None:
+    pass
+
+
+def _local_pre_load_state_dict_hook(
+    module: nn.Module,
+    fsdp_state: _FSDPState,
+    state_dict: Dict[str, Any],
+    prefix: str,
+) -> None:
+    """
+    This hook finds the local flat_param for this FSDP module from the
+    state_dict. The flat_param should be a ShardedTensor. This hook converts
+    the ShardedTensor to a tensor. No copy happen unless padding is required.
+    """
+    _lazy_init(fsdp_state, module)
+    _replace_by_prefix(state_dict, prefix, f"{prefix}{FSDP_PREFIX}")
+    fqn = f"{prefix}{FSDP_PREFIX}{FLAT_PARAM}"
+    if fqn not in state_dict:
+        assert not _has_fsdp_params(fsdp_state, module), (
+            "No `FlatParameter` in `state_dict` for this FSDP instance "
+            "but it has parameters"
+        )
+        return
+    load_tensor = state_dict[fqn]
+    assert isinstance(
+        load_tensor, ShardedTensor
+    ), "Tensors in local_state_dict should be ShardedTensor."
+
+    # Convert the ShardedTensor to a Tensor.
+    flat_param = _module_handle(fsdp_state, module).flat_param
+    assert flat_param is not None
+    valid_data_size = flat_param.numel() - flat_param._shard_numel_padded
+    shards = load_tensor.local_shards()
+    if valid_data_size > 0:
+        assert len(shards), "load_local_state_dict assume one shard per ShardedTensor."
+        load_tensor = shards[0].tensor
+
+        # Get the metadata of the flat_param to decide whether to pad the loaded
+        # tensor.
+        if flat_param._shard_numel_padded > 0:
+            assert load_tensor.numel() < flat_param.numel(), (
+                f"Local shard size = {flat_param.numel()} and the tensor in "
+                f"the state_dict is {load_tensor.numel()}."
+            )
+            load_tensor = F.pad(load_tensor, [0, flat_param._shard_numel_padded])
+    else:
+        load_tensor = flat_param
+    # TODO: Add DTensor state_dict support for LOCAL_STATE_DICT.
+    state_dict[fqn] = load_tensor
+
+
+def _sharded_pre_state_dict_hook(
+    fsdp_state: _FSDPState,
+    module: nn.Module,
+    *args,
+    **kwargs,
+) -> None:
+    """
+    Hook that runs before model.state_dict() is called. Check
+    ``_full_pre_load_state_dict_hook`` for the detail.
+    """
+    if (
+        _has_fsdp_params(fsdp_state, module)
+        and not _module_handle(fsdp_state, module).uses_sharded_strategy
+    ):
+        raise RuntimeError(
+            "``sharded_state_dict`` can only be used when parameters are flatten "
+            "and sharded."
+        )
+    _common_pre_state_dict_hook(module, fsdp_state)
+    # Setting offload_to_cpu here does not work even if offload_to_cpu is True.
+    # We have to create ShardedTensor first then move it to CPU.
+    _common_unshard_pre_state_dict_hook(
+        module,
+        fsdp_state,
+        offload_to_cpu=False,
+        rank0_only=False,
+    )
+
+
+@no_type_check
+def _sharded_post_state_dict_hook(
+    module: nn.Module,
+    fsdp_state: _FSDPState,
+    state_dict: Dict[str, Any],
+    prefix: str,
+) -> Dict[str, Any]:
+    """
+    The hook replaces the unflattened, unsharded parameter in the state_dict
+    with a unflattened, sharded parameter (a ShardedTensor).
+    """
+
+    def param_hook(state_dict: Dict[str, Any], prefix: str, fqn: str):
+        param = state_dict[fqn]
+        if not fsdp_state._state_dict_config._use_dtensor:
+            sharded_tensor = _ext_chunk_tensor(
+                tensor=param,
+                rank=fsdp_state.rank,
+                world_size=fsdp_state.world_size,
+                num_devices_per_node=fsdp_state._device_handle.device_count(),
+                pg=fsdp_state.process_group,
+                fsdp_extension=fsdp_state._fsdp_extension,
+            )
+        else:
+            sharded_tensor = _ext_chunk_dtensor(
+                tensor=param,
+                rank=fsdp_state.rank,
+                device_mesh=fsdp_state._device_mesh,
+                fsdp_extension=fsdp_state._fsdp_extension,
+            )
+        if fsdp_state._state_dict_config.offload_to_cpu:
+            sharded_tensor = sharded_tensor.cpu()
+        state_dict[fqn] = sharded_tensor
+
+    return _common_unshard_post_state_dict_hook(
+        module, fsdp_state, state_dict, prefix, param_hook
+    )
+
+
+@no_type_check
+def _sharded_post_load_state_dict_hook(
+    module: nn.Module, fsdp_state: _FSDPState, *args, **kwargs
+) -> None:
+    if _has_fsdp_params(fsdp_state, module):
+        with SimpleProfiler.profile("_exit_unshard_params_ctx"):
+            _exit_unshard_params_ctx(module, fsdp_state)
+
+
+@no_type_check
+def _sharded_pre_load_state_dict_hook(
+    module: nn.Module,
+    fsdp_state: _FSDPState,
+    state_dict: Dict[str, Any],
+    prefix: str,
+) -> None:
+    """
+    The hook combines the unflattened, sharded parameters (ShardedTensor) to
+    a new FlatParameter and shards the new FlatParameter to the local chunk.
+    """
+    _lazy_init(fsdp_state, module)
+    if not _is_composable(fsdp_state):
+        _replace_by_prefix(state_dict, prefix, prefix + f"{FSDP_PREFIX}")
+    if not _has_fsdp_params(fsdp_state, module):
+        return
+
+    handle = _module_handle(fsdp_state, module)
+    if not handle.uses_sharded_strategy:
+        raise RuntimeError(
+            "load_sharded_state_dict can only be called when parameters "
+            "are flattened and sharded."
+        )
+    fqn_to_param_ext = dict(
+        zip(handle.flat_param._fqns, handle.flat_param._param_extensions)
+    )
+
+    for fqn, _, _ in _param_name_infos(module, fsdp_state):
+        if not _is_composable(fsdp_state):
+            fqn_from_global_root = f"{prefix}{FSDP_PREFIX}{fqn}"
+        else:
+            fqn_from_global_root = f"{prefix}{fqn}"
+        try:
+            param = state_dict.pop(fqn_from_global_root)
+        except KeyError:
+            logger.warning(
+                f"Did not find param with FQN {fqn_from_global_root}, skipping it. "  # noqa: G004
+                "The weight will not be filled if you expect it to be."
+            )
+            continue  # TODO: Improve unittesting for state_dict finetuning
+            # cases: https://github.com/pytorch/pytorch/issues/109134
+
+        if not fsdp_state._state_dict_config._use_dtensor:
+            # All-gather the param (ShardedTensor)
+            param, shards = _ext_pre_load_state_dict_transform(
+                param, fsdp_state._fsdp_extension
+            )
+
+            assert len(shards) < 2, (
+                "Expects 0 or 1 shard per rank "
+                f"but got {len(shards)} shards on rank {fsdp_state.rank}."
+            )
+            param_numel = param.size().numel()
+            dim_0_size = param.size()[0]
+            chunk_size = (
+                math.ceil(dim_0_size / fsdp_state.world_size)
+                * param_numel
+                // dim_0_size
+            )
+            if len(shards) == 1:
+                local_tensor = shards[0].tensor.flatten()
+                with SimpleProfiler.profile(SimpleProfiler.Type.H2D):
+                    local_tensor = local_tensor.to(fsdp_state.compute_device)
+                num_padding = chunk_size - local_tensor.numel()
+                if num_padding > 0:
+                    local_tensor = F.pad(local_tensor, [0, num_padding])
+            else:
+                local_tensor = torch.zeros(
+                    chunk_size, dtype=param.dtype, device=fsdp_state.compute_device
+                )
+            tensor = torch.empty(
+                chunk_size * fsdp_state.world_size,
+                dtype=local_tensor.dtype,
+                device=fsdp_state.compute_device,
+            )
+            with SimpleProfiler.profile(SimpleProfiler.Type.ALLGATHER):
+                dist.all_gather_into_tensor(
+                    tensor, local_tensor, group=fsdp_state.process_group
+                )
+            tensor = tensor.narrow(0, 0, param_numel).reshape(param.size())
+            state_dict[fqn_from_global_root] = tensor
+        else:
+            if param.device != fsdp_state._device_mesh.device_type:
+                param = param.to(fsdp_state._device_mesh.device_type)
+
+            root_mesh = _mesh_resources.get_root_mesh(fsdp_state._device_mesh)
+            local_tensor = _ext_all_gather_dtensor(
+                param, root_mesh, fsdp_state._fsdp_extension
+            )
+
+            if fqn_to_param_ext.get(fqn) is not None:
+                ext = fqn_to_param_ext[fqn]
+                local_tensor = _ext_post_unflatten_transform(
+                    local_tensor, ext, fsdp_state._fsdp_extension
+                )
+            state_dict[fqn_from_global_root] = local_tensor
+
+    with SimpleProfiler.profile("_enter_unshard_params_ctx"):
+        _enter_unshard_params_ctx(module, fsdp_state, writeback=True)
+
+
+@contextlib.contextmanager
+def _replace_with_full_state_dict_type(fsdp_state: _FSDPState) -> Generator:
+    old_state_dict_config = fsdp_state._state_dict_config
+    old_state_dict_type = fsdp_state._state_dict_type
+    fsdp_state._state_dict_config = FullStateDictConfig()
+    fsdp_state._state_dict_type = StateDictType.FULL_STATE_DICT
+    yield
+    fsdp_state._state_dict_config = old_state_dict_config
+    fsdp_state._state_dict_type = old_state_dict_type
+
+
+@no_type_check
+@torch.no_grad()
+def _post_state_dict_hook(
+    module: nn.Module,
+    state_dict: Dict[str, Any],
+    prefix: str,
+    *args: Any,
+) -> Dict[str, Any]:
+    """
+    _post_state_dict_hook() is called after the state_dict() of this
+    FSDP module is executed. ``fsdp_state._state_dict_type`` is used to decide
+    what postprocessing will be done.
+    """
+    fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module)
+    if fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD:
+        context = _replace_with_full_state_dict_type(fsdp_state)
+        warnings.warn(
+            "When using ``NO_SHARD`` for ``ShardingStrategy``, full_state_dict will"
+            "be returned."
+        )
+    else:
+        context = contextlib.nullcontext()
+
+    with context:
+        _post_state_dict_hook_fn = {
+            StateDictType.FULL_STATE_DICT: _full_post_state_dict_hook,
+            StateDictType.LOCAL_STATE_DICT: _local_post_state_dict_hook,
+            StateDictType.SHARDED_STATE_DICT: _sharded_post_state_dict_hook,
+        }
+        processed_state_dict = _post_state_dict_hook_fn[fsdp_state._state_dict_type](
+            module, fsdp_state, state_dict, prefix
+        )
+
+    if fsdp_state._is_root:
+        logger.info("FSDP finished processing state_dict(), prefix=%s", prefix)
+        for key, tensor in sorted(processed_state_dict.items()):
+            if key.startswith(prefix) and isinstance(tensor, torch.Tensor):
+                local_shape = tensor.shape
+                if isinstance(tensor, ShardedTensor):
+                    local_shape = None
+                    shards = tensor.local_shards()
+                    if shards:
+                        local_shape = shards[0].tensor.shape
+                elif isinstance(tensor, DTensor):
+                    local_shape = tensor.to_local().shape
+                logger.info(
+                    "FQN=%s: type=%s, shape=%s, local_shape=%s, dtype=%s, device=%s",
+                    key,
+                    type(tensor),
+                    tensor.shape,
+                    local_shape,
+                    tensor.dtype,
+                    tensor.device,
+                )
+
+    return processed_state_dict
+
+
+@no_type_check
+@torch.no_grad()
+def _pre_state_dict_hook(
+    module: nn.Module,
+    *args,
+    **kwargs,
+) -> None:
+    """
+    This is called before the core state dict saving logic of ``module``.
+    ``fsdp_state._state_dict_type`` is used to decide what postprocessing will
+    be done.
+    """
+    fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module)
+    if fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD:
+        context = _replace_with_full_state_dict_type(fsdp_state)
+        warnings.warn(
+            "When using ``NO_SHARD`` for ``ShardingStrategy``, full_state_dict will"
+            "be returned."
+        )
+    else:
+        _set_use_dtensor(fsdp_state)
+        context = contextlib.nullcontext()
+
+    with context:
+        _pre_state_dict_hook_fn = {
+            StateDictType.FULL_STATE_DICT: _full_pre_state_dict_hook,
+            StateDictType.LOCAL_STATE_DICT: _local_pre_state_dict_hook,
+            StateDictType.SHARDED_STATE_DICT: _sharded_pre_state_dict_hook,
+        }
+        _pre_state_dict_hook_fn[fsdp_state._state_dict_type](
+            fsdp_state,
+            module,
+            *args,
+            **kwargs,
+        )
+
+
+@no_type_check
+def _set_use_dtensor(fsdp_state: _FSDPState) -> None:
+    # If device_mesh is passed in when initalizing FSDP, we automatically turn the
+    # _use_dtensor flag to be true for ShardedStateDictConfig().
+    if getattr(fsdp_state, "_device_mesh", None):
+        state_dict_type = fsdp_state._state_dict_type
+        if state_dict_type == StateDictType.LOCAL_STATE_DICT:
+            raise RuntimeError(
+                "Found state_dict_type LOCAL_STATE_DICT",
+                "DeviceMesh is not compatible with LOCAL_STATE_DICT.",
+                "Please set state_dict_type to SHARDED_STATE_DICT to get DTensor state_dict.",
+            )
+        else:
+            fsdp_state._state_dict_config._use_dtensor = True
+
+
+@no_type_check
+@torch.no_grad()
+def _pre_load_state_dict_hook(
+    module: nn.Module,
+    state_dict: Dict[str, Any],
+    prefix: str,
+    *args: Any,
+) -> None:
+    """
+    This is called before ``module._load_from_state_dict()``.
+    ``fsdp_state._state_dict_type`` is used to decide what preprocessing will
+    be done.
+    """
+    fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module)
+    if fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD:
+        context = _replace_with_full_state_dict_type(fsdp_state)
+        warnings.warn(
+            "When using ``NO_SHARD`` for ``ShardingStrategy``, full_state_dict will"
+            "be returned."
+        )
+    else:
+        _set_use_dtensor(fsdp_state)
+        context = contextlib.nullcontext()
+
+    _lazy_init(fsdp_state, module)
+    if fsdp_state._is_root:
+        SimpleProfiler.reset()
+
+    with context:
+        _pre_load_state_dict_hook_fn = {
+            StateDictType.FULL_STATE_DICT: _full_pre_load_state_dict_hook,
+            StateDictType.LOCAL_STATE_DICT: _local_pre_load_state_dict_hook,
+            StateDictType.SHARDED_STATE_DICT: _sharded_pre_load_state_dict_hook,
+        }
+        # Code that is common for all state_dict impls
+        if fsdp_state._device_handle.is_available():
+            fsdp_state._device_handle.synchronize()
+        # Dispatch into state_dict specific implementation of pre-hook.
+        _pre_load_state_dict_hook_fn[fsdp_state._state_dict_type](
+            module, fsdp_state, state_dict, prefix
+        )
+
+
+@no_type_check
+@torch.no_grad()
+def _post_load_state_dict_hook(
+    module: nn.Module,
+    incompatible_keys: Tuple[List[str], List[str]],
+    *args: Any,
+) -> None:
+    fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module)
+    if fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD:
+        context = _replace_with_full_state_dict_type(fsdp_state)
+        warnings.warn(
+            "When using ``NO_SHARD`` for ``ShardingStrategy``, full_state_dict will"
+            "be returned."
+        )
+    else:
+        context = contextlib.nullcontext()
+
+    with context:
+        _post_load_state_dict_hook_fn = {
+            StateDictType.FULL_STATE_DICT: _full_post_load_state_dict_hook,
+            StateDictType.LOCAL_STATE_DICT: _local_post_load_state_dict_hook,
+            StateDictType.SHARDED_STATE_DICT: _sharded_post_load_state_dict_hook,
+        }
+        # Code that is common for all state_dict impls
+        # Dispatch into state_dict type specific implementation of post-hook for
+        # loading state_dict.
+        _post_load_state_dict_hook_fn[fsdp_state._state_dict_type](module, fsdp_state)
+
+    # When reporting incompatible keys, trim FSDP prefixes.
+    missing_keys = incompatible_keys[0]
+    unexpected_keys = incompatible_keys[1]
+    for i in range(len(missing_keys)):
+        missing_keys[i] = clean_tensor_name(missing_keys[i])
+
+    for i in range(len(unexpected_keys)):
+        unexpected_keys[i] = clean_tensor_name(unexpected_keys[i])
+
+    if fsdp_state._is_root:
+        SimpleProfiler.dump_and_reset("FSDP model load_state_dict profiling: ")
+
+
+def _register_all_state_dict_hooks(state: _FSDPState):
+    """
+    Registers pre-save, post-save, pre-load, and post-load state dict hooks.
+    """
+    for hook_registration_fn_str, hook, hook_registration_fn_kwargs in (
+        ("register_state_dict_pre_hook", _pre_state_dict_hook, {}),
+        ("_register_state_dict_hook", _post_state_dict_hook, {}),
+        (
+            "_register_load_state_dict_pre_hook",
+            _pre_load_state_dict_hook,
+            {"with_module": True},
+        ),
+        ("register_load_state_dict_post_hook", _post_load_state_dict_hook, {}),
+    ):
+        _register_state_dict_hooks_base(
+            state, hook_registration_fn_str, hook, hook_registration_fn_kwargs
+        )
+
+
+@no_type_check
+def _register_state_dict_hooks_base(
+    state: _FSDPState,
+    hook_registration_fn_name: str,
+    hook: Callable,
+    hook_registration_fn_kwargs: Dict[str, Any],
+) -> None:
+    """Registers ``hook`` using ``hook_registration_fn``."""
+    if not _is_composable(state):
+        getattr(state, hook_registration_fn_name)(hook, **hook_registration_fn_kwargs)
+    else:
+        handle = state._handle
+        if handle:
+            getattr(handle._fully_sharded_module, hook_registration_fn_name)(
+                hook, **hook_registration_fn_kwargs
+            )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_trace_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_trace_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6059e222b3c669d10ecd79793c078989569279d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_trace_utils.py
@@ -0,0 +1,238 @@
+# mypy: allow-untyped-defs
+import functools
+from contextlib import contextmanager
+from dataclasses import dataclass, field
+from typing import Any, Callable, Dict, List, NamedTuple, Optional, Set, Tuple
+
+import torch
+import torch.nn as nn
+
+
+@dataclass
+class TracingConfig:
+    """
+    This represents a symbolic tracing configuration.
+
+    Args:
+        tracer (torch.fx.Tracer): An instance of :class:`torch.fx.Tracer` to
+            use for symbolic tracing. The default value is the native
+            :class:`torch.fx.Tracer` constructed with default arguments.
+            However, the user may want to pass a different value such as the
+            ``HFTracer`` for models in the HuggingFace Transformers_ library.
+            .. _Transformers: https://huggingface.co/docs/transformers/index
+        concrete_args (Optional[Dict[str, Any]]): Concrete arguments that
+            should not be treated as ``torch.fx.Proxy`` when tracing the
+            module ``forward()``. Passing ``concrete_args`` allows partially
+            specializing the forward, e.g. to remove control flow or data
+            structures. This ``concrete_args`` here is the same argument used
+            in :meth:`~torch.fx.Tracer.trace`.
+    """
+
+    tracer: torch.fx.Tracer = field(default_factory=torch.fx.Tracer)
+    concrete_args: Optional[Dict[str, Any]] = None
+
+
+class _ParamUsageInfo(NamedTuple):
+    """
+    This is used for ``_ExecutionInfo.module_to_param_usage_infos`` to record
+    execution information. The ``dict`` maps modules to a list of these
+    ``_ParamUsageInfo`` instances, where each instance represents a group of
+    parameters used together.
+
+    Specifically, for each module key in the ``dict``, each instance of this
+    class represents either:
+    (1) the module and some sublist of its ``named_parameters()`` used
+    together in execution (see ``_patched_create_proxy()``), or
+    (2) a submodule and all of ``submodule.named_parameters()`` (see
+    ``_patched_call_module()``).
+
+    Type (1) corresponds to directly using parameters in ops without calling
+    ``forward()``, and type (2) corresponds to calling ``forward()``. The
+    mapped-to lists in the ``dict`` follow the execution order.
+    """
+
+    module: nn.Module
+    named_params: List[Tuple[str, nn.Parameter]]
+
+
+class _ExecutionInfo:
+    """
+    This represents the execution order information from the forward pass.
+
+    Attributes:
+        curr_module (nn.Module): Current module being traced.
+        module_forward_order (List[nn.Module]): The modules in (pre-)forward
+            order, i.e. the order in which their ``forward()`` methods are
+            called. Each call to a module's ``forward()`` corresponds to one
+            element in the list.
+        module_to_param_usage_infos (Dict[nn.Module, List[_ParamUsageInfo]]):
+            Maps a module to a list of module execution infos. See
+            :class:`_ParamUsageInfo` for details.
+        param_forward_order (List[nn.Parameter]): The parameters in forward
+            execution order, where only a parameter's first participation is
+            included.
+        visited_params (Set[nn.Parameter]): The parameters visited so far
+            during the trace. This is only used during tracing for fast
+            membership check. Invariant: The parameters in
+            ``param_forward_order`` are exactly those in ``visited_params``.
+    """
+
+    def __init__(self, root_module: nn.Module) -> None:
+        self.curr_module: nn.Module = root_module
+        self.module_forward_order: List[nn.Module] = [root_module]
+        self.module_to_param_usage_infos: Dict[nn.Module, List[_ParamUsageInfo]] = {
+            root_module: []
+        }
+        self.param_forward_order: List[nn.Parameter] = []
+        self.visited_params: Set[nn.Parameter] = set()
+
+
+class _ExecOrderTracer:
+    def __init__(self) -> None:
+        self.exec_info: Optional[_ExecutionInfo] = None
+
+    @contextmanager
+    def patch_tracer(self, tracer: torch.fx.Tracer, root_module: nn.Module):
+        self.exec_info = _ExecutionInfo(root_module)
+        orig_call_module = tracer.call_module
+        orig_create_proxy = tracer.create_proxy
+        tracer.call_module = functools.partial(  # type: ignore[method-assign]
+            self._patched_call_module, orig_call_module, self.exec_info
+        )
+        fqn_to_param = dict(root_module.named_parameters())
+        tracer.create_proxy = functools.partial(  # type: ignore[method-assign]
+            self._patched_create_proxy,
+            orig_create_proxy,
+            self.exec_info,
+            fqn_to_param,
+        )
+        try:
+            yield
+        finally:
+            tracer.call_module = orig_call_module  # type: ignore[method-assign]
+            tracer.create_proxy = orig_create_proxy  # type: ignore[method-assign]
+
+    def _patched_call_module(
+        self,
+        call_module: Callable,
+        exec_info: _ExecutionInfo,
+        # Below are the expected arguments to `call_module()`
+        module: nn.Module,
+        forward: Callable,
+        args: Tuple[Any, ...],
+        kwargs: Dict[str, Any],
+    ) -> Any:
+        """
+        Overrides ``call_module`` to save execution information to
+        ``exec_info``. Note that ``call_module`` is called during symbolic
+        tracing for each non-root module.
+
+        Args:
+            call_module (Callable): Original ``call_module`` to override.
+            exec_info (_ExecutionInfo): Used to record execution information.
+            module (nn.Module): Module corresponding to this ``call_module``.
+            forward (Callable): ``forward()`` method of ``module`` to be called
+                for this ``call_module``.
+            args (Tuple[Any, ...]): Positional arguments for ``forward``.
+            kwargs (Dict[str, Any]): Keyword arguments for ``forward``.
+
+        Returns:
+            Same return value as ``call_module``.
+        """
+        exec_info.module_forward_order.append(module)
+        named_params = list(module.named_parameters())
+        curr_module = exec_info.curr_module
+        if named_params:
+            assert (
+                curr_module in exec_info.module_to_param_usage_infos
+            ), "The current module should have already been processed by a patched `call_module`"
+            exec_info.module_to_param_usage_infos[exec_info.curr_module].append(
+                _ParamUsageInfo(module, named_params)
+            )
+        prev_curr_module = curr_module
+        exec_info.curr_module = module
+        exec_info.module_to_param_usage_infos[module] = []
+        output = call_module(module, forward, args, kwargs)
+        exec_info.curr_module = prev_curr_module
+        return output
+
+    def _patched_create_proxy(
+        self,
+        create_proxy: Callable,
+        exec_info: _ExecutionInfo,
+        fqn_to_param: Dict[str, nn.Parameter],
+        # Below are the expected arguments to `create_proxy()`
+        kind: str,
+        target: torch.fx.node.Target,
+        args: Tuple[Any, ...],
+        kwargs: Dict[str, Any],
+        name: Optional[str] = None,
+        type_expr: Optional[Any] = None,
+        proxy_factory_fn: Optional[Callable[[torch.fx.Node], torch.fx.Proxy]] = None,
+    ) -> torch.fx.Proxy:
+        """
+        Overrides ``create_proxy`` to save execution information to
+        ``exec_info``. Note that ``create_proxy`` is called during symbolic
+        tracing for each leaf function/method/module.
+
+        Args:
+            create_proxy (Callable): Original ``create_proxy`` to override.
+            exec_info (_ExecutionInfo): Used to record execution information.
+            fqn_to_param (Dict[str, nn.Parameter]): ``dict`` version of the
+                root module's ``named_parameters()`` with FQN as key and
+                parameter as value.
+            kind (str): Kind of the target method ('call_function',
+                'call_method', 'get_attr', 'call_module', 'placeholder', or
+                'output'). See :class:`torch.fx.Graph` for details. This is
+                passed to ``create_proxy``.
+            target (torch.fx.node.Target): Contains the string name of the
+                function/method/module. This is passed to ``create_proxy``.
+            args (Tuple[Any, ...]): Positional arguments for the function/
+                method/module. This is passed to ``create_proxy``.
+            kwargs (Dict[str, Any]): Keyword arguments for the function/method/
+                module. This is passed to ``create_proxy``
+            name (Optional[str]): An optional string name for the ``Node``
+                created in ``create_proxy``. This is passed to
+                ``create_proxy``.
+            type_expr (Optional[Any]): An optional type annotation representing
+                the Python type that the output of the node has. This is passed
+                to ``create_proxy``.
+            proxy_factory_fn (Callable[[torch.fx.Node], torch.fx.Proxy]):
+                An alternative proxy constructor used in ``create_proxy``. This
+                is passed to ``create_proxy``.
+
+        Returns:
+            torch.fx.Proxy: Created ``Node`` wrapped in a ``Proxy`` object.
+        """
+        proxy = create_proxy(
+            kind, target, args, kwargs, name, type_expr, proxy_factory_fn
+        )
+        curr_module = exec_info.curr_module
+        if kind in ("call_function", "call_method"):
+            if args is not None:
+                named_params: List[Tuple[str, nn.Parameter]] = []
+                for arg in args:
+                    if (
+                        isinstance(arg, torch.fx.Proxy)
+                        and arg.node.target in fqn_to_param
+                    ):
+                        param = fqn_to_param[arg.node.target]  # type: ignore[index]
+                        named_params.append((arg.node.target, param))  # type: ignore[arg-type]
+                        if param not in exec_info.visited_params:
+                            exec_info.visited_params.add(param)
+                            exec_info.param_forward_order.append(param)
+                if named_params:
+                    exec_info.module_to_param_usage_infos[curr_module].append(
+                        _ParamUsageInfo(curr_module, named_params)
+                    )
+        elif kind == "call_module":
+            named_params = list(curr_module.named_parameters())
+            if named_params:
+                exec_info.module_to_param_usage_infos[curr_module].append(
+                    _ParamUsageInfo(curr_module, named_params)
+                )
+            for _, param in named_params:
+                if param not in exec_info.visited_params:
+                    exec_info.visited_params.add(param)
+                    exec_info.param_forward_order.append(param)
+        return proxy
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_traversal_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_traversal_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..68c38d15daf1f97b54fa3366c2b668c934c7a17d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_traversal_utils.py
@@ -0,0 +1,113 @@
+"""
+NOTE: This file must be imported like
+``import torch.distributed.fsdp._traversal_utils`` and not like
+``from torch.distirbuted.fsdp._traversal_utils import ...`` to avoid circular
+imports. For brevity, we may import the file as ``traversal_utils``.
+"""
+
+import collections
+from typing import Deque, List, Set, Tuple
+
+import torch.nn as nn
+from torch.distributed._composable.contract import _get_registry
+from torch.distributed.fsdp._common_utils import _FSDPState, _get_module_fsdp_state
+
+
+"""
+[Note: FSDP State Traversal]
+For the wrapper code path, ``_FSDPState`` is the ``FullyShardedDataParallel``
+module wrapping a fully sharded module, and for the non-wrapper code path,
+``_FSDPState`` is an object that gets embedded on a fully sharded module.
+See [Note: Fully Sharded Module] for the definition.
+
+There are three common traversal idioms: Given a root module,
+- ``_get_fsdp_states()`` returns all ``_FSDPState`` s in the tree.
+- ``get_fsdp_root_states()`` returns all local root ``_FSDPState`` s in the
+tree (i.e. those with ``_is_root == True``).
+- ``_get_fsdp_handles()``returns all ``FlatParamHandle`` s in the tree.
+
+All of these methods must take in the root module (i.e. an ``nn.Module``) and
+not a general ``_FSDPState`` because ``_FSDPState`` does not support a graph
+traversal, whereas ``nn.Module`` has ``nn.Module.modules()`` for traversal.
+"""
+
+
+def _composable(module: nn.Module) -> bool:
+    """
+    Returns if ``module`` can compose with ``fully_shard``.
+    """
+    # TODO: Add any other composable APIs that are mutually exclusive.
+    registry = _get_registry(module)
+    if registry is None:
+        return True
+    return "replicate" not in registry
+
+
+# TODO (awgu): We may be able to remove this function if we retired the
+# `use_orig_params=False` code path since so far we only need the module for
+# `FlatParameter` registration, which is not needed for `use_orig_params=True`.
+def _get_fsdp_states_with_modules(
+    module: nn.Module,
+) -> Tuple[List[_FSDPState], List[nn.Module]]:
+    """
+    Returns a tuple containing:
+    1. A list of the ``_FSDPState`` instances in the module tree rooted at
+    ``module`` without any duplicates and following the ``module.modules()``
+    traversal order (which is assumed to be depth-first).
+    2. A corresponding list of the modules owning the states in the first list.
+
+    For the wrapper code path, both returned lists are the same, each
+    containing all ``FullyShardedDataParallel`` instances. For the composable
+    code path, this returns a list of all composable state instances and a list
+    of the corresponding fully sharded modules. See [Note: Fully Sharded
+    Module].
+
+    NOTE: The traversal does not proceed into any module annotated by an
+    incompatible API (e.g. ``replicate``).
+    """
+    fsdp_states: List[_FSDPState] = []
+    fsdp_modules: List[nn.Module] = []
+    # Track the visited FSDP states since multiple modules may share the same
+    # one and we want to return a de-duplicated list
+    visited_fsdp_states: Set[_FSDPState] = set()
+    # Track the visited modules in case of shared modules, which implies the
+    # module graph is no longer a tree
+    visited_modules: Set[nn.Module] = set()
+
+    # Perform depth-first search from `module` to ensure that we do not
+    # traverse into an incompatible API's subtree (use DFS instead of BFS to
+    # match `.modules()` order)
+    deque: Deque[nn.Module] = collections.deque([module])
+    while deque:
+        submodule = deque.popleft()
+        visited_modules.add(submodule)
+        if not _composable(submodule):
+            continue
+        for child_module in reversed(list(submodule.children())):
+            if child_module not in visited_modules:
+                deque.appendleft(child_module)
+        optional_state = _get_module_fsdp_state(submodule)
+        if optional_state is not None and optional_state not in visited_fsdp_states:
+            visited_fsdp_states.add(optional_state)
+            fsdp_states.append(optional_state)
+            fsdp_modules.append(submodule)
+    return fsdp_states, fsdp_modules
+
+
+def _get_fsdp_states(module: nn.Module) -> List[_FSDPState]:
+    """See :func:`_get_fsdp_states_with_modules`."""
+    fsdp_states, _ = _get_fsdp_states_with_modules(module)
+    return fsdp_states
+
+
+def _get_fsdp_handles(module: nn.Module) -> List:
+    """
+    Returns all ``FlatParamHandle`` s in the module tree rooted at ``module``
+    following the rules in :func:`_get_fsdp_state`.
+    """
+    handles = [
+        fsdp_state._handle
+        for fsdp_state in _get_fsdp_states(module)
+        if fsdp_state._handle is not None
+    ]
+    return handles
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_unshard_param_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_unshard_param_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..4143d2928c8b83a1714813960c668490ac9ca50e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_unshard_param_utils.py
@@ -0,0 +1,336 @@
+# mypy: allow-untyped-defs
+import contextlib
+import warnings
+from typing import cast, Generator
+
+import torch
+import torch.distributed.fsdp._traversal_utils as traversal_utils
+import torch.nn as nn
+from torch.distributed.fsdp._common_utils import (
+    _FSDPState,
+    _get_module_fsdp_state,
+    _has_fsdp_params,
+    _module_handle,
+    HandleTrainingState,
+    TrainingState,
+)
+from torch.distributed.fsdp._runtime_utils import (
+    _lazy_init,
+    _reset_flat_param_grad_info_if_needed,
+    _reshard,
+    _reshard_grads,
+    _unshard,
+    _unshard_grads,
+)
+from torch.distributed.utils import _p_assert
+
+from ._flat_param import FlatParamHandle
+
+
+FLAT_PARAM = "_flat_param"
+
+
+@torch.no_grad()
+def _writeback_to_local_shard(
+    handle: FlatParamHandle,
+    writeback_grad: bool,
+):
+    """
+    For the handle, writes back the this rank's shard of the unsharded
+    flattened parameter to the sharded flattened parameter. If
+    ``writeback_grad=True``, then writes back to the sharded gradient as
+    well.
+
+    Precondition: The handle's ``FlatParameter`` 's data points to the
+    padded unsharded flattened parameter.
+    """
+
+    def _get_shard(flat_param_or_grad: torch.Tensor) -> torch.Tensor:
+        if handle.uses_sharded_strategy:
+            # For sharded strategies, get the *unpadded* shard instead of
+            # the *padded* shard to persist user changes to the padding
+            # (though FSDP does not explicitly support this)
+            shard, _ = FlatParamHandle._get_unpadded_shard(
+                flat_param_or_grad,
+                handle.rank,
+                handle.world_size,
+            )
+            return shard
+        # For `NO_SHARD`, the `flat_param` or its gradient may be modified,
+        # so we write it back directly
+        return flat_param_or_grad
+
+    param_shard = _get_shard(handle.flat_param)
+    handle.flat_param._local_shard[: param_shard.numel()].copy_(param_shard)  # type: ignore[attr-defined]
+    if writeback_grad:
+        existing_grad = handle.sharded_grad
+        if existing_grad is not None:
+            assert handle.flat_param.grad is not None
+            grad_shard = _get_shard(handle.flat_param.grad)
+            existing_grad[: grad_shard.numel()].copy_(grad_shard)
+
+
+def _deregister_flat_param(state: _FSDPState, module: nn.Module) -> None:
+    """
+    De-registers the flattened parameter from the wrapped module, hiding it
+    from ``nn.Module`` methods.
+
+    We do not use ``del`` because we want ``FLAT_PARAM`` to always be an
+    attribute but dynamically change whether it is visible to ``nn.Module``
+    methods.
+    """
+    if _has_fsdp_params(state, module):
+        # TODO: figure out the case for the composable APIs.
+        cast(nn.Module, module.module)._parameters.pop(FLAT_PARAM, None)
+
+
+def _register_flat_param(state: _FSDPState, module: nn.Module) -> None:
+    """
+    Registers the flattened parameter to the wrapped module, making it
+    visible to ``nn.Module`` methods.
+
+    We do not use :meth:`nn.Module.register_parameter` because we want
+    ``FLAT_PARAM`` to always be an attribute but dynamically change whether
+    it is visible to ``nn.Module`` methods.
+    """
+    handle = _module_handle(state, module)
+    if _has_fsdp_params(state, module):
+        # TODO: figure out the case for the composable APIs.
+        cast(nn.Module, module.module)._parameters[FLAT_PARAM] = handle.flat_param
+
+
+@contextlib.contextmanager
+def _unflatten_as_params(state: _FSDPState, module: nn.Module) -> Generator:
+    """
+    Assumes that the flattened parameter is unsharded. When in the context,
+    de-registers the flattened parameter and unflattens the original
+    parameters as ``nn.Parameter`` views into the flattened parameter.
+    After the context, re-registers the flattened parameter and restores
+    the original parameters as ``Tensor`` views into the flattened
+    parameter.
+    """
+    handle = _module_handle(state, module)
+    if not handle:
+        yield
+    else:
+        _deregister_flat_param(state, module)
+        try:
+            with handle.unflatten_as_params():
+                yield
+        finally:
+            if not handle._use_orig_params:
+                _register_flat_param(state, module)
+
+
+def _validate_unshard_params_args(
+    state: _FSDPState,
+    writeback: bool,
+    rank0_only: bool,
+    offload_to_cpu: bool,
+    with_grads: bool,
+) -> None:
+    if with_grads and (offload_to_cpu or not state._use_orig_params):
+        raise NotImplementedError(
+            f"with_grads={with_grads}, "
+            f"use_orig_params={state._use_orig_params}, "
+            f"offload_to_cpu={offload_to_cpu} "
+            f"is not supported yet"
+        )
+    if offload_to_cpu and state._handle and (not state._handle.uses_sharded_strategy):
+        raise NotImplementedError(
+            "offload_to_cpu=True and NO_SHARD is not supported yet"
+        )
+    if writeback and rank0_only:
+        # TODO: Rank 0 can broadcast the `FlatParameter` to allow all ranks to
+        # persist the changes.
+        raise NotImplementedError(
+            "writeback=True and rank0_only=True is not supported yet"
+        )
+    if offload_to_cpu and not rank0_only:
+        warnings.warn(
+            "offload_to_cpu=True and rank0_only=False may result in the"
+            "unsharded parameters being redundantly copied to CPU memory for "
+            "GPUs sharing the same CPU memory, which risks CPU OOM. We "
+            "recommend using offload_to_cpu=True with rank0_only=True."
+        )
+
+
+@contextlib.contextmanager
+def _unshard_fsdp_state_params(
+    module: nn.Module,
+    state: _FSDPState,
+    writeback: bool,
+    rank0_only: bool,
+    offload_to_cpu: bool,
+    with_grads: bool,
+):
+    """
+    This unshards the parameters for a single FSDP state ``state`` that
+    corresponds to ``module``.
+    """
+    _validate_unshard_params_args(
+        state, writeback, rank0_only, offload_to_cpu, with_grads
+    )
+    state._device_handle.synchronize()
+    # If handles are shared by other module(s), the handle may be already unsharded.
+    maybe_handle = _module_handle(state, module)
+    handle = None
+    if (
+        maybe_handle
+        and maybe_handle._training_state != HandleTrainingState.SUMMON_FULL_PARAMS
+    ):
+        handle = maybe_handle
+    if not handle:
+        yield
+        return
+
+    assert (
+        handle._training_state == HandleTrainingState.IDLE
+    ), f"Expects the handle training to be IDLE but got {handle._training_state}"
+
+    handle._training_state = HandleTrainingState.SUMMON_FULL_PARAMS
+
+    _reset_flat_param_grad_info_if_needed(handle)
+    free_unsharded_flat_param = handle.needs_unshard()
+    # No need to call `wait_stream()` since we unshard in the computation
+    # stream directly
+    computation_stream = state._device_handle.current_stream()
+    _unshard(state, handle, computation_stream, computation_stream)
+    if with_grads:
+        _unshard_grads(handle)
+
+    if rank0_only and state.rank != 0:
+        # Free the unsharded flattened parameter early
+        _reshard(state, handle, free_unsharded_flat_param)
+        if with_grads:
+            _reshard_grads(handle)
+        try:
+            yield
+        finally:
+            handle._training_state = HandleTrainingState.IDLE
+    else:
+        # Unflatten the unsharded flattened parameters
+        with contextlib.ExitStack() as stack:
+            # Invariant: rank == 0 or !rank0_only
+            if offload_to_cpu and handle.uses_sharded_strategy:
+                stack.enter_context(handle.to_cpu())
+                # NOTE: Since PyTorch enforces that a parameter and its
+                # gradients need to match metadata (e.g. device), we must
+                # move gradients to CPU *after* we move parameters.
+            # NOTE: This assumes 1 `FlatParameter`
+            if not state._use_orig_params:
+                stack.enter_context(_unflatten_as_params(state, module))
+            try:
+                yield
+            finally:
+                stack.close()
+                if writeback:
+                    _writeback_to_local_shard(handle, with_grads)
+                _reshard(state, handle, free_unsharded_flat_param)
+                if with_grads:
+                    _reshard_grads(handle)
+                handle._training_state = HandleTrainingState.IDLE
+
+
+@contextlib.contextmanager
+def _unshard_params_for_summon(
+    module: nn.Module,
+    state: _FSDPState,
+    writeback: bool,
+    rank0_only: bool,
+    offload_to_cpu: bool,
+    with_grads: bool,
+):
+    _validate_unshard_params_args(
+        state, writeback, rank0_only, offload_to_cpu, with_grads
+    )
+    _lazy_init(state, module)
+    if state.training_state == TrainingState.FORWARD_BACKWARD:
+        raise AssertionError(
+            "Cannot manually unshard parameters during forward/backward"
+        )
+    elif state.training_state == TrainingState.SUMMON_FULL_PARAMS:
+        raise AssertionError(
+            "Cannot manually unshard parameters when already unsharding parameters"
+        )
+    with _unshard_fsdp_state_params(
+        module=module,
+        state=state,
+        writeback=writeback,
+        rank0_only=rank0_only,
+        offload_to_cpu=offload_to_cpu,
+        with_grads=with_grads,
+    ):
+        try:
+            state.training_state = TrainingState.SUMMON_FULL_PARAMS
+            yield
+        finally:
+            state.training_state = TrainingState.IDLE
+
+
+@contextlib.contextmanager
+def _unshard_params(
+    module: nn.Module,
+    recurse: bool,
+    writeback: bool,
+    rank0_only: bool,
+    offload_to_cpu: bool,
+    with_grads: bool,
+):
+    """
+    This unshards FSDP-managed parameters for all modules with FSDP applied in
+    the module tree rooted at ``module``.
+    """
+    if not recurse:
+        optional_state = _get_module_fsdp_state(module)
+        if optional_state is None:
+            with contextlib.nullcontext():
+                yield
+            return
+        states_and_modules = ([optional_state], [module])
+    else:
+        states_and_modules = traversal_utils._get_fsdp_states_with_modules(module)
+    with contextlib.ExitStack() as stack:
+        for state, module in zip(*states_and_modules):
+            stack.enter_context(
+                _unshard_params_for_summon(
+                    module=module,
+                    state=state,
+                    writeback=writeback,
+                    rank0_only=rank0_only,
+                    offload_to_cpu=offload_to_cpu,
+                    with_grads=with_grads,
+                )
+            )
+        yield
+
+
+def _deregister_orig_params(state: _FSDPState, module: nn.Module) -> None:
+    """
+    Deregisters the original parameters; registers the ``FlatParameter``.
+    """
+    handle = _module_handle(state, module)
+    if not handle:
+        return
+    _p_assert(
+        handle._use_orig_params,
+        f"Inconsistent `_use_orig_params` -- FSDP: {state._use_orig_params} "
+        f"handle: {handle._use_orig_params}",
+    )
+    handle._deregister_orig_params()
+    _register_flat_param(state, module)
+
+
+def _register_orig_params(state: _FSDPState, module: nn.Module) -> None:
+    """
+    Deregisters the ``FlatParameter``; registers the original parameters.
+    """
+    handle = _module_handle(state, module)
+    if not handle:
+        return
+    _deregister_flat_param(state, module)
+    if handle.is_sharded(handle.flat_param):
+        handle._use_sharded_views()
+        handle._use_sharded_grad_views()
+    else:
+        handle._use_unsharded_views(as_params=True)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_wrap_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_wrap_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..895bcbd8e967b467b7aeab48db14094457eef2bb
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/_wrap_utils.py
@@ -0,0 +1,262 @@
+# mypy: allow-untyped-defs
+import collections
+import functools
+import inspect
+import warnings
+from functools import partial
+from typing import Any, Callable, Dict, List, Set, Tuple, Type, Union
+
+import torch.nn as nn
+from torch.distributed.fsdp._common_utils import (
+    _get_module_fsdp_state,
+    _override_module_mixed_precision,
+)
+from torch.distributed.fsdp.wrap import (
+    _construct_wrap_fn,
+    _or_policy,
+    _Policy,
+    _post_order_apply,
+    _recursive_wrap,
+    _run_mixed_precision_override_policy,
+    _wrap_module_cls_individually,
+)
+
+
+def _auto_wrap(
+    root_module: nn.Module,
+    policy: Union[Callable, _Policy],
+    ignored_modules: Set[nn.Module],
+    ignored_params: Set[nn.Parameter],
+    root_kwargs: Dict[str, Any],
+    fsdp_fn: Callable,  # e.g. `FullyShardedDataParallel` or `fully_shard`
+):
+    """
+    Auto wraps modules in ``root_module`` 's tree according to ``policy``
+    following a post-order traversal.
+
+    Precondition: ``root_kwargs`` should contain all arguments except
+    ``module``. This function accepts the kwargs dict directly since it gets
+    forwarded into the post-order traversal function.
+    """
+    mixed_precision = root_kwargs["mixed_precision"]
+    is_wrapper = inspect.isclass(fsdp_fn)
+    # TODO: We may relax this no-nested-wrapping constraint to support manual
+    # wrapping followed by auto wrapping.
+    _check_nested_wrapping(root_module)
+
+    if isinstance(policy, _Policy):
+        root_kwargs["auto_wrap_policy" if is_wrapper else "policy"] = None
+        target_module_to_kwargs = policy._run_policy(
+            root_module, ignored_modules, root_kwargs
+        )
+        if mixed_precision is not None:
+            target_module_to_kwargs = _run_mixed_precision_override_policy(
+                root_module,
+                mixed_precision._module_classes_to_ignore,
+                ignored_modules,
+                root_kwargs,
+                target_module_to_kwargs,
+            )
+            overridden_module_classes = _override_module_mixed_precision(
+                root_module, mixed_precision._module_classes_to_ignore
+            )
+            _warn_on_overridden_mixed_precision(overridden_module_classes)
+        use_orig_params = root_kwargs.get("use_orig_params", False)
+        _validate_frozen_params(
+            root_module,
+            set(target_module_to_kwargs.keys()),
+            ignored_params,
+            use_orig_params,
+        )
+        wrap_fn = _construct_wrap_fn(root_module, target_module_to_kwargs, fsdp_fn)
+        _post_order_apply(root_module, wrap_fn)
+        return
+
+    recursive_wrap_kwargs = {
+        "module": root_module,
+        "auto_wrap_policy": policy,
+        "wrapper_cls": fsdp_fn,
+        "ignored_modules": ignored_modules,
+        "ignored_params": ignored_params,
+        "only_wrap_children": True,
+    }
+    if mixed_precision is not None:
+        # Wrap modules of the ignored types separately and register forward
+        # hooks to cast to fp32 and back to the original dtype, respectively
+        overridden_module_classes = _override_module_mixed_precision(
+            root_module, mixed_precision._module_classes_to_ignore
+        )
+        policy = functools.partial(
+            _or_policy,
+            policies=[
+                policy,
+                partial(
+                    _wrap_module_cls_individually,
+                    module_classes=mixed_precision._module_classes_to_ignore,
+                ),
+            ],
+        )
+        recursive_wrap_kwargs["auto_wrap_policy"] = policy
+        _warn_on_overridden_mixed_precision(overridden_module_classes)
+    _recursive_wrap(**recursive_wrap_kwargs, **root_kwargs)  # type: ignore[arg-type]
+
+
+def _check_nested_wrapping(root_module: nn.Module):
+    for module_name, module in root_module.named_modules():
+        if _get_module_fsdp_state(module) is not None:
+            raise ValueError(
+                "FSDP auto wrapping requires modules to not already have "
+                f"FSDP applied but found {module_name} in\n{root_module}"
+            )
+
+
+def _warn_on_overridden_mixed_precision(
+    overridden_module_classes: Set[Type[nn.Module]],
+):
+    if len(overridden_module_classes) == 0:
+        return
+    warnings.warn(
+        "Both mixed precision and an auto_wrap_policy were specified to FSDP, "
+        f"where the wrapped module has submodules of type:\n{overridden_module_classes}\n"
+        "These modules will be wrapped as separate FSDP instacnes with mixed "
+        "precision disabled."
+    )
+
+
+def _validate_frozen_params(
+    root_module: nn.Module,
+    modules_to_wrap: Set[nn.Module],
+    ignored_params: Set[nn.Parameter],
+    use_orig_params: bool,
+):
+    """
+    This checks that, given ``modules_to_wrap``, each module would manage
+    parameters that are uniformly frozen or non-frozen. This uniformity
+    requirement is strict for ``use_orig_params=False`` (hard error) and highly
+    recommended for ``use_orig_params=True`` (user warning).
+    """
+    post_order_named_modules = _get_post_order_named_modules(root_module)
+    visited_modules: Set[nn.Module] = set()
+    for module_name, module in post_order_named_modules:
+        if module in modules_to_wrap:
+            param_to_fqn = _get_managed_param_to_fqn(
+                module, ignored_params, visited_modules, module_name
+            )
+            frozen_param_fqns: List[str] = []
+            frozen_param_numel = 0
+            nonfrozen_param_fqns: List[str] = []
+            nonfrozen_param_numel = 0
+            for param, fqn in param_to_fqn.items():
+                if param.requires_grad:
+                    nonfrozen_param_fqns.append(fqn)
+                    nonfrozen_param_numel += param.numel()
+                else:
+                    frozen_param_fqns.append(fqn)
+                    frozen_param_numel += param.numel()
+            if len(frozen_param_fqns) > 0 and len(nonfrozen_param_fqns) > 0:
+                msg = f"{module_name} has both parameters with requires_grad=True and False."
+                if use_orig_params:
+                    total_param_numel = frozen_param_numel + nonfrozen_param_numel
+                    msg += (
+                        " We do not recommend wrapping such modules since "
+                        "the gradient memory usage will be higher than expected "
+                        f"({total_param_numel} numel instead of {nonfrozen_param_numel} numel "
+                        "before sharding via reduce-scatter). "
+                    )
+                else:
+                    msg += " FSDP does not support wrapping such modules when use_orig_params=False. "
+                msg += "If possible, wrap the frozen parameters with FSDP separately.\n"
+                msg += (
+                    f"The following parameters have requires_grad=True:\n{nonfrozen_param_fqns}\n"
+                    f"The following parameters have requires_grad=False:\n{frozen_param_fqns}"
+                )
+                if use_orig_params:
+                    warnings.warn(msg)
+                else:
+                    raise ValueError(msg)
+
+
+def _get_post_order_named_modules(
+    root_module: nn.Module,
+) -> List[Tuple[str, nn.Module]]:
+    """
+    This returns the named modules following a post-order traversal, which is a
+    valid reverse topological sort. We achieve this using the reverse of a
+    stack-based DFS order instead of reversing ``root_module.named_modules()``
+    since the former gives the modules in registration order at each level in
+    the module tree (as opposed to the reverse), which allows us to error/warn
+    on the first registered module that violates the condition.
+
+    For example, consider the following module structure:
+        M(
+          S1(),
+          S2(
+            SS1(),
+            SS2(),
+          ),
+          S3(),
+        )
+    The reverse DFS order is [S1, SS1, SS2, S2, S3, M], while the reverse
+    ``named_modules()`` order is [S3, SS2, SS1, S2, S1, M].
+    """
+    visited_modules = {root_module}
+    stack = [("", root_module)]
+    # Append and reverse at the end for linear-time algorithm
+    reverse_post_order_named_modules: List[Tuple[str, nn.Module]] = []
+    while stack:
+        module_name, module = stack.pop()
+        reverse_post_order_named_modules.append((module_name, module))
+        for child_module_name, child_module in module.named_children():
+            if child_module is None:  # only for overrides of `named_children()`
+                continue
+            if child_module not in visited_modules:
+                visited_modules.add(child_module)
+                if module_name != "":
+                    child_module_name = module_name + "." + child_module_name
+                stack.append((child_module_name, child_module))
+    post_order_named_modules = list(reversed(reverse_post_order_named_modules))
+    return post_order_named_modules
+
+
+def _get_managed_param_to_fqn(
+    module_to_wrap: nn.Module,
+    ignored_params: Set[nn.Parameter],
+    visited_modules: Set[nn.Module],
+    root_prefix: str,
+) -> Dict[nn.Parameter, str]:
+    """
+    This returns a dict that maps managed parameter to its FQN for the given
+    ``module_to_wrap``. The dict's keys are exactly the parameters that would
+    be managed by the module, where this is achieved by calling this function
+    on the modules to wrap in reverse topological order, destructively updating
+    ``visited_modules``, and not traversing into those modules. The FQNs are
+    prefixed from the root (via ``root_prefix``) to be more informative.
+
+    NOTE: This function is meant to be called pre-wrapping and iteratively in
+    reverse topological order to cover the full module tree. This differs from
+    the ``_get_param_to_fqn()`` function meant to be called post-wrapping and
+    on the full module tree in one shot. Given those differences, we do not try
+    to unify the two.
+    """
+    param_to_fqn: Dict[nn.Parameter, str] = {}
+    # Run BFS (or any tree traversal works)
+    queue = collections.deque([(module_to_wrap, root_prefix)])
+    visited_modules.add(module_to_wrap)
+    while queue:
+        module, prefix = queue.popleft()
+        for param_name, param in module.named_parameters(recurse=False):
+            if param not in ignored_params:
+                fqn = param_name if prefix == "" else prefix + "." + param_name
+                param_to_fqn[param] = fqn
+        for child_module_name, child_module in module.named_children():
+            if child_module is None:  # only for overrides of `named_children()`
+                continue
+            if child_module not in visited_modules:
+                visited_modules.add(child_module)
+                child_prefix = (
+                    child_module_name
+                    if prefix == ""
+                    else prefix + "." + child_module_name
+                )
+                queue.append((child_module, child_prefix))
+    return param_to_fqn
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/api.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..f2e4bdb7ea02311ddb6df89c40c11ff7b6ef0465
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/api.py
@@ -0,0 +1,410 @@
+"""
+This file includes public APIs for FSDP such as the classes used for the
+constructor arguments.
+"""
+
+from dataclasses import dataclass
+from enum import auto, Enum
+from typing import Optional, Sequence, Type
+
+import torch
+from torch.nn.modules.batchnorm import _BatchNorm
+
+
+__all__ = [
+    "ShardingStrategy",
+    "BackwardPrefetch",
+    "MixedPrecision",
+    "CPUOffload",
+    "StateDictType",
+    "StateDictConfig",
+    "FullStateDictConfig",
+    "LocalStateDictConfig",
+    "ShardedStateDictConfig",
+    "OptimStateDictConfig",
+    "FullOptimStateDictConfig",
+    "LocalOptimStateDictConfig",
+    "ShardedOptimStateDictConfig",
+    "StateDictSettings",
+]
+
+
+class ShardingStrategy(Enum):
+    """
+    This specifies the sharding strategy to be used for distributed training by
+    :class:`FullyShardedDataParallel`.
+
+    - ``FULL_SHARD``: Parameters, gradients, and optimizer states are sharded.
+      For the parameters, this strategy unshards (via all-gather) before the
+      forward, reshards after the forward, unshards before the backward
+      computation, and reshards after the backward computation. For gradients,
+      it synchronizes and shards them (via reduce-scatter) after the backward
+      computation. The sharded optimizer states are updated locally per rank.
+    - ``SHARD_GRAD_OP``: Gradients and optimizer states are sharded during
+      computation, and additionally, parameters are sharded outside
+      computation. For the parameters, this strategy unshards before the
+      forward, does not reshard them after the forward, and only reshards them
+      after the backward computation. The sharded optimizer states are updated
+      locally per rank. Inside ``no_sync()``, the parameters are not resharded
+      after the backward computation.
+    - ``NO_SHARD``: Parameters, gradients, and optimizer states are not sharded
+      but instead replicated across ranks similar to PyTorch's
+      :class:`DistributedDataParallel` API. For gradients, this strategy
+      synchronizes them (via all-reduce) after the backward computation. The
+      unsharded optimizer states are updated locally per rank.
+    - ``HYBRID_SHARD``: Apply ``FULL_SHARD`` within a node, and replicate parameters across
+      nodes. This results in reduced communication volume as expensive all-gathers and
+      reduce-scatters are only done within a node, which can be more performant for medium
+      -sized models.
+    - ``_HYBRID_SHARD_ZERO2``: Apply ``SHARD_GRAD_OP`` within a node, and replicate parameters across
+      nodes. This is like ``HYBRID_SHARD``, except this may provide even higher throughput
+      since the unsharded parameters are not freed after the forward pass, saving the
+      all-gathers in the pre-backward.
+    """
+
+    FULL_SHARD = auto()
+    SHARD_GRAD_OP = auto()
+    NO_SHARD = auto()
+    HYBRID_SHARD = auto()
+    _HYBRID_SHARD_ZERO2 = auto()
+
+
+class BackwardPrefetch(Enum):
+    """
+    This configures explicit backward prefetching, which improves throughput by
+    enabling communication and computation overlap in the backward pass at the
+    cost of slightly increased memory usage.
+
+    - ``BACKWARD_PRE``: This enables the most overlap but increases memory
+      usage the most. This prefetches the next set of parameters *before* the
+      current set of parameters' gradient computation. This overlaps the *next
+      all-gather* and the *current gradient computation*, and at the peak, it
+      holds the current set of parameters, next set of parameters, and current
+      set of gradients in memory.
+    - ``BACKWARD_POST``: This enables less overlap but requires less memory
+      usage. This prefetches the next set of parameters *after* the current
+      set of parameters' gradient computation. This overlaps the *current
+      reduce-scatter* and the *next gradient computation*, and it frees the
+      current set of parameters before allocating memory for the next set of
+      parameters, only holding the next set of parameters and current set of
+      gradients in memory at the peak.
+    - FSDP's ``backward_prefetch`` argument accepts ``None``, which disables
+      the backward prefetching altogether. This has no overlap and does not
+      increase memory usage. In general, we do not recommend this setting since
+      it may degrade throughput significantly.
+
+    For more technical context: For a single process group using NCCL backend,
+    any collectives, even if issued from different streams, contend for the
+    same per-device NCCL stream, which implies that the relative order in which
+    the collectives are issued matters for overlapping. The two backward
+    prefetching values correspond to different issue orders.
+    """
+
+    # NOTE: For both modes, the ordering that defines "current" and "next" is
+    # not always exact in the current implementation. A mistargeted prefetch
+    # simply means that the parameter memory is allocated earlier than needed,
+    # possibly increasing peak memory usage, but does not affect correctness.
+    BACKWARD_PRE = auto()
+    BACKWARD_POST = auto()
+
+
+@dataclass
+class MixedPrecision:
+    """
+    This configures FSDP-native mixed precision training.
+
+    Attributes:
+        param_dtype (Optional[torch.dtype]): This specifies the dtype for model
+            parameters during forward and backward and thus the dtype for
+            forward and backward computation. Outside forward and backward, the
+            *sharded* parameters are kept in full precision (e.g. for the
+            optimizer step), and for model checkpointing, the parameters are
+            always saved in full precision. (Default: ``None``)
+        reduce_dtype (Optional[torch.dtype]): This specifies the dtype for
+            gradient reduction (i.e. reduce-scatter or all-reduce). If this is
+            ``None`` but ``param_dtype`` is not ``None``, then this takes on
+            the ``param_dtype`` value, still running gradient reduction in low
+            precision. This is permitted to differ from ``param_dtype``, e.g.
+            to force gradient reduction to run in full precision. (Default:
+            ``None``)
+        buffer_dtype (Optional[torch.dtype]): This specifies the dtype for
+            buffers. FSDP does not shard buffers. Rather, FSDP casts them to
+            ``buffer_dtype`` in the first forward pass and keeps them in that
+            dtype thereafter. For model checkpointing, the buffers are saved
+            in full precision except for ``LOCAL_STATE_DICT``. (Default:
+            ``None``)
+        keep_low_precision_grads (bool): If ``False``, then FSDP upcasts
+            gradients to full precision after the backward pass in preparation
+            for the optimizer step. If ``True``, then FSDP keeps the gradients
+            in the dtype used for gradient reduction, which can save memory if
+            using a custom optimizer that supports running in low precision.
+            (Default: ``False``)
+        cast_forward_inputs (bool): If ``True``, then this FSDP module casts
+            its forward args and kwargs to ``param_dtype``. This is to ensure
+            that parameter and input dtypes match for forward computation, as
+            required by many ops. This may need to be set to ``True`` when only
+            applying mixed precision to some but not all FSDP modules, in which
+            case a mixed-precision FSDP submodule needs to recast its inputs.
+            (Default: ``False``)
+        cast_root_forward_inputs (bool): If ``True``, then the root FSDP module
+            casts its forward args and kwargs to ``param_dtype``, overriding
+            the value of ``cast_forward_inputs``. For non-root FSDP modules,
+            this does not do anything. (Default: ``True``)
+        _module_classes_to_ignore: (Sequence[Type[nn.Module]]): This specifies
+            module classes to ignore for mixed precision when using an
+            ``auto_wrap_policy``: Modules of these classes will have FSDP
+            applied to them separately with mixed precision disabled (meaning
+            that the final FSDP construction would deviate from the specified
+            policy). If ``auto_wrap_policy`` is not specified, then this does
+            not do anything. This API is experimental and subject to change.
+            (Default: ``(_BatchNorm,)``)
+
+    .. note:: This API is experimental and subject to change.
+
+    .. note:: Only floating point tensors are cast to their specified dtypes.
+
+    .. note:: In ``summon_full_params``, parameters are forced to full
+        precision, but buffers are not.
+
+    .. note:: Layer norm and batch norm accumulate in ``float32`` even when
+        their inputs are in a low precision like ``float16`` or ``bfloat16``.
+        Disabling FSDP's mixed precision for those norm modules only means that
+        the affine parameters are kept in ``float32``. However, this incurs
+        separate all-gathers and reduce-scatters for those norm modules, which
+        may be inefficient, so if the workload permits, the user should prefer
+        to still apply mixed precision to those modules.
+
+    .. note:: By default, if the user passes a model with any ``_BatchNorm``
+        modules and specifies an ``auto_wrap_policy``, then the batch norm
+        modules will have FSDP applied to them separately with mixed precision
+        disabled. See the ``_module_classes_to_ignore`` argument.
+
+    .. note:: ``MixedPrecision`` has ``cast_root_forward_inputs=True`` and
+        ``cast_forward_inputs=False`` by default. For the root FSDP instance,
+        its ``cast_root_forward_inputs`` takes precedence over its
+        ``cast_forward_inputs``. For non-root FSDP instances, their
+        ``cast_root_forward_inputs`` values are ignored. The default setting is
+        sufficient for the typical case where each FSDP instance has the same
+        ``MixedPrecision`` configuration and only needs to cast inputs to the
+        ``param_dtype`` at the beginning of the model's forward pass.
+
+    .. note:: For nested FSDP instances with different ``MixedPrecision``
+        configurations, we recommend setting individual ``cast_forward_inputs``
+        values to configure casting inputs or not before each instance's
+        forward. In such a case, since the casts happen before each FSDP
+        instance's forward, a parent FSDP instance should have its non-FSDP
+        submodules run before its FSDP submodules to avoid the activation dtype
+        being changed due to a different ``MixedPrecision`` configuration.
+
+        Example::
+
+            >>> # xdoctest: +SKIP("undefined variables")
+            >>> model = nn.Sequential(nn.Linear(3, 3), nn.Linear(3, 3))
+            >>> model[1] = FSDP(
+            >>>     model[1],
+            >>>     mixed_precision=MixedPrecision(param_dtype=torch.float16, cast_forward_inputs=True),
+            >>> )
+            >>> model = FSDP(
+            >>>     model,
+            >>>     mixed_precision=MixedPrecision(param_dtype=torch.bfloat16, cast_forward_inputs=True),
+            >>> )
+
+        The above shows a working example. On the other hand, if ``model[1]``
+        were replaced with ``model[0]``, meaning that the submodule using
+        different ``MixedPrecision`` ran its forward first, then ``model[1]``
+        would incorrectly see ``float16`` activations instead of ``bfloat16``
+        ones.
+
+    """
+
+    param_dtype: Optional[torch.dtype] = None
+    reduce_dtype: Optional[torch.dtype] = None
+    buffer_dtype: Optional[torch.dtype] = None
+    keep_low_precision_grads: bool = False
+    cast_forward_inputs: bool = False
+    cast_root_forward_inputs: bool = True
+    _module_classes_to_ignore: Sequence[Type[torch.nn.Module]] = (_BatchNorm,)
+
+
+@dataclass
+class CPUOffload:
+    """
+    This configures CPU offloading.
+
+    Attributes:
+        offload_params (bool): This specifies whether to offload parameters to
+            CPU when not involved in computation. If ``True``, then this
+            offloads gradients to CPU as well, meaning that the optimizer step
+            runs on CPU.
+    """
+
+    offload_params: bool = False
+
+
+class StateDictType(Enum):
+    """
+    This enum indicates that which type of ``state_dict`` the FSDP module is
+    currently processing (returning or loading).
+    The default value is FULL_STATE_DICT to comply the PyTorch convention.
+    ..note::
+        FSDP currently supports three types of ``state_dict``:
+            1. ``state_dict/load_state_dict`: this pair of APIs return and load
+               the non-sharded, unflattened parameters. The semantics is the
+               same as using DDP.
+            2. ``_local_state_dict/_load_local_state_dict``: this pair of APIs return
+               and load local sharded, flattened parameters. The values returned
+               by ``_local_state_dict`` can be directly used by FSDP and is only
+               meaningful to FSDP (because parameters are flattened). Note that
+               these APIs are meant for use via the :func:`state_dict_type`
+               context manager as follows:
+                   >>> # xdoctest: +SKIP("undefined variables")
+                   >>> with fsdp.state_dict_type(StateDictType.LOCAL_STATE_DICT):
+                   ...     state = fsdp.state_dict()  # loads local state dict
+            3. ``_sharded_state_dict/_load_sharded_state_dict``: this pair of APIs
+               return and load sharded, unflattened parameters. The ``state_dict``
+               return by ``sharded_state_dict`` can be used by all other parallel
+               schemes (resharding may be required).
+    """
+
+    FULL_STATE_DICT = auto()
+    LOCAL_STATE_DICT = auto()
+    SHARDED_STATE_DICT = auto()
+
+
+@dataclass
+class StateDictConfig:
+    """
+    ``StateDictConfig`` is the base class for all ``state_dict`` configuration
+    classes. Users should instantiate a child class (e.g.
+    ``FullStateDictConfig``) in order to configure settings for the
+    corresponding ``state_dict`` type supported by FSDP.
+
+    Attributes:
+        offload_to_cpu (bool): If ``True``, then FSDP offloads the state dict
+            values to CPU, and if ``False``, then FSDP keeps them on GPU.
+            (Default: ``False``)
+    """
+
+    offload_to_cpu: bool = False
+
+
+@dataclass
+class FullStateDictConfig(StateDictConfig):
+    """
+    ``FullStateDictConfig`` is a config class meant to be used with
+    ``StateDictType.FULL_STATE_DICT``. We recommend enabling both
+    ``offload_to_cpu=True`` and ``rank0_only=True`` when saving full state
+    dicts to save GPU memory and CPU memory, respectively. This config class
+    is meant to be used via the :func:`state_dict_type` context manager as
+    follows:
+
+        >>> # xdoctest: +SKIP("undefined variables")
+        >>> from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
+        >>> fsdp = FSDP(model, auto_wrap_policy=...)
+        >>> cfg = FullStateDictConfig(offload_to_cpu=True, rank0_only=True)
+        >>> with FSDP.state_dict_type(fsdp, StateDictType.FULL_STATE_DICT, cfg):
+        >>>     state = fsdp.state_dict()
+        >>>     # `state` will be empty on non rank 0 and contain CPU tensors on rank 0.
+        >>> # To reload checkpoint for inference, finetuning, transfer learning, etc:
+        >>> model = model_fn() # Initialize model in preparation for wrapping with FSDP
+        >>> if dist.get_rank() == 0:
+        >>>     # Load checkpoint only on rank 0 to avoid memory redundancy
+        >>>     state_dict = torch.load("my_checkpoint.pt")
+        >>>     model.load_state_dict(state_dict)
+        >>> # All ranks initialize FSDP module as usual. `sync_module_states` argument
+        >>> # communicates loaded checkpoint states from rank 0 to rest of the world.
+        >>> fsdp = FSDP(model, device_id=torch.cuda.current_device(), auto_wrap_policy=..., sync_module_states=True)
+        >>> # After this point, all ranks have FSDP model with loaded checkpoint.
+
+    Attributes:
+        rank0_only (bool): If ``True``, then only rank 0 saves the full state
+            dict, and nonzero ranks save an empty dict. If ``False``, then all
+            ranks save the full state dict. (Default: ``False``)
+    """
+
+    rank0_only: bool = False
+
+
+@dataclass
+class LocalStateDictConfig(StateDictConfig):
+    pass
+
+
+@dataclass
+class ShardedStateDictConfig(StateDictConfig):
+    """
+    ``ShardedStateDictConfig`` is a config class meant to be used with
+    ``StateDictType.SHARDED_STATE_DICT``.
+
+    Attributes:
+        _use_dtensor (bool): If ``True``, then FSDP saves the state dict values
+            as ``DTensor``, and if ``False``, then FSDP saves them as
+            ``ShardedTensor``. (Default: ``False``)
+
+    .. warning:: ``_use_dtensor`` is a private field of :class:`ShardedStateDictConfig`
+      and it is used by FSDP to determine the type of state dict values. Users should not
+      manually modify ``_use_dtensor``.
+    """
+
+    _use_dtensor: bool = False
+
+
+@dataclass
+class OptimStateDictConfig:
+    """
+    ``OptimStateDictConfig`` is the base class for all ``optim_state_dict``
+    configuration classes.  Users should instantiate a child class (e.g.
+    ``FullOptimStateDictConfig``) in order to configure settings for the
+    corresponding ``optim_state_dict`` type supported by FSDP.
+
+    Attributes:
+        offload_to_cpu (bool): If ``True``, then FSDP offloads the state dict's
+            tensor values to CPU, and if ``False``, then FSDP keeps them on the
+            original device (which is GPU unless parameter CPU offloading is
+            enabled). (Default: ``True``)
+    """
+
+    offload_to_cpu: bool = True
+
+
+@dataclass
+class FullOptimStateDictConfig(OptimStateDictConfig):
+    """
+    Attributes:
+        rank0_only (bool): If ``True``, then only rank 0 saves the full state
+            dict, and nonzero ranks save an empty dict. If ``False``, then all
+            ranks save the full state dict. (Default: ``False``)
+    """
+
+    rank0_only: bool = False
+
+
+@dataclass
+class LocalOptimStateDictConfig(OptimStateDictConfig):
+    offload_to_cpu: bool = False
+
+
+@dataclass
+class ShardedOptimStateDictConfig(OptimStateDictConfig):
+    """
+    ``ShardedOptimStateDictConfig`` is a config class meant to be used with
+    ``StateDictType.SHARDED_STATE_DICT``.
+
+    Attributes:
+        _use_dtensor (bool): If ``True``, then FSDP saves the state dict values
+            as ``DTensor``, and if ``False``, then FSDP saves them as
+            ``ShardedTensor``. (Default: ``False``)
+
+    .. warning:: ``_use_dtensor`` is a private field of :class:`ShardedOptimStateDictConfig`
+      and it is used by FSDP to determine the type of state dict values. Users should not
+      manually modify ``_use_dtensor``.
+    """
+
+    _use_dtensor: bool = False
+
+
+@dataclass
+class StateDictSettings:
+    state_dict_type: StateDictType
+    state_dict_config: StateDictConfig
+    optim_state_dict_config: OptimStateDictConfig
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/fully_sharded_data_parallel.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/fully_sharded_data_parallel.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ff9e80ca12e3cfab4ccff455748d693be11a79a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/fully_sharded_data_parallel.py
@@ -0,0 +1,2185 @@
+# mypy: ignore-errors
+
+import contextlib
+import copy
+import functools
+import math
+import traceback
+import warnings
+from contextlib import contextmanager
+from enum import auto, Enum
+from typing import (
+    Any,
+    Callable,
+    Dict,
+    Generator,
+    Iterable,
+    Iterator,
+    List,
+    Optional,
+    Tuple,
+    Union,
+)
+
+import torch
+import torch.distributed as dist
+import torch.distributed.fsdp._traversal_utils as traversal_utils
+import torch.nn as nn
+from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import (
+    _CHECKPOINT_WRAPPED_MODULE,
+    ActivationWrapper,
+)
+from torch.distributed.algorithms._comm_hooks import LOW_PRECISION_HOOKS
+from torch.distributed.fsdp._common_utils import (
+    _FSDPState,
+    _get_param_to_fqns,
+    FSDP_PREFIX,
+    FSDP_WRAPPED_MODULE,
+    HandleTrainingState,
+    TrainingState,
+)
+from torch.distributed.fsdp._dynamo_utils import _annotate_modules_for_dynamo
+from torch.distributed.fsdp._init_utils import (
+    _check_orig_params_flattened,
+    _init_buffer_state,
+    _init_core_state,
+    _init_device_handle,
+    _init_extension,
+    _init_ignored_module_states,
+    _init_param_handle_from_module,
+    _init_prefetching_state,
+    _init_process_group_state,
+    _init_runtime_state,
+    _init_state_dict_state,
+    HYBRID_SHARDING_STRATEGIES,
+    ProcessGroupType,
+)
+from torch.distributed.fsdp._runtime_utils import (
+    _get_fsdp_root_states,
+    _is_fsdp_root,
+    _lazy_init,
+    _post_forward,
+    _post_forward_reshard,
+    _pre_forward,
+    _pre_forward_unshard,
+    _root_pre_forward,
+    _unshard,
+    _wait_for_computation_stream,
+)
+from torch.distributed.fsdp._wrap_utils import _auto_wrap
+from torch.distributed.fsdp.api import (
+    BackwardPrefetch,
+    CPUOffload,
+    FullOptimStateDictConfig,
+    FullStateDictConfig,
+    LocalOptimStateDictConfig,
+    LocalStateDictConfig,
+    MixedPrecision,
+    OptimStateDictConfig,
+    ShardedOptimStateDictConfig,
+    ShardedStateDictConfig,
+    ShardingStrategy,
+    StateDictConfig,
+    StateDictSettings,
+    StateDictType,
+)
+from torch.distributed.tensor import DeviceMesh
+from torch.distributed.utils import _p_assert
+
+from ._flat_param import FlatParameter, FlatParamHandle
+from ._optim_utils import (
+    _flatten_optim_state_dict,
+    _get_param_id_to_param_from_optim_input,
+    _get_param_key_to_param,
+    _get_param_to_param_id_from_optim_input,
+    _get_param_to_param_key,
+    _optim_state_dict,
+    _rekey_sharded_optim_state_dict,
+    _set_optim_use_dtensor,
+)
+from ._state_dict_utils import _register_all_state_dict_hooks
+from ._unshard_param_utils import (
+    _deregister_orig_params,
+    _register_flat_param,
+    _register_orig_params,
+    _unshard_params,
+    _unshard_params_for_summon,
+)
+from .wrap import CustomPolicy, ModuleWrapPolicy
+
+
+__all__ = [
+    "FullyShardedDataParallel",
+    "OptimStateKeyType",
+]
+
+
+FLAT_PARAM = "_flat_param"
+
+
+class OptimStateKeyType(Enum):
+    """Represents the type of key in an optimizer state-dict."""
+
+    PARAM_NAME = auto()
+    PARAM_ID = auto()
+
+
+class FullyShardedDataParallel(nn.Module, _FSDPState):
+    """A wrapper for sharding module parameters across data parallel workers.
+
+    This is inspired by `Xu et al.`_ as well as the ZeRO Stage 3 from DeepSpeed_.
+    FullyShardedDataParallel is commonly shortened to FSDP.
+
+    .. _`Xu et al.`: https://arxiv.org/abs/2004.13336
+    .. _DeepSpeed: https://www.deepspeed.ai/
+
+    To understand FSDP internals, refer to the
+    :ref:`fsdp_notes`.
+
+    Example::
+
+        >>> # xdoctest: +SKIP("undefined variables")
+        >>> import torch
+        >>> from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
+        >>> torch.cuda.set_device(device_id)
+        >>> sharded_module = FSDP(my_module)
+        >>> optim = torch.optim.Adam(sharded_module.parameters(), lr=0.0001)
+        >>> x = sharded_module(x, y=3, z=torch.Tensor([1]))
+        >>> loss = x.sum()
+        >>> loss.backward()
+        >>> optim.step()
+
+    Using FSDP involves wrapping your module and then initializing your
+    optimizer after. This is required since FSDP changes the parameter
+    variables.
+
+    When setting up FSDP, you need to consider the destination CUDA
+    device. If the device has an ID (``dev_id``), you have three options:
+
+    * Place the module on that device
+    * Set the device using ``torch.cuda.set_device(dev_id)``
+    * Pass ``dev_id`` into the ``device_id`` constructor argument.
+
+    This ensures that the FSDP instance's compute device is the
+    destination device. For option 1 and 3, the FSDP initialization
+    always occurs on GPU. For option 2, the FSDP initialization
+    happens on module's current device, which may be a CPU.
+
+    If you're using the ``sync_module_states=True`` flag, you need to
+    ensure that the module is on a GPU or use the ``device_id``
+    argument to specify a CUDA device that FSDP will move the module
+    to in the FSDP constructor. This is necessary because
+    ``sync_module_states=True`` requires GPU communication.
+
+    FSDP also takes care of moving input tensors to the forward method
+    to the GPU compute device, so you don't need to manually move them
+    from CPU.
+
+    For ``use_orig_params=True``,
+    ``ShardingStrategy.SHARD_GRAD_OP`` exposes the unsharded
+    parameters, not the sharded parameters after forward, unlike
+    ``ShardingStrategy.FULL_SHARD``. If you want
+    to inspect the gradients, you can use the ``summon_full_params``
+    method with ``with_grads=True``.
+
+    With ``limit_all_gathers=True``, you may see a gap in the FSDP
+    pre-forward where the CPU thread is not issuing any kernels. This is
+    intentional and shows the rate limiter in effect. Synchronizing the CPU
+    thread in that way prevents over-allocating memory for subsequent
+    all-gathers, and it should not actually delay GPU kernel execution.
+
+    FSDP replaces managed modules' parameters with ``torch.Tensor``
+    views during forward and backward computation for autograd-related
+    reasons. If your module's forward relies on saved references to
+    the parameters instead of reacquiring the references each
+    iteration, then it will not see FSDP's newly created views,
+    and autograd will not work correctly.
+
+    Finally, when using ``sharding_strategy=ShardingStrategy.HYBRID_SHARD``
+    with the sharding process group being intra-node and the
+    replication process group being inter-node, setting
+    ``NCCL_CROSS_NIC=1`` can help improve the all-reduce times over
+    the replication process group for some cluster setups.
+
+    **Limitations**
+
+    There are several limitations to be aware of when using FSDP:
+
+    * FSDP currently does not support gradient accumulation outside
+      ``no_sync()`` when using CPU offloading. This is because FSDP
+      uses the newly-reduced gradient instead of accumulating with any
+      existing gradient, which can lead to incorrect results.
+
+    * FSDP does not support running the forward pass of a submodule
+      that is contained in an FSDP instance. This is because the
+      submodule's parameters will be sharded, but the submodule itself
+      is not an FSDP instance, so its forward pass will not all-gather
+      the full parameters appropriately.
+
+    * FSDP does not work with double backwards due to the way it
+      registers backward hooks.
+
+    * FSDP has some constraints when freezing parameters.
+      For ``use_orig_params=False``, each FSDP instance must manage
+      parameters that are all frozen or all non-frozen. For
+      ``use_orig_params=True``, FSDP supports mixing frozen and
+      non-frozen parameters, but it's recommended to avoid doing so to
+      prevent higher than expected gradient memory usage.
+
+    * As of PyTorch 1.12, FSDP offers limited support for shared
+      parameters. If enhanced shared parameter support is needed for
+      your use case, please post in
+      `this issue `__.
+
+    * You should avoid modifying the parameters between forward and
+      backward without using the ``summon_full_params`` context, as
+      the modifications may not persist.
+
+    Args:
+        module (nn.Module):
+            This is the module to be wrapped with FSDP.
+        process_group (Optional[Union[ProcessGroup, Tuple[ProcessGroup, ProcessGroup]]]):
+            This is the process group over which the model is sharded and thus
+            the one used for FSDP's all-gather and reduce-scatter collective
+            communications. If ``None``, then FSDP uses the default process
+            group. For hybrid sharding strategies such as
+            ``ShardingStrategy.HYBRID_SHARD``, users can pass in a tuple of
+            process groups, representing the groups over which to shard and
+            replicate, respectively. If ``None``, then FSDP constructs process
+            groups for the user to shard intra-node and replicate inter-node.
+            (Default: ``None``)
+        sharding_strategy (Optional[ShardingStrategy]):
+            This configures the sharding strategy, which may trade off memory
+            saving and communication overhead. See :class:`ShardingStrategy`
+            for details. (Default: ``FULL_SHARD``)
+        cpu_offload (Optional[CPUOffload]):
+            This configures CPU offloading. If this is set to ``None``, then
+            no CPU offloading happens. See :class:`CPUOffload` for details.
+            (Default: ``None``)
+        auto_wrap_policy (Optional[Union[Callable[[nn.Module, bool, int], bool], ModuleWrapPolicy, CustomPolicy]]):
+            This specifies a policy to apply FSDP to submodules of ``module``,
+            which is needed for communication and computation overlap and thus
+            affects performance. If ``None``, then FSDP only applies to
+            ``module``, and users should manually apply FSDP to parent modules
+            themselves (proceeding bottom-up). For convenience, this accepts
+            ``ModuleWrapPolicy`` directly, which allows users to specify the
+            module classes to wrap (e.g. the transformer block). Otherwise,
+            this should be a callable that takes in three arguments
+            ``module: nn.Module``, ``recurse: bool``, and
+            ``nonwrapped_numel: int`` and should return a ``bool`` specifying
+            whether the passed-in ``module`` should have FSDP applied if
+            ``recurse=False`` or if the traversal should continue into the
+            module's subtree if ``recurse=True``. Users may add additional
+            arguments to the callable. The ``size_based_auto_wrap_policy`` in
+            ``torch.distributed.fsdp.wrap.py`` gives an example callable that
+            applies FSDP to a module if the parameters in its subtree exceed
+            100M numel. We recommend printing the model after applying FSDP
+            and adjusting as needed.
+
+            Example::
+
+                >>> def custom_auto_wrap_policy(
+                >>>     module: nn.Module,
+                >>>     recurse: bool,
+                >>>     nonwrapped_numel: int,
+                >>>     # Additional custom arguments
+                >>>     min_num_params: int = int(1e8),
+                >>> ) -> bool:
+                >>>     return nonwrapped_numel >= min_num_params
+                >>> # Configure a custom `min_num_params`
+                >>> my_auto_wrap_policy = functools.partial(custom_auto_wrap_policy, min_num_params=int(1e5))
+
+        backward_prefetch (Optional[BackwardPrefetch]):
+            This configures explicit backward prefetching of all-gathers. If
+            ``None``, then FSDP does not backward prefetch, and there is no
+            communication and computation overlap in the backward pass. See
+            :class:`BackwardPrefetch` for details. (Default: ``BACKWARD_PRE``)
+        mixed_precision (Optional[MixedPrecision]):
+            This configures native mixed precision for FSDP. If this is set to
+            ``None``, then no mixed precision is used. Otherwise, parameter,
+            buffer, and gradient reduction dtypes can be set. See
+            :class:`MixedPrecision` for details. (Default: ``None``)
+        ignored_modules (Optional[Iterable[torch.nn.Module]]): Modules whose
+            own parameters and child modules' parameters and buffers are
+            ignored by this instance. None of the modules directly in
+            ``ignored_modules`` should be :class:`FullyShardedDataParallel`
+            instances, and any child modules that are already-constructed
+            :class:`FullyShardedDataParallel` instances will not be ignored if
+            they are nested under this instance. This argument may be used to
+            avoid sharding specific parameters at module granularity when using an
+            ``auto_wrap_policy`` or if parameters' sharding is not managed by
+            FSDP. (Default: ``None``)
+        param_init_fn (Optional[Callable[[nn.Module], None]]):
+            A ``Callable[torch.nn.Module] -> None`` that
+            specifies how modules that are currently on the meta device should
+            be initialized onto an actual device. As of v1.12, FSDP detects
+            modules with parameters or buffers on meta device via ``is_meta``
+            and either applies ``param_init_fn`` if specified or calls
+            ``nn.Module.reset_parameters()`` otherwise. For both cases, the
+            implementation should *only* initialize the parameters/buffers of
+            the module, not those of its submodules. This is to avoid
+            re-initialization. In addition, FSDP also supports deferred
+            initialization via torchdistX's (https://github.com/pytorch/torchdistX)
+            ``deferred_init()`` API, where the deferred modules are initialized
+            by calling ``param_init_fn`` if specified or torchdistX's default
+            ``materialize_module()`` otherwise. If ``param_init_fn`` is
+            specified, then it is applied to all meta-device modules, meaning
+            that it should probably case on the module type. FSDP calls the
+            initialization function before parameter flattening and sharding.
+
+            Example::
+
+                >>> # xdoctest: +SKIP("undefined variables")
+                >>> module = MyModule(device="meta")
+                >>> def my_init_fn(module: nn.Module):
+                >>>     # E.g. initialize depending on the module type
+                >>>     ...
+                >>> fsdp_model = FSDP(module, param_init_fn=my_init_fn, auto_wrap_policy=size_based_auto_wrap_policy)
+                >>> print(next(fsdp_model.parameters()).device) # current CUDA device
+                >>> # With torchdistX
+                >>> module = deferred_init.deferred_init(MyModule, device="cuda")
+                >>> # Will initialize via deferred_init.materialize_module().
+                >>> fsdp_model = FSDP(module, auto_wrap_policy=size_based_auto_wrap_policy)
+
+        device_id (Optional[Union[int, torch.device]]): An ``int`` or
+            ``torch.device`` giving the CUDA device on which FSDP
+            initialization takes place, including the module initialization
+            if needed and the parameter sharding. This should be specified to
+            improve initialization speed if ``module`` is on CPU. If the
+            default CUDA device was set (e.g. via ``torch.cuda.set_device``),
+            then the user may pass ``torch.cuda.current_device`` to this.
+            (Default: ``None``)
+        sync_module_states (bool): If ``True``, then each FSDP module will
+            broadcast module parameters and buffers from rank 0 to ensure that
+            they are replicated across ranks (adding communication overhead to
+            this constructor). This can help load ``state_dict`` checkpoints
+            via ``load_state_dict`` in a memory efficient way. See
+            :class:`FullStateDictConfig` for an example of this. (Default:
+            ``False``)
+        forward_prefetch (bool): If ``True``, then FSDP *explicitly* prefetches
+            the next forward-pass all-gather before the current forward
+            computation. This is only useful for CPU-bound workloads, in which
+            case issuing the next all-gather earlier may improve overlap. This
+            should only be used for static-graph models since the prefetching
+            follows the first iteration's execution order. (Default: ``False``)
+        limit_all_gathers (bool): If ``True``, then FSDP explicitly
+            synchronizes the CPU thread to ensure GPU memory usage from only
+            *two* consecutive FSDP instances (the current instance running
+            computation and the next instance whose all-gather is prefetched).
+            If ``False``, then FSDP allows the CPU thread to issue all-gathers
+            without any extra synchronization. (Default: ``True``) We often
+            refer to this feature as the "rate limiter". This flag should only
+            be set to ``False`` for specific CPU-bound workloads with low
+            memory pressure in which case the CPU thread can aggressively issue
+            all kernels without concern for the GPU memory usage.
+        use_orig_params (bool): Setting this to ``True`` has FSDP use
+            ``module`` 's original parameters. FSDP exposes those original
+            parameters to the user via :meth:`nn.Module.named_parameters`
+            instead of FSDP's internal :class:`FlatParameter` s. This means
+            that the optimizer step runs on the original parameters, enabling
+            per-original-parameter hyperparameters. FSDP preserves the original
+            parameter variables and manipulates their data between unsharded
+            and sharded forms, where they are always views into the underlying
+            unsharded or sharded :class:`FlatParameter`, respectively. With the
+            current algorithm, the sharded form is always 1D, losing the
+            original tensor structure. An original parameter may have all,
+            some, or none of its data present for a given rank. In the none
+            case, its data will be like a size-0 empty tensor. Users should not
+            author programs relying on what data is present for a given
+            original parameter in its sharded form. ``True`` is required to
+            use ``torch.compile()``. Setting this to ``False`` exposes FSDP's
+            internal :class:`FlatParameter` s to the user via
+            :meth:`nn.Module.named_parameters`. (Default: ``False``)
+        ignored_states (Optional[Iterable[torch.nn.Parameter]], Optional[Iterable[torch.nn.Module]]):
+            Ignored parameters or modules that will not be managed by this FSDP
+            instance, meaning that the parameters are not sharded and their
+            gradients are not reduced across ranks. This argument unifies with
+            the existing ``ignored_modules`` argument, and we may deprecate
+            ``ignored_modules`` soon. For backward compatibility, we keep both
+            ``ignored_states`` and `ignored_modules``, but FSDP only allows one
+            of them to be specified as not ``None``.
+        device_mesh (Optional[DeviceMesh]): DeviceMesh can be used as an altenative to
+            process_group. When device_mesh is passed, FSDP will use the underlying process
+            groups for all-gather and reduce-scatter collective communications. Therefore,
+            these two args need to be mutually exclusive. For hybrid sharding strategies such as
+            ``ShardingStrategy.HYBRID_SHARD``, users can pass in a 2D DeviceMesh instead
+            of a tuple of process groups. For 2D FSDP + TP, users are required to pass in
+            device_mesh instead of process_group. For more DeviceMesh info, please visit:
+            https://pytorch.org/tutorials/recipes/distributed_device_mesh.html
+    """
+
+    def __init__(
+        self,
+        module: nn.Module,
+        process_group: ProcessGroupType = None,
+        sharding_strategy: Optional[ShardingStrategy] = None,
+        cpu_offload: Optional[CPUOffload] = None,
+        auto_wrap_policy: Optional[
+            Union[Callable, ModuleWrapPolicy, CustomPolicy]
+        ] = None,
+        backward_prefetch: Optional[BackwardPrefetch] = BackwardPrefetch.BACKWARD_PRE,
+        mixed_precision: Optional[MixedPrecision] = None,
+        ignored_modules: Optional[Iterable[torch.nn.Module]] = None,
+        param_init_fn: Optional[Callable[[nn.Module], None]] = None,
+        device_id: Optional[Union[int, torch.device]] = None,
+        sync_module_states: bool = False,
+        forward_prefetch: bool = False,
+        limit_all_gathers: bool = True,
+        use_orig_params: bool = False,
+        ignored_states: Union[
+            Optional[Iterable[torch.nn.Parameter]], Optional[Iterable[torch.nn.Module]]
+        ] = None,
+        device_mesh: Optional[DeviceMesh] = None,
+    ):
+        torch._C._log_api_usage_once("torch.distributed.fsdp")
+        super().__init__()
+        if isinstance(module, (nn.ModuleList, nn.ModuleDict)):
+            warnings.warn(
+                "FSDP will not all-gather parameters for containers that do "
+                f"not implement forward: {module}",
+                stacklevel=2,
+            )
+        _init_ignored_module_states(self, module, ignored_modules, ignored_states)
+        _init_device_handle(self, module, self._ignored_params, device_id)
+
+        # Add module annotations for Dynamo support (see function for details)
+        _annotate_modules_for_dynamo(module, self._ignored_modules, use_orig_params)
+
+        # Initializes self.process_group, along with rank and world size. This will
+        # also set another attribute, _inter_node_pg, to control the process group
+        # over which sharding occurs, if sharding_strategy is {HYBRID_SHARD, _HYBRID_SHARD_ZERO2}.
+        # Note that this is done before auto_wrapping, so that child FSDP modules simply pick up
+        # the same process group state as the root FSDP module.
+        self._device_mesh = device_mesh
+        _init_process_group_state(
+            self,
+            process_group,
+            sharding_strategy,
+            auto_wrap_policy,
+            device_mesh,
+        )
+        if auto_wrap_policy is not None:
+            root_kwargs = {
+                "process_group": process_group,
+                "sharding_strategy": sharding_strategy,
+                "cpu_offload": cpu_offload,
+                "backward_prefetch": backward_prefetch,
+                "mixed_precision": mixed_precision,
+                "param_init_fn": param_init_fn,
+                "device_id": device_id,
+                "sync_module_states": sync_module_states,
+                "forward_prefetch": forward_prefetch,
+                "limit_all_gathers": limit_all_gathers,
+                "use_orig_params": use_orig_params,
+                "ignored_states": self._ignored_params,
+                "device_mesh": device_mesh,
+            }
+            if sharding_strategy in HYBRID_SHARDING_STRATEGIES and device_mesh is None:
+                # Share root process groups with children to maintain
+                # the invariant that all FSDP modules will have the same
+                # process groups.
+                root_kwargs["process_group"] = (self.process_group, self._inter_node_pg)
+
+            _auto_wrap(
+                module,
+                auto_wrap_policy,
+                self._ignored_modules,
+                self._ignored_params,
+                root_kwargs,
+                FullyShardedDataParallel,
+            )
+
+        backward_prefetch_limit = 1
+        forward_prefetch_limit = 1
+        _init_core_state(
+            self,
+            sharding_strategy,
+            mixed_precision,
+            cpu_offload,
+            limit_all_gathers,
+            use_orig_params,
+            backward_prefetch_limit,
+            forward_prefetch_limit,
+        )
+        _init_runtime_state(self)
+        _init_prefetching_state(self, backward_prefetch, forward_prefetch)
+        _init_buffer_state(self, module)
+        # extension needs to be set before `_init_param_handle_from_module()`
+        _init_extension(self, device_mesh)
+        _init_param_handle_from_module(
+            self,
+            module,
+            device_id,
+            param_init_fn,
+            sync_module_states,
+        )
+        self._fsdp_wrapped_module = module
+        if not use_orig_params:
+            _check_orig_params_flattened(self, self._ignored_params)
+            _register_flat_param(self, self)
+
+        # `_state_dict_type` controls the `state_dict()` behavior, which is
+        # implemented using post-save and pre-load hooks
+        _init_state_dict_state(self)
+        _register_all_state_dict_hooks(self)
+        self._zero_scalar = None
+
+    @property
+    def module(self) -> nn.Module:
+        """Return the wrapped module."""
+        # FSDP's `.module` must refer to the innermost wrapped module when
+        # composing with other module wrappers in order for state dict to work
+        if isinstance(self._fsdp_wrapped_module, ActivationWrapper):
+            return getattr(self._fsdp_wrapped_module, _CHECKPOINT_WRAPPED_MODULE)
+        return self._fsdp_wrapped_module
+
+    @property
+    def _has_params(self) -> bool:
+        """Returns whether this FSDP instance manages any parameters."""
+        return hasattr(self, "_handle") and self._handle is not None
+
+    @property
+    def _flat_param(self) -> Optional[FlatParameter]:
+        return self._handle.flat_param if self._handle else None
+
+    def __getattr__(self, name: str) -> Any:
+        """Forward missing attributes to the wrapped module."""
+        try:
+            return super().__getattr__(name)  # defer to nn.Module's logic
+        except AttributeError:
+            return getattr(self._fsdp_wrapped_module, name)
+
+    def __getitem__(self, key: int) -> Any:
+        """Forward indexing calls in case the module is an ``nn.Sequential``."""
+        if hasattr(self, FSDP_WRAPPED_MODULE):
+            return self._fsdp_wrapped_module.__getitem__(key)  # type: ignore[operator]
+        return super().__getitem__(key)
+
+    def check_is_root(self) -> bool:
+        """Check if this instance is a root FSDP module."""
+        return _is_fsdp_root(self, self)
+
+    @staticmethod
+    def fsdp_modules(
+        module: nn.Module,
+        root_only: bool = False,
+    ) -> List["FullyShardedDataParallel"]:
+        """Return all nested FSDP instances.
+
+        This possibly includes ``module`` itself and only includes FSDP root modules if ``root_only=True``.
+
+        Args:
+            module (torch.nn.Module): Root module, which may or may not be an
+                ``FSDP`` module.
+            root_only (bool): Whether to return only FSDP root modules.
+                (Default: ``False``)
+
+        Returns:
+            List[FullyShardedDataParallel]: FSDP modules that are nested in
+            the input ``module``.
+        """
+        if root_only:
+            return _get_fsdp_root_states(module)
+        return traversal_utils._get_fsdp_states(module)
+
+    def apply(self, fn: Callable[[nn.Module], None]) -> "FullyShardedDataParallel":
+        r"""Apply ``fn`` recursively to every submodule (as returned by ``.children()``) as well as self.
+
+        Typical use includes initializing the parameters of a model (see also :ref:`nn-init-doc`).
+
+        Compared to ``torch.nn.Module.apply``, this version additionally gathers
+        the full parameters before applying ``fn``. It should not be called from
+        within another ``summon_full_params`` context.
+
+        Args:
+            fn (:class:`Module` -> None): function to be applied to each submodule
+
+        Returns:
+            Module: self
+        """
+        uninitialized = self._is_root is None
+        self._assert_state(TrainingState.IDLE)
+        # Use `_unshard_params_for_summon()` with `recurse=False` instead of
+        # `_unshard_fsdp_state_params()` directly to perform lazy
+        # initialization, which is needed to initialize `FlatParameter`
+        # parameter attributes as required by the unshard logic
+        with _unshard_params_for_summon(
+            self,
+            self,
+            writeback=True,
+            rank0_only=False,
+            offload_to_cpu=False,
+            with_grads=False,
+        ):
+            ret = super().apply(fn)
+
+        # Reset lazy init called in `_unshard_params_for_summon()` since
+        # `apply()` may have been called on FSDP instance that is not truly a
+        # root, in which case it will be incorrectly marked as one.
+        if uninitialized and self._is_root:
+            for module in traversal_utils._get_fsdp_states(self):
+                module._reset_lazy_init()
+
+        return ret
+
+    def _mixed_precision_enabled_for_buffers(self) -> bool:
+        """Return whether the user explicitly enabled buffer mixed precision.
+
+        NOTE: Unlike parameters and gradient reduction, buffer mixed precision
+        is applied at the FSDP instance level, not the ``FlatParameter`` level,
+        which may be different for the composable code path.
+        """
+        return self.mixed_precision.buffer_dtype is not None
+
+    def _low_precision_hook_enabled(self) -> bool:
+        """Whether a low precision hook is registered or not."""
+        return self._comm_hook is not None and self._comm_hook in LOW_PRECISION_HOOKS
+
+    def _reset_lazy_init(self) -> None:
+        """Reset instance so :func:`_lazy_init` will run on the next forward."""
+        self._is_root: Optional[bool] = None
+
+    @staticmethod
+    def set_state_dict_type(
+        module: nn.Module,
+        state_dict_type: StateDictType,
+        state_dict_config: Optional[StateDictConfig] = None,
+        optim_state_dict_config: Optional[OptimStateDictConfig] = None,
+    ) -> StateDictSettings:
+        """Set the ``state_dict_type`` of all the descendant FSDP modules of the target module.
+
+        Also takes (optional) configuration for the model's and optimizer's state dict.
+        The target module does not have to be a FSDP module. If the target
+        module is a FSDP module, its ``state_dict_type`` will also be changed.
+
+        .. note:: This API should be called for only the top-level (root)
+            module.
+
+        .. note:: This API enables users to transparently use the conventional
+            ``state_dict`` API to take model checkpoints in cases where the
+            root FSDP module is wrapped by another ``nn.Module``. For example,
+            the following will ensure ``state_dict`` is called on all non-FSDP
+            instances, while dispatching into `sharded_state_dict` implementation
+            for FSDP:
+
+        Example::
+
+            >>> # xdoctest: +SKIP("undefined variables")
+            >>> model = DDP(FSDP(...))
+            >>> FSDP.set_state_dict_type(
+            >>>     model,
+            >>>     StateDictType.SHARDED_STATE_DICT,
+            >>>     state_dict_config = ShardedStateDictConfig(offload_to_cpu=True),
+            >>>     optim_state_dict_config = OptimStateDictConfig(offload_to_cpu=True),
+            >>> )
+            >>> param_state_dict = model.state_dict()
+            >>> optim_state_dict = FSDP.optim_state_dict(model, optim)
+
+        Args:
+            module (torch.nn.Module): Root module.
+            state_dict_type (StateDictType): the desired ``state_dict_type`` to set.
+            state_dict_config (Optional[StateDictConfig]): the configuration for the
+                target ``state_dict_type``.
+            optim_state_dict_config (Optional[OptimStateDictConfig]): the configuration
+                for the optimizer state dict.
+
+        Returns:
+            A StateDictSettings that include the previous state_dict type and
+            configuration for the module.
+        """
+        warnings.warn(
+            "FSDP.state_dict_type() and FSDP.set_state_dict_type() are being "
+            "deprecated. Please use APIs, get_state_dict() and set_state_dict(), "
+            "which can support different parallelisms, FSDP1, FSDP2, DDP. "
+            "API doc: https://pytorch.org/docs/stable/distributed.checkpoint.html"
+            "#torch.distributed.checkpoint.state_dict.get_state_dict ."
+            "Tutorial: https://pytorch.org/tutorials/recipes/distributed_checkpoint_recipe.html .",
+            FutureWarning,
+        )
+        _state_dict_type_to_config = {
+            StateDictType.FULL_STATE_DICT: FullStateDictConfig,
+            StateDictType.LOCAL_STATE_DICT: LocalStateDictConfig,
+            StateDictType.SHARDED_STATE_DICT: ShardedStateDictConfig,
+        }
+        _optim_state_dict_type_to_config = {
+            StateDictType.FULL_STATE_DICT: FullOptimStateDictConfig,
+            StateDictType.LOCAL_STATE_DICT: LocalOptimStateDictConfig,
+            StateDictType.SHARDED_STATE_DICT: ShardedOptimStateDictConfig,
+        }
+
+        # Use the default config if a state_dict config is not set.
+        state_dict_config_type = _state_dict_type_to_config[state_dict_type]
+        optim_state_dict_config_type = _optim_state_dict_type_to_config[state_dict_type]
+        if state_dict_config is None:
+            state_dict_config = state_dict_config_type()
+        if optim_state_dict_config is None:
+            optim_state_dict_config = optim_state_dict_config_type()
+        if state_dict_config_type != type(state_dict_config):
+            raise RuntimeError(
+                f"Expected state_dict_config of type {state_dict_config_type} "
+                f"but got {type(state_dict_config)}"
+            )
+        if optim_state_dict_config_type != type(optim_state_dict_config):
+            raise RuntimeError(
+                f"Expected optim_state_dict_config of type {optim_state_dict_config_type} "
+                f"but got {type(optim_state_dict_config)}"
+            )
+
+        # Set the state_dict type and configurations.
+        prev_state_dict_type = None
+        prev_state_dict_config = None
+        prev_optim_state_dict_config = None
+        for submodule in traversal_utils._get_fsdp_states(module):
+            if prev_state_dict_type is None:
+                prev_state_dict_type = submodule._state_dict_type
+            else:
+                assert (
+                    prev_state_dict_type == submodule._state_dict_type
+                ), "All FSDP modules should have the same state_dict_type."
+            if prev_state_dict_config is None:
+                prev_state_dict_config = submodule._state_dict_config
+            else:
+                assert isinstance(
+                    submodule._state_dict_config, type(prev_state_dict_config)
+                ), "All FSDP modules must have the same type of state_dict_config."
+            if prev_optim_state_dict_config is None:
+                prev_optim_state_dict_config = submodule._optim_state_dict_config
+            else:
+                assert isinstance(
+                    submodule._optim_state_dict_config,
+                    type(prev_optim_state_dict_config),
+                ), "All FSDP modules must have the same type of optim_state_dict_config."
+
+            submodule._state_dict_type = state_dict_type
+            submodule._state_dict_config = state_dict_config
+            submodule._optim_state_dict_config = optim_state_dict_config
+
+        return StateDictSettings(
+            prev_state_dict_type, prev_state_dict_config, prev_optim_state_dict_config
+        )
+
+    @staticmethod
+    def get_state_dict_type(module: nn.Module) -> StateDictSettings:
+        """Get the state_dict_type and the corresponding configurations for the FSDP modules rooted at ``module``.
+
+        The target module does not have to be an FSDP module.
+
+        Returns:
+            A ``StateDictSettings`` containing the state_dict_type and
+            state_dict / optim_state_dict configs that are currently set.
+
+        Raises:
+            ``AssertionError`` if the ``StateDictSettings`` for different
+            FSDP submodules differ.
+        """
+        state_dict_settings: Optional[StateDictSettings] = None
+        for submodule in FullyShardedDataParallel.fsdp_modules(module):
+            if state_dict_settings is None:
+                state_dict_settings = StateDictSettings(
+                    state_dict_type=submodule._state_dict_type,
+                    state_dict_config=submodule._state_dict_config,
+                    optim_state_dict_config=submodule._optim_state_dict_config,
+                )
+                _set_optim_use_dtensor(submodule, state_dict_settings)
+            else:
+                submodule_settings = StateDictSettings(
+                    submodule._state_dict_type,
+                    submodule._state_dict_config,
+                    submodule._optim_state_dict_config,
+                )
+                assert state_dict_settings == submodule_settings, (
+                    "All FSDP modules must have the same state dict settings."
+                    f"Got {submodule_settings} and {state_dict_settings}."
+                )
+                _set_optim_use_dtensor(submodule, submodule_settings)
+        return state_dict_settings
+
+    @staticmethod
+    @contextlib.contextmanager
+    def state_dict_type(
+        module: nn.Module,
+        state_dict_type: StateDictType,
+        state_dict_config: Optional[StateDictConfig] = None,
+        optim_state_dict_config: Optional[OptimStateDictConfig] = None,
+    ) -> Generator:
+        """Set the ``state_dict_type`` of all the descendant FSDP modules of the target module.
+
+        This context manager has the same functions as :meth:`set_state_dict_type`. Read the document of
+        :meth:`set_state_dict_type` for the detail.
+
+        Example::
+
+            >>> # xdoctest: +SKIP("undefined variables")
+            >>> model = DDP(FSDP(...))
+            >>> with FSDP.state_dict_type(
+            >>>     model,
+            >>>     StateDictType.SHARDED_STATE_DICT,
+            >>> ):
+            >>>     checkpoint = model.state_dict()
+
+        Args:
+            module (torch.nn.Module): Root module.
+            state_dict_type (StateDictType): the desired ``state_dict_type`` to set.
+            state_dict_config (Optional[StateDictConfig]): the model ``state_dict``
+                configuration for the target ``state_dict_type``.
+            optim_state_dict_config (Optional[OptimStateDictConfig]): the optimizer
+               ``state_dict`` configuration for the target ``state_dict_type``.
+        """
+        prev_state_dict_settings = FullyShardedDataParallel.set_state_dict_type(
+            module,
+            state_dict_type,
+            state_dict_config,
+            optim_state_dict_config,
+        )
+        yield
+        FullyShardedDataParallel.set_state_dict_type(
+            module,
+            prev_state_dict_settings.state_dict_type,
+            prev_state_dict_settings.state_dict_config,
+            prev_state_dict_settings.optim_state_dict_config,
+        )
+
+    def forward(self, *args: Any, **kwargs: Any) -> Any:
+        """Run the forward pass for the wrapped module, inserting FSDP-specific pre- and post-forward sharding logic."""
+        handle = self._handle
+        with torch.autograd.profiler.record_function(
+            "FullyShardedDataParallel.forward"
+        ):
+            args, kwargs = _root_pre_forward(self, self, args, kwargs)
+            unused = None
+            args, kwargs = _pre_forward(
+                self,
+                handle,
+                _pre_forward_unshard,
+                self._fsdp_wrapped_module,
+                args,
+                kwargs,
+            )
+            if handle:
+                _p_assert(
+                    handle.flat_param.device == self.compute_device,
+                    "Expected `FlatParameter` to be on the compute device "
+                    f"{self.compute_device} but got {handle.flat_param.device}",
+                )
+            output = self._fsdp_wrapped_module(*args, **kwargs)
+            return _post_forward(
+                self, handle, _post_forward_reshard, self, unused, output
+            )
+
+    @staticmethod
+    @contextlib.contextmanager
+    def summon_full_params(
+        module: nn.Module,
+        recurse: bool = True,
+        writeback: bool = True,
+        rank0_only: bool = False,
+        offload_to_cpu: bool = False,
+        with_grads: bool = False,
+    ) -> Generator:
+        r"""Expose full params for FSDP instances with this context manager.
+
+        Can be useful *after* forward/backward for a model to get
+        the params for additional processing or checking. It can take a non-FSDP
+        module and will summon full params for all contained FSDP modules as
+        well as their children, depending on the ``recurse`` argument.
+
+        .. note:: This can be used on inner FSDPs.
+        .. note:: This can *not* be used within a forward or backward pass. Nor
+            can forward and backward be started from within this context.
+        .. note:: Parameters will revert to their local shards after the context
+            manager exits, storage behavior is the same as forward.
+        .. note:: The full parameters can be modified, but only the portion
+            corresponding to the local param shard will persist after the
+            context manager exits (unless ``writeback=False``, in which case
+            changes will be discarded). In the case where FSDP does not shard
+            the parameters, currently only when ``world_size == 1``, or ``NO_SHARD``
+            config, the modification is persisted regardless of ``writeback``.
+        .. note:: This method works on modules which are not FSDP themselves but
+            may contain multiple independent FSDP units. In that case, the given
+            arguments will apply to all contained FSDP units.
+
+        .. warning:: Note that ``rank0_only=True`` in conjunction with
+            ``writeback=True`` is not currently supported and will raise an
+            error. This is because model parameter shapes would be different
+            across ranks within the context, and writing to them can lead to
+            inconsistency across ranks when the context is exited.
+
+        .. warning:: Note that ``offload_to_cpu`` and ``rank0_only=False`` will
+            result in full parameters being redundantly copied to CPU memory for
+            GPUs that reside on the same machine, which may incur the risk of
+            CPU OOM. It is recommended to use ``offload_to_cpu`` with
+            ``rank0_only=True``.
+
+        Args:
+            recurse (bool, Optional): recursively summon all params for nested
+                FSDP instances (default: True).
+            writeback (bool, Optional): if ``False``, modifications to params are
+                discarded after the context manager exits;
+                disabling this can be slightly more efficient (default: True)
+            rank0_only (bool, Optional): if ``True``, full parameters are
+                materialized on only global rank 0. This means that within the
+                context, only rank 0 will have full parameters and the other
+                ranks will have sharded parameters. Note that setting
+                ``rank0_only=True`` with ``writeback=True`` is not supported,
+                as model parameter shapes will be different across ranks
+                within the context, and writing to them can lead to
+                inconsistency across ranks when the context is exited.
+            offload_to_cpu (bool, Optional): If ``True``, full parameters are
+                offloaded to CPU. Note that this offloading currently only
+                occurs if the parameter is sharded (which is only not the case
+                for world_size = 1 or ``NO_SHARD`` config). It is recommended
+                to use ``offload_to_cpu`` with ``rank0_only=True`` to avoid
+                redundant copies of model parameters being offloaded to the same CPU memory.
+            with_grads (bool, Optional): If ``True``, gradients are also
+                unsharded with the parameters. Currently, this is only
+                supported when passing ``use_orig_params=True`` to the FSDP
+                constructor and ``offload_to_cpu=False`` to this method.
+                (Default: ``False``)
+        """
+        with _unshard_params(
+            module, recurse, writeback, rank0_only, offload_to_cpu, with_grads
+        ):
+            yield
+
+    @contextlib.contextmanager
+    def _deregister_orig_params_ctx(self):
+        """Deregister the original parameters and expose the :class:`FlatParameter`.
+
+        If a :class:`FlatParameter` is sharded, then
+        this refreshes the sharded views before exiting. This method should
+        only be called when using the original parameters.
+        """
+        _p_assert(
+            self._use_orig_params,
+            "`_deregister_orig_params_ctx()` should only be called when "
+            "`_use_orig_params=True`",
+        )
+        for fsdp_module in traversal_utils._get_fsdp_states(self):
+            _deregister_orig_params(fsdp_module, fsdp_module)
+        try:
+            yield
+        finally:
+            for fsdp_module in traversal_utils._get_fsdp_states(self):
+                _register_orig_params(fsdp_module, fsdp_module)
+
+    def _apply(self, *args, **kwargs):
+        """Deregister the original parameters and expose the :class:`FlatParameter` s before calling ``_apply()``."""
+        # When using the original parameters: Since (1) the `FlatParameter`s
+        # own the storage and (2) `_apply()` is the subroutine underlying the
+        # most common storage-changing ops like `to()` and `cuda()`, we
+        # override `_apply()` to have the storage change directly performed on
+        # the `FlatParameter`s instead of applying to the original parameters
+        # and then writing back to the `FlatParameter`s.
+        context = (
+            self._deregister_orig_params_ctx()
+            if self._use_orig_params
+            else contextlib.nullcontext()
+        )
+        with context:
+            return super()._apply(*args, **kwargs)
+
+    def named_buffers(
+        self,
+        *args,
+        **kwargs,
+    ) -> Iterator[Tuple[str, torch.Tensor]]:
+        """Return an iterator over module buffers, yielding both the name of the buffer and the buffer itself.
+
+        Intercepts buffer names and removes all occurrences of the FSDP-specific flattened buffer prefix
+        when inside the :meth:`summon_full_params` context manager.
+        """
+        should_clean_name = self.training_state == TrainingState.SUMMON_FULL_PARAMS
+        for buffer_name, buffer in super().named_buffers(*args, **kwargs):
+            if should_clean_name:
+                # Remove any instances of the FSDP-specific prefix; there can
+                # be multiple in the case of nested FSDP modules
+                buffer_name = buffer_name.replace(FSDP_PREFIX, "")
+            yield (buffer_name, buffer)
+
+    def named_parameters(
+        self,
+        *args,
+        **kwargs,
+    ) -> Iterator[Tuple[str, torch.nn.Parameter]]:
+        """Return an iterator over module parameters, yielding both the name of the parameter and the parameter itself.
+
+        Intercepts parameter names and removes all occurrences of the FSDP-specific flattened parameter prefix
+        when inside the :meth:`summon_full_params` context manager.
+        """
+        should_clean_name = self.training_state == TrainingState.SUMMON_FULL_PARAMS
+        for param_name, param in super().named_parameters(*args, **kwargs):
+            if should_clean_name:
+                # Remove any instances of the FSDP-specific prefix; there can
+                # be multiple in the case of nested FSDP modules
+                param_name = param_name.replace(FSDP_PREFIX, "")
+            yield (param_name, param)
+
+    def _assert_state(self, state: Union[TrainingState, List[TrainingState]]) -> None:
+        """Assert we are in the given state."""
+        # Since assert can be turned off and this error checking
+        # is really important, we use explicit error checking
+        # and raise a ValueError if needed.
+        if isinstance(state, TrainingState):
+            state = [state]
+        if self.training_state not in state:
+            msg = (
+                f"expected to be in states {state} but current state "
+                f"is {self.training_state}"
+            )
+            # In case we are failing in the context of autograd hook, asserting
+            # may not generate useful msg. So, let's print it to be sure.
+            if self.rank == 0:
+                print(f"Asserting FSDP instance is: {self}")
+                print(f"ERROR: {msg}")
+                traceback.print_stack()
+            raise ValueError(msg)
+
+    @contextmanager
+    def no_sync(self) -> Generator:
+        """Disable gradient synchronizations across FSDP instances.
+
+        Within this context, gradients will be accumulated in module
+        variables, which will later be synchronized in the first
+        forward-backward pass after exiting the context. This should only be
+        used on the root FSDP instance and will recursively apply to all
+        children FSDP instances.
+
+        .. note:: This likely results in higher memory usage because FSDP will
+            accumulate the full model gradients (instead of gradient shards)
+            until the eventual sync.
+
+        .. note:: When used with CPU offloading, the gradients will not be
+            offloaded to CPU when inside the context manager. Instead, they
+            will only be offloaded right after the eventual sync.
+        """
+        _lazy_init(self, self)
+        if not self._is_root:
+            raise RuntimeError(
+                "`no_sync()` on inner FSDP instances is not supported. Please call `no_sync()` on root FSDP module."
+            )
+        self._assert_state(TrainingState.IDLE)
+        old_flags = []
+        for m in self.modules():
+            if isinstance(m, FullyShardedDataParallel):
+                old_flags.append((m, m._sync_gradients))
+                m._sync_gradients = False
+        try:
+            yield
+        finally:
+            for m, old_flag in old_flags:
+                assert not m._sync_gradients, (
+                    "`_sync_gradients` was incorrectly set to "
+                    "`True` while in the `no_sync()` context manager"
+                )
+                m._sync_gradients = old_flag
+
+    @torch.no_grad()
+    def clip_grad_norm_(
+        self, max_norm: Union[float, int], norm_type: Union[float, int] = 2.0
+    ) -> torch.Tensor:
+        """Clip the gradient norm of all parameters.
+
+        The norm is computed over all parameters' gradients as viewed as a single vector, and the
+        gradients are modified in-place.
+
+        Args:
+            max_norm (float or int): max norm of the gradients
+            norm_type (float or int): type of the used p-norm. Can be ``'inf'``
+                for infinity norm.
+
+        Returns:
+            Total norm of the parameters (viewed as a single vector).
+
+        If every FSDP instance uses ``NO_SHARD``, meaning that no
+        gradients are sharded across ranks, then you may directly use
+        :func:`torch.nn.utils.clip_grad_norm_`.
+
+        If at least some FSDP instance uses a sharded strategy (i.e.
+        one other than ``NO_SHARD``), then you should use this method
+        instead of :func:`torch.nn.utils.clip_grad_norm_` since this method
+        handles the fact that gradients are sharded across ranks.
+
+        The total norm returned will have the "largest" dtype across
+        all parameters/gradients as defined by PyTorch's type promotion
+        semantics. For example, if *all* parameters/gradients use a low
+        precision dtype, then the returned norm's dtype will be that low
+        precision dtype, but if there exists at least one parameter/
+        gradient using FP32, then the returned norm's dtype will be FP32.
+
+        .. warning:: This needs to be called on all ranks since it uses
+            collective communications.
+        """
+        _lazy_init(self, self)
+        if not self._is_root:
+            raise RuntimeError(
+                "`clip_grad_norm_()` should only be called on the root FSDP instance"
+            )
+        if self._zero_scalar is None:
+            self._zero_scalar = torch.tensor(0.0, device=self.compute_device)
+        self._assert_state(TrainingState.IDLE)
+        # If every FSDP instance uses `NO_SHARD`, then we can directly use
+        # the normal `nn.utils` one targeting local gradients
+        all_no_shard = all(
+            not handle.uses_sharded_strategy for handle in self._all_handles
+        )
+        if all_no_shard:
+            return torch.nn.utils.clip_grad_norm_(
+                self.parameters(), max_norm, norm_type
+            )
+        # Otherwise, there exists some FSDP instance using a sharded strategy,
+        # where sharded and non-sharded parameters must be handled separately
+        max_norm = float(max_norm)
+        norm_type = float(norm_type)
+        sharded_params_set = set()
+        nonsharded_params_set = set()  # `NO_SHARD` or not FSDP-managed
+        # Make sure to compute the local norm using lists for deterministic
+        # iteration order and hence deterministic total norm computation
+        sharded_params = []
+        nonsharded_params = []
+        grads: List[torch.Tensor] = []
+        for handle in self._all_handles:
+            if handle.uses_sharded_strategy:
+                target_set = sharded_params_set
+                target_list = sharded_params
+            else:
+                target_set = nonsharded_params_set
+                target_list = nonsharded_params
+            if handle._use_orig_params:
+                for param in handle.flat_param._params:
+                    if param not in target_set:
+                        target_set.add(param)
+                        target_list.append(param)
+                        if param.grad is not None:
+                            grads.append(param.grad)
+            else:
+                if handle.flat_param not in target_set:
+                    target_set.add(handle.flat_param)
+                    target_list.append(handle.flat_param)
+                    if handle.flat_param.grad is not None:
+                        grads.append(handle.flat_param.grad)
+        for param in self.parameters():
+            not_fsdp_managed = (
+                param not in sharded_params_set and param not in nonsharded_params_set
+            )
+            if not_fsdp_managed:
+                nonsharded_params_set.add(param)
+                nonsharded_params.append(param)
+                if param.grad is not None:
+                    grads.append(param.grad)
+        # Compute local norms (forced to be in FP32)
+        local_sharded_norm = _get_grad_norm(
+            sharded_params, norm_type, self._zero_scalar, self.compute_device
+        )
+        local_nonsharded_norm = (
+            _get_grad_norm(
+                nonsharded_params, norm_type, self._zero_scalar, self.compute_device
+            )
+            if nonsharded_params
+            else None
+        )
+        # Reconstruct the total gradient norm depending on the norm type
+        if norm_type == math.inf:
+            total_norm = (
+                torch.maximum(local_sharded_norm, local_nonsharded_norm)
+                if local_nonsharded_norm is not None
+                else local_sharded_norm
+            )
+            dist.all_reduce(
+                total_norm, op=torch.distributed.ReduceOp.MAX, group=self.process_group
+            )
+        else:
+            total_norm = local_sharded_norm**norm_type
+            dist.all_reduce(total_norm, group=self.process_group)
+            # All-reducing the local non-sharded norm would count it an extra
+            # world-size-many times
+            if local_nonsharded_norm is not None:
+                total_norm += local_nonsharded_norm**norm_type
+            total_norm = total_norm ** (1.0 / norm_type)
+        if self.cpu_offload.offload_params:
+            total_norm = total_norm.cpu()
+
+        clip_coef = max_norm / (total_norm + 1e-6)
+        # Multiplying by the clamped coefficient is meaningless when it is
+        # equal to 1, but it avoids the host-device sync that would result from
+        # `if clip_coef < 1`
+        clip_coef_clamped = torch.clamp(clip_coef, max=1.0)
+        for grad in grads:
+            grad.mul_(clip_coef_clamped.to(grad.device, grad.dtype))
+        # Use the "largest" dtype by type promotion semantics to use the same
+        # dtype as if we did not force local norm computation to be in FP32
+        if len(grads) == 0:
+            # If this rank has no gradients, then we must default to FP32
+            # unless we use additional communication, which we prefer to avoid
+            # since `clip_grad_norm_()` is called in the training loop
+            warnings.warn(
+                f"Called FSDP.clip_grad_norm_() on rank {self.rank} with no "
+                "gradients -- returning the total norm in the default dtype "
+                f"{total_norm.dtype}"
+            )  # warn since this is generally unexpected
+            return total_norm
+        total_norm_dtype = functools.reduce(
+            torch.promote_types,
+            [grad.dtype for grad in grads],
+        )
+        return total_norm.to(total_norm_dtype)
+
+    @staticmethod
+    def _warn_optim_input(optim_input, *, stacklevel: int = 1):
+        if optim_input is not None:
+            warnings.warn(
+                "The `optim_input` argument is deprecated and will be removed after PyTorch 1.13. "
+                "You may remove it from your code without changing its functionality.",
+                FutureWarning,
+                stacklevel=stacklevel + 1,
+            )
+
+    @staticmethod
+    def _is_using_optim_input(optim_input, optim) -> bool:
+        if optim_input is None and optim is None:
+            # Use the default behavior of `optim_input``
+            return True
+        if optim_input is not None:
+            # Use the `optim_input` code path
+            return True
+        # Use the `optim` code path
+        return False
+
+    @staticmethod
+    def _warn_legacy_optim_state_dict(curr: str, new: str, *, stacklevel: int = 1):
+        warnings.warn(
+            f"``FullyShardedDataParallel.{curr}``is being deprecated and is "
+            f"replaced by ``FullyShardedDataParallel.{new}``. "
+            f"``FullyShardedDataParallel.{curr}`` may be removed after PyTorch 2.2.",
+            FutureWarning,
+            stacklevel=stacklevel + 1,
+        )
+
+    @staticmethod
+    def _optim_state_dict_impl(
+        model: torch.nn.Module,
+        optim: torch.optim.Optimizer,
+        optim_state_dict: Dict[str, Any],
+        optim_input: Optional[
+            Union[
+                List[Dict[str, Any]],
+                Iterable[torch.nn.Parameter],
+            ]
+        ] = None,
+        rank0_only: bool = True,
+        full_state_dict: bool = True,
+        group: Optional[dist.ProcessGroup] = None,
+        cpu_offload: bool = True,
+        *,
+        _stacklevel: int = 1,
+    ) -> Dict[str, Any]:
+        """Transform the state-dict of an optimizer corresponding to a sharded model.
+
+        This is the internal API that is used by all the optim_state_dict implementations.
+        Given model, optim, the original optim_state_dict, this API removes the
+        FSDP internal information and internal sharding from the optim_state_dict.
+        """
+        if full_state_dict:
+            FullyShardedDataParallel._warn_optim_input(
+                optim_input, stacklevel=_stacklevel + 1
+            )
+            using_optim_input = FullyShardedDataParallel._is_using_optim_input(
+                optim_input,
+                optim,
+            )
+        else:
+            using_optim_input = False
+            assert optim_input is None and not rank0_only
+
+        use_orig_params = FullyShardedDataParallel.fsdp_modules(model)[
+            0
+        ]._use_orig_params
+        assert all(
+            use_orig_params == m._use_orig_params
+            for m in FullyShardedDataParallel.fsdp_modules(model)
+        ), "Not all FSDP modules have the same _use_orig_params value"
+
+        return _optim_state_dict(
+            model=model,
+            optim=optim,
+            optim_state_dict=optim_state_dict,
+            optim_input=optim_input,
+            rank0_only=rank0_only,
+            shard_state=not full_state_dict,
+            group=group,
+            using_optim_input=using_optim_input,
+            use_orig_params=use_orig_params,
+            cpu_offload=cpu_offload,
+        )
+
+    @staticmethod
+    def _optim_state_dict_to_load_impl(
+        optim_state_dict: Dict[str, Any],
+        model: torch.nn.Module,
+        optim_input: Optional[
+            Union[
+                List[Dict[str, Any]],
+                Iterable[torch.nn.Parameter],
+            ]
+        ] = None,
+        optim: Optional[torch.optim.Optimizer] = None,
+        full_state_dict: bool = True,
+        rank0_only: bool = False,
+        is_named_optimizer: bool = False,
+        group: Optional[dist.ProcessGroup] = None,
+    ) -> Dict[str, Any]:
+        """
+        Convert an optimizer state-dict so that it can be loaded into the optimizer associated with the FSDP model.
+
+        This is the internal API that is used by all the load optim_state_dict implementations.
+        Given model, optim, and the saved optim_state_dict, this API adds the FSDP
+        internal information and internal sharding to the optim_state_dict.
+        """
+        if full_state_dict:
+            FullyShardedDataParallel._warn_optim_input(optim_input)
+            using_optim_input = FullyShardedDataParallel._is_using_optim_input(
+                optim_input,
+                optim,
+            )
+        else:
+            using_optim_input = False
+            assert optim_input is None and not rank0_only
+
+        use_orig_params = FullyShardedDataParallel.fsdp_modules(model)[
+            0
+        ]._use_orig_params
+        assert all(
+            use_orig_params == m._use_orig_params
+            for m in FullyShardedDataParallel.fsdp_modules(model)
+        ), "Not all FSDP modules have the same _use_orig_params value"
+
+        if rank0_only and dist.get_rank(group) > 0:
+            optim_state_dict = {}
+        sharded_osd = _flatten_optim_state_dict(
+            optim_state_dict,
+            model=model,
+            use_orig_params=use_orig_params,
+            optim=(optim if is_named_optimizer else None),
+            rank0_only=rank0_only,
+            group=group,
+        )
+        return _rekey_sharded_optim_state_dict(
+            sharded_osd,
+            model=model,
+            optim=optim,
+            optim_input=optim_input,
+            using_optim_input=using_optim_input,
+            is_named_optimizer=is_named_optimizer,
+        )
+
+    @staticmethod
+    def full_optim_state_dict(
+        model: torch.nn.Module,
+        optim: torch.optim.Optimizer,
+        optim_input: Optional[
+            Union[
+                List[Dict[str, Any]],
+                Iterable[torch.nn.Parameter],
+            ]
+        ] = None,
+        rank0_only: bool = True,
+        group: Optional[dist.ProcessGroup] = None,
+    ) -> Dict[str, Any]:
+        """Return the full optimizer state-dict.
+
+        Consolidates the full optimizer state on rank 0 and returns it
+        as a :class:`dict` following the convention of
+        :meth:`torch.optim.Optimizer.state_dict`, i.e. with keys ``"state"``
+        and ``"param_groups"``. The flattened parameters in ``FSDP`` modules
+        contained in ``model`` are mapped back to their unflattened parameters.
+
+        This needs to be called on all ranks since it uses
+        collective communications. However, if ``rank0_only=True``, then
+        the state dict is only populated on rank 0, and all other ranks
+        return an empty :class:`dict`.
+
+        Unlike ``torch.optim.Optimizer.state_dict()``, this method
+        uses full parameter names as keys instead of parameter IDs.
+
+        Like in :meth:`torch.optim.Optimizer.state_dict`, the tensors
+        contained in the optimizer state dict are not cloned, so there may
+        be aliasing surprises. For best practices, consider saving the
+        returned optimizer state dict immediately, e.g. using
+        ``torch.save()``.
+
+        Args:
+            model (torch.nn.Module): Root module (which may or may not be a
+                :class:`FullyShardedDataParallel` instance) whose parameters
+                were passed into the optimizer ``optim``.
+            optim (torch.optim.Optimizer): Optimizer for ``model`` 's
+                parameters.
+            optim_input (Optional[Union[List[Dict[str, Any]], Iterable[torch.nn.Parameter]]]):
+                Input passed into the optimizer ``optim`` representing either a
+                :class:`list` of parameter groups or an iterable of parameters;
+                if ``None``, then this method assumes the input was
+                ``model.parameters()``. This argument is deprecated, and there
+                is no need to pass it in anymore. (Default: ``None``)
+            rank0_only (bool): If ``True``, saves the populated :class:`dict`
+                only on rank 0; if ``False``, saves it on all ranks. (Default:
+                ``True``)
+            group (dist.ProcessGroup): Model's process group or ``None`` if using
+                the default process group. (Default: ``None``)
+
+        Returns:
+            Dict[str, Any]: A :class:`dict` containing the optimizer state for
+            ``model`` 's original unflattened parameters and including keys
+            "state" and "param_groups" following the convention of
+            :meth:`torch.optim.Optimizer.state_dict`. If ``rank0_only=True``,
+            then nonzero ranks return an empty :class:`dict`.
+        """
+        FullyShardedDataParallel._warn_legacy_optim_state_dict(
+            "full_optim_state_dict",
+            "optim_state_dict",
+            stacklevel=2,
+        )
+        return FullyShardedDataParallel._optim_state_dict_impl(
+            model=model,
+            optim=optim,
+            optim_state_dict=optim.state_dict(),
+            optim_input=optim_input,
+            rank0_only=rank0_only,
+            group=group,
+            full_state_dict=True,
+            _stacklevel=2,
+        )
+
+    @staticmethod
+    def sharded_optim_state_dict(
+        model: torch.nn.Module,
+        optim: torch.optim.Optimizer,
+        group: Optional[dist.ProcessGroup] = None,
+    ) -> Dict[str, Any]:
+        """Return the optimizer state-dict in its sharded form.
+
+        The API is similar to :meth:`full_optim_state_dict` but this API chunks
+        all non-zero-dimension states to :class:`ShardedTensor` to save memory.
+        This API should only be used when the model ``state_dict`` is derived
+        with the context manager ``with state_dict_type(SHARDED_STATE_DICT):``.
+
+        For the detailed usage, refer to :meth:`full_optim_state_dict`.
+
+        .. warning:: The returned state dict contains ``ShardedTensor`` and
+            cannot be directly used by the regular ``optim.load_state_dict``.
+        """
+        FullyShardedDataParallel._warn_legacy_optim_state_dict(
+            "sharded_optim_state_dict",
+            "optim_state_dict",
+            stacklevel=2,
+        )
+        return FullyShardedDataParallel._optim_state_dict_impl(
+            model=model,
+            optim=optim,
+            optim_state_dict=optim.state_dict(),
+            optim_input=None,
+            rank0_only=False,
+            full_state_dict=False,
+            group=group,
+            _stacklevel=2,
+        )
+
+    @staticmethod
+    def shard_full_optim_state_dict(
+        full_optim_state_dict: Dict[str, Any],
+        model: torch.nn.Module,
+        optim_input: Optional[
+            Union[
+                List[Dict[str, Any]],
+                Iterable[torch.nn.Parameter],
+            ]
+        ] = None,
+        optim: Optional[torch.optim.Optimizer] = None,
+    ) -> Dict[str, Any]:
+        """Shard a full optimizer state-dict.
+
+        Remaps the state in ``full_optim_state_dict`` to flattened parameters instead of unflattened
+        parameters and restricts to only this rank's part of the optimizer state.
+        The first argument should be the return value of :meth:`full_optim_state_dict`.
+
+        Example::
+
+            >>> # xdoctest: +SKIP("undefined variables")
+            >>> from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
+            >>> model, optim = ...
+            >>> full_osd = FSDP.full_optim_state_dict(model, optim)
+            >>> torch.save(full_osd, PATH)
+            >>> # Define new model with possibly different world size
+            >>> new_model, new_optim = ...
+            >>> full_osd = torch.load(PATH)
+            >>> sharded_osd = FSDP.shard_full_optim_state_dict(full_osd, new_model)
+            >>> new_optim.load_state_dict(sharded_osd)
+
+        .. note:: Both :meth:`shard_full_optim_state_dict` and
+            :meth:`scatter_full_optim_state_dict` may be used to get the
+            sharded optimizer state dict to load. Assuming that the full
+            optimizer state dict resides in CPU memory, the former requires
+            each rank to have the full dict in CPU memory, where each rank
+            individually shards the dict without any communication, while the
+            latter requires only rank 0 to have the full dict in CPU memory,
+            where rank 0 moves each shard to GPU memory (for NCCL) and
+            communicates it to ranks appropriately. Hence, the former has
+            higher aggregate CPU memory cost, while the latter has higher
+            communication cost.
+
+        Args:
+            full_optim_state_dict (Dict[str, Any]): Optimizer state dict
+                corresponding to the unflattened parameters and holding the
+                full non-sharded optimizer state.
+            model (torch.nn.Module): Root module (which may or may not be a
+                :class:`FullyShardedDataParallel` instance) whose parameters
+                correspond to the optimizer state in ``full_optim_state_dict``.
+            optim_input (Optional[Union[List[Dict[str, Any]], Iterable[torch.nn.Parameter]]]):
+                Input passed into the optimizer representing either a
+                :class:`list` of parameter groups or an iterable of parameters;
+                if ``None``, then this method assumes the input was
+                ``model.parameters()``. This argument is deprecated, and there
+                is no need to pass it in anymore. (Default: ``None``)
+            optim (Optional[torch.optim.Optimizer]): Optimizer that will load
+                the state dict returned by this method. This is the preferred
+                argument to use over ``optim_input``. (Default: ``None``)
+
+        Returns:
+            Dict[str, Any]: The full optimizer state dict now remapped to
+            flattened parameters instead of unflattened parameters and
+            restricted to only include this rank's part of the optimizer state.
+        """
+        FullyShardedDataParallel._warn_legacy_optim_state_dict(
+            "shard_full_optim_state_dict",
+            "optim_state_dict_to_load",
+            stacklevel=2,
+        )
+        return FullyShardedDataParallel._optim_state_dict_to_load_impl(
+            optim_state_dict=full_optim_state_dict,
+            model=model,
+            optim_input=optim_input,
+            optim=optim,
+            full_state_dict=True,
+            is_named_optimizer=False,
+        )
+
+    @staticmethod
+    def flatten_sharded_optim_state_dict(
+        sharded_optim_state_dict: Dict[str, Any],
+        model: torch.nn.Module,
+        optim: torch.optim.Optimizer,
+    ) -> Dict[str, Any]:
+        """Flatten a sharded optimizer state-dict.
+
+        The API is similar to :meth:`shard_full_optim_state_dict`. The only
+        difference is that the input ``sharded_optim_state_dict`` should be
+        returned from :meth:`sharded_optim_state_dict`. Therefore, there will
+        be all-gather calls on each rank to gather ``ShardedTensor`` s.
+
+        Args:
+            sharded_optim_state_dict (Dict[str, Any]): Optimizer state dict
+                corresponding to the unflattened parameters and holding the
+                sharded optimizer state.
+            model (torch.nn.Module):
+                Refer to :meth:`shard_full_optim_state_dict`.
+            optim (torch.optim.Optimizer): Optimizer for ``model`` 's
+                parameters.
+
+        Returns:
+            Refer to :meth:`shard_full_optim_state_dict`.
+        """
+        FullyShardedDataParallel._warn_legacy_optim_state_dict(
+            "flatten_sharded_optim_state_dict",
+            "optim_state_dict_to_load",
+            stacklevel=2,
+        )
+        return FullyShardedDataParallel._optim_state_dict_to_load_impl(
+            optim_state_dict=sharded_optim_state_dict,
+            model=model,
+            optim_input=None,
+            optim=optim,
+            full_state_dict=False,
+            is_named_optimizer=False,
+        )
+
+    @staticmethod
+    def scatter_full_optim_state_dict(
+        full_optim_state_dict: Optional[Dict[str, Any]],
+        model: torch.nn.Module,
+        optim_input: Optional[
+            Union[
+                List[Dict[str, Any]],
+                Iterable[torch.nn.Parameter],
+            ]
+        ] = None,
+        optim: Optional[torch.optim.Optimizer] = None,
+        group: Optional[Any] = None,
+    ) -> Dict[str, Any]:
+        """Scatter the full optimizer state dict from rank 0 to all other ranks.
+
+        Returns the sharded optimizer state dict on each rank.
+        The return value is the same as :meth:`shard_full_optim_state_dict`, and on rank
+        0, the first argument should be the return value of
+        :meth:`full_optim_state_dict`.
+
+        Example::
+
+            >>> # xdoctest: +SKIP("undefined variables")
+            >>> from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
+            >>> model, optim = ...
+            >>> full_osd = FSDP.full_optim_state_dict(model, optim)  # only non-empty on rank 0
+            >>> # Define new model with possibly different world size
+            >>> new_model, new_optim, new_group = ...
+            >>> sharded_osd = FSDP.scatter_full_optim_state_dict(full_osd, new_model, group=new_group)
+            >>> new_optim.load_state_dict(sharded_osd)
+
+        .. note:: Both :meth:`shard_full_optim_state_dict` and
+            :meth:`scatter_full_optim_state_dict` may be used to get the
+            sharded optimizer state dict to load. Assuming that the full
+            optimizer state dict resides in CPU memory, the former requires
+            each rank to have the full dict in CPU memory, where each rank
+            individually shards the dict without any communication, while the
+            latter requires only rank 0 to have the full dict in CPU memory,
+            where rank 0 moves each shard to GPU memory (for NCCL) and
+            communicates it to ranks appropriately. Hence, the former has
+            higher aggregate CPU memory cost, while the latter has higher
+            communication cost.
+
+        Args:
+            full_optim_state_dict (Optional[Dict[str, Any]]): Optimizer state
+                dict corresponding to the unflattened parameters and holding
+                the full non-sharded optimizer state if on rank 0; the argument
+                is ignored on nonzero ranks.
+            model (torch.nn.Module): Root module (which may or may not be a
+                :class:`FullyShardedDataParallel` instance) whose parameters
+                correspond to the optimizer state in ``full_optim_state_dict``.
+            optim_input (Optional[Union[List[Dict[str, Any]], Iterable[torch.nn.Parameter]]]):
+                Input passed into the optimizer representing either a
+                :class:`list` of parameter groups or an iterable of parameters;
+                if ``None``, then this method assumes the input was
+                ``model.parameters()``. This argument is deprecated, and there
+                is no need to pass it in anymore. (Default: ``None``)
+            optim (Optional[torch.optim.Optimizer]): Optimizer that will load
+                the state dict returned by this method. This is the preferred
+                argument to use over ``optim_input``. (Default: ``None``)
+            group (dist.ProcessGroup): Model's process group or ``None`` if
+                using the default process group. (Default: ``None``)
+
+        Returns:
+            Dict[str, Any]: The full optimizer state dict now remapped to
+            flattened parameters instead of unflattened parameters and
+            restricted to only include this rank's part of the optimizer state.
+        """
+        FullyShardedDataParallel._warn_legacy_optim_state_dict(
+            "scatter_full_optim_state_dict",
+            "optim_state_dict_to_load",
+            stacklevel=2,
+        )
+        return FullyShardedDataParallel._optim_state_dict_to_load_impl(
+            optim_state_dict=full_optim_state_dict,
+            model=model,
+            optim_input=optim_input,
+            optim=optim,
+            full_state_dict=True,
+            rank0_only=True,
+            is_named_optimizer=False,
+            group=group,
+        )
+
+    @staticmethod
+    def rekey_optim_state_dict(
+        optim_state_dict: Dict[str, Any],
+        optim_state_key_type: OptimStateKeyType,
+        model: torch.nn.Module,
+        optim_input: Optional[
+            Union[
+                List[Dict[str, Any]],
+                Iterable[torch.nn.Parameter],
+            ]
+        ] = None,
+        optim: Optional[torch.optim.Optimizer] = None,
+    ) -> Dict[str, Any]:
+        """Re-keys the optimizer state dict ``optim_state_dict`` to use the key type ``optim_state_key_type``.
+
+        This can be used to achieve compatibility between optimizer state dicts from models with FSDP
+        instances and ones without.
+
+        To re-key an FSDP full optimizer state dict (i.e. from
+        :meth:`full_optim_state_dict`) to use parameter IDs and be loadable to
+        a non-wrapped model::
+
+            >>> # xdoctest: +SKIP("undefined variables")
+            >>> wrapped_model, wrapped_optim = ...
+            >>> full_osd = FSDP.full_optim_state_dict(wrapped_model, wrapped_optim)
+            >>> nonwrapped_model, nonwrapped_optim = ...
+            >>> rekeyed_osd = FSDP.rekey_optim_state_dict(full_osd, OptimStateKeyType.PARAM_ID, nonwrapped_model)
+            >>> nonwrapped_optim.load_state_dict(rekeyed_osd)
+
+        To re-key a normal optimizer state dict from a non-wrapped model to be
+        loadable to a wrapped model::
+
+            >>> # xdoctest: +SKIP("undefined variables")
+            >>> nonwrapped_model, nonwrapped_optim = ...
+            >>> osd = nonwrapped_optim.state_dict()
+            >>> rekeyed_osd = FSDP.rekey_optim_state_dict(osd, OptimStateKeyType.PARAM_NAME, nonwrapped_model)
+            >>> wrapped_model, wrapped_optim = ...
+            >>> sharded_osd = FSDP.shard_full_optim_state_dict(rekeyed_osd, wrapped_model)
+            >>> wrapped_optim.load_state_dict(sharded_osd)
+
+        Returns:
+            Dict[str, Any]: The optimizer state dict re-keyed using the
+            parameter keys specified by ``optim_state_key_type``.
+        """
+        FullyShardedDataParallel._warn_optim_input(optim_input)
+        using_optim_input = FullyShardedDataParallel._is_using_optim_input(
+            optim_input,
+            optim,
+        )
+        assert optim_state_key_type in (
+            OptimStateKeyType.PARAM_NAME,
+            OptimStateKeyType.PARAM_ID,
+        )
+        osd = optim_state_dict  # alias
+        # Validate that the existing parameter keys are uniformly typed
+        uses_param_name_mask = [type(param_key) is str for param_key in osd["state"]]
+        uses_param_id_mask = [type(param_key) is int for param_key in osd["state"]]
+        if (any(uses_param_name_mask) and not all(uses_param_name_mask)) or (
+            any(uses_param_id_mask) and not all(uses_param_id_mask)
+        ):
+            error_msg = f"Invalid parameter keys: {osd['state'].keys()}"
+            raise ValueError(error_msg)
+        # Return directly if the existing key type matches the target key type
+        if (
+            optim_state_key_type == OptimStateKeyType.PARAM_NAME
+            and all(uses_param_name_mask)
+        ) or (
+            optim_state_key_type == OptimStateKeyType.PARAM_ID
+            and all(uses_param_id_mask)
+        ):
+            return osd
+        # Otherwise, actually perform the re-keying
+        new_osd = {}
+        if optim_state_key_type == OptimStateKeyType.PARAM_NAME:  # ID -> name
+            param_id_to_param = (
+                _get_param_id_to_param_from_optim_input(model, optim_input)
+                if using_optim_input
+                else _get_param_key_to_param(optim)
+            )
+            param_to_param_name = _get_param_to_fqn(model)
+            param_id_to_param_name: List[str] = [
+                param_to_param_name[param] for param in param_id_to_param.values()
+            ]
+            new_osd["state"] = {
+                param_id_to_param_name[param_id]: param_state
+                for param_id, param_state in osd["state"].items()
+            }
+            new_osd["param_groups"] = copy.deepcopy(osd["param_groups"])
+            for param_group in new_osd["param_groups"]:
+                param_group["params"] = sorted(
+                    [
+                        param_id_to_param_name[param_id]
+                        for param_id in param_group["params"]
+                    ]
+                )
+            return new_osd
+        elif optim_state_key_type == OptimStateKeyType.PARAM_ID:  # name -> ID
+            param_name_to_param = _get_fqn_to_param(model)
+            param_to_param_id = (
+                _get_param_to_param_id_from_optim_input(model, optim_input)
+                if using_optim_input
+                else _get_param_to_param_key(optim)
+            )
+            # Because not all model parameters may be passed as the optimizer
+            # input, we may need to drop some parameters from this mapping
+            param_name_to_param_id = {
+                param_name: param_to_param_id[param]
+                for param_name, param in param_name_to_param.items()
+                if param in param_to_param_id
+            }
+            new_osd["state"] = {
+                param_name_to_param_id[param_name]: param_state
+                for param_name, param_state in osd["state"].items()
+            }
+            new_osd["param_groups"] = copy.deepcopy(osd["param_groups"])
+            for param_group in new_osd["param_groups"]:
+                param_group["params"] = sorted(
+                    [
+                        param_name_to_param_id[param_name]
+                        for param_name in param_group["params"]
+                    ]
+                )
+            return new_osd
+        return new_osd  # should never reach here
+
+    @staticmethod
+    def optim_state_dict(
+        model: torch.nn.Module,
+        optim: torch.optim.Optimizer,
+        optim_state_dict: Optional[Dict[str, Any]] = None,
+        group: Optional[dist.ProcessGroup] = None,
+    ) -> Dict[str, Any]:
+        """
+        Transform the state-dict of an optimizer corresponding to a sharded model.
+
+        The given state-dict can be transformed to one of three types:
+        1) full optimizer state_dict, 2) sharded optimizer state_dict, 3) local optimizer state_dict.
+
+        For full optimizer state_dict, all states are unflattened and not sharded.
+        Rank0 only and CPU only can be specified via :meth:`state_dict_type` to
+        avoid OOM.
+
+        For sharded optimizer state_dict, all states are unflattened but sharded.
+        CPU only can be specified via :meth:`state_dict_type` to further save
+        memory.
+
+        For local state_dict, no transformation will be performed. But a state
+        will be converted from nn.Tensor to ShardedTensor to represent its sharding
+        nature (this is not supported yet).
+
+        Example::
+
+            >>> # xdoctest: +SKIP("undefined variables")
+            >>> from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
+            >>> from torch.distributed.fsdp import StateDictType
+            >>> from torch.distributed.fsdp import FullStateDictConfig
+            >>> from torch.distributed.fsdp import FullOptimStateDictConfig
+            >>> # Save a checkpoint
+            >>> model, optim = ...
+            >>> FSDP.set_state_dict_type(
+            >>>     model,
+            >>>     StateDictType.FULL_STATE_DICT,
+            >>>     FullStateDictConfig(rank0_only=False),
+            >>>     FullOptimStateDictConfig(rank0_only=False),
+            >>> )
+            >>> state_dict = model.state_dict()
+            >>> optim_state_dict = FSDP.optim_state_dict(model, optim)
+            >>> save_a_checkpoint(state_dict, optim_state_dict)
+            >>> # Load a checkpoint
+            >>> model, optim = ...
+            >>> state_dict, optim_state_dict = load_a_checkpoint()
+            >>> FSDP.set_state_dict_type(
+            >>>     model,
+            >>>     StateDictType.FULL_STATE_DICT,
+            >>>     FullStateDictConfig(rank0_only=False),
+            >>>     FullOptimStateDictConfig(rank0_only=False),
+            >>> )
+            >>> model.load_state_dict(state_dict)
+            >>> optim_state_dict = FSDP.optim_state_dict_to_load(
+            >>>     model, optim, optim_state_dict
+            >>> )
+            >>> optim.load_state_dict(optim_state_dict)
+
+        Args:
+            model (torch.nn.Module): Root module (which may or may not be a
+                :class:`FullyShardedDataParallel` instance) whose parameters
+                were passed into the optimizer ``optim``.
+            optim (torch.optim.Optimizer): Optimizer for ``model`` 's
+                parameters.
+            optim_state_dict (Dict[str, Any]): the target optimizer state_dict to
+                transform. If the value is None, optim.state_dict() will be used. (
+                Default: ``None``)
+            group (dist.ProcessGroup): Model's process group across which parameters
+                are sharded or ``None`` if using the default process group. (
+                Default: ``None``)
+
+        Returns:
+            Dict[str, Any]: A :class:`dict` containing the optimizer state for
+            ``model``. The sharding of the optimizer state is based on
+            ``state_dict_type``.
+        """
+        state_dict_settings = FullyShardedDataParallel.get_state_dict_type(model)
+        if optim_state_dict is None:
+            optim_state_dict = optim.state_dict()
+        return FullyShardedDataParallel._optim_state_dict_impl(
+            model=model,
+            optim=optim,
+            optim_state_dict=optim_state_dict,
+            optim_input=None,
+            rank0_only=getattr(
+                state_dict_settings.optim_state_dict_config, "rank0_only", False
+            ),
+            full_state_dict=state_dict_settings.state_dict_type
+            == StateDictType.FULL_STATE_DICT,
+            group=group,
+            cpu_offload=getattr(
+                state_dict_settings.optim_state_dict_config, "offload_to_cpu", True
+            ),
+            _stacklevel=2,
+        )
+
+    @staticmethod
+    def optim_state_dict_to_load(
+        model: torch.nn.Module,
+        optim: torch.optim.Optimizer,
+        optim_state_dict: Dict[str, Any],
+        is_named_optimizer: bool = False,
+        load_directly: bool = False,
+        group: Optional[dist.ProcessGroup] = None,
+    ) -> Dict[str, Any]:
+        """
+        Convert an optimizer state-dict so that it can be loaded into the optimizer associated with the FSDP model.
+
+        Given a ``optim_state_dict`` that is transformed through
+        :meth:`optim_state_dict`, it gets converted to the flattened optimizer
+        state_dict that can be loaded to ``optim`` which is the optimizer for
+        ``model``. ``model`` must be sharded by FullyShardedDataParallel.
+
+            >>> # xdoctest: +SKIP("undefined variables")
+            >>> from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
+            >>> from torch.distributed.fsdp import StateDictType
+            >>> from torch.distributed.fsdp import FullStateDictConfig
+            >>> from torch.distributed.fsdp import FullOptimStateDictConfig
+            >>> # Save a checkpoint
+            >>> model, optim = ...
+            >>> FSDP.set_state_dict_type(
+            >>>     model,
+            >>>     StateDictType.FULL_STATE_DICT,
+            >>>     FullStateDictConfig(rank0_only=False),
+            >>>     FullOptimStateDictConfig(rank0_only=False),
+            >>> )
+            >>> state_dict = model.state_dict()
+            >>> original_osd = optim.state_dict()
+            >>> optim_state_dict = FSDP.optim_state_dict(
+            >>>     model,
+            >>>     optim,
+            >>>     optim_state_dict=original_osd
+            >>> )
+            >>> save_a_checkpoint(state_dict, optim_state_dict)
+            >>> # Load a checkpoint
+            >>> model, optim = ...
+            >>> state_dict, optim_state_dict = load_a_checkpoint()
+            >>> FSDP.set_state_dict_type(
+            >>>     model,
+            >>>     StateDictType.FULL_STATE_DICT,
+            >>>     FullStateDictConfig(rank0_only=False),
+            >>>     FullOptimStateDictConfig(rank0_only=False),
+            >>> )
+            >>> model.load_state_dict(state_dict)
+            >>> optim_state_dict = FSDP.optim_state_dict_to_load(
+            >>>     model, optim, optim_state_dict
+            >>> )
+            >>> optim.load_state_dict(optim_state_dict)
+
+        Args:
+            model (torch.nn.Module): Root module (which may or may not be a
+                :class:`FullyShardedDataParallel` instance) whose parameters
+                were passed into the optimizer ``optim``.
+            optim (torch.optim.Optimizer): Optimizer for ``model`` 's
+                parameters.
+            optim_state_dict (Dict[str, Any]): The optimizer states to be loaded.
+            is_named_optimizer (bool): Is this optimizer a NamedOptimizer or
+                KeyedOptimizer. Only set to True if ``optim`` is TorchRec's
+                KeyedOptimizer or torch.distributed's NamedOptimizer.
+            load_directly (bool): If this is set to True, this API will also
+                call optim.load_state_dict(result) before returning the result.
+                Otherwise, users are responsible to call ``optim.load_state_dict()``
+                (Default: ``False``)
+            group (dist.ProcessGroup): Model's process group across which parameters
+                are sharded or ``None`` if using the default process group. (
+                Default: ``None``)
+        """
+        state_dict_settings = FullyShardedDataParallel.get_state_dict_type(model)
+        result = FullyShardedDataParallel._optim_state_dict_to_load_impl(
+            optim_state_dict=optim_state_dict,
+            model=model,
+            optim_input=None,
+            optim=optim,
+            full_state_dict=(
+                state_dict_settings.state_dict_type == StateDictType.FULL_STATE_DICT
+            ),
+            rank0_only=getattr(
+                state_dict_settings.optim_state_dict_config, "rank0_only", False
+            ),
+            is_named_optimizer=is_named_optimizer,
+            group=group,
+        )
+        if load_directly:
+            optim.load_state_dict(result)
+        return result
+
+    def register_comm_hook(self, state: object, hook: callable):
+        """Register a communication hook.
+
+        This is an enhancement that provides a flexible hook to users where they can specify how FSDP aggregates
+        gradients across multiple workers.
+        This hook can be used to implement several algorithms like
+        `GossipGrad `_ and gradient compression
+        which involve different communication strategies for
+        parameter syncs while training with :class:`FullyShardedDataParallel`.
+
+        .. warning ::
+            FSDP communication hook should be registered before running an initial forward pass
+            and only once.
+
+        Args:
+            state (object): Passed to the hook to maintain any state information during the training process.
+                            Examples include error feedback in gradient compression,
+                            peers to communicate with next in `GossipGrad `_, etc.
+                            It is locally stored by each worker
+                            and shared by all the gradient tensors on the worker.
+            hook (Callable): Callable, which has one of the following signatures:
+                            1) ``hook: Callable[torch.Tensor] -> None``:
+                            This function takes in a Python tensor, which represents
+                            the full, flattened, unsharded gradient with respect to all variables
+                            corresponding to the model this FSDP unit is wrapping
+                            (that are not wrapped by other FSDP sub-units).
+                            It then performs all necessary processing and returns ``None``;
+                            2) ``hook: Callable[torch.Tensor, torch.Tensor] -> None``:
+                            This function takes in two Python tensors, the first one represents
+                            the full, flattened, unsharded gradient with respect to all variables
+                            corresponding to the model this FSDP unit is wrapping
+                            (that are not wrapped by other FSDP sub-units). The latter
+                            represents a pre-sized tensor to store a chunk of a sharded gradient after
+                            reduction.
+                            In both cases, callable performs all necessary processing and returns ``None``.
+                            Callables with signature 1 are expected to handle gradient communication for a `NO_SHARD` case.
+                            Callables with signature 2 are expected to handle gradient communication for sharded cases.
+
+        """
+        if not self.check_is_root():
+            raise AssertionError(
+                "register_comm_hook can only be called on a root instance."
+            )
+        for fsdp_state in traversal_utils._get_fsdp_states(self):
+            if fsdp_state.sharding_strategy in HYBRID_SHARDING_STRATEGIES:
+                raise AssertionError(
+                    f"Communication hook is not supported for hybrid strategies: {fsdp_state.sharding_strategy}"
+                )
+            if fsdp_state._comm_hook is not None:
+                raise AssertionError("A communication hook is already registered")
+            if not callable(hook):
+                raise ValueError(
+                    f"The communication hook must be callable but got {hook}"
+                )
+            fsdp_state._comm_hook = hook
+            fsdp_state._comm_hook_state = state
+
+    def _unshard(self, async_op: bool = False):
+        class UnshardHandle:
+            def __init__(
+                self,
+                flat_param_handle: Optional[FlatParamHandle],
+                unshard_event: torch.Event,
+            ):
+                self._flat_param_handle = flat_param_handle
+                self._unshard_event = unshard_event
+
+            def wait(self):
+                if self._flat_param_handle is not None:
+                    current_stream = (
+                        self._flat_param_handle._device_handle.current_stream()
+                    )
+                    current_stream.wait_event(self._unshard_event)
+                    self._flat_param_handle = None
+
+        if self._handle:
+            with self._use_training_state(
+                TrainingState.FORWARD_BACKWARD, HandleTrainingState.FORWARD
+            ):
+                _unshard(
+                    self, self._handle, self._unshard_stream, self._pre_unshard_stream
+                )
+                self._unshard_event = self._unshard_stream.record_event()
+            self._handle._prefetched = True
+        unshard_handle = UnshardHandle(self._handle, self._unshard_stream)
+        if async_op:
+            return unshard_handle
+        unshard_handle.wait()
+        return None
+
+    def _wait_unshard_streams_on_current_stream(self):
+        _wait_for_computation_stream(
+            self._device_handle.current_stream(),
+            self._unshard_stream,
+            self._pre_unshard_stream,
+        )
+
+    @contextlib.contextmanager
+    def _use_training_state(
+        self, training_state: TrainingState, handle_training_state: HandleTrainingState
+    ):
+        prev_training_state = self.training_state
+        self.training_state = training_state
+        if self._handle:
+            prev_handle_training_state = self._handle._training_state
+            self._handle._training_state = handle_training_state
+        try:
+            yield
+        finally:
+            self.training_state = prev_training_state
+            if self._handle:
+                self._handle._training_state = prev_handle_training_state
+
+
+def _get_grad_norm(
+    params: Iterable[nn.Parameter],
+    norm_type: float,
+    zero: torch.Tensor,
+    device: torch.device,
+) -> torch.Tensor:
+    """
+    Return the gradient norm of parameters ``param`` s, where the gradients are viewed as a single vector.
+
+    The returned norm is in FP32 even if parameters/gradients are in a low precision. This is because the downstream
+    use of this return value is a reduction across ranks.
+    """
+    params_with_grad = [param for param in params if param.grad is not None]
+    if len(params_with_grad) == 0:
+        # Reuse a tensor for zero to avoid a GPU sync
+        return zero
+    grads = [param.grad for param in params_with_grad]
+    grad_dtypes = {grad.dtype for grad in grads}
+    if len(grad_dtypes) != 1:
+        raise ValueError(
+            f"Requires uniform dtype across all gradients but got {grad_dtypes}"
+        )
+    # Compute the gradient norm in FP32, where we treat the gradients as a
+    # single vector
+    grad_norm = torch.linalg.vector_norm(
+        torch.stack(
+            [
+                torch.linalg.vector_norm(grad.detach(), norm_type, dtype=torch.float32)
+                for grad in grads
+            ],
+        ),
+        norm_type,
+        dtype=torch.float32,
+    )
+    return grad_norm.to(device=device)
+
+
+def _get_param_to_fqn(
+    model: torch.nn.Module,
+) -> Dict[torch.nn.Parameter, str]:
+    """
+    Construct a mapping from parameters to their parameter names.
+
+    The ``model`` should not contain any :class:`FullyShardedDataParallel` instances, which
+    means that none of the parameters should be ``FlatParameter`` s. As a
+    result, compared to :meth:`_get_param_to_fqns`, the mapped
+    values may be flattened from singleton :class:`list` s to the contained
+    names themselves.
+
+    Args:
+        model (torch.nn.Module): Root module, which should not contain any
+            :class:`FullyShardedDataParallel` instances.
+    """
+    param_to_param_names = _get_param_to_fqns(model)
+    for param_names in param_to_param_names.values():
+        assert (
+            len(param_names) > 0
+        ), "`_get_param_to_fqns()` should not construct empty lists"
+        if len(param_names) > 1:
+            raise RuntimeError(
+                "Each parameter should only map to one parameter name but got "
+                f"{len(param_names)}: {param_names}"
+            )
+    param_to_param_name = {
+        param: param_names[0] for param, param_names in param_to_param_names.items()
+    }
+    return param_to_param_name
+
+
+def _get_fqn_to_param(
+    model: torch.nn.Module,
+) -> Dict[str, torch.nn.Parameter]:
+    """Construct the inverse mapping of :meth:`_get_param_to_fqn`."""
+    param_to_param_name = _get_param_to_fqn(model)
+    return dict(zip(param_to_param_name.values(), param_to_param_name.keys()))
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/sharded_grad_scaler.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/sharded_grad_scaler.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4f1f1dae4e82c6958aea8f7ff68524f981d3640
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/sharded_grad_scaler.py
@@ -0,0 +1,396 @@
+# mypy: allow-untyped-defs
+import logging
+from collections import abc, defaultdict
+from typing import Any, Dict, Iterable, List, Optional, overload, Sequence, Tuple, Union
+
+import torch
+import torch.distributed as dist
+from torch.amp.grad_scaler import _MultiDeviceReplicator, GradScaler, OptState
+from torch.distributed.distributed_c10d import ProcessGroup
+
+
+logger = logging.getLogger(__name__)
+
+
+def _refresh_per_optimizer_state() -> Dict[str, Any]:
+    return {"stage": OptState.READY, "found_inf_per_device": {}}
+
+
+def _is_supported_device(tensor: torch.Tensor) -> bool:
+    return tensor.is_cuda or tensor.device.type in (
+        "xla",
+        "cpu",
+        "hpu",
+        "mtia",
+        torch._C._get_privateuse1_backend_name(),
+    )
+
+
+class _GeneralMultiDeviceReplicator(_MultiDeviceReplicator):
+    """
+    Lazily serves tensor to request device. This class extends
+    _MultiDeviceReplicator to allow support for "cpu" as a device.
+    """
+
+    def __init__(self, master_tensor: torch.Tensor) -> None:
+        assert _is_supported_device(master_tensor)
+        self.master = master_tensor
+        self._per_device_tensors: Dict[torch.device, torch.Tensor] = {}
+
+
+class ShardedGradScaler(GradScaler):
+    """
+    ShardedGradScaler helps perform gradient scaling in a shard aware manner. It extends
+    functionality from GradScaler:
+    * Supports Pytorch DDP and FSDP implementations
+    * Support CPU offloaded tensors (as used in fully sharded data parallel[FSDP])
+    * Supports the custom Mixed Precision loss dtype (fp16, bf16) that FSDP returns
+    * Sync inf/nan for scaled gradient tensors on any torch.device (where tensors are placed) across
+    nodes
+
+    Example::
+
+        # Creates a ShardedGradScaler once at the beginning of training.
+        scaler = ShardedGradScaler()
+
+        for epoch in epochs:
+            for input, target in data:
+                optimizer.zero_grad()
+                output = model(input)
+                loss = loss_fn(output, target)
+
+                # Scales loss.  Calls backward() on scaled loss to create scaled gradients.
+                scaler.scale(loss).backward()
+
+                # scaler.step() first unscales gradients of the optimizer's params.
+                # If gradients don't contain infs/NaNs, optimizer.step() is then called,
+                # otherwise, optimizer.step() is skipped.
+                scaler.step(optimizer)
+
+                # Updates the scale for next iteration.
+                scaler.update()
+
+    See :class:`GradScaler` for explanation of scaling/unscaling and more use cases.
+
+    Args:
+        init_scale (float, optional, default=2.**16):  Initial scale factor.
+        growth_factor (float, optional, default=2.0):  Factor by which the scale is multiplied during
+            :meth:`update` if no inf/NaN gradients occur for ``growth_interval`` consecutive iterations.
+        backoff_factor (float, optional, default=0.5):  Factor by which the scale is multiplied during
+            :meth:`update` if inf/NaN gradients occur in an iteration.
+        growth_interval (int, optional, default=2000):  Number of consecutive iterations without inf/NaN gradients
+            that must occur for the scale to be multiplied by ``growth_factor``.
+        enabled (bool, optional):  If ``False``, disables gradient scaling. :meth:`step` simply
+            invokes the underlying ``optimizer.step()``, and other methods become no-ops.
+            Default: ``True``
+        process_group (ProcessGroup, optional, default=torch.distributed.group.WORLD):
+            process group for sharding
+    """
+
+    def __init__(
+        self,
+        device: str = "cuda",
+        init_scale: float = 2.0**16,
+        backoff_factor: float = 0.5,
+        growth_factor: float = 2.0,
+        growth_interval: int = 2000,
+        enabled: bool = True,
+        process_group: Optional[ProcessGroup] = dist.group.WORLD,
+    ) -> None:
+        super().__init__(
+            device,
+            init_scale=init_scale,
+            backoff_factor=backoff_factor,
+            growth_factor=growth_factor,
+            growth_interval=growth_interval,
+            enabled=enabled,
+        )
+        if self._enabled:
+            self.process_group = process_group
+            self._per_optimizer_states = defaultdict(_refresh_per_optimizer_state)
+
+    @overload
+    def scale(self, outputs: torch.Tensor) -> torch.Tensor:
+        ...
+
+    @overload
+    def scale(self, outputs: List[torch.Tensor]) -> List[torch.Tensor]:
+        ...
+
+    @overload
+    def scale(self, outputs: Tuple[torch.Tensor, ...]) -> Tuple[torch.Tensor, ...]:
+        ...
+
+    @overload
+    def scale(self, outputs: Iterable[torch.Tensor]) -> Iterable[torch.Tensor]:
+        ...
+
+    def scale(
+        self, outputs: Union[torch.Tensor, Iterable[torch.Tensor]]
+    ) -> Union[torch.Tensor, Iterable[torch.Tensor]]:
+        if not self._enabled:
+            return outputs
+
+        if isinstance(outputs, torch.Tensor):
+            assert _is_supported_device(outputs)
+            if self._scale is None:
+                self._lazy_init_scale_growth_tracker(outputs.device)
+            assert self._scale is not None
+            scaled_output = outputs * self._scale.to(
+                device=outputs.device, non_blocking=True
+            )
+            # Here we ensure the return dtype is the same as the outputs dtype.
+            # For the FSDP + Mixed Precision use case, the loss output is in the Mixed Precision
+            # format (fp16, bf16) and so the scaled loss should be of the same dtype.
+            return scaled_output.type(outputs.dtype)
+
+        stash: List[_GeneralMultiDeviceReplicator] = []
+
+        def apply_scale(val: Union[torch.Tensor, Iterable[torch.Tensor]]):
+            if isinstance(val, torch.Tensor):
+                assert _is_supported_device(val)
+                if len(stash) == 0:
+                    if self._scale is None:
+                        self._lazy_init_scale_growth_tracker(val.device)
+                    assert self._scale is not None
+                    stash.append(_GeneralMultiDeviceReplicator(self._scale))
+                scaled_val = val * stash[0].get(val.device)
+                # Here we ensure the return dtype is the same as the outputs dtype.
+                # For the FSDP + Mixed Precision use case, the loss output is in the Mixed Precision
+                # format (fp16, bf16) and so the scaled loss should be of the same dtype.
+                return scaled_val.type(val.dtype)
+            if isinstance(val, abc.Iterable):
+                iterator = map(apply_scale, val)
+                if isinstance(val, (list, tuple)):
+                    return type(val)(iterator)
+                return iterator
+            raise ValueError("outputs must be a Tensor or an iterable of Tensors")
+
+        return apply_scale(outputs)
+
+    def _foreach_non_finite_check_and_unscale_cpu_(
+        self,
+        grads: Sequence[torch.Tensor],
+        found_inf: torch.Tensor,
+        inv_scale: torch.Tensor,
+    ) -> None:
+        if len(grads) == 0:
+            return
+        assert inv_scale.numel() == 1, "inv_scale must be a 1-element tensor."
+        assert found_inf.numel() == 1, "found_inf must be a 1-element tensor."
+
+        for grad in grads:
+            if grad.device.type != "cpu":
+                logger.error(
+                    "tensor device is %s but was expected to be ``cpu``",
+                    grad.device,
+                )
+                raise ValueError(
+                    "Gradients were found on a non-CPU device when"
+                    " expected to be on CPU."
+                )
+            if (
+                torch.isinf(grad).any().item() is True
+                or torch.isnan(grad).any().item() is True
+            ):
+                found_inf.data = torch.tensor([1.0])
+                break
+            else:
+                grad.data *= inv_scale.item()
+
+    def _unscale_grads_(
+        self,
+        optimizer: torch.optim.Optimizer,
+        inv_scale: torch.Tensor,
+        found_inf: torch.Tensor,
+        allow_fp16: bool = True,
+    ) -> Dict[torch.device, torch.Tensor]:
+        per_device_inv_scale = _GeneralMultiDeviceReplicator(inv_scale)
+        per_device_found_inf = _GeneralMultiDeviceReplicator(found_inf)
+
+        # To set up _amp_foreach_non_finite_check_and_unscale_, split grads by device and dtype.
+        # There could be thousands of grads, so we'd like to iterate through them just once.
+        # However, we don't know their devices or dtypes in advance.
+
+        # https://stackoverflow.com/questions/5029934/defaultdict-of-defaultdict
+        # Google says mypy struggles with defaultdicts type annotations.
+        per_device_and_dtype_grads = defaultdict(lambda: defaultdict(list))  # type: ignore[var-annotated]
+        with torch.no_grad():
+            for group in optimizer.param_groups:
+                for param in group["params"]:
+                    if param.grad is None:
+                        continue
+                    if (not allow_fp16) and param.grad.dtype == torch.float16:
+                        raise ValueError("Attempting to unscale FP16 gradients.")
+                    if param.grad.is_sparse:
+                        # is_coalesced() == False means the sparse grad has values with duplicate indices.
+                        # coalesce() deduplicates indices and adds all values that have the same index.
+                        # For scaled fp16 values, there's a good chance coalescing will cause overflow,
+                        # so we should check the coalesced _values().
+                        if param.grad.dtype is torch.float16:
+                            # coalesce is not supported in torch.float16
+                            param_grad_fp32 = param.grad.type(torch.float32).coalesce()
+                            param.grad = param_grad_fp32.type(torch.float16)
+                        to_unscale = param.grad._values()
+                    else:
+                        to_unscale = param.grad
+
+                    per_device_and_dtype_grads[to_unscale.device][
+                        to_unscale.dtype
+                    ].append(to_unscale)
+
+            for device, per_dtype_grads in per_device_and_dtype_grads.items():
+                for grads in per_dtype_grads.values():
+                    if grads[0].device.type == "cpu":
+                        self._foreach_non_finite_check_and_unscale_cpu_(
+                            grads,
+                            per_device_found_inf.get(device),
+                            per_device_inv_scale.get(device),
+                        )
+                    else:
+                        torch._amp_foreach_non_finite_check_and_unscale_(
+                            grads,
+                            per_device_found_inf.get(device),
+                            per_device_inv_scale.get(device),
+                        )
+        # There exist contexts (e.g. w/ `use_orig_params=True`) wherein some
+        # ranks may have no (non-zero sized) parameter shards, necessitating the
+        # initialization of `per_device_found_inf._per_device_tensors` here
+        if not per_device_found_inf._per_device_tensors:
+            assert self._scale is not None
+            per_device_found_inf.get(self._scale.device)
+        return per_device_found_inf._per_device_tensors
+
+    def unscale_(self, optimizer: torch.optim.Optimizer) -> None:
+        if not self._enabled:
+            return
+
+        self._check_scale_growth_tracker("unscale_")
+
+        optimizer_state = self._per_optimizer_states[id(optimizer)]
+
+        if optimizer_state["stage"] is OptState.UNSCALED:
+            raise RuntimeError(
+                "unscale_() has already been called on this optimizer since the last update()."
+            )
+        elif optimizer_state["stage"] is OptState.STEPPED:
+            raise RuntimeError("unscale_() is being called after step().")
+
+        # FP32 division can be imprecise for certain compile options, so we carry out the reciprocal in FP64.
+        assert self._scale is not None
+        inv_scale = self._scale.double().reciprocal().float()
+        found_inf = torch.full(
+            (1,), 0.0, dtype=torch.float32, device=self._scale.device
+        )
+
+        optimizer_state["found_inf_per_device"] = self._unscale_grads_(
+            optimizer, inv_scale, found_inf, True
+        )
+        optimizer_state["stage"] = OptState.UNSCALED
+
+        # Synchronize the detected inf across the ranks
+        optimizer_state = self._per_optimizer_states[id(optimizer)]
+        works = []
+        found_inf_on_cpus = []
+        found_inf_on_devices = []
+
+        for found_inf in optimizer_state["found_inf_per_device"].values():
+            if self._device != "cpu" and found_inf.device.type == "cpu":
+                found_inf_on_cpus.append(found_inf)
+                found_inf_on_device = found_inf.to(self._device)
+                found_inf_on_devices.append(found_inf_on_device)
+                works.append(
+                    dist.all_reduce(
+                        found_inf_on_device, async_op=True, group=self.process_group
+                    )
+                )
+            else:
+                works.append(
+                    dist.all_reduce(found_inf, async_op=True, group=self.process_group)
+                )
+        for work in works:
+            work.wait()
+        if found_inf_on_cpus:
+            torch._foreach_copy_(found_inf_on_cpus, found_inf_on_devices)
+
+    def _amp_update_scale_cpu_(self, found_inf: torch.Tensor) -> None:
+        """
+        If found_inf is 1.0 (True), then scale is multiplied by backoff_factor and growth_tracker is set to zero.
+        Otherwise, scale is multiplied by the growth factor when the growth interval is reached.
+        """
+        assert self._scale is not None and self._growth_tracker is not None
+
+        if found_inf.item() >= 1.0:
+            self._scale *= self._backoff_factor
+            self._growth_tracker.fill_(0)
+        else:
+            successful = self._growth_tracker + 1
+            if successful == self._growth_interval:
+                self._scale *= self._growth_factor
+                self._growth_tracker.fill_(0)
+            else:
+                self._growth_tracker = successful
+
+    def update(self, new_scale: Optional[Union[float, torch.Tensor]] = None) -> None:
+        """
+        Updates the scale factor.
+        If any optimizer steps were skipped the scale is multiplied by ``backoff_factor``
+        to reduce it. If ``growth_interval`` unskipped iterations occurred consecutively,
+        the scale is multiplied by ``growth_factor`` to increase it.
+        Passing ``new_scale`` sets the new scale value manually. (``new_scale`` is not
+        used directly, it's used to fill GradScaler's internal scale tensor. So if
+        ``new_scale`` was a tensor, later in-place changes to that tensor will not further
+        affect the scale GradScaler uses internally.)
+        Args:
+            new_scale (float or :class:`torch.Tensor`, optional, default=None):  New scale factor.
+        .. warning::
+            :meth:`update` should only be called at the end of the iteration, after ``scaler.step(optimizer)`` has
+            been invoked for all optimizers used this iteration.
+        """
+
+        if not self._enabled:
+            return
+
+        _scale, _growth_tracker = self._check_scale_growth_tracker("update")  # type: ignore[var-annotated]
+
+        if new_scale is not None:
+            # Accept a new user-defined scale.
+            if isinstance(new_scale, float):
+                self._scale.fill_(new_scale)  # type: ignore[union-attr]
+            else:
+                reason = "new_scale should be a float or a 1-element torch.cuda.FloatTensor or \
+                    torch.FloatTensor with requires_grad=False."
+                assert new_scale.device.type == self._device, reason
+                assert new_scale.numel() == 1, reason
+                assert new_scale.requires_grad is False, reason
+                self._scale.copy_(new_scale)  # type: ignore[union-attr]
+        else:
+            # Consume shared inf/nan data collected from optimizers to update the scale.
+            # If all found_inf tensors are on the same device as self._scale, this operation is asynchronous.
+            found_infs = [
+                found_inf.to(device=_scale.device, non_blocking=True)
+                for state in self._per_optimizer_states.values()
+                for found_inf in state["found_inf_per_device"].values()
+            ]
+
+            assert len(found_infs) > 0, "No inf checks were recorded prior to update."
+
+            found_inf_combined = found_infs[0]
+            if len(found_infs) > 1:
+                for i in range(1, len(found_infs)):
+                    found_inf_combined += found_infs[i]
+
+            if _scale.device.type == "cpu":
+                self._amp_update_scale_cpu_(found_inf_combined)
+            else:
+                torch._amp_update_scale_(
+                    self._scale,  # type: ignore[arg-type]
+                    self._growth_tracker,  # type: ignore[arg-type]
+                    found_inf_combined,
+                    self._growth_factor,  # type: ignore[arg-type]
+                    self._backoff_factor,  # type: ignore[arg-type]
+                    self._growth_interval,  # type: ignore[arg-type]
+                )
+
+        # To prepare for next iteration, clear the data collected from optimizers this iteration.
+        self._per_optimizer_states = defaultdict(_refresh_per_optimizer_state)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/wrap.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/wrap.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8604bbb1bb048ea9a485fcda6ce33d083a5c1a8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/fsdp/wrap.py
@@ -0,0 +1,608 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Facebook, Inc. and its affiliates.
+#
+# This source code is licensed under the BSD license found in the
+# LICENSE file in the root directory of this source tree.
+
+import contextlib
+import copy
+from abc import ABC, abstractmethod
+from typing import (
+    Any,
+    Callable,
+    cast,
+    Dict,
+    Generator,
+    Iterable,
+    Optional,
+    Sequence,
+    Set,
+    Tuple,
+    Type,
+    Union,
+)
+
+import torch.nn as nn
+
+
+__all__ = [
+    "always_wrap_policy",
+    "lambda_auto_wrap_policy",
+    "transformer_auto_wrap_policy",
+    "size_based_auto_wrap_policy",
+    "enable_wrap",
+    "wrap",
+    "CustomPolicy",
+    "ModuleWrapPolicy",
+]
+
+
+# NOTE: We intentionally keep this function simple and isolate the complexity
+# to `fn` to enable using this function generically. We may move this to a
+# non-FSDP-specific folder and/or make it public in the future.
+def _post_order_apply(
+    root_module: nn.Module,
+    fn: Callable[[nn.Module], Optional[nn.Module]],
+):
+    """
+    This applies ``fn`` to every module in the module tree of ``root_module``
+    following a post-order traversal. If ``fn`` returns an :class:`nn.Module`,
+    then this replaces the original module with the newly returned one in the
+    tree. Otherwise, ``fn`` should return ``None``, in which case the module is
+    not changed.
+    """
+    # Track visited modules to avoid visiting shared modules multiple times
+    visited_modules: Set[nn.Module] = {root_module}
+
+    def _post_order_apply_inner(
+        module: nn.Module,
+        module_name: str,
+        parent_module: Optional[nn.Module],
+    ):
+        for child_module_name, child_module in module.named_children():
+            if child_module not in visited_modules:
+                visited_modules.add(child_module)
+                _post_order_apply_inner(child_module, child_module_name, module)
+        optional_module = fn(module)
+        if optional_module is not None:
+            assert isinstance(parent_module, nn.Module), (
+                "Non-root modules should have their parent module set but got "
+                f"{parent_module} for {module}"
+            )
+            assert module_name, (
+                "Non-root modules should have their module name set but got "
+                f"an empty module name for {module}"
+            )
+            assert isinstance(
+                optional_module, nn.Module
+            ), f"fn should return None or an nn.Module but got {optional_module}"
+            setattr(parent_module, module_name, optional_module)
+
+    _post_order_apply_inner(root_module, "", None)
+
+
+def _construct_wrap_fn(
+    root_module: nn.Module,
+    target_module_to_kwargs: Dict[nn.Module, Dict[str, Any]],
+    fsdp_fn: Callable,
+) -> Callable[[nn.Module], Optional[nn.Module]]:
+    """
+    This constructs the "wrap" function to pass to :func:`_post_order_apply`
+    based on ``target_module_to_kwargs``, which should be constructed from the
+    wrapping policy.
+    """
+
+    def fn(module: nn.Module) -> Optional[nn.Module]:
+        # Explicitly avoid wrapping the root module since for FSDP, it is
+        # handled by the caller
+        if module in target_module_to_kwargs and module is not root_module:
+            kwargs = target_module_to_kwargs[module]
+            return fsdp_fn(module, **kwargs)
+        return None
+
+    return fn
+
+
+def _run_mixed_precision_override_policy(
+    root_module: nn.Module,
+    module_classes: Iterable[Type[nn.Module]],
+    ignored_modules: Set[nn.Module],
+    root_kwargs: Dict[str, Any],
+    target_module_to_kwargs: Dict[nn.Module, Dict[str, Any]],
+):
+    module_classes_tuple = tuple(set(module_classes))
+    for module in root_module.modules():
+        if module in ignored_modules:
+            continue
+        elif isinstance(module, module_classes_tuple):
+            # This policy overrides any existing policy
+            if module not in target_module_to_kwargs:
+                # Only inherit from the root kwargs if not already specified
+                target_module_to_kwargs[module] = root_kwargs
+            target_module_to_kwargs[module]["mixed_precision"] = None
+    return target_module_to_kwargs
+
+
+def always_wrap_policy(*args, **kwargs) -> bool:
+    """
+    A simple recursive wrap policy that always returns ``True``. This means
+    that every submodule is wrapped by the wrapper class in
+    :func:`_recursive_wrap`.
+    """
+    return True
+
+
+class _Policy(ABC):
+    """
+    This defines an abstract base class that represents a policy for applying
+    a module-level API.
+    """
+
+    @abstractmethod
+    def _run_policy(
+        self,
+        root_module: nn.Module,
+        ignored_modules: Set[nn.Module],
+        root_kwargs: Dict[str, Any],
+    ) -> Dict[nn.Module, Dict[str, Any]]:
+        """
+        This should return a dict ``target_module_to_kwargs`` that maps from
+        each target module to wrap to its kwargs.
+        """
+        ...
+
+
+def _module_wrap_policy(
+    module: nn.Module,
+    recurse: bool,
+    nonwrapped_numel: int,
+    module_classes: Set[Type[nn.Module]],
+) -> bool:
+    """
+    This auto wrap policy wraps every module that is an instance of any type in
+    ``module_classes`` as its own FSDP instance. The root module given by
+    ``module`` is always wrapped as an FSDP instance regardless. Since the
+    wrapping proceeds bottom up, each FSDP instance manages the parameters in
+    its subtree excluding any already managed by a child FSDP instance.
+
+    Args:
+        module (nn.Module): Current module being considered.
+        recurse (bool): If ``False``, then this function must decide whether
+            ``module`` should be wrapped as an FSDP instance or not. If
+            ``True``, then the function is still recursing down the module
+            tree as a part of the DFS.
+        nonwrapped_numel (int): Parameter numel not yet wrapped.
+        module_classes (Set[Type[nn.Module]]): Set of module classes that are
+            wrapped as FSDP instances.
+
+    Returns:
+        ``True`` if ``recurse=True``, and whether ``module`` should be wrapped
+        if ``recurse=False``.
+    """
+    if recurse:
+        return True  # always recurse
+    return isinstance(module, tuple(module_classes))
+
+
+class ModuleWrapPolicy(_Policy):
+    """
+    This policy applies to every module of the specified module classes,
+    passing in the kwargs given to the root.
+    """
+
+    def __init__(self, module_classes: Iterable[Type[nn.Module]]):
+        module_classes_set = set(module_classes)
+        self._module_classes = module_classes_set
+        self._module_classes_str = str(module_classes_set)
+
+    def _run_policy(
+        self,
+        root_module: nn.Module,
+        ignored_modules: Set[nn.Module],
+        root_kwargs: Dict[str, Any],
+    ) -> Dict[nn.Module, Dict[str, Any]]:
+        module_classes = tuple(self._module_classes)
+        target_module_to_kwargs: Dict[nn.Module, Dict[str, Any]] = {}
+        for module in root_module.modules():
+            if module in ignored_modules:
+                continue
+            elif isinstance(module, module_classes):
+                # Shallow copy to avoid coupling changes across modules
+                target_module_to_kwargs[module] = copy.copy(root_kwargs)
+        return target_module_to_kwargs
+
+    def __call__(self, module, recurse, *args, **kwargs):
+        # nonwrapped_numel is not used.
+        return _module_wrap_policy(
+            module, recurse, nonwrapped_numel=-1, module_classes=self._module_classes
+        )
+
+    def __repr__(self) -> str:
+        return super().__repr__() + f"({self._module_classes_str})"
+
+
+class CustomPolicy(_Policy):
+    """
+    This policy takes in a lambda function that maps a given ``nn.Module`` to
+    either ``False``, ``True``, or a kwarg dictionary.
+    - If the function returns ``False`` or an empty dictionary, then the module
+      does not have the API applied.
+    - If the function returns ``True``, then the module has the API applied
+      with the root's kwargs.
+    - If the function returns a non-empty dictionary, then the module has the
+      API applied, and the dictionary overrides the root's kwargs.
+
+    Example::
+
+        >>> # xdoctest: +SKIP("undefined variables")
+        >>> model = init_transformer_model(...)
+        >>> def lambda_fn(module: nn.Module):
+        >>>     if module is model.lm_head:
+        >>>         return {"sharding_strategy": ShardingStrategy.SHARD_GRAD_OP}
+        >>>     elif isinstance(module, TransformerBlock):
+        >>>         return True
+        >>>     return False
+        >>> policy = CustomPolicy(lambda_fn)
+        >>> fsdp_model = FSDP(model, auto_wrap_policy=policy)
+    """
+
+    def __init__(self, lambda_fn: Callable[[nn.Module], Union[bool, Dict[str, Any]]]):
+        self._lambda_fn = lambda_fn
+
+    def _run_policy(
+        self,
+        root_module: nn.Module,
+        ignored_modules: Set[nn.Module],
+        root_kwargs: Dict[str, Any],
+    ) -> Dict[nn.Module, Dict[str, Any]]:
+        target_module_to_kwargs: Dict[nn.Module, Dict[str, Any]] = {}
+        for module in root_module.modules():
+            if module in ignored_modules:
+                continue
+            res = self._lambda_fn(module)
+            if not isinstance(res, (dict, bool)):
+                raise ValueError(
+                    "The lambda_fn passed to CustomPolicy should return "
+                    f"False/True or a kwarg dict, but it returned {res}"
+                )
+            if not res:
+                continue
+            kwargs = copy.copy(root_kwargs)
+            if isinstance(res, dict):
+                # Override the root kwargs with the ones specified by the
+                # lambda function
+                kwargs.update(res)
+            target_module_to_kwargs[module] = kwargs
+        return target_module_to_kwargs
+
+
+def lambda_auto_wrap_policy(
+    module: nn.Module, recurse: bool, nonwrapped_numel: int, lambda_fn: Callable
+) -> bool:
+    """
+    A convenient auto wrap policy to wrap submodules based on an arbitrary user
+    function. If `lambda_fn(submodule) == True``, the submodule will be wrapped as
+    a `wrapper_cls` unit.
+
+    Return if a module should be wrapped during auto wrapping.
+
+    The first three parameters are required by :func:`_recursive_wrap`.
+
+    Args:
+        module (nn.Module): Current module being considered.
+        recurse (bool): If ``False``, then this function must decide whether
+            ``module`` should be wrapped as an FSDP instance or not. If
+            ``True``, then the function is still recursing down the module
+            tree as a part of the DFS.
+        nonwrapped_numel (int): Parameter numel not yet wrapped.
+
+        lambda_fn (Callable[[nn.Module], bool]): If this returns ``True``, then
+            this module will be wrapped.
+    """
+    if recurse:
+        return True  # always recurse
+    return lambda_fn(module)
+
+
+def transformer_auto_wrap_policy(
+    module: nn.Module,
+    recurse: bool,
+    nonwrapped_numel: int,
+    transformer_layer_cls: Set[Type[nn.Module]],
+) -> bool:
+    """
+    See :func:`_module_wrap_policy`, where ``transformer_layer_cls`` is the
+    same as ``module_classes``. Note that shared parameters must be wrapped in
+    the same FSDP instance, so this auto wrap policy can help wrap shared
+    embeddings into the same FSDP instance for transformer models.
+    """
+    return _module_wrap_policy(module, recurse, nonwrapped_numel, transformer_layer_cls)
+
+
+def _wrap_module_cls_individually(
+    module: nn.Module, module_classes: Sequence[type], recurse: bool, *args, **kwargs
+):
+    if recurse:
+        # always recurse
+        return True
+    else:
+        # if not recursing, decide whether we should wrap based on whether the type of module
+        # is in `module_classes`.
+        return isinstance(module, tuple(module_classes))
+
+
+def _or_policy(
+    module: nn.Module,
+    recurse: bool,
+    nonwrapped_numel: int,
+    policies,
+) -> bool:
+    """
+    A policy that wraps ``module`` if any policy in the passed in iterable of
+    ``policies`` returns ``True``.
+    """
+    return any(
+        policy(module=module, recurse=recurse, nonwrapped_numel=nonwrapped_numel)
+        for policy in policies
+    )
+
+
+def size_based_auto_wrap_policy(
+    module: nn.Module,
+    recurse: bool,
+    nonwrapped_numel: int,
+    # Additional custom arguments
+    min_num_params: int = int(1e8),
+    force_leaf_modules: Optional[Set[Type[nn.Module]]] = None,
+    exclude_wrap_modules: Optional[Set[Type[nn.Module]]] = None,
+) -> bool:
+    """
+    A size-based auto wrap policy.
+
+    Args:
+        module (nn.Module): Current module being considered.
+        recurse (bool): If ``False``, then this function must decide whether
+            ``module`` should be wrapped as an FSDP instance or not. If
+            ``True``, then the function is still recursing down the module
+            tree as a part of the DFS.
+        nonwrapped_numel (int): Parameter numel not yet wrapped.
+
+        min_num_params (int): Customizable policy input that controls the size
+            threshold over which a module is ready to be wrapped. This is in
+            units of numel.
+        force_leaf_modules (Set[Type[nn.Module]]): Set of module types to keep
+            as leaves, i.e. their children will never be wrapped.
+        exclude_wrap_modules (Set[Type[nn.Module]]): Set of module types to be
+            excluded in wrapping.
+
+    Returns:
+        Whether ``module`` should be wrapped.
+    """
+    force_leaf_modules = (
+        size_based_auto_wrap_policy.FORCE_LEAF_MODULES  # type: ignore[attr-defined]
+        if force_leaf_modules is None
+        else force_leaf_modules
+    )
+    exclude_wrap_modules = (
+        size_based_auto_wrap_policy.EXCLUDE_WRAP_MODULES  # type: ignore[attr-defined]
+        if exclude_wrap_modules is None
+        else exclude_wrap_modules
+    )
+
+    # Keep the argument `min_num_params` for BC for now, but it represents the
+    # minimum non-wrapped *numel* before triggering a wrapping
+    min_nonwrapped_numel = min_num_params
+    is_large = nonwrapped_numel >= min_nonwrapped_numel
+    if recurse:
+        # We should recurse if the module is big enough but not in force_leaf_modules list.
+        return is_large and not isinstance(module, tuple(force_leaf_modules))
+    else:
+        # If we are not recursing, determine if we should wrap.
+        return is_large and not isinstance(module, tuple(exclude_wrap_modules))
+
+
+# Set those defaults to the size_based_auto_wrap_policy function. Make them easy to be imported.
+size_based_auto_wrap_policy.EXCLUDE_WRAP_MODULES = {nn.ModuleList, nn.ModuleDict}  # type: ignore[attr-defined]
+size_based_auto_wrap_policy.FORCE_LEAF_MODULES = {nn.MultiheadAttention}  # type: ignore[attr-defined]
+
+
+@contextlib.contextmanager
+def enable_wrap(
+    *, wrapper_cls: Any, **wrapper_kwargs: Any
+) -> Generator[None, None, None]:
+    """
+    Context manager to wrap modules using a wrapper.
+
+    Useful for when you'd like to apply the same configuration arguments to all
+    child modules that you wrap. A particularly important use case is wrapping
+    large layers so that they get sharded (in-place) during initialization, to
+    avoid running out of system memory. Large layers can indicate that they
+    should be sharded via the ``wrap`` annotation and this context manager can
+    provide the exact configuration for these nested instances.
+
+    Usage::
+
+        with enable_wrap(wrapper_cls, **params):
+            # Wraps layer in FSDP by default if within context
+            self.l1 = wrap(torch.nn.Linear(5, 5))
+
+    Args:
+        wrapper_cls:
+            Class that `wrap` annotation will `wrap` modules with, such as
+            `FullyShardedDataParallel`.
+        **wrapper_kwargs:
+            Configuration settings that will be passed to all ``wrap``
+            instances inside the context
+    """
+    kwargs = {
+        "wrapper_cls": wrapper_cls,
+        **wrapper_kwargs,
+    }
+    with _ConfigAutoWrap(**kwargs):
+        yield
+
+
+def wrap(module: nn.Module, **wrap_overrides: Any) -> nn.Module:
+    """
+    Annotate that a module should be wrapped. Annotated modules will only be
+    wrapped if inside of an :func:`enable_wrap` context manager. This allows
+    a module to be initialized both with and without a wrapper without code
+    change.
+
+    The class that this function wraps the passed in ``nn.Module`` with is the
+    passed in ``wrapper_cls`` argument into ``enable_wrap``. Both
+    ``enable_wrap`` and ``wrap`` can take in kwargs specifying how to construct
+    the ``wrapper_cls`` instance. In the case of duplicate kwargs in
+    ``enable_wrap`` and ``wrap``, the argument passed into ``wrap`` will be
+    respected.
+
+    Usage::
+
+        with enable_wrap(wrapper_cls=FSDP, **fsdp_config):
+            # Wraps layer in FSDP by default if within context
+            self.l1 = wrap(torch.nn.Linear(5, 5))
+
+    Args:
+        module (nn.Module): module to wrap (if in :func:`enable_wrap` context)
+        **wrap_overrides: configuration overrides that will take priority over
+            the values provided by the :func:`enable_wrap` context
+    """
+    if _ConfigAutoWrap.in_autowrap_context:
+        assert _ConfigAutoWrap.wrapper_cls is not None
+
+        wrap_overrides = {**_ConfigAutoWrap.kwargs, **wrap_overrides}
+        return _wrap(
+            module,
+            _ConfigAutoWrap.wrapper_cls,
+            **wrap_overrides,
+        )
+    return module
+
+
+def _wrap(module: nn.Module, wrapper_cls: Callable, **kwargs) -> nn.Module:
+    assert wrapper_cls is not None
+    if hasattr(module, "_wrap_overrides"):
+        # If module has a _wrap_overrides attribute, we force overriding the
+        # FSDP config with these attributes for this module. Currently this
+        # is only used to disable mixed precision for BatchNorm when
+        # auto_wrapping.
+        overrides = {**kwargs, **module._wrap_overrides}  # type: ignore[arg-type]
+        return wrapper_cls(module, **overrides)
+
+    return wrapper_cls(module, **kwargs)
+
+
+def _recursive_wrap(
+    module: nn.Module,
+    auto_wrap_policy: Callable,
+    wrapper_cls: Callable,
+    ignored_modules: Set[nn.Module],
+    ignored_params: Set[nn.Parameter],
+    only_wrap_children: bool = False,
+    **kwargs: Any,
+) -> Tuple[nn.Module, int]:
+    """
+    Wraps submodules of ``module`` for which ``auto_wrap_policy`` returns
+    ``True`` with ``wrapper_cls``.
+
+    Args:
+        module (nn.Module): Module to recursively wrap.
+        auto_wrap_policy (Callable): A callable representing a policy that
+            determines which modules to recursively wrap with ``wrapper_cls``.
+        ignored_modules (Set[torch.nn.Module]): Modules to ignore when
+            wrapping.
+        ignored_params (Set[torch.nn.Parameter]): Parameters to ignore when
+            wrapping; these should be the parameters contained in the modules
+            in ``ignored_modules``.
+    Returns:
+        (nn.Module, int):
+            ``module`` after wrapping and the numel recursively wrapped.
+    """
+    assert auto_wrap_policy is not None, "Must specify auto_wrap_policy."
+    assert wrapper_cls is not None, "Must specify wrapper_cls"
+    # Make sure no child is already wrapped.
+    for _, child in module.named_modules():
+        if child in ignored_modules:
+            continue
+        try:
+            assert not isinstance(child, cast(type, wrapper_cls))
+        except TypeError:
+            # wrapper_cls is a function as opposed to a class type, just bypass above check.
+            pass
+
+    # We count all params, assuming none of them are already wrapped.
+    nonwrapped_numel = sum(
+        p.numel() for p in module.parameters() if p not in ignored_params
+    )
+
+    assert auto_wrap_policy is not None
+    if auto_wrap_policy(module=module, recurse=True, nonwrapped_numel=nonwrapped_numel):
+        total_wrapped_numel = 0
+        # Iterate through the children, recursively wrap if necessary
+        for name, child in module.named_children():
+            if child in ignored_modules:
+                continue
+            wrapped_child, num_wrapped_params = _recursive_wrap(
+                module=child,
+                auto_wrap_policy=auto_wrap_policy,
+                wrapper_cls=wrapper_cls,
+                ignored_modules=ignored_modules,
+                ignored_params=ignored_params,
+                **kwargs,
+            )
+            setattr(module, name, wrapped_child)
+            # Keep track of how many parameters have been wrapped
+            total_wrapped_numel += num_wrapped_params
+        # decide if we need to wrap the current module,
+        # since the left over parameters exceed the number of params to wrap
+        remainder = nonwrapped_numel - total_wrapped_numel
+        if not only_wrap_children and auto_wrap_policy(
+            module=module, recurse=False, nonwrapped_numel=remainder
+        ):
+            # Leaf node or final wrapping of the remainder both happen here.
+            return _wrap(module, wrapper_cls, **kwargs), nonwrapped_numel
+        else:
+            return module, total_wrapped_numel
+    return module, 0
+
+
+class _ConfigAutoWrap:
+    """
+    Helper class to wrap modules based on default config args via a context manager.
+    See :func:`enable_wrap` for more information.
+    """
+
+    in_autowrap_context: bool = False  # Context flag
+    wrapper_cls: Optional[Callable] = None  # The wrapper class
+    kwargs: Dict[str, Any] = {}  # Wrapper's args
+
+    def __init__(self, **kwargs: Dict[str, Any]):
+        self.kwargs = kwargs
+
+    @staticmethod
+    def enable_autowrap_context(kwargs: Any) -> None:
+        if _ConfigAutoWrap.in_autowrap_context:
+            raise NotImplementedError(
+                "You are already within an autowrap context and we currently do not supported nested autowrap."
+            )
+        _ConfigAutoWrap.in_autowrap_context = True
+        # Get and save the wrapper cls for the context.
+        assert (
+            "wrapper_cls" in kwargs.keys()
+        ), "Expected to pass in wrapper_cls arg into _ConfigAutoWrap."
+        _ConfigAutoWrap.wrapper_cls = cast(Callable, kwargs["wrapper_cls"])
+        del kwargs["wrapper_cls"]
+        # Save the rest.
+        _ConfigAutoWrap.kwargs = kwargs
+
+    @staticmethod
+    def disable_autowrap_context() -> None:
+        _ConfigAutoWrap.in_autowrap_context = False
+        _ConfigAutoWrap.wrapper_cls = None
+        _ConfigAutoWrap.kwargs = {}
+
+    def __enter__(self) -> None:
+        self.enable_autowrap_context(self.kwargs)
+
+    def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
+        self.disable_autowrap_context()
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/launcher/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/launcher/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb744a2b93615b703eb0dafb7c8e6c71bc1ad5d2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/launcher/__init__.py
@@ -0,0 +1,14 @@
+#!/usr/bin/env/python3
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+
+from torch.distributed.launcher.api import (  # noqa: F401
+    elastic_launch,
+    launch_agent,
+    LaunchConfig,
+)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/launcher/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/launcher/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ddb2fc172dd779e238295767d594321697c6227c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/launcher/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/launcher/__pycache__/api.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/launcher/__pycache__/api.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..60d32678446d6265852538910c96372b04724936
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/launcher/__pycache__/api.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/launcher/api.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/launcher/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3bcd4073c9bafab05668e8f91acdc181001a0d2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/launcher/api.py
@@ -0,0 +1,289 @@
+#!/usr/bin/env python3
+# mypy: allow-untyped-defs
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+import sys
+import uuid
+from dataclasses import dataclass, field
+from typing import Any, Callable, Dict, List, Optional, Tuple, Union
+
+import torch.distributed.elastic.rendezvous.registry as rdzv_registry
+from torch.distributed.elastic import events, metrics
+from torch.distributed.elastic.agent.server.api import WorkerSpec
+from torch.distributed.elastic.agent.server.local_elastic_agent import LocalElasticAgent
+from torch.distributed.elastic.multiprocessing import (
+    DefaultLogsSpecs,
+    LogsSpecs,
+    SignalException,
+)
+from torch.distributed.elastic.multiprocessing.errors import ChildFailedError
+from torch.distributed.elastic.rendezvous import RendezvousParameters
+from torch.distributed.elastic.rendezvous.utils import parse_rendezvous_endpoint
+from torch.distributed.elastic.utils.logging import get_logger
+
+
+__all__ = ["LaunchConfig", "elastic_launch", "launch_agent"]
+
+logger = get_logger(__name__)
+
+
+@dataclass
+class LaunchConfig:
+    """
+    Creates a rendezvous config.
+
+    Args:
+        min_nodes: Minimum amount of nodes that the user function will
+                        be launched on. Elastic agent ensures that the user
+                        function start only when the min_nodes amount enters
+                        the rendezvous.
+        max_nodes: Maximum amount of nodes that the user function
+                        will be launched on.
+        nproc_per_node: On each node the elastic agent will launch
+                            this amount of workers that will execute user
+                            defined function.
+        rdzv_backend: rdzv_backend to use in the rendezvous (zeus-adapter, etcd).
+        rdzv_endpoint: The endpoint of the rdzv sync. storage.
+        rdzv_configs: Key, value pair that specifies rendezvous specific configuration.
+        rdzv_timeout: Legacy argument that specifies timeout for the rendezvous. It is going
+            to be removed in future versions, see the note below. The default timeout is 900 seconds.
+        run_id: The unique run id of the job (if not passed a unique one will be
+                deduced from run environment - flow workflow id in flow - or auto generated).
+        role: User defined role of the worker (defaults to "trainer").
+        max_restarts: The maximum amount of restarts that elastic agent will conduct
+                    on workers before failure.
+        monitor_interval: The interval in seconds that is used by the elastic_agent
+                        as a period of monitoring workers.
+        start_method: The method is used by the elastic agent to start the
+                    workers (spawn, fork, forkserver).
+        metrics_cfg: configuration to initialize metrics.
+        local_addr: address of the local node if any. If not set, a lookup on the local
+                machine's FQDN will be performed.
+        local_ranks_filter: ranks for which to show logs in console. If not set, show from all.
+    ..note:
+        `rdzv_timeout` is a legacy argument that will be removed in future.
+        Set the timeout via `rdzv_configs['timeout']`
+
+    """
+
+    min_nodes: int
+    max_nodes: int
+    nproc_per_node: int
+    logs_specs: Optional[LogsSpecs] = None
+    run_id: str = ""
+    role: str = "default_role"
+    rdzv_endpoint: str = ""
+    rdzv_backend: str = "etcd"
+    rdzv_configs: Dict[str, Any] = field(default_factory=dict)
+    rdzv_timeout: int = -1
+    max_restarts: int = 3
+    monitor_interval: float = 0.1
+    start_method: str = "spawn"
+    log_line_prefix_template: Optional[str] = None
+    metrics_cfg: Dict[str, str] = field(default_factory=dict)
+    local_addr: Optional[str] = None
+
+    def __post_init__(self):
+        default_timeout = 900
+        if self.rdzv_timeout != -1:
+            self.rdzv_configs["timeout"] = self.rdzv_timeout
+        elif "timeout" not in self.rdzv_configs:
+            self.rdzv_configs["timeout"] = default_timeout
+
+        # Post-processing to enable refactoring to introduce logs_specs due to non-torchrun API usage
+        if self.logs_specs is None:
+            self.logs_specs = DefaultLogsSpecs()
+
+
+class elastic_launch:
+    """
+    Launches an torchelastic agent on the container that invoked the entrypoint.
+
+        1. Pass the ``entrypoint`` arguments as non ``kwargs`` (e.g. no named parameters)/
+           ``entrypoint`` can be a function or a command.
+        2. The return value is a map of each worker's output mapped
+           by their respective global rank.
+
+    Usage
+
+    ::
+
+    def worker_fn(foo):
+        # ...
+
+    def main():
+        # entrypoint is a function.
+        outputs = elastic_launch(LaunchConfig, worker_fn)(foo)
+        # return rank 0's output
+        return outputs[0]
+
+        # entrypoint is a command and ``script.py`` is the python module.
+        outputs = elastic_launch(LaunchConfig, "script.py")(args)
+        outputs = elastic_launch(LaunchConfig, "python")("script.py")
+    """
+
+    def __init__(
+        self,
+        config: LaunchConfig,
+        entrypoint: Union[Callable, str, None],
+    ):
+        self._config = config
+        self._entrypoint = entrypoint
+
+    def __call__(self, *args):
+        return launch_agent(self._config, self._entrypoint, list(args))
+
+
+def _get_entrypoint_name(
+    entrypoint: Union[Callable, str, None], args: List[Any]
+) -> str:
+    """Retrieve entrypoint name with the rule:
+    1. If entrypoint is a function, use ``entrypoint.__qualname__``.
+    2. If entrypoint is a string, check its value:
+        2.1 if entrypoint equals to ``sys.executable`` (like "python"), use the first element from ``args``
+            which does not start with hifen letter (for example, "-u" will be skipped).
+        2.2 otherwise, use ``entrypoint`` value.
+    3. Otherwise, return empty string.
+    """
+    if isinstance(entrypoint, Callable):  # type: ignore[arg-type]
+        return entrypoint.__name__  # type: ignore[union-attr]
+    elif isinstance(entrypoint, str):
+        if entrypoint == sys.executable:
+            return next((arg for arg in args if arg[0] != "-"), "")
+        else:
+            return entrypoint
+    else:
+        return ""
+
+
+def _get_addr_and_port(
+    rdzv_parameters: RendezvousParameters,
+) -> Tuple[Optional[str], Optional[int]]:
+    if rdzv_parameters.backend != "static":
+        return (None, None)
+    endpoint = rdzv_parameters.endpoint
+    endpoint = endpoint.strip()
+    if not endpoint:
+        raise ValueError(
+            "Endpoint is missing in endpoint. Try to add --master-addr and --master-port"
+        )
+    master_addr, master_port = parse_rendezvous_endpoint(endpoint, default_port=-1)
+    if master_port == -1:
+        raise ValueError(
+            f"port is missing in endpoint: {endpoint}. Try to specify --master-port"
+        )
+    return (master_addr, master_port)
+
+
+def launch_agent(
+    config: LaunchConfig,
+    entrypoint: Union[Callable, str, None],
+    args: List[Any],
+) -> Dict[int, Any]:
+    if not config.run_id:
+        run_id = str(uuid.uuid4().int)
+        logger.warning("config has no run_id, generated a random run_id: %s", run_id)
+        config.run_id = run_id
+
+    entrypoint_name = _get_entrypoint_name(entrypoint, args)
+
+    logger.info(
+        "Starting elastic_operator with launch configs:\n"
+        "  entrypoint       : %(entrypoint)s\n"
+        "  min_nodes        : %(min_nodes)s\n"
+        "  max_nodes        : %(max_nodes)s\n"
+        "  nproc_per_node   : %(nproc_per_node)s\n"
+        "  run_id           : %(run_id)s\n"
+        "  rdzv_backend     : %(rdzv_backend)s\n"
+        "  rdzv_endpoint    : %(rdzv_endpoint)s\n"
+        "  rdzv_configs     : %(rdzv_configs)s\n"
+        "  max_restarts     : %(max_restarts)s\n"
+        "  monitor_interval : %(monitor_interval)s\n"
+        "  log_dir          : %(log_dir)s\n"
+        "  metrics_cfg      : %(metrics_cfg)s\n",
+        {
+            "entrypoint": entrypoint_name,
+            "min_nodes": config.min_nodes,
+            "max_nodes": config.max_nodes,
+            "nproc_per_node": config.nproc_per_node,
+            "run_id": config.run_id,
+            "rdzv_backend": config.rdzv_backend,
+            "rdzv_endpoint": config.rdzv_endpoint,
+            "rdzv_configs": config.rdzv_configs,
+            "max_restarts": config.max_restarts,
+            "monitor_interval": config.monitor_interval,
+            "log_dir": config.logs_specs.root_log_dir,  # type: ignore[union-attr]
+            "metrics_cfg": config.metrics_cfg,
+        },
+    )
+
+    rdzv_parameters = RendezvousParameters(
+        backend=config.rdzv_backend,
+        endpoint=config.rdzv_endpoint,
+        run_id=config.run_id,
+        min_nodes=config.min_nodes,
+        max_nodes=config.max_nodes,
+        local_addr=config.local_addr,
+        **config.rdzv_configs,
+    )
+
+    master_addr, master_port = _get_addr_and_port(rdzv_parameters)
+
+    spec = WorkerSpec(
+        role=config.role,
+        local_world_size=config.nproc_per_node,
+        entrypoint=entrypoint,
+        args=tuple(args),
+        rdzv_handler=rdzv_registry.get_rendezvous_handler(rdzv_parameters),
+        max_restarts=config.max_restarts,
+        monitor_interval=config.monitor_interval,
+        master_addr=master_addr,
+        master_port=master_port,
+        local_addr=config.local_addr,
+    )
+
+    agent = LocalElasticAgent(
+        spec=spec,
+        logs_specs=config.logs_specs,  # type: ignore[arg-type]
+        start_method=config.start_method,
+        log_line_prefix_template=config.log_line_prefix_template,
+    )
+
+    shutdown_rdzv = True
+    try:
+        metrics.initialize_metrics(metrics.MetricsConfig(config.metrics_cfg))
+
+        result = agent.run()
+        # records that agent.run() has succeeded NOT that workers have succeeded
+        events.record(agent.get_event_succeeded())
+
+        if result.is_failed():
+            # ChildFailedError is treated specially by @record
+            # if the error files for the failed children exist
+            # @record will copy the first error (root cause)
+            # to the error file of the launcher process.
+            raise ChildFailedError(
+                name=entrypoint_name,
+                failures=result.failures,
+            )
+
+        return result.return_values
+    except ChildFailedError:
+        raise
+    except SignalException:
+        # when the agent dies with a signal do NOT shutdown the rdzv_handler
+        # since this closes the rendezvous on this rdzv_id permanently and
+        # prevents any additional scaling events
+        shutdown_rdzv = False
+        events.record(agent.get_event_failed())
+        raise
+    except Exception:
+        events.record(agent.get_event_failed())
+        raise
+    finally:
+        if shutdown_rdzv:
+            spec.rdzv_handler.shutdown()
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e15fb517052e4aefeb7377d1f0ca63cf2b2da753
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/__init__.py
@@ -0,0 +1,7 @@
+import torch
+
+from .functional import *  # noqa: F403
+
+
+if torch.distributed.rpc.is_available():
+    from .api.remote_module import RemoteModule
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..13027c10d0008d5a1b96a08ceaea84356dab8289
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/__pycache__/functional.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/__pycache__/functional.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..90293b19287504a3e7b2f8e7ced3549de9782446
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/__pycache__/functional.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/api/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/api/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/api/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/api/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..232310c76f5fe4a6fbdb5c69bf2efc01014d111b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/api/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/api/__pycache__/remote_module.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/api/__pycache__/remote_module.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a246cf90edb937d06d068e05e6a4dbcb5753d3a8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/api/__pycache__/remote_module.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/api/remote_module.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/api/remote_module.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e18fe3245e183d49bba8e9b862ae8c3fe7402dc
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/api/remote_module.py
@@ -0,0 +1,762 @@
+#!/usr/bin/python3
+# mypy: allow-untyped-defs
+import collections
+import io
+import sys
+import types
+from typing import (
+    Any,
+    Callable,
+    Dict,
+    Iterator,
+    List,
+    Mapping,
+    Optional,
+    Set,
+    Tuple,
+    Type,
+    TypeVar,
+    Union,
+)
+
+import torch
+import torch.distributed.rpc as rpc
+from torch import device, dtype, nn, Tensor
+from torch.distributed import _remote_device
+from torch.distributed.nn.jit import instantiator
+from torch.distributed.rpc.internal import _internal_rpc_pickler
+from torch.nn import Module
+from torch.nn.parameter import Parameter
+from torch.utils.hooks import RemovableHandle
+
+
+__all__ = ["RemoteModule"]
+
+_grad_t = Union[Tuple[Tensor, ...], Tensor]
+# See https://mypy.readthedocs.io/en/latest/generics.html#generic-methods-and-generic-self for the use
+# of `T` to annotate `self`. Many methods of `Module` return `self` and we want those return values to be
+# the type of the subclass, not the looser type of `Module`.
+T = TypeVar("T", bound="Module")
+
+_NON_SCRIPTABLE_REMOTE_MODULE_MODULE = (
+    instantiator.instantiate_non_scriptable_remote_module_template()
+)
+
+_REMOTE_MODULE_PICKLED_ATTRIBUTES = (
+    "on",
+    "device",
+    "is_device_map_set",
+    "is_scriptable",
+    "generated_methods",
+    "module_rref",
+)
+
+_SerializedRemoteModule = collections.namedtuple("_SerializedRemoteModule", _REMOTE_MODULE_PICKLED_ATTRIBUTES)  # type: ignore[misc]
+
+# These attributes are mostly from RemoteModule's parent class and are intentionally not pickled.
+# A new attribute of RemoteModule should be either in _REMOTE_MODULE_PICKLED_ATTRIBUTES
+# or _REMOTE_MODULE_ATTRIBUTES_IGNORE_FOR_PICKLING.
+# Otherwise, it will not be pickled.
+_REMOTE_MODULE_ATTRIBUTES_IGNORE_FOR_PICKLING = (
+    "training",
+    "_parameters",
+    "_buffers",
+    "_non_persistent_buffers_set",
+    "_backward_hooks",
+    "_backward_pre_hooks",
+    "_is_full_backward_hook",
+    "_forward_hooks",
+    "_forward_hooks_with_kwargs",
+    "_forward_hooks_always_called",
+    "_forward_pre_hooks",
+    "_forward_pre_hooks_with_kwargs",
+    "_state_dict_hooks",
+    "_state_dict_pre_hooks",
+    "_load_state_dict_pre_hooks",
+    "_load_state_dict_post_hooks",
+    "_state_dict_pre_hooks",
+    "_modules",
+    # The two attributes below are generated methods, not available at pickling time.
+    "forward_async",
+    "forward",
+)
+
+
+# RPC handler.
+def _instantiate_template(module_interface_cls, enable_moving_cpu_tensors_to_cuda):
+    instantiator.instantiate_scriptable_remote_module_template(
+        module_interface_cls, enable_moving_cpu_tensors_to_cuda
+    )
+
+
+def _create_module(module_cls, args, kwargs, device):
+    module = module_cls(*args, **kwargs)
+    if not isinstance(module, nn.Module):
+        raise ValueError(
+            "Expect `module_cls(*args, **kwargs)` returns an instance of , "
+            f"but it returns an instance of {type(module)}."
+        )
+    module.to(device)
+    return module
+
+
+def _create_module_with_interface(
+    module_cls, args, kwargs, device, module_interface_cls
+):
+    module = _create_module(module_cls, args, kwargs, device)
+    if module_interface_cls is not None:
+        module = torch.jit.script(module)
+    return rpc.RRef(module, module_interface_cls)
+
+
+def _param_rrefs(module_rref, recurse) -> List[rpc.RRef[Parameter]]:
+    ret: List[rpc.RRef[Parameter]] = []
+    for param in module_rref.local_value().parameters(recurse):
+        ret.append(rpc.RRef(param))
+    return ret
+
+
+def _raise_not_supported(name: str) -> None:
+    raise ValueError(f"Method ``{name}`` not supported for RemoteModule")
+
+
+class _RemoteModule(nn.Module):
+    def __new__(cls, *args, **kwargs):
+        # Use __new__ for logging purposes.
+        torch._C._log_api_usage_once("torch.distributed.nn.api.remote_module")
+        return super().__new__(cls)
+
+    def __init__(
+        self,
+        remote_device: str,
+        module_cls: Type[nn.Module],
+        args: Optional[Tuple] = None,
+        kwargs: Optional[Dict[str, Any]] = None,
+        _module_interface_cls: Any = None,
+    ):
+        """
+        RemoteModule instance can only be created after RPC initialization.
+
+        It creates a user-specified module on a specified remote node.
+        It behaves like a regular ``nn.Module`` except that the ``forward`` method is
+        executed on the remote node.
+        It takes care of autograd recording to ensure the backward pass propagates
+        gradients back to the corresponding remote module.
+        It can be shared across processors using `RPC framework `__,
+        without incurring any overheads of copying the actual module,
+        which is equivalent to an :class:`~torch.distributed.rpc.RRef`
+        pointing to the remote module.
+
+        The arguments of ``forward_async`` and ``forward`` are the same as
+        the ``forward`` method of the module returned by the ``module_cls``.
+
+        Apart from ``forward_async`` and ``forward``, no other methods are supported from nn.Module for now.
+
+        Particularly, to create a hybrid model, typically the local modules should be
+        created outside of remote modules, rather than as submodules of any remote module (by calling ``add_module``).
+        Hybrid Example:
+                >>> class HybridModel(nn.Module):
+                >>>     def __init__(self) -> None:
+                >>>         nn.Module.__init__(self)
+                >>>         self.remote_embedding = RemoteModule(...)
+                >>>         self.local_linear = nn.Linear(...)
+
+        For example, if ``module_cls`` returns an instance of ``nn.Linear``,
+        that has ``forward`` method signature, ``def forward(input: Tensor) -> Tensor:``,
+        the generated ``RemoteModule`` will have 2 methods in signature of
+        ``def forward(input: Tensor) -> Tensor:`` and
+        ``def forward_async(input: Tensor) -> Future[Tensor]:``.
+
+        .. note::
+            If the remote module is placed on a cuda device,
+            any input CPU tensors will be automatically moved to the same cuda device,
+            and GPU tensors are returned over the wire according to the device map of the remote worker on TensorPipe RPC backend.
+
+        Args:
+            remote_device (str): Device on the destination worker where we'd like to place this module.
+                The device can be a local device or a remote device specified by one of the following remote
+                formats:
+
+                    1. "rank:/" (ex: "rank:0/cuda:0").
+                    2. "/" (ex: "trainer0/cuda:0").
+
+                In addition, the device field can be optional and the default value is "cpu".
+            module_cls (nn.Module): For example,
+                >>> class MyModule(nn.Module):
+                >>>     def forward(input):
+                >>>         return input + 1
+                >>>
+                >>> module_cls = MyModule
+            args (Sequence, optional): args to be passed to ``module_cls``.
+            kwargs (Dict, optional): kwargs to be passed to ``module_cls``.
+            _module_interface_cls (type, optional): The TorchScript interface type for the module
+                to be created. The type object should be decorated by @torch.jit.interface.
+                If not provided, the generated RemoteModule is not torchscript-able.
+                Warning, this is an experimental API and susceptible to frequent changes.
+
+        Returns:
+            A remote module instance which wraps the :class:`~nn.Module` created by the
+            user-provided ``module_cls``, it has a blocking ``forward`` method and an
+            asynchronous ``forward_async`` method that returns a future of the ``forward`` call
+            on the user-provided module on the remote side.
+
+        Example::
+            Run the following code in two different processes:
+
+            >>> # xdoctest: +SKIP("distributed")
+            >>> # On worker 0:
+            >>> import torch
+            >>> import torch.distributed.rpc as rpc
+            >>> from torch import nn, Tensor
+            >>> from torch.distributed.nn.api.remote_module import RemoteModule
+            >>>
+            >>> rpc.init_rpc("worker0", rank=0, world_size=2)
+            >>> remote_linear_module = RemoteModule(
+            >>>     "worker1/cpu", nn.Linear, args=(20, 30),
+            >>> )
+            >>> input = torch.randn(128, 20)
+            >>> ret_fut = remote_linear_module.forward_async(input)
+            >>> ret = ret_fut.wait()
+            >>> rpc.shutdown()
+
+            >>> # On worker 1:
+            >>> import torch
+            >>> import torch.distributed.rpc as rpc
+            >>>
+            >>> rpc.init_rpc("worker1", rank=1, world_size=2)
+            >>> rpc.shutdown()
+        """
+        super().__init__()
+
+        enable_moving_cpu_tensors_to_cuda = self._prepare_init(remote_device)
+
+        # Default arguments preparation.
+        args = args if args is not None else ()
+        kwargs = kwargs if kwargs is not None else {}
+
+        if _module_interface_cls is not None:
+            # Users reply on this field to know if this generated RemoteModule is TorchScript-able.
+            self.is_scriptable = True
+
+            # Instantiate template on remote side.
+            fut = rpc.rpc_async(
+                self.on,
+                _instantiate_template,
+                (_module_interface_cls, enable_moving_cpu_tensors_to_cuda),
+            )
+
+            self._init_template(
+                _module_interface_cls, enable_moving_cpu_tensors_to_cuda
+            )
+
+            # Instantiate template on remote side.
+            fut = rpc.rpc_async(
+                self.on,
+                _instantiate_template,
+                (_module_interface_cls, enable_moving_cpu_tensors_to_cuda),
+            )
+
+            # Create the module on the remote side.
+            fut.wait()  # Ensure remote_module_cls is available on remote side.
+
+            # TODO: We need to change this to rpc.remote, and make it async (see the else branch below).
+            # For that we need to be able to apply _module_interface_cls to the RRef returned by rpc.remote
+            # See https://github.com/pytorch/pytorch/issues/58098 for more context.
+            self.module_rref = rpc.rpc_sync(
+                self.on,
+                _create_module_with_interface,
+                (module_cls, args, kwargs, self.device, _module_interface_cls),
+            )
+        else:
+            self.is_scriptable = False
+            self.generated_methods = (
+                _NON_SCRIPTABLE_REMOTE_MODULE_MODULE._generated_methods
+            )
+            # Create the module on the remote side.
+            self.module_rref = rpc.remote(
+                self.on,
+                _create_module,
+                (module_cls, args, kwargs, self.device),
+            )
+
+        self._install_generated_methods()
+        self._check_attribute_picklability()
+
+    def remote_parameters(self, recurse: bool = True) -> List[rpc.RRef[Parameter]]:
+        """
+        Return a list of :class:`~torch.distributed.rpc.RRef` pointing to the remote module's parameters.
+
+        This can typically be used in conjunction
+        with :class:`~torch.distributed.optim.DistributedOptimizer`.
+
+        Args:
+            recurse (bool): if True, then returns parameters of the remote
+                module and all submodules of the remote module. Otherwise,
+                returns only parameters that are direct members of the
+                remote module.
+
+        Returns:
+            A list of :class:`~torch.distributed.rpc.RRef` (``List[RRef[nn.Parameter]]``)
+            to remote module's parameters.
+        """
+        return rpc.rpc_sync(self.on, _param_rrefs, args=(self.module_rref, recurse))
+
+    def get_module_rref(self) -> rpc.RRef[nn.Module]:
+        """Return an :class:`~torch.distributed.rpc.RRef` (``RRef[nn.Module]``) pointing to the remote module."""
+        return self.module_rref
+
+    @torch.jit.export
+    def __getstate__(self):
+        raise RuntimeError(
+            "Cannot pickle RemoteModule in python pickler. RemoteModule can only be pickled when using RPC"
+        )
+
+    @torch.jit.export
+    def __setstate__(self, state):
+        raise RuntimeError(
+            "Cannot unpickle RemoteModule in python pickler. RemoteModule can only be unpickled when using RPC"
+        )
+
+    def register_buffer(
+        self, name: str, tensor: Optional[Tensor], persistent: bool = True
+    ) -> None:
+        _raise_not_supported(self.register_buffer.__name__)
+
+    def register_parameter(self, name: str, param: Optional[Parameter]) -> None:
+        _raise_not_supported(self.register_parameter.__name__)
+
+    def add_module(self, name: str, module: Optional[Module]) -> None:
+        _raise_not_supported(self.add_module.__name__)
+
+    def apply(self: T, fn: Callable[[Module], None]) -> T:  # type: ignore[return]
+        _raise_not_supported(self.apply.__name__)
+
+    def cuda(self: T, device: Optional[Union[int, device]] = None) -> T:  # type: ignore[return]
+        _raise_not_supported(self.cuda.__name__)
+
+    def ipu(self: T, device: Optional[Union[int, device]] = None) -> T:  # type: ignore[return]
+        _raise_not_supported(self.ipu.__name__)
+
+    def xpu(self: T, device: Optional[Union[int, device]] = None) -> T:  # type: ignore[return]
+        _raise_not_supported(self.xpu.__name__)
+
+    def cpu(self: T) -> T:  # type: ignore[return]
+        _raise_not_supported(self.cpu.__name__)
+
+    def type(self: T, dst_type: Union[dtype, str]) -> T:  # type: ignore[return]
+        _raise_not_supported(self.type.__name__)
+
+    def float(self: T) -> T:  # type: ignore[return]
+        _raise_not_supported(self.float.__name__)
+
+    def double(self: T) -> T:  # type: ignore[return]
+        _raise_not_supported(self.double.__name__)
+
+    def half(self: T) -> T:  # type: ignore[return]
+        _raise_not_supported(self.half.__name__)
+
+    def bfloat16(self: T) -> T:  # type: ignore[return]
+        _raise_not_supported(self.bfloat16.__name__)
+
+    def to(self, *args, **kwargs) -> T:  # type: ignore[misc, return, type-var]
+        _raise_not_supported(self.to.__name__)
+
+    def register_backward_hook(  # type: ignore[return]
+        self, hook: Callable[[Module, _grad_t, _grad_t], Union[None, _grad_t]]
+    ) -> RemovableHandle:
+        _raise_not_supported(self.register_backward_hook.__name__)
+
+    def register_forward_pre_hook(  # type: ignore[return]
+        self,
+        hook: Union[
+            Callable[[T, Tuple[Any, ...]], Optional[Any]],
+            Callable[
+                [T, Tuple[Any, ...], Dict[str, Any]],
+                Optional[Tuple[Any, Dict[str, Any]]],
+            ],
+        ],
+        prepend: bool = False,
+        with_kwargs: bool = False,
+    ) -> RemovableHandle:
+        _raise_not_supported(self.register_forward_pre_hook.__name__)
+
+    def register_forward_hook(  # type: ignore[return, override]
+        self,
+        hook: Union[
+            Callable[[T, Tuple[Any, ...], Any], Optional[Any]],
+            Callable[[T, Tuple[Any, ...], Dict[str, Any], Any], Optional[Any]],
+        ],
+        prepend: bool = False,
+        with_kwargs: bool = False,
+    ) -> RemovableHandle:
+        _raise_not_supported(self.register_forward_hook.__name__)
+
+    def state_dict(self, *args, **kwargs):
+        _raise_not_supported(self.state_dict.__name__)
+
+    def load_state_dict(
+        self,
+        state_dict: Mapping[str, Any],
+        strict: bool = True,
+        assign: bool = False,
+    ):
+        _raise_not_supported(self.load_state_dict.__name__)
+
+    def parameters(self, recurse: bool = True) -> Iterator[Parameter]:
+        raise ValueError(
+            "Method ``parameters`` not supported for RemoteModule. Please use ``remote_parameters`` instead."
+        )
+
+    def named_parameters(  # type: ignore[return]
+        self, prefix: str = "", recurse: bool = True, remove_duplicate: bool = True
+    ) -> Iterator[Tuple[str, Parameter]]:
+        _raise_not_supported(self.named_parameters.__name__)
+
+    def buffers(self, recurse: bool = True) -> Iterator[Tensor]:  # type: ignore[return]
+        _raise_not_supported(self.buffers.__name__)
+
+    def named_buffers(  # type: ignore[return]
+        self, prefix: str = "", recurse: bool = True, remove_duplicate: bool = True
+    ) -> Iterator[Tuple[str, Tensor]]:
+        _raise_not_supported(self.named_buffers.__name__)
+
+    def children(self) -> Iterator[Module]:  # type: ignore[return]
+        _raise_not_supported(self.children.__name__)
+
+    def named_children(self) -> Iterator[Tuple[str, Module]]:  # type: ignore[return]
+        _raise_not_supported(self.named_children.__name__)
+
+    def modules(self) -> Iterator[Module]:  # type: ignore[return]
+        _raise_not_supported(self.modules.__name__)
+
+    def named_modules(
+        self,
+        memo: Optional[Set[Module]] = None,
+        prefix: str = "",
+        remove_duplicate: bool = True,
+    ):
+        _raise_not_supported(self.named_modules.__name__)
+
+    def train(self: T, mode: bool = True) -> T:
+        return self.module_rref.rpc_sync().train()  # type: ignore[operator, union-attr]
+
+    def eval(self: T) -> T:
+        return self.module_rref.rpc_sync().eval()  # type: ignore[operator, union-attr]
+
+    def requires_grad_(self: T, requires_grad: bool = True) -> T:  # type: ignore[return]
+        _raise_not_supported(self.requires_grad_.__name__)
+
+    def zero_grad(self, set_to_none: bool = True) -> None:
+        _raise_not_supported(self.zero_grad.__name__)
+
+    def share_memory(self: T) -> T:  # type: ignore[return]
+        _raise_not_supported(self.share_memory.__name__)
+
+    def extra_repr(self) -> str:  # type: ignore[return]
+        _raise_not_supported(self.extra_repr.__name__)
+
+    def _prepare_init(self, remote_device_str: str) -> bool:
+        """Prepare the initialization and returns whether to enable automatically moving CPU tensors to CUDA devices."""
+        # Sanity check.
+        assert rpc._is_current_rpc_agent_set(), "RemoteModule only works in RPC."
+
+        remote_device = _remote_device(remote_device_str)
+        self.on = (
+            remote_device.worker_name()
+            if remote_device.worker_name() is not None
+            else remote_device.rank()
+        )
+        self.device = str(remote_device.device())
+        agent = rpc._get_current_rpc_agent()
+        # If the device map of the remote worker is set,
+        # then enable moving any input CPU tensors to the same cuda device.
+        self.is_device_map_set = bool(
+            agent._get_device_map(agent.get_worker_info(self.on))  # type: ignore[arg-type]
+        )
+        # ``enable_moving_cpu_tensors_to_cuda`` is less strict than ``is_device_map_set``:
+        # If ``enable_moving_cpu_tensors_to_cuda`` is true, but the device map is not set,
+        # then any CPU tensors can still be moved to a cuda device to run forward,
+        # but the output must be moved back to CPU before being sent over the wire.
+        enable_moving_cpu_tensors_to_cuda = torch.device(self.device).type == "cuda"
+        return enable_moving_cpu_tensors_to_cuda
+
+    def _init_template(self, module_interface_cls, enable_moving_cpu_tensors_to_cuda):
+        """Instantiate template on local side."""
+        generated_module = instantiator.instantiate_scriptable_remote_module_template(
+            module_interface_cls, enable_moving_cpu_tensors_to_cuda
+        )
+        self.generated_methods = generated_module._generated_methods
+
+    def _check_attribute_picklability(self):
+        """Check if all the attribute has explicitly defined whether to be pickled (i.e., picklability)."""
+        for k in self.__dict__.keys():
+            if (
+                k not in _REMOTE_MODULE_PICKLED_ATTRIBUTES
+                and k not in _REMOTE_MODULE_ATTRIBUTES_IGNORE_FOR_PICKLING
+            ):
+                raise AttributeError(
+                    f"Attribute {k} must be either in ``_REMOTE_MODULE_PICKLED_ATTRIBUTES`` or "
+                    "``_REMOTE_MODULE_ATTRIBUTES_IGNORE_FOR_PICKLING``."
+                )
+
+    def _install_generated_methods(self):
+        for method in self.generated_methods:
+            method_name = method.__name__
+            method = torch.jit.export(method)
+            setattr(self, method_name, types.MethodType(method, self))
+
+    @staticmethod
+    def init_from_module_rref(
+        remote_device: str,
+        module_rref: rpc.RRef[nn.Module],
+        _module_interface_cls: Any = None,
+    ):
+        """
+        Besides the constructor, a RemoteModule instance can also be initialized given a module RRef.
+
+        This alternate initialization method can be particularly useful if we want to create multiple
+        RemoteModule instances that share the same underlying module and reduce memory consumption.
+
+        Moreover, this also provides a workaround for passing script RemoteModule over RPC,
+        which is not supported. The recommended way is as follows:
+
+            1. the sender creates a RemoteModule;
+            2. the sender sends its ``module_rref`` over RPC;
+            3. the receiver calls this method to initialize another RemoteModule using the same ``module_rref``.
+
+        Example::
+            Run the following code in two different processes:
+
+            >>> # xdoctest: +SKIP("distributed")
+            >>> # On worker 0:
+            >>> import torch
+            >>> import torch.distributed.rpc as rpc
+            >>> from torch import nn, Tensor
+            >>> from torch.distributed.nn.api.remote_module import RemoteModule
+            >>>
+            >>> rpc.init_rpc("worker0", rank=0, world_size=2)
+            >>> remote_module = RemoteModule(
+            >>>     "worker1/cpu", nn.Linear, args=(20, 30),
+            >>> )
+            >>>
+            >>> remote_module1 = rpc.rpc_sync(
+            >>>     "worker1/cpu",
+            >>>     RemoteModule.init_from_module_rref,
+            >>>     ("worker1/cpu", remote_module1.get_module_rref()),
+            >>> )
+            >>> rpc.shutdown()
+
+            >>> # On worker 1:
+            >>> import torch
+            >>> import torch.distributed.rpc as rpc
+            >>>
+            >>> rpc.init_rpc("worker1", rank=1, world_size=2)
+            >>> rpc.shutdown()
+
+        Args:
+            remote_device (str): Device on the destination worker where we'd like to place this module.
+                The device can be a local device or a remote device specified by one of the following remote
+                formats:
+
+                    1. "rank:/" (ex: "rank:0/cuda:0").
+                    2. "/" (ex: "trainer0/cuda:0").
+
+                In addition, the device field can be optional and the default value is "cpu".
+            module_rref (RRef[nn.Module]): The module reference shared by both the caller and
+                the created remote module.
+            _module_interface_cls (type, optional): The TorchScript interface type for the module
+                to be created. The type object should be decorated by @torch.jit.interface.
+                If not provided, the generated RemoteModule is not torchscript-able.
+                Warning, this is an experimental API and susceptible to frequent changes.
+
+        Returns:
+            A remote module instance which wraps the :class:`~nn.Module` created by the
+            user-provided ``module_rref``, it has a blocking ``forward`` method and an
+            asynchronous ``forward_async`` method that returns a future of the ``forward`` call
+            on the user-provided module on the remote side.
+        """
+        # NOTE: if a new attribute is added to this class, also need to add it
+        # to ``_REMOTE_MODULE_PICKLED_ATTRIBUTES`` for pickling/unpickling.
+
+        remote_module = object.__new__(RemoteModule)
+
+        enable_moving_cpu_tensors_to_cuda = remote_module._prepare_init(remote_device)
+
+        if _module_interface_cls is not None:
+            # Users reply on this field to know if this generated RemoteModule is TorchScript-able.
+            remote_module.is_scriptable = True
+
+            remote_module._init_template(
+                _module_interface_cls, enable_moving_cpu_tensors_to_cuda
+            )
+        else:
+            remote_module.is_scriptable = False
+            remote_module.generated_methods = (
+                _NON_SCRIPTABLE_REMOTE_MODULE_MODULE._generated_methods
+            )
+        remote_module.module_rref = module_rref
+
+        remote_module._install_generated_methods()
+        remote_module._check_attribute_picklability()
+
+        return remote_module
+
+
+class RemoteModule(_RemoteModule):
+    """
+        A RemoteModule instance can only be created after RPC initialization.
+
+        It creates a user-specified module on a specified remote node.
+        It behaves like a regular ``nn.Module`` except that the ``forward`` method is
+        executed on the remote node.
+        It takes care of autograd recording to ensure the backward pass propagates
+        gradients back to the corresponding remote module.
+
+        It generates two methods ``forward_async`` and ``forward`` based on the
+        signature of the ``forward`` method of ``module_cls``. ``forward_async``
+        runs asynchronously and returns a Future. The arguments of ``forward_async``
+        and ``forward`` are the same as the ``forward`` method of the module
+        returned by the ``module_cls``.
+
+        For example, if ``module_cls`` returns an instance of ``nn.Linear``,
+        that has ``forward`` method signature: ``def forward(input: Tensor) -> Tensor:``,
+        the generated ``RemoteModule`` will have 2 methods with the signatures:
+
+        | ``def forward(input: Tensor) -> Tensor:``
+        | ``def forward_async(input: Tensor) -> Future[Tensor]:``
+
+    Args:
+        remote_device (str): Device on the destination worker where we'd like to place this module.
+            The format should be "/", where the device field can be parsed as torch.device type.
+            E.g., "trainer0/cpu", "trainer0", "ps0/cuda:0".
+            In addition, the device field can be optional and the default value is "cpu".
+        module_cls (nn.Module): Class for the module to be created remotely. For example,
+
+            >>> class MyModule(nn.Module):
+            >>>     def forward(input):
+            >>>         return input + 1
+            >>>
+            >>> module_cls = MyModule
+
+        args (Sequence, optional): args to be passed to ``module_cls``.
+        kwargs (Dict, optional): kwargs to be passed to ``module_cls``.
+
+    Returns:
+        A remote module instance which wraps the :class:`~nn.Module` created by the
+        user-provided ``module_cls``, it has a blocking ``forward`` method and an
+        asynchronous ``forward_async`` method that returns a future of the ``forward`` call
+        on the user-provided module on the remote side.
+
+    Example::
+        Run the following code in two different processes:
+
+        >>> # xdoctest: +SKIP("distributed")
+        >>> # On worker 0:
+        >>> import torch
+        >>> import torch.distributed.rpc as rpc
+        >>> from torch import nn, Tensor
+        >>> from torch.distributed.nn.api.remote_module import RemoteModule
+        >>>
+        >>> rpc.init_rpc("worker0", rank=0, world_size=2)
+        >>> remote_linear_module = RemoteModule(
+        >>>     "worker1/cpu", nn.Linear, args=(20, 30),
+        >>> )
+        >>> input = torch.randn(128, 20)
+        >>> ret_fut = remote_linear_module.forward_async(input)
+        >>> ret = ret_fut.wait()
+        >>> rpc.shutdown()
+
+        >>> # On worker 1:
+        >>> import torch
+        >>> import torch.distributed.rpc as rpc
+        >>>
+        >>> rpc.init_rpc("worker1", rank=1, world_size=2)
+        >>> rpc.shutdown()
+
+        Furthermore, a more practical example that is combined with
+        `DistributedDataParallel `__ (DDP)
+        can be found in this `tutorial `__.
+    """
+
+    def __init__(
+        self,
+        remote_device: str,
+        module_cls: Type[nn.Module],
+        args: Optional[Tuple] = None,
+        kwargs: Optional[Dict[str, Any]] = None,
+    ):
+        super().__init__(remote_device, module_cls, args, kwargs)
+
+
+def _remote_module_receiver(
+    *remote_module_pickled_attrs,
+):
+    """Deserializes a RemoteModule."""
+    serialized_remote_module = _SerializedRemoteModule._make(
+        remote_module_pickled_attrs
+    )
+    m = object.__new__(RemoteModule)
+    m.__dict__.update(serialized_remote_module._asdict())
+
+    # Unpickling the attribute `module_rref` must invoke RRef's `_deserialize()` method.
+    m.module_rref = rpc.PyRRef._deserialize(m.module_rref)
+
+    # Install generated methods when unpickled.
+    for method in m.generated_methods:
+        method_name = method.__name__
+        method = torch.jit.export(method)
+        setattr(m, method_name, types.MethodType(method, m))
+
+    return m
+
+
+def _remote_module_reducer(remote_module):
+    """Serialize a RemoteModule."""
+    pickled_attrs = {}
+    for k, v in remote_module.__dict__.items():
+        # Pickling the attribute `module_rref` must invoke RRef's `_serialize()` method.
+        if k == "module_rref":
+            pickled_attrs[k] = v._serialize()
+        elif k in _REMOTE_MODULE_PICKLED_ATTRIBUTES:
+            pickled_attrs[k] = v
+        # Check if unpickled attributes are all in _REMOTE_MODULE_ATTRIBUTES_IGNORE_FOR_PICKLING.
+        elif k not in _REMOTE_MODULE_ATTRIBUTES_IGNORE_FOR_PICKLING:
+            print(
+                f"The new attribute ``{k}`` of RemoteModule is ignored during RPC pickling. "
+                "To pickle this attribute, please add it to ``_REMOTE_MODULE_PICKLED_ATTRIBUTES``. "
+                "Otherwise, please explicitly add it to ``_REMOTE_MODULE_ATTRIBUTES_IGNORE_FOR_PICKLING``.",
+                file=sys.stderr,
+            )
+
+    return (
+        _remote_module_receiver,
+        tuple(pickled_attrs.values()),
+    )
+
+
+def _recursive_script_module_receiver(
+    recursive_script_module_serialized,
+):
+    """Deserializes a RecursiveScriptModule that does not contain a script RemoteModule."""
+    f = io.BytesIO(recursive_script_module_serialized)
+    m = torch.jit.load(f)
+    return m
+
+
+def _recursive_script_module_reducer(recursive_script_module):
+    """Serialize a RecursiveScriptModule that does not contain a script RemoteModule, and raises an error otherwise."""
+    if hasattr(recursive_script_module._c, "module_rref"):
+        raise RuntimeError(
+            "Passing a script RemoteModule over RPC is not supported. Please create a RemoteModule in the sender, "
+            "send the `module_rref` to the receiver, and create a new instance on the receiver end by passing this `module_rref`."
+        )
+
+    f = io.BytesIO()
+    torch.jit.save(recursive_script_module, f)
+    return (_recursive_script_module_receiver, (f.getvalue(),))
+
+
+_internal_rpc_pickler._register_reducer(RemoteModule, _remote_module_reducer)
+_internal_rpc_pickler._register_reducer(
+    torch.jit.RecursiveScriptModule, _recursive_script_module_reducer
+)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/functional.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/functional.py
new file mode 100644
index 0000000000000000000000000000000000000000..110df578552a59ab95f622ad5a306bc2a57f6457
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/functional.py
@@ -0,0 +1,452 @@
+# mypy: allow-untyped-defs
+import torch
+import torch.distributed as dist
+from torch.autograd import Function
+
+# The two imports below are not always available depending on the
+# USE_DISTRIBUTED compile flag. Make sure they raise import error
+# if we're trying to use them.
+from torch.distributed import group, ReduceOp
+
+
+def broadcast(tensor, src, group=group.WORLD):
+    """
+    Broadcasts the tensor to the whole group.
+
+    ``tensor`` must have the same number of elements in all processes
+    participating in the collective.
+
+    Arguments:
+        tensor (Tensor): Data to be sent if ``src`` is the rank of current
+            process.
+        src (int): Source rank.
+        group (ProcessGroup, optional): The process group to work on.
+
+    Returns:
+        Tensor: Received tensor from the broadcast op.
+
+    """
+    return _Broadcast.apply(src, group, tensor)
+
+
+def gather(tensor, dst=0, group=group.WORLD):
+    """
+    Gathers a list of tensors in a single process.
+
+    Arguments:
+        tensor (Tensor): Input tensor.
+        dst (int, optional): Destination rank (default is 0).
+        group (ProcessGroup, optional): The process group to work on.
+
+    Returns:
+        tuple[Tensor]: List of appropriately-sized tensors with the gathered data.
+    """
+    return _Gather.apply(dst, group, tensor)
+
+
+def scatter(tensors, src=0, group=group.WORLD):
+    """
+    Scatters a list of tensors to all processes in a group.
+
+    Each process will receive exactly one tensor and store its data in the
+    ``tensor`` argument.
+
+    Arguments:
+        tensors (list[Tensor]): List of tensors to scatter on the source rank.
+            Receivers must pass ``None`.
+        src (int, optional): Source rank (default is 0).
+        group (ProcessGroup, optional): The process group to work on.
+
+    Returns:
+        Tensor: Output tensor from the scatter operation.
+
+    """
+    return _Scatter.apply(src, group, *tensors)
+
+
+def reduce(tensor, dst, op=ReduceOp.SUM, group=group.WORLD):
+    """
+    Reduces the tensor data across all machines.
+
+    Only the process with rank ``dst`` is going to receive the final result.
+
+    Arguments:
+        tensor (Tensor): Input of the collective.
+        dst (int): Destination rank.
+        op (optional): One of the values from
+            ``torch.distributed.ReduceOp``
+            enum.  Specifies an operation used for element-wise reductions.
+        group (ProcessGroup, optional): The process group to work on.
+
+    Returns:
+        Tensor: Output of the collective.
+
+    """
+    return _Reduce.apply(dst, op, group, tensor)
+
+
+def reduce_scatter(output, input_list, op=ReduceOp.SUM, group=group.WORLD):
+    """
+    Reduces, then scatters a list of tensors to all processes in a group.
+
+    Arguments:
+        output (Tensor): Output tensor.
+        input_list (list[Tensor]): List of tensors to reduce and scatter.
+        op (optional): One of the values from
+            ``torch.distributed.ReduceOp``
+            enum.  Specifies an operation used for element-wise reductions.
+        group (ProcessGroup, optional): The process group to work on.
+
+    Returns:
+        Tensor: Output of the collective.
+
+    """
+    return _Reduce_Scatter.apply(op, group, output, *input_list)
+
+
+def all_gather(tensor, group=group.WORLD):
+    """
+    Gathers tensors from the whole group in a list.
+
+    Arguments:
+        tensor (Tensor): Tensor to be broadcast from current process.
+        group (ProcessGroup, optional): The process group to work on.
+
+    Returns:
+        tuple([Tensor]): Output of the collective.
+
+    """
+    return _AllGather.apply(group, tensor)
+
+
+def _all_gather_base(output_tensor, input_tensor, group=group.WORLD):
+    """
+    Single tensor all gather. Gathers a single tensor from all ranks, and puts them in a single output tensor.
+
+    Args:
+        output_tensor (Tensor): Output tensor. It should contain
+            correctly-sized tensors to be used for output of the collective.
+        input_tensor (Tensor): Tensor to be broadcast from current process.
+        group (ProcessGroup, optional): The process group to work on. If None,
+            the default process group will be used.
+
+    Examples:
+        >>> # All tensors below are of torch.int64 dtype.
+        >>> # We have 2 process groups, 2 ranks.
+        >>> # xdoctest: +SKIP("incorrect want text")
+        >>> output_tensor = torch.zeros(2, dtype=torch.int64)
+        >>> output_tensor
+        [tensor([0, 0])] # Rank 0 and 1
+        >>> tensor = torch.arange(1, dtype=torch.int64) + 1 + rank
+        >>> tensor
+        tensor([1]) # Rank 0
+        tensor([2]) # Rank 1
+        >>> dist.all_gather_base(output_tensor, tensor)
+        >>> output_tensor
+        tensor([1,2]) # Rank 0
+        tensor([1,2]) # Rank 1
+
+    .. warning::
+        `_all_gather_base` is experimental and subject to change.
+        It is the caller's responsibility to ensure the output_tensor
+        is correctly sized.
+
+    """
+    return _AllGatherBase.apply(output_tensor, input_tensor, group)
+
+
+def all_to_all(output_tensor_list, input_tensor_list, group=group.WORLD):
+    """
+    Each process scatters list of input tensors to all processes in a group and return gathered list of tensors in output list.
+
+    Arguments:
+        output_tensor_list (list[Tensor]): list of tensors to gather one per rank.
+        input_tensor_list (list[Tensor]): List of tensors to scatter one per rank.
+        group (ProcessGroup, optional): The process group to work on.
+
+    Returns:
+        tuple([Tensor]): Output of the collective.
+
+    """
+    return _AlltoAll.apply(group, output_tensor_list, *input_tensor_list)
+
+
+def all_to_all_single(
+    output,
+    input,
+    output_split_sizes=None,
+    input_split_sizes=None,
+    group=group.WORLD,
+):
+    """
+    Each process splits input tensor and then scatters the split list to all processes in a group.
+
+    Then concatenate the received tensors from all the processes in the group and return single output tensor.
+
+    Arguments:
+        output (Tensor): Gathered concatenated output tensor.
+        input (Tensor): Input tensor to scatter.
+        output_split_sizes: (list[Int], optional): Output split sizes for dim 0
+            if specified None or empty, dim 0 of ``output`` tensor must divide
+            equally by ``world_size``.
+        input_split_sizes: (list[Int], optional): Input split sizes for dim 0
+            if specified None or empty, dim 0 of ``input`` tensor must divide
+            equally by ``world_size``.
+
+    Returns:
+        Tensor: Output of the collective.
+
+    """
+    return _AlltoAllSingle.apply(
+        group, output, output_split_sizes, input_split_sizes, input
+    )
+
+
+def all_reduce(tensor, op=ReduceOp.SUM, group=group.WORLD):
+    """
+    Reduces the tensor data across all machines in such a way that all get the final result.
+
+    After the call the returned tensor is going to be bitwise
+    identical in all processes.
+
+    Arguments:
+        tensor (Tensor): Input of the collective.
+        op (optional): One of the values from
+            ``torch.distributed.ReduceOp``
+            enum.  Specifies an operation used for element-wise reductions.
+        group (ProcessGroup, optional): The process group to work on.
+
+    Returns:
+        Tensor: Output of the collective
+
+    """
+    return _AllReduce.apply(op, group, tensor)
+
+
+class _Broadcast(Function):
+    @staticmethod
+    def forward(ctx, src, group, tensor):
+        ctx.src = src
+        ctx.group = group
+        ctx.rank = dist.get_rank(group=group)
+        # torch.distributed makes all the calls in place
+        # we allocate new tensors to avoid this
+        tensor = tensor.clone()
+        dist.broadcast(tensor, src, group=group)
+        return tensor
+
+    @staticmethod
+    def backward(ctx, grad_output):
+        gx = _Reduce.apply(ctx.src, ReduceOp.SUM, ctx.group, grad_output)
+        if ctx.src != ctx.rank:
+            gx.zero_()
+        return (None, None, gx)
+
+
+class _Gather(Function):
+    @staticmethod
+    def forward(ctx, dst, group, tensor):
+        ctx.dst = dst
+        ctx.group = group
+        # Need to create a list of tensors here to do the
+        # aggregation, get it from the group size
+        # tensor should be correctly sized for the method
+        # gathering
+        tensor_list = [
+            torch.zeros_like(tensor) for i in range(dist.get_world_size(group=group))
+        ]
+
+        tensor = tensor.contiguous()
+        if dist.get_rank(group=group) == dst:
+            dist.gather(tensor, tensor_list, dst, group=group)
+        else:
+            dist.gather(tensor, None, dst, group=group)
+        return tuple(tensor_list)
+
+    @staticmethod
+    def backward(ctx, *grad_outputs):
+        return (None, None) + (_Scatter.apply(ctx.dst, ctx.group, *grad_outputs),)
+
+
+class _Scatter(Function):
+    @staticmethod
+    def forward(ctx, src, group, *tensors):
+        ctx.src = src
+        ctx.group = group
+        assert all(t.size() == tensors[0].size() for t in tensors)
+        output = torch.zeros_like(tensors[0])
+        if dist.get_rank(group=group) == src:
+            dist.scatter(output, list(tensors), src, group=group)
+        else:
+            dist.scatter(output, None, src, group=group)
+        return output
+
+    @staticmethod
+    def backward(ctx, grad_output):
+        return (None, None) + _Gather.apply(ctx.src, ctx.group, grad_output)
+
+
+class _Reduce(Function):
+    @staticmethod
+    def forward(ctx, src, op, group, tensor):
+        ctx.src = src
+        ctx.group = group
+        tensor = tensor.clone()
+        dist.reduce(tensor, src, op=op, group=group)
+        return tensor
+
+    @staticmethod
+    def backward(ctx, grad_output):
+        return (None, None, None) + (_Broadcast.apply(ctx.src, ctx.group, grad_output),)
+
+
+class _Reduce_Scatter(Function):
+    @staticmethod
+    def forward(ctx, op, group, tensor, *input_tensor_list):
+        ctx.group = group
+        # Need contiguous tensors for collectives.
+        tensor = tensor.contiguous()
+        input_tensor_list = tuple(t.contiguous() for t in input_tensor_list)
+        dist.reduce_scatter(tensor, list(input_tensor_list), op=op, group=group)
+        return tensor
+
+    @staticmethod
+    def backward(ctx, grad_output):
+        return (None, None, None) + _AllGather.apply(ctx.group, grad_output)
+
+
+class _AllGather(Function):
+    @staticmethod
+    def forward(ctx, group, tensor):
+        # Need contiguous tensors for collectives.
+        tensor = tensor.contiguous()
+
+        ctx.group = group
+        out_tensor_list = [
+            torch.empty_like(tensor) for _ in range(dist.get_world_size(group=group))
+        ]
+
+        dist.all_gather(out_tensor_list, tensor, group=group)
+        return tuple(out_tensor_list)
+
+    @staticmethod
+    def backward(ctx, *grad_outputs):
+        if dist.get_backend(group=ctx.group) is dist.Backend.NCCL:
+            rank = dist.get_rank(group=ctx.group)
+            gx = torch.empty_like(grad_outputs[rank])
+            gx = _Reduce_Scatter.apply(ReduceOp.SUM, ctx.group, gx, *grad_outputs)
+        else:
+            # As many backends doesn't support ReduceScatter, we use AlltoAll with .sum()
+            # to emulate the ReduceScatter behavior
+            tensor_list = [torch.empty_like(tensor) for tensor in grad_outputs]
+            gxs = _AlltoAll.apply(ctx.group, tensor_list, *grad_outputs)
+            gx = torch.sum(torch.stack(gxs), dim=0)
+        return (None, gx)
+
+
+class _AllGatherBase(Function):
+    @staticmethod
+    def forward(ctx, output_tensor, input_tensor, group):
+        ctx.group = group
+        dist._all_gather_base(output_tensor, input_tensor.contiguous(), group=group)
+        return output_tensor
+
+    @staticmethod
+    def backward(ctx, grad_output):
+        if dist.get_backend(group=ctx.group) is dist.Backend.NCCL:
+            world_size = dist.get_world_size(group=ctx.group)
+            out_size = list(grad_output.size())
+            if out_size[0] % world_size != 0:
+                raise RuntimeError(
+                    f"Tensor with dimensions: {out_size} does "
+                    f"not have first dimension divisible by world_size: {world_size}"
+                )
+            out_size[0] = out_size[0] // dist.get_world_size(group=ctx.group)
+            gx = torch.empty(
+                out_size, device=grad_output.device, dtype=grad_output.dtype
+            )
+            dist._reduce_scatter_base(gx, grad_output, ReduceOp.SUM, ctx.group)
+        else:
+            raise RuntimeError("Backend not supported!")
+        return (None, gx, None)
+
+
+class _AlltoAll(Function):
+    @staticmethod
+    def forward(ctx, group, out_tensor_list, *tensors):
+        ctx.group = group
+        ctx.input_tensor_size_list = [
+            tensors[i].size() for i in range(dist.get_world_size(group=group))
+        ]
+        my_rank = dist.get_rank(group=group)
+        tensors = tuple(t.contiguous() for t in tensors)
+        # Implement it on means of scatter/gather, send/recv async operations have issues
+        if dist.get_backend(group=group) is dist.Backend.GLOO:
+            for i in range(dist.get_world_size(group=group)):
+                to_send = None
+                if i == my_rank:
+                    to_send = list(tensors)
+                dist.scatter(out_tensor_list[i], to_send, i, group=group)
+        else:
+            dist.all_to_all(
+                out_tensor_list,
+                list(tensors),
+                group=group,
+            )
+        return tuple(out_tensor_list)
+
+    @staticmethod
+    def backward(ctx, *grad_outputs):
+        tensor_list = [
+            torch.empty(
+                size, device=grad_outputs[0].device, dtype=grad_outputs[0].dtype
+            )
+            for size in ctx.input_tensor_size_list
+        ]
+        return (None, None) + _AlltoAll.apply(ctx.group, tensor_list, *grad_outputs)
+
+
+class _AlltoAllSingle(Function):
+    @staticmethod
+    def forward(ctx, group, output, output_split_sizes, input_split_sizes, input):
+        ctx.group = group
+        ctx.input_size = input.size()
+        ctx.output_split_sizes = input_split_sizes
+        ctx.input_split_sizes = output_split_sizes
+        dist.all_to_all_single(
+            output,
+            input,
+            output_split_sizes=output_split_sizes,
+            input_split_sizes=input_split_sizes,
+            group=group,
+        )
+        return output
+
+    @staticmethod
+    def backward(ctx, grad_output):
+        tensor = torch.empty(
+            ctx.input_size, device=grad_output.device, dtype=grad_output.dtype
+        )
+        return (None, None, None, None) + (
+            _AlltoAllSingle.apply(
+                ctx.group,
+                tensor,
+                ctx.output_split_sizes,
+                ctx.input_split_sizes,
+                grad_output.contiguous(),
+            ),
+        )
+
+
+class _AllReduce(Function):
+    @staticmethod
+    def forward(ctx, op, group, tensor):
+        ctx.group = group
+        ctx.op = op
+        tensor = tensor.clone()
+        dist.all_reduce(tensor, op=op, group=group)
+        return tensor
+
+    @staticmethod
+    def backward(ctx, grad_output):
+        return (None, None) + (_AllReduce.apply(ctx.op, ctx.group, grad_output),)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/jit/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/jit/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/jit/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/jit/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3c7ad35c618dfc87f899bf2d9a467f9b63ba201d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/jit/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/jit/__pycache__/instantiator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/jit/__pycache__/instantiator.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..97c7f9f45a023f1b91025ffa3114aa9f3544337b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/jit/__pycache__/instantiator.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/jit/instantiator.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/jit/instantiator.py
new file mode 100644
index 0000000000000000000000000000000000000000..d529fc740945a058c11bcc87ddf766c198a3ebfe
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/jit/instantiator.py
@@ -0,0 +1,154 @@
+#!/usr/bin/python3
+# mypy: allow-untyped-defs
+import importlib
+import logging
+import os
+import sys
+import tempfile
+from typing import Optional
+
+import torch
+from torch.distributed.nn.jit.templates.remote_module_template import (
+    get_remote_module_template,
+)
+
+
+logger = logging.getLogger(__name__)
+
+
+_FILE_PREFIX = "_remote_module_"
+_TEMP_DIR = tempfile.TemporaryDirectory()
+INSTANTIATED_TEMPLATE_DIR_PATH = _TEMP_DIR.name
+logger.info("Created a temporary directory at %s", INSTANTIATED_TEMPLATE_DIR_PATH)
+sys.path.append(INSTANTIATED_TEMPLATE_DIR_PATH)
+
+
+def get_arg_return_types_from_interface(module_interface):
+    assert getattr(
+        module_interface, "__torch_script_interface__", False
+    ), "Expect a TorchScript class interface decorated by @torch.jit.interface."
+    qualified_name = torch._jit_internal._qualified_name(module_interface)
+    cu = torch.jit._state._python_cu
+    module_interface_c = cu.get_interface(qualified_name)
+    assert (
+        "forward" in module_interface_c.getMethodNames()
+    ), f"Expect forward in interface methods, while it has {module_interface_c.getMethodNames()}"
+    method_schema = module_interface_c.getMethod("forward")
+
+    arg_str_list = []
+    arg_type_str_list = []
+    assert method_schema is not None
+    for argument in method_schema.arguments:
+        arg_str_list.append(argument.name)
+
+        if argument.has_default_value():
+            default_value_str = f" = {argument.default_value}"
+        else:
+            default_value_str = ""
+        arg_type_str = f"{argument.name}: {argument.type}{default_value_str}"
+        arg_type_str_list.append(arg_type_str)
+
+    arg_str_list = arg_str_list[1:]  # Remove "self".
+    args_str = ", ".join(arg_str_list)
+
+    arg_type_str_list = arg_type_str_list[1:]  # Remove "self".
+    arg_types_str = ", ".join(arg_type_str_list)
+
+    assert len(method_schema.returns) == 1
+    argument = method_schema.returns[0]
+    return_type_str = str(argument.type)
+
+    return args_str, arg_types_str, return_type_str
+
+
+def _write(out_path, text):
+    old_text: Optional[str]
+    try:
+        with open(out_path) as f:
+            old_text = f.read()
+    except OSError:
+        old_text = None
+    if old_text != text:
+        with open(out_path, "w") as f:
+            logger.info("Writing %s", out_path)
+            f.write(text)
+    else:
+        logger.info("Skipped writing %s", out_path)
+
+
+def _do_instantiate_remote_module_template(
+    generated_module_name, str_dict, enable_moving_cpu_tensors_to_cuda
+):
+    generated_code_text = get_remote_module_template(
+        enable_moving_cpu_tensors_to_cuda
+    ).format(**str_dict)
+    out_path = os.path.join(
+        INSTANTIATED_TEMPLATE_DIR_PATH, f"{generated_module_name}.py"
+    )
+    _write(out_path, generated_code_text)
+
+    # From importlib doc,
+    # > If you are dynamically importing a module that was created since
+    # the interpreter began execution (e.g., created a Python source file),
+    # you may need to call invalidate_caches() in order for the new module
+    # to be noticed by the import system.
+    importlib.invalidate_caches()
+    generated_module = importlib.import_module(f"{generated_module_name}")
+    return generated_module
+
+
+def instantiate_scriptable_remote_module_template(
+    module_interface_cls, enable_moving_cpu_tensors_to_cuda=True
+):
+    if not getattr(module_interface_cls, "__torch_script_interface__", False):
+        raise ValueError(
+            f"module_interface_cls {module_interface_cls} must be a type object decorated by "
+            "@torch.jit.interface"
+        )
+
+    # Generate the template instance name.
+    module_interface_cls_name = torch._jit_internal._qualified_name(
+        module_interface_cls
+    ).replace(".", "_")
+    generated_module_name = f"{_FILE_PREFIX}{module_interface_cls_name}"
+
+    # Generate type annotation strs.
+    assign_module_interface_cls_str = (
+        f"from {module_interface_cls.__module__} import "
+        f"{module_interface_cls.__name__} as module_interface_cls"
+    )
+    args_str, arg_types_str, return_type_str = get_arg_return_types_from_interface(
+        module_interface_cls
+    )
+    kwargs_str = ""
+    arrow_and_return_type_str = f" -> {return_type_str}"
+    arrow_and_future_return_type_str = f" -> Future[{return_type_str}]"
+
+    str_dict = dict(
+        assign_module_interface_cls=assign_module_interface_cls_str,
+        arg_types=arg_types_str,
+        arrow_and_return_type=arrow_and_return_type_str,
+        arrow_and_future_return_type=arrow_and_future_return_type_str,
+        args=args_str,
+        kwargs=kwargs_str,
+        jit_script_decorator="@torch.jit.script",
+    )
+    return _do_instantiate_remote_module_template(
+        generated_module_name, str_dict, enable_moving_cpu_tensors_to_cuda
+    )
+
+
+def instantiate_non_scriptable_remote_module_template():
+    generated_module_name = f"{_FILE_PREFIX}non_scriptable"
+    str_dict = dict(
+        assign_module_interface_cls="module_interface_cls = None",
+        args="*args",
+        kwargs="**kwargs",
+        arg_types="*args, **kwargs",
+        arrow_and_return_type="",
+        arrow_and_future_return_type="",
+        jit_script_decorator="",
+    )
+    # For a non-scriptable template, always enable moving CPU tensors to a cuda device,
+    # because there is no syntax limitation on the extra handling caused by the script.
+    return _do_instantiate_remote_module_template(generated_module_name, str_dict, True)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/jit/templates/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/jit/templates/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/jit/templates/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/jit/templates/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..65c7d98950d4e0218040628e9c77a12cd6a6b31b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/jit/templates/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/jit/templates/__pycache__/remote_module_template.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/jit/templates/__pycache__/remote_module_template.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..54b66b029c27d1f5b0fb7c97a8e564eddd0fcca4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/jit/templates/__pycache__/remote_module_template.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/jit/templates/remote_module_template.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/jit/templates/remote_module_template.py
new file mode 100644
index 0000000000000000000000000000000000000000..07b055774b36af4835e308c8a1f85afd0ab35f0f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/nn/jit/templates/remote_module_template.py
@@ -0,0 +1,108 @@
+#!/usr/bin/python3
+# mypy: allow-untyped-defs
+
+
+def get_remote_module_template(enable_moving_cpu_tensors_to_cuda: bool):
+    return _TEMPLATE_PREFIX + (
+        _REMOTE_FORWARD_TEMPLATE_ENABLE_MOVING_CPU_TENSORS_TO_CUDA
+        if enable_moving_cpu_tensors_to_cuda
+        else _REMOTE_FORWARD_TEMPLATE
+    )
+
+
+_TEMPLATE_PREFIX = """from typing import *
+
+import torch
+import torch.distributed.rpc as rpc
+from torch import Tensor
+from torch._jit_internal import Future
+from torch.distributed.rpc import RRef
+from typing import Tuple  # pyre-ignore: unused import
+
+
+{assign_module_interface_cls}
+
+
+def forward_async(self, {arg_types}){arrow_and_future_return_type}:
+    args = (self.module_rref, self.device, self.is_device_map_set, {args})
+    kwargs = {{{kwargs}}}
+    return rpc.rpc_async(
+        self.module_rref.owner(),
+        _remote_forward,
+        args,
+        kwargs,
+    )
+
+
+def forward(self, {arg_types}){arrow_and_return_type}:
+    args = (self.module_rref, self.device, self.is_device_map_set, {args})
+    kwargs = {{{kwargs}}}
+    ret_fut = rpc.rpc_async(
+        self.module_rref.owner(),
+        _remote_forward,
+        args,
+        kwargs,
+    )
+    return ret_fut.wait()
+
+
+_generated_methods = [
+    forward_async,
+    forward,
+]
+
+
+{jit_script_decorator}
+"""
+
+# This template may cause typing error (the mismatch between ``Tuple[()]`` and ``Tuple[Any]``)
+# even if the code is only used for instantiation but not execution.
+# Therefore, only include handling moving CPU tensors to a cuda device if necessary.
+# TODO: Merge these two templates together in the future once TorchScript syntax is improved.
+_REMOTE_FORWARD_TEMPLATE_ENABLE_MOVING_CPU_TENSORS_TO_CUDA = """
+def _remote_forward(
+    module_rref: RRef[module_interface_cls], device: str, is_device_map_set: bool, {arg_types}){arrow_and_return_type}:
+    module = module_rref.local_value()
+    device = torch.device(device)
+
+    if device.type != "cuda":
+        return module.forward({args}, {kwargs})
+
+    # If the module is on a cuda device,
+    # move any CPU tensor in args or kwargs to the same cuda device.
+    # Since torch script does not support generator expression,
+    # have to use concatenation instead of
+    # ``tuple(i.to(device) if isinstance(i, Tensor) else i for i in *args)``.
+    args = ({args},)
+    out_args: Tuple[()] = ()
+    for arg in args:
+        arg = (arg.to(device),) if isinstance(arg, Tensor) else (arg,)
+        out_args = out_args + arg
+
+    kwargs = {{{kwargs}}}
+    for k, v in kwargs.items():
+        if isinstance(v, Tensor):
+            kwargs[k] = kwargs[k].to(device)
+
+    if is_device_map_set:
+        return module.forward(*out_args, {kwargs})
+
+    # If the device map is empty, then only CPU tensors are allowed to send over wire,
+    # so have to move any GPU tensor to CPU in the output.
+    # Since torch script does not support generator expression,
+    # have to use concatenation instead of
+    # ``tuple(i.cpu() if isinstance(i, Tensor) else i for i in module.forward(*out_args, {kwargs}))``.
+    ret: Tuple[()] = ()
+    for i in module.forward(*out_args, {kwargs}):
+        i = (i.cpu(),) if isinstance(i, Tensor) else (i,)
+        ret = ret + i
+    return ret
+"""
+
+_REMOTE_FORWARD_TEMPLATE = """
+def _remote_forward(
+    module_rref: RRef[module_interface_cls], device: str, is_device_map_set: bool, {arg_types}){arrow_and_return_type}:
+    module = module_rref.local_value()
+
+    return module.forward({args}, {kwargs})
+"""
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..924b993ec8414b0282ee3d791717e7c34a231cda
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__init__.py
@@ -0,0 +1,53 @@
+"""
+:mod:`torch.distributed.optim` exposes DistributedOptimizer, which takes a list
+of remote parameters (:class:`~torch.distributed.rpc.RRef`) and runs the
+optimizer locally on the workers where the parameters live.  The distributed
+optimizer can use any of the local optimizer :ref:`optimizer-algorithms` to
+apply the gradients on each worker.
+"""
+import warnings
+
+import torch
+from torch import optim
+
+from .apply_optimizer_in_backward import (
+    _apply_optimizer_in_backward,
+    _get_in_backward_optimizers,
+)
+from .functional_adadelta import _FunctionalAdadelta
+from .functional_adagrad import _FunctionalAdagrad
+from .functional_adam import _FunctionalAdam
+from .functional_adamax import _FunctionalAdamax
+from .functional_adamw import _FunctionalAdamW
+from .functional_rmsprop import _FunctionalRMSprop
+from .functional_rprop import _FunctionalRprop
+from .functional_sgd import _FunctionalSGD
+from .named_optimizer import _NamedOptimizer
+from .utils import as_functional_optim
+
+
+with warnings.catch_warnings():
+    warnings.simplefilter("always")
+    warnings.warn(
+        "`TorchScript` support for functional optimizers is deprecated "
+        "and will be removed in a future PyTorch release. "
+        "Consider using the `torch.compile` optimizer instead.",
+        DeprecationWarning,
+        stacklevel=2,
+    )
+
+# DistributedOptimizer imports torch.distributed.rpc names, so gate availability
+# based on RPC being available.
+if hasattr(torch._C, "_rpc_init"):
+    from .optimizer import DistributedOptimizer
+
+from .post_localSGD_optimizer import PostLocalSGDOptimizer
+from .zero_redundancy_optimizer import ZeroRedundancyOptimizer
+
+
+__all__ = [
+    "as_functional_optim",
+    "DistributedOptimizer",
+    "PostLocalSGDOptimizer",
+    "ZeroRedundancyOptimizer",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8e93fb9fd9f72fa89c195f99f4f4ef6cd7b5626e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/apply_optimizer_in_backward.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/apply_optimizer_in_backward.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..66cc960af4c697c4f4cfb3d13d6a2fd2ece9a833
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/apply_optimizer_in_backward.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/functional_adadelta.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/functional_adadelta.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7be329b28d303e743642a307ef69c477798d49ff
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/functional_adadelta.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/functional_adagrad.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/functional_adagrad.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0cee568aaa0978b6e15d9e61a2fa13475bd2f50d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/functional_adagrad.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/functional_adam.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/functional_adam.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8b531b457c603102565d8e61f0ae5710e459360a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/functional_adam.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/functional_adamax.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/functional_adamax.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ad45a8427244e0e2b86e747e16e70f3df3ba78a6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/functional_adamax.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/functional_adamw.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/functional_adamw.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4155cf4a26a80a3c96ebe3f60ce83433b5f57651
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/functional_adamw.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/functional_rmsprop.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/functional_rmsprop.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..86dd670fe03aec3ba76b504652fdaad54c8d0ec1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/functional_rmsprop.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/functional_rprop.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/functional_rprop.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b9e8a0182a7bfb8ec4b4dad7bd3abc8b17d18f38
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/functional_rprop.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/functional_sgd.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/functional_sgd.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e65aa0ed87a22ff7915c1ec82c1a5f780894221c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/functional_sgd.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/named_optimizer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/named_optimizer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3571348371f342bd5d729c6e52a36fffceb231b8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/named_optimizer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/optimizer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/optimizer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..840c6eb092d9b3ae5a1f9d34431ebf5ff673972b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/optimizer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/post_localSGD_optimizer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/post_localSGD_optimizer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fb9d225cf531b71487dc85f1e53bbc5012bebc41
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/post_localSGD_optimizer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dfceeb552c2bdab105125f45db490207df506d39
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/zero_redundancy_optimizer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/zero_redundancy_optimizer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..560597432ceea1d0d2c1e5db65b10c2886d4992e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/__pycache__/zero_redundancy_optimizer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/apply_optimizer_in_backward.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/apply_optimizer_in_backward.py
new file mode 100644
index 0000000000000000000000000000000000000000..36f679f4eba49b378036bae2f8dc89e7278c91a4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/apply_optimizer_in_backward.py
@@ -0,0 +1,120 @@
+from typing import Any, Dict, Iterable, List, no_type_check, Type
+
+import torch
+
+
+__all__: List[str] = []
+
+# WeakTensorKeyDictionary to store relevant meta-data for the Tensor/Parameter
+# without changing it's life-time.
+# NOTE: Alternative is to add the meta-data as an attribute to the tensor,
+#       but that will serialize the meta-data if Tensor is serialized.
+param_to_optim_hook_handle_map = torch.utils.weak.WeakTensorKeyDictionary()
+param_to_acc_grad_map = torch.utils.weak.WeakTensorKeyDictionary()
+
+
+@no_type_check
+def _apply_optimizer_in_backward(
+    optimizer_class: Type[torch.optim.Optimizer],
+    params: Iterable[torch.nn.Parameter],
+    optimizer_kwargs: Dict[str, Any],
+    register_hook: bool = True,
+) -> None:
+    """
+    Upon ``backward()``, the optimizer specified for each parameter will fire after
+    the gradient has been accumulated into the parameter.
+
+    Note - gradients for these parameters will be set to None after ``backward()``.
+    This means that any other optimizer not specified via `_apply_optimizer_in_backward`
+    over this parameter will be a no-op.
+
+    Args:
+        optimizer_class: (Type[torch.optim.Optimizer]): Optimizer to apply to parameter
+        params: (Iterator[nn.Parameter]): parameters to apply optimizer state to
+        optimizer_kwargs: (Dict[str, Any]): kwargs to pass to optimizer constructor
+        register_hook: (bool): whether to register a hook that runs the optimizer
+            after gradient for this parameter is accumulated. This is the default
+            way that optimizer in backward is implemented, but specific use cases
+            (such as DDP) may wish to override this to implement custom behavior.
+            (Default = True)
+
+    Example::
+        params_generator = model.parameters()
+        param_1 = next(params_generator)
+        remainder_params = list(params_generator)
+
+        apply_optimizer_in_backward(torch.optim.SGD, [param_1], {"lr": .02})
+        apply_optimizer_in_backward(torch.optim.Adam, remainder_params, {"lr": .04})
+
+        model(...).sum().backward() # after backward, parameters will already
+        # have their registered optimizer(s) applied.
+
+    """
+    torch._C._log_api_usage_once("torch.distributed.optim.apply_optimizer_in_backward")
+
+    @no_type_check
+    def _apply_optimizer_in_backward_to_param(param: torch.nn.Parameter) -> None:
+        # view_as creates a node in autograd graph that allows us access to the
+        # parameter's AccumulateGrad autograd function object. We register a
+        # hook on this object to fire the optimizer when the gradient for
+        # this parameter is ready (has been accumulated into .grad field)
+
+        # Don't create a new acc_grad if we already have one
+        # i.e. for shared parameters or attaching multiple optimizers to a param.
+        if param not in param_to_acc_grad_map:
+            param_to_acc_grad_map[param] = param.view_as(param).grad_fn.next_functions[
+                0
+            ][0]
+
+        optimizer = optimizer_class([param], **optimizer_kwargs)
+
+        if not hasattr(param, "_in_backward_optimizers"):
+            param._in_backward_optimizers = []  # type: ignore[attr-defined]
+            # TODO: Remove these attributes once we have a better way of accessing
+            # optimizer classes and kwargs for a parameter.
+            param._optimizer_classes = []  # type: ignore[attr-defined]
+            param._optimizer_kwargs = []  # type: ignore[attr-defined]
+
+        param._in_backward_optimizers.append(optimizer)  # type: ignore[attr-defined]
+        param._optimizer_classes.append(optimizer_class)  # type: ignore[attr-defined]
+        param._optimizer_kwargs.append(optimizer_kwargs)  # type: ignore[attr-defined]
+
+        if not register_hook:
+            return
+
+        def optimizer_hook(*_unused) -> None:
+            for opt in param._in_backward_optimizers:  # type: ignore[attr-defined]
+                opt.step()
+
+            param.grad = None
+
+        handle = param_to_acc_grad_map[param].register_hook(optimizer_hook)  # type: ignore[attr-defined]
+        if param not in param_to_optim_hook_handle_map:
+            param_to_optim_hook_handle_map[param] = []
+        param_to_optim_hook_handle_map[param].append(handle)
+
+    for param in params:
+        _apply_optimizer_in_backward_to_param(param)
+
+
+def _get_in_backward_optimizers(module: torch.nn.Module) -> List[torch.optim.Optimizer]:
+    """
+    Return a list of in-backward optimizers applied to ``module``'s parameters. Note that these
+    optimizers are not intended to directly have their ``step`` or ``zero_grad`` methods called
+    by the user and are intended to be used for things like checkpointing.
+
+    Args:
+        module: (torch.nn.Module): model to retrieve in-backward optimizers for
+
+    Returns:
+        List[torch.optim.Optimizer]: the in-backward optimizers.
+
+    Example::
+        _apply_optimizer_in_backward(torch.optim.SGD, model.parameters(), {'lr': 0.01})
+        optims = _get_optimizers_in_backward(model)
+    """
+    optims: List[torch.optim.Optimizer] = []
+    for param in module.parameters():
+        optims.extend(getattr(param, "_in_backward_optimizers", []))
+
+    return optims
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/functional_adadelta.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/functional_adadelta.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ad51348b6afab2b4031f3852d12794c2c65e7e4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/functional_adadelta.py
@@ -0,0 +1,107 @@
+# mypy: allow-untyped-defs
+from typing import Dict, List, Optional
+
+import torch
+import torch.optim._functional as F
+from torch import Tensor
+
+
+__all__: List[str] = []
+
+
+# Define a TorchScript compatible Functional Adadelta Optimizer
+# where we use these optimizer in a functional way.
+# Instead of using the `param.grad` when updating parameters,
+# we explicitly allow the distributed optimizer pass gradients to
+# the `step` function. In this way, we could separate the gradients
+# and parameters and allow multithreaded trainer to update the
+# parameters without data traces on accumulating to the same .grad.
+# NOTE: This should be only used by distributed optimizer internals
+# and not meant to expose to the user.
+@torch.jit.script
+class _FunctionalAdadelta:
+    def __init__(
+        self,
+        params: List[Tensor],
+        lr: float = 1.0,
+        rho: float = 0.9,
+        eps: float = 1e-6,
+        weight_decay: float = 0.0,
+        foreach: bool = False,
+        maximize: bool = False,
+        _allow_empty_param_list: bool = False,
+    ):
+        self.defaults = {
+            "lr": lr,
+            "rho": rho,
+            "eps": eps,
+            "weight_decay": weight_decay,
+        }
+        self.foreach = foreach
+        self.maximize = maximize
+
+        if len(params) == 0 and not _allow_empty_param_list:
+            raise ValueError("optimizer got an empty parameter list")
+
+        # NOTE: we only have one param_group and don't allow user to add additional
+        # param group as it's not a common use case.
+        self.param_group = {"params": params}
+
+        self.state = torch.jit.annotate(Dict[torch.Tensor, Dict[str, torch.Tensor]], {})
+
+    def step(self, gradients: List[Optional[Tensor]]):
+        params = self.param_group["params"]
+        params_with_grad = []
+        grads = []
+        square_avgs = []
+        acc_deltas = []
+        state_steps = []
+        lr = self.defaults["lr"]
+        rho = self.defaults["rho"]
+        eps = self.defaults["eps"]
+        weight_decay = self.defaults["weight_decay"]
+
+        if len(params) != len(gradients):
+            raise ValueError(
+                "the gradients passed in does not equal to the size of the parameters!"
+                + f"Params length: {len(params)}. "
+                + f"Gradients length: {len(gradients)}"
+            )
+        has_complex = False
+        for param, gradient in zip(params, gradients):
+            if gradient is not None:
+                has_complex |= torch.is_complex(param)
+                params_with_grad.append(param)
+                grads.append(gradient)
+                # Lazy state initialization
+                if param not in self.state:
+                    self.state[param] = {}
+                    state = self.state[param]
+                    state["step"] = torch.tensor(0.0)
+                    state["square_avg"] = torch.zeros_like(
+                        param, memory_format=torch.preserve_format
+                    )
+                    state["acc_delta"] = torch.zeros_like(
+                        param, memory_format=torch.preserve_format
+                    )
+
+                state = self.state[param]
+                square_avgs.append(state["square_avg"])
+                acc_deltas.append(state["acc_delta"])
+                state_steps.append(state["step"])
+
+        with torch.no_grad():
+            F.adadelta(
+                params_with_grad,
+                grads,
+                square_avgs,
+                acc_deltas,
+                state_steps,
+                lr=lr,
+                rho=rho,
+                eps=eps,
+                weight_decay=weight_decay,
+                foreach=self.foreach,
+                maximize=self.maximize,
+                has_complex=has_complex,
+            )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/functional_adagrad.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/functional_adagrad.py
new file mode 100644
index 0000000000000000000000000000000000000000..67f7328489ed2175bff78846905fca2cc3917e38
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/functional_adagrad.py
@@ -0,0 +1,111 @@
+# mypy: allow-untyped-defs
+from typing import Dict, List, Optional
+
+import torch
+import torch.optim._functional as F
+from torch import Tensor
+
+
+__all__: List[str] = []
+
+
+# Define a TorchScript compatible Functional Adagrad Optimizer
+# where we use these optimizer in a functional way.
+# Instead of using the `param.grad` when updating parameters,
+# we explicitly let the user pass gradients to the `step` function
+# this is so that we could separate the gradients and parameters
+# and allow multithreaded trainer to update the parameters
+# without data traces on accumulating to the same .grad.
+# NOTE: This should be only used by distributed optimizer internals
+# and not meant to expose to the user.
+@torch.jit.script
+class _FunctionalAdagrad:
+    def __init__(
+        self,
+        params: List[Tensor],
+        lr: float = 1e-2,
+        lr_decay: float = 0.0,
+        weight_decay: float = 0.0,
+        initial_accumulator_value: float = 0.0,
+        warmup_lr_multiplier: float = 1.0,
+        warmup_num_iters: float = 0.0,
+        eps: float = 1e-10,
+        coalesce_grad: bool = True,
+        foreach: bool = False,
+        fused: bool = False,
+        maximize: bool = False,
+        _allow_empty_param_list: bool = False,
+    ):
+        self.defaults = {
+            "lr": lr,
+            "lr_decay": lr_decay,
+            "eps": eps,
+            "weight_decay": weight_decay,
+            "initial_accumulator_value": initial_accumulator_value,
+            "warmup_lr_multiplier": warmup_lr_multiplier,
+            "warmup_num_iters": warmup_num_iters,
+        }
+        self.coalesce_grad = coalesce_grad
+        self.foreach = foreach
+        self.fused = fused
+        self.maximize = maximize
+        self.state = torch.jit.annotate(Dict[torch.Tensor, Dict[str, torch.Tensor]], {})
+
+        if len(params) == 0 and not _allow_empty_param_list:
+            raise ValueError("optimizer got an empty parameter list")
+
+        # NOTE: we only have one param_group and don't allow user to add additional
+        # param group as it's not a common use case.
+        self.param_group = {"params": params}
+
+        # TODO: no union or any types in TorchScript, make step a scalar tensor instead
+        # This is also needed by if we want to share_memory on the step across processes
+        for p in self.param_group["params"]:
+            self.state[p] = {
+                "sum": torch.full_like(p.data, initial_accumulator_value),
+                "step": torch.tensor(0.0),
+            }
+
+    def step(self, gradients: List[Optional[Tensor]]):
+        params = self.param_group["params"]
+        params_with_grad = []
+        grads = []
+        state_sums = []
+        state_steps: List[Tensor] = []
+
+        if len(params) != len(gradients):
+            raise ValueError(
+                "the gradients passed in does not equal to the size of the parameters!"
+                + f"Params length: {len(params)}. "
+                + f"Gradients length: {len(gradients)}"
+            )
+
+        has_sparse_grad, has_complex = False, False
+        for param, gradient in zip(self.param_group["params"], gradients):
+            if gradient is not None:
+                has_sparse_grad |= gradient.is_sparse
+                has_complex |= torch.is_complex(param)
+                params_with_grad.append(param)
+                grads.append(gradient)
+                state = self.state[param]
+                state_sums.append(state["sum"])
+                state_steps.append(state["step"])
+
+        with torch.no_grad():
+            F.adagrad(
+                params,
+                grads,
+                state_sums,
+                state_steps,
+                lr=self.defaults["lr"],
+                weight_decay=self.defaults["weight_decay"],
+                lr_decay=self.defaults["lr_decay"],
+                eps=self.defaults["eps"],
+                has_sparse_grad=has_sparse_grad,
+                foreach=self.foreach,
+                maximize=self.maximize,
+                has_complex=has_complex,
+                fused=self.fused,
+                grad_scale=None,
+                found_inf=None,
+            )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/functional_adam.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/functional_adam.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ed271765170c67dca529cd65b11cb79275bfaba
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/functional_adam.py
@@ -0,0 +1,198 @@
+# mypy: allow-untyped-defs
+from typing import Dict, List, Optional, Tuple
+
+import torch
+import torch.optim._functional as F
+from torch import Tensor
+
+
+__all__: List[str] = []
+
+
+# Define a TorchScript compatible Functional Adam Optimizer
+# where we use these optimizer in a functional way.
+# Instead of using the `param.grad` when updating parameters,
+# we explicitly allow the distributed optimizer pass gradients to
+# the `step` function. In this way, we could separate the gradients
+# and parameters and allow multithreaded trainer to update the
+# parameters without data traces on accumulating to the same .grad.
+# NOTE: This should be only used by distributed optimizer internals
+# and not meant to expose to the user.
+@torch.jit.script
+class _FunctionalAdam:
+    def __init__(
+        self,
+        params: List[Tensor],
+        lr: float = 1e-3,
+        betas: Tuple[float, float] = (0.9, 0.999),
+        eps: float = 1e-8,
+        weight_decay: float = 0.0,
+        amsgrad: bool = False,
+        maximize: bool = False,
+        foreach: bool = False,
+        fused: bool = False,
+        _allow_empty_param_list: bool = False,
+    ):
+        if not 0.0 <= lr:
+            raise ValueError(f"Invalid learning rate: {lr}")
+        if not 0.0 <= eps:
+            raise ValueError(f"Invalid epsilon value: {eps}")
+        if not 0.0 <= betas[0] < 1.0:
+            raise ValueError(f"Invalid beta parameter at index 0: {betas[0]}")
+        if not 0.0 <= betas[1] < 1.0:
+            raise ValueError(f"Invalid beta parameter at index 1: {betas[1]}")
+        if not 0.0 <= weight_decay:
+            raise ValueError(f"Invalid weight_decay value: {weight_decay}")
+
+        self.defaults = {
+            "lr": lr,
+            "eps": eps,
+            "beta1": betas[0],
+            "beta2": betas[1],
+            "weight_decay": weight_decay,
+        }
+        self.amsgrad = amsgrad
+        self.maximize = maximize
+        self.foreach = foreach
+        self.fused = fused
+        self.state = torch.jit.annotate(Dict[torch.Tensor, Dict[str, torch.Tensor]], {})
+
+        if len(params) == 0 and not _allow_empty_param_list:
+            raise ValueError("optimizer got an empty parameter list")
+
+        # NOTE: we only have one param_group and don't allow user to add additional
+        # param group as it's not a common use case.
+        self.param_group = {"params": params}
+
+    def step_param(self, param: Tensor, grad: Optional[Tensor]):
+        """
+        Similar to step, but operates on a single parameter and optionally a
+        gradient tensor.
+        """
+        params_with_grad = []
+        grads = []
+        exp_avgs = []
+        exp_avg_sqs = []
+        max_exp_avg_sqs = []
+        state_steps: List[Tensor] = []
+        has_complex = torch.is_complex(param)
+        if grad is not None:
+            params_with_grad.append(param)
+            grads.append(grad)
+        if param not in self.state:
+            self.state[param] = {}
+            state = self.state[param]
+            state["step"] = torch.tensor(0.0)
+            state["exp_avg"] = torch.zeros_like(
+                param, memory_format=torch.preserve_format
+            )
+            state["exp_avg_sq"] = torch.zeros_like(
+                param, memory_format=torch.preserve_format
+            )
+            if self.amsgrad:
+                state["max_exp_avg_sq"] = torch.zeros_like(
+                    param, memory_format=torch.preserve_format
+                )
+
+        state = self.state[param]
+        exp_avgs.append(state["exp_avg"])
+        exp_avg_sqs.append(state["exp_avg_sq"])
+
+        if self.amsgrad:
+            max_exp_avg_sqs.append(state["max_exp_avg_sq"])
+
+        state_steps.append(state["step"])
+        with torch.no_grad():
+            F.adam(
+                params_with_grad,
+                grads,
+                exp_avgs,
+                exp_avg_sqs,
+                max_exp_avg_sqs,
+                state_steps,
+                amsgrad=self.amsgrad,
+                has_complex=has_complex,
+                maximize=self.maximize,
+                beta1=self.defaults["beta1"],
+                beta2=self.defaults["beta2"],
+                lr=self.defaults["lr"],
+                weight_decay=self.defaults["weight_decay"],
+                eps=self.defaults["eps"],
+                foreach=self.foreach,
+                fused=self.fused,
+                grad_scale=None,
+                found_inf=None,
+            )
+
+    def step(self, gradients: List[Optional[Tensor]]):
+        params = self.param_group["params"]
+        params_with_grad = []
+        grads = []
+        exp_avgs = []
+        exp_avg_sqs = []
+        max_exp_avg_sqs = []
+        state_steps: List[Tensor] = []
+        has_complex = False
+
+        if len(params) != len(gradients):
+            raise ValueError(
+                "the gradients passed in does not equal to the size of the parameters!"
+                + f"Params length: {len(params)}. "
+                + f"Gradients length: {len(gradients)}"
+            )
+
+        for param, gradient in zip(self.param_group["params"], gradients):
+            if gradient is not None:
+                has_complex |= torch.is_complex(param)
+                params_with_grad.append(param)
+                grads.append(gradient)
+                # Lazy state initialization
+                if param not in self.state:
+                    self.state[param] = {}
+                    state = self.state[param]
+                    state["step"] = torch.tensor(0.0)
+                    # Exponential moving average of gradient values
+                    state["exp_avg"] = torch.zeros_like(
+                        param, memory_format=torch.preserve_format
+                    )
+                    # Exponential moving average of squared gradient values
+                    state["exp_avg_sq"] = torch.zeros_like(
+                        param, memory_format=torch.preserve_format
+                    )
+                    if self.amsgrad:
+                        # Maintains max of all exp. moving avg. of sq. grad. values
+                        state["max_exp_avg_sq"] = torch.zeros_like(
+                            param, memory_format=torch.preserve_format
+                        )
+
+                state = self.state[param]
+
+                exp_avgs.append(state["exp_avg"])
+                exp_avg_sqs.append(state["exp_avg_sq"])
+
+                if self.amsgrad:
+                    max_exp_avg_sqs.append(state["max_exp_avg_sq"])
+
+                state_steps.append(state["step"])
+
+        with torch.no_grad():
+            F.adam(
+                params_with_grad,
+                grads,
+                exp_avgs,
+                exp_avg_sqs,
+                max_exp_avg_sqs,
+                state_steps,
+                amsgrad=self.amsgrad,
+                has_complex=has_complex,
+                maximize=self.maximize,
+                beta1=self.defaults["beta1"],
+                beta2=self.defaults["beta2"],
+                lr=self.defaults["lr"],
+                weight_decay=self.defaults["weight_decay"],
+                eps=self.defaults["eps"],
+                foreach=self.foreach,
+                fused=self.fused,
+                grad_scale=None,
+                found_inf=None,
+            )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/functional_adamax.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/functional_adamax.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f1fdc0ccc02bea63c9d2a2a2ab22a72898d903d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/functional_adamax.py
@@ -0,0 +1,119 @@
+# mypy: allow-untyped-defs
+from typing import Dict, List, Optional, Tuple
+
+import torch
+import torch.optim._functional as F
+from torch import Tensor
+
+
+__all__: List[str] = []
+
+
+# Define a TorchScript compatible Functional Adamax Optimizer
+# where we use these optimizer in a functional way.
+# Instead of using the `param.grad` when updating parameters,
+# we explicitly allow the distributed optimizer pass gradients to
+# the `step` function. In this way, we could separate the gradients
+# and parameters and allow multithreaded trainer to update the
+# parameters without data traces on accumulating to the same .grad.
+# NOTE: This should be only used by distributed optimizer internals
+# and not meant to expose to the user.
+@torch.jit.script
+class _FunctionalAdamax:
+    def __init__(
+        self,
+        params: List[Tensor],
+        lr: float = 1e-3,
+        betas: Tuple[float, float] = (0.9, 0.999),
+        eps: float = 1e-8,
+        weight_decay: float = 0.0,
+        foreach: bool = False,
+        maximize: bool = False,
+        _allow_empty_param_list: bool = False,
+    ):
+        if not 0.0 <= lr:
+            raise ValueError(f"Invalid learning rate: {lr}")
+        if not 0.0 <= eps:
+            raise ValueError(f"Invalid epsilon value: {eps}")
+        if not 0.0 <= betas[0] < 1.0:
+            raise ValueError(f"Invalid beta parameter at index 0: {betas[0]}")
+        if not 0.0 <= betas[1] < 1.0:
+            raise ValueError(f"Invalid beta parameter at index 1: {betas[1]}")
+        if not 0.0 <= weight_decay:
+            raise ValueError(f"Invalid weight_decay value: {weight_decay}")
+
+        self.defaults = {
+            "lr": lr,
+            "eps": eps,
+            "beta1": betas[0],
+            "beta2": betas[1],
+            "weight_decay": weight_decay,
+        }
+        self.foreach = foreach
+        self.maximize = maximize
+        self.state = torch.jit.annotate(Dict[torch.Tensor, Dict[str, torch.Tensor]], {})
+
+        if len(params) == 0 and not _allow_empty_param_list:
+            raise ValueError("optimizer got an empty parameter list")
+
+        # NOTE: we only have one param_group and don't allow user to add additional
+        # param group as it's not a common use case.
+        self.param_group = {"params": params}
+
+    def step(self, gradients: List[Optional[Tensor]]):
+        params = self.param_group["params"]
+        params_with_grad = []
+        grads = []
+        exp_avgs = []
+        exp_infs = []
+        state_steps: List[Tensor] = []
+
+        if len(params) != len(gradients):
+            raise ValueError(
+                "the gradients passed in does not equal to the size of the parameters!"
+                + f"Params length: {len(params)}. "
+                + f"Gradients length: {len(gradients)}"
+            )
+
+        has_complex = False
+        for param, gradient in zip(self.param_group["params"], gradients):
+            if gradient is not None:
+                has_complex |= torch.is_complex(param)
+                params_with_grad.append(param)
+                grads.append(gradient)
+                # Lazy state initialization
+                if param not in self.state:
+                    self.state[param] = {}
+                    state = self.state[param]
+                    state["step"] = torch.tensor(0.0)
+                    # Exponential moving average of gradient values
+                    state["exp_avg"] = torch.zeros_like(
+                        param, memory_format=torch.preserve_format
+                    )
+                    # Exponential moving average of squared gradient values
+                    state["exp_inf"] = torch.zeros_like(
+                        param, memory_format=torch.preserve_format
+                    )
+
+                state = self.state[param]
+
+                exp_avgs.append(state["exp_avg"])
+                exp_infs.append(state["exp_inf"])
+                state_steps.append(state["step"])
+
+        with torch.no_grad():
+            F.adamax(
+                params_with_grad,
+                grads,
+                exp_avgs,
+                exp_infs,
+                state_steps,
+                eps=self.defaults["eps"],
+                beta1=self.defaults["beta1"],
+                beta2=self.defaults["beta2"],
+                lr=self.defaults["lr"],
+                weight_decay=self.defaults["weight_decay"],
+                foreach=self.foreach,
+                maximize=self.maximize,
+                has_complex=has_complex,
+            )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/functional_adamw.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/functional_adamw.py
new file mode 100644
index 0000000000000000000000000000000000000000..d3f1f80e9209bdb26e45221d7ba0252a3f49c79a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/functional_adamw.py
@@ -0,0 +1,199 @@
+# mypy: allow-untyped-defs
+from typing import Dict, List, Optional, Tuple
+
+import torch
+import torch.optim._functional as F
+from torch import Tensor
+
+
+__all__: List[str] = []
+
+
+# Define a TorchScript compatible Functional AdamW Optimizer
+# where we use these optimizer in a functional way.
+# Instead of using the `param.grad` when updating parameters,
+# we explicitly allow the distributed optimizer pass gradients to
+# the `step` function. In this way, we could separate the gradients
+# and parameters and allow multithreaded trainer to update the
+# parameters without data traces on accumulating to the same .grad.
+# NOTE: This should be only used by distributed optimizer internals
+# and not meant to expose to the user.
+@torch.jit.script
+class _FunctionalAdamW:
+    def __init__(
+        self,
+        params: List[Tensor],
+        lr: float = 1e-3,
+        betas: Tuple[float, float] = (0.9, 0.999),
+        eps: float = 1e-8,
+        weight_decay: float = 1e-2,
+        amsgrad: bool = False,
+        maximize: bool = False,
+        foreach: bool = False,
+        fused: bool = False,
+        _allow_empty_param_list: bool = False,
+    ):
+        if not 0.0 <= lr:
+            raise ValueError(f"Invalid learning rate: {lr}")
+        if not 0.0 <= eps:
+            raise ValueError(f"Invalid epsilon value: {eps}")
+        if not 0.0 <= betas[0] < 1.0:
+            raise ValueError(f"Invalid beta parameter at index 0: {betas[0]}")
+        if not 0.0 <= betas[1] < 1.0:
+            raise ValueError(f"Invalid beta parameter at index 1: {betas[1]}")
+        if not 0.0 <= weight_decay:
+            raise ValueError(f"Invalid weight_decay value: {weight_decay}")
+
+        self.defaults = {
+            "lr": lr,
+            "eps": eps,
+            "beta1": betas[0],
+            "beta2": betas[1],
+            "weight_decay": weight_decay,
+        }
+        self.amsgrad = amsgrad
+        self.maximize = maximize
+        self.foreach = foreach
+        self.fused = fused
+        self.state = torch.jit.annotate(Dict[torch.Tensor, Dict[str, torch.Tensor]], {})
+
+        if len(params) == 0 and not _allow_empty_param_list:
+            raise ValueError("optimizer got an empty parameter list")
+
+        # NOTE: we only have one param_group and don't allow user to add additional
+        # param group as it's not a common use case.
+        self.param_group = {"params": params}
+
+    def step_param(self, param: Tensor, grad: Optional[Tensor]):
+        params_with_grad = []
+        grads = []
+        exp_avgs = []
+        exp_avg_sqs = []
+        max_exp_avg_sqs = []
+        state_steps: List[Tensor] = []
+        has_complex = torch.is_complex(param)
+        if grad is not None:
+            params_with_grad.append(param)
+            grads.append(grad)
+        # Lazy state initialization
+        if param not in self.state:
+            self.state[param] = {}
+            state = self.state[param]
+            state["step"] = torch.tensor(0.0)
+            # Exponential moving average of gradient values
+            state["exp_avg"] = torch.zeros_like(
+                param, memory_format=torch.preserve_format
+            )
+            # Exponential moving average of squared gradient values
+            state["exp_avg_sq"] = torch.zeros_like(
+                param, memory_format=torch.preserve_format
+            )
+            if self.amsgrad:
+                # Maintains max of all exp. moving avg. of sq. grad. values
+                state["max_exp_avg_sq"] = torch.zeros_like(
+                    param, memory_format=torch.preserve_format
+                )
+
+        state = self.state[param]
+
+        exp_avgs.append(state["exp_avg"])
+        exp_avg_sqs.append(state["exp_avg_sq"])
+
+        if self.amsgrad:
+            max_exp_avg_sqs.append(state["max_exp_avg_sq"])
+
+        state_steps.append(state["step"])
+        with torch.no_grad():
+            F.adamw(
+                params_with_grad,
+                grads,
+                exp_avgs,
+                exp_avg_sqs,
+                max_exp_avg_sqs,
+                state_steps,
+                amsgrad=self.amsgrad,
+                maximize=self.maximize,
+                beta1=self.defaults["beta1"],
+                beta2=self.defaults["beta2"],
+                lr=self.defaults["lr"],
+                weight_decay=self.defaults["weight_decay"],
+                eps=self.defaults["eps"],
+                foreach=self.foreach,
+                fused=self.fused,
+                grad_scale=None,
+                found_inf=None,
+                has_complex=has_complex,
+            )
+
+    def step(self, gradients: List[Optional[Tensor]]):
+        params = self.param_group["params"]
+        params_with_grad = []
+        grads = []
+        exp_avgs = []
+        exp_avg_sqs = []
+        max_exp_avg_sqs = []
+        state_steps: List[Tensor] = []
+
+        if len(params) != len(gradients):
+            raise ValueError(
+                "the gradients passed in does not equal to the size of the parameters!"
+                + f"Params length: {len(params)}. "
+                + f"Gradients length: {len(gradients)}"
+            )
+
+        has_complex = False
+        for param, gradient in zip(self.param_group["params"], gradients):
+            if gradient is not None:
+                has_complex |= torch.is_complex(param)
+                params_with_grad.append(param)
+                grads.append(gradient)
+                # Lazy state initialization
+                if param not in self.state:
+                    self.state[param] = {}
+                    state = self.state[param]
+                    state["step"] = torch.tensor(0.0)
+                    # Exponential moving average of gradient values
+                    state["exp_avg"] = torch.zeros_like(
+                        param, memory_format=torch.preserve_format
+                    )
+                    # Exponential moving average of squared gradient values
+                    state["exp_avg_sq"] = torch.zeros_like(
+                        param, memory_format=torch.preserve_format
+                    )
+                    if self.amsgrad:
+                        # Maintains max of all exp. moving avg. of sq. grad. values
+                        state["max_exp_avg_sq"] = torch.zeros_like(
+                            param, memory_format=torch.preserve_format
+                        )
+
+                state = self.state[param]
+
+                exp_avgs.append(state["exp_avg"])
+                exp_avg_sqs.append(state["exp_avg_sq"])
+
+                if self.amsgrad:
+                    max_exp_avg_sqs.append(state["max_exp_avg_sq"])
+
+                state_steps.append(state["step"])
+
+        with torch.no_grad():
+            F.adamw(
+                params_with_grad,
+                grads,
+                exp_avgs,
+                exp_avg_sqs,
+                max_exp_avg_sqs,
+                state_steps,
+                amsgrad=self.amsgrad,
+                maximize=self.maximize,
+                beta1=self.defaults["beta1"],
+                beta2=self.defaults["beta2"],
+                lr=self.defaults["lr"],
+                weight_decay=self.defaults["weight_decay"],
+                eps=self.defaults["eps"],
+                foreach=self.foreach,
+                fused=self.fused,
+                grad_scale=None,
+                found_inf=None,
+                has_complex=has_complex,
+            )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/functional_rmsprop.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/functional_rmsprop.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a03e8e9f462f8e95316152031579210725e215a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/functional_rmsprop.py
@@ -0,0 +1,126 @@
+# mypy: allow-untyped-defs
+from typing import Dict, List, Optional
+
+import torch
+import torch.optim._functional as F
+from torch import Tensor
+
+
+__all__: List[str] = []
+
+
+# Define a TorchScript compatible Functional RMSprop Optimizer
+# where we use these optimizer in a functional way.
+# Instead of using the `param.grad` when updating parameters,
+# we explicitly allow the distributed optimizer pass gradients to
+# the `step` function. In this way, we could separate the gradients
+# and parameters and allow multithreaded trainer to update the
+# parameters without data traces on accumulating to the same .grad.
+# NOTE: This should be only used by distributed optimizer internals
+# and not meant to expose to the user.
+@torch.jit.script
+class _FunctionalRMSprop:
+    def __init__(
+        self,
+        params: List[Tensor],
+        lr: float = 1e-2,
+        alpha: float = 0.99,
+        eps: float = 1e-8,
+        weight_decay: float = 0.0,
+        momentum: float = 0.0,
+        centered: bool = False,
+        foreach: bool = False,
+        maximize: bool = False,
+        _allow_empty_param_list: bool = False,
+    ):
+        self.defaults = {
+            "lr": lr,
+            "alpha": alpha,
+            "eps": eps,
+            "weight_decay": weight_decay,
+            "momentum": momentum,
+        }
+        self.centered = centered
+        self.foreach = foreach
+        self.maximize = maximize
+
+        if len(params) == 0 and not _allow_empty_param_list:
+            raise ValueError("optimizer got an empty parameter list")
+
+        # NOTE: we only have one param_group and don't allow user to add additional
+        # param group as it's not a common use case.
+        self.param_group = {"params": params}
+
+        self.state = torch.jit.annotate(Dict[torch.Tensor, Dict[str, torch.Tensor]], {})
+
+    def step(self, gradients: List[Optional[Tensor]]):
+        params = self.param_group["params"]
+        params_with_grad = []
+        grads = []
+        square_avgs = []
+        grad_avgs = []
+        momentum_buffer_list = []
+        state_steps = []
+        lr = self.defaults["lr"]
+        alpha = self.defaults["alpha"]
+        eps = self.defaults["eps"]
+        momentum = self.defaults["momentum"]
+        weight_decay = self.defaults["weight_decay"]
+
+        if len(params) != len(gradients):
+            raise ValueError(
+                "the gradients passed in does not equal to the size of the parameters!"
+                + f"Params length: {len(params)}. "
+                + f"Gradients length: {len(gradients)}"
+            )
+
+        has_complex = False
+        for param, gradient in zip(params, gradients):
+            if gradient is not None:
+                has_complex |= torch.is_complex(param)
+                params_with_grad.append(param)
+                grads.append(gradient)
+                # Lazy state initialization
+                if param not in self.state:
+                    self.state[param] = {}
+                    state = self.state[param]
+                    state["step"] = torch.tensor(0.0)
+                    state["square_avg"] = torch.zeros_like(
+                        param, memory_format=torch.preserve_format
+                    )
+                    if momentum > 0:
+                        state["momentum_buffer"] = torch.zeros_like(
+                            param, memory_format=torch.preserve_format
+                        )
+                    if self.centered:
+                        state["grad_avg"] = torch.zeros_like(
+                            param, memory_format=torch.preserve_format
+                        )
+
+                state = self.state[param]
+                square_avgs.append(state["square_avg"])
+                if momentum > 0:
+                    momentum_buffer_list.append(state["momentum_buffer"])
+                if self.centered:
+                    grad_avgs.append(state["grad_avg"])
+
+                state_steps.append(state["step"])
+
+        with torch.no_grad():
+            F.rmsprop(
+                params_with_grad,
+                grads,
+                square_avgs,
+                grad_avgs,
+                momentum_buffer_list,
+                state_steps,
+                lr=lr,
+                alpha=alpha,
+                eps=eps,
+                weight_decay=weight_decay,
+                momentum=momentum,
+                centered=self.centered,
+                foreach=self.foreach,
+                maximize=self.maximize,
+                has_complex=has_complex,
+            )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/functional_rprop.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/functional_rprop.py
new file mode 100644
index 0000000000000000000000000000000000000000..615015a95a316b1a56cdfb9f845b55f80d9d3a65
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/functional_rprop.py
@@ -0,0 +1,103 @@
+# mypy: allow-untyped-defs
+from typing import Dict, List, Optional, Tuple
+
+import torch
+import torch.optim._functional as F
+from torch import Tensor
+
+
+__all__: List[str] = []
+
+
+# Define a TorchScript compatible Functional Rprop Optimizer
+# where we use these optimizer in a functional way.
+# Instead of using the `param.grad` when updating parameters,
+# we explicitly allow the distributed optimizer pass gradients to
+# the `step` function. In this way, we could separate the gradients
+# and parameters and allow multithreaded trainer to update the
+# parameters without data traces on accumulating to the same .grad.
+# NOTE: This should be only used by distributed optimizer internals
+# and not meant to expose to the user.
+@torch.jit.script
+class _FunctionalRprop:
+    def __init__(
+        self,
+        params: List[Tensor],
+        lr: float = 1e-2,
+        etas: Tuple[float, float] = (0.5, 1.2),
+        step_sizes: Tuple[float, float] = (1e-6, 50),
+        foreach: bool = False,
+        maximize: bool = False,
+        _allow_empty_param_list: bool = False,
+    ):
+        self.defaults = {
+            "lr": lr,
+        }
+        self.etas = etas
+        self.step_sizes = step_sizes
+        self.foreach = foreach
+        self.maximize = maximize
+
+        if len(params) == 0 and not _allow_empty_param_list:
+            raise ValueError("optimizer got an empty parameter list")
+
+        # NOTE: we only have one param_group and don't allow user to add additional
+        # param group as it's not a common use case.
+        self.param_group = {"params": params}
+
+        self.state = torch.jit.annotate(Dict[torch.Tensor, Dict[str, torch.Tensor]], {})
+
+    def step(self, gradients: List[Optional[Tensor]]):
+        params = self.param_group["params"]
+        params_with_grad = []
+        grads = []
+        prevs = []
+        step_sizes = []
+        state_steps = []
+        lr = self.defaults["lr"]
+        etaminus, etaplus = self.etas
+        step_size_min, step_size_max = self.step_sizes
+
+        if len(params) != len(gradients):
+            raise ValueError(
+                "the gradients passed in does not equal to the size of the parameters!"
+                + f"Params length: {len(params)}. "
+                + f"Gradients length: {len(gradients)}"
+            )
+
+        has_complex = False
+        for param, gradient in zip(params, gradients):
+            if gradient is not None:
+                has_complex |= torch.is_complex(param)
+                params_with_grad.append(param)
+                grads.append(gradient)
+                # Lazy state initialization
+                if param not in self.state:
+                    self.state[param] = {}
+                    state = self.state[param]
+                    state["step"] = torch.tensor(0.0)
+                    state["prev"] = torch.zeros_like(
+                        param, memory_format=torch.preserve_format
+                    )
+                    state["step_size"] = torch.full_like(gradient, lr)
+
+                state = self.state[param]
+                prevs.append(state["prev"])
+                step_sizes.append(state["step_size"])
+                state_steps.append(state["step"])
+
+        with torch.no_grad():
+            F.rprop(
+                params_with_grad,
+                grads,
+                prevs,
+                step_sizes,
+                state_steps,
+                step_size_min=step_size_min,
+                step_size_max=step_size_max,
+                etaminus=etaminus,
+                etaplus=etaplus,
+                foreach=self.foreach,
+                maximize=self.maximize,
+                has_complex=has_complex,
+            )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/functional_sgd.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/functional_sgd.py
new file mode 100644
index 0000000000000000000000000000000000000000..32381855db6b5500a073f6cdafed8d3b1e3201d9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/functional_sgd.py
@@ -0,0 +1,162 @@
+# mypy: allow-untyped-defs
+from typing import Dict, List, Optional
+
+import torch
+import torch.optim._functional as F
+from torch import Tensor
+
+
+__all__: List[str] = []
+
+
+# Define a TorchScript compatible Functional SGD Optimizer
+# where we use these optimizer in a functional way.
+# Instead of using the `param.grad` when updating parameters,
+# we explicitly allow the distributed optimizer pass gradients to
+# the `step` function. In this way, we could separate the gradients
+# and parameters and allow multithreaded trainer to update the
+# parameters without data traces on accumulating to the same .grad.
+# NOTE: This should be only used by distributed optimizer internals
+# and not meant to expose to the user.
+@torch.jit.script
+class _FunctionalSGD:
+    def __init__(
+        self,
+        params: List[Tensor],
+        lr: float = 1e-2,
+        momentum: float = 0.0,
+        dampening: float = 0.0,
+        weight_decay: float = 0.0,
+        nesterov: bool = False,
+        maximize: bool = False,
+        foreach: bool = False,
+        fused: bool = False,
+        _allow_empty_param_list: bool = False,
+    ):
+        self.defaults = {
+            "lr": lr,
+            "momentum": momentum,
+            "dampening": dampening,
+            "weight_decay": weight_decay,
+        }
+        self.nesterov = nesterov
+        self.maximize = maximize
+        self.foreach = foreach
+        self.fused = fused
+        self.state = torch.jit.annotate(Dict[torch.Tensor, Dict[str, torch.Tensor]], {})
+
+        if len(params) == 0 and not _allow_empty_param_list:
+            raise ValueError("optimizer got an empty parameter list")
+
+        # NOTE: we only have one param_group and don't allow user to add additional
+        # param group as it's not a common use case.
+        self.param_group = {"params": params}
+
+    def step_param(self, param: Tensor, grad: Optional[Tensor]):
+        """Similar to self.step, but operates on a single parameter and
+        its gradient.
+        """
+        # TODO: Once step_param interface is robust, refactor step to call
+        # step param on each param.
+        weight_decay = self.defaults["weight_decay"]
+        momentum = self.defaults["momentum"]
+        dampening = self.defaults["dampening"]
+        lr = self.defaults["lr"]
+        params = [param]
+        momentum_buffer_list: List[Optional[Tensor]] = []
+        grads = []
+
+        has_sparse_grad = False
+        if grad is not None:
+            grads.append(grad)
+            if grad.is_sparse:
+                has_sparse_grad = True
+            if param not in self.state:
+                self.state[param] = {}
+            state = self.state[param]
+            if "momentum_buffer" not in state:
+                momentum_buffer_list.append(None)
+            else:
+                momentum_buffer_list.append(state["momentum_buffer"])
+
+        with torch.no_grad():
+            F.sgd(
+                params,
+                grads,
+                momentum_buffer_list,
+                weight_decay=weight_decay,
+                momentum=momentum,
+                lr=lr,
+                dampening=dampening,
+                nesterov=self.nesterov,
+                maximize=self.maximize,
+                has_sparse_grad=has_sparse_grad,
+                foreach=self.foreach,
+                fused=self.fused,
+                grad_scale=None,
+                found_inf=None,
+            )
+        # update momentum_buffer in state
+        state = self.state[param]
+        momentum_buffer = momentum_buffer_list[0]
+        if momentum_buffer is not None:
+            state["momentum_buffer"] = momentum_buffer
+
+    def step(self, gradients: List[Optional[Tensor]]):
+        params = self.param_group["params"]
+        params_with_grad = []
+        grads = []
+        momentum_buffer_list: List[Optional[Tensor]] = []
+        lr = self.defaults["lr"]
+        weight_decay = self.defaults["weight_decay"]
+        momentum = self.defaults["momentum"]
+        dampening = self.defaults["dampening"]
+
+        if len(params) != len(gradients):
+            raise ValueError(
+                "the gradients passed in does not equal to the size of the parameters!"
+                + f"Params length: {len(params)}. "
+                + f"Gradients length: {len(gradients)}"
+            )
+
+        has_sparse_grad = False
+        for param, gradient in zip(params, gradients):
+            if gradient is not None:
+                params_with_grad.append(param)
+                grads.append(gradient)
+                if gradient.is_sparse:
+                    has_sparse_grad = True
+
+                if param not in self.state:
+                    self.state[param] = {}
+
+                state = self.state[param]
+                if "momentum_buffer" not in state:
+                    momentum_buffer_list.append(None)
+                else:
+                    momentum_buffer_list.append(state["momentum_buffer"])
+
+        with torch.no_grad():
+            F.sgd(
+                params_with_grad,
+                grads,
+                momentum_buffer_list,
+                weight_decay=weight_decay,
+                momentum=momentum,
+                lr=lr,
+                dampening=dampening,
+                nesterov=self.nesterov,
+                maximize=self.maximize,
+                has_sparse_grad=has_sparse_grad,
+                foreach=self.foreach,
+                fused=self.fused,
+                grad_scale=None,
+                found_inf=None,
+            )
+
+        # update momentum_buffers in state
+        for i, p in enumerate(params_with_grad):
+            state = self.state[p]
+            momentum_buffer = momentum_buffer_list[i]
+            if momentum_buffer is not None:
+                state["momentum_buffer"] = momentum_buffer
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/named_optimizer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/named_optimizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e0b539b14826470aaa5db10d8cc95b5401642d6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/named_optimizer.py
@@ -0,0 +1,341 @@
+# mypy: allow-untyped-defs
+import logging
+import warnings
+from copy import deepcopy
+from typing import (
+    Any,
+    Callable,
+    Collection,
+    Dict,
+    List,
+    Mapping,
+    Optional,
+    overload,
+    Union,
+)
+
+import torch
+import torch.nn as nn
+from torch import optim
+from torch.distributed._shard.sharded_tensor import ShardedTensor
+from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
+
+
+__all__: List[str] = []
+
+logger = logging.getLogger(__name__)
+
+
+class _NamedOptimizer(optim.Optimizer):
+    """
+    ``_NamedOptimizer`` takes a dict of parameters and exposes ``state_dict`` by parameter key.
+
+    We replace the original key (number) in an optim to the
+    fully qualified name (FQN) string. User can initialize the optim as they
+    initialize a PyTorch optim, the only difference is that they also need to
+    pass in the FQN of each parameters.
+
+    Args:
+        named_parameters (Mapping[str, Union[torch.Tensor, ShardedTensor]]):
+            Mapping from FQN to parameter.
+        optimizer_class (optim.Optimizer):
+            The class of optimizer to instantiate.
+        param_groups (Collection[Mapping[str, Any]]):
+            `param_groups` to pass to optimizer if specified.
+            The key of the inner map needs to be FQNs.
+            Default: None
+        module (nn.Module): the module whose parameters to updated
+            by the optimizer.
+        args: arguments to pass to the optimizer constructor.
+        kwargs: arguments to pass to the optimizer constructor.
+
+    Example::
+        >>> # xdoctest: +SKIP("distributed")
+        >>> from torch import optim
+        >>> from torch.distributed.optim import _NamedOptimizer
+        >>>
+        >>> # Define the named optimizer.
+        >>> m = Model(...)
+        >>> named_optim = _NamedOptimizer(m.named_parameters(), optim.SGD)
+        >>> # Forward pass + backward pass.
+        >>> named_optim.step()
+        >>> ...
+        >>> # Call state_dict for the named optimizer returns a FQN state_dict.
+        >>> named_optim.state_dict()
+
+    Warning: This API is still in development and subject to change.
+
+    TODO: Add tutorial for _NamedOptimizer.
+    TODO: Add documentation in the docstring for the public attributes
+          like self.param_groups and self.named_parameters.
+    """
+
+    def __init__(
+        self,
+        named_parameters: Mapping[str, Union[torch.Tensor, ShardedTensor]],
+        optimizer_class: optim.Optimizer,
+        param_groups: Optional[Collection[Mapping[str, Any]]] = None,
+        module: Optional[nn.Module] = None,
+        *args,
+        **kwargs,
+    ) -> None:
+        torch._C._log_api_usage_once("torch.distributed.optim._NamedOptimizer")
+        self.param_groups: Collection[Mapping[str, Any]] = param_groups  # type: ignore[assignment]
+        self._param_groups_check()
+        self.named_parameters = dict(named_parameters)
+        params_for_optimizer = (
+            self.named_parameters.values() if param_groups is None else param_groups
+        )
+        self._optimizer = optimizer_class(  # type: ignore[operator]
+            params_for_optimizer,
+            *args,
+            **kwargs,
+        )
+        self.module = module
+        if param_groups is None:
+            self.ordered_param_keys = list(self.named_parameters.keys())
+        else:
+            warnings.warn(
+                "Since we pass in param_groups, we will use param_groups to "
+                "initialize the optimizer, not all parameters of the module."
+            )
+            param_to_key = {param: key for key, param in self.named_parameters.items()}  # type: ignore[misc, has-type]
+            ordered_param_keys = []
+            for group in param_groups:
+                for param in group["params"]:
+                    if param not in param_to_key:
+                        raise ValueError(
+                            f"Expect param name {param} found in param group but is missing."
+                        )
+                    ordered_param_keys.append(param_to_key[param])
+            self.ordered_param_keys = ordered_param_keys
+        # Update param_groups from optimizer.
+        self.param_groups = self._optimizer.param_groups
+
+    def _param_groups_check(self):
+        if self.param_groups is not None:
+            for param_group in self.param_groups:
+                assert isinstance(param_group, dict), "param group must be a dict"
+                assert "params" in param_group, "param group must contain key params"
+                params = param_group["params"]
+                if isinstance(params, torch.Tensor):
+                    params = [params]
+                params = list(params)
+                for param in params:
+                    if not isinstance(param, torch.Tensor):
+                        raise TypeError(
+                            "optimizer can only optimize Tensors, "
+                            "but one of the params is " + torch.typename(param)
+                        )
+                param_group["params"] = params
+
+    def state_dict(self) -> Dict[str, Any]:
+        """
+        Return the ``state_dict`` of the optimizer.
+
+        Instead of using number to index
+        parameters, we will use module fully qualified name (FQN) as the key.
+        """
+        state_dict = self._optimizer.state_dict()
+        param_groups = state_dict["param_groups"]
+
+        ret_state = {
+            self.ordered_param_keys[st_key]: state_val
+            for st_key, state_val in state_dict["state"].items()
+        }
+
+        ret_groups = []
+        for group in param_groups:
+            param_keys = []
+            for param in group["params"]:
+                param_keys.append(self.ordered_param_keys[param])
+            ret_group = {"params": sorted(param_keys)}
+            for k, v in group.items():
+                if k != "params":
+                    ret_group[k] = deepcopy(v)
+            ret_groups.append(ret_group)
+
+        return self._post_state_dict({"state": ret_state, "param_groups": ret_groups})
+
+    @overload
+    def step(self, closure: None = ...) -> None:
+        ...
+
+    @overload
+    def step(self, closure: Callable[[], float]) -> float:
+        ...
+
+    def step(self, closure: Optional[Callable[[], float]] = None) -> Optional[float]:
+        """
+        Perform a single optimization step.
+
+        This will call :meth:`torch.optim.Optimizer.step` on the wrapped
+        optimizer.
+        """
+        return self._optimizer.step(closure=closure)
+
+    @property
+    def state(self) -> Mapping[torch.Tensor, Any]:  # type: ignore[override]
+        return self._optimizer.state
+
+    def load_state_dict(self, state_dict: Mapping[str, Any]) -> None:
+        """
+        Define the default behavior to load a state_dict for ``_NamedOptimizer``.
+
+        Sample Code
+        ```
+            my_model = MyModule()
+            optimizer = _NamedOptimizer(my_model.named_parameters(), Adagrad)
+            ...
+
+            optim_state_dict = optimizer.state_dict()
+            ...
+            ...
+
+            optimizer.load_state_dict(optim_state_dict)
+            ...
+        ```
+        Args:
+            state_dict (Dict[str, Any]) : A ``state_dict`` to load into the optimizer.
+                Note that this state dict update is performed in place.
+
+        .. note:: PyTorch is using lazy init to initialize the optim states.
+            So it is possible that there is no optim state when user call
+            ``load_state_dict`` and for ``_NamedOptimizer`` we make it stricter
+            that users can only call ``load_state_dict`` after the state is initialized.
+            By doing this, we can validate the optim ``state_dict`` to be loaded.
+        """
+        new_state_dict = self._optimizer.state_dict()
+        state_dict = self._pre_load_state_dict(state_dict)
+        state = state_dict["state"]
+        new_state = new_state_dict["state"]
+        if len(new_state) == 0:
+            raise ValueError(
+                "Expects the optim to be initialized before load but found not initialized."
+            )
+
+        for idx, param_key in enumerate(self.ordered_param_keys):
+            # When the conditional training is performed, not all parameters are updated in the optim.
+            if param_key not in state.keys():
+                continue
+            if len(state[param_key]) != len(new_state[idx]):
+                raise ValueError(
+                    f"Expects equal length as {len(new_state[idx])} for parameter {param_key} but found: {len(state[param_key])}"
+                )
+            # Iterate through all optimizer states.
+            for state_key, state_val in new_state[idx].items():
+                if state_key not in state[param_key]:
+                    raise ValueError(
+                        f"Expects state {state_key} for parameter {param_key} but not found."
+                    )
+
+                src_state_val = state[param_key][state_key]
+                if isinstance(state_val, ShardedTensor):
+                    assert isinstance(src_state_val, ShardedTensor)
+                    num_shards = len(state_val.local_shards())
+                    num_new_shards = len(src_state_val.local_shards())
+                    if num_shards != num_new_shards:
+                        raise ValueError(
+                            f"Expects equal number of shards as {num_new_shards} but found {num_shards} for {param_key}/{state_key}"
+                        )
+                    for shard, src_shard in zip(
+                        state_val.local_shards(), src_state_val.local_shards()
+                    ):
+                        shard.tensor.detach().copy_(src_shard.tensor)
+                elif isinstance(state_val, torch.Tensor):
+                    assert isinstance(src_state_val, torch.Tensor)
+                    state_val.detach().copy_(src_state_val)
+                else:
+                    new_state[idx][state_key] = deepcopy(src_state_val)
+
+        # Load param_groups of state_dict
+        src_param_groups = state_dict["param_groups"]
+        new_param_groups = new_state_dict["param_groups"]
+
+        src_group_map = {}
+        for group in src_param_groups:
+            param_keys = list(group["params"])
+            src_group_map[_gen_param_group_key(param_keys)] = group
+        new_group_map = {}
+        for new_group in new_param_groups:
+            param_keys = []
+            for param_key in new_group["params"]:
+                param_keys.append(self.ordered_param_keys[param_key])  # type: ignore[call-overload]
+            new_group_map[_gen_param_group_key(param_keys)] = new_group
+        for group_key, new_group in new_group_map.items():
+            # When not all parameters are used in training or receive gradient, aka., not all parameters
+            # would be in the param_group. Thus we skip the group_key here.
+            if group_key not in src_group_map:
+                continue
+            src_group = src_group_map[group_key]
+            if len(src_group) != len(new_group):
+                raise ValueError(
+                    f"Expects equal param_group size as {len(new_group)} for group {group_key} but found {len(src_group)}."
+                )
+            for k in src_group:
+                if k not in new_group:
+                    raise ValueError(
+                        f"Expects group key {k} to be in group {group_key} in `state_dict` but is missing."
+                    )
+                if k != "params":
+                    new_group[k] = deepcopy(src_group[k])
+
+        self._optimizer.load_state_dict(new_state_dict)
+
+    def add_param_group(self, param_group: Mapping[str, Any]) -> None:
+        """
+        Add a param group to the :class:`_NamedOptimizer` s `param_groups`.
+
+        Warning: This API is still in development and subject to change.
+        """
+        assert isinstance(param_group, dict), "param group must be a dict"
+
+        params = param_group["params"]
+        if isinstance(params, torch.Tensor):
+            param_group["params"] = [params]
+        else:
+            param_group["params"] = list(params)
+
+        param_to_key = {param: key for key, param in self.named_parameters.items()}  # type: ignore[misc, has-type]
+        for param in param_group["params"]:
+            if param not in param_to_key:
+                raise ValueError("some parameters are not in the module")
+            self.ordered_param_keys.append(param_to_key[param])
+
+        self._optimizer.add_param_group(param_group)
+        # Update param_groups from optimizer.
+        self.param_groups = self._optimizer.param_groups
+
+    def init_state(self) -> None:
+        """
+        Run a dummy optimizer step, which allows to initialize optimizer state because we do lazy init for most optimizers.
+
+        This allows doing in-place loading of optimizer state from a checkpoint.
+        """
+        for param in self.named_parameters.values():
+            if param.requires_grad:
+                t = torch.zeros_like(param)
+                param.grad = torch.autograd.Variable(t)
+        # Calling ``step`` will load the initial state for optimizer states.
+        self.step(closure=None)
+
+    def _pre_load_state_dict(self, state_dict) -> Dict[str, Any]:
+        # TODO(chienchin): This API should be FSDP agnostic and should support
+        # general user hooks.
+        if isinstance(self.module, FSDP):
+            return FSDP.optim_state_dict_to_load(
+                self.module, self._optimizer, state_dict, is_named_optimizer=True
+            )
+        return state_dict
+
+    def _post_state_dict(self, state_dict) -> Dict[str, Any]:
+        # TODO(chienchin): This API should be FSDP agnostic and should support
+        # general user hooks.
+        if isinstance(self.module, FSDP):
+            FSDP.optim_state_dict(self.module, self._optimizer, state_dict)
+        return state_dict
+
+
+def _gen_param_group_key(param_keys: List[str]) -> str:
+    """Concatenate all param keys as a unique indentifier for one param group."""
+    return "/".join(sorted(param_keys))
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/optimizer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/optimizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..f52fe488c4682d173d6c32aba61b9c2a1a95aef3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/optimizer.py
@@ -0,0 +1,257 @@
+# mypy: allow-untyped-decorators
+# mypy: allow-untyped-defs
+import logging
+from collections import defaultdict
+from threading import Lock
+from typing import List, Optional
+
+import torch
+import torch.distributed.autograd as dist_autograd
+import torch.distributed.rpc as rpc
+import torch.jit as jit
+import torch.nn as nn
+from torch import Tensor
+from torch.distributed.rpc import RRef
+
+from .utils import functional_optim_map
+
+
+__all__ = ["DistributedOptimizer"]
+
+logger = logging.getLogger(__name__)
+
+
+# XXX: we define a _ScriptModuleOptimizer here to explicitly
+# compile the FunctionalOptimizer class into TorchScript
+# This is because ScriptClass instance still lives in
+# python unless you explicitly compile it as an attribute
+# in ScriptModule or pass it to a ScriptFunction
+# _ScriptLocalOptimizerInterface serves as a common
+# interface type for Optimizer ScriptModules.
+#
+# TODO (wanchaol): remove this once we added TorchScript
+# class reference semantics
+@jit.interface
+class _ScriptLocalOptimizerInterface:
+    def step(self, autograd_ctx_id: int) -> None:
+        pass
+
+
+class _ScriptLocalOptimizer(nn.Module):
+    # TorchScript does not support multithread concurrent compiling.
+    # request_callback might invoke concurrent compiling, so we
+    # serialize the compiling with a lock
+    compile_lock = Lock()
+
+    def __init__(self, optim_cls, local_params_rref, *args, **kwargs):
+        super().__init__()
+        self._local_params = [rref.local_value() for rref in local_params_rref]
+        self.optim = optim_cls(self._local_params, *args, **kwargs)
+
+    @jit.export
+    def step(self, autograd_ctx_id: int):
+        all_local_grads = dist_autograd.get_gradients(autograd_ctx_id)
+        # apply functional optimizer step with a list of gradients
+        grads: List[Optional[Tensor]] = [
+            all_local_grads[p] if p in all_local_grads else None
+            for p in self._local_params
+        ]
+
+        self.optim.step(grads)
+
+
+# TODO (wanchaol): remove/merge this with ScriptLocalOptimizer once
+# we have converted all to functional optimizer in distributed.optim
+class _LocalOptimizer:
+    # Ideally we would only need to share a lock for instances of
+    # _LocalOptimizer that deal with the same parameters. We are
+    # making a simplifying assumption here that if there is more
+    # than one instance of _LocalOptimizer per worker, they will
+    # be optimizing the same parameters (e.g. each data parallel
+    # trainer will create its own instance of _LocalOptimizer but
+    # they will all optimize the same parameters on each worker)
+    global_lock = Lock()
+
+    def __init__(self, optim_cls, local_params_rref, *args, **kwargs):
+        self._local_params = [rref.local_value() for rref in local_params_rref]
+        self.optim = optim_cls(self._local_params, *args, **kwargs)
+
+    def step(self, autograd_ctx_id):
+        all_local_grads = dist_autograd.get_gradients(autograd_ctx_id)
+
+        with _LocalOptimizer.global_lock:
+            for param, grad in all_local_grads.items():
+                param.grad = grad
+            self.optim.step()
+
+
+def _new_local_optimizer(optim_cls, local_params_rref, *args, **kwargs):
+    return rpc.RRef(_LocalOptimizer(optim_cls, local_params_rref, *args, **kwargs))
+
+
+def _local_optimizer_step(local_optim_rref, autograd_ctx_id):
+    local_optim = local_optim_rref.local_value()
+    local_optim.step(autograd_ctx_id)
+
+
+# new/step functions combined with _ScriptLocalOptimizer to provide GIL-free optimizer
+def _new_script_local_optimizer(optim_cls, local_params_rref, *args, **kwargs):
+    optim = _ScriptLocalOptimizer(optim_cls, local_params_rref, *args, **kwargs)
+
+    with _ScriptLocalOptimizer.compile_lock:
+        script_optim = jit.script(optim)
+        return rpc.RRef(script_optim, _ScriptLocalOptimizerInterface)
+
+
+@jit.script
+def _script_local_optimizer_step(
+    local_optim_rref: RRef[_ScriptLocalOptimizerInterface], autograd_ctx_id: int
+) -> None:
+    local_optim = local_optim_rref.local_value()
+    local_optim.step(autograd_ctx_id)
+
+
+def _wait_for_all(rpc_futs):
+    # TODO: improve error propagation
+    exception = None
+    results = []
+    for fut in rpc_futs:
+        try:
+            results.append(fut.wait())
+        except Exception as e:
+            results.append(e)
+            exception = e
+    if exception is not None:
+        raise exception
+    return results
+
+
+class DistributedOptimizer:
+    """
+    DistributedOptimizer takes remote references to parameters scattered
+    across workers and applies the given optimizer locally for each parameter.
+
+    This class uses :meth:`~torch.distributed.autograd.get_gradients` in order
+    to retrieve the gradients for specific parameters.
+
+    Concurrent calls to
+    :meth:`~torch.distributed.optim.DistributedOptimizer.step`,
+    either from the same or different clients, will
+    be serialized on each worker -- as each worker's optimizer can only work
+    on one set of gradients at a time. However, there is no guarantee that
+    the full forward-backward-optimizer sequence will execute for one client
+    at a time. This means that the gradients being applied may not correspond
+    to the latest forward pass executed on a given worker. Also, there is no
+    guaranteed ordering across workers.
+
+    `DistributedOptimizer` creates the local optimizer with TorchScript enabled
+    by default, so that optimizer updates are not blocked by the Python Global
+    Interpreter Lock (GIL) in the case of multithreaded training (e.g. Distributed
+    Model Parallel). This feature is currently enabled for most optimizers. You
+    can also follow `the recipe`__ in PyTorch tutorials to enable TorchScript support
+    for your own custom optimizers.
+
+    Args:
+        optimizer_class (optim.Optimizer): the class of optimizer to
+            instantiate on each worker.
+        params_rref (list[RRef]): list of RRefs to local or remote parameters
+            to optimize.
+        args: arguments to pass to the optimizer constructor on each worker.
+        kwargs: arguments to pass to the optimizer constructor on each worker.
+
+    Example::
+        >>> # xdoctest: +SKIP("distributed")
+        >>> import torch.distributed.autograd as dist_autograd
+        >>> import torch.distributed.rpc as rpc
+        >>> from torch import optim
+        >>> from torch.distributed.optim import DistributedOptimizer
+        >>>
+        >>> with dist_autograd.context() as context_id:
+        >>>   # Forward pass.
+        >>>   rref1 = rpc.remote("worker1", torch.add, args=(torch.ones(2), 3))
+        >>>   rref2 = rpc.remote("worker1", torch.add, args=(torch.ones(2), 1))
+        >>>   loss = rref1.to_here() + rref2.to_here()
+        >>>
+        >>>   # Backward pass.
+        >>>   dist_autograd.backward(context_id, [loss.sum()])
+        >>>
+        >>>   # Optimizer.
+        >>>   dist_optim = DistributedOptimizer(
+        >>>      optim.SGD,
+        >>>      [rref1, rref2],
+        >>>      lr=0.05,
+        >>>   )
+        >>>   dist_optim.step(context_id)
+
+    __ https://github.com/pytorch/tutorials/pull/1465
+    """
+
+    def __init__(self, optimizer_class, params_rref, *args, **kwargs):
+        torch._C._log_api_usage_once("torch.distributed.optim.DistributedOptimizer")
+        per_worker_params_rref = defaultdict(list)
+        for param in params_rref:
+            per_worker_params_rref[param.owner()].append(param)
+
+        if optimizer_class in functional_optim_map and jit._state._enabled:
+            optim_ctor = functional_optim_map.get(optimizer_class)
+        else:
+            optim_ctor = optimizer_class
+        self.is_functional_optim = optim_ctor != optimizer_class
+
+        if self.is_functional_optim:
+            optimizer_new_func = _new_script_local_optimizer
+        else:
+            logger.warning(
+                "Creating the optimizer %s without TorchScript support, "
+                "this might result in slow computation time in multithreading environment"
+                "(i.e. Distributed Model Parallel training on CPU) due to the Python's "
+                "Global Interpreter Lock (GIL). Please file an issue if you need this "
+                "optimizer in TorchScript. ",
+                optimizer_class,
+            )
+            optimizer_new_func = _new_local_optimizer
+
+        remote_optim_futs = []
+        for worker, param_rrefs in per_worker_params_rref.items():
+            remote_optim_rref_fut = rpc.rpc_async(
+                worker,
+                optimizer_new_func,
+                args=(optim_ctor, param_rrefs) + args,
+                kwargs=kwargs,
+            )
+            remote_optim_futs.append(remote_optim_rref_fut)
+
+        self.remote_optimizers = _wait_for_all(remote_optim_futs)
+
+    def step(self, context_id):
+        """
+        Performs a single optimization step.
+
+        This will call :meth:`torch.optim.Optimizer.step` on each worker
+        containing parameters to be optimized, and will block until all workers
+        return. The provided ``context_id`` will be used to retrieve the
+        corresponding :class:`~torch.distributed.autograd.context` that
+        contains the gradients that should be applied to the parameters.
+
+        Args:
+            context_id: the autograd context id for which we should run the
+                optimizer step.
+        """
+        dist_autograd._is_valid_context(context_id)
+
+        optimizer_step_func = (
+            _script_local_optimizer_step
+            if self.is_functional_optim
+            else _local_optimizer_step
+        )
+
+        rpc_futs = []
+        for optimizer in self.remote_optimizers:
+            rpc_futs.append(
+                rpc.rpc_async(
+                    optimizer.owner(),
+                    optimizer_step_func,
+                    args=(optimizer, context_id),
+                )
+            )
+        _wait_for_all(rpc_futs)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/post_localSGD_optimizer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/post_localSGD_optimizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..db65856e32adad3f04e1fe7e38accce5875b22e0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/post_localSGD_optimizer.py
@@ -0,0 +1,110 @@
+# mypy: allow-untyped-defs
+import warnings
+
+import torch
+import torch.distributed.algorithms.model_averaging.averagers as averagers
+
+
+class PostLocalSGDOptimizer(torch.optim.Optimizer):
+    r"""
+    Wraps an arbitrary :class:`torch.optim.Optimizer` and runs `post-local SGD `_,
+    This optimizer runs local optimizer at every step.
+    After the warm-up stage, it averages parameters periodically afer the local optimizer is applied.
+
+    Args:
+        optim: The local optimizer.
+        averager: A model averager instance to run post-localSGD algorithm.
+
+    Example::
+
+        >>> # xdoctest: +SKIP("undefined variables")
+        >>> import torch
+        >>> import torch.distributed as dist
+        >>> import torch.distributed.algorithms.model_averaging.averagers as averagers
+        >>> import torch.nn as nn
+        >>> from torch.distributed.optim import PostLocalSGDOptimizer
+        >>> from torch.distributed.algorithms.ddp_comm_hooks.post_localSGD_hook import (
+        >>>   PostLocalSGDState,
+        >>>   post_localSGD_hook,
+        >>> )
+        >>>
+        >>> model = nn.parallel.DistributedDataParallel(
+        >>>    module, device_ids=[rank], output_device=rank
+        >>> )
+        >>>
+        >>> # Register a post-localSGD communication hook.
+        >>> state = PostLocalSGDState(process_group=None, subgroup=None, start_localSGD_iter=100)
+        >>> model.register_comm_hook(state, post_localSGD_hook)
+        >>>
+        >>> # Create a post-localSGD optimizer that wraps a local optimizer.
+        >>> # Note that ``warmup_steps`` used in ``PostLocalSGDOptimizer`` must be the same as
+        >>> # ``start_localSGD_iter`` used in ``PostLocalSGDState``.
+        >>> local_optim = torch.optim.SGD(params=model.parameters(), lr=0.01)
+        >>> opt = PostLocalSGDOptimizer(
+        >>>     optim=local_optim,
+        >>>     averager=averagers.PeriodicModelAverager(period=4, warmup_steps=100)
+        >>> )
+        >>>
+        >>> # In the first 100 steps, DDP runs global gradient averaging at every step.
+        >>> # After 100 steps, DDP runs gradient averaging within each subgroup (intra-node by default),
+        >>> # and post-localSGD optimizer runs global model averaging every 4 steps after applying the local optimizer.
+        >>> for step in range(0, 200):
+        >>>    opt.zero_grad()
+        >>>    loss = loss_fn(output, labels)
+        >>>    loss.backward()
+        >>>    opt.step()
+    """
+
+    def __init__(self, optim: torch.optim.Optimizer, averager: averagers.ModelAverager):
+        self.optim = optim
+        self.param_groups = self.optim.param_groups
+        self.averager = averager
+
+    @property
+    def state(self):
+        return self.optim.state
+
+    def __repr__(self):
+        return self.optim.__repr__()
+
+    def state_dict(self):
+        r"""
+        This is the same as :class:`torch.optim.Optimizer` :meth:`state_dict`,
+        but adds an extra entry to record model averager's step to the checkpoint
+        to ensure reload does not cause unnecessary warm up again.
+        """
+        optim_state_dict = self.optim.state_dict()
+        optim_state_dict["step"] = self.averager.step
+        return optim_state_dict
+
+    def load_state_dict(self, state_dict):
+        r"""
+        This is the same as :class:`torch.optim.Optimizer` :meth:`load_state_dict`,
+        but also restores model averager's step value to the one
+        saved in the provided ``state_dict``.
+
+        If there is no ``"step"`` entry in ``state_dict``,
+        it will raise a warning and initialize the model averager's step to 0.
+        """
+        self.optim.load_state_dict(state_dict)
+        if "step" in state_dict:
+            self.averager.step = state_dict["step"]
+        else:
+            warnings.warn(
+                "Loaded state dict does not contain a step counter for an averager. "
+                "Setting step counter to 0."
+            )
+            self.averager.step = 0
+
+    def step(self):
+        r"""
+        Performs a single optimization step (parameter update).
+        """
+        self.optim.step()
+        self.averager.average_parameters(params=self.param_groups)
+
+    def zero_grad(self, set_to_none: bool = True):  # type: ignore[override]
+        self.optim.zero_grad(set_to_none=set_to_none)
+
+    def add_param_group(self, param_group):
+        self.optim.add_param_group(param_group)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..d2c75eee7e39bc1e079c871e7a0e40ba47af0026
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/utils.py
@@ -0,0 +1,66 @@
+# mypy: allow-untyped-defs
+from typing import Type
+
+from torch import optim
+
+from .functional_adadelta import _FunctionalAdadelta
+from .functional_adagrad import _FunctionalAdagrad
+from .functional_adam import _FunctionalAdam
+from .functional_adamax import _FunctionalAdamax
+from .functional_adamw import _FunctionalAdamW
+from .functional_rmsprop import _FunctionalRMSprop
+from .functional_rprop import _FunctionalRprop
+from .functional_sgd import _FunctionalSGD
+
+
+# dict to map a user passed in optimizer_class to a functional
+# optimizer class if we have already defined inside the
+# distributed.optim package, this is so that we hide the
+# functional optimizer to user and still provide the same API.
+functional_optim_map = {
+    optim.Adagrad: _FunctionalAdagrad,
+    optim.Adam: _FunctionalAdam,
+    optim.AdamW: _FunctionalAdamW,
+    optim.SGD: _FunctionalSGD,
+    optim.Adadelta: _FunctionalAdadelta,
+    optim.RMSprop: _FunctionalRMSprop,
+    optim.Rprop: _FunctionalRprop,
+    optim.Adamax: _FunctionalAdamax,
+}
+
+
+def register_functional_optim(key, optim):
+    """
+    Interface to insert a new functional optimizer to functional_optim_map
+    ``fn_optim_key`` and ``fn_optimizer`` are user defined. The optimizer and key
+    need not be of :class:`torch.optim.Optimizer` (e.g. for custom optimizers)
+    Example::
+        >>> # import the new functional optimizer
+        >>> # xdoctest: +SKIP
+        >>> from xyz import fn_optimizer
+        >>> from torch.distributed.optim.utils import register_functional_optim
+        >>> fn_optim_key = "XYZ_optim"
+        >>> register_functional_optim(fn_optim_key, fn_optimizer)
+    """
+    if key not in functional_optim_map:
+        functional_optim_map[key] = optim
+
+
+def as_functional_optim(optim_cls: Type, *args, **kwargs):
+    try:
+        functional_cls = functional_optim_map[optim_cls]
+    except KeyError as e:
+        raise ValueError(
+            f"Optimizer {optim_cls} does not have a functional " f"counterpart!"
+        ) from e
+
+    return _create_functional_optim(functional_cls, *args, **kwargs)
+
+
+def _create_functional_optim(functional_optim_cls: Type, *args, **kwargs):
+    return functional_optim_cls(
+        [],
+        *args,
+        **kwargs,
+        _allow_empty_param_list=True,
+    )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/zero_redundancy_optimizer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/zero_redundancy_optimizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..0493b97f27f77231b4890f03c1fc315f47009ddf
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/optim/zero_redundancy_optimizer.py
@@ -0,0 +1,1652 @@
+# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
+#
+# This source code is licensed under the BSD license found in the
+# LICENSE file in the root directory of this source tree.
+
+r"""Zero Redundancy Optimizer."""
+import collections
+import copy
+import enum
+import inspect
+import io
+import logging
+from itertools import chain
+from typing import Any, Callable, Dict, List, Optional, Set, Type, Union
+
+import torch
+import torch.distributed as dist
+from torch.distributed.algorithms.join import Join, Joinable, JoinHook
+from torch.distributed.optim.utils import functional_optim_map
+from torch.optim import Optimizer
+
+
+__all__ = ["ZeroRedundancyOptimizer"]
+
+
+logger = logging.getLogger(__name__)
+
+
+# Credits:  classy_vision/generic/distributed_util.py
+def _recursive_copy_to_device(
+    value: Any,
+    non_blocking: bool,
+    device: torch.device,
+) -> Any:
+    r"""
+    Recursively searches lists, tuples, dicts and copies tensors to device if possible.
+
+    Non-tensor values are passed as-is in the result.
+
+    .. note:  These are all copies, so if there are two objects that reference
+    the same object, then after this call, there will be two different objects
+    referenced on the device.
+    """
+    if isinstance(value, torch.Tensor):
+        return value.to(device, non_blocking=non_blocking)
+
+    if isinstance(value, (list, tuple)):
+        values = [
+            _recursive_copy_to_device(val, non_blocking=non_blocking, device=device)
+            for val in value
+        ]
+        return values if isinstance(value, list) else tuple(values)
+
+    if isinstance(value, collections.abc.Mapping):
+        return {
+            key: _recursive_copy_to_device(
+                val, non_blocking=non_blocking, device=device
+            )
+            for key, val in value.items()
+        }
+
+    return value
+
+
+def _is_trainable(param: torch.Tensor) -> bool:
+    r"""Return if a parameter is trainable, where trainability is equivalent to requiring a gradient."""
+    return param.requires_grad
+
+
+def _broadcast_object(
+    obj: Any,
+    src_rank: int,
+    group: object = dist.group.WORLD,
+    device: torch.device = torch.device("cpu"),
+) -> Any:
+    r"""
+    Broadcasts an object to the given group.
+
+    It will be sending the object if called from the source rank and receiving
+    the object otherwise.
+
+    Arguments:
+        obj: object to broadcast; only used if called on the source rank.
+        src_rank (int): source rank.
+        group (``ProcessGroup``, optional): group used for the broadcast
+            (default: ``dist.group.WORLD``).
+        device (``torch.device``, optional): device to send from or receive
+            to (default: ``torch.device("cpu")``).
+
+    Returns:
+        The broadcasted object.
+    """
+    if dist.get_rank() == src_rank:
+        # Send the object
+        buffer = io.BytesIO()
+        torch.save(obj, buffer)
+        data = bytearray(buffer.getbuffer())
+        length_tensor = torch.LongTensor([len(data)]).to(device)
+        data_send_tensor = torch.ByteTensor(data).to(device)
+        dist.broadcast(length_tensor, src=src_rank, group=group, async_op=False)
+        dist.broadcast(data_send_tensor, src=src_rank, group=group, async_op=False)
+    else:
+        # Receive the object
+        length_tensor = torch.LongTensor([0]).to(device)
+        dist.broadcast(length_tensor, src=src_rank, group=group, async_op=False)
+        data_recv_tensor = torch.empty(
+            [int(length_tensor.item())], dtype=torch.uint8, device=device
+        )
+        dist.broadcast(data_recv_tensor, src=src_rank, group=group, async_op=False)
+        buffer = io.BytesIO(data_recv_tensor.cpu().numpy())
+        obj = torch.load(buffer, map_location=device, weights_only=False)
+    return obj
+
+
+class _ZeROJoinHook(JoinHook):
+    def __init__(self, zero):
+        assert isinstance(zero, ZeroRedundancyOptimizer), (
+            "ZeRO join hook requires passing in a ZeroRedundancyOptimizer "
+            "instance as the state"
+        )
+        self.zero = zero
+        super().__init__()
+
+    def main_hook(self):
+        """
+        Perform an optimizer step.
+
+        This step updates the joined process's shard of
+        the parameters and broadcasts those parameters.
+        """
+        self.zero.step()
+
+
+class _DDPBucketAssignment:
+    r"""
+    Represent a :class:`DistributedDataParallel` bucket assignment.
+
+    This means that a (possibly non-strict) subset of the parameters corresponding to
+    a DDP bucket assigned to a rank to update.
+
+    Attributes:
+        bucket_index (int): index of the bucket determined by the DDP gradient
+            bucket all-reduce order.
+        parameters (List[torch.Tensor]): model parameters in the bucket
+            assigned to this rank.
+        offset (int): offset into the :class:`GradBucket` 's :meth:`parameters`
+            giving the index of the first element in the passed-in
+            ``parameters``; this equivalently indexes into the
+            :class:`GradBucket` 's :meth:`gradients`.
+        device (torch.device): device on which the parameters are stored.
+        tensor (torch.Tensor): flattened tensor giving the data of the
+            parameter subset assigned to the rank.
+    """
+
+    def __init__(
+        self,
+        bucket_index: int,
+        parameters: List[torch.Tensor],
+        offset: int,
+    ):
+        self.bucket_index = bucket_index
+        self.parameters = parameters
+        self.offset = offset
+        if len(self.parameters) == 0:
+            raise ValueError("Empty bucket assignment")
+        # DDP guarantees all parameters in the bucket have the same device
+        self.device: torch.device = self.parameters[0].device
+        self.tensor: Optional[torch.Tensor] = None
+
+
+class _OverlapStatus(enum.IntEnum):
+    r"""
+    Define possible statuses that :class:`ZeroRedundancyOptimizer` can be in when overlapping with :class:`DistributedDataParallel`.
+
+    Attributes:
+        ``UNINITIALIZED``: The ZeRO instance is effectively uninitialized and
+            is waiting for DDP to finalize its bucketing.
+        ``DDP_HAS_REBUILT_BUCKETS``: DDP has rebuilt its buckets, meaning that
+            its bucketing is finalized. The ZeRO instance can now collect the
+            necessary information about the DDP bucketing.
+        ``INITIALIZED``: The ZeRO instance is fully initialized and can now
+            optimize parameters.
+    """
+
+    UNINITIALIZED = 0
+    DDP_HAS_REBUILT_BUCKETS = 1
+    INITIALIZED = 2
+
+
+class _OverlapInfo:
+    r"""
+    Information needed by :class:`ZeroRedundancyOptimizer` to overlap with :class:`DistributedDataParallel`.
+
+    Arguments:
+        world_size (int): world size of the process group being used.
+
+    Attributes:
+        shard_buckets (bool): if ``True``, then the assignment of each
+            :class:`DistributedDataParallel` bucket is partitioned across
+            possibly multiple :class:`ZeroRedundancyOptimizer` instances (i.e.
+            across possibly multiple ranks) to approximate uniformity following
+            a threshold given by the total parameter size divided by the world
+            size; if ``False``, then each bucket is wholly assigned to a single
+            :class:`ZeroRedundancyOptimizer` instance (i.e. to a single rank);
+            this should be set to the value passed into the hook constructor.
+        status (_OverlapStatus): current status; see :class:`_OverlapStatus`
+            for more information.
+        params_per_bucket (List[List[torch.Tensor]]): ``params_per_bucket[i]``
+            gives the model parameters in the ``i``th bucket.
+        params_per_rank (List[List[torch.Tensor]]): ``params_per_rank[i]``
+            gives the model parameters assigned to the ``i``th rank, where the
+            parameters are grouped by increasing bucket indices.
+        offsets (Dict[int, int]): maps from bucket index to the offset in
+            ``self.params_per_rank[rank]`` giving the index of the first
+            parameter in that bucket, where ``rank`` is this process's own
+            rank; the keys of this :class:`dict` are the bucket indices
+            assigned to this rank.
+        num_bucket_assignments (int): total number of bucket assignments across
+            all ranks; this is equal to the number of
+            :class:`DistributedDataParallel` gradient buckets if
+            ``shard_buckets=False`` and possibly greater otherwise.
+        total_size (int, optional): total size of all buckets (i.e. sum of
+            ``param.numel()`` for all ``param`` across all buckets) if
+            ``shard_buckets=True``; otherwise, ``None``.
+        broadcast_handles (List[Work]): :class:`list` of async work handles for
+            the parameter broadcasts.
+        bucket_index_to_future (Dict[int, torch.futures.Future]):
+            :class:`dict` mapping bucket index to the corresponding all-reduce
+            future.
+        bucket_index_to_bucket (Dict[int, dist.GradBucket]): :class:`dict`
+            mapping bucket index to the corresponding bucket.
+        bucket_indices_seen (List[int]): :class:`list` of the bucket indices
+            seen on this iteration.
+    """
+
+    def __init__(self, world_size) -> None:
+        self.status: _OverlapStatus = _OverlapStatus.UNINITIALIZED
+        self.shard_buckets: bool = False
+
+        # Modified per bucket reconstruction
+        self.params_per_bucket: List[List[torch.Tensor]] = []
+        self.params_per_rank: List[List[torch.Tensor]] = [[] for _ in range(world_size)]
+        self.offsets: Dict[int, int] = {}
+        # Group Ranks
+        self.assigned_ranks_per_bucket: List[Set[int]] = []
+        self.num_bucket_assignments: int = 0
+        self.total_size: Optional[int] = None
+
+        # Modified per iteration
+        self.broadcast_handles: List[Any] = []
+        self.bucket_indices_seen: List[int] = []
+        # Used by `hook_with_zero_step()`
+        self.bucket_index_to_future: Dict[int, torch.futures.Future] = {}
+        self.bucket_index_to_bucket: Dict[int, dist.GradBucket] = {}
+
+    def wait_for_broadcasts(self) -> None:
+        r"""
+        Wait for all parameter broadcasts.
+
+        This function should be called once all broadcasts have been scheduled,
+        meaning ``self.broadcast_handles`` is filled. This clears ``self.broadcast_handles``
+        in preparation for the next iteration.
+        """
+        assert (
+            len(self.broadcast_handles) == self.num_bucket_assignments
+        ), f"Missing at least one broadcast handle on rank {dist.get_rank()}"
+        _ = [x.wait() for x in self.broadcast_handles]
+        self.broadcast_handles.clear()
+
+    def clear_per_iter_info(self) -> None:
+        r"""
+        Clear the data structures that are modified per-iteration.
+
+        This function should be called at the end of an iteration.
+        """
+        self.bucket_indices_seen.clear()
+        self.bucket_index_to_future.clear()
+        self.bucket_index_to_bucket.clear()
+
+
+class ZeroRedundancyOptimizer(Optimizer, Joinable):
+    r"""
+    Wrap an arbitrary :class:`optim.Optimizer ` and shards its states across ranks in the group.
+
+    The sharing is done as described by ZeRO_.
+
+    The local optimizer instance in each rank is only
+    responsible for updating approximately ``1 / world_size`` parameters and
+    hence only needs to keep ``1 / world_size`` optimizer states. After
+    parameters are updated locally, each rank will broadcast its parameters to
+    all other peers to keep all model replicas in the same state.
+    ``ZeroRedundancyOptimizer`` can be used in conjunction with
+    :class:`torch.nn.parallel.DistributedDataParallel` to reduce per-rank peak
+    memory consumption.
+
+    ``ZeroRedundancyOptimizer`` uses a sorted-greedy algorithm to pack a number
+    of parameters at each rank. Each parameter belongs to a single rank and is
+    not divided among ranks. The partition is arbitrary and might not match the
+    the parameter registration or usage order.
+
+    Arguments:
+        params (``Iterable``): an ``Iterable`` of :class:`torch.Tensor` s
+            or :class:`dict` s giving all parameters, which will be sharded
+            across ranks.
+
+    Keyword Args:
+        optimizer_class (:class:`torch.nn.Optimizer`): the class of the local
+            optimizer.
+        process_group (``ProcessGroup``, optional): ``torch.distributed``
+            ``ProcessGroup`` (default: ``dist.group.WORLD`` initialized by
+            :meth:`torch.distributed.init_process_group`).
+        parameters_as_bucket_view (bool, optional): if ``True``, parameters are
+            packed into buckets to speed up communication, and ``param.data``
+            fields point to bucket views at different offsets; if ``False``,
+            each individual parameter is communicated separately, and each
+            ``params.data`` stays intact (default: ``False``).
+        overlap_with_ddp (bool, optional): if ``True``, :meth:`step` is
+            overlapped with :class:`DistributedDataParallel` 's gradient
+            synchronization; this requires (1) either a functional optimizer
+            for the ``optimizer_class`` argument or one with a functional
+            equivalent and (2) registering a DDP communication hook
+            constructed from one of the functions in ``ddp_zero_hook.py``;
+            parameters are packed into buckets matching those in
+            :class:`DistributedDataParallel`, meaning that the
+            ``parameters_as_bucket_view`` argument is ignored.
+            If ``False``, :meth:`step` runs disjointly after the backward pass
+            (per normal).
+            (default: ``False``)
+        **defaults: any trailing arguments, which are forwarded to the local
+            optimizer.
+
+    Example::
+
+        >>> # xdoctest: +SKIP
+        >>> import torch.nn as nn
+        >>> from torch.distributed.optim import ZeroRedundancyOptimizer
+        >>> from torch.nn.parallel import DistributedDataParallel as DDP
+        >>> model = nn.Sequential(*[nn.Linear(2000, 2000).to(rank) for _ in range(20)])
+        >>> ddp = DDP(model, device_ids=[rank])
+        >>> opt = ZeroRedundancyOptimizer(
+        >>>     ddp.parameters(),
+        >>>     optimizer_class=torch.optim.Adam,
+        >>>     lr=0.01
+        >>> )
+        >>> ddp(inputs).sum().backward()
+        >>> opt.step()
+
+    .. warning::
+        Currently, ``ZeroRedundancyOptimizer`` requires that all of the
+        passed-in parameters are the same dense type.
+
+    .. warning::
+        If you pass ``overlap_with_ddp=True``, be wary of the following: Given
+        the way that overlapping :class:`DistributedDataParallel` with
+        :class:`ZeroRedundancyOptimizer` is currently implemented, the first
+        two or three training iterations do not perform parameter updates in
+        the optimizer step, depending on if ``static_graph=False`` or
+        ``static_graph=True``, respectively. This is because it needs
+        information about the gradient bucketing strategy used by
+        :class:`DistributedDataParallel`, which is not finalized until the
+        second forward pass if ``static_graph=False`` or until the third
+        forward pass if ``static_graph=True``. To adjust for this, one option
+        is to prepend dummy inputs.
+
+    .. warning:: ZeroRedundancyOptimizer is experimental and subject to change.
+
+    .. _ZeRO: https://arxiv.org/abs/1910.02054
+
+    """
+
+    def __init__(
+        self,
+        params,
+        optimizer_class: Type[Optimizer],
+        process_group: Optional[Any] = None,
+        parameters_as_bucket_view: bool = False,
+        overlap_with_ddp: bool = False,
+        **defaults: Any,
+    ):
+        r"""Init."""
+        # Perform type and assumption checks on the input parameters
+        params = self._verify_and_init_params(params)
+        self._verify_same_dense_param_type()
+
+        # NOTE: The parent constructor uses `add_param_group()` which is
+        # partially overloaded in ZeroRedundancyOptimizer, so we use the
+        # `initialized` flag to dissociate the behaviour of `add_param_group()`
+        # between the parent and child.
+        self.initialized = False
+
+        Optimizer.__init__(self, params, defaults)
+        Joinable.__init__(self)
+        # Now, all parameters are held in both `self._all_params` and
+        # `self.param_groups`
+
+        # Internal data structures (`_cache` indicates lazily evaluated)
+        self._param_to_rank_cache: Dict[torch.Tensor, int] = {}
+        self._param_to_index_cache: Dict[torch.Tensor, int] = {}
+        self._partition_parameters_cache: List[List[Dict]] = []
+        self._index_to_param_cache: List[torch.Tensor] = []
+        self._device_to_params_per_rank_cache: Dict[
+            torch.device, List[List[torch.Tensor]]
+        ] = {}
+        self._bucket_assignments_per_rank_cache: List[
+            Dict[int, _DDPBucketAssignment]
+        ] = []
+        self._is_trainable_mask = self._get_is_trainable_mask()
+
+        # Default device for collective communication and buckets
+        self._default_device = self._all_params[0].device
+
+        self.process_group = (
+            process_group if process_group is not None else dist.group.WORLD
+        )
+        self.world_size: int = dist.get_world_size(self.process_group)
+        self.rank: int = dist.get_rank(self.process_group)
+        self.global_rank: int = dist.distributed_c10d.get_global_rank(
+            self.process_group, self.rank
+        )
+
+        self._overlap_with_ddp: bool = overlap_with_ddp
+        self._optim_defaults = defaults
+        self._optim_constructor = self._get_optimizer_constructor(optimizer_class)
+
+        # If `overlap_with_ddp=True`, local optimizer initialization is delayed
+        # to run time after the necessary information has been collected
+        if not overlap_with_ddp:
+            self._init_local_optimizer()
+        else:
+            self._overlap_info: _OverlapInfo = _OverlapInfo(self.world_size)
+            if parameters_as_bucket_view:
+                logger.warning(
+                    "`parameters_as_bucket_view=True` will be ignored since "
+                    "`overlap_with_ddp=True`; instead, a different bucketing "
+                    "strategy will be used"
+                )
+
+        # `self._buckets` is used if `parameters_as_bucket_view=True`, in
+        # which case parameter data is flattened into contiguous bucket tensors
+        self.parameters_as_bucket_view = parameters_as_bucket_view
+        self._buckets: List[List[torch.Tensor]] = []
+        self._build_param_buckets()
+
+        # Optional consolidated optimizer state, only populated if this rank
+        # is the target in `consolidate_state_dict()`
+        self._all_state_dicts: List[Dict[str, Any]] = []
+
+        self.initialized = True
+
+    def _clear_cache(self) -> None:
+        r"""Clear the cached data structures giving partition information."""
+        self._partition_parameters_cache.clear()
+        self._param_to_rank_cache.clear()
+        self._index_to_param_cache.clear()
+        self._param_to_index_cache.clear()
+        self._device_to_params_per_rank_cache.clear()
+        self._bucket_assignments_per_rank_cache.clear()
+
+    def add_param_group(self, param_group: Dict[str, Any]) -> None:
+        r"""
+        Add a parameter group to the :class:`Optimizer` 's ``param_groups``.
+
+        This can be useful when fine tuning a pre-trained network, as frozen
+        layers can be made trainable and added to the :class:`Optimizer` as
+        training progresses.
+
+        Arguments:
+            param_group (dict): specifies the parameters to be optimized and
+                group-specific optimization options.
+
+        .. warning:: This method handles updating the shards on all partitions
+            but needs to be called on all ranks. Calling this on a subset of
+            the ranks will cause the training to hang because communication
+            primitives are called depending on the managed parameters and
+            expect all the ranks to participate on the same set of parameters.
+        """
+        if self.initialized and self._overlap_with_ddp:
+            raise RuntimeError(
+                "ZeroRedundancyOptimizer with `overlap_with_ddp=True` only "
+                "supports a single parameter group"
+            )
+
+        super().add_param_group(param_group)
+        # NOTE: The rest of the method assumes that the call to the parent's
+        # `add_param_group()` appends the new parameter group and preserves
+        # the previous parameter-group ordering
+
+        if self.initialized:
+            # Force a re-partitioning of the parameters
+            self._clear_cache()
+            param_groups = self._partition_parameters()[self.rank]
+            # NOTE: All parameters in the old parameter groups should be
+            # assigned to the same ranks so that the local optimizers do not
+            # need to be reinitialized
+
+            # Add the parameters assigned to this rank from the new parameter
+            # group to the local optimizer, if any
+            if len(param_groups) == len(self.optim.param_groups) + 1:
+                self.optim.add_param_group(param_groups[-1])
+
+            # Update the bucketing strategy accordingly
+            if self.parameters_as_bucket_view:
+                self._build_param_buckets()
+
+    def consolidate_state_dict(self, to: int = 0) -> None:
+        r"""
+        Consolidate a list of ``state_dict`` s (one per rank) on the target rank.
+
+        Arguments:
+            to (int): the rank that receives the optimizer states (default: 0).
+
+        Raises:
+            RuntimeError: if ``overlap_with_ddp=True`` and this method is
+                called before this :class:`ZeroRedundancyOptimizer` instance
+                has been fully initialized, which happens once
+                :class:`DistributedDataParallel` gradient buckets have been
+                rebuilt.
+
+        .. warning:: This needs to be called on all ranks.
+        """
+        self._check_overlap_initialized()
+
+        # Sync the exposed `param_groups` attributes to the local optimizer in
+        # case they have been updated
+        self._sync_param_groups(self.param_groups, self.optim.param_groups)
+
+        # Pull the sharded state from all ranks and store them in rank order
+        empty_messenger = torch.tensor(
+            [0], dtype=torch.uint8, device=self._default_device
+        )
+
+        # NOTE: We wastefully use `broadcast()` (e.g. instead of `gather()`)
+        # due to compatibility issues with NCCL backend; a possible follow-up
+        # is to move all sharded state management to RPC RRef
+        self._all_state_dicts = []
+        for rank in range(self.world_size):
+            global_rank = dist.distributed_c10d.get_global_rank(
+                self.process_group, rank
+            )
+            if self.rank == to:
+                # Consolidate all local `state_dict`s on this rank, storing on
+                # CPU to save GPU memory
+                if rank == self.rank:
+                    # Directly append own optimizer state
+                    self._all_state_dicts.append(
+                        _recursive_copy_to_device(
+                            self.optim.state_dict(),
+                            non_blocking=True,
+                            device=torch.device("cpu"),
+                        )
+                    )
+                else:
+                    # Receive the optimizer state from the source rank
+                    local_state_dict = _broadcast_object(
+                        empty_messenger,
+                        src_rank=global_rank,
+                        group=self.process_group,
+                        device=self._default_device,
+                    )
+                    self._all_state_dicts.append(
+                        _recursive_copy_to_device(
+                            local_state_dict,
+                            non_blocking=True,
+                            device=torch.device("cpu"),
+                        )
+                    )
+            else:
+                if rank == self.rank:
+                    # Send the optimizer state to the target rank
+                    _ = _broadcast_object(
+                        self.optim.state_dict(),
+                        src_rank=self.global_rank,
+                        group=self.process_group,
+                        device=self._default_device,
+                    )
+                elif rank != to:
+                    # Discard the received object; `broadcast()` is used for
+                    # compatibility reasons
+                    _ = _broadcast_object(
+                        empty_messenger,
+                        src_rank=global_rank,
+                        group=self.process_group,
+                        device=self._default_device,
+                    )
+
+    def _verify_params_per_rank(
+        self,
+        params_per_rank: List[List[torch.Tensor]],
+    ) -> None:
+        r"""
+        Verify ``params_per_rank`` for :meth:`_partition_parameters`.
+
+        The verification is done by checking that ``params_per_rank`` has length equal
+        to the world size and that it does not contain any parameters not passed into the
+        :class:`ZeroRedundancyOptimizer` constructor.
+
+        The parameters in ``params_per_rank`` being a strict subset of those
+        passed into the constructor is valid since some parameters may be
+        frozen.
+
+        Raises:
+            ValueError: if ``params_per_rank`` does not have length equal to
+                the world size or if it contains a parameter that was not
+                passed into the :class:`ZeroRedundancyOptimizer` constructor.
+        """
+        if len(params_per_rank) != self.world_size:
+            raise ValueError(
+                "`params_per_rank` must have length equal to the world size"
+            )
+        all_params_set = set(self._all_params)
+        for params in params_per_rank:
+            for param in params:
+                if param not in all_params_set:
+                    raise ValueError(
+                        "Passing a new parameter in `params_per_rank` that "
+                        "was not passed into the ZeroRedundancyOptimizer "
+                        "constructor"
+                    )
+
+    def _partition_param_group(
+        self, param_group: Dict[str, Any], params_per_rank: List[List[torch.Tensor]]
+    ) -> None:
+        r"""
+        Partition the parameter group ``param_group`` according to ``params_per_rank``.
+
+        The partition will modify the ``self._partition_parameters_cache``. This method should
+        only be used as a subroutine for :meth:`_partition_parameters`.
+
+        Arguments:
+            param_group (dict[str, Any]): a parameter group as normally defined
+                in an optimizer state.
+            params_per_rank (list[list[torch.Tensor]]): a :class:`list` of
+                length world size containing :class:`list` s of parameters to
+                assign to each rank.
+        """
+        for rank, params in enumerate(params_per_rank):
+            rank_param_group = copy.copy(param_group)
+            rank_param_group["params"] = params
+            self._partition_parameters_cache[rank].append(rank_param_group)
+
+    def _partition_parameters(
+        self,
+        params_per_rank: Optional[List[List[torch.Tensor]]] = None,
+    ) -> List[List[Dict]]:
+        r"""
+        Partitions parameters across distributed data parallel ranks.
+
+        Arguments:
+            params_per_rank (list[list[torch.Tensor]], optional): a
+                :class:`list` of length world size containing :class:`list` s
+                of parameters to assign to each rank; this provides a way to
+                specify a partition manually.
+                If ``None``, the parameters are partitioned according to an
+                internal algorithm.
+                (default: ``None``)
+
+        Returns:
+            A :class:`list` where each element of the list contains the
+            ``param_groups`` for a rank (which itself is a :class:`list` of
+            :class:`dict`); element 0 corresponds to rank 0, etc.; each rank
+            stores the ``param_groups`` for all ranks for the collective
+            communication in :meth:`step`.
+
+        Raises:
+            ValueError: see :meth:`_validate_params_per_rank`.
+            RuntimeError: if ``params_per_rank`` is not ``None`` and this
+                :class:`ZeroRedundancyOptimizer` instance is using more than
+                one parameter group.
+        """
+        if params_per_rank is None:
+            # Partition the parameters optimizing for uniformity
+            if len(self._partition_parameters_cache) == 0:
+                self._partition_parameters_cache = [[] for _ in range(self.world_size)]
+                sizes = [0] * self.world_size
+                for param_group in self.param_groups:
+                    param_group_params_per_rank: List[List] = [
+                        [] for _ in range(self.world_size)
+                    ]
+                    # Sort the parameters by size (largest first)
+                    params_sorted = sorted(
+                        param_group["params"], key=lambda t: t.numel(), reverse=True
+                    )
+                    for param in params_sorted:
+                        # Greedily add the parameter to rank with smallest size so far
+                        rank = self._get_min_index(sizes)
+                        param_group_params_per_rank[rank].append(param)
+                        sizes[rank] += param.numel()
+                    # Apply the constructed partition of the parameter group
+                    self._partition_param_group(
+                        param_group, param_group_params_per_rank
+                    )
+
+            return self._partition_parameters_cache
+
+        # Partition the parameters according to `params_per_rank`
+        assert len(self._partition_parameters_cache) == 0, (
+            "Specifying `params_per_rank` should only be done when the "
+            "parameters have not been partitioned yet"
+        )
+        if len(self.param_groups) != 1:
+            raise RuntimeError(
+                "Specifying `params_per_rank` only supports a single parameter group"
+            )
+        self._verify_params_per_rank(params_per_rank)
+        self._partition_parameters_cache = [[] for _ in range(self.world_size)]
+
+        # Apply the passed-in partition of the parameter group
+        param_group = self.param_groups[0]
+        self._partition_param_group(param_group, params_per_rank)
+
+        return self._partition_parameters_cache
+
+    @property
+    def _param_to_rank(self) -> Dict[torch.Tensor, int]:
+        r""":class:`dict` mapping parameters to their assigned data parallel rank in the partition."""
+        if len(self._param_to_rank_cache) == 0:
+            for rank, param_groups in enumerate(self._partition_parameters()):
+                for param_group in param_groups:
+                    for param in param_group["params"]:
+                        self._param_to_rank_cache[param] = rank
+        return self._param_to_rank_cache
+
+    @property
+    def _param_to_index(self) -> Dict[torch.Tensor, int]:
+        r"""
+        :class:`dict` mapping parameters to their indices in the global optimizer state.
+
+        NOTE: This assumes that the global optimizer state's indexing (in
+        ``state_dict``) follows a linear ordering over the parameter groups.
+        """
+        if len(self._param_to_index_cache) == 0:
+            self._param_to_index_cache = {
+                p: i
+                for i, p in enumerate(chain(*(g["params"] for g in self.param_groups)))
+            }
+        return self._param_to_index_cache
+
+    @property
+    def _index_to_param(self) -> List[torch.Tensor]:
+        r"""List mapping parameter indices in the global optimizer scheme to the actual params."""
+        if len(self._index_to_param_cache) == 0:
+            self._index_to_param_cache = list(
+                chain(*(g["params"] for g in self.param_groups))
+            )
+        return self._index_to_param_cache
+
+    def _broadcast_params_from_rank(self, rank: int):
+        r"""
+        Broadcast the shard of parameters from a given rank to all other ranks asynchronously.
+
+        Arguments:
+            rank (int): the source rank.
+
+        Returns:
+            A :class:`list` of async work handles for the ``broadcast()`` s
+            performed to synchronize the parameters.
+        """
+        assert not self._overlap_with_ddp, (
+            "`_broadcast_params_from_rank()` should not be used if "
+            "`overlap_with_ddp=True`; instead, the broadcasting should "
+            "happen in the DDP communication hook"
+        )
+        handles = []
+        if self.parameters_as_bucket_view:
+            for dev_i_buckets in self._buckets:
+                bucket = dev_i_buckets[rank]
+                global_rank = dist.distributed_c10d.get_global_rank(
+                    self.process_group, rank
+                )
+                handles.append(
+                    dist.broadcast(
+                        tensor=bucket,
+                        src=global_rank,
+                        group=self.process_group,
+                        async_op=True,
+                    )
+                )
+        else:
+            param_groups = self._partition_parameters()[rank]
+            global_rank = dist.distributed_c10d.get_global_rank(
+                self.process_group, rank
+            )
+            for param_group in param_groups:
+                for param in param_group["params"]:
+                    handles.append(
+                        dist.broadcast(
+                            tensor=param.data,
+                            src=global_rank,
+                            group=self.process_group,
+                            async_op=True,
+                        )
+                    )
+        return handles
+
+    def _sync_params(self):
+        r"""
+        Sync all parameter shards across the ranks.
+
+        This rank sends its shard of the parameters to all other ranks and
+        receives a shard from each other rank. This is done using
+        ``broadcast()``. Parameters are sent bucket-by-bucket if
+        ``parameters_as_bucket_view=True``and sent parameter-by-parameter
+        otherwise.
+        """
+        handles = []
+        for rank in range(self.world_size):
+            handles.extend(self._broadcast_params_from_rank(rank))
+        _ = [x.wait() for x in handles]
+
+    @property
+    def _device_to_params_per_rank(
+        self,
+    ) -> Dict[torch.device, List[List[torch.Tensor]]]:
+        r"""
+        Return device parameters assigned per rank.
+
+        :class:`dict` mapping each device to a :class:`list` of the per-rank parameter
+        lists filtered to only include the parameters stored on that device.
+        Each per-rank parameter list gives the parameters assigned to that rank
+        to update.
+
+        This is used for constructing the parameter buckets if
+        ``parameters_as_bucket_view=True``.
+
+        Let ``dev_i`` denote the ``i``th device for this rank. Then:
+        ``dev_0`` maps to a list containing:
+            rank 0's assigned parameters stored on ``dev_0``,
+            rank 1's assigned parameters stored on ``dev_0``,
+            ...
+        ``dev_1`` maps to a list containing:
+            rank 0's assigned parameters stored on ``dev_1``,
+            rank 1's assigned parameters stored on ``dev_1``,
+            ...
+        ...
+        """
+        assert self.parameters_as_bucket_view, (
+            "`_device_to_params_per_rank` should only be used if "
+            "`parameters_as_bucket_view=True`"
+        )
+        if len(self._device_to_params_per_rank_cache) == 0:
+            for rank, param_groups in enumerate(self._partition_parameters()):
+                for param_group in param_groups:
+                    for param in param_group["params"]:
+                        device = param.device
+                        if device not in self._device_to_params_per_rank_cache:
+                            self._device_to_params_per_rank_cache[device] = [
+                                [] for _ in range(self.world_size)
+                            ]
+                        self._device_to_params_per_rank_cache[device][rank].append(
+                            param
+                        )
+        return self._device_to_params_per_rank_cache
+
+    def _get_min_index(
+        self,
+        values: List[int],
+        disallowed_indices: Optional[Set[int]] = None,
+    ) -> int:
+        r"""
+        Return ``values.index(min(values))``, except only uses one pass.
+
+        It also excludes any indices in ``disallowed_indices`` if provided.
+
+        Arguments:
+            values: (List[int]): :class:`list` of values.
+            disallowed_indices (Optional[Set[int]]): indices that are
+                disallowed from being the returned min index.
+        """
+        min_index = -1
+        min_value = float("inf")
+        for i, value in enumerate(values):
+            if disallowed_indices and i in disallowed_indices:
+                continue
+            if value < min_value:
+                min_value = value
+                min_index = i
+        assert min_index >= 0, "All indices are disallowed"
+        return min_index
+
+    def _assign_bucket_subset_to_rank(
+        self,
+        bucket_index: int,
+        bucket_params: List[torch.Tensor],
+        bucket_offset: int,
+        assigned_rank: int,
+        assigned_ranks_per_bucket: List[Set[int]],
+    ) -> None:
+        r"""
+        Assign ``bucket_params`` to the rank with the least size assigned so far and collects relevant information.
+
+        The model parameters given by ``bucket_params`` represents a (possibly non-strict)
+        subset of the parameters corresponding to a :class:`DistributedDataParallel` bucket.
+
+        Arguments:
+            bucket_index (int): index of the :class:`DistributedDataParallel`
+                gradient bucket.
+            bucket_params (List[torch.Tensor]): subset of the parameters
+                corresponding to the bucket to assign.
+            bucket_offset (int): offset giving the index of the first element
+                in ``bucket_params`` in the bucket's full parameter list.
+            assigned_rank (int): group rank to assign to.
+            assigned_ranks_per_bucket (List[Set[int]]): :class:`set` of group ranks
+                assigned to each bucket.
+        """
+        overlap_info = self._overlap_info
+        if len(bucket_params) == 0:
+            raise ValueError("Empty bucket assignment")
+        params_per_rank = overlap_info.params_per_rank
+        offsets = overlap_info.offsets
+
+        self._bucket_assignments_per_rank_cache[assigned_rank][
+            bucket_index
+        ] = _DDPBucketAssignment(bucket_index, bucket_params, bucket_offset)
+        if self.global_rank == assigned_rank:
+            offsets[bucket_index] = len(params_per_rank[assigned_rank])
+        params_per_rank[assigned_rank].extend(bucket_params)
+        assigned_ranks_per_bucket[bucket_index].add(assigned_rank)
+        self._overlap_info.num_bucket_assignments += 1
+
+    @property
+    def _bucket_assignments_per_rank(self) -> List[Dict[int, _DDPBucketAssignment]]:
+        r"""
+        Return DDP bucket parameters assigned per rank.
+
+        :class:`list` of length world size consisting of :class:`dict` s
+        mapping bucket indices to :class:`_DDPBucketAssignment` s for each
+        rank.
+        """
+        assert (
+            self._overlap_with_ddp
+        ), "`_bucket_assignments_per_rank` only be used if `overlap_with_ddp=True`"
+        if len(self._bucket_assignments_per_rank_cache) > 0:
+            return self._bucket_assignments_per_rank_cache
+
+        overlap_info = self._overlap_info
+        assert overlap_info.status == _OverlapStatus.INITIALIZED
+
+        self._bucket_assignments_per_rank_cache = [{} for _ in range(self.world_size)]
+        params_per_bucket = overlap_info.params_per_bucket
+
+        if overlap_info.shard_buckets:
+            # Define the assignment threshold to approximate uniformity
+            assert overlap_info.total_size is not None, "`total_size` was not computed"
+            threshold = overlap_info.total_size / self.world_size  # type: ignore[operator]
+            size_per_rank = [0 for _ in range(self.world_size)]
+
+        num_buckets = len(params_per_bucket)
+        overlap_info.assigned_ranks_per_bucket = [set() for _ in range(num_buckets)]
+        assigned_ranks_per_bucket = overlap_info.assigned_ranks_per_bucket
+        if not overlap_info.shard_buckets:
+            # Assign each DDP bucket entirely to a single rank
+            for bucket_index, bucket_params in enumerate(params_per_bucket):
+                assert len(bucket_params) > 0, "Empty bucket"
+                assigned_rank = self._get_assigned_rank(bucket_index)
+                self._assign_bucket_subset_to_rank(
+                    bucket_index,
+                    bucket_params,
+                    0,
+                    assigned_rank,
+                    assigned_ranks_per_bucket,
+                )
+        else:
+            # Assign each DDP bucket to possibly multiple ranks
+            # Specifically, sort the DDP buckets by increasing size, and for
+            # each bucket, iteratively assign the maximal unassigned subset
+            # with size less than `threshold` to the rank with the least total
+            # size so far -- each such assignment is represented by a
+            # `_DDPBucketAssignment` instance and only contains parameters from
+            # a single DDP bucket
+            params_per_bucket_enum = sorted(
+                enumerate(params_per_bucket), key=lambda x: sum(p.numel() for p in x[1])
+            )
+            for bucket_index, bucket_params in params_per_bucket_enum:
+                assert len(bucket_params) > 0, "Empty bucket"
+                bucket_offset = 0
+                assignment_size = 0
+                for param_index, param in enumerate(bucket_params):
+                    param_numel = param.numel()
+                    if (
+                        assignment_size + param_numel >= threshold
+                        and param_index > bucket_offset
+                    ):
+                        assigned_rank = self._get_min_index(
+                            size_per_rank, assigned_ranks_per_bucket[bucket_index]
+                        )
+                        # Include up to but not including the parameter that
+                        # exceeded the threshold
+                        self._assign_bucket_subset_to_rank(
+                            bucket_index,
+                            bucket_params[bucket_offset:param_index],
+                            bucket_offset,
+                            assigned_rank,
+                            assigned_ranks_per_bucket,
+                        )
+                        size_per_rank[assigned_rank] += assignment_size
+                        bucket_offset = param_index
+                        assignment_size = 0
+                    assignment_size += param_numel
+                # Assign the remainder of the bucket so that no assignment
+                # spans across two buckets
+                assigned_rank = self._get_min_index(
+                    size_per_rank, assigned_ranks_per_bucket[bucket_index]
+                )
+                self._assign_bucket_subset_to_rank(
+                    bucket_index,
+                    bucket_params[bucket_offset:],
+                    bucket_offset,
+                    assigned_rank,
+                    assigned_ranks_per_bucket,
+                )
+                size_per_rank[assigned_rank] += assignment_size
+
+        return self._bucket_assignments_per_rank_cache
+
+    def _local_step(
+        self,
+        gradients: Optional[List[Optional[torch.Tensor]]] = None,
+        closure: Optional[Callable[[], float]] = None,
+        **kwargs: Any,
+    ) -> Optional[float]:
+        r"""
+        Perform a single optimizer step without syncing parameters across ranks.
+
+        Arguments:
+            gradients (list[Optional[torch.Tensor]], optional): a :class:`list`
+                of length equal to the number of parameters assigned to this
+                rank containing gradient tensors or ``None`` as its elements;
+                a ``None`` in the :class:`list` indicates that the
+                corresponding parameter should not be updated.
+                If the argument itself is ``None``, then all parameters are
+                updated, and the gradients are assumed to be already populated.
+                (default: ``None``)
+            closure (Callable): a closure that re-evaluates the model and
+                returns the loss; optional for most optimizers and should be
+                ``None`` if ``gradients`` is not ``None``; (default: ``None``)
+        Returns:
+            Optional loss depending on the underlying local optimizer.
+
+        .. warning::
+            The argument ``gradients`` should only be specified (i.e. not
+            ``None``) if ``overlap_with_ddp=True``, in which case
+            :class:`ZeroRedundancyOptimizer` wraps a functional optimizer.
+        """
+        Join.notify_join_context(self)
+        # Check if the model trainability has changed
+        is_trainable_mask = self._get_is_trainable_mask()
+        if is_trainable_mask != self._is_trainable_mask:
+            if self._overlap_with_ddp:
+                raise RuntimeError(
+                    "ZeroRedundancyOptimizer with `overlap_with_ddp=True` "
+                    "does not support changing parameter trainability at run "
+                    "time"
+                )
+            logger.warning(
+                "ZeroRedundancyOptimizer detected that the trainable "
+                "parameters changed; rebuilding the parameter buckets if "
+                "enabled"
+            )
+            self._build_param_buckets()
+            self._is_trainable_mask = is_trainable_mask
+
+        # Sync the exposed `param_groups` attributes to the local optimizer in
+        # case they have been updated
+        self._sync_param_groups(self.param_groups, self.optim.param_groups)
+
+        # Run the optimizer step on this shard only
+        if gradients is None:
+            loss = (
+                self.optim.step(**kwargs)
+                if closure is None
+                else self.optim.step(closure=closure, **kwargs)
+            )
+        else:
+            assert self._overlap_with_ddp, (
+                "Specifying `gradients` should not "
+                "be used when `overlap_with_ddp=False`"
+            )
+            assert (
+                closure is None
+            ), "`closure` is not supported when using a local functional optimizer"
+            loss = self.optim.step(gradients=gradients)
+
+        # Sync any updated attributes in the local optimizer to the exposed
+        # `param_groups`
+        self._sync_param_groups(self.optim.param_groups, self.param_groups)
+
+        return loss
+
+    def step(
+        self,
+        closure: Optional[Callable[[], float]] = None,
+        **kwargs: Any,
+    ) -> Optional[float]:
+        r"""
+        Perform a single optimizer step and syncs parameters across all ranks.
+
+        Arguments:
+            closure (Callable): a closure that re-evaluates the model and
+                returns the loss; optional for most optimizers.
+        Returns:
+            Optional loss depending on the underlying local optimizer.
+
+        .. note: Any extra parameters are passed to the base optimizer as-is.
+        """
+        if self._overlap_with_ddp:
+            logger.warning(
+                "`step()` should not be included in the training loop when "
+                "`overlap_with_ddp=True`"
+            )
+            return None
+
+        # Perform the local optimizer step
+        loss = self._local_step(closure=closure, **kwargs)
+
+        # Sync all of the updated parameter shards across the ranks
+        self._sync_params()
+
+        return loss
+
+    def join_hook(self, **kwargs):
+        r"""
+        Return the ZeRO join hook.
+
+        It enables training on uneven inputs by
+        shadowing the collective communications in the optimizer step.
+
+        Gradients must be properly set before this hook is called.
+
+        Arguments:
+            kwargs (dict): a :class:`dict` containing any keyword arguments
+                to modify the behavior of the join hook at run time; all
+                :class:`Joinable` instances sharing the same join context
+                manager are forwarded the same value for ``kwargs``.
+
+        This hook does not support any keyword arguments; i.e. ``kwargs`` is
+        unused.
+        """
+        return _ZeROJoinHook(self)
+
+    @property
+    def join_device(self) -> torch.device:
+        r"""Return default device."""
+        return self._default_device
+
+    @property
+    def join_process_group(self) -> Any:
+        r"""Return process group."""
+        return self.process_group
+
+    def load_state_dict(self, state_dict: Dict[str, Any]) -> None:
+        r"""
+        Load the state pertaining to the given rank from the input ``state_dict``, updating the local optimizer as needed.
+
+        Arguments:
+            state_dict (dict): optimizer state; should be an object returned
+                from a call to :meth:`state_dict`.
+
+        Raises:
+            RuntimeError: if ``overlap_with_ddp=True`` and this method is
+                called before this :class:`ZeroRedundancyOptimizer` instance
+                has been fully initialized, which happens once
+                :class:`DistributedDataParallel` gradient buckets have been
+                rebuilt.
+        """
+        self._check_overlap_initialized()
+
+        for index, value in state_dict["state"].items():
+            param = self._index_to_param[index]
+            if self._param_to_rank[param] != self.rank:
+                # Clear any state irrelevant to this rank
+                state_dict["state"][index] = None
+            else:
+                # Load the parameter state to the local optimizer
+                self.optim.state[param] = _recursive_copy_to_device(
+                    value, non_blocking=True, device=param.device
+                )
+                # Force zero-dimensional tensors (like Adam "step") on CPU
+                for state_name, state_value in self.optim.state[param].items():
+                    if torch.is_tensor(state_value) and state_value.dim() == 0:
+                        self.optim.state[param][state_name] = state_value.cpu()
+
+        super().load_state_dict(state_dict)
+
+        # Sync the input state with the exposed and local optimizer states
+        self._sync_param_groups(state_dict["param_groups"], self.param_groups)
+        self._sync_param_groups(self.param_groups, self.optim.param_groups)
+
+    def state_dict(self) -> Dict[str, Any]:
+        r"""
+        Return the last global optimizer state known to this rank.
+
+        .. warning:
+            If the state has not been consolidated to this rank, this raises a
+            runtime error, and even if it has, the state may not be up-to-date,
+            depending on when :meth:`consolidate_state_dict` was last called.
+
+        Raises:
+            RuntimeError: if ``overlap_with_ddp=True`` and this method is
+                called before this :class:`ZeroRedundancyOptimizer` instance
+                has been fully initialized, which happens once
+                :class:`DistributedDataParallel` gradient buckets have been
+                rebuilt; or if this method is called without a preceding call
+                to :meth:`consolidate_state_dict`.
+        """
+        self._check_overlap_initialized()
+
+        if len(self._all_state_dicts) == 0:
+            raise RuntimeError(
+                "Optimizer state has not been consolidated on this rank. "
+                f"Please call `consolidate_state_dict(to={self.rank})` on "
+                "all ranks beforehand if you meant to save the global state."
+            )
+
+        # Get the possibly-stale global optimizer state that uses global
+        # parameter indexing
+        state_dict = super().state_dict()
+
+        # Update the global optimizer state with local state information,
+        # factoring in the translation from local to global indexing
+        for rank, local_state_dict in enumerate(self._all_state_dicts):
+            local_param_groups = local_state_dict["param_groups"]
+            global_param_groups = self._partition_parameters()[rank]
+            assert len(local_param_groups) == len(
+                global_param_groups
+            ), "Mismatch between number of local and global parameter groups"
+
+            for local_param_group, global_param_group in zip(
+                local_param_groups, global_param_groups
+            ):
+                # `local_param_group` stores local indices, while
+                # `global_param_group` stores the tensors directly
+                local_param_indices = local_param_group["params"]
+                global_params = global_param_group["params"]
+
+                assert len(local_param_indices) == len(
+                    global_params
+                ), "Mismatch between number of local and global parameters in parameter group"
+                for local_param_index, global_param in zip(
+                    local_param_indices, global_params
+                ):
+                    # Update the global parameter state, if any
+                    if local_param_index in local_state_dict["state"]:
+                        global_param_index = self._param_to_index[global_param]
+                        state_dict["state"][global_param_index] = local_state_dict[
+                            "state"
+                        ][local_param_index]
+
+        # Sort the parameters in the state
+        state_dict["state"] = dict(sorted(state_dict["state"].items()))
+        return state_dict
+
+    @staticmethod
+    def _sync_param_groups(
+        src_param_groups: List[Dict[Any, Any]],
+        dst_param_groups: List[Dict[Any, Any]],
+    ) -> None:
+        r"""
+        Sync the attributes from the source parameter groups to the destination parameter groups.
+
+        Example attributes include learning rate or scheduler attributes. The
+        two parameter groups should have the same length (i.e. same number of
+        parameter groups).
+
+        Arguments:
+            src_param_groups (list[dict]): parameter groups giving the
+                attribute settings to copy.
+            dst_param_groups (list[dict]): parameter groups giving the
+                attribute settings to set.
+        """
+        assert len(src_param_groups) == len(
+            dst_param_groups
+        ), "Mismatch between number of source and destination parameter groups"
+        for src_param_group, dst_param_group in zip(src_param_groups, dst_param_groups):
+            # Sync all attributes except the parameters
+            for attr in filter(lambda x: x != "params", src_param_group.keys()):
+                dst_param_group[attr] = src_param_group[attr]
+
+    def _build_param_buckets(self) -> None:
+        r"""
+        Build parameter buckets if ``parameters_as_bucket_view=True``.
+
+        For each device that stores this rank's parameters, there is a
+        bucket (represented as a tensor) containing all of the parameters on
+        that device that are assigned to a given rank in the parameter update
+        partition.
+
+        This method is called in the constructor and any time parameter
+        trainability is changed.
+
+        .. warning::
+            The current implementation assumes that all of the parameters in a
+            bucket are of the same dense type when allocating the bucket's
+            tensor.
+
+        .. warning::
+            If the model parameters are stored across more than one device,
+            then the storage partitioning must be the same across all
+            processes in order for parameter synchronization to work.
+        """
+        if not self.parameters_as_bucket_view or self._overlap_with_ddp:
+            return
+
+        # `self._buckets[i][j]` are the parameters stored on device i and
+        # assigned to rank j
+        num_devices = len(self._device_to_params_per_rank)
+        self._buckets = [[] for _ in range(num_devices)]  # type: ignore[assignment]
+
+        for dev_i, (device, params_per_rank) in enumerate(
+            self._device_to_params_per_rank.items()
+        ):
+            for params in params_per_rank:
+                bucket_size = 0
+                dtype = None
+                trainable_params = []
+                for param in params:
+                    if not _is_trainable(param):
+                        # Clone in case the parameter was previously part of
+                        # a bucket to avoid the data from being destroyed
+                        param.data = param.data.detach().clone()
+                    else:
+                        bucket_size += param.numel()
+                        trainable_params.append(param)
+                    dtype = param.dtype  # assumes all same dtype
+
+                if bucket_size == 0:
+                    # Create a dummy bucket if there are no parameters
+                    bucket = torch.zeros(1, device=device)
+                else:
+                    # Construct the bucket (assuming all dense and same dtype)
+                    bucket = torch.empty(bucket_size, dtype=dtype, device=device)
+                    offset = 0
+                    for param in trainable_params:
+                        offset_next = offset + param.numel()
+                        bucket[offset:offset_next].copy_(param.data.flatten())
+                        param.data = bucket[offset:offset_next].view_as(param.data)
+                        offset = offset_next
+                self._buckets[dev_i].append(bucket)  # type: ignore[arg-type]
+
+    def _build_ddp_param_buckets(self) -> None:
+        r"""
+        Build the DDP bucket with parameters assigned to this rank.
+
+        For each DDP bucket with parameters assigned to this rank, flattens the
+        data of those parameters into a single tensor and saves the tensor to
+        the ``tensor`` attribute in the corresponding
+        :class:`_DDPBucketAssignment` instance stored in
+        ``self._bucket_assignments_per_rank``.
+
+        :class:`DistributedDataParallel` guarantees that the parameters
+        corresponding to a gradient bucket have the same device and the same
+        dtype.
+        """
+        for bucket_assignments in self._bucket_assignments_per_rank:
+            for bucket_assignment in bucket_assignments.values():
+                params = bucket_assignment.parameters
+                bucket_size = 0
+                dtype = None
+                for param in params:
+                    assert _is_trainable(param), (
+                        "Model parameter "
+                        "corresponding to a gradient in a DDP bucket should "
+                        "require a gradient"
+                    )
+                    bucket_size += param.numel()
+                    dtype = param.dtype  # assumes all same dtype
+                assert bucket_size > 0, "Empty bucket"
+
+                # Construct the bucket tensor (assuming all dense and same dtype)
+                tensor = torch.empty(
+                    bucket_size, dtype=dtype, device=bucket_assignment.device
+                )
+                offset = 0
+                for param in params:
+                    offset_next = offset + param.numel()
+                    tensor[offset:offset_next].copy_(param.data.flatten())
+                    param.data = tensor[offset:offset_next].view_as(param.data)
+                    offset = offset_next
+                bucket_assignment.tensor = tensor
+
+    def _verify_and_init_params(
+        self,
+        params: Any,
+    ) -> Union[List[torch.Tensor], List[dict]]:
+        r"""
+        Verify the type of ``params`` and initializes ``self._all_params`` as a :class:`list` of all parameters.
+
+        The initializagtion will first make sure that provided ``params`` is valid.
+
+        Arguments:
+            params (Any): Candidate parameter list or parameter groups to verify.
+
+        Raises:
+            TypeError: ``params`` has an invalid type.
+            ValueError: ``params`` is empty.
+
+        Returns:
+            The persistent form of ``params`` to be passed into the parent
+            :class:`Optimizer` constructor -- i.e. returns ``params`` as a
+            :class:`list` to ensure that it can be iterated over again.
+        """
+        if isinstance(params, torch.Tensor):
+            raise TypeError(
+                "`params` argument should be an iterable of "
+                f"Tensors, but got {torch.typename(params)}"
+            )
+        try:
+            all_params = list(params)
+        except TypeError as e:
+            raise TypeError(
+                "`params` argument should be an iterable of Tensors"
+                f" or dicts, but got {torch.typename(params)}"
+            ) from e
+        if len(all_params) == 0:
+            raise ValueError("ZeroRedundancyOptimizer got an empty parameter list")
+        all_tensors = True
+        all_dicts = True
+        for param in all_params:
+            all_tensors &= isinstance(param, torch.Tensor)
+            all_dicts &= isinstance(param, dict)
+        if not all_tensors and not all_dicts:
+            raise TypeError(
+                "`params` argument should be an iterable of Tensors or dicts"
+            )
+        # Ensure that `self._all_params` contains a list of all parameters
+        if all_tensors:
+            self._all_params = all_params
+        elif all_dicts:
+            self._all_params = []
+            # `all_params` contains parameter groups (not parameters)
+            for param_group in all_params:
+                if "params" not in param_group:
+                    raise ValueError(
+                        "Each parameter group passed-in via `params` must "
+                        "have a 'params' key mapping to the parameters in "
+                        "the group"
+                    )
+                self._all_params.extend(param_group["params"])
+        return all_params
+
+    def _verify_same_dense_param_type(self) -> None:
+        r"""
+        Verify that all parameters are of the same dense type.
+
+        The method assumes that ``self._all_params`` has been initialized
+        and is non-empty.
+
+        Raises:
+            ValueError: ``params`` contains sparse parameters or parameters
+            of varying dense types.
+
+        NOTE: This method can be removed once support for sparse parameters
+        and varying parameter types is added.
+        """
+        typename = torch.typename(self._all_params[0])
+        if self._all_params[0].is_sparse:
+            raise ValueError(
+                "ZeroRedundancyOptimizer only supports using "
+                "the same dense type for all parameters but got "
+                f"{typename}"
+            )
+        for param in self._all_params[1:]:
+            other_typename = torch.typename(param)
+            if other_typename != typename:
+                raise ValueError(
+                    "ZeroRedundancyOptimizer only supports "
+                    "using the same dense type for all "
+                    f"parameters but got both {typename} and "
+                    f"{other_typename}"
+                )
+
+    def _get_is_trainable_mask(self) -> List[bool]:
+        r"""Return a boolean mask indicating if each parameter is trainable (``requires_grad``) or not."""
+        return list(map(_is_trainable, self._all_params))
+
+    def _init_local_optimizer(self) -> None:
+        r"""
+        Initialize this rank's local optimizer, responsible for its subset of the parameters.
+
+        The local optimizer is saved in ``self.optim``.
+        """
+        assert (
+            self._optim_constructor is not None
+        ), "The local optimizer class has not been set"
+
+        param_groups = self._partition_parameters()[self.rank]
+        # `overlap_with_ddp=True` requires a local functional optimizer
+        if self._overlap_with_ddp:
+            # Functional optimizers only support a single parameter group and
+            # require passing in the parameters as a list
+            assert len(param_groups) == 1, (
+                "Initializing the local "
+                "functional optimizer with more than one parameter group"
+            )
+            params = param_groups[0]["params"]
+            # Try to pass `_allow_empty_param_list=True` to avoid erroring
+            if (
+                "_allow_empty_param_list"
+                in inspect.signature(self._optim_constructor).parameters
+            ):
+                self.optim: Any = self._optim_constructor(
+                    params, **self._optim_defaults, _allow_empty_param_list=True
+                )
+            else:
+                logger.warning(
+                    "%s does not support the argument "
+                    "`_allow_empty_param_list`; ZeroRedundancyOptimizer may "
+                    "error due to an empty parameter list",
+                    self._optim_constructor,
+                )
+                self.optim: Any = self._optim_constructor(params, **self._optim_defaults)  # type: ignore[no-redef]
+
+            # Log information about the DDP and ZeRO bucketing
+            if dist.get_debug_level() != dist.DebugLevel.OFF:
+                local_numel = sum(p.numel() for p in params)
+                num_assigned_buckets = len(
+                    self._bucket_assignments_per_rank[self.global_rank]
+                )
+                logger.info(
+                    "rank %s with %s parameters " "across %s buckets",
+                    self.global_rank,
+                    local_numel,
+                    num_assigned_buckets,
+                )
+                if self.global_rank == 0:
+                    logger.info(
+                        "%s DDP " "buckets and " "%s bucket " "assignments",
+                        len(self._overlap_info.params_per_bucket),
+                        self._overlap_info.num_bucket_assignments,
+                    )
+        else:
+            # NOTE: Passing `param_groups` into the local optimizer constructor
+            # bypasses the empty parameter list check
+            self.optim: Optimizer = self._optim_constructor(param_groups, **self._optim_defaults)  # type: ignore[no-redef]
+
+        # TODO: Manually add `self.param_groups` if using a functional
+        # optimizer; remove this if/when the functional optimizers support
+        # multiple parameter groups
+        if self._overlap_with_ddp and not hasattr(self.optim, "param_groups"):
+            assert hasattr(self.optim, "param_group"), (
+                "The functional optimizer should set at least one of the "
+                "attributes `param_group` or `param_groups`"
+            )
+            self.optim.param_groups = [self.optim.param_group]  # type: ignore[attr-defined]
+
+        self._sync_param_groups(self.optim.param_groups, self.param_groups)
+
+    def _init_zero_for_overlap(self) -> None:
+        r"""Perform a delayed initialization of the local optimizer and the supporting data structures."""
+        assert self._overlap_with_ddp, (
+            "`_init_zero_for_overlap()` should only be called when "
+            "`overlap_with_ddp=True`"
+        )
+        self._overlap_info.status = _OverlapStatus.INITIALIZED
+        self._clear_cache()
+        self._partition_parameters(self._overlap_info.params_per_rank)
+        self._build_ddp_param_buckets()
+        self._init_local_optimizer()
+
+    def _get_assigned_rank(self, bucket_index: int) -> int:
+        r"""
+        Return the single rank assigned to a :class:`DistributedDataParallel` gradient bucket.
+
+        Arguments:
+            bucket_index (int): index of the :class:`DistributedDataParallel`
+                bucket for which to get the assigned rank.
+        """
+        assert not self._overlap_info.shard_buckets, (
+            "The bucket assignment requires global bucket information and "
+            "will be computed later; there should be no need to use this "
+            "method"
+        )
+        return bucket_index % self.world_size
+
+    def _check_overlap_initialized(self):
+        r"""
+        Check the delayed initialization depending on the value of ``overlap_with_ddp``.
+
+        The delayed initialization has occurred (see
+        :meth:`_init_zero_for_overlap`) if ``overlap_with_ddp=True``, and
+        raises a ``RuntimeError`` if not. This should preface methods that
+        should not be run before that delayed initialization.
+
+        Raises:
+            RuntimeError: if ``overlap_with_ddp=True`` and
+                :meth:`_init_zero_for_overlap` has not been called.
+        """
+        if (
+            self._overlap_with_ddp
+            and self._overlap_info.status != _OverlapStatus.INITIALIZED
+        ):
+            raise RuntimeError(
+                "This method should not be called until this "
+                "ZeroRedundancyOptimizer instance has been fully "
+                "initialized"
+            )
+
+    def _get_optimizer_constructor(self, optimizer_class: Any) -> Any:
+        r"""
+        Return the optimizer constructor using validation and transformation depending on ``overlap_with_ddp``.
+
+        Returns:
+            - ``optimizer_class`` if ``overlap_with_ddp=False`` and
+                ``optimizer_class`` is not a functional optimizer.
+            - ``optimizer_class`` if ``overlap_with_ddp=True`` and
+                ``optimizer_class`` is already a functional optimizer.
+            - The functional equivalent of ``optimizer_class`` if
+                ``overlap_with_ddp=True`` and ``optimizer_class`` is not
+                already a functional optimizer (assuming the equivalent
+                exists).
+
+        Raises:
+            ValueError:
+
+                - if ``overlap_with_ddp=True`` but ``optimizer_class`` is
+                    neither a functional optimizer nor translatable to a
+                    functional optimizer.
+                - if ``overlap_with_ddp=False`` and ``optimizer_class`` is a
+                    functional optimizer.
+        """
+        functional_optims = functional_optim_map.values()
+        if not self._overlap_with_ddp:
+            if optimizer_class in functional_optims:
+                # Using a functional optimizer is only supported when
+                # `overlap_with_ddp=True`
+                raise ValueError(
+                    f"Passing in a functional optimizer {optimizer_class} "
+                    "when `overlap_with_ddp=False`"
+                )
+            else:
+                return optimizer_class
+        else:
+            if optimizer_class in functional_optims:
+                # Already a functional optimizer
+                return optimizer_class
+            elif optimizer_class in functional_optim_map:
+                # Translate the passed-in optimizer class to its functional
+                # equivalent if `overlap_with_ddp=True`
+                optim_constructor = functional_optim_map[optimizer_class]
+                logger.info(
+                    "Using the functional optimizer %s "
+                    "instead of %s since "
+                    "`overlap_with_ddp=True`",
+                    optim_constructor,
+                    optimizer_class,
+                )
+                return optim_constructor
+            else:
+                raise ValueError(
+                    "Using `ddp_with_overlap=True` requires using a "
+                    "functional optimizer, but there is no supported functional "
+                    f"optimizer equivalent for {optimizer_class}"
+                )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/_IR.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/_IR.py
new file mode 100644
index 0000000000000000000000000000000000000000..036ad6cf8621eb4e0473f5ba6494f347d90d97d4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/_IR.py
@@ -0,0 +1,1243 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and affiliates
+import copy
+import logging
+import operator
+from collections import defaultdict
+from enum import Enum
+from inspect import Parameter, Signature, signature
+from types import MethodType
+from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
+
+import torch
+import torch.fx as fx
+from torch.distributed import ProcessGroup
+from torch.export import ExportedProgram
+from torch.export.unflatten import (
+    _assign_attr,
+    _AttrKind,
+    _sink_params,
+    InterpreterModule,
+)
+from torch.fx.node import map_aggregate
+from torch.fx.passes.split_module import split_module
+
+from ._backward import _null_coalesce_accumulate, stage_backward
+from ._unflatten import _outline_submodules
+from ._utils import PipeInfo
+from .stage import _PipelineStage
+
+
+logger = logging.getLogger(__name__)
+
+# TODO:
+# 1. investigate gradient sync for shared parameters. how does DDP do it?
+# 2. Add parameter movement to split_module
+
+
+def _find_loss_from_output_and_spec(output_val, spec_val):
+    if spec_val is False:
+        return None
+    if spec_val is True:
+        if not isinstance(output_val, fx.Node):
+            raise RuntimeError(
+                f"Loss spec must specify a dynamic value but got {output_val}"
+            )
+        return output_val
+
+    if isinstance(spec_val, (tuple, list)):
+        if not isinstance(output_val, (tuple, list)):
+            raise RuntimeError(
+                f"Output value {output_val} must match type of loss specification "
+                f"{spec_val}"
+            )
+        if len(output_val) != len(spec_val):
+            raise RuntimeError(
+                f"Output value {output_val} must match length of loss specification "
+                f"{spec_val}"
+            )
+        for out, spec in zip(output_val, spec_val):
+            loss_val = _find_loss_from_output_and_spec(out, spec)
+            if loss_val is not None:
+                return loss_val
+        raise RuntimeError(f"Did not find loss value in specification {spec_val}")
+
+    if isinstance(spec_val, dict):
+        if not isinstance(output_val, dict):
+            raise RuntimeError(
+                f"Output value {output_val} must match type of loss specification "
+                f"{spec_val}"
+            )
+        if set(output_val.keys()) != set(spec_val.keys()):
+            raise RuntimeError(
+                f"Output value {output_val} must match keys of loss specification "
+                f"{spec_val}"
+            )
+        for k in spec_val:
+            loss_val = _find_loss_from_output_and_spec(output_val[k], spec_val[k])
+            if loss_val is not None:
+                return loss_val
+        raise RuntimeError(f"Did not find loss value in specification {spec_val}")
+
+    raise RuntimeError(f"Unsupported type {type(spec_val)} in loss specification")
+
+
+def _find_loss_output(mod: torch.nn.Module, g: fx.Graph, output_loss_value_spec):
+    output_nodes = [n for n in g.nodes if n.op == "output"]
+    assert len(output_nodes) == 1
+    output_node = output_nodes[0]
+    output_val = output_node.args[0]
+    generated_spec: Any = None
+
+    if isinstance(mod, TrivialLossWrapper):
+        # TrivialLossWrapper is pre-defined by PiPPy.
+        # It has loss as the only output so we can safely assume the first output arg is the loss.
+        assert len(output_node.args) == 1
+        loss_node = output_val
+        generated_spec = TrivialLossWrapper.loss_spec
+    elif output_loss_value_spec is None:
+        # Use default spec, i.e. search for "loss" in output values
+        if isinstance(output_val, dict) and "loss" in output_val.keys():
+            loss_node = output_val["loss"]
+            generated_spec = {k: k == "loss" for k in output_val}
+        else:
+            loss_node = None
+            generated_spec = None
+    else:
+        loss_node = _find_loss_from_output_and_spec(output_val, output_loss_value_spec)
+        generated_spec = output_loss_value_spec
+
+    return loss_node, output_node, generated_spec
+
+
+def _insert_stage_symbolic_backward(
+    g: fx.Graph,
+    loss_node: fx.Node,
+    output_node: fx.Node,
+):
+    # Collect metadata about tuple output values. TODO: move this to split_module or FX IR
+    tuples: Dict[fx.Node, Tuple] = {}
+    for node in reversed(g.nodes):
+        if node.op == "call_function":
+            # In the forward pass, only emit placeholder, module calls, and
+            # getitem calls. If we have a target other than getitem in this
+            # (forward-only) code, there is a bug.
+            assert node.target == operator.getitem, (
+                "Found non-getitem call in forward pass. "
+                "Please report a bug to PiPPy"
+            )
+            assert (
+                len(node.args) == 2
+            ), "Found malformed getitem call. Please report a bug to PiPPy"
+            indexed_value, node_idx = tuple(node.args)
+
+            # indexed_value is a collection that we are indexing into. It could
+            # exist in the tuples map if we've processed another `getitem`
+            # already.
+            existing_list_size = (
+                len(tuples[indexed_value]) if indexed_value in tuples else -1
+            )
+            new_list_size = max(node_idx + 1, existing_list_size)
+
+            reconstructed_list = [None for _ in range(new_list_size)]
+
+            # Copy over existing elements if present
+            if indexed_value in tuples:
+                for i, val in enumerate(tuples[indexed_value]):
+                    reconstructed_list[i] = val
+
+            # Populate value represented by this node
+            reconstructed_list[node_idx] = node
+
+            tuples[indexed_value] = tuple(reconstructed_list)
+
+    # Keep track of nodes that dominate the loss node.
+    # We will only emit backward operations for nodes that can contribute
+    # to the specified loss value.
+    live_nodes = {loss_node: None}
+    val_to_grad: Dict[fx.Node, Optional[fx.Node]] = {loss_node: None}
+
+    def assign_or_accumulate_grad(forward_node, grad_value):
+        if forward_node in val_to_grad and forward_node.op != "placeholder":
+            grad_value = g.call_function(
+                _null_coalesce_accumulate,
+                (val_to_grad[forward_node], grad_value),
+            )
+        val_to_grad[forward_node] = grad_value
+
+    with g.inserting_before(output_node):
+        for node in reversed(g.nodes):
+            if node not in live_nodes:
+                continue
+
+            def add_to_live_nodes(n):
+                live_nodes.setdefault(n, None)
+
+            fx.node.map_arg(node.args, add_to_live_nodes)
+            fx.node.map_arg(node.kwargs, add_to_live_nodes)
+            if node.op == "call_module":
+                output_grads: Union[Tuple[Optional[fx.Node], ...], Optional[fx.Node]]
+                if node in tuples:
+                    stage_output = tuples[node]
+                    output_grads = tuple(val_to_grad.get(n, None) for n in tuples[node])
+                    outputs_with_grads_idxs = [
+                        i for i, n in enumerate(tuples[node]) if n in live_nodes
+                    ]
+                else:
+                    stage_output = (node,)
+                    output_grads = val_to_grad[node]
+                    outputs_with_grads_idxs = [0]
+
+                output_grads = (
+                    (output_grads,)
+                    if not isinstance(output_grads, tuple)
+                    else output_grads
+                )
+
+                grad_call = g.call_function(
+                    stage_backward,
+                    kwargs={
+                        "stage_output": stage_output,
+                        "output_grads": output_grads,
+                        "input_values": list(node.all_input_nodes),
+                        "outputs_with_grads_idxs": outputs_with_grads_idxs,
+                    },
+                )
+                # Insert backward stage debug info
+                kwargs_copy = dict(grad_call.kwargs)
+                grad_call.kwargs = kwargs_copy
+
+                grad_call_proxy = fx.Proxy(grad_call)
+                grads = grad_call_proxy.node
+
+                input_nodes = list(node.all_input_nodes)
+                grads_proxy = fx.Proxy(grads)
+                for i, input_node in enumerate(input_nodes):
+                    assign_or_accumulate_grad(input_node, grads_proxy[i].node)  # type: ignore[index]
+
+    return g
+
+
+class PipeSequential(torch.nn.Sequential):
+    @staticmethod
+    def from_sequential(sequential_instance: torch.nn.Sequential):
+        return PipeSequential(*[copy.copy(m) for m in sequential_instance])
+
+    def forward(self, input):
+        for i, module in enumerate(self):
+            input = module(input)
+            if i != len(self) - 1:
+                pipe_split()
+        return input
+
+
+class LossWrapper(torch.nn.Module):
+    """
+    LossWrapper is a convenient abstract class that allows you to wrap up both
+    your model as well as its loss function and specify the connectivity between
+    the inputs, model, loss function, and output value. Example::
+
+        class MyModelWrapper(LossWrapper):
+            def forward(self, x, targets):
+                model_out = self.module(x)
+                loss_value = self.loss_fn(model_out, targets)
+                return loss_value
+
+    The above example defines a connectivity where we expect the forward/loss/backward
+    training procedure to take two arguments (x and targets), pass x into the module
+    to get the output of the feedforward computation, pass the model output and the
+    targets value into the loss function, and get and return the loss value, which will
+    be backpropagated by PiPPy. The above class would then be instantiated like::
+
+        model = ... # instantiate the model
+        loss_fn = torch.nn.MSELoss() # for the sake of demonstration
+
+        wrapper = MyModelWrapper(model, loss_fn)
+        pipe = Pipe.from_tracing(wrapper, ...)
+
+    """
+
+    def __init__(self, module, loss_fn):
+        super().__init__()
+        self.module = module
+        self.loss_fn = loss_fn
+
+    def forward(self, *args, **kwargs):
+        raise NotImplementedError(
+            "This instance of LossWrapper does not have an overridden"
+            "forward(). Please implement forward() to specify the arguments, "
+            "connection between the module and loss, and loss output "
+            "value."
+        )
+
+
+class TrivialLossWrapper(LossWrapper):
+    def forward(self, x, targets):
+        model_out = self.module(x)
+        return self.loss_fn(model_out, targets)
+
+    loss_spec = True
+
+
+# Pipe model representation
+#
+# Pipe can be thought of as an `nn.Sequential++`. That is to say: it specifies
+# a single topological ordering of pipeline "stages" that, when run in series,
+# constitutes all of the operations of the program. However, unlike `nn.Sequential`,
+# Pipe allows non-local usages of values, so long as those uses still respect
+# topological ordering. In particular:
+#
+# 1. Non-local activations. This type of usage can appear in, for example, skip
+#    connections. These values will be directly transmitted from the "def" stage
+#    to all stages that use them skipping intermediate stages. During autograd,
+#    gradients will be propagated back through this skip connection reverse
+#    to how activations propagated in the forward pass.
+# 2. Non-local parameter/module invocations. This occurs when a parameter is used
+#    in a stage downstream of where it is resident. These values can be carried
+#    forward similarly to (1), but in addition one might want to replicate the
+#    value on multiple stages. Gradients for these shared parameters will be
+#    accumulated separately on each stage, but there will be an additional
+#    gradient accumulation before the optimizer step.
+
+
+# Register `_pipe_split()` as an ATen operator. This is required for Export to
+# preserve this marker in the graph.
+torch.library.define("pippy::_pipe_split", "() -> ()")
+
+
+@torch.library.impl("pippy::_pipe_split", "BackendSelect")
+def _pipe_split():
+    return None
+
+
+@torch.library.register_fake("pippy::_pipe_split")  # type: ignore[no-redef]
+def _pipe_split():  # noqa: F811
+    return None
+
+
+# Add an alias for convenience
+aten_pipe_split_alias = torch.ops.pippy._pipe_split.default
+
+# Ask Export to preserve the `_pipe_split` op.
+# See examples in pytorch/torch/fx/node.py
+fx.node._side_effectful_functions.add(aten_pipe_split_alias)
+
+
+# User facing API
+def pipe_split():
+    """
+    pipe_split is a special operator that is used to mark the boundary between
+    stages in a module. It is used to split the module into stages. It is a
+    no-op if your annotated module is run eagerly.
+
+    Example:
+        >>> # xdoctest: +SKIP
+        >>> def forward(self, x):
+        >>>     x = torch.mm(x, self.mm_param)
+        >>>     x = torch.relu(x)
+        >>>     pipe_split()
+        >>>     x = self.lin(x)
+        >>>     return x
+
+    The above example will be split into two stages.
+    """
+    return torch.ops.pippy._pipe_split()
+
+
+class MultiUseParameterConfig(Enum):
+    TRANSMIT = 1
+    REPLICATE = 2
+
+
+MultiUseParamSpec = Union[MultiUseParameterConfig, Dict[str, MultiUseParameterConfig]]
+
+
+class DetachExecutor(fx.Interpreter):
+    """
+    Special interpreter to run the split_gm in testing that detaches all inputs to
+    a module invocation. This is needed so that the values at the boundary are
+    leaf modules in autograd execution.
+    """
+
+    def __init__(self, module, garbage_collect_values=True):
+        garbage_collect_values = False
+        super().__init__(module, garbage_collect_values)
+        self.value_remap = {}
+
+    def run(self, *args, initial_env=None):
+        self.value_remap = {}
+        return super().run(*args, initial_env=initial_env)
+
+    def call_module(self, target, args, kwargs):
+        def detach_tensors(a):
+            if isinstance(a, torch.Tensor) and a.requires_grad:
+                if a not in self.value_remap:
+                    new_val = a.detach().requires_grad_(True)
+                    self.value_remap[a] = new_val
+                return self.value_remap[a]
+            else:
+                return a
+
+        """
+        def dont_traverse_size(a):
+            return type(a) != torch.Size
+        """
+
+        args = map_aggregate(
+            args,
+            detach_tensors,  # dont_traverse_size
+        )
+        kwargs = map_aggregate(
+            kwargs,
+            detach_tensors,  # dont_traverse_size
+        )
+
+        return super().call_module(target, args, kwargs)
+
+    def call_function(self, target, args, kwargs):
+        # HACK to reroute saved input tensors to point to the detach()ed version
+        if target == stage_backward:
+            kwargs = dict(kwargs)
+            kwargs["input_values"] = [
+                self.value_remap.get(v, v) for v in kwargs["input_values"]
+            ]
+        return super().call_function(target, args, kwargs)
+
+
+class _NodeReference:
+    def __init__(self, name):
+        self.name = name
+
+    name: str
+
+
+class _LinearNodeList:
+    def __init__(self, node_list):
+        self.serialize_node_list = []
+        for node in node_list:
+            node_args = fx.node.map_arg(node.args, lambda n: _NodeReference(n.name))  # type: ignore[arg-type,return-value]
+            node_kwargs = fx.node.map_arg(node.kwargs, lambda n: _NodeReference(n.name))  # type: ignore[arg-type,return-value]
+            serialize_node = fx.Node(
+                graph=None,  # type: ignore[arg-type]
+                name=node.name,
+                op=node.op,
+                target=node.target,
+                args=node_args,  # type: ignore[arg-type]
+                kwargs=node_kwargs,  # type: ignore[arg-type]
+                return_type=node.type,
+            )
+            serialize_node.meta = copy.copy(node.meta)
+            self.serialize_node_list.append(serialize_node)
+
+    def to_graph(self):
+        graph = fx.Graph()
+
+        ref_str_to_node: Dict[str, fx.Node] = {}
+
+        def ref_to_node(arg):
+            if isinstance(arg, _NodeReference):
+                return ref_str_to_node[arg.name]
+            else:
+                return arg
+
+        for node in self.serialize_node_list:
+            node_args = map_aggregate(node.args, ref_to_node)
+            node_kwargs = map_aggregate(node.kwargs, ref_to_node)
+            deser_node = graph.create_node(
+                op=node.op,
+                target=node.target,
+                args=node_args,  # type: ignore[arg-type]
+                kwargs=node_kwargs,  # type: ignore[arg-type]
+                name=node.name,
+                type_expr=node.type,
+            )
+            ref_str_to_node[node.name] = deser_node
+
+        return graph
+
+
+def _direct_serialization_deserialize(body, nodes):
+    """
+    Custom `__reduce__` method for serialization.
+    DO AS I SAY -- NOT AS I DO. This violates the principle that
+    GraphModules serialize via code export & re-tracing. We allow
+    for this here because **PIPE STAGES SHOULD NOT BE PERSISTED
+    TO DISK -- THIS IS ONLY FOR TRANSMISSION VIA RPC**. Persisting
+    these instances to disk will expose internal implementation
+    details of `fx.Graph` and related data structures and is
+    NOT advised.
+    """
+
+    class DummyModule(torch.nn.Module):
+        def __init__(self, body):
+            super().__init__()
+            self.__dict__.update(body)
+
+    dummy = DummyModule(body)
+
+    return fx.GraphModule(dummy, nodes.to_graph())
+
+
+def _direct_serialization_reduce(self):
+    serialization_dict = dict(self.__dict__)
+    serialization_dict.pop("_graph")
+    return (
+        _direct_serialization_deserialize,
+        (serialization_dict, _LinearNodeList(self.graph.nodes)),
+    )
+
+
+def _modify_graph_op_device(
+    gm: torch.fx.GraphModule,
+    new_device: torch.device,
+):
+    """
+    Modify the device argument of all "call_function" nodes in the graph.  This
+    is useful for moving the graph to a different device. In particular for
+    generator ops, like torch.ones.
+    """
+    modified = False
+    for node in gm.graph.nodes:
+        if node.op == "call_function":
+            if "device" in node.kwargs and node.kwargs["device"] != new_device:
+                logger.debug(
+                    f"Changing device of Node {node.name} from {node.kwargs['device']} to {new_device}"  # noqa: G004
+                )
+                node.update_kwarg("device", new_device)
+                modified = True
+        elif node.op == "call_module":
+            # Recursively modify "device" in submodules
+            submod = gm.get_submodule(node.target)
+            if isinstance(submod, torch.fx.GraphModule):
+                _modify_graph_op_device(submod, new_device)
+            elif isinstance(submod, InterpreterModule):
+                # If unflattening has been performed, we need to access its graph module by `.graph_module`
+                _modify_graph_op_device(submod.graph_module, new_device)
+            else:
+                logger.warning(
+                    f"Skipping device modification for submodule {node.target} because it is a {type(submod)}"  # noqa: G004
+                )
+
+    if modified:
+        gm.recompile()
+
+
+class Pipe(torch.nn.Module):
+    def __init__(
+        self,
+        split_gm: fx.GraphModule,
+        num_stages: int,
+        has_loss_and_backward: bool,
+        loss_spec,
+    ):
+        # TODO: is there a way not to hard wire init?
+        torch.nn.Module.__init__(self)
+        self.split_gm: fx.GraphModule = split_gm
+        self.executor: DetachExecutor = DetachExecutor(self.split_gm)
+        self.num_stages: int = num_stages
+        self.has_loss_and_backward = has_loss_and_backward
+        self.loss_spec = loss_spec
+
+        for node in split_gm.graph.nodes:
+            assert (
+                node.op in {"call_module", "placeholder", "output"}
+                or (node.op, node.target) == ("call_function", operator.getitem)
+                or (node.op, node.target) == ("call_method", "backward")
+                or (node.op, node.target) == ("call_function", stage_backward)
+                or (node.op, node.target)
+                == ("call_function", _null_coalesce_accumulate)
+            ), node
+
+        # Detect replicated parameters so we know that we have to do an additional allreduce
+        # before applying the optimizer
+        #
+        # Note that this also handles the case where there were multiple calls to a single
+        # module from different stages, regardless of whether that module invocation
+        # was handled by the logic above.
+
+        # Map parameter value to a dictionary that maps the user pipeline module
+        # to the local qualname within that module
+        params_to_users: Dict[torch.nn.Parameter, Dict[str, str]] = {}
+
+        for m_qualname, mod in self.split_gm.named_children():
+            for p_qualname, param in mod.named_parameters():
+                params_to_users.setdefault(param, {})
+                params_to_users[param][m_qualname] = p_qualname
+
+        self.replicated_params: List[Dict[str, str]] = [
+            use_mapping
+            for _, use_mapping in params_to_users.items()
+            if len(use_mapping) > 1
+        ]
+
+        # We must break the aliasing relationship between the replicated parameters for correct
+        # numerics in reference runs. If we do not do this, the autograd tape in separate stages
+        # will have a reference to the same tensor value and will erroneously apply gradient
+        # updates multiple times. Therefore, for each replicated parameter set, we deepcopy the
+        # values so that we have separate instances.
+        for param_mapping in self.replicated_params:
+            for submod_name, param_qualname in param_mapping.items():
+                submod = getattr(self.split_gm, submod_name)
+                atoms = param_qualname.split(".")
+                for atom in atoms[:-1]:
+                    submod = getattr(submod, atom)
+                setattr(submod, atoms[-1], copy.deepcopy(getattr(submod, atoms[-1])))
+
+        def throw(self, *args, **kwargs):
+            raise RuntimeError(
+                "To run pipeline locally, invoke the Pipe object directly, not `split_gm`"
+            )
+
+        self.split_gm.forward = throw
+
+        # Make submodules use custom direct-serialized GraphModule
+        i = 0
+        while True:
+            try:
+                name = f"submod_{i}"
+                submod = getattr(self.split_gm, name)
+                submod.__class__.__reduce__ = _direct_serialization_reduce
+                i += 1
+            except AttributeError:
+                break
+
+    def forward(self, *args, **kwargs):
+        executor_args = args
+        if len(kwargs) > 0:
+            parameters = []
+            for node in self.split_gm.graph.nodes:
+                if node.op == "placeholder":
+                    if node.args and len(node.args) > 0:
+                        parameters.append(
+                            Parameter(
+                                node.target,
+                                Parameter.POSITIONAL_OR_KEYWORD,
+                                default=node.args[0],
+                            )
+                        )
+                    else:
+                        parameter_kind = Parameter.POSITIONAL_OR_KEYWORD
+                        param_name = node.target
+                        if node.target.startswith("**"):
+                            parameter_kind = Parameter.VAR_KEYWORD  # type: ignore[assignment]
+                            param_name = param_name[2:]
+                        elif node.target.startswith("*"):
+                            parameter_kind = Parameter.VAR_POSITIONAL  # type: ignore[assignment]
+                            param_name = param_name[1:]
+                        parameters.append(Parameter(param_name, parameter_kind))
+            signature = Signature(parameters)
+            ba = signature.bind(*args, **kwargs)
+            ba.apply_defaults()
+            executor_args = ba.arguments.values()  # type: ignore[assignment]
+
+        res = self.executor.run(*executor_args)
+
+        return res
+
+    def get_stage_module(self, stage_idx: int) -> torch.nn.Module:
+        """
+        Return a stage module corresponding to `stage_idx` of the `pipe`.
+        """
+        if stage_idx < 0 or stage_idx >= self.num_stages:
+            raise ValueError(f"Invalid stage index {stage_idx}!")
+        return getattr(self.split_gm, f"submod_{stage_idx}")
+
+    @staticmethod
+    def _number_and_count_forward_stages(gm: fx.GraphModule):
+        num_stages = 0
+        found_idxs: Dict[int, None] = {}
+        for node in gm.graph.nodes:
+            if node.op == "call_module" and node.target.startswith("submod_"):
+                node.meta["stage_idx"] = int(node.target[len("submod_") :])
+                found_idxs.setdefault(node.meta["stage_idx"])
+                num_stages += 1
+
+        # this assert will fail if a split point is inserted before the first layer, which creates empty first submodule
+        # Update: the following assert may fail against some torch versions >=
+        # 2.2.0, as:
+        # submod_0, submod_1, submod_2, ...
+        # may be named as
+        # submod_0, submod_2, submod_4, ...
+        # TODO: investigate
+        # assert all(i in found_idxs for i in range(num_stages))
+
+        return num_stages
+
+    @staticmethod
+    def _from_traced(
+        mod: torch.nn.Module,
+        exported_program: ExportedProgram,
+        multi_use_param_spec: Optional[MultiUseParamSpec] = None,
+        output_loss_value_spec=None,
+        split_policy: Optional[
+            Callable[[torch.fx.GraphModule], torch.fx.GraphModule]
+        ] = None,
+    ):
+        """
+        Additionally, the ``output_loss_value_spec`` value can be specified to disambiguate
+        which value in the output of `forward` is the loss value on which PiPPy should apply
+        backpropagation. For example, if your ``forward`` returns a tuple ``(loss, model_out)``,
+        you can specify ``output_loss_value_spec=(True, False)``. Or, if your ``forward`` returns
+        a dict ``{'loss': loss_value, 'model_out': model_out}``, you can specify
+        ``output_loss_value_spec={'loss': True, 'model_out': False}``
+        """
+
+        traced = exported_program.module()
+
+        if split_policy is not None:
+            logger.info("Auto-splitting model")
+            traced = split_policy(traced)  # type: ignore[arg-type]
+
+        logger.debug(traced.print_readable(print_output=False))
+
+        # Deduplicate `get_attr` nodes that refer to the same parameter . Downstream code for moving
+        # parameters relies on the invariant that parameter accesses happen once. This is not necessarily
+        # the case (especially with custom tracers), so fix that up here.
+        get_attr_nodes: Dict[str, fx.Node] = {}
+        for node in traced.graph.nodes:
+            if node.op == "get_attr":
+                get_attr_nodes.setdefault(node.target, node)
+
+                if get_attr_nodes[node.target] != node:
+                    node.replace_all_uses_with(get_attr_nodes[node.target])
+                    traced.graph.erase_node(node)
+
+        # avoid looking at next node by keeping track of previous pipe_split
+        prev_pipe_split_idx = -1
+        pipe_split_nodes_to_erase = set()
+        for i, node in enumerate(traced.graph.nodes):
+            if (node.op, node.target) == ("call_function", pipe_split):
+                if prev_pipe_split_idx == i - 1:
+                    pipe_split_nodes_to_erase.add(node)
+                prev_pipe_split_idx = i
+
+        for node in pipe_split_nodes_to_erase:
+            traced.graph.erase_node(node)
+
+        traced.recompile()
+
+        part_idx = 0
+
+        def split_callback(n: fx.Node):
+            nonlocal part_idx
+            if (n.op, n.target) == (
+                "call_function",
+                aten_pipe_split_alias,
+            ):
+                logger.debug(f"Found pipe_split {part_idx}")  # noqa: G004
+                part_idx += 1
+            return part_idx
+
+        # TODO: what does split do with module invocations? does it move the modules
+        # into the submodules?
+        split = split_module(traced, mod, split_callback)  # type: ignore[arg-type]
+        # a (custom) tracer can produce dead code like orphan get_attr nodes
+        split.graph.eliminate_dead_code()
+
+        # peephole to remove pipe_split
+        for submodule in split.modules():
+            if isinstance(submodule, fx.GraphModule):
+                for node in submodule.graph.nodes:
+                    if (node.op, node.target) == (
+                        "call_function",
+                        aten_pipe_split_alias,
+                    ):
+                        submodule.graph.erase_node(node)
+                submodule.recompile()
+
+        for name, submodule in split.named_children():
+            if isinstance(submodule, fx.GraphModule):
+                new_submod = _outline_submodules(submodule.graph)
+                # Replace old submod
+                split.register_module(name, new_submod)
+
+        # TODO: backport this into split_module
+        def delete_user_reference(node, user):
+            """
+            Delete reference of `node` from `user`'s arg list.
+            Args:
+                - node: a `get_attr` node at root.
+                - user: a submodule node that uses `node`.
+            """
+            assert len(user.kwargs) == 0
+            use_idxs = [i for i, arg in enumerate(user.args) if arg == node]
+            assert len(use_idxs) == 1
+            args_copy = list(user.args)
+            args_copy.pop(use_idxs[0])
+            user.args = tuple(args_copy)
+            logger.debug(
+                f"Deleted {node} from user {user}, arg index = {use_idxs[0]}"  # noqa: G004
+            )
+
+        # A list of param referrals for deferred deletion.
+        # To be accumulated in `move_param_to_callee`.
+        to_delete = []
+
+        def _recursive_getattr_with_parent(mod, fqn):
+            # Returns getattr call given a nested FQN, and the last parent
+            atoms = fqn.split(".")
+            for atom in atoms[:-1]:
+                if not hasattr(mod, atom):
+                    return None, None
+                mod = getattr(mod, atom)
+            if not hasattr(mod, atoms[-1]):
+                return mod, None
+            attr = getattr(mod, atoms[-1])
+            return mod, attr
+
+        def move_param_to_callee(
+            root,
+            callee_name,
+            param_fqn,
+        ):
+            """
+            Move a parameter from the root module to a submodule.
+            Args:
+                root: The root module.
+                callee_name: The name of the submodule to move the parameter to.
+                param_fqn: The fully qualified name of the parameter to move.
+            """
+            # `atoms` is a list of strings representing the path to the
+            # parameter in the original model
+            atoms = param_fqn.split(".")
+            mod_itr, param_val = _recursive_getattr_with_parent(split, param_fqn)
+            # Check whether the parameter is a buffer or a parameter
+            is_buffer = atoms[-1] in mod_itr._buffers
+
+            # Check whether the parameter is a tensor
+            assert isinstance(param_val, torch.Tensor), (
+                f"Expected '{param_fqn}' to be {torch.Tensor} but got {type(param_val)}."
+                + (
+                    f" It might happen if module '{param_fqn}' was passed to some 'leaf function'"
+                    f"(see https://pytorch.org/docs/stable/fx.html#fx.wrap). Please inspect "
+                    f"usages of '{param_fqn}' in the traced graph."
+                    if isinstance(param_val, torch.nn.Module)
+                    else ""
+                )
+            )
+
+            # Get submodule
+            callee = root.get_submodule(callee_name)
+            assert not hasattr(
+                callee, param_fqn
+            ), f"Module {callee_name} already has a parameter named {param_fqn}"
+
+            # Assign the parameter to the submodule
+            if is_buffer:
+                _assign_attr(
+                    param_val,
+                    callee,
+                    param_fqn,
+                    attr_kind=_AttrKind.BUFFER,
+                    persistent=True,  # TODO: handle non-persistent buffer
+                )
+            else:
+                _assign_attr(
+                    param_val,
+                    callee,
+                    param_fqn,
+                    attr_kind=_AttrKind.PARAMETER,
+                )
+            logger.debug(f"Moved parameter {param_fqn} to {callee_name}")  # noqa: G004
+
+            # Next step is to replace placeholder of submodule with a get_attr.
+            # Those placeholders are created by `split_module` inside each
+            # submodule.
+            # Update: this step is now moved to `_sink_params` because
+            # `_sink_params` can do it recursively (i.e. for modules inside
+            # submodule)
+
+            to_delete.append((mod_itr, atoms[-1]))
+
+        # Get the list of all parameters in the root module
+        attr_nodes = list(filter(lambda n: n.op == "get_attr", split.graph.nodes))
+        for node in attr_nodes:
+            # Check whether the parameter is used in only one submodule
+            if len(node.users) > 1:
+                logger.info(
+                    f"Parameter {node.target} used in multiple stages: {node.users}."  # noqa: G004
+                )
+            for user in node.users:
+                assert user.op == "call_module"
+                # Move parameter into submodule
+                move_param_to_callee(
+                    split,
+                    user.target,
+                    node.target,
+                )
+
+        # [aliasing] store tensor id -> list of FQNs, built from state dict
+        # Also assign non-persistent buffers
+        id_to_fqns: Dict[int, Set[str]] = defaultdict(set)
+        for fqn, tensor in mod.state_dict(keep_vars=True).items():
+            id_to_fqns[id(tensor)].add(fqn)
+        for fqn, tensor in mod.named_buffers():
+            id_to_fqns[id(tensor)].add(fqn)
+
+        # After moving the params to their corresponding hierarchies, we also
+        # need to move the `get_attr` nodes from the root of the graph to those
+        # hierarchies.
+        # [aliasing] use id -> fqn mapping to list out all valid FQNs
+        inputs_to_state: Dict[str, List[str]] = {}
+        for attr in attr_nodes:
+            _, tensor = _recursive_getattr_with_parent(mod, attr.target)
+            fqns = list(id_to_fqns[id(tensor)])
+            if fqns:
+                inputs_to_state[attr.name] = fqns
+            elif attr.target in exported_program.constants:  # lifted constants
+                inputs_to_state[attr.name] = [attr.target]
+
+        # [aliasing] for each submodule split, assign attributes on FQNs that may be used.
+        # We determine this based on whether or not the FQN attribute parent exists.
+        # i.e. if the last submodule exists, assign the attribute.
+        added_attributes: Dict[str, List[str]] = defaultdict(list)
+        for fqn, tensor in mod.state_dict(keep_vars=True).items():
+            for name, submod in split.named_children():
+                if isinstance(submod, fx.GraphModule):
+                    parent, child = _recursive_getattr_with_parent(submod, fqn)
+                    if (
+                        parent and child is None
+                    ):  # parent exists, attribute doesn't -> assign
+                        added_attributes[name].append(fqn)
+                        setattr(parent, fqn.split(".")[-1], tensor)
+
+        # Deferral deletion: Remove the original attributes (to params) from the
+        # root GraphModule
+        for mod_itr, last_atom in to_delete:
+            try:
+                delattr(mod_itr, last_atom)
+            except AttributeError:
+                # This is expected if the parameter is used in multiple stages
+                pass
+
+        # This is done by (1) `_sink_params` at each submodule;
+        for name, submod in split.named_children():
+            if isinstance(submod, fx.GraphModule):
+                _sink_params(submod, inputs_to_state, [])
+                submod.graph.lint()
+                submod.recompile()
+
+        # [aliasing] This step is not super necessary, but helps reduce parameter usage/memory.
+        # After _sink_params() routine has run, clean up unused attributes that we previously added.
+        # Determine this based on the get_attr nodes - if not used, remove it.
+        for name, attributes in added_attributes.items():
+            submod = getattr(split, name)
+            unused_attributes = set(attributes)
+            # track used attributes in the submodule, running DFS on subgraph hierarchy
+            stack = [("", submod)]  # (scope, submodule)
+            while stack:
+                scope, _mod = stack.pop()
+                if isinstance(_mod, (fx.GraphModule, InterpreterModule)):
+                    for node in _mod.graph.nodes:
+                        if node.op == "get_attr":
+                            # get_attr might get access deeper level attribute
+                            fqn = scope + "." + node.target if scope else node.target
+                            if fqn in unused_attributes:  # used, remove it
+                                unused_attributes.remove(fqn)
+                for _name, _submod in _mod.named_children():
+                    stack.append((scope + "." + _name if scope else _name, _submod))
+            # delete unused attributes
+            for attr in unused_attributes:
+                mod_itr, atoms = submod, attr.split(".")
+                for atom in atoms[:-1]:
+                    mod_itr = getattr(mod_itr, atom)
+                delattr(mod_itr, atoms[-1])
+
+        for node in attr_nodes:
+            # And (2): remove `get_attr` node from submod's arg list
+            for user in copy.copy(node.users):
+                assert user.op == "call_module"
+                delete_user_reference(node, user)
+            # And (3): remove the `get_attr` node from the root graph.
+            split.graph.erase_node(node)
+
+        split.delete_all_unused_submodules()
+        split.graph.lint()
+        split.recompile()
+
+        num_stages = Pipe._number_and_count_forward_stages(split)
+
+        has_loss_and_backward = False
+        generated_loss_spec = output_loss_value_spec
+
+        if output_loss_value_spec is not None:
+            loss_node, output_node, generated_loss_spec = _find_loss_output(
+                mod, split.graph, output_loss_value_spec
+            )
+            if loss_node is not None:
+                _insert_stage_symbolic_backward(
+                    split.graph,
+                    loss_node,
+                    output_node,
+                )
+                split.recompile()
+                has_loss_and_backward = True
+                logger.debug("Pipeline is in training mode, backward pass generated")
+            else:
+                raise RuntimeError(
+                    f"Did not find any loss value according to {output_loss_value_spec=}"
+                )
+        else:
+            logger.debug("Pipeline is in inference mode, backward pass not generated")
+
+        logger.debug("Full pipe model:\n" f"{split}")  # noqa: G004
+
+        return Pipe(
+            split,
+            num_stages,
+            has_loss_and_backward,
+            generated_loss_spec,
+        )
+
+    def print_readable(self):
+        """
+        Print the pipe in a human-readable format.
+        This will print both the root pipe and each stage module.
+        """
+        self.split_gm.print_readable()
+
+    @staticmethod
+    def _trace_with_export(
+        mod: torch.nn.Module,
+        example_args: Tuple[Any, ...],
+        example_kwargs: Optional[Dict[str, Any]] = None,
+    ) -> ExportedProgram:
+        logger.info("Tracing model ...")
+        try:
+            ep = torch.export.export(
+                mod,
+                example_args,
+                example_kwargs,
+            )
+        except Exception as e:
+            raise RuntimeError(
+                "It seems that we cannot capture your model as a full graph. "
+                "Typical reasons include graph breaks, data/shape-dependent "
+                "control flow, or missing meta kernels for custom operators. "
+                "You can use our manual pipeline interfaces, or try to fix the "
+                "graph breaks, see https://pytorch.org/docs/stable/export.html"
+            ) from e
+
+        return ep
+
+    @staticmethod
+    def from_tracing(
+        mod: torch.nn.Module,
+        example_args: Tuple[Any, ...],
+        example_kwargs: Optional[Dict[str, Any]] = None,
+        split_policy: Optional[Callable[[fx.GraphModule], fx.GraphModule]] = None,
+    ):
+        # If a param will be used in multiple pipeline stages, we default the strategy to REPLICATE'ing the param across
+        # stages instead of TRANSMIT'ting it
+        multi_use_param_spec = MultiUseParameterConfig.REPLICATE
+
+        # Figure out which output is loss from output_chunk_spec
+        output_loss_value_spec: Any = None
+        # Deprecated
+        """
+        if output_chunk_spec is not None:
+            output_loss_value_spec = map_aggregate(
+                output_chunk_spec, lambda v: isinstance(v, _LossReducer)
+            )
+        """
+
+        # Trace with export
+        exported_program = Pipe._trace_with_export(
+            mod,
+            example_args,
+            example_kwargs,
+        )
+
+        pipe = Pipe._from_traced(
+            mod,
+            exported_program,
+            multi_use_param_spec,
+            output_loss_value_spec=output_loss_value_spec,
+            split_policy=split_policy,
+        )
+
+        # Users want the first pipeline stage to accept kwargs if the original
+        # program does. This is controlled by the `_codegen` field of the graph,
+        # so we make a copy here. Note: we only want the input spec and not the
+        # output spec, because the output spec is for the last stage. Maybe a
+        # TODO? Not sure yet.
+        split = pipe.split_gm
+        traced = exported_program.module()
+        submod0 = next(iter(split.children()))
+        submod0_sign = signature(submod0.forward)
+        model_sign = signature(traced.forward)
+        if len(model_sign.parameters) != len(submod0_sign.parameters):
+            # We don't change the signature of the first stage if it takes
+            # different number of args than original model
+            logger.info(
+                f"Original model takes {len(model_sign.parameters)} args but the "  # noqa: G004
+                f"first pipeline stage takes {len(submod0_sign.parameters)}. "
+                "Please provide args to respective pipeline stages."
+            )
+        else:
+            # Support kwargs for the first stage
+            submod0.graph._codegen = copy.deepcopy(traced.graph._codegen)
+            # `_replace` is actually not "private" or internal. based on this doc:
+            # To prevent conflicts with field names, the method and attribute names
+            # start with an underscore
+            submod0.graph._codegen.pytree_info = (
+                submod0.graph._codegen.pytree_info._replace(out_spec=None)
+            )
+            submod0.recompile()
+
+        return pipe
+
+    def __str__(self):
+        return self.split_gm.__str__()
+
+    def __repr__(self):
+        return self.split_gm.__repr__()
+
+    def info(self) -> PipeInfo:
+        """
+        Get information about the pipe.
+
+        Returns
+        -------
+        PipeInfo
+            A dataclass containing information about the pipe.
+        """
+        return PipeInfo(
+            graph=self.split_gm.graph,
+            num_stages=self.num_stages,
+            has_loss_and_backward=self.has_loss_and_backward,
+        )
+
+    def build_stage(
+        self,
+        stage_index: int,
+        device: torch.device,
+        group: Optional[ProcessGroup] = None,
+    ) -> _PipelineStage:
+        """
+        Create a `PipelineStage` given a stage index and distributed group.
+        The `PipelineStage` can run with `PipelineSchedule`s.
+        """
+        # Find stage module
+        stage_module = self.get_stage_module(stage_index)
+
+        # Move ops argument to device
+        # Today PT2 tracer does not treat `x.device` as a symbolic device;
+        # instead, the device of tracing time got burned into the generated
+        # code.  Here we provide a workaround for users to manually modify the
+        # "device" kwarg of operations. Such operation may include:
+        # `torch.ones`, `torch.zeros`, `torch.rand`, etc.
+        if isinstance(stage_module, torch.fx.GraphModule):
+            _modify_graph_op_device(stage_module, device)
+        else:
+            logger.warning(
+                f"Expected a `torch.fx.GraphModule` but got {type(stage_module)}"  # noqa: G004
+            )
+
+        # Detach pipe info
+        # Note: be careful what's included in `pipe_info`. We don't want to keep
+        # a reference to `Pipe` or `Pipe.split_gm` which stops python from
+        # recycling them. When python recycles them, other stage modules (which
+        # are irrelevant to current rank) can be automatically freed.
+        pipe_info = self.info()
+        return _PipelineStage(stage_module, stage_index, pipe_info, device, group)
+
+
+class SplitPoint(Enum):
+    BEGINNING = 1
+    END = 2
+
+
+# For backward compatibility, we kept the PipeSplitWrapper class because `class
+# SplitPoint` used to be defined in this class.
+class PipeSplitWrapper:
+    # Create a class alias for BC
+    SplitPoint = SplitPoint
+
+
+def _split_before_forward(self, *args, **kwargs):
+    pipe_split()
+    return self._orig_forward(*args, **kwargs)
+
+
+def _split_after_forward(self, *args, **kwargs):
+    try:
+        return self._orig_forward(*args, **kwargs)
+    finally:
+        pipe_split()
+
+
+def annotate_split_points(mod: torch.nn.Module, spec: Dict[str, SplitPoint]):
+    # TODO: make this implementation out-of-place?
+    for qualname, split_type in spec.items():
+        atoms = qualname.split(".")
+        predecessor_module = mod
+        for i, atom in enumerate(atoms[:-1]):
+            try:
+                predecessor_module = getattr(predecessor_module, atom)
+            except AttributeError as e:
+                raise AttributeError(
+                    f"Specified target {qualname} referenced "
+                    f'nonexistent module {".".join(atoms[: i + 1])}'
+                ) from e
+
+        mod_to_wrap = getattr(predecessor_module, atoms[-1])
+        mod_to_wrap._orig_forward = mod_to_wrap.forward
+        if split_type == SplitPoint.BEGINNING:
+            mod_to_wrap.forward = MethodType(_split_before_forward, mod_to_wrap)
+        elif split_type == SplitPoint.END:
+            mod_to_wrap.forward = MethodType(_split_after_forward, mod_to_wrap)
+        else:
+            raise ValueError("Unknown split point type.")
+
+
+def pipeline(
+    module: torch.nn.Module,
+    mb_args: Tuple[Any, ...],
+    mb_kwargs: Optional[Dict[str, Any]] = None,
+    split_spec: Optional[Dict[str, SplitPoint]] = None,
+    split_policy: Optional[Callable[[fx.GraphModule], fx.GraphModule]] = None,
+) -> Pipe:
+    """
+    Split a module based on a specification.
+
+    See `Pipe` for more details.
+
+    Arguments
+    ---------
+    module:
+        The module to be splitted.
+    mb_args:
+        Example positional inputs, in micro-batch form.
+    mb_kwargs:
+        Example keyword inputs, in micro-batch form. (default: `None`)
+    split_spec:
+        A dictionary using submodule names as split marker. (default: `None`)
+    split_policy:
+        The policy to use for splitting the module. (default: `None`)
+
+    Returns
+    -------
+    A pipeline representation of class `Pipe`.
+    """
+    if split_spec is not None and split_policy is not None:
+        raise ValueError(
+            "Cannot specify both `split_spec` and `split_policy`. Please use only one of them."
+        )
+
+    if split_spec is not None:
+        # Annotate split points in the module based on user spec
+        annotate_split_points(module, split_spec)
+        return Pipe.from_tracing(
+            mod=module,
+            example_args=mb_args,
+            example_kwargs=mb_kwargs,
+        )
+    else:
+        # Use split policy
+        return Pipe.from_tracing(
+            mod=module,
+            example_args=mb_args,
+            example_kwargs=mb_kwargs,
+            split_policy=split_policy,
+        )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..476bf6a18a08713aa2d01c2cc8b0e9087269a7ef
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__init__.py
@@ -0,0 +1,28 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates
+from ._IR import Pipe, pipe_split, pipeline, SplitPoint
+from .schedules import (
+    _ScheduleForwardOnly,
+    Schedule1F1B,
+    ScheduleFlexibleInterleaved1F1B,
+    ScheduleGPipe,
+    ScheduleInterleaved1F1B,
+    ScheduleInterleavedZeroBubble,
+    ScheduleLoopedBFS,
+)
+from .stage import build_stage, PipelineStage
+
+
+__all__ = [
+    "Pipe",
+    "pipe_split",
+    "SplitPoint",
+    "pipeline",
+    "PipelineStage",
+    "build_stage",
+    "Schedule1F1B",
+    "ScheduleFlexibleInterleaved1F1B",
+    "ScheduleGPipe",
+    "ScheduleInterleaved1F1B",
+    "ScheduleLoopedBFS",
+    "ScheduleInterleavedZeroBubble",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/_IR.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/_IR.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f998d466a21f3b158c4895c21e9248970337ce5d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/_IR.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..737a4000e1368604be7083b300236d3a56676c07
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/_backward.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/_backward.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..af7995def196f227e10a8901ebbc8f2bc683e5b7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/_backward.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/_debug.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/_debug.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5c897134667a43f35b9a72c6bd2a97ed93a4b4cd
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/_debug.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/_unflatten.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/_unflatten.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..80965f7cb86015b8bd099dec81ae0527a8d50bcd
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/_unflatten.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..383bd2af018df3b4111cb0d908fafddca12dbf35
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/microbatch.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/microbatch.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bbd7ae5c7ca6e129856cc2d69badf337bc495142
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/microbatch.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/schedules.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/schedules.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b0f132e2da342888df33f2c9848bc4bf1d3b6f99
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/schedules.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/stage.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/stage.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1235eac2f4861dbbe295b7f96f8fe0e449b4216a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/__pycache__/stage.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/_backward.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/_backward.py
new file mode 100644
index 0000000000000000000000000000000000000000..a4c5516e83da0175f9fb7cc1c836b562ac10c1fd
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/_backward.py
@@ -0,0 +1,370 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and affiliates
+import collections
+import logging
+import weakref
+from typing import Any, cast, Deque, Dict, Iterator, List, Optional, Set, Tuple, Union
+
+import torch
+from torch.autograd.graph import GradientEdge, Node
+from torch.nn import Parameter
+
+from ._debug import map_debug_info
+
+
+logger = logging.getLogger(__name__)
+
+
+def _get_grad_fn_or_grad_acc(t: torch.Tensor) -> Union[Node, None]:
+    """
+    Get the grad function or grad accumulator for a tensor.
+
+    Accumulate grad nodes are lazily created, so we need to a
+    dummy view in order to trigger its creation.
+    """
+    if t.requires_grad and t.grad_fn is None:
+        # if no grad function (leaf tensors) we use view
+        viewed_t = t.view_as(t)
+        grad_fn = viewed_t.grad_fn
+        if grad_fn is not None:
+            return grad_fn.next_functions[0][0]
+        else:
+            raise RuntimeError(
+                "Attempted to get grad_fn, but got None."
+                "Is this being created in a no-grad context?"
+            )
+    else:
+        return t.grad_fn
+
+
+def reverse_closure(
+    roots: List[Node], target_nodes: Set[Node]
+) -> Tuple[Set[Node], Set[Node]]:
+    """
+    This function returns the reverse closure of the given roots,
+    i.e. the set of nodes that can be reached from the roots by following the
+    reverse edges of the graph. The target_nodes are the nodes that we want to
+    include in the closure.
+    """
+    # Recurse until we reach a target node
+    closure: Set[Node] = set()
+    visited_target_nodes = set()
+    q: Deque[Node] = collections.deque()
+    for node in roots:
+        if node is not None and node not in closure:
+            closure.add(node)
+            q.append(node)
+    while q:
+        node = q.popleft()
+        metadata = cast(Dict[str, List], node.metadata)
+        reverse_edges = metadata.get("reverse_edges", [])
+        for holder_ref, idx in reverse_edges:
+            ref = holder_ref()
+            if ref is None:
+                # this reverse graph is no longer alive
+                # raise RuntimeError("Reverse graph is no longer alive")
+                continue
+            fn = ref.node
+            if fn in closure or fn is None:
+                continue
+            if fn in target_nodes:
+                visited_target_nodes.add(fn)
+                continue
+            closure.add(fn)
+            q.append(fn)
+    return closure, visited_target_nodes
+
+
+# Enable weak pointer
+class Holder:
+    def __init__(self, node: Node):
+        self.node = node
+
+
+def construct_reverse_graph(roots: List[Node]) -> List[Holder]:
+    q: Deque[Node] = collections.deque()
+    root_seen: Set[Node] = set()
+    reverse_graph_refs: List[Holder] = []
+    for node in roots:
+        if node is not None and node not in root_seen:
+            q.append(node)
+            root_seen.add(node)
+    while q:
+        node = q.popleft()
+        for fn, idx in node.next_functions:
+            if fn is not None:
+                # Don't necessarily need to store on the graph
+                metadata = cast(Dict[str, List], fn.metadata)
+                reverse_edges = metadata.get("reverse_edges", [])
+                if len(reverse_edges) == 0:
+                    q.append(fn)
+                holder = Holder(node)
+                holder_ref = weakref.ref(holder)
+                reverse_graph_refs.append(holder)
+                reverse_edges.append((holder_ref, idx))
+                metadata["reverse_edges"] = reverse_edges
+    return reverse_graph_refs
+
+
+def get_param_groups(inputs: List[Node], params: List[Node]) -> List[Dict[str, Any]]:
+    """
+    Given a list of inputs and a list of parameters, return a list of parameter
+    groups, where each group contains the parameters and the intermediates that
+    are connected to the parameters.
+
+    The returned list of parameter groups is a list of dictionaries, where each
+    dictionary contains the following keys:
+    - "params": a set of parameters
+    - "intermediates": a set of intermediates
+
+    The returned list of parameter groups is a list of dictionaries,
+    """
+    # reverse graph that starts with inputs, and goes up to the dOutput or the loss,
+    # but omits weights and any subgraphs connecting weights to this closure
+    inputs_closure, _ = reverse_closure(inputs, set())
+    param_groups: Dict[Node, Dict[str, Set]] = dict()  # keyed on intermediates
+    for i, param in enumerate(params):
+        closure, intersected = reverse_closure([param], inputs_closure)
+        param_group: Dict[str, Set] = {
+            "params": {param},
+            "intermediates": intersected,
+        }
+        for input_node in intersected:
+            existing = param_groups.get(input_node, None)
+            if existing is not None:
+                existing["params"] = existing["params"].union(param_group["params"])
+                existing["intermediates"] = existing["intermediates"].union(
+                    param_group["intermediates"]
+                )
+                param_group = existing
+            else:
+                param_groups[input_node] = param_group
+
+    # Sanity check: union of all param_groups params should be equal to all params
+    union_params: Set[Node] = set()
+    seen_ids: Set[int] = set()
+    unique_param_groups = []
+    for param_group in param_groups.values():
+        if id(param_group) not in seen_ids:
+            seen_ids.add(id(param_group))
+            unique_param_groups.append(param_group)
+            union_params = union_params.union(param_group["params"])
+
+    # The assert will only be true if the input tensor requires gradients,
+    # otherwise the autograd graph will miss the first layer of inputs
+    # assert union_params == set(params)
+    return unique_param_groups
+
+
+def stage_backward_input(
+    stage_outputs: List[torch.Tensor],
+    output_grads: Optional[List[torch.Tensor]],
+    input_values: List[torch.Tensor],
+    weights: Iterator[Parameter],
+):
+    """
+    compute the gradients for only the stage inputs with respect to the stage outputs
+    """
+    stage_output_grad_fns: List[Node] = list(
+        filter(None, map(_get_grad_fn_or_grad_acc, stage_outputs))
+    )
+    stage_input_grad_fns: List[Node] = list(
+        filter(None, map(_get_grad_fn_or_grad_acc, input_values))
+    )
+    weight_grad_fns: List[Node] = list(
+        filter(None, map(_get_grad_fn_or_grad_acc, weights))
+    )
+
+    reverse_graph_refs = construct_reverse_graph(stage_output_grad_fns)
+    param_groups = get_param_groups(stage_input_grad_fns, weight_grad_fns)
+    del reverse_graph_refs
+
+    for param_group in param_groups:
+        for i, intermediate in enumerate(param_group["intermediates"]):
+
+            def get_hook(param_group, i):
+                def hook(grad_inputs):
+                    if param_group.get("grads", None) is None:
+                        param_group["grads"] = [None] * len(
+                            param_group["intermediates"]
+                        )
+                    param_group["grads"][i] = grad_inputs
+
+                return hook
+
+            # These are always "split" nodes that we need to recompute, so
+            # save their inputs.
+            intermediate.register_prehook(get_hook(param_group, i))
+
+    # Stage 0 inputs do not require grads? Should we skip in that case?
+    if all(tensor.requires_grad for tensor in input_values):
+        if output_grads is None:
+            # In case this is the loss and there are no output_grads, then we just use 1s
+            output_grads = [
+                torch.ones_like(stage_output) for stage_output in stage_outputs
+            ]
+
+        dinputs = torch.autograd.grad(
+            stage_outputs,
+            inputs=input_values,
+            grad_outputs=output_grads,
+            retain_graph=True,
+        )
+
+        # update the gradients for inputs
+        for i, inp in enumerate(input_values):
+            if inp.grad is None:
+                inp.grad = dinputs[i]
+            else:
+                inp.grad += dinputs[i]
+    else:
+        dinputs = None
+    return dinputs, param_groups
+
+
+def stage_backward_weight(
+    weights: Iterator[Parameter], param_groups: List[Dict[str, Any]]
+):
+    # map weights to param_group_weights
+    grad_acc_to_weight = {}
+    weight_grads = []
+    for index, weight in enumerate(weights):
+        grad_acc = _get_grad_fn_or_grad_acc(weight)
+        grad_acc_to_weight[grad_acc] = weight, index
+        weight_grads.append(weight.grad)
+
+    for param_group in param_groups:
+        # TODO: Handle case where intermediate can have multiple outputs
+        intermediate_edges = tuple(
+            GradientEdge(i, 0) for i in param_group["intermediates"]
+        )
+        weights_edges = tuple(GradientEdge(w, 0) for w in param_group["params"])
+
+        assert all(len(g) == 1 for g in param_group["grads"])
+        # [NEW!] Able to pass a GradientEdge to autograd.grad as output
+        # We do not need to retain_graph because... guarantee no overlap?
+        # print("trying to execute: ", intermediate_edges, weights_edges)
+        dweights = torch.autograd.grad(
+            intermediate_edges,
+            weights_edges,
+            grad_outputs=sum(param_group["grads"], tuple()),
+        )
+        for grad_acc, dw in zip(param_group["params"], dweights):
+            weight, index = grad_acc_to_weight[grad_acc]
+            if weight.grad is None:
+                weight.grad = dw
+            else:
+                weight.grad += dw
+    # return grads in the original order weights were provided in
+    return weight_grads
+
+
+def stage_backward(
+    stage_output,
+    output_grads,
+    input_values,
+    outputs_with_grads_idxs: Optional[List[int]] = None,  # deprecated, not used
+):
+    """
+    This is a helper function to:
+    1. compute the gradients for the stage inputs, and
+    2. accumulate gradients for the stage module's parameters.
+
+    Given the input value(s) and the corresponding gradient for the output
+    value(s), compute and accumulate gradients for all parameter values (leaves
+    in the autograd trace) as well as return a list of the gradients for the
+    input values
+    """
+    if outputs_with_grads_idxs is not None:
+        # Deprecated, not used in runtime calls, only exists in compiler
+        stage_output = [stage_output[i] for i in outputs_with_grads_idxs]
+        output_grads = [output_grads[i] for i in outputs_with_grads_idxs]
+
+    try:
+        # stage_output may be a composite datatype like dict. Extract all individual
+        # tensor values here
+        stage_output_tensors = []
+        output_grad_tensors = []
+
+        def extract_tensors_with_grads(output_val, grad_val):
+            if isinstance(output_val, torch.Tensor):
+                if not output_val.requires_grad and output_val.grad_fn is None:
+                    return
+                assert isinstance(
+                    grad_val, (torch.Tensor, type(None))
+                ), f"Expected Tensor or None gradient but got {type(grad_val)}"
+                stage_output_tensors.append(output_val)
+                output_grad_tensors.append(grad_val)
+            elif isinstance(output_val, (tuple, list)):
+                if grad_val is None:
+                    return
+                assert isinstance(
+                    grad_val, (tuple, list)
+                ), f"grad_value expected to have type {type(output_val)} but got {type(grad_val)}"
+                assert len(output_val) == len(grad_val)
+                for ov, gv in zip(output_val, grad_val):
+                    extract_tensors_with_grads(ov, gv)
+            elif isinstance(output_val, dict):
+                if grad_val is None:
+                    return
+                assert isinstance(grad_val, dict)
+                assert set(output_val.keys()) == set(grad_val.keys())
+                for k in output_val.keys():
+                    extract_tensors_with_grads(output_val[k], grad_val[k])
+            else:
+                # Output is a non-tensor type; just ignore it
+                pass
+
+        extract_tensors_with_grads(stage_output, output_grads)
+
+        torch.autograd.backward(
+            stage_output_tensors, grad_tensors=output_grad_tensors  # type: ignore[arg-type]
+        )
+
+        # Extract gradients wrt the input values
+        grad_inputs = []
+        for val in input_values:
+            if isinstance(val, torch.Tensor):
+                grad_inputs.append(val.grad)
+            else:
+                grad_inputs.append(None)
+
+        # Alternative impl: `torch.autograd.grad`.
+        # Note that `torch.autograd.grad` will not accumulate gradients into the
+        # model's parameters.
+        """
+        inputs_with_grad = []
+        for val in input_values:
+            if isinstance(val, torch.Tensor) and val.requires_grad:
+                inputs_with_grad.append(val)
+
+        grad_inputs = torch.autograd.grad(
+            stage_output_tensors, inputs_with_grad, output_grad_tensors,  # type: ignore[arg-type]
+        )
+        """
+
+    except Exception as e:
+        exc_msg = f"""
+        Failed to run stage backward:
+        Stage output: {map_debug_info(stage_output)}
+        Output gradient: {map_debug_info(output_grads)}
+        Input: {map_debug_info(input_values)}
+        """
+        raise RuntimeError(exc_msg) from e
+
+    return grad_inputs
+
+
+# TODO: handling requires_grad=False dynamically. Can we analyze this during initial
+# IR emission?
+def _null_coalesce_accumulate(lhs, rhs):
+    """
+    Coalesce two values, even if one of them is null, returning the non-null
+    value.
+    """
+    if lhs is None:
+        return rhs
+    elif rhs is None:
+        return lhs
+    else:
+        return torch.add(lhs, rhs)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/_debug.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/_debug.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b153ec78d8902bb2187ffc25eb902593a30db52
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/_debug.py
@@ -0,0 +1,21 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and affiliates
+import torch
+
+
+def friendly_debug_info(v):
+    """
+    Helper function to print out debug info in a friendly way.
+    """
+    if isinstance(v, torch.Tensor):
+        return f"Tensor({v.shape}, grad={v.requires_grad}, dtype={v.dtype})"
+    else:
+        return str(v)
+
+
+def map_debug_info(a):
+    """
+    Helper function to apply `friendly_debug_info` to items in `a`.
+    `a` may be a list, tuple, or dict.
+    """
+    return torch.fx.node.map_aggregate(a, friendly_debug_info)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/_unflatten.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/_unflatten.py
new file mode 100644
index 0000000000000000000000000000000000000000..659c9804a96691516d2458e1d6fac3cee2d5ccb4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/_unflatten.py
@@ -0,0 +1,27 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and affiliates
+from typing import Dict
+
+import torch
+from torch.export.unflatten import _ModuleFrame
+
+
+def _outline_submodules(orig_graph: torch.fx.Graph):
+    # Create an empty GraphModule to hold the outlined modules
+    new_module = torch.fx.GraphModule(torch.nn.Module(), torch.fx.Graph())
+    seen_nodes: Dict[str, torch.fx.Node] = {}
+    seen_modules: Dict[int, torch.nn.Module] = {}
+    _ModuleFrame(
+        orig_graph,
+        tuple(orig_graph.nodes),
+        seen_nodes,
+        seen_modules,
+        None,
+        [""],
+        "",
+        {},
+        module=new_module,
+    ).run_outer()
+    new_module.graph.lint()
+    new_module.recompile()
+    return new_module
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf7097795868684c5e51b55e345ddbc66fe76325
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/_utils.py
@@ -0,0 +1,99 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and affiliates
+import logging
+from dataclasses import dataclass
+from typing import List, Tuple, Union
+
+import torch
+from torch import fx
+
+
+logger = logging.getLogger(__name__)
+
+
+def flatten_args_detach(args):
+    """
+    Flatten the args into a list form and detach the tensors from computational graph.
+    """
+    flat_detached_args = []
+
+    def extract_tensor_args(a):
+        nonlocal flat_detached_args
+        if isinstance(a, torch.Tensor):
+            val = a.detach().requires_grad_(a.requires_grad)
+            flat_detached_args.append(val)
+            return val
+        else:
+            flat_detached_args.append(a)
+            return a
+
+    new_args = fx.node.map_aggregate(
+        args,
+        extract_tensor_args,
+    )
+
+    return new_args, flat_detached_args
+
+
+def flatten_args(args):
+    """
+    Flatten the args into a list form.
+    """
+    flat_args = []
+
+    def extract_tensor_args(a):
+        nonlocal flat_args
+        flat_args.append(a)
+        return a
+
+    fx.node.map_aggregate(
+        args,
+        extract_tensor_args,
+    )
+
+    return flat_args
+
+
+class PipeliningShapeError(RuntimeError):
+    """Shape mismatch between configured and runtime values."""
+
+
+def validate_tensor_metadata(desc, expected, given):
+    if not expected.shape == given.shape:
+        raise PipeliningShapeError(
+            f"{desc} has a shape mismatch: expected {expected.shape} actual {given.shape}"
+        )
+    if not expected.dtype == given.dtype:
+        raise PipeliningShapeError(
+            f"{desc} has a dtype mismatch: expected {expected.dtype} actual {given.dtype}"
+        )
+    if not expected.stride() == given.stride():
+        raise PipeliningShapeError(
+            f"{desc} has a stride mismatch: expected {expected.stride()} actual {given.stride()}"
+        )
+
+
+def validate_tensors_metadata(
+    desc,
+    expected_tensors: Union[List[torch.Tensor], Tuple[torch.Tensor, ...]],
+    actual_tensors: Union[List[torch.Tensor], Tuple[torch.Tensor, ...]],
+):
+    if len(expected_tensors) != len(actual_tensors):
+        raise PipeliningShapeError(
+            f"{desc}: Number of values ({len(actual_tensors)}) does not match expected number ({len(expected_tensors)})"
+        )
+    for i in range(len(expected_tensors)):
+        validate_tensor_metadata(
+            f"{desc}: value {i}", expected_tensors[i], actual_tensors[i]
+        )
+
+
+@dataclass
+class PipeInfo:
+    """
+    Captures information for a pipeline (`Pipe` object).
+    """
+
+    graph: fx.Graph
+    num_stages: int
+    has_loss_and_backward: bool
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/microbatch.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/microbatch.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c276b7d6a557cf671fc0a3fc253383a121cbe17
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/microbatch.py
@@ -0,0 +1,469 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and affiliates
+import logging
+from typing import Any, Dict, List, Optional, Tuple
+
+import torch
+from torch.fx.node import map_aggregate
+from torch.utils._pytree import tree_flatten, tree_unflatten
+
+
+__all__ = [
+    "TensorChunkSpec",
+    "split_args_kwargs_into_chunks",
+    "merge_chunks",
+]
+
+logger = logging.getLogger(__name__)
+
+"""
+_debug_mask_minibatches specifies to send masked versions of the mini-batch
+through instead of micro-batch slices--this can be used for more stable
+numerical testing (see [A Note About Correctness Testing])
+"""
+_debug_mask_minibatches = False
+
+
+class _CustomReducer:
+    """
+    Custom reducer class that can be used to specify a custom operation that
+    reduces losses of multiple microbatches into one value.
+
+    Example:
+    >>> # xdoctest: +SKIP
+    >>> sum_reducer = _CustomReducer(
+    >>>     torch.tensor(0.0),
+    >>>     lambda a, b: a + b
+    >>> )
+    """
+
+    def __init__(self, init_value, reduce_fn):
+        self.init_value = init_value
+        self.reduce_fn = reduce_fn
+
+
+class _LossReducer(_CustomReducer):
+    pass
+
+
+sum_reducer = _LossReducer(torch.tensor(0.0), lambda a, b: a + b)
+
+# Default chunking dimension is 0. This is used for the case where the user did
+# not specify a chunking dimension.
+DEFAULT_CHUNK_DIM = 0
+
+
+class TensorChunkSpec:
+    """
+    Class used to specify chunking of inputs
+    """
+
+    def __init__(self, split_dim):
+        self.split_dim = split_dim
+
+    split_dim: int
+
+    def __repr__(self):
+        return (
+            f"{self.__class__.__module__}.{self.__class__.__name__}({self.split_dim})"
+        )
+
+    def __str__(self):
+        return f"TensorChunkSpec({self.split_dim})"
+
+    @staticmethod
+    def from_tuple(
+        chunk_dims: Tuple[int, ...],
+    ):
+        """
+        A helper for creating a tuple of `TensorChunkSpec` from a tuple of chunk
+        dimensions (int's).
+        Example:
+            >>> # xdoctest: +SKIP
+            >>> # There are three positional arguments to the model, and
+            >>> # we are chunking them along dimension 0, 0 and 1, respectively
+            >>> args_chunk_spec = TensorChunkSpec.from_tuple((0, 0, 1))
+        """
+        args_chunk_spec = map_aggregate(
+            chunk_dims,
+            lambda dim: TensorChunkSpec(dim),  # type: ignore[arg-type,return-value]
+        )
+        return args_chunk_spec
+
+    @staticmethod
+    def from_dict(
+        chunk_dims: Dict[str, int],
+    ):
+        """
+        A helper for creating a dictionary of `TensorChunkSpec` from a
+        dictionary of chunk dimensions (int's).
+        Example:
+            >>> # xdoctest: +SKIP
+            >>> # Chunk dimension 0 for the "id" argument, 1 for the "mask" argument
+            >>> kwargs_chunk_spec = TensorChunkSpec.from_dict({"id": 0, "mask": 1})
+        """
+        kwargs_chunk_spec = map_aggregate(
+            chunk_dims,
+            lambda dim: TensorChunkSpec(dim),  # type: ignore[arg-type,return-value]
+        )
+        return kwargs_chunk_spec
+
+
+# Class used to specify replication of inputs
+class _Replicate:
+    pass
+
+
+def _shard_dict_of_args(
+    args_dict,
+    args_chunk_spec,
+    num_chunks,
+):
+    """
+    Given a dictionary of args, and a dictionary of chunking specs, shard the
+    args according to the chunking specs.
+
+    Args:
+        args_dict: Dictionary of args
+        args_chunk_spec: Dictionary of chunking specs
+        num_chunks: Number of chunks to shard the args into
+
+    Returns:
+        args_split: List of sharded args
+    """
+    # Stage 1+2: flatten and shard/replicate
+
+    # args_sharded_replicated : [num args, num flat values, num chunks]
+    args_sharded_replicated = {}
+    arg_specs = []
+
+    real_num_chunks = num_chunks
+    first_tensor = True
+
+    assert len(args_dict) == len(
+        args_chunk_spec
+    ), f"args_dict.keys() = {list(args_dict.keys())} args_chunk_spec.keys() = {list(args_chunk_spec.keys())}"
+
+    for arg_key, arg in args_dict.items():
+        flat, spec = tree_flatten(arg)
+        arg_specs.append(spec)
+
+        chunk_spec = args_chunk_spec[arg_key]
+        assert chunk_spec is not None  # Should have been set by caller
+        chunk_spec_flat, _ = tree_flatten(chunk_spec)
+        if len(flat) != len(chunk_spec_flat):
+            raise ValueError(
+                f"Argument value {arg} did not have the same number of "
+                f"values as as chunk spec {chunk_spec}"
+            )
+
+        sharded_arg_flat = []
+
+        for v, chunk_v in zip(flat, chunk_spec_flat):
+            if chunk_v is _Replicate or not isinstance(v, torch.Tensor):
+                sharded_arg_flat.append([v] * real_num_chunks)
+            elif isinstance(chunk_v, TensorChunkSpec):
+                # TODO: check type of v. If it's a tensor, use chunk (or debug mask).
+                # If it's a collection type, split it as you would expect. Otherwise,
+                # Throw an error
+                assert isinstance(v, torch.Tensor), f"{v} is not a tensor"
+
+                v_split_dim_size = v.size(chunk_v.split_dim)
+                if v_split_dim_size < real_num_chunks:
+                    if first_tensor:
+                        # We can only adjust number of chunks when we hit this
+                        # issue at the first tensor encountered
+                        logger.warning(
+                            f"Tensor size on chunking dimension is {v_split_dim_size}, "  # noqa: G004
+                            f"downsizing the number of chunks from {num_chunks} to {v_split_dim_size}."
+                        )
+                        real_num_chunks = v_split_dim_size
+                    else:
+                        raise RuntimeError(
+                            f"Arg {arg_key} on chunking dimension has a size of {v_split_dim_size}, "
+                            f"smaller than the number of chunks {num_chunks}. "
+                            "PiPPy cannot reduce the number of chunks because "
+                            "other arguments have bigger chunk-dimension sizes. "
+                            "Please adjust your num_chunks setting."
+                        )
+
+                chunk_tensors = torch.tensor_split(
+                    v, real_num_chunks, chunk_v.split_dim
+                )
+
+                if _debug_mask_minibatches:
+                    expanded_chunks = []
+
+                    split_dim_idx = 0
+                    for chunk_tensor in chunk_tensors:
+                        new_val = torch.zeros_like(v)
+                        upper_idx = split_dim_idx + chunk_tensor.size(chunk_v.split_dim)
+
+                        slice_indices = [slice(None, None, None)] * new_val.ndim
+                        slice_indices[chunk_v.split_dim] = slice(
+                            split_dim_idx, upper_idx
+                        )
+                        new_val[slice_indices] = chunk_tensor
+
+                        expanded_chunks.append(new_val)
+
+                        split_dim_idx += chunk_tensor.size(chunk_v.split_dim)
+
+                    sharded_arg_flat.append(expanded_chunks)
+                else:
+                    sharded_arg_flat.append(chunk_tensors)  # type: ignore[arg-type]
+
+                first_tensor = False
+            else:
+                raise TypeError(f"Unrecognized chunk spec: {chunk_v}")
+
+        args_sharded_replicated[arg_key] = sharded_arg_flat
+
+    # chunks_flat : [num chunks, num args, num flat values]
+    chunks_flat = []
+    for chunk_idx in range(real_num_chunks):
+        chunk_args = {}
+        for key, arg in args_sharded_replicated.items():
+            arg_single_chunk = []
+            for v_flat in arg:
+                arg_single_chunk.append(v_flat[chunk_idx])
+            chunk_args[key] = arg_single_chunk
+        chunks_flat.append(chunk_args)
+
+    # args_split : [num chunks, num args]
+    args_split = []
+
+    for chunk in chunks_flat:
+        per_chunk_args = {}
+        assert len(arg_specs) == len(chunk)
+        for (key, arg), arg_spec in zip(chunk.items(), arg_specs):
+            per_chunk_args[key] = tree_unflatten(arg, arg_spec)
+        args_split.append(per_chunk_args)
+
+    return args_split
+
+
+def split_args_kwargs_into_chunks(
+    args: Tuple[Any, ...],
+    kwargs: Optional[Dict[str, Any]],
+    chunks: int,
+    args_chunk_spec: Optional[Tuple[TensorChunkSpec, ...]] = None,
+    kwargs_chunk_spec: Optional[Dict[str, TensorChunkSpec]] = None,
+) -> Tuple[List[Tuple], List[Dict]]:
+    """
+    Given a sequence of args and kwargs, split them into a number of chunks
+    according to  their respective chunking specs.
+
+    Args:
+        args: Tuple of args
+        kwargs: Dict of kwargs
+        chunks: Number of chunks to split the args and kwargs into
+        args_chunk_spec: chunking specs for args, in same shape as args
+        kwargs_chunk_spec: chunking specs for kwargs, in same shape as kwargs
+
+    Returns:
+        args_split: List of sharded args
+        kwargs_split: List of sharded kwargs
+    """
+    # Given `args` and `kwargs`, we want to yield a set of `chunks` args and kwargs such that
+    # the constituent Tensor values have been sharded/replicated according to the `args_chunk_spec`
+    # and `kwargs_chunk_spec` specifications. The steps are as follows:
+    #
+    # 1. Use pytree.tree_flatten to flatten each arg and its spec into nto a 1d array of values.
+    #    To use a running example: suppose our inputs look like
+    #
+    #       args = ([A, [B, C]], D) args_spec = ([None, [None, TensorChunkSpec]], None)
+    #       (kwargs not shown but it's a similar process)
+    #
+    #    Then for this step we would end up with
+    #
+    #       args = ([A, B, C], D) args_spec = ([None, None, TensorChunkSpec], None)
+    #
+    # 2. Shard or replicate the arguments subject to the policy in the spec. Suppose chunks = 2
+    #
+    #       args = ([[A, A], [B, B], [C_1, C_2]], [D, D])
+    #
+    # 3. Rotate the nesting order such that chunks are the outer dimension
+    #
+    #       args_chunks = [
+    #           ([A, B, C_1], D),
+    #           ([A, B, C_2], D),
+    #       ]
+    #
+    # 4. Unflatten each chunk according to the spec
+    #
+    #       args_chunks = [
+    #           ([A, [B, C_1]], D),
+    #           ([A, [B, C_2]], D),
+    #       ]
+
+    # TODO: _debug_mask_minibatches
+    # Handle the case where kwargs is None
+    if kwargs is None:
+        kwargs = {}
+
+    # If user did not provide args_chunk_spec or kwargs_chunk_spec, we extend
+    # their format and use default chunking along dim 0
+    if args_chunk_spec is None:
+        args_chunk_spec = (TensorChunkSpec(DEFAULT_CHUNK_DIM),) * len(args)
+
+    if kwargs_chunk_spec is None:
+        kwargs_chunk_spec = dict.fromkeys(kwargs, TensorChunkSpec(DEFAULT_CHUNK_DIM))
+
+    args_split_dict = _shard_dict_of_args(
+        dict(enumerate(args)),
+        dict(enumerate(args_chunk_spec)),
+        chunks,
+    )
+    real_num_chunks = len(args_split_dict)
+
+    kwargs_split = _shard_dict_of_args(
+        kwargs,
+        kwargs_chunk_spec,
+        real_num_chunks,
+    )
+
+    if len(kwargs_split) < real_num_chunks:
+        # In case kwargs are sharded into less chunks
+        # e.g. when `args` has no tensor, just values
+        real_num_chunks = len(kwargs_split)
+        # Re-shard args
+        args_split_dict = _shard_dict_of_args(
+            dict(enumerate(args)),
+            dict(enumerate(args_chunk_spec)),
+            real_num_chunks,
+        )
+
+    if len(args_split_dict) != len(kwargs_split):
+        raise RuntimeError(
+            "args and kwargs are split into different number of chunks: "
+            f"{len(args_split_dict)}, {len(kwargs_split)}"
+        )
+
+    args_split = []
+    for chunk_args in args_split_dict:
+        args_split.append(tuple(chunk_args[i] for i in range(len(chunk_args))))
+
+    return args_split, kwargs_split
+
+
+def merge_chunks(
+    chunks: List[Any],
+    chunk_spec,
+):
+    """
+    Given a list of chunks, merge them into a single value according to
+    the chunk spec.
+
+    Args:
+        chunks: list of chunks
+        chunk_spec: Chunking spec for the chunks
+
+    Returns:
+        value: Merged value
+    """
+    # This is essentially the inverse of `split_args_kwargs_into_chunks`, so the
+    # steps are similar to the steps in that function but in reverse. Given the
+    # input values:
+    #
+    #       chunks = [
+    #           ([A, [B, C_1]], D),
+    #           ([A, [B, C_2]], D),
+    #       ]
+    #       args_spec = ([None, [None, TensorChunkSpec]], None)
+    #
+    # 1. Flatten the chunks according to the chunk_spec
+    #
+    #       chunks_flat = [
+    #           ([A, B, C_1], D),
+    #           ([A, B, C_2], D),
+    #       ]
+    #
+    # 2. Rotate the nesting order such that chunks are the inner dimension
+    #
+    #       value_inner = ([A, B, [C_1, C_2]], D)
+    #
+    # 3. Concatenate sharded arguments
+    #
+    #       value_combined = ([A, B, C], D)
+    #
+    # 4. Unflatten the combined args given the spec
+    #
+    #       value = ([A, [B, C]], D)
+
+    # Preliminary: flatten the chunk spec
+    if chunk_spec is not None:
+        spec_flattened, flatten_spec = tree_flatten(chunk_spec)
+    else:
+        # If chunk_spec is not provided, we will merge chunks along the default dimension (0), for all output fields
+        # We obtain the output structure by flattening chunk 0 and generate the chunk_spec
+        chunk0_flat, flatten_spec = tree_flatten(chunks[0])
+        spec_flattened = [TensorChunkSpec(DEFAULT_CHUNK_DIM)] * len(chunk0_flat)
+
+    # Stage 1: flatten chunks
+    # chunks_flattened : [num chunks, num args]
+    chunks_flattened = []
+
+    for chunk in chunks:
+        chunk_flattened, _ = tree_flatten(chunk)
+        if len(chunk_flattened) != len(spec_flattened):
+            raise ValueError(f"Chunk {chunk} did not match chunk spec {chunk_spec}")
+
+        chunks_flattened.append(chunk_flattened)
+
+    # Stage 2 and 3: Rotate nesting order s.t. chunks are inner dimension and
+    #                concatenate sharded operands
+    # args_flattened : [num args]
+    args_flattened = []
+    for arg_idx, arg in enumerate(spec_flattened):
+        if isinstance(arg, TensorChunkSpec):
+            partial_values = [
+                chunks_flattened[chunk_idx][arg_idx]
+                for chunk_idx in range(len(chunks_flattened))
+            ]
+
+            if _debug_mask_minibatches:
+                # Infer size of individual chunks by running `tensor_split` again
+                overall_shape = partial_values[0].shape
+                for val in partial_values[1:]:
+                    assert val.shape == overall_shape
+                meta_chunks = torch.tensor_split(
+                    torch.empty(*overall_shape, device="meta"),
+                    sections=len(partial_values),
+                    dim=arg.split_dim,
+                )
+
+                values_to_cat = []
+                chunk_start_idx = 0
+                assert len(partial_values) == len(meta_chunks)
+                for partial_value, meta_chunk in zip(partial_values, meta_chunks):
+                    chunk_end_idx = chunk_start_idx + meta_chunk.size(arg.split_dim)
+
+                    slice_indices = [slice(None, None, None)] * partial_value.ndim
+                    slice_indices[arg.split_dim] = slice(chunk_start_idx, chunk_end_idx)
+                    sliced = partial_value[slice_indices]
+                    values_to_cat.append(sliced)
+
+                    chunk_start_idx = chunk_end_idx
+
+            else:
+                values_to_cat = partial_values
+
+            args_flattened.append(torch.cat(values_to_cat, dim=arg.split_dim))
+        elif isinstance(arg, _CustomReducer):
+            reduced_val = arg.init_value
+
+            for chunk_idx in range(len(chunks_flattened)):
+                reduced_val = arg.reduce_fn(
+                    reduced_val, chunks_flattened[chunk_idx][arg_idx]
+                )
+
+            args_flattened.append(reduced_val)
+        else:
+            value = chunks_flattened[0][arg_idx]
+            for chunk_idx in range(1, len(chunks_flattened)):
+                assert chunks_flattened[chunk_idx][arg_idx] == value
+            args_flattened.append(value)
+
+    # Stage 4: Unflatten combined args
+    return tree_unflatten(args_flattened, flatten_spec)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/schedules.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/schedules.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd02e0e9042ce4fce06b853f485dbb3e0726c921
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/schedules.py
@@ -0,0 +1,2162 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and affiliates
+
+import csv
+import itertools
+import logging
+import re
+from abc import ABC, abstractmethod
+from collections import defaultdict
+from enum import Enum
+from typing import (
+    Any,
+    Callable,
+    Dict,
+    List,
+    NamedTuple,
+    Optional,
+    Set,
+    Tuple,
+    TYPE_CHECKING,
+    Union,
+)
+
+import torch
+import torch.distributed as dist
+from torch.distributed._composable.fsdp.fully_shard import FSDPModule, UnshardHandle
+from torch.profiler import record_function
+
+from .microbatch import merge_chunks, split_args_kwargs_into_chunks, TensorChunkSpec
+from .stage import _PipelineStageBase
+
+
+if TYPE_CHECKING:
+    from torch.distributed import Work
+
+__all__ = [
+    "get_schedule_class",
+    "PipelineScheduleSingle",
+    "PipelineScheduleMulti",
+    "Schedule1F1B",
+    "ScheduleFlexibleInterleaved1F1B",
+    "ScheduleGPipe",
+    "ScheduleInterleaved1F1B",
+    "ScheduleLoopedBFS",
+    "ScheduleInterleavedZeroBubble",
+]
+
+logger = logging.getLogger(__name__)
+
+
+class _ComputationType(Enum):
+    # TODO(whc) rename to _ActType?
+    FORWARD = 1
+    BACKWARD = 2
+    WEIGHT = 3
+    UNSHARD = 4
+    RESHARD = 5
+    SEND_F = 6
+    RECV_F = 7
+    SEND_B = 8
+    RECV_B = 9
+
+    def __str__(self):
+        str_map = {
+            _ComputationType.FORWARD: "F",
+            _ComputationType.BACKWARD: "B",
+            _ComputationType.WEIGHT: "W",
+            _ComputationType.UNSHARD: "UNSHARD",
+            _ComputationType.RESHARD: "RESHARD",
+            _ComputationType.SEND_F: "SEND_F",
+            _ComputationType.RECV_F: "RECV_F",
+            _ComputationType.SEND_B: "SEND_B",
+            _ComputationType.RECV_B: "RECV_B",
+        }
+        return str_map[self]
+
+    @staticmethod
+    def from_str(action):
+        if action == "F":
+            return _ComputationType.FORWARD
+        elif action == "B":
+            return _ComputationType.BACKWARD
+        elif action == "W":
+            return _ComputationType.WEIGHT
+        elif action == "UNSHARD":
+            return _ComputationType.UNSHARD
+        elif action == "RESHARD":
+            return _ComputationType.RESHARD
+        elif action == "SEND_F":
+            return _ComputationType.SEND_F
+        elif action == "RECV_F":
+            return _ComputationType.RECV_F
+        elif action == "SEND_B":
+            return _ComputationType.SEND_B
+        elif action == "RECV_B":
+            return _ComputationType.RECV_B
+        else:
+            raise RuntimeError(f"Invalid computation type {action}")
+
+
+FORWARD = _ComputationType.FORWARD
+BACKWARD = _ComputationType.BACKWARD
+WEIGHT = _ComputationType.WEIGHT
+UNSHARD = _ComputationType.UNSHARD
+RESHARD = _ComputationType.RESHARD
+SEND_F = _ComputationType.SEND_F
+RECV_F = _ComputationType.RECV_F
+SEND_B = _ComputationType.SEND_B
+RECV_B = _ComputationType.RECV_B
+
+# Convenience shorthand for compute actions only since they are used in 'simple schedule format'
+F = FORWARD
+B = BACKWARD
+W = WEIGHT
+
+# Helper to parse an action string like 1F0 into a tuple of (stage_index, computation_type, microbatch_index)
+_action_regex = re.compile(
+    r"(\d+)([F,B,W]|UNSHARD|RESHARD|SEND_F|RECV_F|SEND_B|RECV_B{0,1})(\d*)"
+)
+
+
+class _Action(NamedTuple):
+    stage_index: int
+    computation_type: _ComputationType
+    microbatch_index: Optional[int] = None
+
+    def __repr__(self):
+        repr = str(self.stage_index)
+        repr += str(self.computation_type)
+        if self.microbatch_index is not None:
+            repr += str(self.microbatch_index)
+        return repr
+
+    @staticmethod
+    def from_str(str):
+        """
+        Reverse of __repr__
+
+        String should be formatted as [stage][action type][(microbatch)]
+            e.g. `2F0`, `1UNSHARD`, `3SEND_F1`
+        """
+        if match := _action_regex.match(str):
+            stage_index, computation_type, microbatch_index = match.groups()
+            return _Action(
+                int(stage_index),
+                _ComputationType.from_str(computation_type),
+                int(microbatch_index) if len(microbatch_index) else None,
+            )
+        elif str == "" or str.isspace():
+            return None
+        raise RuntimeError(
+            f"Invalid action string: {str}, should be formatted as [stage][action type][(microbatch)] e.g. 2F0"
+        )
+
+
+def _format_pipeline_order(pipeline_order: Dict[int, List[Optional[_Action]]]) -> str:
+    """
+    Formats the pipeline order in a timestep (row) x rank (column) grid of actions
+    and returns the formatted string
+    """
+    # Calculate the maximum number of steps across all ranks
+    num_steps = max(len(actions) for actions in pipeline_order.values())
+    step_labels = [
+        "Step " + str(i).zfill(len(str(num_steps - 1))) for i in range(num_steps)
+    ]
+    # Sorting the dictionary by keys and retrieving values in that order
+    rank_actions = [
+        pipeline_order.get(key, [""] * num_steps) for key in sorted(pipeline_order)
+    ]
+    # Transpose the list of lists (rows to columns)
+    transposed_actions = list(itertools.zip_longest(*rank_actions, fillvalue=""))
+    # Generate column labels for ranks
+    num_ranks = len(pipeline_order)
+    rank_labels = ["Rank " + str(i) for i in range(num_ranks)]
+    # Calculate the maximum length of each column, considering labels
+    max_lengths = [
+        max(len(str(item)) if item is not None else 0 for item in col)
+        for col in zip(step_labels, *transposed_actions)
+    ]
+    # Format the header row with rank labels
+    header_row = " " * (len(step_labels[0]) + 2) + " ".join(
+        f"{label:<{max_lengths[i]}}" for i, label in enumerate(rank_labels)
+    )
+    # Format each row with its corresponding label
+    formatted_rows = [
+        f"{label}: "
+        + " ".join(f"{str(item):<{max_lengths[i]}}" for i, item in enumerate(row))
+        for label, row in zip(step_labels, transposed_actions)
+    ]
+    # Join the rows into a single string
+    formatted_table = header_row + "\n" + "\n".join(formatted_rows) + "\n"
+    return formatted_table
+
+
+def _validate_pipeline_order(
+    pipeline_order: Dict[int, List[Optional[_Action]]],
+    num_microbatches: int,
+    num_stages: int,
+    enable_zero_bubble: bool = False,
+):
+    """
+    pipeline_order[rank] = [(computation_type, microbatch_index, stage_index), ...]
+    Validating that the pipeline order follows the rules:
+    1. Forward action for a microbatch must be before the Backward action for that microbatch
+    2. Recv for a microbatch must be before the send for that microbatch
+    3. Microbatch index is handled in sequential order for each stage
+    4. A later stage cannot operate on a microbatch before any of the previous stages have operated on it
+    5. Same microbatch cannot be handled in the same time step across ranks
+    """
+    # microbatch_index: (current computation type, current stage)
+    microbatch_process_info: Dict[int, Tuple[_ComputationType, int]] = {}
+    max_timestep = max(len(rank_list) for rank_list in pipeline_order.values())
+    for timestep in range(max_timestep):
+        error_msg: List[str] = []
+        current_timestep_actions = []
+        for rank in range(len(pipeline_order)):
+            action = (
+                pipeline_order[rank][timestep]
+                if timestep < len(pipeline_order[rank])
+                else None
+            )
+
+            if action is not None:
+                computation_type = action.computation_type
+                if computation_type != _ComputationType.WEIGHT:
+                    current_timestep_actions.append(action)
+
+        # TODO: enable this
+        # if len(current_timestep_actions) == 0:
+        #     error_msg.append(
+        #         "All actions were None, there is an unnecessary gap in the schedule"
+        #     )
+
+        # Ensure that no microbatch is operated on twice in current_timestep_actions
+        unique_microbatch_indices = {
+            action.microbatch_index for action in current_timestep_actions
+        }
+        if len(unique_microbatch_indices) != len(current_timestep_actions):
+            error_msg.append(
+                "Duplicate microbatch index found in current_timestep_actions"
+            )
+
+        for action in current_timestep_actions:
+            stage_index = action.stage_index
+            computation_type = action.computation_type
+            mb_index = action.microbatch_index
+            assert (
+                mb_index is not None
+            ), "All currently supported action types require valid microbatch_index"
+            if mb_index >= num_microbatches:
+                error_msg.append(f"Microbatch index {mb_index} out of range")
+
+            # first microbatch
+            if mb_index not in microbatch_process_info:
+                if computation_type != _ComputationType.FORWARD or stage_index != 0:
+                    error_msg.append(f"Incorrect start for microbatch {mb_index}")
+                microbatch_process_info[mb_index] = (computation_type, stage_index)
+            else:
+                # if the microbatch is included, check that the current stage is right after prev
+                prev_computation, prev_stage = microbatch_process_info[mb_index]
+
+                if prev_computation == _ComputationType.FORWARD:
+                    if prev_stage == num_stages - 1:
+                        expected_stage = num_stages - 1
+                        expected_computation = _ComputationType.BACKWARD
+                    else:
+                        expected_stage = prev_stage + 1
+                        expected_computation = _ComputationType.FORWARD
+                elif prev_computation == _ComputationType.BACKWARD:
+                    if prev_stage == 0:
+                        error_msg.append(
+                            f"[{mb_index=}] already finished backward computation"
+                        )
+                        break
+                    else:
+                        expected_stage = prev_stage - 1
+                        expected_computation = _ComputationType.BACKWARD
+                else:
+                    raise ValueError(
+                        f"Computation type {prev_computation} not supported"
+                    )
+
+                if expected_computation is not None:
+                    if expected_computation != computation_type:
+                        error_msg.append(
+                            f"[{mb_index=}] {expected_computation=} VS. actual {computation_type=}"
+                        )
+
+                if expected_stage != stage_index:
+                    error_msg.append(
+                        f"[{mb_index=}] {expected_stage=} VS. actual {stage_index=}"
+                    )
+
+                microbatch_process_info[mb_index] = (
+                    expected_computation,
+                    expected_stage,
+                )
+
+        if not enable_zero_bubble:
+            if len(error_msg) != 0:
+                raise RuntimeError(
+                    f"Error at timestep {timestep}: " + ",".join(error_msg)
+                )
+            return
+
+        for rank in range(len(pipeline_order)):
+            backward_steps: Set[Tuple[int, int]] = set()
+            weight_steps: Set[Tuple[int, int]] = set()
+
+            for action in pipeline_order[rank]:
+                if action is None:
+                    continue
+
+                stage_index = action.stage_index
+                computation_type = action.computation_type
+                mb_index = action.microbatch_index
+                if computation_type == _ComputationType.BACKWARD:
+                    if mb_index is not None:
+                        backward_steps.add((mb_index, stage_index))
+                elif computation_type == _ComputationType.WEIGHT:
+                    if (mb_index, stage_index) not in backward_steps:
+                        error_msg.append(
+                            f"{mb_index=}, {stage_index=} Weight happened before bwd"
+                        )
+                    if (mb_index, stage_index) in weight_steps:
+                        error_msg.append(
+                            f"{mb_index=}, {stage_index=} Duplicated weight step"
+                        )
+                    if mb_index is not None:
+                        weight_steps.add((mb_index, stage_index))
+
+            if len(backward_steps) != len(weight_steps):
+                error_msg.append("Length weight steps != Length bwd steps")
+
+        if len(error_msg) != 0:
+            raise RuntimeError(f"Error at timestep {timestep}: " + ",".join(error_msg))
+
+
+class _PipelineSchedule(ABC):
+    def __init__(
+        self,
+        n_microbatches: int,
+        loss_fn: Optional[Callable[..., torch.Tensor]] = None,
+        args_chunk_spec: Optional[Tuple[TensorChunkSpec, ...]] = None,
+        kwargs_chunk_spec: Optional[Dict[str, TensorChunkSpec]] = None,
+        output_merge_spec: Optional[Union[Dict[str, Any], Tuple[Any]]] = None,
+    ):
+        # From arguments
+        self._n_microbatches = n_microbatches
+        self._loss_fn = loss_fn
+        # Chunking specification for positional inputs. (default: `None`)
+        self._args_chunk_spec = args_chunk_spec
+        # Chunking specification for keyword inputs. (default: `None`)
+        self._kwargs_chunk_spec = kwargs_chunk_spec
+        self._output_merge_spec = output_merge_spec
+        """
+        # args_chunk_spec and kwargs_chunk_spec specify how to chunk inputs.
+        # They are used to convert batch to microbatches in `step(x)`.  See
+        # `TensorChunkSpec` for helper methods for creating them.
+        """
+
+        # Derived
+        self._has_backward = self._loss_fn is not None
+
+        # Holds the losses for each microbatch.
+        self._internal_losses: List[torch.Tensor] = []
+        logger.info("Using %s", self.__class__.__name__)
+
+    def _maybe_compute_loss(self, stage, output, target_mbs, mb_index):
+        if stage.is_last and self._has_backward:
+            loss = self._compute_loss(output, target_mbs[mb_index])  # type: ignore[index]
+            self._internal_losses.append(loss)
+
+    def _maybe_get_loss(self, stage, mb_index):
+        valid_index = 0 <= mb_index < len(self._internal_losses)
+        if stage.is_last and self._has_backward and valid_index:
+            return self._internal_losses[mb_index]
+        elif len(self._internal_losses) != 0 and not valid_index:
+            raise RuntimeError(
+                f"Loss for microbatch {mb_index} is not available. "
+                f"Available losses for microbatches: {self._internal_losses}"
+            )
+        else:
+            return None
+
+    def _update_losses(self, stages, losses):
+        """
+        Update the losses to those in the internal state
+        """
+        # if stages not a list turn into a list
+        if not isinstance(stages, list):
+            stages = [stages]
+        contains_last_stage = any(stage.is_last for stage in stages)
+
+        # Return losses if there is a container passed in
+        if contains_last_stage and losses is not None:
+            if len(self._internal_losses) != self._n_microbatches:
+                raise RuntimeError(
+                    f"Expecting {self._n_microbatches} losses but got {len(self._internal_losses)}"
+                )
+
+            # Clean external container first
+            losses.clear()
+            # Copy internal losses to external container
+            losses.extend(self._internal_losses)
+
+        self._internal_losses.clear()
+
+    @abstractmethod
+    def _step_microbatches(
+        self,
+        arg_mbs: Optional[List] = None,
+        kwarg_mbs: Optional[List] = None,
+        target_mbs: Optional[List] = None,
+        losses: Optional[List] = None,
+    ):
+        """
+        Run one iteration of the pipeline schedule with list of microbatches.
+        Will go through all the microbatches according to the schedule
+        implementation.
+
+        Args:
+            microbatches: list of microbatch args.
+        """
+        raise NotImplementedError
+
+    @abstractmethod
+    def step(self, *args, target=None, losses: Optional[List] = None, **kwargs):
+        """
+        Run one iteration of the pipeline schedule with *whole-batch* input.
+        Will chunk the input into microbatches automatically, and go through the
+        microbatches according to the schedule implementation.
+
+        args: positional arguments to the model (as in non-pipeline case).
+        kwargs: keyword arguments to the model (as in non-pipeline case).
+        target: target for the loss function.
+        losses: a list to store the losses for each microbatch.
+        """
+        raise NotImplementedError
+
+    def _check_inputs(
+        self,
+        arg_mbs: Optional[List] = None,
+        kwarg_mbs: Optional[List] = None,
+        target_mbs: Optional[List] = None,
+        losses: Optional[List] = None,
+    ):
+        """
+        Pre-process/check inputs
+        """
+
+        def check_type_and_len(mbs, name: str):
+            if not isinstance(mbs, list):
+                raise TypeError(f"{name} must be a list but got a {type(mbs)}")
+            if len(mbs) != self._n_microbatches:
+                raise ValueError(
+                    f"Expecting {self._n_microbatches} {name} but got {len(mbs)}"
+                )
+
+        if arg_mbs is not None:
+            check_type_and_len(arg_mbs, "arg_mbs")
+        else:
+            arg_mbs = [()] * self._n_microbatches
+
+        if kwarg_mbs is not None:
+            check_type_and_len(kwarg_mbs, "kwarg_mbs")
+        else:
+            kwarg_mbs = [{}] * self._n_microbatches
+
+        if target_mbs is not None:
+            check_type_and_len(target_mbs, "target_mbs")
+
+        if losses is not None:
+            if not isinstance(losses, list):
+                raise TypeError(f"losses must be a list but got a {type(losses)}")
+
+        return arg_mbs, kwarg_mbs
+
+    def _compute_loss(self, output, target):
+        return self._loss_fn(output, target)  # type: ignore[misc]
+
+    def _split_inputs(
+        self,
+        args: Tuple[Any, ...],
+        kwargs: Optional[Dict[str, Any]] = None,
+    ):
+        """
+        Splits a full-batch input into chunks (i.e. microbatches) and returns
+        the chunks
+        """
+        if args or kwargs:
+            args_split, kwargs_split = split_args_kwargs_into_chunks(
+                args,
+                kwargs,
+                self._n_microbatches,
+                self._args_chunk_spec,
+                self._kwargs_chunk_spec,
+            )
+            return args_split, kwargs_split
+        else:
+            # Empty inputs (e.g. when called on middle stages)
+            # Return a list of empty tuples/dicts with matching length as chunks
+            return [()] * self._n_microbatches, [{}] * self._n_microbatches
+
+    def _merge_outputs(self, output_chunks: List[Any]) -> Any:
+        """
+        Merge output chunks back to a batch state.
+        If output_merge_spec is None, the utility will merge output chunks by dimension 0 (batch dim).
+        """
+        return merge_chunks(
+            output_chunks,
+            self._output_merge_spec,
+        )
+
+
+def _batch_p2p(p2p_ops: List[dist.P2POp], desc: Optional[str] = None):
+    """
+    Simple wrapper over batch_isend_irecv from torch.distributed, which just adds a descriptive logger on top.
+    """
+    if len(p2p_ops) == 0:
+        return None
+    desc_str = f"{desc}, " if desc else ""
+    logger.debug("batch_p2p %s%s", desc_str, p2p_ops)
+    return dist.batch_isend_irecv(p2p_ops).pop()
+
+
+def _sorted_batch_p2p(
+    p2p_ops: List[dist.P2POp], desc: Optional[str] = None
+) -> Dict[int, dist.Work]:
+    """
+    Sorts the list of P2P ops by the peer rank, and then calls
+    batch_isend_irecv. Return a dictionary of works by peer rank. This function
+    helps us avoid hangs in case of skip connections.
+    """
+    # Arrange p2p_ops by peer rank:
+    #   int is the peer rank;
+    #   List is the list of ops towards the peer
+    ops_by_peer: Dict[int, List[dist.P2POp]] = defaultdict(list)
+    work_by_peer: Dict[int, dist.Work] = {}
+    if len(p2p_ops) == 0:
+        return work_by_peer
+
+    # Classify the ops by peer rank
+    for op in p2p_ops:
+        ops_by_peer[op.peer].append(op)
+
+    # Call batch_isend_irecv per peer, in sorted order of the peers (to avoid hangs)
+    for peer, ops in sorted(ops_by_peer.items()):
+        work_by_peer[peer] = _batch_p2p(ops, desc=desc)
+
+    return work_by_peer
+
+
+class PipelineScheduleSingle(_PipelineSchedule):
+    """
+    Base class for single-stage schedules.
+    Implements the `step` method.
+    Derived classes should implement `_step_microbatches`.
+    """
+
+    def __init__(
+        self,
+        stage: _PipelineStageBase,
+        n_microbatches: int,
+        loss_fn: Optional[Callable] = None,
+        args_chunk_spec: Optional[Tuple[TensorChunkSpec, ...]] = None,
+        kwargs_chunk_spec: Optional[Dict[str, TensorChunkSpec]] = None,
+        output_merge_spec: Optional[Union[Dict[str, Any], Tuple[Any]]] = None,
+    ):
+        # Init parent
+        super().__init__(
+            n_microbatches=n_microbatches,
+            loss_fn=loss_fn,
+            args_chunk_spec=args_chunk_spec,
+            kwargs_chunk_spec=kwargs_chunk_spec,
+            output_merge_spec=output_merge_spec,
+        )
+        # Self attributes
+        self._stage = stage
+        self._num_stages = stage.num_stages
+        # Set the same has_backward flag for stage object
+        self._stage.has_backward = self._has_backward
+
+        # TODO: later replace this with lazy shape inference during forward
+        # Prepare forward send/recv infrastructure for stage
+        stage._prepare_forward_infra(n_microbatches)
+        if self._has_backward:
+            stage._prepare_backward_infra(n_microbatches)
+
+    def step(self, *args, target=None, losses: Optional[List] = None, **kwargs):
+        """
+        Run one iteration of the pipeline schedule with *whole-batch* input.
+        Will chunk the input into microbatches automatically, and go through the
+        microbatches according to the schedule implementation.
+
+        args: positional arguments to the model (as in non-pipeline case).
+        kwargs: keyword arguments to the model (as in non-pipeline case).
+        target: target for the loss function.
+        losses: a list to store the losses for each microbatch.
+        """
+
+        # Clean per iteration
+        self._stage.clear_runtime_states()
+
+        # Split inputs into microbatches
+        args_split, kwargs_split = self._split_inputs(args, kwargs)
+
+        # Split target into microbatches
+        if target is not None:
+            targets_split = list(torch.tensor_split(target, self._n_microbatches))
+        else:
+            targets_split = None
+
+        # Run microbatches
+        self._step_microbatches(args_split, kwargs_split, targets_split, losses)
+
+        # Return merged results per original format
+        if self._stage.is_last:
+            return self._merge_outputs(self._stage.output_chunks)
+        else:
+            return None
+
+
+class _ScheduleForwardOnly(PipelineScheduleSingle):
+    """
+    The forward-only schedule.
+    Will go through all the microbatches and perform only the forward pass
+    """
+
+    def _step_microbatches(
+        self,
+        arg_mbs: Optional[List] = None,
+        kwarg_mbs: Optional[List] = None,
+        target_mbs: Optional[List] = None,
+        losses: Optional[List] = None,
+    ):
+        """
+        Run one iteration of the pipeline schedule
+        """
+        if target_mbs is not None or losses is not None:
+            raise RuntimeError(
+                "Forward-only schedule does not support loss computation"
+            )
+
+        arg_mbs, kwarg_mbs = self._check_inputs(arg_mbs, kwarg_mbs, target_mbs, losses)
+
+        # Delay send waits
+        fwd_sends_to_wait: List[dist.Work] = []
+
+        # Run microbatches
+        for i in range(self._n_microbatches):
+            with record_function(f"Forward {i}"):
+                ops = self._stage.get_fwd_recv_ops(i)
+                works = _sorted_batch_p2p(ops, desc="fwd_recv")
+                for work in works.values():
+                    work.wait()
+
+                self._stage.forward_one_chunk(i, arg_mbs[i], kwarg_mbs[i])  # type: ignore[index]
+
+                ops = self._stage.get_fwd_send_ops(i)
+                works = _sorted_batch_p2p(ops, desc="fwd_send")
+                fwd_sends_to_wait.extend(works.values())
+
+            logger.debug("[%s] Forwarded microbatch %s", self._stage.stage_index, i)
+
+        # Wait for all forward sends to finish
+        # This should not have performance impact because by the time the first
+        # backward arrives all the forward sends should have been finished.
+        for work in fwd_sends_to_wait:
+            work.wait()
+
+
+class ScheduleGPipe(PipelineScheduleSingle):
+    """
+    The GPipe schedule.
+    Will go through all the microbatches in a fill-drain manner.
+    """
+
+    def _step_microbatches(
+        self,
+        arg_mbs: Optional[List] = None,
+        kwarg_mbs: Optional[List] = None,
+        target_mbs: Optional[List] = None,
+        losses: Optional[List] = None,
+    ):
+        """
+        Run one iteration of the pipeline schedule with list of microbatches.
+        Will go through all the microbatches according to the GPipe schedule.
+
+        Args:
+            microbatches: list of microbatch args.
+        """
+        arg_mbs, kwarg_mbs = self._check_inputs(arg_mbs, kwarg_mbs, target_mbs, losses)
+
+        # Delay send waits
+        fwd_sends_to_wait: List[dist.Work] = []
+
+        # Run microbatches
+        for i in range(self._n_microbatches):
+            with record_function(f"Forward {i}"):
+                ops = self._stage.get_fwd_recv_ops(i)
+                works = _sorted_batch_p2p(ops, desc="fwd_recv")
+                for work in works.values():
+                    work.wait()
+
+                output = self._stage.forward_one_chunk(i, arg_mbs[i], kwarg_mbs[i])  # type: ignore[index]
+
+                ops = self._stage.get_fwd_send_ops(i)
+                works = _sorted_batch_p2p(ops, desc="fwd_send")
+                fwd_sends_to_wait.extend(works.values())
+
+            logger.debug("[%s] Forwarded microbatch %s", self._stage.stage_index, i)
+
+            self._maybe_compute_loss(self._stage, output, target_mbs, i)
+
+        # Wait for all forward sends to finish
+        # This should not have performance impact because by the time the first
+        # backward arrives all the forward sends should have been finished.
+        for work in fwd_sends_to_wait:
+            work.wait()
+
+        # No loss function, no need to run backward
+        if not self._has_backward:
+            return
+
+        # Run backward
+        # Delay send waits
+        bwd_sends_to_wait: List[dist.Work] = []
+        for i in range(self._n_microbatches):
+            with record_function(f"Backward {i}"):
+                ops = self._stage.get_bwd_recv_ops(i)
+                works = _sorted_batch_p2p(ops, desc="bwd_recv")
+                for work in works.values():
+                    work.wait()
+
+                loss = self._maybe_get_loss(self._stage, i)
+                self._stage.backward_one_chunk(i, loss=loss)
+
+                ops = self._stage.get_bwd_send_ops(i)
+                works = _sorted_batch_p2p(ops, desc="bwd_send")
+                bwd_sends_to_wait.extend(works.values())
+
+            logger.debug("[%s] Backwarded microbatch %s", self._stage.stage_index, i)
+
+        # Return losses if there is a container passed in
+        self._update_losses(self._stage, losses)
+
+        # Wait for all backward sends to finish
+        for work in bwd_sends_to_wait:
+            work.wait()
+
+
+class Schedule1F1B(PipelineScheduleSingle):
+    """
+    The 1F1B schedule.
+    Will perform one forward and one backward on the microbatches in steady state.
+    """
+
+    def _step_microbatches(
+        self,
+        arg_mbs: Optional[List] = None,
+        kwarg_mbs: Optional[List] = None,
+        target_mbs: Optional[List] = None,
+        losses: Optional[List] = None,
+    ):
+        """
+        Run one iteration of the pipeline schedule with list of microbatches.
+        Will go through all the microbatches according to the 1F1B schedule.
+
+        Args:
+            microbatches: list of microbatch args.
+        """
+        arg_mbs, kwarg_mbs = self._check_inputs(arg_mbs, kwarg_mbs, target_mbs, losses)
+
+        # Last stage has 1 warmup, second-to-last 2 warmups, ...
+        # first stage `num_stages` warmups
+        warmup_chunks = min(
+            self._n_microbatches,
+            self._num_stages - self._stage.stage_index,
+        )
+
+        # Chunk counters
+        fwd_mb_index = 0
+        bwd_mb_index = 0
+        weight_stage_mb_index = 0
+
+        # Warmup phase
+        send_work = None
+        fwd_sends = []
+        for _ in range(warmup_chunks):
+            # Receive activations
+            fwd_recvs = self._stage.get_fwd_recv_ops(fwd_mb_index)
+            if recv_work := _batch_p2p(fwd_recvs, desc="fwd_recv"):
+                recv_work.wait()
+
+            # Compute
+            output = self._stage.forward_one_chunk(fwd_mb_index, arg_mbs[fwd_mb_index], kwarg_mbs[fwd_mb_index])  # type: ignore[index]
+
+            # Clear previous chunk's forward sends (hopefully they have well
+            # finished, otherwise, we are heavily communication bound, in which
+            # case it doesn't create a lot of benefit to compute next chunk
+            # eagerly either)
+            if send_work:
+                send_work.wait()
+
+            # Send activations
+            fwd_sends = self._stage.get_fwd_send_ops(fwd_mb_index)
+            if fwd_mb_index != warmup_chunks - 1:
+                # Safe to fire
+                send_work = _batch_p2p(fwd_sends, desc="fwd_send")
+            # otherwise:
+            #   The last foward send is left for fuse with first 1B in 1B1F below
+
+            # Compute loss
+            self._maybe_compute_loss(self._stage, output, target_mbs, fwd_mb_index)
+            fwd_mb_index += 1
+
+        # Now we should have send ops left over, to be fused with first 1B of 1B1F phase below.
+
+        # 1B1F phase
+        while True:  # Don't worry, we have a break inside
+            # We actually do 1B first as the `1B1F` name indicates, so prepare its recv ops
+            bwd_recvs = self._stage.get_bwd_recv_ops(bwd_mb_index)
+
+            # Now, we need to fire the fwd_sends and bwd_recvs together
+            if fuse_work := _batch_p2p(fwd_sends + bwd_recvs, desc="fwd_send_bwd_recv"):
+                fuse_work.wait()
+
+            # Backward one chunk
+            loss = self._maybe_get_loss(self._stage, bwd_mb_index)
+            self._stage.backward_one_chunk(bwd_mb_index, loss=loss)
+
+            # Get the bwd send ops, but don't fire, to be fused with the 1F below
+            bwd_sends = self._stage.get_bwd_send_ops(bwd_mb_index)
+            bwd_mb_index += 1
+
+            if fwd_mb_index == self._n_microbatches:
+                # We are done with 1B1F, so break with some left-over bwd_sends
+                break
+
+            # We prepare 1F of the `1B1F`
+            fwd_recvs = self._stage.get_fwd_recv_ops(fwd_mb_index)
+
+            # Fuse it with bwd_sends above
+            if fuse_work := _batch_p2p(bwd_sends + fwd_recvs, desc="bwd_send_fwd_recv"):
+                fuse_work.wait()
+
+            # Now do the fwd
+            output = self._stage.forward_one_chunk(fwd_mb_index, arg_mbs[fwd_mb_index], kwarg_mbs[fwd_mb_index])  # type: ignore[index]
+
+            # Compute loss
+            self._maybe_compute_loss(self._stage, output, target_mbs, fwd_mb_index)
+
+            # Get the fwd send ops, but don't fire, leave it for the next iter (wrap-around)
+            fwd_sends = self._stage.get_fwd_send_ops(fwd_mb_index)
+            fwd_mb_index += 1
+
+        # Remember we still have some bwd_sends left over after the break? Now it is time to fire it
+        send_work = _batch_p2p(bwd_sends, desc="bwd_send")
+
+        # Cooldown
+        while bwd_mb_index < self._n_microbatches:
+            # prepare bwd recv ops
+            bwd_recvs = self._stage.get_bwd_recv_ops(bwd_mb_index)
+            if recv_work := _batch_p2p(bwd_recvs, desc="bwd_recv"):
+                recv_work.wait()
+
+            # Backward one chunk
+            loss = self._maybe_get_loss(self._stage, bwd_mb_index)
+            self._stage.backward_one_chunk(bwd_mb_index, loss=loss)
+
+            # Clear previous chunk's backward sends (hopefully they have well finished)
+            if send_work:
+                send_work.wait()
+
+            # Get the bwd send ops, fire it
+            bwd_sends = self._stage.get_bwd_send_ops(bwd_mb_index)
+            send_work = _batch_p2p(bwd_sends, desc="bwd_send")
+            bwd_mb_index += 1
+
+        # Wait for the last backward send to finish
+        if send_work:
+            send_work.wait()
+
+        # Return losses if there is a container passed in
+        self._update_losses(self._stage, losses)
+
+
+def _add_unshard_reshard(
+    compute_actions: List[Optional[_Action]],
+    max_active_stages: int = 3,
+) -> List[_Action]:
+    """Given a basic schedule involving only compute actions (F,B,W), add UNSHARD/RESHARD actions for FSDP.
+
+    UNSHARD refers to fetching the full contents of an FSDP-sharded layer, requiring an all-gather operation.
+    RESHARD does the opposite, releasing memory (but doing no commmunication)
+
+    We abandon the "timestep lock"  during lowering
+
+    max_active_stages controls how many prefetches we allow. It should be measured in mb and tuneable but in practice
+    3 stages is probably the thing we want?
+    (to account for having one f and one b active, and something else prefetching?)
+    """
+
+    def next_stage_indices(
+        count: int, next_actions: List[Optional[_Action]]
+    ) -> List[int]:
+        """Remove duplicates (same stage, different microbatch), find next 'count' stages that will do compute."""
+        seen: Set[int] = set()
+        ret: List[int] = []
+
+        for a in next_actions:
+            if a is not None and a.stage_index not in seen:
+                seen.add(a.stage_index)
+                ret.append(a.stage_index)
+                if len(ret) == count:
+                    break
+        return ret
+
+    active_stages: Set[int] = set()
+    fsdp_aware_actions: List[_Action] = []
+
+    def _unshard(stage_index: int):
+        active_stages.add(stage_index)
+        fsdp_aware_actions.append(_Action(stage_index, UNSHARD, None))
+
+    def _reshard(stage_index: int):
+        active_stages.remove(stage_index)
+        fsdp_aware_actions.append(_Action(stage_index, RESHARD, None))
+
+    for i, action in enumerate(compute_actions):
+        if action is None:
+            continue
+
+        # We prefetch the next N stages we'll see, dropping existing stages to make room
+        next_n = next_stage_indices(max_active_stages, compute_actions[i:])
+        # Fetch needs to be ordered correctly, so don't use a set
+        fetch = list(filter(lambda s: s not in active_stages, next_n))
+        # Unclear what the best policy is for eviction, but we can maintain order so we do
+        evict = list(filter(lambda s: s not in next_n, active_stages))
+
+        # logger.debug(
+        #     "_add_unshard_reshard Step %d active: %s fetch %s, evict %s",
+        #     i,
+        #     active_stages,
+        #     fetch,
+        #     evict,
+        # )
+
+        for stage in evict:
+            _reshard(stage)
+        for stage in fetch:
+            _unshard(stage)
+        fsdp_aware_actions.append(action)
+
+    return fsdp_aware_actions
+
+
+def _add_send_recv(
+    compute_actions: Dict[int, List[_Action]],
+    stage_to_rank: Callable[[int], int],
+    num_stages: int,
+) -> Dict[int, List[_Action]]:
+    comm_actions: Dict[int, List[_Action]] = {rank: [] for rank in compute_actions}
+
+    def _has_comms(action: _Action) -> bool:
+        if action.computation_type == F:
+            return action.stage_index != num_stages - 1
+        elif action.computation_type == B:
+            return action.stage_index != 0
+        return False
+
+    def _get_comms(action: _Action) -> Tuple[_Action, _Action]:
+        assert _has_comms(action), f"{action} is not a valid comm action"
+        stage_idx = action.stage_index
+        ctype = action.computation_type
+        mb_idx = action.microbatch_index
+        send = _Action(stage_idx, SEND_F if ctype == F else SEND_B, mb_idx)
+        recv_stage_idx = stage_idx + 1 if ctype == F else stage_idx - 1
+        recv = _Action(recv_stage_idx, RECV_F if ctype == F else RECV_B, mb_idx)
+        return send, recv
+
+    def _ready_to_schedule(
+        action: Optional[_Action], prev_actions: List[_Action]
+    ) -> bool:
+        """We don't put our own recv ops in the schedule, we let a sender on another rank put our recv ops in place.
+        This helps ensure a sane (non-hanging) ordering of sends and recvs.
+        But it also means we might not be able to schedule our next compute action yet.
+        """
+        if action is None:
+            return True
+        elif action.computation_type == F and not action.stage_index == 0:
+            expected_recv = _Action(
+                action.stage_index,
+                RECV_F if action.computation_type == F else RECV_B,
+                action.microbatch_index,
+            )
+            return expected_recv in prev_actions
+        elif action.computation_type == B and not action.stage_index == num_stages - 1:
+            expected_recv = _Action(
+                action.stage_index,
+                RECV_F if action.computation_type == F else RECV_B,
+                action.microbatch_index,
+            )
+            return expected_recv in prev_actions
+        else:
+            return True
+
+    while compute_actions:
+        progress = False
+        # go in order of ranks even if dict keys aren't ordered
+        for rank in range(len(compute_actions)):
+            assert len(compute_actions[rank]) > 0
+            action = compute_actions[rank][0]
+
+            if not _ready_to_schedule(action, comm_actions[rank]):
+                continue
+
+            if action is not None:
+                comm_actions[rank].append(action)
+                if _has_comms(action):
+                    send, recv = _get_comms(action)
+                    # TODO we can avoid send/recv if the 2 stages are on the same rank.
+                    # should we avoid that in the runtime or here?
+                    comm_actions[rank].append(send)
+                    comm_actions[stage_to_rank(recv.stage_index)].append(recv)
+
+            compute_actions[rank].pop(0)
+            if len(compute_actions[rank]) == 0:
+                del compute_actions[rank]
+            progress = True
+        assert progress, "Malformed compute schedule, can't schedule sends/recvs"
+    return comm_actions
+
+
+class PipelineScheduleMulti(_PipelineSchedule):
+    """
+    Base class for multi-stage schedules.
+    Implements the `step` method.
+    """
+
+    def __init__(
+        self,
+        stages: List[_PipelineStageBase],
+        n_microbatches: int,
+        loss_fn: Optional[Callable] = None,
+        args_chunk_spec: Optional[Tuple[TensorChunkSpec, ...]] = None,
+        kwargs_chunk_spec: Optional[Dict[str, TensorChunkSpec]] = None,
+        output_merge_spec: Optional[Union[Dict[str, Any], Tuple[Any]]] = None,
+        stage_index_to_group_rank: Optional[Dict[int, int]] = None,
+        use_full_backward: bool = True,
+    ):
+        if len(stages) <= 1:
+            raise ValueError(
+                f"Multi-stage schedule expects at least two stages but got {len(stages)}"
+            )
+        # Init parent
+        super().__init__(
+            n_microbatches=n_microbatches,
+            loss_fn=loss_fn,
+            args_chunk_spec=args_chunk_spec,
+            kwargs_chunk_spec=kwargs_chunk_spec,
+            output_merge_spec=output_merge_spec,
+        )
+        # Self attributes
+        self._stages = stages
+        self._num_stages = stages[0].num_stages
+        self.pp_group_size = stages[0].group_size
+        self.rank = stages[0].group_rank
+        # Set the pipeline stage states
+        if stage_index_to_group_rank is not None:
+            for stage in self._stages:
+                stage.stage_index_to_group_rank = stage_index_to_group_rank
+        self.stage_index_to_group_rank = stages[0].stage_index_to_group_rank
+
+        # Set the same has_backward flag for stage object
+        for stage in self._stages:
+            stage.has_backward = self._has_backward
+
+        self._should_compute_loss = (
+            lambda stage: stage.is_last and self._loss_fn is not None
+        )
+
+        # This will be set during init of derived schedules
+        self.pipeline_order: Dict[int, List[Optional[_Action]]] = {}
+        self.use_full_backward = use_full_backward
+
+        # TODO: later replace this with lazy shape inference during forward
+        # Prepare forward send/recv infrastructure for stage
+        for stage in self._stages:
+            stage._prepare_forward_infra(n_microbatches)
+            if self._has_backward:
+                stage._prepare_backward_infra(n_microbatches)
+
+    def _dump_csv(self, filename):
+        """Dump a CSV representation of the schedule into a file with the provided filename."""
+        with open(filename, "w", newline="") as csvfile:
+            writer = csv.writer(csvfile)
+            for rank in self.pipeline_order:
+                writer.writerow(self.pipeline_order[rank])
+
+    def _validate_schedule(self):
+        # TODO(whc) this should be merged with the logic in test_schedule.py#L453-L554
+        def _validate_rank_actions(
+            actions: Dict[int, List[_Action | None]],
+            num_stages: int,
+            num_microbatches: int,
+        ):
+            # We will count all the actions per stage and ensure they happen in a valid order
+            # (e.g. F before B before W for a given microbatch)
+            stage_actions: Dict[int, Dict[_ComputationType, Set]] = {
+                stage_id: {
+                    F: set(),
+                    B: set(),
+                    W: set(),
+                }
+                for stage_id in range(num_stages)
+            }
+            for rank in actions:
+                for action in actions[rank]:
+                    if action is None:
+                        continue
+                    assert isinstance(
+                        action, _Action
+                    ), f"Got an invalid action: {action}, expected instance of _Action"
+                    s_id = action.stage_index
+                    ctype = action.computation_type
+                    mb_id = action.microbatch_index
+                    if ctype == F:
+                        stage_actions[s_id][F].add(mb_id)
+                    elif ctype == B:
+                        assert (
+                            mb_id in stage_actions[s_id][F]
+                        ), f"Running Backward for stage {s_id}, microbatch {mb_id} without first running Forward"
+                        stage_actions[s_id][B].add(mb_id)
+                    elif ctype == W:
+                        assert (
+                            not self.use_full_backward
+                        ), "Schedule contains 'W' actions, but is configured to use full backward"
+                        assert (
+                            mb_id in stage_actions[s_id][B]
+                        ), f"Running Weight for stage {s_id}, microbatch {mb_id} without first running Backward"
+                        stage_actions[s_id][W].add(mb_id)
+
+            for s_id in stage_actions:
+                for ctype in (F, B, W):
+                    stage_mb = len(stage_actions[s_id][ctype])
+                    assert (
+                        stage_mb == num_microbatches
+                    ), f"Got {stage_mb} {ctype} microbatches for stage {s_id}, expected {num_microbatches}"
+
+        assert (
+            len(self.pipeline_order) == self.pp_group_size
+        ), f"Schedule has incorrect number of ranks - expected {self.pp_group_size}, actual {len(self.pipeline_order)}"
+        for rank in range(self.pp_group_size):
+            assert (
+                rank in self.pipeline_order
+            ), f"Schedule is missing actions for rank {rank}"
+        _validate_rank_actions(
+            self.pipeline_order,
+            self._num_stages,
+            self._n_microbatches,
+        )
+
+    def _load_csv(self, filename, format="compute_only"):
+        """Load a CSV representation of the schedule from a file with the provided filename.
+        This API will most likely get renamed/refactored so is marked as internal for now.
+
+        format must be "compute_only" for PipelineScheduleMulti
+        """
+        assert format == "compute_only"
+        with open(filename, newline="") as csvfile:
+            reader = csv.reader(csvfile)
+            for rank, row in enumerate(reader):
+                self.pipeline_order[rank] = [_Action.from_str(s) for s in row]
+        self._validate_schedule()
+
+    def step(self, *args, target=None, losses: Optional[List] = None, **kwargs):
+        """
+        Run one iteration of the pipeline schedule with *whole-batch* input.
+        Will chunk the input into microbatches automatically, and go through the
+        microbatches according to the schedule implementation.
+
+        args: positional arguments to the model (as in non-pipeline case).
+        kwargs: keyword arguments to the model (as in non-pipeline case).
+        target: target for the loss function.
+        losses: a list to store the losses for each microbatch.
+        """
+
+        # Clean per iteration
+        for stage in self._stages:
+            stage.clear_runtime_states()
+
+        # Split inputs into microbatches
+        args_split, kwargs_split = self._split_inputs(args, kwargs)
+
+        # Split target into microbatches
+        if target is not None:
+            targets_split = list(torch.tensor_split(target, self._n_microbatches))
+        else:
+            targets_split = None
+
+        # Run microbatches
+        self._step_microbatches(args_split, kwargs_split, targets_split, losses)
+
+        # Return merged results per original format
+        for stage in self._stages:
+            if stage.is_last:
+                return self._merge_outputs(stage.output_chunks)
+        # Does not contain the last stage
+        return None
+
+    def _step_microbatches(
+        self,
+        arg_mbs: Optional[List] = None,
+        kwarg_mbs: Optional[List] = None,
+        target_mbs: Optional[List] = None,
+        losses: Optional[List] = None,
+    ):
+        """
+        Operate on the microbatches for looped schedules (multiple stages on each rank).
+
+        TODO: Does not use sorted_batch_isend_irecv(). As a result, this schedule does
+        not support models with skip connections.
+        """
+        arg_mbs, kwarg_mbs = self._check_inputs(arg_mbs, kwarg_mbs, target_mbs, losses)
+
+        # Based on the plan in Step 1 created in __init__:
+        # 2. Perform communication based on the pipeline_order
+        stage_index_to_stage: Dict[int, _PipelineStageBase] = {
+            stage.stage_index: stage for stage in self._stages
+        }
+
+        # determine prev_rank and next_rank based on which ranks are next to
+        # the stages in the pipeline_order
+        all_prev_ranks: Set[int] = set()
+        all_next_ranks: Set[int] = set()
+        for stage_index in stage_index_to_stage.keys():
+            # TODO: assumption that stages only communicate from distances of +1/-1 (no skip connections)
+            if stage_index > 0:
+                all_prev_ranks.add(self.stage_index_to_group_rank[stage_index - 1])
+            if stage_index < self._num_stages - 1:
+                all_next_ranks.add(self.stage_index_to_group_rank[stage_index + 1])
+
+        for time_step, action in enumerate(self.pipeline_order[self.rank]):
+            try:
+                ops: List[dist.P2POp] = []
+                if action is not None:
+                    computation_type = action.computation_type
+                    mb_index = action.microbatch_index
+                    stage_index = action.stage_index
+                    assert (
+                        mb_index is not None
+                    ), "All currently supported action types require valid microbatch_index"
+                    if computation_type == _ComputationType.FORWARD:
+                        # perform forward computation
+                        stage = stage_index_to_stage[stage_index]
+                        output = stage.forward_one_chunk(
+                            mb_index, arg_mbs[mb_index], kwarg_mbs[mb_index]
+                        )
+                        self._maybe_compute_loss(stage, output, target_mbs, mb_index)
+                        ops.extend(stage.get_fwd_send_ops(mb_index))
+                    elif computation_type == _ComputationType.BACKWARD:
+                        # perform backward computation
+                        stage = stage_index_to_stage[stage_index]
+                        loss = self._maybe_get_loss(stage, mb_index)
+                        stage.backward_one_chunk(
+                            mb_index, loss=loss, full_backward=self.use_full_backward
+                        )
+                        ops.extend(stage.get_bwd_send_ops(mb_index))
+                    elif computation_type == _ComputationType.WEIGHT:
+                        # perform weight update
+                        if self.use_full_backward:
+                            raise ValueError(
+                                f"We detected a weight update in the pipeline schedule, but \
+                                {self.use_full_backward=}"
+                            )
+                        stage = stage_index_to_stage[stage_index]
+                        stage.backward_weight_one_chunk(mb_index)
+                    else:
+                        raise ValueError(f"Unknown computation type {computation_type}")
+
+                # Look at the neighboring ranks for this current timestep and determine whether
+                # this current rank needs to do any recv communication
+                for prev_rank in all_prev_ranks:
+                    prev_rank_ops = self.pipeline_order[prev_rank]
+                    prev_rank_action = None
+                    if time_step < len(prev_rank_ops):
+                        prev_rank_action = prev_rank_ops[time_step]
+                    if prev_rank_action is not None:
+                        computation_type = prev_rank_action.computation_type
+                        mb_index = prev_rank_action.microbatch_index
+                        stage_index = prev_rank_action.stage_index
+                        assert (
+                            mb_index is not None
+                        ), "All currently supported action types require valid microbatch_index"
+                        # Only handle sends for the forward from a previous rank
+                        if computation_type == _ComputationType.FORWARD:
+                            # If not the last stage, then receive fwd activations
+                            if stage_index + 1 in stage_index_to_stage:
+                                # TODO: We are assuming that stage will always receive from stage-1
+                                # however that is not necessarily true of get_fwd_recv_ops
+                                stage = stage_index_to_stage[stage_index + 1]
+                                ops.extend(stage.get_fwd_recv_ops(mb_index))
+                        elif (
+                            computation_type == _ComputationType.BACKWARD
+                            or computation_type == _ComputationType.WEIGHT
+                        ):
+                            # Previous rank doing backward or weight update has no influence for the current rank forward recv
+                            pass
+                        else:
+                            raise ValueError(
+                                f"Unknown computation type {computation_type}"
+                            )
+                for next_rank in all_next_ranks:
+                    next_rank_ops = self.pipeline_order[next_rank]
+                    next_rank_action = None
+                    if time_step < len(next_rank_ops):
+                        next_rank_action = next_rank_ops[time_step]
+                    if next_rank_action is not None:
+                        computation_type = next_rank_action.computation_type
+                        mb_index = next_rank_action.microbatch_index
+                        stage_index = next_rank_action.stage_index
+                        assert (
+                            mb_index is not None
+                        ), "All currently supported action types require valid microbatch_index"
+                        # Only handle receives for the backwards from a next rank
+                        if (
+                            computation_type == _ComputationType.FORWARD
+                            or computation_type == _ComputationType.WEIGHT
+                        ):
+                            # Next rank doing forward or weight update has no influence for the current rank backward recv
+                            pass
+                        elif computation_type == _ComputationType.BACKWARD:
+                            # If not the first stage, then receive bwd gradients
+                            if stage_index - 1 in stage_index_to_stage:
+                                # TODO: We are assuming that stage will always receive from stage+1
+                                # however that is not necessarily true of get_bwd_recv_ops
+                                stage = stage_index_to_stage[stage_index - 1]
+                                ops.extend(stage.get_bwd_recv_ops(mb_index))
+                        else:
+                            raise ValueError(
+                                f"Unknown computation type {computation_type}"
+                            )
+
+                # do the communication
+                if ops:
+                    _batch_p2p(ops).wait()
+            except Exception as e:
+                logger.error(
+                    "[Rank %s] pipeline schedule %s caught the following exception \
+                     at time_step %s when running action %s",
+                    self.rank,
+                    self.__class__.__name__,
+                    time_step,
+                    action,
+                )
+                logger.error("%s", _format_pipeline_order(self.pipeline_order))
+                raise e
+        # Return losses if there is a container passed in
+        self._update_losses(self._stages, losses)
+
+
+class _PipelineScheduleRuntime(PipelineScheduleMulti):
+    """
+    Provides a simple runtime that requires a 'schedule IR' including specified communication operations.
+
+    Can be instantiated directly by creating _PipelineScheduleRuntime and calling load_csv, or can be
+    subclassed and the subclass can be responsible for creating a schedule IR.
+    """
+
+    def _load_actions(
+        self,
+        actions: Dict[int, List[Optional[_Action]]],
+        format: str = "compute_only",
+    ):
+        """
+        Given an in-memory representation for a simple compute-only schedule, lower it to a complex schedule including
+        communication actions.  Stores the schedule in self, and must be called before running step_mo()
+        """
+        assert (
+            self.stage_index_to_group_rank is not None
+        ), "stage_index_to_group_rank is required for PipelineScheduleRuntime"
+        self.pipeline_order_with_comms: Dict[int, List[_Action]] = {}
+        if format == "compute_comms":
+            for rank in actions:
+                self.pipeline_order_with_comms[rank] = []
+                for action in actions[rank]:
+                    assert action is not None
+                    self.pipeline_order_with_comms[rank].append(action)
+            # TODO what level of validation should we offer for compute+comms schedule?
+        elif format == "compute_only":
+            # Perform schedule lowering
+            for rank in actions:
+                self.pipeline_order_with_comms[rank] = _add_unshard_reshard(
+                    actions[rank]
+                )
+
+            self.pipeline_order_with_comms = _add_send_recv(
+                self.pipeline_order_with_comms,
+                stage_to_rank=lambda s: self.stage_index_to_group_rank[s],
+                num_stages=self._num_stages,
+            )
+        else:
+            raise NotImplementedError(f"{format=} is not implemented")
+
+    def _load_csv(self, filename: str, format: str = "compute_only"):
+        """Loads a csv in simple format and then lowers it to include comunication actions
+
+        format must be either "compute_only" or "compute_comms".  If compute_only, the lowering passes
+        will automatically be run to generate a compute_comms schedule.
+        """
+        if format == "compute_only":
+            # this will populate self.pipeline_order
+            super()._load_csv(filename)
+            # this will populate self.pipeline_order_with_comms
+            self._load_actions(self.pipeline_order)
+        elif format == "compute_comms":
+            actions = {}
+            with open(filename, newline="") as csvfile:
+                reader = csv.reader(csvfile)
+                for rank, row in enumerate(reader):
+                    actions[rank] = [_Action.from_str(s) for s in row]
+                self._load_actions(actions, format=format)
+        else:
+            raise NotImplementedError(f"{format=} is not implemented")
+
+    def _dump_csv(self, filename: str):
+        """Dump a CSV representation of the compute + comms schedule into a file with the provided filename."""
+        # TODO should there be an option to dump the compute_only schedule from PipelineScheduleRuntime? It's possible
+        # that it does not exist if it was created from a compute_comms schedule.
+        assert (
+            self.pipeline_order_with_comms is not None
+        ), "Must initialize compute_comms schedule before dump_csv"
+        with open(filename, "w", newline="") as csvfile:
+            writer = csv.writer(csvfile)
+            for rank in self.pipeline_order_with_comms:
+                writer.writerow(self.pipeline_order_with_comms[rank])
+
+    def _step_microbatches(
+        self,
+        arg_mbs: Optional[List] = None,
+        kwarg_mbs: Optional[List] = None,
+        target_mbs: Optional[List] = None,
+        losses: Optional[List] = None,
+    ):
+        """
+        Operate on the microbatches for looped schedules (multiple stages on each rank).
+
+        TODO: Does not use sorted_batch_isend_irecv(). As a result, this schedule does
+        not support models with skip connections.
+        """
+        arg_mbs, kwarg_mbs = self._check_inputs(arg_mbs, kwarg_mbs, target_mbs, losses)
+
+        # Based on the plan in Step 1 created in __init__:
+        # 2. Perform communication based on the pipeline_order
+        stage_index_to_stage: Dict[int, _PipelineStageBase] = {
+            stage.stage_index: stage for stage in self._stages
+        }
+
+        assert (
+            self.pipeline_order_with_comms is not None
+        ), "Must call _load_actions() before calling _step_microbatches()"
+
+        # recv ops indexed by (stage_idx, mb_idx) need to be waited on before use
+        bwd_recv_ops: Dict[Tuple[int, int], Work] = {}
+        fwd_recv_ops: Dict[Tuple[int, int], Work] = {}
+
+        # send ops should be waited on before step() exists, mainly for hygeine
+        send_ops: List[Work] = []
+
+        # we track which stages are 'active' when used with FSDP, and wait on unshard ops before computing on stages
+        unshard_ops: Dict[int, UnshardHandle] = {}
+        unsharded_stages = set()
+
+        def _assert_unsharded(stage_idx: int):
+            """If an unshard is active for `stage_idx`, wait() it and mark `stage_idx` unshared."""
+            if stage_idx in unshard_ops:
+                unshard_ops[stage_idx].wait()
+                del unshard_ops[stage_idx]
+                unsharded_stages.add(stage_idx)
+            assert (
+                stage_idx in unsharded_stages
+            ), f"Attempted to compute on sharded {stage_idx=}"
+
+        for time_step, action in enumerate(self.pipeline_order_with_comms[self.rank]):
+            try:
+                comp_type = action.computation_type
+                mb_index: int = (
+                    action.microbatch_index
+                    if action.microbatch_index is not None
+                    else -1
+                )
+                assert mb_index >= 0 or comp_type in (
+                    UNSHARD,
+                    RESHARD,
+                ), f"{action=} missing mb_index"
+                stage_idx = action.stage_index
+                stage = stage_index_to_stage[stage_idx]
+                stage_uses_fsdp = isinstance(stage.submod, FSDPModule)
+
+                logger.debug(
+                    "_PipelineScheduleRuntime running time_step %d, action %s",
+                    time_step,
+                    action,
+                )
+
+                # TODO(whc) it's not actually safe to use _batch_p2p here in the uncommon case the model has skip-connections,
+                # since we do not want to batch up ops between more than a pair of ranks.  _sorted_batch_p2p would be
+                # safe to use instead.
+                # However, I was wondering if I should avoid calling batched operators at all in the case that there is
+                # only one operator per batch.  I could iterate through the 'fwd_send_ops' one by one and run them.
+                if comp_type == SEND_F:
+                    send_ops.append(_batch_p2p(stage.get_fwd_send_ops(mb_index)))
+                elif comp_type == SEND_B:
+                    send_ops.append(_batch_p2p(stage.get_bwd_send_ops(mb_index)))
+                elif comp_type == RECV_F:
+                    assert (
+                        stage_idx,
+                        mb_index,
+                    ) not in fwd_recv_ops, "Recv twice for {stage_idx=} {mb_index=} without executing forward"
+                    fwd_recv_ops[(stage_idx, mb_index)] = _batch_p2p(
+                        stage.get_fwd_recv_ops(mb_index)
+                    )
+                elif comp_type == RECV_B:
+                    assert (
+                        stage_idx,
+                        mb_index,
+                    ) not in bwd_recv_ops, "Recv twice for {stage_idx=} {mb_index=} without executing backward"
+                    bwd_recv_ops[(stage_idx, mb_index)] = _batch_p2p(
+                        stage.get_bwd_recv_ops(mb_index)
+                    )
+                elif comp_type == UNSHARD:
+                    if stage_uses_fsdp:
+                        assert (
+                            stage_idx not in unsharded_stages
+                            and stage_idx not in unshard_ops
+                        ), f"Unsharding the same {stage_idx=} twice"
+                        unshard_ops[stage_idx] = stage.submod.unshard(async_op=True)
+                elif comp_type == RESHARD:
+                    if stage_uses_fsdp:
+                        assert (
+                            stage_idx in unsharded_stages
+                        ), f"Resharding {stage_idx=} without unsharding"
+                        assert (
+                            stage_idx not in unshard_ops
+                        ), f"Resharding {stage_idx=} before finishing unshard"
+                        stage.submod.reshard()
+                elif comp_type == FORWARD:
+                    if stage_uses_fsdp:
+                        _assert_unsharded(stage_idx)
+
+                    if not stage.is_first:
+                        assert (
+                            stage_idx,
+                            mb_index,
+                        ) in fwd_recv_ops, f"Computing {action=} before receiving input"
+                        fwd_recv_ops.pop((stage_idx, mb_index)).wait()
+                    output = stage.forward_one_chunk(
+                        mb_index, arg_mbs[mb_index], kwarg_mbs[mb_index]
+                    )
+                    self._maybe_compute_loss(stage, output, target_mbs, mb_index)
+                elif comp_type == BACKWARD:
+                    if stage_uses_fsdp:
+                        _assert_unsharded(stage_idx)
+
+                    if not stage.is_last:
+                        assert (
+                            stage_idx,
+                            mb_index,
+                        ) in bwd_recv_ops, (
+                            f"Attempted to run compute {action=} before receiving input"
+                        )
+                        bwd_recv_ops.pop((stage_idx, mb_index)).wait()
+                    loss = self._maybe_get_loss(stage, mb_index)
+                    stage.backward_one_chunk(
+                        mb_index, loss=loss, full_backward=self.use_full_backward
+                    )
+                elif comp_type == WEIGHT:
+                    if stage_uses_fsdp:
+                        _assert_unsharded(stage_idx)
+
+                    if self.use_full_backward:
+                        raise ValueError(
+                            f"We detected a weight update in the pipeline schedule, but \
+                            {self.use_full_backward=}"
+                        )
+                    stage.backward_weight_one_chunk(mb_index)
+                else:
+                    raise ValueError(f"{action=} is unknown or unsupported")
+            except Exception as e:
+                logger.error(
+                    "_PipelineScheduleRuntime caught exception at step %s when running action %s.  Full Schedule:",
+                    time_step,
+                    action,
+                )
+                # TODO(whc) what is the best practice for printing a multiline log?
+                # logger will split it into multiple log lines, but this makes it hard to read (too wide)
+                print(_format_pipeline_order(self.pipeline_order_with_comms))  # type: ignore[arg-type]
+                raise e
+
+        # Mostly these operations should have finished long ago, but there isn't an obvious time when to wait for them
+        while len(send_ops):
+            send_ops.pop().wait()
+
+        assert len(unshard_ops) == 0, "Unused unshard operations"
+
+        # Return losses if there is a container passed in
+        self._update_losses(self._stages, losses)
+
+
+class ScheduleLoopedBFS(PipelineScheduleMulti):
+    """
+    Breadth-First Pipeline Parallelism.
+    See https://arxiv.org/abs/2211.05953 for details.
+    Simliar to Interleaved 1F1B, Looped BFS supports multiple stages per rank.
+    What is different is that when microbatches are ready for multiple local
+    stages, Loops BFS will prioritizes the earlier stage, running all available
+    microbatches at once.
+    """
+
+    def __init__(
+        self,
+        stages: List[_PipelineStageBase],
+        n_microbatches: int,
+        loss_fn: Optional[Callable] = None,
+        output_merge_spec: Optional[Union[Dict[str, Any], Tuple[Any]]] = None,
+    ):
+        super().__init__(
+            stages=stages,
+            n_microbatches=n_microbatches,
+            loss_fn=loss_fn,
+            output_merge_spec=output_merge_spec,
+        )
+
+        # 1. Create the pipeline_order (all ranks do this calculation)
+        # This will be used to keep track of the current state of the entire pipeline
+        # pipeline_order[rank] = [Action(computation_type, microbatch_index, stage_index), ...]
+        self.pipeline_order: Dict[int, List[Optional[_Action]]] = {}
+        # ========================================================================
+        for rank in range(self.pp_group_size):
+            rank_ops = self._calculate_single_rank_operations(rank)
+            self.pipeline_order[rank] = rank_ops
+
+    def _calculate_single_rank_operations(self, rank):
+        n_local_stages = len(self._stages)
+        stage_indices = range(
+            rank, self.pp_group_size * n_local_stages, self.pp_group_size
+        )
+
+        # Store the list of operations used for that rank
+        rank_ops: List[Optional[_Action]] = []
+        # Pre-padding, rank starts with no-ops based on the warmup.
+        for _ in range(rank):
+            rank_ops.append(None)
+
+        for stage_index in stage_indices:
+            for mb_index in range(self._n_microbatches):
+                rank_ops.append(
+                    _Action(stage_index, _ComputationType.FORWARD, mb_index)
+                )
+
+        # wait for the first backward to trickle up
+        # which is 2 for every hop away
+        post_warmup_ops = 2 * (self.pp_group_size - 1 - rank)
+        rank_ops.extend([None] * post_warmup_ops)
+
+        for stage_index in reversed(stage_indices):
+            for mb_index in reversed(range(self._n_microbatches)):
+                rank_ops.append(
+                    _Action(stage_index, _ComputationType.BACKWARD, mb_index)
+                )
+        return rank_ops
+
+
+def _get_1f1b_rank_ops(
+    n_local_stages,
+    pp_group_size,
+    warmup_ops,
+    fwd_bwd_ops,
+    cooldown_ops,
+    rank,
+    forward_stage_index,
+    backward_stage_index,
+    num_1f1b_microbatches=0,
+    enable_zero_bubble=False,
+):
+    # All stages start with handling microbatch 0
+    fwd_stage_mb_index: Dict[int, int] = defaultdict(int)
+    bwd_stage_mb_index: Dict[int, int] = defaultdict(int)
+    weight_stage_mb_index: Dict[int, int] = defaultdict(int)
+
+    # Store the list of operations used for that rank
+    rank_ops: List[Optional[_Action]] = []
+    # Pre-padding, rank starts with no-ops based on the warmup.
+    for _ in range(rank):
+        rank_ops.append(None)
+    # These are used to calculate the number of slots to fill with no-ops, to account for the delay in warmup
+    # when we want to wait for the backward to trickle back up and start 1f1b to align all ranks.
+    # Formula:
+    # pre-padding + warmup_ops + post_warmup_ops = earliest time step of first backward
+    # post_warmup_ops = [earliest time step of first backward] - (warmup_ops + pre-padding)
+    # earliest time step of first backward = [local_stages * group_size + 2 * (group_size - 1 - rank)]
+    # warmup_ops = calculated above
+    post_warmup_ops = (
+        n_local_stages * pp_group_size + 2 * (pp_group_size - 1 - rank)
+    ) - (warmup_ops + rank)
+
+    if enable_zero_bubble:
+        post_warmup_ops = pp_group_size - rank - 1
+
+    total_ops = warmup_ops + fwd_bwd_ops + cooldown_ops
+
+    backward_op_ids = []
+    weight_op_count = 0
+
+    for op in range(total_ops):
+        # Warmup phase
+        if op < warmup_ops:
+            fwd_stage_index = forward_stage_index(op)
+            # This will assign the current microbatch index and update it as well
+            fwd_stage_mb_index[fwd_stage_index] = (
+                mb_index := fwd_stage_mb_index[fwd_stage_index]
+            ) + 1
+            rank_ops.append(
+                _Action(fwd_stage_index, _ComputationType.FORWARD, mb_index)
+            )
+            if op == warmup_ops - 1:
+                # This is the last step in the warmup phase, so we need to wait for the backward to trickle back up
+                rank_ops.extend([None] * post_warmup_ops)
+        # 1F1B Phase (forward and backward)
+        elif warmup_ops <= op < warmup_ops + fwd_bwd_ops:
+            fwd_stage_index = forward_stage_index(op)
+            fwd_stage_mb_index[fwd_stage_index] = (
+                fwd_mb_index := fwd_stage_mb_index[fwd_stage_index]
+            ) + 1
+            rank_ops.append(
+                _Action(fwd_stage_index, _ComputationType.FORWARD, fwd_mb_index)
+            )
+            bwd_stage_index = backward_stage_index(op)
+            bwd_stage_mb_index[bwd_stage_index] = (
+                bwd_mb_index := bwd_stage_mb_index[bwd_stage_index]
+            ) + 1
+            rank_ops.append(
+                _Action(bwd_stage_index, _ComputationType.BACKWARD, bwd_mb_index)
+            )
+            backward_op_ids.append(op)
+
+            if enable_zero_bubble and op - warmup_ops >= num_1f1b_microbatches:
+                weight_stage_index = backward_stage_index(
+                    backward_op_ids[weight_op_count]
+                )
+                weight_stage_mb_index[weight_stage_index] = (
+                    weight_mb_index := weight_stage_mb_index[weight_stage_index]
+                ) + 1
+                rank_ops.append(
+                    _Action(
+                        weight_stage_index, _ComputationType.WEIGHT, weight_mb_index
+                    )
+                )
+                weight_op_count += 1
+        # Cooldown phase
+        else:
+            # During cooldown phase, we need steps to align with 1f1b happening in other ranks
+            # TODO: we don't need to always append, after all 1f1b are finished we can stop appending None
+            if not enable_zero_bubble:
+                rank_ops.append(None)
+
+            bwd_stage_index = backward_stage_index(op)
+            bwd_stage_mb_index[bwd_stage_index] = (
+                bwd_mb_index := bwd_stage_mb_index[bwd_stage_index]
+            ) + 1
+            rank_ops.append(
+                _Action(bwd_stage_index, _ComputationType.BACKWARD, bwd_mb_index)
+            )
+            backward_op_ids.append(op)
+
+            if enable_zero_bubble and op - warmup_ops >= num_1f1b_microbatches:
+                weight_stage_index = backward_stage_index(
+                    backward_op_ids[weight_op_count]
+                )
+                weight_stage_mb_index[weight_stage_index] = (
+                    weight_mb_index := weight_stage_mb_index[weight_stage_index]
+                ) + 1
+                rank_ops.append(
+                    _Action(
+                        weight_stage_index, _ComputationType.WEIGHT, weight_mb_index
+                    )
+                )
+                weight_op_count += 1
+
+    while enable_zero_bubble and weight_op_count < len(backward_op_ids):
+        weight_stage_index = backward_stage_index(backward_op_ids[weight_op_count])
+        weight_stage_mb_index[weight_stage_index] = (
+            weight_mb_index := weight_stage_mb_index[weight_stage_index]
+        ) + 1
+        rank_ops.append(
+            _Action(weight_stage_index, _ComputationType.WEIGHT, weight_mb_index)
+        )
+        weight_op_count += 1
+
+    return rank_ops
+
+
+class ScheduleInterleaved1F1B(PipelineScheduleMulti):
+    """
+    The Interleaved 1F1B schedule.
+    See https://arxiv.org/pdf/2104.04473 for details.
+    Will perform one forward and one backward on the microbatches in steady
+    state and supports multiple stages per rank. When microbatches are ready for
+    multiple local stages, Interleaved 1F1B prioritizes the earlier microbatch
+    (also called "depth first").
+    """
+
+    def __init__(
+        self,
+        stages: List[_PipelineStageBase],
+        n_microbatches: int,
+        loss_fn: Optional[Callable] = None,
+        args_chunk_spec: Optional[Tuple[TensorChunkSpec, ...]] = None,
+        kwargs_chunk_spec: Optional[Dict[str, TensorChunkSpec]] = None,
+        output_merge_spec: Optional[Union[Dict[str, Any], Tuple[Any]]] = None,
+    ):
+        self.pp_group_size = stages[0].group_size
+        # TODO: is this limitation a must?
+        if n_microbatches % self.pp_group_size != 0:
+            raise ValueError(
+                f"Interleaved 1F1B schedule requires the number of microbatches ({n_microbatches}) \
+                to be a multiple of the number of pipeline ranks ({self.pp_group_size})."
+            )
+
+        super().__init__(
+            stages=stages,
+            n_microbatches=n_microbatches,
+            loss_fn=loss_fn,
+            args_chunk_spec=args_chunk_spec,
+            kwargs_chunk_spec=kwargs_chunk_spec,
+            output_merge_spec=output_merge_spec,
+        )
+
+        self.n_local_stages = len(stages)
+        self.rank = stages[0].group_rank
+        self.group = stages[0].group
+
+        # 1. Create the pipeline_order (all ranks do this calculation)
+        # This will be used to keep track of the current state of the entire pipeline
+        # pipeline_order[rank] = [Action(computation_type, microbatch_index, stage_index), ...]
+        self.pipeline_order: Dict[int, List[Optional[_Action]]] = {}
+
+        for rank in range(self.pp_group_size):
+            rank_ops = self._calculate_single_rank_operations(rank)
+            self.pipeline_order[rank] = rank_ops
+
+    def _calculate_single_rank_operations(self, rank) -> List[Optional[_Action]]:
+        def get_rank_warmup_ops(rank):
+            # Warms up operations for last stage
+            warmups_ops_last_stage = (self.n_local_stages - 1) * self.pp_group_size
+            # Increment warmup operations by 2 for each hop away from the last stage
+            warmup_ops = warmups_ops_last_stage + 2 * ((self.pp_group_size - 1) - rank)
+            # We cannot have more warmup operations than there are number of microbatches, so cap it there
+            return min(warmup_ops, self._n_microbatches * self.n_local_stages)
+
+        warmup_ops = get_rank_warmup_ops(rank)
+        microbatch_ops = self.n_local_stages * self._n_microbatches
+        # fwd_bwd_ops should encompass the remaining forwards
+        fwd_bwd_ops = microbatch_ops - warmup_ops
+        # cooldown_ops should encompass the remaining backwards
+        cooldown_ops = microbatch_ops - fwd_bwd_ops
+        # total ops encompass both forward and backward ops
+        total_ops = warmup_ops + fwd_bwd_ops + cooldown_ops
+        # warmup_ops + fwd_bwd_ops * 2 + cooldown_ops == microbatch_ops * 2
+
+        logger.debug(
+            "rank %s, warmup_ops %s, 1f1b %s, cooldown_ops %s total_ops %s",
+            rank,
+            warmup_ops,
+            fwd_bwd_ops,
+            cooldown_ops,
+            total_ops,
+        )
+
+        # Calculates the stage index based on step and pp_group_size
+        def forward_stage_index(step):
+            # Get the local index from 0 to n_local_stages-1
+            local_index = (step // self.pp_group_size) % self.n_local_stages
+            return (local_index * self.pp_group_size) + rank
+
+        def backward_stage_index(step):
+            local_index = (
+                self.n_local_stages
+                - 1
+                - ((step - warmup_ops) // self.pp_group_size) % self.n_local_stages
+            )
+            return (local_index * self.pp_group_size) + rank
+
+        return _get_1f1b_rank_ops(
+            self.n_local_stages,
+            self.pp_group_size,
+            warmup_ops,
+            fwd_bwd_ops,
+            cooldown_ops,
+            rank,
+            forward_stage_index,
+            backward_stage_index,
+        )
+
+
+class ScheduleFlexibleInterleaved1F1B(PipelineScheduleMulti):
+    """
+    The Flexible Interleaved 1F1B schedule.
+
+    This schedule is mostly similar to the interleaved 1F1B schedule.
+    It differs by being relaxing the requirement of num_microbatch % pp_size == 0.
+    Using the flex_pp schedule, we will have num_rounds = max(1, n_microbatches // pp_group_size) and
+    it works as long as n_microbatches % num_rounds is 0. As a few examples, support
+
+    1. pp_group_size = 4, n_microbatches = 10. We will have num_rounds = 2 and n_microbatches % 2 is 0.
+    2. pp_group_size = 4, n_microbatches = 3. We will have num_rounds = 1 and n_microbatches % 1 is 0.
+
+    When enable_zero_bubble is True, we will use the ZB1P schedule in https://openreview.net/pdf?id=tuzTN0eIO5
+    """
+
+    def __init__(
+        self,
+        stages: List[_PipelineStageBase],
+        n_microbatches: int,
+        loss_fn: Optional[Callable] = None,
+        args_chunk_spec: Optional[Tuple[TensorChunkSpec, ...]] = None,
+        kwargs_chunk_spec: Optional[Dict[str, TensorChunkSpec]] = None,
+        output_merge_spec: Optional[Union[Dict[str, Any], Tuple[Any]]] = None,
+        enable_zero_bubble: bool = False,
+    ):
+        self.pp_group_size = stages[0].group_size
+        super().__init__(
+            stages=stages,
+            n_microbatches=n_microbatches,
+            loss_fn=loss_fn,
+            args_chunk_spec=args_chunk_spec,
+            kwargs_chunk_spec=kwargs_chunk_spec,
+            output_merge_spec=output_merge_spec,
+            use_full_backward=not enable_zero_bubble,
+        )
+        self.n_local_stages = len(stages)
+        self.rank = stages[0].group_rank
+        self.number_of_rounds = max(1, n_microbatches // self.pp_group_size)
+        self.microbatches_per_round = n_microbatches // self.number_of_rounds
+        self.enable_zero_bubble = enable_zero_bubble
+        if n_microbatches % self.number_of_rounds != 0:
+            raise ValueError(
+                "Flexible Interleaved 1F1B requires the number of microbatches to be a "
+                f"multiple of the number of rounds ({self.number_of_rounds}), "
+                f"but got {n_microbatches}."
+            )
+        # 1. Create the pipeline_order (all ranks do this calculation)
+        # This will be used to keep track of the current state of the entire pipeline
+        # pipeline_order[rank] = [Action(computation_type, microbatch_index, stage_index), ...]
+        self.pipeline_order: Dict[int, List[Optional[_Action]]] = {}
+        for rank in range(self.pp_group_size):
+            rank_ops = self._calculate_single_rank_operations(rank)
+            self.pipeline_order[rank] = rank_ops
+
+        # This function add bubbles to the generated schedule based on dependencies of actions
+        # Note that the ZB1P schedule will not require bubbles to be manually added and it is
+        # only useful when n_microbatches <= microbatches_per_round
+        self.pipeline_order = self._add_bubbles_to_actions(
+            self.n_local_stages * self.pp_group_size,
+        )
+
+    def _calculate_single_rank_operations(self, rank) -> List[Optional[_Action]]:
+        def get_rank_warmup_ops(rank):
+            # Warms up operations for last stage
+            warmups_ops_last_stage = (
+                self.n_local_stages - 1
+            ) * self.microbatches_per_round
+            # Increment warmup operations by 2 for each hop away from the last stage
+            multiply_factor = 1 if self.enable_zero_bubble else 2
+            warmup_ops = warmups_ops_last_stage + multiply_factor * (
+                (self.pp_group_size - 1) - rank
+            )
+
+            # We cannot have more warmup operations than there are number of microbatches, so cap it there
+            return min(warmup_ops, self._n_microbatches * self.n_local_stages)
+
+        warmup_ops = get_rank_warmup_ops(rank)
+        microbatch_ops = self.n_local_stages * self._n_microbatches
+        # fwd_bwd_ops should encompass the remaining forwards
+        fwd_bwd_ops = microbatch_ops - warmup_ops
+        # cooldown_ops should encompass the remaining backwards
+        cooldown_ops = microbatch_ops - fwd_bwd_ops
+        # total ops encompass both forward and backward ops
+        total_ops = warmup_ops + fwd_bwd_ops + cooldown_ops
+        # warmup_ops + fwd_bwd_ops * 2 + cooldown_ops == microbatch_ops * 2
+        logger.debug(
+            "rank %s, warmup_ops %s, 1f1b %s, cooldown_ops %s total_ops %s",
+            rank,
+            warmup_ops,
+            fwd_bwd_ops,
+            cooldown_ops,
+            total_ops,
+        )
+
+        # Calculates the stage index based on step and pp_group_size
+
+        def forward_stage_index(step):
+            # Get the local index from 0 to n_local_stages-1
+            local_index = (step // self.microbatches_per_round) % self.n_local_stages
+            return (local_index * self.pp_group_size) + rank
+
+        def backward_stage_index(step):
+            local_index = (
+                self.n_local_stages
+                - 1
+                - ((step - warmup_ops) // self.microbatches_per_round)
+                % self.n_local_stages
+            )
+            return (local_index * self.pp_group_size) + rank
+
+        if self.enable_zero_bubble:
+            num_1f1b_microbatches = rank
+
+            return _get_1f1b_rank_ops(
+                self.n_local_stages,
+                self.pp_group_size,
+                warmup_ops,
+                fwd_bwd_ops,
+                cooldown_ops,
+                rank,
+                forward_stage_index,
+                backward_stage_index,
+                num_1f1b_microbatches,
+                enable_zero_bubble=True,
+            )
+
+        return _get_1f1b_rank_ops(
+            self.n_local_stages,
+            self.pp_group_size,
+            warmup_ops,
+            fwd_bwd_ops,
+            cooldown_ops,
+            rank,
+            forward_stage_index,
+            backward_stage_index,
+        )
+
+    def _add_bubbles_to_actions(self, num_stages_global):
+        actions = self.pipeline_order
+        if not self.enable_zero_bubble:
+            return actions
+
+        def need_bubble(stage, op, microbatch, num_stages_global, seen_ops):
+            if op == _ComputationType.FORWARD:
+                if stage != 0 and (stage - 1, op, microbatch) not in seen_ops:
+                    return True
+            elif op == _ComputationType.BACKWARD:
+                if stage == num_stages_global - 1:
+                    return (stage, _ComputationType.FORWARD, microbatch) not in seen_ops
+                return (stage + 1, op, microbatch) not in seen_ops
+            return False
+
+        seen_ops: Set[Tuple[int, _ComputationType, int]] = set()
+        result: Dict[int, List[Optional[_Action]]] = {}
+        next_pointer: Dict[int, int] = {}
+        bubbles_added: Dict[int, int] = {}
+        total_bubbles_added = 0
+
+        for rank in range(self.pp_group_size):
+            result[rank] = []
+            next_pointer[rank] = 0
+            bubbles_added[rank] = 0
+
+        while True:
+            should_stop = True
+
+            temp_seen_ops: Set[Tuple[int, _ComputationType, int]] = set()
+
+            for rank in range(self.pp_group_size):
+                timestamp = next_pointer[rank]
+                if timestamp >= len(actions[rank]):
+                    continue
+
+                should_stop = False
+
+                if actions[rank][timestamp] is not None:
+                    temp_action = actions[rank][timestamp]
+                    assert temp_action is not None
+                    stage_index, op, microbatch = temp_action
+                    if not need_bubble(
+                        stage_index, op, microbatch, num_stages_global, seen_ops
+                    ):
+                        result[rank].append(actions[rank][timestamp])
+                        if microbatch is not None:
+                            temp_seen_ops.add((stage_index, op, microbatch))
+                        next_pointer[rank] += 1
+                    else:
+                        result[rank].append(None)
+                        bubbles_added[rank] += 1
+                else:
+                    next_pointer[rank] += 1
+                    result[rank].append(None)
+
+            seen_ops.update(temp_seen_ops)
+            if should_stop:
+                break
+
+        if total_bubbles_added > 0:
+            logger.warning(
+                "Non zero bubbles added: total_bubbles_added=%s bubbles_added=%s",
+                total_bubbles_added,
+                bubbles_added,
+            )
+        return result
+
+
+class ScheduleInterleavedZeroBubble(ScheduleFlexibleInterleaved1F1B):
+    """
+    The Interleaved Zero Bubble schedule.
+    See https://arxiv.org/pdf/2401.10241 for details.
+    Will perform one forward and one backward on inputs for the microbatches in steady
+    state and supports multiple stages per rank. Uses the backward for weights to fill in
+    the pipeline bubble.
+    """
+
+    def __init__(
+        self,
+        stages: List[_PipelineStageBase],
+        n_microbatches: int,
+        loss_fn: Optional[Callable] = None,
+        args_chunk_spec: Optional[Tuple[TensorChunkSpec, ...]] = None,
+        kwargs_chunk_spec: Optional[Dict[str, TensorChunkSpec]] = None,
+        output_merge_spec: Optional[Union[Dict[str, Any], Tuple[Any]]] = None,
+    ):
+        super().__init__(
+            stages=stages,
+            n_microbatches=n_microbatches,
+            loss_fn=loss_fn,
+            args_chunk_spec=args_chunk_spec,
+            kwargs_chunk_spec=kwargs_chunk_spec,
+            output_merge_spec=output_merge_spec,
+            enable_zero_bubble=True,
+        )
+
+
+def get_schedule_class(schedule_name: str):
+    """
+    Maps a schedule name to its corresponding class object.
+
+    Args:
+        schedule_name (str): The name of the schedule.
+    """
+    schedule_map = {
+        "1F1B": Schedule1F1B,
+        "Interleaved1F1B": ScheduleInterleaved1F1B,
+        "GPipe": ScheduleGPipe,
+        "FlexibleInterleaved1F1B": ScheduleFlexibleInterleaved1F1B,
+        "LoopedBFS": ScheduleLoopedBFS,
+        "InterleavedZeroBubble": ScheduleInterleavedZeroBubble,
+        "PipelineScheduleSingle": PipelineScheduleSingle,
+        "PipelineScheduleMulti": PipelineScheduleMulti,
+    }
+    if schedule_name not in schedule_map:
+        raise ValueError(f"Unknown schedule name: {schedule_name}")
+    return schedule_map[schedule_name]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/stage.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/stage.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c4abfb7b0b35271e36703aca6fdff46db0cf4d7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/pipelining/stage.py
@@ -0,0 +1,1468 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and affiliates
+import logging
+import operator
+from abc import ABC, abstractmethod
+from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union
+
+import torch
+import torch.distributed as dist
+import torch.fx as fx
+import torch.nn as nn
+from torch._subclasses.fake_tensor import FakeTensor
+from torch.distributed._composable.fsdp.fully_shard import FSDPModule, fully_shard
+from torch.fx.node import map_aggregate
+from torch.nn.parallel import DistributedDataParallel
+
+from ._backward import stage_backward, stage_backward_input, stage_backward_weight
+from ._debug import map_debug_info
+from ._utils import flatten_args, PipeInfo, validate_tensors_metadata
+
+
+__all__ = [
+    "PipelineStage",
+    "build_stage",
+]
+
+logger = logging.getLogger(__name__)
+
+
+class _RootArgPlaceholder:
+    """
+    Placeholder for model-level inputs.
+    """
+
+    def __init__(self, tensor):
+        self.meta = tensor.to("meta")
+
+
+class _RecvInfo:
+    """
+    Represents a stage input.
+    """
+
+    def __init__(
+        self,
+        input_name: str,
+        source: int,
+        buffer: torch.Tensor,
+    ):
+        # Name of this input
+        self.input_name = input_name
+        # Stage index of the source of this input
+        self.source = source
+        # Buffer to receive the input into.
+        self.buffer = buffer
+
+    def __repr__(self):
+        return f"_RecvInfo(input={self.input_name}, source={self.source}, shape={self.buffer.size()})"
+
+
+# An input can be either a received activation or a model input
+InputInfo = Union[_RecvInfo, _RootArgPlaceholder]
+
+
+def _make_tensor_from_meta(
+    example: Union[torch.Tensor, FakeTensor],
+    device: torch.device,
+) -> torch.Tensor:
+    """
+    Create a real tensor from a tensor.
+    """
+    return torch.empty(
+        example.size(),
+        dtype=example.dtype,
+        layout=example.layout,
+        device=device,
+    )
+
+
+class _PipelineStageBase(ABC):
+    """
+    Base class for pipeline stages.
+    Defines or implements common methods used by the `_PipelineStage` used by
+    the tracing frontend and `PipelineStage` used by manual frontend.
+    """
+
+    def __init__(
+        self,
+        submodule: torch.nn.Module,
+        stage_index: int,
+        num_stages: int,
+        device: torch.device,
+        group: Optional[dist.ProcessGroup] = None,
+        dw_builder: Optional[Callable[[], Callable[..., None]]] = None,
+    ):
+        """
+        Args:
+            submodule (torch.nn.Module): The module to be executed in this stage.
+            stage_index (int): The index of this stage.
+            num_stages (int): The total number of stages in this pipeline.
+            device (torch.device): The device to run this stage on.
+            group (Optional[dist.ProcessGroup]): The process group to use for communication.
+                If `None`, the default process group will be used.
+                Default: `None`.
+            dw_builder (Optional[Callable[[], Callable[..., None]]): If provided, dw_runner is a builder function
+                that will build a new dw_runner function that will run parts of module backward that were intentionally
+                skipped during the module's actual backward pass. The builder must be invoked by stage after stage runs
+                model backwards, and stage should save the latest dw_runner to run during weight pass.
+                If not provided, a dw_runner will be generated automatically by traversing the autograd graph.
+                When used with schedules that only have F and B steps, the fresh dw_runner function will be called as
+                part of B.
+                When used with F,B,W schedules, the dw_runner function implements 'W'.
+        """
+        super().__init__()
+        if stage_index >= num_stages:
+            raise ValueError(
+                f"Stage index {stage_index} is out of range of {num_stages}"
+            )
+
+        self.submod = submodule
+        self.stage_index = stage_index
+        self.num_stages = num_stages
+        self.device = device
+        self.group = group
+
+        self.dw_builder = dw_builder
+
+        # backward state
+        self.backward_state: Dict[int, Tuple[Any, ...]] = {}
+
+        # store dw_runner per microbatch_id
+        self.dw_runner: Dict[int, Callable[..., None]] = {}
+
+        # `group_rank` is rank in process group `group`.
+        self.group_rank = dist.get_rank(self.group)
+        self.group_size = dist.get_world_size(self.group)
+        if self.group_size > self.num_stages:
+            raise RuntimeError(
+                f"Pipeline group size {self.group_size} cannot be larger than number of stages {self.num_stages}"
+            )
+
+        # Run time states
+        self._outputs_meta: Optional[Tuple[torch.Tensor, ...]] = None
+        # map microbatch ID to list of forward tensor args
+        self.fwd_cache: Dict[int, Tuple[Any, List[torch.Tensor]]] = {}
+        # Caching chunk outputs for final output merge or reduction
+        self.output_chunks: List[Any] = []
+
+        # Initialize has_backward to false; this will be set to true if loss
+        # function is passed to pipeline schedule
+        self.has_backward = False
+        # Log prefix
+        self.log_prefix = f"[Stage {self.stage_index}]"
+
+        # Forward infra
+        self.args_recv_info: Dict[int, Tuple[InputInfo, ...]] = {}
+        self.set_requires_grad: Dict[int, bool] = {}
+        self.act_send_info: Dict[int, List] = {}
+
+        # Backward infra will created lazily
+        self.grad_recv_info: Dict = {}
+        self.grad_send_info: Optional[List] = None
+
+        # Number of backward chunks seen. This is used to determine when to do
+        # grad reduction in DDP or FSDP.
+        self._seen_bwd_chunks = 0
+
+        # To be populated later by the Schedule
+        self.chunks: Optional[int] = None
+        self.stage_index_to_group_rank: Dict[int, int] = {
+            i: i % self.group_size for i in range(self.num_stages)
+        }
+
+    @property
+    def has_backward(self) -> bool:
+        """
+        Returns true if this stage has a backward pass.
+        """
+        return self._has_backward
+
+    @has_backward.setter
+    def has_backward(self, has_backward: bool):
+        self._has_backward = has_backward
+
+    @property
+    def is_first(self):
+        """
+        Returns true if this stage is the first stage in the pipeline.
+        """
+        return self.stage_index == 0
+
+    @property
+    def is_last(self):
+        """
+        Returns true if this stage is the last stage in the pipeline.
+        """
+        return self.stage_index == self.num_stages - 1
+
+    def _check_chunk_id(self, chunk_id: int):
+        if self.chunks is None:
+            raise RuntimeError(
+                "Attempted to access chunk_id before chunks have been configured."
+            )
+        if chunk_id >= self.chunks:
+            raise RuntimeError(
+                f"Chunk id {chunk_id} is out of range [0, {self.chunks})"
+            )
+
+    def _configure_outputs_meta(self, outputs_meta: Tuple[torch.Tensor, ...]):
+        """
+        Track the output shapes/dtype of this stage since they determine the send operation(s) which must match
+        recv operations of the next stage.  The next stage _will_ be freezing its recv buffers based on its initial
+        configuration, so it's important to also freeze/validate the output side to avoid any send/recv mismatches
+        which could show up as hangs, silent corruption, or other errors.
+        """
+        assert (
+            self._outputs_meta is None
+        ), "Attempting to reconfigure output_meta, which is not supported"
+        self._outputs_meta = tuple(outputs_meta)  # type: ignore[assignment]
+
+    def get_outputs_meta(self) -> Tuple[torch.Tensor, ...]:
+        """Get the output metadata (meta tensors) reprensenting the outputs of this stage"""
+        assert (
+            self._outputs_meta is not None
+        ), "Attempted to get_outputs_meta() without configuring output meta"
+        return self._outputs_meta
+
+    def _create_grad_send_info(
+        self,
+        args_recv_info: Tuple,
+    ) -> List[Optional[int]]:
+        """
+        Create a list of stage indices to send gradients to.
+        """
+        grad_send_info: List[Optional[int]] = []
+
+        def map_recv_to_send(a):
+            # Note: we send gradients back to previous stage as long as in
+            # forward it is a received input, regardless of whether it requires
+            # grad. It is up to the previous stage to disgard this gradient.
+            if isinstance(a, _RecvInfo):
+                grad_send_info.append(a.source)
+                return a.source
+            else:
+                grad_send_info.append(None)
+                return None
+
+        map_aggregate(args_recv_info, map_recv_to_send)
+
+        logger.debug("%s Grad send info: %s", self.log_prefix, grad_send_info)
+        return grad_send_info
+
+    @abstractmethod
+    def _prepare_forward_infra(self, num_microbatches: int):
+        raise NotImplementedError
+
+    def _prepare_backward_infra(self, num_microbatches: int):
+        # TODO: this is needed for backward_maybe_with_nosync
+        self.chunks = num_microbatches
+
+        for mb_index in range(num_microbatches):
+            # `grad_recv_info` is a mirror of `act_send_info`
+            self.grad_recv_info[mb_index] = self._create_grad_recv_info(
+                self.act_send_info
+            )
+
+    @abstractmethod
+    def _create_grad_recv_info(
+        self,
+        act_send_info: Dict,
+    ) -> Tuple[_RecvInfo, ...]:
+        raise NotImplementedError
+
+    def _get_recv_ops(
+        self,
+        recv_infos: Tuple[InputInfo, ...],
+    ) -> List[dist.P2POp]:
+        """
+        Helper function shared by `get_fwd_recv_ops` and `get_bwd_recv_ops`.
+        Returns a list of ops that correspond to the recv infos.
+        """
+        ops: List[dist.P2POp] = []
+        for info in recv_infos:
+            if not isinstance(info, _RecvInfo):
+                continue
+
+            peer_rank = self.stage_index_to_group_rank[info.source]
+            peer_global_rank = (
+                peer_rank
+                if self.group is None
+                else dist.get_global_rank(self.group, peer_rank)
+            )  # TODO
+            ops.append(
+                dist.P2POp(dist.irecv, info.buffer, peer_global_rank, self.group)
+            )
+
+        return ops
+
+    def get_fwd_recv_ops(self, fwd_chunk_id: int) -> List[dist.P2POp]:
+        """
+        Returns a list of ops that are needed to receive the input arguments
+        for this stage.
+        """
+        recv_infos: Tuple[InputInfo, ...] = self.args_recv_info[fwd_chunk_id]
+
+        # In case there is backward pass, set requires_grad for receive buffers
+        # before first forward
+        if self.has_backward and not self.set_requires_grad[fwd_chunk_id]:
+            for a in recv_infos:
+                if isinstance(a, _RecvInfo):
+                    a.buffer.requires_grad_(True)
+
+        return self._get_recv_ops(recv_infos)
+
+    def get_bwd_recv_ops(self, bwd_chunk_id: int) -> List[dist.P2POp]:
+        """
+        Returns a list of ops that are needed to receive the gradients
+        for this stage.
+        """
+        if not self.has_backward or self.is_last:
+            return []
+
+        recv_infos = self.grad_recv_info[bwd_chunk_id]
+        return self._get_recv_ops(recv_infos)
+
+    def get_fwd_send_ops(self, fwd_chunk_id: int) -> List[dist.P2POp]:
+        """
+        Get the activation send ops for current stage's forward.
+        """
+        output = self.output_chunks[fwd_chunk_id]
+        # Unify output form to tuple for easy correspondance with
+        # `act_send_info`
+        output_tuple = output if type(output) is tuple else (output,)
+
+        ops: List[dist.P2POp] = []
+
+        for idx, out in enumerate(output_tuple):
+            dst_stages = self.act_send_info[idx]
+            for dst in dst_stages:
+                if dst is None:
+                    continue
+                logger.debug(
+                    "%s Sending tensor to Stage %s: %s",
+                    self.log_prefix,
+                    dst,
+                    out.size(),
+                )
+                peer_rank = self.stage_index_to_group_rank[dst]
+                peer_global_rank = (
+                    peer_rank
+                    if self.group is None
+                    else dist.get_global_rank(self.group, peer_rank)
+                )  # TODO
+                ops.append(dist.P2POp(dist.isend, out, peer_global_rank, self.group))
+
+        return ops
+
+    def get_bwd_send_ops(self, bwd_chunk_id: int) -> List[dist.P2POp]:
+        """
+        Get the gradient send ops for current stage's backward.
+        """
+        self._check_chunk_id(bwd_chunk_id)
+
+        if not self.has_backward or self.is_first:
+            return []
+
+        # Create bwd send infra lazily
+        if self.grad_send_info is None:
+            # Send info for input grads during backward:
+            # List of destinations corresponding to input grads
+            # Can be None if an input has no grad
+            # `grad_send_info` is a mirror of `args_recv_info`
+            self.grad_send_info = self._create_grad_send_info(self.args_recv_info[0])
+
+        ops: List[dist.P2POp] = []
+        for grad, grad_recv_stage in zip(self.grads_input, self.grad_send_info):
+            if isinstance(grad, torch.Tensor) and grad_recv_stage is not None:
+                logger.debug(
+                    "%s Sending gradient to Stage %s: %s",
+                    self.log_prefix,
+                    grad_recv_stage,
+                    grad.size(),
+                )
+                peer_rank = self.stage_index_to_group_rank[grad_recv_stage]
+                peer_global_rank = (
+                    peer_rank
+                    if self.group is None
+                    else dist.get_global_rank(self.group, peer_rank)
+                )  # TODO
+                ops.append(dist.P2POp(dist.isend, grad, peer_global_rank, self.group))
+            else:
+                if not (grad is None and grad_recv_stage is None):
+                    raise RuntimeError(
+                        f"[{self.stage_index}] for chunk {bwd_chunk_id} has gradients {grad} "
+                        f"and is expecting to send gradients to stage {grad_recv_stage}"
+                    )
+        return ops
+
+    def clear_runtime_states(self) -> None:
+        """
+        Clear runtime states of the stage.
+        """
+        # map microbatch ID to list of forward tensor args
+        self.fwd_cache.clear()
+        # Caching chunk outputs for final output merge or reduction
+        self.output_chunks.clear()
+        # Reset bwd chunk counter
+        self._seen_bwd_chunks = 0
+
+        # Clear grad of input buffers in between schedule steps. This is because
+        # `torch.autograd.backward()` will accumulate gradients into leaf
+        # tensors by default. For gradients to pass back to previous stages, we
+        # don't want such accumulation.
+        for recv_tuple in self.args_recv_info.values():  # iterate over all chunks
+            for a in recv_tuple:  # iterate over all input args
+                if isinstance(a, _RecvInfo):
+                    # Set to None is the newer and recommended way to clear grads, compared to `zero_()`.
+                    # See https://github.com/pytorch/pytorch/pull/92731
+                    a.buffer.grad = None
+
+    def _map_tensor_from_recv_info(
+        self,
+        recv_infos: Tuple[InputInfo, ...],
+    ):
+        """
+        Map tensors from recv infos to a list.
+        """
+
+        def get_recv_tensor(info):
+            if isinstance(info, _RecvInfo):
+                return info.buffer
+            else:
+                raise AssertionError(f"Expected _RecvInfo but got {type(info)}")
+
+        tensors = map_aggregate(
+            recv_infos,
+            get_recv_tensor,
+        )
+
+        return tensors
+
+    def _retrieve_recv_activations(self, fwd_chunk_id: int):
+        """
+        Retrieve the activations received for the current stage during forward.
+        """
+        recv_infos = self.args_recv_info[fwd_chunk_id]
+        activations = self._map_tensor_from_recv_info(recv_infos)
+        return activations
+
+    def _retrieve_recv_grads(
+        self,
+        bwd_chunk_id: int,
+    ):
+        """
+        Retrieve the gradients received for the current stage during backward.
+        """
+        recv_infos = self.grad_recv_info[bwd_chunk_id]
+        grads = self._map_tensor_from_recv_info(recv_infos)
+        return grads
+
+    def forward_maybe_with_nosync(self, *args, **kwargs):
+        # If submod is wrapped with DDP, we use the `no_sync` context manager to
+        # avoid gradient all-reduce per microbatch
+        if isinstance(self.submod, DistributedDataParallel):
+            with self.submod.no_sync():  # type: ignore[operator]
+                out_val = self.submod(*args, **kwargs)
+        else:
+            out_val = self.submod(*args, **kwargs)
+        return out_val
+
+    def backward_maybe_with_nosync(self, backward_type, bwd_kwargs: Dict):
+        """
+        Whether using PP with FSDP or DDP, there are some runtime differences between the last backward step and the
+        other steps.  Namely, we need to accumulate gradients on previous steps and reduce them on the last step, but
+        there are additional state-variables and performance considerations depending on the data parallelism used.
+        This helper should adapt any pipeline parallel schedule to work with common/supported data parallel libraries.
+        """
+        full_backward = bwd_kwargs["full_backward"]
+        if full_backward:
+            last_backward = self._seen_bwd_chunks == self.chunks - 1  # type: ignore[operator]
+        else:
+            # For backwards are split into weight and input, we will see twice as many bwd_chunks
+            last_backward = self._seen_bwd_chunks == 2 * self.chunks - 1  # type: ignore[operator]
+
+        def perform_backward(backward_type):
+            if backward_type == "full":
+                return lambda: stage_backward(
+                    bwd_kwargs["stage_output"],
+                    bwd_kwargs["output_grads"],
+                    bwd_kwargs["input_values"],
+                )
+            elif backward_type == "input":
+                return lambda: stage_backward_input(
+                    bwd_kwargs["stage_output"],
+                    bwd_kwargs["output_grads"],
+                    bwd_kwargs["input_values"],
+                    self.submod.parameters(),
+                )
+            elif backward_type == "weight":
+                return lambda: stage_backward_weight(
+                    self.submod.parameters(), bwd_kwargs["param_groups"]
+                )
+            else:
+                raise RuntimeError(f"Unknown backward type: {backward_type}")
+
+        # If submod is wrapped by DDP
+        if isinstance(self.submod, DistributedDataParallel):
+            if last_backward:
+                # Last chunk, prepare for gradient reduction
+                # HACK: reaching into DDP implementation details here. Is there a better way?
+                self.submod.reducer.prepare_for_backward(  # type: ignore[union-attr, operator]
+                    list(
+                        torch.nn.parallel.distributed._find_tensors(  # type: ignore[attr-defined]
+                            bwd_kwargs["stage_output"]
+                        )
+                    )
+                )
+                result = perform_backward(backward_type)()
+            else:
+                with self.submod.no_sync():  # type: ignore[operator]
+                    result = perform_backward(backward_type)()
+        # If submod is a FSDP module
+        elif isinstance(self.submod, FSDPModule):
+            self.submod.set_is_last_backward(False)
+            self.submod.set_reshard_after_backward(False)
+            self.submod.set_requires_gradient_sync(False)
+            result = perform_backward(backward_type)()
+            if last_backward:
+                # Manually call post backward for FSDP
+                def run_post_backward(fsdp_module: FSDPModule) -> None:
+                    fsdp_module.set_is_last_backward(True)
+                    fsdp_module.set_reshard_after_backward(True)
+                    fsdp_module.set_requires_gradient_sync(True)
+                    fsdp_state = fully_shard.state(fsdp_module)
+                    for state in fsdp_state._state_ctx.all_states:
+                        if state._fsdp_param_group:
+                            state._fsdp_param_group.post_backward()
+
+                run_post_backward(self.submod)
+        else:
+            # Non-DP submodule, regular backward
+            result = perform_backward(backward_type)()
+
+        self._seen_bwd_chunks += 1
+
+        if isinstance(result, tuple) and len(result) == 2:
+            # for stage_backward_input()
+            grads, param_groups = result
+        else:
+            grads, param_groups = result, None
+
+        return grads, param_groups
+
+    def forward_one_chunk(
+        self,
+        fwd_chunk_id: int,
+        args: Tuple[Any, ...],
+        kwargs: Optional[Dict[str, Any]] = None,
+    ):
+        """
+        Perform forward pass on the stage with one microbatch.
+        `args` and `kwargs` are the inputs from *external* to this stage. They
+        applies only to the first stage in most cases.
+        """
+
+        if self.is_first:
+            # First stage doesn't need to receive anything
+            composite_args = args
+            composite_kwargs = kwargs or {}
+        else:
+            # Receive activations for this chunk
+            # Activations only come in args form
+            composite_args = self._retrieve_recv_activations(fwd_chunk_id)
+            composite_kwargs = {}
+
+        self._validate_fwd_input(args, kwargs)
+
+        # Compute forward
+        try:
+            output = self.forward_maybe_with_nosync(*composite_args, **composite_kwargs)
+
+        except Exception as e:
+            exc_msg = f"""
+            {self.log_prefix} failed to run forward:
+            args: {map_debug_info(composite_args)}
+            kwargs: {map_debug_info(composite_kwargs)}
+            """
+            raise RuntimeError(exc_msg) from e
+
+        if type(output) is list:
+            # HACK: this is a hacky workaround for the fact that export creates
+            # output in list format
+            output = tuple(output)
+
+        # Unify output form to tuple for easy correspondance with
+        # `act_send_info`
+        output_tuple = output if type(output) is tuple else (output,)
+        # Prepare for final output merge or reduction
+        self.output_chunks.append(output)
+
+        # Save activations and inputs for backward
+        flat_args = flatten_args(composite_args)
+        flat_kwargs = flatten_args(composite_kwargs)
+        flatten_input_tensors = flat_args + flat_kwargs
+        self.fwd_cache[fwd_chunk_id] = (
+            output_tuple,  # stage_output
+            flatten_input_tensors,  # input_values
+        )
+
+        logger.debug(
+            "%s Forwarded chunk %s, outputs: %s",
+            self.log_prefix,
+            fwd_chunk_id,
+            map_debug_info(output),
+        )
+        self._validate_fwd_outputs(output_tuple)
+        return output
+
+    def backward_one_chunk(
+        self, bwd_chunk_id: int, loss=None, full_backward: bool = True
+    ):
+        """
+        Perform backward pass on the module.
+        This should only be called once per microbatch.
+
+        If full_backward is True (the default), the full backward pass including weight and input gradients will be run,
+        and it is an error to call `backward_weight_one_chunk` for this bwd_chunk_id.
+
+        If full_backward is False, it is optional that `dw_runner` was provided to the PipelineStage at __init__ time,
+        and a subsequent call to `backward_weight_one_chunk` is required to invoke dw_runner and complete the backward.
+        """
+        self._check_chunk_id(bwd_chunk_id)
+
+        (
+            stage_output,
+            input_values,
+        ) = self.fwd_cache.pop(bwd_chunk_id)
+
+        # Compute backward
+        if self.is_last:
+            # Last stage computes gradients from loss and has no gradients from
+            # next stage
+            bwd_kwargs = {
+                "stage_output": loss,
+                "output_grads": None,
+                "input_values": input_values,
+            }
+        else:
+            # Otherwise, receive gradients from next stage
+            grads_output = self._retrieve_recv_grads(bwd_chunk_id)
+            # If an input to the pipeline requires gradient,
+            # `torch.autograd.backward` will accumulate the gradient into the
+            # `.grad` field of such input
+            bwd_kwargs = {
+                "stage_output": stage_output,
+                "output_grads": grads_output,
+                "input_values": input_values,
+            }
+
+        # Save full_backward
+        bwd_kwargs["full_backward"] = full_backward
+
+        # Custom backward function
+        if self.dw_builder:
+            # TODO: We may want to change our semantics so we are allowed to ignore
+            # the 'dw_builder' and call full_backward directly when it is a full_backward op.
+            self.grads_input, _ = self.backward_maybe_with_nosync("full", bwd_kwargs)
+            if full_backward:
+                self.dw_builder()()
+            else:
+                self.dw_runner[bwd_chunk_id] = self.dw_builder()
+        else:
+            if full_backward:
+                self.grads_input, _ = self.backward_maybe_with_nosync(
+                    "full", bwd_kwargs
+                )
+            else:
+                # perform the partial backwards for the inputs with a custom backward function
+                # when the "stage_ouput" is a loss, then it is a tensor, otherwise it is a tuple of tensors
+                if isinstance(bwd_kwargs["stage_output"], torch.Tensor):
+                    bwd_kwargs["stage_output"] = (bwd_kwargs["stage_output"],)
+
+                grads_input, param_groups = self.backward_maybe_with_nosync(
+                    "input", bwd_kwargs
+                )
+
+                # TODO: we dont need to save this, add to dw_runner?
+                self.backward_state[bwd_chunk_id] = (
+                    input_values,
+                    param_groups,
+                    bwd_kwargs["stage_output"],
+                    bwd_kwargs["output_grads"],
+                )
+                self.grads_input = grads_input
+                # Save a placeholder for the dw_runner
+                self.dw_runner[bwd_chunk_id] = lambda: None
+        logger.debug("%s Backwarded chunk %s", self.log_prefix, bwd_chunk_id)
+
+    def backward_weight_one_chunk(self, bwd_chunk_id: int):
+        assert bwd_chunk_id in self.dw_runner, (
+            f"{self.log_prefix} Attempted to run backward_weight_one_chunk for chunk {bwd_chunk_id}"
+            " without first calling `backward_one_chunk(full_backward=False)`"
+        )
+
+        if self.dw_builder is not None:
+            self.dw_runner.pop(bwd_chunk_id)()
+        else:
+            (
+                input_values,
+                param_groups,
+                stage_output,
+                output_grads,
+            ) = self.backward_state.pop(bwd_chunk_id)
+
+            if self.stage_index != 0:
+                bwd_kwargs = {
+                    "stage_output": stage_output,
+                    "param_groups": param_groups,
+                    "full_backward": False,
+                }
+                weight_grads, _ = self.backward_maybe_with_nosync("weight", bwd_kwargs)
+            else:
+                # TODO: figure out a better way to do this:
+                # if inputs does not require gradient,
+                # then the parameter group will not be fully captured during stage_backward_input
+                # in this case, we need call grad directly on the parameters
+                # To solve: make input fn do the intersect compute and then finish it off during W
+                bwd_kwargs = {
+                    "stage_output": stage_output,
+                    "output_grads": output_grads,
+                    "input_values": input_values,
+                    "full_backward": False,
+                }
+                self.backward_maybe_with_nosync("full", bwd_kwargs)
+
+    def _validate_fwd_input(self, args, kwargs):
+        """Raises a RuntimeError if shapes of input args/kwargs do not match the shapes configured for this stage."""
+
+        if self.is_first:
+            # TODO why is there a separate recv_info for each pipeline chunk?
+            # kwen2501: to avoid passing a `fwd_chunk_id` to this function, we
+            # check all chunks against args_recv_info[0]
+            expected_args = self.args_recv_info[0]
+        else:
+            # We don't check inputs for non-0 stages assuming they don't accept
+            # user inputs in canonical pipeline scenarios
+            return
+
+        if len(kwargs):
+            # TODO- need a mapping of kwarg to position in self.args_recv_info
+            # without it, we just validate shapes for args and ignore kwargs
+            expected_args = expected_args[: len(expected_args) - len(kwargs)]
+
+        # TODO- need a mapping of kwarg to position in self.args_recv_info
+        # maybe it's impossible to tell whether the len mismatches because
+        # (a) the user passed an extra arg or missed an arg
+        # (b) the user did not pass a kwarg, which has a default value baked into expected_args
+        expected_tensors_meta = [
+            e.meta if isinstance(e, _RootArgPlaceholder) else e.buffer
+            for e in expected_args
+        ]
+        validate_tensors_metadata(
+            f"Stage {self.stage_index} forward inputs", expected_tensors_meta, args
+        )
+
+    def _validate_fwd_outputs(self, outputs: Tuple[torch.Tensor, ...]):
+        """Raises a RuntimeError if this stage produces an output of unexpected shape/dtype.
+        Most likely, this could be cause either by incorrect user specification of output shapes, or becuase
+        shape inference was done on the original model but then at runtime the model is wrapped with something like
+        mixed precision which changes output dtype.
+        """
+        expected_tensors_meta = self.get_outputs_meta()
+        validate_tensors_metadata(
+            f"Stage {self.stage_index} forward outputs", expected_tensors_meta, outputs
+        )
+
+
+class _PipelineStage(_PipelineStageBase):
+    def __init__(
+        self,
+        stage_module: torch.nn.Module,
+        stage_index: int,
+        pipe_info: PipeInfo,
+        device: torch.device,
+        group: Optional[dist.ProcessGroup] = None,
+    ):
+        """
+        Create a pipeline stage given a stage_module to be wrapped by this stage
+        and a `pipe_info` describing the stage relationship of the pipeline.
+
+        Args:
+            stage_module (torch.nn.Module): the module to be wrapped by this stage
+            stage_index (int): the index of this stage in the pipeline
+            pipe_info (PipeInfo): information about the pipeline, can be retrieved by `pipe.info()`
+            device (torch.device): the device to be used by this stage
+            group (Optional[dist.ProcessGroup]): the process group to be used by this stage
+        """
+        _PipelineStageBase.__init__(
+            self,
+            stage_module,
+            stage_index,
+            pipe_info.num_stages,
+            device,
+            group,
+        )
+        self.pipe_info = pipe_info
+
+        # Find stage nodes in graph
+        submod_nodes = [
+            node for node in pipe_info.graph.nodes if node.op == "call_module"
+        ]
+        if len(submod_nodes) != self.num_stages:
+            raise AssertionError(
+                f"Number of submodules in pipe graph {len(submod_nodes)} does not match number of stages {self.num_stages}"
+            )
+
+        # Find my stage node in graph
+        self.node = submod_nodes[self.stage_index]
+        self.name = self.node.name
+        logger.info(
+            "[%s] Creating PipelineStage %s for %s",
+            self.group_rank,
+            stage_index,
+            self.name,
+        )
+
+        # Create mapping from stage name to stage index
+        self.submod_to_stage_index: Dict[str, int] = {}
+        for i, node in enumerate(submod_nodes):
+            self.submod_to_stage_index.setdefault(node.name, i)
+
+        # Cast submodule to device
+        self._move_submod_to_device()
+
+    def _move_submod_to_device(self):
+        # Move submodule to indicated device if possible
+        # Note: we cannot move meta module to real devices because meta tensors
+        # do not support to() method. One needs to do an in-place tensor swap in
+        # that case.
+        has_meta_param = any(
+            isinstance(p, FakeTensor) or p.is_meta for p in self.submod.parameters()
+        )
+        if has_meta_param:
+            logger.debug("%s Found meta parameters!", self.log_prefix)
+        else:
+            self.submod.to(self.device)
+
+    def _prepare_forward_infra(self, num_microbatches: int):
+        """
+        Create send/recv infrastructures for activations (during forward)
+        """
+        # Flag per chunk to keep track of whether we have set `requires_grad`
+        # for receive buffers. Format: {chunk : Boolean}
+        for chunk in range(num_microbatches):
+            self.args_recv_info[chunk] = self._create_act_recv_info()
+            self.set_requires_grad[chunk] = False
+
+        # Send info during forward for each activation
+        self.act_send_info = self._create_act_send_info()
+
+    def get_stage_index_of_submod(
+        self,
+        submod_name: str,
+    ):
+        """
+        Given a submodule name, return the stage index of the submodule.
+        """
+        if submod_name not in self.submod_to_stage_index:
+            raise AssertionError(f"Stage id of {submod_name} not found")
+
+        return self.submod_to_stage_index[submod_name]
+
+    def _create_act_recv_info(
+        self,
+    ):
+        """
+        Create a tuple of `_RecvInfo` for inputs to the stage.
+        """
+
+        def create_recv_tensor(placeholder, arg_node):
+            """
+            Create a receive buffer for a placeholder.
+            """
+            example_value = placeholder.meta["val"]
+            if arg_node.op == "placeholder":
+                # This is a root level placeholder, thus an input argument to the entire model.
+                # We are likely at stage 0, hence no need to create a receive buffer.
+                return _RootArgPlaceholder(example_value)
+
+            # Figure out the source stage of this input
+            while arg_node.target is operator.getitem:
+                # If the input is a getitem, we need to go deeper
+                arg_node = arg_node.args[0]
+
+            assert (
+                arg_node.op == "call_module"
+            ), f"Expecting call_module, got {arg_node.op}"
+            src_stage = self.get_stage_index_of_submod(arg_node.name)
+
+            # Create a receive buffer for this placeholder
+            logger.debug(
+                "%s Creating recv buffer for input '%s' : %s, %s",
+                self.log_prefix,
+                placeholder.name,
+                example_value.shape,
+                example_value.dtype,
+            )
+            buffer = _make_tensor_from_meta(example_value, self.device)
+
+            return _RecvInfo(
+                arg_node.name,
+                src_stage,
+                buffer,
+            )
+
+        args_recv_info: List[InputInfo] = []
+        # Filter out placeholder nodes from `self.submod` (a GraphModule)
+        placeholders = filter(
+            lambda node: node.op == "placeholder", self.submod.graph.nodes
+        )
+        # `placeholders` are nodes internal to submod.
+        # `self.node.args` are dependency nodes in the outer graph.
+        # The two are 1:1.
+        for placeholder, arg_node in zip(placeholders, self.node.args):
+            # Create a receive buffer for this placeholder
+            recv_info = create_recv_tensor(placeholder, arg_node)
+            args_recv_info.append(recv_info)
+
+        logger.debug(
+            "%s Activation recv / args info: %s", self.log_prefix, args_recv_info
+        )
+        # `args` is a Tuple, hence we will return a Tuple[InputInfo]
+        return tuple(args_recv_info)
+
+    def find_dst_rank(
+        self,
+        user: fx.Node,
+    ) -> Optional[int]:
+        """
+        Find the destination rank of a `user` node.
+        If the `user` is not a submod, `None` may be returned.
+        """
+        if user.op == "call_module":
+            # User is a stage (`call_module`)
+            return self.get_stage_index_of_submod(user.name)
+        else:
+            # - If user.op == "output":
+            #   No need to send back to rank 0
+            # - If user.target is stage_backward:
+            #   No need to send assuming submod output is stored locally or
+            #   should be re-calucated in case of activation checkpointing
+            return None
+
+    def _create_act_send_info(self):
+        """
+        Create a dict of send info for activations.
+        The dict is of the form:
+        {
+            output_index: [dst_rank_0, dst_rank_1, ...],
+            ...
+        }
+        where the list of `dst_rank`s covers the case where an output value may
+        be consumed by multiple stages.
+        """
+        # Output index: List of receiver ranks
+        act_send_info: Dict[int, List] = {}
+        out_idx = 0
+
+        for user in self.node.users:
+            if user.target is operator.getitem:
+                # Recursively find the real destination
+                gi_dsts = act_send_info.setdefault(out_idx, [])
+                for gi_user in user.users:
+                    dst_rank = self.find_dst_rank(gi_user)
+                    if dst_rank is not None:
+                        gi_dsts.append(dst_rank)
+                # Next `getitem` will point to the next output index
+                out_idx += 1
+            else:
+                # In case of single output value, `out_idx` will not increase
+                dsts = act_send_info.setdefault(out_idx, [])
+                dst_rank = self.find_dst_rank(user)
+                if dst_rank is not None:
+                    dsts.append(dst_rank)
+
+        output_node = self._get_output_node()
+        output_vals: Tuple[torch.Tensor] = tuple(
+            v.meta["val"] for v in flatten_args(output_node.args)
+        )
+        self._configure_outputs_meta(output_vals)
+
+        logger.debug("%s Send info: %s", self.log_prefix, act_send_info)
+        return act_send_info
+
+    def _get_output_node(self):
+        output_nodes = [node for node in self.submod.graph.nodes if node.op == "output"]
+        assert len(output_nodes) == 1
+        output_node = output_nodes[0]
+        return output_node
+
+    def _create_grad_recv_info(
+        self,
+        act_send_info: Dict,
+    ) -> Tuple[_RecvInfo, ...]:
+        """
+        Create a tuple of `_RecvInfo` for gradients.
+        """
+        # Dict[output_index, _RecvInfo]
+        grad_recv_info: Dict[int, _RecvInfo] = {}
+        output_node = self._get_output_node()
+
+        # The output node may take multiple args, meaning the submod having multiple output values.
+        output_vals = flatten_args(output_node.args)
+
+        for out_idx, dst_list in act_send_info.items():
+            if not dst_list:
+                # No actual receiver for activation so no grad coming back
+                continue
+
+            output = output_vals[out_idx]
+            example_value = output.meta["val"]
+            logger.debug(
+                f"{self.log_prefix} Creating grad recv buffer for output {output.name} "  # noqa: G004
+                f": {example_value.shape}, {example_value.dtype}"
+            )
+
+            # TODO: otherwise needs grad accumulation
+            assert len(dst_list) == 1, "Backward of skip connections not supported yet"
+            grad_src = dst_list[0]
+            grad_recv_info[out_idx] = _RecvInfo(
+                f"{grad_src}",  # noqa: G004
+                grad_src,
+                _make_tensor_from_meta(example_value, self.device),
+            )
+
+        # Convert to tuple for convenience in get_ops and retrieve tensor
+        grad_recv_info_tuple = tuple(grad_recv_info.values())
+        logger.debug("%s Grad recv info: %s", self.log_prefix, grad_recv_info_tuple)
+        return grad_recv_info_tuple
+
+
+# A helper function to create a pipeline stage based on traced pipeline information
+def build_stage(
+    stage_module: torch.nn.Module,
+    stage_index: int,
+    pipe_info: PipeInfo,
+    device: torch.device,
+    group: Optional[dist.ProcessGroup] = None,
+) -> _PipelineStage:
+    """
+    Create a pipeline stage given a stage_module to be wrapped by this stage
+    and pipeline information.
+
+    Args:
+        stage_module (torch.nn.Module): the module to be wrapped by this stage
+        stage_index (int): the index of this stage in the pipeline
+        pipe_info (PipeInfo): information about the pipeline, can be retrieved by `pipe.info()`
+        device (torch.device): the device to be used by this stage
+        group (Optional[dist.ProcessGroup]): the process group to be used by this stage
+
+    Returns:
+        _PipelineStage: a pipeline stage that can run with `PipelineSchedules`.
+    """
+    return _PipelineStage(
+        stage_module,
+        stage_index,
+        pipe_info,
+        device,
+        group,
+    )
+
+
+# Manual PipelineStage functions and definition
+
+METADATA_TENSOR_LEN = 100
+PLACEHOLDER_VAL = -1
+
+
+def _create_empty_tensors(
+    tensor: Union[torch.Tensor, Iterable[torch.Tensor]], device: torch.device
+) -> List[torch.Tensor]:
+    """
+    Creates a list of empty tensors with the same properties (like shape and dtype) as the input tensor(s),
+    and places them on the specified device.
+    Args:
+        tensor (Union[torch.Tensor, List[torch.tensor]]): The input tensor(s).
+        device (torch.device): The device where the new tensors will be placed.
+    Returns:
+        List[torch.Tensor]: A list of empty tensors with the same properties as the input tensor(s).
+    """
+    if isinstance(tensor, torch.Tensor):
+        return [torch.empty_like(tensor, device=device)]
+    elif isinstance(tensor, (list, tuple)):
+        return [torch.empty_like(t, device=device) for t in tensor]
+    raise TypeError(f"Unsupported type {type(tensor)} cannot create empty tensors")
+
+
+def _create_metadata_tensor(
+    tensors: Optional[List[torch.Tensor]] = None,
+    device: Optional[torch.device] = torch.device("cpu"),
+) -> torch.Tensor:
+    """
+    Create a metadata tensor that can be sent over the wire.
+    This tensor contains the number of dimensions and the shape of each tensor being sent.
+
+    The data is of format [num_dims, dim1, dim2, ...].
+    If the tensor is None, a tensor of only placeholder values will be returned.
+
+    Inputs:
+        tensors: A list of tensors, the tensors will converted into its shape dimensions and
+                 these dimensions will be concatenated.
+        device: The device where the metadata tensor will be created.
+    If the tensor is None, then this tensor will contain PLACEHOLDER_VALs.
+
+    """
+    metadata_tensor = torch.full(
+        (METADATA_TENSOR_LEN,),
+        PLACEHOLDER_VAL,
+        dtype=torch.int32,
+        device=device,
+    )
+    if tensors:
+        # Create a list of tensors containing the number of dimensions and the shape of each tensor
+        data = [
+            # data is of format [num_dims, dim1, dim2, ...]
+            torch.tensor(
+                [len(tensor.shape)] + list(tensor.shape),
+                dtype=torch.int32,
+                device=device,
+            )
+            for tensor in tensors
+        ]
+        # Concatenate the data into a single tensor
+        data_tensor = torch.cat(data)
+        dt_shape = data_tensor.shape[0]
+        if dt_shape > METADATA_TENSOR_LEN:
+            raise ValueError(
+                f"Metadata tensor size ({dt_shape}) exceeds maximum allowed length ({METADATA_TENSOR_LEN})."
+            )
+        metadata_tensor[:dt_shape] = data_tensor
+    return metadata_tensor
+
+
+def _extract_metadata_from_tensor(tensor: torch.Tensor) -> List[torch.Size]:
+    """
+    Extract the number of dimensions and the shape of each tensor from a metadata tensor.
+    """
+    metadata: List[torch.Size] = []
+    i = 0
+    while i < len(tensor) and tensor[i] != PLACEHOLDER_VAL:
+        num_dims = int(tensor[i].item())
+        shape = torch.Size(tensor[i + 1 : i + 1 + num_dims].tolist())
+        metadata.append(shape)
+        i += num_dims + 1
+    return metadata
+
+
+def _get_stage_shapes(
+    stage_modules: List[nn.Module],
+    stage_ids: List[int],
+    num_stages: int,
+    rank: int,
+    world_size: int,
+    device: torch.device,
+    microbatch: Optional[Union[torch.Tensor, List[torch.Tensor]]] = None,
+):
+    """
+    Performs a dry run through all the pipeline stages (a rank can have multiple pipeline stages in the case of
+    virtual pipelining) and returns the shape of the inputs and outputs of the module.
+    Only the first stage must pass in a microbatch.
+
+    Each rank must call _get_stage_shapes or the program will hang.
+
+    Args:
+        stage_modules: The chunks assigned to this rank. Rhe length should be 1 for any
+                non-interleaved schedules and >1 for any interleaved schedules.
+        stage_ids: The id of the stages assigned to this rank.
+        num_stages: Total number of stages.
+        rank: Rank of the current process.
+        world_size: Number of processes participating in the pipeline.
+        device: Device where the tensors are allocated.
+
+    Returns a dictionary containing the following keys:
+        "inputs": Shape of the inputs to the module
+        "outputs": Shape of the outputs of the module
+    """
+
+    stage_id_to_shapes: Dict[int, Dict[str, list[torch.Size]]] = {}
+    for stage_id, model in zip(stage_ids, stage_modules):
+        input_shape_metadata_tensor = _create_metadata_tensor(device=device)
+        # TODO: Assumes prev_stage == rank - 1 and next_stage == rank + 1
+        prev_rank = (rank - 1) % world_size
+        next_rank = (rank + 1) % world_size
+        shapes = {}
+
+        # first stage doesn't receive anything and uses a microbatch
+        if stage_id == 0:
+            if microbatch is None:
+                raise RuntimeError("Microbatch is required for first stage")
+            example_fwd_inputs = microbatch
+            if isinstance(example_fwd_inputs, torch.Tensor):
+                example_fwd_inputs = [example_fwd_inputs]
+        else:
+            # other stages must receive shape information
+            # TODO: send/recv should take a group, rather than use the default group
+            dist.recv(input_shape_metadata_tensor, prev_rank)
+            metadata = _extract_metadata_from_tensor(input_shape_metadata_tensor)
+            example_fwd_inputs = [
+                torch.empty(shape_list, device=device) for shape_list in metadata
+            ]
+        shapes["inputs"] = [fwd_input.shape for fwd_input in example_fwd_inputs]
+
+        # perform forward
+        # TODO: if forward fails raise a more descriptive error explaining which stage failed
+        fwd_outputs = model(*example_fwd_inputs)
+        fwd_outputs = _create_empty_tensors(fwd_outputs, device)
+        shapes["outputs"] = [fwd_output.shape for fwd_output in fwd_outputs]
+
+        # send shape dims
+        if stage_id != num_stages - 1:
+            output_shape_metadata_tensor = _create_metadata_tensor(
+                fwd_outputs, device=device
+            )
+            dist.send(output_shape_metadata_tensor, next_rank)
+        stage_id_to_shapes[stage_id] = shapes
+    logger.info(stage_id_to_shapes)
+    return stage_id_to_shapes
+
+
+class PipelineStage(_PipelineStageBase):
+    """
+    A class representing a pipeline stage in a pipeline parallelism setup.
+    This class is created manually by providing a example input (and optionally output)
+    as opposed to the PipelineStage class that is outputed from pipeline().
+    This class extends the `_PipelineStageBase` class and can similarly be used
+    in `PipelineScheule`.
+
+    Args:
+        submodule (nn.Module): The PyTorch module wrapped by this stage.
+        stage_index (int): The ID of this stage.
+        num_stages (int): The total number of stages.
+        device (torch.device): The device where this stage is located.
+        input_args (Union[torch.Tensor, Tuple[torch.tensor]], optional): The input arguments for the submodule.
+        output_args (Union[torch.Tensor, Tuple[torch.tensor]], optional): The output arguments for the submodule.
+        group (dist.ProcessGroup, optional): The process group for distributed training. If None, default group.
+        dw_builder: TODO clean up comments
+    """
+
+    def __init__(
+        self,
+        submodule: nn.Module,
+        stage_index: int,
+        num_stages: int,
+        device: torch.device,
+        input_args: Union[torch.Tensor, Tuple[torch.Tensor, ...]],
+        output_args: Optional[Union[torch.Tensor, Tuple[torch.Tensor, ...]]] = None,
+        group: Optional[dist.ProcessGroup] = None,
+        dw_builder: Optional[Callable[[], Callable[..., None]]] = None,
+    ):
+        super().__init__(submodule, stage_index, num_stages, device, group, dw_builder)
+        self.submod.to(self.device)
+        # When we materialize the model partition on cuda, we call reset_parameters() if it is available
+        self.inputs: List[torch.Tensor] = []
+        self.outputs: List[torch.Tensor] = []
+
+        self.inputs = _create_empty_tensors(input_args, device)
+
+        if output_args is None:
+            logger.info("output_args not provided, performing forward using input_args")
+            self.outputs = self.submod(*self.inputs)
+            # create buffers for the output so that the data is in the correct
+            # shape in order to use in p2p op (send)
+            self.outputs = _create_empty_tensors(self.outputs, device)
+        else:
+            self.outputs = _create_empty_tensors(output_args, device)
+
+        self._configure_outputs_meta(tuple(self.outputs))
+
+        # these are the buffers used in backwards send/recv, they are allocated later
+        self.outputs_grad: List[torch.Tensor] = []
+
+        def stage_global_rank(peer_rank):
+            return (
+                peer_rank
+                if self.group is None
+                else dist.get_global_rank(self.group, peer_rank)
+            )
+
+        self.prev_stage = stage_global_rank((self.group_rank - 1) % self.group_size)
+        self.next_stage = stage_global_rank((self.group_rank + 1) % self.group_size)
+
+        logger.debug(
+            f"finished pipeline stage init, {self.stage_index=}, {self.is_first=}, "  # noqa: G004
+            f"{self.is_last=}, {self.num_stages=}, "
+            f"inputs: {[inp.shape for inp in self.inputs]}, "
+            f"output: {[output.shape for output in self.outputs]}"
+        )
+
+    def _prepare_forward_infra(self, num_microbatches: int) -> None:
+        # Receive info during forward
+        # TODO: create args_recv_info lazily? (same needed for PipelineStage)
+        for chunk_id in range(num_microbatches):
+            self.set_requires_grad[chunk_id] = False
+            if not self.is_first:
+                # We assume that we always receive from stage - 1
+                recv_infos = tuple(
+                    [
+                        _RecvInfo(
+                            f"recv_for_{self.stage_index}_from_{self.stage_index - 1}",
+                            self.stage_index - 1,
+                            _make_tensor_from_meta(inp, self.device),
+                        )
+                        for inp in self.inputs
+                    ]
+                )
+
+                self.args_recv_info[chunk_id] = recv_infos
+            else:
+                self.args_recv_info[chunk_id] = tuple(
+                    [_RootArgPlaceholder(i) for i in self.inputs]
+                )
+
+        # Send info during forward for each activation
+        # only need the rank that is being sent to
+        self.act_send_info: Dict[int, List] = {}
+        for idx in range(len(self.outputs)):
+            # We assume we always send to stage + 1
+            if not self.is_last:
+                self.act_send_info[idx] = [self.stage_index + 1]
+            else:
+                self.act_send_info[idx] = []
+
+    def _create_grad_recv_info(
+        self,
+        act_send_info: Dict,
+    ) -> Tuple[_RecvInfo, ...]:
+        grad_recv_info: Tuple[_RecvInfo, ...] = ()
+        if not self.is_last:
+            # Receiving gradients from multiple sources is not supported
+            # hence we only take the first destination
+            grad_recv_info = tuple(
+                [
+                    _RecvInfo(
+                        f"recv_grad_for_{self.stage_index}_from_{dst_list[0]}",
+                        dst_list[0],
+                        _make_tensor_from_meta(self.outputs[idx], self.device),
+                    )
+                    for idx, dst_list in act_send_info.items()
+                ]
+            )
+        return grad_recv_info
+
+    def _init_p2p_neighbors(self):
+        """
+        Set up p2p communitors between previous and next stages
+        by sending a dummy tensor.
+
+        If this is used, must be called for all pipeline stages.
+        """
+        ops = []
+        recv_tensor = torch.zeros(1, device="cuda")
+        send_tensor = torch.ones(1, device="cuda")
+        # forward
+        if not self.is_first:
+            ops.append(dist.P2POp(dist.irecv, recv_tensor, self.prev_stage, self.group))
+        if not self.is_last:
+            ops.append(dist.P2POp(dist.isend, send_tensor, self.next_stage, self.group))
+
+        # backward
+        if not self.is_first:
+            ops.append(dist.P2POp(dist.isend, send_tensor, self.prev_stage, self.group))
+        if not self.is_last:
+            ops.append(dist.P2POp(dist.irecv, recv_tensor, self.next_stage, self.group))
+
+        return True
+
+
+def _validate_stage_shapes(pipeline_stages: List[PipelineStage]):
+    """
+    Check that the buffer shapes match between stages was expected by performing an all_gather between
+    all stages.
+    """
+    if len(pipeline_stages) == 0:
+        raise ValueError("No pipeline stages provided.")
+
+    virtual_pipeline_size = len(pipeline_stages)
+    all_inputs = []
+    all_outputs = []
+    world_size = pipeline_stages[0].group_size
+    num_stages = pipeline_stages[0].num_stages
+
+    # perform all gathers between all stages
+    for virtual_id, stage in enumerate(pipeline_stages):
+        world_size = stage.group_size
+        stage_id: int = stage.stage_index
+        rank = stage.group_rank
+        # check that world_size and num_stages are consistent across all stages
+        if stage.group_size != world_size:
+            raise ValueError(
+                f"Stage id {stage_id} has world size ({stage.group_size}) \
+                which does not match world size ({world_size}) of other stages."
+            )
+        if stage.num_stages != num_stages:
+            raise ValueError(
+                f"Stage id {stage_id} has num stages ({stage.num_stages}) \
+                which does not match num stages ({num_stages}) of other stages."
+            )
+
+        pg_rank = dist.get_rank(stage.group)
+        if rank != pg_rank:
+            raise ValueError(
+                f"Rank {rank} is not equal to process group rank {pg_rank}"
+            )
+
+        if (num_stages := stage.num_stages) % world_size != 0:
+            raise ValueError(
+                f"Number of stages ({num_stages}) must be a multiple of the world_size ({world_size})"
+            )
+
+        # all gather each ranks inputs
+        tensor_list = [
+            _create_metadata_tensor(device=stage.device)
+            for _ in range(stage.group_size)
+        ]
+        expected_inputs = stage.inputs
+        stage_input = _create_metadata_tensor(expected_inputs, device=stage.device)
+        dist.all_gather(tensor_list, stage_input)
+        stage_input_shapes = [
+            _extract_metadata_from_tensor(tensor) for tensor in tensor_list
+        ]
+
+        # all gather each ranks outputs
+        tensor_list = [
+            _create_metadata_tensor(device=stage.device)
+            for _ in range(stage.group_size)
+        ]
+        expected_outputs = stage.outputs
+        stage_output = _create_metadata_tensor(expected_outputs, device=stage.device)
+        dist.all_gather(tensor_list, stage_output)
+        stage_output_shapes = [
+            _extract_metadata_from_tensor(tensor) for tensor in tensor_list
+        ]
+
+        logger.debug(
+            f"Rank: {pg_rank}"  # noqa: G004
+            f"Stage id: {stage_id}"
+            f"Stage num stages: {stage.num_stages}"
+            f"Stage rank: {rank}"
+            f"Stage world size: {world_size}"
+            f"Stage {virtual_id * world_size}-{(virtual_id + 1) * world_size - 1} input shapes: {stage_input_shapes}"  # noqa: G003
+            f"Stage {virtual_id * world_size}-{(virtual_id + 1) * world_size - 1} output shapes: {stage_output_shapes}"  # noqa: G003
+        )
+
+        all_inputs.extend(stage_input_shapes)
+        all_outputs.extend(stage_output_shapes)
+
+        # log only rank 0's view, they will all be equivalent
+        if pg_rank == 0:
+            logger.info(
+                "all stage inputs: %s \n all stage outputs: %s", all_inputs, all_outputs
+            )
+
+    # Check if the output for stage 0 matches the input at stage 1, and so forth
+    for i in range(virtual_pipeline_size * world_size - 1):
+        if (out := all_outputs[i]) != (inp := all_inputs[i + 1]):
+            raise ValueError(
+                f"Stage_id {i} output shape {out} at does not match stage_id {i + 1} input shape {inp}."
+            )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c6608a2a773f3be7d0166d8f36bb4ce237bed7b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__init__.py
@@ -0,0 +1,249 @@
+# mypy: allow-untyped-defs
+import logging
+import os
+import threading
+import warnings
+from datetime import timedelta
+from typing import Generator, Tuple
+from urllib.parse import urlparse
+
+import torch
+import torch.distributed as dist
+
+
+__all__ = ["is_available"]
+
+
+logger = logging.getLogger(__name__)
+
+
+_init_counter = 0
+_init_counter_lock = threading.Lock()
+
+
+def is_available() -> bool:
+    return hasattr(torch._C, "_rpc_init")
+
+
+if is_available() and not torch._C._rpc_init():
+    raise RuntimeError("Failed to initialize torch.distributed.rpc")
+
+
+if is_available():
+    import numbers
+
+    import torch.distributed.autograd as dist_autograd
+    from torch._C._distributed_c10d import Store
+    from torch._C._distributed_rpc import (  # noqa: F401
+        _cleanup_python_rpc_handler,
+        _DEFAULT_INIT_METHOD,
+        _DEFAULT_NUM_WORKER_THREADS,
+        _DEFAULT_RPC_TIMEOUT_SEC,
+        _delete_all_user_and_unforked_owner_rrefs,
+        _destroy_rref_context,
+        _disable_jit_rref_pickle,
+        _disable_server_process_global_profiler,
+        _enable_jit_rref_pickle,
+        _enable_server_process_global_profiler,
+        _get_current_rpc_agent,
+        _invoke_remote_builtin,
+        _invoke_remote_python_udf,
+        _invoke_remote_torchscript,
+        _invoke_rpc_builtin,
+        _invoke_rpc_python_udf,
+        _invoke_rpc_torchscript,
+        _is_current_rpc_agent_set,
+        _reset_current_rpc_agent,
+        _rref_context_get_debug_info,
+        _set_and_start_rpc_agent,
+        _set_profiler_node_id,
+        _set_rpc_timeout,
+        _TensorPipeRpcBackendOptionsBase,
+        _UNSET_RPC_TIMEOUT,
+        enable_gil_profiling,
+        get_rpc_timeout,
+        PyRRef,
+        RemoteProfilerManager,
+        RpcAgent,
+        RpcBackendOptions,
+        TensorPipeAgent,
+        WorkerInfo,
+    )
+
+    from . import api, backend_registry, functions
+    from .api import *  # noqa: F401,F403
+    from .backend_registry import BackendType
+    from .options import TensorPipeRpcBackendOptions  # noqa: F401
+    from .server_process_global_profiler import _server_process_global_profile
+
+    rendezvous_iterator: Generator[Tuple[Store, int, int], None, None]
+
+    __all__ += ["init_rpc", "BackendType", "TensorPipeRpcBackendOptions"]
+    __all__ = __all__ + api.__all__ + backend_registry.__all__  # noqa: PLE0605
+
+    def init_rpc(
+        name,
+        backend=None,
+        rank=-1,
+        world_size=None,
+        rpc_backend_options=None,
+    ):
+        r"""
+        Initializes RPC primitives such as the local RPC agent
+        and distributed autograd, which immediately makes the current
+        process ready to send and receive RPCs.
+
+        Args:
+            name (str): a globally unique name of this node. (e.g.,
+                ``Trainer3``, ``ParameterServer2``, ``Master``, ``Worker1``)
+                Name can only contain number, alphabet, underscore, colon,
+                and/or dash, and must be shorter than 128 characters.
+            backend (BackendType, optional): The type of RPC backend
+                implementation. Supported values is
+                ``BackendType.TENSORPIPE`` (the default).
+                See :ref:`rpc-backends` for more information.
+            rank (int): a globally unique id/rank of this node.
+            world_size (int): The number of workers in the group.
+            rpc_backend_options (RpcBackendOptions, optional): The options
+                passed to the RpcAgent constructor. It must be an agent-specific
+                subclass of :class:`~torch.distributed.rpc.RpcBackendOptions`
+                and contains agent-specific initialization configurations. By
+                default, for all agents, it sets the default timeout to 60
+                seconds and performs the rendezvous with an underlying process
+                group initialized using ``init_method = "env://"``,
+                meaning that environment variables ``MASTER_ADDR`` and
+                ``MASTER_PORT`` need to be set properly. See
+                :ref:`rpc-backends` for more information and find which options
+                are available.
+        """
+        torch._C._log_api_usage_once("torch.distributed.init_rpc")
+        if backend is not None and not isinstance(
+            backend, backend_registry.BackendType
+        ):
+            raise TypeError("Argument backend must be a member of BackendType")
+
+        if rpc_backend_options is not None and not isinstance(
+            rpc_backend_options, RpcBackendOptions
+        ):
+            raise TypeError(
+                "Argument rpc_backend_options must be an instance of RpcBackendOptions"
+            )
+
+        # Try to detect the backend from the options
+        if backend is None and rpc_backend_options is not None:
+            for candidate_backend in BackendType:
+                if isinstance(
+                    rpc_backend_options,
+                    type(
+                        backend_registry.construct_rpc_backend_options(
+                            candidate_backend
+                        )
+                    ),
+                ):
+                    backend = candidate_backend
+                    break
+            else:
+                raise TypeError(
+                    f"Could not infer backend for options {rpc_backend_options}"
+                )
+            # Ignore type error because mypy doesn't handle dynamically generated type objects (#4865)
+            if backend != BackendType.TENSORPIPE:  # type: ignore[attr-defined]
+                logger.warning(
+                    "RPC was initialized with no explicit backend but with options "  # type: ignore[attr-defined]
+                    "corresponding to %(backend)s, hence that backend will be used "
+                    "instead of the default BackendType.TENSORPIPE. To silence this "
+                    "warning pass `backend=%(backend)s` explicitly.",
+                    {"backend": backend},
+                )
+
+        if backend is None:
+            backend = BackendType.TENSORPIPE  # type: ignore[attr-defined]
+
+        if rpc_backend_options is None:
+            # default construct a set of RPC backend options.
+            rpc_backend_options = backend_registry.construct_rpc_backend_options(
+                backend
+            )
+
+        # Create store, performs rendezvous for static RPC group.
+        if not world_size:
+            # If world_size is not set in construction and also not set in environment variables
+            # The store will be created for the dynamic group setting
+            store = dist._create_store_from_options(rpc_backend_options, rank)
+        else:
+            # This rendezvous state sometimes is destroyed before all processes
+            # finishing handshaking. To avoid that issue, we make it global to
+            # keep it alive.
+            global rendezvous_iterator
+            rendezvous_iterator = dist.rendezvous(
+                rpc_backend_options.init_method, rank=rank, world_size=world_size
+            )
+            store, _, _ = next(rendezvous_iterator)
+        # Use same timeout as RPC.
+        store.set_timeout(timedelta(seconds=rpc_backend_options.rpc_timeout))
+
+        # Use a PrefixStore to distinguish multiple invocations.
+        with _init_counter_lock:
+            global _init_counter
+            store = dist.PrefixStore(str(f"rpc_prefix_{_init_counter}"), store)
+            _init_counter += 1
+
+        # Initialize autograd before RPC since _init_rpc_backend guarantees all
+        # processes sync via the store. If we initialize autograd after RPC,
+        # there could be a race where some nodes might have initialized autograd
+        # and others might not have. As a result, a node calling
+        # torch.distributed.autograd.backward() would run into errors since
+        # other nodes might not have been initialized.
+        dist_autograd._init(rank)
+
+        _set_profiler_node_id(rank)
+        # Initialize RPC.
+        _init_rpc_backend(backend, store, name, rank, world_size, rpc_backend_options)
+
+    def _validate_rpc_args(backend, store, name, rank, world_size, rpc_backend_options):
+        type_mapping = {
+            backend: backend_registry.BackendType,
+            store: dist.Store,
+            name: str,
+            rank: numbers.Integral,
+            # world_size can be None for a dynamic group
+            world_size: (numbers.Integral, type(None)),
+            rpc_backend_options: RpcBackendOptions,
+        }
+        for arg, arg_type in type_mapping.items():
+            if not isinstance(arg, arg_type):  # type: ignore[arg-type]
+                raise RuntimeError(
+                    f"Argument {arg} must be of type {arg_type} but got type {type(arg)}"
+                )
+
+    def _init_rpc_backend(
+        backend=BackendType.TENSORPIPE,  # type: ignore[attr-defined]
+        store=None,
+        name=None,
+        rank=-1,
+        world_size=None,
+        rpc_backend_options=None,
+    ):
+        _validate_rpc_args(backend, store, name, rank, world_size, rpc_backend_options)
+
+        if _is_current_rpc_agent_set():
+            raise RuntimeError("RPC is already initialized")
+
+        # Initialize RPC.
+        rpc_agent = backend_registry.init_backend(
+            backend,
+            store=store,
+            name=name,
+            rank=rank,
+            world_size=world_size,
+            rpc_backend_options=rpc_backend_options,
+        )
+
+        api._init_rpc_states(rpc_agent)
+
+    @api._require_initialized
+    def _get_debug_info():
+        info = _rref_context_get_debug_info()
+        info.update(api._get_current_rpc_agent().get_debug_info())
+        info.update(dist_autograd._get_debug_info())
+        return info
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8fc4caa2db3844bad2773ed40b72e264876252eb
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1cfe4847f166b36bfa5f815167e0a6eea525b102
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/api.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/api.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c1bbd4c69c8d5637d454d4335e22ebbd183952d5
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/api.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/backend_registry.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/backend_registry.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0feefc2d1fde7ffcdd65dd3335d94b7225befdde
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/backend_registry.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/constants.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/constants.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cddd2dfd4d95d897f7cc0e3b31dfbd43e75cb539
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/constants.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/functions.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/functions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..493d43ae9ed98cd998b2f0aa6ab106add5159791
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/functions.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/internal.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/internal.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..59be489dbe0311544db6d2d411c8b752433b3842
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/internal.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/options.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/options.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..69d37250b1cdfb1ee866ca7c358ef65b177efea4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/options.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/rref_proxy.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/rref_proxy.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8bf9db07520fbf20d70e949e37a4a0591bb4b18e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/rref_proxy.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/server_process_global_profiler.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/server_process_global_profiler.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8bbec86025f6038f3ee87970cb59e130ff0011d3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/__pycache__/server_process_global_profiler.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/_testing/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/_testing/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ac1c02f4cee4c38c896cacd245b9ededf9a8a29
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/_testing/__init__.py
@@ -0,0 +1,20 @@
+# mypy: allow-untyped-defs
+
+import torch
+
+
+def is_available():
+    return hasattr(torch._C, "_faulty_agent_init")
+
+
+if is_available() and not torch._C._faulty_agent_init():
+    raise RuntimeError("Failed to initialize torch.distributed.rpc._testing")
+
+if is_available():
+    # Registers FAULTY_TENSORPIPE RPC backend.
+    from torch._C._distributed_rpc_testing import (
+        FaultyTensorPipeAgent,
+        FaultyTensorPipeRpcBackendOptions,
+    )
+
+    from . import faulty_agent_backend_registry
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/_testing/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/_testing/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..33c486099fc46f9543a4911f6a41a4d0aa97b891
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/_testing/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/_testing/__pycache__/faulty_agent_backend_registry.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/_testing/__pycache__/faulty_agent_backend_registry.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..36fe5d4a21b2cd7a448bcd878d6b4b1704f461ee
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/_testing/__pycache__/faulty_agent_backend_registry.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/_testing/faulty_agent_backend_registry.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/_testing/faulty_agent_backend_registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..d04882e16e79a94f74ddc1350e94f547ef625611
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/_testing/faulty_agent_backend_registry.py
@@ -0,0 +1,62 @@
+#!/usr/bin/env python3
+# mypy: allow-untyped-defs
+
+import torch.distributed as dist
+import torch.distributed.rpc as rpc
+
+
+def _faulty_tensorpipe_construct_rpc_backend_options_handler(
+    rpc_timeout,
+    init_method,
+    num_worker_threads,
+    messages_to_fail,
+    messages_to_delay,
+    num_fail_sends,
+    **kwargs,
+):
+    from . import FaultyTensorPipeRpcBackendOptions
+
+    return FaultyTensorPipeRpcBackendOptions(
+        num_worker_threads=num_worker_threads,
+        rpc_timeout=rpc_timeout,
+        init_method=init_method,
+        messages_to_fail=messages_to_fail,
+        messages_to_delay=messages_to_delay,
+        num_fail_sends=num_fail_sends,
+    )
+
+
+def _faulty_tensorpipe_init_backend_handler(
+    store, name, rank, world_size, rpc_backend_options
+):
+    from torch.distributed.rpc import api
+
+    from . import FaultyTensorPipeAgent, FaultyTensorPipeRpcBackendOptions
+
+    if not isinstance(store, dist.Store):
+        raise TypeError(f"`store` must be a c10d::Store. {store}")
+
+    if not isinstance(rpc_backend_options, FaultyTensorPipeRpcBackendOptions):
+        raise TypeError(
+            f"`rpc_backend_options` must be a `FaultyTensorPipeRpcBackendOptions`. {rpc_backend_options}"
+        )
+
+    agent = FaultyTensorPipeAgent(
+        store,
+        name,
+        rank,
+        world_size,
+        rpc_backend_options,
+        {},  # reverse_device_map
+        [],  # devices
+    )
+    api._init_rpc_states(agent)
+
+    return agent
+
+
+rpc.backend_registry.register_backend(
+    "FAULTY_TENSORPIPE",
+    _faulty_tensorpipe_construct_rpc_backend_options_handler,
+    _faulty_tensorpipe_init_backend_handler,
+)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..8925bc662b5f97555d273d4c641ae5930f50d789
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/_utils.py
@@ -0,0 +1,47 @@
+# mypy: allow-untyped-defs
+import logging
+from contextlib import contextmanager
+from typing import cast
+
+from . import api, TensorPipeAgent
+
+
+logger = logging.getLogger(__name__)
+
+
+@contextmanager
+def _group_membership_management(store, name, is_join):
+    token_key = "RpcGroupManagementToken"
+    join_or_leave = "join" if is_join else "leave"
+    my_token = f"Token_for_{name}_{join_or_leave}"
+    while True:
+        # Retrieve token from store to signal start of rank join/leave critical section
+        returned = store.compare_set(token_key, "", my_token).decode()
+        if returned == my_token:
+            # Yield to the function this context manager wraps
+            yield
+            # Finished, now exit and release token
+            # Update from store to signal end of rank join/leave critical section
+            store.set(token_key, "")
+            # Other will wait for this token to be set before they execute
+            store.set(my_token, "Done")
+            break
+        else:
+            # Store will wait for the token to be released
+            try:
+                store.wait([returned])
+            except RuntimeError:
+                logger.error(
+                    "Group membership token %s timed out waiting for %s to be released.",
+                    my_token,
+                    returned,
+                )
+                raise
+
+
+def _update_group_membership(worker_info, my_devices, reverse_device_map, is_join):
+    agent = cast(TensorPipeAgent, api._get_current_rpc_agent())
+    ret = agent._update_group_membership(
+        worker_info, my_devices, reverse_device_map, is_join
+    )
+    return ret
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/api.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..fbe77e465740aee9ebdaaebdb2ce4e2d4c03b6ef
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/api.py
@@ -0,0 +1,965 @@
+# mypy: allow-untyped-decorators
+# mypy: allow-untyped-defs
+
+import collections
+import contextlib
+import functools
+import inspect
+import logging
+import threading
+from typing import Any, Dict, Generic, Set, TYPE_CHECKING, TypeVar
+
+import torch
+from torch._C._distributed_rpc import (
+    _cleanup_python_rpc_handler,
+    _delete_all_user_and_unforked_owner_rrefs,
+    _destroy_rref_context,
+    _get_current_rpc_agent,
+    _invoke_remote_builtin,
+    _invoke_remote_python_udf,
+    _invoke_remote_torchscript,
+    _invoke_rpc_builtin,
+    _invoke_rpc_python_udf,
+    _invoke_rpc_torchscript,
+    _is_current_rpc_agent_set,
+    _reset_current_rpc_agent,
+    _set_and_start_rpc_agent,
+    get_rpc_timeout,
+    PyRRef,
+    RemoteProfilerManager,
+    TensorPipeAgent,
+    WorkerInfo,
+)
+from torch.futures import Future
+
+from ._utils import _group_membership_management, _update_group_membership
+from .constants import DEFAULT_SHUTDOWN_TIMEOUT, UNSET_RPC_TIMEOUT
+from .internal import (
+    _build_rpc_profiling_key,
+    _internal_rpc_pickler,
+    PythonUDF,
+    RPCExecMode,
+)
+
+
+__all__ = [
+    "shutdown",
+    "get_worker_info",
+    "remote",
+    "rpc_sync",
+    "rpc_async",
+    "RRef",
+    "AllGatherStates",
+    "method_factory",
+    "new_method",
+]
+
+
+logger = logging.getLogger(__name__)
+
+# NB: Ignoring RRef leaks during shutdown. Without this, applications have to
+# make sure there is no references to any RRef in the application code and
+# Python GC has done its job to delete those RRefs. This is could result in bad
+# debugging experiences especially when for large applications. Therefore, by
+# default, we are going to ignore RRef leaks during shutdown. This is usually
+# fine as shutdown means applications have done training and no longer care
+# about states.
+#
+# To enable RRef leak checking, set this _ignore_rref_leak to False
+_ignore_rref_leak = True
+_default_pickler = _internal_rpc_pickler
+
+
+@contextlib.contextmanager
+def _use_rpc_pickler(rpc_pickler):
+    r"""
+    rpc_pickler: (.internal._InternalRPCPickler) Overrides the default RPC pickler
+    """
+    global _default_pickler
+    _default_pickler = rpc_pickler
+    try:
+        yield
+    finally:
+        _default_pickler = _internal_rpc_pickler
+
+
+def _require_initialized(func):
+    @functools.wraps(func)
+    def wrapper(*args, **kwargs):
+        if not _is_current_rpc_agent_set():
+            raise RuntimeError(
+                "RPC has not been initialized. Call "
+                "torch.distributed.rpc.init_rpc first."
+            )
+        return func(*args, **kwargs)
+
+    return wrapper
+
+
+class AllGatherStates:
+    def __init__(self):
+        # Each `gathered_objects` is an empty dict at beginning.
+        # The leader worker is elected as the first worker in a sorted worker
+        # name list. Whenever there is a worker entering `_all_gather()`, it
+        # runs `_gather_to_leader()` on the leader to add its own name and
+        # data obj to this dict. The leader also adds itself's name to the dict
+        # on calling `_all_gather()`.
+        # Once `set(gathered_objects.keys()) == _ALL_WORKER_NAMES`, the leader
+        # will broadcast the gathered dict to all follower workers and set their
+        # `gathered_objects` field and the `proceed_signal` field.
+        self.gathered_objects = {}
+        # All workers wait on this signal until it receives all gathered
+        # objects.
+        self.proceed_signal = threading.Event()
+
+
+# States used by `def _all_gather()`.
+# `_ALL_WORKER_NAMES` is initialized on initializing RPC layer.
+_ALL_WORKER_NAMES: Set[Any] = set()
+_all_gather_dict_lock = threading.RLock()
+_all_gather_sequence_id: Dict[str, int] = {}
+_all_gather_sequence_id_to_states: collections.defaultdict = collections.defaultdict(
+    AllGatherStates
+)
+
+
+def _init_rpc_states(agent):
+    worker_infos = agent.get_worker_infos()
+    global _ALL_WORKER_NAMES
+    _ALL_WORKER_NAMES = {worker_info.name for worker_info in worker_infos}
+
+    # NB: backend implementation might have already set the rpc_agent.
+    if not _is_current_rpc_agent_set():
+        _set_and_start_rpc_agent(agent)
+
+
+def _gather_to_leader(sequence_id, worker_name, obj, worker_names=None):
+    with _all_gather_dict_lock:
+        if not worker_names:
+            worker_names = _ALL_WORKER_NAMES
+            assert (
+                worker_name in worker_names
+            ), f"{worker_name} is not expected by leader."
+        states = _all_gather_sequence_id_to_states[sequence_id]
+        assert (
+            worker_name not in states.gathered_objects
+        ), f"{worker_name} reported intent sequence id {sequence_id} twice. "
+        states.gathered_objects[worker_name] = obj
+        if worker_names == set(states.gathered_objects.keys()):
+            states.proceed_signal.set()
+
+
+def _broadcast_to_followers(sequence_id, objects_map):
+    with _all_gather_dict_lock:
+        states = _all_gather_sequence_id_to_states[sequence_id]
+
+    assert (
+        not states.proceed_signal.is_set()
+    ), f"Termination signal sequence id {sequence_id} got set twice."
+    states.gathered_objects = objects_map
+    states.proceed_signal.set()
+
+
+_thread_local_var = threading.local()
+
+
+@contextlib.contextmanager
+def _wait_all():
+    r"""
+    A context manager that collects all futures returned by ``rpc_async`` and
+    waits them on the context manager's exit; relieving the user of needing
+    to explicitly call wait.
+
+
+    Example::
+        >>> # xdoctest: +SKIP("distributed")
+        >>> # On worker 0:
+        >>> import torch
+        >>> import torch.distributed.rpc as rpc
+        >>> rpc.init_rpc("worker0", rank=0, world_size=2)
+        >>> with rpc._wait_all():
+        >>>    fut_1 = rpc.rpc_async(dst, torch.add, (torch.ones(2, 2), 1))
+        >>>    fut_2 = rpc.rpc_async(dst, torch.add, (torch.ones(2, 2), 1))
+        >>> #fut_1 and fut_2 are waited on
+    """
+    _thread_local_var.future_list = []
+    try:
+        yield
+    finally:
+        try:
+            torch.futures.wait_all(_thread_local_var.future_list)
+        finally:
+            del _thread_local_var.future_list
+
+
+@_require_initialized
+def _all_gather(obj, worker_names=None, timeout: float = UNSET_RPC_TIMEOUT):
+    r"""
+    This is similar to torch.distributed.all_gather(), but is using RPC. It
+    picks the worker with the smallest name (alphabetic order) as the leader.
+    Then all followers send their data ``obj`` to the leader. After the leader
+    has received all, it will broadcast the results back to all followers. This
+    function blocks until all workers have received the gathered results.
+    """
+    if not worker_names:
+        assert (
+            _ALL_WORKER_NAMES is not None
+        ), "`_ALL_WORKER_NAMES` is not initialized for `def _all_gather`."
+        worker_names = _ALL_WORKER_NAMES
+    leader_name = min(worker_names)
+
+    self_name = _get_current_rpc_agent().get_worker_info().name
+
+    with _all_gather_dict_lock:
+        concat_names = "".join(sorted(worker_names))
+        sequence_num = _all_gather_sequence_id.get(concat_names, 0)
+        _all_gather_sequence_id[concat_names] = sequence_num + 1
+        sequence_id = concat_names + str(sequence_num)
+
+    is_leader = leader_name == self_name
+
+    if timeout == UNSET_RPC_TIMEOUT:
+        # Timeout is specified by agent for RPC calls
+        rpc_timeout = get_rpc_timeout()
+        # No timeout for signal
+        signal_timeout = None
+    elif timeout == DEFAULT_SHUTDOWN_TIMEOUT:
+        # No timeout for RPC
+        rpc_timeout = timeout
+        # No timeout for signal
+        signal_timeout = None
+    else:
+        # Signal and RPC timeout use the same timeout
+        signal_timeout = rpc_timeout = timeout
+
+    # Phase 1: Followers send it's object to the leader
+    if is_leader:
+        _gather_to_leader(sequence_id, self_name, obj, worker_names)
+    else:
+        rpc_sync(
+            leader_name,
+            _gather_to_leader,
+            args=(sequence_id, self_name, obj, worker_names),
+            timeout=rpc_timeout,
+        )
+
+    with _all_gather_dict_lock:
+        states = _all_gather_sequence_id_to_states[sequence_id]
+
+    # Timeout is either set by function parameter or None (which is indefinite)
+    states.proceed_signal.wait(timeout=signal_timeout)
+
+    # Phase 2: Leader broadcast gathered results to all followers
+    # Leader's signal is the first to be unblocked, after receiving all
+    # followers' data objects.
+    if is_leader:
+        worker_name_to_response_future_dict = {}
+        for follower_name in worker_names - {leader_name}:
+            fut = rpc_async(
+                follower_name,
+                _broadcast_to_followers,
+                args=(sequence_id, states.gathered_objects),
+                timeout=rpc_timeout,
+            )
+            worker_name_to_response_future_dict[follower_name] = fut
+
+        errors = []
+        for follower_name, fut in worker_name_to_response_future_dict.items():
+            try:
+                fut.wait()
+            except RuntimeError as ex:
+                errors.append((follower_name, ex))
+
+        if errors:
+            raise RuntimeError(
+                f"Followers {[e[0] for e in errors]} timed out in _all_gather "
+                f"after {rpc_timeout:.2f} seconds. The first exception is {errors[0][1]}"
+            )
+
+    # Clean up for the states using the sequence_id
+    with _all_gather_dict_lock:
+        states = _all_gather_sequence_id_to_states.pop(sequence_id)
+    return states.gathered_objects
+
+
+@_require_initialized
+def _barrier(worker_names):
+    r"""
+    Synchronizes local and remote RPC processes.
+
+    This will block until all local and remote RPC processes specified under worker_names
+    reach this method to wait for all outstanding work to complete.
+
+    Args:
+        worker_names (List[str]): The set of workers to synchronize.
+
+    """
+    try:
+        _all_gather(None, set(worker_names))
+    except RuntimeError as ex:
+        logger.error("Failed to complete barrier, got error %s", ex)
+
+
+@_require_initialized
+def _wait_all_workers(timeout=DEFAULT_SHUTDOWN_TIMEOUT):
+    r"""
+    Block until all local and remote RPC processes reach this method and wait
+    for all outstanding work to complete. Every RPC process must call this
+    method before exit to perform a graceful shutdown. This should be used to
+    terminate the RPC framework, and there is no guarantee that the RPC
+    framework will work after this method returns.
+    """
+    try:
+        _all_gather(None, timeout=timeout)
+    except RuntimeError as ex:
+        logger.error(
+            "Failed to respond to 'Shutdown Proceed' in time, got error %s", ex
+        )
+        raise ex
+
+
+@_require_initialized
+def shutdown(graceful=True, timeout=DEFAULT_SHUTDOWN_TIMEOUT):
+    r"""
+    Perform a shutdown of the RPC agent, and then destroy the RPC agent. This
+    stops the local agent from accepting outstanding requests, and shuts
+    down the RPC framework by terminating all RPC threads. If ``graceful=True``,
+    this will block until all local and remote RPC processes reach this method
+    and wait for all outstanding work to complete. Otherwise, if
+    ``graceful=False``, this is a local shutdown, and it does not wait for other
+    RPC processes to reach this method.
+
+    .. warning::
+        For :class:`~torch.futures.Future` objects returned by
+        :meth:`~torch.distributed.rpc.rpc_async`, ``future.wait()`` should not
+        be called after ``shutdown()``.
+
+    Args:
+        graceful (bool): Whether to do a graceful shutdown or not. If True,
+                         this will 1) wait until there is no pending system
+                         messages for ``UserRRefs`` and delete them; 2) block
+                         until all local and remote RPC processes have reached
+                         this method and wait for all outstanding work to
+                         complete.
+
+    Example::
+        Make sure that ``MASTER_ADDR`` and ``MASTER_PORT`` are set properly
+        on both workers. Refer to :meth:`~torch.distributed.init_process_group`
+        API for more details. For example,
+
+        export MASTER_ADDR=localhost
+        export MASTER_PORT=5678
+
+        Then run the following code in two different processes:
+
+        >>> # xdoctest: +SKIP
+        >>> # On worker 0:
+        >>> import torch
+        >>> import torch.distributed.rpc as rpc
+        >>> rpc.init_rpc("worker0", rank=0, world_size=2)
+        >>> # do some work
+        >>> result = rpc.rpc_sync("worker1", torch.add, args=(torch.ones(1), 1))
+        >>> # ready to shutdown
+        >>> rpc.shutdown()
+
+        >>> # On worker 1:
+        >>> import torch.distributed.rpc as rpc
+        >>> rpc.init_rpc("worker1", rank=1, world_size=2)
+        >>> # wait for worker 0 to finish work, and then shutdown.
+        >>> rpc.shutdown()
+    """
+    if graceful:
+        try:
+            agent = _get_current_rpc_agent()
+            if not isinstance(agent, TensorPipeAgent) or agent.is_static_group:
+                _wait_all_workers(timeout)
+                _delete_all_user_and_unforked_owner_rrefs()
+                agent.join(shutdown=True, timeout=timeout)
+            else:
+                # This is a dynamic group so we need to grab the token for the operation
+                my_worker_info = agent.get_worker_info()
+                my_name = my_worker_info.name
+                with _group_membership_management(agent.store, my_name, False):
+                    all_worker_infos = agent.get_worker_infos()
+                    for worker in all_worker_infos:
+                        if worker.name != my_name:
+                            rpc_sync(
+                                worker.name,
+                                _update_group_membership,
+                                args=(my_worker_info, [], {}, False),
+                            )
+                    agent.join(shutdown=True, timeout=timeout)
+        finally:
+            # In case of errors, continue to complete the local shutdown.
+            _finalize_shutdown()
+    else:
+        _finalize_shutdown()
+
+
+def _finalize_shutdown():
+    try:
+        # This raises a `TORCH_CHECK()` exception on RRef leak detected.
+        _destroy_rref_context(_ignore_rref_leak)
+    finally:
+        _get_current_rpc_agent().shutdown()
+        # clean up python rpc handler in shutdown(), see comments in
+        # PythonRpcHandler::cleanup(), call it in python API because the
+        # cleanup() function has python dependency, it assumes python
+        # interpreter exists.
+        # No matter if RRef leak exception is raised, this clean-up code
+        # must run to avoid destruction segfault in Python 3.5.
+        #
+        # future.wait() should not be called after shutdown().
+        # pythonRpcHandler is cleaned up in shutdown(), after
+        # shutdown(), python objects returned from rpc python call can not be
+        # resolved.
+        _cleanup_python_rpc_handler()
+        _reset_current_rpc_agent()
+
+
+@_require_initialized
+def get_worker_info(worker_name=None):
+    r"""
+    Get :class:`~torch.distributed.rpc.WorkerInfo` of a given worker name.
+    Use this :class:`~torch.distributed.rpc.WorkerInfo` to avoid passing an
+    expensive string on every invocation.
+
+    Args:
+        worker_name (str): the string name of a worker. If ``None``, return the
+                           the id of the current worker. (default ``None``)
+
+    Returns:
+        :class:`~torch.distributed.rpc.WorkerInfo` instance for the given
+        ``worker_name`` or :class:`~torch.distributed.rpc.WorkerInfo` of the
+        current worker if ``worker_name`` is ``None``.
+    """
+    if worker_name is not None:
+        return _get_current_rpc_agent().get_worker_info(worker_name)
+    else:
+        return _get_current_rpc_agent().get_worker_info()
+
+
+def _to_worker_info(to):
+    if isinstance(to, WorkerInfo):
+        return to
+    elif isinstance(to, (str, int)):
+        return get_worker_info(to)
+    else:
+        raise ValueError(f"Cannot get WorkerInfo from name {to}")
+
+
+def _rref_typeof_on_owner(rref, blocking: bool = True):
+    rref_type = type(rref.local_value())
+    if blocking:
+        return rref_type
+    else:
+        # Wrap result into a completed Future. This is so that if blocking=`False`
+        # is specified, we return a future regardless of if this call is on user
+        # or owner.
+        future = Future[type]()
+        future.set_result(rref_type)
+        return future
+
+
+def _rref_typeof_on_user(
+    rref, timeout: float = UNSET_RPC_TIMEOUT, blocking: bool = True
+):
+    fut = rpc_async(rref.owner(), _rref_typeof_on_owner, args=(rref,), timeout=timeout)
+    if blocking:
+        return fut.wait()
+    else:
+        return fut
+
+
+T = TypeVar("T")
+GenericWithOneTypeVar = Generic[T]
+
+
+if TYPE_CHECKING:
+
+    class RRef(PyRRef[T], Generic[T]):
+        pass
+
+else:
+    try:
+        # Combine the implementation class and the type class.
+        class RRef(PyRRef, Generic[T]):
+            pass
+
+    except TypeError:
+        # TypeError: metaclass conflict: the metaclass of a derived class
+        # must be a (non-strict) subclass of the metaclasses of all its bases
+        # Mypy doesn't understand __class__ (mypy bug #4177)
+        class RRefMeta(PyRRef.__class__, GenericWithOneTypeVar.__class__):  # type: ignore[name-defined, misc, valid-type]
+            pass
+
+        # Combine the implementation class and the type class.
+        # Types for classes expecting a certain generic parameter (mypy bug #7791)
+        class RRef(PyRRef, GenericWithOneTypeVar, metaclass=RRefMeta):  # type: ignore[misc, no-redef, valid-type]
+            pass
+
+
+# Install docstrings from `PyRRef` to `RRef`.
+#
+# This is for the fact that pybind11 generates the parameter
+# `self` as type `rpc.PyRRef`, so a `:inherited-members:`
+# under `.. autoclass:: RRef` does not work.
+# we have to do the following process to replace `rpc.PyRRef` with `rpc.RRef`.
+#
+def method_factory(method_name, docstring):
+    def method(self, *args, **kwargs):
+        return getattr(super(RRef, self), method_name)(*args, **kwargs)
+
+    if method.__doc__:
+        method.__doc__ = docstring
+    return method
+
+
+for method_name, method in inspect.getmembers(PyRRef):
+    # Ignore magic methods, except "__str__".
+    if method_name.startswith("_") and method_name != "__str__":
+        continue
+
+    # Get pybind11 generated docstring.
+    # It's like,
+    """
+    to_here(self: torch.distributed.rpc.PyRRef, timeout: float=-1.0) -> object
+
+        Blocking call that copies the value of the RRef from the owner
+        to the local node and returns it. If the current node is the
+        owner, returns a reference to the local value.
+    """
+    docstring = getattr(method, "__doc__", None)
+    assert docstring is not None, "RRef user-facing methods should all have docstrings."
+
+    # Do surgery on pybind11 generated docstrings.
+    docstring = docstring.replace(
+        "torch.distributed.rpc.PyRRef", "torch.distributed.rpc.RRef"
+    )
+
+    # Attach user-facing RRef method with modified docstring.
+    new_method = method_factory(method_name, docstring)
+    setattr(RRef, method_name, new_method)
+
+
+@_require_initialized
+def remote(to, func, args=None, kwargs=None, timeout=UNSET_RPC_TIMEOUT):
+    r"""
+    Make a remote call to run ``func`` on worker ``to`` and return an
+    :class:`~torch.distributed.rpc.RRef` to the result value immediately.
+    Worker ``to`` will be the owner of the returned
+    :class:`~torch.distributed.rpc.RRef`, and the worker calling ``remote`` is
+    a user. The owner manages the global reference count of its
+    :class:`~torch.distributed.rpc.RRef`, and the owner
+    :class:`~torch.distributed.rpc.RRef` is only destructed when globally there
+    are no living references to it.
+
+    Args:
+        to (str or WorkerInfo or int): name/rank/``WorkerInfo`` of the destination worker.
+        func (Callable): a callable function, such as Python callables, builtin
+                         operators (e.g. :meth:`~torch.add`) and annotated
+                         TorchScript functions.
+        args (tuple): the argument tuple for the ``func`` invocation.
+        kwargs (dict): is a dictionary of keyword arguments for the ``func``
+                       invocation.
+
+        timeout (float, optional): timeout in seconds for this remote call. If the
+                                   creation of this
+                                   :class:`~torch.distributed.rpc.RRef` on worker
+                                   ``to`` is not successfully processed on this
+                                   worker within this timeout, then the next time
+                                   there is an attempt to use the RRef (such as
+                                   ``to_here()``), a timeout will be raised
+                                   indicating this failure. A value of 0 indicates
+                                   an infinite timeout, i.e. a timeout error will
+                                   never be raised. If not provided, the default
+                                   value set during initialization or with
+                                   ``_set_rpc_timeout`` is used.
+
+    Returns:
+        A user :class:`~torch.distributed.rpc.RRef` instance to the result
+        value. Use the blocking API :meth:`torch.distributed.rpc.RRef.to_here`
+        to retrieve the result value locally.
+
+    .. warning ::
+        The ``remote`` API does not copy storages of argument tensors until
+        sending them over the wire, which could be done by a different thread
+        depending on the RPC backend type. The caller should make sure that the
+        contents of those tensors stay intact until the returned RRef is
+        confirmed by the owner, which can be checked using the
+        :meth:`torch.distributed.rpc.RRef.confirmed_by_owner` API.
+
+    .. warning ::
+        Errors such as timeouts for the ``remote`` API are handled on a
+        best-effort basis. This means that when remote calls initiated by
+        ``remote`` fail, such as with a timeout error, we take a best-effort
+        approach to error handling. This means that errors are handled and set
+        on the resulting RRef on an asynchronous basis. If the RRef has not been
+        used by the application before this handling (such as ``to_here`` or
+        fork call), then future uses of the ``RRef`` will appropriately raise
+        errors. However, it is possible that the user application will use the
+        ``RRef`` before the errors are handled. In this case, errors may not be
+        raised as they have not yet been handled.
+
+    Example::
+
+        Make sure that ``MASTER_ADDR`` and ``MASTER_PORT`` are set properly
+        on both workers. Refer to :meth:`~torch.distributed.init_process_group`
+        API for more details. For example,
+
+        export MASTER_ADDR=localhost
+        export MASTER_PORT=5678
+
+        Then run the following code in two different processes:
+
+        >>> # xdoctest: +SKIP
+        >>> # On worker 0:
+        >>> import torch
+        >>> import torch.distributed.rpc as rpc
+        >>> rpc.init_rpc("worker0", rank=0, world_size=2)
+        >>> rref1 = rpc.remote("worker1", torch.add, args=(torch.ones(2), 3))
+        >>> rref2 = rpc.remote("worker1", torch.add, args=(torch.ones(2), 1))
+        >>> x = rref1.to_here() + rref2.to_here()
+        >>> rpc.shutdown()
+
+        >>> # On worker 1:
+        >>> import torch.distributed.rpc as rpc
+        >>> rpc.init_rpc("worker1", rank=1, world_size=2)
+        >>> rpc.shutdown()
+
+        Below is an example of running a TorchScript function using RPC.
+
+        >>> # On both workers:
+        >>> @torch.jit.script
+        >>> def my_script_add(tensor: torch.Tensor, scalar: int):
+        >>>    return torch.add(tensor, scalar)
+
+        >>> # On worker 0:
+        >>> import torch.distributed.rpc as rpc
+        >>> rpc.init_rpc("worker0", rank=0, world_size=2)
+        >>> rref = rpc.remote("worker1", my_script_add, args=(torch.ones(2), 3))
+        >>> rref.to_here()
+        >>> rpc.shutdown()
+
+        >>> # On worker 1:
+        >>> import torch.distributed.rpc as rpc
+        >>> rpc.init_rpc("worker1", rank=1, world_size=2)
+        >>> rpc.shutdown()
+    """
+    torch._C._log_api_usage_once("torch.distributed.rpc_remote")
+    qualified_name = torch.jit._builtins._find_builtin(func)
+    dst_worker_info = _to_worker_info(to)
+    should_profile = _get_should_profile()
+
+    ctx_manager = _enable_rpc_profiler(
+        should_profile, qualified_name, func, RPCExecMode.REMOTE, dst_worker_info
+    )
+
+    with ctx_manager as rf:
+        args = args if args else ()
+        kwargs = kwargs if kwargs else {}
+
+        is_async_exec = hasattr(func, "_wrapped_async_rpc_function")
+
+        if is_async_exec:
+            wrapped = func._wrapped_async_rpc_function
+            if isinstance(wrapped, torch.jit.ScriptFunction):
+                func = wrapped
+
+        if qualified_name is not None:
+            rref = _invoke_remote_builtin(
+                dst_worker_info, qualified_name, timeout, *args, **kwargs
+            )
+        elif isinstance(func, torch.jit.ScriptFunction):
+            rref = _invoke_remote_torchscript(
+                dst_worker_info.name,
+                torch._jit_internal._qualified_name(func),
+                timeout,
+                is_async_exec,
+                *args,
+                **kwargs,
+            )
+        else:
+            (pickled_python_udf, tensors) = _default_pickler.serialize(
+                PythonUDF(func, args, kwargs)
+            )
+            rref = _invoke_remote_python_udf(
+                dst_worker_info, pickled_python_udf, tensors, timeout, is_async_exec
+            )
+        # attach profiling information
+        if should_profile:
+            assert torch.autograd._profiler_enabled()
+            assert rf is not None
+            fut = rf._call_end_callbacks_on_future(rref._get_future())
+            rref._set_profiling_future(fut)
+
+    return rref
+
+
+def _invoke_rpc(
+    to, func, rpc_type, args=None, kwargs=None, rpc_timeout: float = UNSET_RPC_TIMEOUT
+):
+    if not callable(func):
+        raise TypeError("function should be callable.")
+
+    qualified_name = torch.jit._builtins._find_builtin(func)
+    dst_worker_info = _to_worker_info(to)
+
+    should_profile = _get_should_profile()
+
+    ctx_manager = _enable_rpc_profiler(
+        should_profile, qualified_name, func, rpc_type, dst_worker_info
+    )
+
+    with ctx_manager as rf:
+        args = args if args else ()
+        kwargs = kwargs if kwargs else {}
+
+        is_async_exec = hasattr(func, "_wrapped_async_rpc_function")
+
+        if is_async_exec:
+            wrapped = func._wrapped_async_rpc_function
+            if isinstance(wrapped, torch.jit.ScriptFunction):
+                func = wrapped
+
+        if qualified_name is not None:
+            fut = _invoke_rpc_builtin(
+                dst_worker_info, qualified_name, rpc_timeout, *args, **kwargs
+            )
+        elif isinstance(func, torch.jit.ScriptFunction):
+            fut = _invoke_rpc_torchscript(
+                dst_worker_info.name,
+                torch._jit_internal._qualified_name(func),
+                args,
+                kwargs,
+                rpc_timeout,
+                is_async_exec,
+            )
+        else:
+            (pickled_python_udf, tensors) = _default_pickler.serialize(
+                PythonUDF(func, args, kwargs)
+            )
+            fut = _invoke_rpc_python_udf(
+                dst_worker_info, pickled_python_udf, tensors, rpc_timeout, is_async_exec
+            )
+        if should_profile:
+            assert torch.autograd._profiler_enabled()
+            assert rf is not None
+            # Schedule profiling callbacks to run when the future completes.
+            # This returns a future that is completed when the original future
+            # completes and the profiling callbacks have been completed as well,
+            # to guarantee that fut.wait() completes the profiling. This new
+            # future will contain the same value as the original future.
+            fut = rf._call_end_callbacks_on_future(fut)
+    return fut
+
+
+@_require_initialized
+def rpc_sync(to, func, args=None, kwargs=None, timeout: float = UNSET_RPC_TIMEOUT):
+    r"""
+    Make a blocking RPC call to run function ``func`` on worker ``to``. RPC
+    messages are sent and received in parallel to execution of Python code. This
+    method is thread-safe.
+
+    Args:
+        to (str or WorkerInfo or int): name/rank/``WorkerInfo`` of the destination worker.
+        func (Callable): a callable function, such as Python callables, builtin
+                         operators (e.g. :meth:`~torch.add`) and annotated
+                         TorchScript functions.
+        args (tuple): the argument tuple for the ``func`` invocation.
+        kwargs (dict): is a dictionary of keyword arguments for the ``func``
+                       invocation.
+        timeout (float, optional): timeout in seconds to use for this RPC. If
+                                   the RPC does not complete in this amount of
+                                   time, an exception indicating it has
+                                   timed out will be raised. A value of 0
+                                   indicates an infinite timeout, i.e. a timeout
+                                   error will never be raised. If not provided,
+                                   the default value set during initialization
+                                   or with ``_set_rpc_timeout`` is used.
+
+    Returns:
+        Returns the result of running ``func`` with ``args`` and ``kwargs``.
+
+    Example::
+        Make sure that ``MASTER_ADDR`` and ``MASTER_PORT`` are set properly
+        on both workers. Refer to :meth:`~torch.distributed.init_process_group`
+        API for more details. For example,
+
+        export MASTER_ADDR=localhost
+        export MASTER_PORT=5678
+
+        Then run the following code in two different processes:
+
+        >>> # xdoctest: +SKIP
+        >>> # On worker 0:
+        >>> import torch
+        >>> import torch.distributed.rpc as rpc
+        >>> rpc.init_rpc("worker0", rank=0, world_size=2)
+        >>> ret = rpc.rpc_sync("worker1", torch.add, args=(torch.ones(2), 3))
+        >>> rpc.shutdown()
+
+        >>> # On worker 1:
+        >>> import torch.distributed.rpc as rpc
+        >>> rpc.init_rpc("worker1", rank=1, world_size=2)
+        >>> rpc.shutdown()
+
+        Below is an example of running a TorchScript function using RPC.
+
+        >>> # On both workers:
+        >>> @torch.jit.script
+        >>> def my_script_add(tensor: torch.Tensor, scalar: int):
+        >>>    return torch.add(tensor, scalar)
+
+        >>> # On worker 0:
+        >>> import torch.distributed.rpc as rpc
+        >>> rpc.init_rpc("worker0", rank=0, world_size=2)
+        >>> ret = rpc.rpc_sync("worker1", my_script_add, args=(torch.ones(2), 3))
+        >>> rpc.shutdown()
+
+        >>> # On worker 1:
+        >>> import torch.distributed.rpc as rpc
+        >>> rpc.init_rpc("worker1", rank=1, world_size=2)
+        >>> rpc.shutdown()
+
+    """
+    torch._C._log_api_usage_once("torch.distributed.rpc_sync")
+    fut = _invoke_rpc(to, func, RPCExecMode.SYNC, args, kwargs, timeout)
+    return fut.wait()
+
+
+@_require_initialized
+def rpc_async(to, func, args=None, kwargs=None, timeout=UNSET_RPC_TIMEOUT):
+    r"""
+    Make a non-blocking RPC call to run function ``func`` on worker ``to``. RPC
+    messages are sent and received in parallel to execution of Python code. This
+    method is thread-safe. This method will immediately return a
+    :class:`~torch.futures.Future` that can be awaited on.
+
+    Args:
+        to (str or WorkerInfo or int): name/rank/``WorkerInfo`` of the destination worker.
+        func (Callable): a callable function, such as Python callables, builtin
+                         operators (e.g. :meth:`~torch.add`) and annotated
+                         TorchScript functions.
+        args (tuple): the argument tuple for the ``func`` invocation.
+        kwargs (dict): is a dictionary of keyword arguments for the ``func``
+                       invocation.
+        timeout (float, optional): timeout in seconds to use for this RPC. If
+                                   the RPC does not complete in this amount of
+                                   time, an exception indicating it has
+                                   timed out will be raised. A value of 0
+                                   indicates an infinite timeout, i.e. a timeout
+                                   error will never be raised. If not provided,
+                                   the default value set during initialization
+                                   or with ``_set_rpc_timeout`` is used.
+
+
+    Returns:
+        Returns a :class:`~torch.futures.Future` object that can be waited
+        on. When completed, the return value of ``func`` on ``args`` and
+        ``kwargs`` can be retrieved from the :class:`~torch.futures.Future`
+        object.
+
+    .. warning ::
+        Using GPU tensors as arguments or return values of ``func`` is not
+        supported since we don't support sending GPU tensors over the wire. You
+        need to explicitly copy GPU tensors to CPU before using them as
+        arguments or return values of ``func``.
+
+    .. warning ::
+        The ``rpc_async`` API does not copy storages of argument tensors until
+        sending them over the wire, which could be done by a different thread
+        depending on the RPC backend type. The caller should make sure that the
+        contents of those tensors stay intact until the returned
+        :class:`~torch.futures.Future` completes.
+
+    Example::
+        Make sure that ``MASTER_ADDR`` and ``MASTER_PORT`` are set properly
+        on both workers. Refer to :meth:`~torch.distributed.init_process_group`
+        API for more details. For example,
+
+        export MASTER_ADDR=localhost
+        export MASTER_PORT=5678
+
+        Then run the following code in two different processes:
+
+        >>> # xdoctest: +SKIP
+        >>> # On worker 0:
+        >>> import torch
+        >>> import torch.distributed.rpc as rpc
+        >>> rpc.init_rpc("worker0", rank=0, world_size=2)
+        >>> fut1 = rpc.rpc_async("worker1", torch.add, args=(torch.ones(2), 3))
+        >>> fut2 = rpc.rpc_async("worker1", min, args=(1, 2))
+        >>> result = fut1.wait() + fut2.wait()
+        >>> rpc.shutdown()
+
+        >>> # On worker 1:
+        >>> import torch.distributed.rpc as rpc
+        >>> rpc.init_rpc("worker1", rank=1, world_size=2)
+        >>> rpc.shutdown()
+
+        Below is an example of running a TorchScript function using RPC.
+
+        >>> # On both workers:
+        >>> @torch.jit.script
+        >>> def my_script_add(tensor: torch.Tensor, scalar: int):
+        >>>    return torch.add(tensor, scalar)
+
+        >>> # On worker 0:
+        >>> import torch.distributed.rpc as rpc
+        >>> rpc.init_rpc("worker0", rank=0, world_size=2)
+        >>> fut = rpc.rpc_async("worker1", my_script_add, args=(torch.ones(2), 3))
+        >>> ret = fut.wait()
+        >>> rpc.shutdown()
+
+        >>> # On worker 1:
+        >>> import torch.distributed.rpc as rpc
+        >>> rpc.init_rpc("worker1", rank=1, world_size=2)
+        >>> rpc.shutdown()
+    """
+    torch._C._log_api_usage_once("torch.distributed.rpc_async")
+    fut = _invoke_rpc(to, func, RPCExecMode.ASYNC, args, kwargs, timeout)
+    if hasattr(_thread_local_var, "future_list"):
+        _thread_local_var.future_list.append(fut)
+    return fut
+
+
+def _get_should_profile():
+    # Legacy profiler should be enabled. RPC profiling is not supported with
+    # Kineto profiler.
+    ActiveProfilerType = torch._C._profiler.ActiveProfilerType
+    return (
+        torch.autograd._profiler_enabled()
+        and torch._C._autograd._profiler_type()
+        == ActiveProfilerType.LEGACY  # type: ignore[attr-defined]
+    )
+
+
+def _enable_rpc_profiler(
+    should_profile, qualified_name, func, rpc_type, dst_worker_info
+):
+    ctx_manager = contextlib.nullcontext()
+
+    if should_profile:
+        # Create appropriate string representation based on type of func
+        # (builtin, script, python)
+        if qualified_name is None:
+            func_name = (
+                torch._jit_internal._qualified_name(func)
+                if isinstance(func, torch.jit.ScriptFunction)
+                else func.__qualname__
+            )
+        else:
+            func_name = qualified_name
+        # Build RPC profiling key.
+        rpc_profiling_key = _build_rpc_profiling_key(
+            rpc_type,
+            func_name,
+            get_worker_info().name,
+            dst_worker_info.name,
+        )
+        RemoteProfilerManager.set_current_profiling_key(rpc_profiling_key)
+        # Mypy doesn't support re-def of a variable not in the same block (#1174)
+        ctx_manager = torch.autograd.profiler.record_function(rpc_profiling_key)  # type: ignore[assignment]
+
+    return ctx_manager
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/backend_registry.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/backend_registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8feba8a52d33712f563aebe659f1b89770f7722
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/backend_registry.py
@@ -0,0 +1,432 @@
+# mypy: allow-untyped-defs
+
+
+import collections
+import enum
+from typing import cast, Dict, List, Set, Tuple
+
+import torch
+import torch.distributed as dist
+
+from . import api, constants as rpc_constants
+from ._utils import _group_membership_management, _update_group_membership
+
+
+__all__ = [
+    "backend_registered",
+    "register_backend",
+    "construct_rpc_backend_options",
+    "init_backend",
+    "BackendValue",
+    "BackendType",
+]
+
+BackendValue = collections.namedtuple(
+    "BackendValue", ["construct_rpc_backend_options_handler", "init_backend_handler"]
+)
+
+
+def _backend_type_repr(self):
+    return "BackendType." + self.name
+
+
+_backend_type_doc = """
+    An enum class of available backends.
+
+    PyTorch ships with a builtin ``BackendType.TENSORPIPE`` backend.
+    Additional ones can be registered using the
+    :func:`~torch.distributed.rpc.backend_registry.register_backend` function.
+"""
+
+# Create an enum type, `BackendType`, with empty members.
+# Can't handle Function Enum API (mypy bug #9079)
+BackendType = enum.Enum(value="BackendType", names={})  # type: ignore[misc]
+# Unable to assign a function a method (mypy bug #2427)
+BackendType.__repr__ = _backend_type_repr  # type: ignore[assignment]
+
+if BackendType.__doc__:
+    BackendType.__doc__ = _backend_type_doc
+
+
+def backend_registered(backend_name):
+    """
+    Checks if backend_name is registered as an RPC backend.
+
+    Args:
+        backend_name (str): string to identify the RPC backend.
+    Returns:
+        True if the backend has been registered with ``register_backend``, else
+        False.
+    """
+    return backend_name in BackendType.__members__.keys()
+
+
+def register_backend(
+    backend_name, construct_rpc_backend_options_handler, init_backend_handler
+):
+    """Registers a new RPC backend.
+
+    Args:
+        backend_name (str): backend string to identify the handler.
+        construct_rpc_backend_options_handler (function):
+            Handler that is invoked when
+            rpc_backend.construct_rpc_backend_options(**dict) is called.
+        init_backend_handler (function): Handler that is invoked when the
+            `_init_rpc_backend()` function is called with a backend.
+             This returns the agent.
+    """
+    global BackendType
+    if backend_registered(backend_name):
+        raise RuntimeError(f"RPC backend {backend_name}: already registered")
+    # Create a new enum type, `BackendType`, with extended members.
+    existing_enum_dict = {member.name: member.value for member in BackendType}
+    extended_enum_dict = dict(
+        {
+            backend_name: BackendValue(
+                construct_rpc_backend_options_handler=construct_rpc_backend_options_handler,
+                init_backend_handler=init_backend_handler,
+            )
+        },
+        **existing_enum_dict,
+    )
+    # Can't handle Function Enum API (mypy bug #9079)
+    BackendType = enum.Enum(value="BackendType", names=extended_enum_dict)  # type: ignore[misc]
+    # Unable to assign a function a method (mypy bug #2427)
+    BackendType.__repr__ = _backend_type_repr  # type: ignore[assignment]
+    if BackendType.__doc__:
+        BackendType.__doc__ = _backend_type_doc
+    return BackendType[backend_name]
+
+
+def construct_rpc_backend_options(
+    backend,
+    rpc_timeout=rpc_constants.DEFAULT_RPC_TIMEOUT_SEC,
+    init_method=rpc_constants.DEFAULT_INIT_METHOD,
+    **kwargs,
+):
+    return backend.value.construct_rpc_backend_options_handler(
+        rpc_timeout, init_method, **kwargs
+    )
+
+
+def init_backend(backend, *args, **kwargs):
+    return backend.value.init_backend_handler(*args, **kwargs)
+
+
+def _init_process_group(store, rank, world_size):
+    # Initialize ProcessGroup.
+    process_group_timeout = rpc_constants.DEFAULT_PROCESS_GROUP_TIMEOUT
+
+    # We're using a bunch of private APIs here since `new_group` requires the
+    # default group to be initialized.
+    group = dist.ProcessGroupGloo(store, rank, world_size, process_group_timeout)
+
+    assert group is not None, "Failed to initialize default ProcessGroup."
+
+    if (rank != -1) and (rank != group.rank()):
+        raise RuntimeError(f"rank argument {rank} doesn't match pg rank {group.rank()}")
+    if (world_size != -1) and (world_size != group.size()):
+        raise RuntimeError(
+            f"world_size argument {world_size} doesn't match pg size {group.size()}"
+        )
+    return group
+
+
+def _tensorpipe_construct_rpc_backend_options_handler(
+    rpc_timeout,
+    init_method,
+    num_worker_threads=rpc_constants.DEFAULT_NUM_WORKER_THREADS,
+    _transports=None,
+    _channels=None,
+    **kwargs,
+):
+    from . import TensorPipeRpcBackendOptions
+
+    return TensorPipeRpcBackendOptions(
+        rpc_timeout=rpc_timeout,
+        init_method=init_method,
+        num_worker_threads=num_worker_threads,
+        _transports=_transports,
+        _channels=_channels,
+    )
+
+
+def _tensorpipe_validate_devices(devices, device_count):
+    return all(
+        d.type == "cpu" or (d.type == "cuda" and 0 <= d.index < device_count)
+        for d in devices
+    )
+
+
+# detect if any worker has invalid device_map configurations, and return
+# reverse device maps
+def _tensorpipe_exchange_and_check_all_device_maps(
+    my_name, my_device_count, my_device_maps, my_devices, group
+):
+    gathered: List[
+        Tuple[str, int, Dict[str, Dict[torch.device, torch.device]], List[torch.device]]
+    ] = [("", 0, {}, []) for _ in range(group.size())]
+    dist.all_gather_object(
+        gathered, (my_name, my_device_count, my_device_maps, my_devices), group
+    )
+    all_names = [name for name, _, _, _ in gathered]
+    all_device_counts = {name: count for name, count, _, _ in gathered}
+    all_device_maps = {name: map_ for name, _, map_, _ in gathered}
+    all_devices = {name: devices for name, _, _, devices in gathered}
+
+    _validate_device_maps(all_names, all_device_counts, all_device_maps, all_devices)
+
+    # passed all checked, construct reverse mapping and get list of devices handled by this agent
+    reverse_device_maps = _create_reverse_mapping(my_name, all_names, all_device_maps)
+    my_devices = _create_device_list(my_devices, my_device_maps, reverse_device_maps)
+    return reverse_device_maps, my_devices
+
+
+def _validate_device_maps(
+    all_names, all_device_counts, all_device_maps, all_devices, is_static_group=True
+):
+    for node in all_names:
+        devices = all_devices[node]
+        if len(set(devices)) != len(devices):
+            raise ValueError(
+                f"Node {node} has duplicated devices\n" f"devices = {devices}"
+            )
+        if not _tensorpipe_validate_devices(devices, all_device_counts[node]):
+            raise ValueError(
+                f"Node {node} has devices with invalid indices\n"
+                f"devices = {devices}\n"
+                f"device count = {all_device_counts[node]}"
+            )
+
+    for source_node in all_names:
+        # For dynamic group (non-static) do not check the target node name since it may not have joined yet
+        if is_static_group and not set(all_device_maps[source_node].keys()).issubset(
+            all_names
+        ):
+            raise ValueError(
+                f"Node {source_node} has invalid target node names in its device maps\n"
+                f"device maps = {all_device_maps[source_node].keys()}\n"
+                f"node names = {all_names}"
+            )
+        for target_node, map_ in all_device_maps[source_node].items():
+            if len(set(map_.values())) != len(map_):
+                raise ValueError(
+                    f"Node {source_node} has duplicated target devices "
+                    f"in its device map for {target_node}\n"
+                    f"device map = {map_}"
+                )
+            if all_devices[source_node]:
+                if not set(map_.keys()).issubset(all_devices[source_node]):
+                    raise ValueError(
+                        f"Node {source_node} has unexpected source devices "
+                        f"in its device map for {target_node}\n"
+                        f"device map = {map_}\n"
+                        f"devices = {all_devices[source_node]}"
+                    )
+            elif not _tensorpipe_validate_devices(
+                map_.keys(), all_device_counts[source_node]
+            ):
+                raise ValueError(
+                    f"Node {source_node} has source devices with invalid indices "
+                    f"in its device map for {target_node}\n"
+                    f"device map = {map_}\n"
+                    f"device count = {all_device_counts[source_node]}"
+                )
+            if all_devices.get(target_node, []):
+                if not set(map_.values()).issubset(all_devices[target_node]):
+                    raise ValueError(
+                        f"Node {source_node} has unexpected target devices "
+                        f"in its device map for {target_node}\n"
+                        f"device map = {map_}\n"
+                        f"devices = {all_devices[target_node]}"
+                    )
+            elif target_node in all_device_counts and not _tensorpipe_validate_devices(
+                map_.values(), all_device_counts[target_node]
+            ):
+                raise ValueError(
+                    f"Node {source_node} has target devices with invalid indices "
+                    f"in its device map for {target_node}\n"
+                    f"device map = {map_}\n"
+                    f"device count = {all_device_counts[target_node]}"
+                )
+
+
+def _create_device_list(my_devices, my_device_maps, reverse_device_maps):
+    if not my_devices:
+        devices_set: Set[torch.device] = set()
+        for map_ in my_device_maps.values():
+            devices_set.update(map_.keys())
+        for map_ in reverse_device_maps.values():
+            devices_set.update(map_.keys())
+        devices_set.discard(torch.device("cpu"))
+        my_devices = list(devices_set)
+    my_devices = sorted(my_devices, key=lambda d: d.index)
+    return my_devices
+
+
+def _create_reverse_mapping(my_name, all_names, all_device_maps):
+    reverse_device_maps: Dict[str, Dict[torch.device, torch.device]] = {}
+    for node in all_names:
+        if my_name in all_device_maps[node]:
+            reverse_device_maps[node] = {
+                v: k for k, v in all_device_maps[node][my_name].items()
+            }
+    return reverse_device_maps
+
+
+def _get_device_infos():
+    from . import TensorPipeAgent
+
+    agent = cast(TensorPipeAgent, api._get_current_rpc_agent())
+    opts = agent._get_backend_options()
+    device_count = torch.cuda.device_count()
+    if torch.cuda.is_available() and opts.devices:
+        torch.cuda.init()
+    return device_count, opts.device_maps, opts.devices
+
+
+def _set_devices_and_reverse_device_map(agent):
+    from . import TensorPipeAgent
+
+    agent = cast(TensorPipeAgent, agent)
+    # Group state is retrieved from local agent
+    # On initialization, tensorpipe agent retrieves information from all existing workers, so group state is valid
+    my_worker_info = agent.get_worker_info()
+    my_name = my_worker_info.name
+    all_worker_infos = agent.get_worker_infos()
+    # One round to get device_maps of all workers and construct reverse device maps
+    all_device_counts, all_device_maps, all_devices, all_names = {}, {}, {}, []
+    for worker_info in all_worker_infos:
+        worker_name = worker_info.name
+        if worker_name != my_name:
+            # TODO: make async?
+            device_count, device_map, devices = api.rpc_sync(
+                worker_name, _get_device_infos
+            )
+        else:
+            opts = agent._get_backend_options()
+            device_count, device_map, devices = (
+                torch.cuda.device_count(),
+                opts.device_maps,
+                opts.devices,
+            )
+        all_device_counts[worker_name] = device_count
+        all_device_maps[worker_name] = device_map
+        all_devices[worker_name] = devices
+        all_names.append(worker_name)
+
+    _validate_device_maps(
+        all_names,
+        all_device_counts,
+        all_device_maps,
+        all_devices,
+        is_static_group=False,
+    )
+    reverse_device_maps = _create_reverse_mapping(my_name, all_names, all_device_maps)
+
+    # Perform RPC call to all workers, including itself, to include newly joined worker information and device maps
+    for worker_name in all_names:
+        # Set device list for each worker
+        all_devices[worker_name] = _create_device_list(
+            all_devices[worker_name], all_device_maps[worker_name], reverse_device_maps
+        )
+        api.rpc_sync(
+            worker_name,
+            _update_group_membership,
+            args=(my_worker_info, all_devices[worker_name], reverse_device_maps, True),
+        )
+
+
+def _tensorpipe_init_backend_handler(
+    store, name, rank, world_size, rpc_backend_options
+):
+    from . import TensorPipeAgent, TensorPipeRpcBackendOptions
+
+    if not isinstance(store, dist.Store):
+        raise TypeError(f"`store` must be a c10d::Store. {store}")
+
+    if not isinstance(rpc_backend_options, TensorPipeRpcBackendOptions):
+        raise TypeError(
+            f"`rpc_backend_options` must be a `TensorPipeRpcBackendOptions`. {rpc_backend_options}"
+        )
+
+    device_count = torch.cuda.device_count()
+
+    is_static_group = True if world_size else False
+    # world_size is specified so this is a static group (ranks cannot join and leave)
+    if is_static_group:
+        # The agent's join method is required to behave like a barrier and perform
+        # collective operations, for which it relies on a process group, instead of
+        # re-implementing this on top of RPCs.
+        group = _init_process_group(store, rank, world_size)
+
+        reverse_device_maps, devices = _tensorpipe_exchange_and_check_all_device_maps(
+            name,
+            device_count,
+            rpc_backend_options.device_maps,
+            rpc_backend_options.devices,
+            group,
+        )
+
+        if torch.cuda.is_available() and devices:
+            # It's necessary to initialize PyTorch CUDA states here (e.g.,
+            # CUDACachingAllocator). If this is missing, we could hit errors like
+            # "allocator not initialized", because other processes might send
+            # CUDA-related RPC request to this process before user code in this
+            # process initializes its PyTorch CUDA states.
+            torch.cuda.init()
+
+        # TODO: add try-except and destroy _agent in all processes if any fails.
+        agent = TensorPipeAgent(
+            store,
+            name,
+            rank,
+            world_size,
+            rpc_backend_options,
+            reverse_device_maps,
+            devices,
+        )
+
+        api._init_rpc_states(agent)
+
+        # Run one dummy round of RPC to initialize channels/transports. Without
+        # this, it's easy to hit timeout in rpc.shutdown() if there is no other RPC
+        # on that process before rpc.shutdown(), as the agent initialization can
+        # take longer than 5s.
+        api._all_gather(None, timeout=rpc_backend_options.rpc_timeout)
+        # Need a barrier here to make sure no peers leave before the rank0 finishes
+        # _all_gather
+        group.barrier().wait()
+
+        return agent
+    # initialization for dynamic rpc (ranks can join and leave)
+    else:
+        with _group_membership_management(store, name, True):
+            # Construct TPAgent with empty reverse_device_map and devices
+            # these properties will be updated after initialization
+            agent = TensorPipeAgent(
+                store,
+                name,
+                rank,
+                world_size,
+                rpc_backend_options,
+                {},
+                [],
+            )
+            api._init_rpc_states(agent)
+
+            try:
+                # Notify all workers in group this rank has joined and set devices and reverse_device_map
+                # This is a synchronous operation that completes once all existing ranks are updated
+                _set_devices_and_reverse_device_map(agent)
+            except Exception:
+                api.shutdown()
+                raise
+            return agent
+
+
+register_backend(
+    "TENSORPIPE",
+    _tensorpipe_construct_rpc_backend_options_handler,
+    _tensorpipe_init_backend_handler,
+)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/constants.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..56f6db4db259df01245c6615e4b41669c23a367c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/constants.py
@@ -0,0 +1,25 @@
+from datetime import timedelta
+from typing import List
+
+from torch._C._distributed_rpc import (
+    _DEFAULT_INIT_METHOD,
+    _DEFAULT_NUM_WORKER_THREADS,
+    _DEFAULT_RPC_TIMEOUT_SEC,
+    _UNSET_RPC_TIMEOUT,
+)
+
+
+# For any RpcAgent.
+DEFAULT_RPC_TIMEOUT_SEC: float = _DEFAULT_RPC_TIMEOUT_SEC
+DEFAULT_INIT_METHOD: str = _DEFAULT_INIT_METHOD
+DEFAULT_SHUTDOWN_TIMEOUT: float = 0
+
+# For TensorPipeAgent.
+DEFAULT_NUM_WORKER_THREADS: int = _DEFAULT_NUM_WORKER_THREADS
+# Ensure that we don't time out when there are long periods of time without
+# any operations against the underlying ProcessGroup.
+DEFAULT_PROCESS_GROUP_TIMEOUT: timedelta = timedelta(milliseconds=2**31 - 1)
+# Value indicating that timeout is not set for RPC call, and the default should be used.
+UNSET_RPC_TIMEOUT: float = _UNSET_RPC_TIMEOUT
+
+__all__: List[str] = []
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/functions.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..e48ea8cc534ab87838965c947bbd0ed76d4d64c7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/functions.py
@@ -0,0 +1,169 @@
+# mypy: allow-untyped-defs
+import functools
+
+
+def async_execution(fn):
+    r"""
+    A decorator for a function indicating that the return value of the function
+    is guaranteed to be a :class:`~torch.futures.Future` object and this
+    function can run asynchronously on the RPC callee. More specifically, the
+    callee extracts the :class:`~torch.futures.Future` returned by the wrapped
+    function and installs subsequent processing steps as a callback to that
+    :class:`~torch.futures.Future`. The installed callback will read the value
+    from the :class:`~torch.futures.Future` when completed and send the
+    value back as the RPC response. That also means the returned
+    :class:`~torch.futures.Future` only exists on the callee side and is never
+    sent through RPC. This decorator is useful when the wrapped function's
+    (``fn``) execution needs to pause and resume due to, e.g., containing
+    :meth:`~torch.distributed.rpc.rpc_async` or waiting for other signals.
+
+    .. note:: To enable asynchronous execution, applications must pass the
+        function object returned by this decorator to RPC APIs. If RPC detected
+        attributes installed by this decorator, it knows that this function
+        returns a ``Future`` object and will handle that accordingly.
+        However, this does not mean this decorator has to be outmost one when
+        defining a function. For example, when combined with ``@staticmethod``
+        or ``@classmethod``, ``@rpc.functions.async_execution`` needs to be the
+        inner decorator to allow the target function be recognized as a static
+        or class function. This target function can still execute asynchronously
+        because, when accessed, the static or class method preserves attributes
+        installed by ``@rpc.functions.async_execution``.
+
+
+    Example::
+        The returned :class:`~torch.futures.Future` object can come from
+        :meth:`~torch.distributed.rpc.rpc_async`,
+        :meth:`~torch.futures.Future.then`, or :class:`~torch.futures.Future`
+        constructor. The example below shows directly using the
+        :class:`~torch.futures.Future` returned by
+        :meth:`~torch.futures.Future.then`.
+
+        >>> from torch.distributed import rpc
+        >>>
+        >>> # omitting setup and shutdown RPC
+        >>>
+        >>> # On all workers
+        >>> @rpc.functions.async_execution
+        >>> def async_add_chained(to, x, y, z):
+        >>>     # This function runs on "worker1" and returns immediately when
+        >>>     # the callback is installed through the `then(cb)` API. In the
+        >>>     # mean time, the `rpc_async` to "worker2" can run concurrently.
+        >>>     # When the return value of that `rpc_async` arrives at
+        >>>     # "worker1", "worker1" will run the lambda function accordingly
+        >>>     # and set the value for the previously returned `Future`, which
+        >>>     # will then trigger RPC to send the result back to "worker0".
+        >>>     return rpc.rpc_async(to, torch.add, args=(x, y)).then(
+        >>>         lambda fut: fut.wait() + z
+        >>>     )
+        >>>
+        >>> # On worker0
+        >>> # xdoctest: +SKIP
+        >>> ret = rpc.rpc_sync(
+        >>>     "worker1",
+        >>>     async_add_chained,
+        >>>     args=("worker2", torch.ones(2), 1, 1)
+        >>> )
+        >>> print(ret)  # prints tensor([3., 3.])
+
+        When combined with TorchScript decorators, this decorator must be the
+        outmost one.
+
+        >>> from torch import Tensor
+        >>> from torch.futures import Future
+        >>> from torch.distributed import rpc
+        >>>
+        >>> # omitting setup and shutdown RPC
+        >>>
+        >>> # On all workers
+        >>> @torch.jit.script
+        >>> def script_add(x: Tensor, y: Tensor) -> Tensor:
+        >>>     return x + y
+        >>>
+        >>> @rpc.functions.async_execution
+        >>> @torch.jit.script
+        >>> def async_add(to: str, x: Tensor, y: Tensor) -> Future[Tensor]:
+        >>>     return rpc.rpc_async(to, script_add, (x, y))
+        >>>
+        >>> # On worker0
+        >>> ret = rpc.rpc_sync(
+        >>>     "worker1",
+        >>>     async_add,
+        >>>     args=("worker2", torch.ones(2), 1)
+        >>> )
+        >>> print(ret)  # prints tensor([2., 2.])
+
+        When combined with static or class method, this decorator must be the
+        inner one.
+
+        >>> from torch.distributed import rpc
+        >>>
+        >>> # omitting setup and shutdown RPC
+        >>>
+        >>> # On all workers
+        >>> class AsyncExecutionClass:
+        >>>
+        >>>     @staticmethod
+        >>>     @rpc.functions.async_execution
+        >>>     def static_async_add(to, x, y, z):
+        >>>         return rpc.rpc_async(to, torch.add, args=(x, y)).then(
+        >>>             lambda fut: fut.wait() + z
+        >>>         )
+        >>>
+        >>>     @classmethod
+        >>>     @rpc.functions.async_execution
+        >>>     def class_async_add(cls, to, x, y, z):
+        >>>         ret_fut = torch.futures.Future()
+        >>>         rpc.rpc_async(to, torch.add, args=(x, y)).then(
+        >>>             lambda fut: ret_fut.set_result(fut.wait() + z)
+        >>>         )
+        >>>         return ret_fut
+        >>>
+        >>>     @rpc.functions.async_execution
+        >>>     def bound_async_add(self, to, x, y, z):
+        >>>         return rpc.rpc_async(to, torch.add, args=(x, y)).then(
+        >>>             lambda fut: fut.wait() + z
+        >>>         )
+        >>>
+        >>> # On worker0
+        >>> ret = rpc.rpc_sync(
+        >>>     "worker1",
+        >>>     AsyncExecutionClass.static_async_add,
+        >>>     args=("worker2", torch.ones(2), 1, 2)
+        >>> )
+        >>> print(ret)  # prints tensor([4., 4.])
+        >>>
+        >>> ret = rpc.rpc_sync(
+        >>>     "worker1",
+        >>>     AsyncExecutionClass.class_async_add,
+        >>>     args=("worker2", torch.ones(2), 1, 2)
+        >>> )
+        >>> print(ret)  # prints tensor([4., 4.])
+
+        This decorator also works with RRef helpers, i.e., .
+        :meth:`torch.distributed.rpc.RRef.rpc_sync`,
+        :meth:`torch.distributed.rpc.RRef.rpc_async`, and
+        :meth:`torch.distributed.rpc.RRef.remote`.
+
+        >>> from torch.distributed import rpc
+        >>>
+        >>> # reuse the AsyncExecutionClass class above
+        >>> rref = rpc.remote("worker1", AsyncExecutionClass)
+        >>> ret = rref.rpc_sync().static_async_add("worker2", torch.ones(2), 1, 2)
+        >>> print(ret)  # prints tensor([4., 4.])
+        >>>
+        >>> rref = rpc.remote("worker1", AsyncExecutionClass)
+        >>> ret = rref.rpc_async().static_async_add("worker2", torch.ones(2), 1, 2).wait()
+        >>> print(ret)  # prints tensor([4., 4.])
+        >>>
+        >>> rref = rpc.remote("worker1", AsyncExecutionClass)
+        >>> ret = rref.remote().static_async_add("worker2", torch.ones(2), 1, 2).to_here()
+        >>> print(ret)  # prints tensor([4., 4.])
+    """
+
+    @functools.wraps(fn)
+    def wrapper(*args, **kwargs):
+        return fn(*args, **kwargs)
+
+    # Can't declare and use attributes of function objects (mypy#2087)
+    wrapper._wrapped_async_rpc_function = fn  # type: ignore[attr-defined]
+    return wrapper
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/internal.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/internal.py
new file mode 100644
index 0000000000000000000000000000000000000000..5faf7d14d0da572a24a36085bdc334e468ab76a6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/internal.py
@@ -0,0 +1,285 @@
+# mypy: allow-untyped-defs
+import collections
+import copyreg
+import io
+import pickle
+import sys
+import threading
+import traceback
+from enum import Enum
+
+import torch
+import torch.distributed as dist
+from torch._C._distributed_rpc import _get_current_rpc_agent
+
+
+__all__ = ["RPCExecMode", "serialize", "deserialize", "PythonUDF", "RemoteException"]
+
+# Thread local tensor tables to store tensors while pickling torch.Tensor
+# objects
+_thread_local_tensor_tables = threading.local()
+_pickler = pickle.Pickler
+_unpickler = pickle.Unpickler
+
+
+class RPCExecMode(Enum):
+    SYNC = "sync"
+    ASYNC = "async"
+    ASYNC_JIT = "async_jit"
+    REMOTE = "remote"
+
+
+class _InternalRPCPickler:
+    r"""
+    This class provides serialize() and deserialize() interfaces to serialize
+    data to be "binary string + tensor table" format
+    So for RPC python UDF function and args, non tensor data will be serialized
+    into regular binary string, tensor data will be put into thread local tensor
+    tables, this serialization format is consistent with builtin operator and args
+    using JIT pickler. This format will make tensor handling in C++ much easier,
+    e.g. attach tensor to distributed autograd graph in C++
+    """
+
+    def __init__(self):
+        # Ignore type error because dispatch_table is defined in third-party package
+        self._dispatch_table = copyreg.dispatch_table.copy()  # type: ignore[attr-defined]
+        self._dispatch_table[torch.Tensor] = self._tensor_reducer
+        # Used for registering customized picklers.
+        self._class_reducer_dict = {}
+
+    def _register_reducer(self, obj_class, reducer):
+        # For the same class, only register the reducer once.
+        if obj_class not in self._class_reducer_dict:
+            self._class_reducer_dict[obj_class] = reducer
+
+    @classmethod
+    def _tensor_receiver(cls, tensor_index):
+        global _thread_local_tensor_tables
+        return _thread_local_tensor_tables.recv_tables[tensor_index]
+
+    def _tensor_reducer(self, tensor):
+        global _thread_local_tensor_tables
+        _thread_local_tensor_tables.send_tables.append(tensor)
+        tensor_index = len(_thread_local_tensor_tables.send_tables) - 1
+        return (_InternalRPCPickler._tensor_receiver, (tensor_index,))
+
+    @classmethod
+    def _py_rref_receiver(cls, rref_fork_data):
+        return dist.rpc.PyRRef._deserialize(rref_fork_data)
+
+    def _py_rref_reducer(self, py_rref):
+        rref_fork_data = py_rref._serialize()
+        return (_InternalRPCPickler._py_rref_receiver, (rref_fork_data,))
+
+    def _rref_reducer(self, rref):
+        return self._py_rref_reducer(rref)
+
+    @classmethod
+    def _script_module_receiver(cls, script_module_serialized):
+        """
+        Given a serialized representation of a ScriptModule created with torch.jit.save,
+        loads and returns the ScriptModule.
+        """
+        f = io.BytesIO(script_module_serialized)
+        m = torch.jit.load(f)
+        return m
+
+    def _script_module_reducer(self, script_module):
+        """
+        Serializes a ScriptModule.
+        """
+        f = io.BytesIO()
+        torch.jit.save(script_module, f)
+        return (_InternalRPCPickler._script_module_receiver, (f.getvalue(),))
+
+    def serialize(self, obj):
+        r"""
+        Serialize non tensor data into binary string, tensor data into
+        tensor table
+        """
+        f = io.BytesIO()
+        p = _pickler(f)
+        p.dispatch_table = self._dispatch_table
+
+        # rpc api could accept user picklers inheriting from _InternalRPCPickler to serialize rref,
+        # user picklers could have different initialization function from _InternalRPCPickler,
+        # but all the user picklers should call serialize() and use _rref_reducer to pickle rref
+        # in python. also, when _internal_rpc_pickler is imported to rpc/api.py, rpc.RRef is not
+        # compiled yet, it is not good place to access rpc.RRef inside _InternalRPCPickler constructor,
+        # so putting rref's dispatch table here
+        #
+        # The return value of a `rpc.remote(..)` call is type of `rpc.PyRRef`.
+        # The deserialized RRef object on an RPC receiver side is type of `rpc.PyRRef`.
+        # Ignore type error because dispatch_table is defined in third-party package
+        p.dispatch_table[dist.rpc.PyRRef] = self._py_rref_reducer  # type: ignore[index]
+        # An RRef created locally by RRef Python constructor is type of `rpc.RRef`.
+        # Ignore type error because dispatch_table is defined in third-party package
+        p.dispatch_table[dist.rpc.RRef] = self._rref_reducer  # type: ignore[index]
+
+        # Add dispatch pickling for ScriptModule or its subclass.
+        if isinstance(obj, torch.jit.ScriptModule):
+            # Ignore type error because dispatch_table is defined in third-party package
+            p.dispatch_table[obj.__class__] = self._script_module_reducer  # type: ignore[index]
+
+        # Install customized picklers.
+        for class_name in self._class_reducer_dict.keys():
+            p.dispatch_table[class_name] = self._class_reducer_dict[class_name]  # type: ignore[index]
+
+        # save _thread_local_tensor_tables.send_tables if it is in nested call
+        global _thread_local_tensor_tables
+        if hasattr(_thread_local_tensor_tables, "send_tables"):
+            old_send_tables = _thread_local_tensor_tables.send_tables
+        else:
+            old_send_tables = None
+        _thread_local_tensor_tables.send_tables = []
+
+        p.dump(obj)
+
+        # restore _thread_local_tensor_tables.send_tables if return
+        # from nested call, otherwise clean up the table
+        tensors = _thread_local_tensor_tables.send_tables
+        if old_send_tables is not None:
+            _thread_local_tensor_tables.send_tables = old_send_tables
+        else:
+            del _thread_local_tensor_tables.send_tables
+
+        return (f.getvalue(), tensors)
+
+    def deserialize(self, binary_data, tensor_table):
+        r"""
+        Deserialize binary string + tensor table to original obj
+        """
+        # save _thread_local_tensor_tables.recv_tables if it is in nested call
+        global _thread_local_tensor_tables
+        if hasattr(_thread_local_tensor_tables, "recv_tables"):
+            old_recv_tables = _thread_local_tensor_tables.recv_tables
+        else:
+            old_recv_tables = None
+        _thread_local_tensor_tables.recv_tables = tensor_table
+
+        try:
+            unpickler = _unpickler(io.BytesIO(binary_data))
+            ret = unpickler.load()
+        except AttributeError as e:
+            # Occurs when function is not found on module/class during
+            # unpickling.
+            except_str = (
+                str(e)
+                + """ Default RPC pickler does not serialize
+            function code. Ensure that UDFs are defined on both caller and
+            callee modules."""
+            )
+            ret = AttributeError(except_str)
+            # Ensure the stack trace gets preserved
+            ret.__cause__ = e
+
+        # restore _thread_local_tensor_tables.recv_tables if return
+        # from nested call, otherwise clean up the table
+        if old_recv_tables is not None:
+            _thread_local_tensor_tables.recv_tables = old_recv_tables
+        else:
+            del _thread_local_tensor_tables.recv_tables
+
+        return ret
+
+
+# Create _internal_rpc_pickler only once to initialize _dispatch_table only once
+_internal_rpc_pickler = _InternalRPCPickler()
+
+
+def serialize(obj):
+    return _internal_rpc_pickler.serialize(obj)
+
+
+def deserialize(binary_data, tensor_table):
+    return _internal_rpc_pickler.deserialize(binary_data, tensor_table)
+
+
+def _run_function(python_udf):
+    r"""
+    This function is exclusively called from C++.
+    See ``torch/csrc/distributed/rpc/python_rpc_handler.cpp``.
+
+    Runs a Python UDF and returns its return value.
+    Wraps any exception in ``RemoteException`` if the function raises.
+    """
+    try:
+        if isinstance(python_udf, AttributeError):
+            raise python_udf
+        result = python_udf.func(*python_udf.args, **python_udf.kwargs)
+    except Exception as e:
+        # except str = exception info + traceback string
+        except_str = (
+            f"On {_get_current_rpc_agent().get_worker_info()}:\n"
+            f"{repr(e)}\n{traceback.format_exc()}"
+        )
+        print(except_str, file=sys.stderr)
+        result = RemoteException(except_str, type(e))
+    return result
+
+
+def _handle_exception(result):
+    if isinstance(result, RemoteException):
+        exception_msg = result.msg.encode("utf-8").decode("unicode_escape")
+        # We wrap exception re-creation here in case some exception classes
+        # cannot be constructed directly from a string.
+        exc = None
+        try:
+            exc = result.exception_type(exception_msg)
+        except BaseException as e:
+            raise RuntimeError(  # noqa: B904
+                f"Failed to create original exception type. Error msg was {str(e)}"
+                f" Original exception on remote side was {exception_msg}"
+            ) from e
+
+        if exc is not None:
+            raise exc
+
+
+def _build_rpc_profiling_key(
+    exec_type, func_name, current_worker_name, dst_worker_name
+):
+    """
+    Builds the key that RPC calls are profiled with using the autograd profiler.
+    This will be the name of the corresponding Event recorded in the profiler.
+
+    Args:
+        exec_type (RPCExecMode): Type of RPC/RRef call
+        func_name (str): Name of function being profiled.
+        current_worker_name (str): Name of current worker.
+        dst_worker_name (str): Name of the destination worker.
+
+    Returns:
+        String representing profiling key
+    """
+    profile_key = (
+        f"rpc_{exec_type.value}#{func_name}({current_worker_name} -> {dst_worker_name})"
+    )
+    return profile_key
+
+
+def _start_record_function(exec_type, func_name, current_worker_name, dest_worker_name):
+    """
+    This function should be called from RPC/RRef functions to create a
+    RecordFunction object for profiling. This function also runs the before
+    callbacks that start the profiling, though the user is responsible for
+    running the appropriate callbacks when the function to be profiled finishes.
+
+    Args:
+        exec_type (RPCExecMode): Type of RPC/RRef call
+        func_name (str): Name of function being profiled.
+        current_worker_name (str): Name of current worker.
+        dest_worker_name (str): Name of the destination worker.
+
+    Returns:
+        An instance of `torch.autograd._RecordFunction`.
+    """
+    assert torch.autograd._profiler_enabled(), "Autograd profiler should be enabled."
+    profile_key = f"rpc_{exec_type.value}#{str(func_name)}({current_worker_name} -> {dest_worker_name})"
+    rf = torch.autograd._RecordFunction()  # type: ignore[attr-defined]
+    torch.autograd._run_before_callbacks(rf, profile_key)  # type: ignore[attr-defined]
+    return rf
+
+
+PythonUDF = collections.namedtuple("PythonUDF", ["func", "args", "kwargs"])
+RemoteException = collections.namedtuple("RemoteException", ["msg", "exception_type"])
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/options.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/options.py
new file mode 100644
index 0000000000000000000000000000000000000000..53bf473ba56287befc57805865463955d999f00b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/options.py
@@ -0,0 +1,175 @@
+# mypy: allow-untyped-defs
+from typing import Dict, List, Optional, Union
+
+import torch
+from torch._C._distributed_rpc import _TensorPipeRpcBackendOptionsBase
+
+from . import constants as rpc_contants
+
+
+DeviceType = Union[int, str, torch.device]
+
+__all__ = ["TensorPipeRpcBackendOptions"]
+
+
+def _to_device(device: DeviceType) -> torch.device:
+    device = torch.device(device)
+    if device.type != "cuda":
+        raise ValueError(
+            "`set_devices` expect a list of CUDA devices, but got "
+            f"device type {device.type}."
+        )
+    return device
+
+
+def _to_device_map(
+    device_map: Dict[DeviceType, DeviceType]
+) -> Dict[torch.device, torch.device]:
+    full_device_map: Dict[torch.device, torch.device] = {}
+    reverse_map: Dict[torch.device, torch.device] = {}
+    for k, v in device_map.items():
+        k, v = torch.device(k), torch.device(v)
+        if v in reverse_map:
+            raise ValueError(
+                "`device_map` only supports 1-to-1 mapping, "
+                f"trying to map {k} and {reverse_map[v]} to {v}"
+            )
+        full_device_map[k] = v
+        reverse_map[v] = k
+    return full_device_map
+
+
+def _to_device_list(devices: List[DeviceType]) -> List[torch.device]:
+    return list(map(_to_device, devices))
+
+
+class TensorPipeRpcBackendOptions(_TensorPipeRpcBackendOptionsBase):
+    r"""
+    The backend options for
+    :class:`~torch.distributed.rpc.TensorPipeAgent`, derived from
+    :class:`~torch.distributed.rpc.RpcBackendOptions`.
+
+    Args:
+        num_worker_threads (int, optional): The number of threads in the
+            thread-pool used by
+            :class:`~torch.distributed.rpc.TensorPipeAgent` to execute
+            requests (default: 16).
+        rpc_timeout (float, optional): The default timeout, in seconds,
+            for RPC requests (default: 60 seconds). If the RPC has not
+            completed in this timeframe, an exception indicating so will
+            be raised. Callers can override this timeout for individual
+            RPCs in :meth:`~torch.distributed.rpc.rpc_sync` and
+            :meth:`~torch.distributed.rpc.rpc_async` if necessary.
+        init_method (str, optional): The URL to initialize the distributed
+            store used for rendezvous. It takes any value accepted for the
+            same argument of :meth:`~torch.distributed.init_process_group`
+            (default: ``env://``).
+        device_maps (Dict[str, Dict], optional): Device placement mappings from
+            this worker to the callee. Key is the callee worker name and value
+            the dictionary (``Dict`` of ``int``, ``str``, or ``torch.device``)
+            that maps this worker's devices to the callee worker's devices.
+            (default: ``None``)
+        devices (List[int, str, or ``torch.device``], optional): all local
+            CUDA devices used by RPC agent. By Default, it will be initialized
+            to all local devices from its own ``device_maps`` and corresponding
+            devices from its peers' ``device_maps``. When processing CUDA RPC
+            requests, the agent will properly synchronize CUDA streams for
+            all devices in this ``List``.
+    """
+
+    def __init__(
+        self,
+        *,
+        num_worker_threads: int = rpc_contants.DEFAULT_NUM_WORKER_THREADS,
+        rpc_timeout: float = rpc_contants.DEFAULT_RPC_TIMEOUT_SEC,
+        init_method: str = rpc_contants.DEFAULT_INIT_METHOD,
+        device_maps: Optional[Dict[str, Dict[DeviceType, DeviceType]]] = None,
+        devices: Optional[List[DeviceType]] = None,
+        _transports: Optional[List] = None,
+        _channels: Optional[List] = None,
+    ):
+        full_device_maps = (
+            {}
+            if device_maps is None
+            else {k: _to_device_map(v) for k, v in device_maps.items()}
+        )
+        full_device_list = [] if devices is None else _to_device_list(devices)
+        super().__init__(
+            num_worker_threads,
+            _transports,
+            _channels,
+            rpc_timeout,
+            init_method,
+            full_device_maps,
+            full_device_list,
+        )
+
+    def set_device_map(self, to: str, device_map: Dict[DeviceType, DeviceType]):
+        r"""
+        Set device mapping between each RPC caller and callee pair. This
+        function can be called multiple times to incrementally add
+        device placement configurations.
+
+        Args:
+            to (str): Callee name.
+            device_map (Dict of int, str, or torch.device): Device placement
+                mappings from this worker to the callee. This map must be
+                invertible.
+
+        Example:
+            >>> # xdoctest: +SKIP("distributed")
+            >>> # both workers
+            >>> def add(x, y):
+            >>>     print(x)  # tensor([1., 1.], device='cuda:1')
+            >>>     return x + y, (x + y).to(2)
+            >>>
+            >>> # on worker 0
+            >>> options = TensorPipeRpcBackendOptions(
+            >>>     num_worker_threads=8,
+            >>>     device_maps={"worker1": {0: 1}}
+            >>>     # maps worker0's cuda:0 to worker1's cuda:1
+            >>> )
+            >>> options.set_device_map("worker1", {1: 2})
+            >>> # maps worker0's cuda:1 to worker1's cuda:2
+            >>>
+            >>> rpc.init_rpc(
+            >>>     "worker0",
+            >>>     rank=0,
+            >>>     world_size=2,
+            >>>     backend=rpc.BackendType.TENSORPIPE,
+            >>>     rpc_backend_options=options
+            >>> )
+            >>>
+            >>> x = torch.ones(2)
+            >>> rets = rpc.rpc_sync("worker1", add, args=(x.to(0), 1))
+            >>> # The first argument will be moved to cuda:1 on worker1. When
+            >>> # sending the return value back, it will follow the invert of
+            >>> # the device map, and hence will be moved back to cuda:0 and
+            >>> # cuda:1 on worker0
+            >>> print(rets[0])  # tensor([2., 2.], device='cuda:0')
+            >>> print(rets[1])  # tensor([2., 2.], device='cuda:1')
+        """
+        full_device_map = _to_device_map(device_map)
+        curr_device_maps = super().device_maps
+
+        if to in curr_device_maps:
+            for k, v in full_device_map.items():
+                if k in curr_device_maps[to] and v != curr_device_maps[to][k]:
+                    raise ValueError(
+                        "`set_device_map` only supports 1-to-1 mapping, trying"
+                        f" to map {k} to {v} and {curr_device_maps[to][k]}"
+                    )
+
+        super()._set_device_map(to, full_device_map)
+
+    def set_devices(self, devices: List[DeviceType]):
+        r"""
+        Set local devices used by the TensorPipe RPC agent. When processing
+        CUDA RPC requests, the TensorPipe RPC agent will properly synchronize
+        CUDA streams for all devices in this ``List``.
+
+        Args:
+            devices (List of int, str, or torch.device): local devices used by
+                the TensorPipe RPC agent.
+        """
+        self.devices = _to_device_list(devices)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/rref_proxy.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/rref_proxy.py
new file mode 100644
index 0000000000000000000000000000000000000000..85927b68bacb9c3fa33eab64a62e52bbf90fd054
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/rref_proxy.py
@@ -0,0 +1,80 @@
+# mypy: allow-untyped-defs
+from functools import partial
+
+import torch
+from torch.futures import Future
+
+from . import functions, rpc_async
+from .constants import UNSET_RPC_TIMEOUT
+
+
+def _local_invoke(rref, func_name, args, kwargs):
+    return getattr(rref.local_value(), func_name)(*args, **kwargs)
+
+
+@functions.async_execution
+def _local_invoke_async_execution(rref, func_name, args, kwargs):
+    return getattr(rref.local_value(), func_name)(*args, **kwargs)
+
+
+def _invoke_rpc(rref, rpc_api, func_name, timeout, *args, **kwargs):
+    def _rref_type_cont(rref_fut):
+        rref_type = rref_fut.value()
+
+        _invoke_func = _local_invoke
+        # Bypass ScriptModules when checking for async function attribute.
+        bypass_type = issubclass(rref_type, torch.jit.ScriptModule) or issubclass(
+            rref_type, torch._C.ScriptModule
+        )
+        if not bypass_type:
+            func = getattr(rref_type, func_name)
+            if hasattr(func, "_wrapped_async_rpc_function"):
+                _invoke_func = _local_invoke_async_execution
+
+        return rpc_api(
+            rref.owner(),
+            _invoke_func,
+            args=(rref, func_name, args, kwargs),
+            timeout=timeout,
+        )
+
+    rref_fut = rref._get_type(timeout=timeout, blocking=False)
+
+    if rpc_api != rpc_async:
+        rref_fut.wait()
+        return _rref_type_cont(rref_fut)
+    else:
+        # A little explanation on this.
+        # rpc_async returns a Future pointing to the return value of `func_name`, it returns a `Future[T]`
+        # Calling _rref_type_cont from the `then` lambda causes Future wrapping. IOW, `then` returns a `Future[Future[T]]`
+        # To address that, we return a Future that is completed with the result of the async call.
+        result: Future = Future()
+
+        def _wrap_rref_type_cont(fut):
+            try:
+                _rref_type_cont(fut).then(_complete_op)
+            except BaseException as ex:
+                result.set_exception(ex)
+
+        def _complete_op(fut):
+            try:
+                result.set_result(fut.value())
+            except BaseException as ex:
+                result.set_exception(ex)
+
+        rref_fut.then(_wrap_rref_type_cont)
+        return result
+
+
+# This class manages proxied RPC API calls for RRefs. It is entirely used from
+# C++ (see python_rpc_handler.cpp).
+class RRefProxy:
+    def __init__(self, rref, rpc_api, timeout=UNSET_RPC_TIMEOUT):
+        self.rref = rref
+        self.rpc_api = rpc_api
+        self.rpc_timeout = timeout
+
+    def __getattr__(self, func_name):
+        return partial(
+            _invoke_rpc, self.rref, self.rpc_api, func_name, self.rpc_timeout
+        )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/server_process_global_profiler.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/server_process_global_profiler.py
new file mode 100644
index 0000000000000000000000000000000000000000..46696599032a88d126b03d12d2f47bc28db184d7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/rpc/server_process_global_profiler.py
@@ -0,0 +1,183 @@
+#!/usr/bin/python3
+# mypy: allow-untyped-defs
+
+import itertools
+from typing import List
+
+import torch
+from torch.autograd.profiler_legacy import profile
+
+from . import (
+    _disable_server_process_global_profiler,
+    _enable_server_process_global_profiler,
+)
+
+
+__all__: List[str] = []
+
+
+class _server_process_global_profile(profile):
+    """
+    It has the same API as ``torch.autograd.profiler.profile`` class,
+    except that it enables profiling on all threads running RPC server request callbacks.
+
+    Context manager that manages autograd profiler state and holds a summary of results.
+    Under the hood it just records events of functions being executed in C++ and
+    exposes those events to Python. You can wrap any code into it and it will
+    only report runtime of PyTorch functions.
+    Note: profiler is thread local and is automatically propagated into the async tasks
+
+    Args:
+        enabled (bool, optional): Setting this to False makes this context manager a no-op.
+            Default: ``True``.
+
+        use_cuda (bool, optional): Enables timing of CUDA events as well using the cudaEvent API.
+            Adds approximately 4us of overhead to each tensor operation.
+            Default: ``False``
+
+        record_shapes (bool, optional): If shapes recording is set, information
+            about input dimensions will be collected. This allows one to see which
+            dimensions have been used under the hood and further group by them
+            using prof.key_averages(group_by_input_shape=True). Please note that
+            shape recording might skew your profiling data. It is recommended to
+            use separate runs with and without shape recording to validate the timing.
+            Most likely the skew will be negligible for bottom most events (in a case
+            of nested function calls). But for higher level functions the total
+            self cpu time might be artificially increased because of the shape
+            collection.
+
+        profile_memory (bool, optional): Whether to report memory usage, default: ``False``
+
+    .. warning:
+        Enabling memory profiling incurs additional profiler overhead
+
+    .. warning:
+        Due to some CUDA multiprocessing limitations (multiprocessing-cuda-note_),
+        one cannot use the profiler with ``use_cuda = True`` to benchmark
+        DataLoaders with ``num_workers > 0``. If you wish to benchmark data loading,
+        please use ``use_cuda = False`` or ``num_workers = 0``.
+
+    Example:
+        >>> # xdoctest: +SKIP
+        >>> # On worker 0:
+        >>> import torch
+        >>> import torch.distributed.rpc as rpc
+        >>> rpc.init_rpc("worker0", rank=0, world_size=2)
+        >>> x, y = torch.tensor(1), torch.tensor(2)
+        >>> outer_profile_rref = rpc.remote(dst_worker_name, rpc._server_process_global_profile)
+        >>> outer_profile_rref.rpc_sync().__enter__()
+        >>> rpc.rpc_sync(dst_worker_name, torch.add, (x, y))
+        >>> inner_profile_rref = rpc.remote(dst_worker_name, rpc._server_process_global_profile)
+        >>> inner_profile_rref.rpc_sync().__enter__()
+        >>> rpc.rpc_sync(dst_worker_name, torch.sub, (x, y))
+        >>> inner_profile_rref.rpc_sync().__exit__(None, None, None)
+        >>> outer_profile_rref.rpc_sync().__exit__(None, None, None)
+        >>> print(inner_profile_rref.rpc_sync().key_averages())
+        ---------  ---------------  ---------------  ---------------  ---------------  ---------------  ---------------
+        Name       Self CPU total %  Self CPU total   CPU total %      CPU total        CPU time avg     Number of Calls
+        ---------  ---------------  ---------------  ---------------  ---------------  ---------------  ---------------
+        sub        85.06%           76.275us         100.00%          89.667us         89.667us         1
+        empty      14.94%           13.392us         14.94%           13.392us         13.392us         1
+        ---------  ---------------  ---------------  ---------------  ---------------  ---------------  ---------------
+        Self CPU time total: 89.667us
+        >>> print(outer_profile_rref.rpc_sync().key_averages())
+        ---------  ---------------  ---------------  ---------------  ---------------  ---------------  ---------------
+        Name       Self CPU total %  Self CPU total   CPU total %      CPU total        CPU time avg     Number of Calls
+        ---------  ---------------  ---------------  ---------------  ---------------  ---------------  ---------------
+        sub        35.65%           76.275us         41.91%           89.667us         89.667us         1
+        empty      12.67%           27.101us         12.67%           27.101us         13.551us         2
+        add        51.68%           110.550us        58.09%           124.259us        124.259us        1
+        ---------  ---------------  ---------------  ---------------  ---------------  ---------------  ---------------
+        Self CPU time total: 213.926us
+        >>> rpc.shutdown()
+
+        >>> # On worker 1:
+        >>> import torch.distributed.rpc as rpc
+        >>> rpc.init_rpc("worker1", rank=1, world_size=2)
+        >>> # wait for worker 0 to finish work, and then shutdown.
+        >>> rpc.shutdown()
+    """
+
+    def __init__(self, *args, **kwargs):
+        super().__init__(*args, **kwargs)
+
+    def __enter__(self):
+        """
+        Turn on server-side process-global profiling.
+        This enables thread-local profiler on all RPC threads running server-side request callbacks.
+        """
+        if not self.enabled:
+            return
+
+        if self.entered:  # type: ignore[has-type]
+            raise RuntimeError("autograd profiler traces are not reentrant")
+        self.entered = True
+
+        profiler_kind = (
+            torch.autograd.ProfilerState.CUDA
+            if self.use_cuda
+            else torch.autograd.ProfilerState.CPU
+        )
+        profiler_config = torch.autograd.ProfilerConfig(
+            profiler_kind,
+            self.record_shapes,
+            self.profile_memory,
+            False,
+            False,
+            False,
+            torch.profiler._ExperimentalConfig(),
+        )
+        _enable_server_process_global_profiler(profiler_config)
+        return self
+
+    def __exit__(self, exc_type, exc_val, exc_tb):
+        """
+        Turn off server-side process-global profiling.
+        Aggregate all profiling events recorded by RPC threads.
+
+        These attributes are assigned on exiting context.
+
+        Attributes:
+            function_events (torch.autograd.profiler.EventList).  It's a list that has helper
+            methods, like 1) show record items in a pretty-print table.
+            2) do averaging by grouping on keys. 3) and more.
+
+            process_global_function_events (List[torch.autograd.profiler.FunctionEvent]).
+            It's a list of ``FunctionEvent`` elements. Every element is a profiling result
+            of an RPC request handling within the profiling range.
+        """
+        if not self.enabled:
+            return
+
+        process_global_events = _disable_server_process_global_profiler()
+
+        # Every element in this list is a thread profiling result from an RPC request handling.
+        process_global_function_events = []
+        for thread_local_events in process_global_events:
+            # Parse from ``Event``s to ``FunctionEvent``s.
+            thread_local_function_events = (
+                torch.autograd.profiler_legacy._parse_legacy_records(
+                    thread_local_events
+                )
+            )
+            thread_local_function_events.sort(
+                key=lambda function_event: [
+                    function_event.time_range.start,
+                    -(function_event.time_range.end),
+                ]
+            )
+            process_global_function_events.append(thread_local_function_events)
+
+        flattened_function_events = list(
+            itertools.chain.from_iterable(process_global_function_events)
+        )
+        self.function_events = torch.autograd.profiler_util.EventList(
+            flattened_function_events,
+            use_device="cuda" if self.use_cuda else None,
+            profile_memory=self.profile_memory,
+        )
+        self.function_events._build_tree()
+
+        self.process_global_function_events = process_global_function_events
+
+        return False
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f2746f60ba8720fa05fb06fa6cd60d7a57558417
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__init__.py
@@ -0,0 +1,67 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates
+
+import torch
+import torch.distributed.tensor._ops  # force import all built-in dtensor ops
+from torch.distributed.device_mesh import DeviceMesh, init_device_mesh  # noqa: F401
+from torch.distributed.tensor._api import (
+    distribute_module,
+    distribute_tensor,
+    DTensor,
+    empty,
+    full,
+    ones,
+    rand,
+    randn,
+    zeros,
+)
+from torch.distributed.tensor.placement_types import (
+    Partial,
+    Placement,
+    Replicate,
+    Shard,
+)
+from torch.optim.optimizer import (
+    _foreach_supported_types as _optim_foreach_supported_types,
+)
+from torch.utils._foreach_utils import (
+    _foreach_supported_types as _util_foreach_supported_types,
+)
+
+
+# All public APIs from dtensor package
+__all__ = [
+    "DTensor",
+    "distribute_tensor",
+    "distribute_module",
+    "Shard",
+    "Replicate",
+    "Partial",
+    "Placement",
+    "ones",
+    "empty",
+    "full",
+    "rand",
+    "randn",
+    "zeros",
+]
+
+
+# Append DTensor to the list of supported types for foreach implementation for optimizer
+# and clip_grad_norm_ so that we will try to use foreach over the for-loop implementation on CUDA.
+if DTensor not in _optim_foreach_supported_types:
+    _optim_foreach_supported_types.append(DTensor)
+
+if DTensor not in _util_foreach_supported_types:
+    _util_foreach_supported_types.append(DTensor)
+
+
+# Set namespace for exposed private names
+DTensor.__module__ = "torch.distributed.tensor"
+distribute_tensor.__module__ = "torch.distributed.tensor"
+distribute_module.__module__ = "torch.distributed.tensor"
+ones.__module__ = "torch.distributed.tensor"
+empty.__module__ = "torch.distributed.tensor"
+full.__module__ = "torch.distributed.tensor"
+rand.__module__ = "torch.distributed.tensor"
+randn.__module__ = "torch.distributed.tensor"
+zeros.__module__ = "torch.distributed.tensor"
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a146a23f4ca6aee96b54dc676dc26380c9d10b27
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_api.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_api.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7158d012d721140e120118fd61a7aa4889391a78
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_api.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_collective_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_collective_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e91c28e0662910fba40d6a48ba53c563f7860cd5
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_collective_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_dispatch.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_dispatch.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ac36c747493717c47151214ab138100cba63d8de
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_dispatch.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_dtensor_spec.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_dtensor_spec.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..715b99a0d5f3344a5a5a465b10c79ffd03d85bf9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_dtensor_spec.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_op_schema.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_op_schema.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..320fddbbda4d39a0a4d9410b64206e53b7e6495a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_op_schema.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_random.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_random.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1cd5b11a6be2c7dac6f8fd4cc9f885eb8e812f4c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_random.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_redistribute.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_redistribute.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f0bdce43b57357bcfd4281f37fee6ea255c79cca
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_redistribute.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_sharding_prop.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_sharding_prop.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a9334676eaf7a251e29a0eb1ebe4ffcf8698a0e5
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_sharding_prop.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_shards_wrapper.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_shards_wrapper.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..059620506d77a3957f40181d66a13fdc8bd09791
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_shards_wrapper.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_tp_conv.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_tp_conv.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..173a5145cd24c816ca5a3a1665b572ced5fe467a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_tp_conv.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..76fbf70cfc35d70d8901e3e5d188b20b5c57d262
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/device_mesh.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/device_mesh.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7bc5311126c4a983e127db44bd9098802d59a058
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/device_mesh.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/placement_types.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/placement_types.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..54d1bb2029203eed8aebdb2c86358d4f13e257fe
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/__pycache__/placement_types.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_api.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec2993690e74e20c6cbd024a760baeb090541ef3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_api.py
@@ -0,0 +1,1231 @@
+# mypy: allow-untyped-decorators
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and affiliates
+import inspect
+import warnings
+from typing import Any, Callable, cast, Optional, Sequence, Tuple
+
+import torch
+import torch.distributed.tensor._dispatch as op_dispatch
+import torch.distributed.tensor._random as random
+import torch.nn as nn
+from torch.distributed.device_mesh import _mesh_resources, DeviceMesh
+from torch.distributed.tensor._collective_utils import check_tensor_meta, mesh_broadcast
+from torch.distributed.tensor._dtensor_spec import DTensorSpec, TensorMeta
+from torch.distributed.tensor._random import (
+    is_rng_supported_mesh,
+    OffsetBasedRNGTracker,
+)
+from torch.distributed.tensor._redistribute import (
+    Redistribute,
+    redistribute_local_tensor,
+)
+from torch.distributed.tensor._utils import (
+    compute_global_tensor_info,
+    compute_local_shape,
+    normalize_to_torch_size,
+)
+from torch.distributed.tensor.placement_types import (
+    Partial,
+    Placement,
+    Replicate,
+    Shard,
+)
+
+
+__all__ = [
+    "DTensor",
+    "distribute_tensor",
+    "distribute_module",
+    "ones",
+    "empty",
+    "full",
+    "rand",
+    "randn",
+    "zeros",
+]
+
+aten = torch.ops.aten
+
+
+# NOTE [Autograd interaction between torch.Tensor]
+#
+# The autograd functions defined below are being used by the public
+# facing APIs (i.e. from_local, to_local) to ensure DTensor to work
+# together with torch.Tensor within the autograd engine. This
+# allows DTensor to only exist on part of the module hierarchy.
+#
+# As an example, we have the a module that consists of submodules
+# A, B, and C, the execution flow would be like:
+#  input(torch.Tensor) -> Module A -> Module B -> Module C -> output (torch.Tensor)
+#
+# Suppose I only want to make Module B be a sharded module with
+# DTensor params, the following forward/backward should work:
+#
+#  input(torch.Tensor) -> Module A
+#       -> DTensor input (from_local) -> Sharded Module B -> DTensor output
+#           -> torch.Tensor output (to_local) -> Module C
+#
+# So from_local/to_local must be Autograd functions.
+#
+class _ToTorchTensor(torch.autograd.Function):
+    @staticmethod
+    def forward(  # type: ignore[override]
+        ctx,
+        input: "DTensor",
+        grad_placements: Optional[Sequence[Placement]],
+    ):
+        ctx.dtensor_spec = input._spec
+        ctx.grad_placements = grad_placements
+        local_tensor = input._local_tensor
+
+        # We need to return a fresh Tensor object there as autograd metadata
+        # will be inplaced into it. So we don't want to pollute the Tensor
+        # object stored in the _local_tensor of this DTensor.
+        return local_tensor.view_as(local_tensor)
+
+    @staticmethod
+    def backward(ctx, grad_output: torch.Tensor):  # type: ignore[override]
+        dtensor_spec = ctx.dtensor_spec
+        mesh = dtensor_spec.mesh
+        grad_placements = ctx.grad_placements
+        dtensor_meta = dtensor_spec.tensor_meta
+
+        _, tensor_stride = compute_global_tensor_info(
+            grad_output, mesh, dtensor_spec.placements
+        )
+        tensor_stride = tuple(tensor_stride)
+        grad_placements = grad_placements or dtensor_spec.placements
+        grad_spec = DTensorSpec(
+            mesh,
+            grad_placements,
+            tensor_meta=TensorMeta(
+                shape=dtensor_meta.shape,
+                stride=tensor_stride,
+                dtype=dtensor_meta.dtype,
+            ),
+        )
+
+        return (
+            DTensor(
+                grad_output,
+                grad_spec,
+                requires_grad=grad_output.requires_grad,
+            ),
+            None,
+        )
+
+
+class _FromTorchTensor(torch.autograd.Function):
+    @staticmethod
+    def forward(  # type: ignore[override]
+        ctx,  # pyre-ignore[2]: Parameter must be annotated.
+        input: torch.Tensor,
+        device_mesh: DeviceMesh,
+        placements: Tuple[Placement, ...],
+        run_check: bool,
+        shape: Optional[torch.Size] = None,
+        stride: Optional[Tuple[int, ...]] = None,
+    ) -> "DTensor":
+        ctx.previous_placement = placements
+        ctx.previous_device_mesh = device_mesh
+
+        if shape and stride:
+            tensor_shape, tensor_stride = shape, stride
+        elif not shape and not stride:
+            # if it's not by default run_check, we assume user is certain that each
+            # rank has the same tensor shape, and we just use that to calculate the
+            # global shape
+            global_shape, global_stride = compute_global_tensor_info(
+                input, device_mesh, placements
+            )
+            tensor_shape, tensor_stride = torch.Size(global_shape), tuple(global_stride)
+        else:
+            raise RuntimeError(
+                f"Found shape:{shape}, stride:{stride}.",
+                "Please pass both shape and stride at the same time.",
+            )
+
+        if device_mesh.get_coordinate() is None:
+            # if the global rank is not participating in the device mesh, we
+            # simply set the local tensor to an empty tensor
+            input = input.new_empty(0, requires_grad=input.requires_grad)
+        elif run_check:
+            # TODO: support uneven sharding when global shape/stride not passed, by
+            # building the global TensorMeta during check_tensor_meta
+            check_shape_stride = not shape and not stride
+            check_tensor_meta(input, check_shape_stride=check_shape_stride)
+            # TODO: See if we need to make this run_check logic
+            # have a corresponding backward.
+            for idx, placement in enumerate(placements):
+                if placement.is_replicate():
+                    # broadcast rank 0 tensor to all ranks
+                    # only broadcast if run_check is True
+                    input = input.contiguous()
+                    mesh_broadcast(input, device_mesh, mesh_dim=idx)
+
+        dist_spec = DTensorSpec(
+            device_mesh,
+            placements,
+            tensor_meta=TensorMeta(
+                tensor_shape,
+                tensor_stride,
+                input.dtype,
+            ),
+        )
+
+        # We want a fresh Tensor object that shares memory with the input tensor
+        dist_tensor = DTensor(
+            input.view_as(input),
+            dist_spec,
+            # requires_grad of the dist tensor depends on if input
+            # requires_grad or not
+            requires_grad=input.requires_grad,
+        )
+        return dist_tensor
+
+    @staticmethod
+    def backward(ctx, grad_output: "DTensor"):  # type: ignore[override]
+        previous_placement = ctx.previous_placement
+        previous_device_mesh = ctx.previous_device_mesh
+
+        # reshard to the placement when creating DistributedTensor
+        # so that the gradient layout matches, and we could return
+        # local gradients directly
+        if grad_output.placements != previous_placement:
+            current_spec = grad_output._spec
+            target_spec = DTensorSpec(
+                previous_device_mesh,
+                previous_placement,
+                tensor_meta=grad_output._spec.tensor_meta,
+            )
+            local_tensor = grad_output._local_tensor
+            output = redistribute_local_tensor(
+                local_tensor, current_spec, target_spec, is_backward=True
+            )
+            # TODO: return the redistributed local tensor directly without
+            # differentiable backward. see if this make sense for all cases.
+            return output, None, None, None, None, None
+
+        # TODO: backward is also differentiable now, add a test
+        # to test higher level gradients.
+        return grad_output.to_local(), None, None, None, None, None
+
+
+class DTensor(torch.Tensor):
+    """
+    ``DTensor`` (Distributed Tensor) is a subclass of ``torch.Tensor`` that provides single-device like
+    abstraction to program with multi-device ``torch.Tensor``. It describes the distributed tensor sharding
+    layout (DTensor Layout) through the :class:`DeviceMesh` and following types of :class:`Placement`:
+
+    * :class:`Shard`: Tensor sharded on the tensor dimension ``dim`` on the devices of the ``DeviceMesh`` dimension
+    * :class:`Replicate`: Tensor replicated on the devices of the ``DeviceMesh`` dimension
+    * :class:`Partial`: Tensor is pending reduction on the devices of the ``DeviceMesh`` dimension
+
+    When calling PyTorch operators, ``DTensor`` overrides the PyTorch operators to perform sharded computation and issue
+    communications whenever necessary. Along with the operator computation, ``DTensor`` will transform or propagate the
+    placements (DTensor Layout) properly (based on the operator semantic itself) and generate new ``DTensor`` outputs.
+
+    To ensure numerical correctness of the ``DTensor`` sharded computation when calling PyTorch operators, ``DTensor``
+    requires every Tensor argument of the operator be DTensor.
+
+    """
+
+    _local_tensor: torch.Tensor
+    _spec: DTensorSpec
+    __slots__ = ["_local_tensor", "_spec"]
+
+    # _op_dispatcher instance as a class attribute to handle runtime dispatching logic
+    _op_dispatcher: op_dispatch.OpDispatcher = op_dispatch.OpDispatcher()
+
+    @staticmethod
+    @torch._disable_dynamo
+    def __new__(
+        cls,
+        local_tensor: torch.Tensor,
+        spec: DTensorSpec,
+        *,
+        requires_grad: bool,
+    ) -> "DTensor":
+        """
+        Construct a DTensor from a local tensor, device mesh, and placement and
+        other tensor properties (i.e. shape, requires_grad, strides, etc).
+
+        .. note:: This is not a public API and it's only supposed to be used by the
+            operator implementations and internals. If you want to construct a
+            DTensor from a local tensor, consider using ``DTensor.from_local``, if
+            you want to construct a DTensor from a "global" tensor (where you
+            already have tensor initialized and want to shard this tensor),
+            consider using ``distribute_tensor``.
+        """
+        if local_tensor.requires_grad and not requires_grad:
+            warnings.warn(
+                "To construct DTensor from torch.Tensor, it's recommended to "
+                "use local_tensor.detach() and make requires_grad consistent."
+            )
+
+        # new method instruct wrapper tensor from local_tensor and add
+        # placement spec, it does not do actual distribution
+        assert spec.tensor_meta is not None, "TensorMeta should not be None!"
+        r = torch.Tensor._make_wrapper_subclass(  # type: ignore[attr-defined]
+            cls,
+            spec.tensor_meta.shape,
+            strides=spec.tensor_meta.stride,
+            dtype=local_tensor.dtype,
+            device=local_tensor.device,
+            layout=local_tensor.layout,
+            requires_grad=requires_grad,
+        )
+
+        r._spec = spec
+        r._local_tensor = local_tensor
+        return r
+
+    # pyre-fixme[14]: `__repr__` overrides method defined in `DTensor` inconsistently.
+    # pyre-fixme[3]: Return type must be annotated.
+    def __repr__(self):
+        # TODO: consider all_gather the local tensors for better debugging
+        return f"DTensor(local_tensor={self._local_tensor}, device_mesh={self._spec.mesh}, placements={self._spec.placements})"
+
+    def __tensor_flatten__(self):
+        """
+        protocol to inform how to flatten a DTensor to local tensor
+        for PT2 tracing
+        """
+        return ["_local_tensor"], (self._spec, self.requires_grad)
+
+    @staticmethod
+    def __tensor_unflatten__(inner_tensors, flatten_spec, outer_size, outer_stride):
+        assert (
+            flatten_spec is not None
+        ), "Expecting spec to be not None from `__tensor_flatten__` return value!"
+        local_tensor = inner_tensors["_local_tensor"]
+        spec, requires_grad = flatten_spec
+        unflatten_tensor_meta = TensorMeta(
+            shape=outer_size,
+            stride=outer_stride,
+            dtype=spec.tensor_meta.dtype,
+        )
+        unflatten_spec = DTensorSpec(
+            spec.mesh,
+            spec.placements,
+            tensor_meta=unflatten_tensor_meta,
+        )
+        return DTensor(
+            local_tensor,
+            unflatten_spec,
+            requires_grad=requires_grad,
+        )
+
+    def __coerce_tangent_metadata__(self):
+        if not any(isinstance(p, Partial) for p in self.placements):
+            return self
+        placements = [
+            Replicate() if isinstance(p, Partial) else p for p in self.placements
+        ]
+        return self.redistribute(device_mesh=self.device_mesh, placements=placements)
+
+    def __coerce_same_metadata_as_tangent__(self, flatten_spec):
+        (spec, _) = flatten_spec  # Result of tensor_flatten()
+        return self.redistribute(
+            device_mesh=self.device_mesh,
+            placements=spec.placements,
+        )
+
+    @classmethod
+    @torch._disable_dynamo
+    # pyre-fixme[3]: Return type must be annotated.
+    # pyre-fixme[2]: Parameter must be annotated.
+    def __torch_dispatch__(cls, func, types, args=(), kwargs=None):
+        return DTensor._op_dispatcher.dispatch(
+            func,
+            args,
+            kwargs or {},
+        )
+
+    @staticmethod
+    def from_local(
+        local_tensor: torch.Tensor,
+        device_mesh: Optional[DeviceMesh] = None,
+        placements: Optional[Sequence[Placement]] = None,
+        *,
+        run_check: bool = False,
+        shape: Optional[torch.Size] = None,
+        stride: Optional[Tuple[int, ...]] = None,
+    ) -> "DTensor":
+        """
+        Create a :class:`DTensor` from a local torch.Tensor on each rank
+        according to the ``device_mesh`` and ``placements`` specified.
+
+        Args:
+            local_tensor (torch.Tensor): local torch.Tensor on each rank.
+            device_mesh (:class:`DeviceMesh`, optional): DeviceMesh to place the
+                tensor, if not specified, must be called under a DeviceMesh
+                context manager, default: None
+            placements (List[:class:`Placement`], optional): the placements that
+                describes how to place the local torch.Tensor on DeviceMesh, must
+                have the same number of elements as ``device_mesh.ndim``.
+
+        Keyword args:
+            run_check (bool, optional): at a cost of extra communications, perform
+                sanity check across ranks to check each local tensor's meta information
+                to ensure correctness. If have :class:`Replicate` in ``placements``, the
+                data on first rank of the device mesh dimension will be broadcasted
+                to other ranks. default: False
+            shape (torch.Size, optional): A List of int which specifies the size of
+                DTensor which build on top of `local_tensor`. Note this needs to be
+                provided if the shape of ``local_tensor`` are different across the ranks.
+                If not provided, ``shape`` will be computed assuming the given distributed
+                tensor is evenly sharded across ranks. default: None
+            stride (tuple, optional): A List of int which specifies the stride of DTensor.
+                If not provided, ``stride`` will be computed assuming the given distributed
+                tensor is evenly sharded across ranks. default: None
+
+        Returns:
+            A :class:`DTensor` object
+
+        .. note:: When ``run_check=False``, it is the user's responsibility to ensure the
+            local tensor passed in is correct across ranks (i.e. the tensor is sharded for
+            the ``Shard(dim)`` placement or replicated for the ``Replicate()`` placement).
+            If not, the behavior of the created DTensor is undefined.
+
+        .. note:: ``from_local`` is differentiable, the `requires_grad` of the created
+            `DTensor` object will depend on if `local_tensor` requires_grad or not.
+        """
+        # if same shape/dtype, no need to run_check, if not, must allgather
+        # the metadatas to check the size/dtype across ranks
+        # There should be no data communication unless there's replication
+        # strategy, where we broadcast the replication from the first rank
+        # in the mesh dimension
+        device_mesh = device_mesh or _mesh_resources.get_current_mesh()
+        device_type = device_mesh.device_type
+
+        # convert the local tensor to desired device base on device mesh's device_type
+        if device_type != local_tensor.device.type and not local_tensor.is_meta:
+            local_tensor = local_tensor.to(device_type)
+
+        # set default placements to replicated if not specified
+        if placements is None:
+            placements = [Replicate() for _ in range(device_mesh.ndim)]
+        else:
+            placements = list(placements)
+            for idx, placement in enumerate(placements):
+                # normalize shard dim to be positive
+                if placement.is_shard():
+                    placement = cast(Shard, placement)
+                    if placement.dim < 0:
+                        placements[idx] = Shard(placement.dim + local_tensor.ndim)
+
+        # `from_local` is differentiable, and the gradient of the dist tensor this function
+        # created should flow back the gradients to the local_tensor, so we call an autograd
+        # function to construct the dist tensor instead.
+        return _FromTorchTensor.apply(  # pyre-ignore[16]: autograd func
+            local_tensor,
+            device_mesh,
+            tuple(placements),
+            run_check,
+            shape,
+            stride,
+        )
+
+    def to_local(
+        self, *, grad_placements: Optional[Sequence[Placement]] = None
+    ) -> torch.Tensor:
+        """
+        Get the local tensor of this DTensor on its current rank. For sharding it returns
+        a local shard of the logical tensor view, for replication it returns the replica on
+        its current rank.
+
+        Keyword args:
+            grad_placements (List[:class:`Placement`], optional): the placements describes
+                the future layout of any gradient layout of the Tensor returned from this
+                function.
+                `to_local` converts DTensor to local tensor and the returned local tensor
+                might not be used as the original DTensor layout later in the code. This
+                argument is the hint that user can give to autograd in case the gradient
+                layout of the returned tensor does not match the original DTensor layout.
+                If not specified, we will assume the gradient layout remains the same
+                as the original DTensor and use that for gradient computation.
+
+        Returns:
+            A :class:`torch.Tensor` or ``AsyncCollectiveTensor`` object. it represents the
+            local tensor on its current rank. When an ``AsyncCollectiveTensor`` object is returned,
+            it means the local tensor is not ready yet (i.e. communication is not finished). In this
+            case, user needs to call ``wait`` to wait the local tensor to be ready.
+
+        .. note:: ``to_local`` is differentiable, the ``requires_grad`` of the local tensor returned
+            will depend on if the `DTensor` requires_grad or not.
+        """
+        if not torch.is_grad_enabled():
+            return self._local_tensor
+
+        if grad_placements is not None and not isinstance(grad_placements, tuple):
+            grad_placements = tuple(grad_placements)
+        return _ToTorchTensor.apply(
+            self, grad_placements
+        )  # pyre-ignore[16]: autograd func
+
+    def redistribute(
+        self,
+        device_mesh: Optional[DeviceMesh] = None,
+        placements: Optional[Sequence[Placement]] = None,
+        *,
+        async_op: bool = False,
+    ) -> "DTensor":
+        """
+        ``redistribute`` performs necessary collective operations that redistribute the current
+        DTensor from its current placements to a new placements, or from is current DeviceMesh
+        to a new DeviceMesh. i.e. we can turn a Sharded DTensor to a Replicated DTensor by
+        specifying a Replicate placement for each dimension of the DeviceMesh.
+
+        When redistributing from current to the new placements on one device mesh dimension, we
+        will perform the following operations including communication collective or local operation:
+
+        1. ``Shard(dim)`` -> ``Replicate()``: ``all_gather``
+        2. ``Shard(src_dim)`` -> ``Shard(dst_dim)``: ``all_to_all``
+        3. ``Replicate()`` -> ``Shard(dim)``: local chunking (i.e. ``torch.chunk``)
+        4. ``Partial()`` -> ``Replicate()``: ``all_reduce``
+        5. ``Partial()`` -> ``Shard(dim)``: ``reduce_scatter``
+
+
+        ``redistribute`` would correctly figure out the necessary redistribute steps for DTensors
+        that are created either on 1-D or N-D DeviceMesh.
+
+        Args:
+            device_mesh (:class:`DeviceMesh`, optional): DeviceMesh to place the
+                DTensor. If not specified, it would use the current DTensor's DeviceMesh.
+                default: None
+            placements (List[:class:`Placement`], optional): the new placements that
+                describes how to place the DTensor into the DeviceMesh, must
+                have the same number of elements as ``device_mesh.ndim``.
+                default: replicate on all mesh dimensions
+
+        Keyword args:
+            async_op (bool, optional): whether to perform the DTensor redistribute operation
+                asynchronously or not. Default: False
+
+        Returns:
+            A :class:`DTensor` object
+
+        .. note:: ``redistribute`` is differentiable, which means user do not need to worry about
+            the backward formula of the redistribute operation.
+
+        .. note:: ``redistribute`` currently only supports redistributing DTensor on the same DeviceMesh,
+            Please file an issue if you need to redistribute DTensor to different DeviceMesh.
+        """
+        # NOTE: This redistribute API currently only supports out
+        # of place redistribution, i.e. it always create a new
+        # DTensor object and leave the original one unchanged.
+
+        # if device_mesh is not specified, use the current device_mesh
+        device_mesh = device_mesh or self.device_mesh
+        # raise error if new placements not specified
+        if placements is None:
+            raise RuntimeError("placements is needed for redistribute!")
+
+        placements = list(placements)
+        for i, placement in enumerate(placements):
+            if placement.is_partial():
+                raise RuntimeError(
+                    "Can not redistribute to Partial, redistributing to Partial is for internal use only!"
+                )
+            elif isinstance(placement, Shard) and placement.dim < 0:
+                # normalize shard dim to be positive
+                placements[i] = Shard(placement.dim + self.ndim)
+        placements = tuple(placements)
+
+        # pyre-fixme[16]: `Redistribute` has no attribute `apply`.
+        return Redistribute.apply(self, device_mesh, placements, async_op)
+
+    def full_tensor(
+        self, *, grad_placements: Optional[Sequence[Placement]] = None
+    ) -> torch.Tensor:
+        """
+        Return the full tensor of this DTensor. It will perform necessary collectives
+        to gather the local tensors from other ranks in its DeviceMesh and concatenate
+        them together. It's a syntatic sugar of the following code:
+
+        ``dtensor.redistribute(placements=[Replicate()] * mesh.ndim).to_local()``
+
+        Keyword args:
+            grad_placements (List[:class:`Placement`], optional): the placements describes
+                the future layout of any gradient layout of the full Tensor returned from this
+                function.
+                `full_tensor` converts DTensor to a full torch.Tensor and the returned torch.tensor
+                might not be used as the original replicated DTensor layout later in the code. This
+                argument is the hint that user can give to autograd in case the gradient
+                layout of the returned tensor does not match the original replicated DTensor layout.
+                If not specified, we will assume the gradient layout of the full tensor be replicated.
+
+        Returns:
+            A :class:`torch.Tensor` object that represents the full tensor of this DTensor.
+
+        .. note:: ``full_tensor`` is differentiable.
+        """
+
+        redist_res = self.redistribute(
+            placements=[Replicate()] * self.device_mesh.ndim, async_op=False
+        )
+        return _ToTorchTensor.apply(redist_res, grad_placements)
+
+    @property
+    def device_mesh(self) -> DeviceMesh:
+        """
+        The :class:`DeviceMesh` attribute that associates with this DTensor object.
+
+        .. note:: ``device_mesh`` is a read-only property, it can not be set.
+        """
+        return self._spec.mesh
+
+    @property
+    def placements(self) -> Tuple[Placement, ...]:
+        """
+        The placements attribute of this DTensor that describes the layout of this
+        DTensor on the its DeviceMesh.
+
+        .. note:: ``placements`` is a read-only property, it can not be set.
+        """
+        return self._spec.placements
+
+    def __create_write_items__(self, fqn: str, object: Any):
+        from torch.distributed.checkpoint.planner_helpers import (
+            _create_write_items_for_dtensor,
+        )
+
+        if hasattr(self._local_tensor, "__create_write_items__"):
+            return self._local_tensor.__create_write_items__(fqn, object)  # type: ignore[attr-defined]
+        elif isinstance(self._local_tensor, torch.Tensor):
+            return [_create_write_items_for_dtensor(fqn, object)]
+        else:
+            raise RuntimeError("Unsupported tensor type!")
+
+    def __create_chunk_list__(self):
+        from torch.distributed.checkpoint.planner_helpers import (
+            _create_chunk_from_dtensor,
+        )
+
+        if hasattr(self._local_tensor, "__create_chunk_list__"):
+            return self._local_tensor.__create_chunk_list__()  # type: ignore[attr-defined]
+        elif isinstance(self._local_tensor, torch.Tensor):
+            return [_create_chunk_from_dtensor(self)]
+        else:
+            raise RuntimeError("Unsupported tensor type!")
+
+    def __get_tensor_shard__(self, index):
+        if hasattr(self._local_tensor, "__get_tensor_shard__"):
+            return self._local_tensor.__get_tensor_shard__(index)  # type: ignore[attr-defined]
+        elif isinstance(self._local_tensor, torch.Tensor):
+            return self.to_local()
+        else:
+            raise RuntimeError("Unsupported tensor type!")
+
+
+def distribute_tensor(
+    tensor: torch.Tensor,
+    device_mesh: Optional[DeviceMesh] = None,
+    placements: Optional[Sequence[Placement]] = None,
+) -> DTensor:
+    """
+    Distribute a leaf ``torch.Tensor`` (i.e. nn.Parameter/buffers) to the ``device_mesh`` according
+    to the ``placements`` specified. The rank of ``device_mesh`` and ``placements`` must be the
+    same. The ``tensor`` to distribute is the logical or "global" tensor, and the API would use
+    the ``tensor`` from first rank of the DeviceMesh dimension as the source of truth to perserve
+    the single-device semantic. If you want to construct a DTensor in the middle of the Autograd
+    computation, please use :meth:`DTensor.from_local` instead.
+
+    Args:
+        tensor (torch.Tensor): torch.Tensor to be distributed. Note that if you
+            want to shard a tensor on a dimension that is not evenly divisible by
+            the number of devices in that mesh dimension, we use ``torch.chunk``
+            semantic to shard the tensor and scatter the shards. The uneven sharding
+            behavior is experimental and subject to change.
+        device_mesh (:class:`DeviceMesh`, optional): DeviceMesh to distribute the
+            tensor, if not specified, must be called under a DeviceMesh context
+            manager, default: None
+        placements (List[:class:`Placement`], optional): the placements that
+            describes how to place the tensor on DeviceMesh, must have the same
+            number of elements as ``device_mesh.ndim``. If not specified, we will
+            by default replicate the tensor across the ``device_mesh`` from the
+            first rank of each dimension of the `device_mesh`.
+
+    Returns:
+        A :class:`DTensor` or ``XLAShardedTensor`` object.
+
+    .. note::
+        When initialize the DeviceMesh with the ``xla`` device_type, ``distribute_tensor``
+        return `XLAShardedTensor` instead. see `this issue `__
+        for more details. The XLA integration is experimental and subject to change.
+    """
+
+    torch._C._log_api_usage_once("torch.dtensor.distribute_tensor")
+
+    # get default device mesh if there's nothing specified
+    device_mesh = device_mesh or _mesh_resources.get_current_mesh()
+    device_type = device_mesh.device_type
+    if device_type == "xla":
+        try:
+            # call PyTorch/XLA SPMD for `xla` backend type device mesh.
+            # This returns XLAShardedTensor
+            from torch_xla.distributed.spmd import (  # type:ignore[import]
+                xla_distribute_tensor,
+            )
+
+            return xla_distribute_tensor(
+                tensor, device_mesh, placements
+            )  # type:ignore[return-value]
+        except ImportError as e:
+            msg = "To use DTensor API with xla, you must install the torch_xla package!"
+            raise ImportError(msg) from e
+
+    # instantiate a RNG tracker if haven't. By default DTensor uses an
+    # OffsetBasedRNGTracker to perform random operators.
+    # TODO: the value assignment to global variable is not the ideal solution
+    # we can replace it in future.
+    if not random._rng_tracker and is_rng_supported_mesh(device_mesh):
+        random._rng_tracker = OffsetBasedRNGTracker(device_type)
+
+    if not tensor.is_leaf:
+        raise RuntimeError(
+            "`distribute_tensor` should be used to distribute leaf tensors! but found non-leaf tensor!"
+        )
+
+    # convert tensor to the corresponding device type if it's not in that device type
+    if device_type != tensor.device.type and not tensor.is_meta:
+        tensor = tensor.to(device_type)
+
+    # set default placements to replicated if not specified
+    if placements is None:
+        placements = [Replicate() for _ in range(device_mesh.ndim)]
+
+    if len(placements) != device_mesh.ndim:
+        raise ValueError(
+            f"`placements` must have the same length as `device_mesh.ndim`! "
+            f"Found placements length: {len(placements)}, and device_mesh.ndim: {device_mesh.ndim}."
+        )
+    if isinstance(tensor, DTensor):
+        # if the tensor is already a DTensor, we need to check:
+        # 1. if the we can further shard this DTensor if the two device mesh belong to
+        #   the same parenet mesh and further sharding is possible.
+        # 2. check if device mesh and placements are the same
+        if tensor.device_mesh != device_mesh:
+            raise ValueError(
+                f"Cannot distribute a DTensor with device mesh {tensor.device_mesh} "
+                f"to a different device mesh {device_mesh}."
+            )
+        if tensor.placements != tuple(placements):
+            raise ValueError(
+                f"Cannot distribute a DTensor with placements {tensor.placements} "
+                f"to a different placements {placements}. do you want to call "
+                f"`redistribute` instead?"
+            )
+        return tensor
+
+    local_tensor = tensor.detach()
+
+    # TODO(xilun): address sharding order
+    # distribute the tensor according to the placements.
+    placements = list(placements)
+    for idx, placement in enumerate(placements):
+        if placement.is_shard():
+            placement = cast(Shard, placement)
+            if placement.dim < 0:
+                # normalize shard placement dim
+                placement = Shard(placement.dim + tensor.ndim)
+                placements[idx] = placement
+            local_tensor = placement._shard_tensor(local_tensor, device_mesh, idx)
+        elif placement.is_replicate():
+            placement = cast(Replicate, placement)
+            local_tensor = placement._replicate_tensor(local_tensor, device_mesh, idx)
+        else:
+            raise RuntimeError(
+                f"Trying to distribute tensor with unsupported placements {placement} on device mesh dimension {idx}!"
+            )
+    placements = tuple(placements)
+
+    assert local_tensor is not None, "distributing a tensor should not be None"
+    # detach the local tensor passed to DTensor since after the construction
+    # of DTensor, autograd would work on top of DTensor instead of local tensor
+    spec = DTensorSpec(
+        mesh=device_mesh,
+        placements=placements,
+        tensor_meta=TensorMeta(
+            shape=tensor.size(),
+            stride=tensor.stride(),
+            dtype=tensor.dtype,
+        ),
+    )
+    return DTensor(
+        local_tensor.requires_grad_(tensor.requires_grad),
+        spec,
+        requires_grad=tensor.requires_grad,
+    )
+
+
+def distribute_module(
+    module: nn.Module,
+    device_mesh: Optional[DeviceMesh] = None,
+    partition_fn: Optional[Callable[[str, nn.Module, DeviceMesh], None]] = None,
+    input_fn: Optional[Callable[[nn.Module, Any, DeviceMesh], None]] = None,
+    output_fn: Optional[Callable[[nn.Module, Any, DeviceMesh], None]] = None,
+) -> nn.Module:
+    """
+    This function expose three functions to control the parameters/inputs/outputs of the module:
+
+    1. To perform sharding on the module before runtime execution by specifying the
+    ``partition_fn`` (i.e. allow user to convert Module parameters to :class:`DTensor`
+    parameters according to the `partition_fn` specified).
+    2. To control the inputs or outputs of the module during runtime execution by
+    specifying the ``input_fn`` and ``output_fn``. (i.e. convert the input to
+    :class:`DTensor`, convert the output back to ``torch.Tensor``)
+
+    Args:
+        module (:class:`nn.Module`): user module to be partitioned.
+        device_mesh (:class:`DeviceMesh`): the device mesh to place the module.
+        partition_fn (Callable): the function to partition parameters (i.e. shard certain
+            parameters across the ``device_mesh``). If ``partition_fn`` is not specified,
+            by default we replicate all module parameters of ``module`` across the mesh.
+        input_fn (Callable): specify the input distribution, i.e. could control how the
+            input of the module is sharded. ``input_fn`` will be installed as a module
+            ``forward_pre_hook`` (pre forward hook).
+        output_fn (Callable): specify the output distribution, i.e. could control how the
+            output is sharded, or convert it back to torch.Tensor. ``output_fn`` will be
+            installed as a module ``forward_hook`` (post forward hook).
+
+    Returns:
+        A module that contains parameters/buffers that are all ``DTensor`` s.
+
+    .. note::
+        When initialize the DeviceMesh with the ``xla`` device_type, ``distribute_module``
+        return nn.Module with PyTorch/XLA SPMD annotated parameters. See
+        `this issue `__
+        for more details. The XLA integration is experimental and subject to change.
+
+    """
+
+    torch._C._log_api_usage_once("torch.dtensor.distribute_module")
+
+    device_mesh = device_mesh or _mesh_resources.get_current_mesh()
+    device_type = device_mesh.device_type
+    if device_type == "xla":
+        try:
+            # This function annotates all module parameters for auto-partitioning with
+            # PyTorch/XLA SPMD or explicitly partition to :class:`XLAShardedTensor` parameters
+            # according to the `partition_fn` specified.
+            from torch_xla.distributed.spmd import (  # type:ignore[import]
+                xla_distribute_module,
+            )
+
+            return xla_distribute_module(
+                module, device_mesh, partition_fn, input_fn, output_fn
+            )  # type:ignore[return-value]
+        except ImportError as e:
+            msg = "To use DTensor API with xla, you must install the torch_xla package!"
+            raise ImportError(msg) from e
+
+    def replicate_module_params_buffers(m: nn.Module, mesh: DeviceMesh) -> None:
+        # This function loop over the immediate module parameters and
+        # buffers, replicate all non DTensor params/buffers to DTensor
+        # parameters/buffers, if they have not been partitioned in the
+        # partition_fn, we can't easily use `module._apply` here
+        # because we don't know what happened inside partition_fn as
+        # user could do anything, i.e. install hooks, and we want to
+        # preserve those.
+        full_replicate = [Replicate()] * mesh.ndim
+        for key, param in m._parameters.items():
+            if param is not None and not isinstance(param, DTensor):
+                m.register_parameter(
+                    key,
+                    nn.Parameter(distribute_tensor(param.data, mesh, full_replicate)),
+                )
+        for key, buffer in m._buffers.items():
+            if buffer is not None and not isinstance(buffer, DTensor):
+                m._buffers[key] = distribute_tensor(buffer, mesh, full_replicate)
+
+    if partition_fn is None:
+        # if partition_fn not specified, we by default replicate
+        # all module params/buffers
+        for name, submod in module.named_modules():
+            replicate_module_params_buffers(submod, device_mesh)
+    else:
+        # apply partition_fun to submodules
+        for name, submod in module.named_modules():
+            partition_fn(name, submod, device_mesh)
+            replicate_module_params_buffers(submod, device_mesh)
+
+    # register input_fn as module forward pre hook
+    if input_fn is not None:
+        # check the input_fn signature
+        num_args = len(inspect.signature(input_fn).parameters)
+        if num_args == 2:
+            # input_fn only takes in inputs and device mesh
+            warnings.warn(
+                "Deprecating input_fn that takes two arguments (inputs, device_mesh), "
+                "please use input_fn that takes in (module, inputs, device_mesh) instead!",
+                FutureWarning,
+                stacklevel=2,
+            )
+            module.register_forward_pre_hook(lambda _, inputs: input_fn(inputs, device_mesh))  # type: ignore[call-arg]
+        elif num_args == 3:
+            # input_fn takes in module, inputs, device mesh
+            module.register_forward_pre_hook(
+                lambda mod, inputs: input_fn(mod, inputs, device_mesh)
+            )
+        else:
+            raise ValueError(
+                f"input_fn should take in 3 arguments, but got {num_args} arguments!"
+            )
+    # register output_fn as module forward hook
+    if output_fn is not None:
+        num_args = len(inspect.signature(output_fn).parameters)
+        if num_args == 2:
+            # output_fn only takes in outputs and device mesh
+            warnings.warn(
+                "Deprecating output_fn that takes two arguments (inputs, device_mesh), "
+                "please use output_fn that takes in (module, inputs, device_mesh) instead!",
+                FutureWarning,
+                stacklevel=2,
+            )
+            module.register_forward_hook(
+                lambda mod, inputs, outputs: output_fn(outputs, device_mesh)  # type: ignore[call-arg]
+            )
+        elif num_args == 3:
+            module.register_forward_hook(
+                lambda mod, inputs, outputs: output_fn(mod, outputs, device_mesh)
+            )
+        else:
+            raise ValueError(
+                f"output_fn should take in 3 arguments, but got {num_args} arguments!"
+            )
+
+    return module
+
+
+# Below are tensor factory function APIs, which are used to create a DTensor directly. We need
+# to make separate factory function APIs because tensor subclass could not override the tensor
+# factory methods, and we need user to call the factory functions with user intended device_mesh
+# and placements to create a proper DTensor.
+
+
+def _dtensor_init_helper(  # type: ignore[no-untyped-def]
+    init_op,
+    size: torch.Size,
+    device_mesh: Optional[DeviceMesh] = None,
+    placements: Optional[Sequence[Placement]] = None,
+    **kwargs,
+) -> DTensor:
+    # from torch.distributed._tensor.placement_types import DTensorSpec, TensorMeta
+
+    # if device_mesh is None, use the one from mesh resources
+    device_mesh = device_mesh or _mesh_resources.get_current_mesh()
+    kwargs["device"] = device_mesh.device_type
+
+    # set default placements to replicated if not specified
+    placements = placements or tuple(Replicate() for _ in range(device_mesh.ndim))
+
+    # check device_mesh againts placements
+    assert device_mesh.ndim == len(
+        placements
+    ), "mesh dimension does not match the length of placements"
+
+    assert kwargs["layout"] == torch.strided, "layout value not supported!"
+    torch_stride = torch._prims_common.make_contiguous_strides_for(size)
+
+    # get local tensor shape
+    local_shape = compute_local_shape(size, device_mesh, placements)
+    # initialize the local tensor
+    if init_op == torch.full:
+        fill_value = kwargs.pop("fill_value", 0)
+        local_tensor = init_op(local_shape, fill_value, **kwargs)
+    elif init_op == torch.rand or init_op == torch.randn:
+        # this tensor meta is not used except `shape`
+        dtype = kwargs.get("dtype", torch.get_default_dtype())
+
+        tensor_meta = TensorMeta(size, (0,), dtype)
+        spec = DTensorSpec(device_mesh, tuple(placements), tensor_meta=tensor_meta)
+
+        if random.is_rng_supported_mesh(device_mesh) and not random._rng_tracker:
+            random._rng_tracker = random.OffsetBasedRNGTracker()
+
+        assert random._rng_tracker is not None
+        with random._rng_tracker._distribute_region(spec):
+            local_tensor = init_op(local_shape, **kwargs)
+    else:
+        local_tensor = init_op(local_shape, **kwargs)
+
+    spec = DTensorSpec(
+        device_mesh,
+        tuple(placements),
+        tensor_meta=TensorMeta(
+            size,
+            torch_stride,
+            local_tensor.dtype,
+        ),
+    )
+
+    return DTensor(
+        local_tensor,
+        spec,
+        requires_grad=kwargs["requires_grad"],
+    )
+
+
+def ones(  # type: ignore[no-untyped-def]
+    *size,
+    dtype: Optional[torch.dtype] = None,
+    layout: torch.layout = torch.strided,
+    requires_grad: bool = False,
+    device_mesh: Optional[DeviceMesh] = None,
+    placements: Optional[Sequence[Placement]] = None,
+) -> DTensor:
+    """
+    Returns a :class:`DTensor` filled with the scalar value 1, with the shape defined
+    by the variable argument ``size``.
+
+    Args:
+        size (int...): a sequence of integers defining the shape of the output :class:`DTensor`.
+            Can be a variable number of arguments or a collection like a list or tuple.
+            E.g.: ones(1,2,3..) or ones([1,2,3..]) or ones((1,2,3..))
+
+    Keyword args:
+        dtype (:class:`torch.dtype`, optional): the desired data type of returned :class:`DTensor`.
+            Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).
+        layout (:class:`torch.layout`, optional): the desired layout of returned DTensor.
+            Default: ``torch.strided``.
+        requires_grad (bool, optional): If autograd should record operations on the
+            returned :class:`DTensor`. Default: ``False``.
+        device_mesh: :class:`DeviceMesh` type, contains the mesh info of ranks
+        placements: a sequence of :class:`Placement` type: ``Shard``, ``Replicate``
+
+    Returns:
+        A :class:`DTensor` object on each rank
+    """
+    torch_size = normalize_to_torch_size(size)
+
+    return _dtensor_init_helper(
+        torch.ones,
+        torch_size,
+        dtype=dtype,
+        layout=layout,
+        requires_grad=requires_grad,
+        device_mesh=device_mesh,
+        placements=placements,
+    )
+
+
+def empty(  # type: ignore[no-untyped-def]
+    *size,
+    dtype: Optional[torch.dtype] = None,
+    layout: torch.layout = torch.strided,
+    requires_grad: bool = False,
+    device_mesh: Optional[DeviceMesh] = None,
+    placements: Optional[Sequence[Placement]] = None,
+) -> DTensor:
+    """
+    Returns a :class:`DTensor` filled with uninitialized data. The shape of the :class:`DTensor`
+    is defined by the variable argument ``size``.
+
+    Args:
+        size (int...): a sequence of integers defining the shape of the output :class:`DTensor`.
+            Can be a variable number of arguments or a collection like a list or tuple.
+            E.g.: empty(1,2,3..) or empty([1,2,3..]) or empty((1,2,3..))
+
+    Keyword args:
+        dtype (:class:`torch.dtype`, optional): the desired data type of returned :class:`DTensor`.
+            Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).\
+        layout (:class:`torch.layout`, optional): the desired layout of returned :class:`DTensor`.
+            Default: ``torch.strided``.
+        requires_grad (bool, optional): If autograd should record operations on the
+            returned :class:`DTensor`. Default: ``False``.
+        device_mesh: :class:`DeviceMesh` type, contains the mesh info of ranks
+        placements: a sequence of :class:`Placement` type: ``Shard``, ``Replicate``
+
+    Returns:
+        A :class:`DTensor` object on each rank
+    """
+    torch_size = normalize_to_torch_size(size)
+
+    return _dtensor_init_helper(
+        torch.empty,
+        torch_size,
+        dtype=dtype,
+        layout=layout,
+        requires_grad=requires_grad,
+        device_mesh=device_mesh,
+        placements=placements,
+    )
+
+
+def full(  # type: ignore[no-untyped-def]
+    size,
+    fill_value,
+    *,
+    dtype: Optional[torch.dtype] = None,
+    layout: torch.layout = torch.strided,
+    requires_grad: bool = False,
+    device_mesh: Optional[DeviceMesh] = None,
+    placements: Optional[Sequence[Placement]] = None,
+) -> DTensor:
+    """
+    Returns a :class:`DTensor` filled with ``fill_value`` according to ``device_mesh`` and
+    ``placements``, with the shape defined by the argument ``size``.
+
+    Args:
+        size (int...): a sequence of integers defining the shape of the output :class:`DTensor`.
+            Can be a variable number of arguments or a collection like a list or tuple.
+            E.g.: ones(1,2,3..) or ones([1,2,3..]) or ones((1,2,3..))
+        fill_value(Scalar): the value to fill the output tensor with.
+
+    Keyword args:
+        dtype (:class:`torch.dtype`, optional): the desired data type of returned :class:`DTensor`.
+            Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).
+        layout (:class:`torch.layout`, optional): the desired layout of returned DTensor.
+            Default: ``torch.strided``.
+        requires_grad (bool, optional): If autograd should record operations on the
+            returned :class:`DTensor`. Default: ``False``.
+        device_mesh: :class:`DeviceMesh` type, contains the mesh info of ranks.
+        placements: a sequence of :class:`Placement` type: ``Shard``, ``Replicate``
+
+    Returns:
+        A :class:`DTensor` object on each rank
+    """
+    torch_size = normalize_to_torch_size(size)
+
+    return _dtensor_init_helper(
+        torch.full,
+        torch_size,
+        fill_value=fill_value,
+        dtype=dtype,
+        layout=layout,
+        requires_grad=requires_grad,
+        device_mesh=device_mesh,
+        placements=placements,
+    )
+
+
+def rand(  # type: ignore[no-untyped-def]
+    *size,
+    requires_grad: bool = False,
+    dtype: Optional[torch.dtype] = None,
+    layout: torch.layout = torch.strided,
+    device_mesh: Optional[DeviceMesh] = None,
+    placements: Optional[Sequence[Placement]] = None,
+) -> DTensor:
+    """
+    Returns a :class:`DTensor` filled with random numbers from a uniform distribution
+    on the interval ``[0, 1)``. The shape of the tensor is defined by the variable
+    argument ``size``.
+
+    Args:
+        size (int...): a sequence of integers defining the shape of the output :class:`DTensor`.
+            Can be a variable number of arguments or a collection like a list or tuple.
+            E.g.: ones(1,2,3..) or ones([1,2,3..]) or ones((1,2,3..))
+
+    Keyword args:
+        dtype (:class:`torch.dtype`, optional): the desired data type of returned :class:`DTensor`.
+            Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).
+        layout (:class:`torch.layout`, optional): the desired layout of returned DTensor.
+            Default: ``torch.strided``.
+        requires_grad (bool, optional): If autograd should record operations on the
+            returned :class:`DTensor`. Default: ``False``.
+        device_mesh: :class:`DeviceMesh` type, contains the mesh info of ranks.
+        placements: a sequence of :class:`Placement` type: ``Shard``, ``Replicate``
+
+    Returns:
+        A :class:`DTensor` object on each rank
+    """
+    torch_size = normalize_to_torch_size(size)
+
+    return _dtensor_init_helper(
+        torch.rand,
+        torch_size,
+        dtype=dtype,
+        layout=layout,
+        requires_grad=requires_grad,
+        device_mesh=device_mesh,
+        placements=placements,
+    )
+
+
+def randn(  # type: ignore[no-untyped-def]
+    *size,
+    requires_grad: bool = False,
+    dtype: Optional[torch.dtype] = None,
+    layout: torch.layout = torch.strided,
+    device_mesh: Optional[DeviceMesh] = None,
+    placements: Optional[Sequence[Placement]] = None,
+) -> DTensor:
+    """
+    Returns a :class:`DTensor` filled with random numbers from a normal distribution
+    with mean 0 and variance 1. The shape of the tensor is defined by the variable
+    argument ``size``.
+
+    Args:
+        size (int...): a sequence of integers defining the shape of the output :class:`DTensor`.
+            Can be a variable number of arguments or a collection like a list or tuple.
+            E.g.: ones(1,2,3..) or ones([1,2,3..]) or ones((1,2,3..))
+
+    Keyword args:
+        dtype (:class:`torch.dtype`, optional): the desired data type of returned :class:`DTensor`.
+            Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).
+        layout (:class:`torch.layout`, optional): the desired layout of returned DTensor.
+            Default: ``torch.strided``.
+        requires_grad (bool, optional): If autograd should record operations on the
+            returned :class:`DTensor`. Default: ``False``.
+        device_mesh: :class:`DeviceMesh` type, contains the mesh info of ranks.
+        placements: a sequence of :class:`Placement` type: ``Shard``, ``Replicate``
+
+    Returns:
+        A :class:`DTensor` object on each rank
+    """
+    torch_size = normalize_to_torch_size(size)
+
+    return _dtensor_init_helper(
+        torch.randn,
+        torch_size,
+        dtype=dtype,
+        layout=layout,
+        requires_grad=requires_grad,
+        device_mesh=device_mesh,
+        placements=placements,
+    )
+
+
+def zeros(  # type: ignore[no-untyped-def]
+    *size,
+    requires_grad: bool = False,
+    dtype: Optional[torch.dtype] = None,
+    layout: torch.layout = torch.strided,
+    device_mesh: Optional[DeviceMesh] = None,
+    placements: Optional[Sequence[Placement]] = None,
+) -> DTensor:
+    """
+    Returns a :class:`DTensor` filled with the scalar value 0.
+
+    Args:
+        size (int...): a sequence of integers defining the shape of the output :class:`DTensor`.
+            Can be a variable number of arguments or a collection like a list or tuple.
+            E.g.: zeros(1,2,3..) or zeros([1,2,3..]) or zeros((1,2,3..))
+    Keyword args:
+        requires_grad (bool, optional): If autograd should record operations on the
+            returned :class:`DTensor`. Default: ``False``.
+        dtype (:class:`torch.dtype`, optional): the desired data type of returned :class:`DTensor`.
+            Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).
+        layout (:class:`torch.layout`, optional): the desired layout of returned :class:`DTensor`.
+            Default: ``torch.strided``.
+        device_mesh: :class:`DeviceMesh` type, contains the mesh info of ranks
+        placements: a sequence of :class:`Placement` type: ``Shard``, ``Replicate``
+
+    Returns:
+        A :class:`DTensor` object on each rank
+    """
+    torch_size = normalize_to_torch_size(size)
+
+    return _dtensor_init_helper(
+        torch.zeros,
+        torch_size,
+        dtype=dtype,
+        layout=layout,
+        requires_grad=requires_grad,
+        device_mesh=device_mesh,
+        placements=placements,
+    )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_collective_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_collective_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..34795858356ab88e973b228998aa8b51d7e7868b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_collective_utils.py
@@ -0,0 +1,373 @@
+# mypy: allow-untyped-defs
+import logging
+import math
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import List, Optional
+
+import torch
+import torch.distributed._functional_collectives as funcol
+import torch.distributed.tensor._dtensor_spec as dtensor_spec
+from torch._C._distributed_c10d import _resolve_process_group
+from torch.distributed.device_mesh import _mesh_resources, DeviceMesh
+from torch.distributed.distributed_c10d import (
+    _get_group_size_by_name,
+    broadcast,
+    get_global_rank,
+    get_group_rank,
+    get_rank,
+    GroupMember,
+    ProcessGroup,
+    scatter,
+    Work,
+)
+
+
+logger = logging.getLogger(__name__)
+
+
+if not torch._running_with_deploy():
+
+    @torch.library.register_fake("_dtensor::shard_dim_alltoall")
+    def _shard_dim_alltoall_meta(input, gather_dim, shard_dim, group_name):
+        group_size = _get_group_size_by_name(group_name)
+        stacked_list = [torch.empty_like(input) for _ in range(group_size)]
+        group = _resolve_process_group(group_name)
+        group_rank = get_group_rank(group, get_rank())
+
+        return torch.cat(stacked_list, dim=gather_dim).chunk(group_size, dim=shard_dim)[
+            group_rank
+        ]
+
+else:
+    import warnings
+
+    warnings.warn(
+        "PyTorch Distributed functional collectives do not work with torch::deploy."
+    )
+
+
+def shard_dim_alltoall(input, gather_dim, shard_dim, mesh, mesh_dim):
+    if mesh.device_type == "cpu":
+        # Gloo does not support alltoall, so falling back to allgather + chunk
+
+        # TODO: This logs way too much
+        logger.warning(
+            "CPU process group does not support alltoall yet, falling back with allgather + chunk!"
+        )
+        out = funcol.all_gather_tensor(input, gather_dim, (mesh, mesh_dim))
+        if isinstance(out, funcol.AsyncCollectiveTensor):
+            # stick to the same behavior for the alltoall case, remove this once we enable alltoall async
+            out = out.wait()
+        out = torch.chunk(out, mesh.size(mesh_dim), dim=shard_dim)[
+            mesh.get_local_rank(mesh_dim)
+        ]
+        return out.contiguous() if not out.is_contiguous() else out
+
+    group_name = funcol._resolve_group_name((mesh, mesh_dim))
+    # TODO: enable async op for shard_dim_alltoall
+    return torch.ops._dtensor.shard_dim_alltoall(
+        input, gather_dim, shard_dim, group_name
+    )
+
+
+def mesh_scatter(
+    output: torch.Tensor,
+    scatter_list: List[torch.Tensor],
+    mesh: DeviceMesh,
+    mesh_dim: int = 0,
+    async_op: bool = False,
+) -> Optional[Work]:
+    """
+    scatter a list of tensors to a device mesh dimension. We by default
+    use the first rank of the mesh dimension as the source of truth, i.e
+    for a 2d mesh [[0, 1], [2, 3]], if we scatter on mesh_dim = 1, we will
+    scatter the tensor list on rank 0 to rank 0/1, and tensor list on rank
+    2 to rank 2/3.
+
+    Args:
+        output (torch.Tensor): the tensor to receive the scattered list.
+        scatter_list (List[torch.Tensor]): the tensor list to be scattered.
+        mesh_dim (int, optional): indicate which mesh dimension we want
+            to scatter on, we by default choose the first rank on the
+            mesh dimension as source of truth.
+
+    Returns:
+        A :class:`Work` object
+    """
+    # TODO: Ideally we should use the meta tensor way
+    # (to register a meta kernel for the collective op)
+    # so that it would avoid the communication. Need to
+    # remove the check below once that is done.
+    if output.is_meta:
+        return None
+    dim_group = mesh.get_group(mesh_dim)
+    assert isinstance(dim_group, ProcessGroup)
+    # src need to be global rank
+    src_for_dim = 0
+
+    if dim_group is not GroupMember.WORLD:
+        src_for_dim = get_global_rank(dim_group, 0)
+
+    if src_for_dim == get_rank():
+        fut = scatter(
+            output,
+            scatter_list=scatter_list,
+            src=src_for_dim,
+            group=dim_group,
+            async_op=async_op,
+        )
+    else:
+        fut = scatter(
+            output,
+            scatter_list=None,
+            src=src_for_dim,
+            group=dim_group,
+            async_op=async_op,
+        )
+
+    return fut
+
+
+def mesh_broadcast(
+    tensor: torch.Tensor,
+    mesh: DeviceMesh,
+    mesh_dim: int = 0,
+    async_op: bool = False,
+) -> Optional[Work]:
+    """
+    broadcast the tensor to a device mesh dimension. We by default
+    use the first rank of the mesh dimension as the source of truth, i.e
+    for a 2d mesh [[0, 1], [2, 3]], if we broadcast on mesh_dim = 1, we will
+    broadcast the tensor on rank 0 to rank 0/1, and tensor on rank 2
+    to rank 2/3.
+
+    Args:
+        tensor (torch.Tensor): tensor to broadcast.
+        mesh_dim (int, optional): indicate which mesh dimension we want
+            to scatter on, we by default choose the first rank on the
+            mesh dimension as source of truth.
+
+    Returns:
+        A :class:`Work` object
+    """
+    # TODO: Ideally we should use the meta tensor way
+    # (to register a meta kernel for the collective op)
+    # so that it would avoid the communication. Need to
+    # remove the check below once that is done.
+    if tensor.is_meta:
+        return None
+    dim_group = mesh.get_group(mesh_dim)
+    assert isinstance(dim_group, ProcessGroup)
+    # src need to be global rank
+    src_for_dim = 0
+    if dim_group is not GroupMember.WORLD:
+        src_for_dim = get_global_rank(dim_group, 0)
+
+    return broadcast(tensor, src=src_for_dim, group=dim_group, async_op=async_op)
+
+
+def pad_tensor(tensor: torch.Tensor, pad_dim: int, pad_size: int) -> torch.Tensor:
+    if pad_size == 0:
+        return tensor
+    pad = [0, 0] * (tensor.ndim - pad_dim)
+    pad[-1] = pad_size
+    return torch.nn.functional.pad(tensor, pad)
+
+
+def unpad_tensor(tensor: torch.Tensor, pad_dim: int, pad_size: int) -> torch.Tensor:
+    if pad_size == 0:
+        return tensor
+    return tensor.narrow(
+        pad_dim,
+        start=0,
+        length=tensor.size(pad_dim) - pad_size,
+    )
+
+
+def fill_empty_tensor_to_shards(
+    shards: List[torch.Tensor], shard_dim: int, num_empty_tensors: int
+) -> List[torch.Tensor]:
+    if num_empty_tensors == 0:
+        return shards
+    tensor_size = list(shards[0].size())
+    tensor_size = [
+        size if idx != shard_dim else 0 for idx, size in enumerate(tensor_size)
+    ]
+    tensor = shards[0].new_zeros(tensor_size)
+    for _ in range(num_empty_tensors):
+        shards.append(tensor)
+    return shards
+
+
+def check_tensor_meta(
+    local_tensor, check_shape_stride=False
+) -> Optional["dtensor_spec.TensorMeta"]:
+    local_metadata = {
+        "dtype": local_tensor.dtype,
+        "requires_grad": local_tensor.requires_grad,
+    }
+
+    if check_shape_stride:
+        local_metadata.update(
+            {"shape": local_tensor.shape, "stride": local_tensor.stride()}
+        )
+
+    gathered_metadata = [None for _ in range(torch.distributed.get_world_size())]
+    torch.distributed.all_gather_object(gathered_metadata, local_metadata)
+
+    # Check if metadata is consistent across ranks
+    if not all(meta == local_metadata for meta in gathered_metadata):
+        raise ValueError(
+            "Inconsistent tensor metadata (including shape and stride) across ranks."
+        )
+    return None
+
+
+def spec_to_bytes(spec: "dtensor_spec.DTensorSpec") -> int:
+    assert spec.tensor_meta is not None, "spec should have tensor meta defined!"
+    return spec.tensor_meta.dtype.itemsize * math.prod(spec.shape)
+
+
+@dataclass
+class MeshTopoInfo:
+    """
+    Mesh information for collective cost estimation
+    """
+
+    mesh: DeviceMesh
+    mesh_dim_devices: List[int]
+    mesh_dim_bandwidth: List[float]
+    mesh_dim_latency: List[float]
+
+    @staticmethod
+    @lru_cache(None)
+    def build_from_mesh(mesh: DeviceMesh) -> "MeshTopoInfo":
+        # Generate mesh topology info for intra-host/inter-host communication pattern
+        # Note that we made bunch of assumptions for simplicity:
+        # 1. we assume the mesh is homogeneous, and it's gpu/nccl model
+        # 2. we assume gpu arch is Ampere or Hopper
+        # 3. we assume collectives are all ring base algo for now
+        num_devices_per_host = _mesh_resources.num_devices_per_host(mesh.device_type)
+        # the base bw number (intra-node), GB/s
+        base_bw = 87.7
+        mesh_dim_bandwidth = [base_bw] * mesh.ndim
+        # the latency in terms of us (intra-node, nv-link)
+        mesh_dim_latency = [0.6] * mesh.ndim
+        mesh_dim_devices = [1] * mesh.ndim
+
+        total_num_devices = 1
+        for mesh_dim in reversed(range(mesh.ndim)):
+            num_devices = mesh.size(mesh_dim)
+            mesh_dim_devices[mesh_dim] = num_devices
+            total_num_devices *= num_devices
+            if total_num_devices > num_devices_per_host:
+                # magic number for inter-host communication bandwidth/latency factor
+                # This number assumes latest GPU arch, i.e. Ampere or Hopper
+                # TODO: see if we need to tweak this or offer a way for user
+                # to specify the bandwidths/latency
+                mesh_dim_bandwidth[mesh_dim] *= 0.22
+                # set to ethernet latency for inter-host
+                mesh_dim_latency[mesh_dim] = 2.7
+
+        return MeshTopoInfo(
+            mesh, mesh_dim_devices, mesh_dim_bandwidth, mesh_dim_latency
+        )
+
+
+def allgather_cost(bytes_gb: float, mesh_topo: MeshTopoInfo, mesh_dim: int) -> float:
+    num_devices_on_mesh_dim = mesh_topo.mesh_dim_devices[mesh_dim]
+    mesh_dim_bandwidth = mesh_topo.mesh_dim_bandwidth[mesh_dim]
+    num_hops = num_devices_on_mesh_dim - 1
+    # base latency + comm latency
+    latency = 6.6 + num_hops * mesh_topo.mesh_dim_latency[mesh_dim]  # us
+    bw = (bytes_gb * num_hops / num_devices_on_mesh_dim) / mesh_dim_bandwidth  # s
+    return latency + bw * 1e6  # rescale to us
+
+
+def allreduce_cost(bytes_gb: float, mesh_topo: MeshTopoInfo, mesh_dim: int) -> float:
+    num_devices_on_mesh_dim = mesh_topo.mesh_dim_devices[mesh_dim]
+    mesh_dim_bandwidth = mesh_topo.mesh_dim_bandwidth[mesh_dim]
+    # allreduce have almost 2x comm bytes compare to allgather/reduce_scatter
+    num_hops = 2 * num_devices_on_mesh_dim - 1
+
+    latency = 6.6 + num_hops * mesh_topo.mesh_dim_latency[mesh_dim]
+    bw = (bytes_gb * num_hops / num_devices_on_mesh_dim) / mesh_dim_bandwidth
+    return latency + bw * 1e6
+
+
+def reduce_scatter_cost(
+    bytes_gb: float,
+    mesh_topo: MeshTopoInfo,
+    mesh_dim: int,
+) -> float:
+    num_devices_on_mesh_dim = mesh_topo.mesh_dim_devices[mesh_dim]
+    mesh_dim_bandwidth = mesh_topo.mesh_dim_bandwidth[mesh_dim]
+    num_hops = num_devices_on_mesh_dim - 1
+    # base latency + comm latency
+    latency = 6.6 + num_hops * mesh_topo.mesh_dim_latency[mesh_dim]
+    bw = (bytes_gb * num_hops / num_devices_on_mesh_dim) / mesh_dim_bandwidth
+    return latency + bw * 1e6
+
+
+def redistribute_cost(
+    current_spec: "dtensor_spec.DTensorSpec",
+    target_spec: "dtensor_spec.DTensorSpec",
+) -> float:
+    """
+    This function returns the cost of redistribute from current to target DTensorSpec.
+
+    NOTE:
+    1. Only consider communication cost here, since computation costs for redistribute
+       are quite trival (i.e. we only need to narrow or simple division)
+    2. Only consider redistribute cost on same mesh, cross mesh communication cost is
+       not quite needed for operator strategy estimation/selection.
+    """
+    if current_spec.mesh != target_spec.mesh:
+        # make infinite cost if meshes are not same
+        # TODO: see if we want to support this once there's cross mesh communication
+        return float("inf")
+
+    if current_spec.is_replicated():
+        # short-cut:
+        # comm cost is 0 if current spec is already full replication
+        return 0.0
+
+    mesh_topo = MeshTopoInfo.build_from_mesh(current_spec.mesh)
+    cost = 0.0
+    comm_bytes_gb = (
+        spec_to_bytes(current_spec) / current_spec.num_shards / 1024 / 1024 / 1024
+    )
+    # Transformation that considered for redistribute cost:
+    # 1. allgather 2. alltoall
+    # 3. allreduce 4. reduce_scatter
+    for i, (current, target) in enumerate(
+        zip(current_spec.placements, target_spec.placements)
+    ):
+        if current == target:
+            continue
+
+        num_devices_on_mesh_dim = mesh_topo.mesh_dim_devices[i]
+        if current.is_shard() and target.is_replicate():
+            # allgather gives larger comm bytes
+            comm_bytes_gb *= num_devices_on_mesh_dim
+            # add up allgather comm cost
+            cost += allgather_cost(comm_bytes_gb, mesh_topo, i)
+        elif current.is_shard() and target.is_shard():
+            # should be alltoall comm, since we haven't implement it yet, add penalty
+            # to favor allgather instead
+            cost += allgather_cost(comm_bytes_gb, mesh_topo, i) + 1.0
+        elif current.is_partial() and target.is_replicate():
+            # add up allreduce comm cost
+            cost += allreduce_cost(comm_bytes_gb, mesh_topo, i)
+        elif current.is_partial() and target.is_shard():
+            # add up reduce_scatter comm cost
+            cost += reduce_scatter_cost(comm_bytes_gb, mesh_topo, i)
+            # after reduce_scatter the comm bytes for further collectives halved.
+            comm_bytes_gb /= num_devices_on_mesh_dim
+        elif current.is_shard() and target.is_partial():
+            # ban shard -> partial as it does not make sense to perform
+            # this redistribute
+            return float("inf")
+
+    return cost
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_dispatch.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_dispatch.py
new file mode 100644
index 0000000000000000000000000000000000000000..4579a16826d0fbfadb8bc4ccc75c352cd01581fa
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_dispatch.py
@@ -0,0 +1,510 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates
+import contextlib
+import functools
+import logging
+import operator
+import warnings
+from typing import cast, Dict, List, Optional, Sequence, Tuple, TYPE_CHECKING
+
+import torch
+import torch.distributed as dist
+import torch.distributed.tensor._api as dtensor
+import torch.distributed.tensor._random as random
+from torch.distributed.tensor._dtensor_spec import DTensorSpec, TensorMeta
+from torch.distributed.tensor._op_schema import (
+    _is_inplace_op,
+    _is_out_variant_op,
+    OpInfo,
+    OpSchema,
+    OutputSpecType,
+)
+from torch.distributed.tensor._random import is_rng_supported_mesh
+from torch.distributed.tensor._redistribute import redistribute_local_tensor
+from torch.distributed.tensor._sharding_prop import ShardingPropagator
+from torch.distributed.tensor._tp_conv import (
+    convolution_backward_handler,
+    convolution_handler,
+)
+from torch.distributed.tensor._utils import try_find_mesh_from_args
+from torch.distributed.tensor.placement_types import Partial, Placement, Replicate
+
+
+if TYPE_CHECKING:
+    from torch.distributed.device_mesh import DeviceMesh
+
+try:
+    from torch.utils import _cxx_pytree as pytree
+except ImportError:
+    from torch.utils import _pytree as pytree  # type: ignore[no-redef]
+
+aten = torch.ops.aten
+logger = logging.getLogger(__name__)
+
+
+def decompose_handler(
+    op_call: torch._ops.OpOverload,
+    args: Tuple[object, ...],
+    kwargs: Dict[str, object],
+) -> object:
+    """
+    Decomposes a op to core ATen op, this handler is mostly here
+    for inference mode usage where the ops are not core aten ops.
+    """
+    r = op_call.decompose(*args, **kwargs)
+    if r is not NotImplemented:
+        return r
+    else:
+        raise RuntimeError("Decomposition failed")
+
+
+def is_same_size_handler(
+    op_call: torch._ops.OpOverload,
+    args: Tuple[object, ...],
+    kwargs: Dict[str, object],
+) -> bool:
+    lhs = cast(torch.Tensor, args[0])
+    rhs = cast(torch.Tensor, args[1])
+    return lhs.shape == rhs.shape
+
+
+def found_inf_reduce_handler(
+    op_call: torch._ops.OpOverload,
+    args: Tuple[object, ...],
+    kwargs: Dict[str, object],
+) -> None:
+    op_info = dtensor.DTensor._op_dispatcher.unwrap_to_op_info(op_call, args, kwargs)
+    local_tensor_args = pytree.tree_unflatten(
+        cast(List[object], op_info.local_args), op_info.args_tree_spec
+    )
+    local_tensor_args = cast(Tuple[object, ...], local_tensor_args)
+    local_results = op_call(*local_tensor_args, **op_info.local_kwargs)
+
+    grad_dtensor = cast(list[dtensor.DTensor], args[0])[0]
+    grad_placements = grad_dtensor.placements
+    mesh = grad_dtensor.device_mesh
+
+    found_inf_placements: list[Placement] = []
+    for placement in grad_placements:
+        if isinstance(placement, Replicate):
+            found_inf_placements.append(placement)
+        else:
+            found_inf_placements.append(Partial("max"))
+
+    target_tensor = cast(torch.Tensor, args[1])
+    spec = DTensorSpec(
+        mesh=mesh,
+        placements=tuple(found_inf_placements),
+        tensor_meta=TensorMeta(
+            shape=target_tensor.size(),
+            stride=target_tensor.stride(),
+            dtype=target_tensor.dtype,
+        ),
+    )
+    found_inf_dtensor = dtensor.DTensor(
+        local_tensor=target_tensor, spec=spec, requires_grad=False
+    )
+    found_inf = found_inf_dtensor.full_tensor()
+    target_tensor.copy_(found_inf)
+
+
+class OpDispatcher:
+    """
+    Op dispatching class instance to handle args/kwargs pre-processing (un-wrapping), sharding
+    propagation, redistribute local args, local compute, and post-processing (re-wrapping). It
+    also handles any op specific logic if necessary.
+
+    NOTE: Given the runtime overhead of Tensor subclass (__torch_dispatch__), the OpDispatcher
+    is designed to minimize the CPU overhead by using the tricks of proper unflattening, faster
+    pytree if needed, and leveraging various caching mechanisms implemented in the sharding
+    propagation and redistribute modules. The CPU overhead is critical to eager mode performance,
+    one need to carefully measure the CPU overhead when making significant changes to the
+    OpDispatcher and ShardingPropagator.
+    """
+
+    def __init__(self) -> None:
+        self.sharding_propagator = ShardingPropagator()
+        self._random_ops = {
+            aten.native_dropout.default,
+            aten.normal_.default,
+            aten.rand_like.default,
+            aten.randn_like.default,
+            aten.randint_like.default,
+            aten.randint_like.low_dtype,
+            aten.randint_like.low_dtype_out,
+            aten.uniform_.default,
+            aten.bernoulli.default,
+            aten.bernoulli_.float,
+        }
+        self._custom_op_handlers = {
+            aten.linear.default: decompose_handler,
+            aten.is_same_size.default: is_same_size_handler,
+            aten.convolution.default: convolution_handler,
+            aten.convolution_backward.default: convolution_backward_handler,
+            aten._amp_foreach_non_finite_check_and_unscale_.default: found_inf_reduce_handler,
+        }
+
+        # This flag is used internally to control whether we treat the torch.Tensor(non-DTensor)
+        # as implicitly replicated or we throw error to user.
+        # NOTE: It is EXTREMELY UNSAFE to turn this flag on by default so we intentionally leave
+        # it as False by default.
+        self._allow_implicit_replication = False
+
+    def dispatch(
+        self,
+        op_call: torch._ops.OpOverload,
+        args: Tuple[object, ...],
+        kwargs: Dict[str, object],
+    ) -> object:
+        """
+        Main dispatching logic
+        """
+        # operators that does not need to go through sharding propagation
+        if op_call in self._custom_op_handlers:
+            return self._custom_op_handlers[op_call](op_call, args, kwargs)  # type: ignore[operator]
+
+        # extract local tensor and sharding infos to a OpInfo
+        op_info = self.unwrap_to_op_info(op_call, args, kwargs)
+        logger.debug("Dispatching op_call: %s", op_info.schema)
+
+        self.sharding_propagator.propagate(op_info)
+        output_sharding = op_info.output_sharding
+        logger.debug("output_sharding for %s: %s", op_call, output_sharding)
+        assert output_sharding is not None, "output sharding should not be None"
+
+        mesh = op_info.mesh
+        if mesh.get_coordinate() is not None:
+            # computation that happens in the current rank of the mesh, normal case
+            if output_sharding.needs_redistribute:
+                # If sharding propagation decision needs redistribute, perform redistribute
+                # on args first, which could potentially modify args (i.e. allgather certain arg)
+                assert output_sharding.redistribute_schema is not None
+                self.redistribute_local_args(
+                    op_info, output_sharding.redistribute_schema
+                )
+
+            local_tensor_args = (
+                pytree.tree_unflatten(
+                    cast(List[object], op_info.local_args), op_info.args_tree_spec
+                )
+                if op_info.args_tree_spec
+                else op_info.local_args
+            )
+
+            # run local op computation with potentially modified args/kwargs
+            local_tensor_args = cast(Tuple[object, ...], local_tensor_args)
+            if op_call in self._random_ops:
+                if not random._rng_tracker and is_rng_supported_mesh(mesh):
+                    # Default to `OffsetBasedRNGTracker` if the parallelism API
+                    # did not already construct one
+                    random._rng_tracker = random.OffsetBasedRNGTracker(mesh.device_type)
+
+                first_arg, first_local_arg = cast(dtensor.DTensor, args[0]), cast(
+                    torch.Tensor, local_tensor_args[0]
+                )
+                rng_context = (
+                    random._rng_tracker._distribute_region(first_arg._spec)
+                    if random._rng_tracker and not first_local_arg.is_meta
+                    else contextlib.nullcontext()
+                )
+                # For DTensor random operator, run it within a RNGTracker context to
+                # ensure the random number generator is properly distributed.
+                with rng_context:
+                    local_results = op_call(*local_tensor_args, **op_info.local_kwargs)
+            else:
+                # normal case, run local sharded op computation
+                local_results = op_call(*local_tensor_args, **op_info.local_kwargs)
+
+        else:
+            # For a non-participating device (happens on rank that does not belong to
+            # the device mesh), we do:
+            #   1. if the return type is scalar, set the local result to None.
+            #   2. if the return type is Tensor or List[Tensor], return empty
+            #   tensor(s) with correct dtype.
+            spec = output_sharding.output_spec
+            ret_list = op_info.schema.op._schema.returns
+
+            if spec is None:
+                # For a scalar return type, the non-participating device has None
+                # as its local result
+                local_results = None
+            else:
+
+                def default_tensor(spec: DTensorSpec) -> torch.Tensor:
+                    if spec.tensor_meta is not None:
+                        shape = spec.tensor_meta.shape
+                        dtype = spec.tensor_meta.dtype
+                        if len(shape) == 0:
+                            # scalar tensor
+                            return torch.zeros((), dtype=dtype)
+                        else:
+                            # non-scalar tensor
+                            return torch.tensor([], dtype=dtype)
+                    else:
+                        raise RuntimeError(f"{spec} has no tensor metadata.")
+
+                if isinstance(spec, DTensorSpec):
+                    # return a Tensor value
+                    local_results = default_tensor(spec)
+                elif isinstance(spec, Sequence):
+                    # return a List[Tensor] value
+                    local_results = [
+                        default_tensor(s) if s is not None else None for s in spec
+                    ]
+                    assert isinstance(local_results, List)
+                    if None in local_results:
+                        ret_type = str(ret_list[0].type)
+                        raise NotImplementedError(
+                            f"return type {ret_type} in DTensor op is not supported"
+                        )
+
+        if output_sharding.output_spec is None:
+            if op_call == aten.equal.default:
+                # For equal operator, The local results from all devices should be all-gathered
+                # and a reduce op (AND) will be performed on the list of results to ensure SPMD
+                # execution. We can extend this for more ops if necessary.
+                obj_list = [None for _ in range(dist.get_world_size())]
+                dist.all_gather_object(obj_list, local_results)  # type: ignore[possibly-undefined]
+                obj_list = list(filter(lambda x: x is not None, obj_list))
+                # perform reduce on the collection with AND op
+                local_results = functools.reduce(operator.and_, obj_list, True)
+
+        if _is_inplace_op(op_call):
+            # inplace op should return self instead of re-wrapping
+            if output_sharding.output_spec is not None:
+                return args[0]
+            else:
+                return None
+        elif _is_out_variant_op(op_call):
+            # out variant could possibly have multiple out args (i.e. lu_unpack.out)
+            output_specs = (
+                (output_sharding.output_spec,)
+                if not isinstance(output_sharding.output_spec, tuple)
+                else output_sharding.output_spec
+            )
+            out_dts = []
+            spec_idx = 0
+            for argument in op_call._schema.arguments:
+                if argument.is_out:
+                    out_dt = cast(dtensor.DTensor, kwargs[argument.name])
+                    out_dt._spec = cast(DTensorSpec, output_specs[spec_idx])
+                    out_dts.append(out_dt)
+                    spec_idx += 1
+
+            assert len(out_dts) >= 1, "out variant should have at least one out arg"
+            return tuple(out_dts) if len(out_dts) > 1 else out_dts[0]
+        else:
+            return self.wrap(local_results, output_sharding.output_spec)  # type: ignore[possibly-undefined]
+
+    @staticmethod
+    def redistribute_local_args(
+        op_info: OpInfo,
+        suggested_input_schema: OpSchema,
+    ) -> None:
+        # NOTE: it's very rare that we need to reshard kwargs so we intentionally skip it
+        if op_info.args_tree_spec is not None:
+            flatten_args_schema_to_reshard = tuple(
+                pytree.tree_leaves(suggested_input_schema.args_schema)
+            )
+        else:
+            flatten_args_schema_to_reshard = suggested_input_schema.args_schema
+
+        new_local_args: List[object] = []
+        for i, arg_spec in enumerate(op_info.flat_args_schema):
+            reshard_arg_spec = flatten_args_schema_to_reshard[i]
+            if isinstance(arg_spec, DTensorSpec):
+                local_tensor = cast(torch.Tensor, op_info.local_args[i])
+                if arg_spec != reshard_arg_spec:
+                    resharded_local_tensor = redistribute_local_tensor(
+                        local_tensor, arg_spec, reshard_arg_spec
+                    )
+                    new_local_args.append(resharded_local_tensor)
+                else:
+                    new_local_args.append(local_tensor)
+            else:
+                new_local_args.append(reshard_arg_spec)
+
+        op_info.local_args = tuple(new_local_args)
+
+    def unwrap_to_op_info(
+        self,
+        op_call: torch._ops.OpOverload,
+        args: Tuple[object, ...],
+        kwargs: Dict[str, object],
+    ) -> OpInfo:
+        # get runtime schema info to determine whether to use pytree to flatten inputs
+        runtime_schema_info = self.sharding_propagator.op_to_schema_info.get(
+            op_call, None
+        )
+
+        if runtime_schema_info is not None and runtime_schema_info.needs_pytree:
+            # flatten args/kwargs when op says necessary
+            tree_args, args_spec = pytree.tree_flatten(args)
+            args_list: Sequence[object] = tree_args
+        else:
+            args_list, args_spec = args, None
+
+        args_schema: List[object] = []
+        kwargs_schema: Dict[str, object] = {}
+        local_args: List[object] = []
+        local_kwargs: Dict[str, object] = {}
+        mesh: Optional[DeviceMesh] = None
+
+        for arg in args_list:
+            if isinstance(arg, dtensor.DTensor):
+                local_args.append(arg._local_tensor)
+                if mesh is not None and mesh != arg.device_mesh:
+                    # TODO: try replicate dtensor spec in missing dimension would work
+                    # for most cases for foreach case except when the first DTensor in
+                    # the list is one that also need to be replicated. We need to revisit
+                    # how we want to handle this corner case. For now, this case would hit
+                    # the cross mesh error even if implicit replication is turned on.
+                    spec = self._try_replicate_dtensor_spec_in_missing_dim(
+                        op_call, arg, mesh
+                    )
+                    args_schema.append(spec)
+                else:
+                    mesh = arg.device_mesh
+                    args_schema.append(arg._spec)
+            elif isinstance(arg, torch.Tensor):
+                mesh = mesh or try_find_mesh_from_args(op_call, args_list)
+                args_schema.append(
+                    self._try_replicate_spec_for_scalar_tensor(op_call, arg, mesh)
+                )
+                local_args.append(arg)
+            else:
+                args_schema.append(arg)
+                local_args.append(arg)
+
+        for k, v in kwargs.items():
+            if isinstance(v, dtensor.DTensor):
+                local_kwargs[k] = v._local_tensor
+                if mesh is not None and mesh != v.device_mesh:
+                    spec = self._try_replicate_dtensor_spec_in_missing_dim(
+                        op_call, v, mesh
+                    )
+                    kwargs_schema[k] = spec
+                else:
+                    mesh = v.device_mesh
+                    kwargs_schema[k] = v._spec
+            elif isinstance(v, torch.Tensor):
+                mesh = mesh or try_find_mesh_from_args(op_call, args_list)
+                kwargs_schema[k] = self._try_replicate_spec_for_scalar_tensor(
+                    op_call, v, mesh
+                )
+                local_kwargs[k] = v
+            else:
+                kwargs_schema[k] = v
+                local_kwargs[k] = v
+
+        assert mesh is not None, f"found no DeviceMesh from dtensor args for {op_call}!"
+        op_info = OpInfo(
+            mesh,
+            OpSchema(
+                op_call,
+                pytree.tree_unflatten(args_schema, args_spec)
+                if args_spec
+                else tuple(args_schema),
+                kwargs_schema,
+                schema_info=runtime_schema_info,
+            ),
+            args_schema,
+            tuple(local_args),
+            local_kwargs,
+            args_spec,
+        )
+        return op_info
+
+    @staticmethod
+    def wrap(res: object, spec: OutputSpecType) -> object:
+        if isinstance(res, torch.Tensor):
+            if spec is not None:
+                assert isinstance(
+                    spec, DTensorSpec
+                ), f"output spec does not match with output! Expected DTensorSpec, got {spec}."
+                return dtensor.DTensor(res, spec, requires_grad=res.requires_grad)
+            else:
+                # if output does not have a DTensorSpec due to specific ops, it must be a scalar tensor
+                assert res.ndim == 0, "output tensor should be scalar!"
+                return res
+        elif isinstance(res, (list, tuple)):
+            assert spec is not None and isinstance(
+                spec, (list, tuple)
+            ), f"output spec does not match with output! Expected list/tuple, got {spec}."
+            res_list = []
+            for e, s in zip(res, spec):
+                res_list.append(OpDispatcher.wrap(e, s))
+
+            return tuple(res_list) if isinstance(res, tuple) else res_list
+        else:
+            # if the res contains only non tensor values (i.e. int/float/none), we simply return it
+            # without rewrapping to DTensor.
+            return res
+
+    def _try_replicate_spec_for_scalar_tensor(
+        self,
+        op_call: torch._ops.OpOverload,
+        tensor_arg: torch.Tensor,
+        mesh: "DeviceMesh",
+    ) -> DTensorSpec:
+        # util function to produce a replicate spec for a scalar tensor arg/kwarg
+        if tensor_arg.numel() == 1 and tensor_arg.ndim == 1:
+            warnings.warn(
+                "Found a non-scalar tensor with numel=1 and ndim!=0, "
+                "we are implicitly creating a replicated DTensor for it. "
+                "However, please consider changing it to a scalar tensor "
+                "or explicitly create a DTensor under distributed enviroment."
+            )
+
+        if tensor_arg.numel() == 1 or self._allow_implicit_replication:
+            # scalar tensor can be safely treated as replicated
+            replication_spec = DTensorSpec(
+                mesh,
+                (Replicate(),) * mesh.ndim,
+                tensor_meta=TensorMeta(
+                    shape=tensor_arg.shape,
+                    stride=tensor_arg.stride(),
+                    dtype=tensor_arg.dtype,
+                ),
+            )
+        else:
+            raise RuntimeError(
+                f"{op_call}: got mixed torch.Tensor and DTensor, need to convert all"
+                " torch.Tensor to DTensor before calling distributed operators!"
+            )
+        return replication_spec
+
+    def _try_replicate_dtensor_spec_in_missing_dim(
+        self,
+        op_call: torch._ops.OpOverload,
+        dtensor_arg: "dtensor.DTensor",
+        mesh: "DeviceMesh",
+    ) -> DTensorSpec:
+        # util function to produce a new spec for a DTensor arg/kwarg
+        # that puts Replicate() placement in the missing dimension for foreach ops
+        from torch.distributed.device_mesh import _mesh_resources
+
+        cur_mesh = dtensor_arg.device_mesh
+        root_mesh = _mesh_resources.get_root_mesh(cur_mesh)
+        if (
+            self._allow_implicit_replication
+            and "foreach" in op_call.__name__
+            and root_mesh == mesh
+        ):
+            placements = [Replicate() for _ in range(root_mesh.ndim)]
+            cur_mesh_root_idx = _mesh_resources.get_root_mesh_dim(cur_mesh)
+            placements[cur_mesh_root_idx] = dtensor_arg.placements[0]  # type: ignore[call-overload]
+            replicate_spec = DTensorSpec(
+                root_mesh,
+                tuple(placements),
+                tensor_meta=TensorMeta(
+                    shape=dtensor_arg.shape,
+                    stride=dtensor_arg.stride(),
+                    dtype=dtensor_arg.dtype,
+                ),
+            )
+        else:
+            raise NotImplementedError(
+                f"{op_call}: DTensor does not support cross-mesh operation yet! "
+                f"Got meshes: {mesh} {cur_mesh}"
+            )
+        return replicate_spec
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_dtensor_spec.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_dtensor_spec.py
new file mode 100644
index 0000000000000000000000000000000000000000..e80729c7b628692cb4f23d1d067c471d8be48938
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_dtensor_spec.py
@@ -0,0 +1,276 @@
+from dataclasses import dataclass
+from typing import Any, cast, List, NamedTuple, Optional, Tuple
+
+import torch
+from torch.distributed.device_mesh import DeviceMesh
+from torch.distributed.tensor.placement_types import (
+    Partial,
+    Placement,
+    Replicate,
+    Shard,
+)
+
+
+class TensorMeta(NamedTuple):
+    # simple named tuple to represent tensor metadata
+    # intentionally to stay simple only for sharding
+    # propagation purposes.
+    shape: torch.Size
+    stride: Tuple[int, ...]
+    dtype: torch.dtype
+
+
+# used internally to propagate the placements
+@dataclass
+class DTensorSpec:
+    mesh: DeviceMesh
+    placements: Tuple[Placement, ...]
+
+    # tensor meta will only be set during sharding propagation
+    tensor_meta: Optional[TensorMeta] = None
+
+    def __post_init__(self) -> None:
+        if not isinstance(self.placements, tuple):
+            self.placements = tuple(self.placements)
+        self._hash: Optional[int] = None
+
+    def __setattr__(self, attr: str, value: Any) -> None:
+        super().__setattr__(attr, value)
+        # Make sure to recompute the hash in case any of the hashed attributes
+        # change (though we do not expect `mesh` or `placements` to change)
+        if hasattr(self, "_hash") and attr in ("mesh", "placements", "tensor_meta"):
+            self._hash = None
+
+    def _hash_impl(self) -> int:
+        # hashing and equality check for DTensorSpec are used to cache the sharding
+        # propagation results. We only need to consider the mesh, placements, shape
+        # dtype and stride.
+        # Caveat: we need to keep this in mind and sync hash and eq if we add more
+        # fields to them.
+        if self.tensor_meta is not None:
+            return hash(
+                (
+                    self.mesh,
+                    self.placements,
+                    self.tensor_meta.shape,
+                    self.tensor_meta.stride,
+                    self.tensor_meta.dtype,
+                )
+            )
+        return hash((self.mesh, self.placements))
+
+    def __hash__(self) -> int:
+        # We lazily cache the spec to avoid recomputing the hash upon each
+        # use, where we make sure to update the hash when the `tensor_meta`
+        # changes by overriding `__setattr__`. This must be lazy so that Dynamo
+        # does not try to hash non-singleton `SymInt`s for the stride.
+        if self._hash is None:
+            self._hash = self._hash_impl()
+        return self._hash
+
+    def __eq__(self, __o: object) -> bool:
+        if not (
+            isinstance(__o, DTensorSpec)
+            and self.mesh == __o.mesh
+            and self.placements == __o.placements
+        ):
+            return False
+        if self.tensor_meta is None or __o.tensor_meta is None:
+            return self.tensor_meta == __o.tensor_meta
+
+        return (
+            self.tensor_meta.shape == __o.tensor_meta.shape  # type: ignore[union-attr]
+            and self.tensor_meta.stride == __o.tensor_meta.stride  # type: ignore[union-attr]
+            and self.tensor_meta.dtype == __o.tensor_meta.dtype  # type: ignore[union-attr]
+        )
+
+    def __str__(self) -> str:
+        """
+        human readable representation of the DTensorSpec
+        """
+        if len(self.placements) == 1:
+            placement_str = str(self.placements[0])
+        else:
+            placement_str = str(self.placements)
+
+        if self.tensor_meta is not None:
+            tensor_shape = str(tuple(self.tensor_meta.shape))
+        else:
+            tensor_shape = "unknown shape"
+
+        return f"Spec({placement_str} on {tensor_shape})"
+
+    @property
+    def shape(self) -> torch.Size:
+        if self.tensor_meta is None:
+            raise ValueError("tensor_meta is not set")
+        return self.tensor_meta.shape
+
+    @property
+    def stride(self) -> Tuple[int, ...]:
+        if self.tensor_meta is None:
+            raise ValueError("tensor_meta is not set")
+        return self.tensor_meta.stride
+
+    @property
+    def ndim(self) -> int:
+        if self.tensor_meta is None:
+            raise ValueError("tensor_meta is not set")
+        return len(self.tensor_meta.shape)
+
+    @property
+    def num_shards(self) -> int:
+        num_shards = 1
+        for i, placement in enumerate(self.placements):
+            if placement.is_shard():
+                num_shards *= self.mesh.size(i)
+        return num_shards
+
+    @property
+    def device_mesh(self) -> DeviceMesh:
+        # simple aliasing for the mesh field, make some
+        # checks that mixes DTensor/DTensorSpec easier
+        return self.mesh
+
+    @property
+    def dim_map(self) -> List[int]:
+        """
+        dim_map is a property we derive from `placements` of
+        the distributed tensor. It simply return a list of ints
+        where dim_map[i] denotes the sharding mapping to the mesh
+        dimension, and len(dim_map) == dist_tensor.ndim
+        dim_map[i] = -1: means tensor dim i replicate on mesh
+        dim_map[i] = j: means tensor dim i shard on mesh dim j
+
+        For example, we have a dist tensor that have the shape of
+        [18, 20, 30], and device_mesh([0, 1, 2, 3]), placements:
+        [Shard(1)], the dim_map of this placement would be:
+        [-1, 0, -1]. This representation is pretty helpful during
+        sharding propagation where we could know exactly each
+        tensor dimension is sharded or not.
+
+        Note that if placements contains `_Partial`, we have to
+        explicitly deal with it, so that when we create a DTensorSpec
+        with dim_map, we could properly record the pending sums.
+        """
+        # dims mapping of dist tensor sharding
+        # return size of tensor ndim, -1 represent replicate
+        # and int >=0 represent shard on that device mesh dim
+        r = [-1] * self.ndim
+        for i, placement in enumerate(self.placements):
+            if placement.is_shard():
+                shard_dim = cast(Shard, placement).dim
+                if r[shard_dim] > -1:
+                    raise ValueError(
+                        f"Tensor dim {shard_dim} is already sharded on mesh dim {r[shard_dim]},"
+                        " DTensor operator implementation does not support things like hybrid"
+                        " sharding strategies yet (i.e. [Shard(0), Shard(0)])"
+                    )
+                r[shard_dim] = i
+        return r
+
+    @property
+    def num_shards_map(self) -> List[int]:
+        """
+        dim_map is a property we derive from `placements` of
+        the distributed tensor. Unlike `dim_map`, `num_shards_map`
+        denotes how many shards each tensor dim has. Like `dim_map`:
+            len(num_shards_map) == dist_tensor.ndim
+            num_shards_map[i] = 1: means tensor dim i is not sharded
+            num_shards_map[i] = j: means tensor dim i has j shards in total
+
+        For example, we have a dist tensor of shape [18, 20, 30],
+        a device_mesh ([[0, 1, 2, 3], [4, 5, 6, 7]]), and placements
+        ([Shard(1), Shard(0)]), the num_shards_map of this distributed tensor
+        would be: [4, 2, 1].
+        """
+        r = [1] * self.ndim
+        for i, placement in enumerate(self.placements):
+            if placement.is_shard():
+                shard_dim = cast(Shard, placement).dim
+                r[shard_dim] *= self.mesh.size(i)
+
+        return r
+
+    @property
+    def sums(self) -> List[int]:
+        """
+        sums is a property we derive from `placements` of the
+        distributed tensor. It simply return a list of ints where
+        sums[i] denotes the pending sum (partial) on mesh dim i
+        """
+        return [
+            idx
+            for idx, placement in enumerate(self.placements)
+            if placement.is_partial()
+        ]
+
+    @classmethod
+    def from_dim_map(
+        cls,
+        mesh: DeviceMesh,
+        dim_map: List[int],
+        sums: List[int],
+        tensor_meta: Optional[TensorMeta] = None,
+    ) -> "DTensorSpec":
+        """
+        Construct a DTensorSpec from dim_map list and pending sum.
+
+        Args:
+            mesh (class:`DeviceMesh`): device mesh to be used in the DTensorSpec
+            dim_map (List[int]): a list of integer that represents sharding on each
+                tensor dimension, see `dim_map` property doc for details
+            sums (List[int]): a list of integer that represents the dist tensor have
+                pending sum on which device mesh dimension.
+            tensor meta (TensorMeta): DTensor metadata
+
+        Return:
+            a class:`DTensorSpec` object
+        """
+        # by default replicate on device mesh dims
+        placements: List[Placement] = [Replicate() for _ in range(mesh.ndim)]
+
+        # find all mesh dims that need pending reductions
+        for s in sums:
+            placements[s] = Partial()
+
+        for i, m in enumerate(dim_map):
+            if m >= 0:
+                placement = placements[m]
+                if placement.is_shard():
+                    placement = cast(Shard, placement)
+                    raise RuntimeError(
+                        f"DeviceMesh dimension cann't be mapped to two dimension of the same tensor: {i} and {placement.dim}"
+                    )
+                elif placement.is_partial():
+                    raise RuntimeError(
+                        f"DeviceMesh dimension {m} cannot be both shard and partial!"
+                    )
+                placements[m] = Shard(i)
+
+        return cls(mesh, tuple(placements), tensor_meta=tensor_meta)
+
+    def is_replicated(self) -> bool:
+        """
+        return True if the current DTensorSpec replicates on all mesh dims (devices)
+        """
+        return all(placement.is_replicate() for placement in self.placements)
+
+    def is_sharded(self) -> bool:
+        """
+        return True if the current DTensorSpec is sharded on any mesh dims (devices)
+        """
+        return any(placement.is_shard() for placement in self.placements)
+
+    def shallow_copy_with_tensor_meta(
+        self, tensor_meta: Optional[TensorMeta]
+    ) -> "DTensorSpec":
+        """
+        Shallow copy the DTensorSpec with a new tensor_meta.
+        """
+        assert tensor_meta is not None, "shallow copy with no tensor_meta!"
+        return DTensorSpec(
+            self.mesh,
+            self.placements,
+            tensor_meta=tensor_meta,
+        )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_op_schema.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_op_schema.py
new file mode 100644
index 0000000000000000000000000000000000000000..190886da21fd220e76adbd6e10a527dbed425f13
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_op_schema.py
@@ -0,0 +1,457 @@
+# mypy: allow-untyped-defs
+from dataclasses import dataclass
+from functools import cached_property
+from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
+
+import torch
+from torch._ops import OpOverload
+from torch.distributed.device_mesh import DeviceMesh
+from torch.distributed.tensor._dtensor_spec import DTensorSpec
+from torch.distributed.tensor.placement_types import Placement
+
+
+try:
+    from torch.utils._cxx_pytree import tree_leaves, tree_map_only, TreeSpec
+except ImportError:
+    from torch.utils._pytree import (  # type: ignore[no-redef, assignment]
+        tree_leaves,
+        tree_map_only,
+        TreeSpec,
+    )
+
+
+# Common type aliases
+ArgsType = Tuple[object, ...]
+KwargsType = Dict[str, object]
+
+PlacementList = List[Optional[Placement]]
+
+# ATen op schemas could have Tensor, Tuple[Tensor] and List[Tensor], so output type sould
+# be the same set of possibilities.
+OutputSpecType = Optional[Union[DTensorSpec, Sequence[Optional[DTensorSpec]]]]
+
+
+def _rebuild_tensor_from_dtensor_meta(arg) -> object:
+    """
+    This is used to propagate tensor metadata, must be under fake mode
+    """
+    assert arg.tensor_meta is not None, "DTensorSpec does not contain tensor_meta."
+    return torch.empty_strided(
+        arg.tensor_meta.shape,
+        arg.tensor_meta.stride,
+        dtype=arg.tensor_meta.dtype,
+    )
+
+
+def _is_inplace_op(op: OpOverload):
+    # simple analysis of function schema to determine
+    # if this is an inplace variant, it might not
+    # be entirely correct, but it's good enough for now.
+    return op._schema.name[-1] == "_"
+
+
+def _is_out_variant_op(op: OpOverload):
+    # simple analysis of function schema to determine
+    # if this is an out variant, it might not
+    # be entirely correct, but it's good enough for now.
+    return "out" in op._schema.overload_name
+
+
+def _pretty_print_spec(spec: object) -> str:
+    if spec is None:
+        return "None"
+    elif isinstance(spec, DTensorSpec):
+        return "".join([str(p) for p in spec.placements])
+    elif isinstance(spec, Sequence):
+        return "(" + ", ".join([_pretty_print_spec(s) for s in spec]) + ")"
+    else:
+        raise RuntimeError(f"Unknown spec type to print: spec={spec}")
+
+
+@dataclass
+class PlacementStrategy:
+    """
+    A placement strategy describes acceptable sharding placements of the output
+    and the tensor arguments of an operation.
+
+    note: when the op return value is a single DTensor object, output_specs is
+    DTensorSpec; when the return value is a tuple of Optional[DTensor],
+    output_specs is a tuple of Optional[DTensorSpec].
+    """
+
+    output_specs: Union[DTensorSpec, Tuple[Optional[DTensorSpec], ...]]
+    input_specs: Optional[Sequence[DTensorSpec]] = None
+
+    # redistribute costs for this op placement strategy
+    # we need a nested list to record the cost for each
+    # operand of this operator, and for each operand of
+    # this operator it might have multiple placement strategies
+    redistribute_cost: Optional[List[List[float]]] = None
+
+    @cached_property
+    def output_spec(self) -> DTensorSpec:
+        """
+        This function requires that the strategy have exactly one DTensorSpec as the
+        output spec. If the output_specs is a tuple, we throw an exception.
+        """
+        if isinstance(self.output_specs, DTensorSpec):
+            return self.output_specs
+        else:
+            raise ValueError(
+                f"function output_spec expects a single DTensorSpec but got: {self.output_specs}"
+            )
+
+    def input_spec(self, index: int = 0) -> DTensorSpec:
+        assert self.input_specs is not None, "input_specs of PlacementStrategy is None!"
+        assert len(self.input_specs) > index, (
+            f"Invalid index {index} for input_specs of length "
+            f"{len(self.input_specs)}: {self.input_specs}"
+        )
+        return self.input_specs[index]
+
+    def __str__(self) -> str:
+        if self.input_specs is not None:
+            input_specs_str = f"{_pretty_print_spec(self.input_specs)} -> "
+        else:
+            input_specs_str = ""
+        output_spec_str = _pretty_print_spec(self.output_specs)
+        return f"{input_specs_str}{output_spec_str}"
+
+
+class StrategyType:
+    """
+    Base class type for op strategy, We have two StrategyType:
+        OpStrategy and TupleStrategy
+    """
+
+
+class OpStrategy(StrategyType):
+    """
+    OpStrategy that consists of a list of placement strategies associated with the op
+    """
+
+    def __init__(self, strategies: List[PlacementStrategy]) -> None:
+        super().__init__()
+        self.strategies: List[PlacementStrategy] = strategies
+
+    def __str__(self) -> str:
+        strategy_list_str = ", ".join([str(strategy) for strategy in self.strategies])
+        mesh_shape = self.mesh_shape
+        return f"[{strategy_list_str}] @ mesh: {mesh_shape}"
+
+    def max_num_shards(self) -> int:
+        """
+        Returns the max number of shards across all placement strategies
+        """
+        return max(strategy.output_spec.num_shards for strategy in self.strategies)
+
+    @property
+    def mesh_shape(self):
+        output_spec = self.strategies[0].output_specs
+        if isinstance(output_spec, DTensorSpec):
+            return output_spec.mesh.shape
+        else:
+            assert isinstance(
+                output_spec, tuple
+            ), "found no DTensorSpec in the OpStrategy!"
+            assert output_spec[0] is not None
+            return output_spec[0].mesh.shape
+
+    @property
+    def ndim(self):
+        return self.strategies[0].output_spec.ndim
+
+    @property
+    def shape(self):
+        return self.strategies[0].output_spec.shape
+
+
+class TupleStrategy(StrategyType):
+    """
+    TupleStrategy represents the output strategy of this op is a tuple
+    of strategy, i.e. If the output of this op is a tuple of tensors or list of tensors
+    with possibly different placement strategies, we should return a TupleStrategy that
+    contains a tuple of OpStrategy, where each child represents the sharding strategy
+    of "each element" of the tuple/list of tensors the op returns.
+
+    NOTE: if the output of the op is a List[Tensor] and they share the same placement
+    strategy, then we should return a single OpStrategy instead of a TupleStrategy
+    """
+
+    def __init__(self, childs: Sequence[StrategyType]) -> None:
+        super().__init__()
+        self.childs: Sequence[StrategyType] = childs
+
+    def __str__(self) -> str:
+        child_strategies_str = ", ".join(
+            [f"{str(strat)}" for idx, strat in enumerate(self.childs)]
+        )
+        return f"TupleStrategy({child_strategies_str})"
+
+
+@dataclass
+class RuntimeSchemaInfo:
+    """
+    RuntimeSchemaInfo stores the operator schema related information for runtime (eager)
+    execution. This is mainly used for two ways: 1. to generate hash for args to determine
+    whether to re-run sharding prop or not 2. to determine if we need pytree
+    """
+
+    # This static_argnum records static arg "starting index" for ops that have non-tensor
+    # args/kwargs which would affect sharding propagation results. All args starting from
+    # this index would be hashed to our sharding cache.
+    # Note that only a few ops need this information, e.g. view, transpose, var.dim, etc.
+    static_argnum: int = 100
+    # This static_kwargkey records static kwarg names which would affect sharding prop
+    static_kwargkey: Optional[List[str]] = None
+    # each op can decide if it wants to use pytree flatten/unflatten during operator
+    # eager execution, by default we don't need to do flatten/unflatten, only if the
+    # op indicate it needs to, this is to accelerate eager performance.
+    needs_pytree: bool = False
+
+
+@dataclass
+class OpSchema:
+    """
+    OpSchema is a data class that describes an operator input schemas, it includes
+    DTensorSpecs (instead of DTensor) and non-tensor args/kwargs (positional order
+    preserved). It is mainly used by the DTensor's dispatching logic to perform various
+    actions (i.e. sharding propagation, caching sharding decisions, redistribute, etc.)
+
+    NOTE: this should be used as a read only data class
+    TODO: make this a frozen dataclass
+
+    Args:
+        op: the operator overload we are intercepting
+        args_schema: contains args except that the DTensor args have been replaced
+            with its DTensorSpec or OpStrategy
+        kwargs_schema: contains kwargs except that the DTensor kwargs have been replaced
+            with its DTensorSpec or OpStrategy
+    """
+
+    op: OpOverload
+    args_schema: ArgsType
+    kwargs_schema: KwargsType
+
+    schema_info: Optional[RuntimeSchemaInfo] = None
+
+    @property
+    def args_spec(self) -> Tuple[DTensorSpec, ...]:
+        """
+        args_spec: Tuple[DTensorSpec, ...]: contains a clean list of args spec list
+            with NO non-DTensor positional arguments (i.e. int/float/tuple, etc)
+            mainly used by sharding propagation to propagate the output spec
+        """
+        args = (
+            tree_leaves(self.args_schema)
+            if self.schema_info is not None and self.schema_info.needs_pytree
+            else self.args_schema
+        )
+        return tuple(item for item in args if isinstance(item, DTensorSpec))
+
+    @property
+    def args_strategy(self) -> Tuple[OpStrategy, ...]:
+        # filter out non-relevant values from args schema to get a clean OpStrategy list
+        # separate with args_spec for the ease of type annotation
+        # TODO: see if we should merge this with args_spec
+        args = (
+            tree_leaves(self.args_schema)
+            if self.schema_info is not None and self.schema_info.needs_pytree
+            else self.args_schema
+        )
+        return tuple(item for item in args if isinstance(item, OpStrategy))
+
+    def __repr__(self) -> str:
+        args_schema = ", ".join([str(arg_schema) for arg_schema in self.args_schema])
+        return (
+            f"OpSchema(op={self.op},"
+            f" args_schema=({args_schema}),"
+            f" kwargs_schema={self.kwargs_schema})"
+        )
+
+    def __str__(self) -> str:
+        args_schema: List[str] = []
+        mesh_shape = None
+        for arg in self.args_schema:
+            if isinstance(arg, DTensorSpec):
+                args_schema.append(str(arg))
+                mesh_shape = arg.mesh.shape
+            elif isinstance(arg, OpStrategy):
+                assert len(arg.strategies) == 1
+                args_schema.append(_pretty_print_spec(arg.strategies[0].output_specs))
+                mesh_shape = arg.mesh_shape
+            elif isinstance(arg, TupleStrategy):
+                first_op_strtgy = arg.childs[0]
+                assert isinstance(first_op_strtgy, OpStrategy)
+                mesh_shape = first_op_strtgy.mesh_shape
+                args_schema.append(str(arg))
+            else:
+                args_schema.append(str(arg))
+        return f"Op(op={self.op}, args_schema={', '.join(args_schema)} @ mesh: {mesh_shape})"
+
+    def __post_init__(self) -> None:
+        has_symints = False
+        for a in self.args_schema:
+            if isinstance(a, DTensorSpec) and a.tensor_meta is not None:
+                if any(isinstance(s, torch.SymInt) for s in a.tensor_meta.shape):
+                    has_symints = True
+                    break
+        self.has_symints = has_symints
+
+    def arg_type_tensor_or_tensor_list_like(self, arg_idx: int) -> bool:
+        arg = self.args_schema[arg_idx]
+        is_tensor = isinstance(arg, DTensorSpec)
+        if is_tensor:
+            return True
+
+        if not isinstance(arg, list):
+            return False
+
+        return all(isinstance(e, DTensorSpec) or e is None for e in arg)
+
+    def return_type_tuple_tensor_like(self) -> bool:
+        # all dispatch ops could only return Tuple[Tensor] or have None/ints/floats
+        # in the tuple, but the first element must be a Tensor, so this check is enough
+        return_types = self.op._schema.returns
+        return len(return_types) > 1 and isinstance(
+            return_types[0].type, torch.TensorType
+        )
+
+    def return_type_tensor(self) -> bool:
+        return_types = self.op._schema.returns
+        # all dispatch ops only return Tensor or Tuple[Tensor] for tensor like
+        # return types, so this check is enough for tensor like types
+        return isinstance(return_types[0].type, torch.TensorType)
+
+    def __hash__(self) -> int:
+        # Only hash args and kwargs that op indicates to hash
+        if not self.schema_info:
+            static_argnum = len(self.args_schema)
+            static_kwargkey = None
+        else:
+            static_argnum = self.schema_info.static_argnum
+            static_kwargkey = self.schema_info.static_kwargkey
+
+        args_to_hash = tuple(
+            tuple(e) if isinstance(e, list) else e
+            for i, e in enumerate(self.args_schema)
+            if self.arg_type_tensor_or_tensor_list_like(i) or i >= static_argnum
+        )
+        if static_kwargkey is not None:
+            kwargs_to_hash = tuple(
+                self.kwargs_schema.get(k, None) for k in static_kwargkey
+            )
+            return hash((self.op, args_to_hash, kwargs_to_hash))
+        else:
+            return hash((self.op, args_to_hash))
+
+    def __eq__(self, other: object) -> bool:
+        # early return checks
+        if not isinstance(other, OpSchema):
+            return False
+
+        if self.op != other.op:
+            return False
+
+        if len(self.args_schema) != len(other.args_schema):
+            return False
+
+        # compare each element and early return if any of them is different
+        if not self.schema_info:
+            static_argnum = len(self.args_schema)
+            static_kwargkey = None
+        else:
+            static_argnum = self.schema_info.static_argnum
+            static_kwargkey = self.schema_info.static_kwargkey
+
+        for i, (self_arg, other_arg) in enumerate(
+            zip(self.args_schema, other.args_schema)
+        ):
+            if isinstance(self_arg, DTensorSpec) and self_arg != other_arg:
+                return False
+            elif i >= static_argnum and self_arg != other_arg:
+                return False
+
+        # check kwarg equality when there's a static kwarg key
+        if static_kwargkey:
+            for key in static_kwargkey:
+                if self.kwargs_schema.get(key, None) != other.kwargs_schema.get(
+                    key, None
+                ):
+                    return False
+
+        return True
+
+    def gen_fake_args(self) -> ArgsType:
+        """
+        gen_fake_args: generate fake args for the operator, this is mainly used
+            by sharding propagation rules to generate fake args for the operator
+            to run the local tensor operator and get the output spec.
+        """
+        return tree_map_only(
+            DTensorSpec, _rebuild_tensor_from_dtensor_meta, self.args_schema
+        )
+
+    def gen_fake_kwargs(self) -> KwargsType:
+        """
+        gen_fake_kwargs: generate fake kwargs for the operator, this is mainly used
+            by sharding propagation rules to generate fake kwargs for the operator
+            to run the local tensor operator and get the output spec.
+        """
+        return tree_map_only(
+            DTensorSpec, _rebuild_tensor_from_dtensor_meta, self.kwargs_schema
+        )
+
+    def _inplace_rewrap_schema_suggestion(self, origin_schema: "OpSchema") -> None:
+        suggestion_args_spec = self.args_spec
+        new_arg_schema: List[object] = []
+        idx_of_args_spec = 0
+        if (
+            origin_schema.schema_info is not None
+            and origin_schema.schema_info.needs_pytree
+        ):
+            args_schema: Sequence[Any] = tree_leaves(origin_schema.args_schema)
+        else:
+            args_schema = origin_schema.args_schema
+        for arg in args_schema:
+            if isinstance(arg, DTensorSpec):
+                new_arg_schema.append(suggestion_args_spec[idx_of_args_spec])
+                idx_of_args_spec += 1
+            else:
+                new_arg_schema.append(arg)
+        self.args_schema = tuple(new_arg_schema)
+        self.kwargs_schema = origin_schema.kwargs_schema
+
+
+@dataclass
+class OutputSharding:
+    """
+    OutputSharding is a data class that is used by the sharding propagation,
+    it could set the output_spec upon successful propagation. If needs_redistribute
+    is set to True, a redistribute_schema would be returned together to indicate
+    the input arguments needs to be redistributed before the op execution.
+
+    NOTE: the redistribute_schema generated by sharding propagation should be
+    exactly the same as the operator OpSchema, except the DTensorSpecs
+    """
+
+    output_spec: OutputSpecType
+    redistribute_schema: Optional[OpSchema] = None
+    needs_redistribute: bool = False
+
+
+@dataclass
+class OpInfo:
+    """
+    All Runtime Op execution info are packed here
+    """
+
+    mesh: DeviceMesh
+    schema: OpSchema
+    flat_args_schema: List[object]
+    local_args: Sequence[object]
+    local_kwargs: Dict[str, object]
+    args_tree_spec: Optional[TreeSpec] = None
+
+    # the output sharding info
+    output_sharding: Optional[OutputSharding] = None
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..dec4665b1c8b957daa4a5f5d15d988ce00cdc79d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__init__.py
@@ -0,0 +1,10 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates
+from ._conv_ops import *  # noqa: F403
+from ._embedding_ops import *  # noqa: F403
+from ._experimental_ops import *  # noqa: F403
+from ._math_ops import *  # noqa: F403
+from ._matrix_ops import *  # noqa: F403
+from ._pointwise_ops import *  # noqa: F403
+from ._random_ops import *  # noqa: F403
+from ._tensor_ops import *  # noqa: F403
+from ._view_ops import *  # noqa: F403
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..989fd529e970e0d7e0c29443d309d20025a03cbe
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_common_rules.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_common_rules.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..78a9484dfe99184d7e0c574efc3ecb2a14297cda
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_common_rules.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_conv_ops.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_conv_ops.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fe5eeaf0cb904aa4b1cb5a990be118a9950beeb5
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_conv_ops.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_einsum_strategy.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_einsum_strategy.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6e02a5f1d41e83706c1b7bc9bb675ca02065b7b2
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_einsum_strategy.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_embedding_ops.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_embedding_ops.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..87493018ea9a631f86280fc56e24d8a7dc6c2ee3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_embedding_ops.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_experimental_ops.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_experimental_ops.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c264b1077291518bf7e64c41b508629decb31086
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_experimental_ops.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_math_ops.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_math_ops.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ce6e45761b6f77d61a665e9f52caa8af91ac7295
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_math_ops.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_matrix_ops.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_matrix_ops.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..165734aebe4d2df6d066ad112b37390a5fe6e707
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_matrix_ops.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_pointwise_ops.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_pointwise_ops.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f172331defdd64346d9eeb612851038d2db8d82b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_pointwise_ops.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_random_ops.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_random_ops.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..03b736c66a4d4ff7b3b2392e5f9ff7d6eafd5484
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_random_ops.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_tensor_ops.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_tensor_ops.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b4cc153e44e963b24bb1e76db8288c508e9fddc0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_tensor_ops.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_view_ops.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_view_ops.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1411e73b4f0a9f7fc1fa27bba9935affca761805
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/_view_ops.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4aae2234fc420d4801f15488fcf2e7487e32b55c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/__pycache__/utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_common_rules.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_common_rules.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a41252be40e76e4cd4896d8e4a2fb84d01d0655
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_common_rules.py
@@ -0,0 +1,288 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates
+from typing import cast, Dict, List, Optional, Tuple
+
+import torch
+from torch.distributed.tensor._dtensor_spec import DTensorSpec, TensorMeta
+from torch.distributed.tensor._op_schema import (
+    _is_inplace_op,
+    _is_out_variant_op,
+    OpSchema,
+    OutputSharding,
+)
+from torch.distributed.tensor._ops.utils import prod
+from torch.distributed.tensor._utils import compute_local_shape
+
+
+def _replace_char_in_str(string: str, new_char: str, idx: int) -> str:
+    return string[:idx] + new_char + string[idx + 1 :]
+
+
+def _gen_reshard_suggestions(
+    op_schema: OpSchema,
+    input_dims: List[str],
+    input_specs: Tuple[DTensorSpec, ...],
+    dim_to_sharding: Dict[str, int],
+    pending_sum: List[int],
+) -> OutputSharding:
+    suggested_arg_specs: List[DTensorSpec] = []
+    for input_dim, input_spec in zip(input_dims, input_specs):
+        dim_map = [dim_to_sharding[dim] for dim in input_dim]
+        suggested_arg_specs.append(
+            DTensorSpec.from_dim_map(
+                mesh=input_spec.mesh,
+                dim_map=dim_map,
+                sums=pending_sum,
+                tensor_meta=input_spec.tensor_meta,
+            )
+        )
+    suggested_schema = OpSchema(op_schema.op, tuple(suggested_arg_specs), {})
+    suggested_schema._inplace_rewrap_schema_suggestion(op_schema)
+    return OutputSharding(
+        None,
+        redistribute_schema=suggested_schema,
+    )
+
+
+def einop_rule(
+    equation: str,
+    op_schema: OpSchema,
+    *,
+    linearity: bool = False,
+    enforce_sharding: Optional[Dict[str, int]] = None,
+) -> OutputSharding:
+    """
+    Propagate the sharding of inputs to output for ops whose data moves according to einsum notation.
+
+    This is mostly borrowed from @zdevito's sharding simulator. Examples:
+        mk,kn->mn - einsum
+        ij,ij->ij - addition
+        ij,j->ij - broadcasted addition
+        ij->i - reduction
+    Other ops could use this propagation algorithm when applied, note
+    that einsum propagation only deal with list of specs (DTensor specs)
+    as it only works on list of tensors!
+
+    linearity in einop_rule means that the calling op `f` follows this rule:
+        f(a + b) = f(a) + f(b)
+
+    In this case we can propagate the partial sum, note that linearity in einop
+    only applies to partial sum, not other operations like min/max (which are
+    associative but not linear).
+    """
+    # parse einop equation and extract arg specs
+    inputs, outputs = equation.split("->")
+    input_dims, output_dims = inputs.split(","), outputs.split(",")
+    input_specs = op_schema.args_spec
+    # NOTE: only support single output unless needed in future
+    output_dim = output_dims[0]
+
+    dim_to_sharding: Dict[str, int] = {}
+    dim_to_size: Dict[str, int] = {}
+    # record pending sum, key is mesh dimension, value is pending sum
+    # counter across input specs
+    pending_sums_counter: Dict[int, int] = {}
+    seen_shardings: Dict[int, str] = {}
+    needs_reshard = False
+
+    def merge_sharding(dim: str, a: int, b: int) -> int:
+        # merge the sharding of inputs if it's able to merge, i.e. we can merge
+        # replicate and shard to shard, but this will trigger an reshard operation
+        if a != b:
+            if a == -1 or b == -1:
+                # reshard the replicate to match the sharded one
+                nonlocal needs_reshard
+                needs_reshard = True
+                return a if a != -1 else b
+            else:
+                # TODO: further merge the sharding properly (i.e. reshard one input to replicate)
+                raise RuntimeError(
+                    f"{equation}: dim {dim} sharded two different ways: {a} and {b}"
+                )
+        else:
+            return a
+
+    for input_dim, input_spec in zip(input_dims, input_specs):
+        # deal with partial sums
+        input_sums = input_spec.sums
+        for sum_dim in input_sums:
+            if sum_dim not in pending_sums_counter:
+                seen_shardings[sum_dim] = "+"
+            # update pending sum counter for pending sum mesh
+            # dimension with the occurrence from each input
+            pending_sums_counter[sum_dim] = pending_sums_counter.get(sum_dim, 0) + 1
+
+        for idx, (dim, mesh_dim) in enumerate(zip(input_dim, input_spec.dim_map)):
+            if enforce_sharding and dim in enforce_sharding:
+                if enforce_sharding[dim] != mesh_dim:
+                    needs_reshard = True
+                dim_to_sharding[dim] = enforce_sharding[dim]
+                dim_to_size[dim] = input_spec.shape[idx]
+            elif dim not in dim_to_sharding:
+                dim_to_sharding[dim] = mesh_dim
+                dim_to_size[dim] = input_spec.shape[idx]
+            else:
+                dim_to_sharding[dim] = merge_sharding(
+                    dim, dim_to_sharding[dim], mesh_dim
+                )
+                assert dim_to_size[dim] == input_spec.shape[idx]
+
+            # after merging sharding, we check if there're multiple
+            # sharding on the same mesh dim.
+            merged_sharding_for_dim = dim_to_sharding[dim]
+            if merged_sharding_for_dim != -1:
+                if (
+                    merged_sharding_for_dim in seen_shardings
+                    and dim != seen_shardings[merged_sharding_for_dim]
+                ):
+                    needs_reshard = True
+                    seen_shardings[merged_sharding_for_dim] += dim
+                else:
+                    seen_shardings[merged_sharding_for_dim] = dim
+
+    if pending_sums_counter and not linearity:
+        # return reshard suggestion with no pending sum, because we already properly
+        # merge the sharding, this reshard suggestion is legit to use
+        return _gen_reshard_suggestions(
+            op_schema, input_dims, input_specs, dim_to_sharding, []
+        )
+    else:
+        # It's a op that support linearity, but not all input arguments are partial
+        # we fail the sharding propagation with suggestion to make all inputs be
+        # partial on the corresponding mesh dim (all inputs should be partial for
+        # the mesh dims in order to execute locally and delay the sum reduction)
+        for value in pending_sums_counter.values():
+            if value != len(input_specs):
+                needs_reshard = True
+
+    for mesh_dim, dims in seen_shardings.items():
+        if len(dims) > 1:
+            # we found different input dims are being sharded on the same mesh dim
+            # in order to perform local op computation, we need to reshard inputs
+            # base on some simple heuristics, now we simply pick the one with least comm
+            # volume. (i.e. the input with least size)
+            # TODO: consider a more advanced heuristic to pick the best sharding
+            costs = []
+            for d in dims:
+                cost = 0
+                for input_dim, input_spec in zip(input_dims, input_specs):
+                    if (
+                        d in input_dim
+                        and input_spec.dim_map[input_dim.index(d)] == mesh_dim
+                    ):
+                        assert input_spec.tensor_meta is not None
+                        global_shape = input_spec.tensor_meta.shape
+                        local_shape = compute_local_shape(
+                            global_shape, input_spec.mesh, input_spec.placements
+                        )
+                        cost += prod(local_shape) * input_spec.mesh.size(mesh_dim)
+                costs.append(cost)
+            d_to_keep_sharding = dims[costs.index(max(costs))]
+            for d in dims:
+                # update dim_to_sharding to keep the sharding of the dim with
+                # highest comm and make the rest of the dims to replicate
+                if d != d_to_keep_sharding:
+                    dim_to_sharding[d] = -1
+
+    pending_sums = list(pending_sums_counter.keys())
+    if needs_reshard:
+        return _gen_reshard_suggestions(
+            op_schema, input_dims, input_specs, dim_to_sharding, pending_sums
+        )
+
+    # generate output pending sum if a dim is sharded, and it appears in input
+    # but not output
+    for dim, shard_on_mesh in dim_to_sharding.items():
+        if dim not in output_dims[0] and shard_on_mesh != -1:
+            pending_sums.append(shard_on_mesh)
+
+    # if no need to reshard, we directly generate the output sharding
+    output_dim_map = []
+    output_shape = []
+    for dim in output_dim:
+        if dim == "1":
+            # find output dim that is a singleton dimension, mark sharding and shape
+            output_dim_map.append(-1)
+            output_shape.append(1)
+        else:
+            output_dim_map.append(dim_to_sharding[dim])
+            output_shape.append(dim_to_size[dim])
+
+    # XXX: since we still need to have intermediate shape calculation, we need
+    # to pass in the shape here. We should remove this once sharding decomp works
+    # for ops like addmm
+    assert input_specs[0].tensor_meta is not None
+    tensor_meta = TensorMeta(
+        torch.Size(output_shape),
+        input_specs[0].tensor_meta.stride,
+        input_specs[0].tensor_meta.dtype,
+    )
+    return OutputSharding(
+        DTensorSpec.from_dim_map(
+            input_specs[0].mesh,
+            output_dim_map,
+            pending_sums,
+            tensor_meta=tensor_meta,
+        )
+    )
+
+
+def pointwise_rule(op_schema: OpSchema, linearity: bool = False) -> OutputSharding:
+    """
+    Propagate the sharding for pointwise operations.
+
+    Examples:
+        ij,ij->ij - addition/mul
+        ij,j->ij - broadcasted addition
+    """
+    alphabet = "abcdefghijklmnopqrstuvwxyz"
+    # find the max_dim first in case we need to broadcasting
+    input_specs = op_schema.args_spec
+    max_dim = max(input.ndim for input in input_specs)
+    dimchars = []
+    singleton_counter: List[int] = [0] * max_dim
+    for input in input_specs:
+        start_dim = max_dim - input.ndim
+        p = alphabet[start_dim:max_dim]
+        # handle the "broadcasting to a common shape case"
+        # see https://pytorch.org/docs/stable/notes/broadcasting.html
+        # If any of the dimensions is singleton dimension (i.e. 1).
+        # we mark the dim char as a special "1" to distinguish with
+        # the non-singleton dimension, so that sharding propagation
+        # should just ignore the singleton dimension.
+        if len(input_specs) > 1:
+            for i in range(max_dim):
+                if i < start_dim:
+                    # treat the leading miss dim chars as singleton
+                    singleton_counter[i] += 1
+                elif input.shape[i - start_dim] == 1:
+                    # mark singleton dim char as a special "1" in einop rule
+                    singleton_counter[i] += 1
+                    p = _replace_char_in_str(p, "1", (i - start_dim))
+
+        dimchars.append(p)
+    out_dimchars = alphabet[:max_dim]
+    # check if we replace the all inputs dim char with singleton dimension,
+    # if we replace all inputs, we also need to replace the output dimension.
+    for output_dim_idx in range(len(out_dimchars)):
+        out_dimchar = out_dimchars[output_dim_idx]
+        if singleton_counter[output_dim_idx] == len(input_specs):
+            out_dimchars = _replace_char_in_str(out_dimchars, "1", output_dim_idx)
+
+    fmt = f"{','.join(p for p in dimchars)}->{out_dimchars}"
+
+    enforce_sharding: Dict[str, int] = {}
+    if _is_inplace_op(op_schema.op):
+        # inplace op should keep the input sharding it writes to
+        for out_dimchar, mesh_dim in zip(out_dimchars, input_specs[0].dim_map):
+            enforce_sharding[out_dimchar] = mesh_dim
+    elif _is_out_variant_op(op_schema.op):
+        out_spec = cast(DTensorSpec, op_schema.kwargs_schema["out"])
+        for out_dimchar, mesh_dim in zip(out_dimchars, out_spec.dim_map):
+            enforce_sharding[out_dimchar] = mesh_dim
+
+    return einop_rule(
+        fmt,
+        op_schema,
+        linearity=linearity,
+        enforce_sharding=enforce_sharding,
+    )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_conv_ops.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_conv_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..db2a8136e14da0aab9969f79329fec49b42a813a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_conv_ops.py
@@ -0,0 +1,110 @@
+# mypy: allow-untyped-decorators
+# Copyright (c) Meta Platforms, Inc. and affiliates
+# implement matrix related ops for distributed tensor
+from typing import List
+
+import torch
+from torch.distributed.tensor._dtensor_spec import DTensorSpec, TensorMeta
+from torch.distributed.tensor._op_schema import OpSchema, OutputSharding
+from torch.distributed.tensor._ops.utils import register_prop_rule
+
+
+aten = torch.ops.aten
+
+
+@register_prop_rule(aten.convolution.default)
+def convolution_rules(op_schema: OpSchema) -> OutputSharding:
+    (
+        input_spec,
+        weight_spec,
+        bias_spec,
+        stride,
+        padding,
+        dilation,
+        transposed,
+        output_padding,
+        groups,
+    ) = op_schema.args_schema
+
+    assert isinstance(input_spec, DTensorSpec)
+    assert isinstance(weight_spec, DTensorSpec)
+    assert isinstance(bias_spec, DTensorSpec)
+    assert input_spec.tensor_meta is not None
+    assert weight_spec.tensor_meta is not None
+    in_shape = input_spec.tensor_meta.shape
+    weight_shape = weight_spec.tensor_meta.shape
+    assert isinstance(stride, List)
+    assert isinstance(padding, List)
+    assert isinstance(dilation, List)
+    assert isinstance(weight_shape, torch.Size)
+    N, C_in, H_in, W_in = in_shape[0], in_shape[1], in_shape[2], in_shape[3]
+    C_out = weight_shape[0]
+    H_out = (H_in + 2 * padding[0] - dilation[0] * (weight_shape[2] - 1) - 1) // stride[
+        0
+    ] + 1
+    W_out = (W_in + 2 * padding[1] - dilation[1] * (weight_shape[3] - 1) - 1) // stride[
+        1
+    ] + 1
+    output_shape = [N, C_out, H_out, W_out]
+    output_stride = (C_out * H_out * W_out, H_out * W_out, W_out, 1)
+    output_dim_map = input_spec.dim_map
+    pending_sums = input_spec.sums
+
+    tensor_meta = TensorMeta(
+        torch.Size(output_shape),
+        output_stride,
+        input_spec.tensor_meta.dtype,
+    )
+    return OutputSharding(
+        DTensorSpec.from_dim_map(
+            input_spec.mesh,
+            output_dim_map,
+            pending_sums,
+            tensor_meta=tensor_meta,
+        )
+    )
+
+
+@register_prop_rule(aten.convolution_backward.default)
+def convolution_backward_rules(op_schema: OpSchema) -> OutputSharding:
+    input_spec = op_schema.args_schema[0]
+    (
+        grad_output_spec,
+        input_spec,
+        weight_spec,
+        bias_shape_opt,
+        stride,
+        padding,
+        dilation,
+        transposed,
+        output_padding,
+        groups,
+        output_mask,
+    ) = op_schema.args_schema
+
+    assert isinstance(grad_output_spec, DTensorSpec)
+    assert isinstance(input_spec, DTensorSpec)
+    assert isinstance(weight_spec, DTensorSpec)
+    assert isinstance(bias_shape_opt, List)
+    assert input_spec.tensor_meta is not None
+    weight_tensor_meta = weight_spec.tensor_meta
+    bias_tensor_meta = TensorMeta(
+        torch.Size(bias_shape_opt),
+        (1,),
+        input_spec.tensor_meta.dtype,
+    )
+
+    grad_input_spec = input_spec
+    grad_weight_spec = DTensorSpec.from_dim_map(
+        input_spec.mesh,
+        [-1, -1, -1, -1],
+        [0],
+        tensor_meta=weight_tensor_meta,
+    )
+    grad_bias_spec = DTensorSpec.from_dim_map(
+        input_spec.mesh,
+        [-1],
+        [0],
+        tensor_meta=bias_tensor_meta,
+    )
+    return OutputSharding([grad_input_spec, grad_weight_spec, grad_bias_spec])
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_einsum_strategy.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_einsum_strategy.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc3227600b35d27011b0cce4291434a633b3bd40
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_einsum_strategy.py
@@ -0,0 +1,181 @@
+import itertools
+from dataclasses import dataclass
+from typing import List, Set, Tuple
+
+from torch.distributed.device_mesh import DeviceMesh
+from torch.distributed.tensor._dtensor_spec import DTensorSpec
+from torch.distributed.tensor._op_schema import OpStrategy, PlacementStrategy
+from torch.distributed.tensor.placement_types import (
+    Partial,
+    Placement,
+    Replicate,
+    Shard,
+)
+
+
+@dataclass
+class EinsumDims:
+    contracting_dims: List[str]
+    batch_dims: List[str]
+    lhs_out_only_dims: List[str]
+    rhs_out_only_dims: List[str]
+
+    @classmethod
+    def parse_equation(cls, equation: str) -> Tuple[List[str], str]:
+        # parse einop equation and extract arg specs
+        """
+        Parse the einsum equation str to input dim chars and output dim char
+        """
+        inputs, outputs = equation.split("->")
+        input_dims, output_dims = inputs.split(","), outputs.split(",")
+
+        # NOTE: only support at most two inputs, and single output
+        # extend to support more inputs if needed in future
+        assert len(input_dims) <= 2, "Only support at most two inputs"
+        assert len(output_dims) == 1, "Only support single output"
+        output_dim = output_dims[0]
+        return input_dims, output_dim
+
+    @classmethod
+    def parse_dims(cls, input_dims: List[str], output_dim: str) -> "EinsumDims":
+        """
+        Parse the dims and extract the contracting, batch, and free dimensions
+        for the left and right hand sides.
+        """
+        dim_char_set: Set[str] = set()
+        for input_dim in input_dims:
+            dim_char_set.update(input_dim)
+
+        # get a determinisitc order of all dim chars
+        all_dim_chars = sorted(dim_char_set)
+
+        # parse input and output dimensions
+        lhs_out_only_dims, rhs_out_only_dims = [], []
+        batch_dims, contracting_dims = [], []
+
+        for dim_char in all_dim_chars:
+            if dim_char not in output_dim:
+                contracting_dims.append(dim_char)
+            else:
+                is_batch_dim = True
+                for input_dim in input_dims:
+                    is_batch_dim = is_batch_dim and dim_char in input_dim
+
+                if is_batch_dim:
+                    batch_dims.append(dim_char)
+                else:
+                    assert (
+                        len(input_dims) == 2
+                    ), "free dimension only supported for two inputs!"
+                    lhs, rhs = input_dims
+                    if dim_char in lhs:
+                        lhs_out_only_dims.append(dim_char)
+                    elif dim_char in rhs:
+                        rhs_out_only_dims.append(dim_char)
+                    else:
+                        raise RuntimeError("Invalid dimension character")
+
+        return cls(
+            contracting_dims=contracting_dims,
+            batch_dims=batch_dims,
+            lhs_out_only_dims=lhs_out_only_dims,
+            rhs_out_only_dims=rhs_out_only_dims,
+        )
+
+
+def gen_einsum_strategies(
+    equation: str,
+    mesh: DeviceMesh,
+    *,
+    linearity: bool = False,
+) -> OpStrategy:
+    """
+    Generate a strategy list for the ops that follow einsum style notation.
+    """
+    # parse einop equation and extract dims
+    input_dims, output_dim = EinsumDims.parse_equation(equation)
+    edims = EinsumDims.parse_dims(input_dims, output_dim)
+
+    all_mesh_dim_strategies = []
+
+    # generate strategies for each mesh dim
+    for mesh_dim in range(mesh.ndim):
+        mesh_dim_strategies = []
+
+        # placement list stores placements of [output, input1, input2, ...]
+        # first we always have replicate all for inputs and output
+        placement_list: List[Placement] = [Replicate()] * (len(input_dims) + 1)
+        mesh_dim_strategies.append(placement_list)
+
+        if mesh.size(mesh_dim) <= 1:
+            # only replicate strategy for mesh dim with size 1
+            # TODO: see if this is valid for the submesh case
+            continue
+
+        # split batch dim
+        for batch_dim in edims.batch_dims:
+            output_batch_dim = output_dim.index(batch_dim)
+            placement_list = [Shard(output_batch_dim)]
+            for input_dim in input_dims:
+                input_batch_dim = input_dim.index(batch_dim)
+                placement_list.append(Shard(input_batch_dim))
+
+            mesh_dim_strategies.append(placement_list)
+
+        # split contracting dim
+        for contracting_dim in edims.contracting_dims:
+            placement_list = [Partial()]
+            for input_dim in input_dims:
+                input_contracting_dim = input_dim.index(contracting_dim)
+                placement_list.append(Shard(input_contracting_dim))
+
+            mesh_dim_strategies.append(placement_list)
+
+        # split lhs free dim
+        for lhs_dim in edims.lhs_out_only_dims:
+            lhs_free_dim = output_dim.index(lhs_dim)
+            # this means split the lhs input and output
+            # i.e. S(0), R -> S(0)
+            lhs_placement_list: List[Placement] = [
+                Shard(lhs_free_dim),
+                Shard(lhs_free_dim),
+                Replicate(),
+            ]
+            mesh_dim_strategies.append(lhs_placement_list)
+
+        # split rhs free dim
+        for rhs_dim in edims.rhs_out_only_dims:
+            rhs_free_dim = output_dim.index(rhs_dim)
+            rhs_placement_list: List[Placement] = [
+                Shard(rhs_free_dim),
+                Replicate(),
+                Shard(rhs_free_dim),
+            ]
+            mesh_dim_strategies.append(rhs_placement_list)
+
+        # linearity strategy
+        if linearity:
+            linearity_placement_list: List[Placement] = [Partial()]
+            for input_dim in input_dims:
+                linearity_placement_list.append(Partial())
+            mesh_dim_strategies.append(linearity_placement_list)
+
+        all_mesh_dim_strategies.append(mesh_dim_strategies)
+
+    # generate strategies for entire mesh
+    strategy_combs = itertools.product(*all_mesh_dim_strategies)
+
+    # TODO: filter out invalid strategies, at this point we generate
+    # all possible strategies without considering the whether the tensor
+    # dim could be sharded or not, we would need to filter out invalid
+    # strategies base on the actual tensor shape
+    # (i.e. for Shard, tensor dim size must > mesh size)
+    all_strategies = []
+    for strategy_comb in strategy_combs:
+        spec_list = []
+        for specs in zip(*strategy_comb):
+            spec_list.append(DTensorSpec(mesh, tuple(specs)))
+        strat = PlacementStrategy(output_specs=spec_list[0], input_specs=spec_list[1:])
+        all_strategies.append(strat)
+
+    return OpStrategy(all_strategies)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_embedding_ops.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_embedding_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae333b800ffcb8dd3b3a827aedb7efcb427be61e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_embedding_ops.py
@@ -0,0 +1,274 @@
+# mypy: allow-untyped-decorators
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and affiliates
+# implement matrix related ops for distributed tensor
+from dataclasses import dataclass, field
+from typing import cast, Optional
+
+import torch
+import torch.distributed._functional_collectives as funcol
+from torch.distributed.device_mesh import DeviceMesh
+from torch.distributed.tensor._op_schema import (
+    OpSchema,
+    OpStrategy,
+    PlacementList,
+    StrategyType,
+)
+from torch.distributed.tensor._ops.utils import (
+    expand_to_full_mesh_op_strategy,
+    register_op_strategy,
+)
+from torch.distributed.tensor.placement_types import (
+    Partial,
+    Placement,
+    Replicate,
+    Shard,
+)
+
+
+aten = torch.ops.aten
+
+
+@dataclass
+class MaskBuffer:
+    data: Optional[torch.Tensor] = None
+    # refcount allows shared usage of the MaskBuffer, as long as all users have the same data
+    refcount: int = 0
+
+    def materialize_mask(self, mask):
+        if self.refcount == 0:
+            self.data = mask
+        else:
+            assert self.data is not None
+            if not torch.equal(self.data, mask):
+                raise RuntimeError(
+                    "MaskBuffer has been materialized with conflicting data"
+                )
+        self.refcount += 1
+
+    def release_mask(self):
+        if self.refcount == 0 or self.data is None:
+            raise RuntimeError("MaskBuffer has not been materialized")
+        self.refcount -= 1
+        if self.refcount == 0:
+            self.data = None
+
+    def apply_mask(self, tensor):
+        if self.refcount == 0 or self.data is None:
+            raise RuntimeError("MaskBuffer has not been materialized")
+
+        # NOTE: _MaskPartial is being used by the embedding op and the gather op.
+        # For gather, the mask has the same dimension as the output tensor, whereas
+        # the output of the embedding op has an additional dimension compare to the input,
+        # hence the output masking logic below having two different cases.
+        if tensor.ndim == self.data.ndim:
+            tensor[self.data] = 0.0
+        else:
+            tensor[self.data, :] = 0.0
+
+
+@dataclass(frozen=True)
+class _MaskPartial(Partial):
+    """
+    A partial mask placement devised for rowwise sharded embedding op, where we need
+    to mask and adjust the indices to the local embedding shard, embedding masking
+    is a special type of the Partial placement
+
+    NOTE: the lifecycle of this MaskPartial placement follows the corresponding DTensor
+    lifecycle, i.e. the indices_mask would only be alive during the lifetime of the DTensor.
+    """
+
+    mask_buffer: MaskBuffer = field(default_factory=MaskBuffer)
+
+    # required fields for computing the local offset and deriving the mask
+    offset_shape: Optional[torch.Size] = None
+    offset_dim: int = 0
+
+    def _partition_value(
+        self, tensor: torch.Tensor, mesh: DeviceMesh, mesh_dim: int
+    ) -> torch.Tensor:
+        # override parent logic to perform partial mask for embedding
+        num_chunks = mesh.size(mesh_dim)
+        # get local shard size and offset on the embedding_dim
+        assert (
+            self.offset_shape is not None
+        ), "offset_shape needs to be set for _MaskPartial"
+        local_shard_size, local_offset_on_dim = Shard._local_shard_size_on_dim(
+            self.offset_shape[self.offset_dim],
+            num_chunks,
+            mesh.get_local_rank(mesh_dim),
+            return_offset=True,
+        )
+        # Build the input mask and save it for the current partial placement
+        # this is so that the output of embedding op can reuse the same partial
+        # placement saved mask to perform mask + reduction
+        mask = (tensor < local_offset_on_dim) | (
+            tensor >= local_offset_on_dim + local_shard_size
+        )
+        # mask the input tensor
+        masked_tensor = tensor.clone() - local_offset_on_dim
+        masked_tensor[mask] = 0
+        # materialize the mask buffer to be used for reduction
+        self.mask_buffer.materialize_mask(mask)
+        return masked_tensor
+
+    def _reduce_value(
+        self, tensor: torch.Tensor, mesh: DeviceMesh, mesh_dim: int
+    ) -> torch.Tensor:
+        # by the time we ned reduction, we should have already saved the mask
+        assert self.mask_buffer.data is not None
+
+        # apply the mask to the tensor that pending reduction
+        self.mask_buffer.apply_mask(tensor)
+
+        # clear the mask buffer
+        self.mask_buffer.release_mask()
+
+        # perform sum reduction
+        return funcol.all_reduce(
+            tensor, reduceOp=self.reduce_op, group=(mesh, mesh_dim)
+        )
+
+    def _reduce_shard_value(
+        self,
+        tensor: torch.Tensor,
+        mesh: DeviceMesh,
+        mesh_dim: int,
+        shard_spec: Placement,
+    ) -> torch.Tensor:
+        # by the time we ned reduction, we should have already saved the mask
+        assert self.mask_buffer.data is not None
+
+        # apply the mask to the tensor that pending reduction
+        self.mask_buffer.apply_mask(tensor)
+
+        # clear the mask buffer
+        self.mask_buffer.release_mask()
+
+        # call reduce_shard_tensor of the shard_spec.
+        shard_spec = cast(Shard, shard_spec)
+        return shard_spec._reduce_shard_tensor(tensor, mesh, self.reduce_op, mesh_dim)
+
+    def __eq__(self, other: object) -> bool:
+        if not isinstance(other, _MaskPartial):
+            return False
+
+        # if either data is not None, we invalidate the sharding cache, as this indicates
+        # the current MaskPartial placement is still in use and should not be used for cache hit.
+        if self.mask_buffer.data is not None or other.mask_buffer.data is not None:
+            return False
+
+        return (
+            self.reduce_op == other.reduce_op
+            and self.offset_shape == other.offset_shape
+            and self.offset_dim == other.offset_dim
+        )
+
+    def __hash__(self) -> int:
+        return 1 + hash(
+            (
+                self.reduce_op,
+                self.offset_shape,
+                self.offset_dim,
+            )
+        )
+
+    def __repr__(self) -> str:
+        """
+        machine readable representation of the MaskPartial placement
+        """
+        return f"_MaskPartial(offset_shape={self.offset_shape}, offset_dim={self.offset_dim})"
+
+    def __str__(self) -> str:
+        """
+        human readable representation of the MaskPartial placement
+        """
+        return "MaskP"
+
+
+@register_op_strategy(aten.embedding.default)
+def embedding_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> StrategyType:
+    """
+    This strategy handles embedding op. We have two possible embedding shardings:
+    rowwise and colwise
+    """
+    weight_strategy = cast(OpStrategy, op_schema.args_schema[0])
+    indices_strategy = cast(OpStrategy, op_schema.args_schema[1])
+
+    weight_shape = weight_strategy.shape
+    indices_shape = indices_strategy.shape
+    output_emd_dim = len(indices_shape)
+
+    single_mesh_dim_strategies = []
+
+    # placement list stores placements of [output, weight, input_indices]
+    # first we always have replicate all for inputs and output
+    all_replicate: PlacementList = [Replicate()] * 3
+    single_mesh_dim_strategies.append(all_replicate)
+
+    # colwise sharding, output shard on last dim, weight shard on dim 1, input replicate
+    colwise_sharding: PlacementList = [Shard(output_emd_dim), Shard(1), Replicate()]
+    single_mesh_dim_strategies.append(colwise_sharding)
+
+    # rowwise sharding, output is embedding partial, weight shard on dim 0, input accepts embedding partial
+    embedding_partial_placement = _MaskPartial(offset_shape=weight_shape, offset_dim=0)
+
+    # NOTE we want to reuse the same mask partial placement so that we can reuse the same mask that generates
+    # from the input indices and use it for output reduction
+    rowwise_sharding: PlacementList = [
+        embedding_partial_placement,
+        Shard(0),
+        embedding_partial_placement,
+    ]
+    single_mesh_dim_strategies.append(rowwise_sharding)
+
+    # batch dim sharding, weight replicated, input can shard on any dim, output follows input
+    for input_dim in range(len(indices_shape)):
+        batch_sharding: PlacementList = [
+            Shard(input_dim),
+            Replicate(),
+            Shard(input_dim),
+        ]
+        single_mesh_dim_strategies.append(batch_sharding)
+
+    return expand_to_full_mesh_op_strategy(mesh, op_schema, single_mesh_dim_strategies)
+
+
+@register_op_strategy(aten.embedding_dense_backward.default)
+def embedding_dense_backward_strategy(
+    mesh: DeviceMesh, op_schema: OpSchema
+) -> StrategyType:
+    """
+    This strategy handles embedding op. We have two possible embedding shardings:
+    rowwise and colwise
+    """
+    grad_out_strategy = cast(OpStrategy, op_schema.args_schema[0])
+    indices_strategy = cast(OpStrategy, op_schema.args_schema[1])
+
+    grad_out_shape = grad_out_strategy.shape
+    indices_shape = indices_strategy.shape
+    grad_out_ndim = len(grad_out_shape)
+
+    single_mesh_dim_strategies = []
+
+    # placement list stores placements of [output, weight, input_indices]
+    # first we always have replicate all for inputs and output
+    all_replicate: PlacementList = [Replicate()] * 3
+    single_mesh_dim_strategies.append(all_replicate)
+
+    # colwise sharding backward, grad_out shard on last dim, input replicate,
+    # weight grad shard colwise
+    colwise_sharding: PlacementList = [Shard(1), Shard(grad_out_ndim - 1), Replicate()]
+    single_mesh_dim_strategies.append(colwise_sharding)
+
+    # batch dim sharding, weight replicated, grad_out/input have same sharding
+    # that can shard on any dim, weight grad partial
+    for input_dim in range(len(indices_shape)):
+        batch_sharding: PlacementList = [Partial(), Shard(input_dim), Shard(input_dim)]
+        single_mesh_dim_strategies.append(batch_sharding)
+
+    # grad_out partial, input replicate, weight grad keep partial
+    partial_sharding: PlacementList = [Partial(), Partial(), Replicate()]
+    single_mesh_dim_strategies.append(partial_sharding)
+
+    return expand_to_full_mesh_op_strategy(mesh, op_schema, single_mesh_dim_strategies)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_experimental_ops.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_experimental_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..d4ab5cc3aeeb020dbee5b71ae76c9d977fcdb0a2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_experimental_ops.py
@@ -0,0 +1,28 @@
+# mypy: allow-untyped-decorators
+# Copyright (c) Meta Platforms, Inc. and affiliates
+# implement matrix related ops for distributed tensor
+
+import torch
+from torch.distributed.tensor._dtensor_spec import DTensorSpec
+from torch.distributed.tensor._op_schema import (
+    OpSchema,
+    OpStrategy,
+    PlacementStrategy,
+    StrategyType,
+)
+from torch.distributed.tensor._ops.utils import register_op_strategy
+from torch.distributed.tensor.device_mesh import DeviceMesh
+from torch.distributed.tensor.placement_types import Replicate
+
+
+aten = torch.ops.aten
+
+
+@register_op_strategy(aten.slice_backward.default)
+def slice_backward_rules(mesh: DeviceMesh, op_schema: OpSchema) -> StrategyType:
+    """
+    slice_backward is a new_zeros + slice_scatter, we only allow replication
+    on the input/output for now since new_zeros would produce replication
+    """
+    replicate_spec = DTensorSpec(mesh, tuple([Replicate()] * mesh.ndim))
+    return OpStrategy([PlacementStrategy(replicate_spec)])
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_math_ops.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_math_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..4905c3389185954ffbe1caf67d2c8d1803a9b749
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_math_ops.py
@@ -0,0 +1,1058 @@
+# mypy: allow-untyped-decorators
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and affiliates
+import math
+from dataclasses import dataclass
+from enum import Enum
+from typing import cast, List, Optional, Sequence, Tuple, Union
+
+import torch
+from torch.distributed.device_mesh import DeviceMesh
+from torch.distributed.tensor._dtensor_spec import DTensorSpec
+from torch.distributed.tensor._op_schema import (
+    OpSchema,
+    OpStrategy,
+    PlacementList,
+    PlacementStrategy,
+    RuntimeSchemaInfo,
+    TupleStrategy,
+)
+from torch.distributed.tensor._ops.utils import (
+    as_list,
+    expand_to_full_mesh_op_strategy,
+    generate_redistribute_costs,
+    is_tensor_evenly_shardable,
+    normalize_dim,
+    normalize_dims,
+    register_op_strategy,
+)
+from torch.distributed.tensor._utils import normalize_to_torch_size
+from torch.distributed.tensor.placement_types import (
+    Partial,
+    Placement,
+    Replicate,
+    Shard,
+)
+
+
+aten = torch.ops.aten
+
+
+class Reduction(Enum):
+    NONE = 0
+    MEAN = 1
+    SUM = 2
+
+
+@dataclass(frozen=True)
+class NormReduction:
+    norm_type: Union[int, float, str]
+
+
+ReductionOpType = Union[NormReduction, str]
+
+
+@dataclass(frozen=True)
+class _NormPartial(Partial):
+    """
+    This placement is used for partial vector norm.
+
+    For p-norms (where p not inf or -inf), the p-norm over n elements computes
+        (sum_i x_i^p)^(1/p)
+    where the sum is from i=1 to n. The reduction op is the p-norm itself.
+    For example, consider 2 ranks, a (4,) tensor sharded on dim-0, and 2-norm:
+        Rank 0: [t1, t2] | Rank 1: [t3, t4]
+    After computing 2-norm per gradient (partial placement):
+        Rank 0: [sqrt(t1^2 + t2^2)] | Rank 1: [sqrt(t3^2 + t4^2)]
+    Converting from partial to replicate wants to ultimately get:
+        Rank 0/1: [sqrt(t1^2 + t2^2 + t3^2 + t4^2)]
+    This can be achieved by computing 2-norm on each rank's result. This holds
+    similarly for inf and -inf norm. For 0-norm, the reduction op is sum.
+    """
+
+    norm_type: Union[int, float, str] = 2
+
+    def __post_init__(self):
+        """Set the appropriate reduce op based on the norm type."""
+        # Use `object.__setattr__` to bypass frozen checks
+        if self.norm_type in (float("inf"), "inf"):
+            object.__setattr__(self, "reduce_op", "max")
+        elif self.norm_type in (float("-inf"), "-inf"):
+            object.__setattr__(self, "reduce_op", "min")
+        elif isinstance(self.norm_type, (int, float)):
+            object.__setattr__(self, "reduce_op", "sum")
+        else:
+            raise NotImplementedError(f"Unsupported norm type: {self.norm_type}")
+
+    def _partition_value(
+        self, tensor: torch.Tensor, mesh: DeviceMesh, mesh_dim: int
+    ) -> torch.Tensor:
+        """
+        For example, consider 4 ranks, a (3,) replicated tensor, and 2-norm:
+            Ranks 0 and 1: sqrt(t1^2 + t2^2 + t3^3)
+        To convert from replicated to partial, we want f(x) such that
+            sqrt(t1^2 + t2^2 + t3^3) = sqrt(4f(t1)^2 + 4f(t2)^2 + 4f(t3)^2)
+                                     = sqrt(4) sqrt(f(t1)^2 + f(t2)^2 + f(t3)^2).
+        One such f(x) is f(x) = x / sqrt(4). This generalizes to d ranks and
+        p-norm as f(x) = x / d^(1/p).
+        """
+        if self.reduce_op in ("max", "min"):
+            return tensor
+        elif self.reduce_op == "sum":
+            if self.norm_type == 0:
+                raise NotImplementedError(f"Unsupported norm type:: {self.norm_type}")
+            elif self.norm_type == 1:
+                return tensor / mesh.size(mesh_dim)
+            assert isinstance(self.norm_type, (int, float))
+            return tensor / math.pow(mesh.size(mesh_dim), 1 / self.norm_type)
+        raise NotImplementedError(self.reduce_op)
+
+    def _reduce_shard_value(
+        self,
+        tensor: torch.Tensor,
+        mesh: DeviceMesh,
+        mesh_dim: int,
+        shard_spec: Placement,
+    ) -> torch.Tensor:
+        assert isinstance(shard_spec, Shard), f"{shard_spec}"
+        tensor = self._pre_reduce_transform(tensor)
+        reduced_tensor = super()._reduce_shard_value(tensor, mesh, mesh_dim, shard_spec)
+        return self._post_reduce_transform(reduced_tensor)
+
+    def _reduce_value(
+        self, tensor: torch.Tensor, mesh: DeviceMesh, mesh_dim: int
+    ) -> torch.Tensor:
+        tensor = self._pre_reduce_transform(tensor)
+        reduced_tensor = super()._reduce_value(tensor, mesh, mesh_dim)
+        return self._post_reduce_transform(reduced_tensor)
+
+    def _pre_reduce_transform(self, tensor: torch.Tensor) -> torch.Tensor:
+        if self.reduce_op == "sum":
+            assert isinstance(self.norm_type, (int, float)), f"{self.norm_type}"
+            if self.norm_type != 0 and self.norm_type != 1:
+                return tensor**self.norm_type
+        return tensor
+
+    def _post_reduce_transform(self, tensor: torch.Tensor) -> torch.Tensor:
+        if self.reduce_op == "sum":
+            assert isinstance(self.norm_type, (int, float)), f"{self.norm_type}"
+            if self.norm_type != 0 and self.norm_type != 1:
+                return tensor ** (1.0 / self.norm_type)
+        return tensor
+
+    def __eq__(self, other: object) -> bool:
+        if not isinstance(other, _NormPartial):
+            return False
+        return self.norm_type == other.norm_type
+
+    def __hash__(self) -> int:
+        return 1 + hash(self.norm_type)
+
+
+def _infer_reduction_dims(dims_arg: object, ndim: int) -> Optional[List[int]]:
+    if dims_arg is None:
+        return None
+    dims = cast(List[int], as_list(dims_arg))
+    dims = cast(List[int], normalize_dims(dims, ndim))
+    empty_dims = [[0], [-1], []]
+    if ndim == 0 and dims_arg in empty_dims:
+        return None
+    return dims
+
+
+def _infer_reduce_dims_map(
+    reduction_dims: List[int], input_ndim: int, keep_dim=False
+) -> List[int]:
+    reduction_dims_map = []
+    new_dim_count = 0
+    for input_dim in range(input_ndim):
+        if input_dim in reduction_dims and not keep_dim:
+            # if input dim in reduction dims, mark it as -1
+            reduction_dims_map.append(-1)
+        else:
+            # otherwise mark it as the new dim
+            reduction_dims_map.append(new_dim_count)
+            new_dim_count += 1
+
+    return reduction_dims_map
+
+
+def _replicate_dims_start_at(
+    placements: Sequence[Placement], start_dim: int = 0
+) -> Tuple[Placement, ...]:
+    new_placements: List[Placement] = []
+    for p in placements:
+        if p.is_partial() or (isinstance(p, Shard) and p.dim >= start_dim):
+            new_placements.append(Replicate())  # make it replicate
+        else:
+            new_placements.append(p)  # keep the placement
+    return tuple(new_placements)
+
+
+# return new_placements which align with placements but skip the skipped_dim
+def _skip_dim(
+    placements: Tuple[Placement, ...], skipped_dim: int
+) -> Tuple[Placement, ...]:
+    new_placements: List[Placement] = []
+    for p in placements:
+        if isinstance(p, Shard) and p.dim >= skipped_dim:
+            new_placements.append(Shard(p.dim - 1))
+        else:
+            new_placements.append(p)
+    return tuple(new_placements)
+
+
+def replicate_reduction_dims(
+    placements: Tuple[Placement, ...], reduction_dims: List[int]
+) -> Tuple[Placement, ...]:
+    # replicate the reduction dims if not reduction_linear
+    new_placements: List[Placement] = []
+
+    for p in placements:
+        if p.is_partial():
+            new_placements.append(Replicate())
+        elif isinstance(p, Shard) and p.dim in reduction_dims:
+            new_placements.append(Replicate())
+        else:
+            new_placements.append(p)
+
+    return tuple(new_placements)
+
+
+def map_placements_after_reduction(
+    placements: Tuple[Placement, ...],
+    reduction_dims: List[int],
+    reduction_dims_map: List[int],
+    reduction_op: ReductionOpType,
+) -> Tuple[Placement, ...]:
+    """
+    Map each placement based on the output shape after reduction.
+    """
+    new_placements: List[Placement] = []
+    for placement in placements:
+        if isinstance(placement, (Replicate, Partial)):
+            new_placements.append(placement)
+        else:
+            assert isinstance(placement, Shard)
+            shard_dim = placement.dim
+            new_shard_dim = reduction_dims_map[shard_dim]
+            if new_shard_dim == -1 or shard_dim in reduction_dims:
+                # if new_shard_dim collapsed or its in the reduction dims
+                # (i.e. for the case where keepdims=True), we generate partial
+                new_placements.append(get_placement_from_reduction_op(reduction_op))
+            else:
+                new_placements.append(Shard(new_shard_dim))
+    return tuple(new_placements)
+
+
+def get_placement_from_reduction_op(reduction_op: ReductionOpType) -> Placement:
+    if isinstance(reduction_op, NormReduction):
+        return _NormPartial(norm_type=reduction_op.norm_type)
+    return Partial(reduction_op)
+
+
+def common_reduction_strategy(
+    mesh: DeviceMesh,
+    input_strategy: OpStrategy,
+    reduce_dims: List[int],
+    keep_dim: bool = False,
+    reduction_linear: bool = True,
+    reduction_op: ReductionOpType = "sum",
+) -> OpStrategy:
+    """
+    reduction_linear means that the reduction `f` follows this rule:
+        f([f(a), f(b)]) = f([a, b])
+
+    reduction linear should be super set of linearity.
+    """
+    # by default follow reduction input strategy
+    reduction_strategy = OpStrategy([])
+
+    for strtg in input_strategy.strategies:
+        if not reduction_linear:
+            # input placements for this strategy should clear out pending sum and sharding
+            # on the reduction dimension
+            input_placements = replicate_reduction_dims(
+                strtg.output_spec.placements, reduce_dims
+            )
+        else:
+            input_placements = strtg.output_spec.placements
+
+        input_spec = DTensorSpec(
+            mesh=mesh,
+            placements=input_placements,
+            tensor_meta=strtg.output_spec.tensor_meta,
+        )
+
+        reduce_dims_map = _infer_reduce_dims_map(reduce_dims, input_spec.ndim, keep_dim)
+        out_placements = map_placements_after_reduction(
+            input_spec.placements, reduce_dims, reduce_dims_map, reduction_op
+        )
+        redistribute_cost = [generate_redistribute_costs(input_strategy, input_spec)]
+        reduction_strategy.strategies.append(
+            PlacementStrategy(
+                output_specs=DTensorSpec(
+                    mesh=mesh,
+                    placements=out_placements,
+                ),
+                input_specs=(input_spec,),
+                redistribute_cost=redistribute_cost,
+            )
+        )
+
+    return reduction_strategy
+
+
+LINEAR_REDUCTION_OP_MAP = {
+    aten.all.default: "sum",
+    aten.all.dim: "sum",
+    aten.sum.default: "sum",
+    aten.sum.dim_IntList: "sum",
+    aten.prod.default: "product",
+    aten.prod.dim_int: "product",
+    aten.prod.int_out: "product",
+    aten.mean.default: "avg",
+    aten.mean.dim: "avg",
+    aten.mean.out: "avg",
+    aten.max.default: "max",
+    aten.max.dim: "max",
+    aten.max.out: "max",
+    aten.min.default: "min",
+    aten.min.dim: "min",
+    aten.min.out: "min",
+    aten.any.default: "sum",
+    aten.any.dim: "sum",
+    aten.any.out: "sum",
+}
+
+
+@register_op_strategy(
+    list(LINEAR_REDUCTION_OP_MAP.keys()), schema_info=RuntimeSchemaInfo(1)
+)
+def linear_reduction_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
+    args_schema = op_schema.args_schema
+    input_strategy = args_schema[0]
+    assert isinstance(input_strategy, OpStrategy)
+    dims = None
+    if len(op_schema.args_schema) > 1:
+        dims = _infer_reduction_dims(args_schema[1], input_strategy.ndim)
+
+    reduce_dims = list(range(input_strategy.ndim)) if dims is None else dims
+
+    keep_dim = len(op_schema.args_schema) > 2 and bool(op_schema.args_schema[2])
+    reduction_op = LINEAR_REDUCTION_OP_MAP[op_schema.op]
+    return common_reduction_strategy(
+        mesh,
+        input_strategy,
+        reduce_dims,
+        keep_dim=keep_dim,
+        reduction_linear=True,
+        reduction_op=reduction_op,
+    )
+
+
+@register_op_strategy(
+    [aten.var.correction, aten.var.correction_out],
+    schema_info=RuntimeSchemaInfo(1, ["keepdim"]),
+)
+def var_reduction_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
+    args_schema = op_schema.args_schema
+    input_strategy = args_schema[0]
+    assert isinstance(input_strategy, OpStrategy)
+    dims = None
+    if len(op_schema.args_schema) > 1:
+        dims = _infer_reduction_dims(args_schema[1], input_strategy.ndim)
+
+    reduce_dims = list(range(input_strategy.ndim)) if dims is None else dims
+
+    keep_dim = cast(bool, op_schema.kwargs_schema.get("keepdim", False))
+    return common_reduction_strategy(
+        mesh, input_strategy, reduce_dims, keep_dim=keep_dim, reduction_linear=False
+    )
+
+
+@register_op_strategy(
+    [aten.linalg_vector_norm.default], schema_info=RuntimeSchemaInfo(1)
+)
+def vector_norm_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
+    args_schema = op_schema.args_schema
+    input_strategy = args_schema[0]
+    assert isinstance(input_strategy, OpStrategy)
+    norm_type = args_schema[1] if len(args_schema) > 1 else 2
+    assert isinstance(norm_type, (int, float, str)), f"{norm_type}"
+    dim = args_schema[2] if len(args_schema) > 2 else None
+    keepdim = args_schema[3] if len(args_schema) > 3 else False
+    dims = _infer_reduction_dims(dim, input_strategy.ndim)
+    reduce_dims = list(range(input_strategy.ndim)) if dims is None else dims
+    return common_reduction_strategy(
+        mesh,
+        input_strategy,
+        reduce_dims,
+        keep_dim=cast(bool, keepdim),
+        reduction_linear=True,
+        reduction_op=NormReduction(norm_type),
+    )
+
+
+@register_op_strategy(
+    [aten._foreach_norm.Scalar], schema_info=RuntimeSchemaInfo(1, needs_pytree=True)
+)
+def foreach_norm_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> TupleStrategy:
+    args_schema = op_schema.args_schema
+    input_tuple_strategy = args_schema[0]
+    assert isinstance(input_tuple_strategy, TupleStrategy)
+    norm_type = args_schema[1] if len(args_schema) > 1 else 2
+    assert isinstance(norm_type, (int, float, str)), f"{norm_type}"
+    output_tuple_strategy_childs: List[OpStrategy] = []
+    for op_strategy in input_tuple_strategy.childs:
+        assert isinstance(op_strategy, OpStrategy), f"{op_strategy}"
+        reduce_dims = list(range(op_strategy.ndim))
+        output_strategy = common_reduction_strategy(
+            mesh,
+            op_strategy,
+            reduce_dims,
+            reduction_linear=True,
+            reduction_op=NormReduction(norm_type),
+        )
+        output_tuple_strategy_childs.append(output_strategy)
+    return TupleStrategy(output_tuple_strategy_childs)
+
+
+@register_op_strategy(
+    [
+        aten._linalg_svd.default,
+        aten.linalg_qr.default,
+        # TODO: The diagonal ops can have an improved sharding strategy for
+        # shard placements that does not require redistributing to replicate.
+        aten.diagonal_copy.default,
+        aten.diag_embed.default,
+        aten.diag.default,
+        aten.diagonal.default,
+        aten.tril.default,
+        aten.triu.default,
+        aten._linalg_eigh.default,
+    ],
+    schema_info=RuntimeSchemaInfo(1),
+)
+def linalg_replicate_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
+    """
+    Since we do not have a simple way to compute some linear algebra operations
+    like SVD or QR decomposition, always fall back to replicate.
+    """
+    args_schema = op_schema.args_schema
+    input_strategy = args_schema[0]
+    assert isinstance(input_strategy, OpStrategy), f"{input_strategy}"
+    output_strategies: List[PlacementStrategy] = []
+    for placement_strategy in input_strategy.strategies:
+        replicate_placements = tuple(Replicate() for _ in range(mesh.ndim))
+        replicate_spec = DTensorSpec(
+            mesh=mesh,
+            placements=replicate_placements,
+            tensor_meta=placement_strategy.output_spec.tensor_meta,
+        )
+        redistribute_cost = [
+            generate_redistribute_costs(input_strategy, replicate_spec)
+        ]
+        replicate_strategy = PlacementStrategy(
+            output_specs=replicate_spec,
+            input_specs=(replicate_spec,),
+            redistribute_cost=redistribute_cost,
+        )
+        output_strategies.append(replicate_strategy)
+    return OpStrategy(output_strategies)
+
+
+@register_op_strategy(
+    [aten._log_softmax.default, aten._softmax.default, aten._safe_softmax.default],
+    schema_info=RuntimeSchemaInfo(1),
+)
+def softmax_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
+    input_strategy, softmax_dim, *_ = op_schema.args_schema
+    input_strategy = cast(OpStrategy, input_strategy)
+    softmax_dim = cast(int, softmax_dim)
+    softmax_dim = normalize_dim(softmax_dim, input_strategy.ndim)
+
+    output_strategy = OpStrategy([])
+    for idx, input_placement_strategy in enumerate(input_strategy.strategies):
+        redistribute_costs = []
+        input_src_spec = input_placement_strategy.output_spec
+
+        # make sure input is replicated along the softmax dim
+        input_target_spec = DTensorSpec(
+            mesh=mesh,
+            placements=replicate_reduction_dims(
+                input_src_spec.placements, [softmax_dim]
+            ),
+            tensor_meta=input_src_spec.tensor_meta,
+        )
+        redistribute_costs.append(
+            generate_redistribute_costs(input_strategy, input_target_spec)
+        )
+        output_target_spec = input_target_spec
+        output_strategy.strategies.append(
+            PlacementStrategy(
+                output_specs=output_target_spec,
+                input_specs=[input_target_spec],
+                redistribute_cost=redistribute_costs,
+            )
+        )
+
+    return output_strategy
+
+
+@register_op_strategy(
+    [
+        aten._log_softmax_backward_data.default,
+        aten._softmax_backward_data.default,
+    ],
+    schema_info=RuntimeSchemaInfo(2),
+)
+def softmax_backward_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
+    grad_out_strategy, out_strategy, softmax_dim, _ = op_schema.args_schema
+    grad_out_strategy = cast(OpStrategy, grad_out_strategy)
+    out_strategy = cast(OpStrategy, out_strategy)
+    softmax_dim = cast(int, softmax_dim)
+    softmax_dim = normalize_dim(softmax_dim, grad_out_strategy.ndim)
+
+    grad_in_strategy = OpStrategy([])
+    for grad_out_placement_strat, out_placement_strat in zip(
+        grad_out_strategy.strategies, out_strategy.strategies
+    ):
+        # follow the sharding of the grad_out or out depending on which has more shards
+        grad_out_src_spec = grad_out_placement_strat.output_spec
+        out_src_spec = out_placement_strat.output_spec
+        src_spec = (
+            grad_out_src_spec
+            if grad_out_src_spec.num_shards >= out_src_spec.num_shards
+            else out_src_spec
+        )
+
+        # make sure inputs are replicated along the softmax dim
+        tgt_spec = DTensorSpec(
+            mesh=mesh,
+            placements=replicate_reduction_dims(src_spec.placements, [softmax_dim]),
+        )
+        redist_grad_out_cost = generate_redistribute_costs(grad_out_strategy, tgt_spec)
+        redist_out_cost = generate_redistribute_costs(out_strategy, tgt_spec)
+        grad_in_strategy.strategies.append(
+            PlacementStrategy(
+                output_specs=tgt_spec,
+                redistribute_cost=[redist_grad_out_cost, redist_out_cost],
+            )
+        )
+
+    return grad_in_strategy
+
+
+@register_op_strategy(
+    [aten.nll_loss_forward.default, aten.nll_loss2d_forward.default],
+    schema_info=RuntimeSchemaInfo(3),
+)
+def nll_loss_forward_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
+    assert len(op_schema.args_schema) == 5
+    (
+        input_strategy,
+        target_strategy,
+        weight_strategy,
+        reduction,
+        _,
+    ) = op_schema.args_schema
+    input_strategy = cast(OpStrategy, input_strategy)
+    target_strategy = cast(OpStrategy, target_strategy)
+    reduction = cast(int, reduction)
+
+    input_shape = input_strategy.shape
+    channel_dim = 1 if len(input_shape) >= 2 else 0
+
+    output_strategy = OpStrategy([])
+    for idx, input_placement_strategy in enumerate(input_strategy.strategies):
+        op_args_target_specs = []
+        redistribute_costs = []
+
+        # make sure input is replicated along the channel dim
+        input_src_spec = input_placement_strategy.output_spec
+        input_expected_spec = DTensorSpec(
+            mesh=mesh,
+            placements=replicate_reduction_dims(
+                input_src_spec.placements, [channel_dim]
+            ),
+            tensor_meta=input_src_spec.tensor_meta,
+        )
+        op_args_target_specs.append(input_expected_spec)
+        redistribute_costs.append(
+            generate_redistribute_costs(input_strategy, input_expected_spec)
+        )
+
+        # target doesn't have channel dim, and it follows input on other dims
+        target_src_spec = target_strategy.strategies[idx].output_spec
+        target_expected_spec = DTensorSpec(
+            mesh=mesh,
+            placements=_skip_dim(input_expected_spec.placements, channel_dim),
+            tensor_meta=target_src_spec.tensor_meta,
+        )
+        op_args_target_specs.append(target_expected_spec)
+        redistribute_costs.append(
+            generate_redistribute_costs(target_strategy, target_expected_spec)
+        )
+
+        # weight tensor, if given, has to be a Tensor of size input_shape[channel_dim]
+        # make sure it is replicated
+        if weight_strategy is not None:
+            assert isinstance(weight_strategy, OpStrategy)
+            weight_src_spec = weight_strategy.strategies[idx].output_spec
+            weight_expected_spec = DTensorSpec(
+                mesh=mesh,
+                placements=_replicate_dims_start_at(weight_src_spec.placements),
+                tensor_meta=weight_src_spec.tensor_meta,
+            )
+            op_args_target_specs.append(weight_expected_spec)
+            redistribute_costs.append(
+                generate_redistribute_costs(weight_strategy, weight_expected_spec)
+            )
+
+        if reduction == Reduction.NONE.value:
+            output_expected_spec = target_expected_spec
+            total_weight_expected_spec = DTensorSpec(
+                mesh=mesh, placements=tuple([Replicate()] * mesh.ndim)
+            )
+        else:
+            if reduction == Reduction.MEAN.value:
+                reduction_op = "avg"
+                if not is_tensor_evenly_shardable(
+                    target_expected_spec.shape, target_expected_spec
+                ):
+                    raise ValueError(
+                        "The intermediate results of nll_loss cannot be evenly sharded, \
+                        resulting in biased mean result."
+                    )
+            else:  # reduction == Reduction.SUM.value:
+                reduction_op = "sum"
+            reduce_dims = list(range(target_expected_spec.ndim))
+            reduce_dims_map = _infer_reduce_dims_map(
+                reduce_dims, target_expected_spec.ndim, keep_dim=False
+            )
+            out_placements = map_placements_after_reduction(
+                target_expected_spec.placements,
+                reduce_dims,
+                reduce_dims_map,
+                reduction_op,
+            )
+            output_expected_spec = DTensorSpec(
+                mesh=mesh,
+                placements=out_placements,
+            )
+
+            # whether reduction is sum or mean, the total weight has to be summed up if not replicated
+            total_weight_placements = map_placements_after_reduction(
+                target_expected_spec.placements,
+                reduce_dims,
+                reduce_dims_map,
+                "sum",
+            )
+            total_weight_expected_spec = DTensorSpec(
+                mesh=mesh,
+                placements=total_weight_placements,
+            )
+
+        output_strategy.strategies.append(
+            PlacementStrategy(
+                output_specs=(output_expected_spec, total_weight_expected_spec),
+                input_specs=op_args_target_specs,
+                redistribute_cost=redistribute_costs,
+            )
+        )
+
+    return output_strategy
+
+
+@register_op_strategy(
+    [aten.nll_loss_backward.default, aten.nll_loss2d_backward.default],
+    schema_info=RuntimeSchemaInfo(4),
+)
+def nll_loss_backward_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
+    assert len(op_schema.args_schema) == 7
+    (
+        grad_out_strategy,
+        input_strategy,
+        target_strategy,
+        weight_strategy,
+        reduction,
+        _,
+        total_weight_strategy,
+    ) = op_schema.args_schema
+    grad_out_strategy = cast(OpStrategy, grad_out_strategy)
+    input_strategy = cast(OpStrategy, input_strategy)
+    target_strategy = cast(OpStrategy, target_strategy)
+    reduction = cast(int, reduction)
+    total_weight_strategy = cast(OpStrategy, total_weight_strategy)
+
+    input_shape = input_strategy.shape
+    channel_dim = 1 if len(input_shape) >= 2 else 0
+
+    grad_in_strategy = OpStrategy([])
+    for idx, input_placement_strategy in enumerate(input_strategy.strategies):
+        op_args_target_specs = []
+        redistribute_costs = []
+
+        # make sure input is replicated along the channel dim
+        input_src_spec = input_placement_strategy.output_spec
+        input_expected_spec = DTensorSpec(
+            mesh=mesh,
+            placements=replicate_reduction_dims(
+                input_src_spec.placements, [channel_dim]
+            ),
+            tensor_meta=input_src_spec.tensor_meta,
+        )
+        op_args_target_specs.append(input_expected_spec)
+        redistribute_costs.append(
+            generate_redistribute_costs(input_strategy, input_expected_spec)
+        )
+
+        # target doesn't have channel dim, and it follows input on other dims
+        target_src_spec = target_strategy.strategies[idx].output_spec
+        target_expected_spec = DTensorSpec(
+            mesh=mesh,
+            placements=_skip_dim(input_expected_spec.placements, channel_dim),
+            tensor_meta=target_src_spec.tensor_meta,
+        )
+        op_args_target_specs.append(target_expected_spec)
+        redistribute_costs.append(
+            generate_redistribute_costs(target_strategy, target_expected_spec)
+        )
+
+        # grad_out follows target if there is no reduction;
+        # otherwise, it should be a replicated scalar.
+        grad_out_src_spec = grad_out_strategy.strategies[idx].output_spec
+        if reduction == Reduction.NONE.value:
+            grad_out_expected_spec = target_expected_spec
+        else:
+            grad_out_expected_spec = DTensorSpec(
+                mesh=mesh,
+                placements=_replicate_dims_start_at(grad_out_src_spec.placements),
+                tensor_meta=grad_out_src_spec.tensor_meta,
+            )
+        op_args_target_specs.insert(0, grad_out_expected_spec)
+        redistribute_costs.insert(
+            0, generate_redistribute_costs(grad_out_strategy, grad_out_expected_spec)
+        )
+
+        # weight tensor, if given, has to be a Tensor of size input_shape[channel_dim]
+        # make sure it is replicated
+        if weight_strategy is not None:
+            assert isinstance(weight_strategy, OpStrategy)
+            weight_src_spec = weight_strategy.strategies[idx].output_spec
+            weight_expected_spec = DTensorSpec(
+                mesh=mesh,
+                placements=_replicate_dims_start_at(weight_src_spec.placements),
+                tensor_meta=weight_src_spec.tensor_meta,
+            )
+            op_args_target_specs.append(weight_expected_spec)
+            redistribute_costs.append(
+                generate_redistribute_costs(weight_strategy, weight_expected_spec)
+            )
+
+        # total_weight should always be replicated
+        total_weight_src_spec = total_weight_strategy.strategies[idx].output_spec
+        total_weight_expected_spec = DTensorSpec(
+            mesh=mesh,
+            placements=_replicate_dims_start_at(total_weight_src_spec.placements),
+            tensor_meta=total_weight_src_spec.tensor_meta,
+        )
+        op_args_target_specs.append(total_weight_expected_spec)
+        redistribute_costs.append(
+            generate_redistribute_costs(
+                total_weight_strategy, total_weight_expected_spec
+            )
+        )
+
+        grad_in_expected_spec = input_expected_spec
+        grad_in_strategy.strategies.append(
+            PlacementStrategy(
+                output_specs=grad_in_expected_spec,
+                input_specs=op_args_target_specs,
+                redistribute_cost=redistribute_costs,
+            )
+        )
+
+    return grad_in_strategy
+
+
+@register_op_strategy(
+    [aten.native_layer_norm.default],
+    schema_info=RuntimeSchemaInfo(1),
+)
+def layer_norm_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
+    # args must be: input, normalized_shape, weight, bias, eps
+    # for None weight and bias, their corresponding objects will
+    # be None as well. layer_norm_strategy returns one OpStrategy
+    # for the triple return values (out, mean, rstd).
+    assert len(op_schema.args_schema) == 5
+    (
+        input_strategy,
+        normalized_shape,
+        weight_strategy,
+        bias_strategy,
+        _,
+    ) = op_schema.args_schema
+
+    # the current layer norm implementation requires that all
+    # input DTensor's sharding must be in form of OpStrategy
+    assert isinstance(input_strategy, OpStrategy)
+    assert isinstance(normalized_shape, (int, Sequence, torch.Size))
+    normalized_size = normalize_to_torch_size(normalized_shape)
+
+    input_ndim = input_strategy.ndim
+    axis = input_ndim - len(normalized_size)
+
+    # we use OpStrategy because the output (out, mean, rstd)
+    # should have the same placements
+    output_strategy = OpStrategy([])
+    for idx, input_placement_strategy in enumerate(input_strategy.strategies):
+        op_args_target_specs = []
+        redistribute_costs = []
+        input_src_spec = input_placement_strategy.output_spec
+
+        # for the input tensor, we replicate it on the inner dims if necessary
+        # TODO: we can avoid forcing the redistribution once we figure out
+        # how to decompose layer norm
+        input_target_spec = DTensorSpec(
+            mesh=mesh,
+            placements=_replicate_dims_start_at(input_src_spec.placements, axis),
+            tensor_meta=input_src_spec.tensor_meta,
+        )
+        op_args_target_specs.append(input_target_spec)
+        redistribute_costs.append(
+            generate_redistribute_costs(input_strategy, input_target_spec)
+        )
+
+        if weight_strategy is not None:
+            assert isinstance(weight_strategy, OpStrategy)
+            weight_src_spec = weight_strategy.strategies[idx].output_spec
+
+            # for the weight tensor, we replicate it on all dims if necessary
+            # TODO: we can avoid forcing the redistribution once we figure out
+            # how to decompose layer norm
+            weight_target_spec = DTensorSpec(
+                mesh=mesh,
+                placements=_replicate_dims_start_at(weight_src_spec.placements),
+                tensor_meta=weight_src_spec.tensor_meta,
+            )
+            op_args_target_specs.append(weight_target_spec)
+            redistribute_costs.append(
+                generate_redistribute_costs(weight_strategy, weight_target_spec)
+            )
+
+        if bias_strategy is not None:
+            assert isinstance(bias_strategy, OpStrategy)
+            bias_src_spec = bias_strategy.strategies[idx].output_spec
+
+            # for the bias tensor, we replicate it on all dims if necessary
+            # TODO: we can avoid forcing the redistribution once we figure out
+            # how to decompose layer norm
+            bias_target_spec = DTensorSpec(
+                mesh=mesh,
+                placements=_replicate_dims_start_at(bias_src_spec.placements),
+                tensor_meta=bias_src_spec.tensor_meta,
+            )
+            op_args_target_specs.append(bias_target_spec)
+            redistribute_costs.append(
+                generate_redistribute_costs(bias_strategy, bias_target_spec)
+            )
+
+        # the output spec is the same as input spec
+        output_target_spec = input_target_spec
+        output_strategy.strategies.append(
+            PlacementStrategy(
+                output_specs=output_target_spec,
+                input_specs=op_args_target_specs,
+                redistribute_cost=redistribute_costs,
+            )
+        )
+
+    return output_strategy
+
+
+@register_op_strategy(
+    [aten.native_layer_norm_backward.default],
+    schema_info=RuntimeSchemaInfo(2),
+)
+def layer_norm_bwd_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
+    # args must be: grad_out, input, normalized_shape, mean, rstd,
+    # weight, bias, output_mask. For None weight and bias, their
+    # corresponding objects will be None as well.
+    assert len(op_schema.args_schema) == 8
+    (
+        grad_out_strategy,
+        input_strategy,
+        normalized_shape,
+        mean_strategy,
+        rstd_strategy,
+        weight_strategy,
+        bias_strategy,
+        output_mask,
+    ) = op_schema.args_schema
+
+    assert isinstance(grad_out_strategy, OpStrategy)
+    assert isinstance(input_strategy, OpStrategy)
+    assert isinstance(mean_strategy, OpStrategy)
+    assert isinstance(rstd_strategy, OpStrategy)
+
+    assert isinstance(normalized_shape, (int, Sequence, torch.Size))
+    normalized_size = normalize_to_torch_size(normalized_shape)
+    input_ndim = input_strategy.ndim
+    axis = input_ndim - len(normalized_size)
+    outer_dims = list(range(axis))
+
+    assert isinstance(output_mask, List) and len(output_mask) == 3
+
+    # output triple: (d_input, d_weight, d_bias)
+    out_tuple_strategy = OpStrategy([])
+    for idx, input_placement_strategy in enumerate(input_strategy.strategies):
+        # args for PlacementStrategy
+        output_specs_list: List[Optional[DTensorSpec]] = []
+        input_specs_list: List[DTensorSpec] = []
+        redistribute_costs = []
+
+        input_src_spec = input_placement_strategy.output_spec
+        # arg: grad_out
+        # TODO: change the strategy to the following rule.
+        # d_input is basically a product of element-wise mul of
+        # grad_out, rstd, and normalized input, among which rstd
+        # and normalized input (x_hat) should have the same sharding
+        # placements, and grad_out's sharding is determined by the
+        # pointwise result of x_hat and weight/bias.
+        # TODO: now grad_out spec follows input spec. we may need
+        # to change it to apply a pointwise rule over grad_out,
+        # input, and weight.
+        grad_out_target_spec = DTensorSpec(
+            mesh=mesh,
+            placements=_replicate_dims_start_at(input_src_spec.placements, axis),
+            tensor_meta=input_src_spec.tensor_meta,
+        )
+        input_specs_list.append(grad_out_target_spec)
+        redistribute_costs.append(
+            generate_redistribute_costs(grad_out_strategy, grad_out_target_spec)
+        )
+        output_specs_list.append(grad_out_target_spec if output_mask[0] else None)
+
+        # arg: input
+        input_target_spec = DTensorSpec(
+            mesh=mesh,
+            placements=_replicate_dims_start_at(input_src_spec.placements, axis),
+            tensor_meta=input_src_spec.tensor_meta,
+        )
+        input_specs_list.append(input_target_spec)
+        redistribute_costs.append(
+            generate_redistribute_costs(input_strategy, input_target_spec)
+        )
+
+        # arg: mean, rstd
+        mean_src_spec = mean_strategy.strategies[idx].output_spec
+        input_specs_list.append(mean_src_spec)
+        redistribute_costs.append([0.0 for _ in mean_strategy.strategies])
+        rstd_src_spec = rstd_strategy.strategies[idx].output_spec
+        input_specs_list.append(rstd_src_spec)
+        redistribute_costs.append([0.0 for _ in rstd_strategy.strategies])
+
+        def _add_target_input_spec(strategy) -> DTensorSpec:
+            # shared logic for setting the weight and bias target input specs
+            assert isinstance(strategy, OpStrategy)
+            src_spec = strategy.strategies[idx].output_spec
+            # no need to redistribute since they should be replicated in forward pass
+            input_specs_list.append(src_spec)
+            redistribute_costs.append([0.0 for _ in strategy.strategies])
+            return src_spec
+
+        # arg: weight
+        # d_weight = sum(grad_out * (input - mean) / rstd, outer_dim, keepdim=False)
+        if weight_strategy is not None:
+            weight_src_spec = _add_target_input_spec(weight_strategy)
+            # TODO: now d_weight spec follows input spec w/ a reduction.
+            # we may need to change to a pointwise rule over grad_out and
+            # input, then apply a reduction.
+            inp_placements = _replicate_dims_start_at(input_src_spec.placements, axis)
+            reduce_dims_map = _infer_reduce_dims_map(
+                outer_dims, input_src_spec.ndim, False
+            )
+            out_placements = map_placements_after_reduction(
+                inp_placements, outer_dims, reduce_dims_map, "sum"
+            )
+            weight_out_spec = DTensorSpec(
+                mesh=mesh,
+                placements=out_placements,
+                tensor_meta=weight_src_spec.tensor_meta,
+            )
+            output_specs_list.append(weight_out_spec if output_mask[1] else None)
+        else:
+            assert (
+                output_mask[1] is False
+            ), "output_mask[1] should not be `True` while weight argument is `None` in native_layer_norm_backward."
+            output_specs_list.append(None)
+
+        # arg: bias
+        # d_bias = sum(grad_out, outer_dim, keepdim=False)
+        if bias_strategy is not None:
+            bias_src_spec = _add_target_input_spec(bias_strategy)
+            # d_bias spec follows a reduction over grad_out
+            inp_placements = _replicate_dims_start_at(
+                grad_out_target_spec.placements, axis
+            )
+            reduce_dims_map = _infer_reduce_dims_map(
+                outer_dims, grad_out_target_spec.ndim, False
+            )
+            out_placements = map_placements_after_reduction(
+                inp_placements, outer_dims, reduce_dims_map, "sum"
+            )
+            bias_out_spec = DTensorSpec(
+                mesh=mesh,
+                placements=out_placements,
+                tensor_meta=bias_src_spec.tensor_meta,
+            )
+            output_specs_list.append(bias_out_spec if output_mask[2] else None)
+        else:
+            assert (
+                output_mask[2] is False
+            ), "output_mask[2] should not be `True` while bias argument is `None` in native_layer_norm_backward."
+            output_specs_list.append(None)
+
+        out_tuple_strategy.strategies.append(
+            PlacementStrategy(
+                output_specs=tuple(output_specs_list),
+                input_specs=input_specs_list,
+                redistribute_cost=redistribute_costs,
+            )
+        )
+
+    return out_tuple_strategy
+
+
+@register_op_strategy(
+    [aten.topk.default],
+    schema_info=RuntimeSchemaInfo(2),
+)
+def topk_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
+    input_strategy = cast(OpStrategy, op_schema.args_schema[0])
+    k = cast(int, op_schema.args_schema[1])
+    input_shape = input_strategy.shape
+    topk_dim = (
+        cast(int, op_schema.args_schema[2]) if len(op_schema.args_schema) > 2 else -1
+    )
+    topk_dim = normalize_dim(topk_dim, input_strategy.ndim)
+
+    single_mesh_dim_strategies = []
+
+    # two outputs (values, indices), 1 input
+    # replicate always works
+    all_replicate: PlacementList = [Replicate()] * 3
+    single_mesh_dim_strategies.append(all_replicate)
+
+    # every dim except topk dim should work
+    for dim in range(input_strategy.ndim):
+        if dim != topk_dim:
+            dim_shardings: PlacementList = [Shard(dim)] * 3
+            single_mesh_dim_strategies.append(dim_shardings)
+    # TODO: topk on sharded dim requries non-trival reduction, address it later
+
+    return expand_to_full_mesh_op_strategy(
+        mesh, op_schema, single_mesh_dim_strategies, input_index=2
+    )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_matrix_ops.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_matrix_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd9a7a430a70eb2d2fb795ebc402effa832e5058
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_matrix_ops.py
@@ -0,0 +1,500 @@
+# mypy: allow-untyped-decorators
+# Copyright (c) Meta Platforms, Inc. and affiliates
+# implement matrix related ops for distributed tensor
+
+from typing import List
+
+import torch
+from torch.distributed.device_mesh import DeviceMesh
+from torch.distributed.tensor._dtensor_spec import DTensorSpec
+from torch.distributed.tensor._op_schema import (
+    OpSchema,
+    OpStrategy,
+    PlacementList,
+    PlacementStrategy,
+    RuntimeSchemaInfo,
+)
+from torch.distributed.tensor._ops._einsum_strategy import gen_einsum_strategies
+from torch.distributed.tensor._ops.utils import (
+    expand_to_full_mesh_op_strategy,
+    generate_redistribute_costs,
+    infer_broadcast_dims_map,
+    is_tensor_shardable,
+    map_placements_after_broadcast,
+    register_op_strategy,
+)
+from torch.distributed.tensor.placement_types import Placement, Replicate, Shard
+
+
+aten = torch.ops.aten
+
+
+@register_op_strategy(aten.t.default)
+def transpose_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
+    self_strategy = op_schema.args_schema[0]
+    assert isinstance(self_strategy, OpStrategy)
+
+    transpose_strategies = []
+    for input_strategy in self_strategy.strategies:
+        input_spec = input_strategy.output_spec
+        # follow the input spec but transpose the Shard placements
+        output_placements = [
+            Shard(1 - p.dim) if isinstance(p, Shard) else p
+            for p in input_spec.placements
+        ]
+        transpose_strategy = PlacementStrategy(
+            output_specs=DTensorSpec(
+                mesh=input_strategy.output_spec.mesh,
+                placements=tuple(output_placements),
+            ),
+            input_specs=(input_strategy.output_spec,),
+        )
+        transpose_strategies.append(transpose_strategy)
+
+    return OpStrategy(strategies=transpose_strategies)
+
+
+def _mm_like_strategy(
+    mm_equation: str, mesh: DeviceMesh, op_schema: OpSchema
+) -> OpStrategy:
+    self_strategy, mat2_strategy = op_schema.args_schema
+    assert isinstance(self_strategy, OpStrategy)
+    assert isinstance(mat2_strategy, OpStrategy)
+    # generate all possible strategies for mm
+    mm_strategy = gen_einsum_strategies(mm_equation, mesh)
+    # filter out invalid strategies and associate costs
+    strategies = mm_strategy.strategies
+    filtered_strategies = []
+    for strtg in strategies:
+        assert strtg.input_specs is not None
+        self_spec = strtg.input_specs[0]
+        mat2_spec = strtg.input_specs[1]
+        if is_tensor_shardable(self_strategy.shape, self_spec) and is_tensor_shardable(
+            mat2_strategy.shape, mat2_spec
+        ):
+            redistribute_cost = [
+                generate_redistribute_costs(self_strategy, self_spec),
+                generate_redistribute_costs(mat2_strategy, mat2_spec),
+            ]
+            strtg.redistribute_cost = redistribute_cost
+            filtered_strategies.append(strtg)
+
+    mm_strategy.strategies = filtered_strategies
+
+    return mm_strategy
+
+
+def _addmm_like_strategy(
+    mm_equation: str, mesh: DeviceMesh, op_schema: OpSchema
+) -> OpStrategy:
+    self_strategy, mat1_strategy, mat2_strategy = op_schema.args_schema
+    assert isinstance(self_strategy, OpStrategy)
+    assert isinstance(mat1_strategy, OpStrategy)
+    assert isinstance(mat2_strategy, OpStrategy)
+    self_shape = self_strategy.shape
+    mm_out_shape = torch.Size(
+        [
+            mat2_strategy.shape[-1] if i == len(mat1_strategy.shape) - 1 else dim_size
+            for i, dim_size in enumerate(mat1_strategy.shape)
+        ]
+    )
+    # generate all possible strategies for mm
+    mm_strategy = gen_einsum_strategies(mm_equation, mesh)
+    # filter out invalid strategies and associate costs
+    strategies = mm_strategy.strategies
+    filtered_strategies = []
+    for strtg in strategies:
+        # construct new strategy by consider the self arg
+        assert strtg.input_specs is not None
+        mat1_spec = strtg.input_specs[0]
+        mat2_spec = strtg.input_specs[1]
+        out_spec = strtg.output_spec
+
+        # self arg's spec should follow the output of mm, but need
+        # to consider broadcast for the self arg
+        broadcast_dims_map = infer_broadcast_dims_map(mm_out_shape, self_shape)
+        self_placements = map_placements_after_broadcast(
+            out_spec.placements, mm_out_shape, broadcast_dims_map
+        )
+        self_spec = DTensorSpec(mesh=mesh, placements=self_placements)
+
+        if is_tensor_shardable(mat1_strategy.shape, mat1_spec) and is_tensor_shardable(
+            mat2_strategy.shape, mat2_spec
+        ):
+            # update input specs with new self spec
+            strtg.input_specs = (self_spec, mat1_spec, mat2_spec)
+
+            # associate costs
+            redistribute_cost = [
+                generate_redistribute_costs(self_strategy, self_spec),
+                generate_redistribute_costs(mat1_strategy, mat1_spec),
+                generate_redistribute_costs(mat2_strategy, mat2_spec),
+            ]
+            strtg.redistribute_cost = redistribute_cost
+            filtered_strategies.append(strtg)
+
+    mm_strategy.strategies = filtered_strategies
+
+    return mm_strategy
+
+
+@register_op_strategy(aten.mm.default)
+def mm_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
+    return _mm_like_strategy("mk,kn->mn", mesh, op_schema)
+
+
+@register_op_strategy(aten.addmm.default)
+def addmm_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
+    return _addmm_like_strategy("mk,kn->mn", mesh, op_schema)
+
+
+@register_op_strategy(aten.bmm.default)
+def bmm_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
+    return _mm_like_strategy("bmk,bkn->bmn", mesh, op_schema)
+
+
+@register_op_strategy(aten.baddbmm.default)
+def baddmm_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
+    return _addmm_like_strategy("bmk,bkn->bmn", mesh, op_schema)
+
+
+@register_op_strategy(
+    aten._scaled_dot_product_flash_attention.default, schema_info=RuntimeSchemaInfo(5)
+)
+def scaled_dot_product_flash_attention_strategy(
+    mesh: DeviceMesh, op_schema: OpSchema
+) -> OpStrategy:
+    # NOTE: currently we only support some simple strategies to support tensor parallelism
+    # TODO: sdpa might be a good candidate for us to explore decomposed sharding propagation
+    # as it involves: matmul, pointwise, reduction ops together.
+    return_debug_mask = len(op_schema.args_schema) >= 6 and op_schema.args_schema[5]
+    q_input_strategy = op_schema.args_schema[0]
+    assert isinstance(q_input_strategy, OpStrategy)
+    # assuming q/k/v have the same shape
+    qkv_shape = q_input_strategy.shape
+
+    single_mesh_dim_strategies = []
+
+    # placement list stores placements of [outputs, inputs]
+    # in the spda case, we have 3 valid tensor outputs and 3 tensor inputs
+    # first we can always accept full replication for both inputs and outputs
+    all_replicate: PlacementList = [
+        Replicate(),
+        Replicate(),
+        None,  # cum_seq_q
+        None,  # cum_seq_k
+        None,  # max_q
+        None,  # max_k
+        None,  # philox_seed
+        None,  # philox_offset
+        Replicate(),
+        Replicate(),
+        Replicate(),
+        Replicate(),
+    ]
+    single_mesh_dim_strategies.append(all_replicate)
+
+    # second we can accept the sharding pattern of tensor parallelism, which
+    # shard on the num of head dim
+    qkv_sharding = Shard(1)  # num head dim
+    output_sharding = Shard(1)  # num head dim
+    logsumexp_sharding = Shard(1)  # num head dim
+    if return_debug_mask:
+        debug_attn_mask_sharding: Placement = Shard(1)  # num head dim
+    else:
+        # empty debug mask, replicated
+        debug_attn_mask_sharding = Replicate()
+
+    num_heads_dim_sharding: PlacementList = [
+        output_sharding,
+        logsumexp_sharding,
+        None,  # cum_seq_q
+        None,  # cum_seq_k
+        None,  # max_q
+        None,  # max_k
+        None,  # philox_seed
+        None,  # philox_offset
+        debug_attn_mask_sharding,
+        qkv_sharding,
+        qkv_sharding,
+        qkv_sharding,
+    ]
+    single_mesh_dim_strategies.append(num_heads_dim_sharding)
+
+    # Context Parallelism: shards on the sequence dim
+    single_mesh_dim_strategies.append(
+        [
+            Shard(2),  # output
+            Shard(2),  # logsumexp
+            None,  # cum_seq_q
+            None,  # cum_seq_k
+            None,  # max_q
+            None,  # max_k
+            None,  # philox_seed
+            None,  # philox_offset
+            Shard(2),  # debugattn
+            Shard(2),  # q
+            Shard(2),  # k
+            Shard(2),  # v
+        ]
+    )
+    return expand_to_full_mesh_op_strategy(
+        mesh, op_schema, single_mesh_dim_strategies, input_index=9
+    )
+
+
+@register_op_strategy(aten._scaled_dot_product_flash_attention_backward.default)
+def scaled_dot_product_flash_attention_backward_strategy(
+    mesh: DeviceMesh, op_schema: OpSchema
+) -> OpStrategy:
+    q_input_strategy = op_schema.args_schema[1]
+    assert isinstance(q_input_strategy, OpStrategy)
+    # assuming q/k/v have the same shape
+    qkv_shape = q_input_strategy.shape
+
+    tensor_input_indices = [
+        i
+        for i, arg_spec in enumerate(op_schema.args_schema)
+        if isinstance(arg_spec, OpStrategy)
+    ]
+    num_tensor_inputs = len(tensor_input_indices)
+
+    single_mesh_dim_strategies = []
+
+    # placement list stores placements of [outputs, inputs]
+    # in the spda backward case, we have 3 tensor outputs and 6 to 10 tensor inputs
+    # first we can always accept full replication for both inputs and outputs
+    all_replicate: PlacementList = [Replicate()] * (3 + num_tensor_inputs)
+
+    single_mesh_dim_strategies.append(all_replicate)
+
+    # second we can accept the sharding pattern of tensor parallelism, which
+    # shard on the num of head dim
+    grad_output_sharding = Shard(1)  # num head dim
+    qkv_sharding = Shard(1)  # num head dim
+    output_sharding = Shard(1)  # num head dim
+    logsumexp_sharding = Shard(1)  # num head dim
+    grad_qkv_sharding = Shard(1)  # num head dim
+
+    num_heads_dim_sharding: PlacementList = [
+        grad_qkv_sharding,
+        grad_qkv_sharding,
+        grad_qkv_sharding,
+        grad_output_sharding,
+        qkv_sharding,
+        qkv_sharding,
+        qkv_sharding,
+        output_sharding,
+        logsumexp_sharding,
+    ]
+    # accept replicate on the rest tensor inputs, potentially
+    # cum_seq_q, cum_seq_k, philox_seed, philox_offset
+    # at indices 6, 7, 12, 13, respectively
+    num_heads_dim_sharding.extend([Replicate()] * (num_tensor_inputs - 6))
+    single_mesh_dim_strategies.append(num_heads_dim_sharding)
+
+    # Context Parallelism: shards on the sequence dim
+    seq_dim_sharding: PlacementList = [
+        Shard(2),  # grad_q
+        Shard(2),  # grad_k
+        Shard(2),  # grad_v
+        Shard(2),  # grad_output
+        Shard(2),  # q
+        Shard(2),  # k
+        Shard(2),  # v
+        Shard(2),  # output
+        Shard(2),  # logsumexp
+    ]
+    # accept replicate on the rest tensor inputs, potentially
+    # cum_seq_q, cum_seq_k, philox_seed, philox_offset
+    # at indices 6, 7, 12, 13, respectively
+    seq_dim_sharding.extend([Replicate()] * (num_tensor_inputs - 6))
+    single_mesh_dim_strategies.append(seq_dim_sharding)
+
+    return expand_to_full_mesh_op_strategy(
+        mesh, op_schema, single_mesh_dim_strategies, input_index=3
+    )
+
+
+@register_op_strategy(aten.constant_pad_nd.default)
+def constant_pad_nd_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
+    # TODO(d4l3k); implement a more correct strategy for constant_pad_nd
+    return OpStrategy(
+        [
+            PlacementStrategy(
+                output_specs=DTensorSpec(mesh, (Replicate(),)),
+                input_specs=(
+                    DTensorSpec(mesh, (Replicate(),)),
+                    DTensorSpec(mesh, (Replicate(),)),
+                ),
+                redistribute_cost=[[1]],
+            )
+        ]
+    )
+
+
+@register_op_strategy(
+    aten._scaled_dot_product_efficient_attention.default,
+    schema_info=RuntimeSchemaInfo(4),
+)
+def scaled_dot_product_efficient_attention_strategy(
+    mesh: DeviceMesh, op_schema: OpSchema
+) -> OpStrategy:
+    # NOTE: currently we only support some simple strategies to support tensor parallelism
+    q_input_strategy = op_schema.args_schema[0]
+    assert isinstance(q_input_strategy, OpStrategy)
+    # assuming q/k/v have the same shape
+    qkv_shape = q_input_strategy.shape
+    has_attn_bias = op_schema.args_schema[3] is not None
+    compute_log_sumexp = op_schema.args_schema[4]
+
+    single_mesh_dim_strategies: List[PlacementList] = []
+
+    # placement list stores placements of [outputs, inputs]
+    # in the spda case, we have 2 valid tensor outputs and 3 or 4 tensor inputs
+    # first we can always accept full replication for both inputs and outputs
+    all_replicate: PlacementList = [
+        Replicate(),
+        Replicate(),
+        None,
+        None,
+        Replicate(),
+        Replicate(),
+        Replicate(),
+    ]
+    if has_attn_bias:
+        all_replicate.append(Replicate())  # attn bias
+
+    # Context Parallelism: shards on the sequence dim
+    single_mesh_dim_strategies.append(
+        [
+            Shard(2),  # output
+            Shard(2),  # logsumexp
+            None,  # philox_seed
+            None,  # philox_offset
+            Shard(2),  # q
+            Shard(2),  # k
+            Shard(2),  # v
+        ]
+    )
+
+    single_mesh_dim_strategies.append(all_replicate)
+
+    # second we can accept the sharding pattern of tensor parallelism, which
+    # shard on the heads dimension
+    qkv_sharding = Shard(1)
+    output_sharding = Shard(1)
+    if compute_log_sumexp:
+        logsumexp_sharding: Placement = Shard(1)
+    else:
+        # empty logsumexp, replicated
+        logsumexp_sharding = Replicate()
+
+    num_heads_dim_sharding = [
+        output_sharding,
+        logsumexp_sharding,
+        None,
+        None,
+        qkv_sharding,
+        qkv_sharding,
+        qkv_sharding,
+    ]
+    if has_attn_bias:
+        num_heads_dim_sharding.append(Shard(1))
+    single_mesh_dim_strategies.append(num_heads_dim_sharding)
+
+    return expand_to_full_mesh_op_strategy(
+        mesh,
+        op_schema,
+        single_mesh_dim_strategies,
+        input_index=4,
+    )
+
+
+@register_op_strategy(aten._scaled_dot_product_efficient_attention_backward.default)
+def scaled_dot_product_efficient_attention_backward_strategy(
+    mesh: DeviceMesh, op_schema: OpSchema
+) -> OpStrategy:
+    q_input_strategy = op_schema.args_schema[1]
+    assert isinstance(q_input_strategy, OpStrategy)
+    # assuming q/k/v have the same shape
+    qkv_shape = q_input_strategy.shape
+    has_attn_bias = op_schema.args_schema[4] is not None
+
+    tensor_input_indices = [
+        i
+        for i, arg_spec in enumerate(op_schema.args_schema)
+        if isinstance(arg_spec, OpStrategy)
+    ]
+
+    single_mesh_dim_strategies = []
+
+    # placement list stores placements of [outputs, inputs]
+    # in the spda backward case, we have 4 tensor outputs and 8 or 9 tensor inputs
+    # NOTE: Output sharding of grad_bias on heads dim if attn_bias is present;
+    #       otherwise grad_bias will be empty and its DTensorSpec will be removed.
+    # first we can always accept full replication for both inputs and outputs
+    all_replicate: PlacementList = [Replicate()] * (12 + has_attn_bias)
+
+    if not has_attn_bias:
+        all_replicate[3] = None  # grad bias is None if attn_bias is not present
+
+    single_mesh_dim_strategies.append(all_replicate)
+
+    # second we can accept the sharding pattern of tensor parallelism, which
+    # shard on the heads dimension
+    grad_output_sharding = Shard(1)
+    qkv_sharding = Shard(1)
+    output_sharding = Shard(1)
+    logsumexp_sharding = Shard(1)
+    grad_qkv_sharding = Shard(1)
+    grad_bias_sharding = Shard(1) if has_attn_bias else None
+
+    num_heads_dim_sharding: PlacementList = [
+        grad_qkv_sharding,
+        grad_qkv_sharding,
+        grad_qkv_sharding,
+        grad_bias_sharding,
+        grad_output_sharding,
+        qkv_sharding,
+        qkv_sharding,
+        qkv_sharding,
+        # the place for optional input attn_bias,
+        output_sharding,
+        logsumexp_sharding,
+    ]
+    # input sharding of attn_bias on heads dim if present
+    if has_attn_bias:
+        num_heads_dim_sharding.insert(8, Shard(1))
+    # accept replicate on the rest scalar tensor inputs
+    # namely philox_seed and philox_offset
+    num_heads_dim_sharding.extend([Replicate(), Replicate()])
+    single_mesh_dim_strategies.append(num_heads_dim_sharding)
+
+    # Context Parallelism: shards on the sequence dim
+    seq_dim_sharding: PlacementList = [
+        Shard(2),  # grad_q
+        Shard(2),  # grad_k
+        Shard(2),  # grad_v
+        Shard(1) if has_attn_bias else None,  # grad_bias
+        Shard(2),  # grad_output
+        Shard(2),  # q
+        Shard(2),  # k
+        Shard(2),  # v
+        Shard(2),  # output
+        Shard(2),  # logsumexp
+    ]
+    # accept replicate on the rest tensor inputs, potentially
+    # cum_seq_q, cum_seq_k, philox_seed, philox_offset
+    # at indices 6, 7, 12, 13, respectively
+    if has_attn_bias:
+        num_heads_dim_sharding.insert(8, Shard(1))
+    seq_dim_sharding.extend([Replicate(), Replicate()])
+    single_mesh_dim_strategies.append(seq_dim_sharding)
+
+    return expand_to_full_mesh_op_strategy(
+        mesh,
+        op_schema,
+        single_mesh_dim_strategies,
+        input_index=4,
+    )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_pointwise_ops.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_pointwise_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb40865ed9c06ab569060199086ce2cfdda23e51
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_pointwise_ops.py
@@ -0,0 +1,688 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates
+from typing import List, Sequence, Tuple
+
+import torch
+from torch.distributed.device_mesh import DeviceMesh
+from torch.distributed.tensor._dtensor_spec import DTensorSpec
+from torch.distributed.tensor._op_schema import (
+    _is_inplace_op,
+    _is_out_variant_op,
+    OpSchema,
+    OpStrategy,
+    PlacementStrategy,
+    RuntimeSchemaInfo,
+    StrategyType,
+    TupleStrategy,
+)
+from torch.distributed.tensor._ops.utils import (
+    generate_redistribute_costs,
+    infer_broadcast_dims_map,
+    map_placements_after_broadcast,
+    normalize_dim,
+    register_op_strategy,
+)
+from torch.distributed.tensor.placement_types import (
+    Partial,
+    Placement,
+    Replicate,
+    Shard,
+)
+
+
+aten = torch.ops.aten
+# leave the remaining pointwise_ops list here for convenience,
+# Below ops are some pointwise ops that are yet to be supported,
+# they might not be a complete list.
+# pointwise_ops = [
+#     "fake_quantize_per_channel_affine",
+#     "fake_quantize_per_tensor_affine",
+#     "floor_divide",  # floor_divide is deprecated
+#     "frexp",  # multiple output pointwise op, need to add support
+#     "gradient",  #  need investigation on this op
+#     "imag",  # complex data type only
+#     "quantized_batch_norm",
+#     "quantized_max_pool1d",
+#     "quantized_max_pool2d",
+#     "real",  # complex data type only
+# ]
+
+
+linear_pointwise_ops = [
+    aten.div.Scalar,  # this op is linear on the first argument, and the second argument is scalar, so it fits as a linear op.
+    aten.div_.Scalar,  # this op is linear on the first argument, and the second argument is scalar, so it fits as a linear op.
+    aten.to.dtype,
+    aten.add.Tensor,
+    aten.add_.Tensor,
+]
+
+
+pointwise_ops = [
+    # please keep the entries below alphabetically sorted
+    aten.__ilshift__.Scalar,
+    aten.__ilshift__.Tensor,
+    aten.__irshift__.Scalar,
+    aten.__irshift__.Tensor,
+    aten.__lshift__.Scalar,
+    aten.__lshift__.Tensor,
+    aten.__rshift__.Scalar,
+    aten.__rshift__.Tensor,
+    aten._conj.default,
+    aten.abs.default,
+    aten.abs.out,
+    aten.abs_.default,
+    aten.acos.default,
+    aten.acos.out,
+    aten.acos_.default,
+    aten.acosh.default,
+    aten.acosh.out,
+    aten.acosh_.default,
+    aten.add.Scalar,
+    aten.add.out,
+    aten.add_.Scalar,
+    aten.addcdiv.default,
+    aten.addcdiv.out,
+    aten.addcdiv_.default,
+    aten.addcmul.default,
+    aten.addcmul.out,
+    aten.addcmul_.default,
+    aten.angle.default,
+    aten.angle.out,
+    aten.asin.default,
+    aten.asin.out,
+    aten.asin_.default,
+    aten.asinh.default,
+    aten.asinh.out,
+    aten.asinh_.default,
+    aten.atan.default,
+    aten.atan.out,
+    aten.atan2.default,
+    aten.atan2.out,
+    aten.atan2_.default,
+    aten.atan_.default,
+    aten.atanh.default,
+    aten.atanh.out,
+    aten.atanh_.default,
+    aten.bitwise_and.Scalar,
+    aten.bitwise_and.Scalar_Tensor,
+    aten.bitwise_and.Scalar_out,
+    aten.bitwise_and.Tensor,
+    aten.bitwise_and.Tensor_out,
+    aten.bitwise_and_.Scalar,
+    aten.bitwise_and_.Tensor,
+    aten.bitwise_left_shift.Scalar_Tensor,
+    aten.bitwise_left_shift.Tensor,
+    aten.bitwise_left_shift.Tensor_Scalar,
+    aten.bitwise_left_shift.Tensor_Scalar_out,
+    aten.bitwise_left_shift.Tensor_out,
+    aten.bitwise_left_shift_.Tensor,
+    aten.bitwise_left_shift_.Tensor_Scalar,
+    aten.bitwise_not.default,
+    aten.bitwise_not.out,
+    aten.bitwise_not_.default,
+    aten.bitwise_or.Scalar,
+    aten.bitwise_or.Scalar_Tensor,
+    aten.bitwise_or.Scalar_out,
+    aten.bitwise_or.Tensor,
+    aten.bitwise_or.Tensor_out,
+    aten.bitwise_or_.Scalar,
+    aten.bitwise_or_.Tensor,
+    aten.bitwise_right_shift.Scalar_Tensor,
+    aten.bitwise_right_shift.Tensor,
+    aten.bitwise_right_shift.Tensor_Scalar,
+    aten.bitwise_right_shift.Tensor_Scalar_out,
+    aten.bitwise_right_shift.Tensor_out,
+    aten.bitwise_right_shift_.Tensor,
+    aten.bitwise_right_shift_.Tensor_Scalar,
+    aten.bitwise_xor.Scalar,
+    aten.bitwise_xor.Scalar_Tensor,
+    aten.bitwise_xor.Scalar_out,
+    aten.bitwise_xor.Tensor,
+    aten.bitwise_xor.Tensor_out,
+    aten.bitwise_xor_.Scalar,
+    aten.bitwise_xor_.Tensor,
+    aten.ceil.default,
+    aten.ceil.out,
+    aten.ceil_.default,
+    aten.clamp.default,
+    aten.clamp.out,
+    aten.clamp_.default,
+    aten.clip.default,
+    aten.clip.out,
+    aten.clip_.default,
+    aten.conj_physical.default,
+    aten.conj_physical.out,
+    aten.conj_physical_.default,
+    aten.copysign.Scalar,
+    aten.copysign.Scalar_out,
+    aten.copysign.Tensor,
+    aten.copysign.out,
+    aten.copysign_.Scalar,
+    aten.copysign_.Tensor,
+    aten.cos.default,
+    aten.cos.out,
+    aten.cos_.default,
+    aten.cosh.default,
+    aten.cosh.out,
+    aten.cosh_.default,
+    aten.deg2rad.default,
+    aten.deg2rad.out,
+    aten.deg2rad_.default,
+    aten.digamma.default,
+    aten.digamma.out,
+    aten.digamma_.default,
+    aten.div.Tensor,
+    aten.div.Tensor_mode,
+    aten.div.out,
+    aten.div.out_mode,
+    aten.div_.Tensor,
+    aten.div_.Tensor_mode,
+    aten.eq.Tensor,
+    aten.eq.Tensor_out,
+    aten.eq.Scalar,
+    aten.eq.Scalar_out,
+    aten.erf.default,
+    aten.erf.out,
+    aten.erf_.default,
+    aten.erfc.default,
+    aten.erfc.out,
+    aten.erfc_.default,
+    aten.erfinv.default,
+    aten.erfinv.out,
+    aten.erfinv_.default,
+    aten.exp.default,
+    aten.exp.out,
+    aten.exp2.default,
+    aten.exp2.out,
+    aten.exp2_.default,
+    aten.exp_.default,
+    aten.expm1.default,
+    aten.expm1.out,
+    aten.expm1_.default,
+    aten.float_power.Scalar,
+    aten.float_power.Scalar_out,
+    aten.float_power.Tensor_Scalar,
+    aten.float_power.Tensor_Scalar_out,
+    aten.float_power.Tensor_Tensor,
+    aten.float_power.Tensor_Tensor_out,
+    aten.float_power_.Scalar,
+    aten.float_power_.Tensor,
+    aten.floor.default,
+    aten.floor.out,
+    aten.floor_.default,
+    aten.fmod.Scalar,
+    aten.fmod.Scalar_out,
+    aten.fmod.Tensor,
+    aten.fmod.Tensor_out,
+    aten.fmod_.Scalar,
+    aten.fmod_.Tensor,
+    aten.frac.default,
+    aten.frac.out,
+    aten.frac_.default,
+    aten.ge.Scalar,
+    aten.ge.Tensor,
+    aten.gelu.default,
+    aten.gt.Tensor,
+    aten.gt.Tensor_out,
+    aten.gt.Scalar,
+    aten.gt.Scalar_out,
+    aten.gt.Scalar,
+    aten.gt.Tensor,
+    aten.hypot.default,
+    aten.hypot.out,
+    aten.hypot_.default,
+    aten.i0.default,
+    aten.i0.out,
+    aten.i0_.default,
+    aten.igamma.default,
+    aten.igamma.out,
+    aten.igamma_.default,
+    aten.igammac.default,
+    aten.igammac.out,
+    aten.igammac_.default,
+    aten.isinf.default,
+    aten.isnan.default,
+    aten.isneginf.default,
+    aten.isneginf.out,
+    aten.isposinf.default,
+    aten.isposinf.out,
+    aten.ldexp.default,
+    aten.ldexp.out,
+    aten.ldexp_.default,
+    aten.lt.Tensor,
+    aten.lt.Tensor_out,
+    aten.lt.Scalar,
+    aten.lt.Scalar_out,
+    aten.le.Scalar,
+    aten.le.Tensor,
+    aten.lerp.Scalar,
+    aten.lerp.Scalar_out,
+    aten.lerp.Tensor,
+    aten.lerp.Tensor_out,
+    aten.lerp_.Scalar,
+    aten.lerp_.Tensor,
+    aten.lgamma.default,
+    aten.lgamma.out,
+    aten.lgamma_.default,
+    aten.log.default,
+    aten.log.out,
+    aten.log10.default,
+    aten.log10.out,
+    aten.log10_.default,
+    aten.log1p.default,
+    aten.log1p.out,
+    aten.log1p_.default,
+    aten.log2.default,
+    aten.log2.out,
+    aten.log2_.default,
+    aten.log_.default,
+    aten.logaddexp.default,
+    aten.logaddexp.out,
+    aten.logaddexp2.default,
+    aten.logaddexp2.out,
+    aten.logical_and.default,
+    aten.logical_and.out,
+    aten.logical_and_.default,
+    aten.logical_not.default,
+    aten.logical_not.out,
+    aten.logical_not_.default,
+    aten.logical_or.default,
+    aten.logical_or.out,
+    aten.logical_or_.default,
+    aten.logical_xor.default,
+    aten.logical_xor.out,
+    aten.logical_xor_.default,
+    aten.logit.default,
+    aten.logit.out,
+    aten.logit_.default,
+    aten.masked_fill.Scalar,
+    aten.maximum.out,
+    aten.mul.Scalar,
+    aten.mul.Tensor,
+    aten.mul.out,
+    aten.mul_.Scalar,
+    aten.mul_.Tensor,
+    aten.mvlgamma.default,
+    aten.mvlgamma.out,
+    aten.mvlgamma_.default,
+    aten.native_dropout_backward.default,
+    aten.native_dropout_backward.out,
+    aten.nan_to_num.default,
+    aten.nan_to_num.out,
+    aten.nan_to_num_.default,
+    aten.ne.Scalar,
+    aten.neg.default,
+    aten.neg.out,
+    aten.neg_.default,
+    aten.nextafter.default,
+    aten.nextafter.out,
+    aten.nextafter_.default,
+    aten.polygamma.default,
+    aten.polygamma.out,
+    aten.polygamma_.default,
+    aten.positive.default,
+    aten.pow.Scalar,
+    aten.pow.Scalar_out,
+    aten.pow.Tensor_Scalar,
+    aten.pow.Tensor_Scalar_out,
+    aten.pow.Tensor_Tensor,
+    aten.pow.Tensor_Tensor_out,
+    aten.pow_.Scalar,
+    aten.pow_.Tensor,
+    aten.reciprocal.default,
+    aten.reciprocal.out,
+    aten.reciprocal_.default,
+    aten.rad2deg.default,
+    aten.rad2deg.out,
+    aten.rad2deg_.default,
+    aten.relu.default,
+    aten.relu_.default,
+    aten.remainder.Scalar,
+    aten.remainder.Scalar_Tensor,
+    aten.remainder.Scalar_out,
+    aten.remainder.Tensor,
+    aten.remainder.Tensor_out,
+    aten.remainder_.Scalar,
+    aten.remainder_.Tensor,
+    aten.round.decimals,
+    aten.round.decimals_out,
+    aten.round.default,
+    aten.round.out,
+    aten.round_.decimals,
+    aten.round_.default,
+    aten.rsqrt.default,
+    aten.rsqrt.out,
+    aten.rsqrt_.default,
+    aten.rsub.Scalar,
+    aten.sgn.default,
+    aten.sgn.out,
+    aten.sgn_.default,
+    aten.sigmoid.default,
+    aten.sigmoid.out,
+    aten.sigmoid_.default,
+    aten.sign.default,
+    aten.sign.out,
+    aten.sign_.default,
+    aten.signbit.default,
+    aten.signbit.out,
+    aten.silu.default,
+    aten.silu.out,
+    aten.sin.default,
+    aten.sin.out,
+    aten.sin_.default,
+    aten.sinc.default,
+    aten.sinc.out,
+    aten.sinc_.default,
+    aten.sinh.default,
+    aten.sinh.out,
+    aten.sinh_.default,
+    aten.sqrt.default,
+    aten.sqrt.out,
+    aten.sqrt_.default,
+    aten.square.default,
+    aten.square.out,
+    aten.square_.default,
+    aten.sub.Scalar,
+    aten.sub.Tensor,
+    aten.sub.out,
+    aten.sub_.Scalar,
+    aten.sub_.Tensor,
+    aten.tan.default,
+    aten.tan.out,
+    aten.tan_.default,
+    aten.tanh.default,
+    aten.tanh.out,
+    aten.tanh_.default,
+    aten.true_divide.Tensor,
+    aten.trunc.default,
+    aten.trunc.out,
+    aten.trunc_.default,
+    aten.where.self,
+    aten.where.self_out,
+    aten.xlogy.OutScalar_Self,
+    aten.xlogy.OutScalar_Other,
+    aten.xlogy.OutTensor,
+    aten.xlogy.Scalar_Other,
+    aten.xlogy.Scalar_Self,
+    aten.xlogy.Tensor,
+    aten.xlogy_.Scalar_Other,
+    aten.xlogy_.Tensor,
+    # backward point-wise ops
+    # please keep the entries below alphabetically sorted
+    aten.gelu_backward.default,
+    aten.sigmoid_backward.default,
+    aten.silu_backward.default,
+    aten.tanh_backward.default,
+    aten.threshold_backward.default,
+]
+
+
+def pointwise_strategy(
+    mesh: DeviceMesh, op_schema: OpSchema, linearity: bool = False
+) -> OpStrategy:
+    max_shards_strategy_index = -1
+    max_shards = -1
+
+    if _is_inplace_op(op_schema.op):
+        # inplace op should follow the first arg strategy
+        followed_strategy = op_schema.args_schema[0]
+    elif _is_out_variant_op(op_schema.op):
+        # out variant op should follow the out kwarg strategy
+        followed_strategy = op_schema.kwargs_schema["out"]
+    else:
+        # normal pointwise op, we choose to follow the arg with
+        # the max shards in case operands needs reshard
+        for idx, arg_strategy in enumerate(op_schema.args_schema):
+            if not isinstance(arg_strategy, OpStrategy):
+                continue
+
+            arg_max_shards = arg_strategy.max_num_shards()
+            if arg_max_shards > max_shards:
+                max_shards_strategy_index = idx
+                max_shards = arg_max_shards
+
+        followed_strategy = op_schema.args_schema[max_shards_strategy_index]
+
+    assert isinstance(
+        followed_strategy, OpStrategy
+    ), f"no strategy to follow for {op_schema}!"
+    return common_pointwise_strategy(
+        mesh, op_schema.args_schema, followed_strategy, linearity
+    )
+
+
+def common_pointwise_strategy(
+    mesh: DeviceMesh,
+    args_schema: Sequence[object],
+    followed_strategy: OpStrategy,
+    linearity: bool,
+) -> OpStrategy:
+    # handle broadcasting
+    common_shape = torch.broadcast_shapes(
+        *[arg.shape for arg in args_schema if isinstance(arg, OpStrategy)]
+    )
+    pointwise_strategy = OpStrategy([])
+
+    for placement_strategy in followed_strategy.strategies:
+        spec_to_follow = placement_strategy.output_spec
+        out_placements: List[Placement] = []
+        for placement in spec_to_follow.placements:
+            if isinstance(placement, Shard):
+                shard_dim = normalize_dim(placement.dim, len(spec_to_follow.shape))
+                common_ndim = len(common_shape)
+                new_shard_dim = common_ndim - len(spec_to_follow.shape) + shard_dim
+                out_placements.append(Shard(new_shard_dim))
+            elif isinstance(placement, Partial) and not linearity:
+                # clear the partial placemnet if op does not support linearity
+                # by default we just replicate the partial, need to see if this
+                # is optimal for all cases
+                out_placements.append(Replicate())
+            else:
+                out_placements.append(placement)
+
+        input_specs: List[DTensorSpec] = []
+        redistribute_costs: List[List[float]] = []
+        for input_arg in args_schema:
+            if isinstance(input_arg, OpStrategy):
+                # every arg follow the out_placements, but need to handle broadcasting
+                input_arg_spec = input_arg.strategies[0].output_spec
+                input_arg_dims_map = infer_broadcast_dims_map(
+                    common_shape, input_arg_spec.shape
+                )
+                input_target_placements = map_placements_after_broadcast(
+                    tuple(out_placements),
+                    common_shape,
+                    input_arg_dims_map,
+                )
+                input_arg_target_spec = DTensorSpec(
+                    mesh=mesh,
+                    placements=input_target_placements,
+                    tensor_meta=input_arg_spec.tensor_meta,
+                )
+                input_specs.append(input_arg_target_spec)
+                redistribute_costs.append(
+                    generate_redistribute_costs(input_arg, input_arg_target_spec)
+                )
+
+        pointwise_strategy.strategies.append(
+            PlacementStrategy(
+                output_specs=DTensorSpec(
+                    mesh=mesh,
+                    placements=tuple(out_placements),
+                ),
+                input_specs=input_specs,
+                redistribute_cost=redistribute_costs,
+            )
+        )
+    return pointwise_strategy
+
+
+def linear_pointwise_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> StrategyType:
+    """
+    Linear pointwise operators can propagate pending reductions.
+    For example, c = add(a, b); if a is pending sum, then c will be
+    pending sum as well without any communication overhead.
+    """
+    return pointwise_strategy(mesh, op_schema, linearity=True)
+
+
+for op in linear_pointwise_ops:
+    register_op_strategy(op, schema_info=RuntimeSchemaInfo(static_kwargkey=["out"]))(
+        linear_pointwise_strategy
+    )
+
+for op in pointwise_ops:
+    register_op_strategy(op, schema_info=RuntimeSchemaInfo(static_kwargkey=["out"]))(
+        pointwise_strategy
+    )
+
+
+# TODO: add all for_each ops
+for_each_ops = [
+    aten._foreach_abs.default,
+    aten._foreach_abs_.default,
+    aten._foreach_addcdiv_.Scalar,
+    aten._foreach_addcdiv_.ScalarList,
+    aten._foreach_addcdiv_.Tensor,
+    aten._foreach_addcmul.Scalar,
+    aten._foreach_addcmul_.Scalar,
+    aten._foreach_addcmul_.ScalarList,
+    aten._foreach_addcmul_.Tensor,
+    aten._foreach_clamp_max_.Scalar,
+    aten._foreach_clamp_min_.Scalar,
+    aten._foreach_div_.List,
+    aten._foreach_div_.Scalar,
+    aten._foreach_div_.ScalarList,
+    aten._foreach_div_.Tensor,
+    aten._foreach_div.List,
+    aten._foreach_div.Scalar,
+    aten._foreach_div.ScalarList,
+    aten._foreach_div.Tensor,
+    aten._foreach_lerp_.Scalar,
+    aten._foreach_maximum_.List,
+    aten._foreach_mul.Scalar,
+    aten._foreach_mul.ScalarList,
+    aten._foreach_mul.Tensor,
+    aten._foreach_mul.List,
+    aten._foreach_mul_.Scalar,
+    aten._foreach_mul_.ScalarList,
+    aten._foreach_mul_.Tensor,
+    aten._foreach_mul_.List,
+    aten._foreach_neg.default,
+    aten._foreach_neg_.default,
+    aten._foreach_reciprocal_.default,
+    aten._foreach_sub.Scalar,
+    aten._foreach_sub_.Scalar,
+    aten._foreach_sub.List,
+    aten._foreach_sub_.List,
+    aten._foreach_sub.ScalarList,
+    aten._foreach_sub_.ScalarList,
+    aten._foreach_sqrt.default,
+    aten._foreach_sqrt_.default,
+    aten._foreach_zero_.default,
+    aten._foreach_exp.default,
+    aten._foreach_exp_.default,
+    aten._foreach_cos.default,
+    aten._foreach_cos_.default,
+    aten._foreach_log.default,
+    aten._foreach_log_.default,
+    aten._amp_foreach_non_finite_check_and_unscale_.default,
+]
+
+for_each_linearity_ops = [
+    aten._foreach_add.Scalar,
+    aten._foreach_add_.Scalar,
+    aten._foreach_add_.ScalarList,
+    aten._foreach_add.List,
+    aten._foreach_add_.List,
+]
+
+
+def list_pointwise_strategy(
+    mesh: DeviceMesh, op_schema: OpSchema, linearity: bool = False
+) -> StrategyType:
+    """
+    Apply the pointwise strategy to the zipped arguments. For example, if we
+    run a foreach add of two lists l1 and l2, then we apply the pointwise
+    strategy on each pair (l1[i], l2[i]). If the first argument is a list but
+    the second (or later) one is a tensor, then we broadcast the tensor by
+    replicating it into a list with the length of the first argument.
+
+    Args:
+        mesh (DeviceMesh): device mesh for pointwise ops
+        op_schema (OpSchema): schema of the operator to generate strategy for
+        linearity (bool): specify whether op(a) + op(b) = op(a + b)
+
+    Returns:
+        OpStrategy: generated strategy
+    """
+
+    def args_tuple_strategies(args_schema: Tuple[object, ...]) -> List[TupleStrategy]:
+        first_arg = args_schema[0]
+        assert isinstance(first_arg, TupleStrategy)
+        strategy_len = len(first_arg.childs)
+        tuple_strategies: List[TupleStrategy] = []
+        for arg_idx, arg in enumerate(args_schema):
+            if isinstance(arg, TupleStrategy):
+                # every tuple strategy should have the same length
+                assert len(arg.childs) == strategy_len
+                tuple_strategies.append(arg)
+            elif isinstance(arg, OpStrategy):
+                if arg_idx > 0:  # implicitly broadcast
+                    tuple_strategies.append(
+                        TupleStrategy([arg for _ in range(strategy_len)])
+                    )
+                else:
+                    raise RuntimeError(
+                        f"list op only supports tuple strategy! {op_schema}"
+                    )
+        return tuple_strategies
+
+    args_strategies = args_tuple_strategies(op_schema.args_schema)
+    follow_strategy: TupleStrategy = args_strategies[0]
+    list_strategy: List[OpStrategy] = []
+    for child_idx, child_strtgy in enumerate(follow_strategy.childs):
+        assert isinstance(child_strtgy, OpStrategy)
+        args_schema: List[StrategyType] = [
+            arg_strategy.childs[child_idx] for arg_strategy in args_strategies
+        ]
+        pointwise_strategy: OpStrategy = common_pointwise_strategy(
+            mesh, args_schema, child_strtgy, linearity
+        )
+        list_strategy.append(pointwise_strategy)
+    return TupleStrategy(list_strategy)
+
+
+def list_linear_pointwise_strategy(
+    mesh: DeviceMesh, op_schema: OpSchema
+) -> StrategyType:
+    """
+    for each list op stratgy that supports linearity
+    """
+    return list_pointwise_strategy(mesh, op_schema, linearity=True)
+
+
+for op in for_each_ops:
+    register_op_strategy(op, schema_info=RuntimeSchemaInfo(needs_pytree=True))(
+        list_pointwise_strategy
+    )
+
+for op in for_each_linearity_ops:
+    register_op_strategy(op, schema_info=RuntimeSchemaInfo(needs_pytree=True))(
+        list_linear_pointwise_strategy
+    )
+
+fused_ops = [
+    aten._fused_adam_.default,
+    aten._fused_adam.default,
+    aten._fused_adam.tensor_lr,
+    aten._fused_adam_.tensor_lr,
+    aten._fused_adamw_.default,
+    aten._fused_adamw.default,
+    aten._fused_adamw.tensor_lr,
+    aten._fused_adamw_.tensor_lr,
+]
+
+for op in fused_ops:
+    register_op_strategy(op, schema_info=RuntimeSchemaInfo(needs_pytree=True))(
+        list_pointwise_strategy
+    )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_random_ops.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_random_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..726b25e1eed023a2b25a53b36b4bb13d1c75a787
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_random_ops.py
@@ -0,0 +1,38 @@
+# mypy: allow-untyped-decorators
+# Copyright (c) Meta Platforms, Inc. and affiliates
+import torch
+from torch.distributed.device_mesh import DeviceMesh
+from torch.distributed.tensor._op_schema import (
+    OpSchema,
+    OpStrategy,
+    PlacementStrategy,
+    StrategyType,
+)
+from torch.distributed.tensor._ops.utils import is_tensor_partial, register_op_strategy
+
+
+aten = torch.ops.aten
+
+
+@register_op_strategy(
+    [
+        aten.normal_.default,
+        aten.uniform_.default,
+        aten.native_dropout.default,
+        aten.bernoulli_.float,
+        aten.bernoulli.default,
+    ]
+)
+def random_op_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> StrategyType:
+    self_strategy = op_schema.args_schema[0]
+    assert isinstance(self_strategy, OpStrategy)
+
+    random_strategy = OpStrategy([])
+    for arg_strategy in self_strategy.strategies:
+        arg_spec = arg_strategy.output_spec
+        if is_tensor_partial(arg_spec):
+            # TODO: figure out how inplace random op should behave when it's partial
+            raise RuntimeError(f"{op_schema.op} with Partial is not supported yet!")
+        random_strategy.strategies.append(PlacementStrategy(output_specs=arg_spec))
+
+    return random_strategy
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_tensor_ops.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_tensor_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9bcb3b0d122402530450b105ba637ab7fc469dc
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_tensor_ops.py
@@ -0,0 +1,792 @@
+# mypy: allow-untyped-decorators
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and affiliates
+from typing import cast, List, Optional, Sequence, Tuple
+
+import torch
+from torch.distributed.device_mesh import DeviceMesh
+from torch.distributed.tensor._dtensor_spec import DTensorSpec
+from torch.distributed.tensor._op_schema import (
+    _is_inplace_op,
+    OpSchema,
+    OpStrategy,
+    OutputSharding,
+    PlacementList,
+    PlacementStrategy,
+    RuntimeSchemaInfo,
+    StrategyType,
+    TupleStrategy,
+)
+from torch.distributed.tensor._ops._common_rules import pointwise_rule
+from torch.distributed.tensor._ops._embedding_ops import _MaskPartial
+from torch.distributed.tensor._ops.utils import (
+    expand_to_full_mesh_op_strategy,
+    is_tensor_dim_sharded,
+    is_tensor_evenly_shardable,
+    is_tensor_partial,
+    normalize_dim,
+    register_op_strategy,
+    register_prop_rule,
+)
+from torch.distributed.tensor.placement_types import (
+    Partial,
+    Placement,
+    Replicate,
+    Shard,
+)
+
+
+aten = torch.ops.aten
+
+
+def default_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> StrategyType:
+    # Default strategy by default just propagate the first input strategy
+    select_strategy = op_schema.args_schema[0]
+    assert isinstance(select_strategy, OpStrategy)
+    default_strategy = []
+    for strategy in select_strategy.strategies:
+        # we create new DTensorSpecs even for default strategy to assure that
+        # the tensor metas are distinct between the arguments and outputs
+        default_strategy.append(
+            PlacementStrategy(
+                output_specs=DTensorSpec(
+                    mesh=strategy.output_spec.mesh,
+                    placements=strategy.output_spec.placements,
+                )
+            )
+        )
+    return OpStrategy(default_strategy)
+
+
+register_op_strategy(
+    [
+        aten.clone.default,
+        aten.contiguous.default,
+        aten.copy_.default,
+        aten.detach.default,
+        aten.fill_.Scalar,
+        aten.zero_.default,
+    ]
+)(default_strategy)
+
+register_op_strategy(
+    aten._to_copy.default, schema_info=RuntimeSchemaInfo(static_kwargkey=["dtype"])
+)(default_strategy)
+
+
+@register_op_strategy(
+    [
+        aten.equal.default,
+        aten.is_same_size.default,
+    ]
+)
+def equal_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> StrategyType:
+    # equal_strategy deals with ops that comparing two tensor, we need to make sure
+    # sharding layout the same with two operands, we choose to follow the arg with max
+    # num of shards, still keep is_same_size here for completeness as they share the
+    # same strategy in theory.
+    self_strategy, other_strategy = op_schema.args_schema
+    assert isinstance(self_strategy, OpStrategy)
+    assert isinstance(other_strategy, OpStrategy)
+
+    select_strategy = (
+        self_strategy
+        if self_strategy.max_num_shards() >= other_strategy.max_num_shards()
+        else other_strategy
+    )
+    equal_strategy = OpStrategy([])
+
+    for arg_strategy in select_strategy.strategies:
+        arg_spec = arg_strategy.output_spec
+        if is_tensor_partial(arg_spec):
+            # if the arg_spec have partial, reshard to replicate
+            # otherwise local shard tensor comparison would be invalid
+            output_spec = DTensorSpec(
+                mesh=arg_spec.mesh,
+                placements=tuple(
+                    Replicate() if isinstance(p, Partial) else p
+                    for p in arg_spec.placements
+                ),
+            )
+            equal_strategy.strategies.append(
+                PlacementStrategy(output_specs=output_spec)
+            )
+        else:
+            equal_strategy.strategies.append(PlacementStrategy(arg_spec))
+    return equal_strategy
+
+
+@register_op_strategy(
+    [
+        aten.empty_like.default,
+        aten.ones_like.default,
+        aten.rand_like.default,
+        aten.randn_like.default,
+        aten.zeros_like.default,
+    ],
+    schema_info=RuntimeSchemaInfo(1, ["dtype"]),
+)
+@register_op_strategy(
+    [aten.full_like.default],
+    schema_info=RuntimeSchemaInfo(2, ["dtype"]),
+)
+@register_op_strategy(
+    [
+        aten.randint_like.default,
+        aten.randint_like.low_dtype,
+        aten.randint_like.low_dtype_out,
+    ],
+    schema_info=RuntimeSchemaInfo(3, ["dtype"]),
+)
+def create_like_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> StrategyType:
+    # create_like_strategy deals with ops that creating tensors with same
+    # shape as input, but with specific content that does not depend on
+    # the input, we can propagate sharding, but we have to make sure we
+    # move from partial to replicated.
+    select_strategy = op_schema.args_schema[0]
+    create_like_strategy = OpStrategy([])
+    assert isinstance(select_strategy, OpStrategy)
+    for arg_strategy in select_strategy.strategies:
+        arg_spec = arg_strategy.output_spec
+        if is_tensor_partial(arg_spec):
+            # if the arg_spec have partial, accept partial
+            # in the input_specs but output replicate for
+            # those corresponding mesh dims
+            output_spec = DTensorSpec(
+                mesh=arg_spec.mesh,
+                placements=tuple(
+                    Replicate() if isinstance(p, Partial) else p
+                    for p in arg_spec.placements
+                ),
+            )
+            create_like_strategy.strategies.append(
+                PlacementStrategy(output_specs=output_spec, input_specs=(arg_spec,))
+            )
+
+        else:
+            create_like_strategy.strategies.append(PlacementStrategy(arg_spec))
+
+    return create_like_strategy
+
+
+@register_op_strategy(
+    [
+        aten.new_empty.default,
+        aten.new_full.default,
+        aten.new_ones.default,
+        aten.new_zeros.default,
+        aten.new_empty_strided.default,
+    ],
+    schema_info=RuntimeSchemaInfo(1, ["dtype"]),
+)
+def new_factory_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> StrategyType:
+    # Currently there are two strategies:
+    # 1. let the output be replicated
+    # 2. let the output follow the input if input and output have the same shape
+    input_strategy = op_schema.args_schema[0]
+    assert isinstance(input_strategy, OpStrategy)
+    input_shape = input_strategy.shape
+    output_shape = op_schema.args_schema[1]
+    assert isinstance(output_shape, list)
+
+    new_factory_strategy = OpStrategy([])
+    for arg_strategy in input_strategy.strategies:
+        input_spec = arg_strategy.output_spec
+        replica_spec = DTensorSpec(mesh, tuple([Replicate()] * mesh.ndim))
+        new_factory_strategy.strategies.append(
+            PlacementStrategy(
+                output_specs=replica_spec,
+                input_specs=(input_spec,),
+                redistribute_cost=[[0.0] * mesh.ndim],
+            )
+        )
+
+        if tuple(input_shape) == tuple(output_shape) and input_spec.is_sharded():
+            # NOTE: for new_empty_strided, currently the non-replicate sharding
+            #       is supported only when the shape is evenly shardable
+            if (
+                op_schema.op == aten.new_empty_strided.default
+                and not is_tensor_evenly_shardable(input_shape, input_spec)
+            ):
+                continue
+
+            new_factory_strategy.strategies.append(
+                PlacementStrategy(
+                    output_specs=input_spec,
+                    input_specs=(input_spec,),
+                    # encouraging new tensor placement to be the same as input
+                    redistribute_cost=[[-0.1] * mesh.ndim],
+                )
+            )
+
+    return new_factory_strategy
+
+
+@register_op_strategy(aten.bucketize.Tensor)
+def gen_bucketize_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> StrategyType:
+    """Just propagate input sharding, but expect replicated for boundaries input."""
+    input_strategy = op_schema.args_schema[0]
+    bucketize_strategy = OpStrategy([])
+    assert isinstance(input_strategy, OpStrategy)
+    for arg_strategy in input_strategy.strategies:
+        arg_spec = DTensorSpec(mesh, arg_strategy.output_spec.placements)
+        replica_spec = DTensorSpec(mesh, tuple([Replicate()] * mesh.ndim))
+        bucketize_strategy.strategies.append(
+            PlacementStrategy(
+                output_specs=arg_spec, input_specs=(arg_spec, replica_spec)
+            )
+        )
+
+    return bucketize_strategy
+
+
+@register_op_strategy(aten.slice.Tensor, schema_info=RuntimeSchemaInfo(1))
+def gen_slice_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> StrategyType:
+    """Forward all shardings except the slice dimension."""
+    defaults = (None, 0, None, None, 1)
+    input_strategy, dim, start, end, step = (
+        op_schema.args_schema + defaults[len(op_schema.args_schema) :]
+    )
+    assert isinstance(input_strategy, OpStrategy)
+    input_shape = input_strategy.shape
+    input_ndim = input_strategy.ndim
+    assert isinstance(dim, int)
+    if start is None:
+        start = 0
+    if end is None or end > input_shape[dim]:
+        end = input_shape[dim]
+    assert isinstance(start, int)
+    assert isinstance(end, int)
+    assert isinstance(step, int)
+
+    # normalize args
+    slice_dim = normalize_dim(dim, input_ndim)
+    start = normalize_dim(start, input_shape[dim])
+    end = normalize_dim(end, input_shape[dim])
+
+    redundant_slice = start == 0 and end == input_shape[dim] and step == 1
+
+    slice_strategy = OpStrategy([])
+
+    for arg_strategy in input_strategy.strategies:
+        arg_spec = arg_strategy.output_spec
+        if not is_tensor_dim_sharded(arg_spec, dim=slice_dim) or redundant_slice:
+            # only add the strategy if the slice dim is not sharded
+            out_spec = DTensorSpec(mesh, arg_spec.placements)
+            slice_strategy.strategies.append(PlacementStrategy(output_specs=out_spec))
+    if not slice_strategy.strategies:
+        # if all strategies are filtered out, unsharding all specs on slice dim
+        # of the input strategy, and use that as the op strategy
+        for arg_strategy in input_strategy.strategies:
+            arg_spec = arg_strategy.output_spec
+            unshard_spec = DTensorSpec(
+                mesh, unshard_tensor_dim(arg_spec.placements, dim=slice_dim)
+            )
+            slice_strategy.strategies.append(
+                PlacementStrategy(output_specs=unshard_spec)
+            )
+    return slice_strategy
+
+
+def unshard_tensor_dim(
+    placements: Sequence[Placement], dim: int
+) -> Tuple[Placement, ...]:
+    """Disallow the given tensor dimension to be sharded."""
+    return tuple(
+        p if (not isinstance(p, Shard) or p.dim != dim) else Replicate()
+        for p in placements
+    )
+
+
+def replicate_tensor_dim(
+    placements: Sequence[Placement], dim: int
+) -> Tuple[Placement, ...]:
+    """Force the given tensor dimension to be replicated."""
+    # Not using p.is_shard() to avoid mypy complain about Placement not having
+    # attribute dim.
+    return tuple(
+        Replicate() if p.is_partial() or isinstance(p, Shard) and p.dim == dim else p
+        for p in placements
+    )
+
+
+@register_op_strategy(aten.slice_scatter.default, schema_info=RuntimeSchemaInfo(2))
+def gen_slice_scatter_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> StrategyType:
+    # 1. number of dimensions in input and src need to match.
+    # 2. number of elements on all non-dim need to match between input and src.
+    # 3. numer of elements in src in dim need to match the slice size.
+    # Given the above:
+    # - We suggest for src to follow the sharding of input, except on the scatter dimension,
+    #   where our best bet for now is to make them replicated as a fall-back.
+    #   TODO: Ideally we'd like to make sure the output is re-sharded afterwards to keep input sharding.
+
+    input_strategy = op_schema.args_schema[0]
+    assert isinstance(input_strategy, OpStrategy)
+    input_ndim = input_strategy.ndim
+    slice_dim = (
+        cast(int, op_schema.args_schema[2]) if len(op_schema.args_schema) > 2 else 0
+    )
+    slice_dim = normalize_dim(slice_dim, input_ndim)
+
+    slice_scatter_strategy = OpStrategy([])
+    # by default follow the input strategy for both input and src
+    for arg_strategy in input_strategy.strategies:
+        arg_spec = arg_strategy.output_spec
+        if not (
+            is_tensor_dim_sharded(arg_spec, dim=slice_dim)
+            or is_tensor_partial(arg_spec)
+        ):
+            # only add the strategy if the slice_scatter dim is not sharded or partial
+            slice_scatter_strategy.strategies.append(
+                PlacementStrategy(output_specs=arg_spec)
+            )
+
+    if not slice_scatter_strategy.strategies:
+        # if all strategies are filtered out, replicating all specs on slice_scatter dim
+        # of the input strategy, and use that as the op strategy
+        for arg_strategy in input_strategy.strategies:
+            arg_spec = arg_strategy.output_spec
+            replicate_spec = DTensorSpec(
+                mesh, replicate_tensor_dim(arg_spec.placements, dim=slice_dim)
+            )
+            slice_scatter_strategy.strategies.append(
+                PlacementStrategy(output_specs=replicate_spec)
+            )
+    return slice_scatter_strategy
+
+
+@register_op_strategy(aten._local_scalar_dense.default)
+def replica_only_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> StrategyType:
+    """Only allow replication on the input/output."""
+    replicate_spec = DTensorSpec(mesh, tuple([Replicate()] * mesh.ndim))
+    return OpStrategy([PlacementStrategy(replicate_spec)])
+
+
+@register_op_strategy(
+    [aten.scatter_.value, aten.scatter.value, aten.scatter_.src, aten.scatter.src],
+    schema_info=RuntimeSchemaInfo(1),
+)
+def scatter_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> StrategyType:
+    input_strategy = cast(OpStrategy, op_schema.args_schema[0])
+    single_mesh_dim_strategies = []
+
+    # placement list stores placements of [output, input, index, src]
+    # first we always have replicate all for inputs and output
+    if len(op_schema.args_strategy) < 3:
+        # scatter_.src/scatter.src with src be float number instead of tensor
+        all_replicate: PlacementList = [Replicate()] * 3
+    else:
+        all_replicate = [Replicate()] * 4
+    single_mesh_dim_strategies.append(all_replicate)
+
+    # TODO: see if we can support input sharding pattern
+    inplace_op = _is_inplace_op(op_schema.op)
+
+    op_strategy = expand_to_full_mesh_op_strategy(
+        mesh, op_schema, single_mesh_dim_strategies, inplace_op=inplace_op
+    )
+    return op_strategy
+
+
+@register_op_strategy(aten.gather.default)
+def gather_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> StrategyType:
+    input_strategy = cast(OpStrategy, op_schema.args_schema[0])
+    dim = cast(int, op_schema.args_schema[1])
+    index_strategy = cast(OpStrategy, op_schema.args_schema[2])
+
+    input_shape = input_strategy.shape
+    index_shape = index_strategy.shape
+
+    single_mesh_dim_strategies = []
+
+    # placement list stores placements of [output, input, index]
+    # first we always have replicate all for inputs and output
+    all_replicate: PlacementList = [Replicate()] * 3
+    single_mesh_dim_strategies.append(all_replicate)
+
+    # input sharding, input sharded, index accepts mask partial, output follows index
+    # this only works when the input is sharded on the gather dimension, and
+    # index has size 1 on the gather dimension
+    if index_shape[dim] == 1:
+        index_partial_placement = _MaskPartial(offset_shape=input_shape, offset_dim=dim)
+        input_sharding: PlacementList = [
+            index_partial_placement,
+            Shard(dim),
+            index_partial_placement,
+        ]
+        single_mesh_dim_strategies.append(input_sharding)
+
+    # index sharding, input replicated, index sharded, output follows index
+    # this only works when the sharding dimension is the gather dimension
+    index_sharding: PlacementList = [Shard(dim), Replicate(), Shard(dim)]
+    single_mesh_dim_strategies.append(index_sharding)
+
+    return expand_to_full_mesh_op_strategy(
+        mesh, op_schema, single_mesh_dim_strategies, input_index=1
+    )
+
+
+def _derive_follow_placements_from_tuple_strategy(
+    tuple_strategy: TupleStrategy,
+) -> Sequence[Placement]:
+    """
+    derive the placements to follow from the tuple strategy, mainly used by
+    aten.stack, aten.cat, where each operand have the same shape, and correspondingly
+    expecting the same sharding
+    """
+
+    def merge_placement(
+        cur_placement: Placement, new_placement: Placement
+    ) -> Placement:
+        # semantic if we already have a follow placement, we
+        # check each placement for the current arg placement
+        # to see if we want to merge/adjust the placement to follow
+        # the priority: Partial -> Shard -> Replicate
+        if cur_placement == new_placement:
+            return cur_placement
+
+        if cur_placement.is_partial():
+            if new_placement.is_shard():
+                # follow new placement
+                return new_placement
+            elif new_placement.is_partial():
+                # different partial types, we can't merge and have to replicate all here
+                return Replicate()
+            else:
+                # follow partial
+                return cur_placement
+        elif cur_placement.is_shard():
+            if new_placement.is_shard():
+                # cur/new placement are different sharding (i.e. different shard dim)
+                # currently fallback to replicate all args
+                return Replicate()
+            else:
+                # for partial/replicate, follow the current shard placement
+                return cur_placement
+        else:
+            # current replicate, just follow new placement
+            return new_placement
+
+    follow_placements: Optional[List[Placement]] = None
+    for arg_strategy in tuple_strategy.childs:
+        assert isinstance(arg_strategy, OpStrategy)
+        for placement_strategy in arg_strategy.strategies:
+            arg_placements = placement_strategy.output_spec.placements
+            if follow_placements is None:
+                follow_placements = list(arg_placements)
+                continue
+            mesh_ndim = len(follow_placements)
+            assert follow_placements is not None
+            for mesh_idx in range(mesh_ndim):
+                # merge placements with the priority
+                follow_placements[mesh_idx] = merge_placement(
+                    follow_placements[mesh_idx], arg_placements[mesh_idx]
+                )
+    assert follow_placements is not None, "follow placements should not be None!"
+    return follow_placements
+
+
+def normalize_shard_for_stack(
+    placements: Sequence[Placement], insert_dim: int = 0
+) -> Sequence[Placement]:
+    # stack op would "insert" new dim, so all sharded dim >= the inserted dim need to
+    # be normalized with the new Shard placement
+    normalized_placements: List[Placement] = []
+    for placement in placements:
+        if isinstance(placement, Shard) and placement.dim >= insert_dim:
+            normalized_placements.append(Shard(placement.dim + 1))
+        else:
+            normalized_placements.append(placement)
+    return normalized_placements
+
+
+@register_op_strategy(aten.stack.default, RuntimeSchemaInfo(1, needs_pytree=True))
+def stack_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> StrategyType:
+    args_schema = op_schema.args_schema
+    input_tuple_strategy = args_schema[0]
+    assert isinstance(input_tuple_strategy, TupleStrategy), f"{input_tuple_strategy}"
+    first_input_strategy = input_tuple_strategy.childs[0]
+    assert isinstance(first_input_strategy, OpStrategy), f"{first_input_strategy}"
+    common_input_ndim = first_input_strategy.ndim
+    dim = cast(int, args_schema[1]) if len(args_schema) > 1 else 0
+    # normalize the dim to be within the common input ndim
+    dim = normalize_dim(dim, common_input_ndim)
+
+    follow_placements = _derive_follow_placements_from_tuple_strategy(
+        input_tuple_strategy
+    )
+
+    # create op strategy base on the follow placements
+    op_strategy = OpStrategy([])
+
+    input_specs = tuple(
+        DTensorSpec(mesh, tuple(follow_placements))
+        for _ in range(len(input_tuple_strategy.childs))
+    )
+
+    follow_placements = normalize_shard_for_stack(follow_placements, dim)
+
+    op_strategy.strategies.append(
+        PlacementStrategy(
+            output_specs=DTensorSpec(mesh, tuple(follow_placements)),
+            input_specs=input_specs,
+        )
+    )
+    return op_strategy
+
+
+@register_op_strategy(aten.cat.default, RuntimeSchemaInfo(1, needs_pytree=True))
+def cat_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> StrategyType:
+    args_schema = op_schema.args_schema
+    input_tuple_strategy = args_schema[0]
+    assert isinstance(input_tuple_strategy, TupleStrategy), f"{input_tuple_strategy}"
+    first_input_strategy = input_tuple_strategy.childs[0]
+    assert isinstance(first_input_strategy, OpStrategy), f"{first_input_strategy}"
+    common_input_ndim = first_input_strategy.ndim
+    dim = cast(int, args_schema[1]) if len(args_schema) > 1 else 0
+    # normalize the dim to be within the common input ndim
+    dim = normalize_dim(dim, common_input_ndim)
+
+    follow_placements = _derive_follow_placements_from_tuple_strategy(
+        input_tuple_strategy
+    )
+    # for cat we unshard the cat dim if it is sharded
+    follow_placements = unshard_tensor_dim(follow_placements, dim)
+
+    # create op strategy base on the follow placements
+    op_strategy = OpStrategy([])
+
+    input_specs = tuple(
+        DTensorSpec(mesh, tuple(follow_placements))
+        for _ in range(len(input_tuple_strategy.childs))
+    )
+    op_strategy.strategies.append(
+        PlacementStrategy(
+            output_specs=DTensorSpec(mesh, tuple(follow_placements)),
+            input_specs=input_specs,
+        )
+    )
+    return op_strategy
+
+
+@register_prop_rule(aten.index_select.default, schema_info=RuntimeSchemaInfo(1))
+def prop_index_select(op_schema: OpSchema) -> OutputSharding:
+    values_spec, dim, indices_spec = op_schema.args_schema
+
+    assert isinstance(values_spec, DTensorSpec)
+    assert isinstance(dim, int)
+    assert isinstance(indices_spec, DTensorSpec)
+
+    all_indices_spec: List[Optional[DTensorSpec]] = [
+        indices_spec if dim == i else None for i in range(values_spec.ndim)
+    ]
+
+    result = prop_index(
+        OpSchema(
+            op=op_schema.op,
+            args_schema=(values_spec, all_indices_spec),
+            kwargs_schema=op_schema.kwargs_schema,
+        )
+    )
+    if result.redistribute_schema:
+        schema_suggestion = result.redistribute_schema
+        result.redistribute_schema = OpSchema(
+            op=op_schema.op,
+            args_schema=(
+                schema_suggestion.args_schema[0],
+                dim,
+                schema_suggestion.args_schema[1][dim],
+            ),
+            kwargs_schema=op_schema.kwargs_schema,
+        )
+    return result
+
+
+@register_prop_rule(aten.index.Tensor, schema_info=RuntimeSchemaInfo(needs_pytree=True))
+def prop_index(op_schema: OpSchema) -> OutputSharding:
+    """
+    Expect replicated on the first input; _mostly_ pointwise on the second input.
+
+    TODO: exception: when the dtype of second input is "bool", then a torch.nonzero needs to be triggered first.
+    """
+    # Current sharding constraints:
+    # For values:
+    #   1. We currently require that the dimension of values_spec be replicated or partial
+    #      if they are being indexed on.
+    #   2. Other dimensions of values_spec can remain sharded if they are so.
+    # For indices:
+    #   Indices can be either sharded or replicated. All index tensors need to be sharded
+    #   in a compatible way, following the pointwise rule (including resolving Partial
+    #   into either sharded or replicated)
+
+    values_spec, multi_indices_spec = op_schema.args_schema
+    assert isinstance(values_spec, DTensorSpec)
+    assert isinstance(multi_indices_spec, list)
+    multi_indices_spec = cast(List[Optional[DTensorSpec]], multi_indices_spec)
+    valid_indices_spec: List[Tuple[int, DTensorSpec]] = [
+        (i, a) for i, a in enumerate(multi_indices_spec) if a is not None
+    ]
+
+    # 1. All indices have to be sharded equally. Moreover, indices can be broadcast.
+    #    Here, we piggyback on the pointwise sharding rule for indices.
+    indices_out = pointwise_rule(
+        OpSchema(
+            op=op_schema.op,
+            args_schema=tuple(v[1] for v in valid_indices_spec),
+            kwargs_schema={},
+        )
+    )
+    need_reshard_on_indices = indices_out.output_spec is None
+
+    if not need_reshard_on_indices:
+        # this means that our inputs are already sharded properly and we will use that as our indices_spec
+        assert isinstance(indices_out.output_spec, DTensorSpec)
+        indices_spec: DTensorSpec = indices_out.output_spec
+    else:
+        assert indices_out.redistribute_schema is not None
+        valid_indices_suggestion = indices_out.redistribute_schema
+        for i, v in enumerate(valid_indices_suggestion.args_spec):
+            multi_indices_spec[valid_indices_spec[i][0]] = v
+        # we'll need to call pointwise_rule again to see what's our ideal indices_spec and then
+        # use that to compute our ideal values_spec
+        indices_output_spec = pointwise_rule(valid_indices_suggestion).output_spec
+        assert isinstance(indices_output_spec, DTensorSpec)
+        indices_spec = indices_output_spec
+
+    lookup_dims = {v[0] for v in valid_indices_spec}
+
+    need_reshard_on_values = tuple(
+        (isinstance(vp, Shard) and (vp.dim in lookup_dims or isinstance(ip, Shard)))
+        for vp, ip in zip(values_spec.placements, indices_spec.placements)
+    )
+
+    if not need_reshard_on_indices and not any(need_reshard_on_values):
+        value_placements = values_spec.placements
+
+        all_dims_consecutive = all(
+            b[0] - a[0] == 1
+            for b, a in zip(valid_indices_spec[1:], valid_indices_spec[:-1])
+        )
+        if all_dims_consecutive:
+            # if all index vectors are consecutives, insert at the dimension of the first index
+            insert_dim: int = valid_indices_spec[0][0]
+        else:
+            # else, insert on the first dimension
+            insert_dim = 0
+
+        def place(vp: Placement, ip: Placement) -> Placement:
+            if isinstance(vp, Shard):
+                return Shard(
+                    vp.dim
+                    if vp.dim < insert_dim
+                    # accounts for the offset in output dimensions
+                    else vp.dim
+                    + indices_spec.ndim
+                    - sum(1 if vp.dim > v[0] else 0 for v in valid_indices_spec)
+                )
+            if isinstance(ip, Shard):
+                return Shard(ip.dim + insert_dim)
+            # Partial or Replicated
+            return vp
+
+        value_placements = tuple(
+            place(vp, ip)
+            for vp, ip in zip(values_spec.placements, indices_spec.placements)
+        )
+        result = OutputSharding(
+            output_spec=DTensorSpec(
+                mesh=values_spec.mesh,
+                placements=value_placements,
+            )
+        )
+        return result
+    else:
+        result = OutputSharding(
+            output_spec=None,
+            redistribute_schema=OpSchema(
+                op=op_schema.op,
+                args_schema=(
+                    DTensorSpec(
+                        mesh=values_spec.mesh,
+                        placements=tuple(
+                            [
+                                Replicate() if need_reshard_on_values[i] else v
+                                for i, v in enumerate(values_spec.placements)
+                            ]
+                        ),
+                        tensor_meta=values_spec.tensor_meta,
+                    ),
+                    multi_indices_spec,
+                ),
+                kwargs_schema=op_schema.kwargs_schema,
+            ),
+        )
+        return result
+
+
+@register_prop_rule(
+    [
+        aten.split.Tensor,
+        aten.split_with_sizes.default,
+        aten.split_with_sizes_copy.default,
+    ],
+    schema_info=RuntimeSchemaInfo(1),
+)
+def split_rule(op_schema: OpSchema) -> OutputSharding:
+    output_spec_list: List[DTensorSpec] = []
+    input_spec = cast(DTensorSpec, op_schema.args_schema[0])
+    ndim = input_spec.ndim
+    split_size_or_sections = op_schema.args_schema[1]
+    dim = cast(int, op_schema.args_schema[2]) if len(op_schema.args_schema) > 2 else 0
+    dim = normalize_dim(dim, ndim)
+
+    # TODO: tensor to split cannot have Partial
+    # in its placements for now. Will need to
+    # support in future.
+    if input_spec.sums:
+        raise NotImplementedError(
+            f"splitting distributed tensor with "
+            f"Partial placement is not implemented!\n"
+            f"DTensorSpec={input_spec}"
+        )
+
+    # TODO: just like slice op, split replicates before
+    # splitting on a sharded dimension
+    need_reshard = False
+    if is_tensor_dim_sharded(input_spec, dim=dim):
+        need_reshard = True
+        input_spec = DTensorSpec(
+            mesh=input_spec.mesh,
+            placements=unshard_tensor_dim(input_spec.placements, dim=dim),
+            tensor_meta=input_spec.tensor_meta,
+        )
+
+    if need_reshard:
+        return OutputSharding(
+            None,
+            redistribute_schema=OpSchema(
+                op=op_schema.op,
+                args_schema=(input_spec,) + op_schema.args_schema[1:],
+                kwargs_schema=op_schema.kwargs_schema,
+            ),
+        )
+
+    def size_split(N, i):
+        # Last chunk will be smaller if the tensor size N
+        # along the given dimension dim is not divisible by i.
+        assert i > 0
+        return [i] * (N // i) + ([N % i] if N % i != 0 else [])
+
+    output_size_list = (
+        size_split(input_spec.shape[dim], split_size_or_sections)
+        if isinstance(split_size_or_sections, int)
+        else split_size_or_sections
+    )
+    output_spec_list = [
+        DTensorSpec(
+            mesh=input_spec.mesh,
+            placements=input_spec.placements,
+        )
+        for _ in range(len(output_size_list))
+    ]
+    return OutputSharding(output_spec_list)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_view_ops.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_view_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..451b92c80b24b8df0ed7719392302f836175e926
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/_view_ops.py
@@ -0,0 +1,666 @@
+# mypy: allow-untyped-decorators
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and affiliates
+from dataclasses import dataclass
+from typing import (
+    Callable,
+    cast,
+    Dict,
+    Iterable,
+    List,
+    Optional,
+    Sequence,
+    Set,
+    Tuple,
+    Union,
+)
+
+import torch
+from torch import Tensor
+from torch.distributed.device_mesh import DeviceMesh
+from torch.distributed.tensor._dtensor_spec import DTensorSpec
+from torch.distributed.tensor._op_schema import (
+    OpSchema,
+    OpStrategy,
+    PlacementStrategy,
+    RuntimeSchemaInfo,
+    StrategyType,
+)
+from torch.distributed.tensor._ops.utils import (
+    generate_redistribute_costs,
+    normalize_dim,
+    normalize_dims,
+    prod,
+    register_op_strategy,
+)
+from torch.distributed.tensor.placement_types import Placement, Replicate, Shard
+
+
+aten = torch.ops.aten
+
+Shape = Tuple[int, ...]
+
+
+@dataclass
+class DimSpec:
+    """Specifies how an output dimension maps to an input dimension."""
+
+    def inputs(self) -> Iterable["DimSpec"]:
+        return ()
+
+
+# Rules that map each dimension of the output to dimensions of the input tensor
+DimMap = Tuple[DimSpec, ...]
+
+
+@dataclass
+class Singleton(DimSpec):
+    """Output dimension is a singleton."""
+
+
+@dataclass
+class InputDim(DimSpec):
+    """Output dimension maps directly to an input dimension."""
+
+    input_dim: int
+
+
+@dataclass
+class Broadcast(DimSpec):
+    """Output is the broadcast of a singleton input dimension."""
+
+    dim: DimSpec
+    dim_size: int
+
+    @classmethod
+    def new(cls, dim: DimSpec, dim_size: int) -> DimSpec:
+        return Broadcast(dim, dim_size)
+
+    def inputs(self) -> Iterable[DimSpec]:
+        return (self.dim,)
+
+
+@dataclass
+class NewDim(DimSpec):
+    """This is a new dimension created by the op."""
+
+    size: int
+
+    @classmethod
+    def new(cls, size: int) -> DimSpec:
+        return Singleton() if size == 1 else NewDim(size)
+
+
+@dataclass
+class Repeat(DimSpec):
+    """Output dimension is the input dimension repeated n-times."""
+
+    input_dim: DimSpec
+    times: int
+
+    @classmethod
+    def new(cls, dim: DimSpec, times: int) -> DimSpec:
+        if times == 1:
+            return dim
+        elif isinstance(dim, Singleton):
+            # repeating a singleton is the same as broadcasting it
+            return Broadcast(dim, times)
+        else:
+            return Repeat(dim, times)
+
+    def inputs(self) -> Iterable[DimSpec]:
+        return (self.input_dim,)
+
+
+@dataclass
+class Flatten(DimSpec):
+    """Flatten a set of input dimensions, ensuring right-most adjacent elements remain adjacent in the output."""
+
+    input_dims: Sequence[DimSpec]
+
+    @classmethod
+    def new(cls, dims: Sequence[DimSpec]) -> DimSpec:
+        if len(dims) == 0:
+            # flattening a scalar leads to a singleton
+            return Singleton()
+        elif len(dims) == 1:
+            # flattening a single dimension is no-op
+            return dims[0]
+        else:
+            return Flatten(dims)
+
+    def inputs(self) -> Iterable[DimSpec]:
+        return self.input_dims
+
+
+@dataclass
+class Split(DimSpec):
+    """
+    This dimension is a member of a decomposition of the input dim.
+
+    Note that input_dim itself could be a Flattened set of input dims.
+    """
+
+    input_dim: DimSpec
+    group_shape: Shape
+    split_id: int
+
+    @classmethod
+    def new(cls, dim: DimSpec, group_shape: Tuple[int, ...], idx: int) -> DimSpec:
+        assert len(group_shape) > 0
+        if len(group_shape) == 1:
+            # not really a group, just return the input dim back
+            assert idx == 0
+            return dim
+        elif group_shape[idx] == 1:
+            return Singleton()
+        else:
+            # remove singletons from group
+            # group_mapping = [(new_index, (shape, old_index)) ...]
+            group_mapping = list(
+                enumerate((s, i) for i, s in enumerate(group_shape) if s != 1)
+            )
+            new_group_shape = tuple(m[1][0] for m in group_mapping)
+            new_idx = next(filter(lambda x: x[1][1] == idx, group_mapping))[0]
+            return Split(dim, new_group_shape, new_idx)
+
+    def inputs(self) -> Iterable[DimSpec]:
+        return (self.input_dim,)
+
+
+def dim_pad_left(ndim: int, min_dims: int) -> DimMap:
+    return (Singleton(),) * max(0, min_dims - ndim) + tuple(
+        InputDim(i) for i in range(ndim)
+    )
+
+
+def dim_atleast_3d(ndim: int) -> DimMap:
+    if ndim == 0:
+        return (Singleton(), Singleton(), Singleton())
+    elif ndim == 1:
+        return (Singleton(), InputDim(0), Singleton())
+    elif ndim == 2:
+        return (InputDim(0), InputDim(1), Singleton())
+    else:
+        return tuple(InputDim(i) for i in range(ndim))
+
+
+def expand(input_shape: Shape, shape: Shape) -> DimMap:
+    """Implement broadcast on multiple dimensions."""
+    assert len(shape) >= len(input_shape)
+
+    # 1. create padded input dimensions
+    padded_input = dim_pad_left(len(input_shape), len(shape))
+    # 2. check that input shapes are compatible
+    mapping = []
+    for p, desired_s in zip(padded_input, shape):
+        if isinstance(p, Singleton):
+            actual_s = 1
+            assert desired_s >= 0
+        else:
+            assert isinstance(p, InputDim), f"DimSpec not supported in expand: {p}"
+            actual_s = input_shape[p.input_dim]
+            assert actual_s == 1 or desired_s == -1 or desired_s == actual_s
+        mapping.append(
+            p
+            if desired_s in (1, -1) or desired_s == actual_s
+            else Broadcast.new(p, desired_s)
+        )
+    return tuple(mapping)
+
+
+def normalize_sizes(sizes: Union[Shape, Tuple[Shape]]) -> Shape:
+    if isinstance(sizes[0], int):
+        return cast(Shape, sizes)
+    elif len(sizes) == 1:
+        return sizes[0]
+    else:
+        raise RuntimeError("Size must be int... or tuple")
+
+
+def dim_flatten(ndim: int, start_dim=0, end_dim=-1) -> DimMap:
+    if ndim == 0:
+        return (Singleton(),)
+    elif ndim == 1:
+        return (InputDim(0),)
+    else:
+        # only flattening dims from start_dim to end_dim (inclusive)
+        # other dims are passed through
+        if end_dim < 0:
+            end_dim += ndim
+        results: List[DimSpec] = [InputDim(i) for i in range(start_dim)]
+        results.append(
+            Flatten.new(tuple(InputDim(i) for i in range(start_dim, end_dim + 1)))
+        )
+        results.extend([InputDim(i) for i in range(end_dim + 1, ndim)])
+        return tuple(results)
+
+
+def dim_movedim(
+    ndim: int,
+    input: Union[int, Sequence[int]],
+    destination: Union[int, Sequence[int]],
+) -> DimMap:
+    input = normalize_dims(input, ndim)
+    destination = normalize_dims(destination, ndim)
+
+    assert len(input) == len(destination)
+    input_set = set(input)
+    assert len(input_set) == len(input), "Found repeated input dims"
+    assert len(set(destination)) == len(destination), "Found repeated output dims"
+    assert max(input) < ndim
+    assert max(destination) < ndim
+
+    dest = [-1] * ndim
+    for i, d in zip(input, destination):
+        dest[d] = i
+
+    unused_inputs_iter = iter(i for i in range(ndim) if i not in input_set)
+    for i in range(ndim):
+        if dest[i] == -1:
+            dest[i] = next(unused_inputs_iter)
+
+    return tuple(InputDim(i) for i in dest)
+
+
+def dim_repeat(ndim: int, sizes: Shape) -> DimMap:
+    sizes = normalize_sizes(sizes)
+    assert (
+        len(sizes) >= ndim
+    ), f"Number of dimensions of repeat dims {sizes} can not be smaller than number of dimensions of tensor {ndim}."
+    pad = len(sizes) - ndim
+    return tuple(Repeat.new(Singleton(), s) for s in sizes[:pad]) + tuple(
+        Repeat.new(InputDim(i), s) for i, s in enumerate(sizes[pad:])
+    )
+
+
+def infer_size(total_size: int, sizes: Shape) -> Shape:
+    """
+    One dimension input to view may be "-1".
+
+    Infer the size of this dimension given the total_size.
+    """
+    infers = [i for i, s in enumerate(sizes) if s == -1]
+    size = prod(sizes)
+    assert len(infers) <= 1, "can only infer one size"
+    if infers:
+        size = -size
+        missing_size = total_size // size
+        assert (
+            total_size % size == 0
+        ), f"size inferred for -1 is not integral {sizes} should have {total_size} elements."
+        return tuple(s if s != -1 else missing_size for s in sizes)
+    assert size == total_size, f"sizes do not match {total_size} vs {size}"
+    return sizes
+
+
+def view_groups(from_size: Shape, to_size: Shape) -> DimMap:
+    """
+    Decompose a reshape operation into forwarding, flattening, or splitting dimensions for each output dimension.
+
+    A view or reshape operation can be decomposed into a set of 3 types of smaller operations:
+    1) Forward a dimension from input to output
+    2) Flatten a set of dimensions into a single dimension
+    3) Split one dimension into multiple dimensions
+
+    view_groups identifies these operations and returns, for each output dimension, what
+    is operation was performed in the input dimension. For example:
+
+        view_groups([2, 3, 4], [2, 12]) -> (
+            InputDim(0),
+            Flatten((InputDim(1), InputDim(2)))
+        )
+
+    - ouptut dimension 0 maps to input dimension 0
+    - output dimension 1 maps to a flattened input dimensions 1 and 2
+
+
+        view_groups([2, 3], [3, 2]) -> (
+            Split(Flatten((InputDim(0), InputDim(1))), (3, 2), 0),
+            Split(Flatten((InputDim(0), InputDim(1))), (3, 2), 1),
+        )
+
+    - in the above, input is flattened into a single dimension and then split
+      into two separate dimensions with different sizes from the input.
+    """
+    from_nelem = prod(from_size)
+    to_size = infer_size(from_nelem, normalize_sizes(to_size))
+
+    assert from_nelem == prod(to_size), "Total view shape does not add up"
+
+    from_idx = 0
+    to_idx = 0
+    from_len = len(from_size)
+    to_len = len(to_size)
+
+    result_pp = []
+
+    while from_idx < from_len or to_idx < to_len:
+        from_group_dim, to_group_shape = [], []
+
+        if from_idx >= from_len:
+            f = 1
+        else:
+            f = from_size[from_idx]
+            from_group_dim.append(from_idx)
+            from_idx += 1
+
+        if to_idx >= to_len:
+            t = 1
+        else:
+            t = to_size[to_idx]
+            to_group_shape.append(t)
+            to_idx += 1
+
+        # if any of the groups is singleton, great, we need to backtrack though
+        if f == 1 and t != 1:
+            # produces ([1], [])
+            to_idx -= 1
+            to_group_shape = []
+        elif f != 1 and t == 1:
+            # produces ([], [1])
+            from_idx -= 1
+            from_group_dim = []
+        else:
+            # produces ([1], [1]),  ([2], [2]), ([2,3], [6])
+            while f != t:
+                if f < t:
+                    nf = from_size[from_idx]
+                    from_group_dim.append(from_idx)
+                    from_idx += 1
+                    f *= nf
+                else:
+                    nt = to_size[to_idx]
+                    to_group_shape.append(nt)
+                    to_idx += 1
+                    t *= nt
+
+        if len(to_group_shape) > 0:
+            flattened = Flatten.new(
+                tuple(InputDim(fi) for fi in from_group_dim if from_size[fi] >= 1)
+            )
+            result_pp += [
+                Split.new(flattened, tuple(to_group_shape), i)
+                for i in range(len(to_group_shape))
+            ]
+
+    return tuple(result_pp)
+
+
+def dim_tile(ndim: int, dims: Tuple[int, ...]) -> DimMap:
+    if len(dims) < ndim:
+        dims = (1,) * (ndim - len(dims)) + dims
+    return dim_repeat(ndim, dims)
+
+
+def dim_transpose(ndim: int, dim1: int, dim2: int) -> DimMap:
+    dim1 = normalize_dim(dim1, ndim)
+    dim2 = normalize_dim(dim2, ndim)
+    assert dim1 < ndim
+    assert dim2 < ndim
+    dimmap = [InputDim(i) for i in range(ndim)]
+    swapdim = dimmap[dim1]
+    dimmap[dim1] = dimmap[dim2]
+    dimmap[dim2] = swapdim
+    return tuple(dimmap)
+
+
+def dim_squeeze(shape: Shape, dim: Optional[int] = None) -> DimMap:
+    # FIXME: this is wrong when dim=None and one of the dimensions
+    # equals size of the mesh. For example squeeze(DTensor(tensor(4), Shard[0])) could
+    # end up as squeeze(tensor(1)) if we have 4 devices; this would lead to
+    # removal of a dimension that is not actually a singleton.
+    return tuple(
+        InputDim(i)
+        for i, s in enumerate(shape)
+        if s > 1 or (dim is not None and i != normalize_dim(dim, len(shape)))
+    )
+
+
+def dim_unsqueeze(ndim: int, dim: int) -> DimMap:
+    dims = tuple(InputDim(i) for i in range(ndim))
+    if dim < 0:
+        dim += ndim + 1
+    return dims[:dim] + (Singleton(),) + dims[dim:]
+
+
+def dim_view_as_real(shape: Shape) -> DimMap:
+    ndim = len(shape)
+    results: List[DimSpec] = [InputDim(i) for i in range(ndim - 1)]
+    # each complex number is split into two real numbers,
+    # resulting in one more dimension of size 2
+    results.append(Split(InputDim(ndim - 1), (shape[-1], 2), 0))
+    results.append(Split(InputDim(ndim - 1), (shape[-1], 2), 1))
+    return tuple(results)
+
+
+def dim_reduction(
+    ndim: int, dim_or_dims: Optional[Union[int, Sequence[int]]], keepdim: bool
+) -> DimMap:
+    """
+    General fallback for reduction ops where Partial() does not apply.
+
+    This will cause incoming tensor to be replicated on the reducing dimensions.
+    """
+    if dim_or_dims is None:
+        dim_or_dims = tuple(range(ndim))
+    if isinstance(dim_or_dims, int):
+        dim_or_dims = (dim_or_dims,)
+    dim_or_dims = tuple(d if d >= 0 else d + ndim for d in dim_or_dims)
+    return tuple(
+        InputDim(i) if i not in dim_or_dims else Singleton()
+        for i in range(ndim)
+        if i not in dim_or_dims or keepdim
+    )
+
+
+dim_maps: Dict[Callable[..., torch.Tensor], Callable[..., DimMap]] = {
+    torch.atleast_1d: lambda x: dim_pad_left(x.ndim, 1),
+    torch.atleast_2d: lambda x: dim_pad_left(x.ndim, 2),
+    torch.atleast_3d: lambda x: dim_atleast_3d(x.ndim),
+    torch.broadcast_to: lambda input, shape: expand(input.shape, shape),
+    Tensor.expand: lambda self, *sizes: expand(self.shape, normalize_sizes(sizes)),
+    torch.flatten: lambda tensor: dim_flatten(tensor.ndim),
+    torch.movedim: lambda input, source, destination: dim_movedim(
+        input.ndim, source, destination
+    ),
+    torch.permute: lambda input, dims: tuple(
+        InputDim(i) for i in normalize_dims(dims, input.ndim)
+    ),
+    torch.ravel: lambda tensor: dim_flatten(tensor.ndim),
+    Tensor.repeat: lambda self, *sizes: dim_repeat(self.ndim, sizes),
+    torch.reshape: lambda input, shape: view_groups(input.shape, shape),
+    torch.squeeze: lambda input, dim=None: dim_squeeze(input.shape, dim),
+    torch.tile: lambda input, dims: dim_tile(input.ndim, dims),
+    torch.transpose: lambda input, dim0, dim1: dim_transpose(input.ndim, dim0, dim1),
+    torch.unsqueeze: lambda input, dim: dim_unsqueeze(input.ndim, dim),
+    Tensor.view: lambda input, *shape: view_groups(input.shape, shape),
+    torch.view_as_complex: lambda input: dim_flatten(input.ndim, input.ndim - 2),
+    torch.view_as_real: lambda input: dim_view_as_real(input.shape),
+}
+
+
+def propagate_shape_and_sharding(
+    input_src_placements: Sequence[Placement],
+    local_in_shape: Shape,
+    rule: DimMap,
+    mesh_sizes: Shape,
+) -> Tuple[Sequence[Placement], Sequence[Placement]]:
+    """
+    Determine input target sharding and output sharding based on
+    given global tensor shape and input source sharding.
+
+    Sharding propagation follows mapped dimensions:
+    - An output dimension that maps directly to an input dimension is sharded equally
+    - An output dimension that is a flattened set of input dimensions can only be
+      sharded if only the leftmost flattened dimension is sharded.
+    - An output dimension that is a split of the input dimension can only be sharded
+      if the leftmost split size is divisible by the mesh dimension
+    """
+    assert len(input_src_placements) == len(mesh_sizes)
+    # for each input dim, for each mesh dim, provides a list of possible shardable dimensions
+    mesh_ndim = len(mesh_sizes)
+    shardable_dims: Dict[int, List[bool]] = {}
+
+    # in case an input dimension disappears (e.g. collapsing, reduction)
+    # we cannot shard in that dimension (we need a replication fall-back rule)
+    seen_input_dims: Set[int] = set()
+
+    def collect_used_inputs(cmd: DimSpec) -> None:
+        if isinstance(cmd, InputDim):
+            seen_input_dims.add(cmd.input_dim)
+        for inp in cmd.inputs():
+            collect_used_inputs(inp)
+
+    for cmd in rule:
+        collect_used_inputs(cmd)
+    for dim in range(len(local_in_shape)):
+        shardable_dims[dim] = [dim in seen_input_dims] * mesh_ndim
+
+    def get_in_dim_to_shard(cmd: DimSpec) -> Optional[InputDim]:
+        if isinstance(cmd, InputDim):
+            return cmd
+        elif isinstance(cmd, Flatten):
+            for dim in cmd.input_dims[1:]:
+                if isinstance(dim, InputDim):
+                    shardable_dims[dim.input_dim] = [False] * mesh_ndim
+            dim0 = cmd.input_dims[0]
+            return dim0 if isinstance(dim0, InputDim) else None
+        elif isinstance(cmd, Split):
+            in_dim = get_in_dim_to_shard(cmd.input_dim)
+            out_size = cmd.group_shape[cmd.split_id]
+            if cmd.split_id == 0 and in_dim is not None:
+                # we need to check that the input dimension is divisible
+                # by the size of the submesh we're sharding it on
+                # NOTE: it would be possible to shard the same input dimension
+                # on more than one mesh dimension. In that case, the dimension
+                # needs to be divisible by the product of mesh sizes.
+                # In order to keep the problem more tractable, we will not consider
+                # double resharding as a suggestion (e.g. [Shard(0), Shard(0) ])
+                # but we will allow it if that's the input and it's compatible
+
+                # 1. is this dimension shardable on each individual mesh dim?
+                shardable_dims[in_dim.input_dim] = [
+                    out_size % mesh_dim_size == 0 for mesh_dim_size in mesh_sizes
+                ]
+
+                # 2. here we special case things like [Shard(0), Shard(0)]
+                submesh_size = 1
+                for size, shard in zip(mesh_sizes, input_src_placements):
+                    if isinstance(shard, Shard) and shard.dim == in_dim:
+                        submesh_size *= size
+                assert (
+                    out_size % submesh_size == 0
+                ), f"Resulting dimension size {out_size} is not divisible by its mesh dimension {submesh_size}."
+
+            # we will only shard our first component of the split
+            return in_dim if cmd.split_id == 0 else None
+        elif isinstance(cmd, Repeat):
+            in_dim = get_in_dim_to_shard(cmd.input_dim)
+            if in_dim is not None:
+                shardable_dims[in_dim.input_dim] = [False] * mesh_ndim
+            return None
+        else:
+            return None
+
+    # for each output dim, find the corresponding input dim in terms of sharding prop
+    shard_dim_map = {}
+    for dim, cmd in enumerate(rule):
+        in_dim = get_in_dim_to_shard(cmd)
+        if in_dim is not None:
+            shard_dim_map[in_dim.input_dim] = dim
+
+    input_tgt_placements = [
+        Replicate()
+        if isinstance(p, Shard) and not shardable_dims[p.dim][mesh_dim]
+        else p
+        for mesh_dim, p in enumerate(input_src_placements)
+    ]
+    output_placements = [
+        Shard(shard_dim_map[p.dim]) if isinstance(p, Shard) else p
+        for p in input_tgt_placements
+    ]
+
+    return input_tgt_placements, output_placements
+
+
+def register_op_strategy_map(
+    aten_op_overload: torch._ops.OpOverload,
+    local_op_name: Callable[..., torch.Tensor],
+    schema_info: Optional[RuntimeSchemaInfo] = None,
+) -> None:
+    dim_map: Callable[..., DimMap] = dim_maps[local_op_name]
+
+    @register_op_strategy(aten_op_overload, schema_info=schema_info)
+    def reshape_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> StrategyType:
+        rules = dim_map(*op_schema.args_schema, **op_schema.kwargs_schema)
+        input_strategy = cast(OpStrategy, op_schema.args_schema[0])
+        global_in_shape = input_strategy.shape
+        assert global_in_shape is not None, "Shape required."
+
+        output_strategy = OpStrategy([])
+        for input_placement_strategy in input_strategy.strategies:
+            input_src_spec = input_placement_strategy.output_spec
+
+            input_tgt_placements, output_placements = propagate_shape_and_sharding(
+                input_src_spec.placements,
+                tuple(global_in_shape),
+                rules,
+                mesh.shape,
+            )
+
+            # TODO: optimize this. we shouldn't simply blindly replicate
+            #       unshardable dims ...
+            # FIXME: this can be wrong for situations where we have
+            #        [Shard(0), Shard(0)]
+            input_tgt_spec = DTensorSpec(
+                placements=tuple(input_tgt_placements),
+                mesh=input_src_spec.mesh,
+                tensor_meta=input_src_spec.tensor_meta,
+            )
+            redistribute_costs = [
+                generate_redistribute_costs(input_strategy, input_tgt_spec)
+            ]
+
+            output_spec = DTensorSpec(mesh=mesh, placements=tuple(output_placements))
+            output_strategy.strategies.append(
+                PlacementStrategy(
+                    output_specs=output_spec,
+                    input_specs=(input_tgt_spec,),
+                    redistribute_cost=redistribute_costs,
+                )
+            )
+
+        return output_strategy
+
+
+register_op_strategy_map(aten.squeeze.default, torch.squeeze)
+register_op_strategy_map(
+    aten.squeeze.dim, torch.squeeze, schema_info=RuntimeSchemaInfo(1)
+)
+register_op_strategy_map(
+    aten.view.default, Tensor.view, schema_info=RuntimeSchemaInfo(1)
+)
+register_op_strategy_map(
+    aten.reshape.default, torch.reshape, schema_info=RuntimeSchemaInfo(1)
+)
+register_op_strategy_map(
+    aten._unsafe_view.default, Tensor.view, schema_info=RuntimeSchemaInfo(1)
+)
+register_op_strategy_map(
+    aten.unsqueeze.default, torch.unsqueeze, schema_info=RuntimeSchemaInfo(1)
+)
+register_op_strategy_map(
+    aten.expand.default, Tensor.expand, schema_info=RuntimeSchemaInfo(1)
+)
+register_op_strategy_map(
+    aten.permute.default, torch.permute, schema_info=RuntimeSchemaInfo(1)
+)
+register_op_strategy_map(
+    aten.repeat.default, Tensor.repeat, schema_info=RuntimeSchemaInfo(1)
+)
+register_op_strategy_map(
+    aten.transpose.int, torch.transpose, schema_info=RuntimeSchemaInfo(1)
+)
+register_op_strategy_map(aten.view_as_complex.default, torch.view_as_complex)
+register_op_strategy_map(aten.view_as_real.default, torch.view_as_real)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..334bcc4a37fea343950b63e62a821e16e432acc5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_ops/utils.py
@@ -0,0 +1,280 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and affiliates
+import functools
+import itertools
+import operator
+from typing import cast, Iterable, List, Optional, Sequence, Tuple, Union
+
+import torch
+from torch.distributed.tensor._api import DTensor
+from torch.distributed.tensor._collective_utils import redistribute_cost
+from torch.distributed.tensor._dtensor_spec import DTensorSpec
+from torch.distributed.tensor._op_schema import (
+    OpSchema,
+    OpStrategy,
+    PlacementList,
+    PlacementStrategy,
+    RuntimeSchemaInfo,
+)
+from torch.distributed.tensor.device_mesh import DeviceMesh
+from torch.distributed.tensor.placement_types import (
+    Partial,
+    Placement,
+    Replicate,
+    Shard,
+)
+
+
+# convenient wrapper to register sharding propagation rules
+# pyre-fixme[3]: Return type must be annotated.
+# pyre-fixme[2]: Parameter must be annotated.
+def register_prop_rule(op, schema_info=None):
+    # pyre-fixme[53]: Captured variable `func` is not annotated.
+    # pyre-fixme[3]: Return type must be annotated.
+    # pyre-fixme[2]: Parameter must be annotated.
+    def wrapper(impl):
+        overloads = op if isinstance(op, list) else [op]
+        for overload in overloads:
+            DTensor._op_dispatcher.sharding_propagator.register_sharding_prop_rule(
+                overload, impl, schema_info
+            )
+        return impl
+
+    return wrapper
+
+
+def register_op_strategy(op, schema_info=None):
+    # pyre-fixme[53]: Captured variable `func` is not annotated.
+    # pyre-fixme[3]: Return type must be annotated.
+    # pyre-fixme[2]: Parameter must be annotated.
+
+    # For every ATen op that accepts any args in this list,
+    # the arg itself can impact the strides (and potentially the sharding strategy)
+    # of the output tensor.
+    # thus, we will detect ATen schemas with any of these args and ensure
+    # that they get specialized here.
+    arg_names_that_require_specializing_cache_strategy = [
+        "memory_format",
+    ]
+
+    def wrapper(impl):
+        if isinstance(op, list):
+            overloads = op
+        else:
+            overloads = [op]
+
+        for overload in overloads:
+            curr_schema_info = None
+            if schema_info is None:
+                specialized_args = [
+                    a.name
+                    for a in overload._schema.arguments
+                    if a.name in arg_names_that_require_specializing_cache_strategy
+                ]
+                if any(specialized_args):
+                    curr_schema_info = RuntimeSchemaInfo(
+                        static_kwargkey=specialized_args
+                    )
+            else:
+                curr_schema_info = schema_info
+            DTensor._op_dispatcher.sharding_propagator.register_op_strategy(
+                overload, impl, curr_schema_info
+            )
+        return impl
+
+    return wrapper
+
+
+def as_list(
+    x: Union[List[object], object]
+    # pyre-fixme[11]: Annotation `immutable_list` is not defined as a type.
+) -> Union[List[object], torch.fx.immutable_collections.immutable_list]:  # type: ignore[valid-type]
+    # During tracing, `aten.sum.dim_IntList` uses `immutable_list` for its args,
+    # which is an object but treated as a list by the tracer. Therefore, keep
+    # `immutable_list` intact here as well.
+    if type(x) is list or isinstance(x, torch.fx.immutable_collections.immutable_list):
+        return x
+    else:
+        return [x]
+
+
+def normalize_dim(dim: int, ndim: int) -> int:
+    return dim if dim >= 0 else dim + ndim
+
+
+def normalize_dims(dims: Union[int, Sequence[int]], ndim: int) -> Sequence[int]:
+    """Normalize a dim or a sequence of dims, so that they are all positive."""
+    if isinstance(dims, int):
+        dims = (normalize_dim(dims, ndim),)
+    elif isinstance(dims, list):
+        dims = [normalize_dim(dim, ndim) for dim in dims]
+    elif isinstance(dims, tuple):
+        dims = tuple([normalize_dim(dim, ndim) for dim in dims])
+    return dims
+
+
+def prod(xs: Iterable[int]) -> int:
+    return functools.reduce(operator.mul, xs, 1)
+
+
+def is_tensor_shardable(shape: Sequence[int], spec: DTensorSpec) -> bool:
+    """Check if the shape is shardable according to the spec."""
+    # number of shards in each tensor dimension
+    shards_map = [1] * len(shape)
+    for i, placement in enumerate(spec.placements):
+        if placement.is_shard():
+            shard_dim = cast(Shard, placement).dim
+            shards_map[shard_dim] *= spec.mesh.size(i)
+
+    for i, dim_size in enumerate(shape):
+        # TODO: maybe we should determine is_shardable based on
+        #       whether it's evenly sharded or not
+        if shards_map[i] > 1 and dim_size < shards_map[i]:
+            return False
+
+    return True
+
+
+def is_tensor_evenly_shardable(shape: Sequence[int], spec: DTensorSpec) -> bool:
+    """Check if the shape is evenly shardable according to the spec."""
+    # number of shards in each tensor dimension
+    shards_map = [1] * len(shape)
+    for i, placement in enumerate(spec.placements):
+        if placement.is_shard():
+            shard_dim = cast(Shard, placement).dim
+            shards_map[shard_dim] *= spec.mesh.size(i)
+
+    for i, dim_size in enumerate(shape):
+        if shards_map[i] > 1 and (dim_size % shards_map[i] != 0):
+            return False
+
+    return True
+
+
+def is_tensor_dim_sharded(spec: DTensorSpec, dim: int) -> bool:
+    """Return True if tensor dim is sharded."""
+    return any(p.is_shard(dim) for p in spec.placements)
+
+
+def is_tensor_partial(spec: DTensorSpec) -> bool:
+    """Return True if tensor is partial on the mesh."""
+    return any(p.is_partial() for p in spec.placements)
+
+
+def infer_broadcast_dims_map(
+    common_shape: torch.Size, input_shape: torch.Size
+) -> List[int]:
+    # infer the broadcast dims map, where it maps from the common shape dim to the input shape dim
+    # this is aligned with the broadcast semantics
+    common_ndim = len(common_shape)
+    input_ndim = len(input_shape)
+    broadcast_dims_map = [-1] * common_ndim
+    for idx in range(-1, -1 - input_ndim, -1):
+        if input_shape[idx] == common_shape[idx]:
+            broadcast_dims_map[common_ndim + idx] = input_ndim + idx
+    return broadcast_dims_map
+
+
+def map_placements_after_broadcast(
+    placements: Tuple[Placement, ...],
+    shape: torch.Size,
+    broadcast_dims_map: List[int],
+) -> Tuple[Placement, ...]:
+    """Map each placement based on the output shape after broadcast."""
+    new_placements: List[Placement] = []
+    for placement in placements:
+        if isinstance(placement, (Replicate, Partial)):
+            new_placements.append(placement)
+        else:
+            assert isinstance(placement, Shard)
+            shard_dim = normalize_dim(placement.dim, len(shape))
+            new_shard_dim = broadcast_dims_map[shard_dim]
+            if new_shard_dim != -1:
+                # there's a map from the common shape shard dim to
+                # the input shape shard dim before broadcasting,
+                # use that instead
+                new_placements.append(Shard(new_shard_dim))
+            else:
+                # there's no map between common shape shard dim and
+                # the input shape shard dim before broadcasting,
+                # in this case it means implicit broadcasting happen
+                # in this dim, so we can just mark it as replicate
+                # and implict broadcast will broadcast automatically
+                # to the sharded shape
+                new_placements.append(Replicate())
+
+    return tuple(new_placements)
+
+
+def generate_redistribute_costs(
+    src_strategy: OpStrategy, dst_spec: DTensorSpec
+) -> List[float]:
+    redistribute_costs: List[float] = []
+    for strat in src_strategy.strategies:
+        redistribute_costs.append(redistribute_cost(strat.output_spec, dst_spec))
+
+    return redistribute_costs
+
+
+def expand_to_full_mesh_op_strategy(
+    mesh: DeviceMesh,
+    op_schema: OpSchema,
+    single_mesh_dim_strategies: List[PlacementList],
+    *,
+    input_index: int = 1,
+    inplace_op: bool = False,
+) -> OpStrategy:
+    # Expand the single_mesh_dim_strategies to full mesh dim strategies.
+    all_mesh_dim_strategies = [single_mesh_dim_strategies] * mesh.ndim
+
+    strategy_combs = itertools.product(*all_mesh_dim_strategies)
+
+    all_strategies = []
+    for strategy_comb in strategy_combs:
+        spec_list: List[Optional[DTensorSpec]] = []
+        for specs in zip(*strategy_comb):
+            if specs[0] is not None:
+                spec_list.append(DTensorSpec(mesh, specs))
+            else:
+                spec_list.append(None)
+
+        input_specs: List[DTensorSpec] = [
+            s for s in spec_list[input_index:] if isinstance(s, DTensorSpec)
+        ]
+
+        input_args_strategy = op_schema.args_strategy
+        assert len(input_specs) == len(input_args_strategy)
+        self_spec = input_args_strategy[0].strategies[0].output_spec
+
+        if inplace_op and self_spec.placements != input_specs[0].placements:
+            # if it's inplace op, we would only allow the placement strategy to be added when the
+            # input_spec matches the first argument's runtime sharding, otherwise we skip
+            continue
+
+        # check inputs shardable
+        inputs_shardable = all(
+            is_tensor_shardable(inp.shape, s)
+            for inp, s in zip(input_args_strategy, input_specs)
+        )
+
+        # only add to the all_strategies list when all inputs are shardable
+        if inputs_shardable:
+            redistribute_cost = [
+                generate_redistribute_costs(input_strategy, input_spec)
+                for input_strategy, input_spec in zip(input_args_strategy, input_specs)
+            ]
+            if input_index > 1:
+                output_specs = tuple(spec_list[:input_index])
+            else:
+                if spec_list[0] is not None:
+                    output_specs = spec_list[0]  # type: ignore[assignment]
+                else:
+                    raise RuntimeError("output spec is None")
+            strategy = PlacementStrategy(
+                output_specs=output_specs,
+                input_specs=input_specs,
+                redistribute_cost=redistribute_cost,
+            )
+            all_strategies.append(strategy)
+
+    return OpStrategy(all_strategies)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_random.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_random.py
new file mode 100644
index 0000000000000000000000000000000000000000..db4b2832548c07525593329893eb4ec900de36e9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_random.py
@@ -0,0 +1,381 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and affiliates
+import contextlib
+import warnings
+from typing import Dict, List, Optional
+
+import torch
+import torch.distributed as dist
+from torch import Tensor
+from torch.distributed.device_mesh import _get_device_handle, DeviceMesh
+from torch.distributed.tensor._dtensor_spec import DTensorSpec
+from torch.distributed.tensor.placement_types import Shard
+
+
+__all__ = [
+    "is_rng_supported_mesh",
+    "manual_seed",
+    "OffsetBasedRNGTracker",
+    "TensorParallelRNGTracker",
+]
+
+_rng_tracker: Optional["_RNGStateTracker"] = None
+
+
+def is_rng_supported_mesh(device_mesh: DeviceMesh) -> bool:
+    """Checks if the current device of ``device_mesh`` supports DTensor's random APIs.
+    Currently DTensor Random APIs only supports cuda/cuda-like devices. We suggest
+    users call this API to test the availability before using our random APIs.
+
+    Args:
+        device_mesh (:class:`DeviceMesh`): The device mesh on which we check if the
+            random ops APIs are supported.
+
+    Returns:
+        A bool value. True if ``device_mesh`` supports DTensor Random APIs; False otherwise.
+
+    .. warning::
+        Currently we only support correct RNG on cuda/cuda-like devices.
+    """
+    device_handle = _get_device_handle(device_mesh.device_type)
+    if device_handle and hasattr(device_handle, "set_rng_state"):
+        return True
+    else:
+        # TODO: Logs way too much
+        warnings.warn(
+            f"DTensor random operators may not have complete support on {device_mesh.device_type} device mesh"
+        )
+        return False
+
+
+def manual_seed(seed: int, device_mesh: DeviceMesh) -> None:
+    """Sets the seed for generating random numbers for the calling rank.
+
+    Args:
+        seed (int): The desired seed.
+        device_mesh (:class:`DeviceMesh`): The device mesh to set the seed.
+
+    Returns:
+        None
+
+    .. warning::
+        When calling this function, :func:`manual_seed` must be called from all ranks of the
+        default ``ProcessGroup`` even if some ranks may not be a part of the ``device_mesh``,
+        with the same ``seed`` value.
+        If ``device_mesh`` is a sub-mesh and the calling rank is not a part of it,
+        ``manual_seed`` will not set its GPU device's generator seed.
+        Current implementation only supports a GPU device mesh.
+    """
+    device_handle = _get_device_handle(device_mesh.device_type)
+    if not device_handle:
+        raise NotImplementedError(
+            f"DTensor randomness only supports cuda/cuda-like device type, but got {device_mesh.device_type}"
+        )
+
+    # allgather the seed over the default PG
+    object_list = [seed] * dist.get_world_size()
+    dist.all_gather_object(object_list, seed)
+    for rank, object in enumerate(object_list):
+        if seed != int(object):
+            raise RuntimeError(
+                f"calling manual_seed function over {device_mesh} but received different seed values on ranks:",
+                f"seed on rank {dist.get_rank()} is {seed}, and seed on rank {rank} is {object}!",
+            )
+    # instantiate a RNG tracker if haven't. By default DTensor uses an
+    # OffsetBasedRNGTracker to perform random operators.
+    global _rng_tracker
+    if not _rng_tracker:
+        _rng_tracker = OffsetBasedRNGTracker(device_mesh.device_type)
+
+    # the current rank is in mesh
+    if device_mesh.get_coordinate() is not None:
+        if isinstance(_rng_tracker, TensorParallelRNGTracker):
+            _rng_tracker._manual_seed(device_mesh, seed)
+        elif isinstance(_rng_tracker, OffsetBasedRNGTracker):
+            _rng_tracker._manual_seed(seed)
+        else:
+            raise RuntimeError(
+                f"Unknown type of cuda RNG state tracker: _rng_tracker = {_rng_tracker}"
+            )
+
+
+class _RNGStateTracker:
+    """
+    _RNGStateTracker stores Random Number Generator (RNG) state (a ByteTensor object)
+    in a dict, mapping from a corresponding tag to each state tensor. It also provides
+    a set of convenient utility methods to help access/modify the state tensors. The most
+    important interface is _distribute_region which will be used when DTensor executes
+    a random op (an operator that calls RNG).
+    """
+
+    def __init__(self, device_type: str = "cuda"):
+        self._device_type = device_type
+        self._device_handle = _get_device_handle(device_type)
+        if not (self._device_handle and self._device_handle.is_available()):
+            raise RuntimeError(
+                f"{self.__class__.__name__} instantiation requires the presence of CUDA/CUDA-like device"
+            )
+
+        self._states: Dict[str, Tensor] = {}
+        self._devices = [self._device_handle.current_device()]
+        self._use_distribute_region = True
+
+    @property
+    def rng_states(self) -> Dict[str, Tensor]:
+        return self._states
+
+    @property
+    def distribute_region_enabled(self) -> bool:
+        return self._use_distribute_region
+
+    @distribute_region_enabled.setter
+    def distribute_region_enabled(self, value) -> None:
+        self._use_distribute_region = value
+
+    def rng_state_is_sync(self, name) -> bool:
+        return name in self.rng_states
+
+    def get_seed(self, name: str) -> int:
+        if name not in self.rng_states:
+            raise RuntimeError(
+                f"{self.__class__.__name__} does not have random state for {name}"
+            )
+
+        seed_tensor = (self.rng_states[name])[0:8].view(dtype=torch.int64)
+        return int(seed_tensor.item())
+
+    def set_seed(self, name: str, seed: int) -> None:
+        seed_tensor = torch.tensor([seed]).view(torch.uint8)
+        offset_tensor = torch.tensor([0]).view(torch.uint8)
+        self.rng_states[name] = torch.cat([seed_tensor, offset_tensor])
+
+    def _distribute_region(self, spec: DTensorSpec):
+        pass
+
+
+class OffsetBasedRNGTracker(_RNGStateTracker):
+    """
+    This subclass of ``_RNGStateTracker`` defines the default policy of how RNG states
+    should be shared and synchronized among all ranks to respect the semantics of DTensor
+    random operators.
+    """
+
+    def __init__(self, device_type: str = "cuda"):
+        super().__init__(device_type)
+        # synchronize RNG state using rank 0's current one
+        rng_state = self._device_handle.get_rng_state().to(device_type)
+        dist.broadcast(rng_state, 0)
+        self.rng_states["parallel-rng"] = rng_state.to("cpu")
+
+    def _manual_seed(self, parallel_seed: int) -> None:
+        self.set_seed("parallel-rng", parallel_seed)
+
+    @contextlib.contextmanager
+    def _distribute_region(self, spec: DTensorSpec):
+        # check if the parallel rng state has been synchronized or not
+        if not self.rng_state_is_sync("parallel-rng"):
+            raise RuntimeError(
+                "OffsetBasedRNGTracker requires the random state to be synchronized "
+                "before entering into a distribute region!"
+            )
+
+        if self.distribute_region_enabled:
+            old_offset = self.get_offset("parallel-rng")
+            self._set_pre_op_offset(spec)
+            with torch.random.fork_rng(self._devices, device_type=self._device_type):
+                self._device_handle.set_rng_state(self.rng_states["parallel-rng"])
+                try:
+                    yield  # execute the region code
+                finally:
+                    # update offset to synchronize among ranks
+                    self._set_post_op_offset(spec, old_offset)
+        else:
+            yield
+
+    def get_offset(self, name: str) -> int:
+        if name not in self.rng_states:
+            raise RuntimeError(
+                f"{self.__class__.__name__} does not have random state for {name}"
+            )
+
+        offset_tensor = (self.rng_states[name])[8:].view(dtype=torch.int64)
+        return int(offset_tensor.item())
+
+    def set_offset(self, name: str, offset: int) -> None:
+        if name not in self.rng_states:
+            raise RuntimeError(
+                f"{self.__class__.__name__} does not have random state for {name}"
+            )
+
+        seed_tensor = (self.rng_states[name])[0:8]
+        offset_tensor = torch.tensor([offset]).view(torch.uint8)
+        self.rng_states[name] = torch.cat([seed_tensor, offset_tensor])
+
+    def _set_pre_op_offset(self, spec: DTensorSpec) -> None:
+        """Set the starting RNG offset for current device's local shard before actual
+        op execution. The pre_op_offset value should start from the current RNG offset
+        and increment by the size of local shard until it reaches the size of the whole
+        DTensor. For different ranks that hold the same DTensor shard, their pre_op_offset
+        will be the same.
+
+        Args:
+            spec (:class:`DTensorSpec`): the spec of the DTensor object on which
+                we prepare the offset for running random ops.
+
+        Returns:
+            None
+
+        .. warning::
+            Note that, current implementation does not consider DTensor's continguity.
+
+        Example:
+            take a DTensor of shape [8, 16] as an example. Assume that the DTensor
+            is placed on a device mesh with placements ([Shard(1), Replicate(), Shard(0)]),
+            and the mesh is:
+                [[[0, 1], [2, 3]], [[4, 5], [6, 7]]]
+            ``spec.mesh.get_coordinate()`` provides the coordinate of the current rank
+            in the mesh. For example, the coordinate of rank 5 is (1, 0, 1).
+
+            Another concept to introduce besides rank coordinate is shard coordinate.
+            Each rank holds a local shard of the DTensor. In the example, the DTensor
+            is partitioned into 4 [4, 8] shards. The first shard has 2 replicas and
+            rank 0 (coord (0, 0, 0)) and rank 2 (coord (0, 1, 0)) have 1 replica each.
+            That being said, the local shard on rank 0 and rank 2 correspond to the same
+            shard of the DTensor. To denote each DTensor shard, we use a shard coordinate
+            (in the example, it will be a tuple (i, j) where shard (i, j) has the slice
+            DTensor[4 * i : 4 * (i + 1), 8 * j : 8 * (j + 1)], 0 <= i < 2, 0 <= j < 2).
+
+            Once we have rank coordinate and shard coordinate, we can calculate on each rank
+            what shard of the DTensor the rank holds, with the help of dim_map. The dim_map
+            of the above DTensor is [2, 0] so the shard coordinate of a rank with rank coord
+            (x, y, z) is simply (z, x) by taking(rank_coord[dim_map[0]],rank_coord[dim_map[1]]).
+            Following this calculation,
+            rank 0 and rank 2 holds the shard of coord (0, 0);
+            rank 1 and rank 3 holds the shard of coord (0, 1);
+            rank 4 and rank 6 holds the shard of coord (1, 0);
+            rank 5 and rank 7 holds the shard of coord (1, 1);
+
+            The last value to calculate before obtaining the starting offset is the shard linear index.
+            The starting offset for each rank will be its shard_linear_index * local_tensor_numel.
+        """
+        dtensor_shape = spec.shape
+        mesh = spec.mesh
+        dim_map = spec.dim_map
+
+        # Compute shard coordinate:
+        # The coordinate on each tensor dim is a tuple (idx, range)
+        # If a DTensor is partitioned on its dim i into n shards, and the current rank
+        # holds the j-th, then its shard coordinate will be (idx=j, range=n) on dim i
+        coordinate = mesh.get_coordinate()
+        assert coordinate is not None
+        shard_coord = [
+            coordinate[mesh_dim] if mesh_dim >= 0 else 0 for mesh_dim in dim_map
+        ]
+        shard_size = [
+            mesh.size(mesh_dim) if mesh_dim >= 0 else 1 for mesh_dim in dim_map
+        ]
+
+        # compute shard linear index
+        shard_linear_idx = self._calc_shard_linear_idx(shard_coord, shard_size)
+
+        # compute starting offset using the first shard's size
+        local_size_on_rank_0 = list(dtensor_shape)
+        for idx, placement in enumerate(spec.placements):
+            if isinstance(placement, Shard):
+                mesh_dim_size = mesh.size(idx)
+                shard_dim = placement.dim
+                local_size_on_rank_0[shard_dim] = placement._local_shard_size_on_dim(
+                    dtensor_shape[shard_dim],
+                    mesh_dim_size,
+                    0,
+                    return_offset=False,
+                )[0]
+
+        from torch.distributed.tensor._ops.utils import prod
+
+        local_size = prod(local_size_on_rank_0)
+
+        # get current RNG offset
+        current_offset = self.get_offset("parallel-rng")
+
+        # pytorch: offset must be multiple of 4
+        # source: aten/src/ATen/cuda/CUDAGeneratorImpl.cpp
+        offset_incr = (shard_linear_idx * local_size + 3) // 4 * 4
+        self.set_offset("parallel-rng", current_offset + offset_incr)
+
+    def _set_post_op_offset(self, spec: DTensorSpec, old_offset: int) -> None:
+        """Sets the RNG to a synchronized state after running the local random op. Every
+        rank should set its RNG offset to `old_offset + DTensor.numel()` where old_offset is
+        the offset before calling `set_pre_op_offset` i.e. the offset before running DTensor
+        random ops.
+
+        Args:
+            spec (:class:`DTensorSpec`): the spec of the DTensor object on which
+                we post-process the offset for running random ops.
+
+        Returns:
+            None
+        """
+        dtensor_shape = spec.shape
+
+        from torch.distributed.tensor._ops.utils import prod
+
+        numel = prod(dtensor_shape)
+        # pytorch: offset must be multiple of 4
+        # source: aten/src/ATen/cuda/CUDAGeneratorImpl.cpp
+        numel = (numel + 3) // 4 * 4
+        self.set_offset("parallel-rng", old_offset + numel)
+
+    def _calc_shard_linear_idx(
+        self, shard_coord: List[int], shard_size: List[int]
+    ) -> int:
+        # compute shard linear index
+        shard_linear_idx = 0
+        shard_coord_stride = 1
+        for idx, size in zip(reversed(shard_coord), reversed(shard_size)):
+            shard_linear_idx += idx * shard_coord_stride
+            shard_coord_stride *= size
+
+        return shard_linear_idx
+
+
+class TensorParallelRNGTracker(_RNGStateTracker):
+    def __init__(self, device_type: str = "cuda"):
+        super().__init__(device_type)
+        # copy the default RNG state
+        self.rng_states["tensor-parallel-rng"] = self._device_handle.get_rng_state()
+
+    def _manual_seed(
+        self,
+        tp_mesh: DeviceMesh,
+        base_seed: int = 1234,
+    ):
+        tensor_parallel_rank = tp_mesh.get_local_rank()
+        # this magic number 2718 comes from Megatron's code
+        # (https://github.com/NVIDIA/Megatron-LM/blob/060415572f4365a2e895f8036c4e37dad0efbdf5/megatron/core/tensor_parallel/random.py#L162-L163)
+        MegatronMagicNum = 2718
+        tensor_parallel_seed = base_seed + MegatronMagicNum + tensor_parallel_rank
+        self.set_seed("tensor-parallel-rng", tensor_parallel_seed)
+
+    @contextlib.contextmanager
+    def _distribute_region(self, spec: DTensorSpec):
+        # check if the tensor parallel rng state has been synchronized or not
+        if not self.rng_state_is_sync("tensor-parallel-rng"):
+            raise RuntimeError(
+                "TensorParallelRNGTracker requires the random state to be synchronized "
+                "before entering into a distribute region!"
+            )
+
+        if self.distribute_region_enabled:
+            with torch.random.fork_rng(self._devices, device_type=self._device_type):
+                self._device_handle.set_rng_state(
+                    self.rng_states["tensor-parallel-rng"]
+                )
+                try:
+                    yield
+                finally:
+                    self.rng_states[
+                        "tensor-parallel-rng"
+                    ] = self._device_handle.get_rng_state()
+        else:
+            yield
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_redistribute.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_redistribute.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b4e37e54744f4d5b909258b0351b42650c3a594
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_redistribute.py
@@ -0,0 +1,351 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and affiliates
+import logging
+from functools import lru_cache
+from typing import cast, List, NamedTuple, Tuple
+
+import torch
+import torch.distributed._functional_collectives as funcol
+import torch.distributed.tensor._api as dtensor
+from torch.distributed.tensor._dtensor_spec import DTensorSpec, TensorMeta
+from torch.distributed.tensor.device_mesh import DeviceMesh
+from torch.distributed.tensor.placement_types import (
+    Partial,
+    Placement,
+    Replicate,
+    Shard,
+)
+
+
+logger = logging.getLogger(__name__)
+
+
+class _TransformInfo(NamedTuple):
+    mesh_dim: int
+    src_dst_placements: Tuple[Placement, Placement]
+    # logical_shape on this mesh dimension
+    logical_shape: List[int]
+
+
+@lru_cache(maxsize=None)
+def _gen_transform_infos(
+    src_spec: DTensorSpec,
+    dst_spec: DTensorSpec,
+) -> List[_TransformInfo]:
+    """
+    Generate the transform infos from the source placements to the target placements.
+
+    To transform from source to target placement it might have multiple steps, i.e. it
+    might decompose Si -> Sj into Si -> R -> Sj.
+    This would detect if there're mis-aligned/nested shardings between src/dst placements.
+    E.g. Suppose the redistribution to perform is (Shard(0), Shard(0)) -> (Replicate(), Shard(0)),
+    in this case Shard(0) -> Shard(0) for mesh dimension 1 actually needs resharding, because in
+    the former is a nested-sharding of a tensor already already sharded dimension 0, whereras
+    the latter is the first sharding on tensor dimension 0.
+    """
+    transform_infos: List[_TransformInfo] = []
+
+    device_mesh = src_spec.device_mesh
+    my_coordinate = device_mesh.get_coordinate()
+    assert my_coordinate is not None
+
+    # logical shape records the logic tensor shape on the mesh dimension
+    # this is useful to ensure uneven sharding gets correct output shape
+    initial_logical_shape = list(src_spec.shape)
+    mesh_dims_to_logical_shape = [initial_logical_shape]
+
+    if device_mesh.ndim == 1:
+        # if device_mesh is 1D, redistribute is a simple direct transformation
+        transform_infos.append(
+            _TransformInfo(
+                mesh_dim=0,
+                src_dst_placements=(src_spec.placements[0], dst_spec.placements[0]),
+                logical_shape=initial_logical_shape,
+            )
+        )
+        return transform_infos
+
+    # Handle multi-dim device mesh placement redistribution
+    # First, we need to build the logical shape for each mesh dim
+    # for correct allgathering uneven shards on each mesh dim (with dynamic padding)
+    for i, (src, dst) in enumerate(zip(src_spec.placements, dst_spec.placements)):
+        current_logical_shape = mesh_dims_to_logical_shape[i]
+        if isinstance(src, Shard):
+            if i < device_mesh.ndim - 1:
+                # calculate and save the logical shape for this sharding
+                mesh_dim_size = device_mesh.size(mesh_dim=i)
+                local_shard_size, _ = src._local_shard_size_on_dim(
+                    current_logical_shape[src.dim],
+                    mesh_dim_size,
+                    my_coordinate[i],
+                )
+                new_logical_shape = list(current_logical_shape)
+                new_logical_shape[src.dim] = local_shard_size
+                mesh_dims_to_logical_shape.append(new_logical_shape)
+        else:
+            mesh_dims_to_logical_shape.append(current_logical_shape)
+
+    # Next, we need to derive the transform infos from src to dst placements,
+    # here we use a greedy search with step by step state transformations
+    current_placements = list(src_spec.placements)
+    target_placements = list(dst_spec.placements)
+
+    if src_spec.num_shards > 1:
+        # If src_spec have sharding, it could potentially have sharding that is misaligned with dst_spec
+        # a common case of this is nested sharding (i.e. (S(0), S(0)) -> (R, S(0))).
+        # In those cases, we first traverse from inner placement to outer placement
+        # to detect misaligned shardings and properly replicate nested sharding first.
+        for mesh_dim in reversed(range(len(current_placements))):
+            current = current_placements[mesh_dim]
+            target = target_placements[mesh_dim]
+            # If target is not Shard, we can directly redistribute since we are traversing from innner
+            # to outer placements here
+            if isinstance(target, Shard):
+                # If target is Shard, check for nested sharding on the tensor dim BEFORE the current mesh_dim
+                shard_dim = target.dim
+                current_mesh_sharding, target_mesh_sharding = [], []
+                for i, (s, p) in enumerate(zip(current_placements, target_placements)):
+                    if i >= mesh_dim:
+                        break
+                    if s.is_shard(shard_dim):
+                        current_mesh_sharding.append(i)
+                    if p.is_shard(shard_dim):
+                        target_mesh_sharding.append(i)
+
+                if current_mesh_sharding != target_mesh_sharding:
+                    # if current/target_placements have misaligned sharding on the tensor dim BEFORE the current
+                    # mesh_dim, we need to replicate the tensor on the mesh dim first to clear the nested sharding
+                    target = Replicate()
+
+            if current != target:
+                transform_infos.append(
+                    _TransformInfo(
+                        mesh_dim=mesh_dim,
+                        src_dst_placements=(current, target),
+                        logical_shape=mesh_dims_to_logical_shape[mesh_dim],
+                    )
+                )
+                current_placements[mesh_dim] = target
+
+    # We always traverse from outer placement to inner placement to collect the remaining
+    # needed transform infos (i.e. the replication from nested sharding might need to further
+    # perform resharding to Shard again)
+    for mesh_dim, (current, target) in enumerate(
+        zip(current_placements, target_placements)
+    ):
+        if current != target:
+            transform_infos.append(
+                _TransformInfo(
+                    mesh_dim=mesh_dim,
+                    src_dst_placements=(current, target),
+                    logical_shape=mesh_dims_to_logical_shape[mesh_dim],
+                )
+            )
+            current_placements[mesh_dim] = target
+
+    return transform_infos
+
+
+def redistribute_local_tensor(
+    local_tensor: torch.Tensor,
+    current_spec: DTensorSpec,
+    target_spec: DTensorSpec,
+    *,
+    async_op: bool = False,
+    is_backward: bool = False,
+) -> torch.Tensor:
+    """
+    This redistribute the local tensor (torch.Tensor) from the current DTensorSpec to
+    the target DTensorSpec, which involves the necessary collective calls to transform
+    the local shard of the DTensor from its current spec to the target spec.
+    """
+
+    if current_spec.mesh != target_spec.mesh:
+        # TODO: alltoall/permute reshuffling to change device_mesh if they are not the same
+        raise NotImplementedError("Cross device mesh comm not supported yet!")
+
+    new_local_tensor = None
+    device_mesh = current_spec.mesh
+
+    my_coordinate = device_mesh.get_coordinate()
+
+    if my_coordinate is None:
+        # if rank is not part of mesh, we skip redistribute and simply return local_tensor,
+        # which should be an empty tensor
+        return local_tensor
+
+    transform_infos = _gen_transform_infos(current_spec, target_spec)
+
+    for transform_info in transform_infos:
+        i = transform_info.mesh_dim
+        current, target = transform_info.src_dst_placements
+        num_chunks = device_mesh.size(mesh_dim=i)
+
+        if current == target:
+            # short cut, just use the original local tensor
+            new_local_tensor = local_tensor
+            continue
+
+        logger.debug("redistribute from %s to %s on mesh dim %s", current, target, i)
+
+        if target.is_replicate():
+            # Case 1: target is Replicate
+            if current.is_partial():
+                partial_spec = cast(Partial, current)
+                new_local_tensor = partial_spec._reduce_value(
+                    local_tensor, device_mesh, i
+                )
+            elif current.is_shard():
+                current_placement = cast(Shard, current)
+                new_local_tensor = current_placement._to_replicate_tensor(
+                    local_tensor, device_mesh, i, transform_info.logical_shape
+                )
+            else:
+                raise RuntimeError(
+                    f"redistribute from {current} to {target} not supported yet"
+                )
+        elif target.is_shard():
+            # Case 2: target is Shard
+            target_placement = cast(Shard, target)
+            target_dim = target_placement.dim
+            if current.is_partial():
+                partial_spec = cast(Partial, current)
+                new_local_tensor = partial_spec._reduce_shard_value(
+                    local_tensor, device_mesh, i, target_placement
+                )
+            elif current.is_replicate():
+                # split the tensor and return the corresponding cloned local shard
+                new_local_tensor = target_placement._replicate_to_shard(
+                    local_tensor, device_mesh, i, my_coordinate[i]
+                )
+            else:
+                assert (
+                    current.is_shard()
+                ), f"Current placement should be shard but found {current}"
+                shard_spec = cast(Shard, current)
+                if shard_spec.dim != target_placement.dim:
+                    new_local_tensor = shard_spec._to_new_shard_dim(
+                        local_tensor,
+                        device_mesh,
+                        i,
+                        transform_info.logical_shape,
+                        target_placement.dim,
+                    )
+        elif target.is_partial():
+            if current.is_replicate():
+                partial_spec = cast(Partial, target)
+                # skip the replicate to partial transformation when we are in backward pass
+                # In this case we keep the grad as replicate, this is because we don't
+                # want to convert the replicated gradients back to partial, although
+                # that's logically conform with the same layout, converting the gradients
+                # back to partial is actually useless as you would have to do reduce later
+                # which would be more expensive than keeping it replicate! For this reason,
+                # we keep the replicate grad here.
+                new_local_tensor = (
+                    partial_spec._partition_value(local_tensor, device_mesh, i)
+                    if not is_backward
+                    else local_tensor
+                )
+            elif current.is_shard():
+                if not is_backward:
+                    raise RuntimeError(
+                        f"redistribute from {current} to {target} not supported yet"
+                    )
+                # for backward shard -> partial, we just need to convert the shard to replicate
+                current_placement = cast(Shard, current)
+                new_local_tensor = current_placement._to_replicate_tensor(
+                    local_tensor, device_mesh, i, transform_info.logical_shape
+                )
+            else:
+                # partial -> partial no op, should never hit
+                new_local_tensor = local_tensor
+
+        assert new_local_tensor is not None
+        local_tensor = new_local_tensor
+
+    assert new_local_tensor is not None, "redistribute failed!"
+
+    if not async_op and isinstance(new_local_tensor, funcol.AsyncCollectiveTensor):
+        new_local_tensor = new_local_tensor.wait()
+
+    return new_local_tensor
+
+
+class Redistribute(torch.autograd.Function):
+    @staticmethod
+    def forward(  # type: ignore[override]
+        # pyre-fixme[2]: Parameter must be annotated.
+        ctx,
+        input: "dtensor.DTensor",
+        device_mesh: DeviceMesh,
+        placements: Tuple[Placement, ...],
+        async_op: bool = False,
+    ):
+        current_spec = input._spec
+        ctx.current_spec = current_spec
+        ctx.async_op = async_op
+
+        if current_spec.placements != placements:
+            target_spec = DTensorSpec(
+                device_mesh, placements, tensor_meta=input._spec.tensor_meta
+            )
+
+            local_tensor = input._local_tensor
+            output = redistribute_local_tensor(
+                local_tensor, current_spec, target_spec, async_op=async_op
+            )
+        else:
+            # use the same local tensor if placements are the same.
+            output = input._local_tensor
+            target_spec = current_spec
+
+        return dtensor.DTensor(
+            output,
+            target_spec,
+            requires_grad=input.requires_grad,
+        )
+
+    @staticmethod
+    def backward(ctx, grad_output: "dtensor.DTensor"):  # type: ignore[override]
+        previous_spec = ctx.current_spec
+        current_spec = grad_output._spec
+        async_op = ctx.async_op
+
+        local_tensor = grad_output._local_tensor
+        output = redistribute_local_tensor(
+            local_tensor,
+            current_spec,
+            previous_spec,
+            async_op=async_op,
+            is_backward=True,
+        )
+        # normalize the target placement to replicate if it is partial
+        normalized_placements: List[Placement] = []
+        for previous_placement in previous_spec.placements:
+            if previous_placement.is_partial():
+                # keep target placement to replicate instead of partial in this case
+                normalized_placements.append(Replicate())
+            else:
+                normalized_placements.append(previous_placement)
+
+        spec = DTensorSpec(
+            previous_spec.device_mesh,
+            tuple(normalized_placements),
+            tensor_meta=TensorMeta(
+                shape=grad_output.shape,
+                stride=grad_output.stride(),
+                dtype=grad_output.dtype,
+            ),
+        )
+        output_dtensor = dtensor.DTensor(
+            output,
+            spec,
+            requires_grad=grad_output.requires_grad,
+        )
+
+        return (
+            output_dtensor,
+            None,
+            None,
+            None,
+        )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_sharding_prop.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_sharding_prop.py
new file mode 100644
index 0000000000000000000000000000000000000000..c277655ff4bf0f0cec77d37956fc5f802125ae9b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_sharding_prop.py
@@ -0,0 +1,497 @@
+# mypy: allow-untyped-defs
+import threading
+from functools import lru_cache
+from itertools import chain
+from typing import Callable, cast, Dict, List, Optional, Sequence, Tuple, Union
+
+import torch
+from torch._ops import OpOverload
+from torch._subclasses import FakeTensorMode
+from torch.distributed.device_mesh import DeviceMesh
+from torch.distributed.tensor._dtensor_spec import DTensorSpec, TensorMeta
+from torch.distributed.tensor._op_schema import (
+    OpInfo,
+    OpSchema,
+    OpStrategy,
+    OutputSharding,
+    OutputSpecType,
+    PlacementStrategy,
+    RuntimeSchemaInfo,
+    StrategyType,
+    TupleStrategy,
+)
+from torch.distributed.tensor._utils import (
+    compute_local_shape,
+    compute_local_stride,
+    try_find_mesh_from_args,
+)
+
+
+aten = torch.ops.aten
+
+
+def _length(obj) -> int:
+    if obj is None:
+        return 0
+    if not isinstance(obj, Sequence):
+        return 1
+    return len(obj)
+
+
+class LocalLRUCache(threading.local):
+    def __init__(self, user_function: Callable) -> None:
+        self.cache = lru_cache(None)(user_function)
+
+    def __call__(self, *args, **kwargs) -> object:
+        return self.cache(*args, **kwargs)
+
+    def cache_info(self):
+        return self.cache.cache_info()
+
+
+class ShardingPropagator:
+    def __init__(self) -> None:
+        self.op_to_rules: Dict[OpOverload, Callable[[OpSchema], OutputSharding]] = {}
+        self.op_strategy_funcs: Dict[
+            OpOverload,
+            Callable[[DeviceMesh, OpSchema], StrategyType],
+        ] = {}
+        # op map to save static argnum to decide to reuse sharding prop cache or re-run sharding prop
+        self.op_to_schema_info: Dict[OpOverload, RuntimeSchemaInfo] = {}
+        self.propagate_op_sharding = LocalLRUCache(
+            self.propagate_op_sharding_non_cached
+        )
+        # op map to save indices of shape (and stride) args which may need to be modified in sharding prop
+        self.op_to_shape_and_stride_idx: Dict[
+            OpOverload, Union[int, Tuple[int, int]]
+        ] = {
+            # new factory ops
+            aten.new_empty.default: 1,
+            aten.new_full.default: 1,
+            aten.new_ones.default: 1,
+            aten.new_zeros.default: 1,
+            aten.new_empty_strided.default: (1, 2),
+            # view ops
+            aten.expand.default: 1,
+            aten.reshape.default: 1,
+            aten.view.default: 1,
+            aten._unsafe_view.default: 1,
+        }
+
+    def register_sharding_prop_rule(
+        self,
+        op_overload: OpOverload,
+        rule_func: Callable[[OpSchema], OutputSharding],
+        schema_info: Optional[RuntimeSchemaInfo] = None,
+    ):
+        """
+        Register a sharding propagation rule for an operator.
+        """
+        self.op_to_rules[op_overload] = rule_func
+        if schema_info is not None:
+            self.op_to_schema_info[op_overload] = schema_info
+
+    def register_op_strategy(
+        self,
+        op_overload: OpOverload,
+        strategy_func: Callable[[DeviceMesh, OpSchema], StrategyType],
+        schema_info: Optional[RuntimeSchemaInfo] = None,
+    ):
+        """
+        Register a sharding strategy generator for an operator.
+        """
+        self.op_strategy_funcs[op_overload] = strategy_func
+        if schema_info is not None:
+            self.op_to_schema_info[op_overload] = schema_info
+
+    @lru_cache  # noqa: B019
+    def _propagate_tensor_meta(
+        self, op_schema: OpSchema
+    ) -> Union[None, TensorMeta, Sequence[Optional[TensorMeta]]]:
+        """
+        Propagate the tensor metadata, it could either return a TensorMeta
+        or a list/tuple of TensorMetas
+        """
+        if op_schema.op == aten.equal.default:
+            # data dependent ops can't be used for fake propagation
+            return None
+
+        # NOTE: We must call the tracing in fake tensor mode so that it
+        # avoids materializing memory
+        with FakeTensorMode():
+            fake_args = op_schema.gen_fake_args()
+            fake_kwargs = op_schema.gen_fake_kwargs()
+            fake_out = op_schema.op(*fake_args, **fake_kwargs)
+
+        if isinstance(fake_out, torch.Tensor):
+            return TensorMeta(
+                shape=fake_out.shape, stride=fake_out.stride(), dtype=fake_out.dtype
+            )
+
+        elif isinstance(fake_out, (tuple, list)):
+            tensor_meta_list: List[Optional[TensorMeta]] = []
+            for fake_out_item in fake_out:
+                if isinstance(fake_out_item, torch.Tensor):
+                    tensor_meta_list.append(
+                        TensorMeta(
+                            shape=fake_out_item.shape,
+                            stride=fake_out_item.stride(),
+                            dtype=fake_out_item.dtype,
+                        )
+                    )
+                else:
+                    tensor_meta_list.append(None)
+            return (
+                tuple(tensor_meta_list)
+                if isinstance(fake_out, tuple)
+                else tensor_meta_list
+            )
+        else:
+            # if fake is not a tensor or tuple of tensor, return as none
+            return None
+
+    def _wrap_output_spec_tensor_meta(
+        self,
+        op: OpOverload,
+        output_specs: OutputSpecType,
+        output_tensor_meta: Union[None, TensorMeta, Sequence[Optional[TensorMeta]]],
+    ) -> None:
+        """
+        Wrap the output_specs with the tensor metadata from the output.
+        """
+
+        if isinstance(output_specs, DTensorSpec):
+            if not isinstance(output_tensor_meta, TensorMeta):
+                # Either error due to ShardingPropagator or due to incorrect OutputSpec
+                if not isinstance(output_tensor_meta, (tuple, list)):
+                    raise ValueError(
+                        "ShardingPropagator error: output does not have an associated TensorMeta"
+                    )
+                raise ValueError(
+                    f"For the op {op.name()}, `output_specs` has 1 output which does not equal the "
+                    f"number of op outputs: {len(output_tensor_meta)}."
+                )
+            output_specs.tensor_meta = output_tensor_meta
+        elif isinstance(output_specs, (tuple, list)):
+            if not isinstance(output_tensor_meta, (tuple, list)) or len(
+                output_specs
+            ) != len(output_tensor_meta):
+                raise ValueError(
+                    f"For the op {op.name()}, `output_specs` has {len(output_specs)} outputs which does not equal the "
+                    f"number of op outputs {_length(output_tensor_meta)}."
+                )
+            for i, spec in enumerate(output_specs):
+                if isinstance(spec, DTensorSpec):
+                    output_tensor_meta_i = output_tensor_meta[i]
+                    if not isinstance(output_tensor_meta_i, TensorMeta):
+                        raise ValueError(
+                            f"ShardingPropagator error: output {i} does not have an associated TensorMeta"
+                        )
+                    spec.tensor_meta = output_tensor_meta_i
+
+    def propagate(self, op_info: OpInfo) -> None:
+        # We cannot use an lru cache if we know that inputs will have dynamic shapes,
+        # because SymInts are not hashable.
+        # This is generally ok because this only happens during tracing in torch.compile,
+        # and tracing does not need to be as fast as eagermode DTensor usages.
+        if op_info.schema.has_symints:
+            output_sharding = self.propagate_op_sharding_non_cached(op_info.schema)
+        else:
+            output_sharding = cast(
+                OutputSharding, self.propagate_op_sharding(op_info.schema)
+            )
+        op_info.output_sharding = output_sharding
+
+    def propagate_op_sharding_non_cached(self, op_schema: OpSchema) -> OutputSharding:
+        """
+        Propagate the sharding for an operator given the op_schema.
+        """
+        # special case op, we don't need to propagate for local
+        # scalar. TODO: figure out a better way to handle this
+        if op_schema.op is aten._local_scalar_dense.default:
+            return OutputSharding(None, op_schema)
+
+        out_tensor_meta = self._propagate_tensor_meta(op_schema)
+
+        def spec_to_strategy(spec: object) -> object:
+            if isinstance(spec, DTensorSpec):
+                return OpStrategy([PlacementStrategy(spec)])
+            elif (
+                isinstance(spec, (list, tuple))
+                and len(spec) > 0
+                and isinstance(spec[0], DTensorSpec)
+            ):
+                # tensor list create tuple strategy
+                tuple_strategy = [spec_to_strategy(s) for s in spec]
+                tuple_strategy = cast(Sequence[StrategyType], tuple_strategy)
+                return TupleStrategy(
+                    tuple(tuple_strategy) if isinstance(spec, tuple) else tuple_strategy
+                )
+            else:
+                return spec
+
+        if op_schema.op in self.op_strategy_funcs:
+            # generate op strategy for the op.
+            mesh = try_find_mesh_from_args(op_schema.op, op_schema.args_schema)
+            # swap the args spec with args strategies
+            args_op_strategy = [spec_to_strategy(i) for i in op_schema.args_schema]
+
+            kwargs_op_strategy = {
+                k: spec_to_strategy(v) for k, v in op_schema.kwargs_schema.items()
+            }
+
+            # construct a new OpSchema on args for strategy based propagation
+            strategy_schema: OpSchema = OpSchema(
+                op=op_schema.op,
+                args_schema=tuple(args_op_strategy),
+                kwargs_schema=kwargs_op_strategy,
+            )
+
+            op_strategy = self.op_strategy_funcs[op_schema.op](mesh, strategy_schema)
+
+            if isinstance(op_strategy, OpStrategy):
+                # single Op strategy
+                output_strategy = self._select_strategy(op_strategy)
+
+                # check if we need to redistribute the input
+                needs_redistribute = False
+                expected_input_specs: List[DTensorSpec] = []
+
+                # in case where the op does not specify input_specs and output_specs
+                # is a DTensorSpec, we use output_specs as the spec for each DTensor
+                # input arg.
+                if output_strategy.input_specs is None:
+                    assert isinstance(output_strategy.output_specs, DTensorSpec)
+
+                for idx, input_spec in enumerate(op_schema.args_spec):
+                    desired_spec = (
+                        output_strategy.output_spec
+                        if output_strategy.input_specs is None
+                        else output_strategy.input_specs[idx]
+                    )
+                    expected_input_specs.append(
+                        desired_spec.shallow_copy_with_tensor_meta(
+                            input_spec.tensor_meta
+                        )
+                    )
+                    if input_spec.placements != desired_spec.placements:
+                        needs_redistribute = True
+
+                suggestion_schema = None
+                if needs_redistribute:
+                    suggestion_schema = OpSchema(
+                        op_schema.op, tuple(expected_input_specs), {}
+                    )
+                    suggestion_schema._inplace_rewrap_schema_suggestion(op_schema)
+
+                # shape and stride args need to be modified for
+                # view ops and new factory ops, potentially
+                if op_schema.op in self.op_to_shape_and_stride_idx:
+                    assert isinstance(output_strategy.output_spec, DTensorSpec)
+                    # It happens when the output has the same shape as the input
+                    # and the input placements are not all Replicate().
+                    if output_strategy.output_spec.is_sharded():
+                        schema = suggestion_schema or op_schema
+                        assert isinstance(out_tensor_meta, TensorMeta)
+                        suggestion_schema = self._adjust_shape_and_stride_args(
+                            out_tensor_meta, schema, output_strategy.output_spec, mesh
+                        )
+                        needs_redistribute = True
+
+                # construct output spec for the op
+                if op_schema.return_type_tuple_tensor_like():
+                    # for ops that return multiple tensors and the output_specs is not
+                    # a tuple, we use a tuple of that single output spec as the new
+                    # output_specs
+                    output_specs: OutputSpecType = output_strategy.output_specs
+                    if isinstance(output_specs, DTensorSpec):
+                        output_specs = tuple(
+                            [
+                                # create a new DTensorSpec with the same placement as the
+                                # output_specs in output_strategy
+                                DTensorSpec(
+                                    mesh=output_specs.mesh,
+                                    placements=output_specs.placements,
+                                    tensor_meta=output_specs.tensor_meta,
+                                )
+                                for _ in range(len(op_schema.op._schema.returns))
+                            ]
+                        )
+                elif op_schema.return_type_tensor():
+                    output_specs = output_strategy.output_specs
+                else:
+                    output_specs = None
+
+                output_sharding = OutputSharding(
+                    output_specs,
+                    suggestion_schema,
+                    needs_redistribute=needs_redistribute,
+                )
+            elif isinstance(op_strategy, TupleStrategy):
+                # tuple strategy output sharding processing
+                # runtime selected placement strategy for each TupleStrategy input arg
+                selected_strategies: List[PlacementStrategy] = []
+                out_spec_list: List[DTensorSpec] = []
+                for strategy in op_strategy.childs:
+                    assert isinstance(strategy, OpStrategy)
+                    selected_strategy = self._select_strategy(strategy)
+                    selected_strategies.append(selected_strategy)
+                    out_spec_list.append(selected_strategy.output_spec)
+
+                needs_redistribute = False
+                suggestion_args: List[object] = []
+                tensor_or_list_tensor_arg_idx = 0
+
+                for arg in op_schema.args_schema:
+                    if (
+                        arg
+                        and isinstance(arg, (list, tuple))
+                        and isinstance(arg[0], DTensorSpec)
+                    ):
+                        expected_input_spec_list: List[DTensorSpec] = []
+                        for idx, arg_spec in enumerate(arg):
+                            expected_input_spec = selected_strategies[idx].input_spec(
+                                tensor_or_list_tensor_arg_idx
+                            )
+                            expected_input_spec = (
+                                expected_input_spec.shallow_copy_with_tensor_meta(
+                                    arg_spec.tensor_meta
+                                )
+                            )
+                            if arg_spec.placements != expected_input_spec.placements:
+                                needs_redistribute = True
+                            expected_input_spec_list.append(expected_input_spec)
+                        suggestion_args.append(
+                            tuple(expected_input_spec_list)
+                            if isinstance(arg, tuple)
+                            else expected_input_spec_list
+                        )
+                        tensor_or_list_tensor_arg_idx += 1
+
+                    elif isinstance(arg, DTensorSpec):
+                        expected_input_spec = selected_strategies[0].input_spec(
+                            tensor_or_list_tensor_arg_idx
+                        )
+                        expected_input_spec = (
+                            expected_input_spec.shallow_copy_with_tensor_meta(
+                                arg.tensor_meta
+                            )
+                        )
+                        if arg.placements != expected_input_spec.placements:
+                            needs_redistribute = True
+                        suggestion_args.append(expected_input_spec)
+                        tensor_or_list_tensor_arg_idx += 1
+                    else:
+                        suggestion_args.append(arg)
+
+                suggestion_schema = None
+                if needs_redistribute:
+                    suggestion_schema = OpSchema(
+                        op_schema.op, tuple(suggestion_args), op_schema.kwargs_schema
+                    )
+
+                output_sharding = OutputSharding(
+                    tuple(out_spec_list) if out_tensor_meta is not None else None,
+                    suggestion_schema,
+                    needs_redistribute=needs_redistribute,
+                )
+            else:
+                raise ValueError("Unsupported op strategy type")
+
+            # associate the output sharding with the output tensor metadata
+            self._wrap_output_spec_tensor_meta(
+                op_schema.op, output_sharding.output_spec, out_tensor_meta
+            )
+            return output_sharding
+        elif op_schema.op in self.op_to_rules:
+            # propagate the sharding with rule
+            sharding_prop_func = self.op_to_rules[op_schema.op]
+
+            # step 1. there's sharding propagation rule, run
+            # sharding propagation to get the output sharding
+            try:
+                output_sharding = sharding_prop_func(op_schema)
+            except NotImplementedError as e:
+                raise e
+            except Exception as e:
+                raise RuntimeError(
+                    f"Sharding propagation failed on op {op_schema}.\n" f"Error: {e}"
+                ) from e
+
+            # step 2. if can't get output_spec from sharding
+            # propagation (i.e. no rules apply for input
+            # placements), we return the output sharding
+            # with schema suggestions, which can be used to
+            # decide how to do redistribute on inputs
+            if output_sharding.output_spec is None:
+                if output_sharding.redistribute_schema is None:
+                    raise RuntimeError(
+                        f"Sharding propagation failed on op {op_schema}!"
+                    )
+                else:
+                    # we do auto redistribute on inputs if necessary
+                    # run sharding propagation again with suggested schema
+                    propagation_res = sharding_prop_func(
+                        output_sharding.redistribute_schema
+                    )
+                    # we set the output sharding with the new propagation result
+                    # so that dispatching know both output_spec and redistribute_schema
+                    # exist, which indicates a reshard is needed
+                    output_sharding.output_spec = propagation_res.output_spec
+                    output_sharding.needs_redistribute = True
+
+            # associate the output sharding with the output tensor metadata
+            self._wrap_output_spec_tensor_meta(
+                op_schema.op, output_sharding.output_spec, out_tensor_meta
+            )
+
+            return output_sharding
+        else:
+            raise NotImplementedError(
+                f"Operator {op_schema.op} does not have a sharding strategy registered."
+            )
+
+    def _select_strategy(self, strategy: OpStrategy) -> PlacementStrategy:
+        if len(strategy.strategies) == 1:
+            # short cut with only one possible strategy
+            return strategy.strategies[0]
+
+        strategy_costs: List[float] = []
+        for strtg in strategy.strategies:
+            assert (
+                strtg.redistribute_cost is not None
+            ), "must set redistribute cost each strategy!"
+            redistribute_cost = sum(chain.from_iterable(strtg.redistribute_cost))
+            strategy_costs.append(redistribute_cost)
+
+        # for eager execution, we just select the one with the minimal redistribute cost
+        return strategy.strategies[strategy_costs.index(min(strategy_costs))]
+
+    def _adjust_shape_and_stride_args(
+        self,
+        out_tensor_meta: TensorMeta,
+        schema: OpSchema,
+        spec: DTensorSpec,
+        mesh: DeviceMesh,
+    ) -> OpSchema:
+        shape_stride_idx = self.op_to_shape_and_stride_idx[schema.op]
+        if isinstance(shape_stride_idx, tuple):
+            shape_idx, stride_idx = shape_stride_idx
+        else:
+            shape_idx = shape_stride_idx
+            stride_idx = None
+
+        expected_input_schema = list(schema.args_schema)
+        # adjust shape to be the same as that of the _local_tensor
+        # of the DTensor input arg at index 0, which is inferred
+        expected_input_schema[shape_idx] = compute_local_shape(
+            out_tensor_meta.shape, mesh, spec.placements
+        )
+
+        # adjust the stride arg for aten.new_empty_strided.default
+        if stride_idx:
+            expected_input_schema[stride_idx] = compute_local_stride(
+                out_tensor_meta.stride, mesh, spec.placements
+            )
+
+        return OpSchema(schema.op, tuple(expected_input_schema), schema.kwargs_schema)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_shards_wrapper.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_shards_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..de396473b77c91eef0b97e17b555f192c709e022
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_shards_wrapper.py
@@ -0,0 +1,316 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+from typing import Any, List, Tuple
+
+import torch
+from torch.distributed.checkpoint.metadata import (
+    ChunkStorageMetadata,
+    MetadataIndex,
+    TensorProperties,
+    TensorStorageMetadata,
+)
+from torch.distributed.checkpoint.planner import (
+    TensorWriteData,
+    WriteItem,
+    WriteItemType,
+)
+
+
+aten = (
+    torch.ops.aten
+)  # pyre-ignore[5]: Globally accessible variable `aten` has no type specified.
+
+
+class LocalShardsWrapper(torch.Tensor):  # pyre-ignore[13]: pyre is bad at __new__
+    """
+    A wrapper class to hold local shards of a DTensor.
+    This class is used largely for checkpointing purposes and implicity subtypes
+    the _Checkpointable protocol.
+    """
+
+    __slots__ = ["_local_shards", "_storage_meta"]
+    _local_shards: List[torch.Tensor]
+    _storage_meta: TensorStorageMetadata
+
+    @staticmethod
+    def __new__(
+        cls, local_shards: List[torch.Tensor], local_offsets: List[Tuple[int, ...]]
+    ) -> "LocalShardsWrapper":
+        assert len(local_shards) > 0
+        assert len(local_shards) == len(local_offsets)
+        assert all(
+            tensor.device == local_shards[0].device for tensor in local_shards[1:]
+        )
+
+        # we calculate the total tensor size by "concat" on second tensor dimension
+        cat_tensor_shape = list(local_shards[0].size())
+        if len(local_shards) > 1:  # column-wise sharding
+            for shard in local_shards[1:]:
+                cat_tensor_shape[1] += shard.size()[1]
+
+        wrapper_properties = TensorProperties.create_from_tensor(local_shards[0])
+        wrapper_shape = torch.Size(cat_tensor_shape)
+        chunks_meta = [
+            ChunkStorageMetadata(
+                offsets=torch.Size(offset),
+                sizes=shard.size(),
+            )
+            for shard, offset in zip(local_shards, local_offsets)
+        ]
+
+        r = torch.Tensor._make_wrapper_subclass(  # type: ignore[attr-defined]
+            cls,
+            torch.Size(cat_tensor_shape),
+        )
+        r._local_shards = local_shards
+        r._storage_meta = TensorStorageMetadata(
+            properties=wrapper_properties,
+            size=wrapper_shape,
+            chunks=chunks_meta,
+        )
+
+        return r
+
+    # necessary for ops dispatching from this subclass to its local shards
+    @classmethod
+    # pyre-fixme[3]: Return type must be annotated.
+    # pyre-fixme[2]: Parameter must be annotated.
+    def __torch_dispatch__(cls, func, types, args=(), kwargs=None):
+        kwargs = kwargs or {}
+
+        dispatcher = {
+            torch.ops._c10d_functional.all_gather_into_tensor.default: cls.handle_all_gather_into_tensor,
+            torch.ops._c10d_functional.wait_tensor.default: cls.handle_wait_tensor,
+            aten._to_copy.default: cls.handle_to_copy,
+            aten.view.default: cls.handle_view,
+            aten.equal.default: cls.handle_equal,
+            aten.detach.default: cls.handle_detach,
+            aten.clone.default: cls.handle_clone,
+        }
+
+        if func in dispatcher:
+            return dispatcher[func](
+                args, kwargs
+            )  # pyre-ignore [29] - `Variable[_VT]` is not a function.
+        else:
+            raise NotImplementedError(
+                f"{func} is not supported for LocalShardsWrapper!"
+            )
+
+    @staticmethod
+    # pyre-fixme[3]: Return type must be annotated.
+    # pyre-fixme[2]: Parameter must be annotated.
+    def handle_all_gather_into_tensor(args, kwargs):
+        dim = args[0].local_sizes()[0][1]
+        cat_tensor = torch.cat(
+            [t.view(-1) for t in args[0].local_shards()], dim=0
+        ).view(-1, dim)
+        return torch.ops._c10d_functional.all_gather_into_tensor.default(
+            cat_tensor, *args[1:], **kwargs
+        )
+
+    @staticmethod
+    # pyre-fixme[3]: Return type must be annotated.
+    # pyre-fixme[2]: Parameter must be annotated.
+    def handle_wait_tensor(args, kwargs):
+        return torch.ops._c10d_functional.wait_tensor(args[0])
+
+    @staticmethod
+    # pyre-fixme[3]: Return type must be annotated.
+    # pyre-fixme[2]: Parameter must be annotated.
+    def handle_to_copy(args, kwargs):
+        res_shards_list = [
+            aten._to_copy.default(shard, *args[1:], **kwargs)
+            for shard in args[0].local_shards()
+        ]
+        return LocalShardsWrapper(res_shards_list, args[0].local_offsets())
+
+    @staticmethod
+    # pyre-fixme[3]: Return type must be annotated.
+    # pyre-fixme[2]: Parameter must be annotated.
+    def handle_view(args, kwargs):
+        # TODO, do we need to change the shape of associated offsets?
+        res_shards_list = [
+            aten.view.default(shard, args[1], **kwargs)
+            for shard in args[0].local_shards()
+        ]
+        return LocalShardsWrapper(res_shards_list, args[0].local_offsets())
+
+    @staticmethod
+    # pyre-fixme[3]: Return type must be annotated.
+    # pyre-fixme[2]: Parameter must be annotated.
+    def handle_equal(args, kwargs):
+        """
+        LocalShardsWrapper equal impl also checks for equality of storage metadata
+        and the order of shards
+        """
+        a, b = args[0], args[1]
+        if len(a.local_shards()) != len(b.local_shards()):
+            return False
+        if not all(
+            aten.equal.default(x, y) for x, y in zip(a.local_shards(), b.local_shards())
+        ):
+            return False
+        if not a.storage_metadata() == b.storage_metadata():
+            return False
+        return True
+
+    @staticmethod
+    # pyre-fixme[3]: Return type must be annotated.
+    # pyre-fixme[2]: Parameter must be annotated.
+    def handle_detach(args, kwargs):
+        self_ls = args[0]
+        deatched_local_shards = [
+            aten.detach.default(shard) for shard in self_ls.local_shards()
+        ]
+        self_ls._local_shards = deatched_local_shards
+        self_ls._storage_meta.properties.requires_grad = False
+        return self_ls
+
+    @staticmethod
+    # pyre-fixme[3]: Return type must be annotated.
+    # pyre-fixme[2]: Parameter must be annotated.
+    def handle_clone(args, kwargs):
+        self_ls = args[0]
+        desired_memory_format = kwargs.get("memory_format", None)
+        if desired_memory_format and desired_memory_format != torch.preserve_format:
+            raise NotImplementedError(
+                f"{desired_memory_format} is not supported for LocalShardsWrapper!"
+            )
+        cloned_local_shards = [
+            shard.clone(memory_format=desired_memory_format)
+            for shard in self_ls._local_shards
+        ]
+        return LocalShardsWrapper(cloned_local_shards, self_ls.local_offsets())
+
+    @property
+    def device(self) -> torch._C.device:  # type: ignore[override]
+        return self._local_shards[0].device
+
+    @property
+    def is_meta(self) -> bool:  # type: ignore[override]
+        return self._local_shards[0].is_meta
+
+    # pyre-ignore[14]
+    def is_pinned(self) -> bool:  # type: ignore[override]
+        return self._storage_meta.properties.pin_memory
+
+    # pyre-ignore[14]
+    def requires_grad_(self, requires_grad: bool = True) -> "LocalShardsWrapper":
+        self._storage_meta.properties.requires_grad = requires_grad
+        [shard.requires_grad_(requires_grad) for shard in self._local_shards]
+        return self
+
+    def local_shards(self) -> List[torch.Tensor]:
+        """
+        Returns a list of :class:`torch.Tensor' corresponding to the
+        local shards for this rank. Returns an empty list if the current rank
+        does not host any shards for this Tensor.
+        """
+        return self._local_shards
+
+    def local_sizes(self) -> List[torch.Size]:
+        """
+        Returns a list of :class:`torch.Size' corresponding to the
+        local sizes for the shards on this rank. Returns an empty list if the current rank
+        does not host any shards for this Tensor.
+        """
+        return [chunk.sizes for chunk in self._storage_meta.chunks]
+
+    def local_offsets(self) -> List[torch.Size]:
+        """
+        Returns a list of :class:`torch.Size' corresponding to the
+        local offsets for the shards on this rank. Returns an empty list if the current rank
+        does not host any shards for this Tensor.
+        """
+        return [chunk.offsets for chunk in self._storage_meta.chunks]
+
+    @property
+    def local_chunks(self) -> List[ChunkStorageMetadata]:
+        """
+        Returns a :class:`List[ChunkStorageMetadata]` object corresponding to the
+        metadata for each tensor shard
+        """
+        return self._storage_meta.chunks
+
+    def storage_metadata(self) -> TensorStorageMetadata:
+        """
+        Returns a :class:`TensorStorageMetadata` object corresponding to the
+        metadata for the local tensor on current rank
+        """
+        return self._storage_meta
+
+    def __create_write_items__(
+        self, fqn: str, object: Any
+    ) -> List[WriteItem]:  # pyre-ignore[2]
+        """
+        For compatibility with DCP, we support creation of WriteItems
+        such that they can be saved properly.
+        """
+        return [
+            WriteItem(
+                index=MetadataIndex(fqn, chunks.offsets),
+                type=WriteItemType.SHARD,
+                tensor_data=TensorWriteData(
+                    chunk=ChunkStorageMetadata(
+                        offsets=chunks.offsets,
+                        sizes=chunks.sizes,
+                    ),
+                    properties=self._storage_meta.properties,
+                    size=object.size(),
+                ),
+            )
+            for tensor, chunks in zip(self.local_shards(), self.local_chunks)
+        ]
+
+    def __create_chunk_list__(self) -> List[ChunkStorageMetadata]:
+        """
+        For compatibility with DCP, we support creation of chunk lists
+        such that they can be saved properly.
+        """
+        return self._storage_meta.chunks
+
+    def __get_tensor_shard__(self, index: MetadataIndex) -> torch.Tensor:
+        """
+        For compatibility with DCP, we support finding shard based on index
+        Return a 'torch.Tensor' shard based on 'MetadataIndex'.
+        """
+        # Fast lookup path
+        if index.index is not None:
+            if (
+                len(self._local_shards) > index.index
+                and self._storage_meta.chunks[index.index].offsets == index.offset
+            ):
+                return self._local_shards[index.index]
+
+        if index.offset is not None:
+            for shard, chunk in zip(self._local_shards, self._storage_meta.chunks):
+                if chunk.offsets == index.offset:
+                    return shard
+
+        raise ValueError(
+            f"Could not find shard at '{index.offset}' for FQN: '{index.fqn}'"
+        )
+
+    def _get_tensor_size_bytes(self) -> int:
+        object_size = 0
+        for shard in self.local_shards():
+            object_size += shard.nelement() * shard.element_size()
+        return object_size
+
+    # pyre-fixme[3]: Return type must be annotated.
+    def __hash__(self):
+        return id(self)
+
+    # pyre-fixme[14]: `__repr__` overrides method defined in `torch._tensor.Tensor` inconsistently.
+    # pyre-fixme[3]: Return type must be annotated.
+    def __repr__(self):
+        return f"LocalShardsWrapper:{self._local_shards} {self._storage_meta}"
+
+    def __str__(self) -> str:
+        return f"LocalShardsWrapper:{self._local_shards} {self._storage_meta}"
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_tp_conv.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_tp_conv.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac11ef2162cbb7f80eecc3914d46ce3d3d5c1852
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_tp_conv.py
@@ -0,0 +1,279 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and affiliates
+# implement matrix related ops for distributed tensor
+from typing import cast, Dict, List, Tuple
+
+import torch
+import torch.distributed as dist
+import torch.distributed.tensor._api as dtensor
+
+
+aten = torch.ops.aten
+
+
+def _requires_data_exchange(padding):
+    # TODO: whether there requires data exchange is currently determined by padding
+    return padding[1] != 0
+
+
+def _is_supported(input_size, kernel_size, stride, padding, dilation):
+    if dilation[1] != 1:
+        raise RuntimeError("Dilation must be 1 for tensor parallel convolution.")
+    if padding[1] != 0:
+        if stride[1] != 1:
+            raise RuntimeError(
+                "Stride must be 1 when there is padding for tensor parallel convolution."
+            )
+        if kernel_size[3] // 2 > input_size[3]:
+            raise RuntimeError(
+                "kernel_size[3] // 2 should be less than or equal to input_size[3] for tensor parallel convolution."
+            )
+    else:
+        if not (input_size[3] % stride[1] == 0 and stride[1] == kernel_size[3]):
+            raise RuntimeError(
+                "It requires that input_size[3] is divisible by stride[1] and stride[1] equals kernel_size[3] "
+                "when there is padding for tensor parallel convolution."
+            )
+    return True
+
+
+def _ring_send_recv_construct(in_tensor, d1, d2, left, right, rank, size):
+    # dist comms and reconstruct local input tensor
+    send_to_right = in_tensor[:, :, :, -d1:].contiguous()
+    send_to_left = in_tensor[:, :, :, :d2].contiguous()
+    recv_from_right = torch.zeros_like(send_to_left)
+    recv_from_left = torch.zeros_like(send_to_right)
+
+    send_op_right = dist.P2POp(dist.isend, send_to_right, right)
+    send_op_left = dist.P2POp(dist.isend, send_to_left, left)
+    recv_op_right = dist.P2POp(dist.irecv, recv_from_right, right)
+    recv_op_left = dist.P2POp(dist.irecv, recv_from_left, left)
+
+    reqs = dist.batch_isend_irecv(
+        [send_op_right, send_op_left, recv_op_left, recv_op_right]
+    )
+    for req in reqs:
+        req.wait()
+
+    if rank == 0:
+        in_tensor = torch.cat([in_tensor, recv_from_right], dim=-1)
+    elif rank == size - 1:
+        in_tensor = torch.cat([recv_from_left, in_tensor], dim=-1)
+    else:
+        in_tensor = torch.cat([recv_from_left, in_tensor, recv_from_right], dim=-1)
+
+    return in_tensor
+
+
+def _ring_send_recv_aggregate(grad_in_tensor, d1, d2, left, right, rank, size):
+    # dist comms and aggregate gradients for edge pixels
+    send_to_right = grad_in_tensor[:, :, :, -d2:].contiguous()
+    send_to_left = grad_in_tensor[:, :, :, :d1].contiguous()
+    recv_from_right = torch.zeros_like(send_to_left)
+    recv_from_left = torch.zeros_like(send_to_right)
+
+    send_op_right = dist.P2POp(dist.isend, send_to_right, right)
+    send_op_left = dist.P2POp(dist.isend, send_to_left, left)
+    recv_op_right = dist.P2POp(dist.irecv, recv_from_right, right)
+    recv_op_left = dist.P2POp(dist.irecv, recv_from_left, left)
+
+    reqs = dist.batch_isend_irecv(
+        [send_op_right, send_op_left, recv_op_left, recv_op_right]
+    )
+    for req in reqs:
+        req.wait()
+
+    if rank == 0:
+        grad_in_tensor = grad_in_tensor[:, :, :, :-d2]
+        grad_in_tensor[:, :, :, -d1:] = torch.add(
+            grad_in_tensor[:, :, :, -d1:], recv_from_right
+        )
+    elif rank == size - 1:
+        grad_in_tensor = grad_in_tensor[:, :, :, d1:]
+        grad_in_tensor[:, :, :, :d2] = torch.add(
+            grad_in_tensor[:, :, :, :d2], recv_from_left
+        )
+    else:
+        grad_in_tensor = grad_in_tensor[:, :, :, d1:-d2]
+        grad_in_tensor[:, :, :, -d1:] = torch.add(
+            grad_in_tensor[:, :, :, -d1:], recv_from_right
+        )
+        grad_in_tensor[:, :, :, :d2] = torch.add(
+            grad_in_tensor[:, :, :, :d2], recv_from_left
+        )
+
+
+def tp_convolution(
+    op_call: torch._ops.OpOverload,
+    local_tensor_args: Tuple[object, ...],
+    local_tensor_kwargs: Dict[str, object],
+) -> object:
+    assert op_call == aten.convolution.default
+    assert len(local_tensor_args) == 9
+
+    rank = dist.get_rank()
+    size = dist.get_world_size()
+    in_tensor = cast(torch.Tensor, local_tensor_args[0])
+    weight = cast(torch.Tensor, local_tensor_args[1])
+    stride, padding, dilation = local_tensor_args[3:6]
+
+    assert _is_supported(in_tensor.shape, weight.shape, stride, padding, dilation)
+    assert isinstance(padding, List)
+
+    if not _requires_data_exchange(padding):
+        local_results = op_call(*local_tensor_args, **local_tensor_kwargs)
+        return local_results
+    else:
+        # step 0 compute the overlap pixels of the input tensor
+        d = weight.shape[3] - 1
+        d1 = d // 2
+        d2 = d - d1
+        assert d1 + d2 == d
+        right = (rank + 1) % size
+        left = (rank - 1 + size) % size
+
+        # step1 reconstruct local input tensor
+        in_tensor = _ring_send_recv_construct(
+            in_tensor, d1, d2, left, right, rank, size
+        )
+
+        # step2 feed local input tensor to op_call
+        local_tensor_args_list = list(local_tensor_args)
+        local_tensor_args_list[0] = in_tensor
+        local_tensor_args = cast(Tuple[object, ...], local_tensor_args_list)
+        local_results = op_call(*local_tensor_args, **local_tensor_kwargs)
+
+        # step3 remove extra outputs from the results
+        padding_w = padding[1]
+        w = local_results.size(3)
+        if rank == 0:
+            local_results = local_results[:, :, :, : w - padding_w]
+        elif rank == size - 1:
+            local_results = local_results[:, :, :, padding_w:]
+        else:
+            local_results = local_results[:, :, :, padding_w : w - padding_w]
+
+        return local_results
+
+
+def tp_convolution_backward(
+    op_call: torch._ops.OpOverload,
+    local_tensor_args: Tuple[object, ...],
+    local_tensor_kwargs: Dict[str, object],
+) -> object:
+    assert op_call == aten.convolution_backward.default
+    assert len(local_tensor_args) == 11
+
+    rank = dist.get_rank()
+    size = dist.get_world_size()
+    grad_out_tensor = cast(torch.Tensor, local_tensor_args[0])
+    in_tensor = cast(torch.Tensor, local_tensor_args[1])
+    weight = cast(torch.Tensor, local_tensor_args[2])
+    stride, padding, dilation = local_tensor_args[4:7]
+
+    assert _is_supported(in_tensor.shape, weight.shape, stride, padding, dilation)
+    assert isinstance(padding, List)
+
+    if not _requires_data_exchange(padding):
+        local_results = op_call(*local_tensor_args, **local_tensor_kwargs)
+        return local_results
+    else:
+        # step 0 compute the overlap pixels of the input tensor
+        d = weight.shape[3] - 1
+        d1 = d // 2
+        d2 = d - d1
+        assert d1 + d2 == d
+        right = (rank + 1) % size
+        left = (rank - 1 + size) % size
+
+        # step1 reconstruct local input tensor
+        in_tensor = _ring_send_recv_construct(
+            in_tensor, d1, d2, left, right, rank, size
+        )
+
+        # step2 reconstruct local gradient output tensor
+        N, C_out, H_out, _ = grad_out_tensor.shape
+        padding_w = padding[1]
+        if rank == 0:
+            grad_out_tensor = torch.nn.functional.pad(
+                grad_out_tensor, (0, padding_w), "constant", 0
+            )
+        elif rank == size - 1:
+            grad_out_tensor = torch.nn.functional.pad(
+                grad_out_tensor, (padding_w, 0), "constant", 0
+            )
+        else:
+            grad_out_tensor = torch.nn.functional.pad(
+                grad_out_tensor, (padding_w, padding_w), "constant", 0
+            )
+
+        # step3 feed local input tensor to op_call
+        local_tensor_args_list = list(local_tensor_args)
+        local_tensor_args_list[0] = grad_out_tensor
+        local_tensor_args_list[1] = in_tensor
+        local_tensor_args = cast(Tuple[object, ...], local_tensor_args_list)
+        local_results = op_call(*local_tensor_args, **local_tensor_kwargs)
+
+        # step4 aggregate gradients for edge pixels
+        grad_in_tensor = local_results[0]
+        grad_in_tensor = _ring_send_recv_aggregate(
+            grad_in_tensor, d1, d2, left, right, rank, size
+        )
+
+        local_results = list(local_results)
+        local_results[0] = grad_in_tensor
+        local_results = cast(Tuple[object, ...], local_results)
+
+        return local_results
+
+
+def convolution_handler(
+    op_call: torch._ops.OpOverload,
+    args: Tuple[object, ...],
+    kwargs: Dict[str, object],
+) -> object:
+    # extract local tensor and sharding infos to a OpInfo
+    op_info = dtensor.DTensor._op_dispatcher.unwrap_to_op_info(op_call, args, kwargs)
+
+    # sharding propagation
+    dtensor.DTensor._op_dispatcher.sharding_propagator.propagate(op_info)
+    output_sharding = op_info.output_sharding
+    assert output_sharding is not None, "output sharding should not be None"
+
+    # local propagation
+    local_results = tp_convolution(
+        op_call, tuple(op_info.local_args), op_info.local_kwargs
+    )
+
+    return dtensor.DTensor._op_dispatcher.wrap(
+        local_results, output_sharding.output_spec
+    )
+
+
+def convolution_backward_handler(
+    op_call: torch._ops.OpOverload,
+    args: Tuple[object, ...],
+    kwargs: Dict[str, object],
+) -> object:
+    # Redistribute grad_output tensor to the same placement as input tensor
+    args = list(args)
+    assert isinstance(args[0], dtensor.DTensor) and isinstance(args[1], dtensor.DTensor)
+    args[0] = args[0].redistribute(args[1].device_mesh, args[1].placements)
+    args = tuple(args)
+
+    # extract local tensor and sharding infos to a OpInfo
+    op_info = dtensor.DTensor._op_dispatcher.unwrap_to_op_info(op_call, args, kwargs)
+
+    # sharding propagation
+    dtensor.DTensor._op_dispatcher.sharding_propagator.propagate(op_info)
+    output_sharding = op_info.output_sharding
+    assert output_sharding is not None, "output sharding should not be None"
+
+    # local propagation
+    local_results = tp_convolution_backward(
+        op_call, tuple(op_info.local_args), op_info.local_kwargs
+    )
+
+    return dtensor.DTensor._op_dispatcher.wrap(
+        local_results, output_sharding.output_spec
+    )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..55a892063db9260e0162f4f07ed9fb4bb684cc8c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/_utils.py
@@ -0,0 +1,316 @@
+from typing import cast, List, Sequence, Tuple
+
+import torch
+import torch.distributed.tensor._api as dtensor
+from torch._prims_common import ShapeType
+from torch.distributed.device_mesh import DeviceMesh
+from torch.distributed.tensor._dtensor_spec import DTensorSpec
+from torch.distributed.tensor.placement_types import (
+    _StridedShard,
+    Partial,
+    Placement,
+    Replicate,
+    Shard,
+)
+
+
+# TODO: audit existing code base to see if we can safely remove this API.
+def compute_local_shape(
+    global_shape: ShapeType, mesh: DeviceMesh, placements: Sequence[Placement]
+) -> Tuple[int, ...]:
+    """
+    Compute the shape of a local shard of the given DTensor on its current
+    coordinate of the mesh.
+    """
+    my_coordinate = mesh.get_coordinate()
+
+    if my_coordinate is None:
+        # if rank not in the mesh, return empty shape
+        return (0,)
+    else:
+        local_shape = list(global_shape)  # start with global shape
+        ndim = len(global_shape)
+        for idx, placement in enumerate(placements):
+            mesh_dim_size = mesh.size(idx)
+            if isinstance(placement, Shard):
+                shard_dim = placement.dim
+                assert (
+                    shard_dim < ndim
+                ), f"Sharding dim {shard_dim} greater than tensor ndim {ndim}"
+                local_shard_size, _ = placement._local_shard_size_on_dim(
+                    local_shape[shard_dim], mesh_dim_size, my_coordinate[idx]
+                )
+                assert isinstance(local_shard_size, int)
+                local_shape[shard_dim] = local_shard_size
+
+        return tuple(local_shape)
+
+
+def compute_local_shape_and_global_offset(
+    global_shape: ShapeType, mesh: DeviceMesh, placements: Sequence[Placement]
+) -> Tuple[Tuple[int, ...], Tuple[int, ...]]:
+    """
+    Compute the local tensor shape and the global offsets into the original tensor
+    of a DTensor on its current global rank. This is useful for checkpointing purpose.
+
+    Example (2 host with 4GPUs each):
+    # Below is a DeviceMesh with mesh_shape of (2, 4)
+    mesh = DeviceMesh(device_type="cuda",
+                        mesh=[
+                        [0, 1, 2, 3],
+                        [4, 5, 6, 7]
+                        ],
+    )
+
+    Let's say we distribute a global_tensor of shape (8,4) over the above DeviceMesh
+    with a placements of [Shard(0), Shard(0)].
+    The local shape and global offset will be as follows:
+    rank0 -- local_shape:[1, 4], global_offset:[0, 0]
+    rank1 -- local_shape:[1, 4], global_offset:[1, 0]
+    rank2 -- local_shape:[1, 4], global_offset:[2, 0]
+    rank5 -- local_shape:[1, 4], global_offset:[5, 0]
+    rank3 -- local_shape:[1, 4], global_offset:[3, 0]
+    rank4 -- local_shape:[1, 4], global_offset:[4, 0]
+    rank6 -- local_shape:[1, 4], global_offset:[6, 0]
+    rank7 -- local_shape:[1, 4], global_offset:[7, 0]
+
+    Let's say we distribute a global_tensor of shape (2) over the above DeviceMesh with
+    a placements of [Shard(0)]. We will not have non-empty local tensor for all the ranks.
+    The local shape and global offset will be as follows:
+    rank0 -- local_shape:[1,], global_offset:[0,]
+    rank1 -- local_shape:[1,], global_offset:[1,]
+    rank2 -- local_shape:[0,], global_offset:[2,]
+    rank5 -- local_shape:[0,], global_offset:[2,]
+    rank3 -- local_shape:[0,], global_offset:[2,]
+    rank4 -- local_shape:[0,], global_offset:[2,]
+    rank6 -- local_shape:[0,], global_offset:[2,]
+    rank7 -- local_shape:[0,], global_offset:[2,]
+    """
+    my_coordinate = mesh.get_coordinate()
+
+    if my_coordinate is None:
+        # if rank not in the mesh, return empty offset
+        return ((), ())
+    else:
+        local_shape = list(global_shape)
+        global_offset = [0] * len(global_shape)
+        shard_idx_stride_by_mesh_dim = [
+            [0] * mesh.ndim for _ in range(len(global_shape))
+        ]  # index by (shard_dim, mesh_dim)
+        num_shards_by_tensor_dim = [1] * len(global_shape)
+
+        for idx, placement in enumerate(placements):
+            mesh_dim_size = mesh.size(idx)
+            if isinstance(placement, Shard):
+                shard_dim = placement.dim
+                local_offset = [0] * len(global_shape)
+                assert shard_dim < len(
+                    local_shape
+                ), f"Sharding dim {shard_dim} greater than tensor ndim {len(local_shape)}"
+                shard_size, shard_offset = placement._local_shard_size_on_dim(
+                    local_shape[shard_dim],
+                    mesh_dim_size,
+                    my_coordinate[idx],
+                    return_offset=True,
+                )
+
+                local_shape[shard_dim] = shard_size
+                local_offset[shard_dim] = shard_offset
+
+                # On a given dimension, if the local_offset[shard_dim] is smaller than global_offset[shard_dim],
+                # it means that this dimension has been already sharded in previous placement.
+                # Therefore, we cannot simply replace the global_offset[shard_dim] with local_offset[shard_dim].
+                # Instead, for the given shard_dim, we need to add local_offset[shard_dim] to existing global_offset[shard_dim].
+                if global_offset[shard_dim] <= local_offset[shard_dim]:
+                    global_offset[shard_dim] = local_offset[shard_dim]
+                else:
+                    global_offset[shard_dim] += local_offset[shard_dim]
+
+                num_shards_by_tensor_dim[shard_dim] *= mesh_dim_size
+
+        # NOTE: the offset compute relies on the local shard index and it has no
+        # problem when strided sharding is not present. To correctly compute, we assume
+        # that the ``_StridedShard.split_factor`` field encodes how many partitions
+        # each local tensor will be further split into when sharding on higher mesh
+        # dimensions. However, this number is only correct if the DTensor is not
+        # sharded after the strided sharding completes. For example,
+        # [Shard(0), _StridedShard(0, split_factor=2), Shard(0)] is the placements
+        # where the DTensor's dim-0 is first sharded on device mesh dim-0, then on
+        # device mesh dim-2, and last on mesh dim-1. We define the
+        # "_StridedShard(0, split_factor=2), Shard(0)" part as the strided sharding
+        # part because strided sharding happens on mesh dim-1 and it was caused by
+        # the fact that sharding on dim-2 occurred ahead. In this case, there's no
+        # further sharding after this strided sharding part and ``split_factor``
+        # correctly encodes the number. Another example is
+        # [_StridedShard(0, split_factor=2), Shard(0), Shard(0)] where the DTensor's
+        # dim-0 is first sharded on mesh dim-1, then on mesh dim-0, and last on mesh
+        # dim-2. This violates our assumption that no further sharding shall occur
+        # after the strided sharding part and ``split_factor`` won't correctly
+        # encode the number of further split. So far, the only case where _StridedShard
+        # placement would appear is FSDP2 + TP on 2D mesh and the above case could only
+        # happen on mesh of 3 or more dimensions.
+        # TODO: change this function to correctly address this.
+        # TODO: this logic can be applied to contiguous sharding as well
+        strided_sharding = any(isinstance(p, _StridedShard) for p in placements)
+        if strided_sharding:
+            strided_part_seen = [False] * len(global_shape)
+            strided_part_end = [False] * len(global_shape)
+            for idx, placement in enumerate(placements):
+                mesh_dim_size = mesh.size(idx)
+                if isinstance(placement, Shard):
+                    shard_dim = placement.dim
+
+                    if strided_part_end[shard_dim]:
+                        raise NotImplementedError(
+                            f"Strided sharding does not allow Shard() to appear after "
+                            f"the strided part has ended. {placement} at idx {idx} in "
+                            f"{placements} violates this assumption."
+                        )
+
+                    if strided_part_seen[shard_dim]:
+                        strided_part_end[shard_dim] = True
+
+                    if isinstance(placement, _StridedShard):
+                        strided_part_seen[shard_dim] = True
+                        shard_idx_stride_by_mesh_dim[shard_dim][
+                            idx
+                        ] = num_shards_by_tensor_dim[shard_dim] // (
+                            placement.split_factor * mesh_dim_size
+                        )
+                    else:
+                        num_shards_by_tensor_dim[shard_dim] //= mesh_dim_size
+                        shard_idx_stride_by_mesh_dim[shard_dim][
+                            idx
+                        ] = num_shards_by_tensor_dim[shard_dim]
+
+            shard_idx = [
+                sum([x * y for x, y in zip(shard_idx_stride, my_coordinate)])
+                for shard_dim, shard_idx_stride in enumerate(
+                    shard_idx_stride_by_mesh_dim
+                )
+            ]
+
+            global_offset = [x * y for x, y in zip(local_shape, shard_idx)]
+
+        return tuple(local_shape), tuple(global_offset)
+
+
+def compute_global_tensor_info(
+    tensor: torch.Tensor, mesh: DeviceMesh, placements: Sequence[Placement]
+) -> Tuple[List[int], List[int]]:
+    """
+    Compute the global size and stride of a DTensor from the given local tensor.
+    The local size is multiplited by `world_size` per Sharding dim.
+    The local stride is multiplited by `world_size` per Sharding dim, as long as the
+    dimension is outside sharding dim.
+
+    For example, if we have a local tensor with size (4, 8, 2) and stride (16, 1, 8).
+    If the DTensor placements are [Shard(2)] and world_size is 2;
+    then the global size is (4, 8, 4) and stride is (16 * 2, 1, 8).
+
+    Args:
+        tensor (:class:`torch.Tensor`):
+            Local tensor which DTensor will be constructed from.
+        mesh (:class:`DeviceMesh`):
+            Object which describes the mesh topology
+            of devices for the DTensor.
+        placements (Sequence[:class:`Placement`]]):
+            The attribute of the DTensor that describes its layout
+            on the mesh topology.
+
+    Return:
+        tensor_shape: A List of int which specifies the size of DTensor which build
+            on top of the local tensor.
+        tensor_stride: A List of int which specifies the stride of DTensor.
+    """
+    tensor_shape = list(tensor.size())
+    tensor_stride = list(tensor.stride())
+    for idx, placement in enumerate(placements):
+        mesh_dim_size = mesh.size(idx)
+        if placement.is_shard():
+            shard_placement = cast(Shard, placement)
+            if shard_placement.dim < 0:
+                raise AssertionError(
+                    "Shard placements should have negative dims normalized in "
+                    f"the user-facing APIs: {shard_placement}"
+                )
+            shard_dim = shard_placement.dim
+
+            assert (
+                shard_dim < tensor.ndim
+            ), f"Sharding dim {shard_dim} greater than tensor ndim {tensor.ndim} for placement number {idx}."
+
+            local_dim_size = tensor_shape[shard_dim]
+            tensor_shape[shard_dim] = local_dim_size * mesh_dim_size
+
+            # recover tensor stride by modifying the stride that larger than
+            # the current stride on the shard_dim
+            for i in range(len(tensor_stride)):
+                if i != shard_dim and tensor_stride[i] >= tensor_stride[shard_dim]:
+                    # rescale the stride by the shard size
+                    tensor_stride[i] = tensor_stride[i] * mesh_dim_size
+        elif not isinstance(placement, (Replicate, Partial)):
+            raise RuntimeError(f"placement type {type(placement)} not supported!")
+    return tensor_shape, tensor_stride
+
+
+def try_find_mesh_from_args(
+    op_call: torch._ops.OpOverload, args: Sequence[object]
+) -> DeviceMesh:
+    """
+    Find the device mesh object from args.
+    It returns None if no mesh is found.
+    NOTE: we can optimize this search if needed
+    """
+    for arg in args:
+        if isinstance(arg, (dtensor.DTensor, DTensorSpec)):
+            return arg.device_mesh
+        elif (
+            isinstance(arg, (list, tuple))
+            and len(arg) > 0
+            and isinstance(arg[0], (dtensor.DTensor, DTensorSpec))
+        ):
+            return arg[0].device_mesh
+
+    raise ValueError(f"Cannot find device mesh from args for op : {op_call}.")
+
+
+def compute_local_stride(
+    global_stride: ShapeType, mesh: DeviceMesh, placements: Sequence[Placement]
+) -> Tuple[int, ...]:
+    """
+    Compute the stride of a local tensor shard, given the global stride of the DTensor.
+    NOTE: Currently this function is assuming the DTensor is evenly shardable.
+    """
+    stride_divisors = [1] * len(global_stride)
+    for mesh_idx, p in enumerate(placements):
+        if p.is_shard():
+            i = cast(Shard, p).dim
+            # tensor dimension i is sharded on mesh dimension mesh_idx,
+            # so we need to divide all the strides larger than stride[i]
+            # (by the submesh size)
+            for j in range(len(global_stride)):
+                if global_stride[j] > global_stride[i]:
+                    stride_divisors[j] *= mesh.size(mesh_idx)
+    return tuple(
+        global_stride[i] // stride_divisors[i] for i in range(len(global_stride))
+    )
+
+
+def normalize_to_torch_size(size) -> torch.Size:  # type: ignore[no-untyped-def]
+    """
+    Unify variable types of size argument to torch.Size
+    Acceptable types include:
+        int, Sequence[int], Tuple[int], Tuple[Sequence[int]],
+        or torch.Size
+    """
+    if isinstance(size, torch.Size):
+        return size
+
+    if isinstance(size, int):
+        torch_size = [size]
+    elif len(size) == 1 and isinstance(size[0], Sequence):
+        torch_size = list(size[0])
+    else:
+        torch_size = list(size)
+    return torch.Size(torch_size)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/debug/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/debug/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5bf3b833fe4786eddcc9f6812faa3ee6a5f3e1a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/debug/__init__.py
@@ -0,0 +1,24 @@
+# mypy: allow-untyped-defs
+from torch.distributed.tensor.debug._comm_mode import CommDebugMode
+from torch.distributed.tensor.debug._visualize_sharding import visualize_sharding
+
+
+__all__ = ["CommDebugMode", "visualize_sharding"]
+
+
+def _get_sharding_prop_cache_info():
+    """
+    Get the cache info for the sharding propagation cache, used for debugging purpose only.
+    This would return a named tuple showing hits, misses, maxsize and cursize of the sharding
+    propagator cache.
+    """
+    from torch.distributed.tensor._api import DTensor
+
+    return (
+        DTensor._op_dispatcher.sharding_propagator.propagate_op_sharding.cache_info()  # type:ignore[attr-defined]
+    )
+
+
+# Set namespace for exposed private names
+CommDebugMode.__module__ = "torch.distributed.tensor.debug"
+visualize_sharding.__module__ = "torch.distributed.tensor.debug"
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/debug/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/debug/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4ffa8282668205dedbc691e61ce7fee845f7be23
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/debug/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/debug/__pycache__/_comm_mode.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/debug/__pycache__/_comm_mode.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..66b2bd12f43391be7cd9801ef399f2372c0c3793
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/debug/__pycache__/_comm_mode.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/debug/__pycache__/_op_coverage.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/debug/__pycache__/_op_coverage.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d7e3a8033654bcf0de13bb73f741a887f1c27bb4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/debug/__pycache__/_op_coverage.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/debug/__pycache__/_visualize_sharding.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/debug/__pycache__/_visualize_sharding.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0bca791de5fb50670f7748d93cfab9d477017b24
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/debug/__pycache__/_visualize_sharding.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/debug/_comm_mode.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/debug/_comm_mode.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a776c88cf0b82bc23af5fc298737b33792c952b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/debug/_comm_mode.py
@@ -0,0 +1,735 @@
+# mypy: allow-untyped-defs
+import copy
+import json
+import re
+import weakref
+from collections import defaultdict
+from typing import Any, Dict
+
+import torch
+import torch.nn
+from torch._guards import detect_fake_mode
+from torch.autograd.graph import register_multi_grad_hook
+from torch.distributed._tools.mod_tracker import ModTracker
+from torch.distributed.tensor._api import DTensor
+from torch.nn.modules.module import (
+    register_module_forward_hook,
+    register_module_forward_pre_hook,
+    register_module_full_backward_pre_hook,
+)
+from torch.utils._python_dispatch import TorchDispatchMode
+from torch.utils._pytree import tree_flatten
+
+
+__all__ = ["CommDebugMode"]
+
+funcol_native = torch.ops._c10d_functional
+funcol_py = torch.ops.c10d_functional
+funcol_autograd = torch.ops._c10d_functional_autograd
+c10d_ops = torch.ops.c10d
+
+NATIVE_TO_PY_MAPPING = {
+    funcol_native.all_gather_into_tensor: funcol_py.all_gather_into_tensor,
+    funcol_native.all_gather_into_tensor_coalesced: funcol_py.all_gather_into_tensor_coalesced,
+    funcol_native.all_reduce: funcol_py.all_reduce,
+    funcol_native.all_reduce_coalesced: funcol_py.all_reduce_coalesced,
+    funcol_native.all_to_all_single: funcol_py.all_to_all_single,
+    funcol_native.broadcast: funcol_py.broadcast,
+    funcol_native.reduce_scatter_tensor: funcol_py.reduce_scatter_tensor,
+    funcol_native.reduce_scatter_tensor_coalesced: funcol_py.reduce_scatter_tensor_coalesced,
+    # functional ops
+    funcol_autograd.all_to_all_single: funcol_py.all_to_all_single,
+}
+
+c10d_collective_ops = {
+    c10d_ops._allgather_base_,
+    c10d_ops._reduce_scatter_base_,
+    c10d_ops.allgather_,
+    c10d_ops.allgather_coalesced_,
+    c10d_ops.allgather_into_tensor_coalesced_,
+    c10d_ops.allreduce_,
+    c10d_ops.allreduce_coalesced_,
+    c10d_ops.alltoall_,
+    c10d_ops.alltoall_base_,
+    c10d_ops.broadcast_,
+    c10d_ops.gather_,
+    c10d_ops.scatter_,
+    c10d_ops.reduce_,
+    c10d_ops.reduce_scatter_,
+    c10d_ops.reduce_scatter_tensor_coalesced_,
+}
+
+trivial_ops = {
+    "aten.detach.default",
+    "aten.t.default",
+    "aten.view.default",
+    "aten._to_copy.default",
+    "aten.as_strided.default",
+    "aten.transpose.int",
+}
+
+
+class _CommModeModuleTracker(ModTracker):
+    """
+    Inherits ModuleTracker and expands on its functionality to track the
+    parameters and sharding information of a model at a module-level
+    """
+
+    def __init__(self):
+        super().__init__()
+        self.module_helper_dict = {}
+        self.module_parameters_dict = {}
+        self.module_parents_dict = {}
+        self.register_forward_hook_handles = {}
+        self.parent_dict = {}
+        self.parent_list = []
+        self.sharding_dict = {}
+        self.activation_checkpointing = False
+        self.name = ""
+
+    def _fw_set_module_hook(self, mod, input, output):
+        """
+        Updates the current module after module finishes running and
+        all other hooks are resolved
+        """
+
+        if self.is_bw:
+            self.activation_checkpointing = True
+        else:
+            self.activation_checkpointing = False
+
+        if not self.activation_checkpointing:
+            # module is no longer parent of next modules
+            self.parent_list.pop()
+
+            # set current module to previous parent module
+            self.name = self.parent_list[-1]
+
+    def _fw_pre_hook(self, mod, input):
+        """
+        This function is called before the forward pass of a module. It
+        collects the parameters and sharding information of a module and
+        stores it in a dictionary.
+        """
+        if self.is_bw:
+            self.activation_checkpointing = True
+        else:
+            self.activation_checkpointing = False
+
+        self.name = super()._get_mod_name(mod)
+        w_mod = weakref.ref(mod)
+
+        # adds current sub-module to module tracker parent class
+        super()._get_append_fn(w_mod, self.name, False)()
+
+        args, _ = tree_flatten(input)
+        tensors = [a for a in args if isinstance(a, torch.Tensor) and a.requires_grad]
+        if not self.is_bw and tensors:
+            register_multi_grad_hook(
+                tensors, super()._get_pop_fn(w_mod, self.name, True)
+            )
+
+        if not self.activation_checkpointing:
+            # contains information about module ordering and depth in the module tree
+            if self.name not in self.module_helper_dict:
+                self.module_helper_dict[self.name] = {}
+
+            self.module_helper_dict[self.name]["module_type"] = (
+                str(type(mod)).replace("<", "").replace(">", "")
+            )
+            self.module_helper_dict[self.name]["depth"] = len(self.parents) - 1
+
+            for param_name, param in mod.named_parameters(recurse=False):
+                if self.name not in self.module_parameters_dict:
+                    self.module_parameters_dict[self.name] = {}
+
+                self.module_parameters_dict[self.name][param_name] = param.data
+
+                if isinstance(param.data, DTensor):
+                    key_name = self.name + "." + param_name
+                    self.sharding_dict[key_name] = param.data.placements
+
+                    if "parameters" not in self.module_helper_dict[self.name]:
+                        self.module_helper_dict[self.name]["parameters"] = {}
+
+                    self.module_helper_dict[self.name]["parameters"][param_name] = str(
+                        param.data.placements
+                    )
+
+            # used to store module's parents to ensure correctness in backward pass/checkpointing
+            if self.name not in self.module_parents_dict:
+                self.module_parents_dict[self.name] = copy.deepcopy(self.parents)
+
+            # used to create parent-child module associations for json dumps
+            parent = self.parent_list[-1]
+            if parent not in self.parent_dict:
+                self.parent_dict[parent] = []
+
+            self.parent_dict[parent].append(self.name)
+            self.parent_list.append(self.name)
+
+            self.register_forward_hook_handles[self.name] = mod.register_forward_hook(
+                self._fw_set_module_hook
+            )
+
+    def _fw_post_hook(self, mod, input, output):
+        """
+        This function is called when the forward pass of a module is called.
+        It updates the module tracker and removes the module from parent data
+        """
+
+        super()._fw_post_hook(mod, input, output)
+
+    def _bw_hook(self, mod, output):
+        """
+        This function is called when the backward pass of a module is called. It
+        updates the current module for backward passes
+        """
+        self.activation_checkpointing = False
+        self.name = super()._get_mod_name(mod)
+
+    def __enter__(self):
+        self.activation_checkpointing = False
+        self.module_parameters_dict.clear()
+        self.sharding_dict.clear()
+        self.parent_dict.clear()
+        self.parent_list = ["Global"]
+        self.module_helper_dict.clear()
+        self.module_helper_dict["Global"] = {"depth": 0}
+        self.module_parents_dict.clear()
+        self.module_parents_dict["Global"] = set()
+        self._fw_pre_handle = register_module_forward_pre_hook(self._fw_pre_hook)
+        self._fw_post_handle = register_module_forward_hook(self._fw_post_hook)
+        self.register_forward_hook_handles.clear()
+        self._bw_handle = register_module_full_backward_pre_hook(self._bw_hook)
+        self.name = "Global"
+
+    def __exit__(self, *args):
+        super().__exit__(*args)
+        self._bw_handle.remove()
+
+        # removes all forward_hook handles added in the pre-hook
+        for handle in self.register_forward_hook_handles.values():
+            handle.remove()
+
+    def print_paramater_info(self):
+        print(self.module_parameters_dict)
+
+    def print_sharding_info(self):
+        for key, value in self.sharding_dict.items():
+            print(key + ": " + str(value))
+
+
+class CommDebugMode(TorchDispatchMode):
+    """
+    :class:`CommDebugMode` is a context manager that counts the number of
+    functional collectives within its context. It does this using a
+    ``TorchDispatchMode``.
+
+    .. note: Not all collectives are supported yet.
+
+    Example usage
+
+    .. code-block:: python
+
+        mod = ...
+        comm_mode = CommDebugMode()
+        with comm_mode:
+            mod.sum().backward()
+        print(comm_mode.get_comm_counts())
+    """
+
+    def __init__(self):
+        self.comm_counts: Dict[Any, int] = defaultdict(int)
+        self.comm_module_counts = {}
+        self.comm_module_operation_counts = {}
+        self.comm_registry = set()
+        for native_op, py_op in NATIVE_TO_PY_MAPPING.items():
+            self.comm_registry.add(native_op)
+            self.comm_registry.add(py_op)
+
+        self.comm_registry.add(torch.ops._dtensor.shard_dim_alltoall)
+        self.advanced_module_tracker = _CommModeModuleTracker()
+
+    def generate_json_dump(self, file_name="comm_mode_log.json", noise_level=3):
+        """
+        Creates json file used to build browser visual
+        0. prints module-level collective counts
+        1. prints dTensor operations not included in trivial operations
+        2. prints operations not included in trivial operations
+        3. prints all operations
+        """
+
+        (
+            include_DTensor_ops,
+            include_module_data,
+            include_ops,
+            include_trivial_ops,
+        ) = self._set_noise_parameters(noise_level)
+
+        # recursively builds json data
+        def add_json_information(json_dict, fqn):
+            json_dict["fqn"] = fqn
+            json_dict["module_type"] = ""
+            json_dict["parameters"] = []
+            json_dict["children"] = []
+            json_dict["collectives_forward"] = []
+            json_dict["collectives_backward"] = []
+            json_dict["operations_forward"] = []
+            json_dict["operations_backward"] = []
+
+            # adds module layer type and parameters, and their sharding
+            if (
+                "module_type" in self.advanced_module_tracker.module_helper_dict[fqn]
+                and include_module_data
+            ):
+                json_dict[
+                    "module_type"
+                ] = self.advanced_module_tracker.module_helper_dict[fqn]["module_type"]
+
+                if "parameters" in self.advanced_module_tracker.module_helper_dict[fqn]:
+                    for (
+                        param_name,
+                        placement,
+                    ) in self.advanced_module_tracker.module_helper_dict[fqn][
+                        "parameters"
+                    ].items():
+                        json_dict["parameters"].append((param_name, placement))
+
+            # adds module collective information
+            if fqn in self.comm_module_counts:
+                for collective, count in self.comm_module_counts[fqn][
+                    "forward"
+                ].items():
+                    json_dict["collectives_forward"].append((str(collective), count))
+
+                for collective, count in self.comm_module_counts[fqn][
+                    "backward"
+                ].items():
+                    json_dict["collectives_backward"].append((str(collective), count))
+
+            # adds module operation information
+            forward_operations = []
+            backward_operations = []
+            checkpointing_operations = []
+
+            # only get operations if the minimum operation noise level is set to true
+            if include_DTensor_ops:
+                if fqn in self.comm_module_operation_counts:
+                    (
+                        forward_operations,
+                        backward_operations,
+                        checkpointing_operations,
+                    ) = self._get_operations_list(
+                        self.comm_module_operation_counts[fqn]
+                    )
+
+            # remove all operations who don't have DTensor inputs
+            if not include_ops:
+                forward_operations = [
+                    op for op in forward_operations if len(op["input_sharding"])
+                ]
+                backward_operations = [
+                    op for op in backward_operations if len(op["input_sharding"])
+                ]
+                checkpointing_operations = [
+                    op for op in checkpointing_operations if len(op["input_sharding"])
+                ]
+
+            # remove all operations in trivial operations set
+            if not include_trivial_ops:
+                forward_operations = [
+                    op
+                    for op in forward_operations
+                    if str(op["name"]) not in trivial_ops
+                ]
+                backward_operations = [
+                    op
+                    for op in backward_operations
+                    if str(op["name"]) not in trivial_ops
+                ]
+                checkpointing_operations = [
+                    op
+                    for op in checkpointing_operations
+                    if str(op["name"]) not in trivial_ops
+                ]
+
+            # converts operation information into string format for json.dumps()
+            forward_operations = copy.deepcopy(forward_operations)
+            for op in forward_operations:
+                op["name"] = str(op["name"])
+
+                for i in range(len(op["input_sharding"])):
+                    op["input_sharding"][i] = str(op["input_sharding"][i])
+                    op["input_shape"][i] = str(op["input_shape"][i])
+
+            backward_operations = copy.deepcopy(backward_operations)
+            for op in backward_operations:
+                op["name"] = str(op["name"])
+
+                for i in range(len(op["input_sharding"])):
+                    op["input_sharding"][i] = str(op["input_sharding"][i])
+                    op["input_shape"][i] = str(op["input_shape"][i])
+
+            checkpointing_operations = copy.deepcopy(checkpointing_operations)
+            for op in checkpointing_operations:
+                op["name"] = str(op["name"])
+
+                for i in range(len(op["input_sharding"])):
+                    op["input_sharding"][i] = str(op["input_sharding"][i])
+                    op["input_shape"][i] = str(op["input_shape"][i])
+
+            json_dict["operations_forward"] = forward_operations
+            json_dict["operations_backward"] = backward_operations
+            json_dict["operations_checkpointing"] = checkpointing_operations
+
+            if fqn not in self.advanced_module_tracker.parent_dict:
+                return json_dict
+
+            # recursively adds module's children
+            for ele in self.advanced_module_tracker.parent_dict[fqn]:
+                json_dict["children"].append(add_json_information({}, ele))
+
+            return json_dict
+
+        json_dict: Dict[str, Any] = {}
+        add_json_information(json_dict, "Global")
+
+        # converts dictonary into json file
+        with open(file_name, "w") as json_file:
+            json.dump(json_dict, json_file, indent=4)
+
+    def generate_comm_debug_tracing_table(self, noise_level=3):
+        """
+        Generates detailed table displaying operations and collective tracing information
+        on a module level. Amount of information is dependent on noise_level
+
+        0. prints module-level collective counts
+        1. prints dTensor operations not included in trivial operations, module information
+        2. prints operations not included in trivial operations
+        3. prints all operations
+        """
+
+        (
+            include_DTensor_ops,
+            include_module_data,
+            include_ops,
+            include_trivial_ops,
+        ) = self._set_noise_parameters(noise_level)
+
+        table = ""
+        for fqn in self.advanced_module_tracker.module_helper_dict:
+            # setting up indentations for table formatting
+            indent = "  " * (
+                2 * self.advanced_module_tracker.module_helper_dict[fqn]["depth"]
+            )
+            table += f"{indent}{fqn}\n"
+
+            if include_module_data:
+                if (
+                    "module_type"
+                    in self.advanced_module_tracker.module_helper_dict[fqn]
+                ):
+                    module_type = self.advanced_module_tracker.module_helper_dict[fqn][
+                        "module_type"
+                    ]
+                    table += f"{indent}*module type: {module_type}\n"
+
+                if "parameters" in self.advanced_module_tracker.module_helper_dict[fqn]:
+                    table += f"{indent}*Parameter List\n"
+                    for (
+                        param_name,
+                        placement,
+                    ) in self.advanced_module_tracker.module_helper_dict[fqn][
+                        "parameters"
+                    ].items():
+                        table += f"{indent} *{param_name}: {placement}\n"
+
+            indent += "  "
+            collective_indent = "  " * (
+                2 * self.advanced_module_tracker.module_helper_dict[fqn]["depth"] + 2
+            )
+            operation_indent = "  " * (
+                2 * self.advanced_module_tracker.module_helper_dict[fqn]["depth"] + 3
+            )
+
+            # separate the module's collective and operations by forward and backward
+            forward_collectives = {}
+            backward_collectives = {}
+            if fqn in self.comm_module_counts:
+                forward_collectives = self.comm_module_counts[fqn]["forward"]
+                backward_collectives = self.comm_module_counts[fqn]["backward"]
+
+            forward_operations = []
+            backward_operations = []
+            checkpointing_operations = []
+
+            if include_DTensor_ops:
+                if fqn in self.comm_module_operation_counts:
+                    (
+                        forward_operations,
+                        backward_operations,
+                        checkpointing_operations,
+                    ) = self._get_operations_list(
+                        self.comm_module_operation_counts[fqn]
+                    )
+
+            def add_tracing_information(table, collectives_dict, operation_list):
+                """
+                adds tracing information for module's forward or backward
+                """
+                for collective, count in collectives_dict.items():
+                    table += (
+                        f"\033[1;33m{collective_indent}*{collective}: {count}\033[0m\n"
+                    )
+
+                def add_operations(
+                    table, operation, collective_indent, operation_indent
+                ):
+                    """
+                    adds operation information to the table
+                    """
+                    table += f"\033[1;33m{collective_indent}**{operation_name}\033[0m\n"
+
+                    if len(operation["input_shape"]):
+                        operation_shape = operation["input_shape"]
+                        operation_sharding = operation["input_sharding"]
+                        operation_device_mesh = operation["device_mesh"]
+
+                        table += f"\033[1;31m{operation_indent}shape: {operation_shape}\033[0m\n"
+                        table += f"\033[1;31m{operation_indent}sharding: {operation_sharding}\033[0m\n"
+                        table += f"\033[1;31m{operation_indent}device mesh: {operation_device_mesh}\033[0m\n"
+
+                    return table
+
+                for operation in operation_list:
+                    operation_name = str(operation["name"])
+
+                    # include all operations
+                    if include_trivial_ops:
+                        table = add_operations(
+                            table, operation, collective_indent, operation_indent
+                        )
+
+                    # include all operations not in trivial operations
+                    elif include_ops and operation_name not in trivial_ops:
+                        table = add_operations(
+                            table, operation, collective_indent, operation_indent
+                        )
+
+                    # only include dTensor operations not in trivial set
+                    elif (
+                        include_DTensor_ops
+                        and (operation_name not in trivial_ops)
+                        and len(operation["input_shape"])
+                    ):
+                        table = add_operations(
+                            table, operation, collective_indent, operation_indent
+                        )
+
+                return table
+
+            if len(forward_collectives) or len(forward_operations):
+                table += f"{indent}FORWARD PASS\n"
+                table = add_tracing_information(
+                    table, forward_collectives, forward_operations
+                )
+
+            if len(backward_collectives) or len(backward_operations):
+                table += f"{indent}BACKWARD PASS\n"
+                table = add_tracing_information(
+                    table, backward_collectives, backward_operations
+                )
+
+            if len(checkpointing_operations):
+                table += f"{indent}ACTIVATION CHECKPOINTING\n"
+                table = add_tracing_information(table, {}, checkpointing_operations)
+
+        return table
+
+    def _get_operations_list(self, module_operation_counts):
+        forward_operations = [
+            op for op in module_operation_counts["operations_list"] if not op["is_bw"]
+        ]
+        backward_operations = [
+            op
+            for op in module_operation_counts["operations_list"]
+            if op["is_bw"] and not op["is_activation_checkpointing"]
+        ]
+        checkpointing_operations = [
+            op
+            for op in module_operation_counts["operations_list"]
+            if op["is_activation_checkpointing"]
+        ]
+
+        return forward_operations, backward_operations, checkpointing_operations
+
+    def get_total_counts(self) -> int:
+        return sum(self.comm_counts.values())
+
+    def get_comm_counts(self) -> Dict[Any, int]:
+        """Returns the communication counts as a dictionary.
+
+        Returns:
+            Dict[Any, int]: The communication counts as a dictionary.
+        """
+        return self.comm_counts
+
+    def get_parameter_info(self) -> Dict[str, Dict[str, Any]]:
+        return self.advanced_module_tracker.module_parameters_dict
+
+    def get_sharding_info(self) -> Dict[str, Dict[str, Any]]:
+        return self.advanced_module_tracker.sharding_dict
+
+    def __enter__(self):
+        self.comm_counts.clear()
+        self.comm_module_counts.clear()
+        self.comm_module_counts["Global"] = {}
+        self.comm_module_counts["Global"]["forward"] = defaultdict(int)
+        self.comm_module_counts["Global"]["backward"] = defaultdict(int)
+
+        self.comm_module_operation_counts.clear()
+
+        super().__enter__()
+        self.advanced_module_tracker.__enter__()
+        return self
+
+    def __exit__(self, *args):
+        self.advanced_module_tracker.__exit__()
+        super().__exit__(*args)
+
+    def log_comm_debug_tracing_table_to_file(
+        self, file_name="comm_mode_log.txt", noise_level=3
+    ):
+        """
+        Alternative to console CommDebugMode output, writes to file specified by the user
+        """
+        ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
+        table = ansi_escape.sub("", self.generate_comm_debug_tracing_table(noise_level))
+
+        with open(file_name, "w") as log_file:
+            log_file.write(table)
+
+    def _set_noise_parameters(self, noise_level):
+        """
+        sets variables controlling what information displays based on noise level
+        """
+        include_DTensor_ops = False
+        include_module_data = False
+        include_ops = False
+        include_trivial_ops = False
+
+        if noise_level > 0:
+            include_DTensor_ops = True
+            include_module_data = True
+
+        if noise_level > 1:
+            include_ops = True
+
+        if noise_level > 2:
+            include_trivial_ops = True
+
+        return (
+            include_DTensor_ops,
+            include_module_data,
+            include_ops,
+            include_trivial_ops,
+        )
+
+    def __torch_dispatch__(self, func, types, args=(), kwargs=None):
+        # When running this mode with DTensor, ordinarily all modes will
+        # run **before** subclasses get a chance to run.
+        # Returning NotImplemented here gives us a chance to let DTensor
+        # run and desugar into comms ops, before CommDebugMode sees them.
+
+        # sets up operation-level collective count
+        if self.advanced_module_tracker.name not in self.comm_module_operation_counts:
+            # dictionary should hold module input and output shape, operations list and collective counter
+            self.comm_module_operation_counts[self.advanced_module_tracker.name] = {
+                "operations_list": []
+            }
+        operation_dict = {}
+        operation_dict["name"] = func
+
+        operation_dict["input_shape"] = []
+        operation_dict["input_sharding"] = []
+        operation_dict["device_mesh"] = ""
+
+        # tracks if the operation is part of the backward pass
+        operation_dict["is_bw"] = self.advanced_module_tracker.is_bw
+
+        # tracks if the operation is part of activation checkpointing
+        operation_dict[
+            "is_activation_checkpointing"
+        ] = self.advanced_module_tracker.activation_checkpointing
+
+        if any(t == DTensor for t in types):
+            for ele in args:
+                if isinstance(ele, DTensor):
+                    # saves shapes and placements of all DTensor args
+                    operation_dict["input_shape"].append(ele.shape)
+                    operation_dict["input_sharding"].append(ele.placements)
+                    operation_dict["device_mesh"] = str(ele.device_mesh)
+
+            self.comm_module_operation_counts[self.advanced_module_tracker.name][
+                "operations_list"
+            ].append(operation_dict)
+
+            return NotImplemented
+
+        kwargs = kwargs if kwargs else {}
+        out = func(*args, **kwargs)
+        func_packet = func._overloadpacket
+
+        # We have many tests that use CommDebugMode to verify the occurrence of
+        # collectives. These tests do so by querying comm_counts with legacy
+        # funcol ops as key. For the purpose of native funcol migration, we
+        # need these tests to work for both legacy and native funcol. To avoid
+        # the need to modify all tests to accommodate the two implementations,
+        # we make CommDebugMode translate native funcol ops into legacy funcol
+        # ops until the migration finishes.
+
+        if func_packet in self.comm_registry or func_packet in c10d_collective_ops:
+            if func_packet in NATIVE_TO_PY_MAPPING:
+                func_packet = NATIVE_TO_PY_MAPPING[func_packet]
+            self.comm_counts[func_packet] += 1
+
+            key = "forward"
+            if self.advanced_module_tracker.is_bw:
+                key = "backward"
+
+            # adds collective count to current module
+            if self.advanced_module_tracker.name not in self.comm_module_counts:
+                self.comm_module_counts[self.advanced_module_tracker.name] = {}
+                self.comm_module_counts[self.advanced_module_tracker.name][
+                    "forward"
+                ] = defaultdict(int)
+                self.comm_module_counts[self.advanced_module_tracker.name][
+                    "backward"
+                ] = defaultdict(int)
+            self.comm_module_counts[self.advanced_module_tracker.name][key][
+                func_packet
+            ] += 1
+
+            # adds collective count to parent modules
+            for par in self.advanced_module_tracker.module_parents_dict[
+                self.advanced_module_tracker.name
+            ]:
+                # makes sure we aren't double counting when current sub-module hasn't been removed from parents
+                if par != self.advanced_module_tracker.name:
+                    if par not in self.comm_module_counts:
+                        self.comm_module_counts[par] = {}
+                        self.comm_module_counts[par]["forward"] = defaultdict(int)
+                        self.comm_module_counts[par]["backward"] = defaultdict(int)
+                    self.comm_module_counts[par][key][func_packet] += 1
+
+        # if tensor op uses fake tensors, return
+        if detect_fake_mode(args):
+            return out
+
+        # add tensor operation to module operation list
+        self.comm_module_operation_counts[self.advanced_module_tracker.name][
+            "operations_list"
+        ].append(operation_dict)
+
+        return out
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/debug/_op_coverage.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/debug/_op_coverage.py
new file mode 100644
index 0000000000000000000000000000000000000000..258dc27a6c43db3068c94a6da2d405e9b4ead3f7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/debug/_op_coverage.py
@@ -0,0 +1,105 @@
+# mypy: allow-untyped-defs
+from operator import itemgetter
+from typing import List
+
+import torch
+import torch.fx
+import torch.nn as nn
+from functorch.compile import make_boxed_func
+from torch._functorch.compilers import aot_module
+from torch._inductor.decomposition import select_decomp_table
+from torch.distributed.tensor import DTensor
+
+
+inductor_decomps = select_decomp_table()
+
+graphs: List[torch.fx.GraphModule] = []
+
+
+def fwd_bwd_compiler(fx_g, _):
+    graphs.append(fx_g)
+    return make_boxed_func(fx_g)
+
+
+def get_inductor_decomp_graphs(model: nn.Module, args, kwargs):
+    """
+    Obtain forward and backward graphs of a model with inductor decompositions using tracing and aot_module.
+
+    Convenient util to get the fwd and bwd graphs of an arbitrary model
+    with inductor decompositions. Note that this would simply do tracing
+    with aot_module and don't ensure correctness. This is useful to track
+    the ops needed in DTensor.
+    """
+    compiled_mod = aot_module(
+        model, fw_compiler=fwd_bwd_compiler, decompositions=inductor_decomps
+    )
+    output = compiled_mod(*args, **kwargs)
+
+    if output.ndim != 0:
+        # if output is not a scalar tensor, by default sum it in order to
+        # run backward
+        output = output.sum()
+
+    output.backward()
+
+    # one fwd, one bwd graph
+    assert len(graphs) == 2
+    return graphs
+
+
+def print_op_coverage_summary(model: nn.Module, args, kwargs, *, output_csv=False):
+    """
+    Util to print the operator coverage summary of a certain model with tabulute.
+
+    Must have tabulate module installed.
+    """
+    # python module required for summary
+    import csv
+
+    from tabulate import tabulate
+
+    fwd_graph, bwd_graph = get_inductor_decomp_graphs(model, args, kwargs)
+
+    op_counts = {}
+
+    for node in fwd_graph.graph.nodes:
+        if node.op == "call_function" and isinstance(
+            node.target, torch._ops.OpOverload
+        ):
+            if node.target not in op_counts:
+                op_counts[node.target] = 0
+
+            op_counts[node.target] += 1
+
+    for node in bwd_graph.graph.nodes:
+        if node.op == "call_function" and isinstance(
+            node.target, torch._ops.OpOverload
+        ):
+            if node.target not in op_counts:
+                op_counts[node.target] = 0
+
+            op_counts[node.target] += 1
+
+    op_infos = []
+
+    for op, count in op_counts.items():
+        supported = op in DTensor._op_dispatcher.sharding_propagator.op_to_rules
+        op_infos.append([op, str(op._schema), count, supported])
+
+    # sort the op info base on the total count index
+    count_idx = 2
+    op_infos.sort(key=itemgetter(count_idx), reverse=True)
+
+    headers = ["Operator", "Schema", "Total Count", "Supported"]
+    print(tabulate(op_infos, headers=headers))
+
+    if output_csv:
+        # Open a CSV file for writing
+        with open("op_summary.csv", "w", newline="") as csv_file:
+            # Create a CSV writer object
+            csv_writer = csv.writer(csv_file)
+
+            csv_writer.writerow(headers)
+            # Write each table row to the CSV file
+            for row in op_infos:
+                csv_writer.writerow(row)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/debug/_visualize_sharding.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/debug/_visualize_sharding.py
new file mode 100644
index 0000000000000000000000000000000000000000..ade935d5133cf1b2962be6f6a6b4721ab3bd88ea
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/debug/_visualize_sharding.py
@@ -0,0 +1,178 @@
+# mypy: allow-untyped-defs
+from typing import List, Sequence, Tuple
+
+import numpy as np
+
+from torch._prims_common import ShapeType
+from torch.distributed.tensor import DeviceMesh
+from torch.distributed.tensor.placement_types import Placement, Shard
+
+
+__all__ = ["visualize_sharding"]
+
+
+def _mesh_to_coordinate(mesh, device_type):
+    """
+    Given a n-dimensional list of device mesh, this function creates a map of
+    device and its coordinate
+    """
+    # Convert the n-dimensional list to a NumPy array
+    np_mesh = np.array(mesh.mesh.tolist())
+
+    # Create a dictionary to map each value to its coordinate
+    device_to_coordinate_map = {}
+    for coord, value in np.ndenumerate(np_mesh):
+        # device is unique in device_mesh
+        device_to_coordinate_map[f"{device_type}:{str(value)}"] = list(coord)
+
+    return device_to_coordinate_map
+
+
+def _convert_offset_to_ranges(all_offsets):
+    """
+    Using tabulate package to create a table is easier when we specify row and col ranges
+    This function converts offsets to ranges.
+    """
+    converted_blocks = []
+
+    for offset in all_offsets:
+        shape, offset, value = offset
+
+        # Calculate row_range and column_range
+        row_range = (offset[0], offset[0] + shape[0] - 1)
+        column_range = (offset[1], offset[1] + shape[1] - 1)
+
+        # Convert value to string to match your desired format
+        converted_block = {
+            "row_range": row_range,
+            "column_range": column_range,
+            "value": str(value),
+        }
+        converted_blocks.append(converted_block)
+
+    return converted_blocks
+
+
+def _create_table(blocks):
+    """
+    Creates a tabulate table given row and column ranges with device name
+    """
+    try:
+        from tabulate import tabulate
+    except ImportError as e:
+        raise ImportError("tabulate package is required to visualize sharding") from e
+
+    # Extract unique row and column ranges
+    row_ranges = sorted({block["row_range"] for block in blocks})
+    col_ranges = sorted({block["column_range"] for block in blocks})
+
+    # Create a matrix initialized with empty strings
+    matrix = [["" for _ in col_ranges] for _ in row_ranges]
+
+    # Fill the matrix with values
+    for block in blocks:
+        row_index = row_ranges.index(block["row_range"])
+        col_index = col_ranges.index(block["column_range"])
+        if matrix[row_index][col_index] == "":
+            matrix[row_index][col_index] = block["value"]
+        else:
+            matrix[row_index][col_index] += ", " + block["value"]
+
+    # Prepare headers
+    row_headers = [f"Row {r[0]}-{r[1]}" for r in row_ranges]
+    col_headers = [f"Col {c[0]}-{c[1]}" for c in col_ranges]
+
+    return tabulate(matrix, headers=col_headers, showindex=row_headers)
+
+
+def _compute_local_shape_and_global_offset(
+    global_shape: ShapeType,
+    mesh: DeviceMesh,
+    placements: Sequence[Placement],
+    my_coordinate: List[int],
+) -> Tuple[Tuple[int, ...], Tuple[int, ...]]:
+    """
+    Same as torch.distributed._tensor._utils.compute_local_shape_and_global_offset but
+    with custom my_coordinate input. This is the modified implementation for visualize_sharding.
+    """
+
+    if my_coordinate is None:
+        # if rank not in the mesh, return empty offset
+        return ((), ())
+    else:
+        local_shape = list(global_shape)
+        global_offset = [0] * len(global_shape)
+
+        for idx, placement in enumerate(placements):
+            mesh_dim_size = mesh.size(idx)
+            if isinstance(placement, Shard):
+                shard_dim = placement.dim
+                local_offset = [0] * len(global_shape)
+                assert shard_dim < len(
+                    local_shape
+                ), f"Sharding dim {shard_dim} greater than tensor ndim {len(local_shape)}"
+                shard_size, shard_offset = placement._local_shard_size_on_dim(
+                    local_shape[shard_dim],
+                    mesh_dim_size,
+                    my_coordinate[idx],
+                    return_offset=True,
+                )
+
+                local_shape[shard_dim] = shard_size
+                local_offset[shard_dim] = shard_offset
+
+                # On a given dimension, if the local_offset[shard_dim] is smaller than global_offset[shard_dim],
+                # it means that this dimension has been already sharded in previous placement.
+                # Therefore, we cannot simply replace the global_offset[shard_dim] with local_offset[shard_dim].
+                # Instead, for the given shard_dim, we need to add local_offset[shard_dim] to existing global_offset[shard_dim].
+                if global_offset[shard_dim] <= local_offset[shard_dim]:
+                    global_offset[shard_dim] = local_offset[shard_dim]
+                else:
+                    global_offset[shard_dim] += local_offset[shard_dim]
+
+        return tuple(local_shape), tuple(global_offset)
+
+
+def visualize_sharding(dtensor, header=""):
+    """
+    Visualizes sharding in the terminal for :class:`DTensor` that are 1D or 2D.
+
+    .. note:: This requires the ``tabulate`` package. No sharding info will be printed for empty tensors
+    """
+    if dtensor.numel() == 0:  # we do not print for empty dtensors
+        return
+
+    if len(dtensor.shape) >= 3:
+        raise RuntimeError(
+            "visualize sharding is only implemented for 1D or 2D dtensor"
+        )
+    placements = dtensor.placements
+    device_mesh = dtensor.device_mesh
+    device_type = dtensor.device_mesh.device_type
+
+    if device_mesh.get_coordinate() is None:  # current rank is not in the mesh
+        return
+
+    # Only display the visualization once for each DTensor, on the rank whose
+    # coordinate is 0 on all dimensions. For example, if the mesh is a full mesh,
+    # we will only print on rank 0.
+    local_rank_zero_on_all_dim = all(
+        device_mesh.get_local_rank(mesh_dim=dim) == 0 for dim in range(device_mesh.ndim)
+    )
+    if not local_rank_zero_on_all_dim:
+        return
+
+    device_map = _mesh_to_coordinate(device_mesh, device_type)
+    all_offsets = []
+    for device in device_map:
+        local_shape, global_offset = _compute_local_shape_and_global_offset(
+            dtensor.shape, device_mesh, placements, device_map[device]
+        )
+        all_offsets.append([local_shape, global_offset, device])
+
+    # Convert offsets to blocks with row_ranges for tabulate
+    blocks = _convert_offset_to_ranges(all_offsets)
+
+    # Print the table
+    print(header)
+    print(_create_table(blocks))
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/device_mesh.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/device_mesh.py
new file mode 100644
index 0000000000000000000000000000000000000000..ca59ded5eb52bc0a3878e76077ad2879df4bf499
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/device_mesh.py
@@ -0,0 +1,9 @@
+from torch.distributed.device_mesh import (  # noqa: F401
+    _get_device_handle,
+    _mesh_resources,
+    DeviceMesh,
+    init_device_mesh,
+)
+
+
+__all__ = ["init_device_mesh", "DeviceMesh"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5193034770af135e7bfd7907273cb4ad5c777140
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/__init__.py
@@ -0,0 +1,32 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and affiliates
+from contextlib import contextmanager
+
+from torch.distributed.tensor._api import DTensor
+from torch.distributed.tensor.experimental._func_map import local_map
+from torch.distributed.tensor.experimental._register_sharding import register_sharding
+
+
+__all__ = ["implicit_replication", "local_map", "register_sharding"]
+
+
+@contextmanager
+def implicit_replication():
+    """
+    This context manager allows :class:`DTensor` to implicitly treat all non-DTensors (``torch.Tensor``)
+    in the program be replicate :class:`DTensor` s during the operator computation.
+
+    .. warning:: This might possible lead to incorrect results if ``torch.Tensor`` s are not replicated
+        in practice, please use it at your discretion.
+    """
+    try:
+        DTensor._op_dispatcher._allow_implicit_replication = True
+        yield
+    finally:
+        DTensor._op_dispatcher._allow_implicit_replication = False
+
+
+# Set namespace for exposed private names
+implicit_replication.__module__ = "torch.distributed.tensor.experimental"
+local_map.__module__ = "torch.distributed.tensor.experimental"
+register_sharding.__module__ = "torch.distributed.tensor.experimental"
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..45cea9a659491efb575a566561050cc6af46c1b3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/__pycache__/_attention.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/__pycache__/_attention.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..817540c15b671694bf8b0f594df824c5dafc63d6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/__pycache__/_attention.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/__pycache__/_func_map.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/__pycache__/_func_map.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cd2f411a4cfef85e7592e3b0f38a963b3c60479e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/__pycache__/_func_map.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/__pycache__/_register_sharding.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/__pycache__/_register_sharding.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..99ac6def50ae99f906304e49072486eb7eedd2ca
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/__pycache__/_register_sharding.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/__pycache__/_tp_transform.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/__pycache__/_tp_transform.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0f5944ba586e1cf8cad056e62a311079c5ca65f6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/__pycache__/_tp_transform.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/_attention.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/_attention.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5c05232a5734912b77e4833a8d294428ce55b8c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/_attention.py
@@ -0,0 +1,867 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates
+
+import contextlib
+import itertools
+import logging
+import types
+import weakref
+from enum import Enum
+from typing import (
+    Any,
+    Callable,
+    Dict,
+    Generator,
+    List,
+    Optional,
+    Protocol,
+    Set,
+    Tuple,
+    Union,
+)
+
+import torch
+import torch.distributed as dist
+import torch.distributed._functional_collectives as ft_c
+import torch.nn.functional as F
+from torch import nn
+from torch.distributed.device_mesh import DeviceMesh
+from torch.distributed.tensor import distribute_module, DTensor, Replicate, Shard
+from torch.distributed.tensor.parallel.style import ParallelStyle
+
+
+# TODO: expose a single API
+__all__ = ["context_parallel"]
+
+aten = torch.ops.aten
+logger = logging.getLogger(__name__)
+# Whether to upcast parameters and gradients to float32 to avoid accumulation
+# errors. It is likely this is always True but we currently keep this variable
+# for the experimental purpose.
+_convert_to_f32 = True
+
+
+class _CausalBehavior(Enum):
+    SKIP = None
+    NOT_IS_CAUSAL = False
+    IS_CAUSAL = True
+
+
+def _is_causal_behavior(
+    rank: int, world_size: int, i: int, is_causal: bool
+) -> _CausalBehavior:
+    """
+    Calculate is_causal behavior for each KV block. The attention can either be
+    calculated in full, not at all or with the causal mask applied.
+    """
+    if not is_causal:
+        return _CausalBehavior.NOT_IS_CAUSAL
+
+    if i == 0:
+        return _CausalBehavior.IS_CAUSAL
+
+    source_rank = (rank - i) % world_size
+    if source_rank < rank:
+        return _CausalBehavior.NOT_IS_CAUSAL
+    else:
+        return _CausalBehavior.SKIP
+
+
+def _maybe_wait(tensor: torch.Tensor) -> torch.Tensor:
+    """
+    When tracing the code, the result tensor is not an AsyncCollectiveTensor,
+    so we cannot call ``wait()``.
+    """
+    if isinstance(tensor, ft_c.AsyncCollectiveTensor):
+        return tensor.wait()
+    return tensor
+
+
+class _SDPAMerger:
+    """A class to help to merge the local SDPA result."""
+
+    def __init__(self, convert_to_f32: bool):
+        self._out: Optional[torch.Tensor] = None
+        self._lse: Optional[torch.Tensor] = None
+        self._convert_to_f32 = convert_to_f32
+        self._out_dtype = torch.float32
+        self._lse_dtype = torch.float32
+
+    def _merge_one(self, block_out: torch.Tensor, block_lse: torch.Tensor) -> None:
+        block_lse = block_lse.unsqueeze(dim=-1)
+        if self._lse is None:
+            self._lse = block_lse
+            self._out = block_out
+        else:
+            # The algorithm from
+            # github.com/zhuzilin/ring-flash-attention/pull/34#issuecomment-2076126795
+            # gives a relatively stable result.
+            self._out = self._out - F.sigmoid(block_lse - self._lse) * (
+                self._out - block_out
+            )
+            self._lse = self._lse - F.logsigmoid(self._lse - block_lse)
+
+    def step(self, out: torch.Tensor, lse: torch.Tensor) -> None:
+        self._out_dtype = out.dtype
+        self._lse_dtype = lse.dtype
+
+        if self._convert_to_f32:
+            out = out.to(torch.float32)
+            lse = lse.to(torch.float32)
+
+        self._merge_one(out, lse)
+
+    def results(self) -> Tuple[torch.Tensor, torch.Tensor]:
+        assert self._out is not None
+        assert self._lse is not None
+        out, lse = self._out, self._lse.squeeze(-1)
+        return out.to(self._out_dtype), lse.to(self._lse_dtype)
+
+
+def _scaled_dot_product_ring_flash_attention(
+    mesh: DeviceMesh,
+    query: torch.Tensor,
+    key: torch.Tensor,
+    value: torch.Tensor,
+    dropout_p: float = 0.0,
+    is_causal: bool = False,
+    return_debug_mask: bool = False,
+    *,
+    scale: Optional[float] = None,
+) -> Tuple[torch.Tensor, ...]:
+    if return_debug_mask:
+        raise NotImplementedError("return_debug_mask is not supported yet")
+
+    return _templated_ring_attention(
+        mesh,
+        aten._scaled_dot_product_flash_attention,
+        query=query,
+        key=key,
+        value=value,
+        is_causal=is_causal,
+        dropout_p=dropout_p,
+        scale=scale,
+    )
+
+
+def _scaled_dot_product_ring_efficient_attention(
+    mesh: DeviceMesh,
+    query: torch.Tensor,
+    key: torch.Tensor,
+    value: torch.Tensor,
+    attn_bias: Optional[torch.Tensor] = None,
+    compute_log_sumexp: bool = True,
+    dropout_p: float = 0.0,
+    is_causal: bool = False,
+    *,
+    scale: Optional[float] = None,
+) -> Tuple[torch.Tensor, ...]:
+    if attn_bias is not None:
+        raise NotImplementedError("attn_bias is not supported yet")
+    if not compute_log_sumexp:
+        raise NotImplementedError("compute_log_sumexp must be set")
+
+    return _templated_ring_attention(
+        mesh,
+        aten._scaled_dot_product_efficient_attention,
+        query=query,
+        key=key,
+        value=value,
+        is_causal=is_causal,
+        attn_bias=attn_bias,
+        dropout_p=dropout_p,
+        scale=scale,
+        compute_log_sumexp=compute_log_sumexp,
+    )
+
+
+class _AttentionOp(Protocol):
+    def __call__(
+        self,
+        query: torch.Tensor,
+        key: torch.Tensor,
+        value: torch.Tensor,
+        **kwargs: object,
+    ) -> Tuple[torch.Tensor, ...]:
+        ...
+
+
+def _ring_rotate(
+    block: torch.Tensor, pg: dist.ProcessGroup, send_to_next: bool
+) -> torch.Tensor:
+    size = dist.get_world_size(pg)
+    dsts = (
+        list(range(1, size)) + [0]
+        if send_to_next
+        else [size - 1] + list(range(0, size - 1))
+    )
+    return ft_c.permute_tensor(block, dsts, pg)
+
+
+def _templated_ring_attention(
+    mesh: DeviceMesh,
+    op: _AttentionOp,
+    query: torch.Tensor,
+    key: torch.Tensor,
+    value: torch.Tensor,
+    is_causal: bool = False,
+    **kwargs: object,
+) -> Tuple[torch.Tensor, ...]:
+    """
+    This is a generalized ring attention implementation that can support multiple attention ops.
+
+    Parameters
+    ----------
+    op:
+        The attention op to use
+    *args:
+        additional args are passed to the op
+    **kwargs:
+        additional kwargs are passed to the op
+
+    Returns
+    -------
+    out:
+        The merged attention output
+    softmax_lse:
+        The logsumexp of the merged attention output
+    """
+    if is_causal and (query.size(2) != key.size(2)):
+        raise NotImplementedError(
+            "is_causal requires the same query and context sequence lengths"
+        )
+
+    if isinstance(mesh, dist.ProcessGroup):
+        pg: Union[dist.ProcessGroup, List[dist.ProcessGroup]] = mesh
+    else:
+        pg = mesh.get_group()
+    assert isinstance(pg, dist.ProcessGroup), "process group must be single dimension"
+    rank = dist.get_rank(pg)
+    size = dist.get_world_size(pg)
+
+    next_kv = None
+
+    # Without making key and value contiguous(), the lose curve is bad.
+    # TODO(fegin): figure out why this is a requirement since SDPA does not have
+    # this requirement.
+    key = key.contiguous()
+    value = value.contiguous()
+
+    sdpa_merger = _SDPAMerger(_convert_to_f32)
+
+    rest: List[Any]
+    out: torch.Tensor
+    logsumexp: torch.Tensor
+
+    for i in range(size):
+        # overlap communication with compute
+        if next_kv is not None:
+            next_kv = _maybe_wait(next_kv)
+            key = next_kv[: key.numel()].reshape(key.shape)
+            value = next_kv[key.numel() :].reshape(value.shape)
+
+        if i < (size - 1):
+            next_kv = torch.cat([key.flatten(), value.flatten()])
+            next_kv = _ring_rotate(next_kv, pg, send_to_next=True)
+
+        is_causal_behavior = _is_causal_behavior(
+            rank=rank, world_size=size, i=i, is_causal=is_causal
+        )
+
+        if is_causal_behavior != _CausalBehavior.SKIP:
+            out, logsumexp, *rest = op(
+                query,
+                key,
+                value,
+                is_causal=is_causal_behavior.value,
+                **kwargs,
+            )
+
+            sdpa_merger.step(out, logsumexp)
+
+    return *sdpa_merger.results(), *rest
+
+
+def _sdpa_handler(
+    op_call: torch._ops.OpOverload,
+    args: Tuple[object, ...],
+    kwargs: Dict[str, object],
+) -> object:
+    # extract local tensor and sharding infos to a OpInfo
+    op_info = DTensor._op_dispatcher.unwrap_to_op_info(op_call, args, kwargs)
+    logger.debug("Dispatching op_call: %s", op_info.schema)
+
+    # sharding propagation
+    # TODO: remove the context parallel strategy from the default propagation
+    # rule. Either figure out how to dynamically enable it or just don't call
+    # propagate.
+    DTensor._op_dispatcher.sharding_propagator.propagate(op_info)
+    output_sharding = op_info.output_sharding
+    assert output_sharding is not None, "output sharding should not be None"
+    assert not output_sharding.needs_redistribute, "inputs need to be redistributed"
+
+    if op_call == aten._scaled_dot_product_flash_attention.default:
+        local_results = _scaled_dot_product_ring_flash_attention(
+            op_info.mesh,
+            *op_info.local_args,  # type: ignore[arg-type]
+            **op_info.local_kwargs,  # type: ignore[arg-type]
+        )
+    elif op_call == aten._scaled_dot_product_efficient_attention.default:
+        local_results = _scaled_dot_product_ring_efficient_attention(
+            op_info.mesh,
+            *op_info.local_args,  # type: ignore[arg-type]
+            **op_info.local_kwargs,  # type: ignore[arg-type]
+        )
+    else:
+        raise NotImplementedError(
+            "CP only supports flash attention and memory efficient attention now."
+        )
+
+    return DTensor._op_dispatcher.wrap(local_results, output_sharding.output_spec)
+
+
+def _sdpa_backward_handler(
+    op_call: torch._ops.OpOverload,
+    args: Tuple[object, ...],
+    kwargs: Dict[str, object],
+) -> object:
+    # Redistribute grad_output tensor to the same placement as output tensor
+    args = list(args)
+    args = tuple(args)
+
+    # extract local tensor and sharding infos to a OpInfo
+    op_info = DTensor._op_dispatcher.unwrap_to_op_info(op_call, args, kwargs)
+    logger.debug("Dispatching op_call: %s", op_info.schema)
+
+    # sharding propagation
+    DTensor._op_dispatcher.sharding_propagator.propagate(op_info)
+    output_sharding = op_info.output_sharding
+    assert output_sharding is not None, "output sharding should not be None"
+    assert not output_sharding.needs_redistribute, "inputs need to be redistributed"
+
+    if op_call == aten._scaled_dot_product_flash_attention_backward.default:
+        local_results = _scaled_dot_product_ring_flash_attention_backward(
+            op_info.mesh,
+            *op_info.local_args,  # type: ignore[arg-type]
+            **op_info.local_kwargs,  # type: ignore[arg-type]
+        )
+    elif op_call == aten._scaled_dot_product_efficient_attention_backward.default:
+        local_results = _scaled_dot_product_ring_efficient_attention_backward(
+            op_info.mesh,
+            *op_info.local_args,  # type: ignore[arg-type]
+            **op_info.local_kwargs,  # type: ignore[arg-type]
+        )
+    else:
+        raise NotImplementedError(f"{op_call=}")
+
+    return DTensor._op_dispatcher.wrap(local_results, output_sharding.output_spec)
+
+
+def _templated_ring_attention_backward(
+    mesh: DeviceMesh,
+    op: _AttentionOp,
+    grad_out: torch.Tensor,
+    grad_out_name: str,
+    query: torch.Tensor,
+    key: torch.Tensor,
+    value: torch.Tensor,
+    out: torch.Tensor,
+    logsumexp: torch.Tensor,
+    is_causal: bool,
+    **kwargs: Any,
+) -> Tuple[torch.Tensor, ...]:
+    pg = mesh.get_group()
+    assert isinstance(pg, dist.ProcessGroup), "must be single dimension"
+    rank = dist.get_rank(pg)
+    size = dist.get_world_size(pg)
+    next_kv = None
+    next_grad_kv = None
+    rest: List[Any]
+    grad_query_, grad_key_, grad_value_ = None, None, None
+
+    accum_dtype = torch.float32 if _convert_to_f32 else query.dtype
+    grad_query = torch.zeros_like(query, dtype=accum_dtype)
+    grad_key = torch.zeros_like(key, dtype=accum_dtype)
+    grad_value = torch.zeros_like(value, dtype=accum_dtype)
+
+    key = key.contiguous()
+    value = value.contiguous()
+    for i in range(size):
+        if next_kv is not None:
+            buffer = _maybe_wait(next_kv)
+            pointer = 0
+            key = buffer[pointer : pointer + key.numel()].reshape(key.shape)
+            pointer += key.numel()
+            value = buffer[pointer : pointer + value.numel()].reshape(value.shape)
+            pointer += value.numel()
+
+        if i != size - 1:
+            next_kv = torch.cat([key.flatten(), value.flatten()])
+            next_kv = _ring_rotate(next_kv, pg, send_to_next=True)
+
+        is_causal_behavior = _is_causal_behavior(
+            rank=rank, world_size=size, i=i, is_causal=is_causal
+        )
+
+        if is_causal_behavior != _CausalBehavior.SKIP:
+            kwargs[grad_out_name] = grad_out
+            grad_query_, grad_key_, grad_value_, *rest = op(
+                query=query,
+                key=key,
+                value=value,
+                out=out,
+                logsumexp=logsumexp,
+                is_causal=is_causal_behavior.value,
+                **kwargs,
+            )
+        else:
+            grad_query_ = torch.zeros_like(query, dtype=accum_dtype)
+            grad_key_ = torch.zeros_like(key, dtype=accum_dtype)
+            grad_value_ = torch.zeros_like(value, dtype=accum_dtype)
+
+        # Get the grad key and grad value for the i round.
+        if i > 0:
+            pointer = 0
+            assert next_grad_kv is not None
+            next_grad_kv = _maybe_wait(next_grad_kv)
+            grad_key = next_grad_kv[pointer : pointer + grad_key.numel()].reshape(
+                grad_key.shape
+            )
+            pointer += grad_key.numel()
+            grad_value = next_grad_kv[pointer : pointer + grad_value.numel()].reshape(
+                grad_value.shape
+            )
+
+        grad_key += grad_key_
+        grad_value += grad_value_
+
+        # Send the key, value, grad key, and grad value to the next rank.
+        next_grad_kv = torch.cat([grad_key.flatten(), grad_value.flatten()])
+        next_grad_kv = _ring_rotate(next_grad_kv, pg, send_to_next=True)
+        grad_query += grad_query_
+
+    assert next_grad_kv is not None
+    assert grad_key_ is not None
+    assert grad_value_ is not None
+    grad_query = grad_query.to(query.dtype)
+    next_grad_kv = _maybe_wait(next_grad_kv).to(key.dtype)
+    grad_key = next_grad_kv[: grad_key.numel()].reshape(grad_key.shape)
+    grad_value = next_grad_kv[grad_value.numel() :].reshape(grad_value.shape)
+    return (
+        grad_query,
+        grad_key,
+        grad_value,
+        *rest,
+    )
+
+
+def _scaled_dot_product_ring_flash_attention_backward(
+    mesh: DeviceMesh,
+    grad_out: torch.Tensor,
+    query: torch.Tensor,
+    key: torch.Tensor,
+    value: torch.Tensor,
+    out: torch.Tensor,
+    logsumexp: torch.Tensor,
+    cum_seq_q: torch.Tensor,
+    cum_seq_k: torch.Tensor,
+    max_q: int,
+    max_k: int,
+    dropout_p: float,
+    is_causal: bool,
+    philox_seed: torch.Tensor,
+    philox_offset: torch.Tensor,
+    *,
+    scale: Optional[float] = None,
+) -> Tuple[torch.Tensor, ...]:
+    return _templated_ring_attention_backward(
+        mesh,
+        aten._scaled_dot_product_flash_attention_backward.default,
+        grad_out=grad_out,
+        grad_out_name="grad_out",
+        query=query,
+        key=key,
+        value=value,
+        out=out,
+        logsumexp=logsumexp,
+        is_causal=is_causal,
+        cum_seq_q=cum_seq_q,
+        cum_seq_k=cum_seq_k,
+        max_q=max_q,
+        max_k=max_k,
+        dropout_p=dropout_p,
+        philox_seed=philox_seed,
+        philox_offset=philox_offset,
+        scale=scale,
+    )
+
+
+def _scaled_dot_product_ring_efficient_attention_backward(
+    mesh: DeviceMesh,
+    grad_out: torch.Tensor,
+    query: torch.Tensor,
+    key: torch.Tensor,
+    value: torch.Tensor,
+    bias: torch.Tensor,
+    out: torch.Tensor,
+    logsumexp: torch.Tensor,
+    philox_seed: torch.Tensor,
+    philox_offset: torch.Tensor,
+    dropout_p: float,
+    grad_input_mask: Tuple[bool, ...],
+    is_causal: bool = False,
+    *,
+    scale: Optional[float] = None,
+) -> Tuple[torch.Tensor, ...]:
+    return _templated_ring_attention_backward(
+        mesh,
+        aten._scaled_dot_product_efficient_attention_backward.default,
+        grad_out=grad_out,
+        grad_out_name="grad_out_",
+        query=query,
+        key=key,
+        value=value,
+        attn_bias=bias,
+        out=out,
+        logsumexp=logsumexp,
+        philox_seed=philox_seed,
+        philox_offset=philox_offset,
+        dropout_p=dropout_p,
+        grad_input_mask=grad_input_mask,
+        is_causal=is_causal,
+        scale=scale,
+    )
+
+
+customized_ops = {
+    aten._scaled_dot_product_flash_attention.default: _sdpa_handler,
+    aten._scaled_dot_product_flash_attention_backward.default: _sdpa_backward_handler,
+    aten._scaled_dot_product_efficient_attention.default: _sdpa_handler,
+    aten._scaled_dot_product_efficient_attention_backward.default: _sdpa_backward_handler,
+}
+
+
+_replaced_functions: Dict[Callable, Tuple[str, Callable]] = {}
+
+
+def _distribute_function(
+    fn: Callable,
+    fn_module: types.ModuleType,
+    device_mesh: DeviceMesh,
+    input_fn: Optional[Callable] = None,
+    output_fn: Optional[Callable] = None,
+) -> None:
+    """
+    ``distribute_function`` is an experimental API that allows users to "distribute"
+    the inputs and outputs of a function. Similar to ``distribute_module``, this API
+    installs hooks to the ``fn`` to convert the inputs and outputs. There are two
+    major differences between ``distribute_function`` and ``distribute_module``.
+    First, a function does not have parammeters and buffers, as a result,
+    ``distribute_function`` itself won't convert any parameters/buffers but simply
+    install the input and output hooks.  The tensor conversion will happen in the hooks.
+    Another difference is an nn.Module subclass can have several instances and each
+    instance be fed into ``distribute_module`` independently with affecting other
+    instance. On the other hand, function is a singleton object. So if a function
+    is distributed by ``distribute_function`` all subsequent calls to the function
+    will invoke the installed hooks.
+
+    Args:
+        fn (Callable): the function to be distributed.
+        fn_module (types.ModuleType): the Python module that the function is declared.
+            e.g., if ``fn`` is ``torch.nn.functional.scaled_dot_product_attention``,
+            ``fn_module`` is ``torch.nn.functional``.
+        device_mesh (:class:`DeviceMesh`): the device mesh that will be used by the
+            input and output hooks to distribute the tensors.
+        input_fn (Optioinal[Callable]): the hook to distribute or convert the input
+            arguments of ``fn``.
+        output_fn (Optioinal[Callable]): the hook to distribute or convert the output
+            arguments of ``fn``.
+    """
+
+    def wrapper(
+        target_fn: Callable, input_fn: Optional[Callable], output_fn: Optional[Callable]
+    ) -> Callable:
+        def inner_fn(*args: Tuple[Any, ...], **kwargs: Dict[str, Any]) -> Any:
+            if input_fn is not None:
+                args, kwargs = input_fn(device_mesh, *args, **kwargs)
+            output = target_fn(*args, **kwargs)
+            if output_fn is not None:
+                output = output_fn(device_mesh, output)
+            return output
+
+        return inner_fn
+
+    global _replaced_functions
+
+    if fn in _replaced_functions:
+        return
+
+    wrapper_fn = wrapper(fn, input_fn, output_fn)
+    setattr(fn_module, fn.__name__, wrapper_fn)
+    _replaced_functions[wrapper_fn] = (fn.__name__, fn)
+
+
+def _restore_function(fn: Callable, fn_module: types.ModuleType) -> None:
+    """Restore the function that is replaced by _distribute_function."""
+    global _original_functions
+    global _wrapper_functions
+
+    if fn not in _replaced_functions:
+        return
+
+    original_name, original_fn = _replaced_functions[fn]
+    setattr(fn_module, original_name, original_fn)
+
+
+@contextlib.contextmanager
+def _enable_cp_dispatcher() -> Generator[None, None, None]:
+    """Enables DTensor dispatcher to dispatch SDPA to CP."""
+    old_handlers = DTensor._op_dispatcher._custom_op_handlers
+    DTensor._op_dispatcher._custom_op_handlers = {**old_handlers, **customized_ops}
+
+    yield
+
+    DTensor._op_dispatcher._custom_op_handlers = old_handlers
+
+
+class _AttentionContextParallel(ParallelStyle):
+    """
+    Applies context parallel optimizations to the attention layer.
+
+    This will work for nn.MultiHeadedAttention and custom attention layers that
+    call F.scaled_dotproduct_attention with a simliar signature.
+
+    This expects the `forward` method consumes either:
+
+    * a single tensor for self attention
+    * one argument for each of: query, key, value
+
+    This currently only supports ring attention and the
+    SDPBackend.FLASH_ATTENTION backend. See sdpa_kernel.
+
+    Non-flash attention backends will result in incorrect results.
+    """
+
+    # use a weakref dictionary to store context managers for each nn.Module
+    _CONTEXT_MANAGERS: "weakref.WeakKeyDictionary[nn.Module, Any]" = (
+        weakref.WeakKeyDictionary()
+    )
+
+    def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
+        if not isinstance(device_mesh, DeviceMesh):
+            raise ValueError(
+                f"{type(device_mesh)} is not supported by {type(self)} yet."
+            )
+
+        if not device_mesh.ndim == 1:
+            raise ValueError
+
+        return distribute_module(
+            module,
+            device_mesh,
+            input_fn=self._input_fn,  # type: ignore[arg-type]
+            output_fn=self._output_fn,  # type: ignore[arg-type]
+        )
+
+    @classmethod
+    def _input_fn(
+        cls,
+        module: nn.Module,
+        inputs: Tuple[Union[torch.Tensor, int, float], ...],
+        device_mesh: DeviceMesh,
+    ) -> Tuple[Union[torch.Tensor, int, float], ...]:
+        # TODO(d4l3k); this should be Shard(2), need to fix Linear layer rules
+        placement = [Replicate()]
+
+        def backward_hook(grad: torch.Tensor) -> None:
+            if module in cls._CONTEXT_MANAGERS:
+                cls._CONTEXT_MANAGERS[module].__exit__(None, None, None)
+                del cls._CONTEXT_MANAGERS[module]
+
+        # convert inputs to DTensor
+        inp = []
+        for input in inputs:
+            if isinstance(input, torch.Tensor) and not isinstance(input, DTensor):
+                input = DTensor.from_local(
+                    input.contiguous(), device_mesh, placement, run_check=False
+                )
+
+            if isinstance(input, torch.Tensor) and input.requires_grad:
+                input.register_hook(backward_hook)
+
+            inp.append(input)
+
+        manager = _enable_cp_dispatcher()
+        manager.__enter__()
+        cls._CONTEXT_MANAGERS[module] = manager
+
+        return tuple(inp)
+
+    @classmethod
+    def _output_fn(
+        cls,
+        module: nn.Module,
+        outputs: Union[torch.Tensor, Tuple[Union[torch.Tensor, int, float], ...]],
+        device_mesh: DeviceMesh,
+    ) -> Union[
+        Union[torch.Tensor, int, float], Tuple[Union[torch.Tensor, int, float], ...]
+    ]:
+        cls._CONTEXT_MANAGERS[module].__exit__(None, None, None)
+        del cls._CONTEXT_MANAGERS[module]
+
+        def backward_hook(grad: torch.Tensor) -> None:
+            if module not in cls._CONTEXT_MANAGERS:
+                manager = _enable_cp_dispatcher()
+                manager.__enter__()
+                cls._CONTEXT_MANAGERS[module] = manager
+
+        # back to local tensor
+        out = []
+        for output in [outputs] if isinstance(outputs, torch.Tensor) else outputs:
+            output = output.to_local() if isinstance(output, DTensor) else output
+
+            if isinstance(output, torch.Tensor) and output.requires_grad:
+                output.register_hook(backward_hook)
+
+            out.append(output)
+
+        if isinstance(outputs, torch.Tensor):
+            return out[0]
+
+        return tuple(out)
+
+
+@contextlib.contextmanager
+def _context_parallel(seq_dim: int, mesh: DeviceMesh) -> Generator[None, None, None]:
+    """Replace SDPA with the CP-wrapped version and enable DTensor CP dispatcher."""
+
+    def attention_input_fn(
+        mesh: DeviceMesh, *args: Tuple[Any, ...], **kwargs: Dict[str, Any]
+    ) -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
+        placement = [Shard(seq_dim)]
+        all_args = []
+
+        for arg in itertools.chain(args, kwargs.values()):
+            if isinstance(arg, torch.Tensor) and not isinstance(arg, DTensor):
+                arg = DTensor.from_local(arg, mesh, placement, run_check=False)
+
+            all_args.append(arg)
+
+        new_args = tuple(all_args[0 : len(args)])
+        new_kwargs = dict(zip(kwargs.keys(), all_args[len(args) :]))
+        return new_args, new_kwargs
+
+    def attention_output_fn(mesh: DeviceMesh, outputs: Any) -> Any:
+        new_outputs = []
+        for output in [outputs] if isinstance(outputs, torch.Tensor) else outputs:
+            output = output.to_local() if isinstance(output, DTensor) else output
+            new_outputs.append(output)
+
+        if isinstance(outputs, torch.Tensor):
+            return new_outputs[0]
+
+        return tuple(new_outputs)
+
+    # TODO: provide a more robust way to replace SDPA.
+    # Currently we use monkey patch to replace scaled_dot_product_attention with the
+    # wrapped fn. This is okay if users do `import torch.nn.functional` but will not
+    # work if users do `import torch.nn.functional.scaled_dot_product_attention`.
+    _distribute_function(
+        F.scaled_dot_product_attention,
+        F,
+        mesh,
+        attention_input_fn,
+        attention_output_fn,
+    )
+
+    with _enable_cp_dispatcher():
+        yield
+
+    _restore_function(F.scaled_dot_product_attention, F)
+
+
+def _get_sequence_shard(
+    buffer: torch.Tensor, mesh: DeviceMesh, seq_dim: int
+) -> torch.Tensor:
+    return buffer.chunk(mesh.size(), dim=seq_dim)[mesh.get_local_rank()]
+
+
+def _context_parallel_buffers(
+    mesh: DeviceMesh,
+    buffers: List[torch.Tensor],
+    buffer_seq_dims: List[int],
+) -> List[torch.Tensor]:
+    """Shard the buffers along the sequence dimensions according to CP rules."""
+    new_buffers = []
+    for buffer, seq_dim in zip(buffers, buffer_seq_dims):
+        new_buffers.append(_get_sequence_shard(buffer, mesh, seq_dim))
+
+    return new_buffers
+
+
+@contextlib.contextmanager
+@torch.no_grad()
+def context_parallel(
+    mesh: DeviceMesh,
+    *,
+    buffers: Optional[List[torch.Tensor]] = None,
+    buffer_seq_dims: Optional[List[int]] = None,
+    no_restore_buffers: Optional[Set[torch.Tensor]] = None,
+) -> Generator[None, None, None]:
+    """
+
+    ``context_parallel`` is an experimental API to enable context
+    parallelism (CP). This API performs two actions: 1) patch the SDPA
+    (``torch.nn.functional.scaled_dot_product_attention``) with the CP-enabled
+    one, 2) shard ``buffers`` along the sequence dimension and each rank will
+    preserve the corresponding shard according ``mesh``.
+
+    Args:
+        mesh (:class:`DeviceMesh`): the device mesh for the context parallelism.
+        buffers (Optional[List[torch.Tensor]]): buffers that the usage depend
+            on the sequence dimension. Examples are input batch, labels and
+            positional embedding buffers. These buffers must be sharded along
+            the sequence dimension to ensure the accuracy. The sharding will
+            happen in-place, the buffer's shape will change within the context.
+            The buffers will be restored after the context finishes.
+            ``no_restore_buffers`` can be used to specify which buffers don't
+            need to be restored. Note that ``buffers`` should not contain any
+            nn.Parameter.
+        buffer_seq_dims (Optional[List[int]]): the sequence dimensions of ``buffers``.
+        no_restore_buffers (Optional[Set[torch.Tensor]]): buffers in these set
+            won't be restored after the context exits. This set must be a subset
+            of ``buffers``. If the buffers won't be used after the context exits,
+            these buffers can be put in this list to avoid extra restore time.
+
+    .. warning::
+        `torch.distributed._tensor.experimental.attention.context_parallel` is a
+        prototype feature in PyTorch. The API is subject to change.
+    """
+    buffers = [] if buffers is None else buffers
+    buffer_seq_dims = [] if buffer_seq_dims is None else buffer_seq_dims
+    no_restore_buffers = set() if no_restore_buffers is None else no_restore_buffers
+
+    if len(buffers) != len(buffer_seq_dims):
+        raise ValueError(
+            "`seq_dims` must have the same number of elements as `buffers`."
+        )
+
+    for buffer in no_restore_buffers:
+        # Cannot use `if not buffer in buffers` which will incur tensor comparison.
+        if not any(b is buffer for b in buffers):
+            raise ValueError("`no_restore_buffers` must be a subset of `buffers`.")
+
+    original_buffers = [None if b in no_restore_buffers else b.clone() for b in buffers]
+
+    chunks = _context_parallel_buffers(mesh, buffers, buffer_seq_dims)
+    for buffer, chunk in zip(buffers, chunks):
+        chunk = chunk.clone()
+        buffer.resize_(chunk.shape)
+        buffer.copy_(chunk)
+
+    with _context_parallel(seq_dim=2, mesh=mesh):
+        yield
+
+    for buffer, original_buffer in zip(buffers, original_buffers):
+        if original_buffer is not None:
+            buffer.resize_(original_buffer.shape)
+            buffer.copy_(original_buffer)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/_func_map.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/_func_map.py
new file mode 100644
index 0000000000000000000000000000000000000000..23b69373e74e57d3120ee449c1365e1872098076
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/_func_map.py
@@ -0,0 +1,228 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and affiliates
+from typing import Callable, Optional, Sequence, Tuple, Union
+
+import torch
+from torch.distributed._functional_collectives import AsyncCollectiveTensor
+from torch.distributed.tensor import DeviceMesh, DTensor
+from torch.distributed.tensor.placement_types import Placement
+
+
+try:
+    from torch.utils import _cxx_pytree as pytree
+except ImportError:
+    from torch.utils import _pytree as pytree  # type: ignore[no-redef]
+
+
+__all__ = ["local_map"]
+
+PlacementType = Optional[Sequence[Placement]]
+InputPlacements = Optional[Tuple[PlacementType, ...]]
+OutputPlacements = Union[PlacementType, Tuple[PlacementType, ...]]
+
+
+def local_map(
+    func: Callable,
+    out_placements: OutputPlacements,
+    in_placements: Optional[InputPlacements] = None,
+    device_mesh: Optional[DeviceMesh] = None,
+    *,
+    redistribute_inputs: bool = False,
+):
+    """
+    :meth:`local_map` is an experimental API that allows users to pass :class:`DTensor` s
+    to a function that is written to be applied on ``torch.Tensor`` s. It is done by extracting
+    the local components of :class:`DTensor`, call the function, and wrap the outputs to
+    :class:`DTensor` according to the ``out_placements``.
+
+    Args:
+        func (Callable): the function to be applied on each local shard of
+            :class:`DTensor` s.
+        out_placements (Union[`PlacementType`, Tuple[`PlacementType`, ...]]):
+            the desired placements of the :class:`DTensor` s in ``func``'s flattened output.
+            If the flattened ``output`` is a single value, the ``out_placements`` should be
+            of type `PlacementType`. Otherwise if the flattened ``output`` has multiple
+            values, the ``out_placements`` should be a tuple of `PlacementType` values 1:1
+            mapping to the flattened ``output``.
+            Besides, for :class:`Tensor` output, we use `PlacementType` as its
+            placements (a `Tuple[Placement]` value). For non-Tensor output, the `PlacementType`
+            should be `None`.
+            Note that the only exception is when no :class:`DTensor` argument is passed
+            in. In this case, even if `out_placements` is not `None`, the result function
+            should ignore the desired placements because the function is not running with
+            :class:`DTensor` s.
+        in_placements (Tuple[`PlacementType`, ...], optional):
+            the required placements of the :class:`DTensor` s in the flattened inputs of ``func``.
+            If ``in_placements`` is specified, :meth:`local_map` would examine whether the
+            placements of each :class:`DTensor` argument is the same as the required
+            placements or not. If the placements are not the same and
+            ``redistribute_inputs`` is ``False``, an exception will be raised. Otherwise if
+            ``redistribute_inputs`` is ``True``, the argument will be first redistributed to
+            the required sharding placements before passing its local tensor to ``func``.
+            The only exception is when required placements are not ``None`` and the
+            argument is a :class:`torch.Tensor`. In this case, the placements examination
+            will be skipped and the argument will be directly passed to ``func``.
+            If ``in_placements`` is ``None``, no placements examination will be performed.
+            Default: None
+        device_mesh (:class:`DeviceMesh`, optional):
+            the device mesh that all the :class:`DTensor` s are placed on. If not
+            specified, this will be inferred from the input :class:`DTensor` s' device
+            mesh. `local_map` requires every :class:`DTensor` s to be placed on the same
+            device mesh. Default: None.
+        redistribute_inputs (bool, optional):
+            the bool value indicating whether to reshard the input :class:`DTensor` s when
+            their placements are different from the required input placements. If this
+            value is ``False`` and some :class:`DTensor` input has a different placement,
+            an exception will be raised. Default: False.
+
+    Returns:
+        A ``Callable`` that applies ``func`` to each local shard of the input :class:`DTensor`
+        and returns a :class:`DTensor` constructed from the return value of ``func``.
+
+    Raises:
+        AssertionError: If the input :class:`DTensor` is not placed on the same device
+            mesh, or if they are placed on a different device mesh than the ``device_mesh``
+            argument passed in.
+
+        AssertionError: For any non-DTensor output, we require its corresponding
+            output placement in ``out_placements`` be None. An AssertionError will be raised
+            if this is not the case.
+
+        ValueError: If ``redistribute_inputs=False`` but the input :class:`DTensor` needs
+            a redistribution according to ``in_placements``.
+
+    Example:
+        >>> # xdoctest: +SKIP("distributed")
+        >>> def mm_allreduce_forward(device_mesh, W, X):
+        >>>     partial_sum_tensor = torch.mm(W, X)
+        >>>     reduced_tensor = funcol.all_reduce(partial_sum_tensor, "sum", device_mesh)
+        >>>     return reduced_tensor
+        >>>
+        >>> W = torch.randn(12, 8, requires_grad=False)
+        >>> X = torch.randn(8, 16, requires_grad=False)
+        >>> Y = torch.mm(W, X)
+        >>> row_wise = [Shard(0)]  # row-wise sharding placements on 1-d mesh
+        >>> col_wise = [Shard(1)]  # col-wise sharding placements on 1-d mesh
+        >>>
+        >>> # local_mm_allreduce_forward is the function wrapped with DTensor/Tensor convertion
+        >>> local_mm_allreduce_forward = local_map(
+        >>>     mm_allreduce_forward,
+        >>>     out_placements=[Replicate()],
+        >>>     in_placements=[col_wise, row_wise],
+        >>>     device_mesh=device_mesh,
+        >>> )
+        >>>
+        >>> W_dt = distribute_tensor(W, device_mesh, (col_wise))  # col-wisely sharded W tensor
+        >>> X_dt = distribute_tensor(X, device_mesh, (row_wise))  # row-wisely sharded X tensor
+        >>> Y_dt = local_mm_allreduce_forward(device_mesh, W_dt, X_dt)  # apply local_mm_allreduce_forward to DTensors
+
+    .. note:: This API is currently experimental and subject to change
+    """
+
+    def wrapped(*args, **kwargs):
+        # process input args
+        flat_args, args_spec = pytree.tree_flatten(args)
+        if in_placements is not None:
+            assert len(in_placements) == len(flat_args), (
+                f"in_placements length {len(in_placements)} does not match the number "
+                f"of input args {len(flat_args)}!"
+            )
+
+        # we assume every DTensor object is placed on the same device mesh
+        flat_local_args = []
+        nonlocal device_mesh  # access var device_mesh from the outer scope
+        seen_dtensor_arg = False
+        for idx, arg in enumerate(flat_args):
+            if isinstance(arg, DTensor):
+                # TODO: the current code doesn't consider the uneven sharding case
+                # Need to think about what the consequence is when the input DTensor
+                # is uneven sharded.
+                if device_mesh is None:  # infer device mesh from the DTensor arg
+                    device_mesh = arg.device_mesh
+
+                # this function is applied to at least one DTensor argument
+                seen_dtensor_arg = True
+
+                assert arg.device_mesh == device_mesh, (
+                    f"arg {arg} in local_map has a mismatched device mesh: "
+                    f"{arg} has device mesh {arg.device_mesh} while "
+                    f"the expected device mesh is {device_mesh}!"
+                )
+                if in_placements is not None:
+                    spec = in_placements[idx]
+                    assert (
+                        spec is not None
+                    ), f"DTensor input {arg} expects placements but received {spec}!"
+
+                    if not isinstance(spec, tuple):
+                        spec = tuple(spec)
+
+                    if arg.placements != spec:
+                        if redistribute_inputs:
+                            # redistribute to input placements
+                            arg = arg.redistribute(device_mesh, spec)
+                        else:
+                            raise ValueError(
+                                f"arg {arg} in local_map has a mismatched placements: "
+                                f"arg placements is {arg.placements} but the input "
+                                f"placements is {spec}! "
+                                "If redistribute_inputs is wanted, set "
+                                "redistribute_inputs=True to local_map."
+                            )
+
+                local_arg = arg.to_local()
+                if isinstance(local_arg, AsyncCollectiveTensor):
+                    local_arg = local_arg.wait()
+
+                flat_local_args.append(local_arg)
+            else:
+                # Non-Tensor input must have None in `in_placements`
+                if in_placements is not None and not isinstance(arg, torch.Tensor):
+                    spec = in_placements[idx]
+                    assert spec is None, (
+                        f"Non-Tensor input {arg} expects None placements "
+                        f"but received {spec}!"
+                    )
+
+                flat_local_args.append(arg)
+
+        local_args = pytree.tree_unflatten(flat_local_args, args_spec)
+
+        out = func(*local_args, **kwargs)
+
+        if seen_dtensor_arg:
+            # process output
+            flat_out, out_spec = pytree.tree_flatten(out)
+
+            flat_dist_out = []
+            out_placements_tuple = (
+                out_placements
+                if isinstance(out_placements, tuple)
+                else (out_placements,)
+            )
+            assert len(flat_out) == len(out_placements_tuple), (
+                "local_map requires one PlacementType be provided for each output value,"
+                f" received {len(out_placements_tuple)} out_placements but"
+                f" {len(flat_out)} is expected!"
+            )
+            for out, spec in zip(flat_out, out_placements_tuple):
+                if isinstance(out, torch.Tensor):
+                    assert not isinstance(
+                        out, DTensor
+                    ), f"torch.Tensor output expected but received {type(out)}: {out}"
+
+                    flat_dist_out.append(
+                        DTensor.from_local(out, device_mesh, spec, run_check=False)
+                    )
+                else:
+                    assert (
+                        spec is None
+                    ), f"Non-tensor output {out} expects None placements but received {spec}!"
+
+                    flat_dist_out.append(out)
+
+            return pytree.tree_unflatten(flat_dist_out, out_spec)
+        else:
+            return out
+
+    return wrapped
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/_register_sharding.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/_register_sharding.py
new file mode 100644
index 0000000000000000000000000000000000000000..c526e2e0a44090a572b739b01b48128b721d44b2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/_register_sharding.py
@@ -0,0 +1,136 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and affiliates
+from functools import partial
+from typing import Callable, List, Sequence, Tuple, Union
+
+import torch
+from torch._ops import OpOverload
+from torch.distributed.tensor import DeviceMesh, DTensor
+from torch.distributed.tensor._op_schema import (
+    _is_inplace_op,
+    OpSchema,
+    OpStrategy,
+    PlacementList,
+    RuntimeSchemaInfo,
+    StrategyType,
+    TupleStrategy,
+)
+from torch.distributed.tensor._ops.utils import expand_to_full_mesh_op_strategy
+
+
+__all__ = ["register_sharding"]
+
+
+def register_sharding(op: Union[OpOverload, List[OpOverload]]):
+    """
+    :meth:`register_sharding` is an experimental API that allows users to register sharding
+    strategies for an operator when the tensor inputs and outputs are DTensor.
+    It can be useful when: (1) there doesn't exist a default sharding strategy for ``op``,
+    e.g. when ``op`` is a custom operator that is not supported by :class:`DTensor`; (2)
+    when users would like to overwrite default sharding strategies of existing operators.
+
+    Args:
+        op (Union[OpOverload, List[OpOverload]]):
+            An op or a list of ops to register the customized sharding function.
+
+    Returns:
+        A function decorator which can be used to wrap a function that defines the sharding
+        strategy for the operator specified in ``op``. The defined sharding strategy will be
+        registered to DTensor and will override the default sharding strategy if DTensor has
+        already implemented the operator. The customized sharding function takes the same inputs
+        as the original op (except that if an arg is a :class:`torch.Tensor`, it will be
+        replaced by a tensor-like object that DTensor uses internally). The function should
+        return a sequence of 2-tuples, each specifying acceptable output placements and its
+        corresponding intput placements.
+
+    Example:
+        >>> # xdoctest: +SKIP("distributed")
+        >>> @register_sharding(aten._softmax.default)
+        >>> def custom_softmax_sharding(x, dim, half_to_float):
+        >>>     softmax_dim = dim if dim >= 0 else dim + x.ndim
+        >>>     acceptable_shardings = []
+        >>>
+        >>>     all_replicate = ([Replicate()], [Replicate(), None, None])
+        >>>     acceptable_shardings.append(all_replicate)
+        >>>
+        >>>     for sharding_dim in range(x.ndim):
+        >>>         if sharding_dim != softmax_dim:
+        >>>             all_sharded = (
+        >>>                 [Shard(sharding_dim)],
+        >>>                 [Shard(sharding_dim), None, None],
+        >>>             )
+        >>>             acceptable_shardings.append(all_sharded)
+        >>>
+        >>>     return acceptable_shardings
+
+    .. note:: This API is currently experimental and subject to change
+    """
+
+    def custom_strategy(
+        custom_sharding_fn: Callable[
+            ..., Sequence[Tuple[PlacementList, PlacementList]]
+        ],
+        mesh: DeviceMesh,
+        op_schema: OpSchema,
+    ) -> StrategyType:
+        def strategy_to_spec(strategy: object) -> object:
+            if isinstance(strategy, OpStrategy):
+                # take the output spec from the first strategy
+                return strategy.strategies[0].output_spec
+            elif isinstance(strategy, TupleStrategy):
+                return tuple(strategy_to_spec(s) for s in strategy.childs)
+            else:
+                return strategy
+
+        args_schema = tuple(strategy_to_spec(i) for i in op_schema.args_schema)
+        kwargs_schema = {
+            k: strategy_to_spec(v) for k, v in op_schema.kwargs_schema.items()
+        }
+
+        acceptable_shardings = custom_sharding_fn(*args_schema, **kwargs_schema)
+
+        single_mesh_dim_strategies: List[PlacementList] = []
+        for output_specs, input_specs in acceptable_shardings:
+            single_mesh_dim_strategies.append(output_specs + input_specs)
+
+        # TODO: handle out variant ops
+        return expand_to_full_mesh_op_strategy(
+            mesh,
+            op_schema,
+            single_mesh_dim_strategies,
+            input_index=len(op_schema.op._schema.returns),
+            inplace_op=_is_inplace_op(op_schema.op),
+        )
+
+    def wrapper(custom_sharding_fn):
+        def derive_schema_info(op):
+            # NOTE: without user directly providing RuntimeSchemaInfo, for now
+            #       we create it in a conservative fashion as follows:
+            #       1. let static_argnum be the first int argument
+            #       2. let static_kwargkey include all the int type kwargs
+            #       3. always set needs_pytree=True
+            static_argnum = 100
+            static_kwargkey: List[str] = []
+            for i, arg in enumerate(op._schema.arguments):
+                if isinstance(arg.type, torch.IntType) or (
+                    isinstance(arg.type, torch.OptionalType)
+                    and isinstance(arg.type.getElementType(), torch.IntType)
+                ):
+                    static_argnum = min(i, static_argnum)
+                    if arg.kwarg_only:
+                        static_kwargkey.append(arg.name)
+            return RuntimeSchemaInfo(
+                static_argnum, static_kwargkey or None, needs_pytree=True
+            )
+
+        overloads = op if isinstance(op, list) else [op]
+        for overload in overloads:
+            DTensor._op_dispatcher.sharding_propagator.register_op_strategy(
+                overload,
+                partial(custom_strategy, custom_sharding_fn),
+                derive_schema_info(overload),
+            )
+
+        return custom_sharding_fn
+
+    return wrapper
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/_tp_transform.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/_tp_transform.py
new file mode 100644
index 0000000000000000000000000000000000000000..81b47c9b5a7d3b14d8176177286681818b99dd51
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/experimental/_tp_transform.py
@@ -0,0 +1,552 @@
+# mypy: allow-untyped-defs
+import copy
+import operator
+from typing import Any, cast, Dict, List, Optional, Sequence, Tuple
+
+import torch
+from torch._subclasses.fake_tensor import FakeTensor
+from torch.distributed.tensor import DeviceMesh, distribute_tensor, DTensor
+from torch.distributed.tensor._dtensor_spec import DTensorSpec, TensorMeta
+from torch.distributed.tensor._op_schema import (
+    OpSchema,
+    OutputSharding,
+    OutputSpecType,
+    PlacementStrategy,
+)
+from torch.distributed.tensor._redistribute import redistribute_local_tensor
+from torch.distributed.tensor.parallel.style import ColwiseParallel, ParallelStyle
+from torch.distributed.tensor.placement_types import Placement, Replicate, Shard
+from torch.export import ExportedProgram
+from torch.export.exported_program import ExportGraphSignature
+from torch.fx import GraphModule
+from torch.fx.experimental.proxy_tensor import make_fx
+from torch.fx.node import Node
+from torch.fx.passes.infra.pass_base import PassBase, PassResult
+from torch.fx.passes.shape_prop import _extract_tensor_metadata
+from torch.utils import _pytree as pytree
+
+
+__all__ = ["tensor_parallel_transformation"]
+
+aten = torch.ops.aten
+
+
+def tensor_parallel_transformation(
+    exported_program: ExportedProgram,
+    rank: int,
+    world_size: int,
+    device_type: str,
+    parallel_strategies: Dict[str, ParallelStyle],
+) -> ExportedProgram:
+    """
+    The entry point function to perform graph transformations on an exported program
+    to transform a single-device graph into a tensor parallel graph.
+
+    .. warning::
+        This API is experimental and subject to change.
+    """
+
+    gm = exported_program.graph_module
+    sig = copy.deepcopy(exported_program.graph_signature)
+    state_dict = copy.copy(exported_program.state_dict)
+
+    with gm._set_replace_hook(sig.get_replace_hook()):
+        res = _TensorParallelTransformPass(
+            rank,
+            world_size,
+            device_type,
+            state_dict,
+            exported_program.graph_signature,
+            parallel_strategies,
+        )(gm)
+        assert res is not None
+        gm = res.graph_module
+
+    return exported_program._update(gm, sig, state_dict=state_dict)
+
+
+class _TensorParallelTransformPass(PassBase):
+    """
+    This pass is responsible for transforming a single-device graph into a tensor parallel
+    graph. It will mark the placement strategy of each node in the graph,
+    partition the graph into distributed graph, then shard the parameters/buffers accordingly.
+    """
+
+    def __init__(
+        self,
+        rank: int,
+        world_size: int,
+        device_type: str,
+        state_dict: Dict[str, torch.Tensor],
+        graph_signature: ExportGraphSignature,
+        parallel_strategies: Dict[str, ParallelStyle],
+    ) -> None:
+        super().__init__()
+        self.rank = rank
+        self.mesh = DeviceMesh(device_type, torch.arange(world_size))
+        self.state_dict: Dict[str, torch.Tensor] = state_dict
+        self.graph_signature = graph_signature
+        self.parallel_strategies = parallel_strategies
+
+    def call(self, graph_module) -> PassResult:
+        gm = copy.deepcopy(graph_module)
+
+        parameter_placements = _generate_parameter_and_buffer_placements(
+            list(self.state_dict.keys()), self.parallel_strategies
+        )
+        placement_strategies = _mark_sharding(
+            gm, self.graph_signature, self.mesh, parameter_placements
+        )
+        _partitioner(gm)
+        _shard_state_dict(
+            self.state_dict, placement_strategies, self.graph_signature, self.mesh
+        )
+        return PassResult(gm, True)
+
+
+def _generate_parameter_and_buffer_placements(
+    params_and_buffers: List[str],
+    parallel_strategies: Dict[str, ParallelStyle],
+) -> Dict[str, Placement]:
+    """
+    Build parameter placements based on the give parallel style of linear layers.
+    """
+    parameter_placements: Dict[str, Placement] = {}
+    for linear_fqn, parallel_style in parallel_strategies.items():
+        weight_fqn = f"{linear_fqn}.weight"
+        bias_fqn = f"{linear_fqn}.bias"
+        assert weight_fqn in params_and_buffers
+        parameter_placements[weight_fqn] = (
+            Shard(0) if parallel_style == ColwiseParallel else Shard(1)
+        )
+        if bias_fqn in params_and_buffers:
+            parameter_placements[bias_fqn] = (
+                Shard(0) if parallel_style == ColwiseParallel else Replicate()
+            )
+    return parameter_placements
+
+
+def _mark_tensor_parallel_shardings(
+    gm: GraphModule,
+    graph_signature: ExportGraphSignature,
+    mesh: DeviceMesh,
+    parameter_placements: Dict[str, Placement],
+) -> Dict[Node, PlacementStrategy]:
+    """
+    Mark the placement strategies of the parameter and buffer placeholder nodes.
+    """
+    placement_strategies: Dict[Node, PlacementStrategy] = {}
+    num_params_and_buffers = len(graph_signature.inputs_to_parameters) + len(
+        graph_signature.inputs_to_buffers
+    )
+    placeholder_idx: int = 0
+    for node in gm.graph.nodes:
+        if node.op == "placeholder":
+            if placeholder_idx < num_params_and_buffers:
+                fqn: str = _get_input_node_fqn(node.name, graph_signature)
+                placement: Placement = (
+                    parameter_placements[fqn]
+                    if fqn in parameter_placements
+                    else Replicate()
+                )
+                placement_strategies[node] = _create_placement_strategy(
+                    node,
+                    mesh,
+                    placements=(placement,),
+                )
+                placeholder_idx += 1
+            else:
+                placement_strategies[node] = _create_placement_strategy(
+                    node,
+                    mesh,
+                    placements=(Replicate(),),
+                )
+    return placement_strategies
+
+
+def _get_input_node_fqn(input_name: str, graph_signature: ExportGraphSignature) -> str:
+    """
+    Return the FQN of an input node.
+    """
+    if input_name in graph_signature.inputs_to_parameters:
+        return graph_signature.inputs_to_parameters[input_name]
+    elif input_name in graph_signature.inputs_to_buffers:
+        return graph_signature.inputs_to_buffers[input_name]
+    else:
+        raise ValueError(
+            f"{input_name} not found in inputs_to_parameters or inputs_to_buffers"
+        )
+
+
+def _mark_sharding(
+    gm: GraphModule,
+    graph_signature: ExportGraphSignature,
+    mesh: DeviceMesh,
+    parameter_placements: Dict[str, Placement],
+) -> Dict[Node, PlacementStrategy]:
+    """
+    Mark the sharding strategy for each node in the graph module.
+    """
+    placement_strategies: Dict[
+        Node, PlacementStrategy
+    ] = _mark_tensor_parallel_shardings(gm, graph_signature, mesh, parameter_placements)
+
+    for node in gm.graph.nodes:
+        if node.op == "placeholder":
+            if node not in placement_strategies:
+                placement_strategies[node] = _create_placement_strategy(
+                    node, mesh, placements=(Replicate(),)
+                )
+            node.meta["sharding"] = placement_strategies[node]
+        elif node.op == "call_function":
+            if node.target == operator.getitem:
+                input_nodes = node.all_input_nodes
+                assert (
+                    len(input_nodes) == 1
+                ), f"non-compute op only support one input now, found node: {node} with length of inputs: {len(node.args)}"
+                arg_strategy = placement_strategies[input_nodes[0]]
+                placement_strategies[node] = _create_placement_strategy(
+                    node,
+                    mesh,
+                    placements=arg_strategy.output_spec.placements,
+                    input_specs=_get_input_node_specs(node, placement_strategies),
+                )
+                node.meta["sharding"] = placement_strategies[node]
+            else:
+                op_schema = _get_op_schema(node, placement_strategies)
+
+                # get DTensor specs for inputs and outputs
+                if (
+                    op_schema.op
+                    not in DTensor._op_dispatcher.sharding_propagator.op_strategy_funcs
+                    and op_schema.op
+                    not in DTensor._op_dispatcher.sharding_propagator.op_to_rules
+                ):
+                    # Mark all as replicated
+                    output_sharding = _generate_default_output_sharding(
+                        node,
+                        mesh,
+                        op_schema,
+                    )
+                else:
+                    output_sharding = DTensor._op_dispatcher.sharding_propagator.propagate_op_sharding(
+                        op_schema,
+                    )
+                placement_strategies[node] = PlacementStrategy(
+                    output_specs=_get_output_spec_from_output_sharding(output_sharding),
+                    input_specs=output_sharding.redistribute_schema.args_spec
+                    if output_sharding.redistribute_schema is not None
+                    else _get_input_node_specs(node, placement_strategies),
+                )
+                node.meta["sharding"] = placement_strategies[node]
+        elif node.op == "output":
+            node.meta["sharding"] = None
+        else:
+            raise RuntimeError(f"op code {node.op} not supported")
+    return placement_strategies
+
+
+def _get_output_spec_from_output_sharding(
+    output_sharding: OutputSharding,
+) -> DTensorSpec:
+    """
+    Util function to extract output spec from output sharding.
+    """
+    if isinstance(output_sharding.output_spec, DTensorSpec):
+        return output_sharding.output_spec
+    else:
+        # For ops that return multiple outputs, the outputs should have the same output spec
+        assert isinstance(output_sharding.output_spec, Sequence)
+        assert output_sharding.output_spec[0] is not None
+        output_sharding.output_spec[0].tensor_meta = None
+        return output_sharding.output_spec[0]
+
+
+def _create_placement_strategy(
+    node: Node,
+    mesh: DeviceMesh,
+    placements: Tuple[Placement, ...],
+    input_specs: Optional[Sequence[DTensorSpec]] = None,
+) -> PlacementStrategy:
+    """
+    Util function to construct a placement strategy for a given node.
+    """
+    placement = PlacementStrategy(
+        input_specs=input_specs,
+        output_specs=DTensorSpec(
+            mesh=mesh,
+            placements=placements,
+        ),
+    )
+    _populate_tensor_meta(node, placement.output_specs)
+    return placement
+
+
+def _populate_tensor_meta(node: Node, output_spec: OutputSpecType) -> None:
+    """
+    Util function to populate tensor meta of output_spec based on node metadata.
+    """
+    if isinstance(node.meta["val"], Sequence):
+        assert isinstance(output_spec, Sequence)
+        for spec, fake_tensor in zip(output_spec, node.meta["val"]):
+            assert spec is not None
+            spec.tensor_meta = TensorMeta(
+                shape=fake_tensor.shape,
+                stride=fake_tensor.stride(),
+                dtype=fake_tensor.dtype,
+            )
+    else:
+        assert isinstance(output_spec, DTensorSpec)
+        output_spec.tensor_meta = TensorMeta(
+            shape=node.meta["val"].shape,
+            stride=node.meta["val"].stride(),
+            dtype=node.meta["val"].dtype,
+        )
+
+
+def _generate_default_output_sharding(
+    node: Node,
+    mesh: DeviceMesh,
+    op_schema: OpSchema,
+) -> OutputSharding:
+    """
+    Util function to create a default output sharding that suggests Replicate placement for both args and outputs.
+    """
+
+    def update_arg_spec(arg_spec: DTensorSpec) -> DTensorSpec:
+        return DTensorSpec(
+            mesh=arg_spec.mesh,
+            placements=(Replicate(),),
+            tensor_meta=arg_spec.tensor_meta,
+        )
+
+    new_op_schema = OpSchema(
+        op=op_schema.op,
+        args_schema=pytree.tree_map_only(
+            DTensorSpec, update_arg_spec, op_schema.args_schema
+        ),
+        kwargs_schema=op_schema.kwargs_schema,
+    )
+
+    def create_output_spec(tensor: FakeTensor) -> DTensorSpec:
+        return DTensorSpec(
+            mesh=mesh,
+            placements=(Replicate(),),
+            tensor_meta=TensorMeta(
+                shape=tensor.shape,
+                stride=tensor.stride(),
+                dtype=tensor.dtype,
+            ),
+        )
+
+    return OutputSharding(
+        output_spec=pytree.tree_map_only(
+            FakeTensor, create_output_spec, node.meta["val"]
+        ),
+        redistribute_schema=new_op_schema,
+        needs_redistribute=True,
+    )
+
+
+def _partitioner(gm: torch.fx.GraphModule) -> torch.fx.GraphModule:
+    """
+    Graph partitioner that partitions the single device graph
+    to distributed graph
+    """
+    for node in gm.graph.nodes:
+        node_sharding = node.meta["sharding"]
+        if node.op == "placeholder":
+            out_spec = node_sharding.output_spec
+            local_val = _partition_val(node.meta["val"], out_spec)
+            # update node value
+            node.meta["val"] = local_val
+        elif node.op == "call_function":
+            out_spec = node_sharding.output_spec
+            # check if there's misaligned sharding, insert reshard if there is
+            expected_input_specs = node_sharding.input_specs
+            for idx, input_arg in enumerate(node.all_input_nodes):
+                input_arg_sharding = input_arg.meta["sharding"]
+                input_arg_spec = input_arg_sharding.output_spec
+                desired_spec = (
+                    out_spec
+                    if expected_input_specs is None
+                    else expected_input_specs[idx]
+                )
+                if input_arg_spec != desired_spec:
+                    _insert_reshard_gm(
+                        gm, node, input_arg, input_arg_spec, desired_spec
+                    )
+            # convert output val to its local component
+            output_val = node.meta["val"]
+            node.meta["val"] = _partition_val(output_val, out_spec)
+        elif node.op == "output":
+            for input_arg in node.all_input_nodes:
+                # input args of output should be Replicate, otherwise redistribution is needed.
+                input_args_to_check: Sequence[Node] = (
+                    input_arg if isinstance(input_arg, Sequence) else [input_arg]
+                )
+                for arg in input_args_to_check:
+                    arg_sharding = arg.meta["sharding"]
+                    arg_spec = arg_sharding.output_spec
+                    desired_spec = copy.copy(arg_spec)
+                    desired_spec.placements = (Replicate(),)
+                    if arg_spec != desired_spec:
+                        _insert_reshard_gm(gm, node, arg, arg_spec, desired_spec)
+        else:
+            raise RuntimeError(f"op code {node} not supported")
+
+    _clean_up_graph_metadata(gm)
+    gm.graph.lint()
+    gm.recompile()
+    return gm
+
+
+def _partition_val(val: Any, spec: DTensorSpec) -> Any:
+    """
+    util function to convert a full tensor val to its local component
+    """
+    if isinstance(val, torch.Tensor):
+        local_shard = val
+        if val.ndim == 0:
+            # If it's already a scalar tensor, it is already local, we don't
+            # need to do anything
+            return local_shard
+
+        for idx, placement in enumerate(spec.placements):
+            if placement.is_shard():
+                placement = cast(Shard, placement)
+                num_chunks = spec.mesh.size(mesh_dim=idx)
+                my_coord = spec.mesh.get_coordinate()
+                assert my_coord is not None, "current rank not in mesh!"
+                my_coord_on_mesh_dim = my_coord[idx]
+                local_shard = placement._split_tensor(
+                    local_shard, num_chunks, with_padding=False, contiguous=True
+                )[0][my_coord_on_mesh_dim]
+        return local_shard
+    elif isinstance(val, (list, tuple)):
+        return val.__class__(_partition_val(v, spec) for v in val)
+    else:
+        raise RuntimeError(f"val type {type(val)} not supported")
+
+
+def _insert_reshard_gm(
+    gm: torch.fx.GraphModule,
+    node: Node,
+    input_arg: Node,
+    input_arg_spec: DTensorSpec,
+    desired_spec: DTensorSpec,
+) -> None:
+    """
+    Transform the graph for tensor redistribution.
+    """
+    input_arg_spec.tensor_meta = input_arg.meta["tensor_meta"]
+    desired_spec.tensor_meta = input_arg.meta["tensor_meta"]
+    input_arg_tensor = input_arg.meta["val"]
+
+    # insert reshard operation
+    def reshard_fn(local_tensor: torch.Tensor) -> torch.Tensor:
+        return redistribute_local_tensor(
+            local_tensor,
+            input_arg_spec,
+            desired_spec,
+        )
+
+    reshard_gm = make_fx(reshard_fn)(input_arg_tensor)
+    reshard_gm_nodes = list(reshard_gm.graph.nodes)
+    input_node = reshard_gm_nodes[0]
+    with gm.graph.inserting_before(node):
+        # copy nn_module_stack metadata for output, all-reduce nodes
+        for reshard_node in reshard_gm.graph.nodes:
+            if reshard_node.op not in ["placeholder", "output"]:
+                reshard_node.meta["nn_module_stack"] = (
+                    copy.copy(input_arg.meta["nn_module_stack"])
+                    if not input_arg.op == "placeholder"
+                    else copy.copy(node.meta["nn_module_stack"])
+                )
+        output_node = gm.graph.graph_copy(
+            reshard_gm.graph,
+            val_map={
+                input_node: input_arg,
+            },
+        )
+    node.replace_input_with(input_arg, output_node)  # type: ignore[arg-type]
+
+
+def _clean_up_graph_metadata(gm: torch.fx.GraphModule) -> None:
+    """
+    Clean up the graph by removing sharding and partitioning related metadata
+    """
+    for node in gm.graph.nodes:
+        if "sharding" in node.meta:
+            del node.meta["sharding"]
+        if "val" in node.meta and isinstance(node.meta["val"], torch.Tensor):
+            local_tensor_meta = _extract_tensor_metadata(node.meta["val"])
+            node.meta["tensor_meta"] = local_tensor_meta
+
+
+def _get_input_node_specs(
+    node: Node, placement_strategies: Dict[Node, PlacementStrategy]
+) -> Tuple[DTensorSpec, ...]:
+    """
+    Get the input specs of a node.
+    """
+    input_specs_list: List[DTensorSpec] = []
+    for input_arg in node.all_input_nodes:
+        if input_arg in placement_strategies:
+            output_spec = placement_strategies[input_arg].output_specs
+            assert isinstance(output_spec, DTensorSpec)
+            input_specs_list.append(output_spec)
+        else:
+            raise ValueError(f"{input_arg} does not have output_spec populated.")
+    return tuple(input_specs_list)
+
+
+def _get_op_schema(
+    node: Node, placement_strategies: Dict[Node, PlacementStrategy]
+) -> OpSchema:
+    """
+    Util function to construct the operator schema of a node.
+    """
+    args_schema_list = pytree.tree_map_only(
+        Node, lambda arg: placement_strategies[arg].output_specs, node.args
+    )
+    op_schema = OpSchema(
+        op=cast(torch._ops.OpOverload, node.target),
+        args_schema=tuple(args_schema_list),
+        kwargs_schema=cast(Dict[str, object], node.kwargs),
+    )
+    return op_schema
+
+
+def _shard_state_dict(
+    state_dict: Dict[str, torch.Tensor],
+    placement_strategies: Dict[Node, PlacementStrategy],
+    graph_signature: ExportGraphSignature,
+    mesh: DeviceMesh,
+) -> None:
+    """
+    Inplace partition the weights based on the placement strategy
+    """
+    for node, placement_strategy in placement_strategies.items():
+        if node.op != "placeholder":
+            continue
+        if node.name in graph_signature.inputs_to_parameters:
+            fqn = graph_signature.inputs_to_parameters[node.name]
+        elif node.name in graph_signature.inputs_to_buffers:
+            fqn = graph_signature.inputs_to_buffers[node.name]
+        else:
+            continue
+        assert fqn in state_dict, f"{fqn} not found in state dict: {state_dict.keys()}"
+
+        original_param = state_dict[fqn]
+        dtensor_param = distribute_tensor(
+            original_param,
+            mesh,
+            placement_strategy.output_spec.placements,
+        )
+        local_param = dtensor_param.to_local()
+        state_dict[fqn] = (
+            torch.nn.Parameter(local_param)
+            if isinstance(original_param, torch.nn.Parameter)
+            else local_param
+        )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9fe378c51b0d4061ef07e0c3f94bde81fc6ed6c2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__init__.py
@@ -0,0 +1,23 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates
+from torch.distributed.tensor.parallel.api import parallelize_module
+from torch.distributed.tensor.parallel.loss import loss_parallel
+from torch.distributed.tensor.parallel.style import (
+    ColwiseParallel,
+    ParallelStyle,
+    PrepareModuleInput,
+    PrepareModuleOutput,
+    RowwiseParallel,
+    SequenceParallel,
+)
+
+
+__all__ = [
+    "ColwiseParallel",
+    "ParallelStyle",
+    "PrepareModuleInput",
+    "PrepareModuleOutput",
+    "RowwiseParallel",
+    "SequenceParallel",
+    "parallelize_module",
+    "loss_parallel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..517921242410bb8a730fc543cd927145db818f14
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/_data_parallel_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/_data_parallel_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3032d2b32550af2de7a295ca574ad11764e22181
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/_data_parallel_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fc474cb53d9ce6c19efa01f265f8a63723dd633b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/api.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/api.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ee3cb9664a2edabcdcc5476b906a046e45953251
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/api.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/ddp.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/ddp.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2f881d21c047e446185659271531ecfdce49a019
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/ddp.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/fsdp.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/fsdp.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e0b9bb06236ca2c7176b16bc9c3210c6b20e4e78
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/fsdp.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/input_reshard.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/input_reshard.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aa82b7bf6de47ccdc6221da708ffd6c7ae435662
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/input_reshard.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/loss.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/loss.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fabe2eb47df6c61dd354491e5ac02c781bf5510f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/loss.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/style.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/style.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d40e839b931ab3d5257c85dbf742761e262c81e4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/__pycache__/style.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/_data_parallel_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/_data_parallel_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d1097f4328c3e83932de336bea1c8daf5cb0982
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/_data_parallel_utils.py
@@ -0,0 +1,51 @@
+from functools import partial
+from typing import no_type_check, Optional, Tuple
+
+import torch
+from torch.distributed._functional_collectives import AsyncCollectiveTensor
+from torch.distributed.tensor import DTensor
+from torch.distributed.tensor._dtensor_spec import DTensorSpec
+
+
+@no_type_check
+def sync_grad_hook(grad, *, device_handle=None, compute_stream=None):
+    if isinstance(grad, AsyncCollectiveTensor):
+        if compute_stream is not None:
+            with device_handle.stream(compute_stream):
+                grad = grad.wait()
+        else:
+            grad = grad.wait()
+
+    return grad
+
+
+def _flatten_tensor(
+    tensor: torch.Tensor,
+) -> Tuple[torch.Tensor, Optional[DTensorSpec]]:
+    if isinstance(tensor, DTensor):
+        tensor._local_tensor.requires_grad_()
+        return tensor._local_tensor, tensor._spec
+    return tensor, None
+
+
+@no_type_check
+def _unflatten_tensor(tensor, spec, *, device_handle=None, compute_stream=None):
+    # unflatten would mainly be called everytime FSDP allgather parameters.
+    result = DTensor.from_local(
+        tensor,
+        spec.mesh,
+        spec.placements,
+        run_check=False,
+        shape=spec.shape,
+        stride=spec.stride,
+    )
+    if tensor.requires_grad:
+        # only register the hook if the tensor requires grad
+        tensor.register_hook(
+            partial(
+                sync_grad_hook,
+                device_handle=device_handle,
+                compute_stream=compute_stream,
+            )
+        )
+    return result
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f50b5dd64768d00a9cc96af161465b46f9ae7434
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/_utils.py
@@ -0,0 +1,67 @@
+# mypy: allow-untyped-defs
+import warnings
+from typing import Tuple, Union
+
+from torch.distributed.device_mesh import _mesh_resources
+from torch.distributed.tensor import DeviceMesh
+from torch.distributed.tensor.placement_types import Placement
+
+
+try:
+    from torch._dynamo.external_utils import is_compiling as is_torchdynamo_compiling
+except Exception:
+
+    def is_torchdynamo_compiling():  # type: ignore[misc]
+        return False
+
+
+LayoutsType = Union[Placement, Tuple[Placement, ...]]
+
+
+def _deprecate_warnings(func_name: str, extra_msg: str) -> None:
+    """
+    Inject common validation logics for `_prepare_input` funcs via this decorator.
+
+    Include verifying that input needs to be either a :class:`Tensor` or :class:`DTensor`
+    and only 1D :class:`DeviceMesh` is passed in.
+    """
+    # TODO: Will follow up with dynamo POC to make warnings.warn working with dynamo.
+    if not is_torchdynamo_compiling():
+        warnings.warn(
+            f"{func_name} is deprecated and will be removed soon. {extra_msg}",
+            FutureWarning,
+            stacklevel=3,
+        )
+
+
+def _validate_tp_mesh_dim(
+    device_mesh: DeviceMesh,
+) -> None:
+    """
+    Check whether TP mesh dimension is valid or not.
+
+    Args:
+        device_mesh (:class:`DeviceMesh`):
+            The `device_mesh` where we perform
+            Tensor Parallelism on.
+
+    Return:
+        `True` if the mesh dimension
+        is valid, `False` otherwise.
+    """
+    if device_mesh.ndim > 1:
+        raise ValueError(
+            f"Tensor Parallel only accepts a 1D DeviceMesh, but found {device_mesh.ndim}D!"
+            'If you have a 2-D or N-D device_mesh, consider passing in device_mesh["tp"]'
+        )
+
+    root_mesh = _mesh_resources.get_root_mesh(device_mesh)
+    # if a root mesh is not the same as device_mesh,
+    # meaning the device_mesh is sliced out from the root mesh.
+    if root_mesh and root_mesh != device_mesh:
+        tp_mesh_dim_in_root = _mesh_resources.get_root_mesh_dim(device_mesh)
+        if tp_mesh_dim_in_root != root_mesh.ndim - 1:
+            raise RuntimeError(
+                f"Found TP device_mesh on the {tp_mesh_dim_in_root} dimension of its parent mesh.",
+                "Currently we only support intranode TP and TP needs to be the innermost dimension on its parent mesh.",
+            )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/api.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..db4db018cce2d329eff3298010f110cc76129d0c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/api.py
@@ -0,0 +1,118 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates
+from fnmatch import fnmatch
+from typing import Dict, Union
+
+import torch
+import torch.distributed.tensor._random as random
+import torch.nn as nn
+from torch.distributed.tensor import DeviceMesh
+from torch.distributed.tensor._random import (
+    is_rng_supported_mesh,
+    TensorParallelRNGTracker,
+)
+from torch.distributed.tensor.parallel._utils import _validate_tp_mesh_dim
+from torch.distributed.tensor.parallel.style import ParallelStyle
+
+
+__all__ = [
+    "parallelize_module",
+]
+
+
+def parallelize_module(  # type: ignore[return]
+    module: nn.Module,
+    device_mesh: DeviceMesh,
+    parallelize_plan: Union[ParallelStyle, Dict[str, ParallelStyle]],
+) -> nn.Module:
+    """
+    Apply Tensor Parallelism in PyTorch by parallelizing modules or sub-modules based on a user-specified plan.
+
+    We parallelize module or sub_modules based on a parallelize_plan. The parallelize_plan contains
+    :class:`ParallelStyle`, which indicates how user wants the module or sub_module
+    to be parallelized.
+
+    User can also specify different parallel style per module fully qualified name (FQN).
+
+    Note that ``parallelize_module`` only accepts a 1-D :class:`DeviceMesh`, if you have a 2-D or N-D :class:`DeviceMesh`,
+    slice the DeviceMesh to a 1-D sub DeviceMesh first then pass to this API(i.e. ``device_mesh[\"tp\"]``)
+
+    Args:
+        module (:class:`nn.Module`):
+            Module to be parallelized.
+        device_mesh (:class:`DeviceMesh`):
+            Object which describes the mesh topology
+            of devices for the DTensor.
+        parallelize_plan (Union[:class:`ParallelStyle`, Dict[str, :class:`ParallelStyle`]]):
+            The plan used to parallelize the module. It can be either a
+            :class:`ParallelStyle` object which contains how
+            we prepare input/output for Tensor Parallelism or it can be a
+            dict of module FQN and its corresponding :class:`ParallelStyle` object.
+    Return:
+        A :class:`nn.Module` object parallelized.
+
+    Example::
+        >>> # xdoctest: +SKIP("distributed")
+        >>> from torch.distributed.tensor.parallel import parallelize_module, ColwiseParallel
+        >>> from torch.distributed.device_mesh import init_device_mesh
+        >>>
+        >>> # Define the module.
+        >>> m = Model(...)
+        >>> tp_mesh = init_device_mesh("cuda", (8,))
+        >>> m = parallelize_module(m, tp_mesh, {"w1": ColwiseParallel(), "w2": RowwiseParallel()})
+        >>>
+
+    .. note:: For complex module architecture like Attention, MLP layers, we recommend composing
+        different ParallelStyles together (i.e. ``ColwiseParallel`` and ``RowwiseParallel``) and pass
+        as a parallelize_plan, to achieves the desired sharding computation.
+    """
+    torch._C._log_api_usage_once("torch.distributed.tensor.parallel.parallelize_module")
+
+    _validate_tp_mesh_dim(device_mesh)
+
+    # instantiate a TP RNG state tracker if it's not there
+    if is_rng_supported_mesh(device_mesh) and not isinstance(
+        random._rng_tracker, TensorParallelRNGTracker
+    ):
+        random._rng_tracker = TensorParallelRNGTracker(device_mesh.device_type)
+        # TODO: we should allow user to pass in the default seed from a config
+        random._rng_tracker._manual_seed(device_mesh, base_seed=1234)
+        # By default we execute random ops in non-tensor-parallel region. If users want
+        # to execute in tensor-parallel region, they can manually set this field to True
+        # after parallelizing the model.
+        random._rng_tracker.distribute_region_enabled = False
+
+    if isinstance(parallelize_plan, ParallelStyle):
+        return parallelize_plan._apply(module, device_mesh)
+    elif isinstance(parallelize_plan, dict):
+        for module_path, parallelize_style in parallelize_plan.items():
+            path_splits = module_path.split(".")
+            if len(path_splits) == 0:
+                raise ValueError(
+                    "Expect module path to be non-empty, but got empty string!"
+                )
+            while path_splits:
+                atom = path_splits.pop(0)
+                matched_children = filter(
+                    # `t[0]` is child name
+                    lambda t: fnmatch(t[0], atom),
+                    module.named_children(),
+                )
+                # apply the plan to all matched submodules
+                for _, submodule in matched_children:
+                    if path_splits:
+                        # we haven't reached the leaf, apply in dict style
+                        leaf_path = ".".join(
+                            path_splits
+                        )  # rest of the path after `atom`
+                        parallelize_module(
+                            submodule, device_mesh, {leaf_path: parallelize_style}
+                        )
+                    else:
+                        # otherwise, directly apply style to this submodule
+                        parallelize_module(submodule, device_mesh, parallelize_style)
+        return module
+    else:
+        raise TypeError(  # pyre-ignore[7]
+            "Expect Union[ParallelStyle, Dict[str, ParallelStyle]] for"
+            f" parallelize_plan, {type(parallelize_plan)} found!"
+        )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/ddp.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/ddp.py
new file mode 100644
index 0000000000000000000000000000000000000000..ccda5bc1b47fb4ac8721011b6d0c7486bfa14f9b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/ddp.py
@@ -0,0 +1,104 @@
+# mypy: allow-untyped-defs
+from typing import Any, List, Optional, Set, Tuple
+
+import torch.nn as nn
+from torch.distributed.tensor.parallel._data_parallel_utils import (
+    _flatten_tensor,
+    _unflatten_tensor,
+)
+
+
+__all__ = []  # type: ignore[var-annotated]
+
+
+def _get_submodule_n_params(module: nn.Module, path: str):
+    """
+    Get submodule and the direct path of parameter from the module
+    """
+    if "." in path:
+        path_list = path.split(".")
+        parent_module_path = ".".join(path_list[:-1])
+        module = module.get_submodule(parent_module_path)
+        path = path_list[-1]
+    return module, path
+
+
+def _update_module_param(param_list: List[Tuple[nn.Module, str, nn.Parameter]]):
+    """
+    Update parameters within the module
+    """
+    for item in param_list:
+        parent_module, module_path, t = item
+        assert hasattr(parent_module, module_path)
+        delattr(parent_module, module_path)
+        setattr(parent_module, module_path, t)
+
+
+def _reconstruct_dtensor(module: nn.Module, _input: Any):
+    """
+    Recontruct DTensor parameters from local tensors
+    """
+    param_list = []
+    # TODO: To add perf optimizations to this iterations
+    for name, t in module.named_parameters():
+        if hasattr(t, "_st_info"):
+            dtensor = _unflatten_tensor(t, t._st_info)
+            param_list.append((*_get_submodule_n_params(module, name), dtensor))
+    _update_module_param(param_list)  # type: ignore[arg-type]
+
+
+def _localize_dtensor(
+    module: nn.Module, *_: Any, ignored_params: Optional[Set[nn.Parameter]] = None
+):
+    """
+    Convert DTensor parameters to local tensors
+    """
+    if ignored_params is None:
+        ignored_params = set()
+    param_list = []
+    for name, param in module.named_parameters():
+        if param in ignored_params:
+            continue
+        t, sharding_info = _flatten_tensor(param)
+        if sharding_info is not None:
+            t = nn.Parameter(t)
+            t._st_info = sharding_info  # type: ignore[attr-defined]
+            param_list.append((*_get_submodule_n_params(module, name), t))
+    _update_module_param(param_list)  # type: ignore[arg-type]
+
+
+def _pre_dp_module_transform(module: nn.Module):
+    """
+    Enable the composability between Tensor Parallelism (TP) and Data
+    Parallelism(DP) in PyTorch when using DDP. We need to convert Parameters which
+    are DTensors to local tensors before wrapping with data parallelism API.
+    We then register two hooks, one for converting local tensors back to DTensor
+    preforward and one to convert DTensors back to tensors after Forward. By
+    integrating this way, we avoid any special handling of DTensor parameters by DDP
+    and get DTensor's gradients propagated back to DP, e.g. gradient buckets of DDP.
+
+    For now, this API only works with ``DistributedDataParallel``. It will later support
+    other DP methods such as FSDP.
+
+    Args:
+        module (:class:`nn.Module`):
+            Module which has been applied TP on.
+
+    Example::
+        >>> # xdoctest: +SKIP("distributed")
+        >>> from torch.distributed.tensor.parallel import parallelize_module, PairwiseParallel
+        >>> from torch.nn.parallel import DistributedDataParallel as DDP
+        >>> from torch.distributed.tensor.parallel.ddp import pre_dp_module_transform
+        >>>
+        >>> # Define the module.
+        >>> m = module(...)
+        >>> parallelize_module(m, PairwiseParallel())
+        >>> m = pre_dp_module_transform(m)
+        >>> m = DDP(m)
+        >>>
+    """
+
+    _localize_dtensor(module, None, None)
+    # TODO: To add test cases and ensure that it works for nested modules
+    module.register_forward_pre_hook(_reconstruct_dtensor)
+    module.register_forward_hook(_localize_dtensor)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/fsdp.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/fsdp.py
new file mode 100644
index 0000000000000000000000000000000000000000..d2faa9ed32dc5dc3012886b776f4e6b96ac8a7ee
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/fsdp.py
@@ -0,0 +1,388 @@
+# mypy: allow-untyped-defs
+import copy
+from typing import Any, cast, List, Optional, Tuple
+
+import torch
+import torch.distributed as dist
+import torch.distributed._shard.sharding_spec as shard_spec
+import torch.distributed.distributed_c10d as c10d
+from torch.distributed._shard.sharded_tensor import (
+    Shard,
+    ShardedTensor,
+    ShardedTensorMetadata,
+    TensorProperties,
+)
+from torch.distributed._shard.sharding_spec import ShardMetadata
+from torch.distributed._shard.sharding_spec.chunk_sharding_spec import ChunkShardingSpec
+from torch.distributed.device_mesh import _mesh_resources
+from torch.distributed.fsdp._common_utils import _set_fsdp_flattened
+from torch.distributed.fsdp._fsdp_extensions import FSDPExtensions
+from torch.distributed.fsdp._shard_utils import _create_chunk_sharded_tensor
+from torch.distributed.remote_device import _remote_device
+from torch.distributed.tensor import DeviceMesh, DTensor, Replicate, Shard as DShard
+from torch.distributed.tensor.parallel._data_parallel_utils import (
+    _flatten_tensor,
+    _unflatten_tensor,
+)
+
+
+__all__ = ["DTensorExtensions"]
+
+
+def _get_box(tensor: DTensor) -> Tuple[torch.Size, torch.Size]:
+    device_mesh = tensor.device_mesh
+    assert device_mesh.ndim == 1, "Only 1D DeviceMeshes currently handled"
+
+    placement = tensor.placements[0]
+    offsets = [0] * len(tensor.size())
+    num_chunks = device_mesh.size(mesh_dim=0)
+
+    if tensor.placements[0].is_shard():
+        shard_dim = cast(DShard, placement).dim
+        chunk_size = tensor.size(shard_dim) // num_chunks
+        offsets[shard_dim] = chunk_size
+
+    return (torch.Size(offsets), tensor._local_tensor.size())
+
+
+def _get_box_for(tensor: DTensor, idx: int) -> Tuple[torch.Size, torch.Size]:
+    offsets, size = _get_box(tensor)
+    return (torch.Size([val * idx for val in offsets]), size)
+
+
+def _get_local_box(tensor: DTensor) -> Tuple[torch.Size, torch.Size]:
+    device_mesh = tensor.device_mesh
+    coord = device_mesh.get_coordinate()
+    assert coord is not None
+    return _get_box_for(tensor, coord[0])
+
+
+def _create_shard_md_from_dt(dt: DTensor, current_rank: int) -> ShardMetadata:
+    mesh = dt.device_mesh
+    assert mesh.ndim == 1, "Only 1D DeviceMeshes currently handled"
+
+    offsets, sizes = _get_local_box(dt)
+    return ShardMetadata(
+        shard_offsets=list(offsets),
+        shard_sizes=list(sizes),
+        placement=f"rank:{current_rank}/{dt._local_tensor.device}",
+    )
+
+
+def _create_sharded_tensor_md_from_dt(
+    dt: DTensor, dt_pg: c10d.ProcessGroup
+) -> ShardedTensorMetadata:
+    # This is where it gets tricky, we have to produce a ShardedTensor that has full coverage
+    # and yet has only one valid shard for the current rank.
+
+    shards_md = []
+    my_rank = dist.get_rank(dt_pg)
+    scapegoat_rank = 0 if my_rank > 0 else 1
+
+    if dt.placements[0].is_shard():
+        shard_count = dt_pg.size()
+    else:
+        shard_count = 1
+
+    for i in range(shard_count):
+        offsets, sizes = _get_box_for(dt, i)
+        shards_md.append(
+            ShardMetadata(
+                shard_offsets=list(offsets),
+                shard_sizes=list(sizes),
+                placement=(
+                    f"rank:{scapegoat_rank if i > 0 else my_rank}/{dt._local_tensor.device}"
+                ),
+            )
+        )
+
+    return ShardedTensorMetadata(
+        shards_metadata=shards_md,
+        size=dt.size(),
+        tensor_properties=TensorProperties(
+            dtype=dt.dtype,
+            layout=dt.layout,
+            requires_grad=dt.requires_grad,
+            # ignore memory_format and pin_memory as those are not supported by DT
+        ),
+    )
+
+
+def _get_dt_pg(dt: DTensor) -> c10d.ProcessGroup:
+    mesh = dt.device_mesh
+    assert mesh.ndim == 1, "Only 1D DeviceMeshes currently handled"
+    return mesh.get_group()
+
+
+def _rewrite_spec_if_needed(
+    spec: shard_spec.ShardingSpec, tensor: torch.Tensor, rank: int
+) -> shard_spec.ShardingSpec:
+    """
+    Rewrite ``spec`` to match the device of ``tensor``.
+
+    FSDP.sharded_optim_state_dict sneakly ships optimizer state to CPU so if the original ShardingSpec
+    produces CUDA metadata, ST construction bombs.
+    """
+    if not isinstance(spec, ChunkShardingSpec):
+        return spec
+
+    # let's see if we need
+    rewrite = False
+    for p in spec.placements:
+        p = cast(_remote_device, p)
+        if p.rank() == rank and p.device() != tensor.device:
+            rewrite = True
+            break
+    if rewrite:
+        spec = copy.deepcopy(spec)
+        for i, placement in enumerate(spec.placements):
+            placement = cast(_remote_device, placement)
+            if placement.rank() == rank and placement.device() != tensor.device:
+                spec.placements[i] = _remote_device(f"rank:{rank}/{tensor.device}")
+
+    return spec
+
+
+def _chunk_tensor(
+    tensor: torch.Tensor,
+    rank: int,
+    world_size: int,
+    num_devices_per_node: int,
+    pg: dist.ProcessGroup,
+) -> torch.Tensor:
+    if type(tensor) is ShardedTensor:
+        assert len(tensor.local_shards()) == 1
+
+        inner_param = tensor.local_tensor()
+        inner_st = _create_chunk_sharded_tensor(
+            inner_param,
+            rank,
+            world_size,
+            num_devices_per_node,
+            pg,
+        )
+
+        outer_local_shard = tensor.local_shards()[0]
+        shards: List[Shard] = [
+            Shard(inner_st, copy.deepcopy(outer_local_shard.metadata))
+        ]
+        st_meta = copy.deepcopy(tensor.metadata())
+        st_meta.tensor_properties.requires_grad = False
+
+        st_outer = ShardedTensor._init_from_local_shards_and_global_metadata(
+            shards,
+            sharded_tensor_metadata=st_meta,
+            process_group=tensor._process_group,
+            init_rrefs=False,
+        )
+        return st_outer
+    elif type(tensor) is DTensor:
+        device_mesh = tensor.device_mesh
+        assert device_mesh.ndim == 1, "Only 1D DeviceMeshes currently handled"
+
+        inner_param = tensor._local_tensor
+
+        inner_st = _create_chunk_sharded_tensor(
+            inner_param,
+            rank,
+            world_size,
+            torch.cuda.device_count(),
+            pg,
+        )
+
+        dt_pg = _get_dt_pg(tensor)
+        # We do this differently here, we create a ST with no local shards then patch it
+        shards = [
+            Shard(inner_st, _create_shard_md_from_dt(tensor, dist.get_rank(dt_pg)))
+        ]
+
+        st_meta = _create_sharded_tensor_md_from_dt(tensor, dt_pg)
+        st_meta.tensor_properties.requires_grad = False
+
+        st_outer = ShardedTensor._init_from_local_shards_and_global_metadata(
+            shards,
+            sharded_tensor_metadata=st_meta,
+            process_group=dt_pg,
+            init_rrefs=False,
+        )
+
+        return st_outer
+    else:
+        return _create_chunk_sharded_tensor(
+            tensor,
+            rank,
+            world_size,
+            num_devices_per_node,
+            pg,
+        )
+
+
+def _chunk_dtensor(
+    tensor: torch.Tensor,
+    rank: int,
+    device_mesh: DeviceMesh,
+) -> DTensor:
+    """
+    Shard a tensor to chunks along the first dimension.
+
+    The local rank will gets its corresponding chunk as the local tensor to create a DTensor.
+    """
+    root_mesh = _mesh_resources.get_root_mesh(device_mesh)
+    if root_mesh is None:
+        raise RuntimeError("No parent device_mesh is found for FSDP device_mesh.")
+    if root_mesh.ndim < 2:
+        raise RuntimeError(
+            f"Found parent device_mesh of ndim={root_mesh.ndim},",
+            "but meshes must be at least 2D.",
+        )
+
+    # We need to explicitly call .detach() to return a new tensor detached from the current graph.
+    tensor = tensor.clone().detach()
+
+    # When a layer is not involved in TP, then the tensor will not be a DTensor.
+    # e.g. When a layer is not sppecified in the parallelize_plan, TP will have no effect on the layer.
+    # e.g. When you do PairwiseParallel on a 3 layer model, TP will have no effect on the third layer.
+    if isinstance(tensor, torch.Tensor) and not isinstance(tensor, DTensor):
+        # For tensors, it is replicated across tp dimension and sharded across FSDP dimension.
+        # TP is the inner dimension and FSDP is the outer dimension.
+        # Therefore, shard placements for tensor is (Shard(0), Replicate()).
+        replicate_placements = [Replicate() for _ in range(root_mesh.ndim)]
+        shard_placements = [Replicate() for _ in range(root_mesh.ndim)]
+        shard_placements[0] = DShard(0)  # type: ignore[call-overload]
+
+        return DTensor.from_local(
+            tensor, root_mesh, replicate_placements, run_check=False
+        ).redistribute(
+            device_mesh=root_mesh,
+            placements=shard_placements,
+        )
+
+    else:
+        tp_placements = tensor.placements
+        tp_placement = tp_placements[0]
+
+        tensor = tensor.to_local()
+
+        # For DTensors, it is sharded across tp dimension first and then sharded across FSDP dimension.
+        # TP is the inner dimension and FSDP is the outer dimension.
+        # Therefore, shard placements for tensor is (Shard(0), tp_placement).
+        # For higher dimensional meshes, it is replicated across other dimensions. For example, with
+        # HSDP the shard placements for tensor is (Replicate, Shard(0), tp_placement).
+        replicate_placements = [Replicate() for _ in range(root_mesh.ndim)]
+        replicate_placements[-1] = tp_placement  # type: ignore[call-overload]
+        shard_placements = [Replicate() for i in range(root_mesh.ndim)]  # type: ignore[misc]
+        shard_placements[-2] = DShard(0)  # type: ignore[call-overload]
+        shard_placements[-1] = tp_placement  # type: ignore[call-overload]
+
+        return DTensor.from_local(
+            tensor, root_mesh, replicate_placements, run_check=False
+        ).redistribute(
+            device_mesh=root_mesh,
+            placements=shard_placements,
+        )
+
+
+def _pre_load_state_dict(
+    tensor: torch.Tensor,
+) -> Tuple[torch.Tensor, List[Shard]]:
+    shards = cast(ShardedTensor, tensor).local_shards()
+    if len(shards) == 1 and type(shards[0].tensor) is ShardedTensor:
+        inner_tensor = shards[0].tensor
+        shards = inner_tensor.local_shards()  # pyre-ignore[16]
+        tensor = inner_tensor
+
+    return (tensor, shards if len(shards) > 0 else [])
+
+
+def _all_gather_dtensor(
+    tensor: DTensor,
+    parent_mesh: Optional[DeviceMesh],
+) -> torch.Tensor:
+    """All gather a DTensor in its FSDP dimension and return the local tensor."""
+    assert parent_mesh == tensor.device_mesh
+
+    placements = list(copy.deepcopy(tensor.placements))
+    # FSDP + TP: [Shard(0), tp_placement] -> [Replicate(), tp_placement]
+    # HSDP + TP: [Replicate(), Shard(0), tp_placement] -> [Replicate(), Replicate(), tp_placement]
+    for i in range(0, len(placements) - 1):
+        placements[i] = Replicate()
+    tensor = tensor.redistribute(
+        device_mesh=tensor.device_mesh,
+        placements=placements,
+    )
+
+    return tensor.to_local()
+
+
+class DTensorExtensions(FSDPExtensions):
+    """
+    DTensorExtension is the TensorFlattener extension needed for 2D FSDP + TP.
+
+    This is the implementation for FSDPExtensions defined in
+    https://github.com/pytorch/pytorch/blob/main/torch/distributed/fsdp/_fsdp_extensions.py
+    """
+
+    def __init__(self, device_handle) -> None:
+        super().__init__()
+        self.compute_stream = None
+        self.device_handle = device_handle
+        # we have to use the dynamo disable this way to disable dynamo as the decorater way would
+        # trigger build failure with torch deploy...
+        self.post_unflatten_transform = torch._dynamo.disable(self.post_unflatten_transform)  # type: ignore[method-assign]
+
+    def pre_flatten_transform(
+        self,
+        tensor: torch.Tensor,
+    ) -> Tuple[torch.Tensor, Optional[Any]]:
+        return _flatten_tensor(tensor)
+
+    def post_unflatten_transform(
+        self, tensor: torch.Tensor, param_extension: Any
+    ) -> torch.Tensor:
+        stream = self.compute_stream or self.device_handle.current_stream()
+        with self.device_handle.stream(stream):
+            # runtime we put the unflattened tensor call on the compute stream since
+            # the unflattened tensor might contain computations in fwd/bwd where we
+            # need to sync properly.
+            # TODO: this is a short term fix and we should make the get_unflat_views
+            # directly happen in the compute stream.
+            result = _unflatten_tensor(
+                tensor,
+                param_extension,
+                device_handle=self.device_handle,
+                compute_stream=self.compute_stream,
+            )
+            _set_fsdp_flattened(result)
+            return result
+
+    def chunk_tensor(
+        self,
+        tensor: torch.Tensor,
+        rank: int,
+        world_size: int,
+        num_devices_per_node: int,
+        pg: dist.ProcessGroup,
+        device: Optional[torch.device] = None,
+    ) -> torch.Tensor:
+        return _chunk_tensor(tensor, rank, world_size, num_devices_per_node, pg)
+
+    def chunk_dtensor(
+        self,
+        tensor: torch.Tensor,
+        rank: int,
+        device_mesh: DeviceMesh,
+    ) -> torch.Tensor:
+        return _chunk_dtensor(tensor, rank, device_mesh)
+
+    def pre_load_state_dict_transform(
+        self,
+        tensor: torch.Tensor,
+    ) -> Tuple[torch.Tensor, List[Shard]]:
+        return _pre_load_state_dict(tensor)
+
+    def all_gather_dtensor(
+        self,
+        tensor: DTensor,
+        parent_mesh: Optional[DeviceMesh],
+    ) -> torch.Tensor:
+        return _all_gather_dtensor(tensor, parent_mesh)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/input_reshard.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/input_reshard.py
new file mode 100644
index 0000000000000000000000000000000000000000..630c287cae88f50b54dec92f135fcaa517156d82
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/input_reshard.py
@@ -0,0 +1,109 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates
+from functools import partial
+from typing import Any, Optional, Tuple
+
+import torch
+from torch.distributed.tensor import DeviceMesh, DTensor, Replicate, Shard
+
+
+__all__ = [
+    "input_reshard",
+]
+
+
+def input_reshard(
+    module: torch.nn.Module,
+    tp_device_mesh: DeviceMesh,
+    input_reshard_dim: Optional[int] = None,
+) -> torch.nn.Module:
+    """
+    Register hooks to an nn.Module for input resharding, enabling sharding and restoration during backward computation.
+
+    Register hooks to an nn.Module with input resharding so that we can shard
+    per the given `tp_device_mesh` and `input_reshard_dim` and restore the
+    input back when recomputing the activations in the backward. The reason
+    why we can do this is that for Tensor Parallel(TP), the input are same
+    across all TP ranks.
+
+    Args:
+        module (:class:`nn.Module`):
+            Module to be registered with input resharding.
+        tp_device_mesh (:class:`DeviceMesh`):
+            Object which describes the mesh topology
+            of devices for Tensor Parallel.
+        input_reshard_dim (Optional[int]):
+            The dimension of where we perform the sharding
+            of input. If set None, there is no sharding of input.
+            Default: None
+
+    Return:
+        A :class:`nn.Module` object registered with TP input resharding.
+    """
+    cx: Optional[torch.autograd.graph.saved_tensors_hooks] = None
+
+    def input_reshard_forward_pre_hook(_: torch.nn.Module, _i: Tuple[Any, ...]) -> None:
+        saved_tensor_hooks = torch.autograd.graph.saved_tensors_hooks(
+            partial(_pack_hook_tp, tp_device_mesh, input_reshard_dim),
+            partial(_unpack_hook_tp, tp_device_mesh, input_reshard_dim),
+        )
+        saved_tensor_hooks.__enter__()
+        nonlocal cx
+        cx = saved_tensor_hooks  # type: ignore[name-defined]
+
+    def input_reshard_backward_hook(
+        _: torch.nn.Module, _i: Tuple[Any, ...], _o: Any
+    ) -> Any:
+        nonlocal cx
+        cx.__exit__()  # type: ignore[name-defined, union-attr]
+
+    if input_reshard_dim is None:
+        return module
+    module.register_forward_pre_hook(input_reshard_forward_pre_hook)
+    module.register_forward_hook(input_reshard_backward_hook)
+    return module
+
+
+def _pack_hook_tp(
+    mesh: DeviceMesh, input_reshard_dim: int, x: torch.Tensor
+) -> Any:  # noqa: D401
+    """Hook function called after FWD to shard input."""
+    if isinstance(x, DTensor) and all(p.is_replicate() for p in x._spec.placements):
+        return x.redistribute(device_mesh=mesh, placements=[Shard(input_reshard_dim)])
+    elif (
+        not isinstance(x, DTensor)
+        and isinstance(x, torch.Tensor)
+        and x.numel() >= mesh.size()
+    ):
+        return (
+            DTensor.from_local(x, device_mesh=mesh)
+            .redistribute(device_mesh=mesh, placements=[Shard(input_reshard_dim)])
+            .to_local()
+        )
+    else:
+        return x
+
+
+def _unpack_hook_tp(
+    mesh: DeviceMesh, input_reshard_dim: int, x: Any
+) -> torch.Tensor:  # noqa: D401
+    """Hook function called before activation recomputing in BWD to restore input."""
+    if (
+        isinstance(x, DTensor)
+        and len(x._spec.placements) == 1
+        and x._spec.placements[0].is_shard()
+    ):
+        return x.redistribute(device_mesh=mesh, placements=[Replicate()])
+    elif (
+        not isinstance(x, DTensor)
+        and isinstance(x, torch.Tensor)
+        and x.numel() >= mesh.size()
+    ):
+        return (
+            DTensor.from_local(
+                x, device_mesh=mesh, placements=[Shard(input_reshard_dim)]
+            )
+            .redistribute(device_mesh=mesh, placements=[Replicate()])
+            .to_local()
+        )
+    else:
+        return x
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/loss.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/loss.py
new file mode 100644
index 0000000000000000000000000000000000000000..99f1e3ad6ef9adbfc8eaf316d9b082c78bbcbc6f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/loss.py
@@ -0,0 +1,490 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and affiliates
+import contextlib
+from typing import cast, Dict, Optional, Tuple
+
+import torch
+import torch._prims_common as utils
+import torch.distributed._functional_collectives as funcol
+import torch.distributed.distributed_c10d as c10d
+from torch import Tensor
+from torch.distributed.device_mesh import DeviceMesh
+from torch.distributed.tensor import DTensor, Replicate, Shard
+from torch.distributed.tensor._dtensor_spec import DTensorSpec, TensorMeta
+from torch.distributed.tensor._ops._embedding_ops import _MaskPartial
+from torch.distributed.tensor._ops._math_ops import (
+    _skip_dim,
+    Reduction,
+    replicate_reduction_dims,
+)
+from torch.distributed.tensor.placement_types import Placement
+
+
+aten = torch.ops.aten
+
+
+__all__ = ["loss_parallel"]
+
+
+@contextlib.contextmanager
+def loss_parallel():
+    """
+    A context manager that enables loss parallelism, where efficient parallelized loss computation
+    can be performed when the input is sharded on the class dimension. Currently only the cross-entropy
+    loss is supported.
+
+    Within this context manager, one can use :func:`~torch.nn.functional.cross_entropy` or
+    :class:`~torch.nn.CrossEntropyLoss` as usual, with the following assumptions on the input parameters.
+    The corresponding ``backward()`` call, if any, also needs to happen under this context manager.
+
+    Args:
+        input (:class:`DTensor`):
+            Input logits. Assumed to be sharded on the class dimension.
+        target (Union[:class:`torch.Tensor`, :class:`DTensor`]):
+            Must be ground truth class indices (class probabilities currently not supported).
+            Assumed to be replicated across the ``DeviceMesh``.
+        weight (Union[:class:`torch.Tensor`, :class:`DTensor`], optional):
+            If given, assumed to be replicated across the ``DeviceMesh``.
+        label_smoothing:
+            Currently not supported.
+
+    Returns:
+        A replicated :class:`DTensor`.
+
+    Example:
+        A sharded DTensor is manually created here to showcase the usage.
+        In practice, it is usually the output of a TP module.
+
+        >>> # xdoctest: +SKIP("distributed")
+        >>> from torch.distributed.tensor.parallel import loss_parallel
+        >>> from torch.distributed.device_mesh import init_device_mesh
+        >>> ...
+        >>> device_mesh = init_device_mesh("cuda", (8,))
+        >>> input = torch.randn(4, 16, device="cuda", requires_grad=True)
+        >>> dist_input = distribute_tensor(input, device_mesh, placements=[Shard(1)])
+        >>> target = torch.randint(16, (4,), device="cuda")
+        >>> with loss_parallel():
+        >>>     loss = F.cross_entropy(dist_input, target, reduction="mean")
+        >>>     loss.backward()
+        >>> ...
+    """
+    _enable_custom_loss_ops()
+
+    yield
+
+    _disable_custom_loss_ops()
+
+
+# Currently only needs to support one dimensional DeviceMesh; in general return
+# the mesh_dim with placements[mesh_dim].is_shard(dim)
+def _find_all_reduce_mesh_dim(placements: Tuple[Placement, ...], dim: int) -> int:
+    if not len(placements) == 1:
+        raise ValueError(
+            "Currently loss_parallel() only supports input on one-dimensional DeviceMesh."
+        )
+    if not placements[0].is_shard(dim):
+        raise ValueError(
+            f"loss_parallel() should be enabled only when the input tensor is sharded on dimension {dim}."
+        )
+    return 0
+
+
+def _cast_to_dtensor(
+    tensor, placements: Tuple[Placement, ...], mesh: DeviceMesh
+) -> DTensor:
+    if isinstance(tensor, DTensor):
+        if tensor.placements == placements:
+            return tensor
+        else:
+            raise RuntimeError(f"Expected {placements} but got {tensor.placements}.")
+    elif isinstance(tensor, torch.Tensor):
+        return DTensor.from_local(
+            tensor, device_mesh=mesh, placements=placements, run_check=False
+        )
+    else:
+        raise TypeError(f"Unsupported type {type(tensor)}")
+
+
+def _propagate_tensor_meta(
+    op_call: torch._ops.OpOverload,
+    args: Tuple[object, ...],
+    kwargs: Dict[str, object],
+) -> TensorMeta:
+    op_info = DTensor._op_dispatcher.unwrap_to_op_info(op_call, args, kwargs)
+    tensor_meta = DTensor._op_dispatcher.sharding_propagator._propagate_tensor_meta(
+        op_info.schema
+    )
+    if isinstance(tensor_meta, TensorMeta):
+        return tensor_meta
+    elif isinstance(tensor_meta, tuple):
+        return tensor_meta[0]
+    else:
+        raise RuntimeError(f"Unexpected tensor meta type: {type(tensor_meta)}.")
+
+
+# NOTE: The implementation follows torch._decomp.decomposition._log_softmax,
+# with all_reduce manually inserted to perform distributed computation.
+def _log_softmax(x, dim, half_to_float, mesh, mesh_dim):
+    x = x.contiguous()
+    if half_to_float:
+        assert x.dtype == torch.half
+    computation_dtype, result_dtype = utils.elementwise_dtypes(
+        x, type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT
+    )
+    x = x.to(computation_dtype)
+    if x.numel() == 0:
+        shifted = x
+    else:
+        x_max = torch.amax(x, dim, keepdim=True)
+        x_max = funcol.all_reduce(
+            x_max, reduceOp=c10d.ReduceOp.MAX.name, group=(mesh, mesh_dim)
+        )
+        shifted = x - x_max
+    shifted_sumexp = torch.sum(torch.exp(shifted), dim, keepdim=True)
+    shifted_sumexp = funcol.all_reduce(
+        shifted_sumexp, reduceOp=c10d.ReduceOp.SUM.name, group=(mesh, mesh_dim)
+    )
+    shifted_logsumexp = torch.log(shifted_sumexp)
+    result = shifted - shifted_logsumexp
+    if not half_to_float:
+        result = result.to(result_dtype)
+    return result
+
+
+def _log_softmax_handler(
+    op_call: torch._ops.OpOverload,
+    args: Tuple[object, ...],
+    kwargs: Dict[str, object],
+) -> object:
+    x = cast(DTensor, args[0])
+    dim = cast(int, args[1])
+    half_to_float = cast(bool, args[2])
+
+    spec = x._spec
+    mesh_dim = _find_all_reduce_mesh_dim(spec.placements, dim)
+
+    output_tensor_meta = _propagate_tensor_meta(op_call, args, kwargs)
+
+    res = _log_softmax(x._local_tensor, dim, half_to_float, spec.mesh, mesh_dim)
+
+    res_spec = DTensorSpec(
+        spec.mesh,
+        spec.placements,
+        tensor_meta=output_tensor_meta,
+    )
+
+    return DTensor(
+        res,
+        res_spec,
+        requires_grad=res.requires_grad,
+    )
+
+
+# NOTE: As explained below at _nll_loss_and_log_softmax_backward, the
+# _log_softmax_backward_handler does not actually do any computation.
+def _log_softmax_backward_handler(
+    op_call: torch._ops.OpOverload,
+    args: Tuple[object, ...],
+    kwargs: Dict[str, object],
+) -> object:
+    grad_output = cast(DTensor, args[0])
+    input_dtype = cast(torch.dtype, args[3])
+    return grad_output.to(input_dtype)
+
+
+# NOTE: The implementation follows torch._decomp.decomposition._nll_loss_forward,
+# with customized communication inserted to perform distributed computation.
+def _nll_loss_forward(
+    x: Tensor,
+    target: Tensor,
+    weight: Optional[Tensor],
+    local_weight: Optional[Tensor],
+    reduction: int,
+    ignore_index: int,
+    input_shape: torch.Size,
+    channel_dim: int,
+    mesh: DeviceMesh,
+    mesh_dim: int,
+) -> Tuple[Tensor, Tensor]:
+    n_dims = x.dim()
+    channel_dim = 1
+    if n_dims < 2:
+        channel_dim = 0
+
+    def _weight_view(weight: Tensor) -> Tensor:
+        if n_dims > 1:
+            shape = [
+                1,
+            ] * n_dims
+            shape[channel_dim] = weight.shape[0]
+            w = weight.view(shape)
+        else:
+            w = weight
+        return w
+
+    if weight is not None:
+        w = _weight_view(weight)
+        assert local_weight is not None
+        local_w = _weight_view(local_weight)
+        x = x * local_w
+    safe_target = torch.where(target != ignore_index, target, 0)
+    safe_target_ = safe_target.unsqueeze(channel_dim)
+
+    # The following code block is a distributed version of
+    # result = -torch.gather(self, channel_dim, safe_target_).squeeze(channel_dim)
+    partial_placement = _MaskPartial(offset_shape=input_shape, offset_dim=channel_dim)
+    safe_target_partial_ = partial_placement._partition_value(
+        safe_target_, mesh, mesh_dim
+    )
+    result_partial = torch.gather(x, channel_dim, safe_target_partial_)
+    # an all_reduce happens here
+    result_reduced = partial_placement._reduce_value(result_partial, mesh, mesh_dim)
+    result = -result_reduced.squeeze(channel_dim)
+
+    result = torch.where(target != ignore_index, result, 0)
+
+    if reduction == Reduction.NONE.value and n_dims > 1:
+        total_weight = x.new_full((), 0.0)
+        return result, total_weight
+
+    if weight is not None:
+        new_shape = list(x.shape)
+        new_shape[channel_dim] = -1
+        w = w.expand(new_shape)
+        wsum = torch.gather(w, channel_dim, safe_target_).squeeze(channel_dim)
+        wsum = torch.where(target != ignore_index, wsum, 0)
+        total_weight = wsum.sum()
+    else:
+        total_weight = (target != ignore_index).sum().to(x)
+
+    # NOTE: this is correct only on 1D DeviceMesh; o/w additional
+    #       all-reduce on result and total_weight is needed
+    if reduction == Reduction.SUM.value:
+        result = result.sum()
+    elif reduction == Reduction.MEAN.value:
+        result = result.sum() / total_weight
+
+    return result, total_weight
+
+
+def _nll_loss_forward_handler(
+    op_call: torch._ops.OpOverload,
+    args: Tuple[object, ...],
+    kwargs: Dict[str, object],
+) -> object:
+    x = cast(DTensor, args[0])
+    target = args[1]
+    weight = args[2]
+    reduction = cast(int, args[3])
+    ignore_index = cast(int, args[4])
+
+    channel_dim = 1 if x.dim() >= 2 else 0
+    channel_dim_size = x.shape[channel_dim]
+    spec = x._spec
+    mesh_dim = _find_all_reduce_mesh_dim(spec.placements, channel_dim)
+
+    # Check user input: if target and weight are not DTensors, convert them to DTensors;
+    # if they are DTensors, check that they have the desired placements.
+    target_placements = _skip_dim(
+        replicate_reduction_dims(spec.placements, [channel_dim]), channel_dim
+    )
+    all_replicate_placements = (Replicate(),) * spec.mesh.ndim
+    target = _cast_to_dtensor(target, target_placements, spec.mesh)
+    local_weight = None
+    if weight is not None:
+        weight = _cast_to_dtensor(weight, all_replicate_placements, spec.mesh)
+        # For local computation, both (replicated) weight and (sharded) local_weight
+        # are needed in _nll_loss_forward(). local_weight is generated here using
+        # DTensor API, without incurring any communication.
+        sharded_placements = [
+            Shard(0) if i == mesh_dim else Replicate() for i in range(spec.mesh.ndim)
+        ]
+        local_weight = weight.redistribute(spec.mesh, sharded_placements)._local_tensor
+        assert local_weight.shape[0] == x._local_tensor.shape[channel_dim]
+
+    if reduction == Reduction.NONE.value:
+        output_placements = target_placements
+    else:
+        output_placements = all_replicate_placements
+
+    # tensor inputs to _propagate_tensor_meta need to be DTensors
+    args = list(args)
+    args[1], args[2] = target, weight
+    output_tensor_meta = _propagate_tensor_meta(op_call, tuple(args), kwargs)
+
+    result, total_weight = _nll_loss_forward(
+        x._local_tensor,
+        target._local_tensor,
+        weight._local_tensor if weight is not None else None,
+        local_weight,
+        reduction,
+        ignore_index,
+        x.shape,
+        channel_dim,
+        spec.mesh,
+        mesh_dim,
+    )
+    out_spec = DTensorSpec(spec.mesh, output_placements, tensor_meta=output_tensor_meta)
+
+    return (
+        DTensor(
+            result,
+            out_spec,
+            requires_grad=result.requires_grad,
+        ),
+        total_weight,
+    )
+
+
+# NOTE: The backward computation of cross_entropy goes through two steps:
+# backward for nll_loss and then backward for log_softmax. In loss parallel,
+# the two steps are fused into the following function (called by _nll_loss_backward_handler)
+# to avoid communication when target contains class indices not class probabilities.
+# Also note that the _log_softmax_backward_handler does not perform computation.
+# The implementation resembles _nll_loss_backward and _log_softmax_backward_data
+# from torch._decomp.decomposition.
+def _nll_loss_and_log_softmax_backward(
+    grad_output: Tensor,
+    x: Tensor,
+    target: Tensor,
+    weight: Optional[Tensor],
+    reduction: int,
+    ignore_index: int,
+    total_weight: Tensor,
+    input_shape: torch.Size,
+    channel_dim: int,
+    mesh: DeviceMesh,
+    mesh_dim: int,
+) -> Tensor:
+    channel_dim = 0 if x.dim() < 2 else 1
+    if reduction == Reduction.MEAN.value:
+        grad_output = grad_output / total_weight
+
+    target = target.unsqueeze(channel_dim)
+    safe_target = torch.where(target != ignore_index, target, 0)
+    grad_input = torch.zeros_like(x)
+
+    # The following code block is a distributed version of
+    # grad_input = torch.scatter(grad_input, channel_dim, safe_target, -1.0)
+    partial_placement = _MaskPartial(offset_shape=input_shape, offset_dim=channel_dim)
+    safe_target = safe_target.squeeze(channel_dim).flatten()
+    masked_safe_target = partial_placement._partition_value(safe_target, mesh, mesh_dim)
+    # only update grad_input to -1 if not masked
+    assert partial_placement.mask_buffer.data is not None
+    grad_update = partial_placement.mask_buffer.data.to(grad_input.dtype) - 1.0
+    arange_1d = torch.arange(
+        masked_safe_target.shape[0], device=masked_safe_target.device
+    )
+    # The first two cases with x.dim() <= 2 are for aten.nll_loss_backward.default;
+    # the last case is for aten.nll_loss2d_backward.default.
+    if x.dim() == 1:
+        grad_input[masked_safe_target] = grad_update
+    elif x.dim() == 2:
+        grad_input[arange_1d, masked_safe_target] = grad_update
+    else:
+        grad_input_t = grad_input.transpose(channel_dim, -1)
+        intermidate_shape = grad_input_t.shape
+        grad_input_2d = grad_input_t.reshape(-1, x.shape[channel_dim])
+        grad_input_2d[arange_1d, masked_safe_target] = grad_update
+        grad_input = grad_input_2d.view(intermidate_shape).transpose(channel_dim, -1)
+
+    if grad_input.dim() > grad_output.dim() > 0:
+        grad_output = grad_output.unsqueeze(channel_dim)
+
+    if weight is not None:
+        new_shape = [1 for _ in range(x.dim())]
+        new_shape[channel_dim] = weight.shape[0]
+        weight = weight.reshape(new_shape)
+        # In order for fused computation to work, the following line is rewritten.
+        # grad_output = grad_output * weight
+        new_shape = list(x.shape)
+        new_shape[channel_dim] = -1
+        w = weight.expand(new_shape)
+        w_target = torch.gather(w, channel_dim, target)
+        grad_output = grad_output * w_target
+
+    grad_output = torch.where(target != ignore_index, grad_output, 0)
+
+    # NOTE: Instead of directly returning the grad_input as grad_output for log_softmax,
+    # here we perform backward computation for log_softmax altogether to avoid the
+    # otherwise extra all_gather communication.
+    # return grad_input * grad_output
+    return (grad_input + torch.exp(x)) * grad_output
+
+
+def _nll_loss_backward_handler(
+    op_call: torch._ops.OpOverload,
+    args: Tuple[object, ...],
+    kwargs: Dict[str, object],
+) -> object:
+    grad_output = cast(DTensor, args[0])
+    x = cast(DTensor, args[1])
+    target = args[2]
+    weight = args[3]
+    reduction = cast(int, args[4])
+    ignore_index = cast(int, args[5])
+    total_weight = cast(Tensor, args[6])
+
+    channel_dim = 1 if x.dim() >= 2 else 0
+    spec = x._spec
+    mesh_dim = _find_all_reduce_mesh_dim(spec.placements, channel_dim)
+
+    # if target and weight are not DTensors, convert them to DTensors
+    target_placements = _skip_dim(
+        replicate_reduction_dims(spec.placements, [channel_dim]), channel_dim
+    )
+    all_replicate_placements = (Replicate(),) * spec.mesh.ndim
+    target = _cast_to_dtensor(target, target_placements, spec.mesh)
+    if weight is not None:
+        weight = _cast_to_dtensor(weight, all_replicate_placements, spec.mesh)
+
+    # tensor inputs to _propagate_tensor_meta need to be DTensors
+    args = list(args)
+    args[2], args[3] = target, weight
+    args[6] = _cast_to_dtensor(total_weight, all_replicate_placements, spec.mesh)
+    output_tensor_meta = _propagate_tensor_meta(op_call, tuple(args), kwargs)
+
+    result = _nll_loss_and_log_softmax_backward(
+        grad_output._local_tensor,
+        x._local_tensor,
+        target._local_tensor,
+        weight._local_tensor if weight is not None else None,
+        reduction,
+        ignore_index,
+        total_weight,
+        x.shape,
+        channel_dim,
+        spec.mesh,
+        mesh_dim,
+    )
+    # the output sharding is the same as input sharding: Shard(channel_dim) on mesh_dim
+    out_spec = DTensorSpec(
+        spec.mesh,
+        spec.placements,
+        tensor_meta=output_tensor_meta,
+    )
+
+    return DTensor(
+        result,
+        out_spec,
+        requires_grad=result.requires_grad,
+    )
+
+
+customized_loss_ops = {
+    aten._log_softmax.default: _log_softmax_handler,
+    aten._log_softmax_backward_data.default: _log_softmax_backward_handler,
+    aten.nll_loss_forward.default: _nll_loss_forward_handler,
+    aten.nll_loss2d_forward.default: _nll_loss_forward_handler,
+    aten.nll_loss_backward.default: _nll_loss_backward_handler,
+    aten.nll_loss2d_backward.default: _nll_loss_backward_handler,
+}
+
+
+def _enable_custom_loss_ops():
+    DTensor._op_dispatcher._custom_op_handlers.update(customized_loss_ops)
+
+
+def _disable_custom_loss_ops():
+    for custom_op in customized_loss_ops:
+        DTensor._op_dispatcher._custom_op_handlers.pop(custom_op)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/style.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/style.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1e8dd7e236cd10c06d138bbadac8738e16ff6cf
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/parallel/style.py
@@ -0,0 +1,627 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and affiliates
+from abc import ABC, abstractmethod
+from functools import partial
+from typing import Any, Dict, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+from torch.distributed.tensor import (
+    DeviceMesh,
+    distribute_module,
+    distribute_tensor,
+    DTensor,
+    Replicate,
+    Shard,
+)
+from torch.distributed.tensor.placement_types import Placement
+
+
+__all__ = [
+    "ParallelStyle",
+    "RowwiseParallel",
+    "SequenceParallel",
+    "ColwiseParallel",
+    "PrepareModuleInput",
+    "PrepareModuleOutput",
+]
+
+
+class ParallelStyle(ABC):
+    """
+    The parallel style contract defines how the module or submodule should be parallelized.
+
+    It only defines the ``apply`` method for ``parallelize_module`` to use, this allows maximum
+    flexibility for different kind of style implementations.
+    """
+
+    @abstractmethod
+    def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
+        ...
+
+
+class ColwiseParallel(ParallelStyle):
+    """
+    Partition a compatible nn.Module in a column-wise fashion. Currently supports nn.Linear and nn.Embedding.
+    Users can compose it together with RowwiseParallel to achieve the sharding of more complicated modules.
+    (i.e. MLP, Attention)
+
+    Keyword Args:
+        input_layouts (Placement, optional):
+            The DTensor layout of input tensor for the nn.Module, this is used to annotate the input tensor to
+            become a DTensor. If not specified, we assume the input tensor to be replicated.
+        output_layouts (Placement, optional):
+            The DTensor layout of the output for the nn.Module, this is used to ensure the output of the nn.Module
+            with the user desired layout. If not specified, the output tensor is sharded on the last dimension.
+        use_local_output (bool, optional):
+            Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module output, default: True.
+    Returns:
+        A :class:`ParallelStyle` object that represents Colwise sharding of the nn.Module.
+
+    Example::
+        >>> # xdoctest: +SKIP(failing)
+        >>> from torch.distributed.tensor.parallel import parallelize_module, ColwiseParallel
+        >>> from torch.distributed.device_mesh import init_device_mesh
+        >>> ...
+        >>> m = Model(...)  # m is a nn.Module that contains a "w1" nn.Linear submodule
+        >>> tp_mesh = init_device_mesh("cuda", (8,))
+        >>>
+        >>> # By default, the input of the "w1" Linear will be converted to Replicated DTensor
+        >>> # and the output of "w1" will return :class:`torch.Tensor` that shards on the last dim.
+        >>>
+        >>> sharded_mod = parallelize_module(m, tp_mesh, {"w1": ColwiseParallel()})
+        >>> ...
+
+    .. note:: By default ``ColwiseParallel`` output is sharded on the last dimension if the ``output_layouts`` not
+        specified, if there're operators that require specific tensor shape (i.e. before the paired ``RowwiseParallel``),
+        keep in mind that if the output is sharded the operator might need to be adjusted to the sharded size.
+    """
+
+    def __init__(
+        self,
+        *,
+        input_layouts: Optional[Placement] = None,
+        output_layouts: Optional[Placement] = None,
+        use_local_output: bool = True,
+    ):
+        super().__init__()
+        self.input_layouts = (input_layouts or Replicate(),)
+        self.output_layouts = (output_layouts or Shard(-1),)
+        # colwise linear runtime sharding (desired sharding):
+        # 1. requires replicate input
+        # 2. shard output on last dim
+        self.desired_input_layouts = (Replicate(),)
+        self.use_local_output = use_local_output
+
+    @staticmethod
+    def _prepare_input_fn(
+        input_layouts, desired_input_layouts, mod, inputs, device_mesh
+    ):
+        # TODO: figure out dynamo support for instance method and switch this to instance method
+
+        # annotate module input placements/sharding with input_layouts
+        input_tensor = inputs[0]
+        if not isinstance(input_tensor, DTensor):
+            input_tensor = DTensor.from_local(
+                input_tensor, device_mesh, input_layouts, run_check=False
+            )
+
+        # transform the input layouts to the desired layouts of ColwiseParallel
+        if input_layouts != desired_input_layouts:
+            input_tensor = input_tensor.redistribute(
+                placements=desired_input_layouts, async_op=True
+            )
+        return input_tensor
+
+    def _partition_linear_fn(self, name, module, device_mesh):
+        # colwise shard weight/bias to Shard(0), weight be Shard(0)
+        # means Colwise as Linear is input * weight^T + bias, where
+        # weight would become Shard(1)
+        for name, param in module.named_parameters():
+            dist_param = nn.Parameter(distribute_tensor(param, device_mesh, [Shard(0)]))
+            module.register_parameter(name, dist_param)
+
+    def _partition_embedding_fn(self, name, module, device_mesh):
+        # colwise shard embedding.weight is straight forward as Shard(1)
+        for name, param in module.named_parameters():
+            dist_param = nn.Parameter(distribute_tensor(param, device_mesh, [Shard(1)]))
+            module.register_parameter(name, dist_param)
+
+    @staticmethod
+    def _prepare_output_fn(output_layouts, use_local_output, mod, outputs, device_mesh):
+        # outputs is a shard on last dimension DTensor, i.e. Shard(-1)
+        if outputs.placements != output_layouts:
+            outputs = outputs.redistribute(placements=output_layouts, async_op=True)
+        # back to local tensor
+        return outputs.to_local() if use_local_output else outputs
+
+    def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
+        if isinstance(module, nn.Linear):
+            partition_fn = self._partition_linear_fn
+        elif isinstance(module, nn.Embedding):
+            partition_fn = self._partition_embedding_fn
+        else:
+            raise NotImplementedError(
+                "ColwiseParallel currently only support nn.Linear and nn.Embedding!"
+            )
+
+        return distribute_module(
+            module,
+            device_mesh,
+            partition_fn,
+            partial(
+                self._prepare_input_fn, self.input_layouts, self.desired_input_layouts
+            ),
+            partial(
+                self._prepare_output_fn, self.output_layouts, self.use_local_output
+            ),
+        )
+
+
+class RowwiseParallel(ParallelStyle):
+    """
+    Partition a compatible nn.Module in a row-wise fashion. Currently supports nn.Linear and nn.Embedding.
+    Users can compose it with ColwiseParallel to achieve the sharding of more complicated modules.
+    (i.e. MLP, Attention)
+
+    Keyword Args:
+        input_layouts (Placement, optional):
+            The DTensor layout of input tensor for the nn.Module, this is used to annotate the input tensor to
+            become a DTensor. If not specified, we assume the input tensor to be sharded on the last dimension.
+        output_layouts (Placement, optional):
+            The DTensor layout of the output for the nn.Module, this is used to ensure the output of the nn.Module
+            with the user desired layout. If not specified, the output tensor is replicated.
+        use_local_output (bool, optional):
+            Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module output, default: True.
+    Returns:
+        A :class:`ParallelStyle` object that represents Rowwise sharding of the nn.Module.
+
+    Example::
+        >>> # xdoctest: +SKIP(failing)
+        >>> from torch.distributed.tensor.parallel import parallelize_module, RowwiseParallel
+        >>> from torch.distributed.device_mesh import init_device_mesh
+        >>> ...
+        >>> m = Model(...)  # m is a nn.Module that contains a "w2" nn.Linear submodule
+        >>> tp_mesh = init_device_mesh("cuda", (8,))
+        >>>
+        >>> # By default, the input of the "w2" Linear will be converted to DTensor that shards on the last dim
+        >>> # and the output of "w2" will return a replicated :class:`torch.Tensor`.
+        >>>
+        >>> sharded_mod = parallelize_module(m, tp_mesh, {"w2": RowwiseParallel()}),
+        >>> ...
+    """
+
+    def __init__(
+        self,
+        *,
+        input_layouts: Optional[Placement] = None,
+        output_layouts: Optional[Placement] = None,
+        use_local_output: bool = True,
+    ):
+        super().__init__()
+        self.input_layouts = (input_layouts or Shard(-1),)
+        self.output_layouts = (output_layouts or Replicate(),)
+        self.use_local_output = use_local_output
+
+    @staticmethod
+    def _prepare_input_fn(
+        input_layouts, desired_input_layouts, mod, inputs, device_mesh
+    ):
+        input_tensor = inputs[0]
+        if not isinstance(input_tensor, DTensor):
+            input_tensor = DTensor.from_local(
+                input_tensor, device_mesh, input_layouts, run_check=False
+            )
+
+        if input_layouts != desired_input_layouts:
+            input_tensor = input_tensor.redistribute(
+                placements=desired_input_layouts, async_op=True
+            )
+        return input_tensor
+
+    def _partition_linear_fn(self, name, module, device_mesh):
+        # Rowwise shard weight to Shard(1), bias to Replicate(), weight be Shard(1)
+        # means Rowwise as nn.Linear is input * weight^T + bias, where
+        # weight would become Shard(0)
+        module.register_parameter(
+            "weight",
+            nn.Parameter(distribute_tensor(module.weight, device_mesh, [Shard(1)])),
+        )
+        if getattr(module, "bias", None) is not None:
+            # The Linear module has bias
+            module.register_parameter(
+                "bias",
+                nn.Parameter(
+                    distribute_tensor(module.bias, device_mesh, [Replicate()])
+                ),
+            )
+
+    def _partition_embedding_fn(self, name, module, device_mesh):
+        # rowwise shard embedding.weight is Shard(0)
+        for name, param in module.named_parameters():
+            dist_param = nn.Parameter(distribute_tensor(param, device_mesh, [Shard(0)]))
+            module.register_parameter(name, dist_param)
+
+    @staticmethod
+    def _prepare_output_fn(output_layouts, use_local_output, mod, outputs, device_mesh):
+        # Rowwise sharding produces partial output, depending on output layouts:
+        # 1. to replicate -> allreduce
+        # 2. to shard -> reduce_scatter
+        if outputs.placements != output_layouts:
+            outputs = outputs.redistribute(placements=output_layouts, async_op=True)
+        # back to local tensor if use_local_output is True
+        return outputs.to_local() if use_local_output else outputs
+
+    def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
+        if isinstance(module, nn.Linear):
+            partition_fn = self._partition_linear_fn
+            # rowwise linear runtime sharding requires input tensor shard on last dim
+            self.desired_input_layouts: Tuple[Placement, ...] = (Shard(-1),)
+        elif isinstance(module, nn.Embedding):
+            partition_fn = self._partition_embedding_fn
+            # rowwise embedding runtime sharding requires input tensor replicated
+            self.desired_input_layouts = (Replicate(),)
+        else:
+            raise NotImplementedError(
+                "RowwiseParallel currently only support nn.Linear and nn.Embedding!"
+            )
+
+        return distribute_module(
+            module,
+            device_mesh,
+            partition_fn,
+            partial(
+                self._prepare_input_fn, self.input_layouts, self.desired_input_layouts
+            ),
+            partial(
+                self._prepare_output_fn, self.output_layouts, self.use_local_output
+            ),
+        )
+
+
+class SequenceParallel(ParallelStyle):
+    """
+    SequenceParallel replicates a compatible ``nn.Module`` parameters and runs the sharded computation with
+    input sharded on the sequence dimension. This currently supports ``nn.LayerNorm``, ``nn.Dropout``, and the
+    `RMSNorm python implementation `__
+
+    This style implements the operation that is described in the paper
+    `Reducing Activation Recomputation in Large Transformer Models `__
+
+    If the input passed in to this ``nn.Module`` is a :class:`torch.Tensor`, it assumes that the input is already sharded
+    on the sequence dimension and converts the input to a :class:`DTensor` sharded on the sequence dimension. If the input
+    passed in to this ``nn.Module`` is already a :class:`DTensor` but is not sharded on the sequence dimension, it would
+    redistribute the input to be sharded on the sequence dimension.
+
+    The output of the ``nn.Module`` will be sharded on the sequence dimension.
+
+    Keyword Args:
+        sequence_dim (int, optional):
+            The sequence dimension of the input tensor for the ``nn.Module``, this is used to annotate the input tensor to
+            become a DTensor that is sharded on the sequence dimension, default: 1.
+        use_local_output (bool, optional):
+            Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module output, default: False.
+    Returns:
+        A :class:`ParallelStyle` object that represents Sequence Parallel of the ``nn.Module``.
+
+    Example::
+        >>> # xdoctest: +SKIP(failing)
+        >>> from torch.distributed.tensor.parallel import parallelize_module, SequenceParallel
+        >>> from torch.distributed.device_mesh import init_device_mesh
+        >>> ...
+        >>> m = Model(...)  # m is a nn.Module that contains a "norm" nn.LayerNorm submodule
+        >>> tp_mesh = init_device_mesh("cuda", (8,))
+        >>>
+        >>> # By default, the input of the "norm" will be converted to DTensor that shards on the sequence dim
+        >>> # and the output of "norm" will return a sharded on sequence dimension :class:`DTensor`.
+        >>>
+        >>> sharded_mod = parallelize_module(m, tp_mesh, {"norm": SequenceParallel()}),
+        >>> ...
+
+    .. note:: SequenceParallel style assumes ones initialization if there are weights in the nn.Module (i.e.
+        ``nn.LayerNorm`` or ``RMSNorm``, and they by default have ones initialization). If you have custom
+        inits for the weights on those modules, you need to broadcast the weights before/after parallelizing
+        to ensure that they are replicated.
+    """
+
+    def __init__(self, *, sequence_dim: int = 1, use_local_output: bool = False):
+        super().__init__()
+        self.sequence_sharding = (Shard(sequence_dim),)
+        self.use_local_output = use_local_output
+
+    def _replicate_module_fn(
+        self, name: str, module: nn.Module, device_mesh: DeviceMesh
+    ):
+        for p_name, param in module.named_parameters():
+            # simple replication with fixed ones_ init from LayerNorm/RMSNorm, which allow
+            # us to simply just use from_local
+            replicated_param = torch.nn.Parameter(
+                DTensor.from_local(param, device_mesh, [Replicate()], run_check=False)
+            )
+            module.register_parameter(p_name, replicated_param)
+
+    @staticmethod
+    def _prepare_input_fn(sequence_sharding, mod, inputs, device_mesh):
+        input_tensor = inputs[0]
+        if isinstance(input_tensor, DTensor):
+            # if the passed in input DTensor is not sharded on the sequence dim, we need to redistribute it
+            if input_tensor.placements != sequence_sharding:
+                input_tensor = input_tensor.redistribute(
+                    placements=sequence_sharding, async_op=True
+                )
+            return input_tensor
+        elif isinstance(input_tensor, torch.Tensor):
+            # assume the input passed in already sharded on the sequence dim and create the DTensor
+            return DTensor.from_local(
+                input_tensor, device_mesh, sequence_sharding, run_check=False
+            )
+        else:
+            raise ValueError(
+                f"expecting input of {mod} to be a torch.Tensor or DTensor, but got {input_tensor}"
+            )
+
+    @staticmethod
+    def _prepare_output_fn(use_local_output, mod, outputs, device_mesh):
+        return outputs.to_local() if use_local_output else outputs
+
+    def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
+        return distribute_module(
+            module,
+            device_mesh,
+            self._replicate_module_fn,
+            partial(self._prepare_input_fn, self.sequence_sharding),
+            partial(self._prepare_output_fn, self.use_local_output),
+        )
+
+
+class PrepareModuleInput(ParallelStyle):
+    """
+    Configure the nn.Module's inputs to convert the input tensors of the nn.Module to DTensors at runtime according to
+    ``input_layouts``, and perform layout redistribution according to the ``desired_input_layouts``.
+
+    Keyword Args:
+        input_layouts (Union[Placement, Tuple[Optional[Placement]]]):
+            The DTensor layouts of input tensors for the nn.Module, this is used to convert the input tensors to
+            DTensors. If some inputs are not torch.Tensor or no need to convert to DTensors, ``None`` need to be specified
+            as a placeholder. default: None.
+        desired_input_layouts (Union[Placement, Tuple[Optional[Placement]]]):
+            The desired DTensor layout of input tensors for the nn.Module, this is used to ensure the inputs of the nn.Module
+            have the desired DTensor layouts. This argument needs to have the same length with ``input_layouts``. default: None.
+        input_kwarg_layouts (Dict[str, Placement]):
+            The DTensor layouts of input kwargs for the nn.Module, this is used to convert the input kwarg tensors to DTensors.
+            default: None
+        desired_input_kwarg_layouts: (Dict[str, Placement]):
+            The desired DTensor layout of input kwargs for the nn.Module, this is used to ensure the inputs of the nn.Module
+            have the desired DTensor layouts. default: None.
+        use_local_output (bool, optional):
+            Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module inputs, default: False.
+    Returns:
+        A :class:`ParallelStyle` object that prepares the sharding layouts of the nn.Module's inputs.
+
+    Example::
+        >>> # xdoctest: +SKIP(failing)
+        >>> from torch.distributed.tensor.parallel import parallelize_module, PrepareModuleInput
+        >>> from torch.distributed.device_mesh import init_device_mesh
+        >>> ...
+        >>> block = TransformerBlock(...)  # block is a nn.Module that contains an "attn" Attention submodule
+        >>> tp_mesh = init_device_mesh("cuda", (8,))
+        >>>
+        >>> # According to the style specified below, the first input of attn will be annotated to Sharded DTensor
+        >>> # and then redistributed to Replicated DTensor.
+        >>> parallelize_module(
+        >>>     block, # this can be a submodule or module
+        >>>     tp_mesh,
+        >>>     parallelize_plan={
+        >>>         "attn": PrepareModuleInput(
+        >>>             input_layouts=(Shard(0), None, None, ...),
+        >>>             desired_input_layouts=(Replicate(), None, None, ...)
+        >>>         ),
+        >>>     }
+        >>> )
+    """
+
+    def __init__(
+        self,
+        *,
+        input_layouts: Optional[Union[Placement, Tuple[Optional[Placement]]]] = None,
+        desired_input_layouts: Optional[
+            Union[Placement, Tuple[Optional[Placement]]]
+        ] = None,
+        input_kwarg_layouts: Optional[Dict[str, Placement]] = None,
+        desired_input_kwarg_layouts: Optional[Dict[str, Placement]] = None,
+        use_local_output: bool = False,
+    ):
+        self.input_layouts = (
+            (input_layouts,) if isinstance(input_layouts, Placement) else input_layouts
+        )
+        self.desired_input_layouts = (
+            (desired_input_layouts,)
+            if isinstance(desired_input_layouts, Placement)
+            else desired_input_layouts
+        )
+        self.use_local_output = use_local_output
+        if self.input_layouts is not None:
+            assert (
+                self.desired_input_layouts is not None
+            ), "desired module inputs should not be None!"
+            assert len(self.input_layouts) == len(
+                self.desired_input_layouts
+            ), "input_layouts and desired_input_layouts should have same length!"
+        self.with_kwargs = input_kwarg_layouts is not None
+        self.input_kwarg_layouts = input_kwarg_layouts or {}
+        self.desired_input_kwarg_layouts = desired_input_kwarg_layouts or {}
+        if self.with_kwargs:
+            assert len(self.input_kwarg_layouts) == len(
+                self.desired_input_kwarg_layouts
+            ), "input_kwarg_layouts and desired_input_kwarg_layouts should have same length!"
+
+    def _prepare_input_arg(
+        self,
+        input: Any,
+        mesh: DeviceMesh,
+        input_layout: Optional[Placement],
+        desired_layout: Optional[Placement],
+    ):
+        if input_layout is not None:
+            if isinstance(input, DTensor):
+                # TODO: re-enable the check once we fix the compile path
+                # assert inp.placements[0] == input_layout
+                dt_inp = input
+            else:
+                assert isinstance(
+                    input, torch.Tensor
+                ), "expecting input to be a torch.Tensor!"
+                dt_inp = DTensor.from_local(
+                    input, mesh, (input_layout,), run_check=False
+                )
+
+            if desired_layout is not None and input_layout != desired_layout:
+                dt_inp = dt_inp.redistribute(placements=(desired_layout,))
+
+            return dt_inp.to_local() if self.use_local_output else dt_inp
+        else:
+            return input
+
+    def _prepare_input_fn(self, inputs, device_mesh):
+        if self.input_layouts is None:
+            return inputs
+        prepared_inputs = []
+        if not isinstance(inputs, tuple):
+            inputs = (inputs,)
+        if len(inputs) != len(self.input_layouts):
+            raise ValueError("module inputs and input_layouts should have same length!")
+
+        assert (
+            self.desired_input_layouts is not None
+        ), "desired module inputs should not be None!"
+        for inp, input_layout, desired_layout in zip(
+            inputs, self.input_layouts, self.desired_input_layouts
+        ):
+            prepared_inputs.append(
+                self._prepare_input_arg(inp, device_mesh, input_layout, desired_layout)
+            )
+        return tuple(prepared_inputs)
+
+    def _prepare_input_kwarg_fn(self, inputs, kwarg_inputs, device_mesh):
+        prepared_arg_inputs = self._prepare_input_fn(inputs, device_mesh)
+        prepared_kwarg_inputs = {}
+        for kwarg_key in kwarg_inputs.keys():
+            kwarg_val = kwarg_inputs[kwarg_key]
+            input_layout = self.input_kwarg_layouts.get(kwarg_key)
+            desired_input_layout = self.desired_input_kwarg_layouts.get(kwarg_key)
+
+            prepared_kwarg_inputs[kwarg_key] = self._prepare_input_arg(
+                kwarg_val, device_mesh, input_layout, desired_input_layout
+            )
+
+        return (prepared_arg_inputs, prepared_kwarg_inputs)
+
+    def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
+        if self.with_kwargs:
+            module.register_forward_pre_hook(
+                lambda _, inputs, kwargs: self._prepare_input_kwarg_fn(
+                    inputs, kwargs, device_mesh
+                ),
+                with_kwargs=True,
+            )  # type: ignore[misc]
+        else:
+            module.register_forward_pre_hook(lambda _, inputs: self._prepare_input_fn(inputs, device_mesh))  # type: ignore[misc, call-arg]
+        return module
+
+
+class PrepareModuleOutput(ParallelStyle):
+    """
+    Configure the nn.Module's outputs to convert the output tensors of the nn.Module to DTensors at runtime according to
+    ``output_layouts``, and perform layout redistribution according to the ``desired_output_layouts``.
+
+    Keyword Args:
+        output_layouts (Union[Placement, Tuple[Placement]]):
+            The DTensor layouts of output tensors for the nn.Module, this is used to convert the output tensors to
+            DTensors if they are :class:`torch.Tensor`. If some outputs are not torch.Tensor or no need to convert to DTensors,
+            ``None`` need to be specified as a placeholder.
+        desired_output_layouts (Union[Placement, Tuple[Placement]]):
+            The desired DTensor layouts of output tensors for the nn.Module, this is used to ensure the outputs of the nn.Module
+            have the desired DTensor layouts.
+        use_local_output (bool, optional):
+            Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module outputs, default: True.
+    Returns:
+        A ParallelStyle object that prepares the sharding layouts of the nn.Module's outputs.
+
+    Example::
+        >>> # xdoctest: +SKIP(failing)
+        >>> from torch.distributed.tensor.parallel import parallelize_module, PrepareModuleOutput
+        >>> from torch.distributed.device_mesh import init_device_mesh
+        >>> ...
+        >>> block = TransformerBlock(...)  # block is a nn.Module that contains an "attn" Attention submodule
+        >>> tp_mesh = init_device_mesh("cuda", (8,))
+        >>>
+        >>> # According to the style specified below, the output of the TransformerBlock will be converted to Replicated DTensor
+        >>> # and then redistributed to Sharded DTensor.
+        >>> parallelize_module(
+        >>>     block, # this can be a submodule or module
+        >>>     tp_mesh,
+        >>>     parallelize_plan = PrepareModuleOutput(
+        >>>         output_layouts=Replicate(),
+        >>>         desired_output_layouts=Shard(0)
+        >>>     )
+        >>> )
+    """
+
+    def __init__(
+        self,
+        *,
+        output_layouts: Union[Placement, Tuple[Placement]],
+        desired_output_layouts: Union[Placement, Tuple[Placement]],
+        use_local_output: bool = True,
+    ):
+        self.output_layouts = (
+            (output_layouts,)
+            if isinstance(output_layouts, Placement)
+            else output_layouts
+        )
+        self.desired_output_layouts = (
+            (desired_output_layouts,)
+            if isinstance(desired_output_layouts, Placement)
+            else desired_output_layouts
+        )
+        self.use_local_output = use_local_output
+        assert len(self.output_layouts) == len(
+            self.desired_output_layouts
+        ), "output_layouts and desired_output_layouts should have same length!"
+
+    def _prepare_out_fn(self, outputs, device_mesh):
+        prepared_outputs = []
+        if not isinstance(outputs, tuple):
+            outputs = (outputs,)
+        if len(outputs) != len(self.output_layouts):
+            raise ValueError(
+                "module outputs and output_layouts should have same length!"
+            )
+        for out, out_layout, desired_out_layout in zip(
+            outputs, self.output_layouts, self.desired_output_layouts
+        ):
+            if out_layout is not None:
+                if isinstance(out, DTensor):
+                    # TODO: re-enable the check once we fix the compile path
+                    # assert out.placements[0] == out_layout
+                    dt_out = out
+                else:
+                    dt_out = DTensor.from_local(
+                        out, device_mesh, (out_layout,), run_check=False
+                    )
+
+                if out_layout != desired_out_layout:
+                    dt_out = dt_out.redistribute(placements=(desired_out_layout,))
+                prepared_outputs.append(
+                    dt_out.to_local() if self.use_local_output else dt_out
+                )
+            else:
+                prepared_outputs.append(out)
+        if len(prepared_outputs) == 1:
+            return prepared_outputs[0]
+        else:
+            return tuple(prepared_outputs)
+
+    def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
+        module.register_forward_hook(lambda _, inputs, outputs: self._prepare_out_fn(outputs, device_mesh))  # type: ignore[misc, call-arg]
+        return module
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/placement_types.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/placement_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d9834ab8b81cddd7efba11a180465513db615d0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/distributed/tensor/placement_types.py
@@ -0,0 +1,652 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and affiliates
+
+from dataclasses import dataclass
+from typing import cast, List, Optional, Tuple
+
+import torch
+import torch.distributed._functional_collectives as funcol
+from torch.distributed.device_mesh import DeviceMesh
+from torch.distributed.tensor._collective_utils import (
+    fill_empty_tensor_to_shards,
+    mesh_broadcast,
+    mesh_scatter,
+    pad_tensor,
+    shard_dim_alltoall,
+    unpad_tensor,
+)
+
+
+__all__ = ["Placement", "Shard", "Replicate", "Partial"]
+
+
+class Placement:
+    """
+    The base class for the Placement type, where it describes how a DTensor is placed onto the
+    ``DeviceMesh``. ``Placement`` and ``DeviceMesh`` together could describe the DTensor Layout.
+    It is the base class of the three main DTensor Placement types: ``Shard``, ``Replicate``,
+    and ``Partial``.
+
+    This class is not meant to be used directly, mainly served as a typing stub.
+    """
+
+    # convenient utils to check for placement types
+    def is_shard(self, dim: Optional[int] = None) -> bool:
+        is_shard_instance = isinstance(self, Shard)
+        if dim is not None and is_shard_instance:
+            return cast(Shard, self).dim == dim
+        else:
+            return is_shard_instance
+
+    def is_replicate(self) -> bool:
+        return isinstance(self, Replicate)
+
+    def is_partial(self) -> bool:
+        return isinstance(self, Partial)
+
+
+@dataclass(frozen=True)
+class Shard(Placement):
+    """
+    The ``Shard(dim)`` placement describes the DTensor sharding on tensor dimension
+    ``dim`` over a corresponding ``DeviceMesh`` dimension, where each rank on the
+    DeviceMesh dimension only holds a shard/piece of the global Tensor. The
+    ``Shard(dim)`` placement follows the ``torch.chunk(dim)`` semantic, where the
+    last few shards on the DeviceMesh dimension might be empty when the tensor dimension
+    is not evenly divisble on the DeviceMesh dimension. The ``Shard`` placement can be
+    used by all DTensor APIs (i.e. distribute_tensor, from_local, etc.)
+
+    Args:
+        dim (int): The tensor dimension that describes the DTensor is sharded over its
+            corresponding DeviceMesh dimension.
+
+    .. warning:: sharding on a tensor dimension where the tensor dimension size is not
+        evenly divisible on a DeviceMesh dimension is currently experimental and subject to change.
+    """
+
+    dim: int
+
+    def _split_tensor(
+        self,
+        tensor: torch.Tensor,
+        num_chunks: int,
+        *,
+        with_padding: bool = True,
+        contiguous: bool = True,
+    ) -> Tuple[List[torch.Tensor], List[int]]:
+        """
+        This function uses torch.chunk to split a tensor into num_chunks shards along
+        the Shard placement dimension, and return a list of shards with their pad sizes.
+
+        Keyword args:
+            with_padding (bool, optional): when True, we pad the tensor on the last
+            few ranks before calling the collectives (i.e. scatter/all_gather, etc.).
+            This is because collectives usually require equal size tensor inputs
+        """
+        assert (
+            self.dim <= tensor.ndim
+        ), f"Sharding dim {self.dim} greater than tensor ndim {tensor.ndim}"
+
+        # chunk tensor over dimension `dim` into n slices
+        tensor_list = list(torch.chunk(tensor, num_chunks, dim=self.dim))
+        num_empty_tensors = num_chunks - len(tensor_list)
+
+        # if no need to have padding or tensor dim size is evenly sharded already
+        # we can return early.
+        if not with_padding or tensor.size(self.dim) % num_chunks == 0:
+            if contiguous:
+                tensor_list = [t.contiguous() for t in tensor_list]
+            return (
+                fill_empty_tensor_to_shards(tensor_list, self.dim, num_empty_tensors),
+                [],
+            )
+
+        # compute the chunk size inline with ``torch.chunk`` to calculate padding
+        full_chunk_size = (tensor.size(self.dim) + num_chunks - 1) // num_chunks
+
+        # Compute chunk size for each chunk for ``self.dim``
+        chunk_sizes = [
+            tensor_list[idx].size(self.dim) if idx < len(tensor_list) else 0
+            for idx in range(num_chunks)
+        ]
+        # Compute pad size on each chunk
+        pad_sizes = [full_chunk_size - chunk_size for chunk_size in chunk_sizes]
+
+        # Reuse tensor to fill empty chunk with empty tensor
+        tensor_list = fill_empty_tensor_to_shards(
+            tensor_list, self.dim, num_empty_tensors
+        )
+        shard_list = []
+        for shard, pad_size in zip(tensor_list, pad_sizes):
+            # Fill the empty tensor with zeroes with padding.
+            if with_padding and pad_size > 0:
+                shard = pad_tensor(shard, self.dim, pad_size)
+            shard = shard.contiguous() if contiguous else shard
+            shard_list.append(shard)
+        return shard_list, pad_sizes
+
+    @staticmethod
+    def _local_shard_size_on_dim(
+        size_on_dim: int,
+        num_chunks: int,
+        rank: int,
+        return_offset: bool = False,
+    ) -> Tuple[int, int]:
+        """
+        returns the local shard size and offset on a given tensor dim
+        """
+        # Compute the chunk size inline with ``torch.chunk``
+        if size_on_dim % num_chunks == 0:
+            full_chunk_size = size_on_dim // num_chunks
+            return full_chunk_size, full_chunk_size * rank if return_offset else -1
+
+        # uneven sharding case
+        full_chunk_size = (size_on_dim + num_chunks - 1) // num_chunks
+        shard_starting_idx = full_chunk_size * rank
+
+        if size_on_dim < shard_starting_idx:
+            return 0, size_on_dim if return_offset else -1
+        else:
+            local_shard_size = (
+                min(size_on_dim, shard_starting_idx + full_chunk_size)
+                - shard_starting_idx
+            )
+            return local_shard_size, shard_starting_idx if return_offset else -1
+
+    def _shard_tensor(
+        self, tensor: torch.Tensor, mesh: DeviceMesh, mesh_dim: int
+    ) -> torch.Tensor:
+        """
+        shard and scatter a tensor on a mesh dimension (use coordinate
+        0 on the mesh dimension as source of truth)
+        """
+        my_coordinate = mesh.get_coordinate()
+        num_chunks = mesh.size(mesh_dim=mesh_dim)
+
+        if my_coordinate is None:
+            # if rank is not part of mesh, we simply return an empty tensor
+            return tensor.new_empty(0, requires_grad=tensor.requires_grad)
+
+        scatter_list, pad_sizes = self._split_tensor(
+            tensor, num_chunks, with_padding=True, contiguous=True
+        )
+
+        mesh_dim_local_rank = my_coordinate[mesh_dim]
+        output = torch.empty_like(scatter_list[mesh_dim_local_rank])
+        mesh_scatter(output, scatter_list, mesh, mesh_dim=mesh_dim)
+
+        # Only unpad if the local_tensor was padded on the dimension.
+        if pad_sizes and pad_sizes[mesh_dim_local_rank] > 0:
+            output = unpad_tensor(output, self.dim, pad_sizes[mesh_dim_local_rank])
+        return output
+
+    def _reduce_shard_tensor(
+        self,
+        tensor: torch.Tensor,
+        mesh: DeviceMesh,
+        reduce_op: str,
+        mesh_dim: int,
+    ) -> torch.Tensor:
+        """
+        reduce and scatter a tensor on a mesh dimension
+        """
+        my_coordinate = mesh.get_coordinate()
+        num_chunks = mesh.size(mesh_dim=mesh_dim)
+
+        if my_coordinate is None:
+            # if rank is not part of mesh, we simply return local_tensor,
+            # which should be an empty tensor
+            return tensor
+
+        is_padded = tensor.size(self.dim) % num_chunks != 0
+        if is_padded:
+            scattered_list, pad_sizes = self._split_tensor(
+                tensor, num_chunks, with_padding=True, contiguous=True
+            )
+            tensor = torch.cat(scattered_list, dim=self.dim)
+        elif not tensor.is_contiguous():
+            tensor = tensor.contiguous()
+
+        output = funcol.reduce_scatter_tensor(
+            tensor, reduce_op, scatter_dim=self.dim, group=(mesh, mesh_dim)
+        )
+
+        if is_padded:
+            output = unpad_tensor(output, self.dim, pad_sizes[my_coordinate[mesh_dim]])  # type: ignore[possibly-undefined]
+        return output
+
+    def _to_replicate_tensor(
+        self,
+        local_tensor: torch.Tensor,
+        mesh: DeviceMesh,
+        mesh_dim: int,
+        current_logical_shape: List[int],
+    ) -> torch.Tensor:
+        """
+        This function all_gather all shards and return a tensor that
+        is replicated on the previously sharded mesh dimension
+        """
+        num_chunks = mesh.size(mesh_dim=mesh_dim)
+        # check if it's uneven, so we need to pad input tensor before all_gather
+        local_shape = list(local_tensor.size())
+
+        logical_dim_size = current_logical_shape[self.dim]
+        is_padded = logical_dim_size % num_chunks != 0
+
+        if is_padded:
+            full_chunk_size = (logical_dim_size + num_chunks - 1) // num_chunks
+            pad_size = full_chunk_size - local_shape[self.dim]
+            local_tensor = pad_tensor(local_tensor, self.dim, pad_size)
+
+        if not local_tensor.is_contiguous():
+            local_tensor = local_tensor.contiguous()
+
+        result = funcol.all_gather_tensor(
+            local_tensor,
+            gather_dim=self.dim,
+            group=(mesh, mesh_dim),
+        )
+        if is_padded:
+            unpad_size = full_chunk_size * num_chunks - logical_dim_size  # type: ignore[possibly-undefined]
+            result = unpad_tensor(result, self.dim, unpad_size)
+        return result
+
+    def _replicate_to_shard(
+        self,
+        local_tensor: torch.Tensor,
+        mesh: DeviceMesh,
+        mesh_dim: int,
+        shard_index: int,
+    ) -> torch.Tensor:
+        """
+        transform from replicated tensor to a sharded tensor on
+        the current rank, which would perform a local chunk
+        """
+        num_chunks = mesh.size(mesh_dim=mesh_dim)
+        shards, _ = self._split_tensor(
+            local_tensor,
+            num_chunks,
+            with_padding=False,
+            contiguous=False,
+        )
+        return shards[shard_index].clone()
+
+    def _to_new_shard_dim(
+        self,
+        local_tensor: torch.Tensor,
+        mesh: DeviceMesh,
+        mesh_dim: int,
+        current_logical_shape: List[int],
+        new_shard_dim: int,
+    ) -> torch.Tensor:
+        """
+        transform from existing sharded tensor to a new sharded tensor on
+        that shard on a new dimension, which performs an alltoall
+        """
+        my_coordinate = mesh.get_coordinate()
+        if my_coordinate is None:
+            # if rank is not part of mesh, we simply return local_tensor,
+            # which should be an empty tensor
+            return local_tensor
+
+        num_chunks = mesh.size(mesh_dim=mesh_dim)
+
+        old_dim_logical_size = current_logical_shape[self.dim]
+        new_dim_logical_size = current_logical_shape[new_shard_dim]
+        old_dim_padding = old_dim_logical_size % num_chunks != 0
+        new_dim_padding = new_dim_logical_size % num_chunks != 0
+        if old_dim_padding:
+            old_dim_full_chunk_size = (
+                old_dim_logical_size + num_chunks - 1
+            ) // num_chunks
+            old_dim_pad_size = old_dim_full_chunk_size - local_tensor.size(self.dim)
+            local_tensor = pad_tensor(local_tensor, self.dim, old_dim_pad_size)
+        if new_dim_padding:
+            new_dim_full_chunk_size = (
+                new_dim_logical_size + num_chunks - 1
+            ) // num_chunks
+            new_dim_pad_size = new_dim_full_chunk_size * num_chunks - local_tensor.size(
+                new_shard_dim
+            )
+            local_tensor = pad_tensor(local_tensor, new_shard_dim, new_dim_pad_size)
+
+        if not local_tensor.is_contiguous():
+            local_tensor = local_tensor.contiguous()
+
+        new_tensor = shard_dim_alltoall(
+            local_tensor, self.dim, new_shard_dim, mesh, mesh_dim
+        )
+
+        if old_dim_padding:
+            old_dim_unpad_size = (
+                old_dim_full_chunk_size * num_chunks - current_logical_shape[self.dim]  # type: ignore[possibly-undefined]
+            )
+            new_tensor = unpad_tensor(new_tensor, self.dim, old_dim_unpad_size)  # type: ignore[possibly-undefined]
+
+        if new_dim_padding:
+            local_shard_size_on_new_dim = self._local_shard_size_on_dim(
+                new_dim_logical_size, num_chunks, my_coordinate[mesh_dim]
+            )[0]
+            new_dim_unpad_size = new_dim_full_chunk_size - local_shard_size_on_new_dim  # type: ignore[possibly-undefined]
+            new_tensor = unpad_tensor(new_tensor, new_shard_dim, new_dim_unpad_size)  # type: ignore[possibly-undefined]
+
+        return new_tensor
+
+    def __eq__(self, other: object) -> bool:
+        if not isinstance(other, Shard):
+            return False
+        return self.dim == other.dim
+
+    def __hash__(self) -> int:
+        return hash(self.dim)
+
+    def __repr__(self) -> str:
+        """
+        machine readable representation of the Shard placement
+        """
+        return f"Shard(dim={self.dim})"
+
+    def __str__(self) -> str:
+        """human readable representation of the Shard placement"""
+        return f"S({self.dim})"
+
+
+# kw_only is only available in python >= 3.10
+kw_only_dataclass = dict(kw_only=True) if "kw_only" in dataclass.__kwdefaults__ else {}
+
+
+@dataclass(frozen=True, **kw_only_dataclass)
+class _StridedShard(Shard):
+    """
+    _StridedShard is only introduced to support 2D FSDP2 + TP sharding where the tensor
+    is sharded on the TP mesh dimension first, then sharded on the FSDP mesh dimension.
+    We call this right-to-left sharding which is the opposite of the default
+    left-to-right sharding. See the example below:
+        tensor shape: [8, 8]
+        mesh: [[0, 1], [2, 3]], names=("dp", "tp")
+        placements: [Shard(0), Shard(0)]
+
+    The default sharding behavior shards the tensor on "dp" mesh dimension first then
+    "tp" dimension. The sharding result will be:
+        Rank    |   Mesh Coordinate |   Shard Index
+        ------------------------------------------------
+        0       |   (0, 0)          |   0 (row 0-1)
+        1       |   (0, 1)          |   1 (row 2-3)
+        2       |   (1, 0)          |   2 (row 4-5)
+        3       |   (1, 1)          |   3 (row 6-7)
+
+    While the FSDP2 + TP sharding behavior does the opposite: it shards the tensor on
+    "tp" mesh dim first then "dp" dim. This right-to-left sharding will produce the
+    result:
+        Rank    |   Mesh Coordinate |   Shard Index
+        ------------------------------------------------
+        0       |   (0, 0)          |   0 (row 0-1)
+        1       |   (0, 1)          |   2 (row 4-5)
+        2       |   (1, 0)          |   1 (row 2-3)
+        3       |   (1, 1)          |   3 (row 6-7)
+
+    The consequence is, any attempt to redistribute this DTensor to a full replica will
+    produce a wrong result because the shard-to-replicate redistribution always happens
+    right-to-left, regardless it's left-to-right sharding or right-to-left. To address
+    this, we use _StridedShard placement to make this right-to-left sharding compatible
+    with our left-to-right convention on both tensor distribution and redistribution.
+
+    Now with _StridedShard, the right-to-left sharding above can be represented as:
+        tensor shape: [8, 8]
+        mesh: [[0, 1], [2, 3]], names=("dp", "tp")
+        placements: [_StridedShard(0, split_factor=2), Shard(0)]
+
+    And a left-to-right processing of `placements` will produce the same result, which is
+    different from using the `Shard` placement:
+        Rank    |   Mesh Coordinate |   Shard Index
+        ------------------------------------------------
+        0       |   (0, 0)          |   0 (row 0-1)
+        1       |   (0, 1)          |   2 (row 4-5)
+        2       |   (1, 0)          |   1 (row 2-3)
+        3       |   (1, 1)          |   3 (row 6-7)
+
+    The argument `split_factor` is the number of existing shards over the tensor sharding
+    dimension before processing the _StridedShard placement, as if the sharding happened
+    right-to-left. In the example above, the tensor should first be sharded on the "tp"
+    dimension into 2 shards before being sharded on the "dp" dimension. Therefore, the
+    `split_factor` of the _StridedShard placement on "dp" dim is 2.
+
+    TODO: strided sharding needs to work fine with uneven sharding. Now it forbids
+    resharding if the tensor is unevenly sharded.
+    TODO: we should remove _StridedShard placement once we can unify it with Shard
+    """
+
+    split_factor: int
+
+    def __eq__(self, other: object) -> bool:
+        if isinstance(other, _StridedShard):
+            return self.dim == other.dim and self.split_factor == other.split_factor
+        elif isinstance(other, Shard):
+            # TODO: this is to avoid extra all-gather in dtensor op dispatch
+            # note that sharding prop would not produce _StridedShard and an
+            # placement inequality would introduce an all-gather for resharding
+            return self.dim == other.dim
+        return False
+
+    def __hash__(self) -> int:
+        return hash((self.dim, self.split_factor))
+
+    def __repr__(self) -> str:
+        """
+        machine readable representation of the _StridedShard placement
+        """
+        return f"_StridedShard(dim={self.dim}, sf={self.split_factor})"
+
+    def __str__(self) -> str:
+        """human readable representation of the _StridedShard placement"""
+        return f"_S({self.dim}, {self.split_factor})"
+
+    def _split_tensor(
+        self,
+        tensor: torch.Tensor,
+        num_chunks: int,
+        *,
+        with_padding: bool = True,
+        contiguous: bool = True,
+    ) -> Tuple[List[torch.Tensor], List[int]]:
+        """
+        TODO: currently _StridedShard does not support padding
+        """
+        assert (
+            self.dim <= tensor.ndim
+        ), f"Sharding dim {self.dim} greater than tensor ndim {tensor.ndim}"
+
+        total_split = num_chunks * self.split_factor
+        assert tensor.size(self.dim) % total_split == 0, (
+            "_StridedShard currently only allows even sharding but got tensor size"
+            f" {tensor.size(self.dim)} on dim {self.dim} and total split"
+            f" {total_split}={num_chunks} * {self.split_factor}"
+        )
+
+        group_size = self.split_factor
+        total_split_tensor_list = list(torch.chunk(tensor, total_split, dim=self.dim))
+        tensor_list = [
+            torch.cat(
+                [
+                    total_split_tensor_list[i + j * num_chunks]  # stride is num_chunks
+                    for j in range(group_size)
+                ],
+                dim=self.dim,
+            )
+            for i in range(num_chunks)
+        ]
+
+        if contiguous:
+            tensor_list = [t.contiguous() for t in tensor_list]
+
+        return tensor_list, []
+
+    def _to_replicate_tensor(
+        self,
+        local_tensor: torch.Tensor,
+        mesh: DeviceMesh,
+        mesh_dim: int,
+        current_logical_shape: List[int],
+    ) -> torch.Tensor:
+        """
+        Note: currently _StridedShard does not support padding
+        """
+        num_chunks = mesh.size(mesh_dim=mesh_dim)
+        total_split = num_chunks * self.split_factor
+        # NOTE: we require Strided Sharding to be even for now
+        assert current_logical_shape[self.dim] % total_split == 0, (
+            "_StridedShard requires even sharding but got tensor size "
+            f"{current_logical_shape[self.dim]} on dim {self.dim} and "
+            f"total split {total_split}=num_chunks {num_chunks} "
+            f"* split_factor {self.split_factor}"
+        )
+
+        result = funcol.all_gather_tensor(
+            local_tensor,
+            gather_dim=self.dim,
+            group=(mesh, mesh_dim),
+        )
+        if isinstance(result, funcol.AsyncCollectiveTensor):
+            result = result.wait()
+
+        tensor_shard_list = torch.chunk(result, total_split, dim=self.dim)
+        # rearrange the order
+        new_tensor_shard_list = []
+        for idx in range(len(tensor_shard_list)):
+            # the shard split of index `idx` is assigned a new index within
+            # _StridedShard._split_tensor:
+            # the original tensor was split into `total_split` chunks,
+            # all chunks with the same `idx % num_chunks` are merged into one
+            # new shard and placed on mesh's local rank `idx % num_chunks`
+            idx_after_split = idx % num_chunks * self.split_factor + idx // num_chunks
+            new_tensor_shard_list.append(tensor_shard_list[idx_after_split])
+
+        return torch.cat(new_tensor_shard_list, dim=self.dim).contiguous()
+
+
+@dataclass(frozen=True)
+class Replicate(Placement):
+    """
+    The ``Replicate()`` placement describes the DTensor replicating on a corresponding
+    ``DeviceMesh`` dimension, where each rank on the DeviceMesh dimension holds a
+    replica of the global Tensor. The ``Replicate`` placement can be used by all
+    DTensor APIs (i.e. ``distribute_tensor``, ``DTensor.from_local``, etc.)
+    """
+
+    def __eq__(self, other: object) -> bool:
+        return isinstance(other, Replicate)
+
+    def __hash__(self) -> int:
+        # every replicate placement is the same
+        return -1
+
+    def __repr__(self) -> str:
+        """
+        machine readable representation of the Replicate placement
+        """
+        return "Replicate()"
+
+    def __str__(self) -> str:
+        """
+        human readable representation of the Replicate placement
+        """
+        return "R"
+
+    def _replicate_tensor(
+        self, tensor: torch.Tensor, mesh: DeviceMesh, mesh_dim: int
+    ) -> torch.Tensor:
+        """
+        Replicate (broadcast) a torch.Tensor on a mesh dimension (use
+        the first coordinate on the mesh dimension as source of truth)
+        """
+        my_coordinate = mesh.get_coordinate()
+        if my_coordinate is None:
+            # if rank is not part of mesh, we simply return an empty tensor
+            return tensor.new_empty(0, requires_grad=tensor.requires_grad)
+
+        tensor = tensor.contiguous()
+        mesh_broadcast(tensor, mesh, mesh_dim=mesh_dim)
+        return tensor
+
+
+@dataclass(frozen=True)
+class Partial(Placement):
+    """
+    The ``Partial(reduce_op)`` placement describes the DTensor that is pending
+    reduction on a specified ``DeviceMesh`` dimension, where each rank on the
+    DeviceMesh dimension holds the partial value of the global Tensor. User can
+    redistribute the ``Partial`` DTensor to a ``Replicate`` or ``Shard(dim)``
+    placement on the specified ``DeviceMesh`` dimension using ``redistribute``,
+    which would trigger necessary communication operations under the hood (i.e.
+    ``allreduce``, ``reduce_scatter``).
+
+    Args:
+        reduce_op (str, optional): The reduction op to be used for the partial DTensor
+            to produce Replicated/Sharded DTensor. Only element-wise reduction operations
+            are supported, including: "sum", "avg", "product", "max", "min", default: "sum".
+
+    .. note:: The ``Partial`` placement can be generated as a result of the DTensor operators,
+        and can only be used by the ``DTensor.from_local`` API.
+    """
+
+    reduce_op: str = "sum"
+
+    def _reduce_value(
+        self, tensor: torch.Tensor, mesh: DeviceMesh, mesh_dim: int
+    ) -> torch.Tensor:
+        # Partial placement contract #1:
+        # _reduce_value: reduce the value of the tensor on the mesh dimension
+        return funcol.all_reduce(
+            tensor, reduceOp=self.reduce_op, group=(mesh, mesh_dim)
+        )
+
+    def _reduce_shard_value(
+        self,
+        tensor: torch.Tensor,
+        mesh: DeviceMesh,
+        mesh_dim: int,
+        shard_spec: Placement,
+    ) -> torch.Tensor:
+        # Partial placement contract #2:
+        # _reduce_shard_value: reduce_scatter the value of the tensor over the mesh dimension
+        shard_spec = cast(Shard, shard_spec)
+        return shard_spec._reduce_shard_tensor(tensor, mesh, self.reduce_op, mesh_dim)
+
+    def _partition_value(
+        self, tensor: torch.Tensor, mesh: DeviceMesh, mesh_dim: int
+    ) -> torch.Tensor:
+        # Partial placement contract #3:
+        # _partition_value: partition the value of a replicated tensor on the mesh dimension
+
+        # _partition_value is the conjugate operation of _reduce_value
+        # - i.e. _partition_value on a sum reduce op is just a divison operation
+        # - the _reduce_value on a sum reduce op would just be a sum(allreduce) operation
+        # TODO: if the reduce_op is min/max, etc. the _partition_value should be a
+        # different operation
+        assert self.reduce_op == "sum", "only support replicate to PartialSUM for now!"
+        num_chunks = mesh.size(mesh_dim=mesh_dim)
+        return tensor / num_chunks
+
+    def __eq__(self, other: object) -> bool:
+        if not isinstance(other, Partial):
+            return False
+        return self.reduce_op == other.reduce_op
+
+    def __hash__(self) -> int:
+        return 1 + hash(self.reduce_op)
+
+    def __repr__(self) -> str:
+        """
+        machine readable representation of the Partial placement
+        """
+        return f"Partial({self.reduce_op})"
+
+    def __str__(self) -> str:
+        """
+        human readable representation of the Partial placement
+        """
+        return "P"
+
+
+# We keep the old _Partial name for a while for BC reason
+_Partial = Partial
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h
new file mode 100644
index 0000000000000000000000000000000000000000..158813043af61883f4df398360c2894a303ac0ad
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h
@@ -0,0 +1,57 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+
+#include 
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace data {
+
+/// Creates a `DataLoader` instance for a stateless `dataset`, a `sampler` and
+/// some `options`.
+template 
+std::enable_if_t<
+    !Dataset::is_stateful,
+    std::unique_ptr>>
+make_data_loader(Dataset dataset, Sampler sampler, DataLoaderOptions options) {
+  return std::make_unique>(
+      std::move(dataset), std::move(sampler), std::move(options));
+}
+
+/// Creates a `DataLoader` instance for a stateless `dataset` and some
+/// `options`. A sampler (by default a `RandomSampler`) will be constructed from
+/// the size of the dataset.
+template 
+std::enable_if_t<
+    !Dataset::is_stateful && std::is_constructible_v,
+    std::unique_ptr>>
+make_data_loader(
+    Dataset dataset,
+    DataLoaderOptions options = DataLoaderOptions()) {
+  const std::optional size = dataset.size();
+  TORCH_CHECK(
+      size.has_value(),
+      "Expected the dataset to be sized in "
+      "order to construct the Sampler");
+  return make_data_loader(
+      std::move(dataset), Sampler(*size), std::move(options));
+}
+
+/// Creates a `DataLoader` for a stateful `dataset` and some `options`.
+template >
+std::unique_ptr> make_data_loader(
+    Dataset dataset,
+    DataLoaderOptions options = DataLoaderOptions()) {
+  return std::make_unique>(
+      std::move(dataset), std::move(options));
+}
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h
new file mode 100644
index 0000000000000000000000000000000000000000..cb17843ba0b33b7071e770e1e4e7b647b8443160
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h
@@ -0,0 +1,255 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace data {
+template 
+class DataLoaderBase {
+ public:
+  using BatchType = Batch;
+  using BatchRequestType = BatchRequest;
+
+  /// Constructs a new DataLoader from a `dataset` to sample from, `options`
+  /// to configure the DataLoader with, and a `sampler` that specifies the
+  /// sampling strategy.
+  DataLoaderBase(
+      DataLoaderOptions options,
+      std::unique_ptr main_thread_dataset = nullptr)
+      : options_(std::move(options)),
+        main_thread_dataset_(std::move(main_thread_dataset)),
+        sequencer_(new_sequencer()) {}
+
+  // NOLINTNEXTLINE(bugprone-exception-escape)
+  virtual ~DataLoaderBase() {
+    join();
+  }
+
+  /// Returns an iterator into the DataLoader. The lifetime of the iterator is
+  /// bound to the DataLoader. In C++ standards language, the category of the
+  /// iterator is `OutputIterator`. See
+  /// https://en.cppreference.com/w/cpp/named_req/OutputIterator for what this
+  /// means. In short: you may increment the iterator and dereference it, but
+  /// cannot go back, or step forward more than one position at a time. When the
+  /// DataLoader is exhausted, it will compare equal with the special
+  /// "sentinel" iterator returned by `DataLoader::end()`. Most of the time, you
+  /// should only use range-for loops to loop over the DataLoader, but
+  /// standard algorithms like `std::copy(dataloader.begin(), dataloader.end(),
+  /// output_iterator)`  are supported too.
+  Iterator begin() {
+    TORCH_CHECK(
+        shuttle_.in_flight_jobs() == 0,
+        "Attempted to get a new DataLoader iterator "
+        "while another iterator is not yet exhausted");
+    reset();
+    return Iterator(std::make_unique>(
+        [this] { return this->next(); }));
+  }
+
+  /// Returns a special "sentinel" iterator that compares equal with a
+  /// non-sentinel iterator once the DataLoader is exhausted.
+  Iterator end() {
+    return Iterator(std::make_unique>());
+  }
+
+  /// Joins the DataLoader's worker threads and drains internal queues.
+  /// This function may only be invoked from the main thread (in which the
+  /// DataLoader lives).
+  void join() {
+    if (joined_) {
+      return;
+    }
+    shuttle_.drain();
+    // Send one 'quit' message per worker. Since a worker dies (exits its
+    // thread) after receiving this message, each `QuitWorker()` message will be
+    // read by exactly one worker.
+    for (const auto w : c10::irange(options_.workers)) {
+      (void)w; // Suppress unused variable warning
+      push_job(QuitWorker());
+    }
+    for (auto& worker : workers_) {
+      worker.join();
+    }
+    joined_ = true;
+  }
+
+  /// Returns the options with which the DataLoader was configured.
+  const FullDataLoaderOptions& options() const noexcept {
+    return options_;
+  }
+
+ protected:
+  /// Simple mix-in to give something a sequence number.
+  struct Sequenced {
+    Sequenced() = default;
+    Sequenced(size_t sqn) : sequence_number(sqn) {}
+    size_t sequence_number;
+  };
+
+  struct QuitWorker {};
+
+  /// A `Job` is either a `BatchRequest` (new indices to fetch data at) or a
+  /// `QuitWorker` object, to indicate the worker should shut down.
+  struct Job : Sequenced {
+    Job() = default;
+    Job(QuitWorker q, size_t sqn) : Sequenced(sqn), quit(q) {}
+    Job(BatchRequest&& i, size_t sqn)
+        : Sequenced(sqn), batch_request(std::move(i)) {}
+    std::optional quit;
+    std::optional batch_request;
+  };
+
+  /// The finished result of a job.
+  struct Result : Sequenced {
+    Result() = default;
+    Result(std::optional&& b, size_t sqn)
+        : Sequenced(sqn), batch(std::move(b)) {}
+    Result(std::exception_ptr exception, size_t sqn)
+        : Sequenced(sqn), exception(std::move(exception)) {}
+    std::optional batch;
+    std::exception_ptr exception;
+  };
+
+  /// Subclass hook for getting the next batch request. The stateless case will
+  /// ask the sampler for a new batch request (e.g. a vector of indices), while
+  /// the stateful one will simply return the batch size.
+  virtual std::optional get_batch_request() = 0;
+
+  /// Resets the internal state of the DataLoader, optionally pre-fetching
+  /// new jobs.
+  virtual void reset() {
+    shuttle_.drain();
+    sequence_number_ = 0;
+    sequencer_ = new_sequencer();
+    prefetch();
+  }
+
+  /// Schedules `requested_jobs` many new batches to be fetched. The actual
+  /// number of jobs scheduled may be less if the DataLoader exhausts.
+  void prefetch(size_t requested_jobs) {
+    for (const auto r : c10::irange(requested_jobs)) {
+      (void)r; // Suppress unused variable
+      if (auto batch_request = get_batch_request()) {
+        this->push_job(std::move(*batch_request));
+      } else {
+        break;
+      }
+    }
+  }
+
+  /// Schedules the maximum number of jobs (based on the `max_jobs` option).
+  void prefetch() {
+    prefetch(options_.max_jobs);
+  }
+
+  /// Returns the next batch of data, or an empty `optional` if the DataLoader
+  /// is exhausted. This operation will block until a batch is available if one
+  /// is still expected.
+  std::optional next() {
+    if (options_.workers > 0) {
+      while (std::optional result = this->pop_result()) {
+        if (result->exception) {
+          throw WorkerException(result->exception);
+        } else if (result->batch) {
+          prefetch(1);
+          return std::move(result->batch);
+        }
+      }
+    } else if (auto batch_request = get_batch_request()) {
+      return this->main_thread_dataset_->get_batch(std::move(*batch_request));
+    }
+    return nullopt;
+  }
+
+  /// The function that worker threads run.
+  void worker_thread(Dataset& dataset) {
+    while (true) {
+      auto job = shuttle_.pop_job();
+      if (job.quit) {
+        break;
+      }
+      try {
+        auto batch = dataset.get_batch(std::move(*job.batch_request));
+        shuttle_.push_result({std::move(batch), job.sequence_number});
+      } catch (...) {
+        shuttle_.push_result({std::current_exception(), job.sequence_number});
+      }
+    }
+  }
+
+  /// Convenience method that calls `shuttle_.push_job()` with the next sequence
+  /// number.
+  template 
+  void push_job(T value) {
+    shuttle_.push_job({std::move(value), sequence_number_++});
+  }
+
+  /// Convenience method that gets the next result from the sequencer.
+  std::optional pop_result() {
+    return sequencer_->next(
+        [this] { return this->shuttle_.pop_result(this->options_.timeout); });
+  }
+
+  /// Convenience method that creates a new sequencer based on the
+  /// `enforce_ordering` option.
+  std::unique_ptr> new_sequencer() {
+    if (options_.enforce_ordering) {
+      return std::make_unique>(
+          options_.max_jobs);
+    }
+    return std::make_unique>();
+  }
+
+  /// The options the DataLoader was configured with.
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  const FullDataLoaderOptions options_;
+
+  /// The dataset for the main thread, only has a value if the number of
+  /// worker threads was configured as zero, meaning the main thread has to do
+  /// all the work (synchronously). NOTE: Really want this to be on the heap
+  /// when empty, therefore `unique_ptr` and not `optional`.
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  std::unique_ptr main_thread_dataset_;
+
+  /// The sequence number for the *next* batch to be retrieved from the
+  /// dataset.
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  size_t sequence_number_ = 0;
+
+  /// The worker threads, running the `worker_thread()` method.
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  std::vector workers_;
+
+  /// The `DataShuttle` which takes care of the life cycle of a job.
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  detail::DataShuttle shuttle_;
+
+  /// The `Sequencer`, which handles optional ordering of batches.
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  std::unique_ptr> sequencer_;
+
+  /// True if the DataLoader has joined its worker threads.
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  bool joined_ = false;
+};
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h
new file mode 100644
index 0000000000000000000000000000000000000000..6ae027119a0c9959870e886f28a9b13b44d532f0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h
@@ -0,0 +1,63 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace data {
+
+/// A dataloader for stateful datasets.
+///
+/// A dataloader for stateful datatasets differs from one for stateless
+/// datasets one in that the dataset is shared among worker threads, and that
+/// this dataset is itself responsible for producing batches rather than
+/// depending on a sampler. The statefulness here actually refers to the
+/// dataset. The StatefulDataLoader simply alters the data loading algorithm to
+/// accommodate the stateful, shared nature of the dataset. Note that the
+/// dataset must be thread safe if more than one worker thread is used.
+///
+/// A stateful dataloader is created by calling `make_data_loader` with a
+/// stateful dataset.
+template 
+class StatefulDataLoader : public DataLoaderBase<
+                               Dataset,
+                               typename Dataset::BatchType::value_type,
+                               typename Dataset::BatchRequestType> {
+ public:
+  using super = DataLoaderBase<
+      Dataset,
+      typename Dataset::BatchType::value_type,
+      typename Dataset::BatchRequestType>;
+  using typename super::BatchRequestType;
+
+  /// Constructs the `StatefulDataLoader` from a `dataset` and some `options`.
+  StatefulDataLoader(Dataset dataset, DataLoaderOptions options)
+      : super(options, std::make_unique(std::move(dataset))) {
+    for ([[maybe_unused]] const auto _ : c10::irange(this->options_.workers)) {
+      // As opposed to the stateless case, here all worker threads access the
+      // same underlying dataset.
+      this->workers_.emplace_back(
+          [this] { this->worker_thread(*this->main_thread_dataset_); });
+    }
+  }
+
+ private:
+  /// Resets the internal state of the dataloader and the dataset.
+  void reset() override {
+    this->main_thread_dataset_->reset();
+    // Call the base class method last because it calls `prefetch()`
+    super::reset();
+  }
+
+  /// For stateful datasets, the batch request is always the batch size. The
+  /// dataset is responsible for determining what goes into the batch next.
+  std::optional get_batch_request() override {
+    return this->options_.batch_size;
+  }
+};
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateless.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateless.h
new file mode 100644
index 0000000000000000000000000000000000000000..422b1097ee71b4a21217063609de8983d5883572
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateless.h
@@ -0,0 +1,82 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace data {
+
+/// A dataloader for stateless datasets.
+///
+/// This dataloader follows the traditional PyTorch dataloader design, whereby a
+/// (posssibly) stateful sampler produces *batch requests* for a stateless
+/// dataset, which acts as a simple batch request to batch mapping. The batch
+/// request will often be an array of indices, and if the dataset is a simple
+/// image dataset, the dataset would produce the images at those indices.
+template 
+class StatelessDataLoader : public DataLoaderBase<
+                                Dataset,
+                                typename Dataset::BatchType,
+                                typename Sampler::BatchRequestType> {
+ public:
+  using super = DataLoaderBase<
+      Dataset,
+      typename Dataset::BatchType,
+      typename Sampler::BatchRequestType>;
+  using typename super::BatchRequestType;
+
+  /// Constructs the `StatelessDataLoader` from a `dataset`, a `sampler` and
+  /// some `options`.
+  StatelessDataLoader(
+      Dataset dataset,
+      Sampler sampler,
+      DataLoaderOptions options)
+      : super(std::move(options)), sampler_(std::move(sampler)) {
+    for (const auto w : c10::irange(this->options_.workers)) {
+      // Here we copy the dataset into the worker thread closure. Each worker
+      // has its own copy of the dataset. This means the dataset must be
+      // trivially copiable, or else we don't expect more than one worker to
+      // be in use.
+      (void)w; // Suppress unused variable warning
+      this->workers_.emplace_back(
+          [this, dataset]() mutable { this->worker_thread(dataset); });
+    }
+    if (this->options_.workers == 0) {
+      this->main_thread_dataset_ =
+          std::make_unique(std::move(dataset));
+    }
+  }
+
+ private:
+  /// Resets the internal state of the dataloader and the sampler.
+  void reset() override {
+    sampler_.reset();
+    // Call the base class method last because it calls `prefetch()`
+    super::reset();
+  }
+
+  /// Queries the sampler for the next batch request (possibly progressing its
+  /// internal state).
+  std::optional get_batch_request() override {
+    auto indices = sampler_.next(this->options_.batch_size);
+    if (!indices ||
+        (indices->size() < this->options_.batch_size &&
+         this->options_.drop_last)) {
+      return nullopt;
+    }
+    AT_ASSERT(indices->size() > 0);
+    return indices;
+  }
+
+  /// The `Sampler` used to produce batch requests.
+  Sampler sampler_;
+};
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h
new file mode 100644
index 0000000000000000000000000000000000000000..a0c96aee0771370b1233c363e38e2777061eb115
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h
@@ -0,0 +1,65 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace data {
+
+/// Options to configure a `DataLoader`.
+struct DataLoaderOptions {
+  DataLoaderOptions() = default;
+  /* implicit */ DataLoaderOptions(size_t batch_size)
+      : batch_size_(batch_size) {}
+
+  /// The size of each batch to fetch.
+  TORCH_ARG(size_t, batch_size) = 1;
+
+  /// The number of worker threads to launch. If zero, the main thread will
+  /// synchronously perform the data loading.
+  TORCH_ARG(size_t, workers) = 0;
+
+  /// The maximum number of jobs to enqueue for fetching by worker threads.
+  /// Defaults to two times the number of worker threads.
+  TORCH_ARG(std::optional, max_jobs);
+
+  /// An optional limit on the time to wait for the next batch.
+  TORCH_ARG(std::optional, timeout);
+
+  /// Whether to enforce ordering of batches when multiple are loaded
+  /// asynchronously by worker threads. Set to `false` for better performance if
+  /// you do not care about determinism.
+  TORCH_ARG(bool, enforce_ordering) = true;
+
+  /// Whether to omit the last batch if it contains less than `batch_size`
+  /// examples.
+  TORCH_ARG(bool, drop_last) = false;
+};
+
+/// Like `DataLoaderOptions`, but without any unconfigured state.
+/// `DataLoaderOptions` has some options that depend on other options
+/// (`max_jobs` => `2 * workers`). In the spirit of properly using the C++ type
+/// system, `DataLoaderOptions` allows only setting values. To access values,
+/// you must create a `FullDataLoaderOptions` from a `DataLoaderOptions`
+/// instance, which will do any necessary coalescing.
+struct FullDataLoaderOptions {
+  explicit FullDataLoaderOptions(DataLoaderOptions options)
+      : batch_size(options.batch_size()),
+        workers(options.workers()),
+        max_jobs(options.max_jobs().value_or(2 * workers)),
+        timeout(options.timeout()),
+        enforce_ordering(options.enforce_ordering()),
+        drop_last(options.drop_last()) {}
+
+  size_t batch_size;
+  size_t workers;
+  size_t max_jobs;
+  std::optional timeout;
+  bool enforce_ordering;
+  bool drop_last;
+};
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets.h
new file mode 100644
index 0000000000000000000000000000000000000000..df565e97235828e5c89c76f0373bc1cdaee01287
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets.h
@@ -0,0 +1,9 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/base.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/base.h
new file mode 100644
index 0000000000000000000000000000000000000000..f17b3fe8af47549dbe1921b753a50bda529a8ebb
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/base.h
@@ -0,0 +1,104 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace data {
+namespace datasets {
+template 
+class MapDataset;
+template 
+MapDataset map(D, T); // NOLINT
+} // namespace datasets
+} // namespace data
+} // namespace torch
+
+namespace torch {
+namespace data {
+namespace datasets {
+namespace detail {
+template 
+struct is_optional : std::false_type {};
+template 
+struct is_optional> : std::true_type {};
+} // namespace detail
+
+/// A dataset that can yield data only in batches.
+template <
+    typename Self,
+    typename Batch = std::vector>,
+    typename BatchRequest = ArrayRef>
+class BatchDataset {
+ public:
+  using SelfType = Self;
+  using BatchType = Batch;
+  using BatchRequestType = BatchRequest;
+  constexpr static bool is_stateful = detail::is_optional::value;
+
+  virtual ~BatchDataset() = default;
+
+  /// Returns a batch of data given an index.
+  virtual Batch get_batch(BatchRequest request) = 0;
+
+  /// Returns the size of the dataset, or an empty std::optional if it is
+  /// unsized.
+  virtual std::optional size() const = 0;
+
+  /// Creates a `MapDataset` that applies the given `transform` to this dataset.
+  template 
+  MapDataset map(TransformType transform) & {
+    return datasets::map(static_cast(*this), std::move(transform));
+  }
+
+  /// Creates a `MapDataset` that applies the given `transform` to this dataset.
+  template 
+  MapDataset map(TransformType transform) && {
+    return datasets::map(
+        std::move(static_cast(*this)), std::move(transform));
+  }
+};
+
+/// A dataset that can yield data in batches, or as individual examples.
+///
+/// A `Dataset` is a `BatchDataset`, because it supports random access and
+/// therefore batched access is implemented (by default) by calling the random
+/// access indexing function for each index in the requested batch of indices.
+/// This can be customized.
+template >
+class Dataset : public BatchDataset> {
+ public:
+  using ExampleType = SingleExample;
+
+  /// Returns the example at the given index.
+  virtual ExampleType get(size_t index) = 0;
+
+  /// Returns a batch of data.
+  /// The default implementation calls `get()` for every requested index
+  /// in the batch.
+  std::vector get_batch(ArrayRef indices) override {
+    std::vector batch;
+    batch.reserve(indices.size());
+    for (const auto i : indices) {
+      batch.push_back(get(i));
+    }
+    return batch;
+  }
+};
+
+/// A `StreamDataset` represents a dataset that is a potentially infinite
+/// stream. It takes as batch index only a number, which is the batch size, and
+/// yields that many elements from the stream.
+template >>
+using StreamDataset = BatchDataset;
+} // namespace datasets
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/chunk.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/chunk.h
new file mode 100644
index 0000000000000000000000000000000000000000..01d940aa3e4885e9c78d527dc56d950b2ecad23a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/chunk.h
@@ -0,0 +1,529 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+namespace torch {
+namespace data {
+namespace datasets {
+
+/// Interface for chunk reader, which performs data chunking and reading of
+/// entire chunks.
+///
+/// A chunk could be an entire file, such as an audio data file or an image,
+/// or part of a file in the case of a large text-file split based on seek
+/// positions.
+template <
+    typename ExampleType_,
+    typename ChunkType_ = std::vector>
+class ChunkDataReader {
+ public:
+  virtual ~ChunkDataReader() = default;
+
+  using ChunkType = ChunkType_;
+  using ExampleType = ExampleType_;
+
+  /// Read an entire chunk.
+  virtual ChunkType read_chunk(size_t chunk_index) = 0;
+
+  /// Returns the number of chunks available in this reader.
+  virtual size_t chunk_count() = 0;
+
+  /// This will clear any internal state associate with this reader.
+  virtual void reset() = 0;
+};
+
+namespace detail {
+/// BatchDataBuffer manages a queue of UnwrappedBatchData. After a new chunk is
+/// loaded, BatchDataBuffer splits it into small batches and push them into the
+/// queue. When get_batch is called from data loader, it pops cached batches and
+/// return. If the cache is empty, it either waits to load more chunks or return
+/// null if all chunks are loaded.
+template <
+    typename UnwrappedBatch,
+    typename ExampleSampler = samplers::RandomSampler>
+class BatchDataBuffer {
+ public:
+  using UnwrappedBatchType = UnwrappedBatch;
+  using BatchType = torch::optional;
+  using BatchRequestType = typename ExampleSampler::BatchRequestType;
+
+  BatchDataBuffer(
+      size_t batch_size,
+      ExampleSampler& example_sampler,
+      size_t queue_capacity)
+      : batch_size_(batch_size),
+        example_sampler_(example_sampler),
+        queue_capacity_(queue_capacity) {}
+
+  /// Return batch data from the queue. Called from the ChunkDataset main
+  /// thread.
+  BatchType get_batch() {
+    std::unique_lock lock(queue_mutex_);
+    cv_read_.wait(lock, [this] {
+      // wait till there is available data in the queue or if all chunks are
+      // loaded (i.e. the dataset is exhausted for this epoch)
+      return (
+          this->total_example_count_in_queue_ >= batch_size_ || this->stop_);
+    });
+    if (batch_queue_.empty()) {
+      AT_ASSERT(stop_);
+      // All batches have been retrieved. Return an empty batch.
+      return nullopt;
+    }
+
+    UnwrappedBatchData batch = std::move(batch_queue_.front());
+    batch_queue_.pop();
+    if (batch.exception) {
+      throw WorkerException(batch.exception);
+    }
+
+    total_example_count_in_queue_ -= batch.batch_data.size();
+    lock.unlock();
+    cv_write_.notify_all();
+
+    return batch.batch_data;
+  }
+
+  /// Push preloaded chunks to batch queue. Called from the ChunkDataset worker
+  /// threads.
+  void add_chunk_data(UnwrappedBatchType data) {
+    std::unique_lock lock(queue_mutex_);
+    cv_write_.wait(lock, [this] {
+      // stop loading if we have preloaded enough data.
+      return this->total_example_count_in_queue_ < this->queue_capacity_ ||
+          this->stop_;
+    });
+    if (stop_) {
+      // When stop_ is true, it means no further chunk loading is necessary.
+      // Return without any further processing.
+      return;
+    }
+
+    auto data_size = data.size();
+    auto remaining_size = data_size;
+    example_sampler_.reset(data_size);
+
+    auto fill_batch = [&](size_t example_count, UnwrappedBatchType& batch) {
+      auto batch_example_indices = this->example_sampler_.next(example_count);
+      AT_ASSERT(
+          batch_example_indices &&
+          batch_example_indices.value().size() == example_count);
+      BatchRequestType& indices = batch_example_indices.value();
+      for (size_t i : indices) {
+        TORCH_CHECK(i < data_size, "Index out of range");
+        batch.emplace_back(std::move(data[i]));
+      }
+      remaining_size -= example_count;
+    };
+
+    if (!batch_queue_.empty()) {
+      // if the queue has existing data, and the last batch doesn't have enough
+      // examples to fill a batch_size batch, add more example to this batch
+      // first.
+      auto& batch = batch_queue_.back();
+      size_t current_count = batch.batch_data.size();
+      if (current_count < batch_size_) {
+        auto example_count =
+            std::min(remaining_size, batch_size_ - current_count);
+        fill_batch(example_count, batch.batch_data);
+      }
+    }
+
+    // If we still have data remaining after filling the last pushed batch, add
+    // them to the queue too.
+    // NOLINTNEXTLINE(bugprone-infinite-loop)
+    while (remaining_size > 0) {
+      UnwrappedBatchType current_batch;
+
+      // Allocate the batch memory ahead of time.
+      current_batch.reserve(batch_size_);
+
+      auto example_count = std::min(remaining_size, batch_size_);
+      fill_batch(example_count, current_batch);
+      batch_queue_.emplace(std::move(current_batch));
+    }
+    total_example_count_in_queue_ += data_size;
+    lock.unlock();
+    cv_read_.notify_all();
+  }
+
+  /// Push exceptions thrown during preloading into batch queue. Called from
+  /// the ChunkDataset worker threads.
+  void add_chunk_data(std::exception_ptr e_ptr) {
+    std::unique_lock lock(queue_mutex_);
+    cv_write_.wait(lock, [this] {
+      // stop loading if we have preloaded enough data.
+      return (
+          this->total_example_count_in_queue_ < this->queue_capacity_ ||
+          this->stop_);
+    });
+    if (stop_) {
+      // When stop_ is true, it means this current thread needs to be tore down,
+      // the batch buffer will be discarded, so no need to enqueue any new
+      // exceptions.
+      return;
+    }
+
+    batch_queue_.emplace(e_ptr);
+    lock.unlock();
+    cv_read_.notify_all();
+  }
+
+  void stop() {
+    {
+      // Hold the lock before changing stop_ to prevent a race condition which
+      // can cause a deadlock. To be more specific, conditional variable
+      // cv_write_ waits on predicate stop_ in add_chunk_data(). The wait
+      // happens in two steps: 1) while still holding the lock, check if
+      // predicate is true; 2) if it is true, proceeds, otherwise, release the
+      // lock and wait until notified. Without holding a lock, cv_write_'s
+      // notification can happen in between step 1) and 2). In that case, as
+      // cv_write_ is not in waiting status yet, so the notification is lost and
+      // cv_write_ will sleep forever. By taking a lock before changing
+      // predicate stop_, it is ensured updating and evaluating stop_ always
+      // happen in a synchronized way
+      std::lock_guard lock(queue_mutex_);
+      stop_ = true;
+    }
+
+    // notify all writers, wake them from wait to exit current method.
+    cv_write_.notify_all();
+    // notify all readers too.
+    cv_read_.notify_all();
+  }
+  /// The batch size is needed to create batches from the chunk data. Similar to
+  /// regular dataloader where the batches are created with prefetches,
+  /// BatchDataBuffer perform the batch creation using the provided batch size.
+  size_t batch_size_ = 0;
+
+  /// count of total example stored in the queue
+  size_t total_example_count_in_queue_ = 0;
+
+  /// struct that contains a raw unwrapped batch unit. An unwrapped batch unit
+  /// is the raw data without 'optional' wrapper. It can be a collection of
+  /// images, utterances, e.t.c.
+  struct UnwrappedBatchData {
+    explicit UnwrappedBatchData(UnwrappedBatchType data)
+        : batch_data(std::move(data)) {}
+
+    // NOLINTNEXTLINE(modernize-pass-by-value)
+    explicit UnwrappedBatchData(std::exception_ptr e) : exception(e) {}
+
+    /// batch data to return
+    UnwrappedBatchType batch_data;
+
+    /// exception pointer which captures any abnormal exceptions while creating
+    /// the batch.
+    std::exception_ptr exception;
+  };
+
+  /// local cache to store example batches from loaded chunk
+  std::queue batch_queue_;
+
+  // sync batch_queue_ update.
+  std::mutex queue_mutex_;
+
+  std::condition_variable cv_read_;
+  std::condition_variable cv_write_;
+
+  ExampleSampler& example_sampler_;
+
+  // configurable maximun number of elements the queue can hold at one time.
+  size_t queue_capacity_;
+
+  // When set to true, it wakes the writer threads from the wait and exit
+  // current function call. This is needed when ChunkDataSet.Reset is called
+  // while the previous epoch is not exhausted yet. When ChunkDataset is waiting
+  // its preloader to finish previous work before tearing down the thread, the
+  // preloader could be still waiting for the conditional variable, thus cause
+  // the program to hang. This boolean is used to break this waiting condition.
+  bool stop_ = false;
+};
+} // namespace detail
+
+/// Options to configure a `ChunkDataset`.
+struct ChunkDatasetOptions {
+  ChunkDatasetOptions() = delete;
+  ChunkDatasetOptions(
+      size_t preloader_count,
+      size_t batch_size,
+      size_t cache_size = 2048,
+      size_t cross_chunk_shuffle_count = 1)
+      : preloader_count_(preloader_count),
+        batch_size_(batch_size),
+        cache_size_(cache_size),
+        cross_chunk_shuffle_count_(cross_chunk_shuffle_count) {
+    TORCH_CHECK(
+        preloader_count_ > 0,
+        "Preloader count is 0. At least one preloader needs to be specified.");
+    TORCH_CHECK(
+        batch_size_ > 0,
+        "Batch size is 0. A positive batch size needs to be specified.");
+    TORCH_CHECK(
+        cache_size_ > 0,
+        "Cache size is 0. A positive cache size needs to be specified.");
+    TORCH_CHECK(
+        cache_size_ >= batch_size_,
+        "Cache size is less than batch size. Cache needs to be large enough to "
+        "hold at least one batch.");
+    TORCH_CHECK(
+        cross_chunk_shuffle_count_ > 0,
+        "cross_chunk_shuffle_count needs to be greater than 0.");
+  }
+
+  /// The number of worker thread to preload chunk data.
+  TORCH_ARG(size_t, preloader_count);
+
+  /// The size of each batch.
+  TORCH_ARG(size_t, batch_size);
+
+  /// The capacity of the queue for batch caching.
+  TORCH_ARG(size_t, cache_size) = 2048;
+
+  // The number of chunks to perfrom cross-chunk shuffling. Default to 1 meaning
+  // no cross-chunk shuffling. When it is equal to n (n > 1), n random
+  // chunks will be loaded at once and example shuffling will be performed
+  // across all those n chunks.
+  // Note: Usually the default config (1 chunk shuffle + example shuffle) is
+  // good enough to generate random distributed data. Use this parameter only if
+  // you know cross-shuffle is needed in your case. Also there is a performance
+  // penalty when this value is greater than 1, as we need to do extra merge
+  // between multiple chunks before performing example sampling.
+  TORCH_ARG(size_t, cross_chunk_shuffle_count) = 1;
+};
+
+/// A stateful dataset that support hierarchical sampling and prefetching of
+/// entre chunks.
+///
+/// Unlike regular dataset, chunk dataset require two samplers to operate and
+/// keeps an internal state. `ChunkSampler` selects, which chunk to load next,
+/// while the `ExampleSampler` determins the order of Examples that are returned
+/// in each `get_batch` call. The hierarchical sampling approach used here is
+/// inspired by this paper http://martin.zinkevich.org/publications/nips2010.pdf
+template <
+    typename ChunkReader,
+    typename ChunkSampler = samplers::RandomSampler,
+    typename ExampleSampler = samplers::RandomSampler>
+class ChunkDataset final
+    : public StatefulDataset<
+          ChunkDataset,
+          typename ChunkReader::BatchType,
+          size_t> {
+ public:
+  using BatchType = torch::optional;
+  using UnwrappedBatchType = typename ChunkReader::BatchType;
+  using BatchRequestType = size_t;
+  using ChunkSamplerType = ChunkSampler;
+  using ExampleSamplerType = ExampleSampler;
+
+  ChunkDataset(
+      ChunkReader chunk_reader,
+      ChunkSampler chunk_sampler,
+      ExampleSampler example_sampler,
+      ChunkDatasetOptions options,
+      std::function preprocessing_policy =
+          std::function())
+      : chunk_reader_(std::move(chunk_reader)),
+        chunk_sampler_(std::move(chunk_sampler)),
+        example_sampler_(std::move(example_sampler)),
+        options_(std::move(options)),
+        preprocessing_policy_(std::move(preprocessing_policy)),
+        quit_worker_(false),
+        running_preloaders_(0),
+        load_checkpoint_(false) {}
+
+  ~ChunkDataset() override {
+    // stop batch buffer first.
+    if (batch_buffer_) {
+      batch_buffer_->stop();
+    }
+    free_workers();
+  }
+
+  /// Default get_batch method of BatchDataset. This method returns
+  /// Example batches created from the preloaded chunks. The implemenation
+  /// is dataset agnostic and does not need overriding in different chunk
+  /// datasets.
+  BatchType get_batch(size_t batch_size) override {
+    TORCH_CHECK(
+        batch_buffer_ != nullptr,
+        "Dataset needs to call reset() before calling get_batch().");
+
+    TORCH_CHECK(
+        batch_size == options_.batch_size(),
+        "The requested batch size does not match with the initialized batch size.\n"
+        " The requested batch size is ",
+        batch_size,
+        ", while the dataset is created with batch size equal to ",
+        options_.batch_size());
+    return batch_buffer_->get_batch();
+  }
+
+  /// Helper method around get_batch as `batch_size` is not strictly necessary
+  BatchType get_batch() {
+    return get_batch(options_.batch_size());
+  }
+
+  /// This will clear any internal state and starts the internal prefetching
+  /// mechanism for the chunk dataset.
+  void reset() override {
+    // We need this to support partial data reads via dataloader iterator.
+    if (batch_buffer_) {
+      batch_buffer_->stop();
+    }
+    // free workers from previous reset if there is any.
+    free_workers();
+    preload_threads_.clear();
+
+    if (!load_checkpoint_) {
+      chunk_reader_.reset();
+      chunk_sampler_.reset(chunk_reader_.chunk_count());
+      load_checkpoint_ = false;
+    }
+
+    // Throw out any existing cached batch in the buffer and re-creates a new
+    // chunk buffer.
+    batch_buffer_ = std::make_unique<
+        detail::BatchDataBuffer>(
+        options_.batch_size(), example_sampler_, options_.cache_size());
+
+    // create new workers for this new epoch.
+    quit_worker_ = false;
+
+    AT_ASSERT(running_preloaders_ == 0);
+    running_preloaders_ = options_.preloader_count();
+    for (const auto i : c10::irange(options_.preloader_count())) {
+      preload_threads_.emplace_back([this, i]() { this->preloader(i); });
+    }
+  }
+
+  /// size is not used for chunk dataset.
+  std::optional size() const override {
+    return torch::nullopt;
+  }
+
+  // provide a references to chunk sampler. Used mainly in distributed data
+  // loading to set the epoch number for the sampler.
+  ChunkSamplerType& chunk_sampler() {
+    return chunk_sampler_;
+  }
+
+  void save(serialize::OutputArchive& archive) const override {
+    std::lock_guard lock(chunk_index_guard_);
+    chunk_sampler_.save(archive);
+  }
+
+  void load(serialize::InputArchive& archive) override {
+    std::lock_guard lock(chunk_index_guard_);
+    chunk_sampler_.load(archive);
+    load_checkpoint_ = true;
+  }
+
+ private:
+  /// running on worker thread to preload chunk data.
+  void preloader(size_t id) {
+    while (!quit_worker_.load()) {
+      try {
+        std::vector chunk_idx;
+        {
+          std::lock_guard lock(chunk_index_guard_);
+          if (auto chunk_sampler_result = chunk_sampler_.next(
+                  this->options_.cross_chunk_shuffle_count())) {
+            chunk_idx = chunk_sampler_result.value();
+          } else {
+            break;
+          }
+        }
+        UnwrappedBatchType data = chunk_reader_.read_chunk(chunk_idx[0]);
+        for (const auto i : c10::irange(1, chunk_idx.size())) {
+          auto chunk_data = chunk_reader_.read_chunk(chunk_idx[i]);
+          std::move(
+              chunk_data.begin(), chunk_data.end(), std::back_inserter(data));
+        }
+        if (preprocessing_policy_) {
+          preprocessing_policy_(data);
+        }
+        if (!data.empty()) { // skip empty chunks.
+          batch_buffer_->add_chunk_data(std::move(data));
+        }
+      } catch (...) {
+        batch_buffer_->add_chunk_data(std::current_exception());
+      }
+    }
+    AT_ASSERT(running_preloaders_.load() > 0);
+    --running_preloaders_;
+    if (running_preloaders_.load() == 0) {
+      // all preloaders are completed, so we can notify the batch_buffer.
+      batch_buffer_->stop();
+    }
+  }
+
+  /// Block the current thread until the workers finish execution and exit.
+  void free_workers() {
+    if (!quit_worker_.load()) {
+      quit_worker_ = true;
+      for (auto& worker_thread : preload_threads_) {
+        worker_thread.join();
+      }
+    }
+  }
+
+ private:
+  // Templated class that defines what is a chunk and how to read chunk data.
+  // When a chunk is returned by chunk_reader_, ChunkDataset split it into
+  // batches and caches them in batch_buffer_.
+  ChunkReader chunk_reader_;
+
+  // chunk sampler to shuffle different chunks
+  ChunkSamplerType chunk_sampler_;
+
+  // example sampler to shuffle examples in a specific chunk
+  ExampleSamplerType example_sampler_;
+
+  // batch data buffer which holds chunk data from preloading thread.
+  std::shared_ptr<
+      detail::BatchDataBuffer>
+      batch_buffer_;
+
+  // worker thread pool
+  std::vector preload_threads_;
+
+  /// The options the Dataset was configured with.
+  const ChunkDatasetOptions options_;
+
+  // function pointer wrapper to apply custom processing over chunk data. This
+  // is considered an advanced parameter for developers who want to apply a
+  // pre-process to the chunk data before sampling into minibatch.
+  // Different than the collate function, this policy is applied on the chunk
+  // level, instead of minibatch level. When a chunk of data is loaded (multiple
+  // chunks if cross_chunk_shuffle_count_ is greater than 1), this policy is
+  // applied to the full loaded data. It is useful if developers want to
+  // perform pre-processing (like bucketing) to the chunk data before
+  // example sampler samples the data. By default it's an empty pointer and no
+  // action will be taken.
+  std::function preprocessing_policy_;
+
+  // indicate whether the worker thread can be teared down
+  std::atomic quit_worker_;
+
+  // keep track of running preloaders to notify batch buffer. A value 0
+  // indicates that the chunk loading is completed.
+  std::atomic running_preloaders_;
+
+  // mutex to synchronize chunk sampler next() call.
+  mutable std::mutex chunk_index_guard_;
+
+  // boolean value to indicate whether we need to load the checkpoint for
+  // chunk_sampler_.
+  bool load_checkpoint_;
+};
+} // namespace datasets
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/map.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/map.h
new file mode 100644
index 0000000000000000000000000000000000000000..ebd4374cca8f3fcb765b937f728b9245d5998bfd
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/map.h
@@ -0,0 +1,118 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace data {
+namespace datasets {
+namespace detail {
+template 
+using optional_if_t = typename std::conditional, T>::type;
+} // namespace detail
+
+/// A `MapDataset` is a dataset that applies a transform to a source dataset.
+template 
+class MapDataset : public BatchDataset<
+                       MapDataset,
+                       detail::optional_if_t<
+                           SourceDataset::is_stateful,
+                           typename AppliedTransform::OutputBatchType>,
+                       typename SourceDataset::BatchRequestType> {
+ public:
+  using DatasetType = SourceDataset;
+  using TransformType = AppliedTransform;
+  using BatchRequestType = typename SourceDataset::BatchRequestType;
+  using OutputBatchType = detail::optional_if_t<
+      SourceDataset::is_stateful,
+      typename AppliedTransform::OutputBatchType>;
+
+  MapDataset(DatasetType dataset, TransformType transform)
+      : dataset_(std::move(dataset)), transform_(std::move(transform)) {}
+
+  /// Gets a batch from the source dataset and applies the transform to it,
+  /// returning the result.
+  OutputBatchType get_batch(BatchRequestType indices) override {
+    return get_batch_impl(std::move(indices));
+  }
+
+  /// Returns the size of the source dataset.
+  // NOLINTNEXTLINE(bugprone-exception-escape)
+  std::optional size() const noexcept override {
+    return dataset_.size();
+  }
+
+  /// Calls `reset()` on the underlying dataset.
+  /// NOTE: Stateless datasets do not have a reset() method, so a call to this
+  /// method will only compile for stateful datasets (which have a reset()
+  /// method).
+  void reset() {
+    dataset_.reset();
+  }
+
+  /// Returns the underlying dataset.
+  const SourceDataset& dataset() noexcept {
+    return dataset_;
+  }
+
+  /// Returns the transform being applied.
+  const AppliedTransform& transform() noexcept {
+    return transform_;
+  }
+
+ private:
+  /// The implementation of `get_batch()` for the stateless case, which simply
+  /// applies the transform to the output of `get_batch()` from the dataset.
+  template <
+      typename D = SourceDataset,
+      typename = std::enable_if_t>
+  OutputBatchType get_batch_impl(BatchRequestType indices) {
+    return transform_.apply_batch(dataset_.get_batch(std::move(indices)));
+  }
+
+  /// The implementation of `get_batch()` for the stateful case. Here, we follow
+  /// the semantics of `Optional.map()` in many functional languages, which
+  /// applies a transformation to the optional's content when the optional
+  /// contains a value, and returns a new optional (of a different type)  if the
+  /// original optional returned by `get_batch()` was empty.
+  template 
+  std::enable_if_t get_batch_impl(
+      BatchRequestType indices) {
+    if (auto batch = dataset_.get_batch(std::move(indices))) {
+      return transform_.apply_batch(std::move(*batch));
+    }
+    return nullopt;
+  }
+
+  /// The underlying dataset being transformed.
+  SourceDataset dataset_;
+
+  // The transformation that is applied to batches received from the dataset.
+  AppliedTransform transform_;
+};
+
+/// Creates a `MapDataset` with the given dataset and transform.
+template 
+MapDataset map(
+    DatasetType dataset,
+    TransformType transform) {
+  static_assert(
+      std::is_same<
+          typename std::conditional<
+              DatasetType::is_stateful,
+              typename DatasetType::BatchType::value_type,
+              typename DatasetType::BatchType>::type,
+          typename TransformType::InputBatchType>::value,
+      "BatchType type of dataset does not match input type of transform");
+  return {std::move(dataset), std::move(transform)};
+}
+
+} // namespace datasets
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/mnist.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/mnist.h
new file mode 100644
index 0000000000000000000000000000000000000000..5d9e352f36d07f38f688ff1c9d63a3d7505d137d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/mnist.h
@@ -0,0 +1,48 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace data {
+namespace datasets {
+/// The MNIST dataset.
+class TORCH_API MNIST : public Dataset {
+ public:
+  /// The mode in which the dataset is loaded.
+  enum class Mode { kTrain, kTest };
+
+  /// Loads the MNIST dataset from the `root` path.
+  ///
+  /// The supplied `root` path should contain the *content* of the unzipped
+  /// MNIST dataset, available from http://yann.lecun.com/exdb/mnist.
+  explicit MNIST(const std::string& root, Mode mode = Mode::kTrain);
+
+  /// Returns the `Example` at the given `index`.
+  Example<> get(size_t index) override;
+
+  /// Returns the size of the dataset.
+  std::optional size() const override;
+
+  /// Returns true if this is the training subset of MNIST.
+  // NOLINTNEXTLINE(bugprone-exception-escape)
+  bool is_train() const noexcept;
+
+  /// Returns all images stacked into a single tensor.
+  const Tensor& images() const;
+
+  /// Returns all targets stacked into a single tensor.
+  const Tensor& targets() const;
+
+ private:
+  Tensor images_, targets_;
+};
+} // namespace datasets
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/shared.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/shared.h
new file mode 100644
index 0000000000000000000000000000000000000000..aff84b586c89cec8870fc996f73009b8271b52e4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/shared.h
@@ -0,0 +1,83 @@
+#pragma once
+
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace data {
+namespace datasets {
+
+/// A dataset that wraps another dataset in a shared pointer and implements the
+/// `BatchDataset` API, delegating all calls to the shared instance. This is
+/// useful when you want all worker threads in the dataloader to access the same
+/// dataset instance. The dataset must take care of synchronization and
+/// thread-safe access itself.
+///
+/// Use `torch::data::datasets::make_shared_dataset()` to create a new
+/// `SharedBatchDataset` like you would a `std::shared_ptr`.
+template 
+class SharedBatchDataset : public BatchDataset<
+                               SharedBatchDataset,
+                               typename UnderlyingDataset::BatchType,
+                               typename UnderlyingDataset::BatchRequestType> {
+ public:
+  using BatchType = typename UnderlyingDataset::BatchType;
+  using BatchRequestType = typename UnderlyingDataset::BatchRequestType;
+
+  /// Constructs a new `SharedBatchDataset` from a `shared_ptr` to the
+  /// `UnderlyingDataset`.
+  /* implicit */ SharedBatchDataset(
+      std::shared_ptr shared_dataset)
+      : dataset_(std::move(shared_dataset)) {}
+
+  /// Calls `get_batch` on the underlying dataset.
+  BatchType get_batch(BatchRequestType request) override {
+    return dataset_->get_batch(std::move(request));
+  }
+
+  /// Returns the `size` from the underlying dataset.
+  std::optional size() const override {
+    return dataset_->size();
+  }
+
+  /// Accesses the underlying dataset.
+  UnderlyingDataset& operator*() {
+    return *dataset_;
+  }
+
+  /// Accesses the underlying dataset.
+  const UnderlyingDataset& operator*() const {
+    return *dataset_;
+  }
+
+  /// Accesses the underlying dataset.
+  UnderlyingDataset* operator->() {
+    return dataset_.get();
+  }
+
+  /// Accesses the underlying dataset.
+  const UnderlyingDataset* operator->() const {
+    return dataset_.get();
+  }
+
+  /// Calls `reset()` on the underlying dataset.
+  void reset() {
+    dataset_->reset();
+  }
+
+ private:
+  std::shared_ptr dataset_;
+};
+
+/// Constructs a new `SharedBatchDataset` by creating a
+/// `shared_ptr`. All arguments are forwarded to
+/// `make_shared`.
+template 
+SharedBatchDataset make_shared_dataset(Args&&... args) {
+  return std::make_shared(std::forward(args)...);
+}
+} // namespace datasets
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/stateful.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/stateful.h
new file mode 100644
index 0000000000000000000000000000000000000000..fb2379c673340fb9b836d1a60088cfc44f3103c5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/stateful.h
@@ -0,0 +1,70 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace serialize {
+class OutputArchive;
+class InputArchive;
+} // namespace serialize
+} // namespace torch
+
+namespace torch {
+namespace data {
+namespace datasets {
+
+/// A stateful dataset is a dataset that maintains some internal state, which
+/// will be `reset()` at the beginning of each epoch. Subclasses can override
+/// the `reset()` method to configure this behavior. Further, the return type of
+/// a stateful dataset's `get_batch()` method is always an `optional`. When the
+/// stateful dataset wants to indicate to the dataloader that its epoch has
+/// ended, it should return an empty optional. The dataloader knows to modify
+/// its implementation based on whether the dataset is stateless or stateful.
+///
+/// Note that when subclassing a from `StatefulDataset`, the return
+/// type of `get_batch()`, which the subclass must override, will be
+/// `optional` (i.e. the type specified in the `StatefulDataset`
+/// specialization is automatically boxed into an `optional` for the dataset's
+/// `BatchType`).
+template <
+    typename Self,
+    typename Batch = std::vector>,
+    typename BatchRequest = size_t>
+class StatefulDataset
+    : public BatchDataset, BatchRequest> {
+ public:
+  /// Resets internal state of the dataset.
+  virtual void reset() = 0;
+
+  /// Saves the statefulDataset's state to OutputArchive.
+  virtual void save(serialize::OutputArchive& archive) const = 0;
+
+  /// Deserializes the statefulDataset's state from the `archive`.
+  virtual void load(serialize::InputArchive& archive) = 0;
+};
+
+/// Serializes a statefulDataset to `OutputArchive`.
+template 
+serialize::OutputArchive& operator<<(
+    serialize::OutputArchive& archive,
+    const StatefulDataset& statefulDataset) {
+  statefulDataset.save(archive);
+  return archive;
+}
+
+/// Deserializes a statefulDataset from an `InputArchive`.
+template 
+serialize::InputArchive& operator>>(
+    serialize::InputArchive& archive,
+    StatefulDataset& statefulDataset) {
+  statefulDataset.load(archive);
+  return archive;
+}
+
+} // namespace datasets
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/tensor.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/tensor.h
new file mode 100644
index 0000000000000000000000000000000000000000..4968e263009f3548a2f7ed41e47586f4290a093c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/tensor.h
@@ -0,0 +1,38 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace data {
+namespace datasets {
+
+/// A dataset of tensors.
+/// Stores a single tensor internally, which is then indexed inside `get()`.
+struct TensorDataset : public Dataset {
+  /// Creates a `TensorDataset` from a vector of tensors.
+  explicit TensorDataset(const std::vector& tensors)
+      : TensorDataset(torch::stack(tensors)) {}
+
+  explicit TensorDataset(torch::Tensor tensor) : tensor(std::move(tensor)) {}
+
+  /// Returns a single `TensorExample`.
+  TensorExample get(size_t index) override {
+    return tensor[index];
+  }
+
+  /// Returns the number of tensors in the dataset.
+  std::optional size() const override {
+    return tensor.size(0);
+  }
+
+  Tensor tensor;
+};
+
+} // namespace datasets
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/detail/data_shuttle.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/detail/data_shuttle.h
new file mode 100644
index 0000000000000000000000000000000000000000..9c3ef121160123ecc048cfb5bbd3eac933f565ae
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/detail/data_shuttle.h
@@ -0,0 +1,87 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace data {
+namespace detail {
+
+/// Encapsulates the full life cycle of DataLoader jobs.
+///
+/// When a new job is enqueued to the `DataShuttle`, a counter for in-flight
+/// jobs is bumped. This job is said to be "in-flight" until its result is
+/// popped. Worker threads dequeue jobs as soon as they are available. When a
+/// worker finishes a job, it enqueues the result. Only when the main thread
+/// dequeues a result is the count of in-flight jobs decremented. When the main
+/// thread attempts to dequeue a job but no jobs are in-flight, that means the
+/// epoch is complete and `pop_result` returns an empty optional.
+template 
+class DataShuttle {
+ public:
+  /// Pushes a new job. Called by the main thread.
+  void push_job(Job job) {
+    new_jobs_.push(std::move(job));
+    ++in_flight_jobs_;
+  }
+
+  /// Pushes the result of a job. Called by worker threads.
+  void push_result(Result result) {
+    results_.push(std::move(result));
+  }
+
+  /// Returns the next job, blocking until there is one available. Called by
+  /// worker threads.
+  Job pop_job() {
+    return new_jobs_.pop();
+  }
+
+  /// Returns the result of a job, or nullopt if all jobs were exhausted. Called
+  /// by the main thread.
+  std::optional pop_result(
+      std::optional timeout = std::nullopt) {
+    if (in_flight_jobs_ > 0) {
+      auto result = results_.pop(timeout);
+      --in_flight_jobs_;
+      return result;
+    }
+    return nullopt;
+  }
+
+  /// Discards any jobs that are not yet in flight, and waits for all in-flight
+  /// jobs to finish, discarding their result.
+  void drain() {
+    // Clear all inputs so that no further jobs are scheduled.
+    auto number_cleared = new_jobs_.clear();
+    in_flight_jobs_ -= number_cleared;
+    // Remove any outstanding results.
+    while (in_flight_jobs_ > 0) {
+      pop_result();
+    }
+  }
+
+  /// Returns the number of jobs that are still in progress.
+  /// When this number is zero, an epoch is finished.
+  size_t in_flight_jobs() const noexcept {
+    return in_flight_jobs_;
+  }
+
+ private:
+  /// The queue for jobs that are not yet in flight.
+  Queue new_jobs_;
+  /// The number of in-flight jobs.
+  /// NOTE: Not atomic because only manipulated by the main thread.
+  size_t in_flight_jobs_ = 0;
+  /// The queue for results of finished jobs.
+  Queue results_;
+};
+
+} // namespace detail
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/detail/queue.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/detail/queue.h
new file mode 100644
index 0000000000000000000000000000000000000000..60236ab3f520c3499de30eb20d8962a50f5c0eef
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/detail/queue.h
@@ -0,0 +1,84 @@
+#pragma once
+
+#include 
+
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace data {
+namespace detail {
+
+/// A basic locked, blocking MPMC queue.
+///
+/// Every `push` and `pop` is guarded by a mutex. A condition variable is used
+/// to communicate insertion of new elements, such that waiting threads will be
+/// woken up if they are currently waiting inside a call to `pop()`.
+///
+/// Note that this data structure is written specifically for use with the
+/// `DataLoader`. Its behavior is tailored to this use case and may not be
+/// applicable to more general uses.
+template 
+class Queue {
+ public:
+  /// Pushes a new value to the back of the `Queue` and notifies one thread on
+  /// the waiting side about this event.
+  void push(T value) {
+    {
+      std::lock_guard lock(mutex_);
+      queue_.push(std::move(value));
+    }
+    cv_.notify_one();
+  }
+
+  /// Blocks until at least one element is ready to be popped from the front of
+  /// the queue. An optional `timeout` in seconds can be used to limit the time
+  /// spent waiting for an element. If the wait times out, an exception is
+  /// raised.
+  T pop(std::optional timeout = std::nullopt) {
+    std::unique_lock lock(mutex_);
+    if (timeout) {
+      if (!cv_.wait_for(
+              lock, *timeout, [this] { return !this->queue_.empty(); })) {
+        // clang-format off
+        AT_ERROR(
+            "Timeout in DataLoader queue while waiting for next batch"
+            " (timeout was ", timeout->count(), " ms)");
+        // clang-format on
+      }
+    } else {
+      cv_.wait(lock, [this] { return !this->queue_.empty(); });
+    }
+    AT_ASSERT(!queue_.empty());
+    T value = queue_.front();
+    queue_.pop();
+    lock.unlock();
+    return value;
+  }
+
+  /// Empties the queue and returns the number of elements that were present at
+  /// the start of the function. No threads are notified about this event as it
+  /// is assumed to be used to drain the queue during shutdown of a
+  /// `DataLoader`.
+  size_t clear() {
+    std::lock_guard lock(this->mutex_);
+    const auto size = queue_.size();
+    while (!queue_.empty()) {
+      queue_.pop();
+    }
+    return size;
+  }
+
+ private:
+  std::queue queue_;
+  std::mutex mutex_;
+  std::condition_variable cv_;
+};
+} // namespace detail
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/detail/sequencers.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/detail/sequencers.h
new file mode 100644
index 0000000000000000000000000000000000000000..c59f4cd7e290df9835bb6f08ecb6e3f638c98ef4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/detail/sequencers.h
@@ -0,0 +1,113 @@
+#pragma once
+
+#include 
+
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace data {
+namespace detail {
+namespace sequencers {
+namespace detail {
+template 
+bool buffer_contains_result(const std::vector>& buffer) {
+  return std::any_of(
+      buffer.begin(), buffer.end(), [](const std::optional& result) {
+        return result.has_value();
+      });
+}
+} // namespace detail
+
+/// A `Sequencer` accepts a function that yields the next result of a
+/// `DataLoader` and then has the opportunity to influence the order in which
+/// these results are returned. The `NoSequencer` does not enforce any
+/// sequencing and returns any result directly. The `OrderedSequencer` instead
+/// buffers results internally to return them in order of their sequence number.
+template 
+struct Sequencer {
+  using ResultProducer = std::function()>;
+  virtual ~Sequencer() = default;
+  virtual std::optional next(ResultProducer next_result) = 0;
+};
+
+/// A `Sequencer` that does not enforce any ordering. It is effectively the
+/// identity function.
+template 
+struct NoSequencer final : public Sequencer {
+  using typename Sequencer::ResultProducer;
+  std::optional next(ResultProducer next_result) override {
+    return next_result();
+  }
+};
+
+/// A `Sequencer` that buffers results and returns them in order of their
+/// sequence number. The `OrderedSequencer` maintains an internal, monotonically
+/// incrementing counter for the next sequence number it expects. If it receives
+/// a result with a higher sequence number, it will buffer it for later (when
+/// the sequence number reaches that of this result). Otherwise, if the sequence
+/// numbers match, the result is returned.
+///
+/// Implementation note: The `OrderedSequencer` is implemented with a fixed-size
+/// buffer. Let `m` be the maximum number of jobs in the data loader's queue and
+/// `s` be the current sequence number. Assume `m` jobs are scheduled in the
+/// `DataLoader`. Any new result is stored at index `job.sqn mod m` in the
+/// `OrderedSequencer`. Why are we sure sequence numbers of new jobs will not
+/// collide with sequence numbers of buffered jobs? The `OrderedSequencer` will
+/// not return from `next()` until it receives the result with sqn `s`. This
+/// means no new jobs can be scheduled in the `DataLoader` in the meantime,
+/// which enforces that as long as sqn `s` has not been received, `s + m` (which
+/// would cause a collision in the fixed-size buffer) will not yet be scheduled.
+template 
+struct OrderedSequencer : public Sequencer {
+  using typename Sequencer::ResultProducer;
+
+  /// Constructs the `OrderedSequencer` with the maximum number of results it
+  /// will ever hold at one point in time.
+  explicit OrderedSequencer(size_t max_jobs) : buffer_(max_jobs) {}
+
+  /// Buffers results until the next one in the expected order is received.
+  std::optional next(ResultProducer next_result) override {
+    // If we already have the result for the next sqn, return it.
+    if (auto& maybe_result = buffer(next_sequence_number_)) {
+      auto result = std::move(*maybe_result);
+      buffer(next_sequence_number_++).reset();
+      return result;
+    }
+    // Otherwise wait for the next result.
+    while (true) {
+      auto result = next_result();
+      if (!result) {
+        AT_ASSERT(!detail::buffer_contains_result(buffer_));
+        break;
+      }
+      // If it was not nullopt and the sequence numbers match, return it
+      // directly and bump the sequence number.
+      if (result->sequence_number == next_sequence_number_) {
+        ++next_sequence_number_;
+        return result;
+      }
+      // Stash the result for later.
+      AT_ASSERT(!buffer(result->sequence_number).has_value());
+      buffer(result->sequence_number) = std::move(result);
+    }
+    // The result was an empty optional, so we are done with this epoch.
+    return nullopt;
+  }
+
+  /// Accesses the buffer at the `index` modulo the buffer size.
+  std::optional& buffer(size_t index) {
+    return buffer_.at(index % buffer_.size());
+  }
+
+  /// The monotonically increasing sequence number we expect.
+  size_t next_sequence_number_ = 0;
+
+  /// A fixed-size buffer (after construction).
+  std::vector> buffer_;
+};
+} // namespace sequencers
+} // namespace detail
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/example.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/example.h
new file mode 100644
index 0000000000000000000000000000000000000000..57219a24cd0b08d65f8f5e46b80c0f8906a0ab03
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/example.h
@@ -0,0 +1,55 @@
+#pragma once
+
+#include 
+
+namespace torch {
+namespace data {
+
+/// An `Example` from a dataset.
+///
+/// A dataset consists of data and an associated target (label).
+template 
+struct Example {
+  using DataType = Data;
+  using TargetType = Target;
+
+  Example() = default;
+  Example(Data data, Target target)
+      : data(std::move(data)), target(std::move(target)) {}
+
+  Data data;
+  Target target;
+};
+
+namespace example {
+using NoTarget = void;
+} // namespace example
+
+/// A specialization for `Example` that does not have a target.
+///
+/// This class exists so that code can be written for a templated `Example`
+/// type, and work both for labeled and unlabeled datasets.
+template 
+struct Example {
+  using DataType = Data;
+  using TargetType = example::NoTarget;
+
+  Example() = default;
+  /* implicit */ Example(Data data) : data(std::move(data)) {}
+
+  // When a DataLoader returns an Example like this, that example should be
+  // implicitly convertible to the underlying data type.
+
+  operator Data&() {
+    return data;
+  }
+  operator const Data&() const {
+    return data;
+  }
+
+  Data data;
+};
+
+using TensorExample = Example;
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/iterator.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/iterator.h
new file mode 100644
index 0000000000000000000000000000000000000000..94293c452d53c44489fdfbbe6f0ee4d375aba9d8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/iterator.h
@@ -0,0 +1,178 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace data {
+namespace detail {
+// For increased safety and more separated logic, this implementation of
+// `Iterator` consists of a `ValidIterator` and a `SentinelIterator`. A
+// `ValidIterator` yields new batches until the `DataLoader` is exhausted. While
+// the `DataLoader` is not exhausted, `ValidIterator`s compare equal if they are
+// the same object. When the `ValidIterator` becomes exhausted, it compares
+// equal to the `SentinelIterator`, but not before. Half the code here is to
+// implement double dispatch for the comparison. Got damnit, C++.
+
+template 
+struct ValidIterator;
+
+template 
+struct SentinelIterator;
+
+/// Base class for the `ValidIterator` and `SentinelIterator`
+template 
+struct IteratorImpl {
+  virtual ~IteratorImpl() = default;
+  virtual void next() = 0;
+  virtual Batch& get() = 0;
+  virtual bool operator==(const IteratorImpl& other) const = 0;
+  virtual bool operator==(const ValidIterator& other) const = 0;
+  virtual bool operator==(const SentinelIterator& other) const = 0;
+};
+
+template 
+struct ValidIterator : public IteratorImpl {
+  using BatchProducer = std::function()>;
+
+  explicit ValidIterator(BatchProducer next_batch)
+      : next_batch_(std::move(next_batch)) {}
+
+  /// Fetches the next batch.
+  void next() override {
+    // If we didn't get the very first batch yet, get it now.
+    lazy_initialize();
+    TORCH_CHECK(
+        batch_.has_value(), "Attempted to increment iterator past the end");
+    // Increment to the next batch.
+    batch_ = next_batch_();
+  }
+
+  /// Returns the current batch. The precondition for this operation to not
+  /// throw an exception is that it has been compared to the `SentinelIterator`
+  /// and did not compare equal.
+  Batch& get() override {
+    // If we didn't get the very first batch yet, get it now.
+    lazy_initialize();
+    TORCH_CHECK(
+        batch_.has_value(),
+        "Attempted to dereference iterator that was past the end");
+    return batch_.value();
+  }
+
+  /// Does double dispatch.
+  bool operator==(const IteratorImpl& other) const override {
+    return other == *this;
+  }
+
+  /// A `ValidIterator` is equal to the `SentinelIterator` iff. the
+  /// `ValidIterator` has reached the end of the dataloader.
+  bool operator==(const SentinelIterator& /* unused */) const override {
+    lazy_initialize();
+    return !batch_;
+  }
+
+  /// Returns true if the memory address of `other` equals that of `this`.
+  bool operator==(const ValidIterator& other) const override {
+    return &other == this;
+  }
+
+  /// Gets the very first batch if it has not yet been fetched.
+  void lazy_initialize() const {
+    if (!initialized_) {
+      batch_ = next_batch_();
+      initialized_ = true;
+    }
+  }
+
+  BatchProducer next_batch_;
+  mutable std::optional batch_;
+  mutable bool initialized_ = false;
+};
+
+template 
+struct SentinelIterator : public IteratorImpl {
+  void next() override {
+    AT_ERROR(
+        "Incrementing the DataLoader's past-the-end iterator is not allowed");
+  }
+
+  Batch& get() override {
+    AT_ERROR(
+        "Dereferencing the DataLoader's past-the-end iterator is not allowed");
+  }
+
+  /// Does double dispatch.
+  bool operator==(const IteratorImpl& other) const override {
+    return other == *this;
+  }
+
+  /// Calls the comparison operator between `ValidIterator` and
+  /// `SentinelIterator`.
+  bool operator==(const ValidIterator& other) const override {
+    return other == *this;
+  }
+
+  /// Sentinel iterators always compare equal.
+  bool operator==(const SentinelIterator& other) const override {
+    return true;
+  }
+};
+} // namespace detail
+
+template 
+class Iterator {
+ public:
+  // Type aliases to make the class recognized as a proper iterator.
+  using difference_type = std::ptrdiff_t;
+  using value_type = Batch;
+  using pointer = Batch*;
+  using reference = Batch&;
+  using iterator_category = std::input_iterator_tag;
+
+  explicit Iterator(std::unique_ptr> impl)
+      : impl_(std::move(impl)) {}
+
+  /// Increments the iterator.
+  /// Only permitted for valid iterators (not past the end).
+  Iterator& operator++() {
+    impl_->next();
+    return *this;
+  }
+
+  /// Returns the current batch.
+  /// Only permitted for valid iterators (not past the end).
+  Batch& operator*() {
+    return impl_->get();
+  }
+
+  /// Returns a pointer to the current batch.
+  /// Only permitted for valid iterators (not past the end).
+  Batch* operator->() {
+    return &impl_->get();
+  }
+
+  /// Compares two iterators for equality.
+  bool operator==(const Iterator& other) const {
+    return *impl_ == *other.impl_;
+  }
+
+  /// Compares two iterators for inequality.
+  bool operator!=(const Iterator& other) const {
+    return !(*this == other);
+  }
+
+ private:
+  /// Points either to a `ValidIterator` or to a `SentinelIterator`.
+  std::shared_ptr> impl_;
+};
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/samplers.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/samplers.h
new file mode 100644
index 0000000000000000000000000000000000000000..928a2412aa76f8a22574b433a2f61152c45ae5c7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/samplers.h
@@ -0,0 +1,9 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/samplers/base.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/samplers/base.h
new file mode 100644
index 0000000000000000000000000000000000000000..8ab48d9d5931f5b86dbb0674043c6c8b658adba3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/samplers/base.h
@@ -0,0 +1,47 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace serialize {
+class OutputArchive;
+class InputArchive;
+} // namespace serialize
+} // namespace torch
+
+namespace torch {
+namespace data {
+namespace samplers {
+/// A `Sampler` is an object that yields an index with which to access a
+/// dataset.
+template >
+class Sampler {
+ public:
+  using BatchRequestType = BatchRequest;
+
+  virtual ~Sampler() = default;
+
+  /// Resets the `Sampler`'s internal state.
+  /// Typically called before a new epoch.
+  /// Optionally, accepts a new size when reseting the sampler.
+  virtual void reset(std::optional new_size) = 0;
+
+  /// Returns the next index if possible, or an empty optional if the
+  /// sampler is exhausted for this epoch.
+  virtual std::optional next(size_t batch_size) = 0;
+
+  /// Serializes the `Sampler` to the `archive`.
+  virtual void save(serialize::OutputArchive& archive) const = 0;
+
+  /// Deserializes the `Sampler` from the `archive`.
+  virtual void load(serialize::InputArchive& archive) = 0;
+};
+
+} // namespace samplers
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/samplers/custom_batch_request.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/samplers/custom_batch_request.h
new file mode 100644
index 0000000000000000000000000000000000000000..a5247b008d75021c3627d1a3bc922072c96f7812
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/samplers/custom_batch_request.h
@@ -0,0 +1,21 @@
+#pragma once
+
+#include 
+#include 
+
+namespace torch {
+namespace data {
+namespace samplers {
+/// A base class for custom index types.
+struct TORCH_API CustomBatchRequest {
+  CustomBatchRequest() = default;
+  CustomBatchRequest(const CustomBatchRequest&) = default;
+  CustomBatchRequest(CustomBatchRequest&&) noexcept = default;
+  virtual ~CustomBatchRequest() = default;
+
+  /// The number of elements accessed by this index.
+  virtual size_t size() const = 0;
+};
+} // namespace samplers
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/samplers/distributed.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/samplers/distributed.h
new file mode 100644
index 0000000000000000000000000000000000000000..bce36aaa4df719be2747fc3e8e5981c9aca20f16
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/samplers/distributed.h
@@ -0,0 +1,139 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace serialize {
+class OutputArchive;
+class InputArchive;
+} // namespace serialize
+} // namespace torch
+
+namespace torch {
+namespace data {
+namespace samplers {
+
+/// A `Sampler` that selects a subset of indices to sample from and defines a
+/// sampling behavior. In a distributed setting, this selects a subset of the
+/// indices depending on the provided num_replicas and rank parameters. The
+/// `Sampler` performs a rounding operation based on the `allow_duplicates`
+/// parameter to decide the local sample count.
+template >
+class DistributedSampler : public Sampler {
+ public:
+  DistributedSampler(
+      size_t size,
+      size_t num_replicas = 1,
+      size_t rank = 0,
+      bool allow_duplicates = true)
+      : size_(size),
+        num_replicas_(num_replicas),
+        rank_(rank),
+        epoch_(0),
+        allow_duplicates_(allow_duplicates) {}
+
+  /// Set the epoch for the current enumeration. This can be used to alter the
+  /// sample selection and shuffling behavior.
+  void set_epoch(size_t epoch) {
+    epoch_ = epoch;
+  }
+
+  size_t epoch() const {
+    return epoch_;
+  }
+
+ protected:
+  size_t local_sample_count() {
+    if (allow_duplicates_) {
+      return (size_ + num_replicas_ - 1) / num_replicas_;
+    } else {
+      return size_ / num_replicas_;
+    }
+  }
+
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  size_t size_;
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  size_t num_replicas_;
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  size_t rank_;
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  size_t epoch_;
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  bool allow_duplicates_;
+};
+
+/// Select samples randomly. The sampling order is shuffled at each `reset()`
+/// call.
+class TORCH_API DistributedRandomSampler : public DistributedSampler<> {
+ public:
+  DistributedRandomSampler(
+      size_t size,
+      size_t num_replicas = 1,
+      size_t rank = 0,
+      bool allow_duplicates = true);
+
+  /// Resets the `DistributedRandomSampler` to a new set of indices.
+  void reset(std::optional new_size = std::nullopt) override;
+
+  /// Returns the next batch of indices.
+  std::optional> next(size_t batch_size) override;
+
+  /// Serializes the `DistributedRandomSampler` to the `archive`.
+  void save(serialize::OutputArchive& archive) const override;
+
+  /// Deserializes the `DistributedRandomSampler` from the `archive`.
+  void load(serialize::InputArchive& archive) override;
+
+  /// Returns the current index of the `DistributedRandomSampler`.
+  size_t index() const noexcept;
+
+ private:
+  void populate_indices();
+
+  size_t begin_index_;
+  size_t end_index_;
+  size_t sample_index_;
+  std::vector all_indices_;
+};
+
+/// Select samples sequentially.
+class TORCH_API DistributedSequentialSampler : public DistributedSampler<> {
+ public:
+  DistributedSequentialSampler(
+      size_t size,
+      size_t num_replicas = 1,
+      size_t rank = 0,
+      bool allow_duplicates = true);
+
+  /// Resets the `DistributedSequentialSampler` to a new set of indices.
+  void reset(std::optional new_size = std::nullopt) override;
+
+  /// Returns the next batch of indices.
+  std::optional> next(size_t batch_size) override;
+
+  /// Serializes the `DistributedSequentialSampler` to the `archive`.
+  void save(serialize::OutputArchive& archive) const override;
+
+  /// Deserializes the `DistributedSequentialSampler` from the `archive`.
+  void load(serialize::InputArchive& archive) override;
+
+  /// Returns the current index of the `DistributedSequentialSampler`.
+  size_t index() const noexcept;
+
+ private:
+  void populate_indices();
+
+  size_t begin_index_;
+  size_t end_index_;
+  size_t sample_index_;
+  std::vector all_indices_;
+};
+
+} // namespace samplers
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/samplers/random.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/samplers/random.h
new file mode 100644
index 0000000000000000000000000000000000000000..4b023b6c703affedad7ccb3134456f437d97de1b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/samplers/random.h
@@ -0,0 +1,54 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace serialize {
+class OutputArchive;
+class InputArchive;
+} // namespace serialize
+} // namespace torch
+
+namespace torch {
+namespace data {
+namespace samplers {
+
+/// A `Sampler` that returns random indices.
+class TORCH_API RandomSampler : public Sampler<> {
+ public:
+  /// Constructs a `RandomSampler` with a size and dtype for the stored indices.
+  ///
+  /// The constructor will eagerly allocate all required indices, which is the
+  /// sequence `0 ... size - 1`. `index_dtype` is the data type of the stored
+  /// indices. You can change it to influence memory usage.
+  explicit RandomSampler(int64_t size, Dtype index_dtype = torch::kInt64);
+
+  ~RandomSampler() override;
+
+  /// Resets the `RandomSampler` to a new set of indices.
+  void reset(std::optional new_size = std::nullopt) override;
+
+  /// Returns the next batch of indices.
+  std::optional> next(size_t batch_size) override;
+
+  /// Serializes the `RandomSampler` to the `archive`.
+  void save(serialize::OutputArchive& archive) const override;
+
+  /// Deserializes the `RandomSampler` from the `archive`.
+  void load(serialize::InputArchive& archive) override;
+
+  /// Returns the current index of the `RandomSampler`.
+  size_t index() const noexcept;
+
+ private:
+  at::Tensor indices_;
+  int64_t index_ = 0;
+};
+} // namespace samplers
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/samplers/sequential.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/samplers/sequential.h
new file mode 100644
index 0000000000000000000000000000000000000000..252ecc3ad3d7503ad37df2fed9d41edcd0235936
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/samplers/sequential.h
@@ -0,0 +1,50 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace serialize {
+class OutputArchive;
+class InputArchive;
+} // namespace serialize
+} // namespace torch
+
+namespace torch {
+namespace data {
+namespace samplers {
+
+/// A `Sampler` that returns indices sequentially.
+class TORCH_API SequentialSampler : public Sampler<> {
+ public:
+  /// Creates a `SequentialSampler` that will return indices in the range
+  /// `0...size - 1`.
+  explicit SequentialSampler(size_t size);
+
+  /// Resets the `SequentialSampler` to zero.
+  void reset(std::optional new_size = std::nullopt) override;
+
+  /// Returns the next batch of indices.
+  std::optional> next(size_t batch_size) override;
+
+  /// Serializes the `SequentialSampler` to the `archive`.
+  void save(serialize::OutputArchive& archive) const override;
+
+  /// Deserializes the `SequentialSampler` from the `archive`.
+  void load(serialize::InputArchive& archive) override;
+
+  /// Returns the current index of the `SequentialSampler`.
+  size_t index() const noexcept;
+
+ private:
+  size_t size_;
+  size_t index_{0};
+};
+
+} // namespace samplers
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/samplers/serialize.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/samplers/serialize.h
new file mode 100644
index 0000000000000000000000000000000000000000..7585217a9cf260a67eb4d4fbda061a27a3fb23af
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/samplers/serialize.h
@@ -0,0 +1,28 @@
+#pragma once
+
+#include 
+#include 
+
+namespace torch {
+namespace data {
+namespace samplers {
+/// Serializes a `Sampler` into an `OutputArchive`.
+template 
+serialize::OutputArchive& operator<<(
+    serialize::OutputArchive& archive,
+    const Sampler& sampler) {
+  sampler.save(archive);
+  return archive;
+}
+
+/// Deserializes a `Sampler` from an `InputArchive`.
+template 
+serialize::InputArchive& operator>>(
+    serialize::InputArchive& archive,
+    Sampler& sampler) {
+  sampler.load(archive);
+  return archive;
+}
+} // namespace samplers
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/samplers/stream.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/samplers/stream.h
new file mode 100644
index 0000000000000000000000000000000000000000..201c914e49e5cf2d34e0f273cc71fb6d02e4068c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/samplers/stream.h
@@ -0,0 +1,63 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+namespace torch {
+namespace serialize {
+class InputArchive;
+class OutputArchive;
+} // namespace serialize
+} // namespace torch
+
+namespace torch {
+namespace data {
+namespace samplers {
+
+/// A wrapper around a batch size value, which implements the
+/// `CustomBatchRequest` interface.
+struct TORCH_API BatchSize : public CustomBatchRequest {
+  explicit BatchSize(size_t size);
+  size_t size() const noexcept override;
+  operator size_t() const noexcept;
+  size_t size_;
+};
+
+/// A sampler for (potentially infinite) streams of data.
+///
+/// The major feature of the `StreamSampler` is that it does not return
+/// particular indices, but instead only the number of elements to fetch from
+/// the dataset. The dataset has to decide how to produce those elements.
+class TORCH_API StreamSampler : public Sampler {
+ public:
+  /// Constructs the `StreamSampler` with the number of individual examples that
+  /// should be fetched until the sampler is exhausted.
+  explicit StreamSampler(size_t epoch_size);
+
+  /// Resets the internal state of the sampler.
+  void reset(std::optional new_size = std::nullopt) override;
+
+  /// Returns a `BatchSize` object with the number of elements to fetch in the
+  /// next batch. This number is the minimum of the supplied `batch_size` and
+  /// the difference between the `epoch_size` and the current index. If the
+  /// `epoch_size` has been reached, returns an empty optional.
+  std::optional next(size_t batch_size) override;
+
+  /// Serializes the `StreamSampler` to the `archive`.
+  void save(serialize::OutputArchive& archive) const override;
+
+  /// Deserializes the `StreamSampler` from the `archive`.
+  void load(serialize::InputArchive& archive) override;
+
+ private:
+  size_t examples_retrieved_so_far_ = 0;
+  size_t epoch_size_;
+};
+
+} // namespace samplers
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/transforms.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/transforms.h
new file mode 100644
index 0000000000000000000000000000000000000000..e5d92062e62d52dd2dac3ab39f76385f9bf1522f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/transforms.h
@@ -0,0 +1,7 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/transforms/base.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/transforms/base.h
new file mode 100644
index 0000000000000000000000000000000000000000..0bc1f2ea7b141a270a7b5f826442d96d9841e72c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/transforms/base.h
@@ -0,0 +1,53 @@
+#pragma once
+
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace data {
+namespace transforms {
+
+/// A transformation of a batch to a new batch.
+template 
+class BatchTransform {
+ public:
+  using InputBatchType = InputBatch;
+  using OutputBatchType = OutputBatch;
+
+  virtual ~BatchTransform() = default;
+
+  /// Applies the transformation to the given `input_batch`.
+  virtual OutputBatch apply_batch(InputBatch input_batch) = 0;
+};
+
+/// A transformation of individual input examples to individual output examples.
+///
+/// Just like a `Dataset` is a `BatchDataset`, a `Transform` is a
+/// `BatchTransform` that can operate on the level of individual examples rather
+/// than entire batches. The batch-level transform is implemented (by default)
+/// in terms of the example-level transform, though this can be customized.
+template 
+class Transform
+    : public BatchTransform, std::vector> {
+ public:
+  using InputType = Input;
+  using OutputType = Output;
+
+  /// Applies the transformation to the given `input`.
+  virtual OutputType apply(InputType input) = 0;
+
+  /// Applies the `transformation` over the entire `input_batch`.
+  std::vector apply_batch(std::vector input_batch) override {
+    std::vector output_batch;
+    output_batch.reserve(input_batch.size());
+    for (auto&& input : input_batch) {
+      output_batch.push_back(apply(std::move(input)));
+    }
+    return output_batch;
+  }
+};
+} // namespace transforms
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/transforms/collate.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/transforms/collate.h
new file mode 100644
index 0000000000000000000000000000000000000000..181bcae0031b6f7f0f77b5eebeb7f3de5436c691
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/transforms/collate.h
@@ -0,0 +1,35 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+
+namespace torch {
+namespace data {
+namespace transforms {
+
+/// A `Collation` is a transform that reduces a batch into a single value.
+/// The result is a `BatchDataset` that has the type of the single value as its
+/// `BatchType`.
+template >
+using Collation = BatchTransform;
+
+/// A `Collate` allows passing a custom function to reduce/collate a batch
+/// into a single value. It's effectively the lambda version of `Collation`,
+/// which you could subclass and override `operator()` to achieve the same.
+///
+/// \rst
+/// .. code-block:: cpp
+///   using namespace torch::data;
+///
+///   auto dataset = datasets::MNIST("path/to/mnist")
+///     .map(transforms::Collate>([](std::vector> e) {
+///       return std::move(e.front());
+///     }));
+/// \endrst
+template >
+using Collate = BatchLambda;
+} // namespace transforms
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/transforms/lambda.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/transforms/lambda.h
new file mode 100644
index 0000000000000000000000000000000000000000..252b29807a8efe5e16fa11b9f9337c9f8a4ffa98
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/transforms/lambda.h
@@ -0,0 +1,56 @@
+#pragma once
+
+#include 
+
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace data {
+namespace transforms {
+
+/// A `BatchTransform` that applies a user-provided functor to a batch.
+template 
+class BatchLambda : public BatchTransform {
+ public:
+  using typename BatchTransform::InputBatchType;
+  using typename BatchTransform::OutputBatchType;
+  using FunctionType = std::function;
+
+  /// Constructs the `BatchLambda` from the given `function` object.
+  explicit BatchLambda(FunctionType function)
+      : function_(std::move(function)) {}
+
+  /// Applies the user-provided function object to the `input_batch`.
+  OutputBatchType apply_batch(InputBatchType input_batch) override {
+    return function_(std::move(input_batch));
+  }
+
+ private:
+  FunctionType function_;
+};
+
+// A `Transform` that applies a user-provided functor to individual examples.
+template 
+class Lambda : public Transform {
+ public:
+  using typename Transform::InputType;
+  using typename Transform::OutputType;
+  using FunctionType = std::function;
+
+  /// Constructs the `Lambda` from the given `function` object.
+  explicit Lambda(FunctionType function) : function_(std::move(function)) {}
+
+  /// Applies the user-provided function object to the `input`.
+  OutputType apply(InputType input) override {
+    return function_(std::move(input));
+  }
+
+ private:
+  FunctionType function_;
+};
+
+} // namespace transforms
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/transforms/stack.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/transforms/stack.h
new file mode 100644
index 0000000000000000000000000000000000000000..4be1bd920b71596b7a91dcae28acc2713c7af782
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/transforms/stack.h
@@ -0,0 +1,49 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace data {
+namespace transforms {
+
+template >
+struct Stack;
+
+/// A `Collation` for `Example` types that stacks all data
+/// tensors into one tensor, and all target (label) tensors into one tensor.
+template <>
+struct Stack> : public Collation> {
+  Example<> apply_batch(std::vector> examples) override {
+    std::vector data, targets;
+    data.reserve(examples.size());
+    targets.reserve(examples.size());
+    for (auto& example : examples) {
+      data.push_back(std::move(example.data));
+      targets.push_back(std::move(example.target));
+    }
+    return {torch::stack(data), torch::stack(targets)};
+  }
+};
+
+/// A `Collation` for `Example` types that stacks all data
+/// tensors into one tensor.
+template <>
+struct Stack
+    : public Collation> {
+  TensorExample apply_batch(std::vector examples) override {
+    std::vector data;
+    data.reserve(examples.size());
+    for (auto& example : examples) {
+      data.push_back(std::move(example.data));
+    }
+    return torch::stack(data);
+  }
+};
+} // namespace transforms
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/transforms/tensor.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/transforms/tensor.h
new file mode 100644
index 0000000000000000000000000000000000000000..2e135c528131506b0249db41f9de56e7cfc84e03
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/transforms/tensor.h
@@ -0,0 +1,77 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace data {
+namespace transforms {
+
+/// A `Transform` that is specialized for the typical `Example`
+/// combination. It exposes a single `operator()` interface hook (for
+/// subclasses), and calls this function on input `Example` objects.
+template 
+class TensorTransform
+    : public Transform, Example> {
+ public:
+  using E = Example;
+  using typename Transform::InputType;
+  using typename Transform::OutputType;
+
+  /// Transforms a single input tensor to an output tensor.
+  virtual Tensor operator()(Tensor input) = 0;
+
+  /// Implementation of `Transform::apply` that calls `operator()`.
+  OutputType apply(InputType input) override {
+    input.data = (*this)(std::move(input.data));
+    return input;
+  }
+};
+
+/// A `Lambda` specialized for the typical `Example` input type.
+template 
+class TensorLambda : public TensorTransform {
+ public:
+  using FunctionType = std::function;
+
+  /// Creates a `TensorLambda` from the given `function`.
+  explicit TensorLambda(FunctionType function)
+      : function_(std::move(function)) {}
+
+  /// Applies the user-provided functor to the input tensor.
+  Tensor operator()(Tensor input) override {
+    return function_(std::move(input));
+  }
+
+ private:
+  FunctionType function_;
+};
+
+/// Normalizes input tensors by subtracting the supplied mean and dividing by
+/// the given standard deviation.
+template 
+struct Normalize : public TensorTransform {
+  /// Constructs a `Normalize` transform. The mean and standard deviation can be
+  /// anything that is broadcastable over the input tensors (like single
+  /// scalars).
+  Normalize(ArrayRef mean, ArrayRef stddev)
+      : mean(torch::tensor(mean, torch::kFloat32)
+                 .unsqueeze(/*dim=*/1)
+                 .unsqueeze(/*dim=*/2)),
+        stddev(torch::tensor(stddev, torch::kFloat32)
+                   .unsqueeze(/*dim=*/1)
+                   .unsqueeze(/*dim=*/2)) {}
+
+  torch::Tensor operator()(Tensor input) override {
+    return input.sub(mean).div(stddev);
+  }
+
+  torch::Tensor mean, stddev;
+};
+} // namespace transforms
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/worker_exception.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/worker_exception.h
new file mode 100644
index 0000000000000000000000000000000000000000..40680b8330c456669826e8957abcbd3ae15c130c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/data/worker_exception.h
@@ -0,0 +1,38 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace data {
+
+/// An exception thrown when a DataLoader's worker thread throws an exception,
+/// which is caught. A `WorkerException` stores an `exception_ptr` to the
+/// original exception thrown in the worker thread.
+struct WorkerException : public std::exception {
+  /// Constructs a `WorkerException` from an `exception_ptr`.
+  explicit WorkerException(std::exception_ptr original)
+      : original_exception(std::move(original)),
+        message("Caught exception in DataLoader worker thread.") {
+    try {
+      std::rethrow_exception(original_exception);
+    } catch (std::exception& e) {
+      message += " Original message: ";
+      message += e.what();
+    }
+  }
+
+  const char* what() const noexcept override {
+    return message.c_str();
+  }
+
+  /// The original exception thrown in the worker thread.
+  std::exception_ptr original_exception;
+
+  /// This exception's message (not the original exception's message).
+  std::string message;
+};
+
+} // namespace data
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/cloneable.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/cloneable.h
new file mode 100644
index 0000000000000000000000000000000000000000..68ddaeb0abad975165dece6aceedd47f8e99b1f3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/cloneable.h
@@ -0,0 +1,98 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+/// The `clone()` method in the base `Module` class does not have knowledge of
+/// the concrete runtime type of its subclasses. Therefore, `clone()` must
+/// either be called from within the subclass, or from a base class that has
+/// knowledge of the concrete type. `Cloneable` uses the CRTP to gain
+/// knowledge of the subclass' static type and provide an implementation of the
+/// `clone()` method. We do not want to use this pattern in the base class,
+/// because then storing a module would always require templatizing it.
+template 
+// NOLINTNEXTLINE(bugprone-exception-escape)
+class Cloneable : public Module {
+ public:
+  using Module::Module;
+
+  /// `reset()` must perform initialization of all members with reference
+  /// semantics, most importantly parameters, buffers and submodules.
+  virtual void reset() = 0;
+
+  /// Performs a recursive "deep copy" of the `Module`, such that all parameters
+  /// and submodules in the cloned module are different from those in the
+  /// original module.
+  std::shared_ptr clone(
+      const std::optional& device = std::nullopt) const override {
+    NoGradGuard no_grad;
+
+    const auto& self = static_cast(*this);
+    auto copy = std::make_shared(self);
+    copy->parameters_.clear();
+    copy->buffers_.clear();
+    copy->children_.clear();
+    copy->reset();
+    TORCH_CHECK(
+        copy->parameters_.size() == parameters_.size(),
+        "The cloned module does not have the same number of "
+        "parameters as the original module after calling reset(). "
+        "Are you sure you called register_parameter() inside reset() "
+        "and not the constructor?");
+    for (const auto& parameter : named_parameters(/*recurse=*/false)) {
+      auto& tensor = *parameter;
+      auto data = device && tensor.device() != *device
+          ? tensor.to(*device)
+          : autograd::Variable(tensor).clone();
+      copy->parameters_[parameter.key()].set_data(data);
+    }
+    TORCH_CHECK(
+        copy->buffers_.size() == buffers_.size(),
+        "The cloned module does not have the same number of "
+        "buffers as the original module after calling reset(). "
+        "Are you sure you called register_buffer() inside reset() "
+        "and not the constructor?");
+    for (const auto& buffer : named_buffers(/*recurse=*/false)) {
+      auto& tensor = *buffer;
+      auto data = device && tensor.device() != *device
+          ? tensor.to(*device)
+          : autograd::Variable(tensor).clone();
+      copy->buffers_[buffer.key()].set_data(data);
+    }
+    TORCH_CHECK(
+        copy->children_.size() == children_.size(),
+        "The cloned module does not have the same number of "
+        "child modules as the original module after calling reset(). "
+        "Are you sure you called register_module() inside reset() "
+        "and not the constructor?");
+    for (const auto& child : children_) {
+      copy->children_[child.key()]->clone_(*child.value(), device);
+    }
+    return copy;
+  }
+
+ private:
+  void clone_(Module& other, const std::optional& device) final {
+    // Here we are *pretty* certain that `other's` type is `Derived` (because it
+    // was registered under the same name as `this`), but you never know what
+    // crazy things `reset()` does, so `dynamic_cast` just to be safe.
+    auto clone = std::dynamic_pointer_cast(other.clone(device));
+    TORCH_CHECK(
+        clone != nullptr,
+        "Attempted to clone submodule, but it is of a "
+        "different type than the submodule it was to be cloned into");
+    static_cast(*this) = *clone;
+  }
+};
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional.h
new file mode 100644
index 0000000000000000000000000000000000000000..b148edc68173f4d11cf58e042902edf3c508afff
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional.h
@@ -0,0 +1,17 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/activation.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/activation.h
new file mode 100644
index 0000000000000000000000000000000000000000..5ae6fcc317602aab1fb9bbe19c42bf4ecd58e0b8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/activation.h
@@ -0,0 +1,966 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+namespace functional {
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor elu(Tensor input, double alpha, bool inplace) {
+  if (inplace) {
+    return torch::elu_(input, alpha);
+  } else {
+    return torch::elu(input, alpha);
+  }
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.elu
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::ELUFuncOptions` class to
+/// learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::elu(x, F::ELUFuncOptions().alpha(0.42).inplace(true));
+/// ```
+inline Tensor elu(Tensor input, const ELUFuncOptions& options = {}) {
+  return detail::elu(std::move(input), options.alpha(), options.inplace());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor selu(Tensor input, bool inplace) {
+  if (inplace) {
+    return torch::selu_(input);
+  } else {
+    return torch::selu(input);
+  }
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.selu
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::SELUFuncOptions` class to
+/// learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::selu(input, F::SELUFuncOptions(false));
+/// ```
+inline Tensor selu(Tensor input, const SELUFuncOptions& options = {}) {
+  return detail::selu(std::move(input), options.inplace());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor hardshrink(const Tensor& input, double lambda) {
+  return torch::hardshrink(input, lambda);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.hardshrink
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::HardshrinkFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::hardshrink(x, F::HardshrinkFuncOptions().lambda(0.42));
+/// ```
+inline Tensor hardshrink(
+    const Tensor& input,
+    const HardshrinkFuncOptions& options = {}) {
+  return detail::hardshrink(input, options.lambda());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor hardtanh(
+    Tensor input,
+    double min_val,
+    double max_val,
+    bool inplace) {
+  if (inplace) {
+    return torch::hardtanh_(input, min_val, max_val);
+  } else {
+    return torch::hardtanh(input, min_val, max_val);
+  }
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.hardtanh
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::HardtanhFuncOptions` class
+/// to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::hardtanh(x,
+/// F::HardtanhFuncOptions().min_val(-1.0).max_val(1.0).inplace(true));
+/// ```
+inline Tensor hardtanh(Tensor input, const HardtanhFuncOptions& options = {}) {
+  return detail::hardtanh(
+      std::move(input),
+      options.min_val(),
+      options.max_val(),
+      options.inplace());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor leaky_relu(Tensor input, double negative_slope, bool inplace) {
+  if (inplace) {
+    return torch::leaky_relu_(input, negative_slope);
+  } else {
+    return torch::leaky_relu(input, negative_slope);
+  }
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.leaky_relu
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::LeakyReLUFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::leaky_relu(x,
+/// F::LeakyReLUFuncOptions().negative_slope(0.42).inplace(true));
+/// ```
+inline Tensor leaky_relu(
+    Tensor input,
+    const LeakyReLUFuncOptions& options = {}) {
+  return detail::leaky_relu(
+      std::move(input), options.negative_slope(), options.inplace());
+}
+
+// ============================================================================
+
+inline Tensor logsigmoid(const Tensor& input) {
+  return torch::log_sigmoid(input);
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor gumbel_softmax(
+    const Tensor& logits,
+    double tau,
+    bool hard,
+    int dim) {
+  auto gumbels =
+      -torch::empty_like(logits).exponential_().log(); // ~Gumbel(0,1)
+  gumbels = (logits + gumbels) / tau; // ~Gumbel(logits, tau)
+  auto y_soft = gumbels.softmax(dim);
+
+  torch::Tensor ret;
+  if (hard) {
+    // Straight through.
+    auto index = std::get<1>(y_soft.max(dim, /*keepdim=*/true));
+    auto y_hard = torch::zeros_like(logits).scatter_(dim, index, 1.0);
+    ret = y_hard - y_soft.detach() + y_soft;
+  } else {
+    ret = y_soft;
+  }
+  return ret;
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.gumbel_softmax
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::GumbelSoftmaxFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::gumbel_softmax(logits, F::GumbelSoftmaxFuncOptions().hard(true).dim(-1));
+/// ```
+inline Tensor gumbel_softmax(
+    const Tensor& logits,
+    const GumbelSoftmaxFuncOptions& options = {}) {
+  return detail::gumbel_softmax(
+      logits, options.tau(), options.hard(), options.dim());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor softmax(
+    const Tensor& input,
+    int64_t dim,
+    std::optional dtype) {
+  Tensor ret;
+
+  if (dtype == std::nullopt) {
+    ret = input.softmax(dim);
+  } else {
+    ret = input.softmax(dim, dtype);
+  }
+
+  return ret;
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.softmax
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::SoftmaxFuncOptions` class
+/// to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::softmax(input, F::SoftmaxFuncOptions(1));
+/// ```
+inline Tensor softmax(const Tensor& input, const SoftmaxFuncOptions& options) {
+  return detail::softmax(input, options.dim(), options.dtype());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor softmin(
+    const Tensor& input,
+    int64_t dim,
+    std::optional dtype) {
+  Tensor ret;
+
+  if (dtype == std::nullopt) {
+    ret = (-input).softmax(dim);
+  } else {
+    ret = (-input).softmax(dim, dtype);
+  }
+
+  return ret;
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.softmin
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::SoftminFuncOptions` class
+/// to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::softmin(input, F::SoftminFuncOptions(1));
+/// ```
+inline Tensor softmin(const Tensor& input, const SoftminFuncOptions& options) {
+  return detail::softmin(input, options.dim(), options.dtype());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor log_softmax(
+    const Tensor& input,
+    int64_t dim,
+    std::optional dtype) {
+  Tensor ret;
+
+  if (dtype == std::nullopt) {
+    ret = input.log_softmax(dim);
+  } else {
+    ret = input.log_softmax(dim, dtype);
+  }
+
+  return ret;
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.log_softmax
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::LogSoftmaxFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::log_softmax(input, LogSoftmaxFuncOptions(1));
+/// ```
+inline Tensor log_softmax(
+    const Tensor& input,
+    const LogSoftmaxFuncOptions& options) {
+  return detail::log_softmax(input, options.dim(), options.dtype());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor glu(const Tensor& input, int64_t dim) {
+  TORCH_CHECK(
+      input.dim() != 0,
+      "glu does not suppport scalars because halving size must be even");
+  return torch::glu(input, dim);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.glu
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::GLUFuncOptions` class to
+/// learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::glu(input, GLUFuncOptions(1));
+/// ```
+inline Tensor glu(const Tensor& input, const GLUFuncOptions& options = {}) {
+  return detail::glu(input, options.dim());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor gelu(const Tensor& input, string approximate) {
+  return torch::gelu(input, approximate);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+inline Tensor gelu(const Tensor& input, const GELUFuncOptions& options = {}) {
+  return detail::gelu(input, options.approximate());
+}
+
+// ============================================================================
+
+inline Tensor silu(const Tensor& input) {
+  return torch::silu(input);
+}
+
+// ============================================================================
+
+inline Tensor mish(const Tensor& input) {
+  return torch::mish(input);
+}
+
+// ============================================================================
+
+inline Tensor prelu(const Tensor& input, const Tensor& weight) {
+  return torch::prelu(input, weight);
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor relu(Tensor input, bool inplace) {
+  if (inplace) {
+    return torch::relu_(input);
+  } else {
+    return torch::relu(input);
+  }
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.relu
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::ReLUFuncOptions` class to
+/// learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::relu(x, F::ReLUFuncOptions().inplace(true));
+/// ```
+inline Tensor relu(Tensor input, const ReLUFuncOptions& options = {}) {
+  return detail::relu(std::move(input), options.inplace());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor relu6(Tensor input, bool inplace) {
+  if (inplace) {
+    return torch::relu6_(input);
+  } else {
+    return torch::relu6(input);
+  }
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.relu6
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::ReLU6FuncOptions` class to
+/// learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::relu6(x, F::ReLU6FuncOptions().inplace(true));
+/// ```
+inline Tensor relu6(Tensor input, const ReLU6FuncOptions& options = {}) {
+  return detail::relu6(std::move(input), options.inplace());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor rrelu(
+    Tensor input,
+    double lower,
+    double upper,
+    bool training,
+    bool inplace) {
+  if (inplace) {
+    return torch::rrelu_(input, lower, upper, training);
+  } else {
+    return torch::rrelu(input, lower, upper, training);
+  }
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.rrelu
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::RReLUFuncOptions` class to
+/// learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::rrelu(x, F::RReLUFuncOptions().lower(0.1).upper(0.4).inplace(true));
+/// ```
+inline Tensor rrelu(Tensor input, const RReLUFuncOptions& options = {}) {
+  return detail::rrelu(
+      std::move(input),
+      options.lower(),
+      options.upper(),
+      options.training(),
+      options.inplace());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor celu(Tensor input, double alpha, bool inplace) {
+  if (inplace) {
+    return torch::celu_(input, alpha);
+  } else {
+    return torch::celu(input, alpha);
+  }
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.celu
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::CELUFuncOptions` class to
+/// learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::celu(x, F::CELUFuncOptions().alpha(0.42).inplace(true));
+/// ```
+inline Tensor celu(Tensor input, const CELUFuncOptions& options = {}) {
+  return detail::celu(std::move(input), options.alpha(), options.inplace());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor softplus(const Tensor& input, double beta, double threshold) {
+  return torch::softplus(input, beta, threshold);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.softplus
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::SoftplusFuncOptions` class
+/// to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::softplus(x, F::SoftplusFuncOptions().beta(0.5).threshold(3.0));
+/// ```
+inline Tensor softplus(
+    const Tensor& input,
+    const SoftplusFuncOptions& options = {}) {
+  return detail::softplus(input, options.beta(), options.threshold());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor softshrink(const Tensor& input, double lambda) {
+  return torch::softshrink(input, lambda);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.softshrink
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::SoftshrinkFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::softshrink(x, F::SoftshrinkFuncOptions(0.42));
+/// ```
+inline Tensor softshrink(
+    const Tensor& input,
+    const SoftshrinkFuncOptions& options = {}) {
+  return detail::softshrink(input, options.lambda());
+}
+
+// ============================================================================
+
+inline Tensor softsign(const Tensor& input) {
+  return input / (input.abs() + 1);
+}
+
+// ============================================================================
+
+inline Tensor tanhshrink(const Tensor& input) {
+  return input - input.tanh();
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor threshold(
+    Tensor input,
+    double threshold,
+    double value,
+    bool inplace) {
+  if (inplace) {
+    return torch::threshold_(input, threshold, value);
+  } else {
+    return torch::threshold(input, threshold, value);
+  }
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.threshold
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::ThresholdFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::threshold(x, F::ThresholdFuncOptions(0.5, 0.5).inplace(true));
+/// ```
+inline Tensor threshold(Tensor input, const ThresholdFuncOptions& options) {
+  return detail::threshold(
+      std::move(input),
+      options.threshold(),
+      options.value(),
+      options.inplace());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline std::tuple multi_head_attention_forward(
+    const Tensor& query,
+    const Tensor& key,
+    const Tensor& value,
+    int64_t embed_dim_to_check,
+    int64_t num_heads,
+    const Tensor& in_proj_weight,
+    const Tensor& in_proj_bias,
+    const Tensor& bias_k,
+    const Tensor& bias_v,
+    bool add_zero_attn,
+    double dropout_p,
+    const Tensor& out_proj_weight,
+    const Tensor& out_proj_bias,
+    bool training = true,
+    const Tensor& key_padding_mask = {},
+    bool need_weights = true,
+    const Tensor& attn_mask = {},
+    bool use_separate_proj_weight = false,
+    const Tensor& q_proj_weight = {},
+    const Tensor& k_proj_weight = {},
+    const Tensor& v_proj_weight = {},
+    const Tensor& static_k = {},
+    const Tensor& static_v = {},
+    bool average_attn_weights = true) {
+  namespace F = torch::nn::functional;
+
+  const auto query_sizes = query.sizes();
+  const auto& tgt_len = query_sizes[0];
+  const auto& bsz = query_sizes[1];
+  const auto& embed_dim = query_sizes[2];
+  TORCH_INTERNAL_ASSERT(embed_dim == embed_dim_to_check);
+  TORCH_INTERNAL_ASSERT(key.sizes() == value.sizes());
+
+  const auto head_dim = embed_dim / num_heads;
+  TORCH_CHECK(
+      head_dim * num_heads == embed_dim,
+      "embed_dim must be divisible by num_heads");
+  const auto scaling = 1 / std::sqrt(head_dim);
+
+  Tensor q, k, v;
+  if (!use_separate_proj_weight) {
+    if (torch::equal(query, key) && torch::equal(key, value)) {
+      // self-attention
+      const auto chunks =
+          F::linear(query, in_proj_weight, in_proj_bias).chunk(3, /*dim=*/-1);
+      q = chunks[0];
+      k = chunks[1];
+      v = chunks[2];
+    } else if (torch::equal(key, value)) {
+      // encoder-decoder attention
+      // This is inline in_proj function with in_proj_weight and in_proj_bias
+      auto _b = in_proj_bias;
+      auto _start = 0;
+      auto _end = embed_dim;
+      auto _w = in_proj_weight.slice(/*dim=*/0, _start, _end);
+      if (_b.defined()) {
+        _b = _b.slice(/*dim=*/0, _start, _end);
+      }
+      q = F::linear(query, _w, _b);
+
+      if (!key.defined()) {
+        TORCH_INTERNAL_ASSERT(!value.defined());
+        k.reset();
+        v.reset();
+      } else {
+        // This is inline in_proj function with in_proj_weight and in_proj_bias
+        _b = in_proj_bias;
+        _start = embed_dim;
+        _w = in_proj_weight.slice(/*dim=*/0, _start);
+        if (_b.defined()) {
+          _b = _b.slice(/*dim=*/0, _start);
+        }
+        const auto chunks = F::linear(key, _w, _b).chunk(2, /*dim=*/-1);
+        k = chunks[0];
+        v = chunks[1];
+      }
+    } else {
+      // This is inline in_proj function with in_proj_weight and in_proj_bias
+      auto _b = in_proj_bias;
+      auto _start = 0;
+      auto _end = embed_dim;
+      auto _w = in_proj_weight.slice(/*dim=*/0, _start, _end);
+      if (_b.defined()) {
+        _b = _b.slice(/*dim=*/0, _start, _end);
+      }
+      q = F::linear(query, _w, _b);
+
+      // This is inline in_proj function with in_proj_weight and in_proj_bias
+      _b = in_proj_bias;
+      _start = embed_dim;
+      _end = embed_dim * 2;
+      _w = in_proj_weight.slice(/*dim=*/0, _start, _end);
+      if (_b.defined()) {
+        _b = _b.slice(/*dim=*/0, _start, _end);
+      }
+      k = F::linear(key, _w, _b);
+
+      // This is inline in_proj function with in_proj_weight and in_proj_bias
+      _b = in_proj_bias;
+      _start = embed_dim * 2;
+      _w = in_proj_weight.slice(/*dim=*/0, _start);
+      if (_b.defined()) {
+        _b = _b.slice(0, _start);
+      }
+      v = F::linear(value, _w, _b);
+    }
+  } else {
+    const auto& q_proj_weight_non_opt = q_proj_weight;
+    {
+      const auto sizes = q_proj_weight_non_opt.sizes();
+      const auto len1 = sizes[0];
+      const auto len2 = sizes[1];
+      TORCH_CHECK(len1 == embed_dim && len2 == query.size(-1));
+    }
+
+    const auto& k_proj_weight_non_opt = k_proj_weight;
+    {
+      const auto sizes = k_proj_weight_non_opt.sizes();
+      const auto len1 = sizes[0];
+      const auto len2 = sizes[1];
+      TORCH_CHECK(len1 == embed_dim && len2 == key.size(-1));
+    }
+
+    const auto& v_proj_weight_non_opt = v_proj_weight;
+    {
+      const auto sizes = v_proj_weight_non_opt.sizes();
+      const auto len1 = sizes[0];
+      const auto len2 = sizes[1];
+      TORCH_CHECK(len1 == embed_dim && len2 == value.size(-1));
+    }
+
+    if (in_proj_bias.defined()) {
+      q = F::linear(
+          query,
+          q_proj_weight_non_opt,
+          in_proj_bias.slice(/*dim=*/0, 0, embed_dim));
+      k = F::linear(
+          key,
+          k_proj_weight_non_opt,
+          in_proj_bias.slice(/*dim=*/0, embed_dim, (embed_dim * 2)));
+      v = F::linear(
+          value,
+          v_proj_weight_non_opt,
+          in_proj_bias.slice(/*dim=*/0, (embed_dim * 2)));
+    } else {
+      q = F::linear(query, q_proj_weight_non_opt, in_proj_bias);
+      k = F::linear(key, k_proj_weight_non_opt, in_proj_bias);
+      v = F::linear(value, v_proj_weight_non_opt, in_proj_bias);
+    }
+  }
+  q = q * scaling;
+  Tensor attn_mask_ = attn_mask;
+  Tensor key_padding_mask_ = key_padding_mask;
+  if (bias_k.defined() && bias_v.defined()) {
+    if (!static_k.defined() && !static_v.defined()) {
+      k = torch::cat({k, bias_k.repeat({1, bsz, 1})});
+      v = torch::cat({v, bias_v.repeat({1, bsz, 1})});
+      if (attn_mask_.defined()) {
+        attn_mask_ = torch::cat(
+            {attn_mask_,
+             torch::zeros(
+                 {attn_mask_.size(0), 1},
+                 at::TensorOptions(attn_mask_.dtype())
+                     .device(attn_mask_.device()))},
+            /*dim=*/1);
+      }
+      if (key_padding_mask_.defined()) {
+        key_padding_mask_ = torch::cat(
+            {key_padding_mask_,
+             torch::zeros(
+                 {key_padding_mask_.size(0), 1},
+                 at::TensorOptions(key_padding_mask_.dtype())
+                     .device(key_padding_mask_.device()))},
+            /*dim=*/1);
+      }
+    } else {
+      TORCH_CHECK(!static_k.defined(), "bias cannot be added to static key.");
+      TORCH_CHECK(!static_v.defined(), "bias cannot be added to static value.");
+    }
+  } else {
+    TORCH_CHECK(!bias_k.defined());
+    TORCH_CHECK(!bias_v.defined());
+  }
+  q = q.contiguous().view({tgt_len, bsz * num_heads, head_dim}).transpose(0, 1);
+  if (k.defined()) {
+    k = k.contiguous().view({-1, bsz * num_heads, head_dim}).transpose(0, 1);
+  }
+  if (v.defined()) {
+    v = v.contiguous().view({-1, bsz * num_heads, head_dim}).transpose(0, 1);
+  }
+  if (static_k.defined()) {
+    TORCH_CHECK(static_k.size(0) == bsz * num_heads);
+    TORCH_CHECK(static_k.size(2) == head_dim);
+    k = static_k;
+  }
+  if (static_v.defined()) {
+    TORCH_CHECK(static_v.size(0) == bsz * num_heads);
+    TORCH_CHECK(static_v.size(2) == head_dim);
+    v = static_v;
+  }
+  auto src_len = k.size(1);
+  if (key_padding_mask_.defined()) {
+    TORCH_CHECK(key_padding_mask_.size(0) == bsz);
+    TORCH_CHECK(key_padding_mask_.size(1) == src_len);
+  }
+  if (add_zero_attn) {
+    src_len += 1;
+    auto k_sizes = k.sizes().vec();
+    k_sizes[1] = 1;
+    k = torch::cat(
+        {k,
+         torch::zeros(
+             k_sizes, at::TensorOptions(k.dtype()).device(k.device()))},
+        /*dim=*/1);
+    auto v_sizes = v.sizes().vec();
+    v_sizes[1] = 1;
+    v = torch::cat(
+        {v,
+         torch::zeros(
+             v_sizes, at::TensorOptions(v.dtype()).device(v.device()))},
+        /*dim=*/1);
+    if (attn_mask_.defined()) {
+      attn_mask_ = torch::cat(
+          {attn_mask_,
+           torch::zeros(
+               {attn_mask_.size(0), 1},
+               at::TensorOptions(attn_mask_.dtype())
+                   .device(attn_mask_.device()))},
+          /*dim=*/1);
+    }
+    if (key_padding_mask_.defined()) {
+      key_padding_mask_ = torch::cat(
+          {key_padding_mask_,
+           torch::zeros(
+               {key_padding_mask_.size(0), 1},
+               at::TensorOptions(key_padding_mask_.dtype())
+                   .device(key_padding_mask_.device()))},
+          /*dim=*/1);
+    }
+  }
+  auto attn_output_weights = torch::bmm(q, k.transpose(1, 2));
+  TORCH_CHECK(
+      attn_output_weights.sizes() ==
+      IntArrayRef({bsz * num_heads, tgt_len, src_len}));
+  if (attn_mask_.defined()) {
+    attn_mask_ = attn_mask_.unsqueeze(0);
+    attn_output_weights += attn_mask_;
+  }
+  if (key_padding_mask_.defined()) {
+    attn_output_weights =
+        attn_output_weights.view({bsz, num_heads, tgt_len, src_len});
+    attn_output_weights = AT_DISPATCH_FLOATING_TYPES(
+        attn_output_weights.scalar_type(),
+        "attn_output_weights.masked_fill",
+        [&]() {
+          return attn_output_weights.masked_fill(
+              key_padding_mask_.unsqueeze(1).unsqueeze(2),
+              -std::numeric_limits::infinity());
+        });
+    attn_output_weights =
+        attn_output_weights.view({bsz * num_heads, tgt_len, src_len});
+  }
+  // NOLINTNEXTLINE(bugprone-argument-comment)
+  attn_output_weights = F::softmax(attn_output_weights, /*dim=*/-1);
+  attn_output_weights = F::dropout(
+      attn_output_weights,
+      F::DropoutFuncOptions().p(dropout_p).training(training));
+  auto attn_output = torch::bmm(attn_output_weights, v);
+  TORCH_CHECK(
+      attn_output.sizes() == IntArrayRef({bsz * num_heads, tgt_len, head_dim}));
+  attn_output =
+      attn_output.transpose(0, 1).contiguous().view({tgt_len, bsz, embed_dim});
+  attn_output = F::linear(attn_output, out_proj_weight, out_proj_bias);
+  if (need_weights) {
+    attn_output_weights =
+        attn_output_weights.view({bsz, num_heads, tgt_len, src_len});
+    if (average_attn_weights) {
+      // average attention weights over heads
+      attn_output_weights = attn_output_weights.sum(/*dim=*/1) / num_heads;
+    }
+    return std::make_tuple(attn_output, attn_output_weights);
+  } else {
+    return std::make_tuple(attn_output, Tensor());
+  }
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+inline std::tuple multi_head_attention_forward(
+    const Tensor& query,
+    const Tensor& key,
+    const Tensor& value,
+    const MultiheadAttentionForwardFuncOptions& options) {
+  return detail::multi_head_attention_forward(
+      query,
+      key,
+      value,
+      options.embed_dim_to_check(),
+      options.num_heads(),
+      options.in_proj_weight(),
+      options.in_proj_bias(),
+      options.bias_k(),
+      options.bias_v(),
+      options.add_zero_attn(),
+      options.dropout_p(),
+      options.out_proj_weight(),
+      options.out_proj_bias(),
+      options.training(),
+      options.key_padding_mask(),
+      options.need_weights(),
+      options.attn_mask(),
+      options.use_separate_proj_weight(),
+      options.q_proj_weight(),
+      options.k_proj_weight(),
+      options.v_proj_weight(),
+      options.static_k(),
+      options.static_v(),
+      options.average_attn_weights());
+}
+
+} // namespace functional
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/batchnorm.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/batchnorm.h
new file mode 100644
index 0000000000000000000000000000000000000000..bc6f141281b39dfbecf01dd38a6c43cb84836b1c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/batchnorm.h
@@ -0,0 +1,83 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+namespace functional {
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor batch_norm(
+    const Tensor& input,
+    const Tensor& running_mean,
+    const Tensor& running_var,
+    Tensor weight,
+    Tensor bias,
+    bool training,
+    std::optional momentum,
+    double eps) {
+  TORCH_CHECK(
+      input.dim() >= 2,
+      "Expected at least 2 input dimensions, but got ",
+      input.dim());
+  if (training) {
+    auto size = input.sizes();
+    int64_t size_prods = size[0];
+    for (const auto i : c10::irange(size.size() - 2)) {
+      size_prods *= size[i + 2];
+    }
+    TORCH_CHECK(
+        size_prods != 1,
+        "Expected more than 1 value per channel when training, got input size ",
+        size);
+  }
+
+  return torch::batch_norm(
+      input,
+      weight,
+      bias,
+      running_mean,
+      running_var,
+      training,
+      momentum.value(),
+      eps,
+      at::globalContext().userEnabledCuDNN());
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.batch_norm
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::BatchNormFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::batch_norm(input, mean, variance,
+/// F::BatchNormFuncOptions().weight(weight).bias(bias).momentum(0.1).eps(1e-05).training(false));
+/// ```
+inline Tensor batch_norm(
+    const Tensor& input,
+    const Tensor& running_mean,
+    const Tensor& running_var,
+    const BatchNormFuncOptions& options = {}) {
+  return detail::batch_norm(
+      input,
+      running_mean,
+      running_var,
+      options.weight(),
+      options.bias(),
+      options.training(),
+      options.momentum(),
+      options.eps());
+}
+
+} // namespace functional
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/conv.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/conv.h
new file mode 100644
index 0000000000000000000000000000000000000000..8f85fb286731ae311ddf866bce70d678dbc9845a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/conv.h
@@ -0,0 +1,301 @@
+#pragma once
+
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+namespace functional {
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+
+inline std::string padding_unwrap(enumtype::kValid) {
+  return "valid";
+}
+
+inline std::string padding_unwrap(enumtype::kSame) {
+  return "same";
+}
+
+template 
+IntArrayRef padding_unwrap(const ExpandingArray& array) {
+  return array;
+}
+
+inline Tensor conv1d(
+    const Tensor& input,
+    const Tensor& weight,
+    const Tensor& bias,
+    ExpandingArray<1> stride,
+    const Conv1dFuncOptions::padding_t& padding,
+    ExpandingArray<1> dilation,
+    int64_t groups) {
+  return std::visit(
+      [&](const auto& pad) {
+        return torch::conv1d(
+            input, weight, bias, stride, padding_unwrap(pad), dilation, groups);
+      },
+      padding);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.conv1d
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::Conv1dFuncOptions` class
+/// to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::conv1d(x, weight, F::Conv1dFuncOptions().stride(1));
+/// ```
+inline Tensor conv1d(
+    const Tensor& input,
+    const Tensor& weight,
+    const Conv1dFuncOptions& options = {}) {
+  return detail::conv1d(
+      input,
+      weight,
+      options.bias(),
+      options.stride(),
+      options.padding(),
+      options.dilation(),
+      options.groups());
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor conv2d(
+    const Tensor& input,
+    const Tensor& weight,
+    const Tensor& bias,
+    ExpandingArray<2> stride,
+    const Conv2dFuncOptions::padding_t& padding,
+    ExpandingArray<2> dilation,
+    int64_t groups) {
+  return std::visit(
+      [&](const auto& pad) {
+        return torch::conv2d(
+            input, weight, bias, stride, padding_unwrap(pad), dilation, groups);
+      },
+      padding);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.conv2d
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::Conv2dFuncOptions` class
+/// to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::conv2d(x, weight, F::Conv2dFuncOptions().stride(1));
+/// ```
+inline Tensor conv2d(
+    const Tensor& input,
+    const Tensor& weight,
+    const Conv2dFuncOptions& options = {}) {
+  return detail::conv2d(
+      input,
+      weight,
+      options.bias(),
+      options.stride(),
+      options.padding(),
+      options.dilation(),
+      options.groups());
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor conv3d(
+    const Tensor& input,
+    const Tensor& weight,
+    const Tensor& bias,
+    ExpandingArray<3> stride,
+    const Conv3dFuncOptions::padding_t& padding,
+    ExpandingArray<3> dilation,
+    int64_t groups) {
+  return std::visit(
+      [&](const auto& pad) {
+        return torch::conv3d(
+            input, weight, bias, stride, padding_unwrap(pad), dilation, groups);
+      },
+      padding);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.conv3d
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::Conv3dFuncOptions` class
+/// to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::conv3d(x, weight, F::Conv3dFuncOptions().stride(1));
+/// ```
+inline Tensor conv3d(
+    const Tensor& input,
+    const Tensor& weight,
+    const Conv3dFuncOptions& options = {}) {
+  return detail::conv3d(
+      input,
+      weight,
+      options.bias(),
+      options.stride(),
+      options.padding(),
+      options.dilation(),
+      options.groups());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor conv_transpose1d(
+    const Tensor& input,
+    const Tensor& weight,
+    const Tensor& bias,
+    IntArrayRef stride,
+    IntArrayRef padding,
+    IntArrayRef output_padding,
+    int64_t groups,
+    IntArrayRef dilation) {
+  return torch::conv_transpose1d(
+      input, weight, bias, stride, padding, output_padding, groups, dilation);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.conv_transpose1d
+/// about the exact behavior of this functional.
+///
+/// See the documentation for
+/// `torch::nn::functional::ConvTranspose1dFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::conv_transpose1d(x, weight, F::ConvTranspose1dFuncOptions().stride(1));
+/// ```
+inline Tensor conv_transpose1d(
+    const Tensor& input,
+    const Tensor& weight,
+    const ConvTranspose1dFuncOptions& options = {}) {
+  return detail::conv_transpose1d(
+      input,
+      weight,
+      options.bias(),
+      options.stride(),
+      options.padding(),
+      options.output_padding(),
+      options.groups(),
+      options.dilation());
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor conv_transpose2d(
+    const Tensor& input,
+    const Tensor& weight,
+    const Tensor& bias,
+    IntArrayRef stride,
+    IntArrayRef padding,
+    IntArrayRef output_padding,
+    int64_t groups,
+    IntArrayRef dilation) {
+  return torch::conv_transpose2d(
+      input, weight, bias, stride, padding, output_padding, groups, dilation);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.conv_transpose2d
+/// about the exact behavior of this functional.
+///
+/// See the documentation for
+/// `torch::nn::functional::ConvTranspose2dFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::conv_transpose2d(x, weight, F::ConvTranspose2dFuncOptions().stride(1));
+/// ```
+inline Tensor conv_transpose2d(
+    const Tensor& input,
+    const Tensor& weight,
+    const ConvTranspose2dFuncOptions& options = {}) {
+  return detail::conv_transpose2d(
+      input,
+      weight,
+      options.bias(),
+      options.stride(),
+      options.padding(),
+      options.output_padding(),
+      options.groups(),
+      options.dilation());
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor conv_transpose3d(
+    const Tensor& input,
+    const Tensor& weight,
+    const Tensor& bias,
+    IntArrayRef stride,
+    IntArrayRef padding,
+    IntArrayRef output_padding,
+    int64_t groups,
+    IntArrayRef dilation) {
+  return torch::conv_transpose3d(
+      input, weight, bias, stride, padding, output_padding, groups, dilation);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.conv_transpose3d
+/// about the exact behavior of this functional.
+///
+/// See the documentation for
+/// `torch::nn::functional::ConvTranspose3dFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::conv_transpose3d(x, weight, F::ConvTranspose3dFuncOptions().stride(1));
+/// ```
+inline Tensor conv_transpose3d(
+    const Tensor& input,
+    const Tensor& weight,
+    const ConvTranspose3dFuncOptions& options = {}) {
+  return detail::conv_transpose3d(
+      input,
+      weight,
+      options.bias(),
+      options.stride(),
+      options.padding(),
+      options.output_padding(),
+      options.groups(),
+      options.dilation());
+}
+
+} // namespace functional
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/distance.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/distance.h
new file mode 100644
index 0000000000000000000000000000000000000000..84f6009fae9d7259118a5451e165e1af644956e2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/distance.h
@@ -0,0 +1,88 @@
+#pragma once
+
+#include 
+
+namespace torch {
+namespace nn {
+namespace functional {
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor cosine_similarity(
+    const Tensor& x1,
+    const Tensor& x2,
+    int64_t dim,
+    double eps) {
+  return torch::cosine_similarity(x1, x2, dim, eps);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.cosine_similarity
+/// about the exact behavior of this functional.
+///
+/// See the documentation for
+/// `torch::nn::functional::CosineSimilarityFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::cosine_similarity(input1, input2,
+/// F::CosineSimilarityFuncOptions().dim(1));
+/// ```
+inline Tensor cosine_similarity(
+    const Tensor& x1,
+    const Tensor& x2,
+    const CosineSimilarityFuncOptions& options = {}) {
+  return detail::cosine_similarity(x1, x2, options.dim(), options.eps());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor pairwise_distance(
+    const Tensor& x1,
+    const Tensor& x2,
+    double p,
+    double eps,
+    bool keepdim) {
+  return torch::pairwise_distance(x1, x2, p, eps, keepdim);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.pairwise_distance
+/// about the exact behavior of this functional.
+///
+/// See the documentation for
+/// `torch::nn::functional::PairwiseDistanceFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::pairwise_distance(input1, input2, F::PairwiseDistanceFuncOptions().p(1));
+/// ```
+inline Tensor pairwise_distance(
+    const Tensor& x1,
+    const Tensor& x2,
+    const PairwiseDistanceFuncOptions& options = {}) {
+  return detail::pairwise_distance(
+      x1, x2, options.p(), options.eps(), options.keepdim());
+}
+
+// ============================================================================
+
+/// Computes the p-norm distance between every pair of row vectors in the input.
+/// This function will be faster if the rows are contiguous.
+inline Tensor pdist(const Tensor& input, double p = 2.0) {
+  return torch::pdist(input, p);
+}
+
+} // namespace functional
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/dropout.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/dropout.h
new file mode 100644
index 0000000000000000000000000000000000000000..6b7953a266c4d16f512da4cac9cf8cf5b06b9430
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/dropout.h
@@ -0,0 +1,234 @@
+#pragma once
+
+#include 
+
+#include 
+
+namespace torch {
+namespace nn {
+namespace functional {
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+
+inline Tensor dropout(Tensor input, double p, bool training, bool inplace) {
+  TORCH_CHECK(
+      p >= 0. && p <= 1.,
+      "dropout probability has to be between 0 and 1, but got ",
+      p);
+  if (inplace) {
+    return torch::dropout_(input, p, training);
+  } else {
+    return torch::dropout(input, p, training);
+  }
+}
+
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.dropout
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::DropoutFuncOptions` class
+/// to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::dropout(input, F::DropoutFuncOptions().p(0.5));
+/// ```
+inline Tensor dropout(Tensor input, const DropoutFuncOptions& options = {}) {
+  return detail::dropout(
+      std::move(input), options.p(), options.training(), options.inplace());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+
+template 
+inline Tensor _dropoutNd_helper(
+    Tensor input,
+    double p,
+    bool training,
+    bool inplace,
+    const char* fn_name) {
+  TORCH_CHECK(
+      p >= 0. && p <= 1.,
+      "dropout probability has to be between 0 and 1, but got ",
+      p);
+
+  auto inp_dim = input.dim();
+  auto is_batched = inp_dim == batched_dim;
+  if (!is_batched) {
+    if (inplace) {
+      input = input.unsqueeze_(0);
+    } else {
+      input = input.unsqueeze(0);
+    }
+  }
+
+  Tensor result;
+  if (inplace) {
+    result = torch::feature_dropout_(input, p, training);
+  } else {
+    result = torch::feature_dropout(input, p, training);
+  }
+
+  if (!is_batched) {
+    if (inplace) {
+      result = result.squeeze_(0);
+    } else {
+      result = result.squeeze(0);
+    }
+  }
+  return result;
+}
+
+inline Tensor dropout2d(Tensor input, double p, bool training, bool inplace) {
+  return _dropoutNd_helper<3, 4>(
+      std::move(input), p, training, inplace, "dropout2d");
+}
+
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.dropout2d
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::Dropout2dFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::dropout2d(input, F::Dropout2dFuncOptions().p(0.5));
+/// ```
+inline Tensor dropout2d(
+    Tensor input,
+    const Dropout2dFuncOptions& options = {}) {
+  return detail::dropout2d(
+      std::move(input), options.p(), options.training(), options.inplace());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+
+inline Tensor dropout3d(Tensor input, double p, bool training, bool inplace) {
+  return _dropoutNd_helper<4, 5>(
+      std::move(input), p, training, inplace, "dropout3d");
+}
+
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.dropout3d
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::Dropout3dFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::dropout3d(input, F::Dropout3dFuncOptions().p(0.5));
+/// ```
+inline Tensor dropout3d(
+    Tensor input,
+    const Dropout3dFuncOptions& options = {}) {
+  return detail::dropout3d(
+      std::move(input), options.p(), options.training(), options.inplace());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+
+inline Tensor alpha_dropout(
+    Tensor input,
+    double p,
+    bool training,
+    bool inplace) {
+  if (p < 0. || p > 1.) {
+    TORCH_CHECK(
+        false, "dropout probability has to be between 0 and 1, but got ", p);
+  }
+  return inplace ? torch::alpha_dropout_(input, p, training)
+                 : torch::alpha_dropout(input, p, training);
+}
+
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.alpha_dropout
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::AlphaDropoutFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::alpha_dropout(input,
+/// F::AlphaDropoutFuncOptions().p(0.5).training(false));
+/// ```
+inline Tensor alpha_dropout(
+    Tensor input,
+    const AlphaDropoutFuncOptions& options = {}) {
+  return detail::alpha_dropout(
+      std::move(input), options.p(), options.training(), options.inplace());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+
+inline Tensor feature_alpha_dropout(
+    Tensor input,
+    double p,
+    bool training,
+    bool inplace) {
+  if (p < 0. || p > 1.) {
+    TORCH_CHECK(
+        false, "dropout probability has to be between 0 and 1, but got ", p);
+  }
+  return inplace ? torch::feature_alpha_dropout_(input, p, training)
+                 : torch::feature_alpha_dropout(input, p, training);
+}
+
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.feature_alpha_dropout
+/// about the exact behavior of this functional.
+///
+/// See the documentation for
+/// `torch::nn::functional::FeatureAlphaDropoutFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::feature_alpha_dropout(input,
+/// F::FeatureAlphaDropoutFuncOptions().p(0.5).training(false));
+/// ```
+inline Tensor feature_alpha_dropout(
+    Tensor input,
+    const FeatureAlphaDropoutFuncOptions& options = {}) {
+  return detail::feature_alpha_dropout(
+      std::move(input), options.p(), options.training(), options.inplace());
+}
+
+} // namespace functional
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/embedding.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/embedding.h
new file mode 100644
index 0000000000000000000000000000000000000000..602268ab2eba300e53e14614cbacf273d91e187e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/embedding.h
@@ -0,0 +1,211 @@
+#pragma once
+
+#include 
+
+namespace torch {
+namespace nn {
+namespace functional {
+
+inline Tensor one_hot(const Tensor& tensor, int64_t num_classes = -1) {
+  return torch::one_hot(tensor, num_classes);
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline void _no_grad_embedding_renorm_(
+    Tensor weight,
+    const Tensor& input,
+    float max_norm,
+    float norm_type) {
+  torch::NoGradGuard no_grad;
+  torch::embedding_renorm_(weight, input, max_norm, norm_type);
+}
+
+inline Tensor embedding(
+    const Tensor& input,
+    const Tensor& weight,
+    std::optional padding_idx,
+    std::optional max_norm,
+    double norm_type,
+    bool scale_grad_by_freq,
+    bool sparse) {
+  auto input_ = input;
+
+  if (padding_idx != std::nullopt) {
+    if (*padding_idx > 0) {
+      TORCH_CHECK(
+          *padding_idx < weight.size(0),
+          "Padding_idx must be within num_embeddings");
+    } else if (*padding_idx < 0) {
+      TORCH_CHECK(
+          *padding_idx >= -weight.size(0),
+          "Padding_idx must be within num_embedding");
+      padding_idx = weight.size(0) + *padding_idx;
+    }
+  } else {
+    padding_idx = -1;
+  }
+
+  if (max_norm != std::nullopt) {
+    input_ = input_.contiguous();
+    // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions)
+    _no_grad_embedding_renorm_(weight, input_, *max_norm, norm_type);
+  }
+  return torch::embedding(
+      weight, input_, *padding_idx, scale_grad_by_freq, sparse);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.embedding
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::EmbeddingFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::embedding(input, weight,
+/// F::EmbeddingFuncOptions().norm_type(2.5).scale_grad_by_freq(true).sparse(true));
+/// ```
+inline Tensor embedding(
+    const Tensor& input,
+    const Tensor& weight,
+    const EmbeddingFuncOptions& options = {}) {
+  return detail::embedding(
+      input,
+      weight,
+      options.padding_idx(),
+      options.max_norm(),
+      options.norm_type(),
+      options.scale_grad_by_freq(),
+      options.sparse());
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor embedding_bag(
+    const Tensor& input,
+    const Tensor& weight,
+    const Tensor& offsets,
+    std::optional max_norm,
+    double norm_type,
+    bool scale_grad_by_freq,
+    EmbeddingBagMode mode,
+    bool sparse,
+    const Tensor& per_sample_weights,
+    bool include_last_offset,
+    std::optional padding_idx) {
+  auto input_ = input;
+  auto offsets_ = offsets;
+  auto per_sample_weights_ = per_sample_weights;
+  TORCH_CHECK(
+      !per_sample_weights_.defined() ||
+          input_.sizes() == per_sample_weights_.sizes(),
+      "embedding_bag: If per_sample_weights (",
+      per_sample_weights_.sizes(),
+      ") is not null, then it must have the same shape as the input (",
+      input_.sizes(),
+      ")");
+  if (input_.dim() == 2) {
+    TORCH_CHECK(
+        !offsets_.defined(),
+        "If input is 2D, then offsets has to be null, as input is treated is a mini-batch of fixed length sequences. However, found offsets of type Tensor");
+    offsets_ = torch::arange(
+        0,
+        input_.numel(),
+        input_.size(1),
+        torch::TensorOptions().dtype(torch::kLong).device(input_.device()));
+    input_ = input_.reshape(-1);
+    if (per_sample_weights_.defined()) {
+      per_sample_weights_ = per_sample_weights_.reshape(-1);
+    }
+  } else if (input_.dim() == 1) {
+    TORCH_CHECK(
+        offsets_.defined(), "offsets has to be a 1D Tensor but got null");
+    TORCH_CHECK(offsets_.dim() == 1, "offsets has to be a 1D Tensor");
+  } else {
+    TORCH_CHECK(
+        false,
+        "input has to be 1D or 2D Tensor, but got Tensor of dimension ",
+        input_.dim());
+  }
+
+  // NOLINTNEXTLINE(cppcoreguidelines-init-variables)
+  int mode_enum;
+  if (std::holds_alternative(mode)) {
+    mode_enum = 0;
+  } else if (std::holds_alternative(mode)) {
+    mode_enum = 1;
+  } else if (std::holds_alternative(mode)) {
+    mode_enum = 2;
+    TORCH_CHECK(
+        !scale_grad_by_freq,
+        "max mode does not support scaling the gradient by the frequency");
+    TORCH_CHECK(!sparse, "max mode does not support sparse weights");
+  } else {
+    TORCH_CHECK(false, "mode has to be one of sum, mean or max");
+  }
+
+  if (max_norm != std::nullopt) {
+    // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions)
+    _no_grad_embedding_renorm_(weight, input_, *max_norm, norm_type);
+  }
+
+  TORCH_CHECK(
+      !per_sample_weights_.defined() || std::get_if(&mode),
+      "embedding_bag: per_sample_weights was not null. ",
+      "per_sample_weights is only supported for mode='kSum' (got mode='",
+      torch::enumtype::get_enum_name(mode),
+      "').Please open a feature request on GitHub.");
+
+  return std::get<0>(torch::embedding_bag(
+      weight,
+      input_,
+      offsets_,
+      scale_grad_by_freq,
+      mode_enum,
+      sparse,
+      per_sample_weights_,
+      include_last_offset,
+      padding_idx));
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.embedding_bag
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::EmbeddingBagFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::embedding_bag(input, weight,
+/// F::EmbeddingBagFuncOptions().mode(torch::kSum).offsets(offsets));
+/// ```
+inline Tensor embedding_bag(
+    const Tensor& input,
+    const Tensor& weight,
+    const EmbeddingBagFuncOptions& options = {}) {
+  return detail::embedding_bag(
+      input,
+      weight,
+      options.offsets(),
+      options.max_norm(),
+      options.norm_type(),
+      options.scale_grad_by_freq(),
+      options.mode(),
+      options.sparse(),
+      options.per_sample_weights(),
+      options.include_last_offset(),
+      options.padding_idx());
+}
+
+} // namespace functional
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/fold.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/fold.h
new file mode 100644
index 0000000000000000000000000000000000000000..4f1716b2881bcc3a2d4d5e49df3020bc2462b289
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/fold.h
@@ -0,0 +1,102 @@
+#pragma once
+
+#include 
+
+namespace torch {
+namespace nn {
+namespace functional {
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor fold(
+    const Tensor& input,
+    ExpandingArray<2> output_size,
+    ExpandingArray<2> kernel_size,
+    ExpandingArray<2> dilation,
+    ExpandingArray<2> padding,
+    ExpandingArray<2> stride) {
+  if (input.dim() == 3 || input.dim() == 2) {
+    return torch::col2im(
+        input, output_size, kernel_size, dilation, padding, stride);
+  } else {
+    TORCH_CHECK(
+        false,
+        "Input Error: Only unbatched (2D) or batched (3D) input Tensors are supported "
+        "(got ",
+        input.dim(),
+        "D)");
+  }
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.fold
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::FoldFuncOptions` class to
+/// learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::fold(input, F::FoldFuncOptions({3, 2}, {2, 2}));
+/// ```
+inline Tensor fold(const Tensor& input, const FoldFuncOptions& options) {
+  return detail::fold(
+      input,
+      options.output_size(),
+      options.kernel_size(),
+      options.dilation(),
+      options.padding(),
+      options.stride());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor unfold(
+    const Tensor& input,
+    ExpandingArray<2> kernel_size,
+    ExpandingArray<2> dilation,
+    ExpandingArray<2> padding,
+    ExpandingArray<2> stride) {
+  if (input.dim() == 4) {
+    return torch::im2col(input, kernel_size, dilation, padding, stride);
+  } else {
+    TORCH_CHECK(
+        false,
+        "Input Error: Only 4D input Tensors are supported "
+        "(got ",
+        input.dim(),
+        "D)");
+  }
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.unfold
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::UnfoldFuncOptions` class
+/// to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::unfold(input, F::UnfoldFuncOptions({2, 2}).padding(1).stride(2));
+/// ```
+inline Tensor unfold(const Tensor& input, const UnfoldFuncOptions& options) {
+  return detail::unfold(
+      input,
+      options.kernel_size(),
+      options.dilation(),
+      options.padding(),
+      options.stride());
+}
+
+} // namespace functional
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/instancenorm.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/instancenorm.h
new file mode 100644
index 0000000000000000000000000000000000000000..17efaea7a5e55c9ce4b467917dfd48be35a5d05e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/instancenorm.h
@@ -0,0 +1,63 @@
+#pragma once
+
+#include 
+
+namespace torch {
+namespace nn {
+namespace functional {
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor instance_norm(
+    const Tensor& input,
+    const Tensor& running_mean,
+    const Tensor& running_var,
+    const Tensor& weight,
+    const Tensor& bias,
+    bool use_input_stats,
+    double momentum,
+    double eps) {
+  return torch::instance_norm(
+      input,
+      weight,
+      bias,
+      running_mean,
+      running_var,
+      use_input_stats,
+      momentum,
+      eps,
+      at::globalContext().userEnabledCuDNN());
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.instance_norm
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::InstanceNormFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::instance_norm(input,
+/// F::InstanceNormFuncOptions().running_mean(mean).running_var(variance).weight(weight).bias(bias).momentum(0.1).eps(1e-5));
+/// ```
+inline Tensor instance_norm(
+    const Tensor& input,
+    const InstanceNormFuncOptions& options = {}) {
+  return detail::instance_norm(
+      input,
+      options.running_mean(),
+      options.running_var(),
+      options.weight(),
+      options.bias(),
+      options.use_input_stats(),
+      options.momentum(),
+      options.eps());
+}
+
+} // namespace functional
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/linear.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/linear.h
new file mode 100644
index 0000000000000000000000000000000000000000..ffeafcd712af0421a23fe6f344f032a35e40c674
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/linear.h
@@ -0,0 +1,37 @@
+#pragma once
+
+#include 
+
+namespace torch {
+namespace nn {
+namespace functional {
+
+inline Tensor bilinear(
+    const Tensor& input1,
+    const Tensor& input2,
+    const Tensor& weight,
+    const Tensor& bias = Tensor()) {
+  return torch::bilinear(input1, input2, weight, bias);
+}
+
+// ============================================================================
+
+inline Tensor linear(
+    const Tensor& input,
+    const Tensor& weight,
+    const Tensor& bias = {}) {
+  if (input.dim() == 2 && bias.defined()) {
+    // fused op is marginally faster
+    return torch::addmm(bias, input, weight.t());
+  } else {
+    auto output = input.matmul(weight.t());
+    if (bias.defined()) {
+      output += bias;
+    }
+    return output;
+  }
+}
+
+} // namespace functional
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/loss.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/loss.h
new file mode 100644
index 0000000000000000000000000000000000000000..6a425e606caf2678bda9f52379325e3894c71fd6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/loss.h
@@ -0,0 +1,1044 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+namespace functional {
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor l1_loss(
+    const Tensor& input,
+    const Tensor& target,
+    L1LossFuncOptions::reduction_t reduction) {
+  return torch::l1_loss(input, target, enumtype::reduction_get_enum(reduction));
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.l1_loss
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::L1LossFuncOptions` class
+/// to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::l1_loss(input, target, F::L1LossFuncOptions(torch::kNone));
+/// ```
+inline Tensor l1_loss(
+    const Tensor& input,
+    const Tensor& target,
+    const L1LossFuncOptions& options = {}) {
+  return detail::l1_loss(input, target, options.reduction());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor kl_div(
+    const Tensor& input,
+    const Tensor& target,
+    KLDivFuncOptions::reduction_t reduction,
+    bool log_target = false) {
+  // NOLINTNEXTLINE(cppcoreguidelines-init-variables)
+  torch::Reduction::Reduction reduction_enum;
+
+  if (std::holds_alternative(reduction)) {
+    TORCH_WARN(
+        "reduction: 'mean' divides the total loss by both the batch size and the support size."
+        "'batchmean' divides only by the batch size, and aligns with the KL div math definition."
+        "'mean' will be changed to behave the same as 'batchmean' in the next major release.");
+  }
+
+  // special case for batchmean
+  if (std::holds_alternative(reduction)) {
+    reduction_enum = torch::Reduction::Sum;
+  } else {
+    reduction_enum = enumtype::reduction_get_enum(reduction);
+  }
+
+  auto reduced = torch::kl_div(input, target, reduction_enum, log_target);
+
+  if (std::holds_alternative(reduction) &&
+      input.dim() != 0) {
+    reduced = reduced / input.sizes()[0];
+  }
+
+  return reduced;
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.kl_div
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::KLDivFuncOptions` class to
+/// learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::kl_div(input, target,
+/// F::KLDivFuncOptions.reduction(torch::kNone).log_target(false));
+/// ```
+inline Tensor kl_div(
+    const Tensor& input,
+    const Tensor& target,
+    const KLDivFuncOptions& options = {}) {
+  return detail::kl_div(
+      input, target, options.reduction(), options.log_target());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor mse_loss(
+    const Tensor& input,
+    const Tensor& target,
+    MSELossFuncOptions::reduction_t reduction) {
+  if (!(target.sizes() == input.sizes())) {
+    TORCH_WARN(
+        "Using a target size (",
+        target.sizes(),
+        ") that is different to the input size (",
+        input.sizes(),
+        "). ",
+        "This will likely lead to incorrect results due to broadcasting. ",
+        "Please ensure they have the same size.");
+  }
+  std::vector broadcast_tensors =
+      torch::broadcast_tensors({input, target});
+  auto expanded_input = broadcast_tensors[0];
+  auto expanded_target = broadcast_tensors[1];
+  return torch::mse_loss(
+      expanded_input, expanded_target, enumtype::reduction_get_enum(reduction));
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.mse_loss
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::MSELossFuncOptions` class
+/// to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::mse_loss(input, target, F::MSELossFuncOptions(torch::kNone));
+/// ```
+inline Tensor mse_loss(
+    const Tensor& input,
+    const Tensor& target,
+    const MSELossFuncOptions& options = {}) {
+  return detail::mse_loss(input, target, options.reduction());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor binary_cross_entropy(
+    const Tensor& input,
+    const Tensor& target,
+    const Tensor& weight,
+    BinaryCrossEntropyFuncOptions::reduction_t reduction) {
+  auto reduction_enum = enumtype::reduction_get_enum(reduction);
+
+  if (target.sizes() != input.sizes()) {
+    TORCH_CHECK(
+        false,
+        "Using a target size (",
+        target.sizes(),
+        ") ",
+        "that is different to the input size (",
+        input.sizes(),
+        ") is deprecated. ",
+        "Please ensure they have the same size.");
+  }
+
+  auto weight_ = weight;
+  if (weight_.defined()) {
+    auto new_size = at::infer_size(target.sizes(), weight_.sizes());
+    weight_ = weight_.expand(new_size);
+  }
+
+  return torch::binary_cross_entropy(input, target, weight_, reduction_enum);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.binary_cross_entropy
+/// about the exact behavior of this functional.
+///
+/// See the documentation for
+/// `torch::nn::functional::BinaryCrossEntropyFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::binary_cross_entropy(input, target,
+/// F::BinaryCrossEntropyFuncOptions().weight(weight));
+/// ```
+inline Tensor binary_cross_entropy(
+    const Tensor& input,
+    const Tensor& target,
+    const BinaryCrossEntropyFuncOptions& options = {}) {
+  return detail::binary_cross_entropy(
+      input, target, options.weight(), options.reduction());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor hinge_embedding_loss(
+    const Tensor& input,
+    const Tensor& target,
+    double margin,
+    HingeEmbeddingLossFuncOptions::reduction_t reduction) {
+  return torch::hinge_embedding_loss(
+      input, target, margin, enumtype::reduction_get_enum(reduction));
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.hinge_embedding_loss
+/// about the exact behavior of this functional.
+///
+/// See the documentation for
+/// `torch::nn::functional::HingeEmbeddingLossFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::hinge_embedding_loss(input, target,
+/// F::HingeEmbeddingLossFuncOptions().margin(2));
+/// ```
+inline Tensor hinge_embedding_loss(
+    const Tensor& input,
+    const Tensor& target,
+    const HingeEmbeddingLossFuncOptions& options = {}) {
+  return detail::hinge_embedding_loss(
+      input, target, options.margin(), options.reduction());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor multi_margin_loss(
+    const Tensor& input,
+    const Tensor& target,
+    int64_t p,
+    double margin,
+    const Tensor& weight,
+    MultiMarginLossFuncOptions::reduction_t reduction) {
+  TORCH_CHECK(p == 1 || p == 2, "only p == 1 and p == 2 supported");
+  if (weight.defined()) {
+    TORCH_CHECK(weight.dim() == 1, "weight must be one-dimensional");
+  }
+
+  return torch::multi_margin_loss(
+      input,
+      target,
+      p,
+      margin,
+      weight,
+      enumtype::reduction_get_enum(reduction));
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.multi_margin_loss
+/// about the exact behavior of this functional.
+///
+/// See the documentation for
+/// `torch::nn::functional::MultiMarginLossFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::multi_margin_loss(input, target,
+/// F::MultiMarginLossFuncOptions().margin(2).weight(weight));
+/// ```
+inline Tensor multi_margin_loss(
+    const Tensor& input,
+    const Tensor& target,
+    const MultiMarginLossFuncOptions& options = {}) {
+  return detail::multi_margin_loss(
+      input,
+      target,
+      options.p(),
+      options.margin(),
+      options.weight(),
+      options.reduction());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor cosine_embedding_loss(
+    const Tensor& input1,
+    const Tensor& input2,
+    const Tensor& target,
+    double margin,
+    CosineEmbeddingLossFuncOptions::reduction_t reduction) {
+  return torch::cosine_embedding_loss(
+      input1, input2, target, margin, enumtype::reduction_get_enum(reduction));
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.cosine_embedding_loss
+/// about the exact behavior of this functional.
+///
+/// See the documentation for
+/// `torch::nn::functional::CosineEmbeddingLossFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::cosine_embedding_loss(input1, input2, target,
+/// F::CosineEmbeddingLossFuncOptions().margin(0.5));
+/// ```
+inline Tensor cosine_embedding_loss(
+    const Tensor& input1,
+    const Tensor& input2,
+    const Tensor& target,
+    const CosineEmbeddingLossFuncOptions& options = {}) {
+  return detail::cosine_embedding_loss(
+      input1, input2, target, options.margin(), options.reduction());
+}
+
+// ============================================================================
+
+inline Tensor _smooth_l1_loss(
+    const Tensor& input,
+    const Tensor& target,
+    double beta = 1.) {
+  auto t = torch::abs(input - target);
+  return torch::where(t < beta, 0.5 * torch::pow(t, 2) / beta, t - 0.5 * beta);
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor smooth_l1_loss(
+    const Tensor& input,
+    const Tensor& target,
+    SmoothL1LossFuncOptions::reduction_t reduction,
+    std::optional beta_opt = std::nullopt) {
+  if (target.sizes() != input.sizes()) {
+    TORCH_WARN(
+        "Using a target size (",
+        target.sizes(),
+        ") that is different to the input size (",
+        input.sizes(),
+        "). ",
+        "This will likely lead to incorrect results due to broadcasting. ",
+        "Please ensure they have the same size.");
+  }
+  double beta = beta_opt.value_or(1.0);
+
+  std::vector expanded_tensors =
+      torch::broadcast_tensors({input, target});
+  return torch::smooth_l1_loss(
+      expanded_tensors[0],
+      expanded_tensors[1],
+      enumtype::reduction_get_enum(reduction),
+      beta);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.smooth_l1_loss
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::SmoothL1LossFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::smooth_l1_loss(input, target, F::SmoothL1LossFuncOptions(torch::kNone));
+/// ```
+inline Tensor smooth_l1_loss(
+    const Tensor& input,
+    const Tensor& target,
+    const SmoothL1LossFuncOptions& options = {}) {
+  return detail::smooth_l1_loss(
+      input, target, options.reduction(), options.beta());
+}
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.smooth_l1_loss
+/// about the exact behavior of this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::smooth_l1_loss(input, target, /*options=*/torch::kNone, /*beta=*/0.5);
+/// ```
+inline Tensor smooth_l1_loss(
+    const Tensor& input,
+    const Tensor& target,
+    const SmoothL1LossFuncOptions& options,
+    double beta) {
+  TORCH_CHECK(
+      options.beta() == std::nullopt,
+      "expected beta not to be provided in 'options', but got ",
+      options.beta().value());
+  return detail::smooth_l1_loss(input, target, options.reduction(), beta);
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor huber_loss(
+    const Tensor& input,
+    const Tensor& target,
+    HuberLossFuncOptions::reduction_t reduction,
+    double delta = 1.) {
+  if (target.sizes() != input.sizes()) {
+    TORCH_WARN(
+        "Using a target size (",
+        target.sizes(),
+        ") that is different to the input size (",
+        input.sizes(),
+        "). ",
+        "This will likely lead to incorrect results due to broadcasting. ",
+        "Please ensure they have the same size.");
+  }
+
+  std::vector expanded_tensors =
+      torch::broadcast_tensors({input, target});
+  return torch::huber_loss(
+      expanded_tensors[0],
+      expanded_tensors[1],
+      enumtype::reduction_get_enum(reduction),
+      delta);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.huber_loss
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::HuberLossFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::huber_loss(input, target,
+/// F::HuberLossFuncOptions().reduction(torch::kNone).delta(0.5));
+/// ```
+inline Tensor huber_loss(
+    const Tensor& input,
+    const Tensor& target,
+    const HuberLossFuncOptions& options = {}) {
+  return detail::huber_loss(
+      input, target, options.reduction(), options.delta());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor multilabel_margin_loss(
+    const Tensor& input,
+    const Tensor& target,
+    MultilabelMarginLossFuncOptions::reduction_t reduction) {
+  return torch::multilabel_margin_loss(
+      input, target, enumtype::reduction_get_enum(reduction));
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.multilabel_margin_loss
+/// about the exact behavior of this functional.
+///
+/// See the documentation for
+/// `torch::nn::functional::MultilabelMarginLossFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::multilabel_margin_loss(input, target,
+/// F::MultilabelMarginLossFuncOptions(torch::kNone));
+/// ```
+inline Tensor multilabel_margin_loss(
+    const Tensor& input,
+    const Tensor& target,
+    const MultilabelMarginLossFuncOptions& options = {}) {
+  return detail::multilabel_margin_loss(input, target, options.reduction());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor soft_margin_loss(
+    const Tensor& input,
+    const Tensor& target,
+    SoftMarginLossFuncOptions::reduction_t reduction) {
+  return torch::soft_margin_loss(
+      input, target, enumtype::reduction_get_enum(reduction));
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.soft_margin_loss
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::SoftMarginLossFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::soft_margin_loss(input, target,
+/// F::SoftMarginLossFuncOptions(torch::kNone));
+/// ```
+inline Tensor soft_margin_loss(
+    const Tensor& input,
+    const Tensor& target,
+    const SoftMarginLossFuncOptions& options = {}) {
+  return detail::soft_margin_loss(input, target, options.reduction());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor multilabel_soft_margin_loss(
+    const Tensor& input,
+    const Tensor& target,
+    const Tensor& weight,
+    MultilabelSoftMarginLossFuncOptions::reduction_t reduction) {
+  auto loss =
+      -(target * torch::log_sigmoid(input) +
+        (1 - target) * torch::log_sigmoid(-input));
+  if (weight.defined()) {
+    loss = loss * weight;
+  }
+
+  auto class_dim = input.dim() - 1;
+  auto C = input.size(class_dim);
+  loss = loss.sum(class_dim) / C; // only return N loss values
+
+  Tensor ret;
+
+  if (std::holds_alternative(reduction)) {
+    ret = loss;
+  } else if (std::holds_alternative(reduction)) {
+    ret = loss.mean();
+  } else if (std::holds_alternative(reduction)) {
+    ret = loss.sum();
+  } else {
+    ret = input;
+    TORCH_INTERNAL_ASSERT(
+        false, enumtype::get_enum_name(reduction), " is not valid");
+  }
+  return ret;
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.multilabel_soft_margin_loss
+/// about the exact behavior of this functional.
+///
+/// See the documentation for
+/// `torch::nn::functional::MultilabelSoftMarginLossFuncOptions` class to learn
+/// what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::multilabel_soft_margin_loss(input, target,
+/// F::MultilabelSoftMarginLossFuncOptions().reduction(torch::kNone).weight(weight));
+/// ```
+inline Tensor multilabel_soft_margin_loss(
+    const Tensor& input,
+    const Tensor& target,
+    const MultilabelSoftMarginLossFuncOptions& options = {}) {
+  return detail::multilabel_soft_margin_loss(
+      input, target, options.weight(), options.reduction());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor triplet_margin_loss(
+    const Tensor& anchor,
+    const Tensor& positive,
+    const Tensor& negative,
+    double margin,
+    double p,
+    double eps,
+    bool swap,
+    TripletMarginLossFuncOptions::reduction_t reduction) {
+  return torch::triplet_margin_loss(
+      anchor,
+      positive,
+      negative,
+      margin,
+      p,
+      eps,
+      swap,
+      enumtype::reduction_get_enum(reduction));
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.triplet_margin_loss
+/// about the exact behavior of this functional.
+///
+/// See the documentation for
+/// `torch::nn::functional::TripletMarginLossFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::triplet_margin_loss(anchor, positive, negative,
+/// F::TripletMarginLossFuncOptions().margin(1.0));
+/// ```
+inline Tensor triplet_margin_loss(
+    const Tensor& anchor,
+    const Tensor& positive,
+    const Tensor& negative,
+    const TripletMarginLossFuncOptions& options = {}) {
+  return detail::triplet_margin_loss(
+      anchor,
+      positive,
+      negative,
+      options.margin(),
+      options.p(),
+      options.eps(),
+      options.swap(),
+      options.reduction());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor triplet_margin_with_distance_loss(
+    const Tensor& anchor,
+    const Tensor& positive,
+    const Tensor& negative,
+    std::optional
+        distance_function,
+    double margin,
+    bool swap,
+    TripletMarginWithDistanceLossFuncOptions::reduction_t reduction) {
+  Tensor dist_pos, dist_neg;
+  if (distance_function.has_value()) {
+    auto distance_function_impl = distance_function.value();
+    dist_pos = distance_function_impl(anchor, positive);
+    dist_neg = distance_function_impl(anchor, negative);
+  } else {
+    dist_pos = pairwise_distance(anchor, positive);
+    dist_neg = pairwise_distance(anchor, negative);
+  }
+
+  if (swap) {
+    Tensor dist_swap;
+    if (distance_function.has_value()) {
+      dist_swap = distance_function.value()(positive, negative);
+    } else {
+      dist_swap = pairwise_distance(positive, negative);
+    }
+    dist_neg = torch::min(dist_neg, dist_swap);
+  }
+
+  auto loss = torch::clamp_min(dist_pos - dist_neg + margin, 0);
+
+  Tensor ret;
+  if (std::holds_alternative(reduction)) {
+    ret = loss;
+  } else if (std::holds_alternative(reduction)) {
+    ret = loss.mean();
+  } else if (std::holds_alternative(reduction)) {
+    ret = loss.sum();
+  } else {
+    ret = anchor;
+    TORCH_INTERNAL_ASSERT(
+        false, enumtype::get_enum_name(reduction), " is not valid");
+  }
+  return ret;
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.triplet_margin_with_distance_loss
+/// about the exact behavior of this functional.
+///
+/// See the documentation for
+/// `torch::nn::functional::TripletMarginWithDistanceLossFuncOptions` class to
+/// learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::triplet_margin_with_distance_loss(anchor, positive, negative,
+/// F::TripletMarginWithDistanceLossFuncOptions().margin(1.0));
+/// ```
+inline Tensor triplet_margin_with_distance_loss(
+    const Tensor& anchor,
+    const Tensor& positive,
+    const Tensor& negative,
+    const TripletMarginWithDistanceLossFuncOptions& options = {}) {
+  return detail::triplet_margin_with_distance_loss(
+      anchor,
+      positive,
+      negative,
+      options.distance_function(),
+      options.margin(),
+      options.swap(),
+      options.reduction());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor ctc_loss(
+    const Tensor& log_probs,
+    const Tensor& targets,
+    const Tensor& input_lengths,
+    const Tensor& target_lengths,
+    int64_t blank,
+    CTCLossFuncOptions::reduction_t reduction,
+    bool zero_infinity) {
+  return torch::ctc_loss(
+      log_probs,
+      targets,
+      input_lengths,
+      target_lengths,
+      blank,
+      enumtype::reduction_get_enum(reduction),
+      zero_infinity);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.ctc_loss
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::CTCLossFuncOptions` class
+/// to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::ctc_loss(log_probs, targets, input_lengths, target_lengths,
+/// F::CTCLossFuncOptions().reduction(torch::kNone));
+/// ```
+inline Tensor ctc_loss(
+    const Tensor& log_probs,
+    const Tensor& targets,
+    const Tensor& input_lengths,
+    const Tensor& target_lengths,
+    const CTCLossFuncOptions& options = {}) {
+  return detail::ctc_loss(
+      log_probs,
+      targets,
+      input_lengths,
+      target_lengths,
+      options.blank(),
+      options.reduction(),
+      options.zero_infinity());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor poisson_nll_loss(
+    const Tensor& input,
+    const Tensor& target,
+    bool log_input,
+    bool full,
+    double eps,
+    PoissonNLLLossFuncOptions::reduction_t reduction) {
+  return torch::poisson_nll_loss(
+      input,
+      target,
+      log_input,
+      full,
+      eps,
+      enumtype::reduction_get_enum(reduction));
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.poisson_nll_loss
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::PoissonNLLLossFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::poisson_nll_loss(input, target,
+/// F::PoissonNLLLossFuncOptions().reduction(torch::kNone));
+/// ```
+inline Tensor poisson_nll_loss(
+    const Tensor& input,
+    const Tensor& target,
+    const PoissonNLLLossFuncOptions& options = {}) {
+  return detail::poisson_nll_loss(
+      input,
+      target,
+      options.log_input(),
+      options.full(),
+      options.eps(),
+      options.reduction());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor margin_ranking_loss(
+    const Tensor& input1,
+    const Tensor& input2,
+    const Tensor& target,
+    double margin,
+    MarginRankingLossFuncOptions::reduction_t reduction) {
+  TORCH_CHECK(
+      input1.dim() == input2.dim() && input1.dim() == target.dim(),
+      "margin_ranking_loss : All input tensors should have same dimension but got sizes: "
+      "input1: ",
+      input1.sizes(),
+      ", input2: ",
+      input2.sizes(),
+      ", target: ",
+      target.sizes());
+  return torch::margin_ranking_loss(
+      input1, input2, target, margin, enumtype::reduction_get_enum(reduction));
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.margin_ranking_loss
+/// about the exact behavior of this functional.
+///
+/// See the documentation for
+/// `torch::nn::functional::MarginRankingLossFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::margin_ranking_loss(input1, input2, target,
+/// F::MarginRankingLossFuncOptions().margin(0.5).reduction(torch::kSum));
+/// ```
+inline Tensor margin_ranking_loss(
+    const Tensor& input1,
+    const Tensor& input2,
+    const Tensor& target,
+    const MarginRankingLossFuncOptions& options = {}) {
+  return detail::margin_ranking_loss(
+      input1, input2, target, options.margin(), options.reduction());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor nll_loss(
+    const Tensor& input,
+    const Tensor& target,
+    const Tensor& weight,
+    int64_t ignore_index,
+    const NLLLossFuncOptions::reduction_t& reduction) {
+  if (input.dim() < 2) {
+    TORCH_CHECK(false, "Expected 2 or more dimensions (got ", input.dim(), ")");
+  }
+
+  if (input.sizes()[0] != target.sizes()[0]) {
+    TORCH_CHECK(
+        false,
+        "Expected input batch_size (",
+        input.sizes()[0],
+        ") to match target batch_size (",
+        target.sizes()[0],
+        ").");
+  }
+
+  return torch::nll_loss_nd(
+      input,
+      target,
+      weight,
+      enumtype::reduction_get_enum(reduction),
+      ignore_index);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.nll_loss
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::NLLLossFuncOptions` class
+/// to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::nll_loss(input, target,
+/// F::NLLLossFuncOptions().ignore_index(-100).reduction(torch::kMean));
+/// ```
+inline Tensor nll_loss(
+    const Tensor& input,
+    const Tensor& target,
+    const NLLLossFuncOptions& options = {}) {
+  return detail::nll_loss(
+      input,
+      target,
+      options.weight(),
+      options.ignore_index(),
+      options.reduction());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor cross_entropy(
+    const Tensor& input,
+    const Tensor& target,
+    const Tensor& weight,
+    int64_t ignore_index,
+    CrossEntropyFuncOptions::reduction_t reduction,
+    double label_smoothing) {
+  return torch::cross_entropy_loss(
+      input,
+      target,
+      weight,
+      enumtype::reduction_get_enum(reduction),
+      ignore_index,
+      label_smoothing);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.cross_entropy
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::CrossEntropyFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::cross_entropy(input, target,
+/// F::CrossEntropyFuncOptions().ignore_index(-100).reduction(torch::kMean));
+/// ```
+inline Tensor cross_entropy(
+    const Tensor& input,
+    const Tensor& target,
+    const CrossEntropyFuncOptions& options = {}) {
+  return detail::cross_entropy(
+      input,
+      target,
+      options.weight(),
+      options.ignore_index(),
+      options.reduction(),
+      options.label_smoothing());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor binary_cross_entropy_with_logits(
+    const Tensor& input,
+    const Tensor& target,
+    const Tensor& weight,
+    BinaryCrossEntropyWithLogitsFuncOptions::reduction_t reduction,
+    const Tensor& pos_weight) {
+  TORCH_CHECK(
+      target.sizes() == input.sizes(),
+      "Target size (",
+      target.sizes(),
+      ") must be the same as input size (",
+      input.sizes(),
+      ")");
+
+  return torch::binary_cross_entropy_with_logits(
+      input,
+      target,
+      weight,
+      pos_weight,
+      enumtype::reduction_get_enum(reduction));
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.binary_cross_entropy_with_logits
+/// about the exact behavior of this functional.
+///
+/// See the documentation for
+/// `torch::nn::functional::BinaryCrossEntropyWithLogitsFuncOptions` class to
+/// learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::binary_cross_entropy_with_logits(input, target,
+/// F::BinaryCrossEntropyWithLogitsFuncOptions().pos_weight(pos_weight).reduction(torch::kSum));
+/// ```
+inline Tensor binary_cross_entropy_with_logits(
+    const Tensor& input,
+    const Tensor& target,
+    const BinaryCrossEntropyWithLogitsFuncOptions& options = {}) {
+  return detail::binary_cross_entropy_with_logits(
+      input,
+      target,
+      options.weight(),
+      options.reduction(),
+      options.pos_weight());
+}
+
+} // namespace functional
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/normalization.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/normalization.h
new file mode 100644
index 0000000000000000000000000000000000000000..965cfcd9ac83fadd41090e1787b02a72ab1a72b4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/normalization.h
@@ -0,0 +1,211 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+namespace functional {
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor normalize(
+    const Tensor& input,
+    double p,
+    int64_t dim,
+    double eps,
+    std::optional out) {
+  if (out == std::nullopt) {
+    auto denom = input.norm(p, dim, true).clamp_min(eps).expand_as(input);
+    return input / denom;
+  } else {
+    auto denom = input.norm(p, dim, true).clamp_min(eps).expand_as(input);
+    return torch::div_out(*out, input, denom);
+  }
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.normalize
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::NormalizeFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::normalize(input, F::NormalizeFuncOptions().p(1).dim(-1));
+/// ```
+inline Tensor normalize(
+    const Tensor& input,
+    NormalizeFuncOptions options = {}) {
+  return detail::normalize(
+      input, options.p(), options.dim(), options.eps(), options.out());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor layer_norm(
+    const Tensor& input,
+    const std::vector& normalized_shape,
+    const Tensor& weight,
+    const Tensor& bias,
+    double eps) {
+  return torch::layer_norm(input, normalized_shape, weight, bias, eps);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.layer_norm
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::LayerNormFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::layer_norm(input, F::LayerNormFuncOptions({2, 2}).eps(2e-5));
+/// ```
+inline Tensor layer_norm(
+    const Tensor& input,
+    const LayerNormFuncOptions& options) {
+  return detail::layer_norm(
+      input,
+      options.normalized_shape(),
+      options.weight(),
+      options.bias(),
+      options.eps());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor local_response_norm(
+    const Tensor& input,
+    int64_t size,
+    double alpha,
+    double beta,
+    double k) {
+  auto dim = input.dim();
+  TORCH_CHECK(
+      dim >= 3,
+      "Expected 3D or higher dimensionality input (got ",
+      dim,
+      " dimensions)");
+  auto div = input.mul(input).unsqueeze(1);
+  if (dim == 3) {
+    div = detail::pad(
+        div,
+        /*pad=*/{0, 0, size / 2, (size - 1) / 2},
+        /*mode=*/torch::kConstant,
+        /*value=*/0);
+    div = detail::avg_pool2d(
+              div,
+              /*kernel_size=*/{size, 1},
+              /*stride=*/1,
+              /*padding=*/0,
+              /*ceil_mode=*/false,
+              /*count_include_pad=*/true,
+              /*divisor_override=*/std::nullopt)
+              .squeeze(1);
+  } else {
+    auto sizes = input.sizes();
+    div = div.view({sizes[0], 1, sizes[1], sizes[2], -1});
+    div = detail::pad(
+        div,
+        /*pad=*/{0, 0, 0, 0, size / 2, (size - 1) / 2},
+        /*mode=*/torch::kConstant,
+        /*value=*/0);
+    div = detail::avg_pool3d(
+              div,
+              /*kernel_size=*/{size, 1, 1},
+              /*stride=*/1,
+              /*padding=*/0,
+              /*ceil_mode=*/false,
+              /*count_include_pad=*/true,
+              /*divisor_override=*/std::nullopt)
+              .squeeze(1);
+    div = div.view(sizes);
+  }
+  div = div.mul(alpha).add(k).pow(beta);
+  return input / div;
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.local_response_norm
+/// about the exact behavior of this functional.
+///
+/// See the documentation for
+/// `torch::nn::functional::LocalResponseNormFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::local_response_norm(x, F::LocalResponseNormFuncOptions(2));
+/// ```
+inline Tensor local_response_norm(
+    const Tensor& input,
+    const LocalResponseNormFuncOptions& options) {
+  return detail::local_response_norm(
+      input, options.size(), options.alpha(), options.beta(), options.k());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor group_norm(
+    const Tensor& input,
+    int64_t num_groups,
+    const Tensor& weight,
+    const Tensor& bias,
+    double eps) {
+  return torch::group_norm(
+      input,
+      num_groups,
+      weight,
+      bias,
+      eps,
+      at::globalContext().userEnabledCuDNN());
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.group_norm
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::GroupNormFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::group_norm(input, F::GroupNormFuncOptions(2).eps(2e-5));
+/// ```
+inline Tensor group_norm(
+    const Tensor& input,
+    const GroupNormFuncOptions& options) {
+  return detail::group_norm(
+      input,
+      options.num_groups(),
+      options.weight(),
+      options.bias(),
+      options.eps());
+}
+
+} // namespace functional
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/padding.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/padding.h
new file mode 100644
index 0000000000000000000000000000000000000000..1bb6f9538290428d5fc748daf2ed07788ad4ea15
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/padding.h
@@ -0,0 +1,58 @@
+#pragma once
+
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+namespace functional {
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor pad(
+    const Tensor& input,
+    IntArrayRef pad,
+    PadFuncOptions::mode_t mode,
+    double value) {
+  const auto mode_enum = [&] {
+    if (std::holds_alternative(mode)) {
+      return at::padding_mode::constant;
+    } else if (std::holds_alternative(mode)) {
+      return at::padding_mode::reflect;
+    } else if (std::holds_alternative(mode)) {
+      return at::padding_mode::replicate;
+    } else if (std::holds_alternative(mode)) {
+      return at::padding_mode::circular;
+    }
+    TORCH_CHECK(false, "Unrecognised padding mode");
+  }();
+
+  std::optional fill_value;
+  if (value != 0.0) {
+    fill_value = value;
+  }
+  return at::_pad_enum(input, pad, static_cast(mode_enum), fill_value);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.pad
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::PadFuncOptions` class to
+/// learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::pad(input, F::PadFuncOptions({1, 2, 2, 1, 1,
+/// 2}).mode(torch::kReplicate));
+/// ```
+inline Tensor pad(const Tensor& input, const PadFuncOptions& options) {
+  return detail::pad(input, options.pad(), options.mode(), options.value());
+}
+
+} // namespace functional
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/pixelshuffle.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/pixelshuffle.h
new file mode 100644
index 0000000000000000000000000000000000000000..a245002428e2d4a0a50011a39f0815cc079794f9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/pixelshuffle.h
@@ -0,0 +1,47 @@
+#pragma once
+
+#include 
+
+namespace torch {
+namespace nn {
+namespace functional {
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor pixel_shuffle(const Tensor& input, int64_t upscale_factor) {
+  return torch::pixel_shuffle(input, upscale_factor);
+}
+
+inline Tensor pixel_unshuffle(const Tensor& input, int64_t downscale_factor) {
+  return torch::pixel_unshuffle(input, downscale_factor);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.pixel_shuffle
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::PixelShuffleFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::pixel_shuffle(x, F::PixelShuffleFuncOptions(2));
+/// ```
+inline Tensor pixel_shuffle(
+    const Tensor& input,
+    const PixelShuffleFuncOptions& options) {
+  return detail::pixel_shuffle(input, options.upscale_factor());
+}
+
+inline Tensor pixel_unshuffle(
+    const Tensor& input,
+    const PixelUnshuffleFuncOptions& options) {
+  return detail::pixel_unshuffle(input, options.downscale_factor());
+}
+
+} // namespace functional
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/pooling.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/pooling.h
new file mode 100644
index 0000000000000000000000000000000000000000..798467c0e0a6815544c89a60a4a9a73eeb8164bf
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/pooling.h
@@ -0,0 +1,1153 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+namespace functional {
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor avg_pool1d(
+    const Tensor& input,
+    ExpandingArray<1> kernel_size,
+    ExpandingArray<1> stride,
+    ExpandingArray<1> padding,
+    bool ceil_mode,
+    bool count_include_pad) {
+  return torch::avg_pool1d(
+      input, kernel_size, stride, padding, ceil_mode, count_include_pad);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.avg_pool1d
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::AvgPool1dFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::avg_pool1d(x, F::AvgPool1dFuncOptions(3).stride(2));
+/// ```
+inline Tensor avg_pool1d(
+    const Tensor& input,
+    const AvgPool1dFuncOptions& options) {
+  return avg_pool1d(
+      input,
+      options.kernel_size(),
+      options.stride(),
+      options.padding(),
+      options.ceil_mode(),
+      options.count_include_pad());
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor avg_pool2d(
+    const Tensor& input,
+    ExpandingArray<2> kernel_size,
+    ExpandingArray<2> stride,
+    ExpandingArray<2> padding,
+    bool ceil_mode,
+    bool count_include_pad,
+    std::optional divisor_override) {
+  return torch::avg_pool2d(
+      input,
+      kernel_size,
+      stride,
+      padding,
+      ceil_mode,
+      count_include_pad,
+      divisor_override);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.avg_pool2d
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::AvgPool2dFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::avg_pool2d(x, F::AvgPool2dFuncOptions(3).stride(2));
+/// ```
+inline Tensor avg_pool2d(
+    const Tensor& input,
+    const AvgPool2dFuncOptions& options) {
+  return detail::avg_pool2d(
+      input,
+      options.kernel_size(),
+      options.stride(),
+      options.padding(),
+      options.ceil_mode(),
+      options.count_include_pad(),
+      options.divisor_override());
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor avg_pool3d(
+    const Tensor& input,
+    ExpandingArray<3> kernel_size,
+    ExpandingArray<3> stride,
+    ExpandingArray<3> padding,
+    bool ceil_mode,
+    bool count_include_pad,
+    std::optional divisor_override) {
+  return torch::avg_pool3d(
+      input,
+      kernel_size,
+      stride,
+      padding,
+      ceil_mode,
+      count_include_pad,
+      divisor_override);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.avg_pool3d
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::AvgPool3dFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::avg_pool3d(x, F::AvgPool3dFuncOptions(3).stride(2));
+/// ```
+inline Tensor avg_pool3d(
+    const Tensor& input,
+    const AvgPool3dFuncOptions& options) {
+  return detail::avg_pool3d(
+      input,
+      options.kernel_size(),
+      options.stride(),
+      options.padding(),
+      options.ceil_mode(),
+      options.count_include_pad(),
+      options.divisor_override());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor max_pool1d(
+    const Tensor& input,
+    ExpandingArray<1> kernel_size,
+    ExpandingArray<1> stride,
+    ExpandingArray<1> padding,
+    ExpandingArray<1> dilation,
+    bool ceil_mode) {
+  return torch::max_pool1d(
+      input, kernel_size, stride, padding, dilation, ceil_mode);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.max_pool1d
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::MaxPool1dFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::max_pool1d(x, F::MaxPool1dFuncOptions(3).stride(2));
+/// ```
+inline Tensor max_pool1d(
+    const Tensor& input,
+    const MaxPool1dFuncOptions& options) {
+  return detail::max_pool1d(
+      input,
+      options.kernel_size(),
+      options.stride(),
+      options.padding(),
+      options.dilation(),
+      options.ceil_mode());
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline std::tuple max_pool1d_with_indices(
+    const Tensor& input,
+    ExpandingArray<1> kernel_size,
+    ExpandingArray<1> stride,
+    ExpandingArray<1> padding,
+    ExpandingArray<1> dilation,
+    bool ceil_mode) {
+  return torch::max_pool1d_with_indices(
+      input, kernel_size, stride, padding, dilation, ceil_mode);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See the documentation for `torch::nn::functional::MaxPool1dFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::max_pool1d_with_indices(x, F::MaxPool1dFuncOptions(3).stride(2));
+/// ```
+inline std::tuple max_pool1d_with_indices(
+    const Tensor& input,
+    const MaxPool1dFuncOptions& options) {
+  return detail::max_pool1d_with_indices(
+      input,
+      options.kernel_size(),
+      options.stride(),
+      options.padding(),
+      options.dilation(),
+      options.ceil_mode());
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor max_pool2d(
+    const Tensor& input,
+    ExpandingArray<2> kernel_size,
+    ExpandingArray<2> stride,
+    ExpandingArray<2> padding,
+    ExpandingArray<2> dilation,
+    bool ceil_mode) {
+  return torch::max_pool2d(
+      input, kernel_size, stride, padding, dilation, ceil_mode);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.max_pool2d
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::MaxPool2dFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::max_pool2d(x, F::MaxPool2dFuncOptions(3).stride(2));
+/// ```
+inline Tensor max_pool2d(
+    const Tensor& input,
+    const MaxPool2dFuncOptions& options) {
+  return detail::max_pool2d(
+      input,
+      options.kernel_size(),
+      options.stride(),
+      options.padding(),
+      options.dilation(),
+      options.ceil_mode());
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline std::tuple max_pool2d_with_indices(
+    const Tensor& input,
+    ExpandingArray<2> kernel_size,
+    ExpandingArray<2> stride,
+    ExpandingArray<2> padding,
+    ExpandingArray<2> dilation,
+    bool ceil_mode) {
+  return torch::max_pool2d_with_indices(
+      input, kernel_size, stride, padding, dilation, ceil_mode);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See the documentation for `torch::nn::functional::MaxPool2dFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::max_pool2d_with_indices(x, F::MaxPool2dFuncOptions(3).stride(2));
+/// ```
+inline std::tuple max_pool2d_with_indices(
+    const Tensor& input,
+    const MaxPool2dFuncOptions& options) {
+  return detail::max_pool2d_with_indices(
+      input,
+      options.kernel_size(),
+      options.stride(),
+      options.padding(),
+      options.dilation(),
+      options.ceil_mode());
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor max_pool3d(
+    const Tensor& input,
+    ExpandingArray<3> kernel_size,
+    ExpandingArray<3> stride,
+    ExpandingArray<3> padding,
+    ExpandingArray<3> dilation,
+    bool ceil_mode) {
+  return torch::max_pool3d(
+      input, kernel_size, stride, padding, dilation, ceil_mode);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.max_pool3d
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::MaxPool3dFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::max_pool3d(x, F::MaxPool3dFuncOptions(3).stride(2));
+/// ```
+inline Tensor max_pool3d(
+    const Tensor& input,
+    const MaxPool3dFuncOptions& options) {
+  return detail::max_pool3d(
+      input,
+      options.kernel_size(),
+      options.stride(),
+      options.padding(),
+      options.dilation(),
+      options.ceil_mode());
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline std::tuple max_pool3d_with_indices(
+    const Tensor& input,
+    ExpandingArray<3> kernel_size,
+    ExpandingArray<3> stride,
+    ExpandingArray<3> padding,
+    ExpandingArray<3> dilation,
+    bool ceil_mode) {
+  return torch::max_pool3d_with_indices(
+      input, kernel_size, stride, padding, dilation, ceil_mode);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See the documentation for `torch::nn::functional::MaxPool3dFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::max_pool3d_with_indices(x, F::MaxPool3dFuncOptions(3).stride(2));
+/// ```
+inline std::tuple max_pool3d_with_indices(
+    const Tensor& input,
+    const MaxPool3dFuncOptions& options) {
+  return detail::max_pool3d_with_indices(
+      input,
+      options.kernel_size(),
+      options.stride(),
+      options.padding(),
+      options.dilation(),
+      options.ceil_mode());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline std::tuple adaptive_max_pool1d_with_indices(
+    const Tensor& input,
+    ExpandingArray<1> output_size) {
+  return torch::adaptive_max_pool1d(input, output_size);
+}
+} // namespace detail
+
+/// See the documentation for
+/// `torch::nn::functional::AdaptiveMaxPool1dFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::adaptive_max_pool1d_with_indices(x, F::AdaptiveMaxPool1dFuncOptions(3));
+/// ```
+inline std::tuple adaptive_max_pool1d_with_indices(
+    const Tensor& input,
+    const AdaptiveMaxPool1dFuncOptions& options) {
+  return detail::adaptive_max_pool1d_with_indices(input, options.output_size());
+}
+
+namespace detail {
+inline Tensor adaptive_max_pool1d(
+    const Tensor& input,
+    ExpandingArray<1> output_size) {
+  return std::get<0>(adaptive_max_pool1d_with_indices(input, output_size));
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.adaptive_max_pool1d
+/// about the exact behavior of this functional.
+///
+/// See the documentation for
+/// `torch::nn::functional::AdaptiveMaxPool1dFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::adaptive_max_pool1d(x, F::AdaptiveMaxPool1dFuncOptions(3));
+/// ```
+inline Tensor adaptive_max_pool1d(
+    const Tensor& input,
+    const AdaptiveMaxPool1dFuncOptions& options) {
+  return detail::adaptive_max_pool1d(input, options.output_size());
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline std::tuple adaptive_max_pool2d_with_indices(
+    const Tensor& input,
+    ExpandingArrayWithOptionalElem<2> output_size) {
+  auto output_size_ =
+      torch::nn::modules::utils::_list_with_default(output_size, input.sizes());
+  return torch::adaptive_max_pool2d(input, output_size_);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See the documentation for
+/// `torch::nn::functional::AdaptiveMaxPool2dFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::adaptive_max_pool2d_with_indices(x, F::AdaptiveMaxPool2dFuncOptions(3));
+/// ```
+inline std::tuple adaptive_max_pool2d_with_indices(
+    const Tensor& input,
+    const AdaptiveMaxPool2dFuncOptions& options) {
+  return detail::adaptive_max_pool2d_with_indices(input, options.output_size());
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor adaptive_max_pool2d(
+    const Tensor& input,
+    ExpandingArrayWithOptionalElem<2> output_size) {
+  return std::get<0>(adaptive_max_pool2d_with_indices(input, output_size));
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.adaptive_max_pool2d
+/// about the exact behavior of this functional.
+///
+/// See the documentation for
+/// `torch::nn::functional::AdaptiveMaxPool2dFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::adaptive_max_pool2d(x, F::AdaptiveMaxPool2dFuncOptions(3));
+/// ```
+inline Tensor adaptive_max_pool2d(
+    const Tensor& input,
+    const AdaptiveMaxPool2dFuncOptions& options) {
+  return detail::adaptive_max_pool2d(input, options.output_size());
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline std::tuple adaptive_max_pool3d_with_indices(
+    const Tensor& input,
+    ExpandingArrayWithOptionalElem<3> output_size) {
+  auto output_size_ =
+      torch::nn::modules::utils::_list_with_default(output_size, input.sizes());
+  return torch::adaptive_max_pool3d(input, output_size_);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See the documentation for
+/// `torch::nn::functional::AdaptiveMaxPool3dFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::adaptive_max_pool3d_with_indices(x, F::AdaptiveMaxPool3dFuncOptions(3));
+/// ```
+inline std::tuple adaptive_max_pool3d_with_indices(
+    const Tensor& input,
+    const AdaptiveMaxPool3dFuncOptions& options) {
+  return detail::adaptive_max_pool3d_with_indices(input, options.output_size());
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor adaptive_max_pool3d(
+    const Tensor& input,
+    ExpandingArrayWithOptionalElem<3> output_size) {
+  return std::get<0>(adaptive_max_pool3d_with_indices(input, output_size));
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.adaptive_max_pool3d
+/// about the exact behavior of this functional.
+///
+/// See the documentation for
+/// `torch::nn::functional::AdaptiveMaxPool3dFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::adaptive_max_pool3d(x, F::AdaptiveMaxPool3dFuncOptions(3));
+/// ```
+inline Tensor adaptive_max_pool3d(
+    const Tensor& input,
+    const AdaptiveMaxPool3dFuncOptions& options) {
+  return detail::adaptive_max_pool3d(input, options.output_size());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor adaptive_avg_pool1d(
+    const Tensor& input,
+    ExpandingArray<1> output_size) {
+  return torch::adaptive_avg_pool1d(input, output_size);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.adaptive_avg_pool1d
+/// about the exact behavior of this functional.
+///
+/// See the documentation for
+/// `torch::nn::functional::AdaptiveAvgPool1dFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::adaptive_avg_pool1d(x, F::AdaptiveAvgPool1dFuncOptions(3));
+/// ```
+inline Tensor adaptive_avg_pool1d(
+    const Tensor& input,
+    const AdaptiveAvgPool1dFuncOptions& options) {
+  return detail::adaptive_avg_pool1d(input, options.output_size());
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor adaptive_avg_pool2d(
+    const Tensor& input,
+    ExpandingArrayWithOptionalElem<2> output_size) {
+  auto output_size_ =
+      torch::nn::modules::utils::_list_with_default(output_size, input.sizes());
+  return torch::adaptive_avg_pool2d(input, output_size_);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.adaptive_avg_pool2d
+/// about the exact behavior of this functional.
+///
+/// See the documentation for
+/// `torch::nn::functional::AdaptiveAvgPool2dFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::adaptive_avg_pool2d(x, F::AdaptiveAvgPool2dFuncOptions(3));
+/// ```
+inline Tensor adaptive_avg_pool2d(
+    const Tensor& input,
+    const AdaptiveAvgPool2dFuncOptions& options) {
+  return detail::adaptive_avg_pool2d(input, options.output_size());
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor adaptive_avg_pool3d(
+    const Tensor& input,
+    ExpandingArrayWithOptionalElem<3> output_size) {
+  auto output_size_ =
+      torch::nn::modules::utils::_list_with_default(output_size, input.sizes());
+  return torch::adaptive_avg_pool3d(input, output_size_);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.adaptive_avg_pool3d
+/// about the exact behavior of this functional.
+///
+/// See the documentation for
+/// `torch::nn::functional::AdaptiveAvgPool3dFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::adaptive_avg_pool3d(x, F::AdaptiveAvgPool3dFuncOptions(3));
+/// ```
+inline Tensor adaptive_avg_pool3d(
+    const Tensor& input,
+    const AdaptiveAvgPool3dFuncOptions& options) {
+  return detail::adaptive_avg_pool3d(input, options.output_size());
+}
+
+// ============================================================================
+
+inline std::vector _unpool_output_size(
+    const Tensor& input,
+    const IntArrayRef& kernel_size,
+    const IntArrayRef& stride,
+    const IntArrayRef& padding,
+    const std::optional>& output_size) {
+  auto input_size = input.sizes();
+  std::vector default_size;
+  for (const auto d : c10::irange(kernel_size.size())) {
+    default_size.push_back(
+        (input_size[input_size.size() - kernel_size.size() + d] - 1) *
+            stride[d] +
+        kernel_size[d] - 2 * padding[d]);
+  }
+  if (!output_size) {
+    return default_size;
+  } else {
+    std::vector output_size_;
+    if (output_size->size() == kernel_size.size() + 2) {
+      output_size_ = IntArrayRef(*output_size).slice(2).vec();
+    }
+    if (output_size_.size() != kernel_size.size()) {
+      TORCH_CHECK(
+          false,
+          "output_size should be a sequence containing ",
+          kernel_size.size(),
+          " or ",
+          kernel_size.size() + 2,
+          " elements, but it has a length of '",
+          output_size_.size(),
+          "'");
+    }
+    for (const auto d : c10::irange(kernel_size.size())) {
+      const auto min_size = default_size[d] - stride[d];
+      const auto max_size = default_size[d] + stride[d];
+      if (!(min_size <= output_size_[d] && output_size_[d] <= max_size)) {
+        TORCH_CHECK(
+            false,
+            "invalid output_size ",
+            output_size_,
+            " (dim ",
+            d,
+            " must be between ",
+            min_size,
+            " and ",
+            max_size,
+            ")");
+      }
+    }
+    return output_size_;
+  }
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor max_unpool1d(
+    const Tensor& input,
+    const Tensor& indices,
+    ExpandingArray<1> kernel_size,
+    ExpandingArray<1> stride,
+    ExpandingArray<1> padding,
+    const std::optional>& output_size) {
+  auto output_size_ =
+      _unpool_output_size(input, kernel_size, stride, padding, output_size);
+  output_size_.push_back(1);
+  return torch::max_unpool2d(
+             input.unsqueeze(-1), indices.unsqueeze(-1), output_size_)
+      .squeeze(-1);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.max_unpool1d
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::MaxUnpool1dFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::max_unpool1d(x, indices,
+/// F::MaxUnpool1dFuncOptions(3).stride(2).padding(1));
+/// ```
+inline Tensor max_unpool1d(
+    const Tensor& input,
+    const Tensor& indices,
+    const MaxUnpool1dFuncOptions& options) {
+  return detail::max_unpool1d(
+      input,
+      indices,
+      options.kernel_size(),
+      options.stride(),
+      options.padding(),
+      options.output_size());
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor max_unpool2d(
+    const Tensor& input,
+    const Tensor& indices,
+    ExpandingArray<2> kernel_size,
+    ExpandingArray<2> stride,
+    ExpandingArray<2> padding,
+    const std::optional>& output_size) {
+  auto output_size_ =
+      _unpool_output_size(input, kernel_size, stride, padding, output_size);
+
+  return torch::max_unpool2d(input, indices, output_size_);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.max_unpool2d
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::MaxUnpool2dFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::max_unpool2d(x, indices,
+/// F::MaxUnpool2dFuncOptions(3).stride(2).padding(1));
+/// ```
+inline Tensor max_unpool2d(
+    const Tensor& input,
+    const Tensor& indices,
+    const MaxUnpool2dFuncOptions& options) {
+  return detail::max_unpool2d(
+      input,
+      indices,
+      options.kernel_size(),
+      options.stride(),
+      options.padding(),
+      options.output_size());
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor max_unpool3d(
+    const Tensor& input,
+    const Tensor& indices,
+    ExpandingArray<3> kernel_size,
+    ExpandingArray<3> stride,
+    ExpandingArray<3> padding,
+    const std::optional>& output_size) {
+  auto output_size_ =
+      _unpool_output_size(input, kernel_size, stride, padding, output_size);
+
+  return torch::max_unpool3d(input, indices, output_size_, stride, padding);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.max_unpool3d
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::MaxUnpool3dFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::max_unpool3d(x, indices, F::MaxUnpool3dFuncOptions(3));
+/// ```
+inline Tensor max_unpool3d(
+    const Tensor& input,
+    const Tensor& indices,
+    const MaxUnpool3dFuncOptions& options) {
+  return detail::max_unpool3d(
+      input,
+      indices,
+      options.kernel_size(),
+      options.stride(),
+      options.padding(),
+      options.output_size());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline std::tuple fractional_max_pool2d_with_indices(
+    const Tensor& input,
+    const ExpandingArray<2>& kernel_size,
+    const std::optional>& output_size,
+    const std::optional>& output_ratio,
+    const Tensor& _random_samples) {
+  if (output_size == std::nullopt && output_ratio == std::nullopt) {
+    TORCH_CHECK(
+        false,
+        "fractional_max_pool2d requires specifying either ",
+        "an output_size or an output_ratio");
+  }
+  std::optional> output_size_ = output_size;
+  if (output_size_ == std::nullopt) {
+    TORCH_INTERNAL_ASSERT(output_ratio != std::nullopt);
+    output_size_ = {
+        (int64_t)(static_cast(input.size(-2)) *
+                  (*output_ratio.value())[0]),
+        (int64_t)(static_cast(input.size(-1)) *
+                  (*output_ratio.value())[1])};
+  }
+
+  Tensor _random_samples_ = _random_samples;
+  if (!_random_samples_.defined()) {
+    auto n_batch = input.dim() == 3 ? 1 : input.size(0);
+    _random_samples_ = torch::rand(
+        {n_batch, input.size(-3), 2},
+        torch::TensorOptions().dtype(input.dtype()).device(input.device()));
+  }
+  return torch::fractional_max_pool2d(
+      input, kernel_size, *output_size_, _random_samples_);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See the documentation for
+/// `torch::nn::functional::FractionalMaxPool2dFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::fractional_max_pool2d_with_indices(x,
+/// F::FractionalMaxPool2dFuncOptions(3).output_size(2));
+/// ```
+inline std::tuple fractional_max_pool2d_with_indices(
+    const Tensor& input,
+    const FractionalMaxPool2dFuncOptions& options) {
+  return detail::fractional_max_pool2d_with_indices(
+      input,
+      options.kernel_size(),
+      options.output_size(),
+      options.output_ratio(),
+      options._random_samples());
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor fractional_max_pool2d(
+    const Tensor& input,
+    ExpandingArray<2> kernel_size,
+    std::optional> output_size,
+    std::optional> output_ratio,
+    const Tensor& _random_samples) {
+  return std::get<0>(fractional_max_pool2d_with_indices(
+      input, kernel_size, output_size, output_ratio, _random_samples));
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See the documentation for
+/// `torch::nn::functional::FractionalMaxPool2dFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::fractional_max_pool2d(x,
+/// F::FractionalMaxPool2dFuncOptions(3).output_size(2));
+/// ```
+inline Tensor fractional_max_pool2d(
+    const Tensor& input,
+    const FractionalMaxPool2dFuncOptions& options) {
+  return detail::fractional_max_pool2d(
+      input,
+      options.kernel_size(),
+      options.output_size(),
+      options.output_ratio(),
+      options._random_samples());
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline std::tuple fractional_max_pool3d_with_indices(
+    const Tensor& input,
+    const ExpandingArray<3>& kernel_size,
+    const std::optional>& output_size,
+    const std::optional>& output_ratio,
+    const Tensor& _random_samples) {
+  if (output_size == std::nullopt && output_ratio == std::nullopt) {
+    TORCH_CHECK(
+        false,
+        "fractional_max_pool3d requires specifying either ",
+        "an output_size or an output_ratio");
+  }
+
+  std::optional> output_size_ = output_size;
+  if (output_size_ == std::nullopt) {
+    TORCH_INTERNAL_ASSERT(output_ratio != std::nullopt);
+    output_size_ = {
+        (int64_t)(static_cast(input.size(-3)) *
+                  (*output_ratio.value())[0]),
+        (int64_t)(static_cast(input.size(-2)) *
+                  (*output_ratio.value())[1]),
+        (int64_t)(static_cast(input.size(-1)) *
+                  (*output_ratio.value())[2])};
+  }
+
+  Tensor _random_samples_ = _random_samples;
+  if (!_random_samples_.defined()) {
+    auto n_batch = input.dim() == 4 ? 1 : input.size(0);
+    _random_samples_ = torch::rand(
+        {n_batch, input.size(-4), 3},
+        torch::TensorOptions().dtype(input.dtype()).device(input.device()));
+  }
+  return torch::fractional_max_pool3d(
+      input, kernel_size, *output_size_, _random_samples_);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See the documentation for
+/// `torch::nn::functional::FractionalMaxPool3dFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::fractional_max_pool3d_with_indices(x,
+/// F::FractionalMaxPool3dFuncOptions(3).output_size(2));
+/// ```
+inline std::tuple fractional_max_pool3d_with_indices(
+    const Tensor& input,
+    const FractionalMaxPool3dFuncOptions& options) {
+  return detail::fractional_max_pool3d_with_indices(
+      input,
+      options.kernel_size(),
+      options.output_size(),
+      options.output_ratio(),
+      options._random_samples());
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor fractional_max_pool3d(
+    const Tensor& input,
+    ExpandingArray<3> kernel_size,
+    std::optional> output_size,
+    std::optional> output_ratio,
+    const Tensor& _random_samples) {
+  return std::get<0>(fractional_max_pool3d_with_indices(
+      input, kernel_size, output_size, output_ratio, _random_samples));
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See the documentation for
+/// `torch::nn::functional::FractionalMaxPool3dFuncOptions` class to learn what
+/// optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::fractional_max_pool3d(x,
+/// F::FractionalMaxPool3dFuncOptions(3).output_size(2));
+/// ```
+inline Tensor fractional_max_pool3d(
+    const Tensor& input,
+    const FractionalMaxPool3dFuncOptions& options) {
+  return detail::fractional_max_pool3d(
+      input,
+      options.kernel_size(),
+      options.output_size(),
+      options.output_ratio(),
+      options._random_samples());
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor lp_pool1d(
+    const Tensor& input,
+    double norm_type,
+    ExpandingArray<1> kernel_size,
+    ExpandingArray<1> stride,
+    bool ceil_mode) {
+  Tensor out = detail::avg_pool1d(
+      input.pow(norm_type),
+      kernel_size,
+      stride,
+      /*padding=*/0,
+      ceil_mode,
+      /*count_include_pad=*/true);
+
+  return (torch::sign(out) * relu(torch::abs(out)))
+      .mul((*kernel_size)[0])
+      .pow(1. / norm_type);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.lp_pool1d
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::LPPool1dFuncOptions` class
+/// to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::lp_pool1d(x, F::LPPool1dFuncOptions(2, 3).stride(2));
+/// ```
+inline Tensor lp_pool1d(
+    const Tensor& input,
+    const LPPool1dFuncOptions& options) {
+  return detail::lp_pool1d(
+      input,
+      options.norm_type(),
+      options.kernel_size(),
+      options.stride(),
+      options.ceil_mode());
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor lp_pool2d(
+    const Tensor& input,
+    double norm_type,
+    ExpandingArray<2> kernel_size,
+    ExpandingArray<2> stride,
+    bool ceil_mode) {
+  int kw = (*kernel_size)[0];
+  int kh = (*kernel_size)[1];
+  Tensor out = detail::avg_pool2d(
+      input.pow(norm_type),
+      kernel_size,
+      stride,
+      /*padding=*/0,
+      ceil_mode,
+      /*count_include_pad=*/true,
+      /*divisor_override=*/std::nullopt);
+
+  return (torch::sign(out) * relu(torch::abs(out)))
+      .mul(kw * kh)
+      .pow(1. / norm_type);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.lp_pool2d
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::LPPool2dFuncOptions` class
+/// to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::lp_pool2d(x, F::LPPool2dFuncOptions(2, {2, 3}).stride(2));
+/// ```
+inline Tensor lp_pool2d(
+    const Tensor& input,
+    const LPPool2dFuncOptions& options) {
+  return detail::lp_pool2d(
+      input,
+      options.norm_type(),
+      options.kernel_size(),
+      options.stride(),
+      options.ceil_mode());
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor lp_pool3d(
+    const Tensor& input,
+    double norm_type,
+    ExpandingArray<3> kernel_size,
+    ExpandingArray<3> stride,
+    bool ceil_mode) {
+  int kd = (*kernel_size)[0];
+  int kw = (*kernel_size)[1];
+  int kh = (*kernel_size)[2];
+  Tensor out = detail::avg_pool3d(
+      input.pow(norm_type),
+      kernel_size,
+      stride,
+      /*padding=*/0,
+      ceil_mode,
+      /*count_include_pad=*/true,
+      /*divisor_override=*/std::nullopt);
+
+  return (torch::sign(out) * relu(torch::abs(out)))
+      .mul(kd * kw * kh)
+      .pow(1. / norm_type);
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.lp_pool3d
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::LPPool3dFuncOptions` class
+/// to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::lp_pool3d(x, F::LPPool3dFuncOptions(3, {3, 3, 5}).stride(3));
+/// ```
+inline Tensor lp_pool3d(
+    const Tensor& input,
+    const LPPool3dFuncOptions& options) {
+  return detail::lp_pool3d(
+      input,
+      options.norm_type(),
+      options.kernel_size(),
+      options.stride(),
+      options.ceil_mode());
+}
+
+} // namespace functional
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/upsampling.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/upsampling.h
new file mode 100644
index 0000000000000000000000000000000000000000..75707ef091a783d79ea777fb3b105760832f682e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/upsampling.h
@@ -0,0 +1,289 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+namespace functional {
+
+inline std::vector _interp_output_size(
+    int64_t dim,
+    std::tuple<
+        Tensor,
+        std::optional>,
+        std::optional>,
+        std::optional> closed_over_args) {
+  auto [input, size, scale_factor, recompute_scale_factor] = closed_over_args;
+  if (size == std::nullopt && scale_factor == std::nullopt) {
+    TORCH_CHECK(false, "either size or scale_factor should be defined");
+  }
+  if (size != std::nullopt && scale_factor != std::nullopt) {
+    TORCH_CHECK(false, "only one of size or scale_factor should be defined");
+  }
+  if (scale_factor != std::nullopt) {
+    if (static_cast(scale_factor.value().size()) != dim) {
+      TORCH_CHECK(
+          false,
+          "scale_factor shape must match input shape. ",
+          "Input is ",
+          dim,
+          "D, scale_factor size is ",
+          torch::ArrayRef(*scale_factor));
+    }
+  }
+  if (size != std::nullopt) {
+    return *size;
+  }
+
+  TORCH_INTERNAL_ASSERT(scale_factor != std::nullopt);
+  auto scale_factors = *scale_factor;
+
+  if (recompute_scale_factor == std::nullopt) {
+    // only warn when the scales have floating values since
+    // the result for ints is the same with/without recompute_scale_factor
+    bool is_float_scale_factor = false;
+    for (double scale : scale_factors) {
+      is_float_scale_factor = floor(scale) != scale;
+      if (is_float_scale_factor) {
+        break;
+      }
+    }
+    if (is_float_scale_factor) {
+      TORCH_WARN(
+          "The default behavior for interpolate/upsample with float scale_factor changed "
+          "in 1.6.0 to align with other frameworks/libraries, and uses scale_factor directly, "
+          "instead of relying on the computed output size. "
+          "If you wish to keep the old behavior, please set recompute_scale_factor=True. "
+          "See the documentation of nn.Upsample for details. ");
+    }
+  }
+
+  std::vector ret;
+  for (const auto i : c10::irange(dim)) {
+    ret.emplace_back(static_cast(
+        floor(static_cast(input.size(i + 2)) * scale_factors[i])));
+  }
+  return ret;
+}
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor interpolate(
+    const Tensor& input,
+    const std::optional>& size,
+    const std::optional>& scale_factor,
+    InterpolateFuncOptions::mode_t mode,
+    std::optional align_corners,
+    std::optional recompute_scale_factor,
+    bool antialias) {
+  if (std::holds_alternative(mode) ||
+      std::get_if(&mode)) {
+    if (align_corners != std::nullopt) {
+      TORCH_CHECK(
+          false,
+          "align_corners option can only be set with the "
+          "interpolating modes: linear | bilinear | bicubic | trilinear");
+    }
+  } else {
+    if (align_corners == std::nullopt) {
+      TORCH_WARN(
+          "Default upsampling behavior when mode=",
+          enumtype::get_enum_name(mode),
+          " is changed "
+          "to align_corners=False since 0.4.0. Please specify "
+          "align_corners=True if the old behavior is desired. "
+          "See the documentation of nn.Upsample for details.");
+      align_corners = false;
+    }
+  }
+
+  TORCH_CHECK(
+      input.dim() >= 3 && input.dim() <= 5,
+      "Input Error: Only 3D, 4D and 5D input Tensors supported "
+      "(got ",
+      input.dim(),
+      "D) for the modes: nearest | linear | bilinear | bicubic | trilinear "
+      "(got ",
+      enumtype::get_enum_name(mode),
+      ")");
+
+  auto scale_factor_len = input.dim() - 2;
+  std::vector> scale_factor_list(
+      scale_factor_len, std::nullopt);
+  if (scale_factor != std::nullopt && !recompute_scale_factor.value_or(false)) {
+    auto _scale_factor_repeated = *scale_factor;
+    scale_factor_list = {};
+    for (const auto& elem : _scale_factor_repeated) {
+      scale_factor_list.emplace_back(elem);
+    }
+  }
+
+  if (antialias &&
+      !(input.dim() == 4 &&
+        (std::get_if(&mode) ||
+         std::get_if(&mode)))) {
+    TORCH_CHECK(
+        false,
+        "Anti-alias option is only supported for bilinear and bicubic modes");
+  }
+
+  auto closed_over_args =
+      std::make_tuple(input, size, scale_factor, recompute_scale_factor);
+  if (input.dim() == 3 && std::get_if(&mode)) {
+    return torch::upsample_nearest1d(
+        input,
+        _interp_output_size(1, std::move(closed_over_args)),
+        scale_factor_list.at(0));
+  } else if (input.dim() == 4 && std::get_if(&mode)) {
+    return torch::upsample_nearest2d(
+        input,
+        _interp_output_size(2, std::move(closed_over_args)),
+        scale_factor_list.at(0),
+        scale_factor_list.at(1));
+  } else if (input.dim() == 5 && std::get_if(&mode)) {
+    return torch::upsample_nearest3d(
+        input,
+        _interp_output_size(3, std::move(closed_over_args)),
+        scale_factor_list.at(0),
+        scale_factor_list.at(1),
+        scale_factor_list.at(2));
+  } else if (input.dim() == 3 && std::get_if(&mode)) {
+    return torch::_upsample_nearest_exact1d(
+        input,
+        _interp_output_size(1, std::move(closed_over_args)),
+        scale_factor_list.at(0));
+  } else if (input.dim() == 4 && std::get_if(&mode)) {
+    return torch::_upsample_nearest_exact2d(
+        input,
+        _interp_output_size(2, std::move(closed_over_args)),
+        scale_factor_list.at(0),
+        scale_factor_list.at(1));
+  } else if (input.dim() == 5 && std::get_if(&mode)) {
+    return torch::_upsample_nearest_exact3d(
+        input,
+        _interp_output_size(3, std::move(closed_over_args)),
+        scale_factor_list.at(0),
+        scale_factor_list.at(1),
+        scale_factor_list.at(2));
+  } else if (input.dim() == 3 && std::get_if(&mode)) {
+    return detail::adaptive_avg_pool1d(
+        input, _interp_output_size(1, std::move(closed_over_args)));
+  } else if (input.dim() == 4 && std::get_if(&mode)) {
+    return detail::adaptive_avg_pool2d(
+        input, _interp_output_size(2, std::move(closed_over_args)));
+  } else if (input.dim() == 5 && std::get_if(&mode)) {
+    return detail::adaptive_avg_pool3d(
+        input, _interp_output_size(3, std::move(closed_over_args)));
+  } else if (input.dim() == 3 && std::get_if(&mode)) {
+    TORCH_CHECK(
+        align_corners != std::nullopt, "align_corners should be specified.");
+    return torch::upsample_linear1d(
+        input,
+        _interp_output_size(1, std::move(closed_over_args)),
+        *align_corners,
+        scale_factor_list.at(0));
+  } else if (input.dim() == 3 && std::get_if(&mode)) {
+    TORCH_CHECK(false, "Got 3D input, but bilinear mode needs 4D input");
+  } else if (input.dim() == 3 && std::get_if(&mode)) {
+    TORCH_CHECK(false, "Got 3D input, but trilinear mode needs 5D input");
+  } else if (input.dim() == 4 && std::get_if(&mode)) {
+    TORCH_CHECK(false, "Got 4D input, but linear mode needs 3D input");
+  } else if (input.dim() == 4 && std::get_if(&mode)) {
+    TORCH_CHECK(
+        align_corners != std::nullopt, "align_corners should be specified.");
+    if (antialias) {
+      return torch::_upsample_bilinear2d_aa(
+          input,
+          _interp_output_size(2, std::move(closed_over_args)),
+          *align_corners,
+          scale_factor_list.at(0),
+          scale_factor_list.at(1));
+    }
+    return torch::upsample_bilinear2d(
+        input,
+        _interp_output_size(2, std::move(closed_over_args)),
+        *align_corners,
+        scale_factor_list.at(0),
+        scale_factor_list.at(1));
+  } else if (input.dim() == 4 && std::get_if(&mode)) {
+    TORCH_CHECK(false, "Got 4D input, but trilinear mode needs 5D input");
+  } else if (input.dim() == 5 && std::get_if(&mode)) {
+    TORCH_CHECK(false, "Got 5D input, but linear mode needs 3D input");
+  } else if (input.dim() == 5 && std::get_if(&mode)) {
+    TORCH_CHECK(false, "Got 5D input, but bilinear mode needs 4D input");
+  } else if (input.dim() == 5 && std::get_if(&mode)) {
+    TORCH_CHECK(
+        align_corners != std::nullopt, "align_corners should be specified.");
+    return torch::upsample_trilinear3d(
+        input,
+        _interp_output_size(3, std::move(closed_over_args)),
+        *align_corners,
+        scale_factor_list.at(0),
+        scale_factor_list.at(1),
+        scale_factor_list.at(2));
+  } else if (input.dim() == 4 && std::get_if(&mode)) {
+    TORCH_CHECK(
+        align_corners != std::nullopt, "align_corners should be specified.");
+    if (antialias) {
+      return torch::_upsample_bicubic2d_aa(
+          input,
+          _interp_output_size(2, std::move(closed_over_args)),
+          *align_corners,
+          scale_factor_list.at(0),
+          scale_factor_list.at(1));
+    }
+    return torch::upsample_bicubic2d(
+        input,
+        _interp_output_size(2, std::move(closed_over_args)),
+        *align_corners,
+        scale_factor_list.at(0),
+        scale_factor_list.at(1));
+  } else {
+    TORCH_CHECK(
+        false,
+        "Input Error: Only 3D, 4D and 5D input Tensors supported "
+        "(got ",
+        input.dim(),
+        "D) for the modes: nearest | linear | bilinear | bicubic | trilinear "
+        "(got ",
+        enumtype::get_enum_name(mode),
+        ")");
+  }
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.interpolate
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::InterpolateFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::interpolate(input,
+/// F::InterpolateFuncOptions().size({4}).mode(torch::kNearest));
+/// ```
+inline Tensor interpolate(
+    const Tensor& input,
+    const InterpolateFuncOptions& options = {}) {
+  return detail::interpolate(
+      input,
+      options.size(),
+      options.scale_factor(),
+      options.mode(),
+      options.align_corners(),
+      options.recompute_scale_factor(),
+      options.antialias());
+}
+
+} // namespace functional
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/vision.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/vision.h
new file mode 100644
index 0000000000000000000000000000000000000000..a6c53e0c0a9adbf6ef2bd9f55aab66d3999239de
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional/vision.h
@@ -0,0 +1,124 @@
+#pragma once
+
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+namespace functional {
+
+inline Tensor affine_grid(
+    const Tensor& theta,
+    const IntArrayRef& size,
+    bool align_corners = false) {
+  // enforce floating point dtype on theta
+  TORCH_CHECK(
+      theta.is_floating_point(),
+      "Expected theta to have floating point type, but got ",
+      theta.dtype());
+
+  // check that shapes and sizes match
+  if (size.size() == 4) {
+    TORCH_CHECK(
+        theta.dim() == 3 && theta.size(-2) == 2 && theta.size(-1) == 3,
+        "Expected a batch of 2D affine matrices of shape Nx2x3 for size ",
+        size,
+        ". Got ",
+        theta.sizes(),
+        ".");
+  } else if (size.size() == 5) {
+    TORCH_CHECK(
+        theta.dim() == 3 && theta.size(-2) == 3 && theta.size(-1) == 4,
+        "Expected a batch of 3D affine matrices of shape Nx3x4 for size ",
+        size,
+        ". Got ",
+        theta.sizes(),
+        ".");
+  } else {
+    TORCH_CHECK(
+        false,
+        "affine_grid only supports 4D and 5D sizes, ",
+        "for 2D and 3D affine transforms, respectively. ",
+        "Got size ",
+        size);
+  }
+
+  if (*std::min_element(size.begin(), size.end()) <= 0) {
+    TORCH_CHECK(false, "Expected non-zero, positive output size. Got ", size);
+  }
+
+  return torch::affine_grid_generator(theta, size, align_corners);
+}
+
+// ============================================================================
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace detail {
+inline Tensor grid_sample(
+    const Tensor& input,
+    const Tensor& grid,
+    GridSampleFuncOptions::mode_t mode,
+    GridSampleFuncOptions::padding_mode_t padding_mode,
+    std::optional align_corners) {
+  // NOLINTNEXTLINE(cppcoreguidelines-init-variables)
+  int64_t mode_enum, padding_mode_enum;
+
+  if (std::holds_alternative(mode)) {
+    mode_enum = 0;
+  } else if (std::holds_alternative(mode)) {
+    mode_enum = 1;
+  } else { /// mode == 'bicubic'
+    mode_enum = 2;
+  }
+
+  if (std::holds_alternative(padding_mode)) {
+    padding_mode_enum = 0;
+  } else if (std::holds_alternative(padding_mode)) {
+    padding_mode_enum = 1;
+  } else { /// padding_mode == 'reflection'
+    padding_mode_enum = 2;
+  }
+
+  if (!align_corners.has_value()) {
+    TORCH_WARN(
+        "Default grid_sample and affine_grid behavior has changed ",
+        "to align_corners=False since 1.3.0. Please specify ",
+        "align_corners=True if the old behavior is desired. ",
+        "See the documentation of grid_sample for details.");
+    align_corners = false;
+  }
+
+  return torch::grid_sampler(
+      input, grid, mode_enum, padding_mode_enum, align_corners.value());
+}
+} // namespace detail
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/// See
+/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.grid_sample
+/// about the exact behavior of this functional.
+///
+/// See the documentation for `torch::nn::functional::GridSampleFuncOptions`
+/// class to learn what optional arguments are supported for this functional.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::grid_sample(input, grid,
+/// F::GridSampleFuncOptions().mode(torch::kBilinear).padding_mode(torch::kZeros).align_corners(true));
+/// ```
+inline Tensor grid_sample(
+    const Tensor& input,
+    const Tensor& grid,
+    const GridSampleFuncOptions& options = {}) {
+  return detail::grid_sample(
+      input,
+      grid,
+      options.mode(),
+      options.padding_mode(),
+      options.align_corners());
+}
+
+} // namespace functional
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/init.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/init.h
new file mode 100644
index 0000000000000000000000000000000000000000..d08d785f1dade72ccc4bc28a48c1d8014c257c6c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/init.h
@@ -0,0 +1,124 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+namespace init {
+
+using NonlinearityType = std::variant<
+    enumtype::kLinear,
+    enumtype::kConv1D,
+    enumtype::kConv2D,
+    enumtype::kConv3D,
+    enumtype::kConvTranspose1D,
+    enumtype::kConvTranspose2D,
+    enumtype::kConvTranspose3D,
+    enumtype::kSigmoid,
+    enumtype::kTanh,
+    enumtype::kReLU,
+    enumtype::kLeakyReLU>;
+
+using FanModeType = std::variant;
+
+} // namespace init
+} // namespace nn
+
+namespace nn {
+namespace init {
+
+/// Return the recommended gain value for the given nonlinearity function.
+TORCH_API double calculate_gain(
+    NonlinearityType nonlinearity,
+    double param = 0.01);
+
+/// Fills the given `tensor` with the provided `value` in-place, and returns it.
+/// No gradient will be recorded for this operation.
+TORCH_API Tensor constant_(Tensor tensor, Scalar value);
+
+/// Fills the given `tensor` with the Dirac delta function in-place, and returns
+/// it. No gradient will be recorded for this operation.
+TORCH_API Tensor dirac_(Tensor tensor);
+
+/// Fills the given 2-dimensional `matrix` with an identity matrix.
+/// No gradient will be recorded for this operation.
+TORCH_API Tensor eye_(Tensor matrix);
+
+/// Fills the given 2-dimensional `matrix` with values drawn from a normal
+/// distribution parameterized by `mean` and `std`.
+/// No gradient will be recorded for this operation.
+TORCH_API Tensor normal_(Tensor tensor, double mean = 0, double std = 1);
+
+/// Fills the given `tensor` with ones.
+/// No gradient will be recorded for this operation.
+TORCH_API Tensor ones_(Tensor tensor);
+
+/// Fills the input `Tensor` with a (semi) orthogonal matrix, as described in
+/// "Exact solutions to the nonlinear dynamics of learning in deep linear neural
+/// networks" - Saxe, A. et al. (2013). The input tensor must have at least 2
+/// dimensions, and for tensors with more than 2 dimensions the trailing
+/// dimensions are flattened.
+/// No gradient will be recorded for this operation.
+TORCH_API Tensor orthogonal_(Tensor tensor, double gain = 1.0);
+
+/// Fills the 2D input `Tensor` as a sparse matrix, where the
+/// non-zero elements will be drawn from a centered normal distribution
+/// with the given standard deviation `std`, as described in "Deep learning via
+/// Hessian-free optimization" - Martens, J. (2010). The `sparsity` is a real
+/// value between 0 and 1 that controls the fraction of elements in each column
+/// to be set to zero.
+/// No gradient will be recorded for this operation.
+TORCH_API Tensor sparse_(Tensor tensor, double sparsity, double std = 0.01);
+
+/// Fills the given 2-dimensional `matrix` with values drawn from a uniform
+/// distribution parameterized by `low` and `high`.
+/// No gradient will be recorded for this operation.
+TORCH_API Tensor uniform_(Tensor tensor, double low = 0, double high = 1);
+
+/// Fills the input `Tensor` with values according to the method
+/// described in "Delving deep into rectifiers: Surpassing human-level
+/// performance on ImageNet classification" - He, K. et al. (2015), using a
+/// normal distribution. Also known as He initialization.
+/// No gradient will be recorded for this operation.
+TORCH_API Tensor kaiming_normal_(
+    Tensor tensor,
+    double a = 0,
+    FanModeType mode = torch::kFanIn,
+    NonlinearityType nonlinearity = torch::kLeakyReLU);
+
+/// Fills the input `Tensor` with values according to the method
+/// described in "Delving deep into rectifiers: Surpassing human-level
+/// performance on ImageNet classification" - He, K. et al. (2015), using a
+/// uniform distribution. Also known as He initialization.
+/// No gradient will be recorded for this operation.
+TORCH_API Tensor kaiming_uniform_(
+    Tensor tensor,
+    double a = 0,
+    FanModeType mode = torch::kFanIn,
+    NonlinearityType nonlinearity = torch::kLeakyReLU);
+
+/// Fills the input `Tensor` with values according to the method
+/// described in "Understanding the difficulty of training deep feedforward
+/// neural networks" - Glorot, X. & Bengio, Y. (2010). Values are scaled by the
+/// `gain` parameter. No gradient will be recorded for this operation.
+TORCH_API Tensor xavier_normal_(Tensor tensor, double gain = 1.0);
+
+/// Fills the input `Tensor` with values according to the method
+/// described in "Understanding the difficulty of training deep feedforward
+/// neural networks" - Glorot, X. & Bengio, Y. (2010), using a uniform
+/// distribution. Values are scaled by the `gain` parameter
+/// No gradient will be recorded for this operation.
+TORCH_API Tensor xavier_uniform_(Tensor tensor, double gain = 1.0);
+
+/// Fills the given `tensor` with zeros.
+/// No gradient will be recorded for this operation.
+TORCH_API Tensor zeros_(Tensor tensor);
+
+TORCH_API std::tuple _calculate_fan_in_and_fan_out(
+    const Tensor& tensor);
+
+} // namespace init
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/module.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/module.h
new file mode 100644
index 0000000000000000000000000000000000000000..78ff200c5f5b7db49edd1cf27f51343a0d375d7f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/module.h
@@ -0,0 +1,702 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// The base class for all modules in PyTorch.
+///
+/// \rst
+/// .. note::
+///   The design and implementation of this class is largely based on the Python
+///   API. You may want to consult the python documentation for
+///   :py:class:`pytorch:torch.nn.Module` for further clarification on certain
+///   methods or behavior.
+/// \endrst
+///
+/// A `Module` is an abstraction over the implementation of some function or
+/// algorithm, possibly associated with some persistent data. A `Module` may
+/// contain further `Module`s ("submodules"), each with their own
+/// implementation, persistent data and further submodules. `Module`s can thus
+/// be said to form a recursive tree structure. A `Module` is registered as a
+/// submodule to another `Module` by calling `register_module()`, typically from
+/// within a parent module's constructor.
+///
+/// A distinction is made between three kinds of persistent data that may be
+/// associated with a `Module`:
+///
+/// 1. *Parameters*: tensors that record gradients, typically weights updated
+///    during the backward step (e.g. the `weight` of a `Linear` module),
+/// 2. *Buffers*: tensors that do not record gradients, typically updated during
+///    the forward step, such as running statistics (e.g. `mean` and `variance`
+///    in the `BatchNorm` module),
+/// 3. Any additional state, not necessarily tensors, required for the
+///    implementation or configuration of a `Module`.
+///
+/// The first two kinds of state are special in that they may be registered
+/// with the `Module` system to allow convenient access and batch configuration.
+/// For example, registered parameters in any `Module` may be iterated over via
+/// the `parameters()` accessor. Further, changing the data type of a `Module`'s
+/// registered parameters can be done conveniently via `Module::to()`, e.g.
+/// `module->to(torch::kCUDA)` to move all parameters to GPU memory. Lastly,
+/// registered parameters and buffers are handled specially during a `clone()`
+/// operation, which performs a deepcopy of a cloneable `Module` hierarchy.
+///
+/// Parameters are registered with a `Module` via `register_parameter`. Buffers
+/// are registered separately via `register_buffer`. These methods are part of
+/// the public API of `Module` and are typically invoked from within a
+/// concrete `Module`s constructor.
+class TORCH_API Module : public std::enable_shared_from_this {
+ public:
+  using ModuleApplyFunction = std::function;
+  using ConstModuleApplyFunction = std::function;
+  using NamedModuleApplyFunction =
+      std::function;
+  using ConstNamedModuleApplyFunction =
+      std::function;
+  using ModulePointerApplyFunction =
+      std::function&)>;
+  using NamedModulePointerApplyFunction =
+      std::function&)>;
+
+  /// Tells the base `Module` about the name of the submodule.
+  explicit Module(std::string name);
+
+  /// Constructs the module without immediate knowledge of the submodule's name.
+  /// The name of the submodule is inferred via RTTI (if possible) the first
+  /// time `.name()` is invoked.
+  Module();
+  Module(const Module&) = default;
+  Module& operator=(const Module&) = default;
+  Module(Module&&) noexcept = default;
+  Module& operator=(Module&&) noexcept = default;
+
+  virtual ~Module() = default;
+
+  /// Returns the name of the `Module`.
+  ///
+  /// A `Module` has an associated `name`, which is a string representation of
+  /// the kind of concrete `Module` it represents, such as `"Linear"` for the
+  /// `Linear` module. Under most circumstances, this name is automatically
+  /// inferred via runtime type information (RTTI). In the unusual circumstance
+  /// that you have this feature disabled, you may want to manually name your
+  /// `Module`s by passing the string name to the `Module` base class'
+  /// constructor.
+  const std::string& name() const noexcept;
+
+  /// Performs a recursive deep copy of the module and all its registered
+  /// parameters, buffers and submodules.
+  ///
+  /// Optionally, this method sets the current device
+  /// to the one supplied before cloning. If no device is given, each
+  /// parameter and buffer will be moved to the device of its source.
+  ///
+  /// \rst
+  /// .. attention::
+  ///   Attempting to call the `clone()` method inherited from the base `Module`
+  ///   class (the one documented here) will fail. To inherit an actual
+  ///   implementation of `clone()`, you must subclass `Cloneable`. `Cloneable`
+  ///   is templatized on the concrete module type, and can thus properly copy a
+  ///   `Module`. This method is provided on the base class' API solely for an
+  ///   easier-to-use polymorphic interface.
+  /// \endrst
+  virtual std::shared_ptr clone(
+      const std::optional& device = std::nullopt) const;
+
+  /// Applies the `function` to the `Module` and recursively to every submodule.
+  /// The function must accept a `Module&`.
+  ///
+  /// \rst
+  /// .. code-block:: cpp
+  ///   MyModule module;
+  ///   module->apply([](nn::Module& module) {
+  ///     std::cout << module.name() << std::endl;
+  ///   });
+  /// \endrst
+  void apply(const ModuleApplyFunction& function);
+
+  /// Applies the `function` to the `Module` and recursively to every submodule.
+  /// The function must accept a `const Module&`.
+  ///
+  /// \rst
+  /// .. code-block:: cpp
+  ///   MyModule module;
+  ///   module->apply([](const nn::Module& module) {
+  ///     std::cout << module.name() << std::endl;
+  ///   });
+  /// \endrst
+  void apply(const ConstModuleApplyFunction& function) const;
+
+  /// Applies the `function` to the `Module` and recursively to every submodule.
+  /// The function must accept a `const std::string&` for the key of the module,
+  /// and a `Module&`. The key of the module itself is the empty string. If
+  /// `name_prefix` is given, it is prepended to every key as
+  /// `.` (and just `name_prefix` for the module itself).
+  ///
+  /// \rst
+  /// .. code-block:: cpp
+  ///   MyModule module;
+  ///   module->apply([](const std::string& key, nn::Module& module) {
+  ///     std::cout << key << ": " << module.name() << std::endl;
+  ///   });
+  /// \endrst
+  void apply(
+      const NamedModuleApplyFunction& function,
+      const std::string& name_prefix = std::string());
+
+  /// Applies the `function` to the `Module` and recursively to every submodule.
+  /// The function must accept a `const std::string&` for the key of the module,
+  /// and a `const Module&`. The key of the module itself is the empty string.
+  /// If `name_prefix` is given, it is prepended to every key as
+  /// `.` (and just `name_prefix` for the module itself).
+  ///
+  /// \rst
+  /// .. code-block:: cpp
+  ///   MyModule module;
+  ///   module->apply([](const std::string& key, const nn::Module& module) {
+  ///     std::cout << key << ": " << module.name() << std::endl;
+  ///   });
+  /// \endrst
+  void apply(
+      const ConstNamedModuleApplyFunction& function,
+      const std::string& name_prefix = std::string()) const;
+
+  /// Applies the `function` to the `Module` and recursively to every submodule.
+  /// The function must accept a `const std::shared_ptr&`.
+  ///
+  /// \rst
+  /// .. code-block:: cpp
+  ///   MyModule module;
+  ///   module->apply([](const std::shared_ptr& module) {
+  ///     std::cout << module->name() << std::endl;
+  ///   });
+  /// \endrst
+  void apply(const ModulePointerApplyFunction& function) const;
+
+  /// Applies the `function` to the `Module` and recursively to every submodule.
+  /// The function must accept a `const std::string&` for the key of the module,
+  /// and a `const std::shared_ptr&`. The key of the module itself is
+  /// the empty string. If `name_prefix` is given, it is prepended to every key
+  /// as
+  /// `.` (and just `name_prefix` for the module itself).
+  ///
+  /// \rst
+  /// .. code-block:: cpp
+  ///   MyModule module;
+  ///   module->apply([](const std::string& key,
+  ///                    const std::shared_ptr& module) {
+  ///     std::cout << key << ": " << module->name() << std::endl;
+  ///   });
+  /// \endrst
+  void apply(
+      const NamedModulePointerApplyFunction& function,
+      const std::string& name_prefix = std::string()) const;
+
+  /// Returns the parameters of this `Module` and if `recurse` is true, also
+  /// recursively of every submodule.
+  std::vector parameters(bool recurse = true) const;
+
+  /// Returns an `OrderedDict` with the parameters of this `Module` along with
+  /// their keys, and if `recurse` is true also recursively of every submodule.
+  OrderedDict named_parameters(bool recurse = true) const;
+
+  /// Returns the buffers of this `Module` and if `recurse` is true, also
+  /// recursively of every submodule.
+  std::vector buffers(bool recurse = true) const;
+
+  /// Returns an `OrderedDict` with the buffers of this `Module` along with
+  /// their keys, and if `recurse` is true also recursively of every submodule.
+  OrderedDict named_buffers(bool recurse = true) const;
+
+  /// Returns the submodules of this `Module` (the entire submodule hierarchy)
+  /// and if `include_self` is true, also inserts a `shared_ptr` to this module
+  /// in the first position.
+  ///
+  /// \rst
+  /// .. warning::
+  ///   Only pass `include_self` as `true` if this `Module` is stored in a
+  ///   `shared_ptr`! Otherwise an exception will be thrown. You may still call
+  ///   this method with `include_self` set to false if your `Module` is not
+  ///   stored in a `shared_ptr`.
+  /// \endrst
+  std::vector> modules(bool include_self = true) const;
+
+  /// Returns an `OrderedDict` of the submodules of this `Module` (the entire
+  /// submodule hierarchy) and their keys, and if `include_self` is true, also
+  /// inserts a `shared_ptr` to this module in the first position. If
+  /// `name_prefix` is given, it is prepended to every key as
+  /// `.` (and just `name_prefix` for the module itself).
+  ///
+  /// \rst
+  /// .. warning::
+  ///   Only pass `include_self` as `true` if this `Module` is stored in a
+  ///   `shared_ptr`! Otherwise an exception will be thrown. You may still call
+  ///   this method with `include_self` set to false if your `Module` is not
+  ///   stored in a `shared_ptr`.
+  /// \endrst
+  OrderedDict> named_modules(
+      const std::string& name_prefix = std::string(),
+      bool include_self = true) const;
+
+  /// Returns the direct submodules of this `Module`.
+  std::vector> children() const;
+
+  /// Returns an `OrderedDict` of the direct submodules of this `Module` and
+  /// their keys.
+  OrderedDict> named_children() const;
+
+  /// Enables "training" mode.
+  virtual void train(bool on = true);
+
+  /// Calls train(false) to enable "eval" mode.
+  /// Do not override this method, override `train()` instead.
+  void eval();
+
+  /// True if the module is in training mode.
+  ///
+  /// Every `Module` has a boolean associated with it that determines whether
+  /// the `Module` is currently in *training* mode (set via `.train()`) or in
+  /// *evaluation* (inference) mode (set via `.eval()`). This property is
+  /// exposed via `is_training()`, and may be used by the implementation of a
+  /// concrete module to modify its runtime behavior. See the `BatchNorm` or
+  /// `Dropout` modules for examples of `Module`s that use different code paths
+  /// depending on this property.
+  virtual bool is_training() const noexcept;
+
+  /// Recursively casts all parameters to the given `dtype` and `device`.
+  ///
+  /// If `non_blocking` is true and the source is in pinned memory and
+  /// destination is on the GPU or vice versa, the copy is performed
+  /// asynchronously with respect to the host. Otherwise, the argument has no
+  /// effect.
+  virtual void to(
+      torch::Device device,
+      torch::Dtype dtype,
+      bool non_blocking = false);
+
+  /// Recursively casts all parameters to the given dtype.
+  ///
+  /// If `non_blocking` is true and the source is in pinned memory and
+  /// destination is on the GPU or vice versa, the copy is performed
+  /// asynchronously with respect to the host. Otherwise, the argument has no
+  /// effect.
+  virtual void to(torch::Dtype dtype, bool non_blocking = false);
+
+  /// Recursively moves all parameters to the given device.
+  ///
+  /// If `non_blocking` is true and the source is in pinned memory and
+  /// destination is on the GPU or vice versa, the copy is performed
+  /// asynchronously with respect to the host. Otherwise, the argument has no
+  /// effect.
+  virtual void to(torch::Device device, bool non_blocking = false);
+
+  /// Recursively zeros out the `grad` value of each registered parameter.
+  virtual void zero_grad(bool set_to_none = true);
+
+  /// Attempts to cast this `Module` to the given `ModuleType`.
+  ///
+  /// This method is useful when calling `apply()`.
+  /// \rst
+  /// .. code-block:: cpp
+  ///
+  ///   void initialize_weights(nn::Module& module) {
+  ///     torch::NoGradGuard no_grad;
+  ///     if (auto* linear = module.as()) {
+  ///       linear->weight.normal_(0.0, 0.02);
+  ///     }
+  ///   }
+  ///
+  ///   MyModule module;
+  ///   module->apply(initialize_weights);
+  /// \endrst
+  template 
+  typename ModuleType::ContainedType* as() noexcept;
+
+  /// Attempts to cast this `Module` to the given `ModuleType`.
+  ///
+  /// This method is useful when calling `apply()`.
+  /// \rst
+  /// .. code-block:: cpp
+  ///   void initialize_weights(nn::Module& module) {
+  ///     torch::NoGradGuard no_grad;
+  ///     if (auto* linear = module.as()) {
+  ///       linear->weight.normal_(0.0, 0.02);
+  ///     }
+  ///   }
+  ///
+  ///   MyModule module;
+  ///   module->apply(initialize_weights);
+  /// \endrst
+  template 
+  const typename ModuleType::ContainedType* as() const noexcept;
+
+  /// Attempts to cast this `Module` to the given `ModuleType`.
+  ///
+  /// This method is useful when calling `apply()`.
+  /// \rst
+  /// .. code-block:: cpp
+  ///
+  ///   void initialize_weights(nn::Module& module) {
+  ///     torch::NoGradGuard no_grad;
+  ///     if (auto* linear = module.as()) {
+  ///       linear->weight.normal_(0.0, 0.02);
+  ///     }
+  ///   }
+  ///
+  ///   MyModule module;
+  ///   module.apply(initialize_weights);
+  /// \endrst
+  template <
+      typename ModuleType,
+      typename = torch::detail::disable_if_module_holder_t>
+  ModuleType* as() noexcept;
+
+  /// Attempts to cast this `Module` to the given `ModuleType`.
+  ///
+  /// This method is useful when calling `apply()`.
+  /// \rst
+  /// .. code-block:: cpp
+  ///
+  ///   void initialize_weights(nn::Module& module) {
+  ///     torch::NoGradGuard no_grad;
+  ///     if (auto* linear = module.as()) {
+  ///       linear->weight.normal_(0.0, 0.02);
+  ///     }
+  ///   }
+  ///
+  ///   MyModule module;
+  ///   module.apply(initialize_weights);
+  /// \endrst
+  template <
+      typename ModuleType,
+      typename = torch::detail::disable_if_module_holder_t>
+  const ModuleType* as() const noexcept;
+
+  /// Serializes the `Module` into the given `OutputArchive`.
+  ///
+  /// If the `Module` contains unserializable submodules (e.g.
+  /// `nn::Functional`), those submodules are skipped when serializing.
+  virtual void save(serialize::OutputArchive& archive) const;
+
+  /// Deserializes the `Module` from the given `InputArchive`.
+  ///
+  /// If the `Module` contains unserializable submodules (e.g.
+  /// `nn::Functional`), we don't check the existence of those submodules in the
+  /// `InputArchive` when deserializing.
+  virtual void load(serialize::InputArchive& archive);
+
+  /// Streams a pretty representation of the `Module` into the given `stream`.
+  /// By default, this representation will be the name of the module (taken from
+  /// `name()`), followed by a recursive pretty print of all of the `Module`'s
+  /// submodules.
+  ///
+  /// Override this method to change the pretty print. The input
+  /// `stream` should be returned from the method, to allow easy chaining.
+  virtual void pretty_print(std::ostream& stream) const;
+
+  /// Returns whether the `Module` is serializable.
+  virtual bool is_serializable() const;
+
+  /// Registers a parameter with this `Module`.
+  ///
+  /// A parameter should be any gradient-recording tensor used in the
+  /// implementation of your `Module`. Registering it makes it available to
+  /// methods such as `parameters()`, `clone()` or `to().`
+  ///
+  /// Note that registering an undefined Tensor (e.g.
+  /// `module.register_parameter("param", Tensor())`) is allowed, and is
+  /// equivalent to `module.register_parameter("param", None)` in Python API.
+  ///
+  /// \rst
+  /// .. code-block:: cpp
+  ///
+  ///   MyModule::MyModule() {
+  ///     weight_ = register_parameter("weight", torch::randn({A, B}));
+  ///   }
+  /// \endrst
+  Tensor& register_parameter(
+      std::string name,
+      Tensor tensor,
+      bool requires_grad = true);
+
+  /// Registers a buffer with this `Module`.
+  ///
+  /// A buffer is intended to be state in your module that does not record
+  /// gradients, such as running statistics. Registering it makes it available
+  /// to methods such as `buffers()`, `clone()` or `to().
+  ///
+  /// \rst
+  /// .. code-block:: cpp
+  ///
+  ///   MyModule::MyModule() {
+  ///     mean_ = register_buffer("mean", torch::empty({num_features_}));
+  ///   }
+  /// \endrst
+  Tensor& register_buffer(std::string name, Tensor tensor);
+
+  /// Registers a submodule with this `Module`.
+  ///
+  /// Registering a module makes it available to methods such as `modules()`,
+  /// `clone()` or `to()`.
+  ///
+  /// \rst
+  /// .. code-block:: cpp
+  ///
+  ///   MyModule::MyModule() {
+  ///     submodule_ = register_module("linear", torch::nn::Linear(3, 4));
+  ///   }
+  /// \endrst
+  template 
+  std::shared_ptr register_module(
+      std::string name,
+      std::shared_ptr module);
+
+  /// Registers a submodule with this `Module`.
+  ///
+  /// This method deals with `ModuleHolder`s.
+  ///
+  /// Registering a module makes it available to methods such as `modules()`,
+  /// `clone()` or `to()`.
+  ///
+  /// \rst
+  /// .. code-block:: cpp
+  ///
+  ///   MyModule::MyModule() {
+  ///     submodule_ = register_module("linear", torch::nn::Linear(3, 4));
+  ///   }
+  /// \endrst
+  template 
+  std::shared_ptr register_module(
+      std::string name,
+      ModuleHolder module_holder);
+
+  /// Replaces a registered submodule with this `Module`.
+  ///
+  /// This takes care of the registration, if you used submodule members, you
+  /// should
+  //  assign the submodule as well, i.e. use as
+  ///     module->submodule_ = module->replace_module("linear",
+  ///     torch::nn::Linear(3, 4));
+  /// It only works when a module of the name is already registered.
+  ///
+  /// This is useful for replacing a module after initialization, e.g.
+  /// for finetuning.
+  template 
+  std::shared_ptr replace_module(
+      const std::string& name,
+      std::shared_ptr module);
+
+  /// Replaces a registered submodule with this `Module`.
+  /// This method deals with `ModuleHolder`s.
+  ///
+  /// This takes care of the registration, if you used submodule members, you
+  /// should
+  //  assign the submodule as well, i.e. use as
+  ///     module->submodule_ = module->replace_module("linear", linear_holder);
+  /// It only works when a module of the name is already registered.
+  ///
+  /// This is useful for replacing a module after initialization, e.g.
+  /// for finetuning.
+  template 
+  std::shared_ptr replace_module(
+      const std::string& name,
+      ModuleHolder module_holder);
+
+  /// Unregisters a submodule from this `Module`. If there is no such module
+  /// with `name` an exception is thrown.
+  void unregister_module(const std::string& name);
+
+ protected:
+  /// The following three functions allow a module with default arguments in its
+  /// forward method to be used in a Sequential module.
+  /// You should NEVER override these functions manually. Instead, you should
+  /// use the `FORWARD_HAS_DEFAULT_ARGS` macro.
+  virtual bool _forward_has_default_args() {
+    return false;
+  }
+
+  virtual unsigned int _forward_num_required_args() {
+    TORCH_CHECK(
+        false,
+        "torch::nn::Module subclass that has default arguments in `forward` method ",
+        "must override `_forward_num_required_args` method. Please use ",
+        "`FORWARD_HAS_DEFAULT_ARGS` macro to do so.");
+  }
+
+  virtual std::vector _forward_populate_default_args(
+      std::vector&& arguments) {
+    TORCH_CHECK(
+        false,
+        "torch::nn::Module subclass that has default arguments in `forward` method ",
+        "must override `_forward_populate_default_args` method. Please use ",
+        "`FORWARD_HAS_DEFAULT_ARGS` macro to do so.");
+  }
+
+  /// The registered parameters of this `Module`.
+  /// Inorder to access parameters_ in ParameterDict and ParameterList
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  OrderedDict parameters_;
+
+ private:
+  // Friend classes.
+
+  template 
+  friend class Cloneable;
+
+  template 
+  friend struct AnyModuleHolder;
+
+  /// Pretty prints the given `Module` into the `ostream`.
+  TORCH_API friend std::ostream& operator<<(
+      std::ostream& stream,
+      const nn::Module& module);
+
+  // data parallel using this method to configure gradient edges during the
+  // replicate step.
+  template 
+  friend void replicate_grad_edges(
+      const std::shared_ptr& module,
+      const std::vector>& replicas,
+      const std::vector& devices);
+
+  // Private methods.
+
+  /// Used in the implementation of `Cloneable`.
+  virtual void clone_(Module& other, const std::optional& device);
+
+  /// The implementation of the various `to()` methods.
+  template 
+  void to_impl(Ts&&... ts);
+
+  /// Implements pretty printing the module hierarchy.
+  void pretty_print_recursive(
+      std::ostream& stream,
+      const std::string& indentation) const;
+
+  /// Applies the `function` to every submodule recursively, starting at this
+  /// `Module`'s children (thus not including the module itself).
+  void apply_to_submodules(
+      const NamedModulePointerApplyFunction& function,
+      const std::string& name_prefix = std::string()) const;
+
+  /// Returns a shared_ptr to `this` in a safe (checked) way.
+  std::shared_ptr shared_from_this_checked() const;
+
+  /// The registered buffers of this `Module`.
+  OrderedDict buffers_;
+
+  /// The registered (direct) submodules of this `Module`.
+  OrderedDict> children_;
+
+  /// The module's name (e.g. "LSTM").
+  mutable std::optional name_;
+
+  /// Whether the module is in training mode.
+  bool is_training_{true};
+};
+
+/// Serialize a `Module` pointer into an `OutputArchive`.
+TORCH_API serialize::OutputArchive& operator<<(
+    serialize::OutputArchive& archive,
+    const std::shared_ptr& module);
+
+/// Deserializes a `Module` from an `InputArchive`.
+TORCH_API serialize::InputArchive& operator>>(
+    serialize::InputArchive& archive,
+    const std::shared_ptr& module);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ nn::Module ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+template 
+typename ModuleType::ContainedType* Module::as() noexcept {
+  // Use the contained type of the `ModuleHolder`, e.g. `LinearImpl` for
+  // `Linear`, since `LinearImpl` inherits `nn::Module`.
+  return as();
+}
+
+template 
+const typename ModuleType::ContainedType* Module::as() const noexcept {
+  // Use the contained type of the `ModuleHolder`, e.g. `LinearImpl` for
+  // `Linear`, since `LinearImpl` inherits `nn::Module`.
+  return as();
+}
+
+template 
+ModuleType* Module::as() noexcept {
+  return dynamic_cast(this);
+}
+
+template 
+const ModuleType* Module::as() const noexcept {
+  return dynamic_cast(this);
+}
+
+template 
+std::shared_ptr Module::register_module(
+    std::string name,
+    std::shared_ptr module) {
+  TORCH_CHECK(!name.empty(), "Submodule name must not be empty");
+  TORCH_CHECK(
+      name.find('.') == std::string::npos,
+      "Submodule name must not contain a dot (got '",
+      name,
+      "')");
+  auto& base_module = children_.insert(std::move(name), std::move(module));
+  return std::dynamic_pointer_cast(base_module);
+}
+
+template 
+std::shared_ptr Module::register_module(
+    std::string name,
+    ModuleHolder module_holder) {
+  return register_module(std::move(name), module_holder.ptr());
+}
+
+template 
+std::shared_ptr Module::replace_module(
+    const std::string& name,
+    std::shared_ptr module) {
+  auto& base_module = (children_[name] = std::move(module));
+  return std::dynamic_pointer_cast(base_module);
+}
+
+template 
+std::shared_ptr Module::replace_module(
+    const std::string& name,
+    ModuleHolder module_holder) {
+  return replace_module(name, module_holder.ptr());
+}
+
+template 
+void Module::to_impl(Ts&&... ts) {
+  // First call `to()` on every child module.
+  for (auto& child : children_) {
+    child.value()->to(ts...);
+  }
+  // Then move every parameter to the new dtype/device.
+  for (auto& parameter : named_parameters(/*recurse=*/false)) {
+    parameter->set_data(autograd::Variable(*parameter).to(ts...));
+  }
+  // Then move every buffer to the new dtype/device.
+  for (auto& buffer : named_buffers(/*recurse=*/false)) {
+    buffer->set_data(autograd::Variable(*buffer).to(ts...));
+  }
+}
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules.h
new file mode 100644
index 0000000000000000000000000000000000000000..e037d52a8535490ff5ecb17e578df5b4101ee9a3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules.h
@@ -0,0 +1,36 @@
+#pragma once
+
+// Common
+#include 
+
+// Containers
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+// Layers
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/_functions.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/_functions.h
new file mode 100644
index 0000000000000000000000000000000000000000..5bf1ce2dcb28537a0f37939c686450292a92c930
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/_functions.h
@@ -0,0 +1,26 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+namespace functions {
+
+class CrossMapLRN2d : public torch::autograd::Function {
+ public:
+  static torch::autograd::Variable forward(
+      torch::autograd::AutogradContext* ctx,
+      const torch::autograd::Variable& input,
+      const CrossMapLRN2dOptions& options);
+
+  static torch::autograd::variable_list backward(
+      torch::autograd::AutogradContext* ctx,
+      torch::autograd::variable_list grad_output);
+};
+
+} // namespace functions
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/activation.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/activation.h
new file mode 100644
index 0000000000000000000000000000000000000000..6946c474f0d90be3ab977ab7977ced29e9c5efca
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/activation.h
@@ -0,0 +1,875 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+namespace torch {
+namespace nn {
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ELU ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies elu over a given input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.ELU to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::ELUOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// ELU model(ELUOptions().alpha(42.42).inplace(true));
+/// ```
+class TORCH_API ELUImpl : public torch::nn::Cloneable {
+ public:
+  explicit ELUImpl(const ELUOptions& options_ = {});
+
+  Tensor forward(Tensor input);
+
+  void reset() override;
+
+  /// Pretty prints the `ELU` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// The options with which this `Module` was constructed.
+  ELUOptions options;
+};
+
+/// A `ModuleHolder` subclass for `ELUImpl`.
+/// See the documentation for `ELUImpl` class to learn what methods it
+/// provides, and examples of how to use `ELU` with `torch::nn::ELUOptions`.
+/// See the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(ELU);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SELU ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the selu function element-wise.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.SELU to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::SELUOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// SELU model(SELUOptions().inplace(true));
+/// ```
+class TORCH_API SELUImpl : public torch::nn::Cloneable {
+ public:
+  explicit SELUImpl(const SELUOptions& options_ = {});
+
+  Tensor forward(Tensor input);
+
+  void reset() override;
+
+  /// Pretty prints the `SELU` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// The options with which this `Module` was constructed.
+  SELUOptions options;
+};
+
+/// A `ModuleHolder` subclass for `SELUImpl`.
+/// See the documentation for `SELUImpl` class to learn what methods it
+/// provides, and examples of how to use `SELU` with `torch::nn::SELUOptions`.
+/// See the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(SELU);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Hardshrink ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the hard shrinkage function element-wise.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.Hardshrink to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::HardshrinkOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// Hardshrink model(HardshrinkOptions().lambda(42.42));
+/// ```
+class TORCH_API HardshrinkImpl : public torch::nn::Cloneable {
+ public:
+  explicit HardshrinkImpl(const HardshrinkOptions& options_ = {});
+
+  Tensor forward(const Tensor& input);
+
+  void reset() override;
+
+  /// Pretty prints the `Hardshrink` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// The options with which this `Module` was constructed.
+  HardshrinkOptions options;
+};
+
+/// A `ModuleHolder` subclass for `HardshrinkImpl`.
+/// See the documentation for `HardshrinkImpl` class to learn what methods it
+/// provides, and examples of how to use `Hardshrink` with
+/// `torch::nn::HardshrinkOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(Hardshrink);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Hardtanh ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the HardTanh function element-wise.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.Hardtanh to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::HardtanhOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// Hardtanh
+/// model(HardtanhOptions().min_val(-42.42).max_val(0.42).inplace(true));
+/// ```
+class TORCH_API HardtanhImpl : public torch::nn::Cloneable {
+ public:
+  explicit HardtanhImpl(const HardtanhOptions& options_ = {});
+
+  Tensor forward(Tensor input);
+
+  void reset() override;
+
+  /// Pretty prints the `Hardtanh` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// The options with which this `Module` was constructed.
+  HardtanhOptions options;
+};
+
+/// A `ModuleHolder` subclass for `HardtanhImpl`.
+/// See the documentation for `HardtanhImpl` class to learn what methods it
+/// provides, and examples of how to use `Hardtanh` with
+/// `torch::nn::HardtanhOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(Hardtanh);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ LeakyReLU ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the LeakyReLU function element-wise.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.LeakyReLU to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::LeakyReLUOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// LeakyReLU model(LeakyReLUOptions().negative_slope(0.42).inplace(true));
+/// ```
+class TORCH_API LeakyReLUImpl : public torch::nn::Cloneable {
+ public:
+  explicit LeakyReLUImpl(const LeakyReLUOptions& options_ = {});
+
+  Tensor forward(Tensor input);
+
+  void reset() override;
+
+  /// Pretty prints the `LeakyReLU` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// The options with which this `Module` was constructed.
+  LeakyReLUOptions options;
+};
+
+/// A `ModuleHolder` subclass for `LeakyReLUImpl`.
+/// See the documentation for `LeakyReLUImpl` class to learn what methods it
+/// provides, and examples of how to use `LeakyReLU` with
+/// `torch::nn::LeakyReLUOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(LeakyReLU);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ LogSigmoid ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the LogSigmoid function element-wise.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.LogSigmoid to learn
+/// about the exact behavior of this module.
+class TORCH_API LogSigmoidImpl : public torch::nn::Cloneable {
+ public:
+  Tensor forward(const Tensor& input);
+
+  void reset() override;
+
+  /// Pretty prints the `LogSigmoid` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+};
+
+/// A `ModuleHolder` subclass for `LogSigmoidImpl`.
+/// See the documentation for `LogSigmoidImpl` class to learn what methods it
+/// provides, or the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(LogSigmoid);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Softmax ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the Softmax function.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.Softmax to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::SoftmaxOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// Softmax model(SoftmaxOptions(1));
+/// ```
+class TORCH_API SoftmaxImpl : public torch::nn::Cloneable {
+ public:
+  explicit SoftmaxImpl(int64_t dim) : SoftmaxImpl(SoftmaxOptions(dim)) {}
+  explicit SoftmaxImpl(const SoftmaxOptions& options_);
+
+  Tensor forward(const Tensor& input);
+
+  void reset() override;
+
+  /// Pretty prints the `Softmax` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  SoftmaxOptions options;
+};
+
+/// A `ModuleHolder` subclass for `SoftmaxImpl`.
+/// See the documentation for `SoftmaxImpl` class to learn what methods it
+/// provides, and examples of how to use `Softmax` with
+/// `torch::nn::SoftmaxOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(Softmax);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Softmin ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the Softmin function element-wise.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.Softmin to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::SoftminOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// Softmin model(SoftminOptions(1));
+/// ```
+class TORCH_API SoftminImpl : public torch::nn::Cloneable {
+ public:
+  explicit SoftminImpl(int64_t dim) : SoftminImpl(SoftminOptions(dim)) {}
+  explicit SoftminImpl(const SoftminOptions& options_);
+
+  Tensor forward(const Tensor& input);
+
+  void reset() override;
+
+  /// Pretty prints the `Softmin` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  SoftminOptions options;
+};
+
+/// A `ModuleHolder` subclass for `SoftminImpl`.
+/// See the documentation for `SoftminImpl` class to learn what methods it
+/// provides, and examples of how to use `Softmin` with
+/// `torch::nn::SoftminOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(Softmin);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ LogSoftmax ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the LogSoftmax function element-wise.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.LogSoftmax to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::LogSoftmaxOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// LogSoftmax model(LogSoftmaxOptions(1));
+/// ```
+class TORCH_API LogSoftmaxImpl : public torch::nn::Cloneable {
+ public:
+  explicit LogSoftmaxImpl(int64_t dim)
+      : LogSoftmaxImpl(LogSoftmaxOptions(dim)) {}
+  explicit LogSoftmaxImpl(const LogSoftmaxOptions& options_);
+
+  Tensor forward(const Tensor& input);
+
+  void reset() override;
+
+  /// Pretty prints the `LogSoftmax` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  LogSoftmaxOptions options;
+};
+
+/// A `ModuleHolder` subclass for `LogSoftmaxImpl`.
+/// See the documentation for `LogSoftmaxImpl` class to learn what methods it
+/// provides, and examples of how to use `LogSoftmax` with
+/// `torch::nn::LogSoftmaxOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(LogSoftmax);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Softmax2d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the Softmax2d function element-wise.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.Softmax2d to learn
+/// about the exact behavior of this module.
+class TORCH_API Softmax2dImpl : public torch::nn::Cloneable {
+ public:
+  Tensor forward(const Tensor& input);
+
+  void reset() override;
+
+  /// Pretty prints the `Softmax2d` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+};
+
+/// A `ModuleHolder` subclass for `Softmax2dImpl`.
+/// See the documentation for `Softmax2dImpl` class to learn what methods it
+/// provides, or the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(Softmax2d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ PReLU ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the PReLU function element-wise.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.PReLU to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::PReLUOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// PReLU model(PReLUOptions().num_parameters(42));
+/// ```
+class TORCH_API PReLUImpl : public torch::nn::Cloneable {
+ public:
+  explicit PReLUImpl(const PReLUOptions& options_ = {});
+
+  Tensor forward(const Tensor& input);
+
+  void reset() override;
+
+  /// Pretty prints the `PReLU` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// The options with which this `Module` was constructed.
+  PReLUOptions options;
+
+  /// The learned weight.
+  Tensor weight;
+};
+
+/// A `ModuleHolder` subclass for `PReLUImpl`.
+/// See the documentation for `PReLUImpl` class to learn what methods it
+/// provides, and examples of how to use `PReLU` with `torch::nn::PReLUOptions`.
+/// See the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(PReLU);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ReLU ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the ReLU function element-wise.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.ReLU to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::ReLUOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// ReLU model(ReLUOptions().inplace(true));
+/// ```
+class TORCH_API ReLUImpl : public torch::nn::Cloneable {
+ public:
+  explicit ReLUImpl(const ReLUOptions& options_ = {});
+
+  Tensor forward(Tensor input);
+
+  void reset() override;
+
+  /// Pretty prints the `ReLU` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// The options with which this `Module` was constructed.
+  ReLUOptions options;
+};
+
+/// A `ModuleHolder` subclass for `ReLUImpl`.
+/// See the documentation for `ReLUImpl` class to learn what methods it
+/// provides, and examples of how to use `ReLU` with `torch::nn::ReLUOptions`.
+/// See the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(ReLU);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ReLU6 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the ReLU6 function element-wise.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.ReLU6 to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::ReLU6Options` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// ReLU6 model(ReLU6Options().inplace(true));
+/// ```
+class TORCH_API ReLU6Impl : public torch::nn::Cloneable {
+ public:
+  explicit ReLU6Impl(const ReLU6Options& options_ = {});
+
+  Tensor forward(Tensor input);
+
+  void reset() override;
+
+  /// Pretty prints the `ReLU6` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// The options with which this `Module` was constructed.
+  ReLU6Options options;
+};
+
+/// A `ModuleHolder` subclass for `ReLU6Impl`.
+/// See the documentation for `ReLU6Impl` class to learn what methods it
+/// provides, and examples of how to use `ReLU6` with `torch::nn::ReLU6Options`.
+/// See the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(ReLU6);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ RReLU ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the RReLU function element-wise.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.RReLU to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::RReLUOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// RReLU model(RReLUOptions().lower(0.24).upper(0.42).inplace(true));
+/// ```
+class TORCH_API RReLUImpl : public torch::nn::Cloneable {
+ public:
+  explicit RReLUImpl(const RReLUOptions& options_ = {});
+
+  Tensor forward(Tensor input);
+
+  void reset() override;
+
+  /// Pretty prints the `RReLU` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// The options with which this `Module` was constructed.
+  RReLUOptions options;
+};
+
+/// A `ModuleHolder` subclass for `RReLUImpl`.
+/// See the documentation for `RReLUImpl` class to learn what methods it
+/// provides, and examples of how to use `RReLU` with `torch::nn::RReLUOptions`.
+/// See the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(RReLU);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ CELU ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies celu over a given input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.CELU to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::CELUOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// CELU model(CELUOptions().alpha(42.42).inplace(true));
+/// ```
+class TORCH_API CELUImpl : public torch::nn::Cloneable {
+ public:
+  explicit CELUImpl(const CELUOptions& options_ = {});
+
+  Tensor forward(Tensor input);
+
+  void reset() override;
+
+  /// Pretty prints the `CELU` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// The options with which this `Module` was constructed.
+  CELUOptions options;
+};
+
+/// A `ModuleHolder` subclass for `CELUImpl`.
+/// See the documentation for `CELUImpl` class to learn what methods it
+/// provides, and examples of how to use `CELU` with `torch::nn::CELUOptions`.
+/// See the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(CELU);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GLU ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies glu over a given input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.GLU to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::GLUOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// GLU model(GLUOptions(1));
+/// ```
+class TORCH_API GLUImpl : public torch::nn::Cloneable {
+ public:
+  explicit GLUImpl(const GLUOptions& options_ = {});
+
+  Tensor forward(const Tensor& input);
+
+  void reset() override;
+
+  /// Pretty prints the `GLU` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// The options with which this `Module` was constructed.
+  GLUOptions options;
+};
+
+/// A `ModuleHolder` subclass for `GLUImpl`.
+/// See the documentation for `GLUImpl` class to learn what methods it
+/// provides, and examples of how to use `GLU` with `torch::nn::GLUOptions`.
+/// See the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(GLU);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GELU ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies gelu over a given input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.GELU to learn
+/// about the exact behavior of this module.
+class TORCH_API GELUImpl : public torch::nn::Cloneable {
+ public:
+  explicit GELUImpl(GELUOptions options_ = {});
+
+  Tensor forward(const Tensor& input);
+
+  void reset() override;
+
+  /// Pretty prints the `GELU` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// The options with which this `Module` was constructed.
+  GELUOptions options;
+};
+
+/// A `ModuleHolder` subclass for `GELUImpl`.
+/// See the documentation for `GELUImpl` class to learn what methods it
+/// provides, or the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(GELU);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SiLU ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies silu over a given input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.SiLU to learn
+/// about the exact behavior of this module.
+class TORCH_API SiLUImpl : public torch::nn::Cloneable {
+ public:
+  Tensor forward(const Tensor& input);
+
+  void reset() override;
+
+  /// Pretty prints the `SiLU` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+};
+
+/// A `ModuleHolder` subclass for `SiLUImpl`.
+/// See the documentation for `SiLUImpl` class to learn what methods it
+/// provides, or the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(SiLU);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Mish ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies mish over a given input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.Mish to learn
+/// about the exact behavior of this module.
+class TORCH_API MishImpl : public torch::nn::Cloneable {
+ public:
+  Tensor forward(const Tensor& input);
+
+  void reset() override;
+
+  /// Pretty prints the `Mish` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+};
+
+/// A `ModuleHolder` subclass for `MishImpl`.
+/// See the documentation for `MishImpl` class to learn what methods it
+/// provides, or the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(Mish);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sigmoid ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies sigmoid over a given input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.Sigmoid to learn
+/// about the exact behavior of this module.
+class TORCH_API SigmoidImpl : public torch::nn::Cloneable {
+ public:
+  Tensor forward(const Tensor& input);
+
+  void reset() override;
+
+  /// Pretty prints the `Sigmoid` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+};
+
+/// A `ModuleHolder` subclass for `SigmoidImpl`.
+/// See the documentation for `SigmoidImpl` class to learn what methods it
+/// provides, or the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(Sigmoid);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Softplus ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies softplus over a given input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.Softplus to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::SoftplusOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// Softplus model(SoftplusOptions().beta(0.24).threshold(42.42));
+/// ```
+class TORCH_API SoftplusImpl : public torch::nn::Cloneable {
+ public:
+  explicit SoftplusImpl(const SoftplusOptions& options_ = {});
+
+  Tensor forward(const Tensor& input);
+
+  void reset() override;
+
+  /// Pretty prints the `Softplus` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// The options with which this `Module` was constructed.
+  SoftplusOptions options;
+};
+
+/// A `ModuleHolder` subclass for `SoftplusImpl`.
+/// See the documentation for `SoftplusImpl` class to learn what methods it
+/// provides, and examples of how to use `Softplus` with
+/// `torch::nn::SoftplusOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(Softplus);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Softshrink ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the soft shrinkage function element-wise.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.Softshrink to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::SoftshrinkOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// Softshrink model(SoftshrinkOptions(42.42));
+/// ```
+class TORCH_API SoftshrinkImpl : public torch::nn::Cloneable {
+ public:
+  explicit SoftshrinkImpl(const SoftshrinkOptions& options_ = {});
+
+  Tensor forward(const Tensor& input);
+
+  void reset() override;
+
+  /// Pretty prints the `Softshrink` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// The options with which this `Module` was constructed.
+  SoftshrinkOptions options;
+};
+
+/// A `ModuleHolder` subclass for `SoftshrinkImpl`.
+/// See the documentation for `SoftshrinkImpl` class to learn what methods it
+/// provides, and examples of how to use `Softshrink` with
+/// `torch::nn::SoftshrinkOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(Softshrink);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Softsign ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies Softsign over a given input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.Softsign to learn
+/// about the exact behavior of this module.
+class TORCH_API SoftsignImpl : public torch::nn::Cloneable {
+ public:
+  Tensor forward(const Tensor& input);
+
+  void reset() override;
+
+  /// Pretty prints the `Softsign` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+};
+
+/// A `ModuleHolder` subclass for `SoftsignImpl`.
+/// See the documentation for `SoftsignImpl` class to learn what methods it
+/// provides, or the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(Softsign);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Tanh ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies Tanh over a given input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.Tanh to learn
+/// about the exact behavior of this module.
+class TORCH_API TanhImpl : public torch::nn::Cloneable {
+ public:
+  Tensor forward(const Tensor& input);
+
+  void reset() override;
+
+  /// Pretty prints the `Tanh` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+};
+
+/// A `ModuleHolder` subclass for `TanhImpl`.
+/// See the documentation for `TanhImpl` class to learn what methods it
+/// provides, or the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(Tanh);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Tanhshrink ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies Tanhshrink over a given input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.Tanhshrink to learn
+/// about the exact behavior of this module.
+class TORCH_API TanhshrinkImpl : public torch::nn::Cloneable {
+ public:
+  Tensor forward(const Tensor& input);
+
+  void reset() override;
+
+  /// Pretty prints the `Tanhshrink` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+};
+
+/// A `ModuleHolder` subclass for `TanhshrinkImpl`.
+/// See the documentation for `TanhshrinkImpl` class to learn what methods it
+/// provides, or the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(Tanhshrink);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Threshold ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the Threshold function element-wise.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.Threshold to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::ThresholdOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// Threshold model(ThresholdOptions(42.42, 24.24).inplace(true));
+/// ```
+class TORCH_API ThresholdImpl : public torch::nn::Cloneable {
+ public:
+  ThresholdImpl(double threshold, double value)
+      : ThresholdImpl(ThresholdOptions(threshold, value)) {}
+  explicit ThresholdImpl(const ThresholdOptions& options_);
+
+  Tensor forward(Tensor input);
+
+  void reset() override;
+
+  /// Pretty prints the `Threshold` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// The options with which this `Module` was constructed.
+  ThresholdOptions options;
+};
+
+/// A `ModuleHolder` subclass for `ThresholdImpl`.
+/// See the documentation for `ThresholdImpl` class to learn what methods it
+/// provides, and examples of how to use `Threshold` with
+/// `torch::nn::ThresholdOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(Threshold);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MultiheadAttention ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the MultiheadAttention function element-wise.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.MultiheadAttention
+/// to learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::MultiheadAttentionOptions` class to
+/// learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// MultiheadAttention model(MultiheadAttentionOptions(20, 10).bias(false));
+/// ```
+class TORCH_API MultiheadAttentionImpl
+    : public torch::nn::Cloneable {
+ public:
+  MultiheadAttentionImpl(int64_t embed_dim, int64_t num_heads)
+      : MultiheadAttentionImpl(
+            MultiheadAttentionOptions(embed_dim, num_heads)) {}
+  explicit MultiheadAttentionImpl(const MultiheadAttentionOptions& options_);
+
+  std::tuple forward(
+      const Tensor& query,
+      const Tensor& key,
+      const Tensor& value,
+      const Tensor& key_padding_mask = {},
+      bool need_weights = true,
+      const Tensor& attn_mask = {},
+      bool average_attn_weights = true);
+
+ protected:
+  FORWARD_HAS_DEFAULT_ARGS(
+      {3, AnyValue(Tensor())},
+      {4, AnyValue(true)},
+      {5, AnyValue(Tensor())},
+      {6, AnyValue(true)})
+
+ public:
+  void reset() override;
+
+  void _reset_parameters();
+
+  /// The options with which this `Module` was constructed.
+  MultiheadAttentionOptions options;
+
+  bool _qkv_same_embed_dim;
+  Tensor in_proj_weight;
+  Tensor in_proj_bias;
+  Tensor bias_k;
+  Tensor bias_v;
+  Linear out_proj = nullptr;
+  Tensor q_proj_weight;
+  Tensor k_proj_weight;
+  Tensor v_proj_weight;
+  int64_t head_dim;
+};
+
+/// A `ModuleHolder` subclass for `MultiheadAttentionImpl`.
+/// See the documentation for `MultiheadAttentionImpl` class to learn what
+/// methods it provides, and examples of how to use `MultiheadAttention` with
+/// `torch::nn::MultiheadAttentionOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(MultiheadAttention);
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/adaptive.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/adaptive.h
new file mode 100644
index 0000000000000000000000000000000000000000..609e690d4c7de7313c73211fcfcc5365f0a3ee20
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/adaptive.h
@@ -0,0 +1,109 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// The output of a single invocation of an AdaptiveLogSoftmaxWithLoss
+/// module's `forward()` method.
+struct TORCH_API ASMoutput {
+  ASMoutput(Tensor output_, double loss_);
+
+  /// Tensor containing computed target log probabilities for each example
+  Tensor output;
+
+  /// Scalar representing the computed negative log likelihood loss
+  double loss;
+};
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ AdaptiveLogSoftmaxWithLoss
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Efficient softmax approximation as described in
+/// `Efficient softmax approximation for GPUs`_ by Edouard Grave, Armand Joulin,
+/// Moustapha Cissé, David Grangier, and Hervé Jégou.
+/// See
+/// https://pytorch.org/docs/main/nn.html#torch.nn.AdaptiveLogSoftmaxWithLoss
+/// to learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::AdaptiveLogSoftmaxWithLossOptions`
+/// class to learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// AdaptiveLogSoftmaxWithLoss model(AdaptiveLogSoftmaxWithLossOptions(8, 10,
+/// {4, 8}).div_value(2.).head_bias(true));
+/// ```
+class TORCH_API AdaptiveLogSoftmaxWithLossImpl
+    : public Cloneable {
+ public:
+  AdaptiveLogSoftmaxWithLossImpl(
+      int64_t in_features,
+      int64_t n_classes,
+      std::vector cutoffs)
+      : AdaptiveLogSoftmaxWithLossImpl(AdaptiveLogSoftmaxWithLossOptions(
+            in_features,
+            n_classes,
+            cutoffs)) {}
+
+  explicit AdaptiveLogSoftmaxWithLossImpl(
+      AdaptiveLogSoftmaxWithLossOptions options_);
+
+  ASMoutput forward(const Tensor& input, const Tensor& target);
+
+  void reset() override;
+
+  void reset_parameters();
+
+  /// Pretty prints the `AdaptiveLogSoftmaxWithLoss` module into the given
+  /// `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// Given input tensor, and output of `head`, computes the log of the full
+  /// distribution
+  Tensor _get_full_log_prob(const Tensor& input, const Tensor& head_output);
+
+  /// Computes log probabilities for all n_classes
+  Tensor log_prob(const Tensor& input);
+
+  /// This is equivalent to `log_pob(input).argmax(1)` but is more efficient in
+  /// some cases
+  Tensor predict(const Tensor& input);
+
+  /// The options with which this `Module` was constructed
+  AdaptiveLogSoftmaxWithLossOptions options;
+
+  /// Cutoffs used to assign targets to their buckets. It should be an ordered
+  /// Sequence of integers sorted in the increasing order
+  std::vector cutoffs;
+
+  int64_t shortlist_size;
+
+  /// Number of clusters
+  int64_t n_clusters;
+
+  /// Output size of head classifier
+  int64_t head_size;
+
+  Linear head = nullptr;
+
+  ModuleList tail;
+};
+
+/// A `ModuleHolder` subclass for `AdaptiveLogSoftmaxWithLossImpl`.
+/// See the documentation for `AdaptiveLogSoftmaxWithLossImpl` class to learn
+/// what methods it provides, and examples of how to use
+/// `AdaptiveLogSoftmaxWithLoss` with
+/// `torch::nn::AdaptiveLogSoftmaxWithLossOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(AdaptiveLogSoftmaxWithLoss);
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/batchnorm.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/batchnorm.h
new file mode 100644
index 0000000000000000000000000000000000000000..0f5e32746936ebc0e1237ea6d1becce9a1d7bb78
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/batchnorm.h
@@ -0,0 +1,250 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Base class for all (dimension-specialized) batchnorm and instancenorm
+/// modules.
+template 
+class NormImplBase : public torch::nn::Cloneable {
+ protected:
+  virtual void _check_input_dim(const Tensor& input) = 0;
+
+ public:
+  NormImplBase(const DerivedOptions& options_) : options(options_) {
+    // NOLINTNEXTLINE(clang-analyzer-optin.cplusplus.VirtualCall)
+    reset();
+  }
+
+  void reset() override {
+    if (options.affine()) {
+      weight = this->register_parameter(
+          "weight", torch::empty({options.num_features()}));
+      bias = this->register_parameter(
+          "bias", torch::empty({options.num_features()}));
+    } else {
+      weight =
+          this->register_parameter("weight", Tensor(), /*requires_grad=*/false);
+      bias =
+          this->register_parameter("bias", Tensor(), /*requires_grad=*/false);
+    }
+    if (options.track_running_stats()) {
+      running_mean = this->register_buffer(
+          "running_mean", torch::zeros({options.num_features()}));
+      running_var = this->register_buffer(
+          "running_var", torch::ones({options.num_features()}));
+      num_batches_tracked = this->register_buffer(
+          "num_batches_tracked", torch::tensor(0, torch::dtype(torch::kLong)));
+    } else {
+      running_mean = this->register_buffer("running_mean", Tensor());
+      running_var = this->register_buffer("running_var", Tensor());
+      num_batches_tracked =
+          this->register_buffer("num_batches_tracked", Tensor());
+    }
+    reset_parameters();
+  }
+
+  void reset_running_stats() {
+    if (options.track_running_stats()) {
+      running_mean.zero_();
+      running_var.fill_(1);
+      num_batches_tracked.zero_();
+    }
+  }
+
+  void reset_parameters() {
+    reset_running_stats();
+    if (options.affine()) {
+      torch::nn::init::ones_(weight);
+      torch::nn::init::zeros_(bias);
+    }
+  }
+
+  /// The options with which this module was constructed.
+  DerivedOptions options;
+
+  /// The learned weight.
+  /// Only defined if the `affine` option was `true` upon construction.
+  Tensor weight;
+
+  /// The learned bias.
+  /// Only defined if the `affine` option was `true` upon construction.
+  Tensor bias;
+
+  /// The running mean.
+  /// Only defined if the `track_running_stats` option was `true` upon
+  /// construction.
+  Tensor running_mean;
+
+  /// The running variance.
+  /// Only defined if the `track_running_stats` option was `true` upon
+  /// construction.
+  Tensor running_var;
+
+  /// The number of the forward call.
+  /// Only defined if the `track_running_stats` option was `true` upon
+  /// construction.
+  Tensor num_batches_tracked;
+};
+
+/// Base class for all (dimension-specialized) batchnorm modules.
+template 
+class BatchNormImplBase : public NormImplBase {
+ public:
+  using NormImplBase::NormImplBase;
+
+  Tensor forward(const Tensor& input) {
+    this->_check_input_dim(input);
+    // NOLINTNEXTLINE(cppcoreguidelines-init-variables)
+    double exponential_average_factor;
+    if (this->options.momentum() == std::nullopt) {
+      exponential_average_factor = 0.0;
+    } else {
+      exponential_average_factor = this->options.momentum().value();
+    }
+
+    if (this->is_training() && this->options.track_running_stats()) {
+      if (this->num_batches_tracked.defined()) {
+        this->num_batches_tracked += 1;
+        if (this->options.momentum() ==
+            std::nullopt) { // use cumulative moving average
+          exponential_average_factor =
+              1.0 / this->num_batches_tracked.template item();
+        } else { // use exponential moving average
+          exponential_average_factor = this->options.momentum().value();
+        }
+      }
+    }
+
+    return torch::nn::functional::detail::batch_norm(
+        input,
+        this->running_mean,
+        this->running_var,
+        this->weight,
+        this->bias,
+        this->is_training() || !this->options.track_running_stats(),
+        /*momentum=*/exponential_average_factor,
+        this->options.eps());
+  }
+
+  /// Pretty prints the `BatchNorm{1,2,3}d` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override {
+    stream << std::boolalpha << "torch::nn::BatchNorm" << D << "d("
+           << this->options.num_features() << ", "
+           << "eps=" << this->options.eps() << ", "
+           << "momentum=";
+
+    if (this->options.momentum().has_value()) {
+      stream << this->options.momentum().value();
+    } else {
+      stream << "None";
+    }
+
+    stream << ", "
+           << "affine=" << this->options.affine() << ", "
+           << "track_running_stats=" << this->options.track_running_stats()
+           << ")";
+  }
+};
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BatchNorm1d
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the BatchNorm1d function.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.BatchNorm1d to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::BatchNorm1dOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// BatchNorm1d
+/// model(BatchNorm1dOptions(4).eps(0.5).momentum(0.1).affine(false).track_running_stats(true));
+/// ```
+class TORCH_API BatchNorm1dImpl : public BatchNormImplBase<1, BatchNorm1dImpl> {
+ protected:
+  void _check_input_dim(const Tensor& input) override;
+
+ public:
+  using BatchNormImplBase<1, BatchNorm1dImpl>::BatchNormImplBase;
+};
+
+/// A `ModuleHolder` subclass for `BatchNorm1dImpl`.
+/// See the documentation for `BatchNorm1dImpl` class to learn what methods it
+/// provides, and examples of how to use `BatchNorm1d` with
+/// `torch::nn::BatchNorm1dOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(BatchNorm1d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BatchNorm2d
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the BatchNorm2d function.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.BatchNorm2d to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::BatchNorm2dOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// BatchNorm2d
+/// model(BatchNorm2dOptions(4).eps(0.5).momentum(0.1).affine(false).track_running_stats(true));
+/// ```
+class TORCH_API BatchNorm2dImpl : public BatchNormImplBase<2, BatchNorm2dImpl> {
+ protected:
+  void _check_input_dim(const Tensor& input) override;
+
+ public:
+  using BatchNormImplBase<2, BatchNorm2dImpl>::BatchNormImplBase;
+};
+
+/// A `ModuleHolder` subclass for `BatchNorm2dImpl`.
+/// See the documentation for `BatchNorm2dImpl` class to learn what methods it
+/// provides, and examples of how to use `BatchNorm2d` with
+/// `torch::nn::BatchNorm2dOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(BatchNorm2d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BatchNorm3d
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the BatchNorm3d function.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.BatchNorm3d to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::BatchNorm3dOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// BatchNorm3d
+/// model(BatchNorm3dOptions(4).eps(0.5).momentum(0.1).affine(false).track_running_stats(true));
+/// ```
+class TORCH_API BatchNorm3dImpl : public BatchNormImplBase<3, BatchNorm3dImpl> {
+ protected:
+  void _check_input_dim(const Tensor& input) override;
+
+ public:
+  using BatchNormImplBase<3, BatchNorm3dImpl>::BatchNormImplBase;
+};
+
+/// A `ModuleHolder` subclass for `BatchNorm3dImpl`.
+/// See the documentation for `BatchNorm3dImpl` class to learn what methods it
+/// provides, and examples of how to use `BatchNorm3d` with
+/// `torch::nn::BatchNorm3dOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(BatchNorm3d);
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/common.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/common.h
new file mode 100644
index 0000000000000000000000000000000000000000..f172c82e7e632411be9ea3b8a4dc3d68ff5e74a3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/common.h
@@ -0,0 +1,97 @@
+#pragma once
+
+/// This macro enables a module with default arguments in its forward method
+/// to be used in a Sequential module.
+///
+/// Example usage:
+///
+/// Let's say we have a module declared like this:
+/// ```
+/// struct MImpl : torch::nn::Module {
+///  public:
+///   explicit MImpl(int value_) : value(value_) {}
+///   torch::Tensor forward(int a, int b = 2, double c = 3.0) {
+///     return torch::tensor(a + b + c);
+///   }
+///  private:
+///   int value;
+/// };
+/// TORCH_MODULE(M);
+/// ```
+///
+/// If we try to use it in a Sequential module and run forward:
+/// ```
+/// torch::nn::Sequential seq(M(1));
+/// seq->forward(1);
+/// ```
+///
+/// We will receive the following error message:
+/// ```
+/// MImpl's forward() method expects 3 argument(s), but received 1.
+/// If MImpl's forward() method has default arguments, please make sure
+/// the forward() method is declared with a corresponding
+/// `FORWARD_HAS_DEFAULT_ARGS` macro.
+/// ```
+///
+/// The right way to fix this error is to use the `FORWARD_HAS_DEFAULT_ARGS`
+/// macro when declaring the module:
+/// ```
+/// struct MImpl : torch::nn::Module {
+///  public:
+///   explicit MImpl(int value_) : value(value_) {}
+///   torch::Tensor forward(int a, int b = 2, double c = 3.0) {
+///     return torch::tensor(a + b + c);
+///   }
+///  protected:
+///   /*
+///   NOTE: looking at the argument list of `forward`:
+///   `forward(int a, int b = 2, double c = 3.0)`
+///   we saw the following default arguments:
+///   ----------------------------------------------------------------
+///   0-based index of default |         Default value of arg
+///   arg in forward arg list  |  (wrapped by `torch::nn::AnyValue()`)
+///   ----------------------------------------------------------------
+///               1            |       torch::nn::AnyValue(2)
+///               2            |       torch::nn::AnyValue(3.0)
+///   ----------------------------------------------------------------
+///   Thus we pass the following arguments to the `FORWARD_HAS_DEFAULT_ARGS`
+///   macro:
+///   */
+///   FORWARD_HAS_DEFAULT_ARGS({1, torch::nn::AnyValue(2)}, {2,
+///   torch::nn::AnyValue(3.0)})
+///  private:
+///   int value;
+/// };
+/// TORCH_MODULE(M);
+/// ```
+/// Now, running the following would work:
+/// ```
+/// torch::nn::Sequential seq(M(1));
+/// seq->forward(1);  // This correctly populates the default arguments for
+/// `MImpl::forward`
+/// ```
+#define FORWARD_HAS_DEFAULT_ARGS(...)                                         \
+  template                    \
+  friend struct torch::nn::AnyModuleHolder;                                   \
+  bool _forward_has_default_args() override {                                 \
+    return true;                                                              \
+  }                                                                           \
+  unsigned int _forward_num_required_args() override {                        \
+    std::pair args_info[] = {__VA_ARGS__}; \
+    return args_info[0].first;                                                \
+  }                                                                           \
+  std::vector _forward_populate_default_args(            \
+      std::vector&& arguments) override {                \
+    std::pair args_info[] = {__VA_ARGS__}; \
+    unsigned int num_all_args = std::rbegin(args_info)->first + 1;            \
+    TORCH_INTERNAL_ASSERT(                                                    \
+        arguments.size() >= _forward_num_required_args() &&                   \
+        arguments.size() <= num_all_args);                                    \
+    std::vector ret = std::move(arguments);              \
+    ret.reserve(num_all_args);                                                \
+    for (auto& arg_info : args_info) {                                        \
+      if (arg_info.first > ret.size() - 1)                                    \
+        ret.emplace_back(std::move(arg_info.second));                         \
+    }                                                                         \
+    return ret;                                                               \
+  }
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/any.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/any.h
new file mode 100644
index 0000000000000000000000000000000000000000..ab4a589aeded124cb6e34fd5dd191165f4aea43c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/any.h
@@ -0,0 +1,372 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Stores a type erased `Module`.
+///
+/// The PyTorch C++ API does not impose an interface on the signature of
+/// `forward()` in `Module` subclasses. This gives you complete freedom to
+/// design your `forward()` methods to your liking. However, this also means
+/// there is no unified base type you could store in order to call `forward()`
+/// polymorphically for any module. This is where the `AnyModule` comes in.
+/// Instead of inheritance, it relies on type erasure for polymorphism.
+///
+/// An `AnyModule` can store any `nn::Module` subclass that provides a
+/// `forward()` method. This `forward()` may accept any types and return any
+/// type. Once stored in an `AnyModule`, you can invoke the underlying module's
+/// `forward()` by calling `AnyModule::forward()` with the arguments you would
+/// supply to the stored module (though see one important limitation below).
+/// Example:
+///
+/// \rst
+/// .. code-block:: cpp
+///
+///   struct GenericTrainer {
+///     torch::nn::AnyModule module;
+///
+///     void train(torch::Tensor input) {
+///       module.forward(input);
+///     }
+///   };
+///
+///   GenericTrainer trainer1{torch::nn::Linear(3, 4)};
+///   GenericTrainer trainer2{torch::nn::Conv2d(3, 4, 2)};
+/// \endrst
+///
+/// As `AnyModule` erases the static type of the stored module (and its
+/// `forward()` method) to achieve polymorphism, type checking of arguments is
+/// moved to runtime. That is, passing an argument with an incorrect type to an
+/// `AnyModule` will compile, but throw an exception at runtime:
+///
+/// \rst
+/// .. code-block:: cpp
+///
+///   torch::nn::AnyModule module(torch::nn::Linear(3, 4));
+///   // Linear takes a tensor as input, but we are passing an integer.
+///   // This will compile, but throw a `torch::Error` exception at runtime.
+///   module.forward(123);
+/// \endrst
+///
+/// \rst
+/// .. attention::
+///   One noteworthy limitation of `AnyModule` is that its `forward()` method
+///   does not support implicit conversion of argument types. For example, if
+///   the stored module's `forward()` method accepts a `float` and you call
+///   `any_module.forward(3.4)` (where `3.4` is a `double`), this will throw
+///   an exception.
+/// \endrst
+///
+/// The return type of the `AnyModule`'s `forward()` method is controlled via
+/// the first template argument to `AnyModule::forward()`. It defaults to
+/// `torch::Tensor`. To change it, you can write `any_module.forward()`,
+/// for example.
+///
+/// \rst
+/// .. code-block:: cpp
+///
+///   torch::nn::AnyModule module(torch::nn::Linear(3, 4));
+///   auto output = module.forward(torch::ones({2, 3}));
+///
+///   struct IntModule {
+///     int forward(int x) { return x; }
+///   };
+///   torch::nn::AnyModule module(IntModule{});
+///   int output = module.forward(5);
+/// \endrst
+///
+/// The only other method an `AnyModule` provides access to on the stored
+/// module is `clone()`. However, you may acquire a handle on the module via
+/// `.ptr()`, which returns a `shared_ptr`. Further, if you know
+/// the concrete type of the stored module, you can get a concrete handle to it
+/// using `.get()` where `T` is the concrete module type.
+///
+/// \rst
+/// .. code-block:: cpp
+///
+///   torch::nn::AnyModule module(torch::nn::Linear(3, 4));
+///   std::shared_ptr ptr = module.ptr();
+///   torch::nn::Linear linear(module.get());
+/// \endrst
+class AnyModule {
+ public:
+  /// A default-constructed `AnyModule` is in an empty state.
+  AnyModule() = default;
+
+  /// Constructs an `AnyModule` from a `shared_ptr` to concrete module object.
+  template 
+  explicit AnyModule(std::shared_ptr module);
+
+  /// Constructs an `AnyModule` from a concrete module object.
+  template <
+      typename ModuleType,
+      typename = torch::detail::enable_if_module_t>
+  explicit AnyModule(ModuleType&& module);
+
+  /// Constructs an `AnyModule` from a module holder.
+  template 
+  explicit AnyModule(const ModuleHolder& module_holder);
+
+  /// Move construction and assignment is allowed, and follows the default
+  /// behavior of move for `std::unique_ptr`.
+  AnyModule(AnyModule&&) = default;
+  AnyModule& operator=(AnyModule&&) = default;
+
+  /// Creates a shallow copy of an `AnyModule`.
+  AnyModule(const AnyModule& other);
+  AnyModule& operator=(const AnyModule& other);
+
+  /// Creates a deep copy of an `AnyModule` if it contains a module, else an
+  /// empty `AnyModule` if it is empty.
+  AnyModule clone(std::optional device = std::nullopt) const;
+
+  /// Assigns a module to the `AnyModule` (to circumvent the explicit
+  /// constructor).
+  template 
+  AnyModule& operator=(std::shared_ptr module);
+
+  /// Invokes `forward()` on the contained module with the given arguments, and
+  /// returns the return value as an `AnyValue`. Use this method when chaining
+  /// `AnyModule`s in a loop.
+  template 
+  AnyValue any_forward(ArgumentTypes&&... arguments);
+
+  /// Invokes `forward()` on the contained module with the given arguments, and
+  /// casts the returned `AnyValue` to the supplied `ReturnType` (which defaults
+  /// to `torch::Tensor`).
+  template 
+  ReturnType forward(ArgumentTypes&&... arguments);
+
+  /// Attempts to cast the underlying module to the given module type. Throws an
+  /// exception if the types do not match.
+  template >
+  T& get();
+
+  /// Attempts to cast the underlying module to the given module type. Throws an
+  /// exception if the types do not match.
+  template >
+  const T& get() const;
+
+  /// Returns the contained module in a `nn::ModuleHolder` subclass if possible
+  /// (i.e. if `T` has a constructor for the underlying module type).
+  template 
+  T get() const;
+
+  /// Returns a `std::shared_ptr` whose dynamic type is that of the underlying
+  /// module.
+  std::shared_ptr ptr() const;
+
+  /// Like `ptr()`, but casts the pointer to the given type.
+  template >
+  std::shared_ptr ptr() const;
+
+  /// Returns the `type_info` object of the contained value.
+  const std::type_info& type_info() const;
+
+  /// Returns true if the `AnyModule` does not contain a module.
+  bool is_empty() const noexcept;
+
+ private:
+  /// Creates a `unique_ptr` pointing to a
+  /// `AnyModuleHolder` of the correct type. This method is used to deduce the
+  /// arguments of the module's `forward()` method.
+  template <
+      typename ModuleType,
+      typename Class,
+      typename ReturnType,
+      typename... ArgumentTypes>
+  std::unique_ptr make_holder(
+      std::shared_ptr&& module,
+      ReturnType (Class::*)(ArgumentTypes...));
+
+  /// Helper method invoked by const and non-const `get()`.
+  template 
+  ModuleType& get_(ReturnType (ModuleType::*)(ArgumentTypes...)) const;
+
+  /// Helper method invoked by const and non-const `get()`.
+  template 
+  ModuleType& get_() const;
+
+  /// The type erased module.
+  std::unique_ptr content_;
+};
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ AnyModule ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+template 
+AnyModule::AnyModule(std::shared_ptr module)
+    : content_(make_holder(
+          std::move(module),
+          &std::remove_reference::type::forward)) {
+  // `AnyModule` can only store an `nn::Module` subclass object that provides
+  // a `forward()` method that has a non-templatized return type.
+  // (e.g. `AnyModule` cannot store `nn::Sequential`, because `nn::Sequential`'s
+  // `forward()` method has a templatized return type.)
+  static_assert(
+      torch::detail::is_module::value,
+      "Can only store object derived from nn::Module into AnyModule");
+  static_assert(
+      torch::detail::has_forward::value,
+      "Can only store module with a forward() method that has a non-templatized"
+      " argument type and return type into AnyModule (e.g. we cannot store nn::Sequential"
+      "into AnyModule, because its forward() method's argument type and return type are templatized."
+      " If you need to use nn::Sequentials inside each other you can subclass "
+      "nn::Sequential and write a non-templatized forward function for it. You can checkout "
+      "https://github.com/pytorch/vision/blob/2f46070f3cb1ea894d82578f3dc5677f82f34958/torchvision/csrc/models/mnasnet.cpp#L59 "
+      "for an example on how to do this.).");
+}
+
+template 
+AnyModule::AnyModule(ModuleType&& module)
+    : AnyModule(
+          std::make_shared(std::forward(module))) {}
+
+template 
+AnyModule::AnyModule(const ModuleHolder& module_holder)
+    : AnyModule(module_holder.ptr()) {}
+
+inline AnyModule::AnyModule(const AnyModule& other)
+    : content_(other.content_ ? other.content_->copy() : nullptr) {}
+
+inline AnyModule& AnyModule::operator=(const AnyModule& other) {
+  if (this != &other) {
+    content_ = other.content_ ? other.content_->copy() : nullptr;
+  }
+  return *this;
+}
+
+inline AnyModule AnyModule::clone(std::optional device) const {
+  AnyModule clone;
+  clone.content_ = content_ ? content_->clone_module(device) : nullptr;
+  return clone;
+}
+
+template 
+AnyModule& AnyModule::operator=(std::shared_ptr module) {
+  // NOLINTNEXTLINE(cppcoreguidelines-c-copy-assignment-signature)
+  return (*this = AnyModule(std::move(module)));
+}
+
+template 
+AnyValue AnyModule::any_forward(ArgumentTypes&&... arguments) {
+  TORCH_CHECK(!is_empty(), "Cannot call forward() on an empty AnyModule");
+  std::vector values;
+  values.reserve(sizeof...(ArgumentTypes));
+  torch::apply(
+      [&values](AnyValue&& value) { values.push_back(std::move(value)); },
+      AnyValue(std::forward(arguments))...);
+  return content_->forward(std::move(values));
+}
+
+template 
+ReturnType AnyModule::forward(ArgumentTypes&&... arguments) {
+  return any_forward(std::forward(arguments)...)
+      .template get();
+}
+
+template 
+T& AnyModule::get() {
+  TORCH_CHECK(!is_empty(), "Cannot call get() on an empty AnyModule");
+  return get_();
+}
+
+template 
+const T& AnyModule::get() const {
+  TORCH_CHECK(!is_empty(), "Cannot call get() on an empty AnyModule");
+  return get_();
+}
+
+template 
+T AnyModule::get() const {
+  return T(ptr());
+}
+
+inline std::shared_ptr AnyModule::ptr() const {
+  TORCH_CHECK(!is_empty(), "Cannot call ptr() on an empty AnyModule");
+  return content_->ptr();
+}
+
+template 
+std::shared_ptr AnyModule::ptr() const {
+  TORCH_CHECK(!is_empty(), "Cannot call ptr() on an empty AnyModule");
+  // Call get() but discard the value, just to do the type checking.
+  get_();
+  return std::dynamic_pointer_cast(ptr());
+}
+
+inline const std::type_info& AnyModule::type_info() const {
+  TORCH_CHECK(!is_empty(), "Cannot call type_info() on an empty AnyModule");
+  return content_->type_info;
+}
+
+inline bool AnyModule::is_empty() const noexcept {
+  return content_ == nullptr;
+}
+
+// Private Methods
+
+template <
+    typename ModuleType,
+    typename Class,
+    typename ReturnType,
+    typename... ArgumentTypes>
+std::unique_ptr AnyModule::make_holder(
+    std::shared_ptr&& module,
+    ReturnType (Class::*)(ArgumentTypes...)) {
+  static_assert(
+      torch::detail::check_not_lvalue_references(),
+      "Modules stored inside AnyModule must not take references. "
+      "Use pointers instead.");
+  static_assert(
+      !std::is_void::value,
+      "AnyModule cannot store modules that return void "
+      "(you can return a dummy value).");
+  return std::make_unique<
+      AnyModuleHolder, ArgumentTypes...>>(
+      std::move(module));
+}
+
+template 
+ModuleType& AnyModule::get_() const {
+  using M = typename std::remove_reference::type;
+  static_assert(
+      torch::detail::has_forward::value,
+      "Can only call AnyModule::get with a type T that has a forward method");
+  return get_(&M::forward);
+}
+
+template 
+ModuleType& AnyModule::get_(
+    ReturnType (ModuleType::*)(ArgumentTypes...)) const {
+  if (typeid(ModuleType).hash_code() == type_info().hash_code()) {
+    return *static_cast&>(
+                *content_)
+                .module;
+  }
+  AT_ERROR(
+      "Attempted to cast module of type ",
+      c10::demangle(type_info().name()),
+      " to type ",
+      c10::demangle(typeid(ModuleType).name()));
+}
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/any_module_holder.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/any_module_holder.h
new file mode 100644
index 0000000000000000000000000000000000000000..edeb8e6b764c516a6fee5445a704905ac7df7c1b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/any_module_holder.h
@@ -0,0 +1,133 @@
+#pragma once
+
+#include 
+
+namespace torch {
+namespace nn {
+
+class Module;
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~ AnyModulePlaceholder ~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// The static type of the object we store in the `AnyModule`, which erases
+/// the actual type, but allows us to call `forward()` on the underlying
+/// module.
+struct AnyModulePlaceholder : public AnyValue::Placeholder {
+  using AnyValue::Placeholder::Placeholder;
+
+  /// The "erased" `forward()` method.
+  virtual AnyValue forward(std::vector&& arguments) = 0;
+
+  /// Returns std::shared_ptr pointing to the erased module.
+  virtual std::shared_ptr ptr() = 0;
+
+  /// Returns a `AnyModulePlaceholder` with a shallow copy of this `AnyModule`.
+  virtual std::unique_ptr copy() const = 0;
+
+  /// Returns a `AnyModulePlaceholder` with a deep copy of this `AnyModule`.
+  virtual std::unique_ptr clone_module(
+      std::optional device) const = 0;
+};
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ AnyModuleHolder ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// The dynamic type of the object stored in the `AnyModule`. It contains the
+/// concrete instance to which all calls are forwarded. It is parameterized
+/// over the concrete type of the module, and the types of the arguments the
+/// module takes in its `forward()` method.
+template 
+struct AnyModuleHolder : public AnyModulePlaceholder {
+  /// \internal
+  struct CheckedGetter {
+    template 
+    std::decay_t&& operator()(size_t index) {
+      AT_ASSERT(index < arguments_.size());
+      auto& value = arguments_[index];
+      if (auto* maybe_value = value.template try_get>()) {
+        return std::move(*maybe_value);
+      }
+      AT_ERROR(
+          "Expected argument #",
+          index,
+          " to be of type ",
+          c10::demangle(typeid(T).name()),
+          ", but received value of type ",
+          c10::demangle(value.type_info().name()));
+    }
+    std::vector& arguments_;
+  };
+
+  /// \internal
+  struct InvokeForward {
+    template 
+    AnyValue operator()(Ts&&... ts) {
+      return AnyValue(module_->forward(std::forward(ts)...));
+    }
+    std::shared_ptr& module_;
+  };
+
+  /// Constructs the `AnyModuleHolder` from a concrete module.
+  explicit AnyModuleHolder(std::shared_ptr&& module_)
+      : AnyModulePlaceholder(typeid(ModuleType)), module(std::move(module_)) {}
+
+  /// Calls `forward()` on the underlying module, casting each `AnyValue` in the
+  /// argument vector to a concrete value.
+  AnyValue forward(std::vector&& arguments) override {
+    if (module->_forward_has_default_args()) {
+      TORCH_CHECK(
+          arguments.size() >= module->_forward_num_required_args() &&
+              arguments.size() <= sizeof...(ArgumentTypes),
+          c10::demangle(type_info.name()),
+          "'s forward() method expects at least ",
+          module->_forward_num_required_args(),
+          " argument(s) and at most ",
+          sizeof...(ArgumentTypes),
+          " argument(s), but received ",
+          arguments.size(),
+          ".");
+      arguments = std::move(
+          module->_forward_populate_default_args(std::move(arguments)));
+    } else {
+      std::string use_default_args_macro_prompt = " If " +
+          c10::demangle(type_info.name()) +
+          "'s forward() method has default arguments, " +
+          "please make sure the forward() method is declared with a corresponding `FORWARD_HAS_DEFAULT_ARGS` macro.";
+      TORCH_CHECK(
+          arguments.size() == sizeof...(ArgumentTypes),
+          c10::demangle(type_info.name()),
+          "'s forward() method expects ",
+          sizeof...(ArgumentTypes),
+          " argument(s), but received ",
+          arguments.size(),
+          ".",
+          (arguments.size() < sizeof...(ArgumentTypes))
+              ? use_default_args_macro_prompt
+              : "");
+    }
+
+    // FYI: During invocation of a module's `forward()` method, the values live
+    // in the `arguments` vector inside this function.
+    return torch::unpack(
+        InvokeForward{module}, CheckedGetter{arguments});
+  }
+
+  std::shared_ptr ptr() override {
+    return module;
+  }
+
+  std::unique_ptr copy() const override {
+    return std::make_unique(*this);
+  }
+
+  std::unique_ptr clone_module(
+      std::optional device) const override {
+    return std::make_unique(
+        std::dynamic_pointer_cast(module->clone(device)));
+  }
+
+  /// The actual concrete module instance.
+  std::shared_ptr module;
+};
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/any_value.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/any_value.h
new file mode 100644
index 0000000000000000000000000000000000000000..d154130618f2dcaaf4724c32bd40fb59ed3bd465
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/any_value.h
@@ -0,0 +1,125 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ AnyValue ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// An implementation of `std::any` which stores
+/// a type erased object, whose concrete value can be retrieved at runtime by
+/// checking if the `typeid()` of a requested type matches the `typeid()` of
+/// the object stored.
+class AnyValue {
+ public:
+  /// Move construction and assignment is allowed, and follows the default
+  /// behavior of move for `std::unique_ptr`.
+  AnyValue(AnyValue&&) = default;
+  AnyValue& operator=(AnyValue&&) = default;
+
+  /// Copy construction and assignment is allowed.
+  AnyValue(const AnyValue& other) : content_(other.content_->clone()) {}
+  AnyValue& operator=(const AnyValue& other) {
+    content_ = other.content_->clone();
+    return *this;
+  }
+
+  /// Constructs the `AnyValue` from value type.
+  template 
+  // NOLINTNEXTLINE(bugprone-forwarding-reference-overload)
+  explicit AnyValue(T&& value)
+      : content_(
+            std::make_unique>>(std::forward(value))) {
+  }
+
+  /// Returns a pointer to the value contained in the `AnyValue` if the type
+  /// passed as template parameter matches the type of the value stored, and
+  /// returns a null pointer otherwise.
+  template 
+  T* try_get() {
+    static_assert(
+        !std::is_reference::value,
+        "AnyValue stores decayed types, you cannot cast it to a reference type");
+    static_assert(
+        !std::is_array::value,
+        "AnyValue stores decayed types, you must cast it to T* instead of T[]");
+    if (typeid(T).hash_code() == type_info().hash_code()) {
+      return &static_cast&>(*content_).value;
+    }
+    return nullptr;
+  }
+
+  /// Returns the value contained in the `AnyValue` if the type passed as
+  /// template parameter matches the type of the value stored, and throws an
+  /// exception otherwise.
+  template 
+  T get() {
+    if (auto* maybe_value = try_get()) {
+      return *maybe_value;
+    }
+    AT_ERROR(
+        "Attempted to cast AnyValue to ",
+        c10::demangle(typeid(T).name()),
+        ", but its actual type is ",
+        c10::demangle(type_info().name()));
+  }
+
+  /// Returns the `type_info` object of the contained value.
+  const std::type_info& type_info() const noexcept {
+    return content_->type_info;
+  }
+
+ private:
+  friend struct AnyModulePlaceholder;
+  friend struct TestAnyValue;
+
+  /// \internal
+  /// The static type of the object we store in the `AnyValue`, which erases the
+  /// actual object's type, allowing us only to check the `type_info` of the
+  /// type stored in the dynamic type.
+  struct Placeholder {
+    explicit Placeholder(const std::type_info& type_info_) noexcept
+        : type_info(type_info_) {}
+    Placeholder(const Placeholder&) = default;
+    Placeholder(Placeholder&&) = default;
+    virtual ~Placeholder() = default;
+    virtual std::unique_ptr clone() const {
+      TORCH_CHECK(false, "clone() should only be called on `AnyValue::Holder`");
+    }
+    const std::type_info& type_info;
+  };
+
+  /// \internal
+  /// The dynamic type of the object we store in the `AnyValue`, which hides the
+  /// actual object we have erased in this `AnyValue`.
+  template 
+  struct Holder : public Placeholder {
+    /// A template because T&& would not be universal reference here.
+    template 
+    // NOLINTNEXTLINE(bugprone-forwarding-reference-overload)
+    explicit Holder(U&& value_) noexcept
+        : Placeholder(typeid(T)), value(std::forward(value_)) {}
+    std::unique_ptr clone() const override {
+      return std::make_unique>(value);
+    }
+    T value;
+  };
+
+  /// The type erased object.
+  std::unique_ptr content_;
+};
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/functional.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/functional.h
new file mode 100644
index 0000000000000000000000000000000000000000..3f381a63944f580a7c787e8142ac65b2be150729
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/functional.h
@@ -0,0 +1,105 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Wraps a function in a `Module`.
+///
+/// The `Functional` module allows wrapping an arbitrary function or function
+/// object in an `nn::Module`. This is primarily handy for usage in
+/// `Sequential`.
+///
+/// \rst
+/// .. code-block:: cpp
+///
+///   Sequential sequential(
+///     Linear(3, 4),
+///     Functional(torch::relu),
+///     BatchNorm1d(3),
+///     Functional(torch::elu, /*alpha=*/1));
+/// \endrst
+///
+/// While a `Functional` module only accepts a single `Tensor` as input, it is
+/// possible for the wrapped function to accept further arguments. However,
+/// these have to be bound *at construction time*. For example, if
+/// you want to wrap `torch::leaky_relu`, which accepts a `slope` scalar as its
+/// second argument, with a particular value for its `slope` in a `Functional`
+/// module, you could write
+///
+/// \rst
+/// .. code-block:: cpp
+///
+///   Functional(torch::leaky_relu, /*slope=*/0.5)
+/// \endrst
+///
+/// The value of `0.5` is then stored within the `Functional` object and
+/// supplied to the function call at invocation time. Note that such bound
+/// values are evaluated eagerly and stored a single time. See the documentation
+/// of [std::bind](https://en.cppreference.com/w/cpp/utility/functional/bind)
+/// for more information on the semantics of argument binding.
+///
+/// \rst
+/// .. attention::
+///   After passing any bound arguments, the function must accept a single
+///   tensor and return a single tensor.
+/// \endrst
+///
+/// Note that `Functional` overloads the call operator (`operator()`) such that
+/// you can invoke it with `my_func(...)`.
+class TORCH_API FunctionalImpl : public torch::nn::Cloneable {
+ public:
+  using Function = std::function;
+
+  /// Constructs a `Functional` from a function object.
+  explicit FunctionalImpl(Function function);
+
+  template <
+      typename SomeFunction,
+      typename... Args,
+      typename = std::enable_if_t<(sizeof...(Args) > 0)>>
+  explicit FunctionalImpl(SomeFunction original_function, Args&&... args)
+      // NOLINTNEXTLINE(modernize-avoid-bind)
+      : function_(std::bind(
+            original_function,
+            /*input=*/std::placeholders::_1,
+            std::forward(args)...)) {
+    // std::bind is normally evil, but (1) gcc is broken w.r.t. handling
+    // parameter pack expansion in lambdas and (2) moving parameter packs into
+    // a lambda only works with C++14, so std::bind is the more move-aware
+    // solution here.
+  }
+
+  void reset() override;
+
+  /// Pretty prints the `Functional` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// Forwards the `input` tensor to the underlying (bound) function object.
+  Tensor forward(Tensor input);
+
+  /// Calls forward(input).
+  Tensor operator()(Tensor input);
+
+  bool is_serializable() const override;
+
+ private:
+  Function function_;
+};
+
+/// A `ModuleHolder` subclass for `FunctionalImpl`.
+/// See the documentation for `FunctionalImpl` class to learn what methods it
+/// provides, or the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(Functional);
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/moduledict.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/moduledict.h
new file mode 100644
index 0000000000000000000000000000000000000000..b96b7611936f16e9bdae934160af263a4710f0a8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/moduledict.h
@@ -0,0 +1,262 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// An OrderedDict of `Module`s that registers its elements by their `key`s.
+///
+/// \rst
+/// .. code-block:: cpp
+///
+///   torch::OrderedDict> ordereddict = {
+///     {"linear", Linear(10, 3).ptr()},
+///     {"conv", Conv2d(1, 2, 3).ptr()},
+///     {"dropout", Dropout(0.5).ptr()},
+///   };
+///   torch::nn::ModuleDict dict1(ordereddict);
+///
+///   for (const auto &module : *dict1) {
+///     module->pretty_print(std::cout);
+///   }
+///
+///   std::vector>> list = {
+///     {"linear", Linear(10, 3).ptr()},
+///     {"conv", Conv2d(1, 2, 3).ptr()},
+///     {"dropout", Dropout(0.5).ptr()},
+///   };
+///   torch::nn::ModuleDict dict2(list);
+///
+///   for (const auto &module : *dict2) {
+///     module->pretty_print(std::cout);
+///   }
+///
+/// \endrst
+///
+/// Why should you use `ModuleDict` instead of a simple `map` or `OrderedDict`?
+/// The value a `ModuleDict` provides over manually calling an ordered map of
+/// modules is that it allows treating the whole container *as a single module*,
+/// such that performing a transformation on the `ModuleDict` applies to each of
+/// the modules it stores (which are each a registered submodule of the
+/// `ModuleDict`). For example, calling `.to(torch::kCUDA)` on a `ModuleDict`
+/// will move each module in the map to CUDA memory. For example:
+///
+/// \rst
+/// .. code-block:: cpp
+///
+///   torch::OrderedDict> ordereddict = {
+///     {"linear", Linear(10, 3).ptr()},
+///     {"conv", Conv2d(1, 2, 3).ptr()},
+///     {"dropout", Dropout(0.5).ptr()},
+///   };
+///   torch::nn::ModuleDict dict(ordereddict);
+///
+///   // Convert all modules to CUDA.
+///   dict->to(torch::kCUDA);
+///
+/// \endrst
+///
+/// Finally, `ModuleDict` provides a lightweight container API, such as allowing
+/// iteration over submodules, positional access, adding new modules from a
+/// vector of key-module pairs or an `OrderedDict` or another `ModuleDict` after
+/// construction via `update`.
+class ModuleDictImpl : public Cloneable {
+ public:
+  using Iterator =
+      torch::OrderedDict>::Iterator;
+  using ConstIterator =
+      torch::OrderedDict>::ConstIterator;
+
+  ModuleDictImpl() = default;
+
+  /// Constructs the `ModuleDict` from a list of string-Module pairs.
+  explicit ModuleDictImpl(
+      const std::vector>>&
+          modules) {
+    update(modules);
+  }
+
+  /// Constructs the `ModuleDict` from an `OrderedDict`.
+  explicit ModuleDictImpl(
+      const torch::OrderedDict>& modules) {
+    update(modules);
+  }
+
+  /// Return the items in the `ModuleDict`.
+  std::vector>> items() const {
+    return modules_.pairs();
+  }
+
+  /// Return the keys in the `ModuleDict`.
+  std::vector keys() const {
+    return modules_.keys();
+  }
+
+  /// Return the values in the `ModuleDict`.
+  std::vector> values() const {
+    return modules_.values();
+  }
+
+  /// Return an iterator to the start of `ModuleDict`.
+  Iterator begin() {
+    return modules_.begin();
+  }
+
+  /// Return a const iterator to the start of `ModuleDict`.
+  ConstIterator begin() const {
+    return modules_.begin();
+  }
+
+  /// Return an iterator to the end of `ModuleDict`.
+  Iterator end() {
+    return modules_.end();
+  }
+
+  /// Return a const iterator to the end of `ModuleDict`.
+  ConstIterator end() const {
+    return modules_.end();
+  }
+
+  /// Return the number of items currently stored in the `ModuleDict`.
+  size_t size() const noexcept {
+    return modules_.size();
+  }
+
+  /// Return true if the `ModuleDict` is empty, otherwise return false.
+  bool empty() const noexcept {
+    return modules_.is_empty();
+  }
+
+  /// Check if the centain parameter with the key in the `ModuleDict`.
+  bool contains(const std::string& key) const noexcept {
+    return modules_.contains(key);
+  }
+
+  /// Remove all items from the `ModuleDict`.
+  void clear() {
+    // Not remove the registration of modules to make it consistent with python
+    // version.
+    modules_.clear();
+  }
+
+  /// Special cloning function for `ModuleDict` because it does not use
+  /// `reset()`.
+  std::shared_ptr clone(
+      const std::optional& device = std::nullopt) const override {
+    auto clone = std::make_shared();
+    for (const auto& module : modules_) {
+      clone->insert(module.key(), module.value()->clone(device));
+    }
+    return clone;
+  }
+
+  /// `reset()` is empty for `ModuleDict`, since it does not have parameters of
+  /// its own.
+  void reset() override {}
+
+  /// Pretty prints the `ModuleDict` into the given `stream`.
+  void pretty_print(std::ostream& stream) const override {
+    stream << "torch::nn::ModuleDict";
+  }
+
+  /// Attempts to returns the `Module` associated with the given `key`. Throws
+  /// an exception if no such `key` is stored in the `ModuleDict`. Check
+  /// contains(key) before for a non-throwing way of access.
+  std::shared_ptr operator[](const std::string& key) const {
+    return modules_[key];
+  }
+
+  /// Attempts to return the module at the given key as the requested type.
+  /// Throws an exception if no such `key` is stored in the `ModuleDict`.
+  /// Check contains(key) before for a non-throwing way of access.
+  template 
+  T& at(const std::string& key) {
+    static_assert(
+        torch::detail::is_module::value,
+        "Can only call ModuleList::at with an nn::Module type");
+    auto module = modules_[key]->as();
+    TORCH_CHECK(
+        module,
+        "Unable to cast module[",
+        key,
+        "] to ",
+        c10::demangle(typeid(T).name()));
+    return *module;
+  }
+
+  /// Attempts to return the module at the given key as the requested type.
+  /// Throws an exception if no such `key` is stored in the `ModuleDict`.
+  /// Check contains(key) before for a non-throwing way of access.
+  template 
+  const T& at(const std::string& key) const {
+    static_assert(
+        torch::detail::is_module::value,
+        "Can only call ModuleList::at with an nn::Module type");
+    const auto module = modules_[key]->as();
+    TORCH_CHECK(
+        module,
+        "Unable to cast module[",
+        key,
+        "] to ",
+        c10::demangle(typeid(T).name()));
+    return *module;
+  }
+
+  /// Removes and returns the `Module` associated with the given `key`.
+  /// Throws an exception if no such `key` is stored in the `ModuleDict`.
+  /// Check contains(key) before for a non-throwing way of access.
+  std::shared_ptr pop(const std::string& key) {
+    auto module = modules_[key];
+    modules_.erase(key);
+    // Not remove the registration of the module to make it consistent with
+    // python version.
+    return module;
+  }
+
+  /// Updated the `ModuleDict` with a vector of key-module pairs.
+  void update(
+      const std::vector>>&
+          modules) {
+    for (auto& item : modules) {
+      insert(item.first, item.second);
+    }
+  }
+
+  /// Updated the `ModuleDict` with key-value pairs from `OrderedDict` or
+  /// `ModuleDict`.
+  template 
+  void update(const Container& container) {
+    for (auto& item : container) {
+      insert(item.key(), item.value());
+    }
+  }
+
+ private:
+  /// Private `OrderedDict` holding the key-Module pairs.
+  torch::OrderedDict> modules_;
+
+  /// Insert a key-module pair by overwriting existing keys,
+  /// and register or replace the `Module`.
+  void insert(const std::string& key, std::shared_ptr module) {
+    if (contains(key)) {
+      modules_[key] = std::move(module);
+      replace_module(key, modules_[key]);
+    } else {
+      modules_.insert(key, std::move(module));
+      register_module(key, modules_.back().value());
+    }
+  }
+};
+
+/// A `ModuleHolder` subclass for `ModuleDictImpl`.
+/// See the documentation for `ModuleDictImpl` class to learn what methods it
+/// provides, or the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(ModuleDict);
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/modulelist.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/modulelist.h
new file mode 100644
index 0000000000000000000000000000000000000000..b115abe1e9551852844b3da886d4b07f1d7e96c1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/modulelist.h
@@ -0,0 +1,274 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// A list of `Module`s that registers its elements.
+///
+/// \rst
+/// .. code-block:: cpp
+///
+///   torch::nn::ModuleList mlist(
+///     torch::nn::Linear(3, 4),
+///     torch::nn::BatchNorm1d(4),
+///     torch::nn::Dropout(0.5)
+///   );
+///
+///   for (const auto &module : *mlist) {
+///     module->pretty_print(std::cout);
+///   }
+///
+/// \endrst
+///
+/// Why should you use `ModuleList` instead of a simple `std::vector`? The value
+/// a `ModuleList` provides over manually calling a sequence of modules is that
+/// it allows treating the whole container *as a single module*, such that
+/// performing a transformation on the `ModuleList` applies to each of the
+/// modules it stores (which are each a registered submodule of the
+/// `ModuleList`). For example, calling
+/// `.to(torch::kCUDA)` on a `ModuleList` will move each module in the list to
+/// CUDA memory. For example:
+///
+/// \rst
+/// .. code-block:: cpp
+///
+///   torch::nn::ModuleList mlist(
+///     torch::nn::Linear(3, 4),
+///     torch::nn::BatchNorm1d(4),
+///     torch::nn::Dropout(0.5)
+///   );
+///
+///   // Convert all modules to CUDA.
+///   mlist->to(torch::kCUDA);
+///
+/// \endrst
+///
+/// Finally, `ModuleList` provides a lightweight container API, such as allowing
+/// iteration over submodules, positional access, adding a new module after
+/// construction via `push_back`, as well as joining two `ModuleList`s via
+/// `extend`.
+class ModuleListImpl : public Cloneable {
+ public:
+  using Iterator = std::vector>::iterator;
+  using ConstIterator = std::vector>::const_iterator;
+
+  ModuleListImpl() = default;
+
+  /// Constructs the `ModuleList` from a variadic list of modules.
+  template 
+  explicit ModuleListImpl(Modules&&... modules) {
+    modules_.reserve(sizeof...(Modules));
+    push_back_var(std::forward(modules)...);
+  }
+
+  /// Special cloning function for `ModuleList` because it does not use
+  /// `reset()`.
+  std::shared_ptr clone(
+      const std::optional& device = std::nullopt) const override {
+    auto clone = std::make_shared();
+    for (const auto& module : modules_) {
+      clone->push_back(module->clone(device));
+    }
+    return clone;
+  }
+
+  /// `reset()` is empty for `ModuleList`, since it does not have parameters of
+  /// its own.
+  void reset() override {}
+
+  /// Pretty prints the `ModuleList` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override {
+    stream << "torch::nn::ModuleList";
+  }
+
+  void push_back(std::shared_ptr module) {
+    modules_.push_back(std::move(module));
+    const auto index = modules_.size() - 1;
+    register_module(std::to_string(index), modules_[index]);
+  }
+
+  /// Adds a new `Module` to the `ModuleList` container, moving or copying
+  /// it into a `shared_ptr` internally. This method allows passing value types,
+  /// and letting the container deal with the boxing.
+  template >
+  void push_back(M&& module) {
+    using Type = typename std::remove_reference::type;
+    push_back(std::make_shared(std::forward(module)));
+  }
+
+  /// Unwraps the contained module of a `ModuleHolder` and adds it to the
+  /// `ModuleList`.
+  template 
+  void push_back(const ModuleHolder& module_holder) {
+    push_back(module_holder.ptr());
+  }
+
+  /// Iterates over the container and calls `push_back()` on each value.
+  template 
+  void extend(const Container& container) {
+    for (const auto& module : container) {
+      push_back(module);
+    }
+  }
+
+  /// Returns an iterator to the start of the `ModuleList`.
+  Iterator begin() {
+    return modules_.begin();
+  }
+
+  /// Returns a const iterator to the start of the `ModuleList`.
+  ConstIterator begin() const {
+    return modules_.begin();
+  }
+
+  /// Returns an iterator to the end of the `ModuleList`.
+  Iterator end() {
+    return modules_.end();
+  }
+
+  /// Returns a const iterator to the end of the `ModuleList`.
+  ConstIterator end() const {
+    return modules_.end();
+  }
+
+  /// Attempts to return the module at the given index as the requested type.
+  /// Throws an exception if the index is out of bounds or the types do not
+  /// match.
+  template 
+  T& at(size_t index) {
+    static_assert(
+        torch::detail::is_module::value,
+        "Can only call ModuleList::at with an nn::Module type");
+    TORCH_CHECK(index < size(), "Index out of range");
+    auto module = modules_[index]->as();
+    TORCH_CHECK(
+        module,
+        "Unable to cast module[",
+        index,
+        "] to ",
+        c10::demangle(typeid(T).name()));
+    return *module;
+  }
+
+  /// Attempts to return the module at the given index as the requested type.
+  /// Throws an exception if the index is out of bounds or the types do not
+  /// match.
+  template 
+  const T& at(size_t index) const {
+    static_assert(
+        torch::detail::is_module::value,
+        "Can only call ModuleList::at with an nn::Module type");
+    TORCH_CHECK(index < size(), "Index out of range");
+    const auto module = modules_[index]->as();
+    TORCH_CHECK(
+        module,
+        "Unable to cast module[",
+        index,
+        "] to ",
+        c10::demangle(typeid(T).name()));
+    return *module;
+  }
+
+  /// Attempts to return a `std::shared_ptr` whose dynamic type is that of the
+  /// underlying module at the given index. Throws an exception if the index is
+  /// out of bounds.
+  std::shared_ptr ptr(size_t index) const {
+    TORCH_CHECK(index < size(), "Index out of range");
+    return modules_[index];
+  }
+
+  /// Attempts to return a `std::shared_ptr` whose type is the one provided.
+  /// Throws an exception if the index is out of bounds or the types do not
+  /// match.
+  template 
+  std::shared_ptr ptr(size_t index) const {
+    static_assert(
+        torch::detail::is_module::value,
+        "Can only call ModuleList::ptr with an nn::Module type");
+    TORCH_CHECK(index < size(), "Index out of range");
+    return std::dynamic_pointer_cast(modules_[index]);
+  }
+
+  /// Like `ptr(index)`.
+  std::shared_ptr operator[](size_t index) const {
+    // This is the only method we can call without a type.
+    return ptr(index);
+  }
+
+  /// The current size of the `ModuleList` container.
+  size_t size() const noexcept {
+    return modules_.size();
+  }
+
+  /// True if there are no modules in the `ModuleList`.
+  bool is_empty() const noexcept {
+    return size() == 0;
+  }
+
+  void insert(size_t index, std::shared_ptr module) {
+    TORCH_CHECK(index <= size(), "Index out of range");
+
+    if (index == size())
+      push_back(std::move(module));
+    else {
+      modules_.insert(
+          modules_.begin() + Iterator::difference_type(index),
+          std::move(module));
+
+      for (const auto i : c10::irange(index, size() - 1)) {
+        (void)i; // Suppress unused variable warning
+        replace_module(std::to_string(index), modules_[index]);
+      }
+      register_module(std::to_string(size() - 1), modules_.back());
+    }
+  }
+
+  /// Unwraps the contained module of a `ModuleHolder` and inserts it in the
+  /// `ModuleList`.
+  template 
+  void insert(size_t index, const ModuleHolder& module_holder) {
+    insert(index, module_holder.ptr());
+  }
+
+  /// inserts a new `Module` to the `ModuleList` container, moving or copying
+  /// it into a `shared_ptr` internally. This method allows passing value types,
+  /// and letting the container deal with the boxing.
+  template >
+  void insert(size_t index, M&& module) {
+    using Type = typename std::remove_reference::type;
+    insert(index, std::make_shared(std::forward(module)));
+  }
+
+ private:
+  template 
+  void push_back_var(Head&& head, Tail&&... tail) {
+    push_back(std::forward(head));
+    // Recursively calls this method, until the parameter pack only thas this
+    // entry left. Then calls `push_back()` a final time (above).
+    push_back_var(std::forward(tail)...);
+  }
+
+  /// The base case, when the list of modules is empty.
+  void push_back_var() {}
+
+  // Box the AnyModules to give ModuleList reference semantics, like the rest of
+  // the API. Note that this is not required otherwise, this could just be a
+  // `vector`.
+  std::vector> modules_;
+};
+
+/// A `ModuleHolder` subclass for `ModuleListImpl`.
+/// See the documentation for `ModuleListImpl` class to learn what methods it
+/// provides, or the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(ModuleList);
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/named_any.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/named_any.h
new file mode 100644
index 0000000000000000000000000000000000000000..00d39de17f4012cbfb9aa4e56327d26c66f33bc2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/named_any.h
@@ -0,0 +1,94 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Stores a type erased `Module` with name.
+///
+/// The `NamedAnyModule` class enables the following API for constructing
+/// `nn::Sequential` with named submodules:
+/// \rst
+/// .. code-block:: cpp
+///
+///   struct M : torch::nn::Module {
+///     explicit M(int value_) : value(value_) {}
+///     int value;
+///     int forward() {
+///       return value;
+///     }
+///   };
+///
+///   Sequential sequential({
+///     {"m1", std::make_shared(1)},  // shared pointer to `Module` is
+///     supported {std::string("m2"), M(2)},  // `Module` is supported
+///     {"linear1", Linear(10, 3)}  // `ModuleHolder` is supported
+///   });
+/// \endrst
+class NamedAnyModule {
+ public:
+  /// Creates a `NamedAnyModule` from a (boxed) `Module`.
+  template 
+  NamedAnyModule(std::string name, std::shared_ptr module_ptr)
+      : NamedAnyModule(std::move(name), AnyModule(std::move(module_ptr))) {}
+
+  /// Creates a `NamedAnyModule` from a `Module`, moving or copying it
+  /// into a `shared_ptr` internally.
+  // NOTE: We need to use `std::remove_reference::type` to get rid of
+  // any reference components for make_unique.
+  template >
+  NamedAnyModule(std::string name, M&& module)
+      : NamedAnyModule(
+            std::move(name),
+            std::make_shared::type>(
+                std::forward(module))) {}
+
+  /// Creates a `NamedAnyModule` from a `Module` that is unwrapped from
+  /// a `ModuleHolder`.
+  template 
+  NamedAnyModule(std::string name, const ModuleHolder& module_holder)
+      : NamedAnyModule(std::move(name), module_holder.ptr()) {}
+
+  /// Creates a `NamedAnyModule` from a type-erased `AnyModule`.
+  NamedAnyModule(std::string name, AnyModule any_module)
+      : name_(std::move(name)), module_(std::move(any_module)) {}
+
+  /// Returns a reference to the name.
+  const std::string& name() const noexcept {
+    return name_;
+  }
+
+  /// Returns a reference to the module.
+  AnyModule& module() noexcept {
+    return module_;
+  }
+
+  /// Returns a const reference to the module.
+  const AnyModule& module() const noexcept {
+    return module_;
+  }
+
+ private:
+  std::string name_;
+  AnyModule module_;
+};
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/parameterdict.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/parameterdict.h
new file mode 100644
index 0000000000000000000000000000000000000000..f201825deb5bad0bc8640b6d977e156d10a74435
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/parameterdict.h
@@ -0,0 +1,148 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+class ParameterDictImpl : public Cloneable {
+ public:
+  using Iterator = OrderedDict::Iterator;
+  using ConstIterator = OrderedDict::ConstIterator;
+
+  ParameterDictImpl() = default;
+
+  explicit ParameterDictImpl(
+      const torch::OrderedDict& params) {
+    parameters_ = params;
+  }
+
+  /// `reset()` is empty for `ParameterDict`, since it does not have
+  /// parameters of its own.
+  void reset() override {}
+
+  /// Pretty prints the `ParameterDict` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override {
+    stream << "torch::nn::ParameterDict(" << std::endl;
+    for (const auto& pair : parameters_) {
+      stream << "(" << pair.key() << ")"
+             << ": Parameter containing: [" << pair.value().scalar_type()
+             << " of size " << pair.value().sizes() << "]";
+      ;
+      stream << std::endl;
+    }
+    stream << ")";
+  }
+
+  /// Insert the parameter along with the key into ParameterDict
+  /// The parameter is set to be require grad by default
+  Tensor& insert(std::string key, Tensor param) {
+    bool requires_grad = param.requires_grad();
+    return register_parameter(std::move(key), std::move(param), requires_grad);
+  }
+
+  /// Remove key from the ParameterDict and return its value, throw exception
+  /// if the key is not contained. Please check contains(key) before for a
+  /// non-throwing access.
+  Tensor pop(const std::string& key) {
+    torch::Tensor v = parameters_[key];
+    parameters_.erase(key);
+    return v;
+  }
+
+  /// Return the keys in the dict
+  ::std::vector keys() const {
+    return parameters_.keys();
+  }
+
+  /// Return the Values in the dict
+  ::std::vector values() const {
+    return parameters_.values();
+  }
+
+  /// Return an iterator to the start of ParameterDict
+  Iterator begin() {
+    return parameters_.begin();
+  }
+
+  /// Return a const iterator to the start of ParameterDict
+  ConstIterator begin() const {
+    return parameters_.begin();
+  }
+
+  /// Return an iterator to the end of ParameterDict
+  Iterator end() {
+    return parameters_.end();
+  }
+
+  /// Return a const iterator to the end of ParameterDict
+  ConstIterator end() const {
+    return parameters_.end();
+  }
+
+  /// Return the number of items currently stored in the ParameterDict
+  size_t size() const noexcept {
+    return parameters_.size();
+  }
+
+  /// Return true if the ParameterDict is empty, otherwise return false
+  bool empty() const noexcept {
+    return parameters_.is_empty();
+  }
+
+  /// Update the ParameterDict with the key-value pairs from
+  /// another ParameterDict, overwriting existing key
+  template 
+  void update(const Container& container) {
+    for (auto& item : container) {
+      parameters_[item.key()] = item.value();
+    }
+  }
+
+  /// Remove all parameters in the ParameterDict
+  void clear() {
+    parameters_.clear();
+  }
+
+  /// Check if the centain parameter with the key in the ParameterDict
+  bool contains(const std::string& key) const noexcept {
+    return parameters_.contains(key);
+  }
+
+  /// Returns the value associated with the given `key`. Throws an exception if
+  /// no such key is stored in the `ParameterDict`. Check contains(key) before
+  /// for a non-throwing way of access
+  const Tensor& get(const std::string& key) const {
+    return parameters_[key];
+  }
+
+  /// Returns the value associated with the given `key`. Throws an exception if
+  /// no such key is stored in the `ParameterDict`. Check contains(key) before
+  /// for a non-throwing way of access
+  Tensor& get(const std::string& key) {
+    return parameters_[key];
+  }
+
+  /// Returns the value associated with the given `key`. Throws an exception if
+  /// no such key is stored in the `ParameterDict`. Check contains(key) before
+  /// for a non-throwing way of access
+  Tensor& operator[](const std::string& key) {
+    return parameters_[key];
+  }
+
+  /// Returns the value associated with the given `key`. Throws an exception if
+  /// no such key is stored in the `ParameterDict`. Check contains(key) before
+  /// for a non-throwing way of access
+  const Tensor& operator[](const std::string& key) const {
+    return parameters_[key];
+  }
+};
+
+TORCH_MODULE(ParameterDict);
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/parameterlist.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/parameterlist.h
new file mode 100644
index 0000000000000000000000000000000000000000..cb816d1bb2a1e6493665a906036602eaac03170f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/parameterlist.h
@@ -0,0 +1,169 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+
+namespace torch {
+namespace nn {
+class ParameterListImpl : public Cloneable {
+ public:
+  using Iterator = typename std::vector<
+      OrderedDict::Item>::iterator;
+  using ConstIterator = typename std::vector<
+      OrderedDict::Item>::const_iterator;
+
+  ParameterListImpl() = default;
+
+  /// Constructs the `ParameterList` from a variadic list of ParameterList.
+  template 
+  explicit ParameterListImpl(Tensors&&... params) {
+    parameters_.reserve(sizeof...(Tensors));
+    push_back_var(std::forward(params)...);
+  }
+
+  template 
+  explicit ParameterListImpl(const Tensors&... params) {
+    parameters_.reserve(sizeof...(Tensors));
+    push_back_var(std::forward(params)...);
+  }
+
+  /// `reset()` is empty for `ParameterList`, since it does not have parameters
+  /// of its own.
+  void reset() override {}
+
+  /// Pretty prints the `ParameterList` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override {
+    stream << "torch::nn::ParameterList(" << std::endl;
+    for (const auto& pair : parameters_) {
+      stream << "(" << pair.key() << ")"
+             << ": Parameter containing: [" << pair.value().scalar_type()
+             << " of size " << pair.value().sizes() << "]";
+      ;
+      stream << std::endl;
+    }
+    stream << ")";
+  }
+
+  /// push the a given parameter at the end of the list
+  void append(torch::Tensor&& param) {
+    bool requires_grad = param.requires_grad();
+    register_parameter(
+        std::to_string(parameters_.size()), std::move(param), requires_grad);
+  }
+
+  /// push the a given parameter at the end of the list
+  void append(const torch::Tensor& param) {
+    bool requires_grad = param.requires_grad();
+    register_parameter(
+        std::to_string(parameters_.size()), param, requires_grad);
+  }
+
+  /// push the a given parameter at the end of the list
+  /// And the key of the pair will be discarded, only the value
+  /// will be added into the `ParameterList`
+  void append(const OrderedDict::Item& pair) {
+    register_parameter(
+        std::to_string(parameters_.size()),
+        pair.value(),
+        pair.value().requires_grad());
+  }
+
+  /// extend parameters from a container to the end of the list
+  template 
+  void extend(const Container& container) {
+    for (const auto& param : container) {
+      append(param);
+    }
+  }
+
+  /// Returns an iterator to the start of the ParameterList
+  /// the iterator returned will be type of `OrderedDict::Item`
+  Iterator begin() {
+    return parameters_.begin();
+  }
+
+  /// Returns a const iterator to the start of the ParameterList
+  /// the iterator returned will be type of `OrderedDict::Item`
+  ConstIterator begin() const {
+    return parameters_.begin();
+  }
+
+  /// Returns an iterator to the end of the ParameterList
+  /// the iterator returned will be type of `OrderedDict::Item`
+  Iterator end() {
+    return parameters_.end();
+  }
+
+  /// Returns a const iterator to the end of the ParameterList
+  /// the iterator returned will be type of `OrderedDict::Item`
+  ConstIterator end() const {
+    return parameters_.end();
+  }
+
+  /// Returns the value associated with the given `key`. Throws an exception if
+  /// no such key is stored in the `ParameterList`. Check contains(key) before
+  /// for a non-throwing way of access
+  at::Tensor& at(size_t idx) {
+    TORCH_CHECK(idx < size(), "Index out of range");
+    return parameters_[std::to_string(idx)];
+  }
+
+  /// Returns the value associated with the given `key`. Throws an exception if
+  /// no such key is stored in the `ParameterList`. Check contains(key) before
+  /// for a non-throwing way of access
+  const at::Tensor& at(size_t idx) const {
+    TORCH_CHECK(idx < size(), "Index out of range");
+    return parameters_[std::to_string(idx)];
+  }
+
+  /// Returns the value associated with the given `key`. Throws an exception if
+  /// no such key is stored in the `ParameterList`. Check contains(key) before
+  /// for a non-throwing way of access
+  at::Tensor& operator[](size_t idx) {
+    return at(idx);
+  }
+
+  /// Returns the value associated with the given `key`. Throws an exception if
+  /// no such key is stored in the `ParameterList`. Check contains(key) before
+  /// for a non-throwing way of access
+  const at::Tensor& operator[](size_t idx) const {
+    return at(idx);
+  }
+
+  /// Return the size of the ParameterList
+  size_t size() const noexcept {
+    return parameters_.size();
+  }
+  /// True if the ParameterList is empty
+  bool is_empty() const noexcept {
+    return parameters_.is_empty();
+  }
+
+  /// Overload the +=, so that two ParameterList could be incrementally added
+  template 
+  Container& operator+=(const Container& other) {
+    extend(other);
+    return *this;
+  }
+
+ private:
+  template 
+  void push_back_var(Head&& head, Tail&&... tail) {
+    append(std::forward(head));
+    // Recursively calls this method, until the parameter pack only thas this
+    // entry left. Then calls `push_back()` a final time (above).
+    push_back_var(std::forward(tail)...);
+  }
+
+  /// The base case, when the list of modules is empty.
+  void push_back_var() {}
+};
+TORCH_MODULE(ParameterList);
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/sequential.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/sequential.h
new file mode 100644
index 0000000000000000000000000000000000000000..6ee12bc477d8293ba6095c3e3b38778c99ce4f43
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/container/sequential.h
@@ -0,0 +1,388 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// A list of `Module`s that acts as a `Module` itself.
+///
+/// A `Sequential` is fundamentally a list of `Module`s, each with a `forward()`
+/// method. `Sequential` provides a `forward()` method of its own, which accepts
+/// any input and forwards it to the first module it stores. It then "chains"
+/// outputs to inputs sequentially for each subsequent module, finally returning
+/// the output of the last module. For example:
+///
+/// \rst
+/// .. code-block:: cpp
+///
+///   torch::nn::Sequential seq(
+///     torch::nn::Linear(3, 4),
+///     torch::nn::BatchNorm1d(4),
+///     torch::nn::Dropout(0.5)
+///   );
+///
+///   auto output = seq->forward(torch::ones(3));
+///
+/// \endrst
+///
+/// This can conceptually be thought of as the following loop (using Python as
+/// pseudocode):
+///
+/// \rst
+/// .. code-block:: python
+///
+///   def forward(sequential, input):
+///     for module in sequential:
+///       input = module(input)
+///     return input
+///
+/// \endrst
+///
+/// Why should you use `Sequential` instead of a simple `std::vector`? The value
+/// a `Sequential` provides over manually calling a sequence of modules is that
+/// it allows treating the whole container *as a single module*, such that
+/// performing a transformation on the `Sequential` applies to each of the
+/// modules it stores (which are each a registered submodule of the
+/// `Sequential`). For example, calling
+/// `.to(torch::kCUDA)` on a `Sequential` will move each module in the list to
+/// CUDA memory. For example:
+///
+/// \rst
+/// .. code-block:: cpp
+///
+///   torch::nn::Sequential seq(
+///     torch::nn::Linear(3, 4),
+///     torch::nn::BatchNorm1d(4),
+///     torch::nn::Dropout(0.5)
+///   );
+///
+///   // Convert all modules to CUDA.
+///   seq->to(torch::kCUDA);
+///
+/// \endrst
+///
+/// Finally, `Sequential` provides a lightweight container API, such as allowing
+/// iteration over submodules, positional access, adding a new module after
+/// construction via `push_back`, as well as joining two `Sequential`s via
+/// `extend`.
+///
+/// \rst
+/// .. attention::
+///   One current limitation of `Sequential` is that all except the first module
+///   must accept a single argument. If your modules need to take multiple
+///   arguments, you should define them to take and return tuples.
+/// \endrst
+class SequentialImpl : public Cloneable {
+ public:
+  using Iterator = std::vector::iterator;
+  using ConstIterator = std::vector::const_iterator;
+
+  SequentialImpl() = default;
+
+  /// Constructs the `Sequential` from a variadic list of modules.
+  template 
+  explicit SequentialImpl(Modules&&... modules) {
+    modules_.reserve(sizeof...(Modules));
+    push_back(std::forward(modules)...);
+  }
+
+  /// Constructs the `Sequential` from an `OrderedDict` of named `AnyModule`s.
+  explicit SequentialImpl(
+      torch::OrderedDict&& ordered_dict) {
+    modules_.reserve(ordered_dict.size());
+    for (auto& item : ordered_dict) {
+      push_back(item.key(), std::move(item.value()));
+    }
+  }
+
+  /// Constructs the `Sequential` from a braced-init-list of named `AnyModule`s.
+  /// It enables the following use case:
+  /// `Sequential sequential({{"m1", M(1)}, {"m2", M(2)}})`
+  explicit SequentialImpl(std::initializer_list named_modules) {
+    modules_.reserve(named_modules.size());
+    for (const auto& named_module : named_modules) {
+      push_back(named_module.name(), named_module.module());
+    }
+  }
+
+  /// Special cloning function for `Sequential` because it does not use
+  /// `reset()`.
+  std::shared_ptr clone(
+      const std::optional& device = std::nullopt) const override {
+    auto clone = std::make_shared();
+    for (const auto& module : modules_) {
+      clone->push_back(module.clone(device));
+    }
+    return clone;
+  }
+
+  /// `reset()` is empty for `Sequential`, since it does not have parameters of
+  /// its own.
+  void reset() override {}
+
+  /// Pretty prints the `Sequential` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override {
+    stream << "torch::nn::Sequential";
+  }
+
+  /// Feeds `inputs` to the first module and then chains outputs to inputs,
+  /// returning the last output.
+  ///
+  /// Conceptually the following loop in Python:
+  ///
+  /// \rst
+  /// .. code-block:: python
+  ///
+  ///   def forward(sequential, input):
+  ///     for module in sequential:
+  ///       input = module(input)
+  ///     return input
+  ///
+  /// \endrst
+  ///
+  /// The return type is taken as the first template parameter. It defaults to
+  /// `Tensor`. If the last module in the `Sequential` returns another type `T`,
+  /// you should call `forward(inputs)` instead of just `forward(inputs)`:
+  ///
+  /// \rst
+  /// .. code-block:: cpp
+  ///
+  ///   torch::Tensor tensor = sequential1->forward(inputs);
+  ///   int integer = sequential2->forward(inputs);
+  ///   float value = sequential3->forward(inputs);
+  ///
+  /// \endrst
+  template 
+  ReturnType forward(InputTypes&&... inputs) {
+    TORCH_CHECK(!is_empty(), "Cannot call forward() on an empty Sequential");
+
+    auto iterator = modules_.begin();
+    auto input = iterator->any_forward(std::forward(inputs)...);
+
+    for (++iterator; iterator != modules_.end(); ++iterator) {
+      input = iterator->any_forward(std::move(input));
+    }
+
+    // Check the return value and give a nice error message if the requested
+    // return type was incorrect.
+    if (auto* return_value = input.template try_get()) {
+      return std::move(*return_value);
+    }
+    AT_ERROR(
+        "The type of the return value is ",
+        c10::demangle(input.type_info().name()),
+        ", but you asked for type ",
+        c10::demangle(typeid(ReturnType).name()));
+  }
+
+  /// Adds a new (boxed) `Module` to the `Sequential` container.
+  template 
+  void push_back(std::shared_ptr module_ptr) {
+    push_back(std::to_string(modules_.size()), std::move(module_ptr));
+  }
+
+  /// Adds a new named (boxed) `Module` to the `Sequential` container.
+  template 
+  void push_back(std::string name, std::shared_ptr module_ptr) {
+    push_back(std::move(name), AnyModule(std::move(module_ptr)));
+  }
+
+  /// Adds a new `Module` to the `Sequential` container, moving or copying it
+  /// into a `shared_ptr` internally. This method allows passing value types,
+  /// and letting the container deal with the boxing. This means you can write
+  /// `Sequential(Module(3, 4))` instead of
+  /// `Sequential(std::make_shared(3, 4))`.
+  template >
+  void push_back(M&& module) {
+    push_back(std::to_string(modules_.size()), std::forward(module));
+  }
+
+  /// Adds a new named `Module` to the `Sequential` container, moving or copying
+  /// it into a `shared_ptr` internally. This method allows passing value types,
+  /// and letting the container deal with the boxing.
+  template >
+  void push_back(std::string name, M&& module) {
+    using Type = typename std::remove_reference_t;
+    push_back(std::move(name), std::make_shared(std::forward(module)));
+  }
+
+  /// Unwraps the contained module of a `ModuleHolder` and adds it to the
+  /// `Sequential`.
+  template 
+  void push_back(const ModuleHolder& module_holder) {
+    push_back(std::to_string(modules_.size()), module_holder);
+  }
+
+  /// Unwraps the contained named module of a `ModuleHolder` and adds it to the
+  /// `Sequential`.
+  template 
+  void push_back(std::string name, const ModuleHolder& module_holder) {
+    push_back(std::move(name), module_holder.ptr());
+  }
+
+  /// Iterates over the container and calls `push_back()` on each value.
+  template 
+  void extend(const Container& container) {
+    for (const auto& module : container) {
+      push_back(module);
+    }
+  }
+
+  /// Adds a type-erased `AnyModule` to the `Sequential`.
+  void push_back(AnyModule any_module) {
+    push_back(std::to_string(modules_.size()), std::move(any_module));
+  }
+
+  void push_back(std::string name, AnyModule any_module) {
+    modules_.push_back(std::move(any_module));
+    const auto index = modules_.size() - 1;
+    register_module(std::move(name), modules_[index].ptr());
+  }
+
+  /// Returns an iterator to the start of the `Sequential`.
+  Iterator begin() {
+    return modules_.begin();
+  }
+
+  /// Returns a const iterator to the start of the `Sequential`.
+  ConstIterator begin() const {
+    return modules_.begin();
+  }
+
+  /// Returns an iterator to the end of the `Sequential`.
+  Iterator end() {
+    return modules_.end();
+  }
+
+  /// Returns a const iterator to the end of the `Sequential`.
+  ConstIterator end() const {
+    return modules_.end();
+  }
+
+  /// Attempts to return the module at the given index as the requested type.
+  /// Throws an exception if the index is out of bounds or the types do not
+  /// match.
+  template 
+  T& at(size_t index) {
+    static_assert(
+        torch::detail::is_module::value,
+        "Can only call Sequential::at with an nn::Module type");
+    TORCH_CHECK(index < size(), "Index out of range");
+    return modules_[index].get();
+  }
+
+  /// Attempts to return the module at the given index as the requested type.
+  /// Throws an exception if the index is out of bounds or the types do not
+  /// match.
+  template 
+  const T& at(size_t index) const {
+    static_assert(
+        torch::detail::is_module::value,
+        "Can only call Sequential::at with an nn::Module type");
+    TORCH_CHECK(index < size(), "Index out of range");
+    return modules_[index].get();
+  }
+
+  /// Attempts to return a `std::shared_ptr` whose dynamic type is that of the
+  /// underlying module at the given index. Throws an exception if the index is
+  /// out of bounds.
+  std::shared_ptr ptr(size_t index) const {
+    TORCH_CHECK(index < size(), "Index out of range");
+    return modules_[index].ptr();
+  }
+
+  /// Attempts to return a `std::shared_ptr` whose type is the one provided.
+  /// Throws an exception if the index is out of bounds or the types do not
+  /// match.
+  template 
+  std::shared_ptr ptr(size_t index) const {
+    static_assert(
+        torch::detail::is_module::value,
+        "Can only call Sequential::ptr with an nn::Module type");
+    TORCH_CHECK(index < size(), "Index out of range");
+    return modules_[index].ptr();
+  }
+
+  /// Like `ptr(index)`.
+  std::shared_ptr operator[](size_t index) const {
+    // This is the only method we can call without a type.
+    return ptr(index);
+  }
+
+  /// The current size of the `Sequential` container.
+  size_t size() const noexcept {
+    return modules_.size();
+  }
+
+  /// True if there are no modules in the `Sequential`.
+  bool is_empty() const noexcept {
+    return size() == 0;
+  }
+
+ private:
+  /// Takes a First *and* Second parameter, to avoid ambiguity when a parameter
+  /// pack has only one type, in which case the template would be preferred,
+  /// even if the other `push_back` functions are better fits (e.g. `unique_ptr`
+  /// -> `shared_ptr` overload).
+  /// NOTE: We explicitly avoid matching this template with
+  /// `push_back(std::string("name"), module)` or `push_back("name", module)`,
+  /// since they should be handled by their respective `push_back` functions.
+  template <
+      typename First,
+      typename Second,
+      typename... Rest,
+      typename = std::enable_if_t<
+          !std::is_same_v &&
+          // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
+          !std::is_same_v, std::decay_t>>>
+  void push_back(First&& first, Second&& second, Rest&&... rest) {
+    push_back(std::forward(first));
+    // Recursively calls this method, until the parameter pack only thas this
+    // entry left. Then calls `push_back()` a final time (above).
+    push_back(std::forward(second), std::forward(rest)...);
+  }
+
+  /// The base case, when the list of modules is empty.
+  void push_back() {}
+
+  // Box the AnyModules to give Sequential reference semantics, like the rest of
+  // the API. Note that this is not required otherwise, this could just be a
+  // `vector`.
+  std::vector modules_;
+};
+
+/// A `ModuleHolder` subclass for `SequentialImpl`.
+/// See the documentation for `SequentialImpl` class to learn what methods it
+/// provides, or the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+class Sequential : public torch::nn::ModuleHolder {
+ public:
+  using torch::nn::ModuleHolder::ModuleHolder;
+
+  Sequential() : ModuleHolder() {}
+
+  /// Constructs the `Sequential` from a braced-init-list of named `AnyModule`s.
+  /// It enables the following use case:
+  /// `Sequential sequential({{"m1", M(1)}, {"m2", M(2)}})`
+  Sequential(std::initializer_list named_modules)
+      : ModuleHolder(std::make_shared(named_modules)) {}
+};
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/conv.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/conv.h
new file mode 100644
index 0000000000000000000000000000000000000000..e44fd44b954abe93cdc122238f4c5cee45a5f8a1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/conv.h
@@ -0,0 +1,451 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Base class for all (dimension-specialized) convolution modules.
+template 
+class ConvNdImpl : public torch::nn::Cloneable {
+ public:
+  explicit ConvNdImpl(detail::ConvNdOptions options_)
+      : options(std::move(options_)) {
+    // NOLINTNEXTLINE(clang-analyzer-optin.cplusplus.VirtualCall)
+    reset();
+  }
+
+  void reset() override {
+    TORCH_CHECK(
+        options.in_channels() > 0 && options.groups() > 0 &&
+            options.out_channels() > 0,
+        "in_channels, groups and out_channels must be a positive integer.");
+    TORCH_CHECK(
+        options.in_channels() % options.groups() == 0,
+        "in_channels must be divisible by groups");
+    TORCH_CHECK(
+        options.out_channels() % options.groups() == 0,
+        "out_channels must be divisible by groups");
+
+    std::visit(
+        c10::overloaded(
+            [&](enumtype::kValid) {
+              _reversed_padding_repeated_twice.resize(2 * D);
+              std::fill_n(_reversed_padding_repeated_twice.begin(), 2 * D, 0);
+            },
+            [&](enumtype::kSame) {
+              for (const auto i : c10::irange(D)) {
+                const auto stride = (*options.stride())[i];
+                TORCH_CHECK(
+                    stride == 1,
+                    "padding='same' is not supported for strided convolutions");
+              }
+
+              _reversed_padding_repeated_twice.resize(2 * D);
+              for (const auto i : c10::irange(D)) {
+                const auto dilation = (*options.dilation())[i];
+                const auto kernel_size = (*options.kernel_size())[i];
+                const auto total_padding = dilation * (kernel_size - 1);
+                auto left_pad = total_padding / 2;
+                auto right_pad = total_padding - left_pad;
+                _reversed_padding_repeated_twice[2 * i] = left_pad;
+                _reversed_padding_repeated_twice[2 * i + 1] = right_pad;
+              }
+            },
+            [&](const ExpandingArray& pad) {
+              _reversed_padding_repeated_twice =
+                  torch::nn::modules::utils::_reverse_repeat_vector(pad, 2);
+            }),
+        options.padding());
+
+    if (options.transposed()) {
+      std::vector weight_sizes = {
+          options.in_channels(), options.out_channels() / options.groups()};
+      weight_sizes.insert(
+          weight_sizes.end(),
+          (*options.kernel_size()).begin(),
+          (*options.kernel_size()).end());
+      weight = this->register_parameter("weight", torch::empty(weight_sizes));
+    } else {
+      std::vector weight_sizes = {
+          options.out_channels(), options.in_channels() / options.groups()};
+      weight_sizes.insert(
+          weight_sizes.end(),
+          (*options.kernel_size()).begin(),
+          (*options.kernel_size()).end());
+      weight = this->register_parameter("weight", torch::empty(weight_sizes));
+    }
+
+    if (options.bias()) {
+      bias = this->register_parameter(
+          "bias", torch::empty({options.out_channels()}));
+    } else {
+      this->register_parameter("bias", Tensor(), /*requires_grad=*/false);
+    }
+
+    reset_parameters();
+  }
+
+  void reset_parameters() {
+    init::kaiming_uniform_(
+        weight,
+        /*a=*/std::sqrt(5)); // NOLINT(cppcoreguidelines-avoid-magic-numbers)
+
+    if (bias.defined()) {
+      auto [fan_in, fan_out] = init::_calculate_fan_in_and_fan_out(weight);
+      auto bound = 1 / std::sqrt(fan_in);
+      init::uniform_(bias, -bound, bound);
+    }
+  }
+
+  /// Pretty prints the `Conv{1,2,3}d` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override {
+    stream << "torch::nn::Conv" << D << "d"
+           << "(" << options.in_channels() << ", " << options.out_channels()
+           << ", kernel_size=" << options.kernel_size()
+           << ", stride=" << options.stride();
+    std::visit(
+        c10::overloaded(
+            [&](enumtype::kValid) { stream << ", padding='valid'"; },
+            [&](enumtype::kSame) { stream << ", padding='same'"; },
+            [&](const ExpandingArray& pad) {
+              if (*pad != *ExpandingArray(0)) {
+                stream << ", padding=" << pad;
+              }
+            }),
+        options.padding());
+    if (*options.dilation() != *ExpandingArray(1)) {
+      stream << ", dilation=" << options.dilation();
+    }
+    if (*options.output_padding() != *ExpandingArray(0)) {
+      stream << ", output_padding=" << options.output_padding();
+    }
+    if (options.groups() != 1) {
+      stream << ", groups=" << options.groups();
+    }
+    if (!options.bias()) {
+      stream << ", bias=" << std::boolalpha << false;
+    }
+    if (!std::get_if(&options.padding_mode())) {
+      stream << ", padding_mode="
+             << enumtype::get_enum_name(options.padding_mode());
+    }
+    stream << ")";
+  }
+
+  /// The options with which this `Module` was constructed.
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  detail::ConvNdOptions options;
+
+  /// The learned kernel (or "weight").
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  Tensor weight;
+
+  /// The learned bias. Only defined if the `bias` option was true.
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  Tensor bias;
+
+ protected:
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  std::vector _reversed_padding_repeated_twice;
+};
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Conv1d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies convolution over a 1-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.Conv1d to learn about
+/// the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::Conv1dOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// Conv1d model(Conv1dOptions(3, 2, 3).stride(1).bias(false));
+/// ```
+class TORCH_API Conv1dImpl : public ConvNdImpl<1, Conv1dImpl> {
+ public:
+  Conv1dImpl(
+      int64_t input_channels,
+      int64_t output_channels,
+      ExpandingArray<1> kernel_size)
+      : Conv1dImpl(
+            Conv1dOptions(input_channels, output_channels, kernel_size)) {}
+  explicit Conv1dImpl(Conv1dOptions options_);
+  Tensor forward(const Tensor& input);
+};
+
+/// A `ModuleHolder` subclass for `Conv1dImpl`.
+/// See the documentation for `Conv1dImpl` class to learn what methods it
+/// provides, and examples of how to use `Conv1d` with
+/// `torch::nn::Conv1dOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(Conv1d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Conv2d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies convolution over a 2-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.Conv2d to learn about
+/// the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::Conv2dOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// Conv2d model(Conv2dOptions(3, 2, 3).stride(1).bias(false));
+/// ```
+class TORCH_API Conv2dImpl : public ConvNdImpl<2, Conv2dImpl> {
+ public:
+  Conv2dImpl(
+      int64_t input_channels,
+      int64_t output_channels,
+      ExpandingArray<2> kernel_size)
+      : Conv2dImpl(
+            Conv2dOptions(input_channels, output_channels, kernel_size)) {}
+  explicit Conv2dImpl(Conv2dOptions options_);
+  Tensor forward(const Tensor& input);
+
+ protected:
+  Tensor _conv_forward(const Tensor& input, const Tensor& weight);
+};
+
+/// A `ModuleHolder` subclass for `Conv2dImpl`.
+/// See the documentation for `Conv2dImpl` class to learn what methods it
+/// provides, and examples of how to use `Conv2d` with
+/// `torch::nn::Conv2dOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(Conv2d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Conv3d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies convolution over a 3-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.Conv3d to learn about
+/// the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::Conv3dOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// Conv3d model(Conv3dOptions(3, 2, 3).stride(1).bias(false));
+/// ```
+class TORCH_API Conv3dImpl : public ConvNdImpl<3, Conv3dImpl> {
+ public:
+  Conv3dImpl(
+      int64_t input_channels,
+      int64_t output_channels,
+      ExpandingArray<3> kernel_size)
+      : Conv3dImpl(
+            Conv3dOptions(input_channels, output_channels, kernel_size)) {}
+  explicit Conv3dImpl(Conv3dOptions options_);
+  Tensor forward(const Tensor& input);
+};
+
+/// A `ModuleHolder` subclass for `Conv3dImpl`.
+/// See the documentation for `Conv3dImpl` class to learn what methods it
+/// provides, and examples of how to use `Conv3d` with
+/// `torch::nn::Conv3dOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(Conv3d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~ ConvTranspose ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Base class for all (dimension-specialized) convolution transpose modules.
+template 
+class ConvTransposeNdImpl : public ConvNdImpl {
+ public:
+  using torch::nn::ConvNdImpl::ConvNdImpl;
+  explicit ConvTransposeNdImpl(detail::ConvNdOptions options_)
+      : ConvNdImpl(options_) {
+    TORCH_INTERNAL_ASSERT(
+        std::holds_alternative>(this->options.padding()),
+        "ConvTranspose padding cannot be a string");
+  }
+
+  /// Pretty prints the `ConvTranspose{1,2,3}d` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override {
+    stream << "torch::nn::ConvTranspose" << D << "d"
+           << "(" << this->options.in_channels() << ", "
+           << this->options.out_channels()
+           << ", kernel_size=" << this->options.kernel_size()
+           << ", stride=" << this->options.stride();
+    const auto& pad = padding();
+    if (*pad != *ExpandingArray(0)) {
+      stream << ", padding=" << pad;
+    }
+    if (*this->options.dilation() != *ExpandingArray(1)) {
+      stream << ", dilation=" << this->options.dilation();
+    }
+    if (*this->options.output_padding() != *ExpandingArray(0)) {
+      stream << ", output_padding=" << this->options.output_padding();
+    }
+    if (this->options.groups() != 1) {
+      stream << ", groups=" << this->options.groups();
+    }
+    if (!this->options.bias()) {
+      stream << ", bias=" << std::boolalpha << false;
+    }
+    if (!std::get_if(&this->options.padding_mode())) {
+      stream << ", padding_mode="
+             << enumtype::get_enum_name(this->options.padding_mode());
+    }
+    stream << ")";
+  }
+
+ protected:
+  const ExpandingArray& padding() const {
+    return std::get>(this->options.padding());
+  }
+
+  std::vector _output_padding(
+      const Tensor& input,
+      const std::optional& output_size,
+      const ExpandingArray& stride,
+      const ExpandingArray& padding,
+      const ExpandingArray& kernel_size);
+};
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ConvTranspose1d
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the ConvTranspose1d function.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.ConvTranspose1d to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::ConvTranspose1dOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// ConvTranspose1d model(ConvTranspose1dOptions(3, 2,
+/// 3).stride(1).bias(false));
+/// ```
+class TORCH_API ConvTranspose1dImpl
+    : public ConvTransposeNdImpl<1, ConvTranspose1dImpl> {
+ public:
+  ConvTranspose1dImpl(
+      int64_t input_channels,
+      int64_t output_channels,
+      ExpandingArray<1> kernel_size)
+      : ConvTranspose1dImpl(ConvTranspose1dOptions(
+            input_channels,
+            output_channels,
+            kernel_size)) {}
+  explicit ConvTranspose1dImpl(ConvTranspose1dOptions options_);
+  Tensor forward(
+      const Tensor& input,
+      const std::optional& output_size = std::nullopt);
+
+ protected:
+  FORWARD_HAS_DEFAULT_ARGS({1, AnyValue(std::optional())})
+};
+
+/// A `ModuleHolder` subclass for `ConvTranspose1dImpl`.
+/// See the documentation for `ConvTranspose1dImpl` class to learn what methods
+/// it provides, and examples of how to use `ConvTranspose1d` with
+/// `torch::nn::ConvTranspose1dOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(ConvTranspose1d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ConvTranspose2d
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the ConvTranspose2d function.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.ConvTranspose2d to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::ConvTranspose2dOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// ConvTranspose2d model(ConvTranspose2dOptions(3, 2,
+/// 3).stride(1).bias(false));
+/// ```
+class TORCH_API ConvTranspose2dImpl
+    : public ConvTransposeNdImpl<2, ConvTranspose2dImpl> {
+ public:
+  ConvTranspose2dImpl(
+      int64_t input_channels,
+      int64_t output_channels,
+      ExpandingArray<2> kernel_size)
+      : ConvTranspose2dImpl(ConvTranspose2dOptions(
+            input_channels,
+            output_channels,
+            kernel_size)) {}
+  explicit ConvTranspose2dImpl(ConvTranspose2dOptions options_);
+  Tensor forward(
+      const Tensor& input,
+      const std::optional& output_size = std::nullopt);
+
+ protected:
+  FORWARD_HAS_DEFAULT_ARGS({1, AnyValue(std::optional())})
+};
+
+/// A `ModuleHolder` subclass for `ConvTranspose2dImpl`.
+/// See the documentation for `ConvTranspose2dImpl` class to learn what methods
+/// it provides, and examples of how to use `ConvTranspose2d` with
+/// `torch::nn::ConvTranspose2dOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(ConvTranspose2d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ConvTranspose3d
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the ConvTranspose3d function.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.ConvTranspose3d to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::ConvTranspose3dOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// ConvTranspose3d model(ConvTranspose3dOptions(2, 2,
+/// 2).stride(1).bias(false));
+/// ```
+class TORCH_API ConvTranspose3dImpl
+    : public ConvTransposeNdImpl<3, ConvTranspose3dImpl> {
+ public:
+  ConvTranspose3dImpl(
+      int64_t input_channels,
+      int64_t output_channels,
+      ExpandingArray<3> kernel_size)
+      : ConvTranspose3dImpl(ConvTranspose3dOptions(
+            input_channels,
+            output_channels,
+            kernel_size)) {}
+  explicit ConvTranspose3dImpl(ConvTranspose3dOptions options_);
+  Tensor forward(
+      const Tensor& input,
+      const std::optional& output_size = std::nullopt);
+
+ protected:
+  FORWARD_HAS_DEFAULT_ARGS({1, AnyValue(std::optional())})
+};
+
+/// A `ModuleHolder` subclass for `ConvTranspose3dImpl`.
+/// See the documentation for `ConvTranspose3dImpl` class to learn what methods
+/// it provides, and examples of how to use `ConvTranspose3d` with
+/// `torch::nn::ConvTranspose3dOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(ConvTranspose3d);
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/distance.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/distance.h
new file mode 100644
index 0000000000000000000000000000000000000000..774b01d7e447cbe566da9f04978cebbabf730110
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/distance.h
@@ -0,0 +1,86 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Returns the cosine similarity between :math:`x_1` and :math:`x_2`, computed
+/// along `dim`.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.CosineSimilarity to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::CosineSimilarityOptions` class to
+/// learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// CosineSimilarity model(CosineSimilarityOptions().dim(0).eps(0.5));
+/// ```
+class TORCH_API CosineSimilarityImpl : public Cloneable {
+ public:
+  explicit CosineSimilarityImpl(const CosineSimilarityOptions& options_ = {});
+
+  void reset() override;
+
+  /// Pretty prints the `CosineSimilarity` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(const Tensor& input1, const Tensor& input2);
+
+  /// The options with which this `Module` was constructed.
+  CosineSimilarityOptions options;
+};
+
+/// A `ModuleHolder` subclass for `CosineSimilarityImpl`.
+/// See the documentation for `CosineSimilarityImpl` class to learn what methods
+/// it provides, and examples of how to use `CosineSimilarity` with
+/// `torch::nn::CosineSimilarityOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(CosineSimilarity);
+
+// ============================================================================
+
+/// Returns the batchwise pairwise distance between vectors :math:`v_1`,
+/// :math:`v_2` using the p-norm.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.PairwiseDistance to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::PairwiseDistanceOptions` class to
+/// learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// PairwiseDistance
+/// model(PairwiseDistanceOptions().p(3).eps(0.5).keepdim(true));
+/// ```
+class TORCH_API PairwiseDistanceImpl : public Cloneable {
+ public:
+  explicit PairwiseDistanceImpl(const PairwiseDistanceOptions& options_ = {});
+
+  void reset() override;
+
+  /// Pretty prints the `PairwiseDistance` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(const Tensor& input1, const Tensor& input2);
+
+  /// The options with which this `Module` was constructed.
+  PairwiseDistanceOptions options;
+};
+
+/// A `ModuleHolder` subclass for `PairwiseDistanceImpl`.
+/// See the documentation for `PairwiseDistanceImpl` class to learn what methods
+/// it provides, and examples of how to use `PairwiseDistance` with
+/// `torch::nn::PairwiseDistanceOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(PairwiseDistance);
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/dropout.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/dropout.h
new file mode 100644
index 0000000000000000000000000000000000000000..a2ebabded6fabba8a105eacbdbb61e0377f98e26
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/dropout.h
@@ -0,0 +1,190 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+namespace detail {
+
+template 
+class _DropoutNd : public torch::nn::Cloneable {
+ public:
+  _DropoutNd(double p) : _DropoutNd(DropoutOptions().p(p)){};
+
+  explicit _DropoutNd(const DropoutOptions& options_ = {}) : options(options_) {
+    // NOLINTNEXTLINE(clang-analyzer-optin.cplusplus.VirtualCall)
+    reset();
+  }
+
+  void reset() override {
+    TORCH_CHECK(
+        options.p() >= 0. && options.p() <= 1.,
+        "dropout probability has to be between 0 and 1, but got ",
+        options.p());
+  }
+
+  /// The options with which this `Module` was constructed.
+  DropoutOptions options;
+};
+
+} // namespace detail
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Dropout ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies dropout over a 1-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.Dropout to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::DropoutOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// Dropout model(DropoutOptions().p(0.42).inplace(true));
+/// ```
+class TORCH_API DropoutImpl : public detail::_DropoutNd {
+ public:
+  using detail::_DropoutNd::_DropoutNd;
+
+  Tensor forward(Tensor input);
+
+  /// Pretty prints the `Dropout` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+};
+
+/// A `ModuleHolder` subclass for `DropoutImpl`.
+/// See the documentation for `DropoutImpl` class to learn what methods it
+/// provides, and examples of how to use `Dropout` with
+/// `torch::nn::DropoutOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(Dropout);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Dropout2d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies dropout over a 2-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.Dropout2d to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::Dropout2dOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// Dropout2d model(Dropout2dOptions().p(0.42).inplace(true));
+/// ```
+class TORCH_API Dropout2dImpl : public detail::_DropoutNd {
+ public:
+  using detail::_DropoutNd::_DropoutNd;
+
+  Tensor forward(Tensor input);
+
+  /// Pretty prints the `Dropout2d` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+};
+
+/// A `ModuleHolder` subclass for `Dropout2dImpl`.
+/// See the documentation for `Dropout2dImpl` class to learn what methods it
+/// provides, and examples of how to use `Dropout2d` with
+/// `torch::nn::Dropout2dOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(Dropout2d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Dropout3d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies dropout over a 3-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.Dropout3d to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::Dropout3dOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// Dropout3d model(Dropout3dOptions().p(0.42).inplace(true));
+/// ```
+class TORCH_API Dropout3dImpl : public detail::_DropoutNd {
+ public:
+  using detail::_DropoutNd::_DropoutNd;
+
+  Tensor forward(Tensor input);
+
+  /// Pretty prints the `Dropout3d` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+};
+
+/// A `ModuleHolder` subclass for `Dropout3dImpl`.
+/// See the documentation for `Dropout3dImpl` class to learn what methods it
+/// provides, and examples of how to use `Dropout3d` with
+/// `torch::nn::Dropout3dOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(Dropout3d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ AlphaDropout ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies Alpha Dropout over the input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.AlphaDropout to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::AlphaDropoutOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// AlphaDropout model(AlphaDropoutOptions(0.2).inplace(true));
+/// ```
+class TORCH_API AlphaDropoutImpl : public detail::_DropoutNd {
+ public:
+  using detail::_DropoutNd::_DropoutNd;
+
+  Tensor forward(const Tensor& input);
+
+  /// Pretty prints the `AlphaDropout` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+};
+
+/// A `ModuleHolder` subclass for `AlphaDropoutImpl`.
+/// See the documentation for `AlphaDropoutImpl` class to learn what methods it
+/// provides, and examples of how to use `AlphaDropout` with
+/// `torch::nn::AlphaDropoutOptions`. See the documentation for `ModuleHolder`
+/// to learn about PyTorch's module storage semantics.
+TORCH_MODULE(AlphaDropout);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FeatureAlphaDropout
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// See the documentation for `torch::nn::FeatureAlphaDropoutOptions` class to
+/// learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// FeatureAlphaDropout model(FeatureAlphaDropoutOptions(0.2).inplace(true));
+/// ```
+class TORCH_API FeatureAlphaDropoutImpl
+    : public detail::_DropoutNd {
+ public:
+  using detail::_DropoutNd::_DropoutNd;
+
+  Tensor forward(const Tensor& input);
+
+  /// Pretty prints the `FeatureAlphaDropout` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+};
+
+/// A `ModuleHolder` subclass for `FeatureAlphaDropoutImpl`.
+/// See the documentation for `FeatureAlphaDropoutImpl` class to learn what
+/// methods it provides, and examples of how to use `FeatureAlphaDropout` with
+/// `torch::nn::FeatureAlphaDropoutOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(FeatureAlphaDropout);
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/embedding.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/embedding.h
new file mode 100644
index 0000000000000000000000000000000000000000..ff61941d3a35baea92ccaaee90210516dc7c0afe
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/embedding.h
@@ -0,0 +1,171 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+namespace torch {
+namespace nn {
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Embedding
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Performs a lookup in a fixed size embedding table.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.Embedding to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::EmbeddingOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// Embedding model(EmbeddingOptions(10,
+/// 2).padding_idx(3).max_norm(2).norm_type(2.5).scale_grad_by_freq(true).sparse(true));
+/// ```
+class TORCH_API EmbeddingImpl : public torch::nn::Cloneable {
+ public:
+  EmbeddingImpl(int64_t num_embeddings, int64_t embedding_dim)
+      : EmbeddingImpl(EmbeddingOptions(num_embeddings, embedding_dim)) {}
+  explicit EmbeddingImpl(EmbeddingOptions options_);
+
+  void reset() override;
+
+  void reset_parameters();
+
+  /// Pretty prints the `Embedding` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// Performs a lookup on the embedding table stored in `weight` using the
+  /// `indices` supplied and returns the result.
+  Tensor forward(const Tensor& indices);
+
+  /// The `Options` used to configure this `Embedding` module.
+  /// Changes to `EmbeddingOptions` *after construction* have no effect.
+  EmbeddingOptions options;
+
+  /// The embedding table.
+  Tensor weight;
+};
+
+/// A `ModuleHolder` subclass for `EmbeddingImpl`.
+/// See the documentation for `EmbeddingImpl` class to learn what methods it
+/// provides, and examples of how to use `Embedding` with
+/// `torch::nn::EmbeddingOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+class Embedding : public torch::nn::ModuleHolder {
+ public:
+  using torch::nn::ModuleHolder::ModuleHolder;
+
+  /// See the documentation for `torch::nn::EmbeddingFromPretrainedOptions`
+  /// class to learn what optional arguments are supported for this function.
+  static Embedding from_pretrained(
+      const torch::Tensor& embeddings,
+      const EmbeddingFromPretrainedOptions& options = {}) {
+    TORCH_CHECK(
+        embeddings.dim() == 2,
+        "Embeddings parameter is expected to be 2-dimensional");
+
+    // NOLINTNEXTLINE(cppcoreguidelines-init-variables)
+    int64_t rows, cols;
+    rows = embeddings.size(0);
+    cols = embeddings.size(1);
+
+    Embedding embedding(EmbeddingOptions(rows, cols)
+                            ._weight(embeddings)
+                            .padding_idx(options.padding_idx())
+                            .max_norm(options.max_norm())
+                            .norm_type(options.norm_type())
+                            .scale_grad_by_freq(options.scale_grad_by_freq())
+                            .sparse(options.sparse()));
+    embedding->weight.set_requires_grad(!options.freeze());
+    return embedding;
+  }
+};
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ EmbeddingBag
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Computes sums or means of 'bags' of embeddings, without instantiating the
+/// intermediate embeddings.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.EmbeddingBag to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::EmbeddingBagOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// EmbeddingBag model(EmbeddingBagOptions(10,
+/// 2).max_norm(2).norm_type(2.5).scale_grad_by_freq(true).sparse(true).mode(torch::kSum).padding_idx(1));
+/// ```
+class TORCH_API EmbeddingBagImpl
+    : public torch::nn::Cloneable {
+ public:
+  EmbeddingBagImpl(int64_t num_embeddings, int64_t embedding_dim)
+      : EmbeddingBagImpl(EmbeddingBagOptions(num_embeddings, embedding_dim)) {}
+  explicit EmbeddingBagImpl(EmbeddingBagOptions options_);
+
+  void reset() override;
+
+  void reset_parameters();
+
+  /// Pretty prints the `EmbeddingBag` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// The `Options` used to configure this `EmbeddingBag` module.
+  EmbeddingBagOptions options;
+  /// The embedding table.
+  Tensor weight;
+
+  Tensor forward(
+      const Tensor& input,
+      const Tensor& offsets = {},
+      const Tensor& per_sample_weights = {});
+
+ protected:
+  FORWARD_HAS_DEFAULT_ARGS({1, AnyValue(Tensor())}, {2, AnyValue(Tensor())})
+};
+
+/// A `ModuleHolder` subclass for `EmbeddingBagImpl`.
+/// See the documentation for `EmbeddingBagImpl` class to learn what methods it
+/// provides, and examples of how to use `EmbeddingBag` with
+/// `torch::nn::EmbeddingBagOptions`. See the documentation for `ModuleHolder`
+/// to learn about PyTorch's module storage semantics.
+class EmbeddingBag : public torch::nn::ModuleHolder {
+ public:
+  using torch::nn::ModuleHolder::ModuleHolder;
+
+  /// See the documentation for `torch::nn::EmbeddingBagFromPretrainedOptions`
+  /// class to learn what optional arguments are supported for this function.
+  static EmbeddingBag from_pretrained(
+      const torch::Tensor& embeddings,
+      const EmbeddingBagFromPretrainedOptions& options = {}) {
+    TORCH_CHECK(
+        embeddings.dim() == 2,
+        "Embeddings parameter is expected to be 2-dimensional");
+
+    // NOLINTNEXTLINE(cppcoreguidelines-init-variables)
+    int64_t rows, cols;
+    rows = embeddings.size(0);
+    cols = embeddings.size(1);
+
+    EmbeddingBag embeddingbag(
+        EmbeddingBagOptions(rows, cols)
+            ._weight(embeddings)
+            .max_norm(options.max_norm())
+            .norm_type(options.norm_type())
+            .scale_grad_by_freq(options.scale_grad_by_freq())
+            .mode(options.mode())
+            .sparse(options.sparse())
+            .padding_idx(options.padding_idx()));
+    embeddingbag->weight.set_requires_grad(!options.freeze());
+    return embeddingbag;
+  }
+};
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/fold.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/fold.h
new file mode 100644
index 0000000000000000000000000000000000000000..6b415a99b5ea8ec94d3ea24a84d21ffedd8f05c6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/fold.h
@@ -0,0 +1,87 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Applies fold over a 3-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.Fold to learn about
+/// the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::FoldOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// Fold model(FoldOptions({8, 8}, {3, 3}).dilation(2).padding({2,
+/// 1}).stride(2));
+/// ```
+class TORCH_API FoldImpl : public torch::nn::Cloneable {
+ public:
+  FoldImpl(ExpandingArray<2> output_size, ExpandingArray<2> kernel_size)
+      : FoldImpl(FoldOptions(output_size, kernel_size)) {}
+  explicit FoldImpl(const FoldOptions& options_);
+
+  void reset() override;
+
+  /// Pretty prints the `Fold` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(const Tensor& input);
+
+  /// The options with which this `Module` was constructed.
+  FoldOptions options;
+};
+
+/// A `ModuleHolder` subclass for `FoldImpl`.
+/// See the documentation for `FoldImpl` class to learn what methods it
+/// provides, and examples of how to use `Fold` with `torch::nn::FoldOptions`.
+/// See the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(Fold);
+
+// ============================================================================
+
+/// Applies unfold over a 4-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.Unfold to learn about
+/// the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::UnfoldOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// Unfold model(UnfoldOptions({2, 4}).dilation(2).padding({2, 1}).stride(2));
+/// ```
+class TORCH_API UnfoldImpl : public Cloneable {
+ public:
+  UnfoldImpl(ExpandingArray<2> kernel_size)
+      : UnfoldImpl(UnfoldOptions(kernel_size)) {}
+  explicit UnfoldImpl(const UnfoldOptions& options_);
+
+  void reset() override;
+
+  /// Pretty prints the `Unfold` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(const Tensor& input);
+
+  /// The options with which this `Module` was constructed.
+  UnfoldOptions options;
+};
+
+/// A `ModuleHolder` subclass for `UnfoldImpl`.
+/// See the documentation for `UnfoldImpl` class to learn what methods it
+/// provides, and examples of how to use `Unfold` with
+/// `torch::nn::UnfoldOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(Unfold);
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/instancenorm.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/instancenorm.h
new file mode 100644
index 0000000000000000000000000000000000000000..66ebb6e7390a958de242d5ddd25e1acce307bd8c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/instancenorm.h
@@ -0,0 +1,153 @@
+#pragma once
+
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Base class for all (dimension-specialized) instance norm modules
+template 
+class InstanceNormImpl
+    : public torch::nn::NormImplBase {
+ private:
+  inline Tensor apply_instance_norm(const Tensor& input) {
+    return torch::nn::functional::detail::instance_norm(
+        input,
+        this->running_mean,
+        this->running_var,
+        this->weight,
+        this->bias,
+        this->is_training() || !this->options.track_running_stats(),
+        this->options.momentum(),
+        this->options.eps());
+  }
+
+  inline Tensor handle_no_batch_input(const Tensor& input) {
+    return this->apply_instance_norm(input.unsqueeze(0)).squeeze(0);
+  }
+
+ public:
+  using torch::nn::NormImplBase::NormImplBase;
+
+  Tensor forward(const Tensor& input) {
+    this->_check_input_dim(input);
+
+    // For InstanceNorm1D, 2D is unbatched and 3D is batched
+    // For InstanceNorm2D, 3D is unbatched and 4D is batched
+    // For InstanceNorm3D, 4D is unbatched and 5D is batched
+    // check if input does not have a batch-dim
+    if (input.dim() == D + 1) {
+      return this->handle_no_batch_input(input);
+    }
+
+    return this->apply_instance_norm(input);
+  }
+
+  /// Pretty prints the `InstanceNorm{1,2,3}d` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override {
+    stream << std::boolalpha << "torch::nn::InstanceNorm" << D << "d("
+           << this->options.num_features() << ", "
+           << "eps=" << this->options.eps() << ", "
+           << "momentum=" << this->options.momentum() << ", "
+           << "affine=" << this->options.affine() << ", "
+           << "track_running_stats=" << this->options.track_running_stats()
+           << ")";
+  }
+};
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ InstanceNorm1d
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the InstanceNorm1d function.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.InstanceNorm1d to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::InstanceNorm1dOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// InstanceNorm1d
+/// model(InstanceNorm1dOptions(4).eps(0.5).momentum(0.1).affine(false).track_running_stats(true));
+/// ```
+class TORCH_API InstanceNorm1dImpl
+    : public InstanceNormImpl<1, InstanceNorm1dImpl> {
+ protected:
+  void _check_input_dim(const Tensor& input) override;
+
+ public:
+  using InstanceNormImpl<1, InstanceNorm1dImpl>::InstanceNormImpl;
+};
+
+/// A `ModuleHolder` subclass for `InstanceNorm1dImpl`.
+/// See the documentation for `InstanceNorm1dImpl` class to learn what methods
+/// it provides, and examples of how to use `InstanceNorm1d` with
+/// `torch::nn::InstanceNorm1dOptions`. See the documentation for `ModuleHolder`
+/// to learn about PyTorch's module storage semantics.
+TORCH_MODULE(InstanceNorm1d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ InstanceNorm2d
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the InstanceNorm2d function.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.InstanceNorm2d to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::InstanceNorm2dOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// InstanceNorm2d
+/// model(InstanceNorm2dOptions(4).eps(0.5).momentum(0.1).affine(false).track_running_stats(true));
+/// ```
+class TORCH_API InstanceNorm2dImpl
+    : public InstanceNormImpl<2, InstanceNorm2dImpl> {
+ protected:
+  void _check_input_dim(const Tensor& input) override;
+
+ public:
+  using InstanceNormImpl<2, InstanceNorm2dImpl>::InstanceNormImpl;
+};
+
+/// A `ModuleHolder` subclass for `InstanceNorm2dImpl`.
+/// See the documentation for `InstanceNorm2dImpl` class to learn what methods
+/// it provides, and examples of how to use `InstanceNorm2d` with
+/// `torch::nn::InstanceNorm2dOptions`. See the documentation for `ModuleHolder`
+/// to learn about PyTorch's module storage semantics.
+TORCH_MODULE(InstanceNorm2d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ InstanceNorm3d
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the InstanceNorm3d function.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.InstanceNorm3d to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::InstanceNorm3dOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// InstanceNorm3d
+/// model(InstanceNorm3dOptions(4).eps(0.5).momentum(0.1).affine(false).track_running_stats(true));
+/// ```
+class TORCH_API InstanceNorm3dImpl
+    : public InstanceNormImpl<3, InstanceNorm3dImpl> {
+ protected:
+  void _check_input_dim(const Tensor& input) override;
+
+ public:
+  using InstanceNormImpl<3, InstanceNorm3dImpl>::InstanceNormImpl;
+};
+
+/// A `ModuleHolder` subclass for `InstanceNorm3dImpl`.
+/// See the documentation for `InstanceNorm3dImpl` class to learn what methods
+/// it provides, and examples of how to use `InstanceNorm3d` with
+/// `torch::nn::InstanceNorm3dOptions`. See the documentation for `ModuleHolder`
+/// to learn about PyTorch's module storage semantics.
+TORCH_MODULE(InstanceNorm3d);
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/linear.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/linear.h
new file mode 100644
index 0000000000000000000000000000000000000000..4a88ea80afe63da747f3483b768319a9a347093b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/linear.h
@@ -0,0 +1,214 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Identity ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// A placeholder identity operator that is argument-insensitive.
+/// See https://pytorch.org/docs/main/generated/torch.nn.Identity.html to
+/// learn about the exact behavior of this module.
+class TORCH_API IdentityImpl : public Cloneable {
+ public:
+  void reset() override;
+
+  /// Pretty prints the `Identity` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(const Tensor& input);
+};
+
+/// A `ModuleHolder` subclass for `IdentityImpl`.
+/// See the documentation for `IdentityImpl` class to learn what methods it
+/// provides, or the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(Identity);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Linear ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies a linear transformation with optional bias.
+/// See https://pytorch.org/docs/main/generated/torch.nn.Linear.html to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::LinearOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// Linear model(LinearOptions(5, 2).bias(false));
+/// ```
+class TORCH_API LinearImpl : public Cloneable {
+ public:
+  LinearImpl(int64_t in_features, int64_t out_features)
+      : LinearImpl(LinearOptions(in_features, out_features)) {}
+  explicit LinearImpl(const LinearOptions& options_);
+
+  void reset() override;
+
+  void reset_parameters();
+
+  /// Pretty prints the `Linear` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// Transforms the `input` tensor by multiplying with the `weight` and
+  /// optionally adding the `bias`, if `with_bias` is true in the options.
+  Tensor forward(const Tensor& input);
+
+  /// The options used to configure this module.
+  LinearOptions options;
+
+  /// The learned weight.
+  Tensor weight;
+
+  /// The learned bias. If `bias` is false in the `options`, this tensor is
+  /// undefined.
+  Tensor bias;
+};
+
+/// A `ModuleHolder` subclass for `LinearImpl`.
+/// See the documentation for `LinearImpl` class to learn what methods it
+/// provides, and examples of how to use `Linear` with
+/// `torch::nn::LinearOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(Linear);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Flatten ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// A placeholder for Flatten operator
+/// See https://pytorch.org/docs/main/generated/torch.nn.Flatten.html to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::FlattenOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// Flatten model(FlattenOptions().start_dim(2).end_dim(4));
+/// ```
+class TORCH_API FlattenImpl : public Cloneable {
+ public:
+  explicit FlattenImpl(const FlattenOptions& options_ = {});
+
+  void reset() override;
+
+  /// Pretty prints the `Flatten` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// Applies a flatten transform on the `input`.
+  Tensor forward(const Tensor& input);
+
+  /// The options used to configure this module.
+  FlattenOptions options;
+};
+
+/// A `ModuleHolder` subclass for `FlattenImpl`.
+/// See the documentation for `FlattenImpl` class to learn what methods it
+/// provides, and examples of how to use `Flatten` with
+/// `torch::nn::FlattenOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(Flatten);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Unflatten
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// A placeholder for unflatten operator
+/// See https://pytorch.org/docs/main/generated/torch.nn.Unflatten.html to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::UnflattenOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// Unflatten model(UnflattenOptions(0, {2, 2}));
+/// Unflatten model(UnflattenOptions("B", {{"B1", 2}, {"B2", 2}}));
+/// ```
+class TORCH_API UnflattenImpl : public Cloneable {
+ public:
+  UnflattenImpl(int64_t dim, std::vector sizes)
+      : UnflattenImpl(UnflattenOptions(dim, sizes)) {}
+  UnflattenImpl(std::string dimname, UnflattenOptions::namedshape_t namedshape)
+      : UnflattenImpl(UnflattenOptions(dimname, namedshape)) {}
+  explicit UnflattenImpl(UnflattenOptions options_);
+
+  void reset() override;
+
+  /// Pretty prints the `Unflatten` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// Applies an unflatten transform on the `input`.
+  Tensor forward(const Tensor& input);
+
+  /// The options used to configure this module.
+  UnflattenOptions options;
+};
+
+/// A `ModuleHolder` subclass for `UnflattenImpl`.
+/// See the documentation for `UnflattenImpl` class to learn what methods it
+/// provides, and examples of how to use `Unflatten` with
+/// `torch::nn::UnflattenOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(Unflatten);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Bilinear ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies a billinear transformation with optional bias.
+/// See https://pytorch.org/docs/main/generated/torch.nn.Bilinear.html to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::BilinearOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// Bilinear model(BilinearOptions(3, 2, 4).bias(false));
+/// ```
+class TORCH_API BilinearImpl : public Cloneable {
+ public:
+  BilinearImpl(int64_t in1_features, int64_t in2_features, int64_t out_features)
+      : BilinearImpl(
+            BilinearOptions(in1_features, in2_features, out_features)) {}
+  explicit BilinearImpl(const BilinearOptions& options_);
+
+  void reset() override;
+
+  void reset_parameters();
+
+  /// Pretty prints the `Bilinear` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// Applies a bilinear transform on the `input1` and `input2` tensor by
+  /// multiplying with the `weight` and optionally adding the `bias`, if
+  /// `with_bias` is true in the options.
+  Tensor forward(const Tensor& input1, const Tensor& input2);
+
+  /// The options used to configure this module.
+  BilinearOptions options;
+
+  /// The learned weight.
+  Tensor weight;
+
+  /// The learned bias. If `with_bias` is false in the `options`, this tensor is
+  /// undefined.
+  Tensor bias;
+};
+
+/// A `ModuleHolder` subclass for `BilinearImpl`.
+/// See the documentation for `BilinearImpl` class to learn what methods it
+/// provides, and examples of how to use `Bilinear` with
+/// `torch::nn::BilinearOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(Bilinear);
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/loss.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/loss.h
new file mode 100644
index 0000000000000000000000000000000000000000..747b548b758441ec7a86ae7a322e38c11f23f9ea
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/loss.h
@@ -0,0 +1,805 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ L1Loss ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Creates a criterion that measures the mean absolute error (MAE) between each
+/// element in the input : math :`x` and target : `y`.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.L1Loss to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::L1LossOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// L1Loss model(L1LossOptions(torch::kNone));
+/// ```
+struct TORCH_API L1LossImpl : Cloneable {
+  explicit L1LossImpl(L1LossOptions options_ = {});
+
+  void reset() override;
+
+  /// Pretty prints the `L1Loss` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(const Tensor& input, const Tensor& target);
+
+  /// The options with which this `Module` was constructed.
+  L1LossOptions options;
+};
+
+/// A `ModuleHolder` subclass for `L1LossImpl`.
+/// See the documentation for `L1LossImpl` class to learn what methods it
+/// provides, and examples of how to use `L1Loss` with
+/// `torch::nn::L1LossOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(L1Loss);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ KLDivLoss
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// The Kullback-Leibler divergence loss measure
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.KLDivLoss to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::KLDivLossOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// KLDivLoss model(KLDivLossOptions().reduction(torch::kNone));
+/// ```
+struct TORCH_API KLDivLossImpl : Cloneable {
+  explicit KLDivLossImpl(KLDivLossOptions options_ = {});
+
+  void reset() override;
+
+  /// Pretty prints the `KLDivLoss` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(const Tensor& input, const Tensor& target);
+
+  /// The options with which this `Module` was constructed.
+  KLDivLossOptions options;
+};
+
+/// A `ModuleHolder` subclass for `KLDivLossImpl`.
+/// See the documentation for `KLDivLossImpl` class to learn what methods it
+/// provides, and examples of how to use `KLDivLoss` with
+/// `torch::nn::KLDivLossOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(KLDivLoss);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MSELoss ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Creates a criterion that measures the mean squared error (squared L2 norm)
+/// between each element in the input :math:`x` and target :math:`y`.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.MSELoss to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::MSELossOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// MSELoss model(MSELossOptions(torch::kNone));
+/// ```
+struct TORCH_API MSELossImpl : Cloneable {
+  explicit MSELossImpl(MSELossOptions options_ = {});
+
+  void reset() override;
+
+  /// Pretty prints the `MSELoss` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(const Tensor& input, const Tensor& target);
+
+  /// The options with which this `Module` was constructed.
+  MSELossOptions options;
+};
+
+/// A `ModuleHolder` subclass for `MSELossImpl`.
+/// See the documentation for `MSELossImpl` class to learn what methods it
+/// provides, and examples of how to use `MSELoss` with
+/// `torch::nn::MSELossOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(MSELoss);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BCELoss ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Creates a criterion that measures the Binary Cross Entropy
+/// between the target and the output.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.BCELoss to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::BCELossOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// BCELoss model(BCELossOptions().reduction(torch::kNone).weight(weight));
+/// ```
+struct TORCH_API BCELossImpl : Cloneable {
+  explicit BCELossImpl(BCELossOptions options_ = {});
+
+  void reset() override;
+
+  /// Pretty prints the `BCELoss` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(const Tensor& input, const Tensor& target);
+
+  /// The options with which this `Module` was constructed.
+  BCELossOptions options;
+};
+
+/// A `ModuleHolder` subclass for `BCELossImpl`.
+/// See the documentation for `BCELossImpl` class to learn what methods it
+/// provides, and examples of how to use `BCELoss` with
+/// `torch::nn::BCELossOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(BCELoss);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ HingeEmbeddingLoss
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Creates a criterion that measures the loss given an input tensor :math:`x`
+/// and a labels tensor :math:`y` (containing 1 or -1).
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.HingeEmbeddingLoss to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::HingeEmbeddingLossOptions` class to
+/// learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// HingeEmbeddingLoss
+/// model(HingeEmbeddingLossOptions().margin(4).reduction(torch::kNone));
+/// ```
+struct TORCH_API HingeEmbeddingLossImpl : Cloneable {
+  explicit HingeEmbeddingLossImpl(HingeEmbeddingLossOptions options_ = {});
+
+  void reset() override;
+
+  /// Pretty prints the `HingeEmbeddingLoss` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(const Tensor& input, const Tensor& target);
+
+  /// The options with which this `Module` was constructed.
+  HingeEmbeddingLossOptions options;
+};
+
+/// A `ModuleHolder` subclass for `HingeEmbeddingLossImpl`.
+/// See the documentation for `HingeEmbeddingLossImpl` class to learn what
+/// methods it provides, and examples of how to use `HingeEmbeddingLoss` with
+/// `torch::nn::HingeEmbeddingLossOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(HingeEmbeddingLoss);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MultiMarginLoss
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Creates a criterion that optimizes a multi-class classification hinge
+/// loss (margin-based loss) between input :math:`x` (a 2D mini-batch `Tensor`)
+/// and output :math:`y` (which is a 1D tensor of target class indices, :math:`0
+/// \leq y \leq \text{x.size}(1)-1`). See
+/// https://pytorch.org/docs/main/nn.html#torch.nn.MultiMarginLoss to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::MultiMarginLossOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// MultiMarginLoss model(MultiMarginLossOptions().margin(2).weight(weight));
+/// ```
+struct TORCH_API MultiMarginLossImpl : public Cloneable {
+  explicit MultiMarginLossImpl(MultiMarginLossOptions options_ = {});
+
+  void reset() override;
+
+  /// Pretty prints the `MultiMarginLoss` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(const Tensor& input, const Tensor& target);
+
+  /// The options with which this `Module` was constructed.
+  MultiMarginLossOptions options;
+};
+
+/// A `ModuleHolder` subclass for `MultiMarginLossImpl`.
+/// See the documentation for `MultiMarginLossImpl` class to learn what methods
+/// it provides, and examples of how to use `MultiMarginLoss` with
+/// `torch::nn::MultiMarginLossOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(MultiMarginLoss);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ CosineEmbeddingLoss
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Creates a criterion that measures the loss given input tensors
+/// `input1`, `input2`, and a `Tensor` label `target` with values 1 or
+/// -1. This is used for measuring whether two inputs are similar or
+/// dissimilar, using the cosine distance, and is typically used for learning
+/// nonlinear embeddings or semi-supervised learning.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.CosineEmbeddingLoss to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::CosineEmbeddingLossOptions` class to
+/// learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// CosineEmbeddingLoss model(CosineEmbeddingLossOptions().margin(0.5));
+/// ```
+struct TORCH_API CosineEmbeddingLossImpl
+    : public Cloneable {
+  explicit CosineEmbeddingLossImpl(CosineEmbeddingLossOptions options_ = {});
+
+  void reset() override;
+
+  /// Pretty prints the `CosineEmbeddingLoss` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(
+      const Tensor& input1,
+      const Tensor& input2,
+      const Tensor& target);
+
+  /// The options with which this `Module` was constructed.
+  CosineEmbeddingLossOptions options;
+};
+
+/// A `ModuleHolder` subclass for `CosineEmbeddingLossImpl`.
+/// See the documentation for `CosineEmbeddingLossImpl` class to learn what
+/// methods it provides, and examples of how to use `CosineEmbeddingLoss` with
+/// `torch::nn::CosineEmbeddingLossOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(CosineEmbeddingLoss);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SmoothL1Loss
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Creates a criterion that uses a squared term if the absolute
+/// element-wise error falls below beta and an L1 term otherwise.
+/// It is less sensitive to outliers than the `MSELoss` and in some cases
+/// prevents exploding gradients (e.g. see the paper `Fast R-CNN` by Ross
+/// Girshick). See https://pytorch.org/docs/main/nn.html#torch.nn.SmoothL1Loss
+/// to learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::SmoothL1LossOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// SmoothL1Loss model(SmoothL1LossOptions().reduction(torch::kNone).beta(0.5));
+/// ```
+struct TORCH_API SmoothL1LossImpl : public Cloneable {
+  explicit SmoothL1LossImpl(SmoothL1LossOptions options = {});
+
+  void reset() override;
+
+  /// Pretty prints the `L1Loss` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(const Tensor& input, const Tensor& target);
+
+  /// The options with which this `Module` was constructed.
+  SmoothL1LossOptions options;
+};
+
+/// A `ModuleHolder` subclass for `SmoothL1LossImpl`.
+/// See the documentation for `SmoothL1LossImpl` class to learn what methods it
+/// provides, and examples of how to use `SmoothL1Loss` with
+/// `torch::nn::SmoothL1LossOptions`. See the documentation for `ModuleHolder`
+/// to learn about PyTorch's module storage semantics.
+TORCH_MODULE(SmoothL1Loss);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ HuberLoss
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Creates a criterion that uses a squared term if the absolute
+/// element-wise error falls below delta and a delta-scaled L1 term otherwise.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.HuberLoss to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::HuberLossOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// HuberLoss model(HuberLossOptions().reduction(torch::kNone).delta(0.5));
+/// ```
+struct TORCH_API HuberLossImpl : public Cloneable {
+  explicit HuberLossImpl(HuberLossOptions options_ = {});
+
+  void reset() override;
+
+  /// Pretty prints the `HuberLoss` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(const Tensor& input, const Tensor& target);
+
+  /// The options with which this `Module` was constructed.
+  HuberLossOptions options;
+};
+
+/// A `ModuleHolder` subclass for `HuberLossImpl`.
+/// See the documentation for `HuberLossImpl` class to learn what methods it
+/// provides, and examples of how to use `HuberLoss` with
+/// `torch::nn::HuberLossOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(HuberLoss);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MultiLabelMarginLoss
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Creates a criterion that optimizes a multi-class multi-classification
+/// hinge loss (margin-based loss) between input :math:`x` (a 2D mini-batch
+/// `Tensor`) and output :math:`y` (which is a 2D `Tensor` of target class
+/// indices). See
+/// https://pytorch.org/docs/main/nn.html#torch.nn.MultiLabelMarginLoss to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::MultiLabelMarginLossOptions` class to
+/// learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// MultiLabelMarginLoss model(MultiLabelMarginLossOptions(torch::kNone));
+/// ```
+struct TORCH_API MultiLabelMarginLossImpl
+    : public Cloneable {
+  explicit MultiLabelMarginLossImpl(MultiLabelMarginLossOptions options_ = {});
+
+  void reset() override;
+
+  /// Pretty prints the `L1Loss` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(const Tensor& input, const Tensor& target);
+
+  /// The options with which this `Module` was constructed.
+  MultiLabelMarginLossOptions options;
+};
+
+/// A `ModuleHolder` subclass for `MultiLabelMarginLossImpl`.
+/// See the documentation for `MultiLabelMarginLossImpl` class to learn what
+/// methods it provides, and examples of how to use `MultiLabelMarginLoss` with
+/// `torch::nn::MultiLabelMarginLossOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(MultiLabelMarginLoss);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SoftMarginLoss
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Creates a criterion that optimizes a two-class classification
+/// logistic loss between input tensor :math:`x` and target tensor :math:`y`
+/// (containing 1 or -1).
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.SoftMarginLoss to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::SoftMarginLossOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// SoftMarginLoss model(SoftMarginLossOptions(torch::kNone));
+/// ```
+struct TORCH_API SoftMarginLossImpl : public Cloneable {
+  explicit SoftMarginLossImpl(SoftMarginLossOptions options_ = {});
+
+  /// Pretty prints the `SoftMarginLoss` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  void reset() override;
+
+  Tensor forward(const Tensor& input, const Tensor& target);
+
+  /// The options with which this `Module` was constructed.
+  SoftMarginLossOptions options;
+};
+
+/// A `ModuleHolder` subclass for `SoftMarginLossImpl`.
+/// See the documentation for `SoftMarginLossImpl` class to learn what methods
+/// it provides, and examples of how to use `SoftMarginLoss` with
+/// `torch::nn::SoftMarginLossOptions`. See the documentation for `ModuleHolder`
+/// to learn about PyTorch's module storage semantics.
+TORCH_MODULE(SoftMarginLoss);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MultiLabelSoftMarginLoss
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Creates a criterion that optimizes a multi-label one-versus-all
+/// loss based on max-entropy, between input :math:`x` and target :math:`y` of
+/// size :math:`(N, C)`. See
+/// https://pytorch.org/docs/main/nn.html#torch.nn.MultiLabelSoftMarginLoss to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::MultiLabelSoftMarginLossOptions` class
+/// to learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// MultiLabelSoftMarginLoss
+/// model(MultiLabelSoftMarginLossOptions().reduction(torch::kNone).weight(weight));
+/// ```
+struct TORCH_API MultiLabelSoftMarginLossImpl
+    : public Cloneable {
+  explicit MultiLabelSoftMarginLossImpl(
+      MultiLabelSoftMarginLossOptions options_ = {});
+
+  /// Pretty prints the `MultiLabelSoftMarginLoss` module into the given
+  /// `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  void reset() override;
+
+  Tensor forward(const Tensor& input, const Tensor& target);
+
+  /// The options with which this `Module` was constructed.
+  MultiLabelSoftMarginLossOptions options;
+};
+
+/// A `ModuleHolder` subclass for `MultiLabelSoftMarginLossImpl`.
+/// See the documentation for `MultiLabelSoftMarginLossImpl` class to learn what
+/// methods it provides, and examples of how to use `MultiLabelSoftMarginLoss`
+/// with `torch::nn::MultiLabelSoftMarginLossOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(MultiLabelSoftMarginLoss);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TripletMarginLoss
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Creates a criterion that measures the triplet loss given an input
+/// tensors :math:`x1`, :math:`x2`, :math:`x3` and a margin with a value greater
+/// than :math:`0`. This is used for measuring a relative similarity between
+/// samples. A triplet is composed by `a`, `p` and `n` (i.e., `anchor`,
+/// `positive examples` and `negative examples` respectively). The
+/// shapes of all input tensors should be :math:`(N, D)`.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.TripletMarginLoss to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::TripletMarginLossOptions` class to
+/// learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// TripletMarginLoss
+/// model(TripletMarginLossOptions().margin(3).p(2).eps(1e-06).swap(false));
+/// ```
+struct TORCH_API TripletMarginLossImpl
+    : public Cloneable {
+  explicit TripletMarginLossImpl(TripletMarginLossOptions options_ = {});
+
+  void reset() override;
+
+  /// Pretty prints the `TripletMarginLoss` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(
+      const Tensor& anchor,
+      const Tensor& positive,
+      const Tensor& negative);
+
+  /// The options with which this `Module` was constructed.
+  TripletMarginLossOptions options;
+};
+
+/// A `ModuleHolder` subclass for `TripletMarginLossImpl`.
+/// See the documentation for `TripletMarginLossImpl` class to learn what
+/// methods it provides, and examples of how to use `TripletMarginLoss` with
+/// `torch::nn::TripletMarginLossOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(TripletMarginLoss);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TripletMarginWithDistanceLoss
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Creates a criterion that measures the triplet loss given input
+/// tensors :math:`a`, :math:`p`, and :math:`n` (representing anchor,
+/// positive, and negative examples, respectively); and a nonnegative,
+/// real-valued function
+/// ("distance function") used to compute the relationships between the anchor
+/// and positive example ("positive distance") and the anchor and negative
+/// example ("negative distance").
+/// See
+/// https://pytorch.org/docs/main/nn.html#torch.nn.TripletMarginWithDistanceLoss
+/// to learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::TripletMarginWithDistanceLossOptions`
+/// class to learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// TripletMarginWithDistanceLoss
+/// model(TripletMarginWithDistanceLossOptions().margin(3).swap(false));
+/// ```
+struct TORCH_API TripletMarginWithDistanceLossImpl
+    : public Cloneable {
+  explicit TripletMarginWithDistanceLossImpl(
+      TripletMarginWithDistanceLossOptions options_ = {});
+
+  void reset() override;
+
+  /// Pretty prints the `TripletMarginWithDistanceLoss` module into the given
+  /// `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(
+      const Tensor& anchor,
+      const Tensor& positive,
+      const Tensor& negative);
+
+  /// The options with which this `Module` was constructed.
+  TripletMarginWithDistanceLossOptions options;
+};
+
+/// A `ModuleHolder` subclass for `TripletMarginWithDistanceLossImpl`.
+/// See the documentation for `TripletMarginWithDistanceLossImpl` class to learn
+/// what methods it provides, and examples of how to use
+/// `TripletMarginWithDistanceLoss` with
+/// `torch::nn::TripletMarginWithDistanceLossOptions`.
+/// See the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(TripletMarginWithDistanceLoss);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ CTCLoss ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// The Connectionist Temporal Classification loss.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.CTCLoss to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::CTCLossOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// CTCLoss
+/// model(CTCLossOptions().blank(42).zero_infinity(false).reduction(torch::kSum));
+/// ```
+struct TORCH_API CTCLossImpl : public Cloneable {
+  explicit CTCLossImpl(CTCLossOptions options_ = {});
+
+  void reset() override;
+
+  /// Pretty prints the `CTCLoss` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(
+      const Tensor& log_probs,
+      const Tensor& targets,
+      const Tensor& input_lengths,
+      const Tensor& target_lengths);
+
+  /// The options with which this `Module` was constructed.
+  CTCLossOptions options;
+};
+
+/// A `ModuleHolder` subclass for `CTCLossImpl`.
+/// See the documentation for `CTCLossImpl` class to learn what methods it
+/// provides, and examples of how to use `CTCLoss` with
+/// `torch::nn::CTCLossOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(CTCLoss);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ PoissonNLLLoss
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Negative log likelihood loss with Poisson distribution of target.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.PoissonNLLLoss to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::PoissonNLLLossOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// PoissonNLLLoss
+/// model(PoissonNLLLossOptions().log_input(false).full(true).eps(0.42).reduction(torch::kSum));
+/// ```
+struct TORCH_API PoissonNLLLossImpl : public Cloneable {
+  explicit PoissonNLLLossImpl(PoissonNLLLossOptions options_ = {});
+
+  void reset() override;
+
+  /// Pretty prints the `PoissonNLLLoss` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(const Tensor& log_input, const Tensor& targets);
+
+  /// The options with which this `Module` was constructed.
+  PoissonNLLLossOptions options;
+};
+
+/// A `ModuleHolder` subclass for `PoissonNLLLossImpl`.
+/// See the documentation for `PoissonNLLLossImpl` class to learn what methods
+/// it provides, and examples of how to use `PoissonNLLLoss` with
+/// `torch::nn::PoissonNLLLossOptions`. See the documentation for `ModuleHolder`
+/// to learn about PyTorch's module storage semantics.
+TORCH_MODULE(PoissonNLLLoss);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MarginRankingLoss
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Creates a criterion that measures the loss given
+/// inputs :math:`x1`, :math:`x2`, two 1D mini-batch `Tensors`,
+/// and a label 1D mini-batch tensor :math:`y` (containing 1 or -1).
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.MarginRankingLoss to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::MarginRankingLossOptions` class to
+/// learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// MarginRankingLoss
+/// model(MarginRankingLossOptions().margin(0.5).reduction(torch::kSum));
+/// ```
+struct TORCH_API MarginRankingLossImpl
+    : public Cloneable {
+  explicit MarginRankingLossImpl(MarginRankingLossOptions options_ = {});
+
+  void reset() override;
+
+  /// Pretty prints the `MarginRankingLoss` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(
+      const Tensor& input1,
+      const Tensor& input2,
+      const Tensor& targets);
+
+  /// The options with which this `Module` was constructed.
+  MarginRankingLossOptions options;
+};
+
+/// A `ModuleHolder` subclass for `MarginRankingLossImpl`.
+/// See the documentation for `MarginRankingLossImpl` class to learn what
+/// methods it provides, and examples of how to use `MarginRankingLoss` with
+/// `torch::nn::MarginRankingLossOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(MarginRankingLoss);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ NLLLoss ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// The negative log likelihood loss. It is useful to train a classification
+/// problem with `C` classes.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.NLLLoss to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::NLLLossOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// NLLLoss model(NLLLossOptions().ignore_index(-100).reduction(torch::kMean));
+/// ```
+struct TORCH_API NLLLossImpl : public Cloneable {
+  explicit NLLLossImpl(NLLLossOptions options_ = {});
+
+  /// Pretty prints the `NLLLoss` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  void reset() override;
+
+  Tensor forward(const Tensor& input, const Tensor& target);
+
+  /// The options with which this `Module` was constructed.
+  NLLLossOptions options;
+
+  /// A manual rescaling weight given to to each class.
+  Tensor weight;
+};
+
+/// A `ModuleHolder` subclass for `NLLLossImpl`.
+/// See the documentation for `NLLLossImpl` class to learn what methods it
+/// provides, and examples of how to use `NLLLoss` with
+/// `torch::nn::NLLLossOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(NLLLoss);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ CrossEntropyLoss
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Creates a criterion that computes cross entropy loss between input and
+/// target. See
+/// https://pytorch.org/docs/main/nn.html#torch.nn.CrossEntropyLoss to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::CrossEntropyLossOptions` class to
+/// learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// CrossEntropyLoss
+/// model(CrossEntropyLossOptions().ignore_index(-100).reduction(torch::kMean));
+/// ```
+struct TORCH_API CrossEntropyLossImpl : public Cloneable {
+  explicit CrossEntropyLossImpl(CrossEntropyLossOptions options_ = {});
+
+  void reset() override;
+
+  /// Pretty prints the `CrossEntropyLoss` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(const Tensor& input, const Tensor& target);
+
+  /// The options with which this `Module` was constructed.
+  CrossEntropyLossOptions options;
+
+  /// A manual rescaling weight given to to each class.
+  Tensor weight;
+};
+
+/// A `ModuleHolder` subclass for `CrossEntropyLossImpl`.
+/// See the documentation for `CrossEntropyLossImpl` class to learn what methods
+/// it provides, and examples of how to use `CrossEntropyLoss` with
+/// `torch::nn::CrossEntropyLossOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(CrossEntropyLoss);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BCEWithLogitsLoss
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// This loss combines a `Sigmoid` layer and the `BCELoss` in one single
+/// class. This version is more numerically stable than using a plain `Sigmoid`
+/// followed by a `BCELoss` as, by combining the operations into one layer,
+/// we take advantage of the log-sum-exp trick for numerical stability.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.BCEWithLogitsLoss to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::BCEWithLogitsLossOptions` class to
+/// learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// BCEWithLogitsLoss
+/// model(BCEWithLogitsLossOptions().reduction(torch::kNone).weight(weight));
+/// ```
+struct TORCH_API BCEWithLogitsLossImpl
+    : public Cloneable {
+  explicit BCEWithLogitsLossImpl(BCEWithLogitsLossOptions options_ = {});
+
+  void reset() override;
+
+  /// Pretty prints the `BCEWithLogitsLoss` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(const Tensor& input, const Tensor& target);
+
+  /// The options with which this `Module` was constructed.
+  BCEWithLogitsLossOptions options;
+
+  /// A manual rescaling weight given to the loss of each batch element.
+  Tensor weight;
+
+  /// A weight of positive examples.
+  Tensor pos_weight;
+};
+
+/// A `ModuleHolder` subclass for `BCEWithLogitsLossImpl`.
+/// See the documentation for `BCEWithLogitsLossImpl` class to learn what
+/// methods it provides, and examples of how to use `BCEWithLogitsLoss` with
+/// `torch::nn::BCEWithLogitsLossOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(BCEWithLogitsLoss);
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/normalization.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/normalization.h
new file mode 100644
index 0000000000000000000000000000000000000000..9bc0b7f9e7fc45208f2b58a79fdc30d6c46b8b8e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/normalization.h
@@ -0,0 +1,198 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ LayerNorm ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies Layer Normalization over a mini-batch of inputs as described in
+/// the paper `Layer Normalization`_ .
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.LayerNorm to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::LayerNormOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// LayerNorm model(LayerNormOptions({2,
+/// 2}).elementwise_affine(false).eps(2e-5));
+/// ```
+class TORCH_API LayerNormImpl : public torch::nn::Cloneable {
+ public:
+  LayerNormImpl(std::vector normalized_shape)
+      : LayerNormImpl(LayerNormOptions(normalized_shape)) {}
+  explicit LayerNormImpl(LayerNormOptions options_);
+
+  void reset() override;
+
+  void reset_parameters();
+
+  /// Pretty prints the `LayerNorm` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// Applies layer normalization over a mini-batch of inputs as described in
+  /// the paper `Layer Normalization`_ .
+  ///
+  /// The mean and standard-deviation are calculated separately over the last
+  /// certain number dimensions which have to be of the shape specified by
+  /// input `normalized_shape`.
+  ///
+  /// `Layer Normalization`: https://arxiv.org/abs/1607.06450
+  Tensor forward(const Tensor& input);
+
+  /// The options with which this module was constructed.
+  LayerNormOptions options;
+
+  /// The learned weight.
+  /// Initialized to ones if the `elementwise_affine` option is set to `true`
+  /// upon construction.
+  Tensor weight;
+
+  /// The learned bias.
+  /// Initialized to zeros `elementwise_affine` option is set to `true` upon
+  /// construction.
+  Tensor bias;
+};
+
+/// A `ModuleHolder` subclass for `LayerNormImpl`.
+/// See the documentation for `LayerNormImpl` class to learn what methods it
+/// provides, and examples of how to use `LayerNorm` with
+/// `torch::nn::LayerNormOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(LayerNorm);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ LocalResponseNorm
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies local response normalization over an input signal composed
+/// of several input planes, where channels occupy the second dimension.
+/// Applies normalization across channels.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.LocalResponseNorm to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::LocalResponseNormOptions` class to
+/// learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// LocalResponseNorm
+/// model(LocalResponseNormOptions(2).alpha(0.0002).beta(0.85).k(2.));
+/// ```
+class TORCH_API LocalResponseNormImpl
+    : public Cloneable {
+ public:
+  LocalResponseNormImpl(int64_t size)
+      : LocalResponseNormImpl(LocalResponseNormOptions(size)) {}
+  explicit LocalResponseNormImpl(const LocalResponseNormOptions& options_);
+
+  Tensor forward(const Tensor& input);
+
+  void reset() override;
+
+  /// Pretty prints the `LocalResponseNormImpl` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// The options with which this `Module` was constructed.
+  LocalResponseNormOptions options;
+};
+
+/// A `ModuleHolder` subclass for `LocalResponseNormImpl`.
+/// See the documentation for `LocalResponseNormImpl` class to learn what
+/// methods it provides, and examples of how to use `LocalResponseNorm` with
+/// `torch::nn::LocalResponseNormOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(LocalResponseNorm);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ CrossMapLRN2d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// See the documentation for `torch::nn::CrossMapLRN2dOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// CrossMapLRN2d model(CrossMapLRN2dOptions(3).alpha(1e-5).beta(0.1).k(10));
+/// ```
+class TORCH_API CrossMapLRN2dImpl
+    : public torch::nn::Cloneable {
+ public:
+  CrossMapLRN2dImpl(int64_t size)
+      : CrossMapLRN2dImpl(CrossMapLRN2dOptions(size)) {}
+  explicit CrossMapLRN2dImpl(const CrossMapLRN2dOptions& options_)
+      : options(options_) {}
+
+  void reset() override;
+
+  /// Pretty prints the `CrossMapLRN2d` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  torch::Tensor forward(const torch::Tensor& input);
+
+  CrossMapLRN2dOptions options;
+};
+
+/// A `ModuleHolder` subclass for `CrossMapLRN2dImpl`.
+/// See the documentation for `CrossMapLRN2dImpl` class to learn what methods it
+/// provides, and examples of how to use `CrossMapLRN2d` with
+/// `torch::nn::CrossMapLRN2dOptions`. See the documentation for `ModuleHolder`
+/// to learn about PyTorch's module storage semantics.
+TORCH_MODULE(CrossMapLRN2d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GroupNorm ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies Group Normalization over a mini-batch of inputs as described in
+/// the paper `Group Normalization`_ .
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.GroupNorm to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::GroupNormOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// GroupNorm model(GroupNormOptions(2, 2).eps(2e-5).affine(false));
+/// ```
+class TORCH_API GroupNormImpl : public torch::nn::Cloneable {
+ public:
+  GroupNormImpl(int64_t num_groups, int64_t num_channels)
+      : GroupNormImpl(GroupNormOptions(num_groups, num_channels)) {}
+  explicit GroupNormImpl(const GroupNormOptions& options_);
+
+  void reset() override;
+
+  void reset_parameters();
+
+  /// Pretty prints the `GroupNorm` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(const Tensor& input);
+
+  /// The options with which this module was constructed.
+  GroupNormOptions options;
+
+  /// The learned weight.
+  Tensor weight;
+
+  /// The learned bias.
+  Tensor bias;
+};
+
+/// A `ModuleHolder` subclass for `GroupNormImpl`.
+/// See the documentation for `GroupNormImpl` class to learn what methods it
+/// provides, and examples of how to use `GroupNorm` with
+/// `torch::nn::GroupNormOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(GroupNorm);
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/padding.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/padding.h
new file mode 100644
index 0000000000000000000000000000000000000000..f051e9a19305c07db0e249feedd4d5a331ac5bdf
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/padding.h
@@ -0,0 +1,378 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Base class for all (dimension-specialized) ReflectionPad modules.
+template 
+class TORCH_API ReflectionPadImpl : public torch::nn::Cloneable {
+ public:
+  ReflectionPadImpl(ExpandingArray padding)
+      : ReflectionPadImpl(ReflectionPadOptions(padding)) {}
+  explicit ReflectionPadImpl(const ReflectionPadOptions& options_);
+
+  void reset() override;
+
+  Tensor forward(const Tensor& input);
+
+  /// Pretty prints the `ReflectionPad{1,2}d` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// The options with which this `Module` was constructed.
+  ReflectionPadOptions options;
+};
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ReflectionPad1d
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies ReflectionPad over a 1-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.ReflectionPad1d to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::ReflectionPad1dOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// ReflectionPad1d model(ReflectionPad1dOptions({3, 1}));
+/// ```
+class TORCH_API ReflectionPad1dImpl
+    : public ReflectionPadImpl<1, ReflectionPad1dImpl> {
+ public:
+  using ReflectionPadImpl<1, ReflectionPad1dImpl>::ReflectionPadImpl;
+};
+
+/// A `ModuleHolder` subclass for `ReflectionPad1dImpl`.
+/// See the documentation for `ReflectionPad1dImpl` class to learn what methods
+/// it provides, and examples of how to use `ReflectionPad1d` with
+/// `torch::nn::ReflectionPad1dOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(ReflectionPad1d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ReflectionPad2d
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies ReflectionPad over a 2-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.ReflectionPad2d to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::ReflectionPad2dOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// ReflectionPad2d model(ReflectionPad2dOptions({1, 1, 2, 0}));
+/// ```
+class TORCH_API ReflectionPad2dImpl
+    : public ReflectionPadImpl<2, ReflectionPad2dImpl> {
+ public:
+  using ReflectionPadImpl<2, ReflectionPad2dImpl>::ReflectionPadImpl;
+};
+
+/// A `ModuleHolder` subclass for `ReflectionPad2dImpl`.
+/// See the documentation for `ReflectionPad2dImpl` class to learn what methods
+/// it provides, and examples of how to use `ReflectionPad2d` with
+/// `torch::nn::ReflectionPad2dOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(ReflectionPad2d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ReflectionPad3d
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies ReflectionPad over a 3-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.ReflectionPad3d to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::ReflectionPad3dOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// ReflectionPad3d model(ReflectionPad3dOptions(1));
+/// ReflectionPad3d model(ReflectionPad3dOptions({1, 1, 2, 0, 1, 2}));
+/// ```
+class TORCH_API ReflectionPad3dImpl
+    : public ReflectionPadImpl<3, ReflectionPad3dImpl> {
+ public:
+  using ReflectionPadImpl<3, ReflectionPad3dImpl>::ReflectionPadImpl;
+};
+
+/// A `ModuleHolder` subclass for `ReflectionPad3dImpl`.
+/// See the documentation for `ReflectionPad3dImpl` class to learn what methods
+/// it provides, and examples of how to use `ReflectionPad3d` with
+/// `torch::nn::ReflectionPad3dOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(ReflectionPad3d);
+
+// ============================================================================
+
+/// Base class for all (dimension-specialized) ReplicationPad modules.
+template 
+class TORCH_API ReplicationPadImpl : public torch::nn::Cloneable {
+ public:
+  ReplicationPadImpl(ExpandingArray padding)
+      : ReplicationPadImpl(ReplicationPadOptions(padding)) {}
+  explicit ReplicationPadImpl(const ReplicationPadOptions& options_);
+
+  void reset() override;
+
+  Tensor forward(const Tensor& input);
+
+  /// Pretty prints the `ReplicationPad{1,2}d` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// The options with which this `Module` was constructed.
+  ReplicationPadOptions options;
+};
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ReplicationPad1d
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies ReplicationPad over a 1-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.ReplicationPad1d to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::ReplicationPad1dOptions` class to
+/// learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// ReplicationPad1d model(ReplicationPad1dOptions({3, 1}));
+/// ```
+class TORCH_API ReplicationPad1dImpl
+    : public ReplicationPadImpl<1, ReplicationPad1dImpl> {
+ public:
+  using ReplicationPadImpl<1, ReplicationPad1dImpl>::ReplicationPadImpl;
+};
+
+/// A `ModuleHolder` subclass for `ReplicationPad1dImpl`.
+/// See the documentation for `ReplicationPad1dImpl` class to learn what methods
+/// it provides, and examples of how to use `ReplicationPad1d` with
+/// `torch::nn::ReplicationPad1dOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(ReplicationPad1d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ReplicationPad2d
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies ReplicationPad over a 2-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.ReplicationPad2d to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::ReplicationPad2dOptions` class to
+/// learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// ReplicationPad2d model(ReplicationPad2dOptions({1, 1, 2, 0}));
+/// ```
+class TORCH_API ReplicationPad2dImpl
+    : public ReplicationPadImpl<2, ReplicationPad2dImpl> {
+ public:
+  using ReplicationPadImpl<2, ReplicationPad2dImpl>::ReplicationPadImpl;
+};
+
+/// A `ModuleHolder` subclass for `ReplicationPad2dImpl`.
+/// See the documentation for `ReplicationPad2dImpl` class to learn what methods
+/// it provides, and examples of how to use `ReplicationPad2d` with
+/// `torch::nn::ReplicationPad2dOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(ReplicationPad2d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ReplicationPad3d
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies ReplicationPad over a 3-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.ReplicationPad3d to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::ReplicationPad3dOptions` class to
+/// learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// ReplicationPad3d model(ReplicationPad3dOptions({1, 2, 1, 2, 1, 2}));
+/// ```
+class TORCH_API ReplicationPad3dImpl
+    : public ReplicationPadImpl<3, ReplicationPad3dImpl> {
+ public:
+  using ReplicationPadImpl<3, ReplicationPad3dImpl>::ReplicationPadImpl;
+};
+
+/// A `ModuleHolder` subclass for `ReplicationPad3dImpl`.
+/// See the documentation for `ReplicationPad3dImpl` class to learn what methods
+/// it provides, and examples of how to use `ReplicationPad3d` with
+/// `torch::nn::ReplicationPad3dOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(ReplicationPad3d);
+
+// ============================================================================
+
+/// Base class for all (dimension-specialized) ZeroPad modules.
+template 
+class TORCH_API ZeroPadImpl : public torch::nn::Cloneable {
+ public:
+  ZeroPadImpl(ExpandingArray padding)
+      : ZeroPadImpl(ZeroPadOptions(padding)) {}
+  explicit ZeroPadImpl(const ZeroPadOptions& options_);
+
+  void reset() override;
+
+  Tensor forward(const Tensor& input);
+
+  /// Pretty prints the `ZeroPad{1,2}d` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// The options with which this `Module` was constructed.
+  ZeroPadOptions options;
+};
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ZeroPad1d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+// Applies ZeroPad over a 1-D input.
+class TORCH_API ZeroPad1dImpl : public ZeroPadImpl<1, ZeroPad1dImpl> {
+ public:
+  using ZeroPadImpl<1, ZeroPad1dImpl>::ZeroPadImpl;
+};
+
+/// A `ModuleHolder` subclass for `ZeroPad1dImpl`.
+/// See the documentation for `ZeroPad1dImpl` class to learn what methods it
+/// provides, and examples of how to use `ZeroPad1d` with
+/// `torch::nn::ZeroPad1dOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(ZeroPad1d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ZeroPad2d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+// Applies ZeroPad over a 2-D input.
+class TORCH_API ZeroPad2dImpl : public ZeroPadImpl<2, ZeroPad2dImpl> {
+ public:
+  using ZeroPadImpl<2, ZeroPad2dImpl>::ZeroPadImpl;
+};
+
+/// A `ModuleHolder` subclass for `ZeroPad2dImpl`.
+/// See the documentation for `ZeroPad2dImpl` class to learn what methods it
+/// provides, and examples of how to use `ZeroPad2d` with
+/// `torch::nn::ZeroPad2dOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(ZeroPad2d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ZeroPad3d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+// Applies ZeroPad over a 3-D input.
+class TORCH_API ZeroPad3dImpl : public ZeroPadImpl<3, ZeroPad3dImpl> {
+ public:
+  using ZeroPadImpl<3, ZeroPad3dImpl>::ZeroPadImpl;
+};
+
+/// A `ModuleHolder` subclass for `ZeroPad3dImpl`.
+/// See the documentation for `ZeroPad3dImpl` class to learn what methods it
+/// provides, and examples of how to use `ZeroPad3d` with
+/// `torch::nn::ZeroPad3dOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(ZeroPad3d);
+
+// ============================================================================
+
+/// Base class for all (dimension-specialized) ConstantPad modules.
+template 
+class TORCH_API ConstantPadImpl : public torch::nn::Cloneable {
+ public:
+  ConstantPadImpl(ExpandingArray padding, double value)
+      : ConstantPadImpl(ConstantPadOptions(padding, value)) {}
+  explicit ConstantPadImpl(const ConstantPadOptions& options_);
+
+  void reset() override;
+
+  Tensor forward(const Tensor& input);
+
+  /// Pretty prints the `ConstantPad{1,2}d` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// The options with which this `Module` was constructed.
+  ConstantPadOptions options;
+};
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ConstantPad1d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies ConstantPad over a 1-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.ConstantPad1d to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::ConstantPad1dOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// ConstantPad1d model(ConstantPad1dOptions({3, 1}, 3.5));
+/// ```
+class TORCH_API ConstantPad1dImpl
+    : public ConstantPadImpl<1, ConstantPad1dImpl> {
+ public:
+  using ConstantPadImpl<1, ConstantPad1dImpl>::ConstantPadImpl;
+};
+
+/// A `ModuleHolder` subclass for `ConstantPad1dImpl`.
+/// See the documentation for `ConstantPad1dImpl` class to learn what methods it
+/// provides, and examples of how to use `ConstantPad1d` with
+/// `torch::nn::ConstantPad1dOptions`. See the documentation for `ModuleHolder`
+/// to learn about PyTorch's module storage semantics.
+TORCH_MODULE(ConstantPad1d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ConstantPad2d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies ConstantPad over a 2-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.ConstantPad2d to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::ConstantPad2dOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// ConstantPad2d model(ConstantPad2dOptions({3, 0, 2, 1}, 3.5));
+/// ```
+class TORCH_API ConstantPad2dImpl
+    : public ConstantPadImpl<2, ConstantPad2dImpl> {
+ public:
+  using ConstantPadImpl<2, ConstantPad2dImpl>::ConstantPadImpl;
+};
+
+/// A `ModuleHolder` subclass for `ConstantPad2dImpl`.
+/// See the documentation for `ConstantPad2dImpl` class to learn what methods it
+/// provides, and examples of how to use `ConstantPad2d` with
+/// `torch::nn::ConstantPad2dOptions`. See the documentation for `ModuleHolder`
+/// to learn about PyTorch's module storage semantics.
+TORCH_MODULE(ConstantPad2d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ConstantPad3d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies ConstantPad over a 3-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.ConstantPad3d to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::ConstantPad3dOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// ConstantPad3d model(ConstantPad3dOptions({1, 2, 1, 2, 1, 2}, 3.5));
+/// ```
+class TORCH_API ConstantPad3dImpl
+    : public ConstantPadImpl<3, ConstantPad3dImpl> {
+ public:
+  using ConstantPadImpl<3, ConstantPad3dImpl>::ConstantPadImpl;
+};
+
+/// A `ModuleHolder` subclass for `ConstantPad3dImpl`.
+/// See the documentation for `ConstantPad3dImpl` class to learn what methods it
+/// provides, and examples of how to use `ConstantPad3d` with
+/// `torch::nn::ConstantPad3dOptions`. See the documentation for `ModuleHolder`
+/// to learn about PyTorch's module storage semantics.
+TORCH_MODULE(ConstantPad3d);
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/pixelshuffle.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/pixelshuffle.h
new file mode 100644
index 0000000000000000000000000000000000000000..7ad916d332f45d24b418c8aed855682d9f960ec1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/pixelshuffle.h
@@ -0,0 +1,88 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+
+namespace torch {
+namespace nn {
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ PixelShuffle
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Rearranges elements in a tensor of shape :math:`(*, C \times r^2, H, W)`
+/// to a tensor of shape :math:`(*, C, H \times r, W \times r)`, where r is an
+/// upscale factor. See
+/// https://pytorch.org/docs/main/nn.html#torch.nn.PixelShuffle to learn about
+/// the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::PixelShuffleOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// PixelShuffle model(PixelShuffleOptions(5));
+/// ```
+struct TORCH_API PixelShuffleImpl
+    : public torch::nn::Cloneable {
+  explicit PixelShuffleImpl(const PixelShuffleOptions& options_);
+
+  /// Pretty prints the `PixelShuffle` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(const Tensor& input);
+
+  void reset() override;
+
+  /// The options with which this `Module` was constructed.
+  PixelShuffleOptions options;
+};
+
+/// A `ModuleHolder` subclass for `PixelShuffleImpl`.
+/// See the documentation for `PixelShuffleImpl` class to learn what methods it
+/// provides, and examples of how to use `PixelShuffle` with
+/// `torch::nn::PixelShuffleOptions`. See the documentation for `ModuleHolder`
+/// to learn about PyTorch's module storage semantics.
+TORCH_MODULE(PixelShuffle);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ PixelUnshuffle ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Reverses the PixelShuffle operation by rearranging elements in a tensor of
+/// shape :math:`(*, C, H \times r, W \times r)` to a tensor of shape :math:`(*,
+/// C \times r^2, H, W)`, where r is a downscale factor. See
+/// https://pytorch.org/docs/main/nn.html#torch.nn.PixelUnshuffle to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::PixelUnshuffleOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// PixelUnshuffle model(PixelUnshuffleOptions(5));
+/// ```
+struct TORCH_API PixelUnshuffleImpl
+    : public torch::nn::Cloneable {
+  explicit PixelUnshuffleImpl(const PixelUnshuffleOptions& options_);
+
+  /// Pretty prints the `PixelUnshuffle` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(const Tensor& input);
+
+  void reset() override;
+
+  /// The options with which this `Module` was constructed.
+  PixelUnshuffleOptions options;
+};
+
+/// A `ModuleHolder` subclass for `PixelUnshuffleImpl`.
+/// See the documentation for `PixelUnshuffleImpl` class to learn what methods
+/// it provides, and examples of how to use `PixelUnshuffle` with
+/// `torch::nn::PixelUnshuffleOptions`. See the documentation for `ModuleHolder`
+/// to learn about PyTorch's module storage semantics.
+TORCH_MODULE(PixelUnshuffle);
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/pooling.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/pooling.h
new file mode 100644
index 0000000000000000000000000000000000000000..0fac60edbcde40948f7dce1f0cea94a26fab2506
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/pooling.h
@@ -0,0 +1,779 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Base class for all (dimension-specialized) avgpool modules.
+template 
+class TORCH_API AvgPoolImpl : public torch::nn::Cloneable {
+ public:
+  AvgPoolImpl(ExpandingArray kernel_size)
+      : AvgPoolImpl(AvgPoolOptions(kernel_size)) {}
+  explicit AvgPoolImpl(const AvgPoolOptions& options_);
+
+  void reset() override;
+
+  /// Pretty prints the `AvgPool{1,2,3}d` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// The options with which this `Module` was constructed.
+  AvgPoolOptions options;
+};
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ AvgPool1d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies avgpool over a 1-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.AvgPool1d to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::AvgPool1dOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// AvgPool1d model(AvgPool1dOptions(3).stride(2));
+/// ```
+class TORCH_API AvgPool1dImpl : public AvgPoolImpl<1, AvgPool1dImpl> {
+ public:
+  using AvgPoolImpl<1, AvgPool1dImpl>::AvgPoolImpl;
+  Tensor forward(const Tensor& input);
+};
+
+/// A `ModuleHolder` subclass for `AvgPool1dImpl`.
+/// See the documentation for `AvgPool1dImpl` class to learn what methods it
+/// provides, and examples of how to use `AvgPool1d` with
+/// `torch::nn::AvgPool1dOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(AvgPool1d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ AvgPool2d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies avgpool over a 2-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.AvgPool2d to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::AvgPool2dOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// AvgPool2d model(AvgPool2dOptions({3, 2}).stride({2, 2}));
+/// ```
+class TORCH_API AvgPool2dImpl : public AvgPoolImpl<2, AvgPool2dImpl> {
+ public:
+  using AvgPoolImpl<2, AvgPool2dImpl>::AvgPoolImpl;
+  Tensor forward(const Tensor& input);
+};
+
+/// A `ModuleHolder` subclass for `AvgPool2dImpl`.
+/// See the documentation for `AvgPool2dImpl` class to learn what methods it
+/// provides, and examples of how to use `AvgPool2d` with
+/// `torch::nn::AvgPool2dOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(AvgPool2d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ AvgPool3d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies avgpool over a 3-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.AvgPool3d to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::AvgPool3dOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// AvgPool3d model(AvgPool3dOptions(5).stride(2));
+/// ```
+class TORCH_API AvgPool3dImpl : public AvgPoolImpl<3, AvgPool3dImpl> {
+ public:
+  using AvgPoolImpl<3, AvgPool3dImpl>::AvgPoolImpl;
+  Tensor forward(const Tensor& input);
+};
+
+/// A `ModuleHolder` subclass for `AvgPool3dImpl`.
+/// See the documentation for `AvgPool3dImpl` class to learn what methods it
+/// provides, and examples of how to use `AvgPool3d` with
+/// `torch::nn::AvgPool3dOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(AvgPool3d);
+
+// ============================================================================
+
+/// Base class for all (dimension-specialized) maxpool modules.
+template 
+class TORCH_API MaxPoolImpl : public torch::nn::Cloneable {
+ public:
+  MaxPoolImpl(ExpandingArray kernel_size)
+      : MaxPoolImpl(MaxPoolOptions(kernel_size)) {}
+  explicit MaxPoolImpl(const MaxPoolOptions& options_);
+
+  void reset() override;
+
+  /// Pretty prints the `MaxPool{1,2,3}d` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// The options with which this `Module` was constructed.
+  MaxPoolOptions options;
+};
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MaxPool1d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies maxpool over a 1-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.MaxPool1d to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::MaxPool1dOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// MaxPool1d model(MaxPool1dOptions(3).stride(2));
+/// ```
+class TORCH_API MaxPool1dImpl : public MaxPoolImpl<1, MaxPool1dImpl> {
+ public:
+  using MaxPoolImpl<1, MaxPool1dImpl>::MaxPoolImpl;
+  Tensor forward(const Tensor& input);
+
+  /// Returns the outputs and the indices of the max values.
+  /// Useful for `torch::nn::MaxUnpool1d` later.
+  std::tuple forward_with_indices(const Tensor& input);
+};
+
+/// A `ModuleHolder` subclass for `MaxPool1dImpl`.
+/// See the documentation for `MaxPool1dImpl` class to learn what methods it
+/// provides, and examples of how to use `MaxPool1d` with
+/// `torch::nn::MaxPool1dOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(MaxPool1d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MaxPool2d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies maxpool over a 2-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.MaxPool2d to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::MaxPool2dOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// MaxPool2d model(MaxPool2dOptions({3, 2}).stride({2, 2}));
+/// ```
+class TORCH_API MaxPool2dImpl : public MaxPoolImpl<2, MaxPool2dImpl> {
+ public:
+  using MaxPoolImpl<2, MaxPool2dImpl>::MaxPoolImpl;
+  Tensor forward(const Tensor& input);
+
+  /// Returns the outputs and the indices of the max values.
+  /// Useful for `torch::nn::MaxUnpool2d` later.
+  std::tuple forward_with_indices(const Tensor& input);
+};
+
+/// A `ModuleHolder` subclass for `MaxPool2dImpl`.
+/// See the documentation for `MaxPool2dImpl` class to learn what methods it
+/// provides, and examples of how to use `MaxPool2d` with
+/// `torch::nn::MaxPool2dOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(MaxPool2d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MaxPool3d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies maxpool over a 3-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.MaxPool3d to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::MaxPool3dOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// MaxPool3d model(MaxPool3dOptions(3).stride(2));
+/// ```
+class TORCH_API MaxPool3dImpl : public MaxPoolImpl<3, MaxPool3dImpl> {
+ public:
+  using MaxPoolImpl<3, MaxPool3dImpl>::MaxPoolImpl;
+  Tensor forward(const Tensor& input);
+
+  /// Returns the outputs and the indices of the max values.
+  /// Useful for `torch::nn::MaxUnpool3d` later.
+  std::tuple forward_with_indices(const Tensor& input);
+};
+
+/// A `ModuleHolder` subclass for `MaxPool3dImpl`.
+/// See the documentation for `MaxPool3dImpl` class to learn what methods it
+/// provides, and examples of how to use `MaxPool3d` with
+/// `torch::nn::MaxPool3dOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(MaxPool3d);
+
+// ============================================================================
+
+/// Base class for all (dimension-specialized) adaptive maxpool modules.
+template 
+class TORCH_API AdaptiveMaxPoolImpl : public torch::nn::Cloneable {
+ public:
+  AdaptiveMaxPoolImpl(output_size_t output_size)
+      : AdaptiveMaxPoolImpl(
+            AdaptiveMaxPoolOptions(output_size)) {}
+  explicit AdaptiveMaxPoolImpl(
+      const AdaptiveMaxPoolOptions& options_)
+      : options(options_) {}
+
+  void reset() override{};
+
+  /// Pretty prints the `AdaptiveMaxPool{1,2,3}d` module into the given
+  /// `stream`.
+  void pretty_print(std::ostream& stream) const override {
+    stream << "torch::nn::AdaptiveMaxPool" << D << "d"
+           << "(output_size=" << options.output_size() << ")";
+  }
+
+  /// The options with which this `Module` was constructed.
+  AdaptiveMaxPoolOptions options;
+};
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ AdaptiveMaxPool1d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies adaptive maxpool over a 1-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.AdaptiveMaxPool1d to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::AdaptiveMaxPool1dOptions` class to
+/// learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// AdaptiveMaxPool1d model(AdaptiveMaxPool1dOptions(3));
+/// ```
+class TORCH_API AdaptiveMaxPool1dImpl
+    : public AdaptiveMaxPoolImpl<1, ExpandingArray<1>, AdaptiveMaxPool1dImpl> {
+ public:
+  using AdaptiveMaxPoolImpl<1, ExpandingArray<1>, AdaptiveMaxPool1dImpl>::
+      AdaptiveMaxPoolImpl;
+
+  Tensor forward(const Tensor& input);
+
+  /// Returns the indices along with the outputs.
+  /// Useful to pass to nn.MaxUnpool1d.
+  std::tuple forward_with_indices(const Tensor& input);
+};
+
+/// A `ModuleHolder` subclass for `AdaptiveMaxPool1dImpl`.
+/// See the documentation for `AdaptiveMaxPool1dImpl` class to learn what
+/// methods it provides, and examples of how to use `AdaptiveMaxPool1d` with
+/// `torch::nn::AdaptiveMaxPool1dOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(AdaptiveMaxPool1d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ AdaptiveMaxPool2d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies adaptive maxpool over a 2-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.AdaptiveMaxPool2d to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::AdaptiveMaxPool2dOptions` class to
+/// learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// AdaptiveMaxPool2d model(AdaptiveMaxPool2dOptions({3, 2}));
+/// ```
+class TORCH_API AdaptiveMaxPool2dImpl : public AdaptiveMaxPoolImpl<
+                                            2,
+                                            ExpandingArrayWithOptionalElem<2>,
+                                            AdaptiveMaxPool2dImpl> {
+ public:
+  using AdaptiveMaxPoolImpl<
+      2,
+      ExpandingArrayWithOptionalElem<2>,
+      AdaptiveMaxPool2dImpl>::AdaptiveMaxPoolImpl;
+
+  Tensor forward(const Tensor& input);
+
+  /// Returns the indices along with the outputs.
+  /// Useful to pass to nn.MaxUnpool2d.
+  std::tuple forward_with_indices(const Tensor& input);
+};
+
+/// A `ModuleHolder` subclass for `AdaptiveMaxPool2dImpl`.
+/// See the documentation for `AdaptiveMaxPool2dImpl` class to learn what
+/// methods it provides, and examples of how to use `AdaptiveMaxPool2d` with
+/// `torch::nn::AdaptiveMaxPool2dOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(AdaptiveMaxPool2d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ AdaptiveMaxPool3d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies adaptive maxpool over a 3-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.AdaptiveMaxPool3d to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::AdaptiveMaxPool3dOptions` class to
+/// learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// AdaptiveMaxPool3d model(AdaptiveMaxPool3dOptions(3));
+/// ```
+class TORCH_API AdaptiveMaxPool3dImpl : public AdaptiveMaxPoolImpl<
+                                            3,
+                                            ExpandingArrayWithOptionalElem<3>,
+                                            AdaptiveMaxPool3dImpl> {
+ public:
+  using AdaptiveMaxPoolImpl<
+      3,
+      ExpandingArrayWithOptionalElem<3>,
+      AdaptiveMaxPool3dImpl>::AdaptiveMaxPoolImpl;
+
+  Tensor forward(const Tensor& input);
+
+  /// Returns the indices along with the outputs.
+  /// Useful to pass to nn.MaxUnpool3d.
+  std::tuple forward_with_indices(const Tensor& input);
+};
+
+/// A `ModuleHolder` subclass for `AdaptiveMaxPool3dImpl`.
+/// See the documentation for `AdaptiveMaxPool3dImpl` class to learn what
+/// methods it provides, and examples of how to use `AdaptiveMaxPool3d` with
+/// `torch::nn::AdaptiveMaxPool3dOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(AdaptiveMaxPool3d);
+
+// ============================================================================
+
+/// Base class for all (dimension-specialized) adaptive avgpool modules.
+template 
+class TORCH_API AdaptiveAvgPoolImpl : public torch::nn::Cloneable {
+ public:
+  AdaptiveAvgPoolImpl(output_size_t output_size)
+      : AdaptiveAvgPoolImpl(
+            AdaptiveAvgPoolOptions(output_size)) {}
+  explicit AdaptiveAvgPoolImpl(
+      const AdaptiveAvgPoolOptions& options_)
+      : options(options_) {}
+
+  void reset() override {}
+
+  /// Pretty prints the `AdaptiveAvgPool{1,2,3}d` module into the given
+  /// `stream`.
+  void pretty_print(std::ostream& stream) const override {
+    stream << "torch::nn::AdaptiveAvgPool" << D << "d"
+           << "(output_size=" << options.output_size() << ")";
+  }
+
+  /// The options with which this `Module` was constructed.
+  AdaptiveAvgPoolOptions options;
+};
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ AdaptiveAvgPool1d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies adaptive avgpool over a 1-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.AdaptiveAvgPool1d to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::AdaptiveAvgPool1dOptions` class to
+/// learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// AdaptiveAvgPool1d model(AdaptiveAvgPool1dOptions(5));
+/// ```
+class TORCH_API AdaptiveAvgPool1dImpl
+    : public AdaptiveAvgPoolImpl<1, ExpandingArray<1>, AdaptiveAvgPool1dImpl> {
+ public:
+  using AdaptiveAvgPoolImpl<1, ExpandingArray<1>, AdaptiveAvgPool1dImpl>::
+      AdaptiveAvgPoolImpl;
+
+  Tensor forward(const Tensor& input);
+};
+
+/// A `ModuleHolder` subclass for `AdaptiveAvgPool1dImpl`.
+/// See the documentation for `AdaptiveAvgPool1dImpl` class to learn what
+/// methods it provides, and examples of how to use `AdaptiveAvgPool1d` with
+/// `torch::nn::AdaptiveAvgPool1dOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(AdaptiveAvgPool1d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ AdaptiveAvgPool2d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies adaptive avgpool over a 2-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.AdaptiveAvgPool2d to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::AdaptiveAvgPool2dOptions` class to
+/// learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// AdaptiveAvgPool2d model(AdaptiveAvgPool2dOptions({3, 2}));
+/// ```
+class TORCH_API AdaptiveAvgPool2dImpl : public AdaptiveAvgPoolImpl<
+                                            2,
+                                            ExpandingArrayWithOptionalElem<2>,
+                                            AdaptiveAvgPool2dImpl> {
+ public:
+  using AdaptiveAvgPoolImpl<
+      2,
+      ExpandingArrayWithOptionalElem<2>,
+      AdaptiveAvgPool2dImpl>::AdaptiveAvgPoolImpl;
+
+  Tensor forward(const Tensor& input);
+};
+
+/// A `ModuleHolder` subclass for `AdaptiveAvgPool2dImpl`.
+/// See the documentation for `AdaptiveAvgPool2dImpl` class to learn what
+/// methods it provides, and examples of how to use `AdaptiveAvgPool2d` with
+/// `torch::nn::AdaptiveAvgPool2dOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(AdaptiveAvgPool2d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ AdaptiveAvgPool3d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies adaptive avgpool over a 3-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.AdaptiveAvgPool3d to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::AdaptiveAvgPool3dOptions` class to
+/// learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// AdaptiveAvgPool3d model(AdaptiveAvgPool3dOptions(3));
+/// ```
+class TORCH_API AdaptiveAvgPool3dImpl : public AdaptiveAvgPoolImpl<
+                                            3,
+                                            ExpandingArrayWithOptionalElem<3>,
+                                            AdaptiveAvgPool3dImpl> {
+ public:
+  using AdaptiveAvgPoolImpl<
+      3,
+      ExpandingArrayWithOptionalElem<3>,
+      AdaptiveAvgPool3dImpl>::AdaptiveAvgPoolImpl;
+
+  Tensor forward(const Tensor& input);
+};
+
+/// A `ModuleHolder` subclass for `AdaptiveAvgPool3dImpl`.
+/// See the documentation for `AdaptiveAvgPool3dImpl` class to learn what
+/// methods it provides, and examples of how to use `AdaptiveAvgPool3d` with
+/// `torch::nn::AdaptiveAvgPool3dOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(AdaptiveAvgPool3d);
+
+// ============================================================================
+
+/// Base class for all (dimension-specialized) maxunpool modules.
+template 
+class TORCH_API MaxUnpoolImpl : public torch::nn::Cloneable {
+ public:
+  MaxUnpoolImpl(ExpandingArray kernel_size)
+      : MaxUnpoolImpl(MaxUnpoolOptions(kernel_size)) {}
+  explicit MaxUnpoolImpl(const MaxUnpoolOptions& options_);
+
+  void reset() override;
+
+  /// Pretty prints the `MaxUnpool{1,2,3}d` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// The options with which this `Module` was constructed.
+  MaxUnpoolOptions options;
+};
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MaxUnpool1d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies maxunpool over a 1-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.MaxUnpool1d to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::MaxUnpool1dOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// MaxUnpool1d model(MaxUnpool1dOptions(3).stride(2).padding(1));
+/// ```
+class TORCH_API MaxUnpool1dImpl : public MaxUnpoolImpl<1, MaxUnpool1dImpl> {
+ public:
+  using MaxUnpoolImpl<1, MaxUnpool1dImpl>::MaxUnpoolImpl;
+  Tensor forward(
+      const Tensor& input,
+      const Tensor& indices,
+      const std::optional>& output_size = std::nullopt);
+
+ protected:
+  FORWARD_HAS_DEFAULT_ARGS({2, AnyValue(std::optional>())})
+};
+
+/// A `ModuleHolder` subclass for `MaxUnpool1dImpl`.
+/// See the documentation for `MaxUnpool1dImpl` class to learn what methods it
+/// provides, and examples of how to use `MaxUnpool1d` with
+/// `torch::nn::MaxUnpool1dOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(MaxUnpool1d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MaxUnpool2d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies maxunpool over a 2-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.MaxUnpool2d to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::MaxUnpool2dOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// MaxUnpool2d model(MaxUnpool2dOptions(3).stride(2).padding(1));
+/// ```
+class TORCH_API MaxUnpool2dImpl : public MaxUnpoolImpl<2, MaxUnpool2dImpl> {
+ public:
+  using MaxUnpoolImpl<2, MaxUnpool2dImpl>::MaxUnpoolImpl;
+  Tensor forward(
+      const Tensor& input,
+      const Tensor& indices,
+      const std::optional>& output_size = std::nullopt);
+
+ protected:
+  FORWARD_HAS_DEFAULT_ARGS({2, AnyValue(std::optional>())})
+};
+
+/// A `ModuleHolder` subclass for `MaxUnpool2dImpl`.
+/// See the documentation for `MaxUnpool2dImpl` class to learn what methods it
+/// provides, and examples of how to use `MaxUnpool2d` with
+/// `torch::nn::MaxUnpool2dOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(MaxUnpool2d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MaxUnpool3d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies maxunpool over a 3-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.MaxUnpool3d to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::MaxUnpool3dOptions` class to learn
+/// what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// MaxUnpool3d model(MaxUnpool3dOptions(3).stride(2).padding(1));
+/// ```
+class TORCH_API MaxUnpool3dImpl : public MaxUnpoolImpl<3, MaxUnpool3dImpl> {
+ public:
+  using MaxUnpoolImpl<3, MaxUnpool3dImpl>::MaxUnpoolImpl;
+  Tensor forward(
+      const Tensor& input,
+      const Tensor& indices,
+      const std::optional>& output_size = std::nullopt);
+
+ protected:
+  FORWARD_HAS_DEFAULT_ARGS({2, AnyValue(std::optional>())})
+};
+
+/// A `ModuleHolder` subclass for `MaxUnpool3dImpl`.
+/// See the documentation for `MaxUnpool3dImpl` class to learn what methods it
+/// provides, and examples of how to use `MaxUnpool3d` with
+/// `torch::nn::MaxUnpool3dOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(MaxUnpool3d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FractionalMaxPool2d
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies fractional maxpool over a 2-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.FractionalMaxPool2d to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::FractionalMaxPool2dOptions` class to
+/// learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// FractionalMaxPool2d model(FractionalMaxPool2dOptions(5).output_size(1));
+/// ```
+class TORCH_API FractionalMaxPool2dImpl
+    : public torch::nn::Cloneable {
+ public:
+  FractionalMaxPool2dImpl(ExpandingArray<2> kernel_size)
+      : FractionalMaxPool2dImpl(FractionalMaxPool2dOptions(kernel_size)) {}
+  explicit FractionalMaxPool2dImpl(FractionalMaxPool2dOptions options_);
+
+  void reset() override;
+
+  /// Pretty prints the `FractionalMaxPool2d` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(const Tensor& input);
+
+  /// Returns the outputs and the indices of the max values.
+  /// Useful for `torch::nn::MaxUnpool2d` later.
+  std::tuple forward_with_indices(const Tensor& input);
+
+  /// The options with which this `Module` was constructed.
+  FractionalMaxPool2dOptions options;
+
+  Tensor _random_samples;
+};
+
+/// A `ModuleHolder` subclass for `FractionalMaxPool2dImpl`.
+/// See the documentation for `FractionalMaxPool2dImpl` class to learn what
+/// methods it provides, and examples of how to use `FractionalMaxPool2d` with
+/// `torch::nn::FractionalMaxPool2dOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(FractionalMaxPool2d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FractionalMaxPool3d
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies fractional maxpool over a 3-D input.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.FractionalMaxPool3d to
+/// learn about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::FractionalMaxPool3dOptions` class to
+/// learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// FractionalMaxPool3d model(FractionalMaxPool3dOptions(5).output_size(1));
+/// ```
+class TORCH_API FractionalMaxPool3dImpl
+    : public torch::nn::Cloneable {
+ public:
+  FractionalMaxPool3dImpl(ExpandingArray<3> kernel_size)
+      : FractionalMaxPool3dImpl(FractionalMaxPool3dOptions(kernel_size)) {}
+  explicit FractionalMaxPool3dImpl(FractionalMaxPool3dOptions options_);
+
+  void reset() override;
+
+  /// Pretty prints the `FractionalMaxPool3d` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(const Tensor& input);
+
+  /// Returns the outputs and the indices of the max values.
+  /// Useful for `torch::nn::MaxUnpool3d` later.
+  std::tuple forward_with_indices(const Tensor& input);
+
+  /// The options with which this `Module` was constructed.
+  FractionalMaxPool3dOptions options;
+
+  Tensor _random_samples;
+};
+
+/// A `ModuleHolder` subclass for `FractionalMaxPool3dImpl`.
+/// See the documentation for `FractionalMaxPool3dImpl` class to learn what
+/// methods it provides, and examples of how to use `FractionalMaxPool3d` with
+/// `torch::nn::FractionalMaxPool3dOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(FractionalMaxPool3d);
+
+// ============================================================================
+
+/// Base class for all (dimension-specialized) lppool modules.
+template 
+class TORCH_API LPPoolImpl : public torch::nn::Cloneable {
+ public:
+  LPPoolImpl(double norm_type, ExpandingArray kernel_size)
+      : LPPoolImpl(LPPoolOptions(norm_type, kernel_size)) {}
+  explicit LPPoolImpl(const LPPoolOptions& options_);
+
+  void reset() override;
+
+  /// Pretty prints the `LPPool{1,2}d` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  LPPoolOptions options;
+};
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ LPPool1d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the LPPool1d function element-wise.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.LPPool1d to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::LPPool1dOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// LPPool1d model(LPPool1dOptions(1, 2).stride(5).ceil_mode(true));
+/// ```
+class TORCH_API LPPool1dImpl : public LPPoolImpl<1, LPPool1dImpl> {
+ public:
+  using LPPoolImpl<1, LPPool1dImpl>::LPPoolImpl;
+
+  Tensor forward(const Tensor& input);
+};
+
+/// A `ModuleHolder` subclass for `LPPool1dImpl`.
+/// See the documentation for `LPPool1dImpl` class to learn what methods it
+/// provides, and examples of how to use `LPPool1d` with
+/// `torch::nn::LPPool1dOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(LPPool1d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ LPPool2d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the LPPool2d function element-wise.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.LPPool2d to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::LPPool2dOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// LPPool2d model(LPPool2dOptions(1, std::vector({3, 4})).stride({5,
+/// 6}).ceil_mode(true));
+/// ```
+class TORCH_API LPPool2dImpl : public LPPoolImpl<2, LPPool2dImpl> {
+ public:
+  using LPPoolImpl<2, LPPool2dImpl>::LPPoolImpl;
+
+  Tensor forward(const Tensor& input);
+};
+
+/// A `ModuleHolder` subclass for `LPPool2dImpl`.
+/// See the documentation for `LPPool2dImpl` class to learn what methods it
+/// provides, and examples of how to use `LPPool2d` with
+/// `torch::nn::LPPool2dOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(LPPool2d);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ LPPool3d ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Applies the LPPool3d function element-wise.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.LPPool3d to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::LPPool3dOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// LPPool3d model(LPPool3dOptions(1, std::vector({3, 4, 5})).stride(
+/// {5, 6, 7}).ceil_mode(true));
+/// ```
+class TORCH_API LPPool3dImpl : public LPPoolImpl<3, LPPool3dImpl> {
+ public:
+  using LPPoolImpl<3, LPPool3dImpl>::LPPoolImpl;
+
+  Tensor forward(const Tensor& input);
+};
+
+/// A `ModuleHolder` subclass for `LPPool3dImpl`.
+/// See the documentation for `LPPool3dImpl` class to learn what methods it
+/// provides, and examples of how to use `LPPool3d` with
+/// `torch::nn::LPPool3dOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(LPPool3d);
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/rnn.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/rnn.h
new file mode 100644
index 0000000000000000000000000000000000000000..eaa76d215fe2bbe32ff922cb1a62fe0ab89111d0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/rnn.h
@@ -0,0 +1,401 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+namespace detail {
+/// Base class for all RNN implementations (intended for code sharing).
+template 
+class TORCH_API RNNImplBase : public torch::nn::Cloneable {
+ public:
+  explicit RNNImplBase(const RNNOptionsBase& options_);
+
+  /// Initializes the parameters of the RNN module.
+  void reset() override;
+
+  void reset_parameters();
+
+  /// Overrides `nn::Module::to()` to call `flatten_parameters()` after the
+  /// original operation.
+  void to(torch::Device device, torch::Dtype dtype, bool non_blocking = false)
+      override;
+  void to(torch::Dtype dtype, bool non_blocking = false) override;
+  void to(torch::Device device, bool non_blocking = false) override;
+
+  /// Pretty prints the RNN module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  /// Modifies the internal storage of weights for optimization purposes.
+  ///
+  /// On CPU, this method should be called if any of the weight or bias vectors
+  /// are changed (i.e. weights are added or removed). On GPU, it should be
+  /// called __any time the storage of any parameter is modified__, e.g. any
+  /// time a parameter is assigned a new value. This allows using the fast path
+  /// in cuDNN implementations of respective RNN `forward()` methods. It is
+  /// called once upon construction, inside `reset()`.
+  void flatten_parameters();
+
+  std::vector all_weights() const;
+
+  /// The RNN's options.
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  RNNOptionsBase options_base;
+
+ protected:
+  // Resets flat_weights_
+  // Note: be v. careful before removing this, as 3rd party device types
+  // likely rely on this behavior to properly .to() modules like LSTM.
+  void reset_flat_weights();
+
+  void check_input(const Tensor& input, const Tensor& batch_sizes) const;
+
+  std::tuple get_expected_hidden_size(
+      const Tensor& input,
+      const Tensor& batch_sizes) const;
+
+  void check_hidden_size(
+      const Tensor& hx,
+      std::tuple expected_hidden_size,
+      std::string msg = "Expected hidden size {1}, got {2}") const;
+
+  void check_forward_args(Tensor input, Tensor hidden, Tensor batch_sizes)
+      const;
+
+  Tensor permute_hidden(Tensor hx, const Tensor& permutation) const;
+
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  std::vector flat_weights_names_;
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  std::vector> all_weights_;
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  std::vector flat_weights_;
+};
+} // namespace detail
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ RNN ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// A multi-layer Elman RNN module with Tanh or ReLU activation.
+/// See https://pytorch.org/docs/main/generated/torch.nn.RNN.html to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::RNNOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// RNN model(RNNOptions(128,
+/// 64).num_layers(3).dropout(0.2).nonlinearity(torch::kTanh));
+/// ```
+class TORCH_API RNNImpl : public detail::RNNImplBase {
+ public:
+  RNNImpl(int64_t input_size, int64_t hidden_size)
+      : RNNImpl(RNNOptions(input_size, hidden_size)) {}
+  explicit RNNImpl(const RNNOptions& options_);
+
+  std::tuple forward(const Tensor& input, Tensor hx = {});
+
+ protected:
+  FORWARD_HAS_DEFAULT_ARGS({1, AnyValue(Tensor())})
+
+ public:
+  std::tuple
+  forward_with_packed_input(
+      const torch::nn::utils::rnn::PackedSequence& packed_input,
+      Tensor hx = {});
+
+  RNNOptions options;
+
+ protected:
+  std::tuple forward_helper(
+      const Tensor& input,
+      const Tensor& batch_sizes,
+      const Tensor& sorted_indices,
+      int64_t max_batch_size,
+      Tensor hx);
+};
+
+/// A `ModuleHolder` subclass for `RNNImpl`.
+/// See the documentation for `RNNImpl` class to learn what methods it
+/// provides, and examples of how to use `RNN` with `torch::nn::RNNOptions`.
+/// See the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(RNN);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ LSTM ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// A multi-layer long-short-term-memory (LSTM) module.
+/// See https://pytorch.org/docs/main/generated/torch.nn.LSTM.html to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::LSTMOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// LSTM model(LSTMOptions(2,
+/// 4).num_layers(3).batch_first(false).bidirectional(true));
+/// ```
+class TORCH_API LSTMImpl : public detail::RNNImplBase {
+ public:
+  LSTMImpl(int64_t input_size, int64_t hidden_size)
+      : LSTMImpl(LSTMOptions(input_size, hidden_size)) {}
+  explicit LSTMImpl(const LSTMOptions& options_);
+
+  std::tuple> forward(
+      const Tensor& input,
+      torch::optional> hx_opt = {});
+
+ protected:
+  FORWARD_HAS_DEFAULT_ARGS(
+      {1, AnyValue(torch::optional>())})
+
+ public:
+  std::tuple>
+  forward_with_packed_input(
+      const torch::nn::utils::rnn::PackedSequence& packed_input,
+      torch::optional> hx_opt = {});
+
+  LSTMOptions options;
+
+ protected:
+  void check_forward_args(
+      const Tensor& input,
+      std::tuple hidden,
+      const Tensor& batch_sizes) const;
+
+  std::tuple get_expected_cell_size(
+      const Tensor& input,
+      const Tensor& batch_sizes) const;
+
+  std::tuple permute_hidden(
+      std::tuple hx,
+      const Tensor& permutation) const;
+
+  std::tuple> forward_helper(
+      const Tensor& input,
+      const Tensor& batch_sizes,
+      const Tensor& sorted_indices,
+      int64_t max_batch_size,
+      torch::optional> hx_opt);
+};
+
+/// A `ModuleHolder` subclass for `LSTMImpl`.
+/// See the documentation for `LSTMImpl` class to learn what methods it
+/// provides, and examples of how to use `LSTM` with `torch::nn::LSTMOptions`.
+/// See the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(LSTM);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GRU ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// A multi-layer gated recurrent unit (GRU) module.
+/// See https://pytorch.org/docs/main/generated/torch.nn.GRU.html to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::GRUOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// GRU model(GRUOptions(2,
+/// 4).num_layers(3).batch_first(false).bidirectional(true));
+/// ```
+class TORCH_API GRUImpl : public detail::RNNImplBase {
+ public:
+  GRUImpl(int64_t input_size, int64_t hidden_size)
+      : GRUImpl(GRUOptions(input_size, hidden_size)) {}
+  explicit GRUImpl(const GRUOptions& options_);
+
+  std::tuple forward(const Tensor& input, Tensor hx = {});
+
+ protected:
+  FORWARD_HAS_DEFAULT_ARGS({1, AnyValue(torch::Tensor())})
+
+ public:
+  std::tuple
+  forward_with_packed_input(
+      const torch::nn::utils::rnn::PackedSequence& packed_input,
+      Tensor hx = {});
+
+  GRUOptions options;
+
+ protected:
+  std::tuple forward_helper(
+      const Tensor& input,
+      const Tensor& batch_sizes,
+      const Tensor& sorted_indices,
+      int64_t max_batch_size,
+      Tensor hx);
+};
+
+/// A `ModuleHolder` subclass for `GRUImpl`.
+/// See the documentation for `GRUImpl` class to learn what methods it
+/// provides, and examples of how to use `GRU` with `torch::nn::GRUOptions`.
+/// See the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(GRU);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ RNNCellImplBase
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+namespace detail {
+/// Base class for all RNNCell implementations (intended for code sharing).
+template 
+class TORCH_API RNNCellImplBase : public torch::nn::Cloneable {
+ public:
+  explicit RNNCellImplBase(const RNNCellOptionsBase& options_);
+
+  /// Initializes the parameters of the RNNCell module.
+  void reset() override;
+
+  void reset_parameters();
+
+  /// Pretty prints the RNN module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  RNNCellOptionsBase options_base;
+
+  Tensor weight_ih;
+  Tensor weight_hh;
+  Tensor bias_ih;
+  Tensor bias_hh;
+
+ protected:
+  void check_forward_input(const Tensor& input, const std::string& name) const;
+  virtual std::string get_nonlinearity_str() const;
+};
+} // namespace detail
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ RNNCell
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// An Elman RNN cell with tanh or ReLU non-linearity.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.RNNCell to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::RNNCellOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// RNNCell model(RNNCellOptions(20,
+/// 10).bias(false).nonlinearity(torch::kReLU));
+/// ```
+class TORCH_API RNNCellImpl : public detail::RNNCellImplBase {
+ public:
+  RNNCellImpl(int64_t input_size, int64_t hidden_size)
+      : RNNCellImpl(RNNCellOptions(input_size, hidden_size)) {}
+  explicit RNNCellImpl(const RNNCellOptions& options_);
+
+  Tensor forward(const Tensor& input, Tensor hx = {});
+
+ protected:
+  FORWARD_HAS_DEFAULT_ARGS({1, AnyValue(Tensor())})
+
+ public:
+  RNNCellOptions options;
+
+ protected:
+  std::string get_nonlinearity_str() const override;
+};
+
+/// A `ModuleHolder` subclass for `RNNCellImpl`.
+/// See the documentation for `RNNCellImpl` class to learn what methods it
+/// provides, and examples of how to use `RNNCell` with
+/// `torch::nn::RNNCellOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(RNNCell);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ LSTMCell
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// A long short-term memory (LSTM) cell.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.LSTMCell to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::LSTMCellOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// LSTMCell model(LSTMCellOptions(20, 10).bias(false));
+/// ```
+class TORCH_API LSTMCellImpl : public detail::RNNCellImplBase {
+ public:
+  LSTMCellImpl(int64_t input_size, int64_t hidden_size)
+      : LSTMCellImpl(LSTMCellOptions(input_size, hidden_size)) {}
+  explicit LSTMCellImpl(const LSTMCellOptions& options_);
+
+  std::tuple forward(
+      const Tensor& input,
+      torch::optional> hx_opt = {});
+
+ protected:
+  FORWARD_HAS_DEFAULT_ARGS(
+      {1, AnyValue(torch::optional>())})
+
+ public:
+  LSTMCellOptions options;
+};
+
+/// A `ModuleHolder` subclass for `LSTMCellImpl`.
+/// See the documentation for `LSTMCellImpl` class to learn what methods it
+/// provides, and examples of how to use `LSTMCell` with
+/// `torch::nn::LSTMCellOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(LSTMCell);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GRUCell
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// A gated recurrent unit (GRU) cell.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.GRUCell to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::GRUCellOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// GRUCell model(GRUCellOptions(20, 10).bias(false));
+/// ```
+class TORCH_API GRUCellImpl : public detail::RNNCellImplBase {
+ public:
+  GRUCellImpl(int64_t input_size, int64_t hidden_size)
+      : GRUCellImpl(GRUCellOptions(input_size, hidden_size)) {}
+  explicit GRUCellImpl(const GRUCellOptions& options_);
+
+  Tensor forward(const Tensor& input, Tensor hx = {});
+
+ protected:
+  FORWARD_HAS_DEFAULT_ARGS({1, AnyValue(Tensor())})
+
+ public:
+  GRUCellOptions options;
+};
+
+/// A `ModuleHolder` subclass for `GRUCellImpl`.
+/// See the documentation for `GRUCellImpl` class to learn what methods it
+/// provides, and examples of how to use `GRUCell` with
+/// `torch::nn::GRUCellOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(GRUCell);
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/transformer.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/transformer.h
new file mode 100644
index 0000000000000000000000000000000000000000..c8c417c7564b3705cfe58f887bf43a03b7573f53
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/transformer.h
@@ -0,0 +1,143 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include 
+
+namespace torch {
+namespace nn {
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Transformer ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// A transformer model. User is able to modify the attributes as needed. The
+/// architecture is based on the paper "Attention Is All You Need". Ashish
+/// Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N
+/// Gomez, Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need.
+/// In Advances in Neural Information Processing Systems, pages 6000-6010.
+///
+/// See https://pytorch.org/docs/stable/generated/torch.nn.Transformer.html to
+/// learn about the exact behavior of this transformer model
+///
+/// See the documentation for `torch::nn::Transformer` class to learn what
+/// constructor arguments are supported for this encoder layer model
+///
+/// Example:
+/// ```
+/// Transformer trans(TransformerOptions(512, 8));
+/// ```
+class TORCH_API TransformerImpl : public Cloneable {
+ public:
+  explicit TransformerImpl(TransformerOptions options_);
+
+  /// forward function for Transformer Module
+  /// Args:
+  ///   src: the sequence to the encoder (required).
+  ///   tgt: the sequence to the decoder (required).
+  ///   src_mask: the additive mask for the src sequence (optional).
+  ///   tgt_mask: the additive mask for the tgt sequence (optional).
+  ///   memory_mask: the additive mask for the encoder output (optional).
+  ///   src_key_padding_mask: the ByteTensor mask for src keys per batch
+  ///   (optional). tgt_key_padding_mask: the ByteTensor mask for tgt keys per
+  ///   batch (optional). memory_key_padding_mask: the ByteTensor mask for
+  ///   memory keys per batch (optional).
+  ///
+  /// Shape:
+  ///   src: `(S, N, E)`
+  ///   tgt: `(T, N, E)`
+  ///   src_mask: `(S, S)`
+  ///   tgt_mask: `(T, T)`
+  ///   memory_mask: `(T, S)`
+  ///   src_key_padding_mask: `(N, S)`
+  ///   tgt_key_padding_mask: `(N, T)`
+  ///   memory_key_padding_mask: `(N, S)`
+  ///
+  ///   Note:
+  ///     [src/tgt/memory]_mask ensures that position i is allowed to attend the
+  ///     unmasked positions. If a ByteTensor is provided, the non-zero
+  ///     positions are not allowed to attend while the zero positions will be
+  ///     unchanged. If a BoolTensor is provided, positions with `True` are not
+  ///     allowed to attend while `False` values will be unchanged. If a
+  ///     FloatTensor is provided, it will be added to the attention weight.
+  ///
+  ///     [src/tgt/memory]_key_padding_mask provides specified elements in the
+  ///     key to be ignored by the attention. If a ByteTensor is provided, the
+  ///     non-zero positions will be ignored while the zero positions will be
+  ///     unchanged. If a BoolTensor is provided, the positions with the value
+  ///     of `True` will be ignored while the position with the value of `False`
+  ///     will be unchanged.
+  ///
+  ///   output: `(T, N, E)`
+  ///
+  ///   Note:
+  ///     Due to the multi-head attention architecture in the transformer model,
+  ///     the output sequence length of a transformer is same as the input
+  ///     sequence (i.e. target) length of the decode.
+  ///
+  ///   where
+  ///   S is the source sequence length,
+  ///   T is the target sequence length,
+  ///   N is the batch size,
+  ///   E is the feature number.
+  Tensor forward(
+      const Tensor& src,
+      const Tensor& tgt,
+      const Tensor& src_mask = {},
+      const Tensor& tgt_mask = {},
+      const Tensor& memory_mask = {},
+      const Tensor& src_key_padding_mask = {},
+      const Tensor& tgt_key_padding_mask = {},
+      const Tensor& memory_key_padding_mask = {});
+
+  void reset() override;
+
+  void reset_parameters();
+
+  /// Generate a square mask for the sequence.
+  /// The masked positions are filled with `-inf` in float type.
+  /// Unmasked positions are filled with `0.0` in float type.
+  /// Note:
+  ///   1. This function will always return a CPU tensor.
+  ///   2. This function requires the platform support IEEE754, since `-inf` is
+  ///   guaranteed to
+  ///      be valid only when IEEE754 is supported. If the platform doesn't
+  ///      support IEEE754, this function will fill the mask with the smallest
+  ///      float number instead of `-inf`, a one time warning will pop up as
+  ///      well.
+  static Tensor generate_square_subsequent_mask(int64_t sz);
+
+ protected:
+  FORWARD_HAS_DEFAULT_ARGS(
+      {2, AnyValue(Tensor())},
+      {3, AnyValue(Tensor())},
+      {4, AnyValue(Tensor())},
+      {5, AnyValue(Tensor())},
+      {6, AnyValue(Tensor())},
+      {7, AnyValue(Tensor())})
+
+ public:
+  /// options with which this `Transformer` was constructed
+  TransformerOptions options;
+
+  /// encoder module
+  AnyModule encoder;
+
+  /// decoder module
+  AnyModule decoder;
+};
+
+/// A `ModuleHolder` subclass for `TransformerImpl`.
+/// See the documentation for `TransformerImpl` class to learn what
+/// methods it provides, and examples of how to use `Transformer` with
+/// `torch::nn::TransformerOptions`.
+/// See the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(Transformer);
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/transformercoder.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/transformercoder.h
new file mode 100644
index 0000000000000000000000000000000000000000..5ca4ddea64b8d9e69083ab1fb6c167a9d1df1011
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/transformercoder.h
@@ -0,0 +1,154 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include 
+
+namespace torch {
+namespace nn {
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TransformerEncoder
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// TransformerEncoder module.
+/// See
+/// https://pytorch.org/docs/main/generated/torch.nn.TransformerEncoder.html
+/// to learn abouut the exact behavior of this encoder layer module.
+///
+/// See the documentation for `torch::nn::TransformerEncoder` class to learn
+/// what constructor arguments are supported for this encoder module.
+///
+/// Example:
+/// ```
+/// TransformerEncoderLayer encoderLayer(TransformerEncoderLayerOptions(512,
+/// 8).dropout(0.1)); TransformerEncoder
+/// encoder(TransformerEncoderOptions(encoderLayer,
+/// 6).norm(LayerNorm(LayerNormOptions({2}))));
+/// ```
+class TORCH_API TransformerEncoderImpl
+    : public Cloneable {
+ public:
+  TransformerEncoderImpl(
+      TransformerEncoderLayer encoder_layer,
+      int64_t num_layers)
+      : TransformerEncoderImpl(
+            TransformerEncoderOptions(encoder_layer, num_layers)) {}
+  explicit TransformerEncoderImpl(TransformerEncoderOptions options_);
+
+  Tensor forward(
+      const Tensor& src,
+      const Tensor& src_mask = {},
+      const Tensor& src_key_padding_mask = {});
+
+  void reset() override;
+
+  void reset_parameters();
+
+ protected:
+  FORWARD_HAS_DEFAULT_ARGS({1, AnyValue(Tensor())}, {2, AnyValue(Tensor())})
+
+ public:
+  /// options with which this `TransformerEncoder` was constructed
+  TransformerEncoderOptions options;
+
+  /// module list that contains all the encoder layers
+  ModuleList layers = nullptr;
+
+  /// optional normalization module
+  AnyModule norm;
+};
+
+/// A `ModuleHolder` subclass for `TransformerEncoderImpl`.
+/// See the documentation for `TransformerEncoderImpl` class to learn what
+/// methods it provides, and examples of how to use `TransformerEncoder` with
+/// `torch::nn::TransformerEncoderOptions`.
+/// See the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(TransformerEncoder);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TransformerDecoder
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// TransformerDecoder is a stack of N decoder layers.
+/// See
+/// https://pytorch.org/docs/main/generated/torch.nn.TransformerDecoder.html
+/// to learn abouut the exact behavior of this decoder module
+///
+/// See the documentation for `torch::nn::TransformerDecoderOptions` class to
+/// learn what constructor arguments are supported for this decoder module
+///
+/// Example:
+/// ```
+/// TransformerDecoderLayer decoder_layer(TransformerDecoderLayerOptions(512,
+/// 8).dropout(0.1)); TransformerDecoder
+/// transformer_decoder(TransformerDecoderOptions(decoder_layer,
+/// 6).norm(LayerNorm(LayerNormOptions({2})))); const auto memory =
+/// torch::rand({10, 32, 512}); const auto tgt = torch::rand({20, 32, 512});
+/// auto out = transformer_decoder(tgt, memory);
+/// ```
+class TORCH_API TransformerDecoderImpl
+    : public Cloneable {
+ public:
+  TransformerDecoderImpl(
+      TransformerDecoderLayer decoder_layer,
+      int64_t num_layers)
+      : TransformerDecoderImpl(
+            TransformerDecoderOptions(decoder_layer, num_layers)) {}
+  explicit TransformerDecoderImpl(TransformerDecoderOptions options_);
+
+  void reset() override;
+
+  void reset_parameters();
+
+  /// Pass the inputs (and mask) through the decoder layer in turn.
+  /// Args:
+  ///       tgt: the sequence to the decoder layer (required).
+  ///       memory: the sequence from the last layer of the encoder (required).
+  ///       tgt_mask: the mask for the tgt sequence (optional).
+  ///       memory_mask: the mask for the memory sequence (optional).
+  ///       tgt_key_padding_mask: the mask for the tgt keys per batch
+  ///       (optional). memory_key_padding_mask: the mask for the memory keys
+  ///       per batch (optional).
+  Tensor forward(
+      const Tensor& tgt,
+      const Tensor& memory,
+      const Tensor& tgt_mask = {},
+      const Tensor& memory_mask = {},
+      const Tensor& tgt_key_padding_mask = {},
+      const Tensor& memory_key_padding_mask = {});
+
+  /// The options used to configure this module.
+  TransformerDecoderOptions options;
+
+  /// Cloned layers of decoder layers
+  ModuleList layers{nullptr};
+
+  /// optional layer normalization module
+  AnyModule norm;
+
+ protected:
+  FORWARD_HAS_DEFAULT_ARGS(
+      {2, AnyValue(Tensor())},
+      {3, AnyValue(Tensor())},
+      {4, AnyValue(Tensor())},
+      {5, AnyValue(Tensor())})
+};
+
+/// A `ModuleHolder` subclass for `TransformerDecoderImpl`.
+/// See the documentation for `TransformerDecoderImpl` class to learn what
+/// methods it provides, and examples of how to use `TransformerDecoder` with
+/// `torch::nn::TransformerDecoderOptions`.
+/// See the documentation for `ModuleHolder` to learn about PyTorch's
+/// module storage semantics.
+TORCH_MODULE(TransformerDecoder);
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/transformerlayer.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/transformerlayer.h
new file mode 100644
index 0000000000000000000000000000000000000000..b2d8131870161cdd62e2a7531df43c620d0b61b6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/transformerlayer.h
@@ -0,0 +1,195 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include 
+
+namespace torch {
+namespace nn {
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TransformerEncoderLayer
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// TransformerEncoderLayer module.
+/// See
+/// https://pytorch.org/docs/main/generated/torch.nn.TransformerEncoderLayer.html
+/// to learn abouut the exact behavior of this encoder layer model
+///
+/// See the documentation for `torch::nn::TransformerEncoderLayer` class to
+/// learn what constructor arguments are supported for this encoder layer model
+///
+/// Example:
+/// ```
+/// TransformerEncoderLayer encoderLayer(TransformerEncoderLayerOptions(512,
+/// 8).dropout(0.1));
+/// ```
+class TORCH_API TransformerEncoderLayerImpl
+    : public Cloneable {
+ public:
+  TransformerEncoderLayerImpl(int64_t d_model, int64_t nhead)
+      : TransformerEncoderLayerImpl(
+            TransformerEncoderLayerOptions(d_model, nhead)) {}
+  explicit TransformerEncoderLayerImpl(TransformerEncoderLayerOptions options_);
+
+  Tensor forward(
+      const Tensor& src,
+      const Tensor& src_mask = {},
+      const Tensor& src_key_padding_mask = {});
+
+  void reset() override;
+
+  void reset_parameters();
+
+ protected:
+  FORWARD_HAS_DEFAULT_ARGS({1, AnyValue(Tensor())}, {2, AnyValue(Tensor())})
+
+ public:
+  /// options with which this `TransformerEncoderLayer` was constructed
+  TransformerEncoderLayerOptions options;
+
+  /// self attention
+  MultiheadAttention self_attn = nullptr;
+
+  /// feedforward first linear layer
+  Linear linear1 = nullptr;
+
+  /// feedforward dropout layer
+  Dropout dropout = nullptr;
+
+  /// feedforward second linear layer
+  Linear linear2 = nullptr;
+
+  /// pre feedforward, normalization layer
+  LayerNorm norm1 = nullptr;
+  /// post feedfastward, normalization layer
+  LayerNorm norm2 = nullptr;
+
+  /// pre feedfastward, dropout layer
+  Dropout dropout1 = nullptr;
+  /// post feedfastward, dropout layer
+  Dropout dropout2 = nullptr;
+};
+
+/// A `ModuleHolder` subclass for `TransformerEncoderLayerImpl``.
+/// See the documentation for `TransformerEncoderLayerImpl` class to learn what
+/// methods it provides, and examples of how to use `TransformerEncoderLayer`
+/// with `torch::nn::TransformerEncoderLayerOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(TransformerEncoderLayer);
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TransformerDecoderLayer
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// TransformerDecoderLayer is made up of self-attn, multi-head-attn and
+/// feedforward network. This standard decoder layer is based on the paper
+/// "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar,
+/// Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia
+/// Polosukhin. 2017. Attention is all you need. In Advances in Neural
+/// Information Processing Systems, pages 6000-6010. Users may modify or
+/// implement in a different way during application. See
+/// https://pytorch.org/docs/main/nn.html#transformer-layers to learn about
+/// the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::TransformerDecoderLayerOptions` class
+/// to learn what constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// TransformerDecoderLayer model(TransformerDecoderLayerOptions(512,
+/// 8).dropout(0.2));
+/// ```
+class TORCH_API TransformerDecoderLayerImpl
+    : public Cloneable {
+ public:
+  TransformerDecoderLayerImpl(int64_t d_model, int64_t nhead)
+      : TransformerDecoderLayerImpl(
+            TransformerDecoderLayerOptions(d_model, nhead)) {}
+  explicit TransformerDecoderLayerImpl(TransformerDecoderLayerOptions options_);
+
+  void reset() override;
+
+  void reset_parameters();
+
+  /// Pass the inputs (and mask) through the decoder layer.
+  /// Args:
+  ///       tgt: the sequence to the decoder layer (required).
+  ///       memory: the sequence from the last layer of the encoder (required).
+  ///       tgt_mask: the mask for the tgt sequence (optional).
+  ///       memory_mask: the mask for the memory sequence (optional).
+  ///       tgt_key_padding_mask: the mask for the tgt keys per batch
+  ///       (optional). memory_key_padding_mask: the mask for the memory keys
+  ///       per batch (optional).
+  Tensor forward(
+      Tensor tgt,
+      const Tensor& memory,
+      const Tensor& tgt_mask = {},
+      const Tensor& memory_mask = {},
+      const Tensor& tgt_key_padding_mask = {},
+      const Tensor& memory_key_padding_mask = {});
+
+  /// The options used to configure this module.
+  TransformerDecoderLayerOptions options;
+
+  /// self attention
+  MultiheadAttention self_attn{nullptr};
+
+  /// Dropout, post self attention
+  Dropout dropout1{nullptr};
+
+  /// Normalization, post self attention
+  LayerNorm norm1{nullptr};
+
+  /// Multi-headed attention
+  MultiheadAttention multihead_attn{nullptr};
+
+  /// Dropout, post multi-headed attention
+  Dropout dropout2{nullptr};
+
+  /// Normalization, post multi-headed attention
+  LayerNorm norm2{nullptr};
+
+  /// Feed forward first linear layer
+  Linear linear1{nullptr};
+
+  /// Feed forward dropout layer
+  Dropout dropout{nullptr};
+
+  /// Feed forward second linear layer
+  Linear linear2{nullptr};
+
+  /// Dropout, post feed forward
+  Dropout dropout3{nullptr};
+
+  /// Normalization, post feed forward
+  LayerNorm norm3{nullptr};
+
+ protected:
+  FORWARD_HAS_DEFAULT_ARGS(
+      {2, AnyValue(Tensor())},
+      {3, AnyValue(Tensor())},
+      {4, AnyValue(Tensor())},
+      {5, AnyValue(Tensor())})
+
+  /// Apply activation based on configuration
+  Tensor activation(const Tensor& input);
+};
+
+/// A `ModuleHolder` subclass for `TransformerDecoderLayerImpl`.
+/// See the documentation for `TransformerDecoderLayerImpl` class to learn what
+/// methods it provides, and examples of how to use `TransformerDecoderLayer`
+/// with `torch::nn::TransformerDecoderLayerOptions`. See the documentation for
+/// `ModuleHolder` to learn about PyTorch's module storage semantics.
+TORCH_MODULE(TransformerDecoderLayer);
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/upsampling.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/upsampling.h
new file mode 100644
index 0000000000000000000000000000000000000000..8520bf632f83e6f42228de2152efd90e458845bc
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/upsampling.h
@@ -0,0 +1,55 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Upsample ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// Upsamples a given multi-channel 1D (temporal), 2D (spatial) or 3D
+/// (volumetric) data.
+/// See https://pytorch.org/docs/main/nn.html#torch.nn.Upsample to learn
+/// about the exact behavior of this module.
+///
+/// See the documentation for `torch::nn::UpsampleOptions` class to learn what
+/// constructor arguments are supported for this module.
+///
+/// Example:
+/// ```
+/// Upsample
+/// model(UpsampleOptions().scale_factor({3}).mode(torch::kLinear).align_corners(false));
+/// ```
+class TORCH_API UpsampleImpl : public Cloneable {
+ public:
+  explicit UpsampleImpl(const UpsampleOptions& options_ = {});
+
+  void reset() override;
+
+  /// Pretty prints the `Upsample` module into the given `stream`.
+  void pretty_print(std::ostream& stream) const override;
+
+  Tensor forward(const Tensor& input);
+
+  /// The options with which this `Module` was constructed.
+  UpsampleOptions options;
+};
+
+/// A `ModuleHolder` subclass for `UpsampleImpl`.
+/// See the documentation for `UpsampleImpl` class to learn what methods it
+/// provides, and examples of how to use `Upsample` with
+/// `torch::nn::UpsampleOptions`. See the documentation for `ModuleHolder` to
+/// learn about PyTorch's module storage semantics.
+TORCH_MODULE(Upsample);
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/utils.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/utils.h
new file mode 100644
index 0000000000000000000000000000000000000000..6eaa0c1fb2c73ecbdeabfa48ba9d9adcb5a3acd3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules/utils.h
@@ -0,0 +1,55 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+
+namespace torch {
+namespace nn {
+namespace modules {
+namespace utils {
+
+// Reverse the order of `t` and repeat each element for `n` times.
+// This can be used to translate padding arg used by Conv and Pooling modules
+// to the ones used by `F::pad`.
+//
+// This mirrors `_reverse_repeat_tuple` in `torch/nn/modules/utils.py`.
+inline std::vector _reverse_repeat_vector(
+    at::ArrayRef t,
+    int64_t n) {
+  TORCH_INTERNAL_ASSERT(n >= 0);
+  std::vector ret;
+  ret.reserve(t.size() * n);
+  for (auto rit = t.rbegin(); rit != t.rend(); ++rit) {
+    for (const auto i : c10::irange(n)) {
+      (void)i; // Suppress unused variable
+      ret.emplace_back(*rit);
+    }
+  }
+  return ret;
+}
+
+inline std::vector _list_with_default(
+    torch::ArrayRef> out_size,
+    torch::IntArrayRef defaults) {
+  TORCH_CHECK(
+      defaults.size() > out_size.size(),
+      "Input dimension should be at least ",
+      out_size.size() + 1);
+  std::vector ret;
+  torch::IntArrayRef defaults_slice =
+      defaults.slice(defaults.size() - out_size.size(), out_size.size());
+  for (const auto i : c10::irange(out_size.size())) {
+    auto v = out_size.at(i);
+    auto d = defaults_slice.at(i);
+    ret.emplace_back(v.has_value() ? v.value() : d);
+  }
+  return ret;
+}
+
+} // namespace utils
+} // namespace modules
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options.h
new file mode 100644
index 0000000000000000000000000000000000000000..4a5224a478e1b650e393dcb3f95adc13ab36d65f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options.h
@@ -0,0 +1,18 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/activation.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/activation.h
new file mode 100644
index 0000000000000000000000000000000000000000..ac6cbc4ea4deab53f03d2d6c6f0e14b8e1c5e714
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/activation.h
@@ -0,0 +1,714 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Options for the `ELU` module.
+///
+/// Example:
+/// ```
+/// ELU model(ELUOptions().alpha(42.42).inplace(true));
+/// ```
+struct TORCH_API ELUOptions {
+  /// The `alpha` value for the ELU formulation. Default: 1.0
+  TORCH_ARG(double, alpha) = 1.0;
+
+  /// can optionally do the operation in-place. Default: False
+  TORCH_ARG(bool, inplace) = false;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::elu`.
+///
+/// See the documentation for `torch::nn::ELUOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::elu(x, F::ELUFuncOptions().alpha(0.42).inplace(true));
+/// ```
+using ELUFuncOptions = ELUOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `SELU` module.
+///
+/// Example:
+/// ```
+/// SELU model(SELUOptions().inplace(true));
+/// ```
+struct TORCH_API SELUOptions {
+  /* implicit */ SELUOptions(bool inplace = false);
+
+  /// can optionally do the operation in-place. Default: False
+  TORCH_ARG(bool, inplace);
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::selu`.
+///
+/// See the documentation for `torch::nn::SELUOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::selu(input, F::SELUFuncOptions(false));
+/// ```
+using SELUFuncOptions = SELUOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `GLU` module.
+///
+/// Example:
+/// ```
+/// GLU model(GLUOptions(1));
+/// ```
+struct TORCH_API GLUOptions {
+  /* implicit */ GLUOptions(int64_t dim = -1);
+
+  /// the dimension on which to split the input. Default: -1
+  TORCH_ARG(int64_t, dim);
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::glu`.
+///
+/// See the documentation for `torch::nn::GLUOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::glu(input, GLUFuncOptions(1));
+/// ```
+using GLUFuncOptions = GLUOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `GELU` module.
+///
+/// Example:
+/// ```
+/// GELU model(GELUOptions().approximate("none"));
+/// ```
+struct TORCH_API GELUOptions {
+  /// Specifies the approximation to apply to the output.
+  TORCH_ARG(std::string, approximate) = "none";
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::gelu`.
+///
+/// See the documentation for `torch::nn::GELUOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::gelu(input, F::GELUFuncOptions().approximate("none"));
+/// ```
+using GELUFuncOptions = GELUOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `Hardshrink` module.
+///
+/// Example:
+/// ```
+/// Hardshrink model(HardshrinkOptions().lambda(42.42));
+/// ```
+struct TORCH_API HardshrinkOptions {
+  /* implicit */ HardshrinkOptions(double lambda = 0.5);
+
+  /// the `lambda` value for the Hardshrink formulation. Default: 0.5
+  TORCH_ARG(double, lambda);
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::hardshrink`.
+///
+/// See the documentation for `torch::nn::HardshrinkOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::hardshrink(x, F::HardshrinkFuncOptions().lambda(0.42));
+/// ```
+using HardshrinkFuncOptions = HardshrinkOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `Hardtanh` module.
+///
+/// Example:
+/// ```
+/// Hardtanh
+/// model(HardtanhOptions().min_val(-42.42).max_val(0.42).inplace(true));
+/// ```
+struct TORCH_API HardtanhOptions {
+  /// minimum value of the linear region range. Default: -1
+  TORCH_ARG(double, min_val) = -1.0;
+
+  /// maximum value of the linear region range. Default: 1
+  TORCH_ARG(double, max_val) = 1.0;
+
+  /// can optionally do the operation in-place. Default: False
+  TORCH_ARG(bool, inplace) = false;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::hardtanh`.
+///
+/// See the documentation for `torch::nn::HardtanhOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::hardtanh(x,
+/// F::HardtanhFuncOptions().min_val(-1.0).max_val(1.0).inplace(true));
+/// ```
+using HardtanhFuncOptions = HardtanhOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `LeakyReLU` module.
+///
+/// Example:
+/// ```
+/// LeakyReLU model(LeakyReLUOptions().negative_slope(0.42).inplace(true));
+/// ```
+struct TORCH_API LeakyReLUOptions {
+  /// Controls the angle of the negative slope. Default: 1e-2
+  TORCH_ARG(double, negative_slope) = 1e-2;
+
+  /// can optionally do the operation in-place. Default: False
+  TORCH_ARG(bool, inplace) = false;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::leaky_relu`.
+///
+/// See the documentation for `torch::nn::LeakyReLUOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::leaky_relu(x,
+/// F::LeakyReLUFuncOptions().negative_slope(0.42).inplace(true));
+/// ```
+using LeakyReLUFuncOptions = LeakyReLUOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `Softmax` module.
+///
+/// Example:
+/// ```
+/// Softmax model(SoftmaxOptions(1));
+/// ```
+struct TORCH_API SoftmaxOptions {
+  SoftmaxOptions(int64_t dim);
+
+  /// Dimension along which Softmax will be computed.
+  TORCH_ARG(int64_t, dim);
+};
+
+// ============================================================================
+
+namespace functional {
+
+/// Options for `torch::nn::functional::softmax`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::softmax(input, F::SoftmaxFuncOptions(1));
+/// ```
+struct TORCH_API SoftmaxFuncOptions {
+  SoftmaxFuncOptions(int64_t dim);
+
+  /// Dimension along which Softmax will be computed.
+  TORCH_ARG(int64_t, dim);
+
+  /// the desired data type of returned tensor.
+  /// If specified, the input tensor is casted to `dtype` before the operation
+  /// is performed. This is useful for preventing data type overflows. Default:
+  /// None.
+  TORCH_ARG(std::optional, dtype) = std::nullopt;
+};
+
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `Softmin` module.
+///
+/// Example:
+/// ```
+/// Softmin model(SoftminOptions(1));
+/// ```
+struct TORCH_API SoftminOptions {
+  SoftminOptions(int64_t dim);
+
+  /// Dimension along which Softmin will be computed.
+  TORCH_ARG(int64_t, dim);
+};
+
+// ============================================================================
+
+namespace functional {
+
+/// Options for `torch::nn::functional::softmin`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::softmin(input, F::SoftminFuncOptions(1));
+/// ```
+struct TORCH_API SoftminFuncOptions {
+  SoftminFuncOptions(int64_t dim);
+
+  /// Dimension along which Softmin will be computed.
+  TORCH_ARG(int64_t, dim);
+
+  /// the desired data type of returned tensor.
+  /// If specified, the input tensor is casted to `dtype` before the operation
+  /// is performed. This is useful for preventing data type overflows. Default:
+  /// None.
+  TORCH_ARG(std::optional, dtype) = std::nullopt;
+};
+
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `LogSoftmax` module.
+///
+/// Example:
+/// ```
+/// LogSoftmax model(LogSoftmaxOptions(1));
+/// ```
+struct TORCH_API LogSoftmaxOptions {
+  LogSoftmaxOptions(int64_t dim);
+
+  /// Dimension along which LogSoftmax will be computed.
+  TORCH_ARG(int64_t, dim);
+};
+
+// ============================================================================
+
+namespace functional {
+
+/// Options for `torch::nn::functional::log_softmax`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::log_softmax(input, LogSoftmaxFuncOptions(1));
+/// ```
+struct TORCH_API LogSoftmaxFuncOptions {
+  LogSoftmaxFuncOptions(int64_t dim);
+
+  /// Dimension along which LogSoftmax will be computed.
+  TORCH_ARG(int64_t, dim);
+
+  /// the desired data type of returned tensor.
+  /// If specified, the input tensor is casted to `dtype` before the operation
+  /// is performed. This is useful for preventing data type overflows. Default:
+  /// None.
+  TORCH_ARG(std::optional, dtype) = std::nullopt;
+};
+
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `PReLU` module.
+///
+/// Example:
+/// ```
+/// PReLU model(PReLUOptions().num_parameters(42));
+/// ```
+struct TORCH_API PReLUOptions {
+  /// number of `a` to learn. Although it takes an int as input, there is only
+  /// two values are legitimate: 1, or the number of channels at input. Default:
+  /// 1
+  TORCH_ARG(int64_t, num_parameters) = 1;
+
+  /// the initial value of `a`. Default: 0.25
+  TORCH_ARG(double, init) = 0.25;
+};
+
+// ============================================================================
+
+/// Options for the `ReLU` module.
+///
+/// Example:
+/// ```
+/// ReLU model(ReLUOptions().inplace(true));
+/// ```
+struct TORCH_API ReLUOptions {
+  /* implicit */ ReLUOptions(bool inplace = false);
+
+  /// can optionally do the operation in-place. Default: False
+  TORCH_ARG(bool, inplace);
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::relu`.
+///
+/// See the documentation for `torch::nn::ReLUOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::relu(x, F::ReLUFuncOptions().inplace(true));
+/// ```
+using ReLUFuncOptions = ReLUOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `ReLU6` module.
+///
+/// Example:
+/// ```
+/// ReLU6 model(ReLU6Options().inplace(true));
+/// ```
+struct TORCH_API ReLU6Options {
+  /* implicit */ ReLU6Options(bool inplace = false);
+
+  /// can optionally do the operation in-place. Default: False
+  TORCH_ARG(bool, inplace);
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::relu6`.
+///
+/// See the documentation for `torch::nn::ReLU6Options` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::relu6(x, F::ReLU6FuncOptions().inplace(true));
+/// ```
+using ReLU6FuncOptions = ReLU6Options;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `RReLU` module.
+///
+/// Example:
+/// ```
+/// RReLU model(RReLUOptions().lower(0.24).upper(0.42).inplace(true));
+/// ```
+struct TORCH_API RReLUOptions {
+  /// lower bound of the uniform distribution. Default: 1/8
+  TORCH_ARG(double, lower) = 1.0 / 8.0;
+
+  /// upper bound of the uniform distribution. Default: 1/3
+  TORCH_ARG(double, upper) = 1.0 / 3.0;
+
+  /// can optionally do the operation in-place. Default: False
+  TORCH_ARG(bool, inplace) = false;
+};
+
+// ============================================================================
+
+namespace functional {
+
+/// Options for `torch::nn::functional::rrelu`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::rrelu(x, F::RReLUFuncOptions().lower(0.1).upper(0.4).inplace(true));
+/// ```
+struct TORCH_API RReLUFuncOptions {
+  /// lower bound of the uniform distribution. Default: 1/8
+  TORCH_ARG(double, lower) = 1.0 / 8.0;
+
+  /// upper bound of the uniform distribution. Default: 1/3
+  TORCH_ARG(double, upper) = 1.0 / 3.0;
+
+  TORCH_ARG(bool, training) = false;
+
+  /// can optionally do the operation in-place. Default: False
+  TORCH_ARG(bool, inplace) = false;
+};
+
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `CELU` module.
+///
+/// Example:
+/// ```
+/// CELU model(CELUOptions().alpha(42.42).inplace(true));
+/// ```
+struct TORCH_API CELUOptions {
+  /// The `alpha` value for the CELU formulation. Default: 1.0
+  TORCH_ARG(double, alpha) = 1.0;
+
+  /// can optionally do the operation in-place. Default: False
+  TORCH_ARG(bool, inplace) = false;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::celu`.
+///
+/// See the documentation for `torch::nn::CELUOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::celu(x, F::CELUFuncOptions().alpha(0.42).inplace(true));
+/// ```
+using CELUFuncOptions = CELUOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `Softplus` module.
+///
+/// Example:
+/// ```
+/// Softplus model(SoftplusOptions().beta(0.24).threshold(42.42));
+/// ```
+struct TORCH_API SoftplusOptions {
+  /// the `beta` value for the Softplus formulation. Default: 1
+  TORCH_ARG(double, beta) = 1.0;
+
+  /// values above this revert to a linear function. Default: 20
+  TORCH_ARG(double, threshold) = 20.0;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::softplus`.
+///
+/// See the documentation for `torch::nn::SoftplusOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::softplus(x, F::SoftplusFuncOptions().beta(0.5).threshold(3.0));
+/// ```
+using SoftplusFuncOptions = SoftplusOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `Softshrink` module.
+///
+/// Example:
+/// ```
+/// Softshrink model(SoftshrinkOptions(42.42));
+/// ```
+struct TORCH_API SoftshrinkOptions {
+  /* implicit */ SoftshrinkOptions(double lambda = 0.5);
+
+  /// the `lambda` value for the Softshrink formulation. Default: 0.5
+  TORCH_ARG(double, lambda);
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::softshrink`.
+///
+/// See the documentation for `torch::nn::SoftshrinkOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::softshrink(x, F::SoftshrinkFuncOptions(0.42));
+/// ```
+using SoftshrinkFuncOptions = SoftshrinkOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `Threshold` module.
+///
+/// Example:
+/// ```
+/// Threshold model(ThresholdOptions(42.42, 24.24).inplace(true));
+/// ```
+struct TORCH_API ThresholdOptions {
+  ThresholdOptions(double threshold, double value)
+      : threshold_(threshold), value_(value) {}
+
+  /// The value to threshold at
+  TORCH_ARG(double, threshold);
+
+  /// The value to replace with
+  TORCH_ARG(double, value);
+
+  /// can optionally do the operation in-place. Default: False
+  TORCH_ARG(bool, inplace) = false;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::threshold`.
+///
+/// See the documentation for `torch::nn::ThresholdOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::threshold(x, F::ThresholdFuncOptions(0.5, 0.5).inplace(true));
+/// ```
+using ThresholdFuncOptions = ThresholdOptions;
+} // namespace functional
+
+// ============================================================================
+
+namespace functional {
+
+/// Options for `torch::nn::functional::gumbel_softmax`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::gumbel_softmax(logits, F::GumbelSoftmaxFuncOptions().hard(true).dim(-1));
+/// ```
+struct TORCH_API GumbelSoftmaxFuncOptions {
+  /// non-negative scalar temperature
+  TORCH_ARG(double, tau) = 1.0;
+
+  /// returned samples will be discretized as one-hot vectors,
+  /// but will be differentiated as if it is the soft sample in autograd.
+  /// Default: False
+  TORCH_ARG(bool, hard) = false;
+
+  /// dimension along which softmax will be computed. Default: -1
+  TORCH_ARG(int, dim) = -1;
+};
+
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `MultiheadAttention` module.
+///
+/// Example:
+/// ```
+/// MultiheadAttention model(MultiheadAttentionOptions(20, 10).bias(false));
+/// ```
+struct TORCH_API MultiheadAttentionOptions {
+  MultiheadAttentionOptions(int64_t embed_dim, int64_t num_heads);
+
+  /// total dimension of the model.
+  TORCH_ARG(int64_t, embed_dim);
+
+  /// parallel attention heads.
+  TORCH_ARG(int64_t, num_heads);
+
+  /// a Dropout layer on attn_output_weights. Default: 0.0.
+  TORCH_ARG(double, dropout) = 0.0;
+
+  /// add bias as module parameter. Default: true.
+  TORCH_ARG(bool, bias) = true;
+
+  /// add bias to the key and value sequences at dim=0.
+  TORCH_ARG(bool, add_bias_kv) = false;
+
+  /// add a new batch of zeros to the key and value sequences at dim=1.
+  TORCH_ARG(bool, add_zero_attn) = false;
+
+  /// total number of features in key. Default: std::nullopt.
+  TORCH_ARG(int64_t, kdim);
+
+  /// total number of features in key. Default: std::nullopt.
+  TORCH_ARG(int64_t, vdim);
+};
+
+// ============================================================================
+
+namespace functional {
+
+/// Options for `torch::nn::functional::multi_head_attention_forward`
+struct TORCH_API MultiheadAttentionForwardFuncOptions {
+  MultiheadAttentionForwardFuncOptions(
+      int64_t embed_dim_to_check,
+      int64_t num_heads,
+      Tensor in_proj_weight,
+      Tensor in_proj_bias,
+      Tensor bias_k,
+      Tensor bias_v,
+      bool add_zero_attn,
+      double dropout_p,
+      Tensor out_proj_weight,
+      Tensor out_proj_bias);
+
+  TORCH_ARG(int64_t, embed_dim_to_check);
+
+  TORCH_ARG(int64_t, num_heads);
+
+  TORCH_ARG(Tensor, in_proj_weight);
+
+  TORCH_ARG(Tensor, in_proj_bias);
+
+  TORCH_ARG(Tensor, bias_k);
+
+  TORCH_ARG(Tensor, bias_v);
+
+  TORCH_ARG(bool, add_zero_attn);
+
+  TORCH_ARG(double, dropout_p);
+
+  TORCH_ARG(Tensor, out_proj_weight);
+
+  TORCH_ARG(Tensor, out_proj_bias);
+
+  TORCH_ARG(bool, training) = true;
+
+  TORCH_ARG(Tensor, key_padding_mask) = {};
+
+  TORCH_ARG(bool, need_weights) = true;
+
+  TORCH_ARG(Tensor, attn_mask) = {};
+
+  TORCH_ARG(bool, use_separate_proj_weight) = false;
+
+  TORCH_ARG(Tensor, q_proj_weight) = {};
+
+  TORCH_ARG(Tensor, k_proj_weight) = {};
+
+  TORCH_ARG(Tensor, v_proj_weight) = {};
+
+  TORCH_ARG(Tensor, static_k) = {};
+
+  TORCH_ARG(Tensor, static_v) = {};
+
+  TORCH_ARG(bool, average_attn_weights) = true;
+};
+
+} // namespace functional
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/adaptive.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/adaptive.h
new file mode 100644
index 0000000000000000000000000000000000000000..d4754747a1d296b878231851af9d1b4caee94ab4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/adaptive.h
@@ -0,0 +1,41 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Options for the `AdaptiveLogSoftmaxWithLoss` module.
+///
+/// Example:
+/// ```
+/// AdaptiveLogSoftmaxWithLoss model(AdaptiveLogSoftmaxWithLossOptions(8, 10,
+/// {4, 8}).div_value(2.).head_bias(true));
+/// ```
+struct TORCH_API AdaptiveLogSoftmaxWithLossOptions {
+  /* implicit */ AdaptiveLogSoftmaxWithLossOptions(
+      int64_t in_features,
+      int64_t n_classes,
+      std::vector cutoffs);
+
+  /// Number of features in the input tensor
+  TORCH_ARG(int64_t, in_features);
+
+  /// Number of classes in the dataset
+  TORCH_ARG(int64_t, n_classes);
+
+  /// Cutoffs used to assign targets to their buckets
+  TORCH_ARG(std::vector, cutoffs);
+
+  /// value used as an exponent to compute sizes of the clusters. Default: 4.0
+  TORCH_ARG(double, div_value) = 4.;
+
+  /// If ``true``, adds a bias term to the 'head' of
+  /// the adaptive softmax. Default: false
+  TORCH_ARG(bool, head_bias) = false;
+};
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/batchnorm.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/batchnorm.h
new file mode 100644
index 0000000000000000000000000000000000000000..943673e2aae741b35bb5fe7c6ce18c6dc66ec57e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/batchnorm.h
@@ -0,0 +1,95 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Options for the `BatchNorm` module.
+struct TORCH_API BatchNormOptions {
+  /* implicit */ BatchNormOptions(int64_t num_features);
+
+  /// The number of features of the input tensor.
+  /// Changing this parameter after construction __has no effect__.
+  TORCH_ARG(int64_t, num_features);
+
+  /// The epsilon value added for numerical stability.
+  /// Changing this parameter after construction __is effective__.
+  TORCH_ARG(double, eps) = 1e-5;
+
+  /// A momentum multiplier for the mean and variance.
+  /// Changing this parameter after construction __is effective__.
+  TORCH_ARG(std::optional, momentum) = 0.1;
+
+  /// Whether to learn a scale and bias that are applied in an affine
+  /// transformation on the input.
+  /// Changing this parameter after construction __has no effect__.
+  TORCH_ARG(bool, affine) = true;
+
+  /// Whether to store and update batch statistics (mean and variance) in the
+  /// module.
+  /// Changing this parameter after construction __has no effect__.
+  TORCH_ARG(bool, track_running_stats) = true;
+};
+
+/// Options for the `BatchNorm1d` module.
+///
+/// Example:
+/// ```
+/// BatchNorm1d
+/// model(BatchNorm1dOptions(4).eps(0.5).momentum(0.1).affine(false).track_running_stats(true));
+/// ```
+using BatchNorm1dOptions = BatchNormOptions;
+
+/// Options for the `BatchNorm2d` module.
+///
+/// Example:
+/// ```
+/// BatchNorm2d
+/// model(BatchNorm2dOptions(4).eps(0.5).momentum(0.1).affine(false).track_running_stats(true));
+/// ```
+using BatchNorm2dOptions = BatchNormOptions;
+
+/// Options for the `BatchNorm3d` module.
+///
+/// Example:
+/// ```
+/// BatchNorm3d
+/// model(BatchNorm3dOptions(4).eps(0.5).momentum(0.1).affine(false).track_running_stats(true));
+/// ```
+using BatchNorm3dOptions = BatchNormOptions;
+
+// ============================================================================
+
+namespace functional {
+
+/// Options for `torch::nn::functional::batch_norm`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::batch_norm(input, mean, variance,
+/// F::BatchNormFuncOptions().weight(weight).bias(bias).momentum(0.1).eps(1e-05).training(false));
+/// ```
+struct TORCH_API BatchNormFuncOptions {
+  TORCH_ARG(Tensor, weight) = Tensor();
+
+  TORCH_ARG(Tensor, bias) = Tensor();
+
+  TORCH_ARG(bool, training) = false;
+
+  /// A momentum multiplier for the mean and variance.
+  /// Changing this parameter after construction __is effective__.
+  TORCH_ARG(std::optional, momentum) = 0.1;
+
+  /// The epsilon value added for numerical stability.
+  /// Changing this parameter after construction __is effective__.
+  TORCH_ARG(double, eps) = 1e-5;
+};
+
+} // namespace functional
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/conv.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/conv.h
new file mode 100644
index 0000000000000000000000000000000000000000..0b5b5b1b3f955abf2ec36a806fb1344611c4f060
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/conv.h
@@ -0,0 +1,415 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+namespace detail {
+
+typedef std::variant<
+    enumtype::kZeros,
+    enumtype::kReflect,
+    enumtype::kReplicate,
+    enumtype::kCircular>
+    conv_padding_mode_t;
+
+template 
+using conv_padding_t =
+    std::variant, enumtype::kValid, enumtype::kSame>;
+
+/// Options for a `D`-dimensional convolution or convolution transpose module.
+template 
+struct ConvNdOptions {
+  using padding_t = conv_padding_t;
+  ConvNdOptions(
+      int64_t in_channels,
+      int64_t out_channels,
+      ExpandingArray kernel_size)
+      : in_channels_(in_channels),
+        out_channels_(out_channels),
+        kernel_size_(std::move(kernel_size)) {}
+
+  /// The number of channels the input volumes will have.
+  /// Changing this parameter after construction __has no effect__.
+  TORCH_ARG(int64_t, in_channels);
+
+  /// The number of output channels the convolution should produce.
+  /// Changing this parameter after construction __has no effect__.
+  TORCH_ARG(int64_t, out_channels);
+
+  /// The kernel size to use.
+  /// For a `D`-dim convolution, must be a single number or a list of `D`
+  /// numbers.
+  /// This parameter __can__ be changed after construction.
+  TORCH_ARG(ExpandingArray, kernel_size);
+
+  /// The stride of the convolution.
+  /// For a `D`-dim convolution, must be a single number or a list of `D`
+  /// numbers.
+  /// This parameter __can__ be changed after construction.
+  TORCH_ARG(ExpandingArray, stride) = 1;
+
+  /// The padding to add to the input volumes.
+  /// For a `D`-dim convolution, must be a single number or a list of `D`
+  /// numbers.
+  /// This parameter __can__ be changed after construction.
+  TORCH_ARG(padding_t, padding) = 0;
+
+ public:
+  decltype(auto) padding(std::initializer_list il) {
+    return padding(IntArrayRef{il});
+  }
+
+  /// The kernel dilation.
+  /// For a `D`-dim convolution, must be a single number or a list of `D`
+  /// numbers.
+  /// This parameter __can__ be changed after construction.
+  TORCH_ARG(ExpandingArray, dilation) = 1;
+
+  /// If true, convolutions will be transpose convolutions (a.k.a.
+  /// deconvolutions).
+  /// Changing this parameter after construction __has no effect__.
+  TORCH_ARG(bool, transposed) = false;
+
+  /// For transpose convolutions, the padding to add to output volumes.
+  /// For a `D`-dim convolution, must be a single number or a list of `D`
+  /// numbers.
+  /// This parameter __can__ be changed after construction.
+  TORCH_ARG(ExpandingArray, output_padding) = 0;
+
+  /// The number of convolution groups.
+  /// This parameter __can__ be changed after construction.
+  TORCH_ARG(int64_t, groups) = 1;
+
+  /// Whether to add a bias after individual applications of the kernel.
+  /// Changing this parameter after construction __has no effect__.
+  TORCH_ARG(bool, bias) = true;
+
+  /// Accepted values `torch::kZeros`, `torch::kReflect`, `torch::kReplicate` or
+  /// `torch::kCircular`. Default: `torch::kZeros`
+  TORCH_ARG(conv_padding_mode_t, padding_mode) = torch::kZeros;
+};
+
+} // namespace detail
+
+// ============================================================================
+
+/// Options for a `D`-dimensional convolution module.
+template 
+struct ConvOptions {
+  using padding_mode_t = detail::conv_padding_mode_t;
+  using padding_t = detail::conv_padding_t;
+
+  ConvOptions(
+      int64_t in_channels,
+      int64_t out_channels,
+      ExpandingArray kernel_size)
+      : in_channels_(in_channels),
+        out_channels_(out_channels),
+        kernel_size_(std::move(kernel_size)) {}
+
+  /// The number of channels the input volumes will have.
+  /// Changing this parameter after construction __has no effect__.
+  TORCH_ARG(int64_t, in_channels);
+
+  /// The number of output channels the convolution should produce.
+  /// Changing this parameter after construction __has no effect__.
+  TORCH_ARG(int64_t, out_channels);
+
+  /// The kernel size to use.
+  /// For a `D`-dim convolution, must be a single number or a list of `D`
+  /// numbers.
+  /// This parameter __can__ be changed after construction.
+  TORCH_ARG(ExpandingArray, kernel_size);
+
+  /// The stride of the convolution.
+  /// For a `D`-dim convolution, must be a single number or a list of `D`
+  /// numbers.
+  /// This parameter __can__ be changed after construction.
+  TORCH_ARG(ExpandingArray, stride) = 1;
+
+  /// The padding to add to the input volumes.
+  /// For a `D`-dim convolution, must be a single number or a list of `D`
+  /// numbers.
+  /// This parameter __can__ be changed after construction.
+  TORCH_ARG(padding_t, padding) = 0;
+
+ public:
+  decltype(auto) padding(std::initializer_list il) {
+    return padding(IntArrayRef{il});
+  }
+
+  /// The kernel dilation.
+  /// For a `D`-dim convolution, must be a single number or a list of `D`
+  /// numbers.
+  /// This parameter __can__ be changed after construction.
+  TORCH_ARG(ExpandingArray, dilation) = 1;
+
+  /// The number of convolution groups.
+  /// This parameter __can__ be changed after construction.
+  TORCH_ARG(int64_t, groups) = 1;
+
+  /// Whether to add a bias after individual applications of the kernel.
+  /// Changing this parameter after construction __has no effect__.
+  TORCH_ARG(bool, bias) = true;
+
+  /// Accepted values `torch::kZeros`, `torch::kReflect`, `torch::kReplicate` or
+  /// `torch::kCircular`. Default: `torch::kZeros`
+  TORCH_ARG(padding_mode_t, padding_mode) = torch::kZeros;
+};
+
+/// `ConvOptions` specialized for the `Conv1d` module.
+///
+/// Example:
+/// ```
+/// Conv1d model(Conv1dOptions(3, 2, 3).stride(1).bias(false));
+/// ```
+using Conv1dOptions = ConvOptions<1>;
+
+/// `ConvOptions` specialized for the `Conv2d` module.
+///
+/// Example:
+/// ```
+/// Conv2d model(Conv2dOptions(3, 2, 3).stride(1).bias(false));
+/// ```
+using Conv2dOptions = ConvOptions<2>;
+
+/// `ConvOptions` specialized for the `Conv3d` module.
+///
+/// Example:
+/// ```
+/// Conv3d model(Conv3dOptions(3, 2, 3).stride(1).bias(false));
+/// ```
+using Conv3dOptions = ConvOptions<3>;
+
+// ============================================================================
+
+namespace functional {
+
+/// Options for a `D`-dimensional convolution functional.
+template 
+struct ConvFuncOptions {
+  using padding_t = torch::nn::detail::conv_padding_t;
+
+  /// optional bias of shape `(out_channels)`. Default: ``None``
+  TORCH_ARG(torch::Tensor, bias) = Tensor();
+
+  /// The stride of the convolving kernel.
+  /// For a `D`-dim convolution, must be a single number or a list of `D`
+  /// numbers.
+  TORCH_ARG(ExpandingArray, stride) = 1;
+
+  /// Implicit paddings on both sides of the input.
+  /// For a `D`-dim convolution, must be a single number or a list of `D`
+  /// numbers.
+  TORCH_ARG(padding_t, padding) = 0;
+
+ public:
+  decltype(auto) padding(std::initializer_list il) {
+    return padding(IntArrayRef{il});
+  }
+
+  /// The spacing between kernel elements.
+  /// For a `D`-dim convolution, must be a single number or a list of `D`
+  /// numbers.
+  TORCH_ARG(ExpandingArray, dilation) = 1;
+
+  /// Split input into groups, `in_channels` should be divisible by
+  /// the number of groups.
+  TORCH_ARG(int64_t, groups) = 1;
+};
+
+/// `ConvFuncOptions` specialized for `torch::nn::functional::conv1d`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::conv1d(x, weight, F::Conv1dFuncOptions().stride(1));
+/// ```
+using Conv1dFuncOptions = ConvFuncOptions<1>;
+
+/// `ConvFuncOptions` specialized for `torch::nn::functional::conv2d`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::conv2d(x, weight, F::Conv2dFuncOptions().stride(1));
+/// ```
+using Conv2dFuncOptions = ConvFuncOptions<2>;
+
+/// `ConvFuncOptions` specialized for `torch::nn::functional::conv3d`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::conv3d(x, weight, F::Conv3dFuncOptions().stride(1));
+/// ```
+using Conv3dFuncOptions = ConvFuncOptions<3>;
+
+} // namespace functional
+
+// ============================================================================
+
+template 
+struct ConvTransposeOptions {
+  using padding_mode_t = detail::conv_padding_mode_t;
+
+  ConvTransposeOptions(
+      int64_t in_channels,
+      int64_t out_channels,
+      ExpandingArray kernel_size)
+      : in_channels_(in_channels),
+        out_channels_(out_channels),
+        kernel_size_(std::move(kernel_size)) {}
+
+  /// The number of channels the input volumes will have.
+  /// Changing this parameter after construction __has no effect__.
+  TORCH_ARG(int64_t, in_channels);
+
+  /// The number of output channels the convolution should produce.
+  /// Changing this parameter after construction __has no effect__.
+  TORCH_ARG(int64_t, out_channels);
+
+  /// The kernel size to use.
+  /// For a `D`-dim convolution, must be a single number or a list of `D`
+  /// numbers.
+  /// This parameter __can__ be changed after construction.
+  TORCH_ARG(ExpandingArray, kernel_size);
+
+  /// The stride of the convolution.
+  /// For a `D`-dim convolution, must be a single number or a list of `D`
+  /// numbers.
+  /// This parameter __can__ be changed after construction.
+  TORCH_ARG(ExpandingArray, stride) = 1;
+
+  /// The padding to add to the input volumes.
+  /// For a `D`-dim convolution, must be a single number or a list of `D`
+  /// numbers.
+  /// This parameter __can__ be changed after construction.
+  TORCH_ARG(ExpandingArray, padding) = 0;
+
+  /// For transpose convolutions, the padding to add to output volumes.
+  /// For a `D`-dim convolution, must be a single number or a list of `D`
+  /// numbers.
+  /// This parameter __can__ be changed after construction.
+  TORCH_ARG(ExpandingArray, output_padding) = 0;
+
+  /// The number of convolution groups.
+  /// This parameter __can__ be changed after construction.
+  TORCH_ARG(int64_t, groups) = 1;
+
+  /// Whether to add a bias after individual applications of the kernel.
+  /// Changing this parameter after construction __has no effect__.
+  TORCH_ARG(bool, bias) = true;
+
+  /// The kernel dilation.
+  /// For a `D`-dim convolution, must be a single number or a list of `D`
+  /// numbers.
+  /// This parameter __can__ be changed after construction.
+  TORCH_ARG(ExpandingArray, dilation) = 1;
+
+  /// Accepted values `torch::kZeros`, `torch::kReflect`, `torch::kReplicate` or
+  /// `torch::kCircular`. Default: `torch::kZeros`
+  TORCH_ARG(padding_mode_t, padding_mode) = torch::kZeros;
+};
+
+/// `ConvTransposeOptions` specialized for the `ConvTranspose1d` module.
+///
+/// Example:
+/// ```
+/// ConvTranspose1d model(ConvTranspose1dOptions(3, 2,
+/// 3).stride(1).bias(false));
+/// ```
+using ConvTranspose1dOptions = ConvTransposeOptions<1>;
+
+/// `ConvTransposeOptions` specialized for the `ConvTranspose2d` module.
+///
+/// Example:
+/// ```
+/// ConvTranspose2d model(ConvTranspose2dOptions(3, 2,
+/// 3).stride(1).bias(false));
+/// ```
+using ConvTranspose2dOptions = ConvTransposeOptions<2>;
+
+/// `ConvTransposeOptions` specialized for the `ConvTranspose3d` module.
+///
+/// Example:
+/// ```
+/// ConvTranspose3d model(ConvTranspose3dOptions(2, 2,
+/// 2).stride(1).bias(false));
+/// ```
+using ConvTranspose3dOptions = ConvTransposeOptions<3>;
+
+// ============================================================================
+
+namespace functional {
+
+/// Options for a `D`-dimensional convolution functional.
+template 
+struct ConvTransposeFuncOptions {
+  /// optional bias of shape `(out_channels)`. Default: ``None``
+  TORCH_ARG(torch::Tensor, bias) = Tensor();
+
+  /// The stride of the convolving kernel.
+  /// For a `D`-dim convolution, must be a single number or a list of `D`
+  /// numbers.
+  TORCH_ARG(ExpandingArray, stride) = 1;
+
+  /// Implicit paddings on both sides of the input.
+  /// For a `D`-dim convolution, must be a single number or a list of `D`
+  /// numbers.
+  TORCH_ARG(ExpandingArray, padding) = 0;
+
+  /// Additional size added to one side of each dimension in the output shape.
+  /// Default: 0
+  TORCH_ARG(ExpandingArray, output_padding) = 0;
+
+  /// Split input into groups, `in_channels` should be divisible by
+  /// the number of groups.
+  TORCH_ARG(int64_t, groups) = 1;
+
+  /// The spacing between kernel elements.
+  /// For a `D`-dim convolution, must be a single number or a list of `D`
+  /// numbers.
+  TORCH_ARG(ExpandingArray, dilation) = 1;
+};
+
+/// `ConvTransposeFuncOptions` specialized for
+/// `torch::nn::functional::conv_transpose1d`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::conv_transpose1d(x, weight, F::ConvTranspose1dFuncOptions().stride(1));
+/// ```
+using ConvTranspose1dFuncOptions = ConvTransposeFuncOptions<1>;
+
+/// `ConvTransposeFuncOptions` specialized for
+/// `torch::nn::functional::conv_transpose2d`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::conv_transpose2d(x, weight, F::ConvTranspose2dFuncOptions().stride(1));
+/// ```
+using ConvTranspose2dFuncOptions = ConvTransposeFuncOptions<2>;
+
+/// `ConvTransposeFuncOptions` specialized for
+/// `torch::nn::functional::conv_transpose3d`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::conv_transpose3d(x, weight, F::ConvTranspose3dFuncOptions().stride(1));
+/// ```
+using ConvTranspose3dFuncOptions = ConvTransposeFuncOptions<3>;
+
+} // namespace functional
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/distance.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/distance.h
new file mode 100644
index 0000000000000000000000000000000000000000..654cd6626498db19fe1ec548e1d10c48cfeb390f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/distance.h
@@ -0,0 +1,71 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Options for the `CosineSimilarity` module.
+///
+/// Example:
+/// ```
+/// CosineSimilarity model(CosineSimilarityOptions().dim(0).eps(0.5));
+/// ```
+struct TORCH_API CosineSimilarityOptions {
+  /// Dimension where cosine similarity is computed. Default: 1
+  TORCH_ARG(int64_t, dim) = 1;
+  /// Small value to avoid division by zero. Default: 1e-8
+  TORCH_ARG(double, eps) = 1e-8;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::cosine_similarity`.
+///
+/// See the documentation for `torch::nn::CosineSimilarityOptions` class to
+/// learn what arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::cosine_similarity(input1, input2,
+/// F::CosineSimilarityFuncOptions().dim(1));
+/// ```
+using CosineSimilarityFuncOptions = CosineSimilarityOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `PairwiseDistance` module.
+///
+/// Example:
+/// ```
+/// PairwiseDistance
+/// model(PairwiseDistanceOptions().p(3).eps(0.5).keepdim(true));
+/// ```
+struct TORCH_API PairwiseDistanceOptions {
+  /// The norm degree. Default: 2
+  TORCH_ARG(double, p) = 2.0;
+  /// Small value to avoid division by zero. Default: 1e-6
+  TORCH_ARG(double, eps) = 1e-6;
+  /// Determines whether or not to keep the vector dimension. Default: false
+  TORCH_ARG(bool, keepdim) = false;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::pairwise_distance`.
+///
+/// See the documentation for `torch::nn::PairwiseDistanceOptions` class to
+/// learn what arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::pairwise_distance(input1, input2, F::PairwiseDistanceFuncOptions().p(1));
+/// ```
+using PairwiseDistanceFuncOptions = PairwiseDistanceOptions;
+} // namespace functional
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/dropout.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/dropout.h
new file mode 100644
index 0000000000000000000000000000000000000000..7f41f5672382c9e612b8c6f29c4ac261f02e328c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/dropout.h
@@ -0,0 +1,130 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Options for the `Dropout` module.
+///
+/// Example:
+/// ```
+/// Dropout model(DropoutOptions().p(0.42).inplace(true));
+/// ```
+struct TORCH_API DropoutOptions {
+  /* implicit */ DropoutOptions(double p = 0.5);
+
+  /// The probability of an element to be zeroed. Default: 0.5
+  TORCH_ARG(double, p) = 0.5;
+
+  /// can optionally do the operation in-place. Default: False
+  TORCH_ARG(bool, inplace) = false;
+};
+
+/// Options for the `Dropout2d` module.
+///
+/// Example:
+/// ```
+/// Dropout2d model(Dropout2dOptions().p(0.42).inplace(true));
+/// ```
+using Dropout2dOptions = DropoutOptions;
+
+/// Options for the `Dropout3d` module.
+///
+/// Example:
+/// ```
+/// Dropout3d model(Dropout3dOptions().p(0.42).inplace(true));
+/// ```
+using Dropout3dOptions = DropoutOptions;
+
+/// Options for the `AlphaDropout` module.
+///
+/// Example:
+/// ```
+/// AlphaDropout model(AlphaDropoutOptions(0.2).inplace(true));
+/// ```
+using AlphaDropoutOptions = DropoutOptions;
+
+/// Options for the `FeatureAlphaDropout` module.
+///
+/// Example:
+/// ```
+/// FeatureAlphaDropout model(FeatureAlphaDropoutOptions(0.2).inplace(true));
+/// ```
+using FeatureAlphaDropoutOptions = DropoutOptions;
+
+namespace functional {
+
+/// Options for `torch::nn::functional::dropout`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::dropout(input, F::DropoutFuncOptions().p(0.5));
+/// ```
+struct TORCH_API DropoutFuncOptions {
+  /// The probability of an element to be zeroed. Default: 0.5
+  TORCH_ARG(double, p) = 0.5;
+
+  TORCH_ARG(bool, training) = true;
+
+  /// can optionally do the operation in-place. Default: False
+  TORCH_ARG(bool, inplace) = false;
+};
+
+/// Options for `torch::nn::functional::dropout2d`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::dropout2d(input, F::Dropout2dFuncOptions().p(0.5));
+/// ```
+using Dropout2dFuncOptions = DropoutFuncOptions;
+
+/// Options for `torch::nn::functional::dropout3d`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::dropout3d(input, F::Dropout3dFuncOptions().p(0.5));
+/// ```
+using Dropout3dFuncOptions = DropoutFuncOptions;
+
+/// Options for `torch::nn::functional::alpha_dropout`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::alpha_dropout(input,
+/// F::AlphaDropoutFuncOptions().p(0.5).training(false));
+/// ```
+struct TORCH_API AlphaDropoutFuncOptions {
+  TORCH_ARG(double, p) = 0.5;
+
+  TORCH_ARG(bool, training) = false;
+
+  TORCH_ARG(bool, inplace) = false;
+};
+
+/// Options for `torch::nn::functional::feature_alpha_dropout`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::feature_alpha_dropout(input,
+/// F::FeatureAlphaDropoutFuncOptions().p(0.5).training(false));
+/// ```
+struct TORCH_API FeatureAlphaDropoutFuncOptions {
+  TORCH_ARG(double, p) = 0.5;
+
+  TORCH_ARG(bool, training) = false;
+
+  TORCH_ARG(bool, inplace) = false;
+};
+
+} // namespace functional
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/embedding.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/embedding.h
new file mode 100644
index 0000000000000000000000000000000000000000..a3d2fdb72f54da12cc797bc2cab50270e79af95d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/embedding.h
@@ -0,0 +1,242 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Options for the `Embedding` module.
+///
+/// Example:
+/// ```
+/// Embedding model(EmbeddingOptions(10,
+/// 2).padding_idx(3).max_norm(2).norm_type(2.5).scale_grad_by_freq(true).sparse(true));
+/// ```
+struct TORCH_API EmbeddingOptions {
+  EmbeddingOptions(int64_t num_embeddings, int64_t embedding_dim);
+
+  /// The size of the dictionary of embeddings.
+  TORCH_ARG(int64_t, num_embeddings);
+  /// The size of each embedding vector.
+  TORCH_ARG(int64_t, embedding_dim);
+  /// If specified, the entries at `padding_idx` do not contribute to the
+  /// gradient; therefore, the embedding vector at `padding_idx` is not updated
+  /// during training, i.e. it remains as a fixed "pad". For a newly constructed
+  /// Embedding, the embedding vector at `padding_idx` will default to all
+  /// zeros, but can be updated to another value to be used as the padding
+  /// vector.
+  TORCH_ARG(std::optional, padding_idx) = std::nullopt;
+  /// If given, each embedding vector with norm larger than `max_norm` is
+  /// renormalized to have norm `max_norm`.
+  TORCH_ARG(std::optional, max_norm) = std::nullopt;
+  /// The p of the p-norm to compute for the `max_norm` option. Default ``2``.
+  TORCH_ARG(double, norm_type) = 2.;
+  /// If given, this will scale gradients by the inverse of frequency of the
+  /// words in the mini-batch. Default ``false``.
+  TORCH_ARG(bool, scale_grad_by_freq) = false;
+  /// If ``true``, gradient w.r.t. `weight` matrix will be a sparse tensor.
+  TORCH_ARG(bool, sparse) = false;
+  /// The learnable weights of the module of shape (num_embeddings,
+  /// embedding_dim)
+  TORCH_ARG(torch::Tensor, _weight) = Tensor();
+};
+
+// ============================================================================
+
+/// Options for the `Embedding::from_pretrained` function.
+struct TORCH_API EmbeddingFromPretrainedOptions {
+  /// If ``true``, the tensor does not get updated in the learning process.
+  /// Equivalent to ``embedding.weight.requires_grad_(false)``. Default:
+  /// ``true``
+  TORCH_ARG(bool, freeze) = true;
+  /// If specified, the entries at `padding_idx` do not contribute to the
+  /// gradient; therefore, the embedding vector at `padding_idx` is not updated
+  /// during training, i.e. it remains as a fixed "pad".
+  TORCH_ARG(std::optional, padding_idx) = std::nullopt;
+  /// If given, each embedding vector with norm larger than `max_norm` is
+  /// renormalized to have norm `max_norm`.
+  TORCH_ARG(std::optional, max_norm) = std::nullopt;
+  /// The p of the p-norm to compute for the `max_norm` option. Default ``2``.
+  TORCH_ARG(double, norm_type) = 2.;
+  /// If given, this will scale gradients by the inverse of frequency of the
+  /// words in the mini-batch. Default ``false``.
+  TORCH_ARG(bool, scale_grad_by_freq) = false;
+  /// If ``true``, gradient w.r.t. `weight` matrix will be a sparse tensor.
+  TORCH_ARG(bool, sparse) = false;
+};
+
+// ============================================================================
+
+namespace functional {
+
+/// Options for `torch::nn::functional::embedding`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::embedding(input, weight,
+/// F::EmbeddingFuncOptions().norm_type(2.5).scale_grad_by_freq(true).sparse(true));
+/// ```
+struct TORCH_API EmbeddingFuncOptions {
+  /// If specified, the entries at `padding_idx` do not contribute to the
+  /// gradient; therefore, the embedding vector at `padding_idx` is not updated
+  /// during training, i.e. it remains as a fixed "pad".
+  TORCH_ARG(std::optional, padding_idx) = std::nullopt;
+  /// If given, each embedding vector with norm larger than `max_norm` is
+  /// renormalized to have norm `max_norm`.
+  TORCH_ARG(std::optional, max_norm) = std::nullopt;
+  /// The p of the p-norm to compute for the `max_norm` option. Default ``2``.
+  TORCH_ARG(double, norm_type) = 2.;
+  /// If given, this will scale gradients by the inverse of frequency of the
+  /// words in the mini-batch. Default ``false``.
+  TORCH_ARG(bool, scale_grad_by_freq) = false;
+  /// If ``true``, gradient w.r.t. `weight` matrix will be a sparse tensor.
+  TORCH_ARG(bool, sparse) = false;
+};
+
+} // namespace functional
+
+// ============================================================================
+
+typedef std::variant
+    EmbeddingBagMode;
+
+/// Options for the `EmbeddingBag` module.
+///
+/// Example:
+/// ```
+/// EmbeddingBag model(EmbeddingBagOptions(10,
+/// 2).max_norm(2).norm_type(2.5).scale_grad_by_freq(true).sparse(true).mode(torch::kSum));
+/// ```
+struct TORCH_API EmbeddingBagOptions {
+  EmbeddingBagOptions(int64_t num_embeddings, int64_t embedding_dim);
+
+  /// The size of the dictionary of embeddings.
+  TORCH_ARG(int64_t, num_embeddings);
+  /// The size of each embedding vector.
+  TORCH_ARG(int64_t, embedding_dim);
+  /// If given, each embedding vector with norm larger than `max_norm` is
+  /// renormalized to have norm `max_norm`.
+  TORCH_ARG(std::optional, max_norm) = std::nullopt;
+  /// The p of the p-norm to compute for the `max_norm` option. Default ``2``.
+  TORCH_ARG(double, norm_type) = 2.;
+  /// If given, this will scale gradients by the inverse of frequency of the
+  /// words in the mini-batch. Default ``false``. Note: this option is not
+  /// supported when ``mode="kMax"``.
+  TORCH_ARG(bool, scale_grad_by_freq) = false;
+  /// ``"kSum"``, ``"kMean"`` or ``"kMax"``. Specifies the way to reduce the
+  /// bag. ``"kSum"`` computes the weighted sum, taking `per_sample_weights`
+  /// into consideration. ``"kMean"`` computes the average of the values in the
+  /// bag, ``"kMax"`` computes the max value over each bag.
+  TORCH_ARG(EmbeddingBagMode, mode) = torch::kMean;
+  /// If ``true``, gradient w.r.t. `weight` matrix will be a sparse tensor.
+  /// Note: this option is not supported when ``mode="kMax"``.
+  TORCH_ARG(bool, sparse) = false;
+  /// The learnable weights of the module of shape (num_embeddings,
+  /// embedding_dim)
+  TORCH_ARG(torch::Tensor, _weight) = Tensor();
+  /// If ``true``, `offsets` has one additional element, where the last element
+  /// is equivalent to the size of `indices`. This matches the CSR format.
+  TORCH_ARG(bool, include_last_offset) = false;
+  /// If specified, the entries at `padding_idx` do not contribute to the
+  /// gradient; therefore, the embedding vector at padding_idx is not updated
+  /// during training, i.e. it remains as a fixed "pad". For a newly constructed
+  /// EmbeddingBag, the embedding vector at `padding_idx` will default to all
+  /// zeros, but can be updated to another value to be used as the padding
+  /// vector. Note that the embedding vector at `padding_idx` is excluded from
+  /// the reduction.
+  TORCH_ARG(std::optional, padding_idx) = std::nullopt;
+};
+
+// ============================================================================
+
+/// Options for the `EmbeddingBag::from_pretrained` function.
+struct TORCH_API EmbeddingBagFromPretrainedOptions {
+  /// If ``true``, the tensor does not get updated in the learning process.
+  /// Equivalent to ``embeddingbag.weight.requires_grad_(false)``. Default:
+  /// ``true``
+  TORCH_ARG(bool, freeze) = true;
+  /// If given, each embedding vector with norm larger than `max_norm` is
+  /// renormalized to have norm `max_norm`.
+  TORCH_ARG(std::optional, max_norm) = std::nullopt;
+  /// The p of the p-norm to compute for the `max_norm` option. Default ``2``.
+  TORCH_ARG(double, norm_type) = 2.;
+  /// If given, this will scale gradients by the inverse of frequency of the
+  /// words in the mini-batch. Default ``false``. Note: this option is not
+  /// supported when ``mode="kMax"``.
+  TORCH_ARG(bool, scale_grad_by_freq) = false;
+  /// ``"kSum"``, ``"kMean"`` or ``"kMax"``. Specifies the way to reduce the
+  /// bag. ``"kSum"`` computes the weighted sum, taking `per_sample_weights`
+  /// into consideration. ``"kMean"`` computes the average of the values in the
+  /// bag, ``"kMax"`` computes the max value over each bag.
+  TORCH_ARG(EmbeddingBagMode, mode) = torch::kMean;
+  /// If ``true``, gradient w.r.t. `weight` matrix will be a sparse tensor.
+  /// Note: this option is not supported when ``mode="kMax"``.
+  TORCH_ARG(bool, sparse) = false;
+  /// If ``true``, `offsets` has one additional element, where the last element
+  /// is equivalent to the size of `indices`. This matches the CSR format. Note:
+  /// this option is currently only supported when ``mode="sum"``.
+  TORCH_ARG(bool, include_last_offset) = false;
+  /// If specified, the entries at `padding_idx` do not contribute to the
+  /// gradient; therefore, the embedding vector at padding_idx is not updated
+  /// during training, i.e. it remains as a fixed "pad". Note that the embedding
+  /// vector at `padding_idx` is excluded from the reduction.
+  TORCH_ARG(std::optional, padding_idx) = std::nullopt;
+};
+
+// ============================================================================
+
+namespace functional {
+
+/// Options for `torch::nn::functional::embedding_bag`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::embedding_bag(input, weight,
+/// F::EmbeddingBagFuncOptions().mode(torch::kSum).offsets(offsets));
+/// ```
+struct TORCH_API EmbeddingBagFuncOptions {
+  /// Only used when `input` is 1D. `offsets` determines
+  /// the starting index position of each bag (sequence) in `input`.
+  TORCH_ARG(torch::Tensor, offsets) = Tensor();
+  /// If given, each embedding vector with norm larger than `max_norm` is
+  /// renormalized to have norm `max_norm`.
+  TORCH_ARG(std::optional, max_norm) = std::nullopt;
+  /// The p of the p-norm to compute for the `max_norm` option. Default ``2``.
+  TORCH_ARG(double, norm_type) = 2.;
+  /// If given, this will scale gradients by the inverse of frequency of the
+  /// words in the mini-batch. Default ``false``. Note: this option is not
+  /// supported when ``mode="kMax"``.
+  TORCH_ARG(bool, scale_grad_by_freq) = false;
+  /// ``"kSum"``, ``"kMean"`` or ``"kMax"``. Specifies the way to reduce the
+  /// bag. ``"kSum"`` computes the weighted sum, taking `per_sample_weights`
+  /// into consideration. ``"kMean"`` computes the average of the values in the
+  /// bag, ``"kMax"`` computes the max value over each bag.
+  TORCH_ARG(EmbeddingBagMode, mode) = torch::kMean;
+  /// If ``true``, gradient w.r.t. `weight` matrix will be a sparse tensor.
+  /// Note: this option is not supported when ``mode="kMax"``.
+  TORCH_ARG(bool, sparse) = false;
+  /// a tensor of float / double weights, or None to indicate all weights should
+  /// be taken to be 1. If specified, `per_sample_weights` must have exactly the
+  /// same shape as input and is treated as having the same `offsets`, if those
+  /// are not None.
+  TORCH_ARG(torch::Tensor, per_sample_weights) = Tensor();
+  /// If ``true``, `offsets` has one additional element, where the last element
+  /// is equivalent to the size of `indices`. This matches the CSR format. Note:
+  /// this option is currently only supported when ``mode="sum"``.
+  TORCH_ARG(bool, include_last_offset) = false;
+  /// If specified, the entries at `padding_idx` do not contribute to the
+  /// gradient; therefore, the embedding vector at padding_idx is not updated
+  /// during training, i.e. it remains as a fixed "pad". Note that the embedding
+  /// vector at `padding_idx` is excluded from the reduction.
+  TORCH_ARG(std::optional, padding_idx) = std::nullopt;
+};
+
+} // namespace functional
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/fold.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/fold.h
new file mode 100644
index 0000000000000000000000000000000000000000..21c24bff845acfcf94724c2b0dc717b7ca250d2a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/fold.h
@@ -0,0 +1,99 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Options for the `Fold` module.
+///
+/// Example:
+/// ```
+/// Fold model(FoldOptions({8, 8}, {3, 3}).dilation(2).padding({2,
+/// 1}).stride(2));
+/// ```
+struct TORCH_API FoldOptions {
+  FoldOptions(ExpandingArray<2> output_size, ExpandingArray<2> kernel_size)
+      : output_size_(std::move(output_size)),
+        kernel_size_(std::move(kernel_size)) {}
+
+  /// describes the spatial shape of the large containing tensor of the sliding
+  /// local blocks. It is useful to resolve the ambiguity when multiple input
+  /// shapes map to same number of sliding blocks, e.g., with stride > 0.
+  TORCH_ARG(ExpandingArray<2>, output_size);
+
+  /// the size of the sliding blocks
+  TORCH_ARG(ExpandingArray<2>, kernel_size);
+
+  /// controls the spacing between the kernel points; also known as the à trous
+  /// algorithm.
+  TORCH_ARG(ExpandingArray<2>, dilation) = 1;
+
+  /// controls the amount of implicit zero-paddings on both sides for padding
+  /// number of points for each dimension before reshaping.
+  TORCH_ARG(ExpandingArray<2>, padding) = 0;
+
+  /// controls the stride for the sliding blocks.
+  TORCH_ARG(ExpandingArray<2>, stride) = 1;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::fold`.
+///
+/// See the documentation for `torch::nn::FoldOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::fold(input, F::FoldFuncOptions({3, 2}, {2, 2}));
+/// ```
+using FoldFuncOptions = FoldOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `Unfold` module.
+///
+/// Example:
+/// ```
+/// Unfold model(UnfoldOptions({2, 4}).dilation(2).padding({2, 1}).stride(2));
+/// ```
+struct TORCH_API UnfoldOptions {
+  UnfoldOptions(ExpandingArray<2> kernel_size)
+      : kernel_size_(std::move(kernel_size)) {}
+
+  /// the size of the sliding blocks
+  TORCH_ARG(ExpandingArray<2>, kernel_size);
+
+  /// controls the spacing between the kernel points; also known as the à trous
+  /// algorithm.
+  TORCH_ARG(ExpandingArray<2>, dilation) = 1;
+
+  /// controls the amount of implicit zero-paddings on both sides for padding
+  /// number of points for each dimension before reshaping.
+  TORCH_ARG(ExpandingArray<2>, padding) = 0;
+
+  /// controls the stride for the sliding blocks.
+  TORCH_ARG(ExpandingArray<2>, stride) = 1;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::unfold`.
+///
+/// See the documentation for `torch::nn::UnfoldOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::unfold(input, F::UnfoldFuncOptions({2, 2}).padding(1).stride(2));
+/// ```
+using UnfoldFuncOptions = UnfoldOptions;
+} // namespace functional
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/instancenorm.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/instancenorm.h
new file mode 100644
index 0000000000000000000000000000000000000000..d93e10d0c95a23befcfe0318ebc4ddcd96aa5e71
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/instancenorm.h
@@ -0,0 +1,89 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Options for the `InstanceNorm` module.
+struct TORCH_API InstanceNormOptions {
+  /* implicit */ InstanceNormOptions(int64_t num_features);
+
+  /// The number of features of the input tensor.
+  TORCH_ARG(int64_t, num_features);
+
+  /// The epsilon value added for numerical stability.
+  TORCH_ARG(double, eps) = 1e-5;
+
+  /// A momentum multiplier for the mean and variance.
+  TORCH_ARG(double, momentum) = 0.1;
+
+  /// Whether to learn a scale and bias that are applied in an affine
+  /// transformation on the input.
+  TORCH_ARG(bool, affine) = false;
+
+  /// Whether to store and update batch statistics (mean and variance) in the
+  /// module.
+  TORCH_ARG(bool, track_running_stats) = false;
+};
+
+/// Options for the `InstanceNorm1d` module.
+///
+/// Example:
+/// ```
+/// InstanceNorm1d
+/// model(InstanceNorm1dOptions(4).eps(0.5).momentum(0.1).affine(false).track_running_stats(true));
+/// ```
+using InstanceNorm1dOptions = InstanceNormOptions;
+
+/// Options for the `InstanceNorm2d` module.
+///
+/// Example:
+/// ```
+/// InstanceNorm2d
+/// model(InstanceNorm2dOptions(4).eps(0.5).momentum(0.1).affine(false).track_running_stats(true));
+/// ```
+using InstanceNorm2dOptions = InstanceNormOptions;
+
+/// Options for the `InstanceNorm3d` module.
+///
+/// Example:
+/// ```
+/// InstanceNorm3d
+/// model(InstanceNorm3dOptions(4).eps(0.5).momentum(0.1).affine(false).track_running_stats(true));
+/// ```
+using InstanceNorm3dOptions = InstanceNormOptions;
+
+namespace functional {
+
+/// Options for `torch::nn::functional::instance_norm`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::instance_norm(input,
+/// F::InstanceNormFuncOptions().running_mean(mean).running_var(variance).weight(weight).bias(bias).momentum(0.1).eps(1e-5));
+/// ```
+struct TORCH_API InstanceNormFuncOptions {
+  TORCH_ARG(Tensor, running_mean) = Tensor();
+
+  TORCH_ARG(Tensor, running_var) = Tensor();
+
+  TORCH_ARG(Tensor, weight) = Tensor();
+
+  TORCH_ARG(Tensor, bias) = Tensor();
+
+  TORCH_ARG(bool, use_input_stats) = true;
+
+  TORCH_ARG(double, momentum) = 0.1;
+
+  TORCH_ARG(double, eps) = 1e-5;
+};
+
+} // namespace functional
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/linear.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/linear.h
new file mode 100644
index 0000000000000000000000000000000000000000..5952d97806b378814f8bb0c1ffa6cf783d2f8426
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/linear.h
@@ -0,0 +1,95 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Options for the `Linear` module.
+///
+/// Example:
+/// ```
+/// Linear model(LinearOptions(5, 2).bias(false));
+/// ```
+struct TORCH_API LinearOptions {
+  LinearOptions(int64_t in_features, int64_t out_features);
+  /// size of each input sample
+  TORCH_ARG(int64_t, in_features);
+
+  /// size of each output sample
+  TORCH_ARG(int64_t, out_features);
+
+  /// If set to false, the layer will not learn an additive bias. Default: true
+  TORCH_ARG(bool, bias) = true;
+};
+
+// ============================================================================
+
+/// Options for the `Flatten` module.
+///
+/// Example:
+/// ```
+/// Flatten model(FlattenOptions().start_dim(2).end_dim(4));
+/// ```
+struct TORCH_API FlattenOptions {
+  /// first dim to flatten
+  TORCH_ARG(int64_t, start_dim) = 1;
+  /// last dim to flatten
+  TORCH_ARG(int64_t, end_dim) = -1;
+};
+
+// ============================================================================
+
+/// Options for the `Unflatten` module.
+///
+/// Note: If input tensor is named, use dimname and namedshape arguments.
+///
+/// Example:
+/// ```
+/// Unflatten unnamed_model(UnflattenOptions(0, {2, 2}));
+/// Unflatten named_model(UnflattenOptions("B", {{"B1", 2}, {"B2", 2}}));
+/// ```
+struct TORCH_API UnflattenOptions {
+  typedef std::vector> namedshape_t;
+
+  UnflattenOptions(int64_t dim, std::vector sizes);
+  UnflattenOptions(const char* dimname, namedshape_t namedshape);
+  UnflattenOptions(std::string dimname, namedshape_t namedshape);
+
+  /// dim to unflatten
+  TORCH_ARG(int64_t, dim);
+  /// name of dim to unflatten, for use with named tensors
+  TORCH_ARG(std::string, dimname);
+  /// new shape of unflattened dim
+  TORCH_ARG(std::vector, sizes);
+  /// new shape of unflattened dim with names, for use with named tensors
+  TORCH_ARG(namedshape_t, namedshape);
+};
+
+// ============================================================================
+
+/// Options for the `Bilinear` module.
+///
+/// Example:
+/// ```
+/// Bilinear model(BilinearOptions(3, 2, 4).bias(false));
+/// ```
+struct TORCH_API BilinearOptions {
+  BilinearOptions(
+      int64_t in1_features,
+      int64_t in2_features,
+      int64_t out_features);
+  /// The number of features in input 1 (columns of the input1 matrix).
+  TORCH_ARG(int64_t, in1_features);
+  /// The number of features in input 2 (columns of the input2 matrix).
+  TORCH_ARG(int64_t, in2_features);
+  /// The number of output features to produce (columns of the output matrix).
+  TORCH_ARG(int64_t, out_features);
+  /// Whether to learn and add a bias after the bilinear transformation.
+  TORCH_ARG(bool, bias) = true;
+};
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/loss.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/loss.h
new file mode 100644
index 0000000000000000000000000000000000000000..5a6e7aa3ab20be52ce7542376a82c53bb45186f7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/loss.h
@@ -0,0 +1,802 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Options for the `L1Loss` module.
+///
+/// Example:
+/// ```
+/// L1Loss model(L1LossOptions(torch::kNone));
+/// ```
+struct TORCH_API L1LossOptions {
+  typedef std::variant
+      reduction_t;
+
+  TORCH_OPTIONS_CTOR_VARIANT_ARG3(L1LossOptions, reduction, kNone, kMean, kSum)
+
+  /// Specifies the reduction to apply to the output.
+  TORCH_ARG(reduction_t, reduction) = torch::kMean;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::l1_loss`.
+///
+/// See the documentation for `torch::nn::L1LossOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::l1_loss(input, target, F::L1LossFuncOptions(torch::kNone));
+/// ```
+using L1LossFuncOptions = L1LossOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `KLDivLoss` module.
+///
+/// Example:
+/// ```
+/// KLDivLoss
+/// model(KLDivLossOptions().reduction(torch::kNone).log_target(false));
+/// ```
+struct TORCH_API KLDivLossOptions {
+  typedef std::variant<
+      enumtype::kNone,
+      enumtype::kBatchMean,
+      enumtype::kSum,
+      enumtype::kMean>
+      reduction_t;
+
+  TORCH_OPTIONS_CTOR_VARIANT_ARG4(
+      KLDivLossOptions,
+      reduction,
+      kNone,
+      kBatchMean,
+      kSum,
+      kMean)
+
+  /// Specifies the reduction to apply to the output.
+  /// ``'none'`` | ``'batchmean'`` | ``'sum'`` | ``'mean'``. Default: ``'mean'``
+  TORCH_ARG(reduction_t, reduction) = torch::kMean;
+
+  /// Specifies whether `target` is accepted in the log space. Default: False
+  TORCH_ARG(bool, log_target) = false;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::kl_div`.
+///
+/// See the documentation for `torch::nn::KLDivLossOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::kl_div(input, target,
+/// F::KLDivFuncOptions().reduction(torch::kNone).log_target(false));
+/// ```
+using KLDivFuncOptions = KLDivLossOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `MSELoss` module.
+///
+/// Example:
+/// ```
+/// MSELoss model(MSELossOptions(torch::kNone));
+/// ```
+struct TORCH_API MSELossOptions {
+  typedef std::variant
+      reduction_t;
+
+  TORCH_OPTIONS_CTOR_VARIANT_ARG3(MSELossOptions, reduction, kNone, kMean, kSum)
+
+  /// Specifies the reduction to apply to the output.
+  /// ``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'mean'``
+  TORCH_ARG(reduction_t, reduction) = torch::kMean;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::mse_loss`.
+///
+/// See the documentation for `torch::nn::MSELossOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::mse_loss(input, target, F::MSELossFuncOptions(torch::kNone));
+/// ```
+using MSELossFuncOptions = MSELossOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `BCELoss` module.
+///
+/// Example:
+/// ```
+/// BCELoss model(BCELossOptions().reduction(torch::kNone).weight(weight));
+/// ```
+struct TORCH_API BCELossOptions {
+  typedef std::variant
+      reduction_t;
+
+  /// A manual rescaling weight given to the loss of each batch element.
+  TORCH_ARG(Tensor, weight) = {};
+  /// Specifies the reduction to apply to the output.
+  /// ``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'mean'``
+  TORCH_ARG(reduction_t, reduction) = torch::kMean;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::binary_cross_entropy`.
+///
+/// See the documentation for `torch::nn::BCELossOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::binary_cross_entropy(input, target,
+/// F::BinaryCrossEntropyFuncOptions().weight(weight));
+/// ```
+using BinaryCrossEntropyFuncOptions = BCELossOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `HingeEmbeddingLoss` module.
+///
+/// Example:
+/// ```
+/// HingeEmbeddingLoss
+/// model(HingeEmbeddingLossOptions().margin(4).reduction(torch::kNone));
+/// ```
+struct TORCH_API HingeEmbeddingLossOptions {
+  typedef std::variant
+      reduction_t;
+
+  /// Specifies the threshold for which the distance of a negative sample must
+  /// reach in order to incur zero loss. Default: 1
+  TORCH_ARG(double, margin) = 1.0;
+  /// Specifies the reduction to apply to the output. Default: Mean
+  TORCH_ARG(reduction_t, reduction) = torch::kMean;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::hinge_embedding_loss`.
+///
+/// See the documentation for `torch::nn::HingeEmbeddingLossOptions` class to
+/// learn what arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::hinge_embedding_loss(input, target,
+/// F::HingeEmbeddingLossFuncOptions().margin(2));
+/// ```
+using HingeEmbeddingLossFuncOptions = HingeEmbeddingLossOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `MultiMarginLoss` module.
+///
+/// Example:
+/// ```
+/// MultiMarginLoss model(MultiMarginLossOptions().margin(2).weight(weight));
+/// ```
+struct TORCH_API MultiMarginLossOptions {
+  typedef std::variant
+      reduction_t;
+
+  /// Has a default value of :math:`1`. :math:`1` and :math:`2`
+  /// are the only supported values.
+  TORCH_ARG(int64_t, p) = 1;
+  /// Has a default value of :math:`1`.
+  TORCH_ARG(double, margin) = 1.0;
+  /// A manual rescaling weight given to each
+  /// class. If given, it has to be a Tensor of size `C`. Otherwise, it is
+  /// treated as if having all ones.
+  TORCH_ARG(Tensor, weight) = Tensor();
+  /// Specifies the reduction to apply to the output:
+  /// ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be
+  /// applied,
+  /// ``'mean'``: the sum of the output will be divided by the number of
+  /// elements in the output, ``'sum'``: the output will be summed. Default:
+  /// ``'mean'``
+  TORCH_ARG(reduction_t, reduction) = torch::kMean;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::multi_margin_loss`.
+///
+/// See the documentation for `torch::nn::MultiMarginLossOptions` class to learn
+/// what arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::multi_margin_loss(input, target,
+/// F::MultiMarginLossFuncOptions().margin(2).weight(weight));
+/// ```
+using MultiMarginLossFuncOptions = MultiMarginLossOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `CosineEmbeddingLoss` module.
+///
+/// Example:
+/// ```
+/// CosineEmbeddingLoss model(CosineEmbeddingLossOptions().margin(0.5));
+/// ```
+struct TORCH_API CosineEmbeddingLossOptions {
+  typedef std::variant
+      reduction_t;
+
+  /// Specifies the threshold for which the distance of a negative sample must
+  /// reach in order to incur zero loss. Should be a number from -1 to 1, 0
+  /// to 0.5 is suggested. Default: 0.0
+  TORCH_ARG(double, margin) = 0.0;
+  /// Specifies the reduction to apply to the output. Default: Mean
+  TORCH_ARG(reduction_t, reduction) = torch::kMean;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::cosine_embedding_loss`.
+///
+/// See the documentation for `torch::nn::CosineEmbeddingLossOptions` class to
+/// learn what arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::cosine_embedding_loss(input1, input2, target,
+/// F::CosineEmbeddingLossFuncOptions().margin(0.5));
+/// ```
+using CosineEmbeddingLossFuncOptions = CosineEmbeddingLossOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `MultiLabelMarginLoss` module.
+///
+/// Example:
+/// ```
+/// MultiLabelMarginLoss model(MultiLabelMarginLossOptions(torch::kNone));
+/// ```
+struct TORCH_API MultiLabelMarginLossOptions {
+  typedef std::variant
+      reduction_t;
+
+  TORCH_OPTIONS_CTOR_VARIANT_ARG3(
+      MultiLabelMarginLossOptions,
+      reduction,
+      kNone,
+      kMean,
+      kSum)
+
+  /// Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.
+  /// 'none': no reduction will be applied, 'mean': the sum of the output will
+  /// be divided by the number of elements in the output, 'sum': the output will
+  /// be summed. Default: 'mean'
+  TORCH_ARG(reduction_t, reduction) = torch::kMean;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::multilabel_margin_loss`.
+///
+/// See the documentation for `torch::nn::MultiLabelMarginLossOptions` class to
+/// learn what arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::multilabel_margin_loss(input, target,
+/// F::MultilabelMarginLossFuncOptions(torch::kNone));
+/// ```
+using MultilabelMarginLossFuncOptions = MultiLabelMarginLossOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `SoftMarginLoss` module.
+///
+/// Example:
+/// ```
+/// SoftMarginLoss model(SoftMarginLossOptions(torch::kNone));
+/// ```
+struct TORCH_API SoftMarginLossOptions {
+  typedef std::variant
+      reduction_t;
+
+  TORCH_OPTIONS_CTOR_VARIANT_ARG3(
+      SoftMarginLossOptions,
+      reduction,
+      kNone,
+      kMean,
+      kSum)
+
+  /// Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.
+  /// 'none': no reduction will be applied, 'mean': the sum of the output will
+  /// be divided by the number of elements in the output, 'sum': the output will
+  /// be summed. Default: 'mean'
+  TORCH_ARG(reduction_t, reduction) = torch::kMean;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::soft_margin_loss`.
+///
+/// See the documentation for `torch::nn::SoftMarginLossOptions` class to learn
+/// what arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::soft_margin_loss(input, target,
+/// F::SoftMarginLossFuncOptions(torch::kNone));
+/// ```
+using SoftMarginLossFuncOptions = SoftMarginLossOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `MultiLabelSoftMarginLoss` module.
+///
+/// Example:
+/// ```
+/// MultiLabelSoftMarginLoss
+/// model(MultiLabelSoftMarginLossOptions().reduction(torch::kNone).weight(weight));
+/// ```
+struct TORCH_API MultiLabelSoftMarginLossOptions {
+  typedef std::variant
+      reduction_t;
+
+  /// A manual rescaling weight given to each
+  /// class. If given, it has to be a Tensor of size `C`. Otherwise, it is
+  /// treated as if having all ones.
+  TORCH_ARG(Tensor, weight) = Tensor();
+
+  /// Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.
+  /// 'none': no reduction will be applied, 'mean': the sum of the output will
+  /// be divided by the number of elements in the output, 'sum': the output will
+  /// be summed. Default: 'mean'
+  TORCH_ARG(reduction_t, reduction) = torch::kMean;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::multilabel_soft_margin_loss`.
+///
+/// See the documentation for `torch::nn::MultiLabelSoftMarginLossOptions` class
+/// to learn what arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::multilabel_soft_margin_loss(input, target,
+/// F::MultilabelSoftMarginLossFuncOptions().reduction(torch::kNone).weight(weight));
+/// ```
+using MultilabelSoftMarginLossFuncOptions = MultiLabelSoftMarginLossOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `TripletMarginLoss` module.
+///
+/// Example:
+/// ```
+/// TripletMarginLoss
+/// model(TripletMarginLossOptions().margin(3).p(2).eps(1e-06).swap(false));
+/// ```
+struct TORCH_API TripletMarginLossOptions {
+  typedef std::variant
+      reduction_t;
+
+  /// Specifies the threshold for which the distance of a negative sample must
+  /// reach in order to incur zero loss. Default: 1
+  TORCH_ARG(double, margin) = 1.0;
+  /// Specifies the norm degree for pairwise distance. Default: 2
+  TORCH_ARG(double, p) = 2.0;
+  TORCH_ARG(double, eps) = 1e-6;
+  /// The distance swap is described in detail in the paper Learning shallow
+  /// convolutional feature descriptors with triplet losses by V. Balntas,
+  /// E. Riba et al. Default: False
+  TORCH_ARG(bool, swap) = false;
+  /// Specifies the reduction to apply to the output. Default: Mean
+  TORCH_ARG(reduction_t, reduction) = torch::kMean;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::triplet_margin_loss`.
+///
+/// See the documentation for `torch::nn::TripletMarginLossOptions` class to
+/// learn what arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::triplet_margin_loss(anchor, positive, negative,
+/// F::TripletMarginLossFuncOptions().margin(1.0));
+/// ```
+using TripletMarginLossFuncOptions = TripletMarginLossOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `TripletMarginWithDistanceLoss` module.
+///
+/// Example:
+/// ```
+/// TripletMarginWithDistanceLoss
+/// model(TripletMarginWithDistanceLossOptions().margin(3).swap(false));
+/// ```
+struct TORCH_API TripletMarginWithDistanceLossOptions {
+  typedef std::variant
+      reduction_t;
+  typedef std::function
+      distance_function_t;
+
+  /// Specifies a nonnegative, real-valued function that quantifies the
+  /// closeness of two tensors. If not specified, `F::pairwise_distance` will
+  /// be used. Default: nullopt
+  TORCH_ARG(std::optional, distance_function) =
+      std::nullopt;
+  /// Specifies a nonnegative margin representing the minimum difference
+  /// between the positive and negative distances required for the loss to be 0.
+  /// Larger margins penalize cases where the negative examples are not distance
+  /// enough from the anchors, relative to the positives. Default: 1
+  TORCH_ARG(double, margin) = 1.0;
+  /// Whether to use the distance swap described in the paper Learning shallow
+  /// convolutional feature descriptors with triplet losses by V. Balntas,
+  /// E. Riba et al. If True, and if the positive example is closer to the
+  /// negative example than the anchor is, swaps the positive example and the
+  /// anchor in the loss computation. Default: False
+  TORCH_ARG(bool, swap) = false;
+  /// Specifies the reduction to apply to the output. Default: Mean
+  TORCH_ARG(reduction_t, reduction) = torch::kMean;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::triplet_margin_with_distance_loss`.
+///
+/// See the documentation for `torch::nn::TripletMarginWithDistanceLossOptions`
+/// class to learn what arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::triplet_margin_with_distance_loss(anchor, positive, negative,
+/// F::TripletMarginWithDistanceLossFuncOptions().margin(1.0));
+/// ```
+using TripletMarginWithDistanceLossFuncOptions =
+    TripletMarginWithDistanceLossOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `CTCLoss` module.
+///
+/// Example:
+/// ```
+/// CTCLoss
+/// model(CTCLossOptions().blank(42).zero_infinity(false).reduction(torch::kSum));
+/// ```
+struct TORCH_API CTCLossOptions {
+  typedef std::variant
+      reduction_t;
+
+  /// blank label. Default `0`.
+  TORCH_ARG(int64_t, blank) = 0;
+  /// Specifies the reduction to apply to the output. Default: Mean
+  TORCH_ARG(reduction_t, reduction) = torch::kMean;
+  /// Whether to zero infinite losses and the associated gradients.
+  /// Default: `false`. Infinite losses mainly occur when the inputs are
+  /// too short to be aligned to the targets.
+  TORCH_ARG(bool, zero_infinity) = false;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::ctc_loss`.
+///
+/// See the documentation for `torch::nn::CTCLossOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::ctc_loss(log_probs, targets, input_lengths, target_lengths,
+/// F::CTCLossFuncOptions().reduction(torch::kNone));
+/// ```
+using CTCLossFuncOptions = CTCLossOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `SmoothL1Loss` module.
+///
+/// Example:
+/// ```
+/// SmoothL1Loss model(SmoothL1LossOptions().reduction(torch::kNone).beta(0.5));
+/// ```
+struct TORCH_API SmoothL1LossOptions {
+  typedef std::variant
+      reduction_t;
+
+  TORCH_OPTIONS_CTOR_VARIANT_ARG3(
+      SmoothL1LossOptions,
+      reduction,
+      kNone,
+      kMean,
+      kSum)
+
+  /// Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.
+  /// 'none': no reduction will be applied, 'mean': the sum of the output will
+  /// be divided by the number of elements in the output, 'sum': the output will
+  /// be summed. Default: 'mean'
+  TORCH_ARG(reduction_t, reduction) = torch::kMean;
+  /// Specifies the threshold at which to change between L1 and L2 loss.
+  /// If beta is not specified, a value of 1.0 will be used.
+  /// Default: nullopt
+  TORCH_ARG(std::optional, beta) = std::nullopt;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::smooth_l1_loss`.
+///
+/// See the documentation for `torch::nn::SmoothL1LossOptions` class to learn
+/// what arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::smooth_l1_loss(input, target, F::SmoothL1LossFuncOptions(torch::kNone));
+/// ```
+using SmoothL1LossFuncOptions = SmoothL1LossOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `HuberLoss` module.
+///
+/// Example:
+/// ```
+/// HuberLoss model(HuberLossOptions().reduction(torch::kNone).delta(0.5));
+/// ```
+struct TORCH_API HuberLossOptions {
+  typedef std::variant
+      reduction_t;
+
+  TORCH_OPTIONS_CTOR_VARIANT_ARG3(
+      HuberLossOptions,
+      reduction,
+      kNone,
+      kMean,
+      kSum)
+
+  /// Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.
+  /// 'none': no reduction will be applied, 'mean': the sum of the output will
+  /// be divided by the number of elements in the output, 'sum': the output will
+  /// be summed. Default: 'mean'
+  TORCH_ARG(reduction_t, reduction) = torch::kMean;
+  /// Specifies the threshold at which to change between L1 and L2 loss.
+  /// Default: 1.0
+  TORCH_ARG(double, delta) = 1.0;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::huber_loss`.
+///
+/// See the documentation for `torch::nn::HuberLossOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::huber_loss(input, target, F::HuberLossFuncOptions(torch::kNone));
+/// ```
+using HuberLossFuncOptions = HuberLossOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `PoissonNLLLoss` module.
+///
+/// Example:
+/// ```
+/// PoissonNLLLoss
+/// model(PoissonNLLLossOptions().log_input(false).full(true).eps(0.42).reduction(torch::kSum));
+/// ```
+struct TORCH_API PoissonNLLLossOptions {
+  typedef std::variant
+      reduction_t;
+
+  /// if true the loss is computed as `exp(input) - target * input`,
+  /// if false the loss is `input - target * log(input + eps)`.
+  TORCH_ARG(bool, log_input) = true;
+  /// whether to compute full loss, i.e. to add the Stirling approximation term
+  /// target * log(target) - target + 0.5 * log(2 * pi * target).
+  TORCH_ARG(bool, full) = false;
+  /// Small value to avoid evaluation of `log(0)` when `log_input = false`.
+  /// Default: 1e-8
+  TORCH_ARG(double, eps) = 1e-8;
+  /// Specifies the reduction to apply to the output. Default: Mean
+  TORCH_ARG(reduction_t, reduction) = torch::kMean;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::poisson_nll_loss`.
+///
+/// See the documentation for `torch::nn::PoissonNLLLossOptions` class to learn
+/// what arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::poisson_nll_loss(input, target,
+/// F::PoissonNLLLossFuncOptions().reduction(torch::kNone));
+/// ```
+using PoissonNLLLossFuncOptions = PoissonNLLLossOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `MarginRankingLoss` module.
+///
+/// Example:
+/// ```
+/// MarginRankingLoss
+/// model(MarginRankingLossOptions().margin(0.5).reduction(torch::kSum));
+/// ```
+struct TORCH_API MarginRankingLossOptions {
+  typedef std::variant
+      reduction_t;
+
+  /// Has a default value of `0`.
+  TORCH_ARG(double, margin) = 0;
+  /// Specifies the reduction to apply to the output. Default: Mean
+  TORCH_ARG(reduction_t, reduction) = torch::kMean;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::margin_ranking_loss`.
+///
+/// See the documentation for `torch::nn::MarginRankingLossOptions` class to
+/// learn what arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::margin_ranking_loss(input1, input2, target,
+/// F::MarginRankingLossFuncOptions().margin(0.5).reduction(torch::kSum));
+/// ```
+using MarginRankingLossFuncOptions = MarginRankingLossOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `NLLLoss` module.
+///
+/// Example:
+/// ```
+/// NLLLoss model(NLLLossOptions().ignore_index(-100).reduction(torch::kMean));
+/// ```
+struct TORCH_API NLLLossOptions {
+  typedef std::variant
+      reduction_t;
+
+  /// A manual rescaling weight given to each
+  /// class. If given, it has to be a Tensor of size `C`. Otherwise, it is
+  /// treated as if having all ones.
+  TORCH_ARG(Tensor, weight) = {};
+  /// Specifies a target value that is ignored
+  /// and does not contribute to the input gradient.
+  TORCH_ARG(int64_t, ignore_index) = -100;
+  /// Specifies the reduction to apply to the output. Default: Mean
+  TORCH_ARG(reduction_t, reduction) = torch::kMean;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::nll_loss`.
+///
+/// See the documentation for `torch::nn::NLLLossOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::nll_loss(input, target,
+/// F::NLLLossFuncOptions().ignore_index(-100).reduction(torch::kMean));
+/// ```
+using NLLLossFuncOptions = NLLLossOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `CrossEntropyLoss` module.
+///
+/// Example:
+/// ```
+/// CrossEntropyLoss
+/// model(CrossEntropyLossOptions().ignore_index(-100).reduction(torch::kMean));
+/// ```
+struct TORCH_API CrossEntropyLossOptions {
+  typedef std::variant
+      reduction_t;
+
+  /// A manual rescaling weight given to each class. If given, has to be a
+  /// Tensor of size C
+  TORCH_ARG(Tensor, weight) = {};
+  /// Specifies a target value that is ignored
+  /// and does not contribute to the input gradient.
+  TORCH_ARG(int64_t, ignore_index) = -100;
+  /// Specifies the reduction to apply to the output. Default: Mean
+  TORCH_ARG(reduction_t, reduction) = torch::kMean;
+  /// Specifies the amount of smoothing when computing the loss. Default: 0.0
+  TORCH_ARG(double, label_smoothing) = 0.0;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::cross_entropy`.
+///
+/// See the documentation for `torch::nn::CrossEntropyLossOptions` class to
+/// learn what arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::cross_entropy(input, target,
+/// F::CrossEntropyFuncOptions().ignore_index(-100).reduction(torch::kMean));
+/// ```
+using CrossEntropyFuncOptions = CrossEntropyLossOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `BCEWithLogitsLoss` module.
+///
+/// Example:
+/// ```
+/// BCEWithLogitsLoss
+/// model(BCEWithLogitsLossOptions().reduction(torch::kNone).weight(weight));
+/// ```
+struct TORCH_API BCEWithLogitsLossOptions {
+  typedef std::variant
+      reduction_t;
+  /// A manual rescaling weight given to the loss of each batch element.
+  /// If given, has to be a Tensor of size `nbatch`.
+  TORCH_ARG(Tensor, weight) = {};
+  /// Specifies the reduction to apply to the output. Default: Mean
+  TORCH_ARG(reduction_t, reduction) = torch::kMean;
+  /// A weight of positive examples.
+  /// Must be a vector with length equal to the number of classes.
+  TORCH_ARG(Tensor, pos_weight) = {};
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::binary_cross_entropy_with_logits`.
+///
+/// See the documentation for `torch::nn::BCEWithLogitsLossOptions` class to
+/// learn what arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::binary_cross_entropy_with_logits(input, target,
+/// F::BinaryCrossEntropyWithLogitsFuncOptions().pos_weight(pos_weight).reduction(torch::kSum));
+/// ```
+using BinaryCrossEntropyWithLogitsFuncOptions = BCEWithLogitsLossOptions;
+} // namespace functional
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/normalization.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/normalization.h
new file mode 100644
index 0000000000000000000000000000000000000000..4b6dcd6ffe0c27364ae6fc547c8f0e0097f1bfa2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/normalization.h
@@ -0,0 +1,192 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Options for the `LayerNorm` module.
+///
+/// Example:
+/// ```
+/// LayerNorm model(LayerNormOptions({2,
+/// 2}).elementwise_affine(false).eps(2e-5));
+/// ```
+struct TORCH_API LayerNormOptions {
+  /* implicit */ LayerNormOptions(std::vector normalized_shape);
+  /// input shape from an expected input.
+  TORCH_ARG(std::vector, normalized_shape);
+  /// a value added to the denominator for numerical stability. ``Default:
+  /// 1e-5``.
+  TORCH_ARG(double, eps) = 1e-5;
+  /// a boolean value that when set to ``true``, this module
+  /// has learnable per-element affine parameters initialized to ones (for
+  /// weights) and zeros (for biases). ``Default: true``.
+  TORCH_ARG(bool, elementwise_affine) = true;
+};
+
+// ============================================================================
+
+namespace functional {
+
+/// Options for `torch::nn::functional::layer_norm`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::layer_norm(input, F::LayerNormFuncOptions({2, 2}).eps(2e-5));
+/// ```
+struct TORCH_API LayerNormFuncOptions {
+  /* implicit */ LayerNormFuncOptions(std::vector normalized_shape);
+  /// input shape from an expected input.
+  TORCH_ARG(std::vector, normalized_shape);
+
+  TORCH_ARG(Tensor, weight) = {};
+
+  TORCH_ARG(Tensor, bias) = {};
+
+  /// a value added to the denominator for numerical stability. ``Default:
+  /// 1e-5``.
+  TORCH_ARG(double, eps) = 1e-5;
+};
+
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `LocalResponseNorm` module.
+///
+/// Example:
+/// ```
+/// LocalResponseNorm
+/// model(LocalResponseNormOptions(2).alpha(0.0002).beta(0.85).k(2.));
+/// ```
+struct TORCH_API LocalResponseNormOptions {
+  /* implicit */ LocalResponseNormOptions(int64_t size) : size_(size) {}
+  /// amount of neighbouring channels used for normalization
+  TORCH_ARG(int64_t, size);
+
+  /// multiplicative factor. Default: 1e-4
+  TORCH_ARG(double, alpha) = 1e-4;
+
+  /// exponent. Default: 0.75
+  TORCH_ARG(double, beta) = 0.75;
+
+  /// additive factor. Default: 1
+  TORCH_ARG(double, k) = 1.;
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::local_response_norm`.
+///
+/// See the documentation for `torch::nn::LocalResponseNormOptions` class to
+/// learn what arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::local_response_norm(x, F::LocalResponseNormFuncOptions(2));
+/// ```
+using LocalResponseNormFuncOptions = LocalResponseNormOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `CrossMapLRN2d` module.
+///
+/// Example:
+/// ```
+/// CrossMapLRN2d model(CrossMapLRN2dOptions(3).alpha(1e-5).beta(0.1).k(10));
+/// ```
+struct TORCH_API CrossMapLRN2dOptions {
+  CrossMapLRN2dOptions(int64_t size);
+
+  TORCH_ARG(int64_t, size);
+
+  TORCH_ARG(double, alpha) = 1e-4;
+
+  TORCH_ARG(double, beta) = 0.75;
+
+  TORCH_ARG(int64_t, k) = 1;
+};
+
+// ============================================================================
+
+namespace functional {
+
+/// Options for `torch::nn::functional::normalize`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::normalize(input, F::NormalizeFuncOptions().p(1).dim(-1));
+/// ```
+struct TORCH_API NormalizeFuncOptions {
+  /// The exponent value in the norm formulation. Default: 2.0
+  TORCH_ARG(double, p) = 2.0;
+  /// The dimension to reduce. Default: 1
+  TORCH_ARG(int64_t, dim) = 1;
+  /// Small value to avoid division by zero. Default: 1e-12
+  TORCH_ARG(double, eps) = 1e-12;
+  /// the output tensor. If `out` is used, this
+  /// operation won't be differentiable.
+  TORCH_ARG(std::optional, out) = std::nullopt;
+};
+
+} // namespace functional
+
+// ============================================================================
+
+/// Options for the `GroupNorm` module.
+///
+/// Example:
+/// ```
+/// GroupNorm model(GroupNormOptions(2, 2).eps(2e-5).affine(false));
+/// ```
+struct TORCH_API GroupNormOptions {
+  /* implicit */ GroupNormOptions(int64_t num_groups, int64_t num_channels);
+
+  /// number of groups to separate the channels into
+  TORCH_ARG(int64_t, num_groups);
+  /// number of channels expected in input
+  TORCH_ARG(int64_t, num_channels);
+  /// a value added to the denominator for numerical stability. Default: 1e-5
+  TORCH_ARG(double, eps) = 1e-5;
+  /// a boolean value that when set to ``true``, this module
+  /// has learnable per-channel affine parameters initialized to ones (for
+  /// weights) and zeros (for biases). Default: ``true``.
+  TORCH_ARG(bool, affine) = true;
+};
+
+// ============================================================================
+
+namespace functional {
+
+/// Options for `torch::nn::functional::group_norm`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::group_norm(input, F::GroupNormFuncOptions(2).eps(2e-5));
+/// ```
+struct TORCH_API GroupNormFuncOptions {
+  /* implicit */ GroupNormFuncOptions(int64_t num_groups);
+
+  /// number of groups to separate the channels into
+  TORCH_ARG(int64_t, num_groups);
+
+  TORCH_ARG(Tensor, weight) = {};
+
+  TORCH_ARG(Tensor, bias) = {};
+
+  /// a value added to the denominator for numerical stability. Default: 1e-5
+  TORCH_ARG(double, eps) = 1e-5;
+};
+
+} // namespace functional
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/padding.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/padding.h
new file mode 100644
index 0000000000000000000000000000000000000000..8b8312f78ee649bd4127da10dd906790878dbd71
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/padding.h
@@ -0,0 +1,219 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Options for a `D`-dimensional ReflectionPad module.
+template 
+struct TORCH_API ReflectionPadOptions {
+  ReflectionPadOptions(ExpandingArray padding) : padding_(padding) {}
+
+  /// The size of the padding.
+  /// If it is `int`, uses the same padding in all boundaries.
+  /// If it is a 2-`tuple` (for ReflectionPad1d), uses (padding_left,
+  /// padding_right). If it is a 4-`tuple` (for ReflectionPad2d), uses
+  /// (padding_left, padding_right, padding_top, padding_bottom). If it is a
+  /// 6-`tuple` (for ReflectionPad3d), uses (padding_left, padding_right,
+  /// padding_top, padding_bottom, padding_front, padding_back).
+
+  TORCH_ARG(ExpandingArray, padding);
+};
+
+/// `ReflectionPadOptions` specialized for the `ReflectionPad1d` module.
+///
+/// Example:
+/// ```
+/// ReflectionPad1d model(ReflectionPad1dOptions({3, 1}));
+/// ```
+using ReflectionPad1dOptions = ReflectionPadOptions<1>;
+
+/// `ReflectionPadOptions` specialized for the `ReflectionPad2d` module.
+///
+/// Example:
+/// ```
+/// ReflectionPad2d model(ReflectionPad2dOptions({1, 1, 2, 0}));
+/// ```
+using ReflectionPad2dOptions = ReflectionPadOptions<2>;
+
+/// `ReflectionPadOptions` specialized for the `ReflectionPad3d` module.
+///
+/// Example:
+/// ```
+/// ReflectionPad3d model(ReflectionPad3dOptions({1, 1, 2, 0, 1, 1}));
+/// ```
+using ReflectionPad3dOptions = ReflectionPadOptions<3>;
+
+// ============================================================================
+
+/// Options for a `D`-dimensional ReplicationPad module.
+template 
+struct TORCH_API ReplicationPadOptions {
+  ReplicationPadOptions(ExpandingArray padding) : padding_(padding) {}
+
+  /// The size of the padding.
+  /// - If it is `int`, uses the same padding in all boundaries.
+  /// - If it is a 2-`tuple` (for ReplicationPad1d), uses (padding_left,
+  /// padding_right).
+  /// - If it is a 4-`tuple` (for ReplicationPad2d), uses (padding_left,
+  /// padding_right, padding_top, padding_bottom).
+  /// - If it is a 6-`tuple` (for ReplicationPad3d), uses
+  ///   (padding_left, padding_right, padding_top, padding_bottom,
+  ///   padding_front, padding_back).
+  TORCH_ARG(ExpandingArray, padding);
+};
+
+/// `ReplicationPadOptions` specialized for the `ReplicationPad1d` module.
+///
+/// Example:
+/// ```
+/// ReplicationPad1d model(ReplicationPad1dOptions({3, 1}));
+/// ```
+using ReplicationPad1dOptions = ReplicationPadOptions<1>;
+
+/// `ReplicationPadOptions` specialized for the `ReplicationPad2d` module.
+///
+/// Example:
+/// ```
+/// ReplicationPad2d model(ReplicationPad2dOptions({1, 1, 2, 0}));
+/// ```
+using ReplicationPad2dOptions = ReplicationPadOptions<2>;
+
+/// `ReplicationPadOptions` specialized for the `ReplicationPad3d` module.
+///
+/// Example:
+/// ```
+/// ReplicationPad3d model(ReplicationPad3dOptions({1, 2, 1, 2, 1, 2}));
+/// ```
+using ReplicationPad3dOptions = ReplicationPadOptions<3>;
+
+// ============================================================================
+
+template 
+struct TORCH_API ZeroPadOptions {
+  ZeroPadOptions(ExpandingArray padding) : padding_(padding) {}
+
+  /// The size of the padding.
+  /// - If it is `int`, uses the same padding in all boundaries.
+  /// - If it is a 2-`tuple` (for ZeroPad1d), uses (padding_left,
+  /// padding_right).
+  /// - If it is a 4-`tuple` (for ZeroPad2d), uses (padding_left, padding_right,
+  /// padding_top, padding_bottom).
+  /// - If it is a 6-`tuple` (for ZeroPad3d), uses
+  ///   (padding_left, padding_right, padding_top, padding_bottom,
+  ///   padding_front, padding_back).
+  TORCH_ARG(ExpandingArray, padding);
+};
+
+/// `ZeroPadOptions` specialized for the `ZeroPad1d` module.
+///
+/// Example:
+/// ```
+/// ConstantPad1d model(ConstantPad1dOptions({3, 1});
+/// ```
+using ZeroPad1dOptions = ZeroPadOptions<1>;
+
+/// `ZeroPadOptions` specialized for the `ZeroPad2d` module.
+///
+/// Example:
+/// ```
+/// ConstantPad2d model(ConstantPad2dOptions({1, 1, 2, 0});
+/// ```
+using ZeroPad2dOptions = ZeroPadOptions<2>;
+
+/// `ZeroPadOptions` specialized for the `ZeroPad3d` module.
+///
+/// Example:
+/// ```
+/// ConstantPad3d model(ConstantPad3dOptions({1, 2, 1, 2, 1, 2});
+/// ```
+using ZeroPad3dOptions = ZeroPadOptions<3>;
+
+// ============================================================================
+
+/// Options for a `D`-dimensional ConstantPad module.
+template 
+struct TORCH_API ConstantPadOptions {
+  ConstantPadOptions(ExpandingArray padding, double value)
+      : padding_(padding), value_(value) {}
+
+  /// The size of the padding.
+  /// - If it is `int`, uses the same padding in all boundaries.
+  /// - If it is a 2-`tuple` (for ConstantPad1d), uses (padding_left,
+  /// padding_right).
+  /// - If it is a 4-`tuple` (for ConstantPad2d), uses (padding_left,
+  /// padding_right, padding_top, padding_bottom).
+  /// - If it is a 6-`tuple` (for ConstantPad3d), uses
+  ///   (padding_left, padding_right, padding_top, padding_bottom,
+  ///   padding_front, padding_back).
+  TORCH_ARG(ExpandingArray, padding);
+
+  /// Fill value for constant padding.
+  TORCH_ARG(double, value);
+};
+
+/// `ConstantPadOptions` specialized for the `ConstantPad1d` module.
+///
+/// Example:
+/// ```
+/// ConstantPad1d model(ConstantPad1dOptions({3, 1}, 3.5));
+/// ```
+using ConstantPad1dOptions = ConstantPadOptions<1>;
+
+/// `ConstantPadOptions` specialized for the `ConstantPad2d` module.
+///
+/// Example:
+/// ```
+/// ConstantPad2d model(ConstantPad2dOptions({3, 0, 2, 1}, 3.5));
+/// ```
+using ConstantPad2dOptions = ConstantPadOptions<2>;
+
+/// `ConstantPadOptions` specialized for the `ConstantPad3d` module.
+///
+/// Example:
+/// ```
+/// ConstantPad3d model(ConstantPad3dOptions({1, 2, 1, 2, 1, 2}, 3.5));
+/// ```
+using ConstantPad3dOptions = ConstantPadOptions<3>;
+
+// ============================================================================
+
+namespace functional {
+
+/// Options for `torch::nn::functional::pad`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::pad(input, F::PadFuncOptions({1, 2, 2, 1, 1,
+/// 2}).mode(torch::kReplicate));
+/// ```
+struct TORCH_API PadFuncOptions {
+  typedef std::variant<
+      enumtype::kConstant,
+      enumtype::kReflect,
+      enumtype::kReplicate,
+      enumtype::kCircular>
+      mode_t;
+
+  PadFuncOptions(std::vector pad);
+
+  /// m-elements tuple, where m/2 <= input dimensions and m is even.
+  TORCH_ARG(std::vector, pad);
+
+  /// "constant", "reflect", "replicate" or "circular". Default: "constant"
+  TORCH_ARG(mode_t, mode) = torch::kConstant;
+
+  /// fill value for "constant" padding. Default: 0
+  TORCH_ARG(double, value) = 0;
+};
+
+} // namespace functional
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/pixelshuffle.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/pixelshuffle.h
new file mode 100644
index 0000000000000000000000000000000000000000..859da98616db155e1729b2bbc5e37dab5c529a44
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/pixelshuffle.h
@@ -0,0 +1,65 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Options for the `PixelShuffle` module.
+///
+/// Example:
+/// ```
+/// PixelShuffle model(PixelShuffleOptions(5));
+/// ```
+struct TORCH_API PixelShuffleOptions {
+  PixelShuffleOptions(int64_t upscale_factor)
+      : upscale_factor_(upscale_factor) {}
+
+  /// Factor to increase spatial resolution by
+  TORCH_ARG(int64_t, upscale_factor);
+};
+
+/// Options for the `PixelUnshuffle` module.
+///
+/// Example:
+/// ```
+/// PixelUnshuffle model(PixelUnshuffleOptions(5));
+/// ```
+struct TORCH_API PixelUnshuffleOptions {
+  /* implicit */ PixelUnshuffleOptions(int64_t downscale_factor)
+      : downscale_factor_(downscale_factor) {}
+
+  /// Factor to decrease spatial resolution by
+  TORCH_ARG(int64_t, downscale_factor);
+};
+
+namespace functional {
+/// Options for `torch::nn::functional::pixel_shuffle`.
+///
+/// See the documentation for `torch::nn::PixelShuffleOptions` class to learn
+/// what arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::pixel_shuffle(x, F::PixelShuffleFuncOptions(2));
+/// ```
+using PixelShuffleFuncOptions = PixelShuffleOptions;
+
+/// Options for `torch::nn::functional::pixel_unshuffle`.
+///
+/// See the documentation for `torch::nn::PixelUnshuffleOptions` class to learn
+/// what arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::pixel_unshuffle(x, F::PixelUnshuffleFuncOptions(2));
+/// ```
+using PixelUnshuffleFuncOptions = PixelUnshuffleOptions;
+} // namespace functional
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/pooling.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/pooling.h
new file mode 100644
index 0000000000000000000000000000000000000000..75408890e7cd1223bc8a9875eeb65404ff985269
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/pooling.h
@@ -0,0 +1,596 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Options for a `D`-dimensional avgpool module.
+template 
+struct AvgPoolOptions {
+  AvgPoolOptions(ExpandingArray kernel_size)
+      : kernel_size_(kernel_size), stride_(kernel_size) {}
+
+  /// the size of the window to take an average over
+  TORCH_ARG(ExpandingArray, kernel_size);
+
+  /// the stride of the window. Default value is `kernel_size`
+  TORCH_ARG(ExpandingArray, stride);
+
+  /// implicit zero padding to be added on both sides
+  TORCH_ARG(ExpandingArray, padding) = 0;
+
+  /// when True, will use `ceil` instead of `floor` to compute the output shape
+  TORCH_ARG(bool, ceil_mode) = false;
+
+  /// when True, will include the zero-padding in the averaging calculation
+  TORCH_ARG(bool, count_include_pad) = true;
+
+  /// if specified, it will be used as divisor, otherwise size of the pooling
+  /// region will be used.
+
+  TORCH_ARG(std::optional, divisor_override) = std::nullopt;
+};
+
+/// `AvgPoolOptions` specialized for the `AvgPool1d` module.
+///
+/// Example:
+/// ```
+/// AvgPool1d model(AvgPool1dOptions(3).stride(2));
+/// ```
+using AvgPool1dOptions = AvgPoolOptions<1>;
+
+/// `AvgPoolOptions` specialized for the `AvgPool2d` module.
+///
+/// Example:
+/// ```
+/// AvgPool2d model(AvgPool2dOptions({3, 2}).stride({2, 2}));
+/// ```
+using AvgPool2dOptions = AvgPoolOptions<2>;
+
+/// `AvgPoolOptions` specialized for the `AvgPool3d` module.
+///
+/// Example:
+/// ```
+/// AvgPool3d model(AvgPool3dOptions(5).stride(2));
+/// ```
+using AvgPool3dOptions = AvgPoolOptions<3>;
+
+namespace functional {
+/// Options for `torch::nn::functional::avg_pool1d`.
+///
+/// See the documentation for `torch::nn::AvgPool1dOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::avg_pool1d(x, F::AvgPool1dFuncOptions(3).stride(2));
+/// ```
+using AvgPool1dFuncOptions = AvgPool1dOptions;
+} // namespace functional
+
+namespace functional {
+/// Options for `torch::nn::functional::avg_pool2d`.
+///
+/// See the documentation for `torch::nn::AvgPool2dOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::avg_pool2d(x, F::AvgPool2dFuncOptions(3).stride(2));
+/// ```
+using AvgPool2dFuncOptions = AvgPool2dOptions;
+} // namespace functional
+
+namespace functional {
+/// Options for `torch::nn::functional::avg_pool3d`.
+///
+/// See the documentation for `torch::nn::AvgPool3dOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::avg_pool3d(x, F::AvgPool3dFuncOptions(3).stride(2));
+/// ```
+using AvgPool3dFuncOptions = AvgPool3dOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for a `D`-dimensional maxpool module.
+template 
+struct MaxPoolOptions {
+  MaxPoolOptions(ExpandingArray kernel_size)
+      : kernel_size_(kernel_size), stride_(kernel_size) {}
+
+  /// the size of the window to take a max over
+  TORCH_ARG(ExpandingArray, kernel_size);
+
+  /// the stride of the window. Default value is `kernel_size
+  TORCH_ARG(ExpandingArray, stride);
+
+  /// implicit zero padding to be added on both sides
+  TORCH_ARG(ExpandingArray, padding) = 0;
+
+  /// a parameter that controls the stride of elements in the window
+  TORCH_ARG(ExpandingArray, dilation) = 1;
+
+  /// when True, will use `ceil` instead of `floor` to compute the output shape
+  TORCH_ARG(bool, ceil_mode) = false;
+};
+
+/// `MaxPoolOptions` specialized for the `MaxPool1d` module.
+///
+/// Example:
+/// ```
+/// MaxPool1d model(MaxPool1dOptions(3).stride(2));
+/// ```
+using MaxPool1dOptions = MaxPoolOptions<1>;
+
+/// `MaxPoolOptions` specialized for the `MaxPool2d` module.
+///
+/// Example:
+/// ```
+/// MaxPool2d model(MaxPool2dOptions({3, 2}).stride({2, 2}));
+/// ```
+using MaxPool2dOptions = MaxPoolOptions<2>;
+
+/// `MaxPoolOptions` specialized for the `MaxPool3d` module.
+///
+/// Example:
+/// ```
+/// MaxPool3d model(MaxPool3dOptions(3).stride(2));
+/// ```
+using MaxPool3dOptions = MaxPoolOptions<3>;
+
+namespace functional {
+/// Options for `torch::nn::functional::max_pool1d` and
+/// `torch::nn::functional::max_pool1d_with_indices`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::max_pool1d(x, F::MaxPool1dFuncOptions(3).stride(2));
+/// ```
+using MaxPool1dFuncOptions = MaxPool1dOptions;
+} // namespace functional
+
+namespace functional {
+/// Options for `torch::nn::functional::max_pool2d` and
+/// `torch::nn::functional::max_pool2d_with_indices`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::max_pool2d(x, F::MaxPool2dFuncOptions(3).stride(2));
+/// ```
+using MaxPool2dFuncOptions = MaxPool2dOptions;
+} // namespace functional
+
+namespace functional {
+/// Options for `torch::nn::functional::max_pool3d` and
+/// `torch::nn::functional::max_pool3d_with_indices`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::max_pool3d(x, F::MaxPool3dFuncOptions(3).stride(2));
+/// ```
+using MaxPool3dFuncOptions = MaxPool3dOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for a `D`-dimensional adaptive maxpool module.
+template 
+struct AdaptiveMaxPoolOptions {
+  AdaptiveMaxPoolOptions(output_size_t output_size)
+      : output_size_(output_size) {}
+
+  /// the target output size
+  TORCH_ARG(output_size_t, output_size);
+};
+
+/// `AdaptiveMaxPoolOptions` specialized for the `AdaptiveMaxPool1d` module.
+///
+/// Example:
+/// ```
+/// AdaptiveMaxPool1d model(AdaptiveMaxPool1dOptions(3));
+/// ```
+using AdaptiveMaxPool1dOptions = AdaptiveMaxPoolOptions>;
+
+/// `AdaptiveMaxPoolOptions` specialized for the `AdaptiveMaxPool2d` module.
+///
+/// Example:
+/// ```
+/// AdaptiveMaxPool2d model(AdaptiveMaxPool2dOptions({3, 2}));
+/// ```
+using AdaptiveMaxPool2dOptions =
+    AdaptiveMaxPoolOptions>;
+
+/// `AdaptiveMaxPoolOptions` specialized for the `AdaptiveMaxPool3d` module.
+///
+/// Example:
+/// ```
+/// AdaptiveMaxPool3d model(AdaptiveMaxPool3dOptions(3));
+/// ```
+using AdaptiveMaxPool3dOptions =
+    AdaptiveMaxPoolOptions>;
+
+namespace functional {
+/// Options for `torch::nn::functional::adaptive_max_pool1d` and
+/// `torch::nn::functional::adaptive_max_pool1d_with_indices`
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::adaptive_max_pool1d(x, F::AdaptiveMaxPool1dFuncOptions(3));
+/// ```
+using AdaptiveMaxPool1dFuncOptions = AdaptiveMaxPool1dOptions;
+} // namespace functional
+
+namespace functional {
+/// Options for `torch::nn::functional::adaptive_max_pool2d` and
+/// `torch::nn::functional::adaptive_max_pool2d_with_indices`
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::adaptive_max_pool2d(x, F::AdaptiveMaxPool2dFuncOptions(3));
+/// ```
+using AdaptiveMaxPool2dFuncOptions = AdaptiveMaxPool2dOptions;
+} // namespace functional
+
+namespace functional {
+/// Options for `torch::nn::functional::adaptive_max_pool3d` and
+/// `torch::nn::functional::adaptive_max_pool3d_with_indices`
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::adaptive_max_pool3d(x, F::AdaptiveMaxPool3dFuncOptions(3));
+/// ```
+using AdaptiveMaxPool3dFuncOptions = AdaptiveMaxPool3dOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for a `D`-dimensional adaptive avgpool module.
+template 
+struct AdaptiveAvgPoolOptions {
+  AdaptiveAvgPoolOptions(output_size_t output_size)
+      : output_size_(output_size) {}
+
+  /// the target output size
+  TORCH_ARG(output_size_t, output_size);
+};
+
+/// `AdaptiveAvgPoolOptions` specialized for the `AdaptiveAvgPool1d` module.
+///
+/// Example:
+/// ```
+/// AdaptiveAvgPool1d model(AdaptiveAvgPool1dOptions(5));
+/// ```
+using AdaptiveAvgPool1dOptions = AdaptiveAvgPoolOptions>;
+
+/// `AdaptiveAvgPoolOptions` specialized for the `AdaptiveAvgPool2d` module.
+///
+/// Example:
+/// ```
+/// AdaptiveAvgPool2d model(AdaptiveAvgPool2dOptions({3, 2}));
+/// ```
+using AdaptiveAvgPool2dOptions =
+    AdaptiveAvgPoolOptions>;
+
+/// `AdaptiveAvgPoolOptions` specialized for the `AdaptiveAvgPool3d` module.
+///
+/// Example:
+/// ```
+/// AdaptiveAvgPool3d model(AdaptiveAvgPool3dOptions(3));
+/// ```
+using AdaptiveAvgPool3dOptions =
+    AdaptiveAvgPoolOptions>;
+
+namespace functional {
+/// Options for `torch::nn::functional::adaptive_avg_pool1d`.
+///
+/// See the documentation for `torch::nn::AdaptiveAvgPool1dOptions` class to
+/// learn what arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::adaptive_avg_pool1d(x, F::AdaptiveAvgPool1dFuncOptions(3));
+/// ```
+using AdaptiveAvgPool1dFuncOptions = AdaptiveAvgPool1dOptions;
+} // namespace functional
+
+namespace functional {
+/// Options for `torch::nn::functional::adaptive_avg_pool2d`.
+///
+/// See the documentation for `torch::nn::AdaptiveAvgPool2dOptions` class to
+/// learn what arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::adaptive_avg_pool2d(x, F::AdaptiveAvgPool2dFuncOptions(3));
+/// ```
+using AdaptiveAvgPool2dFuncOptions = AdaptiveAvgPool2dOptions;
+} // namespace functional
+
+namespace functional {
+/// Options for `torch::nn::functional::adaptive_avg_pool3d`.
+///
+/// See the documentation for `torch::nn::AdaptiveAvgPool3dOptions` class to
+/// learn what arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::adaptive_avg_pool3d(x, F::AdaptiveAvgPool3dFuncOptions(3));
+/// ```
+using AdaptiveAvgPool3dFuncOptions = AdaptiveAvgPool3dOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for a `D`-dimensional maxunpool module.
+template 
+struct MaxUnpoolOptions {
+  MaxUnpoolOptions(ExpandingArray kernel_size)
+      : kernel_size_(kernel_size), stride_(kernel_size) {}
+
+  /// the size of the window to take a max over
+  TORCH_ARG(ExpandingArray, kernel_size);
+
+  /// the stride of the window. Default value is `kernel_size
+  TORCH_ARG(ExpandingArray, stride);
+
+  /// implicit zero padding to be added on both sides
+  TORCH_ARG(ExpandingArray, padding) = 0;
+};
+
+/// `MaxUnpoolOptions` specialized for the `MaxUnpool1d` module.
+///
+/// Example:
+/// ```
+/// MaxUnpool1d model(MaxUnpool1dOptions(3).stride(2).padding(1));
+/// ```
+using MaxUnpool1dOptions = MaxUnpoolOptions<1>;
+
+/// `MaxUnpoolOptions` specialized for the `MaxUnpool2d` module.
+///
+/// Example:
+/// ```
+/// MaxUnpool2d model(MaxUnpool2dOptions(3).stride(2).padding(1));
+/// ```
+using MaxUnpool2dOptions = MaxUnpoolOptions<2>;
+
+/// `MaxUnpoolOptions` specialized for the `MaxUnpool3d` module.
+///
+/// Example:
+/// ```
+/// MaxUnpool3d model(MaxUnpool3dOptions(3).stride(2).padding(1));
+/// ```
+using MaxUnpool3dOptions = MaxUnpoolOptions<3>;
+
+// ============================================================================
+
+namespace functional {
+
+/// Options for a `D`-dimensional maxunpool functional.
+template 
+struct MaxUnpoolFuncOptions {
+  MaxUnpoolFuncOptions(ExpandingArray kernel_size)
+      : kernel_size_(kernel_size), stride_(kernel_size) {}
+
+  /// the size of the window to take a max over
+  TORCH_ARG(ExpandingArray, kernel_size);
+
+  /// the stride of the window. Default value is `kernel_size
+  TORCH_ARG(ExpandingArray, stride);
+
+  /// implicit zero padding to be added on both sides
+  TORCH_ARG(ExpandingArray, padding) = 0;
+
+  /// the targeted output size
+  TORCH_ARG(std::optional>, output_size) = std::nullopt;
+};
+
+/// `MaxUnpoolFuncOptions` specialized for
+/// `torch::nn::functional::max_unpool1d`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::max_unpool1d(x, indices,
+/// F::MaxUnpool1dFuncOptions(3).stride(2).padding(1));
+/// ```
+using MaxUnpool1dFuncOptions = MaxUnpoolFuncOptions<1>;
+
+/// `MaxUnpoolFuncOptions` specialized for
+/// `torch::nn::functional::max_unpool2d`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::max_unpool2d(x, indices,
+/// F::MaxUnpool2dFuncOptions(3).stride(2).padding(1));
+/// ```
+using MaxUnpool2dFuncOptions = MaxUnpoolFuncOptions<2>;
+
+/// `MaxUnpoolFuncOptions` specialized for
+/// `torch::nn::functional::max_unpool3d`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::max_unpool3d(x, indices, F::MaxUnpool3dFuncOptions(3));
+/// ```
+using MaxUnpool3dFuncOptions = MaxUnpoolFuncOptions<3>;
+
+} // namespace functional
+
+// ============================================================================
+
+/// Options for a `D`-dimensional fractional maxpool module.
+template 
+struct FractionalMaxPoolOptions {
+  FractionalMaxPoolOptions(ExpandingArray kernel_size)
+      : kernel_size_(kernel_size) {}
+
+  /// the size of the window to take a max over
+  TORCH_ARG(ExpandingArray, kernel_size);
+
+  /// the target output size of the image
+  TORCH_ARG(std::optional>, output_size) = std::nullopt;
+
+  /// If one wants to have an output size as a ratio of the input size, this
+  /// option can be given. This has to be a number or tuple in the range (0, 1)
+  using ExpandingArrayDouble = torch::ExpandingArray;
+  TORCH_ARG(std::optional, output_ratio) = std::nullopt;
+
+  TORCH_ARG(torch::Tensor, _random_samples) = Tensor();
+};
+
+/// `FractionalMaxPoolOptions` specialized for the `FractionalMaxPool2d` module.
+///
+/// Example:
+/// ```
+/// FractionalMaxPool2d model(FractionalMaxPool2dOptions(5).output_size(1));
+/// ```
+using FractionalMaxPool2dOptions = FractionalMaxPoolOptions<2>;
+
+/// `FractionalMaxPoolOptions` specialized for the `FractionalMaxPool3d` module.
+///
+/// Example:
+/// ```
+/// FractionalMaxPool3d model(FractionalMaxPool3dOptions(5).output_size(1));
+/// ```
+using FractionalMaxPool3dOptions = FractionalMaxPoolOptions<3>;
+
+namespace functional {
+/// Options for `torch::nn::functional::fractional_max_pool2d` and
+/// `torch::nn::functional::fractional_max_pool2d_with_indices`
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::fractional_max_pool2d(x,
+/// F::FractionalMaxPool2dFuncOptions(3).output_size(2));
+/// ```
+using FractionalMaxPool2dFuncOptions = FractionalMaxPool2dOptions;
+} // namespace functional
+
+namespace functional {
+/// Options for `torch::nn::functional::fractional_max_pool3d` and
+/// `torch::nn::functional::fractional_max_pool3d_with_indices`
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::fractional_max_pool3d(x,
+/// F::FractionalMaxPool3dFuncOptions(3).output_size(2));
+/// ```
+using FractionalMaxPool3dFuncOptions = FractionalMaxPool3dOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for a `D`-dimensional lppool module.
+template 
+struct LPPoolOptions {
+  LPPoolOptions(double norm_type, ExpandingArray kernel_size)
+      : norm_type_(norm_type),
+        kernel_size_(kernel_size),
+        stride_(kernel_size) {}
+
+  TORCH_ARG(double, norm_type);
+
+  // the size of the window to take an average over
+  TORCH_ARG(ExpandingArray, kernel_size);
+
+  // the stride of the window. Default value is `kernel_size`
+  TORCH_ARG(ExpandingArray, stride);
+
+  // when True, will use `ceil` instead of `floor` to compute the output shape
+  TORCH_ARG(bool, ceil_mode) = false;
+};
+
+/// `LPPoolOptions` specialized for the `LPPool1d` module.
+///
+/// Example:
+/// ```
+/// LPPool1d model(LPPool1dOptions(1, 2).stride(5).ceil_mode(true));
+/// ```
+using LPPool1dOptions = LPPoolOptions<1>;
+
+/// `LPPoolOptions` specialized for the `LPPool2d` module.
+///
+/// Example:
+/// ```
+/// LPPool2d model(LPPool2dOptions(1, std::vector({3, 4})).stride({5,
+/// 6}).ceil_mode(true));
+/// ```
+using LPPool2dOptions = LPPoolOptions<2>;
+
+/// `LPPoolOptions` specialized for the `LPPool3d` module.
+///
+/// Example:
+/// ```
+/// LPPool3d model(LPPool3dOptions(1, std::vector({3, 4, 5})).stride(
+/// {5, 6, 7}).ceil_mode(true));
+/// ```
+using LPPool3dOptions = LPPoolOptions<3>;
+
+namespace functional {
+/// Options for `torch::nn::functional::lp_pool1d`.
+///
+/// See the documentation for `torch::nn::LPPool1dOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::lp_pool1d(x, F::LPPool1dFuncOptions(2, 3).stride(2));
+/// ```
+using LPPool1dFuncOptions = LPPool1dOptions;
+} // namespace functional
+
+namespace functional {
+/// Options for `torch::nn::functional::lp_pool2d`.
+///
+/// See the documentation for `torch::nn::LPPool2dOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::lp_pool2d(x, F::LPPool2dFuncOptions(2, {2, 3}).stride(2));
+/// ```
+using LPPool2dFuncOptions = LPPool2dOptions;
+} // namespace functional
+
+namespace functional {
+/// Options for `torch::nn::functional::lp_pool3d`.
+///
+/// See the documentation for `torch::nn::LPPool3dOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::lp_pool3d(x, F::LPPool3dFuncOptions(2, {2, 3, 4}).stride(2));
+/// ```
+using LPPool3dFuncOptions = LPPool3dOptions;
+} // namespace functional
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/rnn.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/rnn.h
new file mode 100644
index 0000000000000000000000000000000000000000..133acc500276d2c0577e863f5bdad4ca6528cc14
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/rnn.h
@@ -0,0 +1,236 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+namespace detail {
+
+/// Common options for RNN, LSTM and GRU modules.
+struct TORCH_API RNNOptionsBase {
+  typedef std::variant<
+      enumtype::kLSTM,
+      enumtype::kGRU,
+      enumtype::kRNN_TANH,
+      enumtype::kRNN_RELU>
+      rnn_options_base_mode_t;
+
+  RNNOptionsBase(
+      rnn_options_base_mode_t mode,
+      int64_t input_size,
+      int64_t hidden_size);
+
+  TORCH_ARG(rnn_options_base_mode_t, mode);
+  /// The number of features of a single sample in the input sequence `x`.
+  TORCH_ARG(int64_t, input_size);
+  /// The number of features in the hidden state `h`.
+  TORCH_ARG(int64_t, hidden_size);
+  /// The number of recurrent layers (cells) to use.
+  TORCH_ARG(int64_t, num_layers) = 1;
+  /// Whether a bias term should be added to all linear operations.
+  TORCH_ARG(bool, bias) = true;
+  /// If true, the input sequence should be provided as `(batch, sequence,
+  /// features)`. If false (default), the expected layout is `(sequence, batch,
+  /// features)`.
+  TORCH_ARG(bool, batch_first) = false;
+  /// If non-zero, adds dropout with the given probability to the output of each
+  /// RNN layer, except the final layer.
+  TORCH_ARG(double, dropout) = 0.0;
+  /// Whether to make the RNN bidirectional.
+  TORCH_ARG(bool, bidirectional) = false;
+  /// Cell projection dimension. If 0, projections are not added. Can only be
+  /// used for LSTMs.
+  TORCH_ARG(int64_t, proj_size) = 0;
+};
+
+} // namespace detail
+
+/// Options for the `RNN` module.
+///
+/// Example:
+/// ```
+/// RNN model(RNNOptions(128,
+/// 64).num_layers(3).dropout(0.2).nonlinearity(torch::kTanh));
+/// ```
+struct TORCH_API RNNOptions {
+  typedef std::variant nonlinearity_t;
+
+  RNNOptions(int64_t input_size, int64_t hidden_size);
+
+  /// The number of expected features in the input `x`
+  TORCH_ARG(int64_t, input_size);
+  /// The number of features in the hidden state `h`
+  TORCH_ARG(int64_t, hidden_size);
+  /// Number of recurrent layers. E.g., setting ``num_layers=2``
+  /// would mean stacking two RNNs together to form a `stacked RNN`,
+  /// with the second RNN taking in outputs of the first RNN and
+  /// computing the final results. Default: 1
+  TORCH_ARG(int64_t, num_layers) = 1;
+  /// The non-linearity to use. Can be either ``torch::kTanh`` or
+  /// ``torch::kReLU``. Default: ``torch::kTanh``
+  TORCH_ARG(nonlinearity_t, nonlinearity) = torch::kTanh;
+  /// If ``false``, then the layer does not use bias weights `b_ih` and `b_hh`.
+  /// Default: ``true``
+  TORCH_ARG(bool, bias) = true;
+  /// If ``true``, then the input and output tensors are provided
+  /// as `(batch, seq, feature)`. Default: ``false``
+  TORCH_ARG(bool, batch_first) = false;
+  /// If non-zero, introduces a `Dropout` layer on the outputs of each
+  /// RNN layer except the last layer, with dropout probability equal to
+  /// `dropout`. Default: 0
+  TORCH_ARG(double, dropout) = 0.0;
+  /// If ``true``, becomes a bidirectional RNN. Default: ``false``
+  TORCH_ARG(bool, bidirectional) = false;
+};
+
+/// Options for the `LSTM` module.
+///
+/// Example:
+/// ```
+/// LSTM model(LSTMOptions(2,
+/// 4).num_layers(3).batch_first(false).bidirectional(true));
+/// ```
+struct TORCH_API LSTMOptions {
+  LSTMOptions(int64_t input_size, int64_t hidden_size);
+
+  /// The number of expected features in the input `x`
+  TORCH_ARG(int64_t, input_size);
+  /// The number of features in the hidden state `h`
+  TORCH_ARG(int64_t, hidden_size);
+  /// Number of recurrent layers. E.g., setting ``num_layers=2``
+  /// would mean stacking two LSTMs together to form a `stacked LSTM`,
+  /// with the second LSTM taking in outputs of the first LSTM and
+  /// computing the final results. Default: 1
+  TORCH_ARG(int64_t, num_layers) = 1;
+  /// If ``false``, then the layer does not use bias weights `b_ih` and `b_hh`.
+  /// Default: ``true``
+  TORCH_ARG(bool, bias) = true;
+  /// If ``true``, then the input and output tensors are provided
+  /// as (batch, seq, feature). Default: ``false``
+  TORCH_ARG(bool, batch_first) = false;
+  /// If non-zero, introduces a `Dropout` layer on the outputs of each
+  /// LSTM layer except the last layer, with dropout probability equal to
+  /// `dropout`. Default: 0
+  TORCH_ARG(double, dropout) = 0.0;
+  /// If ``true``, becomes a bidirectional LSTM. Default: ``false``
+  TORCH_ARG(bool, bidirectional) = false;
+  /// Cell projection dimension. If 0, projections are not added
+  TORCH_ARG(int64_t, proj_size) = 0;
+};
+
+/// Options for the `GRU` module.
+///
+/// Example:
+/// ```
+/// GRU model(GRUOptions(2,
+/// 4).num_layers(3).batch_first(false).bidirectional(true));
+/// ```
+struct TORCH_API GRUOptions {
+  GRUOptions(int64_t input_size, int64_t hidden_size);
+
+  /// The number of expected features in the input `x`
+  TORCH_ARG(int64_t, input_size);
+  /// The number of features in the hidden state `h`
+  TORCH_ARG(int64_t, hidden_size);
+  /// Number of recurrent layers. E.g., setting ``num_layers=2``
+  /// would mean stacking two GRUs together to form a `stacked GRU`,
+  /// with the second GRU taking in outputs of the first GRU and
+  /// computing the final results. Default: 1
+  TORCH_ARG(int64_t, num_layers) = 1;
+  /// If ``false``, then the layer does not use bias weights `b_ih` and `b_hh`.
+  /// Default: ``true``
+  TORCH_ARG(bool, bias) = true;
+  /// If ``true``, then the input and output tensors are provided
+  /// as (batch, seq, feature). Default: ``false``
+  TORCH_ARG(bool, batch_first) = false;
+  /// If non-zero, introduces a `Dropout` layer on the outputs of each
+  /// GRU layer except the last layer, with dropout probability equal to
+  /// `dropout`. Default: 0
+  TORCH_ARG(double, dropout) = 0.0;
+  /// If ``true``, becomes a bidirectional GRU. Default: ``false``
+  TORCH_ARG(bool, bidirectional) = false;
+};
+
+namespace detail {
+
+/// Common options for RNNCell, LSTMCell and GRUCell modules
+struct TORCH_API RNNCellOptionsBase {
+  RNNCellOptionsBase(
+      int64_t input_size,
+      int64_t hidden_size,
+      bool bias,
+      int64_t num_chunks);
+  TORCH_ARG(int64_t, input_size);
+  TORCH_ARG(int64_t, hidden_size);
+  TORCH_ARG(bool, bias);
+  TORCH_ARG(int64_t, num_chunks);
+};
+
+} // namespace detail
+
+/// Options for the `RNNCell` module.
+///
+/// Example:
+/// ```
+/// RNNCell model(RNNCellOptions(20,
+/// 10).bias(false).nonlinearity(torch::kReLU));
+/// ```
+struct TORCH_API RNNCellOptions {
+  typedef std::variant nonlinearity_t;
+
+  RNNCellOptions(int64_t input_size, int64_t hidden_size);
+
+  /// The number of expected features in the input `x`
+  TORCH_ARG(int64_t, input_size);
+  /// The number of features in the hidden state `h`
+  TORCH_ARG(int64_t, hidden_size);
+  /// If ``false``, then the layer does not use bias weights `b_ih` and `b_hh`.
+  /// Default: ``true``
+  TORCH_ARG(bool, bias) = true;
+  /// The non-linearity to use. Can be either ``torch::kTanh`` or
+  /// ``torch::kReLU``. Default: ``torch::kTanh``
+  TORCH_ARG(nonlinearity_t, nonlinearity) = torch::kTanh;
+};
+
+/// Options for the `LSTMCell` module.
+///
+/// Example:
+/// ```
+/// LSTMCell model(LSTMCellOptions(20, 10).bias(false));
+/// ```
+struct TORCH_API LSTMCellOptions {
+  LSTMCellOptions(int64_t input_size, int64_t hidden_size);
+
+  /// The number of expected features in the input `x`
+  TORCH_ARG(int64_t, input_size);
+  /// The number of features in the hidden state `h`
+  TORCH_ARG(int64_t, hidden_size);
+  /// If ``false``, then the layer does not use bias weights `b_ih` and `b_hh`.
+  /// Default: ``true``
+  TORCH_ARG(bool, bias) = true;
+};
+
+/// Options for the `GRUCell` module.
+///
+/// Example:
+/// ```
+/// GRUCell model(GRUCellOptions(20, 10).bias(false));
+/// ```
+struct TORCH_API GRUCellOptions {
+  GRUCellOptions(int64_t input_size, int64_t hidden_size);
+
+  /// The number of expected features in the input `x`
+  TORCH_ARG(int64_t, input_size);
+  /// The number of features in the hidden state `h`
+  TORCH_ARG(int64_t, hidden_size);
+  /// If ``false``, then the layer does not use bias weights `b_ih` and `b_hh`.
+  /// Default: ``true``
+  TORCH_ARG(bool, bias) = true;
+};
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/transformer.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/transformer.h
new file mode 100644
index 0000000000000000000000000000000000000000..41db38fe0757a72081b0125f8747bc0b65c16c85
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/transformer.h
@@ -0,0 +1,64 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Options for the `Transformer` module
+///
+/// Example:
+/// ```
+/// TransformerOptions options;
+/// TransformerOptions options(16, 4);
+/// auto options = TransformerOptions().d_model(4).nhead(2).dropout(0.0);
+/// ```
+struct TORCH_API TransformerOptions {
+  // The following constructors are commonly used
+  // Please don't add more unless it is proved as a common usage
+  TransformerOptions() = default;
+  TransformerOptions(int64_t d_model, int64_t nhead);
+  TransformerOptions(
+      int64_t d_model,
+      int64_t nhead,
+      int64_t num_encoder_layers,
+      int64_t num_decoder_layers);
+
+  /// the number of expected features in the encoder/decoder inputs
+  /// (default=512)
+  TORCH_ARG(int64_t, d_model) = 512;
+
+  /// the number of heads in the multiheadattention models (default=8)
+  TORCH_ARG(int64_t, nhead) = 8;
+
+  /// the number of sub-encoder-layers in the encoder (default=6)
+  TORCH_ARG(int64_t, num_encoder_layers) = 6;
+
+  /// the number of sub-decoder-layers in the decoder (default=6)
+  TORCH_ARG(int64_t, num_decoder_layers) = 6;
+
+  /// the dimension of the feedforward network model (default=2048)
+  TORCH_ARG(int64_t, dim_feedforward) = 2048;
+
+  /// the dropout value (default=0.1)
+  TORCH_ARG(double, dropout) = 0.1;
+
+  /// the activation function of encoder/decoder intermediate layer
+  /// (default=``torch::kReLU``)
+  TORCH_ARG(activation_t, activation) = torch::kReLU;
+
+  /// custom encoder (default=None)
+  TORCH_ARG(AnyModule, custom_encoder);
+
+  /// custom decoder (default=None)
+  TORCH_ARG(AnyModule, custom_decoder);
+};
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/transformercoder.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/transformercoder.h
new file mode 100644
index 0000000000000000000000000000000000000000..64f6b998f4c657d1ca45a0123dbba379effd0979
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/transformercoder.h
@@ -0,0 +1,76 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Options for the `TransformerEncoder`
+///
+/// Example:
+/// ```
+/// TransformerEncoderLayer encoderLayer(TransformerEncoderLayerOptions(512,
+/// 8).dropout(0.1)); auto options = TransformerEncoderOptions(encoderLayer,
+/// 6).norm(LayerNorm(LayerNormOptions({2})));
+/// ```
+struct TORCH_API TransformerEncoderOptions {
+  // This constructor will keep a shallow copy of encoder_layer, so it keeps all
+  // the data in encoder_layer.
+  TransformerEncoderOptions(
+      TransformerEncoderLayer encoder_layer,
+      int64_t num_layers);
+  // This constructor will create a new TransformerEncoderLayer obj based on
+  // passed in encoder_layer_options.
+  TransformerEncoderOptions(
+      const TransformerEncoderLayerOptions& encoder_layer_options,
+      int64_t num_layers);
+
+  /// transformer Encoder Layer
+  TORCH_ARG(TransformerEncoderLayer, encoder_layer) = nullptr;
+
+  /// number of encoder layers
+  TORCH_ARG(int64_t, num_layers);
+
+  /// normalization module
+  TORCH_ARG(AnyModule, norm);
+};
+
+/// Options for the `TransformerDecoder` module.
+///
+/// Example:
+/// ```
+/// TransformerDecoderLayer decoder_layer(TransformerDecoderLayerOptions(512,
+/// 8).dropout(0.1)); auto options = TransformerDecoderOptions(decoder_layer,
+/// 6)norm(LayerNorm(LayerNormOptions({2}))); TransformerDecoder
+/// transformer_decoder(options);
+/// ```
+struct TORCH_API TransformerDecoderOptions {
+  // This constructor will keep the a ref of passed in decoder_layer,
+  // so it keeps all the data in decoder_layer.
+  TransformerDecoderOptions(
+      TransformerDecoderLayer decoder_layer,
+      int64_t num_layers);
+  // This constructor will create a new TransformerDecoderLayer obj,
+  // based on passed in decoder_layer_options.
+  TransformerDecoderOptions(
+      const TransformerDecoderLayerOptions& decoder_layer_options,
+      int64_t num_layers);
+
+  /// decoder layer to be cloned
+  TORCH_ARG(TransformerDecoderLayer, decoder_layer) = nullptr;
+
+  /// number of decoder layers
+  TORCH_ARG(int64_t, num_layers);
+
+  /// normalization module
+  TORCH_ARG(AnyModule, norm);
+};
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/transformerlayer.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/transformerlayer.h
new file mode 100644
index 0000000000000000000000000000000000000000..cbd6af26a1da696ef118caa70b77d9c17a969dfd
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/transformerlayer.h
@@ -0,0 +1,72 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+using activation_t = std::variant<
+    enumtype::kReLU,
+    enumtype::kGELU,
+    std::function>;
+
+/// Options for the `TransformerEncoderLayer`
+///
+/// Example:
+/// ```
+/// auto options = TransformerEncoderLayer(512, 8).dropout(0.2);
+/// ```
+struct TORCH_API TransformerEncoderLayerOptions {
+  /* implicit */ TransformerEncoderLayerOptions(int64_t d_model, int64_t nhead);
+
+  /// the number of expected features in the input
+  TORCH_ARG(int64_t, d_model);
+
+  /// the number of heads in the multiheadattention models
+  TORCH_ARG(int64_t, nhead);
+
+  /// the dimension of the feedforward network model, default is 2048
+  TORCH_ARG(int64_t, dim_feedforward) = 2048;
+
+  /// the dropout value, default is 0.1
+  TORCH_ARG(double, dropout) = 0.1;
+
+  /// the activation function of intermediate layer, can be ``torch::kReLU``,
+  /// ``torch::GELU``, or a unary callable. Default: ``torch::kReLU``
+  TORCH_ARG(activation_t, activation) = torch::kReLU;
+};
+
+// ============================================================================
+
+/// Options for the `TransformerDecoderLayer` module.
+///
+/// Example:
+/// ```
+/// TransformerDecoderLayer model(TransformerDecoderLayerOptions(512,
+/// 8).dropout(0.2));
+/// ```
+struct TORCH_API TransformerDecoderLayerOptions {
+  TransformerDecoderLayerOptions(int64_t d_model, int64_t nhead);
+
+  /// number of expected features in the input
+  TORCH_ARG(int64_t, d_model);
+
+  /// number of heads in the multiheadattention models
+  TORCH_ARG(int64_t, nhead);
+
+  /// dimension of the feedforward network model. Default: 2048
+  TORCH_ARG(int64_t, dim_feedforward) = 2048;
+
+  /// dropout value. Default: 1
+  TORCH_ARG(double, dropout) = 0.1;
+
+  /// activation function of intermediate layer, can be ``torch::kGELU``,
+  /// ``torch::kReLU``, or a unary callable. Default: ``torch::kReLU``
+  TORCH_ARG(activation_t, activation) = torch::kReLU;
+};
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/upsampling.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/upsampling.h
new file mode 100644
index 0000000000000000000000000000000000000000..df8eb194180acc87b2fa2eaff6ab4e2343db0ea6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/upsampling.h
@@ -0,0 +1,110 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+namespace torch {
+namespace nn {
+
+/// Options for the `Upsample` module.
+///
+/// Example:
+/// ```
+/// Upsample
+/// model(UpsampleOptions().scale_factor(std::vector({3})).mode(torch::kLinear).align_corners(false));
+/// ```
+struct TORCH_API UpsampleOptions {
+  /// output spatial sizes.
+  TORCH_ARG(std::optional>, size) = std::nullopt;
+
+  /// multiplier for spatial size.
+  TORCH_ARG(std::optional>, scale_factor) = std::nullopt;
+
+  /// the upsampling algorithm: one of "nearest", "linear", "bilinear",
+  /// "bicubic" and "trilinear". Default: "nearest"
+  typedef std::variant<
+      enumtype::kNearest,
+      enumtype::kLinear,
+      enumtype::kBilinear,
+      enumtype::kBicubic,
+      enumtype::kTrilinear>
+      mode_t;
+  TORCH_ARG(mode_t, mode) = torch::kNearest;
+
+  /// if "True", the corner pixels of the input and output tensors are
+  /// aligned, and thus preserving the values at those pixels. This only has
+  /// effect when :attr:`mode` is "linear", "bilinear", "bicubic", or
+  /// "trilinear". Default: "False"
+  TORCH_ARG(std::optional, align_corners) = std::nullopt;
+};
+
+namespace functional {
+
+/// Options for `torch::nn::functional::interpolate`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::interpolate(input,
+/// F::InterpolateFuncOptions().size(std::vector({4})).mode(torch::kNearest));
+/// ```
+struct TORCH_API InterpolateFuncOptions {
+  typedef std::variant<
+      enumtype::kNearest,
+      enumtype::kLinear,
+      enumtype::kBilinear,
+      enumtype::kBicubic,
+      enumtype::kTrilinear,
+      enumtype::kArea,
+      enumtype::kNearestExact>
+      mode_t;
+
+  /// output spatial sizes.
+  TORCH_ARG(std::optional>, size) = std::nullopt;
+
+  /// multiplier for spatial size.
+  TORCH_ARG(std::optional>, scale_factor) = std::nullopt;
+
+  /// the upsampling algorithm: one of "nearest", "linear", "bilinear",
+  /// "bicubic", "trilinear", "area", "nearest-exact". Default: "nearest"
+  TORCH_ARG(mode_t, mode) = torch::kNearest;
+
+  /// Geometrically, we consider the pixels of the input and output as squares
+  /// rather than points. If set to "True", the input and output tensors are
+  /// aligned by the center points of their corner pixels, preserving the values
+  /// at the corner pixels. If set to "False", the input and output tensors
+  /// are aligned by the corner points of their corner pixels, and the
+  /// interpolation uses edge value padding for out-of-boundary values, making
+  /// this operation *independent* of input size when `scale_factor` is
+  /// kept the same.  It is *required* when interpolating mode is "linear",
+  /// "bilinear", "bicubic" or "trilinear". Default: "False"
+  TORCH_ARG(std::optional, align_corners) = std::nullopt;
+
+  /// recompute the scale_factor for use in the
+  /// interpolation calculation.  When `scale_factor` is passed as a parameter,
+  /// it is used to compute the `output_size`.  If `recompute_scale_factor` is
+  /// `true` or not specified, a new `scale_factor` will be computed based on
+  /// the output and input sizes for use in the interpolation computation (i.e.
+  /// the computation will be identical to if the computed `output_size` were
+  /// passed-in explicitly).  Otherwise, the passed-in `scale_factor` will be
+  /// used in the interpolation computation.  Note that when `scale_factor` is
+  /// floating-point, the recomputed scale_factor may differ from the one passed
+  /// in due to rounding and precision issues.
+  TORCH_ARG(std::optional, recompute_scale_factor) = std::nullopt;
+
+  /// flag to apply anti-aliasing. Using anti-alias
+  /// option together with :attr:`align_corners` equals "False", interpolation
+  /// result would match Pillow result for downsampling operation. Supported
+  /// modes: "bilinear". Default: "False".
+  TORCH_ARG(bool, antialias) = false;
+};
+
+} // namespace functional
+
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/vision.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/vision.h
new file mode 100644
index 0000000000000000000000000000000000000000..a5204f0dffb6241d2a4613d4a84b2ab107ee1e3b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/vision.h
@@ -0,0 +1,36 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+namespace functional {
+
+/// Options for `torch::nn::functional::grid_sample`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::grid_sample(input, grid,
+/// F::GridSampleFuncOptions().mode(torch::kBilinear).padding_mode(torch::kZeros).align_corners(true));
+/// ```
+struct TORCH_API GridSampleFuncOptions {
+  typedef std::variant mode_t;
+  typedef std::
+      variant
+          padding_mode_t;
+
+  /// interpolation mode to calculate output values. Default: Bilinear
+  TORCH_ARG(mode_t, mode) = torch::kBilinear;
+  /// padding mode for outside grid values. Default: Zeros
+  TORCH_ARG(padding_mode_t, padding_mode) = torch::kZeros;
+  /// Specifies perspective to pixel as point. Default: false
+  TORCH_ARG(std::optional, align_corners) = std::nullopt;
+};
+
+} // namespace functional
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/parallel/data_parallel.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/parallel/data_parallel.h
new file mode 100644
index 0000000000000000000000000000000000000000..22f8f678a8e74653f22dc70e6fa1c8ae6bc3b3ee
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/parallel/data_parallel.h
@@ -0,0 +1,297 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+
+namespace {
+
+// Note [Replicating Modules]
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~
+//
+// Module replication is implemented in the following two steps:
+// 1) create a module replica on each destination device using Module.clone().
+// 2) manually add a gradient edge pointing from every parameter X in every
+//    module replica to the same parameter X in the original module, using
+//    ReduceAdd as the grad_fn.
+//
+// ReduceAdd can ONLY be used during the backward pass of data parallel. Forward
+// pass cannot use this function as it does not setup gradient function and
+// history at all. Do NOT try to use ReduceAdd for any other purposes.
+//
+// NB: An alternative is to add Broadcast and ReduceAddCoalesce to
+// torch/csrc/autograd/functions/comm.cpp as normal autograd functions,
+// implement a Replicatable (like cloneable) class and add it as a friend class
+// in Module.h. In the forward pass, the Replicatable could use the Broadcast
+// function to replicate every module parameter and set gradient functions using
+// ReduceAddCoalesce (like how it is implemented in Python). However, unlike in
+// Python, where changes to Linear._parameters["weight"] would also apply to
+// Linear.weight (using Linear as an example), Linear.weight and
+// Linear.parameters_["weight"] are two tensor objects pointing to the same
+// TensorImpl. Assigning a new tensor to Linear.parameters_["weight"] will not
+// change Linear.weight. To make this work, we will have to:
+// 1) force every module to also inherit from Replicatable
+// 2) force every module to implement an additional function, e.g.,
+//    Replicatable::load_params(), to pick up changes from parameters_ to their
+//    own member fields.
+// This will be an overkill as Replicatable will only be used in data_parallel,
+// not even ddp.
+
+// Autograd function for the replicate step in data parallel. This is only used
+// in data parallel, and should not be exposed as a user API.
+struct ReduceAdd : public autograd::Node {
+  explicit ReduceAdd(const at::Device& destination_device)
+      : destination_device_(destination_device){};
+  ~ReduceAdd() override {}
+
+  autograd::variable_list apply(autograd::variable_list&& inputs) override {
+    TORCH_CHECK(
+        !torch::autograd::compute_requires_grad(inputs),
+        "ReduceAdd can only be used during the backward pass of data parallel.");
+
+    Tensor output = torch::zeros_like(inputs[0], {destination_device_});
+
+    for (auto& input : inputs) {
+      TORCH_CHECK(
+          input.sizes() == inputs[0].sizes(),
+          "All inputs of ReduceAdd must have the same size, but got ",
+          input.sizes(),
+          " and ",
+          inputs[0].sizes());
+
+      TORCH_CHECK(
+          input.dtype() == inputs[0].dtype(),
+          "All inputs of ReduceAdd must have the same dtype, but got ",
+          input.dtype(),
+          " and ",
+          inputs[0].dtype());
+
+      // TODO: use nccl reduce
+      output.add_(input.to(destination_device_));
+    }
+
+    return {output};
+  }
+
+ private:
+  at::Device destination_device_;
+};
+
+} // namespace
+
+// A friend function to Module, it recursively sets gradient edges pointing from
+// every parameter X in every module replica to the same parameter X in the
+// original module. See [Replicating Modules]
+template 
+void replicate_grad_edges(
+    const std::shared_ptr& module,
+    const std::vector>& replicas,
+    const std::vector& devices) {
+  for (auto& parameter : module->named_parameters(/*recurse=*/false)) {
+    auto grad_fn = std::make_shared((*parameter).device());
+    grad_fn->set_next_edges(autograd::collect_next_edges(*parameter));
+
+    for (const auto i : c10::irange(devices.size())) {
+      autograd::set_history(replicas[i]->parameters_[parameter.key()], grad_fn);
+    }
+  }
+
+  for (auto& buffer : module->named_buffers(/*recurse=*/false)) {
+    if (buffer.value().requires_grad()) {
+      auto grad_fn = std::make_shared((*buffer).device());
+      grad_fn->set_next_edges(autograd::collect_next_edges(*buffer));
+
+      for (const auto i : c10::irange(devices.size())) {
+        autograd::set_history(replicas[i]->buffers_[buffer.key()], grad_fn);
+      }
+    }
+  }
+
+  for (auto& child : module->children_) {
+    std::vector> child_replicas;
+    child_replicas.reserve(devices.size());
+    for (auto& replica : replicas) {
+      child_replicas.push_back(replica->children_[child.key()]);
+    }
+
+    // recursively set gradient edges for all children
+    replicate_grad_edges(*child, child_replicas, devices);
+  }
+}
+
+namespace parallel {
+
+/// Replicates a module on the given list of devices.
+/// A replica is created by calling `clone()` on the module. For this, the
+/// module must inherit from `nn::Cloneable`, or define its own `clone()`
+/// method, which is expected to perform a deep copy of the module.
+template 
+std::vector> replicate(
+    const std::shared_ptr& module,
+    const std::vector& devices) {
+  std::vector> replicas;
+  replicas.reserve(devices.size());
+  for (const auto& device : devices) {
+    replicas.push_back(
+        std::dynamic_pointer_cast(module->clone(device)));
+  }
+  // Configure gradient edges to point from replcia parameters to original
+  // module parameters. See [Replicating Modules]
+  replicate_grad_edges(module, replicas, devices);
+  return replicas;
+}
+
+/// Replicates a module holder on the given list of devices.
+/// This method allows calling `replicate()` with a module holder, such as
+/// `Linear`.
+template 
+std::vector> replicate(
+    const ModuleHolder& module,
+    const std::vector& devices) {
+  auto ptrs = replicate(module.ptr(), devices);
+  return std::vector>(ptrs.begin(), ptrs.end());
+}
+
+/// Applies the given inputs to the given modules in a parallel fashion.
+/// Conceptually, a thread is spawned for each `(module, input)` pair, in which
+/// `forward()` is called on the module with its corresponding input. The
+/// outputs of the individual calls are stored in a vector and returned.
+///
+/// The first exception caught by any thread is stashed and rethrown after all
+/// threads have completed their operation.
+///
+/// Further remarks:
+/// 1. The length of the module container must match the length of the inputs.
+/// 2. If a list of devices is supplied, it must match the list of modules in
+/// length. Each device will be set to the current default device during the
+/// invocation of the respective module. This means any tensors allocated on the
+/// default device inside the module will be constructed on this device.
+template 
+std::vector parallel_apply(
+    std::vector& modules,
+    const std::vector& inputs,
+    const std::optional>& devices = std::nullopt) {
+  TORCH_CHECK(
+      modules.size() == inputs.size(), "Must have as many inputs as modules");
+  if (devices) {
+    TORCH_CHECK(
+        modules.size() == devices->size(),
+        "Must have as many devices as modules");
+  }
+
+  std::vector outputs(modules.size());
+  std::mutex mutex;
+
+  // std::exception_ptr can be passed between threads:
+  // > An instance of std::exception_ptr may be passed to another function,
+  // > possibly on another thread, where the exception may be rethrown [...].
+  // https://en.cppreference.com/w/cpp/error/exception_ptr
+  std::exception_ptr exception;
+
+  at::parallel_for(
+      /*begin=*/0,
+      /*end=*/modules.size(),
+      /*grain_size=*/1,
+      [&modules, &inputs, &devices, &outputs, &mutex, &exception](
+          int64_t index, int64_t stop) {
+        for (; index < stop; ++index) {
+          try {
+            auto output = modules[index]->forward(inputs[index]);
+            output =
+                output.to(devices ? (*devices)[index] : inputs[index].device());
+            std::lock_guard lock(mutex);
+            outputs[index] = output;
+          } catch (...) {
+            std::lock_guard lock(mutex);
+            if (!exception) {
+              exception = std::current_exception();
+            }
+          }
+        }
+      });
+
+  if (exception) {
+    std::rethrow_exception(exception);
+  }
+
+  return outputs;
+}
+
+/// Evaluates `module(input)` in parallel across the given `devices`. If
+/// `devices` is not supplied, the invocation is parallelized across all
+/// available CUDA devices. If `output_device` is supplied, the final, combined
+/// tensor will be placed on this device. If not, it defaults to the first
+/// device in `devices`.
+///
+/// In detail, this method performs the following four distinct steps:
+/// 1. *Scatter* the input to the given devices,
+/// 2. *Replicate* (deep clone) the model on each device,
+/// 3. *Evaluate* each module with its input on its device,
+/// 4. *Gather* the outputs of each replica into a single output tensor, located
+/// on the `output_device`.
+template 
+Tensor data_parallel(
+    ModuleType module,
+    Tensor input,
+    std::optional> devices = std::nullopt,
+    std::optional output_device = std::nullopt,
+    int64_t dim = 0) {
+  if (!devices) {
+    const auto device_count = torch::cuda::device_count();
+    TORCH_CHECK(
+        device_count > 0, "Expected at least one CUDA device to be available");
+    devices = std::vector();
+    devices->reserve(device_count);
+    for (const auto index : c10::irange(device_count)) {
+      devices->emplace_back(kCUDA, static_cast(index));
+    }
+  }
+  if (!output_device) {
+    output_device = devices->front();
+  }
+
+  if (devices->size() == 1) {
+    module->to(devices->front());
+    input = input.to(devices->front());
+    return module->forward(std::move(input)).to(*output_device);
+  }
+
+  autograd::Scatter scatter(*devices, /*chunk_sizes=*/nullopt, dim);
+  auto scattered_inputs = fmap(scatter.apply({std::move(input)}));
+  // Input tensor might not be big enough to scale across all available devices
+  if (scattered_inputs.size() < devices->size()) {
+    devices->resize(
+        scattered_inputs.size(),
+        Device(DeviceType::COMPILE_TIME_MAX_DEVICE_TYPES));
+  }
+
+  auto replicas = replicate(module, *devices);
+  auto outputs = parallel_apply(replicas, scattered_inputs, *devices);
+  return autograd::Gather(*output_device, dim)
+      .apply(fmap(std::move(outputs)))
+      .front();
+}
+
+} // namespace parallel
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/pimpl-inl.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/pimpl-inl.h
new file mode 100644
index 0000000000000000000000000000000000000000..cea53b6562bd1d1cec21a7d6ed520fd271ae4c50
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/pimpl-inl.h
@@ -0,0 +1,76 @@
+// This class exists  only to do SFINAE on abstract types `T` that are really
+// `ModuleHolder`, because there's no good way to say that `T` is a
+// `ModuleHolder` over some unknown type `ModuleType`. With this, you can do
+// `enable_if_t>`.
+struct ModuleHolderIndicator {};
+
+// A type trait that is true for types that are `ModuleHolder`s.
+template 
+using is_module_holder =
+    std::is_base_of>;
+
+template 
+using disable_if_module_holder_t =
+    std::enable_if_t::value>;
+
+// A collection of templates that answer the question whether a type `T` is a
+// `ModuleHolder`, and if so whether its contained type is of type `C`. This is
+// tricky because it is hard to short circuit in template metaprogramming. A
+// naive and incorrect solution to this problem would be something like
+// `disable_if::value && typename T::ContainedType == C>`.
+// This would disable all types that are not `ModuleHolder`s, because even
+// though the `is_module_holder::value` may be `false` for such types the
+// `T::ContainedType` access would be ill-formed and thus fail the whole
+// expression by the rules of SFINAE. Instead we have to use template
+// specialization to statically branch on the first condition
+// (`is_module_holder`) and are only then allowed to query
+// `T::ContainedType` in the branch for which the condition was true.
+
+// Base template.
+template 
+struct is_module_holder_of_impl;
+
+// False branch. `T` is not a `ModuleHolder` and thus not a `ModuleHolder` with
+// contained type `C`.
+template 
+struct is_module_holder_of_impl : std::false_type {};
+
+// True branch. `T` is a `ModuleHolder` and thus we can legit access its
+// `ContainedType` and compare it against `C`.
+template 
+struct is_module_holder_of_impl
+    : std::is_same {};
+
+// Helper template.
+template 
+struct is_module_holder_of : is_module_holder_of_impl<
+                                 is_module_holder::value,
+                                 std::decay_t,
+                                 std::decay_t> {};
+
+// A collection of templates that allow deducing the return type of the
+// `forward()` method, but only if a module actually has a `forward()` method,
+// and otherwise deduces to the type `void`.
+
+template 
+struct return_type_of_forward_impl;
+
+template 
+struct return_type_of_forward_impl {
+  using type = decltype(::std::declval().forward(::std::declval()...));
+};
+
+template 
+struct return_type_of_forward_impl {
+  using type = void;
+};
+
+template 
+using return_type_of_forward = return_type_of_forward_impl<
+    torch::detail::has_forward::value,
+    C,
+    Args...>;
+
+template 
+using return_type_of_forward_t =
+    typename return_type_of_forward::type;
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/pimpl.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/pimpl.h
new file mode 100644
index 0000000000000000000000000000000000000000..a5a71a01c833c85c4c2c98ff268fb3c9198accce
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/pimpl.h
@@ -0,0 +1,200 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace detail {
+// Dump all the template metaprogramming in this file.
+#include 
+} // namespace detail
+
+namespace nn {
+
+/// A `ModuleHolder` is essentially a wrapper around `std::shared_ptr` where
+/// `M` is an `nn::Module` subclass, with convenient constructors defined for
+/// the kind of constructions we want to allow for our modules.
+template 
+class ModuleHolder : torch::detail::ModuleHolderIndicator {
+ protected:
+  /// The module pointer this class wraps.
+  /// NOTE: Must be placed at the top of the class so that we can use it with
+  /// trailing return types below.
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  std::shared_ptr impl_;
+
+ public:
+  using ContainedType = Contained;
+
+  /// Default constructs the contained module if if has a default constructor,
+  /// else produces a static error.
+  ///
+  /// NOTE: This uses the behavior of template
+  /// classes in C++ that constructors (or any methods) are only compiled when
+  /// actually used.
+  ModuleHolder() : impl_(default_construct()) {
+    static_assert(
+        std::is_default_constructible::value,
+        "You are trying to default construct a module which has "
+        "no default constructor. Use = nullptr to give it the empty state "
+        "(e.g. `Linear linear = nullptr;` instead of `Linear linear;`).");
+  }
+
+  /// Constructs the `ModuleHolder` with an empty contained value. Access to
+  /// the underlying module is not permitted and will throw an exception, until
+  /// a value is assigned.
+  /* implicit */ ModuleHolder(std::nullptr_t) : impl_(nullptr) {}
+
+  /// Constructs the `ModuleHolder` with a contained module, forwarding all
+  /// arguments to its constructor.
+  template <
+      typename Head,
+      typename... Tail,
+      typename = typename std::enable_if<
+          !(torch::detail::is_module_holder_of::value &&
+            (sizeof...(Tail) == 0))>::type>
+  explicit ModuleHolder(Head&& head, Tail&&... tail)
+      : impl_(new Contained(
+            std::forward(head),
+            std::forward(tail)...)) {}
+
+  /// Constructs the `ModuleHolder` from a pointer to the contained type.
+  /// Example: `Linear(std::make_shared(...))`.
+  /* implicit */ ModuleHolder(std::shared_ptr module)
+      : impl_(std::move(module)) {}
+
+  /// Returns true if the `ModuleHolder` contains a module, or false if it is
+  /// `nullptr`.
+  explicit operator bool() const noexcept {
+    return !is_empty();
+  }
+
+  /// Forwards to the contained module.
+  Contained* operator->() {
+    return get();
+  }
+
+  /// Forwards to the contained module.
+  const Contained* operator->() const {
+    return get();
+  }
+
+  /// Returns a reference to the contained module.
+  Contained& operator*() {
+    return *get();
+  }
+
+  /// Returns a const reference to the contained module.
+  const Contained& operator*() const {
+    return *get();
+  }
+
+  /// Returns a shared pointer to the underlying module.
+  const std::shared_ptr& ptr() const {
+    TORCH_CHECK(!is_empty(), "Accessing empty ModuleHolder");
+    return impl_;
+  }
+
+  /// Returns a pointer to the underlying module.
+  Contained* get() {
+    TORCH_CHECK(!is_empty(), "Accessing empty ModuleHolder");
+    return impl_.get();
+  }
+
+  /// Returns a const pointer to the underlying module.
+  const Contained* get() const {
+    TORCH_CHECK(!is_empty(), "Accessing empty ModuleHolder");
+    return impl_.get();
+  }
+
+  /// Calls the `forward()` method of the contained module.
+  template 
+  auto operator()(Args&&... args)
+      -> torch::detail::return_type_of_forward_t {
+    // This will not compile if the module does not have a `forward()` method
+    // (as expected).
+    // NOTE: `std::forward` is qualified to prevent VS2017 emitting
+    // error C2872: 'std': ambiguous symbol
+    return impl_->forward(::std::forward(args)...);
+  }
+
+  /// Forwards to the subscript operator of the contained module.
+  /// NOTE: std::forward is qualified to prevent VS2017 emitting
+  ///       error C2872: 'std': ambiguous symbol
+  template 
+  decltype(auto) operator[](Arg&& arg) {
+    return (*impl_)[::std::forward(arg)];
+  }
+
+  /// Returns true if the `ModuleHolder` does not contain a module.
+  bool is_empty() const noexcept {
+    return impl_ == nullptr;
+  }
+
+ private:
+  template 
+  std::shared_ptr default_construct() {
+    if constexpr (std::is_default_constructible_v) {
+      return std::make_shared();
+    } else {
+      return nullptr;
+    }
+  }
+};
+
+/// Pretty prints the given `Module` into the `ostream`.
+template 
+std::ostream& operator<<(
+    std::ostream& stream,
+    const nn::ModuleHolder& module) {
+  return stream << *module;
+}
+
+/// Serializes a `ModuleHolder` into an `OutputArchive`.
+template 
+serialize::OutputArchive& operator<<(
+    serialize::OutputArchive& archive,
+    const nn::ModuleHolder& module) {
+  return archive << module.ptr();
+}
+
+/// Deserializes a `ModuleHolder` from an `InputArchive`.
+template 
+serialize::InputArchive& operator>>(
+    serialize::InputArchive& archive,
+    nn::ModuleHolder& module) {
+  return archive >> module.ptr();
+}
+
+} // namespace nn
+} // namespace torch
+
+// Workaround for CUDA 10.2 and below not allowing attribute unused on
+// using declarations.
+#ifdef __CUDACC__
+#define TORCH_UNUSED_EXCEPT_CUDA
+#else
+#define TORCH_UNUSED_EXCEPT_CUDA C10_UNUSED
+#endif
+
+/// Defines a class `Name` which inherits from `nn::ModuleHolder` to provide a
+/// wrapper over a `std::shared_ptr`.
+/// `Impl` is a type alias for `ImplType` which provides a way to call static
+/// method of `ImplType`.
+#define TORCH_MODULE_IMPL(Name, ImplType)                              \
+  class Name : public torch::nn::ModuleHolder { /* NOLINT */ \
+   public:                                                             \
+    using torch::nn::ModuleHolder::ModuleHolder;             \
+    using Impl TORCH_UNUSED_EXCEPT_CUDA = ImplType;                    \
+  }
+
+/// Like `TORCH_MODULE_IMPL`, but defaults the `ImplType` name to `Impl`.
+#define TORCH_MODULE(Name) TORCH_MODULE_IMPL(Name, Name##Impl)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/utils.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/utils.h
new file mode 100644
index 0000000000000000000000000000000000000000..8dbfaf5126e4f3db94174937432ea4b017354ab7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/utils.h
@@ -0,0 +1,5 @@
+#pragma once
+
+#include 
+#include 
+#include 
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/utils/clip_grad.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/utils/clip_grad.h
new file mode 100644
index 0000000000000000000000000000000000000000..8a2a569c03335cf60e3be785a5bebb4c821d237b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/utils/clip_grad.h
@@ -0,0 +1,147 @@
+#pragma once
+
+#include 
+
+#include 
+
+namespace torch {
+namespace nn {
+namespace utils {
+
+// Clips gradient norm of a vector of Tensors.
+// See
+// https://pytorch.org/docs/stable/nn.html?highlight=clip_grad_norm#torch.nn.utils.clip_grad_norm_
+// for more details about this module.
+//
+// Difference with the python version: unlike the python version, even when
+// skipping the finiteness checks (error_if_nonfinite = false), this function
+// will introduce a device <=> CPU synchronization (for devices where that makes
+// sense!) in order to return a CPU-side `double`. This C++ version therefore
+// cannot be run fully asynchronously w.r.t. the device of the gradients.
+inline double clip_grad_norm_(
+    const std::vector& parameters,
+    double max_norm,
+    double norm_type = 2.0,
+    bool error_if_nonfinite = false) {
+  std::vector params_with_grad;
+
+  for (const auto& param : parameters) {
+    auto& grad = param.grad();
+    if (grad.defined()) {
+      params_with_grad.push_back(param);
+    }
+  }
+
+  if (params_with_grad.empty()) {
+    return 0.0;
+  }
+
+  Tensor total_norm_tensor;
+  if (norm_type == std::numeric_limits::infinity()) {
+    std::vector norms;
+    norms.reserve(params_with_grad.size());
+
+    for (const auto& param : params_with_grad) {
+      norms.emplace_back(param.grad().data().abs().max());
+    }
+    total_norm_tensor =
+        (norms.size() == 1) ? norms[0] : torch::max(torch::stack(norms));
+  } else if (norm_type == 0) {
+    total_norm_tensor =
+        torch::full({}, static_cast(params_with_grad.size()));
+  } else {
+    std::vector norms;
+    norms.reserve(params_with_grad.size());
+
+    for (const auto& param : params_with_grad) {
+      norms.emplace_back(param.grad().data().norm(norm_type));
+    }
+    total_norm_tensor =
+        (norms.size() == 1) ? norms[0] : torch::stack(norms).norm(norm_type);
+  }
+
+  // When possible (ie when skipping the finiteness check), we avoid
+  // synchronizing the CPU and the gradients' device until the very end to
+  // preserve async execution on the device. When checking for finite-ness, this
+  // optional ensures we only sync once.
+  std::optional total_norm = std::nullopt;
+  if (error_if_nonfinite) {
+    total_norm = total_norm_tensor.item().toDouble();
+    TORCH_CHECK(
+        std::isfinite(*total_norm),
+        "The total norm of order ",
+        norm_type,
+        " for gradients from `parameters` ",
+        "is non-finite, so it cannot be clipped. To disable this error and scale ",
+        "the gradients with the non-finite norm anyway, set ",
+        "`error_if_nonfinite=false`");
+  }
+
+  auto clip_coef = max_norm / (total_norm_tensor + 1e-6);
+  auto clip_coef_clamped =
+      torch::clamp(clip_coef, std::nullopt /* min */, 1.0 /* max */);
+  for (auto& param : params_with_grad) {
+    param.grad().data().mul_(clip_coef_clamped);
+  }
+
+  if (!total_norm.has_value()) {
+    total_norm = total_norm_tensor.item().toDouble();
+  }
+  return *total_norm;
+}
+
+// A wrapper around clip_grad_norm_ that allows us to call the function with a
+// braced-init-list of Tensors.
+inline double clip_grad_norm_(
+    std::initializer_list parameters,
+    double max_norm,
+    double norm_type = 2.0,
+    bool error_if_nonfinite = false) {
+  return clip_grad_norm_(
+      std::vector(parameters), max_norm, norm_type, error_if_nonfinite);
+}
+
+// A wrapper around clip_grad_norm_ that allows us to call the function with a
+// single Tensor.
+inline double clip_grad_norm_(
+    Tensor parameter,
+    double max_norm,
+    double norm_type = 2.0,
+    bool error_if_nonfinite = false) {
+  std::vector params = {std::move(parameter)};
+  return clip_grad_norm_(
+      std::move(params), max_norm, norm_type, error_if_nonfinite);
+}
+
+// Clips gradient of an iterable of parameters at specified value.
+// Gradients are modified in-place.
+// See https://pytorch.org/docs/stable/nn.html#clip-grad-value
+// for more details about this module.
+inline void clip_grad_value_(
+    const std::vector& parameters,
+    double clip_value) {
+  for (const auto& param : parameters) {
+    if (param.grad().defined()) {
+      param.grad().data().clamp_(-clip_value, clip_value);
+    }
+  }
+}
+
+// A wrapper around clip_grad_value_ that allows us to call the function with a
+// braced-init-list of Tensors.
+inline void clip_grad_value_(
+    std::initializer_list parameters,
+    double clip_value) {
+  clip_grad_value_(std::vector(parameters), clip_value);
+}
+
+// A wrapper around clip_grad_value_ that allows us to call the function with a
+// single Tensor.
+inline void clip_grad_value_(Tensor parameter, double clip_value) {
+  std::vector params = {std::move(parameter)};
+  clip_grad_value_(std::move(params), clip_value);
+}
+
+} // namespace utils
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/utils/convert_parameters.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/utils/convert_parameters.h
new file mode 100644
index 0000000000000000000000000000000000000000..b8bfee33473f2a4ee6cb4acf45d5940b7f06850d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/utils/convert_parameters.h
@@ -0,0 +1,82 @@
+#pragma once
+
+#include 
+#include 
+
+namespace torch {
+namespace nn {
+namespace utils {
+
+// This helper function is to check if the parameters are located
+// in the same device. Currently, the conversion between model parameters
+// and single vector form is not supported for multiple allocations,
+// e.g. parameters in different GPUs, or mixture of CPU/GPU.
+inline std::optional _check_param_device(
+    const torch::Tensor& param,
+    std::optional old_param_device) {
+  // Meet the first parameter
+  if (old_param_device == std::nullopt) {
+    old_param_device = param.is_cuda() ? param.get_device() : -1;
+  } else {
+    bool warn = false;
+    if (param.is_cuda()) { // Check if in same GPU
+      warn = (param.get_device() != old_param_device.value());
+    } else { // Check if in CPU
+      warn = (old_param_device.value() != -1);
+    }
+    if (warn) {
+      TORCH_CHECK(
+          false,
+          "Found two parameters on different devices, ",
+          "this is currently not supported.");
+    }
+  }
+
+  return old_param_device;
+}
+
+// Convert parameters to one vector
+inline torch::Tensor parameters_to_vector(
+    const std::vector& parameters) {
+  std::optional param_device;
+
+  std::vector vec;
+  vec.reserve(parameters.size());
+
+  for (const torch::Tensor& param : parameters) {
+    // Ensure the parameters are located in the same device
+    param_device = _check_param_device(param, param_device);
+
+    vec.push_back(param.view(-1));
+  }
+
+  return torch::cat(vec);
+}
+
+// Convert one vector to the parameters
+inline void vector_to_parameters(
+    const torch::Tensor& vec,
+    const std::vector& parameters) {
+  // Flag for the device where the parameter is located
+  std::optional param_device;
+
+  // Pointer for slicing the vector for each parameter
+  int64_t pointer = 0;
+  for (const torch::Tensor& param : parameters) {
+    // Ensure the parameters are located in the same device
+    param_device = _check_param_device(param, param_device);
+
+    // The length of the parameter
+    auto num_param = param.numel();
+    // Slice the vector, reshape it, and replace the old data of the parameter
+    param.set_data(
+        vec.slice(0, pointer, pointer + num_param).view_as(param).data());
+
+    // Increment the pointer
+    pointer += num_param;
+  }
+}
+
+} // namespace utils
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/utils/rnn.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/utils/rnn.h
new file mode 100644
index 0000000000000000000000000000000000000000..6f2a68984c80ac9c6355664bd86d624f00cd3203
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/nn/utils/rnn.h
@@ -0,0 +1,354 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+
+namespace torch {
+namespace nn {
+namespace utils {
+namespace rnn {
+
+inline Tensor invert_permutation(const Tensor& permutation) {
+  if (!permutation.defined()) {
+    return torch::Tensor();
+  }
+  Tensor output =
+      torch::empty_like(permutation, torch::MemoryFormat::Contiguous);
+  output.scatter_(
+      0,
+      permutation,
+      torch::arange(0, permutation.numel(), permutation.device()));
+  return output;
+}
+
+/// Holds the data and list of `batch_sizes` of a packed sequence.
+///
+/// All RNN modules accept packed sequences as inputs.
+///
+/// Note:
+///     Instances of this class should never be created manually. They are meant
+///     to be instantiated by functions like `pack_padded_sequence`.
+///
+///     Batch sizes represent the number elements at each sequence step in
+///     the batch, not the varying sequence lengths passed to
+///     `pack_padded_sequence`.  For instance, given data ``abc`` and ``x``
+///     the :class:`PackedSequence` would contain data ``axbc`` with
+///     ``batch_sizes=[2,1,1]``.
+///
+/// Attributes:
+///     data (Tensor): Tensor containing packed sequence
+///     batch_sizes (Tensor): Tensor of integers holding
+///         information about the batch size at each sequence step
+///     sorted_indices (Tensor, optional): Tensor of integers holding how this
+///         :class:`PackedSequence` is constructed from sequences.
+///     unsorted_indices (Tensor, optional): Tensor of integers holding how this
+///         to recover the original sequences with correct order.
+///
+/// .. note::
+///     `data` can be on arbitrary device and of arbitrary dtype.
+///     `sorted_indices` and `unsorted_indices` must be ``torch::kInt64``
+///     tensors on the same device as `data`.
+///
+///     However, `batch_sizes` should always be a CPU ``torch::kInt64`` tensor.
+///
+///     This invariant is maintained throughout `PackedSequence` class,
+///     and all functions that construct a `PackedSequence` in libtorch
+///     (i.e., they only pass in tensors conforming to this constraint).
+class PackedSequence {
+ public:
+  explicit PackedSequence(
+      Tensor data,
+      Tensor batch_sizes,
+      Tensor sorted_indices = {},
+      Tensor unsorted_indices = {}) {
+    // NB: if unsorted_indices is provided, it should be the inverse permutation
+    // to sorted_indices. Don't assert it here because the PackedSequence ctor
+    // should only be used internally.
+    if (!unsorted_indices.defined()) {
+      unsorted_indices = invert_permutation(sorted_indices);
+    }
+    TORCH_CHECK(
+        batch_sizes.device().type() == kCPU,
+        "batch_sizes should always be on CPU. "
+        "Instances of PackedSequence should never be created manually. "
+        "They should be instantiated by functions like pack_sequence "
+        "and pack_padded_sequences in nn::utils::rnn. "
+        "https://pytorch.org/docs/stable/nn.html#torch.nn.utils.rnn.pack_sequence");
+    data_ = std::move(data);
+    batch_sizes_ = std::move(batch_sizes);
+    sorted_indices_ = std::move(sorted_indices);
+    unsorted_indices_ = std::move(unsorted_indices);
+  }
+
+  const Tensor& data() const {
+    return data_;
+  }
+
+  const Tensor& batch_sizes() const {
+    return batch_sizes_;
+  }
+
+  const Tensor& sorted_indices() const {
+    return sorted_indices_;
+  }
+
+  const Tensor& unsorted_indices() const {
+    return unsorted_indices_;
+  }
+
+  PackedSequence pin_memory() const {
+    // Why not convert `batch_sizes`?
+    // See NOTE [ device and dtype of a PackedSequence ]
+    return PackedSequence(
+        data_.pin_memory(),
+        batch_sizes_,
+        sorted_indices_.defined() ? sorted_indices_.pin_memory() : Tensor(),
+        unsorted_indices_.defined() ? unsorted_indices_.pin_memory()
+                                    : Tensor());
+  }
+
+  PackedSequence to(TensorOptions options) const {
+    // Performs dtype and/or device conversion on `data_`.
+    //
+    // If the ``data_`` Tensor already has the correct `torch::Dtype`
+    // and `torch::Device`, then ``self`` is returned.
+    // Otherwise, returns a copy with the desired configuration.
+
+    // Why not convert `batch_sizes`?
+    // See NOTE [ device and dtype of a PackedSequence ]
+    Tensor data = data_.to(options);
+    if (data.is_same(data_)) {
+      return *this;
+    } else {
+      // Does not forward device or dtype args, device is set from data.device()
+      Tensor sorted_indices = sorted_indices_.defined()
+          ? sorted_indices_.to(
+                options.device(data.device()).dtype(sorted_indices_.dtype()))
+          : Tensor();
+      Tensor unsorted_indices = unsorted_indices_.defined()
+          ? unsorted_indices_.to(
+                options.device(data.device()).dtype(unsorted_indices_.dtype()))
+          : Tensor();
+      return PackedSequence(
+          std::move(data),
+          batch_sizes_,
+          std::move(sorted_indices),
+          std::move(unsorted_indices));
+    }
+  }
+
+  PackedSequence cuda() const {
+    return to(kCUDA);
+  }
+
+  PackedSequence cpu() const {
+    return to(kCPU);
+  }
+
+  /// Returns true if `data_` stored on a gpu
+  bool is_cuda() const {
+    return data_.is_cuda();
+  }
+
+  /// Returns true if `data_` stored on in pinned memory
+  bool is_pinned() const {
+    return data_.is_pinned();
+  }
+
+ private:
+  Tensor data_;
+  Tensor batch_sizes_;
+  Tensor sorted_indices_;
+  Tensor unsorted_indices_;
+};
+
+/// Packs a Tensor containing padded sequences of variable length.
+///
+/// `input` can be of size ``T x B x *`` where `T` is the length of the
+/// longest sequence (equal to ``lengths[0]``), ``B`` is the batch size, and
+/// ``*`` is any number of dimensions (including 0). If ``batch_first`` is
+/// ``true``, ``B x T x *`` `input` is expected.
+///
+/// For unsorted sequences, use `enforce_sorted = false`. If `enforce_sorted` is
+/// ``true``, the sequences should be sorted by length in a decreasing order,
+/// i.e.
+/// ``input[:,0]`` should be the longest sequence, and ``input[:,B-1]`` the
+/// shortest one.
+///
+/// Note:
+///     This function accepts any input that has at least two dimensions. You
+///     can apply it to pack the labels, and use the output of the RNN with
+///     them to compute the loss directly. A Tensor can be retrieved from
+///     a `PackedSequence` object by calling its ``.data()`` function.
+///
+/// Arguments:
+///     input (Tensor): padded batch of variable length sequences.
+///     lengths (Tensor): list of sequences lengths of each batch element.
+///     batch_first (bool, optional): if ``true``, the input is expected in ``B
+///     x T x *``
+///         format. Default: ``false``.
+///     enforce_sorted (bool, optional): if ``true``, the input is expected to
+///         contain sequences sorted by length in a decreasing order. If
+///         ``false``, this condition is not checked. Default: ``true``.
+///
+/// Returns:
+///     a `PackedSequence` object
+inline PackedSequence pack_padded_sequence(
+    Tensor input,
+    Tensor lengths,
+    bool batch_first = false,
+    bool enforce_sorted = true) {
+  lengths = lengths.to(kInt64);
+  Tensor sorted_indices;
+  if (enforce_sorted) {
+    sorted_indices = Tensor();
+  } else {
+    std::tie(lengths, sorted_indices) =
+        torch::sort(lengths, /*dim=*/-1, /*descending=*/true);
+    sorted_indices = sorted_indices.to(input.device());
+    int64_t batch_dim = batch_first ? 0 : 1;
+    input = input.index_select(batch_dim, sorted_indices);
+  }
+
+  auto [data, batch_sizes] =
+      torch::_pack_padded_sequence(input, lengths, batch_first);
+  return PackedSequence(
+      std::move(data), std::move(batch_sizes), std::move(sorted_indices), {});
+}
+
+/// Pads a packed batch of variable length sequences.
+///
+/// It is an inverse operation to `pack_padded_sequence`.
+///
+/// The returned Tensor's data will be of size ``T x B x *``, where `T` is the
+/// length of the longest sequence and `B` is the batch size. If ``batch_first``
+/// is true, the data will be transposed into ``B x T x *`` format.
+///
+/// Batch elements will be ordered decreasingly by their length.
+///
+/// Arguments:
+///     sequence (PackedSequence): batch to pad
+///     batch_first (bool, optional): if ``true``, the output will be in ``B x T
+///     x *``
+///         format.
+///     padding_value (double, optional): values for padded elements.
+///     total_length (int64_t, optional): if specified, the output will be
+///     padded to
+///         have length `total_length`. This method will throw error
+///         if `total_length` is less than the max sequence length in
+///         `sequence`.
+///
+/// Returns:
+///     Tuple of Tensor containing the padded sequence, and a Tensor
+///     containing the list of lengths of each sequence in the batch.
+inline std::tuple pad_packed_sequence(
+    PackedSequence sequence,
+    bool batch_first = false,
+    double padding_value = 0.0,
+    std::optional total_length = torch::nullopt) {
+  int64_t max_seq_length = sequence.batch_sizes().size(0);
+  if (total_length.has_value()) {
+    int64_t total_length_val = total_length.value();
+    TORCH_CHECK(
+        total_length_val >= max_seq_length,
+        "Expected total_length to be at least the length "
+        "of the longest sequence in input, but got "
+        "total_length=",
+        total_length_val,
+        " and max sequence length being ",
+        max_seq_length);
+    max_seq_length = total_length_val;
+  }
+  auto [padded_output, lengths] = torch::_pad_packed_sequence(
+      sequence.data(),
+      sequence.batch_sizes(),
+      batch_first,
+      padding_value,
+      max_seq_length);
+  const Tensor& unsorted_indices = sequence.unsorted_indices();
+  if (unsorted_indices.defined()) {
+    int64_t batch_dim = batch_first ? 0 : 1;
+    return std::make_tuple(
+        padded_output.index_select(batch_dim, unsorted_indices),
+        lengths.index({unsorted_indices.cpu()}));
+  }
+  return std::make_tuple(padded_output, lengths);
+}
+
+/// Pad a list of variable length Tensors with ``padding_value``
+///
+/// ``pad_sequence`` stacks a list of Tensors along a new dimension,
+/// and pads them to equal length. For example, if the input is list of
+/// sequences with size ``L x *`` and if batch_first is false, and ``T x B x *``
+/// otherwise.
+///
+/// `B` is batch size. It is equal to the number of elements in ``sequences``.
+/// `T` is length of the longest sequence.
+/// `L` is length of the sequence.
+/// `*` is any number of trailing dimensions, including none.
+///
+/// Note:
+///     This function returns a Tensor of size ``T x B x *`` or ``B x T x *``
+///     where `T` is the length of the longest sequence. This function assumes
+///     trailing dimensions and type of all the Tensors in sequences are same.
+///
+/// Arguments:
+///     sequences (torch::ArrayRef): list of variable length sequences.
+///     batch_first (bool, optional): output will be in ``B x T x *`` if true,
+///     or in
+///         ``T x B x *`` otherwise
+///     padding_value (double, optional): value for padded elements. Default: 0.
+///     padding_side (str, optional): the side to pad the sequences on. Default:
+///         "right".
+///
+/// Returns:
+///     Tensor of size ``T x B x *`` if `batch_first` is ``false``.
+///     Tensor of size ``B x T x *`` otherwise
+inline Tensor pad_sequence(
+    ArrayRef sequences,
+    bool batch_first = false,
+    double padding_value = 0,
+    c10::string_view padding_side = "right") {
+  return at::pad_sequence(sequences, batch_first, padding_value, padding_side);
+}
+
+/// Packs a list of variable length Tensors
+///
+/// ``sequences`` should be a list of Tensors of size ``L x *``, where `L` is
+/// the length of a sequence and `*` is any number of trailing dimensions,
+/// including zero.
+///
+/// For unsorted sequences, use `enforce_sorted = false`. If ``enforce_sorted``
+/// is ``true``, the sequences should be sorted in the order of decreasing
+/// length.
+///
+///
+/// Arguments:
+///     sequences (torch::ArrayRef): A list of sequences of decreasing
+///     length. enforce_sorted (bool, optional): if ``true``, checks that the
+///     input
+///         contains sequences sorted by length in a decreasing order. If
+///         ``false``, this condition is not checked. Default: ``true``.
+///
+/// Returns:
+///     a `PackedSequence` object
+inline PackedSequence pack_sequence(
+    ArrayRef sequences,
+    bool enforce_sorted = true) {
+  Tensor lengths = torch::empty({(int64_t)sequences.size()}, kInt64);
+  for (const auto i : c10::irange(sequences.size())) {
+    lengths[i] = sequences[i].size(0);
+  }
+  return pack_padded_sequence(
+      at::pad_sequence(sequences),
+      std::move(lengths),
+      /*batch_first=*/false,
+      /*enforce_sorted=*/enforce_sorted);
+}
+
+} // namespace rnn
+} // namespace utils
+} // namespace nn
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/adagrad.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/adagrad.h
new file mode 100644
index 0000000000000000000000000000000000000000..4b2ff3c676b3d7b35485ace2b37c1545b6a66381
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/adagrad.h
@@ -0,0 +1,109 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace serialize {
+class OutputArchive;
+class InputArchive;
+} // namespace serialize
+} // namespace torch
+
+namespace torch {
+namespace optim {
+
+struct TORCH_API AdagradOptions
+    : public OptimizerCloneableOptions {
+  AdagradOptions(double lr = 1e-2);
+  TORCH_ARG(double, lr) = 1e-2;
+  TORCH_ARG(double, lr_decay) = 0;
+  TORCH_ARG(double, weight_decay) = 0;
+  TORCH_ARG(double, initial_accumulator_value) = 0;
+  TORCH_ARG(double, eps) = 1e-10;
+
+ public:
+  void serialize(torch::serialize::InputArchive& archive) override;
+  void serialize(torch::serialize::OutputArchive& archive) const override;
+  TORCH_API friend bool operator==(
+      const AdagradOptions& lhs,
+      const AdagradOptions& rhs);
+  double get_lr() const override;
+  void set_lr(const double lr) override;
+};
+
+struct TORCH_API AdagradParamState
+    : public OptimizerCloneableParamState {
+  TORCH_ARG(torch::Tensor, sum);
+  TORCH_ARG(int64_t, step) = 0;
+
+ public:
+  AdagradParamState() = default;
+  AdagradParamState(const AdagradParamState&) = default;
+  AdagradParamState& operator=(const AdagradParamState&) = default;
+  AdagradParamState(AdagradParamState&&) noexcept = default;
+  AdagradParamState& operator=(AdagradParamState&&) noexcept = default;
+  void serialize(torch::serialize::InputArchive& archive) override;
+  void serialize(torch::serialize::OutputArchive& archive) const override;
+  TORCH_API friend bool operator==(
+      const AdagradParamState& lhs,
+      const AdagradParamState& rhs);
+};
+
+class TORCH_API Adagrad : public Optimizer {
+ public:
+  explicit Adagrad(
+      std::vector param_groups,
+      AdagradOptions defaults = {})
+      : Optimizer(
+            std::move(param_groups),
+            std::make_unique(defaults)) {
+    TORCH_CHECK(defaults.lr() >= 0, "Invalid learning rate: ", defaults.lr());
+    TORCH_CHECK(
+        defaults.lr_decay() >= 0,
+        "Invalid lr_decay value: ",
+        defaults.lr_decay());
+    TORCH_CHECK(
+        defaults.weight_decay() >= 0,
+        "Invalid weight_decay value: ",
+        defaults.weight_decay());
+    TORCH_CHECK(
+        defaults.initial_accumulator_value() >= 0,
+        "Invalid initial_accumulator_value value: ",
+        defaults.initial_accumulator_value());
+    TORCH_CHECK(defaults.eps() >= 0, "Invalid epsilon value: ", defaults.eps());
+
+    for (const auto& group : param_groups_) {
+      for (const auto& p : group.params()) {
+        auto state = std::make_unique();
+        state->step(0);
+        state->sum(torch::full_like(
+            p.data(),
+            defaults.initial_accumulator_value(),
+            at::MemoryFormat::Preserve));
+        state_[p.unsafeGetTensorImpl()] = std::move(state);
+      }
+    }
+  }
+
+  explicit Adagrad(std::vector params, AdagradOptions defaults = {})
+      : Adagrad({OptimizerParamGroup(std::move(params))}, defaults) {}
+
+  torch::Tensor step(LossClosure closure = nullptr) override;
+  void save(serialize::OutputArchive& archive) const override;
+  void load(serialize::InputArchive& archive) override;
+
+ private:
+  template 
+  static void serialize(Self& self, Archive& archive) {
+    _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(Adagrad);
+  }
+};
+} // namespace optim
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/adam.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/adam.h
new file mode 100644
index 0000000000000000000000000000000000000000..6e5e02d82c5442e1b007dd65a9240b5f959efe75
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/adam.h
@@ -0,0 +1,92 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace serialize {
+class OutputArchive;
+class InputArchive;
+} // namespace serialize
+} // namespace torch
+
+namespace torch {
+namespace optim {
+
+struct TORCH_API AdamOptions : public OptimizerCloneableOptions {
+  AdamOptions(double lr = 1e-3);
+  TORCH_ARG(double, lr) = 1e-3;
+  typedef std::tuple betas_t;
+  TORCH_ARG(betas_t, betas) = std::make_tuple(0.9, 0.999);
+  TORCH_ARG(double, eps) = 1e-8;
+  TORCH_ARG(double, weight_decay) = 0;
+  TORCH_ARG(bool, amsgrad) = false;
+
+ public:
+  void serialize(torch::serialize::InputArchive& archive) override;
+  void serialize(torch::serialize::OutputArchive& archive) const override;
+  TORCH_API friend bool operator==(
+      const AdamOptions& lhs,
+      const AdamOptions& rhs);
+  double get_lr() const override;
+  void set_lr(const double lr) override;
+};
+
+struct TORCH_API AdamParamState
+    : public OptimizerCloneableParamState {
+  TORCH_ARG(int64_t, step) = 0;
+  TORCH_ARG(torch::Tensor, exp_avg);
+  TORCH_ARG(torch::Tensor, exp_avg_sq);
+  TORCH_ARG(torch::Tensor, max_exp_avg_sq) = {};
+
+ public:
+  void serialize(torch::serialize::InputArchive& archive) override;
+  void serialize(torch::serialize::OutputArchive& archive) const override;
+  TORCH_API friend bool operator==(
+      const AdamParamState& lhs,
+      const AdamParamState& rhs);
+};
+
+class TORCH_API Adam : public Optimizer {
+ public:
+  explicit Adam(
+      std::vector param_groups,
+      AdamOptions defaults = {})
+      : Optimizer(
+            std::move(param_groups),
+            std::make_unique(defaults)) {
+    TORCH_CHECK(defaults.lr() >= 0, "Invalid learning rate: ", defaults.lr());
+    TORCH_CHECK(defaults.eps() >= 0, "Invalid epsilon value: ", defaults.eps());
+    auto betas = defaults.betas();
+    TORCH_CHECK(
+        0 <= std::get<0>(betas) && std::get<0>(betas) < 1.0,
+        "Invalid beta parameter at index 0: ",
+        std::get<0>(betas));
+    TORCH_CHECK(
+        0 <= std::get<1>(betas) && std::get<1>(betas) < 1.0,
+        "Invalid beta parameter at index 1: ",
+        std::get<1>(betas));
+    TORCH_CHECK(
+        defaults.weight_decay() >= 0,
+        "Invalid weight_decay value: ",
+        defaults.weight_decay());
+  }
+  explicit Adam(std::vector params, AdamOptions defaults = {})
+      : Adam({OptimizerParamGroup(std::move(params))}, defaults) {}
+
+  torch::Tensor step(LossClosure closure = nullptr) override;
+  void save(serialize::OutputArchive& archive) const override;
+  void load(serialize::InputArchive& archive) override;
+
+ private:
+  template 
+  static void serialize(Self& self, Archive& archive) {
+    _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(Adam);
+  }
+};
+} // namespace optim
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/adamw.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/adamw.h
new file mode 100644
index 0000000000000000000000000000000000000000..a63d7fc32d455425fbb6967534e72c36ac2830c8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/adamw.h
@@ -0,0 +1,92 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace serialize {
+class OutputArchive;
+class InputArchive;
+} // namespace serialize
+} // namespace torch
+
+namespace torch {
+namespace optim {
+
+struct TORCH_API AdamWOptions : public OptimizerCloneableOptions {
+  AdamWOptions(double lr = 1e-3);
+  TORCH_ARG(double, lr) = 1e-3;
+  typedef std::tuple betas_t;
+  TORCH_ARG(betas_t, betas) = std::make_tuple(0.9, 0.999);
+  TORCH_ARG(double, eps) = 1e-8;
+  TORCH_ARG(double, weight_decay) = 1e-2;
+  TORCH_ARG(bool, amsgrad) = false;
+
+ public:
+  void serialize(torch::serialize::InputArchive& archive) override;
+  void serialize(torch::serialize::OutputArchive& archive) const override;
+  TORCH_API friend bool operator==(
+      const AdamWOptions& lhs,
+      const AdamWOptions& rhs);
+  double get_lr() const override;
+  void set_lr(const double lr) override;
+};
+
+struct TORCH_API AdamWParamState
+    : public OptimizerCloneableParamState {
+  TORCH_ARG(int64_t, step) = 0;
+  TORCH_ARG(torch::Tensor, exp_avg);
+  TORCH_ARG(torch::Tensor, exp_avg_sq);
+  TORCH_ARG(torch::Tensor, max_exp_avg_sq) = {};
+
+ public:
+  void serialize(torch::serialize::InputArchive& archive) override;
+  void serialize(torch::serialize::OutputArchive& archive) const override;
+  TORCH_API friend bool operator==(
+      const AdamWParamState& lhs,
+      const AdamWParamState& rhs);
+};
+
+class TORCH_API AdamW : public Optimizer {
+ public:
+  explicit AdamW(
+      std::vector param_groups,
+      AdamWOptions defaults = {})
+      : Optimizer(
+            std::move(param_groups),
+            std::make_unique(defaults)) {
+    TORCH_CHECK(defaults.lr() >= 0, "Invalid learning rate: ", defaults.lr());
+    TORCH_CHECK(defaults.eps() >= 0, "Invalid epsilon value: ", defaults.eps());
+    auto betas = defaults.betas();
+    TORCH_CHECK(
+        0 <= std::get<0>(betas) && std::get<0>(betas) < 1.0,
+        "Invalid beta parameter at index 0: ",
+        std::get<0>(betas));
+    TORCH_CHECK(
+        0 <= std::get<1>(betas) && std::get<1>(betas) < 1.0,
+        "Invalid beta parameter at index 1: ",
+        std::get<1>(betas));
+    TORCH_CHECK(
+        defaults.weight_decay() >= 0,
+        "Invalid weight_decay value: ",
+        defaults.weight_decay());
+  }
+  explicit AdamW(std::vector params, AdamWOptions defaults = {})
+      : AdamW({OptimizerParamGroup(std::move(params))}, defaults) {}
+
+  torch::Tensor step(LossClosure closure = nullptr) override;
+  void save(serialize::OutputArchive& archive) const override;
+  void load(serialize::InputArchive& archive) override;
+
+ private:
+  template 
+  static void serialize(Self& self, Archive& archive) {
+    _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(AdamW);
+  }
+};
+} // namespace optim
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/lbfgs.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/lbfgs.h
new file mode 100644
index 0000000000000000000000000000000000000000..0832afff5f8f2026bcdca8dab726673ec2710fb1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/lbfgs.h
@@ -0,0 +1,103 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace optim {
+
+struct TORCH_API LBFGSOptions : public OptimizerCloneableOptions {
+  LBFGSOptions(double lr = 1);
+  TORCH_ARG(double, lr) = 1;
+  TORCH_ARG(int64_t, max_iter) = 20;
+  TORCH_ARG(std::optional, max_eval) = std::nullopt;
+  TORCH_ARG(double, tolerance_grad) = 1e-7;
+  TORCH_ARG(double, tolerance_change) = 1e-9;
+  TORCH_ARG(int64_t, history_size) = 100;
+  TORCH_ARG(std::optional, line_search_fn) = std::nullopt;
+
+ public:
+  void serialize(torch::serialize::InputArchive& archive) override;
+  void serialize(torch::serialize::OutputArchive& archive) const override;
+  TORCH_API friend bool operator==(
+      const LBFGSOptions& lhs,
+      const LBFGSOptions& rhs);
+  double get_lr() const override;
+  void set_lr(const double lr) override;
+};
+
+struct TORCH_API LBFGSParamState
+    : public OptimizerCloneableParamState {
+  TORCH_ARG(int64_t, func_evals) = 0;
+  TORCH_ARG(int64_t, n_iter) = 0;
+  TORCH_ARG(double, t) = 0;
+  TORCH_ARG(double, prev_loss) = 0;
+  TORCH_ARG(Tensor, d) = {};
+  TORCH_ARG(Tensor, H_diag) = {};
+  TORCH_ARG(Tensor, prev_flat_grad) = {};
+  TORCH_ARG(std::deque, old_dirs);
+  TORCH_ARG(std::deque, old_stps);
+  TORCH_ARG(std::deque, ro);
+  TORCH_ARG(std::optional>, al) = std::nullopt;
+
+ public:
+  void serialize(torch::serialize::InputArchive& archive) override;
+  void serialize(torch::serialize::OutputArchive& archive) const override;
+  TORCH_API friend bool operator==(
+      const LBFGSParamState& lhs,
+      const LBFGSParamState& rhs);
+};
+
+class TORCH_API LBFGS : public Optimizer {
+ public:
+  explicit LBFGS(
+      std::vector param_groups,
+      LBFGSOptions defaults = {})
+      : Optimizer(
+            std::move(param_groups),
+            std::make_unique(defaults)) {
+    TORCH_CHECK(
+        param_groups_.size() == 1,
+        "LBFGS doesn't support per-parameter options (parameter groups)");
+    if (defaults.max_eval() == std::nullopt) {
+      auto max_eval_val = (defaults.max_iter() * 5) / 4;
+      static_cast(param_groups_[0].options())
+          .max_eval(max_eval_val);
+      static_cast(*defaults_.get()).max_eval(max_eval_val);
+    }
+    _numel_cache = std::nullopt;
+  }
+  explicit LBFGS(std::vector params, LBFGSOptions defaults = {})
+      : LBFGS({OptimizerParamGroup(std::move(params))}, defaults) {}
+
+  Tensor step(LossClosure closure) override;
+  void save(serialize::OutputArchive& archive) const override;
+  void load(serialize::InputArchive& archive) override;
+
+ private:
+  std::optional _numel_cache;
+  int64_t _numel();
+  Tensor _gather_flat_grad();
+  void _add_grad(const double step_size, const Tensor& update);
+  std::tuple _directional_evaluate(
+      const LossClosure& closure,
+      const std::vector& x,
+      double t,
+      const Tensor& d);
+  void _set_param(const std::vector& params_data);
+  std::vector _clone_param();
+
+  template 
+  static void serialize(Self& self, Archive& archive) {
+    _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(LBFGS);
+  }
+};
+} // namespace optim
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/optimizer.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/optimizer.h
new file mode 100644
index 0000000000000000000000000000000000000000..f6599248244a24363b58e786bc7cca6baa3f9672
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/optimizer.h
@@ -0,0 +1,219 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+// Forward declarations confuse Doxygen
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+namespace at {
+class Tensor;
+} // namespace at
+
+namespace torch {
+using at::Tensor;
+namespace serialize {
+class OutputArchive;
+class InputArchive;
+} // namespace serialize
+} // namespace torch
+#endif // DOXYGEN_SHOULD_SKIP_THIS
+
+namespace torch {
+namespace optim {
+
+class TORCH_API OptimizerParamState {
+ public:
+  OptimizerParamState() = default;
+  OptimizerParamState(const OptimizerParamState&) = default;
+  OptimizerParamState& operator=(const OptimizerParamState&) = default;
+  OptimizerParamState(OptimizerParamState&&) noexcept = default;
+  OptimizerParamState& operator=(OptimizerParamState&&) noexcept = default;
+  virtual std::unique_ptr clone() const;
+  virtual void serialize(torch::serialize::InputArchive& archive);
+  virtual void serialize(torch::serialize::OutputArchive& archive) const;
+  virtual ~OptimizerParamState() = default;
+};
+
+template 
+class OptimizerCloneableParamState : public OptimizerParamState {
+  std::unique_ptr clone() const override {
+    return std::make_unique(static_cast(*this));
+  }
+};
+
+class TORCH_API OptimizerOptions {
+ public:
+  OptimizerOptions() = default;
+  OptimizerOptions(const OptimizerOptions&) = default;
+  OptimizerOptions& operator=(const OptimizerOptions&) = default;
+  OptimizerOptions(OptimizerOptions&&) noexcept = default;
+  OptimizerOptions& operator=(OptimizerOptions&&) noexcept = default;
+  virtual std::unique_ptr clone() const;
+  virtual void serialize(torch::serialize::InputArchive& archive);
+  virtual void serialize(torch::serialize::OutputArchive& archive) const;
+  virtual ~OptimizerOptions() = default;
+  virtual double get_lr() const;
+  virtual void set_lr(const double lr);
+};
+
+template 
+class OptimizerCloneableOptions : public OptimizerOptions {
+ private:
+  std::unique_ptr clone() const override {
+    return std::make_unique(static_cast(*this));
+  }
+};
+
+/// Stores parameters in the param_group and stores a pointer to the
+/// OptimizerOptions
+class TORCH_API OptimizerParamGroup {
+ public:
+  // NOTE: In order to store `OptimizerParamGroup` in a `std::vector`, it has to
+  // be copy-constructible.
+  OptimizerParamGroup(const OptimizerParamGroup& param_group)
+      : params_(param_group.params()),
+        options_(
+            param_group.has_options() ? param_group.options().clone()
+                                      : nullptr) {}
+  OptimizerParamGroup(std::vector params)
+      : params_(std::move(params)) {}
+  OptimizerParamGroup(
+      std::vector params,
+      std::unique_ptr options)
+      : params_(std::move(params)), options_(std::move(options)) {}
+
+  OptimizerParamGroup& operator=(const OptimizerParamGroup& param_group) =
+      delete;
+  bool has_options() const;
+  OptimizerOptions& options();
+  const OptimizerOptions& options() const;
+  void set_options(std::unique_ptr options);
+  std::vector& params();
+  const std::vector& params() const;
+
+ protected:
+  std::vector params_;
+  std::unique_ptr options_;
+};
+
+class TORCH_API Optimizer {
+ public:
+  // The copy constructor is deleted, because the user should use the
+  // `state_dict` / `load_state_dict` API to copy an optimizer instead.
+  Optimizer(const Optimizer& optimizer) = delete;
+  Optimizer(Optimizer&& optimizer) = default;
+
+  explicit Optimizer(
+      std::vector param_groups,
+      std::unique_ptr defaults)
+      : defaults_(std::move(defaults)) {
+    for (const auto& param_group : param_groups) {
+      add_param_group(param_group);
+    }
+  }
+
+  /// Constructs the `Optimizer` from a vector of parameters.
+  explicit Optimizer(
+      std::vector parameters,
+      std::unique_ptr defaults)
+      : Optimizer(
+            {OptimizerParamGroup(std::move(parameters))},
+            std::move(defaults)){};
+
+  /// Adds the given param_group to the optimizer's param_group list.
+  void add_param_group(const OptimizerParamGroup& param_group);
+
+  virtual ~Optimizer() = default;
+
+  using LossClosure = std::function;
+  /// A loss function closure, which is expected to return the loss value.
+  virtual Tensor step(LossClosure closure = nullptr) = 0;
+
+  /// Adds the given vector of parameters to the optimizer's parameter list.
+  void add_parameters(const std::vector& parameters);
+
+  /// Zeros out the gradients of all parameters.
+  void zero_grad(bool set_to_none = true);
+
+  /// Provides a const reference to the parameters in the first param_group this
+  /// optimizer holds.
+  const std::vector& parameters() const noexcept;
+
+  /// Provides a reference to the parameters in the first param_group this
+  /// optimizer holds.
+  std::vector& parameters() noexcept;
+
+  /// Returns the number of parameters referenced by the optimizer.
+  size_t size() const noexcept;
+
+  OptimizerOptions& defaults() noexcept;
+
+  const OptimizerOptions& defaults() const noexcept;
+
+  /// Provides a reference to the param_groups this optimizer holds.
+  std::vector& param_groups() noexcept;
+
+  /// Provides a const reference to the param_groups this optimizer holds.
+  const std::vector& param_groups() const noexcept;
+
+  /// Provides a reference to the state this optimizer holds
+  ska::flat_hash_map>&
+  state() noexcept;
+
+  /// Provides a const reference to the state this optimizer holds
+  const ska::flat_hash_map>& state()
+      const noexcept;
+
+  /// Serializes the optimizer state into the given `archive`.
+  virtual void save(serialize::OutputArchive& archive) const;
+
+  /// Deserializes the optimizer state from the given `archive`.
+  virtual void load(serialize::InputArchive& archive);
+
+ protected:
+  std::vector param_groups_;
+  ska::flat_hash_map> state_;
+  std::unique_ptr defaults_;
+};
+
+/* How do we decide whether to serialize undefined tensors or
+  std::nullopt values into the output archive?
+Answer: we strictly follow the behavior of Python API. To be more specific:
+
+For optimizer options:
+a) For undefined tensor: currently no tensor is used as an options argument in
+Python API, so we don't need to worry about it now. b) For std::nullopt value:
+we serialize std::nullopt values into the output archive, to follow the exact
+same behavior as Python API.
+
+For optimizer param state:
+a) For undefined tensor: in param state, undefined tensor in C++ impl is
+equivalent to missing key in Python impl. Since we don't serialize missing keys
+in Python API, we skip undefined tensors when serializing the param state. b)
+For std::nullopt value: in param state, std::nullopt value in C++ impl is
+equivalent to missing key in Python impl. Since we don't serialize missing keys
+in Python API, we skip std::nullopt values when serializing the param state. */
+
+/// Serializes an `Optimizer` into an `OutputArchive`.
+TORCH_API serialize::OutputArchive& operator<<(
+    serialize::OutputArchive& archive,
+    const Optimizer& optimizer);
+
+/// Deserializes a `Tensor` from an `InputArchive`.
+TORCH_API serialize::InputArchive& operator>>(
+    serialize::InputArchive& archive,
+    Optimizer& optimizer);
+
+} // namespace optim
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/rmsprop.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/rmsprop.h
new file mode 100644
index 0000000000000000000000000000000000000000..69a2e27993d5b76165cb268cb0186e632b1e05f1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/rmsprop.h
@@ -0,0 +1,95 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace serialize {
+class OutputArchive;
+class InputArchive;
+} // namespace serialize
+} // namespace torch
+
+namespace torch {
+namespace optim {
+
+struct TORCH_API RMSpropOptions
+    : public OptimizerCloneableOptions {
+  RMSpropOptions(double lr = 1e-2);
+  TORCH_ARG(double, lr) = 1e-2;
+  TORCH_ARG(double, alpha) = 0.99;
+  TORCH_ARG(double, eps) = 1e-8;
+  TORCH_ARG(double, weight_decay) = 0;
+  TORCH_ARG(double, momentum) = 0;
+  TORCH_ARG(bool, centered) = false;
+
+ public:
+  void serialize(torch::serialize::InputArchive& archive) override;
+  void serialize(torch::serialize::OutputArchive& archive) const override;
+  TORCH_API friend bool operator==(
+      const RMSpropOptions& lhs,
+      const RMSpropOptions& rhs);
+  double get_lr() const override;
+  void set_lr(const double lr) override;
+};
+
+struct TORCH_API RMSpropParamState
+    : public OptimizerCloneableParamState {
+  TORCH_ARG(int64_t, step) = 0;
+  TORCH_ARG(torch::Tensor, square_avg);
+  TORCH_ARG(torch::Tensor, momentum_buffer) = {};
+  TORCH_ARG(torch::Tensor, grad_avg) = {};
+
+ public:
+  void serialize(torch::serialize::InputArchive& archive) override;
+  void serialize(torch::serialize::OutputArchive& archive) const override;
+  TORCH_API friend bool operator==(
+      const RMSpropParamState& lhs,
+      const RMSpropParamState& rhs);
+};
+
+class TORCH_API RMSprop : public Optimizer {
+ public:
+  explicit RMSprop(
+      std::vector param_groups,
+      RMSpropOptions defaults = {})
+      : Optimizer(
+            std::move(param_groups),
+            std::make_unique(defaults)) {
+    TORCH_CHECK(defaults.lr() >= 0, "Invalid learning rate: ", defaults.lr());
+    TORCH_CHECK(defaults.eps() >= 0, "Invalid epsilon value: ", defaults.eps());
+    TORCH_CHECK(
+        defaults.momentum() >= 0,
+        "Invalid momentum value: ",
+        defaults.momentum());
+    TORCH_CHECK(
+        defaults.weight_decay() >= 0,
+        "Invalid weight_decay value: ",
+        defaults.weight_decay());
+    TORCH_CHECK(
+        defaults.alpha() >= 0, "Invalid alpha value: ", defaults.alpha());
+  }
+
+  explicit RMSprop(std::vector params, RMSpropOptions defaults = {})
+      : RMSprop({OptimizerParamGroup(std::move(params))}, defaults) {}
+
+  torch::Tensor step(LossClosure closure = nullptr) override;
+  void save(serialize::OutputArchive& archive) const override;
+  void load(serialize::InputArchive& archive) override;
+
+ private:
+  template 
+  static void serialize(Self& self, Archive& archive) {
+    _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(RMSprop);
+  }
+};
+} // namespace optim
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/lr_scheduler.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/lr_scheduler.h
new file mode 100644
index 0000000000000000000000000000000000000000..26d324fbecce166c19e315ab41142b5e9e4cf4de
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/lr_scheduler.h
@@ -0,0 +1,39 @@
+#pragma once
+
+#include 
+
+#include 
+
+namespace torch {
+namespace optim {
+
+class TORCH_API LRScheduler {
+ public:
+  // This class needs to take a reference of an optimizer from outside such that
+  // it can modify its learning rates; due to this the lifetime of said
+  // optimizer must be maintained
+  LRScheduler(torch::optim::Optimizer& optimizer);
+
+  virtual ~LRScheduler() = default;
+
+  void step();
+
+ protected:
+  // A vector of learning rates is calculated and returned from the specific
+  // subclass. A vector is returned with each element being a separate learning
+  // rate for each param group - although the normal use case would be to return
+  // a vector of identical elements.
+  virtual std::vector get_lrs() = 0;
+
+  // Get current learning rates from the optimizer
+  std::vector get_current_lrs() const;
+
+  unsigned step_count_{};
+
+ private:
+  void set_optimizer_lrs(const std::vector& learning_rates);
+
+  torch::optim::Optimizer& optimizer_;
+};
+} // namespace optim
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/reduce_on_plateau_scheduler.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/reduce_on_plateau_scheduler.h
new file mode 100644
index 0000000000000000000000000000000000000000..ae8892ff4fda6b129178f092cef0f9a0892c24c7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/reduce_on_plateau_scheduler.h
@@ -0,0 +1,64 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+
+#include 
+
+#include 
+
+#include 
+
+namespace torch {
+namespace optim {
+
+class TORCH_API ReduceLROnPlateauScheduler {
+ public:
+  enum SchedulerMode { min, max };
+  enum ThresholdMode { rel, abs };
+  ReduceLROnPlateauScheduler(
+      Optimizer& optimizer,
+      SchedulerMode mode = min,
+      float factor = 0.1,
+      int patience = 10,
+      double threshold = 1e-4,
+      ThresholdMode threshold_mode = rel,
+      int cooldown = 0,
+      const std::vector& min_lr = std::vector(),
+      double eps = 1e-8,
+      bool verbose = false);
+
+  virtual ~ReduceLROnPlateauScheduler() = default;
+
+  void step(float metric);
+
+ private:
+  void reset();
+  void reduce_lr(int epoch);
+  bool in_cooldown();
+  bool is_better(float a);
+  void init_is_better(
+      SchedulerMode mode,
+      double threshold,
+      ThresholdMode threshold_mode);
+
+  Optimizer& optimizer;
+  SchedulerMode mode;
+  float mode_worse;
+  float factor;
+  int patience;
+  double threshold;
+  ThresholdMode threshold_mode;
+  int cooldown;
+  int cooldown_counter;
+  std::vector min_lrs;
+  double eps;
+  float best;
+  bool verbose;
+  int last_epoch;
+  int num_bad_epochs;
+};
+} // namespace optim
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/step_lr.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/step_lr.h
new file mode 100644
index 0000000000000000000000000000000000000000..289bb4bd84e54e995bfc6581aa0c76724661c7ca
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/step_lr.h
@@ -0,0 +1,22 @@
+#pragma once
+
+#include 
+
+namespace torch {
+namespace optim {
+
+class TORCH_API StepLR : public LRScheduler {
+ public:
+  StepLR(
+      torch::optim::Optimizer& optimizer,
+      const unsigned step_size,
+      const double gamma = 0.1);
+
+ private:
+  std::vector get_lrs() override;
+
+  const unsigned step_size_;
+  const double gamma_;
+};
+} // namespace optim
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/serialize.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/serialize.h
new file mode 100644
index 0000000000000000000000000000000000000000..7c34450999b6215a40131699d028c55052a83e50
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/serialize.h
@@ -0,0 +1,315 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace optim {
+namespace detail {
+// Utility function to save state
+template 
+void serialize(
+    serialize::OutputArchive& archive,
+    const ska::flat_hash_map>&
+        state) {
+  for (const auto& item : state) {
+    serialize::OutputArchive param_state_archive(archive.compilation_unit());
+    std::string tensorimpl_key =
+        std::to_string(reinterpret_cast(item.first));
+    const DerivedOptimizerParamState& curr_state =
+        static_cast(*(item.second.get()));
+    curr_state.serialize(param_state_archive);
+    archive.write(tensorimpl_key, param_state_archive);
+  }
+}
+
+// Utility function to load state
+template 
+void serialize(
+    serialize::InputArchive& archive,
+    ska::flat_hash_map>& state) {
+  std::vector tensorimpl_keys = archive.keys();
+  for (const std::string& tensorimpl_key : tensorimpl_keys) {
+    serialize::InputArchive param_state_archive;
+    archive.read(tensorimpl_key, param_state_archive);
+    DerivedOptimizerParamState param_state;
+    param_state.serialize(param_state_archive);
+    state[reinterpret_cast(std::stoull(tensorimpl_key))] =
+        std::make_unique(param_state);
+  }
+}
+
+// Utility function to save param_groups
+template 
+void serialize(
+    serialize::OutputArchive& archive,
+    const std::vector& param_groups) {
+  archive.write(
+      "param_groups/size",
+      torch::tensor(static_cast(param_groups.size())));
+  for (const auto i : c10::irange(param_groups.size())) {
+    serialize::OutputArchive param_group_archive(archive.compilation_unit());
+    std::vector params = param_groups[i].params();
+    param_group_archive.write(
+        "params/size", torch::tensor(static_cast(params.size())));
+    for (const auto index : c10::irange(params.size())) {
+      param_group_archive.write(
+          "params/" + std::to_string(index),
+          IValue(std::to_string(
+              reinterpret_cast(params[index].unsafeGetTensorImpl()))));
+    }
+    const DerivedOptimizerParamOptions& param_group_options =
+        static_cast(
+            param_groups[i].options());
+    serialize::OutputArchive param_group_options_archive(
+        param_group_archive.compilation_unit());
+    param_group_options.serialize(param_group_options_archive);
+    param_group_archive.write("options", param_group_options_archive);
+    archive.write("param_groups/" + std::to_string(i), param_group_archive);
+  }
+}
+
+// Utility function to load param_groups
+// We take as input vector of pair of string and unique_ptr to optimizer options
+// so that we can retain the state for each param by using the old tensor impl
+// keys (saved during serialization) and map the new tensor impl keys to the
+// correct state for each param
+template 
+void serialize(
+    serialize::InputArchive& archive,
+    std::vector<
+        std::pair, std::unique_ptr>>&
+        param_groups) {
+  torch::Tensor param_groups_size_tensor;
+  archive.read("param_groups/size", param_groups_size_tensor);
+  const int64_t param_groups_size = param_groups_size_tensor.item();
+  for (const auto i : c10::irange(param_groups_size)) {
+    serialize::InputArchive param_group_archive;
+    archive.read("param_groups/" + std::to_string(i), param_group_archive);
+    torch::Tensor size_tensor;
+    param_group_archive.read("params/size", size_tensor);
+    const int64_t size = size_tensor.item();
+    std::vector params;
+    for (const auto index : c10::irange(size)) {
+      IValue ivalue;
+      param_group_archive.read("params/" + std::to_string(index), ivalue);
+      std::string element = ivalue.toStringRef();
+      params.emplace_back(element);
+    }
+    serialize::InputArchive param_group_options_archive;
+    param_group_archive.read("options", param_group_options_archive);
+    DerivedOptimizerParamOptions param_group_options(0);
+    param_group_options.serialize(param_group_options_archive);
+    param_groups.emplace_back(std::make_pair(
+        params,
+        std::make_unique(param_group_options)));
+  }
+}
+} // namespace detail
+
+// Note: These functions are all called `serialize()` so they can be called
+// inside a template where the archive type is a template type and can thus be
+// passed such that the appropriate overload is selected.
+
+/// Utility function to save a value of `int64_t` type.
+void serialize(
+    serialize::OutputArchive& archive,
+    const std::string& key,
+    const int64_t& value);
+
+/// Utility function to load a value of `int64_t` type.
+void serialize(
+    serialize::InputArchive& archive,
+    const std::string& key,
+    int64_t& value);
+
+/// Utility function to save a vector of step buffers.
+void serialize(
+    serialize::OutputArchive& archive,
+    const std::string& key,
+    const std::vector& steps);
+
+/// Utility function to load a vector of step buffers.
+void serialize(
+    serialize::InputArchive& archive,
+    const std::string& key,
+    std::vector& steps);
+
+// Utility function to save state and param_groups
+template <
+    typename DerivedOptimizerParamState,
+    typename DerivedOptimizerParamOptions>
+void serialize(serialize::OutputArchive& archive, const Optimizer& optimizer) {
+  archive.write("pytorch_version", IValue("1.5.0"));
+  serialize::OutputArchive state_archive(archive.compilation_unit());
+  detail::serialize(
+      state_archive, optimizer.state());
+  archive.write("state", state_archive);
+
+  serialize::OutputArchive param_groups_archive(archive.compilation_unit());
+  detail::serialize(
+      param_groups_archive, optimizer.param_groups());
+  archive.write("param_groups", param_groups_archive);
+}
+
+// Utility function to load state and param_groups and update state
+template <
+    typename DerivedOptimizerParamState,
+    typename DerivedOptimizerParamOptions>
+void serialize(serialize::InputArchive& archive, Optimizer& optimizer) {
+  IValue pytorch_version;
+  archive.read("pytorch_version", pytorch_version);
+  TORCH_INTERNAL_ASSERT(pytorch_version.toStringRef() == "1.5.0");
+  serialize::InputArchive state_archive;
+  archive.read("state", state_archive);
+  ska::flat_hash_map> saved_state;
+  detail::serialize(state_archive, saved_state);
+
+  serialize::InputArchive param_groups_archive;
+  archive.read("param_groups", param_groups_archive);
+  std::vector<
+      std::pair, std::unique_ptr>>
+      saved_param_groups;
+  detail::serialize(
+      param_groups_archive, saved_param_groups);
+
+  // update state and optimizer options
+  TORCH_CHECK(
+      saved_param_groups.size() == optimizer.param_groups().size(),
+      "loaded state dict has a different number of parameter groups");
+  for (const auto i : c10::irange(saved_param_groups.size())) {
+    std::vector param_group_old_keys = saved_param_groups[i].first;
+    std::vector params = optimizer.param_groups()[i].params();
+    TORCH_CHECK(
+        param_group_old_keys.size() == params.size(),
+        "loaded state dict contains a parameter group that has a different size than the optimizer's parameter group");
+
+    for (const auto idx : c10::irange(params.size())) {
+      auto param_group_old_key =
+          reinterpret_cast(std::stoull(param_group_old_keys[idx]));
+      if (saved_state.find(param_group_old_key) != saved_state.end()) {
+        optimizer.state()[params[idx].unsafeGetTensorImpl()] =
+            std::move(saved_state[param_group_old_key]);
+      }
+    }
+
+    auto& saved_options = reinterpret_cast(
+        *saved_param_groups[i].second);
+    auto& current_options = reinterpret_cast(
+        optimizer.param_groups()[i].options());
+    current_options = saved_options;
+  }
+}
+
+/// Utility function to save a vector of buffers.
+template 
+void serialize(
+    serialize::OutputArchive& archive,
+    const std::string& key,
+    const BufferContainer& buffers) {
+  archive.write(
+      key + "/size", torch::tensor(static_cast(buffers.size())));
+  for (const auto index : c10::irange(buffers.size())) {
+    archive.write(
+        key + "/" + std::to_string(index), buffers[index], /*is_buffer=*/true);
+  }
+}
+
+/// Utility function to load a vector of buffers.
+template 
+void serialize(
+    serialize::InputArchive& archive,
+    const std::string& key,
+    BufferContainer& buffers) {
+  buffers.clear();
+  torch::Tensor size_tensor;
+  archive.read(key + "/size", size_tensor);
+  const size_t size = size_tensor.item();
+  for (const auto index : c10::irange(size)) {
+    buffers.emplace_back();
+    archive.read(
+        key + "/" + std::to_string(index), buffers.back(), /*is_buffer=*/true);
+  }
+}
+
+template 
+c10::List deque_to_list(const std::deque& dq) {
+  c10::List list;
+  list.reserve(dq.size());
+  for (const auto& e : dq) {
+    list.emplace_back(e);
+  }
+  return list;
+}
+
+template 
+std::deque list_to_deque(const c10::List& list) {
+  std::deque dq;
+  for (const auto& e : list) {
+    dq.emplace_back(e);
+  }
+  return dq;
+}
+
+#define _TORCH_OPTIM_SERIALIZE(name) \
+  torch::optim::serialize(archive, #name, self.name)
+
+#define _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(OptimizerName)               \
+  torch::optim::serialize( \
+      archive, self)
+
+#define _TORCH_OPTIM_SERIALIZE_TORCH_ARG(name)           \
+  {                                                      \
+    auto ivalue = torch::IValue(name());                 \
+    /* do not serialize if name is an undefined tensor*/ \
+    if (!(ivalue.isTensor() &&                           \
+          ivalue.unsafeToTensorImpl() ==                 \
+              at::UndefinedTensorImpl::singleton())) {   \
+      archive.write(#name, ivalue);                      \
+    }                                                    \
+  }
+
+#define _TORCH_OPTIM_SERIALIZE_TORCH_ARG_DEQUE(name)           \
+  {                                                            \
+    c10::IValue ivalue = torch::IValue(deque_to_list(name())); \
+    archive.write(#name, ivalue);                              \
+  }
+
+#define _TORCH_OPTIM_DESERIALIZE_TORCH_ARG(T, name)                   \
+  {                                                                   \
+    c10::IValue ivalue;                                               \
+    bool exists = archive.try_read(#name, ivalue);                    \
+    if (exists) {                                                     \
+      name(ivalue.to());                                           \
+    } else {                                                          \
+      bool is_tensor_type = std::is_base_of::value; \
+      TORCH_INTERNAL_ASSERT(is_tensor_type);                          \
+    }                                                                 \
+  }
+
+#define _TORCH_OPTIM_DESERIALIZE_TORCH_ARG_OPTIONAL(T, name) \
+  {                                                          \
+    c10::IValue ivalue;                                      \
+    bool exists = archive.try_read(#name, ivalue);           \
+    if (exists) {                                            \
+      name(ivalue.toOptional());                          \
+    }                                                        \
+  }
+
+#define _TORCH_OPTIM_DESERIALIZE_TORCH_ARG_DEQUE(T, name) \
+  {                                                       \
+    c10::IValue ivalue;                                   \
+    archive.read(#name, ivalue);                          \
+    auto list = ivalue.to>();    \
+    name(list_to_deque(list));                            \
+  }
+
+} // namespace optim
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/sgd.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/sgd.h
new file mode 100644
index 0000000000000000000000000000000000000000..85e9aba7ba48f751d0ae00f8356ca8d47d7b0ad2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/optim/sgd.h
@@ -0,0 +1,91 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace serialize {
+class OutputArchive;
+class InputArchive;
+} // namespace serialize
+} // namespace torch
+
+namespace torch {
+namespace optim {
+
+struct TORCH_API SGDOptions : public OptimizerCloneableOptions {
+  SGDOptions(double lr);
+  TORCH_ARG(double, lr);
+  TORCH_ARG(double, momentum) = 0;
+  TORCH_ARG(double, dampening) = 0;
+  TORCH_ARG(double, weight_decay) = 0;
+  TORCH_ARG(bool, nesterov) = false;
+
+ public:
+  void serialize(torch::serialize::InputArchive& archive) override;
+  void serialize(torch::serialize::OutputArchive& archive) const override;
+  TORCH_API friend bool operator==(
+      const SGDOptions& lhs,
+      const SGDOptions& rhs);
+  double get_lr() const override;
+  void set_lr(const double lr) override;
+};
+
+struct TORCH_API SGDParamState
+    : public OptimizerCloneableParamState {
+  TORCH_ARG(torch::Tensor, momentum_buffer);
+
+ public:
+  void serialize(torch::serialize::InputArchive& archive) override;
+  void serialize(torch::serialize::OutputArchive& archive) const override;
+  TORCH_API friend bool operator==(
+      const SGDParamState& lhs,
+      const SGDParamState& rhs);
+};
+
+class TORCH_API SGD : public Optimizer {
+ public:
+  explicit SGD(
+      std::vector param_groups,
+      SGDOptions defaults)
+      : Optimizer(
+            std::move(param_groups),
+            std::make_unique(defaults)) {
+    TORCH_CHECK(defaults.lr() >= 0, "Invalid learning rate: ", defaults.lr());
+    TORCH_CHECK(
+        defaults.momentum() >= 0,
+        "Invalid momentum value: ",
+        defaults.momentum());
+    TORCH_CHECK(
+        defaults.weight_decay() >= 0,
+        "Invalid weight_decay value: ",
+        defaults.weight_decay());
+    TORCH_CHECK(
+        !defaults.nesterov() ||
+            (defaults.momentum() > 0 && defaults.dampening() == 0),
+        "Nesterov momentum requires a momentum and zero dampening");
+  }
+
+  explicit SGD(std::vector params, SGDOptions defaults)
+      : SGD({OptimizerParamGroup(std::move(params))}, defaults) {}
+
+  torch::Tensor step(LossClosure closure = nullptr) override;
+
+  void save(serialize::OutputArchive& archive) const override;
+  void load(serialize::InputArchive& archive) override;
+
+ private:
+  template 
+  static void serialize(Self& self, Archive& archive) {
+    _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(SGD);
+  }
+};
+} // namespace optim
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/serialize/input-archive.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/serialize/input-archive.h
new file mode 100644
index 0000000000000000000000000000000000000000..3650cfcfea23f9b7ebac6afc726025df5953342e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/serialize/input-archive.h
@@ -0,0 +1,117 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+
+namespace at {
+class Tensor;
+} // namespace at
+
+namespace torch {
+using at::Tensor;
+namespace jit {
+struct Module;
+} // namespace jit
+} // namespace torch
+
+namespace torch {
+namespace serialize {
+
+/// A recursive representation of tensors that can be deserialized from a file
+/// or stream. In most cases, users should not have to interact with this class,
+/// and should instead use `torch::load`.
+class TORCH_API InputArchive final {
+ public:
+  /// Default-constructs the `InputArchive`.
+  InputArchive();
+
+  // Move is allowed.
+  InputArchive(InputArchive&&) = default;
+  InputArchive& operator=(InputArchive&&) = default;
+
+  // Copy is disallowed.
+  InputArchive(InputArchive&) = delete;
+  InputArchive& operator=(InputArchive&) = delete;
+
+  ~InputArchive() = default;
+
+  /// Reads an `IValue` associated with a given `key`.
+  void read(const std::string& key, c10::IValue& ivalue);
+
+  /// Reads an `IValue` associated with a given `key`. If there is no `IValue`
+  /// associated with the `key`, this returns false, otherwise it returns true.
+  bool try_read(const std::string& key, c10::IValue& ivalue);
+
+  /// Reads a `tensor` associated with a given `key`. If there is no `tensor`
+  /// associated with the `key`, this returns false, otherwise it returns true.
+  /// If the tensor is expected to be a buffer (not differentiable), `is_buffer`
+  /// must be `true`.
+  bool try_read(const std::string& key, Tensor& tensor, bool is_buffer = false);
+
+  /// Reads a `tensor` associated with a given `key`.
+  /// If the tensor is expected to be a buffer (not differentiable), `is_buffer`
+  /// must be `true`.
+  void read(const std::string& key, Tensor& tensor, bool is_buffer = false);
+
+  /// Reads a `InputArchive` associated with a given `key`. If there is no
+  /// `InputArchive` associated with the `key`, this returns false, otherwise
+  /// it returns true.
+  bool try_read(const std::string& key, InputArchive& archive);
+
+  /// Reads an `InputArchive` associated with a given `key`.
+  /// The archive can thereafter be used for further deserialization of the
+  /// nested data.
+  void read(const std::string& key, InputArchive& archive);
+
+  /// Loads the `InputArchive` from a serialized representation stored in the
+  /// file at `filename`. Storage are remapped using device option. If device
+  /// is not specified, the module is loaded to the original device.
+  void load_from(
+      const std::string& filename,
+      std::optional device = std::nullopt);
+
+  /// Loads the `InputArchive` from a serialized representation stored in the
+  /// given `stream`. Storage are remapped using device option. If device
+  /// is not specified, the module is loaded to the original device.
+  void load_from(
+      std::istream& stream,
+      std::optional device = std::nullopt);
+
+  // Loads given the specified flat array.
+  void load_from(
+      const char* data,
+      size_t size,
+      std::optional device = std::nullopt);
+
+  // Loads given the specified read and size functions.
+  void load_from(
+      const std::function&
+          read_func,
+      const std::function& size_func,
+      std::optional device = std::nullopt);
+
+  // Returns the vector of keys in the input archive.
+  std::vector keys();
+
+  /// Forwards all arguments to `read()`.
+  /// Useful for generic code that can be re-used for both `InputArchive` and
+  /// `OutputArchive` (where `operator()` forwards to `write()`).
+  template 
+  void operator()(Ts&&... ts) {
+    read(std::forward(ts)...);
+  }
+
+ private:
+  jit::Module module_;
+  std::string hierarchy_prefix_;
+};
+} // namespace serialize
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/serialize/output-archive.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/serialize/output-archive.h
new file mode 100644
index 0000000000000000000000000000000000000000..12e0f54971cb3912fb5a54334e2d4f6ac06d3022
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/api/include/torch/serialize/output-archive.h
@@ -0,0 +1,82 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+
+namespace at {
+class Tensor;
+} // namespace at
+
+namespace torch {
+using at::Tensor;
+namespace jit {
+struct Module;
+} // namespace jit
+} // namespace torch
+
+namespace torch {
+namespace serialize {
+class TORCH_API OutputArchive final {
+ public:
+  explicit OutputArchive(std::shared_ptr cu);
+  explicit OutputArchive()
+      : cu_(std::make_shared()),
+        module_("__torch__.Module", cu_) {}
+
+  // Move is allowed.
+  OutputArchive(OutputArchive&&) = default;
+  OutputArchive& operator=(OutputArchive&&) = default;
+
+  // Copy is disallowed.
+  OutputArchive(OutputArchive&) = delete;
+  OutputArchive& operator=(OutputArchive&) = delete;
+
+  std::shared_ptr compilation_unit() const {
+    return cu_;
+  }
+
+  /// Writes an `IValue` to the `OutputArchive`.
+  void write(const std::string& key, const c10::IValue& ivalue);
+
+  /// Writes a `(key, tensor)` pair to the `OutputArchive`, and marks it as
+  /// being or not being a buffer (non-differentiable tensor).
+  void write(
+      const std::string& key,
+      const Tensor& tensor,
+      bool is_buffer = false);
+
+  /// Writes a nested `OutputArchive` under the given `key` to this
+  /// `OutputArchive`.
+  void write(const std::string& key, OutputArchive& nested_archive);
+
+  /// Saves the `OutputArchive` into a serialized representation in a file at
+  /// `filename`.
+  void save_to(const std::string& filename);
+
+  /// Saves the `OutputArchive` into a serialized representation into the given
+  /// `stream`.
+  void save_to(std::ostream& stream);
+
+  /// Saves the `OutputArchive` into a serialized representation using the
+  /// given writer function.
+  void save_to(const std::function& func);
+
+  /// Forwards all arguments to `write()`.
+  /// Useful for generic code that can be re-used for both `OutputArchive` and
+  /// `InputArchive` (where `operator()` forwards to `read()`).
+  template 
+  void operator()(Ts&&... ts) {
+    write(std::forward(ts)...);
+  }
+
+ private:
+  std::shared_ptr cu_;
+  jit::Module module_;
+};
+} // namespace serialize
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/functions/accumulate_grad.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/functions/accumulate_grad.h
new file mode 100644
index 0000000000000000000000000000000000000000..39ea91bf0e763d88cf0e6632cf5050d05f0daf3d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/functions/accumulate_grad.h
@@ -0,0 +1,275 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#ifndef AT_PER_OPERATOR_HEADERS
+#include 
+#else
+#include 
+#endif
+
+#include 
+
+namespace torch::autograd {
+
+#define CHECK_RESULT(RESULT, VAR)                                          \
+  if (!(RESULT.is_sparse() || VAR.is_sparse() || RESULT.is_sparse_csr() || \
+        VAR.is_sparse_csr())) {                                            \
+    if (!utils::obeys_layout_contract(RESULT, VAR)) {                      \
+      TORCH_WARN_ONCE(                                                     \
+          "grad and param do not obey the gradient layout contract. "      \
+          "This is not an error, but may impair performance.\n"            \
+          "grad.sizes() = ",                                               \
+          RESULT.sizes(),                                                  \
+          ", strides() = ",                                                \
+          RESULT.strides(),                                                \
+          "\n",                                                            \
+          "param.sizes() = ",                                              \
+          VAR.sizes(),                                                     \
+          ", strides() = ",                                                \
+          VAR.strides());                                                  \
+    }                                                                      \
+  }
+
+struct TORCH_API AccumulateGrad : public Node {
+  explicit AccumulateGrad(Variable variable_);
+
+  variable_list apply(variable_list&& grads) override;
+
+  std::vector>& tensor_pre_hooks() noexcept
+      override {
+    // NB: Since the AccumulateGrad Node is only a weak ref from the Tensor,
+    //     it can be destroyed even though the Tensor is still alive (contrary
+    //     to all other Nodes). So we must lazily read the Tensor hooks here.
+    return impl::hooks(variable);
+  }
+
+  std::unique_ptr& tensor_post_acc_grad_hooks() noexcept
+      override {
+    // NB: Since the AccumulateGrad Node is only a weak ref from the Tensor,
+    //     it can be destroyed even though the Tensor is still alive (contrary
+    //     to all other Nodes). So we must lazily read the Tensor hooks here.
+    return impl::post_acc_grad_hooks(variable);
+  }
+
+  // Given a variable with its current grad as variable_grad, accumulates
+  // new_grad into variable_grad if in place accumulation is possible.
+  // Otherwise, uses 'update_grad' to update the grad for the variable.
+
+  // "Gradient Layout Contract"
+  //
+  // AccumulateGrad tries to stash strided (non-sparse) grads with memory layout
+  // (strides) such that variables and grads interact efficiently in later
+  // optimizer kernels, and grads interact efficiently with c10d::Reducer.cpp.
+  //
+  // Specifically, AccumulateGrad tries to ensure the following
+  // (cf torch/csrc/autograd/utils/grad_layout_contract.h):
+  //   (1) if variable.is_non_overlapping_and_dense(), the stashed grad's
+  //       strides match variable.
+  //   (2) else, stashed grad is rowmajor contiguous.
+  // If variable's grad does not exist (!variable_grad.defined())
+  // AccumulateGrad steals new_grad if it's stealable and obeys the contract
+  // already, otherwise it deep copies new_grad into an obedient clone.
+  //
+  // If variable's grad already exists (variable_grad.defined()), new_grad must
+  // be added to variable_grad.  If we aren't setting up for double backward
+  // (!GradMode::is_enabled()), AccumulateGrad performs "variable_grad +=
+  // new_grad" in-place, which keeps variable_grad's layout. We assume (hope)
+  // variable_grad was created obeying (1) or (2) at some point in the past.
+  //
+  // If we are setting up for double backward, AccumulateGrad updates the grad
+  // out-of-place via "variable_grad + new_grad."  TensorIterator operator+
+  // decides result's layout.  Typically TensorIterator matches strides of the
+  // first arg, so we once again assume (hope) variable_grad was originally
+  // created obeying (1) or (2).
+  //
+  // AccumulateGrad does not enforce the contract with 100% certainty. Examples:
+  //  - If a user manually permutes a param or its grad, then runs a fwd+bwd,
+  //    variable_grad += new_grad keeps variable_grad's layout without
+  //    rechecking the contract.
+  //  - If TensorIterator changes its corner cases about operator+'s result
+  //    (for example, giving more or less priority to channels_last inputs, see
+  //    https://github.com/pytorch/pytorch/pull/37968) the result may not obey.
+  //
+  // Fortunately, if a given grad doesn't satisfy (1) or (2), the penalty is
+  // degraded performance in Reducer.cpp or optimizer kernels, not death by
+  // assert or silently bad numerics.
+
+  // variable: the variable whose grad we're accumulating.
+  // variable_grad: the current grad for the variable.
+  // new_grad: new grad we want to accumulate for the variable.
+  // num_expected_refs: the number of refs we expect to hold internally
+  //                    such that it is safe to avoid cloning the grad
+  //                    if use_count() of the grad is less than or equal
+  //                    to this value (in addition to post_hooks).
+  // update_grad: Function that is used to update grad for the variable.
+  //              The argument to the function is a Tensor which
+  //              is used to set a new value for the grad.
+  template 
+  static void accumulateGrad(
+      const Variable& variable,
+      at::Tensor& variable_grad,
+      const at::Tensor& new_grad,
+      size_t num_expected_refs,
+      const T& update_grad) {
+    if (!variable_grad.defined()) {
+      if (!GradMode::is_enabled() && !new_grad.is_sparse() &&
+          !new_grad.is_sparse_csr() &&
+          !(variable.is_sparse_csr() && new_grad.layout() == at::kStrided) &&
+          at::caching::adjusted_use_count(new_grad) <= num_expected_refs &&
+          (new_grad.is_mkldnn() ||
+           utils::obeys_layout_contract(new_grad, variable))) {
+        // we aren't setting up for double-backward
+        // not sparse
+        // no other user-visible tensor references new_grad
+        // new_grad obeys the "Gradient Layout Contract", there has a special
+        // case, For MKLDNN tensor, which is a opaque tensor, assuming it obeys
+        // layout_contract. Under these conditions, we can steal new_grad
+        // without a deep copy.
+        update_grad(new_grad.detach());
+      } else if (
+          !GradMode::is_enabled() && new_grad.is_sparse() &&
+          new_grad._indices().is_contiguous() &&
+          new_grad._values().is_contiguous() &&
+          // Use count for indices and values should always be <=1 since the
+          // SparseTensor should be the only one holding a reference to these.
+          new_grad._indices().use_count() <= 1 &&
+          new_grad._values().use_count() <= 1 &&
+          new_grad.use_count() <= num_expected_refs) {
+        // Can't detach sparse tensor (since metadata changes are not allowed
+        // after detach), so just create a new one for the grad which is a
+        // shallow copy. We need a shallow copy so that modifying the original
+        // grad tensor doesn't modify the grad we accumulate.
+        // We only skip clone if indices and values themselves are contiguous
+        // for backward compatibility reasons. Since without this optimization,
+        // earlier we would clone the entire SparseTensor which cloned indices
+        // and values.
+        // For details see https://github.com/pytorch/pytorch/issues/34375.
+
+        // No scenario where we expect this to be true currently
+        TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
+            !at::caching::is_cached_tensor(new_grad._indices()) &&
+            !at::caching::is_cached_tensor(new_grad._values()) &&
+            !at::caching::is_cached_tensor(new_grad));
+
+        update_grad(at::_sparse_coo_tensor_unsafe(
+            new_grad._indices(),
+            new_grad._values(),
+            new_grad.sizes(),
+            new_grad.options()));
+      } else {
+        if (new_grad.is_sparse() || new_grad.is_sparse_csr() ||
+            new_grad.is_nested()) {
+          update_grad(new_grad.clone());
+        } else {
+          if (new_grad.is_mkldnn()) {
+            update_grad(new_grad.clone());
+          } else {
+            // Deep copies new_grad according to the "Gradient Layout Contract."
+            update_grad(utils::clone_obey_contract(new_grad, variable));
+          }
+        }
+      }
+    } else if (!GradMode::is_enabled()) {
+      // This case is not strictly necessary, but it makes the first-order only
+      // case slightly more efficient.
+      if (variable_grad.is_sparse() && !new_grad.is_sparse()) {
+        // If `variable_grad` is sparse and `new_grad` is not sparse, their
+        // sum is not sparse, and we must change the TensorImpl type of
+        // `variable_grad` for it to store the result. However, changing the
+        // TensorImpl type of a tensor requires changing the tensor itself, and
+        // thus in this case we have to change the grad tensor.
+        auto result = new_grad + variable_grad;
+        CHECK_RESULT(result, variable);
+        update_grad(std::move(result));
+      } else if (!at::inplaceIsVmapCompatible(variable_grad, new_grad)) {
+        // Ideally we'd perform an in-place operation to avoid changing
+        // the grad tensor. However, if that's impossible because the grads
+        // are vmap-incompatible (See NOTE: [vmap-incompatible in-place
+        // operations]), then we just add them out-of-place.
+        auto result = variable_grad + new_grad;
+        CHECK_RESULT(result, variable);
+        update_grad(std::move(result));
+      } else {
+        // In this case we can avoid changing the grad tensor. There are three
+        // scenarios when we'll hit this case:
+        //
+        // 1. `variable_grad` is sparse, and `new_grad` is sparse.
+        // 2. `variable_grad` is dense, and `new_grad` is sparse.
+        // 3. `variable_grad` is dense, and `new_grad` is dense.
+        // 4. `variable_grad` is mkldnn, and `new_grad` is mkldnn.
+        //
+        // In all of these four cases, `variable_grad += new_grad` is a
+        // valid operation which adds `new_grad` to `variable_grad` in
+        // place. `variable_grad` is thus still referring to the same tensor
+        // after the operation.
+        // Also DistributedDataParallel(DDP) package relies on grad being
+        // mutated in place for saving peak memory usage. DDP will still
+        // work correctly if it is mutated out of place here, but DDP will
+        // maintain one extra copy of grad tensors in buffer and thus
+        // increase peak memory usage.
+        variable_grad += new_grad;
+        CHECK_RESULT(variable_grad, variable);
+        // ^ We could enforce the contract more aggressively here by writing:
+        // if (variable_grad.is_sparse() || new_grad.is_sparse()) {
+        //   variable_grad += new_grad;
+        // } else if (obeys_layout_contract(variable_grad, variable)) {
+        //   variable_grad += new_grad;
+        // } else {
+        //   result = at::empty_strided(variable.sizes(), variable.strides(),
+        //                              variable.options().memory_format(std::nullopt));
+        //   update_grad(at::native::add_out(result, variable_grad,
+        //   new_grad, 1.0);
+        // }
+        // However, that accumulation is sometimes in place and sometimes not,
+        // which may break user code.
+      }
+    } else {
+      at::Tensor result;
+      if (variable_grad.is_sparse() && !new_grad.is_sparse()) {
+        // CPU backend throws an error on sparse + dense, so prefer dense +
+        // sparse here.
+        result = new_grad + variable_grad;
+      } else {
+        // Assumes operator+ result typically matches strides of first arg,
+        // and hopes variable_grad was originally created obeying layout
+        // contract.
+        result = variable_grad + new_grad;
+      }
+      CHECK_RESULT(result, variable);
+      update_grad(std::move(result));
+      // ^ We could enforce the contract more aggressively here by saying
+      // if (obeys_layout_contract(new_grad, variable)) {
+      //   update_grad(new_grad + variable_grad);
+      // } else {
+      //   update_grad(variable_grad + new_grad);
+      // }
+      // such that the stashed grad is likely to have the right strides if
+      // either variable_grad or new_grad already has the right strides.
+      // We could enforce the contract with certainty by saying
+      // auto result = variable_grad + new_grad (or vice versa), checking
+      // result's layout, and copying to an obedient clone if necessary before
+      // update_grad. The copy would require another gmem pass.  We can't create
+      // empty result with the right layout then add_out into it with a single
+      // kernel, because GradMode is enabled in this branch, and add_out isn't
+      // differentiable. Maybe more trouble than it's worth.
+    }
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(
+      const variable_list& inputs,
+      SwapSavedVariables& saved) override;
+
+  Variable variable;
+};
+
+#undef CHECK_RESULT
+
+} // namespace torch::autograd
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/functions/basic_ops.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/functions/basic_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..87530756a3b4488af364ce6ed085443810a21ae9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/functions/basic_ops.h
@@ -0,0 +1,107 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+namespace torch::autograd {
+
+struct TORCH_API Error : public Node {
+  Error(std::string msg, edge_list&& next_edges)
+      : Node(std::move(next_edges)), msg(std::move(msg)) {}
+
+  Error(std::string msg) : msg(std::move(msg)) {}
+
+  variable_list apply(variable_list&& inputs) override;
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(
+      const variable_list& inputs,
+      SwapSavedVariables& saved) override;
+
+  std::string msg;
+};
+
+// We print grad_fn names in tensor printing. For functions with backward
+// NYI, grad_fn= will be printed if we use Error, which is confusing. So
+// special case with a new NotImplemented function here.
+struct TORCH_API NotImplemented : public Error {
+  NotImplemented(const std::string& forward_fn, edge_list&& next_edges)
+      : Error(
+            "derivative for " + forward_fn + " is not implemented",
+            std::move(next_edges)) {}
+
+  NotImplemented(const std::string& forward_fn)
+      : Error("derivative for " + forward_fn + " is not implemented") {}
+};
+
+// Identity in forward, Error in backward. Used to implement
+// @once_differentiable
+struct TORCH_API DelayedError : public Node {
+  DelayedError(std::string msg, int64_t num_inputs) : msg(std::move(msg)) {
+    for (const auto _ [[maybe_unused]] : c10::irange(num_inputs)) {
+      add_input_metadata(Node::undefined_input());
+    }
+  }
+
+  variable_list apply(variable_list&& inputs) override;
+
+  std::string msg;
+};
+
+struct TORCH_API UndefinedGrad : public Node {
+  UndefinedGrad() {
+    add_input_metadata(Node::undefined_input());
+  }
+
+  variable_list apply(variable_list&& inputs) override;
+};
+
+struct TORCH_API UndefinedGradBackward : public Node {
+  UndefinedGradBackward(edge_list&& next_edges) : Node(std::move(next_edges)) {}
+
+  UndefinedGradBackward() = default;
+
+  variable_list apply(variable_list&& inputs) override;
+
+  void compiled_args(CompiledNodeArgs& args) override {}
+  variable_list apply_with_saved(
+      const variable_list& inputs,
+      SwapSavedVariables& saved) override {
+    return apply(variable_list(inputs));
+  }
+};
+
+struct TORCH_API GraphRoot : public Node {
+  GraphRoot(edge_list functions, variable_list inputs)
+      : Node(std::move(functions)), outputs(std::move(inputs)) {
+    // Ensures calls to stream() on a GraphRoot instance reflect current
+    // stream(s) on devices of root grad tensors at the time the instance is
+    // constructed.
+    for (const auto& t : outputs) {
+      add_input_metadata(t);
+    }
+  }
+
+  variable_list apply(variable_list&& inputs) override {
+    return outputs;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(
+      const variable_list& inputs,
+      SwapSavedVariables& saved) override;
+
+  variable_list outputs;
+};
+
+struct TORCH_API Identity : public Node {
+  variable_list apply(variable_list&& inputs) override;
+};
+
+} // namespace torch::autograd
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/functions/comm.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/functions/comm.h
new file mode 100644
index 0000000000000000000000000000000000000000..7def169ab992b0b6bcaeffb14a2740e0a769fc8f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/functions/comm.h
@@ -0,0 +1,45 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+namespace torch::autograd {
+
+struct TORCH_CUDA_CU_API Scatter : public Node {
+  explicit Scatter(
+      std::vector devices,
+      std::optional> chunk_sizes = std::nullopt,
+      int64_t dim = 0,
+      std::optional>> streams =
+          std::nullopt,
+      bool unsqueeze_scalars = false);
+  ~Scatter() override;
+
+  variable_list apply(variable_list&& inputs) override;
+
+  std::vector devices_;
+  std::optional> chunk_sizes_;
+  int64_t dim_;
+  std::optional>> streams_;
+  bool unsqueeze_scalars_;
+};
+
+struct TORCH_CUDA_CU_API Gather : public Node {
+  explicit Gather(const at::Device& destination_device, int64_t dim = 0);
+  ~Gather() override;
+
+  variable_list apply(variable_list&& inputs) override;
+
+  at::Device destination_device_;
+  int64_t dim_;
+};
+
+} // namespace torch::autograd
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/functions/pybind.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/functions/pybind.h
new file mode 100644
index 0000000000000000000000000000000000000000..94b3c9c679969b5bf3b6e9581fb06125d236c1fb
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/functions/pybind.h
@@ -0,0 +1,15 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+namespace py = pybind11;
+
+namespace pybind11 {
+namespace detail {}
+} // namespace pybind11
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/functions/tensor.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/functions/tensor.h
new file mode 100644
index 0000000000000000000000000000000000000000..e812860e3adc1e2a846a4a50f60efbcee70dc823
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/functions/tensor.h
@@ -0,0 +1,184 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+namespace torch::autograd {
+
+struct TORCH_API CopyBackwards : public Node {
+  variable_list apply(variable_list&& grads) override;
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(
+      const variable_list& inputs,
+      SwapSavedVariables& saved) override;
+
+  at::TensorOptions src_options;
+};
+
+// Note [View + Inplace update for base tensor]
+//
+// This note covers a few important topics related to view + inplace handling.
+//   - It explains what is the CopySlices Node and why we need it.
+//   - It explains the considerations on what is saved for backward in
+//   CopySlices.
+//   - It explains why we need to sometimes change the exec_info of the current
+//   backward
+//
+// What is CopySlices?
+// ~~~~~~~~~~~~~~~~~~~
+//
+// We support autograd with inplace mutation; e.g., if you write x.mul_(2)
+// the autograd will work as if you now had multiple Tensors under the hood and
+// you did
+//   x = t.clone()
+//   x0 = x
+//   x1 = x0 * 2
+//   x = x1
+// As you can see here, after this operation, x.grad_fn now points to x1.grad_fn
+// (the MulBackward node) and this node points to x's original grad_fn (which is
+// also x0.grad_fn). It is important to keep in mind that after the inplace,
+// there is no Tensor object that represents the x0 state anymore. But the graph
+// for it is still around in autograd (in case x was used before being modified
+// inplace). See Example 1 in
+// https://docs.google.com/drawings/d/1-T5DyYfChMX1ONQkY-zU-hj_ayQ2zmA5CBOKDWqvEhE
+// We call this rebasing the history of the Tensor.
+//
+// Now, a difficult situation is what happens if x is a differentiable view
+// of a base b.
+//   b = t.clone()
+//   x = b.select(0, 0)
+//   x *= 2
+// With the same approach as above, this will become
+//   b = t.clone()
+//   x = b.select(0, 0)
+//   b0 = b
+//   x0 = x
+//   x1 = x0 * 2
+//   b1 = b0.select_scatter(x1, 0, 0)
+//   x2 = b1.select(0, 0)
+//   x = x2
+//   b = b1
+// As you can see here, not only we need to modify x's grad_fn, we also need to
+// modify the one from b. We also need to ensure that the new grad_fn on x is
+// linked to b's new grad_fn. The chain the select_scatter, multiplication and
+// select is what CopySlices does, all wrapped into a single Node.
+//
+// See Example 1 in
+// https://docs.google.com/drawings/d/1-T5DyYfChMX1ONQkY-zU-hj_ayQ2zmA5CBOKDWqvEhE
+//
+// What do we need to save in CopySlices to run backward?
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+//
+// We need to perform grad_view = fn(grad_view), but out-of-place.
+// view_fn_ is an optional function saved in DifferentiableViewMeta
+// from forward pass, so that we can recover we when as_strided is not
+// supported. It preserves the invariants:
+//   view = view_fn_(base)
+//   grad_view = view_fn_(grad_base)
+//
+// When as_strided is supported (e.g. strided CPU/CUDA Tensors), view_fn_
+// is empty and we save TensorGeometry(view) instead.
+// With the TensorGeometry information we can use `as_strided` call which
+// is more efficient to recover views in backward.
+//
+// For example:
+//   view_1 = view_op_1(base)
+//   view_2 = view_op_2(view_1)
+//   ...
+//   view_n = view_op_n(view_n-1)
+//   view_n = inplace_op(view_n)
+//
+// In CPU/CUDA case where we support efficient as_strided implementation,
+// grad_view_n can be calculated through 1 step.
+//
+//   grad_view_n = grad_base.as_strided(view_sizes, view_strides, view_offset);
+//
+// But in XLA backend where we don't have full support of as_strided,
+// it has to save a chained lambda function view_fn_, to exactly
+// replay how the view was done in forward.
+//
+//   view_fn_ = view_op_n(...(view_op_2(view_op_1())))
+//   grad_view_n = view_fn_(grad_base)
+//
+// This chain view_fn_ works as long as forward view ops are implemented,
+// e.g XLA simulates view without a real Storage behind Tensor, but it's less
+// efficient than the as_strided one so we should be careful to only use it when
+// necessary.
+//
+//   - For CPU/CUDA we save TensorGeometry of both base and view tensors,
+//     That's all we need to pass into as_strided.
+//     E.g. int[] sizes, int[] strides, and int storage_offset.
+//   - For XLA we use view_fn_, which captures all forward view op arguments
+//     by **value**.
+//     E.g for at::narrow, int dim, int start, in length are saved.
+//
+// Theoretically we could also save Tensor `view` in CopySlices Node, but
+// it's far more expensive than what we currently save.
+//   1. We cannot afford keeping large tensors alive to recover views only.
+//   2. There are inplace checks when Tensors are loaded back to make sure
+//      they haven't been changed (including size metadata).
+// So saving metadata like TensorGeometry/view arguments is much better
+// because it is minimal information needed to recover views, as well as it
+// allows the user to modify the original Tensor without preventing the
+// backward pass from running.
+//
+// Why do we manually change exec_info in the apply?
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+//
+// Using the same example as before,
+//   b = t.clone()
+//   x = b.select(0, 0)
+//   x *= y
+//
+// You can see the visualization at
+// https://docs.google.com/drawings/d/1Bx-Hcz-zlIv7PabQqnPhUIVIs9F8WWi48svqMsAUMFs
+// which contains the wrapped MulBackward Node and show what it links to.
+// Since a backward can happen between any subset of the inputs (t and y) and
+// outputs (o, x, b). It is possible to get into a state where CopySlices's 0th
+// next function (CloneBackward) needs gradient but MulBackward's 0th next
+// function (SelectBackward) is not. This happens if you do autograd.grad
+// between x and t for example.
+// In such a case, we do need to mark SelectBackward as requiring gradient such
+// that, during the execution of MulBackward, we will actually compute gradient
+// for the 0th input.
+//
+// All the other next functions are always shared (this is asserted in the apply
+// code) and so nothing needs to be done for them.
+
+// See Note [View + Inplace update for view tensor] for what we do to view
+// tensor when an in-place operation happens.
+struct TORCH_API CopySlices : public Node {
+  CopySlices(
+      const Variable& base_var,
+      at::TensorGeometry view_,
+      std::unique_ptr view_fn_,
+      std::shared_ptr fn_);
+
+  // common code between apply/apply_with_saved
+  template 
+  variable_list apply_impl(variable_list&& inputs, const T& call_fn);
+
+  variable_list apply(variable_list&& inputs) override;
+  void release_variables() override;
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(
+      const variable_list& inputs,
+      SwapSavedVariables& saved) override;
+
+  at::TensorGeometry base;
+  // view and view_fn are redundant and view_fn will be used if available.
+  // See Note [View + Inplace update for base tensor] for details.
+  at::TensorGeometry view;
+  std::unique_ptr view_fn;
+  std::shared_ptr fn;
+};
+
+} // namespace torch::autograd
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/functions/utils.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/functions/utils.h
new file mode 100644
index 0000000000000000000000000000000000000000..0494f7f89a8b325bcf8a6590432c77efcc3b02a0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/functions/utils.h
@@ -0,0 +1,112 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include 
+#include 
+#include 
+
+namespace torch::autograd {
+
+using function_constructor = std::function(edge_list&&)>;
+
+/**
+ * Wraps the tensor outputs in variables and creates the grad_fn and sets the
+ * grad_fn if necessary.
+ */
+TORCH_API variable_list wrap_outputs(
+    const variable_list& inputs,
+    tensor_list&& outputs,
+    const function_constructor& ctr);
+
+///  Checks that inputs contains exactly `args` items and that the first
+///  `required_args`
+/// items are not nullptr. If not specified, `required_args` defaults to `args`.
+TORCH_API void check_input_variables(
+    const char* name,
+    const variable_list& inputs,
+    int args,
+    int required_args = -1,
+    bool allow_undefined = false);
+
+struct ComputeRequiresGrad : IterArgs {
+  bool out = false;
+  using IterArgs::operator();
+  void operator()(const at::Tensor& tensor) {
+    const auto& var = static_cast(tensor);
+    if (var.defined() && var.requires_grad()) {
+      out = true;
+    }
+  }
+  void operator()(const std::optional& tensor) {
+    if (tensor.has_value()) {
+      (*this)(*tensor);
+    }
+  }
+  bool short_circuit() {
+    return out;
+  }
+};
+
+template 
+inline bool compute_requires_grad(Args&&... args) {
+  if (!GradMode::is_enabled()) {
+    return false;
+  }
+  return ComputeRequiresGrad().apply(std::forward(args)...).out;
+}
+
+inline void set_history(
+    const at::Tensor& variable,
+    const std::shared_ptr& grad_fn) {
+  TORCH_CHECK(grad_fn != nullptr);
+  if (variable.defined()) {
+    // If the codegen triggers this, you most likely want to add your newly
+    // added function to the DONT_REQUIRE_DERIVATIVE list in
+    // tools/autograd/gen_variable_type.py
+    TORCH_INTERNAL_ASSERT(isDifferentiableType(variable.scalar_type()));
+    auto output_nr = grad_fn->add_input_metadata(variable);
+    impl::set_gradient_edge(variable, {grad_fn, output_nr});
+  } else {
+    grad_fn->add_input_metadata(Node::undefined_input());
+  }
+}
+
+inline void set_history(
+    const std::vector& variables,
+    const std::shared_ptr& grad_fn) {
+  for (auto& variable : variables) {
+    set_history(variable, grad_fn);
+  }
+}
+
+inline bool isFwGradDefined(const std::optional& t) {
+  return t.has_value() && t->defined() && t->_fw_grad(/*level */ 0).defined();
+}
+
+inline bool isFwGradDefinedTensorList(const at::ITensorListRef& variables) {
+  bool ret = false;
+  for (auto& variable : variables) {
+    ret |= isFwGradDefined(variable);
+  }
+  return ret;
+}
+
+inline bool isFwGradDefinedTensorList(
+    const c10::List>& li) {
+  bool ret = false;
+  for (auto i : c10::irange(li.size())) {
+    auto t = li.get(i);
+    ret |= isFwGradDefined(t);
+  }
+  return ret;
+}
+
+} // namespace torch::autograd
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/generated/Functions.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/generated/Functions.h
new file mode 100644
index 0000000000000000000000000000000000000000..8c43bacb5b7048e6156a7a9fd8c4aa8b7cffab43
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/generated/Functions.h
@@ -0,0 +1,15194 @@
+#pragma once
+
+// @generated from ../tools/autograd/templates/Functions.h
+
+#include 
+#include 
+#include 
+
+#include "torch/csrc/autograd/function.h"
+#include "torch/csrc/autograd/variable.h"
+#include "torch/csrc/autograd/saved_variable.h"
+#include 
+
+#include 
+
+namespace torch { namespace autograd { namespace generated {
+
+using at::Scalar;
+using at::Tensor;
+using at::IntArrayRef;
+using at::ArrayRef;
+using at::Type;
+using at::TensorGeometry;
+using at::ScalarType;
+using std::optional;
+using c10::fmap;
+
+inline std::vector unpack_list(at::ArrayRef xs, std::shared_ptr saved_for = nullptr) {
+  // NB: we must explicitly do the conversion in the lambda, otherwise template
+  // deduction will give a Tensor of Variable which is not convertible
+  return fmap(xs, [&saved_for](const SavedVariable& x) {
+    // TODO(crcrpar): Use `std::move(saved_for)` to avoid incrementing refcount, which would need refactoring.
+    return static_cast(x.unpack(saved_for));
+  });
+}
+
+inline c10::List> unpack_opt_list(at::ArrayRef xs, std::shared_ptr saved_for = nullptr) {
+  torch::List> result;
+  result.reserve(xs.size());
+  for (const SavedVariable& v : xs) {
+    auto var = v.unpack(saved_for);
+    result.push_back(var.defined() ? std::optional(var) : ::std::nullopt);
+  }
+  return result;
+}
+
+using torch::autograd::TypeAndSize;
+
+#ifdef _WIN32
+struct AbsBackward0 : public TraceableFunction {
+  TORCH_API AbsBackward0() = default;
+#else
+struct TORCH_API AbsBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AbsBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct AcosBackward0 : public TraceableFunction {
+  TORCH_API AcosBackward0() = default;
+#else
+struct TORCH_API AcosBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AcosBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct AddBackward0 : public TraceableFunction {
+  TORCH_API AddBackward0() = default;
+#else
+struct TORCH_API AddBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AddBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar alpha;
+  at::ScalarType other_scalar_type;
+  at::ScalarType self_scalar_type;
+
+};
+#ifdef _WIN32
+struct AddBackward1 : public TraceableFunction {
+  TORCH_API AddBackward1() = default;
+#else
+struct TORCH_API AddBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AddBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::ScalarType self_scalar_type;
+
+};
+#ifdef _WIN32
+struct AddbmmBackward0 : public TraceableFunction {
+  TORCH_API AddbmmBackward0() = default;
+#else
+struct TORCH_API AddbmmBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AddbmmBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    batch1_.reset_data();
+    batch2_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar alpha;
+  SavedVariable batch1_;
+  c10::SymInt batch1_sym_argsize_0;
+  c10::SymInt batch1_sym_argsize_1;
+  SavedVariable batch2_;
+  c10::SymInt batch2_sym_argsize_2;
+  at::Scalar beta;
+
+};
+#ifdef _WIN32
+struct AddcdivBackward0 : public TraceableFunction {
+  TORCH_API AddcdivBackward0() = default;
+#else
+struct TORCH_API AddcdivBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AddcdivBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    tensor1_.reset_data();
+    tensor2_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::ScalarType self_scalar_type;
+  SavedVariable tensor1_;
+  at::ScalarType tensor1_scalar_type;
+  SavedVariable tensor2_;
+  at::ScalarType tensor2_scalar_type;
+  at::Scalar value;
+
+};
+#ifdef _WIN32
+struct AddcmulBackward0 : public TraceableFunction {
+  TORCH_API AddcmulBackward0() = default;
+#else
+struct TORCH_API AddcmulBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AddcmulBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    tensor1_.reset_data();
+    tensor2_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::ScalarType self_scalar_type;
+  SavedVariable tensor1_;
+  at::ScalarType tensor1_scalar_type;
+  SavedVariable tensor2_;
+  at::ScalarType tensor2_scalar_type;
+  at::Scalar value;
+
+};
+#ifdef _WIN32
+struct AddmmBackward0 : public TraceableFunction {
+  TORCH_API AddmmBackward0() = default;
+#else
+struct TORCH_API AddmmBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AddmmBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    mat1_.reset_data();
+    mat2_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar alpha;
+  at::Scalar beta;
+  SavedVariable mat1_;
+  at::Layout mat1_layout;
+  std::vector mat1_sym_sizes;
+  std::vector mat1_sym_strides;
+  SavedVariable mat2_;
+  at::Layout mat2_layout;
+  std::vector mat2_sym_sizes;
+  std::vector mat2_sym_strides;
+
+};
+#ifdef _WIN32
+struct SparseAddmmBackward0 : public TraceableFunction {
+  TORCH_API SparseAddmmBackward0() = default;
+#else
+struct TORCH_API SparseAddmmBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SparseAddmmBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    mat1_.reset_data();
+    mat2_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar alpha;
+  at::Scalar beta;
+  SavedVariable mat1_;
+  SavedVariable mat2_;
+  at::Layout mat2_layout;
+  std::vector mat2_sym_sizes;
+  std::vector mat2_sym_strides;
+
+};
+#ifdef _WIN32
+struct AddmvBackward0 : public TraceableFunction {
+  TORCH_API AddmvBackward0() = default;
+#else
+struct TORCH_API AddmvBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AddmvBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    mat_.reset_data();
+    vec_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar alpha;
+  at::Scalar beta;
+  SavedVariable mat_;
+  SavedVariable vec_;
+
+};
+#ifdef _WIN32
+struct AddrBackward0 : public TraceableFunction {
+  TORCH_API AddrBackward0() = default;
+#else
+struct TORCH_API AddrBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AddrBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    vec1_.reset_data();
+    vec2_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar alpha;
+  at::Scalar beta;
+  SavedVariable vec1_;
+  SavedVariable vec2_;
+
+};
+#ifdef _WIN32
+struct AffineGridGeneratorBackward0 : public TraceableFunction {
+  TORCH_API AffineGridGeneratorBackward0() = default;
+#else
+struct TORCH_API AffineGridGeneratorBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AffineGridGeneratorBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool align_corners;
+  std::vector size;
+
+};
+#ifdef _WIN32
+struct AliasBackward0 : public Node {
+  TORCH_API AliasBackward0() = default;
+#else
+struct TORCH_API AliasBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AliasBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct AngleBackward0 : public TraceableFunction {
+  TORCH_API AngleBackward0() = default;
+#else
+struct TORCH_API AngleBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AngleBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct AcoshBackward0 : public TraceableFunction {
+  TORCH_API AcoshBackward0() = default;
+#else
+struct TORCH_API AcoshBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AcoshBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct AcoshBackward1 : public TraceableFunction {
+  TORCH_API AcoshBackward1() = default;
+#else
+struct TORCH_API AcoshBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AcoshBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct AsinhBackward0 : public TraceableFunction {
+  TORCH_API AsinhBackward0() = default;
+#else
+struct TORCH_API AsinhBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AsinhBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct AsinhBackward1 : public TraceableFunction {
+  TORCH_API AsinhBackward1() = default;
+#else
+struct TORCH_API AsinhBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AsinhBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct AtanhBackward0 : public TraceableFunction {
+  TORCH_API AtanhBackward0() = default;
+#else
+struct TORCH_API AtanhBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AtanhBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct AtanhBackward1 : public TraceableFunction {
+  TORCH_API AtanhBackward1() = default;
+#else
+struct TORCH_API AtanhBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AtanhBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct AsStridedBackward0 : public Node {
+  TORCH_API AsStridedBackward0() = default;
+#else
+struct TORCH_API AsStridedBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AsStridedBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::TensorGeometry self_geometry;
+  std::vector size;
+  ::std::optional storage_offset;
+  std::vector stride;
+
+};
+#ifdef _WIN32
+struct AsStridedBackward1 : public TraceableFunction {
+  TORCH_API AsStridedBackward1() = default;
+#else
+struct TORCH_API AsStridedBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AsStridedBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::TensorGeometry self_geometry;
+  std::vector size;
+  ::std::optional storage_offset;
+  std::vector stride;
+
+};
+#ifdef _WIN32
+struct AsinBackward0 : public TraceableFunction {
+  TORCH_API AsinBackward0() = default;
+#else
+struct TORCH_API AsinBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AsinBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct AtanBackward0 : public TraceableFunction {
+  TORCH_API AtanBackward0() = default;
+#else
+struct TORCH_API AtanBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AtanBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct Atan2Backward0 : public TraceableFunction {
+  TORCH_API Atan2Backward0() = default;
+#else
+struct TORCH_API Atan2Backward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "Atan2Backward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct BaddbmmBackward0 : public TraceableFunction {
+  TORCH_API BaddbmmBackward0() = default;
+#else
+struct TORCH_API BaddbmmBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "BaddbmmBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    batch1_.reset_data();
+    batch2_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar alpha;
+  SavedVariable batch1_;
+  SavedVariable batch2_;
+  at::Scalar beta;
+
+};
+#ifdef _WIN32
+struct BernoulliBackward0 : public TraceableFunction {
+  TORCH_API BernoulliBackward0() = default;
+#else
+struct TORCH_API BernoulliBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "BernoulliBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct BernoulliBackward1 : public TraceableFunction {
+  TORCH_API BernoulliBackward1() = default;
+#else
+struct TORCH_API BernoulliBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "BernoulliBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  torch::autograd::generated::TypeAndSize p_info;
+
+};
+#ifdef _WIN32
+struct BernoulliBackward2 : public TraceableFunction {
+  TORCH_API BernoulliBackward2() = default;
+#else
+struct TORCH_API BernoulliBackward2 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "BernoulliBackward2"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct BmmBackward0 : public TraceableFunction {
+  TORCH_API BmmBackward0() = default;
+#else
+struct TORCH_API BmmBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "BmmBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    mat2_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable mat2_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct MatmulBackward0 : public TraceableFunction {
+  TORCH_API MatmulBackward0() = default;
+#else
+struct TORCH_API MatmulBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MatmulBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct CatBackward0 : public TraceableFunction {
+  TORCH_API CatBackward0() = default;
+#else
+struct TORCH_API CatBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CatBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  ::std::vector tensors_args_scalartypes;
+  ::std::vector<::std::vector> tensors_args_sizes_symint;
+  size_t tensors_size_;
+};
+#ifdef _WIN32
+struct CauchyBackward0 : public TraceableFunction {
+  TORCH_API CauchyBackward0() = default;
+#else
+struct TORCH_API CauchyBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CauchyBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct CeilBackward0 : public TraceableFunction {
+  TORCH_API CeilBackward0() = default;
+#else
+struct TORCH_API CeilBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CeilBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct CholeskyBackward0 : public TraceableFunction {
+  TORCH_API CholeskyBackward0() = default;
+#else
+struct TORCH_API CholeskyBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CholeskyBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool upper;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct ChunkBackward0 : public TraceableFunction {
+  TORCH_API ChunkBackward0() = default;
+#else
+struct TORCH_API ChunkBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ChunkBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct ChunkBackwardAutogradNestedTensor0 : public TraceableFunction {
+  TORCH_API ChunkBackwardAutogradNestedTensor0() = default;
+#else
+struct TORCH_API ChunkBackwardAutogradNestedTensor0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ChunkBackwardAutogradNestedTensor0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t chunks = 0;
+  int64_t dim = 0;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct LinalgCholeskyExBackward0 : public TraceableFunction {
+  TORCH_API LinalgCholeskyExBackward0() = default;
+#else
+struct TORCH_API LinalgCholeskyExBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LinalgCholeskyExBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    L_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool upper;
+  SavedVariable L_;
+
+};
+#ifdef _WIN32
+struct CholeskySolveBackward0 : public TraceableFunction {
+  TORCH_API CholeskySolveBackward0() = default;
+#else
+struct TORCH_API CholeskySolveBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CholeskySolveBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    input2_.reset_data();
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable input2_;
+  SavedVariable self_;
+  bool upper;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct CholeskyInverseBackward0 : public TraceableFunction {
+  TORCH_API CholeskyInverseBackward0() = default;
+#else
+struct TORCH_API CholeskyInverseBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CholeskyInverseBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+  bool upper;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct ClampBackward0 : public TraceableFunction {
+  TORCH_API ClampBackward0() = default;
+#else
+struct TORCH_API ClampBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ClampBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    max_.reset_data();
+    min_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable max_;
+  SavedVariable min_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct ClampBackward1 : public TraceableFunction {
+  TORCH_API ClampBackward1() = default;
+#else
+struct TORCH_API ClampBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ClampBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  ::std::optional max;
+  ::std::optional min;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct ClampMinBackward0 : public TraceableFunction {
+  TORCH_API ClampMinBackward0() = default;
+#else
+struct TORCH_API ClampMinBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ClampMinBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar min;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct ClampMinBackward1 : public TraceableFunction {
+  TORCH_API ClampMinBackward1() = default;
+#else
+struct TORCH_API ClampMinBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ClampMinBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    min_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable min_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct ClampMaxBackward0 : public TraceableFunction {
+  TORCH_API ClampMaxBackward0() = default;
+#else
+struct TORCH_API ClampMaxBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ClampMaxBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar max;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct ClampMaxBackward1 : public TraceableFunction {
+  TORCH_API ClampMaxBackward1() = default;
+#else
+struct TORCH_API ClampMaxBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ClampMaxBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    max_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable max_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct CloneBackward0 : public TraceableFunction {
+  TORCH_API CloneBackward0() = default;
+#else
+struct TORCH_API CloneBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CloneBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct LazyCloneBackward0 : public TraceableFunction {
+  TORCH_API LazyCloneBackward0() = default;
+#else
+struct TORCH_API LazyCloneBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LazyCloneBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct ToCopyBackward0 : public TraceableFunction {
+  TORCH_API ToCopyBackward0() = default;
+#else
+struct TORCH_API ToCopyBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ToCopyBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::TensorOptions self_options;
+
+};
+#ifdef _WIN32
+struct CoalesceBackward0 : public TraceableFunction {
+  TORCH_API CoalesceBackward0() = default;
+#else
+struct TORCH_API CoalesceBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CoalesceBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct ComplexBackward0 : public TraceableFunction {
+  TORCH_API ComplexBackward0() = default;
+#else
+struct TORCH_API ComplexBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ComplexBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    imag_.reset_data();
+    real_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable imag_;
+  SavedVariable real_;
+
+};
+#ifdef _WIN32
+struct PolarBackward0 : public TraceableFunction {
+  TORCH_API PolarBackward0() = default;
+#else
+struct TORCH_API PolarBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "PolarBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct ConjBackward0 : public Node {
+  TORCH_API ConjBackward0() = default;
+#else
+struct TORCH_API ConjBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ConjBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct NegViewBackward0 : public Node {
+  TORCH_API NegViewBackward0() = default;
+#else
+struct TORCH_API NegViewBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NegViewBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct ConjPhysicalBackward0 : public TraceableFunction {
+  TORCH_API ConjPhysicalBackward0() = default;
+#else
+struct TORCH_API ConjPhysicalBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ConjPhysicalBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct ConjPhysicalBackward1 : public TraceableFunction {
+  TORCH_API ConjPhysicalBackward1() = default;
+#else
+struct TORCH_API ConjPhysicalBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ConjPhysicalBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct CopysignBackward0 : public TraceableFunction {
+  TORCH_API CopysignBackward0() = default;
+#else
+struct TORCH_API CopysignBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CopysignBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  torch::autograd::generated::TypeAndSize other_info;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct CopysignBackward1 : public TraceableFunction {
+  TORCH_API CopysignBackward1() = default;
+#else
+struct TORCH_API CopysignBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CopysignBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct CosBackward0 : public TraceableFunction {
+  TORCH_API CosBackward0() = default;
+#else
+struct TORCH_API CosBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CosBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct CoshBackward0 : public TraceableFunction {
+  TORCH_API CoshBackward0() = default;
+#else
+struct TORCH_API CoshBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CoshBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct LinalgCrossBackward0 : public TraceableFunction {
+  TORCH_API LinalgCrossBackward0() = default;
+#else
+struct TORCH_API LinalgCrossBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LinalgCrossBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  SavedVariable other_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct LogcumsumexpBackward0 : public TraceableFunction {
+  TORCH_API LogcumsumexpBackward0() = default;
+#else
+struct TORCH_API LogcumsumexpBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LogcumsumexpBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct CumprodBackward0 : public TraceableFunction {
+  TORCH_API CumprodBackward0() = default;
+#else
+struct TORCH_API CumprodBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CumprodBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  SavedVariable self_;
+  at::ScalarType self_scalar_type;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct CumsumBackward0 : public TraceableFunction {
+  TORCH_API CumsumBackward0() = default;
+#else
+struct TORCH_API CumsumBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CumsumBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  at::ScalarType self_scalar_type;
+
+};
+#ifdef _WIN32
+struct CummaxBackward0 : public TraceableFunction {
+  TORCH_API CummaxBackward0() = default;
+#else
+struct TORCH_API CummaxBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CummaxBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    indices_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  SavedVariable self_;
+  SavedVariable indices_;
+
+};
+#ifdef _WIN32
+struct CumminBackward0 : public TraceableFunction {
+  TORCH_API CumminBackward0() = default;
+#else
+struct TORCH_API CumminBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CumminBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    indices_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  SavedVariable self_;
+  SavedVariable indices_;
+
+};
+#ifdef _WIN32
+struct ConvTbcBackward0 : public TraceableFunction {
+  TORCH_API ConvTbcBackward0() = default;
+#else
+struct TORCH_API ConvTbcBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ConvTbcBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    bias_.reset_data();
+    self_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable bias_;
+  int64_t pad = 0;
+  SavedVariable self_;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct CtcLossBackward0 : public TraceableFunction {
+  TORCH_API CtcLossBackward0() = default;
+#else
+struct TORCH_API CtcLossBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CtcLossBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    log_probs_.reset_data();
+    targets_.reset_data();
+    result0_.reset_data();
+    result1_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t blank = 0;
+  std::vector input_lengths;
+  SavedVariable log_probs_;
+  std::vector target_lengths;
+  SavedVariable targets_;
+  bool zero_infinity;
+  SavedVariable result0_;
+  SavedVariable result1_;
+
+};
+#ifdef _WIN32
+struct CtcLossBackward1 : public TraceableFunction {
+  TORCH_API CtcLossBackward1() = default;
+#else
+struct TORCH_API CtcLossBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CtcLossBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    input_lengths_.reset_data();
+    log_probs_.reset_data();
+    target_lengths_.reset_data();
+    targets_.reset_data();
+    result0_.reset_data();
+    result1_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t blank = 0;
+  SavedVariable input_lengths_;
+  SavedVariable log_probs_;
+  SavedVariable target_lengths_;
+  SavedVariable targets_;
+  bool zero_infinity;
+  SavedVariable result0_;
+  SavedVariable result1_;
+
+};
+#ifdef _WIN32
+struct Deg2RadBackward0 : public TraceableFunction {
+  TORCH_API Deg2RadBackward0() = default;
+#else
+struct TORCH_API Deg2RadBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "Deg2RadBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct LinalgDetBackward0 : public TraceableFunction {
+  TORCH_API LinalgDetBackward0() = default;
+#else
+struct TORCH_API LinalgDetBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LinalgDetBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    A_.reset_data();
+    LU_.reset_data();
+    pivots_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable A_;
+  SavedVariable LU_;
+  SavedVariable pivots_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct LinalgSlogdetBackward0 : public TraceableFunction {
+  TORCH_API LinalgSlogdetBackward0() = default;
+#else
+struct TORCH_API LinalgSlogdetBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LinalgSlogdetBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    A_.reset_data();
+    LU_.reset_data();
+    pivots_.reset_data();
+    sign_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable A_;
+  SavedVariable LU_;
+  SavedVariable pivots_;
+  SavedVariable sign_;
+
+};
+#ifdef _WIN32
+struct BlockDiagBackward0 : public TraceableFunction {
+  TORCH_API BlockDiagBackward0() = default;
+#else
+struct TORCH_API BlockDiagBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "BlockDiagBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  ::std::vector tensors_args_scalartypes;
+  ::std::vector<::std::vector> tensors_args_sizes;
+  size_t tensors_size_;
+};
+#ifdef _WIN32
+struct DiagEmbedBackward0 : public TraceableFunction {
+  TORCH_API DiagEmbedBackward0() = default;
+#else
+struct TORCH_API DiagEmbedBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "DiagEmbedBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim1 = 0;
+  int64_t dim2 = 0;
+  int64_t offset = 0;
+
+};
+#ifdef _WIN32
+struct DiagonalBackward0 : public Node {
+  TORCH_API DiagonalBackward0() = default;
+#else
+struct TORCH_API DiagonalBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "DiagonalBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim1 = 0;
+  int64_t dim2 = 0;
+  int64_t offset = 0;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct DiagonalBackwardBackward0 : public TraceableFunction {
+  TORCH_API DiagonalBackwardBackward0() = default;
+#else
+struct TORCH_API DiagonalBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "DiagonalBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim1 = 0;
+  int64_t dim2 = 0;
+  int64_t offset = 0;
+
+};
+#ifdef _WIN32
+struct DistBackward0 : public TraceableFunction {
+  TORCH_API DistBackward0() = default;
+#else
+struct TORCH_API DistBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "DistBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  at::Scalar p;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct DivBackward0 : public TraceableFunction {
+  TORCH_API DivBackward0() = default;
+#else
+struct TORCH_API DivBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "DivBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  SavedVariable self_;
+  at::ScalarType self_scalar_type;
+
+};
+#ifdef _WIN32
+struct DivBackward1 : public TraceableFunction {
+  TORCH_API DivBackward1() = default;
+#else
+struct TORCH_API DivBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "DivBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar other;
+  at::ScalarType self_scalar_type;
+
+};
+#ifdef _WIN32
+struct DivBackward2 : public TraceableFunction {
+  TORCH_API DivBackward2() = default;
+#else
+struct TORCH_API DivBackward2 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "DivBackward2"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  std::optional rounding_mode;
+  SavedVariable self_;
+  at::ScalarType self_scalar_type;
+
+};
+#ifdef _WIN32
+struct DivBackward3 : public TraceableFunction {
+  TORCH_API DivBackward3() = default;
+#else
+struct TORCH_API DivBackward3 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "DivBackward3"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar other;
+  std::optional rounding_mode;
+  at::ScalarType self_scalar_type;
+
+};
+#ifdef _WIN32
+struct DotBackward0 : public TraceableFunction {
+  TORCH_API DotBackward0() = default;
+#else
+struct TORCH_API DotBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "DotBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    tensor_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+  SavedVariable tensor_;
+
+};
+#ifdef _WIN32
+struct VdotBackward0 : public TraceableFunction {
+  TORCH_API VdotBackward0() = default;
+#else
+struct TORCH_API VdotBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "VdotBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct FusedDropoutBackward0 : public TraceableFunction {
+  TORCH_API FusedDropoutBackward0() = default;
+#else
+struct TORCH_API FusedDropoutBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FusedDropoutBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result1_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  double p;
+  SavedVariable result1_;
+
+};
+#ifdef _WIN32
+struct NativeDropoutBackward0 : public TraceableFunction {
+  TORCH_API NativeDropoutBackward0() = default;
+#else
+struct TORCH_API NativeDropoutBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NativeDropoutBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result1_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  double p;
+  ::std::optional train;
+  SavedVariable result1_;
+
+};
+#ifdef _WIN32
+struct NativeDropoutBackwardBackward0 : public TraceableFunction {
+  TORCH_API NativeDropoutBackwardBackward0() = default;
+#else
+struct TORCH_API NativeDropoutBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NativeDropoutBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grad_output_.reset_data();
+    mask_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable grad_output_;
+  SavedVariable mask_;
+  double scale;
+
+};
+#ifdef _WIN32
+struct EqBackward0 : public TraceableFunction {
+  TORCH_API EqBackward0() = default;
+#else
+struct TORCH_API EqBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "EqBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct EqBackward1 : public TraceableFunction {
+  TORCH_API EqBackward1() = default;
+#else
+struct TORCH_API EqBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "EqBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  torch::autograd::generated::TypeAndSize other_info;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct ErfBackward0 : public TraceableFunction {
+  TORCH_API ErfBackward0() = default;
+#else
+struct TORCH_API ErfBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ErfBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct ErfcBackward0 : public TraceableFunction {
+  TORCH_API ErfcBackward0() = default;
+#else
+struct TORCH_API ErfcBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ErfcBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct SpecialErfcxBackward0 : public TraceableFunction {
+  TORCH_API SpecialErfcxBackward0() = default;
+#else
+struct TORCH_API SpecialErfcxBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SpecialErfcxBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct ErfinvBackward0 : public TraceableFunction {
+  TORCH_API ErfinvBackward0() = default;
+#else
+struct TORCH_API ErfinvBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ErfinvBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct ExpBackward0 : public TraceableFunction {
+  TORCH_API ExpBackward0() = default;
+#else
+struct TORCH_API ExpBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ExpBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct Exp2Backward0 : public TraceableFunction {
+  TORCH_API Exp2Backward0() = default;
+#else
+struct TORCH_API Exp2Backward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "Exp2Backward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct Expm1Backward0 : public TraceableFunction {
+  TORCH_API Expm1Backward0() = default;
+#else
+struct TORCH_API Expm1Backward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "Expm1Backward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct ExpandBackward0 : public Node {
+  TORCH_API ExpandBackward0() = default;
+#else
+struct TORCH_API ExpandBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ExpandBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct ExponentialBackward0 : public TraceableFunction {
+  TORCH_API ExponentialBackward0() = default;
+#else
+struct TORCH_API ExponentialBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ExponentialBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct FakeQuantizePerTensorAffineCachemaskBackward0 : public TraceableFunction {
+  TORCH_API FakeQuantizePerTensorAffineCachemaskBackward0() = default;
+#else
+struct TORCH_API FakeQuantizePerTensorAffineCachemaskBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FakeQuantizePerTensorAffineCachemaskBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    mask_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable mask_;
+
+};
+#ifdef _WIN32
+struct FakeQuantizePerTensorAffineCachemaskTensorQparamsBackward0 : public TraceableFunction {
+  TORCH_API FakeQuantizePerTensorAffineCachemaskTensorQparamsBackward0() = default;
+#else
+struct TORCH_API FakeQuantizePerTensorAffineCachemaskTensorQparamsBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FakeQuantizePerTensorAffineCachemaskTensorQparamsBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    mask_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable mask_;
+
+};
+#ifdef _WIN32
+struct FakeQuantizeLearnablePerTensorAffineBackward0 : public TraceableFunction {
+  TORCH_API FakeQuantizeLearnablePerTensorAffineBackward0() = default;
+#else
+struct TORCH_API FakeQuantizeLearnablePerTensorAffineBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FakeQuantizeLearnablePerTensorAffineBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    scale_.reset_data();
+    self_.reset_data();
+    zero_point_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  double grad_factor;
+  int64_t quant_max = 0;
+  int64_t quant_min = 0;
+  SavedVariable scale_;
+  SavedVariable self_;
+  SavedVariable zero_point_;
+
+};
+#ifdef _WIN32
+struct FakeQuantizePerChannelAffineCachemaskBackward0 : public TraceableFunction {
+  TORCH_API FakeQuantizePerChannelAffineCachemaskBackward0() = default;
+#else
+struct TORCH_API FakeQuantizePerChannelAffineCachemaskBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FakeQuantizePerChannelAffineCachemaskBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    mask_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable mask_;
+
+};
+#ifdef _WIN32
+struct FakeQuantizeLearnablePerChannelAffineBackward0 : public TraceableFunction {
+  TORCH_API FakeQuantizeLearnablePerChannelAffineBackward0() = default;
+#else
+struct TORCH_API FakeQuantizeLearnablePerChannelAffineBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FakeQuantizeLearnablePerChannelAffineBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    scale_.reset_data();
+    self_.reset_data();
+    zero_point_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t axis = 0;
+  double grad_factor;
+  int64_t quant_max = 0;
+  int64_t quant_min = 0;
+  SavedVariable scale_;
+  SavedVariable self_;
+  SavedVariable zero_point_;
+
+};
+#ifdef _WIN32
+struct FusedMovingAvgObsFqHelperBackward0 : public TraceableFunction {
+  TORCH_API FusedMovingAvgObsFqHelperBackward0() = default;
+#else
+struct TORCH_API FusedMovingAvgObsFqHelperBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FusedMovingAvgObsFqHelperBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    mask_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable mask_;
+
+};
+#ifdef _WIN32
+struct FillBackward0 : public TraceableFunction {
+  TORCH_API FillBackward0() = default;
+#else
+struct TORCH_API FillBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FillBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct FillBackward1 : public TraceableFunction {
+  TORCH_API FillBackward1() = default;
+#else
+struct TORCH_API FillBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FillBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct FillBackward2 : public TraceableFunction {
+  TORCH_API FillBackward2() = default;
+#else
+struct TORCH_API FillBackward2 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FillBackward2"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct FillBackward3 : public TraceableFunction {
+  TORCH_API FillBackward3() = default;
+#else
+struct TORCH_API FillBackward3 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FillBackward3"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct FloorBackward0 : public TraceableFunction {
+  TORCH_API FloorBackward0() = default;
+#else
+struct TORCH_API FloorBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FloorBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct FmodBackward0 : public TraceableFunction {
+  TORCH_API FmodBackward0() = default;
+#else
+struct TORCH_API FmodBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FmodBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct FmodBackward1 : public TraceableFunction {
+  TORCH_API FmodBackward1() = default;
+#else
+struct TORCH_API FmodBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FmodBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct FracBackward0 : public TraceableFunction {
+  TORCH_API FracBackward0() = default;
+#else
+struct TORCH_API FracBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FracBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct FrexpBackward0 : public TraceableFunction {
+  TORCH_API FrexpBackward0() = default;
+#else
+struct TORCH_API FrexpBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FrexpBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    exponent_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable exponent_;
+
+};
+#ifdef _WIN32
+struct GatherBackward0 : public TraceableFunction {
+  TORCH_API GatherBackward0() = default;
+#else
+struct TORCH_API GatherBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "GatherBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    index_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  SavedVariable index_;
+  SavedVariable self_;
+  bool sparse_grad;
+
+};
+#ifdef _WIN32
+struct GeBackward0 : public TraceableFunction {
+  TORCH_API GeBackward0() = default;
+#else
+struct TORCH_API GeBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "GeBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct GeBackward1 : public TraceableFunction {
+  TORCH_API GeBackward1() = default;
+#else
+struct TORCH_API GeBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "GeBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  torch::autograd::generated::TypeAndSize other_info;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct GeometricBackward0 : public TraceableFunction {
+  TORCH_API GeometricBackward0() = default;
+#else
+struct TORCH_API GeometricBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "GeometricBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct GeqrfBackward0 : public TraceableFunction {
+  TORCH_API GeqrfBackward0() = default;
+#else
+struct TORCH_API GeqrfBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "GeqrfBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct GridSampler2DBackward0 : public TraceableFunction {
+  TORCH_API GridSampler2DBackward0() = default;
+#else
+struct TORCH_API GridSampler2DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "GridSampler2DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grid_.reset_data();
+    input_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool align_corners;
+  SavedVariable grid_;
+  SavedVariable input_;
+  int64_t interpolation_mode = 0;
+  int64_t padding_mode = 0;
+
+};
+#ifdef _WIN32
+struct GridSampler3DBackward0 : public TraceableFunction {
+  TORCH_API GridSampler3DBackward0() = default;
+#else
+struct TORCH_API GridSampler3DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "GridSampler3DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grid_.reset_data();
+    input_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool align_corners;
+  SavedVariable grid_;
+  SavedVariable input_;
+  int64_t interpolation_mode = 0;
+  int64_t padding_mode = 0;
+
+};
+#ifdef _WIN32
+struct GridSampler2DCpuFallbackBackward0 : public TraceableFunction {
+  TORCH_API GridSampler2DCpuFallbackBackward0() = default;
+#else
+struct TORCH_API GridSampler2DCpuFallbackBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "GridSampler2DCpuFallbackBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grid_.reset_data();
+    input_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool align_corners;
+  SavedVariable grid_;
+  SavedVariable input_;
+  int64_t interpolation_mode = 0;
+  int64_t padding_mode = 0;
+
+};
+#ifdef _WIN32
+struct GtBackward0 : public TraceableFunction {
+  TORCH_API GtBackward0() = default;
+#else
+struct TORCH_API GtBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "GtBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct GtBackward1 : public TraceableFunction {
+  TORCH_API GtBackward1() = default;
+#else
+struct TORCH_API GtBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "GtBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  torch::autograd::generated::TypeAndSize other_info;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct HardsigmoidBackward0 : public TraceableFunction {
+  TORCH_API HardsigmoidBackward0() = default;
+#else
+struct TORCH_API HardsigmoidBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "HardsigmoidBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct HardswishBackward0 : public TraceableFunction {
+  TORCH_API HardswishBackward0() = default;
+#else
+struct TORCH_API HardswishBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "HardswishBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct HardswishBackwardBackward0 : public TraceableFunction {
+  TORCH_API HardswishBackwardBackward0() = default;
+#else
+struct TORCH_API HardswishBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "HardswishBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grad_output_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable grad_output_;
+  SavedVariable self_;
+  at::TensorOptions self_options;
+
+};
+#ifdef _WIN32
+struct HypotBackward0 : public TraceableFunction {
+  TORCH_API HypotBackward0() = default;
+#else
+struct TORCH_API HypotBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "HypotBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct I0Backward0 : public TraceableFunction {
+  TORCH_API I0Backward0() = default;
+#else
+struct TORCH_API I0Backward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "I0Backward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct SpecialI0EBackward0 : public TraceableFunction {
+  TORCH_API SpecialI0EBackward0() = default;
+#else
+struct TORCH_API SpecialI0EBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SpecialI0EBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct SpecialI1Backward0 : public TraceableFunction {
+  TORCH_API SpecialI1Backward0() = default;
+#else
+struct TORCH_API SpecialI1Backward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SpecialI1Backward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct SpecialI1EBackward0 : public TraceableFunction {
+  TORCH_API SpecialI1EBackward0() = default;
+#else
+struct TORCH_API SpecialI1EBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SpecialI1EBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct IgammaBackward0 : public TraceableFunction {
+  TORCH_API IgammaBackward0() = default;
+#else
+struct TORCH_API IgammaBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "IgammaBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct IgammacBackward0 : public TraceableFunction {
+  TORCH_API IgammacBackward0() = default;
+#else
+struct TORCH_API IgammacBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "IgammacBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct IndexBackward0 : public TraceableFunction {
+  TORCH_API IndexBackward0() = default;
+#else
+struct TORCH_API IndexBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "IndexBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.clear();
+    indices_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector indices_;
+  bool indices_released_ = false;
+  at::TensorOptions self_options;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct UnsafeIndexBackward0 : public TraceableFunction {
+  TORCH_API UnsafeIndexBackward0() = default;
+#else
+struct TORCH_API UnsafeIndexBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UnsafeIndexBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.clear();
+    indices_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector indices_;
+  bool indices_released_ = false;
+  at::TensorOptions self_options;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct UnsafeMaskedIndexBackward0 : public TraceableFunction {
+  TORCH_API UnsafeMaskedIndexBackward0() = default;
+#else
+struct TORCH_API UnsafeMaskedIndexBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UnsafeMaskedIndexBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.clear();
+    indices_released_ = true;
+    mask_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector indices_;
+  bool indices_released_ = false;
+  SavedVariable mask_;
+  at::TensorOptions self_options;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct UnsafeMaskedIndexPutAccumulateBackward0 : public TraceableFunction {
+  TORCH_API UnsafeMaskedIndexPutAccumulateBackward0() = default;
+#else
+struct TORCH_API UnsafeMaskedIndexPutAccumulateBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UnsafeMaskedIndexPutAccumulateBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.clear();
+    indices_released_ = true;
+    mask_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector indices_;
+  bool indices_released_ = false;
+  SavedVariable mask_;
+
+};
+#ifdef _WIN32
+struct IndexAddBackward0 : public TraceableFunction {
+  TORCH_API IndexAddBackward0() = default;
+#else
+struct TORCH_API IndexAddBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "IndexAddBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    index_.reset_data();
+    source_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar alpha;
+  int64_t dim = 0;
+  SavedVariable index_;
+  SavedVariable source_;
+  int64_t source_dim = 0;
+
+};
+#ifdef _WIN32
+struct IndexReduceBackward0 : public TraceableFunction {
+  TORCH_API IndexReduceBackward0() = default;
+#else
+struct TORCH_API IndexReduceBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "IndexReduceBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    index_.reset_data();
+    self_.reset_data();
+    source_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  bool include_self;
+  SavedVariable index_;
+  std::string reduce;
+  SavedVariable self_;
+  SavedVariable source_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct IndexCopyBackward0 : public TraceableFunction {
+  TORCH_API IndexCopyBackward0() = default;
+#else
+struct TORCH_API IndexCopyBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "IndexCopyBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    index_.reset_data();
+    source_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  SavedVariable index_;
+  SavedVariable source_;
+  int64_t source_dim = 0;
+
+};
+#ifdef _WIN32
+struct IndexFillBackward0 : public TraceableFunction {
+  TORCH_API IndexFillBackward0() = default;
+#else
+struct TORCH_API IndexFillBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "IndexFillBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    index_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  SavedVariable index_;
+
+};
+#ifdef _WIN32
+struct IndexFillBackward1 : public TraceableFunction {
+  TORCH_API IndexFillBackward1() = default;
+#else
+struct TORCH_API IndexFillBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "IndexFillBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    index_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  SavedVariable index_;
+
+};
+#ifdef _WIN32
+struct IndexPutBackward0 : public TraceableFunction {
+  TORCH_API IndexPutBackward0() = default;
+#else
+struct TORCH_API IndexPutBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "IndexPutBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.clear();
+    indices_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool accumulate;
+  std::vector indices_;
+  bool indices_released_ = false;
+  torch::autograd::generated::TypeAndSize values_info;
+
+};
+#ifdef _WIN32
+struct UnsafeIndexPutBackward0 : public TraceableFunction {
+  TORCH_API UnsafeIndexPutBackward0() = default;
+#else
+struct TORCH_API UnsafeIndexPutBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UnsafeIndexPutBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.clear();
+    indices_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool accumulate;
+  std::vector indices_;
+  bool indices_released_ = false;
+  torch::autograd::generated::TypeAndSize values_info;
+
+};
+#ifdef _WIN32
+struct IndexPutImplBackward0 : public TraceableFunction {
+  TORCH_API IndexPutImplBackward0() = default;
+#else
+struct TORCH_API IndexPutImplBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "IndexPutImplBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.clear();
+    indices_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool accumulate;
+  std::vector indices_;
+  bool indices_released_ = false;
+  torch::autograd::generated::TypeAndSize values_info;
+
+};
+#ifdef _WIN32
+struct IndexSelectBackward0 : public TraceableFunction {
+  TORCH_API IndexSelectBackward0() = default;
+#else
+struct TORCH_API IndexSelectBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "IndexSelectBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    index_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  SavedVariable index_;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct LinalgInvExBackward0 : public TraceableFunction {
+  TORCH_API LinalgInvExBackward0() = default;
+#else
+struct TORCH_API LinalgInvExBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LinalgInvExBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    inverse_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable inverse_;
+
+};
+#ifdef _WIN32
+struct LinalgPinvBackward0 : public TraceableFunction {
+  TORCH_API LinalgPinvBackward0() = default;
+#else
+struct TORCH_API LinalgPinvBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LinalgPinvBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct KthvalueBackward0 : public TraceableFunction {
+  TORCH_API KthvalueBackward0() = default;
+#else
+struct TORCH_API KthvalueBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "KthvalueBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  bool keepdim;
+  std::vector self_sym_sizes;
+  SavedVariable indices_;
+
+};
+#ifdef _WIN32
+struct LeBackward0 : public TraceableFunction {
+  TORCH_API LeBackward0() = default;
+#else
+struct TORCH_API LeBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LeBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct LeBackward1 : public TraceableFunction {
+  TORCH_API LeBackward1() = default;
+#else
+struct TORCH_API LeBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LeBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  torch::autograd::generated::TypeAndSize other_info;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct LerpBackward0 : public TraceableFunction {
+  TORCH_API LerpBackward0() = default;
+#else
+struct TORCH_API LerpBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LerpBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar weight;
+
+};
+#ifdef _WIN32
+struct LerpBackward1 : public TraceableFunction {
+  TORCH_API LerpBackward1() = default;
+#else
+struct TORCH_API LerpBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LerpBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    end_.reset_data();
+    self_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable end_;
+  SavedVariable self_;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct LgammaBackward0 : public TraceableFunction {
+  TORCH_API LgammaBackward0() = default;
+#else
+struct TORCH_API LgammaBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LgammaBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct DigammaBackward0 : public TraceableFunction {
+  TORCH_API DigammaBackward0() = default;
+#else
+struct TORCH_API DigammaBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "DigammaBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct PolygammaBackward0 : public TraceableFunction {
+  TORCH_API PolygammaBackward0() = default;
+#else
+struct TORCH_API PolygammaBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "PolygammaBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t n = 0;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct PolygammaBackward1 : public TraceableFunction {
+  TORCH_API PolygammaBackward1() = default;
+#else
+struct TORCH_API PolygammaBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "PolygammaBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t n = 0;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct LogBackward0 : public TraceableFunction {
+  TORCH_API LogBackward0() = default;
+#else
+struct TORCH_API LogBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LogBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct Log10Backward0 : public TraceableFunction {
+  TORCH_API Log10Backward0() = default;
+#else
+struct TORCH_API Log10Backward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "Log10Backward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct Log1PBackward0 : public TraceableFunction {
+  TORCH_API Log1PBackward0() = default;
+#else
+struct TORCH_API Log1PBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "Log1PBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct Log2Backward0 : public TraceableFunction {
+  TORCH_API Log2Backward0() = default;
+#else
+struct TORCH_API Log2Backward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "Log2Backward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct LogaddexpBackward0 : public TraceableFunction {
+  TORCH_API LogaddexpBackward0() = default;
+#else
+struct TORCH_API LogaddexpBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LogaddexpBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct Logaddexp2Backward0 : public TraceableFunction {
+  TORCH_API Logaddexp2Backward0() = default;
+#else
+struct TORCH_API Logaddexp2Backward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "Logaddexp2Backward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct XlogyBackward0 : public TraceableFunction {
+  TORCH_API XlogyBackward0() = default;
+#else
+struct TORCH_API XlogyBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "XlogyBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct XlogyBackward1 : public TraceableFunction {
+  TORCH_API XlogyBackward1() = default;
+#else
+struct TORCH_API XlogyBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "XlogyBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  at::Scalar self;
+
+};
+#ifdef _WIN32
+struct XlogyBackward2 : public TraceableFunction {
+  TORCH_API XlogyBackward2() = default;
+#else
+struct TORCH_API XlogyBackward2 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "XlogyBackward2"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar other;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct SpecialXlog1PyBackward0 : public TraceableFunction {
+  TORCH_API SpecialXlog1PyBackward0() = default;
+#else
+struct TORCH_API SpecialXlog1PyBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SpecialXlog1PyBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct SpecialXlog1PyBackward1 : public TraceableFunction {
+  TORCH_API SpecialXlog1PyBackward1() = default;
+#else
+struct TORCH_API SpecialXlog1PyBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SpecialXlog1PyBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  at::Scalar self;
+
+};
+#ifdef _WIN32
+struct SpecialXlog1PyBackward2 : public TraceableFunction {
+  TORCH_API SpecialXlog1PyBackward2() = default;
+#else
+struct TORCH_API SpecialXlog1PyBackward2 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SpecialXlog1PyBackward2"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar other;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct SpecialZetaBackward0 : public TraceableFunction {
+  TORCH_API SpecialZetaBackward0() = default;
+#else
+struct TORCH_API SpecialZetaBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SpecialZetaBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct SpecialZetaBackward1 : public TraceableFunction {
+  TORCH_API SpecialZetaBackward1() = default;
+#else
+struct TORCH_API SpecialZetaBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SpecialZetaBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  at::Scalar self;
+
+};
+#ifdef _WIN32
+struct SpecialZetaBackward2 : public TraceableFunction {
+  TORCH_API SpecialZetaBackward2() = default;
+#else
+struct TORCH_API SpecialZetaBackward2 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SpecialZetaBackward2"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct LogNormalBackward0 : public TraceableFunction {
+  TORCH_API LogNormalBackward0() = default;
+#else
+struct TORCH_API LogNormalBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LogNormalBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct LogsumexpBackward0 : public TraceableFunction {
+  TORCH_API LogsumexpBackward0() = default;
+#else
+struct TORCH_API LogsumexpBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LogsumexpBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dim;
+  bool keepdim;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct LinalgLstsqBackward0 : public TraceableFunction {
+  TORCH_API LinalgLstsqBackward0() = default;
+#else
+struct TORCH_API LinalgLstsqBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LinalgLstsqBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    b_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable b_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct LtBackward0 : public TraceableFunction {
+  TORCH_API LtBackward0() = default;
+#else
+struct TORCH_API LtBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LtBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct LtBackward1 : public TraceableFunction {
+  TORCH_API LtBackward1() = default;
+#else
+struct TORCH_API LtBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LtBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  torch::autograd::generated::TypeAndSize other_info;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct LinalgLuFactorExBackward0 : public TraceableFunction {
+  TORCH_API LinalgLuFactorExBackward0() = default;
+#else
+struct TORCH_API LinalgLuFactorExBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LinalgLuFactorExBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    LU_.reset_data();
+    pivots_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool pivot;
+  SavedVariable LU_;
+  SavedVariable pivots_;
+
+};
+#ifdef _WIN32
+struct LinalgLuFactorBackward0 : public TraceableFunction {
+  TORCH_API LinalgLuFactorBackward0() = default;
+#else
+struct TORCH_API LinalgLuFactorBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LinalgLuFactorBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    LU_.reset_data();
+    pivots_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool pivot;
+  SavedVariable LU_;
+  SavedVariable pivots_;
+
+};
+#ifdef _WIN32
+struct LinalgLuBackward0 : public TraceableFunction {
+  TORCH_API LinalgLuBackward0() = default;
+#else
+struct TORCH_API LinalgLuBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LinalgLuBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    L_.reset_data();
+    P_.reset_data();
+    U_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool pivot;
+  SavedVariable L_;
+  SavedVariable P_;
+  SavedVariable U_;
+
+};
+#ifdef _WIN32
+struct LinalgLuSolveBackward0 : public TraceableFunction {
+  TORCH_API LinalgLuSolveBackward0() = default;
+#else
+struct TORCH_API LinalgLuSolveBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LinalgLuSolveBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    LU_.reset_data();
+    pivots_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable LU_;
+  bool adjoint;
+  bool left;
+  SavedVariable pivots_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct LuUnpackBackward0 : public TraceableFunction {
+  TORCH_API LuUnpackBackward0() = default;
+#else
+struct TORCH_API LuUnpackBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LuUnpackBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::SymInt LU_data_sym_argsize_minus_1;
+  c10::SymInt LU_data_sym_argsize_minus_2;
+
+};
+#ifdef _WIN32
+struct MaskedFillBackward0 : public TraceableFunction {
+  TORCH_API MaskedFillBackward0() = default;
+#else
+struct TORCH_API MaskedFillBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MaskedFillBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    mask_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable mask_;
+
+};
+#ifdef _WIN32
+struct MaskedFillBackward1 : public TraceableFunction {
+  TORCH_API MaskedFillBackward1() = default;
+#else
+struct TORCH_API MaskedFillBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MaskedFillBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    mask_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable mask_;
+
+};
+#ifdef _WIN32
+struct MaskedScatterBackward0 : public TraceableFunction {
+  TORCH_API MaskedScatterBackward0() = default;
+#else
+struct TORCH_API MaskedScatterBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MaskedScatterBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    mask_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable mask_;
+  std::vector source_sym_sizes;
+
+};
+#ifdef _WIN32
+struct MaskedScatterBackwardBackward0 : public TraceableFunction {
+  TORCH_API MaskedScatterBackwardBackward0() = default;
+#else
+struct TORCH_API MaskedScatterBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MaskedScatterBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    mask_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  torch::autograd::generated::TypeAndSize grad_output_info;
+  SavedVariable mask_;
+
+};
+#ifdef _WIN32
+struct MaskedSelectBackward0 : public TraceableFunction {
+  TORCH_API MaskedSelectBackward0() = default;
+#else
+struct TORCH_API MaskedSelectBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MaskedSelectBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    mask_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable mask_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct LinalgMatrixExpBackward0 : public TraceableFunction {
+  TORCH_API LinalgMatrixExpBackward0() = default;
+#else
+struct TORCH_API LinalgMatrixExpBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LinalgMatrixExpBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct MaxBackward0 : public TraceableFunction {
+  TORCH_API MaxBackward0() = default;
+#else
+struct TORCH_API MaxBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MaxBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  bool keepdim;
+  std::vector self_sym_sizes;
+  SavedVariable indices_;
+
+};
+#ifdef _WIN32
+struct MaxBackward1 : public TraceableFunction {
+  TORCH_API MaxBackward1() = default;
+#else
+struct TORCH_API MaxBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MaxBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct MaximumBackward0 : public TraceableFunction {
+  TORCH_API MaximumBackward0() = default;
+#else
+struct TORCH_API MaximumBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MaximumBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct FmaxBackward0 : public TraceableFunction {
+  TORCH_API FmaxBackward0() = default;
+#else
+struct TORCH_API FmaxBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FmaxBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct MeanBackward0 : public TraceableFunction {
+  TORCH_API MeanBackward0() = default;
+#else
+struct TORCH_API MeanBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MeanBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::SymInt self_sym_numel;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct MeanBackward1 : public TraceableFunction {
+  TORCH_API MeanBackward1() = default;
+#else
+struct TORCH_API MeanBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MeanBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::OptionalArray dim;
+  bool keepdim;
+  c10::SymInt self_sym_numel;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct MedianBackward0 : public TraceableFunction {
+  TORCH_API MedianBackward0() = default;
+#else
+struct TORCH_API MedianBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MedianBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct NanmedianBackward0 : public TraceableFunction {
+  TORCH_API NanmedianBackward0() = default;
+#else
+struct TORCH_API NanmedianBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NanmedianBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct MedianBackward1 : public TraceableFunction {
+  TORCH_API MedianBackward1() = default;
+#else
+struct TORCH_API MedianBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MedianBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  bool keepdim;
+  std::vector self_sym_sizes;
+  SavedVariable indices_;
+
+};
+#ifdef _WIN32
+struct NanmedianBackward1 : public TraceableFunction {
+  TORCH_API NanmedianBackward1() = default;
+#else
+struct TORCH_API NanmedianBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NanmedianBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  bool keepdim;
+  std::vector self_sym_sizes;
+  SavedVariable indices_;
+
+};
+#ifdef _WIN32
+struct MinBackward0 : public TraceableFunction {
+  TORCH_API MinBackward0() = default;
+#else
+struct TORCH_API MinBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MinBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  bool keepdim;
+  std::vector self_sym_sizes;
+  SavedVariable indices_;
+
+};
+#ifdef _WIN32
+struct MinBackward1 : public TraceableFunction {
+  TORCH_API MinBackward1() = default;
+#else
+struct TORCH_API MinBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MinBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct MinimumBackward0 : public TraceableFunction {
+  TORCH_API MinimumBackward0() = default;
+#else
+struct TORCH_API MinimumBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MinimumBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct FminBackward0 : public TraceableFunction {
+  TORCH_API FminBackward0() = default;
+#else
+struct TORCH_API FminBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FminBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct AmaxBackward0 : public TraceableFunction {
+  TORCH_API AmaxBackward0() = default;
+#else
+struct TORCH_API AmaxBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AmaxBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dim;
+  bool keepdim;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct AminBackward0 : public TraceableFunction {
+  TORCH_API AminBackward0() = default;
+#else
+struct TORCH_API AminBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AminBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dim;
+  bool keepdim;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct MmBackward0 : public TraceableFunction {
+  TORCH_API MmBackward0() = default;
+#else
+struct TORCH_API MmBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MmBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    mat2_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable mat2_;
+  at::Layout mat2_layout;
+  std::vector mat2_sym_sizes;
+  std::vector mat2_sym_strides;
+  SavedVariable self_;
+  at::Layout self_layout;
+  std::vector self_sym_sizes;
+  std::vector self_sym_strides;
+
+};
+#ifdef _WIN32
+struct ModeBackward0 : public TraceableFunction {
+  TORCH_API ModeBackward0() = default;
+#else
+struct TORCH_API ModeBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ModeBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  bool keepdim;
+  std::vector self_sym_sizes;
+  SavedVariable indices_;
+
+};
+#ifdef _WIN32
+struct MulBackward0 : public TraceableFunction {
+  TORCH_API MulBackward0() = default;
+#else
+struct TORCH_API MulBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MulBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  at::ScalarType other_scalar_type;
+  SavedVariable self_;
+  at::ScalarType self_scalar_type;
+
+};
+#ifdef _WIN32
+struct MulBackward1 : public TraceableFunction {
+  TORCH_API MulBackward1() = default;
+#else
+struct TORCH_API MulBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MulBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar other;
+  at::ScalarType self_scalar_type;
+
+};
+#ifdef _WIN32
+struct MvBackward0 : public TraceableFunction {
+  TORCH_API MvBackward0() = default;
+#else
+struct TORCH_API MvBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MvBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    vec_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+  SavedVariable vec_;
+
+};
+#ifdef _WIN32
+struct MvlgammaBackward0 : public TraceableFunction {
+  TORCH_API MvlgammaBackward0() = default;
+#else
+struct TORCH_API MvlgammaBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MvlgammaBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t p = 0;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct NanToNumBackward0 : public TraceableFunction {
+  TORCH_API NanToNumBackward0() = default;
+#else
+struct TORCH_API NanToNumBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NanToNumBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct NativeBatchNormBackward0 : public TraceableFunction {
+  TORCH_API NativeBatchNormBackward0() = default;
+#else
+struct TORCH_API NativeBatchNormBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NativeBatchNormBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    input_.reset_data();
+    running_mean_.reset_data();
+    running_var_.reset_data();
+    weight_.reset_data();
+    result1_.reset_data();
+    result2_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  double eps;
+  SavedVariable input_;
+  SavedVariable running_mean_;
+  SavedVariable running_var_;
+  bool training;
+  SavedVariable weight_;
+  SavedVariable result1_;
+  SavedVariable result2_;
+
+};
+#ifdef _WIN32
+struct NativeBatchNormLegitBackward0 : public TraceableFunction {
+  TORCH_API NativeBatchNormLegitBackward0() = default;
+#else
+struct TORCH_API NativeBatchNormLegitBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NativeBatchNormLegitBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    input_.reset_data();
+    running_mean_.reset_data();
+    running_var_.reset_data();
+    weight_.reset_data();
+    result1_.reset_data();
+    result2_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  double eps;
+  SavedVariable input_;
+  SavedVariable running_mean_;
+  SavedVariable running_var_;
+  bool training;
+  SavedVariable weight_;
+  SavedVariable result1_;
+  SavedVariable result2_;
+
+};
+#ifdef _WIN32
+struct NativeBatchNormLegitNoTrainingBackward0 : public TraceableFunction {
+  TORCH_API NativeBatchNormLegitNoTrainingBackward0() = default;
+#else
+struct TORCH_API NativeBatchNormLegitNoTrainingBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NativeBatchNormLegitNoTrainingBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    input_.reset_data();
+    running_mean_.reset_data();
+    running_var_.reset_data();
+    weight_.reset_data();
+    result1_.reset_data();
+    result2_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  double eps;
+  SavedVariable input_;
+  SavedVariable running_mean_;
+  SavedVariable running_var_;
+  SavedVariable weight_;
+  SavedVariable result1_;
+  SavedVariable result2_;
+
+};
+#ifdef _WIN32
+struct NativeBatchNormLegitBackward1 : public TraceableFunction {
+  TORCH_API NativeBatchNormLegitBackward1() = default;
+#else
+struct TORCH_API NativeBatchNormLegitBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NativeBatchNormLegitBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    input_.reset_data();
+    weight_.reset_data();
+    result1_.reset_data();
+    result2_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  double eps;
+  SavedVariable input_;
+  bool training;
+  SavedVariable weight_;
+  SavedVariable result1_;
+  SavedVariable result2_;
+
+};
+#ifdef _WIN32
+struct NativeBatchNormBackwardBackward0 : public TraceableFunction {
+  TORCH_API NativeBatchNormBackwardBackward0() = default;
+#else
+struct TORCH_API NativeBatchNormBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NativeBatchNormBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grad_out_.reset_data();
+    input_.reset_data();
+    running_mean_.reset_data();
+    running_var_.reset_data();
+    save_invstd_.reset_data();
+    save_mean_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  double eps;
+  SavedVariable grad_out_;
+  SavedVariable input_;
+  SavedVariable running_mean_;
+  SavedVariable running_var_;
+  SavedVariable save_invstd_;
+  SavedVariable save_mean_;
+  bool train;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct NativeLayerNormBackward0 : public TraceableFunction {
+  TORCH_API NativeLayerNormBackward0() = default;
+#else
+struct TORCH_API NativeLayerNormBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NativeLayerNormBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    bias_.reset_data();
+    input_.reset_data();
+    weight_.reset_data();
+    result1_.reset_data();
+    result2_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable bias_;
+  SavedVariable input_;
+  std::vector normalized_shape;
+  SavedVariable weight_;
+  SavedVariable result1_;
+  SavedVariable result2_;
+
+};
+#ifdef _WIN32
+struct NativeLayerNormBackwardBackward0 : public TraceableFunction {
+  TORCH_API NativeLayerNormBackwardBackward0() = default;
+#else
+struct TORCH_API NativeLayerNormBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NativeLayerNormBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grad_out_.reset_data();
+    input_.reset_data();
+    mean_.reset_data();
+    rstd_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable grad_out_;
+  SavedVariable input_;
+  SavedVariable mean_;
+  std::vector normalized_shape;
+  SavedVariable rstd_;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct NativeGroupNormBackward0 : public TraceableFunction {
+  TORCH_API NativeGroupNormBackward0() = default;
+#else
+struct TORCH_API NativeGroupNormBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NativeGroupNormBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    input_.reset_data();
+    weight_.reset_data();
+    result1_.reset_data();
+    result2_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::SymInt C;
+  c10::SymInt HxW;
+  c10::SymInt N;
+  double eps;
+  int64_t group = 0;
+  SavedVariable input_;
+  SavedVariable weight_;
+  SavedVariable result1_;
+  SavedVariable result2_;
+
+};
+#ifdef _WIN32
+struct NeBackward0 : public TraceableFunction {
+  TORCH_API NeBackward0() = default;
+#else
+struct TORCH_API NeBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NeBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct NeBackward1 : public TraceableFunction {
+  TORCH_API NeBackward1() = default;
+#else
+struct TORCH_API NeBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NeBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  torch::autograd::generated::TypeAndSize other_info;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct NegBackward0 : public TraceableFunction {
+  TORCH_API NegBackward0() = default;
+#else
+struct TORCH_API NegBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NegBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct BatchNormWithUpdateBackward0 : public TraceableFunction {
+  TORCH_API BatchNormWithUpdateBackward0() = default;
+#else
+struct TORCH_API BatchNormWithUpdateBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "BatchNormWithUpdateBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    input_.reset_data();
+    running_mean_.reset_data();
+    running_var_.reset_data();
+    weight_.reset_data();
+    result1_.reset_data();
+    result2_.reset_data();
+    result3_.reset_data();
+  }
+  bool retain_variables = true;
+  void will_release_variables() override {
+    retain_variables = false;
+  }
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  double eps;
+  SavedVariable input_;
+  SavedVariable running_mean_;
+  SavedVariable running_var_;
+  SavedVariable weight_;
+  SavedVariable result1_;
+  SavedVariable result2_;
+  SavedVariable result3_;
+
+};
+#ifdef _WIN32
+struct BatchNormNoUpdateBackward0 : public TraceableFunction {
+  TORCH_API BatchNormNoUpdateBackward0() = default;
+#else
+struct TORCH_API BatchNormNoUpdateBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "BatchNormNoUpdateBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    input_.reset_data();
+    running_mean_.reset_data();
+    running_var_.reset_data();
+    weight_.reset_data();
+    result1_.reset_data();
+    result2_.reset_data();
+    result3_.reset_data();
+  }
+  bool retain_variables = true;
+  void will_release_variables() override {
+    retain_variables = false;
+  }
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  double eps;
+  SavedVariable input_;
+  SavedVariable running_mean_;
+  SavedVariable running_var_;
+  SavedVariable weight_;
+  SavedVariable result1_;
+  SavedVariable result2_;
+  SavedVariable result3_;
+
+};
+#ifdef _WIN32
+struct BatchNormBackwardBackward0 : public TraceableFunction {
+  TORCH_API BatchNormBackwardBackward0() = default;
+#else
+struct TORCH_API BatchNormBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "BatchNormBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grad_out_.reset_data();
+    input_.reset_data();
+    reserve_.reset_data();
+    running_mean_.reset_data();
+    running_var_.reset_data();
+    save_mean_.reset_data();
+    save_var_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  double eps;
+  SavedVariable grad_out_;
+  SavedVariable input_;
+  SavedVariable reserve_;
+  SavedVariable running_mean_;
+  SavedVariable running_var_;
+  SavedVariable save_mean_;
+  SavedVariable save_var_;
+  bool update;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct NextafterBackward0 : public TraceableFunction {
+  TORCH_API NextafterBackward0() = default;
+#else
+struct TORCH_API NextafterBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NextafterBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct NormBackward0 : public TraceableFunction {
+  TORCH_API NormBackward0() = default;
+#else
+struct TORCH_API NormBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NormBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar p;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct NormBackward1 : public TraceableFunction {
+  TORCH_API NormBackward1() = default;
+#else
+struct TORCH_API NormBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NormBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dim;
+  bool keepdim;
+  ::std::optional p;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct NormBackward2 : public TraceableFunction {
+  TORCH_API NormBackward2() = default;
+#else
+struct TORCH_API NormBackward2 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NormBackward2"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  ::std::optional p;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct NormBackward3 : public TraceableFunction {
+  TORCH_API NormBackward3() = default;
+#else
+struct TORCH_API NormBackward3 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NormBackward3"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dim;
+  bool keepdim;
+  ::std::optional p;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct LinalgVectorNormBackward0 : public TraceableFunction {
+  TORCH_API LinalgVectorNormBackward0() = default;
+#else
+struct TORCH_API LinalgVectorNormBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LinalgVectorNormBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::OptionalArray dim;
+  bool keepdim;
+  at::Scalar ord;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct PdistBackward0 : public TraceableFunction {
+  TORCH_API PdistBackward0() = default;
+#else
+struct TORCH_API PdistBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "PdistBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  double p;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct PdistBackwardBackward0 : public TraceableFunction {
+  TORCH_API PdistBackwardBackward0() = default;
+#else
+struct TORCH_API PdistBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "PdistBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct EuclideanDistBackward0 : public TraceableFunction {
+  TORCH_API EuclideanDistBackward0() = default;
+#else
+struct TORCH_API EuclideanDistBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "EuclideanDistBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    x1_.reset_data();
+    x2_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable x1_;
+  SavedVariable x2_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct CdistBackward0 : public TraceableFunction {
+  TORCH_API CdistBackward0() = default;
+#else
+struct TORCH_API CdistBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CdistBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    x1_.reset_data();
+    x2_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  double p;
+  SavedVariable x1_;
+  SavedVariable x2_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct CdistBackwardBackward0 : public TraceableFunction {
+  TORCH_API CdistBackwardBackward0() = default;
+#else
+struct TORCH_API CdistBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CdistBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct NormalBackward0 : public TraceableFunction {
+  TORCH_API NormalBackward0() = default;
+#else
+struct TORCH_API NormalBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NormalBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct NormalBackward1 : public TraceableFunction {
+  TORCH_API NormalBackward1() = default;
+#else
+struct TORCH_API NormalBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NormalBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector mean_sym_sizes;
+
+};
+#ifdef _WIN32
+struct NormalBackward2 : public TraceableFunction {
+  TORCH_API NormalBackward2() = default;
+#else
+struct TORCH_API NormalBackward2 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NormalBackward2"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector std_sym_sizes;
+
+};
+#ifdef _WIN32
+struct NormalBackward3 : public TraceableFunction {
+  TORCH_API NormalBackward3() = default;
+#else
+struct TORCH_API NormalBackward3 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NormalBackward3"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector mean_sym_sizes;
+  std::vector std_sym_sizes;
+
+};
+#ifdef _WIN32
+struct LinalgHouseholderProductBackward0 : public TraceableFunction {
+  TORCH_API LinalgHouseholderProductBackward0() = default;
+#else
+struct TORCH_API LinalgHouseholderProductBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LinalgHouseholderProductBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    input_.reset_data();
+    tau_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable input_;
+  SavedVariable tau_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct OrmqrBackward0 : public TraceableFunction {
+  TORCH_API OrmqrBackward0() = default;
+#else
+struct TORCH_API OrmqrBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "OrmqrBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    input2_.reset_data();
+    input3_.reset_data();
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable input2_;
+  SavedVariable input3_;
+  bool left;
+  SavedVariable self_;
+  bool transpose;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct PermuteBackward0 : public Node {
+  TORCH_API PermuteBackward0() = default;
+#else
+struct TORCH_API PermuteBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "PermuteBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dims;
+
+};
+#ifdef _WIN32
+struct PoissonBackward0 : public TraceableFunction {
+  TORCH_API PoissonBackward0() = default;
+#else
+struct TORCH_API PoissonBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "PoissonBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct PowBackward0 : public TraceableFunction {
+  TORCH_API PowBackward0() = default;
+#else
+struct TORCH_API PowBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "PowBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar exponent;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct PowBackward1 : public TraceableFunction {
+  TORCH_API PowBackward1() = default;
+#else
+struct TORCH_API PowBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "PowBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    exponent_.reset_data();
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable exponent_;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct PowBackward2 : public TraceableFunction {
+  TORCH_API PowBackward2() = default;
+#else
+struct TORCH_API PowBackward2 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "PowBackward2"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    exponent_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable exponent_;
+  at::Scalar self;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct ProdBackward0 : public TraceableFunction {
+  TORCH_API ProdBackward0() = default;
+#else
+struct TORCH_API ProdBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ProdBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct ProdBackward1 : public TraceableFunction {
+  TORCH_API ProdBackward1() = default;
+#else
+struct TORCH_API ProdBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ProdBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  bool keepdim;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct PutBackward0 : public TraceableFunction {
+  TORCH_API PutBackward0() = default;
+#else
+struct TORCH_API PutBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "PutBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    index_.reset_data();
+    source_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool accumulate;
+  SavedVariable index_;
+  SavedVariable source_;
+  torch::autograd::generated::TypeAndSize source_info;
+
+};
+#ifdef _WIN32
+struct LinalgQrBackward0 : public TraceableFunction {
+  TORCH_API LinalgQrBackward0() = default;
+#else
+struct TORCH_API LinalgQrBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LinalgQrBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    Q_.reset_data();
+    R_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::string mode;
+  SavedVariable Q_;
+  SavedVariable R_;
+
+};
+#ifdef _WIN32
+struct Rad2DegBackward0 : public TraceableFunction {
+  TORCH_API Rad2DegBackward0() = default;
+#else
+struct TORCH_API Rad2DegBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "Rad2DegBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct RandomBackward0 : public TraceableFunction {
+  TORCH_API RandomBackward0() = default;
+#else
+struct TORCH_API RandomBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "RandomBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct RandomBackward1 : public TraceableFunction {
+  TORCH_API RandomBackward1() = default;
+#else
+struct TORCH_API RandomBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "RandomBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct RandomBackward2 : public TraceableFunction {
+  TORCH_API RandomBackward2() = default;
+#else
+struct TORCH_API RandomBackward2 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "RandomBackward2"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct ReciprocalBackward0 : public TraceableFunction {
+  TORCH_API ReciprocalBackward0() = default;
+#else
+struct TORCH_API ReciprocalBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ReciprocalBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct RemainderBackward0 : public TraceableFunction {
+  TORCH_API RemainderBackward0() = default;
+#else
+struct TORCH_API RemainderBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "RemainderBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct RemainderBackward1 : public TraceableFunction {
+  TORCH_API RemainderBackward1() = default;
+#else
+struct TORCH_API RemainderBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "RemainderBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct RenormBackward0 : public TraceableFunction {
+  TORCH_API RenormBackward0() = default;
+#else
+struct TORCH_API RenormBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "RenormBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  at::Scalar maxnorm;
+  at::Scalar p;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct RepeatBackward0 : public TraceableFunction {
+  TORCH_API RepeatBackward0() = default;
+#else
+struct TORCH_API RepeatBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "RepeatBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector repeats;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct SpecialEntrBackward0 : public TraceableFunction {
+  TORCH_API SpecialEntrBackward0() = default;
+#else
+struct TORCH_API SpecialEntrBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SpecialEntrBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct SpecialNdtriBackward0 : public TraceableFunction {
+  TORCH_API SpecialNdtriBackward0() = default;
+#else
+struct TORCH_API SpecialNdtriBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SpecialNdtriBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct SpecialLogNdtrBackward0 : public TraceableFunction {
+  TORCH_API SpecialLogNdtrBackward0() = default;
+#else
+struct TORCH_API SpecialLogNdtrBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SpecialLogNdtrBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct ReshapeAliasBackward0 : public Node {
+  TORCH_API ReshapeAliasBackward0() = default;
+#else
+struct TORCH_API ReshapeAliasBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ReshapeAliasBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct RoundBackward0 : public TraceableFunction {
+  TORCH_API RoundBackward0() = default;
+#else
+struct TORCH_API RoundBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "RoundBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct RoundBackward1 : public TraceableFunction {
+  TORCH_API RoundBackward1() = default;
+#else
+struct TORCH_API RoundBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "RoundBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct RsqrtBackward0 : public TraceableFunction {
+  TORCH_API RsqrtBackward0() = default;
+#else
+struct TORCH_API RsqrtBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "RsqrtBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct ScatterBackward0 : public TraceableFunction {
+  TORCH_API ScatterBackward0() = default;
+#else
+struct TORCH_API ScatterBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ScatterBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    index_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  SavedVariable index_;
+
+};
+#ifdef _WIN32
+struct ScatterBackward1 : public TraceableFunction {
+  TORCH_API ScatterBackward1() = default;
+#else
+struct TORCH_API ScatterBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ScatterBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    index_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  SavedVariable index_;
+
+};
+#ifdef _WIN32
+struct ScatterAddBackward0 : public TraceableFunction {
+  TORCH_API ScatterAddBackward0() = default;
+#else
+struct TORCH_API ScatterAddBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ScatterAddBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    index_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  SavedVariable index_;
+
+};
+#ifdef _WIN32
+struct SelectBackward0 : public Node {
+  TORCH_API SelectBackward0() = default;
+#else
+struct TORCH_API SelectBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SelectBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  c10::SymInt index;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct SelectBackwardAutogradNestedTensor0 : public Node {
+  TORCH_API SelectBackwardAutogradNestedTensor0() = default;
+#else
+struct TORCH_API SelectBackwardAutogradNestedTensor0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SelectBackwardAutogradNestedTensor0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  c10::SymInt index;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct SelectBackwardBackward0 : public TraceableFunction {
+  TORCH_API SelectBackwardBackward0() = default;
+#else
+struct TORCH_API SelectBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SelectBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  c10::SymInt index;
+
+};
+#ifdef _WIN32
+struct SigmoidBackward0 : public TraceableFunction {
+  TORCH_API SigmoidBackward0() = default;
+#else
+struct TORCH_API SigmoidBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SigmoidBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct LogitBackward0 : public TraceableFunction {
+  TORCH_API LogitBackward0() = default;
+#else
+struct TORCH_API LogitBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LogitBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  ::std::optional eps;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct SignBackward0 : public TraceableFunction {
+  TORCH_API SignBackward0() = default;
+#else
+struct TORCH_API SignBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SignBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct SgnBackward0 : public TraceableFunction {
+  TORCH_API SgnBackward0() = default;
+#else
+struct TORCH_API SgnBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SgnBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct SinBackward0 : public TraceableFunction {
+  TORCH_API SinBackward0() = default;
+#else
+struct TORCH_API SinBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SinBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct SincBackward0 : public TraceableFunction {
+  TORCH_API SincBackward0() = default;
+#else
+struct TORCH_API SincBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SincBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct SinhBackward0 : public TraceableFunction {
+  TORCH_API SinhBackward0() = default;
+#else
+struct TORCH_API SinhBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SinhBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct SliceBackward0 : public Node {
+  TORCH_API SliceBackward0() = default;
+#else
+struct TORCH_API SliceBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SliceBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  ::std::optional end;
+  std::vector self_sym_sizes;
+  ::std::optional start;
+  c10::SymInt step;
+
+};
+#ifdef _WIN32
+struct SliceBackwardBackward0 : public TraceableFunction {
+  TORCH_API SliceBackwardBackward0() = default;
+#else
+struct TORCH_API SliceBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SliceBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  c10::SymInt end;
+  c10::SymInt start;
+  c10::SymInt step;
+
+};
+#ifdef _WIN32
+struct SliceInverseBackward0 : public Node {
+  TORCH_API SliceInverseBackward0() = default;
+#else
+struct TORCH_API SliceInverseBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SliceInverseBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  ::std::optional end;
+  torch::autograd::generated::TypeAndSize self_info;
+  ::std::optional start;
+  c10::SymInt step;
+
+};
+#ifdef _WIN32
+struct SliceScatterBackward0 : public TraceableFunction {
+  TORCH_API SliceScatterBackward0() = default;
+#else
+struct TORCH_API SliceScatterBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SliceScatterBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  ::std::optional end;
+  torch::autograd::generated::TypeAndSize src_info;
+  ::std::optional start;
+  c10::SymInt step;
+
+};
+#ifdef _WIN32
+struct SelectScatterBackward0 : public TraceableFunction {
+  TORCH_API SelectScatterBackward0() = default;
+#else
+struct TORCH_API SelectScatterBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SelectScatterBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  c10::SymInt index;
+  torch::autograd::generated::TypeAndSize src_info;
+
+};
+#ifdef _WIN32
+struct DiagonalScatterBackward0 : public TraceableFunction {
+  TORCH_API DiagonalScatterBackward0() = default;
+#else
+struct TORCH_API DiagonalScatterBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "DiagonalScatterBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim1 = 0;
+  int64_t dim2 = 0;
+  int64_t offset = 0;
+  torch::autograd::generated::TypeAndSize src_info;
+
+};
+#ifdef _WIN32
+struct AsStridedScatterBackward0 : public TraceableFunction {
+  TORCH_API AsStridedScatterBackward0() = default;
+#else
+struct TORCH_API AsStridedScatterBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AsStridedScatterBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::TensorGeometry self_geometry;
+  std::vector size;
+  at::TensorGeometry src_geometry;
+  ::std::optional storage_offset;
+  std::vector stride;
+
+};
+#ifdef _WIN32
+struct LinalgSolveExBackward0 : public TraceableFunction {
+  TORCH_API LinalgSolveExBackward0() = default;
+#else
+struct TORCH_API LinalgSolveExBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LinalgSolveExBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    A_.reset_data();
+    LU_.reset_data();
+    pivots_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable A_;
+  bool left;
+  SavedVariable LU_;
+  SavedVariable pivots_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct SortBackward0 : public TraceableFunction {
+  TORCH_API SortBackward0() = default;
+#else
+struct TORCH_API SortBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SortBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  std::vector self_sym_sizes;
+  SavedVariable indices_;
+
+};
+#ifdef _WIN32
+struct SortBackward1 : public TraceableFunction {
+  TORCH_API SortBackward1() = default;
+#else
+struct TORCH_API SortBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SortBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  std::vector self_sym_sizes;
+  SavedVariable indices_;
+
+};
+#ifdef _WIN32
+struct SplitBackward0 : public Node {
+  TORCH_API SplitBackward0() = default;
+#else
+struct TORCH_API SplitBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SplitBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  at::TensorOptions self_options;
+  std::vector self_sym_sizes;
+  c10::SymInt split_size;
+
+};
+#ifdef _WIN32
+struct UnsafeSplitBackward0 : public TraceableFunction {
+  TORCH_API UnsafeSplitBackward0() = default;
+#else
+struct TORCH_API UnsafeSplitBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UnsafeSplitBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  at::TensorOptions self_options;
+  std::vector self_sym_sizes;
+  c10::SymInt split_size;
+
+};
+#ifdef _WIN32
+struct SplitWithSizesBackward0 : public Node {
+  TORCH_API SplitWithSizesBackward0() = default;
+#else
+struct TORCH_API SplitWithSizesBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SplitWithSizesBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  at::TensorOptions self_options;
+  std::vector self_sym_sizes;
+  std::vector split_sizes;
+
+};
+#ifdef _WIN32
+struct SplitWithSizesBackwardAutogradNestedTensor0 : public Node {
+  TORCH_API SplitWithSizesBackwardAutogradNestedTensor0() = default;
+#else
+struct TORCH_API SplitWithSizesBackwardAutogradNestedTensor0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SplitWithSizesBackwardAutogradNestedTensor0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  SavedVariable self_;
+  at::TensorOptions self_options;
+  std::vector split_sizes;
+
+};
+#ifdef _WIN32
+struct UnsafeSplitWithSizesBackward0 : public TraceableFunction {
+  TORCH_API UnsafeSplitWithSizesBackward0() = default;
+#else
+struct TORCH_API UnsafeSplitWithSizesBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UnsafeSplitWithSizesBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  at::TensorOptions self_options;
+  std::vector self_sym_sizes;
+  std::vector split_sizes;
+
+};
+#ifdef _WIN32
+struct SqrtBackward0 : public TraceableFunction {
+  TORCH_API SqrtBackward0() = default;
+#else
+struct TORCH_API SqrtBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SqrtBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct SqueezeBackward0 : public Node {
+  TORCH_API SqueezeBackward0() = default;
+#else
+struct TORCH_API SqueezeBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SqueezeBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct SqueezeBackward1 : public Node {
+  TORCH_API SqueezeBackward1() = default;
+#else
+struct TORCH_API SqueezeBackward1 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SqueezeBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct SqueezeBackwardAutogradNestedTensor0 : public Node {
+  TORCH_API SqueezeBackwardAutogradNestedTensor0() = default;
+#else
+struct TORCH_API SqueezeBackwardAutogradNestedTensor0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SqueezeBackwardAutogradNestedTensor0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+
+};
+#ifdef _WIN32
+struct SqueezeBackward2 : public Node {
+  TORCH_API SqueezeBackward2() = default;
+#else
+struct TORCH_API SqueezeBackward2 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SqueezeBackward2"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dim;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct SqueezeBackwardAutogradNestedTensor1 : public Node {
+  TORCH_API SqueezeBackwardAutogradNestedTensor1() = default;
+#else
+struct TORCH_API SqueezeBackwardAutogradNestedTensor1 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SqueezeBackwardAutogradNestedTensor1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dim;
+  int64_t self_dim = 0;
+
+};
+#ifdef _WIN32
+struct SqueezeBackward3 : public TraceableFunction {
+  TORCH_API SqueezeBackward3() = default;
+#else
+struct TORCH_API SqueezeBackward3 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SqueezeBackward3"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct SqueezeBackward4 : public TraceableFunction {
+  TORCH_API SqueezeBackward4() = default;
+#else
+struct TORCH_API SqueezeBackward4 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SqueezeBackward4"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct SqueezeBackward5 : public TraceableFunction {
+  TORCH_API SqueezeBackward5() = default;
+#else
+struct TORCH_API SqueezeBackward5 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SqueezeBackward5"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dim;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct StdBackward0 : public TraceableFunction {
+  TORCH_API StdBackward0() = default;
+#else
+struct TORCH_API StdBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "StdBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  ::std::optional correction;
+  c10::OptionalArray dim;
+  bool keepdim;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct StdMeanBackward0 : public TraceableFunction {
+  TORCH_API StdMeanBackward0() = default;
+#else
+struct TORCH_API StdMeanBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "StdMeanBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result0_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  ::std::optional correction;
+  c10::OptionalArray dim;
+  bool keepdim;
+  SavedVariable self_;
+  SavedVariable result0_;
+
+};
+#ifdef _WIN32
+struct SubBackward0 : public TraceableFunction {
+  TORCH_API SubBackward0() = default;
+#else
+struct TORCH_API SubBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SubBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar alpha;
+  at::ScalarType other_scalar_type;
+  at::ScalarType self_scalar_type;
+
+};
+#ifdef _WIN32
+struct SubBackward1 : public TraceableFunction {
+  TORCH_API SubBackward1() = default;
+#else
+struct TORCH_API SubBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SubBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::ScalarType self_scalar_type;
+
+};
+#ifdef _WIN32
+struct RsubBackward0 : public TraceableFunction {
+  TORCH_API RsubBackward0() = default;
+#else
+struct TORCH_API RsubBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "RsubBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar alpha;
+  at::ScalarType other_scalar_type;
+  at::ScalarType self_scalar_type;
+
+};
+#ifdef _WIN32
+struct RsubBackward1 : public TraceableFunction {
+  TORCH_API RsubBackward1() = default;
+#else
+struct TORCH_API RsubBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "RsubBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar alpha;
+  at::ScalarType self_scalar_type;
+
+};
+#ifdef _WIN32
+struct SumBackward0 : public TraceableFunction {
+  TORCH_API SumBackward0() = default;
+#else
+struct TORCH_API SumBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SumBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct SumBackward1 : public TraceableFunction {
+  TORCH_API SumBackward1() = default;
+#else
+struct TORCH_API SumBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SumBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::OptionalArray dim;
+  bool keepdim;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct SumBackwardAutogradNestedTensor0 : public TraceableFunction {
+  TORCH_API SumBackwardAutogradNestedTensor0() = default;
+#else
+struct TORCH_API SumBackwardAutogradNestedTensor0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SumBackwardAutogradNestedTensor0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::OptionalArray dim;
+  bool keepdim;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct NansumBackward0 : public TraceableFunction {
+  TORCH_API NansumBackward0() = default;
+#else
+struct TORCH_API NansumBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NansumBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::OptionalArray dim;
+  bool keepdim;
+  SavedVariable self_;
+  at::ScalarType self_scalar_type;
+
+};
+#ifdef _WIN32
+struct LinalgSvdBackward0 : public TraceableFunction {
+  TORCH_API LinalgSvdBackward0() = default;
+#else
+struct TORCH_API LinalgSvdBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LinalgSvdBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    S_.reset_data();
+    U_.reset_data();
+    Vh_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool full_matrices;
+  SavedVariable S_;
+  c10::SymInt S_sym_argsize_minus_1;
+  SavedVariable U_;
+  SavedVariable Vh_;
+
+};
+#ifdef _WIN32
+struct LinalgEighBackward0 : public TraceableFunction {
+  TORCH_API LinalgEighBackward0() = default;
+#else
+struct TORCH_API LinalgEighBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LinalgEighBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    eigenvalues_.reset_data();
+    eigenvectors_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable eigenvalues_;
+  SavedVariable eigenvectors_;
+
+};
+#ifdef _WIN32
+struct LinalgEigBackward0 : public TraceableFunction {
+  TORCH_API LinalgEigBackward0() = default;
+#else
+struct TORCH_API LinalgEigBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LinalgEigBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    eigenvalues_.reset_data();
+    eigenvectors_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::ScalarType self_scalar_type;
+  SavedVariable eigenvalues_;
+  SavedVariable eigenvectors_;
+
+};
+#ifdef _WIN32
+struct TBackward0 : public Node {
+  TORCH_API TBackward0() = default;
+#else
+struct TORCH_API TBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "TBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct TBackward1 : public TraceableFunction {
+  TORCH_API TBackward1() = default;
+#else
+struct TORCH_API TBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "TBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct FlipBackward0 : public TraceableFunction {
+  TORCH_API FlipBackward0() = default;
+#else
+struct TORCH_API FlipBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FlipBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dims;
+
+};
+#ifdef _WIN32
+struct RollBackward0 : public TraceableFunction {
+  TORCH_API RollBackward0() = default;
+#else
+struct TORCH_API RollBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "RollBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dims;
+  std::vector shifts;
+
+};
+#ifdef _WIN32
+struct Rot90Backward0 : public TraceableFunction {
+  TORCH_API Rot90Backward0() = default;
+#else
+struct TORCH_API Rot90Backward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "Rot90Backward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dims;
+  int64_t k = 0;
+
+};
+#ifdef _WIN32
+struct TakeBackward0 : public TraceableFunction {
+  TORCH_API TakeBackward0() = default;
+#else
+struct TORCH_API TakeBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "TakeBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    index_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable index_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct TanBackward0 : public TraceableFunction {
+  TORCH_API TanBackward0() = default;
+#else
+struct TORCH_API TanBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "TanBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct TanhBackward0 : public TraceableFunction {
+  TORCH_API TanhBackward0() = default;
+#else
+struct TORCH_API TanhBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "TanhBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct TopkBackward0 : public TraceableFunction {
+  TORCH_API TopkBackward0() = default;
+#else
+struct TORCH_API TopkBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "TopkBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  std::vector self_sym_sizes;
+  SavedVariable indices_;
+
+};
+#ifdef _WIN32
+struct TraceBackward0 : public TraceableFunction {
+  TORCH_API TraceBackward0() = default;
+#else
+struct TORCH_API TraceBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "TraceBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct TransposeBackward0 : public Node {
+  TORCH_API TransposeBackward0() = default;
+#else
+struct TORCH_API TransposeBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "TransposeBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim0 = 0;
+  int64_t dim1 = 0;
+
+};
+#ifdef _WIN32
+struct TransposeBackward1 : public TraceableFunction {
+  TORCH_API TransposeBackward1() = default;
+#else
+struct TORCH_API TransposeBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "TransposeBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim0 = 0;
+  int64_t dim1 = 0;
+
+};
+#ifdef _WIN32
+struct TriangularSolveBackward0 : public TraceableFunction {
+  TORCH_API TriangularSolveBackward0() = default;
+#else
+struct TORCH_API TriangularSolveBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "TriangularSolveBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    A_.reset_data();
+    self_.reset_data();
+    solution_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable A_;
+  SavedVariable self_;
+  bool transpose;
+  bool unitriangular;
+  bool upper;
+  SavedVariable solution_;
+
+};
+#ifdef _WIN32
+struct LinalgSolveTriangularBackward0 : public TraceableFunction {
+  TORCH_API LinalgSolveTriangularBackward0() = default;
+#else
+struct TORCH_API LinalgSolveTriangularBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LinalgSolveTriangularBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool left;
+  SavedVariable self_;
+  bool unitriangular;
+  bool upper;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct TrilBackward0 : public TraceableFunction {
+  TORCH_API TrilBackward0() = default;
+#else
+struct TORCH_API TrilBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "TrilBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t diagonal = 0;
+
+};
+#ifdef _WIN32
+struct TriuBackward0 : public TraceableFunction {
+  TORCH_API TriuBackward0() = default;
+#else
+struct TORCH_API TriuBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "TriuBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t diagonal = 0;
+
+};
+#ifdef _WIN32
+struct TruncBackward0 : public TraceableFunction {
+  TORCH_API TruncBackward0() = default;
+#else
+struct TORCH_API TruncBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "TruncBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct ToDenseBackward0 : public TraceableFunction {
+  TORCH_API ToDenseBackward0() = default;
+#else
+struct TORCH_API ToDenseBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ToDenseBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  ::std::optional masked_grad;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct ToSparseBackward0 : public TraceableFunction {
+  TORCH_API ToSparseBackward0() = default;
+#else
+struct TORCH_API ToSparseBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ToSparseBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Layout self_layout;
+  c10::OptionalArray self_self_sym_blocksize_opt;
+
+};
+#ifdef _WIN32
+struct ToSparseBackward1 : public TraceableFunction {
+  TORCH_API ToSparseBackward1() = default;
+#else
+struct TORCH_API ToSparseBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ToSparseBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Layout self_layout;
+  c10::OptionalArray self_self_sym_blocksize_opt;
+
+};
+#ifdef _WIN32
+struct ToSparseCsrBackward0 : public TraceableFunction {
+  TORCH_API ToSparseCsrBackward0() = default;
+#else
+struct TORCH_API ToSparseCsrBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ToSparseCsrBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Layout self_layout;
+  c10::OptionalArray self_self_sym_blocksize_opt;
+
+};
+#ifdef _WIN32
+struct ToSparseCscBackward0 : public TraceableFunction {
+  TORCH_API ToSparseCscBackward0() = default;
+#else
+struct TORCH_API ToSparseCscBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ToSparseCscBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Layout self_layout;
+  c10::OptionalArray self_self_sym_blocksize_opt;
+
+};
+#ifdef _WIN32
+struct ToSparseBsrBackward0 : public TraceableFunction {
+  TORCH_API ToSparseBsrBackward0() = default;
+#else
+struct TORCH_API ToSparseBsrBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ToSparseBsrBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Layout self_layout;
+  c10::OptionalArray self_self_sym_blocksize_opt;
+
+};
+#ifdef _WIN32
+struct ToSparseBscBackward0 : public TraceableFunction {
+  TORCH_API ToSparseBscBackward0() = default;
+#else
+struct TORCH_API ToSparseBscBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ToSparseBscBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Layout self_layout;
+  c10::OptionalArray self_self_sym_blocksize_opt;
+
+};
+#ifdef _WIN32
+struct ToMkldnnBackward0 : public TraceableFunction {
+  TORCH_API ToMkldnnBackward0() = default;
+#else
+struct TORCH_API ToMkldnnBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ToMkldnnBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct UnfoldBackward0 : public Node {
+  TORCH_API UnfoldBackward0() = default;
+#else
+struct TORCH_API UnfoldBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UnfoldBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dimension = 0;
+  std::vector self_sym_sizes;
+  int64_t size = 0;
+  int64_t step = 0;
+
+};
+#ifdef _WIN32
+struct UnfoldBackwardBackward0 : public TraceableFunction {
+  TORCH_API UnfoldBackwardBackward0() = default;
+#else
+struct TORCH_API UnfoldBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UnfoldBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  int64_t size = 0;
+  int64_t step = 0;
+
+};
+#ifdef _WIN32
+struct UniformBackward0 : public TraceableFunction {
+  TORCH_API UniformBackward0() = default;
+#else
+struct TORCH_API UniformBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UniformBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct UniqueBackward0 : public TraceableFunction {
+  TORCH_API UniqueBackward0() = default;
+#else
+struct TORCH_API UniqueBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UniqueBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct UniqueDimBackward0 : public TraceableFunction {
+  TORCH_API UniqueDimBackward0() = default;
+#else
+struct TORCH_API UniqueDimBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UniqueDimBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct UniqueConsecutiveBackward0 : public TraceableFunction {
+  TORCH_API UniqueConsecutiveBackward0() = default;
+#else
+struct TORCH_API UniqueConsecutiveBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UniqueConsecutiveBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct UniqueDimConsecutiveBackward0 : public TraceableFunction {
+  TORCH_API UniqueDimConsecutiveBackward0() = default;
+#else
+struct TORCH_API UniqueDimConsecutiveBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UniqueDimConsecutiveBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct Unique2Backward0 : public TraceableFunction {
+  TORCH_API Unique2Backward0() = default;
+#else
+struct TORCH_API Unique2Backward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "Unique2Backward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct UnsafeViewBackward0 : public TraceableFunction {
+  TORCH_API UnsafeViewBackward0() = default;
+#else
+struct TORCH_API UnsafeViewBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UnsafeViewBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct LiftBackward0 : public TraceableFunction {
+  TORCH_API LiftBackward0() = default;
+#else
+struct TORCH_API LiftBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LiftBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct LiftFreshBackward0 : public TraceableFunction {
+  TORCH_API LiftFreshBackward0() = default;
+#else
+struct TORCH_API LiftFreshBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LiftFreshBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct UnsqueezeBackward0 : public Node {
+  TORCH_API UnsqueezeBackward0() = default;
+#else
+struct TORCH_API UnsqueezeBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UnsqueezeBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+
+};
+#ifdef _WIN32
+struct UnsqueezeBackward1 : public TraceableFunction {
+  TORCH_API UnsqueezeBackward1() = default;
+#else
+struct TORCH_API UnsqueezeBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UnsqueezeBackward1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+
+};
+#ifdef _WIN32
+struct VarBackward0 : public TraceableFunction {
+  TORCH_API VarBackward0() = default;
+#else
+struct TORCH_API VarBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "VarBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  ::std::optional correction;
+  c10::OptionalArray dim;
+  bool keepdim;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct VarMeanBackward0 : public TraceableFunction {
+  TORCH_API VarMeanBackward0() = default;
+#else
+struct TORCH_API VarMeanBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "VarMeanBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  ::std::optional correction;
+  c10::OptionalArray dim;
+  bool keepdim;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct ViewBackward0 : public Node {
+  TORCH_API ViewBackward0() = default;
+#else
+struct TORCH_API ViewBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ViewBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct ViewBackwardAutogradNestedTensor0 : public Node {
+  TORCH_API ViewBackwardAutogradNestedTensor0() = default;
+#else
+struct TORCH_API ViewBackwardAutogradNestedTensor0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ViewBackwardAutogradNestedTensor0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct ViewAsRealBackward0 : public Node {
+  TORCH_API ViewAsRealBackward0() = default;
+#else
+struct TORCH_API ViewAsRealBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ViewAsRealBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct ViewAsComplexBackward0 : public Node {
+  TORCH_API ViewAsComplexBackward0() = default;
+#else
+struct TORCH_API ViewAsComplexBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ViewAsComplexBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct WhereBackward0 : public TraceableFunction {
+  TORCH_API WhereBackward0() = default;
+#else
+struct TORCH_API WhereBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "WhereBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    condition_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable condition_;
+
+};
+#ifdef _WIN32
+struct WeightNormInterfaceBackward0 : public TraceableFunction {
+  TORCH_API WeightNormInterfaceBackward0() = default;
+#else
+struct TORCH_API WeightNormInterfaceBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "WeightNormInterfaceBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    g_.reset_data();
+    v_.reset_data();
+    result1_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  SavedVariable g_;
+  SavedVariable v_;
+  SavedVariable result1_;
+
+};
+#ifdef _WIN32
+struct ZeroBackward0 : public TraceableFunction {
+  TORCH_API ZeroBackward0() = default;
+#else
+struct TORCH_API ZeroBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ZeroBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct SparseMaskBackward0 : public TraceableFunction {
+  TORCH_API SparseMaskBackward0() = default;
+#else
+struct TORCH_API SparseMaskBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SparseMaskBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    mask_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable mask_;
+  at::Layout self_layout;
+
+};
+#ifdef _WIN32
+struct SparseCooTensorWithDimsAndTensorsBackward0 : public TraceableFunction {
+  TORCH_API SparseCooTensorWithDimsAndTensorsBackward0() = default;
+#else
+struct TORCH_API SparseCooTensorWithDimsAndTensorsBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SparseCooTensorWithDimsAndTensorsBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct SparseCompressedTensorBackward0 : public TraceableFunction {
+  TORCH_API SparseCompressedTensorBackward0() = default;
+#else
+struct TORCH_API SparseCompressedTensorBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SparseCompressedTensorBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    values_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable values_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct SparseSumBackward0 : public TraceableFunction {
+  TORCH_API SparseSumBackward0() = default;
+#else
+struct TORCH_API SparseSumBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SparseSumBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dim;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct StandardGammaBackward0 : public TraceableFunction {
+  TORCH_API StandardGammaBackward0() = default;
+#else
+struct TORCH_API StandardGammaBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "StandardGammaBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct StandardGammaGradBackward0 : public TraceableFunction {
+  TORCH_API StandardGammaGradBackward0() = default;
+#else
+struct TORCH_API StandardGammaGradBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "StandardGammaGradBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct ValuesBackward0 : public Node {
+  TORCH_API ValuesBackward0() = default;
+#else
+struct TORCH_API ValuesBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ValuesBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct ValuesBackwardAutogradNestedTensor0 : public Node {
+  TORCH_API ValuesBackwardAutogradNestedTensor0() = default;
+#else
+struct TORCH_API ValuesBackwardAutogradNestedTensor0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ValuesBackwardAutogradNestedTensor0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct TrilinearBackward0 : public TraceableFunction {
+  TORCH_API TrilinearBackward0() = default;
+#else
+struct TORCH_API TrilinearBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "TrilinearBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    i1_.reset_data();
+    i2_.reset_data();
+    i3_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector expand1;
+  std::vector expand2;
+  std::vector expand3;
+  SavedVariable i1_;
+  SavedVariable i2_;
+  SavedVariable i3_;
+  std::vector sumdim;
+
+};
+#ifdef _WIN32
+struct ConstantPadNdBackward0 : public TraceableFunction {
+  TORCH_API ConstantPadNdBackward0() = default;
+#else
+struct TORCH_API ConstantPadNdBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ConstantPadNdBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector pad;
+
+};
+#ifdef _WIN32
+struct BinaryCrossEntropyBackward0 : public TraceableFunction {
+  TORCH_API BinaryCrossEntropyBackward0() = default;
+#else
+struct TORCH_API BinaryCrossEntropyBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "BinaryCrossEntropyBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    target_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t reduction = 0;
+  SavedVariable self_;
+  SavedVariable target_;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct BinaryCrossEntropyBackwardBackward0 : public TraceableFunction {
+  TORCH_API BinaryCrossEntropyBackwardBackward0() = default;
+#else
+struct TORCH_API BinaryCrossEntropyBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "BinaryCrossEntropyBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grad_output_.reset_data();
+    self_.reset_data();
+    target_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable grad_output_;
+  int64_t reduction = 0;
+  SavedVariable self_;
+  SavedVariable target_;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct BinaryCrossEntropyWithLogitsBackward0 : public TraceableFunction {
+  TORCH_API BinaryCrossEntropyWithLogitsBackward0() = default;
+#else
+struct TORCH_API BinaryCrossEntropyWithLogitsBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "BinaryCrossEntropyWithLogitsBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    pos_weight_.reset_data();
+    self_.reset_data();
+    target_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable pos_weight_;
+  int64_t reduction = 0;
+  SavedVariable self_;
+  SavedVariable target_;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct EmbeddingBackward0 : public TraceableFunction {
+  TORCH_API EmbeddingBackward0() = default;
+#else
+struct TORCH_API EmbeddingBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "EmbeddingBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable indices_;
+  c10::SymInt padding_idx;
+  bool scale_grad_by_freq;
+  bool sparse;
+  c10::SymInt weight_sym_argsize_0;
+
+};
+#ifdef _WIN32
+struct EmbeddingDenseBackwardBackward0 : public TraceableFunction {
+  TORCH_API EmbeddingDenseBackwardBackward0() = default;
+#else
+struct TORCH_API EmbeddingDenseBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "EmbeddingDenseBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable indices_;
+  c10::SymInt padding_idx;
+
+};
+#ifdef _WIN32
+struct EmbeddingBagBackward0 : public TraceableFunction {
+  TORCH_API EmbeddingBagBackward0() = default;
+#else
+struct TORCH_API EmbeddingBagBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "EmbeddingBagBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.reset_data();
+    offsets_.reset_data();
+    per_sample_weights_.reset_data();
+    weight_.reset_data();
+    result1_.reset_data();
+    result2_.reset_data();
+    result3_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable indices_;
+  int64_t mode = 0;
+  SavedVariable offsets_;
+  int64_t padding_idx = 0;
+  SavedVariable per_sample_weights_;
+  bool scale_grad_by_freq;
+  bool sparse;
+  SavedVariable weight_;
+  c10::SymInt weight_sym_argsize_0;
+  SavedVariable result1_;
+  SavedVariable result2_;
+  SavedVariable result3_;
+
+};
+#ifdef _WIN32
+struct EmbeddingBagBackwardBackward0 : public TraceableFunction {
+  TORCH_API EmbeddingBagBackwardBackward0() = default;
+#else
+struct TORCH_API EmbeddingBagBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "EmbeddingBagBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct EmbeddingBagDenseBackwardBackward0 : public TraceableFunction {
+  TORCH_API EmbeddingBagDenseBackwardBackward0() = default;
+#else
+struct TORCH_API EmbeddingBagDenseBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "EmbeddingBagDenseBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct EmbeddingRenormBackward0 : public TraceableFunction {
+  TORCH_API EmbeddingRenormBackward0() = default;
+#else
+struct TORCH_API EmbeddingRenormBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "EmbeddingRenormBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct MseLossBackward0 : public TraceableFunction {
+  TORCH_API MseLossBackward0() = default;
+#else
+struct TORCH_API MseLossBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MseLossBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    target_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t reduction = 0;
+  SavedVariable self_;
+  SavedVariable target_;
+
+};
+#ifdef _WIN32
+struct MultiMarginLossBackward0 : public TraceableFunction {
+  TORCH_API MultiMarginLossBackward0() = default;
+#else
+struct TORCH_API MultiMarginLossBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MultiMarginLossBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    target_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar margin;
+  at::Scalar p;
+  int64_t reduction = 0;
+  SavedVariable self_;
+  SavedVariable target_;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct MultilabelMarginLossBackward0 : public TraceableFunction {
+  TORCH_API MultilabelMarginLossBackward0() = default;
+#else
+struct TORCH_API MultilabelMarginLossBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MultilabelMarginLossBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    target_.reset_data();
+    is_target_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t reduction = 0;
+  SavedVariable self_;
+  SavedVariable target_;
+  SavedVariable is_target_;
+
+};
+#ifdef _WIN32
+struct NllLossBackward0 : public TraceableFunction {
+  TORCH_API NllLossBackward0() = default;
+#else
+struct TORCH_API NllLossBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NllLossBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    target_.reset_data();
+    weight_.reset_data();
+    total_weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::SymInt ignore_index;
+  int64_t reduction = 0;
+  SavedVariable self_;
+  SavedVariable target_;
+  SavedVariable weight_;
+  SavedVariable total_weight_;
+
+};
+#ifdef _WIN32
+struct NllLoss2DBackward0 : public TraceableFunction {
+  TORCH_API NllLoss2DBackward0() = default;
+#else
+struct TORCH_API NllLoss2DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NllLoss2DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    target_.reset_data();
+    weight_.reset_data();
+    total_weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::SymInt ignore_index;
+  int64_t reduction = 0;
+  SavedVariable self_;
+  SavedVariable target_;
+  SavedVariable weight_;
+  SavedVariable total_weight_;
+
+};
+#ifdef _WIN32
+struct SmoothL1LossBackward0 : public TraceableFunction {
+  TORCH_API SmoothL1LossBackward0() = default;
+#else
+struct TORCH_API SmoothL1LossBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SmoothL1LossBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    target_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  double beta;
+  int64_t reduction = 0;
+  SavedVariable self_;
+  SavedVariable target_;
+
+};
+#ifdef _WIN32
+struct HuberLossBackward0 : public TraceableFunction {
+  TORCH_API HuberLossBackward0() = default;
+#else
+struct TORCH_API HuberLossBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "HuberLossBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    target_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  double delta;
+  int64_t reduction = 0;
+  SavedVariable self_;
+  SavedVariable target_;
+
+};
+#ifdef _WIN32
+struct SoftMarginLossBackward0 : public TraceableFunction {
+  TORCH_API SoftMarginLossBackward0() = default;
+#else
+struct TORCH_API SoftMarginLossBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SoftMarginLossBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    target_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t reduction = 0;
+  SavedVariable self_;
+  SavedVariable target_;
+
+};
+#ifdef _WIN32
+struct ReluBackward0 : public TraceableFunction {
+  TORCH_API ReluBackward0() = default;
+#else
+struct TORCH_API ReluBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ReluBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct SiluBackward0 : public TraceableFunction {
+  TORCH_API SiluBackward0() = default;
+#else
+struct TORCH_API SiluBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SiluBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct MishBackward0 : public TraceableFunction {
+  TORCH_API MishBackward0() = default;
+#else
+struct TORCH_API MishBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MishBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct EluBackward0 : public TraceableFunction {
+  TORCH_API EluBackward0() = default;
+#else
+struct TORCH_API EluBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "EluBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar alpha;
+  at::Scalar input_scale;
+  at::Scalar scale;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct EluBackward1 : public TraceableFunction {
+  TORCH_API EluBackward1() = default;
+#else
+struct TORCH_API EluBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "EluBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar alpha;
+  at::Scalar input_scale;
+  at::Scalar scale;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct CeluBackward0 : public TraceableFunction {
+  TORCH_API CeluBackward0() = default;
+#else
+struct TORCH_API CeluBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CeluBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar alpha;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct CeluBackward1 : public TraceableFunction {
+  TORCH_API CeluBackward1() = default;
+#else
+struct TORCH_API CeluBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CeluBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar alpha;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct GeluBackward0 : public TraceableFunction {
+  TORCH_API GeluBackward0() = default;
+#else
+struct TORCH_API GeluBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "GeluBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::string approximate;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct GeluBackwardBackward0 : public TraceableFunction {
+  TORCH_API GeluBackwardBackward0() = default;
+#else
+struct TORCH_API GeluBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "GeluBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grad_output_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::string approximate;
+  SavedVariable grad_output_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct GluBackward0 : public TraceableFunction {
+  TORCH_API GluBackward0() = default;
+#else
+struct TORCH_API GluBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "GluBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct HardshrinkBackward0 : public TraceableFunction {
+  TORCH_API HardshrinkBackward0() = default;
+#else
+struct TORCH_API HardshrinkBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "HardshrinkBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar lambd;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct HardshrinkBackwardBackward0 : public TraceableFunction {
+  TORCH_API HardshrinkBackwardBackward0() = default;
+#else
+struct TORCH_API HardshrinkBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "HardshrinkBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar lambd;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct HardtanhBackward0 : public TraceableFunction {
+  TORCH_API HardtanhBackward0() = default;
+#else
+struct TORCH_API HardtanhBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "HardtanhBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar max_val;
+  at::Scalar min_val;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct LeakyReluBackward0 : public TraceableFunction {
+  TORCH_API LeakyReluBackward0() = default;
+#else
+struct TORCH_API LeakyReluBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LeakyReluBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar negative_slope;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct LeakyReluBackward1 : public TraceableFunction {
+  TORCH_API LeakyReluBackward1() = default;
+#else
+struct TORCH_API LeakyReluBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LeakyReluBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar negative_slope;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct LogSigmoidBackward0 : public TraceableFunction {
+  TORCH_API LogSigmoidBackward0() = default;
+#else
+struct TORCH_API LogSigmoidBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LogSigmoidBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    buffer_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+  SavedVariable buffer_;
+
+};
+#ifdef _WIN32
+struct LogSoftmaxBackward0 : public TraceableFunction {
+  TORCH_API LogSoftmaxBackward0() = default;
+#else
+struct TORCH_API LogSoftmaxBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LogSoftmaxBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  at::ScalarType self_scalar_type;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct SparseLogSoftmaxBackward0 : public TraceableFunction {
+  TORCH_API SparseLogSoftmaxBackward0() = default;
+#else
+struct TORCH_API SparseLogSoftmaxBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SparseLogSoftmaxBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct MaskedSoftmaxBackward0 : public TraceableFunction {
+  TORCH_API MaskedSoftmaxBackward0() = default;
+#else
+struct TORCH_API MaskedSoftmaxBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MaskedSoftmaxBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    mask_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  ::std::optional dim;
+  SavedVariable mask_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct PreluKernelBackward0 : public TraceableFunction {
+  TORCH_API PreluKernelBackward0() = default;
+#else
+struct TORCH_API PreluKernelBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "PreluKernelBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct PreluKernelBackwardBackward0 : public TraceableFunction {
+  TORCH_API PreluKernelBackwardBackward0() = default;
+#else
+struct TORCH_API PreluKernelBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "PreluKernelBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grad_output_.reset_data();
+    self_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable grad_output_;
+  at::TensorOptions grad_output_options;
+  SavedVariable self_;
+  torch::autograd::generated::TypeAndSize self_info;
+  at::TensorOptions self_options;
+  SavedVariable weight_;
+  at::TensorOptions weight_options;
+
+};
+#ifdef _WIN32
+struct RreluWithNoiseBackward0 : public TraceableFunction {
+  TORCH_API RreluWithNoiseBackward0() = default;
+#else
+struct TORCH_API RreluWithNoiseBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "RreluWithNoiseBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    noise_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar lower;
+  SavedVariable noise_;
+  SavedVariable self_;
+  bool training;
+  at::Scalar upper;
+
+};
+#ifdef _WIN32
+struct RreluWithNoiseBackward1 : public TraceableFunction {
+  TORCH_API RreluWithNoiseBackward1() = default;
+#else
+struct TORCH_API RreluWithNoiseBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "RreluWithNoiseBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    noise_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar lower;
+  SavedVariable noise_;
+  bool training;
+  at::Scalar upper;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct SoftmaxBackward0 : public TraceableFunction {
+  TORCH_API SoftmaxBackward0() = default;
+#else
+struct TORCH_API SoftmaxBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SoftmaxBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  at::ScalarType self_scalar_type;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct SparseSoftmaxBackward0 : public TraceableFunction {
+  TORCH_API SparseSoftmaxBackward0() = default;
+#else
+struct TORCH_API SparseSoftmaxBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SparseSoftmaxBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  SavedVariable self_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct SparseSparseMatmulBackward0 : public TraceableFunction {
+  TORCH_API SparseSparseMatmulBackward0() = default;
+#else
+struct TORCH_API SparseSparseMatmulBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SparseSparseMatmulBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct SoftplusBackward0 : public TraceableFunction {
+  TORCH_API SoftplusBackward0() = default;
+#else
+struct TORCH_API SoftplusBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SoftplusBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar beta;
+  SavedVariable self_;
+  at::Scalar threshold;
+
+};
+#ifdef _WIN32
+struct SoftshrinkBackward0 : public TraceableFunction {
+  TORCH_API SoftshrinkBackward0() = default;
+#else
+struct TORCH_API SoftshrinkBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SoftshrinkBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar lambd;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct ThresholdBackward0 : public TraceableFunction {
+  TORCH_API ThresholdBackward0() = default;
+#else
+struct TORCH_API ThresholdBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ThresholdBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+  at::Scalar threshold;
+
+};
+#ifdef _WIN32
+struct ThresholdBackward1 : public TraceableFunction {
+  TORCH_API ThresholdBackward1() = default;
+#else
+struct TORCH_API ThresholdBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ThresholdBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+  at::Scalar threshold;
+
+};
+#ifdef _WIN32
+struct ReflectionPad1DBackward0 : public TraceableFunction {
+  TORCH_API ReflectionPad1DBackward0() = default;
+#else
+struct TORCH_API ReflectionPad1DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ReflectionPad1DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector padding;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct ReflectionPad2DBackward0 : public TraceableFunction {
+  TORCH_API ReflectionPad2DBackward0() = default;
+#else
+struct TORCH_API ReflectionPad2DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ReflectionPad2DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector padding;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct ReflectionPad3DBackward0 : public TraceableFunction {
+  TORCH_API ReflectionPad3DBackward0() = default;
+#else
+struct TORCH_API ReflectionPad3DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ReflectionPad3DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector padding;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct ReplicationPad1DBackward0 : public TraceableFunction {
+  TORCH_API ReplicationPad1DBackward0() = default;
+#else
+struct TORCH_API ReplicationPad1DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ReplicationPad1DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector padding;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct ReplicationPad2DBackward0 : public TraceableFunction {
+  TORCH_API ReplicationPad2DBackward0() = default;
+#else
+struct TORCH_API ReplicationPad2DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ReplicationPad2DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector padding;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct ReplicationPad3DBackward0 : public TraceableFunction {
+  TORCH_API ReplicationPad3DBackward0() = default;
+#else
+struct TORCH_API ReplicationPad3DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ReplicationPad3DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector padding;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct UpsampleLinear1DBackward0 : public TraceableFunction {
+  TORCH_API UpsampleLinear1DBackward0() = default;
+#else
+struct TORCH_API UpsampleLinear1DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UpsampleLinear1DBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool align_corners;
+  std::vector output_size;
+  ::std::optional scales;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct UpsampleBilinear2DBackward0 : public TraceableFunction {
+  TORCH_API UpsampleBilinear2DBackward0() = default;
+#else
+struct TORCH_API UpsampleBilinear2DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UpsampleBilinear2DBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool align_corners;
+  std::vector output_size;
+  ::std::optional scales_h;
+  ::std::optional scales_w;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct UpsampleBilinear2DAaBackward0 : public TraceableFunction {
+  TORCH_API UpsampleBilinear2DAaBackward0() = default;
+#else
+struct TORCH_API UpsampleBilinear2DAaBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UpsampleBilinear2DAaBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool align_corners;
+  std::vector output_size;
+  ::std::optional scales_h;
+  ::std::optional scales_w;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct UpsampleBicubic2DBackward0 : public TraceableFunction {
+  TORCH_API UpsampleBicubic2DBackward0() = default;
+#else
+struct TORCH_API UpsampleBicubic2DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UpsampleBicubic2DBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool align_corners;
+  std::vector output_size;
+  ::std::optional scales_h;
+  ::std::optional scales_w;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct UpsampleBicubic2DAaBackward0 : public TraceableFunction {
+  TORCH_API UpsampleBicubic2DAaBackward0() = default;
+#else
+struct TORCH_API UpsampleBicubic2DAaBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UpsampleBicubic2DAaBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool align_corners;
+  std::vector output_size;
+  ::std::optional scales_h;
+  ::std::optional scales_w;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct UpsampleTrilinear3DBackward0 : public TraceableFunction {
+  TORCH_API UpsampleTrilinear3DBackward0() = default;
+#else
+struct TORCH_API UpsampleTrilinear3DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UpsampleTrilinear3DBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool align_corners;
+  std::vector output_size;
+  ::std::optional scales_d;
+  ::std::optional scales_h;
+  ::std::optional scales_w;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct UpsampleNearest1DBackward0 : public TraceableFunction {
+  TORCH_API UpsampleNearest1DBackward0() = default;
+#else
+struct TORCH_API UpsampleNearest1DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UpsampleNearest1DBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector output_size;
+  ::std::optional scales;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct UpsampleNearestExact1DBackward0 : public TraceableFunction {
+  TORCH_API UpsampleNearestExact1DBackward0() = default;
+#else
+struct TORCH_API UpsampleNearestExact1DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UpsampleNearestExact1DBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector output_size;
+  ::std::optional scales;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct UpsampleNearest2DBackward0 : public TraceableFunction {
+  TORCH_API UpsampleNearest2DBackward0() = default;
+#else
+struct TORCH_API UpsampleNearest2DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UpsampleNearest2DBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector output_size;
+  ::std::optional scales_h;
+  ::std::optional scales_w;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct UpsampleNearestExact2DBackward0 : public TraceableFunction {
+  TORCH_API UpsampleNearestExact2DBackward0() = default;
+#else
+struct TORCH_API UpsampleNearestExact2DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UpsampleNearestExact2DBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector output_size;
+  ::std::optional scales_h;
+  ::std::optional scales_w;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct UpsampleNearest3DBackward0 : public TraceableFunction {
+  TORCH_API UpsampleNearest3DBackward0() = default;
+#else
+struct TORCH_API UpsampleNearest3DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UpsampleNearest3DBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector output_size;
+  ::std::optional scales_d;
+  ::std::optional scales_h;
+  ::std::optional scales_w;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct UpsampleNearestExact3DBackward0 : public TraceableFunction {
+  TORCH_API UpsampleNearestExact3DBackward0() = default;
+#else
+struct TORCH_API UpsampleNearestExact3DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UpsampleNearestExact3DBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector output_size;
+  ::std::optional scales_d;
+  ::std::optional scales_h;
+  ::std::optional scales_w;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct PixelShuffleBackward0 : public TraceableFunction {
+  TORCH_API PixelShuffleBackward0() = default;
+#else
+struct TORCH_API PixelShuffleBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "PixelShuffleBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t upscale_factor = 0;
+
+};
+#ifdef _WIN32
+struct PixelUnshuffleBackward0 : public TraceableFunction {
+  TORCH_API PixelUnshuffleBackward0() = default;
+#else
+struct TORCH_API PixelUnshuffleBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "PixelUnshuffleBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t downscale_factor = 0;
+
+};
+#ifdef _WIN32
+struct ChannelShuffleBackward0 : public TraceableFunction {
+  TORCH_API ChannelShuffleBackward0() = default;
+#else
+struct TORCH_API ChannelShuffleBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ChannelShuffleBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::SymInt groups;
+
+};
+#ifdef _WIN32
+struct AdaptiveAvgPool2DBackward0 : public TraceableFunction {
+  TORCH_API AdaptiveAvgPool2DBackward0() = default;
+#else
+struct TORCH_API AdaptiveAvgPool2DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AdaptiveAvgPool2DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct AdaptiveAvgPool3DBackward0 : public TraceableFunction {
+  TORCH_API AdaptiveAvgPool3DBackward0() = default;
+#else
+struct TORCH_API AdaptiveAvgPool3DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AdaptiveAvgPool3DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct AdaptiveMaxPool2DBackward0 : public TraceableFunction {
+  TORCH_API AdaptiveMaxPool2DBackward0() = default;
+#else
+struct TORCH_API AdaptiveMaxPool2DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AdaptiveMaxPool2DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result1_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+  SavedVariable result1_;
+
+};
+#ifdef _WIN32
+struct AdaptiveMaxPool3DBackward0 : public TraceableFunction {
+  TORCH_API AdaptiveMaxPool3DBackward0() = default;
+#else
+struct TORCH_API AdaptiveMaxPool3DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AdaptiveMaxPool3DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result1_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+  SavedVariable result1_;
+
+};
+#ifdef _WIN32
+struct AvgPool2DBackward0 : public TraceableFunction {
+  TORCH_API AvgPool2DBackward0() = default;
+#else
+struct TORCH_API AvgPool2DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AvgPool2DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool ceil_mode;
+  bool count_include_pad;
+  ::std::optional divisor_override;
+  std::vector kernel_size;
+  std::vector padding;
+  SavedVariable self_;
+  std::vector stride;
+
+};
+#ifdef _WIN32
+struct AvgPool3DBackward0 : public TraceableFunction {
+  TORCH_API AvgPool3DBackward0() = default;
+#else
+struct TORCH_API AvgPool3DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AvgPool3DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool ceil_mode;
+  bool count_include_pad;
+  ::std::optional divisor_override;
+  std::vector kernel_size;
+  std::vector padding;
+  SavedVariable self_;
+  std::vector stride;
+
+};
+#ifdef _WIN32
+struct FractionalMaxPool2DBackward0 : public TraceableFunction {
+  TORCH_API FractionalMaxPool2DBackward0() = default;
+#else
+struct TORCH_API FractionalMaxPool2DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FractionalMaxPool2DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result1_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector kernel_size;
+  std::vector output_size;
+  SavedVariable self_;
+  SavedVariable result1_;
+
+};
+#ifdef _WIN32
+struct FractionalMaxPool3DBackward0 : public TraceableFunction {
+  TORCH_API FractionalMaxPool3DBackward0() = default;
+#else
+struct TORCH_API FractionalMaxPool3DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FractionalMaxPool3DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result1_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector kernel_size;
+  std::vector output_size;
+  SavedVariable self_;
+  SavedVariable result1_;
+
+};
+#ifdef _WIN32
+struct LinearBackward0 : public TraceableFunction {
+  TORCH_API LinearBackward0() = default;
+#else
+struct TORCH_API LinearBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LinearBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    input_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable input_;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct LinearBackwardBackward0 : public TraceableFunction {
+  TORCH_API LinearBackwardBackward0() = default;
+#else
+struct TORCH_API LinearBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LinearBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grad_output_.reset_data();
+    self_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable grad_output_;
+  SavedVariable self_;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct MaxPool2DBackward0 : public TraceableFunction {
+  TORCH_API MaxPool2DBackward0() = default;
+#else
+struct TORCH_API MaxPool2DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MaxPool2DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool ceil_mode;
+  std::vector dilation;
+  std::vector kernel_size;
+  std::vector padding;
+  SavedVariable self_;
+  std::vector stride;
+
+};
+#ifdef _WIN32
+struct MpsConvolutionBackward0 : public TraceableFunction {
+  TORCH_API MpsConvolutionBackward0() = default;
+#else
+struct TORCH_API MpsConvolutionBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MpsConvolutionBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dilation;
+  c10::SymInt groups;
+  std::vector padding;
+  SavedVariable self_;
+  std::vector stride;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct MpsConvolutionBackwardBackward0 : public TraceableFunction {
+  TORCH_API MpsConvolutionBackwardBackward0() = default;
+#else
+struct TORCH_API MpsConvolutionBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MpsConvolutionBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grad_output_.reset_data();
+    self_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dilation;
+  SavedVariable grad_output_;
+  c10::SymInt groups;
+  std::vector padding;
+  SavedVariable self_;
+  std::vector stride;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct MaxPool2DWithIndicesBackward0 : public TraceableFunction {
+  TORCH_API MaxPool2DWithIndicesBackward0() = default;
+#else
+struct TORCH_API MaxPool2DWithIndicesBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MaxPool2DWithIndicesBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result1_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool ceil_mode;
+  std::vector dilation;
+  std::vector kernel_size;
+  std::vector padding;
+  SavedVariable self_;
+  std::vector stride;
+  SavedVariable result1_;
+
+};
+#ifdef _WIN32
+struct MaxPool3DWithIndicesBackward0 : public TraceableFunction {
+  TORCH_API MaxPool3DWithIndicesBackward0() = default;
+#else
+struct TORCH_API MaxPool3DWithIndicesBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MaxPool3DWithIndicesBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result1_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool ceil_mode;
+  std::vector dilation;
+  std::vector kernel_size;
+  std::vector padding;
+  SavedVariable self_;
+  std::vector stride;
+  SavedVariable result1_;
+
+};
+#ifdef _WIN32
+struct MaxUnpool2DBackward0 : public TraceableFunction {
+  TORCH_API MaxUnpool2DBackward0() = default;
+#else
+struct TORCH_API MaxUnpool2DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MaxUnpool2DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable indices_;
+
+};
+#ifdef _WIN32
+struct MaxUnpool3DBackward0 : public TraceableFunction {
+  TORCH_API MaxUnpool3DBackward0() = default;
+#else
+struct TORCH_API MaxUnpool3DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MaxUnpool3DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable indices_;
+
+};
+#ifdef _WIN32
+struct ConvolutionBackward0 : public TraceableFunction {
+  TORCH_API ConvolutionBackward0() = default;
+#else
+struct TORCH_API ConvolutionBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ConvolutionBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    input_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::OptionalArray bias_sym_sizes_opt;
+  std::vector dilation;
+  c10::SymInt groups;
+  SavedVariable input_;
+  std::vector output_padding;
+  std::vector padding;
+  std::vector stride;
+  bool transposed;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct ConvolutionBackward1 : public TraceableFunction {
+  TORCH_API ConvolutionBackward1() = default;
+#else
+struct TORCH_API ConvolutionBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ConvolutionBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    input_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::OptionalArray bias_sym_sizes_opt;
+  std::vector dilation;
+  c10::SymInt groups;
+  SavedVariable input_;
+  std::vector output_padding;
+  std::vector padding;
+  std::vector stride;
+  bool transposed;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct ConvolutionBackwardBackward0 : public TraceableFunction {
+  TORCH_API ConvolutionBackwardBackward0() = default;
+#else
+struct TORCH_API ConvolutionBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ConvolutionBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grad_output_.reset_data();
+    input_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dilation;
+  SavedVariable grad_output_;
+  c10::SymInt groups;
+  SavedVariable input_;
+  std::vector output_padding;
+  std::vector padding;
+  std::vector stride;
+  bool transposed;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct ConvolutionOverrideableBackward0 : public TraceableFunction {
+  TORCH_API ConvolutionOverrideableBackward0() = default;
+#else
+struct TORCH_API ConvolutionOverrideableBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ConvolutionOverrideableBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    input_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dilation;
+  c10::SymInt groups;
+  SavedVariable input_;
+  std::vector output_padding;
+  std::vector padding;
+  std::vector stride;
+  bool transposed;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct ConvolutionBackwardOverrideableBackward0 : public TraceableFunction {
+  TORCH_API ConvolutionBackwardOverrideableBackward0() = default;
+#else
+struct TORCH_API ConvolutionBackwardOverrideableBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ConvolutionBackwardOverrideableBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grad_output_.reset_data();
+    input_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dilation;
+  SavedVariable grad_output_;
+  c10::SymInt groups;
+  SavedVariable input_;
+  std::vector output_padding;
+  std::vector padding;
+  std::vector stride;
+  bool transposed;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct SlowConvTranspose2DBackward0 : public TraceableFunction {
+  TORCH_API SlowConvTranspose2DBackward0() = default;
+#else
+struct TORCH_API SlowConvTranspose2DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SlowConvTranspose2DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::OptionalArray bias_sym_sizes_opt;
+  std::vector dilation;
+  std::vector output_padding;
+  std::vector padding;
+  SavedVariable self_;
+  std::vector stride;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct SlowConvTranspose3DBackward0 : public TraceableFunction {
+  TORCH_API SlowConvTranspose3DBackward0() = default;
+#else
+struct TORCH_API SlowConvTranspose3DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SlowConvTranspose3DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::OptionalArray bias_sym_sizes_opt;
+  std::vector dilation;
+  std::vector output_padding;
+  std::vector padding;
+  SavedVariable self_;
+  std::vector stride;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct SlowConv2DBackward0 : public TraceableFunction {
+  TORCH_API SlowConv2DBackward0() = default;
+#else
+struct TORCH_API SlowConv2DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SlowConv2DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector kernel_size;
+  std::vector padding;
+  SavedVariable self_;
+  std::vector stride;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct SlowConv2DBackwardBackward0 : public TraceableFunction {
+  TORCH_API SlowConv2DBackwardBackward0() = default;
+#else
+struct TORCH_API SlowConv2DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SlowConv2DBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grad_output_.reset_data();
+    self_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable grad_output_;
+  std::vector padding;
+  SavedVariable self_;
+  std::vector stride;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct ConvDepthwise2DBackward0 : public TraceableFunction {
+  TORCH_API ConvDepthwise2DBackward0() = default;
+#else
+struct TORCH_API ConvDepthwise2DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ConvDepthwise2DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::OptionalArray bias_sym_sizes_opt;
+  std::vector dilation;
+  std::vector padding;
+  SavedVariable self_;
+  std::vector stride;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct ConvDepthwise3DBackward0 : public TraceableFunction {
+  TORCH_API ConvDepthwise3DBackward0() = default;
+#else
+struct TORCH_API ConvDepthwise3DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ConvDepthwise3DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::OptionalArray bias_sym_sizes_opt;
+  std::vector dilation;
+  std::vector padding;
+  SavedVariable self_;
+  std::vector stride;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct SlowConv3DBackward0 : public TraceableFunction {
+  TORCH_API SlowConv3DBackward0() = default;
+#else
+struct TORCH_API SlowConv3DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SlowConv3DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::OptionalArray bias_sym_sizes_opt;
+  std::vector padding;
+  SavedVariable self_;
+  std::vector stride;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct SlowConvDilated2DBackward0 : public TraceableFunction {
+  TORCH_API SlowConvDilated2DBackward0() = default;
+#else
+struct TORCH_API SlowConvDilated2DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SlowConvDilated2DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::OptionalArray bias_sym_sizes_opt;
+  std::vector dilation;
+  std::vector padding;
+  SavedVariable self_;
+  std::vector stride;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct SlowConvDilated3DBackward0 : public TraceableFunction {
+  TORCH_API SlowConvDilated3DBackward0() = default;
+#else
+struct TORCH_API SlowConvDilated3DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SlowConvDilated3DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::OptionalArray bias_sym_sizes_opt;
+  std::vector dilation;
+  std::vector padding;
+  SavedVariable self_;
+  std::vector stride;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct Col2ImBackward0 : public TraceableFunction {
+  TORCH_API Col2ImBackward0() = default;
+#else
+struct TORCH_API Col2ImBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "Col2ImBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dilation;
+  std::vector kernel_size;
+  std::vector padding;
+  std::vector stride;
+
+};
+#ifdef _WIN32
+struct Im2ColBackward0 : public TraceableFunction {
+  TORCH_API Im2ColBackward0() = default;
+#else
+struct TORCH_API Im2ColBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "Im2ColBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dilation;
+  std::vector kernel_size;
+  std::vector padding;
+  c10::SymInt self_sym_argsize_minus_1;
+  c10::SymInt self_sym_argsize_minus_2;
+  std::vector stride;
+
+};
+#ifdef _WIN32
+struct AdaptiveAvgPool2DBackwardBackward0 : public TraceableFunction {
+  TORCH_API AdaptiveAvgPool2DBackwardBackward0() = default;
+#else
+struct TORCH_API AdaptiveAvgPool2DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AdaptiveAvgPool2DBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::SymInt grad_output_sym_argsize_minus_1;
+  c10::SymInt grad_output_sym_argsize_minus_2;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct AdaptiveAvgPool3DBackwardBackward0 : public TraceableFunction {
+  TORCH_API AdaptiveAvgPool3DBackwardBackward0() = default;
+#else
+struct TORCH_API AdaptiveAvgPool3DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AdaptiveAvgPool3DBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::SymInt grad_output_sym_argsize_minus_1;
+  c10::SymInt grad_output_sym_argsize_minus_2;
+  c10::SymInt grad_output_sym_argsize_minus_3;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct AdaptiveMaxPool2DBackwardBackward0 : public TraceableFunction {
+  TORCH_API AdaptiveMaxPool2DBackwardBackward0() = default;
+#else
+struct TORCH_API AdaptiveMaxPool2DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AdaptiveMaxPool2DBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable indices_;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct AdaptiveMaxPool3DBackwardBackward0 : public TraceableFunction {
+  TORCH_API AdaptiveMaxPool3DBackwardBackward0() = default;
+#else
+struct TORCH_API AdaptiveMaxPool3DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AdaptiveMaxPool3DBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable indices_;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct AvgPool2DBackwardBackward0 : public TraceableFunction {
+  TORCH_API AvgPool2DBackwardBackward0() = default;
+#else
+struct TORCH_API AvgPool2DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AvgPool2DBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool ceil_mode;
+  bool count_include_pad;
+  ::std::optional divisor_override;
+  std::vector kernel_size;
+  std::vector padding;
+  torch::autograd::generated::TypeAndSize self_info;
+  std::vector stride;
+
+};
+#ifdef _WIN32
+struct AvgPool3DBackwardBackward0 : public TraceableFunction {
+  TORCH_API AvgPool3DBackwardBackward0() = default;
+#else
+struct TORCH_API AvgPool3DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AvgPool3DBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool ceil_mode;
+  bool count_include_pad;
+  ::std::optional divisor_override;
+  std::vector kernel_size;
+  std::vector padding;
+  torch::autograd::generated::TypeAndSize self_info;
+  std::vector stride;
+
+};
+#ifdef _WIN32
+struct EluBackwardBackward0 : public TraceableFunction {
+  TORCH_API EluBackwardBackward0() = default;
+#else
+struct TORCH_API EluBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "EluBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grad_output_.reset_data();
+    self_or_result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar alpha;
+  SavedVariable grad_output_;
+  at::Scalar input_scale;
+  bool is_result;
+  at::Scalar scale;
+  SavedVariable self_or_result_;
+
+};
+#ifdef _WIN32
+struct FractionalMaxPool2DBackwardBackward0 : public TraceableFunction {
+  TORCH_API FractionalMaxPool2DBackwardBackward0() = default;
+#else
+struct TORCH_API FractionalMaxPool2DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FractionalMaxPool2DBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable indices_;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct FractionalMaxPool3DBackwardBackward0 : public TraceableFunction {
+  TORCH_API FractionalMaxPool3DBackwardBackward0() = default;
+#else
+struct TORCH_API FractionalMaxPool3DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FractionalMaxPool3DBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable indices_;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct GluBackwardBackward0 : public TraceableFunction {
+  TORCH_API GluBackwardBackward0() = default;
+#else
+struct TORCH_API GluBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "GluBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grad_output_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  SavedVariable grad_output_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct HardtanhBackwardBackward0 : public TraceableFunction {
+  TORCH_API HardtanhBackwardBackward0() = default;
+#else
+struct TORCH_API HardtanhBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "HardtanhBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar max_val;
+  at::Scalar min_val;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct LogSigmoidBackwardBackward0 : public TraceableFunction {
+  TORCH_API LogSigmoidBackwardBackward0() = default;
+#else
+struct TORCH_API LogSigmoidBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LogSigmoidBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    buffer_.reset_data();
+    grad_output_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable buffer_;
+  SavedVariable grad_output_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct LogSoftmaxBackwardDataBackward0 : public TraceableFunction {
+  TORCH_API LogSoftmaxBackwardDataBackward0() = default;
+#else
+struct TORCH_API LogSoftmaxBackwardDataBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LogSoftmaxBackwardDataBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grad_output_.reset_data();
+    output_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  SavedVariable grad_output_;
+  SavedVariable output_;
+
+};
+#ifdef _WIN32
+struct LeakyReluBackwardBackward0 : public TraceableFunction {
+  TORCH_API LeakyReluBackwardBackward0() = default;
+#else
+struct TORCH_API LeakyReluBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LeakyReluBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar negative_slope;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct MaxPool2DBackwardBackward0 : public TraceableFunction {
+  TORCH_API MaxPool2DBackwardBackward0() = default;
+#else
+struct TORCH_API MaxPool2DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MaxPool2DBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct MaxPool2DWithIndicesBackwardBackward0 : public TraceableFunction {
+  TORCH_API MaxPool2DWithIndicesBackwardBackward0() = default;
+#else
+struct TORCH_API MaxPool2DWithIndicesBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MaxPool2DWithIndicesBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable indices_;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct MaxPool3DWithIndicesBackwardBackward0 : public TraceableFunction {
+  TORCH_API MaxPool3DWithIndicesBackwardBackward0() = default;
+#else
+struct TORCH_API MaxPool3DWithIndicesBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MaxPool3DWithIndicesBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    indices_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable indices_;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct MseLossBackwardBackward0 : public TraceableFunction {
+  TORCH_API MseLossBackwardBackward0() = default;
+#else
+struct TORCH_API MseLossBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MseLossBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grad_output_.reset_data();
+    self_.reset_data();
+    target_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable grad_output_;
+  int64_t reduction = 0;
+  SavedVariable self_;
+  SavedVariable target_;
+
+};
+#ifdef _WIN32
+struct NllLossBackwardBackward0 : public TraceableFunction {
+  TORCH_API NllLossBackwardBackward0() = default;
+#else
+struct TORCH_API NllLossBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NllLossBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    target_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::SymInt ignore_index;
+  int64_t reduction = 0;
+  SavedVariable target_;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct NllLoss2DBackwardBackward0 : public TraceableFunction {
+  TORCH_API NllLoss2DBackwardBackward0() = default;
+#else
+struct TORCH_API NllLoss2DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NllLoss2DBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    target_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::SymInt ignore_index;
+  int64_t reduction = 0;
+  SavedVariable target_;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct RreluWithNoiseBackwardBackward0 : public TraceableFunction {
+  TORCH_API RreluWithNoiseBackwardBackward0() = default;
+#else
+struct TORCH_API RreluWithNoiseBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "RreluWithNoiseBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    noise_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar lower;
+  SavedVariable noise_;
+  SavedVariable self_;
+  bool training;
+  at::Scalar upper;
+
+};
+#ifdef _WIN32
+struct ReflectionPad1DBackwardBackward0 : public TraceableFunction {
+  TORCH_API ReflectionPad1DBackwardBackward0() = default;
+#else
+struct TORCH_API ReflectionPad1DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ReflectionPad1DBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector padding;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct ReflectionPad2DBackwardBackward0 : public TraceableFunction {
+  TORCH_API ReflectionPad2DBackwardBackward0() = default;
+#else
+struct TORCH_API ReflectionPad2DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ReflectionPad2DBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector padding;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct ReflectionPad3DBackwardBackward0 : public TraceableFunction {
+  TORCH_API ReflectionPad3DBackwardBackward0() = default;
+#else
+struct TORCH_API ReflectionPad3DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ReflectionPad3DBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector padding;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct ReplicationPad1DBackwardBackward0 : public TraceableFunction {
+  TORCH_API ReplicationPad1DBackwardBackward0() = default;
+#else
+struct TORCH_API ReplicationPad1DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ReplicationPad1DBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector padding;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct ReplicationPad2DBackwardBackward0 : public TraceableFunction {
+  TORCH_API ReplicationPad2DBackwardBackward0() = default;
+#else
+struct TORCH_API ReplicationPad2DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ReplicationPad2DBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector padding;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct ReplicationPad3DBackwardBackward0 : public TraceableFunction {
+  TORCH_API ReplicationPad3DBackwardBackward0() = default;
+#else
+struct TORCH_API ReplicationPad3DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ReplicationPad3DBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector padding;
+  torch::autograd::generated::TypeAndSize self_info;
+
+};
+#ifdef _WIN32
+struct SparseSampledAddmmBackward0 : public TraceableFunction {
+  TORCH_API SparseSampledAddmmBackward0() = default;
+#else
+struct TORCH_API SparseSampledAddmmBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SparseSampledAddmmBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    mat1_.reset_data();
+    mat2_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar alpha;
+  at::Scalar beta;
+  SavedVariable mat1_;
+  SavedVariable mat2_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct SparseMmReduceImplBackward0 : public TraceableFunction {
+  TORCH_API SparseMmReduceImplBackward0() = default;
+#else
+struct TORCH_API SparseMmReduceImplBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SparseMmReduceImplBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.reset_data();
+    result1_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  std::string reduce;
+  SavedVariable self_;
+  SavedVariable result1_;
+
+};
+#ifdef _WIN32
+struct SmoothL1LossBackwardBackward0 : public TraceableFunction {
+  TORCH_API SmoothL1LossBackwardBackward0() = default;
+#else
+struct TORCH_API SmoothL1LossBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SmoothL1LossBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grad_output_.reset_data();
+    self_.reset_data();
+    target_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  double beta;
+  SavedVariable grad_output_;
+  int64_t reduction = 0;
+  SavedVariable self_;
+  SavedVariable target_;
+
+};
+#ifdef _WIN32
+struct HuberLossBackwardBackward0 : public TraceableFunction {
+  TORCH_API HuberLossBackwardBackward0() = default;
+#else
+struct TORCH_API HuberLossBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "HuberLossBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grad_output_.reset_data();
+    self_.reset_data();
+    target_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  double delta;
+  SavedVariable grad_output_;
+  int64_t reduction = 0;
+  SavedVariable self_;
+  SavedVariable target_;
+
+};
+#ifdef _WIN32
+struct SoftplusBackwardBackward0 : public TraceableFunction {
+  TORCH_API SoftplusBackwardBackward0() = default;
+#else
+struct TORCH_API SoftplusBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SoftplusBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grad_output_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar beta;
+  SavedVariable grad_output_;
+  SavedVariable self_;
+  at::Scalar threshold;
+
+};
+#ifdef _WIN32
+struct SoftmaxBackwardDataBackward0 : public TraceableFunction {
+  TORCH_API SoftmaxBackwardDataBackward0() = default;
+#else
+struct TORCH_API SoftmaxBackwardDataBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SoftmaxBackwardDataBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grad_output_.reset_data();
+    output_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  SavedVariable grad_output_;
+  at::ScalarType input_dtype;
+  SavedVariable output_;
+
+};
+#ifdef _WIN32
+struct SoftMarginLossBackwardBackward0 : public TraceableFunction {
+  TORCH_API SoftMarginLossBackwardBackward0() = default;
+#else
+struct TORCH_API SoftMarginLossBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SoftMarginLossBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grad_output_.reset_data();
+    self_.reset_data();
+    target_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable grad_output_;
+  int64_t reduction = 0;
+  SavedVariable self_;
+  SavedVariable target_;
+
+};
+#ifdef _WIN32
+struct SoftshrinkBackwardBackward0 : public TraceableFunction {
+  TORCH_API SoftshrinkBackwardBackward0() = default;
+#else
+struct TORCH_API SoftshrinkBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SoftshrinkBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar lambd;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct ThresholdBackwardBackward0 : public TraceableFunction {
+  TORCH_API ThresholdBackwardBackward0() = default;
+#else
+struct TORCH_API ThresholdBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ThresholdBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+  at::Scalar threshold;
+
+};
+#ifdef _WIN32
+struct UpsampleLinear1DBackwardBackward0 : public TraceableFunction {
+  TORCH_API UpsampleLinear1DBackwardBackward0() = default;
+#else
+struct TORCH_API UpsampleLinear1DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UpsampleLinear1DBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool align_corners;
+  std::vector output_size;
+  ::std::optional scales;
+
+};
+#ifdef _WIN32
+struct UpsampleBilinear2DBackwardBackward0 : public TraceableFunction {
+  TORCH_API UpsampleBilinear2DBackwardBackward0() = default;
+#else
+struct TORCH_API UpsampleBilinear2DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UpsampleBilinear2DBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool align_corners;
+  std::vector output_size;
+  ::std::optional scales_h;
+  ::std::optional scales_w;
+
+};
+#ifdef _WIN32
+struct UpsampleBilinear2DAaBackwardBackward0 : public TraceableFunction {
+  TORCH_API UpsampleBilinear2DAaBackwardBackward0() = default;
+#else
+struct TORCH_API UpsampleBilinear2DAaBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UpsampleBilinear2DAaBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool align_corners;
+  std::vector output_size;
+  ::std::optional scales_h;
+  ::std::optional scales_w;
+
+};
+#ifdef _WIN32
+struct UpsampleBicubic2DBackwardBackward0 : public TraceableFunction {
+  TORCH_API UpsampleBicubic2DBackwardBackward0() = default;
+#else
+struct TORCH_API UpsampleBicubic2DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UpsampleBicubic2DBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool align_corners;
+  std::vector output_size;
+  ::std::optional scales_h;
+  ::std::optional scales_w;
+
+};
+#ifdef _WIN32
+struct UpsampleBicubic2DAaBackwardBackward0 : public TraceableFunction {
+  TORCH_API UpsampleBicubic2DAaBackwardBackward0() = default;
+#else
+struct TORCH_API UpsampleBicubic2DAaBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UpsampleBicubic2DAaBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool align_corners;
+  std::vector output_size;
+  ::std::optional scales_h;
+  ::std::optional scales_w;
+
+};
+#ifdef _WIN32
+struct UpsampleTrilinear3DBackwardBackward0 : public TraceableFunction {
+  TORCH_API UpsampleTrilinear3DBackwardBackward0() = default;
+#else
+struct TORCH_API UpsampleTrilinear3DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UpsampleTrilinear3DBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool align_corners;
+  std::vector output_size;
+  ::std::optional scales_d;
+  ::std::optional scales_h;
+  ::std::optional scales_w;
+
+};
+#ifdef _WIN32
+struct UpsampleNearest1DBackwardBackward0 : public TraceableFunction {
+  TORCH_API UpsampleNearest1DBackwardBackward0() = default;
+#else
+struct TORCH_API UpsampleNearest1DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UpsampleNearest1DBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector output_size;
+  ::std::optional scales;
+
+};
+#ifdef _WIN32
+struct UpsampleNearestExact1DBackwardBackward0 : public TraceableFunction {
+  TORCH_API UpsampleNearestExact1DBackwardBackward0() = default;
+#else
+struct TORCH_API UpsampleNearestExact1DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UpsampleNearestExact1DBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector output_size;
+  ::std::optional scales;
+
+};
+#ifdef _WIN32
+struct UpsampleNearest2DBackwardBackward0 : public TraceableFunction {
+  TORCH_API UpsampleNearest2DBackwardBackward0() = default;
+#else
+struct TORCH_API UpsampleNearest2DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UpsampleNearest2DBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector output_size;
+  ::std::optional scales_h;
+  ::std::optional scales_w;
+
+};
+#ifdef _WIN32
+struct UpsampleNearestExact2DBackwardBackward0 : public TraceableFunction {
+  TORCH_API UpsampleNearestExact2DBackwardBackward0() = default;
+#else
+struct TORCH_API UpsampleNearestExact2DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UpsampleNearestExact2DBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector output_size;
+  ::std::optional scales_h;
+  ::std::optional scales_w;
+
+};
+#ifdef _WIN32
+struct UpsampleNearest3DBackwardBackward0 : public TraceableFunction {
+  TORCH_API UpsampleNearest3DBackwardBackward0() = default;
+#else
+struct TORCH_API UpsampleNearest3DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UpsampleNearest3DBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector output_size;
+  ::std::optional scales_d;
+  ::std::optional scales_h;
+  ::std::optional scales_w;
+
+};
+#ifdef _WIN32
+struct UpsampleNearestExact3DBackwardBackward0 : public TraceableFunction {
+  TORCH_API UpsampleNearestExact3DBackwardBackward0() = default;
+#else
+struct TORCH_API UpsampleNearestExact3DBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UpsampleNearestExact3DBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector output_size;
+  ::std::optional scales_d;
+  ::std::optional scales_h;
+  ::std::optional scales_w;
+
+};
+#ifdef _WIN32
+struct SigmoidBackwardBackward0 : public TraceableFunction {
+  TORCH_API SigmoidBackwardBackward0() = default;
+#else
+struct TORCH_API SigmoidBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SigmoidBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grad_output_.reset_data();
+    output_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable grad_output_;
+  SavedVariable output_;
+
+};
+#ifdef _WIN32
+struct TanhBackwardBackward0 : public TraceableFunction {
+  TORCH_API TanhBackwardBackward0() = default;
+#else
+struct TORCH_API TanhBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "TanhBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grad_output_.reset_data();
+    output_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable grad_output_;
+  SavedVariable output_;
+
+};
+#ifdef _WIN32
+struct CudnnCtcLossBackward0 : public TraceableFunction {
+  TORCH_API CudnnCtcLossBackward0() = default;
+#else
+struct TORCH_API CudnnCtcLossBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CudnnCtcLossBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result0_.reset_data();
+    result1_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool zero_infinity;
+  SavedVariable result0_;
+  SavedVariable result1_;
+
+};
+#ifdef _WIN32
+struct CudnnCtcLossBackward1 : public TraceableFunction {
+  TORCH_API CudnnCtcLossBackward1() = default;
+#else
+struct TORCH_API CudnnCtcLossBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CudnnCtcLossBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result0_.reset_data();
+    result1_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool zero_infinity;
+  SavedVariable result0_;
+  SavedVariable result1_;
+
+};
+#ifdef _WIN32
+struct CudnnConvolutionTransposeBackward0 : public TraceableFunction {
+  TORCH_API CudnnConvolutionTransposeBackward0() = default;
+#else
+struct TORCH_API CudnnConvolutionTransposeBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CudnnConvolutionTransposeBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dilation;
+  c10::SymInt groups;
+  std::vector output_padding;
+  std::vector padding;
+  SavedVariable self_;
+  std::vector stride;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct MpsConvolutionTransposeBackward0 : public TraceableFunction {
+  TORCH_API MpsConvolutionTransposeBackward0() = default;
+#else
+struct TORCH_API MpsConvolutionTransposeBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MpsConvolutionTransposeBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dilation;
+  c10::SymInt groups;
+  std::vector output_padding;
+  std::vector padding;
+  SavedVariable self_;
+  std::vector stride;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct CudnnConvolutionBackward0 : public TraceableFunction {
+  TORCH_API CudnnConvolutionBackward0() = default;
+#else
+struct TORCH_API CudnnConvolutionBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CudnnConvolutionBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dilation;
+  c10::SymInt groups;
+  std::vector padding;
+  SavedVariable self_;
+  std::vector stride;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct CudnnGridSamplerBackward0 : public TraceableFunction {
+  TORCH_API CudnnGridSamplerBackward0() = default;
+#else
+struct TORCH_API CudnnGridSamplerBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CudnnGridSamplerBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grid_.reset_data();
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable grid_;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct CudnnAffineGridGeneratorBackward0 : public TraceableFunction {
+  TORCH_API CudnnAffineGridGeneratorBackward0() = default;
+#else
+struct TORCH_API CudnnAffineGridGeneratorBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CudnnAffineGridGeneratorBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t C = 0;
+  int64_t H = 0;
+  int64_t N = 0;
+  int64_t W = 0;
+
+};
+#ifdef _WIN32
+struct CudnnBatchNormBackward0 : public TraceableFunction {
+  TORCH_API CudnnBatchNormBackward0() = default;
+#else
+struct TORCH_API CudnnBatchNormBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CudnnBatchNormBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    input_.reset_data();
+    running_mean_.reset_data();
+    running_var_.reset_data();
+    weight_.reset_data();
+    result1_.reset_data();
+    result2_.reset_data();
+    result3_.reset_data();
+  }
+  bool retain_variables = true;
+  void will_release_variables() override {
+    retain_variables = false;
+  }
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  double epsilon;
+  SavedVariable input_;
+  SavedVariable running_mean_;
+  SavedVariable running_var_;
+  bool training;
+  SavedVariable weight_;
+  SavedVariable result1_;
+  SavedVariable result2_;
+  SavedVariable result3_;
+
+};
+#ifdef _WIN32
+struct CudnnBatchNormBackwardBackward0 : public TraceableFunction {
+  TORCH_API CudnnBatchNormBackwardBackward0() = default;
+#else
+struct TORCH_API CudnnBatchNormBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CudnnBatchNormBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grad_output_.reset_data();
+    input_.reset_data();
+    reserveSpace_.reset_data();
+    running_mean_.reset_data();
+    running_var_.reset_data();
+    save_mean_.reset_data();
+    save_var_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  double epsilon;
+  SavedVariable grad_output_;
+  SavedVariable input_;
+  SavedVariable reserveSpace_;
+  SavedVariable running_mean_;
+  SavedVariable running_var_;
+  SavedVariable save_mean_;
+  SavedVariable save_var_;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct NnpackSpatialConvolutionBackward0 : public TraceableFunction {
+  TORCH_API NnpackSpatialConvolutionBackward0() = default;
+#else
+struct TORCH_API NnpackSpatialConvolutionBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NnpackSpatialConvolutionBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    input_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::OptionalArray bias_sym_sizes_opt;
+  SavedVariable input_;
+  std::vector padding;
+  std::vector stride;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct LstmMpsBackward0 : public TraceableFunction {
+  TORCH_API LstmMpsBackward0() = default;
+#else
+struct TORCH_API LstmMpsBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LstmMpsBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    hx_.clear();
+    hx_released_ = true;
+    input_.reset_data();
+    params_.clear();
+    params_released_ = true;
+    result3_.reset_data();
+    result4_.reset_data();
+    result5_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool batch_first;
+  bool bidirectional;
+  double dropout;
+  bool has_biases;
+  std::vector hx_;
+  bool hx_released_ = false;
+  SavedVariable input_;
+  int64_t num_layers = 0;
+  std::vector params_;
+  bool params_released_ = false;
+  bool train;
+  SavedVariable result3_;
+  SavedVariable result4_;
+  SavedVariable result5_;
+  size_t hx_size_;
+  size_t params_size_;
+};
+#ifdef _WIN32
+struct CudnnRnnBackward0 : public TraceableFunction {
+  TORCH_API CudnnRnnBackward0() = default;
+#else
+struct TORCH_API CudnnRnnBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CudnnRnnBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    cx_.reset_data();
+    dropout_state_.reset_data();
+    hx_.reset_data();
+    input_.reset_data();
+    weight_.clear();
+    weight_released_ = true;
+    result0_.reset_data();
+    result3_.reset_data();
+    result4_.reset_data();
+  }
+  bool retain_variables = true;
+  void will_release_variables() override {
+    retain_variables = false;
+  }
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool batch_first;
+  std::vector batch_sizes;
+  bool bidirectional;
+  SavedVariable cx_;
+  double dropout;
+  SavedVariable dropout_state_;
+  c10::SymInt hidden_size;
+  SavedVariable hx_;
+  SavedVariable input_;
+  int64_t mode = 0;
+  int64_t num_layers = 0;
+  c10::SymInt proj_size;
+  bool train;
+  std::vector weight_;
+  bool weight_released_ = false;
+  int64_t weight_stride0 = 0;
+  SavedVariable result0_;
+  SavedVariable result3_;
+  SavedVariable result4_;
+  size_t weight_size_;
+};
+#ifdef _WIN32
+struct CudnnRnnBackwardBackward0 : public TraceableFunction {
+  TORCH_API CudnnRnnBackwardBackward0() = default;
+#else
+struct TORCH_API CudnnRnnBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "CudnnRnnBackwardBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+  size_t weight_size_;
+};
+#ifdef _WIN32
+struct MiopenConvolutionTransposeBackward0 : public TraceableFunction {
+  TORCH_API MiopenConvolutionTransposeBackward0() = default;
+#else
+struct TORCH_API MiopenConvolutionTransposeBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MiopenConvolutionTransposeBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::OptionalArray bias_sym_sizes_opt;
+  std::vector dilation;
+  c10::SymInt groups;
+  std::vector output_padding;
+  std::vector padding;
+  SavedVariable self_;
+  std::vector stride;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct MiopenConvolutionBackward0 : public TraceableFunction {
+  TORCH_API MiopenConvolutionBackward0() = default;
+#else
+struct TORCH_API MiopenConvolutionBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MiopenConvolutionBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::OptionalArray bias_sym_sizes_opt;
+  std::vector dilation;
+  c10::SymInt groups;
+  std::vector padding;
+  SavedVariable self_;
+  std::vector stride;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct MiopenDepthwiseConvolutionBackward0 : public TraceableFunction {
+  TORCH_API MiopenDepthwiseConvolutionBackward0() = default;
+#else
+struct TORCH_API MiopenDepthwiseConvolutionBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MiopenDepthwiseConvolutionBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::OptionalArray bias_sym_sizes_opt;
+  std::vector dilation;
+  c10::SymInt groups;
+  std::vector padding;
+  SavedVariable self_;
+  std::vector stride;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct MiopenBatchNormBackward0 : public TraceableFunction {
+  TORCH_API MiopenBatchNormBackward0() = default;
+#else
+struct TORCH_API MiopenBatchNormBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MiopenBatchNormBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    input_.reset_data();
+    running_mean_.reset_data();
+    running_var_.reset_data();
+    weight_.reset_data();
+    result1_.reset_data();
+    result2_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  double epsilon;
+  SavedVariable input_;
+  SavedVariable running_mean_;
+  SavedVariable running_var_;
+  bool training;
+  SavedVariable weight_;
+  SavedVariable result1_;
+  SavedVariable result2_;
+
+};
+#ifdef _WIN32
+struct MiopenBatchNormBackwardBackward0 : public TraceableFunction {
+  TORCH_API MiopenBatchNormBackwardBackward0() = default;
+#else
+struct TORCH_API MiopenBatchNormBackwardBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MiopenBatchNormBackwardBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    grad_output_.reset_data();
+    input_.reset_data();
+    running_mean_.reset_data();
+    running_var_.reset_data();
+    save_mean_.reset_data();
+    save_var_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  double epsilon;
+  SavedVariable grad_output_;
+  SavedVariable input_;
+  SavedVariable running_mean_;
+  SavedVariable running_var_;
+  SavedVariable save_mean_;
+  SavedVariable save_var_;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct MiopenRnnBackward0 : public TraceableFunction {
+  TORCH_API MiopenRnnBackward0() = default;
+#else
+struct TORCH_API MiopenRnnBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MiopenRnnBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    cx_.reset_data();
+    dropout_state_.reset_data();
+    hx_.reset_data();
+    input_.reset_data();
+    weight_.clear();
+    weight_released_ = true;
+    result0_.reset_data();
+    result3_.reset_data();
+    result4_.reset_data();
+  }
+  bool retain_variables = true;
+  void will_release_variables() override {
+    retain_variables = false;
+  }
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool batch_first;
+  std::vector batch_sizes;
+  bool bidirectional;
+  SavedVariable cx_;
+  double dropout;
+  SavedVariable dropout_state_;
+  int64_t hidden_size = 0;
+  SavedVariable hx_;
+  SavedVariable input_;
+  int64_t mode = 0;
+  int64_t num_layers = 0;
+  bool train;
+  std::vector weight_;
+  bool weight_released_ = false;
+  int64_t weight_stride0 = 0;
+  SavedVariable result0_;
+  SavedVariable result3_;
+  SavedVariable result4_;
+  size_t weight_size_;
+};
+#ifdef _WIN32
+struct MkldnnRnnLayerBackward0 : public TraceableFunction {
+  TORCH_API MkldnnRnnLayerBackward0() = default;
+#else
+struct TORCH_API MkldnnRnnLayerBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MkldnnRnnLayerBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    cx__.reset_data();
+    hx__.reset_data();
+    input_.reset_data();
+    weight0_.reset_data();
+    weight1_.reset_data();
+    weight2_.reset_data();
+    weight3_.reset_data();
+    result0_.reset_data();
+    result1_.reset_data();
+    result2_.reset_data();
+    result3_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool batch_first;
+  std::vector batch_sizes;
+  bool bidirectional;
+  SavedVariable cx__;
+  bool has_biases;
+  int64_t hidden_size = 0;
+  SavedVariable hx__;
+  SavedVariable input_;
+  int64_t mode = 0;
+  int64_t num_layers = 0;
+  bool reverse;
+  bool train;
+  SavedVariable weight0_;
+  SavedVariable weight1_;
+  SavedVariable weight2_;
+  SavedVariable weight3_;
+  SavedVariable result0_;
+  SavedVariable result1_;
+  SavedVariable result2_;
+  SavedVariable result3_;
+
+};
+#ifdef _WIN32
+struct MkldnnConvolutionBackward0 : public TraceableFunction {
+  TORCH_API MkldnnConvolutionBackward0() = default;
+#else
+struct TORCH_API MkldnnConvolutionBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MkldnnConvolutionBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  c10::OptionalArray bias_sym_sizes_opt;
+  std::vector dilation;
+  c10::SymInt groups;
+  std::vector padding;
+  SavedVariable self_;
+  std::vector stride;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct MkldnnLinearBackward0 : public TraceableFunction {
+  TORCH_API MkldnnLinearBackward0() = default;
+#else
+struct TORCH_API MkldnnLinearBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MkldnnLinearBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    weight_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+  SavedVariable weight_;
+
+};
+#ifdef _WIN32
+struct MkldnnMaxPool2DBackward0 : public TraceableFunction {
+  TORCH_API MkldnnMaxPool2DBackward0() = default;
+#else
+struct TORCH_API MkldnnMaxPool2DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MkldnnMaxPool2DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool ceil_mode;
+  std::vector dilation;
+  std::vector kernel_size;
+  std::vector padding;
+  SavedVariable self_;
+  std::vector stride;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct MkldnnMaxPool3DBackward0 : public TraceableFunction {
+  TORCH_API MkldnnMaxPool3DBackward0() = default;
+#else
+struct TORCH_API MkldnnMaxPool3DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MkldnnMaxPool3DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool ceil_mode;
+  std::vector dilation;
+  std::vector kernel_size;
+  std::vector padding;
+  SavedVariable self_;
+  std::vector stride;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct MkldnnAdaptiveAvgPool2DBackward0 : public TraceableFunction {
+  TORCH_API MkldnnAdaptiveAvgPool2DBackward0() = default;
+#else
+struct TORCH_API MkldnnAdaptiveAvgPool2DBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MkldnnAdaptiveAvgPool2DBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct MkldnnReshapeBackward0 : public TraceableFunction {
+  TORCH_API MkldnnReshapeBackward0() = default;
+#else
+struct TORCH_API MkldnnReshapeBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "MkldnnReshapeBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct NestedTensorFromTensorListBackward0 : public TraceableFunction {
+  TORCH_API NestedTensorFromTensorListBackward0() = default;
+#else
+struct TORCH_API NestedTensorFromTensorListBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NestedTensorFromTensorListBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    list_.clear();
+    list_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector list_;
+  bool list_released_ = false;
+  size_t list_size_;
+};
+#ifdef _WIN32
+struct NestedTensorFromMaskBackward0 : public TraceableFunction {
+  TORCH_API NestedTensorFromMaskBackward0() = default;
+#else
+struct TORCH_API NestedTensorFromMaskBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NestedTensorFromMaskBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector t_sym_sizes;
+
+};
+#ifdef _WIN32
+struct NestedFromPaddedBackward0 : public TraceableFunction {
+  TORCH_API NestedFromPaddedBackward0() = default;
+#else
+struct TORCH_API NestedFromPaddedBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NestedFromPaddedBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    padded_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool fuse_transform_0213;
+  SavedVariable padded_;
+
+};
+#ifdef _WIN32
+struct ToPaddedTensorBackward0 : public TraceableFunction {
+  TORCH_API ToPaddedTensorBackward0() = default;
+#else
+struct TORCH_API ToPaddedTensorBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ToPaddedTensorBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct NestedViewFromBufferBackward0 : public Node {
+  TORCH_API NestedViewFromBufferBackward0() = default;
+#else
+struct TORCH_API NestedViewFromBufferBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NestedViewFromBufferBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct NestedViewFromJaggedBackward0 : public Node {
+  TORCH_API NestedViewFromJaggedBackward0() = default;
+#else
+struct TORCH_API NestedViewFromJaggedBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NestedViewFromJaggedBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct NestedGetValuesBackward0 : public Node {
+  TORCH_API NestedGetValuesBackward0() = default;
+#else
+struct TORCH_API NestedGetValuesBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NestedGetValuesBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct SafeSoftmaxBackward0 : public TraceableFunction {
+  TORCH_API SafeSoftmaxBackward0() = default;
+#else
+struct TORCH_API SafeSoftmaxBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SafeSoftmaxBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  at::ScalarType self_scalar_type;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct ScaledDotProductEfficientAttentionBackward0 : public TraceableFunction {
+  TORCH_API ScaledDotProductEfficientAttentionBackward0() = default;
+#else
+struct TORCH_API ScaledDotProductEfficientAttentionBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ScaledDotProductEfficientAttentionBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    attn_bias_.reset_data();
+    key_.reset_data();
+    query_.reset_data();
+    value_.reset_data();
+    log_sumexp_.reset_data();
+    output_.reset_data();
+    philox_offset_.reset_data();
+    philox_seed_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable attn_bias_;
+  double dropout_p;
+  bool is_causal;
+  SavedVariable key_;
+  SavedVariable query_;
+  ::std::optional scale;
+  SavedVariable value_;
+  SavedVariable log_sumexp_;
+  SavedVariable output_;
+  SavedVariable philox_offset_;
+  SavedVariable philox_seed_;
+
+};
+#ifdef _WIN32
+struct ScaledDotProductFlashAttentionBackward0 : public TraceableFunction {
+  TORCH_API ScaledDotProductFlashAttentionBackward0() = default;
+#else
+struct TORCH_API ScaledDotProductFlashAttentionBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ScaledDotProductFlashAttentionBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    key_.reset_data();
+    query_.reset_data();
+    value_.reset_data();
+    cum_seq_k_.reset_data();
+    cum_seq_q_.reset_data();
+    logsumexp_.reset_data();
+    output_.reset_data();
+    philox_offset_.reset_data();
+    philox_seed_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  double dropout_p;
+  bool is_causal;
+  SavedVariable key_;
+  SavedVariable query_;
+  ::std::optional scale;
+  SavedVariable value_;
+  SavedVariable cum_seq_k_;
+  SavedVariable cum_seq_q_;
+  SavedVariable logsumexp_;
+  c10::SymInt max_k;
+  c10::SymInt max_q;
+  SavedVariable output_;
+  SavedVariable philox_offset_;
+  SavedVariable philox_seed_;
+
+};
+#ifdef _WIN32
+struct ScaledDotProductFlashAttentionForCpuBackward0 : public TraceableFunction {
+  TORCH_API ScaledDotProductFlashAttentionForCpuBackward0() = default;
+#else
+struct TORCH_API ScaledDotProductFlashAttentionForCpuBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ScaledDotProductFlashAttentionForCpuBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    attn_mask_.reset_data();
+    key_.reset_data();
+    query_.reset_data();
+    value_.reset_data();
+    logsumexp_.reset_data();
+    output_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable attn_mask_;
+  double dropout_p;
+  bool is_causal;
+  SavedVariable key_;
+  SavedVariable query_;
+  ::std::optional scale;
+  SavedVariable value_;
+  SavedVariable logsumexp_;
+  SavedVariable output_;
+
+};
+#ifdef _WIN32
+struct FlashAttentionBackward0 : public TraceableFunction {
+  TORCH_API FlashAttentionBackward0() = default;
+#else
+struct TORCH_API FlashAttentionBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FlashAttentionBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    cum_seq_k_.reset_data();
+    cum_seq_q_.reset_data();
+    key_.reset_data();
+    query_.reset_data();
+    value_.reset_data();
+    output_.reset_data();
+    philox_offset_.reset_data();
+    philox_seed_.reset_data();
+    softmax_logsumexp_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable cum_seq_k_;
+  SavedVariable cum_seq_q_;
+  double dropout_p;
+  bool is_causal;
+  SavedVariable key_;
+  c10::SymInt max_k;
+  c10::SymInt max_q;
+  SavedVariable query_;
+  ::std::optional scale;
+  SavedVariable value_;
+  ::std::optional window_size_left;
+  ::std::optional window_size_right;
+  SavedVariable output_;
+  SavedVariable philox_offset_;
+  SavedVariable philox_seed_;
+  SavedVariable softmax_logsumexp_;
+
+};
+#ifdef _WIN32
+struct EfficientAttentionBackward0 : public TraceableFunction {
+  TORCH_API EfficientAttentionBackward0() = default;
+#else
+struct TORCH_API EfficientAttentionBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "EfficientAttentionBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    bias_.reset_data();
+    cu_seqlens_k_.reset_data();
+    cu_seqlens_q_.reset_data();
+    key_.reset_data();
+    query_.reset_data();
+    value_.reset_data();
+    logsumexp_.reset_data();
+    output_.reset_data();
+    philox_offset_.reset_data();
+    philox_seed_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable bias_;
+  SavedVariable cu_seqlens_k_;
+  SavedVariable cu_seqlens_q_;
+  int64_t custom_mask_type = 0;
+  double dropout_p;
+  SavedVariable key_;
+  SavedVariable query_;
+  ::std::optional scale;
+  SavedVariable value_;
+  SavedVariable logsumexp_;
+  c10::SymInt max_seqlen_batch_k;
+  c10::SymInt max_seqlen_batch_q;
+  SavedVariable output_;
+  SavedVariable philox_offset_;
+  SavedVariable philox_seed_;
+
+};
+#ifdef _WIN32
+struct ScaledDotProductCudnnAttentionBackward0 : public TraceableFunction {
+  TORCH_API ScaledDotProductCudnnAttentionBackward0() = default;
+#else
+struct TORCH_API ScaledDotProductCudnnAttentionBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ScaledDotProductCudnnAttentionBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    attn_bias_.reset_data();
+    key_.reset_data();
+    query_.reset_data();
+    value_.reset_data();
+    cum_seq_k_.reset_data();
+    cum_seq_q_.reset_data();
+    logsumexp_.reset_data();
+    output_.reset_data();
+    philox_offset_.reset_data();
+    philox_seed_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable attn_bias_;
+  double dropout_p;
+  bool is_causal;
+  SavedVariable key_;
+  SavedVariable query_;
+  ::std::optional scale;
+  SavedVariable value_;
+  SavedVariable cum_seq_k_;
+  SavedVariable cum_seq_q_;
+  SavedVariable logsumexp_;
+  c10::SymInt max_k;
+  c10::SymInt max_q;
+  SavedVariable output_;
+  SavedVariable philox_offset_;
+  SavedVariable philox_seed_;
+
+};
+#ifdef _WIN32
+struct ScaledDotProductFusedAttentionOverrideableBackward0 : public TraceableFunction {
+  TORCH_API ScaledDotProductFusedAttentionOverrideableBackward0() = default;
+#else
+struct TORCH_API ScaledDotProductFusedAttentionOverrideableBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ScaledDotProductFusedAttentionOverrideableBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    attn_bias_.reset_data();
+    key_.reset_data();
+    query_.reset_data();
+    value_.reset_data();
+    cum_seq_k_.reset_data();
+    cum_seq_q_.reset_data();
+    logsumexp_.reset_data();
+    output_.reset_data();
+    philox_offset_.reset_data();
+    philox_seed_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable attn_bias_;
+  double dropout_p;
+  bool is_causal;
+  SavedVariable key_;
+  SavedVariable query_;
+  ::std::optional scale;
+  SavedVariable value_;
+  SavedVariable cum_seq_k_;
+  SavedVariable cum_seq_q_;
+  SavedVariable logsumexp_;
+  c10::SymInt max_k;
+  c10::SymInt max_q;
+  SavedVariable output_;
+  SavedVariable philox_offset_;
+  SavedVariable philox_seed_;
+
+};
+#ifdef _WIN32
+struct FftR2CBackward0 : public TraceableFunction {
+  TORCH_API FftR2CBackward0() = default;
+#else
+struct TORCH_API FftR2CBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FftR2CBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dim;
+  int64_t normalization = 0;
+  bool onesided;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct FftC2RBackward0 : public TraceableFunction {
+  TORCH_API FftC2RBackward0() = default;
+#else
+struct TORCH_API FftC2RBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FftC2RBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dim;
+  int64_t normalization = 0;
+
+};
+#ifdef _WIN32
+struct FftC2CBackward0 : public TraceableFunction {
+  TORCH_API FftC2CBackward0() = default;
+#else
+struct TORCH_API FftC2CBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "FftC2CBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dim;
+  bool forward;
+  int64_t normalization = 0;
+
+};
+#ifdef _WIN32
+struct UnbindBackward0 : public Node {
+  TORCH_API UnbindBackward0() = default;
+#else
+struct TORCH_API UnbindBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UnbindBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+
+};
+#ifdef _WIN32
+struct UnbindBackwardAutogradNestedTensor0 : public Node {
+  TORCH_API UnbindBackwardAutogradNestedTensor0() = default;
+#else
+struct TORCH_API UnbindBackwardAutogradNestedTensor0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UnbindBackwardAutogradNestedTensor0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  SavedVariable self_;
+  at::Layout self_layout;
+  at::TensorOptions self_options;
+
+};
+#ifdef _WIN32
+struct StackBackward0 : public TraceableFunction {
+  TORCH_API StackBackward0() = default;
+#else
+struct TORCH_API StackBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "StackBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  ::std::vector tensors_args_scalartypes;
+  size_t tensors_size_;
+};
+#ifdef _WIN32
+struct ThnnFusedLstmCellBackward0 : public TraceableFunction {
+  TORCH_API ThnnFusedLstmCellBackward0() = default;
+#else
+struct TORCH_API ThnnFusedLstmCellBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ThnnFusedLstmCellBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    cx_.reset_data();
+    hidden_bias_.reset_data();
+    hidden_gates_.reset_data();
+    input_bias_.reset_data();
+    input_gates_.reset_data();
+    result1_.reset_data();
+    result2_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable cx_;
+  SavedVariable hidden_bias_;
+  SavedVariable hidden_gates_;
+  SavedVariable input_bias_;
+  SavedVariable input_gates_;
+  SavedVariable result1_;
+  SavedVariable result2_;
+
+};
+#ifdef _WIN32
+struct ThnnFusedGruCellBackward0 : public TraceableFunction {
+  TORCH_API ThnnFusedGruCellBackward0() = default;
+#else
+struct TORCH_API ThnnFusedGruCellBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ThnnFusedGruCellBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    hidden_bias_.reset_data();
+    hidden_gates_.reset_data();
+    hx_.reset_data();
+    input_bias_.reset_data();
+    input_gates_.reset_data();
+    result1_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable hidden_bias_;
+  SavedVariable hidden_gates_;
+  SavedVariable hx_;
+  SavedVariable input_bias_;
+  SavedVariable input_gates_;
+  SavedVariable result1_;
+
+};
+#ifdef _WIN32
+struct PackPaddedSequenceBackward0 : public TraceableFunction {
+  TORCH_API PackPaddedSequenceBackward0() = default;
+#else
+struct TORCH_API PackPaddedSequenceBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "PackPaddedSequenceBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result1_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  bool batch_first;
+  std::vector input_sym_sizes;
+  SavedVariable result1_;
+
+};
+#ifdef _WIN32
+struct SegmentReduceBackward0 : public TraceableFunction {
+  TORCH_API SegmentReduceBackward0() = default;
+#else
+struct TORCH_API SegmentReduceBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SegmentReduceBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    data_.reset_data();
+    lengths_.reset_data();
+    offsets_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t axis = 0;
+  SavedVariable data_;
+  ::std::optional initial;
+  SavedVariable lengths_;
+  SavedVariable offsets_;
+  std::string reduce;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct PinMemoryBackward0 : public TraceableFunction {
+  TORCH_API PinMemoryBackward0() = default;
+#else
+struct TORCH_API PinMemoryBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "PinMemoryBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct TestWarnInAutogradBackward0 : public TraceableFunction {
+  TORCH_API TestWarnInAutogradBackward0() = default;
+#else
+struct TORCH_API TestWarnInAutogradBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "TestWarnInAutogradBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct TestAutogradMultipleDispatchBackward0 : public TraceableFunction {
+  TORCH_API TestAutogradMultipleDispatchBackward0() = default;
+#else
+struct TORCH_API TestAutogradMultipleDispatchBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "TestAutogradMultipleDispatchBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct TestAutogradMultipleDispatchBackwardAutogradNestedTensor0 : public TraceableFunction {
+  TORCH_API TestAutogradMultipleDispatchBackwardAutogradNestedTensor0() = default;
+#else
+struct TORCH_API TestAutogradMultipleDispatchBackwardAutogradNestedTensor0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "TestAutogradMultipleDispatchBackwardAutogradNestedTensor0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct TestAutogradMultipleDispatchBackwardAutogradCUDA0 : public TraceableFunction {
+  TORCH_API TestAutogradMultipleDispatchBackwardAutogradCUDA0() = default;
+#else
+struct TORCH_API TestAutogradMultipleDispatchBackwardAutogradCUDA0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "TestAutogradMultipleDispatchBackwardAutogradCUDA0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct TestAutogradMultipleDispatchBackwardAutogradNestedTensor1 : public TraceableFunction {
+  TORCH_API TestAutogradMultipleDispatchBackwardAutogradNestedTensor1() = default;
+#else
+struct TORCH_API TestAutogradMultipleDispatchBackwardAutogradNestedTensor1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "TestAutogradMultipleDispatchBackwardAutogradNestedTensor1"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct TestAutogradMultipleDispatchViewBackward0 : public Node {
+  TORCH_API TestAutogradMultipleDispatchViewBackward0() = default;
+#else
+struct TORCH_API TestAutogradMultipleDispatchViewBackward0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "TestAutogradMultipleDispatchViewBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct TestAutogradMultipleDispatchViewBackwardAutogradCUDA0 : public Node {
+  TORCH_API TestAutogradMultipleDispatchViewBackwardAutogradCUDA0() = default;
+#else
+struct TORCH_API TestAutogradMultipleDispatchViewBackwardAutogradCUDA0 : public Node {
+#endif
+  using Node::Node;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "TestAutogradMultipleDispatchViewBackwardAutogradCUDA0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct ScatterReduceBackward0 : public TraceableFunction {
+  TORCH_API ScatterReduceBackward0() = default;
+#else
+struct TORCH_API ScatterReduceBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ScatterReduceBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    index_.reset_data();
+    self_.reset_data();
+    src_.reset_data();
+    result_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  bool include_self;
+  SavedVariable index_;
+  std::string reduce;
+  SavedVariable self_;
+  SavedVariable src_;
+  SavedVariable result_;
+
+};
+#ifdef _WIN32
+struct ReshapeCopyBackward0 : public TraceableFunction {
+  TORCH_API ReshapeCopyBackward0() = default;
+#else
+struct TORCH_API ReshapeCopyBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ReshapeCopyBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct ForeachDivBackward0 : public TraceableFunction {
+  TORCH_API ForeachDivBackward0() = default;
+#else
+struct TORCH_API ForeachDivBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachDivBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.clear();
+    other_released_ = true;
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector other_;
+  bool other_released_ = false;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+  size_t other_size_;
+};
+#ifdef _WIN32
+struct ForeachPowBackward0 : public TraceableFunction {
+  TORCH_API ForeachPowBackward0() = default;
+#else
+struct TORCH_API ForeachPowBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachPowBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    exponent_.clear();
+    exponent_released_ = true;
+    self_.clear();
+    self_released_ = true;
+    result_.clear();
+    result_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector exponent_;
+  bool exponent_released_ = false;
+  std::vector self_;
+  bool self_released_ = false;
+  std::vector result_;
+  bool result_released_ = false;
+  size_t self_size_;
+  size_t exponent_size_;
+};
+#ifdef _WIN32
+struct ForeachPowBackward1 : public TraceableFunction {
+  TORCH_API ForeachPowBackward1() = default;
+#else
+struct TORCH_API ForeachPowBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachPowBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    exponent.clear();
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector exponent;
+  bool exponent_released_ = false;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachPowBackward2 : public TraceableFunction {
+  TORCH_API ForeachPowBackward2() = default;
+#else
+struct TORCH_API ForeachPowBackward2 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachPowBackward2"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    exponent_.clear();
+    exponent_released_ = true;
+    result_.clear();
+    result_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector exponent_;
+  bool exponent_released_ = false;
+  at::Scalar self;
+  std::vector result_;
+  bool result_released_ = false;
+  size_t exponent_size_;
+};
+#ifdef _WIN32
+struct ForeachMinimumBackward0 : public TraceableFunction {
+  TORCH_API ForeachMinimumBackward0() = default;
+#else
+struct TORCH_API ForeachMinimumBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachMinimumBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar scalar;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachMinimumBackward1 : public TraceableFunction {
+  TORCH_API ForeachMinimumBackward1() = default;
+#else
+struct TORCH_API ForeachMinimumBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachMinimumBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    scalars.clear();
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector scalars;
+  bool scalars_released_ = false;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachMaximumBackward0 : public TraceableFunction {
+  TORCH_API ForeachMaximumBackward0() = default;
+#else
+struct TORCH_API ForeachMaximumBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachMaximumBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar scalar;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachMaximumBackward1 : public TraceableFunction {
+  TORCH_API ForeachMaximumBackward1() = default;
+#else
+struct TORCH_API ForeachMaximumBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachMaximumBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    scalars.clear();
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector scalars;
+  bool scalars_released_ = false;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachNormBackward0 : public TraceableFunction {
+  TORCH_API ForeachNormBackward0() = default;
+#else
+struct TORCH_API ForeachNormBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachNormBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+    result_.clear();
+    result_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar ord;
+  std::vector self_;
+  bool self_released_ = false;
+  std::vector result_;
+  bool result_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct AliasBackward0_copy : public TraceableFunction {
+  TORCH_API AliasBackward0_copy() = default;
+#else
+struct TORCH_API AliasBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AliasBackward0_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct AsStridedBackward0_copy : public TraceableFunction {
+  TORCH_API AsStridedBackward0_copy() = default;
+#else
+struct TORCH_API AsStridedBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "AsStridedBackward0_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::TensorGeometry self_geometry;
+  std::vector size;
+  ::std::optional storage_offset;
+  std::vector stride;
+
+};
+#ifdef _WIN32
+struct ConjBackward0_copy : public TraceableFunction {
+  TORCH_API ConjBackward0_copy() = default;
+#else
+struct TORCH_API ConjBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ConjBackward0_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct NegViewBackward0_copy : public TraceableFunction {
+  TORCH_API NegViewBackward0_copy() = default;
+#else
+struct TORCH_API NegViewBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NegViewBackward0_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct DiagonalBackward0_copy : public TraceableFunction {
+  TORCH_API DiagonalBackward0_copy() = default;
+#else
+struct TORCH_API DiagonalBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "DiagonalBackward0_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim1 = 0;
+  int64_t dim2 = 0;
+  int64_t offset = 0;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct ExpandBackward0_copy : public TraceableFunction {
+  TORCH_API ExpandBackward0_copy() = default;
+#else
+struct TORCH_API ExpandBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ExpandBackward0_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct PermuteBackward0_copy : public TraceableFunction {
+  TORCH_API PermuteBackward0_copy() = default;
+#else
+struct TORCH_API PermuteBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "PermuteBackward0_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dims;
+
+};
+#ifdef _WIN32
+struct ReshapeAliasBackward0_copy : public TraceableFunction {
+  TORCH_API ReshapeAliasBackward0_copy() = default;
+#else
+struct TORCH_API ReshapeAliasBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ReshapeAliasBackward0_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct SelectBackward0_copy : public TraceableFunction {
+  TORCH_API SelectBackward0_copy() = default;
+#else
+struct TORCH_API SelectBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SelectBackward0_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  c10::SymInt index;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct SelectBackwardAutogradNestedTensor0_copy : public TraceableFunction {
+  TORCH_API SelectBackwardAutogradNestedTensor0_copy() = default;
+#else
+struct TORCH_API SelectBackwardAutogradNestedTensor0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SelectBackwardAutogradNestedTensor0_copy"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  c10::SymInt index;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct SliceBackward0_copy : public TraceableFunction {
+  TORCH_API SliceBackward0_copy() = default;
+#else
+struct TORCH_API SliceBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SliceBackward0_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  ::std::optional end;
+  std::vector self_sym_sizes;
+  ::std::optional start;
+  c10::SymInt step;
+
+};
+#ifdef _WIN32
+struct SplitBackward0_copy : public TraceableFunction {
+  TORCH_API SplitBackward0_copy() = default;
+#else
+struct TORCH_API SplitBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SplitBackward0_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  at::TensorOptions self_options;
+  std::vector self_sym_sizes;
+  c10::SymInt split_size;
+
+};
+#ifdef _WIN32
+struct SplitWithSizesBackward0_copy : public TraceableFunction {
+  TORCH_API SplitWithSizesBackward0_copy() = default;
+#else
+struct TORCH_API SplitWithSizesBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SplitWithSizesBackward0_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  at::TensorOptions self_options;
+  std::vector self_sym_sizes;
+  std::vector split_sizes;
+
+};
+#ifdef _WIN32
+struct SplitWithSizesBackwardAutogradNestedTensor0_copy : public TraceableFunction {
+  TORCH_API SplitWithSizesBackwardAutogradNestedTensor0_copy() = default;
+#else
+struct TORCH_API SplitWithSizesBackwardAutogradNestedTensor0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SplitWithSizesBackwardAutogradNestedTensor0_copy"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  SavedVariable self_;
+  at::TensorOptions self_options;
+  std::vector split_sizes;
+
+};
+#ifdef _WIN32
+struct SqueezeBackward0_copy : public TraceableFunction {
+  TORCH_API SqueezeBackward0_copy() = default;
+#else
+struct TORCH_API SqueezeBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SqueezeBackward0_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct SqueezeBackward1_copy : public TraceableFunction {
+  TORCH_API SqueezeBackward1_copy() = default;
+#else
+struct TORCH_API SqueezeBackward1_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SqueezeBackward1_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct SqueezeBackwardAutogradNestedTensor0_copy : public TraceableFunction {
+  TORCH_API SqueezeBackwardAutogradNestedTensor0_copy() = default;
+#else
+struct TORCH_API SqueezeBackwardAutogradNestedTensor0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SqueezeBackwardAutogradNestedTensor0_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+
+};
+#ifdef _WIN32
+struct SqueezeBackward2_copy : public TraceableFunction {
+  TORCH_API SqueezeBackward2_copy() = default;
+#else
+struct TORCH_API SqueezeBackward2_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SqueezeBackward2_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dim;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct SqueezeBackwardAutogradNestedTensor1_copy : public TraceableFunction {
+  TORCH_API SqueezeBackwardAutogradNestedTensor1_copy() = default;
+#else
+struct TORCH_API SqueezeBackwardAutogradNestedTensor1_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "SqueezeBackwardAutogradNestedTensor1_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector dim;
+  int64_t self_dim = 0;
+
+};
+#ifdef _WIN32
+struct TBackward0_copy : public TraceableFunction {
+  TORCH_API TBackward0_copy() = default;
+#else
+struct TORCH_API TBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "TBackward0_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct TransposeBackward0_copy : public TraceableFunction {
+  TORCH_API TransposeBackward0_copy() = default;
+#else
+struct TORCH_API TransposeBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "TransposeBackward0_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim0 = 0;
+  int64_t dim1 = 0;
+
+};
+#ifdef _WIN32
+struct UnfoldBackward0_copy : public TraceableFunction {
+  TORCH_API UnfoldBackward0_copy() = default;
+#else
+struct TORCH_API UnfoldBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UnfoldBackward0_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dimension = 0;
+  std::vector self_sym_sizes;
+  int64_t size = 0;
+  int64_t step = 0;
+
+};
+#ifdef _WIN32
+struct LiftFreshBackward0_copy : public TraceableFunction {
+  TORCH_API LiftFreshBackward0_copy() = default;
+#else
+struct TORCH_API LiftFreshBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "LiftFreshBackward0_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct UnsqueezeBackward0_copy : public TraceableFunction {
+  TORCH_API UnsqueezeBackward0_copy() = default;
+#else
+struct TORCH_API UnsqueezeBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UnsqueezeBackward0_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+
+};
+#ifdef _WIN32
+struct ViewBackward0_copy : public TraceableFunction {
+  TORCH_API ViewBackward0_copy() = default;
+#else
+struct TORCH_API ViewBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ViewBackward0_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_sym_sizes;
+
+};
+#ifdef _WIN32
+struct ViewBackwardAutogradNestedTensor0_copy : public TraceableFunction {
+  TORCH_API ViewBackwardAutogradNestedTensor0_copy() = default;
+#else
+struct TORCH_API ViewBackwardAutogradNestedTensor0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ViewBackwardAutogradNestedTensor0_copy"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct ViewAsRealBackward0_copy : public TraceableFunction {
+  TORCH_API ViewAsRealBackward0_copy() = default;
+#else
+struct TORCH_API ViewAsRealBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ViewAsRealBackward0_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct ViewAsComplexBackward0_copy : public TraceableFunction {
+  TORCH_API ViewAsComplexBackward0_copy() = default;
+#else
+struct TORCH_API ViewAsComplexBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ViewAsComplexBackward0_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct ValuesBackward0_copy : public TraceableFunction {
+  TORCH_API ValuesBackward0_copy() = default;
+#else
+struct TORCH_API ValuesBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ValuesBackward0_copy"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct ValuesBackwardAutogradNestedTensor0_copy : public TraceableFunction {
+  TORCH_API ValuesBackwardAutogradNestedTensor0_copy() = default;
+#else
+struct TORCH_API ValuesBackwardAutogradNestedTensor0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ValuesBackwardAutogradNestedTensor0_copy"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct NestedViewFromBufferBackward0_copy : public TraceableFunction {
+  TORCH_API NestedViewFromBufferBackward0_copy() = default;
+#else
+struct TORCH_API NestedViewFromBufferBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NestedViewFromBufferBackward0_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct NestedViewFromJaggedBackward0_copy : public TraceableFunction {
+  TORCH_API NestedViewFromJaggedBackward0_copy() = default;
+#else
+struct TORCH_API NestedViewFromJaggedBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NestedViewFromJaggedBackward0_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+
+};
+#ifdef _WIN32
+struct NestedGetValuesBackward0_copy : public TraceableFunction {
+  TORCH_API NestedGetValuesBackward0_copy() = default;
+#else
+struct TORCH_API NestedGetValuesBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "NestedGetValuesBackward0_copy"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct UnbindBackward0_copy : public TraceableFunction {
+  TORCH_API UnbindBackward0_copy() = default;
+#else
+struct TORCH_API UnbindBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UnbindBackward0_copy"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+
+};
+#ifdef _WIN32
+struct UnbindBackwardAutogradNestedTensor0_copy : public TraceableFunction {
+  TORCH_API UnbindBackwardAutogradNestedTensor0_copy() = default;
+#else
+struct TORCH_API UnbindBackwardAutogradNestedTensor0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "UnbindBackwardAutogradNestedTensor0_copy"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  int64_t dim = 0;
+  SavedVariable self_;
+  at::Layout self_layout;
+  at::TensorOptions self_options;
+
+};
+#ifdef _WIN32
+struct TestAutogradMultipleDispatchViewBackward0_copy : public TraceableFunction {
+  TORCH_API TestAutogradMultipleDispatchViewBackward0_copy() = default;
+#else
+struct TORCH_API TestAutogradMultipleDispatchViewBackward0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "TestAutogradMultipleDispatchViewBackward0_copy"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct TestAutogradMultipleDispatchViewBackwardAutogradCUDA0_copy : public TraceableFunction {
+  TORCH_API TestAutogradMultipleDispatchViewBackwardAutogradCUDA0_copy() = default;
+#else
+struct TORCH_API TestAutogradMultipleDispatchViewBackwardAutogradCUDA0_copy : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "TestAutogradMultipleDispatchViewBackwardAutogradCUDA0_copy"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.reset_data();
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable self_;
+
+};
+#ifdef _WIN32
+struct ForeachAbsBackward0 : public TraceableFunction {
+  TORCH_API ForeachAbsBackward0() = default;
+#else
+struct TORCH_API ForeachAbsBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachAbsBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachAcosBackward0 : public TraceableFunction {
+  TORCH_API ForeachAcosBackward0() = default;
+#else
+struct TORCH_API ForeachAcosBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachAcosBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachAddBackward1Scalar : public TraceableFunction {
+  TORCH_API ForeachAddBackward1Scalar() = default;
+#else
+struct TORCH_API ForeachAddBackward1Scalar : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachAddBackward1Scalar"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachAddBackward0List : public TraceableFunction {
+  TORCH_API ForeachAddBackward0List() = default;
+#else
+struct TORCH_API ForeachAddBackward0List : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachAddBackward0List"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.clear();
+    other_released_ = true;
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar alpha;
+  std::vector other_;
+  bool other_released_ = false;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+  size_t other_size_;
+};
+#ifdef _WIN32
+struct ForeachAddBackward1ScalarList : public TraceableFunction {
+  TORCH_API ForeachAddBackward1ScalarList() = default;
+#else
+struct TORCH_API ForeachAddBackward1ScalarList : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachAddBackward1ScalarList"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachAddBackward0Tensor : public TraceableFunction {
+  TORCH_API ForeachAddBackward0Tensor() = default;
+#else
+struct TORCH_API ForeachAddBackward0Tensor : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachAddBackward0Tensor"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar alpha;
+  SavedVariable other_;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachAddcdivBackward0Scalar : public TraceableFunction {
+  TORCH_API ForeachAddcdivBackward0Scalar() = default;
+#else
+struct TORCH_API ForeachAddcdivBackward0Scalar : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachAddcdivBackward0Scalar"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+    tensor1_.clear();
+    tensor1_released_ = true;
+    tensor2_.clear();
+    tensor2_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_;
+  bool self_released_ = false;
+  std::vector tensor1_;
+  bool tensor1_released_ = false;
+  std::vector tensor2_;
+  bool tensor2_released_ = false;
+  at::Scalar value;
+  size_t self_size_;
+  size_t tensor1_size_;
+  size_t tensor2_size_;
+};
+#ifdef _WIN32
+struct ForeachAddcdivBackward0ScalarList : public TraceableFunction {
+  TORCH_API ForeachAddcdivBackward0ScalarList() = default;
+#else
+struct TORCH_API ForeachAddcdivBackward0ScalarList : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachAddcdivBackward0ScalarList"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    scalars.clear();
+    self_.clear();
+    self_released_ = true;
+    tensor1_.clear();
+    tensor1_released_ = true;
+    tensor2_.clear();
+    tensor2_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector scalars;
+  bool scalars_released_ = false;
+  std::vector self_;
+  bool self_released_ = false;
+  std::vector tensor1_;
+  bool tensor1_released_ = false;
+  std::vector tensor2_;
+  bool tensor2_released_ = false;
+  size_t self_size_;
+  size_t tensor1_size_;
+  size_t tensor2_size_;
+};
+#ifdef _WIN32
+struct ForeachAddcmulBackward0Scalar : public TraceableFunction {
+  TORCH_API ForeachAddcmulBackward0Scalar() = default;
+#else
+struct TORCH_API ForeachAddcmulBackward0Scalar : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachAddcmulBackward0Scalar"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+    tensor1_.clear();
+    tensor1_released_ = true;
+    tensor2_.clear();
+    tensor2_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_;
+  bool self_released_ = false;
+  std::vector tensor1_;
+  bool tensor1_released_ = false;
+  std::vector tensor2_;
+  bool tensor2_released_ = false;
+  at::Scalar value;
+  size_t self_size_;
+  size_t tensor1_size_;
+  size_t tensor2_size_;
+};
+#ifdef _WIN32
+struct ForeachAddcmulBackward0ScalarList : public TraceableFunction {
+  TORCH_API ForeachAddcmulBackward0ScalarList() = default;
+#else
+struct TORCH_API ForeachAddcmulBackward0ScalarList : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachAddcmulBackward0ScalarList"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    scalars.clear();
+    self_.clear();
+    self_released_ = true;
+    tensor1_.clear();
+    tensor1_released_ = true;
+    tensor2_.clear();
+    tensor2_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector scalars;
+  bool scalars_released_ = false;
+  std::vector self_;
+  bool self_released_ = false;
+  std::vector tensor1_;
+  bool tensor1_released_ = false;
+  std::vector tensor2_;
+  bool tensor2_released_ = false;
+  size_t self_size_;
+  size_t tensor1_size_;
+  size_t tensor2_size_;
+};
+#ifdef _WIN32
+struct ForeachAsinBackward0 : public TraceableFunction {
+  TORCH_API ForeachAsinBackward0() = default;
+#else
+struct TORCH_API ForeachAsinBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachAsinBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachAtanBackward0 : public TraceableFunction {
+  TORCH_API ForeachAtanBackward0() = default;
+#else
+struct TORCH_API ForeachAtanBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachAtanBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachCeilBackward0 : public TraceableFunction {
+  TORCH_API ForeachCeilBackward0() = default;
+#else
+struct TORCH_API ForeachCeilBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachCeilBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachClampMaxBackward0Scalar : public TraceableFunction {
+  TORCH_API ForeachClampMaxBackward0Scalar() = default;
+#else
+struct TORCH_API ForeachClampMaxBackward0Scalar : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachClampMaxBackward0Scalar"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar scalar;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachClampMaxBackward1List : public TraceableFunction {
+  TORCH_API ForeachClampMaxBackward1List() = default;
+#else
+struct TORCH_API ForeachClampMaxBackward1List : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachClampMaxBackward1List"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.clear();
+    other_released_ = true;
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector other_;
+  bool other_released_ = false;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+  size_t other_size_;
+};
+#ifdef _WIN32
+struct ForeachClampMaxBackward0ScalarList : public TraceableFunction {
+  TORCH_API ForeachClampMaxBackward0ScalarList() = default;
+#else
+struct TORCH_API ForeachClampMaxBackward0ScalarList : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachClampMaxBackward0ScalarList"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    scalars.clear();
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector scalars;
+  bool scalars_released_ = false;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachClampMinBackward0Scalar : public TraceableFunction {
+  TORCH_API ForeachClampMinBackward0Scalar() = default;
+#else
+struct TORCH_API ForeachClampMinBackward0Scalar : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachClampMinBackward0Scalar"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar scalar;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachClampMinBackward1List : public TraceableFunction {
+  TORCH_API ForeachClampMinBackward1List() = default;
+#else
+struct TORCH_API ForeachClampMinBackward1List : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachClampMinBackward1List"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.clear();
+    other_released_ = true;
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector other_;
+  bool other_released_ = false;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+  size_t other_size_;
+};
+#ifdef _WIN32
+struct ForeachClampMinBackward0ScalarList : public TraceableFunction {
+  TORCH_API ForeachClampMinBackward0ScalarList() = default;
+#else
+struct TORCH_API ForeachClampMinBackward0ScalarList : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachClampMinBackward0ScalarList"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    scalars.clear();
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector scalars;
+  bool scalars_released_ = false;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachCosBackward0 : public TraceableFunction {
+  TORCH_API ForeachCosBackward0() = default;
+#else
+struct TORCH_API ForeachCosBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachCosBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachCoshBackward0 : public TraceableFunction {
+  TORCH_API ForeachCoshBackward0() = default;
+#else
+struct TORCH_API ForeachCoshBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachCoshBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachDivBackward1Scalar : public TraceableFunction {
+  TORCH_API ForeachDivBackward1Scalar() = default;
+#else
+struct TORCH_API ForeachDivBackward1Scalar : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachDivBackward1Scalar"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar scalar;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachDivBackward1ScalarList : public TraceableFunction {
+  TORCH_API ForeachDivBackward1ScalarList() = default;
+#else
+struct TORCH_API ForeachDivBackward1ScalarList : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachDivBackward1ScalarList"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    scalars.clear();
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector scalars;
+  bool scalars_released_ = false;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachDivBackward0Tensor : public TraceableFunction {
+  TORCH_API ForeachDivBackward0Tensor() = default;
+#else
+struct TORCH_API ForeachDivBackward0Tensor : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachDivBackward0Tensor"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachErfBackward0 : public TraceableFunction {
+  TORCH_API ForeachErfBackward0() = default;
+#else
+struct TORCH_API ForeachErfBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachErfBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachErfcBackward0 : public TraceableFunction {
+  TORCH_API ForeachErfcBackward0() = default;
+#else
+struct TORCH_API ForeachErfcBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachErfcBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachExpBackward0 : public TraceableFunction {
+  TORCH_API ForeachExpBackward0() = default;
+#else
+struct TORCH_API ForeachExpBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachExpBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.clear();
+    result_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector result_;
+  bool result_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachExpm1Backward0 : public TraceableFunction {
+  TORCH_API ForeachExpm1Backward0() = default;
+#else
+struct TORCH_API ForeachExpm1Backward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachExpm1Backward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.clear();
+    result_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector result_;
+  bool result_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachFloorBackward0 : public TraceableFunction {
+  TORCH_API ForeachFloorBackward0() = default;
+#else
+struct TORCH_API ForeachFloorBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachFloorBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachFracBackward0 : public TraceableFunction {
+  TORCH_API ForeachFracBackward0() = default;
+#else
+struct TORCH_API ForeachFracBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachFracBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachLerpBackward1List : public TraceableFunction {
+  TORCH_API ForeachLerpBackward1List() = default;
+#else
+struct TORCH_API ForeachLerpBackward1List : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachLerpBackward1List"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+    tensors1_.clear();
+    tensors1_released_ = true;
+    weights_.clear();
+    weights_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_;
+  bool self_released_ = false;
+  std::vector tensors1_;
+  bool tensors1_released_ = false;
+  std::vector weights_;
+  bool weights_released_ = false;
+  size_t self_size_;
+  size_t tensors1_size_;
+  size_t weights_size_;
+};
+#ifdef _WIN32
+struct ForeachLerpBackward0Scalar : public TraceableFunction {
+  TORCH_API ForeachLerpBackward0Scalar() = default;
+#else
+struct TORCH_API ForeachLerpBackward0Scalar : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachLerpBackward0Scalar"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar weight;
+  size_t self_size_;
+  size_t tensors1_size_;
+};
+#ifdef _WIN32
+struct ForeachLgammaBackward0 : public TraceableFunction {
+  TORCH_API ForeachLgammaBackward0() = default;
+#else
+struct TORCH_API ForeachLgammaBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachLgammaBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachLogBackward0 : public TraceableFunction {
+  TORCH_API ForeachLogBackward0() = default;
+#else
+struct TORCH_API ForeachLogBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachLogBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachLog10Backward0 : public TraceableFunction {
+  TORCH_API ForeachLog10Backward0() = default;
+#else
+struct TORCH_API ForeachLog10Backward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachLog10Backward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachLog1PBackward0 : public TraceableFunction {
+  TORCH_API ForeachLog1PBackward0() = default;
+#else
+struct TORCH_API ForeachLog1PBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachLog1PBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachLog2Backward0 : public TraceableFunction {
+  TORCH_API ForeachLog2Backward0() = default;
+#else
+struct TORCH_API ForeachLog2Backward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachLog2Backward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachMaxBackward1 : public TraceableFunction {
+  TORCH_API ForeachMaxBackward1() = default;
+#else
+struct TORCH_API ForeachMaxBackward1 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachMaxBackward1"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+    result_.clear();
+    result_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_;
+  bool self_released_ = false;
+  std::vector result_;
+  bool result_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachMaximumBackward0List : public TraceableFunction {
+  TORCH_API ForeachMaximumBackward0List() = default;
+#else
+struct TORCH_API ForeachMaximumBackward0List : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachMaximumBackward0List"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.clear();
+    other_released_ = true;
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector other_;
+  bool other_released_ = false;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+  size_t other_size_;
+};
+#ifdef _WIN32
+struct ForeachMinimumBackward0List : public TraceableFunction {
+  TORCH_API ForeachMinimumBackward0List() = default;
+#else
+struct TORCH_API ForeachMinimumBackward0List : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachMinimumBackward0List"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.clear();
+    other_released_ = true;
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector other_;
+  bool other_released_ = false;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+  size_t other_size_;
+};
+#ifdef _WIN32
+struct ForeachMulBackward1Scalar : public TraceableFunction {
+  TORCH_API ForeachMulBackward1Scalar() = default;
+#else
+struct TORCH_API ForeachMulBackward1Scalar : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachMulBackward1Scalar"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar scalar;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachMulBackward0List : public TraceableFunction {
+  TORCH_API ForeachMulBackward0List() = default;
+#else
+struct TORCH_API ForeachMulBackward0List : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachMulBackward0List"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.clear();
+    other_released_ = true;
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector other_;
+  bool other_released_ = false;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+  size_t other_size_;
+};
+#ifdef _WIN32
+struct ForeachMulBackward1ScalarList : public TraceableFunction {
+  TORCH_API ForeachMulBackward1ScalarList() = default;
+#else
+struct TORCH_API ForeachMulBackward1ScalarList : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachMulBackward1ScalarList"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    scalars.clear();
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector scalars;
+  bool scalars_released_ = false;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachMulBackward0Tensor : public TraceableFunction {
+  TORCH_API ForeachMulBackward0Tensor() = default;
+#else
+struct TORCH_API ForeachMulBackward0Tensor : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachMulBackward0Tensor"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.reset_data();
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  SavedVariable other_;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachNegBackward0 : public TraceableFunction {
+  TORCH_API ForeachNegBackward0() = default;
+#else
+struct TORCH_API ForeachNegBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachNegBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachPowBackward0Scalar : public TraceableFunction {
+  TORCH_API ForeachPowBackward0Scalar() = default;
+#else
+struct TORCH_API ForeachPowBackward0Scalar : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachPowBackward0Scalar"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar exponent;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachReciprocalBackward0 : public TraceableFunction {
+  TORCH_API ForeachReciprocalBackward0() = default;
+#else
+struct TORCH_API ForeachReciprocalBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachReciprocalBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.clear();
+    result_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector result_;
+  bool result_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachRoundBackward0 : public TraceableFunction {
+  TORCH_API ForeachRoundBackward0() = default;
+#else
+struct TORCH_API ForeachRoundBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachRoundBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachSigmoidBackward0 : public TraceableFunction {
+  TORCH_API ForeachSigmoidBackward0() = default;
+#else
+struct TORCH_API ForeachSigmoidBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachSigmoidBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.clear();
+    result_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector result_;
+  bool result_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachSignBackward0 : public TraceableFunction {
+  TORCH_API ForeachSignBackward0() = default;
+#else
+struct TORCH_API ForeachSignBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachSignBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachSinBackward0 : public TraceableFunction {
+  TORCH_API ForeachSinBackward0() = default;
+#else
+struct TORCH_API ForeachSinBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachSinBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachSinhBackward0 : public TraceableFunction {
+  TORCH_API ForeachSinhBackward0() = default;
+#else
+struct TORCH_API ForeachSinhBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachSinhBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachSqrtBackward0 : public TraceableFunction {
+  TORCH_API ForeachSqrtBackward0() = default;
+#else
+struct TORCH_API ForeachSqrtBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachSqrtBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.clear();
+    result_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector result_;
+  bool result_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachSubBackward1Scalar : public TraceableFunction {
+  TORCH_API ForeachSubBackward1Scalar() = default;
+#else
+struct TORCH_API ForeachSubBackward1Scalar : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachSubBackward1Scalar"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachSubBackward0List : public TraceableFunction {
+  TORCH_API ForeachSubBackward0List() = default;
+#else
+struct TORCH_API ForeachSubBackward0List : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachSubBackward0List"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    other_.clear();
+    other_released_ = true;
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  at::Scalar alpha;
+  std::vector other_;
+  bool other_released_ = false;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+  size_t other_size_;
+};
+#ifdef _WIN32
+struct ForeachSubBackward1ScalarList : public TraceableFunction {
+  TORCH_API ForeachSubBackward1ScalarList() = default;
+#else
+struct TORCH_API ForeachSubBackward1ScalarList : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachSubBackward1ScalarList"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    self_.clear();
+    self_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector self_;
+  bool self_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachTanBackward0 : public TraceableFunction {
+  TORCH_API ForeachTanBackward0() = default;
+#else
+struct TORCH_API ForeachTanBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachTanBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.clear();
+    result_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector result_;
+  bool result_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachTanhBackward0 : public TraceableFunction {
+  TORCH_API ForeachTanhBackward0() = default;
+#else
+struct TORCH_API ForeachTanhBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachTanhBackward0"; }
+  void release_variables() override {
+    std::lock_guard lock(mutex_);
+    result_.clear();
+    result_released_ = true;
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  std::vector result_;
+  bool result_released_ = false;
+  size_t self_size_;
+};
+#ifdef _WIN32
+struct ForeachTruncBackward0 : public TraceableFunction {
+  TORCH_API ForeachTruncBackward0() = default;
+#else
+struct TORCH_API ForeachTruncBackward0 : public TraceableFunction {
+#endif
+  using TraceableFunction::TraceableFunction;
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "ForeachTruncBackward0"; }
+  void release_variables() override {
+
+
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+
+  size_t self_size_;
+};
+
+}}} // namespace torch::autograd::generated
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/generated/VariableType.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/generated/VariableType.h
new file mode 100644
index 0000000000000000000000000000000000000000..c2f2ed43d44737e440ee12e172446ffb7e35e112
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/generated/VariableType.h
@@ -0,0 +1,59 @@
+#pragma once
+
+// @generated from ../tools/autograd/templates/VariableType.h
+
+#include 
+#include 
+
+#include 
+
+#include 
+#include 
+
+#include  // for size_t
+#include  // for function
+#include  // for unique_ptr
+#include 
+#include 
+
+namespace at {
+  struct Quantizer;
+};
+
+namespace torch { namespace autograd {
+
+using Variable = at::Tensor;
+using at::Context;
+using at::Device;
+using at::Dimname;
+using at::DimnameList;
+using at::Generator;
+using at::IntArrayRef;
+using at::MemoryFormat;
+using at::QScheme;
+using at::Scalar;
+using at::ScalarType;
+using at::Storage;
+using at::Tensor;
+using at::TensorList;
+using at::TensorOptions;
+using at::Quantizer;
+// This is temporary typedef to enable Quantizer in aten native function API
+// we'll remove them when we are actually exposing Quantizer class
+// to frontend
+using ConstQuantizerPtr = const c10::intrusive_ptr&;
+using std::optional;
+
+namespace VariableType {
+  TORCH_API std::vector allCUDATypes();
+  TORCH_API std::vector allXPUTypes();
+  TORCH_API std::vector allCPUTypes();
+  TORCH_API std::vector allPrivateUser1Types();
+
+  at::Tensor & unpack(Tensor & t, const char * name, int pos);
+  const at::Tensor & unpack(const Tensor & t, const char * name, int pos);
+  at::Tensor unpack_opt(const Tensor & t, const char * name, int pos);
+  std::vector unpack(const at::ITensorListRef& tl, const char *name, int pos);
+};
+
+}} // namespace torch::autograd
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/generated/ViewFuncs.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/generated/ViewFuncs.h
new file mode 100644
index 0000000000000000000000000000000000000000..bf2190b8adca94d02c3e862e55dba235f0d0aec1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/generated/ViewFuncs.h
@@ -0,0 +1,955 @@
+#pragma once
+
+// @generated from ../tools/autograd/templates/ViewFuncs.h
+
+#include 
+#include 
+#include 
+
+#ifndef AT_PER_OPERATOR_HEADERS
+#include 
+#else
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#endif
+
+namespace torch::autograd::generated {
+
+using at::Scalar;
+using at::Tensor;
+using at::IntArrayRef;
+using at::ArrayRef;
+using at::Type;
+using at::ScalarType;
+using std::optional;
+using c10::fmap;
+
+#define _CONJ_VIEW_FUNC_AVAILABLE
+struct _ConjViewFunc : public torch::autograd::ViewFunc {
+  _ConjViewFunc() 
+  {};
+  virtual ~_ConjViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+
+};
+
+#define _INDICES_VIEW_FUNC_AVAILABLE
+struct _IndicesViewFunc : public torch::autograd::ViewFunc {
+  _IndicesViewFunc() 
+  {};
+  virtual ~_IndicesViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+
+};
+
+#define _NEG_VIEW_VIEW_FUNC_AVAILABLE
+struct _NegViewViewFunc : public torch::autograd::ViewFunc {
+  _NegViewViewFunc() 
+  {};
+  virtual ~_NegViewViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+
+};
+
+#define _NESTED_GET_VALUES_VIEW_FUNC_AVAILABLE
+struct _NestedGetValuesViewFunc : public torch::autograd::ViewFunc {
+  _NestedGetValuesViewFunc() 
+  {};
+  virtual ~_NestedGetValuesViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+
+};
+
+#define _NESTED_VIEW_FROM_BUFFER_VIEW_FUNC_AVAILABLE
+struct _NestedViewFromBufferViewFunc : public torch::autograd::ViewFunc {
+  _NestedViewFromBufferViewFunc(const at::Tensor & nested_size, const at::Tensor & nested_strides, const at::Tensor & offsets) : nested_size(nested_size), nested_strides(nested_strides), offsets(offsets)
+  {};
+  virtual ~_NestedViewFromBufferViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+  at::Tensor nested_size;
+  at::Tensor nested_strides;
+  at::Tensor offsets;
+};
+
+#define _NESTED_VIEW_FROM_JAGGED_VIEW_FUNC_AVAILABLE
+struct _NestedViewFromJaggedViewFunc : public torch::autograd::ViewFunc {
+  _NestedViewFromJaggedViewFunc(const at::Tensor & offsets, const at::Tensor & dummy, const ::std::optional & lengths, int64_t ragged_idx, const ::std::optional & min_seqlen, const ::std::optional & max_seqlen) : offsets(offsets), dummy(dummy), lengths(lengths), ragged_idx(ragged_idx), min_seqlen(min_seqlen), max_seqlen(max_seqlen)
+  {};
+  virtual ~_NestedViewFromJaggedViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+  at::Tensor offsets;
+  at::Tensor dummy;
+  ::std::optional lengths;
+  int64_t ragged_idx;
+  ::std::optional min_seqlen;
+  ::std::optional max_seqlen;
+};
+
+#define _RESHAPE_ALIAS_VIEW_FUNC_AVAILABLE
+struct _ReshapeAliasViewFunc : public torch::autograd::ViewFunc {
+  _ReshapeAliasViewFunc(c10::SymIntArrayRef size, c10::SymIntArrayRef stride) : size(size.vec()), stride(stride.vec())
+  {};
+  virtual ~_ReshapeAliasViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+  ::std::vector size;
+  ::std::vector stride;
+};
+
+#define _TEST_AUTOGRAD_MULTIPLE_DISPATCH_VIEW_VIEW_FUNC_AVAILABLE
+struct _TestAutogradMultipleDispatchViewViewFunc : public torch::autograd::ViewFunc {
+  _TestAutogradMultipleDispatchViewViewFunc() 
+  {};
+  virtual ~_TestAutogradMultipleDispatchViewViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+
+};
+
+#define _VALUES_VIEW_FUNC_AVAILABLE
+struct _ValuesViewFunc : public torch::autograd::ViewFunc {
+  _ValuesViewFunc() 
+  {};
+  virtual ~_ValuesViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+
+};
+
+#define ALIAS_VIEW_FUNC_AVAILABLE
+struct AliasViewFunc : public torch::autograd::ViewFunc {
+  AliasViewFunc() 
+  {};
+  virtual ~AliasViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+
+};
+
+#define AS_STRIDED_VIEW_FUNC_AVAILABLE
+struct AsStridedViewFunc : public torch::autograd::ViewFunc {
+  AsStridedViewFunc(c10::SymIntArrayRef size, c10::SymIntArrayRef stride, ::std::optional storage_offset) : size(size.vec()), stride(stride.vec()), storage_offset(storage_offset)
+  {};
+  virtual ~AsStridedViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+  ::std::vector size;
+  ::std::vector stride;
+  ::std::optional storage_offset;
+};
+
+#define CCOL_INDICES_VIEW_FUNC_AVAILABLE
+struct CcolIndicesViewFunc : public torch::autograd::ViewFunc {
+  CcolIndicesViewFunc() 
+  {};
+  virtual ~CcolIndicesViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+
+};
+
+#define CHUNK_VIEW_FUNC_AVAILABLE
+struct ChunkViewFunc : public torch::autograd::ViewFunc {
+  ChunkViewFunc(int64_t chunks, int64_t dim, int64_t view_idx) : chunks(chunks), dim(dim), view_idx(view_idx)
+  {};
+  virtual ~ChunkViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+  int64_t chunks;
+  int64_t dim;
+  int64_t view_idx;
+};
+
+#define COL_INDICES_VIEW_FUNC_AVAILABLE
+struct ColIndicesViewFunc : public torch::autograd::ViewFunc {
+  ColIndicesViewFunc() 
+  {};
+  virtual ~ColIndicesViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+
+};
+
+#define CROW_INDICES_VIEW_FUNC_AVAILABLE
+struct CrowIndicesViewFunc : public torch::autograd::ViewFunc {
+  CrowIndicesViewFunc() 
+  {};
+  virtual ~CrowIndicesViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+
+};
+
+#define DIAGONAL_VIEW_FUNC_AVAILABLE
+struct DiagonalViewFunc : public torch::autograd::ViewFunc {
+  DiagonalViewFunc(int64_t offset, int64_t dim1, int64_t dim2) : offset(offset), dim1(dim1), dim2(dim2)
+  {};
+  virtual ~DiagonalViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+  int64_t offset;
+  int64_t dim1;
+  int64_t dim2;
+};
+
+#define EXPAND_VIEW_FUNC_AVAILABLE
+struct ExpandViewFunc : public torch::autograd::ViewFunc {
+  ExpandViewFunc(c10::SymIntArrayRef size, bool implicit) : size(size.vec()), implicit(implicit)
+  {};
+  virtual ~ExpandViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+  ::std::vector size;
+  bool implicit;
+};
+
+#define INDICES_VIEW_FUNC_AVAILABLE
+struct IndicesViewFunc : public torch::autograd::ViewFunc {
+  IndicesViewFunc() 
+  {};
+  virtual ~IndicesViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+
+};
+
+#define NARROW_VIEW_FUNC_AVAILABLE
+struct NarrowViewFunc : public torch::autograd::ViewFunc {
+  NarrowViewFunc(int64_t dim, c10::SymInt start, c10::SymInt length) : dim(dim), start(start), length(length)
+  {};
+  virtual ~NarrowViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+  int64_t dim;
+  c10::SymInt start;
+  c10::SymInt length;
+};
+
+#define PERMUTE_VIEW_FUNC_AVAILABLE
+struct PermuteViewFunc : public torch::autograd::ViewFunc {
+  PermuteViewFunc(at::IntArrayRef dims) : dims(dims.vec())
+  {};
+  virtual ~PermuteViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+  ::std::vector dims;
+};
+
+#define ROW_INDICES_VIEW_FUNC_AVAILABLE
+struct RowIndicesViewFunc : public torch::autograd::ViewFunc {
+  RowIndicesViewFunc() 
+  {};
+  virtual ~RowIndicesViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+
+};
+
+#define SELECT_INT_VIEW_FUNC_AVAILABLE
+struct SelectIntViewFunc : public torch::autograd::ViewFunc {
+  SelectIntViewFunc(int64_t dim, c10::SymInt index) : dim(dim), index(index)
+  {};
+  virtual ~SelectIntViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+  int64_t dim;
+  c10::SymInt index;
+};
+
+#define SLICE_TENSOR_VIEW_FUNC_AVAILABLE
+struct SliceTensorViewFunc : public torch::autograd::ViewFunc {
+  SliceTensorViewFunc(int64_t dim, ::std::optional start, ::std::optional end, c10::SymInt step) : dim(dim), start(start), end(end), step(step)
+  {};
+  virtual ~SliceTensorViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+  int64_t dim;
+  ::std::optional start;
+  ::std::optional end;
+  c10::SymInt step;
+};
+
+#define SLICE_INVERSE_VIEW_FUNC_AVAILABLE
+struct SliceInverseViewFunc : public torch::autograd::ViewFunc {
+  SliceInverseViewFunc(const at::Tensor & src, int64_t dim, ::std::optional start, ::std::optional end, c10::SymInt step) : src(src), dim(dim), start(start), end(end), step(step)
+  {};
+  virtual ~SliceInverseViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+  at::Tensor src;
+  int64_t dim;
+  ::std::optional start;
+  ::std::optional end;
+  c10::SymInt step;
+};
+
+#define SPLIT_TENSOR_VIEW_FUNC_AVAILABLE
+struct SplitTensorViewFunc : public torch::autograd::ViewFunc {
+  SplitTensorViewFunc(c10::SymInt split_size, int64_t dim, int64_t view_idx) : split_size(split_size), dim(dim), view_idx(view_idx)
+  {};
+  virtual ~SplitTensorViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+  c10::SymInt split_size;
+  int64_t dim;
+  int64_t view_idx;
+};
+
+#define SPLIT_WITH_SIZES_VIEW_FUNC_AVAILABLE
+struct SplitWithSizesViewFunc : public torch::autograd::ViewFunc {
+  SplitWithSizesViewFunc(c10::SymIntArrayRef split_sizes, int64_t dim, int64_t view_idx) : split_sizes(split_sizes.vec()), dim(dim), view_idx(view_idx)
+  {};
+  virtual ~SplitWithSizesViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+  ::std::vector split_sizes;
+  int64_t dim;
+  int64_t view_idx;
+};
+
+#define SQUEEZE_VIEW_FUNC_AVAILABLE
+struct SqueezeViewFunc : public torch::autograd::ViewFunc {
+  SqueezeViewFunc() 
+  {};
+  virtual ~SqueezeViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+
+};
+
+#define SQUEEZE_DIM_VIEW_FUNC_AVAILABLE
+struct SqueezeDimViewFunc : public torch::autograd::ViewFunc {
+  SqueezeDimViewFunc(int64_t dim) : dim(dim)
+  {};
+  virtual ~SqueezeDimViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+  int64_t dim;
+};
+
+#define SQUEEZE_DIMS_VIEW_FUNC_AVAILABLE
+struct SqueezeDimsViewFunc : public torch::autograd::ViewFunc {
+  SqueezeDimsViewFunc(at::IntArrayRef dim) : dim(dim.vec())
+  {};
+  virtual ~SqueezeDimsViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+  ::std::vector dim;
+};
+
+#define T_VIEW_FUNC_AVAILABLE
+struct TViewFunc : public torch::autograd::ViewFunc {
+  TViewFunc() 
+  {};
+  virtual ~TViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+
+};
+
+#define TRANSPOSE_INT_VIEW_FUNC_AVAILABLE
+struct TransposeIntViewFunc : public torch::autograd::ViewFunc {
+  TransposeIntViewFunc(int64_t dim0, int64_t dim1) : dim0(dim0), dim1(dim1)
+  {};
+  virtual ~TransposeIntViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+  int64_t dim0;
+  int64_t dim1;
+};
+
+#define UNBIND_INT_VIEW_FUNC_AVAILABLE
+struct UnbindIntViewFunc : public torch::autograd::ViewFunc {
+  UnbindIntViewFunc(int64_t dim, int64_t view_idx) : dim(dim), view_idx(view_idx)
+  {};
+  virtual ~UnbindIntViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+  int64_t dim;
+  int64_t view_idx;
+};
+
+#define UNFOLD_VIEW_FUNC_AVAILABLE
+struct UnfoldViewFunc : public torch::autograd::ViewFunc {
+  UnfoldViewFunc(int64_t dimension, int64_t size, int64_t step) : dimension(dimension), size(size), step(step)
+  {};
+  virtual ~UnfoldViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+  int64_t dimension;
+  int64_t size;
+  int64_t step;
+};
+
+#define UNSQUEEZE_VIEW_FUNC_AVAILABLE
+struct UnsqueezeViewFunc : public torch::autograd::ViewFunc {
+  UnsqueezeViewFunc(int64_t dim) : dim(dim)
+  {};
+  virtual ~UnsqueezeViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+  int64_t dim;
+};
+
+#define VALUES_VIEW_FUNC_AVAILABLE
+struct ValuesViewFunc : public torch::autograd::ViewFunc {
+  ValuesViewFunc() 
+  {};
+  virtual ~ValuesViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+
+};
+
+#define VIEW_VIEW_FUNC_AVAILABLE
+struct ViewViewFunc : public torch::autograd::ViewFunc {
+  ViewViewFunc(c10::SymIntArrayRef size) : size(size.vec())
+  {};
+  virtual ~ViewViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+  ::std::vector size;
+};
+
+#define VIEW_DTYPE_VIEW_FUNC_AVAILABLE
+struct ViewDtypeViewFunc : public torch::autograd::ViewFunc {
+  ViewDtypeViewFunc(at::ScalarType dtype) : dtype(dtype)
+  {};
+  virtual ~ViewDtypeViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+  at::ScalarType dtype;
+};
+
+#define VIEW_AS_COMPLEX_VIEW_FUNC_AVAILABLE
+struct ViewAsComplexViewFunc : public torch::autograd::ViewFunc {
+  ViewAsComplexViewFunc() 
+  {};
+  virtual ~ViewAsComplexViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+
+};
+
+#define VIEW_AS_REAL_VIEW_FUNC_AVAILABLE
+struct ViewAsRealViewFunc : public torch::autograd::ViewFunc {
+  ViewAsRealViewFunc() 
+  {};
+  virtual ~ViewAsRealViewFunc() override {};
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+
+};
+
+} // namespace torch::autograd::generated
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/generated/python_functions.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/generated/python_functions.h
new file mode 100644
index 0000000000000000000000000000000000000000..90e4910e96a347215d587d879bdcee0f52ffbb9f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/generated/python_functions.h
@@ -0,0 +1,25 @@
+#pragma once
+
+#include 
+
+// @generated from ../tools/autograd/templates/python_functions.h
+
+// Python bindings for automatically generated autograd functions
+
+namespace torch { namespace autograd { namespace generated {
+
+void initialize_autogenerated_functions_0(PyObject* module);
+void initialize_autogenerated_functions_1(PyObject* module);
+void initialize_autogenerated_functions_2(PyObject* module);
+void initialize_autogenerated_functions_3(PyObject* module);
+void initialize_autogenerated_functions_4(PyObject* module);
+
+inline void initialize_autogenerated_functions(PyObject* module) {
+  initialize_autogenerated_functions_0(module);
+  initialize_autogenerated_functions_1(module);
+  initialize_autogenerated_functions_2(module);
+  initialize_autogenerated_functions_3(module);
+  initialize_autogenerated_functions_4(module);
+}
+
+}}} // namespace torch::autograd::generated
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/generated/python_return_types.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/generated/python_return_types.h
new file mode 100644
index 0000000000000000000000000000000000000000..81fa1cb708d38382e05048942671c451bf4e04e3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/generated/python_return_types.h
@@ -0,0 +1,98 @@
+#pragma once
+
+namespace torch {
+namespace autograd {
+namespace generated {
+
+PyTypeObject* get__fake_quantize_per_tensor_affine_cachemask_tensor_qparams_structseq();
+PyTypeObject* get__fused_moving_avg_obs_fq_helper_structseq();
+PyTypeObject* get__linalg_det_structseq();
+PyTypeObject* get__linalg_det_out_structseq();
+PyTypeObject* get__linalg_eigh_structseq();
+PyTypeObject* get__linalg_eigh_out_structseq();
+PyTypeObject* get__linalg_slogdet_structseq();
+PyTypeObject* get__linalg_slogdet_out_structseq();
+PyTypeObject* get__linalg_solve_ex_structseq();
+PyTypeObject* get__linalg_solve_ex_out_structseq();
+PyTypeObject* get__linalg_svd_structseq();
+PyTypeObject* get__linalg_svd_out_structseq();
+PyTypeObject* get__lu_with_info_structseq();
+PyTypeObject* get__scaled_dot_product_cudnn_attention_structseq();
+PyTypeObject* get__scaled_dot_product_efficient_attention_structseq();
+PyTypeObject* get__scaled_dot_product_flash_attention_structseq();
+PyTypeObject* get__scaled_dot_product_flash_attention_for_cpu_structseq();
+PyTypeObject* get__unpack_dual_structseq();
+PyTypeObject* get_aminmax_structseq();
+PyTypeObject* get_aminmax_out_structseq();
+PyTypeObject* get_cummax_structseq();
+PyTypeObject* get_cummax_out_structseq();
+PyTypeObject* get_cummin_structseq();
+PyTypeObject* get_cummin_out_structseq();
+PyTypeObject* get_frexp_structseq();
+PyTypeObject* get_frexp_out_structseq();
+PyTypeObject* get_geqrf_out_structseq();
+PyTypeObject* get_geqrf_structseq();
+PyTypeObject* get_histogram_out_structseq();
+PyTypeObject* get_histogram_structseq();
+PyTypeObject* get_histogramdd_structseq();
+PyTypeObject* get_kthvalue_structseq();
+PyTypeObject* get_kthvalue_out_structseq();
+PyTypeObject* get_linalg_cholesky_ex_structseq();
+PyTypeObject* get_linalg_cholesky_ex_out_structseq();
+PyTypeObject* get_linalg_eig_structseq();
+PyTypeObject* get_linalg_eig_out_structseq();
+PyTypeObject* get_linalg_eigh_structseq();
+PyTypeObject* get_linalg_eigh_out_structseq();
+PyTypeObject* get_linalg_inv_ex_structseq();
+PyTypeObject* get_linalg_inv_ex_out_structseq();
+PyTypeObject* get_linalg_ldl_factor_structseq();
+PyTypeObject* get_linalg_ldl_factor_out_structseq();
+PyTypeObject* get_linalg_ldl_factor_ex_structseq();
+PyTypeObject* get_linalg_ldl_factor_ex_out_structseq();
+PyTypeObject* get_linalg_lstsq_structseq();
+PyTypeObject* get_linalg_lstsq_out_structseq();
+PyTypeObject* get_linalg_lu_structseq();
+PyTypeObject* get_linalg_lu_out_structseq();
+PyTypeObject* get_linalg_lu_factor_structseq();
+PyTypeObject* get_linalg_lu_factor_out_structseq();
+PyTypeObject* get_linalg_lu_factor_ex_structseq();
+PyTypeObject* get_linalg_lu_factor_ex_out_structseq();
+PyTypeObject* get_linalg_qr_structseq();
+PyTypeObject* get_linalg_qr_out_structseq();
+PyTypeObject* get_linalg_slogdet_structseq();
+PyTypeObject* get_linalg_slogdet_out_structseq();
+PyTypeObject* get_linalg_solve_ex_structseq();
+PyTypeObject* get_linalg_solve_ex_out_structseq();
+PyTypeObject* get_linalg_svd_structseq();
+PyTypeObject* get_linalg_svd_out_structseq();
+PyTypeObject* get_lu_unpack_structseq();
+PyTypeObject* get_lu_unpack_out_structseq();
+PyTypeObject* get_max_structseq();
+PyTypeObject* get_max_out_structseq();
+PyTypeObject* get_median_structseq();
+PyTypeObject* get_median_out_structseq();
+PyTypeObject* get_min_structseq();
+PyTypeObject* get_min_out_structseq();
+PyTypeObject* get_mode_structseq();
+PyTypeObject* get_mode_out_structseq();
+PyTypeObject* get_nanmedian_structseq();
+PyTypeObject* get_nanmedian_out_structseq();
+PyTypeObject* get_qr_out_structseq();
+PyTypeObject* get_qr_structseq();
+PyTypeObject* get_slogdet_structseq();
+PyTypeObject* get_slogdet_out_structseq();
+PyTypeObject* get_sort_out_structseq();
+PyTypeObject* get_sort_structseq();
+PyTypeObject* get_svd_out_structseq();
+PyTypeObject* get_svd_structseq();
+PyTypeObject* get_topk_out_structseq();
+PyTypeObject* get_topk_structseq();
+PyTypeObject* get_triangular_solve_out_structseq();
+PyTypeObject* get_triangular_solve_structseq();
+
+}
+
+void initReturnTypes(PyObject* module);
+
+} // namespace autograd
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/generated/variable_factories.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/generated/variable_factories.h
new file mode 100644
index 0000000000000000000000000000000000000000..9d1fb12be955fc397cde53a535dea5daf10bd723
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/generated/variable_factories.h
@@ -0,0 +1,741 @@
+#pragma once
+
+// @generated from ../tools/autograd/templates/variable_factories.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#ifndef AT_PER_OPERATOR_HEADERS
+#include 
+#else
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#endif
+
+#include 
+#include 
+#include 
+
+namespace torch {
+
+/// NOTE: Currently `torch::tensor(...)` doesn't support mixed data types
+/// (i.e. `torch::tensor({{bool, 2.0}})` doesn't work). We might be able to
+/// support it in the future by iterating over all sub-lists to find
+/// the largest data type that can represent all of the elements, or by using
+/// variadic templates.
+///
+/// NOTE: C++ `torch::tensor` with a floating-point type or an `at::ArrayRef` / `std::vector` /
+/// (nested) braced-init-list of floating-point types always produces a tensor of dtype
+/// `torch::get_default_dtype()`, matching Python `torch.tensor` behavior.
+///
+/// NOTE: C++ `torch::tensor` with an integer type or an `at::ArrayRef` / `std::vector` /
+/// (nested) braced-init-list of integer types always produces a tensor of dtype `at::kLong`
+/// (aka. int64_t), matching Python `torch.tensor` behavior.
+///
+/// NOTE: The following dtypes are not supported by `torch::tensor` currently:
+/// - `unsigned int`
+/// - `unsigned long int`
+/// - `unsigned long long int`
+/// - `long long int`
+inline at::Tensor tensor(detail::TensorDataContainer tensor_data_container, const at::TensorOptions& options = {}) {
+  return autograd::make_variable(
+    // note: we remove the requires_grad setting from the TensorOptions because
+    // it is ignored anyways (and we actually have an assertion that it isn't set
+    // which would fail otherwise). We handle requires_grad explicitly here
+    // instead of passing it through to the kernel.
+    tensor_data_container.convert_to_tensor(options.requires_grad(::std::nullopt)),
+    options.requires_grad());
+}
+
+/// A generic deleter function.
+using Deleter = std::function;
+using at::MemoryFormat;
+
+/// Exposes the given `data` as a `Tensor` without taking ownership of the
+/// original data. `sizes` should specify the shape of the tensor, `strides` the
+/// stride in each dimension. The `deleter` function (a
+/// `std::function`) will be called on the `data` when the Tensor
+/// data would normally be deallocated. The `TensorOptions` specify additional
+/// configuration options for the returned tensor, such as what type to
+/// interpret the `data` as.
+inline at::Tensor from_blob(
+    void* data,
+    at::IntArrayRef sizes,
+    at::IntArrayRef strides,
+    const Deleter& deleter,
+    const at::TensorOptions& options = at::TensorOptions()) {
+  at::Tensor tensor = ([&]() {
+    at::AutoDispatchBelowAutograd guard;  // TODO: remove
+    at::tracer::impl::NoTracerDispatchMode tracer_guard;
+    return at::from_blob(data, sizes, strides, deleter, options.requires_grad(::std::nullopt));
+  })();
+  return autograd::make_variable(tensor, options.requires_grad());
+}
+
+/// Exposes the given `data` as a `Tensor` without taking ownership of the
+/// original data. `sizes` should specify the shape of the tensor, `strides` the
+/// stride in each dimension. The `TensorOptions`
+/// specify additional configuration options for the returned tensor, such as
+/// what type to interpret the `data` as.
+inline at::Tensor from_blob(
+    void* data,
+    at::IntArrayRef sizes,
+    at::IntArrayRef strides,
+    const at::TensorOptions& options = at::TensorOptions()) {
+  at::Tensor tensor = ([&]() {
+    at::AutoDispatchBelowAutograd guard;  // TODO: remove
+    at::tracer::impl::NoTracerDispatchMode tracer_guard;
+    return at::from_blob(data, sizes, strides, options.requires_grad(::std::nullopt));
+  })();
+  return autograd::make_variable(tensor, options.requires_grad());
+}
+
+/// Exposes the given `data` as a `Tensor` without taking ownership of the
+/// original data. `sizes` should specify the shape of the tensor. The `deleter`
+/// (a `std::function`) function will be called on the `data` when
+/// the Tensor data would normally be deallocated. The `TensorOptions` specify
+/// additional configuration options for the returned tensor, such as what type
+/// to interpret the `data` as.
+inline at::Tensor from_blob(
+    void* data,
+    at::IntArrayRef sizes,
+    const Deleter& deleter,
+    const at::TensorOptions& options = at::TensorOptions()) {
+  at::Tensor tensor = ([&]() {
+    at::AutoDispatchBelowAutograd guard;  // TODO: remove
+    at::tracer::impl::NoTracerDispatchMode tracer_guard;
+    return at::from_blob(data, sizes, deleter, options.requires_grad(::std::nullopt));
+  })();
+  return autograd::make_variable(tensor, options.requires_grad());
+}
+
+/// Exposes the given `data` as a `Tensor` without taking ownership of the
+/// original data. `sizes` should specify the shape of the tensor. The
+/// `TensorOptions` specify additional configuration options for the returned
+/// tensor, such as what type to interpret the `data` as.
+inline at::Tensor from_blob(
+    void* data,
+    at::IntArrayRef sizes,
+    const at::TensorOptions& options = at::TensorOptions()) {
+  at::Tensor tensor = ([&]() {
+    at::AutoDispatchBelowAutograd guard;  // TODO: remove
+    at::tracer::impl::NoTracerDispatchMode tracer_guard;
+    return at::from_blob(data, sizes, options.requires_grad(::std::nullopt));
+  })();
+  return autograd::make_variable(tensor, options.requires_grad());
+}
+
+inline at::Tensor _make_dep_token(at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::_make_dep_token(at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor _cudnn_init_dropout_state(double dropout, bool train, int64_t dropout_seed, at::TensorOptions options) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::_cudnn_init_dropout_state(dropout, train, dropout_seed, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor arange(const at::Scalar & end, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::arange(end, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor arange(const at::Scalar & start, const at::Scalar & end, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::arange(start, end, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor arange(const at::Scalar & start, const at::Scalar & end, const at::Scalar & step, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::arange(start, end, step, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor bartlett_window(int64_t window_length, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::bartlett_window(window_length, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor bartlett_window(int64_t window_length, bool periodic, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::bartlett_window(window_length, periodic, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor blackman_window(int64_t window_length, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::blackman_window(window_length, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor blackman_window(int64_t window_length, bool periodic, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::blackman_window(window_length, periodic, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor empty(at::IntArrayRef size, ::std::optional names, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::empty(size, names, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor empty(at::IntArrayRef size, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::empty(size, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor empty_symint(c10::SymIntArrayRef size, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::empty_symint(size, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor empty_permuted(at::IntArrayRef size, at::IntArrayRef physical_layout, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::empty_permuted(size, physical_layout, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor empty_permuted_symint(c10::SymIntArrayRef size, at::IntArrayRef physical_layout, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::empty_permuted_symint(size, physical_layout, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor _empty_affine_quantized(at::IntArrayRef size, at::TensorOptions options = {}, double scale = 1, int64_t zero_point = 0, ::std::optional memory_format = c10::MemoryFormat::Contiguous) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::_empty_affine_quantized(size, at::TensorOptions(options).requires_grad(::std::nullopt), scale, zero_point, memory_format), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor _empty_affine_quantized_symint(c10::SymIntArrayRef size, at::TensorOptions options = {}, double scale = 1, int64_t zero_point = 0, ::std::optional memory_format = c10::MemoryFormat::Contiguous) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::_empty_affine_quantized_symint(size, at::TensorOptions(options).requires_grad(::std::nullopt), scale, zero_point, memory_format), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor _empty_per_channel_affine_quantized(at::IntArrayRef size, const at::Tensor & scales, const at::Tensor & zero_points, int64_t axis, at::TensorOptions options = {}, ::std::optional memory_format = c10::MemoryFormat::Contiguous) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::_empty_per_channel_affine_quantized(size, scales, zero_points, axis, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor _empty_per_channel_affine_quantized_symint(c10::SymIntArrayRef size, const at::Tensor & scales, const at::Tensor & zero_points, int64_t axis, at::TensorOptions options = {}, ::std::optional memory_format = c10::MemoryFormat::Contiguous) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::_empty_per_channel_affine_quantized_symint(size, scales, zero_points, axis, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor empty_quantized(at::IntArrayRef size, const at::Tensor & qtensor, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::empty_quantized(size, qtensor, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor empty_like(const at::Tensor & self, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::empty_like(self, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor empty_strided(at::IntArrayRef size, at::IntArrayRef stride, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::empty_strided(size, stride, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor empty_strided_symint(c10::SymIntArrayRef size, c10::SymIntArrayRef stride, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::empty_strided_symint(size, stride, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor eye(int64_t n, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::eye(n, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor eye_symint(c10::SymInt n, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::eye_symint(n, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor eye(int64_t n, int64_t m, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::eye(n, m, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor eye_symint(c10::SymInt n, c10::SymInt m, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::eye_symint(n, m, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor full(at::IntArrayRef size, const at::Scalar & fill_value, ::std::optional names, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::full(size, fill_value, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor full(at::IntArrayRef size, const at::Scalar & fill_value, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::full(size, fill_value, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor full_symint(c10::SymIntArrayRef size, const at::Scalar & fill_value, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::full_symint(size, fill_value, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor full_like(const at::Tensor & self, const at::Scalar & fill_value, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::full_like(self, fill_value, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor from_file(c10::string_view filename, ::std::optional shared = ::std::nullopt, ::std::optional size = 0, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::from_file(filename, shared, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor hann_window(int64_t window_length, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::hann_window(window_length, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor hann_window(int64_t window_length, bool periodic, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::hann_window(window_length, periodic, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor hamming_window(int64_t window_length, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::hamming_window(window_length, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor hamming_window(int64_t window_length, bool periodic, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::hamming_window(window_length, periodic, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor hamming_window(int64_t window_length, bool periodic, double alpha, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::hamming_window(window_length, periodic, alpha, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor hamming_window(int64_t window_length, bool periodic, double alpha, double beta, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::hamming_window(window_length, periodic, alpha, beta, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor kaiser_window(int64_t window_length, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::kaiser_window(window_length, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor kaiser_window(int64_t window_length, bool periodic, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::kaiser_window(window_length, periodic, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor kaiser_window(int64_t window_length, bool periodic, double beta, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::kaiser_window(window_length, periodic, beta, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor linspace(const at::Scalar & start, const at::Scalar & end, int64_t steps, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::linspace(start, end, steps, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor linspace(const at::Tensor & start, const at::Tensor & end, int64_t steps, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::linspace(start, end, steps, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor linspace(const at::Tensor & start, const at::Scalar & end, int64_t steps, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::linspace(start, end, steps, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor linspace(const at::Scalar & start, const at::Tensor & end, int64_t steps, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::linspace(start, end, steps, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor logspace(const at::Scalar & start, const at::Scalar & end, int64_t steps, double base = 10.0, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::logspace(start, end, steps, base, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor logspace(const at::Tensor & start, const at::Tensor & end, int64_t steps, double base = 10.0, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::logspace(start, end, steps, base, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor logspace(const at::Tensor & start, const at::Scalar & end, int64_t steps, double base = 10.0, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::logspace(start, end, steps, base, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor logspace(const at::Scalar & start, const at::Tensor & end, int64_t steps, double base = 10.0, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::logspace(start, end, steps, base, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor ones(at::IntArrayRef size, ::std::optional names, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::ones(size, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor ones(at::IntArrayRef size, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::ones(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor ones_symint(c10::SymIntArrayRef size, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::ones_symint(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor ones_like(const at::Tensor & self, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::ones_like(self, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor scalar_tensor(const at::Scalar & s, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::scalar_tensor(s, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor rand(at::IntArrayRef size, ::std::optional names, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::rand(size, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor rand_symint(c10::SymIntArrayRef size, ::std::optional names, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::rand_symint(size, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor rand(at::IntArrayRef size, ::std::optional generator, ::std::optional names, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::rand(size, generator, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor rand_symint(c10::SymIntArrayRef size, ::std::optional generator, ::std::optional names, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::rand_symint(size, generator, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor rand(at::IntArrayRef size, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::rand(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor rand_symint(c10::SymIntArrayRef size, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::rand_symint(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor rand(at::IntArrayRef size, ::std::optional generator, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::rand(size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor rand_symint(c10::SymIntArrayRef size, ::std::optional generator, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::rand_symint(size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor rand_like(const at::Tensor & self, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::rand_like(self, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor randint(int64_t high, at::IntArrayRef size, at::TensorOptions options = at::kLong) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::randint(high, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor randint_symint(c10::SymInt high, c10::SymIntArrayRef size, at::TensorOptions options = at::kLong) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::randint_symint(high, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor randint(int64_t high, at::IntArrayRef size, ::std::optional generator, at::TensorOptions options = at::kLong) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::randint(high, size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor randint_symint(c10::SymInt high, c10::SymIntArrayRef size, ::std::optional generator, at::TensorOptions options = at::kLong) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::randint_symint(high, size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor randint(int64_t low, int64_t high, at::IntArrayRef size, at::TensorOptions options = at::kLong) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::randint(low, high, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor randint_symint(c10::SymInt low, c10::SymInt high, c10::SymIntArrayRef size, at::TensorOptions options = at::kLong) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::randint_symint(low, high, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor randint(int64_t low, int64_t high, at::IntArrayRef size, ::std::optional generator, at::TensorOptions options = at::kLong) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::randint(low, high, size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor randint_symint(c10::SymInt low, c10::SymInt high, c10::SymIntArrayRef size, ::std::optional generator, at::TensorOptions options = at::kLong) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::randint_symint(low, high, size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor randint_like(const at::Tensor & self, int64_t high, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::randint_like(self, high, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor randint_like_symint(const at::Tensor & self, c10::SymInt high, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::randint_like_symint(self, high, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor randint_like(const at::Tensor & self, int64_t low, int64_t high, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::randint_like(self, low, high, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor randint_like_symint(const at::Tensor & self, c10::SymInt low, c10::SymInt high, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::randint_like_symint(self, low, high, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor randn(at::IntArrayRef size, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::randn(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor randn_symint(c10::SymIntArrayRef size, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::randn_symint(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor randn(at::IntArrayRef size, ::std::optional generator, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::randn(size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor randn_symint(c10::SymIntArrayRef size, ::std::optional generator, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::randn_symint(size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor randn(at::IntArrayRef size, ::std::optional names, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::randn(size, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor randn_symint(c10::SymIntArrayRef size, ::std::optional names, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::randn_symint(size, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor randn(at::IntArrayRef size, ::std::optional generator, ::std::optional names, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::randn(size, generator, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor randn_symint(c10::SymIntArrayRef size, ::std::optional generator, ::std::optional names, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::randn_symint(size, generator, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor randn_like(const at::Tensor & self, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::randn_like(self, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor randperm(int64_t n, at::TensorOptions options = at::kLong) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::randperm(n, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor randperm_symint(c10::SymInt n, at::TensorOptions options = at::kLong) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::randperm_symint(n, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor randperm(int64_t n, ::std::optional generator, at::TensorOptions options = at::kLong) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::randperm(n, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor randperm_symint(c10::SymInt n, ::std::optional generator, at::TensorOptions options = at::kLong) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::randperm_symint(n, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor range(const at::Scalar & start, const at::Scalar & end, const at::Scalar & step = 1, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::range(start, end, step, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor range(const at::Scalar & start, const at::Scalar & end, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::range(start, end, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor zeros(at::IntArrayRef size, ::std::optional names, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::zeros(size, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor _efficientzerotensor(at::IntArrayRef size, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::_efficientzerotensor(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor _efficientzerotensor_symint(c10::SymIntArrayRef size, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::_efficientzerotensor_symint(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor zeros(at::IntArrayRef size, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::zeros(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor zeros_symint(c10::SymIntArrayRef size, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::zeros_symint(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor zeros_like(const at::Tensor & self, at::TensorOptions options = {}, ::std::optional memory_format = ::std::nullopt) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::zeros_like(self, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor _sparse_compressed_tensor_with_dims(int64_t nnz, int64_t dense_dim, at::IntArrayRef size, at::IntArrayRef blocksize, at::ScalarType index_dtype, at::TensorOptions options) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::_sparse_compressed_tensor_with_dims(nnz, dense_dim, size, blocksize, index_dtype, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor sparse_compressed_tensor(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::sparse_compressed_tensor(compressed_indices, plain_indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor sparse_compressed_tensor_symint(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, c10::SymIntArrayRef size, at::TensorOptions options) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::sparse_compressed_tensor_symint(compressed_indices, plain_indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor sparse_csr_tensor(const at::Tensor & crow_indices, const at::Tensor & col_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::sparse_csr_tensor(crow_indices, col_indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor sparse_csc_tensor(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::sparse_csc_tensor(ccol_indices, row_indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor sparse_bsr_tensor(const at::Tensor & crow_indices, const at::Tensor & col_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::sparse_bsr_tensor(crow_indices, col_indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor sparse_bsc_tensor(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::sparse_bsc_tensor(ccol_indices, row_indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor sparse_compressed_tensor(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, at::TensorOptions options) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::sparse_compressed_tensor(compressed_indices, plain_indices, values, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor sparse_csr_tensor(const at::Tensor & crow_indices, const at::Tensor & col_indices, const at::Tensor & values, at::TensorOptions options) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::sparse_csr_tensor(crow_indices, col_indices, values, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor sparse_csc_tensor(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::TensorOptions options) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::sparse_csc_tensor(ccol_indices, row_indices, values, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor sparse_bsr_tensor(const at::Tensor & crow_indices, const at::Tensor & col_indices, const at::Tensor & values, at::TensorOptions options) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::sparse_bsr_tensor(crow_indices, col_indices, values, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor sparse_bsc_tensor(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::TensorOptions options) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::sparse_bsc_tensor(ccol_indices, row_indices, values, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor _sparse_compressed_tensor_unsafe(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::_sparse_compressed_tensor_unsafe(compressed_indices, plain_indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor _sparse_compressed_tensor_unsafe_symint(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, c10::SymIntArrayRef size, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::_sparse_compressed_tensor_unsafe_symint(compressed_indices, plain_indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor _sparse_csr_tensor_unsafe(const at::Tensor & crow_indices, const at::Tensor & col_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::_sparse_csr_tensor_unsafe(crow_indices, col_indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor _sparse_csc_tensor_unsafe(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::_sparse_csc_tensor_unsafe(ccol_indices, row_indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor _sparse_bsr_tensor_unsafe(const at::Tensor & crow_indices, const at::Tensor & col_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::_sparse_bsr_tensor_unsafe(crow_indices, col_indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor _sparse_bsc_tensor_unsafe(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::_sparse_bsc_tensor_unsafe(ccol_indices, row_indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor sparse_coo_tensor(at::IntArrayRef size, at::TensorOptions options) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::sparse_coo_tensor(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor sparse_coo_tensor(const at::Tensor & indices, const at::Tensor & values, at::TensorOptions options = {}, ::std::optional is_coalesced = ::std::nullopt) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::sparse_coo_tensor(indices, values, at::TensorOptions(options).requires_grad(::std::nullopt), is_coalesced), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor sparse_coo_tensor(const at::Tensor & indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options = {}, ::std::optional is_coalesced = ::std::nullopt) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::sparse_coo_tensor(indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt), is_coalesced), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor _sparse_coo_tensor_unsafe(const at::Tensor & indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options = {}, ::std::optional is_coalesced = ::std::nullopt) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::_sparse_coo_tensor_unsafe(indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt), is_coalesced), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor _sparse_coo_tensor_unsafe_symint(const at::Tensor & indices, const at::Tensor & values, c10::SymIntArrayRef size, at::TensorOptions options = {}, ::std::optional is_coalesced = ::std::nullopt) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::_sparse_coo_tensor_unsafe_symint(indices, values, size, at::TensorOptions(options).requires_grad(::std::nullopt), is_coalesced), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor _sparse_coo_tensor_with_dims(int64_t sparse_dim, int64_t dense_dim, at::IntArrayRef size, at::TensorOptions options) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::_sparse_coo_tensor_with_dims(sparse_dim, dense_dim, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor _sparse_coo_tensor_with_dims_and_tensors(int64_t sparse_dim, int64_t dense_dim, at::IntArrayRef size, const at::Tensor & indices, const at::Tensor & values, at::TensorOptions options, ::std::optional is_coalesced = ::std::nullopt) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::_sparse_coo_tensor_with_dims_and_tensors(sparse_dim, dense_dim, size, indices, values, at::TensorOptions(options).requires_grad(::std::nullopt), is_coalesced), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor _sparse_coo_tensor_with_dims_and_tensors_symint(int64_t sparse_dim, int64_t dense_dim, c10::SymIntArrayRef size, const at::Tensor & indices, const at::Tensor & values, at::TensorOptions options, ::std::optional is_coalesced = ::std::nullopt) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::_sparse_coo_tensor_with_dims_and_tensors_symint(sparse_dim, dense_dim, size, indices, values, at::TensorOptions(options).requires_grad(::std::nullopt), is_coalesced), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor _to_copy(const at::Tensor & self, at::TensorOptions options = {}, bool non_blocking = false, ::std::optional memory_format = ::std::nullopt) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::_to_copy(self, at::TensorOptions(options).requires_grad(::std::nullopt), non_blocking, memory_format), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor tril_indices(int64_t row, int64_t col, int64_t offset = 0, at::TensorOptions options = at::kLong) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::tril_indices(row, col, offset, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor triu_indices(int64_t row, int64_t col, int64_t offset = 0, at::TensorOptions options = at::kLong) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::triu_indices(row, col, offset, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor normal(double mean, double std, at::IntArrayRef size, ::std::optional generator = ::std::nullopt, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::normal(mean, std, size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor normal_symint(double mean, double std, c10::SymIntArrayRef size, ::std::optional generator = ::std::nullopt, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::normal_symint(mean, std, size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor fft_fftfreq(int64_t n, double d = 1.0, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::fft_fftfreq(n, d, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+inline at::Tensor fft_rfftfreq(int64_t n, double d = 1.0, at::TensorOptions options = {}) {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::fft_rfftfreq(n, d, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
+}
+
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/utils/error_messages.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/utils/error_messages.h
new file mode 100644
index 0000000000000000000000000000000000000000..89105f527c96e7026285dc4ccfa73e9a2d56aed6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/utils/error_messages.h
@@ -0,0 +1,18 @@
+#pragma once
+
+#include 
+
+namespace torch::autograd::utils {
+
+inline std::string requires_grad_leaf_error(bool requires_grad) {
+  std::ostringstream oss;
+  oss << "you can only change requires_grad flags of leaf variables.";
+  if (requires_grad == false) {
+    oss << " If you want to use a computed variable in a subgraph "
+           "that doesn't require differentiation use "
+           "var_no_grad = var.detach().";
+  }
+  return oss.str();
+}
+
+} // namespace torch::autograd::utils
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/utils/grad_layout_contract.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/utils/grad_layout_contract.h
new file mode 100644
index 0000000000000000000000000000000000000000..ed97dc4530eb418cdbc84bc456273445be62cae7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/utils/grad_layout_contract.h
@@ -0,0 +1,76 @@
+#pragma once
+
+#include 
+
+namespace torch::autograd::utils {
+
+// Helper functions to enforce the "Gradient Layout Contract" described in
+// torch/csrc/autograd/functions/accumulate_grad.h.
+
+// Checks if grad obeys the contract with variable.
+inline bool obeys_layout_contract(
+    const at::Tensor& grad,
+    const at::Tensor& variable) {
+  TORCH_INTERNAL_ASSERT(!grad.is_sparse());
+  TORCH_INTERNAL_ASSERT(!grad.is_sparse_csr());
+  TORCH_INTERNAL_ASSERT(!variable.is_sparse_csr());
+
+  // NOLINTNEXTLINE(bugprone-branch-clone)
+  if (variable.is_nested()) {
+    // TODO: Nested Tensor does not have an implementation of detach. The
+    // current implementation of nested tensor likely does obey the gradient
+    // contract and should return true, but this would likely change in the
+    // future
+    return false;
+  } else if (variable.is_sparse()) {
+    // Gradient Layout Contract is not applicable for sparse layouts
+    return false;
+  } else if (variable.is_non_overlapping_and_dense()) {
+    // Only look at stride for dimensions that are not of size 1.
+    const auto& grad_sizes = grad.sym_sizes();
+    const auto& grad_strides = grad.sym_strides();
+    const auto& variable_strides = variable.sym_strides();
+    for (const auto idx : c10::irange(grad_sizes.size())) {
+      if (grad_sizes[idx] != 1) {
+        if (grad_strides[idx] != variable_strides[idx]) {
+          return false;
+        }
+      } else {
+        // This should not be needed but we don't check if a Tensor has views
+        // before stashing it. And 0-strided Tensors of size 1 are actually
+        // views for ops like cat.
+        // TODO: Actually detect views in the accumulateGrad function so that
+        // this Tensor is not considered at all.
+        if (grad_strides[idx] == 0) {
+          return false;
+        }
+      }
+    }
+    return true;
+  } else {
+    return grad.is_contiguous(at::MemoryFormat::Contiguous);
+  }
+}
+
+// Creates a clone of new_grad that obeys the contract with variable.
+// The clone should attach to new_grad's history if GradMode::is_enabled().
+inline at::Tensor clone_obey_contract(
+    const at::Tensor& new_grad,
+    const at::Tensor& variable) {
+  if (variable.is_non_overlapping_and_dense()) {
+    // (1)
+    // Does this dicey-looking sequence attach the result to new_grad's
+    // history if GradMode::is_enabled()?  Yes, and @alband says it should.
+    return std::move(new_grad
+                         .new_empty_strided_symint(
+                             variable.sym_sizes(),
+                             variable.sym_strides(),
+                             variable.options().memory_format(std::nullopt))
+                         .copy_(new_grad));
+  } else {
+    // (2)
+    return new_grad.clone(at::MemoryFormat::Contiguous);
+  }
+}
+
+} // namespace torch::autograd::utils
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/utils/lambda_post_hook.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/utils/lambda_post_hook.h
new file mode 100644
index 0000000000000000000000000000000000000000..c2f47347a4cff85c9f338a542c86233b69f5a05f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/utils/lambda_post_hook.h
@@ -0,0 +1,37 @@
+#pragma once
+
+#include 
+#include 
+
+namespace torch::autograd::utils {
+
+// Turns lambda into a torch::autograd::FunctionPostHook.
+class LambdaPostHook : public torch::autograd::FunctionPostHook {
+  using variable_list = std::vector;
+  using fn_type =
+      std::function;
+  using compiled_fn_type = std::function;
+
+ public:
+  // The lambda function takes as arguments the outputs and inputs of the
+  // autograd function and can modify the outputs of the autograd function by
+  // returning a new output if needed.
+  /* implicit */ LambdaPostHook(fn_type fn) : fn_(std::move(fn)) {}
+
+  LambdaPostHook(fn_type fn, compiled_fn_type compiled_fn)
+      : fn_(std::move(fn)), compiled_fn_(std::move(compiled_fn)) {}
+
+  variable_list operator()(
+      const variable_list& outputs,
+      const variable_list& inputs) override {
+    return fn_(outputs, inputs);
+  }
+
+  void compiled_args(CompiledNodeArgs& args) override {}
+
+ protected:
+  std::function fn_;
+  compiled_fn_type compiled_fn_{};
+};
+
+} // namespace torch::autograd::utils
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/utils/python_arg_parsing.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/utils/python_arg_parsing.h
new file mode 100644
index 0000000000000000000000000000000000000000..9d4ec8dfcd3af072f6375093d2a2dd4182af4d86
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/utils/python_arg_parsing.h
@@ -0,0 +1,49 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+
+namespace torch::autograd::utils {
+
+// The parameter allow_copy is to accept copy for Tensor.to (and by proxy
+// PackedSequences.to) but not nn.Module.to.
+inline std::tuple<
+    std::optional,
+    std::optional,
+    bool,
+    bool,
+    std::optional>
+parse_to_conversion(PythonArgs& r, bool allow_copy) {
+  if (r.idx == 0) {
+    if (!allow_copy && !r.isNone(3))
+      throw std::runtime_error(".to() does not accept copy argument");
+    return std::make_tuple(
+        r.deviceOptional(0),
+        r.scalartypeOptional(1),
+        r.toBool(2),
+        r.toBool(3),
+        r.memoryformatOptional(4));
+  } else if (r.idx == 1) {
+    if (!allow_copy && !r.isNone(2))
+      throw std::runtime_error(".to() does not accept copy argument");
+    return std::make_tuple(
+        std::nullopt,
+        r.scalartype(0),
+        r.toBool(1),
+        r.toBool(2),
+        r.memoryformatOptional(3));
+  } else {
+    auto tensor = r.tensor(0);
+    if (!allow_copy && !r.isNone(2))
+      throw std::runtime_error(".to() does not accept copy argument");
+    return std::make_tuple(
+        tensor.device(),
+        tensor.scalar_type(),
+        r.toBool(1),
+        r.toBool(2),
+        r.memoryformatOptional(3));
+  }
+}
+} // namespace torch::autograd::utils
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/utils/warnings.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/utils/warnings.h
new file mode 100644
index 0000000000000000000000000000000000000000..ced5663ef4ed1da825d84bf022e01caf94ca9d2d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/utils/warnings.h
@@ -0,0 +1,24 @@
+#pragma once
+#include 
+
+#include 
+#include 
+
+namespace torch::autograd::utils {
+
+// Warning handler for multi-threaded contexts. Gather warnings from
+// all threads into a single queue, then process together at the end
+// in the main thread.
+class DelayWarningHandler : public at::WarningHandler {
+ public:
+  ~DelayWarningHandler() override = default;
+  void replay_warnings();
+
+ private:
+  void process(const c10::Warning& warning) override;
+
+  std::vector warnings_;
+  std::mutex mutex_;
+};
+
+} // namespace torch::autograd::utils
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/utils/wrap_outputs.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/utils/wrap_outputs.h
new file mode 100644
index 0000000000000000000000000000000000000000..5d1d17c597af3244eeba796670e057d439794330
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/autograd/utils/wrap_outputs.h
@@ -0,0 +1,149 @@
+#pragma once
+
+// Wrap tensor operation outputs as PyObject*
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch::autograd::utils {
+
+inline PyObject* wrap(bool value) {
+  if (value) {
+    Py_RETURN_TRUE;
+  } else {
+    Py_RETURN_FALSE;
+  }
+}
+
+inline PyObject* wrap(c10::DeviceIndex value) {
+  return THPUtils_packDeviceIndex(value);
+}
+
+inline PyObject* wrap(int64_t value) {
+  return THPUtils_packInt64(value);
+}
+
+inline PyObject* wrap(double value) {
+  return PyFloat_FromDouble(value);
+}
+
+inline PyObject* wrap(c10::complex value) {
+  // I could probably also use FromComplex with a reinterpret cast,
+  // but... eh.
+  return PyComplex_FromDoubles(value.real(), value.imag());
+}
+
+inline PyObject* wrap(void* value) {
+  return THPUtils_packInt64(reinterpret_cast(value));
+}
+
+inline PyObject* wrap(THPDtype* dtype) {
+  return Py_NewRef(dtype);
+}
+
+inline PyObject* wrap(at::ScalarType scalarType) {
+  return Py_NewRef(getTHPDtype(scalarType));
+}
+
+inline PyObject* wrap(THPLayout* layout) {
+  return Py_NewRef(layout);
+}
+
+inline PyObject* wrap(at::Layout layout) {
+  return Py_NewRef(getTHPLayout(layout));
+}
+
+inline PyObject* wrap(at::Tensor tensor) {
+  return THPVariable_Wrap(Variable(std::move(tensor)));
+}
+
+inline PyObject* wrap(const at::Scalar& scalar) {
+  return wrap(scalar_to_tensor(scalar));
+}
+
+inline PyObject* wrap(at::QScheme qscheme) {
+  auto* thp_qscheme = torch::utils::getTHPQScheme(qscheme);
+  Py_INCREF(thp_qscheme);
+  return thp_qscheme;
+}
+
+inline PyObject* wrap(at::TensorList tl) {
+  auto r = THPObjectPtr{PyTuple_New(tl.size())};
+  if (!r)
+    throw python_error();
+  for (const auto i : c10::irange(tl.size())) {
+    PyTuple_SET_ITEM(r.get(), i, wrap(tl[i]));
+  }
+  return r.release();
+}
+
+inline PyObject* wrap(at::IntArrayRef list) {
+  auto r = THPObjectPtr{PyTuple_New(list.size())};
+  if (!r)
+    throw python_error();
+  for (const auto i : c10::irange(list.size())) {
+    PyTuple_SET_ITEM(r.get(), i, wrap(list[i]));
+  }
+  return r.release();
+}
+
+inline PyObject* wrap(at::Stream stream) {
+  return THPStream_Wrap(stream);
+}
+
+namespace detail {
+template 
+void apply_with_idx_impl(
+    const F& f,
+    Tuple& t,
+    std::index_sequence /*indices*/) {
+  (void)std::initializer_list{(f(std::get(t), Is), 0)...};
+}
+
+// For tuple(a, b, c), calls f(a, 0), f(b, 1), f(c, 2)
+template 
+void apply_with_idx(const F& f, std::tuple& t) {
+  apply_with_idx_impl(f, t, std::index_sequence_for{});
+}
+} // namespace detail
+
+template 
+PyObject* wrap(std::tuple values) {
+  auto r = THPObjectPtr{PyTuple_New(sizeof...(Ts))};
+  if (!r)
+    throw python_error();
+  detail::apply_with_idx(
+      [&](auto& value, size_t idx) {
+        PyTuple_SET_ITEM(r.get(), idx, wrap(std::move(value)));
+      },
+      values);
+  return r.release();
+}
+
+template 
+PyObject* wrap(PyTypeObject* type, std::tuple values) {
+  auto r = THPObjectPtr{PyStructSequence_New(type)};
+  if (!r)
+    throw python_error();
+  detail::apply_with_idx(
+      [&](auto& value, size_t idx) {
+        PyStructSequence_SET_ITEM(r.get(), idx, wrap(std::move(value)));
+      },
+      values);
+  return r.release();
+}
+
+} // namespace torch::autograd::utils
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/context/container.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/context/container.h
new file mode 100644
index 0000000000000000000000000000000000000000..3f3864077e2106650ca4ea126740f92d4ba3f824
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/context/container.h
@@ -0,0 +1,167 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+
+namespace torch {
+namespace distributed {
+namespace autograd {
+
+// Singleton class per worker which is responsible for storing the distributed
+// autograd context for each autograd pass and also cleans up data for an
+// autograd pass once its done.
+//
+// Each autograd pass is assigned a unique autograd_context_id and all data for
+// that pass (DistAutogradContext) is stored in this container indexed by the
+// autograd_context_id. The autograd_context_id itself is a 64 bit globally
+// unique id. The first 16 bits is the worker_id and the next 48 bits is an
+// auto-incrementing id for each worker.
+//
+// This container is also responsible for maintaining a globally unique message
+// id, which is used to associate send/recv autograd function pairs. The format
+// is similar to the autograd_context_id where we have a 64 bit integer with
+// first 16 bits being the worker id and next 48 bits are auto-incrementing.
+class TORCH_API DistAutogradContainer {
+ public:
+  explicit DistAutogradContainer(uint32_t num_shards);
+
+  // One time initialization of the container.
+  static DistAutogradContainer& init(int64_t worker_id);
+
+  // Retrieve the singleton instance of the container, ensures we have
+  // initialized the container.
+  static DistAutogradContainer& getInstance();
+
+  // Create a new context for a distributed autograd pass.
+  const ContextPtr newContext();
+
+  // Clean up resources for a given context_id once the autograd pass is done.
+  // Sends RPC to other workers this worker knows about, telling them to clean
+  // up their context as well. Throws an exception if the context_id does not
+  // exist.
+  void releaseContext(int64_t context_id);
+
+  // Releases an autograd context if it is present on this node. Also sends RPC
+  // to other workers this worker knows about, telling them to clean up their
+  // context. Does nothing if it is not present.
+  void releaseContextIfPresent(int64_t context_id);
+
+  // Checks if the passed in context_id is valid.
+  void isValidContext(int64_t context_id);
+
+  // Retrieve the autograd context for a given context_id.
+  ContextPtr retrieveContext(int64_t context_id);
+
+  // Retrieves the currently active autograd context for the current thread.
+  ContextPtr currentContext();
+
+  // Checks whether or not the current thread has a valid autograd context.
+  bool hasValidContext() const;
+
+  // Generate a new autograd_message_id for send/recv autograd functions.
+  int64_t newAutogradMessageId();
+
+  // Creates a new autograd context with the provided context_id. If a context
+  // already exists with the provided context_id, we just return it.
+  // This does not set the current context for the current thread.
+  ContextPtr getOrCreateContext(int64_t context_id);
+
+  // Retrieves the maximum possible autograd_context_id/autograd_message_id that
+  // can be generated by this worker.
+  int64_t getMaxId();
+
+  // Retrieves the worker ID for this node
+  rpc::worker_id_t getWorkerId() const;
+
+  // Can set current context id if there is no valid context yet
+  static void setCurrentContextId(int64_t contextId);
+
+  // Forcibly sets the thread local current context id. Should only be used in
+  // cases where you know what you're doing and need to override the thread
+  // local. Otherwise, use setCurrentContextId instead.
+  static void forceCurrentContextId(int64_t contextId);
+
+  // Clear current context id
+  void clearCurrentContext();
+
+  // Returns the number of autograd contexts in the container.
+  size_t numAutogradContexts() const;
+
+  // Returns the current thread local context id for this thread.
+  static int64_t currentContextId();
+
+  DistAutogradContainer(const DistAutogradContainer&) = delete;
+  DistAutogradContainer& operator=(const DistAutogradContainer&) = delete;
+  DistAutogradContainer(DistAutogradContainer&&) = delete;
+  DistAutogradContainer& operator=(DistAutogradContainer&&) = delete;
+
+ private:
+  // Number of shards for the map storing autograd contexts. We'd like this
+  // to be a power of 2 and we don't expect a value much higher than the
+  // number of cores would provide much benefit.
+  static constexpr uint32_t kNumDefaultShards = 128;
+
+  // Use cache line size for alignment.
+  static constexpr int kCacheLineSize = 64;
+
+  // Structure holding one shard of the sharded autograd context map with its
+  // associated lock. Align to cache line size to avoid contention between
+  // adjacent entries.
+  struct alignas(kCacheLineSize) ContextsShard {
+    // Lock for this shard.
+    mutable std::mutex lock;
+
+    // Map storing autograd contexts for this shard.
+    std::unordered_map contexts;
+  };
+
+  DistAutogradContainer() = delete;
+  ~DistAutogradContainer() = default;
+
+  static DistAutogradContainer& getInstanceInternal();
+
+  // Retrieve the shard for given context_id.
+  ContextsShard& getShard(int64_t context_id);
+
+  // Sends an RPC to the workers that have a context corresponding to passed in
+  // context_id. This function should be called with the lock.
+  void sendReleaseContextRpc(
+      const std::unordered_set& workerIds,
+      int64_t context_id);
+
+  // Erase context_id from the autograd context map, and reset the thread local
+  // current context id if it corresponds to the passed in context id. This
+  // function should be called with the lock.
+  void eraseContextIdAndReset(ContextsShard& shard, int64_t context_id);
+
+  // Compute the number of shards for the autograd_contexts_ map.
+  static uint32_t computeNumShards();
+
+  // Auto incrementing context id used to identify unique autograd passes.
+  // Initialized with the first 16 bits being the worker_id.
+  std::atomic next_context_id_;
+
+  // Unique id to identify a worker in the distributed setting.
+  int16_t worker_id_;
+
+  // Whether or not the container has been initialized appropriately.
+  bool initialized_;
+
+  // Sharded autograd context map.
+  std::vector autograd_contexts_;
+
+  // Number of shards for the sharded autograd_contexts_ map.
+  uint32_t num_shards_;
+
+  // Autograd message id to identify unique send/recv autograd function pairs.
+  std::atomic next_autograd_message_id_;
+
+  // Maximum allowed value for autograd_context_id or autograd_message_id.
+  int64_t max_id_;
+};
+
+} // namespace autograd
+} // namespace distributed
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/context/context.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/context/context.h
new file mode 100644
index 0000000000000000000000000000000000000000..bf8bb7cdef8c06cd638532c4671cd2875b7d7796
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/context/context.h
@@ -0,0 +1,174 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace distributed {
+namespace autograd {
+
+class RecvRpcBackward;
+
+// DistAutogradContext which stores information for a single distributed
+// autograd pass on a worker.
+class TORCH_API DistAutogradContext {
+ public:
+  using GradCallback = std::function;
+
+  explicit DistAutogradContext(int64_t contextId);
+
+  // Retrieves the autograd context id for this context.
+  int64_t contextId() const;
+
+  // Records a 'send' autograd function for this context with the provided
+  // message id.
+  void addSendFunction(
+      const std::shared_ptr& func,
+      int64_t autograd_message_id);
+
+  // Records a 'recv' autograd function for this context with the provided
+  // message id.
+  void addRecvFunction(
+      std::shared_ptr& func,
+      int64_t autograd_message_id);
+
+  // Given an autograd_message_id, retrieve the appropriate send function.
+  std::shared_ptr retrieveSendFunction(
+      int64_t autograd_message_id);
+
+  // Return all send functions for this context.
+  std::unordered_map> sendFunctions()
+      const;
+
+  // Return all recv functions for this context.
+  std::unordered_map> recvFunctions()
+      const;
+
+  // Adds a future message recording an outstanding RPC.
+  void addOutstandingRpc(const c10::intrusive_ptr& jitFuture);
+
+  // Returns all gradients.
+  const c10::Dict getGradients() const;
+
+  // This function gives a mutable grad reference to the callback.
+  // If the callback returns true, it means the grad in the context
+  // needs to be updated.
+  void runGradCallbackForVariable(
+      const torch::autograd::Variable& variable,
+      GradCallback&& cb);
+
+  DistAutogradContext(const DistAutogradContext&) = delete;
+  DistAutogradContext& operator=(const DistAutogradContext&) = delete;
+  DistAutogradContext(DistAutogradContext&&) = delete;
+  DistAutogradContext& operator=(DistAutogradContext&&) = delete;
+
+  // records the workerID of a node that we sent an RPC to.
+  // workerIDs are added here when we attach a send function to this autograd
+  // context
+  void addKnownWorkerId(const rpc::worker_id_t workerId);
+
+  // Retrieves a set containing the known workerIds for this context
+  // These are the different workers that this context has sent RPCs to.
+  std::unordered_set getKnownWorkerIds() const;
+
+ private:
+  friend class BackwardPassCleanupGuard;
+  friend class DistEngine;
+  friend class RecvRpcBackward;
+  friend class DistAccumulateGradCaptureHook;
+
+  // Record that we would like to accumulate the provided gradient on the given
+  // variable.
+  void accumulateGrad(
+      const torch::autograd::Variable& variable,
+      const torch::Tensor& grad,
+      size_t num_expected_refs);
+
+  // Retrieve the GraphTask.
+  std::shared_ptr retrieveGraphTask();
+
+  // Set the appropriate graph task for the backward pass. Can be called only
+  // once.
+  void setGraphTask(std::shared_ptr graphTask);
+
+  // Resets the graph task to ensure we can run another distributed backward
+  // pass for the same autograd context.
+  void resetGraphTask();
+
+  // Waits for all outstanding RPCs for this context to finish and clears all
+  // outstanding rpcs held in this context. This should be called only once.
+  c10::intrusive_ptr clearAndWaitForOutstandingRpcsAsync();
+
+  void clearOutstandingRpcs();
+
+  // Record an event to mark the completion of gradient computation. These
+  // events will later help to properly synchronize gradients consumptions
+  // in getGradients(). We need these events because backward and
+  // optimizer.step are separate RPC calls, and will occur on different CUDA
+  // streams. Without synchronization, it is possible that gradients are
+  // consumed before they are ready.
+  void recordGradEvent(c10::Device device);
+
+  const int64_t contextId_;
+
+  // Set containing known worker IDs, used in cleaning up autograd context.
+  // Whenever a sendRpcBackward is attached to the autograd graph for this
+  // context, the destination is added here.
+  std::unordered_set knownWorkerIds_;
+
+  // Map from autograd_message_id to appropriate 'send' autograd function.
+  std::unordered_map>
+      sendAutogradFunctions_;
+
+  // Map from autograd_message_id to appropriate 'recv' autograd function.
+  std::unordered_map>
+      recvAutogradFunctions_;
+
+  // Gradients accumulated in this context so far. The key is the variable on
+  // which the gradient needs to be accumulated and the value is the gradient
+  // that needs to be accumulated on that variable..
+  c10::Dict accumulatedGrads_;
+
+  // See comments for recordGradEvent(c10::Device device);
+  std::unordered_map gradReadyEvents_;
+  const c10::impl::VirtualGuardImpl impl_;
+
+  // The autograd GraphTask for the backward pass on this node for this context.
+  std::shared_ptr graphTask_;
+
+  // List of futures for RPCs initiated by this node to propagate gradients to
+  // other nodes. The distributed autograd engine on this node can return
+  // successfully only if all these futures are done and are successful.
+  std::vector> outStandingRpcs_;
+
+  // Lock to protect concurrent modification of the context.
+  mutable std::mutex lock_;
+};
+
+using ContextPtr = std::shared_ptr;
+
+// This class stores a shared_ptr to a DistAutogradContext instance in a
+// thread local variable. The instance is given by the call site. The class
+// doesn't know the current context. It's just a util class.
+class TORCH_API ThreadLocalDistAutogradContext {
+ public:
+  // Store 'new_context' to the thread local variable maintained by this class.
+  explicit ThreadLocalDistAutogradContext(ContextPtr&& new_context);
+  ~ThreadLocalDistAutogradContext();
+
+  // Retrieve the stored DistAutogradContext instance.
+  static ContextPtr getContextPtr();
+
+ private:
+  ContextPtr prev_context_ptr_;
+};
+
+} // namespace autograd
+} // namespace distributed
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/functions/recvrpc_backward.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/functions/recvrpc_backward.h
new file mode 100644
index 0000000000000000000000000000000000000000..6e6678b1289859eb162a96ccd3063d94a9e5e0fe
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/functions/recvrpc_backward.h
@@ -0,0 +1,49 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace distributed {
+namespace autograd {
+
+// Forward declarations.
+class DistAutogradContext;
+
+// As part of our distributed autograd implementation, whenever we receive an
+// RPC from a node, we add a 'RecvRpcBackward' autograd function to the
+// autograd graph. This is more or less a placeholder function that is used to
+// pass gradients to the remote host during the backward pass. The inputs to the
+// RPC function are the inputs to this autograd function.
+class TORCH_API RecvRpcBackward : public torch::autograd::Node {
+ public:
+  explicit RecvRpcBackward(
+      const AutogradMetadata& autogradMetadata,
+      std::shared_ptr autogradContext,
+      rpc::worker_id_t fromWorkerId,
+      rpc::DeviceMap deviceMap);
+
+  torch::autograd::variable_list apply(
+      torch::autograd::variable_list&& grads) override;
+
+ private:
+  const AutogradMetadata autogradMetadata_;
+
+  // Hold a weak reference to the autograd context to avoid circular
+  // dependencies with the context (since it holds a reference to
+  // RecvRpcBackward).
+  std::weak_ptr autogradContext_;
+
+  // The worker id from which the RPC was received. During the backward pass,
+  // we need to propagate the gradients to this workerId.
+  rpc::worker_id_t fromWorkerId_;
+
+  // Device mapping for tensors sent over RPC.
+  const rpc::DeviceMap deviceMap_;
+};
+
+} // namespace autograd
+} // namespace distributed
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/functions/sendrpc_backward.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/functions/sendrpc_backward.h
new file mode 100644
index 0000000000000000000000000000000000000000..ff576ace174fdfae29abafdec3678532e03cc29d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/functions/sendrpc_backward.h
@@ -0,0 +1,37 @@
+#pragma once
+
+#include 
+
+namespace torch {
+namespace distributed {
+namespace autograd {
+
+// As part of our distributed autograd implementation, whenever we send an RPC
+// from one node to another, we add a 'SendRpcBackward' autograd function to the
+// autograd graph. This is more or less a placeholder function that is used to
+// kickoff the autograd engine on the current worker on the backward pass. The
+// edges for this autograd function are the inputs to the RPC method.
+//
+// During the backward pass, this function is queued for execution in the
+// autograd engine which eventually runs the rest of the autograd graph.
+struct TORCH_API SendRpcBackward : public torch::autograd::Node {
+ public:
+  torch::autograd::variable_list apply(
+      torch::autograd::variable_list&& inputs) override;
+
+  // SendRpcBackward is actually the root of an autograd graph on the local
+  // node. As a result, it doesn't receive any 'inputs', but rather the RPC
+  // framework passes gradients over to this function to kickoff local autograd
+  // computation.
+  void setGrads(const torch::autograd::variable_list& grads);
+
+  // Retrieve the grads for the function.
+  const torch::autograd::variable_list& getGrads() const;
+
+ private:
+  torch::autograd::variable_list grads_;
+};
+
+} // namespace autograd
+} // namespace distributed
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/autograd_metadata.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/autograd_metadata.h
new file mode 100644
index 0000000000000000000000000000000000000000..1d5aefbd2010a76a05ab90de3c71d096377ecc82
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/autograd_metadata.h
@@ -0,0 +1,25 @@
+#pragma once
+
+#include 
+#include 
+
+namespace torch {
+namespace distributed {
+namespace autograd {
+
+// This structure represents autograd metadata that we need to pass across
+// different nodes when we call an RPC which needs autograd computation.
+struct TORCH_API AutogradMetadata {
+  AutogradMetadata(int64_t autogradContextId, int64_t autogradMessageId);
+
+  // autogradContextId_ is a globally unique integer that identifies a
+  // particular distributed autograd pass.
+  int64_t autogradContextId;
+  // autogradMessageId_ is a globally unique integer that identifies a pair
+  // of send/recv autograd functions.
+  int64_t autogradMessageId;
+};
+
+} // namespace autograd
+} // namespace distributed
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/cleanup_autograd_context_req.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/cleanup_autograd_context_req.h
new file mode 100644
index 0000000000000000000000000000000000000000..525790b8c86b4d10f03b6f84a73a31c6a253bef1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/cleanup_autograd_context_req.h
@@ -0,0 +1,29 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace distributed {
+namespace autograd {
+
+// Used to request other workers to clean up their autograd context.
+class TORCH_API CleanupAutogradContextReq : public rpc::RpcCommandBase {
+ public:
+  explicit CleanupAutogradContextReq(int64_t context_id);
+  // Serialization and deserialization methods.
+  c10::intrusive_ptr toMessageImpl() && override;
+  static std::unique_ptr fromMessage(
+      const rpc::Message& message);
+
+  // Retrieve the context id we are cleaning up with this message.
+  int64_t getContextId();
+
+ private:
+  int64_t context_id_;
+};
+
+} // namespace autograd
+} // namespace distributed
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/cleanup_autograd_context_resp.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/cleanup_autograd_context_resp.h
new file mode 100644
index 0000000000000000000000000000000000000000..5b55fad7190c6efa71020dd024c7da62f58acfd9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/cleanup_autograd_context_resp.h
@@ -0,0 +1,23 @@
+#pragma once
+
+#include 
+#include 
+
+namespace torch {
+namespace distributed {
+namespace autograd {
+
+// Empty response for CleanupAutogradContextReq. Send to acknowledge receipt of
+// a CleanupAutogradContextReq.
+class TORCH_API CleanupAutogradContextResp : public rpc::RpcCommandBase {
+ public:
+  CleanupAutogradContextResp() = default;
+  // Serialization and deserialization methods.
+  c10::intrusive_ptr toMessageImpl() && override;
+  static std::unique_ptr fromMessage(
+      const rpc::Message& message);
+};
+
+} // namespace autograd
+} // namespace distributed
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/propagate_gradients_req.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/propagate_gradients_req.h
new file mode 100644
index 0000000000000000000000000000000000000000..4bb58f35852137492d3886095242b77245224c5d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/propagate_gradients_req.h
@@ -0,0 +1,42 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace distributed {
+namespace autograd {
+
+// Used to propagate gradients from one node to another during a distributed
+// backwards pass. This RPC call is invoked when we hit a `recv` autograd
+// function during backward pass execution.
+class TORCH_API PropagateGradientsReq : public rpc::RpcCommandBase {
+ public:
+  PropagateGradientsReq(
+      const AutogradMetadata& autogradMetadata,
+      std::vector grads,
+      bool retainGraph = false);
+
+  const AutogradMetadata& getAutogradMetadata();
+
+  const std::vector& getGrads();
+
+  // Serialization and deserialization methods.
+  c10::intrusive_ptr toMessageImpl() && override;
+  static std::unique_ptr fromMessage(
+      const rpc::Message& message);
+
+  // Whether or not to retain the autograd graph.
+  bool retainGraph();
+
+ private:
+  AutogradMetadata autogradMetadata_;
+  std::vector grads_;
+  bool retainGraph_;
+};
+
+} // namespace autograd
+} // namespace distributed
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/propagate_gradients_resp.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/propagate_gradients_resp.h
new file mode 100644
index 0000000000000000000000000000000000000000..5e2ed0f0e34eb09f0ec029a6491ffd988042516c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/propagate_gradients_resp.h
@@ -0,0 +1,24 @@
+#pragma once
+
+#include 
+#include 
+
+namespace torch {
+namespace distributed {
+namespace autograd {
+
+// Response for the PropagateGradients call. Currently, this class is mostly
+// just a placeholder and sends an empty message over the wire. The purpose of
+// this RPC command is to indicate whether or not the PropagateGradientsReq call
+// was successfully or not.
+class TORCH_API PropagateGradientsResp : public rpc::RpcCommandBase {
+ public:
+  PropagateGradientsResp() = default;
+  c10::intrusive_ptr toMessageImpl() && override;
+  static std::unique_ptr fromMessage(
+      const rpc::Message& message);
+};
+
+} // namespace autograd
+} // namespace distributed
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_autograd.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_autograd.h
new file mode 100644
index 0000000000000000000000000000000000000000..6d0b6111cc88cd5a1df33d334851f8d17e166941
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_autograd.h
@@ -0,0 +1,98 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace distributed {
+namespace autograd {
+
+// Represents an RPC that includes autograd information. This class basically
+// wraps another `RpcCommandBase` object which represents the actual RPC and has
+// additional autograd information associated with that RPC.
+class TORCH_API RpcWithAutograd final : public rpc::RpcCommandBase {
+ public:
+  // Used when we are sending an RPC over the wire.
+  RpcWithAutograd(
+      rpc::worker_id_t fromWorkerId,
+      rpc::MessageType messageType,
+      const AutogradMetadata& autogradMetadata,
+      c10::intrusive_ptr wrappedMessage,
+      rpc::DeviceMap deviceMap = {});
+
+  // Used when receiving an RPC over the wire.
+  RpcWithAutograd(
+      rpc::worker_id_t fromWorkerId,
+      rpc::MessageType messageType,
+      const AutogradMetadata& autogradMetadata,
+      std::unique_ptr wrappedRpc,
+      rpc::MessageType wrappedMessageType,
+      std::vector tensors,
+      rpc::DeviceMap deviceMap = {});
+
+  c10::intrusive_ptr toMessageImpl() && override;
+
+  static std::unique_ptr fromMessage(
+      const rpc::Message& message);
+
+  // Retrieves tensors as part of this RPC, which need to be considered for
+  // autograd computations.
+  std::vector& tensors();
+
+  const AutogradMetadata& autogradMetadata() const;
+
+  RpcCommandBase& wrappedRpc();
+
+  void setWrappedRpc(std::unique_ptr wrappedRpc);
+
+  std::unique_ptr moveWrappedRpc() &&;
+
+  // Message type of the wrapped RPC.
+  rpc::MessageType wrappedMessageType() const;
+
+  // Retrieve the worker id from which the RPC originated.
+  rpc::worker_id_t fromWorkerId() const;
+
+  // Retrieve the device map.
+  const rpc::DeviceMap& deviceMap();
+
+ private:
+  // WorkerId from which this RPC originated. This is necessary for knowing
+  // which worker we need to contact during the backward pass.
+  rpc::worker_id_t fromWorkerId_;
+
+  // Message type for this call.
+  rpc::MessageType messageType_;
+
+  AutogradMetadata autogradMetadata_;
+
+  // Since wrappedMessage_ is destructively constructed from wrappedRpc_,
+  // they are valid exclusively. They are used for different purpose.
+  // wrappedRpc_ is used while constructing receive rpcWithAutograd;
+  // wrappedMessage_ is used while constructing send rpcWithAutograd;
+
+  // When receive rpcWithAutograd is constructed fromMessage, it is valid;
+  // When send rpcWithAutograd is constructed before toMessage, it is nullptr;
+  std::unique_ptr wrappedRpc_;
+
+  // Serialized message representing wrappedRpc_. Used mostly as a cache to
+  // avoid serializing the request twice.
+  // When receive rpcWithAutograd is constructed fromMessage, it is nullptr;
+  // When send rpcWithAutograd is constructed before toMessage, it is valid;
+  c10::intrusive_ptr wrappedMessage_;
+
+  // message type of the wrappedMessage, this is stored separately since
+  // wrappedMessage_ is not always guaranteed to be populated.
+  rpc::MessageType wrappedMessageType_;
+
+  // Tensors part of the wrappedRpc that need to be considered for autograd.
+  std::vector tensors_;
+
+  // Device mapping for tensors that are sent across an RPC to another node.
+  rpc::DeviceMap deviceMap_;
+};
+
+} // namespace autograd
+} // namespace distributed
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_profiling_req.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_profiling_req.h
new file mode 100644
index 0000000000000000000000000000000000000000..e25728d79194aed9053b2475d48580f735ba53c0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_profiling_req.h
@@ -0,0 +1,62 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace distributed {
+namespace autograd {
+
+class TORCH_API RpcWithProfilingReq : public rpc::RpcCommandBase {
+ public:
+  // For sending RPCs, invoked when client is creating this RPC command.
+  RpcWithProfilingReq(
+      rpc::MessageType messageType,
+      c10::intrusive_ptr wrappedMessage,
+      torch::autograd::profiler::ProfilerConfig&& profilerConfig,
+      rpc::ProfilingId profilingKeyId);
+
+  // For receiving an RPC
+  // Used in fromMessage.
+  RpcWithProfilingReq(
+      rpc::MessageType messageType,
+      std::unique_ptr wrappedRpc,
+      rpc::MessageType wrappedMessageType,
+      std::vector tensors,
+      torch::autograd::profiler::ProfilerConfig&& profilerConfig,
+      rpc::ProfilingId profilingKeyId);
+
+  // Convert this RPC Command to a Message that can be sent over the wire.
+  c10::intrusive_ptr toMessageImpl() && override;
+  static std::unique_ptr fromMessage(
+      const rpc::Message& message);
+
+  // Retrieve the profiling data that is associated with this command.
+  torch::autograd::profiler::ProfilerConfig getProfilingConfig() const;
+  // Retrieve the globally unique profiling ID corresponding to this command.
+  const rpc::ProfilingId& getProfilingId() const;
+  // Retrieve the original RPC which this ProfilingRPC wraps.
+  RpcCommandBase& wrappedRpc();
+  // Destructively move the wrapped RPC.
+  std::unique_ptr moveWrappedRpc() &&;
+  // Message type of the wrapped RPC
+  rpc::MessageType wrappedMessageType() const;
+  void setWrappedRpc(std::unique_ptr wrappedRpc);
+
+ private:
+  // message type
+  const rpc::MessageType messageType_;
+  // wrapped message
+  c10::intrusive_ptr wrappedMessage_;
+  std::unique_ptr wrappedRpc_;
+  rpc::MessageType wrappedMessageType_;
+  std::vector tensors_;
+  const torch::autograd::profiler::ProfilerConfig profilerConfig_;
+  const rpc::ProfilingId profilingKeyId_;
+};
+} // namespace autograd
+} // namespace distributed
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_profiling_resp.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_profiling_resp.h
new file mode 100644
index 0000000000000000000000000000000000000000..fef0055e04be28873dc684bd79b168273e68fe50
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_profiling_resp.h
@@ -0,0 +1,59 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace distributed {
+namespace autograd {
+class TORCH_API RpcWithProfilingResp : public rpc::RpcCommandBase {
+ public:
+  // For sending RPCs over the wire
+  RpcWithProfilingResp(
+      rpc::MessageType messageType,
+      c10::intrusive_ptr wrappedMessage,
+      std::vector profiledEvents,
+      rpc::ProfilingId profilingId);
+
+  // For receiving RPCs. Used in from message when converting a message received
+  // over the wire.
+  RpcWithProfilingResp(
+      rpc::MessageType messageType,
+      std::unique_ptr wrappedRpc,
+      rpc::MessageType wrappedMessageType,
+      std::vector tensors,
+      std::vector profiledEvents,
+      rpc::ProfilingId profilingId);
+  c10::intrusive_ptr toMessageImpl() && override;
+  static std::unique_ptr fromMessage(
+      const rpc::Message& message);
+  // Retrieve remote Events
+  std::vector getProfiledEvents() const;
+  // Retrieve the globally unique profiling ID corresponding to this command.
+  const rpc::ProfilingId& getProfilingId() const;
+  // Retrieve the original RPC which this ProfilingRPC wraps.
+  RpcCommandBase& wrappedRpc();
+  // Destructively move the wrapped RPC.
+  std::unique_ptr moveWrappedRpc() &&;
+  // Message type of the wrapped RPC
+  rpc::MessageType wrappedMessageType() const;
+  // Set the wrapped RPC for this RPC.
+  void setWrappedRpc(std::unique_ptr wrappedRpc);
+
+ private:
+  // message type
+  const rpc::MessageType messageType_;
+  // wrapped message
+  c10::intrusive_ptr wrappedMessage_;
+  std::unique_ptr wrappedRpc_;
+  rpc::MessageType wrappedMessageType_;
+  std::vector tensors_;
+  const std::vector profiledEvents_;
+  const rpc::ProfilingId profilingId_;
+};
+} // namespace autograd
+} // namespace distributed
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rref_backward_req.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rref_backward_req.h
new file mode 100644
index 0000000000000000000000000000000000000000..6dc4413cfa50980af4df98bd88c9fd57e86a2a75
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rref_backward_req.h
@@ -0,0 +1,39 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace distributed {
+namespace autograd {
+
+// Internal system RPC to invoke distributed backward pass on remote nodes when
+// 'rref.backward()' is invoked.
+class TORCH_API RRefBackwardReq : public rpc::RpcCommandBase {
+ public:
+  RRefBackwardReq(
+      const rpc::RRefId& rrefId,
+      int64_t autogradContextId,
+      bool retainGraph = false);
+
+  const rpc::RRefId& getRRefId() const;
+
+  int64_t getAutogradContextId() const;
+
+  bool retainGraph() const;
+
+  // Serialization and deserialization methods.
+  c10::intrusive_ptr toMessageImpl() && override;
+  static std::unique_ptr fromMessage(
+      const rpc::Message& message);
+
+ private:
+  const rpc::RRefId rrefId_;
+  const int64_t autogradContextId_;
+  const bool retainGraph_;
+};
+
+} // namespace autograd
+} // namespace distributed
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rref_backward_resp.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rref_backward_resp.h
new file mode 100644
index 0000000000000000000000000000000000000000..2ce4d6f3fa84264dee58733070a7c42592f1af53
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rref_backward_resp.h
@@ -0,0 +1,21 @@
+#pragma once
+
+#include 
+#include 
+
+namespace torch {
+namespace distributed {
+namespace autograd {
+
+// Response for the RRefBackwardReq.
+class TORCH_API RRefBackwardResp : public rpc::RpcCommandBase {
+ public:
+  RRefBackwardResp() = default;
+  c10::intrusive_ptr toMessageImpl() && override;
+  static std::unique_ptr fromMessage(
+      const rpc::Message& message);
+};
+
+} // namespace autograd
+} // namespace distributed
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/Backend.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/Backend.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..b75e457b8cd01c4344b93c3eb3231e297784d19d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/Backend.hpp
@@ -0,0 +1,416 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+
+constexpr auto kBackendDefaultTimeout =
+    std::chrono::milliseconds(30 * 60 * 1000);
+
+namespace c10d {
+
+class TORCH_API Backend : public torch::CustomClassHolder {
+ public:
+  // Backend Options is a base struct that defines the basic options
+  // when constructing a Backend. Each Backend subclass should
+  // extend this struct and define its options if it wants to provide more
+  // config options (beyond basic ones defined here) to end user.
+  struct TORCH_API Options : torch::CustomClassHolder {
+    explicit Options(
+        std::string backend,
+        std::chrono::milliseconds timeout = kBackendDefaultTimeout)
+        : timeout(timeout), backend(std::move(backend)) {}
+    ~Options() override = default;
+
+    std::chrono::milliseconds timeout;
+
+    // backend name
+    // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
+    const std::string backend;
+  };
+
+  explicit Backend(int rank, int size);
+  ~Backend() override = 0;
+
+  int getRank() const {
+    return rank_;
+  }
+
+  int getSize() const {
+    return size_;
+  }
+
+  // Returns an unique opaque ID of this backend that can be used to correlate
+  // with its collectives.
+  int64_t getID() const {
+    return reinterpret_cast(this);
+  }
+
+  virtual bool supportsSplitting() const {
+    return false;
+  }
+
+  virtual void startCoalescing() {
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ",
+            getBackendName(),
+            " does not implement startCoalescing"));
+  }
+
+  virtual c10::intrusive_ptr endCoalescing() {
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ", getBackendName(), " does not implement endCoalescing"));
+  }
+
+  // Subclasses must override this method to return the backend name
+  virtual const std::string getBackendName() const {
+    TORCH_INTERNAL_ASSERT(false, "getBackendName is not implemented.");
+  };
+
+  virtual c10::intrusive_ptr broadcast(
+      std::vector& /* tensors */,
+      const BroadcastOptions& /* opts */ = BroadcastOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str("Backend ", getBackendName(), " does not support broadcast"));
+  }
+
+  virtual c10::intrusive_ptr allreduce(
+      std::vector& /* tensors */,
+      const AllreduceOptions& /* opts */ = AllreduceOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str("Backend ", getBackendName(), " does not support allreduce"));
+  }
+
+  virtual c10::intrusive_ptr allreduce_sparse(
+      std::vector& /* tensors */,
+      const AllreduceOptions& /* opts */ = AllreduceOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ",
+            getBackendName(),
+            " does not support allreduce sparse"));
+  }
+
+  virtual c10::intrusive_ptr allreduce_coalesced(
+      std::vector& /* tensors */,
+      const AllreduceCoalescedOptions& /* opts */ =
+          AllreduceCoalescedOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ",
+            getBackendName(),
+            " does not support allreduce_coalesced"));
+  }
+
+  virtual c10::intrusive_ptr reduce(
+      std::vector& /* tensors */,
+      const ReduceOptions& /* opts */ = ReduceOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str("Backend ", getBackendName(), " does not support reduce"));
+  }
+
+  virtual c10::intrusive_ptr allgather(
+      std::vector>& /* outputTensors */,
+      std::vector& /* inputTensors */,
+      const AllgatherOptions& /* opts */ = AllgatherOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str("Backend ", getBackendName(), " does not support allgather"));
+  }
+
+  // Gathers a single tensor inputBuffer into a single buffer outputBuffer that
+  // is interpreted as a contiguous collection of size inputBuffer * WORLD_SIZE.
+  // For implementers of ProcessGroup API and advanced users only.
+  // Note: this function will be deprecated in near future.
+  virtual c10::intrusive_ptr _allgather_base(
+      at::Tensor& /* outputBuffer */,
+      at::Tensor& /* inputBuffer */,
+      const AllgatherOptions& /* opts */ = AllgatherOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ", getBackendName(), " does not support _allgather_base"));
+  }
+
+  // This function is deprecated and will be moved out of Backend to comms:
+  // * do not add dependencies on this function,
+  // * do not implement it in your Backend, implement _allgather_base
+  //   instead.
+  virtual c10::intrusive_ptr allgather_coalesced(
+      std::vector>& /* outputTensorLists */,
+      std::vector& /* inputTensors */,
+      const AllgatherOptions& /* opts */ = AllgatherOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ",
+            getBackendName(),
+            " does not support allgather_coalesced"));
+  }
+
+  // This function is a coalesced version of `allgather_into_tensor` (currently
+  // still named as `_allgather_base`). Each tensor in the vector corresponds to
+  // an input/output of one `allgather_into_tensor` operation.
+  virtual c10::intrusive_ptr allgather_into_tensor_coalesced(
+      std::vector& /* outputs */,
+      std::vector& /* inputs */,
+      const AllgatherOptions& /* opts */ = AllgatherOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ",
+            getBackendName(),
+            " does not support allgather_into_tensor_coalesced"));
+  }
+
+  virtual c10::intrusive_ptr gather(
+      std::vector>& /* outputTensors */,
+      std::vector& /* inputTensors */,
+      const GatherOptions& /* opts */ = GatherOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str("Backend ", getBackendName(), " does not support gather"));
+  }
+
+  virtual c10::intrusive_ptr scatter(
+      std::vector& /* outputTensors */,
+      std::vector>& /* inputTensors */,
+      const ScatterOptions& /* opts */ = ScatterOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str("Backend ", getBackendName(), " does not support scatter"));
+  }
+
+  virtual c10::intrusive_ptr reduce_scatter(
+      std::vector& /* outputTensors */,
+      std::vector>& /* inputTensors */,
+      const ReduceScatterOptions& /* opts */ = ReduceScatterOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ", getBackendName(), " does not support reduce_scatter"));
+  }
+
+  virtual c10::intrusive_ptr _reduce_scatter_base(
+      at::Tensor& /* outputBuffer */,
+      at::Tensor& /* inputBuffer */,
+      const ReduceScatterOptions& /* opts */ = ReduceScatterOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ",
+            getBackendName(),
+            " does not support _reduce_scatter_base"));
+  }
+
+  // This function is a coalesced version of `reduce_scatter_tensor` (currently
+  // still named as `_reduce_scatter_base`). Each tensor in the vector
+  // corresponds to an input/output of one `reduce_scatter_tensor` operation.
+  virtual c10::intrusive_ptr reduce_scatter_tensor_coalesced(
+      std::vector& /* outputs */,
+      std::vector& /* inputs */,
+      const ReduceScatterOptions& /* opts */ = ReduceScatterOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ",
+            getBackendName(),
+            " does not support reduce_scatter_tensor_coalesced"));
+  }
+
+  virtual c10::intrusive_ptr alltoall_base(
+      at::Tensor& /* outputBuffer */,
+      at::Tensor& /* inputBuffer */,
+      std::vector& /* outputSplitSizes */,
+      std::vector& /* inputSplitSizes */,
+      const AllToAllOptions& /* opts */ = AllToAllOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ", getBackendName(), " does not support alltoall_base"));
+  }
+
+  virtual c10::intrusive_ptr alltoall(
+      std::vector& /* outputTensors */,
+      std::vector& /* inputTensors */,
+      const AllToAllOptions& opts = AllToAllOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str("Backend ", getBackendName(), " does not support alltoall"));
+  }
+
+  virtual void monitoredBarrier(
+      const BarrierOptions& /* unused */,
+      bool /* unused */ = false) {
+    auto backendName = getBackendName();
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ",
+            backendName,
+            " does not support monitoredBarrier, only GLOO supports monitored barrier."));
+  }
+
+  // Agrees on an initial sequence number for the whole group by having rank 0
+  // create it and broadcast it to other ranks using the store. Only implemented
+  // for GLOO and NCCL backends currently.
+  virtual void setSequenceNumberForGroup() {
+    auto backendName = getBackendName();
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ",
+            backendName,
+            " does not yet support sequence numbers."));
+  }
+
+  // Retrieves the current sequence number for the whole group, which should be
+  // in sync. If the returned number is not consistent across the group, it
+  // may indicate that there is some sort of collective desynchronization.
+  virtual uint64_t getSequenceNumberForGroup() {
+    auto backendName = getBackendName();
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ",
+            backendName,
+            " does not yet support sequence numbers."));
+  }
+
+  virtual c10::intrusive_ptr send(
+      std::vector& /* tensors */,
+      int /* dstRank */,
+      int /* tag */) {
+    TORCH_CHECK(
+        false,
+        c10::str("Backend ", getBackendName(), " does not support send"));
+  }
+
+  virtual c10::intrusive_ptr recv(
+      std::vector& /* tensors */,
+      int /* srcRank */,
+      int /* tag */) {
+    TORCH_CHECK(
+        false,
+        c10::str("Backend ", getBackendName(), " does not support recv"));
+  }
+
+  virtual c10::intrusive_ptr recvAnysource(
+      std::vector& /* tensors */,
+      int /* tag */) {
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ", getBackendName(), " does not support recvAnysource"));
+  }
+
+  virtual c10::intrusive_ptr barrier(
+      const BarrierOptions& /* opts */ = BarrierOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str("Backend ", getBackendName(), " does not support barrier"));
+  }
+
+  virtual void registerOnCompletionHook(
+      std::function)>&& hook) {
+    TORCH_CHECK(
+        false,
+        "Only ProcessGrouppNCCL supports onCompletion hook, but got ",
+        getBackendName(),
+        " backend.");
+  }
+
+  virtual void waitForPendingWorks() {
+    TORCH_CHECK(
+        false,
+        "Only ProcessGrouppNCCL supports waitForPendingWorks, but got ",
+        getBackendName(),
+        " backend.");
+  }
+
+  virtual void enableCollectivesTiming() {
+    TORCH_CHECK(
+        false,
+        "Backend ",
+        getBackendName(),
+        " is missing implementation of enableCollectivesTiming.");
+  }
+
+  bool hasHooks() const {
+    return onCompletionHook_ != nullptr;
+  }
+
+  // Do not call this directly, use ProcessGroup::setGroupName instead.
+  void setGroupUid(const std::string& pg_uid) {
+    pg_uid_ = pg_uid;
+  }
+
+  const std::string& getGroupUid() const {
+    return pg_uid_;
+  }
+
+  void setGroupDesc(const std::string& desc) {
+    pg_desc_ = desc;
+  }
+
+  const std::string& getGroupDesc() const {
+    return pg_desc_;
+  }
+
+  // See similar functions in ProcessGroup.hpp for context.
+  std::optional getBoundDeviceId() const {
+    return bound_device_id_;
+  }
+
+  // Perform an eager connect to the specified device if the backend supports
+  // it.
+  virtual void eagerConnectSingleDevice(at::Device device) {
+    // no-op in the default case; this is an optimization some
+    // backends may perform
+  }
+
+  void setBoundDeviceId(std::optional device) {
+    if (device) {
+      TORCH_CHECK(device->has_index(), "setBoundDeviceId must have an index");
+    }
+    bound_device_id_ = device;
+  }
+
+ protected:
+  // Implementations of this interface need to call this to setup
+  // appropriate logging etc.
+  void init();
+
+  // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
+  const int rank_;
+  // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
+  const int size_;
+  // Debug level setting. It is parsed once when ProcessGroup is constructed and
+  // remains the same across use of this process group.
+  DebugLevel dist_debug_level_;
+  std::string pg_uid_;
+  std::string pg_desc_;
+
+  std::function)> onCompletionHook_;
+
+  std::optional bound_device_id_;
+};
+
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/Backoff.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/Backoff.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..de6da20ed825f24c32c205912b5897e277c2d302
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/Backoff.hpp
@@ -0,0 +1,52 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+
+namespace c10d {
+
+class TORCH_API Backoff {
+ public:
+  virtual ~Backoff() = default;
+
+  virtual std::chrono::milliseconds nextBackoff() = 0;
+  virtual void reset() = 0;
+
+  void sleepBackoff() {
+    std::this_thread::sleep_for(nextBackoff());
+  }
+};
+
+class TORCH_API ExponentialBackoffWithJitter : public Backoff {
+ public:
+  ExponentialBackoffWithJitter();
+
+  std::chrono::milliseconds nextBackoff() override;
+  void reset() override;
+
+ public:
+  std::chrono::milliseconds initialInterval{500};
+  double randomizationFactor{0.5};
+  double multiplier{1.5};
+  std::chrono::milliseconds maxInterval{60000};
+
+ private:
+  std::mt19937 gen_;
+  std::chrono::milliseconds currentInterval_{0};
+};
+
+class TORCH_API FixedBackoff : public Backoff {
+ public:
+  FixedBackoff(std::chrono::milliseconds interval);
+
+  std::chrono::milliseconds nextBackoff() override;
+  void reset() override;
+
+ private:
+  std::chrono::milliseconds interval_;
+};
+
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/CUDASymmetricMemory-inl.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/CUDASymmetricMemory-inl.h
new file mode 100644
index 0000000000000000000000000000000000000000..78d474dc5c7f54b14d18d72663464b80f896a960
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/CUDASymmetricMemory-inl.h
@@ -0,0 +1,256 @@
+#pragma once
+
+#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900) && CUDART_VERSION >= 12010
+#define NVCC_SUPPORTS_MULTICAST 1
+#endif
+
+#include 
+
+namespace c10d::symmetric_memory {
+
+constexpr size_t max_num_threads_per_block = 1024;
+constexpr size_t max_num_blocks = 8;
+
+template 
+size_t get_alignment(T ptr_or_size) {
+  auto val = reinterpret_cast(ptr_or_size);
+  if (val % 16 == 0) {
+    return 16;
+  } else if (val % 8 == 0) {
+    return 8;
+  } else if (val % 4 == 0) {
+    return 4;
+  } else if (val % 2 == 0) {
+    return 2;
+  } else {
+    return 1;
+  }
+}
+
+template <>
+size_t get_alignment(size_t size) {
+  return get_alignment(reinterpret_cast(size));
+}
+
+__device__ __forceinline__ uint32_t
+cas_sys(uint32_t* addr, uint32_t compare, uint32_t val) {
+#if defined(USE_ROCM) || (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 800))
+  CUDA_KERNEL_ASSERT(false);
+#else
+  uint32_t old_val;
+  asm volatile("atom.global.sys.cas.b32 %0, [%1], %2, %3;"
+               : "=r"(old_val)
+               : "l"(addr), "r"(compare), "r"(val)
+               : "memory");
+  return old_val;
+#endif
+}
+
+__device__ __forceinline__ uint32_t
+cas_release_sys(uint32_t* addr, uint32_t compare, uint32_t val) {
+#if defined(USE_ROCM) || (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 800))
+  CUDA_KERNEL_ASSERT(false);
+#else
+  uint32_t old_val;
+  asm volatile("atom.global.release.sys.cas.b32 %0, [%1], %2, %3;"
+               : "=r"(old_val)
+               : "l"(addr), "r"(compare), "r"(val)
+               : "memory");
+  return old_val;
+#endif
+}
+
+__device__ __forceinline__ void release_signal(uint32_t* addr) {
+  while (cas_release_sys(addr, 0, 1) != 0)
+    ;
+}
+
+__device__ __forceinline__ void wait_signal(uint32_t* addr) {
+  while (cas_sys(addr, 1, 0) != 1)
+    ;
+}
+
+__device__ __forceinline__ uint32_t acquire_signal(uint32_t* addr) {
+#if defined(USE_ROCM) || (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 800))
+  CUDA_KERNEL_ASSERT(false);
+#else
+  uint32_t val;
+  asm volatile("ld.acquire.sys.global.u32 %0, [%1];"
+               : "=r"(val)
+               : "l"(addr)
+               : "memory");
+  return val;
+#endif
+}
+
+// Perform a barrier to establish observation order between memory operations
+// issued before and after the barrier.
+__device__ __forceinline__ void barrier(
+    uint32_t** signal_pads,
+    size_t rank,
+    size_t world_size) {
+  if (threadIdx.x < world_size) {
+    auto target_rank = threadIdx.x;
+    release_signal(signal_pads[target_rank] + blockIdx.x * world_size + rank);
+    wait_signal(signal_pads[rank] + blockIdx.x * world_size + target_rank);
+  }
+  __syncthreads();
+}
+
+// Perform a barrier and establish causality order between memory operations
+// issued before the calling kernel on all devices and memory operations
+// issued after this function by all thread in the calling kernel.
+//
+// NOTE: this function does NOT ensure that memory operations issues in the
+// current kernel are visible to all threads in the current kernel.
+//
+// | mem ops (guaranteed to be visible by all threads at point T)
+// | kernel K
+// | +- mem ops (not guaranteed to be visible all threads at point T)
+// | +- barrier_and_acquire_previous_kernel_writes()
+// | +- point T
+// v
+__device__ __forceinline__ void barrier_and_acquire_previous_kernel_writes(
+    uint32_t** signal_pads,
+    size_t rank,
+    size_t world_size) {
+  if (threadIdx.x < world_size) {
+    auto target_rank = threadIdx.x;
+    release_signal(signal_pads[target_rank] + blockIdx.x * world_size + rank);
+    wait_signal(signal_pads[rank] + blockIdx.x * world_size + target_rank);
+  }
+  __syncthreads();
+  // At this point, we established observation order between memory operations
+  // issued before and after the barrier. Now we convert the observation order
+  // into causality order by having every thread acquire the signals released
+  // by threads on peer devices. Due to the implicit synchronizes-with
+  // relationships at task/kernel boundaries, acquiring the signal released by
+  // thread T in kernel K transitively acquires memory operations issued prior
+  // to kernel K.
+  //
+  // https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#memory-fence-interference
+  for (size_t target_rank = 0; target_rank < world_size; ++target_rank) {
+    acquire_signal(signal_pads[rank] + blockIdx.x * world_size + target_rank);
+  }
+}
+
+template 
+inline constexpr bool dependent_bool_value = Value;
+
+template 
+inline constexpr bool dependent_false = dependent_bool_value;
+
+template 
+union Vec;
+
+template <>
+union Vec<4> {
+  uint16_t u16[2];
+  uint32_t u32, as_scalar;
+};
+
+template <>
+union Vec<8> {
+  uint16_t u16[4];
+  uint32_t u32[2];
+  uint64_t u64, as_scalar;
+};
+
+template <>
+union alignas(16) Vec<16> {
+  uint16_t u16[8];
+  uint32_t u32[4];
+  uint64_t u64[2];
+  uint4 u128, as_scalar;
+};
+
+template 
+struct MultimemLdReduce {
+  template 
+  __device__ __inline__ Vec operator()(T* mc_ptr) {
+    static_assert(dependent_false);
+  }
+};
+
+template 
+__device__ __inline__ Vec multimem_ld_reduce_add(T* mc_ptr) {
+  MultimemLdReduce functor;
+  return functor.template operator()(mc_ptr);
+}
+
+#if defined(USE_ROCM) || !defined(NVCC_SUPPORTS_MULTICAST)
+#define SPECIALIZE_MULTIMEM_LD_REDUCE_VEC_32(type, asm_type)        \
+  template <>                                                       \
+  struct MultimemLdReduce {                                   \
+    template                                         \
+    __device__ __inline__ Vec operator()(type* mc_ptr) { \
+      CUDA_KERNEL_ASSERT(false);                                    \
+    }                                                               \
+  };
+#else
+#define SPECIALIZE_MULTIMEM_LD_REDUCE_VEC_32(type, asm_type)                   \
+  template <>                                                                  \
+  struct MultimemLdReduce {                                              \
+    template                                                    \
+    __device__ __inline__ Vec operator()(type* mc_ptr) {            \
+      Vec vec;                                                      \
+      if constexpr (Alignment == 16) {                                         \
+        asm("multimem.ld_reduce.relaxed.sys.global.add.v4." asm_type           \
+            " {%0,%1,%2,%3}, [%4];"                                            \
+            : "=r"(vec.u32[0]),                                                \
+              "=r"(vec.u32[1]),                                                \
+              "=r"(vec.u32[2]),                                                \
+              "=r"(vec.u32[3])                                                 \
+            : "l"(mc_ptr)                                                      \
+            : "memory");                                                       \
+      } else if constexpr (Alignment == 8) {                                   \
+        asm("multimem.ld_reduce.relaxed.sys.global.add.v2." asm_type           \
+            " {%0,%1}, [%2];"                                                  \
+            : "=r"(vec.u32[0]), "=r"(vec.u32[1])                               \
+            : "l"(mc_ptr)                                                      \
+            : "memory");                                                       \
+      } else if constexpr (Alignment == 4) {                                   \
+        asm("multimem.ld_reduce.relaxed.sys.global.add." asm_type " %0, [%1];" \
+            : "=r"(vec.u32)                                                    \
+            : "l"(mc_ptr)                                                      \
+            : "memory");                                                       \
+      }                                                                        \
+      return vec;                                                              \
+    }                                                                          \
+  };
+#endif
+
+SPECIALIZE_MULTIMEM_LD_REDUCE_VEC_32(at::BFloat16, "bf16x2");
+SPECIALIZE_MULTIMEM_LD_REDUCE_VEC_32(float, "f32");
+
+template 
+__device__ __inline__ void multimem_st(T* mc_ptr, Vec& vec) {
+#if defined(USE_ROCM) || !defined(NVCC_SUPPORTS_MULTICAST)
+  CUDA_KERNEL_ASSERT(false);
+#else
+  if constexpr (Alignment == 16) {
+    asm("multimem.st.relaxed.sys.global.v4.f32 [%0], {%1,%2,%3,%4};"
+        :
+        : "l"(mc_ptr),
+          "r"(vec.u32[0]),
+          "r"(vec.u32[1]),
+          "r"(vec.u32[2]),
+          "r"(vec.u32[3])
+        : "memory");
+  } else if constexpr (Alignment == 8) {
+    asm("multimem.st.relaxed.sys.global.v2.f32 [%0], {%1,%2};"
+        :
+        : "l"(mc_ptr), "r"(vec.u32[0]), "r"(vec.u32[1])
+        : "memory");
+  } else if constexpr (Alignment == 4) {
+    asm("multimem.st.relaxed.sys.global.f32 [%0], %1;"
+        :
+        : "l"(mc_ptr), "r"(vec.u32)
+        : "memory");
+  } else {
+    static_assert(dependent_false);
+  }
+#endif
+}
+
+} // namespace c10d::symmetric_memory
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/CUDASymmetricMemory.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/CUDASymmetricMemory.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..2ffd194a76e288145ffb80f1cc5814ab577d955b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/CUDASymmetricMemory.hpp
@@ -0,0 +1,115 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+namespace c10d {
+namespace symmetric_memory {
+
+#if !defined(USE_ROCM) && defined(PYTORCH_C10_DRIVER_API_SUPPORTED)
+using HandleType = CUmemGenericAllocationHandle;
+#else
+using HandleType = void*;
+#endif
+
+class CUDASymmetricMemory : public SymmetricMemory {
+ public:
+  CUDASymmetricMemory(
+      std::vector handles,
+      size_t block_size,
+      std::vector buffers,
+      std::vector signal_pads,
+      HandleType mc_handle,
+      void* mc_addr,
+      size_t buffer_size,
+      int local_device_idx,
+      int rank,
+      int world_size);
+
+  ~CUDASymmetricMemory() override;
+
+  std::vector get_buffer_ptrs() override;
+  std::vector get_signal_pad_ptrs() override;
+  void** get_buffer_ptrs_dev() override;
+  void** get_signal_pad_ptrs_dev() override;
+  size_t get_buffer_size() override;
+  size_t get_signal_pad_size() override;
+
+  bool has_multicast_support() override;
+  void* get_multicast_ptr() override;
+
+  at::Tensor get_buffer(
+      int rank,
+      c10::IntArrayRef sizes,
+      c10::ScalarType dtype,
+      int64_t storage_offset) override;
+
+  void barrier(int channel) override;
+  void put_signal(int dst_rank, int channel) override;
+  void wait_signal(int src_rank, int channel) override;
+
+  int get_rank() override;
+  int get_world_size() override;
+
+ private:
+  std::vector handles_;
+  size_t block_size_;
+  std::vector buffers_;
+  std::vector signal_pads_;
+  HandleType mc_handle_;
+  void* mc_addr_;
+  size_t buffer_size_;
+  int local_device_idx_;
+  int rank_;
+  int world_size_;
+  void** buffers_dev_;
+  void** signal_pads_dev_;
+  std::optional> finalizer_;
+};
+
+struct Block : public c10::intrusive_ptr_target {
+  HandleType handle;
+  int device_idx;
+  size_t block_size;
+  size_t buffer_size;
+  size_t signal_pad_offset;
+  std::string group_name;
+  c10::intrusive_ptr symm_mem = nullptr;
+
+  Block(
+      HandleType handle,
+      int device_idx,
+      size_t block_size,
+      size_t buffer_size,
+      size_t signal_pad_offset,
+      const std::string& group_name)
+      : handle(handle),
+        device_idx(device_idx),
+        block_size(block_size),
+        buffer_size(buffer_size),
+        signal_pad_offset(signal_pad_offset),
+        group_name(group_name),
+        symm_mem(nullptr) {}
+};
+
+class CUDASymmetricMemoryAllocator : public SymmetricMemoryAllocator {
+ public:
+  void* alloc(size_t size, int device_idx, const std::string& group_name)
+      override;
+
+  void free(void* ptr) override;
+  size_t get_alloc_size(void* ptr) override;
+  c10::intrusive_ptr rendezvous(void* ptr) override;
+  bool is_rendezvous_completed(void* ptr) override;
+  bool has_multicast_support(int device_idx) override;
+
+ private:
+  c10::intrusive_ptr find_block(void* ptr);
+
+  std::shared_mutex mutex_;
+  std::unordered_map> ptr_to_block_;
+};
+
+} // namespace symmetric_memory
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/DMAConnectivity.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/DMAConnectivity.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..cede6aa265c7733a5f65f5c1840d9fa093290bf3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/DMAConnectivity.hpp
@@ -0,0 +1,40 @@
+#pragma once
+
+#include 
+
+#include 
+
+namespace c10d {
+
+struct TORCH_API DMAConnectivity : c10::intrusive_ptr_target {
+  c10::DeviceType device_type;
+  std::string connection_type;
+
+  // This is an NxN matrix representing the connectivity between N devices,
+  // where each element matrix[i][j] indicates the connectivity between device
+  // i and device j. A value of 0 denotes that there is no connection between
+  // device i and j. The meaning of non-zero values are specific to the
+  // connection type (e.g., for NVLink it represents the number of NVLinks).
+  std::vector> matrix;
+
+  explicit DMAConnectivity(
+      c10::DeviceType device_type,
+      std::string connection_type,
+      std::vector> matrix);
+};
+
+struct DMAConnectivityDetector : c10::intrusive_ptr_target {
+  virtual c10::intrusive_ptr detect() = 0;
+  virtual ~DMAConnectivityDetector() {}
+};
+
+C10_EXPORT void register_dma_connectivity_detector(
+    c10::DeviceType device_type,
+    const std::string& connection_type,
+    c10::intrusive_ptr detector);
+
+TORCH_API c10::intrusive_ptr detect_dma_connectivity(
+    c10::DeviceType device_type,
+    const std::string& connection_type);
+
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/FakeProcessGroup.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/FakeProcessGroup.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..2736e0e3538d8a95191f45ced1e7c0dd83cd33d5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/FakeProcessGroup.hpp
@@ -0,0 +1,186 @@
+#pragma once
+
+#include 
+
+namespace c10d {
+
+class FakeWork : public Work {
+ public:
+  bool wait(std::chrono::milliseconds timeout) override {
+    return true;
+  }
+
+  c10::intrusive_ptr getFuture() override {
+    auto fut = c10::make_intrusive(c10::NoneType::get());
+    fut->markCompleted();
+    return fut;
+  }
+};
+
+class FakeProcessGroup : public Backend {
+ public:
+  FakeProcessGroup(int rank, int size) : Backend(rank, size) {}
+
+  c10::intrusive_ptr broadcast(
+      std::vector& /* tensors */,
+      const BroadcastOptions& /* opts */ = BroadcastOptions()) override {
+    return c10::make_intrusive();
+  }
+
+  c10::intrusive_ptr allreduce(
+      std::vector& /* tensors */,
+      const AllreduceOptions& /* opts */ = AllreduceOptions()) override {
+    return c10::make_intrusive();
+  }
+
+  c10::intrusive_ptr allreduce_sparse(
+      std::vector& /* tensors */,
+      const AllreduceOptions& /* opts */ = AllreduceOptions()) override {
+    return c10::make_intrusive();
+  }
+
+  c10::intrusive_ptr allreduce_coalesced(
+      std::vector& /* tensors */,
+      const AllreduceCoalescedOptions& /* opts */ =
+          AllreduceCoalescedOptions()) override {
+    return c10::make_intrusive();
+  }
+
+  c10::intrusive_ptr reduce(
+      std::vector& /* tensors */,
+      const ReduceOptions& /* opts */ = ReduceOptions()) override {
+    return c10::make_intrusive();
+  }
+
+  // NOTE [allgather on FakeProcessGroup]
+  // Assume each rank have the same input tensor so we just copy to the results
+  // since it's not a real allgather, we simply make this copying logic to let
+  // some simple validation works (i.e. calling allgather to see if each rank
+  // have the same tensor or not).
+  //
+  // NOTE: in general it's not good form to try to make FakeProcessGroup work
+  // with real data, but the reasoning here is that we want FakeProcessGroup to
+  // work with DeviceMesh's init code that have the data validation, which
+  // makes it worth the tradeoff.
+  c10::intrusive_ptr allgather(
+      std::vector>& outputTensors,
+      std::vector& inputTensors,
+      const AllgatherOptions& /* opts */ = AllgatherOptions()) override {
+    for (auto& tensor : outputTensors[0]) {
+      tensor.copy_(inputTensors[0]);
+    }
+    return c10::make_intrusive();
+  }
+
+  c10::intrusive_ptr _allgather_base(
+      at::Tensor& outputBuffer,
+      at::Tensor& inputBuffer,
+      const AllgatherOptions& /* opts */ = AllgatherOptions()) override {
+    auto chunks = outputBuffer.chunk(size_);
+    for (auto& tensor : chunks) {
+      tensor.copy_(inputBuffer);
+    }
+    return c10::make_intrusive();
+  }
+
+  c10::intrusive_ptr allgather_coalesced(
+      std::vector>& /* outputTensorLists */,
+      std::vector& /* inputTensors */,
+      const AllgatherOptions& /* opts */ = AllgatherOptions()) override {
+    return c10::make_intrusive();
+  }
+
+  c10::intrusive_ptr allgather_into_tensor_coalesced(
+      std::vector& outputs,
+      std::vector& inputs,
+      const AllgatherOptions& /* opts */ = AllgatherOptions()) override {
+    for (size_t i = 0; i < outputs.size(); ++i) {
+      auto chunks = outputs[i].chunk(size_);
+      for (auto& chunk : chunks) {
+        chunk.copy_(inputs[i]);
+      }
+    }
+    return c10::make_intrusive();
+  }
+
+  c10::intrusive_ptr gather(
+      std::vector>& /* outputTensors */,
+      std::vector& /* inputTensors */,
+      const GatherOptions& /* opts */ = GatherOptions()) override {
+    return c10::make_intrusive();
+  }
+
+  c10::intrusive_ptr scatter(
+      std::vector& /* outputTensors */,
+      std::vector>& /* inputTensors */,
+      const ScatterOptions& /* opts */ = ScatterOptions()) override {
+    return c10::make_intrusive();
+  }
+
+  c10::intrusive_ptr reduce_scatter(
+      std::vector& /* outputTensors */,
+      std::vector>& /* inputTensors */,
+      const ReduceScatterOptions& /* opts */ =
+          ReduceScatterOptions()) override {
+    return c10::make_intrusive();
+  }
+
+  c10::intrusive_ptr _reduce_scatter_base(
+      at::Tensor& /* outputBuffer */,
+      at::Tensor& /* inputBuffer */,
+      const ReduceScatterOptions& /* opts */ =
+          ReduceScatterOptions()) override {
+    return c10::make_intrusive();
+  }
+
+  c10::intrusive_ptr reduce_scatter_tensor_coalesced(
+      std::vector& /* outputs */,
+      std::vector& /* inputs */,
+      const ReduceScatterOptions& /* opts */ =
+          ReduceScatterOptions()) override {
+    return c10::make_intrusive();
+  }
+
+  c10::intrusive_ptr alltoall_base(
+      at::Tensor& /* outputBuffer */,
+      at::Tensor& /* inputBuffer */,
+      std::vector& /* outputSplitSizes */,
+      std::vector& /* inputSplitSizes */,
+      const AllToAllOptions& /* opts */ = AllToAllOptions()) override {
+    return c10::make_intrusive();
+  }
+
+  c10::intrusive_ptr alltoall(
+      std::vector& /* outputTensors */,
+      std::vector& /* inputTensors */,
+      const AllToAllOptions& opts = AllToAllOptions()) override {
+    return c10::make_intrusive();
+  }
+
+  c10::intrusive_ptr send(
+      std::vector& /* tensors */,
+      int /* dstRank */,
+      int /* tag */) override {
+    return c10::make_intrusive();
+  }
+
+  c10::intrusive_ptr recv(
+      std::vector& /* tensors */,
+      int /* srcRank */,
+      int /* tag */) override {
+    return c10::make_intrusive();
+  }
+
+  c10::intrusive_ptr recvAnysource(
+      std::vector& /* tensors */,
+      int /* tag */) override {
+    return c10::make_intrusive();
+  }
+
+  c10::intrusive_ptr barrier(
+      const BarrierOptions& /* opts */ = BarrierOptions()) override {
+    return c10::make_intrusive();
+  }
+};
+
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/FileStore.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/FileStore.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..0bb0756e061678945521349daba47da9d0a6b696
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/FileStore.hpp
@@ -0,0 +1,63 @@
+#pragma once
+
+#include 
+
+#include 
+#include 
+
+#include 
+
+namespace c10d {
+
+class TORCH_API FileStore : public Store {
+ public:
+  explicit FileStore(std::string path, int numWorkers);
+
+  ~FileStore() override;
+
+  void set(const std::string& key, const std::vector& value) override;
+
+  std::vector compareSet(
+      const std::string& key,
+      const std::vector& expectedValue,
+      const std::vector& desiredValue) override;
+
+  std::vector get(const std::string& key) override;
+
+  int64_t add(const std::string& key, int64_t value) override;
+
+  int64_t getNumKeys() override;
+
+  bool deleteKey(const std::string& key) override;
+
+  bool check(const std::vector& keys) override;
+
+  void wait(const std::vector& keys) override;
+
+  void wait(
+      const std::vector& keys,
+      const std::chrono::milliseconds& timeout) override;
+
+  // Returns the path used by the FileStore.
+  const std::string& getPath() const noexcept {
+    return path_;
+  }
+
+ protected:
+  int64_t addHelper(const std::string& key, int64_t i);
+
+  std::string path_;
+  off_t pos_{0};
+
+  int numWorkers_;
+  const std::string cleanupKey_;
+  const std::string refCountKey_;
+  const std::string regularPrefix_;
+  const std::string deletePrefix_;
+
+  std::unordered_map> cache_;
+
+  std::mutex activeFileOpLock_;
+};
+
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/Functional.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/Functional.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..cbb19e686095a75e747795d2216c2ff3eece380c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/Functional.hpp
@@ -0,0 +1,11 @@
+#pragma once
+
+#include 
+
+namespace c10d {
+
+C10_EXPORT void register_work(
+    const at::Tensor& tensor,
+    const c10::intrusive_ptr& work);
+
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/GlooDeviceFactory.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/GlooDeviceFactory.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..1221e9d033f2ffde494883fc08122e8fb6a55902
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/GlooDeviceFactory.hpp
@@ -0,0 +1,32 @@
+#pragma once
+
+#ifdef USE_C10D_GLOO
+
+#include 
+
+#include 
+#include 
+#include 
+
+namespace c10d {
+
+class TORCH_API GlooDeviceFactory {
+ public:
+  // Create new device instance for specific interface.
+  static std::shared_ptr<::gloo::transport::Device> makeDeviceForInterface(
+      const std::string& interface);
+
+  // Create new device instance for specific hostname or address.
+  static std::shared_ptr<::gloo::transport::Device> makeDeviceForHostname(
+      const std::string& hostname);
+};
+
+TORCH_DECLARE_SHARED_REGISTRY(
+    GlooDeviceRegistry,
+    ::gloo::transport::Device,
+    const std::string&, /* interface */
+    const std::string& /* hostname */);
+
+} // namespace c10d
+
+#endif // USE_C10D_GLOO
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/GroupRegistry.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/GroupRegistry.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..b22fb1ae8faf3f65a1032c8d6fd2f81931d72cf2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/GroupRegistry.hpp
@@ -0,0 +1,22 @@
+#pragma once
+
+#include 
+
+namespace c10d {
+
+C10_EXPORT void set_thread_isolation_mode(bool enable);
+
+bool get_thread_isolation_mode();
+
+C10_EXPORT void register_process_group(
+    const std::string& group_name,
+    c10::intrusive_ptr group);
+
+C10_EXPORT c10::intrusive_ptr resolve_process_group(
+    const std::string& group_name);
+
+C10_EXPORT void unregister_process_group(const std::string& group_name);
+
+C10_EXPORT void unregister_all_process_groups();
+
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/HashStore.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/HashStore.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..3697d62301ba36655fff862fe462b6814208526a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/HashStore.hpp
@@ -0,0 +1,59 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+
+namespace c10d {
+
+class TORCH_API HashStore : public Store {
+ public:
+  ~HashStore() override = default;
+
+  void set(const std::string& key, const std::vector& data) override;
+
+  std::vector compareSet(
+      const std::string& key,
+      const std::vector& expectedValue,
+      const std::vector& desiredValue) override;
+
+  std::vector get(const std::string& key) override;
+
+  void wait(const std::vector& keys) override {
+    wait(keys, timeout_);
+  }
+
+  void wait(
+      const std::vector& keys,
+      const std::chrono::milliseconds& timeout) override;
+
+  int64_t add(const std::string& key, int64_t value) override;
+
+  int64_t getNumKeys() override;
+
+  bool check(const std::vector& keys) override;
+
+  bool deleteKey(const std::string& key) override;
+
+  void append(const std::string& key, const std::vector& value)
+      override;
+
+  std::vector> multiGet(
+      const std::vector& keys) override;
+
+  void multiSet(
+      const std::vector& keys,
+      const std::vector>& values) override;
+
+  // Returns true if this store support append, multiGet and multiSet
+  bool hasExtendedApi() const override;
+
+ protected:
+  std::unordered_map> map_;
+  std::mutex m_;
+  std::condition_variable cv_;
+};
+
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/NCCLUtils.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/NCCLUtils.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..070cbd34b3797016fa7f45976fc2a51c739736cc
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/NCCLUtils.hpp
@@ -0,0 +1,718 @@
+#pragma once
+
+#ifdef USE_C10D_NCCL
+
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#if defined(NCCL_MAJOR) && (NCCL_MAJOR == 2) && defined(NCCL_MINOR) && \
+    (NCCL_MINOR >= 14)
+#define NCCL_HAS_COMM_NONBLOCKING
+#endif
+
+#if defined(NCCL_MAJOR) && (NCCL_MAJOR == 2) && defined(NCCL_MINOR) && \
+    (NCCL_MINOR >= 18)
+#define NCCL_HAS_COMM_SPLIT
+#endif
+
+// ncclGetLastError() is enabled only for NCCL versions 2.13+
+// ncclRemoteError only exists in NCCL versions 2.13+
+#if defined(NCCL_MAJOR) && (NCCL_MAJOR == 2) && defined(NCCL_MINOR) && \
+    (NCCL_MINOR >= 13)
+#define ENABLE_NCCL_GET_LAST_ERROR
+#define NCCL_REMOTE_ERROR
+#elif defined(NCCL_MAJOR) && (NCCL_MAJOR >= 3)
+#define ENABLE_NCCL_GET_LAST_ERROR
+#define NCCL_REMOTE_ERROR
+#endif
+
+// Error checking is enabled only for NCCL versions 2.4+ since ncclCommAbort()
+// and ncclCommGetAsyncError() are not supported in earlier versions.
+#if defined(NCCL_MAJOR) && (NCCL_MAJOR == 2) && defined(NCCL_MINOR) && \
+    (NCCL_MINOR >= 4)
+#define ENABLE_NCCL_ERROR_CHECKING
+#elif defined(NCCL_MAJOR) && (NCCL_MAJOR >= 3)
+#define ENABLE_NCCL_ERROR_CHECKING
+#endif
+
+// P2P is enabled only for NCCL versions 2.7+ since ncclSend()
+// and ncclRecv() are not supported in earlier versions.
+#if defined(NCCL_MAJOR) && (NCCL_MAJOR == 2) && defined(NCCL_MINOR) && \
+    (NCCL_MINOR >= 7)
+#define ENABLE_NCCL_P2P_SUPPORT
+#elif defined(NCCL_MAJOR) && (NCCL_MAJOR >= 3)
+#define ENABLE_NCCL_P2P_SUPPORT
+#endif
+
+#if defined(NCCL_MAJOR) && (NCCL_MAJOR == 2) && defined(NCCL_MINOR) && \
+    (NCCL_MINOR >= 11)
+#define ENABLE_NCCL_PREMUL_SUM_SUPPORT
+#elif defined(NCCL_MAJOR) && (NCCL_MAJOR >= 3)
+#define ENABLE_NCCL_PREMUL_SUM_SUPPORT
+#endif
+
+#if defined(NCCL_MAJOR) && (NCCL_MAJOR == 2) && defined(NCCL_MINOR) && \
+    (NCCL_MINOR >= 17)
+#define NCCL_HAS_COMM_CTA_CGA
+#elif defined(NCCL_MAJOR) && (NCCL_MAJOR >= 3)
+#define NCCL_HAS_COMM_CTA_CGA
+#endif
+
+#if defined(NCCL_REGISTRATION_SUPPORTED) ||                              \
+    ((defined(NCCL_MAJOR) && (NCCL_MAJOR == 2) && defined(NCCL_MINOR) && \
+      (NCCL_MINOR >= 19)))
+#define NCCL_HAS_COMM_REGISTER
+#elif defined(NCCL_MAJOR) && (NCCL_MAJOR >= 3)
+#define NCCL_HAS_COMM_REGISTER
+#endif
+
+// Macro to throw on a non-successful NCCL return value.
+#define C10D_NCCL_CHECK(cmd, failureReason)                                   \
+  do {                                                                        \
+    ncclResult_t result = cmd;                                                \
+    if (result != ncclSuccess) {                                              \
+      std::string err = "NCCL error in: " + std::string(__FILE__) + ":" +     \
+          std::to_string(__LINE__) + ", " + ncclGetErrorWithVersion(result) + \
+          "\n" + getNcclErrorDetailStr(result, failureReason);                \
+      TORCH_CHECK_WITH(DistBackendError, false, err);                         \
+    }                                                                         \
+  } while (0)
+
+// Macro to throw on a non-successful NCCL return value for NONBLOCKING calls.
+#define C10D_NCCL_CHECK_NONBLOCKING(cmd, failureReason)                       \
+  do {                                                                        \
+    ncclResult_t result = cmd;                                                \
+    if (result != ncclSuccess && result != ncclInProgress) {                  \
+      std::string err = "NCCL error in: " + std::string(__FILE__) + ":" +     \
+          std::to_string(__LINE__) + ", " + ncclGetErrorWithVersion(result) + \
+          "\n" + getNcclErrorDetailStr(result, failureReason);                \
+      TORCH_CHECK_WITH(DistBackendError, false, err);                         \
+    }                                                                         \
+  } while (0)
+
+// Macro to throw on a non-successful NCCL return value, non-blocking.
+#define C10D_NCCL_CHECK_TIMEOUT(cmd, comm, failureReason)                     \
+  ncclResult_t result = cmd;                                                  \
+  auto startTimepoint = std::chrono::steady_clock::now();                     \
+  while (result == ncclInProgress) {                                          \
+    if (nccl_nonblocking_timeout() > 0) {                                     \
+      auto currentTimepoint = std::chrono::steady_clock::now();               \
+      auto timeElapsed = std::chrono::duration_cast(    \
+                             currentTimepoint - startTimepoint)               \
+                             .count();                                        \
+      if (timeElapsed > nccl_nonblocking_timeout()) {                         \
+        std::string err = "NCCL timeout in: " + std::string(__FILE__) + ":" + \
+            std::to_string(__LINE__) + ", " +                                 \
+            ncclGetErrorWithVersion(result) + "\n" +                          \
+            getNcclErrorDetailStr(result, failureReason);                     \
+        TORCH_CHECK_WITH(DistBackendError, false, err);                       \
+      }                                                                       \
+    }                                                                         \
+    ncclCommGetAsyncError(comm, &result);                                     \
+  }                                                                           \
+  if (result != ncclSuccess) {                                                \
+    std::string err = "NCCL error in: " + std::string(__FILE__) + ":" +       \
+        std::to_string(__LINE__) + ", " + ncclGetErrorWithVersion(result) +   \
+        "\n" + getNcclErrorDetailStr(result, failureReason);                  \
+    TORCH_CHECK_WITH(DistBackendError, false, err);                           \
+  }
+
+#define C10D_NCCL_CHECK_TIMEOUT_GROUPEND(cmd, comm, failureReason)           \
+  ncclResult_t state = cmd;                                                  \
+  auto startTimepoint = std::chrono::steady_clock::now();                    \
+  if (state == ncclInProgress) {                                             \
+    do {                                                                     \
+      if (nccl_nonblocking_timeout() > 0) {                                  \
+        auto currentTimepoint = std::chrono::steady_clock::now();            \
+        auto timeElapsed = std::chrono::duration_cast( \
+                               currentTimepoint - startTimepoint)            \
+                               .count();                                     \
+        if (timeElapsed > nccl_nonblocking_timeout()) {                      \
+          std::string err = "NCCL timeout in: " + std::string(__FILE__) +    \
+              ":" + std::to_string(__LINE__) + ", " +                        \
+              ncclGetErrorWithVersion(state) + "\n" +                        \
+              getNcclErrorDetailStr(state, failureReason);                   \
+          TORCH_CHECK_WITH(DistBackendError, false, err);                    \
+        }                                                                    \
+      }                                                                      \
+      ncclCommGetAsyncError(comm->getNcclComm(), &state);                    \
+    } while (state == ncclInProgress);                                       \
+  }                                                                          \
+  if (state != ncclSuccess) {                                                \
+    std::string err = "NCCL error in: " + std::string(__FILE__) + ":" +      \
+        std::to_string(__LINE__) + ", " + ncclGetErrorWithVersion(state) +   \
+        "\n" + getNcclErrorDetailStr(state, failureReason);                  \
+    TORCH_CHECK_WITH(DistBackendError, false, err);                          \
+  }
+
+// Macro to print and abort on a non-successful NCCL return value.
+#define C10D_NCCL_ASSERT(cmd)                            \
+  do {                                                   \
+    ncclResult_t result = cmd;                           \
+    if (result != ncclSuccess) {                         \
+      std::string err = ncclGetErrorWithVersion(result); \
+      fprintf(                                           \
+          stderr,                                        \
+          "NCCL error in: %s:%d, %s\n",                  \
+          __FILE__,                                      \
+          __LINE__,                                      \
+          err.c_str());                                  \
+      abort();                                           \
+    }                                                    \
+  } while (0)
+
+namespace c10d {
+#define DEFINE_CONSTANT(name, value) \
+  static c10::IValue name = value;   \
+  static std::string name##_str = value;
+// Update whenever changing contents or formatting of the dump
+// (minor when adding fields, major when changing existing fields)
+// Also update both JSON and Pickle dumps to make use of the newly defined
+// field(s).
+DEFINE_CONSTANT(version_val, "2.4");
+DEFINE_CONSTANT(entries_key, "entries");
+DEFINE_CONSTANT(nccl_comm_key, "nccl_comm_state");
+DEFINE_CONSTANT(version_key, "version");
+DEFINE_CONSTANT(pg_config_key, "pg_config");
+DEFINE_CONSTANT(pg_status_key, "pg_status");
+DEFINE_CONSTANT(record_id_key, "record_id");
+DEFINE_CONSTANT(pg_id_key, "pg_id");
+DEFINE_CONSTANT(pg_name_key, "process_group");
+DEFINE_CONSTANT(collective_seq_id_key, "collective_seq_id");
+DEFINE_CONSTANT(p2p_seq_id_key, "p2p_seq_id");
+DEFINE_CONSTANT(is_p2p_key, "is_p2p");
+DEFINE_CONSTANT(op_id_key, "op_id");
+DEFINE_CONSTANT(profiling_name_key, "profiling_name");
+DEFINE_CONSTANT(input_sizes_key, "input_sizes");
+DEFINE_CONSTANT(input_dtypes_key, "input_dtypes");
+DEFINE_CONSTANT(output_sizes_key, "output_sizes");
+DEFINE_CONSTANT(output_dtypes_key, "output_dtypes");
+DEFINE_CONSTANT(time_created_key, "time_created_ns");
+DEFINE_CONSTANT(duration_key, "duration_ms");
+DEFINE_CONSTANT(timeout_key, "timeout_ms");
+DEFINE_CONSTANT(frames_key, "frames");
+DEFINE_CONSTANT(state_key, "state");
+DEFINE_CONSTANT(line_key, "line");
+DEFINE_CONSTANT(name_key, "name");
+DEFINE_CONSTANT(filename_key, "filename");
+DEFINE_CONSTANT(retired_key, "retired");
+DEFINE_CONSTANT(time_discovered_started_key, "time_discovered_started_ns");
+DEFINE_CONSTANT(time_discovered_completed_key, "time_discovered_completed_ns");
+DEFINE_CONSTANT(completed_state, "completed");
+DEFINE_CONSTANT(scheduled_state, "scheduled");
+DEFINE_CONSTANT(started_state, "started");
+#undef DEFINE_CONSTANT
+
+TORCH_API size_t hashTensors(const std::vector& tensors);
+TORCH_API std::string getNcclVersion();
+TORCH_API std::string ncclGetErrorWithVersion(ncclResult_t error);
+bool nccl_use_nonblocking();
+int nccl_nonblocking_timeout();
+
+// Provides additional detail into NCCL error codes based on when these are
+// thrown in the NCCL codebase.
+TORCH_API std::string getNcclErrorDetailStr(
+    ncclResult_t error,
+    std::optional processGroupFailureReason = std::nullopt);
+
+// Write NCCL debug info to local disk or any storage users define.
+// There are some constrains we set for the debug info writer:
+// 1. The writer should only be registered once.
+// 2. Once registered, users cannot change it including un-register.
+// 3. It is recommended to register the customized writer in the trainer setup,
+//    If users don't register before calling launchAsyncDebugDump, then users
+//    lose the chance to register (and the default writer will be
+//    auto-registered).
+class TORCH_API DebugInfoWriter {
+ public:
+  virtual ~DebugInfoWriter() = default;
+  virtual void write(const std::string& ncclTrace);
+  static DebugInfoWriter& getWriter(int rank);
+  static void registerWriter(std::unique_ptr writer);
+  virtual std::string getWriterTarget() {
+    return filename_;
+  }
+
+ protected:
+  DebugInfoWriter(std::string namePrefix, int rank) {
+    filename_ = c10::str(namePrefix, rank);
+  }
+  std::string filename_;
+
+ private:
+  static std::unique_ptr writer_;
+  static std::atomic hasWriterRegistered_;
+};
+
+// RAII wrapper for NCCL communicator
+class NCCLComm {
+ public:
+  explicit NCCLComm(ncclComm_t ncclComm)
+      : ncclComm_(ncclComm),
+        aborted_(false),
+        ncclAsyncErr_(ncclSuccess),
+        commFailureReason_(std::nullopt),
+        initialized_(false) {}
+
+  NCCLComm() : NCCLComm(nullptr) {}
+
+  ~NCCLComm() noexcept {
+    // Add lock in this destructor, as aborted_ needs to be read after memory
+    // barrier here.
+    std::unique_lock lock(mutex_);
+    if (ncclComm_ && initialized_ && !aborted_) {
+#ifdef ENABLE_NCCL_ERROR_CHECKING
+      // Use ncclCommAbort instead of ncclCommDestroy here since
+      // ncclCommDestroy could block forever waiting for work to complete on
+      // the communicator.
+      C10D_NCCL_ASSERT(::ncclCommAbort(ncclComm_));
+#else
+      C10D_NCCL_ASSERT(::ncclCommDestroy(ncclComm_));
+#endif
+    }
+  }
+
+  static std::shared_ptr create(
+      int numRanks,
+      int rank,
+      ncclUniqueId commId) {
+    auto comm = std::make_shared();
+    C10D_NCCL_CHECK(
+        ncclCommInitRank(&(comm->ncclComm_), numRanks, commId, rank),
+        std::nullopt);
+    comm->ncclId_ = commId;
+    comm->rank_ = rank;
+    comm->initialized_ = true;
+    return comm;
+  }
+
+#ifdef NCCL_HAS_COMM_NONBLOCKING
+  static std::shared_ptr create(
+      int numRanks,
+      int rank,
+      ncclUniqueId commId,
+      ncclConfig_t& config) {
+    auto comm = std::make_shared();
+    bool isInitialized = false;
+    if (nccl_use_nonblocking()) {
+      config.blocking = 0;
+      LOG(INFO) << "Rank " << rank
+                << ": creating NCCL communicator in nonblocking mode";
+      C10D_NCCL_CHECK_NONBLOCKING(
+          ncclCommInitRankConfig(
+              &(comm->ncclComm_), numRanks, commId, rank, &config),
+          std::nullopt);
+    } else {
+      C10D_NCCL_CHECK(
+          ncclCommInitRankConfig(
+              &(comm->ncclComm_), numRanks, commId, rank, &config),
+          std::nullopt);
+      // under blocking mode, comm is initialized after NCCL CHECK
+      isInitialized = true;
+    }
+    comm->ncclId_ = commId;
+    comm->rank_ = rank;
+    comm->initialized_ = isInitialized;
+    return comm;
+  }
+
+  static std::shared_ptr split(
+      NCCLComm* source,
+      int color_id,
+      int rank,
+      ncclConfig_t& config,
+      std::vector& ranks_ull);
+#endif
+
+#if defined(IS_NCCLX) && defined(NCCL_COMM_DUMP)
+  std::unordered_map ncclCommDump() {
+    std::unordered_map dump;
+    if (isAborted()) {
+      LOG(INFO) << "Communicator was aborted before trying to dump its state.";
+      return dump;
+    }
+    C10D_NCCL_CHECK(::ncclCommDump(ncclComm_, dump), std::nullopt);
+    return dump;
+  }
+#endif
+
+  ncclUniqueId getNcclId() {
+    return ncclId_;
+  }
+
+  // Must not be copyable
+  NCCLComm(const NCCLComm&) = delete;
+  NCCLComm& operator=(const NCCLComm&) = delete;
+
+  // Do not support move assignment as there is no valid use case
+  NCCLComm& operator=(NCCLComm&& other) = delete;
+
+  // Move constructable
+  NCCLComm(NCCLComm&& other) {
+    // Using other's lock, as it reads other's states
+    // Can not use this.mutex_, as this object is being constructed.
+    std::unique_lock lock(other.mutex_);
+    std::swap(ncclComm_, other.ncclComm_);
+    std::swap(aborted_, other.aborted_);
+    std::swap(ncclAsyncErr_, other.ncclAsyncErr_);
+    std::swap(initialized_, other.initialized_);
+  }
+
+  ncclComm_t getNcclComm();
+
+  std::optional getNcclCommFailureReason() const {
+    std::unique_lock lock(mutex_);
+    return commFailureReason_;
+  }
+
+  void ncclCommAbort(
+      std::optional commFailureReason = std::nullopt) {
+    std::unique_lock lock(mutex_);
+#ifdef ENABLE_NCCL_ERROR_CHECKING
+    if (aborted_ && !initialized_) {
+      // Should not abort twice.
+      return;
+    }
+
+#ifdef NCCL_HAS_COMM_REGISTER
+    // Deregister all registered segments before aborting.
+    for (auto& it : registeredSegmentHandles_) {
+      void* handle = it.second;
+      C10D_NCCL_CHECK(
+          ::ncclCommDeregister(ncclComm_, handle),
+          c10::str(
+              "Failed to deregister segment handle ",
+              handle,
+              " on ncclComm_ ",
+              ncclComm_));
+    }
+    registeredSegmentHandles_.clear();
+#endif
+
+    // Set true failure reason if provided by ProcessGroupNCCL (e.g. work
+    // timeout)
+    commFailureReason_ = commFailureReason;
+    LOG(INFO) << "Aborting ncclComm_ " << ncclComm_ << " with reason: "
+              << (commFailureReason ? *commFailureReason
+                                    : "No abort reason provided.");
+#ifndef NCCL_HAS_COMM_NONBLOCKING
+    C10D_NCCL_CHECK(::ncclCommAbort(ncclComm_), commFailureReason_);
+#else
+    C10D_NCCL_CHECK_TIMEOUT(
+        ::ncclCommAbort(ncclComm_), ncclComm_, commFailureReason_);
+#endif
+    aborted_ = true;
+    ncclComm_ = nullptr;
+
+    // Set an appropriate error so that we avoid using the communicator.
+    if (ncclAsyncErr_ == ncclSuccess) {
+      ncclAsyncErr_ = ncclSystemError;
+    }
+#else
+    // This is a NOOP, if error checks are disabled.
+    return;
+#endif
+  }
+
+  bool isAborted() const {
+    std::unique_lock lock(mutex_);
+    return aborted_;
+  }
+
+  uint64_t getCommSplitCounter() const {
+    return ncclCommSplitCounter_;
+  }
+
+  ncclResult_t checkForNcclError() {
+    std::unique_lock lock(mutex_);
+#ifdef ENABLE_NCCL_ERROR_CHECKING
+    if (ncclAsyncErr_ != ncclSuccess) {
+      return ncclAsyncErr_;
+    }
+    C10D_NCCL_CHECK(
+        ncclCommGetAsyncError(ncclComm_, &ncclAsyncErr_), commFailureReason_);
+    return ncclAsyncErr_;
+#else
+    // Always return success, if error checks are disabled.
+    return ncclSuccess;
+#endif
+  }
+
+  ncclResult_t registerSegment(void* ptr, size_t size) {
+    std::unique_lock lock(mutex_);
+#ifdef NCCL_HAS_COMM_REGISTER
+    // We register only segments from cache allocator
+    // which are guaranteed to be with disjoint addr ranges. Thus, a ptr always
+    // maps to a unique handle and should not be registered before the current
+    // ptr is deregistered and freed.
+    TORCH_CHECK(
+        registeredSegmentHandles_.count(ptr) == 0,
+        "Segment with ptr ",
+        ptr,
+        " has already been registered on ncclComm_ ",
+        ncclComm_);
+
+    void* handle;
+    C10D_NCCL_CHECK(
+        ncclCommRegister(ncclComm_, ptr, size, &handle),
+        c10::str(
+            "Failed to register segment with ptr ",
+            ptr,
+            ", size ",
+            size,
+            " on ncclComm_ ",
+            ncclComm_));
+    registeredSegmentHandles_[ptr] = handle;
+    return ncclSuccess;
+#else
+    return ncclInvalidUsage;
+#endif
+  }
+
+  ncclResult_t deregisterSegment(void* ptr) {
+    std::unique_lock lock(mutex_);
+#ifdef NCCL_HAS_COMM_REGISTER
+    TORCH_CHECK(
+        registeredSegmentHandles_.count(ptr) == 1,
+        "Segment with ptr ",
+        ptr,
+        " is not registered on ncclComm_ ",
+        ncclComm_);
+
+    void* handle = registeredSegmentHandles_[ptr];
+    C10D_NCCL_CHECK(
+        ncclCommDeregister(ncclComm_, handle),
+        c10::str(
+            "Failed to deregister segment handle ",
+            handle,
+            ", with ptr ",
+            ptr,
+            " on ncclComm_ ",
+            ncclComm_));
+    registeredSegmentHandles_.erase(ptr);
+    return ncclSuccess;
+#else
+    return ncclInvalidUsage;
+#endif
+  }
+
+  friend class ProcessGroupNCCL;
+
+ protected:
+  // a helper function to wait until the communicator is initialized;
+  void waitUntilInitialized(int timeoutSecs);
+  ncclComm_t ncclComm_;
+  // Unique nccl_id for this communicator.
+  ncclUniqueId ncclId_;
+  bool aborted_;
+  uint64_t ncclCommSplitCounter_{0};
+  ncclResult_t ncclAsyncErr_;
+  mutable std::mutex mutex_;
+  // Rank that this communicator corresponds to.
+  int rank_;
+  // Optional reason for communicator failure, provided by ProcessGroupNCCL for
+  // better error messaging.
+  std::optional commFailureReason_;
+  bool initialized_{false};
+#ifdef NCCL_HAS_COMM_REGISTER
+  // Stores handlers for tensors registered by NCCL
+  std::unordered_map registeredSegmentHandles_;
+#endif
+};
+
+// Helper that automatically cleans up premul sums.
+struct ncclRedOpRAII {
+  ncclRedOpRAII() = default;
+  ncclRedOpRAII(ncclRedOp_t op) : op_(op) {}
+  ncclRedOpRAII(ncclRedOp_t op, ncclComm_t comm)
+      : op_(op), comm_(comm), premul_sum_(true) {}
+  ncclRedOpRAII(const ncclRedOpRAII&) = delete;
+  ncclRedOpRAII& operator=(const ncclRedOpRAII&) = delete;
+  ncclRedOpRAII(ncclRedOpRAII&& tmp) : ncclRedOpRAII() {
+    std::swap(tmp.op_, this->op_);
+    std::swap(tmp.comm_, this->comm_);
+    std::swap(tmp.premul_sum_, this->premul_sum_);
+  }
+#if defined(ENABLE_NCCL_PREMUL_SUM_SUPPORT)
+  ~ncclRedOpRAII() {
+    if (premul_sum_) {
+      ncclRedOpDestroy(op_, comm_);
+    }
+  }
+#endif
+  operator ncclRedOp_t() const {
+    return op_;
+  }
+  ncclRedOp_t op_;
+  ncclComm_t comm_;
+  bool premul_sum_ = false;
+};
+
+/* Helper used by work::getDuration() and nccl flight recorder */
+float getDurationFromEvent(
+    at::cuda::CUDAEvent& ncclStartEvent,
+    at::cuda::CUDAEvent& ncclEndEvent);
+
+struct NCCLTraceBuffer {
+  static NCCLTraceBuffer* get() {
+    // intentionally leak on exit
+    // because this will hold python state that may get destructed
+    static NCCLTraceBuffer* instance = new NCCLTraceBuffer();
+    return instance;
+  }
+  NCCLTraceBuffer() {
+    max_entries_ = getCvarInt({"TORCH_NCCL_TRACE_BUFFER_SIZE"}, 0);
+    capture_cpp_stack_ = getCvarBool({"TORCH_NCCL_TRACE_CPP_STACK"}, false);
+    enabled_ = max_entries_ > 0;
+  }
+  using Event = at::cuda::CUDAEvent;
+  struct Entry {
+    size_t id_; // incremented id in the trace buffer
+                // used to figure out where in the circular entries
+                // buffer this entry will be located to
+                // update state information
+    size_t pg_id_;
+    std::tuple pg_name_; // 
+
+    // collective_seq_id and p2p_seq_id refer to actual kernel launches (e.g. 1
+    // per coalesced group).
+    // collective_seq_id only increments for true collective operations (over
+    // all ranks in the group). p2p_seq_id only increments over non-collective
+    // operations in the group. op_id refers to logical operations (e.g. one per
+    // op inside coalesced group)
+    size_t collective_seq_id_;
+    size_t p2p_seq_id_;
+    size_t op_id_;
+    std::string profiling_name_;
+
+    std::shared_ptr traceback_;
+    // we borrow pointers to start_ and end_ so we can query the state
+    // on reporting. However, once the event is completed, the call
+    // to `complete` will clear these.
+    Event *start_, *end_;
+
+    // timestamp when the entry was created, likely close to the time the work
+    // was 'enqueued'- not necessarily started
+    c10::time_t time_created_;
+
+    // configured timeout for this entry
+    c10::time_t timeout_ms_;
+
+    // Is this a P2P event?
+    bool isP2P_;
+
+    std::optional duration_;
+
+    // timestamp when our CPU threads discovered that the kernel started.
+    // will always be _after_ it actually started, and can be very late
+    // if the watchdog thread got stuck on CUDA APIs.
+    std::optional time_discovered_started_;
+
+    // timestamp when our CPU threads discovered that the kernel completed.
+    // will always be _after_ it actually complated, and can be the same time
+    // as the discovery of the start if the watchdog thread is stuck on CUDA
+    // APIs
+    std::optional time_discovered_completed_;
+
+    // size information for input/output tensors
+    c10::SmallVector input_dims_;
+    std::vector input_dtypes_;
+    c10::SmallVector output_dims_;
+    std::vector output_dtypes_;
+    c10::SmallVector sizes_; // flattened from inputs, outputs
+    bool retired_ = false; // is this work entry no longer in the workMetaList_?
+                           // a retired but not completed event has timed out
+  };
+
+  bool enabled_ = false;
+  bool capture_cpp_stack_ = false;
+  std::mutex mutex_;
+  std::vector entries_;
+  size_t max_entries_ = 0;
+  size_t next_ = 0;
+  size_t id_ = 0;
+  std::map> all_pg_status_ = {};
+  std::map, std::vector>
+      pg_name_to_ranks_ = {};
+
+  std::optional record(
+      size_t pg_id,
+      const std::tuple& pg_name,
+      size_t collective_seq_id,
+      size_t p2p_seq_id,
+      size_t op_id,
+      std::string profiling_name,
+      const std::vector& inputs,
+      const std::vector& outputs,
+      Event* start,
+      Event* end,
+      std::chrono::milliseconds timeout_ms,
+      std::shared_ptr pg_status,
+      bool isP2P);
+
+  void record_pg_ranks(
+      const std::tuple& pg_name,
+      std::vector ranks);
+
+  void update_state(Entry& r);
+
+  std::vector dump_entries();
+
+  /*
+  Mark an Event as completed and free its events.
+  This is called by the watchdog thread, and is asynchronous from the
+  perspective of the main thread.
+  compute_duration defaults to true since retire_id is only called in the
+  watchdog thread, which is currently a place we call cuda APIs which may hang,
+  but care should be taken to avoid computing duration in any function that must
+  never hang. (timing must also be enabled for compute_duration - see
+  TORCH_NCCL_ENABLE_TIMING).
+  */
+  void retire_id(std::optional id, bool compute_duration = true);
+
+  const c10::List getCollectiveTrace(
+      bool includeStacktraces,
+      bool onlyActive);
+
+  // dump pg_entries
+  const c10::Dict getPgConfig();
+
+  const std::map>
+  getPgConfigJson();
+
+  // dump pg_status
+  const c10::Dict getPgStatus();
+
+  const std::map>
+  getPgStatusJson();
+
+  std::string dump_json(
+      const std::optional>>& ncclDumpMap,
+      bool includeCollectives,
+      bool onlyActive);
+
+  // dump all collectives + ncclDumpMap
+  std::string dump(
+      const std::optional>>& ncclDumpMap,
+      bool includeCollectives,
+      bool includeStackTraces,
+      bool onlyActive);
+};
+} // namespace c10d
+
+#endif // USE_C10D_NCCL
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/NanCheck.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/NanCheck.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..cc9a5867c3dd400597370adada91022d7dde2201
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/NanCheck.hpp
@@ -0,0 +1,16 @@
+#pragma once
+
+#ifdef USE_C10D_NCCL
+
+#include 
+#include 
+
+namespace c10d {
+
+// Check for NaNs in a tensor on a given stream. If any are found, throw a
+// device-side error.
+void checkForNan(const at::Tensor& tensor, at::cuda::CUDAStream& stream);
+
+} // namespace c10d
+
+#endif // USE_C10D_NCCL
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/ParamCommsUtils.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/ParamCommsUtils.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..027b13c73ae9cbd7abe83069c7c51bd754651619
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/ParamCommsUtils.hpp
@@ -0,0 +1,180 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+
+class TORCH_API ParamCommsDebugInfo : public c10::DebugInfoBase {
+ public:
+  ParamCommsDebugInfo() = default;
+  ParamCommsDebugInfo(
+      std::tuple pgName,
+      int rank,
+      std::string&& collName,
+      int64_t inNelems,
+      int64_t outNelems,
+      at::ScalarType dType,
+      std::vector inSplitSizes,
+      std::vector outSplitSizes,
+      int globalRankStart,
+      int globalRankStride,
+      int worldSize);
+
+  ~ParamCommsDebugInfo() override = default;
+
+  const std::string getProcessGroupName() const {
+    return std::get<0>(pgName_);
+  }
+
+  const std::string getProcessGroupDesc() const {
+    return std::get<1>(pgName_);
+  }
+
+  int getRank() const {
+    return rank_;
+  }
+
+  int getWorldSize() const {
+    return worldSize_;
+  }
+
+  int getGlobalRankStart() const {
+    return globalRankStart_;
+  }
+
+  int getGlobalRankStride() const {
+    return globalRankStride_;
+  }
+
+  const std::string getCollectiveName() const {
+    return collectiveName_;
+  }
+
+  int64_t getInMessageNelems() const {
+    return inMessageNelems_;
+  }
+
+  int64_t getOutMessageNelems() const {
+    return outMessageNelems_;
+  }
+
+  at::ScalarType getDType() const {
+    return dType_;
+  }
+
+  const std::vector& getInputSplitSizes() const {
+    return inputSplitSizes_;
+  }
+
+  const std::vector& getOutputSplitSizes() const {
+    return outputSplitSizes_;
+  }
+
+  const std::vector& getGroupRanks() const {
+    return groupRanks_;
+  }
+
+ private:
+  std::tuple pgName_; // 
+  int rank_{};
+  int worldSize_{};
+  std::string collectiveName_;
+  int64_t inMessageNelems_{};
+  int64_t outMessageNelems_{};
+  at::ScalarType dType_ = at::kByte;
+  std::vector inputSplitSizes_;
+  std::vector outputSplitSizes_;
+  int globalRankStart_{};
+  int globalRankStride_{};
+  std::vector groupRanks_{};
+};
+
+#define RECORD_PARAM_COMMS(                                                    \
+    seq,                                                                       \
+    pgName,                                                                    \
+    rank,                                                                      \
+    collName,                                                                  \
+    inNelems,                                                                  \
+    outNelems,                                                                 \
+    dType,                                                                     \
+    inSplitSizes,                                                              \
+    outSplitSizes,                                                             \
+    globalRankStart,                                                           \
+    globalRankStride,                                                          \
+    worldSize)                                                                 \
+  auto paramCommsInfo = std::make_shared(          \
+      pgName,                                                                  \
+      rank,                                                                    \
+      collName,                                                                \
+      inNelems,                                                                \
+      outNelems,                                                               \
+      dType,                                                                   \
+      inSplitSizes,                                                            \
+      outSplitSizes,                                                           \
+      globalRankStart,                                                         \
+      globalRankStride,                                                        \
+      worldSize);                                                              \
+  c10::DebugInfoGuard g(c10::DebugInfoKind::PARAM_COMMS_INFO, paramCommsInfo); \
+  std::initializer_list paramList = {                       \
+      c10::IValue(seq),                                                        \
+      pgName,                                                                  \
+      rank,                                                                    \
+      collName,                                                                \
+      inSplitSizes,                                                            \
+      outSplitSizes,                                                           \
+      globalRankStart,                                                         \
+      globalRankStride,                                                        \
+      worldSize};                                                              \
+  c10::ArrayRef paramInputs(paramList);                     \
+  RECORD_FUNCTION(at::kParamCommsCallName, paramInputs);
+
+#define RECORD_PARAM_COMMS_DATA(                                               \
+    seq,                                                                       \
+    pgName,                                                                    \
+    InputTensors,                                                              \
+    OutputTensors,                                                             \
+    rank,                                                                      \
+    collName,                                                                  \
+    inNelems,                                                                  \
+    outNelems,                                                                 \
+    dType,                                                                     \
+    inSplitSizes,                                                              \
+    outSplitSizes,                                                             \
+    globalRankStart,                                                           \
+    globalRankStride,                                                          \
+    worldSize)                                                                 \
+  auto paramCommsInfo = std::make_shared(          \
+      pgName,                                                                  \
+      rank,                                                                    \
+      collName,                                                                \
+      inNelems,                                                                \
+      outNelems,                                                               \
+      dType,                                                                   \
+      inSplitSizes,                                                            \
+      outSplitSizes,                                                           \
+      globalRankStart,                                                         \
+      globalRankStride,                                                        \
+      worldSize);                                                              \
+  c10::DebugInfoGuard g(c10::DebugInfoKind::PARAM_COMMS_INFO, paramCommsInfo); \
+  std::initializer_list paramList = {                       \
+      c10::IValue(InputTensors),                                               \
+      c10::IValue(seq),                                                        \
+      pgName,                                                                  \
+      rank,                                                                    \
+      collName,                                                                \
+      inSplitSizes,                                                            \
+      outSplitSizes,                                                           \
+      globalRankStart,                                                         \
+      globalRankStride,                                                        \
+      worldSize};                                                              \
+  c10::ArrayRef paramInputs(paramList);                     \
+  RECORD_FUNCTION_WITH_INPUTS_OUTPUTS(                                         \
+      at::kParamCommsCallName,                                                 \
+      paramInputs,                                                             \
+      std::vector(1, c10::IValue(OutputTensors)));
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/PrefixStore.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/PrefixStore.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..19098f0c38f015ebb1134fa52631602792f765c6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/PrefixStore.hpp
@@ -0,0 +1,66 @@
+#pragma once
+
+#include 
+
+namespace c10d {
+
+class TORCH_API PrefixStore : public Store {
+ public:
+  explicit PrefixStore(std::string prefix, c10::intrusive_ptr store);
+
+  using Store::set;
+  void set(const std::string& key, const std::vector& value) override;
+
+  using Store::compareSet;
+  std::vector compareSet(
+      const std::string& key,
+      const std::vector& expectedValue,
+      const std::vector& desiredValue) override;
+
+  std::vector get(const std::string& key) override;
+
+  int64_t add(const std::string& key, int64_t value) override;
+
+  bool deleteKey(const std::string& key) override;
+
+  int64_t getNumKeys() override;
+
+  bool check(const std::vector& keys) override;
+
+  void wait(const std::vector& keys) override;
+
+  void wait(
+      const std::vector& keys,
+      const std::chrono::milliseconds& timeout) override;
+
+  const std::chrono::milliseconds& getTimeout() const noexcept override;
+
+  void setTimeout(const std::chrono::milliseconds& timeout) override;
+
+  void append(const std::string& key, const std::vector& value)
+      override;
+
+  std::vector> multiGet(
+      const std::vector& keys) override;
+
+  void multiSet(
+      const std::vector& keys,
+      const std::vector>& values) override;
+
+  // Returns true if this store support append, multiGet and multiSet
+  bool hasExtendedApi() const override;
+
+  c10::intrusive_ptr getUnderlyingStore();
+
+  // Recursively to fetch the store before layers of wrapping with PrefixStore.
+  c10::intrusive_ptr getUnderlyingNonPrefixStore();
+
+ protected:
+  std::string prefix_;
+  c10::intrusive_ptr store_;
+
+  std::string joinKey(const std::string& key);
+  std::vector joinKeys(const std::vector& keys);
+};
+
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroup.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroup.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..acf8c9c354a76b8c8a28f25c8a24854acea0e560
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroup.hpp
@@ -0,0 +1,748 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+#include 
+// *************************************************************************
+// PROCESS GROUP collective communication API IS BEING CHANGED BETWEEN
+// versions 1.7 and 1.8.
+// PLEASE DO NOT ADD ANY DEPENDENCIES.
+// SEE RFC: https://github.com/pytorch/pytorch/issues/39662
+// *************************************************************************
+
+constexpr auto kProcessGroupDefaultTimeout =
+    std::chrono::milliseconds(30 * 60 * 1000);
+
+namespace c10d {
+
+// ProcessGroup is a base class that captures collective and point to
+// point communication in a fixed set of processes.
+//
+// The functions specified in the class below describe the API alone;
+// implementations are provided in subclasses.
+//
+// Every function that performs I/O is executed asynchronously by a
+// thread pool owned by the ProcessGroup (by default). They return an
+// object that can be used to wait for completion or error.
+//
+// The ProcessGroup can instantiate subgroups with fewer or an equal
+// number of members. Implementations must take care that multiple
+// process groups can be used in parallel and synchronize accordingly.
+//
+// The ProcessGroup assumes a fixed set of processes. If the set
+// changes, existing instances must be destructed and instantiation
+// and initialization must start from scratch. For members of the
+// process group to find each other (referred to as rendezvous from
+// hereon)
+//
+class TORCH_API ProcessGroup : public torch::CustomClassHolder {
+ public:
+  // ProcessGroup Options is a base struct that defines the basic options
+  // when constructing a ProcessGroup. Each ProcessGroup subclass should
+  // extend this struct and define its options if it wants to provide more
+  // config options (beyond basic ones defined here) to end user.
+  struct TORCH_API Options : torch::CustomClassHolder {
+    explicit Options(
+        std::string backend,
+        std::chrono::milliseconds timeout = kProcessGroupDefaultTimeout)
+        : timeout(timeout), backend(std::move(backend)) {}
+    ~Options() override = default;
+
+    std::chrono::milliseconds timeout;
+
+    // backend name
+    // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
+    const std::string backend;
+  };
+
+  enum BackendType : uint8_t {
+    UNDEFINED = 0,
+    GLOO = 1,
+    NCCL = 2,
+    UCC = 3,
+    MPI = 4,
+    CUSTOM = 5,
+  };
+
+  // Not used, set for backwards compatibility and only used for TypeDef in
+  // Ops.cpp
+  explicit ProcessGroup(int rank, int size);
+
+  explicit ProcessGroup(
+      const c10::intrusive_ptr<::c10d::Store>& store,
+      int rank,
+      int size,
+      c10::intrusive_ptr options);
+  ~ProcessGroup() override;
+
+  int getRank() const {
+    return rank_;
+  }
+
+  int getSize() const {
+    return size_;
+  }
+
+  // Returns an unique opaque ID of this process group object.
+  int64_t getID() const {
+    return reinterpret_cast(this);
+  }
+
+  // Returns an unique opaque ID of a backend for the specific backend type
+  // that can correlate with this process group's collectives.
+  int64_t getBackendID(BackendType backend_type) const {
+    return reinterpret_cast(getBackend(backend_type).get());
+  }
+
+  virtual const std::string getBackendName() const {
+    return options_->backend;
+  };
+
+  BackendType getBackendType() const {
+    return backendType_;
+  };
+
+  virtual void startCoalescing(c10::DeviceType deviceType) {
+    // only nccl has implemented startCoalescing so only execute for nccl
+    // backends
+    auto backend = getBackend(deviceType);
+    backend->startCoalescing();
+  }
+
+  virtual c10::intrusive_ptr endCoalescing(c10::DeviceType deviceType) {
+    // only nccl has implemented endCoalescing so only execute for nccl
+    // backends
+    auto backend = getBackend(deviceType);
+    auto work = backend->endCoalescing();
+    return work;
+  }
+
+  virtual c10::intrusive_ptr broadcast(
+      std::vector& tensors,
+      const BroadcastOptions& opts = BroadcastOptions()) {
+    static auto op =
+        c10::Dispatcher::singleton()
+            .findSchemaOrThrow("c10d::broadcast_", "")
+            .typed<
+                std::tuple, c10::intrusive_ptr>(
+                    at::TensorList,
+                    const c10::intrusive_ptr<::c10d::ProcessGroup>&,
+                    int64_t,
+                    int64_t,
+                    bool,
+                    int64_t)>();
+    // It's awakward to unbox the opts here and box them again in the custom C++
+    // op. But it's also complicated to make opts as a CustomClassHolder. Leave
+    // it as it is now.
+    return std::get<1>(op.call(
+        tensors,
+        c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this),
+        opts.rootRank,
+        opts.rootTensor,
+        opts.asyncOp,
+        opts.timeout.count()));
+  }
+
+  virtual c10::intrusive_ptr allreduce(
+      std::vector& tensors,
+      const AllreduceOptions& opts = AllreduceOptions()) {
+    static auto op =
+        c10::Dispatcher::singleton()
+            .findSchemaOrThrow("c10d::allreduce_", "")
+            .typed<
+                std::tuple, c10::intrusive_ptr>(
+                    at::TensorList,
+                    const c10::intrusive_ptr<::c10d::ProcessGroup>&,
+                    const c10::intrusive_ptr<::c10d::ReduceOp>&,
+                    const std::optional& sparse_indices,
+                    int64_t)>();
+
+    return std::get<1>(op.call(
+        tensors,
+        c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this),
+        c10::make_intrusive(opts.reduceOp),
+        opts.sparseIndices,
+        opts.timeout.count()));
+  }
+
+  virtual c10::intrusive_ptr allreduce_coalesced(
+      std::vector& tensors,
+      const AllreduceCoalescedOptions& opts = AllreduceCoalescedOptions()) {
+    static auto op = c10::Dispatcher::singleton()
+                         .findSchemaOrThrow("c10d::allreduce_coalesced_", "")
+                         .typed(
+                             at::TensorList,
+                             const c10::intrusive_ptr<::c10d::ProcessGroup>&,
+                             const c10::intrusive_ptr<::c10d::ReduceOp>&,
+                             int64_t)>();
+
+    return op.call(
+        tensors,
+        c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this),
+        c10::make_intrusive(opts.reduceOp),
+        opts.timeout.count());
+  }
+
+  virtual c10::intrusive_ptr reduce(
+      std::vector& tensors,
+      const ReduceOptions& opts = ReduceOptions()) {
+    static auto op = c10::Dispatcher::singleton()
+                         .findSchemaOrThrow("c10d::reduce_", "")
+                         .typed(
+                             at::TensorList,
+                             const c10::intrusive_ptr<::c10d::ProcessGroup>&,
+                             const c10::intrusive_ptr<::c10d::ReduceOp>&,
+                             int64_t,
+                             int64_t,
+                             int64_t)>();
+    return op.call(
+        tensors,
+        c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this),
+        c10::make_intrusive(opts.reduceOp),
+        opts.rootRank,
+        opts.rootTensor,
+        opts.timeout.count());
+  }
+
+  virtual c10::intrusive_ptr allgather(
+      std::vector>& outputTensors,
+      std::vector& inputTensors,
+      const AllgatherOptions& opts = AllgatherOptions()) {
+    static auto op = c10::Dispatcher::singleton()
+                         .findSchemaOrThrow("c10d::allgather_", "")
+                         .typed>,
+                             c10::intrusive_ptr>(
+                             const std::vector>&,
+                             at::TensorList,
+                             const c10::intrusive_ptr<::c10d::ProcessGroup>&,
+                             int64_t)>();
+
+    return std::get<1>(op.call(
+        outputTensors,
+        inputTensors,
+        c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this),
+        opts.timeout.count()));
+  }
+
+  // Gathers a single tensor inputBuffer into a single buffer outputBuffer that
+  // is interpreted as a contiguous collection of size inputBuffer * WORLD_SIZE.
+  // For implementers of ProcessGroup API and advanced users only.
+  // Note: this function will be deprecated in near future.
+  virtual c10::intrusive_ptr _allgather_base(
+      at::Tensor& outputBuffer,
+      at::Tensor& inputBuffer,
+      const AllgatherOptions& opts = AllgatherOptions()) {
+    static auto op =
+        c10::Dispatcher::singleton()
+            .findSchemaOrThrow("c10d::_allgather_base_", "")
+            .typed>(
+                at::Tensor&,
+                at::Tensor&,
+                const c10::intrusive_ptr<::c10d::ProcessGroup>&,
+                bool,
+                int64_t)>();
+
+    return std::get<1>(op.call(
+        outputBuffer,
+        inputBuffer,
+        c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this),
+        opts.asyncOp,
+        opts.timeout.count()));
+  }
+
+  // This function is deprecated and will be moved out of ProcessGroup to comms:
+  // * do not add dependencies on this function,
+  // * do not implement it in your ProcessGroup, implement _allgather_base
+  //   instead.
+  virtual c10::intrusive_ptr allgather_coalesced(
+      std::vector>& outputTensorLists,
+      std::vector& inputTensors,
+      const AllgatherOptions& opts = AllgatherOptions()) {
+    static auto op =
+        c10::Dispatcher::singleton()
+            .findSchemaOrThrow("c10d::allgather_coalesced_", "")
+            .typed(
+                const std::vector>&,
+                const at::TensorList&,
+                const c10::intrusive_ptr<::c10d::ProcessGroup>&)>();
+
+    return op.call(
+        outputTensorLists,
+        inputTensors,
+        c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this));
+  }
+
+  // This function is a coalesced version of `allgather_into_tensor` (currently
+  // still named as `_allgather_base`). Each tensor in the vector corresponds to
+  // an input/output of one `allgather_into_tensor` operation.
+  virtual c10::intrusive_ptr allgather_into_tensor_coalesced(
+      std::vector& outputTensors,
+      std::vector& inputTensors,
+      const AllgatherOptions& opts = AllgatherOptions()) {
+    static auto op =
+        c10::Dispatcher::singleton()
+            .findSchemaOrThrow("c10d::allgather_into_tensor_coalesced_", "")
+            .typed(
+                const at::TensorList,
+                const at::TensorList,
+                const c10::intrusive_ptr<::c10d::ProcessGroup>&)>();
+
+    return op.call(
+        outputTensors,
+        inputTensors,
+        c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this));
+  }
+
+  virtual c10::intrusive_ptr gather(
+      std::vector>& outputTensors,
+      std::vector& inputTensors,
+      const GatherOptions& opts = GatherOptions()) {
+    static auto op = c10::Dispatcher::singleton()
+                         .findSchemaOrThrow("c10d::gather_", "")
+                         .typed(
+                             const std::vector>&,
+                             const at::TensorList&,
+                             const c10::intrusive_ptr<::c10d::ProcessGroup>&,
+                             int64_t,
+                             int64_t)>();
+    return op.call(
+        outputTensors,
+        inputTensors,
+        c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this),
+        opts.rootRank,
+        opts.timeout.count());
+  }
+
+  virtual c10::intrusive_ptr scatter(
+      std::vector& outputTensors,
+      std::vector>& inputTensors,
+      const ScatterOptions& opts = ScatterOptions()) {
+    static auto op =
+        c10::Dispatcher::singleton()
+            .findSchemaOrThrow("c10d::scatter_", "")
+            .typed<
+                std::tuple, c10::intrusive_ptr>(
+                    const at::TensorList&,
+                    const std::vector>&,
+                    const c10::intrusive_ptr<::c10d::ProcessGroup>&,
+                    int64_t,
+                    bool,
+                    int64_t)>();
+    return std::get<1>(op.call(
+        outputTensors,
+        inputTensors,
+        c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this),
+        opts.rootRank,
+        opts.asyncOp,
+        opts.timeout.count()));
+  }
+
+  virtual c10::intrusive_ptr reduce_scatter(
+      std::vector& outputTensors,
+      std::vector>& inputTensors,
+      const ReduceScatterOptions& opts = ReduceScatterOptions()) {
+    static auto op =
+        c10::Dispatcher::singleton()
+            .findSchemaOrThrow("c10d::reduce_scatter_", "")
+            .typed<
+                std::tuple, c10::intrusive_ptr>(
+                    const at::TensorList&,
+                    const std::vector>&,
+                    const c10::intrusive_ptr<::c10d::ProcessGroup>&,
+                    const c10::intrusive_ptr<::c10d::ReduceOp>&,
+                    int64_t)>();
+    return std::get<1>(op.call(
+        outputTensors,
+        inputTensors,
+        c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this),
+        c10::make_intrusive<::c10d::ReduceOp>(opts.reduceOp),
+        opts.timeout.count()));
+  }
+
+  virtual c10::intrusive_ptr _reduce_scatter_base(
+      at::Tensor& outputBuffer,
+      at::Tensor& inputBuffer,
+      const ReduceScatterOptions& opts = ReduceScatterOptions()) {
+    static auto op =
+        c10::Dispatcher::singleton()
+            .findSchemaOrThrow("c10d::_reduce_scatter_base_", "")
+            .typed>(
+                at::Tensor&,
+                at::Tensor&,
+                const c10::intrusive_ptr<::c10d::ProcessGroup>&,
+                const c10::intrusive_ptr<::c10d::ReduceOp>&,
+                bool,
+                int64_t)>();
+    return std::get<1>(op.call(
+        outputBuffer,
+        inputBuffer,
+        c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this),
+        c10::make_intrusive<::c10d::ReduceOp>(opts.reduceOp),
+        opts.asyncOp,
+        opts.timeout.count()));
+  }
+
+  // This function is a coalesced version of `reduce_scatter_tensor` (currently
+  // still named as `_reduce_scatter_base`). Each tensor in the vector
+  // corresponds to an input/output of one `reduce_scatter_tensor` operation.
+  virtual c10::intrusive_ptr reduce_scatter_tensor_coalesced(
+      std::vector& outputTensors,
+      std::vector& inputTensors,
+      const ReduceScatterOptions& opts = ReduceScatterOptions()) {
+    static auto op =
+        c10::Dispatcher::singleton()
+            .findSchemaOrThrow("c10d::reduce_scatter_tensor_coalesced_", "")
+            .typed(
+                const at::TensorList,
+                const at::TensorList,
+                const c10::intrusive_ptr<::c10d::ProcessGroup>&,
+                const c10::intrusive_ptr<::c10d::ReduceOp>&,
+                int64_t)>();
+
+    return op.call(
+        outputTensors,
+        inputTensors,
+        c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this),
+        c10::make_intrusive<::c10d::ReduceOp>(opts.reduceOp),
+        opts.timeout.count());
+  }
+
+  virtual c10::intrusive_ptr alltoall_base(
+      at::Tensor& outputBuffer,
+      at::Tensor& inputBuffer,
+      std::vector& outputSplitSizes,
+      std::vector& inputSplitSizes,
+      const AllToAllOptions& opts = AllToAllOptions()) {
+    static auto op = c10::Dispatcher::singleton()
+                         .findSchemaOrThrow("c10d::alltoall_base_", "")
+                         .typed(
+                             at::Tensor&,
+                             at::Tensor&,
+                             const c10::intrusive_ptr<::c10d::ProcessGroup>&,
+                             std::vector,
+                             std::vector,
+                             int64_t)>();
+    return op.call(
+        outputBuffer,
+        inputBuffer,
+        c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this),
+        outputSplitSizes,
+        inputSplitSizes,
+        opts.timeout.count());
+  }
+
+  virtual c10::intrusive_ptr alltoall(
+      std::vector& outputTensors,
+      std::vector& inputTensors,
+      const AllToAllOptions& opts = AllToAllOptions()) {
+    static auto op =
+        c10::Dispatcher::singleton()
+            .findSchemaOrThrow("c10d::alltoall_", "")
+            .typed<
+                std::tuple, c10::intrusive_ptr>(
+                    const at::TensorList&,
+                    const at::TensorList&,
+                    const c10::intrusive_ptr<::c10d::ProcessGroup>&,
+                    int64_t)>();
+    return std::get<1>(op.call(
+        outputTensors,
+        inputTensors,
+        c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this),
+        opts.timeout.count()));
+  }
+
+  virtual void monitoredBarrier(
+      const BarrierOptions& opts,
+      bool wait_all_ranks = false) {
+    static auto op = c10::Dispatcher::singleton()
+                         .findSchemaOrThrow("c10d::monitored_barrier_", "")
+                         .typed&,
+                             const std::vector&,
+                             int64_t,
+                             bool)>();
+    // Default to using cpu implementation, monitored barrier is only for GLOO
+    at::Tensor tensor = at::empty({0}, at::TensorOptions().device(at::kCPU));
+    op.call(
+        tensor,
+        c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this),
+        opts.device_ids,
+        opts.timeout.count(),
+        wait_all_ranks);
+  }
+
+  // Agrees on an initial sequence number for the whole group by having rank 0
+  // create it and broadcast it to other ranks using the store. Only implemented
+  // for GLOO and NCCL backends currently.
+  virtual void setSequenceNumberForGroup() {
+    auto backendType = getBackendType();
+    // TODO: HACK for backend name to get sequence number for that backend.
+    if (backendType == ProcessGroup::BackendType::GLOO ||
+        backendType == ProcessGroup::BackendType::NCCL ||
+        backendType == ProcessGroup::BackendType::UCC) {
+      getDefaultBackend()->setSequenceNumberForGroup();
+    } else {
+      TORCH_CHECK(
+          false,
+          c10::str(
+              "ProcessGroup ",
+              getBackendName(),
+              " does not yet support sequence numbers."));
+    }
+  }
+
+  // Retrieves the current sequence number for the whole group, which should be
+  // in sync. If the returned number is not consistent across the group, it
+  // may indicate that there is some sort of collective desynchronization.
+  virtual uint64_t getSequenceNumberForGroup() {
+    auto backendType = getBackendType();
+
+    // TODO: HACK for backend name to get sequence number for that backend.
+    if (backendType == ProcessGroup::BackendType::GLOO ||
+        backendType == ProcessGroup::BackendType::NCCL ||
+        backendType == ProcessGroup::BackendType::UCC) {
+      return getDefaultBackend()->getSequenceNumberForGroup();
+    } else {
+      TORCH_CHECK(
+          false,
+          c10::str(
+              "ProcessGroup ",
+              getBackendName(),
+              " does not yet support sequence numbers."));
+    }
+  }
+
+  virtual c10::intrusive_ptr send(
+      std::vector& tensors,
+      int dstRank,
+      int tag) {
+    static auto op = c10::Dispatcher::singleton()
+                         .findSchemaOrThrow("c10d::send", "")
+                         .typed(
+                             at::TensorList,
+                             const c10::intrusive_ptr<::c10d::ProcessGroup>&,
+                             int64_t,
+                             int64_t)>();
+    return op.call(
+        tensors,
+        c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this),
+        dstRank,
+        tag);
+  }
+
+  virtual c10::intrusive_ptr recv(
+      std::vector& tensors,
+      int srcRank,
+      int tag) {
+    static auto op = c10::Dispatcher::singleton()
+                         .findSchemaOrThrow("c10d::recv_", "")
+                         .typed(
+                             at::TensorList,
+                             const c10::intrusive_ptr<::c10d::ProcessGroup>&,
+                             int64_t,
+                             int64_t)>();
+    return op.call(
+        tensors,
+        c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this),
+        srcRank,
+        tag);
+  }
+
+  virtual c10::intrusive_ptr recvAnysource(
+      std::vector& tensors,
+      int tag) {
+    static auto op = c10::Dispatcher::singleton()
+                         .findSchemaOrThrow("c10d::recv_any_source_", "")
+                         .typed(
+                             at::TensorList,
+                             const c10::intrusive_ptr<::c10d::ProcessGroup>&,
+                             int64_t)>();
+    return op.call(
+        tensors,
+        c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this),
+        tag);
+  }
+
+  virtual c10::intrusive_ptr barrier(
+      const BarrierOptions& opts = BarrierOptions()) {
+    static at::Tensor tensor;
+    // TODO: if nccl was specified then use it
+    auto device = opts.device;
+    if (device.has_value()) {
+      // set device tensor from argument
+      tensor = at::empty(
+          {1}, at::TensorOptions().device(device.value()).dtype(at::kByte));
+    } else if (backendType_ == c10d::ProcessGroup::BackendType::NCCL) {
+      // set cuda tensor
+      tensor = at::empty(
+          {1},
+          at::TensorOptions().device(at::DeviceType::CUDA).dtype(at::kByte));
+    } else {
+      // Default to using cpu implementation
+      tensor = at::empty(
+          {1},
+          at::TensorOptions().device(at::DeviceType::CPU).dtype(at::kByte));
+    }
+
+    static auto op = c10::Dispatcher::singleton()
+                         .findSchemaOrThrow("c10d::barrier", "")
+                         .typed(
+                             at::Tensor,
+                             const c10::intrusive_ptr<::c10d::ProcessGroup>&,
+                             const std::vector&,
+                             int64_t)>();
+
+    return op.call(
+        tensor,
+        c10::intrusive_ptr::unsafe_reclaim_from_nonowning(this),
+        opts.device_ids,
+        opts.timeout.count());
+  }
+
+  c10::intrusive_ptr getOptions() {
+    return options_;
+  }
+
+  bool hasBackends() {
+    return !deviceTypeToBackendType_.empty();
+  }
+
+  void setBackend(
+      c10::DeviceType deviceType,
+      BackendType backendType,
+      const std::optional>& backend) {
+    // TODO: should we add these entries after the backend setting succeeds?
+    deviceTypeToBackendType_[deviceType] = backendType;
+    deviceTypes_.insert(deviceType);
+    // if the backendType is already set then reuse it for this device
+    if (backendTypeToBackend_.find(backendType) !=
+        backendTypeToBackend_.end()) {
+      auto existingBackend = backendTypeToBackend_.at(backendType);
+      deviceTypeToBackend_[deviceType] = existingBackend;
+      TORCH_CHECK(
+          existingBackend->getBoundDeviceId() ==
+          (*backend)->getBoundDeviceId());
+    } else {
+      // check if backend has value
+      if (backend.has_value()) {
+        deviceTypeToBackend_[deviceType] = backend.value();
+        backendTypeToBackend_[backendType] = backend.value();
+        (*backend)->setBoundDeviceId(bound_device_id_);
+      }
+    }
+  }
+
+  c10::intrusive_ptr getDefaultBackend() const {
+    TORCH_CHECK(
+        backendTypeToBackend_.find(backendType_) != backendTypeToBackend_.end(),
+        "Could not find the default backend type ",
+        backendType_,
+        " for Process Group with name ",
+        getBackendName(),
+        ".");
+    return backendTypeToBackend_.at(backendType_);
+  }
+
+  c10::intrusive_ptr getBackend(c10::DeviceType deviceType);
+
+  c10::intrusive_ptr getBackend(BackendType backendType) const {
+    TORCH_CHECK(
+        backendTypeToBackend_.find(backendType) != backendTypeToBackend_.end(),
+        "Could not find backend type ",
+        backendType,
+        ".");
+    return backendTypeToBackend_.at(backendType);
+  }
+
+  // Return device types supported by this ProcessGroup.
+  // Note: the return type is `Device` rather than `DeviceType` for the purpose
+  // of easy comparison at Python level. The `Device` will have default index
+  // (-1).
+  std::vector getDeviceTypes() const {
+    std::vector devices;
+    devices.reserve(deviceTypes_.size());
+    for (auto& dt : deviceTypes_) {
+      devices.emplace_back(dt);
+    }
+    return devices;
+  }
+
+  void registerOnCompletionHook(
+      std::function)>&& hook) {
+    getDefaultBackend()->registerOnCompletionHook(std::move(hook));
+  }
+
+  void waitForPendingWorks() {
+    getDefaultBackend()->waitForPendingWorks();
+  }
+
+  bool hasHooks() const {
+    return getDefaultBackend()->hasHooks();
+  }
+
+  const std::string& getGroupName() const;
+  void setGroupName(const std::string& name);
+  const std::string& getGroupDesc() const;
+  void setGroupDesc(const std::string& name);
+  void enableCollectivesTiming();
+
+  void release_resources() override;
+
+  // ProcessGroups optionally can be "bound" to a specific device.
+  // Currently this is only for nccl and allows for some opt-in
+  // optimizations such as automatic use of ncclCommSplit.  The device
+  // is specified in `init_process_group` and eventually makes it
+  // here and then down into the actual backend instances.
+  std::optional getBoundDeviceId() const {
+    return bound_device_id_;
+  }
+
+  void setBoundDeviceId(std::optional device) {
+    if (device) {
+      TORCH_CHECK(device->has_index(), "setBoundDeviceId must have an index");
+    }
+    bound_device_id_ = device;
+  }
+
+ protected:
+  // Implementations of this interface need to call this to setup
+  // appropriate logging etc.
+  void init();
+
+  c10::intrusive_ptr store_;
+  // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
+  const int rank_;
+  // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
+  const int size_;
+  // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
+  const c10::intrusive_ptr options_;
+  // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
+  const BackendType backendType_;
+  std::string pg_desc_;
+
+  // Debug level setting. It is parsed once when ProcessGroup is constructed and
+  // remains the same across use of this process group.
+  DebugLevel dist_debug_level_{DebugLevel::Off};
+
+  // Backend classes for this ProcessGroup
+  std::unordered_set deviceTypes_;
+  std::unordered_map deviceTypeToBackendType_;
+  std::unordered_map>
+      deviceTypeToBackend_;
+  std::unordered_map>
+      backendTypeToBackend_;
+
+  std::optional bound_device_id_;
+};
+
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupGloo.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupGloo.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..9f1e63d58adf2d2858271bb3e80c3d5cf86739ea
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupGloo.hpp
@@ -0,0 +1,448 @@
+#pragma once
+
+#ifdef USE_C10D_GLOO
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include 
+#include 
+#include 
+#include 
+
+namespace c10d {
+
+constexpr const char* GLOO_BACKEND_NAME = "gloo";
+
+// ProcessGroupGloo implements Gloo bindings for c10d.
+//
+// All functions on this class are expected to be called in the same
+// order across processes in the group. This is the only way that we
+// can guarantee to match up the same calls across processes. For
+// multi-threaded usage of process groups, you can use consider using
+// multiple process group instances.
+//
+// The Gloo algorithms that this class calls into are cached by their
+// signature (see description of AlgorithmKey above). This cache works
+// as follows: every function call instantiates an AlgorithmKey and
+// looks in the cache for existing entries. If there is one, it is
+// removed from the cache and returned to the caller. If there are
+// none, a new entry is created and returned. If an entry was created
+// before, but is still in use, the call will block and wait until the
+// entry is returned to the cache.
+//
+// In the future, we hope to extend this to allow multiple entries per
+// key, to enable parallelism for a single key. The number of entries
+// per key must always be identical for all processes. This maximum
+// number can be automatically tuned, but only if we let a single
+// process take charge, and have it broadcast the limits.
+//
+class TORCH_API ProcessGroupGloo : public Backend {
+ public:
+  // AsyncWork is the Gloo specific superclass for asynchronous work items.
+  // We can split asynchronous work into 3 phases:
+  // 1) Sanity checks and prepare input (e.g. memcpy)
+  // 2) Run operation on background thread
+  // 3) Synchronize with completion on foreground thread
+  //
+  // There is state to be shared between these 3 phases and all of this state
+  // is captured in the AsyncWork class and its derivatives.
+  //
+  // Note: while we are porting operations to use new style collectives, there
+  // is a split between operations using the existing caching approach and
+  // operations using the new AsyncWork base class. Over time we will port
+  // all operations and perform needed cleanup.
+  //
+  // FIXME: This probably should be called WorkGloo since the work is executed
+  // in sync mode by a background thread.
+  class TORCH_API AsyncWork : public Work {
+   public:
+    explicit AsyncWork(
+        std::vector> outputTensors,
+        OpType opType,
+        uint64_t seq,
+        const char* profilingTitle = nullptr,
+        const std::optional>& inputTensors =
+            std::nullopt);
+
+    ~AsyncWork() override = default;
+
+    static void execute(const c10::intrusive_ptr& work);
+
+    virtual void run() = 0;
+
+    std::vector result() override;
+
+    c10::intrusive_ptr getFuture() override;
+    uint64_t getSequencenumber() const override;
+
+   protected:
+    friend class ProcessGroupGloo;
+
+   private:
+    void finishWorkGloo();
+    void finishWorkGlooError(const std::exception_ptr& eptr);
+    inline void recordAsyncWorkProfilingInfo(
+        const char* profilingTitle,
+        const std::optional>& inputTensors);
+
+    const std::vector> outputTensors_;
+    c10::intrusive_ptr future_;
+    std::function recordFunctionBeforeCallback_;
+    const uint64_t seq_;
+  };
+
+  // Wrap c10d store as Gloo store
+  class TORCH_API GlooStore : public ::gloo::rendezvous::Store {
+   public:
+    GlooStore(const c10::intrusive_ptr<::c10d::Store>& store) : store_(store) {}
+
+    void setUint(const std::string& key, const std::vector& value) {
+      store_->set(key, value);
+    }
+
+    void set(const std::string& key, const std::vector& value) override {
+      std::vector tmp(value.begin(), value.end());
+      store_->set(key, tmp);
+    }
+
+    std::vector getUint(const std::string& key) {
+      auto value = store_->get(key);
+      return value;
+    }
+
+    std::vector get(const std::string& key) override {
+      auto value = store_->get(key);
+      return std::vector(value.begin(), value.end());
+    }
+
+    void wait(const std::vector& keys) override {
+      store_->wait(keys, ::c10d::Store::kDefaultTimeout);
+    }
+
+    void wait(
+        const std::vector& keys,
+        const std::chrono::milliseconds& timeout) override {
+      store_->wait(keys, timeout);
+    }
+
+#ifdef GLOO_STORE_HAS_STORE_V2
+    bool has_v2_support() override {
+      return store_->hasExtendedApi();
+    }
+
+    std::vector> multi_get(
+        const std::vector& keys) override {
+      std::vector> res;
+      for (auto& value : store_->multiGet(keys)) {
+        res.emplace_back(value.begin(), value.end());
+      }
+      return res;
+    }
+
+    void multi_set(
+        const std::vector& keys,
+        const std::vector>& values) override {
+      std::vector> u_values;
+      u_values.reserve(values.size());
+      for (auto& value : values) {
+        u_values.emplace_back(value.begin(), value.end());
+      }
+      store_->multiSet(keys, u_values);
+    }
+
+    void append(const std::string& key, const std::vector& value)
+        override {
+      std::vector tmp(value.begin(), value.end());
+      return store_->append(key, tmp);
+    }
+
+    int64_t add(const std::string& key, int64_t value) override {
+      return store_->add(key, value);
+    }
+#endif
+
+   protected:
+    c10::intrusive_ptr<::c10d::Store> store_;
+  };
+
+  // For send and recv operations there is no need to pass them to the
+  // thread pool as they are entirely completed by the device thread.
+  // This work object is used to synchronize completion of the send or
+  // recv operation. It keeps a reference to the tensor it is
+  // operating on to prevent it from being deallocated while the
+  // operation is still in flight.
+  class TORCH_API SendWork : public Work {
+   public:
+    explicit SendWork(
+        at::Tensor& tensor,
+        std::unique_ptr<::gloo::transport::UnboundBuffer> buffer,
+        uint64_t seq);
+
+    bool wait(std::chrono::milliseconds timeout = kNoTimeout) override;
+
+    void abort() override;
+
+    uint64_t getSequencenumber() const override;
+
+   protected:
+    at::Tensor tensor_;
+    std::unique_ptr<::gloo::transport::UnboundBuffer> buffer_;
+    const uint64_t seq_;
+  };
+
+  class TORCH_API RecvWork : public Work {
+   public:
+    explicit RecvWork(
+        at::Tensor& tensor,
+        std::unique_ptr<::gloo::transport::UnboundBuffer> buffer,
+        OpType opType,
+        uint64_t seq,
+        const char* profilingTitle = nullptr);
+
+    int sourceRank() const override;
+
+    bool wait(std::chrono::milliseconds timeout = kNoTimeout) override;
+
+    void abort() override;
+
+    uint64_t getSequencenumber() const override;
+
+   protected:
+    at::Tensor tensor_;
+    std::unique_ptr<::gloo::transport::UnboundBuffer> buffer_;
+    int srcRank_;
+    const uint64_t seq_;
+  };
+
+  struct TORCH_API Options : public Backend::Options {
+    explicit Options(
+        std::chrono::milliseconds timeout = kBackendDefaultTimeout);
+
+    // return intrusive_ptr of the object
+    static c10::intrusive_ptr create(
+        std::chrono::milliseconds timeout = kBackendDefaultTimeout) {
+      return c10::make_intrusive(timeout);
+    }
+
+    std::vector> devices;
+    int threads;
+  };
+
+  const std::string getBackendName() const override {
+    return std::string(GLOO_BACKEND_NAME);
+  }
+
+  // Helper functions to create a new device object.
+  // They are static functions on this class to keep them logically
+  // separate from the rest of the code base (e.g. torch/csrc/distributed).
+
+  // Create new device instance for specific interface.
+  static std::shared_ptr<::gloo::transport::Device> createDeviceForInterface(
+      const std::string& interface);
+
+  // Create new device instance for specific hostname or address.
+  static std::shared_ptr<::gloo::transport::Device> createDeviceForHostname(
+      const std::string& hostname);
+
+  // Create new device instance.
+  // It tries to resolve this machine's hostname and bind to that address.
+  // If that fails (i.e. the hostname doesn't resolve to an address), it
+  // falls back to binding to the loopback address.
+  static std::shared_ptr<::gloo::transport::Device> createDefaultDevice();
+
+  // Create ProcessGroupGloo instance.
+  static c10::intrusive_ptr createProcessGroupGloo(
+      const c10::intrusive_ptr& store,
+      int rank,
+      int size,
+      std::chrono::milliseconds timeout);
+
+  explicit ProcessGroupGloo(
+      const c10::intrusive_ptr& store,
+      int rank,
+      int size,
+      c10::intrusive_ptr options = Options::create());
+
+  ~ProcessGroupGloo() override;
+
+  c10::intrusive_ptr getOptions() {
+    return options_;
+  }
+
+  c10::intrusive_ptr broadcast(
+      std::vector& tensors,
+      const BroadcastOptions& opts = BroadcastOptions()) override;
+
+  c10::intrusive_ptr allreduce(
+      std::vector& tensors,
+      const AllreduceOptions& opts = AllreduceOptions()) override;
+
+  c10::intrusive_ptr allreduce_sparse(
+      std::vector& tensors,
+      const AllreduceOptions& opts = AllreduceOptions()) override;
+
+  c10::intrusive_ptr allreduce_coalesced(
+      std::vector& tensors,
+      const AllreduceCoalescedOptions& opts =
+          AllreduceCoalescedOptions()) override;
+
+  c10::intrusive_ptr reduce(
+      std::vector& tensors,
+      const ReduceOptions& opts = ReduceOptions()) override;
+
+  c10::intrusive_ptr _reduce_scatter_base(
+      at::Tensor& outputTensor,
+      at::Tensor& inputTensor,
+      const ReduceScatterOptions& opts = ReduceScatterOptions()) override;
+
+  c10::intrusive_ptr _allgather_base(
+      at::Tensor& output_tensor,
+      at::Tensor& input_tensor,
+      const AllgatherOptions& opts = AllgatherOptions()) override;
+
+  c10::intrusive_ptr allgather(
+      std::vector>& outputs,
+      std::vector& inputs,
+      const AllgatherOptions& opts = AllgatherOptions()) override;
+
+  c10::intrusive_ptr allgather_coalesced(
+      std::vector>& output_lists,
+      std::vector& input_list,
+      const AllgatherOptions& opts = AllgatherOptions()) override;
+
+  c10::intrusive_ptr allgather_into_tensor_coalesced(
+      std::vector& outputs,
+      std::vector& inputs,
+      const AllgatherOptions& opts = AllgatherOptions()) override;
+
+  c10::intrusive_ptr gather(
+      std::vector>& outputs,
+      std::vector& inputs,
+      const GatherOptions& opts = GatherOptions()) override;
+
+  c10::intrusive_ptr scatter(
+      std::vector& outputs,
+      std::vector>& inputs,
+      const ScatterOptions& opts = ScatterOptions()) override;
+
+  c10::intrusive_ptr reduce_scatter(
+      std::vector& outputs,
+      std::vector>& inputs,
+      const ReduceScatterOptions& opts = ReduceScatterOptions()) override;
+
+  c10::intrusive_ptr reduce_scatter_tensor_coalesced(
+      std::vector& outputTensors,
+      std::vector& inputTensors,
+      const ReduceScatterOptions& opts = ReduceScatterOptions()) override;
+
+  c10::intrusive_ptr alltoall_base(
+      at::Tensor& outputTensor,
+      at::Tensor& inputTensor,
+      std::vector& outputCounts,
+      std::vector& inputCounts,
+      const AllToAllOptions& opts = AllToAllOptions()) override;
+
+  c10::intrusive_ptr send(
+      std::vector& tensors,
+      int dstRank,
+      int tag) override;
+
+  c10::intrusive_ptr recv(
+      std::vector& tensors,
+      int srcRank,
+      int tag) override;
+
+  c10::intrusive_ptr recvAnysource(
+      std::vector& tensors,
+      int tag) override;
+
+  c10::intrusive_ptr barrier(
+      const BarrierOptions& opts = BarrierOptions()) override;
+
+  void enableCollectivesTiming() override;
+
+  const std::unique_ptr<::gloo::rendezvous::Store>& _getStore() const {
+    return store_;
+  }
+
+  // Similar to barrier(), but blocks rank 0 until all other ranks have
+  // acknowledged that they are alive (through send/recv from rank 0). Rank 0
+  // is able to report all failed ranks if waitAllRanks = true, otherwise
+  // reports the first rank it detected as failed.
+  void monitoredBarrier(
+      const BarrierOptions& opts = BarrierOptions(),
+      bool waitAllRanks = false) override;
+
+  // Agrees on an initial sequence number for the whole group by having rank 0
+  // create it and broadcast it to other ranks using the store.
+  void setSequenceNumberForGroup() override;
+
+  // Retrieves the current sequence number for the whole group, which should be
+  // in sync. If the returned number is not consistent across the group, it
+  // may indicate that there is some sort of collective desynchronization.
+  uint64_t getSequenceNumberForGroup() override;
+
+  int getNumThreads() {
+    return options_->threads;
+  }
+
+ protected:
+  std::unique_ptr<::gloo::rendezvous::Store> store_;
+  const c10::intrusive_ptr options_;
+
+  // Every Gloo context represents a set of connections to its peers.
+  // In order to use more than one device (or allow for parallelism on
+  // a single device), you need multiple contexts.
+  std::vector> contexts_;
+  std::vector threads_;
+  bool stop_;
+
+  // Incremented for every collective we kick off.
+  // The value is used as tag for collective operations. Collectives are kicked
+  // off in identical order across processes. Therefore the tag can be used
+  // to match up operations during concurrent execution.
+  uint32_t collectiveCounter_;
+
+  // Returns next collective tag to use (uses collectiveCounter_).
+  uint32_t nextTag();
+
+  // Returns the context to use for the specified tag.
+  // With `nextTag` returning an increasing number, this should lead
+  // to contexts being used in a round-robin fashion.
+  std::shared_ptr<::gloo::Context> getContext(uint32_t tag);
+
+  // Entrypoint for worker threads.
+  void runLoop(int workerIndex);
+
+  // Queue work to run on worker thread.
+  void enqueue(c10::intrusive_ptr work);
+
+  // Keep both a queue of pending work, and a vector with in progress work.
+  // Both of these can only be mutated when holding the queue lock.
+  // We keep both around instead of just the queue, so we can grab a weak_ptr
+  // to all in progress and pending work when executing a barrier.
+  // When executing a barrier, we need to ensure that all prior work
+  // has completed before completing itself.
+  std::deque> workQueue_;
+  std::vector> workInProgress_;
+  std::mutex workMutex_;
+  std::condition_variable workProduceCV_;
+  std::condition_variable workConsumeCV_;
+  uint64_t seq_{0};
+};
+
+} // namespace c10d
+
+#endif // USE_C10D_GLOO
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupMPI.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupMPI.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..5eb06b7395570ecb0d670f52be9ec09fbaa25ab3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupMPI.hpp
@@ -0,0 +1,271 @@
+#pragma once
+
+#ifdef USE_C10D_MPI
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+#include 
+
+#include 
+
+namespace c10d {
+
+constexpr const char* MPI_BACKEND_NAME = "mpi";
+
+// WorkEntry is the state associated with a single MPI run instance.
+// It include the source Tensor list and destination Tensor list, as well as
+// The actual run function that will operate either on src or dst or both.
+struct WorkEntry {
+  explicit WorkEntry(
+      std::vector* srcPtr,
+      std::vector* dstPtr,
+      std::function&)> run)
+      : dst(dstPtr ? *dstPtr : std::vector()), run(std::move(run)) {
+    if (srcPtr) {
+      src = *srcPtr;
+    }
+  }
+
+  // Not copyable
+  WorkEntry(const WorkEntry&) = delete;
+  // Not copy assignable
+  WorkEntry& operator=(const WorkEntry&) = delete;
+
+  // For input and output tensors (in-place), we will always use src
+  std::vector src;
+
+  // Copy of user provided outputs.
+  const std::vector dst;
+
+  // src rank returned, for recv only
+  int* srcRank = nullptr;
+  std::function&)> run;
+};
+
+// ProcessGroupMPI implements MPI bindings for c10d.
+//
+// All functions on this class are expected to be called in the same
+// order across processes in the group. This is the only way that we
+// can guarantee to match up the same calls across processes.
+//
+// All MPI functions provided by this class is asynchronously scheduled on a
+// Worker thread. Therefore, ProcessGroupMPI requires the MPI implementation
+// that is used to have a minimum thread support value of MPI_THREAD_SERIALIZED.
+// That is, The process may be multi-threaded, and multiple threads may make
+// MPI calls, but only one at a time: MPI calls are not made concurrently from
+// two distinct threads (all MPI calls are serialized). However, with
+// MPI_THREAD_SERIALIZED, ProcessGroupMPI will only support a singe process
+// group. In other words, no more than 1 process group can be created globally.
+//
+// If you would like to use multiple ProcessGroupMPI, it requires your MPI
+// implementation to have a thread support value of MPI_THREAD_MULTIPLE, that
+// is, multiple threads may call MPI, with no restriction.
+//
+// Also note that ProcessGroupMPI only supports a single Tensor operation. In
+// other words, the size of the input Tensor vector should always be 1.
+//
+// CUDA tensor can be supported if the MPI used is CUDA-aware MPI, and
+// ProcessGroupMPI will automatically detect this support.
+class TORCH_API ProcessGroupMPI : public Backend {
+ public:
+  class WorkMPI : public Work {
+   public:
+    explicit WorkMPI(
+        std::vector outputTensors,
+        const char* profilingTitle = nullptr,
+        const std::optional>& inputTensors =
+            std::nullopt)
+        : Work(-1, OpType::UNKNOWN, profilingTitle, inputTensors),
+          outputTensors_(std::move(outputTensors)),
+          future_(c10::make_intrusive(
+              c10::ListType::create(c10::TensorType::get()))) {}
+
+    std::vector result() override;
+
+    c10::intrusive_ptr getFuture() override;
+
+   protected:
+    friend class ProcessGroupMPI;
+
+   private:
+    void finishWorkMPI();
+    void finishWorkMPIError(const std::exception_ptr& eptr);
+
+    std::vector outputTensors_;
+    c10::intrusive_ptr future_;
+  };
+
+  class AsyncWork : public Work {
+   public:
+    AsyncWork(
+        MPI_Request request,
+        std::vector outputTensors,
+        const char* profilingTitle = nullptr,
+        const std::optional>& inputTensors =
+            std::nullopt);
+
+    ~AsyncWork() override;
+
+    bool isCompleted() override;
+
+    bool isSuccess() const override;
+
+    int sourceRank() const override;
+
+    bool wait(std::chrono::milliseconds timeout = kUnsetTimeout) override;
+
+    void abort() override;
+
+    std::vector result() override;
+
+   protected:
+    void populateException();
+
+   private:
+    const std::vector outputTensors_;
+    MPI_Request request_;
+    MPI_Status status_{};
+  };
+
+  // Constructor will spawn up the worker thread loop
+  explicit ProcessGroupMPI(int rank, int size, MPI_Comm pgComm);
+
+  ~ProcessGroupMPI() override;
+
+  // Abort the MPI program, needs to be called when exception is detected
+  void abort();
+
+  const std::string getBackendName() const override {
+    return std::string(MPI_BACKEND_NAME);
+  }
+
+  c10::intrusive_ptr broadcast(
+      std::vector& data,
+      const BroadcastOptions& opts = BroadcastOptions()) override;
+
+  c10::intrusive_ptr allreduce(
+      std::vector& tensors,
+      const AllreduceOptions& opts = AllreduceOptions()) override;
+
+  c10::intrusive_ptr allreduce_coalesced(
+      std::vector& tensors,
+      const AllreduceCoalescedOptions& opts =
+          AllreduceCoalescedOptions()) override;
+
+  c10::intrusive_ptr reduce(
+      std::vector& tensors,
+      const ReduceOptions& opts = ReduceOptions()) override;
+
+  c10::intrusive_ptr allgather(
+      std::vector>& outputTensors,
+      std::vector& inputTensors,
+      const AllgatherOptions& opts = AllgatherOptions()) override;
+
+  c10::intrusive_ptr _allgather_base(
+      at::Tensor& outputbuffer,
+      at::Tensor& inputbuffer,
+      const AllgatherOptions& opts = AllgatherOptions()) override;
+
+  c10::intrusive_ptr allgather_coalesced(
+      std::vector>& outputTensorLists,
+      std::vector& inputTensors,
+      const AllgatherOptions& opts = AllgatherOptions()) override;
+
+  c10::intrusive_ptr gather(
+      std::vector>& outputTensors,
+      std::vector& inputTensors,
+      const GatherOptions& opts = GatherOptions()) override;
+
+  c10::intrusive_ptr scatter(
+      std::vector& outputTensors,
+      std::vector>& inputTensors,
+      const ScatterOptions& opts = ScatterOptions()) override;
+
+  c10::intrusive_ptr reduce_scatter(
+      std::vector& outputTensors,
+      std::vector>& inputTensors,
+      const ReduceScatterOptions& opts = ReduceScatterOptions()) override;
+
+  c10::intrusive_ptr alltoall_base(
+      at::Tensor& outputTensor,
+      at::Tensor& inputTensor,
+      std::vector& outputSplitSizes,
+      std::vector& inputSplitSizes,
+      const AllToAllOptions& opts = AllToAllOptions()) override;
+
+  c10::intrusive_ptr alltoall(
+      std::vector& outputTensors,
+      std::vector& inputTensors,
+      const AllToAllOptions& opts = AllToAllOptions()) override;
+
+  c10::intrusive_ptr send(
+      std::vector& tensors,
+      int dstRank,
+      int tag) override;
+
+  c10::intrusive_ptr recv(
+      std::vector& tensors,
+      int srcRank,
+      int tag) override;
+
+  c10::intrusive_ptr recvAnysource(
+      std::vector& tensor,
+      int tag) override;
+
+  c10::intrusive_ptr barrier(
+      const BarrierOptions& opts = BarrierOptions()) override;
+
+  // Creating a new ProcessGroupMPI, will initialize MPI if not initialized
+  static c10::intrusive_ptr createProcessGroupMPI(
+      std::vector ranks = {});
+
+ protected:
+  using WorkType =
+      std::tuple, c10::intrusive_ptr>;
+  // Worker thread loop
+  void runLoop();
+  // Helper function that is called by the destructor
+  void destroy();
+
+  c10::intrusive_ptr enqueue(
+      std::unique_ptr entry,
+      const char* profilingTitle = nullptr,
+      const std::optional>& inputTensors =
+          std::nullopt);
+
+  bool stop_;
+
+  std::mutex pgMutex_;
+  std::thread workerThread_;
+
+  std::deque queue_;
+  std::condition_variable queueProduceCV_;
+  std::condition_variable queueConsumeCV_;
+
+  // Global states
+  static void initMPIOnce();
+  static void mpiExit();
+  static c10::once_flag onceFlagInitMPI;
+
+  static std::mutex pgGlobalMutex_;
+  static int mpiThreadSupport_;
+
+  MPI_Comm pgComm_;
+};
+
+} // namespace c10d
+
+#endif // USE_C10D_MPI
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupNCCL.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupNCCL.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..10a7d20947433a7a30ca04946777e04702e3b92d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupNCCL.hpp
@@ -0,0 +1,1232 @@
+#pragma once
+
+#ifdef USE_C10D_NCCL
+
+#if defined(__linux__)
+#include 
+#include 
+#include 
+#include 
+#endif
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+namespace c10d {
+
+// Control broadcasting of NCCL uniqueId
+static std::vector TORCH_NCCL_BCAST_UNIQUEID = {
+    "TORCH_NCCL_BCAST_UNIQUEID"};
+
+// Control whether to always use high priority streams
+static std::vector TORCH_NCCL_HIGH_PRIORITY = {
+    "TORCH_NCCL_HIGH_PRIORITY"};
+
+// Control whether or not wait() is blocking or non-blocking.
+static std::vector TORCH_NCCL_BLOCKING_WAIT = {
+    "TORCH_NCCL_BLOCKING_WAIT",
+    "NCCL_BLOCKING_WAIT"};
+
+// TODO: We want to eventually remove this variable and make users to use
+// the default value (3 - SkipCleanUp).
+// Control whether or not we perform Async Error Handling with NCCL.
+static std::vector TORCH_NCCL_ASYNC_ERROR_HANDLING = {
+    "TORCH_NCCL_ASYNC_ERROR_HANDLING",
+    "NCCL_ASYNC_ERROR_HANDLING"};
+
+// Control whether dumping debug info on watchdog
+// timeout is enabled. This variable must be set together with
+// TORCH_NCCL_ENABLE_MONITORING=1 and TORCH_NCCL_TRACE_BUFFER_SIZE > 0.
+static std::vector TORCH_NCCL_DUMP_ON_TIMEOUT = {
+    "TORCH_NCCL_DUMP_ON_TIMEOUT"};
+
+// Control whether Desync Debug is enabled. This variable must be set
+// together with TORCH_NCCL_ASYNC_ERROR_HANDLING.
+static std::vector TORCH_NCCL_DESYNC_DEBUG = {
+    "TORCH_NCCL_DESYNC_DEBUG",
+    "NCCL_DESYNC_DEBUG"};
+
+// Enable recording start-events for all ProcessGroupNCCL collectives, and
+// compute accurate collective timing per-collective. (Note: end-events are
+// recorded by default. Turn on this flag can increase chances of a watchdog
+// hang due to performing a CUDA event query which eventually calls
+// cudaEventElapsedTime() API.
+static std::vector TORCH_NCCL_ENABLE_TIMING = {
+    "TORCH_NCCL_ENABLE_TIMING",
+    "NCCL_ENABLE_TIMING"};
+
+// Enable monitoring thread which aborts the process when the ProcessGroupNCCL
+// Watchdog thread gets stuck and no heartbeat is detected after
+// TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC. This can happen due to calling CUDA/NCCL
+// APIs that may hang. It is Useful to prevent jobs being stuck for a prolonged
+// time than necessary tying up cluster resources.
+static std::vector TORCH_NCCL_ENABLE_MONITORING = {
+    "TORCH_NCCL_ENABLE_MONITORING"};
+
+// Control the watchdog heartbeat timeout period after which the monitoring
+// thread will abort the process.
+static std::vector TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC = {
+    "TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC"};
+
+// Whether to rethrow CUDA Errors in the watchdog (default true)
+static std::vector TORCH_NCCL_RETHROW_CUDA_ERRORS = {
+    "TORCH_NCCL_RETHROW_CUDA_ERRORS"};
+
+// The maximum number of events we store in the flight recorder's ring buffer.
+// (One event could be the start or end of a collective, for example).
+static std::vector TORCH_NCCL_TRACE_BUFFER_SIZE = {
+    "TORCH_NCCL_TRACE_BUFFER_SIZE"};
+
+// Control how much extra time we will wait for dumping the debugging info
+// before we exit and throws timeout exception.
+static std::vector TORCH_NCCL_WAIT_TIMEOUT_DUMP_MILSEC = {
+    "TORCH_NCCL_WAIT_TIMEOUT_DUMP_MILSEC"};
+
+// Control the interval inside the monitoring thread to check the coordinated
+// signal from other ranks, e.g. to dump the debugging information.
+static std::vector TORCH_NCCL_COORD_CHECK_MILSEC = {
+    "TORCH_NCCL_COORD_CHECK_MILSEC"};
+
+// Whether to log C++ stack traces on unclean shutdown (default true)
+static std::vector TORCH_NCCL_LOG_CPP_STACK_ON_UNCLEAN_SHUTDOWN = {
+    "TORCH_NCCL_LOG_CPP_STACK_ON_UNCLEAN_SHUTDOWN"};
+
+// Control whether to use CudaEventCache for the collective in watchdog thread.
+// We noticed in the past when cuda global lock is held, destroying CudaEvent
+// can cause a hang.
+static std::vector TORCH_NCCL_CUDA_EVENT_CACHE = {
+    "TORCH_NCCL_CUDA_EVENT_CACHE"};
+
+static std::vector TORCH_NCCL_NAN_CHECK = {"TORCH_NCCL_NAN_CHECK"};
+
+constexpr const char* NCCL_BACKEND_NAME = "nccl";
+
+constexpr const char* EXCEPTION_DUMP = "exception_dump";
+
+constexpr const int kWorkStatusUpdatePeriodMs = 30 * 1000; // 30 seconds
+
+constexpr auto kProcessGroupNCCLDefaultTimeout =
+    std::chrono::milliseconds(10 * 60 * 1000);
+
+// NoHandling: do not handle asynchronous NCCL errors
+// TearDown: tear down process upon error, see `WorkNCCL::handleException`
+// CleanUpOnly: just clean up collectives and abort communicators without
+// tearing down process SkipCleanUp: (this is a temporary option and can be
+// removed in future) tear down process without cleaning up NCCL communicators.
+// This should be used as a last resort in case `ncclCommAbort` itself is
+// hanging
+enum ErrorHandlingMode {
+  NoHandling = 0,
+  TearDown = 1,
+  CleanUpOnly = 2,
+  SkipCleanUp = 3
+};
+
+#define SHOULD_CLEAN_UP(a) (a != NoHandling && a != SkipCleanUp)
+
+#define SHOULD_TEAR_DOWN(a) (a != NoHandling && a != CleanUpOnly)
+
+#define PRINT_COLLECTIVE_HASH_SIGNATURE(phase, opType, numel, hashValue)      \
+  LOG(WARNING) << logPrefix() << "Hash of " << phase << " to NCCL " << opType \
+               << " with size " << numel << " is " << hashValue;
+
+// If set, ProcessGroupNCCL doesn't use recordStream calls to ensure
+// caching allocator safety for tensors used on both user-facing and
+// internal comm streams.
+// Instead, it stashes live references to those tensors until after
+// user-facing streams are synced with comm streams.
+// See stashed_for_allocator_safety_ below.
+static std::vector TORCH_NCCL_AVOID_RECORD_STREAMS = {
+    "TORCH_NCCL_AVOID_RECORD_STREAMS"};
+
+// If set, ProcessGroupNCCL registers postAlloc and preFree hooks to cuda cache
+// allocator so that whenever a tensor is allocated or freed, ProcessGroupNCCL
+// can register/deregister the tensor on all available NCCL communicators.
+static std::vector TORCH_NCCL_USE_TENSOR_REGISTER_ALLOCATOR_HOOK =
+    {"TORCH_NCCL_USE_TENSOR_REGISTER_ALLOCATOR_HOOK",
+     "NCCL_USE_TENSOR_REGISTER_ALLOCATOR_HOOK"};
+
+#if defined(__linux__)
+struct DumpPipe {
+  DumpPipe(int rank) {
+    std::string fileStem =
+        getCvarString({"TORCH_NCCL_DEBUG_INFO_PIPE_FILE"}, "");
+    if (fileStem.empty() ||
+        getCvarInt({"TORCH_NCCL_TRACE_BUFFER_SIZE"}, 0) <= 0) {
+      return;
+    }
+    TORCH_CHECK(!fileStem.empty(), "TORCH_NCCL_DEBUG_INFO_TEMP_FILE is empty");
+    std::string filename = c10::str(fileStem, rank, ".pipe");
+    TORCH_CHECK(
+        unlink(filename.c_str()) != -1 || errno == ENOENT,
+        "Error removing existing named pipe ",
+        filename);
+    TORCH_CHECK(
+        mkfifo(filename.c_str(), 0666) != -1,
+        "Error creating named pipe ",
+        filename);
+    fd_ = open(filename.c_str(), O_RDONLY | O_NONBLOCK);
+    LOG(INFO) << "Pipe file " << filename
+              << " has been opened, write to it to trigger NCCL Debug Dump.";
+    TORCH_CHECK(fd_ != -1, "Error opening named pipe ", filename);
+  }
+  bool shouldDump() {
+    if (fd_ == -1) {
+      return false;
+    }
+    char buf[128];
+    // non-blocking from O_NONBLOCK above.
+    // Ignore EINTR because we already will poll this
+    // again later.
+    ssize_t bytesRead = read(fd_, &buf, 128);
+    return bytesRead > 0;
+  }
+  ~DumpPipe() {
+    if (fd_ != -1) {
+      close(fd_);
+    }
+  }
+
+ private:
+  int fd_ = -1;
+};
+#else
+struct DumpPipe {
+  DumpPipe(int rank) {}
+  bool shouldDump() {
+    return false;
+  }
+};
+#endif
+
+// ProcessGroupNCCL implements NCCL bindings for c10d.
+//
+// All functions of the class are expected to be called in the same order
+// across all processes in the process group.  This is the only way that we
+// can guarantee to match up the same calls among all processes.
+//
+// All NCCL functions provided by this class are asynchronous functions. More
+// specifically, each NCCL call is scheduled on a separate CUDA stream that is
+// different from the current CUDA stream. This is for the purpose of
+// achieving potentially concurrency and better performance. As a result,
+// it is the callers' responsibility to make sure that the CUDA stream their
+// code works on needs to wait for the NCCL operation from
+// this class.
+//
+// This can be done by calling:
+//
+// either WorkNCCL::wait() or WorkNCCL::synchronize(), both achieves the same
+// functionality and are synonyms.
+//
+// Also note that WorkNCCL::finishedGPUExecution() is a helper function only
+// provided by ProcessGroupNCCL to check if the NCCL operation of WorkNCCL has
+// finished execution on the GPU (not just scheduled).
+//
+// Example on using the NCCL process group
+//
+//   ProcessGroupNCCL pg(store, rank, size);
+//   std::shared_ptr work = pg.allreduce(tensors);
+//
+//   // At this point, NCCL kernel has already by queued successfully
+//   // Now, let current stream wait for the NCCL to finish, this function is
+//   // async operation as well
+//
+//   work->wait()
+//
+//   // Now continue on other work in the current stream.
+class TORCH_API ProcessGroupNCCL : public Backend {
+ public:
+  class WorkNCCL : public Work, public std::enable_shared_from_this {
+   public:
+    friend struct WorkInfo;
+
+    // Constructor takes a list of CUDA devices
+    WorkNCCL(
+        const std::string& pgUID,
+        const std::string& pgDesc,
+        at::Device& device,
+        int rank,
+        OpType opType,
+        uint64_t seq,
+        const char* profilingTitle = nullptr,
+        const std::optional>& inputs = std::nullopt,
+        bool desyncDebug = false,
+        bool enableTiming = false,
+        bool cudaEventCacheEnabled = false,
+        DebugLevel distDebugLevel = DebugLevel::Off);
+    // Copy constructor doing partial copy without outputs_. Cleanup thread
+    // monitors and removes finished works. However it will deadlock when
+    // destructs outputs_ tensors who are view tensors in autograd graph.
+    WorkNCCL(const WorkNCCL& w);
+
+    ~WorkNCCL() override;
+
+    // Checks if the NCCL kernel has started to execute.
+    bool isStarted();
+
+    // Checks if request has completed. In this specific case of NCCL, it checks
+    // if the NCCL operation has completed on the GPU in its own NCCL stream.
+    // Non-blocking operation.
+    bool isCompleted() override;
+
+    bool isSuccess() const override;
+
+    // Same as calling synchronize() for NCCL work.
+    bool wait(std::chrono::milliseconds timeout = kNoTimeout) override;
+
+    void abort() override;
+
+    // Let current stream wait on the completing of the NCCL work
+    // Throws on exceptions. Blocking operation, which will wait for work
+    // completion.
+    void synchronize() override;
+
+    // Synchronize streams by blocking each on the NCCL stream
+    void synchronizeStream();
+
+    // Helper function to handle exception (throw if needed).
+    void handleException(ErrorHandlingMode asyncErrorHandling);
+
+    // Helper function that checks if the NCCL kernels have finished
+    // execution on the GPUs
+    bool finishedGPUExecution();
+
+    // Get a Future object that will be marked as completed internally.
+    c10::intrusive_ptr getFuture() override;
+
+    float getDuration() const override;
+
+    uint64_t getSequencenumber() const override;
+
+    const std::string& logPrefix() const;
+
+    // Helper function that sets an exception_ptr on the WorkNCCL object.
+    void setException(std::exception_ptr exception_ptr);
+
+    // Helper function that returns True if the WorkNCCL object has timed out
+    // and False otherwise.
+    // In case of timeout, set exception on the WorkNCCL object.
+    bool checkTimeout(
+        std::optional timeout = std::nullopt);
+
+    std::vector result() override;
+
+   protected:
+    // The process group unique id
+    std::string pgUID_;
+
+    // The process group description
+    std::string pgDesc_;
+
+    // The cached list of CUDA devices to operate on
+    at::Device device_;
+
+    // The start CUDA event of NCCL operator tracking this work item. These
+    // start CUDA events are needed by desync debugging if enabled.
+    std::shared_ptr ncclStartEvent_;
+
+    // The end CUDA event of NCCL operator tracking this work item.
+    std::shared_ptr ncclEndEvent_;
+
+    // The NCCL communicator used for this work item.
+    std::shared_ptr ncclComm_;
+
+    // Tensors used for barrier op
+    at::Tensor barrierTensor_;
+
+    // Clone of blockingWait_ from ProcessGroupNCCL.
+    bool blockingWait_ = false;
+
+    // Clone of avoidRecordStreams_ from ProcessGroupNCCL.
+    bool avoidRecordStreams_ = false;
+
+    // Clone of opTimeout_ from ProcessGroupNCCL.
+    std::chrono::milliseconds opTimeout_;
+
+    // Ephemeral timeouts are owned by exactly one work,
+    // and reset after that work completes.
+    // There may be more than one ephemeral timeout active at the same time,
+    // and this variable is used to track the ownership of ephemeral timeout.
+    std::chrono::milliseconds ownedEphermeralTimeout_ =
+        std::chrono::milliseconds(0);
+
+    // Time point representing when the work started.
+    std::chrono::time_point workStartTime_;
+
+    // Record the collective sequential number.
+    uint64_t seq_;
+
+    // Indicates if the nccl start event has been updated to the store trace.
+    // This will be used by desync debug.
+    bool startTraceUpdated_{false};
+
+    // Record collective sizes for debug. We only record the size on the first
+    // device as multi-device per process is deprecated
+    size_t numelIn_ = -1;
+    size_t numelOut_ = -1;
+
+    // Wrapper method for the static checkForNCCLErrors which can be overridden
+    // for tests.
+    virtual std::exception_ptr checkForNCCLErrors();
+
+    friend std::ostream& operator<<(
+        std::ostream& output,
+        const WorkNCCL& workNCCL);
+
+   private:
+    // Helper function for synchronize
+    void synchronizeInternal(std::chrono::milliseconds timeout);
+
+    // Checks for NCCL errors and sets an appropriate exception_ptr.
+    void checkAndSetException();
+
+    // Just checks whether GPU execution has started, without modifying
+    // exception_ptr.
+    bool startedGPUExecutionInternal() const;
+
+    // Just checks whether GPU execution has completed, without modifying
+    // exception_ptr.
+    bool finishedGPUExecutionInternal() const;
+
+    // Reference to the store so that we can write aborted communicators
+    // to the store.
+    c10::intrusive_ptr store_;
+
+    // Store a reference to NCCL collective's outputs, used by result and to
+    // give a more descriptive message when representing the Work as a string.
+    std::shared_ptr> outputs_;
+
+    // TORCH_NCCL_AVOID_RECORD_STREAMS implementation helper.
+    // Stores references to participating non-output tensors (ie inputs,
+    // flattened intermediates).
+    // We'll clear this list in synchronizeStream, just after user-facing
+    // stream(s) are synced with the nccl work stream(s).
+    // By keeping these refs (as well as outputs_) alive until after the
+    // collective's work rejoins the user-facing streams, we achieve
+    // caching allocator safety without any recordStream calls.
+    // For in-place collectives, some refs stashed here may alias outputs_,
+    // but that doesn't do any harm.
+    std::shared_ptr> stashed_for_allocator_safety_;
+
+    // The future returned by getFuture.
+    c10::intrusive_ptr future_;
+
+    bool timingEnabled_;
+    // unique id used to tell the trace buffer that this
+    // work has completed
+    std::optional trace_id_;
+    DebugLevel distDebugLevel_;
+    friend class ProcessGroupNCCL;
+  };
+
+  class CUDAEventCache {
+   public:
+    CUDAEventCache();
+    std::shared_ptr create(bool timing);
+    static CUDAEventCache& get();
+
+   private:
+    std::mutex cacheMutex_;
+    // NOTE: We intentionaly store raw pointers so that
+    // we do not attempt to destroy the event objects on process exit,
+    // because cuda may be gone.
+    std::vector
+        eventsArray_[2]; // 0 for timing=false, 1 for timing=true
+  };
+
+  struct Options : Backend::Options {
+    // NOTE: timeout in ProcessGroupNCCL::Options denote the timeout for
+    // operations. This is only used when blockingWait_ is enabled.
+    explicit Options(bool is_high_priority_stream = false);
+
+    // return intrusive_ptr of the object
+    static c10::intrusive_ptr create(
+        bool is_high_priority_stream = false) {
+      return c10::make_intrusive(is_high_priority_stream);
+    }
+
+    // Schedule NCCL operations on high priority CUDA streams
+    bool is_high_priority_stream;
+
+#ifdef NCCL_HAS_COMM_NONBLOCKING
+    // Configure ranks
+    ncclConfig_t config = NCCL_CONFIG_INITIALIZER;
+#endif
+
+    // Optional "parent" backend and color to create communicators from
+    // via `ncclCommSplit`
+    std::shared_ptr split_from;
+    int64_t split_color{0};
+    std::vector global_ranks_in_group;
+    std::string group_name;
+  };
+
+  // If you wish to create multiple process groups, each with a potentially
+  // different rank and size, you can do so by passing a new store instance
+  // to each one. If you have only a single store object, you can
+  // use the `c10d::PrefixStore` to derive scoped instances.
+  // This is also what the Python API in torch.distributed does.
+  //
+  // The process group instance keeps a reference to the store because
+  // it may be used long after the constructor runs. In fact, the constructor
+  // doesn't create any NCCL communicators. A single NCCL communicator can
+  // only be used on a specific set of devices, and are therefore created
+  // on-demand when a collective runs. If another collective is executed later,
+  // against a different set of devices, the process group creates another NCCL
+  // communicator. These NCCL communicators are cached and reused if possible.
+  //
+  ProcessGroupNCCL(
+      const c10::intrusive_ptr& store,
+      int rank,
+      int size,
+      c10::intrusive_ptr options = Options::create());
+
+  // This constructor includes the deprecated `groupName` argument.
+  // If you have existing code that uses the `groupName`, you can replace
+  // it by specifying a `c10d::PrefixStore(groupName, store)` for store.
+  C10_DEPRECATED ProcessGroupNCCL(
+      const c10::intrusive_ptr& store,
+      int rank,
+      int size,
+      const std::string& groupName,
+      c10::intrusive_ptr options = Options::create())
+      : ProcessGroupNCCL(store, rank, size, options) {}
+
+  ~ProcessGroupNCCL() override;
+
+  // This function returns a local uid for ProcessGroupNCCL.
+  uint64_t getUid() {
+    return static_cast(local_id_);
+  }
+
+  c10::intrusive_ptr getOptions() {
+    return options_;
+  }
+
+  const std::string getBackendName() const override {
+    return std::string(NCCL_BACKEND_NAME);
+  }
+
+  bool supportsSplitting() const override {
+    return true;
+  }
+
+  void startCoalescing() override;
+
+  c10::intrusive_ptr endCoalescing() override;
+
+  // For specifying a composite optype, such as ALLGATHER and REDUCE_SCATTER
+  c10::intrusive_ptr endCoalescing(OpType optype);
+
+  c10::intrusive_ptr broadcast(
+      std::vector& tensors,
+      const BroadcastOptions& opts = BroadcastOptions()) override;
+
+  c10::intrusive_ptr _broadcast_oop(
+      at::Tensor& outputTensors,
+      at::Tensor& inputTensors,
+      const BroadcastOptions& opts = BroadcastOptions());
+
+  c10::intrusive_ptr allreduce_sparse(
+      std::vector& tensors,
+      const AllreduceOptions& opts = AllreduceOptions()) override;
+
+  c10::intrusive_ptr allreduce(
+      std::vector& tensors,
+      const AllreduceOptions& opts = AllreduceOptions()) override;
+
+  c10::intrusive_ptr allreduce_coalesced(
+      std::vector& tensors,
+      const AllreduceCoalescedOptions& opts =
+          AllreduceCoalescedOptions()) override;
+
+  c10::intrusive_ptr reduce(
+      std::vector& tensors,
+      const ReduceOptions& opts = ReduceOptions()) override;
+
+  c10::intrusive_ptr _reduce_oop(
+      at::Tensor& outputTensors,
+      at::Tensor& inputTensors,
+      const ReduceOptions& opts = ReduceOptions());
+
+  c10::intrusive_ptr allgather(
+      std::vector>& outputTensors,
+      std::vector& inputTensors,
+      const AllgatherOptions& opts = AllgatherOptions()) override;
+
+  c10::intrusive_ptr _allgather_base(
+      at::Tensor& outputbuffer,
+      at::Tensor& inputbuffer,
+      const AllgatherOptions& opts = AllgatherOptions()) override;
+
+  c10::intrusive_ptr allgather_coalesced(
+      std::vector>& outputTensorLists,
+      std::vector& inputTensors,
+      const AllgatherOptions& opts = AllgatherOptions()) override;
+
+  c10::intrusive_ptr allgather_into_tensor_coalesced(
+      std::vector& outputs,
+      std::vector& inputs,
+      const AllgatherOptions& opts = AllgatherOptions()) override;
+
+  c10::intrusive_ptr reduce_scatter(
+      std::vector& outputTensors,
+      std::vector>& inputTensors,
+      const ReduceScatterOptions& opts = ReduceScatterOptions()) override;
+
+  c10::intrusive_ptr _reduce_scatter_base(
+      at::Tensor& outputTensor,
+      at::Tensor& inputTensor,
+      const ReduceScatterOptions& opts = ReduceScatterOptions()) override;
+
+  c10::intrusive_ptr reduce_scatter_tensor_coalesced(
+      std::vector& outputs,
+      std::vector& inputs,
+      const ReduceScatterOptions& opts = ReduceScatterOptions()) override;
+
+  c10::intrusive_ptr barrier(
+      const BarrierOptions& opts = BarrierOptions()) override;
+
+  c10::intrusive_ptr alltoall_base(
+      at::Tensor& outputTensor,
+      at::Tensor& inputTensor,
+      std::vector& outputSplitSizes,
+      std::vector& inputSplitSizes,
+      const AllToAllOptions& opts = AllToAllOptions()) override;
+
+  c10::intrusive_ptr alltoall(
+      std::vector& outputTensors,
+      std::vector& inputTensors,
+      const AllToAllOptions& opts = AllToAllOptions()) override;
+
+  c10::intrusive_ptr send(
+      std::vector& tensors,
+      int dstRank,
+      int tag) override;
+
+  c10::intrusive_ptr recv(
+      std::vector& tensors,
+      int srcRank,
+      int tag) override;
+
+  void groupStart();
+
+  void groupEnd();
+
+  void groupEndNonblocking(std::shared_ptr comm);
+
+  c10::intrusive_ptr gather(
+      std::vector>& outputTensors,
+      std::vector& inputTensors,
+      const GatherOptions& opts = GatherOptions()) override;
+
+  c10::intrusive_ptr scatter(
+      std::vector& outputTensors,
+      std::vector>& inputTensors,
+      const ScatterOptions& opts = ScatterOptions()) override;
+
+  // Unsupported Ops
+  c10::intrusive_ptr recvAnysource(
+      std::vector& tensors,
+      int tag) override;
+
+  // Agrees on an initial sequence number for the whole group by having rank 0
+  // create it and broadcast it to other ranks using the store.
+  void setSequenceNumberForGroup() override;
+
+  // Retrieves the current sequence number for the whole group, which should be
+  // in sync. If the returned number is not consistent across the group, it
+  // may indicate that there is some sort of collective desynchronization.
+  uint64_t getSequenceNumberForGroup() override;
+
+  // Return the total number of splits the communicators held by this process
+  // group have performed.  Counts ncclCommCreateFromRanks() for ncclx v2.21.5+
+  uint64_t getCommSplitCounter() const;
+
+  void registerOnCompletionHook(
+      std::function)>&& hook) override;
+  void waitForPendingWorks() override;
+
+  void enableCollectivesTiming() override;
+
+  // Helper function for iteratively aborting communicators in the provided map
+  void abortCommsFromMap(
+      std::unordered_map>& ncclCommsMap,
+      std::optional abortReason);
+
+  c10::intrusive_ptr initIntraNodeComm();
+
+  // Provides an API to abort the ProcessGroup (similar to ncclCommAbort)
+  // instead of relying on ProcessGroupNCCL destructor.
+  // return true if abort is successful, otherwise false
+  bool abort(std::optional abortReason = std::nullopt);
+
+  void shutdown(std::optional reason = std::nullopt);
+
+  void eagerConnectSingleDevice(at::Device device) override;
+
+  void performNocolorSplit(at::Device device);
+
+  // This method adds a temporary extension for the timeout period,
+  // applying to all collectives between the calling of this API and
+  // the completion of the first collective on the GPU. While this feature
+  // provides flexibility in specific scenarios, it introduces statefulness
+  // to timeout setting. Therefore, it is advisable to use this API sparingly
+  // and consider alternative approaches, such as directly setting the timeout
+  // or utilizing a barrier collective (one can set any timeout to the barrier),
+  // whenever feasible.
+  void addEphemeralTimeout(const std::chrono::milliseconds& timeout);
+
+  // This function is only intended for testing purposes because we don't
+  // want to expose the `WorkNCCL` via pybind. It verifies whether the
+  // `opTimeout_` of the provided WorkNCCL instance is the same as the specified
+  // timeout.
+  bool verifyWorkTimeoutForTest(
+      const c10::intrusive_ptr work,
+      const std::chrono::milliseconds& timeout);
+
+ protected:
+  // Helper that broadcasts nccl unique ID to all ranks through the store
+  void broadcastUniqueNCCLID(
+      ncclUniqueId* ncclID,
+      bool isSingleP2POp,
+      const std::string& devicesKey,
+      int p2pRank);
+
+  // Helper that either looks up the cached NCCL communicators or creates
+  // a new set of NCCL communicators as a cache entry
+  std::shared_ptr getNCCLComm(
+      const std::string& deviceKey,
+      at::Device& device,
+      OpType opType,
+      int p2pRank = 0,
+      bool isSendRecvSelf = false);
+
+  // Wrapper method which can be overridden for tests.
+  virtual std::exception_ptr checkForNCCLErrors(
+      std::shared_ptr& ncclComm);
+
+  // Ensure thaht if record is True, the work obj will be enqueued via
+  // workEnqueue
+  virtual c10::intrusive_ptr initWork(
+      at::Device& device,
+      int rank,
+      OpType opType,
+      const char* profilingTitle = nullptr,
+      const std::vector& inputs = {},
+      const std::vector& outputs = {},
+      bool record = false);
+
+  // In the timeout case and we will dump debug info such as the NCCL flight
+  // recorder to storage. Down the road, if we have more complicated or blocking
+  // operations, we might need to use a side thread to do it.
+  bool dumpDebuggingInfo();
+
+ private:
+  int globalRankStart;
+  int globalRankStride;
+
+  // Helper that encapsulates work shared across all collective communication
+  // primitives.  The callbacks have the following signatures:
+  //
+  //    ncclResult_t fn(at::Tensor& input, at::Tensor& output,
+  //                    ncclComm_t, at::cuda::CUDAStream&);
+  //    void {pre,post}(std::vector);
+  template 
+  c10::intrusive_ptr collective(
+      at::Tensor& input,
+      at::Tensor& output,
+      Fn fn,
+      OpType opType,
+      const char* profilingTitle = nullptr,
+      bool avoidRecordStreams = false,
+      bool nanCheck = true);
+
+  template 
+  c10::intrusive_ptr collective(
+      at::Tensor& input,
+      at::Tensor& output,
+      Fn fn,
+      PreProcess pre,
+      PostProcess post,
+      OpType opType,
+      const char* profilingTitle = nullptr,
+      bool avoidRecordStreams = false,
+      bool nanCheck = true);
+
+  template 
+  c10::intrusive_ptr collective(
+      std::vector& inputs,
+      std::vector& outputs,
+      Fn fn,
+      PreProcess pre,
+      PostProcess post,
+      OpType opType,
+      const char* profilingTitle = nullptr,
+      bool avoidRecordStreams = false,
+      bool nanCheck = true);
+
+  template 
+  c10::intrusive_ptr collectiveCoalesced(
+      std::vector& input,
+      std::vector& output,
+      Fn fn,
+      OpType opType,
+      const char* profilingTitle = nullptr,
+      bool avoidRecordStreams = false);
+
+  // Helper that encapsulates work shared across point-to-point communication
+  // primitives. It is the same structure as the helper used for collective
+  // communication primitives.
+  template 
+  c10::intrusive_ptr pointToPoint(
+      at::Tensor& tensor,
+      Fn fn,
+      int peer,
+      OpType opType,
+      const char* profilingTitle = nullptr);
+
+  template 
+  c10::intrusive_ptr pointToPoint(
+      at::Tensor& tensor,
+      Fn fn,
+      int peer,
+      OpType opType,
+      PreProcess pre,
+      PostProcess post,
+      const char* profilingTitle);
+
+  c10::intrusive_ptr allreduce_impl(
+      at::Tensor& tensor,
+      const AllreduceOptions& opts = AllreduceOptions());
+
+  // Checks for NCCL errors on each of the communicators and returns an
+  // appropriate exception_ptr (nullptr if no errors).
+  static std::exception_ptr checkForNCCLErrorsInternal(
+      std::shared_ptr& ncclComm);
+
+  // Function that runs as part of a separate thread and checks for errors on
+  // NCCL communicators. We need a separate thread to check for NCCL errors
+  // since we can't rely on the user calling certain methods like wait(),
+  // isCompleted() etc. to detect and remediate errors. In addition to this, we
+  // need a mechanism to safely abort and remove NCCL communicators from our
+  // cache. This can be done cleanly by having a thread for the ProcessGroupNCCL
+  // class. Attempting to modify the communicator cache from the WorkNCCL class
+  // might run into issues with object lifetime since the ProcessGroupNCCL
+  // object might get destroyed before the WorkNCCL object.
+  void ncclCommWatchdog();
+
+  // Return the CUDA device most likely associated with this backend.
+  // If we aren't bound to a specific device, there is no strict
+  // guarantee that this heuristic is the correct assignment of ranks
+  // to GPUs that Python layers use, but in practice it tends to be.
+  // Fortunately we don't rely on this for correctness of any tensor
+  // operations, just for ancillary uses like barriers.
+  at::Device guessDeviceForRank() const;
+
+  // Destroys initialized NCCL communicators in devNCCLComMap_ given by input
+  // key. Throws if there are no communicators to destroy. Also removes
+  // communicators from the cache and clears used device indices.
+  void destroyNCCLComms(const std::string& devNCCLCommMapKey);
+
+  // Watchdog's inside loop.
+  // Takes care of cleaning up completed work, and aborting upon failure or
+  // timeout.
+  void watchdogHandler();
+
+  void runHookLoop();
+
+  // Desync debug helper
+  void logWorkStart(WorkNCCL& work);
+
+  // Desync debug helper
+  void logWorkEnd(WorkNCCL& work);
+
+  // Generates a prefix that is unique to this process group and rank, for
+  // disambiguating logs
+  std::string createLogPrefix() const;
+
+  // Returns the unique prefix created in createLogPrefix
+  const std::string& logPrefix() const;
+
+  // Returns the global rank of the device. This function assumes that users
+  // always create a default global process group(PG) which includes all
+  // devices. It is called in the constructor of ProcessGroupNCCL, so it always
+  // return the rank_ of the the very first PG created, aka, default global PG.
+  const int& globalRank() const;
+
+  // Returns the global ranks of a PG.
+  const std::vector& groupRanks() const;
+
+  // Util function to assign timeout to each work.
+  void assignTimeoutToWork(
+      const c10::intrusive_ptr& work,
+      const c10::intrusive_ptr& option);
+
+ protected:
+  // Function that runs as part of a separate thread aside from watchdog
+  // thread because we need to check the heartbeat from watchdog thread
+  // so that when we get stuck in some NCCL/CUDA calls,
+  // we can dump the debugging information and abort the process.
+  virtual void heartbeatMonitor();
+
+  // Function that directly trigger std::abort so that the whole process
+  // gets terminated.
+  virtual void terminateProcess(std::string errMsg);
+
+  // A helper function to wait for a future to complete or timeout.
+  void waitForFutureOrTimeout(
+      std::future& fut,
+      const std::chrono::milliseconds& timeOutMilSec,
+      const std::string& futDescription,
+      bool throwException = false,
+      bool log = false);
+
+  // When watchdog timeout, this function will be called and return debug info
+  // for users. For now we only get information from retrieveDesyncReport.
+  // We are working on enabling more useful debug information for watchdog
+  // timeout.
+  virtual std::string getNCCLWatchdogDebugInfo();
+
+  std::string getNCCLWatchdogTimeoutErrorMsg(const std::string& extraMsg);
+
+  std::string getNCCLWatchdogTimeoutExitMsg(const std::string& exitReason);
+
+  static const int64_t kWatchdogThreadSleepMillis;
+
+  // The store is used to broadcast the NCCL unique ID of rank 0. This store
+  // comes with prefix and it is different across ProcessGroup NCCL instances
+  // (aka, different ProcessGroups).
+  c10::intrusive_ptr store_;
+
+  // Reference to the store without prefix so that keys are same across all
+  // ProcessGroup NCCL instances and (key, value) pairs written to the store are
+  // global.
+  c10::intrusive_ptr globalStore_;
+
+  bool storeError_{false};
+
+  // The lock which protects the write/read of
+  // ephemeralTimeoutActive_/ephemeralTimeoutInflight_.
+  // TODO(fduwjj): We need to have an audit on all mutexes we are adding here.
+  // And consolidate them if possible.
+  std::mutex mtxTimeoutExtension_;
+
+  // The ephemeral timeout added on top of existing timeout for works issued
+  // before first work finishes.
+  std::chrono::milliseconds ephemeralTimeoutActive_ =
+      std::chrono::milliseconds(0);
+
+  // The ephemeral timeout addition which has been already applied to work.
+  std::chrono::milliseconds ephemeralTimeoutInflight_ =
+      std::chrono::milliseconds(0);
+
+  const c10::intrusive_ptr options_;
+
+  // The number of NCCL communicators that have been created during
+  // the lifetime of this process group. This sequence number is
+  // used to scope keys used in the store.
+  uint64_t ncclCommCounter_{0};
+
+  // The store keys to trace the last NCCL collective kernel CUDA events - start
+  // event and end event respectively. These are used to do desync root cause
+  // analysis.
+  const std::string traceKeyStart_;
+  const std::string traceKeyEnd_;
+
+  // The NCCL communicator that the process group has cached.
+  //
+  // For collective operations:
+  // The key is a list of GPU devices that an operation is operating on
+  // The GPU devices are stored in a device sequence and the cache NCCL
+  // communicator is associated with this GPU device sequence
+  //
+  // e.g. If the process group op only uses device 0, then the value of
+  // the used device string stored (value of the hashmap) would be "0".
+  //
+  //      If the process group op uses device 0 - 7 and the each tensor of the
+  //      input tensor list is on device, 0, 1, 2, 3, 4, 5, 6, 7 separately,
+  //      then the value of the used device string (key) stored would be
+  //      "0,1,2,3,4,5,6,7"
+  //
+  //      If the process group op uses device 0 - 7 and the each tensor of the
+  //      input tensor list is on device, 0, 4, 5, 6, 7, 1, 2, 3 separately,
+  //      then the value of the used device string stored would be
+  //      "0,4,5,6,7,1,2,3"
+  //
+  //      Note that the order of the device for the tensor list matters.
+  //
+  // For point-to-point operations:
+  // The key is a string of my current rank and the peer process rank.
+  // e.g. If process 1 and process 2 are involved in a point-to-point
+  // communication, the key will be "1:2" on both processes. Note: this is for
+  // the scenario where there is only 1 GPU per process. When it comes to
+  // multiple GPUs per process, this part may need to redesigned.
+  // TODO: we probably need a separte map for P2P comms
+  std::unordered_map> devNCCLCommMap_;
+
+  // The NCCL communicators currently in process of being initialized.
+  std::unordered_map>
+      inInitializationCommMap_;
+
+  // Mutex to guard maps like devNCCLCommMap_.
+  std::mutex mutex_;
+
+  // Heartbeat of watchdog thread.
+  std::atomic_uint64_t heartbeat_;
+
+  // The time interval used for deciding whether there is no watchdog heartbeat.
+  int heartbeatTimeoutInSec_;
+
+  // timeout for the dump to finish.
+  int waitTimeoutDumpInMilSec_;
+
+  // Interval of check coordinated signals in ProcessGroupNCCL from other ranks
+  // e.g., trigger the dump of the debugging info for timeout when notified.
+  int coordCheckIntervalMilSec_;
+
+  // Size of ring buffer where we store NCCL Traces for debugging.
+  int ncclTraceBufferSize_;
+
+  // We gate the heartbeat monitor thread so that we can roll it out gradually.
+  std::atomic monitorThreadEnabled_;
+
+  // We gate the cudaEventCache so that we can roll it out gradually.
+  std::atomic cudaEventCacheEnabled_;
+
+  // Monitor thread which checks the heartbeat of Watchdog thread.
+  // If the monitor thread finds there is no heartbeat, it will dump debug info
+  // and then kill the watchdog thread to avoid hang.
+  std::thread ncclHeartbeatMonitorThread_;
+
+  // Watchdog thread which looks for errors on the cached NCCL communicators.
+  std::thread ncclCommWatchdogThread_;
+
+  std::thread onCompletionHookThread_;
+
+  // Whether or not we should terminate the watchdog and workCleanup threads.
+  std::atomic terminateProcessGroup_;
+
+  // Whether or not we should terminate the heartbeat monitoring threads.
+  std::atomic terminateHeartbeatMonitorThread_;
+
+  // Whether we are in the shutdown mode when we are trying to get debug info,
+  // such as desync report.
+  std::atomic collectiveDebugInfoMode_;
+
+  // Whether there are hooks pending to be fired
+  std::atomic hasPendingHooks_;
+
+  // This is the signal from watchdog threads to indicate whether the monitor
+  // thread should dump. Making it static so that it is accessiable from all the
+  // PGs. With this flag, monitor thread would dump debug info under any one of
+  // the three conditions:
+  //
+  // 1: watchdog thread of any PG detects a collective timeout.
+  // 2: timeout signal is received from other ranks through tcpstore.
+  // 3: current PG's watchdog heartbeat timeout occurs.
+  //
+  // Note that only the monitor thread from PG0 will dump the debug info for
+  // case one and two so that the debug info is only dumped once.
+  static std::atomic shouldDump_;
+
+  // Mutex to Guard workMetaList_
+  std::mutex workMetaListMutex_;
+
+  // Mutex to Guard monitorWakeUpCV_
+  std::mutex monitorMutex_;
+
+  bool writeDebugInfo_ = false;
+
+  // Condition Variable for watchdog thread sleep
+  std::condition_variable workMetaListCV_;
+
+  // Condition Variable for monitor thread to wake up early
+  std::condition_variable monitorWakeUpCV_;
+
+  // Vector to Store WorkNCCL pointers
+  std::list workMetaList_;
+
+  std::chrono::time_point lastWorkListUpdateTime_;
+
+  // Mutex to Guard workMetaList_
+  std::mutex completedWorkListMutex_;
+
+  // Condition Variable for watchdog thread sleep
+  std::condition_variable completedWorkListCV_;
+
+  std::list completedWorkList_;
+
+  // Add Work Pointer to workVector
+  void workEnqueue(c10::intrusive_ptr);
+
+  // The CUDA streams used by NCCL kernels
+  std::unordered_map ncclStreams_;
+
+  // The CUDA events used to sync NCCL streams
+  std::unordered_map ncclEvents_;
+
+  // Device Indexes used for all collectives in this group
+  std::set usedDeviceIdxs_;
+
+  // Flag to denote if a coalescing groupStart/groupEnd block is active
+  int coalescing_state_ = 0;
+
+  // Stores device indexes for all collectives run inside a coalescing block
+  at::Device coalescedDevice_ = at::Device("cuda");
+
+  // Stores communicators for all collectives run inside a coalescing block
+  std::shared_ptr coalescedComm_ = nullptr;
+
+  // map from the key: "group name + pg counter (ID)" to the
+  // unique NCCL ID count. This needs to be group and pg specific
+  //
+  // For each process group, we need a uniform unique NCCL ID counter to ensure
+  // that NCCL operation in this process group can be completed successfully.
+  // Since each process group ID belongs to a group name, the key to this map
+  // is a combination of group name and ProcessGroupNCCL ID.
+  static std::unordered_map pgUniqueNCCLIDCnt_;
+
+  // map from group name to the pg counter (ID) within that group
+  //
+  // For each group with the "group name" (which is the key), we need to
+  // keep track of a unique process group ID when creating a new
+  // ProcessGroupNCCL for this "group name". Therefore, the value of this
+  // map keeps the unique ProcessGroupNCCL's ID for a specific group with
+  // the "group name". The reason we need a per-group process group ID counter
+  // is that different group can have different ranks and we need ensure that
+  // each group has its own uniform process group ID for all its ranks.
+  static std::unordered_map processGroupCounterMap_;
+
+  // Whether or not wait() and synchronize() are blocking operations that wait
+  // for the operation to complete.
+  bool blockingWait_ = false;
+
+  // Whether or not to hook the cache allocator to register all allocated
+  // tensors
+  bool useTensorRegisterAllocatorHook_ = false;
+
+  // Whether or not the workCleanupThread is used to perform async error
+  // handling.
+  ErrorHandlingMode asyncErrorHandling_ = NoHandling;
+
+  // Whether or not to enable timeout root cause analysis.
+  bool desyncDebug_;
+
+  // Whether or not to dump debug info on exception including both watchdog
+  // timeout and nccl errors.
+  bool dumpOnTimeoutOrEx_;
+
+  // Whether or not to enable nan check for input tensors to collectives.
+  bool enableNanCheck_;
+
+  // Whether or not to print C++ stack traces to logs on unclean shutdown.
+  bool logCppStackOnUncleanShutdown_;
+
+  // Whether or not to create start CUDAEvent and enable timing for start
+  // and end events. Note that enableTiming_ is always true if desyncDebug_
+  // is set to true.
+  std::atomic enableTiming_;
+
+  // Flag to enable the print of hash value of input/output of collectives for
+  // verification.
+  std::atomic enableCollecticeHashDebug_;
+
+  // Whether or not TORCH_NCCL_AVOID_RECORD_STREAMS was set
+  bool avoidRecordStreams_ = false;
+
+  // Whether the NCCL watchdog should rethrow CUDA errors.
+  bool rethrowCUDAErrors_ = false;
+
+  // Set of communicators that this process group has aborted and their
+  // ncclUniqueId has been written to the store. We don't need a lock
+  // for this map since only the watchdog thread accesses this set. The
+  // set contains the string representation of ncclUniqueId.
+  std::unordered_set abortedComms_;
+
+  // The number of active ncclGroupStart() calls. This counter will be increased
+  // by 1 when ncclGroupStart() is called and decreased by 1 when ncclGroupEnd()
+  // is called.
+  static thread_local uint64_t ncclActiveGroupCounter_;
+
+  // Counting for the sequential number of NCCL collective call.
+  // (specifically, how many actual kernels we launched, which differs from
+  // op_id_ when coalescing is enabled)
+  uint64_t seqCollective_{0};
+
+  // Counting for the sequential number of NCCL P2P calls.
+  uint64_t seqP2P_{0};
+
+  // Incrementing counter for logical operations (collective or p2p) issued on
+  // the ProcessGroup
+  uint64_t op_id_{0};
+
+  std::exception_ptr watchDogException_ = nullptr;
+
+  // The number of ProcessGroupNCCL created on the current rank.
+  size_t local_id_;
+
+  std::string logPrefix_;
+
+  c10::intrusive_ptr intraNodeComm_;
+
+  // Number of devices on this node.
+  int localDeviceCount_{0};
+
+  std::shared_ptr pgStatus_ =
+      std::make_shared();
+};
+
+// Dumps the NCCL comm traces and additional information about the Process
+// Group.
+TORCH_API std::string dump_nccl_trace(
+    bool includeCollectives,
+    bool includeStackTraces,
+    bool onlyActive);
+
+// Dumps the NCCL comm traces and additional information about the Process
+// Group in JSON formatted string.
+// We don't include stack traces in JSON format as it is far too much data.
+TORCH_API std::string dump_nccl_trace_json(
+    bool includeCollectives,
+    bool onlyActive);
+
+// Gets a mutable reference to a global optional function.Heartbeat Monitor
+// will use this function to dump traces, if available. Inside fbcode, we
+// store a function here that uses an internal tool for process tracing
+TORCH_API std::optional<
+    std::function)>>&
+get_cpp_trace_dumper();
+
+// Similar to get_cpp_trace_dumper, this stores a function defined in
+// torch-python layer that lets us check whether the GIL can be acquired,
+// helpful for instrumenting in cases where a hang was observed.
+typedef bool (*gil_checker_t)();
+
+TORCH_API gil_checker_t& get_gil_checker();
+} // namespace c10d
+
+#endif // USE_C10D_NCCL
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupUCC.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupUCC.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..ab1e1e4c4899e3de0bac5bd1e9137af1c353ae43
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupUCC.hpp
@@ -0,0 +1,353 @@
+#pragma once
+
+#ifdef USE_C10D_UCC
+
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#ifdef USE_CUDA
+#include 
+#include 
+#endif
+
+namespace c10d {
+
+#define TORCH_UCC_DEVICE_NOT_SET -2
+
+#ifdef USE_CUDA
+#define SAVE_TENSORS(_TENSORS, _DATA)                       \
+  do {                                                      \
+    if ((_TENSORS)[0].device().is_cuda()) {                 \
+      for (const auto i : c10::irange((_TENSORS).size())) { \
+        c10::cuda::CUDACachingAllocator::recordStream(      \
+            (_TENSORS)[i].storage().data_ptr(), (*stream)); \
+      }                                                     \
+    } else {                                                \
+      (_DATA) = (_TENSORS);                                 \
+    }                                                       \
+  } while (0)
+
+#else
+#define SAVE_TENSORS(_TENSORS, _DATA) (_DATA) = (_TENSORS);
+#endif
+
+constexpr const char* UCC_BACKEND_NAME = "ucc";
+
+struct event_pool_t {
+#ifdef USE_CUDA
+  std::queue> event_pool;
+#endif
+  std::mutex event_pool_mutex;
+};
+
+class Comm;
+
+// UCC does not support multiple CUDA devices per process.
+class TORCH_API ProcessGroupUCC : public Backend {
+ private:
+  void set_timeout(ucc_coll_args_t& args);
+
+ public:
+  class WorkData {
+   public:
+    std::vector src;
+    std::vector dst;
+    std::vector flat;
+    WorkData() {}
+    virtual ~WorkData() = default;
+  };
+  class AlltoallWorkData : public WorkData {
+   public:
+    AlltoallWorkData(int size)
+        : send_lengths(size),
+          send_offsets(size),
+          recv_lengths(size),
+          recv_offsets(size) {}
+    std::vector send_lengths;
+    std::vector send_offsets;
+    std::vector recv_lengths;
+    std::vector recv_offsets;
+  };
+
+  class AllgathervWorkData : public WorkData {
+   public:
+    AllgathervWorkData(int size) : recv_lengths(size), recv_offsets(size) {}
+    std::vector recv_lengths;
+    std::vector recv_offsets;
+  };
+
+  class ScattervWorkData : public WorkData {
+   public:
+    ScattervWorkData(int size) : send_lengths(size), send_offsets(size) {}
+    std::vector send_lengths;
+    std::vector send_offsets;
+  };
+
+  class ProgressEntry {
+    friend class ProcessGroupUCC;
+    friend class Comm;
+
+   public:
+    ProgressEntry(CommBase* comm, ucc_coll_req_h request)
+        : status_(UCC_INPROGRESS), comm_(comm), request_(request) {}
+    // Finalizes UCC status or exception of collective request.
+    void finalize(std::exception_ptr eptr = nullptr);
+    ucc_status_t status_;
+    CommBase* comm_;
+    ucc_coll_req_h request_;
+    std::unique_ptr data;
+    c10::intrusive_ptr future_;
+    std::exception_ptr eptr_;
+  };
+
+  class WorkUCC : public Work {
+    friend class ProcessGroupUCC;
+    friend class Comm;
+
+   public:
+    WorkUCC(
+        OpType opType,
+        uint64_t seq,
+        const char* prof_title,
+        const std::optional>& inputs,
+        const c10::intrusive_ptr& logger)
+        : Work(-1, opType, prof_title, inputs), logger_(logger), seq_(seq) {}
+    ~WorkUCC();
+    void setException();
+    void setAndThrowException();
+    bool isCompleted() override;
+    bool isSuccess() const override;
+    bool wait(std::chrono::milliseconds timeout = kUnsetTimeout) override;
+    c10::intrusive_ptr getFuture() override;
+    std::vector result() override;
+    int sourceRank() const override;
+#ifdef USE_CUDA
+    std::unique_ptr fence = nullptr;
+    event_pool_t* ep = nullptr;
+#endif
+    int sourceRank_;
+
+   protected:
+    std::shared_ptr entry_;
+    c10::intrusive_ptr logger_;
+    uint64_t seq_;
+
+   private:
+    // The future returned by getFuture.
+    c10::intrusive_ptr future_;
+    // Store a reference to collective's outputs, used by result
+    std::shared_ptr> outputs_;
+  };
+
+  explicit ProcessGroupUCC(
+      const c10::intrusive_ptr& store,
+      int rank = -1,
+      int size = -1,
+      std::chrono::duration timeout = kBackendDefaultTimeout);
+
+  void initComm(c10::Device dev);
+
+  ~ProcessGroupUCC() override;
+
+  const std::string getBackendName() const override {
+    return std::string(UCC_BACKEND_NAME);
+  }
+
+#ifdef USE_CUDA
+  std::unique_ptr getPooledEvent();
+#endif
+
+  // Performs a health check by initializing dummy UCC & UCX communicators and
+  // then destroying them. This will help indicate and signal any
+  // UCC/UCX-related issues prior to the first collective. The actual
+  // initialization and subsequent destruction is ran on a separate thread and
+  // the main thread is signalled about timeouts/errors to report to the
+  // application.
+  void runHealthCheck();
+
+  template 
+  c10::intrusive_ptr collective_post(
+      OpType opType,
+      PreProcess preproc,
+      PostProcess postproc,
+      ucc_coll_args_t& coll,
+      std::unique_ptr data,
+      c10::Device dev,
+      std::vector& inputTensors,
+      std::vector& outputTensors,
+      const char* prof_title);
+
+  c10::intrusive_ptr broadcast(
+      std::vector& data,
+      const BroadcastOptions& opts = BroadcastOptions()) override;
+
+  c10::intrusive_ptr allreduce(
+      std::vector& tensors,
+      const AllreduceOptions& opts = AllreduceOptions()) override;
+
+  c10::intrusive_ptr allreduce_coalesced(
+      std::vector& tensors,
+      const AllreduceCoalescedOptions& opts =
+          AllreduceCoalescedOptions()) override;
+
+  c10::intrusive_ptr reduce(
+      std::vector& tensors,
+      const ReduceOptions& opts = ReduceOptions()) override;
+
+  c10::intrusive_ptr allgather(
+      std::vector>& outputTensors,
+      std::vector& inputTensors,
+      const AllgatherOptions& opts = AllgatherOptions()) override;
+
+  c10::intrusive_ptr _allgather_base(
+      at::Tensor& outputBuffer,
+      at::Tensor& inputBuffer,
+      const AllgatherOptions& opts = AllgatherOptions()) override;
+
+  c10::intrusive_ptr barrier(
+      const BarrierOptions& opts = BarrierOptions()) override;
+
+  c10::intrusive_ptr gather(
+      std::vector>& outputTensors,
+      std::vector& inputTensors,
+      const GatherOptions& opts = GatherOptions()) override;
+
+  c10::intrusive_ptr scatter(
+      std::vector& outputTensors,
+      std::vector>& inputTensors,
+      const ScatterOptions& opts = ScatterOptions()) override;
+
+  c10::intrusive_ptr reduce_scatter(
+      std::vector& outputTensors,
+      std::vector>& inputTensors,
+      const ReduceScatterOptions& opts = ReduceScatterOptions()) override;
+
+  c10::intrusive_ptr alltoall_base(
+      at::Tensor& outputTensor,
+      at::Tensor& inputTensor,
+      std::vector& outputSplitSizes,
+      std::vector& inputSplitSizes,
+      const AllToAllOptions& opts = AllToAllOptions()) override;
+
+  c10::intrusive_ptr alltoall(
+      std::vector& outputTensors,
+      std::vector& inputTensors,
+      const AllToAllOptions& opts = AllToAllOptions()) override;
+
+  c10::intrusive_ptr send(
+      std::vector& tensors,
+      int dstRank,
+      int tag) override;
+
+  c10::intrusive_ptr recv(
+      std::vector& tensors,
+      int srcRank,
+      int tag) override;
+
+  // Counting for the sequential number of UCC collective_post call.
+  uint64_t seq_{0};
+
+  // Agrees on an initial sequence number for the whole group by having rank 0
+  // create it and broadcast it to other ranks using the store.
+  void setSequenceNumberForGroup() override;
+
+  // Retrieves the current sequence number for the whole group, which should be
+  // in sync. If the returned number is not consistent across the group, it
+  // may indicate that there is some sort of collective desynchronization.
+  uint64_t getSequenceNumberForGroup() override;
+
+  static c10::intrusive_ptr createProcessGroupUCC(
+      const c10::intrusive_ptr<::c10d::Store>& store,
+      int rank,
+      int size,
+      const std::chrono::duration& timeout);
+
+ protected:
+  const std::chrono::duration timeout_;
+  std::shared_ptr oob;
+  std::shared_ptr comm = {nullptr};
+  uint32_t comm_id;
+  ucc_team_h team{nullptr};
+  ucc_ee_h cuda_ee{nullptr};
+  ucc_ee_h cuda_ee_p2p[2]{nullptr, nullptr};
+
+#ifdef USE_CUDA
+  std::unique_ptr stream = nullptr;
+  std::unique_ptr stream_p2p[2] = {nullptr, nullptr};
+  event_pool_t ep;
+#endif
+  c10::intrusive_ptr logger;
+};
+
+class Comm {
+  c10::intrusive_ptr logger;
+  std::shared_ptr oob;
+  CommUCC ucc_comm;
+  std::mutex mutex;
+  std::thread progress_thread;
+  std::condition_variable queue_produce_cv;
+  std::condition_variable queue_consume_cv;
+  std::deque> progress_queue;
+  bool stop_progress_loop;
+  bool collective_inprogress;
+  torch_ucc_phase_t finalize_phase;
+
+ public:
+  c10::DeviceIndex cuda_device_index;
+  Comm(
+      const c10::intrusive_ptr& logger,
+      std::shared_ptr oob,
+      c10::Device dev,
+      bool is_health_check);
+
+  ~Comm();
+
+  void ucc_create_team(
+      ucc_team_h& team,
+      std::shared_ptr oob);
+
+  void ucc_destroy_team(ucc_team_h& team);
+
+  c10::intrusive_ptr enqueue_p2p(
+      OpType opType,
+      ucc_coll_req_h request,
+      const char* prof_title);
+
+#ifdef USE_CUDA
+  void enqueue_cuda_collective(
+      std::unique_ptr data,
+      c10::intrusive_ptr work,
+      ucc_coll_args_t& coll,
+      ucc_team_h team,
+      ucc_ee_h ee);
+#endif
+
+  void enqueue_collective(
+      std::unique_ptr data,
+      c10::intrusive_ptr work,
+      ucc_coll_args_t& coll,
+      ucc_team_h team);
+
+  static std::shared_ptr get_comm(
+      uint32_t& id,
+      c10::Device dev,
+      std::shared_ptr oob,
+      const c10::intrusive_ptr& logger,
+      bool is_health_check = false);
+
+  void progress_loop();
+};
+
+} // namespace c10d
+
+#endif // USE_C10D_UCC
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupWrapper.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupWrapper.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..50c0bfca921c537dd65274e2e4be63a9f4a90923
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupWrapper.hpp
@@ -0,0 +1,140 @@
+#pragma once
+
+#ifdef USE_C10D_GLOO
+
+#include 
+#include 
+#include 
+
+namespace c10d {
+
+class TORCH_API ProcessGroupWrapper : public Backend {
+ public:
+  explicit ProcessGroupWrapper(
+      const c10::intrusive_ptr& backend,
+      c10::intrusive_ptr glooBackend);
+
+  const std::string getBackendName() const override;
+
+  c10::intrusive_ptr broadcast(
+      std::vector& data,
+      const BroadcastOptions& opts = BroadcastOptions()) override;
+
+  c10::intrusive_ptr allreduce(
+      std::vector& data,
+      const AllreduceOptions& opts = AllreduceOptions()) override;
+
+  c10::intrusive_ptr allreduce_coalesced(
+      std::vector& tensors,
+      const AllreduceCoalescedOptions& opts =
+          AllreduceCoalescedOptions()) override;
+
+  c10::intrusive_ptr reduce(
+      std::vector& tensors,
+      const ReduceOptions& opts = ReduceOptions()) override;
+
+  c10::intrusive_ptr allgather(
+      std::vector>& outputTensors,
+      std::vector& inputTensors,
+      const AllgatherOptions& opts = AllgatherOptions()) override;
+
+  c10::intrusive_ptr _allgather_base(
+      at::Tensor& outputBuffer,
+      at::Tensor& inputBuffer,
+      const AllgatherOptions& opts = AllgatherOptions()) override;
+
+  // This function is deprecated and will be moved out of ProcessGroup to comms:
+  // * do not add dependencies on this function,
+  // * do not implement it in your ProcessGroup, implement _allgather_base
+  //   instead.
+  c10::intrusive_ptr allgather_coalesced(
+      std::vector>& outputTensorLists,
+      std::vector& inputTensors,
+      const AllgatherOptions& opts = AllgatherOptions()) override;
+
+  c10::intrusive_ptr gather(
+      std::vector>& outputTensors,
+      std::vector& inputTensors,
+      const GatherOptions& opts = GatherOptions()) override;
+
+  c10::intrusive_ptr scatter(
+      std::vector& outputTensors,
+      std::vector>& inputTensors,
+      const ScatterOptions& opts = ScatterOptions()) override;
+
+  c10::intrusive_ptr reduce_scatter(
+      std::vector& outputTensors,
+      std::vector>& inputTensors,
+      const ReduceScatterOptions& opts = ReduceScatterOptions()) override;
+
+  c10::intrusive_ptr alltoall_base(
+      at::Tensor& outputTensor,
+      at::Tensor& inputTensor,
+      std::vector& outputSplitSizes,
+      std::vector& inputSplitSizes,
+      const AllToAllOptions& opts = AllToAllOptions()) override;
+
+  c10::intrusive_ptr alltoall(
+      std::vector& outputTensors,
+      std::vector& inputTensors,
+      const AllToAllOptions& opts = AllToAllOptions()) override;
+
+  void monitoredBarrier(const BarrierOptions& opts, bool waitAllRanks = false)
+      override;
+
+  // Agrees on an initial sequence number for the whole group by having rank 0
+  // create it and broadcast it to other ranks using the store. Only implemented
+  // for GLOO and NCCL backends currently.
+  // dont implement this
+  void setSequenceNumberForGroup() override;
+
+  // Retrieves the current sequence number for the whole group, which should be
+  // in sync. If the returned number is not consistent across the group, it
+  // may indicate that there is some sort of collective desynchronization.
+  uint64_t getSequenceNumberForGroup() override; // just call underlying
+
+  c10::intrusive_ptr send(
+      std::vector& tensors,
+      int dstRank,
+      int tag) override;
+
+  c10::intrusive_ptr recv(
+      std::vector& tensors,
+      int srcRank,
+      int tag) override;
+
+  c10::intrusive_ptr recvAnysource(
+      std::vector& tensors,
+      int tag) override;
+
+  c10::intrusive_ptr barrier(
+      const BarrierOptions& opts = BarrierOptions()) override;
+
+  c10::intrusive_ptr _reduce_scatter_base(
+      at::Tensor& outputBuffer,
+      at::Tensor& inputBuffer,
+      const ReduceScatterOptions& opts) override;
+
+  void startCoalescing() override;
+
+  c10::intrusive_ptr endCoalescing() override;
+
+  c10::intrusive_ptr getWrappedPg() const;
+
+ private:
+  // Underlying process group that actual application collectives will be
+  // dispatched to
+  c10::intrusive_ptr backend_;
+  // Gloo process group responsible for internal coordination such as monitored
+  // barrier, sequence number checking, collective fingerprint collecting.
+  c10::intrusive_ptr glooBackend_;
+  // Conducts several checks to ensure that the underlying collective is well
+  // formed with the goal of notifying the user about incorrect collective use
+  // in the application.
+  void runCollectiveChecks(
+      OpType op_type,
+      const std::vector& tensors);
+};
+} // namespace c10d
+
+#endif // USE_C10D_GLOO
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/PyProcessGroup.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/PyProcessGroup.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..265c78f1b78cf9a59bd8400581e71912969c2890
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/PyProcessGroup.hpp
@@ -0,0 +1,249 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+namespace c10d {
+
+// PyProcessGroup is a pybind11 trampoline class to allow a Python
+// class to inherit from torch.distributed.ProcessGroup
+class PyProcessGroup : public ProcessGroup {
+ public:
+  // PyWork is a pybind11 trampoline class to allow a Python
+  // class to inherit from torch.distributed.Work
+  class TORCH_PYTHON_API PyWork : public Work {
+   public:
+    PyWork() = default;
+
+    bool wait(std::chrono::milliseconds timeout = kNoTimeout) override {
+      PYBIND11_OVERRIDE(
+          bool, /* Return type */
+          Work, /* Parent class */
+          wait, /* Name of function in C++ */
+          timeout);
+    }
+
+    c10::intrusive_ptr getFuture() override {
+      // We cannot use PYBIND11_OVERRIDE because:
+      // 1. We have to >MANUALLY< unwrap the PyFutureWrapper and
+      // 2. The python name is get_future
+      pybind11::gil_scoped_acquire gil;
+      auto override =
+          pybind11::get_override(static_cast(this), "get_future");
+
+      if (override) {
+        py::object o = override();
+        auto futWrapper =
+            o.cast>();
+        return futWrapper->fut;
+      }
+
+      return Work::getFuture();
+    }
+
+    // Take a reference of the corresponding py::object.
+    // With functional collectives, ownership of work objects is generally
+    // transferred to C++. For pure C++ work objects, it is sufficient to
+    // transfer the ownership of work object. For user-defined work objects in
+    // Python, it is necessary to keep the corresponding py::object alive in
+    // addition to ensure that the user-defined methods can be executed.
+    void ref_py_object() {
+      py_obj_ = py::cast(this);
+    }
+
+   private:
+    py::object py_obj_;
+  };
+
+  using ProcessGroup::ProcessGroup;
+
+  const std::string getBackendName() const override {
+    PYBIND11_OVERRIDE_PURE(
+        std::string, /* Return type */
+        ProcessGroup, /* Parent class */
+        getBackendName, /* Name of function in C++ */
+    );
+  }
+
+  c10::intrusive_ptr allgather(
+      std::vector>& outputTensors,
+      std::vector& inputTensors,
+      const AllgatherOptions& opts = AllgatherOptions()) override {
+    PYBIND11_OVERRIDE(
+        c10::intrusive_ptr, /* Return type */
+        ProcessGroup, /* Parent class */
+        allgather, /* Name of function in C++ */
+        outputTensors,
+        inputTensors,
+        opts);
+  }
+
+  c10::intrusive_ptr allgather_into_tensor_coalesced(
+      std::vector& outputTensors,
+      std::vector& inputTensors,
+      const AllgatherOptions& opts = AllgatherOptions()) override {
+    PYBIND11_OVERRIDE(
+        c10::intrusive_ptr, /* Return type */
+        ProcessGroup, /* Parent class */
+        allgather_into_tensor_coalesced, /* Name of function in C++ */
+        outputTensors,
+        inputTensors,
+        opts);
+  }
+
+  c10::intrusive_ptr allreduce(
+      std::vector& tensors,
+      const AllreduceOptions& opts = AllreduceOptions()) override {
+    PYBIND11_OVERRIDE(
+        c10::intrusive_ptr, /* Return type */
+        ProcessGroup, /* Parent class */
+        allreduce, /* Name of function in C++ */
+        tensors,
+        opts);
+  }
+
+  c10::intrusive_ptr allreduce_coalesced(
+      std::vector& tensors,
+      const AllreduceCoalescedOptions& opts =
+          AllreduceCoalescedOptions()) override {
+    PYBIND11_OVERRIDE(
+        c10::intrusive_ptr, /* Return type */
+        ProcessGroup, /* Parent class */
+        allreduce_coalesced, /* Name of function in C++ */
+        tensors,
+        opts);
+  }
+
+  c10::intrusive_ptr alltoall_base(
+      at::Tensor& outputBuffer,
+      at::Tensor& inputBuffer,
+      std::vector& outputSplitSizes,
+      std::vector& inputSplitSizes,
+      const AllToAllOptions& opts = AllToAllOptions()) override {
+    PYBIND11_OVERRIDE(
+        c10::intrusive_ptr, /* Return type */
+        ProcessGroup, /* Parent class */
+        alltoall_base, /* Name of function in C++ */
+        outputBuffer,
+        inputBuffer,
+        outputSplitSizes,
+        inputSplitSizes,
+        opts);
+  }
+
+  c10::intrusive_ptr barrier(
+      const BarrierOptions& opts = BarrierOptions()) override {
+    PYBIND11_OVERRIDE(
+        c10::intrusive_ptr, /* Return type */
+        ProcessGroup, /* Parent class */
+        barrier, /* Name of function in C++ */
+        opts);
+  }
+
+  c10::intrusive_ptr broadcast(
+      std::vector& tensors,
+      const BroadcastOptions& opts = BroadcastOptions()) override {
+    PYBIND11_OVERRIDE(
+        c10::intrusive_ptr, /* Return type */
+        ProcessGroup, /* Parent class */
+        broadcast, /* Name of function in C++ */
+        tensors,
+        opts);
+  }
+
+  c10::intrusive_ptr reduce_scatter(
+      std::vector& outputTensors,
+      std::vector>& inputTensors,
+      const ReduceScatterOptions& opts = ReduceScatterOptions()) override {
+    PYBIND11_OVERRIDE(
+        c10::intrusive_ptr, /* Return type */
+        ProcessGroup, /* Parent class */
+        reduce_scatter, /* Name of function in C++ */
+        outputTensors,
+        inputTensors,
+        opts);
+  }
+
+  c10::intrusive_ptr reduce_scatter_tensor_coalesced(
+      std::vector& outputTensors,
+      std::vector& inputTensors,
+      const ReduceScatterOptions& opts = ReduceScatterOptions()) override {
+    PYBIND11_OVERRIDE(
+        c10::intrusive_ptr, /* Return type */
+        ProcessGroup, /* Parent class */
+        reduce_scatter_tensor_coalesced, /* Name of function in C++ */
+        outputTensors,
+        inputTensors,
+        opts);
+  }
+
+  c10::intrusive_ptr send(
+      std::vector& tensors,
+      int dstRank,
+      int tag) override {
+    PYBIND11_OVERRIDE(
+        c10::intrusive_ptr, /* Return type */
+        ProcessGroup, /* Parent class */
+        send, /* Name of function in C++ */
+        tensors,
+        dstRank,
+        tag);
+  }
+
+  c10::intrusive_ptr recv(
+      std::vector& tensors,
+      int srcRank,
+      int tag) override {
+    PYBIND11_OVERRIDE(
+        c10::intrusive_ptr, /* Return type */
+        ProcessGroup, /* Parent class */
+        recv, /* Name of function in C++ */
+        tensors,
+        srcRank,
+        tag);
+  }
+};
+
+class TORCH_PYTHON_API PythonOnCompletionHook {
+ public:
+  // Wraps a py::object hook and acquires Python GIL in dtor before
+  // destructing the hook object.
+  PythonOnCompletionHook(py::object hook) : hook_(std::move(hook)) {}
+
+  ~PythonOnCompletionHook() {
+    py::gil_scoped_acquire ag;
+    hook_.dec_ref();
+    // Explicitly set hook_ to nullptr to prevent py::object's dtor
+    // to decref on the PyObject again.
+    // See Note [Destructing py::object] in python_ivalue.h
+    hook_.ptr() = nullptr;
+  }
+
+  void operator()(const std::shared_ptr& workInfo) const {
+    std::exception_ptr eptr;
+    {
+      py::gil_scoped_acquire acquire;
+      try {
+        hook_(workInfo);
+      } catch (py::error_already_set& e) {
+        // py::error_already_set requires GIL to destruct, take
+        // special care.
+        eptr = std::make_exception_ptr(std::runtime_error(e.what()));
+        e.restore();
+        PyErr_Clear();
+      } catch (std::exception& e) {
+        eptr = std::current_exception();
+      }
+    }
+    // No more Python-related stuff at this point, i.e., this
+    // exception can be captured and handled by PG backend.
+    if (eptr)
+      std::rethrow_exception(eptr);
+  }
+
+ private:
+  py::object hook_;
+};
+
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/RankLocal.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/RankLocal.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..b3a649659af4c40b675f837e897443b7b3df6f01
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/RankLocal.hpp
@@ -0,0 +1,73 @@
+
+#pragma once
+
+#include 
+
+#include 
+
+namespace c10d {
+
+// `RankLocal` maintains a unique instance of T for each non-autograd thread.
+// For non-autograd threads, `RankLocal::get()` functions similar to
+// thread_local. For autograd threads, `RankLocal::get()` returns the
+// instance of T corresponding to the enqueuing non-autograd thread. The
+// mechanism allows for rank-specific context shared between forward and
+// backward. It works for both the one-rank-per-process and one-rank-per-thread
+// scenarios.
+//
+// NOTE: RankLocal doesn't make the underlying objects thread-safe.
+template 
+class RankLocal {
+ public:
+  RankLocal(const RankLocal&) = delete;
+  RankLocal& operator=(const RankLocal&) = delete;
+
+  static T& get() {
+    // Fast path: non-autograd threads can simply return
+    // the object reference cached in TLS.
+    if (cached_ != nullptr) {
+      return *cached_;
+    }
+    const auto node = torch::autograd::get_current_node();
+    auto fwd_thread_id = node == nullptr ? at::RecordFunction::currentThreadId()
+                                         : node->thread_id();
+    // Optimistically acquire the read lock first, since most likely we are in
+    // an autograd thread and the object has already been constructed.
+    {
+      std::shared_lock read_lock(lock_);
+      auto it = thread_id_to_rank_local_.find(fwd_thread_id);
+      if (it != thread_id_to_rank_local_.end()) {
+        // Cache for non-autograd threads
+        if (node == nullptr) {
+          cached_ = &it->second;
+        }
+        return it->second;
+      }
+    }
+
+    std::unique_lock write_lock(lock_);
+    auto [it, _] = thread_id_to_rank_local_.try_emplace(fwd_thread_id);
+    // Cache for non-autograd threads
+    if (node == nullptr) {
+      cached_ = &it->second;
+    }
+    return it->second;
+  }
+
+ private:
+  RankLocal(){};
+  thread_local static T* cached_;
+  static std::unordered_map thread_id_to_rank_local_;
+  static std::shared_mutex lock_;
+};
+
+template 
+thread_local T* RankLocal::cached_ = nullptr;
+
+template 
+std::unordered_map RankLocal::thread_id_to_rank_local_;
+
+template 
+std::shared_mutex RankLocal::lock_;
+
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/Store.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/Store.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..d18de830ff7f33b6410bcc91e8b3c567995aa904
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/Store.hpp
@@ -0,0 +1,128 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+namespace c10d {
+
+// callback function will be given arguments (std::optional oldValue,
+// std::optional newValue)
+using WatchKeyCallback =
+    std::function, std::optional)>;
+
+class TORCH_API Store : public torch::CustomClassHolder {
+ public:
+  static constexpr std::chrono::milliseconds kDefaultTimeout =
+      std::chrono::seconds(300);
+  static constexpr std::chrono::milliseconds kNoTimeout =
+      std::chrono::milliseconds::zero();
+
+  Store() : timeout_(kDefaultTimeout) {}
+
+  explicit Store(const std::chrono::milliseconds& timeout)
+      : timeout_(timeout) {}
+
+  Store(const Store&) = default;
+  Store(Store&&) noexcept = default;
+
+  ~Store() override = default;
+
+  void set(const std::string& key, const std::string& value);
+
+  virtual void set(
+      const std::string& key,
+      const std::vector& value) = 0;
+
+  std::string compareSet(
+      const std::string& key,
+      const std::string& currentValue,
+      const std::string& newValue);
+
+  virtual std::vector compareSet(
+      const std::string& key,
+      const std::vector& currentValue,
+      const std::vector& newValue) {
+    TORCH_INTERNAL_ASSERT(false, "Not implemented.");
+  }
+
+  std::string get_to_str(const std::string& key);
+
+  virtual std::vector get(const std::string& key) = 0;
+
+  virtual int64_t add(const std::string& key, int64_t value) = 0;
+
+  virtual bool deleteKey(const std::string& key) = 0;
+
+  virtual bool check(const std::vector& keys) = 0;
+
+  virtual int64_t getNumKeys() = 0;
+
+  virtual void wait(const std::vector& keys) = 0;
+
+  virtual void wait(
+      const std::vector& keys,
+      const std::chrono::milliseconds& timeout) = 0;
+
+  virtual const std::chrono::milliseconds& getTimeout() const noexcept;
+
+  virtual void setTimeout(const std::chrono::milliseconds& timeout);
+
+  // watchKey() is deprecated and no longer supported.
+  virtual void watchKey(
+      const std::string& /* unused */,
+      WatchKeyCallback /* unused */) {
+    TORCH_CHECK(false, "watchKey is deprecated, no implementation support it.");
+  }
+
+  virtual void append(
+      const std::string& key,
+      const std::vector& value);
+
+  virtual std::vector> multiGet(
+      const std::vector& keys);
+
+  virtual void multiSet(
+      const std::vector& keys,
+      const std::vector>& values);
+
+  // Returns true if this store support append, multiGet and multiSet
+  virtual bool hasExtendedApi() const;
+
+ protected:
+  std::chrono::milliseconds timeout_;
+};
+
+/*
+StoreTimeoutGuard is a RAII guard that will set the store timeout and restore it
+when it returns.
+*/
+class StoreTimeoutGuard {
+ public:
+  explicit StoreTimeoutGuard(
+      Store& store,
+      const std::chrono::milliseconds& timeout)
+      : store_(store), oldTimeout_(store.getTimeout()) {
+    store.setTimeout(timeout);
+  }
+
+  ~StoreTimeoutGuard() {
+    store_.setTimeout(oldTimeout_);
+  }
+
+  /* Disabling copy and move semantics */
+  StoreTimeoutGuard(const StoreTimeoutGuard&) = delete;
+  StoreTimeoutGuard& operator=(const StoreTimeoutGuard&) = delete;
+  StoreTimeoutGuard(StoreTimeoutGuard&&) = delete;
+  StoreTimeoutGuard& operator=(StoreTimeoutGuard&&) = delete;
+
+ private:
+  Store& store_;
+  std::chrono::milliseconds oldTimeout_{};
+};
+
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/SymmetricMemory.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/SymmetricMemory.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..9302822c78432cafec29c5a1e0bd0bc6e41028ff
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/SymmetricMemory.hpp
@@ -0,0 +1,161 @@
+#pragma once
+
+#include 
+#include 
+
+namespace c10d {
+namespace symmetric_memory {
+
+// SymmetricMemory represents symmetric allocations across a group of devices.
+// The allocations represented by a SymmetricMemory object are accessible by
+// all devices in the group. The class can be used for op-level custom
+// communication patterns (via the get_buffer APIs and the synchronization
+// primitives), as well as custom communication kernels (via the buffer and
+// signal_pad device pointers).
+//
+// To acquire a SymmetricMemory object, each rank first allocates
+// identical-sized memory via SymmetricMemoryAllocator::alloc(), then invokes
+// SymmetricMemoryAllocator::rendezvous() on the memory to establish the
+// association across peer buffers. The rendezvous is a one-time process, and
+// the mapping between a local memory memory and the associated SymmetricMemory
+// object is unique.
+//
+// NOTE [symmetric memory signal pad]
+// Signal pads are P2P-accessible memory regions designated for
+// synchronization. SymmetricMemory offers built-in synchronization primitives
+// such as barriers, put_signal, and wait_signal, which are all based on signal
+// pads. Users may utilize signal pads for their own synchronization logic,
+// provided that the signal pads remain zero-filled following successful
+// synchronization.
+//
+// NOTE [symmetric memory synchronization channel]
+// Synchronization channels allow users to use a single SymmetricMemory object
+// to perform isolated synchronizations on different streams. For example,
+// consider the case in which two barriers are issued on two streams for
+// different purposes. Without the concept of channels, we cannot guarantee the
+// correctness of the barriers since signals issued from barrier on stream A
+// can be received by the barrier on stream B. By specifying different channels
+// for these two barriers, they can operate correctly in parallel.
+class TORCH_API SymmetricMemory : public c10::intrusive_ptr_target {
+ public:
+  virtual ~SymmetricMemory() {}
+
+  virtual std::vector get_buffer_ptrs() = 0;
+  virtual std::vector get_signal_pad_ptrs() = 0;
+
+  // get_buffer_ptrs_dev() and get_signal_pad_ptrs_dev() each return a pointer
+  // to a device array of size world_size, containing buffer pointers and
+  // signal pad pointers, respectively.
+  virtual void** get_buffer_ptrs_dev() = 0;
+  virtual void** get_signal_pad_ptrs_dev() = 0;
+  virtual size_t get_buffer_size() = 0;
+  virtual size_t get_signal_pad_size() = 0;
+
+  virtual bool has_multicast_support() = 0;
+  virtual void* get_multicast_ptr() = 0;
+
+  virtual at::Tensor get_buffer(
+      int rank,
+      c10::IntArrayRef sizes,
+      c10::ScalarType dtype,
+      int64_t storage_offset) = 0;
+
+  virtual void barrier(int channel) = 0;
+  virtual void put_signal(int dst_rank, int channel) = 0;
+  virtual void wait_signal(int src_rank, int channel) = 0;
+
+  virtual int get_rank() = 0;
+  virtual int get_world_size() = 0;
+};
+
+class SymmetricMemoryAllocator : public c10::intrusive_ptr_target {
+ public:
+  virtual ~SymmetricMemoryAllocator(){};
+
+  virtual void* alloc(
+      size_t size,
+      int device_idx,
+      const std::string& group_name) = 0;
+
+  virtual void free(void* ptr) = 0;
+  virtual size_t get_alloc_size(void* ptr) = 0;
+  virtual c10::intrusive_ptr rendezvous(void* ptr) = 0;
+  virtual bool is_rendezvous_completed(void* ptr) = 0;
+  virtual bool has_multicast_support(int device_idx) = 0;
+};
+
+C10_EXPORT bool is_finalizing();
+
+C10_EXPORT void register_allocator(
+    c10::DeviceType device_type,
+    c10::intrusive_ptr allocator);
+
+C10_EXPORT c10::intrusive_ptr get_allocator(
+    c10::DeviceType device_type);
+
+// Set a store for rendezvousing symmetric allocations on a group of devices
+// identified by `group_name`. The concept of groups is logical; users can
+// utilize predefined groups (e.g., a group of device identified by a
+// ProcessGroup) or create custom ones. Note that a SymmetricMemoryAllocator
+// backends might employ a more efficient communication channel for the actual
+// rendezvous process and only use the store for bootstrapping purposes.
+TORCH_API void set_group_info(
+    const std::string& group_name,
+    int rank,
+    int world_size,
+    c10::intrusive_ptr store);
+
+struct GroupInfo {
+  int rank;
+  int world_size;
+  c10::intrusive_ptr store;
+};
+
+C10_EXPORT const GroupInfo& get_group_info(const std::string& group_name);
+
+// Identical to empty_strided, but allows symmetric memory access to be
+// established for the allocated tensor via SymmetricMemory::rendezvous(). This
+// function itself is not a collective operation. It invokes
+// SymmetricMemoryAllocator::alloc() for the requested device under the hood.
+//
+// NOTE [symmetric memory persistent allocation]
+// If an `alloc_id` is supplied, empty_strided_p2p will perform persistent
+// allocation. This makes the function cache allocated memory and ensure that
+// invocations with the same `alloc_id` receive tensors backed by the same
+// memory address. For safety, if a previous persistent allocation is still
+// active (i.e., the storage of the returned tensor is still alive), persistent
+// allocations with the same `alloc_id` will fail. This determinism coupled
+// with memory planning of communication buffers (e.g., by Inductor) allows
+// communication algorithms to reliably reuse previously established remote
+// memory access.
+TORCH_API at::Tensor empty_strided_p2p(
+    c10::IntArrayRef size,
+    c10::IntArrayRef stride,
+    c10::ScalarType dtype,
+    c10::Device device,
+    const std::string& group_name,
+    std::optional alloc_id);
+
+// Establishes symmetric memory access on tensors allocated via
+// empty_strided_p2p() and empty_strided_p2p_persistent(). rendezvous() is a
+// one-time process, and the mapping between a local memory region and the
+// associated SymmetricMemory object is unique. Subsequent calls to
+// rendezvous() with the same tensor, or tensors allocated with
+// empty_strided_p2p_persistent() using the same alloc_id, will receive the
+// cached SymmetricMemory object.
+//
+// The function has a collective semantic and must be invoked simultaneously
+// from all rendezvous participants.
+TORCH_API c10::intrusive_ptr rendezvous(
+    const at::Tensor& tensor);
+
+// Returns the SymmetricMemory object associated with the tensor. It can only
+// be invoked after rendezvous() but does not need to be invoked collectively.
+TORCH_API c10::intrusive_ptr get_symmetric_memory(
+    const at::Tensor& tensor);
+
+TORCH_API bool has_multicast_support(
+    c10::DeviceType device_type,
+    int device_idx);
+} // namespace symmetric_memory
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/TCPStore.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/TCPStore.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..5ac48d8205e5daf805abb9fbaff3ae572cedbf37
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/TCPStore.hpp
@@ -0,0 +1,141 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+
+namespace c10d {
+namespace detail {
+
+class TCPServer;
+
+class TCPClient;
+
+struct SocketAddress {
+  std::string host{};
+  std::uint16_t port{};
+};
+
+} // namespace detail
+
+struct TCPStoreOptions {
+  static constexpr std::uint16_t kDefaultPort = 29500;
+
+  std::uint16_t port = kDefaultPort;
+  bool isServer = false;
+  std::optional numWorkers = std::nullopt;
+  bool waitWorkers = true;
+  std::chrono::milliseconds timeout = Store::kDefaultTimeout;
+
+  // A boolean value indicating whether multiple store instances can be
+  // initialized with the same host:port pair.
+  bool multiTenant = false;
+
+  // If specified, and if isServer is true, the underlying TCPServer will take
+  // over the bound socket associated to this fd. This option is useful to avoid
+  // port assignment races in certain scenarios.
+  std::optional masterListenFd = std::nullopt;
+
+  // A boolean value indicating whether to use the experimental libUV backend.
+  bool useLibUV = true;
+};
+
+class TORCH_API TCPStore : public Store {
+ public:
+  static constexpr std::chrono::milliseconds kConnectRetryDelay{1000};
+
+  explicit TCPStore(std::string host, const TCPStoreOptions& opts = {});
+
+  [[deprecated("Use TCPStore(host, opts) instead.")]] explicit TCPStore(
+      const std::string& masterAddr,
+      std::uint16_t masterPort,
+      std::optional numWorkers = std::nullopt,
+      bool isServer = false,
+      const std::chrono::milliseconds& timeout = kDefaultTimeout,
+      bool waitWorkers = true);
+
+  ~TCPStore() override;
+
+  void set(const std::string& key, const std::vector& value) override;
+
+  std::vector compareSet(
+      const std::string& key,
+      const std::vector& expectedValue,
+      const std::vector& desiredValue) override;
+
+  std::vector get(const std::string& key) override;
+
+  int64_t add(const std::string& key, int64_t value) override;
+
+  bool deleteKey(const std::string& key) override;
+
+  bool check(const std::vector& keys) override;
+
+  int64_t getNumKeys() override;
+
+  void wait(const std::vector& keys) override;
+
+  void wait(
+      const std::vector& keys,
+      const std::chrono::milliseconds& timeout) override;
+
+  void append(const std::string& key, const std::vector& value)
+      override;
+
+  std::vector> multiGet(
+      const std::vector& keys) override;
+
+  void multiSet(
+      const std::vector& keys,
+      const std::vector>& values) override;
+
+  bool hasExtendedApi() const override;
+
+  // Waits for all workers to join.
+  void waitForWorkers();
+
+  // Returns the hostname used by the TCPStore.
+  const std::string& getHost() const noexcept {
+    return addr_.host;
+  }
+
+  // Returns the port used by the TCPStore.
+  std::uint16_t getPort() const noexcept {
+    return addr_.port;
+  }
+
+  bool isLibUvBackend() const noexcept {
+    return usingLibUv_;
+  }
+
+  // note(xilunwu): this function is only for internal testing
+  void _splitSet(const std::string& key, const std::vector& data);
+
+  std::string repr() const;
+
+ private:
+  int64_t incrementValueBy(const std::string& key, int64_t delta);
+
+  void ping();
+  void validate();
+
+  std::vector doGet(const std::string& key);
+
+  void doWait(
+      c10::ArrayRef keys,
+      std::chrono::milliseconds timeout);
+
+  detail::SocketAddress addr_;
+  std::shared_ptr server_;
+  std::unique_ptr client_;
+  std::optional numWorkers_;
+
+  const std::string initKey_ = "init/";
+  const std::string keyPrefix_ = "/";
+  std::mutex activeOpLock_;
+  bool usingLibUv_ = true;
+};
+
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/TCPStoreBackend.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/TCPStoreBackend.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..d3f68d59fca1783a8cdfe7c1890673833e516f6e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/TCPStoreBackend.hpp
@@ -0,0 +1,74 @@
+#pragma once
+
+#include 
+
+#include 
+#include 
+
+#ifdef _WIN32
+#include 
+#include 
+#else
+#include 
+#include 
+#endif
+
+namespace c10d::detail {
+
+// Magic number for client validation.
+static const uint32_t validationMagicNumber = 0x3C85F7CE;
+
+enum class QueryType : uint8_t {
+  VALIDATE,
+  SET,
+  COMPARE_SET,
+  GET,
+  ADD,
+  CHECK,
+  WAIT,
+  GETNUMKEYS,
+  DELETE_KEY,
+  APPEND,
+  MULTI_GET,
+  MULTI_SET,
+  CANCEL_WAIT,
+  PING,
+};
+
+enum class CheckResponseType : uint8_t { READY, NOT_READY };
+
+enum class WaitResponseType : uint8_t { STOP_WAITING, WAIT_CANCELED };
+
+// Abstract base class to handle thread state for TCPStoreMasterDaemon.
+// Contains the windows/unix implementations to signal a
+// shutdown sequence for the thread
+class BackgroundThread {
+ public:
+  explicit BackgroundThread();
+
+  virtual ~BackgroundThread() = 0;
+  virtual std::uint16_t port() const = 0;
+
+  void start();
+  bool stop_requested();
+
+ protected:
+  void dispose();
+  virtual void run() = 0;
+  virtual void stop() = 0;
+  bool is_running() {
+    return is_running_.load();
+  }
+
+ private:
+  std::atomic is_running_{false};
+  std::thread daemonThread_{};
+};
+
+std::unique_ptr create_tcpstore_backend(
+    const TCPStoreOptions& opts);
+std::unique_ptr create_libuv_tcpstore_backend(
+    const TCPStoreOptions& opts);
+bool is_libuv_tcpstore_backend_available();
+
+} // namespace c10d::detail
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/TraceUtils.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/TraceUtils.h
new file mode 100644
index 0000000000000000000000000000000000000000..9684ebe468a871418c1c584a2caa0fa53793c2fd
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/TraceUtils.h
@@ -0,0 +1,352 @@
+#pragma once
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace c10d {
+
+// A struct to hold the latest status of the process group.
+struct ProcessGroupStatus {
+  // the sequential number of the last collective enqueued into workMetaList_
+  // This is useful for indentifying a rank that has not join a collective
+  // initialized to be -1 to indicate no collective has been enqueued
+  int64_t lastEnqueuedSeq{-1};
+  // the sequential number of the last collective started as the kernel
+  int64_t lastStartedSeq{-1};
+  // the sequential number of the last colletive completed marked by
+  // the watchdog thread
+  // initialized to be -1 to indicate no collective has been completed
+  int64_t lastCompletedSeq{-1};
+
+  // the name of the last collective enqueued into workMetaList_
+  std::string lastEnqueuedWorkName;
+  // the name of the last collective started as the kernel
+  std::string lastStartedWorkName;
+  // the name of the last collective completed
+  std::string lastCompletedWorkName;
+
+  // the sizes of the last work enqueued
+  size_t lastEnqueuedNumelIn;
+  size_t lastEnqueuedNumelOut;
+  // the sizes of the last work completed
+  size_t lastCompletedNumelIn;
+  size_t lastCompletedNumelOut;
+};
+
+inline std::string getTraceStartKey(const std::string& pgName, int rank) {
+  return pgName + "_" + std::to_string(rank) + "_trace_start";
+}
+
+inline std::string getTraceEndKey(const std::string& pgName, int rank) {
+  return pgName + "_" + std::to_string(rank) + "_trace_end";
+}
+
+inline bool traceUpdate(
+    c10::intrusive_ptr& store,
+    const std::string& key,
+    uint64_t seq,
+    const std::string& col) {
+  std::vector value(col.size() + sizeof(seq) + 1);
+  memcpy(value.data(), &seq, sizeof(seq));
+  memcpy(value.data() + sizeof(seq), col.data(), col.size());
+  try {
+    store->set(key, value);
+    return true;
+  } catch (...) {
+    LOG(ERROR) << "Store is down while updating #" << seq << " with key "
+               << key;
+    return false;
+  }
+  return true;
+}
+
+enum TraceDebugEvent {
+  kEventStart,
+  kEventEnd,
+};
+// >>
+using TraceMap =
+    std::map>>;
+
+inline std::string ranksToString(const std::vector& ranks) {
+  std::string str;
+  for (int rank : ranks) {
+    if (str.empty()) {
+      str = std::to_string(rank);
+    } else {
+      str += ", " + std::to_string(rank);
+    }
+  }
+  return str;
+}
+
+inline std::string ranksFromTrace(
+    const std::vector>& items) {
+  std::string ranks;
+  for (auto& p : items) {
+    if (ranks.empty()) {
+      ranks = std::to_string(p.first);
+    } else {
+      ranks += ", " + std::to_string(p.first);
+    }
+  }
+  return ranks;
+}
+
+inline std::string analyzeMissingRanks(const std::vector& missingRanks) {
+  return c10::str(
+      "\n\t - To our best knowledge, ranks [",
+      ranksToString(missingRanks),
+      "] are the lagging ranks that caused this timeout. "
+      "They never joined any collectives");
+}
+
+inline std::string analyzeLaggingRanks(const TraceMap& traceMap) {
+  uint64_t lagSeq = traceMap.begin()->first;
+  std::vector startRanks;
+  std::vector endRanks;
+  for (auto& p : traceMap.begin()->second) {
+    if (p.second.second == kEventStart) {
+      startRanks.push_back(p.first);
+    } else {
+      endRanks.push_back(p.first);
+    }
+  }
+  std::string report =
+      "\n\t - To our best knowledge, the lagging/dead/mismatched ranks "
+      "that caused the desync are:";
+  if (startRanks.size()) {
+    report += c10::str(
+        "\n\t   - [",
+        ranksToString(startRanks),
+        "] joined but didn't finish collective #",
+        lagSeq,
+        " (count from 1)");
+  }
+  if (endRanks.size()) {
+    report += c10::str(
+        "\n\t     [",
+        ranksToString(endRanks),
+        "] finished collective #",
+        lagSeq,
+        ", but didn't join collective #",
+        lagSeq + 1,
+        " (count from 1)");
+  }
+  return report;
+}
+
+inline std::string dumpSnapshot(TraceMap& traceMap) {
+  std::string report = "\n\t - Snapshot of ranks' latest states:";
+  for (auto& tracePair : traceMap) {
+    uint64_t seq = tracePair.first;
+    std::map>& subMap =
+        tracePair.second;
+
+    std::unordered_map> collectivesStart;
+    std::unordered_map> collectivesEnd;
+    for (auto& p : subMap) {
+      int rank = p.first;
+      const std::string& col = p.second.first;
+      if (p.second.second == kEventStart) {
+        collectivesStart[col].push_back(rank);
+      } else {
+        collectivesEnd[col].push_back(rank);
+      }
+    }
+
+    if (collectivesStart.size()) {
+      report += c10::str("\n\t   #", seq, " started ranks:");
+      for (auto& mapPair : collectivesStart) {
+        report += c10::str(
+            "\n\t     [",
+            ranksToString(mapPair.second),
+            "] started ",
+            mapPair.first);
+      }
+    }
+    if (collectivesEnd.size()) {
+      report += c10::str("\n\t   #", seq, " finished ranks:");
+      for (auto& mapPair : collectivesEnd) {
+        report += c10::str(
+            "\n\t     [",
+            ranksToString(mapPair.second),
+            "] finished ",
+            mapPair.first);
+      }
+    }
+  }
+  return report;
+}
+
+inline bool parseTraceValue(
+    c10::intrusive_ptr& store,
+    const std::string& key,
+    uint64_t& seq,
+    std::string& col) {
+  try {
+    std::vector traceValue = store->get(key);
+    memcpy(&seq, traceValue.data(), sizeof(seq));
+    std::string colName((char*)traceValue.data() + sizeof(seq));
+    col = colName;
+    return true;
+  } catch (...) {
+    LOG(ERROR) << "Store is down while getting key " << key;
+    return false;
+  }
+  return true;
+}
+
+inline std::string retrieveDesyncReport(
+    c10::intrusive_ptr& store,
+    const std::string& pgName,
+    int myRank,
+    int worldSize) {
+  std::string report;
+
+  uint64_t thisSeq;
+  std::string thisCol;
+
+  std::vector missingRanks;
+  TraceMap traceMap;
+
+  for (const auto rank : c10::irange(worldSize)) {
+    // Build traceMapStart.
+    uint64_t seqStart;
+    {
+      std::string traceKeyStart = getTraceStartKey(pgName, rank);
+      if (!store->check({traceKeyStart})) {
+        missingRanks.push_back(rank);
+        continue;
+      }
+      std::string col;
+      if (!parseTraceValue(store, traceKeyStart, seqStart, col)) {
+        return report;
+      }
+      traceMap[seqStart].emplace(rank, std::make_pair(col, kEventStart));
+      if (rank == myRank) {
+        thisSeq = seqStart;
+        thisCol = std::move(col);
+      }
+    }
+
+    // Build traceMapEnd.
+    {
+      std::string traceKeyEnd = getTraceEndKey(pgName, rank);
+      if (!store->check({traceKeyEnd})) {
+        continue;
+      }
+      uint64_t seq;
+      std::string col;
+      if (!parseTraceValue(store, traceKeyEnd, seq, col)) {
+        return report;
+      }
+      if (seq == seqStart) {
+        traceMap[seq][rank].second = kEventEnd;
+      }
+    }
+  }
+
+  TORCH_INTERNAL_ASSERT(
+      !missingRanks.empty() || !traceMap.empty(),
+      "Trace shouldn't be empty while enabled GLOO_ASYNC_TIMEOUT_DEBUG");
+  TORCH_INTERNAL_ASSERT(
+      !thisCol.empty(),
+      "Timeout rank [",
+      myRank,
+      "] must have collective tracking iteam in c10::Store trace");
+  TORCH_INTERNAL_ASSERT(
+      traceMap[thisSeq][myRank].second == kEventStart,
+      "Timeout rank [",
+      myRank,
+      "] last trace item must be kEventStart. thisSeq = ",
+      thisSeq,
+      ", col = ",
+      thisCol);
+
+  report += c10::str(
+      "\n\t - [", myRank, "] Timeout at collective: ", thisCol, ", #", thisSeq);
+
+  if (!missingRanks.empty()) {
+    report += analyzeMissingRanks(missingRanks);
+  } else {
+    report += analyzeLaggingRanks(traceMap);
+    report += dumpSnapshot(traceMap);
+  }
+
+  return report;
+}
+
+inline std::string pickle_str(const c10::IValue& v) {
+  std::vector result;
+  {
+    auto writer = [&](const char* data, size_t size) {
+      result.insert(result.end(), data, data + size);
+    };
+    torch::jit::Pickler pickler(
+        writer, nullptr, nullptr, nullptr, nullptr, false);
+    pickler.protocol();
+    pickler.pushIValue(v);
+    pickler.stop();
+  }
+  return std::string(result.begin(), result.end());
+}
+
+inline std::string get_python_cpp_trace() {
+  // usage:
+  // LOG(INFO) << "stacktrace: "
+  //           << get_python_cpp_trace();
+  // warn: might be slow in getting cpp traces
+  // because of slow/broken addr2line
+  // in different system libs
+  std::shared_ptr tb =
+      torch::CapturedTraceback::gather(
+          /*python=*/true, /*script=*/true, /*cpp=*/true);
+  torch::SymbolizedTracebacks s_tbs = torch::symbolize({tb.get()});
+  const auto& s_tb = s_tbs.tracebacks.at(0);
+  std::stringstream oss;
+  for (auto idx : c10::irange(s_tb.size())) {
+    auto frame_id = s_tb[idx];
+    const auto& frame = s_tbs.all_frames.at(frame_id);
+    oss << "#" << idx << " " << frame.funcname << " from " << frame.filename
+        << ":" << frame.lineno << std::endl;
+  }
+  return oss.str();
+}
+
+inline c10::Dict new_dict() {
+  return c10::Dict(
+      c10::AnyType::get(), c10::AnyType::get());
+}
+
+inline c10::List new_list() {
+  return c10::List(c10::AnyType::get());
+}
+
+inline std::string ranks_str(const std::vector& ranks) {
+  std::string str;
+  for (const auto& rank : ranks) {
+    if (str.empty()) {
+      str = std::to_string(rank);
+    } else {
+      str += ", " + std::to_string(rank);
+    }
+  }
+  return c10::str("[", str, "]");
+}
+
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/Types.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/Types.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..7cdb9f62ebbb85eef0b4240c876b07a0bf452919
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/Types.hpp
@@ -0,0 +1,177 @@
+#pragma once
+
+#include 
+
+#include 
+#include 
+
+#include 
+#include 
+
+#include 
+#include 
+
+namespace c10d {
+
+// Base class for supplementary data potentially needed by ReduceOps
+struct TORCH_API _SupplementBase : torch::CustomClassHolder {
+  ~_SupplementBase() override = default;
+};
+
+// Supplementary data specific to NCCL PREMUL_SUM
+// The point of use in ProcessGroupNCCL knows how to unpack it.
+struct NCCLPreMulSumSupplement : _SupplementBase {
+  double double_factor{0.0};
+  at::Tensor tensor_factor;
+  NCCLPreMulSumSupplement(double f) : double_factor{f} {}
+  NCCLPreMulSumSupplement(at::Tensor t) : tensor_factor{std::move(t)} {
+    TORCH_CHECK_EQ(tensor_factor.numel(), 1);
+  }
+};
+
+// Other ReduceOps that need different supplementary data can also
+// derive from _SupplementBase.
+struct TORCH_API ReduceOp : torch::CustomClassHolder {
+  // note(crcrpar): RedOpType could be defined outside of `ReduceOp`
+  enum RedOpType : uint8_t {
+    SUM = 0,
+    AVG = 1,
+    PRODUCT = 2,
+    MIN = 3,
+    MAX = 4,
+    BAND = 5, // Bitwise AND
+    BOR = 6, // Bitwise OR
+    BXOR = 7, // Bitwise XOR
+    PREMUL_SUM = 8, // Multiply by a user-supplied constant before summing.
+    UNUSED = 9
+  };
+
+  ReduceOp() = default;
+
+  ReduceOp(RedOpType op) : op_(op) {
+    TORCH_INTERNAL_ASSERT(
+        op_ != PREMUL_SUM,
+        "Use `torch.distributed._make_nccl_premul_sum` to create an instance of ReduceOp with PREMUL_SUM");
+  }
+
+  ReduceOp(
+      RedOpType op,
+      const c10::intrusive_ptr<_SupplementBase>& optional_supplement) {
+    if (optional_supplement) {
+      op_ = op;
+    } else {
+      supplement_ = optional_supplement;
+    }
+  }
+
+  // The heap resource supplement_, if it exists, is managed by a
+  // c10::intrusive_ptr, so constructors and operator= can be simple
+  ReduceOp(const ReduceOp& other) = default;
+  ReduceOp& operator=(const ReduceOp& other) = default;
+
+  ReduceOp(ReduceOp&& other) = default;
+  ReduceOp& operator=(ReduceOp&& other) = default;
+
+  operator RedOpType() const {
+    return op_;
+  }
+
+  bool operator==(const std::uint8_t other) {
+    TORCH_INTERNAL_ASSERT(other < 9, "Invalid other op value");
+    return other == op_;
+  }
+
+  bool operator==(const ReduceOp::RedOpType other) {
+    return *this == static_cast(other);
+  }
+
+  // todo(crcrpar): Handle `RedOpType::PREMUL_SUM` with its scaling factor.
+  bool operator==(const ReduceOp& other) {
+    return *this == other.op_;
+  }
+
+  RedOpType op_ = SUM;
+  // supplement_ is "type-erased" storage for optional supplementary
+  // data the op might need.
+  // The point of use will know the derived type supplement_ really is,
+  // and downcast its pointer to extract the data as the needed type(s).
+  // Right now, only PREMUL_SUM needs supplementary data, but the same
+  // mechanism could extend to support other nontrivial reduce ops with
+  // different supplementary payloads.
+  c10::intrusive_ptr<_SupplementBase> supplement_;
+};
+
+template 
+ReduceOp makeNCCLPreMulSum(const T& factor) {
+  ReduceOp rop;
+  rop.op_ = ReduceOp::PREMUL_SUM;
+  rop.supplement_ = c10::make_intrusive(factor);
+  return rop;
+}
+
+constexpr auto kUnsetTimeout = std::chrono::milliseconds(-1);
+
+struct BroadcastOptions {
+  int64_t rootRank = 0;
+  int64_t rootTensor = 0;
+  std::chrono::milliseconds timeout = kUnsetTimeout;
+  bool asyncOp = true;
+};
+
+struct AllreduceOptions {
+  ReduceOp reduceOp = ReduceOp::SUM;
+  std::chrono::milliseconds timeout = kUnsetTimeout;
+  std::optional sparseIndices = std::nullopt;
+};
+
+struct AllreduceCoalescedOptions : AllreduceOptions {};
+
+struct ReduceOptions {
+  ReduceOp reduceOp = ReduceOp::SUM;
+  int64_t rootRank = 0;
+  int64_t rootTensor = 0;
+  std::chrono::milliseconds timeout = kUnsetTimeout;
+};
+
+struct AllgatherOptions {
+  std::chrono::milliseconds timeout = kUnsetTimeout;
+  bool asyncOp = true;
+};
+
+struct GatherOptions {
+  int64_t rootRank = 0;
+  std::chrono::milliseconds timeout = kUnsetTimeout;
+};
+
+struct ScatterOptions {
+  int64_t rootRank = 0;
+  std::chrono::milliseconds timeout = kUnsetTimeout;
+  bool asyncOp = true;
+};
+
+struct ReduceScatterOptions {
+  ReduceOp reduceOp = ReduceOp::SUM;
+  std::chrono::milliseconds timeout = kUnsetTimeout;
+  bool asyncOp = true;
+};
+
+struct AllToAllOptions {
+  std::chrono::milliseconds timeout = kUnsetTimeout;
+};
+
+struct BarrierOptions {
+  std::vector device_ids;
+  std::chrono::milliseconds timeout = kUnsetTimeout;
+  std::optional device;
+};
+
+struct DistributedBackendOptions {
+  c10::intrusive_ptr<::c10d::Store> store;
+  int group_rank;
+  int group_size;
+  std::chrono::duration timeout;
+  std::string group_id;
+  std::vector global_ranks_in_group;
+};
+
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/UCCTracing.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/UCCTracing.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..953cec8a1bc36e8550b026e49ef4d2b4fab76e75
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/UCCTracing.hpp
@@ -0,0 +1,58 @@
+#pragma once
+
+#ifdef USE_C10D_UCC
+
+#include 
+
+namespace c10d {
+
+#define RECORD_COMMS_TRACE(                                                    \
+    _comms_tracer, _work, _opType, _rank, _comm_size, _inTensors, _outTensors) \
+  do {                                                                         \
+    if (torch_ucc_config.enable_comms_logger) {                                \
+      _comms_tracer->recordComms(                                              \
+          opTypeToString(_opType),                                             \
+          (uintptr_t)_work.get(),                                              \
+          _rank,                                                               \
+          _comm_size,                                                          \
+          _inTensors,                                                          \
+          _outTensors);                                                        \
+    }                                                                          \
+  } while (0)
+
+// interfaces to collect communication traces
+class TORCH_API CommTraceLogger : public torch::CustomClassHolder {
+ private:
+  std::vector comms_trace_;
+  std::vector curBlocks_; /* unused */
+  std::vector curOutSplitSizes_;
+  std::vector curInSplitSizes_;
+  int curRoot_ = -1;
+  unsigned long seqnum = 0;
+
+ public:
+  void setCurBlock(const std::string& name); /* unused */
+  void popBlock(); /* unused */
+  // record root info if applicable, e.g., broadcast, gather, scatter
+  void recordOptionalInfo(int root = -1);
+  // record input/output splits of Alltoallv
+  void recordOptionalInfo(
+      const std::vector& outputSplitSizes = {},
+      const std::vector& inputSplitSizes = {});
+  // record essential comms information
+  void recordComms(
+      const std::string& collName,
+      const uintptr_t workReq = 0,
+      const int rank = -1,
+      const int world_size = -1,
+      const std::vector& inputTensors = {},
+      const std::vector& outputTensor = {});
+  // return collected comms traces
+  std::vector& getCommsTrace() {
+    return comms_trace_;
+  }
+};
+
+} // namespace c10d
+
+#endif // USE_C10D_UCC
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/UCCUtils.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/UCCUtils.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..a44e2de86ef7dc2477d59cbf221f477b00cc8370
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/UCCUtils.hpp
@@ -0,0 +1,187 @@
+#pragma once
+
+#ifdef USE_C10D_UCC
+
+#include 
+#include 
+#include 
+
+namespace c10d {
+
+// Macro to generate the error message on a non-successful UCC return value.
+#define TORCH_UCC_GET_ERROR_MSG(_err, _error_msg, _result) \
+  do {                                                     \
+    _err = c10::str(                                       \
+        "[",                                               \
+        std::string(__FILE__),                             \
+        ":",                                               \
+        std::to_string(__LINE__),                          \
+        "] ",                                              \
+        logger->getLogPrefix(),                            \
+        _error_msg,                                        \
+        ", error code ",                                   \
+        _result,                                           \
+        ": ",                                              \
+        ucc_status_string(_result),                        \
+        ", system error code ",                            \
+        errno);                                            \
+  } while (0)
+
+// Macro to throw on a non-successful UCC return value.
+#define TORCH_UCC_CHECK(_cmd, _error_msg)               \
+  do {                                                  \
+    ucc_status_t result = _cmd;                         \
+    if (result != UCC_OK) {                             \
+      std::string err;                                  \
+      TORCH_UCC_GET_ERROR_MSG(err, _error_msg, result); \
+      TORCH_CHECK(false, err);                          \
+    }                                                   \
+  } while (0)
+
+// Macro and throw on a non-successful UCC return value and free its request.
+#define TORCH_UCC_CHECK_REQUEST(_request, _cmd, _error_msg) \
+  do {                                                      \
+    ucc_status_t result = _cmd;                             \
+    if (result != UCC_OK) {                                 \
+      std::string err;                                      \
+      TORCH_UCC_GET_ERROR_MSG(err, _error_msg, result);     \
+      if (_request != nullptr) {                            \
+        ucc_collective_finalize(_request);                  \
+      }                                                     \
+      TORCH_CHECK(false, err);                              \
+    }                                                       \
+  } while (0)
+
+// Macros to print logs with unified format
+#define TORCH_UCC_LOG_ERROR(_phase, _msg) \
+  LOG(ERROR) << logger->getLogPrefix(_phase) << "[ERROR] " << _msg;
+#define TORCH_UCC_LOG_INFO(_phase, _msg) \
+  LOG(INFO) << logger->getLogPrefix(_phase) << "[INFO] " << _msg;
+#define TORCH_UCC_LOG_DEBUG(_phase, _msg) \
+  VLOG(1) << logger->getLogPrefix(_phase) << "[DEBUG] " << _msg;
+
+enum torch_ucc_phase_t {
+  TORCH_UCC_UNKNOWN = -1,
+  TORCH_UCC_INIT,
+  TORCH_UCC_HEALTH_CHECK,
+  TORCH_UCC_READY,
+  TORCH_UCC_COLL_POST,
+  TORCH_UCC_COLL_PROGRESS,
+  TORCH_UCC_FINALIZE,
+};
+
+const std::map ucc_phase_map = {
+    {TORCH_UCC_UNKNOWN, "UNKNOWN"},
+    {TORCH_UCC_INIT, "INIT"},
+    {TORCH_UCC_HEALTH_CHECK, "HEALTH_CHECK"},
+    {TORCH_UCC_READY, "READY"},
+    {TORCH_UCC_COLL_POST, "COLL_POST"},
+    {TORCH_UCC_COLL_PROGRESS, "COLL_PROGRESS"},
+    {TORCH_UCC_FINALIZE, "FINALIZE"},
+};
+
+class CommTraceLogger;
+
+class TORCH_API ProcessGroupUCCLogger : public torch::CustomClassHolder {
+ public:
+  ProcessGroupUCCLogger();
+  ProcessGroupUCCLogger(std::string log_prefix, torch_ucc_phase_t phase);
+
+  std::string getLogPrefix(torch_ucc_phase_t phase = TORCH_UCC_UNKNOWN);
+  void setLogPrefix(std::string log_prefix);
+  inline void setPhase(torch_ucc_phase_t phase) {
+    local_phase = phase;
+  }
+
+  void initCommsTracer();
+  void flushComms(int rank, int world_size);
+  std::shared_ptr trace_generator = nullptr;
+
+ protected:
+  std::string log_prefix;
+  torch_ucc_phase_t local_phase = TORCH_UCC_UNKNOWN;
+  bool initialized_CommTraceLogger = false;
+};
+
+struct torch_ucc_oob_coll_info_t {
+  c10::intrusive_ptr store;
+  uint32_t comm_id;
+  int rank;
+  int size;
+  void* rbuf;
+  size_t msglen;
+  std::string getKey(std::string key) {
+    return std::to_string(comm_id) + key;
+  }
+};
+
+class CommBase {
+ public:
+  CommBase(const c10::intrusive_ptr& logger_)
+      : logger(logger_) {}
+  virtual void progress() = 0;
+  virtual void free_request(ucc_coll_req_h request) = 0;
+  virtual ~CommBase() {}
+  c10::intrusive_ptr logger;
+};
+class CommUCC : public CommBase {
+ public:
+  ucc_lib_h lib{nullptr};
+  ucc_context_h context{nullptr};
+
+ public:
+  void progress() override;
+  CommUCC(
+      std::shared_ptr oob,
+      const c10::intrusive_ptr& logger);
+  void free_request(ucc_coll_req_h request) override;
+  ~CommUCC();
+};
+
+ucc_status_t oob_allgather(
+    void* sbuf,
+    void* rbuf,
+    size_t msglen,
+    void* coll_info,
+    void** req);
+
+ucc_status_t oob_allgather_test(void* req);
+
+ucc_status_t oob_allgather_free(void* req);
+
+// trim: remove spaces before and after the string view
+// implementation borrowed from https://stackoverflow.com/a/17976541
+inline c10::string_view trim(c10::string_view s) {
+  auto wsfront = std::find_if_not(
+      s.begin(), s.end(), [](int c) { return std::isspace(c); });
+  auto wsback = std::find_if_not(s.rbegin(), s.rend(), [](int c) {
+                  return std::isspace(c);
+                }).base();
+  return (
+      wsback <= wsfront ? "" : s.substr(wsfront - s.begin(), wsback - wsfront));
+}
+
+inline std::string tolower(c10::string_view s) {
+  std::string result;
+  result.reserve(s.size());
+  for (auto c : s) {
+    result.push_back(std::tolower(c));
+  }
+  return result;
+}
+
+inline std::vector parse_list(std::string list) {
+  std::vector result;
+  list = tolower(trim(list));
+  while (!list.empty()) {
+    const auto end_pos = list.find_first_of(',');
+    const auto token = trim(list.substr(0, end_pos));
+    result.push_back(std::string(token));
+    list = (end_pos != c10::string_view::npos) ? list.substr(end_pos + 1) : "";
+  }
+  return result;
+}
+
+} // namespace c10d
+
+#endif // USE_C10D_UCC
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/UnixSockUtils.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/UnixSockUtils.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..531f8459aa7ad4739448040dde4eda5769079f90
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/UnixSockUtils.hpp
@@ -0,0 +1,25 @@
+#pragma once
+
+#include 
+
+namespace c10d::tcputil {
+
+#define CONNECT_SOCKET_OFFSET 2
+
+inline int poll(struct pollfd* fds, unsigned long nfds, int timeout) {
+  return ::poll(fds, nfds, timeout);
+}
+
+inline void addPollfd(
+    std::vector& fds,
+    int socket,
+    short events) {
+  fds.push_back({.fd = socket, .events = events});
+}
+
+inline struct ::pollfd getPollfd(int socket, short events) {
+  struct ::pollfd res = {.fd = socket, .events = events};
+  return res;
+}
+
+} // namespace c10d::tcputil
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/Utils.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/Utils.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..ea4a4653bc35fc2fc28852f8dcf20309bb902dd7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/Utils.hpp
@@ -0,0 +1,729 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#ifdef _WIN32
+#include 
+#include 
+typedef SSIZE_T ssize_t;
+#pragma comment(lib, "Ws2_32.lib")
+#else
+#include 
+#include 
+#include 
+#include 
+#include 
+#endif
+
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace c10d {
+
+TORCH_API size_t getTensorsNumel(const std::vector& tensors);
+
+// Retrieve tensor shapes from a given tensor.
+TORCH_API std::vector getTensorShapes(
+    const std::vector& tensors);
+
+// Use -2 to represent unset state of env vars
+#define C10D_ENV_NOT_SET -2
+
+#define WARN_ENV_VAR_ONCE(deprecated_env, new_env)                        \
+  TORCH_WARN_ONCE(                                                        \
+      "Environment variable " + deprecated_env + " is deprecated; use " + \
+      new_env + " instead");
+
+// Turns at::IntArrayRef into "(1, 2, 3, 4)".
+inline std::string toString(at::IntArrayRef l) {
+  std::stringstream ss;
+  ss << "(";
+  for (const auto i : c10::irange(l.size())) {
+    if (i > 0) {
+      ss << ", ";
+    }
+    ss << l[i];
+  }
+  ss << ")";
+  return ss.str();
+}
+
+inline std::string toString(const c10::Layout& layout) {
+  std::stringstream ss;
+  ss << layout;
+  return ss.str();
+}
+
+inline void assertSameType(
+    const at::DeprecatedTypeProperties& type,
+    const std::vector& tensors) {
+  for (const auto i : c10::irange(tensors.size())) {
+    if (!tensors[i].options().type_equal(type.options())) {
+      const std::string expected = type.toString();
+      const std::string actual = tensors[i].toString();
+      throw std::invalid_argument(
+          // NOLINTNEXTLINE(performance-inefficient-string-concatenation)
+          "mixed types (" + expected + " and " + actual + ")");
+    }
+  }
+}
+
+inline std::vector split(
+    char separator,
+    const std::string& string) {
+  std::vector pieces;
+  std::stringstream ss(string);
+  std::string item;
+  while (std::getline(ss, item, separator)) {
+    pieces.push_back(std::move(item));
+  }
+  return pieces;
+}
+
+inline std::string getCvarString(
+    const std::vector& env,
+    const char* def) {
+  const char* ret = def;
+
+  if (env.empty()) {
+    TORCH_CHECK(false, "No environment variables passed");
+    return ret;
+  }
+
+  /* parse environment variable in reverse order, so the early
+   * versions of a variable get higher priority than the latter
+   * versions of the same variable */
+  for (ssize_t i = static_cast(env.size()) - 1; i >= 0; i--) {
+    const char* val = std::getenv(env[i].c_str());
+    if (val == nullptr) {
+      continue;
+    } else if (i) {
+      WARN_ENV_VAR_ONCE(env[i], env[0]);
+    }
+
+    ret = val;
+  }
+
+  return ret;
+}
+
+inline int getCvarInt(const std::vector& env, int def) {
+  int ret = def;
+
+  if (env.empty()) {
+    TORCH_CHECK(false, "No environment variables passed");
+    return ret;
+  }
+
+  /* parse environment variable in reverse order, so the early
+   * versions of a variable get higher priority than the latter
+   * versions of the same variable */
+  for (ssize_t i = static_cast(env.size()) - 1; i >= 0; i--) {
+    char* val = std::getenv(env[i].c_str());
+    if (val == nullptr) {
+      continue;
+    } else if (i) {
+      WARN_ENV_VAR_ONCE(env[i], env[0]);
+    }
+
+    try {
+      ret = std::stoi(val);
+    } catch (std::exception&) {
+      TORCH_CHECK(false, "Invalid value for environment variable: " + env[i]);
+    }
+  }
+
+  return ret;
+}
+
+inline bool getCvarBool(const std::vector& env, bool def) {
+  bool ret = def;
+
+  if (env.empty()) {
+    TORCH_CHECK(false, "No environment variables passed");
+    return ret;
+  }
+
+  /* parse environment variable in reverse order, so the early
+   * versions of a variable get higher priority than the latter
+   * versions of the same variable */
+  for (ssize_t i = static_cast(env.size()) - 1; i >= 0; i--) {
+    char* val_ = std::getenv(env[i].c_str());
+    if (val_ == nullptr) {
+      continue;
+    } else if (i) {
+      WARN_ENV_VAR_ONCE(env[i], env[0]);
+    }
+
+    std::string val = std::string(val_);
+    for (auto& x : val) {
+      // NOLINTNEXTLINE(*-narrowing-conversions)
+      x = std::tolower(x);
+    }
+
+    if (val == "y" || val == "yes" || val == "1" || val == "t" ||
+        val == "true") {
+      ret = true;
+    } else if (
+        val == "n" || val == "no" || val == "0" || val == "f" ||
+        val == "false") {
+      ret = false;
+    } else {
+      TORCH_CHECK(false, "Invalid value for environment variable: " + env[i]);
+      return ret;
+    }
+  }
+
+  return ret;
+}
+
+inline void assertSameSizes(
+    const at::IntArrayRef& sizes,
+    const std::vector& tensors) {
+  for (const auto i : c10::irange(tensors.size())) {
+    if (!tensors[i].sizes().equals(sizes)) {
+      const auto expected = toString(sizes);
+      const auto actual = toString(tensors[i].sizes());
+      throw std::invalid_argument(
+          // NOLINTNEXTLINE(performance-inefficient-string-concatenation)
+          "mixed sizes (" + expected + " and " + actual + ")");
+    }
+  }
+}
+
+inline void assertSameSizeAndType(const std::vector& tensors) {
+  // Ensure we have at least one tensor
+  if (tensors.empty()) {
+    throw std::invalid_argument("argument is empty");
+  }
+
+  // Ensure all tensors have identical type and shape
+  auto options = tensors[0].options();
+  auto sizes = tensors[0].sizes();
+  for (const auto i : c10::irange(1, tensors.size())) {
+    if (!tensors[i].options().type_equal(options)) {
+      const auto expected = toString(options);
+      const auto actual = toString(tensors[i].options());
+      throw std::invalid_argument(
+          // NOLINTNEXTLINE(performance-inefficient-string-concatenation)
+          "argument contains mixed types (" + expected + " and " + actual +
+          ")");
+    }
+    if (!tensors[i].sizes().equals(sizes)) {
+      const auto expected = toString(sizes);
+      const auto actual = toString(tensors[i].sizes());
+      throw std::invalid_argument(
+          // NOLINTNEXTLINE(performance-inefficient-string-concatenation)
+          "argument contains mixed types (" + expected + " and " + actual +
+          ")");
+    }
+  }
+}
+
+inline void assertTypeMatch(
+    const std::function& fn,
+    const at::DeprecatedTypeProperties& type,
+    const at::ArrayRef tensors,
+    size_t index) {
+  if (!tensors[index].options().type_equal(type.options())) {
+    fn("invalid tensor type at index " + std::to_string(index) + " (expected " +
+       type.toString() + ", got " + tensors[index].toString() + ")");
+  }
+}
+
+inline void assertTypeMatch(
+    const std::function& fn,
+    const at::TensorOptions& options,
+    const at::ArrayRef tensors,
+    size_t index) {
+  if (!tensors[index].options().type_equal(options)) {
+    fn("invalid tensor type at index " + std::to_string(index) + " (expected " +
+       toString(options) + ", got " + toString(tensors[index].options()) + ")");
+  }
+}
+
+inline void assertSizesMatch(
+    const std::function& fn,
+    const at::IntArrayRef& sizes,
+    const at::ArrayRef tensors,
+    size_t index) {
+  if (tensors[index].sizes() != sizes) {
+    fn("invalid tensor size at index " + std::to_string(index) + " (expected " +
+       toString(sizes) + ", got " + toString(tensors[index].sizes()) + ")");
+  }
+}
+
+inline void assertLayoutMatch(
+    const std::function& fn,
+    const c10::Layout& expected,
+    const at::ArrayRef tensors,
+    size_t index) {
+  const auto& actual = tensors[index].layout();
+  if (actual != expected) {
+    fn("invalid tensor layout at index " + std::to_string(index) +
+       " (expected " + toString(expected) + ", got " + toString(actual) + ")");
+  }
+}
+
+inline void assertLayoutMatch(
+    const std::function& fn,
+    const at::ArrayRef tensors) {
+  const auto& layout = tensors[0].layout();
+  for (const auto i : c10::irange(1, tensors.size())) {
+    assertLayoutMatch(fn, layout, tensors, i);
+  }
+}
+
+inline void assertNonEmpty(
+    const std::function& fn,
+    const at::ArrayRef tensors) {
+  if (tensors.empty()) {
+    fn("requires non-empty tensor list");
+  }
+}
+
+inline void assertSingleElement(
+    const std::function& fn,
+    const at::ArrayRef tensors) {
+  if (tensors.size() != 1) {
+    fn("requires a single-element tensor list");
+  }
+}
+
+inline void assertSingleElementInput(
+    const std::function& fn,
+    const at::ArrayRef tensors) {
+  if (tensors.size() != 1) {
+    fn("requires a single-element input tensor list");
+  }
+}
+
+inline void assertSingleElementOutput(
+    const std::function& fn,
+    const at::ArrayRef tensors) {
+  if (tensors.size() != 1) {
+    fn("requires a single-element output tensor list");
+  }
+}
+
+inline void assertRootRank(
+    const std::function& fn,
+    int64_t rank,
+    int64_t size) {
+  if (rank < 0 || rank >= size) {
+    fn("invalid root rank: " + std::to_string(rank));
+  }
+}
+
+inline void assertRootTensor(
+    const std::function& fn,
+    int64_t rank,
+    int64_t size) {
+  if (rank < 0 || rank >= size) {
+    fn("invalid root tensor: " + std::to_string(rank));
+  }
+}
+
+inline void assertDense(
+    const std::function& fn,
+    const at::ArrayRef tensors) {
+  const auto& layout = tensors[0].layout();
+  if (layout != at::kStrided) {
+    fn("only supports dense tensors");
+  }
+}
+
+inline void assertCPU(
+    const std::function& fn,
+    const at::ArrayRef tensors) {
+  const auto& device = tensors[0].device();
+  if (device.type() != at::kCPU) {
+    fn("only supports CPU tensors");
+  }
+}
+
+inline void assertSameDevice(
+    const std::function& fn,
+    const at::ArrayRef tensors) {
+  if (tensors.size() < 2) {
+    return;
+  }
+  const auto& device = tensors[0].device();
+  for (const auto i : c10::irange(1, tensors.size())) {
+    if (tensors[i].device() != device) {
+      fn("tensors should be on the same device");
+    }
+  }
+}
+
+inline void assertTypeAndSizesMatch(
+    const std::function& fn,
+    const at::ArrayRef tensors,
+    const at::DeprecatedTypeProperties& type,
+    const at::IntArrayRef& sizes) {
+  for (const auto i : c10::irange(tensors.size())) {
+    assertTypeMatch(fn, type, tensors, i);
+    assertSizesMatch(fn, sizes, tensors, i);
+  }
+}
+
+inline void assertTypeAndSizesMatch(
+    const std::function& fn,
+    const at::ArrayRef tensors,
+    const at::TensorOptions& options,
+    const at::IntArrayRef& sizes) {
+  for (const auto i : c10::irange(tensors.size())) {
+    assertTypeMatch(fn, options, tensors, i);
+    assertSizesMatch(fn, sizes, tensors, i);
+  }
+}
+
+inline void assertTypeAndSizesMatch(
+    const std::function& fn,
+    const at::ArrayRef tensors) {
+  const auto& options = tensors[0].options();
+  const auto sizes = tensors[0].sizes();
+  assertTypeAndSizesMatch(fn, tensors.slice(1), options, sizes);
+}
+
+// Copied from ATen/core/functional.h.
+template 
+inline auto fmap(T& inputs, const F& fn)
+    -> std::vector {
+  std::vector r;
+  r.reserve(inputs.size());
+  for (auto& input : inputs) {
+    r.push_back(fn(input));
+  }
+  return r;
+}
+
+// Copied from torch/csrc/utils/tensor_flatten.h.
+inline at::Tensor flattenDenseTensors(at::TensorList tensors) {
+  static const auto flatten = [](const at::Tensor& t) {
+    return t.contiguous().view({-1});
+  };
+  if (tensors.size() == 1) {
+    return flatten(tensors[0]);
+  }
+  return at::cat(::c10d::fmap(tensors, flatten));
+}
+
+inline at::Tensor newLikeFlat(
+    std::vector>& tensors,
+    size_t deviceIdx) {
+  if (tensors.empty() || tensors[0].empty()) {
+    TORCH_CHECK(false, "Received an empty list");
+  }
+  if (deviceIdx >= tensors.size()) {
+    TORCH_CHECK(false, "Invalid device index");
+  }
+  auto& t = tensors[deviceIdx][0];
+  auto device = t.device();
+  for (const auto i : c10::irange(1, tensors[deviceIdx].size())) {
+    if (tensors[deviceIdx][i].device() != device) {
+      TORCH_CHECK(false, "Expecting all tensors on the same device");
+    }
+  }
+  at::DeviceGuard gpuGuard(device);
+  std::vector sizes{static_cast(tensors[deviceIdx].size())};
+  std::vector strides{static_cast(t.numel())};
+  sizes.insert(sizes.end(), t.sizes().begin(), t.sizes().end());
+  strides.insert(strides.end(), t.strides().begin(), t.strides().end());
+  return at::empty_strided(
+      sizes, strides, t.options().memory_format(std::nullopt));
+}
+
+inline at::Tensor newLikeFlat(std::vector& tensors) {
+  if (tensors.empty()) {
+    TORCH_CHECK(false, "Received an empty list");
+  }
+  auto& t = tensors[0];
+  at::DeviceGuard gpuGuard(t.device());
+  std::vector sizes{static_cast(tensors.size())};
+  sizes.insert(sizes.end(), t.sizes().begin(), t.sizes().end());
+  return at::empty(sizes, t.options());
+}
+
+inline std::vector> getSizes(
+    const std::vector& tensors) {
+  std::vector> sizes(tensors.size());
+  for (const auto i : c10::irange(tensors.size())) {
+    sizes[i] = tensors[i].sizes().vec();
+  }
+  return sizes;
+}
+
+inline std::vector getDevices(const std::vector& tensors) {
+  std::vector devices(tensors.size(), -1);
+  if (tensors[0].device().is_cuda()) {
+    for (const auto i : c10::irange(tensors.size())) {
+      // NOLINTNEXTLINE(bugprone-signed-char-misuse)
+      devices[i] = tensors[i].storage().device().index();
+    }
+  }
+  return devices;
+}
+
+template 
+inline T* getDataPointer(const at::Tensor& tensor) {
+  // This method is only used in ProcessGroupGloo for now. Call sites must make
+  // sure that the input tensor is contiguous. It is OK if the tensor does not
+  // start from the beginning of the storage. For example, it could come from
+  // chunk(..., dim=0)[1]. Hence, we need to use data_ptr() instead of
+  // tensor.storage().data()
+  // NB: not using tensor.data() because tensor is not aware of gloo::TYPE
+  return static_cast(tensor.data_ptr());
+}
+
+template 
+std::vector getDataPointers(const std::vector& tensors) {
+  std::vector ptrs(tensors.size());
+  for (const auto i : c10::irange(tensors.size())) {
+    ptrs[i] = getDataPointer(tensors[i]);
+  }
+  return ptrs;
+}
+
+// For alltoall split size sanity check
+inline void checkSplitSizes(
+    const std::vector& split_sizes,
+    const at::Tensor& tensor,
+    int group_size) {
+  if (split_sizes.empty()) {
+    TORCH_CHECK(
+        tensor.size(0) % group_size == 0,
+        "Tensor's dim 0 does not divide equally across group size");
+  } else {
+    TORCH_CHECK(
+        split_sizes.size() == static_cast(group_size),
+        "Number of tensor splits not equal to group size");
+    const auto sum = c10::sum_integers(split_sizes);
+    TORCH_CHECK(
+        sum == tensor.size(0), "Split sizes doesn't match total dim 0 size");
+  }
+}
+
+// Compute alltoall lengths and offsets, handling multi-dimension tensors
+template 
+size_t computeLengthsAndOffsets(
+    const std::vector& split_sizes,
+    const at::Tensor& tensor,
+    std::vector* lengths,
+    std::vector* offsets) {
+  size_t group_size = lengths->size();
+  bool equal_splits = false;
+  size_t dim0_size = tensor.size(0);
+  size_t row_size = (dim0_size ? tensor.numel() / dim0_size : 1);
+  size_t split_size = 0;
+  size_t offset = 0;
+
+  if (split_sizes.empty()) {
+    equal_splits = true;
+    split_size = tensor.size(0) / group_size;
+  }
+  for (const auto i : c10::irange(group_size)) {
+    size_t length = row_size * (equal_splits ? split_size : split_sizes[i]);
+    (*lengths)[i] = length;
+    (*offsets)[i] = offset;
+    // TODO: see if we should add overflow protection for offset
+    offset += length;
+  }
+  return offset;
+}
+
+template 
+size_t computeLengthsAndOffsets(
+    const std::vector& tensors,
+    std::vector* lengths,
+    std::vector* offsets) {
+  size_t group_size = lengths->size();
+  size_t offset = 0;
+  for (const auto i : c10::irange(group_size)) {
+    size_t length = tensors[i].numel();
+    (*lengths)[i] = length;
+    (*offsets)[i] = offset;
+    offset += length;
+  }
+  return offset;
+}
+
+using RankType = uint32_t;
+using SizeType = uint64_t;
+
+// `errno` is only meaningful when it fails. E.g., a  successful `fork()` sets
+// `errno` to `EINVAL` in child process on some macos
+// (https://stackoverflow.com/a/20295079), and thus `errno` should really only
+// be inspected if an error occurred.
+//
+// `success_cond` is an expression used to check if an error has happend. So for
+// `fork()`, we can use `SYSCHECK(pid = fork(), pid != -1)`. The function output
+// is stored in variable `__output` and may be used in `success_cond`.
+#ifdef _WIN32
+#define SYSCHECK(expr, success_cond)                                      \
+  while (true) {                                                          \
+    auto __output = (expr);                                               \
+    auto errno_local = WSAGetLastError();                                 \
+    (void)__output;                                                       \
+    if (!(success_cond)) {                                                \
+      if (errno == EINTR) {                                               \
+        continue;                                                         \
+      } else if (                                                         \
+          errno_local == WSAETIMEDOUT || errno_local == WSAEWOULDBLOCK) { \
+        C10_THROW_ERROR(DistNetworkError, "Socket Timeout");              \
+      } else {                                                            \
+        C10_THROW_ERROR(DistNetworkError, std::strerror(errno_local));    \
+      }                                                                   \
+    } else {                                                              \
+      break;                                                              \
+    }                                                                     \
+  }
+#else
+#define SYSCHECK(expr, success_cond)                             \
+  while (true) {                                                 \
+    auto __output = (expr);                                      \
+    (void)__output;                                              \
+    if (!(success_cond)) {                                       \
+      if (errno == EINTR) {                                      \
+        continue;                                                \
+      } else if (errno == EAGAIN || errno == EWOULDBLOCK) {      \
+        C10_THROW_ERROR(DistNetworkError, "Socket Timeout");     \
+      } else {                                                   \
+        C10_THROW_ERROR(DistNetworkError, std::strerror(errno)); \
+      }                                                          \
+    } else {                                                     \
+      break;                                                     \
+    }                                                            \
+  }
+#endif
+
+// Most functions indicate error by returning `-1`. This is a helper macro for
+// this common case with `SYSCHECK`.
+// Since SOCKET_ERROR = -1 in MSVC, so also leverage SYSCHECK_ERR_RETURN_NEG1
+#define SYSCHECK_ERR_RETURN_NEG1(expr) SYSCHECK(expr, __output != -1)
+
+namespace tcputil {
+
+// Send and receive
+template 
+void sendBytes(
+    int socket,
+    const T* buffer,
+    size_t length,
+    bool moreData = false) {
+  size_t bytesToSend = sizeof(T) * length;
+  if (bytesToSend == 0) {
+    return;
+  }
+
+  auto currentBytes = reinterpret_cast(buffer);
+
+  int flags = 0;
+
+#ifdef MSG_MORE
+  if (moreData) { // there is more data to send
+    flags |= MSG_MORE;
+  }
+#endif
+
+// Ignore SIGPIPE as the send() return value is always checked for error
+#ifdef MSG_NOSIGNAL
+  flags |= MSG_NOSIGNAL;
+#endif
+
+  while (bytesToSend > 0) {
+    ssize_t bytesSent = 0;
+    SYSCHECK_ERR_RETURN_NEG1(
+        bytesSent = ::send(socket, currentBytes, bytesToSend, flags))
+    if (bytesSent == 0) {
+      C10_THROW_ERROR(DistNetworkError, "failed to send, sent 0 bytes");
+    }
+
+    bytesToSend -= bytesSent;
+    currentBytes += bytesSent;
+  }
+}
+
+template 
+void recvBytes(int socket, T* buffer, size_t length) {
+  size_t bytesToReceive = sizeof(T) * length;
+  if (bytesToReceive == 0) {
+    return;
+  }
+
+  auto currentBytes = reinterpret_cast(buffer);
+
+  while (bytesToReceive > 0) {
+    ssize_t bytesReceived = 0;
+    SYSCHECK_ERR_RETURN_NEG1(
+        bytesReceived = recv(socket, currentBytes, bytesToReceive, 0))
+    if (bytesReceived == 0) {
+      C10_THROW_ERROR(DistNetworkError, "failed to recv, got 0 bytes");
+    }
+
+    bytesToReceive -= bytesReceived;
+    currentBytes += bytesReceived;
+  }
+}
+
+// send a vector's length and data
+template 
+void sendVector(int socket, const std::vector& vec, bool moreData = false) {
+  SizeType size = vec.size();
+  sendBytes(socket, &size, 1, true);
+  sendBytes(socket, vec.data(), size, moreData);
+}
+
+// receive a vector as sent in sendVector
+template 
+std::vector recvVector(int socket) {
+  SizeType valueSize = 0;
+  recvBytes(socket, &valueSize, 1);
+  std::vector value(valueSize);
+  recvBytes(socket, value.data(), value.size());
+  return value;
+}
+
+// this is only for convenience when sending rvalues
+template 
+void sendValue(int socket, const T& value, bool moreData = false) {
+  sendBytes(socket, &value, 1, moreData);
+}
+
+template 
+T recvValue(int socket) {
+  T value;
+  recvBytes(socket, &value, 1);
+  return value;
+}
+
+// send a string's length and data
+inline void sendString(
+    int socket,
+    const std::string& str,
+    bool moreData = false) {
+  SizeType size = str.size();
+  sendBytes(socket, &size, 1, true);
+  sendBytes(socket, str.data(), size, moreData);
+}
+
+// receive a string as sent in sendString
+inline std::string recvString(int socket) {
+  SizeType valueSize = 0;
+  recvBytes(socket, &valueSize, 1);
+  std::vector value(valueSize);
+  recvBytes(socket, value.data(), value.size());
+  return std::string(value.data(), value.size());
+}
+
+} // namespace tcputil
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/WinSockUtils.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/WinSockUtils.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..1a2c749129c787b23c819fd42bc719de61c1aea3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/WinSockUtils.hpp
@@ -0,0 +1,25 @@
+#pragma once
+
+#include 
+
+namespace c10d::tcputil {
+
+#define CONNECT_SOCKET_OFFSET 1
+
+inline int poll(struct pollfd* fdArray, unsigned long fds, int timeout) {
+  return WSAPoll(fdArray, fds, timeout);
+}
+
+inline void addPollfd(
+    std::vector& fds,
+    int socket,
+    short events) {
+  fds.push_back({(SOCKET)socket, events});
+}
+
+inline struct ::pollfd getPollfd(int socket, short events) {
+  struct ::pollfd res = {(SOCKET)socket, events};
+  return res;
+}
+
+} // namespace c10d::tcputil
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/Work.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/Work.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..c10e5007b9f54495cec904c1d72d2247a70e60b1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/Work.hpp
@@ -0,0 +1,165 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+constexpr auto kNoTimeout = std::chrono::milliseconds(0);
+
+namespace c10d {
+
+constexpr const char* const kSeqNumStoreKey = "SEQ_NUM_STORE_KEY";
+
+enum class OpType : std::uint8_t {
+  BROADCAST = 0,
+  ALLREDUCE = 1,
+  ALLREDUCE_COALESCED = 2,
+  REDUCE = 3,
+  ALLGATHER = 4,
+  _ALLGATHER_BASE = 5,
+  ALLGATHER_COALESCED = 6,
+  GATHER = 7,
+  SCATTER = 8,
+  REDUCE_SCATTER = 9,
+  ALLTOALL_BASE = 10,
+  ALLTOALL = 11,
+  SEND = 12,
+  RECV = 13,
+  RECVANYSOURCE = 14,
+  BARRIER = 15,
+  _REDUCE_SCATTER_BASE = 16,
+  COALESCED = 17,
+  _ALLREDUCE_SPARSE = 18,
+  UNKNOWN = 100,
+};
+
+// Converts OpType to human readable string.
+TORCH_API std::string opTypeToString(OpType opType);
+
+// Whether or not an OP is an p2p op (SEND, RECV, RECVANYSOURCE)
+TORCH_API bool isP2POp(OpType opType, bool batchP2P = false);
+
+// Please do not use Work API, it is going away, to be
+// replaced by ivalue::Future.
+// Python binding for this class might change, please do not assume
+// this will be bound using pybind.
+class TORCH_API Work : public torch::CustomClassHolder {
+ public:
+  Work(
+      int rank = -1,
+      OpType opType = OpType::UNKNOWN,
+      const char* profilingTitle = nullptr,
+      const std::optional>& inputTensors =
+          std::nullopt);
+
+  ~Work() override;
+
+  // Checks if request has completed. Non-blocking operation.
+  virtual bool isCompleted();
+
+  // Returns if the work completed successfully.
+  // If false, the exception function can be called to get details.
+  virtual bool isSuccess() const;
+
+  // Returns exception if isSuccess() returned false.
+  virtual std::exception_ptr exception() const;
+
+  // Returns source rank if this objects represents a recv-from-any.
+  virtual int sourceRank() const;
+
+  // Returns result tensors, if applicable.
+  // If work is not supposed to have result, we return empty list.
+  virtual std::vector result();
+
+  // Ensures that operations on the output tensors that are invoked
+  // after this function returns are correctly sequenced after the
+  // asynchronous completion of this work.
+  //
+  // For CUDA tensors, it inserts stream synchronization such that
+  // the streams of the caller wait for completion of the
+  // asynchronous operations on the destination tensors.
+  //
+  // For CPU tensors, it is currently a nop.
+  //
+  // This function should only be used if the caller polls for
+  // completion through the `isCompleted` function, it has returned
+  // true, and the `isSuccess` function also has returned true.
+  //
+  virtual void synchronize();
+
+  // Waits until request completes. Blocking operation.
+  // Throws if the work completed with an exception.
+  // Returns false if the work is aborted.
+  // Otherwise, it always returns true, indicating the work is completed.
+  //
+  // Functionally equivalent to:
+  //
+  //   while (!isCompleted()) { /* nop */ }
+  //   auto success = isSuccess();
+  //   if (!success) { std::rethrow_exception(exception()); }
+  //   return success;
+  //
+  virtual bool wait(std::chrono::milliseconds timeout = kNoTimeout);
+
+  virtual void abort();
+
+  // Returns a Future object that will be associated with the completion of
+  // work. Only NCCL backend is currently supported.
+  virtual c10::intrusive_ptr getFuture();
+
+  virtual float getDuration() const;
+
+  virtual uint64_t getSequencenumber() const;
+
+  OpType retrieveOpType() const;
+
+  static c10::intrusive_ptr create_from_future(
+      const c10::intrusive_ptr&);
+
+ protected:
+  // Completes the work object and optionally sets the exception in a
+  // thread-safe manner. Notifies all waiting condition variables as well.
+  void finish(std::exception_ptr exception = nullptr);
+
+  // Similar to finish, but throws an exception if one is already set or
+  // provided by the user.
+  void finishAndThrow(std::exception_ptr exception);
+
+  mutable std::mutex mutex_;
+  std::condition_variable cv_;
+  bool completed_ = false;
+  std::exception_ptr exception_;
+
+  // Current rank of the node.
+  const int rank_;
+
+  // Operation type that this work object refers to.
+  OpType opType_;
+
+  // When profiling, the callback to record end of operation event. This
+  // callback needs to be called when collective operation is complete.
+  std::function recordFunctionEndCallback_;
+};
+
+struct TORCH_API WorkInfo {
+  WorkInfo(
+      const OpType& opType,
+      const uint64_t seq,
+      const std::chrono::time_point& timeStarted,
+      const std::chrono::time_point& timeFinished,
+      const std::chrono::duration& activeDuration)
+      : opType(opType),
+        seq(seq),
+        timeStarted(timeStarted),
+        timeFinished(timeFinished),
+        activeDuration(activeDuration) {}
+
+  OpType opType;
+  uint64_t seq;
+  std::chrono::time_point timeStarted;
+  std::chrono::time_point timeFinished;
+  std::chrono::duration activeDuration;
+};
+
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/c10d.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/c10d.h
new file mode 100644
index 0000000000000000000000000000000000000000..5151a33f7ee351184e53daa68155dcc6c7390358
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/c10d.h
@@ -0,0 +1,13 @@
+#pragma once
+
+#include 
+
+namespace torch {
+namespace distributed {
+namespace c10d {
+
+PyMethodDef* python_functions();
+
+} // namespace c10d
+} // namespace distributed
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/comm.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/comm.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..6f9203e214348f9f53b89b10a13e3d62fdc4403c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/comm.hpp
@@ -0,0 +1,141 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace c10d {
+
+// Broadcast many tensors to all processes in the process group.
+TORCH_API void broadcast_coalesced(
+    const c10::intrusive_ptr& process_group,
+    at::TensorList tensors,
+    size_t buffer_size,
+    int rank = 0);
+
+// This class passes bucket contents tensor to DDP communication hook.
+class TORCH_API GradBucket {
+ public:
+  explicit GradBucket(
+      size_t index,
+      size_t bucket_count,
+      at::Tensor tensor,
+      std::vector offsets,
+      std::vector lengths,
+      std::vector sizes_vec,
+      std::vector parameters,
+      std::optional sparse_grad_indices)
+      : index_(index),
+        bucket_count_(bucket_count),
+        buffer_(std::move(tensor)),
+        offsets_(std::move(offsets)),
+        lengths_(std::move(lengths)),
+        sizes_vec_(std::move(sizes_vec)),
+        parameters_(std::move(parameters)),
+        sparse_grad_indices_(std::move(sparse_grad_indices)) {}
+
+  // Returns the index of the bucket, which is unique across all the buckets.
+  size_t getIndex() const {
+    return index_;
+  }
+
+  const at::Tensor& getBuffer() const {
+    return buffer_;
+  }
+
+  // Returns a mutable buffer compared with the above method.
+  at::Tensor& getBufferRef() {
+    return buffer_;
+  }
+
+  // Overwrites the buffer at a specific index.
+  void setBuffer(at::Tensor& buffer) {
+    buffer_ = buffer;
+  }
+
+  // Each tensor in the list that getGradients corresponds to a
+  // parameter.
+  std::vector getGradients() const;
+
+  // Returns model parameters belonging to this bucket. They are returned in the
+  // same order as gradient tensors via getGradients(). For example,
+  // getParameters[i] will have its gradient stored in
+  // getGradients[i]
+  const std::vector getParameters() const {
+    return parameters_;
+  }
+
+  // Returns whther this bucket is the last bucket to allreduce in an iteration.
+  bool isLast() const {
+    return index_ == bucket_count_ - 1;
+  }
+
+  std::optional& getSparseGradIndices() {
+    return sparse_grad_indices_;
+  }
+
+ private:
+  size_t index_;
+  size_t bucket_count_;
+  at::Tensor buffer_;
+
+  // Per-variable info in buffer_.
+  std::vector offsets_;
+  std::vector lengths_;
+  std::vector sizes_vec_;
+
+  // Model parameters for this bucket.
+  // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
+  const std::vector parameters_;
+
+  // Predefined sparse indices for this bucket (only used for sparse tensors).
+  // The gradients will be updated to have indices with these tensor values
+  std::optional sparse_grad_indices_;
+};
+
+// Base class of both `PythonCommHook` and `CppCommHook`.
+// Requires implementing 1) `runHook` method that communicates gradients
+// asynchronously, and 2) `parseHookResult` method that converts the hook
+// result into a tensor.
+class TORCH_API CommHookInterface {
+ public:
+  virtual ~CommHookInterface() = default;
+
+  // Passes the input grad bucket to the registered communication hook.
+  // Once the tensor in the bucket are ready, kicks off the hook asynchronously
+  // and returns a future that holds the communication results.
+  virtual c10::intrusive_ptr runHook(
+      GradBucket& bucket) = 0;
+
+  // Returns the resulting tensor once the communication hook result is
+  // ready. The resulting tensor will then be copied to the grads of
+  // individual parameters.
+  virtual at::Tensor parseHookResult(const c10::IValue& result) = 0;
+};
+
+namespace detail {
+// This helper function is called both by CppCommHookInterface below and inside
+// reducer.
+TORCH_API at::Tensor parseCppCommHookResult(const c10::IValue& result);
+} // namespace detail
+
+// This CppCommHook interface only requires implementing runHook method that
+// potentially uses a state.
+template 
+class CppCommHookInterface : public CommHookInterface {
+ public:
+  explicit CppCommHookInterface(T state) : state_(std::move(state)) {}
+
+  ~CppCommHookInterface() override = default;
+
+  at::Tensor parseHookResult(const c10::IValue& result) override {
+    return detail::parseCppCommHookResult(result);
+  }
+
+ protected:
+  T state_;
+};
+
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/debug.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/debug.h
new file mode 100644
index 0000000000000000000000000000000000000000..8524191515190083dc1f3063405533bd2782e315
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/debug.h
@@ -0,0 +1,23 @@
+// Copyright (c) Meta Platforms, Inc. and its affiliates.
+// All rights reserved.
+//
+// This source code is licensed under the BSD-style license found in the
+// LICENSE file in the root directory of this source tree.
+
+#pragma once
+
+#include 
+
+namespace c10d {
+
+enum class DebugLevel { Off = 0, Info = 1, Detail = 2 };
+
+TORCH_API void setDebugLevel(DebugLevel level);
+
+// Sets the debug level based on the value of the `TORCH_DISTRIBUTED_DEBUG`
+// environment variable.
+TORCH_API void setDebugLevelFromEnvironment();
+
+TORCH_API DebugLevel debug_level() noexcept;
+
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/default_comm_hooks.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/default_comm_hooks.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..a4f47f13bb540509e15cc53daf4063fd2c72bd95
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/default_comm_hooks.hpp
@@ -0,0 +1,52 @@
+#pragma once
+
+#include 
+#include 
+
+namespace c10d {
+
+enum class BuiltinCommHookType : uint8_t {
+  ALLREDUCE = 1,
+  FP16_COMPRESS = 2,
+};
+
+class AllReduceCommHook
+    : public CppCommHookInterface> {
+ public:
+  explicit AllReduceCommHook(const c10::intrusive_ptr& state)
+      : CppCommHookInterface>(state) {}
+
+  ~AllReduceCommHook() override = default;
+
+  c10::intrusive_ptr runHook(GradBucket& bucket) override;
+};
+
+class FP16CompressCommHook
+    : public CppCommHookInterface> {
+ public:
+  explicit FP16CompressCommHook(const c10::intrusive_ptr& state)
+      : CppCommHookInterface>(state) {}
+
+  ~FP16CompressCommHook() override = default;
+
+  c10::intrusive_ptr runHook(GradBucket& bucket) override;
+};
+
+// Almost same as AllReduceCommHook, but without division inside the hook.
+// This enables the optimization of fusing copy and division and saves one scan
+// over all the input parameters, when no communication hook is provided by the
+// user. Only used internally and not released as a public built-in
+// communication hook.
+class _AllReduceBySumCommHook
+    : public CppCommHookInterface> {
+ public:
+  explicit _AllReduceBySumCommHook(
+      const c10::intrusive_ptr& state)
+      : CppCommHookInterface>(state) {}
+
+  ~_AllReduceBySumCommHook() override = default;
+
+  c10::intrusive_ptr runHook(GradBucket& bucket) override;
+};
+
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/error.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/error.h
new file mode 100644
index 0000000000000000000000000000000000000000..fff2b45c4c952b99b3ba2f27696cb6d2b9c29326
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/error.h
@@ -0,0 +1,56 @@
+// Copyright (c) Facebook, Inc. and its affiliates.
+// All rights reserved.
+//
+// This source code is licensed under the BSD-style license found in the
+// LICENSE file in the root directory of this source tree.
+
+#pragma once
+
+#include 
+#include 
+
+#include 
+
+namespace fmt {
+
+template <>
+struct formatter {
+  constexpr decltype(auto) parse(format_parse_context& ctx) const {
+    return ctx.begin();
+  }
+
+  template 
+  decltype(auto) format(const std::error_category& cat, FormatContext& ctx)
+      const {
+    if (std::strcmp(cat.name(), "generic") == 0) {
+      return fmt::format_to(ctx.out(), "errno");
+    } else {
+      return fmt::format_to(ctx.out(), "{} error", cat.name());
+    }
+  }
+};
+
+template <>
+struct formatter {
+  constexpr decltype(auto) parse(format_parse_context& ctx) const {
+    return ctx.begin();
+  }
+
+  template 
+  decltype(auto) format(const std::error_code& err, FormatContext& ctx) const {
+    return fmt::format_to(
+        ctx.out(), "({}: {} - {})", err.category(), err.value(), err.message());
+  }
+};
+
+} // namespace fmt
+
+namespace c10d {
+namespace detail {
+
+inline std::error_code lastError() noexcept {
+  return std::error_code{errno, std::generic_category()};
+}
+
+} // namespace detail
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/exception.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/exception.h
new file mode 100644
index 0000000000000000000000000000000000000000..a00b6f70653aaa8d4456033800c5dc69942e3b03
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/exception.h
@@ -0,0 +1,33 @@
+// Copyright (c) Facebook, Inc. and its affiliates.
+// All rights reserved.
+//
+// This source code is licensed under the BSD-style license found in the
+// LICENSE file in the root directory of this source tree.
+
+#pragma once
+
+#include 
+
+#include 
+#include 
+
+// Utility macro similar to C10_THROW_ERROR, the major difference is that this
+// macro handles exception types defined in the c10d namespace, whereas
+// C10_THROW_ERROR requires an exception to be defined in the c10 namespace.
+#define C10D_THROW_ERROR(err_type, msg) \
+  throw ::c10d::err_type(               \
+      {__func__, __FILE__, static_cast(__LINE__)}, msg)
+
+namespace c10d {
+
+using c10::DistNetworkError;
+
+class TORCH_API SocketError : public DistNetworkError {
+  using DistNetworkError::DistNetworkError;
+};
+
+class TORCH_API TimeoutError : public DistNetworkError {
+  using DistNetworkError::DistNetworkError;
+};
+
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/intra_node_comm.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/intra_node_comm.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..37fe285cb929ee46161d0f89d52ffa7fe25b4112
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/intra_node_comm.hpp
@@ -0,0 +1,152 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace c10d::intra_node_comm {
+
+using namespace c10d::symmetric_memory;
+
+constexpr size_t kMaxDevices = 8;
+constexpr size_t kDefaultBufferSize = 10ull * 1024 * 1024;
+constexpr size_t kP2pStateSize = 2048;
+
+using NvlMesh = std::array, kMaxDevices>;
+using HybridCubeMesh = std::array, kMaxDevices>;
+
+enum class Topology : uint8_t {
+  UNKNOWN = 0,
+  FULLY_CONNECTED = 1,
+  HYBRID_CUBE_MESH = 2
+};
+
+enum class AllReduceAlgo : uint8_t {
+  NONE = 0,
+  ONE_SHOT = 1,
+  TWO_SHOT = 2,
+  HCM = 3
+};
+
+// NOTE: this class will be be removed soon in favor of SymmetricMemory
+class TORCH_API IntraNodeComm : public c10::intrusive_ptr_target {
+ public:
+  IntraNodeComm(
+      c10::intrusive_ptr store,
+      size_t rank,
+      size_t worldSize,
+      std::optional bufferSize = std::nullopt);
+
+  ~IntraNodeComm() override;
+
+  static bool isEnabled();
+
+  /**
+   * Performs rendezvous.
+   * If rendezvous fails, the IntraNodeComm object will be in an invalid
+   * state and it is the caller's responsibility to dispose it.
+   */
+  bool rendezvous();
+
+  Topology getTopology() {
+    return topology_;
+  }
+
+  size_t getBufferSize() {
+    return bufferSize_;
+  }
+
+  /**
+   * Selects a AllReduceAlgo that we think will outperform nccl.
+   * Returns AllReduceAlgo::NONE if we don't think we can outperform nccl.
+   */
+  AllReduceAlgo selectAllReduceAlgo(const at::Tensor& input);
+
+  at::Tensor allReduce(const at::Tensor& input, AllReduceAlgo algo);
+
+  /**
+   * Perform a barrier among the specified ranks.
+   */
+  void barrier(std::optional> ranks = std::nullopt);
+
+  at::Tensor getBuffer(
+      size_t rank,
+      const std::vector& sizes,
+      c10::ScalarType dtype,
+      int64_t storageOffset);
+
+ private:
+  at::Tensor oneShotAllReduce(
+      const at::Tensor& input,
+      at::cuda::CUDAStream& stream);
+
+  at::Tensor twoShotAllReduce(
+      const at::Tensor& input,
+      at::cuda::CUDAStream& stream);
+
+  at::Tensor hybridCubeMeshAllReduce(
+      const at::Tensor& input,
+      at::cuda::CUDAStream& stream);
+
+  c10::intrusive_ptr store_;
+  size_t rank_;
+  size_t worldSize_;
+  size_t bufferSize_;
+  at::cuda::CUDAEvent barrierReady_;
+
+  /**
+   * Members initialized after rendezvous
+   */
+  bool isInitialized_ = false;
+  int deviceIdx_;
+  Topology topology_ = Topology::UNKNOWN;
+  void* symmetricMemoryPtr_ = nullptr;
+  c10::intrusive_ptr symmetricMemory_ = nullptr;
+  void* p2pStatesDev_{};
+  void* buffersDev_{};
+  void* topoInfo_{};
+};
+
+/**
+ * NOTE [IntraNodeComm Stream Semantics]
+ *
+ * ProcessGroupNCCL launches kernels differently from the conventional PyTorch
+ * CUDA semantics: it always launches collective kernels onto a dedicated
+ * communication stream. Therefore, it needs to:
+ *
+ * - Synchronize the calling stream and the comm stream.
+ * - Ensure the memory safety of the operands (via record_stream or stashing).
+ * - Synchronize the waiting stream with the comm stream.
+ *
+ * Unconditionally performing these tasks makes sense when we expect most of the
+ * communication to benefit from compute/comm overlap. However, IntraNodeComm
+ * primarily aims to optimize small, latency-sensitive, blocking communication,
+ * in which the overhead incurred by the above steps can be quite pronounced.
+ *
+ * Thus, IntraNodeComm follows the conventional PyTorch CUDA semantics and
+ * launches kernels onto the stream specified by the user. Although the user
+ * can perform neccessary synchronization via wait_stream, to provide a UX
+ * consistent to that of ProcessGroupNCCL, the neccessary stream
+ * synchronization can also be performed via IntraNodeWork::wait().
+ */
+class IntraNodeCommWork : public c10d::Work {
+ public:
+  IntraNodeCommWork() : c10d::Work() {
+    event_.record();
+  }
+
+  bool wait(std::chrono::milliseconds timeout = kNoTimeout) override {
+    event_.block(at::cuda::getCurrentCUDAStream());
+    return true;
+  }
+
+ private:
+  at::cuda::CUDAEvent event_;
+};
+
+TORCH_API int64_t getIntraNodeCommUsageCounter();
+
+} // namespace c10d::intra_node_comm
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/logger.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/logger.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..d2949a4f6745ac2d324ce426fd7c98d080ba6e8f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/logger.hpp
@@ -0,0 +1,138 @@
+#include 
+#include 
+
+#include 
+
+namespace c10d {
+
+class TORCH_API Logger {
+ public:
+  explicit Logger(std::shared_ptr reducer);
+  // Set logging data that can be got during DistributedDataParallel
+  // construction time.
+  void set_construction_data_and_log(
+      const std::string& module_name,
+      const std::vector& device_ids,
+      int output_device,
+      bool broadcast_buffers,
+      bool has_sync_bn,
+      bool static_graph);
+
+  void set_static_graph();
+
+  // An interface for users to get DDPLoggingData and log them
+  // in the applications. Explanation of logging fields are in
+  // "struct DDPLoggingData" of "torch/c10/util/Logging.h".
+  at::DDPLoggingData get_ddp_logging_data();
+
+  // Stream insertion operator for logging data to stream under
+  // TORCH_DISTRIBUTED_DEBUG.
+  friend std::ostream& operator<<(std::ostream& output, const Logger& logger);
+
+  ~Logger() noexcept(false) {
+    // Log if DDP graph is static in Logger dtor instead of Reducer dtor since
+    // Logger is deleted before Reducer.
+    log_if_graph_static(reducer_->ddp_graph_static());
+  }
+
+  // Set environment variables.
+  void set_env_variables();
+  // Set parameters stats.
+  void set_parameter_stats();
+  // Get size of each bucket (Bytes).
+  std::vector get_bucket_sizes();
+  // Get variable indices for each bucket.
+  std::vector> get_per_bucket_variable_indices();
+  // Set comm. hook, if used
+  void set_comm_hook(const std::string& hook);
+  // Set running with uneven input detection (model.join() context manager)
+  void set_uneven_input_join();
+
+  // Reset performance stats at current iteration
+  void reset_performance_stats();
+
+  // Calculate avg stats using cpu timer and gpu timer
+  // that has been recorded in reducer.
+  void calculate_avg_time(
+      int64_t& avg_time,
+      int64_t& time_duration,
+      Timer& timer,
+      Timer::Event start_event,
+      Timer::Event end_event);
+
+  // Set the absolute time of the event that has been recorded in reducer.
+  void set_event_time(int64_t& event_time, Timer& timer, Timer::Event event);
+  // Set stats that can be collected only during
+  // training loop. It is called at the beginning of forward call
+  // to record the run time stats of sampled iterations that previously ran.
+  // GPU performance stats are collected only for single process
+  // single device program and single device module right now.
+  // TODO to support single process multiple devices and multi device modules,
+  // events need to be created and recorded on multiple devices.
+  void set_runtime_stats_and_log();
+
+  // Called when DDP/reducer is failing with an error. The
+  // logging data structure will have two fields filled: "has_error" indicating
+  // that this iteration encountered an error and other fields are not valid,
+  // and "error", a string which contains the error message that DDP failed
+  // with.
+  template 
+  void set_error_and_log(const std::string& ddp_error, const Args&... args) {
+    ddp_logging_data_->ints_map["has_error"] = 1;
+    auto err = c10::str(ddp_error, args...);
+    ddp_logging_data_->strs_map["error"] = err;
+    // Report the iteration we are erroring at so user knows how many examples
+    // successfully processed before this error was hit.
+    ddp_logging_data_->ints_map["iteration"] = reducer_->num_iterations_;
+    at::LogPyTorchDDPUsage(*ddp_logging_data_);
+  }
+
+  // When running without static graph, called when reducer is destroyed to log
+  // if graph was actually static and is a candidate for static graph
+  // optimization.
+  void log_if_graph_static(bool is_static);
+
+ private:
+  // ddp_logging_data_ is used to hold all the ddp related logging
+  // data fields.
+  std::unique_ptr ddp_logging_data_;
+  std::shared_ptr reducer_;
+  // track the number of iterations when runtime stats are collected so far.
+  long num_iterations_stats_recorded_ = 0;
+};
+
+// a generic logging data struct that holds different types of logging data.
+// starting with key value pairs of strings and integers,
+// It can be extended to more types as needed.
+struct C10dLoggingData {
+  // logging fields that are string types.
+  std::map strings;
+  // logging fields that are int64_t types.
+  std::map integers;
+};
+
+class TORCH_API C10dLogger {
+ public:
+  C10dLogger(const C10dLogger&) = default;
+  C10dLogger(C10dLogger&&) = delete;
+  C10dLogger& operator=(const C10dLogger&) = default;
+  C10dLogger& operator=(C10dLogger&&) = delete;
+  virtual ~C10dLogger() = default;
+  virtual void log(const C10dLoggingData& data);
+  static C10dLogger* getLogger();
+  static void registerLogger(std::unique_ptr);
+
+ protected:
+  // singletion, hide constructor from the public
+  C10dLogger(std::string logDestination)
+      : logDestination_(std::move(logDestination)) {}
+
+  // the name of the destination this logger should log to
+  std::string logDestination_;
+
+ private:
+  static std::unique_ptr logger_;
+  static std::atomic registered_;
+};
+
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/logging.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/logging.h
new file mode 100644
index 0000000000000000000000000000000000000000..b4df02e773807ee8786570cf0044f0d3615ff592
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/logging.h
@@ -0,0 +1,51 @@
+// Copyright (c) Meta Platforms, Inc. and its affiliates.
+// All rights reserved.
+//
+// This source code is licensed under the BSD-style license found in the
+// LICENSE file in the root directory of this source tree.
+
+#pragma once
+
+#include 
+
+#include 
+#include 
+#include 
+
+namespace c10d {
+namespace detail {
+
+enum class LogLevel { Trace, Debug, Info, Warning, Error };
+
+TORCH_API bool isLogLevelEnabled(LogLevel level) noexcept;
+
+template 
+std::string formatLogMessage(fmt::string_view fmt, T&&... args) {
+  return fmt::vformat(fmt, fmt::make_format_args(args...));
+}
+
+} // namespace detail
+} // namespace c10d
+
+#define C10D_ERROR(...)                                                      \
+  LOG_IF(                                                                    \
+      ERROR, c10d::detail::isLogLevelEnabled(c10d::detail::LogLevel::Error)) \
+      << "[c10d] " << c10d::detail::formatLogMessage(__VA_ARGS__)
+
+#define C10D_WARNING(...)                                               \
+  LOG_IF(                                                               \
+      WARNING,                                                          \
+      c10d::detail::isLogLevelEnabled(c10d::detail::LogLevel::Warning)) \
+      << "[c10d] " << c10d::detail::formatLogMessage(__VA_ARGS__)
+
+#define C10D_INFO(...)                                                        \
+  LOG_IF(INFO, c10d::detail::isLogLevelEnabled(c10d::detail::LogLevel::Info)) \
+      << "[c10d] " << c10d::detail::formatLogMessage(__VA_ARGS__)
+
+#define C10D_DEBUG(...)                                                        \
+  LOG_IF(INFO, c10d::detail::isLogLevelEnabled(c10d::detail::LogLevel::Debug)) \
+      << "[c10d - debug] " << c10d::detail::formatLogMessage(__VA_ARGS__)
+
+#define C10D_TRACE(...)                                                        \
+  LOG_IF(INFO, c10d::detail::isLogLevelEnabled(c10d::detail::LogLevel::Trace)) \
+      << "[c10d - trace] " << c10d::detail::formatLogMessage(__VA_ARGS__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/python_comm_hook.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/python_comm_hook.h
new file mode 100644
index 0000000000000000000000000000000000000000..48ad7cefae9418ffc989a334aa8b2636ec110219
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/python_comm_hook.h
@@ -0,0 +1,34 @@
+#pragma once
+
+#include 
+
+#include 
+#include 
+#include 
+#include 
+
+namespace c10d {
+
+class TORCH_PYTHON_API PythonCommHook : public CommHookInterface {
+ public:
+  // Takes a state and a callable hook. The inputs are Python objects.
+  // The state is passed to the hook in runHook method, and it can be used to
+  // maintain and update any state information during the execution of the hook.
+  // The hook performs user-specified processing and returns a future indicating
+  // asychronous communication of gradients.
+  PythonCommHook(py::object state, py::object hook)
+      : state_(std::move(state)), hook_(std::move(hook)) {}
+
+  ~PythonCommHook() override;
+
+  c10::intrusive_ptr runHook(GradBucket& bucket) override;
+
+  at::Tensor parseHookResult(const c10::IValue& result) override;
+
+ private:
+  // Only needed for stateful communication.
+  py::object state_;
+  py::object hook_;
+};
+
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/reducer.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/reducer.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..aa3c40ae95bbf2f453d50712a108799d6eba72fe
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/reducer.hpp
@@ -0,0 +1,587 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#ifndef _WIN32
+#include 
+#endif
+
+namespace c10d {
+
+constexpr int kDefaultFirstBucketBytes = int(1024 * 1024);
+constexpr int kDefaultBucketBytesCap = int(25 * 1024 * 1024);
+// Collect runtime stats once for every kDDPRuntimeLoggingSampleRate iterations.
+constexpr int kDDPRuntimeLoggingSampleRate = 100;
+
+// Forward declaration
+class Logger;
+
+// Local accumulator type for a single bucket.
+struct BucketAccumulator {
+  std::vector indices;
+  size_t size = 0;
+  size_t size_limit = 0;
+};
+
+class TORCH_API Reducer {
+ public:
+  // The constructor takes a list of variables (i.e. parameters) for this
+  // process's single model replica (as DDP assumes single-process
+  // single-device). The bucket assignment for this reducer, `bucket_indices`,
+  // is specified as a list of buckets, each of which is specified as a list of
+  // indices into the bucket's `variables` list.
+  explicit Reducer(
+      std::vector params,
+      std::vector> bucket_indices,
+      const std::vector& per_bucket_size_limits,
+      c10::intrusive_ptr process_group,
+      std::vector expect_sparse_gradients,
+      int64_t bucket_bytes_cap,
+      bool find_unused_parameters,
+      bool gradient_as_bucket_view,
+      std::unordered_map param_names,
+      int64_t first_bucket_bytes_cap);
+
+  ~Reducer() noexcept(false);
+
+  // To (re-)initialize bucket assignment, pass a list of buckets, each of
+  // which is specified by a list of indices in the bucket's `variables` list.
+  // This function performs validation that the variables within a bucket
+  // all live on the same device and have the same dimensionality.
+  void initialize_buckets(std::vector> bucket_indices);
+
+  void autograd_hook(size_t index);
+
+  // This function is called when the forward function has produced an output,
+  // and the user wishes to reduce gradients in the backwards pass.
+  // If they don't, and wish to accumulate gradients before reducing them,
+  // a call to this function can simply be omitted.
+  void prepare_for_backward(const std::vector& outputs);
+
+  // Called at the beginning of forward() inside DistributedDataParallel,
+  // right now it captures the starting time of forward in each iteration.
+  void prepare_for_forward();
+
+  // Returns the relative time in nanoseconds when gradients were ready,
+  // with respect to the time `prepare_for_backward` was called. The
+  // vector is for parameters for a single model replica.
+  std::vector get_backward_stats() const {
+    return backward_stats_;
+  }
+
+  // Registers a hook to the reducer. The hook is `CommHookInterface`
+  // type to allow both Python and CPP hooks. This function can only
+  // be called once before calling backward.
+  // Cannot combine with the call of `register_builtin_comm_hook`.
+  void register_comm_hook(std::unique_ptr iface);
+
+  // Registers a built-in C++ comm hook to the reducer. This function can only
+  // be called once before calling backward.
+  // Cannot combine with the call of `register_comm_hook`.
+  void register_builtin_comm_hook(c10d::BuiltinCommHookType comm_hook_type);
+
+  // Informs reducer that optimizer is running in backward, so gradients
+  // don't need to be copied from buckets as the optimizer would've already
+  // been applied.
+  void set_optimizer_in_backward() {
+    optim_in_backward_ = true;
+  };
+
+  // Runs allreduce or installed communication hook given GradBucket instance.
+  c10::intrusive_ptr run_comm_hook(
+      GradBucket& grad_bucket);
+
+  // Runs default allreduce hook.
+  c10::intrusive_ptr run_allreduce_hook(
+      GradBucket& grad_bucket);
+
+  // Returns gradient buckets in sequential order of buckets_. This is the order
+  // in which buckets are reduced across processes. If return_zero_tensors=true,
+  // will return zero tensors of the same shape instead of the true tensors.
+  std::vector get_grad_buckets(
+      bool return_zero_tensors = true) const;
+
+  // Rebuild buckets based on rebuilt_params_ and rebuilt_param_indices_
+  // according to when tensors received grads in the backward pass.
+  // TODO this function makes broadcast communication call and
+  // could be overlapped with next forward() call, thus
+  // it could be async. Will make it async when rebuilding buckets for
+  // find_unused_parameters = true case, as we could rebuild buckets more than
+  // once for find_unused_parameters = true case, where subgraphs are trained
+  // and parameter indices order may change more frequently.
+  // For find_unused_parameters = false case, buckets are only rebuilt once,
+  // the performance cost is negligible. Returns true if the buckets were
+  // rebuilt.
+  bool rebuild_buckets();
+
+  void setSparseMetadata(std::map& metadata);
+
+  // Install futures that should be awaited at end of backwards. Currently these
+  // are only used by user-defined custom buffer reduction hooks, but can be
+  // generalized to any user-originating futures that need to be awaited.
+  void install_futures(c10::List> futs);
+
+  // Returns true if we should rebuild buckets, else false. We only rebuild
+  // buckets once after the first iteration and never rebuild them if
+  // find_unused_parameters_.
+  inline bool should_rebuild_buckets() const {
+    return (static_graph_ || !find_unused_parameters_) && !has_rebuilt_bucket_;
+  }
+
+  // Pushes all parameters to be rebuilt.
+  void push_rebuilt_params_for_all_indices();
+
+  // Creates and sets ForwardPassWorkHandle given a Work and the
+  // corresponding tensor being reduced.
+  void set_forward_pass_work_handle(
+      c10::intrusive_ptr forwardPassWorkHandle,
+      bool useStaticWorldSize);
+
+  // Retrieve on-device tensors used to track locally unused parameters. It is
+  // a tensor where index i = 1 if the Variable with that index has been used.
+  at::Tensor get_local_used_map_on_device() const;
+
+  // An function for users to set sample_rate of collecting
+  // runtime stats. The time stats will be recorded for the
+  // first 10 iterations, after 10 iterations time stats will be
+  // recorded once every "sample_rate" training iterations.
+  void set_ddp_runtime_logging_sample_rate(int sample_rate);
+
+  // Specify the training graph is static.
+  void set_static_graph();
+
+  // Delay all reduce to be after all gradients' calculation is complete.
+  void delay_all_reduce();
+
+  void set_mixed_precision_param_dtype(c10::ScalarType dtype);
+
+  // Weak reference to associated DDP logger. The reference is weak to avoid
+  // refcycle between reducer and logger.
+  void set_logger(std::weak_ptr logger);
+
+  // When graph is not explicitly set by user as static and has unused
+  // parameters, this will return whether the graph has been static until the
+  // current iteration, which means unused params set has not changed.
+  bool ddp_graph_static();
+
+  // Removes autograd hooks registered by the Reducer on the model parameters.
+  void remove_autograd_hooks();
+
+  // Checks whether or not the reducer has finalized the current backward
+  // iteration.
+  void check_finalized();
+
+  // Updates the underlying process group used by DDP with the new process
+  // group.
+  void update_process_group(
+      c10::intrusive_ptr new_process_group);
+
+  // Resets reducer state.
+  void reset_state();
+
+ protected:
+  // Forward declaration.
+  struct Bucket;
+
+  void push_rebuilt_params(const size_t& index);
+
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  mutable std::mutex mutex_;
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  const std::vector params_;
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  c10::intrusive_ptr<::c10d::ProcessGroup> process_group_;
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  std::vector expect_sparse_gradients_;
+
+  std::vector>
+      grad_accumulators_; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes)
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  std::unordered_map gradAccToVariableMap_;
+  std::vector>>
+      hooks_; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes)
+
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  bool expect_autograd_hooks_;
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  bool require_finalize_;
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  size_t next_bucket_;
+
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  bool has_marked_unused_parameters_;
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  const bool find_unused_parameters_;
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  const bool gradient_as_bucket_view_;
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  std::vector unused_parameters_;
+  // Previous iteration's unused params, used for checking if unused parameters
+  // change between iterations. Only filled during the first backwards call.
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  std::vector prev_iteration_unused_parameters_;
+  // Whether graph is static or not. When user does not explicitly set static
+  // graph, the only possible dynamism is set of unused parameters changing
+  // between iterations which is tracked by this flag.
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  bool ddp_graph_static_{true};
+  // Locally used parameter maps indicating if parameters are used locally
+  // during the current iteration or no_sync session if no_sync is on.
+  // Each map is a one-dim int32 tensor of number of parameters. These tensors
+  // are marked in autograd_hook to indicate the corresponding param has been
+  // used, and get allreduced in the end of backward step of current iteration
+  // or no_sync session for figuring out the globally unused parameters.
+  //
+  // local_used_map_:     CPU tensor for bookkeeping locally used params
+  // local_used_map_dev_: dev tensor for reducing globally unused params
+  at::Tensor local_used_map_;
+  at::Tensor local_used_map_dev_;
+  // Indicate that reduction is done and D2H copy is done as well.
+  bool local_used_map_reduced_;
+
+  // Weak pointer to associated DDP logger.
+  std::weak_ptr logger_;
+  // List of futures installed by Reducer::install_futures that should be
+  // awaited at the end of backwards pass.
+  std::optional>>
+      installed_futures_{std::nullopt};
+  // Mixed precision parameter dtype for bucket type checking.
+  std::optional mixed_precision_param_dtype_{std::nullopt};
+
+  // Work handle for allreduce on local_used_map_
+  c10::intrusive_ptr local_used_work_;
+
+  void mark_variable_ready_dense(size_t variable_index);
+
+  void mark_variable_ready_sparse(size_t variable_index);
+
+  void mark_variable_ready(size_t variable_index);
+
+  void mark_bucket_ready(size_t bucket_index);
+
+  void finalize_bucket_dense(Bucket& bucket);
+
+  void finalize_backward();
+
+  // Returns list of model parameters corresponding to the given bucket.
+  // bucket_index is a key to cache after buckets are rebuilt, after which this
+  // mapping never changes.
+  std::vector get_variables_for_bucket(
+      size_t bucket_index,
+      const Bucket& bucket) const;
+
+  // Asserts that the reduction for the previous iteration has finished before
+  // rebuilding buckets or kicking off the next one.
+  void ensure_prior_reduction_finished();
+
+  // Broadcast rebuilt buckets from rank 0 to other ranks before initializing
+  // the buckets
+  void sync_bucket_indices(std::vector>& bucket_indices);
+
+  // We'd like to use DistAutogradContext::GradCallback here but dist autograd
+  // doesn't exist under Windows. So we just directly use the concrete type but
+  // to preserve and enforce our original intent we do a static assert when dist
+  // autograd is available.
+  using GradCallback = std::function;
+#ifndef _WIN32
+  static_assert(
+      std::is_same_v<
+          GradCallback,
+          torch::distributed::autograd::DistAutogradContext::GradCallback>);
+#endif
+  void runGradCallbackForVariable(at::Tensor& variable, GradCallback&& cb);
+
+  // This function is called inside `initialize_buckets()`. It initializes both
+  // `bucket_views_in` and `bucket_views_out` with views for each variable's
+  // gradient into the bucket's flattened `gradients` tensor. Views serve as
+  // entry points to `copy_()` each grad's data in/out of the flattened
+  // `gradients` tensor.
+  void initialize_bucket_views(Bucket& bucket);
+
+  // This function is called inside `finalize_backward`, it happens only if
+  // DDP communication hook was registered to recreate just bucket_views_out
+  // with the result of `future_work`.
+  void populate_bucket_views_out(Bucket& bucket, at::Tensor& tensor);
+
+  // If gradient_as_bucket_view_ is false, after allreduce buckets,
+  // copy bucket results back to grads.
+  void copy_bucket_to_grad(
+      at::Tensor& variable,
+      Reducer::Bucket& bucket,
+      size_t intra_bucket_index,
+      bool global_unused);
+  // Check layout of grad and bucket_view before copying the grad to bucket.
+  void check_grad_layout(const at::Tensor& grad, const at::Tensor& bucket_view);
+
+  // A bucket contains [1..N] gradients to be reduced, where the gradients
+  // have the same dtype and device.
+  // Coalescing gradients together before reducing can result in lower overhead
+  // and/or faster time to completion. Coalescing requires the constituent
+  // gradients to have the same dtype and device, and the resulting flattened
+  // tensor uses that common dtype and device. The flattened tensor is filled
+  // as the corresponding gradients are computed (triggered by autograd hooks),
+  // and the buckets are reduced in a predetermined order consistent across
+  // processes.
+  struct Bucket {
+    // Gradients of the bucket flattened into a 1-dimensional tensor
+    at::Tensor gradients;
+
+    // Views into the `gradients` tensor for each individual gradient
+    // Each view is created with layout (size and stride) matching the
+    // gradient's expected layout (see the "Gradient Layout Contract" in
+    // torch/csrc/autograd/functions/accumulate_grad.h).
+    // `bucket_views_in[i].copy_(grad)` and `grad.copy_(bucket_views_out[i])`
+    // provide convenient ways to copy gradient data in/out of `gradients`,
+    // respectively.
+    // We keep both `bucket_views_in` and `bucket_views_out` because
+    // registering a DDP communication hook may re-initialize
+    // `bucket_views_out` with the value of the hook's `future_work` but we
+    // still need separate views into the bucket's original flattened gradient
+    // to copy in gradient data.
+    std::vector bucket_views_in;
+    std::vector bucket_views_out;
+
+    // Variables whose gradients are held in this bucket
+    // We use refcounted tensors here so that we can easily unflatten the
+    // bucket's flattened `gradients` tensor into the participating variables
+    // after reduction has completed.
+    std::vector variables;
+
+    // Per-variable offset/length into the flattened `gradients` tensor and
+    // the corresponding `GradBucket` instance for communication hooks
+    std::vector offsets;
+    std::vector lengths;
+
+    // Per-variable sizes slicing into the bucket's `gradients` tensor
+    std::vector sizes_vec;
+
+    // Number of gradients left to be computed before the bucket is ready to
+    // be reduced
+    size_t pending;
+
+    // Global indices of participating variables in the bucket
+    std::vector variable_indices;
+
+    // Future work handle for DDP communication hook
+    // If no hook is registered, a temporary vanilla allreduce hook is used.
+    c10::intrusive_ptr future_work;
+
+    // If this bucket should expect a single sparse gradient
+    // If `true`, then this implies that `bucket.variables.size() == 1`.
+    bool expect_sparse_gradient = false;
+
+    // Sparse indices tensor
+    std::optional sparse_tensor_indices = std::nullopt;
+
+    // TODO(@pietern)
+    // Memory copies from gradient tensors into the bucket are potentially
+    // done on different CUDA streams. We record an event for every copy
+    // so that we can synchronize with them prior to kicking off the reduction.
+    // std::vector events;
+  };
+
+  std::vector buckets_;
+
+  // A variable locator locates a particular variable in the reducer's buckets
+  struct VariableLocator {
+    // Index of the bucket containing the variable in the `buckets_` vector
+    size_t bucket_index;
+    // Index of the variable in the bucket, which may be used consistently
+    // across `bucket_views_in`, `bucket_views_out`, `variables`, `offsets`,
+    // `lengths`, `sizes_vec`, and `variable_indices` in `Bucket`
+    size_t intra_bucket_index;
+
+    VariableLocator() = default;
+
+    VariableLocator(size_t bucket_index_, size_t intra_bucket_index_)
+        : bucket_index(bucket_index_),
+          intra_bucket_index(intra_bucket_index_) {}
+  };
+
+  // Map the index of a variable to its location in the bucket structure.
+  std::vector variable_locators_;
+
+  // track the number of iterations to synchronize grads in training so far.
+  long num_iterations_;
+  // track distinct iteration of backward call. This is distinct from
+  // num_iterations_, for example in the case of multiple forward before
+  // backward.
+  long num_bwd_calls_;
+  // whether the first autograd hook for a distinct backward pass has been
+  // called.
+  bool first_autograd_hook_called_;
+  // track the number of buckets that have been ready for
+  // communication calls like allReduce or communication hooks.
+  int num_buckets_ready_;
+
+  // Timing information.
+  int64_t backward_compute_start_time_ = -1;
+  std::unique_ptr timer_;
+
+  // We collect the relative timestamp of every gradient being ready
+  // when executing autograd. This can be used to derive a timeline of
+  // the point in time buckets were ready, or ideal bucket assignment/ordering.
+  std::vector backward_stats_;
+
+  bool should_collect_runtime_stats();
+  void record_forward_compute_start_time();
+  void record_backward_compute_start_time();
+  void record_backward_compute_end_time();
+  void record_backward_comm_start_time();
+  void record_backward_comm_end_time();
+
+  int get_ddp_runtime_logging_sample_rate();
+  int ddp_runtime_logging_sample_rate_ = kDDPRuntimeLoggingSampleRate;
+
+  bool is_multi_device_module_ = false;
+
+  // Following variables are to help build dynamic bucket order
+  bool has_rebuilt_bucket_;
+  std::vector rebuilt_params_;
+  std::vector rebuilt_param_indices_;
+  const int64_t bucket_bytes_cap_;
+
+#ifndef _WIN32
+  struct RpcContext {
+    using ContextPtr = torch::distributed::autograd::ContextPtr;
+    // The shared_ptr is to hold the context instance.
+    ContextPtr context_ptr_holder;
+    std::atomic context_ptr{nullptr};
+
+    void set(ContextPtr&& new_context_ptr);
+  };
+  RpcContext rpc_context_;
+#endif
+
+  // A struct containing work handle and tensor for allreduce scheduled in
+  // forward pass, if applicable.
+  struct ForwardPassAllreduceWork {
+    c10::intrusive_ptr workHandle;
+    at::Tensor resultTensor;
+    // whether we should divide by the initial world_size or the no. of
+    // remaining DDP ranks.
+    bool useStaticWorldSize;
+  };
+
+  // Handle for the currently scheduled allreduce in the forward pass, if
+  // applicable.
+  ForwardPassAllreduceWork forwardPassWorkHandle_;
+
+  // Division factor for reduction of gradients.
+  // Equal to the process group size, with an exception of handling uneven
+  // input.
+  int div_factor_;
+
+  bool static_graph_;
+
+  // Key: size_t (index), Value: the number of times that a variable's
+  // autograd_hook() should be triggered before marking this variable's grad as
+  // ready for communication. Map will not change after 1st iteration.
+  std::unordered_map numGradHooksTriggeredMap_;
+  // Key: size_t (index), Value: the number of times that a variable's
+  // autograd_hook() are left to be triggered before marking this variable's
+  // grad as ready for communication. Map will change after 1st iteration to
+  // track a grad is ready for communication or not.
+  std::unordered_map numGradHooksTriggeredMapPerIteration_;
+
+ private:
+  // reset counting for buckets before backward starts
+  void reset_bucket_counting();
+  // search unused parameters beore backward starts
+  void search_unused_parameters(
+      const std::vector& outputs);
+  void set_divide_factor();
+  // kick off all reduce for the ready bucket
+  void all_reduce_bucket(Bucket& bucket);
+  // kick off all reduce to local used map, it can help find global unused
+  // parameters
+  void all_reduce_local_used_map();
+  // initialize locally used parameter maps
+  void initialize_local_used_map();
+  // get current cuda stream
+  const c10::Stream get_current_stream();
+  bool dynamic_graph_find_unused();
+  bool static_graph_first_iteration();
+  bool static_graph_after_first_iteration();
+
+  // comm_hook_ is used to access the DDP communication hook if registered.
+  std::unique_ptr comm_hook_;
+
+  // Sparse metadata contains the indices that will be used
+  // when calling into sparse allreduce.
+  // This is only used in the sparse allreduce collective calls
+  std::unique_ptr> sparse_metadata_;
+
+  // Debug level setting. It is parsed once when Reducer is constructed, and
+  // remains the same across a single invocation of DDP training.
+  DebugLevel ddp_debug_level_;
+  // Mapping of variable index to fully qualified name of model to notify users
+  // about errors when certain parameters do not get gradient.
+  std::unordered_map param_names_;
+  // Variable indices stored sequentially in order of when the gradient is ready
+  // for the current backwards pass.
+  std::vector grad_ready_order_indices_;
+  // Bytes capacity of first bucket, can be configured by user
+  int64_t first_bucket_bytes_cap_;
+  // Per iteration set of parameter indices that have been marked ready.
+  std::unordered_set perIterationReadyParams_;
+  // Retrieves parameter names that have not been marked as ready as part of
+  // previous iteration.
+  std::vector getUnmarkedParamsForIteration();
+  // Retrieves parameter indices that have not been marked as ready as part of
+  // previous iteration.
+  std::vector getUnmarkedParamIndicesForIteration();
+  // Raises appropriate error if mark_variable_ready is called on the same
+  // variable twice, which is unexpected.
+  void checkAndRaiseMarkedTwiceError(size_t curVariableIndex);
+  // Retrieves parameter corresponding to the given VariableIndex.
+  at::Tensor& get_param_from_index(size_t index);
+
+  // Cached bucket index to model parameter mapping. Populated after buckets
+  // are rebuilt after which this mapping is static.
+  mutable std::unordered_map>
+      cached_variables_for_bucket_;
+
+  bool optim_in_backward_{false};
+  friend class Logger;
+};
+
+// This is equivalent to take_tensors but returns indices into the
+// tensor list argument for bucket assignment. Also, it is aware
+// of device placement and will not allow buckets to span devices.
+// The index of tensors[i] assigned to bucket is tensor_indices[i],
+// when tensor_indices is empty, the index of tensors[i] assigned to
+// bucket is i.
+TORCH_API std::tuple>, std::vector>
+compute_bucket_assignment_by_size(
+    const std::vector& tensors,
+    const std::vector& bucket_size,
+    const std::vector& expect_sparse_gradient = {},
+    const std::vector& tensor_indices = {},
+    const std::optional>& logger = {});
+
+// Verify models across all processes are the same as model on rank 0 with
+// respect to no. of params and matching dtype/size/layout.
+TORCH_API void verify_params_across_processes(
+    const c10::intrusive_ptr& process_group,
+    const std::vector& params,
+    const std::optional>& logger);
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/reducer_timer.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/reducer_timer.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..dbea3958db43daad99adf3021cbc157e4ec0fc28
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/reducer_timer.hpp
@@ -0,0 +1,81 @@
+#pragma once
+#include 
+#include 
+
+namespace c10d {
+constexpr int kUnsetTime = -1;
+
+inline int64_t current_time_in_nanos() {
+  return c10::getTime();
+}
+
+class TORCH_API Timer {
+ private:
+  // The timestamp of forward call start time in each iteration.
+  int64_t forward_start_time = kUnsetTime;
+  // The timestamp of backward computation start and end time in each
+  // iteration.
+  int64_t backward_compute_start_time = kUnsetTime;
+  int64_t backward_compute_end_time = kUnsetTime;
+  // The timestamp of first communication call start time in each iteration.
+  int64_t backward_comm_start_time = kUnsetTime;
+  // The timestamp of last communication call end time in each iteration.
+  int64_t backward_comm_end_time = kUnsetTime;
+
+ public:
+  enum class Event : uint8_t {
+    kForwardStart,
+    kBackwardComputeStart,
+    kBackwardComputeEnd,
+    kBackwardCommStart,
+    kBackwardCommEnd,
+  };
+
+  // Record the current event, i.e., mark it as having occurred now. Default
+  // CPU implementation.
+  virtual void record(Event event) {
+    getTimeRef(event) = current_time_in_nanos();
+  }
+
+  // Return the difference between when two events occurred, in nanoseconds.
+  // Or nullopt if one of them hasn't been recorded.
+  virtual std::optional measureDifference(Event start, Event end) = 0;
+
+  virtual ~Timer() = default;
+
+  // Return host-side timestamp, or nullopt if it has not yet been recorded.
+  std::optional getTimestamp(Event event) {
+    auto time = getTimeRef(event);
+    if (time == kUnsetTime) {
+      return std::nullopt;
+    } else {
+      return time;
+    }
+  }
+
+  // Return host-side time member variable corresponding to the given event.
+  int64_t& getTimeRef(Event event) {
+    switch (event) {
+      case Event::kForwardStart:
+        return forward_start_time;
+      case Event::kBackwardComputeStart:
+        return backward_compute_start_time;
+      case Event::kBackwardComputeEnd:
+        return backward_compute_end_time;
+      case Event::kBackwardCommStart:
+        return backward_comm_start_time;
+      case Event::kBackwardCommEnd:
+        return backward_comm_end_time;
+      default:
+        TORCH_INTERNAL_ASSERT(false);
+    }
+  }
+};
+
+TORCH_DECLARE_TYPED_REGISTRY(
+    TimerRegistry,
+    c10::DeviceType,
+    Timer,
+    std::unique_ptr,
+    c10::Device);
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/sequence_num.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/sequence_num.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..38bd4cb5ed9d38ea2bd6ce47e4e7fae5e5819385
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/sequence_num.hpp
@@ -0,0 +1,66 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace c10d {
+const int kUnsetSeqNum = 0;
+
+namespace {
+constexpr int kByteOffset = 8;
+}
+
+// Converts from int to char vec to write in store
+template 
+inline std::vector toVec(uint64_t num, int numBytes) {
+  std::vector values;
+  // Read off bytes from right to left, pushing them into
+  // char array.
+  for (const auto i : c10::irange(numBytes)) {
+    uint8_t x = (num >> (kByteOffset * i)) & 0xff;
+    values.push_back(static_cast(x));
+  }
+  return values;
+}
+
+// Converts from char vec (such as from store read) to int.
+template 
+inline uint64_t fromVec(const std::vector& values) {
+  uint64_t num = 0;
+  // Set each byte at the correct location on num
+  for (const auto i : c10::irange(values.size())) {
+    uint8_t x = static_cast(values[i]);
+    num |= (static_cast(x) << (kByteOffset * i));
+  }
+  return num;
+}
+
+class TORCH_API SequenceNum {
+ public:
+  SequenceNum();
+  explicit SequenceNum(const uint64_t num);
+  // Retrieve num_. Will throw if not set.
+  uint64_t get() const;
+  // Increment num_. Will throw if not set.
+  void increment();
+  // Increment num_ and return the old value. Will throw if not set.
+  uint64_t getAndIncrement();
+  // Sets num_
+  void set(const uint64_t num);
+  // Returns true if this SequenceNum is properly initialized with a value, else
+  // false.
+  bool isSet() const;
+
+  SequenceNum& operator=(const SequenceNum& other);
+
+  SequenceNum(const SequenceNum& other);
+
+ private:
+  std::optional num_;
+  mutable std::mutex lock_;
+};
+
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/socket.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/socket.h
new file mode 100644
index 0000000000000000000000000000000000000000..1e42a53b0b530dc2b58867a248ed985a9748130b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/c10d/socket.h
@@ -0,0 +1,109 @@
+// Copyright (c) Meta Platforms, Inc. and its affiliates.
+// All rights reserved.
+//
+// This source code is licensed under the BSD-style license found in the
+// LICENSE file in the root directory of this source tree.
+
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+
+namespace c10d {
+namespace detail {
+
+class SocketOptions {
+ public:
+  SocketOptions& prefer_ipv6(bool value) noexcept {
+    prefer_ipv6_ = value;
+
+    return *this;
+  }
+
+  bool prefer_ipv6() const noexcept {
+    return prefer_ipv6_;
+  }
+
+  SocketOptions& connect_timeout(std::chrono::milliseconds value) noexcept {
+    connect_timeout_ = value;
+
+    return *this;
+  }
+
+  std::chrono::milliseconds connect_timeout() const noexcept {
+    return connect_timeout_;
+  }
+
+  // Sets the backoff policy to use for socket connect ops.
+  SocketOptions& connect_backoff(std::shared_ptr value) noexcept {
+    connect_backoff_ = std::move(value);
+
+    return *this;
+  }
+
+  const std::shared_ptr& connect_backoff() const noexcept {
+    return connect_backoff_;
+  }
+
+ private:
+  bool prefer_ipv6_ = true;
+  std::chrono::milliseconds connect_timeout_{std::chrono::seconds{30}};
+  std::shared_ptr connect_backoff_{
+      std::make_shared(std::chrono::milliseconds(1000))};
+};
+
+class SocketImpl;
+
+class Socket {
+ public:
+  // This function initializes the underlying socket library and must be called
+  // before any other socket function.
+  static void initialize();
+
+  static Socket listen(std::uint16_t port, const SocketOptions& opts = {});
+
+  static Socket listenFromFd(int fd, std::uint16_t expected_port);
+
+  static Socket connect(
+      const std::string& host,
+      std::uint16_t port,
+      const SocketOptions& opts = {});
+
+  Socket() noexcept = default;
+
+  Socket(const Socket& other) = delete;
+
+  Socket& operator=(const Socket& other) = delete;
+
+  Socket(Socket&& other) noexcept;
+
+  Socket& operator=(Socket&& other) noexcept;
+
+  ~Socket();
+
+  Socket accept() const;
+
+  int handle() const noexcept;
+
+  std::uint16_t port() const;
+
+  bool waitForInput(std::chrono::milliseconds timeout);
+
+  std::string repr() const;
+
+ private:
+  explicit Socket(std::unique_ptr&& impl) noexcept;
+
+  std::unique_ptr impl_;
+};
+
+} // namespace detail
+
+} // namespace c10d
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/agent_utils.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/agent_utils.h
new file mode 100644
index 0000000000000000000000000000000000000000..8ba7226dc1fe7eab537049db26d5c090820fb0d3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/agent_utils.h
@@ -0,0 +1,46 @@
+#pragma once
+
+#include 
+#include 
+
+namespace torch {
+namespace distributed {
+namespace rpc {
+
+// All RPC peers should call into this function at the same time. Each peer
+// provides its own id and name, and this function uses the given Store to
+// gather global name-to-id mapping on all peers.
+TORCH_API std::unordered_map collectNames(
+    ::c10d::PrefixStore store,
+    const worker_id_t selfId,
+    const std::string& selfName,
+    const int worldSize);
+
+// Ranks in dynamic RPC groups will initially call into this to establish the
+// name-to-id mapping for the current peers in the group. The current rank will
+// put its own worker info in the store and discover all the ranks that came
+// before it. NOTE: This needs to be called with the Dynamic RPC group
+// membership management token held.
+TORCH_API std::unordered_map collectCurrentNames(
+    ::c10d::PrefixStore store,
+    const worker_id_t selfId,
+    const std::string& selfName);
+
+// Remove name frmo Store, used in dynamic RPC groups.
+// NOTE: This needs to be called with the Dynamic RPC group
+// membership management token held.
+TORCH_API void removeCurrentName(
+    ::c10d::PrefixStore store,
+    const worker_id_t selfId,
+    const std::string& selfName);
+
+// This performs a synchronization of all call counts by using store.
+// All RPC peers wait for others to join to exit at the same time.
+TORCH_API int syncCallCount(
+    ::c10d::PrefixStore store,
+    const int worldSize,
+    int activeCalls = 0);
+
+} // namespace rpc
+} // namespace distributed
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/message.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/message.h
new file mode 100644
index 0000000000000000000000000000000000000000..6ef573cf14ff33a49a47b2fa0f61714b2ac05e85
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/message.h
@@ -0,0 +1,193 @@
+#pragma once
+
+#include 
+#include 
+
+namespace torch {
+namespace distributed {
+namespace rpc {
+
+// An enum denoting common RPC errors to allow specific error handling for them.
+enum RPCErrorType {
+  UNKNOWN_ERROR = 0, /* Indicates that error type could not be parsed */
+  TIMEOUT = 1, /* Indicates that the RPC has timed out */
+  INTENTIONAL_FAILURE = 2 /* Deliberate failure, such as those injected by
+                             FaultyAgent for testing */
+};
+
+// The enum values are bitwise ORed with MessageType
+// They are bit flags starting from 0x100 and should have
+// value such as 0x100, 0x200, 0x400, 0x800, 0xF00, etc.
+enum MessageTypeFlags {
+  REQUEST_TYPE = 0x100,
+  RESPONSE_TYPE = 0x200,
+};
+
+// Message types must have values between 0x00 to 0xff
+enum MessageType {
+  // messages for dist.rpc on builtin operators
+  SCRIPT_CALL = 0x00 | MessageTypeFlags::REQUEST_TYPE,
+  SCRIPT_RET = 0x01 | MessageTypeFlags::RESPONSE_TYPE,
+
+  // messages for dist.rpc on Python UDF
+  PYTHON_CALL = 0x02 | MessageTypeFlags::REQUEST_TYPE,
+  PYTHON_RET = 0x03 | MessageTypeFlags::RESPONSE_TYPE,
+
+  // messages for dist.remote on builtin operators and Python UDF
+  SCRIPT_REMOTE_CALL = 0x04 |
+      MessageTypeFlags::REQUEST_TYPE, // A remote call on a builtin operator
+  PYTHON_REMOTE_CALL =
+      0x05 | MessageTypeFlags::REQUEST_TYPE, // A remote call on a Python UDF
+  REMOTE_RET =
+      0x06 | MessageTypeFlags::RESPONSE_TYPE, // Response for remote calls for
+                                              // UDF, builtin, or script
+
+  // RRef related internal messages
+  SCRIPT_RREF_FETCH_CALL =
+      0x07 | MessageTypeFlags::REQUEST_TYPE, // A UserRRef fetches value
+                                             // from owner
+  PYTHON_RREF_FETCH_CALL =
+      0x08 | MessageTypeFlags::REQUEST_TYPE, // A UserRRef fetches
+                                             // value from owner
+  SCRIPT_RREF_FETCH_RET = 0x09 |
+      MessageTypeFlags::RESPONSE_TYPE, // An OwnerRRef sends ivalue to user
+  PYTHON_RREF_FETCH_RET = 0x0a |
+      MessageTypeFlags::RESPONSE_TYPE, // An OwnerRRef sends py::object to user
+  RREF_USER_DELETE = 0x0b |
+      MessageTypeFlags::REQUEST_TYPE, // A UserRRef tells the owner to deref
+  RREF_FORK_REQUEST =
+      0x0c | MessageTypeFlags::REQUEST_TYPE, // A child UserRRef tells the owner
+                                             // about itself
+  RREF_CHILD_ACCEPT =
+      0x0d | MessageTypeFlags::REQUEST_TYPE, // A child UserRRef tells parent
+                                             // that owner knows it
+  RREF_ACK =
+      0x0e | MessageTypeFlags::RESPONSE_TYPE, // ACK to internal RRef messages
+
+  // Messages with autograd info
+  FORWARD_AUTOGRAD_REQ = 0x0f | MessageTypeFlags::REQUEST_TYPE,
+  FORWARD_AUTOGRAD_RESP = 0x10 | MessageTypeFlags::RESPONSE_TYPE,
+
+  // Messages to propagate gradients on the backward pass.
+  BACKWARD_AUTOGRAD_REQ = 0x11 | MessageTypeFlags::REQUEST_TYPE,
+  BACKWARD_AUTOGRAD_RESP = 0x12 | MessageTypeFlags::RESPONSE_TYPE,
+
+  // Messages to tell workers to clean up their autograd context.
+  CLEANUP_AUTOGRAD_CONTEXT_REQ = 0x13 | MessageTypeFlags::REQUEST_TYPE,
+  CLEANUP_AUTOGRAD_CONTEXT_RESP = 0x14 | MessageTypeFlags::RESPONSE_TYPE,
+
+  // Messages that tell workers to run requests with profiling enabled.
+  RUN_WITH_PROFILING_REQ = 0x15 | MessageTypeFlags::REQUEST_TYPE,
+  RUN_WITH_PROFILING_RESP = 0x16 | MessageTypeFlags::RESPONSE_TYPE,
+
+  // Messages to support RRef.backward().
+  RREF_BACKWARD_REQ = 0x17 | MessageTypeFlags::REQUEST_TYPE,
+  RREF_BACKWARD_RESP = 0x18 | MessageTypeFlags::RESPONSE_TYPE,
+
+  // Other internal message types
+  EXCEPTION = 0x37 | MessageTypeFlags::RESPONSE_TYPE,
+  UNKNOWN = 0x3c
+};
+
+// A message to be sent/received by an RpcAgent.
+//
+// A Message object contains 4 fields:
+//    payload (std::vector): a binary chunk of data.
+//    tensors (std::vector): all tensors. Tensor data are not
+//        included in the payload, and it is up to the RpcAgent implementation
+//        to determine how to serialize them. This design is helpful for
+//        communicating super large tensors where serializing all the data at
+//        once leads to excessively large memory footprint. An implementation
+//        can then serialize and send tensors chunk-by-chunk, in the streaming
+//        fashion.
+//    type (MessageType): type of the message.
+//    id (int64_t): message id, this is used to match request and response.
+//               Other implementation can ignore it if they have their own
+//               ways to do matching.
+//
+// Layers above ``RpcAgent`` only converts ScriptCall, ScriptResp, PythonCall,
+// and PythonResp into a Message, and it is up to the RpcAgent
+// implementation to determine how to serialize a message.
+class TORCH_API Message final : public torch::CustomClassHolder {
+ private:
+  // Keep these private in order to force users to go through make_intrusive and
+  // thus prevent creating a Message that's not held by an intrusive_ptr.
+  Message();
+
+  Message(
+      std::vector&& payload,
+      std::vector&& tensors,
+      MessageType type);
+
+  Message(
+      std::vector&& payload,
+      std::vector&& tensors,
+      MessageType type,
+      int64_t id);
+
+  friend c10::intrusive_ptr;
+
+ public:
+  Message(const Message& other) = delete;
+  Message(Message&& other) = delete;
+  Message& operator=(Message const& rhs) = delete;
+  Message& operator=(Message&& rhs) = delete;
+
+  // Destructively retrieves the payload.
+  std::vector&& movePayload() &&;
+  std::vector&& moveTensors() &&;
+
+  std::vector& payload();
+  const std::vector& payload() const;
+  std::vector& tensors();
+  const std::vector& tensors() const;
+  MessageType type() const;
+
+  bool isRequest() const;
+  bool isResponse() const;
+  bool isShutdown() const;
+
+  // id is an optional field to match request/response. If an RpcAgent
+  // implementation is able to do the matching without using this id, it can be
+  // dropped during message serialization.
+  int64_t id() const;
+  void setId(int64_t id);
+
+  std::vector> getStorages() const;
+
+ private:
+  std::vector payload_;
+  std::vector tensors_;
+  MessageType type_ = MessageType::UNKNOWN;
+  int64_t id_ = -1;
+};
+
+// Create a response Message of type Exception.
+// The exception string representation will be used as the message's payload.
+// A message ID corresponding to the request that resulted in this response can
+// be provided for matching requests/responses.
+TORCH_API c10::intrusive_ptr createExceptionResponse(
+    const std::exception& e,
+    int64_t id);
+
+// Create a response Message of type Exception.
+// The passed in string representation will be used as the message's payload.
+// A message ID corresponding to the request that resulted in this response can
+// be provided for matching requests/responses.
+TORCH_API c10::intrusive_ptr createExceptionResponse(
+    const std::string& exceptionStr,
+    int64_t id);
+
+inline std::tuple<
+    c10::intrusive_ptr,
+    std::vector>>
+withStorages(c10::intrusive_ptr message) {
+  auto storages = message->getStorages();
+  return std::make_tuple(std::move(message), std::move(storages));
+}
+
+using JitFuture = c10::ivalue::Future;
+
+} // namespace rpc
+} // namespace distributed
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/py_rref.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/py_rref.h
new file mode 100644
index 0000000000000000000000000000000000000000..2c9fd3433d045e68e990408bdd0e18bae305c671
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/py_rref.h
@@ -0,0 +1,84 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace distributed {
+namespace rpc {
+
+enum RRefProxyType { RPC_SYNC, RPC_ASYNC, REMOTE };
+
+// Python wrapper of an RRef shared_ptr that supports Python
+// pickle and unpickle.
+class PYBIND11_EXPORT PyRRef {
+ public:
+  // The first ctor can only be called while holding GIL. See its implementation
+  // for more explanations.
+  explicit PyRRef(const py::object& value, const py::object& type_hint);
+  explicit PyRRef(c10::intrusive_ptr rref);
+  PyRRef(const PyRRef&) = default;
+  ~PyRRef();
+
+  bool isOwner() const;
+  bool confirmedByOwner() const;
+  WorkerInfo owner() const;
+  std::string ownerName() const;
+  py::object toHere(
+      const float timeoutSeconds =
+          torch::distributed::rpc::kUnsetRpcTimeout) const;
+  py::object localValue() const;
+  std::string str() const;
+  py::tuple pickle() const;
+  static PyRRef unpickle(const py::tuple& t);
+  c10::IValue toIValue() const;
+  // Future that is associated with the creation of this RRef on the remote end.
+  // This is only used to get the future corresponding to the rref for profiling
+  // use cases.
+  c10::intrusive_ptr getFuture() const;
+  // Keeps track of the future responsible for profiling owner creation
+  // acknowledgement
+  c10::intrusive_ptr getProfilingFuture() const;
+  // Sets the future responsible for profiling owner creation acknowledgement.
+  // This future is set from python to be a future that returns when profiling
+  // callbacks have been run.
+  void setProfilingFuture(c10::intrusive_ptr profilingFuture);
+
+  // create a proxy on this RRef, which can be used to launch RPC on the owner
+  // of this RRef to run functions on the object referenced by this RRef.
+  py::object createRRefProxy(
+      const RRefProxyType& mode,
+      float timeoutSeconds = rpc::kUnsetRpcTimeout) const;
+
+  // get the type of the data object referenced by this RRef. Timeout argument
+  // is only used in the first invocation of this function as an argument to the
+  // RPC to the owner node of the RRef.
+  py::object getRRefType(
+      float timeout = rpc::kUnsetRpcTimeout,
+      bool blocking = true);
+
+  // Run the backward pass with the RRef as the root.
+  void backward(int64_t autogradContextId, bool retainGraph);
+
+  // Helper static function to run backward on a given rref.
+  static void backward(
+      int64_t autogradContextId,
+      bool retainGraph,
+      const c10::intrusive_ptr& rref);
+
+  // Specialization of backward if the rref is an OwnerRRef.
+  static void backwardOwnerRRef(
+      int64_t autogradContextId,
+      bool retainGraph,
+      IValue value);
+
+ private:
+  c10::intrusive_ptr rref_;
+  std::optional> profilingFuture_;
+  std::optional type_;
+};
+
+} // namespace rpc
+} // namespace distributed
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/python_call.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/python_call.h
new file mode 100644
index 0000000000000000000000000000000000000000..8b0a94ecc12e7355cade411fd68dcb839c0fef02
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/python_call.h
@@ -0,0 +1,28 @@
+#pragma once
+
+#include 
+#include 
+
+namespace torch::distributed::rpc {
+
+// RPC call representing calling a Python function over RPC.
+class TORCH_API PythonCall final : public RpcCommandBase {
+ public:
+  PythonCall(SerializedPyObj&& serializedPyObj, bool isAsyncExecution);
+
+  c10::intrusive_ptr toMessageImpl() && override;
+
+  static std::unique_ptr fromMessage(const Message& message);
+
+  const SerializedPyObj& serializedPyObj() const;
+
+  inline bool isAsyncExecution() const {
+    return isAsyncExecution_;
+  }
+
+ private:
+  SerializedPyObj serializedPyObj_;
+  const bool isAsyncExecution_;
+};
+
+} // namespace torch::distributed::rpc
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/python_functions.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/python_functions.h
new file mode 100644
index 0000000000000000000000000000000000000000..e17d8b6753b74e2d4788d151c3c196a7c5baf7f2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/python_functions.h
@@ -0,0 +1,66 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch::distributed::rpc {
+
+// Converts an internal ivalue::Future of Message into a user-facing
+// ivalue::Future of py::object type by creating a new ivalue::Future and call
+// its  markCompleted as a callback in the given ivalue::Future.
+// If hasValue is true, the Message will be converted into a py::object and then
+// wrap it with an IValue. If hasValue is false, this ivalue::Future is only
+// used for signaling and launching callbacks. In this case, the message will be
+// discarded and then set the ivalue::Future using an empty IValue or the given
+// FutureError if there is an error.
+c10::intrusive_ptr toPyJitFuture(
+    const c10::intrusive_ptr& messageJitFuture,
+    bool hasValue = true);
+
+c10::intrusive_ptr pyRpcBuiltin(
+    const WorkerInfo& dst,
+    const std::string& opName,
+    const py::args& args,
+    const py::kwargs& kwargs,
+    const float rpcTimeoutSeconds);
+
+c10::intrusive_ptr pyRpcPythonUdf(
+    const WorkerInfo& dst,
+    std::string& pickledPythonUDF,
+    std::vector& tensors,
+    const float rpcTimeoutSeconds,
+    const bool isAsyncExecution);
+
+c10::intrusive_ptr pyRpcTorchscript(
+    const std::string& dstWorkerName,
+    const std::string& qualifiedNameStr,
+    const py::tuple& argsTuple,
+    const py::dict& kwargsDict,
+    const float rpcTimeoutSeconds,
+    const bool isAsyncExecution);
+
+PyRRef pyRemoteBuiltin(
+    const WorkerInfo& dst,
+    const std::string& opName,
+    const float rpcTimeoutSeconds,
+    const py::args& args,
+    const py::kwargs& kwargs);
+
+PyRRef pyRemotePythonUdf(
+    const WorkerInfo& dst,
+    std::string& pickledPythonUDF,
+    std::vector& tensors,
+    const float rpcTimeoutSeconds,
+    const bool isAsyncExecution);
+
+PyRRef pyRemoteTorchscript(
+    const std::string& dstWorkerName,
+    const std::string& qualifiedNameStr,
+    const float rpcTimeoutSeconds,
+    const bool isAsyncExecution,
+    const py::args& args,
+    const py::kwargs& kwargs);
+
+} // namespace torch::distributed::rpc
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/python_remote_call.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/python_remote_call.h
new file mode 100644
index 0000000000000000000000000000000000000000..9ab968a5f1eec0e80f46dc3d444f7534f69c21d4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/python_remote_call.h
@@ -0,0 +1,45 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch::distributed::rpc {
+
+class TORCH_API PythonRemoteCall : public RpcCommandBase {
+ public:
+  PythonRemoteCall(
+      SerializedPyObj&& serializedPyObj,
+      at::IValue retRRefId,
+      at::IValue retForkId,
+      const bool isAsyncExecution);
+
+  inline const SerializedPyObj& serializedPyObj() const {
+    return serializedPyObj_;
+  }
+
+  inline const at::IValue& retRRefId() const {
+    return retRRefId_;
+  }
+
+  inline const at::IValue& retForkId() const {
+    return retForkId_;
+  }
+
+  inline bool isAsyncExecution() const {
+    return isAsyncExecution_;
+  }
+
+  c10::intrusive_ptr toMessageImpl() && override;
+  static std::unique_ptr fromMessage(const Message& message);
+
+ private:
+  SerializedPyObj serializedPyObj_;
+  const at::IValue retRRefId_;
+  const at::IValue retForkId_;
+  const bool isAsyncExecution_;
+};
+
+} // namespace torch::distributed::rpc
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/python_resp.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/python_resp.h
new file mode 100644
index 0000000000000000000000000000000000000000..8c656b6ff45457877cd0be1bda0fc8b22459773a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/python_resp.h
@@ -0,0 +1,23 @@
+#pragma once
+
+#include 
+#include 
+
+namespace torch::distributed::rpc {
+
+// RPC call representing the response of a Python UDF over RPC.
+class TORCH_API PythonResp final : public RpcCommandBase {
+ public:
+  explicit PythonResp(SerializedPyObj&& serializedPyObj);
+
+  c10::intrusive_ptr toMessageImpl() && override;
+
+  static std::unique_ptr fromMessage(const Message& message);
+
+  const SerializedPyObj& serializedPyObj() const;
+
+ private:
+  SerializedPyObj serializedPyObj_;
+};
+
+} // namespace torch::distributed::rpc
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/python_rpc_handler.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/python_rpc_handler.h
new file mode 100644
index 0000000000000000000000000000000000000000..0772a6b7fbb3e649f8bdca97d69c38af4e772b02
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/python_rpc_handler.h
@@ -0,0 +1,129 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch::distributed::rpc {
+
+// Singleton class provides interface to execute python UDF remote call
+// and deserialize the returned results by running python function
+// in internal_rpc_utilities.
+// The singleton object is constructed at first when RPC agent is
+// constructed, where the python function in
+// torch/distributed/internal_rpc_utils.py are imported only once.
+class PYBIND11_EXPORT PythonRpcHandler {
+ public:
+  struct RRefProxyFunctions {
+    py::object rrefProxyCtor_;
+    py::object rpcSync_;
+    py::object rpcAsync_;
+    py::object remote_;
+  };
+
+  struct RRefTypeFunctions {
+    py::object onOwner_;
+    py::object onUser_;
+  };
+
+  static PythonRpcHandler& getInstance();
+
+  // Run a pickled Python UDF and return the result py::object
+  py::object runPythonUdf(const py::object& pythonUdf);
+
+  // Serialized a py::object into a string
+  SerializedPyObj serialize(const py::object& obj);
+
+  // Deserialize a string into a py::object
+  py::object deserialize(const SerializedPyObj& serializedObj);
+
+  // Check if obj is RemoteException, then throw it
+  void handleException(const py::object& obj);
+  // Alternative if the caller is already holding the GIL.
+  void handleExceptionGILHeld(const py::object& obj);
+  // Check if obj is an RemoteException instance.
+  bool isRemoteException(const py::object& obj);
+
+  // Explicitly clean up py::objects to avoid segment faults when
+  // py::objects with CPython are cleaned up later at program exit
+  // See similar issues reported https://github.com/pybind/pybind11/issues/1598
+  // and https://github.com/pybind/pybind11/issues/1493
+  // Our local tests also caught this segment faults if py::objects are cleaned
+  // up at program exit. The explanation is: CPython cleans up most critical
+  // utilities before cleaning up PythonRpcHandler singleton, so when
+  // PythonRpcHandler singleton cleans up py::objects and call dec_ref(), it
+  // will crash.
+  // The solution is to clean up py::objects earlier when Rpc agent join().
+  // Be note that py::objects can not be cleaned up when Rpc agent is destroyed
+  // as well, as Rpc agent is global variable and it will have same issue as
+  // PythonRpcHandler.
+  void cleanup();
+
+  std::shared_ptr jitCompilationUnit();
+
+  // Parse the string to recover the jit_type, this is used for RRef python
+  // pickling/unpickling type recovery. The type string inference rule is as
+  // follows:
+  // 1. first try to parse if this is primitive types.
+  //    i.e. TensorType, IntType, PyObjectType, etc.
+  // 2. if not primitive type, we query the python_cu to see if it is a
+  //    class type or interface type registered in python
+  // We use a ScriptTypeParser instance with custom PythonTypeResolver
+  // to resolve types according to the above rules.
+  TypePtr parseTypeFromStr(const std::string& typeStr);
+
+  // Return a set of Python functions for RRef helpers.
+  const RRefProxyFunctions& getRRefProxyFunctions() const;
+
+  // Return a set of Python functions to retrieve the type of the object
+  // referenced by a given RRef.
+  const RRefTypeFunctions& getRRefTypeFunctions() const;
+
+  PythonRpcHandler(const PythonRpcHandler&) = delete;
+  PythonRpcHandler& operator=(const PythonRpcHandler&) = delete;
+  PythonRpcHandler(PythonRpcHandler&&) = delete;
+  PythonRpcHandler& operator=(PythonRpcHandler&&) = delete;
+
+ private:
+  void init();
+  PythonRpcHandler();
+  ~PythonRpcHandler() = default;
+
+  // Ref to `torch.distributed.rpc.internal._run_function`.
+  py::object pyRunFunction_;
+
+  // Ref to `torch.distributed.rpc.internal.serialize`.
+  py::object pySerialize_;
+
+  // Ref to `torch.distributed.rpc.internal.deserialize`.
+  py::object pyDeserialize_;
+
+  // Ref to 'torch.distributed.rpc.internal._handle_exception'
+  py::object pyHandleException_;
+
+  // Python functions for RRef proxy
+  RRefProxyFunctions rrefProxyFunctions_;
+
+  // Ref to 'torch.distributed.rpc.api._rref_typeof_on_'
+  RRefTypeFunctions rrefTypeFunctions_;
+
+  // Shared ptr to python compilation unit in jit, it is constructed in python
+  // side (see _python_cu = torch._C.CompilationUnit() in jit/__init__.py)
+  // and imported in C++ (see get_python_cu() in
+  // csrc/jit/python/pybind_utils.h). We import the compilation unit here only
+  // once for less cost and thread safety.
+  std::shared_ptr jitCompilationUnit_;
+
+  // jit type parser to parse type_str back to TypePtr for RRef type
+  // recovery when pickling and unpickling RRef
+  std::shared_ptr typeParser_;
+
+  // Indicates whether or not we have properly initialized the handler.
+  bool initialized_;
+
+  // Lock to protect initialization.
+  std::mutex init_lock_;
+};
+
+} // namespace torch::distributed::rpc
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback.h
new file mode 100644
index 0000000000000000000000000000000000000000..e0bf1388b48be527f9b7dc21a24174ceaf4b7b37
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback.h
@@ -0,0 +1,32 @@
+#pragma once
+
+#include 
+
+namespace torch::distributed::rpc {
+
+// Functor which is invoked to process an RPC message. This is an abstract class
+// with some common functionality across all request handlers. Users need to
+// implement this interface to perform the actual business logic.
+class TORCH_API RequestCallback {
+ public:
+  // Invoke the callback.
+  c10::intrusive_ptr operator()(
+      Message& request,
+      std::vector streams) const;
+
+  virtual ~RequestCallback() = default;
+
+ protected:
+  // RpcAgent implementation should invoke ``RequestCallback`` to process
+  // received requests. There is no restriction on the implementation's
+  // threading model. This function takes an rvalue reference of the Message
+  // object. It is expected to return the future to a response message or
+  // message containing an exception. Different rpc agent implementations are
+  // expected to ensure delivery of the response/exception based on their
+  // implementation specific mechanisms.
+  virtual c10::intrusive_ptr processMessage(
+      Message& request,
+      std::vector streams) const = 0;
+};
+
+} // namespace torch::distributed::rpc
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback_impl.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback_impl.h
new file mode 100644
index 0000000000000000000000000000000000000000..d8c3efc29ffd0111af0379a8bb2690890e7baeed
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback_impl.h
@@ -0,0 +1,61 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch::distributed::rpc {
+
+class TORCH_API RequestCallbackImpl : public RequestCallbackNoPython {
+ public:
+  std::unique_ptr deserializePythonRpcCommand(
+      std::unique_ptr rpc,
+      const MessageType& messageType) const override;
+
+  c10::intrusive_ptr processPythonCall(
+      RpcCommandBase& rpc,
+      const std::vector& streams) const override;
+
+  c10::intrusive_ptr processScriptCall(
+      RpcCommandBase& rpc,
+      const std::vector& streams) const override;
+
+  c10::intrusive_ptr processScriptRemoteCall(
+      RpcCommandBase& rpc,
+      const std::vector& streams) const override;
+
+  c10::intrusive_ptr processPythonRemoteCall(
+      RpcCommandBase& rpc,
+      const std::vector& streams) const override;
+
+  c10::intrusive_ptr processPythonRRefFetchCall(
+      RpcCommandBase& rpc) const override;
+
+  void handleRRefDelete(c10::intrusive_ptr& rref) const override;
+
+  c10::intrusive_ptr processRpcWithErrors(
+      RpcCommandBase& rpc,
+      const MessageType& messageType,
+      const std::vector& streams) const override;
+
+  bool cudaAvailable() const override;
+
+  c10::intrusive_ptr processRRefBackward(
+      RpcCommandBase& rpc) const override;
+
+  // Helpers to run user-defined functions, operators and other computations.
+
+  c10::intrusive_ptr runJitFunction(
+      const c10::QualifiedName& name,
+      std::vector& stack,
+      const std::vector& streams,
+      bool isAsyncExecution) const;
+
+  c10::intrusive_ptr runPythonFunction(
+      const py::object& function,
+      const std::vector& streams,
+      bool isAsyncExecution) const;
+};
+
+} // namespace torch::distributed::rpc
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback_no_python.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback_no_python.h
new file mode 100644
index 0000000000000000000000000000000000000000..dfb0d5d2c430c4a637c27fc802e0e63884685647
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback_no_python.h
@@ -0,0 +1,115 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch::distributed::rpc {
+
+// RequestCallback implementation with no Python dependencies.
+class TORCH_API RequestCallbackNoPython : public RequestCallback {
+ public:
+  c10::intrusive_ptr processMessage(
+      Message& request,
+      std::vector streams) const override;
+
+ protected:
+  virtual std::unique_ptr deserializePythonRpcCommand(
+      std::unique_ptr rpc,
+      const MessageType& messageType) const;
+
+  virtual c10::intrusive_ptr processScriptCall(
+      RpcCommandBase& rpc,
+      const std::vector& streams) const;
+
+  virtual c10::intrusive_ptr processPythonCall(
+      RpcCommandBase& rpc,
+      const std::vector& streams) const;
+
+  c10::intrusive_ptr assignOwnerRRef(
+      const RRefId& rrefId,
+      const RRefId& forkId,
+      const c10::intrusive_ptr& valueFuture) const;
+
+  virtual c10::intrusive_ptr processScriptRemoteCall(
+      RpcCommandBase& rpc,
+      const std::vector& streams) const;
+
+  virtual c10::intrusive_ptr processPythonRemoteCall(
+      RpcCommandBase& rpc,
+      const std::vector& streams) const;
+
+  c10::intrusive_ptr retrieveOwnerRRef(const RRefId& rrefId) const;
+
+  c10::intrusive_ptr processScriptRRefFetchCall(
+      RpcCommandBase& rpc) const;
+
+  virtual c10::intrusive_ptr processPythonRRefFetchCall(
+      RpcCommandBase& rpc) const;
+
+  c10::intrusive_ptr processRRefUserDelete(
+      RpcCommandBase& rpc) const;
+
+  c10::intrusive_ptr processRRefChildAccept(
+      RpcCommandBase& rpc) const;
+
+  c10::intrusive_ptr processRRefForkRequest(
+      RpcCommandBase& rpc) const;
+
+  c10::intrusive_ptr processForwardAutogradReq(
+      RpcCommandBase& rpc,
+      const std::vector& streams) const;
+
+  c10::intrusive_ptr processBackwardAutogradReq(
+      RpcCommandBase& rpc,
+      const std::vector& streams) const;
+
+  c10::intrusive_ptr processCleanupAutogradContextReq(
+      RpcCommandBase& rpc) const;
+
+  c10::intrusive_ptr processRunWithProfilingReq(
+      RpcCommandBase& rpc) const;
+
+  virtual void handleRRefDelete(c10::intrusive_ptr& rref) const;
+
+  c10::intrusive_ptr processRpc(
+      RpcCommandBase& rpc,
+      const MessageType& messageType,
+      const std::vector& streams) const;
+
+  virtual c10::intrusive_ptr processRpcWithErrors(
+      RpcCommandBase& rpc,
+      const MessageType& messageType,
+      const std::vector& streams) const;
+
+  c10::intrusive_ptr handleError(
+      const std::exception& e,
+      const MessageType messageType,
+      int64_t messageId) const;
+
+  virtual bool cudaAvailable() const;
+
+  virtual c10::intrusive_ptr processRRefBackward(
+      RpcCommandBase& rpc) const;
+
+  // Helpers to run user-defined functions, operators and other computations.
+
+  c10::intrusive_ptr runJitOperator(
+      const jit::Operator& op,
+      std::vector& stack,
+      const std::vector& streams) const;
+
+  // Helpers to convert various kinds of objects into already-completed futures.
+
+  c10::intrusive_ptr asFuture(IValue value, TypePtr type) const;
+
+  c10::intrusive_ptr asFuture(
+      c10::intrusive_ptr message) const;
+
+  c10::intrusive_ptr asFuture(std::exception_ptr err) const;
+};
+
+} // namespace torch::distributed::rpc
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/rpc.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/rpc.h
new file mode 100644
index 0000000000000000000000000000000000000000..bfeb3a8f4a370b37ee88e92bbc826bbcf2c1dbf5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/rpc.h
@@ -0,0 +1,9 @@
+#pragma once
+
+#include 
+
+namespace torch::distributed::rpc {
+
+PyMethodDef* python_functions();
+
+} // namespace torch::distributed::rpc
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/rpc_agent.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/rpc_agent.h
new file mode 100644
index 0000000000000000000000000000000000000000..bb63f47a00550808069c7279f2d529cbc569f617
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/rpc_agent.h
@@ -0,0 +1,337 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch::distributed::rpc {
+
+using DeviceMap = std::unordered_map;
+
+// Default RPC timeout
+constexpr float kDefaultRpcTimeoutSeconds = 60;
+// Unset RPC timeout. This is the value agent::send() will have if user does not
+// pass in a specific timeout, and indicates that we must use the default
+// timeout for RPCs.
+constexpr float kUnsetRpcTimeout = -1;
+constexpr auto kDefaultInitMethod = "env://";
+constexpr float kSecToMsConversion = 1000;
+constexpr auto kRpcTimeoutErrorStr =
+    "RPC ran for more than set timeout ({} ms) and will now be marked with an error";
+
+using steady_clock_time_point =
+    std::chrono::time_point;
+// Input is qualified name string, output is JIT StrongTypePtr
+// Same as jit::TypeResolver, did not import jit::TypeResolver to here
+// because it could introduce cyclic dependencies.
+using TypeResolver =
+    std::function;
+
+struct TORCH_API RpcBackendOptions {
+  RpcBackendOptions()
+      : RpcBackendOptions(kDefaultRpcTimeoutSeconds, kDefaultInitMethod) {}
+
+  RpcBackendOptions(float rpcTimeoutSeconds, std::string initMethod)
+      : rpcTimeoutSeconds(rpcTimeoutSeconds),
+        initMethod(std::move(initMethod)) {
+    TORCH_CHECK(rpcTimeoutSeconds >= 0, "RPC Timeout must be non-negative");
+  }
+
+  float rpcTimeoutSeconds;
+  std::string initMethod;
+};
+
+// A globally unique ID to identify an RpcAgent
+struct TORCH_API WorkerInfo : torch::CustomClassHolder {
+  WorkerInfo(std::string name, int64_t id);
+
+  WorkerInfo(std::string name, worker_id_t id);
+
+  bool operator==(const WorkerInfo& rhs) {
+    return (id_ == rhs.id_) && (name_ == rhs.name_);
+  }
+
+  static constexpr size_t MAX_NAME_LEN = 128;
+
+  const std::string name_;
+  const worker_id_t id_;
+};
+
+struct TORCH_API RegisterWorkerInfoOnce {
+  RegisterWorkerInfoOnce();
+};
+
+TORCH_API std::ostream& operator<<(
+    std::ostream& os,
+    const WorkerInfo& workerInfo);
+
+// Struct for options to configure the RPC Retry protocol.
+struct TORCH_API RpcRetryOptions {
+  // Using a default constructor like all other Options structs in the RPC
+  // codebase. TORCH_CHECKs for input validation are done in the
+  // sendWithRetries function.
+  RpcRetryOptions() = default;
+  // Maximum number of times we will retry the RPC
+  int maxRetries{5};
+  // Initial duration between consecutive RPC send attempts
+  std::chrono::milliseconds rpcRetryDuration{std::chrono::milliseconds(1000)};
+  // Constant for exponential backoff used while calculating future wait
+  // durations
+  float retryBackoff{1.5};
+};
+
+// Struct that stores all the metadata needed to retry a given RPC.
+struct TORCH_API RpcRetryInfo {
+  RpcRetryInfo(
+      const WorkerInfo& to,
+      c10::intrusive_ptr message,
+      c10::intrusive_ptr originalFuture,
+      int retryCount,
+      RpcRetryOptions options)
+      : to_(to),
+        message_(std::move(message)),
+        originalFuture_(std::move(originalFuture)),
+        retryCount_(retryCount),
+        options_(options) {}
+
+  const WorkerInfo& to_;
+  c10::intrusive_ptr message_;
+  // Future that is returned to the caller of sendWithRetries().
+  c10::intrusive_ptr originalFuture_;
+  // Number of send attempts completed so far.
+  int retryCount_;
+  RpcRetryOptions options_;
+};
+
+// ``RpcAgent`` is the base class for sending and receiving RPC messages. It
+// provides a unified ``send`` API for both request and response messages, and
+// will invoke the given ``RequestCallback`` to process received requests. It
+// should immediately become ready to serve request and accept response after
+// construction.
+class TORCH_API RpcAgent {
+ public:
+  // `WorkerInfo` is the globally unique identifier for this RpcAgent instance.
+  // It contains a ``name_`` field and an ``id_`` field. ``name_`` is the
+  // globally unique name for this ``RpcAgent``. It is up to the ``RpcAgent``
+  // implementation to determine how to resolve names. ``id_`` is the globally
+  // unique ID for this ``RpcAgent``. This should be determined by the
+  // ``RpcAgent`` implementation.
+  // The ``RequestCallback`` will be invoked to handle received requests. This
+  // ``RpcAgent`` base class makes no assumption on the thread-safeness of the
+  // ``RequestCallback``. ``RpcAgent`` implementations need to make sure that
+  // its threading model conform to ``RequestCallback``'s requirement.
+  // NB: RpcAgent implementations should not start serving requests until
+  // ``start()`` is called, as there could be other contexts that have not been
+  // initialized yet at this time.
+  RpcAgent(
+      WorkerInfo id,
+      std::unique_ptr cb,
+      std::chrono::milliseconds rpcTimeout);
+
+  virtual ~RpcAgent();
+
+  // Send a message to the ``RpcAgent`` of id ``to`` and returns a
+  // ``JitFuture`` ptr. The implementation must be asynchronous, i.e., it
+  // cannot block until it receives the response.
+  //
+  // If ``message.isRequest()`` is true, the ``JitFuture`` will be
+  // completed when the response arrives. For other message types, the Future
+  // should be ignored by the caller.
+  virtual c10::intrusive_ptr send(
+      const WorkerInfo& to,
+      c10::intrusive_ptr message,
+      const float rpcTimeoutSeconds = kUnsetRpcTimeout,
+      const DeviceMap& deviceMap = {}) = 0;
+
+  // Retries sending the message up to maxRetries times until an ACK is
+  // received. The duration between consecutive sends is increased over
+  // time using an exponential backoff algorithm.
+  //
+  // Sends ``message`` to the ``RpcAgent`` of id ``to`` and returns a
+  // ``JitFuture`` ptr, just like send(). Caller can specify the maximum
+  // number of retries for this RPC (default is 5), initial duration between
+  // sends (default is 1000ms), and backoff constant (default is 1.5) by
+  // passing in the RpcRetryOptions struct. This API might end up
+  // executing a method twice on the remote end (it does not guarantee
+  // exactly-once semantics). Therefore, the user must ensure their requests
+  // are idempotent.
+  c10::intrusive_ptr sendWithRetries(
+      const WorkerInfo& to,
+      c10::intrusive_ptr message,
+      RpcRetryOptions retryOptions = RpcRetryOptions());
+
+  // Return a reference to the ``WorkerInfo`` of this RpcAgent.
+  // NB: not using ``std::optional`` here because we might
+  // need to create a separate RPC API lib and avoid forcing all ``RpcAgent``
+  // implementations to depend on libtorch.
+  const WorkerInfo& getWorkerInfo() const;
+
+  // Return a reference to the ``WorkerInfo`` of the given ``workerName``.
+  virtual const WorkerInfo& getWorkerInfo(
+      const std::string& workerName) const = 0;
+
+  virtual const WorkerInfo& getWorkerInfo(worker_id_t id) const = 0;
+
+  virtual std::vector getWorkerInfos() const = 0;
+
+  // Retrieve the timeout for all RPCs.
+  inline std::chrono::milliseconds getRpcTimeout() const {
+    return rpcTimeout_.load();
+  }
+
+  // Set the timeout for all RPCs
+  inline void setRpcTimeout(const std::chrono::milliseconds& rpcTimeout) {
+    rpcTimeout_.store(rpcTimeout);
+  }
+
+  // Call sync and join all internal threads. This method should be called
+  // before every RPC process exits.
+  virtual void join(bool shutdown = false, float timeout = 0) = 0;
+
+  // Synchronize the this process with other ``RpcAgent`` processes. Block until
+  // all ``RpcAgent``s reach this method and send all pending messages.
+  virtual void sync() = 0;
+
+  // Sets up backend-agnostic state for accepting requests. Currently, this
+  // entails setting rpcAgentRunning_ to true, creating the retry thread, and
+  // calling the backend's startImpl.
+  void start();
+
+  // Derived classes must override this function to start accepting requests.
+  // This is used to initialize any backend-specific state. Users must call
+  // start, not startImpl, to initialize the RPC Agent.
+  virtual void startImpl() = 0;
+
+  // Stop accepting requests and shutdown the RPC framework as soon as possible
+  // by terminating all RPC threads.
+  void shutdown();
+
+  // Derived classes must override this function to start accepting requests.
+  // THis is used to clean up any backend-specific state. Users must call
+  // shutdown, not shutdownImpl, to shutdown the RPC Agent.
+  virtual void shutdownImpl() = 0;
+
+  // Check if current RPC agent is set.
+  static bool isCurrentRpcAgentSet();
+
+  // Retrieve the valid current RPC agent.
+  static std::shared_ptr getCurrentRpcAgent();
+
+  // Set the current RPC agent.
+  static void setCurrentRpcAgent(std::shared_ptr rpcAgent);
+
+  // Retrieve metrics as KV map
+  virtual std::unordered_map getMetrics() = 0;
+
+  // Retrieve debug info in addition to metrics as KV map
+  virtual std::unordered_map getDebugInfo();
+
+  // Flag to control whether GIL wait times
+  // should be profiled or not.
+  void enableGILProfiling(bool flag);
+
+  // Retrieve wheher we should profile GIL wait times or not.
+  bool isGILProfilingEnabled();
+
+  // Set type resolver that will be passed to JIT pickler to resolver type Ptr
+  // based on type str.
+  void setTypeResolver(std::shared_ptr typeResolver);
+
+  // Get the type resolver
+  std::shared_ptr getTypeResolver();
+
+  // Retrieves the device map for the provided destination worker.
+  virtual DeviceMap getDeviceMap(const WorkerInfo& dst) const;
+
+  // Retrieve the (non-CPU) devices that are supported by the agent.
+  virtual const std::vector& getDevices() const;
+
+ protected:
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  const WorkerInfo workerInfo_;
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  const std::unique_ptr cb_;
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  std::atomic rpcTimeout_;
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  std::atomic profilingEnabled_;
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  std::shared_ptr typeResolver_;
+  // Atomic boolean indicating whether this agent is running. It controls
+  // whether several background threads should be running. It is set in
+  // RpcAgent::start() and unset in the derived class shutdown().
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  std::atomic rpcAgentRunning_;
+
+ private:
+  static std::shared_ptr currentRpcAgent_;
+  // Add GIL wait time data point to metrics
+  virtual void addGilWaitTime(const std::chrono::microseconds gilWaitTime) = 0;
+  friend class PythonRpcHandler;
+
+  // Map that stores metadata for RPC's that may need to be re-tried as well as
+  // the timepoint at which we should re-try them.
+  std::map<
+      steady_clock_time_point,
+      std::unordered_set>>
+      rpcRetryMap_;
+
+  // Thread that checks for retryable RPC's in the rpcRetryMap_ and sleeps until
+  // the next unACKed RPC's timeout has expired.
+  std::thread rpcRetryThread_;
+
+  // Function that rpcRetryThread_ calls in a loop as long as RpcAgent is
+  // running.
+  void retryExpiredRpcs();
+
+  // This is the callback attached to futures corresponding to send retries.
+  // This handles 3 cases: 1). send was completed, 2). send failed with an
+  // error and we've done maxRetries failed send attempts, and 3). send
+  // failed with an error and we have more retries to go. In case 1, we mark
+  // the original future as complete. In case 2, we mark the future with an
+  // error and do not retry again. In case 3, we move the RpcRetryInfo struct
+  // to another time point in the map to schedule the RPC for a future send.
+  void rpcRetryCallback(
+      JitFuture& message,
+      steady_clock_time_point newTime,
+      std::shared_ptr earliestRpc);
+
+  // Function that uses the exponential backoff algorithm to compute the next
+  // time point to retry a given RPC.
+  inline steady_clock_time_point computeNewRpcRetryTime(
+      RpcRetryOptions& options,
+      int retryCount) {
+    // The exponential backoff algorithm being used here is:
+    // newTime = timeNow + (retryDuration * (backoffConstant ^ retryCount)).
+    std::chrono::milliseconds timedelta =
+        std::chrono::duration_cast(
+            options.rpcRetryDuration * pow(options.retryBackoff, retryCount));
+    return std::chrono::time_point_cast(
+        std::chrono::steady_clock::now() + timedelta);
+  }
+
+  // Condition Variable to signal when the rpcRetryMap_ has been populated.
+  std::condition_variable rpcRetryMapCV_;
+
+  // Mutex to protect RpcRetryMap_.
+  std::mutex rpcRetryMutex_;
+};
+
+} // namespace torch::distributed::rpc
+
+namespace std {
+template <>
+struct hash {
+  std::size_t operator()(
+      const torch::distributed::rpc::WorkerInfo& worker_info) const noexcept {
+    return worker_info.id_;
+  }
+};
+} // namespace std
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/rpc_command_base.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/rpc_command_base.h
new file mode 100644
index 0000000000000000000000000000000000000000..91821930ac2f4f0d6975394e6e7f19dd4c414aa6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/rpc_command_base.h
@@ -0,0 +1,23 @@
+#pragma once
+
+#include 
+#include 
+
+namespace torch::distributed::rpc {
+
+// Base class for all RPC request and responses.
+class RpcCommandBase {
+ public:
+  // Need to override this to serialize the RPC. This should destructively
+  // create a message for the RPC (Hence the &&).
+  c10::intrusive_ptr toMessage() && {
+    JitRRefPickleGuard jitPickleGuard;
+    return std::move(*this).toMessageImpl();
+  }
+  virtual c10::intrusive_ptr toMessageImpl() && = 0;
+  virtual ~RpcCommandBase() = 0;
+};
+
+inline RpcCommandBase::~RpcCommandBase() = default;
+
+} // namespace torch::distributed::rpc
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/rref_context.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/rref_context.h
new file mode 100644
index 0000000000000000000000000000000000000000..3282e8c0e108f5ddf86ad2c135f1d1b1ba4097b2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/rref_context.h
@@ -0,0 +1,335 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+namespace torch::distributed::rpc {
+
+namespace callback {
+// It's the callback for RemoteCall.
+void TORCH_API
+confirmPendingUser(const JitFuture& jitFuture, const ForkId& expectedForkId);
+
+// It's the callback for finishing creating owner rref, it returned deletedRRef,
+// so that the deletedRRef can be handled under GIL in python_functions.cpp if
+// deletedRRef contains python object.
+c10::intrusive_ptr TORCH_API
+finishCreatingOwnerRRef(const JitFuture& jitFuture, const RRefId& rrefId);
+} // namespace callback
+
+// Manages RRef lifetime and keeps track of RRef forks.
+class TORCH_API RRefContext {
+ public:
+  static RRefContext& getInstance();
+  // NB: This method must be called before destructing RRefContext singleton.
+  // Similar to delForkOfOwner, this method returns a vector of OwnerRRefs that
+  // hold py::object. The call-site is also responsible for resetting those
+  // shared_ptr objects with a GIL. See comments at delForkOfOwner() for more
+  // details.
+  static std::vector> destroyInstance(
+      bool ignoreRRefLeak = true);
+
+  static void handleException(const JitFuture& jitFuture);
+
+  // handle exception without throw ::c10::Error again
+  static void handleExceptionSilent(const JitFuture& jitFuture);
+
+  RRefContext(const RRefContext&) = delete;
+  RRefContext(RRefContext&& other) = delete;
+  void operator=(const RRefContext&) = delete;
+  RRefContext& operator=(RRefContext&& other) = delete;
+
+  ~RRefContext();
+
+  // get the worker id of the current worker
+  inline worker_id_t getWorkerId() const {
+    return agent_->getWorkerInfo().id_;
+  }
+
+  // get the worker name of the current worker
+  inline const std::string& getWorkerName() const {
+    return agent_->getWorkerInfo().name_;
+  }
+
+  //  generate a globally unique ID
+  inline GloballyUniqueId genGloballyUniqueId() {
+    return GloballyUniqueId(getWorkerId(), nextLocalId_++);
+  }
+
+  inline const std::shared_ptr& agent() const {
+    return agent_;
+  }
+
+  // create a ``UserRRef`` owned by the worker ``ownerId``
+  c10::intrusive_ptr createUserRRef(
+      worker_id_t ownerId,
+      const TypePtr& type);
+
+  // Convert an RRefForkData into an RRef. This RRef could be user or owner.
+  // This RRef could have already existed before, or could be created in this
+  // method, we pass type here to validate or help the rref creation.
+  c10::intrusive_ptr getOrCreateRRef(
+      const RRefForkData& rfd,
+      const TypePtr& type);
+
+  // Get the ``OwnerRRef`` of id ``rrefId``. If it does not exist, create a new
+  // one. This function is called in two places:
+  // 1. when processing ``rpc.remote()``, i.e., ``SCRIPT_REMOTE_CALL``
+  //    ``PYTHON_REMOTE_CALL``.
+  // 2. when unpickling ``OwnerRRef``.
+  // What's common in these two cases are, 1) the RRefId is already generated
+  // 2) the TypePtr is presented. So it can always create the ``OwnerRRef`` if
+  // it is not yet available.
+  c10::intrusive_ptr getOrCreateOwnerRRef(
+      const RRefId& rrefId,
+      const TypePtr& type);
+
+  // Create an empty owner rref of type.
+  // This method is called to first time generate an ``OwnerRRef``, e.g.,
+  // 1) ``rpc.RRef(obj)``
+  // 2) create the ``OwnerRRef`` on `rpc.remote()` caller side.
+  // What's common in these two cases are, 1) the RRefId hasn't been generated
+  // 2) the TypePtr is presented.
+  c10::intrusive_ptr createOwnerRRef(const TypePtr& type);
+
+  // Returns a Future of the OwnerRRef, which will be marked completed when
+  // ``OwnerRRef`` is created. This method is used when the TypePtr is not
+  // available, e.g., when processing to_here(). The forceCreated flag can be
+  // used to ensure that the rref is created on the owner, otherwise throw in
+  // cases where the user of this API expects this to return a completed future.
+  // Note that the return value is a intrusive_ptr to a c10::ivalue::Future that
+  // holds the RRef.
+  c10::intrusive_ptr getOwnerRRef(
+      const RRefId& rrefId,
+      bool forceCreated = false);
+
+  // Adding the RRefId of an OwnerRRef into the forks_ map. This is useful when
+  // making a remote call to self, which as for now, still goes through serde
+  // and invokes request callback. In this case, the OwnerRRef has already been
+  // created on the send side, and we need to pass it to the receive side,
+  // instead of creating a new OwnerRRef. This is done by adding the OwnerRRef
+  // into owners_. However, that alone is not enough, as it could be deleted
+  // when all UserRRef die, which would then remove the OwnerRRef from owners_
+  // and this could happen before the self remote call finishes. To prevent
+  // that, this API adds the RRefId as a ForkId, which will then delete the
+  // ForkId when the self remote is done.
+  void addSelfAsFork(c10::intrusive_ptr& rref);
+
+  // Register a fork of the ``OwnerRRef``, and inserts a intrusive_ptr of the
+  // ``OwnerRRef`` in a map to keep it alive.
+  void addForkOfOwner(const RRefId& rrefId, const ForkId& forkId);
+  // Performs the same function as addForkOfOwner but ignores duplicate
+  // requests. This idempotent function is used with RREF_FORK_REQUEST calls,
+  // whereas all other message types use the non-idempotent variant.
+  void addForkOfOwnerIfNotPresent(const RRefId& rrefId, const ForkId& forkId);
+  // Delete a fork of the ``OwnerRRef``. NB: this could trigger deletion on the
+  // IValue or py::object. For the later, this method will acquire GIL.
+  // NB: If this fork deletion triggered deleting OwnerRRef, this method will
+  // return a shared_ptr to the OwnerRRef, which is likely to be the last
+  // shared_ptr instance for it. Therefore, deleting this shared_ptr
+  // will also trigger deleting the object it points to. If OwnerRRef holds a
+  // py::object, deleting it require GIL. The call site should guarded it with
+  // a GIL and reset the shared_ptr. The GIL-guarded deletion is intentionally
+  // left out of this function to avoid creating dependency on pybind.
+  c10::intrusive_ptr delForkOfOwner(
+      const RRefId& rrefId,
+      const ForkId& forkId);
+
+  // Invoked when pickling an RRef to setup child/fork properly
+  RRefForkData prepareChildFork(const c10::intrusive_ptr& rref);
+  // Invoked when unpickling an RRef to send RREF_FORK_REQUEST to owner and
+  // send RREF_CHILD_ACCEPT to the parent.
+  // NB: forkId is necessary here as the rref could be an OwnerRRef
+  void notifyOwnerAndParentOfFork(
+      const ForkId& forkId,
+      worker_id_t parent,
+      const c10::intrusive_ptr& rref);
+
+  // When a UserRRef is forked to another worker (user or owner), it is added
+  // into pendingChildren_ to be held alive until it receives RREF_CHILD_ACCEPT
+  // from the child.
+  // NB: This is necessary for both user and owner child. As we do not have FIFO
+  // communication between workers, we need this strategy to make sure that all
+  // previously submitted rpc/remote calls are acked before sending out the
+  // RREF_USER_DELETE message. Otherwise, the OwnerRRef could be deleted too
+  // soon.
+  void addPendingChild(
+      const ForkId& forkId,
+      const c10::intrusive_ptr& rref);
+  void delPendingChild(const ForkId& forkId);
+
+  // When a UserRRef is created, it is added into pendingUsers_ to be held alive
+  // until it receives RREF_USER_ACCEPT from the owner.
+  void addPendingUser(
+      const ForkId& forkId,
+      const c10::intrusive_ptr& rref);
+  void delPendingUser(const ForkId& forkId);
+  void addConfirmedUser(
+      const ForkId& forkId,
+      const c10::intrusive_ptr& rref);
+
+  // Retrieve a pending user given the fork ID. Throws if the user has already
+  // been confirmed (i.e. is no longer in the pendingUsers_ map).
+  c10::intrusive_ptr getPendingUser(const ForkId& forkId);
+
+  // Start recording new pending UserRRefs. All pending UserRRefs introduced
+  // after this point will be put into the thread_local userTable_, which will
+  // then be consumed and cleared in waitForThreadLocalPendingRRefs().
+  void recordThreadLocalPendingRRefs();
+  // End recording new pending UserRRefs, and clear the thread_local userTable_.
+  // Returns a Future which will be marked as completed when all pending
+  // UserRRefs in the current userTable_ are confirmed by their owners. The bool
+  // value in the Future is unused.
+  // This method is useful to make sure RRefs in user function arguments are
+  // confirmed before launching user code.
+  // NB: Callers of this method does not need to keep the returned Future alive,
+  // because this Future is already captured in callbacks of the
+  // PendingUserState. If there is no pending UserRRefs, this method returns a
+  // completed future.
+  c10::intrusive_ptr waitForThreadLocalPendingRRefs();
+  // Only call this function when there are errors during a recording session,
+  // and it is likely that waitForThreadLocalPendingRRefs() cannot be invoked
+  // properly.
+  // TODO: make this a context guard
+  void clearRecordedPendingRRefsOnError();
+
+  void delUser(
+      const worker_id_t owner,
+      const RRefId& rrefId,
+      const ForkId& forkId);
+  void delAllUsersAndUnforkedOwners(std::chrono::milliseconds timeoutMillis);
+
+  std::unordered_map getDebugInfo();
+
+ private:
+  struct PendingUserState {
+    PendingUserState(c10::intrusive_ptr rref)
+        : rref_(std::move(rref)),
+          confirmationFuture_(c10::make_intrusive(BoolType::get())) {
+    }
+
+    inline void confirm() {
+      c10::static_intrusive_pointer_cast(rref_)->confirm();
+      confirmationFuture_->markCompleted();
+    }
+
+    c10::intrusive_ptr rref_;
+    // Use Future.wait() and Future.markCompleted() to block and unblock user
+    // functions. The bool value wrapped by the future_ is not used.
+    c10::intrusive_ptr confirmationFuture_;
+  };
+
+  RRefContext(std::shared_ptr);
+
+  c10::intrusive_ptr createUserRRef(
+      worker_id_t ownerId,
+      const RRefId& rrefId,
+      const ForkId& forkId,
+      const TypePtr& type);
+
+  void finishForkRequest(const ForkId& forkId, worker_id_t parent);
+
+  // If there is any leak on any RRef, this method will throw an error.
+  void checkRRefLeaks(bool ignoreRRefLeak);
+
+  static std::atomic nextLocalId_;
+
+  const std::shared_ptr agent_;
+  mutable std::mutex mutex_;
+  // Keep OwnerRRefs alive until there is no living UserRRefs.
+  std::unordered_map, RRefId::Hash> owners_;
+  // A map to track OwnerRRefs that are requested but not yet created. This can
+  // happen if the to_here() message is processed on the owner before the
+  // corresponding creator rpc.remote() message. If this happens, instead of
+  // to_here() RPC thread to block waiting for the OwnerRRef creation, the
+  // RRefContext returns a Future, so that the RPC request processing logic can
+  // attach subsequent code as a callback to that Future.
+  // NB: the OwnerRRefs in this map must be cleared when the corresponding
+  // OwnerRRef is created. Note that the values in this map are intrusive_ptrs
+  // to c10::ivalue::Future that will be marked completed with the owner RRef.
+  std::unordered_map, RRefId::Hash>
+      pendingOwners_;
+  // Tracks known living UserRRefs of an OwnerRRef
+  std::unordered_map<
+      RRefId,
+      std::unordered_set,
+      RRefId::Hash>
+      forks_;
+
+  // This cond var is used by deleteAllUsers(), a event notification is sent if
+  // number of pending UserRRef or UserRRef children is reduced, or
+  // number of owned OwnerRRef is reduced.
+  std::condition_variable deleteAllUsersCV_;
+  // The follow 3 maps keep UserRRefs alive by holding a intrusive_ptr to the
+  // RRef instances. A UserRRef must be added into this map if any of the
+  // following two conditions is true:
+  //
+  // (1) A UserRRef has not been accepted by owner yet.
+  //
+  //     It can be used or shared, but cannot be deleted, and hence kept alive
+  //     in this map. A message of type RREF_USER_ACCEPT will move the
+  //     corresponding RRef from pendingUsers_ map to confirmedUsers_ map.
+  std::unordered_map, ForkId::Hash>
+      pendingUsers_;
+  //     UserRRefs are added into this map when it is confirmed by the owner.
+  //     When destroying RRefContext this map helps to find local UserRRefs
+  //     and send delete messages if they are still not deleted by Python
+  //     garbage collection.
+  std::unordered_map, ForkId::Hash>
+      confirmedUsers_;
+
+  // (2) A UserRRef has forked a child UserRRef which has not been accepted by
+  //     the owner yet.
+  //
+  //     In this case, this UserRRef cannot send out RREF_USER_DELETE message,
+  //     as it could potentially trigger the OwnerRRef been deleted before the
+  //     owner learns about the forked child.
+  std::unordered_map, ForkId::Hash>
+      pendingChildren_;
+
+  // The RRef context performs its operations through async RPC requests, in
+  // order to not block the user code. Therefore the RRef context's state may be
+  // lagging a bit behind what it is intended to be, while it waits for these
+  // requests to complete. To allow syncing when needed, we store the count of
+  // these pending requests, so that users can wait for it to reach zero.
+  std::atomic numPendingFutures_{0};
+
+  std::mutex destroyedMutex_;
+  bool destroyed_{false};
+
+  // Thread local states to keep UserRRefs deserialized from user function
+  // arguments.
+  static thread_local std::vector> userTable_;
+  // A flag indicating whether subsequently created UserRRefs should be added to
+  // the thread_local userTable_. The flag is set to true before serializing
+  // RPC arguments and then set to false before running the corresponding
+  // user code. See addPendingUser and delPendingUser for more details.
+  // NB: The reason for having this flag is because addPendingUser are called in
+  // two cases, and we only want to track the 2nd case.
+  // (1) RRef as the return value: when calling rpc.remote, the UserRRef on the
+  //     caller side is added to the context using addPendingUser.
+  // (2) RRef as an argument: When running an RPC using RRefs as arguments, the
+  //     RRef is forwarded to the callee as new UserRRefs (if the callee is not
+  //     the owner). In this case, we block running the user function until all
+  //     UserRRefs are confirmed by the owner.
+  // This contract gurantees that no UserRRefs can be used remotely without
+  // confirmation. Note that, however, the UserRRef created by rpc.remote can
+  // still be passed to local functions as arguments and used there. This is by
+  // design, because this feature is especially useful when, say a master node
+  // creates multiple UserRRefs in a loop and then shares them with other nodes.
+  // Blocking every iteration in the loop until RRefs are confirmed will slow
+  // this down. This nuance on UserRRef can be interpreted as we only make
+  // exceptions for UserRRef creators. And using the UserRRef on its creator
+  // without confirmation is OK, because the creator would either call to_here
+  // or forward the UserRRef, and both would then require confirmations from the
+  // owner.
+  static thread_local bool recording_;
+};
+
+} // namespace torch::distributed::rpc
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/rref_impl.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/rref_impl.h
new file mode 100644
index 0000000000000000000000000000000000000000..8a1634ca61f30acfaf661b19b8a52b3fbde3b21b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/rref_impl.h
@@ -0,0 +1,416 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+namespace torch::distributed::rpc {
+
+class RRef;
+class RRefContext;
+class UserRRef;
+
+constexpr int OWNER_IDX = 0; // index of ownerId in the tuple
+constexpr int RREFID_ON_IDX = 1; // index of RRefId.createdOn_ in the tuple
+constexpr int RREFID_ID_IDX = 2; // index of RRefId.localId_ in the tuple
+constexpr int FORKID_ON_IDX = 3; // index of ForkId.createdOn_ in the tuple
+constexpr int FORKID_ID_IDX = 4; // index of ForkId.localId_ in the tuple
+constexpr int PARENT_IDX = 5; // index of parent in the tuple
+constexpr int TYPE_IDX = 6; // index of parent in the tuple
+
+// NB: if more fields are added, make sure this field is also bumped
+constexpr int RFD_TUPLE_SIZE = 7; // number of RRefForkData fields in py::tuple
+
+// Represents fork of an RRef to be sent over the wire.
+struct TORCH_API RRefForkData {
+  const worker_id_t ownerId_;
+  const RRefId rrefId_;
+  const ForkId forkId_;
+  const worker_id_t parent_;
+  const std::string typeStr_;
+
+  RRefForkData(
+      worker_id_t ownerId,
+      const RRefId& rrefId,
+      const ForkId& forkId,
+      worker_id_t parent,
+      std::string typeStr);
+};
+
+// Note [RRef Protocol]
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~
+//
+// [Background]
+//
+// RRef stands for Remote REFerence. Each RRef is owned by a single worker
+// (i.e., owner) and can be used by multiple users. The owner stores the real
+// data referenced by its RRefs. RRef needs to support fast and scalable RPC.
+// Hence, in the design, we avoid using a single global master to keep RRef
+// states, instead owners will keep track of the global reference counts
+// for its RRefs. Every RRef can be uniquely identified by a global RRefId,
+// which is assigned at the time it is first created either on a user or on the
+// owner.
+//
+// On the owner worker, there is only one OwnerRRef instance, which contains the
+// real data, while on user workers, there can be as many UserRRefs as
+// necessary, and UserRRef does not hold the data. All usage on the OwnerRRef
+// should retrieve the unique OwnerRRef instance using the globally unique
+// RRefId. //A UserRRef will be created when it is used as an argument or return
+// value in dist.rpc or dist.remote call, but RRef forking and reference
+// counting (RC) are completely transparent to applications. Every UserRRef will
+// also have its globally unique ForkId.
+//
+// [Assumptions]
+//
+// 1. Transient Network Failures
+//
+// TODO: current RRef implementation does not tolerate failures
+//
+// The RRef design handles transient network failures by retrying
+// messages. Node crashes or permanent network partition is beyond the scope.
+// When those incidents occur, the application may take down all workers, revert
+// to the previous checkpoint, and resume training.
+//
+// 2. Non-idempotent UDFs
+//
+// We assume UDFs are not idempotent and therefore cannot be retried. However,
+// internal RRef control messages are idempotent and retried upon message
+// failure.
+//
+// TODO: RRef internal messages are not yet idempotent
+//
+// 3. Out of Order Message Delivery
+//
+// We do not assume message delivery order between any pair of nodes, because
+// both sender and receiver are using multiple threads. There is no guarantee on
+// which message will be processed first.
+//
+// [RRef Lifetime]
+//
+// The goal of the protocol is to delete an OwnerRRef at an appropriate time.
+// The right time to delete an OwnerRRef is when there are no living UserRRefs
+// and Python GC also agrees to delete the OwnerRRef instance on the owner. The
+// tricky part is to determine if there are any living UserRRefs.
+//
+// A user can get a UserRRef in three situations:
+//
+// (1). Receiving a UserRRef from the owner.
+// (2). Receiving a UserRRef from another user.
+// (3). Creating a new UserRRef owned by another worker.
+//
+// (1) is the simplest case where the owner initiates the fork, and hence it can
+// easily increment local RC. The only requirement is that any UserRRef must
+// notify the owner before destruction. Hence, we need the first guarantee:
+//
+// G1. The owner will be notified when any UserRRef is deleted.
+//
+// As messages might come delayed or out-of-order, we need more one guarantee to
+// make sure the delete message is not sent out too soon. Let us first introduce
+// a new concept. If A sends an RPC to B that involves an RRef, we call the RRef
+// on A the parent RRef and the RRef on B the child RRef.
+//
+// G2. Parent RRef cannot be deleted until the child RRef is confirmed by the
+//     owner.
+//
+// Under (1), where the caller is UserRRef and callee is OwnerRRef, it simply
+// means that the user will not send out the delete message until all previous
+// messages are ACKed. Note that ACKed does not mean the owner finishes
+// executing the function, instead, it only means the owner has retrieved its
+// local OwnerRRef and about to pass it to the function, which is sufficient to
+// keep the OwnerRRef alive even if the delete message from the user arrives at
+// the owner before the function finishes execution.
+//
+// With (2) and (3), it is possible that the owner only partially knows the RRef
+// fork graph or not even knowing it at all. For example, the RRef could be
+// constructed on a user, and before the owner receives the RPC call, the
+// creator user might have already shared the RRef with other users, and those
+// users could further share the RRef. One invariant is that the fork graph of
+// any RRef is always a tree rooted at the owner, because forking an RRef always
+// creates a new RRef instance, and hence every RRef has a single parent. One
+// nasty detail is that when an RRef is created on a user, technically the owner
+// is not its parent but we still consider it that way and it does not break the
+// argument below.
+//
+// The owner's view on any node (fork) in the tree has three stages:
+//
+//       1) unknown -> 2) known -> 3) deleted.
+//
+// The owner's view on the entire tree keeps changing. The owner deletes its
+// OwnerRRef instance when it thinks there are no living UserRRefs, i.e., when
+// OwnerRRef is deleted, all UserRRefs could be either indeed deleted or
+// unknown. The dangerous case is when some forks are unknown and others are
+// deleted.
+//
+// G2 trivially guarantees that no parent UserRRef Y can be deleted before the
+// owner knows all of Y's children UserRRefs.
+//
+// However, it is possible that the child UserRRef Z may be deleted before the
+// owner knows its parent Y. More specifically, this can happen when all of Z's
+// messages are processed by the owner before all messages from Y, including the
+// delete message. Nevertheless, this does not cause any problem. Because, at
+// least one of Y's ancestor will be alive, and it will prevent the owner from
+// deleting the OwnerRRef. Consider the following example: (NB: this scenario
+// will no longer relevant when we block UDF until all RRefs are confirmed by
+// the owner)
+//
+//     OwnerRRef -> A -> Y -> Z
+//
+// OwnerRRef forks to A, then A forks to Y, and Y forks to Z. Z can be deleted
+// without OwnerRRef knowing Y. However, the OwnerRRef will at least know A, as
+// the owner directly forks the RRef to A. A won't die before the owner knows Y.
+//
+// Things get a little trickier if the RRef is created on a user:
+//
+//  OwnerRRef
+//      ^
+//      |
+//      A -> Y -> Z
+//
+// If Z calls to_here on the UserRRef, the owner at least knows A when Z is
+// deleted, because otherwise to_here wouldn't finish. If Z does not call
+// to_here, it is possible that the owner receives all messages from Z before
+// any message from A and Y. In this case, as the real data of the OwnerRRef has
+// not been created yet, there is nothing to be deleted either. It is the same
+// as Z does not exist at all Hence, it's still OK.
+//
+// See #26759 for more details and discussions.
+//
+// TODO: make RRef an IValue, and edit createStackForSchema accordingly
+// TODO: make RRef system messages idempotent and retry on failures.
+//
+// ``RRef`` is the base type for both ``UserRRef`` and ``OwnerRRef``.
+// Each ``RRef`` has a globally unique ``RRefId``.
+class TORCH_API RRef : public RRefInterface {
+ public:
+  // RRef is made NOT copyable NOT movable to prevent messing up reference
+  // counting.
+  explicit RRef(const RRef& other) = delete;
+  explicit RRef(RRef&& other) = delete;
+  RRef& operator=(RRef&& other) = delete;
+
+  ~RRef() override = default;
+
+  // returns the worker id of the owner
+  inline worker_id_t owner() const override {
+    return ownerId_;
+  }
+
+  // returns the worker name of the owner
+  inline std::string ownerName() const override {
+    return RpcAgent::getCurrentRpcAgent()->getWorkerInfo(ownerId_).name_;
+  }
+
+  // returns the worker info of the owner
+  inline WorkerInfo ownerWorkerInfo() const {
+    return RpcAgent::getCurrentRpcAgent()->getWorkerInfo(ownerId_);
+  }
+
+  // Returns the globally unique RRefId of this RRef
+  inline const RRefId& rrefId() const {
+    return rrefId_;
+  }
+
+  inline bool isPyObj() const {
+    return type_ == PyObjectType::get();
+  }
+  inline const TypePtr type() const override {
+    return type_;
+  }
+
+  // Save the future corresponding to the creation of this RRef on a remote
+  // node. Note that this is only set when processing requests invoked with
+  // rpc.remote. This is only used to get the future corresponding to the rref
+  // for profiling use cases.
+  inline void registerOwnerCreationFuture(c10::intrusive_ptr fut) {
+    ownerCreationFuture_ = std::move(fut);
+  }
+
+  // Get the future corresponding to the creation of this rref.
+  inline c10::intrusive_ptr getOwnerCreationFuture() const {
+    return ownerCreationFuture_;
+  }
+
+  // Check if creation of this RRef on owner node has timed out.
+  inline bool getTimedOut() const {
+    return timedOut_.load();
+  }
+
+  // Dispatches an error to the correct handler based on its RPCErrorType.
+  void handleError(RPCErrorType errorType, const JitFuture& JitFuture);
+
+  // Send delete UserRRef request to Owner,
+  // if the request hasn't been sent yet.
+  // There are 2 cases to call it,
+  // 1, Python GC decides end of UserRRef lifetime, calling destructor.
+  // 2, RPC module graceful shutdown calls it on all UserRRefs tracked
+  //    in the RRefContext.
+  virtual void tryDel() {}
+
+ protected:
+  // Indicates that the creation of this RRef on owner node has timed out.
+  inline void setTimedOut() {
+    timedOut_ = true;
+  }
+  friend class RRefContext;
+
+  RRef(worker_id_t ownerId, const RRefId& rrefId, TypePtr type);
+
+  virtual RRefForkData fork() const;
+
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  const worker_id_t ownerId_;
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  const RRefId rrefId_;
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  std::atomic timedOut_{false};
+
+  // type field to denote the type of the element that the RRef is holding
+  // it could be any TypePtr that JIT support, including PyObjectType
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  const TypePtr type_;
+  // Future corresponding to request to create RRef on remote node.
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  c10::intrusive_ptr ownerCreationFuture_;
+};
+
+// ``UserRRef`` represents a user of an RRef. Besides the ``RRefId``, each user
+// also has a globally unique ``ForkId`` to identify this user. ``UserRRef``
+// never owns the real value, the only way to get the value of the ``RRef`` is
+// to call ``to_here()`` and get a copy..
+class TORCH_API UserRRef final : public RRef {
+ public:
+  UserRRef(const UserRRef& other) = delete;
+  UserRRef(UserRRef&& other) = delete;
+  UserRRef& operator=(const UserRRef& other) = delete;
+  UserRRef& operator=(UserRRef&& other) = delete;
+
+  UserRRef(
+      worker_id_t ownerId,
+      const RRefId& rrefId,
+      const ForkId& forkId,
+      TypePtr type);
+
+  inline bool isOwner() const override {
+    return false;
+  }
+
+  inline bool confirmedByOwner() const override {
+    return confirmedByOwner_;
+  }
+
+  // Returns the globally unique ForkId of this RRef
+  const ForkId& forkId() const;
+
+  // Get of copy of the value from the ``OwnerRRef``. If the value is not ready
+  // yet, this call will block.
+  IValue toHere(
+      const float timeoutSeconds =
+          torch::distributed::rpc::kUnsetRpcTimeout) const;
+
+  void tryDel() override;
+
+  // Will be called when refcount reaches 0.
+  // Upon destruction, this ``UserRRef`` will tell the owner to deref.
+  void release_resources() override;
+
+  // Will be called when both refcount and weakcount reach 0. See
+  // https://github.com/pytorch/pytorch/blob/9116f02bebf3a5260feef5732d36c54ecb3b4033/c10/util/intrusive_ptr.h#L204
+  // This is called on destructing the wrapping intrusive_ptr_target instance
+  // and it's data members.
+  ~UserRRef() override;
+
+ private:
+  friend class RRefContext;
+
+  RRefForkData fork() const override;
+  inline void confirm() {
+    confirmedByOwner_ = true;
+  }
+
+  const ForkId forkId_;
+
+  // Indicates if this user has sent delete message to it's owner.
+  // Note, thread safety is needed because delete message could be sent by
+  // either the destructor called by Python garbage collection or RRefContext
+  // proactive cleanup on RPC graceful shutdown.
+  std::mutex deletedOnOwnerMutex_;
+  bool deletedOnOwner_{false};
+  // Indicating whether this UserRRef has been confirmed by its owner.
+  std::atomic confirmedByOwner_;
+};
+
+// Keep the template only on the derived class because ``RRefContext`` needs to
+// erase the type on ``RRef`` and keep them in one map.
+class TORCH_API OwnerRRef final : public RRef {
+ public:
+  OwnerRRef(const OwnerRRef& other) = delete;
+  OwnerRRef(OwnerRRef&& other) = delete;
+  OwnerRRef& operator=(const OwnerRRef& other) = delete;
+  OwnerRRef& operator=(OwnerRRef&& other) = delete;
+
+  OwnerRRef(
+      worker_id_t ownerId,
+      const RRefId& rrefId,
+      TypePtr type,
+      std::vector devices);
+
+  OwnerRRef(
+      worker_id_t ownerId,
+      const RRefId& rrefId,
+      TypePtr type,
+      std::optional value,
+      std::vector devices);
+
+  inline bool isOwner() const override {
+    return true;
+  }
+
+  // OwnerRRef is always confirmed, while UserRRef is only confirmed when the
+  // owner knows about it.
+  inline bool confirmedByOwner() const override {
+    return true;
+  }
+
+  // Get a constant reference of the real value. This method will block if the
+  // value is not ready. This method does not need GIL as it does not create
+  // any new py::object. It will throw if there is an error.
+  const IValue& getValue() const;
+
+  // Set the value of this ``OwnerRRef``. This method does not need GIL as it
+  // does not create any new py::object.
+  void setValue(IValue&& value);
+  // Sets the value of this ``OwnerRRef`` to contain an exception.
+  void setError(std::exception_ptr eptr);
+
+  // Has a value or error been set?
+  bool hasValue() const;
+  // Gets a future that is satisfied when the value or error is set.
+  c10::intrusive_ptr getFuture();
+
+ private:
+  friend class RRefContext;
+
+  c10::intrusive_ptr future_;
+};
+
+TORCH_API std::ostream& operator<<(std::ostream& os, const RRef& rref);
+
+// Helper function that casts from c10::RRefInterface to OwnerRRef
+inline TORCH_API c10::intrusive_ptr fromRRefInterface(
+    const c10::intrusive_ptr& rrefInterface) {
+  return c10::static_intrusive_pointer_cast(rrefInterface);
+}
+
+// Helper function that casts from OwnerRRef to c10::RRefInterface
+inline TORCH_API c10::intrusive_ptr fromOwnerRRef(
+    const c10::intrusive_ptr& ownerRRef) {
+  return c10::static_intrusive_pointer_cast(ownerRRef);
+}
+
+} // namespace torch::distributed::rpc
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/rref_proto.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/rref_proto.h
new file mode 100644
index 0000000000000000000000000000000000000000..0a84ceac969bd478e16de63538b73897f7417baa
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/rref_proto.h
@@ -0,0 +1,160 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch::distributed::rpc {
+
+// Temporary solution of RRef operations.
+// TODO: Remove all these messages and use rpc + registered functions instead.
+class TORCH_API RRefMessageBase : public RpcCommandBase {
+ public:
+  RRefMessageBase(const RRefId& rrefId, MessageType type)
+      : rrefId_(rrefId), type_(type) {}
+
+  const RRefId& rrefId();
+
+ protected:
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  const RRefId rrefId_;
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  const MessageType type_;
+};
+
+class TORCH_API ForkMessageBase : public RRefMessageBase {
+ public:
+  ForkMessageBase(const RRefId& rrefId, const ForkId& forkId, MessageType type)
+      : RRefMessageBase(rrefId, type), forkId_(forkId) {}
+
+  const ForkId& forkId();
+
+  c10::intrusive_ptr toMessageImpl() && override;
+  static std::pair fromMessage(
+      const Message& message,
+      MessageType type);
+
+ protected:
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  const ForkId forkId_;
+};
+
+// UserRRef uses this message to fetch the remote RRef value from the owner.
+class TORCH_API ScriptRRefFetchCall final : public RRefMessageBase {
+ public:
+  ScriptRRefFetchCall(worker_id_t fromWorkerId, const RRefId& rrefId)
+      : RRefMessageBase(rrefId, MessageType::SCRIPT_RREF_FETCH_CALL),
+        fromWorkerId_(fromWorkerId) {}
+
+  inline worker_id_t fromWorkerId() const {
+    return fromWorkerId_;
+  }
+
+  c10::intrusive_ptr toMessageImpl() && override;
+  static std::unique_ptr fromMessage(
+      const Message& message);
+
+ private:
+  const worker_id_t fromWorkerId_;
+};
+
+class TORCH_API PythonRRefFetchCall final : public RRefMessageBase {
+ public:
+  PythonRRefFetchCall(worker_id_t fromWorkerId, const RRefId& rrefId)
+      : RRefMessageBase(rrefId, MessageType::PYTHON_RREF_FETCH_CALL),
+        fromWorkerId_(fromWorkerId) {}
+
+  c10::intrusive_ptr toMessageImpl() && override;
+  static std::unique_ptr fromMessage(
+      const Message& message);
+
+ private:
+  const worker_id_t fromWorkerId_;
+};
+
+// OwnerRRef uses this message to send the RRef value to a remote UserRRef
+class TORCH_API RRefFetchRet : public RpcCommandBase {
+ public:
+  RRefFetchRet(std::vector values, MessageType type)
+      : values_(std::move(values)), type_(type) {}
+
+  const std::vector& values();
+  c10::intrusive_ptr toMessageImpl() && override;
+
+ private:
+  std::vector values_;
+  const MessageType type_;
+};
+
+class TORCH_API ScriptRRefFetchRet final : public RRefFetchRet {
+ public:
+  explicit ScriptRRefFetchRet(std::vector values)
+      : RRefFetchRet(std::move(values), MessageType::SCRIPT_RREF_FETCH_RET) {}
+
+  static std::unique_ptr fromMessage(
+      const Message& message);
+};
+
+class TORCH_API PythonRRefFetchRet final : public RRefFetchRet {
+ public:
+  explicit PythonRRefFetchRet(std::vector values)
+      : RRefFetchRet(std::move(values), MessageType::PYTHON_RREF_FETCH_RET) {}
+
+  static std::unique_ptr fromMessage(
+      const Message& message);
+};
+
+// UserRRef (regardless it's the creator or not) uses this message to notify
+// OwnerRRef on delete.
+class TORCH_API RRefUserDelete final : public ForkMessageBase {
+ public:
+  RRefUserDelete(const RRefId& rrefId, const ForkId& forkId)
+      : ForkMessageBase(rrefId, forkId, MessageType::RREF_USER_DELETE) {}
+
+  static std::unique_ptr fromMessage(const Message& message);
+};
+
+class TORCH_API RemoteRet final : public ForkMessageBase {
+ public:
+  RemoteRet(const RRefId& rrefId, const ForkId& forkId)
+      : ForkMessageBase(rrefId, forkId, MessageType::REMOTE_RET) {}
+
+  static std::unique_ptr fromMessage(const Message& message);
+};
+
+// A child RRef uses this message to notify its parent that the child has been
+// confirmed by the owner.
+class TORCH_API RRefChildAccept final : public RpcCommandBase {
+ public:
+  explicit RRefChildAccept(const ForkId& forkId) : forkId_(forkId) {}
+
+  const ForkId& forkId() const;
+
+  c10::intrusive_ptr toMessageImpl() && override;
+  static std::unique_ptr fromMessage(const Message& message);
+
+ private:
+  const ForkId forkId_;
+};
+
+// A child RRef uses this message to send a fork request to the owner.
+class TORCH_API RRefForkRequest final : public ForkMessageBase {
+ public:
+  RRefForkRequest(const RRefId& rrefId, const ForkId& forkId)
+      : ForkMessageBase(rrefId, forkId, MessageType::RREF_FORK_REQUEST) {}
+
+  static std::unique_ptr fromMessage(const Message& message);
+};
+
+class TORCH_API RRefAck final : public RpcCommandBase {
+ public:
+  RRefAck() = default;
+
+  c10::intrusive_ptr toMessageImpl() && override;
+  static std::unique_ptr fromMessage(const Message& message);
+};
+
+} // namespace torch::distributed::rpc
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/script_call.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/script_call.h
new file mode 100644
index 0000000000000000000000000000000000000000..5db4adf95f85bad2b712293e0e85ec12f60af3ef
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/script_call.h
@@ -0,0 +1,71 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace distributed {
+namespace rpc {
+
+using torch::jit::Operator;
+
+// A ScriptCall instance represents an invocation of a builtin operator for a
+// TorchScript function. If it is a builtin operator, it
+// contains a shared ptr to the `Operator` and a list of arguments.
+// If it is a TorchScript function, it contains a non empty qualifiedName string
+// to the TorchScript function schema name and a list of arguments.
+class TORCH_API ScriptCall : public RpcCommandBase {
+ public:
+  // Constructor for builitin operator call.
+  ScriptCall(std::shared_ptr op, std::vector&& stack);
+  // Constructor for TorchScript function call.
+  ScriptCall(
+      const c10::QualifiedName& qualifiedName,
+      std::vector&& stack,
+      const bool isAsyncExecution = false);
+
+  bool hasOp() const;
+  std::shared_ptr op() const;
+  bool hasQualifiedName() const;
+  const c10::QualifiedName& qualifiedName() const;
+  // return the argument stack of this builtin operator
+  const std::vector& stack() const;
+  std::vector& stackRef();
+  inline bool isAsyncExecution() const {
+    return isAsyncExecution_;
+  }
+
+  c10::intrusive_ptr toMessageImpl() && override;
+  static std::unique_ptr fromMessage(const Message& message);
+
+  ~ScriptCall() override = default;
+
+ protected:
+  virtual void toIValues(std::vector& ivalues) const;
+  static std::unique_ptr fromIValues(
+      std::vector& ivalues);
+
+ private:
+  // Given an operator symbol and a string schema, return the matched operator.
+  static std::shared_ptr matchOperator(const std::string& str_schema);
+
+  static const std::string BUILTIN_OP_NAMESPACE_;
+  static const std::string ATEN_PREFIX_;
+
+  // This field has value if this ScriptCall represents invocation of a builtin
+  // operator.
+  std::optional> op_;
+  // This field has non empty string if this ScriptCall represents invocation of
+  // an annotated torchscript function defined by users.
+  std::optional qualifiedName_;
+  std::vector stack_;
+  const bool isAsyncExecution_;
+};
+
+} // namespace rpc
+} // namespace distributed
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/script_remote_call.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/script_remote_call.h
new file mode 100644
index 0000000000000000000000000000000000000000..460bc7352bd1f1d7571c4a705a4eae49f6532eec
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/script_remote_call.h
@@ -0,0 +1,57 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace distributed {
+namespace rpc {
+
+using torch::jit::Operator;
+
+// A ScriptRemoteCall instance represents an invocation of `dist.remote` on a
+// builtin operator. Currently, it does not support using RRef as arguments yet.
+// Besides the operator and a vector of arguments, ScriptRemoteCall also
+// contains the RRefId and the ForkId of the return value RRef.
+class TORCH_API ScriptRemoteCall final : public ScriptCall {
+ public:
+  // Constructor for builitin operator call.
+  ScriptRemoteCall(
+      std::shared_ptr op,
+      std::vector&& stack,
+      const RRefId& retRRefId,
+      const ForkId& retForkId);
+
+  // Constructor for TorchScript function call.
+  ScriptRemoteCall(
+      const c10::QualifiedName& qualifiedName,
+      std::vector&& stack,
+      const RRefId& retRRefId,
+      const ForkId& retForkId,
+      const bool isAsyncExecution);
+
+  inline const RRefId& retRRefId() const {
+    return retRRefId_;
+  }
+
+  inline const ForkId& retForkId() const {
+    return retForkId_;
+  }
+
+  static std::unique_ptr fromIValues(
+      std::vector& ivalues);
+
+  c10::intrusive_ptr toMessageImpl() && override;
+  static std::unique_ptr fromMessage(const Message& message);
+
+ private:
+  const RRefId retRRefId_;
+  const ForkId retForkId_;
+};
+
+} // namespace rpc
+} // namespace distributed
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/script_resp.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/script_resp.h
new file mode 100644
index 0000000000000000000000000000000000000000..958b59bab5bbd1d8818964e5af9c42b3f4a16154
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/script_resp.h
@@ -0,0 +1,26 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace distributed {
+namespace rpc {
+
+// Return value of a builtin operator or a TorchScript function.
+class TORCH_API ScriptResp final : public RpcCommandBase {
+ public:
+  explicit ScriptResp(at::IValue&& values);
+
+  const at::IValue& value();
+  c10::intrusive_ptr toMessageImpl() && override;
+  static std::unique_ptr fromMessage(const Message& message);
+
+ private:
+  const at::IValue value_;
+};
+
+} // namespace rpc
+} // namespace distributed
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/tensorpipe_agent.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/tensorpipe_agent.h
new file mode 100644
index 0000000000000000000000000000000000000000..4decb445759c783b8d2c7dc54b918c9d714eae3a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/tensorpipe_agent.h
@@ -0,0 +1,492 @@
+#pragma once
+
+#ifdef USE_TENSORPIPE
+
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+// Forward-declare the TensorPipe classes we need, to avoid including its
+// headers in PyTorch's ones and thus have it become a public dependency.
+
+namespace tensorpipe {
+
+class Context;
+class Error;
+class Listener;
+class Message;
+class Pipe;
+
+namespace transport {
+class Context;
+} // namespace transport
+
+namespace channel {
+class Context;
+} // namespace channel
+
+} // namespace tensorpipe
+
+namespace torch::distributed::rpc {
+
+// These priorities instruct TensorPipe on which transport/channel to pick
+// during handshake. Higher priorities will take precedence over lower ones.
+// The transport with lowest priority will be the one used to bootstrap pipes.
+
+constexpr int64_t kShmTransportPriority = 200;
+constexpr int64_t kIbvTransportPriority = 100;
+// The UV transport just uses TCP and should work everywhere, thus keep it last.
+constexpr int64_t kUvTransportPriority = 0;
+
+constexpr int64_t kCmaChannelPriority = 1200;
+constexpr int64_t kMultiplexedUvChannelPriority = 1100;
+// The basic channel reuses a transport as a channel, and is thus our fallback.
+constexpr int64_t kBasicChannelPriority = 1000;
+
+// CPU channel have higher priority than CUDA channels, since the latter might
+// handle CPU-to-CPU transfers, but will always be less efficient than their
+// CPU-only counterparts.
+constexpr int64_t kCudaIpcChannelPriority = 300;
+constexpr int64_t kCudaGdrChannelPriority = 200;
+constexpr int64_t kCudaXthChannelPriority = 400;
+constexpr int64_t kCudaBasicChannelPriority = 0;
+
+using steady_clock_time_point =
+    std::chrono::time_point;
+
+struct TORCH_API TransportRegistration {
+  std::shared_ptr transport;
+  int64_t priority;
+  std::string address;
+};
+
+C10_DECLARE_REGISTRY(TensorPipeTransportRegistry, TransportRegistration);
+
+struct TORCH_API ChannelRegistration {
+  std::shared_ptr channel;
+  int64_t priority;
+};
+
+C10_DECLARE_REGISTRY(TensorPipeChannelRegistry, ChannelRegistration);
+
+constexpr auto kDefaultNumWorkerThreads = 16;
+
+struct TORCH_API TensorPipeRpcBackendOptions : public RpcBackendOptions {
+  TensorPipeRpcBackendOptions(
+      int numWorkerThreads,
+      std::optional> transports,
+      std::optional> channels,
+      float rpc_timeout,
+      std::string init_method,
+      std::unordered_map device_maps = {},
+      std::vector devices = {})
+      : RpcBackendOptions(rpc_timeout, std::move(init_method)),
+        numWorkerThreads(numWorkerThreads),
+        transports(std::move(transports)),
+        channels(std::move(channels)),
+        deviceMaps(std::move(device_maps)),
+        devices(std::move(devices)) {
+    TORCH_CHECK(
+        numWorkerThreads > 0,
+        "num_worker_threads must be positive, got ",
+        numWorkerThreads);
+
+    if (this->transports.has_value()) {
+      for (const std::string& transportName : this->transports.value()) {
+        TORCH_CHECK(
+            TensorPipeTransportRegistry()->Has(transportName),
+            "Unknown transport: ",
+            transportName);
+      }
+    }
+
+    if (this->channels.has_value()) {
+      for (const std::string& channelName : this->channels.value()) {
+        TORCH_CHECK(
+            TensorPipeChannelRegistry()->Has(channelName),
+            "Unknown channel: ",
+            channelName);
+      }
+    }
+  }
+
+  void setDeviceMap(const std::string& workerName, const DeviceMap& deviceMap) {
+    auto iter = deviceMaps.find(workerName);
+    if (iter == deviceMaps.end()) {
+      deviceMaps[workerName] = deviceMap;
+    } else {
+      for (auto& entry : deviceMap) {
+        // c10::Device has no default constructor, hence map[device] dosn't work
+        // In C++-17 we can use insert_or_assign.
+        auto entryIter = iter->second.find(entry.first);
+        if (entryIter == iter->second.end()) {
+          iter->second.emplace(entry.first, entry.second);
+        } else {
+          entryIter->second = entry.second;
+        }
+      }
+    }
+  }
+
+  int numWorkerThreads;
+  const std::optional> transports;
+  const std::optional> channels;
+  std::unordered_map deviceMaps;
+  std::vector devices;
+};
+
+// Struct to track the network source metrics
+struct TORCH_API NetworkSourceInfo {
+  worker_id_t srcRank;
+  std::vector srcMachineAddr;
+};
+
+// Struct to track aggregated network metrics
+struct TORCH_API AggregatedNetworkData {
+  uint64_t numCalls{0};
+  uint64_t totalSentBytes{0};
+  uint64_t totalRecvBytes{0};
+  uint64_t totalErrors{0};
+};
+
+// TensorPipeAgent leverages TensorPipe (https://github.com/pytorch/tensorpipe)
+// to transparently move tensors and payloads through the fastest available
+// transport or channel. It acts like a hybrid RPC transport, providing shared
+// memory (linux) and TCP (linux & mac) support. CUDA support is in progress.
+class TORCH_API TensorPipeAgent : public RpcAgent {
+ public:
+  TensorPipeAgent(
+      const c10::intrusive_ptr<::c10d::Store>& store,
+      std::string selfName,
+      worker_id_t selfId,
+      std::optional worldSize,
+      TensorPipeRpcBackendOptions opts,
+      std::unordered_map reverseDeviceMaps,
+      std::vector devices,
+      std::unique_ptr cb);
+
+  TensorPipeAgent(const TensorPipeAgent&) = delete;
+  TensorPipeAgent& operator=(const TensorPipeAgent&) = delete;
+
+  c10::intrusive_ptr send(
+      const WorkerInfo& to,
+      c10::intrusive_ptr message,
+      const float rpcTimeoutSeconds = kUnsetRpcTimeout,
+      const DeviceMap& deviceMap = {}) override;
+
+  // join() and sync() would be deprecated -
+  // https://github.com/pytorch/pytorch/issues/27647
+  void join(bool shutdown = false, float timeout = 0) override;
+  void sync() override{};
+  void startImpl() override;
+  void shutdownImpl() override;
+
+  ~TensorPipeAgent() override;
+
+  const WorkerInfo& getWorkerInfo(const std::string& workerName) const override;
+  const WorkerInfo& getWorkerInfo(worker_id_t workerId) const override;
+  std::vector getWorkerInfos() const override;
+  void updateGroupMembership(
+      const WorkerInfo& workerInfo,
+      const std::vector& devices,
+      const std::unordered_map& reverseDeviceMaps,
+      bool isJoin);
+
+  std::unordered_map getMetrics() override;
+
+  void addGilWaitTime(const std::chrono::microseconds gilWaitTime) override;
+
+  TensorPipeRpcBackendOptions getBackendOptions() const;
+
+  const c10::intrusive_ptr<::c10d::Store> getStore() const;
+
+  DeviceMap getDeviceMap(const WorkerInfo& dest) const override;
+
+  const std::vector& getDevices() const override;
+
+  using NetworkDataDict =
+      std::unordered_map;
+
+  // Returns metrics tracked by the NetworkDataDict
+  NetworkDataDict getNetworkData();
+  // Returns NetworkSourceInfo struct
+  NetworkSourceInfo getNetworkSourceInfo();
+
+  static const std::string& guessAddress();
+
+  // For testing purposes.
+  size_t timeoutMapSize();
+  size_t numPendingResponses();
+  size_t messageIdToTimeoutMapSize();
+
+  const bool isStaticGroup_;
+
+ protected:
+  // TensorPipe write function that could be used to write response
+  // messages by server, and write request messages by client. This
+  // is a protected method since it is overwritten by FaultyTensorPipeAgent
+  virtual void pipeWrite(
+      const std::shared_ptr&,
+      c10::intrusive_ptr message,
+      std::vector&& devices,
+      std::vector streams,
+      std::function) noexcept;
+
+ private:
+  // Removes the given messageId with the given expirationTime from the
+  // timeoutMap_.
+  void removeFromTimeoutMap(uint64_t messageId);
+
+  // Populates workerIdToInfo_ and workerNameToInfo_ using addressStore_
+  void prepareNames(bool isStaticGroup);
+
+  // Check the static group attribute with the value set in store
+  void checkAndSetStaticGroup(const c10::intrusive_ptr<::c10d::Store>& store);
+
+  const std::string& findWorkerURL(const WorkerInfo& worker) const;
+
+  // Only use for Dynamic RPC groups, method to have worker leave group
+  void leaveGroup();
+
+  // TensorPipe read function that could be used to read response messages
+  // by client, and read request messages by server.
+  void pipeRead(
+      const std::shared_ptr&,
+      std::function,
+          std::vector)>) noexcept;
+
+  // Callback of listener accept()
+  void onListenerAccepted(
+      const tensorpipe::Error& error,
+      std::shared_ptr& pipe);
+
+  // Respond to a call from a peer
+  void respond(std::shared_ptr& pipe);
+
+  void sendCompletedResponseMessage(
+      std::shared_ptr& pipe,
+      JitFuture& futureResponseMessage,
+      uint64_t messageId,
+      std::vector stream);
+
+  // Collects metrics from successful RPC calls
+  void trackNetworkData(
+      uint64_t requestSize,
+      uint64_t responseSize,
+      const std::string& destWorkerName);
+
+  // Collects metrics from failed RPC calls
+  void trackNetworkError(
+      uint64_t requestSize,
+      const std::string& destWorkerName);
+
+  inline std::vector getDevicesForRemote(
+      const std::string& remoteName,
+      const Message& message) const;
+
+  // When a request+response completes, we need to mark the future message as
+  // complete. However, if its timeout has already expired, it already has an
+  // error set. There is no atomic "test-and-set" way to mark a future complete
+  // only if it isn't yet. It does exist for errors (setErrorIfNeeded) but, even
+  // then, it ends up printing a log message, which may worry the user. To solve
+  // both issues we use a separate atomic flag to know the status of the future.
+  struct AtomicJitFuture {
+    explicit AtomicJitFuture(const std::vector& devices) {
+      jitFuture = c10::make_intrusive(
+          at::AnyClassType::get(), devices);
+    }
+
+    std::atomic_flag isComplete = ATOMIC_FLAG_INIT;
+    c10::intrusive_ptr jitFuture;
+  };
+
+  // Maintains state per client pipe to track pending response messages and
+  // error states. pendingResponseMessage_ should be protected by a mutex since
+  // it can be raced with user send() call.
+  // TODO: To achieve better performance we can have a pipe pool per
+  // client that can be configured using RpcBackendOptions.
+  struct ClientPipe {
+    explicit ClientPipe(std::shared_ptr pipe)
+        : pipe_(std::move(pipe)) {}
+    std::shared_ptr pipe_;
+    mutable std::mutex mutex_;
+    bool inError_{false};
+    // Map from Message Request ID's to corresponding futures.
+    std::unordered_map>
+        pendingResponseMessage_;
+  };
+
+  const c10::intrusive_ptr<::c10d::Store> store_;
+
+  const TensorPipeRpcBackendOptions opts_;
+  // For dynamic RPC, the reverse device maps are updated whenever a new rank
+  // joins or leaves the group
+  std::unordered_map reverseDeviceMaps_;
+  // Local devices used by this agent. If application didn't specify this
+  // field, it will be initialized using corresponding local devices in
+  // opts_.deviceMaps and reverseDeviceMaps_;
+  std::vector devices_;
+
+  ThreadPool threadPool_;
+  std::shared_ptr context_;
+  std::shared_ptr listener_;
+
+  mutable std::mutex connectedPipesMutex_;
+  std::unordered_map connectedPipes_;
+
+  // Maps keyed on name and id for easy WorkerInfo lookup.
+  std::unordered_map workerIdToInfo_;
+  std::unordered_map workerNameToInfo_;
+  std::unordered_map workerNameToURL_;
+
+  ::c10d::PrefixStore rankToNameStore_;
+  ::c10d::PrefixStore nameToAddressStore_;
+  // Store keys that will used to count joined processes and active calls during
+  // the shutdown process
+  ::c10d::PrefixStore shutdownStore_;
+  int worldSize_ = 0;
+  std::atomic nextMessageID_{0};
+
+  // Metadata used for tracking of whether certain RPCs have timed out or not.
+  struct TimeoutMessageMetadata {
+    TimeoutMessageMetadata(
+        uint64_t messageId_,
+        std::shared_ptr responseFuture_,
+        std::chrono::milliseconds timeout_)
+        : messageId(messageId_),
+          responseFuture(std::move(responseFuture_)),
+          timeout(timeout_) {}
+    uint64_t messageId;
+    std::shared_ptr responseFuture;
+    std::chrono::milliseconds timeout;
+  };
+
+  // Map to store the expiration times for each message.
+  std::map>
+      timeoutMap_;
+
+  // Map to store the messageId to expiry time.
+  std::unordered_map messageIdToTimeout_;
+
+  // Thread that will poll the timeoutMap_ for timed out messages and mark them
+  // with an error accordingly
+  std::thread timeoutThread_;
+
+  // Function run by the timeoutThread_ to check for timed out RPCs
+  void pollTimeoutRpcs();
+
+  // Mutex to guard the timeoutMap_
+  std::mutex timeoutMapMutex_;
+
+  // Condition Variable to signal population of the timeoutMap_
+  std::condition_variable timeoutThreadCV_;
+
+  // Returns the expiration time for an RPC by adding the current time to the
+  // passed in timeout.
+  inline steady_clock_time_point computeRpcMessageExpiryTime(
+      std::chrono::milliseconds timeout) const {
+    return std::chrono::time_point_cast(
+        std::chrono::steady_clock::now() + timeout);
+  }
+
+  // Handle error on an outgoing pipe
+  void handleClientError(
+      ClientPipe& clientPipe,
+      const tensorpipe::Error& error);
+
+  // This is a generic struct for capturing Time-Series Metrics. It keeps a
+  // running sum and count of data points (observations), and can return an
+  // average of the data points seen so far. This is currently only used for
+  // tracking the GIL Wait Time in RPC Agents, but can be used for other metrics
+  // as well.
+  struct TimeSeriesMetricsTracker {
+    // Running sum of the data points seen so far
+    uint64_t currentSum_;
+    // Running count of the data points seen so far
+    uint64_t currentCount_;
+
+    explicit TimeSeriesMetricsTracker(
+        uint64_t currentSum = 0,
+        uint64_t currentCount = 0);
+
+    // Adds a data point (which is basically one observation for the metric
+    // being tracked) to the running sum and count.
+    void addData(uint64_t dataPoint);
+    // Returns the average of all the data points seen so far.
+    float computeAverage() const;
+  };
+
+  // Map of Time-Series metrics tracked by the RPC Agent
+  std::unordered_map timeSeriesMetrics_;
+  // Mutex to guard timeSeriesMetrics_
+  std::mutex metricsMutex_;
+
+  // Custom lock guard used to check if the RPC group is dynamic and lock the
+  // mutex if so
+  struct GroupMembershipLockGuard {
+    GroupMembershipLockGuard(std::mutex& mutex, bool isStaticGroup)
+        : ref_(mutex), isStaticGroup_(isStaticGroup) {
+      if (isStaticGroup_) {
+        ref_.lock();
+      }
+    }
+
+    ~GroupMembershipLockGuard() {
+      if (isStaticGroup_) {
+        ref_.unlock();
+      }
+    }
+
+    GroupMembershipLockGuard(const GroupMembershipLockGuard&) = delete;
+
+   private:
+    std::mutex& ref_;
+    bool isStaticGroup_;
+  };
+  // Mutex to guard access to group membership data
+  // e.g. updates to (workerIdToInfo_, workerNameToInfo_, workerNameToURL_)
+  mutable std::mutex groupMembershipMutex_;
+
+  // Map to Track Network Data
+  NetworkDataDict networkData_;
+  // Mutex to guard networkData_
+  std::mutex networkDataMutex_;
+
+  // A mutex and a cv to guard access to the call counts and watch for changes.
+  std::mutex callCountMutex_;
+  std::condition_variable callCountCV_;
+  // Running total of un-processed, un-errored RPC calls sent
+  int32_t clientActiveCalls_{0};
+  // Running total of un-processed RPC requests received
+  int32_t serverActiveCalls_{0};
+  // Running total of RPC requests that will be completed asynchronously
+  int32_t serverActiveAsyncCalls_{0};
+
+  // Whether a global graceful shutdown has begun, in which case we'll silence
+  // error messages due to remote workers closing their pipes.
+  std::atomic shuttingDown_{false};
+
+  // Helpers to modify the counts while correctly dealing with the mutex and cv.
+  void increaseCallCount(int32_t& count);
+  void decreaseCallCount(int32_t& count);
+
+  // Helpers to set the state of the requests.
+  void markFutureAsComplete(
+      std::shared_ptr atomicFuture,
+      c10::intrusive_ptr message,
+      std::vector streams);
+  void markFutureWithError(
+      std::shared_ptr atomicFuture,
+      std::string errorMsg);
+};
+
+} // namespace torch::distributed::rpc
+
+#endif // USE_TENSORPIPE
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/tensorpipe_utils.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/tensorpipe_utils.h
new file mode 100644
index 0000000000000000000000000000000000000000..9de28ef0e31a5623aa7d9bae98d2749db9d4700e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/tensorpipe_utils.h
@@ -0,0 +1,119 @@
+#pragma once
+
+#ifdef USE_TENSORPIPE
+
+#include 
+
+namespace tensorpipe {
+class Message;
+class Allocation;
+class Descriptor;
+} // namespace tensorpipe
+
+namespace torch::distributed::rpc {
+
+TORCH_API const c10::Stream& getStreamForDevice(
+    const std::vector& streams,
+    const c10::Device& device);
+
+// Inspired by c10/core/impl/DeviceGuardImplInterface.h.
+
+class TensorpipeDeviceTypeConverter {
+ public:
+  // Ideally we'd want this to also return a tensorpipe::Message::Tensor object
+  // but we cannot forward-declare that class (because it's nested), and we
+  // cannot include the TensorPipe headers because it's a private dependency.
+  // Thus we bend over backwards and entrust this method with appending that
+  // object to the `tensors` field of the tensorpipe::Message object we pass.
+  virtual std::optional> prepareTensorForSending(
+      const c10::Storage& storage,
+      const std::vector& streams,
+      tensorpipe::Message& message) const = 0;
+
+  // Same as above: this method cannot return a tensorpipe::Allocation::Tensor,
+  // thus it appends it to the `tensors` field of the tensorpipe::Allocation.
+  virtual at::DataPtr allocateTensorForReceiving(
+      c10::DeviceIndex deviceIndex,
+      size_t length,
+      const std::vector& streams,
+      tensorpipe::Allocation& allocation) const = 0;
+
+  virtual ~TensorpipeDeviceTypeConverter() = default;
+};
+
+extern TORCH_API std::array<
+    std::atomic,
+    static_cast(DeviceType::COMPILE_TIME_MAX_DEVICE_TYPES)>
+    device_type_converter_registry;
+
+class TORCH_API TensorpipeDeviceTypeConverterRegistrar {
+ public:
+  TensorpipeDeviceTypeConverterRegistrar(
+      DeviceType,
+      const TensorpipeDeviceTypeConverter*);
+};
+
+#define C10_REGISTER_TENSORPIPE_DEVICE_TYPE_CONVERTER(                     \
+    DevType, TensorpipeDeviceTypeConverter)                                \
+  static ::torch::distributed::rpc::TensorpipeDeviceTypeConverterRegistrar \
+      C10_ANONYMOUS_VARIABLE(g_##DeviceType)(                              \
+          ::c10::DeviceType::DevType, new TensorpipeDeviceTypeConverter());
+
+inline const TensorpipeDeviceTypeConverter* getDeviceTypeConverter(
+    DeviceType type) {
+  return device_type_converter_registry[static_cast(type)].load();
+}
+
+// A struct that holds pointers that keep alive all the memory that will be
+// accessed by TensorPipe during a write operation.
+struct TensorpipeWriteBuffers {
+  // Allocate on heap so pointers stay valid as we move the holder.
+  std::unique_ptr type;
+  std::unique_ptr id;
+  std::vector payload;
+  std::vector pickle;
+  // This contains the original tensors and the clones of the sparse tensors.
+  std::vector tensors;
+  // This contains the copies of the data of the tensors that didn't own their
+  // memory, e.g., the ones created from torch::from_blob() with no deleter.
+  std::vector> copiedTensors;
+};
+
+// A struct that holds pointers that keep alive all the memory that will be
+// accessed by TensorPipe during a read operation.
+struct TensorpipeReadBuffers {
+  // Allocate on heap so pointers stay valid as we move the holder.
+  std::unique_ptr type;
+  std::unique_ptr id;
+  std::vector payload;
+  std::vector pickle;
+  std::vector tensors;
+};
+
+// Convert an RPC message into a TensorPipe message, plus a holder to all the
+// data that must be kept alive while the write is performed asynchronously.
+TORCH_API std::tuple
+tensorpipeSerialize(
+    const c10::intrusive_ptr& rpcMessage,
+    std::vector devices,
+    const std::vector& streams);
+
+// Allocate the buffers that will hold the incoming data. They will be managed
+// by the returned holder, which must be kept alive until the asynchronous read
+// has finished. Pointers to these buffers will be stored in the returned
+// tensorpipe::Allocation struct.
+TORCH_API std::pair
+tensorpipeAllocate(
+    const tensorpipe::Descriptor& tpDescriptor,
+    const std::vector& streams);
+
+// Convert a TensorPipe message back into an RPC message. This requires the data
+// to be available and can thus only be performed once the asynchronous read has
+// completed. The holder can be destroyed once this function returns.
+TORCH_API c10::intrusive_ptr tensorpipeDeserialize(
+    tensorpipe::Descriptor&& tpDescriptor,
+    TensorpipeReadBuffers&& holder);
+
+} // namespace torch::distributed::rpc
+
+#endif // USE_TENSORPIPE
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/torchscript_functions.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/torchscript_functions.h
new file mode 100644
index 0000000000000000000000000000000000000000..5338c23108096708481b1a5a0659862e2db20881
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/torchscript_functions.h
@@ -0,0 +1,37 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch::distributed::rpc {
+
+// This function sends an rpc call to run torchscript function, currently the
+// torchscript function could only be a user defined python function with
+// "@torch.jit.script" annotation. The torchscript function could not be
+// a class constructor, class method, instance method or a script module.
+//   dst: destination worker name
+//   qualifiedName: torchscript function qualified name string like
+//                  "moduleName::torchscriptFunctionName", e.g,
+//                  "dist_autograd_test::my_py_add"
+//   stack: a bag of IValue args passed to torchscriptFunctionName
+// It returns c10::intrusive_ptr
+c10::intrusive_ptr TORCH_API rpcTorchscript(
+    const std::string& dstWorkerName,
+    const c10::QualifiedName& qualifiedName,
+    const c10::FunctionSchema& functionSchema,
+    std::vector& stack,
+    const float rpcTimeoutSeconds = torch::distributed::rpc::kUnsetRpcTimeout,
+    const bool isAsyncExecution = false);
+
+c10::intrusive_ptr TORCH_API remoteTorchscript(
+    const std::string& dstWorkerName,
+    const c10::QualifiedName& qualifiedName,
+    const c10::FunctionSchema& functionSchema,
+    std::vector& stack,
+    const float rpcTimeoutSeconds = torch::distributed::rpc::kUnsetRpcTimeout,
+    const bool isAsyncExecution = false);
+
+} // namespace torch::distributed::rpc
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/types.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/types.h
new file mode 100644
index 0000000000000000000000000000000000000000..4babac93713f263e3aee4f96c0e16cb39584c072
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/types.h
@@ -0,0 +1,62 @@
+#pragma once
+
+#include 
+#include 
+
+namespace torch::distributed::rpc {
+
+using worker_id_t = int16_t;
+using local_id_t = int64_t;
+
+bool getAllowJitRRefPickle();
+TORCH_API void enableJitRRefPickle();
+TORCH_API void disableJitRRefPickle();
+
+struct TORCH_API JitRRefPickleGuard {
+  JitRRefPickleGuard();
+  ~JitRRefPickleGuard();
+};
+
+struct TORCH_API GloballyUniqueId final {
+  GloballyUniqueId(worker_id_t createdOn, local_id_t localId);
+  GloballyUniqueId(const GloballyUniqueId& other) = default;
+  GloballyUniqueId& operator=(const GloballyUniqueId& other) = delete;
+
+  bool operator==(const GloballyUniqueId& other) const;
+  bool operator!=(const GloballyUniqueId& other) const;
+
+  at::IValue toIValue() const;
+  static GloballyUniqueId fromIValue(const at::IValue&);
+
+  struct Hash {
+    size_t operator()(const GloballyUniqueId& key) const {
+      return (uint64_t(key.createdOn_) << kLocalIdBits) | key.localId_;
+    }
+  };
+
+  static constexpr int kLocalIdBits = 48;
+
+  const worker_id_t createdOn_;
+  const local_id_t localId_;
+};
+
+TORCH_API std::ostream& operator<<(
+    std::ostream& os,
+    const GloballyUniqueId& globalId);
+
+using RRefId = GloballyUniqueId;
+using ForkId = GloballyUniqueId;
+using ProfilingId = GloballyUniqueId;
+
+struct TORCH_API SerializedPyObj final {
+  SerializedPyObj(std::string&& payload, std::vector&& tensors)
+      : payload_(std::move(payload)), tensors_(std::move(tensors)) {}
+
+  std::vector toIValues() &&;
+  static SerializedPyObj fromIValues(std::vector value);
+
+  std::string payload_;
+  std::vector tensors_;
+};
+
+} // namespace torch::distributed::rpc
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/unpickled_python_call.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/unpickled_python_call.h
new file mode 100644
index 0000000000000000000000000000000000000000..22d13d2e833cee8135b7634045f68377b10a2e86
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/unpickled_python_call.h
@@ -0,0 +1,38 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+namespace torch::distributed::rpc {
+
+// This class converts the content in a PythonCall into py::object. This is a
+// helper class to make sure that all arguments deserialization is done before
+// entering RequestCallbackImpl::processRpc(...), so that the deserialization
+// related logic can be carried out in one spot instead of scattered in multiple
+// places for different message types.
+// NB: The reason for not consolidating class into PythonCall is because
+// PythonCall is a libtorch type which should not depend on Python types.
+class TORCH_API UnpickledPythonCall : public RpcCommandBase {
+ public:
+  UnpickledPythonCall(
+      const SerializedPyObj& serializedPyObj,
+      bool isAsyncExecution);
+  ~UnpickledPythonCall() override;
+
+  // toMessage() method is not implemented, as objects of this class should
+  // never be directly converted into a Message object.
+  c10::intrusive_ptr toMessageImpl() && override;
+  const py::object& pythonUdf() const;
+
+  inline bool isAsyncExecution() const {
+    return isAsyncExecution_;
+  }
+
+ private:
+  py::object pythonUdf_;
+  // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
+  const bool isAsyncExecution_;
+};
+
+} // namespace torch::distributed::rpc
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/unpickled_python_remote_call.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/unpickled_python_remote_call.h
new file mode 100644
index 0000000000000000000000000000000000000000..99386ffaaf96e069b18a39b040abe06d19deea5c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/unpickled_python_remote_call.h
@@ -0,0 +1,33 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch::distributed::rpc {
+
+// This class converts the content in a PythonRemoteCall into py::object. This
+// is a helper class to make sure that all arguments deserialization is done
+// before entering RequestCallbackImpl::processRpc(...), so that the
+// deserialization related logic can be carried out in one spot instead of
+// scattered in multiple places for different message types.
+// NB: The reason for not consolidating class into PythonRemoteCall is because
+// PythonRemoteCall is a libtorch type which should not depend on Python types.
+class TORCH_API UnpickledPythonRemoteCall final : public UnpickledPythonCall {
+ public:
+  explicit UnpickledPythonRemoteCall(
+      const SerializedPyObj& serializedPyObj,
+      const at::IValue& retRRefId,
+      const at::IValue& retForkId,
+      const bool isAsyncExecution);
+
+  const RRefId& rrefId() const;
+  const ForkId& forkId() const;
+
+ private:
+  RRefId rrefId_;
+  ForkId forkId_;
+};
+
+} // namespace torch::distributed::rpc
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/utils.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/utils.h
new file mode 100644
index 0000000000000000000000000000000000000000..3627d0db14f9c104600d9c1f6af51dd2833a2971
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/distributed/rpc/utils.h
@@ -0,0 +1,90 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace distributed {
+namespace rpc {
+
+// Parse error message and return RPCErrorType based on the message.
+TORCH_API RPCErrorType getRPCErrorType(const JitFuture& jitFuture);
+// Create an error string given the error description and error type
+TORCH_API std::string makeRPCError(
+    const std::string& rpcErrorStr,
+    RPCErrorType errorType);
+
+// Given an RPC message received as a request over the wire, deserialize it into
+// the appropriate 'RpcCommandBase' type.
+TORCH_API std::unique_ptr deserializeRequest(
+    const Message& request);
+
+// Given an RPC message received as a response over the wire, deserialize it
+// into the appropriate 'RpcCommandBase' type, if the response is
+// FORWARD_AUTOGRAD_RESP type, unwrap it, attach recvBackward() functions
+// to received tensors and set the wrappedMsgType to its wrapped message type.
+TORCH_API std::unique_ptr deserializeResponse(
+    const Message& response,
+    MessageType& wrappedMsgType);
+
+// Given an RPC message received as a response over the wire, deserialize it
+// into the valid IValue if the message is for a script rpc result,
+// otherwise deserialize it into dummy none ivalue that will never be used.
+// In this deserialization, we also attach recv rpc backward functions if
+// needed.
+IValue deserializeResptoIValueInternal(
+    RpcCommandBase& rpc,
+    MessageType messageType);
+TORCH_API IValue deserializeRespToIValue(const Message& message);
+
+// Note: format is subject to change and intended for RPCs.
+// For saving persistently to disk, use torch::save().
+TORCH_API std::string wireSerialize(
+    const std::vector& payload,
+    const std::vector& tensors);
+
+TORCH_API std::pair, std::vector> wireDeserialize(
+    const void* data,
+    size_t data_size);
+
+// We use vector as the type of blobs because it's what rpc::Message uses
+// for its payload, even though it has the disadvantage that it cannot be
+// allocated with uninitialized memory: it is always zeroed out.
+
+// Some Tensors are effectively views of larger Tensors, where only a small
+// subset of the Storage data is referenced. This normally is good and avoids
+// copies when kept locally, but if we naively push the whole Storage over the
+// wire, we'll end up with excess network traffic. This change clones tensors if
+// we'd save at least half the data, and over a minimum hurdle.
+TORCH_API c10::List cloneSparseTensors(
+    const std::vector& tensors);
+
+// Combines an original payload and wrapped payload into the original payload.
+// Used to generate the overall payload for the wrapped RPC.
+TORCH_API void writeWrappedPayload(
+    std::vector& originalPayload,
+    std::vector& additionalPayload);
+
+// Reads the additional, wrapped payload from a wrapped RPC off of the input
+// payload. After this, payload will contain the payload of the original,
+// un-wrapped RPC.
+TORCH_API std::vector readWrappedPayload(
+    std::vector& payload,
+    const rpc::Message& message);
+
+// Takes a list of events from autograd profiler and populates them into
+// profiledEvents to be carried over RPC.
+TORCH_API void populateRemoteProfiledEvents(
+    std::vector& profiledEvents,
+    const torch::autograd::profiler::ProfilerConfig& profilerConfig,
+    const std::vector>&
+        eventLists);
+
+} // namespace rpc
+} // namespace distributed
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner.h
new file mode 100644
index 0000000000000000000000000000000000000000..99669aec14ac095b98ca6f691b1fc284ece3c0fc
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner.h
@@ -0,0 +1,108 @@
+#if !defined(C10_MOBILE) && !defined(ANDROID)
+#pragma once
+
+#include 
+#include 
+#include 
+
+// Forward declare DynamicLibrary
+namespace at {
+struct DynamicLibrary;
+}
+
+namespace torch::inductor {
+using TensorConstantMap = std::unordered_map;
+
+class TORCH_API AOTIModelContainerRunner {
+ public:
+  AOTIModelContainerRunner() = delete;
+  AOTIModelContainerRunner(const AOTIModelContainerRunner& other) = delete;
+  AOTIModelContainerRunner(AOTIModelContainerRunner&& other) = delete;
+  AOTIModelContainerRunner& operator=(const AOTIModelContainerRunner& other) =
+      delete;
+  AOTIModelContainerRunner& operator=(AOTIModelContainerRunner&& other) =
+      delete;
+  ~AOTIModelContainerRunner();
+
+  std::vector run(
+      std::vector& inputs,
+      AOTInductorStreamHandle cuda_stream_handle = nullptr);
+
+  std::unordered_map getConstantNamesToOriginalFQNs()
+      const;
+  std::unordered_map getConstantNamesToDtypes() const;
+  void update_inactive_constant_buffer(const TensorConstantMap& const_map);
+  void update_constant_buffer(
+      const TensorConstantMap& const_map,
+      bool use_inactive,
+      bool validate_full_updates);
+  void run_const_fold(
+      bool use_inactive,
+      AOTInductorStreamHandle cuda_stream_handle = nullptr);
+  void swap_constant_buffer();
+
+  std::vector get_call_spec();
+
+ protected:
+  AOTIModelContainerRunner(
+      const std::string& model_so_path,
+      size_t num_models,
+      const std::string& device_str,
+      const std::string& cubin_dir);
+
+  std::unique_ptr model_so_;
+  decltype(&AOTInductorModelContainerCreateWithDevice) create_func_{nullptr};
+  decltype(&AOTInductorModelContainerDelete) delete_func_{nullptr};
+  decltype(&AOTInductorModelContainerGetNumOutputs) get_num_outputs_func_{
+      nullptr};
+  decltype(&AOTInductorModelContainerRun) run_func_{nullptr};
+  decltype(&AOTInductorModelContainerGetNumConstants) get_num_constants_func_{
+      nullptr};
+  decltype(&AOTInductorModelContainerGetConstantName) get_constant_name_func_{
+      nullptr};
+  decltype(&AOTInductorModelContainerGetConstantOriginalFQN)
+      get_constant_original_fqn_func_{nullptr};
+  decltype(&AOTInductorModelContainerGetConstantDtype) get_constant_dtype_func_{
+      nullptr};
+  decltype(&AOTInductorModelContainerUpdateConstantBuffer)
+      update_constant_buffer_func_{nullptr};
+  decltype(&AOTInductorModelContainerUpdateInactiveConstantBuffer)
+      update_inactive_constant_buffer_func_{nullptr};
+  decltype(&AOTInductorModelContainerRunConstantFolding) run_const_fold_func_{
+      nullptr};
+  decltype(&AOTInductorModelContainerSwapConstantBuffer)
+      swap_constant_buffer_func_{nullptr};
+  decltype(&AOTInductorModelContainerGetCallSpec) get_call_spec_func_{nullptr};
+
+  AOTInductorModelContainerHandle container_handle_ = nullptr;
+
+  AOTIProxyExecutorHandle proxy_executor_handle_;
+
+ private:
+  std::unique_ptr proxy_executor_;
+};
+
+using CreateAOTIModelRunnerFunc = std::shared_ptr (*)(
+    const std::string& model_so_path,
+    size_t num_models,
+    const std::string& device_str,
+    const std::string& bin_dir);
+
+// Return a global map "device name" -> "aoti model runner create function" for
+// all registered in AOTI external backends
+TORCH_API std::unordered_map&
+getAOTIModelRunnerRegistry();
+
+// To register a new external backend in AOTI one needs to create an instance of
+// this struct. It is not thread-safe. Becase it is expected to be called during
+// the initialization of the program.
+struct TORCH_API RegisterAOTIModelRunner {
+  RegisterAOTIModelRunner(
+      const std::string& name,
+      CreateAOTIModelRunnerFunc create_aoti_model_runner_fn) {
+    getAOTIModelRunnerRegistry()[name] = create_aoti_model_runner_fn;
+  }
+};
+
+} // namespace torch::inductor
+#endif
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_cpu.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_cpu.h
new file mode 100644
index 0000000000000000000000000000000000000000..eed595930a8bd6fa9cb4866fb9878e17f69ef2d0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_cpu.h
@@ -0,0 +1,19 @@
+#if !defined(C10_MOBILE) && !defined(ANDROID)
+#pragma once
+
+#include 
+
+namespace torch::inductor {
+class TORCH_API AOTIModelContainerRunnerCpu : public AOTIModelContainerRunner {
+ public:
+  AOTIModelContainerRunnerCpu(
+      const std::string& model_so_path,
+      size_t num_models = 1);
+
+  ~AOTIModelContainerRunnerCpu();
+
+  std::vector run(std::vector& inputs);
+};
+
+} // namespace torch::inductor
+#endif
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_cuda.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_cuda.h
new file mode 100644
index 0000000000000000000000000000000000000000..5db82bf413668a862c775cf0c1ae1416037837fe
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_cuda.h
@@ -0,0 +1,30 @@
+#if !defined(C10_MOBILE) && !defined(ANDROID)
+#pragma once
+
+#include 
+#include 
+
+namespace torch::inductor {
+
+// NOTICE: Following APIs are subject to change due to active development
+// We provide NO BC guarantee for these APIs
+class TORCH_API AOTIModelContainerRunnerCuda : public AOTIModelContainerRunner {
+ public:
+  // @param device_str: cuda device string, e.g. "cuda", "cuda:0"
+  AOTIModelContainerRunnerCuda(
+      const std::string& model_so_path,
+      size_t num_models = 1,
+      const std::string& device_str = "cuda",
+      const std::string& cubin_dir = "");
+
+  ~AOTIModelContainerRunnerCuda();
+
+  std::vector run(std::vector& inputs);
+
+  std::vector run_with_cuda_stream(
+      std::vector& inputs,
+      at::cuda::CUDAStream cuda_stream);
+};
+
+} // namespace torch::inductor
+#endif
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runner/pybind.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runner/pybind.h
new file mode 100644
index 0000000000000000000000000000000000000000..3797c7e1e6a2798dd238cae06ff3db6eb990495b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runner/pybind.h
@@ -0,0 +1,7 @@
+#include 
+
+namespace torch::inductor {
+
+void initAOTIRunnerBindings(PyObject* module);
+
+} // namespace torch::inductor
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/arrayref_tensor.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/arrayref_tensor.h
new file mode 100644
index 0000000000000000000000000000000000000000..afb41ee0bdd09c8bfd4dec37b578cf09d966d485
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/arrayref_tensor.h
@@ -0,0 +1,381 @@
+#pragma once
+
+#include 
+
+#include 
+#include 
+#include 
+
+namespace torch::aot_inductor {
+
+// Can't use c10::ArrayRef because it's not truly header-only and
+// pulls in other c10 headers. This is (sadly) copy-pasted and
+// adapted.
+template 
+class MiniArrayRef final {
+ public:
+  using iterator = T*;
+  using const_iterator = const T*;
+  using size_type = size_t;
+  using value_type = T;
+
+  using reverse_iterator = std::reverse_iterator;
+
+ private:
+  /// The start of the array, in an external buffer.
+  T* Data;
+
+  /// The number of elements.
+  size_type Length;
+
+ public:
+  /// @name Constructors
+  /// @{
+
+  /// Construct an empty MiniArrayRef.
+  /* implicit */ constexpr MiniArrayRef() : Data(nullptr), Length(0) {}
+
+  /// Construct an MiniArrayRef from a single element.
+  // TODO Make this explicit
+  constexpr MiniArrayRef(const T& OneElt) : Data(&OneElt), Length(1) {}
+
+  /// Construct an MiniArrayRef from a pointer and length.
+  constexpr MiniArrayRef(T* data, size_t length) : Data(data), Length(length) {}
+
+  /// Construct an MiniArrayRef from a range.
+  constexpr MiniArrayRef(T* begin, T* end) : Data(begin), Length(end - begin) {}
+
+  template <
+      typename Container,
+      typename = std::enable_if_t().data())>,
+          T*>>>
+  /* implicit */ MiniArrayRef(Container& container)
+      : Data(container.data()), Length(container.size()) {}
+
+  /// Construct an MiniArrayRef from a std::vector.
+  // The enable_if stuff here makes sure that this isn't used for
+  // std::vector, because MiniArrayRef can't work on a std::vector
+  // bitfield.
+  template 
+  /* implicit */ MiniArrayRef(const std::vector& Vec)
+      : Data(Vec.data()), Length(Vec.size()) {
+    static_assert(
+        !std::is_same::value,
+        "MiniArrayRef cannot be constructed from a std::vector bitfield.");
+  }
+
+  /// Construct an MiniArrayRef from a std::array
+  template 
+  /* implicit */ constexpr MiniArrayRef(std::array& Arr)
+      : Data(Arr.data()), Length(N) {}
+
+  /// Construct an MiniArrayRef from a C array.
+  template 
+  // NOLINTNEXTLINE(*c-array*)
+  /* implicit */ constexpr MiniArrayRef(T (&Arr)[N]) : Data(Arr), Length(N) {}
+
+  // /// Construct an MiniArrayRef from an empty C array.
+  /* implicit */ constexpr MiniArrayRef(const volatile void* Arr)
+      : Data(nullptr), Length(0) {}
+
+  /// Construct an MiniArrayRef from a std::initializer_list.
+  /* implicit */ constexpr MiniArrayRef(const std::initializer_list& Vec)
+      : Data(
+            std::begin(Vec) == std::end(Vec) ? static_cast(nullptr)
+                                             : std::begin(Vec)),
+        Length(Vec.size()) {}
+
+  /// @}
+  /// @name Simple Operations
+  /// @{
+
+  constexpr iterator begin() const {
+    return Data;
+  }
+  constexpr iterator end() const {
+    return Data + Length;
+  }
+
+  // These are actually the same as iterator, since MiniArrayRef only
+  // gives you const iterators.
+  constexpr const_iterator cbegin() const {
+    return Data;
+  }
+  constexpr const_iterator cend() const {
+    return Data + Length;
+  }
+
+  constexpr reverse_iterator rbegin() const {
+    return reverse_iterator(end());
+  }
+  constexpr reverse_iterator rend() const {
+    return reverse_iterator(begin());
+  }
+
+  /// empty - Check if the array is empty.
+  constexpr bool empty() const {
+    return Length == 0;
+  }
+
+  constexpr T* data() const {
+    return Data;
+  }
+
+  /// size - Get the array size.
+  constexpr size_t size() const {
+    return Length;
+  }
+
+  /// equals - Check for element-wise equality.
+  constexpr bool equals(MiniArrayRef RHS) const {
+    return Length == RHS.Length && std::equal(begin(), end(), RHS.begin());
+  }
+
+  /// @}
+  /// @name Operator Overloads
+  /// @{
+  constexpr const T& operator[](size_t Index) const {
+    return Data[Index];
+  }
+
+  /// Disallow accidental assignment from a temporary.
+  ///
+  /// The declaration here is extra complicated so that "arrayRef = {}"
+  /// continues to select the move assignment operator.
+  template 
+  std::enable_if_t, MiniArrayRef>& operator=(
+      U&& Temporary) = delete;
+
+  /// Disallow accidental assignment from a temporary.
+  ///
+  /// The declaration here is extra complicated so that "arrayRef = {}"
+  /// continues to select the move assignment operator.
+  template 
+  std::enable_if_t, MiniArrayRef>& operator=(
+      std::initializer_list) = delete;
+};
+
+using MiniIntArrayRef = MiniArrayRef;
+
+static_assert(
+    sizeof(MiniIntArrayRef) == sizeof(void*) + sizeof(size_t),
+    "changing the size of MiniArrayRef breaks ABI compatibility!");
+
+inline bool is_contiguous_strides_for_shape(
+    int64_t ndim,
+    const int64_t* strides_ptr,
+    const int64_t* sizes_ptr) {
+  int64_t z = 1;
+  for (int64_t d = ndim - 1; d >= 0; d--) {
+    const auto& size_d = sizes_ptr[d];
+    if (size_d != 1) {
+      if (strides_ptr[d] == z) {
+        z *= size_d;
+      } else {
+        return false;
+      }
+    }
+  }
+  return true;
+}
+
+// Shim for AOTI generated code to pretend a raw array works like an
+// AtenTensorHandle.
+template 
+class ArrayRefTensor {
+ public:
+  ArrayRefTensor() = default;
+
+  explicit ArrayRefTensor(
+      MiniArrayRef arr,
+      MiniArrayRef sizes,
+      MiniArrayRef strides,
+      int32_t device_type,
+      int32_t device_idx)
+      : arrayRef_(arr),
+        sizes_(sizes),
+        strides_(strides),
+        device_type_(device_type),
+        device_idx_(device_idx) {
+    assert(sizes.size() == strides.size());
+    assert(is_contiguous_strides_for_shape(
+        sizes.size(), strides.data(), sizes.data()));
+  }
+
+  AtenTensorHandle expensiveCopyToTensor() const {
+    AtenTensorHandle result = nullptr;
+    AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_empty_strided(
+        sizes_.size(),
+        sizes_.data(),
+        strides_.data(),
+        aoti_torch_dtype>(),
+        device_type_,
+        device_idx_,
+        &result));
+    void* dataPtr = nullptr;
+    AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_data_ptr(result, &dataPtr));
+    std::memcpy(dataPtr, data(), numel() * sizeof(T));
+    return result;
+  }
+
+  // We need to look the same as RAIIAtenTensorHandle, which returns
+  // an owning AtenTensorHandle from release(). So, we allocate one!
+  AtenTensorHandle release() {
+    return expensiveCopyToTensor();
+  }
+
+  // We don't need to free any memory.
+  void reset() {}
+
+  auto sizes() const {
+    return sizes_;
+  }
+
+  auto strides() const {
+    return strides_;
+  }
+
+  auto device_type() const {
+    return device_type_;
+  }
+
+  auto device_idx() const {
+    return device_idx_;
+  }
+
+  T* data() const {
+    return arrayRef_.data();
+  }
+
+  auto numel() const {
+    return arrayRef_.size();
+  }
+
+  void set_arrayref(MiniArrayRef new_arrayref) {
+    arrayRef_ = new_arrayref;
+  }
+
+ private:
+  MiniArrayRef arrayRef_;
+  // We expect generated code to have statically available sizes &
+  // strides for us.
+  MiniArrayRef sizes_;
+  MiniArrayRef strides_;
+  int32_t device_type_ = 0;
+  int32_t device_idx_ = 0;
+  // We continue to zero-initialize this field in case we repurpose
+  // the space later; having predictable contents can only help.
+  int32_t unusedDoNotRemoveForABICompatibility_ = 0;
+};
+
+static_assert(
+    sizeof(ArrayRefTensor) ==
+        3 * sizeof(MiniIntArrayRef) + 3 * sizeof(int32_t) +
+            (alignof(ArrayRefTensor) > 4 ? sizeof(int32_t) : 0),
+    "changing the size of ArrayRefTensor breaks ABI compatibility!");
+
+inline AtenTensorHandle reinterpret_tensor_wrapper(
+    AtenTensorHandle self,
+    int64_t ndim,
+    const int64_t* sizes_ptr,
+    const int64_t* strides_ptr,
+    int64_t storage_offset) {
+  AtenTensorHandle result = nullptr;
+  AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch__reinterpret_tensor(
+      self, ndim, sizes_ptr, strides_ptr, storage_offset, &result));
+  return result;
+}
+
+template 
+inline ArrayRefTensor reinterpret_tensor_wrapper(
+    const ArrayRefTensor& self,
+    int64_t ndim,
+    const int64_t* sizes_ptr,
+    const int64_t* strides_ptr,
+    int64_t storage_offset) {
+  // REVIEW: we should add a way to build the DSO in debug mode during
+  // tests so we can have checks like this!
+  assert(is_contiguous_strides_for_shape(ndim, strides_ptr, sizes_ptr));
+  return ArrayRefTensor(
+      MiniArrayRef(
+          self.data() + storage_offset, self.numel() - storage_offset),
+      MiniArrayRef(sizes_ptr, ndim),
+      MiniArrayRef(strides_ptr, ndim),
+      self.device_type(),
+      self.device_idx());
+}
+
+inline void* get_data_ptr_wrapper(AtenTensorHandle tensor) {
+  void* result = nullptr;
+  AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_data_ptr(tensor, &result));
+  return result;
+}
+
+template 
+inline T* get_data_ptr_wrapper(ArrayRefTensor& tensor) {
+  return tensor.data();
+}
+
+template 
+inline T* get_data_ptr_wrapper(const MiniArrayRef& arr) {
+  return arr.data();
+}
+
+inline AtenTensorHandle unwrap_raii_handle_if_needed(
+    const RAIIAtenTensorHandle& handle) {
+  return handle.get();
+}
+
+template 
+inline const ArrayRefTensor& unwrap_raii_handle_if_needed(
+    const ArrayRefTensor& tensor) {
+  return tensor;
+}
+
+template 
+inline ArrayRefTensor& unwrap_raii_handle_if_needed(
+    ArrayRefTensor& tensor) {
+  return tensor;
+}
+
+inline RAIIAtenTensorHandle wrap_with_raii_handle_if_needed(
+    AtenTensorHandle handle) {
+  return RAIIAtenTensorHandle(handle);
+}
+
+template 
+inline const ArrayRefTensor& wrap_with_raii_handle_if_needed(
+    const ArrayRefTensor& tensor) {
+  return tensor;
+}
+
+template 
+inline ArrayRefTensor& wrap_with_raii_handle_if_needed(
+    ArrayRefTensor& tensor) {
+  return tensor;
+}
+
+template 
+inline RAIIAtenTensorHandle expensive_copy_to_tensor_if_needed(
+    const ArrayRefTensor& tensor) {
+  return tensor.expensiveCopyToTensor();
+}
+
+inline AtenTensorHandle expensive_copy_to_tensor_if_needed(
+    AtenTensorHandle handle) {
+  return handle;
+}
+
+template 
+const T& convert_arrayref_tensor_to_tensor(const T& t) {
+  return t;
+}
+
+template 
+RAIIAtenTensorHandle convert_arrayref_tensor_to_tensor(
+    const ArrayRefTensor& art) {
+  return art.expensiveCopyToTensor();
+}
+
+} // namespace torch::aot_inductor
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/device_utils.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/device_utils.h
new file mode 100644
index 0000000000000000000000000000000000000000..76731999968dd7da2726fa3af2cebd293a93d0f6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/device_utils.h
@@ -0,0 +1,49 @@
+#pragma once
+
+// WARNING: Be careful when adding new includes here. This header will be used
+// in model.so, and should not refer to any aten/c10 headers except the stable
+// C ABI defined in torch/csrc/inductor/aoti_torch/c/shim.h. The same rule
+// applies to other files under torch/csrc/inductor/aoti_runtime/.
+
+#ifdef USE_CUDA
+
+// FIXME: Currently, CPU and CUDA backend are mutually exclusive.
+// This is a temporary workaround. We need a better way to support
+// multi devices.
+
+#include 
+#include 
+
+#define AOTI_RUNTIME_DEVICE_CHECK(EXPR)                    \
+  do {                                                     \
+    const cudaError_t code = EXPR;                         \
+    const char* msg = cudaGetErrorString(code);            \
+    if (code != cudaSuccess) {                             \
+      throw std::runtime_error(                            \
+          std::string("CUDA error: ") + std::string(msg)); \
+    }                                                      \
+  } while (0)
+
+namespace torch::aot_inductor {
+
+using DeviceStreamType = cudaStream_t;
+
+} // namespace torch::aot_inductor
+
+#else // !USE_CUDA
+
+#define AOTI_RUNTIME_DEVICE_CHECK(EXPR)            \
+  bool ok = EXPR;                                  \
+  if (!ok) {                                       \
+    throw std::runtime_error("CPU runtime error"); \
+  }
+
+namespace torch {
+namespace aot_inductor {
+
+using DeviceStreamType = void*;
+
+} // namespace aot_inductor
+} // namespace torch
+
+#endif // USE_CUDA
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/interface.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/interface.h
new file mode 100644
index 0000000000000000000000000000000000000000..cf30c3742d523a18fce73bbdde40be55a7608190
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/interface.h
@@ -0,0 +1,182 @@
+#pragma once
+
+// WARNING: Be careful when adding new includes here. This header will be used
+// in model.so, and should not refer to any aten/c10 headers except the stable
+// C ABI defined in torch/csrc/inductor/aoti_torch/c/shim.h. The same rule
+// applies to other files under torch/csrc/inductor/aoti_runtime/.
+#include 
+
+extern "C" {
+struct AOTInductorModelOpaque;
+using AOTInductorModelHandle = AOTInductorModelOpaque*;
+
+struct AOTInductorModelContainerOpaque;
+using AOTInductorModelContainerHandle = AOTInductorModelContainerOpaque*;
+
+struct AOTInductorStreamOpaque;
+using AOTInductorStreamHandle = AOTInductorStreamOpaque*;
+
+struct AOTInductorConstantMap;
+using AOTInductorConstantMapHandle = AOTInductorConstantMap*;
+
+// TODO: Deprecate this API. This was kept for BC compatibility.
+// Please use AOTInductorModelContainerCreateWithDevice instead.
+AOTIRuntimeError AOTInductorModelContainerCreate(
+    AOTInductorModelContainerHandle* container_handle,
+    size_t num_models,
+    bool is_cpu,
+    const char* cubin_dir);
+
+// Creates an AOTInductor model container. The parameter num_models
+// specifies the number of model instances that may be run concurrently for
+// the same input model.
+// `device_str` MUST NOT be nullptr. It must be a valid device string, e.g.
+// "cpu", "cuda", "cuda:0", etc. If the device index is not specified for CUDA
+// device, runtime will use the device index returned by
+// "cudaGetDevice(&device_idx)"
+AOTIRuntimeError AOTInductorModelContainerCreateWithDevice(
+    AOTInductorModelContainerHandle* container_handle,
+    size_t num_models,
+    const char* device_str,
+    const char* cubin_dir);
+
+// Deletes the AOTInductor model container.
+AOTIRuntimeError AOTInductorModelContainerDelete(
+    AOTInductorModelContainerHandle container_handle);
+
+// Runs the inference.
+AOTIRuntimeError AOTInductorModelContainerRun(
+    AOTInductorModelContainerHandle container_handle,
+    AtenTensorHandle* input_handles, // array of input AtenTensorHandle; handles
+                                     // are stolen; the array itself is borrowed
+    size_t num_inputs,
+    AtenTensorHandle*
+        output_handles, // array for writing output AtenTensorHandle; handles
+                        // will be stolen by the caller; the array itself is
+                        // borrowed
+    size_t num_outputs,
+    AOTInductorStreamHandle stream_handle,
+    AOTIProxyExecutorHandle proxy_executor_handle);
+
+// Retrieves the number of constants for the model.
+AOTIRuntimeError AOTInductorModelContainerGetNumConstants(
+    AOTInductorModelContainerHandle container_handle,
+    size_t* num_constants);
+
+// Retrieves a constant's name.
+// idx is the index of the internal's constants.
+// Need idx < num_constants from AOTInductorModelContainerGetNumConstants
+AOTIRuntimeError AOTInductorModelContainerGetConstantName(
+    AOTInductorModelContainerHandle container_handle,
+    size_t idx,
+    const char** name);
+
+// Retrieves a constant's original FQN.
+// idx is the index of the internal's constants.
+// Need idx < num_constants from AOTInductorModelContainerGetNumConstants
+AOTIRuntimeError AOTInductorModelContainerGetConstantOriginalFQN(
+    AOTInductorModelContainerHandle container_handle,
+    size_t idx,
+    const char** original_fqn);
+
+// Retrieves whether a constant is from folded.
+// idx is the index of the internal's constants.
+// Need idx < num_constants from AOTInductorModelContainerGetNumConstants
+AOTIRuntimeError AOTInductorModelContainerGetConstantFromFolded(
+    AOTInductorModelContainerHandle container_handle,
+    size_t idx,
+    bool* from_folded);
+
+// Retrieves a constant's dtype.
+// idx is the index of the internal's constants.
+// Need idx < num_constants from AOTInductorModelContainerGetNumConstants
+AOTIRuntimeError AOTInductorModelContainerGetConstantDtype(
+    AOTInductorModelContainerHandle container_handle,
+    size_t idx,
+    int32_t* dtype);
+
+// Setup the constant buffer in model container with provided ConstantMap
+// use_inactive should be set as true if the inactive buffer is to be updated.
+// validate_full_update checks if all constants are included in the ConstantMap
+AOTIRuntimeError AOTInductorModelContainerUpdateConstantBuffer(
+    AOTInductorModelContainerHandle container_handle,
+    AOTInductorConstantMapHandle constant_map_handle,
+    bool use_inactive,
+    bool validate_full_update);
+
+// Setup the inactive constant buffer in model container with provided
+// ConstantMap
+AOTIRuntimeError AOTInductorModelContainerUpdateInactiveConstantBuffer(
+    AOTInductorModelContainerHandle container_handle,
+    AOTInductorConstantMapHandle constant_map_handle);
+
+// Run constant folding on constant buffer.
+AOTIRuntimeError AOTInductorModelContainerRunConstantFolding(
+    AOTInductorModelContainerHandle container_handle,
+    bool use_inactive,
+    AOTInductorStreamHandle stream_handle,
+    AOTIProxyExecutorHandle proxy_executor_handle);
+
+// Swap the constant buffer being used to the inactive one.
+AOTIRuntimeError AOTInductorModelContainerSwapConstantBuffer(
+    AOTInductorModelContainerHandle container_handle);
+
+// Retrieves the number of inputs for the model.
+AOTIRuntimeError AOTInductorModelContainerGetNumInputs(
+    AOTInductorModelContainerHandle container_handle,
+    size_t* ret_num_inputs);
+
+// Retrieves the input name at the given index.
+AOTIRuntimeError AOTInductorModelContainerGetInputName(
+    AOTInductorModelContainerHandle container_handle,
+    size_t input_idx,
+    const char** ret_input_names);
+
+// Retrieves the number of outputs for the model.
+AOTIRuntimeError AOTInductorModelContainerGetNumOutputs(
+    AOTInductorModelContainerHandle container_handle,
+    size_t* ret_num_outputs);
+
+// Retrieves the output name at the given index.
+AOTIRuntimeError AOTInductorModelContainerGetOutputName(
+    AOTInductorModelContainerHandle container_handle,
+    size_t output_idx,
+    const char** ret_output_names);
+
+// Creates an AOTInductorModel instance.  This is a thin and light wrapper
+// around the compiled model; it doesn't handle concurrency, queueing, device
+// management, etc.  Use this if bare-metal performance is needed and you are
+// willing to handle other "management" aspects yourself.
+//
+// constant_map_handle is an opaque type to satisfy the C ABI.  It should be a
+// std::unordered_map*.
+AOTIRuntimeError AOTInductorModelCreate(
+    AOTInductorModelHandle* model_handle,
+    AOTInductorConstantMapHandle constant_map_handle);
+
+// Run an AOTInductorModel (see AOTInductorModelCreate for when one should use
+// this function versus AOTInductorModelContainerRun).
+AOTIRuntimeError AOTInductorModelRun(
+    AOTInductorModelHandle model_handle,
+    AtenTensorHandle* input_handles,
+    AtenTensorHandle* output_handles);
+
+// Replace AOTInductorModel's constant map. Note it doesn't handle concurrency
+// so be sure to handle ordering if AOTInductorModelRun is ran concurrently.
+AOTIRuntimeError AOTInductorModelUpdateConstantsMap(
+    AOTInductorModelHandle model_handle,
+    AOTInductorConstantMapHandle constant_map_handle);
+
+// Delete an AOTInductorModel created by AOTInductorModelCreate.
+AOTIRuntimeError AOTInductorModelDelete(AOTInductorModelHandle model_handle);
+
+AOTIRuntimeError AOTInductorModelGetNumOutputs(
+    AOTInductorModelHandle model_handle,
+    size_t* ret_num_outputs);
+
+AOTIRuntimeError AOTInductorModelContainerGetCallSpec(
+    AOTInductorModelContainerHandle container_handle,
+    const char** in_spec,
+    const char** out_spec);
+
+} // extern "C"
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/model.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/model.h
new file mode 100644
index 0000000000000000000000000000000000000000..91df28433d436da771a988d2498a4f4ab5f3ccb0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/model.h
@@ -0,0 +1,621 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+// WARNING: Be careful when adding new includes here. This header will be used
+// in model.so, and should not refer to any aten/c10 headers except the stable
+// C ABI defined in torch/csrc/inductor/aoti_torch/c/shim.h. The same rule
+// applies to other files under torch/csrc/inductor/aoti_runtime/.
+#include 
+#include 
+
+#define AOTI_RUNTIME_CHECK(EXPR, MSG) \
+  do {                                \
+    bool ok = EXPR;                   \
+    if (!ok) {                        \
+      throw std::runtime_error(MSG);  \
+    }                                 \
+  } while (0)
+
+// At codegen time, we write out a binary file called constants.bin.
+// We then turn the raw binary to an object file that exposes this
+// symbol and link it into the final .so.
+// For information on the binary format, see `man objcopy`, under
+// the "binary-architecture" flag:
+// https://man7.org/linux/man-pages/man1/objcopy.1.html
+// todo: use #embed in C++ 23 once available
+// The constants are NOT readonly because they may be mutated.
+extern uint8_t _binary_constants_bin_start[];
+extern uint8_t _binary_constants_bin_end[];
+
+#define AOTI_CONST_GPU_ALIGNMENT 64
+
+namespace {
+
+#ifdef USE_CUDA
+
+using CUDAPtr = std::unique_ptr>;
+
+CUDAPtr RAII_cudaMalloc(size_t num_bytes) {
+  void* data_ptr;
+  AOTI_RUNTIME_DEVICE_CHECK(cudaMalloc((void**)&data_ptr, num_bytes));
+  auto deleter = [](void* ptr) { AOTI_RUNTIME_DEVICE_CHECK(cudaFree(ptr)); };
+  return CUDAPtr(data_ptr, deleter);
+}
+
+#endif // USE_CUDA
+
+} // anonymous namespace
+
+namespace torch::aot_inductor {
+using ConstantMap = std::unordered_map;
+
+// valid device strs are: cpu, cuda, cuda:0, cuda:1, ...
+// Update the list here if more devices are supported in the future
+inline void parse_device_str(
+    const std::string& device_str,
+    int32_t& device_type,
+    int32_t& device_idx) {
+  std::regex re("(cpu|cuda)(:([0-9]+))?");
+  std::smatch sm;
+  bool matched = std::regex_match(device_str, sm, re);
+  AOTI_RUNTIME_CHECK(matched, "Invalid device: " + device_str);
+
+  if (sm[1].str() == "cpu") {
+    device_type = aoti_torch_device_type_cpu();
+  } else if (sm[1].str() == "cuda") {
+    device_type = aoti_torch_device_type_cuda();
+  } else {
+    AOTI_RUNTIME_CHECK(false, "Invalid device: " + device_str);
+  }
+
+  if (sm[3].matched) {
+    device_idx = stoi(sm[3].str());
+  } else {
+    device_idx = -1;
+  }
+}
+
+// Defines the base class for AOTInductorModel, which is generated by the
+// AOTInductor cpp codegen. Since we do not need dynamic dispatch, we rely
+// on curiously recurring template pattern (CRTP) to save some runtime
+// v-table overhead. The generated AOTInductorModel is specialized with
+// methods such as run_impl.
+template 
+class AOTInductorModelBase {
+ public:
+  AOTInductorModelBase(
+      size_t num_inputs,
+      size_t num_outputs,
+      size_t num_constants,
+      const std::string& device_str,
+      std::optional cubin_dir)
+      : inputs_info_(num_inputs),
+        outputs_info_(num_outputs),
+        constants_info_(num_constants),
+        cubin_dir_(std::move(cubin_dir)) {
+    parse_device_str(device_str, device_type_, device_idx_);
+
+#ifdef USE_CUDA
+    if (device_idx_ == -1) {
+      AOTI_RUNTIME_DEVICE_CHECK(cudaGetDevice(&device_idx_));
+    }
+#endif // USE_CUDA
+  }
+
+  ~AOTInductorModelBase() {
+#ifdef USE_CUDA
+    if (run_finished_) {
+      auto code = cudaEventDestroy(*run_finished_);
+      if (code != cudaSuccess) {
+        std::cerr << "Failed to destroy CUDA event in AOTInductor model: "
+                  << cudaGetErrorString(code) << std::endl;
+      }
+    }
+#endif // USE_CUDA
+  }
+
+  AOTInductorModelBase(AOTInductorModelBase&&) = delete;
+  AOTInductorModelBase& operator=(AOTInductorModelBase&&) = delete;
+  AOTInductorModelBase(const AOTInductorModelBase&) = delete;
+  AOTInductorModelBase& operator=(const AOTInductorModelBase&) = delete;
+
+  void run(
+      AtenTensorHandle*
+          input_handles, // array of input AtenTensorHandle; handles
+                         // are stolen; the array itself is borrowed
+      AtenTensorHandle*
+          output_handles, // array for writing output AtenTensorHandle; handles
+                          // will be stolen by the caller; the array itself is
+                          // borrowed
+      DeviceStreamType stream,
+      AOTIProxyExecutorHandle proxy_executor) {
+#ifdef USE_CUDA
+    if (!run_finished_) {
+      cudaEvent_t run_finished;
+      AOTI_RUNTIME_DEVICE_CHECK(cudaEventCreate(&run_finished));
+      run_finished_.emplace(run_finished);
+    }
+
+    auto* model = static_cast(this);
+    model->run_impl(input_handles, output_handles, stream, proxy_executor);
+    AOTI_RUNTIME_DEVICE_CHECK(cudaEventRecord(*run_finished_, stream));
+#else // !USE_CUDA
+    run_finished_ = false;
+    auto* model = static_cast(this);
+    model->run_impl(input_handles, output_handles, stream, proxy_executor);
+    run_finished_ = true;
+#endif // USE_CUDA
+  }
+
+  std::unordered_map run_const_fold(
+      DeviceStreamType stream,
+      AOTIProxyExecutorHandle proxy_executor,
+      bool initialization = false) {
+#ifdef USE_CUDA
+    if (!run_finished_) {
+      cudaEvent_t run_finished;
+      AOTI_RUNTIME_DEVICE_CHECK(cudaEventCreate(&run_finished));
+      run_finished_.emplace(run_finished);
+    }
+#else // USE_CUDA
+    run_finished_ = false;
+#endif // USE_CUDA
+
+    auto* model = static_cast(this);
+    auto folded_constants =
+        model->const_run_impl(stream, proxy_executor, initialization);
+
+#ifdef USE_CUDA
+    AOTI_RUNTIME_DEVICE_CHECK(cudaEventRecord(*run_finished_, stream));
+#else // USE_CUDA
+    run_finished_ = true;
+#endif // USE_CUDA
+
+    return folded_constants;
+  }
+
+  void load_constants() {
+    size_t num_constants = this->num_constants();
+    constants_map_->reserve(num_constants);
+
+    std::vector constants_internal_offset(num_constants);
+    if (device_type_ != aoti_torch_device_type_cpu()) {
+      size_t blob_size = 0;
+      compute_cuda_constant_blob(blob_size, constants_internal_offset);
+#ifdef USE_CUDA
+      constant_blob_ = RAII_cudaMalloc(blob_size);
+#endif
+    }
+
+    size_t bytes_read = 0;
+    for (size_t i = 0; i < num_constants; i++) {
+      bool from_folded = this->constant_from_folded(i);
+#ifndef USE_CUDA
+      if (from_folded) {
+        // We do not reallocate and copy for CPU.
+        continue;
+      }
+#endif // USE_CUDA
+      std::string name = this->constant_name(i);
+      size_t data_size = this->constant_data_size(i);
+      uint8_t* internal_ptr = (data_size != 0)
+          ? constant_ptr(
+                constants_internal_offset[i],
+                bytes_read,
+                data_size,
+                from_folded)
+          : nullptr;
+      bytes_read += data_size;
+
+      // Create at::Tensor from copied memory.
+      auto dtype = this->constant_dtype(i);
+      auto ndim = this->constant_ndim(i);
+      auto size = this->constant_shape(i);
+      auto stride = this->constant_stride(i);
+      auto offset = this->constant_offset(i);
+      auto layout = this->constant_layout(i);
+      auto opaque_metadata_ptr = this->opaque_metadata(i);
+      auto opaque_metadata_size = this->opaque_metadata_size(i);
+
+      AtenTensorHandle tensor_handle = nullptr;
+#ifdef AOTI_USE_CREATE_TENSOR_FROM_BLOB_V1
+      // When opaque_metadata_size is not 0, we need to have the
+      // aoti_torch_create_tensor_from_blob_v2 available
+      AOTI_RUNTIME_CHECK(
+          opaque_metadata_size == 0,
+          "Expect opaque_metadata_size to be 0 when AOTI_USE_CREATE_TENSOR_FROM_BLOB_V1 is defined");
+      AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_create_tensor_from_blob(
+          internal_ptr,
+          ndim,
+          size,
+          stride,
+          offset,
+          dtype,
+          device_type_,
+          device_idx_,
+          &tensor_handle));
+#else
+      AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_create_tensor_from_blob_v2(
+          internal_ptr,
+          ndim,
+          size,
+          stride,
+          offset,
+          dtype,
+          device_type_,
+          device_idx_,
+          &tensor_handle,
+          layout,
+          opaque_metadata_ptr,
+          opaque_metadata_size));
+#endif // AOTI_USE_CREATE_TENSOR_FROM_BLOB_V1
+      constants_map_->emplace(std::move(name), tensor_handle);
+    }
+    if (constants_map_) {
+      this->update_constants_array_from_map();
+    }
+  }
+
+#ifdef USE_CUDA
+  CUDAPtr&& release_constant_blob() {
+    return std::move(constant_blob_);
+  }
+#endif
+
+  std::shared_ptr> get_constants_array() {
+    return constants_;
+  }
+
+  int32_t get_device_idx() const {
+    return device_idx_;
+  }
+
+  uint8_t* constant_ptr(
+      size_t constant_offset,
+      size_t bytes_read,
+      size_t data_size,
+      bool skip_copy) {
+#ifdef USE_CUDA
+    auto* constants_ptr = static_cast(constant_blob_.get());
+    uint8_t* internal_ptr = constants_ptr + constant_offset;
+    // Copy data to GPU memory
+    // TODO: Handle shared storage case.
+    if (!skip_copy) {
+      AOTI_RUNTIME_DEVICE_CHECK(cudaMemcpy(
+          internal_ptr,
+          _get_constants_start() + bytes_read,
+          data_size,
+          cudaMemcpyHostToDevice));
+    }
+    return internal_ptr;
+
+#else
+    // get pointer to constant which is packed in model during compile time.
+    AOTI_RUNTIME_CHECK(!skip_copy, "pure cpu mode doesn't support skip copy");
+    return _get_constants_start() + bytes_read;
+#endif // USE_CUDA
+  }
+
+  void compute_cuda_constant_blob(
+      size_t& blob_size,
+      std::vector& constants_internal_offset) {
+#ifdef USE_CUDA
+    size_t num_constants = this->num_constants();
+    // Compute required blob size with 64-alignment if on GPU.
+    blob_size = 0;
+    for (size_t i = 0; i < num_constants; i++) {
+      size_t data_size = this->constant_data_size(i);
+      if (data_size % AOTI_CONST_GPU_ALIGNMENT) {
+        data_size = AOTI_CONST_GPU_ALIGNMENT +
+            (data_size / AOTI_CONST_GPU_ALIGNMENT) * AOTI_CONST_GPU_ALIGNMENT;
+      }
+      constants_internal_offset[i] = blob_size;
+      blob_size += data_size;
+    }
+#endif // USE_CUDA
+  }
+
+  size_t num_inputs() const {
+    return inputs_info_.size();
+  }
+
+  size_t num_outputs() const {
+    return outputs_info_.size();
+  }
+
+  size_t num_constants() const {
+    return constants_info_.size();
+  }
+
+  const char* input_name(int64_t idx) const {
+    return inputs_info_.at(idx).name;
+  }
+
+  const char* output_name(int64_t idx) const {
+    return outputs_info_.at(idx).name;
+  }
+
+  const char* constant_name(int64_t idx) const {
+    return constants_info_.at(idx).name;
+  }
+
+  size_t constant_ndim(int64_t idx) {
+    return constants_info_.at(idx).shape.size();
+  }
+
+  const int64_t* constant_shape(int64_t idx) const {
+    return constants_info_.at(idx).shape.data();
+  }
+
+  const int64_t* constant_stride(int64_t idx) const {
+    return constants_info_.at(idx).stride.data();
+  }
+
+  int32_t constant_dtype(int64_t idx) const {
+    return constants_info_.at(idx).dtype;
+  }
+
+  int32_t constant_layout(int64_t idx) const {
+    return constants_info_.at(idx).layout;
+  }
+
+  size_t constant_offset(int64_t idx) const {
+    return constants_info_.at(idx).offset;
+  }
+
+  size_t constant_data_size(int64_t idx) const {
+    return constants_info_.at(idx).data_size;
+  }
+
+  const char* constant_original_fqn(int64_t idx) const {
+    return constants_info_.at(idx).original_fqn;
+  }
+
+  const uint8_t* opaque_metadata(int64_t idx) const {
+    return constants_info_.at(idx).opaque_metadata.data();
+  }
+
+  size_t opaque_metadata_size(int64_t idx) {
+    return constants_info_.at(idx).opaque_metadata.size();
+  }
+
+  bool constant_from_folded(int64_t idx) const {
+    return constants_info_.at(idx).from_folded;
+  }
+
+  const char* get_in_spec() const {
+    return in_spec_.c_str();
+  }
+
+  const char* get_out_spec() const {
+    return out_spec_.c_str();
+  }
+
+  void update_constants_array_from_map() {
+    if (!constants_map_) {
+      throw std::runtime_error{
+          "constants_map_ was not ready when constants_ is trying to be constructed from it!"};
+    }
+    if (!constants_) {
+      constants_ =
+          std::make_shared>(constants_info_.size());
+    } else {
+      constants_->resize(constants_info_.size());
+    }
+    int idx = 0;
+    for (const auto& info : constants_info_) {
+      const auto it = constants_map_->find(info.name);
+      if (it != constants_map_->end()) {
+        constants_->at(idx) = ConstantHandle(it->second);
+      }
+      idx++;
+    }
+  }
+
+  void update_constants_map(
+      std::shared_ptr constants_map,
+      bool remap_constants_array = true) {
+    constants_map_ = std::move(constants_map);
+    if (remap_constants_array) {
+      update_constants_array_from_map();
+    }
+  }
+
+  // This function allows us to update the constants_ that is used to look up
+  // the corresponding constant tensor during runtime.
+  void update_constants_array(
+      std::shared_ptr> constants_array) {
+    constants_ = std::move(constants_array);
+  }
+
+  /// Returns true if the model is complete.
+  bool is_finished() {
+#ifdef USE_CUDA
+    if (!run_finished_) {
+      throw std::runtime_error{"Model CUDA event was not initialized"};
+    }
+
+    auto event_status = cudaEventQuery(*run_finished_);
+    if (event_status == cudaSuccess) {
+      return true;
+    } else if (event_status == cudaErrorNotReady) {
+      return false;
+    }
+
+    throw std::runtime_error(
+        std::string("The model did not finish successfully. Error: ") +
+        cudaGetErrorString(cudaGetLastError()));
+#else // !USE_CUDA
+    return run_finished_;
+#endif // USE_CUDA
+  }
+
+  /// Synchronizes completion event.
+  void wait_for_completion() {
+#ifdef USE_CUDA
+    if (!run_finished_) {
+      throw std::runtime_error{"Model event was not initialized"};
+    }
+
+    AOTI_RUNTIME_DEVICE_CHECK(cudaEventSynchronize(*run_finished_));
+#endif // USE_CUDA
+  }
+
+ protected:
+  uint8_t* _get_constants_start() {
+#ifndef USE_MMAP_SELF
+    return const_cast(_binary_constants_bin_start);
+#else
+    if (self_mmap) {
+      return self_mmap;
+    }
+    Dl_info dl_info;
+    // get pointer to constant which are appended to the binary
+    AOTI_RUNTIME_CHECK(
+        dladdr(__func__, &dl_info), "Can't find shared library name");
+    int fd = open(dl_info.dli_fname, O_RDONLY);
+    AOTI_RUNTIME_CHECK(fd >= 0, "Shared library file cannot be opened");
+    auto fsize = lseek(fd, 0, SEEK_END);
+    auto weights_size =
+        reinterpret_cast(_binary_constants_bin_start)[0];
+    auto magic_number =
+        reinterpret_cast(_binary_constants_bin_start)[1];
+    auto weights_offset = fsize - weights_size;
+    AOTI_RUNTIME_CHECK(
+        (weights_offset & 0x3fff) == 0,
+        "weights_offset must be aligned to 16K boundary");
+    auto ptr = mmap(
+        NULL,
+        weights_size,
+        PROT_READ | PROT_WRITE,
+        MAP_PRIVATE,
+        fd,
+        weights_offset);
+    close(fd);
+    AOTI_RUNTIME_CHECK(ptr != MAP_FAILED, "mmap() failed");
+    self_mmap = static_cast(ptr);
+    AOTI_RUNTIME_CHECK(
+        reinterpret_cast(
+            self_mmap + weights_size - sizeof(uint64_t))[0] == magic_number,
+        "Weigths data seems corrupt");
+    return self_mmap;
+#endif
+  }
+  struct ParamInfo {
+    const char* name = nullptr;
+  };
+
+  struct ConstInfo {
+    const char* name = nullptr;
+    std::vector shape;
+    std::vector stride;
+    int32_t dtype{};
+    int64_t offset{};
+    size_t data_size{};
+    int32_t layout{};
+    std::vector opaque_metadata;
+    int64_t opaque_metadata_size{};
+    const char* original_fqn = nullptr;
+    bool from_folded{};
+  };
+
+  std::vector inputs_info_;
+  std::vector outputs_info_;
+  std::vector constants_info_;
+  std::string in_spec_;
+  std::string out_spec_;
+
+  std::shared_ptr constants_map_;
+  std::shared_ptr> constants_;
+
+#ifdef USE_CUDA
+  // Holds the blob storage for constants' at::Tensor for CUDA.
+  CUDAPtr constant_blob_;
+#endif // USE_CUDA
+#ifdef USE_MMAP_SELF
+  uint8_t* self_mmap = NULL;
+#endif
+
+  // A directory with CUDA binary files, e.g. compiled kernels, etc.
+  const std::optional cubin_dir_;
+
+  // Record if the model finishes an inference run so that its owning
+  // AOTModelContainer can re-use this instance.
+#ifdef USE_CUDA
+  std::optional run_finished_;
+#else // !USE_CUDA
+  bool run_finished_{};
+#endif
+
+  // Generated model uses this device index to create CUDA guards.
+  int32_t device_type_{};
+  int32_t device_idx_{};
+};
+
+// Codegen-ed classes can derive from this to keep pointers to loaded kernels.
+class AOTInductorModelKernelsBase {
+ public:
+  virtual ~AOTInductorModelKernelsBase() = default;
+};
+
+class AOTInductorModel : public AOTInductorModelBase {
+ public:
+  AOTInductorModel(
+      std::shared_ptr constants_map,
+      std::shared_ptr> constants_array,
+      const std::string& device_str,
+      std::optional cubin_dir);
+
+  std::unordered_map const_run_impl(
+      DeviceStreamType stream,
+      AOTIProxyExecutorHandle proxy_executor,
+      bool initialization = false);
+
+  void _const_run_impl(
+      std::vector& output_handles,
+      DeviceStreamType stream,
+      AOTIProxyExecutorHandle proxy_executor);
+
+  void run_impl(
+      AtenTensorHandle*
+          input_handles, // array of input AtenTensorHandle; handles
+                         // are stolen; the array itself is borrowed
+      AtenTensorHandle*
+          output_handles, // array for writing output AtenTensorHandle; handles
+                          // will be stolen by the caller; the array itself is
+                          // borrowed
+      DeviceStreamType stream,
+      AOTIProxyExecutorHandle proxy_executor);
+
+  template 
+  Outputs run_impl_minimal_arrayref_interface(
+      const Inputs& inputs,
+      DeviceStreamType stream,
+      AOTIProxyExecutorHandle proxy_executor);
+
+  static std::unique_ptr Create(
+      std::shared_ptr constants_map,
+      std::shared_ptr> constants_array,
+      const std::string& device_str,
+      std::optional cubin_dir) {
+    return std::make_unique(
+        std::move(constants_map),
+        std::move(constants_array),
+        device_str,
+        std::move(cubin_dir));
+  }
+
+ private:
+  std::unique_ptr kernels_;
+};
+
+} // namespace torch::aot_inductor
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/model_container.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/model_container.h
new file mode 100644
index 0000000000000000000000000000000000000000..8227338f0112bc9d0407ba4fb14b0e4b3ccede43
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/model_container.h
@@ -0,0 +1,532 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+// WARNING: Be careful when adding new includes here. This header will be used
+// in model.so, and should not refer to any aten/c10 headers except the stable
+// C ABI defined in torch/csrc/inductor/aoti_torch/c/shim.h. The same rule
+// applies to other files under torch/csrc/inductor/aoti_runtime/.
+#include 
+
+namespace torch::aot_inductor {
+
+class AOTInductorModelContainer {
+ public:
+  AOTInductorModelContainer(
+      size_t num_models,
+      const std::string& device_str,
+      const std::optional& cubin_dir = std::nullopt)
+      : use_secondary_(false), constant_folded_(false) {
+    constants_map_ = std::make_shared();
+    constants_array_ = std::make_shared>();
+
+    models_.reserve(num_models);
+    available_models_.reserve(num_models);
+    for (size_t i = 0; i < num_models; ++i) {
+      models_.push_back(AOTInductorModel::Create(
+          constants_map_, constants_array_, device_str, cubin_dir));
+      available_models_.push_back(models_.back().get());
+    }
+
+    // Note that the all following fields (input_names_, output_names,
+    // etc) can be filled in by the AOT
+    // codegen. However, we choose to query such information from
+    // the owned AOTInductorModel for a couple of reasons:
+    //   * simplify the codegen templates
+    //   * reduce information fragmentation and duplication
+    //   * the initialization process below is done only once when the container
+    //     is constructed, so it would have little performance impact
+    auto* model = available_models_[0];
+    size_t num_inputs = model->num_inputs();
+    input_names_.reserve(num_inputs);
+    for (size_t i = 0; i < num_inputs; i++) {
+      input_names_.emplace_back(model->input_name(static_cast(i)));
+    }
+
+    size_t num_outputs = model->num_outputs();
+    output_names_.reserve(num_outputs);
+    for (size_t i = 0; i < num_outputs; i++) {
+      output_names_.emplace_back(model->output_name(static_cast(i)));
+    }
+
+    model->load_constants();
+#ifdef USE_CUDA
+    constant_blob_ = model->release_constant_blob();
+    constants_internal_offset_.resize(model->num_constants());
+    model->compute_cuda_constant_blob(blob_size_, constants_internal_offset_);
+#endif
+
+    for (auto& model : models_) {
+      model->update_constants_map(constants_map_);
+    }
+
+    in_spec_ = model->get_in_spec();
+    out_spec_ = model->get_out_spec();
+  }
+
+  void run(
+      AtenTensorHandle*
+          input_handles, // array of input AtenTensorHandle; handles
+                         // are stolen; the array itself is borrowed
+      AtenTensorHandle*
+          output_handles, // array for writing output AtenTensorHandle; handles
+                          // will be stolen by the caller; the array itself is
+                          // borrowed
+      DeviceStreamType stream,
+      AOTIProxyExecutorHandle proxy_executor) {
+    std::shared_lock model_lk(model_exec_mutex_);
+    auto* model = get_available_model();
+
+    if (!constant_folded_) {
+      // At this point, constant is not ready yet. We need to call constant
+      // folding before we execute the model. We obtain a unique lock at this
+      // point to make sure constant is ready for all.
+      model_lk.unlock();
+      std::unique_lock constants_folding_lk(model_exec_mutex_);
+      // Double locking to make sure constant folding is only ran once.
+      if (!constant_folded_) {
+        auto folded_const_map = model->run_const_fold(
+            stream, proxy_executor, /* initialization = */ true);
+        update_constant_buffer(
+            folded_const_map,
+            /* use_inactive = */ false,
+            /* validate_full_update = */ false);
+        constant_folded_ = true;
+      }
+      constants_folding_lk.unlock();
+      model_lk.lock();
+    }
+
+    try {
+      model->run(input_handles, output_handles, stream, proxy_executor);
+    } catch (...) {
+      std::lock_guard lk(models_mutex_);
+      available_models_.push_back(model);
+      throw;
+    }
+
+    {
+      std::lock_guard lk(models_mutex_);
+      pending_models_.push_back(model);
+    }
+    pending_models_available_.notify_one();
+  }
+
+  size_t num_constants() const {
+    if (this->num_models() == 0) {
+      throw std::runtime_error("No available models in container!");
+    }
+    return models_[0]->num_constants();
+  }
+
+  // retrieve the constant name of constants_info_[idx]
+  const char* constant_name(size_t idx) const {
+    if (this->num_models() == 0) {
+      throw std::runtime_error("No available models in container!");
+    }
+    return models_[0]->constant_name(static_cast(idx));
+  }
+
+  // retrieve original FQN of constants_info_[idx]
+  const char* constant_original_fqn(size_t idx) const {
+    if (this->num_models() == 0) {
+      throw std::runtime_error("No available models in container!");
+    }
+    return models_[0]->constant_original_fqn(static_cast(idx));
+  }
+
+  // retrieve whether constant is from folded of constants_info_[idx]
+  bool constant_from_folded(size_t idx) const {
+    if (this->num_models() == 0) {
+      throw std::runtime_error("No available models in container!");
+    }
+    return models_[0]->constant_from_folded(static_cast(idx));
+  }
+
+  // retrieve dtype of constants_info_[idx]
+  int32_t constant_dtype(size_t idx) const {
+    if (this->num_models() == 0) {
+      throw std::runtime_error("No available models in container!");
+    }
+    return models_[0]->constant_dtype(static_cast(idx));
+  }
+
+  void run_const_fold(
+      bool inactive_buffer,
+      DeviceStreamType stream,
+      AOTIProxyExecutorHandle proxy_executor) {
+    std::shared_lock model_lk(model_exec_mutex_);
+    auto* model = get_available_model();
+
+    if (!inactive_buffer) {
+      // We would need to acquire a unique lock if we want to run constant
+      // folding on the active buffer.
+      model_lk.unlock();
+      std::unique_lock constants_folding_lk(model_exec_mutex_);
+      try {
+        auto folded_const_map = model->run_const_fold(stream, proxy_executor);
+        update_constant_buffer(
+            folded_const_map,
+            /* use_inactive = */ false,
+            /* validate_full_update = */ false);
+      } catch (...) {
+        std::lock_guard lk(models_mutex_);
+        available_models_.push_back(model);
+        throw;
+      }
+      constants_folding_lk.unlock();
+      model_lk.lock();
+    } else {
+      // We swap the constant mapping to the inactive buffer in the model to run
+      // const run.
+      auto constants_map = get_constants_map(/* get_inactive= */ true);
+      auto constants_array = get_constants_array(/* get_inactive= */ true);
+
+      try {
+        model->update_constants_map(
+            constants_map, /* remap_constants_array= */ false);
+        model->update_constants_array(constants_array);
+
+        auto folded_const_map = model->run_const_fold(stream, proxy_executor);
+        update_constant_buffer(
+            folded_const_map,
+            /* use_inactive = */ true,
+            /* validate_full_update = */ false);
+
+        // Swap back the model's constants mapping
+        constants_map = get_constants_map(/* get_inactive= */ false);
+        constants_array = get_constants_array(/* get_inactive= */ false);
+        model->update_constants_map(
+            constants_map, /* remap_constants_array= */ false);
+        model->update_constants_array(constants_array);
+      } catch (...) {
+        std::lock_guard lk(models_mutex_);
+        available_models_.push_back(model);
+        throw;
+      }
+    }
+
+    {
+      std::lock_guard lk(models_mutex_);
+      pending_models_.push_back(model);
+    }
+    pending_models_available_.notify_one();
+  }
+
+  bool _is_tensor_constant(const std::string& constant_name) const {
+    return constant_name.rfind("_tensor_constant", 0) == 0;
+  }
+  // This function updates the buffer for storing constants.
+  // It will update the buffer, the mapping and the array mapping.
+  void update_constant_buffer(
+      const std::unordered_map& constants_map,
+      bool use_inactive,
+      bool validate_full_update) {
+    if (this->num_models() == 0) {
+      throw std::runtime_error("No model available in container!");
+    }
+    auto num_constants = models_[0]->num_constants();
+
+    if (validate_full_update) {
+      for (size_t idx = 0; idx < num_constants; idx++) {
+        if (models_[0]->constant_from_folded(static_cast(idx))) {
+          continue;
+        }
+
+        auto constant_name =
+            std::string(models_[0]->constant_name(static_cast(idx)));
+        auto it = constants_map.find(constant_name);
+        if (it == constants_map.end()) {
+          if (_is_tensor_constant(constant_name)) {
+            // tracing sometimes creates tensors that are non-existent in
+            // original graph. We could skip those and do a direct copy.
+            std::cerr << "[WARNING] Found constant " << constant_name
+                      << " in model, but not provided by user!\n";
+            continue;
+          }
+          throw std::runtime_error(
+              std::string("Cannot find constants ") + constant_name +
+              std::string(" in constants_map!"));
+        }
+      }
+    }
+
+    auto original_constants_map = get_constants_map(!use_inactive);
+    auto constants_map_to_update = get_constants_map(use_inactive);
+
+    for (size_t idx = 0; idx < num_constants; idx++) {
+      auto constant_name =
+          std::string(models_[0]->constant_name(static_cast(idx)));
+      auto it = constants_map.find(constant_name);
+      if (it == constants_map.end() &&
+          !(_is_tensor_constant(constant_name) && use_inactive)) {
+        continue;
+      }
+
+#ifdef USE_CUDA
+      AtenTensorHandle tensor;
+      if (_is_tensor_constant(constant_name) && use_inactive) {
+        tensor = original_constants_map->find(constant_name)->second.get();
+      } else {
+        tensor = it->second;
+      }
+      auto* constants_blob_ptr =
+          static_cast(get_constant_blob_ptr(use_inactive));
+
+      // Move the data to container handled blob.
+      uint8_t* internal_constants_ptr =
+          constants_blob_ptr + constants_internal_offset_[idx];
+      void* user_constant_ptr;
+      int64_t constant_size;
+      aoti_torch_get_data_ptr(tensor, &user_constant_ptr);
+      aoti_torch_get_storage_size(tensor, &constant_size);
+
+      AOTI_RUNTIME_DEVICE_CHECK(cudaMemcpy(
+          internal_constants_ptr,
+          user_constant_ptr,
+          constant_size,
+          cudaMemcpyDefault));
+
+      // Generate Tensor from container handled blob.
+      // We extract stride and offset from provided Tensor since we do not
+      // guarantee that the tensor is contiguous.
+      AtenTensorHandle tensor_handle;
+      int64_t* stride;
+      int64_t offset;
+      int device_idx = models_[0]->get_device_idx();
+      AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_strides(tensor, &stride));
+      AOTI_TORCH_ERROR_CODE_CHECK(
+          aoti_torch_get_storage_offset(tensor, &offset));
+      AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_create_tensor_from_blob(
+          internal_constants_ptr,
+          models_[0]->constant_ndim(idx),
+          models_[0]->constant_shape(idx),
+          stride,
+          offset,
+          models_[0]->constant_dtype(idx),
+          aoti_torch_device_type_cuda(),
+          device_idx,
+          &tensor_handle));
+#else // USE_CUDA
+      AtenTensorHandle tensor_handle = it->second;
+#endif // USE_CUDA
+
+      // Now place the tensor to constants_map. Note at this point the ownership
+      // of the tensor_handle will be taken over.
+      constants_map_to_update->emplace(constant_name, tensor_handle);
+    }
+    // Update the inactive constant array.
+    update_array_from_map(
+        get_constants_array(use_inactive), constants_map_to_update);
+  }
+
+  void update_array_from_map(
+      const std::shared_ptr>& constants_array,
+      const std::shared_ptr& constants_map) {
+    auto num_constants = models_[0]->num_constants();
+    for (size_t idx = 0; idx < num_constants; idx++) {
+      if (constants_map->find(models_[0]->constant_name(
+              static_cast(idx))) != constants_map->end()) {
+        constants_array->at(idx) = ConstantHandle(
+            constants_map
+                ->find(models_[0]->constant_name(static_cast(idx)))
+                ->second);
+      }
+    }
+  }
+
+  void swap_constant_buffer() {
+    std::lock_guard unique_lk(model_exec_mutex_);
+
+    auto constants_map = get_constants_map(/* get_inactive= */ true);
+    auto constants_array = get_constants_array(/* get_inactive= */ true);
+
+    for (auto& model : models_) {
+      model->update_constants_map(
+          constants_map, /* remap_constants_array = */ false);
+      model->update_constants_array(constants_array);
+    }
+
+    use_secondary_ = !use_secondary_;
+  }
+
+  size_t num_inputs() const {
+    return input_names_.size();
+  }
+
+  size_t num_outputs() const {
+    return output_names_.size();
+  }
+
+  const char* input_name(size_t idx) const {
+    return input_names_.at(idx).c_str();
+  }
+
+  const char* output_name(size_t idx) const {
+    return output_names_.at(idx).c_str();
+  }
+
+  size_t num_models() const {
+    return models_.size();
+  }
+
+  const char* get_in_spec() const {
+    return in_spec_;
+  }
+
+  const char* get_out_spec() const {
+    return out_spec_;
+  }
+
+ private:
+  std::vector input_names_;
+  std::vector output_names_;
+  const char* in_spec_;
+  const char* out_spec_;
+
+#ifdef USE_CUDA
+  // Holds the blob storage for constants' at::Tensor for CUDA.
+  CUDAPtr constant_blob_;
+  CUDAPtr constant_blob_secondary_;
+
+  // Let's place this within USE_CUDA at the moment before we fully support
+  // update for CPU cases.
+  size_t blob_size_;
+  std::vector constants_internal_offset_;
+#endif // USE_CUDA
+
+  // Determine which constants is being used for the model.
+  // If true,
+  // constants_map_secondary/constant_blob_secondary/constants_array_secondary
+  // is being used.
+  bool use_secondary_;
+
+  // Determine whether we have ran constant folding
+  bool constant_folded_;
+
+  // Holds the mapping of constants to at::Tensor.
+  // The underlying data of at::Tensor is in either constant_blob_ (for CUDA).
+  // or _binary_constants_bin_start (for CPU).
+  std::shared_ptr constants_map_;
+  std::shared_ptr constants_map_secondary_;
+
+  // Holds the indexed array of constant for faster lookup during runtime.
+  std::shared_ptr> constants_array_;
+  std::shared_ptr> constants_array_secondary_;
+
+  // Holds all the AOTInductorModel instances owned by this container.
+  std::vector> models_;
+
+  // Holds the AOTInductorModel instances available for inference.
+  std::vector available_models_;
+
+  // Holds the AOTInductorModel instances that have started running
+  // inference and can be placed onto available_models_ upon their
+  // completion.
+  std::deque pending_models_;
+
+  // Protects available_models_ and pending_models_.
+  std::mutex models_mutex_;
+
+  // Notified whenever a model is placed onto pending_models_.
+  std::condition_variable pending_models_available_;
+
+  AOTInductorModel* get_available_model() {
+    std::unique_lock lk(models_mutex_);
+    if (available_models_.empty()) {
+      reclaim_finished_models(lk);
+    }
+    auto* result = available_models_.back();
+    available_models_.pop_back();
+    return result;
+  }
+
+  // This mutex is used to protect execution of model.
+  // We acquire the mutex in shared mode if we allow concurrent execution.
+  // We acquire the mutex in unique mode when we want exclusive access of the
+  // model. One such case is when we want to do a weight swapping. We want to
+  // make sure no one is executing the model.
+  std::shared_mutex model_exec_mutex_;
+
+#ifdef USE_CUDA
+  void* get_constant_blob_ptr(bool get_inactive) {
+    if ((get_inactive && use_secondary_) ||
+        (!get_inactive && !use_secondary_)) {
+      return constant_blob_.get();
+    } else {
+      if (!constant_blob_secondary_) {
+        constant_blob_secondary_ = RAII_cudaMalloc(blob_size_);
+      }
+      return constant_blob_secondary_.get();
+    }
+  }
+#endif // USE_CUDA
+
+  std::shared_ptr get_constants_map(bool get_inactive) {
+    if ((get_inactive && use_secondary_) ||
+        (!get_inactive && !use_secondary_)) {
+      return constants_map_;
+    } else {
+      if (!constants_map_secondary_) {
+        constants_map_secondary_ = std::make_shared();
+      }
+      return constants_map_secondary_;
+    }
+  }
+
+  std::shared_ptr> get_constants_array(
+      bool get_inactive) {
+    if ((get_inactive && use_secondary_) ||
+        (!get_inactive && !use_secondary_)) {
+      return constants_array_;
+    } else {
+      if (!constants_array_secondary_) {
+        constants_array_secondary_ =
+            std::make_shared>(
+                models_[0]->num_constants());
+      }
+      return constants_array_secondary_;
+    }
+  }
+
+  void reclaim_finished_models(std::unique_lock& lk) {
+    // push finished model instances to the end of pending_models_
+    auto it = std::stable_partition(
+        pending_models_.begin(),
+        pending_models_.end(),
+        [](AOTInductorModel* m) { return !m->is_finished(); });
+
+    if (it != pending_models_.end()) {
+      // We have finished model instances that can be pushed into
+      // available_models_ so that we don't have to be blocked on waiting
+      // the pending_models_available_ condition.
+      available_models_.insert(
+          available_models_.end(), it, pending_models_.end());
+      pending_models_.erase(it, pending_models_.end());
+      return;
+    }
+
+    pending_models_available_.wait(
+        lk, [this]() { return !pending_models_.empty(); });
+    // Let's make the schedule simple first. We always wait on the first
+    // pending_models_ to be complete.
+    auto* model = pending_models_.front();
+    pending_models_.pop_front();
+    lk.unlock();
+    try {
+      model->wait_for_completion();
+    } catch (...) {
+      lk.lock();
+      available_models_.push_back(model);
+      throw;
+    }
+    lk.lock();
+    available_models_.push_back(model);
+  }
+};
+
+} // namespace torch::aot_inductor
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/scalar_to_tensor.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/scalar_to_tensor.h
new file mode 100644
index 0000000000000000000000000000000000000000..2c044962cca54dd043e68ec1c96e4ae307c2cb9d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/scalar_to_tensor.h
@@ -0,0 +1,35 @@
+#pragma once
+
+#include 
+
+namespace torch::aot_inductor {
+
+template 
+inline RAIIAtenTensorHandle scalar_to_tensor_handle(T value) {
+  throw std::runtime_error("Unsupported scalar_to_tensor_handle");
+}
+
+// Specialize for supported C++ primitive types
+#define AOTI_RUNTIME_SCALAR_TO_TENSOR(dtype, ctype)                         \
+  template <>                                                               \
+  inline RAIIAtenTensorHandle scalar_to_tensor_handle(ctype value) { \
+    AtenTensorHandle tensor_handle;                                         \
+    AOTI_TORCH_ERROR_CODE_CHECK(                                            \
+        aoti_torch_scalar_to_tensor_##dtype(value, &tensor_handle));        \
+    return RAIIAtenTensorHandle(tensor_handle);                             \
+  }
+
+AOTI_RUNTIME_SCALAR_TO_TENSOR(float32, float)
+AOTI_RUNTIME_SCALAR_TO_TENSOR(float64, double)
+AOTI_RUNTIME_SCALAR_TO_TENSOR(uint8, uint8_t)
+AOTI_RUNTIME_SCALAR_TO_TENSOR(uint16, uint16_t)
+AOTI_RUNTIME_SCALAR_TO_TENSOR(uint32, uint32_t)
+AOTI_RUNTIME_SCALAR_TO_TENSOR(uint64, uint64_t)
+AOTI_RUNTIME_SCALAR_TO_TENSOR(int8, int8_t)
+AOTI_RUNTIME_SCALAR_TO_TENSOR(int16, int16_t)
+AOTI_RUNTIME_SCALAR_TO_TENSOR(int32, int32_t)
+AOTI_RUNTIME_SCALAR_TO_TENSOR(int64, int64_t)
+AOTI_RUNTIME_SCALAR_TO_TENSOR(bool, bool)
+#undef AOTI_RUNTIME_SCALAR_TO_TENSOR
+
+} // namespace torch::aot_inductor
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/thread_local.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/thread_local.h
new file mode 100644
index 0000000000000000000000000000000000000000..e640ffe630d5c76b90686992fa8e19294647fb77
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/thread_local.h
@@ -0,0 +1,156 @@
+#pragma once
+
+#include 
+
+namespace torch::aot_inductor {
+
+template 
+struct ThreadLocalCachedOutputTensor;
+
+template <>
+struct ThreadLocalCachedOutputTensor {
+  explicit ThreadLocalCachedOutputTensor(const RAIIAtenTensorHandle&) {}
+  void copy_data_from(const RAIIAtenTensorHandle& handle) {
+    throw std::runtime_error("can't happen");
+  }
+
+  AtenTensorHandle tensor() const {
+    throw std::runtime_error("can't happen");
+  }
+};
+
+template <>
+struct ThreadLocalCachedOutputTensor {
+  explicit ThreadLocalCachedOutputTensor(const AtenTensorHandle&) {}
+  void copy_data_from(const AtenTensorHandle& handle) {
+    throw std::runtime_error("can't happen");
+  }
+
+  AtenTensorHandle tensor() const {
+    throw std::runtime_error("can't happen");
+  }
+};
+
+template <>
+struct ThreadLocalCachedOutputTensor {
+  explicit ThreadLocalCachedOutputTensor(const ConstantHandle&) {}
+  void copy_data_from(const ConstantHandle& handle) {
+    throw std::runtime_error("can't happen");
+  }
+
+  AtenTensorHandle tensor() const {
+    throw std::runtime_error("can't happen");
+  }
+};
+
+template 
+struct ThreadLocalCachedOutputTensor> {
+  explicit ThreadLocalCachedOutputTensor(const ArrayRefTensor& t) {
+    realloc(t);
+  }
+
+  void copy_data_from(const ArrayRefTensor& t) {
+    if (t.numel() > capacity_) {
+      realloc(t);
+    }
+    std::copy(t.data(), t.data() + t.numel(), storage_.get());
+  }
+
+  AtenTensorHandle tensor() const {
+    return tensor_.get();
+  }
+
+ private:
+  void realloc(const ArrayRefTensor& t) {
+    capacity_ = t.numel();
+    storage_ = std::make_unique(t.numel());
+    AtenTensorHandle handle = nullptr;
+    AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_create_tensor_from_blob(
+        storage_.get(),
+        t.sizes().size(),
+        t.sizes().data(),
+        t.strides().data(),
+        0,
+        aoti_torch_dtype>(),
+        t.device_type(),
+        t.device_idx(),
+        &handle));
+    tensor_ = handle;
+  }
+
+  std::unique_ptr storage_;
+  int64_t capacity_ = 0;
+  RAIIAtenTensorHandle tensor_;
+};
+
+template 
+struct ThreadLocalCachedOutputArray;
+
+// Just needs to compile, doesn't need to do anything.
+template <>
+struct ThreadLocalCachedOutputArray {
+  explicit ThreadLocalCachedOutputArray(const RAIIAtenTensorHandle&) {
+    throw std::runtime_error("can't happen");
+  }
+
+  // Not supported yet! We would need to put contiguous() or
+  // expect_contiguous() into the ABI.
+  void copy_data_from(const RAIIAtenTensorHandle&) {
+    throw std::runtime_error("can't happen");
+  }
+
+  template 
+  ArrayRefTensor arrayref_tensor() const {
+    throw std::runtime_error("can't happen");
+  }
+};
+
+// Just needs to compile, doesn't need to do anything.
+template <>
+struct ThreadLocalCachedOutputArray {
+  explicit ThreadLocalCachedOutputArray(const ConstantHandle&) {
+    throw std::runtime_error("can't happen");
+  }
+
+  // Not supported yet! We would need to put contiguous() or
+  // expect_contiguous() into the ABI.
+  void copy_data_from(const ConstantHandle&) {
+    throw std::runtime_error("can't happen");
+  }
+
+  template 
+  ArrayRefTensor arrayref_tensor() const {
+    throw std::runtime_error("can't happen");
+  }
+};
+
+template 
+struct ThreadLocalCachedOutputArray> {
+  explicit ThreadLocalCachedOutputArray(const ArrayRefTensor& t) {}
+
+  template <
+      typename U,
+      std::enable_if_t<
+          std::is_same_v, std::remove_const_t>,
+          bool> = true>
+  ArrayRefTensor arrayref_tensor() const {
+    return tensor_;
+  }
+
+  void copy_data_from(const ArrayRefTensor& t) {
+    if (t.numel() > capacity_) {
+      capacity_ = t.numel();
+      storage_ = std::make_unique(capacity_);
+    }
+    std::copy(t.data(), t.data() + t.numel(), storage_.get());
+    tensor_ = t;
+    tensor_.set_arrayref(MiniArrayRef(storage_.get(), t.numel()));
+  }
+
+ private:
+  std::unique_ptr storage_;
+  uint32_t capacity_ = 0;
+  ArrayRefTensor tensor_;
+};
+
+} // namespace torch::aot_inductor
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/utils.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/utils.h
new file mode 100644
index 0000000000000000000000000000000000000000..db7b366a92c7d7ec682b3219cf7ffe2e91398341
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/utils.h
@@ -0,0 +1,184 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+// WARNING: Be careful when adding new includes here. This header will be used
+// in model.so, and should not refer to any aten/c10 headers except the stable
+// C ABI defined in torch/csrc/inductor/aoti_torch/c/shim.h. The same rule
+// applies to other files under torch/csrc/inductor/aoti_runtime/.
+#include 
+
+#if defined(__GNUC__) || defined(__clang__)
+#define AOTI_NOINLINE __attribute__((noinline))
+#elif _MSC_VER
+#define AOTI_NOINLINE __declspec(noinline)
+#else
+#define AOTI_NOINLINE
+#endif
+
+AOTI_NOINLINE static void throw_exception(
+    const char* call,
+    const char* file,
+    int64_t line) {
+  std::stringstream ss;
+  ss << call << " API call failed at " << file << ", line " << line;
+  throw std::runtime_error(ss.str());
+}
+
+#define AOTI_TORCH_ERROR_CODE_CHECK(call)       \
+  if ((call) != AOTI_TORCH_SUCCESS) {           \
+    throw_exception(#call, __FILE__, __LINE__); \
+  }
+
+using AOTIRuntimeError = int32_t;
+#define AOTI_RUNTIME_SUCCESS 0
+#define AOTI_RUNTIME_FAILURE 1
+
+#define AOTI_RUNTIME_ERROR_CODE_CHECK(call)     \
+  if ((call) != AOTI_RUNTIME_SUCCESS) {         \
+    throw_exception(#call, __FILE__, __LINE__); \
+  }
+
+namespace torch::aot_inductor {
+
+using DeleterFnPtr = void (*)(void*);
+
+inline void noop_deleter(void*) {}
+
+inline void delete_tensor_object(void* ptr) {
+  AOTI_TORCH_ERROR_CODE_CHECK(
+      aoti_torch_delete_tensor_object(reinterpret_cast(ptr)));
+}
+
+// RAIIAtenTensorHandle steals the tensor objects created by the libtorch C ABI
+class RAIIAtenTensorHandle {
+ public:
+  RAIIAtenTensorHandle() : handle_(nullptr, noop_deleter) {}
+  RAIIAtenTensorHandle(const RAIIAtenTensorHandle& other) = delete;
+  RAIIAtenTensorHandle& operator=(const RAIIAtenTensorHandle& other) = delete;
+
+  // Steal the ownership from another RAIIAtenTensorHandle using std::move
+  RAIIAtenTensorHandle(RAIIAtenTensorHandle&& other) = default;
+  RAIIAtenTensorHandle& operator=(RAIIAtenTensorHandle&& other) = default;
+
+  // Steal the ownership from raw AtenTensorHandle
+  RAIIAtenTensorHandle(AtenTensorHandle handle)
+      : handle_(handle, delete_tensor_object) {}
+
+  ~RAIIAtenTensorHandle() {
+    handle_.reset();
+  }
+
+  // Return a raw AtenTensorHandle to be used by aoti_torch functions
+  // Note: this function does NOT transfer the ownership of the handle
+  operator AtenTensorHandle() const {
+    return handle_.get();
+  }
+
+  AtenTensorHandle release() {
+    return handle_.release();
+  }
+
+  AtenTensorHandle get() const {
+    return handle_.get();
+  }
+
+  void reset() {
+    handle_.reset();
+  }
+
+  int64_t size(int64_t d) {
+    int64_t size = 0;
+    AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_size(handle_.get(), d, &size));
+    return size;
+  }
+
+  int64_t stride(int64_t d) {
+    int64_t stride = 0;
+    AOTI_TORCH_ERROR_CODE_CHECK(
+        aoti_torch_get_stride(handle_.get(), d, &stride));
+    return stride;
+  }
+
+  int64_t storage_offset() {
+    int64_t storage_offset = 0;
+    AOTI_TORCH_ERROR_CODE_CHECK(
+        aoti_torch_get_storage_offset(handle_.get(), &storage_offset));
+    return storage_offset;
+  }
+
+ private:
+  std::unique_ptr handle_;
+};
+
+// Steal the ownership from raw AtenTensorHandle to RAIIAtenTensorHandle
+inline std::vector steal_from_raw_handles_to_raii_handles(
+    AtenTensorHandle* handles,
+    size_t size) {
+  std::vector result;
+  result.reserve(size);
+  for (size_t i = 0; i < size; i++) {
+    result.emplace_back(handles[i]);
+    handles[i] = nullptr;
+  }
+  return result;
+}
+
+class ConstantHandle {
+ public:
+  ConstantHandle() = default;
+
+  explicit ConstantHandle(AtenTensorHandle handle) : handle_(handle) {
+    AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_data_ptr(handle_, &data_));
+  }
+
+  operator AtenTensorHandle() const {
+    return handle_;
+  }
+
+  AtenTensorHandle tensor() const {
+    return handle_;
+  }
+
+  AtenTensorHandle get() const {
+    return handle_;
+  }
+
+  void* data_ptr() const {
+    return data_;
+  }
+
+ private:
+  AtenTensorHandle handle_{};
+  void* data_ = nullptr;
+};
+
+inline void* get_data_ptr_wrapper(const ConstantHandle& constant) {
+  return constant.data_ptr();
+}
+
+inline const ConstantHandle& unwrap_raii_handle_if_needed(
+    const ConstantHandle& handle) {
+  return handle;
+}
+
+// Shouldn't be called.
+inline AtenTensorHandle wrap_with_raii_handle_if_needed(
+    const ConstantHandle& handle) = delete;
+
+#define CACHE_TORCH_DTYPE(typename) \
+  static auto cached_torch_dtype_##typename = aoti_torch_dtype_##typename()
+
+#define CACHE_TORCH_DEVICE(device)                \
+  static auto cached_torch_device_type_##device = \
+      aoti_torch_device_type_##device()
+
+#define CACHE_TORCH_LAYOUT(layout) \
+  static auto cached_torch_layout_##layout = aoti_torch_layout_##layout()
+
+} // namespace torch::aot_inductor
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/utils_cuda.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/utils_cuda.h
new file mode 100644
index 0000000000000000000000000000000000000000..d024c3ac411f166371d07ba3797081590fb1957a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/utils_cuda.h
@@ -0,0 +1,58 @@
+#pragma once
+
+#ifdef USE_CUDA
+// WARNING: Be careful when adding new includes here. This header will be used
+// in model.so, and should not refer to any aten/c10 headers except the stable
+// C ABI defined in torch/csrc/inductor/aoti_torch/c/shim.h. The same rule
+// applies to other files under torch/csrc/inductor/aoti_runtime/.
+#include 
+
+#include 
+#include 
+
+namespace torch::aot_inductor {
+
+inline void delete_cuda_guard(void* ptr) {
+  AOTI_TORCH_ERROR_CODE_CHECK(
+      aoti_torch_delete_cuda_guard(reinterpret_cast(ptr)));
+}
+
+inline void delete_cuda_stream_guard(void* ptr) {
+  AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_delete_cuda_stream_guard(
+      reinterpret_cast(ptr)));
+}
+
+class AOTICudaGuard {
+ public:
+  AOTICudaGuard(int32_t device_index) : guard_(nullptr, delete_cuda_guard) {
+    CUDAGuardHandle ptr = nullptr;
+    AOTI_TORCH_ERROR_CODE_CHECK(
+        aoti_torch_create_cuda_guard(device_index, &ptr));
+    guard_.reset(ptr);
+  }
+
+  void set_index(int32_t device_index) {
+    AOTI_TORCH_ERROR_CODE_CHECK(
+        aoti_torch_cuda_guard_set_index(guard_.get(), device_index));
+  }
+
+ private:
+  std::unique_ptr guard_;
+};
+
+class AOTICudaStreamGuard {
+ public:
+  AOTICudaStreamGuard(cudaStream_t stream, int32_t device_index)
+      : guard_(nullptr, delete_cuda_stream_guard) {
+    CUDAStreamGuardHandle ptr = nullptr;
+    AOTI_TORCH_ERROR_CODE_CHECK(
+        aoti_torch_create_cuda_stream_guard(stream, device_index, &ptr));
+    guard_.reset(ptr);
+  }
+
+ private:
+  std::unique_ptr guard_;
+};
+
+} // namespace torch::aot_inductor
+#endif // USE_CUDA
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim.h
new file mode 100644
index 0000000000000000000000000000000000000000..49b16504e6ce2e076f90c8010e78ca45d9ab070d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim.h
@@ -0,0 +1,686 @@
+#ifndef AOTI_TORCH_SHIM
+#define AOTI_TORCH_SHIM
+
+#include 
+#include 
+
+// This header defines a stable C API for certain ATen functionality in
+// libtorch. The AOTInductor compiled model.so will only refer to this header
+// instead of other headers from aten/c10, which means it will NOT be able to
+// directly use any data structures or call functions from libtorch.
+//
+// What problems are we trying to solve here?  Direct use of aten/c10 APIs
+// means use of C++ APIs on a library that doesn't have any ABI compatibility
+// guarantees.  However, we want model.so to remain usable across updates
+// to the PyTorch C++ libraries, which requires a stable ABI.  By introducing
+// a C shim layer, we can minimize the surface that will cause breakage. The
+// corresponding software stack can be illustrated as follows:
+//
+// |--------------------------------|
+// |     inference service code     |
+// |--------------------------------|
+// |           model.so             |
+// |--------------|-----------------|
+// |                        |
+// |          libtorch.so           |
+// |--------------------------------|
+//
+// The general guidelines for the C API:
+//
+//  - No exceptions, return an explicit error code to be checked at call site
+//  - Only pointers (AtenTensorHandle counts), integers and floats in headers
+//
+// If you want to make changes to this header, you MUST MAINTAIN ABI
+// compatibility.  Typically, this means you will have to add a _v2 version
+// of a function that you, e.g., want to add a new function parameter to, and
+// maintain the old and new versions of the APIs until all old model.so
+// go out of use.
+
+#ifdef __GNUC__
+#define AOTI_TORCH_EXPORT __attribute__((__visibility__("default")))
+#else // !__GNUC__
+#ifdef _WIN32
+// PyTorch2 doesn't currently work on Windows. Exporting these APIs can lead
+// to symbol clashes at link time if libtorch is included in a DLL and binary
+// that depends on the DLL. As a short term fix, we don't export the symbols.
+// In the long term, this will need to be addressed when Windows is supported.
+// #define AOTI_TORCH_EXPORT __declspec(dllexport)
+#define AOTI_TORCH_EXPORT
+#else // !_WIN32
+#define AOTI_TORCH_EXPORT
+#endif // _WIN32
+#endif // __GNUC__
+
+#include 
+#include 
+#include 
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// AtenTensorHandle represents an abstract notion of Tensor that can be passed
+// between model.so and libtorch.so.  The contents of the structure itself
+// are private; model.so is not allowed to access any fields directly, it must
+// go through functions defined in this ABI.  Under the hood, this is
+// represented as at::Tensor*, but we reserve the right to change this (and in
+// fact, we probably should change it to at::TensorImpl* at least).
+//
+// An AtenTensorHandle can be owning (please check the API reference for exact
+// ownership/borrow semantics).  If you have an owning AtenTensorHandle
+// in model.so, you are obligated to aoti_torch_delete_tensor_object when you
+// are done.  You can use the helper C++ class RAIIAtenTensorHandle
+// (see aot_runtime/model.h) to ensure the deallocator is called in RAII style
+// (note that RAIIAtenTensorHandle is private to model.so, and never crosses
+// the ABI boundary.)
+struct AtenTensorOpaque;
+using AtenTensorHandle = AtenTensorOpaque*;
+
+struct AtenGeneratorOpaque;
+using AtenGeneratorHandle = AtenGeneratorOpaque*;
+
+struct AOTIProxyExecutorOpaque;
+using AOTIProxyExecutorHandle = AOTIProxyExecutorOpaque*;
+
+using AOTITorchError = int32_t;
+#define AOTI_TORCH_SUCCESS 0
+#define AOTI_TORCH_FAILURE 1
+
+// Getter functions for retrieving various constants from the runtime, that
+// can subsequently be passed to other aoti_* functions.  By hiding these
+// behind functions, the precise value of device/dtype is NOT part of the
+// ABI contract.  (In practice, aten/c10 is pretty good about not renumbering
+// these, so we probably could later switch to having these in the ABI, if
+// desired for perf reasons.)
+AOTI_TORCH_EXPORT int32_t aoti_torch_device_type_cpu();
+AOTI_TORCH_EXPORT int32_t aoti_torch_device_type_cuda();
+
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float8_e5m2();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float8_e4m3fn();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float8_e5m2fnuz();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float8_e4m3fnuz();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_bfloat16();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float16();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float32();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float64();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_uint8();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_uint16();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_uint32();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_uint64();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_int8();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_int16();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_int32();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_int64();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_bool();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_complex32();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_complex64();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_complex128();
+
+AOTI_TORCH_EXPORT int32_t aoti_torch_layout_strided();
+AOTI_TORCH_EXPORT int32_t aoti_torch_layout__mkldnn();
+
+// Functions for converting a single-element tensor to a scalar value
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_item_float16(AtenTensorHandle tensor, c10::Half* ret_value);
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_item_float32(AtenTensorHandle tensor, float* ret_value);
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_item_float64(AtenTensorHandle tensor, double* ret_value);
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_item_uint8(AtenTensorHandle tensor, uint8_t* ret_value);
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_item_uint16(AtenTensorHandle tensor, uint16_t* ret_value);
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_item_uint32(AtenTensorHandle tensor, uint32_t* ret_value);
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_item_uint64(AtenTensorHandle tensor, uint64_t* ret_value);
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_item_int8(AtenTensorHandle tensor, int8_t* ret_value);
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_item_int16(AtenTensorHandle tensor, int16_t* ret_value);
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_item_int32(AtenTensorHandle tensor, int32_t* ret_value);
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_item_int64(AtenTensorHandle tensor, int64_t* ret_value);
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_item_bool(AtenTensorHandle tensor, bool* ret_value);
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_item_bfloat16(AtenTensorHandle tensor, c10::BFloat16* ret_value);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_item_complex64(
+    AtenTensorHandle tensor,
+    c10::complex* ret_value);
+
+// Functions for wrapping a scalar value to a single-element tensor
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_float32(
+    float value,
+    AtenTensorHandle* ret_new_tensor);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_float64(
+    double value,
+    AtenTensorHandle* ret_new_tensor);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_uint8(
+    uint8_t value,
+    AtenTensorHandle* ret_new_tensor);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_uint16(
+    uint16_t value,
+    AtenTensorHandle* ret_new_tensor);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_uint32(
+    uint32_t value,
+    AtenTensorHandle* ret_new_tensor);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_uint64(
+    uint64_t value,
+    AtenTensorHandle* ret_new_tensor);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_int8(
+    int8_t value,
+    AtenTensorHandle* ret_new_tensor);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_int16(
+    int16_t value,
+    AtenTensorHandle* ret_new_tensor);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_int32(
+    int32_t value,
+    AtenTensorHandle* ret_new_tensor);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_int64(
+    int64_t value,
+    AtenTensorHandle* ret_new_tensor);
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_scalar_to_tensor_bool(bool value, AtenTensorHandle* ret_new_tensor);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_complex64(
+    c10::complex value,
+    AtenTensorHandle* ret_new_tensor);
+
+AOTI_TORCH_EXPORT bool aoti_torch_grad_mode_is_enabled();
+AOTI_TORCH_EXPORT void aoti_torch_grad_mode_set_enabled(bool enabled);
+
+// Free the tensor object
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_delete_tensor_object(AtenTensorHandle tensor);
+
+// Get a pointer to the underlying storage data
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_get_data_ptr(
+    AtenTensorHandle tensor,
+    void** ret_data_ptr // returns borrowed reference
+);
+
+// Get the nbytes of the underlying storage
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_get_storage_size(AtenTensorHandle tensor, int64_t* ret_size);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_get_dim(AtenTensorHandle tensor, int64_t* ret_dim);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_get_numel(AtenTensorHandle tensor, int64_t* ret_numel);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_get_storage_numel(AtenTensorHandle tensor, int64_t* ret_numel);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_get_sizes(
+    AtenTensorHandle tensor,
+    int64_t** ret_sizes // returns borrowed reference
+);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_get_size(AtenTensorHandle tensor, int64_t d, int64_t* ret_size);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_get_strides(
+    AtenTensorHandle tensor,
+    int64_t** ret_strides // returns borrowed reference
+);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_get_stride(AtenTensorHandle tensor, int64_t d, int64_t* ret_stride);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_get_dtype(AtenTensorHandle tensor, int32_t* ret_dtype);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_get_device_type(AtenTensorHandle tensor, int32_t* ret_device_type);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_get_device_index(AtenTensorHandle tensor, int32_t* ret_device_index);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_get_storage_offset(
+    AtenTensorHandle tensor,
+    int64_t* ret_storage_offset);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch__alloc_from_pool(
+    AtenTensorHandle self,
+    int64_t offset_bytes,
+    int32_t dtype,
+    int64_t ndim,
+    const int64_t* sizes_ptr,
+    const int64_t* strides_ptr,
+    AtenTensorHandle* ret_new_tensor);
+
+// This function will create a new tensor object and its pointer is returned
+// through *out. The caller is responsible for wrapping the tensor pointer
+// with RAIIAtenTensorHandle which will call aoti_torch_delete_tensor_object
+// when going out of scope.
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch__reinterpret_tensor(
+    AtenTensorHandle self,
+    int64_t ndim,
+    const int64_t* sizes_ptr,
+    const int64_t* strides_ptr,
+    int64_t storage_offset,
+    AtenTensorHandle* ret_new_tensor // returns new reference
+);
+
+// This function will create a new tensor object and its pointer is returned
+// through *out. The caller is responsible for wrapping the tensor pointer
+// with RAIIAtenTensorHandle which will call aoti_torch_delete_tensor_object
+// when going out of scope.
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_empty_strided(
+    int64_t ndim,
+    const int64_t* sizes_ptr,
+    const int64_t* strides_ptr,
+    int32_t dtype,
+    int32_t device_type,
+    int32_t device_index,
+    AtenTensorHandle* ret_new_tensor // returns new reference
+);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_create_tensor_from_blob(
+    void* data,
+    int64_t ndim,
+    const int64_t* sizes_ptr,
+    const int64_t* strides_ptr,
+    int64_t storage_offset,
+    int32_t dtype,
+    int32_t device_type,
+    int32_t device_index,
+    AtenTensorHandle* ret // returns new reference
+);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_create_tensor_from_blob_v2(
+    void* data,
+    int64_t ndim,
+    const int64_t* sizes_ptr,
+    const int64_t* strides_ptr,
+    int64_t storage_offset,
+    int32_t dtype,
+    int32_t device_type,
+    int32_t device_index,
+    AtenTensorHandle* ret, // returns new reference
+    int32_t layout,
+    const uint8_t* opaque_metadata,
+    int64_t opaque_metadata_size);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch__embedding_bag(
+    AtenTensorHandle weight,
+    AtenTensorHandle indices,
+    AtenTensorHandle offsets,
+    int32_t scale_grad_by_freq,
+    int32_t mode,
+    int32_t sparse,
+    AtenTensorHandle per_sample_weights, // optional argument
+    int32_t include_last_offset,
+    int32_t padding_idx,
+    AtenTensorHandle* ret0, // returns new reference
+    AtenTensorHandle* ret1, // returns new reference
+    AtenTensorHandle* ret2, // returns new reference
+    AtenTensorHandle* ret3 // returns new reference
+);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch__fft_c2c(
+    AtenTensorHandle self,
+    const int64_t* dim_ptr,
+    int64_t dim_size,
+    int64_t normalization,
+    int32_t forward,
+    AtenTensorHandle* ret // returns new reference
+);
+
+// This version is deprecated. We will remove it later
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch__scaled_dot_product_flash_attention(
+    AtenTensorHandle query,
+    AtenTensorHandle key,
+    AtenTensorHandle value,
+    double dropout_p,
+    bool is_causal,
+    bool return_debug_mask,
+    double scale,
+    AtenTensorHandle* ret0, // returns new reference
+    AtenTensorHandle* ret1, // returns new reference
+    AtenTensorHandle* ret2, // returns new reference
+    AtenTensorHandle* ret3, // returns new reference
+    int64_t* ret4,
+    int64_t* ret5,
+    AtenTensorHandle* ret6, // returns new reference
+    AtenTensorHandle* ret7, // returns new reference
+    AtenTensorHandle* ret8 // returns new reference
+);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch__scaled_dot_product_flash_attention_v2(
+    AtenTensorHandle query,
+    AtenTensorHandle key,
+    AtenTensorHandle value,
+    double dropout_p,
+    int is_causal,
+    int return_debug_mask,
+    double* scale, // optional argument
+    AtenTensorHandle* ret0, // returns new reference
+    AtenTensorHandle* ret1, // returns new reference
+    AtenTensorHandle* ret2, // returns new reference
+    AtenTensorHandle* ret3, // returns new reference
+    int64_t* ret4,
+    int64_t* ret5,
+    AtenTensorHandle* ret6, // returns new reference
+    AtenTensorHandle* ret7, // returns new reference
+    AtenTensorHandle* ret8 // returns new reference
+);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch__scaled_dot_product_efficient_attention(
+    AtenTensorHandle query,
+    AtenTensorHandle key,
+    AtenTensorHandle value,
+    AtenTensorHandle attn_bias, // optional argument
+    int compute_log_sumexp,
+    double dropout_p,
+    int is_causal,
+    double* scale, // optional argument
+    AtenTensorHandle* ret0, // returns new reference
+    AtenTensorHandle* ret1, // returns new reference
+    AtenTensorHandle* ret2, // returns new reference
+    AtenTensorHandle* ret3 // returns new reference
+);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch__scaled_mm(
+    AtenTensorHandle self,
+    AtenTensorHandle mat2,
+    AtenTensorHandle bias,
+    int32_t* out_dtype,
+    AtenTensorHandle scale_a,
+    AtenTensorHandle scale_b,
+    AtenTensorHandle scale_result,
+    int8_t use_fast_accum,
+    AtenTensorHandle* ret0,
+    AtenTensorHandle* ret1);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch__scaled_mm_v2(
+    AtenTensorHandle self,
+    AtenTensorHandle mat2,
+    AtenTensorHandle scale_a,
+    AtenTensorHandle scale_b,
+    AtenTensorHandle bias,
+    AtenTensorHandle scale_result,
+    int32_t* out_dtype,
+    int8_t use_fast_accum,
+    AtenTensorHandle* ret0);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_convolution(
+    AtenTensorHandle input,
+    AtenTensorHandle weight,
+    AtenTensorHandle bias, // optional argument
+    const int64_t* stride_ptr,
+    int64_t stride_size,
+    const int64_t* padding_ptr,
+    int64_t padding_size,
+    const int64_t* dilation_ptr,
+    int64_t dilation_size,
+    int transposed,
+    const int64_t* output_padding_ptr,
+    int64_t output_padding_size,
+    int64_t groups,
+    AtenTensorHandle* ret // returns new reference
+);
+
+// This function will create a new uninitialized tensor object
+// and its pointer is returned through *ret.
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_new_uninitialized_tensor(AtenTensorHandle* ret);
+
+// WARNING: This will be deprecated. Use aoti_torch_copy_ instead.
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_tensor_copy_(AtenTensorHandle src, AtenTensorHandle dst);
+
+// Make the tensor referred to by dst an alias for the tensor referred
+// to by src. The two tensors must still be deleted with
+// aoti_torch_delete_tensor separately (or not) as before the call.
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_assign_tensors(AtenTensorHandle src, AtenTensorHandle dst);
+
+// Make a shallow copy of the tensor referred to by src and assign
+// it to the handle in the ret_dst. This is similar to the above
+// aoti_torch_assign_tensors function, but creates and sets the
+// ret_dst from within.
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_assign_tensors_out(AtenTensorHandle src, AtenTensorHandle* ret_dst);
+
+// This function will create a new tensor object and its pointer is returned
+// through *ret. The caller is responsible for wrapping the tensor pointer
+// with RAIIAtenTensorHandle which will call aoti_torch_delete_tensor_object
+// when going out of scope.
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_clone(AtenTensorHandle self, AtenTensorHandle* ret);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_addmm_out(
+    AtenTensorHandle out,
+    AtenTensorHandle self,
+    AtenTensorHandle mat1,
+    AtenTensorHandle mat2,
+    float beta,
+    float alpha);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_bmm_out(
+    AtenTensorHandle out,
+    AtenTensorHandle self,
+    AtenTensorHandle mat2);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_copy_(
+    AtenTensorHandle self,
+    AtenTensorHandle src,
+    int32_t non_blocking);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mm_out(
+    AtenTensorHandle out,
+    AtenTensorHandle self,
+    AtenTensorHandle mat2);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch__mm_plus_mm_out(
+    AtenTensorHandle out,
+    AtenTensorHandle a,
+    AtenTensorHandle b,
+    AtenTensorHandle c,
+    AtenTensorHandle d);
+
+// This will soon be deprecated after ao_quantization is complete.
+// Please refrain from using this or increasing callsites.
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_cpu_wrapped_fbgemm_pack_gemm_matrix_fp16(
+    AtenTensorHandle weight,
+    AtenTensorHandle* out);
+
+// This will soon be deprecated after ao_quantization is complete.
+// Please refrain from using this or increasing callsites.
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__wrapped_linear_prepack(
+    AtenTensorHandle weight,
+    AtenTensorHandle weight_scale,
+    AtenTensorHandle weight_zero_point,
+    AtenTensorHandle bias,
+    AtenTensorHandle* out);
+
+// This will soon be deprecated after ao_quantization is complete.
+// Please refrain from using this or increasing callsites.
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_cpu_wrapped_fbgemm_linear_fp16_weight(
+    AtenTensorHandle input,
+    AtenTensorHandle weight,
+    AtenTensorHandle bias,
+    int64_t out_channel,
+    AtenTensorHandle* out);
+
+// This will soon be deprecated after ao_quantization is complete.
+// Please refrain from using this or increasing callsites.
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_cpu__wrapped_quantized_linear_prepacked(
+    AtenTensorHandle input,
+    AtenTensorHandle input_scale,
+    AtenTensorHandle input_zero_point,
+    AtenTensorHandle weight,
+    AtenTensorHandle out_scale,
+    AtenTensorHandle out_zeropoint,
+    int64_t out_channel,
+    AtenTensorHandle* out);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_nonzero(AtenTensorHandle self, AtenTensorHandle* out);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_repeat_interleave_Tensor(
+    AtenTensorHandle repeats,
+    int64_t* output_size,
+    AtenTensorHandle* out);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_check_inf_and_nan(const char* tensor_name, AtenTensorHandle tensor);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scatter_out(
+    AtenTensorHandle out,
+    AtenTensorHandle self,
+    int64_t dim,
+    AtenTensorHandle index,
+    AtenTensorHandle src);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scatter_reduce_out(
+    AtenTensorHandle out,
+    AtenTensorHandle self,
+    int64_t dim,
+    AtenTensorHandle index,
+    AtenTensorHandle src,
+    const char* reduce,
+    int32_t include_self);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_index_put_out(
+    AtenTensorHandle out,
+    AtenTensorHandle self,
+    const AtenTensorHandle* indices,
+    const uint32_t num_indices,
+    const AtenTensorHandle values,
+    bool accumulate);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_view_as_real(
+    AtenTensorHandle self,
+    AtenTensorHandle* ret // returns new reference
+);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_view_dtype(
+    AtenTensorHandle self,
+    int32_t dtype,
+    AtenTensorHandle* ret // returns new reference
+);
+
+AOTI_TORCH_EXPORT void aoti_torch_print_tensor_handle(
+    AtenTensorHandle self,
+    const char* msg);
+
+// When AOTI debug printer option is enabled, this function will be invoked to
+// torch pickle save the intermediate tensor for debugging purpose.
+AOTI_TORCH_EXPORT void aoti_torch_save_tensor_handle(
+    AtenTensorHandle self,
+    const char* tensor_name,
+    const char* launch_prefix,
+    const char* kernel_name);
+
+#ifdef USE_CUDA
+
+struct CUDAGuardOpaque;
+using CUDAGuardHandle = CUDAGuardOpaque*;
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_create_cuda_guard(
+    int32_t device_index,
+    CUDAGuardHandle* ret_guard // returns new reference
+);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_delete_cuda_guard(CUDAGuardHandle guard);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_cuda_guard_set_index(CUDAGuardHandle guard, int32_t device_index);
+
+struct CUDAStreamGuardOpaque;
+using CUDAStreamGuardHandle = CUDAStreamGuardOpaque*;
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_create_cuda_stream_guard(
+    void* stream,
+    int32_t device_index,
+    CUDAStreamGuardHandle* ret_guard // returns new reference
+);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_delete_cuda_stream_guard(CUDAStreamGuardHandle guard);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_get_current_cuda_stream(int32_t device_index, void** ret_stream);
+
+#endif
+
+// See `ProxyExecutor Design Note` in ir.py for more details
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_proxy_executor_call_function(
+    AOTIProxyExecutorHandle proxy_executor,
+    int extern_node_index,
+    int num_ints,
+    int64_t* flatten_int_args,
+    int num_tensors,
+    AtenTensorHandle* flatten_tensor_args);
+
+AOTI_TORCH_EXPORT void aoti_torch_check(
+    bool cond,
+    const char* func,
+    const char* file,
+    uint32_t line,
+    const char* msg);
+
+#ifdef STRIP_ERROR_MESSAGES
+#define AOTI_TORCH_CHECK(cond, ...)              \
+  if (!(cond)) {                                 \
+    aoti_torch_check(                            \
+        false,                                   \
+        __func__,                                \
+        __FILE__,                                \
+        static_cast(__LINE__),         \
+        TORCH_CHECK_MSG(cond, "", __VA_ARGS__)); \
+  }
+#else
+#define AOTI_TORCH_CHECK(cond, ...)                \
+  if (!(cond)) {                                   \
+    aoti_torch_check(                              \
+        false,                                     \
+        __func__,                                  \
+        __FILE__,                                  \
+        static_cast(__LINE__),           \
+        TORCH_CHECK_MSG(cond, "", ##__VA_ARGS__)); \
+  }
+#endif
+
+#ifdef __cplusplus
+} // extern "C"
+
+template 
+int32_t aoti_torch_dtype() = delete;
+
+#define DEFINE_DTYPE_SPECIALIZATION(ctype, typename) \
+  template <>                                        \
+  inline int32_t aoti_torch_dtype() {         \
+    return aoti_torch_dtype_##typename();            \
+  }
+
+namespace c10 {
+struct BFloat16;
+struct Half;
+} // namespace c10
+
+DEFINE_DTYPE_SPECIALIZATION(c10::BFloat16, bfloat16)
+DEFINE_DTYPE_SPECIALIZATION(c10::Half, float16)
+DEFINE_DTYPE_SPECIALIZATION(c10::complex, complex64)
+DEFINE_DTYPE_SPECIALIZATION(float, float32)
+DEFINE_DTYPE_SPECIALIZATION(double, float64)
+DEFINE_DTYPE_SPECIALIZATION(uint8_t, uint8)
+DEFINE_DTYPE_SPECIALIZATION(int8_t, int8)
+DEFINE_DTYPE_SPECIALIZATION(int16_t, int16)
+DEFINE_DTYPE_SPECIALIZATION(int32_t, int32)
+DEFINE_DTYPE_SPECIALIZATION(int64_t, int64)
+DEFINE_DTYPE_SPECIALIZATION(bool, bool)
+
+#endif
+
+#endif // AOTI_TORCH_SHIM
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_cpu.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_cpu.h
new file mode 100644
index 0000000000000000000000000000000000000000..52576b28b6b94bb5934345730c91333e792cca7d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_cpu.h
@@ -0,0 +1,137 @@
+
+
+// WARNING: THIS FILE IS AUTOGENERATED BY torchgen. DO NOT MODIFY BY HAND.
+// See https://github.com/pytorch/pytorch/blob/7e86a7c0155295539996e0cf422883571126073e/torchgen/gen.py#L2424-L2436 for details
+
+#pragma once
+
+#include 
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__adaptive_avg_pool2d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__adaptive_avg_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__adaptive_avg_pool3d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__adaptive_avg_pool3d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__addmm_activation(AtenTensorHandle self, AtenTensorHandle mat1, AtenTensorHandle mat2, double beta, double alpha, int32_t use_gelu, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__cdist_backward(AtenTensorHandle grad, AtenTensorHandle x1, AtenTensorHandle x2, double p, AtenTensorHandle cdist, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__cdist_forward(AtenTensorHandle x1, AtenTensorHandle x2, double p, int64_t* compute_mode, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__efficientzerotensor(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__embedding_bag(AtenTensorHandle weight, AtenTensorHandle indices, AtenTensorHandle offsets, int32_t scale_grad_by_freq, int64_t mode, int32_t sparse, AtenTensorHandle* per_sample_weights, int32_t include_last_offset, int64_t padding_idx, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__embedding_bag_dense_backward(AtenTensorHandle grad, AtenTensorHandle indices, AtenTensorHandle offset2bag, AtenTensorHandle bag_size, AtenTensorHandle maximum_indices, int64_t num_weights, int32_t scale_grad_by_freq, int64_t mode, AtenTensorHandle* per_sample_weights, int64_t padding_idx, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__embedding_bag_forward_only(AtenTensorHandle weight, AtenTensorHandle indices, AtenTensorHandle offsets, int32_t scale_grad_by_freq, int64_t mode, int32_t sparse, AtenTensorHandle* per_sample_weights, int32_t include_last_offset, int64_t padding_idx, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__embedding_bag_per_sample_weights_backward(AtenTensorHandle grad, AtenTensorHandle weight, AtenTensorHandle indices, AtenTensorHandle offsets, AtenTensorHandle offset2bag, int64_t mode, int64_t padding_idx, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__fft_c2c(AtenTensorHandle self, const int64_t* dim, int64_t dim_len_, int64_t normalization, int32_t forward, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__fft_r2c(AtenTensorHandle self, const int64_t* dim, int64_t dim_len_, int64_t normalization, int32_t onesided, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__fused_moving_avg_obs_fq_helper(AtenTensorHandle self, AtenTensorHandle observer_on, AtenTensorHandle fake_quant_on, AtenTensorHandle running_min, AtenTensorHandle running_max, AtenTensorHandle scale, AtenTensorHandle zero_point, double averaging_const, int64_t quant_min, int64_t quant_max, int64_t ch_axis, int32_t per_row_fake_quant, int32_t symmetric_quant, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__fused_moving_avg_obs_fq_helper_functional(AtenTensorHandle self, AtenTensorHandle observer_on, AtenTensorHandle fake_quant_on, AtenTensorHandle running_min, AtenTensorHandle running_max, AtenTensorHandle scale, AtenTensorHandle zero_point, double averaging_const, int64_t quant_min, int64_t quant_max, int64_t ch_axis, int32_t per_row_fake_quant, int32_t symmetric_quant, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, AtenTensorHandle* ret4, AtenTensorHandle* ret5);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__histogramdd_from_bin_cts(AtenTensorHandle self, const int64_t* bins, int64_t bins_len_, const double** range, int64_t range_len_, AtenTensorHandle* weight, int32_t density, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__pdist_backward(AtenTensorHandle grad, AtenTensorHandle self, double p, AtenTensorHandle pdist, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__pdist_forward(AtenTensorHandle self, double p, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__scaled_dot_product_flash_attention_for_cpu(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, double dropout_p, int32_t is_causal, AtenTensorHandle* attn_mask, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__scaled_dot_product_flash_attention_for_cpu_backward(AtenTensorHandle grad_out, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle out, AtenTensorHandle logsumexp, double dropout_p, int32_t is_causal, AtenTensorHandle* attn_mask, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__segment_reduce_backward(AtenTensorHandle grad, AtenTensorHandle output, AtenTensorHandle data, const char* reduce, AtenTensorHandle* lengths, AtenTensorHandle* offsets, int64_t axis, double* initial, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__to_sparse(AtenTensorHandle self, int32_t* layout, const int64_t** blocksize, int64_t blocksize_len_, int64_t* dense_dim, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__trilinear(AtenTensorHandle i1, AtenTensorHandle i2, AtenTensorHandle i3, const int64_t* expand1, int64_t expand1_len_, const int64_t* expand2, int64_t expand2_len_, const int64_t* expand3, int64_t expand3_len_, const int64_t* sumdim, int64_t sumdim_len_, int64_t unroll_dim, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_adaptive_max_pool2d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_adaptive_max_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle indices, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_adaptive_max_pool3d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_adaptive_max_pool3d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle indices, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_addbmm(AtenTensorHandle self, AtenTensorHandle batch1, AtenTensorHandle batch2, double beta, double alpha, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_addmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat1, AtenTensorHandle mat2, double beta, double alpha);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_addmv(AtenTensorHandle self, AtenTensorHandle mat, AtenTensorHandle vec, double beta, double alpha, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_angle(AtenTensorHandle self, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_avg_pool2d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_avg_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_avg_pool3d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_avg_pool3d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_bernoulli__Tensor(AtenTensorHandle self, AtenTensorHandle p, AtenGeneratorHandle* generator);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_bernoulli__float(AtenTensorHandle self, double p, AtenGeneratorHandle* generator);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_bmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_bucketize_Tensor(AtenTensorHandle self, AtenTensorHandle boundaries, int32_t out_int32, int32_t right, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_cat(const AtenTensorHandle* tensors, int64_t tensors_len_, int64_t dim, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_cholesky_inverse(AtenTensorHandle self, int32_t upper, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_cholesky_solve(AtenTensorHandle self, AtenTensorHandle input2, int32_t upper, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_convolution(AtenTensorHandle input, AtenTensorHandle weight, AtenTensorHandle* bias, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t transposed, const int64_t* output_padding, int64_t output_padding_len_, int64_t groups, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_convolution_backward(AtenTensorHandle grad_output, AtenTensorHandle input, AtenTensorHandle weight, const int64_t** bias_sizes, int64_t bias_sizes_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t transposed, const int64_t* output_padding, int64_t output_padding_len_, int64_t groups, const int32_t* output_mask, int64_t output_mask_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_cummax(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_cummin(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_cumprod(AtenTensorHandle self, int64_t dim, int32_t* dtype, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_cumsum(AtenTensorHandle self, int64_t dim, int32_t* dtype, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_exponential(AtenTensorHandle self, double lambd, AtenGeneratorHandle* generator, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_fractional_max_pool2d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle random_samples, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_fractional_max_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle indices, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_fractional_max_pool3d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle random_samples, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_fractional_max_pool3d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle indices, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_gcd(AtenTensorHandle self, AtenTensorHandle other, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_geqrf(AtenTensorHandle self, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_grid_sampler_2d_backward(AtenTensorHandle grad_output, AtenTensorHandle input, AtenTensorHandle grid, int64_t interpolation_mode, int64_t padding_mode, int32_t align_corners, const int32_t* output_mask, int64_t output_mask_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_histc(AtenTensorHandle self, int64_t bins, double min, double max, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_histogram_bin_ct(AtenTensorHandle self, int64_t bins, const double** range, int64_t range_len_, AtenTensorHandle* weight, int32_t density, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_index_Tensor(AtenTensorHandle self, const AtenTensorHandle** indices, int64_t indices_len_, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_index_put(AtenTensorHandle self, const AtenTensorHandle** indices, int64_t indices_len_, AtenTensorHandle values, int32_t accumulate, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_index_reduce(AtenTensorHandle self, int64_t dim, AtenTensorHandle index, AtenTensorHandle source, const char* reduce, int32_t include_self, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_kthvalue(AtenTensorHandle self, int64_t k, int64_t dim, int32_t keepdim, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_logcumsumexp(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_lu_unpack(AtenTensorHandle LU_data, AtenTensorHandle LU_pivots, int32_t unpack_data, int32_t unpack_pivots, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_masked_scatter(AtenTensorHandle self, AtenTensorHandle mask, AtenTensorHandle source, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_masked_scatter_backward(AtenTensorHandle grad_output, AtenTensorHandle mask, const int64_t* sizes, int64_t sizes_len_, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_max_pool2d_with_indices(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_max_pool2d_with_indices_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle indices, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_max_pool3d_with_indices(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_max_pool3d_with_indices_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle indices, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_max_unpool2d(AtenTensorHandle self, AtenTensorHandle indices, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_max_unpool3d(AtenTensorHandle self, AtenTensorHandle indices, const int64_t* output_size, int64_t output_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_median(AtenTensorHandle self, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_mm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_mode(AtenTensorHandle self, int64_t dim, int32_t keepdim, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_mul_Scalar(AtenTensorHandle self, double other, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_mul_Tensor(AtenTensorHandle self, AtenTensorHandle other, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_nanmedian(AtenTensorHandle self, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_native_dropout(AtenTensorHandle input, double p, int32_t* train, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_nonzero(AtenTensorHandle self, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_normal_functional(AtenTensorHandle self, double mean, double std, AtenGeneratorHandle* generator, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_ormqr(AtenTensorHandle self, AtenTensorHandle input2, AtenTensorHandle input3, int32_t left, int32_t transpose, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_polar(AtenTensorHandle abs, AtenTensorHandle angle, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_pow_Scalar(double self, AtenTensorHandle exponent, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_pow_Tensor_Scalar(AtenTensorHandle self, double exponent, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_pow_Tensor_Tensor(AtenTensorHandle self, AtenTensorHandle exponent, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_rand(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_rand_generator(const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_randint(int64_t high, const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_randint_generator(int64_t high, const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_randint_low(int64_t low, int64_t high, const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_randint_low_out(AtenTensorHandle out, int64_t low, int64_t high, const int64_t* size, int64_t size_len_);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_randn(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_randn_generator(const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_randperm(int64_t n, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_repeat_interleave_Tensor(AtenTensorHandle repeats, int64_t* output_size, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_replication_pad1d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* padding, int64_t padding_len_, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_replication_pad2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* padding, int64_t padding_len_, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_reshape(AtenTensorHandle self, const int64_t* shape, int64_t shape_len_, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_resize_(AtenTensorHandle self, const int64_t* size, int64_t size_len_, int32_t* memory_format);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_resize_as_(AtenTensorHandle self, AtenTensorHandle the_template, int32_t* memory_format);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_scatter_src_out(AtenTensorHandle out, AtenTensorHandle self, int64_t dim, AtenTensorHandle index, AtenTensorHandle src);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_scatter_value_out(AtenTensorHandle out, AtenTensorHandle self, int64_t dim, AtenTensorHandle index, double value);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_scatter_reduce_two_out(AtenTensorHandle out, AtenTensorHandle self, int64_t dim, AtenTensorHandle index, AtenTensorHandle src, const char* reduce, int32_t include_self);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_segment_reduce(AtenTensorHandle data, const char* reduce, AtenTensorHandle* lengths, AtenTensorHandle* indices, AtenTensorHandle* offsets, int64_t axis, int32_t unsafe, double* initial, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_slice_Tensor(AtenTensorHandle self, int64_t dim, int64_t* start, int64_t* end, int64_t step, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_soft_margin_loss_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle target, int64_t reduction, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_sort(AtenTensorHandle self, int64_t dim, int32_t descending, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_sort_stable(AtenTensorHandle self, int32_t* stable, int64_t dim, int32_t descending, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_to_sparse(AtenTensorHandle self, int32_t* layout, const int64_t** blocksize, int64_t blocksize_len_, int64_t* dense_dim, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_topk(AtenTensorHandle self, int64_t k, int64_t dim, int32_t largest, int32_t sorted, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_triangular_solve(AtenTensorHandle self, AtenTensorHandle A, int32_t upper, int32_t transpose, int32_t unitriangular, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_uniform(AtenTensorHandle self, double from, double to, AtenGeneratorHandle* generator, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_upsample_bicubic2d_backward(AtenTensorHandle grad_output, const int64_t* output_size, int64_t output_size_len_, const int64_t* input_size, int64_t input_size_len_, int32_t align_corners, double* scales_h, double* scales_w, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_upsample_linear1d_backward(AtenTensorHandle grad_output, const int64_t* output_size, int64_t output_size_len_, const int64_t* input_size, int64_t input_size_len_, int32_t align_corners, double* scales, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_upsample_trilinear3d_backward(AtenTensorHandle grad_output, const int64_t* output_size, int64_t output_size_len_, const int64_t* input_size, int64_t input_size_len_, int32_t align_corners, double* scales_d, double* scales_h, double* scales_w, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_view_dtype(AtenTensorHandle self, int32_t dtype, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_view_as_complex(AtenTensorHandle self, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_view_as_real(AtenTensorHandle self, AtenTensorHandle* ret0);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_cuda.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_cuda.h
new file mode 100644
index 0000000000000000000000000000000000000000..a7c728bf7bc511d336cdff85752ba9f6a23691c5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_cuda.h
@@ -0,0 +1,146 @@
+
+
+// WARNING: THIS FILE IS AUTOGENERATED BY torchgen. DO NOT MODIFY BY HAND.
+// See https://github.com/pytorch/pytorch/blob/7e86a7c0155295539996e0cf422883571126073e/torchgen/gen.py#L2424-L2436 for details
+
+#pragma once
+
+#include 
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__adaptive_avg_pool2d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__adaptive_avg_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__adaptive_avg_pool3d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__adaptive_avg_pool3d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__addmm_activation(AtenTensorHandle self, AtenTensorHandle mat1, AtenTensorHandle mat2, double beta, double alpha, int32_t use_gelu, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__cdist_backward(AtenTensorHandle grad, AtenTensorHandle x1, AtenTensorHandle x2, double p, AtenTensorHandle cdist, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__cdist_forward(AtenTensorHandle x1, AtenTensorHandle x2, double p, int64_t* compute_mode, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__cudnn_rnn(AtenTensorHandle input, const AtenTensorHandle* weight, int64_t weight_len_, int64_t weight_stride0, AtenTensorHandle* weight_buf, AtenTensorHandle hx, AtenTensorHandle* cx, int64_t mode, int64_t hidden_size, int64_t proj_size, int64_t num_layers, int32_t batch_first, double dropout, int32_t train, int32_t bidirectional, const int64_t* batch_sizes, int64_t batch_sizes_len_, AtenTensorHandle* dropout_state, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, AtenTensorHandle* ret4);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__efficient_attention_backward(AtenTensorHandle grad_out_, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle* bias, AtenTensorHandle out, AtenTensorHandle* cu_seqlens_q, AtenTensorHandle* cu_seqlens_k, int64_t max_seqlen_q, int64_t max_seqlen_k, AtenTensorHandle logsumexp, double dropout_p, AtenTensorHandle philox_seed, AtenTensorHandle philox_offset, int64_t custom_mask_type, int32_t bias_requires_grad, double* scale, int64_t* num_splits_key, int64_t* window_size, int32_t shared_storage_dqdkdv, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__efficient_attention_forward(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle* bias, AtenTensorHandle* cu_seqlens_q, AtenTensorHandle* cu_seqlens_k, int64_t* max_seqlen_q, int64_t* max_seqlen_k, double dropout_p, int64_t custom_mask_type, int32_t compute_log_sumexp, double* scale, AtenTensorHandle* seqlen_k, int64_t* window_size, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, int64_t* ret4, int64_t* ret5);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__efficientzerotensor(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__embedding_bag(AtenTensorHandle weight, AtenTensorHandle indices, AtenTensorHandle offsets, int32_t scale_grad_by_freq, int64_t mode, int32_t sparse, AtenTensorHandle* per_sample_weights, int32_t include_last_offset, int64_t padding_idx, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__embedding_bag_dense_backward(AtenTensorHandle grad, AtenTensorHandle indices, AtenTensorHandle offset2bag, AtenTensorHandle bag_size, AtenTensorHandle maximum_indices, int64_t num_weights, int32_t scale_grad_by_freq, int64_t mode, AtenTensorHandle* per_sample_weights, int64_t padding_idx, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__embedding_bag_forward_only(AtenTensorHandle weight, AtenTensorHandle indices, AtenTensorHandle offsets, int32_t scale_grad_by_freq, int64_t mode, int32_t sparse, AtenTensorHandle* per_sample_weights, int32_t include_last_offset, int64_t padding_idx, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__embedding_bag_per_sample_weights_backward(AtenTensorHandle grad, AtenTensorHandle weight, AtenTensorHandle indices, AtenTensorHandle offsets, AtenTensorHandle offset2bag, int64_t mode, int64_t padding_idx, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__fft_c2c(AtenTensorHandle self, const int64_t* dim, int64_t dim_len_, int64_t normalization, int32_t forward, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__fft_r2c(AtenTensorHandle self, const int64_t* dim, int64_t dim_len_, int64_t normalization, int32_t onesided, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__flash_attention_backward(AtenTensorHandle grad_out, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle out, AtenTensorHandle logsumexp, AtenTensorHandle cum_seq_q, AtenTensorHandle cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, int32_t is_causal, AtenTensorHandle philox_seed, AtenTensorHandle philox_offset, double* scale, int64_t* window_size_left, int64_t* window_size_right, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__flash_attention_forward(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle* cum_seq_q, AtenTensorHandle* cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, int32_t is_causal, int32_t return_debug_mask, double* scale, int64_t* window_size_left, int64_t* window_size_right, AtenTensorHandle* seqused_k, AtenTensorHandle* alibi_slopes, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, AtenTensorHandle* ret4);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__fused_moving_avg_obs_fq_helper(AtenTensorHandle self, AtenTensorHandle observer_on, AtenTensorHandle fake_quant_on, AtenTensorHandle running_min, AtenTensorHandle running_max, AtenTensorHandle scale, AtenTensorHandle zero_point, double averaging_const, int64_t quant_min, int64_t quant_max, int64_t ch_axis, int32_t per_row_fake_quant, int32_t symmetric_quant, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__fused_moving_avg_obs_fq_helper_functional(AtenTensorHandle self, AtenTensorHandle observer_on, AtenTensorHandle fake_quant_on, AtenTensorHandle running_min, AtenTensorHandle running_max, AtenTensorHandle scale, AtenTensorHandle zero_point, double averaging_const, int64_t quant_min, int64_t quant_max, int64_t ch_axis, int32_t per_row_fake_quant, int32_t symmetric_quant, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, AtenTensorHandle* ret4, AtenTensorHandle* ret5);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__pdist_backward(AtenTensorHandle grad, AtenTensorHandle self, double p, AtenTensorHandle pdist, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__pdist_forward(AtenTensorHandle self, double p, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_dot_product_cudnn_attention(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle* attn_bias, int32_t compute_log_sumexp, double dropout_p, int32_t is_causal, int32_t return_debug_mask, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, int64_t* ret4, int64_t* ret5, AtenTensorHandle* ret6, AtenTensorHandle* ret7, AtenTensorHandle* ret8);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_dot_product_cudnn_attention_backward(AtenTensorHandle grad_out, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle out, AtenTensorHandle logsumexp, AtenTensorHandle philox_seed, AtenTensorHandle philox_offset, AtenTensorHandle attn_bias, AtenTensorHandle cum_seq_q, AtenTensorHandle cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, int32_t is_causal, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_dot_product_efficient_attention(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle* attn_bias, int32_t compute_log_sumexp, double dropout_p, int32_t is_causal, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_dot_product_efficient_attention_backward(AtenTensorHandle grad_out_, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle attn_bias, AtenTensorHandle out, AtenTensorHandle logsumexp, AtenTensorHandle philox_seed, AtenTensorHandle philox_offset, double dropout_p, const int32_t* grad_input_mask, int64_t grad_input_mask_len_, int32_t is_causal, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_dot_product_flash_attention(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, double dropout_p, int32_t is_causal, int32_t return_debug_mask, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, int64_t* ret4, int64_t* ret5, AtenTensorHandle* ret6, AtenTensorHandle* ret7, AtenTensorHandle* ret8);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_dot_product_flash_attention_backward(AtenTensorHandle grad_out, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle out, AtenTensorHandle logsumexp, AtenTensorHandle cum_seq_q, AtenTensorHandle cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, int32_t is_causal, AtenTensorHandle philox_seed, AtenTensorHandle philox_offset, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_mm(AtenTensorHandle self, AtenTensorHandle mat2, AtenTensorHandle scale_a, AtenTensorHandle scale_b, AtenTensorHandle* bias, AtenTensorHandle* scale_result, int32_t* out_dtype, int32_t use_fast_accum, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__segment_reduce_backward(AtenTensorHandle grad, AtenTensorHandle output, AtenTensorHandle data, const char* reduce, AtenTensorHandle* lengths, AtenTensorHandle* offsets, int64_t axis, double* initial, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__thnn_fused_lstm_cell(AtenTensorHandle input_gates, AtenTensorHandle hidden_gates, AtenTensorHandle cx, AtenTensorHandle* input_bias, AtenTensorHandle* hidden_bias, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__to_sparse(AtenTensorHandle self, int32_t* layout, const int64_t** blocksize, int64_t blocksize_len_, int64_t* dense_dim, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__trilinear(AtenTensorHandle i1, AtenTensorHandle i2, AtenTensorHandle i3, const int64_t* expand1, int64_t expand1_len_, const int64_t* expand2, int64_t expand2_len_, const int64_t* expand3, int64_t expand3_len_, const int64_t* sumdim, int64_t sumdim_len_, int64_t unroll_dim, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_adaptive_max_pool2d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_adaptive_max_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle indices, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_adaptive_max_pool3d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_adaptive_max_pool3d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle indices, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_addbmm(AtenTensorHandle self, AtenTensorHandle batch1, AtenTensorHandle batch2, double beta, double alpha, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_addmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat1, AtenTensorHandle mat2, double beta, double alpha);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_addmv(AtenTensorHandle self, AtenTensorHandle mat, AtenTensorHandle vec, double beta, double alpha, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_angle(AtenTensorHandle self, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_avg_pool2d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_avg_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_avg_pool3d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_avg_pool3d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_bernoulli__Tensor(AtenTensorHandle self, AtenTensorHandle p, AtenGeneratorHandle* generator);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_bernoulli__float(AtenTensorHandle self, double p, AtenGeneratorHandle* generator);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_bmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_bucketize_Tensor(AtenTensorHandle self, AtenTensorHandle boundaries, int32_t out_int32, int32_t right, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_cat(const AtenTensorHandle* tensors, int64_t tensors_len_, int64_t dim, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_cholesky_inverse(AtenTensorHandle self, int32_t upper, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_cholesky_solve(AtenTensorHandle self, AtenTensorHandle input2, int32_t upper, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_convolution(AtenTensorHandle input, AtenTensorHandle weight, AtenTensorHandle* bias, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t transposed, const int64_t* output_padding, int64_t output_padding_len_, int64_t groups, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_convolution_backward(AtenTensorHandle grad_output, AtenTensorHandle input, AtenTensorHandle weight, const int64_t** bias_sizes, int64_t bias_sizes_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t transposed, const int64_t* output_padding, int64_t output_padding_len_, int64_t groups, const int32_t* output_mask, int64_t output_mask_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_cummax(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_cummin(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_cumprod(AtenTensorHandle self, int64_t dim, int32_t* dtype, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_cumsum(AtenTensorHandle self, int64_t dim, int32_t* dtype, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_exponential(AtenTensorHandle self, double lambd, AtenGeneratorHandle* generator, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_fractional_max_pool2d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle random_samples, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_fractional_max_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle indices, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_fractional_max_pool3d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle random_samples, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_fractional_max_pool3d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle indices, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_gcd(AtenTensorHandle self, AtenTensorHandle other, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_geqrf(AtenTensorHandle self, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_grid_sampler_2d_backward(AtenTensorHandle grad_output, AtenTensorHandle input, AtenTensorHandle grid, int64_t interpolation_mode, int64_t padding_mode, int32_t align_corners, const int32_t* output_mask, int64_t output_mask_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_histc(AtenTensorHandle self, int64_t bins, double min, double max, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_index_Tensor(AtenTensorHandle self, const AtenTensorHandle** indices, int64_t indices_len_, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_index_put(AtenTensorHandle self, const AtenTensorHandle** indices, int64_t indices_len_, AtenTensorHandle values, int32_t accumulate, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_index_reduce(AtenTensorHandle self, int64_t dim, AtenTensorHandle index, AtenTensorHandle source, const char* reduce, int32_t include_self, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_kthvalue(AtenTensorHandle self, int64_t k, int64_t dim, int32_t keepdim, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_logcumsumexp(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_lu_unpack(AtenTensorHandle LU_data, AtenTensorHandle LU_pivots, int32_t unpack_data, int32_t unpack_pivots, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_masked_scatter(AtenTensorHandle self, AtenTensorHandle mask, AtenTensorHandle source, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_masked_scatter_backward(AtenTensorHandle grad_output, AtenTensorHandle mask, const int64_t* sizes, int64_t sizes_len_, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_max_pool2d_with_indices(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_max_pool2d_with_indices_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle indices, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_max_pool3d_with_indices(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_max_pool3d_with_indices_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle indices, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_max_unpool2d(AtenTensorHandle self, AtenTensorHandle indices, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_max_unpool3d(AtenTensorHandle self, AtenTensorHandle indices, const int64_t* output_size, int64_t output_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_median(AtenTensorHandle self, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_mm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_mode(AtenTensorHandle self, int64_t dim, int32_t keepdim, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_mul_Scalar(AtenTensorHandle self, double other, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_mul_Tensor(AtenTensorHandle self, AtenTensorHandle other, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_nanmedian(AtenTensorHandle self, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_native_dropout(AtenTensorHandle input, double p, int32_t* train, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_nonzero(AtenTensorHandle self, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_normal_functional(AtenTensorHandle self, double mean, double std, AtenGeneratorHandle* generator, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_ormqr(AtenTensorHandle self, AtenTensorHandle input2, AtenTensorHandle input3, int32_t left, int32_t transpose, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_polar(AtenTensorHandle abs, AtenTensorHandle angle, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_pow_Scalar(double self, AtenTensorHandle exponent, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_pow_Tensor_Scalar(AtenTensorHandle self, double exponent, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_pow_Tensor_Tensor(AtenTensorHandle self, AtenTensorHandle exponent, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_rand(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_rand_generator(const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_randint(int64_t high, const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_randint_generator(int64_t high, const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_randint_low(int64_t low, int64_t high, const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_randint_low_out(AtenTensorHandle out, int64_t low, int64_t high, const int64_t* size, int64_t size_len_);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_randn(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_randn_generator(const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_randperm(int64_t n, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_repeat_interleave_Tensor(AtenTensorHandle repeats, int64_t* output_size, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_replication_pad1d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* padding, int64_t padding_len_, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_replication_pad2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* padding, int64_t padding_len_, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_reshape(AtenTensorHandle self, const int64_t* shape, int64_t shape_len_, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_resize_(AtenTensorHandle self, const int64_t* size, int64_t size_len_, int32_t* memory_format);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_resize_as_(AtenTensorHandle self, AtenTensorHandle the_template, int32_t* memory_format);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_scatter_src_out(AtenTensorHandle out, AtenTensorHandle self, int64_t dim, AtenTensorHandle index, AtenTensorHandle src);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_scatter_value_out(AtenTensorHandle out, AtenTensorHandle self, int64_t dim, AtenTensorHandle index, double value);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_scatter_reduce_two_out(AtenTensorHandle out, AtenTensorHandle self, int64_t dim, AtenTensorHandle index, AtenTensorHandle src, const char* reduce, int32_t include_self);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_segment_reduce(AtenTensorHandle data, const char* reduce, AtenTensorHandle* lengths, AtenTensorHandle* indices, AtenTensorHandle* offsets, int64_t axis, int32_t unsafe, double* initial, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_slice_Tensor(AtenTensorHandle self, int64_t dim, int64_t* start, int64_t* end, int64_t step, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_soft_margin_loss_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle target, int64_t reduction, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_sort(AtenTensorHandle self, int64_t dim, int32_t descending, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_sort_stable(AtenTensorHandle self, int32_t* stable, int64_t dim, int32_t descending, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_to_sparse(AtenTensorHandle self, int32_t* layout, const int64_t** blocksize, int64_t blocksize_len_, int64_t* dense_dim, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_topk(AtenTensorHandle self, int64_t k, int64_t dim, int32_t largest, int32_t sorted, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_triangular_solve(AtenTensorHandle self, AtenTensorHandle A, int32_t upper, int32_t transpose, int32_t unitriangular, AtenTensorHandle* ret0, AtenTensorHandle* ret1);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_uniform(AtenTensorHandle self, double from, double to, AtenGeneratorHandle* generator, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_upsample_bicubic2d_backward(AtenTensorHandle grad_output, const int64_t* output_size, int64_t output_size_len_, const int64_t* input_size, int64_t input_size_len_, int32_t align_corners, double* scales_h, double* scales_w, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_upsample_linear1d_backward(AtenTensorHandle grad_output, const int64_t* output_size, int64_t output_size_len_, const int64_t* input_size, int64_t input_size_len_, int32_t align_corners, double* scales, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_upsample_trilinear3d_backward(AtenTensorHandle grad_output, const int64_t* output_size, int64_t output_size_len_, const int64_t* input_size, int64_t input_size_len_, int32_t align_corners, double* scales_d, double* scales_h, double* scales_w, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_view_dtype(AtenTensorHandle self, int32_t dtype, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_view_as_complex(AtenTensorHandle self, AtenTensorHandle* ret0);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_view_as_real(AtenTensorHandle self, AtenTensorHandle* ret0);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_torch/mkldnn_tensor.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_torch/mkldnn_tensor.h
new file mode 100644
index 0000000000000000000000000000000000000000..adf0927ca0a5eb5473cd7499e642a0b42afaa412
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_torch/mkldnn_tensor.h
@@ -0,0 +1,17 @@
+#pragma once
+
+#include 
+
+namespace torch::aot_inductor {
+
+void* data_ptr_from_mkldnn(at::Tensor* mkldnn_tensor);
+
+at::Tensor mkldnn_tensor_from_data_ptr(
+    void* data_ptr,
+    at::IntArrayRef dims,
+    at::ScalarType dtype,
+    at::Device device,
+    const uint8_t* opaque_metadata,
+    int64_t opaque_metadata_size);
+
+} // namespace torch::aot_inductor
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_torch/oss_proxy_executor.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_torch/oss_proxy_executor.h
new file mode 100644
index 0000000000000000000000000000000000000000..c1a0f9260edd541d1f39fddfc30baaa50a267ba6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_torch/oss_proxy_executor.h
@@ -0,0 +1,103 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch::aot_inductor {
+
+enum class DynamicArgType : int {
+  TensorType = 0,
+  ListTensorType = 1,
+  ListOptionalTensorType = 2,
+  IntType = 3,
+  ListIntType = 4,
+};
+
+inline std::ostream& operator<<(std::ostream& os, DynamicArgType arg_type) {
+  os << static_cast(arg_type);
+  return os;
+}
+
+inline bool isTensorType(DynamicArgType arg_type) {
+  return arg_type == DynamicArgType::TensorType ||
+      arg_type == DynamicArgType::ListTensorType ||
+      arg_type == DynamicArgType::ListOptionalTensorType;
+}
+
+struct OSSDynamicArg {
+  OSSDynamicArg(
+      int arg_index,
+      DynamicArgType arg_type,
+      int length,
+      std::optional> list_item_types = std::nullopt)
+      : arg_index(arg_index),
+        arg_type(arg_type),
+        length(length),
+        list_item_types(std::move(list_item_types)) {}
+  int arg_index;
+  DynamicArgType arg_type;
+  int length;
+  std::optional>
+      list_item_types; // only used for parsing list of optional tensors
+};
+
+struct OSSOpKernel {
+  OSSOpKernel(std::string target, c10::OperatorHandle op_handle)
+      : target_(std::move(target)), op_handle_(std::move(op_handle)) {}
+
+  std::string target_;
+  c10::OperatorHandle op_handle_;
+  std::vector dynamic_args_;
+  std::vector outputs_;
+  std::vector stack_;
+
+  int num_output_tensors() const {
+    int num_output_tensors = 0;
+    for (const auto& output : outputs_) {
+      if (isTensorType(output.arg_type)) {
+        num_output_tensors += output.length;
+      }
+    }
+    return num_output_tensors;
+  }
+};
+
+class OSSProxyExecutor : public ProxyExecutor {
+ public:
+  explicit OSSProxyExecutor(const std::string& json_path, bool is_cpu);
+
+  void call_function(
+      int extern_node_index,
+      int num_ints,
+      int64_t* flatten_int_args,
+      int num_tensors,
+      AtenTensorHandle* flatten_tensor_args) override;
+
+ private:
+  void prefill_stack_with_static_arguments(
+      int index,
+      at::TypePtr schema_arg_type,
+      const nlohmann::json& serialized_arg,
+      OSSOpKernel& op_kernel);
+
+  void get_input_info_from_serialized(
+      const std::vector& schema_args,
+      const nlohmann::json& serialized_node,
+      OSSOpKernel& op_kernel);
+
+  void get_output_info_from_serialized(
+      const std::vector& schema_returns,
+      const nlohmann::json& serialized_node,
+      OSSOpKernel& op_kernel);
+
+  std::vector op_kernels_;
+  std::unique_ptr device_;
+};
+
+} // namespace torch::aot_inductor
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_torch/proxy_executor.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_torch/proxy_executor.h
new file mode 100644
index 0000000000000000000000000000000000000000..6943bca5df49e9b92e590c8ac255f23ef28e2cec
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_torch/proxy_executor.h
@@ -0,0 +1,22 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+namespace torch::aot_inductor {
+
+class ProxyExecutor {
+ public:
+  ProxyExecutor() = default;
+  virtual ~ProxyExecutor() = default;
+
+  virtual void call_function(
+      int extern_node_index,
+      int num_ints,
+      int64_t* flatten_int_args,
+      int num_tensors,
+      AtenTensorHandle* flatten_tensor_args) = 0;
+};
+
+} // namespace torch::aot_inductor
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_torch/tensor_converter.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_torch/tensor_converter.h
new file mode 100644
index 0000000000000000000000000000000000000000..19c4ed74530e7fb4134c29bc9dd1efb8c79baada
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_torch/tensor_converter.h
@@ -0,0 +1,26 @@
+#pragma once
+
+#include 
+#include 
+
+namespace torch::aot_inductor {
+
+// Functions declared here are not meant to be called from the AOTInductor
+// generated model.so
+
+// unsafe_alloc_new_handles_from_tensors is used for allocating new aten
+// tensor objects and return them as a vector of AtenTensorHandle (raw
+// pointers), and those pointers will be stolen by model.so.
+TORCH_API std::vector unsafe_alloc_new_handles_from_tensors(
+    std::vector& tensors);
+
+// alloc_tensors_by_stealing_from_handles is used for creating a vector of aten
+// tensors by stealing from an array of handles. Only the handles are stolen,
+// and the array itself is borrowed.
+//
+// WARNING: Can NOT be called in model.so unless in the non-ABI-compatible mode
+TORCH_API std::vector alloc_tensors_by_stealing_from_handles(
+    AtenTensorHandle* handles,
+    size_t length);
+
+} // namespace torch::aot_inductor
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_torch/utils.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_torch/utils.h
new file mode 100644
index 0000000000000000000000000000000000000000..870918093e8eb58d35f9e17bfd5b4ea17ec18023
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/inductor/aoti_torch/utils.h
@@ -0,0 +1,185 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#define AOTI_TORCH_CONVERT_EXCEPTION_TO_ERROR_CODE(...)    \
+  try {                                                    \
+    __VA_ARGS__                                            \
+  } catch (const std::exception& e) {                      \
+    LOG(ERROR) << "Exception in aoti_torch: " << e.what(); \
+    return AOTI_TORCH_FAILURE;                             \
+  } catch (...) {                                          \
+    LOG(ERROR) << "Exception in aoti_torch: UNKNOWN";      \
+    return AOTI_TORCH_FAILURE;                             \
+  }                                                        \
+  return AOTI_TORCH_SUCCESS;
+
+namespace torch::aot_inductor {
+
+inline at::Tensor* tensor_handle_to_tensor_pointer(AtenTensorHandle handle) {
+  return reinterpret_cast(handle);
+}
+
+inline AtenTensorHandle tensor_pointer_to_tensor_handle(at::Tensor* tensor) {
+  return reinterpret_cast(tensor);
+}
+
+inline at::Generator* generator_handle_to_generator_pointer(
+    AtenGeneratorHandle handle) {
+  return reinterpret_cast(handle);
+}
+
+inline AtenGeneratorHandle generator_pointer_to_generator_handle(
+    at::Generator* generator) {
+  return reinterpret_cast(generator);
+}
+
+inline AtenTensorHandle new_tensor_handle(at::Tensor&& tensor) {
+  at::Tensor* new_tensor = new at::Tensor(std::move(tensor));
+  return tensor_pointer_to_tensor_handle(new_tensor);
+}
+
+inline void assert_inf_and_nan(
+    const std::string& tensor_name,
+    at::Tensor& check_tensor) {
+  auto isnan_tensor = check_tensor.isnan();
+  if (isnan_tensor.any().item()) {
+    throw std::runtime_error("At least one NaN in " + tensor_name);
+  }
+  auto isinf_tensor = check_tensor.isinf();
+  if (isinf_tensor.any().item()) {
+    throw std::runtime_error("At least one INF in " + tensor_name);
+  }
+}
+
+// utility functions to convert a pointer to an optional value
+template 
+inline std::optional pointer_to_optional(T* ptr) {
+  return ptr ? std::make_optional(*ptr) : std::nullopt;
+}
+
+template >>
+inline std::optional pointer_to_optional(U* ptr) {
+  return ptr ? std::make_optional(T(*ptr)) : std::nullopt;
+}
+
+template <>
+inline std::optional pointer_to_optional(AtenTensorHandle* ptr) {
+  return ptr ? std::make_optional(*tensor_handle_to_tensor_pointer(*ptr))
+             : std::nullopt;
+}
+
+template <>
+inline std::optional pointer_to_optional(
+    const AtenTensorHandle* ptr) {
+  return ptr ? std::make_optional(*tensor_handle_to_tensor_pointer(*ptr))
+             : std::nullopt;
+}
+
+template <>
+inline std::optional pointer_to_optional(
+    AtenGeneratorHandle* ptr) {
+  return ptr ? std::make_optional(*generator_handle_to_generator_pointer(*ptr))
+             : std::nullopt;
+}
+
+inline std::optional pointer_to_optional_device(
+    int32_t* device_type,
+    int32_t device_index) {
+  return device_type ? std::make_optional(c10::Device(
+                           static_cast(*device_type),
+                           static_cast(device_index)))
+                     : std::nullopt;
+}
+
+// utility functions to convert a pointer to a list
+template 
+struct is_optional : std::false_type {};
+template 
+struct is_optional> : std::true_type {};
+
+template 
+inline c10::ArrayRef pointer_to_list(T* ptr, int64_t len) {
+  return c10::ArrayRef(ptr, len);
+}
+
+template <
+    class T,
+    class U,
+    typename = std::enable_if_t>,
+    typename = std::enable_if_t::value>>
+inline std::vector pointer_to_list(U* ptr, int64_t len) {
+  // std::vector will be implicitly converted to c10::ArrayRef at the call
+  // site
+  std::vector result;
+  result.reserve(len);
+  for (int64_t i = 0; i < len; i++) {
+    result.emplace_back(T(ptr[i]));
+  }
+  return result;
+}
+
+template ::value>>
+inline std::vector pointer_to_list(U** ptr, int64_t len) {
+  // Here U** denotes a list of optional arguments
+  // std::vector will be implicitly converted to c10::ArrayRef at the call
+  // site
+  std::vector result;
+  result.reserve(len);
+  for (int64_t i = 0; i < len; i++) {
+    result.emplace_back(pointer_to_optional(ptr[i]));
+  }
+  return result;
+}
+
+template <>
+inline std::vector pointer_to_list(
+    const AtenTensorHandle* ptr,
+    int64_t len) {
+  std::vector result;
+  result.reserve(len);
+  for (int64_t i = 0; i < len; i++) {
+    result.emplace_back(*tensor_handle_to_tensor_pointer(*ptr));
+  }
+  return result;
+}
+
+template <>
+inline std::vector> pointer_to_list(
+    const AtenTensorHandle** ptr,
+    int64_t len) {
+  std::vector> result;
+  result.reserve(len);
+  for (int64_t i = 0; i < len; i++) {
+    result.emplace_back(pointer_to_optional(ptr[i]));
+  }
+  return result;
+}
+
+template 
+inline std::array pointer_to_list(const int32_t* ptr) {
+  std::array result;
+  std::copy(ptr, ptr + N, result.begin());
+  return result;
+}
+
+// Utility function to convert a pointer to an optional list of values
+template 
+inline std::optional> pointer_to_optional_list(
+    U** ptr,
+    int64_t len) {
+  return ptr
+      ? std::make_optional>(pointer_to_list(*ptr, len))
+      : std::nullopt;
+}
+
+} // namespace torch::aot_inductor
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/backend/backend_data.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/backend/backend_data.h
new file mode 100644
index 0000000000000000000000000000000000000000..496ecbdbbc6c530e50e0d3a8e3b815e9a5f005e0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/backend/backend_data.h
@@ -0,0 +1,61 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace lazy {
+
+class TORCH_API BackendData {
+ public:
+  struct Info {
+    /**
+     * Used by Lazy Graph Executor to tag info on BackendData objs
+     * */
+    virtual ~Info() = default;
+  };
+  /**
+   * Represents (Tensor) data stored on a backend device
+   * in its native format.
+   * */
+  using Handle = int64_t;
+
+  BackendData(BackendDevice device, Shape shape)
+      : device_(std::move(device)), shape_(std::move(shape)) {}
+
+  virtual ~BackendData() = default;
+
+  const BackendDevice& device() const {
+    return device_;
+  }
+
+  const Shape& shape() const {
+    return shape_;
+  }
+
+  Info* info() const {
+    return info_.get();
+  }
+
+  std::shared_ptr SetInfo(std::shared_ptr info) {
+    std::swap(info, info_);
+    return info;
+  }
+
+  virtual Handle GetHandle() = 0;
+
+  virtual void Assign(const BackendData& data) = 0;
+
+  virtual bool HasValue() const = 0;
+
+ private:
+  BackendDevice device_;
+  Shape shape_;
+  std::shared_ptr info_;
+};
+
+using BackendDataPtr = std::shared_ptr;
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/backend/backend_device.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/backend/backend_device.h
new file mode 100644
index 0000000000000000000000000000000000000000..fdfc2ac15d9a89351c43517071fdec857c3d5f2f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/backend/backend_device.h
@@ -0,0 +1,100 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+
+namespace c10 {
+struct Device;
+}
+
+namespace torch {
+namespace lazy {
+
+// Backend should extend it and define their own supported hardware types.
+struct TORCH_API BackendDeviceType {
+  int8_t type{(int8_t)at::kCPU};
+  // Note: previous default value was '0', which actually maps to at::kCPU, at
+  // least now it is explicit, we may want to make default/undefined semantics
+  // more clear though
+  BackendDeviceType() : type((int8_t)at::kCPU) {}
+  BackendDeviceType(int8_t type) : type(type) {}
+
+  virtual ~BackendDeviceType() = default;
+  virtual std::string toString() const {
+    return "Unknown";
+  }
+};
+
+class TORCH_API BackendDevice {
+ public:
+  // The default constructor will set both the device type and ordinal
+  // to backend specific defaults.
+  BackendDevice();
+  BackendDevice(std::shared_ptr&& type, int64_t ordinal);
+
+  int8_t type() const;
+  int64_t ordinal() const {
+    return ordinal_;
+  }
+
+  bool operator==(const BackendDevice& other) const {
+    return compare(other) == 0;
+  }
+  bool operator!=(const BackendDevice& other) const {
+    return compare(other) != 0;
+  }
+  bool operator<(const BackendDevice& rhs) const {
+    return compare(rhs) < 0;
+  }
+
+  std::string toString() const;
+
+ private:
+  int compare(const BackendDevice& rhs) const;
+
+  // Use shared_ptr instead of unique_ptr so that BackendDevice can be copied.
+  std::shared_ptr type_;
+  int64_t ordinal_;
+};
+
+TORCH_API std::ostream& operator<<(
+    std::ostream& os,
+    const BackendDevice& device);
+
+// Helpers for converting a c10::Device to BackendDevice and vice versa.
+TORCH_API BackendDevice atenDeviceToBackendDevice(const c10::Device& device);
+TORCH_API c10::Device backendDeviceToAtenDevice(const BackendDevice& device);
+
+// Tries to extract the backend device out of the lazy tensor. Returns nullopt
+// if the input is not a lazy tensor.
+TORCH_API std::optional GetBackendDevice(
+    const at::ITensorListRef tensors);
+TORCH_API std::optional GetBackendDevice(
+    const at::TensorList tensors);
+TORCH_API std::optional GetBackendDevice(
+    const at::Tensor& tensor);
+TORCH_API std::optional GetBackendDevice(
+    const std::optional& device);
+
+// For variadic template.
+TORCH_API std::optional GetBackendDevice();
+
+template 
+std::optional GetBackendDevice(
+    const T& tensor,
+    const Args&... forward_tensors) {
+  auto optional_device = GetBackendDevice(tensor);
+  if (optional_device) {
+    return optional_device;
+  }
+  return GetBackendDevice(forward_tensors...);
+}
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/backend/backend_interface.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/backend/backend_interface.h
new file mode 100644
index 0000000000000000000000000000000000000000..366311921c3945e4c2b564cc36cf7423895f8f94
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/backend/backend_interface.h
@@ -0,0 +1,158 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace lazy {
+
+struct IrBuilder;
+
+/**
+ * Work in progress- don't treat this as a stable interface yet!
+ */
+class TORCH_API BackendImplInterface {
+ public:
+  virtual ~BackendImplInterface() = default;
+
+  /**
+   * Initialization/Teardown
+   * */
+  // No-op by default. Allows custom functionality to be exposed through
+  // extension bindings.
+  virtual void InitializeAtenBindings() const {}
+
+  virtual void PrepareToExit() const = 0;
+
+  /**
+   * Configuration
+   * */
+
+  virtual void SetRngSeed(size_t seed) const = 0;
+
+  /**
+   * IR Tracing
+   * */
+
+  virtual const IrBuilder* GetIrBuilder() const = 0;
+
+  /**
+   * Data Transfer
+   * */
+
+  virtual BackendDataPtr MakeComputationDataFromTensor(
+      const at::Tensor& tensor,
+      const Shape& shape,
+      const BackendDevice& device) const = 0;
+  virtual BackendDataPtr MakeComputationDataFromScalar(
+      const at::Scalar& scalar,
+      const torch::lazy::BackendDevice& device) const = 0;
+  virtual BackendDataPtr CreateDataPlaceholder(
+      const BackendDevice& device,
+      const Shape& shape) const = 0;
+
+  // Gets backend data if the node is a device data node. Otherwise returns
+  // nullptr
+  virtual BackendDataPtr GetComputationDataFromNode(const Node*) const = 0;
+
+  virtual at::Tensor MakeTensorFromComputationData(
+      const BackendDataPtr data,
+      std::optional logical_scalar_type) const = 0;
+
+  /**
+   * Lowering, Compilation, Execution
+   * */
+
+  virtual std::unique_ptr CreateLoweringContext(
+      const std::string& name,
+      BackendDevice device,
+      c10::ArrayRef post_order,
+      Util::EmissionMap emit_status) const = 0;
+
+  virtual std::unique_ptr CreateLoweringContext(
+      const std::string& name,
+      BackendDevice device) const = 0;
+
+  // TODO(whc) need to keep this?
+  virtual std::vector GetCompilationDevices(
+      const std::string& device,
+      c10::ArrayRef devices) const = 0;
+
+  virtual std::vector Compile(
+      std::vector instances) const = 0;
+
+  virtual std::vector ExecuteComputation(
+      torch::lazy::ComputationPtr computation,
+      c10::ArrayRef arguments,
+      const BackendDevice& device) const = 0;
+
+  /**
+   * Device Configuration
+   * */
+
+  // Set or get the default device type.
+  // For backends used with virtual c10::Devices, this configures what real
+  // device type the backend should use, and matters if the backend supports
+  // more than one type of real device.
+  virtual std::shared_ptr GetDefaultDeviceType() const = 0;
+  virtual void SetDefaultDeviceType(int8_t type) = 0;
+
+  // Set or get the default device ordinal.
+  // For backends that supports multi-device, this configures what the
+  // default device the backend should use.
+  virtual int64_t GetDefaultDeviceOrdinal() const = 0;
+  virtual void SetDefaultDeviceOrdinal(int64_t) = 0;
+
+  // Specify which aten device should be used for eager fallback
+  // may change depending on current 'Default' DeviceType
+  virtual at::DeviceType EagerFallbackDeviceType() const = 0;
+
+  // Query all available backend devices
+  virtual std::vector GetBackendDevices() const = 0;
+
+  virtual std::string CreateMetricReport() const {
+    return "";
+  }
+
+  // Map a particular c10:: device to a concrete backend device
+  // Note:: c10:: devices may be virtual or concrete.  xla:: and lazy:: are
+  // virtual devices, meaning they may map to a gpu, tpu, etc. behind the
+  // scenes. In the future, non-virtual c10:: devices may also use lazy tensors
+  // through a mode, in which case these APIs should still work, but should be
+  // identity mappings.
+  virtual BackendDevice GetBackendDevice(c10::Device device) const = 0;
+
+  // TODO(whc)
+  // Additional APIs expected for supporting distributed training, to be
+  // designed
+
+  /**
+   * Debug/Metrics
+   * */
+
+  //   virtual std::map GetMetrics() const = 0;
+
+  //   virtual MemoryInfo GetMemoryInfo(const std::string& device) = 0;
+
+  virtual std::string GetComputationBackendText(
+      const ComputationPtr computation) const = 0;
+};
+
+class TORCH_API BackendRegistrar {
+ public:
+  BackendRegistrar(const BackendImplInterface* backend_impl_interface);
+};
+
+TORCH_API bool hasBackend();
+TORCH_API const BackendImplInterface* getBackend();
+
+TORCH_API const IrBuilder* getIrBuilder();
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/backend/lowering_context.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/backend/lowering_context.h
new file mode 100644
index 0000000000000000000000000000000000000000..49e7b8be58cbf234b546bc4988e870a520d797f8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/backend/lowering_context.h
@@ -0,0 +1,114 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace lazy {
+
+class TORCH_API Computation {
+ public:
+  virtual int parameters_size() const = 0;
+
+  virtual const std::vector& parameter_shapes() const = 0;
+
+  virtual const std::vector& parameter_names() const = 0;
+
+  virtual const Shape& result_shape() const = 0;
+
+  virtual const std::string to_string() const = 0;
+
+  virtual ~Computation() = default;
+
+  // Indicates whether this computation is being executed inside a mark step
+  // Assume false unless set otherwise
+  bool in_mark_step = false;
+};
+
+using ComputationPtr = std::shared_ptr;
+
+// Keeps track of the code generation state.
+class TORCH_API LoweringContext {
+ public:
+  LoweringContext(const std::string& name, BackendDevice device);
+  LoweringContext(
+      const std::string& name,
+      BackendDevice device,
+      c10::ArrayRef post_order,
+      Util::EmissionMap emit_status);
+
+  virtual ~LoweringContext() = default;
+
+  static std::unique_ptr Create(
+      const std::string& name,
+      BackendDevice device,
+      c10::ArrayRef post_order,
+      Util::EmissionMap emit_status);
+
+  static std::unique_ptr Create(
+      const std::string& name,
+      BackendDevice device);
+
+  const BackendDevice& device() const {
+    return device_;
+  };
+
+  // Retrieves the vector holding all the tensors associated with the parameter
+  // instructions which have been created.
+  const std::vector& GetParametersData() const;
+
+  // Adds a new input/output alias.
+  virtual void SetUpAlias(
+      const std::vector& output_index,
+      int64_t param_number,
+      const std::vector& param_index,
+      bool must_alias = false) {
+    // Dummy default implementation to do nothing.
+  }
+
+  // Check if parameter shape matches result at index.
+  virtual bool CheckResultShape(
+      const BackendDataPtr& parameter_data,
+      size_t result_idx) {
+    // Dummy default implementation to do nothing.
+    return false;
+  }
+
+  // Adds the given output as a component of the result tuple and returns its
+  // assigned position within the tuple.
+  virtual size_t AddResult(const torch::lazy::Output& output) = 0;
+
+  // Associates the given output with the input parameter of the given index and
+  // shape. Only used for the operator-by-operator execution, mostly for
+  // debugging purposes.
+  virtual void AddParameter(
+      const torch::lazy::Output& output,
+      size_t index,
+      const Shape& shape,
+      const std::string& name) = 0;
+
+  // Build the computation capturing all the operations created with the
+  // embedded builder (returned by the builder() API).
+  virtual ComputationPtr Build() = 0;
+
+  size_t GetEmittedNodeCount() const {
+    return emit_status_.size();
+  }
+
+ protected:
+  BackendDevice device_;
+  std::vector parameters_;
+  std::vector parameter_sequence_;
+  Util::EmissionMap emit_status_;
+};
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/cache.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/cache.h
new file mode 100644
index 0000000000000000000000000000000000000000..1ee635b667f90a1d56a186650c3bb023ae542660
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/cache.h
@@ -0,0 +1,144 @@
+/**
+ * Cache utils in this file is adapted from PyTorch/XLA
+ * https://github.com/pytorch/xla/blob/master/third_party/xla_client/cache.h
+ */
+
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace lazy {
+
+// Generic key and object cache with LRU expiration policy. The objects of type
+// T will be stored as std::shared_ptr and taken and returned as such, by the
+// cache API.
+template <
+    typename K,
+    typename T,
+    typename H = std::hash,
+    typename E = std::equal_to>
+class Cache {
+ public:
+  using TypePtr = std::shared_ptr;
+  using Element = std::pair;
+
+  explicit Cache(size_t max_size) : max_size_(max_size) {}
+
+  // Adds an object to the cache, unless it already exists. If the cache grows
+  // beyond the limit set during construction, the oldest used object will be
+  // removed from the cache.
+  TypePtr Add(K key, TypePtr object) {
+    if (!max_size_) {
+      return object;
+    }
+    std::lock_guard slock(lock_);
+    element_list_.emplace_front(Element(std::move(key), std::move(object)));
+    auto it = element_list_.begin();
+    auto emplace_result = element_map_.emplace(&it->first, it);
+    if (!emplace_result.second) {
+      element_list_.erase(it);
+      DoLRU(emplace_result.first->second);
+    } else if (element_list_.size() > max_size_) {
+      Element* last = &element_list_.back();
+      element_map_.erase(&last->first);
+      element_list_.pop_back();
+    }
+    return emplace_result.first->second->second;
+  }
+
+  // Retrieves the existing object if it exists. If it does, its position in
+  // the LRU list gets moved to the head of the list.
+  // Returns nullptr if no object with the specified key is found within the
+  // cache.
+  TypePtr Get(const K& key) {
+    if (!max_size_) {
+      return nullptr;
+    }
+    std::lock_guard slock(lock_);
+    auto it = element_map_.find(&key);
+    if (it == element_map_.end()) {
+      return nullptr;
+    }
+    DoLRU(it->second);
+    return it->second->second;
+  }
+
+  TypePtr GetLatest() {
+    std::lock_guard g(lock_);
+    TORCH_CHECK(!element_list_.empty());
+    return element_list_.front().second;
+  }
+
+  bool Erase(const K& key) {
+    if (!max_size_) {
+      return false;
+    }
+    std::lock_guard slock(lock_);
+    auto it = element_map_.find(&key);
+    if (it == element_map_.end()) {
+      return false;
+    }
+    auto lit = it->second;
+    element_map_.erase(it);
+    element_list_.erase(lit);
+    return true;
+  }
+
+  void Clear() {
+    if (!max_size_) {
+      return;
+    }
+    std::lock_guard slock(lock_);
+    element_map_.clear();
+    element_list_.clear();
+  }
+
+  int Numel() const {
+    if (!max_size_) {
+      return 0;
+    }
+    std::lock_guard g(lock_);
+    TORCH_CHECK(element_map_.size() == element_list_.size());
+    return element_map_.size();
+  }
+
+ private:
+  using ElementList = std::list;
+
+  struct Hasher {
+    size_t operator()(const K* key) const {
+      return hasher(*key);
+    }
+
+    H hasher;
+  };
+
+  struct Equaler {
+    bool operator()(const K* k1, const K* k2) const {
+      return equaler(*k1, *k2);
+    }
+
+    E equaler;
+  };
+
+  using ElementMap = std::
+      unordered_map;
+
+  void DoLRU(typename ElementList::iterator it) {
+    element_list_.splice(element_list_.begin(), element_list_, it);
+  }
+
+  mutable std::mutex lock_;
+  const size_t max_size_ = 0;
+  ElementList element_list_;
+  ElementMap element_map_;
+};
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/config.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/config.h
new file mode 100644
index 0000000000000000000000000000000000000000..16d2b80701536166c817ad609db14f342e6c94d0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/config.h
@@ -0,0 +1,28 @@
+#pragma once
+#include 
+#include 
+
+C10_DECLARE_bool(torch_lazy_ir_debug);
+C10_DECLARE_bool(torch_lazy_handle_special_scalars);
+C10_DECLARE_bool(torch_lazy_all_numbers_special_scalars);
+C10_DECLARE_bool(torch_lazy_param_aliasing);
+C10_DECLARE_bool(torch_lazy_reuse_ir);
+C10_DECLARE_bool(torch_lazy_use_thread_pool);
+C10_DECLARE_bool(torch_lazy_enable_device_data_cache);
+
+C10_DECLARE_int(torch_lazy_compilation_cache_size);
+C10_DECLARE_int(torch_lazy_device_data_cache_size);
+C10_DECLARE_int(torch_lazy_io_thread_pool_size);
+C10_DECLARE_int(torch_lazy_metrics_samples);
+C10_DECLARE_int(torch_lazy_trim_graph_check_frequency);
+C10_DECLARE_int(torch_lazy_trim_graph_size);
+
+C10_DECLARE_string(torch_lazy_metrics_percentiles);
+
+C10_DECLARE_int(torch_lazy_shape_cache_size);
+
+namespace torch {
+namespace lazy {
+TORCH_API std::string& getLTCForceFallback();
+}
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/debug_util.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/debug_util.h
new file mode 100644
index 0000000000000000000000000000000000000000..ef4b81e1ca9c5dd7878603f4efcf8f381825dc4b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/debug_util.h
@@ -0,0 +1,47 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+
+namespace torch {
+namespace lazy {
+
+TORCH_API std::function()>&
+GetPythonFramesFunction();
+
+TORCH_API std::string GetFirstUserFrameInPython();
+
+class TORCH_API DebugUtil {
+ public:
+  enum GraphFormat {
+    kText,
+    kDot,
+    kBackend,
+  };
+
+  static GraphFormat GetDefaultGraphFormat();
+
+  // Dumps the current Python frame and the IR Graph whose roots are the IR
+  // values held at the tensors. If indices is not nullptr, it selects the
+  // indices of the tensors whose graph will be emitted.
+  static std::string GetTensorsGraphInfo(
+      c10::ArrayRef tensors,
+      const std::vector* indices,
+      GraphFormat format = GetDefaultGraphFormat());
+
+  // If the environment variable LTC_SAVE_TENSORS_FILE is set to the proper
+  // output path, an instance of the report returned by GetTensorsGraphInfo() is
+  // saved.
+  static void SaveTensorsGraphInfo(
+      const char* name,
+      c10::ArrayRef tensors,
+      const std::vector* indices,
+      GraphFormat format = GetDefaultGraphFormat());
+
+  static bool ExperimentEnabled(const std::string& name);
+};
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/dynamic_ir.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/dynamic_ir.h
new file mode 100644
index 0000000000000000000000000000000000000000..8af7f4fae44ecd7cfec27236d930e129f0f68117
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/dynamic_ir.h
@@ -0,0 +1,59 @@
+#pragma once
+
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace lazy {
+
+/**
+ * The goal of "dynamic" Nodes is to patch a hole in our tracing.
+ * Previously, if a user called `sizes` on a Tensor, it would leak out
+ * of our tracing system, as `sizes` returns a torch.Size or an int. To
+ * prevent this from happening, we introduce DimensionNode, a new type
+ * of Node that abstracts the operation of getting the dimensions of a
+ * Tensor.
+ *
+ * Consider the following example:
+ * ```
+ * numel = x.shape()[0] * x.shape()[1]
+ * ```
+ *
+ * Here, `x.shape()[i]` will be a SizeNode (subclass of DimensionNode),
+ * and the multiplication of the two SizeNodes will be represented by
+ * a SizeMul (also a subclass of DimensionNode). Through this, we can
+ * prevent `numel` from being represented as a Python int and thus
+ * burned into the Graph.
+ */
+
+class TORCH_API DimensionNode {
+ public:
+  virtual bool isSymbolic() const {
+    return false;
+  };
+  virtual int64_t getDynamicValue() const {
+    TORCH_CHECK(false, "NYI");
+  };
+  virtual int64_t getStaticValue() const {
+    TORCH_CHECK(false, "NYI");
+  };
+  virtual ~DimensionNode() = default;
+};
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/hash.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/hash.h
new file mode 100644
index 0000000000000000000000000000000000000000..b7d20dbd7b1158f18c6cb6a2feabcfdba14f117d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/hash.h
@@ -0,0 +1,249 @@
+/**
+ * Hash utils in this file is adapted from PyTorch/XLA
+ * https://github.com/pytorch/xla/blob/e0e5f937a0ba8d904f9608137dc8c51ba439df2d/third_party/xla_client/util.h
+ */
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace lazy {
+
+using size_t = std::size_t;
+
+class TORCH_API hash_t : public c10::uint128 {
+ public:
+  // Swich from typedef hash_t = uint128 to provide explicit casters
+  hash_t(int8_t val) : uint128(static_cast(val)) {}
+  hash_t(int16_t val) : uint128(static_cast(val)) {}
+  hash_t(int32_t val) : uint128(static_cast(val)) {}
+  hash_t(int64_t val) : uint128(static_cast(val)) {}
+  hash_t(uint32_t val) : uint128(val) {}
+  hash_t(uint64_t val) : uint128(val) {}
+  hash_t(uint128 val) : uint128(val) {}
+  hash_t(uint64_t top, uint64_t bottom) : uint128(top, bottom) {}
+  hash_t() : uint128() {}
+};
+
+// Std* functions use 64-bit hash
+size_t TORCH_API StdDataHash(const void* data, size_t size);
+
+size_t TORCH_API StdHashCombine(uintmax_t a, uintmax_t b);
+
+// Other functions are all 128-bit
+hash_t TORCH_API HashBlock(const void* data, size_t n, const hash_t& seed);
+
+hash_t TORCH_API DataHash(const void* data, size_t size);
+
+hash_t TORCH_API HashCombine(const hash_t& a, const hash_t& b);
+
+size_t TORCH_API HashReduce(const hash_t& a);
+
+// Returns a string representation of a hash
+std::string TORCH_API HashToString(const hash_t& a);
+
+struct HashReducer {
+  size_t operator()(const hash_t& value) const {
+    return HashReduce(value);
+  }
+};
+
+static inline hash_t StringHash(const char* data) {
+  return DataHash(data, std::strlen(data));
+}
+
+// Automatic templated implementation for 'arithmetic' types
+template <
+    typename T,
+    typename std::enable_if::value>::type* = nullptr>
+hash_t Hash(const T& value) {
+  return DataHash(&value, sizeof(value));
+}
+
+// added because on macos builds the vector specialization
+// breaks falling through to the templated arithmetic types above
+hash_t TORCH_API Hash(const std::vector& value);
+
+// Specialiazed implementations for proprietary types
+static inline hash_t Hash(const c10::ScalarType& value) {
+  return DataHash(&value, sizeof(value));
+}
+
+static inline hash_t Hash(const c10::MemoryFormat& value) {
+  return DataHash(&value, sizeof(value));
+}
+
+static inline hash_t Hash(const c10::DeviceType& value) {
+  return DataHash(&value, sizeof(value));
+}
+
+static inline hash_t Hash(const c10::Device& value) {
+  return HashCombine(Hash(value.type()), Hash(value.index()));
+}
+
+static inline hash_t Hash(const c10::Layout& value) {
+  return DataHash(&value, sizeof(value));
+}
+
+static inline hash_t Hash(const c10::Scalar& value) {
+  switch (value.type()) {
+    case c10::ScalarType::ComplexDouble:
+      return Hash(value.toComplexDouble());
+    case c10::ScalarType::Double:
+      return Hash(value.toDouble());
+    case c10::ScalarType::Long:
+      return Hash(value.toLong());
+    case c10::ScalarType::Bool:
+      return Hash(value.toBool());
+    default:
+      TORCH_INTERNAL_ASSERT(false, "Unknown scalar type.", value.type());
+  }
+}
+
+static inline hash_t TensorHash(const at::Tensor& tensor) {
+  at::Tensor ctensor = tensor.contiguous();
+  int64_t size = ctensor.numel() * ctensor.element_size();
+  switch (ctensor.scalar_type()) {
+    case at::ScalarType::Bool:
+      return DataHash(ctensor.const_data_ptr(), size);
+    case at::ScalarType::Byte:
+      return DataHash(ctensor.const_data_ptr(), size);
+    case at::ScalarType::Char:
+      return DataHash(ctensor.const_data_ptr(), size);
+    case at::ScalarType::Short:
+      return DataHash(ctensor.const_data_ptr(), size);
+    case at::ScalarType::Int:
+      return DataHash(ctensor.const_data_ptr(), size);
+    case at::ScalarType::Long:
+      return DataHash(ctensor.const_data_ptr(), size);
+    case at::ScalarType::Float:
+      return DataHash(ctensor.const_data_ptr(), size);
+    case at::ScalarType::Double:
+      return DataHash(ctensor.const_data_ptr(), size);
+    case at::ScalarType::BFloat16:
+      return DataHash(ctensor.const_data_ptr(), size);
+    case at::ScalarType::Half:
+      return DataHash(ctensor.const_data_ptr(), size);
+    case at::ScalarType::ComplexFloat:
+      return DataHash(ctensor.const_data_ptr>(), size);
+    case at::ScalarType::ComplexDouble:
+      return DataHash(ctensor.const_data_ptr>(), size);
+    case at::ScalarType::UInt16:
+      return DataHash(ctensor.const_data_ptr(), size);
+    case at::ScalarType::UInt32:
+      return DataHash(ctensor.const_data_ptr(), size);
+    case at::ScalarType::UInt64:
+      return DataHash(ctensor.const_data_ptr(), size);
+    default:
+      TORCH_INTERNAL_ASSERT(
+          false, "Unsupported scalar type:", ctensor.scalar_type());
+  }
+}
+
+static inline hash_t Hash(const std::string& value) {
+  return DataHash(value.data(), value.size());
+}
+
+static inline hash_t Hash(const c10::string_view& value) {
+  return DataHash(value.data(), value.size());
+}
+
+static inline hash_t Hash(const std::string_view& value) {
+  return DataHash(value.data(), value.size());
+}
+
+static inline hash_t Hash(const at::Generator& value) {
+  return TensorHash(value.get_state());
+}
+
+// Taken from glibc's implementation of hashing optionals,
+// we want to include a contribution to the hash to distinguish
+// cases where one or another option was null, but we hope it doesn't
+// collide with an actually scalar value.
+//
+// Use an arbitrary randomly-selected 64-bit integer rather than a
+// small constant that we then hash at runtime so we don't have to
+// repeatedly hash a constant at runtime.
+static const int64_t kNullOpt = 0x8655d738f3678dda;
+
+// Hashing for std::optional types contributes to hash
+// for optionals with null value, important to distinguish
+// between  and  cases
+template 
+hash_t Hash(const std::optional& value) {
+  if (value.has_value()) {
+    return Hash(value.value());
+  } else {
+    return kNullOpt;
+  }
+}
+
+// Hashing of containers
+// Forward declare to allow hashes of vectors of vectors to work.
+template 
+hash_t ContainerHash(const T& values);
+
+template 
+hash_t Hash(const std::vector& values) {
+  return ContainerHash(values);
+}
+
+// Need a special case for std::optional?
+template 
+hash_t Hash(const std::optional>& value) {
+  if (value.has_value()) {
+    return ContainerHash(value.value());
+  } else {
+    return kNullOpt;
+  }
+}
+
+template 
+hash_t Hash(const std::set& values) {
+  return ContainerHash(values);
+}
+
+template 
+hash_t Hash(const std::pair& values) {
+  return HashCombine(Hash(values.first), Hash(values.second));
+}
+
+static inline hash_t Hash(const hash_t& value) {
+  return value;
+}
+
+template 
+hash_t Hash(c10::ArrayRef values) {
+  return ContainerHash(values);
+}
+
+template 
+hash_t ContainerHash(const T& values) {
+  hash_t h(static_cast(0x85ebca77c2b2ae63));
+  for (const auto& value : values) {
+    h = HashCombine(h, Hash(value));
+  }
+  return h;
+}
+
+// Varargs hashing
+template 
+hash_t MHash() {
+  return hash_t(static_cast(0x165667b19e3779f9));
+}
+
+template 
+hash_t MHash(T value, Targs... Fargs) {
+  return HashCombine(Hash(value), MHash(Fargs...));
+}
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/helpers.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/helpers.h
new file mode 100644
index 0000000000000000000000000000000000000000..c99a17f56f0e494a325d0603aa0d36ddd4cc79d4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/helpers.h
@@ -0,0 +1,72 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+// TODO: Consolidate this file with util.h
+
+namespace torch {
+namespace lazy {
+
+// Converts an iterable container to a vector of int64's.
+template 
+static std::vector ToI64Vector(const S& input) {
+  return ToVector(input);
+}
+
+// Creates a set of dimension by dropping the drop_dims ones.
+TORCH_API std::vector DropDimensions(
+    c10::ArrayRef sizes,
+    c10::ArrayRef drop_dims);
+
+// Get the canonical dimension index in the [0, rank) interval. Negative
+// indices are interpreted as follows: -1 is rank-1, -2 is rank-2 etc.
+TORCH_API int64_t GetCanonicalDimensionIndex(int64_t dim, int64_t rank);
+
+// Same as above, for multiple dimensions.
+TORCH_API std::vector GetCanonicalDimensionIndices(
+    c10::ArrayRef dimensions,
+    int64_t rank);
+
+// Returns the canonical position in the dim dimension, handling negative
+// values for the position.
+TORCH_API int64_t GetCanonicalPosition(
+    c10::ArrayRef dimensions,
+    int64_t dim,
+    int64_t pos);
+
+// Creates a transposition from the given input and dimensions.
+TORCH_API std::vector MakeTransposePermutation(
+    int64_t dim0,
+    int64_t dim1,
+    int64_t rank);
+
+// Calculates the protomoted shape to which the input shapes should be
+// broadcasted for an elementwise operation. The size of the common dimensions
+// (2,3,4 for shape1, and 0,1,2 for shape2) must either match, or either one
+// of the two be 1.
+// Example:
+//   shape1       = [9, 7, 6, 1, 2]
+//   shape2       =       [6, 5, 2]
+//   result_shape = [9, 7, 6, 5, 2]
+TORCH_API std::vector GetPromotedShape(
+    c10::ArrayRef shape1_dims,
+    c10::ArrayRef shape2_dims);
+
+TORCH_API Shape
+GetPromotedBinaryOpShape(const Shape& shape1, const Shape& shape2);
+
+TORCH_API std::vector StrSplit(c10::string_view text, char delim);
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/internal_ops/ltc_ops.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/internal_ops/ltc_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..ce62f2e51f539d04cf78e05a8a18677c1aca6f7c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/internal_ops/ltc_ops.h
@@ -0,0 +1,52 @@
+#pragma once
+
+#include 
+
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace lazy {
+
+class TORCH_API OpKindWrapper {
+ public:
+  explicit OpKindWrapper(const char* name) : name_(name) {}
+
+  const OpKind& operator*() const {
+    return get();
+  }
+
+  operator OpKind() const {
+    return get();
+  }
+
+ private:
+  const OpKind& get() const {
+    c10::call_once(once_, [this]() { op_kind_ = OpKind::Get(name_); });
+    return op_kind_;
+  }
+
+  const char* name_;
+  mutable OpKind op_kind_;
+  mutable c10::once_flag once_;
+};
+
+const OpKindWrapper ltc_all_to_all("lazy_tensors::all_to_all");
+const OpKindWrapper ltc_cast("lazy_tensors::cast");
+const OpKindWrapper ltc_collective_permute("lazy_tensors::collective_permute");
+const OpKindWrapper ltc_cross_replica_sum("lazy_tensors::cross_replica_sum");
+const OpKindWrapper ltc_device_data("lazy_tensors::device_data");
+const OpKindWrapper ltc_get_dimensions_size(
+    "lazy_tensors::ltc_get_dimensions_size");
+const OpKindWrapper ltc_moving_average("lazy_tensors::moving_average");
+const OpKindWrapper ltc_nms("lazy_tensors::nms");
+const OpKindWrapper ltc_not_supported("lazy_tensors::not_supported");
+const OpKindWrapper ltc_replication_pad("lazy_tensors::replication_pad");
+const OpKindWrapper ltc_replication_pad_backward(
+    "lazy_tensors::replication_pad_backward");
+const OpKindWrapper ltc_tensor_data("lazy_tensors::tensor_data");
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/ir.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/ir.h
new file mode 100644
index 0000000000000000000000000000000000000000..0f40456e1bf56b3ec24c9a33f6f1f6f41c1b8445
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/ir.h
@@ -0,0 +1,298 @@
+#pragma once
+
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+C10_DECLARE_bool(ltc_enable_dynamic_shapes);
+
+namespace torch {
+namespace lazy {
+
+static const hash_t kHashSeed(static_cast(0x5a2d296e9));
+
+class Node;
+struct Output;
+struct Value;
+
+using NodePtr = std::shared_ptr;
+
+// The Kind of operation a Node can be associated to.
+struct TORCH_API OpKind {
+  OpKind() = default;
+  explicit OpKind(c10::Symbol op) : op(op) {}
+
+  bool operator==(const OpKind& rhs) const {
+    return op == rhs.op;
+  }
+  bool operator!=(const OpKind& rhs) const {
+    return !operator==(rhs);
+  }
+  bool operator<(const OpKind& rhs) const {
+    return c10::unique_t(op) < c10::unique_t(rhs.op);
+  }
+
+  hash_t hash() const;
+
+  std::string ToString() const {
+    return op.toQualString();
+  }
+
+  // Retrieves an existing operation object, or creates a new one. Operations
+  // that are specific to lazy tensors, should live within the 'lazy_tensors::'
+  // namespace.
+  static OpKind Get(const std::string& name);
+
+  c10::Symbol op;
+};
+
+inline std::ostream& operator<<(std::ostream& stream, const OpKind& op) {
+  stream << op.ToString();
+  return stream;
+}
+
+using OpList = c10::ArrayRef;
+
+hash_t OperandHashes(
+    const OpList& operands,
+    const hash_t& seed,
+    bool bakeInSizes);
+// A node in the graph. Nodes for operations which require extra data to be
+// stored for lowering should inherit from this class and add an operation
+// specific member there. For example, a constant might create a new
+// NodeConstant class (inheriting from Node) with an extra lazy_tensors::Literal
+// field, or a tensor value might create a new NodeTensor with a computation
+// client data handle in it.
+class TORCH_API Node {
+ public:
+  static bool enableDynamicShape();
+
+  // Creates a new node with the given op name. The op is a unique identifier
+  // for the operation. The num_outputs tells how many outputs a given operation
+  // generates.
+  //
+  // None leaf node's node_hash does not contains shape information always.
+  // So we pass in the hash value rather than a function.
+  Node(OpKind op, size_t num_outputs);
+
+  // Construct node with operands and shapes
+  Node(
+      OpKind op,
+      OpList operands,
+      std::vector&& shapes,
+      size_t num_outputs = 1);
+
+  // Construct node with operands and shape generated from a function
+  Node(
+      OpKind op,
+      OpList operands,
+      const std::function& shape_fn,
+      size_t num_outputs = 1);
+
+  // Construct node with operands and no shape
+  Node(OpKind op, OpList operands, size_t num_outputs = 1);
+
+  // Construct node with shape and no operands
+  Node(OpKind op, Shape shape, size_t num_outputs = 1);
+
+  virtual ~Node();
+
+  const OpKind& op() const {
+    return op_;
+  }
+
+  size_t num_outputs() const {
+    return num_outputs_;
+  }
+
+  // Retrieves the full shape of the IR Node.
+  virtual c10::ArrayRef shapes() const;
+
+  virtual const Shape& shape(size_t output_index = 0) const;
+
+  // Add the shape computed by the shape_fn
+  void addComputedShape(const std::function& shape_fn);
+
+  // Compute the shape using the provided shape_fn if not previously cached
+  Shape computeShape(const std::function& shape_fn);
+
+  virtual const std::vector& operands() const;
+
+  virtual const Output& operand(size_t i) const;
+
+  // Gets operand at index i if index is valid, or kNullOutput otherwise.
+  virtual const Output& nullable_operand(size_t i) const;
+
+  // Returns the hash of the dag used to look up the compiled graph
+  virtual hash_t hash() const = 0;
+
+  // Returns the hash of the dag used to for shape caching
+  virtual hash_t shapeHash() const = 0;
+
+  const MetaData& metadata() const {
+    return metadata_;
+  }
+
+  UserMetaData* user_metadata() const {
+    return user_metadata_.get();
+  }
+
+  std::shared_ptr SetUserMetadata(
+      std::shared_ptr user_meta) {
+    std::swap(user_metadata_, user_meta);
+    return user_meta;
+  }
+
+  virtual std::string ToString() const;
+
+ private:
+  // The ID of the operation captured by this node.
+  OpKind op_;
+  size_t num_outputs_ = 1;
+
+  // The IR specific metadata attached to the IR node.
+  MetaData metadata_;
+  // The IR framework user can attach a user defined metadata object deriving
+  // from UserMetaData.
+  std::shared_ptr user_metadata_;
+
+ protected:
+  // Adds node's index output number as operand.
+  void AddOperand(NodePtr node, size_t index = 0);
+
+  std::vector shapes_;
+  // A node holds a real reference to its operands.
+  std::vector operands_;
+  // Outputs do not hold references on the nodes, and neither do the uses, since
+  // otherwise we get into circular reference counting.
+  std::vector operands_as_outputs_;
+};
+
+inline std::ostream& operator<<(std::ostream& stream, const Node& node) {
+  stream << node.ToString();
+  return stream;
+}
+
+// Note: Keep this version of NodeCast for smooth PyTorch/XLA migration, and
+// clean up once the migration is done.
+template 
+const T* NodeCast(const Node* node, OpKind op) {
+  if (op != node->op()) {
+    return nullptr;
+  }
+#ifdef NDEBUG
+  return static_cast(node);
+#else
+  return &dynamic_cast(*node);
+#endif
+}
+
+template 
+const T* NodeCast(const Node* node) {
+  if (T::ClassOpKind() != node->op()) {
+    return nullptr;
+  }
+  // TODO: Some IR classes share the same opkind, such as Mean and MeanDim, so
+  // static_cast is not safe here. Unless we have opkind unique for each class,
+  // we have to use dynamic_cast here.
+  return dynamic_cast(node);
+}
+
+// Represents a specific output produced by a node. Since the output of a node
+// can be composed by multiple outputs, the node+index coordinates fully qualify
+// each single output.
+struct TORCH_API Output {
+  struct Hasher {
+    size_t operator()(const Output& output) const;
+  };
+
+  Output() = default;
+  explicit Output(const Node* node, size_t index = 0)
+      : node(node), index(index) {}
+
+  hash_t hash() const;
+  hash_t shapeHash() const;
+
+  bool operator==(const Output& rhs) const {
+    return node == rhs.node && index == rhs.index;
+  }
+
+  // To compare the operands of to-be-constructed node and to-be-reused node
+  bool operator==(const Value& rhs) const;
+
+  bool operator!=(const Output& rhs) const {
+    return !operator==(rhs);
+  }
+
+  const Shape& shape() const {
+    return node->shape(index);
+  }
+
+  std::string ToString() const;
+
+  // The node providing the output.
+  const Node* node{nullptr};
+  // The index in the node's output this output refers to.
+  size_t index{0};
+};
+
+inline std::ostream& operator<<(std::ostream& stream, const Output& output) {
+  stream << output.ToString();
+  return stream;
+}
+
+template 
+using OutputMap = std::unordered_map;
+
+// Represents an input/operand for a Node object.
+struct TORCH_API Value {
+  Value() = default;
+  /* implicit */ Value(NodePtr&& node, size_t index = 0)
+      : node(std::move(node)), index(index) {}
+  /* implicit */ Value(const NodePtr& node, size_t index = 0)
+      : node(node), index(index) {}
+
+  hash_t hash() const;
+  hash_t shapeHash() const;
+
+  operator bool() const {
+    return node != nullptr;
+  }
+
+  operator Output() const {
+    return Output(node.get(), index);
+  }
+
+  const Shape& shape() const {
+    return node->shape(index);
+  }
+
+  Node* operator->() const {
+    return node.get();
+  }
+
+  NodePtr node;
+  size_t index = 0;
+};
+
+} // namespace lazy
+} // namespace torch
+
+namespace c10 {
+// Explicit template instantiation to make ArrayRef work
+template class at::ArrayRef;
+} // namespace c10
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/ir_builder.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/ir_builder.h
new file mode 100644
index 0000000000000000000000000000000000000000..570dc942e6a68afc240cfdf93b29a496b279da40
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/ir_builder.h
@@ -0,0 +1,150 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+// This file is part of the backend interface. So, ops shouldn't be added or
+// removed without due process The exception to this being the view ops which
+// will be removed soon pending functionalization
+
+namespace torch {
+namespace lazy {
+
+template 
+NodePtr ReuseNode(Args&&... args) {
+  if (FLAGS_torch_lazy_reuse_ir) {
+    return LookupNodeFromTrieCache(std::forward(args)...);
+  }
+  return nullptr;
+}
+
+// Caching an IR node into TrieCache
+static inline void CacheNode(NodePtr node) {
+  if (FLAGS_torch_lazy_reuse_ir) {
+    TrieCache::Get()->Insert(std::move(node));
+  }
+}
+
+template 
+NodePtr MakeNode(Args&&... args) {
+  return std::make_shared(std::forward(args)...);
+}
+
+// op is passed in for a more efficient node casting, see the implementation of
+// NodeCast
+template 
+NodePtr ReuseOrMakeNode(Args&&... args) {
+  NodePtr node = ReuseNode(std::forward(args)...);
+  if (!node) {
+    node = MakeNode(std::forward(args)...);
+    CacheNode(node);
+  }
+  return node;
+}
+
+struct IrBuilder {
+  virtual NodePtr MakeDeviceData(
+      const std::shared_ptr& data) const = 0;
+  virtual NodePtr MakeScalar(
+      const at::Scalar& value,
+      const at::ScalarType& type) const = 0;
+  virtual NodePtr MakeExpand(
+      const Value& input0,
+      const std::vector& size,
+      const bool& is_scalar_expand) const = 0;
+  virtual NodePtr MakeCast(
+      const Value& input0,
+      const at::ScalarType& dtype,
+      const std::optional& stype = std::nullopt) const = 0;
+  virtual NodePtr MakeTensorList(const OpList& inputs) const = 0;
+  virtual NodePtr MakeGeneric(
+      const OpKind& op,
+      const OpList& operands,
+      const Shape& shape,
+      const size_t& num_outputs = 1,
+      const hash_t& hash_seed = static_cast(0x5a2d296e9)) const = 0;
+
+  // dynamic ir nodes
+  virtual NodePtr MakeSizeNode(const Value& input, size_t dim) const = 0;
+  virtual NodePtr MakeSizeAdd(const Value& a, const Value& b) const = 0;
+  virtual NodePtr MakeSizeMul(const Value& a, const Value& b) const = 0;
+  virtual NodePtr MakeSizeDiv(const Value& a, const Value& b) const = 0;
+
+  virtual ~IrBuilder() = default;
+};
+
+static inline NodePtr MakeDeviceData(const std::shared_ptr& data) {
+  return getIrBuilder()->MakeDeviceData(data);
+}
+static inline NodePtr MakeScalar(
+    const at::Scalar& value,
+    const at::ScalarType& type) {
+  return getIrBuilder()->MakeScalar(value, type);
+}
+static inline NodePtr MakeExpand(
+    const Value& input0,
+    const std::vector& size,
+    const bool& is_scalar_expand) {
+  return getIrBuilder()->MakeExpand(input0, size, is_scalar_expand);
+}
+static inline NodePtr MakeCast(
+    const Value& input0,
+    const at::ScalarType& dtype,
+    const std::optional& stype = std::nullopt) {
+  return getIrBuilder()->MakeCast(input0, dtype, stype);
+}
+static inline NodePtr MakeTensorList(const OpList& inputs) {
+  return getIrBuilder()->MakeTensorList(inputs);
+}
+static inline NodePtr MakeGeneric(
+    const OpKind& op,
+    const OpList& operands,
+    const Shape& shape,
+    const size_t& num_outputs = 1,
+    const hash_t& hash_seed = static_cast(0x5a2d296e9)) {
+  return getIrBuilder()->MakeGeneric(
+      op, operands, shape, num_outputs, hash_seed);
+}
+
+// dynamic ir nodes
+static inline NodePtr MakeSizeNode(const Value& input, size_t dim) {
+  return getIrBuilder()->MakeSizeNode(input, dim);
+}
+static inline NodePtr MakeSizeAdd(const Value& a, const Value& b) {
+  return getIrBuilder()->MakeSizeAdd(a, b);
+}
+static inline NodePtr MakeSizeMul(const Value& a, const Value& b) {
+  return getIrBuilder()->MakeSizeAdd(a, b);
+}
+static inline NodePtr MakeSizeDiv(const Value& a, const Value& b) {
+  return getIrBuilder()->MakeSizeDiv(a, b);
+}
+
+inline Value GetSymIntValue(c10::SymInt a) {
+  if (auto ma = a.maybe_as_int()) {
+    return Value(MakeScalar(*ma, at::kLong), 0);
+  } else {
+    return Value(
+        dynamic_cast(a.toSymNodeImplUnowned())
+            ->node_,
+        0);
+  }
+}
+
+// TODO: this should return Value
+inline std::vector GetSymIntArrayRefValue(c10::SymIntArrayRef arr) {
+  std::vector r;
+  for (const auto& a : arr) {
+    r.emplace_back(a.guard_int(__FILE__, __LINE__));
+  }
+  return r;
+}
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/ir_dump_util.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/ir_dump_util.h
new file mode 100644
index 0000000000000000000000000000000000000000..4b4e1e0749b24f619e2d97f41fba31b24d8fd31f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/ir_dump_util.h
@@ -0,0 +1,32 @@
+#pragma once
+
+#include 
+
+#include 
+
+namespace torch {
+namespace lazy {
+
+class BackendDevice;
+
+class TORCH_API DumpUtil {
+ public:
+  static std::string ToDot(c10::ArrayRef nodes);
+
+  static std::string PostOrderToDot(
+      c10::ArrayRef post_order,
+      c10::ArrayRef roots);
+
+  static std::string ToText(c10::ArrayRef nodes);
+
+  static std::string PostOrderToText(
+      c10::ArrayRef post_order,
+      c10::ArrayRef roots);
+
+  static std::string ToBackend(
+      c10::ArrayRef values,
+      const BackendDevice& device);
+};
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/ir_metadata.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/ir_metadata.h
new file mode 100644
index 0000000000000000000000000000000000000000..435785df8ff42bbf105c3c788b8e75c976b1d70b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/ir_metadata.h
@@ -0,0 +1,49 @@
+#pragma once
+
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace lazy {
+struct SourceLocation {
+  std::string file;
+  std::string function;
+  int line = -1;
+};
+
+TORCH_API void EmitShortFrameInfo(
+    std::ostream& stream,
+    const std::vector& frames);
+
+TORCH_API std::ostream& operator<<(
+    std::ostream& stream,
+    const std::vector& frames);
+
+// The base class for user defined metadata which is possible to attach to IR
+// nodes.
+struct TORCH_API UserMetaData {
+  virtual ~UserMetaData() = default;
+};
+
+struct TORCH_API MetaData {
+  std::string scope;
+  std::vector frame_info;
+};
+
+// TODO(whc) is this going to be used outside of in IR decompositions?
+// RAII data structure to be used a stack variable to enter a new IR scope. IR
+// scope names will appear in the IR and will help identifying the source of the
+// single IR nodes.
+struct TORCH_API ScopePusher {
+  explicit ScopePusher(const std::string& name);
+  ~ScopePusher();
+
+  static void ResetScopes();
+};
+
+TORCH_API MetaData GetMetaDataIfDebugging();
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/ir_util.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/ir_util.h
new file mode 100644
index 0000000000000000000000000000000000000000..df3d0fd7ac406dce34e0e9ce4cab85ab6e3f130e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/ir_util.h
@@ -0,0 +1,47 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+
+namespace torch {
+namespace lazy {
+
+class TORCH_API Util {
+ public:
+  // Tracks the emission status of the nodes during the post-order generation.
+  // It helps tracking loops within the computation graphs.
+  enum EmitStatus {
+    kNotEmitted,
+    kEmitting,
+    kEmitted,
+  };
+
+  using EmissionMap = std::unordered_map;
+
+  // Computes the post order from the given node, without using recursion. The
+  // emission map can be used as saved state, for multiple separate calls to
+  // this API. The returned post-order can be empty if the node has already been
+  // emitted inside the emission map. An error is generated if a loop is
+  // detected.
+  static std::vector ComputePostOrder(
+      const Node* node,
+      EmissionMap* emap);
+
+  static std::vector ComputePostOrder(
+      c10::ArrayRef nodes,
+      EmissionMap* emap);
+
+  // Same as above, but computes the post order on the set of nodes specified as
+  // argument.
+  static std::vector ComputePostOrder(
+      c10::ArrayRef nodes);
+
+  // Retrieves the number of nodes within the graph whose sink are passed in the
+  // nodes argument.
+  static size_t GetGraphSize(c10::ArrayRef nodes);
+};
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/lazy_graph_executor.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/lazy_graph_executor.h
new file mode 100644
index 0000000000000000000000000000000000000000..d2edbb75ffba338bcc79e33e529fdd3005b3f1dc
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/lazy_graph_executor.h
@@ -0,0 +1,426 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace lazy {
+
+class TORCH_API LazyGraphExecutor {
+ public:
+  struct DeviceDataInfo : public BackendData::Info {
+    DeviceDataInfo(int64_t tensor_id, bool read_only)
+        : tensor_id(tensor_id), read_only(read_only) {}
+
+    int64_t tensor_id = 0;
+    bool read_only = false;
+  };
+
+  // Register a lazy graph executor instance that can be retrieved using Get()
+  static void Register(LazyGraphExecutor*);
+  static LazyGraphExecutor* Get();
+
+  virtual ~LazyGraphExecutor() = default;
+
+  // Override these methods to perform custom tensor registration and
+  // unregistration Note: It is vital that the parent implementations are also
+  // called in order for the tensors to show up in the live tensor list
+  virtual void RegisterTensor(std::shared_ptr data);
+  virtual void UnregisterTensor(LazyTensor::Data* data);
+
+  // Seed for random generator.
+  // Override to supply your own DeviceContextArena.
+  virtual Value GetRngSeed(const BackendDevice& device);
+  virtual uint64_t GetRunningSeed(const BackendDevice& device);
+  virtual void SetRngSeed(const BackendDevice& device, uint64_t seed);
+
+  void DeviceBarrier(const BackendDevice& device);
+
+  BackendDataPtr GetDeviceData(
+      const at::Tensor& tensor,
+      const BackendDevice& device);
+
+  BackendDataPtr GetDeviceData(
+      const at::Scalar& value,
+      at::ScalarType scalar_type,
+      const BackendDevice& device);
+
+  // Retrieves the set of lazy tensors which are currently live in the system,
+  // for the given device. If device is nullptr, the live tensors for all
+  // devices will be returned. Returned tensors are sorted by device as primary
+  // key, and by unique ID as secondary key.
+  std::vector GetLiveTensors(const BackendDevice* device);
+
+  // Makes sure that any outstanding IR operation accumulated over live tensors,
+  // gets turned into device data. If wait is true, the sync operation will be
+  // run synchronously. The devices argument, if not empty, tells the devices
+  // which should be partecipating into the replicated computation.
+  virtual void SyncLiveTensorsGraph(
+      const BackendDevice* device,
+      c10::ArrayRef devices,
+      bool wait);
+
+  // Applies all the pending IR operations queued over the input tensors. All
+  // the tensors must be on the same device. If wait is true, the sync operation
+  // will be run synchronously. The devices argument, if not empty, tells the
+  // devices which should be partecipating into the replicated computation.
+  void SyncTensorsGraph(
+      std::vector* tensors,
+      c10::ArrayRef devices,
+      bool wait,
+      bool sync_ltc_data);
+
+  // Marks an execution step, which allows the tensor framework to understand
+  // the computation boundaries.
+  // Override to supply your own DeviceContextArena.
+  virtual void MarkStep(const BackendDevice& device);
+
+  // Waits for all the outstanding operations on all the supplied devices.
+  // If devices is empty, the wait will happen for all local devices.
+  void WaitDeviceOps(c10::ArrayRef devices);
+
+  // Retrieves the PyTorch CPU tensors behind the lazy tensors IR operations.
+  // All the tensors must be on the same device.
+  std::vector GetTensors(std::vector* tensors);
+
+  size_t IncTrimCounter() const;
+
+  // Dumps the backend specific text of the computation accumulated in the graph
+  // which is attached the tensors.
+  std::string DumpBackendComputation(const std::vector& tensors);
+
+  Value GetDeviceDataIrValue(
+      const at::Scalar& value,
+      c10::ScalarType type,
+      const BackendDevice& device);
+  Value GetIrValueForScalar(
+      const at::Scalar& value,
+      c10::ScalarType type,
+      const BackendDevice& device);
+  Value GetIrValueForScalar(
+      const at::Scalar& value,
+      const BackendDevice& device);
+
+  // TODO: even though this API is currently used **only** in codegen to
+  // generate real scalar IR values vs scalar tensors, we would like to
+  // use it in other cases where `GetIrValueForXXXScalar` is used, as well
+  // In order to do that, we need to untangle the cases where we don't need
+  // `expand` and where we don't expect a scalar tensor
+  Value GetIrValueForScalarFromCodegen(
+      const at::Scalar& value,
+      const BackendDevice& device);
+  Value GetIrValueForExpandedScalar(
+      const at::Scalar& value,
+      const Shape& shape,
+      const BackendDevice& device);
+
+  struct CachedComputation {
+    explicit CachedComputation(ComputationPtr computation)
+        : computation(std::move(computation)) {}
+
+    ComputationPtr computation;
+  };
+
+  using ComputationCache = Cache;
+
+  ComputationCache* GetComputationCache();
+
+  hash_t GetGraphHash(const std::vector& tensors);
+
+ protected:
+  // TODO(alanwaketan): Revisit if all of them need to be accessible to
+  // derived classes.
+
+  struct SyncTensorsConfig {
+    // Whether we want to force data on the target tensors (hence trimming
+    // the IR graph above them).
+    bool force_ltc_data = true;
+    // Whether when setting the data, the other properties of the tensor
+    // state should be reset.
+    bool sync_ltc_data = true;
+  };
+
+  struct SyncTensorCollection {
+    SyncTensorCollection() : hash(0) {}
+
+    SyncTensorsConfig config;
+    std::vector indices;
+    hash_t hash;
+    std::vector unlocker;
+    BackendDevice device;
+  };
+
+  struct PostOrderData {
+    std::vector post_order;
+    Util::EmissionMap emission_map;
+    std::vector parameters_data;
+    std::vector parameter_sequence;
+  };
+
+  // Locking:
+  // We perform two kinds of operations of tensors, synchronous and
+  // asynchronous. The ApplyPendingGraph() are synchronous, as we need the
+  // device data result immediately. Before the synchronous operations can
+  // start, they need to wait that the pending asynchronous operations have
+  // completed. Synchronous operations do not hold device locks, since they are
+  // strictly sequential, dictated by the PyTorch execution order. The
+  // SyncTensorsGraph() is asynchronous, and returns immediately after having
+  // scheduled the asynchronous operation. While executing, the asynchronous
+  // operations will hold locks on all the participating devices (in most common
+  // cases there will be only one device).
+  // Since asynchronous operations capture device locks, only one asynchronous
+  // operation can execute at the same time, on a given device. Tensor
+  // operations which send data to device do not need to hold any device locks
+  // while doing so. Only operations which _use_ device data (computations, and
+  // transfer from server) need to wait for asynchronous operations to complete
+  // (barrier).
+
+  class DeviceLocker {
+   public:
+    explicit DeviceLocker(BackendDevice device) : device_(std::move(device)) {}
+
+    const BackendDevice& device() const {
+      return device_;
+    }
+
+    void Lock();
+    void Unlock(std::exception_ptr exptr);
+    void Barrier();
+
+   private:
+    void CheckResetException();
+
+    BackendDevice device_;
+    std::mutex mutex_;
+    std::condition_variable cv_;
+    bool locked_ = false;
+    std::exception_ptr exptr_;
+  };
+
+  class DeviceLockerArena {
+   public:
+    static DeviceLockerArena* Get();
+
+    std::shared_ptr GetLocker(const BackendDevice& device);
+
+    void DeviceBarrier(const BackendDevice& device);
+
+    // Use a set to impose an order on the device locking sequence (ABBA
+    // prevention).
+    std::vector LockDevices(
+        const std::set& devices);
+
+   private:
+    ExceptionCleanup LockDevice(const BackendDevice& device);
+
+    std::mutex mutex_;
+    std::map> lockers_;
+  };
+
+  class DataCacheArena {
+   public:
+    static DataCacheArena* Get();
+
+    BackendDataPtr GetDeviceData(
+        const at::Tensor& tensor,
+        const BackendDevice& device);
+
+    BackendDataPtr GetDeviceData(
+        const at::Scalar& value,
+        at::ScalarType scalar_type,
+        const BackendDevice& device);
+
+   private:
+    struct TensorHasher {
+      size_t operator()(const at::Tensor& tensor) const;
+    };
+    struct TensorComparer {
+      bool operator()(const at::Tensor& tensor1, const at::Tensor& tensor2)
+          const;
+    };
+
+    explicit DataCacheArena(size_t max_cache_size);
+
+    using DataCache =
+        Cache;
+
+    DataCache* GetDataCache(const BackendDevice& device);
+
+    size_t max_cache_size_ = 0;
+    std::mutex mutex_;
+    std::map> device_caches_;
+  };
+
+  // The DeviceContextArena holds per device live information and statistics,
+  // among which the lazy tensors which are currently alive in the system. This
+  // is used to create computation "barriers" in order to flush pending
+  // operations and ensure the same computations are created during the training
+  // loops.
+  // TODO(alanwaketan): Add a registry such that we don't need to make all
+  // related methods virtual.
+  class DeviceContextArena {
+   protected:
+    struct DeviceContext {
+      std::mutex lock;
+      std::map> tensors_data;
+      uint64_t seed = 101;
+      uint64_t running_seed = 101;
+      Value seed_ir_value;
+    };
+
+   public:
+    static DeviceContextArena* Get();
+    virtual ~DeviceContextArena() = default;
+
+    void RegisterTensor(std::shared_ptr data);
+    void UnregisterTensor(LazyTensor::Data* data);
+
+    std::vector GetLiveTensors(const BackendDevice* device);
+
+    // Overriding it allow derived class to use their own IRs for Value.
+    virtual Value GetRngSeed(const BackendDevice& device);
+    uint64_t GetRunningSeed(const BackendDevice& device);
+    void SetRngSeed(const BackendDevice& device, uint64_t seed);
+
+    void MarkStep(const BackendDevice& device);
+
+    std::vector GetActiveDevices();
+
+   protected:
+    DeviceContext* GetDeviceContext(const BackendDevice& device);
+
+    void ForAllDeviceContexts(
+        const std::function& fn,
+        const BackendDevice* device);
+
+    // Overriding it allow derived class to use their own conversions.
+    virtual Value IrValueFromScalar(
+        const at::Scalar& value,
+        at::ScalarType scalar_type,
+        const BackendDevice& device);
+
+   private:
+    std::vector GetAllDeviceContexts();
+
+    std::mutex lock_;
+    std::map device_contexts_;
+  };
+
+  struct Async {
+    Async(
+        SyncTensorCollection* coll,
+        std::vector parameters_data,
+        std::vector tensors_data,
+        ComputationCache::TypePtr cached_computation);
+    virtual ~Async() = default;
+
+    void Wait();
+
+    MultiWait mwait;
+    std::vector indices;
+    std::vector unlocker;
+    std::vector parameters_data;
+    BackendDevice device;
+    ComputationCache::TypePtr cached_computation;
+    std::vector tensors_data;
+  };
+
+  void ResetTrimCounter() const;
+
+  // Waits for this SyncTensorCollection's device barrier and acquire the lock.
+  virtual void TensorCollectionBarrier(SyncTensorCollection* coll);
+
+  // One can override to insert your own profiler.
+  virtual PostOrderData RunPostOrder(
+      const std::vector& ir_values,
+      SyncTensorCollection* coll);
+
+ private:
+  struct CompilationResult {
+    BackendDevice device;
+    size_t emitted_nodes = 0;
+    ComputationPtr computation;
+    std::vector parameters_data;
+  };
+
+  virtual bool ShouldSyncTensor(const LazyTensorPtr& tensor) const;
+
+  SyncTensorCollection CollectSyncTensors(
+      const std::vector& tensors,
+      const SyncTensorsConfig& config);
+
+  std::vector CollectRoots(
+      const std::vector& tensors,
+      c10::ArrayRef indices);
+
+  std::vector SetTensorData(
+      std::vector* tensors,
+      const SyncTensorsConfig& config,
+      c10::ArrayRef indices,
+      const std::vector& tensor_data_vec);
+
+  void ExtractIRAndPrepareTensorData(
+      std::vector* tensors,
+      const SyncTensorsConfig& config,
+      c10::ArrayRef indices,
+      std::vector& ir_values,
+      std::vector& tensor_data_vec);
+
+  std::shared_ptr TryRunCachedSync(
+      std::vector* tensors,
+      SyncTensorCollection* coll,
+      PostOrderData* po_data,
+      const std::vector& tensor_data_vec);
+
+  CompilationResult Compile(
+      const std::vector& tensors,
+      c10::ArrayRef devices,
+      const SyncTensorCollection& coll,
+      PostOrderData* po_data,
+      const std::vector& ir_values);
+
+  ComputationCache::TypePtr LookupCachedCompile(const hash_t& hash);
+
+  std::shared_ptr SyncTensorsGraphInternal(
+      std::vector* tensors,
+      c10::ArrayRef devices,
+      const SyncTensorsConfig& config);
+
+  // Schedules the execution of a sync tensors operation in background. The
+  // asynchronous operation will hold the device locks by capturing the ones
+  // present within the coll structure.
+  std::shared_ptr ScheduleSyncTensorsGraph(
+      SyncTensorCollection* coll,
+      std::vector parameters_data,
+      std::vector tensors_data,
+      ComputationCache::TypePtr cached_computation);
+
+  std::shared_ptr ScheduleSyncTensorsGraph(
+      std::vector* tensors,
+      SyncTensorCollection* coll,
+      std::vector parameters_data,
+      ComputationCache::TypePtr cached_computation,
+      const std::vector& tensor_data_vec);
+
+  std::vector GetTensorsFused(std::vector* tensors);
+
+  std::vector FetchTensors(
+      std::vector* tensors,
+      c10::ArrayRef tensors_data,
+      const std::vector* indices);
+
+  // Gathers the device data for all the input tensors, after an
+  // asynchronous operation.
+  std::vector GatherTensorsData(
+      const std::vector& tensors,
+      c10::ArrayRef indices,
+      c10::ArrayRef tensors_data);
+};
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/metrics.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/metrics.h
new file mode 100644
index 0000000000000000000000000000000000000000..b651ecea24ec334bf5de4591552c9f733f4dc718
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/metrics.h
@@ -0,0 +1,286 @@
+/**
+ * This file is adapted from PyTorch/XLA
+ * https://github.com/pytorch/xla/blob/master/third_party/xla_client/metrics.h
+ */
+
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+namespace torch {
+namespace lazy {
+
+struct TORCH_API Sample {
+  Sample() = default;
+  Sample(int64_t timestamp_ns, double value)
+      : timestamp_ns(timestamp_ns), value(value) {}
+
+  int64_t timestamp_ns = 0;
+  double value = 0;
+};
+
+using MetricReprFn = std::function;
+
+// Class used to collect time-stamped numeric samples. The samples are stored in
+// a circular buffer whose size can be configured at constructor time.
+class TORCH_API MetricData {
+ public:
+  // Creates a new MetricData object with the internal circular buffer storing
+  // max_samples samples. The repr_fn argument allow to specify a function which
+  // pretty-prints a sample value.
+  MetricData(MetricReprFn repr_fn, size_t max_samples);
+
+  // Returns the total values of all the samples being posted to this metric.
+  double Accumulator() const;
+
+  size_t TotalSamples() const;
+
+  void AddSample(int64_t timestamp_ns, double value);
+
+  // Returns a vector with all the current samples, from the oldest to the
+  // newer. If accumulator is not nullptr, it will receive the current value of
+  // the metrics' accumulator (the sum of all posted values). If total_samples
+  // is not nullptr, it will receive the count of the posted values.
+  std::vector Samples(double* accumulator, size_t* total_samples) const;
+
+  std::string Repr(double value) const {
+    return repr_fn_(value);
+  }
+
+  void Reset();
+
+  bool IsValid() const {
+    return TotalSamples() > 0;
+  }
+
+ private:
+  mutable std::mutex lock_;
+  MetricReprFn repr_fn_;
+  size_t count_ = 0;
+  std::vector samples_;
+  double accumulator_ = 0.0;
+};
+
+// Counters are a very lightweight form of metrics which do not need to track
+// sample time.
+class TORCH_API CounterData {
+ public:
+  CounterData() : value_(0) {}
+
+  void AddValue(int64_t value) {
+    value_ += value;
+  }
+
+  int64_t Value() const {
+    return value_;
+  }
+
+  void Reset() {
+    value_ = 0;
+  }
+
+  bool IsValid() const {
+    return value_ > 0;
+  }
+
+ private:
+  std::atomic value_;
+};
+
+class TORCH_API MetricsArena {
+ public:
+  static MetricsArena* Get();
+
+  void ResetCounters();
+  void ResetMetrics();
+
+  // Registers a new metric in the global arena.
+  void RegisterMetric(
+      const std::string& name,
+      MetricReprFn repr_fn,
+      size_t max_samples,
+      std::shared_ptr* data);
+
+  void RegisterCounter(
+      const std::string& name,
+      std::shared_ptr* data);
+
+  void ForEachMetric(
+      const std::function& metric_func);
+
+  void ForEachCounter(
+      const std::function&
+          counter_func);
+
+  std::vector GetMetricNames();
+
+  MetricData* GetMetric(const std::string& name);
+
+  std::vector GetCounterNames();
+
+  CounterData* GetCounter(const std::string& name);
+
+ private:
+  std::mutex lock_;
+  std::map> metrics_;
+  std::map> counters_;
+};
+
+// Emits the value in a to_string() conversion.
+TORCH_API std::string MetricFnValue(double value);
+// Emits the value in a humanized bytes representation.
+TORCH_API std::string MetricFnBytes(double value);
+// Emits the value in a humanized time representation. The value is expressed in
+// nanoseconds EPOCH time.
+TORCH_API std::string MetricFnTime(double value);
+
+// The typical use of a Metric is one in which it gets created either in a
+// global scope context:
+//   static Metric* metric = new Metric("RpcCount");
+// Or within a function scope:
+//   void MyFunction(...) {
+//     static Metric* metric = new Metric("RpcCount");
+//     ...
+//     metric->AddSample(ts_nanos, some_value);
+//   }
+class TORCH_API Metric {
+ public:
+  explicit Metric(
+      std::string name,
+      MetricReprFn repr_fn = MetricFnValue,
+      size_t max_samples = 0);
+
+  const std::string& Name() const {
+    return name_;
+  }
+
+  double Accumulator() const;
+
+  void AddSample(int64_t timestamp_ns, double value);
+
+  void AddSample(double value);
+
+  std::vector Samples(double* accumulator, size_t* total_samples) const;
+
+  std::string Repr(double value) const;
+
+ private:
+  MetricData* GetData() const;
+
+  std::string name_;
+  MetricReprFn repr_fn_;
+  size_t max_samples_;
+  mutable std::shared_ptr data_ptr_;
+  mutable std::atomic data_;
+};
+
+// A Counter is a lightweight form of metric which tracks an integer value which
+// can increase or decrease.
+// A typical use is as:
+//   static Counter* counter = new Counter("MyCounter");
+//   ...
+//   counter->AddValue(+1);
+class TORCH_API Counter {
+ public:
+  explicit Counter(std::string name);
+
+  void AddValue(int64_t value) {
+    GetData()->AddValue(value);
+  }
+
+  int64_t Value() const {
+    return GetData()->Value();
+  }
+
+ private:
+  CounterData* GetData() const;
+
+  std::string name_;
+  mutable std::shared_ptr data_ptr_;
+  mutable std::atomic data_;
+};
+
+#define TORCH_LAZY_COUNTER(name, value)        \
+  do {                                         \
+    static ::torch::lazy::Counter* __counter = \
+        new ::torch::lazy::Counter(name);      \
+    __counter->AddValue(value);                \
+  } while (0)
+
+#define TORCH_LAZY_FN_COUNTER(ns) TORCH_LAZY_COUNTER(c10::str(ns, __func__), 1)
+
+#define TORCH_LAZY_VALUE_METRIC(name, value)                         \
+  do {                                                               \
+    static ::torch::lazy::Metric* __metric =                         \
+        new ::torch::lazy::Metric(name, torch::lazy::MetricFnValue); \
+    __metric->AddSample(value);                                      \
+  } while (0)
+
+// Creates a report with the current metrics statistics.
+TORCH_API std::string CreateMetricReport();
+
+// Creates a report with the selected metrics statistics.
+TORCH_API std::string CreateMetricReport(
+    const std::vector& counter_names,
+    const std::vector& metric_names);
+
+// Returns the currently registered metric names. Note that the list can grow
+// since metrics are usually function intialized (they are static function
+// variables).
+TORCH_API std::vector GetMetricNames();
+
+// Retrieves the metric data of a given metric, or nullptr if such metric does
+// not exist.
+TORCH_API MetricData* GetMetric(const std::string& name);
+
+// Returns the currently registered counter names. Note that the list can grow
+// since counters are usually function intialized (they are static function
+// variables).
+TORCH_API std::vector GetCounterNames();
+
+// Retrieves the counter data of a given counter, or nullptr if such counter
+// does not exist.
+TORCH_API CounterData* GetCounter(const std::string& name);
+
+// Retrieves the current EPOCH time in nanoseconds.
+TORCH_API int64_t NowNs();
+
+// Scope based utility class TORCH_API to measure the time the code takes within
+// a given C++ scope.
+class TORCH_API TimedSection {
+ public:
+  explicit TimedSection(Metric* metric) : metric_(metric), start_(NowNs()) {}
+
+  ~TimedSection() {
+    int64_t now = NowNs();
+    metric_->AddSample(now, now - start_);
+  }
+
+  double Elapsed() const {
+    return 1e-9 * static_cast(NowNs() - start_);
+  }
+
+ private:
+  Metric* metric_;
+  int64_t start_;
+};
+
+#define TORCH_LAZY_TIMED(name)                                  \
+  static torch::lazy::Metric* timed_metric =                    \
+      new torch::lazy::Metric(name, torch::lazy::MetricFnTime); \
+  torch::lazy::TimedSection timed_section(timed_metric)
+
+#define TORCH_LAZY_FN_COUNTER_TIMED_TRACING(ns) \
+  TORCH_LAZY_FN_COUNTER(ns);                    \
+  TORCH_LAZY_TIMED("LazyTracing")
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/multi_wait.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/multi_wait.h
new file mode 100644
index 0000000000000000000000000000000000000000..d970b008e1b6b81ca7ad7535e98bedb702fc93a7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/multi_wait.h
@@ -0,0 +1,62 @@
+/**
+ * This file is adapted from PyTorch/XLA
+ * https://github.com/pytorch/xla/blob/master/third_party/xla_client/multi_wait.h
+ */
+
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+namespace torch {
+namespace lazy {
+
+// Support waiting for a number of tasks to complete.
+class TORCH_API MultiWait {
+ public:
+  explicit MultiWait(size_t count) : count_(count) {}
+
+  // Signal the completion of a single task.
+  void Done();
+
+  // Waits until at least count (passed as constructor value) completions
+  // happened.
+  void Wait();
+
+  // Same as above, but waits up to wait_seconds.
+  void Wait(double wait_seconds);
+
+  // Resets the threshold counter for the MultiWait object. The completed count
+  // is also reset to zero.
+  void Reset(size_t count);
+
+  // Creates a completer functor which signals the mult wait object once func
+  // has completed. Handles exceptions by signaling the multi wait with the
+  // proper status value. This API returns a function which captures a MultiWait
+  // reference, so care must be taken such that the reference remains valid for
+  // the whole lifetime of the returned function.
+  std::function Completer(std::function func);
+
+  // Similar as the above API, but with explicit capture of the MultiWait shared
+  // pointer.
+  static std::function Completer(
+      std::shared_ptr mwait,
+      std::function func);
+
+ private:
+  void Complete(const std::function& func);
+
+  std::mutex mutex_;
+  std::condition_variable cv_;
+  size_t count_ = 0;
+  size_t completed_count_ = 0;
+  std::exception_ptr exptr_;
+};
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/ops/arithmetic_ir_ops.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/ops/arithmetic_ir_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..3abb6cb3b10858a13163957c992bba80fe9c2e27
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/ops/arithmetic_ir_ops.h
@@ -0,0 +1,14 @@
+#pragma once
+
+#include 
+
+namespace torch {
+namespace lazy {
+
+TORCH_API NodePtr operator+(const Value& node1, const Value& node2);
+TORCH_API NodePtr operator-(const Value& node1, const Value& node2);
+TORCH_API NodePtr operator*(const Value& node1, const Value& node2);
+TORCH_API NodePtr operator/(const Value& node1, const Value& node2);
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/ops/utils.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/ops/utils.h
new file mode 100644
index 0000000000000000000000000000000000000000..cc5d5bdbe25bc3412d9507dad3da5631d72ae818
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/ops/utils.h
@@ -0,0 +1,41 @@
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace lazy {
+
+TORCH_API bool StrideIsSupported(c10::ArrayRef stride);
+
+TORCH_API std::vector GetArrayStridePermutation(
+    c10::ArrayRef stride);
+
+TORCH_API Shape MakeDiagonalShape(
+    const Shape& shape,
+    int64_t offset,
+    int64_t dim1,
+    int64_t dim2);
+
+TORCH_API Shape
+MakePermuteShape(const Shape& source_shape, c10::ArrayRef permutation);
+
+TORCH_API Shape MakeSelectShape(
+    const Shape& shape,
+    int64_t dim,
+    int64_t start,
+    int64_t end,
+    int64_t stride);
+
+TORCH_API int64_t GetStride(int64_t start, int64_t end, int64_t stride);
+
+TORCH_API std::vector BuildSqueezedDimensions(
+    c10::ArrayRef dimensions,
+    int64_t squeeze_dim);
+
+TORCH_API std::vector BuildUnsqueezedDimensions(
+    c10::ArrayRef dimensions,
+    int64_t squeeze_dim);
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/permutation_util.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/permutation_util.h
new file mode 100644
index 0000000000000000000000000000000000000000..7a368301035e9fd8861458ef902a4012405a9590
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/permutation_util.h
@@ -0,0 +1,43 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+
+namespace torch {
+namespace lazy {
+
+TORCH_API std::vector InversePermutation(
+    c10::ArrayRef input_permutation);
+
+TORCH_API bool IsPermutation(c10::ArrayRef permutation);
+
+// Gathers the input using the order specified by the permutation. For each i,
+// output[i] = dimensions[permutation[i]]. The given permutation must be the
+// same size as the input.
+template 
+std::vector PermuteDimensions(
+    c10::ArrayRef permutation,
+    const Container& dimensions) {
+  using T = typename Container::value_type;
+  TORCH_CHECK(
+      dimensions.size() == permutation.size(),
+      "Invalid permutation specified. dimensions.size() != permutation.size()  (",
+      dimensions.size(),
+      " vs. ",
+      permutation.size(),
+      ")");
+  TORCH_CHECK(
+      IsPermutation(permutation),
+      "Invalid permutation specified. Permutation is not permutation");
+  std::vector output(dimensions.size());
+  for (const auto i : c10::irange(permutation.size())) {
+    output[i] = dimensions[permutation[i]];
+  }
+  return output;
+}
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/shape.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/shape.h
new file mode 100644
index 0000000000000000000000000000000000000000..99e4a892bc589f93298d1caec785af1f4f1a09e4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/shape.h
@@ -0,0 +1,80 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+C10_DECLARE_bool(ltc_enable_symbolic_shapes);
+
+namespace torch {
+namespace lazy {
+
+class TORCH_API Shape {
+ public:
+  Shape() = default;
+
+  Shape(
+      at::ScalarType scalar_type,
+      c10::ArrayRef sizes,
+      std::optional> is_symbolic = std::nullopt);
+
+  std::string to_string() const;
+
+  c10::ScalarType scalar_type() const {
+    return scalar_type_;
+  }
+  void set_scalar_type(at::ScalarType value) {
+    scalar_type_ = value;
+  }
+
+  int64_t dim() const {
+    return sizes_.size();
+  }
+  c10::ArrayRef sizes() const {
+    return sizes_;
+  }
+  int64_t size(int64_t dim) const {
+    return sizes_.at(dim);
+  }
+  void set_size(int64_t dim, int64_t size) {
+    sizes_.at(dim) = size;
+  }
+
+  const std::optional>& is_symbolic() const {
+    return is_symbolic_;
+  }
+
+  // Makes a copy with symbolic dims applied
+  Shape with_symbolic_dims(
+      std::optional> symbolic_dims) const;
+
+  size_t numel() const;
+  hash_t hash(bool bakeInSizes) const;
+
+  bool operator==(const Shape& other) const;
+
+ private:
+  c10::ScalarType scalar_type_{c10::ScalarType::Undefined};
+
+  // Sizes are the upper bound sizes for a tensor, used by XLA.
+  std::vector sizes_;
+  // Stores which dimmensions are symbolic
+  // If nullopt, either it hasn't been initialized or the symbolic
+  // dimmensions are not calculatable
+  std::optional> is_symbolic_ = std::nullopt;
+};
+
+TORCH_API std::ostream& operator<<(std::ostream& out, const Shape& shape);
+
+TORCH_API bool symbolicShapeEnabled();
+// Calculate and applies symbolic shapes onto the
+// Shape objects passed to result_shapes
+TORCH_API void applySymbolicShapesOnLT(
+    const char* schema_str,
+    std::vector args,
+    std::vector& result_shapes);
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/shape_inference.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/shape_inference.h
new file mode 100644
index 0000000000000000000000000000000000000000..76ddea597a784ac7f64081f4b88b793e0e008b4e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/shape_inference.h
@@ -0,0 +1,124 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace lazy {
+// Turn clang-format off, as we rely on the whole signature being on one line
+// for codegen.
+// clang-format off
+TORCH_API std::vector compute_shape__adaptive_avg_pool2d(const at::Tensor & self, at::IntArrayRef output_size);
+TORCH_API std::vector compute_shape__adaptive_avg_pool2d_backward(const at::Tensor & grad_output, const at::Tensor & self);
+TORCH_API std::vector compute_shape__adaptive_avg_pool3d(const at::Tensor & self, at::IntArrayRef output_size);
+TORCH_API std::vector compute_shape__adaptive_avg_pool3d_backward(const at::Tensor & grad_output, const at::Tensor & self);
+TORCH_API std::vector compute_shape_abs(const at::Tensor & self);
+TORCH_API std::vector compute_shape_arange_out(const at::Scalar & start, const at::Scalar & end, const at::Scalar & step, at::Tensor & out);
+TORCH_API std::vector compute_shape_bernoulli(const at::Tensor & self, ::std::optional generator);
+TORCH_API std::vector compute_shape_bernoulli(const at::Tensor & self, double p, ::std::optional generator);
+TORCH_API std::vector compute_shape_binary_cross_entropy(const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction);
+TORCH_API std::vector compute_shape_binary_cross_entropy_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction);
+TORCH_API std::vector compute_shape_cat(at::TensorList tensors, int64_t dim);
+TORCH_API std::vector compute_shape_cholesky(const at::Tensor & self, bool upper);
+TORCH_API std::vector compute_shape_clamp_min(const at::Tensor & self, const at::Scalar & min);
+TORCH_API std::vector compute_shape_clone(const at::Tensor & self, ::std::optional memory_format);
+TORCH_API std::vector compute_shape_constant_pad_nd(const at::Tensor & self, at::IntArrayRef pad, const at::Scalar & value);
+TORCH_API std::vector compute_shape_convolution(const at::Tensor & input, const at::Tensor & weight, const ::std::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups);
+TORCH_API std::vector compute_shape_convolution_backward(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::OptionalIntArrayRef bias_sizes, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, ::std::array output_mask);
+TORCH_API std::vector compute_shape_embedding(const at::Tensor & weight, const at::Tensor & indices, int64_t padding_idx, bool scale_grad_by_freq, bool sparse);
+TORCH_API std::vector compute_shape_embedding_dense_backward(const at::Tensor & grad_output, const at::Tensor & indices, int64_t num_weights, int64_t padding_idx, bool scale_grad_by_freq);
+TORCH_API std::vector compute_shape_expand(const at::Tensor & self, at::IntArrayRef size, bool implicit);
+TORCH_API std::vector compute_shape_expand(const at::Tensor & self, c10::SymIntArrayRef size, bool implicit);
+TORCH_API std::vector compute_shape_flip(const at::Tensor & self, at::IntArrayRef dims);
+TORCH_API std::vector compute_shape_glu_backward(const at::Tensor & grad_output, const at::Tensor & self, int64_t dim);
+TORCH_API std::vector compute_shape_glu_jvp(const at::Tensor & glu, const at::Tensor & x, const at::Tensor & dx, int64_t dim);
+TORCH_API std::vector compute_shape_grid_sampler_2d(const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners);
+TORCH_API std::vector compute_shape_grid_sampler_2d_backward(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners, ::std::array output_mask);
+TORCH_API std::vector compute_shape_index_select(const at::Tensor & self, int64_t dim, const at::Tensor & index);
+TORCH_API std::vector compute_shape_inverse(const at::Tensor & self);
+TORCH_API std::vector compute_shape_isnan(const at::Tensor & self);
+TORCH_API std::vector compute_shape_log_sigmoid_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & buffer);
+TORCH_API std::vector compute_shape_log_sigmoid_forward(const at::Tensor & self);
+TORCH_API std::vector compute_shape_logdet(const at::Tensor & self);
+TORCH_API std::vector compute_shape_logical_and(const at::Tensor & self, const at::Tensor & other);
+TORCH_API std::vector compute_shape_logical_not(const at::Tensor & self);
+TORCH_API std::vector compute_shape_logical_or(const at::Tensor & self, const at::Tensor & other);
+TORCH_API std::vector compute_shape_logical_xor(const at::Tensor & self, const at::Tensor & other);
+TORCH_API std::vector compute_shape_masked_fill(const at::Tensor & self, const at::Tensor & mask, const at::Scalar & value);
+TORCH_API std::vector compute_shape_masked_fill(const at::Tensor & self, const at::Tensor & mask, const at::Tensor & value);
+TORCH_API std::vector compute_shape_max(const at::Tensor & self);
+TORCH_API std::vector compute_shape_mean(const at::Tensor & self, ::std::optional dtype);
+TORCH_API std::vector compute_shape_min(const at::Tensor & self);
+TORCH_API std::vector compute_shape_mv(const at::Tensor & self, const at::Tensor & vec);
+TORCH_API std::vector compute_shape_native_batch_norm(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, const ::std::optional & running_mean, const ::std::optional & running_var, bool training, double momentum, double eps);
+TORCH_API std::vector compute_shape_native_batch_norm_backward(const at::Tensor & grad_out, const at::Tensor & input, const ::std::optional & weight, const ::std::optional & running_mean, const ::std::optional & running_var, const ::std::optional & save_mean, const ::std::optional & save_invstd, bool train, double eps, ::std::array output_mask);
+TORCH_API std::vector compute_shape_native_dropout(const at::Tensor & input, double p, ::std::optional train);
+TORCH_API std::vector compute_shape_native_dropout_backward(const at::Tensor & grad_output, const at::Tensor & mask, double scale);
+TORCH_API std::vector compute_shape_native_layer_norm(const at::Tensor & input, at::IntArrayRef normalized_shape, const ::std::optional & weight, const ::std::optional & bias, double eps);
+TORCH_API std::vector compute_shape_native_layer_norm_backward(const at::Tensor & grad_out, const at::Tensor & input, at::IntArrayRef normalized_shape, const at::Tensor & mean, const at::Tensor & rstd, const ::std::optional & weight, const ::std::optional & bias, ::std::array output_mask);
+TORCH_API std::vector compute_shape_new_empty_strided(const at::Tensor & self, at::IntArrayRef size, at::IntArrayRef stride, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory);
+TORCH_API std::vector compute_shape_nll_loss2d_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, int64_t ignore_index, const at::Tensor & total_weight);
+TORCH_API std::vector compute_shape_nll_loss2d_forward(const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, int64_t ignore_index);
+TORCH_API std::vector compute_shape_nonzero(const at::Tensor & self);
+TORCH_API std::vector compute_shape_normal_functional(const at::Tensor & self, double mean, double std, ::std::optional generator);
+TORCH_API std::vector compute_shape_random(const at::Tensor & self, ::std::optional generator);
+TORCH_API std::vector compute_shape_random(const at::Tensor & self, int64_t to, ::std::optional generator);
+TORCH_API std::vector compute_shape_random(const at::Tensor & self, int64_t from, ::std::optional to, ::std::optional generator);
+TORCH_API std::vector compute_shape_relu(const at::Tensor & self);
+TORCH_API std::vector compute_shape_repeat(const at::Tensor & self, at::IntArrayRef repeats);
+TORCH_API std::vector compute_shape_slogdet(const at::Tensor & self);
+TORCH_API std::vector compute_shape_smooth_l1_loss_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, int64_t reduction, double beta);
+TORCH_API std::vector compute_shape_sort(const at::Tensor & self, int64_t dim, bool descending);
+TORCH_API std::vector compute_shape_stack(at::TensorList tensors, int64_t dim);
+TORCH_API std::vector compute_shape_std(const at::Tensor & self, bool unbiased);
+TORCH_API std::vector compute_shape_std(const at::Tensor & self, at::OptionalIntArrayRef dim, bool unbiased, bool keepdim);
+TORCH_API std::vector compute_shape_std(const at::Tensor & self, at::OptionalIntArrayRef dim, const ::std::optional & correction, bool keepdim);
+TORCH_API std::vector compute_shape_sum(const at::Tensor & self, ::std::optional dtype);
+TORCH_API std::vector compute_shape__to_copy(const at::Tensor & self, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory, bool non_blocking, ::std::optional memory_format);
+TORCH_API std::vector compute_shape_take(const at::Tensor & self, const at::Tensor & index);
+TORCH_API std::vector compute_shape_trace(const at::Tensor & self);
+TORCH_API std::vector compute_shape_zero(const at::Tensor & self);
+TORCH_API std::vector compute_shape_narrow_copy_symint(const at::Tensor & self, int64_t dim, int64_t start, c10::SymInt length);
+TORCH_API std::vector compute_shape_hardswish(const at::Tensor & self);
+TORCH_API std::vector compute_shape_hardswish_backward(const at::Tensor & grad_output, const at::Tensor & self);
+TORCH_API std::vector compute_shape_selu(const at::Tensor & self);
+TORCH_API std::vector compute_shape_uniform(const at::Tensor & self, double from, double to, ::std::optional generator);
+
+// Non-Native ops
+TORCH_API std::vector compute_shape_scalar(const at::Scalar& value, const at::ScalarType& type);
+TORCH_API std::vector compute_shape_expand(const Output& input0, const std::vector& size, const bool& is_scalar_expand);
+TORCH_API std::vector compute_shape_view(const Output& input0, const std::vector& output_sizes);
+TORCH_API std::vector compute_shape_cast(const Output& input0, const at::ScalarType& dtype, const ::std::optional& stype);
+
+// View Ops
+// (Now that functionalization pass is used, we should kill these in a later PR)
+TORCH_API std::vector compute_shape_as_strided_view_update(const Output& target, const Output& input, const std::vector& size, const std::vector& stride, const int64_t& storage_offset);
+TORCH_API std::vector compute_shape_as_strided(const Output& input, const std::vector& size, const std::vector& stride, const int64_t& storage_offset);
+TORCH_API std::vector compute_shape_diagonal_view_update(const Output& target, const Output& input, const int64_t& offset, const int64_t& dim1, const int64_t& dim2);
+TORCH_API std::vector compute_shape_diagonal(const Output& input, const int64_t& offset, const int64_t& dim1, const int64_t& dim2);
+TORCH_API std::vector compute_shape_narrow_view_update(const Output& input, const Output& source, const std::vector& base_indices);
+TORCH_API std::vector compute_shape_narrow(const Output& input, const std::vector& base_indices, const std::vector& sizes);
+TORCH_API std::vector compute_shape_permute(const Output& input, const std::vector& dims);
+TORCH_API std::vector compute_shape_resize(const Output& input, const std::vector& size);
+TORCH_API std::vector compute_shape_select_view_update(const Output& target, const Output& source, const int64_t& dim, const int64_t& start, const int64_t& end, const int64_t& stride);
+TORCH_API std::vector compute_shape_select(const Output& input, const int64_t& dim, const int64_t& start, const int64_t& end, const int64_t& stride);
+TORCH_API std::vector compute_shape_squeeze(const Output& input, const int& dim);
+TORCH_API std::vector compute_shape_unsqueeze(const Output& input, const int& dim);
+
+TORCH_API std::vector compute_shape_select_scatter(const at::Tensor & self, const at::Tensor & src, int64_t dim, int64_t index);
+TORCH_API std::vector compute_shape_diagonal_scatter(const at::Tensor & self, const at::Tensor & src, int64_t offset, int64_t dim1, int64_t dim2);
+TORCH_API std::vector compute_shape_slice_scatter_symint(const at::Tensor & self, const at::Tensor & src, int64_t dim, ::std::optional start, ::std::optional end, c10::SymInt step);
+TORCH_API std::vector compute_shape_as_strided_scatter_symint(const at::Tensor & self, const at::Tensor & src, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, ::std::optional storage_offset);
+// clang-format on
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/tensor.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/tensor.h
new file mode 100644
index 0000000000000000000000000000000000000000..afc52376c55452b9c295e0e2716dd0abc2a4768f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/tensor.h
@@ -0,0 +1,259 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace lazy {
+
+class TORCH_API SymNodeImpl : public c10::SymNodeImpl {
+ public:
+  SymNodeImpl(NodePtr ptr) : node_(std::move(ptr)){};
+  NodePtr node_;
+};
+
+class LazyTensor;
+using LazyTensorPtr = c10::intrusive_ptr;
+
+class TORCH_API LazyTensor : public c10::intrusive_ptr_target {
+ public:
+  // This is the core lazy tensor data structure where all the tensor data is
+  // held. The lazy tensor is nothing more than a shared pointer to a Data
+  // object.
+  struct Data {
+    Data(BackendDataPtr handle, BackendDevice device)
+        : handle(std::move(handle)),
+          device(std::move(device)),
+          unique_id(GetNextTensorId()) {}
+    Data(Value ir_value, BackendDevice device)
+        : ir_value(std::move(ir_value)),
+          device(std::move(device)),
+          unique_id(GetNextTensorId()) {}
+    Data(at::Tensor tensor_data, BackendDevice device)
+        : tensor_data(std::move(tensor_data)),
+          device(std::move(device)),
+          unique_id(GetNextTensorId()) {}
+    // TODO(alanwaketan): Remove this ctor. This is a
+    // temporary ctor to ease XLA LTC migration. It depends on
+    // XLA's Functionalization integration.
+    Data(BackendDevice device)
+        : device(std::move(device)), unique_id(GetNextTensorId()) {}
+
+    virtual ~Data();
+
+    BackendDataPtr handle;
+    Value ir_value;
+    std::optional tensor_data;
+    const BackendDevice device;
+    const int64_t unique_id = 0;
+    size_t generation = 1;
+  };
+
+  static LazyTensorPtr Create(
+      const at::Tensor& tensor,
+      const BackendDevice& device);
+  static LazyTensorPtr Create(Value ir_value, const BackendDevice& device);
+  static LazyTensorPtr Create(BackendDataPtr handle);
+  static LazyTensorPtr Create(std::shared_ptr data);
+
+  // The default ctor previously created a null LazyTensor (one with no 'data'
+  // obj). Creating a null LazyTensor is no longer possible, since the same can
+  // be achieved by creating a null LazyTensorPtr and it is way too confusing to
+  // have to check both lazy_tensor_ptr && *lazy_tensor_ptr, so everywhere that
+  // used to rely on a LazyTensor obj with a null Data can now rely on a null
+  // LazyTensorPtr instead.
+  LazyTensor() = delete;
+  LazyTensor(const LazyTensor&) = default;
+  LazyTensor(LazyTensor&&) noexcept = default;
+
+  ~LazyTensor() override = default;
+
+  size_t generation() const {
+    return data()->generation;
+  }
+
+  // Override it to use your own Shape.
+  virtual int64_t size(int64_t dim) const;
+
+  // Override it to use your own graph executor.
+  virtual at::Tensor ToTensor(bool detached);
+
+  void ShallowCopyTo(LazyTensorPtr dest) const;
+
+  // Assigns the tensor value to the lazy tensor.
+  void SetTensor(at::Tensor tensor);
+
+  void UpdateFromTensor(at::Tensor tensor, bool sync);
+  void UpdateFromTensorOut(at::Tensor tensor);
+  void UpdateFromTensorOut(const LazyTensorPtr& tensor);
+
+  const std::shared_ptr& data() const;
+
+  // Override it to use your own type conversion.
+  virtual at::ScalarType dtype() const;
+
+  MaybeRef shape() const;
+
+  const BackendDevice& GetDevice() const;
+  int64_t GetUniqueId() const;
+
+  // Fetches the data behind the tensor. If the tensor has a graph defining
+  // its current value, executes the graph and fetches the data result.
+  BackendDataPtr GetDataHandle();
+
+  // Fetches the current value of the data, which can be missing (nullptr)
+  // in case the tensor has a graph defining its current value,
+  BackendDataPtr CurrentDataHandle() const;
+
+  void SetDataHandle(BackendDataPtr handle);
+  void SetDataHandle(BackendDataPtr handle, bool sync);
+
+  // Retrieves the current IR Node, or nullptr in case no active IR Node is
+  // available.
+  Value CurrentIrValue() const;
+
+  // Retrieves the IR Node representing this LazyTensor. One will be created if
+  // missing. Note that although this is a const API, it actually changes the
+  // internal state ofthe object.
+  Value GetIrValue() const;
+
+  void SetIrValue(Value ir_value);
+  void SetInPlaceIrValue(Value ir_value);
+
+  std::optional CurrentTensorData() const;
+
+  std::vector MakeOutputTensors(NodePtr node) const;
+
+  LazyTensorPtr CopyTensorToDevice(const BackendDevice& device);
+
+  // Applies the queue of operations in preparation for using the data.
+  // Override it to use your own graph executor.
+  virtual void ApplyPendingGraph();
+
+  // Override it to set extra information.
+  virtual void AssignIrValue(Value ir_value) const;
+
+ protected:
+  explicit LazyTensor(std::shared_ptr data);
+
+  void SetTensorData(at::Tensor tensor_data);
+
+  // We build a graph accumulating operations, but at a given point we
+  // need to force a rendering, otherwise the graph can grow without control.
+  // Think:
+  //   for i in range(0, 100000):
+  //     a = a + b
+  void TryLimitGraphSize();
+
+  // Override it to instantiate your own data.
+  virtual Value GetIrValueForTensor(
+      const at::Tensor& tensor,
+      const BackendDevice& device) const;
+
+  Value CreateTensorNode(BackendDataPtr data, bool read_only) const;
+
+ private:
+  LazyTensor(const at::Tensor& tensor, const BackendDevice& device);
+  LazyTensor(Value ir_value, const BackendDevice& device);
+  explicit LazyTensor(BackendDataPtr handle);
+
+  static int64_t GetNextTensorId();
+
+  std::shared_ptr data_;
+};
+
+// Utils to convert at::Tensor to LazyTensor, and vice versa.
+
+// Section 0: c10::Tensorlist ==> lazy::TensorList
+// note: GetTensorList is not totally parallel to GetLtcTensor; A TensorList
+// skips
+//       the LazyTensor wrappers, assuming that the list of underlying IR nodes
+//       is actually more useful for downstream computations.  TBD.
+TORCH_API torch::lazy::Value GetTensorList(at::ITensorListRef tensors);
+
+// Section 1: at::Tensor => LazyTensor.
+// Extracts the LazyTensor out of an at::Tensor. Returns a null LazyTensor
+// if the tensor is not a lazy tensor.
+TORCH_API LazyTensorPtr TryGetLtcTensor(const at::Tensor& tensor);
+
+// Extracts the LazyTensor out of an at::Tensor. Throws an exception
+// if the tensor is not a lazy tensor.
+TORCH_API LazyTensorPtr GetLtcTensor(const at::Tensor& tensor);
+
+// Same as above, applied to a list of tensors.
+TORCH_API std::vector GetLtcTensors(
+    c10::ArrayRef tensors);
+
+// If tensor is a lazy tensor type, returns the LazyTensor embedded within it,
+// otherwise creates a new lazy tensor type with tensor as data.
+TORCH_API LazyTensorPtr GetOrCreateLtcTensor(
+    const std::optional& tensor,
+    const BackendDevice& device);
+
+TORCH_API LazyTensorPtr GetLtcTensorOrCreateForWrappedNumber(
+    const at::Tensor& tensor,
+    const BackendDevice& device);
+
+// Section 2: LazyTensor => at::Tensor.
+// Creates an ATen tensor from an LazyTensor.
+TORCH_API at::Tensor CreateAtenFromLtcTensor(const LazyTensorPtr& ltc_tensor);
+TORCH_API at::Tensor CreateAtenFromLtcTensor(LazyTensor&& ltc_tensor);
+
+// Note [Lazy Tensor Functionalization]
+// The functionalization pass is implemented by wrapping all TensorImpl
+// objects in C++ with an extra FunctionalTensorWrapper object,
+// that knows how to perform functionalization
+//
+// Certain functions in the aten API serve as entry/exit points for
+// functionalization, where we need to perform the wrapping/unwrapping:
+// - aten::to.device
+// - aten::empty
+
+// Given a non-lazy tensor, this function creates a lazy tensor on the specified
+// (lazy) device. The functionalize_output determines whether or not we should
+// wrap the output in a "functional wrapper".
+//
+// How do you know whether to pass true/false for functionalize_output?
+//
+// Case 1: nonlazy -> lazy
+//   If you're implementing a function that takes in nonlazy tensors and returns
+//   lazy tensors, then you should think of that function as an "entrypoint" to
+//   functionalization, and use functionalize_output=true Examples include:
+//   - factory functions (the LTC kernel for at::empty)
+//   - CPU -> Lazy device converions (the LTC kernel for at::to_device)
+//
+// Case 2: lazy -> lazy
+//   If you're implementing a function that takes in lazy tensors and returns
+//   lazy tensors,
+//   **but** requires creating lazy tensors internally,
+//   then you can assume that the current function is running inside of some
+//   outer context where functionalization is already running, that will take
+//   care of doing the wrapping for you, and use functionalize_output=true
+//   Examples include:
+//   - CPU fallback (takes in lazy tensors, converts to cpu, calls kernel,
+//   converts returns back to lazy tensors).
+TORCH_API at::Tensor to_lazy_tensor(
+    const at::Tensor& self,
+    const c10::TensorOptions& options,
+    at::Device device,
+    bool non_blocking,
+    bool functionalize_output);
+
+template 
+auto TupleAtenFromLtcTensorsImpl(
+    const std::vector& tensors,
+    std::index_sequence) {
+  return std::make_tuple(CreateAtenFromLtcTensor(tensors[Indices])...);
+}
+
+template 
+auto TupleAtenFromLtcTensors(const std::vector& tensors) {
+  return TupleAtenFromLtcTensorsImpl(tensors, std::make_index_sequence{});
+}
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/tensor_impl.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/tensor_impl.h
new file mode 100644
index 0000000000000000000000000000000000000000..a35c02a7aeac40d86abb73a3fe8378e8184e941e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/tensor_impl.h
@@ -0,0 +1,62 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+
+namespace torch {
+namespace lazy {
+
+// Tensor implementation class used to be fed to the at::Tensor.
+// Its scope is just to handle an LazyTensor.
+class TORCH_API LTCTensorImpl final : public c10::TensorImpl {
+ public:
+  explicit LTCTensorImpl(const LazyTensorPtr& tensor);
+  explicit LTCTensorImpl(const LazyTensor& tensor);
+  explicit LTCTensorImpl(LazyTensor&& tensor);
+
+  LazyTensorPtr tensor() {
+    return tensor_;
+  }
+
+  void set_tensor(const LazyTensorPtr& lazy_tensor);
+
+  void force_refresh_sizes() {
+    generation_ = 0;
+  }
+
+  c10::intrusive_ptr shallow_copy_and_detach(
+      const c10::VariableVersion& version_counter,
+      bool allow_tensor_metadata_change) const override;
+
+  c10::intrusive_ptr shallow_copy_and_detach(
+      c10::VariableVersion&& version_counter,
+      bool allow_tensor_metadata_change) const override;
+
+  void shallow_copy_from(const c10::intrusive_ptr& impl) override;
+
+  at::IntArrayRef sizes_custom() const override;
+  at::IntArrayRef strides_custom() const override;
+  int64_t numel_custom() const override;
+  int64_t storage_offset_custom() const override;
+  int64_t dim_custom() const override;
+  bool is_contiguous_custom(at::MemoryFormat memory_format) const override;
+  bool is_strides_like_custom(at::MemoryFormat memory_format) const override;
+  bool is_non_overlapping_and_dense_custom() const override;
+
+  c10::SymIntArrayRef sym_sizes_custom() const override;
+  c10::SymIntArrayRef sym_strides_custom() const override;
+  c10::SymInt sym_numel_custom() const override;
+
+ private:
+  void setup_size_properties();
+
+  LazyTensorPtr tensor_;
+  mutable std::optional> sym_sizes_;
+  size_t generation_{0};
+};
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/tensor_util.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/tensor_util.h
new file mode 100644
index 0000000000000000000000000000000000000000..121235ef9d8c0c23499745c7beb6a9a2d419bc0d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/tensor_util.h
@@ -0,0 +1,78 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace lazy {
+
+TORCH_API std::vector ComputeArrayStrides(
+    c10::ArrayRef sizes);
+
+TORCH_API std::vector DataHandlesToTensors(
+    c10::ArrayRef data_handles,
+    at::ScalarType dest_element_type);
+
+// Uploads an ATEN tensor data to the device and fetches the corresponding
+// device data handle.
+TORCH_API BackendDataPtr
+TensorToDataHandle(const at::Tensor& tensor, const BackendDevice& device);
+
+// Retrieves the device data handles by parallel uploading data onto the
+// corresponding devices.
+TORCH_API std::vector CreateTensorsData(
+    const std::vector& tensors,
+    const std::vector& devices);
+
+// Makes a deep copy of an ATEN tensor.
+inline at::Tensor CopyTensor(const at::Tensor& ref) {
+  return ref.to(ref.options(), /*non_blocking=*/false, /*copy=*/true);
+}
+
+// Same as above, with an additional cast.
+inline at::Tensor CopyTensor(
+    const at::Tensor& ref,
+    at::ScalarType dest_type,
+    bool copy = true) {
+  return ref.to(ref.options().dtype(dest_type), /*non_blocking=*/false, copy);
+}
+
+template 
+T OptionalOr(const std::optional& value, T defval) {
+  return value ? static_cast(*value) : defval;
+}
+
+// Unwraps tensor to target dtype if it's a wrapped number.
+inline at::Tensor UnwrapNumber(const at::Tensor& tensor, at::ScalarType dtype) {
+  return tensor.unsafeGetTensorImpl()->is_wrapped_number() ? tensor.to(dtype)
+                                                           : tensor;
+}
+
+template 
+at::Scalar MakeIntScalar(T value) {
+  return at::Scalar(static_cast(value));
+}
+
+// Routing values to device data maximizes the changes for compilation cache
+// hits, but it can prevent the compiler to perform optimizations. So tensor
+// values which are within a given set, are routed to constant scalars if this
+// API returns true.
+TORCH_API bool IsSpecialScalar(const at::Scalar& value);
+
+// Note: returns a reference instead of a fresh tensor to avoid refcount bumps.
+inline const at::Tensor& maybe_unwrap_functional(const at::Tensor& tensor) {
+  if (at::functionalization::impl::isFunctionalTensor(tensor)) {
+    return at::functionalization::impl::unsafeGetFunctionalWrapper(tensor)
+        ->value();
+  } else {
+    return tensor;
+  }
+}
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/thread_pool.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/thread_pool.h
new file mode 100644
index 0000000000000000000000000000000000000000..571a55b468fdd5a7114aa3c30221604ed0113795
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/thread_pool.h
@@ -0,0 +1,37 @@
+/**
+ * This file is adapted from PyTorch/XLA
+ * https://github.com/pytorch/xla/blob/master/third_party/xla_client/metrics.h
+ */
+
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+
+namespace torch {
+namespace lazy {
+
+class TORCH_API Completion {
+ public:
+  class Data;
+
+  explicit Completion(std::shared_ptr data);
+
+  ~Completion();
+
+  void Wait();
+
+ private:
+  std::shared_ptr data_;
+};
+
+// Schedules a closure which might wait for IO or other events/conditions.
+TORCH_API void ScheduleIoClosure(std::function closure);
+TORCH_API Completion
+ScheduleIoClosureWithCompletion(std::function closure);
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/trie.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/trie.h
new file mode 100644
index 0000000000000000000000000000000000000000..bfb026d963cc0fa79020963f7d7c49310f41459c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/trie.h
@@ -0,0 +1,79 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace lazy {
+
+struct TORCH_API TrieNode {
+  static size_t GetNextUniqueId() {
+    static thread_local size_t id_generator = 0;
+    return id_generator++;
+  }
+
+  size_t unique_id;
+  size_t hit_counter;
+  NodePtr ir_node;
+  std::list> successors;
+
+  TrieNode() : unique_id(GetNextUniqueId()), hit_counter(0), ir_node(nullptr) {}
+  explicit TrieNode(NodePtr node)
+      : unique_id(GetNextUniqueId()),
+        hit_counter(0),
+        ir_node(std::move(node)) {}
+};
+
+class TORCH_API TrieCache {
+ public:
+  static TrieCache* Get();
+
+  TrieNode* Current() const;
+  // Take an iterator as the input because we want to move the corresponding
+  // node in the successor list to achieve a LRU caching effect
+  void SetCurrent(std::list>::iterator& iter);
+  // Used in MarkStep to indicate the end of one tracing
+  void ResetCurrent();
+
+  // Create a new TrieNode for ir_node and insert into the TrieCache
+  void Insert(NodePtr ir_node);
+
+  // Clear all TrieCache nodes
+  // TODO: Because we don't expect user to explicitly call this function via
+  // a Python API, we may need to introduce a threshold on the size of the cache
+  // to avoid holding tensors for too long.
+  void Clear();
+
+  void DumpToDotFile(const std::string& file_name);
+
+ private:
+  TrieCache();
+
+  std::shared_ptr root_;
+  TrieNode* current_;
+};
+
+template 
+NodePtr LookupNodeFromTrieCache(Args&&... args) {
+  auto& successors = TrieCache::Get()->Current()->successors;
+  for (auto it = successors.begin(); it != successors.end(); it++) {
+    NodePtr ir_node = (*it)->ir_node;
+    const T* concrete_node = NodeCast(ir_node.get());
+    if (concrete_node &&
+        concrete_node->CanBeReused(std::forward(args)...)) {
+      TORCH_LAZY_COUNTER(
+          "IrNodeReused_" + c10::demangle((typeid(T).name())), 1);
+      (*it)->hit_counter++;
+      TrieCache::Get()->SetCurrent(it);
+      return ir_node;
+    }
+  }
+  return nullptr;
+}
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/unique.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/unique.h
new file mode 100644
index 0000000000000000000000000000000000000000..3088da160860b709ed208407aa75fff2a8c88819
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/unique.h
@@ -0,0 +1,56 @@
+/**
+ * Unique in this file is adapted from PyTorch/XLA
+ * https://github.com/pytorch/xla/blob/master/third_party/xla_client/unique.h
+ */
+
+#pragma once
+
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace lazy {
+
+// Helper class to allow tracking zero or more things, which should be forcibly
+// be one only thing.
+template >
+class Unique {
+ public:
+  std::pair set(const T& value) {
+    if (value_) {
+      TORCH_CHECK(C()(*value_, value), "'", *value_, "' vs '", value);
+      return std::pair(false, *value_);
+    }
+    value_ = value;
+    return std::pair(true, *value_);
+  }
+
+  operator bool() const {
+    return value_.has_value();
+  }
+  operator const T&() const {
+    return *value_;
+  }
+  const T& operator*() const {
+    return *value_;
+  }
+  const T* operator->() const {
+    return value_.operator->();
+  }
+
+  std::set AsSet() const {
+    std::set vset;
+    if (value_.has_value()) {
+      vset.insert(*value_);
+    }
+    return vset;
+  }
+
+ private:
+  std::optional value_;
+};
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/util.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/util.h
new file mode 100644
index 0000000000000000000000000000000000000000..bfd68b73355dfcc928bc5a0247a550330f5e1dae
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/core/util.h
@@ -0,0 +1,126 @@
+/**
+ * Most of the utils in this file is adapted from PyTorch/XLA
+ * https://github.com/pytorch/xla/blob/master/third_party/xla_client/util.h
+ */
+
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace lazy {
+
+// Similar to c10::scope_exit but with a status.
+// TODO(alanwaketan): Consolidate it with c10::scope_exit.
+template 
+class Cleanup {
+ public:
+  using StatusType = T;
+
+  explicit Cleanup(std::function&& func)
+      : func_(std::move(func)) {}
+  Cleanup(Cleanup&& ref) noexcept
+      : func_(std::move(ref.func_)), status_(std::move(ref.status_)) {}
+  Cleanup(const Cleanup&) = delete;
+
+  ~Cleanup() {
+    if (func_ != nullptr) {
+      func_(std::move(status_));
+    }
+  }
+
+  Cleanup& operator=(const Cleanup&) = delete;
+
+  Cleanup& operator=(Cleanup&& ref) noexcept {
+    if (this != &ref) {
+      func_ = std::move(ref.func_);
+      status_ = std::move(ref.status_);
+    }
+    return *this;
+  }
+
+  void Release() {
+    func_ = nullptr;
+  }
+
+  void SetStatus(StatusType&& status) {
+    status_ = std::move(status);
+  }
+
+  const StatusType& GetStatus() const {
+    return status_;
+  }
+
+ private:
+  std::function func_;
+  StatusType status_;
+};
+
+using ExceptionCleanup = Cleanup;
+
+// Allows APIs which might return const references and values, to not be forced
+// to return values in the signature.
+// TODO(alanwaketan): This is clever, but is there really no std or c10
+// supports? Needs more investigations.
+template 
+class MaybeRef {
+ public:
+  /* implicit */ MaybeRef(const T& ref) : ref_(ref) {}
+  /* implicit */ MaybeRef(T&& value)
+      : storage_(std::move(value)), ref_(*storage_) {}
+
+  const T& Get() const {
+    return ref_;
+  }
+  const T& operator*() const {
+    return Get();
+  }
+  operator const T&() const {
+    return Get();
+  }
+
+  bool IsStored() const {
+    return storage_.has_value();
+  }
+
+ private:
+  std::optional storage_;
+  const T& ref_;
+};
+
+template 
+std::vector Iota(size_t size, T init = 0, T incr = 1) {
+  std::vector result(size);
+  T value = init;
+  for (size_t i = 0; i < size; ++i, value += incr) {
+    result[i] = value;
+  }
+  return result;
+}
+
+template 
+std::vector ToVector(const S& input) {
+  return std::vector(input.begin(), input.end());
+}
+
+template 
+std::optional> ToOptionalVector(
+    c10::OptionalArrayRef arrayRef) {
+  if (arrayRef) {
+    return arrayRef->vec();
+  }
+  return std::nullopt;
+}
+
+template 
+typename std::underlying_type::type GetEnumValue(T value) {
+  return static_cast::type>(value);
+}
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/python/python_util.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/python/python_util.h
new file mode 100644
index 0000000000000000000000000000000000000000..271c694ee35ddcc0900582cc3ab42c87b0cc8706
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/python/python_util.h
@@ -0,0 +1,15 @@
+#pragma once
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace lazy {
+
+std::optional TORCH_PYTHON_API GetPythonFrameTop();
+
+std::vector TORCH_PYTHON_API GetPythonFrames();
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/config.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/config.h
new file mode 100644
index 0000000000000000000000000000000000000000..ac0320b9d0ac3cca01ddfc12f01e4a232fdda0df
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/config.h
@@ -0,0 +1,7 @@
+#pragma once
+#include 
+
+// TODO(whc) unclear if this is useful, has only been tested as true
+C10_DECLARE_bool(torch_lazy_ts_tensor_update_sync);
+
+C10_DECLARE_bool(torch_lazy_ts_cuda);
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/dynamic_ir.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/dynamic_ir.h
new file mode 100644
index 0000000000000000000000000000000000000000..aa0ed1eb99321f53cf0f16ef3403bc7abf491738
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/dynamic_ir.h
@@ -0,0 +1,85 @@
+#pragma once
+
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+C10_DECLARE_bool(ltc_enable_dynamic_shapes);
+
+namespace torch {
+namespace lazy {
+
+/**
+ * The goal of "dynamic" Nodes is to patch a hole in our tracing.
+ * Previously, if a user called `sizes` on a Tensor, it would leak out
+ * of our tracing system, as `sizes` returns a torch.Size or an int. To
+ * prevent this from happening, we introduce DimensionNode, a new type
+ * of Node that abstracts the operation of getting the dimensions of a
+ * Tensor.
+ *
+ * Consider the following example:
+ * ```
+ * numel = x.shape()[0] * x.shape()[1]
+ * ```
+ *
+ * Here, `x.shape()[i]` will be a SizeNode (subclass of DimensionNode),
+ * and the multiplication of the two SizeNodes will be represented by
+ * a SizeMul (also a subclass of DimensionNode). Through this, we can
+ * prevent `numel` from being represented as a Python int and thus
+ * burned into the Graph.
+ */
+
+// Represents the result of calling `size` on a Tensor
+class TORCH_API SizeNode : public TsNode, public DimensionNode {
+ public:
+  SizeNode(Value input, size_t dim);
+  int64_t getStaticValue() const override;
+  bool isSymbolic() const override;
+  std::string ToString() const override;
+  size_t dim_ = 0;
+  torch::lazy::TSOpVector Lower(
+      std::shared_ptr function,
+      TSLoweringContext* loctx) const override;
+};
+
+class TORCH_API SizeAdd : public TsNode, public DimensionNode {
+ public:
+  SizeAdd(Value a, Value b);
+  int64_t getStaticValue() const override;
+  bool isSymbolic() const override;
+  std::string ToString() const override;
+};
+
+class TORCH_API SizeMul : public TsNode, public DimensionNode {
+ public:
+  SizeMul(Value a, Value b);
+  int64_t getStaticValue() const override;
+  bool isSymbolic() const override;
+  std::string ToString() const override;
+};
+
+class TORCH_API SizeDiv : public TsNode, public DimensionNode {
+ public:
+  SizeDiv(Value a, Value b);
+  int64_t getStaticValue() const override;
+  bool isSymbolic() const override;
+  std::string ToString() const override;
+};
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/ir_builder.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/ir_builder.h
new file mode 100644
index 0000000000000000000000000000000000000000..9fff33135a5c87223d1b91a5797c42158a026e10
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/ir_builder.h
@@ -0,0 +1,71 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace lazy {
+
+struct TorchScriptIrBuilder : IrBuilder {
+  NodePtr MakeDeviceData(
+      const std::shared_ptr& data) const override {
+    return DeviceData::Create(data);
+  }
+  // TODO: Scalar node is not currently used by ts_backend. Enable reusing
+  // Scalar node later if needed.
+  NodePtr MakeScalar(const at::Scalar& value, const at::ScalarType& type)
+      const override {
+    return MakeNode(value, type);
+  }
+  NodePtr MakeExpand(
+      const Value& input0,
+      const std::vector& size,
+      const bool& is_scalar_expand) const override {
+    return ReuseOrMakeNode(input0, size, is_scalar_expand);
+  }
+  NodePtr MakeCast(
+      const Value& input0,
+      const at::ScalarType& dtype,
+      const std::optional& stype =
+          std::nullopt) const override {
+    return ReuseOrMakeNode(input0, dtype, stype);
+  }
+  NodePtr MakeTensorList(const OpList& inputs) const override {
+    return ReuseOrMakeNode(inputs);
+  }
+  // Generic needs cleanup
+  NodePtr MakeGeneric(
+      const OpKind& op,
+      const OpList& operands,
+      const Shape& shape,
+      const size_t& num_outputs = 1,
+      const hash_t& hash_seed =
+          static_cast(0x5a2d296e9)) const override {
+    return MakeNode(op, operands, shape, num_outputs, hash_seed);
+  }
+
+  // dynamic ir nodes
+  // TODO: verify if IR node reusing works for Dynamic shape ops
+  NodePtr MakeSizeNode(const Value& input, size_t dim) const override {
+    return MakeNode(input, dim);
+  }
+  NodePtr MakeSizeAdd(const Value& a, const Value& b) const override {
+    return MakeNode(a, b);
+  }
+  NodePtr MakeSizeMul(const Value& a, const Value& b) const override {
+    return MakeNode(a, b);
+  }
+  NodePtr MakeSizeDiv(const Value& a, const Value& b) const override {
+    return MakeNode(a, b);
+  }
+};
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/tensor_aten_ops.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/tensor_aten_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..bf663f4ca6b1b78634a15bd65617328e92584239
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/tensor_aten_ops.h
@@ -0,0 +1,17 @@
+#pragma once
+
+#include 
+
+namespace torch {
+namespace lazy {
+
+//////////////////////////////////////////////////////////////////////////////
+// ATEN operators follows here, listed in alphabetical order.
+//////////////////////////////////////////////////////////////////////////////
+
+void copy_(torch::lazy::LazyTensorPtr& input, torch::lazy::LazyTensorPtr& src);
+// Fills the input with the given value.
+void fill_(torch::lazy::LazyTensorPtr& input, const at::Scalar& value);
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_autograd_functions.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_autograd_functions.h
new file mode 100644
index 0000000000000000000000000000000000000000..7e01724470384497a5fcdc9102d4b06403bdc640
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_autograd_functions.h
@@ -0,0 +1,24 @@
+#pragma once
+
+#include 
+
+namespace torch {
+namespace lazy {
+
+struct MaxPool3dAutogradFunctionTS
+    : public torch::autograd::Function {
+  static at::Tensor forward(
+      torch::autograd::AutogradContext* ctx,
+      at::Tensor self,
+      at::IntArrayRef kernel_size,
+      at::IntArrayRef stride,
+      at::IntArrayRef padding,
+      at::IntArrayRef dilation,
+      bool ceil_mode);
+  static torch::autograd::variable_list backward(
+      torch::autograd::AutogradContext* ctx,
+      torch::autograd::variable_list grad_output);
+};
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_backend_impl.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_backend_impl.h
new file mode 100644
index 0000000000000000000000000000000000000000..0607c3efb53866434a592d16b92194bed24a799f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_backend_impl.h
@@ -0,0 +1,52 @@
+#pragma once
+
+#include 
+
+namespace torch {
+namespace lazy {
+
+class TORCH_API TSData : public torch::lazy::BackendData {
+ public:
+  TSData(const at::Scalar& scalar, const torch::lazy::BackendDevice& device)
+      : torch::lazy::BackendData(device, torch::lazy::Shape(scalar.type(), {})),
+        scalar(scalar) {}
+
+  TSData(
+      const at::Tensor& data,
+      const torch::lazy::Shape& shape,
+      const torch::lazy::BackendDevice& device)
+      : torch::lazy::BackendData(device, shape), data_(data) {}
+
+  TSData(
+      const torch::lazy::Shape& shape,
+      const torch::lazy::BackendDevice& device)
+      : torch::lazy::BackendData(device, shape) {}
+
+  Handle GetHandle() override {
+    return reinterpret_cast(this);
+  }
+
+  void Assign(const torch::lazy::BackendData& data) override {
+    data_ = static_cast(data).data_;
+  }
+
+  bool HasValue() const override {
+    return data_.defined();
+  }
+
+  at::Tensor data() {
+    return data_;
+  }
+
+  std::optional scalar;
+
+ private:
+  at::Tensor data_;
+};
+
+TORCH_API torch::lazy::BackendImplInterface* GetTSBackendImpl();
+
+TORCH_API void InitTorchScriptBackend();
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_eager_fallback.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_eager_fallback.h
new file mode 100644
index 0000000000000000000000000000000000000000..9f993d6f30290eb5914603d013f49884fcb3ea69
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_eager_fallback.h
@@ -0,0 +1,27 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace lazy {
+
+bool force_eager_fallback(c10::Symbol op);
+void ltc_eager_fallback(
+    const c10::OperatorHandle& op,
+    torch::jit::Stack* stack);
+
+void ts_eager_fallback(
+    const c10::OperatorHandle& op,
+    torch::jit::Stack* stack,
+    c10::DeviceType device_type);
+
+// The TorchScript backend does not register itself with pytorch dispatcher
+// until it is explicitly initialized.  This function should only be called
+// by the main Torchscript backend init function.
+void register_ts_ltc_eager_fallback();
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_lowering_context.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_lowering_context.h
new file mode 100644
index 0000000000000000000000000000000000000000..a898dfea654ad0e04bcc5e8bf003430b563f79a3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_lowering_context.h
@@ -0,0 +1,152 @@
+#pragma once
+
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace lazy {
+
+using TSOpVector = std::vector;
+
+class TORCH_API TSComputation : public Computation {
+ public:
+  TSComputation(const std::shared_ptr& graph)
+      : graph_(graph), graph_executor_(graph, "") {
+    for (torch::jit::Value* input : graph_->inputs()) {
+      parameter_names_.push_back(input->debugName());
+    }
+  }
+
+  int parameters_size() const override {
+    return parameter_names_.size();
+  }
+
+  const std::vector& parameter_shapes() const override {
+    throw std::runtime_error(
+        "TODO(whc) implement TS computation shapes or change interface");
+    return parameter_shapes_;
+  }
+
+  const std::vector& parameter_names() const override {
+    return parameter_names_;
+  }
+
+  const Shape& result_shape() const override {
+    throw std::runtime_error(
+        "TODO(whc) implement TS computation shapes or change interface");
+    return result_shape_;
+  }
+
+  const std::string to_string() const override {
+    std::ostringstream oss;
+    oss << *graph_;
+    return oss.str();
+  }
+
+  std::shared_ptr graph() const {
+    return graph_;
+  }
+
+  torch::jit::GraphExecutor& graph_executor() {
+    return graph_executor_;
+  }
+
+ private:
+  std::shared_ptr graph_;
+  torch::jit::GraphExecutor graph_executor_;
+  std::vector parameter_names_;
+  std::vector parameter_shapes_;
+  Shape result_shape_;
+};
+
+class TORCH_API TSLoweringContext : public LoweringContext {
+ public:
+  TSLoweringContext(const std::string& name, const BackendDevice device);
+
+  TSLoweringContext(
+      const std::string& name,
+      BackendDevice device,
+      c10::ArrayRef post_order,
+      Util::EmissionMap emit_status);
+
+  size_t AddResult(const Output& output) override {
+    return AddResult(GetOutputOp(output));
+  }
+
+  void AddParameter(
+      const torch::lazy::Output& output,
+      size_t index,
+      const Shape& shape,
+      const std::string& name) override {
+    TORCH_INTERNAL_ASSERT(false, "not implemented");
+  }
+
+  void Lower(const Node* node);
+
+  ComputationPtr Build() override {
+    for (torch::jit::Value* output : root_tuple_) {
+      graph_->block()->registerOutput(output);
+    }
+    return std::shared_ptr(new TSComputation(graph_));
+  }
+
+  // Retrieves the lowered operation for an output. If the requested output is
+  // not available yet, the graph behind the output's Node is lowered, and the
+  // corresponding TS operation returned.
+  torch::jit::Value* GetOutputOp(const Output& output) {
+    auto it = emitted_outputs_.find(output);
+    if (it == emitted_outputs_.end()) {
+      auto post_order = Util::ComputePostOrder(output.node, &emit_status_);
+      for (auto node : post_order) {
+        Lower(node);
+      }
+      // At this point the output better be present, otherwise there is an issue
+      // with the lowering code.
+      it = emitted_outputs_.find(output);
+      TORCH_CHECK(
+          it != emitted_outputs_.end(),
+          "No TS operation emitted for output: ",
+          output.ToString());
+    }
+    return it->second;
+  }
+
+  // Assigns the given TS operation to the specified output. As outputs are
+  // lowered in a post-order fashion, later nodes should always find their
+  // operands among the emitted outputs.
+  void AssignOutputOp(const Output& output, torch::jit::Value* op);
+
+  // If a parameter associated with data has already been declared, it will be
+  // returned. Otherwise a new one will be created, associated with the tensor
+  // held in data.
+  torch::jit::Value* GetParameter(BackendDataPtr data);
+
+  std::shared_ptr graph() const {
+    return graph_;
+  }
+
+ private:
+  struct Parameter {
+    torch::jit::Value* param{nullptr};
+    size_t index = 0;
+  };
+
+  size_t AddResult(torch::jit::Value* op) {
+    root_tuple_.push_back(std::move(op));
+    return root_tuple_.size() - 1;
+  }
+
+  std::shared_ptr graph_;
+  std::shared_ptr function_;
+  std::unordered_map parameters_map_;
+  std::vector root_tuple_;
+  OutputMap emitted_outputs_;
+};
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_node.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_node.h
new file mode 100644
index 0000000000000000000000000000000000000000..62cc9016f6ffa2e50fb4d19501823eedcc0befde
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_node.h
@@ -0,0 +1,106 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace lazy {
+
+using TSOpVector = std::vector;
+
+class TORCH_API TsNode : public lazy::Node {
+ public:
+  TsNode(
+      OpKind op,
+      OpList operands,
+      std::vector&& shapes,
+      size_t num_outputs,
+      hash_t hash_seed = kHashSeed);
+
+  TsNode(
+      OpKind op,
+      OpList operands,
+      const std::function& shape_fn,
+      size_t num_outputs,
+      hash_t hash_seed = kHashSeed);
+
+  TsNode(
+      OpKind op,
+      OpList operands,
+      size_t num_outputs,
+      hash_t hash_seed = kHashSeed);
+
+  TsNode(
+      OpKind op,
+      Shape shape,
+      size_t num_outputs,
+      hash_t hash_seed = kHashSeed);
+
+  ~TsNode() override = default;
+
+  hash_t hash() const override;
+
+  hash_t shapeHash() const override;
+
+  const std::string getPythonStacktrace() const;
+
+  // Lower is a backend-specific method since it returns a backend specific
+  // type. hence, it is convenient to define it differently per-backend rather
+  // than at Node API
+  virtual TSOpVector Lower(
+      std::shared_ptr function,
+      TSLoweringContext* loctx) const;
+
+ private:
+  // The hash of the dag WITH size info. Used for shape caching
+  hash_t shape_hash_;
+  // The hash of the dag used to look up the compiled graph by a hash
+  // in this case, we will use the dag hash WITHOUT size info if dynamic shape
+  // is enabled and use the dag hash WITH size info otherwise.
+  hash_t dag_hash_;
+};
+
+// Note: this OpKind is separate from ltc_ops.h since it would be a circular
+// import otherwise, I like leaving TensorList in this file, and I think most of
+// ltc_ops special cases will be deleted anyway
+const OpKind tensor_list_opkind = OpKind::Get("lazy_tensors::tensor_list");
+
+// TensorList represents an at::TensorList which is a vector[Tensor] but is also
+// a first-class IValue and can be fed as a single input to a TS program.  It is
+// much easier to handle TensorLists in Lazy Tensor code if they are represented
+// as a single Node so there can be more than one TensorList and more than one
+// Tensor side-by-side as operands to an op.
+//
+// Note: shape is undefined for TensorList.  We assert in some places that
+// #shapes matches #outputs and this stems from
+//       the fact that currently all IR nodes represent tensors (there is no
+//       type system for this IR).  Becuase of this, TensorList is a bit of a
+//       hack.
+//
+// TODO(whc) once Shape() API is moved to Node base, also make it virtual, and
+// then implement it as NotImplemented for TensorList, also fixing the assertion
+// that would fail.
+struct TORCH_API TensorList : public TsNode {
+  static OpKind ClassOpKind() {
+    return tensor_list_opkind;
+  }
+
+  TensorList() = delete;
+  TensorList(OpList values);
+
+  bool CanBeReused(OpList values) const {
+    return operands() == std::vector(values.begin(), values.end());
+  }
+
+  TSOpVector Lower(
+      std::shared_ptr function,
+      TSLoweringContext* loctx) const override;
+};
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_node_lowering.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_node_lowering.h
new file mode 100644
index 0000000000000000000000000000000000000000..cf46311ca24b3375f73130ed895429dc3f8dd446
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/lazy/ts_backend/ts_node_lowering.h
@@ -0,0 +1,17 @@
+#pragma once
+
+#include 
+#include 
+
+namespace torch {
+namespace lazy {
+using TSOpVector = std::vector;
+
+TORCH_API TSOpVector LowerTSBuiltin(
+    std::shared_ptr function,
+    c10::Symbol sym,
+    const std::vector& arguments,
+    const std::vector& kwarguments = {});
+
+} // namespace lazy
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/orchestration/observer.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/orchestration/observer.h
new file mode 100644
index 0000000000000000000000000000000000000000..f8491eec77828c5c4fba596f77f8bca1646d959a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/orchestration/observer.h
@@ -0,0 +1,166 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+
+namespace torch {
+namespace profiler {
+namespace impl {
+
+// ----------------------------------------------------------------------------
+// -- Profiler Config ---------------------------------------------------------
+// ----------------------------------------------------------------------------
+enum class C10_API_ENUM ActivityType {
+  CPU = 0,
+  XPU, // XPU kernels, runtime
+  CUDA, // CUDA kernels, runtime
+  MTIA, // MTIA kernels, runtime
+  PrivateUse1, // PrivateUse1 kernels, runtime
+  NUM_KINETO_ACTIVITIES, // must be the last one
+};
+
+inline std::string actToString(ActivityType t) {
+  const std::string ActivityTypeNames[] = {
+      "CPU", "XPU", "CUDA", "MTIA", "PrivateUse1"};
+  return ActivityTypeNames[static_cast(t)];
+}
+
+enum class C10_API_ENUM ProfilerState {
+  Disabled = 0,
+  CPU, // CPU-only profiling
+  CUDA, // CPU + CUDA events
+  NVTX, // only emit NVTX markers
+  ITT, // only emit ITT markers
+  PRIVATEUSE1, // only emit PRIVATEUSE1 markers
+  KINETO, // use libkineto
+  KINETO_GPU_FALLBACK, // use CUDA events when CUPTI is not available
+  KINETO_PRIVATEUSE1_FALLBACK, // use PrivateUse1 events
+  KINETO_ONDEMAND, // run the profiler in on-demand mode
+  NUM_PROFILER_STATES, // must be the last one
+};
+
+enum class C10_API_ENUM ActiveProfilerType {
+  NONE = 0,
+  LEGACY,
+  KINETO,
+  NVTX,
+  ITT,
+  PRIVATEUSE1
+};
+
+struct TORCH_API ExperimentalConfig {
+  ExperimentalConfig(
+      std::vector profiler_metrics = {},
+      bool profiler_measure_per_kernel = false,
+      bool verbose = false,
+      std::vector performance_events = {},
+      bool enable_cuda_sync_events = false,
+      bool adjust_timestamps = false);
+  explicit operator bool() const;
+
+  std::vector profiler_metrics;
+  bool profiler_measure_per_kernel;
+  bool verbose;
+  /*
+   * List of performance events to be profiled.
+   * An empty list will disable performance event based profiling altogether.
+   */
+  std::vector performance_events;
+  /*
+   * For CUDA profiling mode, enable adding CUDA synchronization events
+   * that expose CUDA device, stream and event synchronization activities.
+   * This feature is new and currently disabled by default.
+   */
+  bool enable_cuda_sync_events;
+  /*
+   * Controls whether or not timestamp adjustment occurs after profiling.
+   * The purpose of this is to adjust Vulkan event timelines to align with those
+   * of their parent CPU events.
+   * This sometimes requires increasing CPU event durations (to fully contain
+   * their child events) and delaying CPU event start times (to
+   * prevent overlaps), so this should not be used unless Vulkan events are
+   * being profiled and it is ok to use this modified timestamp/duration
+   * information instead of the original information.
+   */
+  bool adjust_timestamps;
+};
+
+struct TORCH_API ProfilerConfig {
+  ProfilerConfig(
+      ProfilerState state,
+      bool report_input_shapes = false,
+      bool profile_memory = false,
+      bool with_stack = false,
+      bool with_flops = false,
+      bool with_modules = false,
+      ExperimentalConfig experimental_config = ExperimentalConfig());
+
+  bool disabled() const;
+  bool global() const;
+
+  ProfilerState state;
+  ExperimentalConfig experimental_config;
+  bool report_input_shapes;
+  bool profile_memory;
+  bool with_stack;
+  bool with_flops;
+  bool with_modules;
+
+  // For serialization
+  at::IValue toIValue() const;
+  static ProfilerConfig fromIValue(const at::IValue& profilerConfigIValue);
+};
+
+// ----------------------------------------------------------------------------
+// -- Profiler base class -----------------------------------------------------
+// ----------------------------------------------------------------------------
+struct TORCH_API ProfilerStateBase : public c10::MemoryReportingInfoBase {
+  explicit ProfilerStateBase(ProfilerConfig config);
+  ~ProfilerStateBase() override;
+
+  static ProfilerStateBase* get(bool global);
+  static ProfilerStateBase* get() {
+    auto* out = get(/*global=*/true);
+    return out ? out : get(/*global=*/false);
+  }
+
+  static void push(std::shared_ptr&& state);
+
+  static std::shared_ptr pop(bool global);
+  static std::shared_ptr pop() {
+    auto out = pop(/*global=*/true);
+    return out ? std::move(out) : pop(/*global=*/false);
+  }
+
+  const ProfilerConfig& config() const {
+    return config_;
+  }
+
+  void setCallbackHandle(at::CallbackHandle handle);
+  void removeCallback();
+
+  bool memoryProfilingEnabled() const override {
+    return config_.profile_memory;
+  }
+
+  virtual ActiveProfilerType profilerType() = 0;
+
+ protected:
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  std::mutex state_mutex_;
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  ProfilerConfig config_ = ProfilerConfig(ProfilerState::Disabled);
+  // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+  at::CallbackHandle handle_ = 0;
+};
+
+// Note: The following are only for the active *thread local* profiler.
+TORCH_API bool profilerEnabled();
+TORCH_API ActiveProfilerType profilerType();
+TORCH_API ProfilerConfig getProfilerConfig();
+
+} // namespace impl
+} // namespace profiler
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/orchestration/python_tracer.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/orchestration/python_tracer.h
new file mode 100644
index 0000000000000000000000000000000000000000..4605dde57e492eee9d99800b4a171f60f1157429
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/orchestration/python_tracer.h
@@ -0,0 +1,64 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+#include 
+#include 
+
+namespace torch {
+namespace profiler {
+namespace impl {
+
+class RecordQueue;
+struct Result;
+namespace python_tracer {
+
+using TraceKey = strong::type<
+    uint64_t,
+    struct TraceKey_,
+    strong::regular,
+    strong::hashable,
+    strong::ostreamable>;
+
+struct CompressedEvent {
+  TraceKey key_;
+  uint64_t system_tid_{};
+  kineto::DeviceAndResource kineto_info_{};
+  c10::time_t enter_t_{};
+};
+
+/*
+Libtorch does not depend on Python (e.g. cannot #include ); however
+when we call the profiler from libtorch_python we need the profiler to be able
+to ingest the data that we collect from the Python tracer. (`PyEval_SetProfile`)
+
+In order to solve this dependency issue we define a virtual base and a function
+to register a getter. The python tracer then implements these functions and
+exposes itself by calling `registerTracer` from `torch/csrc/autograd/init.cpp`.
+This pattern of registration for faux python dependencies in libtorch is common
+in the PyTorch codebase.
+*/
+struct TORCH_API PythonTracerBase {
+  static std::unique_ptr make(RecordQueue* queue);
+  virtual ~PythonTracerBase() = default;
+
+  virtual void stop() = 0;
+  virtual void restart() = 0;
+  virtual std::vector> getEvents(
+      std::function time_converter,
+      std::vector& enters,
+      c10::time_t end_time_ns) = 0;
+};
+
+using MakeFn = std::unique_ptr (*)(RecordQueue*);
+TORCH_API void registerTracer(MakeFn make_tracer);
+} // namespace python_tracer
+} // namespace impl
+} // namespace profiler
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/orchestration/vulkan.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/orchestration/vulkan.h
new file mode 100644
index 0000000000000000000000000000000000000000..2b11d5a0e21e5ed83fe4cf8ca1e042325d47073b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/orchestration/vulkan.h
@@ -0,0 +1,28 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace profiler {
+namespace impl {
+namespace vulkan {
+
+// Using function pointer i.e. [std::tuple (*)(int64_t)]
+// doesn't work because we need to capture the QueryPool in the lambda context
+// https://stackoverflow.com/a/28746827
+using GetShaderNameAndDurationNsFn =
+    std::function(int64_t)>;
+TORCH_API void registerGetShaderNameAndDurationNs(
+    GetShaderNameAndDurationNsFn get_shader_name_and_duration_ns);
+
+TORCH_API void deregisterGetShaderNameAndDurationNs();
+
+std::tuple getShaderNameAndDurationNs(
+    const vulkan_id_t& vulkan_id);
+
+} // namespace vulkan
+} // namespace impl
+} // namespace profiler
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/python/combined_traceback.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/python/combined_traceback.h
new file mode 100644
index 0000000000000000000000000000000000000000..f71033fd88e708100da75b4bfe5035440afdfb64
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/python/combined_traceback.h
@@ -0,0 +1,22 @@
+#include 
+
+#include 
+#include 
+
+namespace torch {
+
+// symbolize combined traceback objects, converting them into lists of
+// dictionaries that are easily consumed in python.
+
+// returns std::vector because one use is to call it with a batch of
+// tracebacks that come from a larger datastructure (e.g. a memory snapshot)
+// and then have more c++ code to put those objects in the right place.
+TORCH_API std::vector py_symbolize(
+    std::vector& to_symbolize);
+
+// requires GIL to be held, frees any pending free frames
+void freeDeadCapturedTracebackFrames();
+
+void installCapturedTracebackPython();
+
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/python/init.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/python/init.h
new file mode 100644
index 0000000000000000000000000000000000000000..28fae14988a0f71ec3ad861afe8f86555c2c1de5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/python/init.h
@@ -0,0 +1,31 @@
+#pragma once
+
+#include 
+
+#include 
+#include 
+
+namespace pybind11::detail {
+using torch::profiler::impl::TensorID;
+
+#define STRONG_POINTER_TYPE_CASTER(T) \
+  template <>                         \
+  struct type_caster : public strong_pointer_type_caster {};
+
+STRONG_POINTER_TYPE_CASTER(torch::profiler::impl::StorageImplData);
+STRONG_POINTER_TYPE_CASTER(torch::profiler::impl::AllocationID);
+STRONG_POINTER_TYPE_CASTER(torch::profiler::impl::TensorImplAddress);
+STRONG_POINTER_TYPE_CASTER(torch::profiler::impl::PyModuleSelf);
+STRONG_POINTER_TYPE_CASTER(torch::profiler::impl::PyModuleCls);
+STRONG_POINTER_TYPE_CASTER(torch::profiler::impl::PyOptimizerSelf);
+#undef STRONG_POINTER_TYPE_CASTER
+
+template <>
+struct type_caster : public strong_uint_type_caster {};
+} // namespace pybind11::detail
+
+namespace torch::profiler {
+
+void initPythonBindings(PyObject* module);
+
+} // namespace torch::profiler
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/python/pybind.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/python/pybind.h
new file mode 100644
index 0000000000000000000000000000000000000000..c44291ef455f162b0b8f40da663f0e973a893b23
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/python/pybind.h
@@ -0,0 +1,48 @@
+#pragma once
+
+#include 
+
+#include 
+#include 
+#include 
+
+namespace pybind11::detail {
+// Strong typedefs don't make much sense in Python since everything is duck
+// typed. So instead we simply extract the underlying value and let the caller
+// handle correctness.
+template 
+struct strong_pointer_type_caster {
+  template 
+  static handle cast(
+      T_&& src,
+      return_value_policy /*policy*/,
+      handle /*parent*/) {
+    const auto* ptr = reinterpret_cast(src.value_of());
+    return ptr ? handle(THPUtils_packUInt64(reinterpret_cast(ptr)))
+               : none();
+  }
+
+  bool load(handle /*src*/, bool /*convert*/) {
+    return false;
+  }
+
+  PYBIND11_TYPE_CASTER(T, _("strong_pointer"));
+};
+
+template 
+struct strong_uint_type_caster {
+  template 
+  static handle cast(
+      T_&& src,
+      return_value_policy /*policy*/,
+      handle /*parent*/) {
+    return handle(THPUtils_packUInt64(src.value_of()));
+  }
+
+  bool load(handle /*src*/, bool /*convert*/) {
+    return false;
+  }
+
+  PYBIND11_TYPE_CASTER(T, _("strong_uint"));
+};
+} // namespace pybind11::detail
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/standalone/execution_trace_observer.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/standalone/execution_trace_observer.h
new file mode 100644
index 0000000000000000000000000000000000000000..cb7a3ea7d81e355c4f8ede316ff90060752c1dad
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/standalone/execution_trace_observer.h
@@ -0,0 +1,21 @@
+#pragma once
+
+#include 
+#include 
+
+namespace torch::profiler::impl {
+
+// Adds the execution trace observer as a global callback function, the data
+// will be written to output file path.
+TORCH_API bool addExecutionTraceObserver(const std::string& output_file_path);
+
+// Remove the execution trace observer from the global callback functions.
+TORCH_API void removeExecutionTraceObserver();
+
+// Enables execution trace observer.
+TORCH_API void enableExecutionTraceObserver();
+
+// Disables execution trace observer.
+TORCH_API void disableExecutionTraceObserver();
+
+} // namespace torch::profiler::impl
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/standalone/itt_observer.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/standalone/itt_observer.h
new file mode 100644
index 0000000000000000000000000000000000000000..6eab7b9ca2c9a531261655dfcfa71593118e4d5e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/standalone/itt_observer.h
@@ -0,0 +1,9 @@
+#include 
+
+namespace torch::profiler::impl {
+
+void pushITTCallbacks(
+    const ProfilerConfig& config,
+    const std::unordered_set& scopes);
+
+} // namespace torch::profiler::impl
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/standalone/nvtx_observer.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/standalone/nvtx_observer.h
new file mode 100644
index 0000000000000000000000000000000000000000..1718969c3ea47a1fa609174d5e3e65a12f04fb48
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/standalone/nvtx_observer.h
@@ -0,0 +1,9 @@
+#include 
+
+namespace torch::profiler::impl {
+
+void pushNVTXCallbacks(
+    const ProfilerConfig& config,
+    const std::unordered_set& scopes);
+
+} // namespace torch::profiler::impl
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/standalone/privateuse1_observer.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/standalone/privateuse1_observer.h
new file mode 100644
index 0000000000000000000000000000000000000000..62b431aabc8b4244dc7ade0231c7c2d12f634d67
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/standalone/privateuse1_observer.h
@@ -0,0 +1,42 @@
+#pragma once
+#include 
+
+namespace torch::profiler::impl {
+
+using CallBackFnPtr = void (*)(
+    const ProfilerConfig& config,
+    const std::unordered_set& scopes);
+
+struct PushPRIVATEUSE1CallbacksStub {
+  PushPRIVATEUSE1CallbacksStub() = default;
+  PushPRIVATEUSE1CallbacksStub(const PushPRIVATEUSE1CallbacksStub&) = delete;
+  PushPRIVATEUSE1CallbacksStub& operator=(const PushPRIVATEUSE1CallbacksStub&) =
+      delete;
+
+  template 
+  void operator()(ArgTypes&&... args) {
+    return (*push_privateuse1_callbacks_fn)(std::forward(args)...);
+  }
+
+  void set_privateuse1_dispatch_ptr(CallBackFnPtr fn_ptr) {
+    push_privateuse1_callbacks_fn = fn_ptr;
+  }
+
+ private:
+  CallBackFnPtr push_privateuse1_callbacks_fn = nullptr;
+};
+
+extern TORCH_API struct PushPRIVATEUSE1CallbacksStub
+    pushPRIVATEUSE1CallbacksStub;
+
+struct RegisterPRIVATEUSE1Observer {
+  RegisterPRIVATEUSE1Observer(
+      PushPRIVATEUSE1CallbacksStub& stub,
+      CallBackFnPtr value) {
+    stub.set_privateuse1_dispatch_ptr(value);
+  }
+};
+
+#define REGISTER_PRIVATEUSE1_OBSERVER(name, fn) \
+  static RegisterPRIVATEUSE1Observer name##__register(name, fn);
+} // namespace torch::profiler::impl
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/stubs/base.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/stubs/base.h
new file mode 100644
index 0000000000000000000000000000000000000000..e0494e342e44dff73fa405aac21cc30d584c8758
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/stubs/base.h
@@ -0,0 +1,57 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+struct CUevent_st;
+
+namespace torch {
+namespace profiler {
+namespace impl {
+
+// ----------------------------------------------------------------------------
+// -- Annotation --------------------------------------------------------------
+// ----------------------------------------------------------------------------
+using ProfilerEventStub = std::shared_ptr;
+using ProfilerVoidEventStub = std::shared_ptr;
+
+struct TORCH_API ProfilerStubs {
+  virtual void record(
+      c10::DeviceIndex* device,
+      ProfilerVoidEventStub* event,
+      int64_t* cpu_ns) const = 0;
+  virtual float elapsed(
+      const ProfilerVoidEventStub* event,
+      const ProfilerVoidEventStub* event2) const = 0;
+  virtual void mark(const char* name) const = 0;
+  virtual void rangePush(const char* name) const = 0;
+  virtual void rangePop() const = 0;
+  virtual bool enabled() const {
+    return false;
+  }
+  virtual void onEachDevice(std::function op) const = 0;
+  virtual void synchronize() const = 0;
+  virtual ~ProfilerStubs();
+};
+
+TORCH_API void registerCUDAMethods(ProfilerStubs* stubs);
+TORCH_API const ProfilerStubs* cudaStubs();
+TORCH_API void registerITTMethods(ProfilerStubs* stubs);
+TORCH_API const ProfilerStubs* ittStubs();
+TORCH_API void registerPrivateUse1Methods(ProfilerStubs* stubs);
+TORCH_API const ProfilerStubs* privateuse1Stubs();
+
+using vulkan_id_t = strong::type<
+    int64_t,
+    struct _VulkanID,
+    strong::regular,
+    strong::convertible_to,
+    strong::hashable>;
+
+} // namespace impl
+} // namespace profiler
+} // namespace torch
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/action.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/action.h
new file mode 100644
index 0000000000000000000000000000000000000000..672fffad8c9171b367598b62bc1116c2c02a2181
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/action.h
@@ -0,0 +1,59 @@
+#pragma once
+#include 
+#include 
+
+namespace torch::unwind {
+
+enum {
+  A_UNDEFINED = 0x0,
+  A_REG_PLUS_DATA = 0x1, // exp = REG[reg] + data0
+  A_LOAD_CFA_OFFSET = 0x2, // exp = *(cfa + data0)
+  A_REG_PLUS_DATA_DEREF = 0x3 // exp = *(REG[reg] + data0)
+};
+
+// register numbers in dwarf info
+enum {
+  D_UNDEFINED = -1,
+  D_RBP = 6,
+  D_RSP = 7,
+  D_RIP = 16,
+  D_REG_SIZE = 17,
+};
+
+struct Action {
+  uint8_t kind = A_UNDEFINED;
+  int32_t reg = -1;
+  int64_t data = 0;
+  static Action undefined() {
+    return Action{A_UNDEFINED};
+  }
+  static Action regPlusData(int32_t reg, int64_t offset) {
+    return Action{A_REG_PLUS_DATA, reg, offset};
+  }
+  static Action regPlusDataDeref(int32_t reg, int64_t offset) {
+    return Action{A_REG_PLUS_DATA_DEREF, reg, offset};
+  }
+  static Action loadCfaOffset(int64_t offset) {
+    return Action{A_LOAD_CFA_OFFSET, D_UNDEFINED, offset};
+  }
+
+  friend std::ostream& operator<<(std::ostream& out, const Action& self) {
+    switch (self.kind) {
+      case A_UNDEFINED:
+        out << "u";
+        break;
+      case A_REG_PLUS_DATA:
+        out << "r" << (int)self.reg << " + " << self.data;
+        break;
+      case A_REG_PLUS_DATA_DEREF:
+        out << "*(r" << (int)self.reg << " + " << self.data << ")";
+        break;
+      case A_LOAD_CFA_OFFSET:
+        out << "*(cfa + " << self.data << ")";
+        break;
+    }
+    return out;
+  }
+};
+
+} // namespace torch::unwind
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/communicate.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/communicate.h
new file mode 100644
index 0000000000000000000000000000000000000000..063fe542a34199cd7b1cb59f29da807b379b09f9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/communicate.h
@@ -0,0 +1,68 @@
+#pragma once
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch::unwind {
+// helper to open a process with stdin/stdout/stderr streams.
+struct Communicate {
+  Communicate(const char* command, const char** args) {
+    if (pipe(inpipe_) < 0 || pipe(outpipe_) < 0 || pipe(errpipe_) < 0) {
+      throw UnwindError("pipe() failed");
+    }
+    pid_t pid = fork();
+    if (pid < 0) {
+      throw UnwindError("fork() failed");
+    } else if (pid == 0) { // child process
+      close(inpipe_[1]);
+      close(outpipe_[0]);
+      close(errpipe_[0]);
+
+      dup2(inpipe_[0], STDIN_FILENO);
+      dup2(outpipe_[1], STDOUT_FILENO);
+      dup2(errpipe_[1], STDERR_FILENO);
+      execvp(command, (char* const*)args);
+      throw UnwindError("failed execvp");
+    } else { // parent process
+      close(inpipe_[0]);
+      close(outpipe_[1]);
+      close(errpipe_[1]);
+      outbuf_.reset(
+          new __gnu_cxx::stdio_filebuf(inpipe_[1], std::ios::out));
+      inbuf_.reset(
+          new __gnu_cxx::stdio_filebuf(outpipe_[0], std::ios::in));
+      errbuf_.reset(
+          new __gnu_cxx::stdio_filebuf(errpipe_[0], std::ios::in));
+      in_.reset(new std::istream(inbuf_.get()));
+      out_.reset(new std::ostream(outbuf_.get()));
+      err_.reset(new std::ostream(errbuf_.get()));
+    }
+  }
+  ~Communicate() {
+    close(inpipe_[1]);
+    close(outpipe_[0]);
+    close(errpipe_[0]);
+  }
+  std::ostream& out() {
+    return *out_;
+  }
+  std::ostream& err() {
+    return *err_;
+  }
+  std::istream& in() {
+    return *in_;
+  }
+
+ private:
+  int inpipe_[2];
+  int outpipe_[2];
+  int errpipe_[2];
+  std::unique_ptr<__gnu_cxx::stdio_filebuf> outbuf_, inbuf_, errbuf_;
+  std::unique_ptr in_;
+  std::unique_ptr out_;
+  std::unique_ptr err_;
+};
+
+} // namespace torch::unwind
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/debug_info.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/debug_info.h
new file mode 100644
index 0000000000000000000000000000000000000000..067d7dc2e83e6ea8242460de853d5cb5dd610edc
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/debug_info.h
@@ -0,0 +1,279 @@
+#pragma once
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch::unwind {
+
+struct DebugInfo {
+  DebugInfo(Sections& s) : s_(s) {}
+
+  void parse(uint64_t offset) {
+    auto L = parseHeader(offset);
+    parseCompileUnit(L);
+  }
+  std::optional lineNumberProgramOffset() {
+    return line_number_program_offset_;
+  }
+  uint64_t nextOffset() {
+    return end_ - s_.debug_info.data;
+  }
+  std::vector> ranges() {
+    if (range_ptr_) {
+      auto offset = range_ptr_->first;
+      if (range_ptr_->second == DW_FORM_rnglistx) {
+        UNWIND_CHECK(rnglists_base_, "rnglistx but not rnglists_base_ set");
+        LOG_INFO("index for rnglistx {:x} + {:x}\n", *rnglists_base_, offset);
+        CheckedLexer L = s_.debug_rnglists.lexer(
+            *rnglists_base_ + offset * sec_offset_size_);
+        auto read = readSegmentOffset(L);
+        offset = *rnglists_base_ + read;
+      }
+      return version_ == 4 ? readRanges4(offset) : readRanges5(offset);
+    }
+    if (!highpc_) {
+      return {};
+    }
+    return {{lowpc_, lowpc_ + *highpc_}};
+  }
+
+  bool is64bit() {
+    return is_64bit_;
+  }
+
+ private:
+  CheckedLexer parseHeader(uint64_t offset) {
+    offset_ = offset;
+    CheckedLexer L = s_.debug_info.lexer(offset_);
+    std::tie(length_, is_64bit_) = L.readSectionLength();
+    sec_offset_size_ = is_64bit_ ? 8 : 4;
+    end_ = (const char*)L.loc() + length_;
+    version_ = L.read();
+    UNWIND_CHECK(
+        version_ == 5 || version_ == 4,
+        "unexpected dwarf version {}",
+        version_);
+    uint8_t address_size = 0;
+    if (version_ == 5) {
+      auto unit_type = L.read();
+      UNWIND_CHECK(unit_type == 0x1, "unexpected unit type {}", unit_type);
+      address_size = L.read();
+      debug_abbrev_offset_ =
+          is_64bit_ ? L.read() : L.read();
+    } else {
+      debug_abbrev_offset_ =
+          is_64bit_ ? L.read() : L.read();
+      address_size = L.read();
+    }
+    LOG_INFO(
+        "compilation unit at offset {:x} with length {:x} and debug_abbrev_offset {:x}\n",
+        offset,
+        length_,
+        debug_abbrev_offset_);
+    UNWIND_CHECK(
+        address_size == 8,
+        "expected 64-bit dwarf but found address size {}",
+        address_size);
+    return L;
+  }
+
+  uint64_t readSegmentOffset(CheckedLexer& L) {
+    return s_.readSegmentOffset(L, is_64bit_);
+  }
+
+  uint64_t readEncoded(CheckedLexer& L, uint64_t encoding) {
+    switch (encoding) {
+      case DW_FORM_data8:
+      case DW_FORM_addr:
+        return L.read();
+      case DW_FORM_data4:
+        return L.read();
+      case DW_FORM_addrx: {
+        auto idx = L.readULEB128();
+        return s_.debug_addr.lexer(address_base_ + sizeof(uint64_t) * idx)
+            .read();
+      }
+      case DW_FORM_sec_offset:
+        return readSegmentOffset(L);
+      case DW_FORM_rnglistx: {
+        return L.readULEB128();
+      }
+      default:
+        UNWIND_CHECK(false, "unexpected encoding");
+    }
+  }
+
+  void parseCompileUnit(CheckedLexer& L) {
+    auto entry = L.readULEB128();
+    auto A = findAbbrev(debug_abbrev_offset_, entry);
+    while (true) {
+      auto attr = A.readULEB128();
+      auto form = A.readULEB128();
+      if (attr == 0 && form == 0) {
+        break;
+      }
+      if (form == DW_FORM_implicit_const) {
+        A.readSLEB128();
+      }
+      if (attr == DW_AT_low_pc) {
+        lowpc_ = readEncoded(L, form);
+        LOG_INFO("  lowpc {:x}\n", lowpc_);
+      } else if (attr == DW_AT_high_pc) {
+        highpc_ = readEncoded(L, form);
+        range_ptr_ = std::nullopt;
+        LOG_INFO("  highpc {:x}\n", *highpc_);
+      } else if (attr == DW_AT_addr_base) {
+        UNWIND_CHECK(form == DW_FORM_sec_offset, "unexpected addr_base form");
+        address_base_ = readSegmentOffset(L);
+        LOG_INFO("  address base {:x}\n", address_base_);
+      } else if (attr == DW_AT_rnglists_base) {
+        UNWIND_CHECK(
+            form == DW_FORM_sec_offset, "unexpected rnglists_base form");
+        rnglists_base_ = readSegmentOffset(L);
+        LOG_INFO("  range base {:x}\n", *rnglists_base_);
+      } else if (form == DW_FORM_string) {
+        L.readCString();
+      } else if (attr == DW_AT_stmt_list) {
+        UNWIND_CHECK(form == DW_FORM_sec_offset, "unexpected stmt_list form");
+        LOG_INFO("  program table offset {:x}\n", *line_number_program_offset_);
+        line_number_program_offset_ = readSegmentOffset(L);
+      } else if (form == DW_FORM_exprloc) {
+        auto sz = L.readULEB128();
+        L.skip(int64_t(sz));
+      } else if (form == DW_FORM_block1) {
+        auto sz = L.read();
+        L.skip(int64_t(sz));
+      } else if (attr == DW_AT_ranges) {
+        auto range_offset = readEncoded(L, form);
+        LOG_INFO("setting range_ptr to {:x} {:x}\n", range_offset, form);
+        range_ptr_.emplace(range_offset, form);
+      } else if (
+          form == DW_FORM_udata || form == DW_FORM_rnglistx ||
+          form == DW_FORM_strx || form == DW_FORM_loclistx ||
+          form == DW_FORM_addrx) {
+        L.readULEB128();
+      } else if (form == DW_FORM_sdata) {
+        L.readSLEB128();
+      } else {
+        auto sz = formSize(form, sec_offset_size_);
+        UNWIND_CHECK(sz, "unsupported form in compilation unit {:x}", form);
+        L.skip(int64_t(*sz));
+      }
+    }
+  }
+
+  std::vector> readRanges4(uint64_t offset) {
+    CheckedLexer L = s_.debug_ranges.lexer(offset);
+    std::vector> ranges;
+    uint64_t base = lowpc_;
+    while (true) {
+      auto start = L.read();
+      auto end = L.read();
+      if (start == 0 && end == 0) {
+        break;
+      }
+      if (start == std::numeric_limits::max()) {
+        base = end;
+      } else {
+        ranges.emplace_back(base + start, base + end);
+      }
+    }
+    return ranges;
+  }
+
+  std::vector> readRanges5(uint64_t offset) {
+    CheckedLexer L = s_.debug_rnglists.lexer(offset);
+    uint64_t base = 0;
+    LOG_INFO("BEGIN RANGES {:x}\n", offset);
+    std::vector> ranges;
+    while (true) {
+      auto op = L.read();
+      switch (op) {
+        case DW_RLE_end_of_list:
+          LOG_INFO("END RANGES\n");
+          return ranges;
+        case DW_RLE_base_addressx: {
+          base = readEncoded(L, DW_FORM_addrx);
+          LOG_INFO("BASE ADDRX {:x}\n", base);
+        } break;
+        case DW_RLE_startx_length: {
+          auto s = readEncoded(L, DW_FORM_addrx);
+          auto e = L.readULEB128();
+          LOG_INFO("startx_length {:x} {:x}\n", s, e);
+          ranges.emplace_back(s, s + e);
+        } break;
+        case DW_RLE_base_address:
+          base = L.read();
+          LOG_INFO("BASE ADDR {:x}\n", base);
+          break;
+        case DW_RLE_offset_pair: {
+          auto s = L.readULEB128();
+          auto e = L.readULEB128();
+          LOG_INFO("offset_pair {:x} {:x}\n", s, e);
+          ranges.emplace_back(base + s, base + e);
+        } break;
+        case DW_RLE_start_length: {
+          auto s = L.read();
+          auto e = L.readULEB128();
+          LOG_INFO("start_length {:x} {:x}\n", s, e);
+          ranges.emplace_back(s, s + e);
+        } break;
+        default:
+          UNWIND_CHECK(false, "unknown range op: {}", op);
+      }
+    }
+  }
+
+  CheckedLexer findAbbrev(uint64_t offset, uint64_t entry) {
+    CheckedLexer L = s_.debug_abbrev.lexer(offset);
+    while (true) {
+      auto abbrev_code = L.readULEB128();
+      UNWIND_CHECK(
+          abbrev_code != 0,
+          "could not find entry {} at offset {:x}",
+          entry,
+          offset);
+      auto tag = L.readULEB128();
+      L.read(); // has children
+      if (abbrev_code == entry) {
+        UNWIND_CHECK(
+            tag == DW_TAG_compile_unit,
+            "first entry was not a compile unit but {}",
+            tag);
+        return L;
+      }
+      while (true) {
+        auto attr = L.readULEB128();
+        auto form = L.readULEB128();
+        if (attr == 0 && form == 0) {
+          break;
+        }
+        if (form == DW_FORM_implicit_const) {
+          L.readSLEB128();
+        }
+      }
+    }
+  }
+
+  Sections& s_;
+  std::optional line_number_program_offset_;
+  uint64_t offset_ = 0;
+  uint8_t sec_offset_size_ = 0;
+  uint64_t length_ = 0;
+  const char* end_ = nullptr;
+  uint64_t debug_abbrev_offset_ = 0;
+  bool is_64bit_ = false;
+
+  std::optional> range_ptr_;
+  uint64_t lowpc_ = 0;
+  std::optional highpc_;
+  uint16_t version_ = 0;
+  uint64_t address_base_ = 0;
+  std::optional rnglists_base_;
+};
+
+} // namespace torch::unwind
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/dwarf_enums.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/dwarf_enums.h
new file mode 100644
index 0000000000000000000000000000000000000000..91af24b34e1f97b02bedba2e59397495c5213719
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/dwarf_enums.h
@@ -0,0 +1,46 @@
+#pragma once
+
+enum {
+  DW_EH_PE_absptr = 0x00,
+  DW_EH_PE_omit = 0xff,
+  /* FDE data encoding.  */
+  DW_EH_PE_uleb128 = 0x01,
+  DW_EH_PE_udata2 = 0x02,
+  DW_EH_PE_udata4 = 0x03,
+  DW_EH_PE_udata8 = 0x04,
+  DW_EH_PE_sleb128 = 0x09,
+  DW_EH_PE_sdata2 = 0x0a,
+  DW_EH_PE_sdata4 = 0x0b,
+  DW_EH_PE_sdata8 = 0x0c,
+  DW_EH_PE_signed = 0x08,
+  /* FDE flags.  */
+  DW_EH_PE_pcrel = 0x10,
+  DW_EH_PE_textrel = 0x20,
+  DW_EH_PE_datarel = 0x30,
+  DW_EH_PE_funcrel = 0x40,
+  DW_EH_PE_aligned = 0x50,
+  DW_EH_PE_indirect = 0x80,
+};
+
+enum {
+  DW_CFA_nop = 0x0,
+  DW_CFA_advance_loc = 0x01,
+  DW_CFA_offset = 0x02,
+  DW_CFA_restore = 0x03,
+  DW_CFA_advance_loc1 = 0x02,
+  DW_CFA_advance_loc2 = 0x03,
+  DW_CFA_advance_loc4 = 0x04,
+  DW_CFA_restore_extended = 0x06,
+  DW_CFA_undefined = 0x07,
+  DW_CFA_register = 0x09,
+  DW_CFA_remember_state = 0x0a,
+  DW_CFA_restore_state = 0x0b,
+  DW_CFA_def_cfa = 0x0c,
+  DW_CFA_def_cfa_register = 0x0d,
+  DW_CFA_def_cfa_offset = 0x0e,
+  DW_CFA_def_cfa_expression = 0xf,
+  DW_CFA_expression = 0x10,
+  DW_CFA_offset_extended_sf = 0x11,
+  DW_CFA_GNU_args_size = 0x2e,
+  DW_OP_deref = 0x6,
+};
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/dwarf_symbolize_enums.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/dwarf_symbolize_enums.h
new file mode 100644
index 0000000000000000000000000000000000000000..3fa56b26d555f8b75debd9153c22436dee6306a0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/dwarf_symbolize_enums.h
@@ -0,0 +1,179 @@
+#pragma once
+#include 
+#include 
+#include 
+
+enum {
+  DW_TAG_subprogram = 0x2e,
+  DW_TAG_inlined_subroutine = 0x1d,
+  DW_TAG_compile_unit = 0x11,
+  DW_AT_sibling = 0x1, // reference
+  DW_AT_name = 0x3, // string
+  DW_AT_stmt_list = 0x10, // lineptr
+  DW_AT_addr_base = 0x73, // sec_offset
+  DW_AT_rnglists_base = 0x74, // sec_offset
+  DW_AT_low_pc = 0x11, // address
+  DW_AT_high_pc = 0x12, // address
+  DW_AT_specification = 0x47, // reference
+  DW_AT_abstract_origin = 0x31, // reference
+  DW_AT_linkage_name = 0x6e, // string
+  DW_AT_ranges = 0x55, // rnglist
+  DW_AT_str_offsets_base = 0x72, // sec_offset
+  DW_FORM_addr = 0x01,
+  DW_FORM_block2 = 0x03,
+  DW_FORM_block4 = 0x04,
+  DW_FORM_data2 = 0x05,
+  DW_FORM_data4 = 0x06,
+  DW_FORM_data8 = 0x07,
+  DW_FORM_string = 0x08,
+  DW_FORM_block = 0x09,
+  DW_FORM_block1 = 0x0a,
+  DW_FORM_data1 = 0x0b,
+  DW_FORM_flag = 0x0c,
+  DW_FORM_sdata = 0x0d,
+  DW_FORM_strp = 0x0e,
+  DW_FORM_udata = 0x0f,
+  DW_FORM_ref_addr = 0x10,
+  DW_FORM_ref1 = 0x11,
+  DW_FORM_ref2 = 0x12,
+  DW_FORM_ref4 = 0x13,
+  DW_FORM_ref8 = 0x14,
+  DW_FORM_ref_udata = 0x15,
+  DW_FORM_indirect = 0x16,
+  DW_FORM_sec_offset = 0x17,
+  DW_FORM_exprloc = 0x18,
+  DW_FORM_flag_present = 0x19,
+  DW_FORM_strx = 0x1a,
+  DW_FORM_addrx = 0x1b,
+  DW_FORM_ref_sup4 = 0x1c,
+  DW_FORM_strp_sup = 0x1d,
+  DW_FORM_data16 = 0x1e,
+  DW_FORM_line_strp = 0x1f,
+  DW_FORM_ref_sig8 = 0x20,
+  DW_FORM_implicit_const = 0x21,
+  DW_FORM_loclistx = 0x22,
+  DW_FORM_rnglistx = 0x23,
+  DW_FORM_ref_sup8 = 0x24,
+  DW_FORM_strx1 = 0x25,
+  DW_FORM_strx2 = 0x26,
+  DW_FORM_strx3 = 0x27,
+  DW_FORM_strx4 = 0x28,
+  DW_FORM_addrx1 = 0x29,
+  DW_FORM_addrx2 = 0x2a,
+  DW_FORM_addrx3 = 0x2b,
+  DW_FORM_addrx4 = 0x2c,
+  /* GNU Debug Fission extensions.  */
+  DW_FORM_GNU_addr_index = 0x1f01,
+  DW_FORM_GNU_str_index = 0x1f02,
+  DW_FORM_GNU_ref_alt = 0x1f20, /* offset in alternate .debuginfo.  */
+  DW_FORM_GNU_strp_alt = 0x1f21, /* offset in alternate .debug_str. */
+  DW_LNCT_path = 0x1,
+  DW_LNCT_directory_index = 0x2,
+  DW_LNS_extended_op = 0x00,
+  DW_LNE_end_sequence = 0x01,
+  DW_LNE_set_address = 0x02,
+  DW_LNS_copy = 0x01,
+  DW_LNS_advance_pc = 0x02,
+  DW_LNS_advance_line = 0x03,
+  DW_LNS_set_file = 0x04,
+  DW_LNS_const_add_pc = 0x08,
+  DW_LNS_fixed_advance_pc = 0x09,
+  DW_RLE_end_of_list = 0x0,
+  DW_RLE_base_addressx = 0x1,
+  DW_RLE_startx_endx = 0x2,
+  DW_RLE_startx_length = 0x3,
+  DW_RLE_offset_pair = 0x4,
+  DW_RLE_base_address = 0x5,
+  DW_RLE_start_end = 0x6,
+  DW_RLE_start_length = 0x7
+};
+
+static std::optional formSize(uint64_t form, uint8_t sec_offset_size) {
+  switch (form) {
+    case DW_FORM_addr:
+      return sizeof(void*);
+    case DW_FORM_block2:
+    case DW_FORM_block4:
+      return std::nullopt;
+    case DW_FORM_data2:
+      return 2;
+    case DW_FORM_data4:
+      return 4;
+    case DW_FORM_data8:
+      return 8;
+    case DW_FORM_string:
+    case DW_FORM_block:
+    case DW_FORM_block1:
+      return std::nullopt;
+    case DW_FORM_data1:
+    case DW_FORM_flag:
+      return 1;
+    case DW_FORM_sdata:
+      return std::nullopt;
+    case DW_FORM_strp:
+      return sec_offset_size;
+    case DW_FORM_udata:
+      return std::nullopt;
+    case DW_FORM_ref_addr:
+      return sec_offset_size;
+    case DW_FORM_ref1:
+      return 1;
+    case DW_FORM_ref2:
+      return 2;
+    case DW_FORM_ref4:
+      return 4;
+    case DW_FORM_ref8:
+      return 8;
+    case DW_FORM_ref_udata:
+    case DW_FORM_indirect:
+      return std::nullopt;
+    case DW_FORM_sec_offset:
+      return sec_offset_size;
+    case DW_FORM_exprloc:
+      return std::nullopt;
+    case DW_FORM_flag_present:
+      return 0;
+    case DW_FORM_strx:
+    case DW_FORM_addrx:
+      return std::nullopt;
+    case DW_FORM_ref_sup4:
+      return 4;
+    case DW_FORM_strp_sup:
+      return sec_offset_size;
+    case DW_FORM_data16:
+      return 16;
+    case DW_FORM_line_strp:
+      return sec_offset_size;
+    case DW_FORM_ref_sig8:
+      return 8;
+    case DW_FORM_implicit_const:
+      return 0;
+    case DW_FORM_loclistx:
+    case DW_FORM_rnglistx:
+      return std::nullopt;
+    case DW_FORM_ref_sup8:
+      return 8;
+    case DW_FORM_strx1:
+      return 1;
+    case DW_FORM_strx2:
+      return 2;
+    case DW_FORM_strx3:
+      return 3;
+    case DW_FORM_strx4:
+      return 4;
+    case DW_FORM_addrx1:
+      return 1;
+    case DW_FORM_addrx2:
+      return 2;
+    case DW_FORM_addrx3:
+      return 3;
+    case DW_FORM_addrx4:
+      return 4;
+    case DW_FORM_GNU_addr_index:
+    case DW_FORM_GNU_str_index:
+    case DW_FORM_GNU_ref_alt:
+    case DW_FORM_GNU_strp_alt:
+    default:
+      return std::nullopt;
+  }
+}
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/eh_frame_hdr.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/eh_frame_hdr.h
new file mode 100644
index 0000000000000000000000000000000000000000..c69c066dae68fd893d276d5122aa586f70b2366c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/eh_frame_hdr.h
@@ -0,0 +1,98 @@
+#pragma once
+#include 
+#include 
+
+#include 
+#include 
+
+// Overview of the format described in
+// https://refspecs.linuxfoundation.org/LSB_1.3.0/gLSB/gLSB/ehframehdr.html
+namespace torch::unwind {
+
+struct EHFrameHdr {
+  EHFrameHdr(void* base) : base_(base) {
+    Lexer L(base, base);
+    version_ = L.read();
+    eh_frame_ptr_enc_ = L.read();
+    fde_count_enc_ = L.read();
+    table_enc_ = L.read();
+    if (table_enc_ == DW_EH_PE_omit) {
+      table_size_ = 0;
+    } else {
+      switch (table_enc_ & 0xF) {
+        case DW_EH_PE_udata2:
+        case DW_EH_PE_sdata2:
+          table_size_ = 2;
+          break;
+        case DW_EH_PE_udata4:
+        case DW_EH_PE_sdata4:
+          table_size_ = 4;
+          break;
+        case DW_EH_PE_udata8:
+        case DW_EH_PE_sdata8:
+          table_size_ = 8;
+          break;
+        case DW_EH_PE_uleb128:
+        case DW_EH_PE_sleb128:
+          throw UnwindError("uleb/sleb table encoding not supported");
+          break;
+        default:
+          throw UnwindError("unknown table encoding");
+      }
+    }
+    eh_frame_ = (void*)L.readEncodedOr(eh_frame_ptr_enc_, 0);
+    fde_count_ = L.readEncodedOr(fde_count_enc_, 0);
+    table_start_ = L.loc();
+  }
+  size_t nentries() const {
+    return fde_count_;
+  }
+
+  uint64_t lowpc(size_t i) const {
+    return Lexer(table_start_, base_)
+        .skip(2 * i * table_size_)
+        .readEncoded(table_enc_);
+  }
+  void* fde(size_t i) const {
+    return (void*)Lexer(table_start_, base_)
+        .skip((2 * i + 1) * table_size_)
+        .readEncoded(table_enc_);
+  }
+
+  void* entryForAddr(uint64_t addr) const {
+    if (!table_size_ || !nentries()) {
+      throw UnwindError("search table not present");
+    }
+    uint64_t low = 0;
+    uint64_t high = nentries();
+    while (low + 1 < high) {
+      auto mid = (low + high) / 2;
+      if (addr < lowpc(mid)) {
+        high = mid;
+      } else {
+        low = mid;
+      }
+    }
+    return fde(low);
+  }
+
+  friend std::ostream& operator<<(std::ostream& out, const EHFrameHdr& self) {
+    out << "EHFrameHeader(version=" << self.version_
+        << ",table_size=" << self.table_size_
+        << ",fde_count=" << self.fde_count_ << ")";
+    return out;
+  }
+
+ private:
+  void* base_;
+  void* table_start_;
+  uint8_t version_;
+  uint8_t eh_frame_ptr_enc_;
+  uint8_t fde_count_enc_;
+  uint8_t table_enc_;
+  void* eh_frame_ = nullptr;
+  int64_t fde_count_;
+  uint32_t table_size_;
+};
+
+} // namespace torch::unwind
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/fast_symbolizer.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/fast_symbolizer.h
new file mode 100644
index 0000000000000000000000000000000000000000..d4201f10c013dc3e944817143e16b4acfb4a3796
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/fast_symbolizer.h
@@ -0,0 +1,108 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch::unwind {
+
+#define UNWIND_WARN(w, ...)                   \
+  do {                                        \
+    w.emplace_back(fmt::format(__VA_ARGS__)); \
+    LOG_INFO("WARNING: {}\n", w.back());      \
+  } while (0);
+
+struct FastSymbolizer {
+  FastSymbolizer() = default;
+  Frame symbolize(const std::string& library, uint64_t offset) {
+    LOG_INFO("symbolizing {} + 0x{:x}\n", library, offset);
+    Frame frame;
+    frame.funcname = "??";
+    frame.filename = library;
+    frame.lineno = offset;
+    auto s = getOrCreateSections(library);
+    if (auto e = s->findSubprogramName(offset)) {
+      frame.funcname = *e;
+    } else {
+      UNWIND_WARN(
+          warnings_,
+          "failed to find subprogram name for {} 0x{:x}",
+          library,
+          offset);
+    }
+    if (auto e = findLine(s, offset)) {
+      frame.filename = e->first;
+      frame.lineno = e->second;
+    } else {
+      UNWIND_WARN(
+          warnings_, "failed to find file/line for {} 0x{:x}", library, offset);
+    }
+    return frame;
+  }
+  const std::vector& warnings() {
+    return warnings_;
+  }
+
+ private:
+  void parseDebugInfo(Sections* s) {
+    uint64_t offset = 0;
+    while (offset < s->debug_info.size) {
+      DebugInfo info(*s);
+      info.parse(offset);
+      if (auto lnp_offset = info.lineNumberProgramOffset()) {
+        for (auto r : info.ranges()) {
+          s->addDebugInfoRange(r.first, r.second, line_number_programs_.size());
+        }
+        line_number_programs_.emplace_back(
+            std::make_unique(*s, *lnp_offset));
+      }
+      offset = info.nextOffset();
+    }
+  }
+  Sections* getOrCreateSections(const std::string& library) {
+    auto it = libraries_.find(library);
+    if (it == libraries_.end()) {
+      it = libraries_.insert({library, std::make_unique()}).first;
+      try {
+        Sections* s = it->second.get();
+        s->parse(library.c_str());
+        parseDebugInfo(s);
+      } catch (UnwindError& err) {
+        UNWIND_WARN(
+            warnings_, "failed to parse library {}: {}", library, err.what());
+      }
+    }
+    return it->second.get();
+  }
+  std::optional> findLine(
+      Sections* s,
+      uint64_t offset) {
+    if (auto idx = s->findDebugInfoOffset(offset)) {
+      auto r = line_number_programs_.at(*idx).get();
+      try {
+        r->parse();
+      } catch (UnwindError& err) {
+        UNWIND_WARN(
+            warnings_,
+            "failed to read line number program [{:x}] {}",
+            r->offset(),
+            err.what());
+      }
+      if (auto e = r->find(offset)) {
+        return std::make_pair(r->filename(e->file), e->line);
+      }
+    }
+    return std::nullopt;
+  }
+  std::unordered_map> libraries_;
+  std::vector> line_number_programs_;
+  std::vector warnings_;
+};
+
+} // namespace torch::unwind
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/fde.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/fde.h
new file mode 100644
index 0000000000000000000000000000000000000000..ea8b4ca94eaea51246aa6cd9d67ce8537824654b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/fde.h
@@ -0,0 +1,404 @@
+#pragma once
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch::unwind {
+
+struct TableState {
+  Action cfa;
+  std::array registers;
+  friend std::ostream& operator<<(std::ostream& out, const TableState& self) {
+    out << "cfa = " << self.cfa << "; ";
+    for (auto r : c10::irange(self.registers.size())) {
+      if (self.registers.at(r).kind != A_UNDEFINED) {
+        out << "r" << r << " = " << self.registers.at(r) << "; ";
+      }
+    }
+    return out;
+  }
+};
+
+// FDE - Frame Description Entry (Concept in ELF spec)
+// This format is explained well by
+// https://www.airs.com/blog/archives/460
+// Details of different dwarf actions are explained
+// in the spec document:
+// https://web.archive.org/web/20221129184704/https://dwarfstd.org/doc/DWARF4.doc
+// An overview of how DWARF unwinding works is given in
+// https://dl.acm.org/doi/pdf/10.1145/3360572
+// A similar implementation written in rust is:
+// https://github.com/mstange/framehop/
+
+template 
+struct FDE {
+  FDE(void* data, const char* library_name, uint64_t load_bias)
+      : library_name_(library_name), load_bias_(load_bias) {
+    Lexer L(data);
+    auto length = L.read4or8Length();
+    void* fde_start = L.loc();
+    void* cie_data = (void*)((int64_t)fde_start - L.read());
+    Lexer LC(cie_data);
+    auto cie_length = LC.read4or8Length();
+    void* cie_start = LC.loc();
+    auto zero = LC.read();
+    TORCH_INTERNAL_ASSERT(zero == 0, "expected 0 for CIE");
+    auto version = LC.read();
+    TORCH_INTERNAL_ASSERT(
+        version == 1 || version == 3, "non-1 version for CIE");
+    augmentation_string_ = LC.readCString();
+    if (hasAugmentation("eh")) {
+      throw UnwindError("unsupported 'eh' augmentation string");
+    }
+    code_alignment_factor_ = LC.readULEB128();
+    data_alignment_factor_ = LC.readSLEB128();
+    if (version == 1) {
+      ra_register_ = LC.read();
+    } else {
+      ra_register_ = LC.readULEB128();
+    }
+    // we assume this in the state
+    TORCH_INTERNAL_ASSERT(ra_register_ == 16, "unexpected number of registers");
+    if (augmentation_string_ && *augmentation_string_ == 'z') {
+      augmentation_length_ = LC.readULEB128();
+      Lexer A(LC.loc());
+      for (auto ap = augmentation_string_ + 1; *ap; ap++) {
+        switch (*ap) {
+          case 'L':
+            lsda_enc = A.read();
+            break;
+          case 'R':
+            fde_enc = A.read();
+            break;
+          case 'P': {
+            uint8_t personality_enc = A.read();
+            A.readEncoded(personality_enc);
+          } break;
+          case 'S': {
+            // signal handler
+          } break;
+          default: {
+            throw UnwindError("unknown augmentation string");
+          } break;
+        }
+      }
+    }
+    LC.skip(augmentation_length_);
+    low_pc_ = L.readEncoded(fde_enc);
+    high_pc_ = low_pc_ + L.readEncodedValue(fde_enc);
+
+    if (hasAugmentation("z")) {
+      augmentation_length_fde_ = L.readULEB128();
+    }
+    L.readEncodedOr(lsda_enc, 0);
+
+    cie_begin_ = LC.loc();
+    fde_begin_ = L.loc();
+    cie_end_ = (void*)((const char*)cie_start + cie_length);
+    fde_end_ = (void*)((const char*)fde_start + length);
+  }
+
+  // OP Code implementations
+
+  void advance_raw(int64_t amount) {
+    auto previous_pc = current_pc_;
+    current_pc_ += amount;
+    if (LOG) {
+      (*out_) << (void*)(previous_pc - load_bias_) << "-"
+              << (void*)(current_pc_ - load_bias_) << ": " << state() << "\n";
+    }
+  }
+
+  void advance_loc(int64_t amount) {
+    if (LOG) {
+      (*out_) << "advance_loc " << amount << "\n";
+    }
+    advance_raw(amount * code_alignment_factor_);
+  }
+
+  void offset(int64_t reg, int64_t offset) {
+    if (LOG) {
+      (*out_) << "offset " << reg << " " << offset << "\n";
+    }
+    if (reg > (int64_t)state().registers.size()) {
+      if (LOG) {
+        (*out_) << "OFFSET OF BIG REGISTER " << reg << "ignored...\n";
+      }
+      return;
+    }
+    state().registers.at(reg) =
+        Action{A_LOAD_CFA_OFFSET, -1, offset * data_alignment_factor_};
+  }
+
+  void restore(int64_t reg) {
+    if (LOG) {
+      (*out_) << "restore " << reg << "\n";
+    }
+    if (reg > (int64_t)state().registers.size()) {
+      if (LOG) {
+        (*out_) << "RESTORE OF BIG REGISTER " << reg << "ignored...\n";
+      }
+      return;
+    }
+    state().registers.at(reg) = initial_state_.registers.at(reg);
+  }
+
+  void def_cfa(int64_t reg, int64_t off) {
+    if (LOG) {
+      (*out_) << "def_cfa " << reg << " " << off << "\n";
+    }
+    last_reg_ = reg;
+    last_offset_ = off;
+    state().cfa = Action::regPlusData(reg, off);
+  }
+  void def_cfa_register(int64_t reg) {
+    def_cfa(reg, last_offset_);
+  }
+  void def_cfa_offset(int64_t off) {
+    def_cfa(last_reg_, off);
+  }
+
+  void remember_state() {
+    if (LOG) {
+      (*out_) << "remember_state\n";
+    }
+    state_stack_.push_back(state());
+  }
+  void restore_state() {
+    if (LOG) {
+      (*out_) << "restore_state\n";
+    }
+    state_stack_.pop_back();
+  }
+
+  void undefined(int64_t reg) {
+    if (LOG) {
+      (*out_) << "undefined " << reg << "\n";
+    }
+    state().registers.at(reg) = Action::undefined();
+  }
+  void register_(int64_t reg, int64_t rhs_reg) {
+    if (LOG) {
+      (*out_) << "register " << reg << " " << rhs_reg << "\n";
+    }
+    state().registers.at(reg) = Action::regPlusData(reg, 0);
+  }
+
+  TableState& state() {
+    return state_stack_.back();
+  }
+
+  void dump(std::ostream& out) {
+    out_ = &out;
+    out << "FDE(augmentation_string=" << augmentation_string_
+        << ", low_pc=" << (void*)(low_pc_ - load_bias_)
+        << ",high_pc=" << (void*)(high_pc_ - load_bias_)
+        << ",code_alignment_factor=" << code_alignment_factor_
+        << ", data_alignment_factor=" << data_alignment_factor_
+        << ", ra_register_=" << ra_register_ << ")\n";
+    readUpTo(high_pc_);
+    out_ = &std::cout;
+  }
+
+  TableState readUpTo(uint64_t addr) {
+    if (addr < low_pc_ || addr > high_pc_) {
+      throw UnwindError("Address not in range");
+    }
+    if (LOG) {
+      (*out_) << "readUpTo " << (void*)addr << " for " << library_name_
+              << " at " << (void*)load_bias_ << "\n";
+    }
+    state_stack_.emplace_back();
+    current_pc_ = low_pc_;
+    // parse instructions...
+    Lexer LC(cie_begin_);
+    while (LC.loc() < cie_end_ && current_pc_ <= addr) {
+      readInstruction(LC);
+    }
+    if (current_pc_ > addr) {
+      return state();
+    }
+
+    initial_state_ = state_stack_.back();
+
+    if (LOG) {
+      (*out_) << "--\n";
+    }
+
+    Lexer L(fde_begin_);
+    while (L.loc() < fde_end_ && current_pc_ <= addr) {
+      readInstruction(L);
+    }
+    // so that we print the full range in debugging
+    if (current_pc_ <= addr) {
+      advance_raw(addr - current_pc_);
+    }
+    return state();
+  }
+
+  void dumpAddr2Line() {
+    std::cout << "addr2line -f -e " << library_name_ << " "
+              << (void*)(low_pc_ - load_bias_) << "\n";
+  }
+
+  void readInstruction(Lexer& L) {
+    uint8_t bc = L.read();
+    auto op = bc >> 6;
+    auto lowbits = bc & 0x3F;
+    switch (op) {
+      case 0x0: {
+        switch (lowbits) {
+          case DW_CFA_nop: {
+            return; // nop
+          }
+          case DW_CFA_advance_loc1: {
+            auto delta = L.read();
+            return advance_loc(delta);
+          }
+          case DW_CFA_advance_loc2: {
+            auto delta = L.read();
+            return advance_loc(delta);
+          }
+          case DW_CFA_advance_loc4: {
+            auto delta = L.read();
+            return advance_loc(delta);
+          }
+          case DW_CFA_restore_extended: {
+            auto reg = L.readULEB128();
+            return restore(reg);
+          }
+          case DW_CFA_undefined: {
+            auto reg = L.readULEB128();
+            return undefined(reg);
+          }
+          case DW_CFA_register: {
+            auto reg = L.readULEB128();
+            auto rhs_reg = L.readULEB128();
+            return register_(reg, rhs_reg);
+          }
+          case DW_CFA_def_cfa: {
+            auto reg = L.readULEB128();
+            auto off = L.readULEB128();
+            return def_cfa(reg, off);
+          }
+          case DW_CFA_def_cfa_register: {
+            auto reg = L.readULEB128();
+            return def_cfa_register(reg);
+          }
+          case DW_CFA_def_cfa_offset: {
+            auto off = L.readULEB128();
+            return def_cfa_offset(off);
+          }
+          case DW_CFA_offset_extended_sf: {
+            auto reg = L.readULEB128();
+            auto off = L.readSLEB128();
+            return offset(reg, off);
+          }
+          case DW_CFA_remember_state: {
+            return remember_state();
+          }
+          case DW_CFA_restore_state: {
+            return restore_state();
+          }
+          case DW_CFA_GNU_args_size: {
+            // GNU_args_size, we do not need to know it..
+            L.readULEB128();
+            return;
+          }
+          case DW_CFA_expression: {
+            auto reg = L.readULEB128();
+            auto len = L.readULEB128();
+            auto end = (void*)((uint64_t)L.loc() + len);
+            auto op = L.read();
+            if ((op & 0xF0) == 0x70) { // DW_bregX
+              auto rhs_reg = (op & 0xF);
+              auto addend = L.readSLEB128();
+              if (L.loc() == end) {
+                state().registers.at(reg) =
+                    Action::regPlusDataDeref(rhs_reg, addend);
+                return;
+              }
+            }
+            throw UnwindError("Unsupported dwarf expression");
+          }
+          case DW_CFA_def_cfa_expression: {
+            auto len = L.readULEB128();
+            auto end = (void*)((uint64_t)L.loc() + len);
+            auto op = L.read();
+            if ((op & 0xF0) == 0x70) { // DW_bregX
+              auto rhs_reg = (op & 0xF);
+              auto addend = L.readSLEB128();
+              if (L.loc() != end) {
+                auto op2 = L.read();
+                if (op2 == DW_OP_deref && L.loc() == end) { // deref
+                  state().cfa = Action::regPlusDataDeref(rhs_reg, addend);
+                  return;
+                }
+              }
+            }
+            throw UnwindError("Unsupported def_cfa dwarf expression");
+          }
+          default: {
+            std::stringstream ss;
+            ss << "unknown op code " << (void*)(uint64_t)lowbits;
+            throw UnwindError(ss.str());
+          }
+        }
+      }
+      case DW_CFA_advance_loc: {
+        return advance_loc(lowbits);
+      }
+      case DW_CFA_offset: {
+        auto off = L.readULEB128();
+        return offset(lowbits, off);
+      }
+      case DW_CFA_restore: {
+        return restore(lowbits);
+      }
+    }
+  }
+  // used for debug printing
+  const char* library_name_;
+  uint64_t load_bias_;
+
+  // parsed from the eh_string data structures:
+  const char* augmentation_string_ = nullptr;
+  int64_t augmentation_length_ = 0;
+  int64_t augmentation_length_fde_ = 0;
+
+  int64_t code_alignment_factor_;
+  int64_t data_alignment_factor_;
+  void* cie_data_;
+
+  int64_t ra_register_;
+  uint8_t lsda_enc = DW_EH_PE_omit;
+  uint8_t fde_enc = DW_EH_PE_absptr;
+  uint64_t low_pc_ = UINT64_MAX;
+  uint64_t high_pc_ = UINT64_MAX;
+
+  void* cie_begin_;
+  void* fde_begin_;
+  void* cie_end_;
+  void* fde_end_;
+
+  // state accumulated while parsing instructions
+  int64_t last_reg_ = 0;
+  int64_t last_offset_ = 0;
+  uint64_t current_pc_;
+
+  TableState
+      initial_state_; // state after the initial instructions, used by restore
+  std::vector state_stack_;
+
+  std::ostream* out_ = &std::cout; // for debug dumping
+ private:
+  bool hasAugmentation(const char* s) {
+    return strstr(augmentation_string_, s) != nullptr;
+  }
+};
+
+} // namespace torch::unwind
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/lexer.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/lexer.h
new file mode 100644
index 0000000000000000000000000000000000000000..117df6b9b028674aae0ff7766368a0bd74a63953
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/lexer.h
@@ -0,0 +1,159 @@
+#pragma once
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+namespace torch::unwind {
+
+template 
+struct LexerImpl {
+  LexerImpl(void* data, void* base = nullptr, void* end = nullptr)
+      : next_((const char*)data),
+        base_((int64_t)base),
+        end_((const char*)end) {}
+
+  template 
+  T read() {
+    T result;
+    auto end = next_ + sizeof(T);
+    UNWIND_CHECK(
+        !checked || end <= end_,
+        "read out of bounds {} >= {}",
+        (void*)end,
+        (void*)end_);
+    memcpy(&result, next_, sizeof(T));
+    next_ = end;
+    return result;
+  }
+
+  // SLEB/ULEB code adapted from LLVM equivalents
+  int64_t readSLEB128() {
+    int64_t Value = 0;
+    unsigned Shift = 0;
+    uint8_t Byte = 0;
+    do {
+      Byte = read();
+      uint64_t Slice = Byte & 0x7f;
+      if ((Shift >= 64 && Slice != (Value < 0 ? 0x7f : 0x00)) ||
+          (Shift == 63 && Slice != 0 && Slice != 0x7f)) {
+        throw UnwindError("sleb128 too big for int64");
+      }
+      Value |= int64_t(Slice << Shift);
+      Shift += 7;
+    } while (Byte >= 128);
+    // Sign extend negative numbers if needed.
+    if (Shift < 64 && (Byte & 0x40)) {
+      Value |= int64_t((-1ULL) << Shift);
+    }
+    return Value;
+  }
+
+  uint64_t readULEB128() {
+    uint64_t Value = 0;
+    unsigned Shift = 0;
+    uint8_t p = 0;
+    do {
+      p = read();
+      uint64_t Slice = p & 0x7f;
+      if ((Shift >= 64 && Slice != 0) || Slice << Shift >> Shift != Slice) {
+        throw UnwindError("uleb128 too big for uint64");
+      }
+      Value += Slice << Shift;
+      Shift += 7;
+    } while (p >= 128);
+    return Value;
+  }
+  const char* readCString() {
+    auto result = next_;
+    if (!checked) {
+      next_ += strlen(next_) + 1;
+      return result;
+    }
+    while (next_ < end_) {
+      if (*next_++ == '\0') {
+        return result;
+      }
+    }
+    UNWIND_CHECK(
+        false, "string is out of bounds {} >= {}", (void*)next_, (void*)end_);
+  }
+  int64_t readEncoded(uint8_t enc) {
+    int64_t r = 0;
+    switch (enc & (~DW_EH_PE_indirect & 0xF0)) {
+      case DW_EH_PE_absptr:
+        break;
+      case DW_EH_PE_pcrel:
+        r = (int64_t)next_;
+        break;
+      case DW_EH_PE_datarel:
+        r = base_;
+        break;
+      default:
+        throw UnwindError("unknown encoding");
+    }
+    return r + readEncodedValue(enc);
+  }
+  int64_t readEncodedOr(uint8_t enc, int64_t orelse) {
+    if (enc == DW_EH_PE_omit) {
+      return orelse;
+    }
+    return readEncoded(enc);
+  }
+
+  int64_t read4or8Length() {
+    return readSectionLength().first;
+  }
+
+  std::pair readSectionLength() {
+    int64_t length = read();
+    if (length == 0xFFFFFFFF) {
+      return std::make_pair(read(), true);
+    }
+    return std::make_pair(length, false);
+  }
+
+  void* loc() const {
+    return (void*)next_;
+  }
+  LexerImpl& skip(int64_t bytes) {
+    next_ += bytes;
+    return *this;
+  }
+
+  int64_t readEncodedValue(uint8_t enc) {
+    switch (enc & 0xF) {
+      case DW_EH_PE_udata2:
+        return read();
+      case DW_EH_PE_sdata2:
+        return read();
+      case DW_EH_PE_udata4:
+        return read();
+      case DW_EH_PE_sdata4:
+        return read();
+      case DW_EH_PE_udata8:
+        return read();
+      case DW_EH_PE_sdata8:
+        return read();
+      case DW_EH_PE_uleb128:
+        return readULEB128();
+      case DW_EH_PE_sleb128:
+        return readSLEB128();
+      default:
+        throw UnwindError("not implemented");
+    }
+  }
+
+ private:
+  const char* next_;
+  int64_t base_;
+  const char* end_;
+};
+
+// using Lexer = LexerImpl;
+using CheckedLexer = LexerImpl;
+using Lexer = LexerImpl;
+
+} // namespace torch::unwind
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/line_number_program.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/line_number_program.h
new file mode 100644
index 0000000000000000000000000000000000000000..ebebbf1d041eedbaa4638b8d1273d9c8ed016b0d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/line_number_program.h
@@ -0,0 +1,325 @@
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch::unwind {
+
+struct LineNumberProgram {
+  LineNumberProgram(Sections& s, uint64_t offset) : s_(s), offset_(offset) {}
+
+  uint64_t offset() {
+    return offset_;
+  }
+  void parse() {
+    if (parsed_) {
+      return;
+    }
+    parsed_ = true;
+    CheckedLexer L = s_.debug_line.lexer(offset_);
+    std::tie(length_, is_64bit_) = L.readSectionLength();
+    program_end_ = (char*)L.loc() + length_;
+    auto version = L.read();
+    UNWIND_CHECK(
+        version == 5 || version == 4,
+        "expected version 4 or 5 but found {}",
+        version);
+    if (version == 5) {
+      auto address_size = L.read();
+      UNWIND_CHECK(
+          address_size == 8,
+          "expected 64-bit dwarf but found address size {}",
+          address_size);
+      segment_selector_size_ = L.read();
+    }
+    header_length_ = is_64bit_ ? L.read() : L.read();
+    program_ = L;
+    program_.skip(int64_t(header_length_));
+    minimum_instruction_length_ = L.read();
+    maximum_operations_per_instruction_ = L.read();
+    default_is_stmt_ = L.read();
+    line_base_ = L.read();
+    line_range_ = L.read();
+    opcode_base_ = L.read();
+    UNWIND_CHECK(line_range_ != 0, "line_range_ must be non-zero");
+    standard_opcode_lengths_.resize(opcode_base_);
+    for (size_t i = 1; i < opcode_base_; i++) {
+      standard_opcode_lengths_[i] = L.read();
+    }
+    // fmt::print("{:x} {:x} {} {} {} {} {}\n", offset_, header_length_,
+    // minimum_instruction_length_, maximum_operations_per_instruction_,
+    // line_base_, line_range_, opcode_base_);
+    uint8_t directory_entry_format_count = L.read();
+
+    if (version == 5) {
+      struct Member {
+        uint64_t content_type;
+        uint64_t form;
+      };
+      std::vector directory_members;
+      for (size_t i = 0; i < directory_entry_format_count; i++) {
+        directory_members.push_back({L.readULEB128(), L.readULEB128()});
+      }
+      uint64_t directories_count = L.readULEB128();
+      for (size_t i = 0; i < directories_count; i++) {
+        for (auto& member : directory_members) {
+          switch (member.content_type) {
+            case DW_LNCT_path: {
+              include_directories_.emplace_back(
+                  s_.readString(L, member.form, is_64bit_));
+            } break;
+            default: {
+              skipForm(L, member.form);
+            } break;
+          }
+        }
+      }
+
+      for (auto i : c10::irange(directories_count)) {
+        (void)i;
+        LOG_INFO("{} {}\n", i, include_directories_[i]);
+      }
+      auto file_name_entry_format_count = L.read();
+      std::vector file_members;
+      for (size_t i = 0; i < file_name_entry_format_count; i++) {
+        file_members.push_back({L.readULEB128(), L.readULEB128()});
+      }
+      auto files_count = L.readULEB128();
+      for (size_t i = 0; i < files_count; i++) {
+        for (auto& member : file_members) {
+          switch (member.content_type) {
+            case DW_LNCT_path: {
+              file_names_.emplace_back(
+                  s_.readString(L, member.form, is_64bit_));
+            } break;
+            case DW_LNCT_directory_index: {
+              file_directory_index_.emplace_back(readData(L, member.form));
+              UNWIND_CHECK(
+                  file_directory_index_.back() < include_directories_.size(),
+                  "directory index out of range");
+            } break;
+            default: {
+              skipForm(L, member.form);
+            } break;
+          }
+        }
+      }
+      for (auto i : c10::irange(files_count)) {
+        (void)i;
+        LOG_INFO("{} {} {}\n", i, file_names_[i], file_directory_index_[i]);
+      }
+    } else {
+      include_directories_.emplace_back(""); // implicit cwd
+      while (true) {
+        auto str = L.readCString();
+        if (*str == '\0') {
+          break;
+        }
+        include_directories_.emplace_back(str);
+      }
+      file_names_.emplace_back("");
+      file_directory_index_.emplace_back(0);
+      while (true) {
+        auto str = L.readCString();
+        if (*str == '\0') {
+          break;
+        }
+        auto directory_index = L.readULEB128();
+        L.readULEB128(); // mod_time
+        L.readULEB128(); // file_length
+        file_names_.emplace_back(str);
+        file_directory_index_.push_back(directory_index);
+      }
+    }
+    UNWIND_CHECK(
+        maximum_operations_per_instruction_ == 1,
+        "maximum_operations_per_instruction_ must be 1");
+    UNWIND_CHECK(
+        minimum_instruction_length_ == 1,
+        "minimum_instruction_length_ must be 1");
+    readProgram();
+  }
+  struct Entry {
+    uint32_t file = 1;
+    int64_t line = 1;
+  };
+  std::optional find(uint64_t address) {
+    auto e = program_index_.find(address);
+    if (!e) {
+      return std::nullopt;
+    }
+    return all_programs_.at(*e).find(address);
+  }
+  std::string filename(uint64_t index) {
+    return fmt::format(
+        "{}/{}",
+        include_directories_.at(file_directory_index_.at(index)),
+        file_names_.at(index));
+  }
+
+ private:
+  void skipForm(CheckedLexer& L, uint64_t form) {
+    auto sz = formSize(form, is_64bit_ ? 8 : 4);
+    UNWIND_CHECK(sz, "unsupported form {}", form);
+    L.skip(int64_t(*sz));
+  }
+
+  uint64_t readData(CheckedLexer& L, uint64_t encoding) {
+    switch (encoding) {
+      case DW_FORM_data1:
+        return L.read();
+      case DW_FORM_data2:
+        return L.read();
+      case DW_FORM_data4:
+        return L.read();
+      case DW_FORM_data8:
+        return L.read();
+      case DW_FORM_udata:
+        return L.readULEB128();
+      default:
+        UNWIND_CHECK(false, "unsupported data encoding {}", encoding);
+    }
+  }
+
+  void produceEntry() {
+    if (shadow_) {
+      return;
+    }
+    if (ranges_.size() == 1) {
+      start_address_ = address_;
+    }
+    PRINT_LINE_TABLE(
+        "{:x}\t{}\t{}\n", address_, filename(entry_.file), entry_.line);
+    UNWIND_CHECK(
+        entry_.file < file_names_.size(),
+        "file index {} > {} entries",
+        entry_.file,
+        file_names_.size());
+    ranges_.add(address_, entry_, true);
+  }
+  void endSequence() {
+    if (shadow_) {
+      return;
+    }
+    PRINT_LINE_TABLE(
+        "{:x}\tEND\n", address_, filename(entry_.file), entry_.line);
+    program_index_.add(start_address_, all_programs_.size(), false);
+    program_index_.add(address_, std::nullopt, false);
+    all_programs_.emplace_back(std::move(ranges_));
+    ranges_ = RangeTable();
+  }
+  void readProgram() {
+    while (program_.loc() < program_end_) {
+      PRINT_INST("{:x}: ", (char*)program_.loc() - (s_.debug_line.data));
+      uint8_t op = program_.read();
+      if (op >= opcode_base_) {
+        auto op2 = int64_t(op - opcode_base_);
+        address_ += op2 / line_range_;
+        entry_.line += line_base_ + (op2 % line_range_);
+        PRINT_INST(
+            "address += {}, line += {}\n",
+            op2 / line_range_,
+            line_base_ + (op2 % line_range_));
+        produceEntry();
+      } else {
+        switch (op) {
+          case DW_LNS_extended_op: {
+            auto len = program_.readULEB128();
+            auto extended_op = program_.read();
+            switch (extended_op) {
+              case DW_LNE_end_sequence: {
+                PRINT_INST("end_sequence\n");
+                endSequence();
+                entry_ = Entry{};
+              } break;
+              case DW_LNE_set_address: {
+                address_ = program_.read();
+                if (!shadow_) {
+                  PRINT_INST(
+                      "set address {:x} {:x} {:x}\n",
+                      address_,
+                      min_address_,
+                      max_address_);
+                }
+                shadow_ = address_ == 0;
+              } break;
+              default: {
+                PRINT_INST("skip extended op {}\n", extended_op);
+                program_.skip(int64_t(len - 1));
+              } break;
+            }
+          } break;
+          case DW_LNS_copy: {
+            PRINT_INST("copy\n");
+            produceEntry();
+          } break;
+          case DW_LNS_advance_pc: {
+            PRINT_INST("advance pc\n");
+            address_ += program_.readULEB128();
+          } break;
+          case DW_LNS_advance_line: {
+            entry_.line += program_.readSLEB128();
+            PRINT_INST("advance line {}\n", entry_.line);
+
+          } break;
+          case DW_LNS_set_file: {
+            PRINT_INST("set file\n");
+            entry_.file = program_.readULEB128();
+          } break;
+          case DW_LNS_const_add_pc: {
+            PRINT_INST("const add pc\n");
+            address_ += (255 - opcode_base_) / line_range_;
+          } break;
+          case DW_LNS_fixed_advance_pc: {
+            PRINT_INST("fixed advance pc\n");
+            address_ += program_.read();
+          } break;
+          default: {
+            PRINT_INST("other {}\n", op);
+            auto n = standard_opcode_lengths_[op];
+            for (int i = 0; i < n; ++i) {
+              program_.readULEB128();
+            }
+          } break;
+        }
+      }
+    }
+    PRINT_INST(
+        "{:x}: end {:x}\n",
+        ((char*)program_.loc() - s_.debug_line.data),
+        program_end_ - s_.debug_line.data);
+  }
+
+  uint64_t address_ = 0;
+  bool shadow_ = false;
+  bool parsed_ = false;
+  Entry entry_ = {};
+  std::vector include_directories_;
+  std::vector file_names_;
+  std::vector file_directory_index_;
+  uint8_t segment_selector_size_ = 0;
+  uint8_t minimum_instruction_length_ = 0;
+  uint8_t maximum_operations_per_instruction_ = 0;
+  int8_t line_base_ = 0;
+  uint8_t line_range_ = 0;
+  uint8_t opcode_base_ = 0;
+  bool default_is_stmt_ = false;
+  CheckedLexer program_ = {nullptr};
+  char* program_end_ = nullptr;
+  uint64_t header_length_ = 0;
+  uint64_t length_ = 0;
+  bool is_64bit_ = false;
+  std::vector standard_opcode_lengths_;
+  Sections& s_;
+  uint64_t offset_;
+  uint64_t start_address_ = 0;
+  RangeTable program_index_;
+  std::vector> all_programs_;
+  RangeTable ranges_;
+};
+
+} // namespace torch::unwind
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/mem_file.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/mem_file.h
new file mode 100644
index 0000000000000000000000000000000000000000..b5b6807a7bbcea17adfc78a660b94e4f500a70cc
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/mem_file.h
@@ -0,0 +1,146 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// All rights reserved.
+//
+// This source code is licensed under the BSD-style license found in the
+// LICENSE file in the root directory of this source tree.
+
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch::unwind {
+
+struct Section {
+  char* data = nullptr;
+  size_t size = 0;
+  const char* string(size_t offset) {
+    return lexer(offset).readCString();
+  }
+  CheckedLexer lexer(size_t offset) {
+    return CheckedLexer(data + offset, data, data + size);
+  }
+};
+
+/// Memory maps a file into the address space read-only, and manages the
+/// lifetime of the mapping. Here are a few use cases:
+/// 1. Used in the loader to read in initial image, and to inspect
+// ELF files for dependencies before callling dlopen.
+///
+/// 2. Used in unity to load the elf file.
+struct MemFile {
+  explicit MemFile(const char* filename_)
+      : fd_(open(filename_, O_RDONLY)), name_(filename_) {
+    UNWIND_CHECK(
+        fd_ != -1, "failed to open {}: {}", filename_, strerror(errno));
+    // NOLINTNEXTLINE
+    struct stat s;
+    if (-1 == fstat(fd_, &s)) {
+      close(fd_); // destructors don't run during exceptions
+      UNWIND_CHECK(false, "failed to stat {}: {}", filename_, strerror(errno));
+    }
+    n_bytes_ = s.st_size;
+    UNWIND_CHECK(
+        n_bytes_ > sizeof(Elf64_Ehdr), "empty shared library: {}", filename_);
+    mem_ = (char*)mmap(nullptr, n_bytes_, PROT_READ, MAP_SHARED, fd_, 0);
+    if (MAP_FAILED == mem_) {
+      close(fd_);
+      UNWIND_CHECK(false, "failed to mmap {}: {}", filename_, strerror(errno));
+    }
+    ehdr_ = (Elf64_Ehdr*)mem_;
+#define ELF_CHECK(cond) UNWIND_CHECK(cond, "not an ELF file: {}", filename_)
+    ELF_CHECK(ehdr_->e_ident[EI_MAG0] == ELFMAG0);
+    ELF_CHECK(ehdr_->e_ident[EI_MAG1] == ELFMAG1);
+    ELF_CHECK(ehdr_->e_ident[EI_MAG2] == ELFMAG2);
+    ELF_CHECK(ehdr_->e_ident[EI_MAG3] == ELFMAG3);
+    ELF_CHECK(ehdr_->e_ident[EI_CLASS] == ELFCLASS64);
+    ELF_CHECK(ehdr_->e_ident[EI_VERSION] == EV_CURRENT);
+    ELF_CHECK(ehdr_->e_version == EV_CURRENT);
+    ELF_CHECK(ehdr_->e_machine == EM_X86_64);
+#undef ELF_CHECK
+    UNWIND_CHECK(
+        ehdr_->e_shoff + sizeof(Elf64_Shdr) * ehdr_->e_shnum <= n_bytes_,
+        "invalid section header table {} {} {}",
+        ehdr_->e_shoff + sizeof(Elf64_Shdr) * ehdr_->e_shnum,
+        n_bytes_,
+        ehdr_->e_shnum);
+    shdr_ = (Elf64_Shdr*)(mem_ + ehdr_->e_shoff);
+    UNWIND_CHECK(
+        ehdr_->e_shstrndx < ehdr_->e_shnum, "invalid strtab section offset");
+    auto& strtab_hdr = shdr_[ehdr_->e_shstrndx];
+    strtab_ = getSection(strtab_hdr);
+  }
+
+  MemFile(const MemFile&) = delete;
+  MemFile& operator=(const MemFile&) = delete;
+  [[nodiscard]] const char* data() const {
+    return (const char*)mem_;
+  }
+
+  /// Returns whether or not the file descriptor
+  /// of the underlying file is valid.
+  int valid() {
+    return fcntl(fd_, F_GETFD) != -1 || errno != EBADF;
+  }
+
+  ~MemFile() {
+    if (mem_) {
+      munmap((void*)mem_, n_bytes_);
+    }
+    if (fd_ >= 0) {
+      close(fd_);
+    }
+  }
+
+  /// Returns the size of the underlying file defined by the `MemFile`
+  size_t size() {
+    return n_bytes_;
+  }
+  [[nodiscard]] int fd() const {
+    return fd_;
+  }
+
+  Section getSection(const Elf64_Shdr& shdr) {
+    UNWIND_CHECK(shdr.sh_offset + shdr.sh_size <= n_bytes_, "invalid section");
+    return Section{mem_ + shdr.sh_offset, shdr.sh_size};
+  }
+
+  Section getSection(const char* name, bool optional) {
+    for (int i = 0; i < ehdr_->e_shnum; i++) {
+      if (strcmp(strtab_.string(shdr_[i].sh_name), name) == 0) {
+        return getSection(shdr_[i]);
+      }
+    }
+    UNWIND_CHECK(optional, "{} has no section {}", name_, name);
+    return Section{nullptr, 0};
+  }
+
+  Section strtab() {
+    return strtab_;
+  }
+
+ private:
+  template 
+  T* load(size_t offset) {
+    UNWIND_CHECK(offset < n_bytes_, "out of range");
+    return (T*)(mem_ + offset);
+  }
+  int fd_;
+  char* mem_{nullptr};
+  size_t n_bytes_{0};
+  std::string name_;
+  Elf64_Ehdr* ehdr_;
+  Elf64_Shdr* shdr_;
+  Section strtab_ = {nullptr, 0};
+};
+
+} // namespace torch::unwind
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/range_table.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/range_table.h
new file mode 100644
index 0000000000000000000000000000000000000000..b8c405ddad6a82bb1196a0ef43bbcb3361c54e89
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/range_table.h
@@ -0,0 +1,73 @@
+#pragma once
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch::unwind {
+template 
+struct RangeTable {
+  RangeTable() {
+    // guarentee that lower_bound[-1] is always valid
+    addresses_.push_back(0);
+    payloads_.emplace_back(std::nullopt);
+  }
+  void add(uint64_t address, std::optional payload, bool sorted) {
+    if (addresses_.back() > address) {
+      UNWIND_CHECK(!sorted, "expected addresses to be sorted");
+      sorted_ = false;
+    }
+    addresses_.push_back(address);
+    payloads_.emplace_back(std::move(payload));
+  }
+  std::optional find(uint64_t address) {
+    maybeSort();
+    auto it = std::upper_bound(addresses_.begin(), addresses_.end(), address);
+    return payloads_.at(it - addresses_.begin() - 1);
+  }
+  void dump() {
+    for (size_t i = 0; i < addresses_.size(); i++) {
+      fmt::print("{} {:x}: {}\n", i, addresses_[i], payloads_[i] ? "" : "END");
+    }
+  }
+  size_t size() const {
+    return addresses_.size();
+  }
+  uint64_t back() {
+    maybeSort();
+    return addresses_.back();
+  }
+
+ private:
+  void maybeSort() {
+    if (sorted_) {
+      return;
+    }
+    std::vector indices;
+    indices.reserve(addresses_.size());
+    for (size_t i = 0; i < addresses_.size(); i++) {
+      indices.push_back(i);
+    }
+    std::sort(indices.begin(), indices.end(), [&](uint64_t a, uint64_t b) {
+      return addresses_[a] < addresses_[b] ||
+          (addresses_[a] == addresses_[b] &&
+           bool(payloads_[a]) < bool(payloads_[b]));
+    });
+    std::vector addresses;
+    std::vector> payloads;
+    addresses.reserve(addresses_.size());
+    payloads.reserve(addresses_.size());
+    for (auto i : indices) {
+      addresses.push_back(addresses_[i]);
+      payloads.push_back(payloads_[i]);
+    }
+    addresses_ = std::move(addresses);
+    payloads_ = std::move(payloads);
+    sorted_ = true;
+  }
+  bool sorted_ = true;
+  std::vector addresses_;
+  std::vector> payloads_;
+};
+} // namespace torch::unwind
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/sections.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/sections.h
new file mode 100644
index 0000000000000000000000000000000000000000..d9f16b9164d5c8c12cde5609da815bb03935ce1b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/sections.h
@@ -0,0 +1,120 @@
+#pragma once
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch::unwind {
+
+static std::string demangle(const std::string& mangled_name) {
+  int status = 0;
+  char* realname =
+      abi::__cxa_demangle(mangled_name.c_str(), nullptr, nullptr, &status);
+  if (status == 0) {
+    std::string demangled_name(realname);
+    // NOLINTNEXTLINE
+    free(realname);
+    return demangled_name;
+  } else {
+    return mangled_name;
+  }
+}
+
+struct Sections {
+  Sections() = default;
+  void parse(const char* name) {
+    library_ = std::make_unique(name);
+    strtab = library_->getSection(".strtab", false);
+
+    symtab = library_->getSection(".symtab", true);
+    debug_info = library_->getSection(".debug_info", true);
+    if (debug_info.size > 0) {
+      debug_abbrev = library_->getSection(".debug_abbrev", false);
+      debug_str = library_->getSection(".debug_str", false);
+      debug_line = library_->getSection(".debug_line", false);
+      // dwarf 5
+      debug_line_str = library_->getSection(".debug_line_str", true);
+      debug_rnglists = library_->getSection(".debug_rnglists", true);
+      debug_addr = library_->getSection(".debug_addr", true);
+      // dwarf 4
+      debug_ranges = library_->getSection(".debug_ranges", true);
+    }
+    parseSymtab();
+  }
+
+  Section debug_info;
+  Section debug_abbrev;
+  Section debug_str;
+  Section debug_line;
+  Section debug_line_str;
+  Section debug_rnglists;
+  Section debug_ranges;
+  Section debug_addr;
+  Section symtab;
+  Section strtab;
+
+  const char* readString(CheckedLexer& data, uint64_t encoding, bool is_64bit) {
+    switch (encoding) {
+      case DW_FORM_string: {
+        return data.readCString();
+      }
+      case DW_FORM_strp: {
+        return debug_str.string(readSegmentOffset(data, is_64bit));
+      }
+      case DW_FORM_line_strp: {
+        return debug_line_str.string(readSegmentOffset(data, is_64bit));
+      }
+      default:
+        UNWIND_CHECK(false, "unsupported string encoding {:x}", encoding);
+    }
+  }
+
+  uint64_t readSegmentOffset(CheckedLexer& data, bool is_64bit) {
+    return is_64bit ? data.read() : data.read();
+  }
+
+  std::optional findDebugInfoOffset(uint64_t address) {
+    return debug_info_offsets_.find(address);
+  }
+  size_t compilationUnitCount() {
+    return debug_info_offsets_.size() / 2;
+  }
+  void addDebugInfoRange(
+      uint64_t start,
+      uint64_t end,
+      uint64_t debug_info_offset) {
+    debug_info_offsets_.add(start, debug_info_offset, false);
+    debug_info_offsets_.add(end, std::nullopt, false);
+  }
+  std::optional findSubprogramName(uint64_t address) {
+    if (auto e = symbol_table_.find(address)) {
+      return demangle(strtab.string(*e));
+    }
+    return std::nullopt;
+  }
+
+ private:
+  void parseSymtab() {
+    auto L = symtab.lexer(0);
+    char* end = symtab.data + symtab.size;
+    while (L.loc() < end) {
+      auto symbol = L.read();
+      if (symbol.st_shndx == SHN_UNDEF ||
+          ELF64_ST_TYPE(symbol.st_info) != STT_FUNC) {
+        continue;
+      }
+      symbol_table_.add(symbol.st_value, symbol.st_name, false);
+      symbol_table_.add(symbol.st_value + symbol.st_size, std::nullopt, false);
+    }
+  }
+
+  std::unique_ptr library_;
+  RangeTable debug_info_offsets_;
+  RangeTable symbol_table_;
+};
+
+} // namespace torch::unwind
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/unwind.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/unwind.h
new file mode 100644
index 0000000000000000000000000000000000000000..bf93b88fa63dcbe6ab77576d5cf7e9c03dae6995
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/unwind.h
@@ -0,0 +1,43 @@
+#pragma once
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch::unwind {
+// gather current stack, relatively fast.
+// gets faster once the cache of program counter locations is warm.
+TORCH_API std::vector unwind();
+
+struct Frame {
+  std::string filename;
+  std::string funcname;
+  uint64_t lineno;
+};
+
+enum class Mode { addr2line, fast, dladdr };
+
+// note: symbolize is really slow
+// it will launch an addr2line process that has to parse dwarf
+// information from the libraries that frames point into.
+// Callers should first batch up all the unique void* pointers
+// across a number of unwind states and make a single call to
+// symbolize.
+TORCH_API std::vector symbolize(
+    const std::vector& frames,
+    Mode mode);
+
+// returns path to the library, and the offset of the addr inside the library
+TORCH_API std::optional> libraryFor(
+    void* addr);
+
+struct Stats {
+  size_t hits = 0;
+  size_t misses = 0;
+  size_t unsupported = 0;
+  size_t resets = 0;
+};
+Stats stats();
+
+} // namespace torch::unwind
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/unwind_error.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/unwind_error.h
new file mode 100644
index 0000000000000000000000000000000000000000..648121616486a6ee9aed49be094c0bc8cb7d59b3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/unwind_error.h
@@ -0,0 +1,29 @@
+#pragma once
+#include 
+#include 
+#include 
+
+namespace torch::unwind {
+
+struct UnwindError : public std::runtime_error {
+  using std::runtime_error::runtime_error;
+};
+
+#define UNWIND_CHECK(cond, fmtstring, ...)                          \
+  do {                                                              \
+    if (!(cond)) {                                                  \
+      throw unwind::UnwindError(fmt::format(                        \
+          "{}:{}: " fmtstring, __FILE__, __LINE__, ##__VA_ARGS__)); \
+    }                                                               \
+  } while (0)
+
+// #define LOG_INFO(...) fmt::print(__VA_ARGS__)
+#define LOG_INFO(...)
+
+// #define PRINT_INST(...) LOG_INFO(__VA_ARGS__)
+#define PRINT_INST(...)
+
+// #define PRINT_LINE_TABLE(...) LOG_INFO(__VA_ARGS__)
+#define PRINT_LINE_TABLE(...)
+
+} // namespace torch::unwind
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/unwinder.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/unwinder.h
new file mode 100644
index 0000000000000000000000000000000000000000..d673f47af8db2ac971562fdbfce5bea61aaf698f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/torch/include/torch/csrc/profiler/unwind/unwinder.h
@@ -0,0 +1,81 @@
+#pragma once
+#include 
+#include 
+#include 
+#include 
+
+namespace torch::unwind {
+
+struct UnwindState {
+  int64_t rip, rbp, rsp;
+};
+
+struct Unwinder {
+  Unwinder(Action rsp, Action rip, Action rbp)
+      : kind_(rip.kind == A_UNDEFINED ? END : STANDARD),
+        reg_(rsp.reg),
+        off_(rsp.data),
+        rip_off_(rip.data),
+        rbp_off_(
+            rbp.kind == A_UNDEFINED ? std::numeric_limits::max()
+                                    : rbp.data),
+        deref_(rsp.kind == A_REG_PLUS_DATA_DEREF) {
+    check(rsp.reg == D_RSP || rsp.reg == D_RBP);
+    check(rip.kind == A_UNDEFINED || rip.kind == A_LOAD_CFA_OFFSET);
+    if (rsp.kind == A_REG_PLUS_DATA) {
+      check(rbp.kind == A_LOAD_CFA_OFFSET || rbp.kind == A_UNDEFINED);
+    } else if (rsp.kind == A_REG_PLUS_DATA_DEREF) {
+      if (rbp.kind == A_REG_PLUS_DATA_DEREF) {
+        check(rbp.reg == rsp.reg);
+        rbp_off_ -= rsp.data;
+      } else {
+        check(rbp.kind == A_UNDEFINED);
+      }
+    } else {
+      check(false);
+    }
+  }
+  void check(bool cond) {
+    if (!cond) {
+      throw UnwindError("Unwinding actions do not follow supported patterns");
+    }
+  }
+  bool terminator() const {
+    return kind_ != STANDARD;
+  }
+  bool isUnknown() const {
+    return kind_ == UNKNOWN;
+  }
+  // unwinder representing some pattern unsupported in
+  // current implementation
+  static Unwinder unknown() {
+    return Unwinder();
+  }
+  UnwindState run(const UnwindState& cur) const {
+    UnwindState r = cur;
+    r.rsp = (reg_ == D_RSP ? cur.rsp : cur.rbp) + off_;
+    r.rbp = rbp_off_ == std::numeric_limits::max()
+        ? cur.rbp
+        // NOLINTNEXTLINE(performance-no-int-to-ptr)
+        : *(int64_t*)(r.rsp + rbp_off_);
+    if (deref_) {
+      // NOLINTNEXTLINE(performance-no-int-to-ptr)
+      r.rsp = *(int64_t*)r.rsp;
+    }
+    // NOLINTNEXTLINE(performance-no-int-to-ptr)
+    r.rip = *(int64_t*)(r.rsp + rip_off_);
+
+    return r;
+  }
+
+ private:
+  Unwinder() : kind_(UNKNOWN), reg_(0), off_(0), rip_off_(0), rbp_off_(0) {}
+  enum Kind { STANDARD, END, UNKNOWN } kind_;
+  uint32_t reg_;
+  int64_t off_;
+  int64_t rip_off_;
+  int64_t rbp_off_;
+  bool deref_{false};
+};
+
+} // namespace torch::unwind